diff --git a/.gitattributes b/.gitattributes index 04b58f3f46cfffc019575c943d0b6e828f9951b3..b30c558773cf51e9d3c152714fc944f089bab0ba 100644 --- a/.gitattributes +++ b/.gitattributes @@ -500,3 +500,48 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_lambdify.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_wester.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/tests/__pycache__/test_python.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/__pycache__/_meta_registrations.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_docs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/__pycache__/_torch_docs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/__pycache__/overrides.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/convert_frame.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/eval_frame.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/guards.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/output_graph.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/base.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builder.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builtin.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/functions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/higher_order_ops.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lists.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/misc.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/user_defined.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/codecache.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpp_builder.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/graph.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ir.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/lowering.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/scheduler.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/pallas.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.12/site-packages/thop/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b29be3b5380965d41b9a482933fa1e12ac119921 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/profile.py b/.venv/lib/python3.12/site-packages/thop/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..1d622be05a5a51bd7d869ef000362aae6963a269 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/profile.py @@ -0,0 +1,441 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import inspect + +from thop.rnn_hooks import ( + count_gru, + count_gru_cell, + count_lstm, + count_lstm_cell, + count_rnn, + count_rnn_cell, + torch, +) +from thop.vision.basic_hooks import ( + count_adap_avgpool, + count_avgpool, + count_bilinear, + count_convNd, + count_convtNd, + count_embedding, + count_linear, + count_multihead_attention, + count_normalization, + count_prelu, + count_softmax, + count_upsample, + logging, + nn, + zero_ops, +) + +from .utils import prRed +from .vision.calc_func import calculate_parameters + +default_dtype = torch.float64 + +# torch>=2.0 +_HOOK_TAKES_KWARGS = "with_kwargs" in inspect.signature(nn.Module.register_forward_hook).parameters + +register_hooks = { + # the padding and dropout families through the private base each shares, as the norm families below + # need for the same reason: naming the two concrete classes left their 10 siblings rule-less, so + # report_missing warned about layers that have nothing to count and taught the reader to ignore it + nn.modules.padding._ConstantPadNd: zero_ops, # padding does not involve any multiplication + nn.modules.padding._ReflectionPadNd: zero_ops, + nn.modules.padding._ReplicationPadNd: zero_ops, + nn.modules.dropout._DropoutNd: zero_ops, + nn.Conv1d: count_convNd, + nn.Conv2d: count_convNd, + nn.Conv3d: count_convNd, + nn.ConvTranspose1d: count_convtNd, + nn.ConvTranspose2d: count_convtNd, + nn.ConvTranspose3d: count_convtNd, + # the batch- and instance-norm families through the base they share, which count_normalization is + # already annotated for. A lazy norm needs the base: LazyBatchNorm2d derives from _BatchNorm, not + # from BatchNorm2d, so its concrete counterpart is a sibling and never appears in its MRO. + nn.modules.batchnorm._NormBase: count_normalization, + nn.LayerNorm: count_normalization, + nn.GroupNorm: count_normalization, + nn.PReLU: count_prelu, + # The softmax family shares no base, so each member is registered explicitly. + nn.Softmax: count_softmax, + nn.LogSoftmax: count_softmax, + nn.Softmin: count_softmax, + nn.Softmax2d: count_softmax, + nn.ReLU: zero_ops, + nn.ReLU6: zero_ops, + nn.LeakyReLU: zero_ops, + nn.MaxPool1d: zero_ops, + nn.MaxPool2d: zero_ops, + nn.MaxPool3d: zero_ops, + nn.AdaptiveMaxPool1d: zero_ops, + nn.AdaptiveMaxPool2d: zero_ops, + nn.AdaptiveMaxPool3d: zero_ops, + nn.FractionalMaxPool2d: zero_ops, # a max pool that picks its windows randomly still only selects + nn.FractionalMaxPool3d: zero_ops, + nn.modules.pooling._MaxUnpoolNd: zero_ops, # scattering into a larger zero tensor adds nothing + nn.AvgPool1d: count_avgpool, + nn.AvgPool2d: count_avgpool, + nn.AvgPool3d: count_avgpool, + nn.AdaptiveAvgPool1d: count_adap_avgpool, + nn.AdaptiveAvgPool2d: count_adap_avgpool, + nn.AdaptiveAvgPool3d: count_adap_avgpool, + nn.Linear: count_linear, + nn.Bilinear: count_bilinear, + nn.Upsample: count_upsample, + nn.UpsamplingBilinear2d: count_upsample, + nn.UpsamplingNearest2d: count_upsample, + nn.RNNCell: count_rnn_cell, + nn.GRUCell: count_gru_cell, + nn.LSTMCell: count_lstm_cell, + nn.RNN: count_rnn, + nn.GRU: count_gru, + nn.LSTM: count_lstm, + # containers hold children and compute nothing themselves; they share no base but nn.Module. + nn.Sequential: zero_ops, + nn.ModuleList: zero_ops, + nn.ModuleDict: zero_ops, + nn.ParameterList: zero_ops, + nn.ParameterDict: zero_ops, + # layers that only move elements around: a view, a re-index or a permutation reads and writes each + # element once and multiplies nothing. The elementwise activations that also reach no rule are left + # warned about on purpose, because registering one asserts it is free and SiLU, Mish, GELU, GLU and + # Hardswish each multiply per element, so they want formulas rather than a blanket entry. nn.Fold is + # out because it sums OVERLAPPING blocks, and an addition per input over a window is the work + # count_adap_avgpool charges rather than something a view does. + nn.Identity: zero_ops, + nn.Flatten: zero_ops, + nn.Unflatten: zero_ops, + nn.Unfold: zero_ops, + nn.PixelShuffle: zero_ops, + nn.PixelUnshuffle: zero_ops, + nn.ChannelShuffle: zero_ops, + # a gather, so it belongs with the block above, but max_norm keeps it out of a blanket zero: that rescale is + # real work and count_embedding warns rather than assert it away, the way count_upsample does for a mode it has + # no cost for. nn.EmbeddingBag stays unregistered, since it really does reduce each bag and how many adds that + # takes is not a function of shape either: padding_idx entries drop out and repeated offsets make empty bags. + nn.Embedding: count_embedding, +} + +if _HOOK_TAKES_KWARGS: + register_hooks[nn.MultiheadAttention] = count_multihead_attention + +if hasattr(nn, "RMSNorm"): # torch>=2.4, and its elementwise_affine flag is one count_normalization already reads + register_hooks[nn.RMSNorm] = count_normalization + +if hasattr(nn.modules.padding, "_CircularPadNd"): # torch>=2.1, which is where the CircularPad classes start + register_hooks[nn.modules.padding._CircularPadNd] = zero_ops + + +def _resolve_rule(m_type, custom_ops, types_collection, verbose, report_missing): + """Return the counting rule for a module type, or None when no ancestor of it carries one. + + The whole MRO is walked, most derived first, so a subclass of a supported type is counted by that type's rule + instead of being skipped, and a lazy module resolves through the class it derives from. custom_ops is consulted + ahead of the built-ins at every level, so a caller's own rule still wins. + """ + first_seen = m_type not in types_collection + for t in m_type.__mro__: + if t in custom_ops: # if defined in both op maps, custom_ops overwrites + fn = custom_ops[t] + if first_seen and verbose: + print(f"[INFO] Customize rule {getattr(fn, '__qualname__', fn)}() {m_type}.") + return fn + if t in register_hooks: + fn = register_hooks[t] + if first_seen and verbose: + print(f"[INFO] Register {getattr(fn, '__qualname__', fn)}() for {m_type}.") + return fn + if first_seen and report_missing: + prRed(f"[WARN] Cannot find rule for {m_type}. Treat it as zero Macs.") + return None + + +def _register_counter(m, fn, keep_result): + """Register a counting hook that receives positional and keyword arguments.""" + if _HOOK_TAKES_KWARGS: + + def counter(m, args, kwargs, y, fn=fn): + """Apply the counting rule to the arguments the module was called with.""" + result = fn(m, _positional(m, args, kwargs) if kwargs else args, y) + return result if keep_result else None + + return m.register_forward_hook(counter, with_kwargs=True) + + def counter(m, args, y, fn=fn): + """Apply the counting rule; this torch delivers no keyword arguments for it to be given.""" + result = fn(m, args, y) + return result if keep_result else None + + return m.register_forward_hook(counter) + + +def _positional(m, args, kwargs): + """Return supplied arguments in the order m.forward declares them.""" + try: + bound = inspect.signature(m.forward).bind(*args, **kwargs) + except (TypeError, ValueError): + return () + values = [] + for name, value in bound.arguments.items(): + kind = bound.signature.parameters[name].kind + if kind == inspect.Parameter.VAR_POSITIONAL: + values.extend(value) + elif kind != inspect.Parameter.VAR_KEYWORD: + values.append(value) + return tuple(values) + + +def _parents_first(roots): + """List reachable modules with every parent before its children.""" + order, seen = [], set() + + def visit(m): + seen.add(m) + for c in m.children(): + if c not in seen: + visit(c) + order.append(m) + + for root in roots: + if root not in seen: + visit(root) + order.reverse() + return order + + +def _displace_total_ops(m): + """Temporarily remove a caller-owned `total_ops` buffer or attribute; reject a name thop cannot borrow.""" + kind = None + if any(hasattr(vars(c).get("total_ops"), "__set__") for c in type(m).__mro__): + kind = "data descriptor" # no per-instance value to displace, and the hook's writes never reach the total + elif "total_ops" in m._parameters: + kind = "parameter" # displacing it would come back as a smaller parameter count + elif "total_ops" in m._modules: + kind = "child module" # displacing it would come back as a dropped subtree + if kind: + raise TypeError(f"{m!s} owns total_ops as a {kind}; thop needs that name to profile it.") + displaced = [(store, store["total_ops"]) for store in (m._buffers, m.__dict__) if "total_ops" in store] + if displaced: + logging.warning(f"{m!s} already has a .total_ops; it is shadowed while profiling and restored after.") + for store, _ in displaced: + del store["total_ops"] + return displaced + + +def _restore_modes(prev_training): + """Restore recorded modes without changing modules attached during forward.""" + order = _parents_first(prev_training) + modes = {m: prev_training.get(m, m.training) for m in order} # read before the first train() call moves any + for m, was_training in modes.items(): + if m.training != was_training: + m.train(was_training) + for m, was_training in modes.items(): + m.training = was_training + + +def profile_origin(model, inputs, custom_ops=None, verbose=True, report_missing=False): + """Profile a model with the legacy per-leaf-module traversal, returning total operations and parameters.""" + handler_collection = {} + displaced_collection = {} + types_collection = set() + if custom_ops is None: + custom_ops = {} + if report_missing: + verbose = True + + def add_hooks(m): + m_type = type(m) + has_own_rule = any(t in custom_ops or t in register_hooks for t in m_type.__mro__) + if (list(m.children()) and not has_own_rule) or m in handler_collection: + return + + fn = _resolve_rule(m_type, custom_ops, types_collection, verbose, report_missing) + + displaced = _displace_total_ops(m) + if displaced: + displaced_collection[m] = displaced + # register_buffer discards this flag; restore it without requiring the newer persistent= argument. + non_persistent = "total_ops" in m._non_persistent_buffers_set + m.register_buffer("total_ops", torch.zeros(1, dtype=default_dtype)) + if non_persistent: + m._non_persistent_buffers_set.add("total_ops") + handler_collection[m] = None + if fn is not None and fn is not zero_ops: + handler_collection[m] = _register_counter(m, fn, keep_result=True) # as profile_origin always has + types_collection.add(m_type) + + prev_training = {m: m.training for m in model.modules()} + + try: + model.eval() + model.apply(add_hooks) + + with torch.no_grad(): + model(*inputs) + + total_ops = 0 + for m in handler_collection: + total_ops += m.total_ops + + total_ops = total_ops.item() + total_params = float(calculate_parameters(model.parameters())) + finally: # no failure, at any stage, may leave behind the hooks or the buffers this call created + for handler in filter(None, handler_collection.values()): + handler.remove() + for m in handler_collection: + m._buffers.pop("total_ops", None) + for m, displaced in displaced_collection.items(): + for store, value in displaced: + store["total_ops"] = value + _restore_modes(prev_training) # last: it calls train(), which is the caller's code and may raise + + return total_ops, total_params + + +def profile( + model: nn.Module, + inputs, + custom_ops=None, + verbose=True, + ret_layer_info=False, + report_missing=False, + stride=None, +): + """Profiles a PyTorch model, optionally estimating target-image MACs from smaller stride-aligned inputs.""" + handler_collection = {} + displaced_collection = {} + types_collection = set() + if custom_ops is None: + custom_ops = {} + if report_missing: + # overwrite `verbose` option when enable report_missing + verbose = True + + def add_hooks(m: nn.Module): + """Registers a hook on a neural network module to track its total operations.""" + if m in handler_collection: # model.apply() revisits modules shared by several parents, e.g. a common act + return + + m_type = type(m) + fn = _resolve_rule(m_type, custom_ops, types_collection, verbose, report_missing) + + displaced = _displace_total_ops(m) + if displaced: + displaced_collection[m] = displaced + # a plain int attribute, not a float64 buffer: buffer reads go through nn.Module.__getattr__ and every + # hook would allocate a tensor per call, which dominates profiling cost on module-heavy models. + # Written straight into __dict__ (mirroring the teardown below) to skip nn.Module.__setattr__. + m.__dict__["total_ops"] = 0 + + handler_collection[m] = None + if fn is not None and fn is not zero_ops: + handler_collection[m] = _register_counter(m, fn, keep_result=False) # never the module output + types_collection.add(m_type) + + counted = set() + + def dfs_count(module: nn.Module, prefix="\t") -> (float, dict): + """Build layer details from the module tree left after forward.""" + total_ops = float(module.__dict__.get("total_ops", 0)) if module in handler_collection else 0.0 + ret_dict = {} + for n, m in module.named_children(): + # every child is walked, whether or not it carries a rule of its own: a rule accounts for its + # module's own arithmetic, not for its subtree's, so the two are added rather than one replacing + # the other. This is what the root of the traversal has always done with its own total_ops above + m_ops, next_dict = dfs_count(m, prefix=prefix + "\t") + if ret_layer_info: # the per-layer tree is the caller's opt-in, so it is not built when discarded + ret_dict[n] = (m_ops, float(calculate_parameters(m.parameters())), next_dict) + if m in counted: # a module reached through several parents already accumulated all of its calls + continue + counted.add(m) + total_ops += m_ops + # print(prefix, module._get_name(), total_ops) + return total_ops, ret_dict + + prev_training = {m: m.training for m in model.modules()} # per module: model.eval() below recurses + + try: + model.eval() + model.apply(add_hooks) + + def run(input_values): + """Profile one set of inputs while reusing the registered hooks.""" + counted.clear() + for m in handler_collection: + m.__dict__["total_ops"] = 0 + with torch.no_grad(): + model(*input_values) + # Count the executed hook record; build the surviving tree only when requested. + total = sum(float(m.__dict__.get("total_ops", 0)) for m in handler_collection) + return total, dfs_count(model)[1] if ret_layer_info else {} + + if stride is None or ret_layer_info: + total_ops, ret_dict = run(inputs) + else: + if len(inputs) != 1 or not isinstance(inputs[0], torch.Tensor) or inputs[0].ndim != 4: + raise ValueError("stride requires inputs to contain one BCHW image tensor") + stride = (stride, stride) if isinstance(stride, int) else tuple(stride) + if len(stride) != 2 or min(stride) < 1: + raise ValueError("stride must be a positive integer or a pair of positive integers") + + image = inputs[0] + target_height, target_width = image.shape[-2:] + fixed_ops = ( + nn.Linear, + nn.AdaptiveAvgPool1d, + nn.AdaptiveAvgPool2d, + nn.AdaptiveAvgPool3d, + nn.RNNBase, + nn.RNNCell, + nn.GRUCell, + nn.LSTMCell, + ) + required_samples = 2 if any(isinstance(m, fixed_ops) for m in model.modules()) else 1 + samples = [] + proxy_area = stride[0] * stride[1] + if ( + # two small samples can only fit a cost that is affine in image area. Attention is quadratic in it, + # and a caller's own rule may be anything at all, so a model carrying either is measured directly. + not any( + isinstance(m, nn.MultiheadAttention) or any(t in custom_ops for t in type(m).__mro__) + for m in model.modules() + ) + and target_height % stride[0] == target_width % stride[1] == 0 + and proxy_area < target_height * target_width + ): + try: + for width in (stride[1], stride[1] * 2)[:required_samples]: + ops, _ = run((image.new_empty((*image.shape[:-2], stride[0], width)),)) + samples.append((stride[0] * width, ops)) + except Exception: + samples.clear() + + if len(samples) == 2: + (area1, ops1), (area2, ops2) = samples + slope = (ops2 - ops1) / (area2 - area1) + total_ops = slope * target_height * target_width + ops1 - slope * area1 + ret_dict = {} + elif len(samples) == 1 and required_samples == 1: + area, ops = samples[0] + total_ops = ops * target_height * target_width / area + ret_dict = {} + else: + total_ops, ret_dict = run(inputs) + # Parameters belong to the module tree, not to the traced call. parameters() deduplicates shared tensors + # and includes unsupported or unexecuted modules. + total_params = float(calculate_parameters(model.parameters())) + finally: # no failure, at any stage, may leave behind hooks or temporary attributes + for handler in filter(None, handler_collection.values()): + handler.remove() + for m in handler_collection: + m.__dict__.pop("total_ops", None) + for m, displaced in displaced_collection.items(): + for store, value in displaced: + store["total_ops"] = value + _restore_modes(prev_training) # last: it calls train(), which is the caller's code and may raise + + if ret_layer_info: + return total_ops, total_params, ret_dict + return total_ops, total_params diff --git a/.venv/lib/python3.12/site-packages/thop/rnn_hooks.py b/.venv/lib/python3.12/site-packages/thop/rnn_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..9e3cb67c859aa159293a8bb1456f5b7c9e3b40e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/rnn_hooks.py @@ -0,0 +1,179 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import torch +from torch import nn +from torch.nn.utils.rnn import PackedSequence + + +def _cell_evaluations(x): + """Return how many cell evaluations a recurrent layer's input asks for.""" + if isinstance(x, PackedSequence): + return int(x.batch_sizes.sum()) # the padded rectangle is the work packing exists to avoid + return x.size(0) if x.dim() == 2 else x.size(0) * x.size(1) # unbatched (L, H_in) carries no batch axis + + +def _count_rnn_cell(input_size, hidden_size, bias=True): + """Calculate the total operations for an RNN cell given input size, hidden size, and optional bias.""" + total_ops = hidden_size * (input_size + hidden_size) + hidden_size + if bias: + total_ops += hidden_size * 2 + + return total_ops + + +def count_rnn_cell(m: nn.RNNCell, x: torch.Tensor, y: torch.Tensor): + """Counts the total RNN cell operations based on input tensor, hidden size, bias, and batch size.""" + total_ops = _count_rnn_cell(m.input_size, m.hidden_size, m.bias) + + # a cell takes one vector per batch entry, so a 1-dimensional input is a single unbatched sample + total_ops *= x[0].size(0) if x[0].dim() == 2 else 1 + + m.total_ops += int(total_ops) + + +def _count_gru_cell(input_size, hidden_size, bias=True): + """Counts the total operations for a GRU cell based on input size, hidden size, and bias configuration.""" + total_ops = 0 + # r = \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\ + # z = \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\ + state_ops = (hidden_size + input_size) * hidden_size + hidden_size + if bias: + state_ops += hidden_size * 2 + total_ops += state_ops * 2 + + # n = \tanh(W_{in} x + b_{in} + r * (W_{hn} h + b_{hn})) \\ + total_ops += (hidden_size + input_size) * hidden_size + hidden_size + if bias: + total_ops += hidden_size * 2 + # r hadamard : r * (~) + total_ops += hidden_size + + # h' = (1 - z) * n + z * h + # hadamard hadamard add + total_ops += hidden_size * 3 + + return total_ops + + +def count_gru_cell(m: nn.GRUCell, x: torch.Tensor, y: torch.Tensor): + """Calculates and updates the total operations for a GRU cell in a mini-batch during inference.""" + total_ops = _count_gru_cell(m.input_size, m.hidden_size, m.bias) + + # a cell takes one vector per batch entry, so a 1-dimensional input is a single unbatched sample + total_ops *= x[0].size(0) if x[0].dim() == 2 else 1 + + m.total_ops += int(total_ops) + + +def _count_lstm_cell(input_size, hidden_size, bias=True, proj_size=0): + """Counts LSTM cell operations during inference based on input size, hidden size, and bias configuration.""" + total_ops = 0 + real_hidden_size = proj_size or hidden_size # what the recurrent matmuls read, torch's own name for it + + # i = \sigma(W_{ii} x + b_{ii} + W_{hi} h + b_{hi}) \\ + # f = \sigma(W_{if} x + b_{if} + W_{hf} h + b_{hf}) \\ + # o = \sigma(W_{io} x + b_{io} + W_{ho} h + b_{ho}) \\ + # g = \tanh(W_{ig} x + b_{ig} + W_{hg} h + b_{hg}) \\ + state_ops = (input_size + real_hidden_size) * hidden_size + hidden_size + if bias: + state_ops += hidden_size * 2 + total_ops += state_ops * 4 + + # c' = f * c + i * g \\ + # hadamard hadamard add + total_ops += hidden_size * 3 + + # h' = W_{hr} (o * \tanh(c')) \\ + total_ops += hidden_size + hidden_size * proj_size + + return total_ops + + +def count_lstm_cell(m: nn.LSTMCell, x: torch.Tensor, y: torch.Tensor): + """Counts and updates the total operations for an LSTM cell in a mini-batch during inference.""" + total_ops = _count_lstm_cell(m.input_size, m.hidden_size, m.bias) + + # a cell takes one vector per batch entry, so a 1-dimensional input is a single unbatched sample + total_ops *= x[0].size(0) if x[0].dim() == 2 else 1 + + m.total_ops += int(total_ops) + + +def count_rnn(m: nn.RNN, x, y): + """Calculate and update the total number of operations for each RNN cell in a given batch.""" + bias = m.bias + input_size = m.input_size + hidden_size = m.hidden_size + num_layers = m.num_layers + + evaluations = _cell_evaluations(x[0]) + + total_ops = 0 + if m.bidirectional: + total_ops += _count_rnn_cell(input_size, hidden_size, bias) * 2 + else: + total_ops += _count_rnn_cell(input_size, hidden_size, bias) + + for _ in range(num_layers - 1): + total_ops += ( + _count_rnn_cell(hidden_size * 2, hidden_size, bias) * 2 + if m.bidirectional + else _count_rnn_cell(hidden_size, hidden_size, bias) + ) + total_ops *= evaluations + + m.total_ops += int(total_ops) + + +def count_gru(m: nn.GRU, x, y): + """Calculates total operations for a GRU layer, updating the model's operation count based on batch size.""" + bias = m.bias + input_size = m.input_size + hidden_size = m.hidden_size + num_layers = m.num_layers + + evaluations = _cell_evaluations(x[0]) + + total_ops = 0 + if m.bidirectional: + total_ops += _count_gru_cell(input_size, hidden_size, bias) * 2 + else: + total_ops += _count_gru_cell(input_size, hidden_size, bias) + + for _ in range(num_layers - 1): + total_ops += ( + _count_gru_cell(hidden_size * 2, hidden_size, bias) * 2 + if m.bidirectional + else _count_gru_cell(hidden_size, hidden_size, bias) + ) + total_ops *= evaluations + + m.total_ops += int(total_ops) + + +def count_lstm(m: nn.LSTM, x, y): + """Calculate total operations for LSTM layers, including bidirectional, updating model's total operations.""" + bias = m.bias + input_size = m.input_size + hidden_size = m.hidden_size + num_layers = m.num_layers + proj_size = m.proj_size + stacked_size = proj_size or hidden_size # the width a projected layer hands the next one + + evaluations = _cell_evaluations(x[0]) + + total_ops = 0 + if m.bidirectional: + total_ops += _count_lstm_cell(input_size, hidden_size, bias, proj_size) * 2 + else: + total_ops += _count_lstm_cell(input_size, hidden_size, bias, proj_size) + + for _ in range(num_layers - 1): + total_ops += ( + _count_lstm_cell(stacked_size * 2, hidden_size, bias, proj_size) * 2 + if m.bidirectional + else _count_lstm_cell(stacked_size, hidden_size, bias, proj_size) + ) + total_ops *= evaluations + + m.total_ops += int(total_ops) diff --git a/.venv/lib/python3.12/site-packages/thop/utils.py b/.venv/lib/python3.12/site-packages/thop/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..76765359664ea976ad1479c38921816eaa1bf7f3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/utils.py @@ -0,0 +1,48 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from collections.abc import Iterable + +COLOR_RED = "91m" +COLOR_GREEN = "92m" +COLOR_YELLOW = "93m" + + +def colorful_print(fn_print, color=COLOR_RED): + """A decorator to print text in the specified terminal color by wrapping the given print function.""" + + def actual_call(*args, **kwargs): + print(f"\033[{color}", end="") + fn_print(*args, **kwargs) + print("\033[00m", end="") + + return actual_call + + +prRed = colorful_print(print, color=COLOR_RED) +prGreen = colorful_print(print, color=COLOR_GREEN) +prYellow = colorful_print(print, color=COLOR_YELLOW) + + +def clever_format(nums, format="%.2f"): + """Formats numbers into human-readable strings with units (K for thousand, M for million, etc.).""" + if not isinstance(nums, Iterable): + nums = [nums] + clever_nums = [] + + for num in nums: + for unit, scale in (("T", 1e12), ("G", 1e9), ("M", 1e6), ("K", 1e3)): + # abs() and >=, not the value against >: a negative satisfied no comparison and came out unscaled, + # and an exact power of 1000 belongs to the unit it is one of rather than to the one below it + if abs(num) >= scale: + clever_nums.append(format % (num / scale) + unit) + break + else: + clever_nums.append(format % num + "B") + + return clever_nums[0] if len(clever_nums) == 1 else (*clever_nums,) + + +if __name__ == "__main__": + prRed("hello", "world") + prGreen("hello", "world") + prYellow("hello", "world") diff --git a/.venv/lib/python3.12/site-packages/thop/vision/__init__.py b/.venv/lib/python3.12/site-packages/thop/vision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77a19dcf0f8093de419453747db2e7e719f96349 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/vision/__init__.py @@ -0,0 +1 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license diff --git a/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc20e444d727e37526110e5b512909d524571597 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/basic_hooks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/basic_hooks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..395ef19efb21eb60c6f8e2bb0b94a7a1f585eee4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/basic_hooks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/calc_func.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/calc_func.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a2a6af241a34d700c3f0bec4fcad2d093376b7c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/calc_func.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/vision/basic_hooks.py b/.venv/lib/python3.12/site-packages/thop/vision/basic_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..0d8b0f2943b81e7cf242e6377531bd2735561315 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/vision/basic_hooks.py @@ -0,0 +1,205 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import logging + +import torch +from torch import nn +from torch.nn.modules.conv import _ConvNd + +from thop.vision.calc_func import ( + calculate_conv2d_flops, + calculate_linear, + calculate_norm, + calculate_softmax, + calculate_zero_ops, + l_prod, +) + +multiply_adds = 1 + + +def zero_ops(m, x, y): + """Incrementally add zero operations to the model's total operations count.""" + m.total_ops += calculate_zero_ops() + + +def count_embedding(m, x, y): + """Charge nothing for an embedding gather, warning when max_norm makes that incomplete.""" + if m.max_norm is not None: # it renormalizes only the rows the indices push over the limit, so data decides + logging.getLogger(__name__).warning("max_norm renormalization is not counted") + + +def count_convNd(m: _ConvNd, x, y: torch.Tensor): + """Calculate and add the number of convolutional operations (FLOPs) for a ConvNd layer to the model's total ops.""" + x = x[0] + + m.total_ops += calculate_conv2d_flops( + input_size=list(x.shape), + output_size=list(y.shape), + kernel_size=list(m.weight.shape), + groups=m.groups, + bias=m.bias, + transpose=False, + ) + # N x Cout x H x W x (Cin x Kw x Kh + bias) + # m.total_ops += calculate_conv( + # bias_ops, + # torch.zeros(m.weight.size()[2:]).numel(), + # y.nelement(), + # m.in_channels, + # m.groups, + # ) + + +def count_convtNd(m: _ConvNd, x, y: torch.Tensor): + """Calculate and add the number of convolutional operations (FLOPs) for a ConvNd layer to the model's total ops.""" + x = x[0] + + m.total_ops += calculate_conv2d_flops( + input_size=list(x.shape), + output_size=list(y.shape), + kernel_size=list(m.weight.shape), + groups=m.groups, + bias=m.bias, + transpose=True, + ) + + +def count_normalization(m: nn.modules.batchnorm._BatchNorm, x, y): + """Calculate and add the FLOPs for a batch normalization layer, including elementwise and affine operations.""" + # https://github.com/Lyken17/pytorch-OpCounter/issues/124 + # y = (x - mean) / sqrt(eps + var) * weight + bias + x = x[0] + # bn is by default fused in inference + flops = calculate_norm(x.numel()) + if getattr(m, "affine", False) or getattr(m, "elementwise_affine", False): + flops *= 2 + m.total_ops += flops + + +# def count_layer_norm(m, x, y): +# x = x[0] +# m.total_ops += calculate_norm(x.numel()) + + +# def count_instance_norm(m, x, y): +# x = x[0] +# m.total_ops += calculate_norm(x.numel()) + + +def count_prelu(m, x, y): + """Calculate and update the total operation counts for a PReLU layer using input element number.""" + x = x[0] + + if not m.training: + m.total_ops += x.numel() + + +def count_softmax(m, x, y): + """Calculate and update the total operation counts for a Softmax layer in a PyTorch model.""" + x = x[0] + # Softmax2d always normalizes channels, with or without a batch dimension. + dim = -3 if isinstance(m, nn.Softmax2d) else m.dim + if dim is None: + # Match torch's deprecated implicit dimension. + dim = 0 if x.dim() in {0, 1, 3} else 1 + # a scalar normalizes over itself, which no shape entry can say: torch returns 1.0 for it, so the cost is + # the one exponential and the one division that produce that, and indexing the empty shape only raises + nfeatures = x.size()[dim] if x.dim() else 1 + batch_size = x.numel() // nfeatures if nfeatures else 0 + + m.total_ops += calculate_softmax(batch_size, nfeatures) + if isinstance(m, nn.Softmin): + m.total_ops += x.numel() + elif isinstance(m, nn.LogSoftmax): + m.total_ops += batch_size + + +def count_avgpool(m, x, y): + """Calculate and update the total operation count for an AvgPool layer.""" + kernel = m.kernel_size + if isinstance(kernel, int): # only AvgPool2d and AvgPool3d keep it as passed, AvgPool1d normalizes to a tuple + kernel = (kernel,) * (3 if isinstance(m, nn.AvgPool3d) else 2) + dims = len(kernel) + stride = (m.stride,) * dims if isinstance(m.stride, int) else m.stride + padding = (m.padding,) * dims if isinstance(m.padding, int) else m.padding + windows = 1 + for size, output, k, s, p in zip(x[0].shape[-dims:], y.shape[-dims:], kernel, stride, padding): + lower, upper = (-p, size + p) if m.count_include_pad else (0, size) + windows *= sum(max(min(i * s - p + k, upper) - max(i * s - p, lower), 0) for i in range(output)) + m.total_ops += l_prod(x[0].shape[:-dims]) * windows + y.numel() # one add per input, one divide per output + + +def count_adap_avgpool(m, x, y): + """Calculate and update the total operation counts for an AdaptiveAvgPool layer from the windows it pools.""" + # the windows nn.AdaptiveAvgPool* actually slices, per dimension: output j spans + # [j * I // O, ceil((j + 1) * I / O)), so their sizes are integral and unequal whenever O does not divide I. + # The input-over-output ratio this replaced was a float, which made total_ops fractional, and it was also + # smaller than the window it stood for. + # Every axis is walked, not only the pooled ones: an axis the layer leaves alone has one input per output, so + # it contributes its own length and the batch and channel counts fall out of the same product. That is what + # the pooled-axes slice had to multiply back by hand, and it needs no batch axis to be there to slice off. + m.total_ops += ( + l_prod( + o if i == o else sum(-(-(j + 1) * i // o) - j * i // o for j in range(o)) + for i, o in zip(x[0].shape, y.shape) + ) + + y.numel() + ) # one add per pooled input, one divide per output + + +# TODO: verify the accuracy +def count_upsample(m, x, y): + """Update total operations counter for upsampling layers based on the mode used.""" + ops_per_element = { + "nearest": 0, + "nearest-exact": 0, + "linear": 5, + "bilinear": 11, + "bicubic": 259, + "trilinear": 31, + }.get(m.mode) + if ops_per_element is None: # one lookup owns both the cost and whether the mode has one at all + logging.getLogger(__name__).warning(f"mode {m.mode} is not implemented yet, take it a zero op") + ops_per_element = 0 + m.total_ops += ops_per_element * y.nelement() + + +# nn.Linear +def count_linear(m, x, y): + """Counts total operations for nn.Linear layers using input and output element dimensions.""" + total_mul = m.in_features + # total_add = m.in_features - 1 + # total_add += 1 if m.bias is not None else 0 + num_elements = y.numel() + + m.total_ops += calculate_linear(total_mul, num_elements) + + +def count_bilinear(m, x, y): + """Count both contractions of each bilinear output.""" + m.total_ops += calculate_linear((m.in1_features + 1) * m.in2_features, y.numel()) + + +def count_multihead_attention(m: nn.MultiheadAttention, x, y): + """Count projections, attention matrix products, and softmax. + + MultiheadAttention calls its projection weights functionally, so none of this work reaches a child-module hook. + Returned weights reveal appended key positions; calls that suppress them fall back to the key input. + """ + out, weights = y if isinstance(y, tuple) else (y, None) + batch_first = getattr(m, "batch_first", False) # added in torch 1.9; before it the layout is always (L, N, E) + tgt_len = out.shape[-2] if batch_first or out.dim() == 2 else out.shape[0] + batch_size = 1 if out.dim() == 2 else out.shape[0 if batch_first else 1] + appended = (m.bias_k is not None) + m.add_zero_attn # each adds one key position, after the projections have run + if weights is not None: + attended = weights.shape[-1] + else: + key = x[1] + attended = (key.shape[-2] if batch_first or key.dim() == 2 else key.shape[0]) + appended + + # Heads sum to embed_dim across both attention matrix products, so num_heads only multiplies the softmax rows. + projections = m.embed_dim * (2 * tgt_len * m.embed_dim + (attended - appended) * (m.kdim + m.vdim)) + attention = 2 * tgt_len * attended * m.embed_dim + softmax = calculate_softmax(batch_size * m.num_heads * tgt_len, attended) + m.total_ops += batch_size * (projections + attention) + softmax diff --git a/.venv/lib/python3.12/site-packages/thop/vision/calc_func.py b/.venv/lib/python3.12/site-packages/thop/vision/calc_func.py new file mode 100644 index 0000000000000000000000000000000000000000..01fbe7100f688fc81e95a990ca5857278239d56b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/vision/calc_func.py @@ -0,0 +1,53 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from torch.nn.parameter import UninitializedParameter + + +def l_prod(in_list): + """Compute the product of all elements in the input list.""" + res = 1 + for _ in in_list: + res *= _ + return res + + +def calculate_parameters(param_list): + """Sum the element counts of an iterable of parameters, skipping any a lazy module has not created yet.""" + # a lazy module's parameters hold no elements until its first forward pass, and asking one for its + # element count raises rather than answering 0, so they are skipped instead of being counted. + # isinstance rather than torch.nn.parameter.is_lazy: that helper only exists from torch 1.9 on + return sum(p.nelement() for p in param_list if not isinstance(p, UninitializedParameter)) + + +def calculate_zero_ops(): + """Return the zero operation count.""" + return 0 + + +def calculate_conv2d_flops( + input_size: list, output_size: list, kernel_size: list, groups: int, bias: bool = False, transpose: bool = False +): + """Calculate FLOPs for a ConvNd layer using input/output sizes, kernel size, groups, and the bias flag.""" + # A transpose scatters rather than gathers, so it walks the input and takes its channel from the output. + volume, channels = (input_size, output_size) if transpose else (output_size, input_size) + # The channel axis is counted from the trailing end, so unbatched input lands on it too. + return l_prod(volume) * (channels[-(len(kernel_size) - 1)] // groups) * l_prod(kernel_size[2:]) + + +def calculate_norm(input_size): + """Compute the L2 norm of a tensor or array based on its input size.""" + return 2 * input_size + + +def calculate_softmax(batch_size, nfeatures): + """Compute FLOPs for a softmax activation given batch size and feature count.""" + total_exp = nfeatures + total_add = max(nfeatures - 1, 0) # normalizing an empty axis costs nothing, rather than one negative addition + total_div = nfeatures + total_ops = batch_size * (total_exp + total_add + total_div) + return int(total_ops) + + +def calculate_linear(in_feature, num_elements): + """Calculate the linear operation count for given input feature and number of elements.""" + return int(in_feature * num_elements) diff --git a/.venv/lib/python3.12/site-packages/torch/_C.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/torch/_C.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a30c4bf779868837477b3834d4028da56406760d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_C.cpython-312-x86_64-linux-gnu.so differ diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_VariableFunctions.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_VariableFunctions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2206a7e4093629d183276c42bfb015b061af3536 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_VariableFunctions.pyi @@ -0,0 +1,31270 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/_VariableFunctions.pyi.in +# mypy: disable-error-code="type-arg" +# mypy: allow-untyped-defs +# ruff: noqa: F401,PYI054 + +from collections.abc import Callable, Sequence +from types import EllipsisType +from typing import Any, Literal, overload, TypeVar + +import torch +from torch import ( + contiguous_format, + Generator, + inf, + memory_format, + strided, + SymInt, + Tensor, +) +from torch._prims_common import DeviceLikeType +from torch.types import ( + _bool, + _complex, + _device, + _dtype, + _float, + _int, + _layout, + _qscheme, + _size, + Device, + Number, + PySymType, +) + +__all__ = [ + "__and__", + "__lshift__", + "__or__", + "__rshift__", + "__xor__", + "_adaptive_avg_pool2d", + "_adaptive_avg_pool3d", + "_add_batch_dim", + "_add_relu", + "_add_relu_", + "_addmm_activation", + "_aminmax", + "_amp_foreach_non_finite_check_and_unscale_", + "_amp_update_scale_", + "_assert_async", + "_assert_scalar", + "_assert_tensor_metadata", + "_batch_norm_impl_index", + "_cast_Byte", + "_cast_Char", + "_cast_Double", + "_cast_Float", + "_cast_Half", + "_cast_Int", + "_cast_Long", + "_cast_Short", + "_choose_qparams_per_tensor", + "_chunk_cat", + "_coalesce", + "_compute_linear_combination", + "_conj", + "_conj_copy", + "_conj_physical", + "_convert_indices_from_coo_to_csr", + "_convert_indices_from_csr_to_coo", + "_convert_weight_to_int4pack", + "_convert_weight_to_int4pack_for_cpu", + "_convolution", + "_convolution_mode", + "_copy_from", + "_copy_from_and_resize", + "_cslt_compress", + "_cslt_sparse_mm", + "_cslt_sparse_mm_search", + "_ctc_loss", + "_cudnn_ctc_loss", + "_cudnn_init_dropout_state", + "_cudnn_rnn", + "_cudnn_rnn_flatten_weight", + "_cufft_clear_plan_cache", + "_cufft_get_plan_cache_max_size", + "_cufft_get_plan_cache_size", + "_cufft_set_plan_cache_max_size", + "_cummax_helper", + "_cummin_helper", + "_debug_has_internal_overlap", + "_dim_arange", + "_dirichlet_grad", + "_disable_functionalization", + "_dyn_quant_matmul_4bit", + "_dyn_quant_pack_4bit_weight", + "_efficientzerotensor", + "_embedding_bag", + "_embedding_bag_forward_only", + "_empty_affine_quantized", + "_empty_per_channel_affine_quantized", + "_enable_functionalization", + "_euclidean_dist", + "_fake_quantize_learnable_per_channel_affine", + "_fake_quantize_learnable_per_tensor_affine", + "_fake_quantize_per_tensor_affine_cachemask_tensor_qparams", + "_fft_c2c", + "_fft_c2r", + "_fft_r2c", + "_fill_mem_eff_dropout_mask_", + "_flash_attention_forward_no_dropout_inplace", + "_foobar", + "_foreach_abs", + "_foreach_abs_", + "_foreach_acos", + "_foreach_acos_", + "_foreach_add", + "_foreach_add_", + "_foreach_addcdiv", + "_foreach_addcdiv_", + "_foreach_addcmul", + "_foreach_addcmul_", + "_foreach_asin", + "_foreach_asin_", + "_foreach_atan", + "_foreach_atan_", + "_foreach_ceil", + "_foreach_ceil_", + "_foreach_clamp_max", + "_foreach_clamp_max_", + "_foreach_clamp_min", + "_foreach_clamp_min_", + "_foreach_clone", + "_foreach_copy_", + "_foreach_cos", + "_foreach_cos_", + "_foreach_cosh", + "_foreach_cosh_", + "_foreach_div", + "_foreach_div_", + "_foreach_erf", + "_foreach_erf_", + "_foreach_erfc", + "_foreach_erfc_", + "_foreach_exp", + "_foreach_exp_", + "_foreach_expm1", + "_foreach_expm1_", + "_foreach_floor", + "_foreach_floor_", + "_foreach_frac", + "_foreach_frac_", + "_foreach_lerp", + "_foreach_lerp_", + "_foreach_lgamma", + "_foreach_lgamma_", + "_foreach_log", + "_foreach_log10", + "_foreach_log10_", + "_foreach_log1p", + "_foreach_log1p_", + "_foreach_log2", + "_foreach_log2_", + "_foreach_log_", + "_foreach_max", + "_foreach_maximum", + "_foreach_maximum_", + "_foreach_minimum", + "_foreach_minimum_", + "_foreach_mm", + "_foreach_mul", + "_foreach_mul_", + "_foreach_neg", + "_foreach_neg_", + "_foreach_norm", + "_foreach_pow", + "_foreach_pow_", + "_foreach_powsum", + "_foreach_reciprocal", + "_foreach_reciprocal_", + "_foreach_round", + "_foreach_round_", + "_foreach_rsqrt", + "_foreach_rsqrt_", + "_foreach_sigmoid", + "_foreach_sigmoid_", + "_foreach_sign", + "_foreach_sign_", + "_foreach_sin", + "_foreach_sin_", + "_foreach_sinh", + "_foreach_sinh_", + "_foreach_sqrt", + "_foreach_sqrt_", + "_foreach_sub", + "_foreach_sub_", + "_foreach_tan", + "_foreach_tan_", + "_foreach_tanh", + "_foreach_tanh_", + "_foreach_trunc", + "_foreach_trunc_", + "_foreach_zero_", + "_from_functional_tensor", + "_functional_assert_async", + "_functional_assert_scalar", + "_functional_sym_constrain_range", + "_functional_sym_constrain_range_for_size", + "_functionalize_apply_view_metas", + "_functionalize_are_all_mutations_hidden_from_autograd", + "_functionalize_are_all_mutations_under_no_grad_or_inference_mode", + "_functionalize_commit_update", + "_functionalize_has_metadata_mutation", + "_functionalize_inductor_storage_resized_counter", + "_functionalize_is_symbolic", + "_functionalize_mark_mutation_hidden_from_autograd", + "_functionalize_mark_storage_changed", + "_functionalize_mutation_counter", + "_functionalize_replace", + "_functionalize_storage_changed_counter", + "_functionalize_sync", + "_functionalize_unsafe_set", + "_functionalize_was_inductor_storage_resized", + "_functionalize_was_storage_changed", + "_fused_adagrad_", + "_fused_adam_", + "_fused_adamw_", + "_fused_dropout", + "_fused_moving_avg_obs_fq_helper", + "_fused_rms_norm", + "_fused_sdp_choice", + "_fused_sgd_", + "_fw_primal_copy", + "_grid_sampler_2d_cpu_fallback", + "_grouped_mm", + "_has_compatible_shallow_copy_type", + "_histogramdd_bin_edges", + "_histogramdd_from_bin_cts", + "_histogramdd_from_bin_tensors", + "_index_put_impl_", + "_indices_copy", + "_int_mm", + "_is_all_true", + "_is_any_true", + "_is_functional_tensor", + "_is_functional_tensor_base", + "_is_zerotensor", + "_lazy_clone", + "_linalg_check_errors", + "_linalg_det", + "_linalg_eigh", + "_linalg_slogdet", + "_linalg_solve_ex", + "_linalg_svd", + "_log_softmax", + "_log_softmax_backward_data", + "_logcumsumexp", + "_lstm_mps", + "_lu_with_info", + "_make_dep_token", + "_make_dual", + "_make_dual_copy", + "_make_per_channel_quantized_tensor", + "_make_per_tensor_quantized_tensor", + "_masked_scale", + "_masked_softmax", + "_mixed_dtypes_linear", + "_mkldnn_reshape", + "_mkldnn_transpose", + "_mkldnn_transpose_", + "_mps_convolution", + "_mps_convolution_transpose", + "_native_batch_norm_legit", + "_native_batch_norm_legit_no_training", + "_native_multi_head_attention", + "_neg_view", + "_neg_view_copy", + "_nested_compute_contiguous_strides_offsets", + "_nested_from_padded", + "_nested_from_padded_and_nested_example", + "_nested_from_padded_tensor", + "_nested_get_jagged_dummy", + "_nested_get_lengths", + "_nested_get_max_seqlen", + "_nested_get_min_seqlen", + "_nested_get_offsets", + "_nested_get_ragged_idx", + "_nested_get_values", + "_nested_get_values_copy", + "_nested_tensor_from_mask", + "_nested_tensor_from_mask_left_aligned", + "_nested_tensor_from_tensor_list", + "_nested_tensor_softmax_with_shape", + "_nested_view_from_buffer", + "_nested_view_from_buffer_copy", + "_nested_view_from_jagged", + "_nested_view_from_jagged_copy", + "_nnpack_available", + "_nnpack_spatial_convolution", + "_pack_padded_sequence", + "_pad_packed_sequence", + "_philox_key_fold_in", + "_philox_key_split", + "_philox_normal_", + "_philox_uniform_", + "_pin_memory", + "_prelu_kernel", + "_print", + "_propagate_xla_data", + "_remove_batch_dim", + "_reshape_alias_copy", + "_reshape_from_tensor", + "_resize_output_", + "_rowwise_prune", + "_safe_softmax", + "_sample_dirichlet", + "_saturate_weight_to_fp16", + "_scaled_dot_product_attention_math", + "_scaled_dot_product_attention_math_for_mps", + "_scaled_dot_product_cudnn_attention", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_flash_attention_for_cpu", + "_scaled_grouped_mm", + "_scaled_grouped_mm_v2", + "_scaled_mm", + "_scaled_mm_v2", + "_shape_as_tensor", + "_sobol_engine_draw", + "_sobol_engine_ff_", + "_sobol_engine_initialize_state_", + "_sobol_engine_scramble_", + "_softmax", + "_softmax_backward_data", + "_sparse_broadcast_to", + "_sparse_broadcast_to_copy", + "_sparse_csr_prod", + "_sparse_csr_sum", + "_sparse_log_softmax_backward_data", + "_sparse_semi_structured_addmm", + "_sparse_semi_structured_apply", + "_sparse_semi_structured_apply_dense", + "_sparse_semi_structured_linear", + "_sparse_semi_structured_mm", + "_sparse_semi_structured_tile", + "_sparse_softmax_backward_data", + "_sparse_sparse_matmul", + "_sparse_sum", + "_stack", + "_standard_gamma", + "_standard_gamma_grad", + "_sync", + "_test_autograd_multiple_dispatch", + "_test_autograd_multiple_dispatch_view", + "_test_autograd_multiple_dispatch_view_copy", + "_test_check_tensor", + "_test_functorch_fallback", + "_test_parallel_materialize", + "_test_serialization_subcmul", + "_to_cpu", + "_to_functional_tensor", + "_to_sparse_semi_structured", + "_transform_bias_rescale_qkv", + "_transformer_encoder_layer_fwd", + "_trilinear", + "_triton_multi_head_attention", + "_triton_scaled_dot_attention", + "_unique", + "_unique2", + "_unpack_dual", + "_unsafe_index", + "_unsafe_index_put", + "_unsafe_masked_index", + "_unsafe_masked_index_put_accumulate", + "_use_cudnn_ctc_loss", + "_use_cudnn_rnn_flatten_weight", + "_use_miopen_ctc_loss", + "_validate_compressed_sparse_indices", + "_validate_sparse_bsc_tensor_args", + "_validate_sparse_bsr_tensor_args", + "_validate_sparse_compressed_tensor_args", + "_validate_sparse_coo_tensor_args", + "_validate_sparse_csc_tensor_args", + "_validate_sparse_csr_tensor_args", + "_values_copy", + "_weight_int4pack_mm", + "_weight_int4pack_mm_for_cpu", + "_weight_int4pack_mm_with_scales_and_zeros", + "_weight_int8pack_mm", + "_weight_norm", + "_weight_norm_interface", + "_wrapped_linear_prepack", + "_wrapped_quantized_linear_prepacked", + "abs", + "abs_", + "absolute", + "acos", + "acos_", + "acosh", + "acosh_", + "adaptive_avg_pool1d", + "adaptive_max_pool1d", + "add", + "addbmm", + "addcdiv", + "addcmul", + "addmm", + "addmv", + "addmv_", + "addr", + "adjoint", + "affine_grid_generator", + "alias_copy", + "all", + "allclose", + "alpha_dropout", + "alpha_dropout_", + "amax", + "amin", + "aminmax", + "angle", + "any", + "arange", + "arccos", + "arccos_", + "arccosh", + "arccosh_", + "arcsin", + "arcsin_", + "arcsinh", + "arcsinh_", + "arctan", + "arctan2", + "arctan_", + "arctanh", + "arctanh_", + "argmax", + "argmin", + "argsort", + "argwhere", + "as_strided", + "as_strided_", + "as_strided_copy", + "as_strided_scatter", + "as_tensor", + "asarray", + "asin", + "asin_", + "asinh", + "asinh_", + "atan", + "atan2", + "atan_", + "atanh", + "atanh_", + "avg_pool1d", + "baddbmm", + "bartlett_window", + "batch_norm", + "batch_norm_backward_elemt", + "batch_norm_backward_reduce", + "batch_norm_elemt", + "batch_norm_gather_stats", + "batch_norm_gather_stats_with_counts", + "batch_norm_stats", + "batch_norm_update_stats", + "bernoulli", + "bilinear", + "binary_cross_entropy_with_logits", + "bincount", + "binomial", + "bitwise_and", + "bitwise_left_shift", + "bitwise_not", + "bitwise_or", + "bitwise_right_shift", + "bitwise_xor", + "blackman_window", + "bmm", + "broadcast_to", + "bucketize", + "can_cast", + "cat", + "ccol_indices_copy", + "ceil", + "ceil_", + "celu", + "celu_", + "channel_shuffle", + "cholesky_inverse", + "cholesky_solve", + "choose_qparams_optimized", + "chunk", + "clamp", + "clamp_", + "clamp_max", + "clamp_max_", + "clamp_min", + "clamp_min_", + "clip", + "clip_", + "clone", + "col_indices_copy", + "column_stack", + "combinations", + "complex", + "concat", + "concatenate", + "conj", + "conj_physical", + "conj_physical_", + "constant_pad_nd", + "conv1d", + "conv2d", + "conv3d", + "conv_tbc", + "conv_transpose1d", + "conv_transpose2d", + "conv_transpose3d", + "convolution", + "copysign", + "corrcoef", + "cos", + "cos_", + "cosh", + "cosh_", + "cosine_embedding_loss", + "cosine_similarity", + "count_nonzero", + "cov", + "cross", + "crow_indices_copy", + "ctc_loss", + "cudnn_affine_grid_generator", + "cudnn_batch_norm", + "cudnn_convolution", + "cudnn_convolution_add_relu", + "cudnn_convolution_relu", + "cudnn_convolution_transpose", + "cudnn_grid_sampler", + "cudnn_is_acceptable", + "cummax", + "cummin", + "cumprod", + "cumsum", + "cumulative_trapezoid", + "deg2rad", + "deg2rad_", + "dequantize", + "det", + "detach", + "detach_", + "detach_copy", + "diag", + "diag_embed", + "diagflat", + "diagonal", + "diagonal_copy", + "diagonal_scatter", + "diff", + "digamma", + "dist", + "div", + "divide", + "dot", + "dropout", + "dropout_", + "dsmm", + "dsplit", + "dstack", + "embedding", + "embedding_bag", + "embedding_renorm_", + "empty", + "empty_like", + "empty_permuted", + "empty_quantized", + "empty_strided", + "eq", + "equal", + "erf", + "erf_", + "erfc", + "erfc_", + "erfinv", + "exp", + "exp2", + "exp2_", + "exp_", + "expand_copy", + "expm1", + "expm1_", + "eye", + "fake_quantize_per_channel_affine", + "fake_quantize_per_tensor_affine", + "fbgemm_linear_fp16_weight", + "fbgemm_linear_fp16_weight_fp32_activation", + "fbgemm_linear_int8_weight", + "fbgemm_linear_int8_weight_fp32_activation", + "fbgemm_linear_quantize_weight", + "fbgemm_pack_gemm_matrix_fp16", + "fbgemm_pack_quantized_matrix", + "feature_alpha_dropout", + "feature_alpha_dropout_", + "feature_dropout", + "feature_dropout_", + "fill", + "fill_", + "fix", + "fix_", + "flatten", + "flip", + "fliplr", + "flipud", + "float_power", + "floor", + "floor_", + "floor_divide", + "fmax", + "fmin", + "fmod", + "frac", + "frac_", + "frexp", + "frobenius_norm", + "from_file", + "from_numpy", + "frombuffer", + "full", + "full_like", + "fused_moving_avg_obs_fake_quant", + "gather", + "gcd", + "gcd_", + "ge", + "geqrf", + "ger", + "get_default_dtype", + "get_num_interop_threads", + "get_num_threads", + "gradient", + "greater", + "greater_equal", + "grid_sampler", + "grid_sampler_2d", + "grid_sampler_3d", + "group_norm", + "gru", + "gru_cell", + "gt", + "hamming_window", + "hann_window", + "hardshrink", + "hash_tensor", + "heaviside", + "hinge_embedding_loss", + "histc", + "histogram", + "histogramdd", + "hsmm", + "hsplit", + "hspmm", + "hstack", + "hypot", + "i0", + "i0_", + "igamma", + "igammac", + "imag", + "index_add", + "index_copy", + "index_fill", + "index_put", + "index_put_", + "index_reduce", + "index_select", + "indices_copy", + "init_num_threads", + "inner", + "instance_norm", + "int_repr", + "inverse", + "is_complex", + "is_conj", + "is_distributed", + "is_floating_point", + "is_grad_enabled", + "is_inference", + "is_inference_mode_enabled", + "is_neg", + "is_nonzero", + "is_same_size", + "is_signed", + "is_vulkan_available", + "isclose", + "isfinite", + "isin", + "isinf", + "isnan", + "isneginf", + "isposinf", + "isreal", + "istft", + "kaiser_window", + "kl_div", + "kron", + "kthvalue", + "layer_norm", + "lcm", + "lcm_", + "ldexp", + "ldexp_", + "le", + "lerp", + "less", + "less_equal", + "lgamma", + "linspace", + "log", + "log10", + "log10_", + "log1p", + "log1p_", + "log2", + "log2_", + "log_", + "log_softmax", + "logaddexp", + "logaddexp2", + "logcumsumexp", + "logdet", + "logical_and", + "logical_not", + "logical_or", + "logical_xor", + "logit", + "logit_", + "logspace", + "logsumexp", + "lstm", + "lstm_cell", + "lt", + "lu_solve", + "lu_unpack", + "margin_ranking_loss", + "masked_fill", + "masked_scatter", + "masked_select", + "matmul", + "matrix_exp", + "matrix_power", + "max", + "max_pool1d", + "max_pool1d_with_indices", + "max_pool2d", + "max_pool3d", + "maximum", + "mean", + "median", + "min", + "minimum", + "miopen_batch_norm", + "miopen_convolution", + "miopen_convolution_add_relu", + "miopen_convolution_relu", + "miopen_convolution_transpose", + "miopen_ctc_loss", + "miopen_depthwise_convolution", + "miopen_rnn", + "mkldnn_adaptive_avg_pool2d", + "mkldnn_convolution", + "mkldnn_linear_backward_weights", + "mkldnn_max_pool2d", + "mkldnn_max_pool3d", + "mkldnn_rnn_layer", + "mm", + "mode", + "moveaxis", + "movedim", + "msort", + "mul", + "multinomial", + "multiply", + "mv", + "mvlgamma", + "nan_to_num", + "nan_to_num_", + "nanmean", + "nanmedian", + "nanquantile", + "nansum", + "narrow", + "narrow_copy", + "native_batch_norm", + "native_channel_shuffle", + "native_dropout", + "native_group_norm", + "native_layer_norm", + "native_norm", + "ne", + "neg", + "neg_", + "negative", + "negative_", + "nextafter", + "nonzero", + "nonzero_static", + "norm_except_dim", + "normal", + "not_equal", + "nuclear_norm", + "numel", + "ones", + "ones_like", + "orgqr", + "ormqr", + "outer", + "pairwise_distance", + "pdist", + "permute", + "permute_copy", + "pinverse", + "pixel_shuffle", + "pixel_unshuffle", + "poisson", + "poisson_nll_loss", + "polar", + "polygamma", + "positive", + "pow", + "prelu", + "prod", + "promote_types", + "put", + "q_per_channel_axis", + "q_per_channel_scales", + "q_per_channel_zero_points", + "q_scale", + "q_zero_point", + "quantile", + "quantize_per_channel", + "quantize_per_tensor", + "quantize_per_tensor_dynamic", + "quantized_batch_norm", + "quantized_gru_cell", + "quantized_lstm_cell", + "quantized_max_pool1d", + "quantized_max_pool2d", + "quantized_max_pool3d", + "quantized_rnn_relu_cell", + "quantized_rnn_tanh_cell", + "rad2deg", + "rad2deg_", + "rand", + "rand_like", + "randint", + "randint_like", + "randn", + "randn_like", + "randperm", + "range", + "ravel", + "real", + "reciprocal", + "reciprocal_", + "relu", + "relu_", + "remainder", + "renorm", + "repeat_interleave", + "reshape", + "resize_as_", + "resize_as_sparse_", + "resolve_conj", + "resolve_neg", + "result_type", + "rms_norm", + "rnn_relu", + "rnn_relu_cell", + "rnn_tanh", + "rnn_tanh_cell", + "roll", + "rot90", + "round", + "round_", + "row_indices_copy", + "row_stack", + "rrelu", + "rrelu_", + "rsqrt", + "rsqrt_", + "rsub", + "saddmm", + "scalar_tensor", + "scatter", + "scatter_add", + "scatter_reduce", + "searchsorted", + "segment_reduce", + "select", + "select_copy", + "select_scatter", + "selu", + "selu_", + "set_flush_denormal", + "set_num_interop_threads", + "set_num_threads", + "sgn", + "sigmoid", + "sigmoid_", + "sign", + "signbit", + "sin", + "sin_", + "sinc", + "sinc_", + "sinh", + "sinh_", + "slice_copy", + "slice_inverse", + "slice_scatter", + "slogdet", + "smm", + "softmax", + "sort", + "sparse_bsc_tensor", + "sparse_bsr_tensor", + "sparse_compressed_tensor", + "sparse_coo_tensor", + "sparse_csc_tensor", + "sparse_csr_tensor", + "split_copy", + "split_with_sizes", + "split_with_sizes_copy", + "spmm", + "sqrt", + "sqrt_", + "square", + "square_", + "squeeze", + "squeeze_copy", + "sspaddmm", + "stack", + "std", + "std_mean", + "sub", + "subtract", + "sum", + "svd", + "swapaxes", + "swapdims", + "sym_constrain_range", + "sym_constrain_range_for_size", + "t", + "t_copy", + "take", + "take_along_dim", + "tan", + "tan_", + "tanh", + "tanh_", + "tensor", + "tensor_split", + "threshold", + "threshold_", + "tile", + "topk", + "trace", + "transpose", + "transpose_copy", + "trapezoid", + "trapz", + "triangular_solve", + "tril", + "tril_indices", + "triplet_margin_loss", + "triu", + "triu_indices", + "true_divide", + "trunc", + "trunc_", + "unbind", + "unbind_copy", + "unflatten", + "unfold_copy", + "unique_dim", + "unsafe_chunk", + "unsafe_split", + "unsafe_split_with_sizes", + "unsqueeze", + "unsqueeze_copy", + "values_copy", + "vander", + "var", + "var_mean", + "vdot", + "view_as_complex", + "view_as_complex_copy", + "view_as_real", + "view_as_real_copy", + "view_copy", + "vsplit", + "vstack", + "where", + "xlogy", + "xlogy_", + "zero_", + "zeros", + "zeros_like", +] + +@overload +def __and__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __and__(input: Tensor, other: Number | _complex | PySymType) -> Tensor: ... +@overload +def __lshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __lshift__( + input: Tensor, + other: Number | _complex | PySymType, +) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Number | _complex | PySymType) -> Tensor: ... +@overload +def __rshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __rshift__( + input: Tensor, + other: Number | _complex | PySymType, +) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Number | _complex | PySymType) -> Tensor: ... +def _adaptive_avg_pool2d( + input: Tensor, + output_size: _int | SymInt | Sequence[_int | SymInt], +) -> Tensor: ... +def _adaptive_avg_pool3d( + input: Tensor, + output_size: _int | SymInt | Sequence[_int | SymInt], +) -> Tensor: ... +def _add_batch_dim(input: Tensor, batch_dim: _int, level: _int) -> Tensor: ... +@overload +def _add_relu( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def _add_relu( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +def _addmm_activation( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + use_gelu: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def _aminmax(input: Tensor) -> tuple[Tensor, Tensor]: ... +@overload +def _aminmax( + input: Tensor, + dim: _int, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _amp_foreach_non_finite_check_and_unscale_( + self: tuple[Tensor, ...] | list[Tensor], + found_inf: Tensor, + inv_scale: Tensor, +) -> None: ... +def _amp_update_scale_( + input: Tensor, + growth_tracker: Tensor, + found_inf: Tensor, + scale_growth_factor: _float, + scale_backoff_factor: _float, + growth_interval: _int, +) -> Tensor: ... +@overload +def _assert_async(input: Tensor) -> None: + r""" + _assert_async(tensor) -> void + + Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, + this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for + CUDA tensors, we DO NOT synchronize and you may only find out the assertion + failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for + testing invariants in CUDA tensors without giving up performance. This function + is NOT intended to be used for regular error checking, as it will trash your CUDA + context if the assert fails (forcing you to restart your PyTorch process.) + + Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. + """ + +@overload +def _assert_async(input: Tensor, assert_msg: str) -> None: + r""" + _assert_async(tensor) -> void + + Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, + this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for + CUDA tensors, we DO NOT synchronize and you may only find out the assertion + failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for + testing invariants in CUDA tensors without giving up performance. This function + is NOT intended to be used for regular error checking, as it will trash your CUDA + context if the assert fails (forcing you to restart your PyTorch process.) + + Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. + """ + +def _assert_scalar( + self: Number | _complex | PySymType, + assert_msg: str, +) -> None: ... +def _assert_tensor_metadata( + a: Tensor, + size: Sequence[_int | SymInt] | None = None, + stride: Sequence[_int | SymInt] | None = None, + dtype: _dtype | None = None, + *, + device: DeviceLikeType | None = None, + layout: _layout | None = None, +) -> None: ... +def _batch_norm_impl_index( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor, _int]: ... +def _cast_Byte(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Char(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Double(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Float(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Half(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Int(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Long(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Short(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _choose_qparams_per_tensor( + input: Tensor, + reduce_range: _bool = False, +) -> tuple[_float, _int]: ... +def _chunk_cat( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int, + num_chunks: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _coalesce(input: Tensor) -> Tensor: ... +def _compute_linear_combination( + input: Tensor, + coefficients: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _conj(input: Tensor) -> Tensor: ... +def _conj_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _conj_physical(input: Tensor) -> Tensor: ... +def _convert_indices_from_coo_to_csr( + input: Tensor, + size: _int, + *, + out_int32: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +def _convert_indices_from_csr_to_coo( + crow_indices: Tensor, + col_indices: Tensor, + *, + out_int32: _bool = False, + transpose: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +def _convert_weight_to_int4pack(input: Tensor, innerKTiles: _int) -> Tensor: ... +def _convert_weight_to_int4pack_for_cpu( + input: Tensor, + innerKTiles: _int, +) -> Tensor: ... +@overload +def _convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: _size, + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + cudnn_enabled: _bool, +) -> Tensor: ... +@overload +def _convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + cudnn_enabled: _bool, + allow_tf32: _bool, +) -> Tensor: ... +def _convolution_mode( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: str, + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def _copy_from( + input: Tensor, + dst: Tensor, + non_blocking: _bool = False, +) -> Tensor: ... +def _copy_from_and_resize(input: Tensor, dst: Tensor) -> Tensor: ... +def _cslt_compress(input: Tensor) -> Tensor: ... +def _cslt_sparse_mm( + compressed_A: Tensor, + dense_B: Tensor, + bias: Tensor | None = None, + alpha: Tensor | None = None, + out_dtype: _dtype | None = None, + transpose_result: _bool = False, + alg_id: _int = 0, + split_k: _int = 1, + split_k_mode: _int = -1, +) -> Tensor: ... +def _cslt_sparse_mm_search( + compressed_A: Tensor, + dense_B: Tensor, + bias: Tensor | None = None, + alpha: Tensor | None = None, + out_dtype: _dtype | None = None, + transpose_result: _bool = False, +) -> _int: ... +@overload +def _ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int = 0, + zero_infinity: _bool = False, +) -> tuple[Tensor, Tensor]: ... +@overload +def _ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int = 0, + zero_infinity: _bool = False, +) -> tuple[Tensor, Tensor]: ... +@overload +def _cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def _cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +def _cudnn_init_dropout_state( + dropout: _float, + train: _bool, + dropout_seed: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _cudnn_rnn( + input: Tensor, + weight: tuple[Tensor, ...] | list[Tensor], + weight_stride0: _int, + weight_buf: Tensor | None, + hx: Tensor, + cx: Tensor | None, + mode: _int, + hidden_size: _int | SymInt, + proj_size: _int | SymInt, + num_layers: _int, + batch_first: _bool, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_sizes: Sequence[_int | SymInt], + dropout_state: Tensor | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _cudnn_rnn_flatten_weight( + weight_arr: tuple[Tensor, ...] | list[Tensor], + weight_stride0: _int, + input_size: _int | SymInt, + mode: _int, + hidden_size: _int | SymInt, + proj_size: _int | SymInt, + num_layers: _int, + batch_first: _bool, + bidirectional: _bool, +) -> Tensor: ... +def _cufft_clear_plan_cache(device_index: _int) -> None: ... +def _cufft_get_plan_cache_max_size(device_index: _int) -> _int: ... +def _cufft_get_plan_cache_size(device_index: _int) -> _int: ... +def _cufft_set_plan_cache_max_size( + device_index: _int, + max_size: _int, +) -> None: ... +def _cummax_helper( + input: Tensor, + values: Tensor, + indices: Tensor, + dim: _int, +) -> None: ... +def _cummin_helper( + input: Tensor, + values: Tensor, + indices: Tensor, + dim: _int, +) -> None: ... +def _debug_has_internal_overlap(input: Tensor) -> _int: ... +def _dim_arange(like: Tensor, dim: _int) -> Tensor: ... +def _dirichlet_grad(x: Tensor, alpha: Tensor, total: Tensor) -> Tensor: ... +def _disable_functionalization(): ... +def _dyn_quant_matmul_4bit( + inp: Tensor, + packed_weights: Tensor, + block_size: _int, + in_features: _int, + out_features: _int, +) -> Tensor: ... +def _dyn_quant_pack_4bit_weight( + weights: Tensor, + scales_zeros: Tensor, + bias: Tensor | None, + block_size: _int, + in_features: _int, + out_features: _int, +) -> Tensor: ... +@overload +def _efficientzerotensor( + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _efficientzerotensor( + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, + padding_idx: _int = -1, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def _embedding_bag_forward_only( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, + padding_idx: _int = -1, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def _empty_affine_quantized( + size: Sequence[_int | SymInt], + *, + scale: _float = 1, + zero_point: _int = 0, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_affine_quantized( + *size: _int | SymInt, + scale: _float = 1, + zero_point: _int = 0, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_per_channel_affine_quantized( + size: Sequence[_int | SymInt], + *, + scales: Tensor, + zero_points: Tensor, + axis: _int, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_per_channel_affine_quantized( + *size: _int | SymInt, + scales: Tensor, + zero_points: Tensor, + axis: _int, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _enable_functionalization(*, reapply_views: _bool = False) -> None: ... +def _euclidean_dist(x1: Tensor, x2: Tensor) -> Tensor: ... +def _fake_quantize_learnable_per_channel_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, + quant_min: _int, + quant_max: _int, + grad_factor: _float = 1.0, +) -> Tensor: ... +def _fake_quantize_learnable_per_tensor_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + quant_min: _int, + quant_max: _int, + grad_factor: _float = 1.0, +) -> Tensor: ... +def _fake_quantize_per_tensor_affine_cachemask_tensor_qparams( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + fake_quant_enabled: Tensor, + quant_min: _int, + quant_max: _int, +) -> torch.return_types._fake_quantize_per_tensor_affine_cachemask_tensor_qparams: # fmt: skip + ... +def _fft_c2c( + input: Tensor, + dim: Sequence[_int | SymInt], + normalization: _int, + forward: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fft_c2r( + input: Tensor, + dim: _size, + normalization: _int, + last_dim_size: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fft_r2c( + input: Tensor, + dim: _size, + normalization: _int, + onesided: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fill_mem_eff_dropout_mask_( + input: Tensor, + dropout_p: _float, + seed: _int, + offset: _int, +) -> Tensor: ... +def _flash_attention_forward_no_dropout_inplace( + out: Tensor | None, + query: Tensor, + key: Tensor, + value: Tensor, + cum_seq_q: Tensor | None, + cum_seq_k: Tensor | None, + max_q: _int | SymInt, + max_k: _int | SymInt, + dropout_p: _float, + is_causal: _bool, + return_debug_mask: _bool, + *, + scale: _float | None = None, + window_size_left: _int | SymInt | None = None, + window_size_right: _int | SymInt | None = None, + seqused_k: Tensor | None = None, + alibi_slopes: Tensor | None = None, + block_table: Tensor | None = None, + num_splits: _int | None = None, +) -> Tensor: ... +def _foobar( + input: Tensor, + arg1: _bool = True, + arg2: _bool = True, + *, + arg3: _bool = True, +) -> Tensor: ... +def _foreach_abs( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_abs(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.abs` to each Tensor of the input list. + """ + +def _foreach_abs_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_abs_(self: List[Tensor]) -> None + + Apply :func:`torch.abs` to each Tensor of the input list. + """ + +def _foreach_acos( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_acos(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.acos` to each Tensor of the input list. + """ + +def _foreach_acos_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_acos_(self: List[Tensor]) -> None + + Apply :func:`torch.acos` to each Tensor of the input list. + """ + +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> None: ... +def _foreach_asin( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_asin(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.asin` to each Tensor of the input list. + """ + +def _foreach_asin_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_asin_(self: List[Tensor]) -> None + + Apply :func:`torch.asin` to each Tensor of the input list. + """ + +def _foreach_atan( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_atan(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.atan` to each Tensor of the input list. + """ + +def _foreach_atan_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_atan_(self: List[Tensor]) -> None + + Apply :func:`torch.atan` to each Tensor of the input list. + """ + +def _foreach_ceil( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_ceil(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.ceil` to each Tensor of the input list. + """ + +def _foreach_ceil_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_ceil_(self: List[Tensor]) -> None + + Apply :func:`torch.ceil` to each Tensor of the input list. + """ + +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_clone( + self: tuple[Tensor, ...] | list[Tensor], + *, + memory_format: memory_format | None = None, +) -> tuple[Tensor, ...]: ... +def _foreach_copy_( + self: tuple[Tensor, ...] | list[Tensor], + src: tuple[Tensor, ...] | list[Tensor], + non_blocking: _bool = False, +) -> None: ... +def _foreach_cos( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_cos(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.cos` to each Tensor of the input list. + """ + +def _foreach_cos_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_cos_(self: List[Tensor]) -> None + + Apply :func:`torch.cos` to each Tensor of the input list. + """ + +def _foreach_cosh( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_cosh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.cosh` to each Tensor of the input list. + """ + +def _foreach_cosh_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_cosh_(self: List[Tensor]) -> None + + Apply :func:`torch.cosh` to each Tensor of the input list. + """ + +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_erf( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_erf(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.erf` to each Tensor of the input list. + """ + +def _foreach_erf_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_erf_(self: List[Tensor]) -> None + + Apply :func:`torch.erf` to each Tensor of the input list. + """ + +def _foreach_erfc( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_erfc(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.erfc` to each Tensor of the input list. + """ + +def _foreach_erfc_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_erfc_(self: List[Tensor]) -> None + + Apply :func:`torch.erfc` to each Tensor of the input list. + """ + +def _foreach_exp( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_exp(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.exp` to each Tensor of the input list. + """ + +def _foreach_exp_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_exp_(self: List[Tensor]) -> None + + Apply :func:`torch.exp` to each Tensor of the input list. + """ + +def _foreach_expm1( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_expm1(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.expm1` to each Tensor of the input list. + """ + +def _foreach_expm1_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_expm1_(self: List[Tensor]) -> None + + Apply :func:`torch.expm1` to each Tensor of the input list. + """ + +def _foreach_floor( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_floor(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.floor` to each Tensor of the input list. + """ + +def _foreach_floor_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_floor_(self: List[Tensor]) -> None + + Apply :func:`torch.floor` to each Tensor of the input list. + """ + +def _foreach_frac( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_frac(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.frac` to each Tensor of the input list. + """ + +def _foreach_frac_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_frac_(self: List[Tensor]) -> None + + Apply :func:`torch.frac` to each Tensor of the input list. + """ + +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weights: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weights: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_lgamma( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_lgamma(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.lgamma` to each Tensor of the input list. + """ + +def _foreach_lgamma_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_lgamma_(self: List[Tensor]) -> None + + Apply :func:`torch.lgamma` to each Tensor of the input list. + """ + +def _foreach_log( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_log(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log` to each Tensor of the input list. + """ + +def _foreach_log10( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_log10(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log10` to each Tensor of the input list. + """ + +def _foreach_log10_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_log10_(self: List[Tensor]) -> None + + Apply :func:`torch.log10` to each Tensor of the input list. + """ + +def _foreach_log1p( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_log1p(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log1p` to each Tensor of the input list. + """ + +def _foreach_log1p_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_log1p_(self: List[Tensor]) -> None + + Apply :func:`torch.log1p` to each Tensor of the input list. + """ + +def _foreach_log2( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_log2(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log2` to each Tensor of the input list. + """ + +def _foreach_log2_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_log2_(self: List[Tensor]) -> None + + Apply :func:`torch.log2` to each Tensor of the input list. + """ + +def _foreach_log_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_log_(self: List[Tensor]) -> None + + Apply :func:`torch.log` to each Tensor of the input list. + """ + +def _foreach_max( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_mm( + self: tuple[Tensor, ...] | list[Tensor], + mat2: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_neg( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_neg(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.neg` to each Tensor of the input list. + """ + +def _foreach_neg_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_neg_(self: List[Tensor]) -> None + + Apply :func:`torch.neg` to each Tensor of the input list. + """ + +def _foreach_norm( + self: tuple[Tensor, ...] | list[Tensor], + ord: Number | _complex | PySymType = 2, + dtype: _dtype | None = None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: Number | _complex | PySymType, + exponent: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_powsum( + self: tuple[Tensor, ...] | list[Tensor], + ord: Number | _complex | PySymType = 2, + dtype: _dtype | None = None, +) -> tuple[Tensor, ...]: ... +def _foreach_reciprocal( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_reciprocal(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.reciprocal` to each Tensor of the input list. + """ + +def _foreach_reciprocal_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_reciprocal_(self: List[Tensor]) -> None + + Apply :func:`torch.reciprocal` to each Tensor of the input list. + """ + +def _foreach_round( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_round(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.round` to each Tensor of the input list. + """ + +def _foreach_round_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_round_(self: List[Tensor]) -> None + + Apply :func:`torch.round` to each Tensor of the input list. + """ + +def _foreach_rsqrt( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +def _foreach_rsqrt_(self: tuple[Tensor, ...] | list[Tensor]) -> None: ... +def _foreach_sigmoid( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_sigmoid(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sigmoid` to each Tensor of the input list. + """ + +def _foreach_sigmoid_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_sigmoid_(self: List[Tensor]) -> None + + Apply :func:`torch.sigmoid` to each Tensor of the input list. + """ + +def _foreach_sign( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +def _foreach_sign_(self: tuple[Tensor, ...] | list[Tensor]) -> None: ... +def _foreach_sin( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_sin(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sin` to each Tensor of the input list. + """ + +def _foreach_sin_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_sin_(self: List[Tensor]) -> None + + Apply :func:`torch.sin` to each Tensor of the input list. + """ + +def _foreach_sinh( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_sinh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sinh` to each Tensor of the input list. + """ + +def _foreach_sinh_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_sinh_(self: List[Tensor]) -> None + + Apply :func:`torch.sinh` to each Tensor of the input list. + """ + +def _foreach_sqrt( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_sqrt(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sqrt` to each Tensor of the input list. + """ + +def _foreach_sqrt_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_sqrt_(self: List[Tensor]) -> None + + Apply :func:`torch.sqrt` to each Tensor of the input list. + """ + +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +def _foreach_tan( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_tan(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.tan` to each Tensor of the input list. + """ + +def _foreach_tan_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_tan_(self: List[Tensor]) -> None + + Apply :func:`torch.tan` to each Tensor of the input list. + """ + +def _foreach_tanh( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_tanh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.tanh` to each Tensor of the input list. + """ + +def _foreach_tanh_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_tanh_(self: List[Tensor]) -> None + + Apply :func:`torch.tanh` to each Tensor of the input list. + """ + +def _foreach_trunc( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_trunc(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.trunc` to each Tensor of the input list. + """ + +def _foreach_trunc_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_trunc_(self: List[Tensor]) -> None + + Apply :func:`torch.trunc` to each Tensor of the input list. + """ + +def _foreach_zero_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_zero_(self: List[Tensor]) -> None + + Apply :func:`torch.zero` to each Tensor of the input list. + """ + +def _from_functional_tensor(t: Tensor) -> Tensor: ... +def _functional_assert_async( + input: Tensor, + assert_msg: str, + dep_token: Tensor, +) -> Tensor: ... +def _functional_assert_scalar( + self: Number | _complex | PySymType, + assert_msg: str, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range( + size: Number | _complex | PySymType, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range_for_size( + size: Number | _complex | PySymType, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functionalize_apply_view_metas(tensor: Tensor, base: Tensor) -> Tensor: ... +def _functionalize_are_all_mutations_hidden_from_autograd( + t: Tensor, +) -> _bool: ... +def _functionalize_are_all_mutations_under_no_grad_or_inference_mode( + t: Tensor, +) -> _bool: ... +def _functionalize_commit_update(t: Tensor) -> None: ... +def _functionalize_has_metadata_mutation(tensor: Tensor) -> _bool: ... +def _functionalize_inductor_storage_resized_counter(t: Tensor) -> _int: ... +def _functionalize_is_symbolic(tensor: Tensor) -> _bool: ... +def _functionalize_mark_mutation_hidden_from_autograd(t: Tensor) -> None: ... +def _functionalize_mark_storage_changed(tensor: Tensor) -> _bool: ... +def _functionalize_mutation_counter(t: Tensor) -> _int: ... +def _functionalize_replace(self_: Tensor, other: Tensor) -> None: ... +def _functionalize_storage_changed_counter(t: Tensor) -> _int: ... +def _functionalize_sync(t: Tensor) -> None: ... +def _functionalize_unsafe_set(dst: Tensor, src: Tensor) -> None: ... +def _functionalize_was_inductor_storage_resized(t: Tensor) -> _bool: ... +def _functionalize_was_storage_changed(tensor: Tensor) -> _bool: ... +@overload +def _fused_adagrad_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + state_sums: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: Tensor, + lr_decay: _float, + weight_decay: _float, + eps: _float, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adagrad_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + state_sums: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: _float, + lr_decay: _float, + weight_decay: _float, + eps: _float, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adam_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: Tensor, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adam_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: _float, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adamw_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: Tensor, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adamw_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: _float, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +def _fused_dropout( + input: Tensor, + p: _float, + generator: Generator | None = None, +) -> tuple[Tensor, Tensor]: ... +def _fused_moving_avg_obs_fq_helper( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> torch.return_types._fused_moving_avg_obs_fq_helper: ... +def _fused_rms_norm( + input: Tensor, + normalized_shape: _size, + weight: Tensor | None, + eps: _float | None, +) -> tuple[Tensor, Tensor]: ... +def _fused_sdp_choice( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> _int: ... +@overload +def _fused_sgd_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor], + *, + weight_decay: _float, + momentum: _float, + lr: Tensor, + dampening: _float, + nesterov: _bool, + maximize: _bool, + is_first_step: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_sgd_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor], + *, + weight_decay: _float, + momentum: _float, + lr: _float, + dampening: _float, + nesterov: _bool, + maximize: _bool, + is_first_step: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +def _fw_primal_copy( + input: Tensor, + level: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _grid_sampler_2d_cpu_fallback( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def _grouped_mm( + input: Tensor, + mat2: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _has_compatible_shallow_copy_type( + input: Tensor, + from_: Tensor, +) -> _bool: ... +def _histogramdd_bin_edges( + input: Tensor, + bins: _size, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> tuple[Tensor, ...]: ... +def _histogramdd_from_bin_cts( + input: Tensor, + bins: _size, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> Tensor: ... +def _histogramdd_from_bin_tensors( + input: Tensor, + bins: tuple[Tensor, ...] | list[Tensor], + *, + weight: Tensor | None = None, + density: _bool = False, +) -> Tensor: ... +def _index_put_impl_( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, + unsafe: _bool = False, +) -> Tensor: ... +def _indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _int_mm( + input: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _is_all_true(input: Tensor) -> Tensor: ... +def _is_any_true(input: Tensor) -> Tensor: ... +def _is_functional_tensor(t: Tensor) -> _bool: ... +def _is_functional_tensor_base(t: Tensor) -> _bool: ... +def _is_zerotensor(input: Tensor) -> _bool: ... +def _lazy_clone(input: Tensor) -> Tensor: ... +def _linalg_check_errors( + info: Tensor, + api_name: str, + *, + is_matrix: _bool, +) -> None: ... +def _linalg_det( + A: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_det: ... +def _linalg_eigh( + A: Tensor, + UPLO: str = "L", + compute_v: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_eigh: ... +def _linalg_slogdet( + A: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_slogdet: ... +def _linalg_solve_ex( + A: Tensor, + B: Tensor, + *, + left: _bool = True, + check_errors: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_solve_ex: ... +def _linalg_svd( + A: Tensor, + full_matrices: _bool = False, + compute_uv: _bool = True, + *, + driver: str | None = None, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_svd: ... +def _log_softmax( + input: Tensor, + dim: _int, + half_to_float: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _log_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _logcumsumexp( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _lstm_mps( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _lu_with_info( + input: Tensor, + pivot: _bool = True, + check_errors: _bool = True, +) -> torch.return_types._lu_with_info: ... +def _make_dep_token( + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _make_dual(primal: Tensor, tangent: Tensor, level: _int) -> Tensor: ... +def _make_dual_copy( + primal: Tensor, + tangent: Tensor, + level: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _make_per_channel_quantized_tensor( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, +) -> Tensor: ... +def _make_per_tensor_quantized_tensor( + input: Tensor, + scale: _float, + zero_point: _int, +) -> Tensor: ... +def _masked_scale(input: Tensor, mask: Tensor, scale: _float) -> Tensor: ... +def _masked_softmax( + input: Tensor, + mask: Tensor, + dim: _int | None = None, + mask_type: _int | None = None, +) -> Tensor: ... +def _mixed_dtypes_linear( + input: Tensor, + weight: Tensor, + scale: Tensor, + *, + bias: Tensor | None = None, + activation: str | None = None, +) -> Tensor: ... +def _mkldnn_reshape(input: Tensor, shape: _size) -> Tensor: ... +def _mkldnn_transpose(input: Tensor, dim0: _int, dim1: _int) -> Tensor: ... +def _mkldnn_transpose_(input: Tensor, dim0: _int, dim1: _int) -> Tensor: ... +def _mps_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def _mps_convolution_transpose( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +@overload +def _native_batch_norm_legit( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def _native_batch_norm_legit( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _native_batch_norm_legit_no_training( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: _float, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _native_multi_head_attention( + query: Tensor, + key: Tensor, + value: Tensor, + embed_dim: _int, + num_head: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + mask: Tensor | None = None, + need_weights: _bool = True, + average_attn_weights: _bool = True, + mask_type: _int | None = None, +) -> tuple[Tensor, Tensor]: ... +def _neg_view(input: Tensor) -> Tensor: ... +def _neg_view_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _nested_compute_contiguous_strides_offsets( + nested_size: Tensor, +) -> tuple[Tensor, Tensor]: ... +def _nested_from_padded( + padded: Tensor, + cpu_nested_shape_example: Tensor, + fuse_transform_0213: _bool = False, +) -> Tensor: ... +def _nested_from_padded_and_nested_example( + padded: Tensor, + nt_example: Tensor, +) -> Tensor: ... +def _nested_from_padded_tensor( + padded: Tensor, + offsets: Tensor, + dummy: Tensor, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, + sum_S: _int | SymInt | None = None, +) -> Tensor: ... +def _nested_get_jagged_dummy(any: Tensor) -> Tensor: ... +def _nested_get_lengths(input: Tensor) -> Tensor: ... +def _nested_get_max_seqlen(input: Tensor) -> Tensor: ... +def _nested_get_min_seqlen(input: Tensor) -> Tensor: ... +def _nested_get_offsets(input: Tensor) -> Tensor: ... +def _nested_get_ragged_idx(input: Tensor) -> _int: ... +def _nested_get_values(input: Tensor) -> Tensor: ... +def _nested_get_values_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nested_tensor_from_mask( + t: Tensor, + mask: Tensor, + mask_check: _bool = True, +) -> Tensor: ... +def _nested_tensor_from_mask_left_aligned(t: Tensor, mask: Tensor) -> _bool: ... +def _nested_tensor_from_tensor_list( + list: tuple[Tensor, ...] | list[Tensor], + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = None, +) -> Tensor: ... +def _nested_tensor_softmax_with_shape( + input: Tensor, + query: Tensor, +) -> Tensor: ... +def _nested_view_from_buffer( + input: Tensor, + nested_size: Tensor, + nested_strides: Tensor, + offsets: Tensor, +) -> Tensor: ... +def _nested_view_from_buffer_copy( + input: Tensor, + nested_size: Tensor, + nested_strides: Tensor, + offsets: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nested_view_from_jagged( + input: Tensor, + offsets: Tensor, + dummy: Tensor, + lengths: Tensor | None = None, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, +) -> Tensor: ... +def _nested_view_from_jagged_copy( + input: Tensor, + offsets: Tensor, + dummy: Tensor, + lengths: Tensor | None = None, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nnpack_available() -> _bool: ... +def _nnpack_spatial_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: _int | SymInt | Sequence[_int | SymInt], + stride: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def _pack_padded_sequence( + input: Tensor, + lengths: Tensor, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def _pad_packed_sequence( + data: Tensor, + batch_sizes: Tensor, + batch_first: _bool, + padding_value: Number | _complex | PySymType, + total_length: _int, +) -> tuple[Tensor, Tensor]: ... +@overload +def _philox_key_fold_in(key: Tensor, data: Tensor) -> Tensor: ... +@overload +def _philox_key_fold_in(key: Tensor, data: _int) -> Tensor: ... +def _philox_key_split(key: Tensor, num_splits: _int) -> Tensor: ... +def _philox_normal_( + input: Tensor, + key: Tensor, + mean: _float = 0, + std: _float = 1, +) -> Tensor: ... +def _philox_uniform_( + input: Tensor, + key: Tensor, + low: _float = 0, + high: _float = 1, +) -> Tensor: ... +def _pin_memory( + input: Tensor, + device: DeviceLikeType | None = None, +) -> Tensor: ... +def _prelu_kernel(input: Tensor, weight: Tensor) -> Tensor: ... +def _print(s: str) -> None: ... +def _propagate_xla_data(input: Tensor, output: Tensor) -> None: ... +def _remove_batch_dim( + input: Tensor, + level: _int, + batch_size: _int | SymInt, + out_dim: _int, +) -> Tensor: ... +def _reshape_alias_copy( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + out: Tensor | None = None, +) -> Tensor: ... +def _reshape_from_tensor(input: Tensor, shape: Tensor) -> Tensor: ... +def _resize_output_( + input: Tensor, + size: Sequence[_int | SymInt], + device: DeviceLikeType | None, +) -> Tensor: ... +def _rowwise_prune( + weight: Tensor, + mask: Tensor, + compressed_indices_dtype: _dtype, +) -> tuple[Tensor, Tensor]: ... +def _safe_softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sample_dirichlet( + input: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +def _saturate_weight_to_fp16(weight: Tensor) -> Tensor: ... +def _scaled_dot_product_attention_math( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + dropout_mask: Tensor | None = None, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _scaled_dot_product_attention_math_for_mps( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + dropout_mask: Tensor | None = None, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _scaled_dot_product_cudnn_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: _bool, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_cudnn_attention: ... +def _scaled_dot_product_efficient_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: _bool, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_efficient_attention: ... +@overload +def _scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + q_descale: Tensor | None, + k_descale: Tensor | None, + v_descale: Tensor | None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention: ... +@overload +def _scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention: ... +def _scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + attn_mask: Tensor | None = None, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention_for_cpu: ... +def _scaled_grouped_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, +) -> Tensor: ... +def _scaled_grouped_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor], + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor], + recipe_b: _size, + swizzle_b: _size, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: _dtype | None = None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _scaled_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _scaled_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor], + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor], + recipe_b: _size, + swizzle_b: _size, + bias: Tensor | None, + out_dtype: _dtype | None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _shape_as_tensor(input: Tensor) -> Tensor: ... +def _sobol_engine_draw( + quasi: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, + dtype: _dtype | None, +) -> tuple[Tensor, Tensor]: ... +def _sobol_engine_ff_( + input: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, +) -> Tensor: ... +def _sobol_engine_initialize_state_( + input: Tensor, + dimension: _int, +) -> Tensor: ... +def _sobol_engine_scramble_( + input: Tensor, + ltm: Tensor, + dimension: _int, +) -> Tensor: ... +def _softmax( + input: Tensor, + dim: _int, + half_to_float: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input_dtype: _dtype, + *, + grad_input: Tensor | None = None, +) -> Tensor: ... +def _sparse_broadcast_to(input: Tensor, size: _size) -> Tensor: ... +def _sparse_broadcast_to_copy( + input: Tensor, + size: _size, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _sparse_csr_prod( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_csr_sum( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_log_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input: Tensor, +) -> Tensor: ... +def _sparse_semi_structured_addmm( + input: Tensor, + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + beta: Number | _complex | PySymType = 1, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_apply( + input: Tensor, + thread_masks: Tensor, +) -> tuple[Tensor, Tensor]: ... +def _sparse_semi_structured_apply_dense( + input: Tensor, + thread_masks: Tensor, +) -> Tensor: ... +def _sparse_semi_structured_linear( + input: Tensor, + weight: Tensor, + meta: Tensor, + *, + bias: Tensor | None = None, + activation: str | None = None, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_mm( + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_tile( + input: Tensor, + algorithm: str = "", + use_cutlass: _bool = True, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _sparse_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input: Tensor, +) -> Tensor: ... +def _sparse_sparse_matmul(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor, *, dtype: _dtype) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor, dim: _int | _size) -> Tensor: ... +@overload +def _sparse_sum( + input: Tensor, + dim: _int | _size, + *, + dtype: _dtype, +) -> Tensor: ... +def _stack( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _standard_gamma( + input: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +def _standard_gamma_grad(input: Tensor, output: Tensor) -> Tensor: ... +def _sync(t: Tensor) -> None: ... +@overload +def _test_autograd_multiple_dispatch(input: Tensor) -> Tensor: ... +@overload +def _test_autograd_multiple_dispatch(input: Tensor, b: _bool) -> Tensor: ... +def _test_autograd_multiple_dispatch_view(input: Tensor) -> Tensor: ... +def _test_autograd_multiple_dispatch_view_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _test_check_tensor(input: Tensor) -> Tensor: ... +def _test_functorch_fallback(input: Tensor, other: Tensor) -> Tensor: ... +def _test_parallel_materialize( + input: Tensor, + num_parallel: _int, + skip_first: _bool = False, +) -> Tensor: ... +def _test_serialization_subcmul( + input: Tensor, + other: Tensor, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +def _to_cpu( + tensors: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +def _to_functional_tensor(t: Tensor) -> Tensor: ... +def _to_sparse_semi_structured(dense: Tensor) -> tuple[Tensor, Tensor]: ... +def _transform_bias_rescale_qkv( + qkv: Tensor, + qkv_bias: Tensor, + num_heads: _int, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _transformer_encoder_layer_fwd( + src: Tensor, + embed_dim: _int, + num_heads: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + use_gelu: _bool, + norm_first: _bool, + eps: _float, + norm_weight_1: Tensor, + norm_bias_1: Tensor, + norm_weight_2: Tensor, + norm_bias_2: Tensor, + ffn_weight_1: Tensor, + ffn_bias_1: Tensor, + ffn_weight_2: Tensor, + ffn_bias_2: Tensor, + mask: Tensor | None = None, + mask_type: _int | None = None, +) -> Tensor: ... +def _trilinear( + i1: Tensor, + i2: Tensor, + i3: Tensor, + expand1: _size, + expand2: _size, + expand3: _size, + sumdim: _size, + unroll_dim: _int = 1, +) -> Tensor: ... +def _triton_multi_head_attention( + query: Tensor, + key: Tensor, + value: Tensor, + embed_dim: _int, + num_head: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + mask: Tensor | None = None, +) -> Tensor: ... +def _triton_scaled_dot_attention( + q: Tensor, + k: Tensor, + v: Tensor, + dropout_p: _float = 0.0, +) -> Tensor: ... +def _unique( + input: Tensor, + sorted: _bool = True, + return_inverse: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _unique2( + input: Tensor, + sorted: _bool = True, + return_inverse: _bool = False, + return_counts: _bool = False, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _unpack_dual( + dual: Tensor, + level: _int, +) -> torch.return_types._unpack_dual: ... +def _unsafe_index( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, +) -> Tensor: ... +def _unsafe_index_put( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def _unsafe_masked_index( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + fill: Number | _complex | PySymType, +) -> Tensor: ... +def _unsafe_masked_index_put_accumulate( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, +) -> Tensor: ... +@overload +def _use_cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, +) -> _bool: ... +@overload +def _use_cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, +) -> _bool: ... +def _use_cudnn_rnn_flatten_weight() -> _bool: ... +@overload +def _use_miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, +) -> _bool: ... +@overload +def _use_miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, +) -> _bool: ... +def _validate_compressed_sparse_indices( + is_crow: _bool, + compressed_idx: Tensor, + plain_idx: Tensor, + cdim: _int, + dim: _int, + nnz: _int, +) -> None: ... +def _validate_sparse_bsc_tensor_args( + ccol_indices: Tensor, + row_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_bsr_tensor_args( + crow_indices: Tensor, + col_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_compressed_tensor_args( + compressed_indices: Tensor, + plain_indices: Tensor, + values: Tensor, + size: _size, + layout: _layout, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_coo_tensor_args( + indices: Tensor, + values: Tensor, + size: _size, + is_coalesced: _bool | None = None, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_csc_tensor_args( + ccol_indices: Tensor, + row_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_csr_tensor_args( + crow_indices: Tensor, + col_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _values_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _weight_int4pack_mm( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScaleAndZeros: Tensor, +) -> Tensor: ... +def _weight_int4pack_mm_for_cpu( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScaleAndZeros: Tensor, +) -> Tensor: ... +def _weight_int4pack_mm_with_scales_and_zeros( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScale: Tensor, + qZeros: Tensor, +) -> Tensor: ... +def _weight_int8pack_mm( + input: Tensor, + mat2: Tensor, + scales: Tensor, +) -> Tensor: ... +def _weight_norm(v: Tensor, g: Tensor, dim: _int = 0) -> Tensor: ... +def _weight_norm_interface( + v: Tensor, + g: Tensor, + dim: _int = 0, +) -> tuple[Tensor, Tensor]: ... +def _wrapped_linear_prepack( + weight: Tensor, + weight_scale: Tensor, + weight_zero_point: Tensor, + bias: Tensor, +) -> Tensor: ... +def _wrapped_quantized_linear_prepacked( + input: Tensor, + input_scale: Tensor, + input_zero_point: Tensor, + packed_weight: Tensor, + output_scale: Tensor, + output_zero_point: Tensor, + out_channel: _int, +) -> Tensor: ... +def abs(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + abs(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the absolute value of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = |\text{input}_{i}| + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.abs(torch.tensor([-1, -2, 3])) + tensor([ 1, 2, 3]) + """ + +def abs_(input: Tensor) -> Tensor: + r""" + abs_(input) -> Tensor + + In-place version of :func:`torch.abs` + """ + +def absolute(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + absolute(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.abs` + """ + +def acos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + acos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arccosine (in radians) of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = \cos^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.3348, -0.5889, 0.2005, -0.1584]) + >>> torch.acos(a) + tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) + """ + +def acos_(input: Tensor) -> Tensor: + r""" + acos_(input) -> Tensor + + In-place version of :func:`torch.acos` + """ + +def acosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + acosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic cosine of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \cosh^{-1}(\text{input}_{i}) + + Note: + The domain of the inverse hyperbolic cosine is `[1, inf)` and values outside this range + will be mapped to ``NaN``, except for `+ INF` for which the output is mapped to `+ INF`. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4).uniform_(1, 2) + >>> a + tensor([ 1.3192, 1.9915, 1.9674, 1.7151 ]) + >>> torch.acosh(a) + tensor([ 0.7791, 1.3120, 1.2979, 1.1341 ]) + """ + +def acosh_(input: Tensor) -> Tensor: + r""" + acosh_(input) -> Tensor + + In-place version of :func:`torch.acosh` + """ + +def adaptive_avg_pool1d(input: Tensor, output_size: _int | _size) -> Tensor: ... +def adaptive_max_pool1d( + input: Tensor, + output_size: _int | _size, +) -> tuple[Tensor, Tensor]: ... +@overload +def add( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def add( + self: Tensor, + alpha: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def add( + self: Tensor, + alpha: Number | _complex | PySymType, + other: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def addbmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addcdiv( + self: Tensor, + value: Number | _complex | PySymType, + tensor1: Tensor, + tensor2: Tensor, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcdiv( + self: Tensor, + value: Number | _complex | PySymType, + tensor1: Tensor, + tensor2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcdiv( + input: Tensor, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcmul( + self: Tensor, + value: Number | _complex | PySymType, + tensor1: Tensor, + tensor2: Tensor, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addcmul( + self: Tensor, + value: Number | _complex | PySymType, + tensor1: Tensor, + tensor2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addcmul( + input: Tensor, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmv( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat: Tensor, + vec: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + input: Tensor, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex | PySymType, + self: Tensor, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex | PySymType, + self: Tensor, + mat: Tensor, + vec: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv_( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addmv_( + input: Tensor, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addmv_( + beta: Number | _complex | PySymType, + self: Tensor, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addr( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + vec1: Tensor, + vec2: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + vec1: Tensor, + vec2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + input: Tensor, + vec1: Tensor, + vec2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex | PySymType, + self: Tensor, + vec1: Tensor, + vec2: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex | PySymType, + self: Tensor, + vec1: Tensor, + vec2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +def adjoint(input: Tensor) -> Tensor: + r""" + adjoint(input: Tensor) -> Tensor + Returns a view of the tensor conjugated and with the last two dimensions transposed. + + ``x.adjoint()`` is equivalent to ``x.transpose(-2, -1).conj()`` for complex tensors and + to ``x.transpose(-2, -1)`` for real tensors. + + Args: + {input} + + Example:: + + >>> x = torch.arange(4, dtype=torch.float) + >>> A = torch.complex(x, x).reshape(2, 2) + >>> A + tensor([[0.+0.j, 1.+1.j], + [2.+2.j, 3.+3.j]]) + >>> A.adjoint() + tensor([[0.-0.j, 2.-2.j], + [1.-1.j, 3.-3.j]]) + >>> (A.adjoint() == A.mH).all() + tensor(True) + """ + +def affine_grid_generator( + theta: Tensor, + size: Sequence[_int | SymInt], + align_corners: _bool, +) -> Tensor: ... +def alias_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.alias`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def all(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +@overload +def all( + input: Tensor, + dim: _size | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +@overload +def all( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +def allclose( + input: Tensor, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, +) -> _bool: + r""" + allclose(input: Tensor, other: Tensor, rtol: float = 1e-05, atol: float = 1e-08, equal_nan: bool = False) -> bool + + This function checks if :attr:`input` and :attr:`other` satisfy the condition: + + .. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other}_i \rvert + + elementwise, for all elements of :attr:`input` and :attr:`other`. The behaviour of this function is analogous to + `numpy.allclose `_ + + Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + atol (float, optional): absolute tolerance. Default: 1e-08 + rtol (float, optional): relative tolerance. Default: 1e-05 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + + Example:: + + >>> torch.allclose(torch.tensor([10000., 1e-07]), torch.tensor([10000.1, 1e-08])) + False + >>> torch.allclose(torch.tensor([10000., 1e-08]), torch.tensor([10000.1, 1e-09])) + True + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')])) + False + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]), equal_nan=True) + True + """ + +def alpha_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def alpha_dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: + r""" + alpha_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.alpha_dropout` + """ + +def amax( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amax(input, dim=None, keepdim=False, *, out=None) -> Tensor + + Returns the maximum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.8177, 1.4878, -0.2491, 0.9130], + [-0.7158, 1.1775, 2.0992, 0.4817], + [-0.0053, 0.0164, -1.3738, -0.0507], + [ 1.9700, 1.1106, -1.0318, -1.0816]]) + >>> torch.amax(a, 1) + tensor([1.4878, 2.0992, 0.0164, 1.9700]) + """ + +def amin( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amin(input, dim=None, keepdim=False, *, out=None) -> Tensor + + Returns the minimum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.6451, -0.4866, 0.2987, -1.3312], + [-0.5744, 1.2980, 1.8397, -0.2713], + [ 0.9128, 0.9214, -1.7268, -0.2995], + [ 0.9023, 0.4853, 0.9075, -1.6165]]) + >>> torch.amin(a, 1) + tensor([-1.3312, -0.5744, -1.7268, -1.6165]) + """ + +def aminmax( + input: Tensor, + *, + dim: _int | None = None, + keepdim: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.aminmax: + r""" + aminmax(input, *, dim=None, keepdim=False, out=None) -> (Tensor min, Tensor max) + + Computes the minimum and maximum values of the :attr:`input` tensor. + + Args: + input (Tensor): + The input tensor + + Keyword Args: + dim (Optional[int]): + The dimension along which to compute the values. If `None`, + computes the values over the entire :attr:`input` tensor. + Default is `None`. + keepdim (bool): + If `True`, the reduced dimensions will be kept in the output + tensor as dimensions with size 1 for broadcasting, otherwise + they will be removed, as if calling (:func:`torch.squeeze`). + Default is `False`. + out (Optional[Tuple[Tensor, Tensor]]): + Optional tensors on which to write the result. Must have the same + shape and dtype as the expected output. + Default is `None`. + + Returns: + A named tuple `(min, max)` containing the minimum and maximum values. + + Raises: + RuntimeError + If any of the dimensions to compute the values over has size 0. + + .. note:: + NaN values are propagated to the output if at least one value is NaN. + + .. seealso:: + :func:`torch.amin` computes just the minimum value + :func:`torch.amax` computes just the maximum value + + Example:: + + >>> torch.aminmax(torch.tensor([1, -3, 5])) + torch.return_types.aminmax( + min=tensor(-3), + max=tensor(5)) + + >>> # aminmax propagates NaNs + >>> torch.aminmax(torch.tensor([1, -3, 5, torch.nan])) + torch.return_types.aminmax( + min=tensor(nan), + max=tensor(nan)) + + >>> t = torch.arange(10).view(2, 5) + >>> t + tensor([[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]]) + >>> t.aminmax(dim=0, keepdim=True) + torch.return_types.aminmax( + min=tensor([[0, 1, 2, 3, 4]]), + max=tensor([[5, 6, 7, 8, 9]])) + """ + +def angle(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + angle(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the element-wise angle (in radians) of the given :attr:`input` tensor. + + .. math:: + \text{out}_{i} = angle(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + .. note:: Starting in PyTorch 1.8, angle returns pi for negative real numbers, + zero for non-negative real numbers, and propagates NaNs. Previously + the function would return zero for all real numbers and not propagate + floating-point NaNs. + + Example:: + + >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159 + tensor([ 135., 135, -45]) + """ + +@overload +def any(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _size | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def arange( + start: Number, + end: Number, + step: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number, + end: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + end: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + end: Number | _complex | PySymType, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number | _complex | PySymType, + end: Number | _complex | PySymType, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number | _complex | PySymType, + end: Number | _complex | PySymType, + step: Number | _complex | PySymType = 1, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +def arccos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arccos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.acos`. + """ + +def arccos_(input: Tensor) -> Tensor: + r""" + arccos_(input) -> Tensor + + In-place version of :func:`torch.arccos` + """ + +def arccosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arccosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.acosh`. + """ + +def arccosh_(input: Tensor) -> Tensor: + r""" + arccosh_(input) -> Tensor + + In-place version of :func:`torch.arccosh` + """ + +def arcsin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arcsin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.asin`. + """ + +def arcsin_(input: Tensor) -> Tensor: + r""" + arcsin_(input) -> Tensor + + In-place version of :func:`torch.arcsin` + """ + +def arcsinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arcsinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.asinh`. + """ + +def arcsinh_(input: Tensor) -> Tensor: + r""" + arcsinh_(input) -> Tensor + + In-place version of :func:`torch.arcsinh` + """ + +def arctan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arctan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.atan`. + """ + +def arctan2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + arctan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + Alias for :func:`torch.atan2`. + """ + +def arctan_(input: Tensor) -> Tensor: + r""" + arctan_(input) -> Tensor + + In-place version of :func:`torch.arctan` + """ + +def arctanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arctanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.atanh`. + """ + +def arctanh_(input: Tensor) -> Tensor: + r""" + arctanh_(input) -> Tensor + + In-place version of :func:`torch.arctanh` + """ + +def argmax( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmax(input) -> LongTensor + + Returns the indices of the maximum value of all elements in the :attr:`input` tensor. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple maximal values then the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a) + tensor(0) + + .. function:: argmax(input, dim, keepdim=False) -> LongTensor + :noindex: + + Returns the indices of the maximum values of a tensor across a dimension. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmax of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a, dim=1) + tensor([ 0, 2, 0, 1]) + """ + +def argmin( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmin(input, dim=None, keepdim=False) -> LongTensor + + Returns the indices of the minimum value(s) of the flattened tensor or along a dimension + + This is the second value returned by :meth:`torch.min`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple minimal values then the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmin of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.1139, 0.2254, -0.1381, 0.3687], + [ 1.0100, -1.1975, -0.0102, -0.4732], + [-0.9240, 0.1207, -0.7506, -1.0213], + [ 1.7809, -1.2960, 0.9384, 0.1438]]) + >>> torch.argmin(a) + tensor(13) + >>> torch.argmin(a, dim=1) + tensor([ 2, 1, 3, 1]) + >>> torch.argmin(a, dim=1, keepdim=True) + tensor([[2], + [1], + [3], + [1]]) + """ + +@overload +def argsort( + input: Tensor, + *, + stable: _bool, + dim: _int = -1, + descending: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +@overload +def argsort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +def argwhere(input: Tensor) -> Tensor: + r""" + argwhere(input) -> Tensor + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + .. note:: + This function is similar to NumPy's `argwhere`. + + When :attr:`input` is on CUDA, this function causes host-device synchronization. + + Args: + {input} + + Example:: + + >>> t = torch.tensor([1, 0, 1]) + >>> torch.argwhere(t) + tensor([[0], + [2]]) + >>> t = torch.tensor([[1, 0, 1], [0, 1, 1]]) + >>> torch.argwhere(t) + tensor([[0, 0], + [0, 2], + [1, 1], + [1, 2]]) + """ + +def as_strided( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided(input, size, stride, storage_offset=None) -> Tensor + + Create a view of an existing `torch.Tensor` :attr:`input` with specified + :attr:`size`, :attr:`stride` and :attr:`storage_offset`. + + .. warning:: + Prefer using other view functions, like :meth:`torch.Tensor.view` or + :meth:`torch.Tensor.expand`, to setting a view's strides manually with + `as_strided`, as this function will throw an error on non-standard Pytorch + backends (that do not have a concept of stride) and the result will depend + on the current layout in memory. The constructed view must only refer to + elements within the Tensor's storage or a runtime error will be thrown. + If the generated view is "overlapped" (with multiple indices referring to + the same element in memory), the behavior of inplace operations on this view + is undefined (and might not throw runtime errors). + + Args: + input (Tensor): the input tensor. + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor. + If ``None``, the storage_offset of the output tensor will match the input tensor. + + Example:: + + >>> x = torch.randn(3, 3) + >>> x + tensor([[ 0.9039, 0.6291, 1.0795], + [ 0.1586, 2.1939, -0.4900], + [-0.1909, -0.7503, 1.9355]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2)) + >>> t + tensor([[0.9039, 1.0795], + [0.6291, 0.1586]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2), 1) + tensor([[0.6291, 0.1586], + [1.0795, 2.1939]]) + """ + +def as_strided_( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided_(input, size, stride, storage_offset=None) -> Tensor + + In-place version of :func:`torch.as_strided` + """ + +def as_strided_copy( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.as_strided`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def as_strided_scatter( + input: Tensor, + src: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided_scatter(input, src, size, stride, storage_offset=None) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` along + the elements corresponding to the result of calling + input.as_strided(size, stride, storage_offset). + + This function returns a tensor with fresh storage; it does not + return a view. + + Args: + input (Tensor): the input tensor. + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + `torch.as_strided(input, size, stride, storage_offset)` + + Example:: + + >>> a = torch.arange(4).reshape(2, 2) + 1 + >>> a + tensor([[1, 2], + [3, 4]]) + >>> b = torch.zeros(3, 3) + >>> b + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> torch.as_strided_scatter(b, a, (2, 2), (1, 2)) + tensor([[1., 3., 2.], + [4., 0., 0.], + [0., 0., 0.]]) + """ + +def as_tensor( + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, +) -> Tensor: + r""" + as_tensor(data: Any, *, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) -> Tensor + + Converts :attr:`data` into a tensor, sharing data and preserving autograd + history if possible. + + If :attr:`data` is already a tensor with the requested dtype and device + then :attr:`data` itself is returned, but if :attr:`data` is a + tensor with a different dtype or device then it's copied as if using + `data.to(dtype=dtype, device=device)`. + + If :attr:`data` is a NumPy array (an ndarray) with the same dtype and device then a + tensor is constructed using :func:`torch.from_numpy`. + + If :attr:`data` is a CuPy array, the returned tensor will be located on the same device as the CuPy array unless + specifically overwritten by :attr:`device` or a default device. The device of the CuPy array is inferred from the + pointer of the array using `cudaPointerGetAttributes` unless :attr:`device` is provided with an explicit device index. + + .. seealso:: + + :func:`torch.tensor` never shares its data and creates a new "leaf tensor" (see :doc:`/notes/autograd`). + + + Args: + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + + + Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a, device=torch.device('cuda')) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([1, 2, 3]) + """ + +def asarray( + obj: Any, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + copy: _bool | None = None, + requires_grad: _bool | None = None, +) -> Tensor: + r""" + asarray(obj: Any, *, dtype: Optional[dtype], device: Optional[DeviceLikeType], copy: Optional[bool] = None, requires_grad: Optional[bool] = None) -> Tensor # noqa: B950 + + Converts :attr:`obj` to a tensor. + + :attr:`obj` can be one of: + + 1. a tensor + 2. a NumPy array or a NumPy scalar + 3. a DLPack capsule + 4. an object that implements Python's buffer protocol + 5. a scalar + 6. a sequence of scalars + + When :attr:`obj` is a tensor, NumPy array, or DLPack capsule the returned tensor will, + by default, have the same requires_grad as :attr:`obj` (defaulting to False), have the + same datatype, be on the same device, and share memory with it. These properties can be + controlled with the :attr:`dtype`, :attr:`device`, :attr:`copy`, and + :attr:`requires_grad` keyword arguments. If the returned tensor is of a different + datatype, on a different device, or a copy is requested then it will not share its + memory with :attr:`obj`. If :attr:`requires_grad` is ``True`` (or ``None``, and + :attr:`obj` was a tensor with requires_grad set), then the returned tensor will require + a gradient, and if :attr:`obj` is also a tensor with an autograd history then the + returned tensor will have the same history. + + When :attr:`obj` is not a tensor, NumPy array, or DLPack capsule but implements Python's + buffer protocol then the buffer is interpreted as an array of bytes grouped according to + the size of the datatype passed to the :attr:`dtype` keyword argument. (If no datatype is + passed then the default floating point datatype is used, instead.) The returned tensor + will have the specified datatype (or default floating point datatype if none is specified) + and, by default, be on the CPU device and share memory with the buffer. + + When :attr:`obj` is a NumPy scalar, the returned tensor will be a 0-dimensional tensor on + the CPU and that doesn't share its memory (i.e. ``copy=True``). By default datatype will + be the PyTorch datatype corresponding to the NumPy's scalar's datatype. + + When :attr:`obj` is none of the above but a scalar, or a sequence of scalars then the + returned tensor will, by default, infer its datatype from the scalar values, be on the + current default device, and not share its memory. + + .. seealso:: + + :func:`torch.tensor` creates a tensor that always copies the data from the input object. + :func:`torch.from_numpy` creates a tensor that always shares memory from NumPy arrays. + :func:`torch.frombuffer` creates a tensor that always shares memory from objects that + implement the buffer protocol. + :func:`torch.from_dlpack` creates a tensor that always shares memory from + DLPack capsules. + + Args: + obj (object): a tensor, NumPy array, DLPack Capsule, object that implements Python's + buffer protocol, scalar, or sequence of scalars. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the datatype of the returned tensor. + Default: ``None``, which causes the datatype of the returned tensor to be + inferred from :attr:`obj`. + copy (bool, optional): controls whether the returned tensor shares memory with :attr:`obj`. + Default: ``None``, which causes the returned tensor to share memory with :attr:`obj` + whenever possible. If ``True`` then the returned tensor does not share its memory. + If ``False`` then the returned tensor shares its memory with :attr:`obj` and an + error is thrown if it cannot. + device (:class:`torch.device`, optional): the device of the returned tensor. + Default: ``None``, which causes the device of :attr:`obj` to be used. Or, if + :attr:`obj` is a Python sequence, the current default device will be used. + requires_grad (bool, optional): whether the returned tensor requires grad. + Default: ``None``, which causes requires_grad for the returned tensor to be + inferred from :attr:`obj`. If ``True``, then the returned tensor will require + a gradient, and if :attr:`obj` is also a tensor with an autograd history then + the returned tensor will have the same history. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> # Shares memory with tensor 'a' + >>> b = torch.asarray(a) + >>> a.data_ptr() == b.data_ptr() + True + >>> # Forces memory copy + >>> c = torch.asarray(a, copy=True) + >>> a.data_ptr() == c.data_ptr() + False + + >>> a = torch.tensor([1., 2., 3.], requires_grad=True) + >>> b = a + 2 + >>> b + tensor([3., 4., 5.], grad_fn=) + >>> # Shares memory with tensor 'b', with no grad + >>> c = torch.asarray(b, requires_grad=False) + >>> c + tensor([3., 4., 5.]) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> d = torch.asarray(b, requires_grad=True) + >>> d + tensor([3., 4., 5.], grad_fn=) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> e = torch.asarray(b) + >>> e + tensor([3., 4., 5.], grad_fn=) + + >>> array = numpy.array([1, 2, 3]) + >>> # Shares memory with array 'array' + >>> t1 = torch.asarray(array) + >>> array.__array_interface__['data'][0] == t1.data_ptr() + True + >>> # Copies memory due to dtype mismatch + >>> t2 = torch.asarray(array, dtype=torch.float32) + >>> array.__array_interface__['data'][0] == t2.data_ptr() + False + + >>> scalar = numpy.float64(0.5) + >>> torch.asarray(scalar) + tensor(0.5000, dtype=torch.float64) + """ + +def asin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + asin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arcsine of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \sin^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5962, 1.4985, -0.4396, 1.4525]) + >>> torch.asin(a) + tensor([-0.6387, nan, -0.4552, nan]) + """ + +def asin_(input: Tensor) -> Tensor: + r""" + asin_(input) -> Tensor + + In-place version of :func:`torch.asin` + """ + +def asinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + asinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic sine of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \sinh^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ]) + >>> torch.asinh(a) + tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ]) + """ + +def asinh_(input: Tensor) -> Tensor: + r""" + asinh_(input) -> Tensor + + In-place version of :func:`torch.asinh` + """ + +def atan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + atan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arctangent of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \tan^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.2341, 0.2539, -0.6256, -0.6448]) + >>> torch.atan(a) + tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) + """ + +def atan2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + atan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Element-wise arctangent of :math:`\text{input}_{i} / \text{other}_{i}` + with consideration of the quadrant. Returns a new tensor with the signed angles + in radians between vector :math:`(\text{other}_{i}, \text{input}_{i})` + and vector :math:`(1, 0)`. (Note that :math:`\text{other}_{i}`, the second + parameter, is the x-coordinate, while :math:`\text{input}_{i}`, the first + parameter, is the y-coordinate.) + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.9041, 0.0196, -0.3108, -2.4423]) + >>> torch.atan2(a, torch.randn(4)) + tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) + """ + +def atan_(input: Tensor) -> Tensor: + r""" + atan_(input) -> Tensor + + In-place version of :func:`torch.atan` + """ + +def atanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + atanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic tangent of the elements of :attr:`input`. + + Note: + The domain of the inverse hyperbolic tangent is `(-1, 1)` and values outside this range + will be mapped to ``NaN``, except for the values `1` and `-1` for which the output is + mapped to `+/-INF` respectively. + + .. math:: + \text{out}_{i} = \tanh^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4).uniform_(-1, 1) + >>> a + tensor([ -0.9385, 0.2968, -0.8591, -0.1871 ]) + >>> torch.atanh(a) + tensor([ -1.7253, 0.3060, -1.2899, -0.1893 ]) + """ + +def atanh_(input: Tensor) -> Tensor: + r""" + atanh_(input) -> Tensor + + In-place version of :func:`torch.atanh` + """ + +def avg_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + ceil_mode: _bool = False, + count_include_pad: _bool = True, +) -> Tensor: ... +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def bartlett_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + bartlett_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Bartlett window function. + + .. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.bartlett_window(L, periodic=True)`` equal to + ``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def bartlett_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + bartlett_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Bartlett window function. + + .. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.bartlett_window(L, periodic=True)`` equal to + ``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +def batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> Tensor: ... +def batch_norm_backward_elemt( + grad_out: Tensor, + input: Tensor, + mean: Tensor, + invstd: Tensor, + weight: Tensor | None, + sum_dy: Tensor, + sum_dy_xmu: Tensor, + count: Tensor, +) -> Tensor: ... +def batch_norm_backward_reduce( + grad_out: Tensor, + input: Tensor, + mean: Tensor, + invstd: Tensor, + weight: Tensor | None, + input_g: _bool, + weight_g: _bool, + bias_g: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def batch_norm_elemt( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + mean: Tensor, + invstd: Tensor, + eps: _float, + *, + out: Tensor | None = None, +) -> Tensor: ... +def batch_norm_gather_stats( + input: Tensor, + mean: Tensor, + invstd: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, + eps: _float, + count: _int, +) -> tuple[Tensor, Tensor]: ... +def batch_norm_gather_stats_with_counts( + input: Tensor, + mean: Tensor, + invstd: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, + eps: _float, + counts: Tensor, +) -> tuple[Tensor, Tensor]: ... +def batch_norm_stats(input: Tensor, eps: _float) -> tuple[Tensor, Tensor]: ... +def batch_norm_update_stats( + input: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, +) -> tuple[Tensor, Tensor]: ... +@overload +def bernoulli( + input: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor + + Draws binary random numbers (0 or 1) from a Bernoulli distribution. + + The :attr:`input` tensor should be a tensor containing probabilities + to be used for drawing the binary random number. + Hence, all values in :attr:`input` have to be in the range: + :math:`0 \leq \text{input}_i \leq 1`. + + The :math:`\text{i}^{th}` element of the output tensor will draw a + value :math:`1` according to the :math:`\text{i}^{th}` probability value given + in :attr:`input`. + + .. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) + + The returned :attr:`out` tensor only has values 0 or 1 and is of the same + shape as :attr:`input`. + + :attr:`out` can have integral ``dtype``, but :attr:`input` must have floating + point ``dtype``. + + Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) + """ + +@overload +def bernoulli( + input: Tensor, + p: _float, + *, + generator: Generator | None = None, +) -> Tensor: + r""" + bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor + + Draws binary random numbers (0 or 1) from a Bernoulli distribution. + + The :attr:`input` tensor should be a tensor containing probabilities + to be used for drawing the binary random number. + Hence, all values in :attr:`input` have to be in the range: + :math:`0 \leq \text{input}_i \leq 1`. + + The :math:`\text{i}^{th}` element of the output tensor will draw a + value :math:`1` according to the :math:`\text{i}^{th}` probability value given + in :attr:`input`. + + .. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) + + The returned :attr:`out` tensor only has values 0 or 1 and is of the same + shape as :attr:`input`. + + :attr:`out` can have integral ``dtype``, but :attr:`input` must have floating + point ``dtype``. + + Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) + """ + +def bilinear( + input1: Tensor, + input2: Tensor, + weight: Tensor, + bias: Tensor | None = None, +) -> Tensor: ... +def binary_cross_entropy_with_logits( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + pos_weight: Tensor | None = None, + reduction: _int = 1, +) -> Tensor: ... +def bincount( + input: Tensor, + weights: Tensor | None = None, + minlength: _int | SymInt = 0, +) -> Tensor: + r""" + bincount(input, weights=None, minlength=0) -> Tensor + + Count the frequency of each value in an array of non-negative ints. + + The number of bins (size 1) is one larger than the largest value in + :attr:`input` unless :attr:`input` is empty, in which case the result is a + tensor of size 0. If :attr:`minlength` is specified, the number of bins is at least + :attr:`minlength` and if :attr:`input` is empty, then the result is tensor of size + :attr:`minlength` filled with zeros. If ``n`` is the value at position ``i``, + ``out[n] += weights[i]`` if :attr:`weights` is specified else + ``out[n] += 1``. + + Note: + This operation may produce nondeterministic gradients when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + Arguments: + input (Tensor): 1-d int tensor + weights (Tensor): optional, weight for each value in the input tensor. + Should be of same size as input tensor. + minlength (int): optional, minimum number of bins. Should be non-negative. + + Returns: + output (Tensor): a tensor of shape ``Size([max(input) + 1])`` if + :attr:`input` is non-empty, else ``Size(0)`` + + Example:: + + >>> input = torch.randint(0, 8, (5,), dtype=torch.int64) + >>> weights = torch.linspace(0, 1, steps=5) + >>> input, weights + (tensor([4, 3, 6, 3, 4]), + tensor([ 0.0000, 0.2500, 0.5000, 0.7500, 1.0000]) + + >>> torch.bincount(input) + tensor([0, 0, 0, 2, 2, 0, 1]) + + >>> input.bincount(weights) + tensor([0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 0.0000, 0.5000]) + """ + +def binomial( + count: Tensor, + prob: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +@overload +def bitwise_and( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_and( + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_and( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_left_shift( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +@overload +def bitwise_left_shift( + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +@overload +def bitwise_left_shift( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +def bitwise_not(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + bitwise_not(input, *, out=None) -> Tensor + + Computes the bitwise NOT of the given input tensor. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical NOT. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_not(torch.tensor([-1, -2, 3], dtype=torch.int8)) + tensor([ 0, 1, -4], dtype=torch.int8) + """ + +@overload +def bitwise_or( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_or( + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_or( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_right_shift( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_right_shift( + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_right_shift( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_xor( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def bitwise_xor( + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def bitwise_xor( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def blackman_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + blackman_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Blackman window function. + + .. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.blackman_window(L, periodic=True)`` equal to + ``torch.blackman_window(L + 1, periodic=False)[:-1]``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def blackman_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + blackman_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Blackman window function. + + .. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.blackman_window(L, periodic=True)`` equal to + ``torch.blackman_window(L + 1, periodic=False)[:-1]``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def bmm( + input: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bmm(input, mat2, *, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored in :attr:`input` + and :attr:`mat2`. + + :attr:`input` and :attr:`mat2` must be 3-D tensors each containing + the same number of matrices. + + If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a + :math:`(b \times m \times p)` tensor, :attr:`out` will be a + :math:`(b \times n \times p)` tensor. + + .. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + + Keyword Args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) + + .. function:: bmm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword Args: + out (Tensor, optional): the output tensor. + """ + +@overload +def bmm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bmm(input, mat2, *, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored in :attr:`input` + and :attr:`mat2`. + + :attr:`input` and :attr:`mat2` must be 3-D tensors each containing + the same number of matrices. + + If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a + :math:`(b \times m \times p)` tensor, :attr:`out` will be a + :math:`(b \times n \times p)` tensor. + + .. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + + Keyword Args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) + + .. function:: bmm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword Args: + out (Tensor, optional): the output tensor. + """ + +def broadcast_to(input: Tensor, size: Sequence[_int | SymInt]) -> Tensor: + r""" + broadcast_to(input, shape) -> Tensor + + Broadcasts :attr:`input` to the shape :attr:`\shape`. + Equivalent to calling ``input.expand(shape)``. See :meth:`~Tensor.expand` for details. + + Args: + input (Tensor): the input tensor. + shape (list, tuple, or :class:`torch.Size`): the new shape. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> torch.broadcast_to(x, (3, 3)) + tensor([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]) + """ + +@overload +def bucketize( + input: Tensor, + boundaries: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + + Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the + boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size + as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that + this behavior is opposite the behavior of + `numpy.digitize `_. + More formally, the returned index satisfies the following rules: + + .. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + + Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + + Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) + """ + +@overload +def bucketize( + self: Number | _complex | PySymType, + boundaries: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, +) -> Tensor: + r""" + bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + + Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the + boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size + as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that + this behavior is opposite the behavior of + `numpy.digitize `_. + More formally, the returned index satisfies the following rules: + + .. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + + Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + + Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) + """ + +def can_cast(from_: _dtype, to: _dtype) -> _bool: + r""" + can_cast(from_, to) -> bool + + Determines if a type conversion is allowed under PyTorch casting rules + described in the type promotion :ref:`documentation `. + + Args: + from\_ (dtype): The original :class:`torch.dtype`. + to (dtype): The target :class:`torch.dtype`. + + Example:: + + >>> torch.can_cast(torch.double, torch.float) + True + >>> torch.can_cast(torch.float, torch.int) + False + """ + +def cat( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cat(tensors, dim=0, *, out=None) -> Tensor + + Concatenates the given sequence of tensors in :attr:`tensors` in the given dimension. + All tensors must either have the same shape (except in the concatenating + dimension) or be a 1-D empty tensor with size ``(0,)``. + + :func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` + and :func:`torch.chunk`. + + :func:`torch.cat` can be best understood via examples. + + .. seealso:: + + :func:`torch.stack` concatenates the given sequence along a new dimension. + + Args: + tensors (sequence of Tensors): Non-empty tensors provided must have the same shape, + except in the cat dimension. + + dim (int, optional): the dimension over which the tensors are concatenated + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 0) + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 1) + tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, + -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, + -0.5790, 0.1497]]) + """ + +def ccol_indices_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def ceil(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + ceil(input, *, out=None) -> Tensor + + Returns a new tensor with the ceil of the elements of :attr:`input`, + the smallest integer greater than or equal to each element. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + .. math:: + \text{out}_{i} = \left\lceil \text{input}_{i} \right\rceil + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.6341, -1.4208, -1.0900, 0.5826]) + >>> torch.ceil(a) + tensor([-0., -1., -1., 1.]) + """ + +def ceil_(input: Tensor) -> Tensor: + r""" + ceil_(input) -> Tensor + + In-place version of :func:`torch.ceil` + """ + +def celu( + input: Tensor, + alpha: Number | _complex | PySymType = 1.0, +) -> Tensor: ... +def celu_( + input: Tensor, + alpha: Number | _complex | PySymType = 1.0, +) -> Tensor: ... +def channel_shuffle(input: Tensor, groups: _int | SymInt) -> Tensor: ... +def cholesky_inverse( + input: Tensor, + upper: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cholesky_inverse(L, upper=False, *, out=None) -> Tensor + + Computes the inverse of a complex Hermitian or real symmetric + positive-definite matrix given its Cholesky decomposition. + + Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, + and :math:`L` its Cholesky decomposition such that: + + .. math:: + + A = LL^{\text{H}} + + where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, + and the transpose when :math:`L` is real-valued. + + Computes the inverse matrix :math:`A^{-1}`. + + Supports input of float, double, cfloat and cdouble dtypes. + Also supports batches of matrices, and if :math:`A` is a batch of matrices + then the output has the same batch dimensions. + + Args: + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False`` + + Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + + Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> torch.cholesky_inverse(L) + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + >>> A.inverse() + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> torch.dist(torch.inverse(A), torch.cholesky_inverse(L)) + tensor(5.6358e-7) + """ + +def cholesky_solve( + input: Tensor, + input2: Tensor, + upper: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cholesky_solve(B, L, upper=False, *, out=None) -> Tensor + + Computes the solution of a system of linear equations with complex Hermitian + or real symmetric positive-definite lhs given its Cholesky decomposition. + + Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, + and :math:`L` its Cholesky decomposition such that: + + .. math:: + + A = LL^{\text{H}} + + where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, + and the transpose when :math:`L` is real-valued. + + Returns the solution :math:`X` of the following linear system: + + .. math:: + + AX = B + + Supports inputs of float, double, cfloat and cdouble dtypes. + Also supports batches of matrices, and if :math:`A` or :math:`B` is a batch of matrices + then the output has the same batch dimensions. + + Args: + B (Tensor): right-hand side tensor of shape `(*, n, k)` + where :math:`*` is zero or more batch dimensions + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False``. + + Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + + Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> B = torch.randn(3, 2) + >>> torch.cholesky_solve(B, L) + tensor([[ -8.1625, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + >>> A.inverse() @ B + tensor([[ -8.1626, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> B = torch.randn(2, 1, dtype=torch.complex64) + >>> X = torch.cholesky_solve(B, L) + >>> torch.dist(X, A.inverse() @ B) + tensor(1.6881e-5) + """ + +def choose_qparams_optimized( + input: Tensor, + numel: _int, + n_bins: _int, + ratio: _float, + bit_width: _int, +) -> tuple[Tensor, Tensor]: ... +def chunk(input: Tensor, chunks: _int, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + chunk(input: Tensor, chunks: int, dim: int = 0) -> Tuple[Tensor, ...] + + Attempts to split a tensor into the specified number of chunks. Each chunk is a view of + the input tensor. + + + .. note:: + + This function may return fewer than the specified number of chunks! + + .. seealso:: + + :func:`torch.tensor_split` a function that always returns exactly the specified number of chunks + + If the tensor size along the given dimension :attr:`dim` is divisible by :attr:`chunks`, + all returned chunks will be the same size. + If the tensor size along the given dimension :attr:`dim` is not divisible by :attr:`chunks`, + all returned chunks will be the same size, except the last one. + If such division is not possible, this function may return fewer + than the specified number of chunks. + + Arguments: + input (Tensor): the tensor to split + chunks (int): number of chunks to return + dim (int): dimension along which to split the tensor + + Example: + >>> torch.arange(11).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10])) + >>> torch.arange(12).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10, 11])) + >>> torch.arange(13).chunk(6) + (tensor([0, 1, 2]), + tensor([3, 4, 5]), + tensor([6, 7, 8]), + tensor([ 9, 10, 11]), + tensor([12])) + """ + +@overload +def clamp( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clamp(input, min=None, max=None, *, out=None) -> Tensor + + Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. + Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + + .. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + + If :attr:`min` is ``None``, there is no lower bound. + Or, if :attr:`max` is ``None`` there is no upper bound. + + + .. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + + Args: + input (Tensor): the input tensor. + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + """ + +@overload +def clamp( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clamp(input, min=None, max=None, *, out=None) -> Tensor + + Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. + Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + + .. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + + If :attr:`min` is ``None``, there is no lower bound. + Or, if :attr:`max` is ``None`` there is no upper bound. + + + .. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + + Args: + input (Tensor): the input tensor. + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + """ + +@overload +def clamp_( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, +) -> Tensor: + r""" + clamp_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clamp` + """ + +@overload +def clamp_( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, +) -> Tensor: + r""" + clamp_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clamp` + """ + +@overload +def clamp_max( + input: Tensor, + max: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max( + input: Tensor, + max: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Tensor) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Number | _complex | PySymType) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Tensor) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Number | _complex | PySymType) -> Tensor: ... +@overload +def clip( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clip(input, min=None, max=None, *, out=None) -> Tensor + + Alias for :func:`torch.clamp`. + """ + +@overload +def clip( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clip(input, min=None, max=None, *, out=None) -> Tensor + + Alias for :func:`torch.clamp`. + """ + +@overload +def clip_( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, +) -> Tensor: + r""" + clip_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clip` + """ + +@overload +def clip_( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, +) -> Tensor: + r""" + clip_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clip` + """ + +def clone( + input: Tensor, + *, + memory_format: memory_format | None = None, +) -> Tensor: + r""" + clone(input, *, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of :attr:`input`. + + .. note:: + + This function is differentiable, so gradients will flow back from the + result of this operation to :attr:`input`. To create a tensor without an + autograd relationship to :attr:`input` see :meth:`~Tensor.detach`. + + In addition, when ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense (contiguous) format. + + Args: + input (Tensor): the input tensor. + + Keyword args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned tensor. Default: ``torch.preserve_format``. + """ + +def col_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.col_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def column_stack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + column_stack(tensors, *, out=None) -> Tensor + + Creates a new tensor by horizontally stacking the tensors in :attr:`tensors`. + + Equivalent to ``torch.hstack(tensors)``, except each zero or one dimensional tensor ``t`` + in :attr:`tensors` is first reshaped into a ``(t.numel(), 1)`` column before being stacked horizontally. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.column_stack((a, b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + >>> a = torch.arange(5) + >>> b = torch.arange(10).reshape(5, 2) + >>> torch.column_stack((a, b, b)) + tensor([[0, 0, 1, 0, 1], + [1, 2, 3, 2, 3], + [2, 4, 5, 4, 5], + [3, 6, 7, 6, 7], + [4, 8, 9, 8, 9]]) + """ + +def combinations( + input: Tensor, + r: _int = 2, + with_replacement: _bool = False, +) -> Tensor: + r""" + combinations(input: Tensor, r: int = 2, with_replacement: bool = False) -> seq + + Compute combinations of length :math:`r` of the given tensor. The behavior is similar to + python's `itertools.combinations` when `with_replacement` is set to `False`, and + `itertools.combinations_with_replacement` when `with_replacement` is set to `True`. + + Arguments: + input (Tensor): 1D vector. + r (int, optional): number of elements to combine + with_replacement (bool, optional): whether to allow duplication in combination + + Returns: + Tensor: A tensor equivalent to converting all the input tensors into lists, do + `itertools.combinations` or `itertools.combinations_with_replacement` on these + lists, and finally convert the resulting list into tensor. + + Example:: + + >>> a = [1, 2, 3] + >>> list(itertools.combinations(a, r=2)) + [(1, 2), (1, 3), (2, 3)] + >>> list(itertools.combinations(a, r=3)) + [(1, 2, 3)] + >>> list(itertools.combinations_with_replacement(a, r=2)) + [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] + >>> tensor_a = torch.tensor(a) + >>> torch.combinations(tensor_a) + tensor([[1, 2], + [1, 3], + [2, 3]]) + >>> torch.combinations(tensor_a, r=3) + tensor([[1, 2, 3]]) + >>> torch.combinations(tensor_a, with_replacement=True) + tensor([[1, 1], + [1, 2], + [1, 3], + [2, 2], + [2, 3], + [3, 3]]) + """ + +def complex( + real: Tensor, + imag: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + complex(real, imag, *, out=None) -> Tensor + + Constructs a complex tensor with its real part equal to :attr:`real` and its + imaginary part equal to :attr:`imag`. + + Args: + real (Tensor): The real part of the complex tensor. Must be half, float or double. + imag (Tensor): The imaginary part of the complex tensor. Must be same dtype + as :attr:`real`. + + Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + + Example:: + + >>> real = torch.tensor([1, 2], dtype=torch.float32) + >>> imag = torch.tensor([3, 4], dtype=torch.float32) + >>> z = torch.complex(real, imag) + >>> z + tensor([(1.+3.j), (2.+4.j)]) + >>> z.dtype + torch.complex64 + """ + +def concat( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concat(tensors, dim=0, *, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +def concatenate( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concatenate(tensors, axis=0, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +def conj(input: Tensor) -> Tensor: + r""" + conj(input) -> Tensor + + Returns a view of :attr:`input` with a flipped conjugate bit. If :attr:`input` has a non-complex dtype, + this function just returns :attr:`input`. + + .. note:: + :func:`torch.conj` performs a lazy conjugation, but the actual conjugated tensor can be materialized + at any time using :func:`torch.resolve_conj`. + + .. warning:: In the future, :func:`torch.conj` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> x.is_conj() + False + >>> y = torch.conj(x) + >>> y.is_conj() + True + """ + +def conj_physical(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + conj_physical(input, *, out=None) -> Tensor + + Computes the element-wise conjugate of the given :attr:`input` tensor. + If :attr:`input` has a non-complex dtype, this function just returns :attr:`input`. + + .. note:: + This performs the conjugate operation regardless of the fact conjugate bit is set or not. + + .. warning:: In the future, :func:`torch.conj_physical` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + + .. math:: + \text{out}_{i} = conj(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.conj_physical(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])) + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + """ + +def conj_physical_(input: Tensor) -> Tensor: + r""" + conj_physical_(input) -> Tensor + + In-place version of :func:`torch.conj_physical` + """ + +def constant_pad_nd( + input: Tensor, + pad: Sequence[_int | SymInt], + value: Number | _complex | PySymType = 0, +) -> Tensor: ... +@overload +def conv1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +def conv_tbc( + input: Tensor, + weight: Tensor, + bias: Tensor, + pad: _int = 0, +) -> Tensor: ... +def conv_transpose1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def conv_transpose2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def conv_transpose3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +@overload +def copysign( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + copysign(input, other, *, out=None) -> Tensor + + Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + + .. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} + + + Supports :ref:`broadcasting to a common shape `, + and integer and float inputs. + + Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + + .. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + """ + +@overload +def copysign( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + copysign(input, other, *, out=None) -> Tensor + + Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + + .. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} + + + Supports :ref:`broadcasting to a common shape `, + and integer and float inputs. + + Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + + .. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + """ + +def corrcoef(input: Tensor) -> Tensor: + r""" + corrcoef(input) -> Tensor + + Estimates the Pearson product-moment correlation coefficient matrix of the variables given by the :attr:`input` matrix, + where rows are the variables and columns are the observations. + + .. note:: + + The correlation coefficient matrix R is computed using the covariance matrix C as given by + :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }` + + .. note:: + + Due to floating point rounding, the resulting array may not be Hermitian and its diagonal elements may not be 1. + The real and imaginary values are clipped to the interval [-1, 1] in an attempt to improve this situation. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Returns: + (Tensor) The correlation coefficient matrix of the variables. + + .. seealso:: + + :func:`torch.cov` covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 1, 2], [2, 1, 0]]) + >>> torch.corrcoef(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> x = torch.randn(2, 4) + >>> x + tensor([[-0.2678, -0.0908, -0.3766, 0.2780], + [-0.5812, 0.1535, 0.2387, 0.2350]]) + >>> torch.corrcoef(x) + tensor([[1.0000, 0.3582], + [0.3582, 1.0000]]) + >>> torch.corrcoef(x[0]) + tensor(1.) + """ + +def cos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + cos(input, *, out=None) -> Tensor + + Returns a new tensor with the cosine of the elements of :attr:`input` given in radians. + + .. math:: + \text{out}_{i} = \cos(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 1.4309, 1.2706, -0.8562, 0.9796]) + >>> torch.cos(a) + tensor([ 0.1395, 0.2957, 0.6553, 0.5574]) + """ + +def cos_(input: Tensor) -> Tensor: + r""" + cos_(input) -> Tensor + + In-place version of :func:`torch.cos` + """ + +def cosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + cosh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic cosine of the elements of + :attr:`input`. + + .. math:: + \text{out}_{i} = \cosh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1632, 1.1835, -0.6979, -0.7325]) + >>> torch.cosh(a) + tensor([ 1.0133, 1.7860, 1.2536, 1.2805]) + """ + +def cosh_(input: Tensor) -> Tensor: + r""" + cosh_(input) -> Tensor + + In-place version of :func:`torch.cosh` + """ + +def cosine_embedding_loss( + input1: Tensor, + input2: Tensor, + target: Tensor, + margin: _float = 0.0, + reduction: _int = 1, +) -> Tensor: ... +def cosine_similarity( + x1: Tensor, + x2: Tensor, + dim: _int = 1, + eps: _float = 1e-08, +) -> Tensor: ... +@overload +def count_nonzero(input: Tensor, dim: _int | None = None) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +@overload +def count_nonzero(input: Tensor, dim: _size) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +def cov( + input: Tensor, + *, + correction: _int = 1, + fweights: Tensor | None = None, + aweights: Tensor | None = None, +) -> Tensor: + r""" + cov(input, *, correction=1, fweights=None, aweights=None) -> Tensor + + Estimates the covariance matrix of the variables given by the :attr:`input` matrix, where rows are + the variables and columns are the observations. + + A covariance matrix is a square matrix giving the covariance of each pair of variables. The diagonal contains + the variance of each variable (covariance of a variable with itself). By definition, if :attr:`input` represents + a single variable (Scalar or 1D) then its variance is returned. + + The sample covariance of the variables :math:`x` and :math:`y` is given by: + + .. math:: + \text{cov}(x,y) = \frac{\sum^{N}_{i = 1}(x_{i} - \bar{x})(y_{i} - \bar{y})}{\max(0,~N~-~\delta N)} + + where :math:`\bar{x}` and :math:`\bar{y}` are the simple means of the :math:`x` and :math:`y` respectively, and + :math:`\delta N` is the :attr:`correction`. + + If :attr:`fweights` and/or :attr:`aweights` are provided, the weighted covariance + is calculated, which is given by: + + .. math:: + \text{cov}_w(x,y) = \frac{\sum^{N}_{i = 1}w_i(x_{i} - \mu_x^*)(y_{i} - \mu_y^*)} + {\max(0,~\sum^{N}_{i = 1}w_i~-~\frac{\sum^{N}_{i = 1}w_ia_i}{\sum^{N}_{i = 1}w_i}~\delta N)} + + where :math:`w` denotes :attr:`fweights` or :attr:`aweights` (``f`` and ``a`` for brevity) based on whichever is + provided, or :math:`w = f \times a` if both are provided, and + :math:`\mu_x^* = \frac{\sum^{N}_{i = 1}w_ix_{i} }{\sum^{N}_{i = 1}w_i}` is the weighted mean of the variable. If not + provided, ``f`` and/or ``a`` can be seen as a :math:`\mathbb{1}` vector of appropriate size. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Keyword Args: + correction (int, optional): difference between the sample size and sample degrees of freedom. + Defaults to Bessel's correction, ``correction = 1`` which returns the unbiased estimate, + even if both :attr:`fweights` and :attr:`aweights` are specified. ``correction = 0`` + will return the simple average. Defaults to ``1``. + fweights (tensor, optional): A Scalar or 1D tensor of observation vector frequencies representing the number of + times each observation should be repeated. Its numel must equal the number of columns of :attr:`input`. + Must have integral dtype. Ignored if ``None``. Defaults to ``None``. + aweights (tensor, optional): A Scalar or 1D array of observation vector weights. + These relative weights are typically large for observations considered "important" and smaller for + observations considered less "important". Its numel must equal the number of columns of :attr:`input`. + Must have floating point dtype. Ignored if ``None``. Defaults to ``None``. + + Returns: + (Tensor) The covariance matrix of the variables. + + .. seealso:: + + :func:`torch.corrcoef` normalized covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 2], [1, 1], [2, 0]]).T + >>> x + tensor([[0, 1, 2], + [2, 1, 0]]) + >>> torch.cov(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> torch.cov(x, correction=0) + tensor([[ 0.6667, -0.6667], + [-0.6667, 0.6667]]) + >>> fw = torch.randint(1, 10, (3,)) + >>> fw + tensor([1, 6, 9]) + >>> aw = torch.rand(3) + >>> aw + tensor([0.4282, 0.0255, 0.4144]) + >>> torch.cov(x, fweights=fw, aweights=aw) + tensor([[ 0.4169, -0.4169], + [-0.4169, 0.4169]]) + """ + +def cross( + input: Tensor, + other: Tensor, + dim: _int | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cross(input, other, dim=None, *, out=None) -> Tensor + + + Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` + and :attr:`other`. + + Supports input of float, double, cfloat and cdouble dtypes. Also supports batches + of vectors, for which it computes the product along the dimension :attr:`dim`. + In this case, the output has the same batch dimensions as the inputs. + + .. warning:: + If :attr:`dim` is not given, it defaults to the first dimension found + with the size 3. Note that this might be unexpected. + + This behavior is deprecated and will be changed to match that of :func:`torch.linalg.cross` + in a future release. + + .. seealso:: + :func:`torch.linalg.cross` which has dim=-1 as default. + + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + dim (int, optional): the dimension to take the cross-product in. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 3) + >>> a + tensor([[-0.3956, 1.1455, 1.6895], + [-0.5849, 1.3672, 0.3599], + [-1.1626, 0.7180, -0.0521], + [-0.1339, 0.9902, -2.0225]]) + >>> b = torch.randn(4, 3) + >>> b + tensor([[-0.0257, -1.4725, -1.2251], + [-1.1479, -0.7005, -1.9757], + [-1.3904, 0.3726, -1.1836], + [-0.9688, -0.7153, 0.2159]]) + >>> torch.cross(a, b, dim=1) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + >>> torch.cross(a, b) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + """ + +def crow_indices_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.crow_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +def cudnn_affine_grid_generator( + theta: Tensor, + N: _int, + C: _int, + H: _int, + W: _int, +) -> Tensor: ... +def cudnn_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + exponential_average_factor: _float, + epsilon: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def cudnn_convolution( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + allow_tf32: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def cudnn_convolution_add_relu( + input: Tensor, + weight: Tensor, + z: Tensor, + alpha: Number | _complex | PySymType | None, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def cudnn_convolution_relu( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def cudnn_convolution_transpose( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + allow_tf32: _bool, +) -> Tensor: ... +def cudnn_grid_sampler(input: Tensor, grid: Tensor) -> Tensor: ... +def cudnn_is_acceptable(input: Tensor) -> _bool: ... +def cummax( + input: Tensor, + dim: _int, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummax: + r""" + cummax(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = max(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284, + 1.9946, -0.8209]) + >>> torch.cummax(a, dim=0) + torch.return_types.cummax( + values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696, + 1.9946, 1.9946]), + indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8])) + """ + +def cummin( + input: Tensor, + dim: _int, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummin: + r""" + cummin(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = min(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762, + 0.9165, 1.6684]) + >>> torch.cummin(a, dim=0) + torch.return_types.cummin( + values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298, + -1.3298, -1.3298]), + indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4])) + """ + +def cumprod( + input: Tensor, + dim: _int, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumprod(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative product of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 \times x_2\times x_3\times \dots \times x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126, + -0.2129, -0.4206, 0.1968]) + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065, + 0.0014, -0.0006, -0.0001]) + + >>> a[5] = 0.0 + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000, + 0.0000, -0.0000, -0.0000]) + """ + +def cumsum( + input: Tensor, + dim: _int, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumsum(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative sum of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 + x_2 + x_3 + \dots + x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(1, 20, (10,)) + >>> a + tensor([13, 7, 3, 10, 13, 3, 15, 10, 9, 10]) + >>> torch.cumsum(a, dim=0) + tensor([13, 20, 23, 33, 46, 49, 64, 74, 83, 93]) + """ + +@overload +def cumulative_trapezoid(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Cumulatively computes the `trapezoidal rule `_ + along :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. + + For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` + and this function is that, :func:`torch.trapezoid` returns a value for each integration, + where as this function returns a cumulative value for every spacing within the integration. This + is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) + """ + +@overload +def cumulative_trapezoid( + y: Tensor, + *, + dx: Number | _complex | PySymType = 1, + dim: _int = -1, +) -> Tensor: + r""" + cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Cumulatively computes the `trapezoidal rule `_ + along :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. + + For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` + and this function is that, :func:`torch.trapezoid` returns a value for each integration, + where as this function returns a cumulative value for every spacing within the integration. This + is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) + """ + +def deg2rad(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + deg2rad(input, *, out=None) -> Tensor + + Returns a new tensor with each of the elements of :attr:`input` + converted from angles in degrees to radians. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([[180.0, -180.0], [360.0, -360.0], [90.0, -90.0]]) + >>> torch.deg2rad(a) + tensor([[ 3.1416, -3.1416], + [ 6.2832, -6.2832], + [ 1.5708, -1.5708]]) + """ + +def deg2rad_(input: Tensor) -> Tensor: + r""" + deg2rad_(input) -> Tensor + + In-place version of :func:`torch.deg2rad` + """ + +@overload +def dequantize(input: Tensor) -> Tensor: + r""" + dequantize(tensor) -> Tensor + + Returns an fp32 Tensor by dequantizing a quantized Tensor + + Args: + tensor (Tensor): A quantized Tensor + + .. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + + Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + + Args: + tensors (sequence of Tensors): A list of quantized Tensors + """ + +@overload +def dequantize( + tensors: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + dequantize(tensor) -> Tensor + + Returns an fp32 Tensor by dequantizing a quantized Tensor + + Args: + tensor (Tensor): A quantized Tensor + + .. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + + Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + + Args: + tensors (sequence of Tensors): A list of quantized Tensors + """ + +def det(input: Tensor) -> Tensor: + r""" + det(input) -> Tensor + + Alias for :func:`torch.linalg.det` + """ + +def detach(input: Tensor) -> Tensor: ... +def detach_(input: Tensor) -> Tensor: + r""" + detach_(input) -> Tensor + + In-place version of :func:`torch.detach` + """ + +def detach_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.detach`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def diag( + input: Tensor, + diagonal: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + diag(input, diagonal=0, *, out=None) -> Tensor + + - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. + - If :attr:`input` is a matrix (2-D tensor), then returns a 1-D tensor with + the diagonal elements of :attr:`input`. + + The argument :attr:`diagonal` controls which diagonal to consider: + + - If :attr:`diagonal` = 0, it is the main diagonal. + - If :attr:`diagonal` > 0, it is above the main diagonal. + - If :attr:`diagonal` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.diagonal` always returns the diagonal of its input. + + :func:`torch.diagflat` always constructs a tensor with diagonal elements + specified by the input. + + Examples: + + Get the square matrix where the input vector is the diagonal:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.5950,-0.0872, 2.3298]) + >>> torch.diag(a) + tensor([[ 0.5950, 0.0000, 0.0000], + [ 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 2.3298]]) + >>> torch.diag(a, 1) + tensor([[ 0.0000, 0.5950, 0.0000, 0.0000], + [ 0.0000, 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 0.0000, 2.3298], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + Get the k-th diagonal of a given matrix:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-0.4264, 0.0255,-0.1064], + [ 0.8795,-0.2429, 0.1374], + [ 0.1029,-0.6482,-1.6300]]) + >>> torch.diag(a, 0) + tensor([-0.4264,-0.2429,-1.6300]) + >>> torch.diag(a, 1) + tensor([ 0.0255, 0.1374]) + """ + +def diag_embed( + input: Tensor, + offset: _int = 0, + dim1: _int = -2, + dim2: _int = -1, +) -> Tensor: + r""" + diag_embed(input, offset=0, dim1=-2, dim2=-1) -> Tensor + + Creates a tensor whose diagonals of certain 2D planes (specified by + :attr:`dim1` and :attr:`dim2`) are filled by :attr:`input`. + To facilitate creating batched diagonal matrices, the 2D planes formed by + the last two dimensions of the returned tensor are chosen by default. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + The size of the new matrix will be calculated to make the specified diagonal + of the size of the last input dimension. + Note that for :attr:`offset` other than :math:`0`, the order of :attr:`dim1` + and :attr:`dim2` matters. Exchanging them is equivalent to changing the + sign of :attr:`offset`. + + Applying :meth:`torch.diagonal` to the output of this function with + the same arguments yields a matrix identical to input. However, + :meth:`torch.diagonal` has different default dimensions, so those + need to be explicitly specified. + + Args: + input (Tensor): the input tensor. Must be at least 1-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: -2. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: -1. + + Example:: + + >>> a = torch.randn(2, 3) + >>> torch.diag_embed(a) + tensor([[[ 1.5410, 0.0000, 0.0000], + [ 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -2.1788]], + + [[ 0.5684, 0.0000, 0.0000], + [ 0.0000, -1.0845, 0.0000], + [ 0.0000, 0.0000, -1.3986]]]) + + >>> torch.diag_embed(a, offset=1, dim1=0, dim2=2) + tensor([[[ 0.0000, 1.5410, 0.0000, 0.0000], + [ 0.0000, 0.5684, 0.0000, 0.0000]], + + [[ 0.0000, 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -1.0845, 0.0000]], + + [[ 0.0000, 0.0000, 0.0000, -2.1788], + [ 0.0000, 0.0000, 0.0000, -1.3986]], + + [[ 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000]]]) + """ + +def diagflat(input: Tensor, offset: _int = 0) -> Tensor: + r""" + diagflat(input, offset=0) -> Tensor + + - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. + - If :attr:`input` is a tensor with more than one dimension, then returns a + 2-D tensor with diagonal elements equal to a flattened :attr:`input`. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. + offset (int, optional): the diagonal to consider. Default: 0 (main + diagonal). + + Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([-0.2956, -0.9068, 0.1695]) + >>> torch.diagflat(a) + tensor([[-0.2956, 0.0000, 0.0000], + [ 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.1695]]) + >>> torch.diagflat(a, 1) + tensor([[ 0.0000, -0.2956, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.1695], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + >>> a = torch.randn(2, 2) + >>> a + tensor([[ 0.2094, -0.3018], + [-0.1516, 1.9342]]) + >>> torch.diagflat(a) + tensor([[ 0.2094, 0.0000, 0.0000, 0.0000], + [ 0.0000, -0.3018, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.1516, 0.0000], + [ 0.0000, 0.0000, 0.0000, 1.9342]]) + """ + +def diagonal( + input: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, +) -> Tensor: + r""" + diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor + + Returns a partial view of :attr:`input` with the its diagonal elements + with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension + at the end of the shape. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Applying :meth:`torch.diag_embed` to the output of this function with + the same arguments yields a diagonal matrix with the diagonal entries + of the input. However, :meth:`torch.diag_embed` has different default + dimensions, so those need to be explicitly specified. + + Args: + input (Tensor): the input tensor. Must be at least 2-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + + .. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1. + + Examples:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0854, 1.1431, -0.1752], + [ 0.8536, -0.0905, 0.0360], + [ 0.6927, -0.3735, -0.4945]]) + + + >>> torch.diagonal(a) + tensor([-1.0854, -0.0905, -0.4945]) + + + >>> torch.diagonal(a, 1) + tensor([ 1.1431, 0.0360]) + + >>> b = torch.randn(2, 5) + >>> b + tensor([[-1.7948, -1.2731, -0.3181, 2.0200, -1.6745], + [ 1.8262, -1.5049, 0.4114, 1.0704, -1.2607]]) + + >>> torch.diagonal(b, 1, 1, 0) + tensor([1.8262]) + + >>> x = torch.randn(2, 5, 4, 2) + >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2) + tensor([[[-1.2631, 0.3755, -1.5977, -1.8172], + [-1.1065, 1.0401, -0.2235, -0.7938]], + + [[-1.7325, -0.3081, 0.6166, 0.2335], + [ 1.0500, 0.7336, -0.3836, -1.1015]]]) + """ + +def diagonal_copy( + input: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.diagonal`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def diagonal_scatter( + input: Tensor, + src: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, +) -> Tensor: + r""" + diagonal_scatter(input, src, offset=0, dim1=0, dim2=1) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` along + the diagonal elements of :attr:`input`, with respect to :attr:`dim1` + and :attr:`dim2`. + + This function returns a tensor with fresh storage; it does not + return a view. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. Must be at least 2-dimensional. + src (Tensor): the tensor to embed into :attr:`input`. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.diagonal(input, offset, dim1, dim2)`` + + Examples:: + + >>> a = torch.zeros(3, 3) + >>> a + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + + >>> torch.diagonal_scatter(a, torch.ones(3), 0) + tensor([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + + >>> torch.diagonal_scatter(a, torch.ones(2), 1) + tensor([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) + """ + +def diff( + input: Tensor, + n: _int = 1, + dim: _int = -1, + prepend: Tensor | None = None, + append: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + diff(input, n=1, dim=-1, prepend=None, append=None) -> Tensor + + Computes the n-th forward difference along the given dimension. + + The first-order differences are given by `out[i] = input[i + 1] - input[i]`. Higher-order + differences are calculated by using :func:`torch.diff` recursively. + + Args: + input (Tensor): the tensor to compute the differences on + n (int, optional): the number of times to recursively compute the difference + dim (int, optional): the dimension to compute the difference along. + Default is the last dimension. + prepend, append (Tensor, optional): values to prepend or append to + :attr:`input` along :attr:`dim` before computing the difference. + Their dimensions must be equivalent to that of input, and their shapes + must match input's shape except on :attr:`dim`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 3, 2]) + >>> torch.diff(a) + tensor([ 2, -1]) + >>> b = torch.tensor([4, 5]) + >>> torch.diff(a, append=b) + tensor([ 2, -1, 2, 1]) + >>> c = torch.tensor([[1, 2, 3], [3, 4, 5]]) + >>> torch.diff(c, dim=0) + tensor([[2, 2, 2]]) + >>> torch.diff(c, dim=1) + tensor([[1, 1], + [1, 1]]) + """ + +def digamma(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + digamma(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.digamma`. + """ + +def dist( + input: Tensor, + other: Tensor, + p: Number | _complex | PySymType = 2, +) -> Tensor: + r""" + dist(input, other, p=2) -> Tensor + + Returns the p-norm of (:attr:`input` - :attr:`other`) + + The shapes of :attr:`input` and :attr:`other` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + other (Tensor): the Right-hand-side input tensor + p (float, optional): the norm to be computed + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([-1.5393, -0.8675, 0.5916, 1.6321]) + >>> y = torch.randn(4) + >>> y + tensor([ 0.0967, -1.0511, 0.6295, 0.8360]) + >>> torch.dist(x, y, 3.5) + tensor(1.6727) + >>> torch.dist(x, y, 3) + tensor(1.6973) + >>> torch.dist(x, y, 0) + tensor(4.) + >>> torch.dist(x, y, 1) + tensor(2.6537) + """ + +def div( + input: Tensor | Number, + other: Tensor | Number, + *, + rounding_mode: str | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + div(input, other, *, rounding_mode=None, out=None) -> Tensor + + Divides each element of the input ``input`` by the corresponding element of + :attr:`other`. + + .. math:: + \text{out}_i = \frac{\text{input}_i}{\text{other}_i} + + .. note:: + By default, this performs a "true" division like Python 3. + See the :attr:`rounding_mode` argument for floor division. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + Always promotes integer types to the default scalar type. + + Args: + input (Tensor): the dividend + other (Tensor or Number): the divisor + + Keyword args: + rounding_mode (str, optional): Type of rounding applied to the result: + + * None - default behavior. Performs no rounding and, if both :attr:`input` and + :attr:`other` are integer types, promotes the inputs to the default scalar type. + Equivalent to true division in Python (the ``/`` operator) and NumPy's ``np.true_divide``. + * ``"trunc"`` - rounds the results of the division towards zero. + Equivalent to C-style integer division. + * ``"floor"`` - rounds the results of the division down. + Equivalent to floor division in Python (the ``//`` operator) and NumPy's ``np.floor_divide``. + + out (Tensor, optional): the output tensor. + + Examples:: + + >>> x = torch.tensor([ 0.3810, 1.2774, -0.2972, -0.3719, 0.4637]) + >>> torch.div(x, 0.5) + tensor([ 0.7620, 2.5548, -0.5944, -0.7438, 0.9274]) + + >>> a = torch.tensor([[-0.3711, -1.9353, -0.4605, -0.2917], + ... [ 0.1815, -1.0111, 0.9805, -1.5923], + ... [ 0.1062, 1.4581, 0.7759, -1.2344], + ... [-0.1830, -0.0313, 1.1908, -1.4757]]) + >>> b = torch.tensor([ 0.8032, 0.2930, -0.8113, -0.2308]) + >>> torch.div(a, b) + tensor([[-0.4620, -6.6051, 0.5676, 1.2639], + [ 0.2260, -3.4509, -1.2086, 6.8990], + [ 0.1322, 4.9764, -0.9564, 5.3484], + [-0.2278, -0.1068, -1.4678, 6.3938]]) + + >>> torch.div(a, b, rounding_mode='trunc') + tensor([[-0., -6., 0., 1.], + [ 0., -3., -1., 6.], + [ 0., 4., -0., 5.], + [-0., -0., -1., 6.]]) + + >>> torch.div(a, b, rounding_mode='floor') + tensor([[-1., -7., 0., 1.], + [ 0., -4., -2., 6.], + [ 0., 4., -1., 5.], + [-1., -1., -2., 6.]]) + """ + +@overload +def divide( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide( + input: Tensor, + other: Tensor, + *, + rounding_mode: str | None, + out: Tensor | None = None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide( + input: Tensor, + other: Number | _complex | PySymType, + *, + rounding_mode: str | None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide(input: Tensor, other: Number | _complex | PySymType) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +def dot( + input: Tensor, + tensor: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + dot(input, tensor, *, out=None) -> Tensor + + Computes the dot product of two 1D tensors. + + .. note:: + + Unlike NumPy's dot, torch.dot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + + Args: + input (Tensor): first tensor in the dot product, must be 1D. + tensor (Tensor): second tensor in the dot product, must be 1D. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + + >>> t1, t2 = torch.tensor([0, 1]), torch.tensor([2, 3]) + >>> torch.dot(t1, t2) + tensor(3) + """ + +def dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def dsmm(input: Tensor, mat2: Tensor) -> Tensor: ... +@overload +def dsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + dsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors + depthwise according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) + (the split dimension is 2), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.dsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + """ + +@overload +def dsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + dsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors + depthwise according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) + (the split dimension is 2), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.dsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + """ + +def dstack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + dstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence depthwise (along third axis). + + This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by :func:`torch.atleast_3d`. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.dstack((a,b)) + tensor([[[1, 4], + [2, 5], + [3, 6]]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.dstack((a,b)) + tensor([[[1, 4]], + [[2, 5]], + [[3, 6]]]) + """ + +def embedding( + weight: Tensor, + indices: Tensor, + padding_idx: _int | SymInt = -1, + scale_grad_by_freq: _bool = False, + sparse: _bool = False, +) -> Tensor: ... +@overload +def embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool, + mode: _int, + sparse: _bool, + per_sample_weights: Tensor | None, + include_last_offset: _bool, + padding_idx: _int | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def embedding_renorm_( + input: Tensor, + indices: Tensor, + max_norm: _float, + norm_type: _float, +) -> Tensor: ... +@overload +def empty( + size: Sequence[_int | SymInt], + *, + memory_format: memory_format | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +@overload +def empty( + *size: _int | SymInt, + memory_format: memory_format | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +def empty_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns an uninitialized tensor with the same size as :attr:`input`. + ``torch.empty_like(input)`` is equivalent to + ``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + When ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense format. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> a=torch.empty((2,3), dtype=torch.int32, device = 'cuda') + >>> torch.empty_like(a) + tensor([[0, 0, 0], + [0, 0, 0]], device='cuda:0', dtype=torch.int32) + """ + +def empty_permuted( + size: Sequence[_int | SymInt], + physical_layout: _size, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_permuted(size, physical_layout, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates an uninitialized, non-overlapping and dense tensor with the + specified :attr:`size`, with :attr:`physical_layout` specifying how the + dimensions are physically laid out in memory (each logical dimension is listed + from outermost to innermost). :attr:`physical_layout` is a generalization + of NCHW/NHWC notation: if each dimension is assigned a number according to + what order they occur in size (N=0, C=1, H=2, W=3), then NCHW is ``(0, 1, 2, 3)`` + while NHWC is ``(0, 2, 3, 1)``. Equivalently, the strides of the output + tensor ``t`` are such that ``t.stride(physical_layout[i]) == contiguous_strides[i]`` + (notably, this function is *not* equivalent to ``torch.empty(size).permute(physical_layout)``). + + Unlike :func:`torch.empty_strided`, this is guaranteed to produce a dense + tensor with no overlaps. If possible, prefer using this function over + :func:`torch.empty_strided` or manual use of :func:`torch.as_strided`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + physical_layout (tuple of int): the ordering of dimensions physically in memory + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Examples: + + >>> torch.empty((2, 3, 5, 7)).stride() + (105, 35, 7, 1) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 1, 2, 3)).stride() + (105, 35, 7, 1) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).dim_order() + (0, 2, 3, 1) + """ + +def empty_quantized( + size: _size, + qtensor: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def empty_strided( + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates a tensor with the specified :attr:`size` and :attr:`stride` and filled with undefined data. + + .. warning:: + If the constructed tensor is "overlapped" (with multiple indices referring to the same element + in memory) its behavior is undefined. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + stride (tuple of int): the strides of the output tensor + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> a = torch.empty_strided((2, 3), (1, 2)) + >>> a + tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07], + [0.0000e+00, 0.0000e+00, 3.0705e-41]]) + >>> a.stride() + (1, 2) + >>> a.size() + torch.Size([2, 3]) + """ + +@overload +def eq( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + eq(input, other, *, out=None) -> Tensor + + Computes element-wise equality + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) + """ + +@overload +def eq( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + eq(input, other, *, out=None) -> Tensor + + Computes element-wise equality + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) + """ + +def equal(input: Tensor, other: Tensor) -> _bool: + r""" + equal(input, other) -> bool + + ``True`` if two tensors have the same size and elements, ``False`` otherwise. + + .. note:: + + Tensors containing NaNs are never equal to each other. Additionally, this function does not + differentiate between the data types of the tensors during comparison. For more thorough tensor checks, + use :meth:`torch.testing.assert_close`. + + Example:: + + >>> torch.equal(torch.tensor([1, 2]), torch.tensor([1, 2])) + True + >>> torch.equal(torch.tensor([3, torch.nan]), torch.tensor([3, torch.nan])) + False + >>> torch.equal(torch.tensor([1, 2, 3], dtype=torch.int32), torch.tensor([1, 2, 3], dtype=torch.float32)) + True + """ + +def erf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erf(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erf`. + """ + +def erf_(input: Tensor) -> Tensor: + r""" + erf_(input) -> Tensor + + In-place version of :func:`torch.erf` + """ + +def erfc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erfc(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erfc`. + """ + +def erfc_(input: Tensor) -> Tensor: + r""" + erfc_(input) -> Tensor + + In-place version of :func:`torch.erfc` + """ + +def erfinv(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erfinv(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erfinv`. + """ + +def exp(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + exp(input, *, out=None) -> Tensor + + Returns a new tensor with the exponential of the elements + of the input tensor :attr:`input`. + + .. math:: + y_{i} = e^{x_{i}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.exp(torch.tensor([0, math.log(2.)])) + tensor([ 1., 2.]) + """ + +def exp2(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + exp2(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.exp2`. + """ + +def exp2_(input: Tensor) -> Tensor: + r""" + exp2_(input) -> Tensor + + In-place version of :func:`torch.exp2` + """ + +def exp_(input: Tensor) -> Tensor: + r""" + exp_(input) -> Tensor + + In-place version of :func:`torch.exp` + """ + +def expand_copy( + input: Tensor, + size: Sequence[_int | SymInt], + *, + implicit: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.Tensor.expand`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def expm1(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + expm1(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.expm1`. + """ + +def expm1_(input: Tensor) -> Tensor: + r""" + expm1_(input) -> Tensor + + In-place version of :func:`torch.expm1` + """ + +@overload +def eye( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +@overload +def eye( + n: _int | SymInt, + m: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +def fake_quantize_per_channel_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized per channel using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`, across the channel specified by :attr:`axis`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), in ``torch.float32`` + scale (Tensor): quantization scale, per channel in ``torch.float32`` + zero_point (Tensor): quantization zero_point, per channel in ``torch.int32`` or ``torch.half`` or ``torch.float32`` + axis (int32): channel axis + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized per channel ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(2, 2, 2) + >>> x + tensor([[[-0.2525, -0.0466], + [ 0.3491, -0.2168]], + + [[-0.5906, 1.6258], + [ 0.6444, -0.0542]]]) + >>> scales = (torch.randn(2) + 1) * 0.05 + >>> scales + tensor([0.0475, 0.0486]) + >>> zero_points = torch.zeros(2).to(torch.int32) + >>> zero_points + tensor([0, 0]) + >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255) + tensor([[[0.0000, 0.0000], + [0.3405, 0.0000]], + + [[0.0000, 1.6134], + [0.6323, 0.0000]]]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: _float, + zero_point: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, + output: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, + output: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex | PySymType, + weight_zero_point: Number | _complex | PySymType, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight_fp32_activation( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex | PySymType, + weight_zero_point: Number | _complex | PySymType, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_quantize_weight( + input: Tensor, +) -> tuple[Tensor, Tensor, _float, _int]: ... +def fbgemm_pack_gemm_matrix_fp16(input: Tensor) -> Tensor: ... +@overload +def fbgemm_pack_quantized_matrix(input: Tensor) -> Tensor: ... +@overload +def fbgemm_pack_quantized_matrix(input: Tensor, K: _int, N: _int) -> Tensor: ... +def feature_alpha_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def feature_alpha_dropout_( + input: Tensor, + p: _float, + train: _bool, +) -> Tensor: + r""" + feature_alpha_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.feature_alpha_dropout` + """ + +def feature_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def feature_dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: + r""" + feature_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.feature_dropout` + """ + +@overload +def fill(input: Tensor, value: Tensor) -> Tensor: ... +@overload +def fill(input: Tensor, value: Number | _complex | PySymType) -> Tensor: ... +@overload +def fill_(input: Tensor, value: Tensor) -> Tensor: + r""" + fill_(input, value) -> Tensor + + In-place version of :func:`torch.fill` + """ + +@overload +def fill_(input: Tensor, value: Number | _complex | PySymType) -> Tensor: + r""" + fill_(input, value) -> Tensor + + In-place version of :func:`torch.fill` + """ + +def fix(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + fix(input, *, out=None) -> Tensor + + Alias for :func:`torch.trunc` + """ + +def fix_(input: Tensor) -> Tensor: + r""" + fix_(input) -> Tensor + + In-place version of :func:`torch.fix` + """ + +def flatten( + input: Tensor, + start_dim: _int = 0, + end_dim: _int = -1, +) -> Tensor: + r""" + flatten(input, start_dim=0, end_dim=-1) -> Tensor + + Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` + are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. + The order of elements in :attr:`input` is unchanged. + + Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, + or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can + be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the + flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + + .. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + + Args: + input (Tensor): the input tensor. + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) + """ + +def flip(input: Tensor, dims: _size) -> Tensor: + r""" + flip(input, dims) -> Tensor + + Reverse the order of an n-D tensor along given axis in dims. + + .. note:: + `torch.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flip` is expected to be slower than `np.flip`. + + Args: + input (Tensor): the input tensor. + dims (a list or tuple): axis to flip on + + Example:: + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[ 0, 1], + [ 2, 3]], + + [[ 4, 5], + [ 6, 7]]]) + >>> torch.flip(x, [0, 1]) + tensor([[[ 6, 7], + [ 4, 5]], + + [[ 2, 3], + [ 0, 1]]]) + """ + +def fliplr(input: Tensor) -> Tensor: + r""" + fliplr(input) -> Tensor + + Flip tensor in the left/right direction, returning a new tensor. + + Flip the entries in each row in the left/right direction. + Columns are preserved, but appear in a different order than before. + + Note: + Requires the tensor to be at least 2-D. + + .. note:: + `torch.fliplr` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.fliplr`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.fliplr` is expected to be slower than `np.fliplr`. + + Args: + input (Tensor): Must be at least 2-dimensional. + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.fliplr(x) + tensor([[1, 0], + [3, 2]]) + """ + +def flipud(input: Tensor) -> Tensor: + r""" + flipud(input) -> Tensor + + Flip tensor in the up/down direction, returning a new tensor. + + Flip the entries in each column in the up/down direction. + Rows are preserved, but appear in a different order than before. + + Note: + Requires the tensor to be at least 1-D. + + .. note:: + `torch.flipud` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flipud`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flipud` is expected to be slower than `np.flipud`. + + Args: + input (Tensor): Must be at least 1-dimensional. + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.flipud(x) + tensor([[2, 3], + [0, 1]]) + """ + +@overload +def float_power( + input: Tensor, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +@overload +def float_power( + self: Number | _complex | PySymType, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +@overload +def float_power( + input: Tensor, + exponent: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +def floor(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + floor(input, *, out=None) -> Tensor + + Returns a new tensor with the floor of the elements of :attr:`input`, + the largest integer less than or equal to each element. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + .. math:: + \text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.8166, 1.5308, -0.2530, -0.2091]) + >>> torch.floor(a) + tensor([-1., 1., -1., -1.]) + """ + +def floor_(input: Tensor) -> Tensor: + r""" + floor_(input) -> Tensor + + In-place version of :func:`torch.floor` + """ + +def floor_divide( + input: Tensor | Number, + other: Tensor | Number, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + floor_divide(input, other, *, out=None) -> Tensor + + .. note:: + + Before PyTorch 1.13 :func:`torch.floor_divide` incorrectly performed + truncation division. To restore the previous behavior use + :func:`torch.div` with ``rounding_mode='trunc'``. + + Computes :attr:`input` divided by :attr:`other`, elementwise, and floors + the result. + + .. math:: + \text{{out}}_i = \text{floor} \left( \frac{{\text{{input}}_i}}{{\text{{other}}_i}} \right) + + + + Supports broadcasting to a common shape, type promotion, and integer and float inputs. + + Args: + input (Tensor or Number): the dividend + other (Tensor or Number): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([4.0, 3.0]) + >>> b = torch.tensor([2.0, 2.0]) + >>> torch.floor_divide(a, b) + tensor([2.0, 1.0]) + >>> torch.floor_divide(a, 1.4) + tensor([2.0, 2.0]) + """ + +def fmax( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmax(input, other, *, out=None) -> Tensor + + Computes the element-wise maximum of :attr:`input` and :attr:`other`. + + This is like :func:`torch.maximum` except it handles NaNs differently: + if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the maximum. + Only if both elements are NaN is NaN propagated. + + This function is a wrapper around C++'s ``std::fmax`` and is similar to NumPy's ``fmax`` function. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and floating-point inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([9.7, float('nan'), 3.1, float('nan')]) + >>> b = torch.tensor([-2.2, 0.5, float('nan'), float('nan')]) + >>> torch.fmax(a, b) + tensor([9.7000, 0.5000, 3.1000, nan]) + """ + +def fmin( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmin(input, other, *, out=None) -> Tensor + + Computes the element-wise minimum of :attr:`input` and :attr:`other`. + + This is like :func:`torch.minimum` except it handles NaNs differently: + if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the minimum. + Only if both elements are NaN is NaN propagated. + + This function is a wrapper around C++'s ``std::fmin`` and is similar to NumPy's ``fmin`` function. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and floating-point inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([2.2, float('nan'), 2.1, float('nan')]) + >>> b = torch.tensor([-9.3, 0.1, float('nan'), float('nan')]) + >>> torch.fmin(a, b) + tensor([-9.3000, 0.1000, 2.1000, nan]) + """ + +@overload +def fmod( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmod(input, other, *, out=None) -> Tensor + + Applies C++'s `std::fmod `_ entrywise. + The result has the same sign as the dividend :attr:`input` and its absolute value + is less than that of :attr:`other`. + + This function may be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + + .. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + + .. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + + Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + """ + +@overload +def fmod( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmod(input, other, *, out=None) -> Tensor + + Applies C++'s `std::fmod `_ entrywise. + The result has the same sign as the dividend :attr:`input` and its absolute value + is less than that of :attr:`other`. + + This function may be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + + .. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + + .. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + + Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + """ + +def frac(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + frac(input, *, out=None) -> Tensor + + Computes the fractional portion of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = \text{input}_{i} - \left\lfloor |\text{input}_{i}| \right\rfloor * \operatorname{sgn}(\text{input}_{i}) + + Example:: + + >>> torch.frac(torch.tensor([1, 2.5, -3.2])) + tensor([ 0.0000, 0.5000, -0.2000]) + """ + +def frac_(input: Tensor) -> Tensor: + r""" + frac_(input) -> Tensor + + In-place version of :func:`torch.frac` + """ + +def frexp( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.frexp: + r""" + frexp(input, *, out=None) -> (Tensor mantissa, Tensor exponent) + + Decomposes :attr:`input` into mantissa and exponent tensors + such that :math:`\text{input} = \text{mantissa} \times 2^{\text{exponent}}`. + + The range of mantissa is the open interval (-1, 1). + + Supports float inputs. + + Args: + input (Tensor): the input tensor + + + Keyword args: + out (tuple, optional): the output tensors + + Example:: + + >>> x = torch.arange(9.) + >>> mantissa, exponent = torch.frexp(x) + >>> mantissa + tensor([0.0000, 0.5000, 0.5000, 0.7500, 0.5000, 0.6250, 0.7500, 0.8750, 0.5000]) + >>> exponent + tensor([0, 1, 2, 2, 3, 3, 3, 3, 4], dtype=torch.int32) + >>> torch.ldexp(mantissa, exponent) + tensor([0., 1., 2., 3., 4., 5., 6., 7., 8.]) + """ + +def frobenius_norm( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def from_file( + filename: str, + shared: _bool | None = None, + size: _int | None = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + from_file(filename, shared=None, size=0, *, dtype=None, layout=None, device=None, pin_memory=False) + + Creates a CPU tensor with a storage backed by a memory-mapped file. + + If ``shared`` is True, then memory is shared between processes. All changes are written to the file. + If ``shared`` is False, then changes to the tensor do not affect the file. + + ``size`` is the number of elements in the Tensor. If ``shared`` is ``False``, then the file must contain + at least ``size * sizeof(dtype)`` bytes. If ``shared`` is ``True`` the file will be created if needed. + + .. note:: + Only CPU tensors can be mapped to files. + + .. note:: + For now, tensors with storages backed by a memory-mapped file cannot be created in pinned memory. + + + Args: + filename (str): file name to map + shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the + underlying `mmap(2) call `_) + size (int): number of elements in the tensor + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> t = torch.randn(2, 5, dtype=torch.float64) + >>> t.numpy().tofile('storage.pt') + >>> t_mapped = torch.from_file('storage.pt', shared=False, size=10, dtype=torch.float64) + """ + +def from_numpy(ndarray) -> Tensor: + r""" + from_numpy(ndarray) -> Tensor + + Creates a :class:`Tensor` from a :class:`numpy.ndarray`. + + The returned tensor and :attr:`ndarray` share the same memory. Modifications to + the tensor will be reflected in the :attr:`ndarray` and vice versa. The returned + tensor is not resizable. + + It currently accepts :attr:`ndarray` with dtypes of ``numpy.float64``, + ``numpy.float32``, ``numpy.float16``, ``numpy.complex64``, ``numpy.complex128``, + ``numpy.int64``, ``numpy.int32``, ``numpy.int16``, ``numpy.int8``, ``numpy.uint8``, + and ``bool``. + + .. warning:: + Writing to a tensor created from a read-only NumPy array is not supported and will result in undefined behavior. + + Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.from_numpy(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + """ + +def frombuffer( + buffer: Any, + *, + dtype: _dtype, + count: int = -1, + offset: int = 0, + requires_grad: _bool = False, +) -> Tensor: + r""" + frombuffer(buffer, *, dtype, count=-1, offset=0, requires_grad=False) -> Tensor + + Creates a 1-dimensional :class:`Tensor` from an object that implements + the Python buffer protocol. + + Skips the first :attr:`offset` bytes in the buffer, and interprets the rest of + the raw bytes as a 1-dimensional tensor of type :attr:`dtype` with :attr:`count` + elements. + + Note that either of the following must be true: + + 1. :attr:`count` is a positive non-zero number, and the total number of bytes + in the buffer is more than :attr:`offset` plus :attr:`count` times the size + (in bytes) of :attr:`dtype`. + + 2. :attr:`count` is negative, and the length (number of bytes) of the buffer + subtracted by the :attr:`offset` is a multiple of the size (in bytes) of + :attr:`dtype`. + + The returned tensor and buffer share the same memory. Modifications to + the tensor will be reflected in the buffer and vice versa. The returned + tensor is not resizable. + + .. note:: + This function increments the reference count for the object that + owns the shared memory. Therefore, such memory will not be deallocated + before the returned tensor goes out of scope. + + .. warning:: + This function's behavior is undefined when passed an object implementing + the buffer protocol whose data is not on the CPU. Doing so is likely to + cause a segmentation fault. + + .. warning:: + This function does not try to infer the :attr:`dtype` (hence, it is not + optional). Passing a different :attr:`dtype` than its source may result + in unexpected behavior. + + Args: + buffer (object): a Python object that exposes the buffer interface. + + Keyword args: + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + count (int, optional): the number of desired elements to be read. + If negative, all the elements (until the end of the buffer) will be + read. Default: -1. + offset (int, optional): the number of bytes to skip at the start of + the buffer. Default: 0. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> import array + >>> a = array.array('i', [1, 2, 3]) + >>> t = torch.frombuffer(a, dtype=torch.int32) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> # Interprets the signed char bytes as 32-bit integers. + >>> # Each 4 signed char elements will be interpreted as + >>> # 1 signed 32-bit integer. + >>> import array + >>> a = array.array('b', [-1, 0, 0, 0]) + >>> torch.frombuffer(a, dtype=torch.int32) + tensor([255], dtype=torch.int32) + """ + +@overload +def full( + size: _size, + fill_value: Number | _complex, + *, + out: Tensor | None = None, + layout: _layout = strided, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +@overload +def full( + size: _size, + fill_value: Number | _complex, + *, + names: list[str | None], + layout: _layout = strided, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +@overload +def full( + size: Sequence[_int | SymInt], + fill_value: Number | _complex | PySymType, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +def full_like( + input: Tensor, + fill_value: Number | _complex | PySymType, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full_like(input, fill_value, \*, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`. + ``torch.full_like(input, fill_value)`` is equivalent to + ``torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + fill_value: the number to fill the output tensor with. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> x = torch.ones(2, 3) + >>> torch.full_like(x, 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + >>> torch.full_like(x, 7) + tensor([[7., 7., 7.], + [7., 7., 7.]]) + >>> torch.full_like(x, 0.5, dtype=torch.int32) + tensor([[0, 0, 0], + [0, 0, 0]], dtype=torch.int32) + >>> y = torch.randn(3, 4, dtype=torch.float64) + >>> torch.full_like(y, -1.0) + tensor([[-1., -1., -1., -1.], + [-1., -1., -1., -1.], + [-1., -1., -1., -1.]], dtype=torch.float64) + """ + +def fused_moving_avg_obs_fake_quant( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> Tensor: ... +def gather( + input: Tensor, + dim: _int, + index: Tensor, + *, + sparse_grad: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + + Gathers values along an axis specified by `dim`. + + For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + + :attr:`input` and :attr:`index` must have the same number of dimensions. + It is also required that ``index.size(d) <= input.size(d)`` for all + dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. + Note that ``input`` and ``index`` do not broadcast against each other. + When :attr:`index` is empty, we always return an empty output with the same shape + without further error checking. + + Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + + Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + + Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) + """ + +def gcd( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gcd(input, other, *, out=None) -> Tensor + + Computes the element-wise greatest common divisor (GCD) of :attr:`input` and :attr:`other`. + + Both :attr:`input` and :attr:`other` must have integer types. + + .. note:: + This defines :math:`gcd(0, 0) = 0`. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.gcd(a, b) + tensor([1, 2, 5]) + >>> c = torch.tensor([3]) + >>> torch.gcd(a, c) + tensor([1, 1, 3]) + """ + +def gcd_(input: Tensor, other: Tensor) -> Tensor: + r""" + gcd_(input, other) -> Tensor + + In-place version of :func:`torch.gcd` + """ + +@overload +def ge( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ge(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \geq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) + """ + +@overload +def ge( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ge(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \geq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) + """ + +def geqrf( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.geqrf: + r""" + geqrf(input, *, out=None) -> (Tensor, Tensor) + + This is a low-level function for calling LAPACK's geqrf directly. This function + returns a namedtuple (a, tau) as defined in `LAPACK documentation for geqrf`_ . + + Computes a QR decomposition of :attr:`input`. + Both `Q` and `R` matrices are stored in the same output tensor `a`. + The elements of `R` are stored on and above the diagonal. + Elementary reflectors (or Householder vectors) implicitly defining matrix `Q` + are stored below the diagonal. + The results of this function can be used together with :func:`torch.linalg.householder_product` + to obtain the `Q` matrix or + with :func:`torch.ormqr`, which uses an implicit representation of the `Q` matrix, + for an efficient matrix-matrix multiplication. + + See `LAPACK documentation for geqrf`_ for further details. + + .. note:: + See also :func:`torch.linalg.qr`, which computes Q and R matrices, and :func:`torch.linalg.lstsq` + with the ``driver="gels"`` option for a function that can solve matrix equations using a QR decomposition. + + Args: + input (Tensor): the input matrix + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, Tensor). Ignored if `None`. Default: `None`. + + .. _LAPACK documentation for geqrf: + http://www.netlib.org/lapack/explore-html/df/dc5/group__variants_g_ecomputational_ga3766ea903391b5cf9008132f7440ec7b.html + """ + +def ger( + input: Tensor, + vec2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ger(input, vec2, *, out=None) -> Tensor + + Alias of :func:`torch.outer`. + + .. warning:: + This function is deprecated and will be removed in a future PyTorch release. + Use :func:`torch.outer` instead. + """ + +def get_default_dtype() -> _dtype: + r""" + get_default_dtype() -> torch.dtype + + Get the current default floating point :class:`torch.dtype`. + + Example:: + + >>> torch.get_default_dtype() # initial default for floating point is torch.float32 + torch.float32 + >>> torch.set_default_dtype(torch.float64) + >>> torch.get_default_dtype() # default is now changed to torch.float64 + torch.float64 + """ + +def get_num_interop_threads() -> _int: + r""" + get_num_interop_threads() -> int + + Returns the number of threads used for inter-op parallelism on CPU + (e.g. in JIT interpreter) + """ + +def get_num_threads() -> _int: + r""" + get_num_threads() -> int + + Returns the number of threads used for parallelizing CPU operations + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Number | _complex | PySymType | None = None, + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex | PySymType], + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex | PySymType], + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor], + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Number | _complex | PySymType, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor], + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def greater( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.gt`. + """ + +@overload +def greater( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.gt`. + """ + +@overload +def greater_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ge`. + """ + +@overload +def greater_equal( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ge`. + """ + +def grid_sampler( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def grid_sampler_2d( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def grid_sampler_3d( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def group_norm( + input: Tensor, + num_groups: _int, + weight: Tensor | None = None, + bias: Tensor | None = None, + eps: _float = 1e-05, + cudnn_enabled: _bool = True, +) -> Tensor: ... +@overload +def gru( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def gru( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def gru_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +@overload +def gt( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} > \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + + Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) + """ + +@overload +def gt( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} > \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + + Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) + """ + +@overload +def hamming_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + beta: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hann_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def hann_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +def hardshrink( + input: Tensor, + lambd: Number | _complex | PySymType = 0.5, + *, + out: Tensor | None = None, +) -> Tensor: ... +def hash_tensor( + input: Tensor, + dim: _int | _size = (), + *, + keepdim: _bool = False, + mode: _int = 0, + out: Tensor | None = None, +) -> Tensor: + r""" + hash_tensor(input, *, mode=0) -> Tensor + + Returns a hash of all elements in the :attr:`input` tensor. + + Currently only mode=0 (reduction via xor) is supported. The output will always + be of type ``torch.uint64``. The elements of ``input`` are upcasted to their + 64 bit float / integer equivalent and bitcasted to ``torch.uint64`` before + reduction via xor. + + Args: + input (Tensor): the input tensor. + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.1918, -1.1813, 0.3373]]) + >>> torch.hash_tensor(a) + tensor(13822780554648485888, dtype=torch.uint64) + + .. function:: hash_tensor(input, dim, *, keepdim=False, mode=0) -> Tensor + :noindex: + + Returns the hash of each row of the :attr:`input` tensor in the given + dimension :attr:`dim` given by mode. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(2, 4) + >>> a + tensor([[ 0.1317, -0.5554, -1.4724, -1.1391], + [ 0.0778, -0.6070, 0.6375, 0.1798]]) + >>> torch.hash_tensor(a, 1) + tensor([9233691267014066176, 9255993250844508160], dtype=torch.uint64) + """ + +def heaviside( + input: Tensor, + values: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + heaviside(input, values, *, out=None) -> Tensor + + Computes the Heaviside step function for each element in :attr:`input`. + The Heaviside step function is defined as: + + .. math:: + \text{{heaviside}}(input, values) = \begin{cases} + 0, & \text{if input < 0}\\ + values, & \text{if input == 0}\\ + 1, & \text{if input > 0} + \end{cases} + + + Args: + input (Tensor): the input tensor. + values (Tensor): The values to use where :attr:`input` is zero. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.tensor([-1.5, 0, 2.0]) + >>> values = torch.tensor([0.5]) + >>> torch.heaviside(input, values) + tensor([0.0000, 0.5000, 1.0000]) + >>> values = torch.tensor([1.2, -2.0, 3.5]) + >>> torch.heaviside(input, values) + tensor([0., -2., 1.]) + """ + +def hinge_embedding_loss( + input: Tensor, + target: Tensor, + margin: _float = 1.0, + reduction: _int = 1, +) -> Tensor: ... +def histc( + input: Tensor, + bins: _int = 100, + min: Number | _complex | PySymType = 0, + max: Number | _complex | PySymType = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + histc(input, bins=100, min=0, max=0, *, out=None) -> Tensor + + Computes the histogram of a tensor. + + The elements are sorted into equal width bins between :attr:`min` and + :attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and + maximum values of the data are used. + + Elements lower than min and higher than max and ``NaN`` elements are ignored. + + Args: + input (Tensor): the input tensor. + bins (int): number of histogram bins + min (Scalar): lower end of the range (inclusive) + max (Scalar): upper end of the range (inclusive) + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: Histogram represented as a tensor + + Example:: + + >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) + tensor([ 0., 2., 1., 0.]) + """ + +@overload +def histogram( + input: Tensor, + bins: Tensor, + *, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogram( + input: Tensor, + bins: _int = 100, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _int, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _size, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: tuple[Tensor, ...] | list[Tensor], + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +def hsmm(input: Tensor, mat2: Tensor) -> Tensor: ... +@overload +def hsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +@overload +def hsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +def hspmm( + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hspmm(mat1, mat2, *, out=None) -> Tensor + + Performs a matrix multiplication of a :ref:`sparse COO matrix + ` :attr:`mat1` and a strided matrix :attr:`mat2`. The + result is a (1 + 1)-dimensional :ref:`hybrid COO matrix + `. + + Args: + mat1 (Tensor): the first sparse matrix to be matrix multiplied + mat2 (Tensor): the second strided matrix to be matrix multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +def hstack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence horizontally (column wise). + + This is equivalent to concatenation along the first axis for 1-D tensors, and along the second axis for all other tensors. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.hstack((a,b)) + tensor([1, 2, 3, 4, 5, 6]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.hstack((a,b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + """ + +def hypot( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hypot(input, other, *, out=None) -> Tensor + + Given the legs of a right triangle, return its hypotenuse. + + .. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}^{2} + \text{other}_{i}^{2}} + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.hypot(torch.tensor([4.0]), torch.tensor([3.0, 4.0, 5.0])) + tensor([5.0000, 5.6569, 6.4031]) + """ + +def i0(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + i0(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.i0`. + """ + +def i0_(input: Tensor) -> Tensor: + r""" + i0_(input) -> Tensor + + In-place version of :func:`torch.i0` + """ + +def igamma( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + igamma(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.gammainc`. + """ + +def igammac( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + igammac(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.gammaincc`. + """ + +def imag(input: Tensor) -> Tensor: + r""" + imag(input) -> Tensor + + Returns a new tensor containing imaginary values of the :attr:`self` tensor. + The returned tensor and :attr:`self` share the same underlying storage. + + .. warning:: + :func:`imag` is only supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.imag + tensor([ 0.3553, -0.7896, -0.0633, -0.8119]) + """ + +def index_add( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + index_add(input: Tensor, dim: int, index: Tensor, source: Tensor, *, alpha: Union[Number, _complex] = 1, out: Optional[Tensor]) -> Tensor # noqa: B950 + + See :meth:`~Tensor.index_add_` for function description. + """ + +def index_copy( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_copy(input: Tensor, dim: int, index: Tensor, source: Tensor, *, out: Optional[Tensor]) -> Tensor + + See :meth:`~Tensor.index_copy_` for function description. + """ + +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Tensor, +) -> Tensor: ... +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, +) -> Tensor: ... +def index_put( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def index_put_( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def index_reduce( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + reduce: str, + *, + include_self: _bool = True, + out: Tensor | None = None, +) -> Tensor: + r""" + index_reduce(input: Tensor, dim: int, index: Tensor, source: Tensor, reduce: str, *, include_self: bool = True, out: Optional[Tensor]) -> Tensor # noqa: B950 + + See :meth:`~Tensor.index_reduce_` for function description. + """ + +def index_select( + input: Tensor, + dim: _int, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_select(input, dim, index, *, out=None) -> Tensor + + Returns a new tensor which indexes the :attr:`input` tensor along dimension + :attr:`dim` using the entries in :attr:`index`. + + The returned tensor has the same number of dimensions as the original tensor + (:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length + of :attr:`index`; other dimensions have the same size as in the original tensor. + + .. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) + """ + +def indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def init_num_threads() -> None: ... +def inner( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + inner(input, other, *, out=None) -> Tensor + + Computes the dot product for 1D tensors. For higher dimensions, sums the product + of elements from :attr:`input` and :attr:`other` along their last dimension. + + .. note:: + + If either :attr:`input` or :attr:`other` is a scalar, the result is equivalent + to `torch.mul(input, other)`. + + If both :attr:`input` and :attr:`other` are non-scalars, the size of their last + dimension must match and the result is equivalent to `torch.tensordot(input, + other, dims=([-1], [-1]))` + + Args: + input (Tensor): First input tensor + other (Tensor): Second input tensor + + Keyword args: + out (Tensor, optional): Optional output tensor to write result into. The output + shape is `input.shape[:-1] + other.shape[:-1]`. + + Example:: + + # Dot product + >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1])) + tensor(7) + + # Multidimensional input tensors + >>> a = torch.randn(2, 3) + >>> a + tensor([[0.8173, 1.0874, 1.1784], + [0.3279, 0.1234, 2.7894]]) + >>> b = torch.randn(2, 4, 3) + >>> b + tensor([[[-0.4682, -0.7159, 0.1506], + [ 0.4034, -0.3657, 1.0387], + [ 0.9892, -0.6684, 0.1774], + [ 0.9482, 1.3261, 0.3917]], + + [[ 0.4537, 0.7493, 1.1724], + [ 0.2291, 0.5749, -0.2267], + [-0.7920, 0.3607, -0.3701], + [ 1.3666, -0.5850, -1.7242]]]) + >>> torch.inner(a, b) + tensor([[[-0.9837, 1.1560, 0.2907, 2.6785], + [ 2.5671, 0.5452, -0.6912, -1.5509]], + + [[ 0.1782, 2.9843, 0.7366, 1.5672], + [ 3.5115, -0.4864, -1.2476, -4.4337]]]) + + # Scalar input + >>> torch.inner(a, torch.tensor(2)) + tensor([[1.6347, 2.1748, 2.3567], + [0.6558, 0.2469, 5.5787]]) + """ + +def instance_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + use_input_stats: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> Tensor: ... +def int_repr(input: Tensor) -> Tensor: ... +def inverse(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + inverse(input, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.inv` + """ + +def is_complex(input: Tensor) -> _bool: + r""" + is_complex(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a complex data type i.e., + one of ``torch.complex64``, and ``torch.complex128``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex64)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex128)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_complex(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + False + """ + +def is_conj(input: Tensor) -> _bool: + r""" + is_conj(input) -> (bool) + + Returns True if the :attr:`input` is a conjugated tensor, i.e. its conjugate bit is set to `True`. + + Args: + input (Tensor): the input tensor. + """ + +def is_distributed(input: Tensor) -> _bool: ... +def is_floating_point(input: Tensor) -> _bool: + r""" + is_floating_point(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a floating point data type i.e., + one of ``torch.float64``, ``torch.float32``, ``torch.float16``, and ``torch.bfloat16``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0])) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.complex64)) + False + """ + +def is_grad_enabled() -> _bool: + r""" + is_grad_enabled() -> (bool) + + Returns True if grad mode is currently enabled. + """ + +def is_inference(input: Tensor) -> _bool: + r""" + is_inference(input) -> (bool) + + Returns True if :attr:`input` is an inference tensor. + + A non-view tensor is an inference tensor if and only if it was + allocated during inference mode. A view tensor is an inference + tensor if and only if the tensor it is a view of is an inference tensor. + + For details on inference mode please see + `Inference Mode `_. + + Args: + input (Tensor): the input tensor. + """ + +def is_inference_mode_enabled() -> _bool: + r""" + is_inference_mode_enabled() -> (bool) + + Returns True if inference mode is currently enabled. + """ + +def is_neg(input: Tensor) -> _bool: ... +def is_nonzero(input: Tensor) -> _bool: + r""" + is_nonzero(input) -> (bool) + + Returns True if the :attr:`input` is a single element tensor which is not equal to zero + after type conversions. + i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or + ``torch.tensor([False])``. + Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case + of sparse tensors). + + Args: + input (Tensor): the input tensor. + + Examples:: + + >>> torch.is_nonzero(torch.tensor([0.])) + False + >>> torch.is_nonzero(torch.tensor([1.5])) + True + >>> torch.is_nonzero(torch.tensor([False])) + False + >>> torch.is_nonzero(torch.tensor([3])) + True + >>> torch.is_nonzero(torch.tensor([1, 3, 5])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with no values is ambiguous + """ + +def is_same_size(input: Tensor, other: Tensor) -> _bool: ... +def is_signed(input: Tensor) -> _bool: ... +def is_vulkan_available() -> _bool: ... +def isclose( + input: Tensor, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, +) -> Tensor: + r""" + isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + Returns a new tensor with boolean elements representing if each element of + :attr:`input` is "close" to the corresponding element of :attr:`other`. + Closeness is defined as: + + .. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{rtol} \times \lvert \text{other}_i \rvert + \texttt{atol} + + + where :attr:`input` and :attr:`other` are finite. Where :attr:`input` + and/or :attr:`other` are nonfinite they are close if and only if + they are equal, with NaNs being considered equal to each other when + :attr:`equal_nan` is True. + + Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + rtol (float, optional): relative tolerance. Default: 1e-05 + atol (float, optional): absolute tolerance. Default: 1e-08 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + + Examples:: + + >>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4))) + tensor([ True, False, False]) + >>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5) + tensor([True, True]) + """ + +def isfinite(input: Tensor) -> Tensor: + r""" + isfinite(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element is `finite` or not. + + Real values are finite when they are not NaN, negative infinity, or infinity. + Complex values are finite when both their real and imaginary parts are finite. + + Args: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is finite and False elsewhere + + Example:: + + >>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([True, False, True, False, False]) + """ + +@overload +def isin( + elements: Tensor, + test_elements: Tensor, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +@overload +def isin( + element: Number | _complex | PySymType, + test_elements: Tensor, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +@overload +def isin( + elements: Tensor, + test_element: Number | _complex | PySymType, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +def isinf(input: Tensor) -> Tensor: + r""" + isinf(input) -> Tensor + + Tests if each element of :attr:`input` is infinite + (positive or negative infinity) or not. + + .. note:: + Complex values are infinite when their real or imaginary part is + infinite. + + Args: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is infinite and False elsewhere + + Example:: + + >>> torch.isinf(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([False, True, False, True, False]) + """ + +def isnan(input: Tensor) -> Tensor: + r""" + isnan(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element of :attr:`input` + is NaN or not. Complex values are considered NaN when either their real + and/or imaginary part is NaN. + + Arguments: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is NaN and False elsewhere + + Example:: + + >>> torch.isnan(torch.tensor([1, float('nan'), 2])) + tensor([False, True, False]) + """ + +def isneginf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + isneginf(input, *, out=None) -> Tensor + Tests if each element of :attr:`input` is negative infinity or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isneginf(a) + tensor([ True, False, False]) + """ + +def isposinf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + isposinf(input, *, out=None) -> Tensor + Tests if each element of :attr:`input` is positive infinity or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isposinf(a) + tensor([False, True, False]) + """ + +def isreal(input: Tensor) -> Tensor: + r""" + isreal(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element of :attr:`input` is real-valued or not. + All real-valued types are considered real. Complex values are considered real when their imaginary part is 0. + + Arguments: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is real and False elsewhere + + Example:: + + >>> torch.isreal(torch.tensor([1, 1+1j, 2+0j])) + tensor([True, False, True]) + """ + +def istft( + input: Tensor, + n_fft: _int, + hop_length: _int | None = None, + win_length: _int | None = None, + window: Tensor | None = None, + center: _bool = True, + normalized: _bool = False, + onesided: _bool | None = None, + length: _int | None = None, + return_complex: _bool = False, +) -> Tensor: ... +@overload +def kaiser_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +@overload +def kaiser_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +@overload +def kaiser_window( + window_length: _int, + periodic: _bool, + beta: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +def kl_div( + input: Tensor, + target: Tensor, + reduction: _int = 1, + *, + log_target: _bool = False, +) -> Tensor: ... +def kron( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + kron(input, other, *, out=None) -> Tensor + + Computes the Kronecker product, denoted by :math:`\otimes`, of :attr:`input` and :attr:`other`. + + If :attr:`input` is a :math:`(a_0 \times a_1 \times \dots \times a_n)` tensor and :attr:`other` is a + :math:`(b_0 \times b_1 \times \dots \times b_n)` tensor, the result will be a + :math:`(a_0*b_0 \times a_1*b_1 \times \dots \times a_n*b_n)` tensor with the following entries: + + .. math:: + (\text{input} \otimes \text{other})_{k_0, k_1, \dots, k_n} = + \text{input}_{i_0, i_1, \dots, i_n} * \text{other}_{j_0, j_1, \dots, j_n}, + + where :math:`k_t = i_t * b_t + j_t` for :math:`0 \leq t \leq n`. + If one tensor has fewer dimensions than the other it is unsqueezed until it has the same number of dimensions. + + Supports real-valued and complex-valued inputs. + + .. note:: + This function generalizes the typical definition of the Kronecker product for two matrices to two tensors, + as described above. When :attr:`input` is a :math:`(m \times n)` matrix and :attr:`other` is a + :math:`(p \times q)` matrix, the result will be a :math:`(p*m \times q*n)` block matrix: + + .. math:: + \mathbf{A} \otimes \mathbf{B}=\begin{bmatrix} + a_{11} \mathbf{B} & \cdots & a_{1 n} \mathbf{B} \\ + \vdots & \ddots & \vdots \\ + a_{m 1} \mathbf{B} & \cdots & a_{m n} \mathbf{B} \end{bmatrix} + + where :attr:`input` is :math:`\mathbf{A}` and :attr:`other` is :math:`\mathbf{B}`. + + Arguments: + input (Tensor) + other (Tensor) + + Keyword args: + out (Tensor, optional): The output tensor. Ignored if ``None``. Default: ``None`` + + Examples:: + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.ones(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]]) + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.arange(1, 5).reshape(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 2., 0., 0.], + [3., 4., 0., 0.], + [0., 0., 1., 2.], + [0., 0., 3., 4.]]) + """ + +def kthvalue( + input: Tensor, + k: _int | SymInt, + dim: _int = -1, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.kthvalue: + r""" + kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th + smallest element of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each element found. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors + are the same size as :attr:`input`, except in the dimension :attr:`dim` where + they are of size 1. Otherwise, :attr:`dim` is squeezed + (see :func:`torch.squeeze`), resulting in both the :attr:`values` and + :attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor. + + .. note:: + When :attr:`input` is a CUDA tensor and there are multiple valid + :attr:`k` th values, this function may nondeterministically return + :attr:`indices` for any of them. + + Args: + input (Tensor): the input tensor. + k (int): k for the k-th smallest element + dim (int, optional): the dimension to find the kth value along + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) + can be optionally given to be used as output buffers + + Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.kthvalue(x, 4) + torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3)) + + >>> x=torch.arange(1.,7.).resize_(2,3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.]]) + >>> torch.kthvalue(x, 2, 0, True) + torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]])) + """ + +def layer_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None = None, + bias: Tensor | None = None, + eps: _float = 1e-05, + cudnn_enable: _bool = True, +) -> Tensor: ... +def lcm( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lcm(input, other, *, out=None) -> Tensor + + Computes the element-wise least common multiple (LCM) of :attr:`input` and :attr:`other`. + + Both :attr:`input` and :attr:`other` must have integer types. + + .. note:: + This defines :math:`lcm(0, 0) = 0` and :math:`lcm(0, a) = 0`. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.lcm(a, b) + tensor([15, 20, 15]) + >>> c = torch.tensor([3]) + >>> torch.lcm(a, c) + tensor([15, 30, 15]) + """ + +def lcm_(input: Tensor, other: Tensor) -> Tensor: + r""" + lcm_(input, other) -> Tensor + + In-place version of :func:`torch.lcm` + """ + +def ldexp( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ldexp(input, other, *, out=None) -> Tensor + + Multiplies :attr:`input` by 2 ** :attr:`other`. + + .. math:: + \text{{out}}_i = \text{{input}}_i * 2^\text{{other}}_i + + + Typically this function is used to construct floating point numbers by multiplying + mantissas in :attr:`input` with integral powers of two created from the exponents + in :attr:`other`. + + Args: + input (Tensor): the input tensor. + other (Tensor): a tensor of exponents, typically integers. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.ldexp(torch.tensor([1.]), torch.tensor([1])) + tensor([2.]) + >>> torch.ldexp(torch.tensor([1.0]), torch.tensor([1, 2, 3, 4])) + tensor([ 2., 4., 8., 16.]) + """ + +def ldexp_(input: Tensor, other: Tensor) -> Tensor: + r""" + ldexp_(input, other) -> Tensor + + In-place version of :func:`torch.ldexp` + """ + +@overload +def le( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + le(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \leq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + + Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) + """ + +@overload +def le( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + le(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \leq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + + Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) + """ + +@overload +def lerp( + input: Tensor, + end: Tensor, + weight: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lerp(input, end, weight, *, out=None) + + Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based + on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + + .. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) + + The shapes of :attr:`start` and :attr:`end` must be + :ref:`broadcastable `. If :attr:`weight` is a tensor, then + the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + + Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + """ + +@overload +def lerp( + input: Tensor, + end: Tensor, + weight: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lerp(input, end, weight, *, out=None) + + Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based + on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + + .. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) + + The shapes of :attr:`start` and :attr:`end` must be + :ref:`broadcastable `. If :attr:`weight` is a tensor, then + the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + + Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + """ + +@overload +def less( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.lt`. + """ + +@overload +def less( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.lt`. + """ + +@overload +def less_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.le`. + """ + +@overload +def less_equal( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.le`. + """ + +def lgamma(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + lgamma(input, *, out=None) -> Tensor + + Computes the natural logarithm of the absolute value of the gamma function on :attr:`input`. + + .. math:: + \text{out}_{i} = \ln |\Gamma(\text{input}_{i})| + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.arange(0.5, 2, 0.5) + >>> torch.lgamma(a) + tensor([ 0.5724, 0.0000, -0.1208]) + """ + +@overload +def linspace( + start: Number, + end: Number, + steps: _int | None = None, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Tensor, + end: Tensor, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Number | _complex | PySymType, + end: Tensor, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Tensor, + end: Number | _complex | PySymType, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Number | _complex | PySymType, + end: Number | _complex | PySymType, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +def log(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log(input, *, out=None) -> Tensor + + Returns a new tensor with the natural logarithm of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{e} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) * 5 + >>> a + tensor([4.7767, 4.3234, 1.2156, 0.2411, 4.5739]) + >>> torch.log(a) + tensor([ 1.5637, 1.4640, 0.1952, -1.4226, 1.5204]) + """ + +def log10(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log10(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the logarithm to the base 10 of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{10} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.5224, 0.9354, 0.7257, 0.1301, 0.2251]) + + + >>> torch.log10(a) + tensor([-0.2820, -0.0290, -0.1392, -0.8857, -0.6476]) + """ + +def log10_(input: Tensor) -> Tensor: + r""" + log10_(input) -> Tensor + + In-place version of :func:`torch.log10` + """ + +def log1p(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log1p(input, *, out=None) -> Tensor + + Returns a new tensor with the natural logarithm of (1 + :attr:`input`). + + .. math:: + y_i = \log_{e} (x_i + 1) + + .. note:: This function is more accurate than :func:`torch.log` for small + values of :attr:`input` + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.0090, -0.9923, 1.0249, -0.5372, 0.2492]) + >>> torch.log1p(a) + tensor([ nan, -4.8653, 0.7055, -0.7705, 0.2225]) + """ + +def log1p_(input: Tensor) -> Tensor: + r""" + log1p_(input) -> Tensor + + In-place version of :func:`torch.log1p` + """ + +def log2(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log2(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the logarithm to the base 2 of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{2} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.8419, 0.8003, 0.9971, 0.5287, 0.0490]) + + + >>> torch.log2(a) + tensor([-0.2483, -0.3213, -0.0042, -0.9196, -4.3504]) + """ + +def log2_(input: Tensor) -> Tensor: + r""" + log2_(input) -> Tensor + + In-place version of :func:`torch.log2` + """ + +def log_(input: Tensor) -> Tensor: + r""" + log_(input) -> Tensor + + In-place version of :func:`torch.log` + """ + +def log_softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, + *, + out: Tensor | None = None, +) -> Tensor: ... +def logaddexp( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logaddexp(input, other, *, out=None) -> Tensor + + Logarithm of the sum of exponentiations of the inputs. + + Calculates pointwise :math:`\log\left(e^x + e^y\right)`. This function is useful + in statistics where the calculated probabilities of events may be so small as to + exceed the range of normal floating point numbers. In such cases the logarithm + of the calculated probability is stored. This function allows adding + probabilities stored in such a fashion. + + This op should be disambiguated with :func:`torch.logsumexp` which performs a + reduction on a single tensor. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logaddexp(torch.tensor([-1.0]), torch.tensor([-1.0, -2, -3])) + tensor([-0.3069, -0.6867, -0.8731]) + >>> torch.logaddexp(torch.tensor([-100.0, -200, -300]), torch.tensor([-1.0, -2, -3])) + tensor([-1., -2., -3.]) + >>> torch.logaddexp(torch.tensor([1.0, 2000, 30000]), torch.tensor([-1.0, -2, -3])) + tensor([1.1269e+00, 2.0000e+03, 3.0000e+04]) + """ + +def logaddexp2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logaddexp2(input, other, *, out=None) -> Tensor + + Logarithm of the sum of exponentiations of the inputs in base-2. + + Calculates pointwise :math:`\log_2\left(2^x + 2^y\right)`. See + :func:`torch.logaddexp` for more details. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + """ + +def logcumsumexp( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logcumsumexp(input, dim, *, out=None) -> Tensor + Returns the logarithm of the cumulative summation of the exponentiation of + elements of :attr:`input` in the dimension :attr:`dim`. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logcumsumexp}(x)_{ij} = \log \sum\limits_{k=0}^{j} \exp(x_{ik}) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> torch.logcumsumexp(a, dim=0) + tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811, + 1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475])) + """ + +def logdet(input: Tensor) -> Tensor: + r""" + logdet(input) -> Tensor + + Calculates log determinant of a square matrix or batches of square matrices. + + It returns ``-inf`` if the input has a determinant of zero, and ``NaN`` if it has + a negative determinant. + + .. note:: + Backward through :meth:`logdet` internally uses SVD results when :attr:`input` + is not invertible. In this case, double backward through :meth:`logdet` will + be unstable in when :attr:`input` doesn't have distinct singular values. See + :func:`torch.linalg.svd` for details. + + .. seealso:: + + :func:`torch.linalg.slogdet` computes the sign (resp. angle) and natural logarithm of the + absolute value of the determinant of real-valued (resp. complex) square matrices. + + Arguments: + input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more + batch dimensions. + + Example:: + + >>> A = torch.randn(3, 3) + >>> torch.det(A) + tensor(0.2611) + >>> torch.logdet(A) + tensor(-1.3430) + >>> A + tensor([[[ 0.9254, -0.6213], + [-0.5787, 1.6843]], + + [[ 0.3242, -0.9665], + [ 0.4539, -0.0887]], + + [[ 1.1336, -0.4025], + [-0.7089, 0.9032]]]) + >>> A.det() + tensor([1.1990, 0.4099, 0.7386]) + >>> A.det().log() + tensor([ 0.1815, -0.8917, -0.3031]) + """ + +def logical_and( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_and(input, other, *, out=None) -> Tensor + + Computes the element-wise logical AND of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute AND with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_and(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, False]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_and(a, b) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b.double()) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b) + tensor([False, False, True, False]) + >>> torch.logical_and(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([False, False, True, False]) + """ + +def logical_not(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + logical_not(input, *, out=None) -> Tensor + + Computes the element-wise logical NOT of the given input tensor. If not specified, the output tensor will have the bool + dtype. If the input tensor is not a bool tensor, zeros are treated as ``False`` and non-zeros are treated as ``True``. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_not(torch.tensor([True, False])) + tensor([False, True]) + >>> torch.logical_not(torch.tensor([0, 1, -10], dtype=torch.int8)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1.5, -10.], dtype=torch.double)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1., -10.], dtype=torch.double), out=torch.empty(3, dtype=torch.int16)) + tensor([1, 0, 0], dtype=torch.int16) + """ + +def logical_or( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_or(input, other, *, out=None) -> Tensor + + Computes the element-wise logical OR of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute OR with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_or(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_or(a, b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b.double()) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, True, False]) + """ + +def logical_xor( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_xor(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the element-wise logical XOR of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute XOR with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_xor(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([False, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_xor(a, b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b.double()) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, False, False]) + """ + +def logit( + input: Tensor, + eps: _float | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logit(input, eps=None, *, out=None) -> Tensor + + Alias for :func:`torch.special.logit`. + """ + +def logit_(input: Tensor, eps: _float | None = None) -> Tensor: + r""" + logit_(input, eps=None) -> Tensor + + In-place version of :func:`torch.logit` + """ + +@overload +def logspace( + start: Number, + end: Number, + steps: _int | None = None, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Tensor, + end: Tensor, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Number | _complex | PySymType, + end: Tensor, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Tensor, + end: Number | _complex | PySymType, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Number | _complex | PySymType, + end: Number | _complex | PySymType, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +def logsumexp( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logsumexp(input, dim, keepdim=False, *, out=None) + + Returns the log of summed exponentials of each row of the :attr:`input` + tensor in the given dimension :attr:`dim`. The computation is numerically + stabilized. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logsumexp}(x)_{i} = \log \sum_j \exp(x_{ij}) + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints): the dimension or dimensions to reduce. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> torch.logsumexp(a, 1) + tensor([1.4907, 1.0593, 1.5696]) + >>> torch.dist(torch.logsumexp(a, 1), torch.log(torch.sum(torch.exp(a), 1))) + tensor(1.6859e-07) + """ + +@overload +def lstm( + data: Tensor, + batch_sizes: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def lstm( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor, Tensor]: ... +def lstm_cell( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> tuple[Tensor, Tensor]: ... +@overload +def lt( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} < \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + + Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) + """ + +@overload +def lt( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} < \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + + Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) + """ + +def lu_solve( + input: Tensor, + LU_data: Tensor, + LU_pivots: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lu_solve(b, LU_data, LU_pivots, *, out=None) -> Tensor + + Returns the LU solve of the linear system :math:`Ax = b` using the partially pivoted + LU factorization of A from :func:`~linalg.lu_factor`. + + This function supports ``float``, ``double``, ``cfloat`` and ``cdouble`` dtypes for :attr:`input`. + + .. warning:: + + :func:`torch.lu_solve` is deprecated in favor of :func:`torch.linalg.lu_solve`. + :func:`torch.lu_solve` will be removed in a future PyTorch release. + ``X = torch.lu_solve(B, LU, pivots)`` should be replaced with + + .. code:: python + + X = linalg.lu_solve(LU, pivots, B) + + Arguments: + b (Tensor): the RHS tensor of size :math:`(*, m, k)`, where :math:`*` + is zero or more batch dimensions. + LU_data (Tensor): the pivoted LU factorization of A from :meth:`~linalg.lu_factor` of size :math:`(*, m, m)`, + where :math:`*` is zero or more batch dimensions. + LU_pivots (IntTensor): the pivots of the LU factorization from :meth:`~linalg.lu_factor` of size :math:`(*, m)`, + where :math:`*` is zero or more batch dimensions. + The batch dimensions of :attr:`LU_pivots` must be equal to the batch dimensions of + :attr:`LU_data`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> A = torch.randn(2, 3, 3) + >>> b = torch.randn(2, 3, 1) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> x = torch.lu_solve(b, LU, pivots) + >>> torch.dist(A @ x, b) + tensor(1.00000e-07 * + 2.8312) + """ + +def lu_unpack( + LU_data: Tensor, + LU_pivots: Tensor, + unpack_data: _bool = True, + unpack_pivots: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.lu_unpack: + r""" + lu_unpack(LU_data, LU_pivots, unpack_data=True, unpack_pivots=True, *, out=None) -> (Tensor, Tensor, Tensor) + + Unpacks the LU decomposition returned by :func:`~linalg.lu_factor` into the `P, L, U` matrices. + + .. seealso:: + + :func:`~linalg.lu` returns the matrices from the LU decomposition. Its gradient formula is more efficient + than that of doing :func:`~linalg.lu_factor` followed by :func:`~linalg.lu_unpack`. + + Args: + LU_data (Tensor): the packed LU factorization data + LU_pivots (Tensor): the packed LU factorization pivots + unpack_data (bool): flag indicating if the data should be unpacked. + If ``False``, then the returned ``L`` and ``U`` are empty tensors. + Default: ``True`` + unpack_pivots (bool): flag indicating if the pivots should be unpacked into a permutation matrix ``P``. + If ``False``, then the returned ``P`` is an empty tensor. + Default: ``True`` + + Keyword args: + out (tuple, optional): output tuple of three tensors. Ignored if `None`. + + Returns: + A namedtuple ``(P, L, U)`` + + Examples:: + + >>> A = torch.randn(2, 3, 3) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # We can recover A from the factorization + >>> A_ = P @ L @ U + >>> torch.allclose(A, A_) + True + + >>> # LU factorization of a rectangular matrix: + >>> A = torch.randn(2, 3, 2) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # P, L, U are the same as returned by linalg.lu + >>> P_, L_, U_ = torch.linalg.lu(A) + >>> torch.allclose(P, P_) and torch.allclose(L, L_) and torch.allclose(U, U_) + True + """ + +def margin_ranking_loss( + input1: Tensor, + input2: Tensor, + target: Tensor, + margin: _float = 0.0, + reduction: _int = 1, +) -> Tensor: ... +@overload +def masked_fill(input: Tensor, mask: Tensor, value: Tensor) -> Tensor: ... +@overload +def masked_fill( + input: Tensor, + mask: Tensor, + value: Number | _complex | PySymType, +) -> Tensor: ... +def masked_scatter(input: Tensor, mask: Tensor, source: Tensor) -> Tensor: ... +def masked_select( + input: Tensor, + mask: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + masked_select(input, mask, *, out=None) -> Tensor + + Returns a new 1-D tensor which indexes the :attr:`input` tensor according to + the boolean mask :attr:`mask` which is a `BoolTensor`. + + The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need + to match, but they must be :ref:`broadcastable `. + + .. note:: The returned tensor does **not** use the same storage + as the original tensor + + Args: + input (Tensor): the input tensor. + mask (BoolTensor): the tensor containing the binary mask to index with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.3552, -2.3825, -0.8297, 0.3477], + [-1.2035, 1.2252, 0.5002, 0.6248], + [ 0.1307, -2.0608, 0.1244, 2.0139]]) + >>> mask = x.ge(0.5) + >>> mask + tensor([[False, False, False, False], + [False, True, True, True], + [False, False, False, True]]) + >>> torch.masked_select(x, mask) + tensor([ 1.2252, 0.5002, 0.6248, 2.0139]) + """ + +def matmul( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matmul(input, other, *, out=None) -> Tensor + + Matrix product of two tensors. + + The behavior depends on the dimensionality of the tensors as follows: + + - If both tensors are 1-dimensional, the dot product (scalar) is returned. + - If both arguments are 2-dimensional, the matrix-matrix product is returned. + - If the first argument is 1-dimensional and the second argument is 2-dimensional, + a 1 is prepended to its dimension for the purpose of the matrix multiply. + After the matrix multiply, the prepended dimension is removed. + - If the first argument is 2-dimensional and the second argument is 1-dimensional, + the matrix-vector product is returned. + - If both arguments are at least 1-dimensional and at least one argument is + N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first + argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the + batched matrix multiply and removed after. If the second argument is 1-dimensional, a + 1 is appended to its dimension for the purpose of the batched matrix multiply and removed after. + + The first N-2 dimensions of each argument, the batch dimensions, are + :ref:`broadcast ` (and thus must be broadcastable). + The last 2, the matrix dimensions, are handled as in the matrix-matrix product. + + For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times m)` tensor and :attr:`other` is a :math:`(k \times m \times p)` + tensor, the batch dimensions are :math:`(j \times 1)` and :math:`(k)`, + and the matrix dimensions are :math:`(n \times m)` and :math:`(m \times p)`. + :attr:`out` will be a :math:`(j \times k \times n \times p)` tensor. + + This operation has support for arguments with :ref:`sparse layouts`. In particular the + matrix-matrix (both arguments 2-dimensional) supports sparse arguments with the same restrictions + as :func:`torch.mm` + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: + + The 1-dimensional dot product version of this function does not support an :attr:`out` parameter. + + Arguments: + input (Tensor): the first tensor to be multiplied + other (Tensor): the second tensor to be multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> # vector x vector + >>> tensor1 = torch.randn(3) + >>> tensor2 = torch.randn(3) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([]) + >>> # matrix x vector + >>> tensor1 = torch.randn(3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([3]) + >>> # batched matrix x broadcasted vector + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3]) + >>> # batched matrix x batched matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(10, 4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + >>> # batched matrix x broadcasted matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + """ + +def matrix_exp(input: Tensor) -> Tensor: + r""" + matrix_exp(A) -> Tensor + + Alias for :func:`torch.linalg.matrix_exp`. + """ + +def matrix_power( + input: Tensor, + n: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matrix_power(input, n, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.matrix_power` + """ + +@overload +def max(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.max: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +def max_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def max_pool1d_with_indices( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def maximum( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + maximum(input, other, *, out=None) -> Tensor + + Computes the element-wise maximum of :attr:`input` and :attr:`other`. + + .. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`maximum` is not supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.maximum(a, b) + tensor([3, 2, 4]) + """ + +@overload +def mean( + input: Tensor, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + mean(input, *, dtype=None) -> Tensor + + .. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + + Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + + Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + + .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + + Returns the mean value of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) + """ + +@overload +def mean( + input: Tensor, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + mean(input, *, dtype=None) -> Tensor + + .. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + + Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + + Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + + .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + + Returns the mean value of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) + """ + +@overload +def median(input: Tensor) -> Tensor: + r""" + median(input) -> Tensor + + Returns the median of the values in :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + + .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size + as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the outputs tensor having 1 fewer dimension than :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) + """ + +@overload +def median( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.median: + r""" + median(input) -> Tensor + + Returns the median of the values in :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + + .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size + as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the outputs tensor having 1 fewer dimension than :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) + """ + +@overload +def min(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.min: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +def minimum( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + minimum(input, other, *, out=None) -> Tensor + + Computes the element-wise minimum of :attr:`input` and :attr:`other`. + + .. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`minimum` is not supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.minimum(a, b) + tensor([1, 0, -1]) + """ + +def miopen_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + exponential_average_factor: _float, + epsilon: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def miopen_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +def miopen_convolution_add_relu( + input: Tensor, + weight: Tensor, + z: Tensor, + alpha: Number | _complex | PySymType | None, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def miopen_convolution_relu( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def miopen_convolution_transpose( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +@overload +def miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +def miopen_depthwise_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +def miopen_rnn( + input: Tensor, + weight: tuple[Tensor, ...] | list[Tensor], + weight_stride0: _int, + hx: Tensor, + cx: Tensor | None, + mode: _int, + hidden_size: _int, + num_layers: _int, + batch_first: _bool, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_sizes: _size, + dropout_state: Tensor | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def mkldnn_adaptive_avg_pool2d( + input: Tensor, + output_size: _int | _size, + *, + out: Tensor | None = None, +) -> Tensor: ... +def mkldnn_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def mkldnn_linear_backward_weights( + grad_output: Tensor, + input: Tensor, + weight: Tensor, + bias_defined: _bool, +) -> tuple[Tensor, Tensor]: ... +def mkldnn_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def mkldnn_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def mkldnn_rnn_layer( + input: Tensor, + weight0: Tensor, + weight1: Tensor, + weight2: Tensor, + weight3: Tensor, + hx_: Tensor, + cx_: Tensor, + reverse: _bool, + batch_sizes: _size, + mode: _int, + hidden_size: _int, + num_layers: _int, + has_biases: _bool, + bidirectional: _bool, + batch_first: _bool, + train: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def mm(input: Tensor, mat2: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + mm(input, mat2, *, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Supports strided and sparse 2-D tensors as inputs, autograd with + respect to strided inputs. + + This operation has support for arguments with :ref:`sparse layouts`. + If :attr:`out` is provided its layout will be used. Otherwise, the result + layout will be deduced from that of :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) + + .. function:: mm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +@overload +def mm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mm(input, mat2, *, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Supports strided and sparse 2-D tensors as inputs, autograd with + respect to strided inputs. + + This operation has support for arguments with :ref:`sparse layouts`. + If :attr:`out` is provided its layout will be used. Otherwise, the result + layout will be deduced from that of :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) + + .. function:: mm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +def mode( + input: Tensor, + dim: _int = -1, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.mode: + r""" + mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the mode + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`, i.e. a value which appears most often + in that row, and ``indices`` is the index location of each mode value found. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2], + ... [0, 3, 0, 0, 2, 0, 1], + ... [2, 2, 2, 0, 0, 0, 3], + ... [2, 2, 3, 0, 1, 1, 0], + ... [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) + """ + +@overload +def moveaxis(input: Tensor, source: _int, destination: _int) -> Tensor: + r""" + moveaxis(input, source, destination) -> Tensor + + Alias for :func:`torch.movedim`. + + This function is equivalent to NumPy's moveaxis function. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def moveaxis(input: Tensor, source: _size, destination: _size) -> Tensor: + r""" + moveaxis(input, source, destination) -> Tensor + + Alias for :func:`torch.movedim`. + + This function is equivalent to NumPy's moveaxis function. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def movedim(input: Tensor, source: _int, destination: _int) -> Tensor: + r""" + movedim(input, source, destination) -> Tensor + + Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` + to the position(s) in :attr:`destination`. + + Other dimensions of :attr:`input` that are not explicitly moved remain in + their original order and appear at the positions not specified in :attr:`destination`. + + Args: + input (Tensor): the input tensor. + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def movedim(input: Tensor, source: _size, destination: _size) -> Tensor: + r""" + movedim(input, source, destination) -> Tensor + + Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` + to the position(s) in :attr:`destination`. + + Other dimensions of :attr:`input` that are not explicitly moved remain in + their original order and appear at the positions not specified in :attr:`destination`. + + Args: + input (Tensor): the input tensor. + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +def msort(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + msort(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Sorts the elements of the :attr:`input` tensor along its first dimension + in ascending order by value. + + .. note:: `torch.msort(t)` is equivalent to `torch.sort(t, dim=0)[0]`. + See also :func:`torch.sort`. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(3, 4) + >>> t + tensor([[-0.1321, 0.4370, -1.2631, -1.1289], + [-2.0527, -1.1250, 0.2275, 0.3077], + [-0.0881, -0.1259, -0.5495, 1.0284]]) + >>> torch.msort(t) + tensor([[-2.0527, -1.1250, -1.2631, -1.1289], + [-0.1321, -0.1259, -0.5495, 0.3077], + [-0.0881, 0.4370, 0.2275, 1.0284]]) + """ + +def mul( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mul(input, other, *, out=None) -> Tensor + + Multiplies :attr:`input` by :attr:`other`. + + + .. math:: + \text{out}_i = \text{input}_i \times \text{other}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to multiply input by. + + Keyword args: + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.2015, -0.4255, 2.6087]) + >>> torch.mul(a, 100) + tensor([ 20.1494, -42.5491, 260.8663]) + + >>> b = torch.randn(4, 1) + >>> b + tensor([[ 1.1207], + [-0.3137], + [ 0.0700], + [ 0.8378]]) + >>> c = torch.randn(1, 4) + >>> c + tensor([[ 0.5146, 0.1216, -0.5244, 2.2382]]) + >>> torch.mul(b, c) + tensor([[ 0.5767, 0.1363, -0.5877, 2.5083], + [-0.1614, -0.0382, 0.1645, -0.7021], + [ 0.0360, 0.0085, -0.0367, 0.1567], + [ 0.4312, 0.1019, -0.4394, 1.8753]]) + """ + +def multinomial( + input: Tensor, + num_samples: _int | SymInt, + replacement: _bool = False, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + multinomial(input, num_samples, replacement=False, *, generator=None, out=None) -> LongTensor + + Returns a tensor where each row contains :attr:`num_samples` indices sampled + from the multinomial (a stricter definition would be multivariate, + refer to :class:`torch.distributions.multinomial.Multinomial` for more details) + probability distribution located in the corresponding row + of tensor :attr:`input`. + + .. note:: + The rows of :attr:`input` do not need to sum to one (in which case we use + the values as weights), but must be non-negative, finite and have + a non-zero sum. + + Indices are ordered from left to right according to when each was sampled + (first samples are placed in first column). + + If :attr:`input` is a vector, :attr:`out` is a vector of size :attr:`num_samples`. + + If :attr:`input` is a matrix with `m` rows, :attr:`out` is an matrix of shape + :math:`(m \times \text{num\_samples})`. + + If replacement is ``True``, samples are drawn with replacement. + + If not, they are drawn without replacement, which means that when a + sample index is drawn for a row, it cannot be drawn again for that row. + + .. note:: + When drawn without replacement, :attr:`num_samples` must be lower than + number of non-zero elements in :attr:`input` (or the min number of non-zero + elements in each row of :attr:`input` if it is a matrix). + + Args: + input (Tensor): the input tensor containing probabilities + num_samples (int): number of samples to draw + replacement (bool, optional): whether to draw with replacement or not + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights + >>> torch.multinomial(weights, 2) + tensor([1, 2]) + >>> torch.multinomial(weights, 5) # ERROR! + RuntimeError: cannot sample n_sample > prob_dist.size(-1) samples without replacement + >>> torch.multinomial(weights, 4, replacement=True) + tensor([ 2, 1, 1, 1]) + """ + +@overload +def multiply( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + multiply(input, other, *, out=None) + + Alias for :func:`torch.mul`. + """ + +@overload +def multiply(input: Tensor, other: Number | _complex | PySymType) -> Tensor: + r""" + multiply(input, other, *, out=None) + + Alias for :func:`torch.mul`. + """ + +def mv(input: Tensor, vec: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + mv(input, vec, *, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`input` and the vector + :attr:`vec`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size :math:`m`, :attr:`out` will be 1-D of size :math:`n`. + + .. note:: This function does not :ref:`broadcast `. + + Args: + input (Tensor): matrix to be multiplied + vec (Tensor): vector to be multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.mv(mat, vec) + tensor([ 1.0404, -0.6361]) + """ + +def mvlgamma( + input: Tensor, + p: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mvlgamma(input, p, *, out=None) -> Tensor + + Alias for :func:`torch.special.multigammaln`. + """ + +def nan_to_num( + input: Tensor, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None) -> Tensor + + Replaces :literal:`NaN`, positive infinity, and negative infinity values in :attr:`input` + with the values specified by :attr:`nan`, :attr:`posinf`, and :attr:`neginf`, respectively. + By default, :literal:`NaN`\ s are replaced with zero, positive infinity is replaced with the + greatest finite value representable by :attr:`input`'s dtype, and negative infinity + is replaced with the least finite value representable by :attr:`input`'s dtype. + + Args: + input (Tensor): the input tensor. + nan (Number, optional): the value to replace :literal:`NaN`\s with. Default is zero. + posinf (Number, optional): if a Number, the value to replace positive infinity values with. + If None, positive infinity values are replaced with the greatest finite value representable by :attr:`input`'s dtype. + Default is None. + neginf (Number, optional): if a Number, the value to replace negative infinity values with. + If None, negative infinity values are replaced with the lowest finite value representable by :attr:`input`'s dtype. + Default is None. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.tensor([float('nan'), float('inf'), -float('inf'), 3.14]) + >>> torch.nan_to_num(x) + tensor([ 0.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0) + tensor([ 2.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0, posinf=1.0) + tensor([ 2.0000e+00, 1.0000e+00, -3.4028e+38, 3.1400e+00]) + """ + +def nan_to_num_( + input: Tensor, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, +) -> Tensor: + r""" + nan_to_num_(input, nan=0.0, posinf=None, neginf=None) -> Tensor + + In-place version of :func:`torch.nan_to_num` + """ + +def nanmean( + input: Tensor, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + nanmean(input, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor + + Computes the mean of all `non-NaN` elements along the specified dimensions. + Input must be floating point or complex. + + This function is identical to :func:`torch.mean` when there are no `NaN` values + in the :attr:`input` tensor. In the presence of `NaN`, :func:`torch.mean` will + propagate the `NaN` to the output whereas :func:`torch.nanmean` will ignore the + `NaN` values (`torch.nanmean(a)` is equivalent to `torch.mean(a[~a.isnan()])`). + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor, either of floating point or complex dtype + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.mean` computes the mean value, propagating `NaN`. + + Example:: + + >>> x = torch.tensor([[torch.nan, 1, 2], [1, 2, 3]]) + >>> x.mean() + tensor(nan) + >>> x.nanmean() + tensor(1.8000) + >>> x.mean(dim=0) + tensor([ nan, 1.5000, 2.5000]) + >>> x.nanmean(dim=0) + tensor([1.0000, 1.5000, 2.5000]) + + # If all elements in the reduced dimensions are NaN then the result is NaN + >>> torch.tensor([torch.nan]).nanmean() + tensor(nan) + """ + +@overload +def nanmedian(input: Tensor) -> Tensor: + r""" + nanmedian(input) -> Tensor + + Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. + When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, + while this function will return the median of the non-``NaN`` elements in :attr:`input`. + If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + + .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values + found in the dimension :attr:`dim`. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has + one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the + median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) + """ + +@overload +def nanmedian( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.nanmedian: + r""" + nanmedian(input) -> Tensor + + Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. + When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, + while this function will return the median of the non-``NaN`` elements in :attr:`input`. + If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + + .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values + found in the dimension :attr:`dim`. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has + one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the + median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) + """ + +@overload +def nanquantile( + input: Tensor, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, + computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did + not exist. If all values in a reduced row are ``NaN`` then the quantiles for + that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) + """ + +@overload +def nanquantile( + input: Tensor, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, + computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did + not exist. If all values in a reduced row are ``NaN`` then the quantiles for + that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) + """ + +def nansum( + input: Tensor, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + nansum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements, treating Not a Numbers (NaNs) as zero. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.tensor([1., 2., float('nan'), 4.]) + >>> torch.nansum(a) + tensor(7.) + + .. function:: nansum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`, treating Not a Numbers (NaNs) as zero. + If :attr:`dim` is a list of dimensions, reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> torch.nansum(torch.tensor([1., float("nan")])) + tensor(1.) + >>> a = torch.tensor([[1, 2], [3., float("nan")]]) + >>> torch.nansum(a) + tensor(6.) + >>> torch.nansum(a, dim=0) + tensor([4., 2.]) + >>> torch.nansum(a, dim=1) + tensor([3., 3.]) + """ + +@overload +def narrow( + input: Tensor, + dim: _int, + start: Tensor, + length: _int | SymInt, +) -> Tensor: + r""" + narrow(input, dim, start, length) -> Tensor + + Returns a new tensor that is a narrowed version of :attr:`input` tensor. The + dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The + returned tensor and :attr:`input` tensor share the same underlying storage. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) + """ + +@overload +def narrow( + input: Tensor, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, +) -> Tensor: + r""" + narrow(input, dim, start, length) -> Tensor + + Returns a new tensor that is a narrowed version of :attr:`input` tensor. The + dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The + returned tensor and :attr:`input` tensor share the same underlying storage. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) + """ + +def narrow_copy( + input: Tensor, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + narrow_copy(input, dim, start, length, *, out=None) -> Tensor + + Same as :meth:`Tensor.narrow` except this returns a copy rather + than shared storage. This is primarily for sparse tensors, which + do not have a shared-storage narrow method. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int): index of the element to start the narrowed dimension from. Can + be negative, which means indexing from the end of `dim` + length (int): length of the narrowed dimension, must be weakly positive + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow_copy(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow_copy(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> s = torch.arange(16).reshape(2, 2, 2, 2).to_sparse(2) + >>> torch.narrow_copy(s, 0, 0, 1) + tensor(indices=tensor([[0, 0], + [0, 1]]), + values=tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]), + size=(1, 2, 2, 2), nnz=2, layout=torch.sparse_coo) + + .. seealso:: + + :func:`torch.narrow` for a non copy variant + """ + +def native_batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +def native_channel_shuffle(input: Tensor, groups: _int | SymInt) -> Tensor: ... +def native_dropout( + input: Tensor, + p: _float, + train: _bool | None, +) -> tuple[Tensor, Tensor]: ... +def native_group_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + N: _int | SymInt, + C: _int | SymInt, + HxW: _int | SymInt, + group: _int, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def native_layer_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None, + bias: Tensor | None, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def native_norm( + input: Tensor, + p: Number | _complex | PySymType | None, + dim: _int | _size, + keepdim: _bool, + dtype: _dtype | None, +) -> Tensor: ... +@overload +def native_norm( + input: Tensor, + p: Number | _complex | PySymType = 2, +) -> Tensor: ... +@overload +def ne( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ne(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \neq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) + """ + +@overload +def ne( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ne(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \neq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) + """ + +def neg(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + neg(input, *, out=None) -> Tensor + + Returns a new tensor with the negative of the elements of :attr:`input`. + + .. math:: + \text{out} = -1 \times \text{input} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.neg(a) + tensor([-0.0090, 0.2262, 0.0682, 0.2866, -0.3940]) + """ + +def neg_(input: Tensor) -> Tensor: + r""" + neg_(input) -> Tensor + + In-place version of :func:`torch.neg` + """ + +def negative(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + negative(input, *, out=None) -> Tensor + + Alias for :func:`torch.neg` + """ + +def negative_(input: Tensor) -> Tensor: + r""" + negative_(input) -> Tensor + + In-place version of :func:`torch.negative` + """ + +def nextafter( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + nextafter(input, other, *, out=None) -> Tensor + + Return the next floating-point value after :attr:`input` towards :attr:`other`, elementwise. + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> eps = torch.finfo(torch.float32).eps + >>> torch.nextafter(torch.tensor([1.0, 2.0]), torch.tensor([2.0, 1.0])) == torch.tensor([eps + 1, 2 - eps]) + tensor([True, True]) + """ + +@overload +def nonzero( + input: Tensor, + *, + as_tuple: Literal[False] = False, + out: Tensor | None = None, +) -> Tensor: + r""" + nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + + .. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + + **When** :attr:`as_tuple` **is** ``False`` **(default)**: + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + **When** :attr:`as_tuple` **is** ``True``: + + Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, + each containing the indices (in that dimension) of all non-zero elements of + :attr:`input` . + + If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` + tensors of size :math:`z`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + As a special case, when :attr:`input` has zero dimensions and a nonzero scalar + value, it is treated as a one-dimensional tensor with one element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (LongTensor, optional): the output tensor containing indices + + Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + + Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) + """ + +@overload +def nonzero( + input: Tensor, + *, + as_tuple: Literal[True], +) -> tuple[Tensor, ...]: + r""" + nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + + .. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + + **When** :attr:`as_tuple` **is** ``False`` **(default)**: + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + **When** :attr:`as_tuple` **is** ``True``: + + Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, + each containing the indices (in that dimension) of all non-zero elements of + :attr:`input` . + + If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` + tensors of size :math:`z`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + As a special case, when :attr:`input` has zero dimensions and a nonzero scalar + value, it is treated as a one-dimensional tensor with one element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (LongTensor, optional): the output tensor containing indices + + Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + + Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) + """ + +def nonzero_static( + input: Tensor, + *, + size: _int | SymInt, + fill_value: _int = -1, + out: Tensor | None = None, +) -> Tensor: + r""" + nonzero_static(input, *, size, fill_value=-1) -> Tensor + + Returns a 2-D tensor where each row is the index for a non-zero value. + The returned Tensor has the same `torch.dtype` as `torch.nonzero()`. + + Args: + input (Tensor): the input tensor. + + Keyword args: + size (int): the size of non-zero elements expected to be included in the out + tensor. Pad the out tensor with `fill_value` if the `size` is larger + than total number of non-zero elements, truncate out tensor if `size` + is smaller. The size must be a non-negative integer. + fill_value (int, optional): the value to fill the output tensor with when `size` is larger + than the total number of non-zero elements. Default is `-1` to represent + invalid index. + + Example:: + + # Example 1: Padding + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 4 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0], + [ 1, 1], + [ -1, -1]], dtype=torch.int64) + + # Example 2: Truncating + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0]], dtype=torch.int64) + + # Example 3: 0 size + >>> input_tensor = torch.tensor([10]) + >>> static_size = 0 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(0, 1), dtype=torch.int64) + + # Example 4: 0 rank input + >>> input_tensor = torch.tensor(10) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(2, 0), dtype=torch.int64) + """ + +def norm_except_dim(v: Tensor, pow: _int = 2, dim: _int = 0) -> Tensor: ... +@overload +def normal( + mean: Tensor, + std: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: Tensor, + std: _float = 1, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: _float, + std: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: _float, + std: _float, + size: Sequence[_int | SymInt], + *, + generator: Generator | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def not_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + not_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ne`. + """ + +@overload +def not_equal( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + not_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ne`. + """ + +@overload +def nuclear_norm( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def nuclear_norm( + input: Tensor, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def numel(self: Tensor) -> _int: + r""" + numel(input: Tensor) -> int + + Returns the total number of elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 2, 3, 4, 5) + >>> torch.numel(a) + 120 + >>> a = torch.zeros(4,4) + >>> torch.numel(a) + 16 + """ + +@overload +def ones( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +@overload +def ones( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +def ones_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the same size as + :attr:`input`. ``torch.ones_like(input)`` is equivalent to + ``torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.ones_like(input, out=output)`` is equivalent to + ``torch.ones(input.size(), out=output)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword arguments: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> input = torch.empty(2, 3) + >>> torch.ones_like(input) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + """ + +def orgqr( + input: Tensor, + input2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + orgqr(input, tau) -> Tensor + + Alias for :func:`torch.linalg.householder_product`. + """ + +def ormqr( + input: Tensor, + input2: Tensor, + input3: Tensor, + left: _bool = True, + transpose: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ormqr(input, tau, other, left=True, transpose=False, *, out=None) -> Tensor + + Computes the matrix-matrix multiplication of a product of Householder matrices with a general matrix. + + Multiplies a :math:`m \times n` matrix `C` (given by :attr:`other`) with a matrix `Q`, + where `Q` is represented using Householder reflectors `(input, tau)`. + See `Representation of Orthogonal or Unitary Matrices`_ for further details. + + If :attr:`left` is `True` then `op(Q)` times `C` is computed, otherwise the result is `C` times `op(Q)`. + When :attr:`left` is `True`, the implicit matrix `Q` has size :math:`m \times m`. + It has size :math:`n \times n` otherwise. + If :attr:`transpose` is `True` then `op` is the conjugate transpose operation, otherwise it's a no-op. + + Supports inputs of float, double, cfloat and cdouble dtypes. + Also supports batched inputs, and, if the input is batched, the output is batched with the same dimensions. + + .. seealso:: + :func:`torch.geqrf` can be used to form the Householder representation `(input, tau)` of matrix `Q` + from the QR decomposition. + + .. note:: + This function supports backward but it is only fast when ``(input, tau)`` do not require gradients + and/or ``tau.size(-1)`` is very small. + `` + + Args: + input (Tensor): tensor of shape `(*, mn, k)` where `*` is zero or more batch dimensions + and `mn` equals to `m` or `n` depending on the :attr:`left`. + tau (Tensor): tensor of shape `(*, min(mn, k))` where `*` is zero or more batch dimensions. + other (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions. + left (bool): controls the order of multiplication. + transpose (bool): controls whether the matrix `Q` is conjugate transposed or not. + + Keyword args: + out (Tensor, optional): the output Tensor. Ignored if `None`. Default: `None`. + + .. _Representation of Orthogonal or Unitary Matrices: + https://www.netlib.org/lapack/lug/node128.html + """ + +def outer( + input: Tensor, + vec2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + outer(input, vec2, *, out=None) -> Tensor + + Outer product of :attr:`input` and :attr:`vec2`. + If :attr:`input` is a vector of size :math:`n` and :attr:`vec2` is a vector of + size :math:`m`, then :attr:`out` must be a matrix of size :math:`(n \times m)`. + + .. note:: This function does not :ref:`broadcast `. + + Args: + input (Tensor): 1-D input vector + vec2 (Tensor): 1-D input vector + + Keyword args: + out (Tensor, optional): optional output matrix + + Example:: + + >>> v1 = torch.arange(1., 5.) + >>> v2 = torch.arange(1., 4.) + >>> torch.outer(v1, v2) + tensor([[ 1., 2., 3.], + [ 2., 4., 6.], + [ 3., 6., 9.], + [ 4., 8., 12.]]) + """ + +def pairwise_distance( + x1: Tensor, + x2: Tensor, + p: _float = 2, + eps: _float = 1e-06, + keepdim: _bool = False, +) -> Tensor: ... +def pdist(input: Tensor, p: _float = 2) -> Tensor: ... +def permute(input: Tensor, dims: _size) -> Tensor: + r""" + permute(input, dims) -> Tensor + + Returns a view of the original tensor :attr:`input` with its dimensions permuted. + + Args: + input (Tensor): the input tensor. + dims (torch.Size, tuple of int or list of int): the desired ordering of dimensions. + + Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> torch.permute(x, (2, 0, 1)).size() + torch.Size([5, 2, 3]) + """ + +def permute_copy( + input: Tensor, + dims: _size, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.permute`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def pinverse(input: Tensor, rcond: _float = 1e-15) -> Tensor: + r""" + pinverse(input, rcond=1e-15) -> Tensor + + Alias for :func:`torch.linalg.pinv` + """ + +def pixel_shuffle(input: Tensor, upscale_factor: _int) -> Tensor: ... +def pixel_unshuffle(input: Tensor, downscale_factor: _int) -> Tensor: ... +def poisson(input: Tensor, generator: Generator | None = None) -> Tensor: + r""" + poisson(input, generator=None) -> Tensor + + Returns a tensor of the same size as :attr:`input` with each element + sampled from a Poisson distribution with rate parameter given by the corresponding + element in :attr:`input` i.e., + + .. math:: + \text{out}_i \sim \text{Poisson}(\text{input}_i) + + :attr:`input` must be non-negative. + + Args: + input (Tensor): the input tensor containing the rates of the Poisson distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + + Example:: + + >>> rates = torch.rand(4, 4) * 5 # rate parameter between 0 and 5 + >>> torch.poisson(rates) + tensor([[9., 1., 3., 5.], + [8., 6., 6., 0.], + [0., 4., 5., 3.], + [2., 1., 4., 2.]]) + """ + +def poisson_nll_loss( + input: Tensor, + target: Tensor, + log_input: _bool, + full: _bool, + eps: _float, + reduction: _int, +) -> Tensor: ... +def polar( + abs: Tensor, + angle: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + polar(abs, angle, *, out=None) -> Tensor + + Constructs a complex tensor whose elements are Cartesian coordinates + corresponding to the polar coordinates with absolute value :attr:`abs` and angle + :attr:`angle`. + + .. math:: + \text{out} = \text{abs} \cdot \cos(\text{angle}) + \text{abs} \cdot \sin(\text{angle}) \cdot j + + .. note:: + `torch.polar` is similar to + `std::polar `_ + and does not compute the polar decomposition + of a complex tensor like Python's `cmath.polar` and SciPy's `linalg.polar` do. + The behavior of this function is undefined if `abs` is negative or NaN, or if `angle` is + infinite. + + + Args: + abs (Tensor): The absolute value the complex tensor. Must be float or double. + angle (Tensor): The angle of the complex tensor. Must be same dtype as + :attr:`abs`. + + Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + + Example:: + + >>> import numpy as np + >>> abs = torch.tensor([1, 2], dtype=torch.float64) + >>> angle = torch.tensor([np.pi / 2, 5 * np.pi / 4], dtype=torch.float64) + >>> z = torch.polar(abs, angle) + >>> z + tensor([(0.0000+1.0000j), (-1.4142-1.4142j)], dtype=torch.complex128) + """ + +def polygamma( + n: _int, + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + polygamma(n, input, *, out=None) -> Tensor + + Alias for :func:`torch.special.polygamma`. + """ + +def positive(input: Tensor) -> Tensor: + r""" + positive(input) -> Tensor + + Returns :attr:`input`. + Throws a runtime error if :attr:`input` is a bool tensor. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> t = torch.randn(5) + >>> t + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.positive(t) + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + """ + +@overload +def pow( + input: Tensor, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +@overload +def pow( + self: Number | _complex | PySymType, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +@overload +def pow( + input: Tensor, + exponent: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +def prelu(input: Tensor, weight: Tensor) -> Tensor: ... +@overload +def prod(input: Tensor, *, dtype: _dtype | None = None) -> Tensor: + r""" + prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + + Returns the product of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + + .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the product of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensor having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) + """ + +@overload +def prod( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + + Returns the product of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + + .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the product of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensor having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) + """ + +def promote_types(type1: _dtype, type2: _dtype) -> _dtype: + r""" + promote_types(type1, type2) -> dtype + + Returns the :class:`torch.dtype` with the smallest size and scalar kind that is + not smaller nor of lower kind than either `type1` or `type2`. See type promotion + :ref:`documentation ` for more information on the type + promotion logic. + + Args: + type1 (:class:`torch.dtype`) + type2 (:class:`torch.dtype`) + + Example:: + + >>> torch.promote_types(torch.int32, torch.float32) + torch.float32 + >>> torch.promote_types(torch.uint8, torch.long) + torch.long + """ + +def put( + input: Tensor, + index: Tensor, + source: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def q_per_channel_axis(input: Tensor) -> _int: ... +def q_per_channel_scales(input: Tensor) -> Tensor: ... +def q_per_channel_zero_points(input: Tensor) -> Tensor: ... +def q_scale(input: Tensor) -> _float: ... +def q_zero_point(input: Tensor) -> _int: ... +@overload +def quantile( + input: Tensor, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +@overload +def quantile( + input: Tensor, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +def quantize_per_channel( + input: Tensor, + scales: Tensor, + zero_points: Tensor, + axis: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor + + Converts a float tensor to a per-channel quantized tensor with given scales and zero points. + + Arguments: + input (Tensor): float tensor to quantize + scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)`` + zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)`` + axis (int): dimension on which apply per-channel quantization + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor + + Example:: + + >>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]]) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8) + tensor([[-1., 0.], + [ 1., 2.]], size=(2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_channel_affine, + scale=tensor([0.1000, 0.0100], dtype=torch.float64), + zero_point=tensor([10, 0]), axis=0) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr() + tensor([[ 0, 10], + [100, 200]], dtype=torch.uint8) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: _float, + zero_point: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + tensors: tuple[Tensor, ...] | list[Tensor], + scales: Tensor, + zero_points: Tensor, + dtype: _dtype, +) -> tuple[Tensor, ...]: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +def quantize_per_tensor_dynamic( + input: Tensor, + dtype: _dtype, + reduce_range: _bool, +) -> Tensor: + r""" + quantize_per_tensor_dynamic(input, dtype, reduce_range) -> Tensor + + Converts a float tensor to a quantized tensor with scale and zero_point calculated + dynamically based on the input. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8`` + reduce_range (bool): a flag to indicate whether to reduce the range of quantized + data by 1 bit, it's required to avoid instruction overflow for some hardwares + + Returns: + Tensor: A newly (dynamically) quantized tensor + + Example:: + + >>> t = torch.quantize_per_tensor_dynamic(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.quint8, False) + >>> print(t) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.011764705882352941, + zero_point=85) + >>> t.int_repr() + tensor([ 0, 85, 170, 255], dtype=torch.uint8) + """ + +def quantized_batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + mean: Tensor, + var: Tensor, + eps: _float, + output_scale: _float, + output_zero_point: _int, +) -> Tensor: + r""" + quantized_batch_norm(input, weight=None, bias=None, mean, var, eps, output_scale, output_zero_point) -> Tensor + + Applies batch normalization on a 4D (NCHW) quantized tensor. + + .. math:: + + y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta + + Arguments: + input (Tensor): quantized tensor + weight (Tensor): float tensor that corresponds to the gamma, size C + bias (Tensor): float tensor that corresponds to the beta, size C + mean (Tensor): float mean value in batch normalization, size C + var (Tensor): float tensor for variance, size C + eps (float): a value added to the denominator for numerical stability. + output_scale (float): output quantized tensor scale + output_zero_point (int): output quantized tensor zero_point + + Returns: + Tensor: A quantized tensor with batch normalization applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_batch_norm(qx, torch.ones(2), torch.zeros(2), torch.rand(2), torch.rand(2), 0.00001, 0.2, 2) + tensor([[[[-0.2000, -0.2000], + [ 1.6000, -0.2000]], + + [[-0.4000, -0.4000], + [-0.4000, 0.6000]]], + + + [[[-0.2000, -0.2000], + [-0.2000, -0.2000]], + + [[ 0.6000, -0.4000], + [ 0.6000, -0.4000]]]], size=(2, 2, 2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=2) + """ + +def quantized_gru_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> Tensor: ... +def quantized_lstm_cell( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> tuple[Tensor, Tensor]: ... +def quantized_max_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: + r""" + quantized_max_pool1d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + + Applies a 1D max pooling over an input quantized tensor composed of several input planes. + + Arguments: + input (Tensor): quantized tensor + kernel_size (list of int): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + + Returns: + Tensor: A quantized tensor with max_pool1d applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool1d(qx, [2]) + tensor([[0.0000], + [1.5000]], size=(2, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) + """ + +def quantized_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: + r""" + quantized_max_pool2d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + + Applies a 2D max pooling over an input quantized tensor composed of several input planes. + + Arguments: + input (Tensor): quantized tensor + kernel_size (``list of int``): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + + Returns: + Tensor: A quantized tensor with max_pool2d applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool2d(qx, [2,2]) + tensor([[[[1.5000]], + + [[1.5000]]], + + + [[[0.0000]], + + [[0.0000]]]], size=(2, 2, 1, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) + """ + +def quantized_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def quantized_rnn_relu_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> Tensor: ... +def quantized_rnn_tanh_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> Tensor: ... +def rad2deg(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + rad2deg(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with each of the elements of :attr:`input` + converted from angles in radians to degrees. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([[3.142, -3.142], [6.283, -6.283], [1.570, -1.570]]) + >>> torch.rad2deg(a) + tensor([[ 180.0233, -180.0233], + [ 359.9894, -359.9894], + [ 89.9544, -89.9544]]) + """ + +def rad2deg_(input: Tensor) -> Tensor: + r""" + rad2deg_(input) -> Tensor + + In-place version of :func:`torch.rad2deg` + """ + +@overload +def rand( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def rand_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint( + low: _int, + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randperm( + n: _int | SymInt, + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +@overload +def randperm( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +def range( + start: Number, + end: Number, + step: Number = 1, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1` + with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is + the gap between two values in the tensor. + + .. math:: + \text{out}_{i+1} = \text{out}_i + \text{step}. + + .. warning:: + This function is deprecated and will be removed in a future release because its behavior is inconsistent with + Python's range builtin. Instead, use :func:`torch.arange`, which produces values in [start, end). + + Args: + start (float, optional): the starting value for the set of points. Default: ``0``. + end (float): the ending value for the set of points + step (float, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.range(1, 4) + tensor([ 1., 2., 3., 4.]) + >>> torch.range(1, 4, 0.5) + tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000]) + """ + +def ravel(input: Tensor) -> Tensor: + r""" + ravel(input) -> Tensor + + Return a contiguous flattened tensor. A copy is made only if needed. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.ravel(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + """ + +def real(input: Tensor) -> Tensor: + r""" + real(input) -> Tensor + + Returns a new tensor containing real values of the :attr:`self` tensor. + The returned tensor and :attr:`self` share the same underlying storage. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + """ + +def reciprocal(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + reciprocal(input, *, out=None) -> Tensor + + Returns a new tensor with the reciprocal of the elements of :attr:`input` + + .. math:: + \text{out}_{i} = \frac{1}{\text{input}_{i}} + + .. note:: + Unlike NumPy's reciprocal, torch.reciprocal supports integral inputs. Integral + inputs to reciprocal are automatically :ref:`promoted ` to + the default scalar type. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.4595, -2.1219, -1.4314, 0.7298]) + >>> torch.reciprocal(a) + tensor([-2.1763, -0.4713, -0.6986, 1.3702]) + """ + +def reciprocal_(input: Tensor) -> Tensor: + r""" + reciprocal_(input) -> Tensor + + In-place version of :func:`torch.reciprocal` + """ + +def relu(input: Tensor) -> Tensor: ... +def relu_(input: Tensor) -> Tensor: ... +@overload +def remainder( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +@overload +def remainder(self: Number | _complex | PySymType, other: Tensor) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +@overload +def remainder( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +def renorm( + input: Tensor, + p: Number | _complex | PySymType, + dim: _int, + maxnorm: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + renorm(input, p, dim, maxnorm, *, out=None) -> Tensor + + Returns a tensor where each sub-tensor of :attr:`input` along dimension + :attr:`dim` is normalized such that the `p`-norm of the sub-tensor is lower + than the value :attr:`maxnorm` + + .. note:: If the norm of a row is lower than `maxnorm`, the row is unchanged + + Args: + input (Tensor): the input tensor. + p (float): the power for the norm computation + dim (int): the dimension to slice over to get the sub-tensors + maxnorm (float): the maximum norm to keep each sub-tensor under + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.ones(3, 3) + >>> x[1].fill_(2) + tensor([ 2., 2., 2.]) + >>> x[2].fill_(3) + tensor([ 3., 3., 3.]) + >>> x + tensor([[ 1., 1., 1.], + [ 2., 2., 2.], + [ 3., 3., 3.]]) + >>> torch.renorm(x, 1, 0, 5) + tensor([[ 1.0000, 1.0000, 1.0000], + [ 1.6667, 1.6667, 1.6667], + [ 1.6667, 1.6667, 1.6667]]) + """ + +@overload +def repeat_interleave( + input: Tensor, + repeats: Tensor, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +@overload +def repeat_interleave( + repeats: Tensor, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +@overload +def repeat_interleave( + input: Tensor, + repeats: _int | SymInt, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +def reshape(input: Tensor, shape: Sequence[_int | SymInt]) -> Tensor: + r""" + reshape(input, shape) -> Tensor + + Returns a tensor with the same data and number of elements as :attr:`input`, + but with the specified shape. When possible, the returned tensor will be a view + of :attr:`input`. Otherwise, it will be a copy. Contiguous inputs and inputs + with compatible strides can be reshaped without copying, but you should not + depend on the copying vs. viewing behavior. + + See :meth:`torch.Tensor.view` on when it is possible to return a view. + + A single dimension may be -1, in which case it's inferred from the remaining + dimensions and the number of elements in :attr:`input`. + + Args: + input (Tensor): the tensor to be reshaped + shape (tuple of int): the new shape + + Example:: + + >>> a = torch.arange(4.) + >>> torch.reshape(a, (2, 2)) + tensor([[ 0., 1.], + [ 2., 3.]]) + >>> b = torch.tensor([[0, 1], [2, 3]]) + >>> torch.reshape(b, (-1,)) + tensor([ 0, 1, 2, 3]) + """ + +def resize_as_( + input: Tensor, + the_template: Tensor, + *, + memory_format: memory_format | None = None, +) -> Tensor: ... +def resize_as_sparse_(input: Tensor, the_template: Tensor) -> Tensor: ... +def resolve_conj(input: Tensor) -> Tensor: + r""" + resolve_conj(input) -> Tensor + + Returns a new tensor with materialized conjugation if :attr:`input`'s conjugate bit is set to `True`, + else returns :attr:`input`. The output tensor will always have its conjugate bit set to `False`. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> y.is_conj() + True + >>> z = y.resolve_conj() + >>> z + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + >>> z.is_conj() + False + """ + +def resolve_neg(input: Tensor) -> Tensor: + r""" + resolve_neg(input) -> Tensor + + Returns a new tensor with materialized negation if :attr:`input`'s negative bit is set to `True`, + else returns :attr:`input`. The output tensor will always have its negative bit set to `False`. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> z = y.imag + >>> z.is_neg() + True + >>> out = z.resolve_neg() + >>> out + tensor([-1., -2., 3.]) + >>> out.is_neg() + False + """ + +@overload +def result_type(tensor: Tensor, other: Tensor) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type( + scalar: Number | _complex | PySymType, + tensor: Tensor, +) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type( + tensor: Tensor, + other: Number | _complex | PySymType, +) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type( + scalar1: Number | _complex | PySymType, + scalar2: Number | _complex | PySymType, +) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +def rms_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None = None, + eps: _float | None = None, +) -> Tensor: ... +@overload +def rnn_relu( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def rnn_relu( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def rnn_relu_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +@overload +def rnn_tanh( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def rnn_tanh( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def rnn_tanh_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +def roll( + input: Tensor, + shifts: _int | SymInt | Sequence[_int | SymInt], + dims: _int | _size = (), +) -> Tensor: + r""" + roll(input, shifts, dims=None) -> Tensor + + Roll the tensor :attr:`input` along the given dimension(s). Elements that are + shifted beyond the last position are re-introduced at the first position. If + :attr:`dims` is `None`, the tensor will be flattened before rolling and then + restored to the original shape. + + Args: + input (Tensor): the input tensor. + shifts (int or tuple of ints): The number of places by which the elements + of the tensor are shifted. If shifts is a tuple, dims must be a tuple of + the same size, and each dimension will be rolled by the corresponding + value + dims (int or tuple of ints): Axis along which to roll + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2) + >>> x + tensor([[1, 2], + [3, 4], + [5, 6], + [7, 8]]) + >>> torch.roll(x, 1) + tensor([[8, 1], + [2, 3], + [4, 5], + [6, 7]]) + >>> torch.roll(x, 1, 0) + tensor([[7, 8], + [1, 2], + [3, 4], + [5, 6]]) + >>> torch.roll(x, -1, 0) + tensor([[3, 4], + [5, 6], + [7, 8], + [1, 2]]) + >>> torch.roll(x, shifts=(2, 1), dims=(0, 1)) + tensor([[6, 5], + [8, 7], + [2, 1], + [4, 3]]) + """ + +def rot90(input: Tensor, k: _int = 1, dims: _size = (0, 1)) -> Tensor: + r""" + rot90(input, k=1, dims=(0, 1)) -> Tensor + + Rotate an n-D tensor by 90 degrees in the plane specified by dims axis. + Rotation direction is from the first towards the second axis if k > 0, and from the second towards the first for k < 0. + + Args: + input (Tensor): the input tensor. + k (int): number of times to rotate. Default value is 1 + dims (a list or tuple): axis to rotate. Default value is [0, 1] + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.rot90(x, 1, [0, 1]) + tensor([[1, 3], + [0, 2]]) + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.rot90(x, 1, [1, 2]) + tensor([[[1, 3], + [0, 2]], + + [[5, 7], + [4, 6]]]) + """ + +@overload +def round(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + round(input, *, decimals=0, out=None) -> Tensor + + Rounds elements of :attr:`input` to the nearest integer. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + The return type of output is same as that of input's dtype. + + .. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + + .. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + + Args: + input (Tensor): the input tensor. + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) + """ + +@overload +def round( + input: Tensor, + *, + decimals: _int, + out: Tensor | None = None, +) -> Tensor: + r""" + round(input, *, decimals=0, out=None) -> Tensor + + Rounds elements of :attr:`input` to the nearest integer. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + The return type of output is same as that of input's dtype. + + .. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + + .. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + + Args: + input (Tensor): the input tensor. + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) + """ + +@overload +def round_(input: Tensor) -> Tensor: + r""" + round_(input, *, decimals=0) -> Tensor + + In-place version of :func:`torch.round` + """ + +@overload +def round_(input: Tensor, *, decimals: _int) -> Tensor: + r""" + round_(input, *, decimals=0) -> Tensor + + In-place version of :func:`torch.round` + """ + +def row_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def row_stack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + row_stack(tensors, *, out=None) -> Tensor + + Alias of :func:`torch.vstack`. + """ + +def rrelu( + input: Tensor, + lower: Number | _complex | PySymType = 0.125, + upper: Number | _complex | PySymType = 0.3333333333333333, + training: _bool = False, + generator: Generator | None = None, +) -> Tensor: ... +def rrelu_( + input: Tensor, + lower: Number | _complex | PySymType = 0.125, + upper: Number | _complex | PySymType = 0.3333333333333333, + training: _bool = False, + generator: Generator | None = None, +) -> Tensor: ... +def rsqrt(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + rsqrt(input, *, out=None) -> Tensor + + Returns a new tensor with the reciprocal of the square-root of each of + the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \frac{1}{\sqrt{\text{input}_{i}}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.0370, 0.2970, 1.5420, -0.9105]) + >>> torch.rsqrt(a) + tensor([ nan, 1.8351, 0.8053, nan]) + """ + +def rsqrt_(input: Tensor) -> Tensor: + r""" + rsqrt_(input) -> Tensor + + In-place version of :func:`torch.rsqrt` + """ + +@overload +def rsub( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def rsub( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +def saddmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number = 1, + alpha: Number = 1, + out: Tensor | None = None, +) -> Tensor: ... +def scalar_tensor( + s: Number | _complex | PySymType, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + reduce: str, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + *, + reduce: str, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +def scatter_add( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter_add(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_add_` + """ + +def scatter_reduce( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + reduce: str, + *, + include_self: _bool = True, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter_reduce(input, dim, index, src, reduce, *, include_self=True) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` + """ + +@overload +def searchsorted( + sorted_sequence: Tensor, + input: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, + side: str | None = None, + sorter: Tensor | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + + Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the + corresponding values in :attr:`values` were inserted before the indices, when sorted, the order + of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. + Return a new tensor with the same size as :attr:`values`. More formally, + the returned index satisfies the following rules: + + .. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + + Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted. PyTorch does not validate this condition when :attr:`sorter` is + not provided, and the behavior is undefined if the sequence is not sorted. + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + + Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) + """ + +@overload +def searchsorted( + sorted_sequence: Tensor, + self: Number | _complex | PySymType, + *, + out_int32: _bool = False, + right: _bool = False, + side: str | None = None, + sorter: Tensor | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + + Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the + corresponding values in :attr:`values` were inserted before the indices, when sorted, the order + of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. + Return a new tensor with the same size as :attr:`values`. More formally, + the returned index satisfies the following rules: + + .. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + + Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted. PyTorch does not validate this condition when :attr:`sorter` is + not provided, and the behavior is undefined if the sequence is not sorted. + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + + Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) + """ + +def segment_reduce( + data: Tensor, + reduce: str, + *, + lengths: Tensor | None = None, + indices: Tensor | None = None, + offsets: Tensor | None = None, + axis: _int = 0, + unsafe: _bool = False, + initial: Number | _complex | PySymType | None = None, +) -> Tensor: + r""" + segment_reduce(data: Tensor, reduce: str, *, lengths: Tensor | None = None, indices: Tensor | None = None, offsets: Tensor | None = None, axis: _int = 0, unsafe: _bool = False, initial: Number | _complex | None = None) -> Tensor # noqa: B950 + + Perform a segment reduction operation on the input tensor along the specified axis. + + Args: + data (Tensor): The input tensor on which the segment reduction operation will be performed. + reduce (str): The type of reduction operation. Supported values are ``sum``, ``mean``, ``max``, ``min``, ``prod``. + + Keyword args: + lengths (Tensor, optional): Length of each segment. Default: ``None``. + offsets (Tensor, optional): Offset of each segment. Default: ``None``. + axis (int, optional): The axis perform reduction. Default: ``0``. + unsafe (bool, optional): Skip validation If `True`. Default: ``False``. + initial (Number, optional): The initial value for the reduction operation. Default: ``None``. + + Example:: + + >>> data = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=torch.float32, device='cuda') + >>> lengths = torch.tensor([2, 1], device='cuda') + >>> torch.segment_reduce(data, 'max', lengths=lengths) + tensor([[ 5., 6., 7., 8.], + [ 9., 10., 11., 12.]], device='cuda:0') + """ + +def select(input: Tensor, dim: _int, index: _int | SymInt) -> Tensor: + r""" + select(input, dim, index) -> Tensor + + Slices the :attr:`input` tensor along the selected dimension at the given index. + This function returns a view of the original tensor with the given dimension removed. + + .. note:: If :attr:`input` is a sparse tensor and returning a view of + the tensor is not possible, a RuntimeError exception is + raised. In this is the case, consider using + :func:`torch.select_copy` function. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to slice + index (int): the index to select with + + .. note:: + + :meth:`select` is equivalent to slicing. For example, + ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and + ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. + """ + +def select_copy( + input: Tensor, + dim: _int, + index: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.select`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def select_scatter( + input: Tensor, + src: Tensor, + dim: _int, + index: _int | SymInt, +) -> Tensor: + r""" + select_scatter(input, src, dim, index) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` at the given index. + This function returns a tensor with fresh storage; it does not create a view. + + + Args: + input (Tensor): the input tensor. + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into. + index (int): the index to select with + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.select(input, dim, index)`` + + Example:: + + >>> a = torch.zeros(2, 2) + >>> b = torch.ones(2) + >>> a.select_scatter(b, 0, 0) + tensor([[1., 1.], + [0., 0.]]) + """ + +def selu(input: Tensor) -> Tensor: ... +def selu_(input: Tensor) -> Tensor: ... +def set_flush_denormal(mode: _bool) -> _bool: + r""" + set_flush_denormal(mode) -> bool + + Disables denormal floating numbers on CPU. + + Returns ``True`` if your system supports flushing denormal numbers and it + successfully configures flush denormal mode. :meth:`~torch.set_flush_denormal` + is supported on x86 architectures supporting SSE3 and AArch64 architecture. + + Args: + mode (bool): Controls whether to enable flush denormal mode or not + + Example:: + + >>> torch.set_flush_denormal(True) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor([ 0.], dtype=torch.float64) + >>> torch.set_flush_denormal(False) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor(9.88131e-324 * + [ 1.0000], dtype=torch.float64) + """ + +def set_num_interop_threads(num: _int) -> None: + r""" + set_num_interop_threads(int) + + Sets the number of threads used for interop parallelism + (e.g. in JIT interpreter) on CPU. + + .. warning:: + Can only be called once and before any inter-op parallel work + is started (e.g. JIT execution). + """ + +def set_num_threads(num: _int) -> None: + r""" + set_num_threads(int) + + Sets the number of threads used for intraop parallelism on CPU. + + .. warning:: + To ensure that the correct number of threads is used, set_num_threads + must be called before running eager, JIT or autograd code. + """ + +def sgn(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sgn(input, *, out=None) -> Tensor + + This function is an extension of torch.sign() to complex tensors. + It computes a new tensor whose elements have + the same angles as the corresponding elements of :attr:`input` and + absolute values (i.e. magnitudes) of one for complex tensors and + is equivalent to torch.sign() for non-complex tensors. + + .. math:: + \text{out}_{i} = \begin{cases} + 0 & |\text{{input}}_i| == 0 \\ + \frac{{\text{{input}}_i}}{|{\text{{input}}_i}|} & \text{otherwise} + \end{cases} + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([3+4j, 7-24j, 0, 1+2j]) + >>> t.sgn() + tensor([0.6000+0.8000j, 0.2800-0.9600j, 0.0000+0.0000j, 0.4472+0.8944j]) + """ + +def sigmoid(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sigmoid(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.expit`. + """ + +def sigmoid_(input: Tensor) -> Tensor: + r""" + sigmoid_(input) -> Tensor + + In-place version of :func:`torch.sigmoid` + """ + +def sign(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sign(input, *, out=None) -> Tensor + + Returns a new tensor with the signs of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \operatorname{sgn}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> a + tensor([ 0.7000, -1.2000, 0.0000, 2.3000]) + >>> torch.sign(a) + tensor([ 1., -1., 0., 1.]) + """ + +def signbit(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + signbit(input, *, out=None) -> Tensor + + Tests if each element of :attr:`input` has its sign bit set or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> torch.signbit(a) + tensor([ False, True, False, False]) + >>> a = torch.tensor([-0.0, 0.0]) + >>> torch.signbit(a) + tensor([ True, False]) + + .. note:: + signbit handles signed zeros, so negative zero (-0) returns True. + """ + +def sin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sin(input, *, out=None) -> Tensor + + Returns a new tensor with the sine of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \sin(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5461, 0.1347, -2.7266, -0.2746]) + >>> torch.sin(a) + tensor([-0.5194, 0.1343, -0.4032, -0.2711]) + """ + +def sin_(input: Tensor) -> Tensor: + r""" + sin_(input) -> Tensor + + In-place version of :func:`torch.sin` + """ + +def sinc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sinc(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.sinc`. + """ + +def sinc_(input: Tensor) -> Tensor: + r""" + sinc_(input) -> Tensor + + In-place version of :func:`torch.sinc` + """ + +def sinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sinh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic sine of the elements of + :attr:`input`. + + .. math:: + \text{out}_{i} = \sinh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.5380, -0.8632, -0.1265, 0.9399]) + >>> torch.sinh(a) + tensor([ 0.5644, -0.9744, -0.1268, 1.0845]) + """ + +def sinh_(input: Tensor) -> Tensor: + r""" + sinh_(input) -> Tensor + + In-place version of :func:`torch.sinh` + """ + +def slice_copy( + input: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.slice`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def slice_inverse( + input: Tensor, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, +) -> Tensor: ... +def slice_scatter( + input: Tensor, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + slice_scatter(input, src, dim=0, start=None, end=None, step=1) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` at the given + dimension. + This function returns a tensor with fresh storage; it does not create a view. + + + Args: + input (Tensor): the input tensor. + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into + start (Optional[int]): the start index of where to insert the slice + end (Optional[int]): the end index of where to insert the slice + step (int): the how many elements to skip in + + Example:: + + >>> a = torch.zeros(8, 8) + >>> b = torch.ones(2, 8) + >>> a.slice_scatter(b, start=6) + tensor([[0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [1., 1., 1., 1., 1., 1., 1., 1.], + [1., 1., 1., 1., 1., 1., 1., 1.]]) + + >>> b = torch.ones(8, 2) + >>> a.slice_scatter(b, dim=1, start=2, end=6, step=2) + tensor([[0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.]]) + """ + +def slogdet( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.slogdet: + r""" + slogdet(input) -> (Tensor, Tensor) + + Alias for :func:`torch.linalg.slogdet` + """ + +def smm(input: Tensor, mat2: Tensor) -> Tensor: + r""" + smm(input, mat) -> Tensor + + Performs a matrix multiplication of the sparse matrix :attr:`input` + with the dense matrix :attr:`mat`. + + Args: + input (Tensor): a sparse matrix to be matrix multiplied + mat (Tensor): a dense matrix to be matrix multiplied + """ + +def softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + softmax(input, dim, *, dtype=None) -> Tensor + + Alias for :func:`torch.nn.functional.softmax`. + """ + +@overload +def sort( + input: Tensor, + *, + stable: _bool | None, + dim: _int = -1, + descending: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +@overload +def sort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +def sparse_bsc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSC (Block Compressed Sparse + Column)) ` with specified 2-dimensional blocks at the + given :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in BSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncolblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + index in values and row_indices depending on where the given + column starts. Each successive number in the tensor subtracted + by the number before it denotes the number of elements in a + given column. + row_indices (array_like): Row block coordinates of each block in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial blocks for the tensor. Can be a list, + tuple, NumPy ``ndarray``, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 1, 2] + >>> row_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 1, 2]), + row_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsc) + """ + +def sparse_bsr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSR (Block Compressed Sparse Row)) + ` with specified 2-dimensional blocks at the given + :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix + multiplication operations in BSR format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrowblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + block index in values and col_indices depending on where the + given row block starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + blocks in a given row. + col_indices (array_like): Column block coordinates of each block + in values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize == + values.shape[1:3]``. If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 1, 2] + >>> col_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 1, 2]), + col_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsr) + """ + +def sparse_compressed_tensor( + compressed_indices: Tensor | list, + plain_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_compressed_tensor(compressed_indices, plain_indices, values, size=None, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in Compressed Sparse format - CSR, + CSC, BSR, or BSC - ` with specified values at + the given :attr:`compressed_indices` and :attr:`plain_indices`. Sparse + matrix multiplication operations in Compressed Sparse format are + typically faster than that for sparse tensors in COO format. Make you + have a look at :ref:`the note on the data type of the indices + `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + compressed_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, compressed_dim_size + 1)``. The last element of + each batch is the number of non-zero elements or blocks. This + tensor encodes the index in ``values`` and ``plain_indices`` + depending on where the given compressed dimension (row or + column) starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + elements or blocks in a given compressed dimension. + plain_indices (array_like): Plain dimension (column or row) + coordinates of each element or block in values. (B+1)-dimensional + tensor with the same length as values. + + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types. that + represents a (1+K)-dimensional (for CSR and CSC layouts) or + (1+2+K)-dimensional tensor (for BSR and BSC layouts) where + ``K`` is the number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize[0] == + blocksize[1] == 1`` for CSR and CSC formats. If not provided, + the size will be inferred as the minimum size big enough to + hold all non-zero elements or blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + layout (:class:`torch.layout`, required): the desired layout of + returned tensor: :attr:`torch.sparse_csr`, + :attr:`torch.sparse_csc`, :attr:`torch.sparse_bsr`, or + :attr:`torch.sparse_bsc`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> compressed_indices = [0, 2, 4] + >>> plain_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_compressed_tensor(torch.tensor(compressed_indices, dtype=torch.int64), + ... torch.tensor(plain_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double, layout=torch.sparse_csr) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def sparse_coo_tensor( + indices: Tensor, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, + is_coalesced: _bool | None = None, +) -> Tensor: + r""" + sparse_coo_tensor(indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) -> Tensor + + Constructs a :ref:`sparse tensor in COO(rdinate) format + ` with specified values at the given + :attr:`indices`. + + .. note:: + + This function returns an :ref:`uncoalesced tensor + ` when :attr:`is_coalesced` is + unspecified or ``None``. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + indices (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor` + internally. The indices are the coordinates of the non-zero values in the matrix, and thus + should be two-dimensional where the first dimension is the number of tensor dimensions and + the second dimension is the number of non-zero values. + values (array_like): Initial values for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not + provided the size will be inferred as the minimum size big enough to hold all non-zero + elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if None, infers data type from :attr:`values`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + is_coalesced (bool, optional): When``True``, the caller is + responsible for providing tensor indices that correspond to a + coalesced tensor. If the :attr:`check_invariants` flag is + False, no error will be raised if the prerequisites are not + met and this will lead to silently incorrect results. To force + coalescing please use :meth:`coalesce` on the resulting + Tensor. + Default: None: except for trivial cases (e.g. nnz < 2) the + resulting Tensor has is_coalesced set to ``False```. + + Example:: + + >>> i = torch.tensor([[0, 1, 1], + ... [2, 0, 2]]) + >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) + >>> torch.sparse_coo_tensor(i, v, [2, 4]) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 4), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v) # Shape inference + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 3), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v, [2, 4], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, + layout=torch.sparse_coo) + + # Create an empty sparse tensor with the following invariants: + # 1. sparse_dim + dense_dim = len(SparseTensor.shape) + # 2. SparseTensor._indices().shape = (sparse_dim, nnz) + # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) + # + # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and + # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0,)), + size=(1,), nnz=0, layout=torch.sparse_coo) + + # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and + # sparse_dim = 1 + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0, 2)), + size=(1, 2), nnz=0, layout=torch.sparse_coo) + + .. _torch.sparse: https://pytorch.org/docs/stable/sparse.html + """ + +def sparse_csc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSC (Compressed Sparse Column) + ` with specified values at the given + :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in CSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncols + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and row_indices depending on where the given column + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + column. + row_indices (array_like): Row coordinates of each element in + values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 2, 4] + >>> row_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 2, 4]), + row_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csc) + """ + +def sparse_csr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSR (Compressed Sparse Row) ` with specified + values at the given :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix multiplication operations + in CSR format are typically faster than that for sparse tensors in COO format. Make you have a look + at :ref:`the note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrows + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and col_indices depending on where the given row + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + row. + col_indices (array_like): Column coordinates of each element in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 2, 4] + >>> col_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def split_copy( + input: Tensor, + split_size: _int | SymInt, + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def split_with_sizes( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: ... +def split_with_sizes_copy( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split_with_sizes`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def spmm(input: Tensor, mat2: Tensor) -> Tensor: ... +def sqrt(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sqrt(input, *, out=None) -> Tensor + + Returns a new tensor with the square-root of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.sqrt(a) + tensor([ nan, 1.0112, 0.2883, 0.6933]) + """ + +def sqrt_(input: Tensor) -> Tensor: + r""" + sqrt_(input) -> Tensor + + In-place version of :func:`torch.sqrt` + """ + +def square(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + square(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the square of the elements of :attr:`input`. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.square(a) + tensor([ 4.3077, 1.0457, 0.0069, 0.2310]) + """ + +def square_(input: Tensor) -> Tensor: + r""" + square_(input) -> Tensor + + In-place version of :func:`torch.square` + """ + +@overload +def squeeze(input: Tensor) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze(input: Tensor, dim: _int) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze(input: Tensor, dim: _size) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def squeeze_copy( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def squeeze_copy( + input: Tensor, + dim: _size, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def sspaddmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def sspaddmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def sspaddmm( + beta: Number | _complex | PySymType, + self: Tensor, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +def stack( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + stack(tensors, dim=0, *, out=None) -> Tensor + + Concatenates a sequence of tensors along a new dimension. + + All tensors need to be of the same size. + + .. seealso:: + + :func:`torch.cat` concatenates the given sequence along an existing dimension. + + Arguments: + tensors (sequence of Tensors): sequence of tensors to concatenate + dim (int, optional): dimension to insert. Has to be between 0 and the number + of dimensions of concatenated tensors (inclusive). Default: 0 + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]) + >>> torch.stack((x, x)) # same as torch.stack((x, x), dim=0) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]], + + [[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x)).size() + torch.Size([2, 2, 3]) + >>> torch.stack((x, x), dim=1) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.3367, 0.1288, 0.2345]], + + [[ 0.2303, -1.1229, -0.1863], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x), dim=2) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + >>> torch.stack((x, x), dim=-1) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + """ + +@overload +def std( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std(input: Tensor, unbiased: _bool = True) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + unbiased: _bool = True, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def sub( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def sub( + self: Tensor, + alpha: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def sub( + self: Tensor, + alpha: Number | _complex | PySymType, + other: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def subtract( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + subtract(input, other, *, alpha=1, out=None) -> Tensor + + Alias for :func:`torch.sub`. + """ + +@overload +def subtract( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: + r""" + subtract(input, other, *, alpha=1, out=None) -> Tensor + + Alias for :func:`torch.sub`. + """ + +@overload +def sum(input: Tensor, *, dtype: _dtype | None = None) -> Tensor: + r""" + sum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + .. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + + .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) + """ + +@overload +def sum( + input: Tensor, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + sum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + .. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + + .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) + """ + +def svd( + input: Tensor, + some: _bool = True, + compute_uv: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.svd: + r""" + svd(input, some=True, compute_uv=True, *, out=None) -> (Tensor, Tensor, Tensor) + + Computes the singular value decomposition of either a matrix or batch of + matrices :attr:`input`. The singular value decomposition is represented as a + namedtuple `(U, S, V)`, such that :attr:`input` :math:`= U \text{diag}(S) V^{\text{H}}`. + where :math:`V^{\text{H}}` is the transpose of `V` for real inputs, + and the conjugate transpose of `V` for complex inputs. + If :attr:`input` is a batch of matrices, then `U`, `S`, and `V` are also + batched with the same batch dimensions as :attr:`input`. + + If :attr:`some` is `True` (default), the method returns the reduced singular + value decomposition. In this case, if the last two dimensions of :attr:`input` are + `m` and `n`, then the returned `U` and `V` matrices will contain only + `min(n, m)` orthonormal columns. + + If :attr:`compute_uv` is `False`, the returned `U` and `V` will be + zero-filled matrices of shape `(m, m)` and `(n, n)` + respectively, and the same device as :attr:`input`. The argument :attr:`some` + has no effect when :attr:`compute_uv` is `False`. + + Supports :attr:`input` of float, double, cfloat and cdouble data types. + The dtypes of `U` and `V` are the same as :attr:`input`'s. `S` will + always be real-valued, even if :attr:`input` is complex. + + .. warning:: + + :func:`torch.svd` is deprecated in favor of :func:`torch.linalg.svd` + and will be removed in a future PyTorch release. + + ``U, S, V = torch.svd(A, some=some, compute_uv=True)`` (default) should be replaced with + + .. code:: python + + U, S, Vh = torch.linalg.svd(A, full_matrices=not some) + V = Vh.mH + + ``_, S, _ = torch.svd(A, some=some, compute_uv=False)`` should be replaced with + + .. code:: python + + S = torch.linalg.svdvals(A) + + .. note:: Differences with :func:`torch.linalg.svd`: + + * :attr:`some` is the opposite of + :func:`torch.linalg.svd`'s :attr:`full_matrices`. Note that + default value for both is `True`, so the default behavior is + effectively the opposite. + * :func:`torch.svd` returns `V`, whereas :func:`torch.linalg.svd` returns + `Vh`, that is, :math:`V^{\text{H}}`. + * If :attr:`compute_uv` is `False`, :func:`torch.svd` returns zero-filled + tensors for `U` and `Vh`, whereas :func:`torch.linalg.svd` returns + empty tensors. + + .. note:: The singular values are returned in descending order. If :attr:`input` is a batch of matrices, + then the singular values of each matrix in the batch are returned in descending order. + + .. note:: The `S` tensor can only be used to compute gradients if :attr:`compute_uv` is `True`. + + .. note:: When :attr:`some` is `False`, the gradients on `U[..., :, min(m, n):]` + and `V[..., :, min(m, n):]` will be ignored in the backward pass, as those vectors + can be arbitrary bases of the corresponding subspaces. + + .. note:: The implementation of :func:`torch.linalg.svd` on CPU uses LAPACK's routine `?gesdd` + (a divide-and-conquer algorithm) instead of `?gesvd` for speed. Analogously, + on GPU, it uses cuSOLVER's routines `gesvdj` and `gesvdjBatched`. + + .. note:: The returned `U` will not be contiguous. The matrix (or batch of matrices) will + be represented as a column-major matrix (i.e. Fortran-contiguous). + + .. warning:: The gradients with respect to `U` and `V` will only be finite when the input does not + have zero nor repeated singular values. + + .. warning:: If the distance between any two singular values is close to zero, the gradients with respect to + `U` and `V` will be numerically unstable, as they depends on + :math:`\frac{1}{\min_{i \neq j} \sigma_i^2 - \sigma_j^2}`. The same happens when the matrix + has small singular values, as these gradients also depend on `S^{-1}`. + + .. warning:: For complex-valued :attr:`input` the singular value decomposition is not unique, + as `U` and `V` may be multiplied by an arbitrary phase factor :math:`e^{i \phi}` on every column. + The same happens when :attr:`input` has repeated singular values, where one may multiply + the columns of the spanning subspace in `U` and `V` by a rotation matrix + and `the resulting vectors will span the same subspace`_. + Different platforms, like NumPy, or inputs on different device types, + may produce different `U` and `V` tensors. + + Args: + input (Tensor): the input tensor of size `(*, m, n)` where `*` is zero or more + batch dimensions consisting of `(m, n)` matrices. + some (bool, optional): controls whether to compute the reduced or full decomposition, and + consequently, the shape of returned `U` and `V`. Default: `True`. + compute_uv (bool, optional): controls whether to compute `U` and `V`. Default: `True`. + + Keyword args: + out (tuple, optional): the output tuple of tensors + + Example:: + + >>> a = torch.randn(5, 3) + >>> a + tensor([[ 0.2364, -0.7752, 0.6372], + [ 1.7201, 0.7394, -0.0504], + [-0.3371, -1.0584, 0.5296], + [ 0.3550, -0.4022, 1.5569], + [ 0.2445, -0.0158, 1.1414]]) + >>> u, s, v = torch.svd(a) + >>> u + tensor([[ 0.4027, 0.0287, 0.5434], + [-0.1946, 0.8833, 0.3679], + [ 0.4296, -0.2890, 0.5261], + [ 0.6604, 0.2717, -0.2618], + [ 0.4234, 0.2481, -0.4733]]) + >>> s + tensor([2.3289, 2.0315, 0.7806]) + >>> v + tensor([[-0.0199, 0.8766, 0.4809], + [-0.5080, 0.4054, -0.7600], + [ 0.8611, 0.2594, -0.4373]]) + >>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t())) + tensor(8.6531e-07) + >>> a_big = torch.randn(7, 5, 3) + >>> u, s, v = torch.svd(a_big) + >>> torch.dist(a_big, torch.matmul(torch.matmul(u, torch.diag_embed(s)), v.mT)) + tensor(2.6503e-06) + + .. _the resulting vectors will span the same subspace: + (https://en.wikipedia.org/wiki/Singular_value_decomposition#Singular_values,_singular_vectors,_and_their_relation_to_the_SVD) + """ + +def swapaxes(input: Tensor, axis0: _int, axis1: _int) -> Tensor: + r""" + swapaxes(input, axis0, axis1) -> Tensor + + Alias for :func:`torch.transpose`. + + This function is equivalent to NumPy's swapaxes function. + + Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) + """ + +def swapdims(input: Tensor, dim0: _int, dim1: _int) -> Tensor: + r""" + swapdims(input, dim0, dim1) -> Tensor + + Alias for :func:`torch.transpose`. + + This function is equivalent to NumPy's swapaxes function. + + Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapdims(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapdims(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) + """ + +def sym_constrain_range( + size: Number | _complex | PySymType, + *, + min: _int | None = None, + max: _int | None = None, +) -> None: ... +def sym_constrain_range_for_size( + size: Number | _complex | PySymType, + *, + min: _int | None = None, + max: _int | None = None, +) -> None: ... +def t(input: Tensor) -> Tensor: + r""" + t(input) -> Tensor + + Expects :attr:`input` to be <= 2-D tensor and transposes dimensions 0 + and 1. + + 0-D and 1-D tensors are returned as is. When input is a 2-D tensor this + is equivalent to ``transpose(input, 0, 1)``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.randn(()) + >>> x + tensor(0.1995) + >>> torch.t(x) + tensor(0.1995) + >>> x = torch.randn(3) + >>> x + tensor([ 2.4320, -0.4608, 0.7702]) + >>> torch.t(x) + tensor([ 2.4320, -0.4608, 0.7702]) + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.4875, 0.9158, -0.5872], + [ 0.3938, -0.6929, 0.6932]]) + >>> torch.t(x) + tensor([[ 0.4875, 0.3938], + [ 0.9158, -0.6929], + [-0.5872, 0.6932]]) + + See also :func:`torch.transpose`. + """ + +def t_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.t`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def take( + input: Tensor, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + take(input, index) -> Tensor + + Returns a new tensor with the elements of :attr:`input` at the given indices. + The input tensor is treated as if it were viewed as a 1-D tensor. The result + takes the same shape as the indices. + + Args: + input (Tensor): the input tensor. + index (LongTensor): the indices into tensor + + Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> torch.take(src, torch.tensor([0, 2, 5])) + tensor([ 4, 5, 8]) + """ + +def take_along_dim( + input: Tensor, + indices: Tensor, + dim: _int | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + take_along_dim(input, indices, dim=None, *, out=None) -> Tensor + + Selects values from :attr:`input` at the 1-dimensional indices from :attr:`indices` along the given :attr:`dim`. + + If :attr:`dim` is None, the input array is treated as if it has been flattened to 1d. + + Functions that return indices along a dimension, like :func:`torch.argmax` and :func:`torch.argsort`, + are designed to work with this function. See the examples below. + + .. note:: + This function is similar to NumPy's `take_along_axis`. + See also :func:`torch.gather`. + + Args: + input (Tensor): the input tensor. + indices (LongTensor): the indices into :attr:`input`. Must have long dtype. + dim (int, optional): dimension to select along. Default: `None`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([[10, 30, 20], [60, 40, 50]]) + >>> max_idx = torch.argmax(t) + >>> torch.take_along_dim(t, max_idx) + tensor([60]) + >>> sorted_idx = torch.argsort(t, dim=1) + >>> torch.take_along_dim(t, sorted_idx, dim=1) + tensor([[10, 20, 30], + [40, 50, 60]]) + """ + +def tan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + tan(input, *, out=None) -> Tensor + + Returns a new tensor with the tangent of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \tan(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.2027, -1.7687, 0.4412, -1.3856]) + >>> torch.tan(a) + tensor([-2.5930, 4.9859, 0.4722, -5.3366]) + """ + +def tan_(input: Tensor) -> Tensor: + r""" + tan_(input) -> Tensor + + In-place version of :func:`torch.tan` + """ + +def tanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + tanh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic tangent of the elements + of :attr:`input`. + + .. math:: + \text{out}_{i} = \tanh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.8986, -0.7279, 1.1745, 0.2611]) + >>> torch.tanh(a) + tensor([ 0.7156, -0.6218, 0.8257, 0.2553]) + """ + +def tanh_(input: Tensor) -> Tensor: + r""" + tanh_(input) -> Tensor + + In-place version of :func:`torch.tanh` + """ + +def tensor( + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Constructs a tensor with no autograd history (also known as a "leaf tensor", see :doc:`/notes/autograd`) by copying :attr:`data`. + + .. warning:: + + When working with tensors prefer using :func:`torch.Tensor.clone`, + :func:`torch.Tensor.detach`, and :func:`torch.Tensor.requires_grad_` for + readability. Letting `t` be a tensor, ``torch.tensor(t)`` is equivalent to + ``t.detach().clone()``, and ``torch.tensor(t, requires_grad=True)`` + is equivalent to ``t.detach().clone().requires_grad_(True)``. + + .. seealso:: + + :func:`torch.as_tensor` preserves autograd history and avoids copies where possible. + :func:`torch.from_numpy` creates a tensor that shares storage with a NumPy array. + + Args: + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + + Example:: + + >>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) + tensor([[ 0.1000, 1.2000], + [ 2.2000, 3.1000], + [ 4.9000, 5.2000]]) + + >>> torch.tensor([0, 1]) # Type inference on data + tensor([ 0, 1]) + + >>> torch.tensor([[0.11111, 0.222222, 0.3333333]], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) # creates a double tensor on a CUDA device + tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0') + + >>> torch.tensor(3.14159) # Create a zero-dimensional (scalar) tensor + tensor(3.1416) + + >>> torch.tensor([]) # Create an empty tensor (of size (0,)) + tensor([]) + """ + +@overload +def tensor_split( + input: Tensor, + tensor_indices_or_sections: Tensor, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +@overload +def tensor_split( + input: Tensor, + sections: _int | SymInt, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +@overload +def tensor_split( + input: Tensor, + indices: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +def threshold( + input: Tensor, + threshold: Number | _complex | PySymType, + value: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +def threshold_( + input: Tensor, + threshold: Number | _complex | PySymType, + value: Number | _complex | PySymType, +) -> Tensor: ... +def tile(input: Tensor, dims: Sequence[_int | SymInt]) -> Tensor: + r""" + tile(input, dims) -> Tensor + + Constructs a tensor by repeating the elements of :attr:`input`. + The :attr:`dims` argument specifies the number of repetitions + in each dimension. + + If :attr:`dims` specifies fewer dimensions than :attr:`input` has, then + ones are prepended to :attr:`dims` until all dimensions are specified. + For example, if :attr:`input` has shape (8, 6, 4, 2) and :attr:`dims` + is (2, 2), then :attr:`dims` is treated as (1, 1, 2, 2). + + Analogously, if :attr:`input` has fewer dimensions than :attr:`dims` + specifies, then :attr:`input` is treated as if it were unsqueezed at + dimension zero until it has as many dimensions as :attr:`dims` specifies. + For example, if :attr:`input` has shape (4, 2) and :attr:`dims` + is (3, 3, 2, 2), then :attr:`input` is treated as if it had the + shape (1, 1, 4, 2). + + .. note:: + + This function is similar to NumPy's tile function. + + Args: + input (Tensor): the tensor whose elements to repeat. + dims (tuple): the number of repetitions per dimension. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.tile((2,)) + tensor([1, 2, 3, 1, 2, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.tile(y, (2, 2)) + tensor([[1, 2, 1, 2], + [3, 4, 3, 4], + [1, 2, 1, 2], + [3, 4, 3, 4]]) + """ + +def topk( + input: Tensor, + k: _int | SymInt, + dim: _int = -1, + largest: _bool = True, + sorted: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.topk: + r""" + topk(input, k, dim=None, largest=True, sorted=True, *, out=None) -> (Tensor, LongTensor) + + Returns the :attr:`k` largest elements of the given :attr:`input` tensor along + a given dimension. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`largest` is ``False`` then the `k` smallest elements are returned. + + A namedtuple of `(values, indices)` is returned with the `values` and + `indices` of the largest `k` elements of each row of the `input` tensor in the + given dimension `dim`. + + The boolean option :attr:`sorted` if ``True``, will make sure that the returned + `k` elements are themselves sorted + + .. note:: + When using `torch.topk`, the indices of tied elements are not guaranteed to be stable + and may vary across different invocations. + + Args: + input (Tensor): the input tensor. + k (int): the k in "top-k" + dim (int, optional): the dimension to sort along + largest (bool, optional): controls whether to return largest or + smallest elements + sorted (bool, optional): controls whether to return the elements + in sorted order + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) that can be + optionally given to be used as output buffers + + Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.topk(x, 3) + torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2])) + """ + +def trace(input: Tensor) -> Tensor: + r""" + trace(input) -> Tensor + + Returns the sum of the elements of the diagonal of the input 2-D matrix. + + Example:: + + >>> x = torch.arange(1., 10.).view(3, 3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.], + [ 7., 8., 9.]]) + >>> torch.trace(x) + tensor(15.) + """ + +def transpose(input: Tensor, dim0: _int, dim1: _int) -> Tensor: + r""" + transpose(input, dim0, dim1) -> Tensor + + Returns a tensor that is a transposed version of :attr:`input`. + The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. + + If :attr:`input` is a strided tensor then the resulting :attr:`out` + tensor shares its underlying storage with the :attr:`input` tensor, so + changing the content of one would change the content of the other. + + If :attr:`input` is a :ref:`sparse tensor ` then the + resulting :attr:`out` tensor *does not* share the underlying storage + with the :attr:`input` tensor. + + If :attr:`input` is a :ref:`sparse tensor ` with compressed + layout (SparseCSR, SparseBSR, SparseCSC or SparseBSC) the arguments + :attr:`dim0` and :attr:`dim1` must be both batch dimensions, or must + both be sparse dimensions. The batch dimensions of a sparse tensor are the + dimensions preceding the sparse dimensions. + + .. note:: + Transpositions which interchange the sparse dimensions of a `SparseCSR` + or `SparseCSC` layout tensor will result in the layout changing between + the two options. Transposition of the sparse dimensions of a ` SparseBSR` + or `SparseBSC` layout tensor will likewise generate a result with the + opposite layout. + + + Args: + input (Tensor): the input tensor. + dim0 (int): the first dimension to be transposed + dim1 (int): the second dimension to be transposed + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 1.0028, -0.9893, 0.5809], + [-0.1669, 0.7299, 0.4942]]) + >>> torch.transpose(x, 0, 1) + tensor([[ 1.0028, -0.1669], + [-0.9893, 0.7299], + [ 0.5809, 0.4942]]) + + See also :func:`torch.t`. + """ + +def transpose_copy( + input: Tensor, + dim0: _int, + dim1: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.transpose`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def trapezoid(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Computes the `trapezoidal rule `_ along + :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified. + + + Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, + the default computation is + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`dx` is specified the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + + effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, + assuming :attr:`x` is also a one-dimensional tensor with + elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. + The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` + and :attr:`y`, the function computes the difference between consecutive elements along + dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have + the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. + After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. + See the examples below for details. + + .. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) + """ + +@overload +def trapezoid( + y: Tensor, + *, + dx: Number | _complex | PySymType = 1, + dim: _int = -1, +) -> Tensor: + r""" + trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Computes the `trapezoidal rule `_ along + :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified. + + + Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, + the default computation is + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`dx` is specified the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + + effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, + assuming :attr:`x` is also a one-dimensional tensor with + elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. + The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` + and :attr:`y`, the function computes the difference between consecutive elements along + dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have + the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. + After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. + See the examples below for details. + + .. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) + """ + +@overload +def trapz(y: Tensor, *, dx: _float = 1, dim: _int = -1) -> Tensor: + r""" + trapz(y, x=None, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +@overload +def trapz(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + trapz(y, x=None, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +def triangular_solve( + input: Tensor, + A: Tensor, + upper: _bool = True, + transpose: _bool = False, + unitriangular: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.triangular_solve: + r""" + triangular_solve(b, A, upper=True, transpose=False, unitriangular=False, *, out=None) -> (Tensor, Tensor) + + Solves a system of equations with a square upper or lower triangular invertible matrix :math:`A` + and multiple right-hand sides :math:`b`. + + In symbols, it solves :math:`AX = b` and assumes :math:`A` is square upper-triangular + (or lower-triangular if :attr:`upper`\ `= False`) and does not have zeros on the diagonal. + + `torch.triangular_solve(b, A)` can take in 2D inputs `b, A` or inputs that are + batches of 2D matrices. If the inputs are batches, then returns + batched outputs `X` + + If the diagonal of :attr:`A` contains zeros or elements that are very close to zero and + :attr:`unitriangular`\ `= False` (default) or if the input matrix is badly conditioned, + the result may contain `NaN` s. + + Supports input of float, double, cfloat and cdouble data types. + + .. warning:: + + :func:`torch.triangular_solve` is deprecated in favor of :func:`torch.linalg.solve_triangular` + and will be removed in a future PyTorch release. + :func:`torch.linalg.solve_triangular` has its arguments reversed and does not return a + copy of one of the inputs. + + ``X = torch.triangular_solve(B, A).solution`` should be replaced with + + .. code:: python + + X = torch.linalg.solve_triangular(A, B) + + Args: + b (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where + :math:`*` is zero of more batch dimensions + A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)` + where :math:`*` is zero or more batch dimensions + upper (bool, optional): whether :math:`A` is upper or lower triangular. Default: ``True``. + transpose (bool, optional): solves `op(A)X = b` where `op(A) = A^T` if this flag is ``True``, + and `op(A) = A` if it is ``False``. Default: ``False``. + unitriangular (bool, optional): whether :math:`A` is unit triangular. + If True, the diagonal elements of :math:`A` are assumed to be + 1 and not referenced from :math:`A`. Default: ``False``. + + Keyword args: + out ((Tensor, Tensor), optional): tuple of two tensors to write + the output to. Ignored if `None`. Default: `None`. + + Returns: + A namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient` + is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b` + (or whatever variant of the system of equations, depending on the keyword arguments.) + + Examples:: + + >>> A = torch.randn(2, 2).triu() + >>> A + tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]]) + >>> b = torch.randn(2, 3) + >>> b + tensor([[-0.0210, 2.3513, -1.5492], + [ 1.5429, 0.7403, -1.0243]]) + >>> torch.triangular_solve(b, A) + torch.return_types.triangular_solve( + solution=tensor([[ 1.7841, 2.9046, -2.5405], + [ 1.9320, 0.9270, -1.2826]]), + cloned_coefficient=tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]])) + """ + +def tril( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + tril(input, diagonal=0, *, out=None) -> Tensor + + Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0813, -0.8619, 0.7105], + [ 0.0935, 0.1380, 2.2112], + [-0.3409, -0.9828, 0.0289]]) + >>> torch.tril(a) + tensor([[-1.0813, 0.0000, 0.0000], + [ 0.0935, 0.1380, 0.0000], + [-0.3409, -0.9828, 0.0289]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461], + [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]]) + >>> torch.tril(b, diagonal=1) + tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]]) + >>> torch.tril(b, diagonal=-1) + tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]]) + """ + +def tril_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + tril_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the lower triangular part of a :attr:`row`-by- + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.tril_indices(3, 3) + >>> a + tensor([[0, 1, 1, 2, 2, 2], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, -1) + >>> a + tensor([[1, 2, 2, 3, 3, 3], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], + [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]]) + """ + +def triplet_margin_loss( + anchor: Tensor, + positive: Tensor, + negative: Tensor, + margin: _float = 1.0, + p: _float = 2, + eps: _float = 1e-06, + swap: _bool = False, + reduction: _int = 1, +) -> Tensor: ... +def triu( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + triu(input, diagonal=0, *, out=None) -> Tensor + + Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.3480, -0.5211, -0.4573]]) + >>> torch.triu(a) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.0000, -1.0680, 0.6602], + [ 0.0000, 0.0000, -0.4573]]) + >>> torch.triu(a, diagonal=1) + tensor([[ 0.0000, 0.5207, 2.0049], + [ 0.0000, 0.0000, 0.6602], + [ 0.0000, 0.0000, 0.0000]]) + >>> torch.triu(a, diagonal=-1) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.0000, -0.5211, -0.4573]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=1) + tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=-1) + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]]) + """ + +def triu_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + triu_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the upper triangular part of a :attr:`row` by + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.triu_indices(3, 3) + >>> a + tensor([[0, 0, 0, 1, 1, 2], + [0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, -1) + >>> a + tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3], + [0, 1, 2, 0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1], + [1, 2, 2]]) + """ + +def true_divide( + input: Tensor | Number, + other: Tensor | Number, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + true_divide(dividend, divisor, *, out) -> Tensor + + Alias for :func:`torch.div` with ``rounding_mode=None``. + """ + +def trunc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + trunc(input, *, out=None) -> Tensor + + Returns a new tensor with the truncated integer values of + the elements of :attr:`input`. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 3.4742, 0.5466, -0.8008, -0.9079]) + >>> torch.trunc(a) + tensor([ 3., 0., -0., -0.]) + """ + +def trunc_(input: Tensor) -> Tensor: + r""" + trunc_(input) -> Tensor + + In-place version of :func:`torch.trunc` + """ + +def unbind(input: Tensor, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + unbind(input, dim=0) -> seq + + Removes a tensor dimension. + + Returns a tuple of all slices along a given dimension, already without it. + + Arguments: + input (Tensor): the tensor to unbind + dim (int): dimension to remove + + Example:: + + >>> torch.unbind(torch.tensor([[1, 2, 3], + >>> [4, 5, 6], + >>> [7, 8, 9]])) + (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9])) + """ + +def unbind_copy( + input: Tensor, + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.unbind`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def unflatten( + input: Tensor, + dim: _int, + sizes: Sequence[_int | SymInt], +) -> Tensor: + r""" + unflatten(input, dim, sizes) -> Tensor + + Expands a dimension of the input tensor over multiple dimensions. + + .. seealso:: + + :func:`torch.flatten` the inverse of this function. It coalesces several dimensions into one. + + Args: + input (Tensor): the input tensor. + dim (int): Dimension to be unflattened, specified as an index into + ``input.shape``. + sizes (Tuple[int]): New shape of the unflattened dimension. + One of its elements can be `-1` in which case the corresponding output + dimension is inferred. Otherwise, the product of ``sizes`` *must* + equal ``input.shape[dim]``. + + Returns: + A View of input with the specified dimension unflattened. + + Examples:: + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (2, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (-1, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(5, 12, 3), -2, (2, 2, 3, 1, 1)).shape + torch.Size([5, 2, 2, 3, 1, 1, 3]) + """ + +def unfold_copy( + input: Tensor, + dimension: _int, + size: _int, + step: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.unfold`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def unique_dim( + input: Tensor, + dim: _int, + sorted: _bool = True, + return_inverse: _bool = False, + return_counts: _bool = False, +) -> tuple[Tensor, Tensor, Tensor]: ... +def unsafe_chunk( + input: Tensor, + chunks: _int, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + unsafe_chunk(input, chunks, dim=0) -> List of Tensors + + Works like :func:`torch.chunk` but without enforcing the autograd restrictions + on inplace modification of the outputs. + + .. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. + """ + +def unsafe_split( + input: Tensor, + split_size: _int | SymInt, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + unsafe_split(tensor, split_size_or_sections, dim=0) -> List of Tensors + + Works like :func:`torch.split` but without enforcing the autograd restrictions + on inplace modification of the outputs. + + .. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. + """ + +def unsafe_split_with_sizes( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: ... +def unsqueeze(input: Tensor, dim: _int) -> Tensor: + r""" + unsqueeze(input, dim) -> Tensor + + Returns a new tensor with a dimension of size one inserted at the + specified position. + + The returned tensor shares the same underlying data with this tensor. + + A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)`` + can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze` + applied at :attr:`dim` = ``dim + input.dim() + 1``. + + Args: + input (Tensor): the input tensor. + dim (int): the index at which to insert the singleton dimension + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4]) + >>> torch.unsqueeze(x, 0) + tensor([[ 1, 2, 3, 4]]) + >>> torch.unsqueeze(x, 1) + tensor([[ 1], + [ 2], + [ 3], + [ 4]]) + """ + +def unsqueeze_copy( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.unsqueeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def values_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.values`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def vander( + x: Tensor, + N: _int | None = None, + increasing: _bool = False, +) -> Tensor: + r""" + vander(x, N=None, increasing=False) -> Tensor + + Generates a Vandermonde matrix. + + The columns of the output matrix are elementwise powers of the input vector :math:`x^{(N-1)}, x^{(N-2)}, ..., x^0`. + If increasing is True, the order of the columns is reversed :math:`x^0, x^1, ..., x^{(N-1)}`. Such a + matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde. + + Arguments: + x (Tensor): 1-D input tensor. + N (int, optional): Number of columns in the output. If N is not specified, + a square array is returned :math:`(N = len(x))`. + increasing (bool, optional): Order of the powers of the columns. If True, + the powers increase from left to right, if False (the default) they are reversed. + + Returns: + Tensor: Vandermonde matrix. If increasing is False, the first column is :math:`x^{(N-1)}`, + the second :math:`x^{(N-2)}` and so forth. If increasing is True, the columns + are :math:`x^0, x^1, ..., x^{(N-1)}`. + + Example:: + + >>> x = torch.tensor([1, 2, 3, 5]) + >>> torch.vander(x) + tensor([[ 1, 1, 1, 1], + [ 8, 4, 2, 1], + [ 27, 9, 3, 1], + [125, 25, 5, 1]]) + >>> torch.vander(x, N=3) + tensor([[ 1, 1, 1], + [ 4, 2, 1], + [ 9, 3, 1], + [25, 5, 1]]) + >>> torch.vander(x, N=3, increasing=True) + tensor([[ 1, 1, 1], + [ 1, 2, 4], + [ 1, 3, 9], + [ 1, 5, 25]]) + """ + +@overload +def var( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var(input: Tensor, unbiased: _bool = True) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + unbiased: _bool = True, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +def vdot( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + vdot(input, other, *, out=None) -> Tensor + + Computes the dot product of two 1D vectors along a dimension. + + In symbols, this function computes + + .. math:: + + \sum_{i=1}^n \overline{x_i}y_i. + + where :math:`\overline{x_i}` denotes the conjugate for complex + vectors, and it is the identity for real vectors. + + .. note:: + + Unlike NumPy's vdot, torch.vdot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + + .. seealso:: + + :func:`torch.linalg.vecdot` computes the dot product of two batches of vectors along a dimension. + + Args: + input (Tensor): first tensor in the dot product, must be 1D. Its conjugate is used if it's complex. + other (Tensor): second tensor in the dot product, must be 1D. + + Keyword args: + + .. note:: out (Tensor, optional): the output tensor. + + + Example:: + + >>> torch.vdot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + >>> a = torch.tensor((1 +2j, 3 - 1j)) + >>> b = torch.tensor((2 +1j, 4 - 0j)) + >>> torch.vdot(a, b) + tensor([16.+1.j]) + >>> torch.vdot(b, a) + tensor([16.-1.j]) + """ + +def view_as_complex(input: Tensor) -> Tensor: + r""" + view_as_complex(input) -> Tensor + + Returns a view of :attr:`input` as a complex tensor. For an input complex + tensor of :attr:`size` :math:`m1, m2, \dots, mi, 2`, this function returns a + new complex tensor of :attr:`size` :math:`m1, m2, \dots, mi` where the last + dimension of the input tensor is expected to represent the real and imaginary + components of complex numbers. + + .. warning:: + :func:`view_as_complex` is only supported for tensors with + :class:`torch.dtype` ``torch.float64`` and ``torch.float32``. The input is + expected to have the last dimension of :attr:`size` 2. In addition, the + tensor must have a `stride` of 1 for its last dimension. The strides of all + other dimensions must be even numbers. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, 2) + >>> x + tensor([[ 1.6116, -0.5772], + [-1.4606, -0.9120], + [ 0.0786, -1.7497], + [-0.6561, -1.6623]]) + >>> torch.view_as_complex(x) + tensor([(1.6116-0.5772j), (-1.4606-0.9120j), (0.0786-1.7497j), (-0.6561-1.6623j)]) + """ + +def view_as_complex_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view_as_complex`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def view_as_real(input: Tensor) -> Tensor: + r""" + view_as_real(input) -> Tensor + + Returns a view of :attr:`input` as a real tensor. For an input complex tensor of + :attr:`size` :math:`m1, m2, \dots, mi`, this function returns a new + real tensor of size :math:`m1, m2, \dots, mi, 2`, where the last dimension of size 2 + represents the real and imaginary components of complex numbers. + + .. warning:: + :func:`view_as_real` is only supported for tensors with ``complex dtypes``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.4737-0.3839j), (-0.2098-0.6699j), (0.3470-0.9451j), (-0.5174-1.3136j)]) + >>> torch.view_as_real(x) + tensor([[ 0.4737, -0.3839], + [-0.2098, -0.6699], + [ 0.3470, -0.9451], + [-0.5174, -1.3136]]) + """ + +def view_as_real_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view_as_real`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def view_copy( + input: Tensor, + dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def view_copy( + input: Tensor, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def vsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + vsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors + vertically according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) + (the split dimension is 0), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.vsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + """ + +@overload +def vsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + vsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors + vertically according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) + (the split dimension is 0), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.vsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + """ + +def vstack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + vstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence vertically (row wise). + + This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by :func:`torch.atleast_2d`. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.vstack((a,b)) + tensor([[1, 2, 3], + [4, 5, 6]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.vstack((a,b)) + tensor([[1], + [2], + [3], + [4], + [5], + [6]]) + """ + +@overload +def where(condition: Tensor) -> tuple[Tensor, ...]: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + input: Tensor, + other: Number | _complex | PySymType, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + self: Number | _complex | PySymType, + other: Number | _complex | PySymType, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def xlogy( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy( + self: Number | _complex | PySymType, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy_(input: Tensor, other: Tensor) -> Tensor: + r""" + xlogy_(input, other) -> Tensor + + In-place version of :func:`torch.xlogy` + """ + +@overload +def xlogy_(input: Tensor, other: Number | _complex | PySymType) -> Tensor: + r""" + xlogy_(input, other) -> Tensor + + In-place version of :func:`torch.xlogy` + """ + +def zero_(input: Tensor) -> Tensor: ... +@overload +def zeros( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +@overload +def zeros( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +def zeros_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the same size as + :attr:`input`. ``torch.zeros_like(input)`` is equivalent to + ``torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.zeros_like(input, out=output)`` is equivalent to + ``torch.zeros(input.size(), out=output)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> input = torch.empty(2, 3) + >>> torch.zeros_like(input) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + """ diff --git a/.venv/lib/python3.12/site-packages/torch/_C/__init__.pyi b/.venv/lib/python3.12/site-packages/torch/_C/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e5157d2e91ce74a46f913bf113e5cb602c569fe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/__init__.pyi @@ -0,0 +1,12539 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/__init__.pyi.in +# mypy: disable-error-code="type-arg" +# mypy: allow-untyped-defs +# ruff: noqa: F401 + +from collections.abc import Callable, Iterable, Iterator, Sequence +from contextlib import AbstractContextManager +from enum import Enum, IntEnum +from pathlib import Path +from types import EllipsisType +from typing import ( + Any, + AnyStr, + Generic, + IO, + Literal, + NamedTuple, + overload, + Protocol, + runtime_checkable, + SupportsIndex, + TypeAlias, + TypeVar, +) +from typing_extensions import ParamSpec, Self + +import numpy + +import torch +from torch import inf, SymInt, Tensor +from torch._C import ( + _acc, + _aoti, + _cpu, + _dynamo, + _export, + _functionalization, + _functorch, + _lazy, + _lazy_ts_backend, + _nn, + _onnx, + _VariableFunctions, + _verbose, +) +from torch._prims_common import DeviceLikeType +from torch.autograd.graph import Node as _Node +from torch.cuda import _POOL_HANDLE +from torch.distributed.device_mesh import DeviceMesh +from torch.distributed.tensor._op_schema import OpSchema +from torch.distributed.tensor.placement_types import Placement +from torch.fx.node import Node as FxNode +from torch.package import PackageExporter +from torch.storage import TypedStorage, UntypedStorage +from torch.types import ( + _bool, + _bytes, + _complex, + _device, + _dispatchkey, + _dtype, + _float, + _int, + _layout, + _qscheme, + _size, + _str, + _symsize, + Device, + IntLikeType, + Number, + PySymType, + Storage, +) +from torch.utils._python_dispatch import TorchDispatchMode +from torch.utils.checkpoint import GraphExecGroup +from torch.xpu import _POOL_HANDLE as XPU_POOL_HANDLE + +# This module is defined in torch/csrc/Module.cpp + +K = TypeVar("K") # noqa: PYI001 +T = TypeVar("T") # noqa: PYI001 +S = TypeVar("S", bound=torch.Tensor) # noqa: PYI001 +P = ParamSpec("P") # noqa: PYI001 +R = TypeVar("R", covariant=True) # return value (always covariant) # noqa: PYI001 +T_co = TypeVar("T_co", covariant=True) # noqa: PYI001 + +@runtime_checkable +class _NestedSequence(Protocol[T_co]): + """A protocol for representing nested sequences. + + References:: + `numpy._typing._NestedSequence` + + """ + + def __len__(self, /) -> _int: ... + def __getitem__(self, index: _int, /) -> T_co | _NestedSequence[T_co]: ... + def __contains__(self, x: object, /) -> _bool: ... + def __iter__(self, /) -> Iterator[T_co | _NestedSequence[T_co]]: ... + def __reversed__(self, /) -> Iterator[T_co | _NestedSequence[T_co]]: ... + def count(self, value: Any, /) -> _int: ... + def index(self, value: Any, /) -> _int: ... + +# Defined in torch/csrc/Device.cpp +class device: + type: str # THPDevice_type + index: _int # THPDevice_index + + def __get__(self, instance, owner=None) -> device: ... + + # THPDevice_pynew + @overload + def __init__(self, device: DeviceLikeType) -> None: ... + @overload + def __init__(self, type: str, index: _int) -> None: ... + + # Uncomment if we ever make torch.device a decorator + # def __call__(self, func: T) -> T: ... + + def __enter__(self) -> Self: ... + def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + def __reduce__(self) -> tuple[Any, ...]: ... # THPDevice_reduce + +# Defined in torch/csrc/Stream.cpp +class Stream: + stream_id: _int # Stream id + device_index: _int + device_type: _int + + device: _device # The device of the stream + + @overload + def __new__( + cls, + device: DeviceLikeType | None = None, + *, + priority: _int = 0, + ) -> Self: ... + @overload + def __new__( + cls, + stream_id: _int, + device_index: _int, + device_type: _int, + *, + priority: _int = 0, + ) -> Self: ... + def query(self) -> _bool: ... + def synchronize(self) -> None: ... + def is_capturing(self) -> _bool: ... + def wait_event(self, event: Event) -> None: ... + def wait_stream(self, other: Stream) -> None: ... + def record_event(self, event: Event | None = None) -> Event: ... + def __hash__(self) -> _int: ... + def __eq__(self, other: object) -> _bool: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + +# Defined in torch/csrc/Event.cpp +class Event: + device: _device # The device of the Event + event_id: _int # The raw event created by device backend + + def __new__( + cls, + device: DeviceLikeType | None = None, + *, + enable_timing: _bool = False, + blocking: _bool = False, + interprocess: _bool = False, + ) -> Self: ... + @classmethod + def from_ipc_handle(cls, device: _device, ipc_handle: bytes) -> Event: ... + def record(self, stream: Stream | None = None) -> None: ... + def wait(self, stream: Stream | None = None) -> None: ... + def query(self) -> _bool: ... + def elapsed_time(self, other: Event) -> _float: ... + def synchronize(self) -> None: ... + def ipc_handle(self) -> bytes: ... + +# Defined in torch/csrc/Size.cpp +class Size(tuple[_int, ...]): + # TODO: __reduce__ + + @overload + def __getitem__(self: Size, key: SupportsIndex, /) -> _int: ... + @overload + def __getitem__(self: Size, key: slice, /) -> Size: ... + # Note: torch.Size does not support adding non-integer tuples. + def __add__(self, other: tuple[_int, ...], /) -> Size: ... # type: ignore[override] + def __radd__(self: Size, other: tuple[_int, ...], /) -> Size: ... + def __mul__(self, other: SupportsIndex, /) -> Size: ... + def __rmul__(self, other: SupportsIndex, /) -> Size: ... + def numel(self: Size, /) -> _int: ... + +# Defined in torch/csrc/Dtype.cpp +class dtype: + # TODO: __reduce__ + is_floating_point: _bool + is_complex: _bool + is_signed: _bool + itemsize: _int + abbr: str + def to_real(self) -> dtype: ... + def to_complex(self) -> dtype: ... + +# Defined in torch/csrc/TypeInfo.cpp +class iinfo: + bits: _int + min: _int + max: _int + dtype: str + + def __init__(self, dtype: _dtype) -> None: ... + +class finfo: + bits: _int + min: _float + max: _float + eps: _float + tiny: _float + smallest_normal: _float + resolution: _float + dtype: str + + @overload + def __init__(self, dtype: _dtype) -> None: ... + @overload + def __init__(self) -> None: ... + +float32: dtype = ... +float: dtype = ... +float64: dtype = ... +double: dtype = ... +float16: dtype = ... +bfloat16: dtype = ... +float8_e4m3fn: dtype = ... +float8_e4m3fnuz: dtype = ... +float8_e5m2: dtype = ... +float8_e5m2fnuz: dtype = ... +float8_e8m0fnu: dtype = ... +float4_e2m1fn_x2: dtype = ... +half: dtype = ... +uint8: dtype = ... +uint16: dtype = ... +uint32: dtype = ... +uint64: dtype = ... +int8: dtype = ... +int16: dtype = ... +short: dtype = ... +int32: dtype = ... +int: dtype = ... +int64: dtype = ... +long: dtype = ... +complex32: dtype = ... +complex64: dtype = ... +chalf: dtype = ... +cfloat: dtype = ... +complex128: dtype = ... +cdouble: dtype = ... +bcomplex32: dtype = ... +quint8: dtype = ... +qint8: dtype = ... +qint32: dtype = ... +bool: dtype = ... +quint4x2: dtype = ... +quint2x4: dtype = ... +bits1x8: dtype = ... +bits2x4: dtype = ... +bits4x2: dtype = ... +bits8: dtype = ... +bits16: dtype = ... + +# Defined in torch/csrc/Layout.cpp +class layout: ... + +# Defined in torch/csrc/utils/disable_torch_function.cpp +def DisableTorchFunction() -> AbstractContextManager[None]: ... +def DisableTorchFunctionSubclass() -> AbstractContextManager[None]: ... + +# Defined in torch/csrc/utils/tensor_layouts.cpp +strided: layout = ... +sparse_coo: layout = ... +sparse_csr: layout = ... +sparse_csc: layout = ... +sparse_bsr: layout = ... +sparse_bsc: layout = ... +_mkldnn: layout = ... +jagged: layout = ... + +# Defined in torch/csrc/MemoryFormat.cpp +class memory_format: ... + +# Defined in torch/csrc/utils/tensor_memoryformats.cpp +contiguous_format: memory_format = ... +channels_last: memory_format = ... +channels_last_3d: memory_format = ... +preserve_format: memory_format = ... + +# Defined in torch/csrc/QScheme.cpp +class qscheme: ... + +# Defined in torch/csrc/utils/tensor_qschemes.h +per_tensor_affine: qscheme = ... +per_channel_affine: qscheme = ... +per_tensor_symmetric: qscheme = ... +per_channel_symmetric: qscheme = ... +per_channel_affine_float_qparams: qscheme = ... + +# Defined in torch/csrc/autograd/python_function.cpp +class _FunctionBase: + saved_tensors: tuple[Tensor] + _raw_saved_tensors: tuple[Any] + next_functions: tuple[tuple[Any, _int], ...] + needs_input_grad: tuple[_bool] + metadata: dict + _materialize_non_diff_grads: _bool + # skip adding type hints for the fields that have wrappers defined + # in torch/autograd/function.py + def _sequence_nr(self) -> _int: ... + def _register_hook_dict(self, tensor: Tensor) -> None: ... + def register_hook(self, hook: Callable[..., Any]) -> Any: ... + def register_prehook(self, hook: Callable[..., Any]) -> Any: ... + +# Defined in torch/csrc/autograd/python_legacy_variable.cpp +class _LegacyVariableBase(Tensor): # inherits from Tensor to appease mypy + def __init__( + self, + data: Tensor | None = ..., + requires_grad: _bool | None = ..., + volatile: _bool | None = ..., + _grad_fn: _FunctionBase | None = ..., + ) -> None: ... + +# Defined in torch/csrc/jit/python/init.cpp +class IODescriptor: ... +class JITException(Exception): ... + +class Future(Generic[T]): + def __init__(self, devices: list[device]) -> None: ... + def done(self) -> _bool: ... + def value(self) -> T: ... + def wait(self) -> T: ... + def add_done_callback(self, callback: Callable) -> None: ... + def then(self, callback: Callable) -> Future[T]: ... + def set_result(self, result: T) -> None: ... + def _set_unwrap_func(self, callback: Callable) -> None: ... + +class _Await: + def __init__(self) -> None: ... + def fn(self) -> Callable: ... + def args(self) -> tuple[Any, ...]: ... + def is_nowait(self) -> _bool: ... + +def _jit_set_num_profiled_runs(num: _size) -> _size: ... + +# Defined in torch/csrc/jit/passes/mobile_optimizer_type.h +class _MobileOptimizerType: ... + +CONV_BN_FUSION: _MobileOptimizerType +INSERT_FOLD_PREPACK_OPS: _MobileOptimizerType +REMOVE_DROPOUT: _MobileOptimizerType +FUSE_ADD_RELU: _MobileOptimizerType +HOIST_CONV_PACKED_PARAMS: _MobileOptimizerType +VULKAN_AUTOMATIC_GPU_TRANSFER: _MobileOptimizerType + +def fork(*args: Any, **kwargs: Any) -> Future: ... +def wait(fut: Future) -> Any: ... +def _awaitable(*args: Any, **kwargs: Any) -> _Await: ... +def _awaitable_wait(aw: _Await) -> Any: ... +def _awaitable_nowait(x: Any) -> _Await: ... +def _collect_all(futures: list[Future]) -> Future: ... +def _set_print_stack_traces_on_fatal_signal(print: _bool) -> None: ... +def unify_type_list(types: list[JitType]) -> JitType: ... +def _freeze_module( + module: ScriptModule, + preserved_attrs: list[str] = ..., + freeze_interfaces: _bool = True, + preserveParameters: _bool = True, +) -> ScriptModule: ... +def _jit_pass_optimize_frozen_graph(Graph, optimize_numerics: _bool = True) -> None: ... +def _jit_pass_optimize_for_inference( + module: torch.jit.ScriptModule, + other_methods: list[str] = ..., +) -> None: ... +def _jit_pass_fold_frozen_conv_bn(graph: Graph): ... +def _jit_pass_fold_frozen_conv_add_or_sub(graph: Graph): ... +def _jit_pass_fold_frozen_conv_mul_or_div(graph: Graph): ... +def _jit_pass_fuse_frozen_conv_add_relu(graph: Graph): ... +def _jit_pass_concat_frozen_linear(graph: Graph): ... +def _jit_pass_convert_frozen_ops_to_mkldnn(graph: Graph): ... +def _jit_pass_transpose_frozen_linear(graph: Graph): ... +def _jit_pass_remove_dropout(module: torch.jit.ScriptModule): ... +def _is_tracing() -> _bool: ... +def _jit_init() -> _bool: ... +def _jit_flatten(arg: Any) -> tuple[list[Tensor], IODescriptor]: ... +def _jit_unflatten(vars: list[Tensor], desc: IODescriptor) -> Any: ... +def _jit_get_operation(op_name: str) -> tuple[Callable, list[str]]: ... +def _get_operation_overload( + op_name: str, + op_overload_name: str, +) -> tuple[Callable, Callable, list[Any]]: ... +def _get_schema(op_name: str, overload_name: str) -> FunctionSchema: ... +def _jit_pass_optimize_for_mobile( + module: torch.jit.ScriptModule, + optimization_blocklist: set[_MobileOptimizerType], + preserved_methods: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _clone_module_with_class( + module: torch.jit.ScriptModule, + ignored_methods: list[AnyStr], + ignored_attributes: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _jit_pass_vulkan_optimize_for_mobile( + module: torch.jit.ScriptModule, + optimization_blocklist: set[_MobileOptimizerType], + preserved_methods: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _jit_pass_metal_optimize_for_mobile( + module: torch.jit.ScriptModule, + preserved_methods: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _jit_pass_inline(Graph) -> None: ... +def _jit_pass_constant_propagation(Graph) -> None: ... +def _jit_pass_propagate_shapes_on_graph(Graph) -> None: ... +def _jit_register_decomposition_for_schema(schema: FunctionSchema, Graph) -> None: ... +def _jit_erase_non_input_shape_information(Graph) -> None: ... +def _jit_get_schemas_for_operator(name: str) -> list[FunctionSchema]: ... +def _jit_get_all_schemas() -> list[FunctionSchema]: ... +def _jit_check_alias_annotation( + g: Graph, + args: tuple[Any, ...], + unqualified_op_name: str, +): ... +def _jit_can_fuse_on_cpu() -> _bool: ... +def _jit_can_fuse_on_gpu() -> _bool: ... +def _jit_can_fuse_on_cpu_legacy() -> _bool: ... +def _debug_get_fusion_group_inlining() -> _bool: ... +def _debug_set_fusion_group_inlining(enable: _bool): ... +def _jit_texpr_fuser_enabled() -> _bool: ... +def _jit_nvfuser_enabled() -> _bool: ... +def _jit_llga_enabled() -> _bool: ... +def _jit_set_llga_enabled(enable: _bool): ... +def _llvm_enabled() -> _bool: ... +def _jit_override_can_fuse_on_cpu(override: _bool): ... +def _jit_override_can_fuse_on_gpu(override: _bool): ... +def _jit_override_can_fuse_on_cpu_legacy(override: _bool): ... +def _jit_set_symbolic_shapes_test_mode(override: _bool): ... +def _jit_symbolic_shapes_test_mode_enabled() -> _bool: ... +def _jit_set_texpr_fuser_enabled(enable: _bool): ... +def _jit_set_te_must_use_llvm_cpu(use_llvm: _bool): ... +def _jit_set_nvfuser_enabled(enable: _bool) -> _bool: ... +def _jit_set_autocast_mode(enable: _bool) -> _bool: ... +def _jit_cat_wo_conditionals(optimize_cat: _bool): ... +def _jit_opt_conditionals(opt_conds: _bool): ... +def _jit_pass_canonicalize(graph: Graph, keep_unique_names: _bool = True): ... +def _jit_pass_erase_shape_information(graph: Graph): ... +def _jit_pass_fold_convbn(module: torch.jit.ScriptModule): ... +def _jit_pass_insert_observers( + module: torch.jit.ScriptModule, + method_name: str, + qconfig_dict: dict[str, Any], + inplace: _bool, + quant_type: _int, +): ... +def _jit_pass_insert_quant_dequant( + module: torch.jit.ScriptModule, + method_name: str, + inplace: _bool, + debug: _bool, + quant_type: _int, +): ... +def _jit_pass_insert_quant_dequant_for_ondevice_ptq( + module: torch.jit.ScriptModule, + method_name: str, + inplace: _bool, + debug: _bool, + quant_type: _int, +): ... +def _jit_pass_quant_finalize( + module: torch.jit.ScriptModule, + quant_type: _int, + preserved_attrs: Sequence[str], +): ... +def _jit_pass_quant_finalize_for_ondevice_ptq( + module: torch.jit.ScriptModule, + quant_type: _int, + method_name: str, +): ... +def _jit_pass_insert_observer_method_for_ondevice_ptq( + module: torch.jit.ScriptModule, + method_name: str, + qconfig_dict: dict[str, Any], + inplace: _bool, + quant_type: _int, +): ... +def _jit_set_profiling_executor(profiling_flag: _bool) -> _bool: ... +def _jit_set_profiling_mode(profiling_flag: _bool) -> _bool: ... +def _jit_set_fusion_strategy( + strategy: list[tuple[str, _int]], +) -> list[tuple[str, _int]]: ... +def _jit_try_infer_type(obj: Any) -> InferredType: ... +def _jit_get_trigger_value(trigger_name: str) -> _int: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +ResolutionCallback: TypeAlias = Callable[[str], Callable[..., Any]] + +# Defined in torch/csrc/jit/python/script_init.cpp +# and torch/csrc/jit/python/init.cpp +def _maybe_call_torch_function_for_op_packet( + op_overload_packet: Any, + *args: Any, + **kwargs: Any, +) -> Any: ... +def _check_schema_allow_fake_script_object( + schema: FunctionSchema, + *args: Any, + **kwargs: Any, +) -> _bool: ... +def _create_function_from_graph(qualname: str, graph: Graph) -> ScriptFunction: ... +def _debug_set_autodiff_subgraph_inlining(disabled: _bool) -> None: ... +def _ivalue_tags_match(lhs: ScriptModule, rhs: ScriptModule) -> _bool: ... +def _jit_assert_is_instance(obj: Any, type: JitType): ... +def _jit_clear_class_registry() -> None: ... +def _jit_set_emit_hooks( + ModuleHook: Callable | None, + FunctionHook: Callable | None, +) -> None: ... +def _jit_get_emit_hooks() -> tuple[Callable, Callable]: ... +def _load_for_lite_interpreter( + filename: str | Path, + map_location: DeviceLikeType | None, +): ... +def _load_for_lite_interpreter_from_buffer( + buffer: IO[bytes], + map_location: DeviceLikeType | None, +): ... +def _export_operator_list(module: LiteScriptModule): ... +def _quantize_ondevice_ptq_dynamic(module: LiteScriptModule, method_name: str): ... +def _get_model_bytecode_version(filename: str | Path) -> _int: ... +def _get_model_bytecode_version_from_buffer(buffer: IO[bytes]) -> _int: ... +def _backport_for_mobile( + filename_input: str | Path, + filename_output: str | Path, + to_version: _int, +) -> None: ... +def _backport_for_mobile_from_buffer( + buffer: IO[bytes], + filename_output: str | Path, + to_version: _int, +) -> None: ... +def _backport_for_mobile_to_buffer( + filename_input: str | Path, + to_version: _int, +) -> bytes: ... +def _backport_for_mobile_from_buffer_to_buffer( + buffer: IO[bytes], + to_version: _int, +) -> bytes: ... +def _get_model_ops_and_info(filename: str | Path): ... +def _get_model_ops_and_info_from_buffer(buffer: IO[bytes]): ... +def _get_mobile_model_contained_types(filename: str | Path): ... +def _get_mobile_model_contained_types_from_buffer(buffer: IO[bytes]): ... +def _logging_set_logger(logger: LoggerBase) -> LoggerBase: ... +def _get_graph_executor_optimize(optimize: _bool | None = None) -> _bool: ... +def _set_graph_executor_optimize(optimize: _bool): ... +def _export_opnames(module: ScriptModule) -> list[str]: ... +def _create_function_from_trace( + qualname: str, + func: Callable[..., Any], + input_tuple: tuple[Any, ...], + var_lookup_fn: Callable[[Tensor], str], + strict: _bool, + force_outplace: _bool, + argument_names: list[str], +) -> tuple[Graph, Stack]: ... +def _create_function_from_trace_with_dict( + qualname: str, + func: Callable[..., Any], + input_dict: dict[str, Any], + var_lookup_fn: Callable[[Tensor], str], + strict: _bool, + force_outplace: _bool, + argument_names: list[str], +) -> tuple[Graph, Stack]: ... +def _jit_is_script_object(obj: Any) -> _bool: ... +def _last_executed_optimized_graph() -> Graph: ... +def parse_type_comment(comment: str) -> Decl: ... +def _get_upgraders_map_size() -> _int: ... +def _get_upgraders_entry_map() -> dict[str, str]: ... +def _dump_upgraders_map() -> dict[str, str]: ... +def _test_only_populate_upgraders(content: dict[str, str]) -> None: ... +def _test_only_remove_upgraders(content: dict[str, str]) -> None: ... +def merge_type_from_type_comment( + decl: Decl, + type_annotation_decl: Decl, + is_method: _bool, +) -> Decl: ... +def parse_ir(input: str, parse_tensor_constants: _bool = False) -> Graph: ... +def parse_schema(schema: str) -> FunctionSchema: ... +def get_device(input: Tensor) -> _int: ... +def _resolve_type_from_object( + obj: Any, + range: SourceRange, + rcb: ResolutionCallback, +) -> JitType: ... +def _create_module_with_type(ty: JitType) -> ScriptModule: ... +def _create_object_with_type(ty: ClassType) -> ScriptObject: ... +def _run_emit_module_hook(m: ScriptModule): ... +def _replace_overloaded_method_decl( + overload_decl: Decl, + implementation_def: Def, + new_name: str, +) -> Def: ... +def _jit_pass_lower_all_tuples(graph: Graph) -> None: ... +def _jit_pass_onnx_set_dynamic_input_shape( + graph: Graph, + dynamic_axes: dict[str, dict[_int, str]], + input_names: list[str], +) -> None: ... +def _jit_pass_onnx_graph_shape_type_inference( + graph: Graph, + params_dict: dict[str, IValue], + opset_version: _int, +) -> None: ... +def _jit_pass_onnx_assign_output_shape( + graph: Graph, + tensors: list[Tensor], + desc: IODescriptor, + onnx_shape_inference: _bool, + is_script: _bool, + opset_version: _int, +) -> None: ... +def _jit_pass_onnx_remove_inplace_ops_for_onnx( + graph: Graph, + module: ScriptModule | None = None, +) -> None: ... +def _jit_pass_remove_inplace_ops(graph: Graph) -> None: ... +def _jit_pass_remove_mutation(graph: Graph) -> _bool: ... +def _jit_pass_canonicalize_graph_fuser_ops(graph: Graph) -> None: ... +def _jit_pass_peephole( + graph: Graph, + disable_shape_peepholes: _bool = False, +) -> None: ... +def _jit_pass_onnx_autograd_function_process(graph: Graph) -> None: ... +def _jit_pass_fuse_addmm(graph: Graph) -> None: ... +def _jit_pass_onnx_preprocess(graph: Graph) -> None: ... +def _jit_pass_prepare_division_for_onnx(graph: Graph) -> None: ... +def _jit_pass_onnx_remove_print(graph: Graph) -> None: ... +def _jit_pass_onnx_preprocess_caffe2(graph: Graph) -> None: ... +def _jit_pass_onnx_unpack_quantized_weights( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_onnx_quantization_insert_permutes( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_custom_pattern_based_rewrite_graph( + pattern: str, + fused_node_name: str, + graph: Graph, +) -> None: ... +def _jit_onnx_list_model_parameters( + module: ScriptModule, +) -> tuple[ScriptModule, list[IValue]]: ... +def _jit_pass_erase_number_types(graph: Graph) -> None: ... +def _jit_pass_onnx_lint(graph: Graph) -> None: ... +def _jit_pass_onnx( + graph: Graph, + _jit_pass_onnx: _onnx.OperatorExportTypes, +) -> Graph: ... +def _jit_pass_onnx_scalar_type_analysis( + graph: Graph, + lowprecision_cast: _bool, + opset_version: _int, +) -> None: ... +def _jit_pass_onnx_peephole( + graph: Graph, + opset_version: _int, + fixed_batch_size: _bool, +) -> None: ... +def _jit_pass_dce_allow_deleting_nodes_with_side_effects(graph: Graph) -> None: ... +def _jit_pass_onnx_function_substitution(graph: Graph) -> None: ... +def _jit_pass_onnx_function_extraction( + graph: Graph, + module_names: set[str], + param_names: list[str], +) -> dict[Node, dict[str, str]]: ... +def _jit_pass_onnx_clear_scope_records() -> None: ... +def _jit_pass_onnx_track_scope_attributes( + graph: Graph, + onnx_attrs: dict[str, Any], +) -> None: ... +def _jit_is_onnx_log_enabled() -> _bool: ... +def _jit_set_onnx_log_enabled(enabled: _bool) -> None: ... +def _jit_set_onnx_log_output_stream(stream_name: str) -> None: ... +def _jit_onnx_log(*args: Any) -> None: ... +def _jit_pass_lower_graph(graph: Graph, m: Module) -> tuple[Graph, list[IValue]]: ... +def _jit_pass_inline_fork_wait(graph: Graph) -> None: ... +def _jit_pass_onnx_deduplicate_initializers( + graph: Graph, + params_dict: dict[str, IValue], + is_train: _bool, +) -> dict[str, IValue]: ... +def _jit_pass_onnx_eval_peephole( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_onnx_constant_fold( + graph: Graph, + paramsDict: dict[str, IValue], + opset_version: _int, +) -> dict[str, IValue]: ... +def _jit_pass_onnx_eliminate_unused_items( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_onnx_cast_all_constant_to_floating(graph: Graph) -> None: ... +def _jit_pass_filter_non_tensor_arguments( + params: dict[str, IValue], +) -> dict[str, Tensor]: ... +def _jit_decay_packed_param_input_types(graph: Graph) -> None: ... +def _jit_pass_onnx_node_shape_type_inference( + n: Node, + paramsDict: dict[str, IValue], + opset_version: _int, +) -> None: ... +def _jit_onnx_convert_pattern_from_subblock( + block: Block, + n: Node, + env: dict[Value, Value], + values_in_env: set[Value], +) -> list[Value]: ... +def _jit_pass_onnx_block( + old_block: Block, + new_block: Block, + operator_export_type: _onnx.OperatorExportTypes, + env: dict[Value, Value], + values_in_env: set[Value], + is_sub_block: _bool, +) -> dict[Value, Value]: ... +def _jit_pass_onnx_assign_scoped_names_for_node_and_value(graph: Graph) -> None: ... +def _jit_pass_fixup_onnx_controlflow_node( + n: Node, + opset_version: _int, +) -> list[Value]: ... +def _jit_onnx_create_full_scope_name(class_name: str, variable_name: str) -> str: ... +def _compile_graph_to_code_table(name: str, graph: Graph) -> IValue: ... +def _generate_upgraders_graph() -> dict[str, Graph]: ... +def _calculate_package_version_based_on_upgraders(val: _bool): ... +def _get_version_calculator_flag() -> _bool: ... +def _jit_script_interface_compile( + name: str, + class_def: ClassDef, + rcb: ResolutionCallback, + is_module: _bool, +): ... +def _jit_script_compile_overload( + qualname: str, + overload_decl: Decl, + implementation_def: Def, + rcb: ResolutionCallback, + implementation_defaults: dict[str, Any], + signature: Any, +): ... +def _jit_script_compile( + qual_name: str, + definition: Def, + rcb: ResolutionCallback, + defaults: dict[str, Any], +): ... +def _jit_script_class_compile( + qual_name: str, + definition: ClassDef, + defaults: dict[str, dict[str, Any]], + rcb: ResolutionCallback, +): ... +def _parse_source_def(src: str) -> Def: ... +def import_ir_module( + cu: CompilationUnit, + filename: str | Path, + map_location: DeviceLikeType | None, + extra_files: dict[str, Any], +) -> ScriptModule: ... +def import_ir_module_from_buffer( + cu: CompilationUnit, + buffer: IO[bytes], + map_location: DeviceLikeType | None, + extra_files: dict[str, Any], +) -> ScriptModule: ... +def _import_ir_module_from_package( + cu: CompilationUnit, + reader: PyTorchFileReader, + storage_context: DeserializationStorageContext, + map_location: DeviceLikeType | None, + ts_id: str, +) -> ScriptModule: ... +def _assign_output_shapes(graph: Graph, inputs: list[Tensor]) -> Graph: ... +def _check_onnx_proto(proto: str) -> None: ... +def _propagate_and_assign_input_shapes( + graph: Graph, + inputs: tuple[Tensor, ...], + param_count_list: list[_int], + with_grad: _bool, + propagate: _bool, +) -> Graph: ... + +# Defined in torch/csrc/jit/runtime/graph_executor.h +class GraphExecutorState: ... + +# Defined in torch/torch/csrc/jit/ir/alias_analysis.h +class AliasDb: ... + +class _InsertPoint: + def __enter__(self) -> None: ... + def __exit__(self, *exc_info: object) -> None: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Use: + @property + def user(self) -> Node: ... + @property + def offset(self) -> _int: ... + def isAfter(self, other: Use) -> _bool: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Value: + def type(self) -> JitType: ... + def setType(self, t: JitType) -> Value: ... + def setTypeAs(self, other: Value) -> Value: ... + def inferTypeFrom(self, t: Tensor) -> None: ... + def debugName(self) -> str: ... + def setDebugName(self, name: str) -> None: ... + def unique(self) -> _int: ... + def offset(self) -> _int: ... + def node(self) -> Node: ... + def uses(self) -> list[Use]: ... + def replaceAllUsesWith(self, val: Value) -> None: ... + def replaceAllUsesAfterNodeWith(self, node: Node, val: Value) -> None: ... + def requires_grad(self) -> _bool: ... + def requiresGrad(self) -> _bool: ... + def copyMetadata(self, other: Value) -> Value: ... + def isCompleteTensor(self) -> _bool: ... + def toIValue(self) -> IValue: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Block: + def inputs(self) -> Iterator[Value]: ... + def outputs(self) -> Iterator[Value]: ... + def nodes(self) -> Iterator[Node]: ... + def paramNode(self) -> Node: ... + def returnNode(self) -> Node: ... + def owningNode(self) -> Node: ... + def registerOutput(self, n: Value) -> _int: ... + def addNode(self, name: str, inputs: Sequence[Value]) -> Node: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Node: + def __getitem__(self, key: str) -> Any: ... + def schema(self) -> str: ... + def input(self) -> Value: ... + def inputs(self) -> Iterator[Value]: ... + def inputsAt(self, idx: _int) -> Value: ... + def inputsSize(self) -> _int: ... + def output(self) -> Value: ... + def outputs(self) -> Iterator[Value]: ... + def outputsAt(self, idx: _int) -> Value: ... + def outputsSize(self) -> _int: ... + def hasMultipleOutputs(self) -> _bool: ... + def blocks(self) -> list[Block]: ... + def addBlock(self) -> Block: ... + def mustBeNone(self) -> _bool: ... + def matches(self, pattern: str) -> _bool: ... + def kind(self) -> str: ... + def kindOf(self, name: str) -> str: ... + def addInput(self, name: str) -> Value: ... + def replaceInput(self, i: _int, newValue: Value) -> Value: ... + def replaceInputWith(self, from_: Value, to: Value) -> None: ... + def replaceAllUsesWith(self, n: Node) -> None: ... + def insertBefore(self, n: Node) -> Node: ... + def insertAfter(self, n: Node) -> Node: ... + def isBefore(self, n: Node) -> _bool: ... + def isAfter(self, n: Node) -> _bool: ... + def moveBefore(self, n: Node) -> None: ... + def moveAfter(self, n: Node) -> None: ... + def removeInput(self, i: _int) -> None: ... + def removeAllInputs(self, i: _int) -> None: ... + def hasUses(self) -> _bool: ... + def eraseOutput(self, i: _int) -> None: ... + def addOutput(self) -> Value: ... + def scopeName(self) -> str: ... + def isNondeterministic(self) -> _bool: ... + def copyAttributes(self, rhs: Node) -> Node: ... + def copyMetadata(self, rhs: Node) -> Node: ... + def hasAttributes(self) -> _bool: ... + def hasAttribute(self, name: str) -> _bool: ... + def removeAttribute(self, attr: str) -> Node: ... + def namedInput(self, name: str) -> Value: ... + def sourceRange(self) -> SourceRange: ... + def owningBlock(self) -> Block: ... + def findNode(self, kind: str, recurse: _bool = True) -> Node: ... + def findAllNodes(self, kind: str, recurse: _bool = True) -> list[Node]: ... + def getModuleHierarchy(self) -> str: ... + def prev(self) -> Node: ... + def destroy(self) -> None: ... + def attributeNames(self) -> list[str]: ... + + # Accessors for attributes as types. + def f(self, name: str) -> _float: ... + def f_(self, name: str, val: _float) -> Node: ... + def fs(self, name: str) -> list[_float]: ... + def fs_(self, name: str, val: list[_float]) -> Node: ... + def c(self, name: str) -> complex: ... + def c_(self, name: str, val: complex) -> Node: ... + def s(self, name: str) -> str: ... + def s_(self, name: str, val: str) -> Node: ... + def ss(self, name: str) -> list[str]: ... + def ss_(self, name: str, val: list[str]) -> Node: ... + def i(self, name: str) -> _int: ... + def i_(self, name: str, val: _int) -> Node: ... + # Cannot define "is" like this because it's a reserved keyword in python. + # def is(self, name: str) -> List[_int]: ... + # def is_(self, name: str, val: List[_int]) -> Node: ... + def g(self, name: str) -> Graph: ... + def g_(self, name: str, val: Graph) -> Node: ... + def gs(self, name: str) -> list[Graph]: ... + def gs_(self, name: str, val: list[Graph]) -> Node: ... + def ival(self, name: str) -> IValue: ... + def ival_(self, name: str, val: IValue) -> Node: ... + def t(self, name: str) -> Tensor: ... + def t_(self, name: str, val: Tensor) -> Node: ... + def ts(self, name: str) -> list[Tensor]: ... + def ts_(self, name: str, val: list[Tensor]) -> Node: ... + def ty(self, name: str) -> JitType: ... + def ty_(self, name: str, val: JitType) -> Node: ... + def tys(self, name: str) -> list[JitType]: ... + def tys_(self, name: str, val: list[JitType]) -> Node: ... + +# Defined in torch/torch/csrc/jit/ir/ir.h +class Graph: + def inputs(self) -> Iterator[Value]: ... + def outputs(self) -> Iterator[Value]: ... + def nodes(self) -> Iterator[Node]: ... + def param_node(self) -> Node: ... + def return_node(self) -> Node: ... + def addInput(self, name: str = "") -> Value: ... + def eraseInput(self, i: _int) -> None: ... + def registerOutput(self, n: Value) -> _int: ... + def eraseOutput(self, i: _int) -> None: ... + def create(self, name: str, args, num_outputs: _int) -> Node: ... + def appendNode(self, n: Node) -> Node: ... + def prependNode(self, n: Node) -> Node: ... + def insertNode(self, n: Node) -> Node: ... + def block(self) -> Block: ... + def lint(self) -> None: ... + def alias_db(self) -> AliasDb: ... + def setInsertPoint(self, n: Block | Node) -> None: ... + def insert_point_guard(self, n: Block | Node) -> _InsertPoint: ... + def insertPoint(self) -> Node: ... + def insertGraph(self, callee: Graph, inputs: list[Value]) -> list[Value]: ... + def makeMultiOutputIntoTuple(self) -> None: ... + def copy(self) -> Graph: ... + +# Defined in torch/aten/src/ATen/core/alias_info.h +class AliasInfo: + is_write: _bool + before_set: set[str] + after_set: set[str] + def __init__( + self, + is_write: _bool, + before_set: set[str], + after_set: set[str], + ) -> None: ... + +# Defined in torch/aten/src/ATen/core/function_schema.h +class Argument: + name: str + type: JitType + default_value: Any | None + def has_default_value(self) -> _bool: ... + kwarg_only: _bool + is_out: _bool + alias_info: AliasInfo | None + is_write: _bool + real_type: JitType + def __init__( + self, + name: str, + type: JitType, + N: _int | None, + default_value: Any | None, + kwarg_only: _bool, + alias_info: AliasInfo | None, + ) -> None: ... + +class FunctionSchema: + arguments: list[Argument] + returns: list[Argument] + name: str + overload_name: str + is_mutable: _bool + def __init__( + self, + name: str, + overload_name: str, + arguments: list[Argument], + returns: list[Argument], + is_vararg: _bool, + is_varret: _bool, + ) -> None: ... + def _is_view_op(self) -> _bool: ... + +class _UpgraderEntry: + bumped_at_version: _int + upgrader_name: str + old_schema: str + def __init__( + self, + bumped_at_version: _int, + upgrader_name: str, + old_schema: str, + ) -> None: ... + +class _UpgraderRange: + min_version: _int + max_version: _int + +def _get_max_operator_version() -> _int: ... +def _get_operator_version_map() -> dict[str, list[_UpgraderEntry]]: ... +def _get_upgrader_ranges(name: str) -> list[_UpgraderRange]: ... +def _test_only_add_entry_to_op_version(op_name: str, entry: _UpgraderEntry) -> None: ... +def _test_only_remove_entry_to_op_version(op_name: str) -> None: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class ScriptModuleSerializer: + def __init__(self, export_writer: PyTorchFileWriter) -> None: ... + def serialize(self, model: ScriptModule, script_module_id: _int) -> None: ... + def write_files(self) -> None: ... + def storage_context(self) -> SerializationStorageContext: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class SerializationStorageContext: + def __init__(self) -> None: ... + def has_storage(self, storage: Storage) -> _bool: ... + def get_or_add_storage(self, storage: Storage) -> _int: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class DeserializationStorageContext: + def __init__(self) -> None: ... + def get_storage(self, name: str, dtype: _dtype) -> Tensor: ... + def has_storage(self, name: str) -> _bool: ... + def add_storage(self, name: str, tensor: Tensor) -> _int: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class ConcreteModuleTypeBuilder: + def __init__(self, obj: Any) -> None: ... + def set_module_dict(self) -> None: ... + def set_module_list(self) -> None: ... + def set_parameter_list(self) -> None: ... + def set_parameter_dict(self) -> None: ... + def add_attribute( + self, + name: str, + ty: JitType, + is_param: _bool, + is_buffer: _bool, + ) -> None: ... + def add_module(self, name: str, meta: ConcreteModuleType) -> None: ... + def add_constant(self, name: str, value: Any) -> None: ... + def add_overload( + self, method_name: str, overloaded_method_names: list[str] + ) -> None: ... + def add_builtin_function(self, name: str, symbol_name: str) -> None: ... + def add_failed_attribute(self, name: str, failure_reason: str) -> None: ... + def add_function_attribute( + self, + name: str, + ty: JitType, + func: Callable[..., Any], + ) -> None: ... + def add_ignored_attribute(self, name: str) -> None: ... + def add_ignored_attributes(self, names: list[str]) -> None: ... + def add_forward_hook(self, hook: Callable[..., Any]) -> None: ... + def add_forward_pre_hook(self, pre_hook: Callable[..., Any]) -> None: ... + +class ConcreteModuleType: + def get_constants(self) -> dict[str, Any]: ... + def equals(self, other: ConcreteModuleType) -> _bool: ... + @staticmethod + def from_jit_type(ty: JitType) -> ConcreteModuleType: ... + +class CallStack: + def __init__(self, name: str, range: SourceRange) -> None: ... + +class ErrorReport: + def __init__(self, range: SourceRange) -> None: ... + def what(self) -> str: ... + @staticmethod + def call_stack() -> str: ... + +class CompilationUnit: + def __init__(self, lang: str = ..., _frames_up: _int = ...) -> None: ... + def find_function(self, name: str) -> ScriptFunction: ... + def __getattr__(self, name: str) -> ScriptFunction: ... + def define( + self, + script: str, + rcb: ResolutionCallback = ..., + _frames_up: _int = ..., + ) -> list[ScriptFunction]: ... + def get_interface(self, name: str) -> InterfaceType: ... + def get_functions(self) -> None: ... + def create_function( + self, + name: str, + graph: Graph, + shouldMangle: _bool = ..., + ) -> ScriptFunction: ... + def get_class(self, name: str) -> ClassType: ... + +class ScriptObject: + def setattr(self, name: str, value: Any) -> None: ... + def _get_method(self, name: str) -> ScriptMethod: ... + def _type(self) -> ClassType: ... + +class ScriptModule(ScriptObject): + def _method_names(self) -> list[str]: ... + def _get_method(self, name: str) -> ScriptMethod: ... + +class LiteScriptModule: + def __call__(self, *input: Any) -> Any: ... + def find_method(self, method_name: str) -> bool: ... + def forward(self, *input: Any) -> list[str]: ... + def run_method(self, method_name: str, *input: Any) -> Any: ... + +# NOTE: switch to collections.abc.Callable in python 3.9 +class ScriptFunction(Generic[P, R]): + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... + def save(self, filename: str, _extra_files: dict[str, bytes]) -> None: ... + def save_to_buffer(self, _extra_files: dict[str, bytes]) -> bytes: ... + @property + def graph(self) -> Graph: ... + def inlined_graph(self) -> Graph: ... + def schema(self) -> FunctionSchema: ... + def code(self) -> str: ... + def name(self) -> str: ... + @property + def qualified_name(self) -> str: ... + +# NOTE: switch to collections.abc.Callable in python 3.9 +class ScriptMethod(Generic[P, R]): + graph: Graph + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... + @property + def owner(self) -> ScriptModule: ... + @property + def name(self) -> str: ... + @property + def schema(self) -> FunctionSchema: ... + +class ScriptDict(Generic[K, T]): + def __init__(self, dict: dict[K, T]) -> None: ... + def __len__(self) -> _int: ... + def __contains__(self, key: K) -> _bool: ... + def __getitem__(self, key: K) -> T: ... + def __setitem__(self, key: K, value: T) -> None: ... + def __delitem__(self, key: K) -> None: ... + def __iter__(self) -> Iterator[K]: ... + def items(self) -> Iterator[tuple[K, T]]: ... + def keys(self) -> Iterator[K]: ... + +class ScriptList(Generic[T]): + def __init__(self, list: list[T]) -> None: ... + def __len__(self) -> _int: ... + def __contains__(self, item: T) -> _bool: ... + @overload + def __getitem__(self, idx: _int) -> T: ... + @overload + def __getitem__(self, idx: slice) -> ScriptList[T]: ... + @overload + def __setitem__(self, idx: _int, value: T) -> None: ... + @overload + def __setitem__(self, idx: slice, value: list[T]) -> None: ... + def __delitem__(self, idx: _int) -> None: ... + def __iter__(self) -> Iterator[T]: ... + def count(self, value: T) -> _int: ... + def remove(self, value: T) -> None: ... + def append(self, value: T) -> None: ... + def clear(self) -> None: ... + @overload + def extend(self, values: list[T]) -> None: ... + @overload + def extend(self, values: Iterable[T]) -> None: ... + @overload + def pop(self) -> T: ... + @overload + def pop(self, idx: _int) -> T: ... + +class ModuleDict: + def __init__(self, mod: ScriptModule) -> None: ... + def items(self) -> list[tuple[str, Any]]: ... + +class ParameterDict: + def __init__(self, mod: ScriptModule) -> None: ... + +class BufferDict: + def __init__(self, mod: ScriptModule) -> None: ... + +# Defined in torch/csrc/jit/api/module.h +class Module: ... + +# Defined in torch/csrc/Module.cpp +def _initExtension(shm_manager_path: str) -> None: ... # THPModule_initExtension +def _autograd_init() -> _bool: ... # THPAutograd_initExtension +def _add_docstr(obj: T, doc_obj: str) -> T: ... # THPModule_addDocStr +def _init_names(arg: Sequence[type]) -> None: ... # THPModule_initNames +def _has_distributed() -> _bool: ... # THPModule_hasDistributed +def _set_default_tensor_type(type) -> None: ... # THPModule_setDefaultTensorType +def _set_default_dtype(d: _dtype) -> None: ... # THPModule_setDefaultDtype +def _infer_size(arg1: Size, arg2: Size) -> Size: ... # THPModule_inferSize +def _crash_if_csrc_asan() -> _int: ... # THPModule_crashIfCsrcASAN +def _crash_if_csrc_ubsan() -> _int: ... # THPModule_crashIfCsrcUBSAN +def _crash_if_aten_asan() -> _int: ... # THPModule_crashIfATenASAN +def _show_config() -> str: ... # THPModule_showConfig +def _cxx_flags() -> str: ... # THPModule_cxxFlags +def _parallel_info() -> str: ... # THPModule_parallelInfo +def _get_cpu_capability() -> str: ... # THPModule_getCpuCapability +def _set_backcompat_broadcast_warn( + arg: _bool, +) -> None: ... # THPModule_setBackcompatBroadcastWarn +def _get_backcompat_broadcast_warn() -> ( + _bool +): ... # THPModule_getBackcompatBroadcastWarn +def _set_backcompat_keepdim_warn( + arg: _bool, +) -> None: ... # THPModule_setBackcompatKeepdimWarn +def _get_backcompat_keepdim_warn() -> _bool: ... # THPModule_getBackcompatKeepdimWarn +def get_num_threads() -> _int: ... # THPModule_getNumThreads +def set_num_threads(nthreads: _int) -> None: ... # THPModule_setNumThreads +def get_num_interop_threads() -> _int: ... # THPModule_getNumInteropThreads +def set_num_interop_threads( + nthreads: _int, +) -> None: ... # THPModule_setNumInteropThreads +def _get_cudnn_enabled() -> _bool: ... # THPModule_userEnabledCuDNN +def _set_cudnn_enabled(arg: _bool) -> None: ... # THPModule_setUserEnabledCuDNN +def _get_flash_sdp_enabled() -> _bool: ... # THPModule_userEnabledFusedSDP +def _set_sdp_use_flash(arg: _bool) -> None: ... # THPModule_setSDPUseFlash +def _get_fa3_sdp_enabled() -> _bool: ... # THPModule_userEnabledFA3SDP +def _set_sdp_use_fa3(arg: _bool) -> None: ... # THPModule_setSDPUseFA3 +def _get_mem_efficient_sdp_enabled() -> _bool: ... # THPModule_userEnabledMathSDP +def _set_sdp_use_mem_efficient( + arg: _bool, +) -> None: ... # THPModule_setSDPUseMemEfficient +def _get_math_sdp_enabled() -> _bool: ... # THPModule_userEnabledMathSDP +def _set_sdp_use_math(arg: _bool) -> None: ... # THPModule_setSDPUseMath +def _get_math_sdp_allow_fp16_bf16_reduction() -> ( + _bool +): ... # THPModule_allowFP16BF16ReductionMathSDP +def _set_math_sdp_allow_fp16_bf16_reduction( + arg: _bool, +) -> None: ... # THPModule_setAllowFP16BF16ReductionMathSDP +def _get_overrideable_sdp_enabled() -> ( + _bool +): ... # THPModule_userEnabledOverrideableSDP +def _set_sdp_use_overrideable( + arg: _bool, +) -> None: ... # THPModule_setSDPUseOverrideable +def _get_sdp_priority_order() -> list[_int]: ... # THPModule_getSDPPriorityOrder +def _set_sdp_priority_order( + arg: list[_int], +) -> None: ... # THPModule_setSDPPriorityOrder +def _get_cudnn_sdp_enabled() -> _bool: ... # THPModule_userEnabledMathSDP +def _set_sdp_use_cudnn(arg: _bool) -> None: ... # THPModule_setSDPUseMath +def _get_mkldnn_enabled() -> _bool: ... # THPModule_userEnabledMkldnn +def _set_mkldnn_enabled(arg: _bool) -> None: ... # THPModule_setUserEnabledMkldnn +def _get_cudnn_benchmark() -> _bool: ... # THPModule_benchmarkCuDNN +def _set_cudnn_benchmark(arg: _bool) -> None: ... # THPModule_setBenchmarkCuDNN +def _get_cudnn_depthwise_kernel() -> str: ... # THPModule_getCuDNNDepthwiseKernel +def _set_cudnn_depthwise_kernel( + arg: str, +) -> None: ... # THPModule_setCuDNNDepthwiseKernel +def _get_miopen_immediate() -> _bool: ... # THPModule_userImmediateMiopen +def _set_miopen_immediate(arg: _bool) -> None: ... # THPModule_setUserImmediateMiopen +def _get_cudnn_deterministic() -> _bool: ... # THPModule_deterministicCuDNN +def _set_cudnn_deterministic(arg: _bool) -> None: ... # THPModule_setDeterministicCuDNN +def _get_mkldnn_deterministic() -> _bool: ... # THPModule_deterministicMkldnn +def _set_mkldnn_deterministic( + arg: _bool, +) -> None: ... # THPModule_setDeterministicMkldnn +def _get_onednn_allow_tf32() -> _bool: ... # THPModule_allowTF32OneDNN +def _set_onednn_allow_tf32(arg: _bool) -> None: ... # THPModule_setAllowTF32OneDNN +def _get_deterministic_algorithms() -> _bool: ... # THPModule_deterministicAlgorithms +def _get_deterministic_algorithms_warn_only() -> ( + _bool +): ... # THPModule_deterministicAlgorithmsWarnOnly +def _set_deterministic_algorithms( + mode: _bool, + *, + warn_only: _bool = ..., +) -> None: ... # THPModule_setDeterministicAlgorithms +def _get_deterministic_fill_uninitialized_memory() -> ( + _bool +): ... # THPModule_deterministicFillUninitializedMemory +def _set_deterministic_fill_uninitialized_memory( + arg: _bool, +) -> None: ... # THPModule_setDeterministicFillUninitializedMemory +def _get_nnpack_enabled() -> _bool: ... # THPModule_userEnabledNNPACK +def _set_nnpack_enabled(arg: _bool) -> None: ... # THPModule_setUserEnabledNNPACK +def _get_warnAlways() -> _bool: ... # THPModule_warnAlways +def _set_warnAlways(arg: _bool) -> None: ... # THPModule_setWarnAlways +def _get_cudnn_allow_tf32() -> _bool: ... # THPModule_allowTF32CuDNN +def _set_cudnn_allow_tf32(arg: _bool) -> None: ... # THPModule_setAllowTF32CuDNN +def _get_cublas_allow_tf32() -> _bool: ... # THPModule_allowTF32CuBLAS +def _set_cublas_allow_tf32(arg: _bool) -> None: ... # THPModule_setAllowTF32CuBLAS +def _get_cublaslt_prefer_grouped_gemm() -> _bool: ... # THPModule_preferCublasltGroupedGemm +def _set_cublaslt_prefer_grouped_gemm( + arg: _bool, +) -> None: ... # THPModule_setPreferCublasltGroupedGemm +def _get_float32_matmul_precision() -> str: ... # THPModule_float32MatmulPrecision +def _set_float32_matmul_precision( + arg: str, +) -> None: ... # THPModule_setFloat32MatmulPrecision +def _get_cublas_allow_fp16_reduced_precision_reduction() -> tuple[ + _bool, _bool +]: ... # THPModule_allowFP16ReductionCuBLAS +def _set_cublas_allow_fp16_reduced_precision_reduction( + arg: _bool, + allow_splitk: _bool = ..., +) -> None: ... # THPModule_setAllowFP16ReductionCuBLAS +def _get_cublas_allow_bf16_reduced_precision_reduction() -> tuple[ + _bool, _bool +]: ... # THPModule_allowBF16ReductionCuBLAS +def _set_cublas_allow_bf16_reduced_precision_reduction( + arg: _bool, + allow_splitk: _bool = ..., +) -> None: ... # THPModule_setAllowBF16ReductionCuBLAS +def _get_cublas_allow_fp16_accumulation() -> ( + _bool +): ... # THPModule_allowFP16AccumulationCuBLAS +def _set_cublas_allow_fp16_accumulation( + arg: _bool, +) -> None: ... # THPModule_setAllowFP16AccumulationCuBLAS +def _get_sm_carveout_experimental() -> _int | None: ... +def _set_sm_carveout_experimental(arg: _int | None) -> None: ... +def _set_conj(x: Tensor, conj: _bool) -> None: ... +def _set_neg(x: Tensor, neg: _bool) -> None: ... +def _set_meta_in_tls_dispatch_include(meta_in_tls: _bool) -> None: ... +def _autocast_supported_devices() -> list[str]: ... +def _meta_in_tls_dispatch_include() -> _bool: ... +def _stash_obj_in_tls(key: str, arg: Any) -> None: ... +def _get_obj_in_tls(key: str) -> Any: ... +def _is_key_in_tls(key: str) -> _bool: ... +def _remove_obj_from_tls(key: str) -> None: ... +def _select_batch_norm_backend(*args, **kwargs) -> BatchNormBackend: ... +def _select_conv_backend(*args, **kwargs) -> ConvBackend: ... +def _conv_determine_backend_memory_format( + input: Tensor, + weight: Tensor, + backend: ConvBackend, +) -> memory_format: ... +def _has_storage(x: Tensor) -> _bool: ... +def _construct_storage_from_data_pointer( + data_ptr: _int, + device: torch.device, + size: _int, +) -> Storage: ... +def _should_allow_numbers_as_tensors(func_name: str) -> _bool: ... +def _group_tensors_by_device_and_dtype( + nested_tensorlists: list[list[Tensor | None]], + with_indices: _bool = False, +) -> dict[ + tuple[torch.device, torch.dtype], + tuple[list[list[Tensor | None]], list[_int]], +]: ... +def _initCrashHandler() -> None: ... +def _set_warn_on_accumulate_grad_stream_mismatch(enabled: _bool) -> None: ... +def _set_override_stale_capture_stream(enabled: _bool) -> None: ... +def _override_stale_capture_stream() -> _bool: ... + +# NB: There is no Capsule type in typing, see +# https://github.com/python/cpython/issues/109562 +def _to_dlpack( + data: Tensor, + dl_device: tuple[IntEnum, _int] | None = None, + copy: _bool | None = None, + read_only: _bool = False, +) -> Any: ... # THPModule_toDLPack +def _to_dlpack_versioned( + data: Tensor, + dl_device: tuple[IntEnum, _int] | None = None, + copy: _bool | None = None, + read_only: _bool = False, +) -> Any: ... # THPModule_toDLPackVersioned +def _from_dlpack(data: Any) -> Tensor: ... # THPModule_fromDLPack +def _torchDeviceToDLDevice( + device: torch.device, +) -> tuple[_int, _int]: ... # THPModule_torchDeviceToDLDevice +def _dlpack_exchange_api() -> object: ... # THPModule_DLPackExchangeAPI +def _const_dlpack_exchange_api() -> object: ... # THPModule_ConstDLPackExchangeAPI +def _get_cpp_backtrace( + frames_to_skip: _int, + maximum_number_of_frames: _int, +) -> str: ... # THPModule_getCppBacktrace +def set_flush_denormal(arg: _bool) -> _bool: ... # THPModule_setFlushDenormal +def get_default_dtype() -> _dtype: ... # THPModule_getDefaultDtype +def _get_all_dtypes() -> list[_dtype]: ... # THPModule_getAllDtypes +def _get_default_device() -> str: ... # THPModule_getDefaultDevice +def _get_qengine() -> _int: ... # THPModule_qEngine +def _set_qengine(qengine: _int) -> None: ... # THPModule_setQEngine +def _supported_qengines() -> list[_int]: ... # THPModule_supportedQEngines +def _is_xnnpack_enabled() -> _bool: ... # THPModule_isEnabledXNNPACK +def _check_sparse_tensor_invariants() -> ( + _bool +): ... # THPModule_checkSparseTensorInvariants +def _set_check_sparse_tensor_invariants( + arg: _bool, +) -> None: ... # THPModule_setCheckSparseTensorInvariants +def _is_default_mobile_cpu_allocator_set() -> ( + _bool +): ... # THPModule_isDefaultMobileCPUAllocatorSet +def _set_default_mobile_cpu_allocator() -> ( + None +): ... # THPModule_setDefaultMobileCPUAllocator +def _unset_default_mobile_cpu_allocator() -> ( + None +): ... # THPModule_unsetDefaultMobileCPUAllocator +def _is_torch_function_enabled() -> _bool: ... # THPModule_isEnabledTorchFunction +def _is_torch_function_all_disabled() -> ( + _bool +): ... # THPModule_isAllDisabledTorchFunction +def _peek_should_skip_torch_function() -> _bool: ... # THPModule_peek_should_skip_torch_function +def _has_torch_function( + args: Iterable[Any], +) -> _bool: ... # THPModule_has_torch_function +def _has_torch_function_unary(Any) -> _bool: ... # THPModule_has_torch_function_unary +def _has_torch_function_variadic( + *args: Any, +) -> _bool: ... # THPModule_has_torch_function_variadic +def _vmapmode_increment_nesting() -> _int: ... # THPModule_vmapmode_increment_nesting +def _vmapmode_decrement_nesting() -> _int: ... # THPModule_vmapmode_decrement_nesting +def _log_api_usage_once(str) -> None: ... # LogAPIUsageOnceFromPython +def _log_api_usage_metadata( + event: str, + metadata_map: dict[str, str], +) -> None: ... # LogAPIUsageMetadataFromPython +def _demangle(str) -> str: ... # c10::demangle +def _getenv(name: str) -> str | None: ... # c10::utils::get_env +def _setenv(name: str, value: str, overwrite: _bool = True) -> None: ... # c10::utils::set_env +def _unsetenv(name: str) -> None: ... # c10::utils::unset_env +def _fake_dispatch_register_decomp(name: str, overload: str) -> None: ... +def _fake_dispatch_register_meta(name: str, overload: str) -> None: ... +def _fake_dispatch_register_op_impl(name: str, overload: str) -> None: ... +def _fake_dispatch_register_prim_meta(name: str, overload: str) -> None: ... +def _fake_dispatch_deregister_op_impl(name: str, overload: str) -> None: ... +def _disabled_torch_function_impl( + func: Callable, + types: Iterable[type], + args: tuple, + kwargs: dict, +) -> Any: ... # THPModule_disable_torch_function +def _disabled_torch_dispatch_impl( + func: Callable, + types: Iterable[type], + args: tuple, + kwargs: dict, +) -> Any: ... # THPModule_disable_dispatch_function +def _skip_one_hop_torch_function( + func: Callable, types: Iterable[type], args: tuple, kwargs: dict +) -> Any: ... # THPModule_skip_one_hop_torch_function +def _get_linalg_preferred_backend() -> _LinalgBackend: ... +def _set_linalg_preferred_backend(arg: _LinalgBackend): ... +def _get_fp32_precision_getter(backend: str, op: str) -> str: ... +def _set_fp32_precision_setter(backend: str, op: str, value: str) -> str: ... +def _ensureCUDADeviceGuardSet() -> None: ... + +class _LinalgBackend: + Default: _LinalgBackend + Cusolver: _LinalgBackend + Magma: _LinalgBackend + +# mypy error: +# Detected enum "torch._C.BatchNormBackend" in a type stub with zero +# members. There is a chance this is due to a recent change in the semantics +# of enum membership. If so, use `member = value` to mark an enum member, +# instead of `member: type` +class BatchNormBackend(Enum): ... # type: ignore[misc] + +def _get_blas_preferred_backend() -> _BlasBackend: ... +def _set_blas_preferred_backend(arg: _BlasBackend): ... +def _get_blas_default_backend() -> _BlasBackend: ... + +class _BlasBackend: + Default: _BlasBackend + Cublas: _BlasBackend + Cublaslt: _BlasBackend + Ck: _BlasBackend + +def _get_rocm_fa_preferred_backend() -> torch._C._ROCmFABackend: ... +def _set_rocm_fa_preferred_backend(arg: torch._C._ROCmFABackend): ... + +class _ROCmFABackend: + Default: _ROCmFABackend + AOTriton: _ROCmFABackend + Ck: _ROCmFABackend + +# mypy error: +# Error (MYPY) [misc] +# Detected enum "torch._C.ConvBackend" in a type stub with zero members. +# There is a chance this is due to a recent change in the semantics of enum +# membership. If so, use `member = value` to mark an enum member, instead of +# `member: type` +class ConvBackend(Enum): ... # type: ignore[misc] + +class Tag(Enum): + core = 0 + cudagraph_unsafe = 1 + data_dependent_output = 2 + dynamic_output_shape = 3 + flexible_layout = 4 + generated = 5 + inplace = 6 + inplace_view = 7 + maybe_aliasing_or_mutating = 8 + needs_contiguous_strides = 9 + needs_exact_strides = 10 + needs_fixed_stride_order = 11 + nondeterministic_bitwise = 12 + nondeterministic_seeded = 13 + out = 14 + out_variant = 15 + pointwise = 16 + pt2_compliant_tag = 17 + reduction = 18 + view_copy = 19 + +# Defined in `valgrind.h` and `callgrind.h` respectively. +def _valgrind_supported_platform() -> _bool: ... # NVALGRIND +def _valgrind_toggle() -> None: ... # CALLGRIND_TOGGLE_COLLECT +def _valgrind_toggle_and_dump_stats() -> ( + None +): ... # CALLGRIND_TOGGLE_COLLECT and CALLGRIND_DUMP_STATS + +has_openmp: _bool +has_mkl: _bool +_has_kleidiai: _bool +_has_mps: _bool +has_lapack: _bool +_has_cuda: _bool +_has_magma: _bool +_has_xpu: _bool +_has_mkldnn: _bool +_has_mkldnn_acl: _bool +_has_cudnn: _bool +_has_cusparselt: _bool +_has_gds: _bool +has_spectral: _bool +_GLIBCXX_USE_CXX11_ABI: _bool +default_generator: Generator + +# Defined in torch/csrc/autograd/init.cpp +def _set_grad_enabled(enabled: _bool) -> None: ... +def is_grad_enabled() -> _bool: ... +def _set_fwd_grad_enabled(enabled: _bool) -> None: ... +def _is_fwd_grad_enabled() -> _bool: ... +def _any_requires_grad(*args, **kwargs) -> _bool: ... +def _any_output_is_alias_to_input_or_output(*args, **kwargs) -> _bool: ... +def is_inference_mode_enabled() -> _bool: ... +@overload +def set_autocast_enabled(device_type: str, enabled: _bool) -> None: ... +@overload +def set_autocast_enabled(enabled: _bool) -> None: ... +@overload +def is_autocast_enabled(device_type: str) -> _bool: ... +@overload +def is_autocast_enabled() -> _bool: ... +def set_autocast_dtype(device_type: str, dtype: _dtype) -> None: ... +def get_autocast_dtype(device_type: str) -> _dtype: ... +def clear_autocast_cache() -> None: ... +def set_autocast_cpu_enabled(enabled: _bool) -> None: ... +def is_autocast_cpu_enabled() -> _bool: ... +def _is_any_autocast_enabled() -> _bool: ... +def _is_autocast_available(device_type: str) -> _bool: ... +def set_autocast_cpu_dtype(dtype: _dtype) -> None: ... +def set_autocast_gpu_dtype(dtype: _dtype) -> None: ... +def get_autocast_cpu_dtype() -> _dtype: ... +def get_autocast_gpu_dtype() -> _dtype: ... +def autocast_increment_nesting() -> _int: ... +def autocast_decrement_nesting() -> _int: ... +def is_autocast_cache_enabled() -> _bool: ... +def set_autocast_cache_enabled(enabled: _bool) -> None: ... +def _increment_version(tensors: Iterable[Tensor]) -> None: ... +def set_anomaly_enabled(enabled: _bool, check_nan: _bool = True) -> None: ... +def is_anomaly_enabled() -> _bool: ... +def is_anomaly_check_nan_enabled() -> _bool: ... +def _is_multithreading_enabled() -> _bool: ... +def _set_multithreading_enabled(enabled: _bool) -> None: ... +def _set_view_replay_enabled(enabled: _bool) -> None: ... +def _is_view_replay_enabled() -> _bool: ... +def _is_grad_layout_enforcement_enabled() -> _bool: ... +def _set_grad_layout_enforcement_enabled(enabled: _bool) -> None: ... +def _set_graph_exec_group(group: GraphExecGroup | None) -> None: ... +def _get_graph_exec_group() -> GraphExecGroup | None: ... +def _enter_dual_level() -> _int: ... +def _exit_dual_level(level: _int) -> None: ... +def _make_dual(tensor: Tensor, tangent: Tensor, level: _int) -> Tensor: ... +def _unpack_dual(tensor: Tensor, level: _int) -> Tensor: ... +def __set_forward_AD_enabled(enabled: _bool) -> None: ... +def __is_forward_AD_enabled() -> _bool: ... +def _register_default_hooks(pack_hook: Callable, unpack_hook: Callable) -> None: ... +def _reset_default_hooks() -> None: ... +def _is_torch_function_mode_enabled() -> _bool: ... +def _push_on_torch_function_stack(cls: Any) -> None: ... +def _pop_torch_function_stack() -> Any: ... +def _get_function_stack_at(idx: _int) -> Any: ... +def _len_torch_function_stack() -> _int: ... +def _set_torch_dispatch_mode(cls: Any) -> None: ... +def _push_on_torch_dispatch_stack(cls: TorchDispatchMode) -> None: ... +def _pop_torch_dispatch_stack(mode_key: _TorchDispatchModeKey | None = None) -> Any: ... +def _get_dispatch_mode(mode_key: _TorchDispatchModeKey | None) -> Any: ... +def _unset_dispatch_mode(mode: _TorchDispatchModeKey) -> TorchDispatchMode | None: ... +def _set_dispatch_mode(mode: TorchDispatchMode) -> None: ... +def _get_dispatch_stack_at(idx: _int) -> Any: ... +def _len_torch_dispatch_stack() -> _int: ... +def _activate_gpu_trace() -> None: ... + +class _DisableTorchDispatch: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _EnableTorchFunction: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _EnablePythonDispatcher: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _DisablePythonDispatcher: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _EnablePreDispatch: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _DisableFuncTorch: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _DisableAutocast: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _InferenceMode: + def __init__(self, enabled: _bool) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +def _set_autograd_fallback_mode(mode: str) -> None: ... +def _get_autograd_fallback_mode() -> str: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class LoggerBase: ... +class NoopLogger(LoggerBase): ... +class LockingLogger(LoggerBase): ... + +class AggregationType(Enum): + SUM = 0 + AVG = 1 + +class FileCheck: + def run(self, test_string: str) -> None: ... + def check(self, test_string: str) -> FileCheck: ... + def check_not(self, test_string: str) -> FileCheck: ... + def check_same(self, test_string: str) -> FileCheck: ... + def check_next(self, test_string: str) -> FileCheck: ... + def check_count( + self, + test_string: str, + count: _int, + exactly: _bool = False, + ) -> FileCheck: ... + def check_dag(self, test_string: str) -> FileCheck: ... + def check_source_highlighted(self, test_string: str) -> FileCheck: ... + def check_regex(self, test_string: str) -> FileCheck: ... + +# Defined in torch/csrc/jit/python/init.cpp +class PyTorchFileReader: + @overload + def __init__(self, name: str) -> None: ... + @overload + def __init__(self, buffer: IO[bytes]) -> None: ... + def get_record(self, name: str) -> bytes: ... + def get_all_records(self) -> list[str]: ... + def get_record_size(self, name: str) -> _int: ... + def get_storage_from_record(self, name: str, numel: _int, dtype: dtype) -> Tensor: ... + def serialization_id(self) -> str: ... + +class PyTorchFileWriter: + @overload + def __init__( + self, + name: str, + compute_crc32: _bool = True, + storage_alignment: _int = 64, + ) -> None: ... + @overload + def __init__( + self, + buffer: IO[bytes], + compute_crc32: _bool = True, + storage_alignment: _int = 64, + ) -> None: ... + def write_record( + self, + name: str, + data: Storage | bytes | _int, + size: _int, + ) -> None: ... + def write_end_of_file(self) -> None: ... + def set_min_version(self, version: _int) -> None: ... + def get_all_written_records(self) -> list[str]: ... + def archive_name(self) -> str: ... + def serialization_id(self) -> str: ... + +def _jit_get_inline_everything_mode() -> _bool: ... +def _jit_set_inline_everything_mode(enabled: _bool) -> None: ... +def _jit_get_logging_option() -> str: ... +def _jit_set_logging_option(option: str) -> None: ... +def _jit_set_logging_stream(stream_name: str) -> None: ... +def _jit_pass_cse(Graph) -> _bool: ... +def _jit_pass_dce(Graph) -> None: ... +def _jit_pass_dce_graph(Graph) -> None: ... +def _jit_pass_lint(Graph) -> None: ... +def _register_opaque_type(type_name: str) -> None: ... +def _is_opaque_type_registered(type_name: str) -> _bool: ... + +# Defined in torch/csrc/jit/python/python_custom_class.cpp +def _get_custom_class_python_wrapper(name: str, attr: str) -> Any: ... + +# Defined in torch/csrc/Module.cpp +def _rename_privateuse1_backend(backend: str) -> None: ... +def _get_privateuse1_backend_name() -> str: ... + +# Defined in torch/csrc/Generator.cpp +def _set_generator_metaclass(metaclass: type) -> None: ... + +class Generator: + device: _device + def __init__(self, device: DeviceLikeType | None = None) -> None: ... + def __reduce__( + self, + ) -> tuple[type[Generator], tuple[_device], tuple[_int, _int | None, Tensor]]: ... + def __setstate__(self, state: tuple[_int, _int | None, Tensor]) -> None: ... + def get_state(self) -> Tensor: ... + def set_state(self, _new_state: Tensor) -> Generator: ... + def clone_state(self) -> Generator: ... + def graphsafe_get_state(self) -> Generator: ... + def graphsafe_set_state(self, _new_state: Generator) -> Generator: ... + def set_offset(self, offset: _int) -> Generator: ... + def get_offset(self) -> _int: ... + def philox_state(self, increment: _int) -> tuple[Tensor, Tensor, Tensor]: ... + def manual_seed(self, seed: _int) -> Generator: ... + def seed(self) -> _int: ... + def initial_seed(self) -> _int: ... + +# Defined in torch/csrc/utils/python_dispatch.cpp + +class _DispatchOperatorHandle: + def schema(self) -> FunctionSchema: ... + def debug(self) -> str: ... + def redispatch_boxed(self, keyset: DispatchKeySet, *args, **kwargs) -> Any: ... + +class _DispatchModule: + def reset(self) -> None: ... + def def_(self, schema: str, alias: str = "") -> _DispatchModule: ... + def def_legacy(self, schema: str) -> _DispatchModule: ... + def def_name_t_t( + self, + name: str, + dispatch: str, + debug: str = "default_def_name_t_t", + ) -> _DispatchModule: ... + def def_schema_t_t( + self, + schema: str, + dispatch: str, + alias: str, + debug: str = "default_def_schema_t_t", + ) -> _DispatchModule: ... + def impl_t_t( + self, + name: str, + dispatch: str, + debug: str = "impl_t_t", + ) -> _DispatchModule: ... + def impl_with_aoti_compile( + self, + ns: str, + op_name_with_overload: str, + dispatch: _dispatchkey, + ) -> None: ... + def impl(self, name: str, dispatch: _dispatchkey, func: Callable) -> None: ... + def define(self, schema: str, alias: str = "") -> str: ... + def fallback_fallthrough(self, dispatch: str = "") -> _DispatchModule: ... + def fallback( + self, + dispatch: _dispatchkey, + func: Callable, + with_keyset: _bool = False, + ) -> None: ... + +_after_ADInplaceOrView_keyset: DispatchKeySet +_after_autograd_keyset: DispatchKeySet + +class _SafeKernelFunction: + def call_boxed(self, keyset: DispatchKeySet, *args, **kwargs) -> Any: ... + @property + def op_handle(self) -> _DispatchOperatorHandle: ... + +def _dispatch_library( + kind: str, + name: str, + dispatch: str, + file: str = "", + linenum: Any = 0, +) -> _DispatchModule: ... +def _dispatch_dump(name: str) -> str: ... +def _dispatch_dump_table(name: str) -> str: ... +def _dispatch_check_invariants(name: str) -> None: ... +def _dispatch_check_all_invariants() -> None: ... +def _dispatch_call_boxed(handle: _DispatchOperatorHandle, *args, **kwargs) -> Any: ... +def _dispatch_make_pyobj_dispatch_fns( + handle: _DispatchOperatorHandle, + dispatch_cpp: Callable, + redispatch_cpp: Callable, +) -> tuple[Callable, Callable]: ... +def _dispatch_find_schema_or_throw( + name: str, + overload_name: str, +) -> _DispatchOperatorHandle: ... +def _dispatch_set_report_error_callback( + handle: _DispatchOperatorHandle, + callback: Callable, +) -> None: ... +def _dispatch_has_kernel(name: str) -> _bool: ... +def _dispatch_has_kernel_for_dispatch_key( + name: str, + dispatch: _dispatchkey, +) -> _bool: ... +def _dispatch_has_kernel_for_any_dispatch_key( + name: str, + dispatch_key_set: DispatchKeySet, +) -> _bool: ... +def _dispatch_kernel_for_dispatch_key_is_fallthrough( + name: str, + dispatch: _dispatchkey, +) -> _bool: ... +def _dispatch_has_computed_kernel_for_dispatch_key( + name: str, + dispatch: _dispatchkey, +) -> _bool: ... +def _dispatch_get_computed_kernel_for_dispatch_key( + name: str, + dispatch: _dispatchkey, +) -> _SafeKernelFunction: ... +def _dispatch_find_dangling_impls() -> list[str]: ... +def _dispatch_get_all_op_names() -> list[str]: ... +def _dispatch_tls_set_dispatch_key_excluded( + dispatch: _dispatchkey, + val: _bool, +) -> None: ... +def _dispatch_tls_is_dispatch_key_excluded(dispatch: _dispatchkey) -> _bool: ... +def _dispatch_tls_set_dispatch_key_included( + dispatch: _dispatchkey, + val: _bool, +) -> None: ... +def _dispatch_tls_is_dispatch_key_included(dispatch: _dispatchkey) -> _bool: ... +def _dispatch_isTensorSubclassLike(tensor: Tensor) -> _bool: ... +def _dispatch_key_name(dispatch: _dispatchkey) -> str: ... +def _dispatch_key_for_device(device_type: str) -> str: ... +def _parse_dispatch_key(key: str) -> DispatchKey | None: ... +def _dispatch_key_parse(dispatch: _dispatchkey) -> DispatchKey: ... +def _dispatch_num_backends() -> _int: ... +def _dispatch_pystub(name: str, overload: str) -> tuple[str, str] | None: ... +def _dispatch_is_alias_key(dispatch: _dispatchkey) -> _bool: ... +def _functionality_to_backend_keys(dispatch: _dispatchkey) -> list[DispatchKey]: ... +def _functionalization_reapply_views_tls() -> _bool: ... +def _only_lift_cpu_tensors() -> _bool: ... +def _set_only_lift_cpu_tensors(value: _bool) -> None: ... +def _set_throw_on_mutable_data_ptr(tensor: Tensor) -> None: ... +def _set_warn_deprecated_on_mutable_data_ptr(tensor: Tensor) -> None: ... + +class DispatchKey(Enum): + Undefined = ... + FPGA = ... + MAIA = ... + Vulkan = ... + Metal = ... + MKLDNN = ... + OpenGL = ... + OpenCL = ... + IDEEP = ... + CustomRNGKeyId = ... + MkldnnCPU = ... + Sparse = ... + SparseCsr = ... + NestedTensor = ... + Dense = ... + PythonTLSSnapshot = ... + PreDispatch = ... + PythonDispatcher = ... + Python = ... + FuncTorchDynamicLayerBackMode = ... + ZeroTensor = ... + Conjugate = ... + Negative = ... + BackendSelect = ... + Named = ... + AutogradOther = ... + AutogradFunctionality = ... + AutogradNestedTensor = ... + Tracer = ... + Autocast = ... + AutocastCPU = ... + AutocastCUDA = ... + AutocastXPU = ... + Batched = ... + VmapMode = ... + FuncTorchGradWrapper = ... + FuncTorchBatched = ... + BatchedNestedTensor = ... + FuncTorchVmapMode = ... + FuncTorchDynamicLayerFrontMode = ... + Functionalize = ... + TESTING_ONLY_GenericWrapper = ... + TESTING_ONLY_GenericMode = ... + ADInplaceOrView = ... + Autograd = ... + CompositeImplicitAutograd = ... + CompositeImplicitAutogradNestedTensor = ... + CompositeExplicitAutograd = ... + CompositeExplicitAutogradNonFunctional = ... + FuncTorchBatchedDecomposition = ... + CPU = ... + CUDA = ... + HIP = ... + XLA = ... + MTIA = ... + MPS = ... + IPU = ... + XPU = ... + HPU = ... + VE = ... + Lazy = ... + Meta = ... + PrivateUse1 = ... + PrivateUse2 = ... + PrivateUse3 = ... + QuantizedCPU = ... + QuantizedCUDA = ... + QuantizedHIP = ... + QuantizedXLA = ... + QuantizedMTIA = ... + QuantizedMPS = ... + QuantizedIPU = ... + QuantizedXPU = ... + QuantizedHPU = ... + QuantizedVE = ... + QuantizedLazy = ... + QuantizedMeta = ... + QuantizedPrivateUse1 = ... + QuantizedPrivateUse2 = ... + QuantizedPrivateUse3 = ... + SparseCPU = ... + SparseCUDA = ... + SparseHIP = ... + SparseXLA = ... + SparseMTIA = ... + SparseMPS = ... + SparseIPU = ... + SparseXPU = ... + SparseHPU = ... + SparseVE = ... + SparseLazy = ... + SparseMeta = ... + SparsePrivateUse1 = ... + SparsePrivateUse2 = ... + SparsePrivateUse3 = ... + SparseCsrCPU = ... + SparseCsrCUDA = ... + SparseCsrHIP = ... + SparseCsrXLA = ... + SparseCsrMTIA = ... + SparseCsrMPS = ... + SparseCsrIPU = ... + SparseCsrXPU = ... + SparseCsrHPU = ... + SparseCsrVE = ... + SparseCsrLazy = ... + SparseCsrMeta = ... + SparseCsrPrivateUse1 = ... + SparseCsrPrivateUse2 = ... + SparseCsrPrivateUse3 = ... + NestedTensorCPU = ... + NestedTensorCUDA = ... + NestedTensorHIP = ... + NestedTensorXLA = ... + NestedTensorMTIA = ... + NestedTensorMPS = ... + NestedTensorIPU = ... + NestedTensorXPU = ... + NestedTensorHPU = ... + NestedTensorVE = ... + NestedTensorLazy = ... + NestedTensorMeta = ... + NestedTensorPrivateUse1 = ... + NestedTensorPrivateUse2 = ... + NestedTensorPrivateUse3 = ... + AutogradCPU = ... + AutogradCUDA = ... + AutogradHIP = ... + AutogradXLA = ... + AutogradMTIA = ... + AutogradMPS = ... + AutogradIPU = ... + AutogradXPU = ... + AutogradHPU = ... + AutogradVE = ... + AutogradLazy = ... + AutogradMeta = ... + AutogradPrivateUse1 = ... + AutogradPrivateUse2 = ... + AutogradPrivateUse3 = ... + +class DispatchKeySet: + def __init__(self, key: DispatchKey) -> None: ... + def __or__(self, other: DispatchKeySet) -> DispatchKeySet: ... + def __sub__(self, other: DispatchKeySet) -> DispatchKeySet: ... + def __and__(self, other: DispatchKeySet) -> DispatchKeySet: ... + def raw_repr(self) -> _int: ... + @staticmethod + def from_raw_repr(raw: _int) -> DispatchKeySet: ... + def highestPriorityTypeId(self) -> DispatchKey: ... + def has(self, k: _dispatchkey) -> _bool: ... + def add(self, k: _dispatchkey) -> DispatchKeySet: ... + def remove(self, k: _dispatchkey) -> DispatchKeySet: ... + +_dispatch_autogradother_backends: DispatchKeySet +_additional_keys_to_prop_for_wrapper_tensors: DispatchKeySet + +def _dispatch_has_backend_fallback(dispatch: _dispatchkey) -> _bool: ... +def _dispatch_keyset_full_after(t: _dispatchkey) -> DispatchKeySet: ... +def _dispatch_keyset_full() -> DispatchKeySet: ... +def _dispatch_keyset_to_string(keyset: DispatchKeySet) -> str: ... +def _dispatch_get_backend_keyset_from_autograd( + dispatch: _dispatchkey, +) -> DispatchKeySet: ... +def _dispatch_keys(tensor: Tensor) -> DispatchKeySet: ... +def _dispatch_tls_local_exclude_set() -> DispatchKeySet: ... +def _dispatch_tls_local_include_set() -> DispatchKeySet: ... +def _dynamo_save_local_dispatch_key_set() -> None: ... +def _dynamo_restore_local_dispatch_key_set() -> None: ... +def _dispatch_is_included_in_alias( + dispatch_a: _dispatchkey, + dispatch_b: _dispatchkey, +) -> _bool: ... +def _propagate_xla_data(a: Tensor, b: Tensor) -> None: ... +def _replace_(a: Tensor, b: Tensor) -> None: ... +def _commit_update(a: Tensor) -> None: ... + +class _ExcludeDispatchKeyGuard: + def __init__(self, keyset: DispatchKeySet) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _IncludeDispatchKeyGuard: + def __init__(self, k: DispatchKey) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _ForceDispatchKeyGuard: + def __init__(self, include: DispatchKeySet, exclude: DispatchKeySet) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _PreserveDispatchKeyGuard: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _AutoDispatchBelowAutograd: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _AutoDispatchBelowADInplaceOrView: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +def _dispatch_print_registrations_for_dispatch_key(dispatch_key: str = "") -> None: ... +def _dispatch_get_registrations_for_dispatch_key( + dispatch_key: str = "", +) -> list[str]: ... +def _are_functorch_transforms_active() -> _bool: ... + +# Define in torch/csrc/autograd/init.cpp +def _set_python_dispatcher(dispatcher: object) -> None: ... +def _get_nested_int(id: _int, coeff: _int) -> SymInt: ... +def _get_constant_bool_symnode(val: _bool) -> Any: ... + +class _TorchDispatchModeKey(Enum): + FAKE = ... + PROXY = ... + FUNCTIONAL = ... + +class _SetExcludeDispatchKeyGuard: + def __init__(self, k: DispatchKey, enabled: _bool) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +def _get_dtensor_allow_implicit_replication() -> _bool: ... +def _set_dtensor_allow_implicit_replication(value: _bool) -> None: ... + +# Defined in torch/csrc/utils/schema_info.h +class _SchemaArgType(Enum): + input = ... + output = ... + +class _SchemaArgument: + type: _SchemaArgType + idx: _int + def __init__(self, type: _SchemaArgType, idx: _int) -> None: ... + +class _SchemaInfo: + def __init__(self, schema: FunctionSchema) -> None: ... + @overload + def is_mutable(self) -> _bool: ... + @overload + def is_mutable(self, name: str) -> _bool: ... + @overload + def is_mutable(self, argument: _SchemaArgument) -> _bool: ... + def has_argument(self, name: str) -> _bool: ... + def may_alias(self, lhs: _SchemaArgument, rhs: _SchemaArgument) -> _bool: ... + def may_contain_alias( + self, lhs: _SchemaArgument, rhs: _SchemaArgument + ) -> _bool: ... + def add_argument_value(self, name: str, value: object) -> None: ... + def add_argument_values(self, values: dict[str, object]) -> None: ... + +def _overlaps(lhs: object, rhs: object) -> _bool: ... + +# Defined in torch/csrc/utils/init.cpp +class BenchmarkConfig: + num_calling_threads: _int + num_worker_threads: _int + num_warmup_iters: _int + num_iters: _int + profiler_output_path: str + +class BenchmarkExecutionStats: + latency_avg_ms: _float + num_iters: _int + +class ThroughputBenchmark: + def __init__(self, module: Any) -> None: ... + def add_input(self, *args: Any, **kwargs: Any) -> None: ... + def run_once(self, *args: Any, **kwargs: Any) -> Any: ... + def benchmark(self, config: BenchmarkConfig) -> BenchmarkExecutionStats: ... + +# Defined in torch/csrc/Storage.cpp +class StorageBase: ... + +# TODO: where +class DoubleTensor(Tensor): ... +class FloatTensor(Tensor): ... +class BFloat16Tensor(Tensor): ... +class LongTensor(Tensor): ... +class IntTensor(Tensor): ... +class ShortTensor(Tensor): ... +class HalfTensor(Tensor): ... +class CharTensor(Tensor): ... +class ByteTensor(Tensor): ... +class BoolTensor(Tensor): ... + +# Defined in torch/csrc/autograd/python_engine.cpp +class _ImperativeEngine: + def queue_callback(self, callback: Callable[[], None]) -> None: ... + def run_backward(self, *args: Any, **kwargs: Any) -> tuple[Tensor, ...]: ... + def is_checkpoint_valid(self) -> _bool: ... + +# Defined in torch/csrc/autograd/python_variable.cpp +class _TensorMeta(type): ... + +_Index: TypeAlias = SupportsIndex | _bool | _int | slice | EllipsisType | Tensor | None | _NestedSequence[_bool | _int | slice | EllipsisType | Tensor | None] # fmt: skip + +# Defined in torch/csrc/autograd/python_variable.cpp +class TensorBase(metaclass=_TensorMeta): + requires_grad: _bool + retains_grad: _bool + shape: Size + data: Tensor + device: _device + dtype: _dtype + grad_dtype: _dtype | None + layout: _layout + real: Tensor + imag: Tensor + T: Tensor + H: Tensor + mT: Tensor + mH: Tensor + ndim: _int + output_nr: _int + _version: _int + _base: Tensor | None + _cdata: _int + grad_fn: _Node | None + _grad_fn: Any + _grad: Tensor | None + grad: Tensor | None + _backward_hooks: dict[_int, Callable[[Tensor], Tensor | None]] | None + nbytes: _int + itemsize: _int + _has_symbolic_sizes_strides: _bool + + def _view_func_unsafe( + self, + new_base: Tensor, + symint_visitor_fn: Callable[[_int], _int] | None = None, + tensor_visitor_fn: Callable[[Tensor], Tensor] | None = None, + ): ... + def __abs__(self) -> Tensor: ... + def __add__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __and__(self, other: Tensor) -> Tensor: ... + @overload + def __and__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __and__(self, other: Tensor | _int) -> Tensor: ... + def __bool__(self) -> _bool: ... + def __complex__(self) -> _complex: ... + def __contains__(self, item: Any, /) -> _bool: ... + def __div__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __eq__(self, other: Tensor | Number | _complex) -> Tensor: ... # type: ignore[overload-overlap] + @overload + def __eq__(self, other: object) -> _bool: ... + def __float__(self) -> _float: ... + def __floordiv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __ge__(self, other: Tensor | Number | PySymType | _complex) -> Tensor: ... + def __getitem__(self, indices: _Index | tuple[_Index, ...], /) -> Tensor: ... + def __gt__(self, other: Tensor | Number | PySymType | _complex) -> Tensor: ... + def __iadd__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + @overload + def __iand__(self, other: Tensor) -> Tensor: ... + @overload + def __iand__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __iand__(self, other: Tensor | _int) -> Tensor: ... + def __idiv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __ifloordiv__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + @overload + def __ilshift__(self, other: Tensor) -> Tensor: ... + @overload + def __ilshift__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __ilshift__(self, other: Tensor | _int) -> Tensor: ... + def __imod__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + def __imul__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + def __index__(self) -> _int: ... + @overload + def __init__( + self, + *args: Any, + device: DeviceLikeType | None = None, + ) -> None: ... + @overload + def __init__(self, storage: Storage) -> None: ... + @overload + def __init__(self, other: Tensor) -> None: ... + @overload + def __init__( + self, + size: _size, + *, + device: DeviceLikeType | None = None, + ) -> None: ... + def __int__(self) -> _int: ... + def __invert__(self) -> Tensor: ... + @overload + def __ior__(self, other: Tensor) -> Tensor: ... + @overload + def __ior__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __ior__(self, other: Tensor | _int) -> Tensor: ... + @overload + def __irshift__(self, other: Tensor) -> Tensor: ... + @overload + def __irshift__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __irshift__(self, other: Tensor | _int) -> Tensor: ... + def __isub__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + @overload + def __ixor__(self, other: Tensor) -> Tensor: ... + @overload + def __ixor__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __ixor__(self, other: Tensor | _int) -> Tensor: ... + def __le__(self, other: Tensor | Number | PySymType | _complex) -> Tensor: ... + def __long__(self) -> _int: ... + @overload + def __lshift__(self, other: Tensor) -> Tensor: ... + @overload + def __lshift__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __lshift__(self, other: Tensor | _int) -> Tensor: ... + def __lt__(self, other: Tensor | Number | PySymType | _complex) -> Tensor: ... + def __matmul__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __mod__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __mul__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __ne__(self, other: Tensor | Number | _complex) -> Tensor: ... # type: ignore[overload-overlap] + @overload + def __ne__(self, other: object) -> _bool: ... + def __neg__(self) -> Tensor: ... + def __new__(cls, *args, **kwargs) -> Self: ... + def __nonzero__(self) -> _bool: ... + @overload + def __or__(self, other: Tensor) -> Tensor: ... + @overload + def __or__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __or__(self, other: Tensor | _int) -> Tensor: ... + def __pow__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __radd__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rand__(self, other: Tensor | _int) -> Tensor: ... + def __rfloordiv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rmul__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __ror__(self, other: Tensor | _int) -> Tensor: ... + def __rpow__(self, other: Tensor | Number | _complex) -> Tensor: ... # type: ignore[has-type] + @overload + def __rshift__(self, other: Tensor) -> Tensor: ... + @overload + def __rshift__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __rshift__(self, other: Tensor | _int) -> Tensor: ... + def __rsub__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rtruediv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rxor__(self, other: Tensor | _int) -> Tensor: ... + def __setitem__( + self, + indices: _Index | tuple[_Index, ...], + value: Tensor | Number, + /, + ) -> None: ... + def __sub__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __truediv__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __xor__(self, other: Tensor) -> Tensor: ... + @overload + def __xor__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __xor__(self, other: Tensor | _int) -> Tensor: ... + def _addmm_activation( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + use_gelu: _bool = False, + ) -> Tensor: ... + def _autocast_to_full_precision( + self, + cuda_enabled: _bool, + cpu_enabled: _bool, + ) -> Tensor: ... + def _autocast_to_reduced_precision( + self, + cuda_enabled: _bool, + cpu_enabled: _bool, + cuda_dtype: _dtype, + cpu_dtype: _dtype, + ) -> Tensor: ... + def _coalesced_(self, coalesced: _bool) -> Tensor: ... + def _conj(self) -> Tensor: ... + def _conj_physical(self) -> Tensor: ... + def _dimI(self) -> _int: ... + def _dimV(self) -> _int: ... + @staticmethod + def _dtensor__new__( + cls: type[S], + local_tensor: Tensor, + spec: torch.distributed.tensor._dtensor_spec.DTensorSpec, + requires_grad: _bool, + ) -> S: ... + def _indices(self) -> Tensor: ... + def _is_all_true(self) -> Tensor: ... + def _is_any_true(self) -> Tensor: ... + def _is_view(self) -> _bool: ... + def _is_zerotensor(self) -> _bool: ... + def _lazy_clone(self) -> Tensor: ... + @staticmethod + def _make_subclass( + cls: type[S], + data: Tensor, + require_grad: _bool = False, + dispatch_strides: _bool = False, + dispatch_device: _bool = False, + device_for_backend_keys: _device | None = None, + ) -> S: ... + @staticmethod + def _make_wrapper_subclass( + cls: type[S], + size: Sequence[_int | SymInt], + strides: Sequence[_int | SymInt] | None = None, + storage_offset: _int | SymInt | None = None, + memory_format: torch.memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout = strided, + device: _device | None = None, + pin_memory: _bool = False, + requires_grad: _bool = False, + dispatch_sizes_strides_policy: str | None = None, + dispatch_device: _bool = False, + dispatch_layout: _bool = False, + _extra_dispatch_keys: torch.DispatchKeySet | None = None, + storage_size: _int | SymInt | None = None, + ) -> S: ... + def _neg_view(self) -> Tensor: ... + def _nested_tensor_size(self) -> Tensor: ... + def _nested_tensor_storage_offsets(self) -> Tensor: ... + def _nested_tensor_strides(self) -> Tensor: ... + def _nnz(self) -> _int: ... + def _philox_normal_( + self, + key: Tensor, + mean: _float = 0, + std: _float = 1, + ) -> Tensor: ... + def _philox_uniform_( + self, + key: Tensor, + low: _float = 0, + high: _float = 1, + ) -> Tensor: ... + def _sparse_mask_projection( + self, + mask: Tensor, + accumulate_matches: _bool = False, + ) -> Tensor: ... + def _to_dense( + self, + dtype: _dtype | None = None, + masked_grad: _bool | None = None, + ) -> Tensor: ... + @overload + def _to_sparse( + self, + *, + layout: _layout | None = None, + blocksize: _int | _size | None = None, + dense_dim: _int | None = None, + ) -> Tensor: ... + @overload + def _to_sparse(self, sparse_dim: _int) -> Tensor: ... + def _to_sparse_bsc( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: ... + def _to_sparse_bsr( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: ... + def _to_sparse_csc(self, dense_dim: _int | None = None) -> Tensor: ... + def _to_sparse_csr(self, dense_dim: _int | None = None) -> Tensor: ... + def _values(self) -> Tensor: ... + def abs(self) -> Tensor: + r""" + abs() -> Tensor + + See :func:`torch.abs` + """ + + def abs_(self) -> Tensor: + r""" + abs_() -> Tensor + + In-place version of :meth:`~Tensor.abs` + """ + + def absolute(self) -> Tensor: + r""" + absolute() -> Tensor + + Alias for :func:`abs` + """ + + def absolute_(self) -> Tensor: + r""" + absolute_() -> Tensor + + In-place version of :meth:`~Tensor.absolute` + Alias for :func:`abs_` + """ + + def acos(self) -> Tensor: + r""" + acos() -> Tensor + + See :func:`torch.acos` + """ + + def acos_(self) -> Tensor: + r""" + acos_() -> Tensor + + In-place version of :meth:`~Tensor.acos` + """ + + def acosh(self) -> Tensor: + r""" + acosh() -> Tensor + + See :func:`torch.acosh` + """ + + def acosh_(self) -> Tensor: + r""" + acosh_() -> Tensor + + In-place version of :meth:`~Tensor.acosh` + """ + + def add( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, + ) -> Tensor: + r""" + add(other, *, alpha=1) -> Tensor + + Add a scalar or tensor to :attr:`self` tensor. If both :attr:`alpha` + and :attr:`other` are specified, each element of :attr:`other` is scaled by + :attr:`alpha` before being used. + + When :attr:`other` is a tensor, the shape of :attr:`other` must be + :ref:`broadcastable ` with the shape of the underlying + tensor + + See :func:`torch.add` + """ + + def add_( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + ) -> Tensor: + r""" + add_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.add` + """ + + def addbmm( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addbmm(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addbmm` + """ + + def addbmm_( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addbmm_(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addbmm` + """ + + def addcdiv( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addcdiv(tensor1, tensor2, *, value=1) -> Tensor + + See :func:`torch.addcdiv` + """ + + def addcdiv_( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addcdiv_(tensor1, tensor2, *, value=1) -> Tensor + + In-place version of :meth:`~Tensor.addcdiv` + """ + + def addcmul( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addcmul(tensor1, tensor2, *, value=1) -> Tensor + + See :func:`torch.addcmul` + """ + + def addcmul_( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addcmul_(tensor1, tensor2, *, value=1) -> Tensor + + In-place version of :meth:`~Tensor.addcmul` + """ + + def addmm( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addmm(mat1, mat2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addmm` + """ + + def addmm_( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addmm_(mat1, mat2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addmm` + """ + + def addmv( + self, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addmv(mat, vec, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addmv` + """ + + def addmv_( + self, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addmv_(mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addmv` + """ + + def addr( + self, + vec1: Tensor, + vec2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addr(vec1, vec2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addr` + """ + + def addr_( + self, + vec1: Tensor, + vec2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addr_(vec1, vec2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addr` + """ + + def adjoint(self) -> Tensor: + r""" + adjoint() -> Tensor + + Alias for :func:`adjoint` + """ + + @overload + def all(self) -> Tensor: + r""" + all(dim=None, keepdim=False) -> Tensor + + See :func:`torch.all` + """ + + @overload + def all(self, dim: _size | None = None, keepdim: _bool = False) -> Tensor: + r""" + all(dim=None, keepdim=False) -> Tensor + + See :func:`torch.all` + """ + + @overload + def all(self, dim: _int, keepdim: _bool = False) -> Tensor: + r""" + all(dim=None, keepdim=False) -> Tensor + + See :func:`torch.all` + """ + + def allclose( + self, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, + ) -> _bool: + r""" + allclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + See :func:`torch.allclose` + """ + + def amax(self, dim: _int | _size = (), keepdim: _bool = False) -> Tensor: + r""" + amax(dim=None, keepdim=False) -> Tensor + + See :func:`torch.amax` + """ + + def amin(self, dim: _int | _size = (), keepdim: _bool = False) -> Tensor: + r""" + amin(dim=None, keepdim=False) -> Tensor + + See :func:`torch.amin` + """ + + def aminmax( + self, + *, + dim: _int | None = None, + keepdim: _bool = False, + ) -> torch.return_types.aminmax: + r""" + aminmax(*, dim=None, keepdim=False) -> (Tensor min, Tensor max) + + See :func:`torch.aminmax` + """ + + def angle(self) -> Tensor: + r""" + angle() -> Tensor + + See :func:`torch.angle` + """ + + @overload + def any(self) -> Tensor: + r""" + any(dim=None, keepdim=False) -> Tensor + + See :func:`torch.any` + """ + + @overload + def any(self, dim: _size | None = None, keepdim: _bool = False) -> Tensor: + r""" + any(dim=None, keepdim=False) -> Tensor + + See :func:`torch.any` + """ + + @overload + def any(self, dim: _int, keepdim: _bool = False) -> Tensor: + r""" + any(dim=None, keepdim=False) -> Tensor + + See :func:`torch.any` + """ + + def apply_(self, callable: Callable) -> Tensor: + r""" + apply_(callable) -> Tensor + + Applies the function :attr:`callable` to each element in the tensor, replacing + each element with the value returned by :attr:`callable`. + + .. note:: + + This function only works with CPU tensors and should not be used in code + sections that require high performance. + """ + + def arccos(self) -> Tensor: + r""" + arccos() -> Tensor + + See :func:`torch.arccos` + """ + + def arccos_(self) -> Tensor: + r""" + arccos_() -> Tensor + + In-place version of :meth:`~Tensor.arccos` + """ + + def arccosh(self) -> Tensor: + r""" + acosh() -> Tensor + + See :func:`torch.arccosh` + """ + + def arccosh_(self) -> Tensor: + r""" + acosh_() -> Tensor + + In-place version of :meth:`~Tensor.arccosh` + """ + + def arcsin(self) -> Tensor: + r""" + arcsin() -> Tensor + + See :func:`torch.arcsin` + """ + + def arcsin_(self) -> Tensor: + r""" + arcsin_() -> Tensor + + In-place version of :meth:`~Tensor.arcsin` + """ + + def arcsinh(self) -> Tensor: + r""" + arcsinh() -> Tensor + + See :func:`torch.arcsinh` + """ + + def arcsinh_(self) -> Tensor: + r""" + arcsinh_() -> Tensor + + In-place version of :meth:`~Tensor.arcsinh` + """ + + def arctan(self) -> Tensor: + r""" + arctan() -> Tensor + + See :func:`torch.arctan` + """ + + def arctan2(self, other: Tensor) -> Tensor: + r""" + arctan2(other) -> Tensor + + See :func:`torch.arctan2` + """ + + def arctan2_(self, other: Tensor) -> Tensor: + r""" + atan2_(other) -> Tensor + + In-place version of :meth:`~Tensor.arctan2` + """ + + def arctan_(self) -> Tensor: + r""" + arctan_() -> Tensor + + In-place version of :meth:`~Tensor.arctan` + """ + + def arctanh(self) -> Tensor: + r""" + arctanh() -> Tensor + + See :func:`torch.arctanh` + """ + + def arctanh_(self) -> Tensor: + r""" + arctanh_(other) -> Tensor + + In-place version of :meth:`~Tensor.arctanh` + """ + + def argmax(self, dim: _int | None = None, keepdim: _bool = False) -> Tensor: + r""" + argmax(dim=None, keepdim=False) -> LongTensor + + See :func:`torch.argmax` + """ + + def argmin(self, dim: _int | None = None, keepdim: _bool = False) -> Tensor: + r""" + argmin(dim=None, keepdim=False) -> LongTensor + + See :func:`torch.argmin` + """ + + @overload + def argsort( + self, + *, + stable: _bool, + dim: _int = -1, + descending: _bool = False, + ) -> Tensor: + r""" + argsort(dim=-1, descending=False) -> LongTensor + + See :func:`torch.argsort` + """ + + @overload + def argsort(self, dim: _int = -1, descending: _bool = False) -> Tensor: + r""" + argsort(dim=-1, descending=False) -> LongTensor + + See :func:`torch.argsort` + """ + + def argwhere(self) -> Tensor: + r""" + argwhere() -> Tensor + + See :func:`torch.argwhere` + """ + + def as_strided( + self, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + ) -> Tensor: + r""" + as_strided(size, stride, storage_offset=None) -> Tensor + + See :func:`torch.as_strided` + """ + + def as_strided_( + self, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + ) -> Tensor: + r""" + as_strided_(size, stride, storage_offset=None) -> Tensor + + In-place version of :meth:`~Tensor.as_strided` + """ + + def as_strided_scatter( + self, + src: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + ) -> Tensor: + r""" + as_strided_scatter(src, size, stride, storage_offset=None) -> Tensor + + See :func:`torch.as_strided_scatter` + """ + + def as_subclass(self, cls: type[S]) -> S: + r""" + as_subclass(cls) -> Tensor + + Makes a ``cls`` instance with the same data pointer as ``self``. Changes + in the output mirror changes in ``self``, and the output stays attached + to the autograd graph. ``cls`` must be a subclass of ``Tensor``. + """ + + def asin(self) -> Tensor: + r""" + asin() -> Tensor + + See :func:`torch.asin` + """ + + def asin_(self) -> Tensor: + r""" + asin_() -> Tensor + + In-place version of :meth:`~Tensor.asin` + """ + + def asinh(self) -> Tensor: + r""" + asinh() -> Tensor + + See :func:`torch.asinh` + """ + + def asinh_(self) -> Tensor: + r""" + asinh_() -> Tensor + + In-place version of :meth:`~Tensor.asinh` + """ + + def atan(self) -> Tensor: + r""" + atan() -> Tensor + + See :func:`torch.atan` + """ + + def atan2(self, other: Tensor) -> Tensor: + r""" + atan2(other) -> Tensor + + See :func:`torch.atan2` + """ + + def atan2_(self, other: Tensor) -> Tensor: + r""" + atan2_(other) -> Tensor + + In-place version of :meth:`~Tensor.atan2` + """ + + def atan_(self) -> Tensor: + r""" + atan_() -> Tensor + + In-place version of :meth:`~Tensor.atan` + """ + + def atanh(self) -> Tensor: + r""" + atanh() -> Tensor + + See :func:`torch.atanh` + """ + + def atanh_(self) -> Tensor: + r""" + atanh_(other) -> Tensor + + In-place version of :meth:`~Tensor.atanh` + """ + + def baddbmm( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + baddbmm(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.baddbmm` + """ + + def baddbmm_( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + baddbmm_(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.baddbmm` + """ + + @overload + def bernoulli(self, *, generator: Generator | None = None) -> Tensor: + r""" + bernoulli(*, generator=None) -> Tensor + + Returns a result tensor where each :math:`\texttt{result[i]}` is independently + sampled from :math:`\text{Bernoulli}(\texttt{self[i]})`. :attr:`self` must have + floating point ``dtype``, and the result will have the same ``dtype``. + + See :func:`torch.bernoulli` + """ + + @overload + def bernoulli( + self, + p: _float, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + bernoulli(*, generator=None) -> Tensor + + Returns a result tensor where each :math:`\texttt{result[i]}` is independently + sampled from :math:`\text{Bernoulli}(\texttt{self[i]})`. :attr:`self` must have + floating point ``dtype``, and the result will have the same ``dtype``. + + See :func:`torch.bernoulli` + """ + + @overload + def bernoulli_( + self, + p: Tensor, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + bernoulli_(p=0.5, *, generator=None) -> Tensor + + Fills each location of :attr:`self` with an independent sample from + :math:`\text{Bernoulli}(\texttt{p})`. :attr:`self` can have integral + ``dtype``. + + :attr:`p` should either be a scalar or tensor containing probabilities to be + used for drawing the binary random number. + + If it is a tensor, the :math:`\text{i}^{th}` element of :attr:`self` tensor + will be set to a value sampled from + :math:`\text{Bernoulli}(\texttt{p\_tensor[i]})`. In this case `p` must have + floating point ``dtype``. + + See also :meth:`~Tensor.bernoulli` and :func:`torch.bernoulli` + """ + + @overload + def bernoulli_( + self, + p: _float = 0.5, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + bernoulli_(p=0.5, *, generator=None) -> Tensor + + Fills each location of :attr:`self` with an independent sample from + :math:`\text{Bernoulli}(\texttt{p})`. :attr:`self` can have integral + ``dtype``. + + :attr:`p` should either be a scalar or tensor containing probabilities to be + used for drawing the binary random number. + + If it is a tensor, the :math:`\text{i}^{th}` element of :attr:`self` tensor + will be set to a value sampled from + :math:`\text{Bernoulli}(\texttt{p\_tensor[i]})`. In this case `p` must have + floating point ``dtype``. + + See also :meth:`~Tensor.bernoulli` and :func:`torch.bernoulli` + """ + + def bfloat16(self) -> Tensor: + r""" + bfloat16(memory_format=torch.preserve_format) -> Tensor + ``self.bfloat16()`` is equivalent to ``self.to(torch.bfloat16)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def bincount( + self, + weights: Tensor | None = None, + minlength: _int | SymInt = 0, + ) -> Tensor: + r""" + bincount(weights=None, minlength=0) -> Tensor + + See :func:`torch.bincount` + """ + + @overload + def bitwise_and(self, other: Tensor) -> Tensor: + r""" + bitwise_and() -> Tensor + + See :func:`torch.bitwise_and` + """ + + @overload + def bitwise_and(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_and() -> Tensor + + See :func:`torch.bitwise_and` + """ + + @overload + def bitwise_and_(self, other: Tensor) -> Tensor: + r""" + bitwise_and_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_and` + """ + + @overload + def bitwise_and_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_and_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_and` + """ + + @overload + def bitwise_left_shift(self, other: Tensor) -> Tensor: + r""" + bitwise_left_shift(other) -> Tensor + + See :func:`torch.bitwise_left_shift` + """ + + @overload + def bitwise_left_shift( + self, + other: Number | _complex | PySymType, + ) -> Tensor: + r""" + bitwise_left_shift(other) -> Tensor + + See :func:`torch.bitwise_left_shift` + """ + + @overload + def bitwise_left_shift_(self, other: Tensor) -> Tensor: + r""" + bitwise_left_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_left_shift` + """ + + @overload + def bitwise_left_shift_( + self, + other: Number | _complex | PySymType, + ) -> Tensor: + r""" + bitwise_left_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_left_shift` + """ + + def bitwise_not(self) -> Tensor: + r""" + bitwise_not() -> Tensor + + See :func:`torch.bitwise_not` + """ + + def bitwise_not_(self) -> Tensor: + r""" + bitwise_not_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_not` + """ + + @overload + def bitwise_or(self, other: Tensor) -> Tensor: + r""" + bitwise_or() -> Tensor + + See :func:`torch.bitwise_or` + """ + + @overload + def bitwise_or(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_or() -> Tensor + + See :func:`torch.bitwise_or` + """ + + @overload + def bitwise_or_(self, other: Tensor) -> Tensor: + r""" + bitwise_or_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_or` + """ + + @overload + def bitwise_or_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_or_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_or` + """ + + @overload + def bitwise_right_shift(self, other: Tensor) -> Tensor: + r""" + bitwise_right_shift(other) -> Tensor + + See :func:`torch.bitwise_right_shift` + """ + + @overload + def bitwise_right_shift( + self, + other: Number | _complex | PySymType, + ) -> Tensor: + r""" + bitwise_right_shift(other) -> Tensor + + See :func:`torch.bitwise_right_shift` + """ + + @overload + def bitwise_right_shift_(self, other: Tensor) -> Tensor: + r""" + bitwise_right_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_right_shift` + """ + + @overload + def bitwise_right_shift_( + self, + other: Number | _complex | PySymType, + ) -> Tensor: + r""" + bitwise_right_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_right_shift` + """ + + @overload + def bitwise_xor(self, other: Tensor) -> Tensor: + r""" + bitwise_xor() -> Tensor + + See :func:`torch.bitwise_xor` + """ + + @overload + def bitwise_xor(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_xor() -> Tensor + + See :func:`torch.bitwise_xor` + """ + + @overload + def bitwise_xor_(self, other: Tensor) -> Tensor: + r""" + bitwise_xor_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_xor` + """ + + @overload + def bitwise_xor_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_xor_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_xor` + """ + + def bmm(self, mat2: Tensor) -> Tensor: + r""" + bmm(batch2) -> Tensor + + See :func:`torch.bmm` + """ + + def bool(self) -> Tensor: + r""" + bool(memory_format=torch.preserve_format) -> Tensor + + ``self.bool()`` is equivalent to ``self.to(torch.bool)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def broadcast_to(self, size: Sequence[_int | SymInt]) -> Tensor: + r""" + broadcast_to(shape) -> Tensor + + See :func:`torch.broadcast_to`. + """ + + @overload + def broadcast_to(self, *size: _int | SymInt) -> Tensor: + r""" + broadcast_to(shape) -> Tensor + + See :func:`torch.broadcast_to`. + """ + + def byte(self) -> Tensor: + r""" + byte(memory_format=torch.preserve_format) -> Tensor + + ``self.byte()`` is equivalent to ``self.to(torch.uint8)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cauchy_( + self, + median: _float = 0, + sigma: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + cauchy_(median=0, sigma=1, *, generator=None) -> Tensor + + Fills the tensor with numbers drawn from the Cauchy distribution: + + .. math:: + + f(x) = \dfrac{1}{\pi} \dfrac{\sigma}{(x - \text{median})^2 + \sigma^2} + + .. note:: + Sigma (:math:`\sigma`) is used to denote the scale parameter in Cauchy distribution. + """ + + def ccol_indices(self) -> Tensor: ... + def ceil(self) -> Tensor: + r""" + ceil() -> Tensor + + See :func:`torch.ceil` + """ + + def ceil_(self) -> Tensor: + r""" + ceil_() -> Tensor + + In-place version of :meth:`~Tensor.ceil` + """ + + def chalf(self, *, memory_format: memory_format | None = None) -> Tensor: + r""" + chalf(memory_format=torch.preserve_format) -> Tensor + + ``self.chalf()`` is equivalent to ``self.to(torch.complex32)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def char(self) -> Tensor: + r""" + char(memory_format=torch.preserve_format) -> Tensor + + ``self.char()`` is equivalent to ``self.to(torch.int8)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cholesky_inverse(self, upper: _bool = False) -> Tensor: + r""" + cholesky_inverse(upper=False) -> Tensor + + See :func:`torch.cholesky_inverse` + """ + + def cholesky_solve(self, input2: Tensor, upper: _bool = False) -> Tensor: + r""" + cholesky_solve(input2, upper=False) -> Tensor + + See :func:`torch.cholesky_solve` + """ + + def chunk(self, chunks: _int, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + chunk(chunks, dim=0) -> List of Tensors + + See :func:`torch.chunk` + """ + + @overload + def clamp( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clamp(min=None, max=None) -> Tensor + + See :func:`torch.clamp` + """ + + @overload + def clamp( + self, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + ) -> Tensor: + r""" + clamp(min=None, max=None) -> Tensor + + See :func:`torch.clamp` + """ + + @overload + def clamp_( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clamp_(min=None, max=None) -> Tensor + + In-place version of :meth:`~Tensor.clamp` + """ + + @overload + def clamp_( + self, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + ) -> Tensor: + r""" + clamp_(min=None, max=None) -> Tensor + + In-place version of :meth:`~Tensor.clamp` + """ + + @overload + def clamp_max(self, max: Tensor) -> Tensor: ... + @overload + def clamp_max(self, max: Number | _complex | PySymType) -> Tensor: ... + @overload + def clamp_max_(self, max: Tensor) -> Tensor: ... + @overload + def clamp_max_(self, max: Number | _complex | PySymType) -> Tensor: ... + @overload + def clamp_min(self, min: Tensor) -> Tensor: ... + @overload + def clamp_min(self, min: Number | _complex | PySymType) -> Tensor: ... + @overload + def clamp_min_(self, min: Tensor) -> Tensor: ... + @overload + def clamp_min_(self, min: Number | _complex | PySymType) -> Tensor: ... + @overload + def clip( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clip(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp`. + """ + + @overload + def clip( + self, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + ) -> Tensor: + r""" + clip(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp`. + """ + + @overload + def clip_( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clip_(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp_`. + """ + + @overload + def clip_( + self, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + ) -> Tensor: + r""" + clip_(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp_`. + """ + + def clone(self, *, memory_format: memory_format | None = None) -> Tensor: + r""" + clone(*, memory_format=torch.preserve_format) -> Tensor + + See :func:`torch.clone` + """ + + def coalesce(self) -> Tensor: + r""" + coalesce() -> Tensor + + Returns a coalesced copy of :attr:`self` if :attr:`self` is an + :ref:`uncoalesced tensor `. + + Returns :attr:`self` if :attr:`self` is a coalesced tensor. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + """ + + def col_indices(self) -> Tensor: + r""" + col_indices() -> IntTensor + + Returns the tensor containing the column indices of the :attr:`self` + tensor when :attr:`self` is a sparse CSR tensor of layout ``sparse_csr``. + The ``col_indices`` tensor is strictly of shape (:attr:`self`.nnz()) + and of type ``int32`` or ``int64``. When using MKL routines such as sparse + matrix multiplication, it is necessary to use ``int32`` indexing in order + to avoid downcasting and potentially losing information. + + Example:: + + >>> csr = torch.eye(5,5).to_sparse_csr() + >>> csr.col_indices() + tensor([0, 1, 2, 3, 4], dtype=torch.int32) + """ + + def conj(self) -> Tensor: + r""" + conj() -> Tensor + + See :func:`torch.conj` + """ + + def conj_physical(self) -> Tensor: + r""" + conj_physical() -> Tensor + + See :func:`torch.conj_physical` + """ + + def conj_physical_(self) -> Tensor: + r""" + conj_physical_() -> Tensor + + In-place version of :meth:`~Tensor.conj_physical` + """ + + def contiguous( + self, + memory_format: torch.memory_format = torch.contiguous_format, + ) -> Tensor: + r""" + contiguous(memory_format=torch.contiguous_format) -> Tensor + + Returns a contiguous in memory tensor containing the same data as :attr:`self` tensor. If + :attr:`self` tensor is already in the specified memory format, this function returns the + :attr:`self` tensor. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + """ + + def copy_(self, other: Tensor, non_blocking: _bool = False) -> Tensor: + r""" + copy_(src, non_blocking=False) -> Tensor + + Copies the elements from :attr:`src` into :attr:`self` tensor and returns + :attr:`self`. + + The :attr:`src` tensor must be :ref:`broadcastable ` + with the :attr:`self` tensor. It may be of a different data type or reside on a + different device. + + Args: + src (Tensor): the source tensor to copy from + non_blocking (bool, optional): if ``True`` and this copy is between CPU and GPU, + the copy may occur asynchronously with respect to the host. For other + cases, this argument has no effect. Default: ``False`` + + .. note:: + + When :attr:`non_blocking` is ``True`` and the copy is issued on a + non-default CUDA stream, the caller is responsible for proper + cross-stream synchronization. See :ref:`cuda-stream-semantics` for + the required pattern. + """ + + @overload + def copysign(self, other: Tensor) -> Tensor: + r""" + copysign(other) -> Tensor + + See :func:`torch.copysign` + """ + + @overload + def copysign(self, other: Number | _complex | PySymType) -> Tensor: + r""" + copysign(other) -> Tensor + + See :func:`torch.copysign` + """ + + @overload + def copysign_(self, other: Tensor) -> Tensor: + r""" + copysign_(other) -> Tensor + + In-place version of :meth:`~Tensor.copysign` + """ + + @overload + def copysign_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + copysign_(other) -> Tensor + + In-place version of :meth:`~Tensor.copysign` + """ + + def corrcoef(self) -> Tensor: + r""" + corrcoef() -> Tensor + + See :func:`torch.corrcoef` + """ + + def cos(self) -> Tensor: + r""" + cos() -> Tensor + + See :func:`torch.cos` + """ + + def cos_(self) -> Tensor: + r""" + cos_() -> Tensor + + In-place version of :meth:`~Tensor.cos` + """ + + def cosh(self) -> Tensor: + r""" + cosh() -> Tensor + + See :func:`torch.cosh` + """ + + def cosh_(self) -> Tensor: + r""" + cosh_() -> Tensor + + In-place version of :meth:`~Tensor.cosh` + """ + + @overload + def count_nonzero(self, dim: _int | None = None) -> Tensor: + r""" + count_nonzero(dim=None) -> Tensor + + See :func:`torch.count_nonzero` + """ + + @overload + def count_nonzero(self, dim: _size) -> Tensor: + r""" + count_nonzero(dim=None) -> Tensor + + See :func:`torch.count_nonzero` + """ + + @overload + def count_nonzero(self, *dim: _int) -> Tensor: + r""" + count_nonzero(dim=None) -> Tensor + + See :func:`torch.count_nonzero` + """ + + def cov( + self, + *, + correction: _int = 1, + fweights: Tensor | None = None, + aweights: Tensor | None = None, + ) -> Tensor: + r""" + cov(*, correction=1, fweights=None, aweights=None) -> Tensor + + See :func:`torch.cov` + """ + + def cpu( + self, + memory_format: torch.memory_format = torch.preserve_format, + ) -> Tensor: + r""" + cpu(memory_format=torch.preserve_format) -> Tensor + + Returns a copy of this object in CPU memory. + + If this object is already in CPU memory, + then no copy is performed and the original object is returned. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cross(self, other: Tensor, dim: _int | None = None) -> Tensor: + r""" + cross(other, dim=None) -> Tensor + + See :func:`torch.cross` + """ + + def crow_indices(self) -> Tensor: + r""" + crow_indices() -> IntTensor + + Returns the tensor containing the compressed row indices of the :attr:`self` + tensor when :attr:`self` is a sparse CSR tensor of layout ``sparse_csr``. + The ``crow_indices`` tensor is strictly of shape (:attr:`self`.size(0) + 1) + and of type ``int32`` or ``int64``. When using MKL routines such as sparse + matrix multiplication, it is necessary to use ``int32`` indexing in order + to avoid downcasting and potentially losing information. + + Example:: + + >>> csr = torch.eye(5,5).to_sparse_csr() + >>> csr.crow_indices() + tensor([0, 1, 2, 3, 4, 5], dtype=torch.int32) + """ + + def cuda( + self, + device: _device | _int | str | None = None, + non_blocking: _bool = False, + memory_format: torch.memory_format = torch.preserve_format, + ) -> Tensor: + r""" + cuda(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of this object in CUDA memory. + + If this object is already in CUDA memory and on the correct device, + then no copy is performed and the original object is returned. + + Args: + device (:class:`torch.device`, optional): The destination GPU device. + Defaults to the current CUDA device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cummax(self, dim: _int) -> torch.return_types.cummax: + r""" + cummax(dim) -> (Tensor, Tensor) + + See :func:`torch.cummax` + """ + + def cummin(self, dim: _int) -> torch.return_types.cummin: + r""" + cummin(dim) -> (Tensor, Tensor) + + See :func:`torch.cummin` + """ + + def cumprod(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumprod(dim, dtype=None) -> Tensor + + See :func:`torch.cumprod` + """ + + def cumprod_(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumprod_(dim, dtype=None) -> Tensor + + In-place version of :meth:`~Tensor.cumprod` + """ + + def cumsum(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumsum(dim, dtype=None) -> Tensor + + See :func:`torch.cumsum` + """ + + def cumsum_(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumsum_(dim, dtype=None) -> Tensor + + In-place version of :meth:`~Tensor.cumsum` + """ + + def data_ptr(self) -> _int: + r""" + data_ptr() -> int + + Returns the address of the first element of :attr:`self` tensor. + + .. note:: + + If the tensor is a copy-on-write tensor (e.g. created via + :meth:`_lazy_clone`), calling this method will materialize the + copy. Use :meth:`const_data_ptr` if you only need read-only access + to the data pointer. + """ + + def deg2rad(self) -> Tensor: + r""" + deg2rad() -> Tensor + + See :func:`torch.deg2rad` + """ + + def deg2rad_(self) -> Tensor: + r""" + deg2rad_() -> Tensor + + In-place version of :meth:`~Tensor.deg2rad` + """ + + def dense_dim(self) -> _int: + r""" + dense_dim() -> int + + Return the number of dense dimensions in a :ref:`sparse tensor ` :attr:`self`. + + .. note:: + Returns ``len(self.shape)`` if :attr:`self` is not a sparse tensor. + + See also :meth:`Tensor.sparse_dim` and :ref:`hybrid tensors `. + """ + + def dequantize(self) -> Tensor: + r""" + dequantize() -> Tensor + + Given a quantized Tensor, dequantize it and return the dequantized float Tensor. + """ + + def det(self) -> Tensor: + r""" + det() -> Tensor + + See :func:`torch.det` + """ + + def detach(self) -> Tensor: ... + def detach_(self) -> Tensor: ... + def diag(self, diagonal: _int = 0) -> Tensor: + r""" + diag(diagonal=0) -> Tensor + + See :func:`torch.diag` + """ + + def diag_embed( + self, + offset: _int = 0, + dim1: _int = -2, + dim2: _int = -1, + ) -> Tensor: + r""" + diag_embed(offset=0, dim1=-2, dim2=-1) -> Tensor + + See :func:`torch.diag_embed` + """ + + def diagflat(self, offset: _int = 0) -> Tensor: + r""" + diagflat(offset=0) -> Tensor + + See :func:`torch.diagflat` + """ + + def diagonal( + self, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, + ) -> Tensor: + r""" + diagonal(offset=0, dim1=0, dim2=1) -> Tensor + + See :func:`torch.diagonal` + """ + + def diagonal_scatter( + self, + src: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, + ) -> Tensor: + r""" + diagonal_scatter(src, offset=0, dim1=0, dim2=1) -> Tensor + + See :func:`torch.diagonal_scatter` + """ + + def diff( + self, + n: _int = 1, + dim: _int = -1, + prepend: Tensor | None = None, + append: Tensor | None = None, + ) -> Tensor: + r""" + diff(n=1, dim=-1, prepend=None, append=None) -> Tensor + + See :func:`torch.diff` + """ + + def digamma(self) -> Tensor: + r""" + digamma() -> Tensor + + See :func:`torch.digamma` + """ + + def digamma_(self) -> Tensor: + r""" + digamma_() -> Tensor + + In-place version of :meth:`~Tensor.digamma` + """ + + def dim(self) -> _int: + r""" + dim() -> int + + Returns the number of dimensions of :attr:`self` tensor. + """ + + def dist( + self, + other: Tensor, + p: Number | _complex | PySymType = 2, + ) -> Tensor: + r""" + dist(other, p=2) -> Tensor + + See :func:`torch.dist` + """ + + def div( + self, + other: Tensor | Number, + *, + rounding_mode: str | None = None, + ) -> Tensor: + r""" + div(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.div` + """ + + def div_( + self, + other: Tensor | Number, + *, + rounding_mode: str | None = None, + ) -> Tensor: + r""" + div_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.div` + """ + + @overload + def divide(self, other: Tensor) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide(self, other: Tensor, *, rounding_mode: str | None) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide( + self, + other: Number | _complex | PySymType, + *, + rounding_mode: str | None, + ) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide(self, other: Number | _complex | PySymType) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide_(self, other: Tensor) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + @overload + def divide_(self, other: Tensor, *, rounding_mode: str | None) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + @overload + def divide_( + self, + other: Number | _complex | PySymType, + *, + rounding_mode: str | None, + ) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + @overload + def divide_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + def dot(self, tensor: Tensor) -> Tensor: + r""" + dot(other) -> Tensor + + See :func:`torch.dot` + """ + + def double(self) -> Tensor: + r""" + double(memory_format=torch.preserve_format) -> Tensor + + ``self.double()`` is equivalent to ``self.to(torch.float64)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def dsplit(self, sections: _int) -> tuple[Tensor, ...]: + r""" + dsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.dsplit` + """ + + @overload + def dsplit(self, indices: _size) -> tuple[Tensor, ...]: + r""" + dsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.dsplit` + """ + + @overload + def dsplit(self, *indices: _int) -> tuple[Tensor, ...]: + r""" + dsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.dsplit` + """ + + def element_size(self) -> _int: + r""" + element_size() -> int + + Returns the size in bytes of an individual element. + + Example:: + + >>> torch.tensor([]).element_size() + 4 + >>> torch.tensor([], dtype=torch.uint8).element_size() + 1 + """ + + @overload + def eq(self, other: Tensor) -> Tensor: + r""" + eq(other) -> Tensor + + See :func:`torch.eq` + """ + + @overload + def eq(self, other: Number | _complex | PySymType) -> Tensor: + r""" + eq(other) -> Tensor + + See :func:`torch.eq` + """ + + @overload + def eq_(self, other: Tensor) -> Tensor: + r""" + eq_(other) -> Tensor + + In-place version of :meth:`~Tensor.eq` + """ + + @overload + def eq_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + eq_(other) -> Tensor + + In-place version of :meth:`~Tensor.eq` + """ + + def equal(self, other: Tensor) -> _bool: + r""" + equal(other) -> bool + + See :func:`torch.equal` + """ + + def erf(self) -> Tensor: + r""" + erf() -> Tensor + + See :func:`torch.erf` + """ + + def erf_(self) -> Tensor: + r""" + erf_() -> Tensor + + In-place version of :meth:`~Tensor.erf` + """ + + def erfc(self) -> Tensor: + r""" + erfc() -> Tensor + + See :func:`torch.erfc` + """ + + def erfc_(self) -> Tensor: + r""" + erfc_() -> Tensor + + In-place version of :meth:`~Tensor.erfc` + """ + + def erfinv(self) -> Tensor: + r""" + erfinv() -> Tensor + + See :func:`torch.erfinv` + """ + + def erfinv_(self) -> Tensor: + r""" + erfinv_() -> Tensor + + In-place version of :meth:`~Tensor.erfinv` + """ + + def exp(self) -> Tensor: + r""" + exp() -> Tensor + + See :func:`torch.exp` + """ + + def exp2(self) -> Tensor: + r""" + exp2() -> Tensor + + See :func:`torch.exp2` + """ + + def exp2_(self) -> Tensor: + r""" + exp2_() -> Tensor + + In-place version of :meth:`~Tensor.exp2` + """ + + def exp_(self) -> Tensor: + r""" + exp_() -> Tensor + + In-place version of :meth:`~Tensor.exp` + """ + + @overload + def expand( + self, + size: Sequence[_int | SymInt], + *, + implicit: _bool = False, + ) -> Tensor: + r""" + expand(*size) -> Tensor + + Returns a new view of the :attr:`self` tensor with singleton dimensions expanded + to a larger size. + + Passing -1 as the size for a dimension means not changing the size of + that dimension. + + Tensor can be also expanded to a larger number of dimensions, and the + new ones will be appended at the front. For the new dimensions, the + size cannot be set to -1. + + Expanding a tensor does not allocate new memory, but only creates a + new view on the existing tensor where a dimension of size one is + expanded to a larger size by setting the ``stride`` to 0. Any dimension + of size 1 can be expanded to an arbitrary value without allocating new + memory. + + .. note:: + + Operations on an expanded view may still allocate memory if they need to + materialize the expanded values. For example, changing dtype after + :meth:`expand` can allocate memory for the full expanded shape. + + Args: + *size (torch.Size or int...): the desired expanded size + + .. warning:: + + More than one element of an expanded tensor may refer to a single + memory location. As a result, in-place operations (especially ones that + are vectorized) may result in incorrect behavior. If you need to write + to the tensors, please clone them first. + + Example:: + + >>> x = torch.tensor([[1], [2], [3]]) + >>> x.size() + torch.Size([3, 1]) + >>> x.expand(3, 4) + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + >>> x.expand(-1, 4) # -1 means not changing the size of that dimension + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + """ + + @overload + def expand(self, *size: _int | SymInt, implicit: _bool = False) -> Tensor: + r""" + expand(*size) -> Tensor + + Returns a new view of the :attr:`self` tensor with singleton dimensions expanded + to a larger size. + + Passing -1 as the size for a dimension means not changing the size of + that dimension. + + Tensor can be also expanded to a larger number of dimensions, and the + new ones will be appended at the front. For the new dimensions, the + size cannot be set to -1. + + Expanding a tensor does not allocate new memory, but only creates a + new view on the existing tensor where a dimension of size one is + expanded to a larger size by setting the ``stride`` to 0. Any dimension + of size 1 can be expanded to an arbitrary value without allocating new + memory. + + .. note:: + + Operations on an expanded view may still allocate memory if they need to + materialize the expanded values. For example, changing dtype after + :meth:`expand` can allocate memory for the full expanded shape. + + Args: + *size (torch.Size or int...): the desired expanded size + + .. warning:: + + More than one element of an expanded tensor may refer to a single + memory location. As a result, in-place operations (especially ones that + are vectorized) may result in incorrect behavior. If you need to write + to the tensors, please clone them first. + + Example:: + + >>> x = torch.tensor([[1], [2], [3]]) + >>> x.size() + torch.Size([3, 1]) + >>> x.expand(3, 4) + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + >>> x.expand(-1, 4) # -1 means not changing the size of that dimension + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + """ + + def expand_as(self, other: Tensor) -> Tensor: + r""" + expand_as(other) -> Tensor + + Expand this tensor to the same size as :attr:`other`. + ``self.expand_as(other)`` is equivalent to ``self.expand(other.size())``. + + Please see :meth:`~Tensor.expand` for more information about ``expand``. + + Args: + other (:class:`torch.Tensor`): The result tensor has the same size + as :attr:`other`. + """ + + def expm1(self) -> Tensor: + r""" + expm1() -> Tensor + + See :func:`torch.expm1` + """ + + def expm1_(self) -> Tensor: + r""" + expm1_() -> Tensor + + In-place version of :meth:`~Tensor.expm1` + """ + + def exponential_( + self, + lambd: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + exponential_(lambd=1, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with elements drawn from the PDF (probability density function): + + .. math:: + + f(x) = \lambda e^{-\lambda x}, x > 0 + + .. note:: + In probability theory, exponential distribution is supported on interval [0, :math:`\inf`) (i.e., :math:`x >= 0`) + implying that zero can be sampled from the exponential distribution. + However, :func:`torch.Tensor.exponential_` does not sample zero, + which means that its actual support is the interval (0, :math:`\inf`). + + Note that :func:`torch.distributions.exponential.Exponential` is supported on the interval [0, :math:`\inf`) and can sample zero. + """ + + @overload + def fill_(self, value: Tensor) -> Tensor: + r""" + fill_(value) -> Tensor + + Fills :attr:`self` tensor with the specified value. + """ + + @overload + def fill_(self, value: Number | _complex | PySymType) -> Tensor: + r""" + fill_(value) -> Tensor + + Fills :attr:`self` tensor with the specified value. + """ + + def fill_diagonal_( + self, + fill_value: Number | _complex | PySymType, + wrap: _bool = False, + ) -> Tensor: + r""" + fill_diagonal_(fill_value, wrap=False) -> Tensor + + Fill the main diagonal of a tensor that has at least 2-dimensions. + When dims>2, all dimensions of input must be of equal length. + This function modifies the input tensor in-place, and returns the input tensor. + + Arguments: + fill_value (Scalar): the fill value + wrap (bool, optional): the diagonal 'wrapped' after N columns for tall matrices. Default: ``False`` + + Example:: + + >>> a = torch.zeros(3, 3) + >>> a.fill_diagonal_(5) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.]]) + >>> b = torch.zeros(7, 3) + >>> b.fill_diagonal_(5) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.], + [0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> c = torch.zeros(7, 3) + >>> c.fill_diagonal_(5, wrap=True) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.], + [0., 0., 0.], + [5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.]]) + """ + + def fix(self) -> Tensor: + r""" + fix() -> Tensor + + See :func:`torch.fix`. + """ + + def fix_(self) -> Tensor: + r""" + fix_() -> Tensor + + In-place version of :meth:`~Tensor.fix` + """ + + def flatten(self, start_dim: _int = 0, end_dim: _int = -1) -> Tensor: + r""" + flatten(start_dim=0, end_dim=-1) -> Tensor + + See :func:`torch.flatten` + """ + + @overload + def flip(self, dims: _size) -> Tensor: + r""" + flip(dims) -> Tensor + + See :func:`torch.flip` + """ + + @overload + def flip(self, *dims: _int) -> Tensor: + r""" + flip(dims) -> Tensor + + See :func:`torch.flip` + """ + + def fliplr(self) -> Tensor: + r""" + fliplr() -> Tensor + + See :func:`torch.fliplr` + """ + + def flipud(self) -> Tensor: + r""" + flipud() -> Tensor + + See :func:`torch.flipud` + """ + + def float(self) -> Tensor: + r""" + float(memory_format=torch.preserve_format) -> Tensor + + ``self.float()`` is equivalent to ``self.to(torch.float32)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def float_power(self, exponent: Tensor) -> Tensor: + r""" + float_power(exponent) -> Tensor + + See :func:`torch.float_power` + """ + + @overload + def float_power(self, exponent: Number | _complex | PySymType) -> Tensor: + r""" + float_power(exponent) -> Tensor + + See :func:`torch.float_power` + """ + + @overload + def float_power_(self, exponent: Tensor) -> Tensor: + r""" + float_power_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.float_power` + """ + + @overload + def float_power_(self, exponent: Number | _complex | PySymType) -> Tensor: + r""" + float_power_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.float_power` + """ + + def floor(self) -> Tensor: + r""" + floor() -> Tensor + + See :func:`torch.floor` + """ + + def floor_(self) -> Tensor: + r""" + floor_() -> Tensor + + In-place version of :meth:`~Tensor.floor` + """ + + def floor_divide( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + *, + out: Tensor | None = None, + ) -> Tensor: + r""" + floor_divide(value) -> Tensor + + See :func:`torch.floor_divide` + """ + + def floor_divide_( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + ) -> Tensor: + r""" + floor_divide_(value) -> Tensor + + In-place version of :meth:`~Tensor.floor_divide` + """ + + def fmax(self, other: Tensor) -> Tensor: + r""" + fmax(other) -> Tensor + + See :func:`torch.fmax` + """ + + def fmin(self, other: Tensor) -> Tensor: + r""" + fmin(other) -> Tensor + + See :func:`torch.fmin` + """ + + @overload + def fmod(self, other: Tensor) -> Tensor: + r""" + fmod(divisor) -> Tensor + + See :func:`torch.fmod` + """ + + @overload + def fmod(self, other: Number | _complex | PySymType) -> Tensor: + r""" + fmod(divisor) -> Tensor + + See :func:`torch.fmod` + """ + + @overload + def fmod_(self, other: Tensor) -> Tensor: + r""" + fmod_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.fmod` + """ + + @overload + def fmod_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + fmod_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.fmod` + """ + + def frac(self) -> Tensor: + r""" + frac() -> Tensor + + See :func:`torch.frac` + """ + + def frac_(self) -> Tensor: + r""" + frac_() -> Tensor + + In-place version of :meth:`~Tensor.frac` + """ + + def frexp(self) -> torch.return_types.frexp: + r""" + frexp(input) -> (Tensor mantissa, Tensor exponent) + + See :func:`torch.frexp` + """ + + def gather( + self, + dim: _int, + index: Tensor, + *, + sparse_grad: _bool = False, + ) -> Tensor: + r""" + gather(dim, index) -> Tensor + + See :func:`torch.gather` + """ + + def gcd(self, other: Tensor) -> Tensor: + r""" + gcd(other) -> Tensor + + See :func:`torch.gcd` + """ + + def gcd_(self, other: Tensor) -> Tensor: + r""" + gcd_(other) -> Tensor + + In-place version of :meth:`~Tensor.gcd` + """ + + @overload + def ge(self, other: Tensor) -> Tensor: + r""" + ge(other) -> Tensor + + See :func:`torch.ge`. + """ + + @overload + def ge(self, other: Number | _complex | PySymType) -> Tensor: + r""" + ge(other) -> Tensor + + See :func:`torch.ge`. + """ + + @overload + def ge_(self, other: Tensor) -> Tensor: + r""" + ge_(other) -> Tensor + + In-place version of :meth:`~Tensor.ge`. + """ + + @overload + def ge_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + ge_(other) -> Tensor + + In-place version of :meth:`~Tensor.ge`. + """ + + def geometric_( + self, + p: _float, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + geometric_(p, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with elements drawn from the geometric distribution: + + .. math:: + + P(X=k) = (1 - p)^{k - 1} p, k = 1, 2, ... + + .. note:: + :func:`torch.Tensor.geometric_` `k`-th trial is the first success hence draws samples in :math:`\{1, 2, \ldots\}`, whereas + :func:`torch.distributions.geometric.Geometric` :math:`(k+1)`-th trial is the first success + hence draws samples in :math:`\{0, 1, \ldots\}`. + """ + + def geqrf(self) -> torch.return_types.geqrf: + r""" + geqrf() -> (Tensor, Tensor) + + See :func:`torch.geqrf` + """ + + def ger(self, vec2: Tensor) -> Tensor: + r""" + ger(vec2) -> Tensor + + See :func:`torch.ger` + """ + + def get_device(self) -> _int: + r""" + get_device() -> Device ordinal (Integer) + + For CUDA tensors, this function returns the device ordinal of the GPU on which the tensor resides. + For CPU tensors, this function returns `-1`. + + Example:: + + >>> x = torch.randn(3, 4, 5, device='cuda:0') + >>> x.get_device() + 0 + >>> x.cpu().get_device() + -1 + """ + + @overload + def greater(self, other: Tensor) -> Tensor: + r""" + greater(other) -> Tensor + + See :func:`torch.greater`. + """ + + @overload + def greater(self, other: Number | _complex | PySymType) -> Tensor: + r""" + greater(other) -> Tensor + + See :func:`torch.greater`. + """ + + @overload + def greater_(self, other: Tensor) -> Tensor: + r""" + greater_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater`. + """ + + @overload + def greater_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + greater_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater`. + """ + + @overload + def greater_equal(self, other: Tensor) -> Tensor: + r""" + greater_equal(other) -> Tensor + + See :func:`torch.greater_equal`. + """ + + @overload + def greater_equal(self, other: Number | _complex | PySymType) -> Tensor: + r""" + greater_equal(other) -> Tensor + + See :func:`torch.greater_equal`. + """ + + @overload + def greater_equal_(self, other: Tensor) -> Tensor: + r""" + greater_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater_equal`. + """ + + @overload + def greater_equal_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + greater_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater_equal`. + """ + + @overload + def gt(self, other: Tensor) -> Tensor: + r""" + gt(other) -> Tensor + + See :func:`torch.gt`. + """ + + @overload + def gt(self, other: Number | _complex | PySymType) -> Tensor: + r""" + gt(other) -> Tensor + + See :func:`torch.gt`. + """ + + @overload + def gt_(self, other: Tensor) -> Tensor: + r""" + gt_(other) -> Tensor + + In-place version of :meth:`~Tensor.gt`. + """ + + @overload + def gt_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + gt_(other) -> Tensor + + In-place version of :meth:`~Tensor.gt`. + """ + + def half(self) -> Tensor: + r""" + half(memory_format=torch.preserve_format) -> Tensor + + ``self.half()`` is equivalent to ``self.to(torch.float16)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def hardshrink(self, lambd: Number | _complex | PySymType = 0.5) -> Tensor: + r""" + hardshrink(lambd=0.5) -> Tensor + + See :func:`torch.nn.functional.hardshrink` + """ + + @overload + def hash_tensor( + self, + dim: _int | _size = (), + *, + keepdim: _bool = False, + mode: _int = 0, + ) -> Tensor: ... + @overload + def hash_tensor( + self, + *dim: _int, + keepdim: _bool = False, + mode: _int = 0, + ) -> Tensor: ... + def heaviside(self, values: Tensor) -> Tensor: + r""" + heaviside(values) -> Tensor + + See :func:`torch.heaviside` + """ + + def heaviside_(self, values: Tensor) -> Tensor: + r""" + heaviside_(values) -> Tensor + + In-place version of :meth:`~Tensor.heaviside` + """ + + def histc( + self, + bins: _int = 100, + min: Number | _complex | PySymType = 0, + max: Number | _complex | PySymType = 0, + ) -> Tensor: + r""" + histc(bins=100, min=0, max=0) -> Tensor + + See :func:`torch.histc` + """ + + @overload + def histogram( + self, + bins: Tensor, + *, + weight: Tensor | None = None, + density: _bool = False, + ) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False) -> (Tensor, Tensor) + + See :func:`torch.histogram` + """ + + @overload + def histogram( + self, + bins: _int = 100, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, + ) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False) -> (Tensor, Tensor) + + See :func:`torch.histogram` + """ + + @overload + def hsplit(self, sections: _int) -> tuple[Tensor, ...]: + r""" + hsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.hsplit` + """ + + @overload + def hsplit(self, indices: _size) -> tuple[Tensor, ...]: + r""" + hsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.hsplit` + """ + + @overload + def hsplit(self, *indices: _int) -> tuple[Tensor, ...]: + r""" + hsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.hsplit` + """ + + def hypot(self, other: Tensor) -> Tensor: + r""" + hypot(other) -> Tensor + + See :func:`torch.hypot` + """ + + def hypot_(self, other: Tensor) -> Tensor: + r""" + hypot_(other) -> Tensor + + In-place version of :meth:`~Tensor.hypot` + """ + + def i0(self) -> Tensor: + r""" + i0() -> Tensor + + See :func:`torch.i0` + """ + + def i0_(self) -> Tensor: + r""" + i0_() -> Tensor + + In-place version of :meth:`~Tensor.i0` + """ + + def igamma(self, other: Tensor) -> Tensor: + r""" + igamma(other) -> Tensor + + See :func:`torch.igamma` + """ + + def igamma_(self, other: Tensor) -> Tensor: + r""" + igamma_(other) -> Tensor + + In-place version of :meth:`~Tensor.igamma` + """ + + def igammac(self, other: Tensor) -> Tensor: + r""" + igammac(other) -> Tensor + See :func:`torch.igammac` + """ + + def igammac_(self, other: Tensor) -> Tensor: + r""" + igammac_(other) -> Tensor + In-place version of :meth:`~Tensor.igammac` + """ + + def index_add( + self, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + index_add(dim, index, source, *, alpha=1) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_add_`. + """ + + def index_add_( + self, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + index_add_(dim, index, source, *, alpha=1) -> Tensor + + Accumulate the elements of :attr:`alpha` times ``source`` into the :attr:`self` + tensor by adding to the indices in the order given in :attr:`index`. For example, + if ``dim == 0``, ``index[i] == j``, and ``alpha=-1``, then the ``i``\ th row of + ``source`` is subtracted from the ``j``\ th row of :attr:`self`. + + The :attr:`dim`\ th dimension of ``source`` must have the same size as the + length of :attr:`index` (which must be a vector), and all other dimensions must + match :attr:`self`, or an error will be raised. + + For a 3-D tensor the output is given as:: + + self[index[i], :, :] += alpha * src[i, :, :] # if dim == 0 + self[:, index[i], :] += alpha * src[:, i, :] # if dim == 1 + self[:, :, index[i]] += alpha * src[:, :, i] # if dim == 2 + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + Args: + dim (int): dimension along which to index + index (Tensor): indices of ``source`` to select from, + should have dtype either `torch.int64` or `torch.int32` + source (Tensor): the tensor containing values to add + + Keyword args: + alpha (Number): the scalar multiplier for ``source`` + + Example:: + + >>> x = torch.ones(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_add_(0, index, t) + tensor([[ 2., 3., 4.], + [ 1., 1., 1.], + [ 8., 9., 10.], + [ 1., 1., 1.], + [ 5., 6., 7.]]) + >>> x.index_add_(0, index, t, alpha=-1) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + """ + + def index_copy(self, dim: _int, index: Tensor, source: Tensor) -> Tensor: + r""" + index_copy(dim, index, tensor2) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_copy_`. + """ + + def index_copy_(self, dim: _int, index: Tensor, source: Tensor) -> Tensor: + r""" + index_copy_(dim, index, tensor) -> Tensor + + Copies the elements of :attr:`tensor` into the :attr:`self` tensor by selecting + the indices in the order given in :attr:`index`. For example, if ``dim == 0`` + and ``index[i] == j``, then the ``i``\ th row of :attr:`tensor` is copied to the + ``j``\ th row of :attr:`self`. + + The :attr:`dim`\ th dimension of :attr:`tensor` must have the same size as the + length of :attr:`index` (which must be a vector), and all other dimensions must + match :attr:`self`, or an error will be raised. + + .. note:: + If :attr:`index` contains duplicate entries, multiple elements from + :attr:`tensor` will be copied to the same index of :attr:`self`. The result + is nondeterministic since it depends on which copy occurs last. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`tensor` to select from + tensor (Tensor): the tensor containing values to copy + + Example:: + + >>> x = torch.zeros(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_copy_(0, index, t) + tensor([[ 1., 2., 3.], + [ 0., 0., 0.], + [ 7., 8., 9.], + [ 0., 0., 0.], + [ 4., 5., 6.]]) + """ + + @overload + def index_fill(self, dim: _int, index: Tensor, value: Tensor) -> Tensor: + r""" + index_fill(dim, index, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_fill_`. + """ + + @overload + def index_fill( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + index_fill(dim, index, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_fill_`. + """ + + @overload + def index_fill_(self, dim: _int, index: Tensor, value: Tensor) -> Tensor: + r""" + index_fill_(dim, index, value) -> Tensor + + Fills the elements of the :attr:`self` tensor with value :attr:`value` by + selecting the indices in the order given in :attr:`index`. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`self` tensor to fill in + value (float): the value to fill with + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 2]) + >>> x.index_fill_(1, index, -1) + tensor([[-1., 2., -1.], + [-1., 5., -1.], + [-1., 8., -1.]]) + """ + + @overload + def index_fill_( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + index_fill_(dim, index, value) -> Tensor + + Fills the elements of the :attr:`self` tensor with value :attr:`value` by + selecting the indices in the order given in :attr:`index`. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`self` tensor to fill in + value (float): the value to fill with + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 2]) + >>> x.index_fill_(1, index, -1) + tensor([[-1., 2., -1.], + [-1., 5., -1.], + [-1., 8., -1.]]) + """ + + def index_put( + self, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + index_put(indices, values, accumulate=False) -> Tensor + + Out-place version of :meth:`~Tensor.index_put_`. + """ + + def index_put_( + self, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + index_put_(indices, values, accumulate=False) -> Tensor + + Puts values from the tensor :attr:`values` into the tensor :attr:`self` using + the indices specified in :attr:`indices` (which is a tuple of Tensors). The + expression ``tensor.index_put_(indices, values)`` is equivalent to + ``tensor[indices] = values``. Returns :attr:`self`. + + If :attr:`accumulate` is ``True``, the elements in :attr:`values` are added to + :attr:`self`. If accumulate is ``False``, the behavior is undefined if indices + contain duplicate elements. + + Args: + indices (tuple of LongTensor): tensors used to index into `self`. + values (Tensor): tensor of same dtype as `self`. + accumulate (bool): whether to accumulate into self + """ + + def index_reduce( + self, + dim: _int, + index: Tensor, + source: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: ... + def index_reduce_( + self, + dim: _int, + index: Tensor, + source: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: + r""" + index_reduce_(dim, index, source, reduce, *, include_self=True) -> Tensor + + Accumulate the elements of ``source`` into the :attr:`self` + tensor by accumulating to the indices in the order given in :attr:`index` + using the reduction given by the ``reduce`` argument. For example, if ``dim == 0``, + ``index[i] == j``, ``reduce == prod`` and ``include_self == True`` then the ``i``\ th + row of ``source`` is multiplied by the ``j``\ th row of :attr:`self`. If + :obj:`include_self="True"`, the values in the :attr:`self` tensor are included + in the reduction, otherwise, rows in the :attr:`self` tensor that are accumulated + to are treated as if they were filled with the reduction identities. + + The :attr:`dim`\ th dimension of ``source`` must have the same size as the + length of :attr:`index` (which must be a vector), and all other dimensions must + match :attr:`self`, or an error will be raised. + + For a 3-D tensor with :obj:`reduce="prod"` and :obj:`include_self=True` the + output is given as:: + + self[index[i], :, :] *= src[i, :, :] # if dim == 0 + self[:, index[i], :] *= src[:, i, :] # if dim == 1 + self[:, :, index[i]] *= src[:, :, i] # if dim == 2 + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + .. note:: + + This function only supports floating point tensors. + + .. warning:: + + This function is in beta and may change in the near future. + + Args: + dim (int): dimension along which to index + index (Tensor): indices of :attr:`self` to accumulate into, + should have dtype either `torch.int64` or `torch.int32` + source (FloatTensor): the tensor containing values to accumulate + reduce (str): the reduction operation to apply + (:obj:`"prod"`, :obj:`"mean"`, :obj:`"amax"`, :obj:`"amin"`) + + Keyword args: + include_self (bool): whether the elements from the ``self`` tensor are + included in the reduction + + Example:: + + >>> x = torch.empty(5, 3).fill_(2) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2, 0]) + >>> x.index_reduce_(0, index, t, 'prod') + tensor([[20., 44., 72.], + [ 2., 2., 2.], + [14., 16., 18.], + [ 2., 2., 2.], + [ 8., 10., 12.]]) + >>> x = torch.empty(5, 3).fill_(2) + >>> x.index_reduce_(0, index, t, 'prod', include_self=False) + tensor([[10., 22., 36.], + [ 2., 2., 2.], + [ 7., 8., 9.], + [ 2., 2., 2.], + [ 4., 5., 6.]]) + """ + + def index_select(self, dim: _int, index: Tensor) -> Tensor: + r""" + index_select(dim, index) -> Tensor + + See :func:`torch.index_select` + """ + + def indices(self) -> Tensor: + r""" + indices() -> Tensor + + Return the indices tensor of a :ref:`sparse COO tensor `. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + + See also :meth:`Tensor.values`. + + .. note:: + This method can only be called on a coalesced sparse tensor. See + :meth:`Tensor.coalesce` for details. + """ + + def inner(self, other: Tensor) -> Tensor: + r""" + inner(other) -> Tensor + + See :func:`torch.inner`. + """ + + def int(self) -> Tensor: + r""" + int(memory_format=torch.preserve_format) -> Tensor + + ``self.int()`` is equivalent to ``self.to(torch.int32)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def int_repr(self) -> Tensor: + r""" + int_repr() -> Tensor + + Given a quantized Tensor, + ``self.int_repr()`` returns a CPU Tensor with uint8_t as data type that stores the + underlying uint8_t values of the given Tensor. + """ + + def inverse(self) -> Tensor: + r""" + inverse() -> Tensor + + See :func:`torch.inverse` + """ + + def is_coalesced(self) -> _bool: + r""" + is_coalesced() -> bool + + Returns ``True`` if :attr:`self` is a :ref:`sparse COO tensor + ` that is coalesced, ``False`` otherwise. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + + See :meth:`coalesce` and :ref:`uncoalesced tensors `. + """ + + def is_complex(self) -> _bool: + r""" + is_complex() -> bool + + Returns True if the data type of :attr:`self` is a complex data type. + """ + + def is_conj(self) -> _bool: + r""" + is_conj() -> bool + + Returns True if the conjugate bit of :attr:`self` is set to true. + """ + + def is_contiguous( + self, + memory_format: torch.memory_format = torch.contiguous_format, + ) -> _bool: + r""" + is_contiguous(memory_format=torch.contiguous_format) -> bool + + Returns True if :attr:`self` tensor is contiguous in memory in the order specified + by memory format. + + Args: + memory_format (:class:`torch.memory_format`, optional): Specifies memory allocation + order. Default: ``torch.contiguous_format``. + """ + is_cpu: _bool + r"""Is ``True`` if the Tensor is stored on the CPU, ``False`` otherwise.""" + is_cuda: _bool + r"""Is ``True`` if the Tensor is stored on the GPU, ``False`` otherwise.""" + + def is_distributed(self) -> _bool: ... + def is_floating_point(self) -> _bool: + r""" + is_floating_point() -> bool + + Returns True if the data type of :attr:`self` is a floating point data type. + """ + + def is_inference(self) -> _bool: + r""" + is_inference() -> bool + + See :func:`torch.is_inference` + """ + is_ipu: _bool + r"""Is ``True`` if the Tensor is stored on the IPU, ``False`` otherwise.""" + is_leaf: _bool + r"""All Tensors that have :attr:`requires_grad` which is ``False`` will be leaf Tensors by convention. + + For Tensors that have :attr:`requires_grad` which is ``True``, they will be leaf Tensors if they were + created by the user. This means that they are not the result of an operation and so + :attr:`grad_fn` is None. + + Only leaf Tensors will have their :attr:`grad` populated during a call to :func:`backward`. + To get :attr:`grad` populated for non-leaf Tensors, you can use :func:`retain_grad`. + + Example:: + + >>> a = torch.rand(10, requires_grad=True) + >>> a.is_leaf + True + >>> b = torch.rand(10, requires_grad=True).cuda() + >>> b.is_leaf + False + # b was created by the operation that cast a cpu Tensor into a cuda Tensor + >>> c = torch.rand(10, requires_grad=True) + 2 + >>> c.is_leaf + False + # c was created by the addition operation + >>> d = torch.rand(10).cuda() + >>> d.is_leaf + True + # d does not require gradients and so has no operation creating it (that is tracked by the autograd engine) + >>> e = torch.rand(10).cuda().requires_grad_() + >>> e.is_leaf + True + # e requires gradients and has no operations creating it + >>> f = torch.rand(10, requires_grad=True, device="cuda") + >>> f.is_leaf + True + # f requires grad, has no operation creating it""" + is_maia: _bool + is_meta: _bool + r"""Is ``True`` if the Tensor is a meta tensor, ``False`` otherwise. Meta tensors + are like normal tensors, but they carry no data.""" + is_mkldnn: _bool + is_mps: _bool + r"""Is ``True`` if the Tensor is stored on the MPS device, ``False`` otherwise.""" + is_mtia: _bool + def is_neg(self) -> _bool: + r""" + is_neg() -> bool + + Returns True if the negative bit of :attr:`self` is set to true. + """ + is_nested: _bool + def is_nonzero(self) -> _bool: ... + def is_pinned(self, device: DeviceLikeType | None = None) -> _bool: + r""" + Returns true if this tensor resides in pinned memory. + By default, the device pinned memory on will be the current :ref:`accelerator`. + """ + is_quantized: _bool + r"""Is ``True`` if the Tensor is quantized, ``False`` otherwise.""" + + def is_same_size(self, other: Tensor) -> _bool: ... + def is_set_to(self, tensor: Tensor) -> _bool: + r""" + is_set_to(tensor) -> bool + + Returns True if both tensors are pointing to the exact same memory (same + storage, offset, size and stride). + """ + + def is_signed(self) -> _bool: + r""" + is_signed() -> bool + + Returns True if the data type of :attr:`self` is a signed data type. + """ + is_sparse: _bool + r"""Is ``True`` if the Tensor uses sparse COO storage layout, ``False`` otherwise.""" + is_sparse_csr: _bool + r"""Is ``True`` if the Tensor uses sparse CSR storage layout, ``False`` otherwise.""" + is_vulkan: _bool + is_xpu: _bool + r"""Is ``True`` if the Tensor is stored on the XPU, ``False`` otherwise.""" + + def isclose( + self, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, + ) -> Tensor: + r""" + isclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + See :func:`torch.isclose` + """ + + def isfinite(self) -> Tensor: + r""" + isfinite() -> Tensor + + See :func:`torch.isfinite` + """ + + def isinf(self) -> Tensor: + r""" + isinf() -> Tensor + + See :func:`torch.isinf` + """ + + def isnan(self) -> Tensor: + r""" + isnan() -> Tensor + + See :func:`torch.isnan` + """ + + def isneginf(self) -> Tensor: + r""" + isneginf() -> Tensor + + See :func:`torch.isneginf` + """ + + def isposinf(self) -> Tensor: + r""" + isposinf() -> Tensor + + See :func:`torch.isposinf` + """ + + def isreal(self) -> Tensor: + r""" + isreal() -> Tensor + + See :func:`torch.isreal` + """ + + def istft( + self, + n_fft: _int, + hop_length: _int | None = None, + win_length: _int | None = None, + window: Tensor | None = None, + center: _bool = True, + normalized: _bool = False, + onesided: _bool | None = None, + length: _int | None = None, + return_complex: _bool = False, + ) -> Tensor: + r""" + istft(n_fft, hop_length=None, win_length=None, window=None, + center=True, normalized=False, onesided=True, length=None) -> Tensor + + See :func:`torch.istft` + """ + + def item(self) -> Number: + r""" + item() -> number + + Returns the value of this tensor as a standard Python number. This only works + for tensors with one element. For other cases, see :meth:`~Tensor.tolist`. + + This operation is not differentiable. + + Example:: + + >>> x = torch.tensor([1.0]) + >>> x.item() + 1.0 + """ + + def kron(self, other: Tensor) -> Tensor: + r""" + kron(other) -> Tensor + + See :func:`torch.kron` + """ + + def kthvalue( + self, + k: _int | SymInt, + dim: _int = -1, + keepdim: _bool = False, + ) -> torch.return_types.kthvalue: + r""" + kthvalue(k, dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.kthvalue` + """ + + def lcm(self, other: Tensor) -> Tensor: + r""" + lcm(other) -> Tensor + + See :func:`torch.lcm` + """ + + def lcm_(self, other: Tensor) -> Tensor: + r""" + lcm_(other) -> Tensor + + In-place version of :meth:`~Tensor.lcm` + """ + + def ldexp(self, other: Tensor) -> Tensor: + r""" + ldexp(other) -> Tensor + + See :func:`torch.ldexp` + """ + + def ldexp_(self, other: Tensor) -> Tensor: + r""" + ldexp_(other) -> Tensor + + In-place version of :meth:`~Tensor.ldexp` + """ + + @overload + def le(self, other: Tensor) -> Tensor: + r""" + le(other) -> Tensor + + See :func:`torch.le`. + """ + + @overload + def le(self, other: Number | _complex | PySymType) -> Tensor: + r""" + le(other) -> Tensor + + See :func:`torch.le`. + """ + + @overload + def le_(self, other: Tensor) -> Tensor: + r""" + le_(other) -> Tensor + + In-place version of :meth:`~Tensor.le`. + """ + + @overload + def le_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + le_(other) -> Tensor + + In-place version of :meth:`~Tensor.le`. + """ + + @overload + def lerp(self, end: Tensor, weight: Tensor) -> Tensor: + r""" + lerp(end, weight) -> Tensor + + See :func:`torch.lerp` + """ + + @overload + def lerp( + self, + end: Tensor, + weight: Number | _complex | PySymType, + ) -> Tensor: + r""" + lerp(end, weight) -> Tensor + + See :func:`torch.lerp` + """ + + @overload + def lerp_(self, end: Tensor, weight: Tensor) -> Tensor: + r""" + lerp_(end, weight) -> Tensor + + In-place version of :meth:`~Tensor.lerp` + """ + + @overload + def lerp_( + self, + end: Tensor, + weight: Number | _complex | PySymType, + ) -> Tensor: + r""" + lerp_(end, weight) -> Tensor + + In-place version of :meth:`~Tensor.lerp` + """ + + @overload + def less(self, other: Tensor) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.less`. + """ + + @overload + def less(self, other: Number | _complex | PySymType) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.less`. + """ + + @overload + def less_(self, other: Tensor) -> Tensor: + r""" + less_(other) -> Tensor + + In-place version of :meth:`~Tensor.less`. + """ + + @overload + def less_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + less_(other) -> Tensor + + In-place version of :meth:`~Tensor.less`. + """ + + @overload + def less_equal(self, other: Tensor) -> Tensor: + r""" + less_equal(other) -> Tensor + + See :func:`torch.less_equal`. + """ + + @overload + def less_equal(self, other: Number | _complex | PySymType) -> Tensor: + r""" + less_equal(other) -> Tensor + + See :func:`torch.less_equal`. + """ + + @overload + def less_equal_(self, other: Tensor) -> Tensor: + r""" + less_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.less_equal`. + """ + + @overload + def less_equal_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + less_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.less_equal`. + """ + + def lgamma(self) -> Tensor: + r""" + lgamma() -> Tensor + + See :func:`torch.lgamma` + """ + + def lgamma_(self) -> Tensor: + r""" + lgamma_() -> Tensor + + In-place version of :meth:`~Tensor.lgamma` + """ + + def log(self) -> Tensor: + r""" + log() -> Tensor + + See :func:`torch.log` + """ + + def log10(self) -> Tensor: + r""" + log10() -> Tensor + + See :func:`torch.log10` + """ + + def log10_(self) -> Tensor: + r""" + log10_() -> Tensor + + In-place version of :meth:`~Tensor.log10` + """ + + def log1p(self) -> Tensor: + r""" + log1p() -> Tensor + + See :func:`torch.log1p` + """ + + def log1p_(self) -> Tensor: + r""" + log1p_() -> Tensor + + In-place version of :meth:`~Tensor.log1p` + """ + + def log2(self) -> Tensor: + r""" + log2() -> Tensor + + See :func:`torch.log2` + """ + + def log2_(self) -> Tensor: + r""" + log2_() -> Tensor + + In-place version of :meth:`~Tensor.log2` + """ + + def log_(self) -> Tensor: + r""" + log_() -> Tensor + + In-place version of :meth:`~Tensor.log` + """ + + def log_normal_( + self, + mean: _float = 1, + std: _float = 2, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + log_normal_(mean=1, std=2, *, generator=None) + + Fills :attr:`self` tensor with numbers samples from the log-normal distribution + parameterized by the given mean :math:`\mu` and standard deviation + :math:`\sigma`. Note that :attr:`mean` and :attr:`std` are the mean and + standard deviation of the underlying normal distribution, and not of the + returned distribution: + + .. math:: + + f(x) = \dfrac{1}{x \sigma \sqrt{2\pi}}\ e^{-\frac{(\ln x - \mu)^2}{2\sigma^2}} + """ + + def log_softmax(self, dim: _int, dtype: _dtype | None = None) -> Tensor: ... + def logaddexp(self, other: Tensor) -> Tensor: + r""" + logaddexp(other) -> Tensor + + See :func:`torch.logaddexp` + """ + + def logaddexp2(self, other: Tensor) -> Tensor: + r""" + logaddexp2(other) -> Tensor + + See :func:`torch.logaddexp2` + """ + + def logcumsumexp(self, dim: _int) -> Tensor: + r""" + logcumsumexp(dim) -> Tensor + + See :func:`torch.logcumsumexp` + """ + + def logdet(self) -> Tensor: + r""" + logdet() -> Tensor + + See :func:`torch.logdet` + """ + + def logical_and(self, other: Tensor) -> Tensor: + r""" + logical_and() -> Tensor + + See :func:`torch.logical_and` + """ + + def logical_and_(self, other: Tensor) -> Tensor: + r""" + logical_and_() -> Tensor + + In-place version of :meth:`~Tensor.logical_and` + """ + + def logical_not(self) -> Tensor: + r""" + logical_not() -> Tensor + + See :func:`torch.logical_not` + """ + + def logical_not_(self) -> Tensor: + r""" + logical_not_() -> Tensor + + In-place version of :meth:`~Tensor.logical_not` + """ + + def logical_or(self, other: Tensor) -> Tensor: + r""" + logical_or() -> Tensor + + See :func:`torch.logical_or` + """ + + def logical_or_(self, other: Tensor) -> Tensor: + r""" + logical_or_() -> Tensor + + In-place version of :meth:`~Tensor.logical_or` + """ + + def logical_xor(self, other: Tensor) -> Tensor: + r""" + logical_xor() -> Tensor + + See :func:`torch.logical_xor` + """ + + def logical_xor_(self, other: Tensor) -> Tensor: + r""" + logical_xor_() -> Tensor + + In-place version of :meth:`~Tensor.logical_xor` + """ + + def logit(self, eps: _float | None = None) -> Tensor: + r""" + logit() -> Tensor + + See :func:`torch.logit` + """ + + def logit_(self, eps: _float | None = None) -> Tensor: + r""" + logit_() -> Tensor + + In-place version of :meth:`~Tensor.logit` + """ + + def logsumexp(self, dim: _int | _size, keepdim: _bool = False) -> Tensor: + r""" + logsumexp(dim, keepdim=False) -> Tensor + + See :func:`torch.logsumexp` + """ + + def long(self) -> Tensor: + r""" + long(memory_format=torch.preserve_format) -> Tensor + + ``self.long()`` is equivalent to ``self.to(torch.int64)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def lt(self, other: Tensor) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.lt`. + """ + + @overload + def lt(self, other: Number | _complex | PySymType) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.lt`. + """ + + @overload + def lt_(self, other: Tensor) -> Tensor: + r""" + lt_(other) -> Tensor + + In-place version of :meth:`~Tensor.lt`. + """ + + @overload + def lt_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + lt_(other) -> Tensor + + In-place version of :meth:`~Tensor.lt`. + """ + + def lu_solve(self, LU_data: Tensor, LU_pivots: Tensor) -> Tensor: + r""" + lu_solve(LU_data, LU_pivots) -> Tensor + + See :func:`torch.lu_solve` + """ + + def map2_(self, x: Tensor, y: Tensor, callable: Callable) -> Tensor: ... + def map_(self, other: Tensor, callable: Callable) -> Tensor: + r""" + map_(tensor, callable) + + Applies :attr:`callable` for each element in :attr:`self` tensor and the given + :attr:`tensor` and stores the results in :attr:`self` tensor. :attr:`self` tensor and + the given :attr:`tensor` must be :ref:`broadcastable `. + + The :attr:`callable` should have the signature:: + + def callable(a, b) -> number + """ + + @overload + def masked_fill(self, mask: Tensor, value: Tensor) -> Tensor: + r""" + masked_fill(mask, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.masked_fill_` + """ + + @overload + def masked_fill( + self, + mask: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + masked_fill(mask, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.masked_fill_` + """ + + @overload + def masked_fill_(self, mask: Tensor, value: Tensor) -> Tensor: + r""" + masked_fill_(mask, value) + + Fills elements of :attr:`self` tensor with :attr:`value` where :attr:`mask` is + True. The shape of :attr:`mask` must be + :ref:`broadcastable ` with the shape of the underlying + tensor. + + Args: + mask (BoolTensor): the boolean mask + value (float): the value to fill in with + """ + + @overload + def masked_fill_( + self, + mask: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + masked_fill_(mask, value) + + Fills elements of :attr:`self` tensor with :attr:`value` where :attr:`mask` is + True. The shape of :attr:`mask` must be + :ref:`broadcastable ` with the shape of the underlying + tensor. + + Args: + mask (BoolTensor): the boolean mask + value (float): the value to fill in with + """ + + def masked_scatter(self, mask: Tensor, source: Tensor) -> Tensor: + r""" + masked_scatter(mask, tensor) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.masked_scatter_` + + .. note:: + + The inputs :attr:`self` and :attr:`mask` + :ref:`broadcast `. + + Example: + + >>> self = torch.tensor([0, 0, 0, 0, 0]) + >>> mask = torch.tensor( + ... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]], + ... dtype=torch.bool, + ... ) + >>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + >>> self.masked_scatter(mask, source) + tensor([[0, 0, 0, 0, 1], + [2, 3, 0, 4, 5]]) + """ + + def masked_scatter_(self, mask: Tensor, source: Tensor) -> Tensor: + r""" + masked_scatter_(mask, source) + + Copies elements from :attr:`source` into :attr:`self` tensor at positions where + the :attr:`mask` is True. Elements from :attr:`source` are copied into :attr:`self` + starting at position 0 of :attr:`source` and continuing in order one-by-one for each + occurrence of :attr:`mask` being True. + The shape of :attr:`mask` must be :ref:`broadcastable ` + with the shape of the underlying tensor. The :attr:`source` should have at least + as many elements as the number of ones in :attr:`mask`. + + Args: + mask (BoolTensor): the boolean mask + source (Tensor): the tensor to copy from + + .. note:: + + The :attr:`mask` operates on the :attr:`self` tensor, not on the given + :attr:`source` tensor. + + Example: + + >>> self = torch.tensor([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) + >>> mask = torch.tensor( + ... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]], + ... dtype=torch.bool, + ... ) + >>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + >>> self.masked_scatter_(mask, source) + tensor([[0, 0, 0, 0, 1], + [2, 3, 0, 4, 5]]) + """ + + def masked_select(self, mask: Tensor) -> Tensor: + r""" + masked_select(mask) -> Tensor + + See :func:`torch.masked_select` + """ + + def matmul(self, other: Tensor) -> Tensor: + r""" + matmul(tensor2) -> Tensor + + See :func:`torch.matmul` + """ + + def matrix_exp(self) -> Tensor: + r""" + matrix_exp() -> Tensor + + See :func:`torch.matrix_exp` + """ + + def matrix_power(self, n: _int) -> Tensor: + r""" + matrix_power(n) -> Tensor + + .. note:: :meth:`~Tensor.matrix_power` is deprecated, use :func:`torch.linalg.matrix_power` instead. + + Alias for :func:`torch.linalg.matrix_power` + """ + + @overload + def max(self) -> Tensor: + r""" + max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.max` + """ + + @overload + def max(self, other: Tensor) -> Tensor: + r""" + max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.max` + """ + + @overload + def max(self, dim: _int, keepdim: _bool = False) -> torch.return_types.max: + r""" + max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.max` + """ + + def maximum(self, other: Tensor) -> Tensor: + r""" + maximum(other) -> Tensor + + See :func:`torch.maximum` + """ + + @overload + def mean(self, *, dtype: _dtype | None = None) -> Tensor: + r""" + mean(dim=None, keepdim=False, *, dtype=None) -> Tensor + + See :func:`torch.mean` + """ + + @overload + def mean( + self, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + mean(dim=None, keepdim=False, *, dtype=None) -> Tensor + + See :func:`torch.mean` + """ + + @overload + def median(self) -> Tensor: + r""" + median(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.median` + """ + + @overload + def median( + self, + dim: _int, + keepdim: _bool = False, + ) -> torch.return_types.median: + r""" + median(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.median` + """ + + @overload + def min(self) -> Tensor: + r""" + min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.min` + """ + + @overload + def min(self, other: Tensor) -> Tensor: + r""" + min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.min` + """ + + @overload + def min(self, dim: _int, keepdim: _bool = False) -> torch.return_types.min: + r""" + min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.min` + """ + + def minimum(self, other: Tensor) -> Tensor: + r""" + minimum(other) -> Tensor + + See :func:`torch.minimum` + """ + + def mm(self, mat2: Tensor) -> Tensor: + r""" + mm(mat2) -> Tensor + + See :func:`torch.mm` + """ + + def mode( + self, + dim: _int = -1, + keepdim: _bool = False, + ) -> torch.return_types.mode: + r""" + mode(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.mode` + """ + + @overload + def moveaxis(self, source: _int, destination: _int) -> Tensor: + r""" + moveaxis(source, destination) -> Tensor + + See :func:`torch.moveaxis` + """ + + @overload + def moveaxis(self, source: _size, destination: _size) -> Tensor: + r""" + moveaxis(source, destination) -> Tensor + + See :func:`torch.moveaxis` + """ + + @overload + def movedim(self, source: _int, destination: _int) -> Tensor: + r""" + movedim(source, destination) -> Tensor + + See :func:`torch.movedim` + """ + + @overload + def movedim(self, source: _size, destination: _size) -> Tensor: + r""" + movedim(source, destination) -> Tensor + + See :func:`torch.movedim` + """ + + def msort(self) -> Tensor: + r""" + msort() -> Tensor + + See :func:`torch.msort` + """ + + def mul( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + out: Tensor | None = None, + ) -> Tensor: + r""" + mul(value) -> Tensor + + See :func:`torch.mul`. + """ + + def mul_( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + ) -> Tensor: + r""" + mul_(value) -> Tensor + + In-place version of :meth:`~Tensor.mul`. + """ + + def multinomial( + self, + num_samples: _int | SymInt, + replacement: _bool = False, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + multinomial(num_samples, replacement=False, *, generator=None) -> Tensor + + See :func:`torch.multinomial` + """ + + @overload + def multiply(self, other: Tensor) -> Tensor: + r""" + multiply(value) -> Tensor + + See :func:`torch.multiply`. + """ + + @overload + def multiply(self, other: Number | _complex | PySymType) -> Tensor: + r""" + multiply(value) -> Tensor + + See :func:`torch.multiply`. + """ + + @overload + def multiply_(self, other: Tensor) -> Tensor: + r""" + multiply_(value) -> Tensor + + In-place version of :meth:`~Tensor.multiply`. + """ + + @overload + def multiply_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + multiply_(value) -> Tensor + + In-place version of :meth:`~Tensor.multiply`. + """ + + def mv(self, vec: Tensor) -> Tensor: + r""" + mv(vec) -> Tensor + + See :func:`torch.mv` + """ + + def mvlgamma(self, p: _int) -> Tensor: + r""" + mvlgamma(p) -> Tensor + + See :func:`torch.mvlgamma` + """ + + def mvlgamma_(self, p: _int) -> Tensor: + r""" + mvlgamma_(p) -> Tensor + + In-place version of :meth:`~Tensor.mvlgamma` + """ + + def nan_to_num( + self, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, + ) -> Tensor: + r""" + nan_to_num(nan=0.0, posinf=None, neginf=None) -> Tensor + + See :func:`torch.nan_to_num`. + """ + + def nan_to_num_( + self, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, + ) -> Tensor: + r""" + nan_to_num_(nan=0.0, posinf=None, neginf=None) -> Tensor + + In-place version of :meth:`~Tensor.nan_to_num`. + """ + + def nanmean( + self, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + nanmean(dim=None, keepdim=False, *, dtype=None) -> Tensor + + See :func:`torch.nanmean` + """ + + @overload + def nanmedian(self) -> Tensor: + r""" + nanmedian(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.nanmedian` + """ + + @overload + def nanmedian( + self, + dim: _int, + keepdim: _bool = False, + ) -> torch.return_types.nanmedian: + r""" + nanmedian(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.nanmedian` + """ + + @overload + def nanquantile( + self, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + nanquantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.nanquantile` + """ + + @overload + def nanquantile( + self, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + nanquantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.nanquantile` + """ + + def nansum( + self, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + nansum(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.nansum` + """ + + @overload + def narrow(self, dim: _int, start: Tensor, length: _int | SymInt) -> Tensor: + r""" + narrow(dimension, start, length) -> Tensor + + See :func:`torch.narrow`. + """ + + @overload + def narrow( + self, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, + ) -> Tensor: + r""" + narrow(dimension, start, length) -> Tensor + + See :func:`torch.narrow`. + """ + + def narrow_copy( + self, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, + ) -> Tensor: + r""" + narrow_copy(dimension, start, length) -> Tensor + + See :func:`torch.narrow_copy`. + """ + + def ndimension(self) -> _int: + r""" + ndimension() -> int + + Alias for :meth:`~Tensor.dim()` + """ + + @overload + def ne(self, other: Tensor) -> Tensor: + r""" + ne(other) -> Tensor + + See :func:`torch.ne`. + """ + + @overload + def ne(self, other: Number | _complex | PySymType) -> Tensor: + r""" + ne(other) -> Tensor + + See :func:`torch.ne`. + """ + + @overload + def ne_(self, other: Tensor) -> Tensor: + r""" + ne_(other) -> Tensor + + In-place version of :meth:`~Tensor.ne`. + """ + + @overload + def ne_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + ne_(other) -> Tensor + + In-place version of :meth:`~Tensor.ne`. + """ + + def neg(self) -> Tensor: + r""" + neg() -> Tensor + + See :func:`torch.neg` + """ + + def neg_(self) -> Tensor: + r""" + neg_() -> Tensor + + In-place version of :meth:`~Tensor.neg` + """ + + def negative(self) -> Tensor: + r""" + negative() -> Tensor + + See :func:`torch.negative` + """ + + def negative_(self) -> Tensor: + r""" + negative_() -> Tensor + + In-place version of :meth:`~Tensor.negative` + """ + + def nelement(self) -> _int: + r""" + nelement() -> int + + Alias for :meth:`~Tensor.numel` + """ + + @overload + def new(cls, *args: Any, device: DeviceLikeType | None = None) -> Self: ... + @overload + def new(cls, storage: Storage) -> Self: ... + @overload + def new(cls, other: Tensor) -> Self: ... + @overload + def new(cls, size: _size, *, device: DeviceLikeType | None = None) -> Self: ... + @overload + def new_empty( + self, + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_empty(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with uninitialized data. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty((2, 3)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + """ + + @overload + def new_empty( + self, + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_empty(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with uninitialized data. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty((2, 3)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + """ + + def new_empty_strided( + self, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_empty_strided(size, stride, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` and strides :attr:`stride` filled with + uninitialized data. By default, the returned Tensor has the same + :class:`torch.dtype` and :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty_strided((2, 3), (3, 1)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + """ + + def new_full( + self, + size: Sequence[_int | SymInt], + fill_value: Number | _complex | PySymType, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_full(size, fill_value, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with :attr:`fill_value`. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + fill_value (scalar): the number to fill the output tensor with. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones((2,), dtype=torch.float64) + >>> tensor.new_full((3, 4), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416, 3.1416]], dtype=torch.float64) + """ + + @overload + def new_ones( + self, + size: _size, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, + ) -> Tensor: + r""" + new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``1``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + """ + + @overload + def new_ones( + self, + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``1``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + """ + + @overload + def new_ones( + self, + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``1``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + """ + + def new_tensor( + self, + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, + ) -> Tensor: + r""" + new_tensor(data, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a new Tensor with :attr:`data` as the tensor data. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + .. warning:: + + :func:`new_tensor` always copies :attr:`data`. If you have a Tensor + ``data`` and want to avoid a copy, use :func:`torch.Tensor.requires_grad_` + or :func:`torch.Tensor.detach`. + If you have a numpy array and want to avoid a copy, use + :func:`torch.from_numpy`. + + .. warning:: + + When data is a tensor `x`, :func:`new_tensor()` reads out 'the data' from whatever it is passed, + and constructs a leaf variable. Therefore ``tensor.new_tensor(x)`` is equivalent to ``x.detach().clone()`` + and ``tensor.new_tensor(x, requires_grad=True)`` is equivalent to ``x.detach().clone().requires_grad_(True)``. + The equivalents using ``detach()`` and ``clone()`` are recommended. + + Args: + data (array_like): The returned Tensor copies :attr:`data`. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones((2,), dtype=torch.int8) + >>> data = [[0, 1], [2, 3]] + >>> tensor.new_tensor(data) + tensor([[ 0, 1], + [ 2, 3]], dtype=torch.int8) + """ + + @overload + def new_zeros( + self, + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_zeros(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``0``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.float64) + >>> tensor.new_zeros((2, 3)) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]], dtype=torch.float64) + """ + + @overload + def new_zeros( + self, + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_zeros(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``0``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.float64) + >>> tensor.new_zeros((2, 3)) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]], dtype=torch.float64) + """ + + def nextafter(self, other: Tensor) -> Tensor: + r""" + nextafter(other) -> Tensor + See :func:`torch.nextafter` + """ + + def nextafter_(self, other: Tensor) -> Tensor: + r""" + nextafter_(other) -> Tensor + In-place version of :meth:`~Tensor.nextafter` + """ + + @overload + def nonzero(self, *, as_tuple: Literal[False] = False) -> Tensor: + r""" + nonzero() -> LongTensor + + See :func:`torch.nonzero` + """ + + @overload + def nonzero(self, *, as_tuple: Literal[True]) -> tuple[Tensor, ...]: + r""" + nonzero() -> LongTensor + + See :func:`torch.nonzero` + """ + + def nonzero_static( + self, + *, + size: _int | SymInt, + fill_value: _int = -1, + ) -> Tensor: + r""" + nonzero_static(*, size, fill_value=-1) -> LongTensor + + See :func:`torch.nonzero_static` + """ + + def normal_( + self, + mean: _float = 0, + std: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + normal_(mean=0, std=1, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with elements samples from the normal distribution + parameterized by :attr:`mean` and :attr:`std`. + """ + + @overload + def not_equal(self, other: Tensor) -> Tensor: + r""" + not_equal(other) -> Tensor + + See :func:`torch.not_equal`. + """ + + @overload + def not_equal(self, other: Number | _complex | PySymType) -> Tensor: + r""" + not_equal(other) -> Tensor + + See :func:`torch.not_equal`. + """ + + @overload + def not_equal_(self, other: Tensor) -> Tensor: + r""" + not_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.not_equal`. + """ + + @overload + def not_equal_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + not_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.not_equal`. + """ + + def numel(self) -> _int: + r""" + numel() -> int + + See :func:`torch.numel` + """ + + def numpy(self, *, force: _bool = False) -> numpy.ndarray: + r""" + numpy(*, force=False) -> numpy.ndarray + + Returns the tensor as a NumPy :class:`ndarray`. + + If :attr:`force` is ``False`` (the default), the conversion + is performed only if the tensor is on the CPU, does not require grad, + does not have its conjugate bit set, and is a dtype and layout that + NumPy supports. The returned ndarray and the tensor will share their + storage, so changes to the tensor will be reflected in the ndarray + and vice versa. + + If :attr:`force` is ``True`` this is equivalent to + calling ``t.detach().cpu().resolve_conj().resolve_neg().numpy()``. + If the tensor isn't on the CPU or the conjugate or negative bit is set, + the tensor won't share its storage with the returned ndarray. + Setting :attr:`force` to ``True`` can be a useful shorthand. + + Args: + force (bool): if ``True``, the ndarray may be a copy of the tensor + instead of always sharing memory, defaults to ``False``. + """ + + def orgqr(self, input2: Tensor) -> Tensor: + r""" + orgqr(input2) -> Tensor + + See :func:`torch.orgqr` + """ + + def ormqr( + self, + input2: Tensor, + input3: Tensor, + left: _bool = True, + transpose: _bool = False, + ) -> Tensor: + r""" + ormqr(input2, input3, left=True, transpose=False) -> Tensor + + See :func:`torch.ormqr` + """ + + def outer(self, vec2: Tensor) -> Tensor: + r""" + outer(vec2) -> Tensor + + See :func:`torch.outer`. + """ + + @overload + def permute(self, dims: _size) -> Tensor: + r""" + permute(*dims) -> Tensor + + Returns a view of the tensor with its dimensions permuted. + + Args: + dims (torch.Size, int..., tuple of int or list of int): the desired ordering of dimensions. + + Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> x.permute(2, 0, 1).size() + torch.Size([5, 2, 3]) + """ + + @overload + def permute(self, *dims: _int) -> Tensor: + r""" + permute(*dims) -> Tensor + + Returns a view of the tensor with its dimensions permuted. + + Args: + dims (torch.Size, int..., tuple of int or list of int): the desired ordering of dimensions. + + Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> x.permute(2, 0, 1).size() + torch.Size([5, 2, 3]) + """ + + def pin_memory(self, device: DeviceLikeType | None = None) -> Tensor: + r""" + pin_memory() -> Tensor + + Copies the tensor to pinned memory, if it's not already pinned. + By default, the device pinned memory on will be the current :ref:`accelerator`. + """ + + def pinverse(self, rcond: _float = 1e-15) -> Tensor: + r""" + pinverse() -> Tensor + + See :func:`torch.pinverse` + """ + + def polygamma(self, n: _int) -> Tensor: + r""" + polygamma(n) -> Tensor + + See :func:`torch.polygamma` + """ + + def polygamma_(self, n: _int) -> Tensor: + r""" + polygamma_(n) -> Tensor + + In-place version of :meth:`~Tensor.polygamma` + """ + + def positive(self) -> Tensor: + r""" + positive() -> Tensor + + See :func:`torch.positive` + """ + + @overload + def pow(self, exponent: Tensor) -> Tensor: + r""" + pow(exponent) -> Tensor + + See :func:`torch.pow` + """ + + @overload + def pow(self, exponent: Number | _complex | PySymType) -> Tensor: + r""" + pow(exponent) -> Tensor + + See :func:`torch.pow` + """ + + @overload + def pow_(self, exponent: Tensor) -> Tensor: + r""" + pow_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.pow` + """ + + @overload + def pow_(self, exponent: Number | _complex | PySymType) -> Tensor: + r""" + pow_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.pow` + """ + + def prelu(self, weight: Tensor) -> Tensor: ... + @overload + def prod(self, *, dtype: _dtype | None = None) -> Tensor: + r""" + prod(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.prod` + """ + + @overload + def prod( + self, + dim: _int, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + prod(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.prod` + """ + + def put( + self, + index: Tensor, + source: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + put(input, index, source, accumulate=False) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.put_`. + `input` corresponds to `self` in :meth:`torch.Tensor.put_`. + """ + + def put_( + self, + index: Tensor, + source: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + put_(index, source, accumulate=False) -> Tensor + + Copies the elements from :attr:`source` into the positions specified by + :attr:`index`. For the purpose of indexing, the :attr:`self` tensor is treated as if + it were a 1-D tensor. + + :attr:`index` and :attr:`source` need to have the same number of elements, but not necessarily + the same shape. + + If :attr:`accumulate` is ``True``, the elements in :attr:`source` are added to + :attr:`self`. If accumulate is ``False``, the behavior is undefined if :attr:`index` + contain duplicate elements. + + Args: + index (LongTensor): the indices into self + source (Tensor): the tensor containing values to copy from + accumulate (bool, optional): whether to accumulate into self. Default: ``False`` + + Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> src.put_(torch.tensor([1, 3]), torch.tensor([9, 10])) + tensor([[ 4, 9, 5], + [ 10, 7, 8]]) + """ + + def q_per_channel_axis(self) -> _int: + r""" + q_per_channel_axis() -> int + + Given a Tensor quantized by linear (affine) per-channel quantization, + returns the index of dimension on which per-channel quantization is applied. + """ + + def q_per_channel_scales(self) -> Tensor: + r""" + q_per_channel_scales() -> Tensor + + Given a Tensor quantized by linear (affine) per-channel quantization, + returns a Tensor of scales of the underlying quantizer. It has the number of + elements that matches the corresponding dimensions (from q_per_channel_axis) of + the tensor. + """ + + def q_per_channel_zero_points(self) -> Tensor: + r""" + q_per_channel_zero_points() -> Tensor + + Given a Tensor quantized by linear (affine) per-channel quantization, + returns a tensor of zero_points of the underlying quantizer. It has the number of + elements that matches the corresponding dimensions (from q_per_channel_axis) of + the tensor. + """ + + def q_scale(self) -> _float: + r""" + q_scale() -> float + + Given a Tensor quantized by linear(affine) quantization, + returns the scale of the underlying quantizer(). + """ + + def q_zero_point(self) -> _int: + r""" + q_zero_point() -> int + + Given a Tensor quantized by linear(affine) quantization, + returns the zero_point of the underlying quantizer(). + """ + + def qscheme(self) -> _qscheme: + r""" + qscheme() -> torch.qscheme + + Returns the quantization scheme of a given QTensor. + """ + + @overload + def quantile( + self, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + quantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.quantile` + """ + + @overload + def quantile( + self, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + quantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.quantile` + """ + + def rad2deg(self) -> Tensor: + r""" + rad2deg() -> Tensor + + See :func:`torch.rad2deg` + """ + + def rad2deg_(self) -> Tensor: + r""" + rad2deg_() -> Tensor + + In-place version of :meth:`~Tensor.rad2deg` + """ + + @overload + def random_(self, *, generator: Generator | None = None) -> Tensor: + r""" + random_(from=0, to=None, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the discrete uniform + distribution over ``[from, to - 1]``. If not specified, the values are usually + only bounded by :attr:`self` tensor's data type. However, for floating point + types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every + value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` + will be uniform in ``[0, 2^53]``. + """ + + @overload + def random_( + self, + from_: _int, + to: _int | None, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + random_(from=0, to=None, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the discrete uniform + distribution over ``[from, to - 1]``. If not specified, the values are usually + only bounded by :attr:`self` tensor's data type. However, for floating point + types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every + value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` + will be uniform in ``[0, 2^53]``. + """ + + @overload + def random_( + self, + to: _int, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + random_(from=0, to=None, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the discrete uniform + distribution over ``[from, to - 1]``. If not specified, the values are usually + only bounded by :attr:`self` tensor's data type. However, for floating point + types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every + value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` + will be uniform in ``[0, 2^53]``. + """ + + def ravel(self) -> Tensor: + r""" + ravel() -> Tensor + + see :func:`torch.ravel` + """ + + def reciprocal(self) -> Tensor: + r""" + reciprocal() -> Tensor + + See :func:`torch.reciprocal` + """ + + def reciprocal_(self) -> Tensor: + r""" + reciprocal_() -> Tensor + + In-place version of :meth:`~Tensor.reciprocal` + """ + + def record_stream(self, s: Stream) -> None: + r""" + record_stream(stream) + + Marks the tensor as having been used by this stream. When the tensor + is deallocated, ensure the tensor memory is not reused for another tensor + until all work queued on :attr:`stream` at the time of deallocation is + complete. + + .. note:: + + The caching allocator is aware of only the stream where a tensor was + allocated. Due to the awareness, it already correctly manages the life + cycle of tensors on only one stream. But if a tensor is used on a stream + different from the stream of origin, the allocator might reuse the memory + unexpectedly. Calling this method lets the allocator know which streams + have used the tensor. + + .. warning:: + + This method is most suitable for use cases where you are providing a + function that created a tensor on a side stream, and want users to be able + to make use of the tensor without having to think carefully about stream + safety when making use of them. These safety guarantees come at some + performance and predictability cost (analogous to the tradeoff between GC + and manual memory management), so if you are in a situation where + you manage the full lifetime of your tensors, you may consider instead + manually managing CUDA events so that calling this method is not necessary. + In particular, when you call this method, on later allocations the + allocator will poll the recorded stream to see if all operations have + completed yet; you can potentially race with side stream computation and + non-deterministically reuse or fail to reuse memory for an allocation. + + You can safely use tensors allocated on side streams without + :meth:`~Tensor.record_stream`; you must manually ensure that + any non-creation stream uses of a tensor are synced back to the creation + stream before you deallocate the tensor. As the CUDA caching allocator + guarantees that the memory will only be reused with the same creation stream, + this is sufficient to ensure that writes to future reallocations of the + memory will be delayed until non-creation stream uses are done. + (Counterintuitively, you may observe that on the CPU side we have already + reallocated the tensor, even though CUDA kernels on the old tensor are + still in progress. This is fine, because CUDA operations on the new + tensor will appropriately wait for the old operations to complete, as they + are all on the same stream.) + + Concretely, this looks like this:: + + with torch.cuda.stream(s0): + x = torch.zeros(N) + + s1.wait_stream(s0) + with torch.cuda.stream(s1): + y = some_comm_op(x) + + ... some compute on s0 ... + + # synchronize creation stream s0 to side stream s1 + # before deallocating x + s0.wait_stream(s1) + del x + + Note that some discretion is required when deciding when to perform + ``s0.wait_stream(s1)``. In particular, if we were to wait immediately + after ``some_comm_op``, there wouldn't be any point in having the side + stream; it would be equivalent to have run ``some_comm_op`` on ``s0``. + Instead, the synchronization must be placed at some appropriate, later + point in time where you expect the side stream ``s1`` to have finished + work. This location is typically identified via profiling, e.g., using + Chrome traces produced + :meth:`torch.autograd.profiler.profile.export_chrome_trace`. If you + place the wait too early, work on s0 will block until ``s1`` has finished, + preventing further overlapping of communication and computation. If you + place the wait too late, you will use more memory than is strictly + necessary (as you are keeping ``x`` live for longer.) For a concrete + example of how this guidance can be applied in practice, see this post: + `FSDP and CUDACachingAllocator + `_. + """ + + def relu(self) -> Tensor: ... + def relu_(self) -> Tensor: ... + @overload + def remainder(self, other: Tensor) -> Tensor: + r""" + remainder(divisor) -> Tensor + + See :func:`torch.remainder` + """ + + @overload + def remainder(self, other: Number | _complex | PySymType) -> Tensor: + r""" + remainder(divisor) -> Tensor + + See :func:`torch.remainder` + """ + + @overload + def remainder_(self, other: Tensor) -> Tensor: + r""" + remainder_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.remainder` + """ + + @overload + def remainder_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + remainder_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.remainder` + """ + + def renorm( + self, + p: Number | _complex | PySymType, + dim: _int, + maxnorm: Number | _complex | PySymType, + ) -> Tensor: + r""" + renorm(p, dim, maxnorm) -> Tensor + + See :func:`torch.renorm` + """ + + def renorm_( + self, + p: Number | _complex | PySymType, + dim: _int, + maxnorm: Number | _complex | PySymType, + ) -> Tensor: + r""" + renorm_(p, dim, maxnorm) -> Tensor + + In-place version of :meth:`~Tensor.renorm` + """ + + @overload + def repeat(self, repeats: Sequence[_int | SymInt]) -> Tensor: + r""" + repeat(*repeats) -> Tensor + + Repeats this tensor along the specified dimensions. + + Unlike :meth:`~Tensor.expand`, this function copies the tensor's data. + + .. warning:: + + :meth:`~Tensor.repeat` behaves differently from + `numpy.repeat `_, + but is more similar to + `numpy.tile `_. + For the operator similar to `numpy.repeat`, see :func:`torch.repeat_interleave`. + + Args: + repeat (torch.Size, int..., tuple of int or list of int): The number of times to repeat this tensor along each dimension + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat(4, 2) + tensor([[ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3]]) + >>> x.repeat(4, 2, 1).size() + torch.Size([4, 2, 3]) + """ + + @overload + def repeat(self, *repeats: _int | SymInt) -> Tensor: + r""" + repeat(*repeats) -> Tensor + + Repeats this tensor along the specified dimensions. + + Unlike :meth:`~Tensor.expand`, this function copies the tensor's data. + + .. warning:: + + :meth:`~Tensor.repeat` behaves differently from + `numpy.repeat `_, + but is more similar to + `numpy.tile `_. + For the operator similar to `numpy.repeat`, see :func:`torch.repeat_interleave`. + + Args: + repeat (torch.Size, int..., tuple of int or list of int): The number of times to repeat this tensor along each dimension + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat(4, 2) + tensor([[ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3]]) + >>> x.repeat(4, 2, 1).size() + torch.Size([4, 2, 3]) + """ + + @overload + def repeat_interleave( + self, + repeats: Tensor, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, + ) -> Tensor: + r""" + repeat_interleave(repeats, dim=None, *, output_size=None) -> Tensor + + See :func:`torch.repeat_interleave`. + """ + + @overload + def repeat_interleave( + self, + repeats: _int | SymInt, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, + ) -> Tensor: + r""" + repeat_interleave(repeats, dim=None, *, output_size=None) -> Tensor + + See :func:`torch.repeat_interleave`. + """ + + def requires_grad_(self, mode: _bool = True) -> Tensor: + r""" + requires_grad_(requires_grad=True) -> Tensor + + Change if autograd should record operations on this tensor: sets this tensor's + :attr:`requires_grad` attribute in-place. Returns this tensor. + + :func:`requires_grad_`'s main use case is to tell autograd to begin recording + operations on a Tensor ``tensor``. If ``tensor`` has ``requires_grad=False`` + (because it was obtained through a DataLoader, or required preprocessing or + initialization), ``tensor.requires_grad_()`` makes it so that autograd will + begin to record operations on ``tensor``. + + Args: + requires_grad (bool): If autograd should record operations on this tensor. + Default: ``True``. + + Example:: + + >>> # Let's say we want to preprocess some saved weights and use + >>> # the result as new weights. + >>> saved_weights = [0.1, 0.2, 0.3, 0.25] + >>> loaded_weights = torch.tensor(saved_weights) + >>> weights = preprocess(loaded_weights) # some function + >>> weights + tensor([-0.5503, 0.4926, -2.1158, -0.8303]) + + >>> # Now, start to record operations done to weights + >>> weights.requires_grad_() + >>> out = weights.pow(2).sum() + >>> out.backward() + >>> weights.grad + tensor([-1.1007, 0.9853, -4.2316, -1.6606]) + """ + + @overload + def reshape(self, shape: Sequence[_int | SymInt]) -> Tensor: + r""" + reshape(*shape) -> Tensor + + Returns a tensor with the same data and number of elements as :attr:`self` + but with the specified shape. This method returns a view if :attr:`shape` is + compatible with the current shape. See :meth:`torch.Tensor.view` on when it is + possible to return a view. + + See :func:`torch.reshape` + + Args: + shape (tuple of ints or int...): the desired shape + """ + + @overload + def reshape(self, *shape: _int | SymInt) -> Tensor: + r""" + reshape(*shape) -> Tensor + + Returns a tensor with the same data and number of elements as :attr:`self` + but with the specified shape. This method returns a view if :attr:`shape` is + compatible with the current shape. See :meth:`torch.Tensor.view` on when it is + possible to return a view. + + See :func:`torch.reshape` + + Args: + shape (tuple of ints or int...): the desired shape + """ + + def reshape_as(self, other: Tensor) -> Tensor: + r""" + reshape_as(other) -> Tensor + + Returns this tensor as the same shape as :attr:`other`. + ``self.reshape_as(other)`` is equivalent to ``self.reshape(other.sizes())``. + This method returns a view if ``other.sizes()`` is compatible with the current + shape. See :meth:`torch.Tensor.view` on when it is possible to return a view. + + Please see :meth:`reshape` for more information about ``reshape``. + + Args: + other (:class:`torch.Tensor`): The result tensor has the same shape + as :attr:`other`. + """ + + @overload + def resize_( + self, + size: Sequence[_int | SymInt], + *, + memory_format: memory_format | None = None, + ) -> Tensor: + r""" + resize_(*sizes, memory_format=torch.contiguous_format) -> Tensor + + Resizes :attr:`self` tensor to the specified size. If the number of elements is + larger than the current storage size, then the underlying storage is resized + to fit the new number of elements. If the number of elements is smaller, the + underlying storage is not changed. Existing elements are preserved but any new + memory is uninitialized. + + .. warning:: + + This is a low-level method. The storage is reinterpreted as C-contiguous, + ignoring the current strides (unless the target size equals the current + size, in which case the tensor is left unchanged). For most purposes, you + will instead want to use :meth:`~Tensor.view()`, which checks for + contiguity, or :meth:`~Tensor.reshape()`, which copies data if needed. To + change the size in-place with custom strides, see :meth:`~Tensor.set_()`. + + .. note:: + + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, new elements are initialized to prevent nondeterministic behavior + from using the result as an input to an operation. Floating point and + complex values are set to NaN, and integer values are set to the maximum + value. + + Args: + sizes (torch.Size or int...): the desired size + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``sizes``. + + Example:: + + >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]]) + >>> x.resize_(2, 2) + tensor([[ 1, 2], + [ 3, 4]]) + """ + + @overload + def resize_( + self, + *size: _int | SymInt, + memory_format: memory_format | None = None, + ) -> Tensor: + r""" + resize_(*sizes, memory_format=torch.contiguous_format) -> Tensor + + Resizes :attr:`self` tensor to the specified size. If the number of elements is + larger than the current storage size, then the underlying storage is resized + to fit the new number of elements. If the number of elements is smaller, the + underlying storage is not changed. Existing elements are preserved but any new + memory is uninitialized. + + .. warning:: + + This is a low-level method. The storage is reinterpreted as C-contiguous, + ignoring the current strides (unless the target size equals the current + size, in which case the tensor is left unchanged). For most purposes, you + will instead want to use :meth:`~Tensor.view()`, which checks for + contiguity, or :meth:`~Tensor.reshape()`, which copies data if needed. To + change the size in-place with custom strides, see :meth:`~Tensor.set_()`. + + .. note:: + + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, new elements are initialized to prevent nondeterministic behavior + from using the result as an input to an operation. Floating point and + complex values are set to NaN, and integer values are set to the maximum + value. + + Args: + sizes (torch.Size or int...): the desired size + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``sizes``. + + Example:: + + >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]]) + >>> x.resize_(2, 2) + tensor([[ 1, 2], + [ 3, 4]]) + """ + + def resize_as_( + self, + the_template: Tensor, + *, + memory_format: memory_format | None = None, + ) -> Tensor: + r""" + resize_as_(tensor, memory_format=torch.contiguous_format) -> Tensor + + Resizes the :attr:`self` tensor to be the same size as the specified + :attr:`tensor`. This is equivalent to ``self.resize_(tensor.size())``. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``tensor.size()``. + """ + + def resize_as_sparse_(self, the_template: Tensor) -> Tensor: ... + def resolve_conj(self) -> Tensor: + r""" + resolve_conj() -> Tensor + + See :func:`torch.resolve_conj` + """ + + def resolve_neg(self) -> Tensor: + r""" + resolve_neg() -> Tensor + + See :func:`torch.resolve_neg` + """ + + def retain_grad(self) -> None: + r""" + retain_grad() -> None + + Enables this Tensor to have their :attr:`grad` populated during + :func:`backward`. This is a no-op for leaf tensors. + """ + + def roll( + self, + shifts: _int | SymInt | Sequence[_int | SymInt], + dims: _int | _size = (), + ) -> Tensor: + r""" + roll(shifts, dims) -> Tensor + + See :func:`torch.roll` + """ + + def rot90(self, k: _int = 1, dims: _size = (0, 1)) -> Tensor: + r""" + rot90(k, dims) -> Tensor + + See :func:`torch.rot90` + """ + + @overload + def round(self) -> Tensor: + r""" + round(decimals=0) -> Tensor + + See :func:`torch.round` + """ + + @overload + def round(self, *, decimals: _int) -> Tensor: + r""" + round(decimals=0) -> Tensor + + See :func:`torch.round` + """ + + @overload + def round_(self) -> Tensor: + r""" + round_(decimals=0) -> Tensor + + In-place version of :meth:`~Tensor.round` + """ + + @overload + def round_(self, *, decimals: _int) -> Tensor: + r""" + round_(decimals=0) -> Tensor + + In-place version of :meth:`~Tensor.round` + """ + + def row_indices(self) -> Tensor: ... + def rsqrt(self) -> Tensor: + r""" + rsqrt() -> Tensor + + See :func:`torch.rsqrt` + """ + + def rsqrt_(self) -> Tensor: + r""" + rsqrt_() -> Tensor + + In-place version of :meth:`~Tensor.rsqrt` + """ + + @overload + def scatter(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: _int, + index: Tensor, + src: Tensor, + *, + reduce: str, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + *, + reduce: str, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter_(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + @overload + def scatter_( + self, + dim: _int, + index: Tensor, + src: Tensor, + *, + reduce: str, + ) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + @overload + def scatter_( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + *, + reduce: str, + ) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + @overload + def scatter_( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + def scatter_add(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter_add(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_add_` + """ + + def scatter_add_(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter_add_(dim, index, src) -> Tensor + + Adds all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor in a similar fashion as + :meth:`~torch.Tensor.scatter_`. For each value in :attr:`src`, it is added to + an index in :attr:`self` which is specified by its index in :attr:`src` + for ``dimension != dim`` and by the corresponding value in :attr:`index` for + ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + + :attr:`self`, :attr:`index` and :attr:`src` should have same number of + dimensions. It is also required that ``index.size(d) <= src.size(d)`` for all + dimensions ``d``, and that ``index.size(d) <= self.size(d)`` for all dimensions + ``d != dim``. Note that ``index`` and ``src`` do not broadcast. + When :attr:`index` is empty, we always return the original tensor + without further error checking. + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter and add, can be + either empty or of the same dimensionality as ``src``. When empty, the + operation returns ``self`` unchanged. + src (Tensor): the source elements to scatter and add + + Example:: + + >>> src = torch.ones((2, 5)) + >>> index = torch.tensor([[0, 1, 2, 0, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) + tensor([[1., 0., 0., 1., 1.], + [0., 1., 0., 0., 0.], + [0., 0., 1., 0., 0.]]) + >>> index = torch.tensor([[0, 1, 2, 0, 0], [0, 1, 2, 2, 2]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) + tensor([[2., 0., 0., 1., 1.], + [0., 2., 0., 0., 0.], + [0., 0., 2., 1., 1.]]) + """ + + def scatter_reduce( + self, + dim: _int, + index: Tensor, + src: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: + r""" + scatter_reduce(dim, index, src, reduce, *, include_self=True) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` + """ + + def scatter_reduce_( + self, + dim: _int, + index: Tensor, + src: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: + r""" + scatter_reduce_(dim, index, src, reduce, *, include_self=True) -> Tensor + + Reduces all values from the :attr:`src` tensor to the indices specified in + the :attr:`index` tensor in the :attr:`self` tensor using the applied reduction + defined via the :attr:`reduce` argument (:obj:`"sum"`, :obj:`"prod"`, :obj:`"mean"`, + :obj:`"amax"`, :obj:`"amin"`). For each value in :attr:`src`, it is reduced to an + index in :attr:`self` which is specified by its index in :attr:`src` for + ``dimension != dim`` and by the corresponding value in :attr:`index` for + ``dimension = dim``. If :obj:`include_self="True"`, the values in the :attr:`self` + tensor are included in the reduction. + + :attr:`self`, :attr:`index` and :attr:`src` should all have + the same number of dimensions. It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``index`` and ``src`` do not broadcast. + + For a 3-D tensor with :obj:`reduce="sum"` and :obj:`include_self=True` the + output is given as:: + + self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + .. warning:: + + This function is in beta and may change in the near future. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter and reduce. + src (Tensor): the source elements to scatter and reduce + reduce (str): the reduction operation to apply for non-unique indices + (:obj:`"sum"`, :obj:`"prod"`, :obj:`"mean"`, :obj:`"amax"`, :obj:`"amin"`) + include_self (bool): whether elements from the :attr:`self` tensor are + included in the reduction + + Example:: + + >>> src = torch.tensor([1., 2., 3., 4., 5., 6.]) + >>> index = torch.tensor([0, 1, 0, 1, 2, 1]) + >>> input = torch.tensor([1., 2., 3., 4.]) + >>> input.scatter_reduce(0, index, src, reduce="sum") + tensor([5., 14., 8., 4.]) + >>> input.scatter_reduce(0, index, src, reduce="sum", include_self=False) + tensor([4., 12., 5., 4.]) + >>> input2 = torch.tensor([5., 4., 3., 2.]) + >>> input2.scatter_reduce(0, index, src, reduce="amax") + tensor([5., 6., 5., 2.]) + >>> input2.scatter_reduce(0, index, src, reduce="amax", include_self=False) + tensor([3., 6., 5., 2.]) + """ + + def select(self, dim: _int, index: _int | SymInt) -> Tensor: + r""" + select(dim, index) -> Tensor + + See :func:`torch.select` + """ + + def select_scatter( + self, + src: Tensor, + dim: _int, + index: _int | SymInt, + ) -> Tensor: + r""" + select_scatter(src, dim, index) -> Tensor + + See :func:`torch.select_scatter` + """ + + @overload + def set_( + self, + source: Storage | TypedStorage | UntypedStorage, + storage_offset: IntLikeType, + size: _symsize, + stride: _symsize, + ) -> Tensor: + r""" + set_(source=None, storage_offset=0, size=None, stride=None) -> Tensor + + Sets the underlying storage, size, and strides. If :attr:`source` is a tensor, + :attr:`self` tensor will share the same storage and have the same size and + strides as :attr:`source`. Changes to elements in one tensor will be reflected + in the other. + + If :attr:`source` is a :class:`~torch.Storage`, the method sets the underlying + storage, offset, size, and stride. + + Args: + source (Tensor or Storage): the tensor or storage to use + storage_offset (int, optional): the offset in the storage + size (torch.Size, optional): the desired size. Defaults to the size of the source. + stride (tuple, optional): the desired stride. Defaults to C-contiguous strides. + """ + + @overload + def set_(self, source: Storage | TypedStorage | UntypedStorage) -> Tensor: + r""" + set_(source=None, storage_offset=0, size=None, stride=None) -> Tensor + + Sets the underlying storage, size, and strides. If :attr:`source` is a tensor, + :attr:`self` tensor will share the same storage and have the same size and + strides as :attr:`source`. Changes to elements in one tensor will be reflected + in the other. + + If :attr:`source` is a :class:`~torch.Storage`, the method sets the underlying + storage, offset, size, and stride. + + Args: + source (Tensor or Storage): the tensor or storage to use + storage_offset (int, optional): the offset in the storage + size (torch.Size, optional): the desired size. Defaults to the size of the source. + stride (tuple, optional): the desired stride. Defaults to C-contiguous strides. + """ + + def sgn(self) -> Tensor: + r""" + sgn() -> Tensor + + See :func:`torch.sgn` + """ + + def sgn_(self) -> Tensor: + r""" + sgn_() -> Tensor + + In-place version of :meth:`~Tensor.sgn` + """ + + def short(self) -> Tensor: + r""" + short(memory_format=torch.preserve_format) -> Tensor + + ``self.short()`` is equivalent to ``self.to(torch.int16)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def sigmoid(self) -> Tensor: + r""" + sigmoid() -> Tensor + + See :func:`torch.sigmoid` + """ + + def sigmoid_(self) -> Tensor: + r""" + sigmoid_() -> Tensor + + In-place version of :meth:`~Tensor.sigmoid` + """ + + def sign(self) -> Tensor: + r""" + sign() -> Tensor + + See :func:`torch.sign` + """ + + def sign_(self) -> Tensor: + r""" + sign_() -> Tensor + + In-place version of :meth:`~Tensor.sign` + """ + + def signbit(self) -> Tensor: + r""" + signbit() -> Tensor + + See :func:`torch.signbit` + """ + + def sin(self) -> Tensor: + r""" + sin() -> Tensor + + See :func:`torch.sin` + """ + + def sin_(self) -> Tensor: + r""" + sin_() -> Tensor + + In-place version of :meth:`~Tensor.sin` + """ + + def sinc(self) -> Tensor: + r""" + sinc() -> Tensor + + See :func:`torch.sinc` + """ + + def sinc_(self) -> Tensor: + r""" + sinc_() -> Tensor + + In-place version of :meth:`~Tensor.sinc` + """ + + def sinh(self) -> Tensor: + r""" + sinh() -> Tensor + + See :func:`torch.sinh` + """ + + def sinh_(self) -> Tensor: + r""" + sinh_() -> Tensor + + In-place version of :meth:`~Tensor.sinh` + """ + + @overload + def size(self, dim: None = None) -> Size: + r""" + size(dim=None) -> torch.Size or int + + Returns the size of the :attr:`self` tensor. If ``dim`` is not specified, + the returned value is a :class:`torch.Size`, a subclass of :class:`tuple`. + If ``dim`` is specified, returns an int holding the size of that dimension. + + Args: + dim (int, optional): The dimension for which to retrieve the size. + + Example:: + + >>> t = torch.empty(3, 4, 5) + >>> t.size() + torch.Size([3, 4, 5]) + >>> t.size(dim=1) + 4 + """ + + @overload + def size(self, dim: _int) -> _int: + r""" + size(dim=None) -> torch.Size or int + + Returns the size of the :attr:`self` tensor. If ``dim`` is not specified, + the returned value is a :class:`torch.Size`, a subclass of :class:`tuple`. + If ``dim`` is specified, returns an int holding the size of that dimension. + + Args: + dim (int, optional): The dimension for which to retrieve the size. + + Example:: + + >>> t = torch.empty(3, 4, 5) + >>> t.size() + torch.Size([3, 4, 5]) + >>> t.size(dim=1) + 4 + """ + + def slice_inverse( + self, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + ) -> Tensor: ... + def slice_scatter( + self, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + ) -> Tensor: + r""" + slice_scatter(src, dim=0, start=None, end=None, step=1) -> Tensor + + See :func:`torch.slice_scatter` + """ + + def slogdet(self) -> torch.return_types.slogdet: + r""" + slogdet() -> (Tensor, Tensor) + + See :func:`torch.slogdet` + """ + + def smm(self, mat2: Tensor) -> Tensor: + r""" + smm(mat) -> Tensor + + See :func:`torch.smm` + """ + + def softmax(self, dim: _int, dtype: _dtype | None = None) -> Tensor: + r""" + softmax(dim) -> Tensor + + Alias for :func:`torch.nn.functional.softmax`. + """ + + @overload + def sort( + self, + *, + stable: _bool | None, + dim: _int = -1, + descending: _bool = False, + ) -> torch.return_types.sort: + r""" + sort(dim=-1, descending=False) -> (Tensor, LongTensor) + + See :func:`torch.sort` + """ + + @overload + def sort( + self, + dim: _int = -1, + descending: _bool = False, + ) -> torch.return_types.sort: + r""" + sort(dim=-1, descending=False) -> (Tensor, LongTensor) + + See :func:`torch.sort` + """ + + def sparse_dim(self) -> _int: + r""" + sparse_dim() -> int + + Return the number of sparse dimensions in a :ref:`sparse tensor ` :attr:`self`. + + .. note:: + Returns ``0`` if :attr:`self` is not a sparse tensor. + + See also :meth:`Tensor.dense_dim` and :ref:`hybrid tensors `. + """ + + def sparse_mask(self, mask: Tensor) -> Tensor: + r""" + sparse_mask(mask) -> Tensor + + Returns a new :ref:`sparse tensor ` with values from a + strided tensor :attr:`self` filtered by the indices of the sparse + tensor :attr:`mask`. The values of :attr:`mask` sparse tensor are + ignored. :attr:`self` and :attr:`mask` tensors must have the same + shape. + + .. note:: + + The returned sparse tensor might contain duplicate values if :attr:`mask` + is not coalesced. It is therefore advisable to pass ``mask.coalesce()`` + if such behavior is not desired. + + .. note:: + + The returned sparse tensor has the same indices as the sparse tensor + :attr:`mask`, even when the corresponding values in :attr:`self` are + zeros. + + Args: + mask (Tensor): a sparse tensor whose indices are used as a filter + + Example:: + + >>> nse = 5 + >>> dims = (5, 5, 2, 2) + >>> I = torch.cat([torch.randint(0, dims[0], size=(nse,)), + ... torch.randint(0, dims[1], size=(nse,))], 0).reshape(2, nse) + >>> V = torch.randn(nse, dims[2], dims[3]) + >>> S = torch.sparse_coo_tensor(I, V, dims).coalesce() + >>> D = torch.randn(dims) + >>> D.sparse_mask(S) + tensor(indices=tensor([[0, 0, 0, 2], + [0, 1, 4, 3]]), + values=tensor([[[ 1.6550, 0.2397], + [-0.1611, -0.0779]], + + [[ 0.2326, -1.0558], + [ 1.4711, 1.9678]], + + [[-0.5138, -0.0411], + [ 1.9417, 0.5158]], + + [[ 0.0793, 0.0036], + [-0.2569, -0.1055]]]), + size=(5, 5, 2, 2), nnz=4, layout=torch.sparse_coo) + """ + + def sparse_resize_( + self, + size: _size, + sparse_dim: _int, + dense_dim: _int, + ) -> Tensor: + r""" + sparse_resize_(size, sparse_dim, dense_dim) -> Tensor + + Resizes :attr:`self` :ref:`sparse tensor ` to the desired + size and the number of sparse and dense dimensions. + + .. note:: + If the number of specified elements in :attr:`self` is zero, then + :attr:`size`, :attr:`sparse_dim`, and :attr:`dense_dim` can be any + size and positive integers such that ``len(size) == sparse_dim + + dense_dim``. + + If :attr:`self` specifies one or more elements, however, then each + dimension in :attr:`size` must not be smaller than the corresponding + dimension of :attr:`self`, :attr:`sparse_dim` must equal the number + of sparse dimensions in :attr:`self`, and :attr:`dense_dim` must + equal the number of dense dimensions in :attr:`self`. + + .. warning:: + Throws an error if :attr:`self` is not a sparse tensor. + + Args: + size (torch.Size): the desired size. If :attr:`self` is non-empty + sparse tensor, the desired size cannot be smaller than the + original size. + sparse_dim (int): the number of sparse dimensions + dense_dim (int): the number of dense dimensions + """ + + def sparse_resize_and_clear_( + self, + size: _size, + sparse_dim: _int, + dense_dim: _int, + ) -> Tensor: + r""" + sparse_resize_and_clear_(size, sparse_dim, dense_dim) -> Tensor + + Removes all specified elements from a :ref:`sparse tensor + ` :attr:`self` and resizes :attr:`self` to the desired + size and the number of sparse and dense dimensions. + + .. warning: + Throws an error if :attr:`self` is not a sparse tensor. + + Args: + size (torch.Size): the desired size. + sparse_dim (int): the number of sparse dimensions + dense_dim (int): the number of dense dimensions + """ + + @overload + def split(self, split_size: _int, dim: _int = 0) -> Sequence[Tensor]: ... + @overload + def split( + self, + split_size: tuple[_int, ...], + dim: _int = 0, + ) -> Sequence[Tensor]: ... + def split_with_sizes( + self, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + ) -> tuple[Tensor, ...]: ... + def sqrt(self) -> Tensor: + r""" + sqrt() -> Tensor + + See :func:`torch.sqrt` + """ + + def sqrt_(self) -> Tensor: + r""" + sqrt_() -> Tensor + + In-place version of :meth:`~Tensor.sqrt` + """ + + def square(self) -> Tensor: + r""" + square() -> Tensor + + See :func:`torch.square` + """ + + def square_(self) -> Tensor: + r""" + square_() -> Tensor + + In-place version of :meth:`~Tensor.square` + """ + + @overload + def squeeze(self) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze(self, dim: _int) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze(self, dim: _size) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze(self, *dim: _int) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze_(self) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + @overload + def squeeze_(self, dim: _int) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + @overload + def squeeze_(self, dim: _size) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + @overload + def squeeze_(self, *dim: _int) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + def sspaddmm( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + sspaddmm(mat1, mat2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.sspaddmm` + """ + + @overload + def std( + self, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + ) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + @overload + def std( + self, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, + ) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + @overload + def std(self, unbiased: _bool = True) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + def untyped_storage(self) -> UntypedStorage: ... + def storage_offset(self) -> _int | SymInt: + r""" + storage_offset() -> int + + Returns :attr:`self` tensor's offset in the underlying storage in terms of + number of storage elements (not bytes). + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5]) + >>> x.storage_offset() + 0 + >>> x[3:].storage_offset() + 3 + """ + + def storage_type(self) -> Storage: ... + @overload + def stride(self, dim: None = None) -> tuple[_int, ...]: + r""" + stride(dim) -> tuple or int + + Returns the stride of :attr:`self` tensor. + + Stride is the jump necessary to go from one element to the next one in the + specified dimension :attr:`dim`. A tuple of all strides is returned when no + argument is passed in. Otherwise, an integer value is returned as the stride in + the particular dimension :attr:`dim`. + + Args: + dim (int, optional): the desired dimension in which stride is required + + Example:: + + >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + >>> x.stride() + (5, 1) + >>> x.stride(0) + 5 + >>> x.stride(-1) + 1 + """ + + @overload + def stride(self, dim: _int) -> _int: + r""" + stride(dim) -> tuple or int + + Returns the stride of :attr:`self` tensor. + + Stride is the jump necessary to go from one element to the next one in the + specified dimension :attr:`dim`. A tuple of all strides is returned when no + argument is passed in. Otherwise, an integer value is returned as the stride in + the particular dimension :attr:`dim`. + + Args: + dim (int, optional): the desired dimension in which stride is required + + Example:: + + >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + >>> x.stride() + (5, 1) + >>> x.stride(0) + 5 + >>> x.stride(-1) + 1 + """ + + def sub( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, + ) -> Tensor: + r""" + sub(other, *, alpha=1) -> Tensor + + See :func:`torch.sub`. + """ + + def sub_( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + ) -> Tensor: + r""" + sub_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.sub` + """ + + @overload + def subtract( + self, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + subtract(other, *, alpha=1) -> Tensor + + See :func:`torch.subtract`. + """ + + @overload + def subtract( + self, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + subtract(other, *, alpha=1) -> Tensor + + See :func:`torch.subtract`. + """ + + @overload + def subtract_( + self, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + subtract_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.subtract`. + """ + + @overload + def subtract_( + self, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + subtract_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.subtract`. + """ + + @overload + def sum(self, *, dtype: _dtype | None = None) -> Tensor: + r""" + sum(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.sum` + """ + + @overload + def sum( + self, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + sum(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.sum` + """ + + @overload + def sum_to_size(self, size: Sequence[_int | SymInt]) -> Tensor: + r""" + sum_to_size(*size) -> Tensor + + Sum ``this`` tensor to :attr:`size`. + :attr:`size` must be broadcastable to ``this`` tensor size. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + """ + + @overload + def sum_to_size(self, *size: _int | SymInt) -> Tensor: + r""" + sum_to_size(*size) -> Tensor + + Sum ``this`` tensor to :attr:`size`. + :attr:`size` must be broadcastable to ``this`` tensor size. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + """ + + def svd( + self, + some: _bool = True, + compute_uv: _bool = True, + ) -> torch.return_types.svd: + r""" + svd(some=True, compute_uv=True) -> (Tensor, Tensor, Tensor) + + See :func:`torch.svd` + """ + + def swapaxes(self, axis0: _int, axis1: _int) -> Tensor: + r""" + swapaxes(axis0, axis1) -> Tensor + + See :func:`torch.swapaxes` + """ + + def swapaxes_(self, axis0: _int, axis1: _int) -> Tensor: + r""" + swapaxes_(axis0, axis1) -> Tensor + + In-place version of :meth:`~Tensor.swapaxes` + """ + + def swapdims(self, dim0: _int, dim1: _int) -> Tensor: + r""" + swapdims(dim0, dim1) -> Tensor + + See :func:`torch.swapdims` + """ + + def swapdims_(self, dim0: _int, dim1: _int) -> Tensor: + r""" + swapdims_(dim0, dim1) -> Tensor + + In-place version of :meth:`~Tensor.swapdims` + """ + + def t(self) -> Tensor: + r""" + t() -> Tensor + + See :func:`torch.t` + """ + + def t_(self) -> Tensor: + r""" + t_() -> Tensor + + In-place version of :meth:`~Tensor.t` + """ + + def take(self, index: Tensor) -> Tensor: + r""" + take(indices) -> Tensor + + See :func:`torch.take` + """ + + def take_along_dim( + self, + indices: Tensor, + dim: _int | None = None, + ) -> Tensor: + r""" + take_along_dim(indices, dim) -> Tensor + + See :func:`torch.take_along_dim` + """ + + def tan(self) -> Tensor: + r""" + tan() -> Tensor + + See :func:`torch.tan` + """ + + def tan_(self) -> Tensor: + r""" + tan_() -> Tensor + + In-place version of :meth:`~Tensor.tan` + """ + + def tanh(self) -> Tensor: + r""" + tanh() -> Tensor + + See :func:`torch.tanh` + """ + + def tanh_(self) -> Tensor: + r""" + tanh_() -> Tensor + + In-place version of :meth:`~Tensor.tanh` + """ + + @overload + def tensor_split( + self, + indices: Sequence[_int | SymInt], + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + tensor_split(indices_or_sections, dim=0) -> List of Tensors + + See :func:`torch.tensor_split` + """ + + @overload + def tensor_split( + self, + tensor_indices_or_sections: Tensor, + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + tensor_split(indices_or_sections, dim=0) -> List of Tensors + + See :func:`torch.tensor_split` + """ + + @overload + def tensor_split( + self, + sections: _int | SymInt, + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + tensor_split(indices_or_sections, dim=0) -> List of Tensors + + See :func:`torch.tensor_split` + """ + + @overload + def tile(self, dims: Sequence[_int | SymInt]) -> Tensor: + r""" + tile(dims) -> Tensor + + See :func:`torch.tile` + """ + + @overload + def tile(self, *dims: _int | SymInt) -> Tensor: + r""" + tile(dims) -> Tensor + + See :func:`torch.tile` + """ + + @overload + def to( + self, + dtype: _dtype, + non_blocking: _bool = False, + copy: _bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> Tensor: + r""" + to(*args, **kwargs) -> Tensor + + Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are + inferred from the arguments of ``self.to(*args, **kwargs)``. + + .. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + + .. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + + Here are the ways to call ``to``: + + .. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + + .. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + .. note:: + + When :attr:`non_blocking` is ``True`` and the conversion is issued on + a non-default CUDA stream, the caller is responsible for proper + cross-stream synchronization. See :ref:`cuda-stream-semantics` for + the required pattern. + + Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + """ + + @overload + def to( + self, + device: DeviceLikeType | None = None, + dtype: _dtype | None = None, + non_blocking: _bool = False, + copy: _bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> Tensor: + r""" + to(*args, **kwargs) -> Tensor + + Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are + inferred from the arguments of ``self.to(*args, **kwargs)``. + + .. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + + .. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + + Here are the ways to call ``to``: + + .. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + + .. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + .. note:: + + When :attr:`non_blocking` is ``True`` and the conversion is issued on + a non-default CUDA stream, the caller is responsible for proper + cross-stream synchronization. See :ref:`cuda-stream-semantics` for + the required pattern. + + Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + """ + + @overload + def to( + self, + other: Tensor, + non_blocking: _bool = False, + copy: _bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> Tensor: + r""" + to(*args, **kwargs) -> Tensor + + Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are + inferred from the arguments of ``self.to(*args, **kwargs)``. + + .. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + + .. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + + Here are the ways to call ``to``: + + .. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + + .. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + .. note:: + + When :attr:`non_blocking` is ``True`` and the conversion is issued on + a non-default CUDA stream, the caller is responsible for proper + cross-stream synchronization. See :ref:`cuda-stream-semantics` for + the required pattern. + + Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + """ + + def to_dense( + self, + dtype: _dtype | None = None, + *, + masked_grad: _bool | None = None, + ) -> Tensor: + r""" + to_dense(dtype=None, *, masked_grad=True) -> Tensor + + Creates a strided copy of :attr:`self` if :attr:`self` is not a strided tensor, otherwise returns :attr:`self`. + + Keyword args: + {dtype} + masked_grad (bool, optional): If set to ``True`` (default) and + :attr:`self` has a sparse layout then the backward of + :meth:`to_dense` returns ``grad.sparse_mask(self)``. + + Example:: + + >>> s = torch.sparse_coo_tensor( + ... torch.tensor([[1, 1], + ... [0, 2]]), + ... torch.tensor([9, 10]), + ... size=(3, 3)) + >>> s.to_dense() + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + """ + + def to_mkldnn(self, dtype: _dtype | None = None) -> Tensor: + r""" + to_mkldnn() -> Tensor + Returns a copy of the tensor in ``torch.mkldnn`` layout. + """ + + def to_padded_tensor( + self, + padding: _float, + output_size: Sequence[_int | SymInt] | None = None, + ) -> Tensor: + r""" + to_padded_tensor(padding, output_size=None) -> Tensor + See :func:`to_padded_tensor` + """ + + @overload + def to_sparse( + self, + *, + layout: _layout | None = None, + blocksize: _int | _size | None = None, + dense_dim: _int | None = None, + ) -> Tensor: + r""" + to_sparse(sparseDims) -> Tensor + + Returns a sparse copy of the tensor. PyTorch supports sparse tensors in + :ref:`coordinate format `. + + Args: + sparseDims (int, optional): the number of sparse dimensions to include in the new sparse tensor + + Example:: + + >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]]) + >>> d + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + >>> d.to_sparse() + tensor(indices=tensor([[1, 1], + [0, 2]]), + values=tensor([ 9, 10]), + size=(3, 3), nnz=2, layout=torch.sparse_coo) + >>> d.to_sparse(1) + tensor(indices=tensor([[1]]), + values=tensor([[ 9, 0, 10]]), + size=(3, 3), nnz=1, layout=torch.sparse_coo) + + .. method:: to_sparse(*, layout=None, blocksize=None, dense_dim=None) -> Tensor + :noindex: + + Returns a sparse tensor with the specified layout and blocksize. If + the :attr:`self` is strided, the number of dense dimensions could be + specified, and a hybrid sparse tensor will be created, with + `dense_dim` dense dimensions and `self.dim() - 2 - dense_dim` batch + dimension. + + .. note:: If the :attr:`self` layout and blocksize parameters match + with the specified layout and blocksize, return + :attr:`self`. Otherwise, return a sparse tensor copy of + :attr:`self`. + + Args: + + layout (:class:`torch.layout`, optional): The desired sparse + layout. One of ``torch.sparse_coo``, ``torch.sparse_csr``, + ``torch.sparse_csc``, ``torch.sparse_bsr``, or + ``torch.sparse_bsc``. Default: if ``None``, + ``torch.sparse_coo``. + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR or BSC tensor. For other layouts, + specifying the block size that is not ``None`` will result in a + RuntimeError exception. A block size must be a tuple of length + two such that its items evenly divide the two sparse dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR, CSC, BSR or BSC tensor. This argument should be + used only if :attr:`self` is a strided tensor, and must be a + value between 0 and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> x = torch.tensor([[1, 0], [0, 0], [2, 3]]) + >>> x.to_sparse(layout=torch.sparse_coo) + tensor(indices=tensor([[0, 2, 2], + [0, 0, 1]]), + values=tensor([1, 2, 3]), + size=(3, 2), nnz=3, layout=torch.sparse_coo) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(1, 2)) + tensor(crow_indices=tensor([0, 1, 1, 2]), + col_indices=tensor([0, 0]), + values=tensor([[[1, 0]], + [[2, 3]]]), size=(3, 2), nnz=2, layout=torch.sparse_bsr) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(2, 1)) + RuntimeError: Tensor size(-2) 3 needs to be divisible by blocksize[0] 2 + >>> x.to_sparse(layout=torch.sparse_csr, blocksize=(3, 1)) + RuntimeError: to_sparse for Strided to SparseCsr conversion does not use specified blocksize + + >>> x = torch.tensor([[[1], [0]], [[0], [0]], [[2], [3]]]) + >>> x.to_sparse(layout=torch.sparse_csr, dense_dim=1) + tensor(crow_indices=tensor([0, 1, 1, 3]), + col_indices=tensor([0, 0, 1]), + values=tensor([[1], + [2], + [3]]), size=(3, 2, 1), nnz=3, layout=torch.sparse_csr) + """ + + @overload + def to_sparse(self, sparse_dim: _int) -> Tensor: + r""" + to_sparse(sparseDims) -> Tensor + + Returns a sparse copy of the tensor. PyTorch supports sparse tensors in + :ref:`coordinate format `. + + Args: + sparseDims (int, optional): the number of sparse dimensions to include in the new sparse tensor + + Example:: + + >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]]) + >>> d + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + >>> d.to_sparse() + tensor(indices=tensor([[1, 1], + [0, 2]]), + values=tensor([ 9, 10]), + size=(3, 3), nnz=2, layout=torch.sparse_coo) + >>> d.to_sparse(1) + tensor(indices=tensor([[1]]), + values=tensor([[ 9, 0, 10]]), + size=(3, 3), nnz=1, layout=torch.sparse_coo) + + .. method:: to_sparse(*, layout=None, blocksize=None, dense_dim=None) -> Tensor + :noindex: + + Returns a sparse tensor with the specified layout and blocksize. If + the :attr:`self` is strided, the number of dense dimensions could be + specified, and a hybrid sparse tensor will be created, with + `dense_dim` dense dimensions and `self.dim() - 2 - dense_dim` batch + dimension. + + .. note:: If the :attr:`self` layout and blocksize parameters match + with the specified layout and blocksize, return + :attr:`self`. Otherwise, return a sparse tensor copy of + :attr:`self`. + + Args: + + layout (:class:`torch.layout`, optional): The desired sparse + layout. One of ``torch.sparse_coo``, ``torch.sparse_csr``, + ``torch.sparse_csc``, ``torch.sparse_bsr``, or + ``torch.sparse_bsc``. Default: if ``None``, + ``torch.sparse_coo``. + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR or BSC tensor. For other layouts, + specifying the block size that is not ``None`` will result in a + RuntimeError exception. A block size must be a tuple of length + two such that its items evenly divide the two sparse dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR, CSC, BSR or BSC tensor. This argument should be + used only if :attr:`self` is a strided tensor, and must be a + value between 0 and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> x = torch.tensor([[1, 0], [0, 0], [2, 3]]) + >>> x.to_sparse(layout=torch.sparse_coo) + tensor(indices=tensor([[0, 2, 2], + [0, 0, 1]]), + values=tensor([1, 2, 3]), + size=(3, 2), nnz=3, layout=torch.sparse_coo) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(1, 2)) + tensor(crow_indices=tensor([0, 1, 1, 2]), + col_indices=tensor([0, 0]), + values=tensor([[[1, 0]], + [[2, 3]]]), size=(3, 2), nnz=2, layout=torch.sparse_bsr) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(2, 1)) + RuntimeError: Tensor size(-2) 3 needs to be divisible by blocksize[0] 2 + >>> x.to_sparse(layout=torch.sparse_csr, blocksize=(3, 1)) + RuntimeError: to_sparse for Strided to SparseCsr conversion does not use specified blocksize + + >>> x = torch.tensor([[[1], [0]], [[0], [0]], [[2], [3]]]) + >>> x.to_sparse(layout=torch.sparse_csr, dense_dim=1) + tensor(crow_indices=tensor([0, 1, 1, 3]), + col_indices=tensor([0, 0, 1]), + values=tensor([[1], + [2], + [3]]), size=(3, 2, 1), nnz=3, layout=torch.sparse_csr) + """ + + def to_sparse_bsc( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: + r""" + to_sparse_bsc(blocksize, dense_dim) -> Tensor + + Convert a tensor to a block sparse column (BSC) storage format of + given blocksize. If the :attr:`self` is strided, then the number of + dense dimensions could be specified, and a hybrid BSC tensor will be + created, with `dense_dim` dense dimensions and `self.dim() - 2 - + dense_dim` batch dimension. + + Args: + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSC tensor. A block size must be a tuple of + length two such that its items evenly divide the two sparse + dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting BSC tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(10, 10) + >>> sparse = dense.to_sparse_csr() + >>> sparse_bsc = sparse.to_sparse_bsc((5, 5)) + >>> sparse_bsc.row_indices() + tensor([0, 1, 0, 1]) + + >>> dense = torch.zeros(4, 3, 1) + >>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1 + >>> dense.to_sparse_bsc((2, 1), 1) + tensor(ccol_indices=tensor([0, 1, 2, 3]), + row_indices=tensor([0, 1, 0]), + values=tensor([[[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]]]), size=(4, 3, 1), nnz=3, + layout=torch.sparse_bsc) + """ + + def to_sparse_bsr( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: + r""" + to_sparse_bsr(blocksize, dense_dim) -> Tensor + + Convert a tensor to a block sparse row (BSR) storage format of given + blocksize. If the :attr:`self` is strided, then the number of dense + dimensions could be specified, and a hybrid BSR tensor will be + created, with `dense_dim` dense dimensions and `self.dim() - 2 - + dense_dim` batch dimension. + + Args: + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR tensor. A block size must be a tuple of + length two such that its items evenly divide the two sparse + dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting BSR tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(10, 10) + >>> sparse = dense.to_sparse_csr() + >>> sparse_bsr = sparse.to_sparse_bsr((5, 5)) + >>> sparse_bsr.col_indices() + tensor([0, 1, 0, 1]) + + >>> dense = torch.zeros(4, 3, 1) + >>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1 + >>> dense.to_sparse_bsr((2, 1), 1) + tensor(crow_indices=tensor([0, 2, 3]), + col_indices=tensor([0, 2, 1]), + values=tensor([[[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]]]), size=(4, 3, 1), nnz=3, + layout=torch.sparse_bsr) + """ + + def to_sparse_csc(self, dense_dim: _int | None = None) -> Tensor: + r""" + to_sparse_csc() -> Tensor + + Convert a tensor to compressed column storage (CSC) format. Except + for strided tensors, only works with 2D tensors. If the :attr:`self` + is strided, then the number of dense dimensions could be specified, + and a hybrid CSC tensor will be created, with `dense_dim` dense + dimensions and `self.dim() - 2 - dense_dim` batch dimension. + + Args: + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSC tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_csc() + >>> sparse._nnz() + 25 + + >>> dense = torch.zeros(3, 3, 1, 1) + >>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1 + >>> dense.to_sparse_csc(dense_dim=2) + tensor(ccol_indices=tensor([0, 1, 2, 3]), + row_indices=tensor([0, 2, 1]), + values=tensor([[[1.]], + + [[1.]], + + [[1.]]]), size=(3, 3, 1, 1), nnz=3, + layout=torch.sparse_csc) + """ + + def to_sparse_csr(self, dense_dim: _int | None = None) -> Tensor: + r""" + to_sparse_csr(dense_dim=None) -> Tensor + + Convert a tensor to compressed row storage format (CSR). Except for + strided tensors, only works with 2D tensors. If the :attr:`self` is + strided, then the number of dense dimensions could be specified, and a + hybrid CSR tensor will be created, with `dense_dim` dense dimensions + and `self.dim() - 2 - dense_dim` batch dimension. + + Args: + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_csr() + >>> sparse._nnz() + 25 + + >>> dense = torch.zeros(3, 3, 1, 1) + >>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1 + >>> dense.to_sparse_csr(dense_dim=2) + tensor(crow_indices=tensor([0, 1, 2, 3]), + col_indices=tensor([0, 2, 1]), + values=tensor([[[1.]], + + [[1.]], + + [[1.]]]), size=(3, 3, 1, 1), nnz=3, + layout=torch.sparse_csr) + """ + + def tolist(self) -> list: + r""" + tolist() -> list or number + + Returns the tensor as a (nested) list. For scalars, a standard + Python number is returned, just like with :meth:`~Tensor.item`. + Tensors are automatically moved to the CPU first if necessary. + + This operation is not differentiable. + + Examples:: + + >>> a = torch.randn(2, 2) + >>> a.tolist() + [[0.012766935862600803, 0.5415473580360413], + [-0.08909505605697632, 0.7729271650314331]] + >>> a[0,0].tolist() + 0.012766935862600803 + """ + + def topk( + self, + k: _int | SymInt, + dim: _int = -1, + largest: _bool = True, + sorted: _bool = True, + ) -> torch.return_types.topk: + r""" + topk(k, dim=None, largest=True, sorted=True) -> (Tensor, LongTensor) + + See :func:`torch.topk` + """ + + def trace(self) -> Tensor: + r""" + trace() -> Tensor + + See :func:`torch.trace` + """ + + def transpose(self, dim0: _int, dim1: _int) -> Tensor: + r""" + transpose(dim0, dim1) -> Tensor + + See :func:`torch.transpose` + """ + + def transpose_(self, dim0: _int, dim1: _int) -> Tensor: + r""" + transpose_(dim0, dim1) -> Tensor + + In-place version of :meth:`~Tensor.transpose` + """ + + def triangular_solve( + self, + A: Tensor, + upper: _bool = True, + transpose: _bool = False, + unitriangular: _bool = False, + ) -> torch.return_types.triangular_solve: + r""" + triangular_solve(A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor) + + See :func:`torch.triangular_solve` + """ + + def tril(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + tril(diagonal=0) -> Tensor + + See :func:`torch.tril` + """ + + def tril_(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + tril_(diagonal=0) -> Tensor + + In-place version of :meth:`~Tensor.tril` + """ + + def triu(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + triu(diagonal=0) -> Tensor + + See :func:`torch.triu` + """ + + def triu_(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + triu_(diagonal=0) -> Tensor + + In-place version of :meth:`~Tensor.triu` + """ + + def true_divide( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + *, + out: Tensor | None = None, + ) -> Tensor: + r""" + true_divide(value) -> Tensor + + See :func:`torch.true_divide` + """ + + def true_divide_( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + ) -> Tensor: + r""" + true_divide_(value) -> Tensor + + In-place version of :meth:`~Tensor.true_divide_` + """ + + def trunc(self) -> Tensor: + r""" + trunc() -> Tensor + + See :func:`torch.trunc` + """ + + def trunc_(self) -> Tensor: + r""" + trunc_() -> Tensor + + In-place version of :meth:`~Tensor.trunc` + """ + + @overload + def type(self, dtype: None = None, non_blocking: _bool = False) -> str: + r""" + type(dtype=None, non_blocking=False, **kwargs) -> str or Tensor + Returns the type if `dtype` is not provided, else casts this object to + the specified type. + + If this is already of the correct type, no copy is performed and the + original object is returned. + + Args: + dtype (dtype or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. + """ + + @overload + def type(self, dtype: str | _dtype, non_blocking: _bool = False) -> Tensor: + r""" + type(dtype=None, non_blocking=False, **kwargs) -> str or Tensor + Returns the type if `dtype` is not provided, else casts this object to + the specified type. + + If this is already of the correct type, no copy is performed and the + original object is returned. + + Args: + dtype (dtype or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. + """ + + def type_as(self, other: Tensor) -> Tensor: + r""" + type_as(tensor) -> Tensor + + Returns this tensor cast to the type of the given tensor. + + This is a no-op if the tensor is already of the correct type. This is + equivalent to ``self.type(tensor.type())`` + + Args: + tensor (Tensor): the tensor which has the desired type + """ + + def unbind(self, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + unbind(dim=0) -> seq + + See :func:`torch.unbind` + """ + + def unflatten(self, dim: _int, sizes: Sequence[_int | SymInt]) -> Tensor: ... + def unfold(self, dimension: _int, size: _int, step: _int) -> Tensor: + r""" + unfold(dimension, size, step) -> Tensor + + Returns a view of the original tensor which contains all slices of size :attr:`size` from + :attr:`self` tensor in the dimension :attr:`dimension`. + + Step between two slices is given by :attr:`step`. + + If `sizedim` is the size of dimension :attr:`dimension` for :attr:`self`, the size of + dimension :attr:`dimension` in the returned tensor will be + `(sizedim - size) / step + 1`. + + An additional dimension of size :attr:`size` is appended in the returned tensor. + + Args: + dimension (int): dimension in which unfolding happens + size (int): the size of each slice that is unfolded + step (int): the step between each slice + + Example:: + + >>> x = torch.arange(1., 8) + >>> x + tensor([ 1., 2., 3., 4., 5., 6., 7.]) + >>> x.unfold(0, 2, 1) + tensor([[ 1., 2.], + [ 2., 3.], + [ 3., 4.], + [ 4., 5.], + [ 5., 6.], + [ 6., 7.]]) + >>> x.unfold(0, 2, 2) + tensor([[ 1., 2.], + [ 3., 4.], + [ 5., 6.]]) + """ + + def uniform_( + self, + from_: _float = 0, + to: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + uniform_(from=0, to=1, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the continuous uniform + distribution: + + .. math:: + f(x) = \dfrac{1}{\text{to} - \text{from}} + """ + + def unsafe_chunk(self, chunks: _int, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + unsafe_chunk(chunks, dim=0) -> List of Tensors + + See :func:`torch.unsafe_chunk` + """ + + def unsafe_split( + self, + split_size: _int | SymInt, + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + unsafe_split(split_size, dim=0) -> List of Tensors + + See :func:`torch.unsafe_split` + """ + + def unsafe_split_with_sizes( + self, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + ) -> tuple[Tensor, ...]: ... + def unsqueeze(self, dim: _int) -> Tensor: + r""" + unsqueeze(dim) -> Tensor + + See :func:`torch.unsqueeze` + """ + + def unsqueeze_(self, dim: _int) -> Tensor: + r""" + unsqueeze_(dim) -> Tensor + + In-place version of :meth:`~Tensor.unsqueeze` + """ + + def values(self) -> Tensor: + r""" + values() -> Tensor + + Return the values tensor of a :ref:`sparse COO tensor `. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + + See also :meth:`Tensor.indices`. + + .. note:: + This method can only be called on a coalesced sparse tensor. See + :meth:`Tensor.coalesce` for details. + """ + + @overload + def var( + self, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + ) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + @overload + def var( + self, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, + ) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + @overload + def var(self, unbiased: _bool = True) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + def vdot(self, other: Tensor) -> Tensor: + r""" + vdot(other) -> Tensor + + See :func:`torch.vdot` + """ + + @overload + def view(self, dtype: _dtype) -> Tensor: + r""" + view(*shape) -> Tensor + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`shape`. + + The returned tensor shares the same data and must have the same number + of elements, but may have a different size. For a tensor to be viewed, the new + view size must be compatible with its original size and stride, i.e., each new + view dimension must either be a subspace of an original dimension, or only span + across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following + contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + + .. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + + Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` + without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a + :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which + returns a view if the shapes are compatible, and copies (equivalent to calling + :meth:`contiguous`) otherwise. + + Args: + shape (torch.Size or int...): the desired size + + Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + + .. method:: view(dtype) -> Tensor + :noindex: + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`dtype`. + + If the element size of :attr:`dtype` is different than that of ``self.dtype``, + then the size of the last dimension of the output will be scaled + proportionally. For instance, if :attr:`dtype` element size is twice that of + ``self.dtype``, then each pair of elements in the last dimension of + :attr:`self` will be combined, and the size of the last dimension of the output + will be half that of :attr:`self`. If :attr:`dtype` element size is half that + of ``self.dtype``, then each element in the last dimension of :attr:`self` will + be split in two, and the size of the last dimension of the output will be + double that of :attr:`self`. For this to be possible, the following conditions + must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + + Additionally, if the element size of :attr:`dtype` is greater than that of + ``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + + If any of the above conditions are not met, an error is thrown. + + .. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + + Args: + dtype (:class:`torch.dtype`): the desired dtype + + Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) + """ + + @overload + def view(self, size: Sequence[_int | SymInt]) -> Tensor: + r""" + view(*shape) -> Tensor + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`shape`. + + The returned tensor shares the same data and must have the same number + of elements, but may have a different size. For a tensor to be viewed, the new + view size must be compatible with its original size and stride, i.e., each new + view dimension must either be a subspace of an original dimension, or only span + across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following + contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + + .. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + + Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` + without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a + :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which + returns a view if the shapes are compatible, and copies (equivalent to calling + :meth:`contiguous`) otherwise. + + Args: + shape (torch.Size or int...): the desired size + + Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + + .. method:: view(dtype) -> Tensor + :noindex: + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`dtype`. + + If the element size of :attr:`dtype` is different than that of ``self.dtype``, + then the size of the last dimension of the output will be scaled + proportionally. For instance, if :attr:`dtype` element size is twice that of + ``self.dtype``, then each pair of elements in the last dimension of + :attr:`self` will be combined, and the size of the last dimension of the output + will be half that of :attr:`self`. If :attr:`dtype` element size is half that + of ``self.dtype``, then each element in the last dimension of :attr:`self` will + be split in two, and the size of the last dimension of the output will be + double that of :attr:`self`. For this to be possible, the following conditions + must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + + Additionally, if the element size of :attr:`dtype` is greater than that of + ``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + + If any of the above conditions are not met, an error is thrown. + + .. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + + Args: + dtype (:class:`torch.dtype`): the desired dtype + + Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) + """ + + @overload + def view(self, *size: _int | SymInt) -> Tensor: + r""" + view(*shape) -> Tensor + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`shape`. + + The returned tensor shares the same data and must have the same number + of elements, but may have a different size. For a tensor to be viewed, the new + view size must be compatible with its original size and stride, i.e., each new + view dimension must either be a subspace of an original dimension, or only span + across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following + contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + + .. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + + Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` + without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a + :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which + returns a view if the shapes are compatible, and copies (equivalent to calling + :meth:`contiguous`) otherwise. + + Args: + shape (torch.Size or int...): the desired size + + Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + + .. method:: view(dtype) -> Tensor + :noindex: + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`dtype`. + + If the element size of :attr:`dtype` is different than that of ``self.dtype``, + then the size of the last dimension of the output will be scaled + proportionally. For instance, if :attr:`dtype` element size is twice that of + ``self.dtype``, then each pair of elements in the last dimension of + :attr:`self` will be combined, and the size of the last dimension of the output + will be half that of :attr:`self`. If :attr:`dtype` element size is half that + of ``self.dtype``, then each element in the last dimension of :attr:`self` will + be split in two, and the size of the last dimension of the output will be + double that of :attr:`self`. For this to be possible, the following conditions + must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + + Additionally, if the element size of :attr:`dtype` is greater than that of + ``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + + If any of the above conditions are not met, an error is thrown. + + .. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + + Args: + dtype (:class:`torch.dtype`): the desired dtype + + Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) + """ + + def view_as(self, other: Tensor) -> Tensor: + r""" + view_as(other) -> Tensor + + View this tensor as the same size as :attr:`other`. + ``self.view_as(other)`` is equivalent to ``self.view(other.size())``. + + Please see :meth:`~Tensor.view` for more information about ``view``. + + Args: + other (:class:`torch.Tensor`): The result tensor has the same size + as :attr:`other`. + """ + + @overload + def vsplit(self, sections: _int) -> tuple[Tensor, ...]: + r""" + vsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.vsplit` + """ + + @overload + def vsplit(self, indices: _size) -> tuple[Tensor, ...]: + r""" + vsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.vsplit` + """ + + @overload + def vsplit(self, *indices: _int) -> tuple[Tensor, ...]: + r""" + vsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.vsplit` + """ + + @overload + def where(self, condition: Tensor, other: Tensor) -> Tensor: + r""" + where(condition, y) -> Tensor + + ``self.where(condition, y)`` is equivalent to ``torch.where(condition, self, y)``. + See :func:`torch.where` + """ + + @overload + def where( + self, + condition: Tensor, + other: Number | _complex | PySymType, + ) -> Tensor: + r""" + where(condition, y) -> Tensor + + ``self.where(condition, y)`` is equivalent to ``torch.where(condition, self, y)``. + See :func:`torch.where` + """ + + @overload + def xlogy(self, other: Tensor) -> Tensor: + r""" + xlogy(other) -> Tensor + + See :func:`torch.xlogy` + """ + + @overload + def xlogy(self, other: Number | _complex | PySymType) -> Tensor: + r""" + xlogy(other) -> Tensor + + See :func:`torch.xlogy` + """ + + @overload + def xlogy_(self, other: Tensor) -> Tensor: + r""" + xlogy_(other) -> Tensor + + In-place version of :meth:`~Tensor.xlogy` + """ + + @overload + def xlogy_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + xlogy_(other) -> Tensor + + In-place version of :meth:`~Tensor.xlogy` + """ + + def xpu( + self, + device: _device | _int | str | None = None, + non_blocking: _bool = False, + memory_format: torch.memory_format = torch.preserve_format, + ) -> Tensor: + r""" + xpu(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of this object in XPU memory. + + If this object is already in XPU memory and on the correct device, + then no copy is performed and the original object is returned. + + Args: + device (:class:`torch.device`, optional): The destination XPU device. + Defaults to the current XPU device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def zero_(self) -> Tensor: + r""" + zero_() -> Tensor + + Fills :attr:`self` tensor with zeros. + """ + +_TensorBase = TensorBase + +def _DTensor_OpSchema_post_init(self: OpSchema) -> None: ... +def _DTensor_OpSchema_recompute_comparison_key(self: OpSchema) -> None: ... +def _DTensor_compute_global_tensor_info( + tensor: Tensor, mesh: DeviceMesh, placements: Sequence[Placement] +) -> tuple[list[_int], list[_int]]: ... +def _get_DTensor_sharding_propagator_cache_stats() -> tuple[_int, _int]: ... +def _clear_DTensor_sharding_propagator_cache() -> None: ... +def _reinit_DTensor_dispatch_logger() -> None: ... + +# Defined in torch/csrc/multiprocessing/init.cpp +def _multiprocessing_init() -> None: ... +def _set_thread_name(name: str) -> None: ... +def _get_thread_name() -> str: ... + +# Defined in torch/csrc/Module.cpp +def _accelerator_hooks_device_count() -> _int: ... +def _accelerator_hooks_set_current_device(device_index: _int) -> None: ... +def _accelerator_hooks_get_current_device() -> _int: ... +def _accelerator_hooks_exchange_device(device_index: _int) -> _int: ... +def _accelerator_hooks_maybe_exchange_device(device_index: _int) -> _int: ... +def _get_accelerator(check: _bool = False) -> _device: ... +def _storage_Use_Count(storage_ptr: _int) -> _int: ... +def _storage_throw_on_immutable_data_ptr(storage_ptr: _int) -> _bool: ... +def _storage_throw_on_mutable_data_ptr(storage_ptr: _int) -> _bool: ... +def _set_storage_data_ptr_access_error_msg(storage_ptr: _int, s: str) -> None: ... +def _clear_storage_data_ptr_access_error_msg(storage_ptr: _int) -> None: ... + +# Defined in torch/csrc/mtia/Module.cpp +def _mtia_init() -> None: ... +def _mtia_isBuilt() -> _bool: ... +def _mtia_isInBadFork() -> _bool: ... +def _mtia_deviceSynchronize() -> None: ... +def _mtia_getCurrentStream(device: _int) -> Stream: ... +def _mtia_getCurrentRawStream(device: _int) -> _int: ... +def _mtia_setCurrentStream(stream: Stream) -> None: ... +def _mtia_getDefaultStream(device: _int) -> Stream: ... +def _mtia_setStream(stream_id: _int, device_index: _int, device_type: _int) -> None: ... +def _mtia_memoryStats(device: _int) -> dict[str, Any]: ... +def _mtia_getDeviceCapability(device: _int) -> tuple[_int, _int]: ... +def _mtia_getDeviceProperties(device: _int) -> dict[str, Any]: ... +def _mtia_emptyCache() -> None: ... +def _mtia_recordMemoryHistory( + enabled: str | None, + stacks: str, + max_entries, +) -> None: ... +def _mtia_memorySnapshot() -> dict[str, Any]: ... +def _mtia_attachOutOfMemoryObserver( + observer: Callable[[_int, _int, _int, _int], None], +) -> None: ... +def _mtia_getDeviceCount() -> _int: ... +def _mtia_getDevice() -> _int: ... +def _mtia_setDevice(device: _int) -> None: ... +def _mtia_exchangeDevice(device: _int) -> _int: ... +def _mtia_maybeExchangeDevice(device: _int) -> _int: ... +def _mtia_resetPeakMemoryStats(device: _int) -> None: ... +def _mtia_graphPoolHandle() -> tuple[_int, _int]: ... + +# Defined in torch/csrc/mtia/Module.cpp +class _MTIAGraph: + def __new__(cls, keep_graph: _bool = ...) -> Self: ... + def capture_begin(self, pool: tuple[_int, _int]) -> None: ... + def capture_end(self) -> None: ... + def instantiate(self) -> None: ... + def replay(self) -> None: ... + def reset(self) -> None: ... + def pool(self) -> tuple[_int, _int]: ... + +# Defined in torch/csrc/mps/Module.cpp +def _mps_deviceSynchronize() -> None: ... +def _mps_get_core_count() -> _int: ... +def _mps_host_alias_storage(storage: UntypedStorage) -> UntypedStorage: ... +def _mps_get_default_generator() -> Generator: ... +def _mps_get_name() -> _str: ... +def _mps_emptyCache() -> None: ... +def _mps_setMemoryFraction(fraction: _float) -> None: ... +def _mps_currentAllocatedMemory() -> _int: ... +def _mps_driverAllocatedMemory() -> _int: ... +def _mps_recommendedMaxMemory() -> _int: ... +def _mps_is_available() -> _bool: ... +def _mps_is_on_macos_or_newer(major: _int, minor: _int) -> _bool: ... +def _mps_profilerStartTrace(mode: str, wait_until_completed: _bool) -> None: ... +def _mps_profilerStopTrace() -> None: ... +def _mps_acquireEvent(enable_timing: _bool) -> _int: ... +def _mps_releaseEvent(event_id: _int) -> None: ... +def _mps_recordEvent(event_id: _int) -> None: ... +def _mps_waitForEvent(event_id: _int) -> None: ... +def _mps_synchronizeEvent(event_id: _int) -> None: ... +def _mps_queryEvent(event_id: _int) -> _bool: ... +def _mps_elapsedTimeOfEvents(start_event_id: _int, end_event_id: _int) -> _float: ... +def _mps_isCaptureEnabled() -> _bool: ... +def _mps_isCapturing() -> _bool: ... +def _mps_startCapture(name: str) -> None: ... +def _mps_stopCapture() -> None: ... + +# Defined in torch/csrc/cuda/Module.cpp +def _cuda_getCurrentStream(device: _int) -> tuple: ... +def _cuda_getCurrentRawStream(device: _int) -> _int: ... +def _cuda_getDefaultStream(device: _int) -> tuple: ... +def _cuda_getStreamFromExternal(data_ptr: _int, device_index: _int) -> tuple: ... +def _cuda_getCurrentBlasHandle() -> _int: ... +def _cuda_getCurrentSolverHandle() -> _int: ... +def _cuda_clearCublasWorkspaces() -> None: ... +def _cuda_getCublasWorkspaceSize() -> _int: ... +def _cuda_setCublasWorkspaceSize(size: _int) -> None: ... +def _cuda_getCublasLtWorkspaceSize() -> _int: ... +def _cuda_setCublasLtWorkspaceSize(size: _int) -> None: ... +def _cuda_resetCublasWorkspaceSize() -> None: ... +def _cuda_resetCublasLtWorkspaceSize() -> None: ... +def _cudnn_clear_dropout_state() -> None: ... +def _cuda_setDevice(device: _int) -> None: ... +def _cuda_exchangeDevice(device: _int) -> _int: ... +def _cuda_maybeExchangeDevice(device: _int) -> _int: ... +def _cuda_getDevice() -> _int: ... +def _cuda_getDeviceCount() -> _int: ... +def _cuda_set_sync_debug_mode(warn_level: _int | str) -> None: ... +def _cuda_get_sync_debug_mode() -> _int: ... +def _cuda_sleep(cycles: _int) -> None: ... +def _cuda_synchronize() -> None: ... +def _cuda_ipc_collect() -> None: ... +def _cuda_getArchFlags() -> str | None: ... +def _cuda_init() -> None: ... +def _cuda_setStream(stream_id: _int, device_index: _int, device_type: _int) -> None: ... +def _cuda_getCompiledVersion() -> _int: ... +def _cuda_cudaHostAllocator() -> _int: ... +def _host_emptyCache() -> None: ... +def _cuda_cudaCachingAllocator_raw_alloc(size: _int, cuda_stream: _int) -> _int: ... +def _cuda_cudaCachingAllocator_raw_delete(ptr: _int) -> None: ... +def _cuda_cudaCachingAllocator_enable(val: _bool) -> None: ... +def _cuda_cudaCachingAllocator_is_enabled() -> _bool: ... +def _cuda_beginAllocateToPool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _cuda_beginAllocateCurrentThreadToPool( + device: _int, + mempool_id: tuple[_int, _int], +) -> None: ... +def _cuda_endAllocateToPool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _cuda_beginAllocateCurrentStreamToPool( + device: _int, + mempool_id: tuple[_int, _int], +) -> None: ... +def _cuda_releasePool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _cuda_checkPoolLiveAllocations( + device: _int, + mempool_id: tuple[_int, _int], + expected_live_allocations: set, +) -> _bool: ... +def _cuda_setCheckpointPoolState( + device: _int, + state: _cuda_CUDAAllocator_AllocatorState, + stale_storages: list[_int], + storages_to_add_deleters_to: list[_int], +) -> None: ... +def _cuda_getMemoryFraction(device: _int) -> _float: ... +def _cuda_setMemoryFraction(fraction: _float, device: _int) -> None: ... +def _cuda_emptyCache() -> None: ... +def _cuda_memoryStats(device: _int) -> dict[str, Any]: ... +def _cuda_resetAccumulatedMemoryStats(device: _int) -> None: ... +def _cuda_resetPeakMemoryStats(device: _int) -> None: ... +def _cuda_hostMemoryStats() -> dict[str, Any]: ... +def _cuda_resetAccumulatedHostMemoryStats() -> None: ... +def _cuda_resetPeakHostMemoryStats() -> None: ... +def _cuda_memorySnapshot( + mempool_id: tuple[_int, _int] | tuple[_int, _int, _bool] | None, +) -> dict[str, Any]: ... +def _cuda_memoryMetadataSupported() -> _bool: ... +def _cuda_setMemoryMetadata(metadata: str) -> None: ... +def _cuda_getMemoryMetadata() -> str: ... +def _cuda_annotateMemory(ptr: _int, metadata: str) -> None: ... +def _cuda_record_memory_history_legacy( + enabled: _bool, + record_context: _bool, + record_context_cpp: _bool, + alloc_trace_max_entries: _int, + alloc_trace_record_context: _bool, + clear_history: _bool, + compile_context: _bool, + global_record_annotations: _bool, + skip_actions: list[str], + record_pinned_host_memory: _bool, + record_cuda: _bool, +) -> None: ... +def _cuda_record_memory_history( + enabled: str | None, + context: str | None, + stacks: str, + max_entries: _int, + clear_history: _bool, + compile_context: _bool, + global_record_annotations: _bool, + skip_actions: list[str], + record_pinned_host_memory: _bool, + record_cuda: _bool, +) -> None: ... +def _cuda_allocationTraceback(data_ptr: _int) -> list[dict[str, Any]] | None: ... +def _cuda_isHistoryEnabled() -> _bool: ... +def _cuda_getAllocatorBackend() -> str: ... + +class _cuda_CUDAAllocator_AllocatorState: ... + +def _cuda_getCheckpointState( + device: _int, + mempool: tuple[_int, _int], +) -> _cuda_CUDAAllocator_AllocatorState: ... +def _set_cached_tensors_enabled(enabled: _bool) -> None: ... +def _add_cached_tensor(t: Tensor) -> None: ... +def _remove_cached_tensor(t: Tensor) -> None: ... +def _is_fake_tensor(t: Tensor) -> _bool: ... +def _tensors_data_ptrs_at_indices_equal( + tensors: list[Tensor | _int], + ptrs: list[_int | None], + indices: list[_int], +) -> _bool: ... +def _construct_CUDA_Tensor_From_Storage_And_Metadata( + metadata: dict, + storage: Storage, +) -> Tensor: ... +def _set_storage_access_error_msg(t: Tensor, s: str) -> None: ... +def _free_And_Remove_DeleterFn(storage_ptr: _int) -> None: ... +def _has_Standard_Deleter(storage_ptr: _int) -> _bool: ... + +class _cuda_CUDAAllocator: ... + +def _cuda_customAllocator(alloc_fn: _int, free_fn: _int) -> _cuda_CUDAAllocator: ... +def _cuda_changeCurrentAllocator(allocator: _cuda_CUDAAllocator) -> None: ... +def _cuda_getAllocator() -> _cuda_CUDAAllocator: ... +def _cuda_canDeviceAccessPeer(device: _int, peer_device: _int) -> _bool: ... +def _cuda_jiterator_compile_and_launch_kernel( + code_string: str, + kernel_name: str, + return_by_ref: _bool, + num_outputs: _int, + tensors: tuple, + kwargs: dict[str, _int | _float | _bool], +) -> Tensor: ... +def _cuda_get_cudnn_benchmark_limit() -> _int: ... +def _cuda_set_cudnn_benchmark_limit(arg: _int) -> None: ... +def _cuda_get_conv_benchmark_empty_cache() -> _bool: ... +def _cudnn_set_conv_benchmark_empty_cache(enable: _bool) -> None: ... +def _nccl_version() -> _int: ... +def _nccl_version_suffix() -> bytes: ... +def _nccl_unique_id() -> bytes: ... +def _nccl_init_rank(nranks: _int, comm_id: bytes, rank: _int) -> object: ... +def _nccl_reduce( + input: Sequence[Tensor], + output: Tensor, + root: _int, + op: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_all_reduce( + input: Sequence[Tensor], + output: Sequence[Tensor], + op: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_broadcast( + input: Sequence[Tensor], + root: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_all_gather( + input: Sequence[Tensor], + output: Sequence[Tensor], + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_reduce_scatter( + input: Sequence[Tensor], + output: Sequence[Tensor], + op: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _rocm_is_backward_pass() -> _bool: ... +def _cuda_tunableop_enable(val: _bool) -> None: ... +def _cuda_tunableop_is_enabled() -> _bool: ... +def _cuda_tunableop_tuning_enable(val: _bool) -> None: ... +def _cuda_tunableop_tuning_is_enabled() -> _bool: ... +def _cuda_tunableop_set_max_tuning_duration(duration: _int) -> None: ... +def _cuda_tunableop_get_max_tuning_duration() -> _int: ... +def _cuda_tunableop_set_max_tuning_iterations(iterations: _int) -> None: ... +def _cuda_tunableop_get_max_tuning_iterations() -> _int: ... +def _cuda_tunableop_set_filename( + filename: str, + insert_device_ordinal: _bool | None, +) -> None: ... +def _cuda_tunableop_get_filename() -> str: ... +def _cuda_tunableop_read_file(filename: str | None) -> _bool: ... +def _cuda_tunableop_get_results() -> tuple[str, str, str, _float]: ... +def _cuda_tunableop_get_validators() -> tuple[str, str]: ... +def _cuda_tunableop_set_rotating_buffer_size(buffer_size: _int) -> None: ... +def _cuda_tunableop_get_rotation_buffer_size() -> _int: ... +def _cuda_tunableop_set_numerical_check_tolerances( + enabled: _bool, atol: _float = 1e-5, rtol: _float = 1e-5 +) -> None: ... + +class _CudaDeviceProperties: + name: str + major: _int + minor: _int + multi_processor_count: _int + total_memory: _int + is_integrated: _int + is_multi_gpu_board: _int + max_threads_per_multi_processor: _int + gcnArchName: str + warp_size: _int + uuid: str + L2_cache_size: _int + clock_rate: _int + memory_clock_rate: _int + memory_bus_width: _int + shared_memory_per_block: _int + shared_memory_per_multiprocessor: _int + +# Functions related to SDPA +class _SDPAParams: + query: Tensor + key: Tensor + value: Tensor + attn_mask: Tensor | None + dropout: _float + is_causal: _bool + enable_gqa: _bool + def __init__( + self, + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None, + dropout: _float, + is_causal: _bool, + enable_gqa: _bool, + ) -> None: ... + +class _SDPBackend(Enum): + ERROR = -1 + MATH = 0 + FLASH_ATTENTION = 1 + EFFICIENT_ATTENTION = 2 + CUDNN_ATTENTION = 3 + OVERRIDEABLE = 4 + +def _is_flash_attention_available() -> _bool: ... +def _can_use_cudnn_attention(params: _SDPAParams, debug: _bool) -> _bool: ... +def _can_use_flash_attention(params: _SDPAParams, debug: _bool) -> _bool: ... +def _can_use_mem_efficient_attention(params: _SDPAParams, debug: _bool) -> _bool: ... +def _is_ck_sdpa_available() -> _bool: ... + +# TensorIterator build pipeline (see torch._tensor_iterator). +class _TensorIteratorSpec: + def __init__(self) -> None: ... + outputs: list[Tensor | None] + inputs: list[Tensor] + const_inputs: list[Tensor] + check_all_same_dtype: _bool + check_all_same_device: _bool + promote_inputs_to_common_dtype: _bool + promote_integer_inputs_to_float: _bool + cast_common_dtype_to_outputs: _bool + enforce_safe_casting_to_output: _bool + enforce_linear_iteration: _bool + resize_outputs: _bool + check_mem_overlap: _bool + allow_cpu_scalars: _bool + is_reduction: _bool + static_dtype: _dtype | None + static_device: _device | None + static_shape: list[_int] | None + squash_dims: list[_int] + def build(self) -> _TensorIterator: ... + +class _TensorIterator: + @property + def ndim(self) -> _int: ... + @property + def shape(self) -> memoryview: ... + @property + def numel(self) -> _int: ... + @property + def ntensors(self) -> _int: ... + @property + def ninputs(self) -> _int: ... + @property + def noutputs(self) -> _int: ... + @property + def is_contiguous(self) -> _bool: ... + @property + def is_trivial_1d(self) -> _bool: ... + @property + def common_dtype(self) -> _dtype | None: ... + def tensor(self, index: _int) -> Tensor: ... + def input(self, index: _int = 0) -> Tensor: ... + def output(self, index: _int = 0) -> Tensor: ... + def dtype(self, index: _int = 0) -> _dtype: ... + def device(self, index: _int = 0) -> _device: ... + def strides(self, index: _int) -> memoryview: ... + def element_strides(self, index: _int) -> tuple[_int, ...]: ... + def __repr__(self) -> str: ... + +# Defined in torch/csrc/cuda/GdsFile.cpp +def _gds_register_buffer(t: Storage) -> None: ... +def _gds_deregister_buffer(t: Storage) -> None: ... +def _gds_register_handle(fd: _int) -> _int: ... +def _gds_deregister_handle(handle: _int) -> None: ... +def _gds_load_storage(handle: _int, s: Storage, offset: _int) -> None: ... +def _gds_save_storage(handle: _int, s: Storage, offset: _int) -> None: ... + +# Defined in torch/csrc/cuda/python_comm.cpp +def _broadcast(tensor: Tensor, devices: list[_int]) -> list[Tensor]: ... +def _broadcast_out(tensor: Tensor, out_tensors: list[Tensor]) -> list[Tensor]: ... +def _broadcast_coalesced( + tensors: list[Tensor], + devices: list[_int], + buffer_size: _int, +) -> list[list[Tensor]]: ... +def _scatter( + tensor: Tensor, + devices: list[_int], + chunk_sizes: list[_int] | None, + dim: _int, + streams: list[Stream] | None, +) -> list[Tensor]: ... +def _scatter_out( + tensor: Tensor, + out_tensors: list[Tensor], + dim: _int, + streams: list[Stream] | None, +) -> list[Tensor]: ... +def _gather( + tensors: list[Tensor], + dim: _int, + destination_index: _int | None, +) -> Tensor: ... +def _gather_out(tensors: list[Tensor], out_tensor: Tensor, dim: _int) -> Tensor: ... + +# Defined in torch/csrc/cuda/Stream.cpp +class _CudaStreamBase(Stream): + stream_id: _int + device_index: _int + device_type: _int + + device: _device + cuda_stream: _int + priority: _int + + def __new__( + cls, + priority: _int = 0, + stream_id: _int = 0, + device_index: _int = 0, + stream_ptr: _int = 0, + ) -> Self: ... + def query(self) -> _bool: ... + def synchronize(self) -> None: ... + def priority_range(self) -> tuple[_int, _int]: ... + +# Defined in torch/csrc/cuda/Event.cpp. At the Python C-API level +# ``THCPEventType.tp_base = THPEventClass`` (see Event.cpp), so this +# binding really does inherit from ``torch._C.Event``. Declaring the +# base here lets static checkers (pyrefly, mypy) see the relationship. +class _CudaEventBase(torch._C.Event): + device: _device + cuda_event: _int + + def __new__( + cls, + enable_timing: _bool = False, + blocking: _bool = False, + interprocess: _bool = False, + external: _bool = False, + ) -> Self: ... + @classmethod + def from_ipc_handle(cls, device: _device, ipc_handle: bytes) -> _CudaEventBase: ... + def record(self, stream: _CudaStreamBase | torch.Stream) -> None: ... + def wait(self, stream: _CudaStreamBase | torch.Stream) -> None: ... + def query(self) -> _bool: ... + def elapsed_time(self, other: _CudaEventBase) -> _float: ... + def synchronize(self) -> None: ... + def ipc_handle(self) -> bytes: ... + +# Defined in torch/csrc/cuda/Graph.cpp +class _CUDAGraph: + def __new__(cls, keep_graph: _bool = ...) -> Self: ... + def capture_begin( + self, + pool: _POOL_HANDLE | None = ..., + capture_error_mode: str = "global", + ) -> None: ... + def capture_end(self) -> None: ... + def capture_end_pre(self) -> None: ... + def capture_end_post(self) -> None: ... + def instantiate(self) -> None: ... + def register_generator_state(self, Generator) -> None: ... + def replay(self) -> None: ... + def reset(self) -> None: ... + def pool(self) -> _POOL_HANDLE: ... + def pools(self) -> list[_POOL_HANDLE]: ... + def _retain_pool(self, pool: _POOL_HANDLE) -> None: ... + def enable_debug_mode(self) -> None: ... + def raw_cuda_graph(self) -> _int: ... + def raw_cuda_graph_exec(self) -> _int: ... + @staticmethod + def get_currently_capturing_graph() -> torch.cuda.CUDAGraph: ... + def begin_capture_to_if_node(self, scalar_cuda_pred_tensor): ... + def begin_capture_to_while_node(self, scalar_cuda_pred_tensor): ... + def end_capture_to_conditional_node(self): ... + def set_conditional_handle_for_current_node(self, scalar_cuda_pred_tensor): ... + +# Defined in torch/csrc/cuda/MemPool.cpp +class _MemPool: + def __init__( + self, + allocator: _cuda_CUDAAllocator | None = None, + is_user_created: _bool = True, + use_on_oom: _bool = False, + no_split: _bool = False, + ) -> None: ... + @property + def id(self) -> tuple[_int, _int]: ... + @property + def allocator(self) -> _cuda_CUDAAllocator | None: ... + def use_count(self) -> _int: ... + +def _cuda_isCurrentStreamCapturing() -> _bool: ... +def _graph_pool_handle() -> tuple[_int, _int]: ... + +# Defined in torch/csrc/xpu/Module.cpp +def _xpu_setDevice(device: _int) -> None: ... +def _xpu_exchangeDevice(device: _int) -> _int: ... +def _xpu_maybeExchangeDevice(device: _int) -> _int: ... +def _xpu_getDevice() -> _int: ... +def _xpu_getDeviceCount() -> _int: ... +def _xpu_getArchFlags() -> str | None: ... +def _xpu_init() -> None: ... +def _xpu_setStream(stream_id: _int, device_index: _int, device_type: _int) -> None: ... +def _xpu_getCurrentStream(device: _int) -> tuple: ... +def _xpu_getCurrentRawStream(device: _int) -> _int: ... +def _xpu_getStreamFromExternal(data_ptr: _int, device_index: _int) -> tuple: ... +def _xpu_synchronize(device: _int) -> None: ... +def _xpu_emptyCache() -> None: ... +def _xpu_memoryStats(device: _int) -> dict[str, Any]: ... +def _xpu_resetAccumulatedMemoryStats(device: _int) -> None: ... +def _xpu_resetPeakMemoryStats(device: _int) -> None: ... +def _xpu_getMemoryInfo(device: _int) -> tuple[_int, _int]: ... +def _xpu_canDeviceAccessPeer(device: _int, peer: _int) -> _bool: ... +def _xpu_sleep(cycles: _int) -> None: ... +def _xpu_getMemoryFraction(device: _int) -> _float: ... +def _xpu_setMemoryFraction(fraction: _float, device: _int) -> None: ... +def _xpu_memorySnapshot(mempool_id: tuple[_int, _int] | None) -> dict[str, Any]: ... +def _xpu_recordMemoryHistory( + enabled: Literal["state", "all"] | None, + context: Literal["state", "alloc", "all"] | None, + stacks: Literal["python", "all"], + max_entries: _int, + clear_history: _bool, + skip_actions: list[str] | None, +) -> None: ... +def _xpu_beginAllocateToPool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _xpu_beginAllocateCurrentThreadToPool( + device: _int, + mempool_id: tuple[_int, _int], +) -> None: ... +def _xpu_endAllocateToPool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _xpu_releasePool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... + +class _XpuDeviceProperties: + name: str + platform_name: str + vendor: str + device_id: _int + driver_version: str + version: str + max_compute_units: _int + gpu_eu_count: _int + max_work_group_size: _int + max_num_sub_groups: _int + memory_clock_rate: _int + memory_bus_width: _int + sub_group_sizes: list[_int] + local_mem_size: _int + last_level_cache_size: _int + has_fp16: _bool + has_fp64: _bool + has_atomic64: _bool + has_bfloat16_conversions: _bool + has_subgroup_matrix_multiply_accumulate: _bool + has_subgroup_matrix_multiply_accumulate_tensor_float32: _bool + has_subgroup_2d_block_io: _bool + is_integrated_gpu: _bool + total_memory: _int + gpu_subslice_count: _int + architecture: _int + type: str + uuid: Any + +class _xpu_XPUAllocator: ... + +def _xpu_customAllocator(alloc_fn: _int, free_fn: _int) -> _xpu_XPUAllocator: ... +def _xpu_changeCurrentAllocator(allocator: _xpu_XPUAllocator) -> None: ... +def _xpu_getAllocator() -> _xpu_XPUAllocator: ... + +# Defined in torch/csrc/xpu/Stream.cpp +class _XpuStreamBase(Stream): + stream_id: _int + device_index: _int + device_type: _int + + device: _device + sycl_queue: _int + priority: _int + + def __new__( + cls, + priority: _int = 0, + stream_id: _int = 0, + device_index: _int = 0, + device_type: _int = 0, + ) -> Self: ... + def query(self) -> _bool: ... + def synchronize(self) -> None: ... + @staticmethod + def priority_range() -> tuple: ... + +# Defined in torch/csrc/xpu/Event.cpp +class _XpuEventBase: + device: _device + sycl_event: _int + + def __new__(cls, enable_timing: _bool = False) -> Self: ... + def record(self, stream: _XpuStreamBase | torch.Stream) -> None: ... + def wait(self, stream: _XpuStreamBase | torch.Stream) -> None: ... + def query(self) -> _bool: ... + def elapsed_time(self, other: _XpuEventBase) -> _float: ... + def synchronize(self) -> None: ... + +# Defined in torch/csrc/xpu/MemPool.cpp +class _XPUMemPool: + def __init__( + self, + allocator: _xpu_XPUAllocator | None = None, + is_user_created: _bool = True, + use_on_oom: _bool = False, + ) -> None: ... + @property + def id(self) -> tuple[_int, _int]: ... + @property + def allocator(self) -> _xpu_XPUAllocator | None: ... + def use_count(self) -> _int: ... + +# Defined in torch/csrc/xpu/Graph.cpp +class _XPUGraph: + def __new__(cls, keep_graph: _bool = ...) -> Self: ... + def capture_begin( + self, + pool: XPU_POOL_HANDLE | None = ..., + ) -> None: ... + def capture_end(self) -> None: ... + def instantiate(self) -> None: ... + def register_generator_state(self, Generator) -> None: ... + def replay(self) -> None: ... + def reset(self) -> None: ... + def pool(self) -> XPU_POOL_HANDLE: ... + def enable_debug_mode(self) -> None: ... + def debug_dump(self, debug_path: str) -> None: ... + def raw_xpu_graph(self) -> _int: ... + def raw_xpu_graph_exec(self) -> _int: ... + +def _xpu_graph_pool_handle() -> tuple[_int, _int]: ... +def _xpu_isCurrentStreamCapturing() -> _bool: ... + +# Defined in torch/csrc/DataLoader.cpp +def _set_worker_signal_handlers( + *arg: Any, +) -> None: ... # THPModule_setWorkerSignalHandlers +def _set_worker_pids( + key: _int, + child_pids: tuple[_int, ...], +) -> None: ... # THPModule_setWorkerPIDs +def _remove_worker_pids(loader_id: _int) -> None: ... # THPModule_removeWorkerPIDs +def _error_if_any_worker_fails() -> None: ... # THPModule_errorIfAnyWorkerFails + +# Defined in torch/csrc/DeviceAccelerator.cpp +def _accelerator_getAccelerator() -> _device: ... +def _accelerator_setDeviceIndex(device_index: _int) -> None: ... +def _accelerator_getDeviceIndex() -> _int: ... +def _accelerator_getDeviceCapability(device_index: _int) -> dict[str, Any]: ... +def _accelerator_setStream(Stream) -> None: ... +def _accelerator_getStream(device_index: _int) -> Stream: ... +def _accelerator_synchronizeDevice(device_index: _int) -> None: ... +def _accelerator_exchangeDevice(device_index: _int) -> _int: ... +def _accelerator_maybeExchangeDevice(device_index: _int) -> _int: ... +def _accelerator_isAllocatorInitialized() -> _bool: ... +def _accelerator_emptyCache() -> None: ... +def _accelerator_emptyHostCache() -> None: ... +def _accelerator_getDeviceStats(device_index: _int) -> dict[str, Any]: ... +def _accelerator_resetAccumulatedStats(device_index: _int) -> None: ... +def _accelerator_resetPeakStats(device_index: _int) -> None: ... +def _accelerator_getMemoryInfo(device_index: _int) -> tuple[_int, _int]: ... +def _accelerator_getAllocatorSettings() -> str: ... +def _accelerator_setAllocatorSettings(env: str) -> None: ... +def _accelerator_getDefaultGenerator(device_index: _int) -> Generator: ... + +class _acceleratorGraph: + def __new__(cls, _bool) -> Self: ... + def __init__(self, _bool) -> None: ... + def capture_begin( + self, + pool: tuple[_int, _int] | None = None, + capture_error_mode: Literal[ + "default", "global", "thread_local", "relaxed" + ] = "default", + ) -> None: ... + def capture_end(self) -> None: ... + def instantiate(self) -> None: ... + def replay(self) -> None: ... + def reset(self) -> None: ... + def pool(self) -> tuple[_int, _int]: ... + def enable_debug_mode(self) -> None: ... + def debug_dump(self, path: str) -> None: ... + +# Defined in torch/csrc/jit/python/python_tracer.cpp +class TracingState: + def push_scope(self, scope_name: str) -> None: ... + def pop_scope(self) -> None: ... + def current_scope(self) -> str: ... + def set_graph(self, graph: Graph) -> None: ... + def graph(self) -> Graph: ... + +def _create_graph_by_tracing( + func: Callable[..., Any], + inputs: Any, + var_name_lookup_fn: Callable[[Tensor], str], + strict: Any, + force_outplace: Any, + self: Any = None, + argument_names: list[str] = ..., +) -> tuple[Graph, Stack]: ... +def _tracer_warn_use_python(): ... +def _get_tracing_state() -> TracingState: ... + +# Defined in torch/csrc/jit/python/python_ir.cpp +# Not actually defined in python_ir.cpp, not sure where they are. +class IValue: ... + +Stack: TypeAlias = list[IValue] + +class JitType: + annotation_str: str + def isSubtypeOf(self, other: JitType) -> _bool: ... + def with_dtype(self, dtype: _dtype) -> JitType: ... + def with_sizes(self, sizes: list[_int | None]) -> JitType: ... + def kind(self) -> str: ... + def scalarType(self) -> str | None: ... + def getElementType(self) -> JitType: ... + def dtype(self) -> _dtype | None: ... + +class InferredType: + def __init__(self, arg: JitType | str) -> None: ... + def type(self) -> JitType: ... + def success(self) -> _bool: ... + def reason(self) -> str: ... + +class Type(JitType): + def str(self) -> _str: ... + def containedTypes(self) -> list[JitType]: ... + def dim(self) -> _int | None: ... + def undefined(self) -> _bool | None: ... + def sizes(self) -> list[_int] | None: ... + def symbol_sizes(self) -> list[_int] | None: ... + def varyingSizes(self) -> list[_int | None] | None: ... + def strides(self) -> list[_int] | None: ... + def contiguous(self) -> Self: ... + def device(self) -> _device | None: ... + def is_interface_type(self) -> _bool: ... + def requires_grad(self) -> _bool: ... + @property + def annotation_string(self) -> _str: ... + +class AnyType(JitType): + @staticmethod + def get() -> AnyType: ... + +class NoneType(JitType): + @staticmethod + def get() -> NoneType: ... + +class BoolType(JitType): + @staticmethod + def get() -> BoolType: ... + +class FloatType(JitType): + @staticmethod + def get() -> FloatType: ... + +class ComplexType(JitType): + @staticmethod + def get() -> ComplexType: ... + +class IntType(JitType): + @staticmethod + def get() -> IntType: ... + +class SymIntType(JitType): + @staticmethod + def get() -> SymIntType: ... + +class SymBoolType(JitType): + @staticmethod + def get() -> SymBoolType: ... + +class NumberType(JitType): + @staticmethod + def get() -> NumberType: ... + +class StringType(JitType): + @staticmethod + def get() -> StringType: ... + +class DeviceObjType(JitType): + @staticmethod + def get() -> DeviceObjType: ... + +class _GeneratorType(JitType): + @staticmethod + def get() -> _GeneratorType: ... + +class StreamObjType(JitType): + @staticmethod + def get() -> StreamObjType: ... + +class ListType(JitType): + def __init__(self, a: JitType) -> None: ... + def getElementType(self) -> JitType: ... + @staticmethod + def ofInts() -> ListType: ... + @staticmethod + def ofTensors() -> ListType: ... + @staticmethod + def ofFloats() -> ListType: ... + @staticmethod + def ofComplexDoubles() -> ListType: ... + @staticmethod + def ofBools() -> ListType: ... + @staticmethod + def ofStrings() -> ListType: ... + +class DictType(JitType): + def __init__(self, key: JitType, value: JitType) -> None: ... + def getKeyType(self) -> JitType: ... + def getValueType(self) -> JitType: ... + +class TupleType(JitType): + def __init__(self, a: list[JitType | None]) -> None: ... + def elements(self) -> list[JitType]: ... + +class UnionType(JitType): + def __init__(self, a: list[JitType]) -> None: ... + +class ClassType(JitType): + def __init__(self, qualified_name: str) -> None: ... + def qualified_name(self) -> str: ... + +class InterfaceType(JitType): + def __init__(self, qualified_name: str) -> None: ... + def getMethod(self, name: str) -> FunctionSchema | None: ... + def getMethodNames(self) -> list[str]: ... + +JitTypeT = TypeVar("JitTypeT", bound=JitType) # noqa: PYI001 + +class OptionalType(JitType, Generic[JitTypeT]): + def __init__(self, a: JitTypeT) -> None: ... + def getElementType(self) -> JitTypeT: ... + @staticmethod + def ofTensor() -> OptionalType: ... + +class FutureType(JitType): + def __init__(self, a: JitType) -> None: ... + def getElementType(self) -> JitType: ... + +class AwaitType(JitType): + def __init__(self, a: JitType) -> None: ... + def getElementType(self) -> JitType: ... + +class RRefType(JitType): + def __init__(self, a: JitType) -> None: ... + +class EnumType(JitType): + def __init__( + self, + qualified_name: str, + value_type: JitType, + enum_names_values: list[Any], + ) -> None: ... + +class TensorType(JitType): + @classmethod + def get(cls) -> TensorType: ... + @classmethod + def getInferred(cls) -> TensorType: ... + def with_sizes(self, other: list[_int | None] | None) -> TensorType: ... + def sizes(self) -> list[_int] | None: ... + def varyingSizes(self) -> list[_int | None] | None: ... + def strides(self) -> list[_int] | None: ... + def device(self) -> _device | None: ... + def dim(self) -> _int: ... + def dtype(self) -> _dtype | None: ... + @staticmethod + def create_from_tensor(t: Tensor) -> TensorType: ... + +# Defined in torch/csrc/jit/python/python_tree_views.cpp +class SourceRange: ... +class TreeView: ... + +class Ident(TreeView): + @property + def name(self) -> str: ... + +class ClassDef(TreeView): ... + +class Def(TreeView): + def name(self) -> Ident: ... + +class Decl(TreeView): ... + +# Defined in torch/csrc/distributed/rpc/init.cpp +def _rpc_init() -> _bool: ... + +# Defined in torch/csrc/distributed/autograd/init.cpp +def _dist_autograd_init() -> _bool: ... + +# Defined in torch/csrc/distributed/c10d/init.cpp +def _c10d_init() -> _bool: ... + +# Defined in torch/csrc/distributed/rpc/testing/init.cpp +def _faulty_agent_init() -> _bool: ... +def _register_py_class_for_device(device: str, cls: Any) -> None: ... + +# Defined in torch/csrc/Module.cpp +def _current_graph_task_id() -> _int: ... +def _current_autograd_node() -> _Node: ... +def _will_engine_execute_node(node: _Node) -> _bool: ... +def _dispatch_key_set(tensor) -> str: ... + +# Defined in torch/csrc/Exceptions.cpp +class AcceleratorError(RuntimeError): ... +class OutOfMemoryError(RuntimeError): ... +class _DistError(RuntimeError): ... +class _DistBackendError(RuntimeError): ... +class _DistStoreError(RuntimeError): ... +class _DistNetworkError(RuntimeError): ... +class _DistQueueEmptyError(_DistStoreError): ... + +# Defined in torch/csrc/profiler/init.cpp +class CapturedTraceback: ... + +def gather_traceback(python: _bool, script: _bool, cpp: _bool) -> CapturedTraceback: ... +def symbolize_tracebacks( + tracebacks: list[CapturedTraceback], +) -> list[dict[str, Any]]: ... +def _load_mobile_module_from_file(filename: str): ... +def _load_mobile_module_from_bytes(bytes_: bytes): ... +def _load_jit_module_from_file(filename: str): ... +def _load_jit_module_from_bytes(bytes_: bytes): ... +def _save_mobile_module(m: LiteScriptModule, filename: str): ... +def _save_jit_module(m: ScriptModule, filename: str, extra_files: dict[str, Any]): ... +def _save_mobile_module_to_bytes(m: LiteScriptModule) -> bytes: ... +def _save_jit_module_to_bytes( + m: ScriptModule, + extra_files: dict[str, Any], +) -> bytes: ... +def _get_module_info_from_flatbuffer(data: bytes): ... +def _jit_resolve_packet(op_name: str, *args, **kwargs) -> str: ... +def _swap_tensor_impl(t1: Tensor, t2: Tensor): ... +def _pickle_save(obj: Any) -> bytes: ... +def _pickle_load_obj(bs: bytes) -> Any: ... + +# Defined in torch/csrc/jit/runtime/static/init.cpp +def _jit_to_static_module(graph_or_module: Graph | ScriptModule) -> Any: ... +def _fuse_to_static_module( + graph_or_module: Graph | ScriptModule, + min_size: _int, +) -> Any: ... + +# Defined in torch/csrc/fx/node.cpp +def _fx_map_aggregate(a: Any, fn: Callable[[Any], Any]) -> Any: ... +def _fx_map_arg(a: Any, fn: Callable[[Any], Any]) -> Any: ... + +class _NodeBase: + _erased: _bool + _prev: FxNode + _next: FxNode + def __init__( + self, + graph: Any, + name: str, + op: str, + target: Any, + return_type: Any, + ) -> None: ... + def _update_args_kwargs(self, args: tuple[Any, ...], kwargs: dict[str, Any]): ... + def _prepend(self, n: FxNode) -> None: ... + def _replace_input_with(self, old_input: FxNode, new_input: FxNode) -> None: ... + def _remove_from_list(self) -> None: ... + def __lt__(self, n: Self) -> _bool: ... + def __gt__(self, n: Self) -> _bool: ... + def __le__(self, n: Self) -> _bool: ... + def __ge__(self, n: Self) -> _bool: ... + +class _NodeIter(Iterator[FxNode]): + def __init__(self, root: FxNode, reversed: _bool) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> FxNode: ... + +# Defined in torch/csrc/inductor/static_launcher/cuda.cpp +class _StaticCudaLauncher: + @staticmethod + def _load_kernel( + cubin_file: str, + func_name: str, + shared_mem_bytes: _int, + device: _int, + ) -> tuple[_int, _int, _int]: ... + @staticmethod + def _launch_kernel( + func: _int, + grid_x: _int, + grid_y: _int, + grid_z: _int, + num_warps: _int, + shared_mem_bytes: _int, + arg_types: str, + args: tuple[Any, ...], + stream: _int, + ) -> None: ... + +# Defined in torch/csrc/inductor/static_launcher/xpu.cpp +class _StaticXpuLauncher(_StaticCudaLauncher): ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_acc/__init__.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_acc/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3ee9b16c225b5ed6a34bc9ab9198eb38ad1e52a4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_acc/__init__.pyi @@ -0,0 +1,15 @@ +from torch import Tensor +from torch.types import _dtype, _int, Device + +# Defined in torch/csrc/acc/Module.cpp +class PrivateUse1Hooks: + def has_primary_context(self, device_index: _int) -> bool: ... + def is_built(self) -> bool: ... + def is_available(self) -> bool: ... + +class DeviceGuard: + def type_(self) -> Device: ... + +def register_python_privateuseone_device_guard(guard: DeviceGuard) -> bool: ... +def register_python_privateuseone_hook(hook: PrivateUse1Hooks) -> bool: ... +def create_empty_tensor(shape: tuple[_int, ...], dtype: _dtype) -> Tensor: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_aoti.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_aoti.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5002c1525899ca5cd4b411769201cbcd9713cdb7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_aoti.pyi @@ -0,0 +1,183 @@ +from ctypes import c_void_p +from typing import overload, Protocol + +from torch import Tensor + +# Defined in torch/csrc/inductor/aoti_runner/pybind.cpp + +# Tensor to AtenTensorHandle +def unsafe_alloc_void_ptrs_from_tensors(tensors: list[Tensor]) -> list[c_void_p]: ... +def unsafe_alloc_void_ptr_from_tensor(tensor: Tensor) -> c_void_p: ... + +# AtenTensorHandle to Tensor +def alloc_tensors_by_stealing_from_void_ptrs( + handles: list[c_void_p], +) -> list[Tensor]: ... +def alloc_tensor_by_stealing_from_void_ptr( + handle: c_void_p, +) -> Tensor: ... + +class AOTIModelContainerRunner(Protocol): + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerCpu: + def __init__(self, model_so_path: str, num_models: int) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerCuda: + @overload + def __init__(self, model_so_path: str, num_models: int) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str + ) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str, cubin_dir: str + ) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def update_constant_buffer_from_cpu( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerXpu: + @overload + def __init__(self, model_so_path: str, num_models: int) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str + ) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str, kernel_bin_dir: str + ) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def update_constant_buffer_from_cpu( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerMps: + def __init__(self, model_so_path: str, num_models: int) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def update_constant_buffer_from_cpu( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +# Defined in torch/csrc/inductor/aoti_package/pybind.cpp +class AOTIModelPackageLoader: + def __init__( + self, + model_package_path: str, + model_name: str, + run_single_threaded: bool, + num_runners: int, + device_index: int, + ) -> None: ... + def get_metadata(self) -> dict[str, str]: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def boxed_run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_fqns(self) -> list[str]: ... + def load_constants( + self, + constants_map: dict[str, Tensor], + use_inactive: bool, + check_full_update: bool, + user_managed: bool = ..., + allow_h2d_copy: bool = ..., + ) -> None: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_autograd.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_autograd.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6a67ccbd2e3798fa9fc3b45f0bf391545680e2aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_autograd.pyi @@ -0,0 +1,167 @@ +# mypy: allow-untyped-defs +from collections.abc import Callable +from enum import Enum +from typing import Any + +import torch +from torch._C._profiler import ( + _ProfilerEvent, + ActiveProfilerType, + ProfilerActivity, + ProfilerConfig, +) + +# Defined in torch/csrc/autograd/init.cpp + +class DeviceType(Enum): + CPU = ... + CUDA = ... + XPU = ... + MKLDNN = ... + OPENGL = ... + OPENCL = ... + IDEEP = ... + HIP = ... + FPGA = ... + MAIA = ... + XLA = ... + MTIA = ... + MPS = ... + HPU = ... + Meta = ... + Vulkan = ... + Metal = ... + PrivateUse1 = ... + +class ProfilerEvent: + def cpu_elapsed_us(self, other: ProfilerEvent) -> float: ... + def cpu_memory_usage(self) -> int: ... + def cuda_elapsed_us(self, other: ProfilerEvent) -> float: ... + def privateuse1_elapsed_us(self, other: ProfilerEvent) -> float: ... + def cuda_memory_usage(self) -> int: ... + def device(self) -> int: ... + def handle(self) -> int: ... + def has_cuda(self) -> bool: ... + def is_remote(self) -> bool: ... + def kind(self) -> int: ... + def name(self) -> str: ... + def node_id(self) -> int: ... + def sequence_nr(self) -> int: ... + def shapes(self) -> list[list[int]]: ... + def thread_id(self) -> int: ... + def flops(self) -> float: ... + def is_async(self) -> bool: ... + +class _KinetoEvent: + def name(self) -> str: ... + def overload_name(self) -> str: ... + def device_index(self) -> int: ... + def device_resource_id(self) -> int: ... + def start_ns(self) -> int: ... + def end_ns(self) -> int: ... + def duration_ns(self) -> int: ... + def is_async(self) -> bool: ... + def linked_correlation_id(self) -> int: ... + def external_id(self) -> int: ... + def shapes(self) -> list[list[int]]: ... + def dtypes(self) -> list[str]: ... + def concrete_inputs(self) -> list[Any]: ... + def kwinputs(self) -> dict[str, Any]: ... + def device_type(self) -> DeviceType: ... + def start_thread_id(self) -> int: ... + def end_thread_id(self) -> int: ... + def correlation_id(self) -> int: ... + def fwd_thread_id(self) -> int: ... + def stack(self) -> list[str]: ... + def scope(self) -> int: ... + def sequence_nr(self) -> int: ... + def flops(self) -> int: ... + def cuda_elapsed_us(self) -> int: ... + def privateuse1_elapsed_us(self) -> int: ... + def is_user_annotation(self) -> bool: ... + def is_python_function(self) -> bool: ... + def is_hidden_event(self) -> bool: ... + def metadata_json(self) -> str: ... + def activity_type(self) -> str: ... + def extra_meta(self) -> dict[str, str]: ... + def typed_metadata(self) -> dict[str, Any]: ... + def flow_id(self) -> int: ... + def flow_type(self) -> int: ... + def flow_start(self) -> bool: ... + def structured_input_shapes(self) -> list[list[int] | list[list[int]]]: ... + def structured_input_strides(self) -> list[list[int] | list[list[int]]]: ... + def python_id(self) -> int: ... + def python_parent_id(self) -> int: ... + def python_module_id(self) -> int: ... + +class _ProfilerResult: + def events(self) -> list[_KinetoEvent]: ... + def legacy_events(self) -> list[list[ProfilerEvent]]: ... + def save(self, path: str) -> None: ... + def experimental_event_tree(self) -> list[_ProfilerEvent]: ... + def trace_start_ns(self) -> int: ... + +class SavedTensor: + def unpack(self) -> torch.Tensor: ... + +def _make_saved_tensor( + tensor: torch.Tensor, + is_output: bool, + is_inplace_on_view: bool = False, +) -> SavedTensor: ... +def _enable_profiler( + config: ProfilerConfig, + activities: set[ProfilerActivity], +) -> None: ... +def _prepare_profiler( + config: ProfilerConfig, + activities: set[ProfilerActivity], + activity_filter: dict[ProfilerActivity, set[str]] = ..., +) -> None: ... +def _toggle_collection_dynamic( + enable: bool, + activities: set[ProfilerActivity], +) -> None: ... +def _disable_profiler() -> _ProfilerResult: ... +def _profiler_enabled() -> bool: ... +def _add_metadata_json(key: str, value: str) -> None: ... +def _is_kineto_stopped() -> bool: ... +def _kineto_step() -> None: ... +def _get_current_graph_task_keep_graph() -> bool: ... +def _get_sequence_nr() -> int: ... +def kineto_available() -> bool: ... +def _record_function_with_args_enter(name: str, *args) -> torch.Tensor: ... +def _record_function_with_args_exit(handle: torch.Tensor) -> None: ... +def _supported_activities() -> set[ProfilerActivity]: ... +def _enable_record_function(enable: bool) -> None: ... +def _set_empty_test_observer(is_global: bool, sampling_prob: float) -> None: ... +def _push_saved_tensors_default_hooks( + pack_hook: Callable[[torch.Tensor], Any], + unpack_hook: Callable[[Any], torch.Tensor], +) -> None: ... +def _pop_saved_tensors_default_hooks() -> None: ... +def _push_node_creation_hook(hook: Callable[[Any], None]) -> None: ... +def _pop_node_creation_hook() -> None: ... +def _top_saved_tensors_default_hooks( + ignore_is_tracing: bool, +) -> tuple[Callable[[torch.Tensor], Any], Callable[[Any], torch.Tensor]]: ... +def _unsafe_set_version_counter( + t: tuple[torch.Tensor, ...], prev_version: tuple[int, ...] +) -> None: ... +def _enable_profiler_legacy(config: ProfilerConfig) -> None: ... +def _disable_profiler_legacy() -> list[list[ProfilerEvent]]: ... +def _profiler_type() -> ActiveProfilerType: ... +def _saved_tensors_hooks_enable() -> None: ... +def _saved_tensors_hooks_disable(message: str, fail_if_non_empty=True) -> None: ... +def _saved_tensors_hooks_get_disabled_error_message() -> str | None: ... +def _saved_tensors_hooks_set_tracing(is_tracing: bool) -> bool: ... + +class CreationMeta(Enum): + DEFAULT = ... + IN_CUSTOM_FUNCTION = ... + MULTI_OUTPUT_NODE = ... + NO_GRAD_MODE = ... + INFERENCE_MODE = ... + +def _set_creation_meta(t: torch.Tensor, creation_meta: CreationMeta) -> None: ... +def _get_creation_meta(t: torch.Tensor) -> CreationMeta: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_cpu.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_cpu.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4d8f2edc430f4611460050a3931886647a1bf31d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_cpu.pyi @@ -0,0 +1,8 @@ +from typing import Any + +from torch.types import _bool + +# Defined in torch/csrc/cpu/Module.cpp + +def _init_amx() -> _bool: ... +def _get_cpu_capability() -> dict[str, Any]: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_cudnn.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_cudnn.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cfea3f956f2a373dfe6895743a49a3c6cec439fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_cudnn.pyi @@ -0,0 +1,14 @@ +from enum import IntEnum + +# Defined in torch/csrc/cuda/shared/cudnn.cpp +is_cuda: bool + +def getRuntimeVersion() -> tuple[int, int, int]: ... +def getCompileVersion() -> tuple[int, int, int]: ... +def getVersionInt() -> int: ... + +class RNNMode(IntEnum): + rnn_relu = ... + rnn_tanh = ... + lstm = ... + gru = ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_cusparselt.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_cusparselt.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a1c4bbb217777d50b9a3384da11d9992db5e18f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_cusparselt.pyi @@ -0,0 +1 @@ +def getVersionInt() -> int: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_distributed.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_distributed.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c8416f60edca35493ad7c1703cf2e27d58975be0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_distributed.pyi @@ -0,0 +1,21 @@ +# This module is defined in torch/csrc/distributed/python_placement.cpp + +class Placement: + def is_partial(self, reduce_op: str | None = None) -> bool: ... + def is_replicate(self) -> bool: ... + def is_shard(self, dim: int | None = None) -> bool: ... + +class Shard(Placement): + dim: int + def __init__(self, dim: int): ... + +class StridedShard(Placement): + dim: int + split_factor: int + def __init__(self, dim: int, *, split_factor: int): ... + +class Replicate(Placement): ... + +class Partial(Placement): + reduce_op: str + def __init__(self, reduce_op: str | None = None): ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_distributed_autograd.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_autograd.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6e1e39bec2927c046455928ff74bc7de9683e66f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_autograd.pyi @@ -0,0 +1,26 @@ +from typing import Any + +import torch + +# This module is defined in torch/csrc/distributed/autograd/init.cpp + +class DistAutogradContext: + def _context_id(self) -> int: ... + def _recv_functions(self) -> dict[int, Any]: ... + def _send_functions(self) -> dict[int, Any]: ... + def _known_worker_ids(self) -> set[int]: ... + +def _new_context() -> DistAutogradContext: ... +def _release_context(context_id: int) -> None: ... +def _get_max_id() -> int: ... +def _is_valid_context(worker_id: int) -> bool: ... +def _retrieve_context(context_id: int) -> DistAutogradContext: ... +def _current_context() -> DistAutogradContext: ... +def _init(worker_id: int) -> None: ... +def _get_debug_info() -> dict[str, str]: ... +def backward( + context_id: int, + roots: list[torch.Tensor], + retain_graph: bool = False, +) -> None: ... +def get_gradients(context_id: int) -> dict[torch.Tensor, torch.Tensor]: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_distributed_c10d.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_c10d.pyi new file mode 100644 index 0000000000000000000000000000000000000000..62c28e342c8f55c4e93ef5671c21d7616a76b0d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_c10d.pyi @@ -0,0 +1,1184 @@ +# mypy: allow-untyped-defs +# mypy: disable-error-code="type-arg" +from collections.abc import Callable +from datetime import timedelta +from enum import Enum +from typing import Any, overload + +import torch +from torch import Tensor +from torch._C import ScriptObject +from torch._C._autograd import DeviceType +from torch.distributed.distributed_c10d import GroupName +from torch.futures import Future + +# This module is defined in torch/csrc/distributed/c10d/init.cpp + +_DEFAULT_FIRST_BUCKET_BYTES: int +_DEFAULT_NO_TIMEOUT: timedelta +_DEFAULT_PG_TIMEOUT: timedelta +_DEFAULT_PG_NCCL_TIMEOUT: timedelta + +class BuiltinCommHookType(Enum): + ALLREDUCE = ... + FP16_COMPRESS = ... + +def _register_comm_hook(reducer: Reducer, state: Any, comm_hook: Any): ... +def _register_builtin_comm_hook( + reducer: Reducer, + comm_hook_type: BuiltinCommHookType, +): ... +def _set_global_rank(rank: int) -> None: ... +def _hash_tensors(tensors: list[Tensor]) -> int: ... + +class GradBucket: + def index(self) -> int: ... + def buffer(self) -> Tensor: ... + def gradients(self) -> list[Tensor]: ... + def is_last(self) -> bool: ... + def set_buffer(self, tensor: Tensor) -> None: ... + def parameters(self) -> list[Tensor]: ... + +class Reducer: + def __init__( + self, + params: list[Tensor], + bucket_indices: list[list[int]], + per_bucket_size_limits: list[int], + process_group: ProcessGroup, + expect_sparse_gradients: list[bool] = ..., + bucket_bytes_cap: int = ..., # kDefaultBucketBytesCap in reducer.hpp + find_unused_parameters: bool = ..., + gradient_as_bucket_view: bool = ..., + param_to_name_mapping: dict[int, str] = ..., + first_bucket_types_cap: int = ..., # kDefaultFirstBucketBytes in reducer.hpp + skip_all_reduce_unused_params: bool = ..., + use_python_reducer: bool = ..., + bucket_bytes_cap_list: list[int] = ..., + batched_grad_copy: bool = ..., + ) -> None: ... + def prepare_for_forward(self) -> None: ... + def prepare_for_backward(self, output: list[Tensor]) -> None: ... + def get_backward_stats(self) -> list[int]: ... + def _install_post_backward_futures(self, futures: list[Future]) -> None: ... + def _rebuild_buckets(self) -> bool: ... + def _get_zeros_like_grad_buckets(self) -> list[GradBucket]: ... + def _push_all_rebuilt_params(self) -> None: ... + def _set_forward_pass_work_handle( + self, + work: Work, + use_static_world_size: bool, + ): ... + def _get_local_used_map(self) -> Tensor: ... + def _set_ddp_runtime_logging_sample_rate(self, sample_rate: int) -> None: ... + def _set_static_graph(self) -> None: ... + def _run_comm_hook(self, bucket: GradBucket) -> Future: ... + def set_logger(self, logger: Logger) -> None: ... + def _remove_autograd_hooks(self) -> None: ... + def _check_reducer_finalized(self) -> None: ... + def _set_sparse_metadata(self, global_unique_ids: dict[str, Tensor]) -> None: ... + def _reset_state(self) -> None: ... + def _update_process_group(self, new_process_group: ProcessGroup) -> None: ... + +class DDPLoggingData: + strs_map: dict[str, str] + ints_map: dict[str, int] + +class Logger: + def __init__(self, reducer: Reducer) -> None: ... + def set_construction_data_and_log( + self, + module_name: str, + device_ids: list[int], + output_device: int, + broadcast_buffers: bool, + has_sync_bn: bool, + static_graph: bool, + ) -> None: ... + def set_runtime_stats_and_log(self) -> None: ... + def set_error_and_log(self, error: str) -> None: ... + def _get_ddp_logging_data(self) -> DDPLoggingData: ... + def _set_comm_hook_name(self, comm_hook: str) -> None: ... + def _set_uneven_input_join(self) -> None: ... + def _set_static_graph(self) -> None: ... + +class _WorkerServer: + port: int + + def __init__(self, host_or_file: str, port: int = ...) -> None: ... + def shutdown(self) -> None: ... + +class DebugLevel(Enum): + OFF = ... + INFO = ... + DETAIL = ... + +def get_debug_level() -> DebugLevel: ... +def set_debug_level(level: DebugLevel) -> None: ... +def set_debug_level_from_env() -> None: ... + +class ReduceOp: + # pyrefly: ignore # unknown-name + def __init__(self, op: RedOpType) -> None: ... + @property + def factor(self) -> float | Tensor: ... + + # pyrefly: ignore # unknown-name + SUM: RedOpType = ... + # pyrefly: ignore # unknown-name + AVG: RedOpType = ... + # pyrefly: ignore # unknown-name + PRODUCT: RedOpType = ... + # pyrefly: ignore # unknown-name + MIN: RedOpType = ... + # pyrefly: ignore # unknown-name + MAX: RedOpType = ... + # pyrefly: ignore # unknown-name + BAND: RedOpType = ... + # pyrefly: ignore # unknown-name + BOR: RedOpType = ... + # pyrefly: ignore # unknown-name + BXOR: RedOpType = ... + # pyrefly: ignore # unknown-name + PREMUL_SUM: RedOpType = ... + # pyrefly: ignore # unknown-name + UNUSED: RedOpType = ... + + # mypy error being ignored: + # Detected enum "torch._C._distributed_c10d.ReduceOp.RedOpType" in a type + # stub with zero members. There is a chance this is due to a recent change + # in the semantics of enum membership. If so, use `member = value` to mark + # an enum member, instead of `member: type` + class RedOpType(Enum): + def __call__(self, factor: float | int | Tensor) -> ReduceOp: + """Create a PREMUL_SUM ReduceOp with the given factor. Only PREMUL_SUM supports this.""" + +class BroadcastOptions: + rootRank: int + rootTensor: int + timeout: timedelta + asyncOp: bool + +class AllreduceOptions: + reduceOp: ReduceOp | ReduceOp.RedOpType + timeout: timedelta + asyncOp: bool + sparseIndices: Tensor | None + +class AllreduceCoalescedOptions(AllreduceOptions): ... + +class ReduceOptions: + reduceOp: ReduceOp | ReduceOp.RedOpType + rootRank: int + rootTensor: int + timeout: timedelta + asyncOp: bool + +class AllgatherOptions: + timeout: timedelta + asyncOp: bool + +class GatherOptions: + rootRank: int + timeout: timedelta + asyncOp: bool + +class ScatterOptions: + rootRank: int + timeout: timedelta + asyncOp: bool + +class ReduceScatterOptions: + reduceOp: ReduceOp | ReduceOp.RedOpType + timeout: timedelta + asyncOp: bool + +class BarrierOptions: + device_ids: list[int] + device: torch.device + timeout: timedelta + asyncOp: bool + +class AllToAllOptions: + timeout: timedelta + asyncOp: bool + +class ReconfigureOptions: + uuid: int + handles: set[str] | list[str] + timeout: timedelta | None + hints: dict[str, str] + +class PutOptions: + timeout: timedelta + hints: dict[str, str] + +class SignalOptions: + timeout: timedelta + hints: dict[str, str] + +class WaitSignalOptions: + timeout: timedelta + hints: dict[str, str] + +class WindowAccessType(Enum): + UNIFIED = ... + SEPARATE = ... + +class WindowAttr: + access_type: WindowAccessType + +class Window: + def tensor_register(self, tensor: Tensor, owning: bool = ...) -> None: ... + def tensor_deregister(self) -> None: ... + def put( + self, + tensor: Tensor, + dst_rank: int, + target_offset_nelems: int, + async_op: bool, + opts: PutOptions = ..., + ) -> Work: ... + def map_remote_tensor(self, rank: int) -> Tensor: ... + def signal( + self, + peer_rank: int, + async_op: bool, + opts: SignalOptions = ..., + ) -> Work: ... + def wait_signal( + self, + peer_rank: int, + async_op: bool, + opts: WaitSignalOptions = ..., + ) -> Work: ... + def get_attr(self, peer_rank: int) -> WindowAttr: ... + +class HookOpName(Enum): + SEND = ... + RECV = ... + BROADCAST = ... + ALLREDUCE = ... + REDUCE = ... + ALLGATHER = ... + REDUCE_SCATTER = ... + ALLTOALL = ... + BARRIER = ... + SCATTER = ... + GATHER = ... + SPLIT = ... + NEW_WINDOW = ... + UNKNOWN = ... + +class PreHookArgs: + name: HookOpName + async_op: bool + input_tensors: list[Tensor] + output_tensors: list[Tensor] + root: int + op_id: int + +class PostHookArgs: + name: HookOpName + async_op: bool + work: Work | None + op_id: int + +class Store: + def set(self, key: str, value: str) -> None: ... + def get(self, key: str) -> bytes: ... + def add(self, key: str, value: int) -> int: ... + def check(self, keys: list[str]) -> bool: ... + def compare_set( + self, + key: str, + expected_value: str, + desired_value: str, + ) -> bytes: ... + def delete_key(self, key: str) -> bool: ... + def multi_get(self, keys: list[str]) -> list[bytes]: ... + def num_keys(self) -> int: ... + def set_timeout(self, timeout: timedelta) -> None: ... + @overload + def wait(self, keys: list[str]) -> None: ... + @overload + def wait(self, keys: list[str], timeout: timedelta) -> None: ... + def queue_pop(self, key: str, block: bool = True) -> bytes: ... + def queue_push(self, key: str, value: bytes | str) -> None: ... + def queue_len(self, key: str) -> int: ... + def list_keys(self) -> list[str]: ... + def clone(self) -> Store: ... + +class FileStore(Store): + def __init__(self, path: str, numWorkers: int = ...) -> None: ... + +class HashStore(Store): + def __init__(self) -> None: ... + +class FakeStore(Store): + def __init__(self) -> None: ... + +class TCPStore(Store): + def __init__( + self, + host_name: str, + port: int, + world_size: int | None = ..., + is_master: bool = ..., + timeout: timedelta = ..., + wait_for_workers: bool = ..., + multi_tenant: bool = ..., + master_listen_fd: int | None = ..., + use_libuv: bool | None = ..., + ) -> None: ... + @property + def host(self) -> str: ... + @property + def port(self) -> int: ... + +class PrefixStore(Store): + def __init__(self, prefix: str, store: Store) -> None: ... + @property + def underlying_store(self) -> Store: ... + +class _DistributedBackendOptions: + def __init__(self) -> None: ... + @property + def store(self) -> Store: ... + @store.setter + def store(self, store: Store) -> None: ... + @property + def group_rank(self) -> int: ... + @group_rank.setter + def group_rank(self, rank: int) -> None: ... + @property + def group_size(self) -> int: ... + @group_size.setter + def group_size(self, size: int) -> None: ... + @property + def timeout(self) -> timedelta: ... + @timeout.setter + def timeout(self, timeout: timedelta) -> None: ... + @property + def group_id(self) -> GroupName: ... + @group_id.setter + def group_id(self, group_id: GroupName) -> None: ... + @property + def global_ranks_in_group(self) -> list[int]: ... + @global_ranks_in_group.setter + def global_ranks_in_group(self, ranks: list[int]) -> None: ... + process_group: ProcessGroup | None + split_from: Backend | None + enable_reconfigure: bool + +class Work: + def is_completed(self) -> bool: ... + def is_success(self) -> bool: ... + def exception(self) -> Any: ... + def wait(self, timeout: timedelta = ...) -> bool: ... + def block_current_stream(self) -> None: ... + def get_future(self) -> Future: ... + def source_rank(self) -> int: ... + def _source_rank(self) -> int: ... + def result(self) -> list[Tensor]: ... + def synchronize(self) -> None: ... + def _get_duration(self) -> float: ... + def _get_sequence_number(self) -> int: ... + @property + def timeout(self) -> timedelta: ... + def boxed(self) -> ScriptObject: ... + @staticmethod + def unbox(obj: ScriptObject) -> Work: ... + +class Backend: + class Options: + def __init__(self, backend: str, timeout: timedelta = ...) -> None: ... + @property + def backend(self) -> str: ... + @property + def _timeout(self) -> timedelta: ... + @_timeout.setter + def _timeout(self, val: timedelta) -> None: ... + global_ranks_in_group: list[int] + group_name: GroupName + use_pg_for_symm_mem_rendezvous: bool + enable_reconfigure: bool + + def __init__( + self, + rank: int, + size: int, + ) -> None: ... + @property + def supports_splitting(self) -> bool: ... + @property + def supports_coalescing(self) -> bool: ... + @property + def supports_time_estimate(self) -> bool: ... + @property + def supports_shrinking(self) -> bool: ... + def shrink( + self, + ranks_to_exclude: list[int], + shrink_flags: int = ..., + opts_override: Backend.Options | None = None, + ) -> Backend: ... + @property + def supports_reconfigure(self) -> bool: ... + def get_reconfigure_handle(self) -> str: ... + def reconfigure(self, opts: ReconfigureOptions) -> Work: ... + @property + def supports_window(self) -> bool: ... + def new_window(self, tensor: Tensor | None = None) -> Window: ... + def register_abort_hook(self, hook_id: int, hook: Callable[[], None]) -> None: ... + def unregister_abort_hook(self, hook_id: int) -> None: ... + def set_timeout(self, timeout: timedelta) -> None: ... + def _add_ephemeral_timeout(self, timeout: timedelta) -> None: ... + @property + def options(self) -> Options: ... + def rank(self) -> int: ... + def size(self) -> int: ... + def name(self) -> str: ... + def abort(self) -> None: ... + def shutdown(self) -> None: ... + def eager_connect_single_device(self, device: torch.device | None) -> None: ... + def _set_sequence_number_for_group(self) -> None: ... + def _set_default_timeout(self, timeout: timedelta) -> None: ... + def get_error(self) -> ErrorType: ... + def supports_tensor_alloc(self, device: torch.device) -> bool: ... + def allocate_tensor( + self, + size: int, + *, + dtype: torch.dtype, + device: torch.device, + ) -> Tensor: ... + @property + def mem_allocator(self) -> Any: ... + +class ProcessGroup: + class BackendType(Enum): + UNDEFINED = ... + GLOO = ... + NCCL = ... + UCC = ... + MPI = ... + XCCL = ... + CUSTOM = ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + ) -> None: ... + def rank(self) -> int: ... + def size(self) -> int: ... + def get_group_store(self) -> Store: ... + def split_group( + self, + new_ranks: list[int], + timeout: timedelta | None = None, + opts: Backend.Options | None = None, + group_name: GroupName | None = None, + group_desc: str | None = None, + device_types: list[torch.device] | None = None, + ) -> ProcessGroup | None: ... + def merge_remote_group( + self, + store: Store, + size: int, + timeout: timedelta, + group_name: GroupName | None = None, + group_desc: str | None = None, + ) -> ProcessGroup: ... + def abort(self) -> None: ... + def set_timeout(self, timeout: timedelta) -> None: ... + def _add_ephemeral_timeout(self, timeout: timedelta) -> None: ... + def shutdown(self) -> None: ... + @property + def supports_reconfigure(self) -> bool: ... + def get_reconfigure_handle(self) -> str: ... + def reconfigure(self, opts: ReconfigureOptions) -> Work: ... + @property + def supports_window(self) -> bool: ... + def new_window(self, tensor: Tensor | None = None) -> Window: ... + def register_abort_hook(self, hook_id: int, hook: Callable[[], None]) -> None: ... + def unregister_abort_hook(self, hook_id: int) -> None: ... + def register_pre_hook( + self, hook_id: int, hook: Callable[[PreHookArgs], None] + ) -> None: ... + def unregister_pre_hook(self, hook_id: int) -> None: ... + def register_post_hook( + self, hook_id: int, hook: Callable[[PostHookArgs], None] + ) -> None: ... + def unregister_post_hook(self, hook_id: int) -> None: ... + @overload + def broadcast( + self, + tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def broadcast( + self, + tensor: Tensor, + root: int, + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def allreduce( + self, + tensors: list[Tensor], + opts: AllreduceOptions = ..., + ) -> Work: ... + @overload + def allreduce( + self, + tensors: list[Tensor], + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def allreduce( + self, + tensor: Tensor, + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + def allreduce_coalesced( + self, + tensors: list[Tensor], + opts=..., + ) -> Work: ... + def reduce_scatter_single_coalesced( + self, + outputTensors: list[Tensor], + inputTensors: list[Tensor], + opts: ReduceScatterOptions | None = None, + ) -> Work: ... + def reduce_scatter_tensor_coalesced( + self, + outputTensors: list[Tensor], + inputTensors: list[Tensor], + opts: ReduceScatterOptions | None = None, + ) -> Work: ... + @overload + def reduce( + self, + tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def reduce( + self, + tensor: Tensor, + root: int, + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def allgather( + self, + output_tensors: list[list[Tensor]], + input_tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def allgather( + self, + output_tensors: list[Tensor], + input_tensor: Tensor, + timeout: timedelta | None = None, + ) -> Work: ... + def all_gather_single( + self, + output: Tensor, + input: Tensor, + opts=..., + ) -> Work: ... + def _allgather_base( + self, + output: Tensor, + input: Tensor, + opts=..., + ) -> Work: ... + def allgather_coalesced( + self, + output_lists: list[list[Tensor]], + input_list: list[Tensor], + opts=..., + ) -> Work: ... + def all_gather_single_coalesced( + self, + output_lists: list[Tensor], + input_list: list[Tensor], + opts=..., + ) -> Work: ... + def allgather_into_tensor_coalesced( + self, + output_lists: list[Tensor], + input_list: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def gather( + self, + output_tensors: list[list[Tensor]], + input_tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def gather( + self, + output_tensors: list[Tensor], + input_tensor: Tensor, + root: int, + timeout: timedelta | None = None, + ) -> Work: ... + def gather_single( + self, + output: Tensor, + input: Tensor, + opts=..., + ) -> Work: ... + def gather_into_tensor( + self, + output: Tensor, + input: Tensor, + opts=..., + ) -> Work: ... + @overload + def scatter( + self, + output_tensors: list[Tensor], + input_tensors: list[list[Tensor]], + opts=..., + ) -> Work: ... + @overload + def scatter( + self, + output_tensor: Tensor, + input_tensors: list[Tensor], + root: int, + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def reduce_scatter( + self, + output_tensors: list[Tensor], + input_tensors: list[list[Tensor]], + opts=..., + ) -> Work: ... + @overload + def reduce_scatter( + self, + output_tensors: Tensor, + input_tensor: list[Tensor], + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + def reduce_scatter_single( + self, + outputTensor: Tensor, + inputTensor: Tensor, + opts: ReduceScatterOptions | None, + ) -> Work: ... + def _reduce_scatter_base( + self, + outputTensor: Tensor, + inputTensor: Tensor, + opts: ReduceScatterOptions | None, + ) -> Work: ... + @overload + def all_to_all_single( + self, + output_tensor: Tensor, + input_tensor: Tensor, + output_split_sizes: list[int], + input_split_sizes: list[int], + opts=..., + ) -> Work: ... + @overload + def all_to_all_single( + self, + output: Tensor, + input: Tensor, + output_split_sizes: list[int], + input_split_sizes: list[int], + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def alltoall_base( + self, + output_tensor: Tensor, + input_tensor: Tensor, + output_split_sizes: list[int], + input_split_sizes: list[int], + opts=..., + ) -> Work: ... + @overload + def alltoall_base( + self, + output: Tensor, + input: Tensor, + output_split_sizes: list[int], + input_split_sizes: list[int], + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def alltoall( + self, + output_tensor: list[Tensor], + input_tensor: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def alltoall( + self, + output: list[Tensor], + input: list[Tensor], + timeout: timedelta | None = None, + ) -> Work: ... + def send( + self, + tensors: list[Tensor], + dstRank: int, + tag: int, + ) -> Work: ... + def recv( + self, + tensors: list[Tensor], + srcRank: int, + tag: int, + ) -> Work: ... + def recv_anysource(self, tensors: list[Tensor], tag: int) -> Work: ... + @overload + def barrier(self, opts=...) -> Work: ... + @overload + def barrier(self, timeout: timedelta | None = None) -> Work: ... + def boxed(self) -> ScriptObject: ... + @staticmethod + def unbox(obj: ScriptObject) -> ProcessGroup: ... + def _start_coalescing(self, device: torch.device) -> None: ... + def _end_coalescing(self, device: torch.device) -> Work: ... + def _get_backend_name(self) -> str: ... + def _backend_id(self, backend_type: BackendType) -> int: ... + @property + def _device_types(self) -> list[torch.device]: ... + def get_backend(self, device: torch.device) -> Backend: ... + def _get_backend(self, device: torch.device) -> Backend: ... + def _set_default_backend(self, backend_type: BackendType) -> None: ... + def _register_backend( + self, + device: torch.device, + backend_type: BackendType, + backend: Backend | None, + ) -> None: ... + def _set_group_name(self, name: GroupName) -> None: ... + def _set_group_desc(self, desc: str) -> None: ... + def name(self) -> str: ... + def _has_hooks(self) -> bool: ... + def _wait_for_pending_works(self) -> None: ... + @property + def bound_device_id(self) -> torch.device | None: ... + @bound_device_id.setter + def bound_device_id(self, device: torch.device | None) -> None: ... + @property + def use_pg_for_symm_mem_rendezvous(self) -> bool: + """When True, symmetric memory rendezvous exchanges metadata via this + PG's NCCL allgather instead of TCPStore, which gets overloaded at large + rank counts. This will lazily create the NCCL communicator if it doesn't + already exist. If this PG is only used for symmetric memory (no regular + collectives), consider calling ``abort()`` after rendezvous to release + the communicator.""" + @use_pg_for_symm_mem_rendezvous.setter + def use_pg_for_symm_mem_rendezvous(self, value: bool) -> None: ... + @property + def group_name(self) -> GroupName: ... + @property + def group_desc(self) -> str: ... + +class FakeProcessGroup(Backend): + @staticmethod + def _create_internal(rank: int, world_size: int) -> FakeProcessGroup: ... + +class FakeWork(Work): + seq_id: int + def __init__(self) -> None: ... + def wait(self, timeout: timedelta = ...) -> bool: ... + def getFuture(self) -> Future: ... + +class NCCLXStub(Backend): + def __init__( + self, + store: Store, + rank: int, + size: int, + options: ProcessGroupNCCL.Options = ..., + ) -> None: ... + +class PythonCallbackWork(Work): + def __init__(self, callback: Callable[[timedelta], bool]) -> None: ... + def wait(self, timeout: timedelta = ...) -> bool: ... + def get_future(self) -> Future: ... + +class ProcessGroupGloo(Backend): + class Device: ... + + class Options(Backend.Options): + devices: list[ProcessGroupGloo.Device] + threads: int + + def __init__(self): ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + timeout: timedelta = ..., + enable_reconfigure: bool = ..., + ) -> None: ... + @staticmethod + def create_device(hostname="", interface="", lazy_init=None) -> Device: ... + @staticmethod + def create_default_device(lazy_init=None) -> Device: ... + def _set_default_timeout(self, timeout) -> None: ... + @property + def options(self) -> Options: ... # type: ignore[override] + +class _ProcessGroupWrapper(Backend): + def __init__(self, pg: Backend, gloo_pg: ProcessGroupGloo) -> None: ... + wrapped_pg: Backend + @property + def options(self) -> Backend.Options: ... + def get_error(self) -> ErrorType: ... + +class ErrorType(Enum): + SUCCESS = ... + TIMEOUT = ... + COMM_ERROR = ... + REMOTE_ERROR = ... + +class ProcessGroupNCCL(Backend): + class NCCLConfig: + blocking: int + cga_cluster_size: int + min_ctas: int + max_ctas: int + def unsafe_get_ptr(self) -> int: ... + + class Options(Backend.Options): + config: ProcessGroupNCCL.NCCLConfig + is_high_priority_stream: bool + split_from: ProcessGroupNCCL + split_color: int + + def __init__(self, is_high_priority_stream: bool = False): ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + options: Options, + ) -> None: ... + def _group_start(self) -> None: ... + def _group_end(self) -> None: ... + def _start_time_estimate(self) -> None: ... + def _end_time_estimate(self) -> float: ... + def _set_default_timeout(self, timeout) -> None: ... + def perform_nocolor_split(self, device: torch.device) -> None: ... + def register_mem_pool( + self, pool: torch.cuda.MemPool, symm: bool = False + ) -> None: ... + def deregister_mem_pool(self, pool: torch.cuda.MemPool) -> None: ... + def comm_split_count(self) -> int: ... + def abort(self) -> None: ... + def _is_initialized(self) -> bool: ... + @property + def uid(self) -> int: ... + @property + def options(self) -> Options: ... # type: ignore[override] + @staticmethod + def get_build_nccl_version(self) -> tuple[int, int, int]: ... + @staticmethod + def get_runtime_nccl_version(self) -> tuple[int, int, int]: ... + +class ProcessGroupUCC(Backend): + def __init__( + self, + store: Store, + rank: int, + size: int, + timeout: timedelta, + ) -> None: ... + +class ProcessGroupMPI(Backend): + def __init__( + self, + rank: int, + size: int, + pgComm: int, + ) -> None: ... + @staticmethod + def create(ranks: list[int]) -> ProcessGroupMPI: ... + +def _compute_bucket_assignment_by_size( + tensors: list[Tensor], + bucket_size_limits: list[int], + expect_sparse_gradient: list[bool] = ..., + tensor_indices: list[int] = ..., +) -> tuple[list[list[int]], list[int]]: ... +def _broadcast_coalesced( + process_group: ProcessGroup, + tensors: list[Tensor], + buffer_size: int, + src: int, +): ... +def _test_python_store(store: Store): ... +def _verify_params_across_processes( + process_group: ProcessGroup, + params: list[Tensor], + logger: Logger | None, +): ... +def _make_nccl_premul_sum(factor: float | Tensor) -> ReduceOp: ... +def _register_process_group( + group_name: GroupName, + process_group: ProcessGroup, +) -> None: ... +def _resolve_process_group(group_name: GroupName) -> ProcessGroup: ... +def _create_work_from_future(future: Future) -> Work: ... +def _register_work(tensor: torch.Tensor, work: Work) -> ProcessGroup: ... +def _get_work_registry_size() -> int: ... +def _set_allow_inflight_collective_as_graph_input( + value: bool, +) -> None: ... +def _allow_inflight_collective_as_graph_input() -> bool: ... +def _unregister_all_process_groups() -> None: ... +def _unregister_process_group(group_name: GroupName) -> None: ... + +# Initializes the device state in CUmodule so that it's able to perform NVSHMEM +# operations. CUmodule is a pointer to a CUDA module, carried by a int64 in +# Python. At C++ interface, it is converted to a uintptr_t. +def _nvshmemx_cumodule_init(module: int) -> None: ... + +# Check if NVSHMEM is available on current system. +def _is_nvshmem_available() -> bool: ... +def _register_external_nccl_comm( + group_name: str, comm_ptr: int, device: torch.device +) -> None: ... +def _unregister_external_nccl_comm(group_name: str, device: torch.device) -> None: ... + +# NCCL EP (contrib/nccl_ep) bindings; only registered in USE_C10D_NCCL builds. +class _NcclEpGroup: + @staticmethod + def create( + pg: ProcessGroup, + num_experts: int, + max_dispatch_tokens_per_rank: int, + max_recv_tokens_per_rank: int, + max_token_bytes: int, + ) -> _NcclEpGroup: ... + +class _NcclEpHandle: + @staticmethod + def create( + group: _NcclEpGroup, + topk_idx: Tensor, + recv_expert_counter: Tensor | None = None, + ) -> _NcclEpHandle: ... + def get_num_recv_tokens(self) -> int: ... + +# handle is Any: the Python layer (torch.distributed._token_switch.Routing) +# holds it opaquely as `object`, so callers don't carry the concrete type. +def _nccl_ep_dispatch( + handle: Any, + tokens: Tensor, + topk_weights: Tensor, + out_tokens: Tensor, + out_topk_weights: Tensor, + out_topk_idx: Tensor, +) -> None: ... +def _nccl_ep_combine( + handle: Any, + expert_tokens: Tensor, + out_tokens: Tensor, +) -> None: ... + +class _SymmetricMemory: + @staticmethod + def set_group_info( + group_name: str, + rank: int, + world_size: int, + store: Store, + ) -> None: ... + @staticmethod + def empty_strided_p2p( + size: torch.types._size, + stride: torch.types._size, + dtype: torch.dtype, + device: torch.device, + group_name: str | None = None, + alloc_id: int | None = None, + ) -> torch.Tensor: ... + @staticmethod + def has_multicast_support( + device_type: DeviceType, + device_idx: int, + ) -> bool: ... + # Set Symmetric Memory allocation backend. + @staticmethod + def set_backend(name: str) -> None: ... + @staticmethod + def get_backend(device: torch.device) -> str | None: ... + @staticmethod + def is_symm_mem_tensor(tensor: torch.Tensor) -> bool: ... + @staticmethod + def get_mempool_allocator(device: torch.device) -> Any: ... + signal_pad_size: int + @property + def rank(self) -> int: ... + @property + def world_size(self) -> int: ... + @staticmethod + def rendezvous( + tensor: torch.Tensor, group_name: str | None = None + ) -> _SymmetricMemory: ... + def boxed(self) -> ScriptObject: ... + def get_buffer( + self, + rank: int, + sizes: torch.types._size, + dtype: torch.dtype, + storage_offset: int | None = 0, + ) -> torch.Tensor: ... + def get_signal_pad( + self, + rank: int, + sizes: torch.types._size = [], + dtype: torch.dtype | None = None, + storage_offset: int | None = 0, + ) -> torch.Tensor: ... + def barrier(self, channel: int = 0, timeout_ms: int = 0) -> None: ... + def put_signal( + self, + dst_rank: int, + channel: int = 0, + timeout_ms: int = 0, + ) -> None: ... + def wait_signal( + self, + src_rank: int, + channel: int = 0, + timeout_ms: int = 0, + ) -> None: ... + def get_remote_tensor( + self, + peer: int, + sizes: torch.types._size, + dtype: torch.dtype, + ) -> torch.Tensor: ... + @staticmethod + def memset32( + tensor: torch.Tensor, offset: int, val: int, count: int = 1 + ) -> torch.Tensor: ... + @staticmethod + def stream_write_value32( + tensor: torch.Tensor, offset: int, val: int + ) -> torch.Tensor: ... + @property + def buffer_ptrs(self) -> list[int]: ... + @property + def buffer_ptrs_dev(self) -> int: ... + @property + def signal_pad_ptrs(self) -> list[int]: ... + @property + def signal_pad_ptrs_dev(self) -> int: ... + @property + def multicast_ptr(self) -> int: ... + @property + def buffer_size(self) -> int: ... + @property + def offset(self) -> int: ... + @property + def device(self) -> torch.device: ... + +class ProcessGroupXCCL(Backend): + class Options(Backend.Options): + is_high_priority_stream: bool + + def __init__(self, is_high_priority_stream: bool = False): ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + options: Options, + ) -> None: ... + @property + def options(self) -> Options: ... # type: ignore[override] + @property + def uid(self) -> int: ... + def _is_initialized(self) -> bool: ... + def _set_enable_nan_check(self, enable_nan_check: bool) -> None: ... + def _set_default_timeout(self, timeout) -> None: ... + def _dump_xccl_trace_json( + self, includeCollectives: bool = False, onlyActive: bool = False + ) -> str: ... + def _reset_fr_recording_xccl(self) -> None: ... + +class ProcessGroupNCCL2(Backend): + Options = ProcessGroupNCCL.Options + + def __init__( + self, + store: Store, + rank: int, + size: int, + options: ProcessGroupNCCL.Options, + ) -> None: ... + def get_error(self) -> ErrorType: ... + @property + def options(self) -> ProcessGroupNCCL.Options: ... + +class ProcessGroupNCCLLazy(Backend): + def __init__( + self, + store: Store, + rank: int, + size: int, + options: ProcessGroupNCCL.Options, + ) -> None: ... + def get_error(self) -> ErrorType: ... + def _num_active_channels(self) -> int: ... + +class FlightRecorderHook: + @staticmethod + def attach(pg: ProcessGroup) -> FlightRecorderHook: ... + def remove(self) -> None: ... + +class NanCheckHook: + @staticmethod + def attach(pg: ProcessGroup) -> NanCheckHook: ... + def remove(self) -> None: ... + +def _set_process_group(pg: ProcessGroup) -> None: ... +def _current_process_group() -> ProcessGroup: ... + +class _Request: + def body(self) -> bytes: ... + def get_param(self, str) -> str: ... + +class _Response: + def set_content(self, content: str | bytes, content_type: str) -> None: ... + def set_status(self, status: int) -> None: ... + +def _register_handler( + name: str, handler: Callable[[_Request, _Response], None] +) -> None: ... +def _set_comm_profiling_name(name: str) -> None: ... +def _get_comm_profiling_name() -> str: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ff0e5b8379a20da0e7760a042fa0df333b6572ca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc.pyi @@ -0,0 +1,188 @@ +# mypy: allow-untyped-defs +# mypy: disable-error-code="type-arg" +from datetime import timedelta +from typing import Any, Generic, overload, TypeVar + +import torch +from torch._C import Future +from torch._C._autograd import ProfilerEvent +from torch._C._distributed_c10d import Store +from torch._C._profiler import ProfilerConfig + +# This module is defined in torch/csrc/distributed/rpc/init.cpp + +_DEFAULT_INIT_METHOD: str +_DEFAULT_NUM_WORKER_THREADS: int +_UNSET_RPC_TIMEOUT: float +_DEFAULT_RPC_TIMEOUT_SEC: float + +_T = TypeVar("_T") + +class RpcBackendOptions: + rpc_timeout: float + init_method: str + def __init__( + self, + rpc_timeout: float = ..., + init_method: str = ..., + ) -> None: ... + +class WorkerInfo: + def __init__(self, name: str, worker_id: int) -> None: ... + @property + def name(self) -> str: ... + @property + def id(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + +class RpcAgent: + def join(self, shutdown: bool = False, timeout: float = 0): ... + def sync(self): ... + def shutdown(self): ... + @overload + def get_worker_info(self) -> WorkerInfo: ... + @overload + def get_worker_info(self, workerName: str) -> WorkerInfo: ... + def get_worker_infos(self) -> list[WorkerInfo]: ... + def _get_device_map(self, dst: WorkerInfo) -> dict[torch.device, torch.device]: ... + def get_debug_info(self) -> dict[str, str]: ... + def get_metrics(self) -> dict[str, str]: ... + +class PyRRef(Generic[_T]): + def __init__(self, value: _T, type_hint: Any = None) -> None: ... + def is_owner(self) -> bool: ... + def confirmed_by_owner(self) -> bool: ... + def owner(self) -> WorkerInfo: ... + def owner_name(self) -> str: ... + def to_here(self, timeout: float = ...) -> _T: ... + def local_value(self) -> Any: ... + def rpc_sync(self, timeout: float = ...) -> Any: ... + def rpc_async(self, timeout: float = ...) -> Any: ... + def remote(self, timeout: float = ...) -> Any: ... + def _serialize(self) -> tuple: ... + @staticmethod + def _deserialize(tp: tuple) -> PyRRef: ... + def _get_type(self) -> type[_T]: ... + def _get_future(self) -> Future[_T]: ... + def _get_profiling_future(self) -> Future[_T]: ... + def _set_profiling_future(self, profilingFuture: Future[_T]): ... + +class _TensorPipeRpcBackendOptionsBase(RpcBackendOptions): + num_worker_threads: int + device_maps: dict[str, dict[torch.device, torch.device]] + devices: list[torch.device] + def __init__( + self, + num_worker_threads: int, + _transports: list | None, + _channels: list | None, + rpc_timeout: float = ..., + init_method: str = ..., + device_maps: dict[str, dict[torch.device, torch.device]] = {}, + devices: list[torch.device] = [], + ) -> None: ... + def _set_device_map( + self, + to: str, + device_map: dict[torch.device, torch.device], + ): ... + +class TensorPipeAgent(RpcAgent): + def __init__( + self, + store: Store, + name: str, + worker_id: int, + world_size: int | None, + opts: _TensorPipeRpcBackendOptionsBase, + reverse_device_maps: dict[str, dict[torch.device, torch.device]], + devices: list[torch.device], + ) -> None: ... + def join(self, shutdown: bool = False, timeout: float = 0): ... + def shutdown(self): ... + @overload + def get_worker_info(self) -> WorkerInfo: ... + @overload + def get_worker_info(self, workerName: str) -> WorkerInfo: ... + @overload + def get_worker_info(self, id: int) -> WorkerInfo: ... + def get_worker_infos(self) -> list[WorkerInfo]: ... + def _get_device_map(self, dst: WorkerInfo) -> dict[torch.device, torch.device]: ... + def _update_group_membership( + self, + worker_info: WorkerInfo, + my_devices: list[torch.device], + reverse_device_map: dict[str, dict[torch.device, torch.device]], + is_join: bool, + ): ... + def _get_backend_options(self) -> _TensorPipeRpcBackendOptionsBase: ... + @property + def is_static_group(self) -> bool: ... + @property + def store(self) -> Store: ... + +def _is_current_rpc_agent_set() -> bool: ... +def _get_current_rpc_agent() -> RpcAgent: ... +def _set_and_start_rpc_agent(agent: RpcAgent): ... +def _reset_current_rpc_agent(): ... +def _delete_all_user_and_unforked_owner_rrefs(timeout: timedelta = ...): ... +def _destroy_rref_context(ignoreRRefLeak: bool): ... +def _rref_context_get_debug_info() -> dict[str, str]: ... +def _cleanup_python_rpc_handler(): ... +def _invoke_rpc_builtin( + dst: WorkerInfo, + opName: str, + rpcTimeoutSeconds: float, + *args: Any, + **kwargs: Any, +): ... +def _invoke_rpc_python_udf( + dst: WorkerInfo, + pickledPythonUDF: str, + tensors: list[torch.Tensor], + rpcTimeoutSeconds: float, + isAsyncExecution: bool, +): ... +def _invoke_rpc_torchscript( + dstWorkerName: str, + qualifiedNameStr: str, + argsTuple: tuple, + kwargsDict: dict, + rpcTimeoutSeconds: float, + isAsyncExecution: bool, +): ... +def _invoke_remote_builtin( + dst: WorkerInfo, + opName: str, + rpcTimeoutSeconds: float, + *args: Any, + **kwargs: Any, +): ... +def _invoke_remote_python_udf( + dst: WorkerInfo, + pickledPythonUDF: str, + tensors: list[torch.Tensor], + rpcTimeoutSeconds: float, + isAsyncExecution: bool, +): ... +def _invoke_remote_torchscript( + dstWorkerName: WorkerInfo, + qualifiedNameStr: str, + rpcTimeoutSeconds: float, + isAsyncExecution: bool, + *args: Any, + **kwargs: Any, +): ... +def get_rpc_timeout() -> float: ... +def enable_gil_profiling(flag: bool): ... +def _set_rpc_timeout(rpcTimeoutSeconds: float): ... + +class RemoteProfilerManager: + @staticmethod + def set_current_profiling_key(key: str): ... + +def _enable_server_process_global_profiler(new_config: ProfilerConfig): ... +def _disable_server_process_global_profiler() -> list[list[list[ProfilerEvent]]]: ... +def _set_profiler_node_id(default_node_id: int): ... +def _enable_jit_rref_pickle(): ... +def _disable_jit_rref_pickle(): ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc_testing.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc_testing.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9313281027dbd89ae65ebe65c95a1d0c38593b80 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc_testing.pyi @@ -0,0 +1,32 @@ +import torch +from torch._C._distributed_c10d import Store +from torch._C._distributed_rpc import _TensorPipeRpcBackendOptionsBase, TensorPipeAgent + +# This module is defined in torch/csrc/distributed/rpc/testing/init.cpp + +class FaultyTensorPipeRpcBackendOptions(_TensorPipeRpcBackendOptionsBase): + def __init__( + self, + num_worker_threads: int, + rpc_timeout: float, + init_method: str, + messages_to_fail: list[str], + messages_to_delay: dict[str, float], + num_fail_sends: int, + ) -> None: ... + num_send_recv_threads: int + messages_to_fail: list[str] + messages_to_delay: dict[str, float] + num_fail_sends: int + +class FaultyTensorPipeAgent(TensorPipeAgent): + def __init__( + self, + store: Store, + name: str, + rank: int, + world_size: int, + options: FaultyTensorPipeRpcBackendOptions, + reverse_device_maps: dict[str, dict[torch.device, torch.device]], + devices: list[torch.device], + ) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/__init__.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..06107eca199d7cc902b86d56a4e331e404c46d82 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/__init__.pyi @@ -0,0 +1,72 @@ +from . import compiled_autograd, eval_frame, guards # noqa: F401 + +def strip_function_call(name: str) -> str: ... +def is_valid_var_name(name: str) -> bool | int: ... +def get_type_slots(obj: type | object) -> tuple[int, int, int, int]: ... +def has_slot(slots: int, slot_bit: int) -> bool: ... + +class PySequenceSlots: + SQ_LENGTH: int + SQ_CONCAT: int + SQ_REPEAT: int + SQ_ITEM: int + SQ_CONTAINS: int + SQ_ASS_ITEM: int + SQ_INPLACE_CONCAT: int + SQ_INPLACE_REPEAT: int + +class PyMappingSlots: + MP_LENGTH: int + MP_SUBSCRIPT: int + MP_ASS_SUBSCRIPT: int + +class PyNumberSlots: + NB_ADD: int + NB_SUBTRACT: int + NB_MULTIPLY: int + NB_REMAINDER: int + NB_POWER: int + NB_NEGATIVE: int + NB_POSITIVE: int + NB_ABSOLUTE: int + NB_BOOL: int + NB_INVERT: int + NB_LSHIFT: int + NB_RSHIFT: int + NB_AND: int + NB_XOR: int + NB_OR: int + NB_INT: int + NB_FLOAT: int + NB_INPLACE_ADD: int + NB_INPLACE_SUBTRACT: int + NB_INPLACE_MULTIPLY: int + NB_INPLACE_REMAINDER: int + NB_INPLACE_POWER: int + NB_INPLACE_LSHIFT: int + NB_INPLACE_RSHIFT: int + NB_INPLACE_AND: int + NB_INPLACE_XOR: int + NB_INPLACE_OR: int + NB_FLOOR_DIVIDE: int + NB_TRUE_DIVIDE: int + NB_INPLACE_FLOOR_DIVIDE: int + NB_INPLACE_TRUE_DIVIDE: int + NB_INDEX: int + NB_MATRIX_MULTIPLY: int + NB_INPLACE_MATRIX_MULTIPLY: int + NB_DIVMOD: int + +class PyTypeSlots: + TP_HASH: int + TP_ITER: int + TP_ITERNEXT: int + TP_CALL: int + TP_REPR: int + TP_RICHCOMPARE: int + TP_GETATTRO: int + TP_SETATTRO: int + TP_DESCR_GET: int + TP_DESCR_SET: int + TP_STR: int + TP_INIT: int diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/compiled_autograd.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/compiled_autograd.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ef24582b5023109733955cc77db0a84fae03b3fd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/compiled_autograd.pyi @@ -0,0 +1,13 @@ +from collections.abc import Callable + +from torch import Tensor +from torch._dynamo.compiled_autograd import AutogradCompilerInstance + +def set_autograd_compiler( + autograd_compiler: Callable[[], AutogradCompilerInstance] | None, + dynamic: bool, +) -> tuple[Callable[[], AutogradCompilerInstance] | None, bool]: ... +def clear_cache() -> None: ... +def is_cache_empty() -> bool: ... +def set_verbose_logger(fn: Callable[[str], None] | None) -> bool: ... +def call_cpp_tensor_pre_hooks(idx: int, grad: Tensor) -> Tensor: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/eval_frame.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/eval_frame.pyi new file mode 100644 index 0000000000000000000000000000000000000000..303b669659e39c87214be22c868af24b9670bc3f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/eval_frame.pyi @@ -0,0 +1,106 @@ +import enum +import types +from collections.abc import Callable +from typing import overload + +from torch._dynamo.guards import GuardManagerWrapper +from torch._dynamo.types import DynamoCallback, DynamoGuardCompleteHook, DynamoGuardHook +from torch._guards import CompileId + +def set_eval_frame(callback: DynamoCallback) -> DynamoCallback: ... +def set_skip_guard_eval_unsafe(value: bool) -> bool: ... +def get_eval_frame_callback() -> DynamoCallback: ... +def reset_code(code: types.CodeType) -> None: ... +def unsupported(obj1: object, obj2: object) -> object: ... +def set_code_exec_strategy( + code: types.CodeType, strategy: _FrameExecStrategy +) -> None: ... +def set_guard_error_hook(hook: DynamoGuardHook) -> None: ... +def set_guard_complete_hook( + hook: DynamoGuardCompleteHook | None, +) -> DynamoGuardCompleteHook | None: ... +def raise_sigtrap() -> None: ... +def get_method_ml_flags(fn: object) -> int | None: ... +def set_c_recursion_limit(limit: int) -> None: ... +def get_c_recursion_limit() -> int: ... + +class _CacheEntry: + def check_fn(self, *args: object, **kwargs: object) -> bool: ... + def update_diff_guard_root_manager(self) -> None: ... + code: types.CodeType + compile_id: CompileId + # If we run into circular issues, just use object + guard_manager: GuardManagerWrapper + backend: Callable + isolate_recompiles_id: int + +class _PrecompileEntry: + guard_manager: GuardManagerWrapper + +class _ExtraState: + def invalidate( + self, cache_entry: _CacheEntry, guard_manager: GuardManagerWrapper + ) -> None: ... + +class _FrameAction(enum.IntEnum): + DEFAULT = 0 + SKIP = 1 + RUN_ONLY = 2 + +class _FrameExecStrategy: + cur_action: _FrameAction + recursive_action: _FrameAction + + @overload + def __init__(self) -> None: ... + @overload + def __init__( + self, cur_action: _FrameAction, recursive_action: _FrameAction + ) -> None: ... + +# This is an object that encapsulates the Python FrameType, and exposes +# properties Dynamo cares about for a frame. +class _PyInterpreterFrame: + f_code: types.CodeType + f_locals: dict[str, object] + f_globals: dict[str, object] + f_builtins: dict[str, object] + f_lasti: int + f_lineno: int + f_back: types.FrameType + # A tuple containing cell objects captured by this frame. + closure: tuple[types.CellType] + +def _debug_get_cache_entry_list(code: types.CodeType) -> list[_CacheEntry]: ... +def _get_cache_entries_for_region( + code: types.CodeType, isolate_recompiles_id: int +) -> list[_CacheEntry]: ... +def _get_total_cache_entry_count(code: types.CodeType) -> int: ... +def _get_frame_value_stack_with_depth( + frame: types.FrameType, depth: int +) -> list[object]: ... +def set_bytecode_debugger_callback( + callback: Callable[[types.CodeType], None] | None, +) -> None: ... +def get_bytecode_debugger_callback() -> Callable[[types.CodeType], None] | None: ... +def register_breakpoint_code(code: types.CodeType) -> None: ... + +# Sentinel for NULL stack values returned by _get_frame_value_stack_at_depth +class NullStackValue: ... + +NULL_STACK_VALUE: NullStackValue + +py_opcode_caches: list[int] + +def code_framelocals_names(code: types.CodeType) -> tuple[str, ...]: ... +def _load_precompile_entry( + code: types.CodeType, + guard_manager: GuardManagerWrapper, + dynamo_code: types.CodeType, +) -> None: ... +def _reset_precompile_entries(code: types.CodeType) -> None: ... +def _debug_get_precompile_entries(code: types.CodeType) -> list[_PrecompileEntry]: ... +def set_fullgraph_compiled_frame_count(value: int) -> int: ... +def set_fullgraph_error_on_nested_compile(value: bool) -> bool: ... +def set_eval_frame_isolate_recompiles_id(isolate_recompiles_id: int) -> int: ... +def get_eval_frame_isolate_recompiles_id() -> int: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/guards.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/guards.pyi new file mode 100644 index 0000000000000000000000000000000000000000..baafdfffa03c0f8c6ab6f1e8cdd43d97cf660940 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/guards.pyi @@ -0,0 +1,519 @@ +import enum +import traceback +from collections.abc import Callable, Sequence +from typing import Any, TypeAlias + +import torch + +# TODO: We should move the `GuardManagerType` +# defined in `guards.py` here and update other +# imports +GuardManagerType: TypeAlias = enum.Enum + +class GlobalStateGuard: + def check(self) -> bool: ... + def reason(self) -> str: ... + +class LeafGuard: + def verbose_code_parts(self) -> list[str]: ... + +class RelationalGuard: ... + +class GuardDebugInfo: + verbose_code_parts: list[str] + result: bool + num_guards_executed: int + user_stack: traceback.StackSummary | None + +class LocalState: ... + +class GuardManager: + def check(self, value: Any) -> bool: ... + def check_verbose(self, value: Any) -> GuardDebugInfo: ... + + # Accessors + def globals_dict_manager( + self, + f_globals: dict[str, Any], + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def framelocals_manager( + self, + key: tuple[str, int], + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def dict_getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def grad_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def generic_getattr_manager( + self, + attr: str, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_generic_dict_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def list_getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tuple_getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def set_getitem_manager( + self, + index: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def func_defaults_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def func_kwdefaults_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tuple_iterator_getitem_manager( + self, + index: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def weakref_call_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def call_function_no_args_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def global_weakref_manager( + self, + global_name: str, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def type_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def getattr_manager( + self, + attr: str, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tensor_property_size_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tensor_property_shape_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tensor_property_storage_offset_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def indexed_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def lambda_manager( + self, + python_lambda: Callable[..., Any], + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_root(self) -> RootGuardManager: ... + def get_source(self) -> str: ... + def fail_count(self) -> int: ... + def get_child_managers(self) -> list[GuardManager]: ... + def repr(self) -> str: ... + def type_of_guarded_value(self) -> str: ... + def get_leaf_guards(self) -> list[LeafGuard]: ... + def get_accessors(self) -> list[GuardManager]: ... + def is_guarded_value_immutable(self) -> bool: ... + def is_tag_safe(self) -> bool: ... + def is_tag_safe_root(self) -> bool: ... + def has_no_accessors(self) -> bool: ... + def has_object_aliasing_guard(self) -> bool: ... + def get_type_of_guarded_value(self) -> type: ... + def type_dict_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def type_mro_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def code_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def closure_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + # Leaf guards + def add_lambda_guard( + self, + user_lambda: Callable[..., Any], + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_id_match_guard( + self, + id_val: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_equals_match_guard( + self, + equals_val: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_global_state_guard( + self, + initial_state: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_torch_function_mode_stack_guard( + self, + initial_stack: list[Any], + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_mapping_keys_guard( + self, + value: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_dict_length_check_guard( + self, + value: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_length_check_guard( + self, + value: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_true_match_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_false_match_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_none_match_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_not_none_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_dispatch_key_set_guard( + self, + dispatch_key: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_tensor_match_guard( + self, + value: Any, + sizes: list[int], + strides: list[int], + tensor_name: str, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ptype: Any, + dispatch_keys: Any, + ) -> None: ... + def add_dimension_marking_guard( + self, + expected_attrs: dict[str, set[int]], + absent_attrs: list[str], + dependent_attrs: dict[str, tuple[dict[int, Any] | None, str]], + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_no_hasattr_guard( + self, + attr_name: str, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_dict_contains_guard( + self, + contains: bool, + key: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_type_match_guard( + self, + value: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_fake_script_type_match_guard( + self, + fake_script_object_type: type, + type_id: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_dict_version_guard( + self, + value: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_set_contains_guard( + self, + contains: bool, + item: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_dual_level_match_guard( + self, + level: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_float_is_nan_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_complex_is_nan_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_tuple_iterator_length_guard( + self, + length: int, + type_id: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_range_iterator_match_guard( + self, + start: int, + stop: int, + step: int, + type_id: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_default_device_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def mark_tag_safe(self) -> None: ... + def mark_tag_safe_root(self) -> None: ... + +class RootGuardManager(GuardManager): + def get_epilogue_lambda_guards(self) -> list[LeafGuard]: ... + def add_epilogue_lambda_guard( + self, + guard: LeafGuard, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def clone_manager( + self, clone_filter_fn: Callable[[GuardManager], bool] + ) -> RootGuardManager: ... + def attach_compile_id(self, compile_id: str) -> None: ... + def get_local_state(self) -> LocalState: ... + def set_local_state(self, local_state: LocalState) -> None: ... + +class DictGuardManager(GuardManager): + def get_key_manager( + self, + index: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_value_manager( + self, + index: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_key_value_managers( + self, + ) -> dict[int, tuple[GuardManager, GuardManager]]: ... + +# Guard accessor stubs +class GuardAccessor: ... +class DictGetItemGuardAccessor(GuardAccessor): ... +class GetGenericDictGuardAccessor(GuardAccessor): ... +class TypeDictGuardAccessor(GuardAccessor): ... +class TypeMROGuardAccessor(GuardAccessor): ... +class ClosureGuardAccessor(GuardAccessor): ... +class TupleGetItemGuardAccessor(GuardAccessor): ... +class TypeGuardAccessor(GuardAccessor): ... +class CodeGuardAccessor(GuardAccessor): ... +class FuncDefaultsGuardAccessor(GuardAccessor): ... +class FuncKwDefaultsGuardAccessor(GuardAccessor): ... + +class GetAttrGuardAccessor(GuardAccessor): + def get_attr_name(self) -> str: ... + +def install_object_aliasing_guard( + x: GuardManager, + y: GuardManager, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, +) -> None: ... +def install_no_tensor_aliasing_guard( + guard_managers: list[GuardManager], + tensor_names: list[str], + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, +) -> None: ... +def install_storage_overlapping_guard( + overlapping_guard_managers: list[GuardManager], + non_overlapping_guard_managers: list[GuardManager], + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, +) -> None: ... +def install_symbolic_shape_guard( + guard_managers: list[GuardManager], + nargs_int: int, + nargs_float: int, + py_addr: int, + py_addr_keep_alive: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, +) -> None: ... +def profile_guard_manager( + guard_manager: GuardManager, + f_locals: dict[str, Any], + n_iters: int, +) -> float: ... + +class TensorGuards: + def __init__( + self, + *, + dynamic_dims_sizes: list[torch.SymInt | None] | None = None, + dynamic_dims_strides: list[torch.SymInt | None] | None = None, + ) -> None: ... + def check(self, *args: Any) -> bool: ... + def check_verbose( + self, *args: Any, tensor_check_names: list[str] | None = None + ) -> bool | str: ... + +def assert_size_stride( + item: torch.Tensor, + size: torch.types._size, + stride: torch.types._size, + op_name: str | None = None, +) -> None: ... +def assert_size_stride_grouped( + items: Sequence[torch.Tensor], + sizes: Sequence[torch.types._size], + strides: Sequence[torch.types._size], + op_name: str | None = None, +) -> None: ... +def assert_alignment( + item: torch.Tensor, + alignment: int, + op_name: str | None = None, +) -> None: ... +def copy_if_misaligned(item: torch.Tensor) -> torch.Tensor: ... +def check_obj_id(obj: object, expected: int) -> bool: ... +def check_type_id(obj: object, expected: int) -> bool: ... +def dict_version(d: dict[Any, Any]) -> int: ... +def compute_overlapping_tensors( + tensors: list[torch.Tensor], symbolic: bool = True +) -> set[int]: ... +def set_is_in_mode_without_ignore_compile_internals(value: bool) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_export/__init__.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_export/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..039f9c22eea620bc9675d233684df72c7ac4471c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_export/__init__.pyi @@ -0,0 +1,9 @@ +# Defined in torch/csrc/export/pybind.cpp +class CppExportedProgram: ... + +def deserialize_exported_program( + serialized_program: str, +) -> CppExportedProgram: ... +def serialize_exported_program( + cpp_exported_program: CppExportedProgram, +) -> str: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_export/pt2_archive_constants.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_export/pt2_archive_constants.pyi new file mode 100644 index 0000000000000000000000000000000000000000..08f847e2aeafc7f238eece7071fa4a128a60a104 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_export/pt2_archive_constants.pyi @@ -0,0 +1,26 @@ +# Defined in torch/csrc/export/pt2_archive_constants.h + +ARCHIVE_ROOT_NAME: str = ... +ARCHIVE_FORMAT_PATH: str = ... +ARCHIVE_FORMAT_VALUE: str = ... +ARCHIVE_VERSION_PATH: str = ... +ARCHIVE_VERSION_VALUE: str = ... +MODELS_DIR: str = ... +MODELS_FILENAME_FORMAT: str = ... +AOTINDUCTOR_DIR: str = ... +MTIA_DIR: str = ... +WEIGHTS_DIR: str = ... +WEIGHTS_CONFIG_FILENAME_FORMAT: str = ... +WEIGHT_FILENAME_PREFIX: str = ... +CONSTANTS_DIR: str = ... +CONSTANTS_CONFIG_FILENAME_FORMAT: str = ... +TENSOR_CONSTANT_FILENAME_PREFIX: str = ... +CUSTOM_OBJ_FILENAME_PREFIX: str = ... +OPAQUE_OBJ_FILENAME_PREFIX: str = ... +SAMPLE_INPUTS_DIR: str = ... +SAMPLE_INPUTS_FILENAME_FORMAT: str = ... +EXECUTORCH_DIR: str = ... +EXTRA_DIR: str = ... +MODULE_INFO_PATH: str = ... +XL_MODEL_WEIGHTS_DIR: str = ... +XL_MODEL_WEIGHTS_PARAM_CONFIG_PATH: str = ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_functionalization.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_functionalization.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e00df97e2717c1d3c63db3fc42e31507211eb99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_functionalization.pyi @@ -0,0 +1,16 @@ +from torch import Tensor +from torch.types import _bool + +# Defined in torch/csrc/functionalization/Module.cpp + +class ViewMeta: + has_symbolic_inputs: _bool + +# Returns the list of ViewMeta instances of the given functional tensor. +# +# Although we do have python bindings for their types, we won't +# expose them here, since they should not be used by users. +def get_view_meta_sequence(tensor: Tensor) -> list[ViewMeta]: ... + +# Applies the ViewMeta sequence on top of the given base. +def apply_view_meta_sequence(base: Tensor, sequence: list[ViewMeta]) -> Tensor: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_functions.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_functions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ce0710ae6315d70a60a705fc216ad1b0071f6088 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_functions.pyi @@ -0,0 +1,22 @@ +from typing import AnyStr, overload + +from torch import Tensor + +class AccumulateGrad: + variable: Tensor + +class UndefinedGrad: + def __init__(self) -> None: ... + def __call__(self, *inputs: Tensor) -> list[Tensor]: ... + +class DelayedError: + def __init__(self, msg: AnyStr, num_inputs: int) -> None: ... + + # __call__ should really be a higher-kinded type: + # def __call__(self, arg: Tensor) -> Tensor: ... + # def __call__(self, *args: Tensor * num_inputs) -> Tuple[Tensor * num_inputs]: ... + + @overload + def __call__(self, i0: Tensor) -> Tensor: ... + @overload + def __call__(self, *args: Tensor) -> tuple[Tensor, ...]: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_functorch.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_functorch.pyi new file mode 100644 index 0000000000000000000000000000000000000000..954aa60de7b7445df594f747d9376bfbb2d2f90a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_functorch.pyi @@ -0,0 +1,102 @@ +# mypy: allow-untyped-defs +from enum import Enum +from typing import Any + +from torch import Tensor + +# Defined in torch/csrc/functorch/init.cpp + +def _assert_wrapped_functional( + input_tensor: Tensor, wrapped_tensor: Tensor +) -> None: ... +def _func_decrement_nesting() -> int: ... +def _func_increment_nesting(reapply_views: bool) -> int: ... +def _propagate_functional_input_mutation( + input_tensor: Tensor, wrapped_tensor: Tensor +) -> None: ... +def set_inplace_requires_grad_allowed(allowed: bool) -> None: ... +def get_inplace_requires_grad_allowed() -> bool: ... +def _set_dynamic_layer_keys_included(included: bool) -> None: ... +def get_unwrapped(tensor: Tensor) -> Tensor: ... +def is_batchedtensor(tensor: Tensor) -> bool: ... +def is_functionaltensor(tensor: Tensor) -> bool: ... +def is_functorch_wrapped_tensor(tensor: Tensor) -> bool: ... +def is_gradtrackingtensor(tensor: Tensor) -> bool: ... +def is_legacy_batchedtensor(tensor: Tensor) -> bool: ... +def maybe_get_bdim(tensor: Tensor) -> int: ... +def maybe_get_level(tensor: Tensor) -> int: ... +def maybe_current_level() -> int | None: ... +def unwrap_dead_wrappers(args: tuple[Any, ...]) -> tuple[Any, ...]: ... +def unwrap_if_dead(tensor: Tensor) -> Tensor: ... +def _unwrap_for_grad(tensor: Tensor, level: int) -> Tensor: ... +def _wrap_for_grad(tensor: Tensor, level: int) -> Tensor: ... +def _unwrap_batched(tensor: Tensor, level: int) -> tuple[Tensor, int | None]: ... +def current_level() -> int: ... +def count_jvp_interpreters() -> int: ... +def _add_batch_dim(tensor: Tensor, bdim: int, level: int) -> Tensor: ... +def _remove_batch_dim( + tensor: Tensor, level: int, batch_size: int, out_dim: int +) -> Tensor: ... +def _maybe_unsafe_set_level(tensor: Tensor, level: int) -> None: ... +def set_single_level_autograd_function_allowed(allowed: bool) -> None: ... +def get_single_level_autograd_function_allowed() -> bool: ... +def _unwrap_functional_tensor(tensor: Tensor, reapply_views: bool) -> Tensor: ... +def _wrap_functional_tensor(tensor: Tensor, level: int) -> Tensor: ... +def _vmap_increment_nesting(batch_size: int, randomness: str) -> int: ... +def _vmap_decrement_nesting() -> int: ... +def _grad_increment_nesting() -> int: ... +def _grad_decrement_nesting() -> int: ... +def _jvp_increment_nesting() -> int: ... +def _jvp_decrement_nesting() -> int: ... + +# Defined in aten/src/ATen/functorch/Interpreter.h +class TransformType(Enum): + Torch = ... + Vmap = ... + Grad = ... + Jvp = ... + Functionalize = ... + +class RandomnessType(Enum): + Error = ... + Same = ... + Different = ... + +class CInterpreter: + def key(self) -> TransformType: ... + def level(self) -> int: ... + def serialize(self) -> bytes: ... + @staticmethod + def deserialize(bytes) -> CInterpreter: ... + +class CGradInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def lift(self, Tensor) -> Tensor: ... + def prevGradMode(self) -> bool: ... + +class CJvpInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def lift(self, Tensor) -> Tensor: ... + def prevFwdGradMode(self) -> bool: ... + +class CFunctionalizeInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def key(self) -> TransformType: ... + def level(self) -> int: ... + def functionalizeAddBackViews(self) -> bool: ... + +class CVmapInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def key(self) -> TransformType: ... + def level(self) -> int: ... + def batchSize(self) -> int: ... + def randomness(self) -> RandomnessType: ... + +class DynamicLayer: ... + +def get_dynamic_layer_stack_depth() -> int: ... +def get_interpreter_stack() -> list[CInterpreter]: ... +def peek_interpreter_stack() -> CInterpreter: ... +def pop_dynamic_layer_stack() -> DynamicLayer: ... +def pop_dynamic_layer_stack_and_undo_to_depth(int) -> None: ... +def push_dynamic_layer_stack(dl: DynamicLayer) -> int: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_instruction_counter.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_instruction_counter.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e3c27567eb228b8763a6d2578db827b1ffbde41 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_instruction_counter.pyi @@ -0,0 +1,4 @@ +# Defined in torch/csrc/instruction_counter/Module.cpp + +def start() -> int: ... +def end(id: int) -> int: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_itt.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_itt.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8a54437f527b994821133532f26598c951631b28 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_itt.pyi @@ -0,0 +1,5 @@ +# Defined in torch/csrc/itt.cpp +def is_available() -> None: ... +def rangePush(message: str) -> None: ... +def rangePop() -> None: ... +def mark(message: str) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_jit_tree_views.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_jit_tree_views.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bc7f7c3b7c1e943a33b68f0e8af87e70312fdc52 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_jit_tree_views.pyi @@ -0,0 +1,200 @@ +from typing import Any + +# Defined in torch/csrc/jit/python/python_tree_views.cpp + +class SourceRange: + def highlight(self) -> str: ... + @property + def start(self) -> int: ... + @property + def end(self) -> int: ... + +class SourceRangeFactory: + def __init__( + self, + text: str, + filename: Any, + file_lineno: int, + leading_whitespace_chars: int, + ) -> None: ... + def make_range(self, line: int, start_col: int, end_col: int) -> SourceRange: ... + def make_raw_range(self, start: int, end: int) -> SourceRange: ... + @property + def source(self) -> str: ... + +class TreeView: + def range(self) -> SourceRange: ... + def dump(self) -> None: ... + +class Ident(TreeView): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + @property + def name(self) -> str: ... + +class Param(TreeView): + def __init__(self, type: Any | None, name: Ident, kwarg_only: bool) -> None: ... + +class Attribute(TreeView): + def __init__(self, name: Ident, value: Any) -> None: ... + +# Literals +def TrueLiteral(range: SourceRange) -> Any: ... +def FalseLiteral(range: SourceRange) -> Any: ... +def NoneLiteral(range: SourceRange) -> Any: ... + +# Tree nodes +class Stmt(TreeView): + def __init__(self, thing: TreeView) -> None: ... + +class Expr(TreeView): ... + +class Def(TreeView): + def __init__(self, name: Ident, decl: Any, body: list[Stmt]) -> None: ... + def decl(self) -> Any: ... + def name(self) -> Ident: ... + +class Property(TreeView): + def __init__( + self, r: SourceRange, name: Ident, getter: Def, setter: Def | None + ) -> None: ... + def name(self) -> Ident: ... + def getter_name(self) -> str: ... + def setter_name(self) -> Ident | None: ... + +class ClassDef(TreeView): + def __init__( + self, name: Ident, body: list[Stmt], props: list[Property], assigns: list[Any] + ) -> None: ... + +class Decl(TreeView): + def __init__( + self, r: SourceRange, params: list[Param], return_type: Expr | None + ) -> None: ... + +class Delete(Stmt): + def __init__(self, range: SourceRange, targets: list[Expr]) -> None: ... + +class WithItem(Expr): + def __init__(self, range: SourceRange, target: Expr, var: Any | None) -> None: ... + +class Assign(Stmt): + def __init__( + self, lhs: list[Expr], rhs: Expr, type: Expr | None = None + ) -> None: ... + +class AugAssign(Stmt): + def __init__(self, lhs: Expr, kind_str: str, rhs: Expr) -> None: ... + +class Return(Stmt): + def __init__(self, range: SourceRange, value: Expr | None) -> None: ... + +class Raise(Stmt): + def __init__(self, range: SourceRange, expr: Expr) -> None: ... + +class Assert(Stmt): + def __init__(self, range: SourceRange, test: Expr, msg: Expr | None) -> None: ... + +class Pass(Stmt): + def __init__(self, range: SourceRange) -> None: ... + +class Break(Stmt): ... +class Continue(Stmt): ... + +class Dots(Expr, TreeView): + def __init__(self, range: SourceRange) -> None: ... + +class If(Stmt): + def __init__( + self, + range: SourceRange, + cond: Expr, + true_branch: list[Stmt], + false_branch: list[Stmt], + ) -> None: ... + +class While(Stmt): + def __init__(self, range: SourceRange, cond: Expr, body: list[Stmt]) -> None: ... + +class With(Stmt): + def __init__( + self, range: SourceRange, targets: list[WithItem], body: list[Stmt] + ) -> None: ... + +class For(Stmt): + def __init__( + self, + range: SourceRange, + targets: list[Expr], + itrs: list[Expr], + body: list[Stmt], + ) -> None: ... + +class ExprStmt(Stmt): + def __init__(self, expr: Expr) -> None: ... + +class Var(Expr): + def __init__(self, name: Ident) -> None: ... + @property + def name(self) -> str: ... + +class BinOp(Expr): + def __init__(self, kind: str, lhs: Expr, rhs: Expr) -> None: ... + +class UnaryOp(Expr): + def __init__(self, range: SourceRange, kind: str, expr: Expr) -> None: ... + +class Const(Expr): + def __init__(self, range: SourceRange, value: str) -> None: ... + +class StringLiteral(Expr): + def __init__(self, range: SourceRange, value: str) -> None: ... + +class Apply(Expr): + def __init__( + self, expr: Expr, args: list[Expr], kwargs: list[Attribute] + ) -> None: ... + +class Select(Expr): + def __init__(self, expr: Expr, field: Ident) -> None: ... + +class TernaryIf(Expr): + def __init__(self, cond: Expr, true_expr: Expr, false_expr: Expr) -> None: ... + +class ListComp(Expr): + def __init__( + self, range: SourceRange, elt: Expr, target: Expr, iter: Expr + ) -> None: ... + +class DictComp(Expr): + def __init__( + self, range: SourceRange, key: Expr, value: Expr, target: Expr, iter: Expr + ) -> None: ... + +class ListLiteral(Expr): + def __init__(self, range: SourceRange, args: list[Expr]) -> None: ... + +class TupleLiteral(Expr): + def __init__(self, range: SourceRange, args: list[Expr]) -> None: ... + +class DictLiteral(Expr): + def __init__( + self, range: SourceRange, keys: list[Expr], values: list[Expr] + ) -> None: ... + +class Subscript(Expr): + def __init__(self, base: Expr, subscript_exprs: list[Expr]) -> None: ... + +class SliceExpr(Expr): + def __init__( + self, + range: SourceRange, + lower: Expr | None, + upper: Expr | None, + step: Expr | None, + ) -> None: ... + +class Starred(Expr): + def __init__(self, range: SourceRange, expr: Expr) -> None: ... + +class EmptyTypeAnnotation(TreeView): + def __init__(self, range: SourceRange) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_lazy.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_lazy.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c6b2b89fa3a9e89d889d9248097315d7c9d8635c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_lazy.pyi @@ -0,0 +1,26 @@ +from torch import Tensor + +# defined in torch/csrc/lazy/python/init.cpp +def _mark_step(device: str, devices: list[str], wait: bool) -> None: ... +def _wait_device_ops(devices: list[str]) -> None: ... +def _reset_metrics() -> None: ... +def _counter_names() -> list[str]: ... +def _counter_value(name: str) -> int: ... +def _metrics_report() -> str: ... +def _get_graph_hash(tensors: list[Tensor]) -> str: ... +def _sync_multi( + tensors: list[Tensor], + devices: list[str], + wait: bool = True, + sync_ltc_data: bool = True, +) -> None: ... +def _get_tensor_id(tensor: Tensor) -> int: ... +def _get_tensors_text(tensors: list[Tensor]) -> str: ... +def _get_tensors_dot(tensors: list[Tensor]) -> str: ... +def _get_tensors_backend(tensors: list[Tensor]) -> str: ... +def _get_force_fallback() -> str: ... +def _set_force_fallback(newval: str) -> None: ... +def _clear_ir_cache() -> None: ... +def _dump_ir_cache(filename: str) -> None: ... +def _set_reuse_ir(val: bool) -> None: ... +def _get_default_device_type() -> str: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_lazy_ts_backend.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_lazy_ts_backend.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cd1bef2de069dfc93cd2b6243ab97d550d75f086 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_lazy_ts_backend.pyi @@ -0,0 +1,12 @@ +# mypy: allow-untyped-defs +# defined in torch/csrc/lazy/python/init.cpp + +from typing import Any + +from torch import Tensor + +def _init(): ... +def _get_tensors_ts_device_data_node( + tensors: list[Tensor], +) -> tuple[list[int], list[Any]]: ... +def _run_cached_graph(hash_str: str, graph_inputs: list[Any]) -> list[Tensor]: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_monitor.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_monitor.pyi new file mode 100644 index 0000000000000000000000000000000000000000..82f2a3e4427038dcb0616d7b305c7c5c85c97606 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_monitor.pyi @@ -0,0 +1,58 @@ +# Defined in torch/csrc/monitor/python_init.cpp + +import datetime +from collections.abc import Callable +from enum import Enum +from types import TracebackType + +class Aggregation(Enum): + VALUE = ... + MEAN = ... + COUNT = ... + SUM = ... + MAX = ... + MIN = ... + +class Stat: + name: str + count: int + def __init__( + self, + name: str, + aggregations: list[Aggregation], + window_size: int, + max_samples: int = -1, + ) -> None: ... + def add(self, v: float) -> None: ... + def get(self) -> dict[Aggregation, float]: ... + +class Event: + name: str + timestamp: datetime.datetime + data: dict[str, int | float | bool | str] + def __init__( + self, + name: str, + timestamp: datetime.datetime, + data: dict[str, int | float | bool | str], + ) -> None: ... + +def log_event(e: Event) -> None: ... + +class EventHandlerHandle: ... + +def register_event_handler(handler: Callable[[Event], None]) -> EventHandlerHandle: ... +def unregister_event_handler(handle: EventHandlerHandle) -> None: ... + +class _WaitCounterTracker: + def __enter__(self) -> None: ... + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: ... + +class _WaitCounter: + def __init__(self, key: str) -> None: ... + def guard(self) -> _WaitCounterTracker: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_nn.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_nn.pyi new file mode 100644 index 0000000000000000000000000000000000000000..08a9fc6e36fd7d997707a8f096ae4b6da7b1ec7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_nn.pyi @@ -0,0 +1,347 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/_nn.pyi.in +# mypy: disable-error-code="type-arg" + +from collections.abc import Sequence +from typing import Literal, overload + +from torch import memory_format, Tensor +from torch.types import _bool, _device, _dtype, _int, _size + +# Defined in tools/autograd/templates/python_nn_functions.cpp + +def adaptive_avg_pool2d(input: Tensor, output_size: _int | _size) -> Tensor: ... +def adaptive_avg_pool3d(input: Tensor, output_size: _int | _size) -> Tensor: ... +def adaptive_max_pool2d( + input: Tensor, + output_size: _int | _size, +) -> tuple[Tensor, Tensor]: ... +def adaptive_max_pool3d( + input: Tensor, + output_size: _int | _size, +) -> tuple[Tensor, Tensor]: ... +def avg_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + ceil_mode: bool = False, + count_include_pad: bool = True, + divisor_override: int | None = None, +) -> Tensor: ... +def avg_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + ceil_mode: bool = False, + count_include_pad: bool = True, + divisor_override: int | None = None, +) -> Tensor: ... +def binary_cross_entropy( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: str = ..., +) -> Tensor: ... +def col2im( + input: Tensor, + output_size: _int | _size, + kernel_size: _int | _size, + dilation: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, +) -> Tensor: ... +def cross_entropy_loss( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: str = ..., + ignore_index: int = -100, + label_smoothing: float = 0.0, +) -> Tensor: ... +def elu( + input: Tensor, + alpha: float = 1.0, + scale: float = 1.0, + input_scale: float = 1.0, +) -> Tensor: ... +def elu_(input: Tensor, alpha: float = ...) -> Tensor: ... +def fractional_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + output_size: _int | _size, + _random_samples: Tensor, +) -> tuple[Tensor, Tensor]: ... +def fractional_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + output_size: _int | _size, + _random_samples: Tensor, +) -> tuple[Tensor, Tensor]: ... +def gelu(input: Tensor, approximate: str = ...) -> Tensor: ... +def glu(input: Tensor, dim: int = -1) -> Tensor: ... +def hardsigmoid(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def hardsigmoid_(input: Tensor) -> Tensor: ... +def hardswish(input: Tensor) -> Tensor: ... +def hardswish_(input: Tensor) -> Tensor: ... +def hardtanh( + input: Tensor, + min_val: float = ..., + max_val: float = ..., + *, + out: Tensor | None = None, +) -> Tensor: ... +def hardtanh_( + input: Tensor, + min_val: float = ..., + max_val: float = ..., +) -> Tensor: ... +def huber_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., + delta: float = 1.0, +) -> Tensor: ... +def im2col( + input: Tensor, + kernel_size: _int | _size, + dilation: _int | _size, + padding: _int | _size, + stride: _int | _size, +) -> Tensor: ... +def l1_loss(input: Tensor, target: Tensor, reduction: str = ...) -> Tensor: ... +def leaky_relu( + input: Tensor, + negative_slope: float = ..., + *, + out: Tensor | None = None, +) -> Tensor: ... +def leaky_relu_(input: Tensor, negative_slope: float = ...) -> Tensor: ... +def linear( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, +) -> Tensor: ... +def log_sigmoid(input: Tensor) -> Tensor: ... +def max_pool2d_with_indices( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: bool = False, +) -> tuple[Tensor, Tensor]: ... +def max_pool3d_with_indices( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: bool = False, +) -> tuple[Tensor, Tensor]: ... +def max_unpool2d( + input: Tensor, + indices: Tensor, + output_size: Sequence[int] | None, +) -> Tensor: ... +def max_unpool3d( + input: Tensor, + indices: Tensor, + output_size: Sequence[int] | None, + stride: _int | _size, + padding: _int | _size, +) -> Tensor: ... +def mish(input: Tensor) -> Tensor: ... +def mish_(input: Tensor) -> Tensor: ... +def mse_loss(input: Tensor, target: Tensor, reduction: str = ...) -> Tensor: ... +def multi_margin_loss( + input: Tensor, + target: Tensor, + p: float = 1.0, + margin: float = 1.0, + weight: Tensor | None = None, + reduction: str = ..., +) -> Tensor: ... +def multilabel_margin_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., +) -> Tensor: ... +def nll_loss_nd( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: str = ..., + ignore_index: int = -100, +) -> Tensor: ... +def one_hot(tensor: Tensor, num_classes: int = ...) -> Tensor: ... +def pad( + input: Tensor, + pad: Sequence[int], + mode: str = ..., + value: float | None = None, +) -> Tensor: ... +def relu6(input: Tensor) -> Tensor: ... +def relu6_(input: Tensor) -> Tensor: ... +def scaled_dot_product_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: float = 0.0, + is_causal: bool = False, + scale: float | None = None, + enable_gqa: bool = False, +) -> Tensor: ... +def silu(input: Tensor) -> Tensor: ... +def silu_(input: Tensor) -> Tensor: ... +def smooth_l1_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., + beta: float = 1.0, +) -> Tensor: ... +def soft_margin_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., +) -> Tensor: ... +def softplus( + input: Tensor, + beta: float = ..., + threshold: float = ..., +) -> Tensor: ... +def softshrink(input: Tensor, lambd: float = ...) -> Tensor: ... + +# Defined in aten/src/ATen/native/mkldnn/Linear.cpp +def mkldnn_linear(input: Tensor, weight: Tensor, bias: Tensor | None) -> Tensor: ... + +# Defined at aten/src/ATen/native/mkldnn/MKLDNNConversions.cpp +def mkldnn_reorder_conv2d_weight( + self: Tensor, + padding: list, + stride: list, + dilatation: list, + groups: int, +) -> Tensor: ... +def mkldnn_reorder_conv3d_weight( + self: Tensor, + padding: list, + stride: list, + dilatation: list, + groups: int, +) -> Tensor: ... + +# Defined in aten/src/ATen/native/mkldnn/Prelu.cpp +def mkldnn_prelu(input: Tensor, weight: Tensor) -> Tensor: ... + +# Defined at tools/autograd/templates/python_nn_functions.cpp +@overload +def _parse_to( + device: _device, + dtype: _dtype, + non_blocking: _bool, + copy: _bool, + *, + memory_format: memory_format, +) -> tuple[_device, _dtype, _bool, memory_format]: ... +@overload +def _parse_to( + dtype: _dtype, + non_blocking: _bool, + copy: _bool, + *, + memory_format: memory_format, +) -> tuple[_device, _dtype, _bool, memory_format]: ... +@overload +def _parse_to( + tensor: Tensor, + non_blocking: _bool, + copy: _bool, + *, + memory_format: memory_format, +) -> tuple[_device, _dtype, _bool, memory_format]: ... + +# Defined in aten/src/ATen/native/PackedSequence.cpp +def pad_sequence( + sequences: list[Tensor] | tuple[Tensor, ...], + batch_first: bool = False, + padding_value: float = 0.0, + padding_side: Literal["left", "right"] = "right", +) -> Tensor: ... + +# Upsample functions used by torch.nn.functional.interpolate +def upsample_nearest1d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_nearest2d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_nearest3d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_nearest_exact1d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_nearest_exact2d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_nearest_exact3d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_linear1d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_bilinear2d_aa( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_bilinear2d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_trilinear3d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_bicubic2d_aa( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_lanczos2d_aa( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_bicubic2d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def flatten_dense_tensors(tensors: list[Tensor]) -> Tensor: ... +def unflatten_dense_tensors(flat: Tensor, tensors: list[Tensor]) -> list[Tensor]: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_nvtx.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_nvtx.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9b96874c36578ebaba065188d726455ff0b771be --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_nvtx.pyi @@ -0,0 +1,9 @@ +# mypy: allow-untyped-defs +# Defined in torch/csrc/cuda/shared/nvtx.cpp +def rangePushA(message: str) -> int: ... +def rangePop() -> int: ... +def rangeStartA(message: str) -> int: ... +def rangeEnd(int) -> None: ... +def markA(message: str) -> None: ... +def deviceRangeStart(message: str, stream: int) -> object: ... +def deviceRangeEnd(range_handle: object, stream: int) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_onnx.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_onnx.pyi new file mode 100644 index 0000000000000000000000000000000000000000..349e0b9ad12f0dd9306fde89a40718f26b158f0e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_onnx.pyi @@ -0,0 +1,39 @@ +# Defined in torch/csrc/onnx/init.cpp + +from enum import Enum + +PRODUCER_VERSION: str + +class TensorProtoDataType(Enum): + UNDEFINED = ... + FLOAT = ... + UINT8 = ... + INT8 = ... + UINT16 = ... + INT16 = ... + INT32 = ... + INT64 = ... + STRING = ... + BOOL = ... + FLOAT16 = ... + DOUBLE = ... + UINT32 = ... + UINT64 = ... + COMPLEX64 = ... + COMPLEX128 = ... + BFLOAT16 = ... + FLOAT8E5M2 = ... + FLOAT8E4M3FN = ... + FLOAT8E5M2FNUZ = ... + FLOAT8E4M3FNUZ = ... + +class OperatorExportTypes(Enum): + ONNX = ... + ONNX_ATEN = ... + ONNX_ATEN_FALLBACK = ... + ONNX_FALLTHROUGH = ... + +class TrainingMode(Enum): + EVAL = ... + PRESERVE = ... + TRAINING = ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_profiler.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_profiler.pyi new file mode 100644 index 0000000000000000000000000000000000000000..925c5dcde668e64e47404ee78cb87f4ec5f8c8b7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_profiler.pyi @@ -0,0 +1,353 @@ +from enum import Enum +from typing import Literal, TypeAlias + +from torch._C import device, dtype, layout + +# defined in torch/csrc/profiler/python/init.cpp + +class RecordScope(Enum): + FUNCTION = ... + BACKWARD_FUNCTION = ... + TORCHSCRIPT_FUNCTION = ... + KERNEL_FUNCTION_DTYPE = ... + CUSTOM_CLASS = ... + BUILD_FEATURE = ... + LITE_INTERPRETER = ... + USER_SCOPE = ... + STATIC_RUNTIME_OP = ... + STATIC_RUNTIME_MODEL = ... + +class ProfilerState(Enum): + Disabled = ... + CPU = ... + CUDA = ... + NVTX = ... + ITT = ... + PRIVATEUSE1 = ... + KINETO = ... + KINETO_GPU_FALLBACK = ... + KINETO_PRIVATEUSE1_FALLBACK = ... + KINETO_PRIVATEUSE1 = ... + +class ActiveProfilerType(Enum): + NONE = ... + LEGACY = ... + KINETO = ... + NVTX = ... + ITT = ... + PRIVATEUSE1 = ... + +class ProfilerActivity(Enum): + CPU = ... + CUDA = ... + XPU = ... + MTIA = ... + HPU = ... + PrivateUse1 = ... + +class _EventType(Enum): + TorchOp = ... + Backend = ... + Allocation = ... + OutOfMemory = ... + PyCall = ... + PyCCall = ... + Kineto = ... + +class _ExperimentalConfig: + def __init__( + self, + profiler_metrics: list[str] = ..., + profiler_measure_per_kernel: bool = ..., + verbose: bool = ..., + performance_events: list[str] = ..., + enable_cuda_sync_events: bool = ..., + adjust_profiler_step: bool = ..., + disable_external_correlation: bool = ..., + profile_all_threads: bool = ..., + capture_overload_names: bool = ..., + record_python_gc_info: bool = ..., + expose_kineto_event_metadata: bool = ..., + custom_profiler_config: str = ..., + adjust_timestamps: bool = ..., + trace_only: bool = ..., + ) -> None: ... + trace_only: bool + # Deprecated no-ops; retained only so the Python layer can detect and warn. + profiler_metrics: list[str] + profiler_measure_per_kernel: bool + +class ProfilerConfig: + def __init__( + self, + state: ProfilerState, + report_input_shapes: bool, + profile_memory: bool, + with_stack: bool, + with_flops: bool, + with_modules: bool, + experimental_config: _ExperimentalConfig, + trace_id: str | None = None, + ) -> None: ... + +class _ProfilerEvent: + start_tid: int + start_time_ns: int + children: list[_ProfilerEvent] + + # TODO(robieta): remove in favor of `self.typed` + extra_fields: ( + _ExtraFields_TorchOp + | _ExtraFields_Backend + | _ExtraFields_Allocation + | _ExtraFields_OutOfMemory + | _ExtraFields_PyCall + | _ExtraFields_PyCCall + | _ExtraFields_Kineto + ) + + @property + def typed( + self, + ) -> ( + tuple[Literal[_EventType.TorchOp], _ExtraFields_TorchOp] + | tuple[Literal[_EventType.Backend], _ExtraFields_Backend] + | tuple[Literal[_EventType.Allocation], _ExtraFields_Allocation] + | tuple[Literal[_EventType.OutOfMemory], _ExtraFields_OutOfMemory] + | tuple[Literal[_EventType.PyCall], _ExtraFields_PyCall] + | tuple[Literal[_EventType.PyCCall], _ExtraFields_PyCCall] + | tuple[Literal[_EventType.Kineto], _ExtraFields_Kineto] + ): ... + @property + def name(self) -> str: ... + @property + def overload_name(self) -> str: ... + @property + def tag(self) -> _EventType: ... + @property + def id(self) -> int: ... + @property + def parent(self) -> _ProfilerEvent | None: ... + @property + def correlation_id(self) -> int: ... + @property + def end_time_ns(self) -> int: ... + @property + def duration_time_ns(self) -> int: ... + +class _TensorMetadata: + impl_ptr: int | None + storage_data_ptr: int | None + id: int | None + + @property + def allocation_id(self) -> int | None: ... + @property + def layout(self) -> layout: ... + @property + def device(self) -> device: ... + @property + def dtype(self) -> dtype: ... + @property + def sizes(self) -> list[int]: ... + @property + def strides(self) -> list[int]: ... + +Scalar: TypeAlias = int | float | bool | complex +Input: TypeAlias = _TensorMetadata | list[_TensorMetadata] | Scalar | None + +class _ExtraFields_TorchOp: + name: str + sequence_number: int + allow_tf32_cublas: bool + + @property + def inputs(self) -> list[Input]: ... + @property + def scope(self) -> RecordScope: ... + +class _ExtraFields_Backend: ... + +class _ExtraFields_Allocation: + ptr: int + id: int | None + alloc_size: int + total_allocated: int + total_reserved: int + + @property + def allocation_id(self) -> int | None: ... + @property + def device(self) -> device: ... + +class _ExtraFields_OutOfMemory: ... + +class _PyFrameState: + line_number: int + function_name: str + + @property + def file_name(self) -> str: ... + +class _NNModuleInfo: + @property + def self_ptr(self) -> int: ... + @property + def cls_ptr(self) -> int: ... + @property + def cls_name(self) -> str: ... + @property + def parameters( + self, + ) -> list[tuple[str, _TensorMetadata, _TensorMetadata | None]]: ... + +class _OptimizerInfo: + @property + def parameters( + self, + ) -> list[ + tuple[ + # Parameter + _TensorMetadata, + # + # Gradient (if present during optimizer.step()) + _TensorMetadata | None, + # + # Optimizer state for Parameter as (name, tensor) pairs + list[tuple[str, _TensorMetadata]], + ] + ]: ... + +class _ExtraFields_PyCCall: + @property + def caller(self) -> _PyFrameState: ... + +class _ExtraFields_PyCall: + @property + def callsite(self) -> _PyFrameState: ... + @property + def caller(self) -> _PyFrameState: ... + @property + def module(self) -> _NNModuleInfo | None: ... + @property + def optimizer(self) -> _OptimizerInfo | None: ... + +class _ExtraFields_Kineto: ... + +def _add_execution_trace_observer(output_file_path: str) -> bool: ... +def _remove_execution_trace_observer() -> None: ... +def _enable_execution_trace_observer() -> None: ... +def _disable_execution_trace_observer() -> None: ... +def _set_record_concrete_inputs_enabled_val(val: bool) -> None: ... +def _set_fwd_bwd_enabled_val(val: bool) -> None: ... +def _set_cuda_sync_enabled_val(val: bool) -> None: ... + +# Approximate-clock helpers used by the experimental CUPTI monitor. +class _ApproximateClockToUnixTimeConverter: + def __init__(self) -> None: ... + def to_unix_ns(self, t: int) -> int: ... + +def _get_approximate_time() -> int: ... + +# GIL-free CUPTI monitor buffer pool (torch/csrc/profiler/cupti/monitor_native). +# Exposed as the torch._C._profiler._cupti_monitor submodule. +class _CuptiMonitorModule: + @staticmethod + def approximate_time_callback_address() -> int: ... + @staticmethod + def configure_buffers(buffer_size: int) -> None: ... + @staticmethod + def buffer_request_callback_address() -> int: ... + @staticmethod + def buffer_complete_callback_address() -> int: ... + @staticmethod + def get_completed() -> ( + tuple[int, int, int, int, list[tuple[int, int, list[tuple[int, int, int]]]]] + | None + ): ... + @staticmethod + def return_buffer(ptr: int) -> None: ... + @staticmethod + def pending_buffers() -> int: ... + @staticmethod + def allocated_buffers() -> int: ... + @staticmethod + def shutdown_buffers() -> None: ... + @staticmethod + def reset_buffers() -> None: ... + @staticmethod + def configure_decoder( + subscriber: int, + get_next_record_fn: int, + fence_kind: int = 0, + fence_end_field: int = -1, + self_flush: bool = False, + flush_period_ns: int = 0, + flush_fn: int = 0, + ) -> None: ... + @staticmethod + def start_decoder() -> None: ... + @staticmethod + def stop_decoder() -> None: ... + @staticmethod + def decoder_max_sync_ns() -> int: ... + @staticmethod + def decoder_buffers_decoded() -> int: ... + @staticmethod + def decoder_valid_bytes() -> int: ... + @staticmethod + def drain_decoded() -> tuple[list, dict[int, str]]: ... + @staticmethod + def bench_decode( + buffer_addr: int, + valid_size: int, + record_layouts: list[tuple[int, int, list[tuple[int, int, int]]]], + iters: int, + ) -> float: ... + @staticmethod + def note_external_push(external_id: int) -> None: ... + @staticmethod + def note_external_pop() -> int: ... + @staticmethod + def current_external_id() -> int: ... + @staticmethod + def metadata_put_external(blob: str, external_id: int = 0) -> None: ... + # groups: each a tuple (ts, end, track_uuid, name_iid, int_annos, str_annos, + # arr_annos, json_annos, flow, gpu_corr, cat_iid) where gpu_corr is a + # (int32_offsets, int64_ids) CSR of per-slice render-stage event_ids or None. + # render: (gpu_specs, gfx_contexts, stage_cols, extra, launch, tables, const_extra) + # where stage_cols = (ts, dur, event_id, gpu_id, hw_queue_iid, stage_iid, + # context, name_iid, event_wait) and event_wait is a (int32_offsets, uint64_ids) + # CSR of per-stage event_wait_ids (graph node->node dependency arrows). + @staticmethod + def encode_pftrace( + base_ns: int, + tracks: list[tuple[int, int, bool, int, int, str]], + name_table: list[str], + category_table: list[str], + groups: list[tuple], + render: tuple | None = None, + counters: tuple | None = None, + compression_level: int = 1, + ) -> bytes: ... + +_cupti_monitor: _CuptiMonitorModule + +class CapturedTraceback: ... + +def gather_traceback(python: bool, script: bool, cpp: bool) -> CapturedTraceback: ... + +# The Dict has name, filename, line +def symbolize_tracebacks( + to_symbolize: list[CapturedTraceback], +) -> list[list[dict[str, str]]]: ... + +class _RecordFunctionFast: + def __init__( + self, + name: str, + input_values: list | tuple | None = None, + keyword_values: dict | None = None, + ) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, *exc_info: object) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_verbose.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_verbose.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2388ce2bb8a5edd4c7640c374537e71607e5b72e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_verbose.pyi @@ -0,0 +1,3 @@ +# Defined in torch/csrc/utils/verbose.cpp +def mkl_set_verbose(enable: int) -> int: ... +def mkldnn_set_verbose(level: int) -> int: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C_flatbuffer/__init__.pyi b/.venv/lib/python3.12/site-packages/torch/_C_flatbuffer/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..38750ed26aa26900591829fb7d51a3e3e1cdeeec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C_flatbuffer/__init__.pyi @@ -0,0 +1,11 @@ +# mypy: allow-untyped-defs +from torch._C import LiteScriptModule, ScriptModule + +def _load_mobile_module_from_file(filename: str): ... +def _load_mobile_module_from_bytes(bytes_: bytes): ... +def _load_jit_module_from_file(filename: str): ... +def _load_jit_module_from_bytes(bytes_: bytes): ... +def _save_mobile_module(m: LiteScriptModule, filename: str): ... +def _save_jit_module(m: ScriptModule, filename: str): ... +def _save_mobile_module_to_bytes(m: LiteScriptModule) -> bytes: ... +def _save_jit_module_to_bytes(m: ScriptModule) -> bytes: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_VF.py b/.venv/lib/python3.12/site-packages/torch/_VF.py new file mode 100644 index 0000000000000000000000000000000000000000..94166b51f1786593b584629744adc24036e8b1d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_VF.py @@ -0,0 +1,31 @@ +""" +This makes the functions in torch._C._VariableFunctions available as + torch._VF. +without mypy being able to find them. + +A subset of those functions are mapped to ATen functions in +torch/jit/_builtins.py + +See https://github.com/pytorch/pytorch/issues/21478 for the reason for +introducing torch._VF + +""" + +import sys +import types + +import torch + + +class VFModule(types.ModuleType): + vf: types.ModuleType + + def __init__(self, name: str): + super().__init__(name) + self.vf = torch._C._VariableFunctions + + def __getattr__(self, name: str) -> object: + return getattr(self.vf, name) + + +sys.modules[__name__] = VFModule(__name__) diff --git a/.venv/lib/python3.12/site-packages/torch/_VF.pyi b/.venv/lib/python3.12/site-packages/torch/_VF.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2206a7e4093629d183276c42bfb015b061af3536 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_VF.pyi @@ -0,0 +1,31270 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/_VariableFunctions.pyi.in +# mypy: disable-error-code="type-arg" +# mypy: allow-untyped-defs +# ruff: noqa: F401,PYI054 + +from collections.abc import Callable, Sequence +from types import EllipsisType +from typing import Any, Literal, overload, TypeVar + +import torch +from torch import ( + contiguous_format, + Generator, + inf, + memory_format, + strided, + SymInt, + Tensor, +) +from torch._prims_common import DeviceLikeType +from torch.types import ( + _bool, + _complex, + _device, + _dtype, + _float, + _int, + _layout, + _qscheme, + _size, + Device, + Number, + PySymType, +) + +__all__ = [ + "__and__", + "__lshift__", + "__or__", + "__rshift__", + "__xor__", + "_adaptive_avg_pool2d", + "_adaptive_avg_pool3d", + "_add_batch_dim", + "_add_relu", + "_add_relu_", + "_addmm_activation", + "_aminmax", + "_amp_foreach_non_finite_check_and_unscale_", + "_amp_update_scale_", + "_assert_async", + "_assert_scalar", + "_assert_tensor_metadata", + "_batch_norm_impl_index", + "_cast_Byte", + "_cast_Char", + "_cast_Double", + "_cast_Float", + "_cast_Half", + "_cast_Int", + "_cast_Long", + "_cast_Short", + "_choose_qparams_per_tensor", + "_chunk_cat", + "_coalesce", + "_compute_linear_combination", + "_conj", + "_conj_copy", + "_conj_physical", + "_convert_indices_from_coo_to_csr", + "_convert_indices_from_csr_to_coo", + "_convert_weight_to_int4pack", + "_convert_weight_to_int4pack_for_cpu", + "_convolution", + "_convolution_mode", + "_copy_from", + "_copy_from_and_resize", + "_cslt_compress", + "_cslt_sparse_mm", + "_cslt_sparse_mm_search", + "_ctc_loss", + "_cudnn_ctc_loss", + "_cudnn_init_dropout_state", + "_cudnn_rnn", + "_cudnn_rnn_flatten_weight", + "_cufft_clear_plan_cache", + "_cufft_get_plan_cache_max_size", + "_cufft_get_plan_cache_size", + "_cufft_set_plan_cache_max_size", + "_cummax_helper", + "_cummin_helper", + "_debug_has_internal_overlap", + "_dim_arange", + "_dirichlet_grad", + "_disable_functionalization", + "_dyn_quant_matmul_4bit", + "_dyn_quant_pack_4bit_weight", + "_efficientzerotensor", + "_embedding_bag", + "_embedding_bag_forward_only", + "_empty_affine_quantized", + "_empty_per_channel_affine_quantized", + "_enable_functionalization", + "_euclidean_dist", + "_fake_quantize_learnable_per_channel_affine", + "_fake_quantize_learnable_per_tensor_affine", + "_fake_quantize_per_tensor_affine_cachemask_tensor_qparams", + "_fft_c2c", + "_fft_c2r", + "_fft_r2c", + "_fill_mem_eff_dropout_mask_", + "_flash_attention_forward_no_dropout_inplace", + "_foobar", + "_foreach_abs", + "_foreach_abs_", + "_foreach_acos", + "_foreach_acos_", + "_foreach_add", + "_foreach_add_", + "_foreach_addcdiv", + "_foreach_addcdiv_", + "_foreach_addcmul", + "_foreach_addcmul_", + "_foreach_asin", + "_foreach_asin_", + "_foreach_atan", + "_foreach_atan_", + "_foreach_ceil", + "_foreach_ceil_", + "_foreach_clamp_max", + "_foreach_clamp_max_", + "_foreach_clamp_min", + "_foreach_clamp_min_", + "_foreach_clone", + "_foreach_copy_", + "_foreach_cos", + "_foreach_cos_", + "_foreach_cosh", + "_foreach_cosh_", + "_foreach_div", + "_foreach_div_", + "_foreach_erf", + "_foreach_erf_", + "_foreach_erfc", + "_foreach_erfc_", + "_foreach_exp", + "_foreach_exp_", + "_foreach_expm1", + "_foreach_expm1_", + "_foreach_floor", + "_foreach_floor_", + "_foreach_frac", + "_foreach_frac_", + "_foreach_lerp", + "_foreach_lerp_", + "_foreach_lgamma", + "_foreach_lgamma_", + "_foreach_log", + "_foreach_log10", + "_foreach_log10_", + "_foreach_log1p", + "_foreach_log1p_", + "_foreach_log2", + "_foreach_log2_", + "_foreach_log_", + "_foreach_max", + "_foreach_maximum", + "_foreach_maximum_", + "_foreach_minimum", + "_foreach_minimum_", + "_foreach_mm", + "_foreach_mul", + "_foreach_mul_", + "_foreach_neg", + "_foreach_neg_", + "_foreach_norm", + "_foreach_pow", + "_foreach_pow_", + "_foreach_powsum", + "_foreach_reciprocal", + "_foreach_reciprocal_", + "_foreach_round", + "_foreach_round_", + "_foreach_rsqrt", + "_foreach_rsqrt_", + "_foreach_sigmoid", + "_foreach_sigmoid_", + "_foreach_sign", + "_foreach_sign_", + "_foreach_sin", + "_foreach_sin_", + "_foreach_sinh", + "_foreach_sinh_", + "_foreach_sqrt", + "_foreach_sqrt_", + "_foreach_sub", + "_foreach_sub_", + "_foreach_tan", + "_foreach_tan_", + "_foreach_tanh", + "_foreach_tanh_", + "_foreach_trunc", + "_foreach_trunc_", + "_foreach_zero_", + "_from_functional_tensor", + "_functional_assert_async", + "_functional_assert_scalar", + "_functional_sym_constrain_range", + "_functional_sym_constrain_range_for_size", + "_functionalize_apply_view_metas", + "_functionalize_are_all_mutations_hidden_from_autograd", + "_functionalize_are_all_mutations_under_no_grad_or_inference_mode", + "_functionalize_commit_update", + "_functionalize_has_metadata_mutation", + "_functionalize_inductor_storage_resized_counter", + "_functionalize_is_symbolic", + "_functionalize_mark_mutation_hidden_from_autograd", + "_functionalize_mark_storage_changed", + "_functionalize_mutation_counter", + "_functionalize_replace", + "_functionalize_storage_changed_counter", + "_functionalize_sync", + "_functionalize_unsafe_set", + "_functionalize_was_inductor_storage_resized", + "_functionalize_was_storage_changed", + "_fused_adagrad_", + "_fused_adam_", + "_fused_adamw_", + "_fused_dropout", + "_fused_moving_avg_obs_fq_helper", + "_fused_rms_norm", + "_fused_sdp_choice", + "_fused_sgd_", + "_fw_primal_copy", + "_grid_sampler_2d_cpu_fallback", + "_grouped_mm", + "_has_compatible_shallow_copy_type", + "_histogramdd_bin_edges", + "_histogramdd_from_bin_cts", + "_histogramdd_from_bin_tensors", + "_index_put_impl_", + "_indices_copy", + "_int_mm", + "_is_all_true", + "_is_any_true", + "_is_functional_tensor", + "_is_functional_tensor_base", + "_is_zerotensor", + "_lazy_clone", + "_linalg_check_errors", + "_linalg_det", + "_linalg_eigh", + "_linalg_slogdet", + "_linalg_solve_ex", + "_linalg_svd", + "_log_softmax", + "_log_softmax_backward_data", + "_logcumsumexp", + "_lstm_mps", + "_lu_with_info", + "_make_dep_token", + "_make_dual", + "_make_dual_copy", + "_make_per_channel_quantized_tensor", + "_make_per_tensor_quantized_tensor", + "_masked_scale", + "_masked_softmax", + "_mixed_dtypes_linear", + "_mkldnn_reshape", + "_mkldnn_transpose", + "_mkldnn_transpose_", + "_mps_convolution", + "_mps_convolution_transpose", + "_native_batch_norm_legit", + "_native_batch_norm_legit_no_training", + "_native_multi_head_attention", + "_neg_view", + "_neg_view_copy", + "_nested_compute_contiguous_strides_offsets", + "_nested_from_padded", + "_nested_from_padded_and_nested_example", + "_nested_from_padded_tensor", + "_nested_get_jagged_dummy", + "_nested_get_lengths", + "_nested_get_max_seqlen", + "_nested_get_min_seqlen", + "_nested_get_offsets", + "_nested_get_ragged_idx", + "_nested_get_values", + "_nested_get_values_copy", + "_nested_tensor_from_mask", + "_nested_tensor_from_mask_left_aligned", + "_nested_tensor_from_tensor_list", + "_nested_tensor_softmax_with_shape", + "_nested_view_from_buffer", + "_nested_view_from_buffer_copy", + "_nested_view_from_jagged", + "_nested_view_from_jagged_copy", + "_nnpack_available", + "_nnpack_spatial_convolution", + "_pack_padded_sequence", + "_pad_packed_sequence", + "_philox_key_fold_in", + "_philox_key_split", + "_philox_normal_", + "_philox_uniform_", + "_pin_memory", + "_prelu_kernel", + "_print", + "_propagate_xla_data", + "_remove_batch_dim", + "_reshape_alias_copy", + "_reshape_from_tensor", + "_resize_output_", + "_rowwise_prune", + "_safe_softmax", + "_sample_dirichlet", + "_saturate_weight_to_fp16", + "_scaled_dot_product_attention_math", + "_scaled_dot_product_attention_math_for_mps", + "_scaled_dot_product_cudnn_attention", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_flash_attention_for_cpu", + "_scaled_grouped_mm", + "_scaled_grouped_mm_v2", + "_scaled_mm", + "_scaled_mm_v2", + "_shape_as_tensor", + "_sobol_engine_draw", + "_sobol_engine_ff_", + "_sobol_engine_initialize_state_", + "_sobol_engine_scramble_", + "_softmax", + "_softmax_backward_data", + "_sparse_broadcast_to", + "_sparse_broadcast_to_copy", + "_sparse_csr_prod", + "_sparse_csr_sum", + "_sparse_log_softmax_backward_data", + "_sparse_semi_structured_addmm", + "_sparse_semi_structured_apply", + "_sparse_semi_structured_apply_dense", + "_sparse_semi_structured_linear", + "_sparse_semi_structured_mm", + "_sparse_semi_structured_tile", + "_sparse_softmax_backward_data", + "_sparse_sparse_matmul", + "_sparse_sum", + "_stack", + "_standard_gamma", + "_standard_gamma_grad", + "_sync", + "_test_autograd_multiple_dispatch", + "_test_autograd_multiple_dispatch_view", + "_test_autograd_multiple_dispatch_view_copy", + "_test_check_tensor", + "_test_functorch_fallback", + "_test_parallel_materialize", + "_test_serialization_subcmul", + "_to_cpu", + "_to_functional_tensor", + "_to_sparse_semi_structured", + "_transform_bias_rescale_qkv", + "_transformer_encoder_layer_fwd", + "_trilinear", + "_triton_multi_head_attention", + "_triton_scaled_dot_attention", + "_unique", + "_unique2", + "_unpack_dual", + "_unsafe_index", + "_unsafe_index_put", + "_unsafe_masked_index", + "_unsafe_masked_index_put_accumulate", + "_use_cudnn_ctc_loss", + "_use_cudnn_rnn_flatten_weight", + "_use_miopen_ctc_loss", + "_validate_compressed_sparse_indices", + "_validate_sparse_bsc_tensor_args", + "_validate_sparse_bsr_tensor_args", + "_validate_sparse_compressed_tensor_args", + "_validate_sparse_coo_tensor_args", + "_validate_sparse_csc_tensor_args", + "_validate_sparse_csr_tensor_args", + "_values_copy", + "_weight_int4pack_mm", + "_weight_int4pack_mm_for_cpu", + "_weight_int4pack_mm_with_scales_and_zeros", + "_weight_int8pack_mm", + "_weight_norm", + "_weight_norm_interface", + "_wrapped_linear_prepack", + "_wrapped_quantized_linear_prepacked", + "abs", + "abs_", + "absolute", + "acos", + "acos_", + "acosh", + "acosh_", + "adaptive_avg_pool1d", + "adaptive_max_pool1d", + "add", + "addbmm", + "addcdiv", + "addcmul", + "addmm", + "addmv", + "addmv_", + "addr", + "adjoint", + "affine_grid_generator", + "alias_copy", + "all", + "allclose", + "alpha_dropout", + "alpha_dropout_", + "amax", + "amin", + "aminmax", + "angle", + "any", + "arange", + "arccos", + "arccos_", + "arccosh", + "arccosh_", + "arcsin", + "arcsin_", + "arcsinh", + "arcsinh_", + "arctan", + "arctan2", + "arctan_", + "arctanh", + "arctanh_", + "argmax", + "argmin", + "argsort", + "argwhere", + "as_strided", + "as_strided_", + "as_strided_copy", + "as_strided_scatter", + "as_tensor", + "asarray", + "asin", + "asin_", + "asinh", + "asinh_", + "atan", + "atan2", + "atan_", + "atanh", + "atanh_", + "avg_pool1d", + "baddbmm", + "bartlett_window", + "batch_norm", + "batch_norm_backward_elemt", + "batch_norm_backward_reduce", + "batch_norm_elemt", + "batch_norm_gather_stats", + "batch_norm_gather_stats_with_counts", + "batch_norm_stats", + "batch_norm_update_stats", + "bernoulli", + "bilinear", + "binary_cross_entropy_with_logits", + "bincount", + "binomial", + "bitwise_and", + "bitwise_left_shift", + "bitwise_not", + "bitwise_or", + "bitwise_right_shift", + "bitwise_xor", + "blackman_window", + "bmm", + "broadcast_to", + "bucketize", + "can_cast", + "cat", + "ccol_indices_copy", + "ceil", + "ceil_", + "celu", + "celu_", + "channel_shuffle", + "cholesky_inverse", + "cholesky_solve", + "choose_qparams_optimized", + "chunk", + "clamp", + "clamp_", + "clamp_max", + "clamp_max_", + "clamp_min", + "clamp_min_", + "clip", + "clip_", + "clone", + "col_indices_copy", + "column_stack", + "combinations", + "complex", + "concat", + "concatenate", + "conj", + "conj_physical", + "conj_physical_", + "constant_pad_nd", + "conv1d", + "conv2d", + "conv3d", + "conv_tbc", + "conv_transpose1d", + "conv_transpose2d", + "conv_transpose3d", + "convolution", + "copysign", + "corrcoef", + "cos", + "cos_", + "cosh", + "cosh_", + "cosine_embedding_loss", + "cosine_similarity", + "count_nonzero", + "cov", + "cross", + "crow_indices_copy", + "ctc_loss", + "cudnn_affine_grid_generator", + "cudnn_batch_norm", + "cudnn_convolution", + "cudnn_convolution_add_relu", + "cudnn_convolution_relu", + "cudnn_convolution_transpose", + "cudnn_grid_sampler", + "cudnn_is_acceptable", + "cummax", + "cummin", + "cumprod", + "cumsum", + "cumulative_trapezoid", + "deg2rad", + "deg2rad_", + "dequantize", + "det", + "detach", + "detach_", + "detach_copy", + "diag", + "diag_embed", + "diagflat", + "diagonal", + "diagonal_copy", + "diagonal_scatter", + "diff", + "digamma", + "dist", + "div", + "divide", + "dot", + "dropout", + "dropout_", + "dsmm", + "dsplit", + "dstack", + "embedding", + "embedding_bag", + "embedding_renorm_", + "empty", + "empty_like", + "empty_permuted", + "empty_quantized", + "empty_strided", + "eq", + "equal", + "erf", + "erf_", + "erfc", + "erfc_", + "erfinv", + "exp", + "exp2", + "exp2_", + "exp_", + "expand_copy", + "expm1", + "expm1_", + "eye", + "fake_quantize_per_channel_affine", + "fake_quantize_per_tensor_affine", + "fbgemm_linear_fp16_weight", + "fbgemm_linear_fp16_weight_fp32_activation", + "fbgemm_linear_int8_weight", + "fbgemm_linear_int8_weight_fp32_activation", + "fbgemm_linear_quantize_weight", + "fbgemm_pack_gemm_matrix_fp16", + "fbgemm_pack_quantized_matrix", + "feature_alpha_dropout", + "feature_alpha_dropout_", + "feature_dropout", + "feature_dropout_", + "fill", + "fill_", + "fix", + "fix_", + "flatten", + "flip", + "fliplr", + "flipud", + "float_power", + "floor", + "floor_", + "floor_divide", + "fmax", + "fmin", + "fmod", + "frac", + "frac_", + "frexp", + "frobenius_norm", + "from_file", + "from_numpy", + "frombuffer", + "full", + "full_like", + "fused_moving_avg_obs_fake_quant", + "gather", + "gcd", + "gcd_", + "ge", + "geqrf", + "ger", + "get_default_dtype", + "get_num_interop_threads", + "get_num_threads", + "gradient", + "greater", + "greater_equal", + "grid_sampler", + "grid_sampler_2d", + "grid_sampler_3d", + "group_norm", + "gru", + "gru_cell", + "gt", + "hamming_window", + "hann_window", + "hardshrink", + "hash_tensor", + "heaviside", + "hinge_embedding_loss", + "histc", + "histogram", + "histogramdd", + "hsmm", + "hsplit", + "hspmm", + "hstack", + "hypot", + "i0", + "i0_", + "igamma", + "igammac", + "imag", + "index_add", + "index_copy", + "index_fill", + "index_put", + "index_put_", + "index_reduce", + "index_select", + "indices_copy", + "init_num_threads", + "inner", + "instance_norm", + "int_repr", + "inverse", + "is_complex", + "is_conj", + "is_distributed", + "is_floating_point", + "is_grad_enabled", + "is_inference", + "is_inference_mode_enabled", + "is_neg", + "is_nonzero", + "is_same_size", + "is_signed", + "is_vulkan_available", + "isclose", + "isfinite", + "isin", + "isinf", + "isnan", + "isneginf", + "isposinf", + "isreal", + "istft", + "kaiser_window", + "kl_div", + "kron", + "kthvalue", + "layer_norm", + "lcm", + "lcm_", + "ldexp", + "ldexp_", + "le", + "lerp", + "less", + "less_equal", + "lgamma", + "linspace", + "log", + "log10", + "log10_", + "log1p", + "log1p_", + "log2", + "log2_", + "log_", + "log_softmax", + "logaddexp", + "logaddexp2", + "logcumsumexp", + "logdet", + "logical_and", + "logical_not", + "logical_or", + "logical_xor", + "logit", + "logit_", + "logspace", + "logsumexp", + "lstm", + "lstm_cell", + "lt", + "lu_solve", + "lu_unpack", + "margin_ranking_loss", + "masked_fill", + "masked_scatter", + "masked_select", + "matmul", + "matrix_exp", + "matrix_power", + "max", + "max_pool1d", + "max_pool1d_with_indices", + "max_pool2d", + "max_pool3d", + "maximum", + "mean", + "median", + "min", + "minimum", + "miopen_batch_norm", + "miopen_convolution", + "miopen_convolution_add_relu", + "miopen_convolution_relu", + "miopen_convolution_transpose", + "miopen_ctc_loss", + "miopen_depthwise_convolution", + "miopen_rnn", + "mkldnn_adaptive_avg_pool2d", + "mkldnn_convolution", + "mkldnn_linear_backward_weights", + "mkldnn_max_pool2d", + "mkldnn_max_pool3d", + "mkldnn_rnn_layer", + "mm", + "mode", + "moveaxis", + "movedim", + "msort", + "mul", + "multinomial", + "multiply", + "mv", + "mvlgamma", + "nan_to_num", + "nan_to_num_", + "nanmean", + "nanmedian", + "nanquantile", + "nansum", + "narrow", + "narrow_copy", + "native_batch_norm", + "native_channel_shuffle", + "native_dropout", + "native_group_norm", + "native_layer_norm", + "native_norm", + "ne", + "neg", + "neg_", + "negative", + "negative_", + "nextafter", + "nonzero", + "nonzero_static", + "norm_except_dim", + "normal", + "not_equal", + "nuclear_norm", + "numel", + "ones", + "ones_like", + "orgqr", + "ormqr", + "outer", + "pairwise_distance", + "pdist", + "permute", + "permute_copy", + "pinverse", + "pixel_shuffle", + "pixel_unshuffle", + "poisson", + "poisson_nll_loss", + "polar", + "polygamma", + "positive", + "pow", + "prelu", + "prod", + "promote_types", + "put", + "q_per_channel_axis", + "q_per_channel_scales", + "q_per_channel_zero_points", + "q_scale", + "q_zero_point", + "quantile", + "quantize_per_channel", + "quantize_per_tensor", + "quantize_per_tensor_dynamic", + "quantized_batch_norm", + "quantized_gru_cell", + "quantized_lstm_cell", + "quantized_max_pool1d", + "quantized_max_pool2d", + "quantized_max_pool3d", + "quantized_rnn_relu_cell", + "quantized_rnn_tanh_cell", + "rad2deg", + "rad2deg_", + "rand", + "rand_like", + "randint", + "randint_like", + "randn", + "randn_like", + "randperm", + "range", + "ravel", + "real", + "reciprocal", + "reciprocal_", + "relu", + "relu_", + "remainder", + "renorm", + "repeat_interleave", + "reshape", + "resize_as_", + "resize_as_sparse_", + "resolve_conj", + "resolve_neg", + "result_type", + "rms_norm", + "rnn_relu", + "rnn_relu_cell", + "rnn_tanh", + "rnn_tanh_cell", + "roll", + "rot90", + "round", + "round_", + "row_indices_copy", + "row_stack", + "rrelu", + "rrelu_", + "rsqrt", + "rsqrt_", + "rsub", + "saddmm", + "scalar_tensor", + "scatter", + "scatter_add", + "scatter_reduce", + "searchsorted", + "segment_reduce", + "select", + "select_copy", + "select_scatter", + "selu", + "selu_", + "set_flush_denormal", + "set_num_interop_threads", + "set_num_threads", + "sgn", + "sigmoid", + "sigmoid_", + "sign", + "signbit", + "sin", + "sin_", + "sinc", + "sinc_", + "sinh", + "sinh_", + "slice_copy", + "slice_inverse", + "slice_scatter", + "slogdet", + "smm", + "softmax", + "sort", + "sparse_bsc_tensor", + "sparse_bsr_tensor", + "sparse_compressed_tensor", + "sparse_coo_tensor", + "sparse_csc_tensor", + "sparse_csr_tensor", + "split_copy", + "split_with_sizes", + "split_with_sizes_copy", + "spmm", + "sqrt", + "sqrt_", + "square", + "square_", + "squeeze", + "squeeze_copy", + "sspaddmm", + "stack", + "std", + "std_mean", + "sub", + "subtract", + "sum", + "svd", + "swapaxes", + "swapdims", + "sym_constrain_range", + "sym_constrain_range_for_size", + "t", + "t_copy", + "take", + "take_along_dim", + "tan", + "tan_", + "tanh", + "tanh_", + "tensor", + "tensor_split", + "threshold", + "threshold_", + "tile", + "topk", + "trace", + "transpose", + "transpose_copy", + "trapezoid", + "trapz", + "triangular_solve", + "tril", + "tril_indices", + "triplet_margin_loss", + "triu", + "triu_indices", + "true_divide", + "trunc", + "trunc_", + "unbind", + "unbind_copy", + "unflatten", + "unfold_copy", + "unique_dim", + "unsafe_chunk", + "unsafe_split", + "unsafe_split_with_sizes", + "unsqueeze", + "unsqueeze_copy", + "values_copy", + "vander", + "var", + "var_mean", + "vdot", + "view_as_complex", + "view_as_complex_copy", + "view_as_real", + "view_as_real_copy", + "view_copy", + "vsplit", + "vstack", + "where", + "xlogy", + "xlogy_", + "zero_", + "zeros", + "zeros_like", +] + +@overload +def __and__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __and__(input: Tensor, other: Number | _complex | PySymType) -> Tensor: ... +@overload +def __lshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __lshift__( + input: Tensor, + other: Number | _complex | PySymType, +) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Number | _complex | PySymType) -> Tensor: ... +@overload +def __rshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __rshift__( + input: Tensor, + other: Number | _complex | PySymType, +) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Number | _complex | PySymType) -> Tensor: ... +def _adaptive_avg_pool2d( + input: Tensor, + output_size: _int | SymInt | Sequence[_int | SymInt], +) -> Tensor: ... +def _adaptive_avg_pool3d( + input: Tensor, + output_size: _int | SymInt | Sequence[_int | SymInt], +) -> Tensor: ... +def _add_batch_dim(input: Tensor, batch_dim: _int, level: _int) -> Tensor: ... +@overload +def _add_relu( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def _add_relu( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +def _addmm_activation( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + use_gelu: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def _aminmax(input: Tensor) -> tuple[Tensor, Tensor]: ... +@overload +def _aminmax( + input: Tensor, + dim: _int, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _amp_foreach_non_finite_check_and_unscale_( + self: tuple[Tensor, ...] | list[Tensor], + found_inf: Tensor, + inv_scale: Tensor, +) -> None: ... +def _amp_update_scale_( + input: Tensor, + growth_tracker: Tensor, + found_inf: Tensor, + scale_growth_factor: _float, + scale_backoff_factor: _float, + growth_interval: _int, +) -> Tensor: ... +@overload +def _assert_async(input: Tensor) -> None: + r""" + _assert_async(tensor) -> void + + Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, + this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for + CUDA tensors, we DO NOT synchronize and you may only find out the assertion + failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for + testing invariants in CUDA tensors without giving up performance. This function + is NOT intended to be used for regular error checking, as it will trash your CUDA + context if the assert fails (forcing you to restart your PyTorch process.) + + Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. + """ + +@overload +def _assert_async(input: Tensor, assert_msg: str) -> None: + r""" + _assert_async(tensor) -> void + + Asynchronously assert that the contents of tensor are nonzero. For CPU tensors, + this is equivalent to ``assert tensor`` or ``assert tensor.is_nonzero()``; for + CUDA tensors, we DO NOT synchronize and you may only find out the assertion + failed at a later CUDA kernel launch. Asynchronous assertion can be helpful for + testing invariants in CUDA tensors without giving up performance. This function + is NOT intended to be used for regular error checking, as it will trash your CUDA + context if the assert fails (forcing you to restart your PyTorch process.) + + Args: + tensor (Tensor): a one element tensor to test to see if it is nonzero. Zero + elements (including False for boolean tensors) cause an assertion failure + to be raised. + """ + +def _assert_scalar( + self: Number | _complex | PySymType, + assert_msg: str, +) -> None: ... +def _assert_tensor_metadata( + a: Tensor, + size: Sequence[_int | SymInt] | None = None, + stride: Sequence[_int | SymInt] | None = None, + dtype: _dtype | None = None, + *, + device: DeviceLikeType | None = None, + layout: _layout | None = None, +) -> None: ... +def _batch_norm_impl_index( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor, _int]: ... +def _cast_Byte(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Char(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Double(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Float(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Half(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Int(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Long(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _cast_Short(input: Tensor, non_blocking: _bool = False) -> Tensor: ... +def _choose_qparams_per_tensor( + input: Tensor, + reduce_range: _bool = False, +) -> tuple[_float, _int]: ... +def _chunk_cat( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int, + num_chunks: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _coalesce(input: Tensor) -> Tensor: ... +def _compute_linear_combination( + input: Tensor, + coefficients: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _conj(input: Tensor) -> Tensor: ... +def _conj_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _conj_physical(input: Tensor) -> Tensor: ... +def _convert_indices_from_coo_to_csr( + input: Tensor, + size: _int, + *, + out_int32: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +def _convert_indices_from_csr_to_coo( + crow_indices: Tensor, + col_indices: Tensor, + *, + out_int32: _bool = False, + transpose: _bool = False, + out: Tensor | None = None, +) -> Tensor: ... +def _convert_weight_to_int4pack(input: Tensor, innerKTiles: _int) -> Tensor: ... +def _convert_weight_to_int4pack_for_cpu( + input: Tensor, + innerKTiles: _int, +) -> Tensor: ... +@overload +def _convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: _size, + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + cudnn_enabled: _bool, +) -> Tensor: ... +@overload +def _convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + cudnn_enabled: _bool, + allow_tf32: _bool, +) -> Tensor: ... +def _convolution_mode( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: str, + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def _copy_from( + input: Tensor, + dst: Tensor, + non_blocking: _bool = False, +) -> Tensor: ... +def _copy_from_and_resize(input: Tensor, dst: Tensor) -> Tensor: ... +def _cslt_compress(input: Tensor) -> Tensor: ... +def _cslt_sparse_mm( + compressed_A: Tensor, + dense_B: Tensor, + bias: Tensor | None = None, + alpha: Tensor | None = None, + out_dtype: _dtype | None = None, + transpose_result: _bool = False, + alg_id: _int = 0, + split_k: _int = 1, + split_k_mode: _int = -1, +) -> Tensor: ... +def _cslt_sparse_mm_search( + compressed_A: Tensor, + dense_B: Tensor, + bias: Tensor | None = None, + alpha: Tensor | None = None, + out_dtype: _dtype | None = None, + transpose_result: _bool = False, +) -> _int: ... +@overload +def _ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int = 0, + zero_infinity: _bool = False, +) -> tuple[Tensor, Tensor]: ... +@overload +def _ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int = 0, + zero_infinity: _bool = False, +) -> tuple[Tensor, Tensor]: ... +@overload +def _cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def _cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +def _cudnn_init_dropout_state( + dropout: _float, + train: _bool, + dropout_seed: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _cudnn_rnn( + input: Tensor, + weight: tuple[Tensor, ...] | list[Tensor], + weight_stride0: _int, + weight_buf: Tensor | None, + hx: Tensor, + cx: Tensor | None, + mode: _int, + hidden_size: _int | SymInt, + proj_size: _int | SymInt, + num_layers: _int, + batch_first: _bool, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_sizes: Sequence[_int | SymInt], + dropout_state: Tensor | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _cudnn_rnn_flatten_weight( + weight_arr: tuple[Tensor, ...] | list[Tensor], + weight_stride0: _int, + input_size: _int | SymInt, + mode: _int, + hidden_size: _int | SymInt, + proj_size: _int | SymInt, + num_layers: _int, + batch_first: _bool, + bidirectional: _bool, +) -> Tensor: ... +def _cufft_clear_plan_cache(device_index: _int) -> None: ... +def _cufft_get_plan_cache_max_size(device_index: _int) -> _int: ... +def _cufft_get_plan_cache_size(device_index: _int) -> _int: ... +def _cufft_set_plan_cache_max_size( + device_index: _int, + max_size: _int, +) -> None: ... +def _cummax_helper( + input: Tensor, + values: Tensor, + indices: Tensor, + dim: _int, +) -> None: ... +def _cummin_helper( + input: Tensor, + values: Tensor, + indices: Tensor, + dim: _int, +) -> None: ... +def _debug_has_internal_overlap(input: Tensor) -> _int: ... +def _dim_arange(like: Tensor, dim: _int) -> Tensor: ... +def _dirichlet_grad(x: Tensor, alpha: Tensor, total: Tensor) -> Tensor: ... +def _disable_functionalization(): ... +def _dyn_quant_matmul_4bit( + inp: Tensor, + packed_weights: Tensor, + block_size: _int, + in_features: _int, + out_features: _int, +) -> Tensor: ... +def _dyn_quant_pack_4bit_weight( + weights: Tensor, + scales_zeros: Tensor, + bias: Tensor | None, + block_size: _int, + in_features: _int, + out_features: _int, +) -> Tensor: ... +@overload +def _efficientzerotensor( + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _efficientzerotensor( + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, + padding_idx: _int = -1, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def _embedding_bag_forward_only( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, + padding_idx: _int = -1, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def _empty_affine_quantized( + size: Sequence[_int | SymInt], + *, + scale: _float = 1, + zero_point: _int = 0, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_affine_quantized( + *size: _int | SymInt, + scale: _float = 1, + zero_point: _int = 0, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_per_channel_affine_quantized( + size: Sequence[_int | SymInt], + *, + scales: Tensor, + zero_points: Tensor, + axis: _int, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def _empty_per_channel_affine_quantized( + *size: _int | SymInt, + scales: Tensor, + zero_points: Tensor, + axis: _int, + memory_format: memory_format | None = contiguous_format, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _enable_functionalization(*, reapply_views: _bool = False) -> None: ... +def _euclidean_dist(x1: Tensor, x2: Tensor) -> Tensor: ... +def _fake_quantize_learnable_per_channel_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, + quant_min: _int, + quant_max: _int, + grad_factor: _float = 1.0, +) -> Tensor: ... +def _fake_quantize_learnable_per_tensor_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + quant_min: _int, + quant_max: _int, + grad_factor: _float = 1.0, +) -> Tensor: ... +def _fake_quantize_per_tensor_affine_cachemask_tensor_qparams( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + fake_quant_enabled: Tensor, + quant_min: _int, + quant_max: _int, +) -> torch.return_types._fake_quantize_per_tensor_affine_cachemask_tensor_qparams: # fmt: skip + ... +def _fft_c2c( + input: Tensor, + dim: Sequence[_int | SymInt], + normalization: _int, + forward: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fft_c2r( + input: Tensor, + dim: _size, + normalization: _int, + last_dim_size: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fft_r2c( + input: Tensor, + dim: _size, + normalization: _int, + onesided: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _fill_mem_eff_dropout_mask_( + input: Tensor, + dropout_p: _float, + seed: _int, + offset: _int, +) -> Tensor: ... +def _flash_attention_forward_no_dropout_inplace( + out: Tensor | None, + query: Tensor, + key: Tensor, + value: Tensor, + cum_seq_q: Tensor | None, + cum_seq_k: Tensor | None, + max_q: _int | SymInt, + max_k: _int | SymInt, + dropout_p: _float, + is_causal: _bool, + return_debug_mask: _bool, + *, + scale: _float | None = None, + window_size_left: _int | SymInt | None = None, + window_size_right: _int | SymInt | None = None, + seqused_k: Tensor | None = None, + alibi_slopes: Tensor | None = None, + block_table: Tensor | None = None, + num_splits: _int | None = None, +) -> Tensor: ... +def _foobar( + input: Tensor, + arg1: _bool = True, + arg2: _bool = True, + *, + arg3: _bool = True, +) -> Tensor: ... +def _foreach_abs( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_abs(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.abs` to each Tensor of the input list. + """ + +def _foreach_abs_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_abs_(self: List[Tensor]) -> None + + Apply :func:`torch.abs` to each Tensor of the input list. + """ + +def _foreach_acos( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_acos(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.acos` to each Tensor of the input list. + """ + +def _foreach_acos_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_acos_(self: List[Tensor]) -> None + + Apply :func:`torch.acos` to each Tensor of the input list. + """ + +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> None: ... +def _foreach_asin( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_asin(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.asin` to each Tensor of the input list. + """ + +def _foreach_asin_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_asin_(self: List[Tensor]) -> None + + Apply :func:`torch.asin` to each Tensor of the input list. + """ + +def _foreach_atan( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_atan(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.atan` to each Tensor of the input list. + """ + +def _foreach_atan_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_atan_(self: List[Tensor]) -> None + + Apply :func:`torch.atan` to each Tensor of the input list. + """ + +def _foreach_ceil( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_ceil(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.ceil` to each Tensor of the input list. + """ + +def _foreach_ceil_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_ceil_(self: List[Tensor]) -> None + + Apply :func:`torch.ceil` to each Tensor of the input list. + """ + +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_clone( + self: tuple[Tensor, ...] | list[Tensor], + *, + memory_format: memory_format | None = None, +) -> tuple[Tensor, ...]: ... +def _foreach_copy_( + self: tuple[Tensor, ...] | list[Tensor], + src: tuple[Tensor, ...] | list[Tensor], + non_blocking: _bool = False, +) -> None: ... +def _foreach_cos( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_cos(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.cos` to each Tensor of the input list. + """ + +def _foreach_cos_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_cos_(self: List[Tensor]) -> None + + Apply :func:`torch.cos` to each Tensor of the input list. + """ + +def _foreach_cosh( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_cosh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.cosh` to each Tensor of the input list. + """ + +def _foreach_cosh_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_cosh_(self: List[Tensor]) -> None + + Apply :func:`torch.cosh` to each Tensor of the input list. + """ + +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_erf( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_erf(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.erf` to each Tensor of the input list. + """ + +def _foreach_erf_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_erf_(self: List[Tensor]) -> None + + Apply :func:`torch.erf` to each Tensor of the input list. + """ + +def _foreach_erfc( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_erfc(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.erfc` to each Tensor of the input list. + """ + +def _foreach_erfc_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_erfc_(self: List[Tensor]) -> None + + Apply :func:`torch.erfc` to each Tensor of the input list. + """ + +def _foreach_exp( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_exp(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.exp` to each Tensor of the input list. + """ + +def _foreach_exp_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_exp_(self: List[Tensor]) -> None + + Apply :func:`torch.exp` to each Tensor of the input list. + """ + +def _foreach_expm1( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_expm1(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.expm1` to each Tensor of the input list. + """ + +def _foreach_expm1_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_expm1_(self: List[Tensor]) -> None + + Apply :func:`torch.expm1` to each Tensor of the input list. + """ + +def _foreach_floor( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_floor(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.floor` to each Tensor of the input list. + """ + +def _foreach_floor_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_floor_(self: List[Tensor]) -> None + + Apply :func:`torch.floor` to each Tensor of the input list. + """ + +def _foreach_frac( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_frac(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.frac` to each Tensor of the input list. + """ + +def _foreach_frac_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_frac_(self: List[Tensor]) -> None + + Apply :func:`torch.frac` to each Tensor of the input list. + """ + +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weights: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weights: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_lgamma( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_lgamma(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.lgamma` to each Tensor of the input list. + """ + +def _foreach_lgamma_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_lgamma_(self: List[Tensor]) -> None + + Apply :func:`torch.lgamma` to each Tensor of the input list. + """ + +def _foreach_log( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_log(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log` to each Tensor of the input list. + """ + +def _foreach_log10( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_log10(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log10` to each Tensor of the input list. + """ + +def _foreach_log10_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_log10_(self: List[Tensor]) -> None + + Apply :func:`torch.log10` to each Tensor of the input list. + """ + +def _foreach_log1p( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_log1p(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log1p` to each Tensor of the input list. + """ + +def _foreach_log1p_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_log1p_(self: List[Tensor]) -> None + + Apply :func:`torch.log1p` to each Tensor of the input list. + """ + +def _foreach_log2( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_log2(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.log2` to each Tensor of the input list. + """ + +def _foreach_log2_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_log2_(self: List[Tensor]) -> None + + Apply :func:`torch.log2` to each Tensor of the input list. + """ + +def _foreach_log_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_log_(self: List[Tensor]) -> None + + Apply :func:`torch.log` to each Tensor of the input list. + """ + +def _foreach_max( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_mm( + self: tuple[Tensor, ...] | list[Tensor], + mat2: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_neg( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_neg(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.neg` to each Tensor of the input list. + """ + +def _foreach_neg_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_neg_(self: List[Tensor]) -> None + + Apply :func:`torch.neg` to each Tensor of the input list. + """ + +def _foreach_norm( + self: tuple[Tensor, ...] | list[Tensor], + ord: Number | _complex | PySymType = 2, + dtype: _dtype | None = None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: Number | _complex | PySymType, + exponent: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_powsum( + self: tuple[Tensor, ...] | list[Tensor], + ord: Number | _complex | PySymType = 2, + dtype: _dtype | None = None, +) -> tuple[Tensor, ...]: ... +def _foreach_reciprocal( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_reciprocal(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.reciprocal` to each Tensor of the input list. + """ + +def _foreach_reciprocal_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_reciprocal_(self: List[Tensor]) -> None + + Apply :func:`torch.reciprocal` to each Tensor of the input list. + """ + +def _foreach_round( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_round(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.round` to each Tensor of the input list. + """ + +def _foreach_round_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_round_(self: List[Tensor]) -> None + + Apply :func:`torch.round` to each Tensor of the input list. + """ + +def _foreach_rsqrt( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +def _foreach_rsqrt_(self: tuple[Tensor, ...] | list[Tensor]) -> None: ... +def _foreach_sigmoid( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_sigmoid(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sigmoid` to each Tensor of the input list. + """ + +def _foreach_sigmoid_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_sigmoid_(self: List[Tensor]) -> None + + Apply :func:`torch.sigmoid` to each Tensor of the input list. + """ + +def _foreach_sign( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +def _foreach_sign_(self: tuple[Tensor, ...] | list[Tensor]) -> None: ... +def _foreach_sin( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_sin(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sin` to each Tensor of the input list. + """ + +def _foreach_sin_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_sin_(self: List[Tensor]) -> None + + Apply :func:`torch.sin` to each Tensor of the input list. + """ + +def _foreach_sinh( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_sinh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sinh` to each Tensor of the input list. + """ + +def _foreach_sinh_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_sinh_(self: List[Tensor]) -> None + + Apply :func:`torch.sinh` to each Tensor of the input list. + """ + +def _foreach_sqrt( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_sqrt(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.sqrt` to each Tensor of the input list. + """ + +def _foreach_sqrt_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_sqrt_(self: List[Tensor]) -> None + + Apply :func:`torch.sqrt` to each Tensor of the input list. + """ + +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +def _foreach_tan( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_tan(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.tan` to each Tensor of the input list. + """ + +def _foreach_tan_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_tan_(self: List[Tensor]) -> None + + Apply :func:`torch.tan` to each Tensor of the input list. + """ + +def _foreach_tanh( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_tanh(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.tanh` to each Tensor of the input list. + """ + +def _foreach_tanh_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_tanh_(self: List[Tensor]) -> None + + Apply :func:`torch.tanh` to each Tensor of the input list. + """ + +def _foreach_trunc( + self: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + _foreach_trunc(self: List[Tensor]) -> List[Tensor] + + Apply :func:`torch.trunc` to each Tensor of the input list. + """ + +def _foreach_trunc_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_trunc_(self: List[Tensor]) -> None + + Apply :func:`torch.trunc` to each Tensor of the input list. + """ + +def _foreach_zero_(self: tuple[Tensor, ...] | list[Tensor]) -> None: + r""" + _foreach_zero_(self: List[Tensor]) -> None + + Apply :func:`torch.zero` to each Tensor of the input list. + """ + +def _from_functional_tensor(t: Tensor) -> Tensor: ... +def _functional_assert_async( + input: Tensor, + assert_msg: str, + dep_token: Tensor, +) -> Tensor: ... +def _functional_assert_scalar( + self: Number | _complex | PySymType, + assert_msg: str, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range( + size: Number | _complex | PySymType, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range_for_size( + size: Number | _complex | PySymType, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functionalize_apply_view_metas(tensor: Tensor, base: Tensor) -> Tensor: ... +def _functionalize_are_all_mutations_hidden_from_autograd( + t: Tensor, +) -> _bool: ... +def _functionalize_are_all_mutations_under_no_grad_or_inference_mode( + t: Tensor, +) -> _bool: ... +def _functionalize_commit_update(t: Tensor) -> None: ... +def _functionalize_has_metadata_mutation(tensor: Tensor) -> _bool: ... +def _functionalize_inductor_storage_resized_counter(t: Tensor) -> _int: ... +def _functionalize_is_symbolic(tensor: Tensor) -> _bool: ... +def _functionalize_mark_mutation_hidden_from_autograd(t: Tensor) -> None: ... +def _functionalize_mark_storage_changed(tensor: Tensor) -> _bool: ... +def _functionalize_mutation_counter(t: Tensor) -> _int: ... +def _functionalize_replace(self_: Tensor, other: Tensor) -> None: ... +def _functionalize_storage_changed_counter(t: Tensor) -> _int: ... +def _functionalize_sync(t: Tensor) -> None: ... +def _functionalize_unsafe_set(dst: Tensor, src: Tensor) -> None: ... +def _functionalize_was_inductor_storage_resized(t: Tensor) -> _bool: ... +def _functionalize_was_storage_changed(tensor: Tensor) -> _bool: ... +@overload +def _fused_adagrad_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + state_sums: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: Tensor, + lr_decay: _float, + weight_decay: _float, + eps: _float, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adagrad_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + state_sums: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: _float, + lr_decay: _float, + weight_decay: _float, + eps: _float, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adam_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: Tensor, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adam_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: _float, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adamw_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: Tensor, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_adamw_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: _float, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +def _fused_dropout( + input: Tensor, + p: _float, + generator: Generator | None = None, +) -> tuple[Tensor, Tensor]: ... +def _fused_moving_avg_obs_fq_helper( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> torch.return_types._fused_moving_avg_obs_fq_helper: ... +def _fused_rms_norm( + input: Tensor, + normalized_shape: _size, + weight: Tensor | None, + eps: _float | None, +) -> tuple[Tensor, Tensor]: ... +def _fused_sdp_choice( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> _int: ... +@overload +def _fused_sgd_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor], + *, + weight_decay: _float, + momentum: _float, + lr: Tensor, + dampening: _float, + nesterov: _bool, + maximize: _bool, + is_first_step: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +@overload +def _fused_sgd_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor], + *, + weight_decay: _float, + momentum: _float, + lr: _float, + dampening: _float, + nesterov: _bool, + maximize: _bool, + is_first_step: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +def _fw_primal_copy( + input: Tensor, + level: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _grid_sampler_2d_cpu_fallback( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def _grouped_mm( + input: Tensor, + mat2: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _has_compatible_shallow_copy_type( + input: Tensor, + from_: Tensor, +) -> _bool: ... +def _histogramdd_bin_edges( + input: Tensor, + bins: _size, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> tuple[Tensor, ...]: ... +def _histogramdd_from_bin_cts( + input: Tensor, + bins: _size, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> Tensor: ... +def _histogramdd_from_bin_tensors( + input: Tensor, + bins: tuple[Tensor, ...] | list[Tensor], + *, + weight: Tensor | None = None, + density: _bool = False, +) -> Tensor: ... +def _index_put_impl_( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, + unsafe: _bool = False, +) -> Tensor: ... +def _indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _int_mm( + input: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _is_all_true(input: Tensor) -> Tensor: ... +def _is_any_true(input: Tensor) -> Tensor: ... +def _is_functional_tensor(t: Tensor) -> _bool: ... +def _is_functional_tensor_base(t: Tensor) -> _bool: ... +def _is_zerotensor(input: Tensor) -> _bool: ... +def _lazy_clone(input: Tensor) -> Tensor: ... +def _linalg_check_errors( + info: Tensor, + api_name: str, + *, + is_matrix: _bool, +) -> None: ... +def _linalg_det( + A: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_det: ... +def _linalg_eigh( + A: Tensor, + UPLO: str = "L", + compute_v: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_eigh: ... +def _linalg_slogdet( + A: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_slogdet: ... +def _linalg_solve_ex( + A: Tensor, + B: Tensor, + *, + left: _bool = True, + check_errors: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_solve_ex: ... +def _linalg_svd( + A: Tensor, + full_matrices: _bool = False, + compute_uv: _bool = True, + *, + driver: str | None = None, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types._linalg_svd: ... +def _log_softmax( + input: Tensor, + dim: _int, + half_to_float: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _log_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _logcumsumexp( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _lstm_mps( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _lu_with_info( + input: Tensor, + pivot: _bool = True, + check_errors: _bool = True, +) -> torch.return_types._lu_with_info: ... +def _make_dep_token( + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def _make_dual(primal: Tensor, tangent: Tensor, level: _int) -> Tensor: ... +def _make_dual_copy( + primal: Tensor, + tangent: Tensor, + level: _int, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _make_per_channel_quantized_tensor( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, +) -> Tensor: ... +def _make_per_tensor_quantized_tensor( + input: Tensor, + scale: _float, + zero_point: _int, +) -> Tensor: ... +def _masked_scale(input: Tensor, mask: Tensor, scale: _float) -> Tensor: ... +def _masked_softmax( + input: Tensor, + mask: Tensor, + dim: _int | None = None, + mask_type: _int | None = None, +) -> Tensor: ... +def _mixed_dtypes_linear( + input: Tensor, + weight: Tensor, + scale: Tensor, + *, + bias: Tensor | None = None, + activation: str | None = None, +) -> Tensor: ... +def _mkldnn_reshape(input: Tensor, shape: _size) -> Tensor: ... +def _mkldnn_transpose(input: Tensor, dim0: _int, dim1: _int) -> Tensor: ... +def _mkldnn_transpose_(input: Tensor, dim0: _int, dim1: _int) -> Tensor: ... +def _mps_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def _mps_convolution_transpose( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +@overload +def _native_batch_norm_legit( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def _native_batch_norm_legit( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _native_batch_norm_legit_no_training( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: _float, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _native_multi_head_attention( + query: Tensor, + key: Tensor, + value: Tensor, + embed_dim: _int, + num_head: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + mask: Tensor | None = None, + need_weights: _bool = True, + average_attn_weights: _bool = True, + mask_type: _int | None = None, +) -> tuple[Tensor, Tensor]: ... +def _neg_view(input: Tensor) -> Tensor: ... +def _neg_view_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _nested_compute_contiguous_strides_offsets( + nested_size: Tensor, +) -> tuple[Tensor, Tensor]: ... +def _nested_from_padded( + padded: Tensor, + cpu_nested_shape_example: Tensor, + fuse_transform_0213: _bool = False, +) -> Tensor: ... +def _nested_from_padded_and_nested_example( + padded: Tensor, + nt_example: Tensor, +) -> Tensor: ... +def _nested_from_padded_tensor( + padded: Tensor, + offsets: Tensor, + dummy: Tensor, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, + sum_S: _int | SymInt | None = None, +) -> Tensor: ... +def _nested_get_jagged_dummy(any: Tensor) -> Tensor: ... +def _nested_get_lengths(input: Tensor) -> Tensor: ... +def _nested_get_max_seqlen(input: Tensor) -> Tensor: ... +def _nested_get_min_seqlen(input: Tensor) -> Tensor: ... +def _nested_get_offsets(input: Tensor) -> Tensor: ... +def _nested_get_ragged_idx(input: Tensor) -> _int: ... +def _nested_get_values(input: Tensor) -> Tensor: ... +def _nested_get_values_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nested_tensor_from_mask( + t: Tensor, + mask: Tensor, + mask_check: _bool = True, +) -> Tensor: ... +def _nested_tensor_from_mask_left_aligned(t: Tensor, mask: Tensor) -> _bool: ... +def _nested_tensor_from_tensor_list( + list: tuple[Tensor, ...] | list[Tensor], + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = None, +) -> Tensor: ... +def _nested_tensor_softmax_with_shape( + input: Tensor, + query: Tensor, +) -> Tensor: ... +def _nested_view_from_buffer( + input: Tensor, + nested_size: Tensor, + nested_strides: Tensor, + offsets: Tensor, +) -> Tensor: ... +def _nested_view_from_buffer_copy( + input: Tensor, + nested_size: Tensor, + nested_strides: Tensor, + offsets: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nested_view_from_jagged( + input: Tensor, + offsets: Tensor, + dummy: Tensor, + lengths: Tensor | None = None, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, +) -> Tensor: ... +def _nested_view_from_jagged_copy( + input: Tensor, + offsets: Tensor, + dummy: Tensor, + lengths: Tensor | None = None, + ragged_idx: _int = 1, + min_seqlen: Tensor | None = None, + max_seqlen: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _nnpack_available() -> _bool: ... +def _nnpack_spatial_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: _int | SymInt | Sequence[_int | SymInt], + stride: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def _pack_padded_sequence( + input: Tensor, + lengths: Tensor, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def _pad_packed_sequence( + data: Tensor, + batch_sizes: Tensor, + batch_first: _bool, + padding_value: Number | _complex | PySymType, + total_length: _int, +) -> tuple[Tensor, Tensor]: ... +@overload +def _philox_key_fold_in(key: Tensor, data: Tensor) -> Tensor: ... +@overload +def _philox_key_fold_in(key: Tensor, data: _int) -> Tensor: ... +def _philox_key_split(key: Tensor, num_splits: _int) -> Tensor: ... +def _philox_normal_( + input: Tensor, + key: Tensor, + mean: _float = 0, + std: _float = 1, +) -> Tensor: ... +def _philox_uniform_( + input: Tensor, + key: Tensor, + low: _float = 0, + high: _float = 1, +) -> Tensor: ... +def _pin_memory( + input: Tensor, + device: DeviceLikeType | None = None, +) -> Tensor: ... +def _prelu_kernel(input: Tensor, weight: Tensor) -> Tensor: ... +def _print(s: str) -> None: ... +def _propagate_xla_data(input: Tensor, output: Tensor) -> None: ... +def _remove_batch_dim( + input: Tensor, + level: _int, + batch_size: _int | SymInt, + out_dim: _int, +) -> Tensor: ... +def _reshape_alias_copy( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + out: Tensor | None = None, +) -> Tensor: ... +def _reshape_from_tensor(input: Tensor, shape: Tensor) -> Tensor: ... +def _resize_output_( + input: Tensor, + size: Sequence[_int | SymInt], + device: DeviceLikeType | None, +) -> Tensor: ... +def _rowwise_prune( + weight: Tensor, + mask: Tensor, + compressed_indices_dtype: _dtype, +) -> tuple[Tensor, Tensor]: ... +def _safe_softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sample_dirichlet( + input: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +def _saturate_weight_to_fp16(weight: Tensor) -> Tensor: ... +def _scaled_dot_product_attention_math( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + dropout_mask: Tensor | None = None, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _scaled_dot_product_attention_math_for_mps( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + dropout_mask: Tensor | None = None, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _scaled_dot_product_cudnn_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: _bool, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_cudnn_attention: ... +def _scaled_dot_product_efficient_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_bias: Tensor | None, + compute_log_sumexp: _bool, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_efficient_attention: ... +@overload +def _scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + q_descale: Tensor | None, + k_descale: Tensor | None, + v_descale: Tensor | None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention: ... +@overload +def _scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention: ... +def _scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + attn_mask: Tensor | None = None, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention_for_cpu: ... +def _scaled_grouped_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, +) -> Tensor: ... +def _scaled_grouped_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor], + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor], + recipe_b: _size, + swizzle_b: _size, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: _dtype | None = None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _scaled_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _scaled_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor], + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor], + recipe_b: _size, + swizzle_b: _size, + bias: Tensor | None, + out_dtype: _dtype | None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _shape_as_tensor(input: Tensor) -> Tensor: ... +def _sobol_engine_draw( + quasi: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, + dtype: _dtype | None, +) -> tuple[Tensor, Tensor]: ... +def _sobol_engine_ff_( + input: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, +) -> Tensor: ... +def _sobol_engine_initialize_state_( + input: Tensor, + dimension: _int, +) -> Tensor: ... +def _sobol_engine_scramble_( + input: Tensor, + ltm: Tensor, + dimension: _int, +) -> Tensor: ... +def _softmax( + input: Tensor, + dim: _int, + half_to_float: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input_dtype: _dtype, + *, + grad_input: Tensor | None = None, +) -> Tensor: ... +def _sparse_broadcast_to(input: Tensor, size: _size) -> Tensor: ... +def _sparse_broadcast_to_copy( + input: Tensor, + size: _size, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _sparse_csr_prod( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_csr_sum( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_log_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input: Tensor, +) -> Tensor: ... +def _sparse_semi_structured_addmm( + input: Tensor, + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + beta: Number | _complex | PySymType = 1, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_apply( + input: Tensor, + thread_masks: Tensor, +) -> tuple[Tensor, Tensor]: ... +def _sparse_semi_structured_apply_dense( + input: Tensor, + thread_masks: Tensor, +) -> Tensor: ... +def _sparse_semi_structured_linear( + input: Tensor, + weight: Tensor, + meta: Tensor, + *, + bias: Tensor | None = None, + activation: str | None = None, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_mm( + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + out_dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_semi_structured_tile( + input: Tensor, + algorithm: str = "", + use_cutlass: _bool = True, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def _sparse_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input: Tensor, +) -> Tensor: ... +def _sparse_sparse_matmul(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor, *, dtype: _dtype) -> Tensor: ... +@overload +def _sparse_sum(input: Tensor, dim: _int | _size) -> Tensor: ... +@overload +def _sparse_sum( + input: Tensor, + dim: _int | _size, + *, + dtype: _dtype, +) -> Tensor: ... +def _stack( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _standard_gamma( + input: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +def _standard_gamma_grad(input: Tensor, output: Tensor) -> Tensor: ... +def _sync(t: Tensor) -> None: ... +@overload +def _test_autograd_multiple_dispatch(input: Tensor) -> Tensor: ... +@overload +def _test_autograd_multiple_dispatch(input: Tensor, b: _bool) -> Tensor: ... +def _test_autograd_multiple_dispatch_view(input: Tensor) -> Tensor: ... +def _test_autograd_multiple_dispatch_view_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _test_check_tensor(input: Tensor) -> Tensor: ... +def _test_functorch_fallback(input: Tensor, other: Tensor) -> Tensor: ... +def _test_parallel_materialize( + input: Tensor, + num_parallel: _int, + skip_first: _bool = False, +) -> Tensor: ... +def _test_serialization_subcmul( + input: Tensor, + other: Tensor, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +def _to_cpu( + tensors: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +def _to_functional_tensor(t: Tensor) -> Tensor: ... +def _to_sparse_semi_structured(dense: Tensor) -> tuple[Tensor, Tensor]: ... +def _transform_bias_rescale_qkv( + qkv: Tensor, + qkv_bias: Tensor, + num_heads: _int, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _transformer_encoder_layer_fwd( + src: Tensor, + embed_dim: _int, + num_heads: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + use_gelu: _bool, + norm_first: _bool, + eps: _float, + norm_weight_1: Tensor, + norm_bias_1: Tensor, + norm_weight_2: Tensor, + norm_bias_2: Tensor, + ffn_weight_1: Tensor, + ffn_bias_1: Tensor, + ffn_weight_2: Tensor, + ffn_bias_2: Tensor, + mask: Tensor | None = None, + mask_type: _int | None = None, +) -> Tensor: ... +def _trilinear( + i1: Tensor, + i2: Tensor, + i3: Tensor, + expand1: _size, + expand2: _size, + expand3: _size, + sumdim: _size, + unroll_dim: _int = 1, +) -> Tensor: ... +def _triton_multi_head_attention( + query: Tensor, + key: Tensor, + value: Tensor, + embed_dim: _int, + num_head: _int, + qkv_weight: Tensor, + qkv_bias: Tensor, + proj_weight: Tensor, + proj_bias: Tensor, + mask: Tensor | None = None, +) -> Tensor: ... +def _triton_scaled_dot_attention( + q: Tensor, + k: Tensor, + v: Tensor, + dropout_p: _float = 0.0, +) -> Tensor: ... +def _unique( + input: Tensor, + sorted: _bool = True, + return_inverse: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def _unique2( + input: Tensor, + sorted: _bool = True, + return_inverse: _bool = False, + return_counts: _bool = False, +) -> tuple[Tensor, Tensor, Tensor]: ... +def _unpack_dual( + dual: Tensor, + level: _int, +) -> torch.return_types._unpack_dual: ... +def _unsafe_index( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, +) -> Tensor: ... +def _unsafe_index_put( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def _unsafe_masked_index( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + fill: Number | _complex | PySymType, +) -> Tensor: ... +def _unsafe_masked_index_put_accumulate( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, +) -> Tensor: ... +@overload +def _use_cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, +) -> _bool: ... +@overload +def _use_cudnn_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, +) -> _bool: ... +def _use_cudnn_rnn_flatten_weight() -> _bool: ... +@overload +def _use_miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, +) -> _bool: ... +@overload +def _use_miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, +) -> _bool: ... +def _validate_compressed_sparse_indices( + is_crow: _bool, + compressed_idx: Tensor, + plain_idx: Tensor, + cdim: _int, + dim: _int, + nnz: _int, +) -> None: ... +def _validate_sparse_bsc_tensor_args( + ccol_indices: Tensor, + row_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_bsr_tensor_args( + crow_indices: Tensor, + col_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_compressed_tensor_args( + compressed_indices: Tensor, + plain_indices: Tensor, + values: Tensor, + size: _size, + layout: _layout, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_coo_tensor_args( + indices: Tensor, + values: Tensor, + size: _size, + is_coalesced: _bool | None = None, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_csc_tensor_args( + ccol_indices: Tensor, + row_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _validate_sparse_csr_tensor_args( + crow_indices: Tensor, + col_indices: Tensor, + values: Tensor, + size: _size, + check_pinning: _bool | None = None, +) -> None: ... +def _values_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def _weight_int4pack_mm( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScaleAndZeros: Tensor, +) -> Tensor: ... +def _weight_int4pack_mm_for_cpu( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScaleAndZeros: Tensor, +) -> Tensor: ... +def _weight_int4pack_mm_with_scales_and_zeros( + input: Tensor, + mat2: Tensor, + qGroupSize: _int, + qScale: Tensor, + qZeros: Tensor, +) -> Tensor: ... +def _weight_int8pack_mm( + input: Tensor, + mat2: Tensor, + scales: Tensor, +) -> Tensor: ... +def _weight_norm(v: Tensor, g: Tensor, dim: _int = 0) -> Tensor: ... +def _weight_norm_interface( + v: Tensor, + g: Tensor, + dim: _int = 0, +) -> tuple[Tensor, Tensor]: ... +def _wrapped_linear_prepack( + weight: Tensor, + weight_scale: Tensor, + weight_zero_point: Tensor, + bias: Tensor, +) -> Tensor: ... +def _wrapped_quantized_linear_prepacked( + input: Tensor, + input_scale: Tensor, + input_zero_point: Tensor, + packed_weight: Tensor, + output_scale: Tensor, + output_zero_point: Tensor, + out_channel: _int, +) -> Tensor: ... +def abs(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + abs(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the absolute value of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = |\text{input}_{i}| + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.abs(torch.tensor([-1, -2, 3])) + tensor([ 1, 2, 3]) + """ + +def abs_(input: Tensor) -> Tensor: + r""" + abs_(input) -> Tensor + + In-place version of :func:`torch.abs` + """ + +def absolute(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + absolute(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.abs` + """ + +def acos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + acos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arccosine (in radians) of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = \cos^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.3348, -0.5889, 0.2005, -0.1584]) + >>> torch.acos(a) + tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) + """ + +def acos_(input: Tensor) -> Tensor: + r""" + acos_(input) -> Tensor + + In-place version of :func:`torch.acos` + """ + +def acosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + acosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic cosine of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \cosh^{-1}(\text{input}_{i}) + + Note: + The domain of the inverse hyperbolic cosine is `[1, inf)` and values outside this range + will be mapped to ``NaN``, except for `+ INF` for which the output is mapped to `+ INF`. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4).uniform_(1, 2) + >>> a + tensor([ 1.3192, 1.9915, 1.9674, 1.7151 ]) + >>> torch.acosh(a) + tensor([ 0.7791, 1.3120, 1.2979, 1.1341 ]) + """ + +def acosh_(input: Tensor) -> Tensor: + r""" + acosh_(input) -> Tensor + + In-place version of :func:`torch.acosh` + """ + +def adaptive_avg_pool1d(input: Tensor, output_size: _int | _size) -> Tensor: ... +def adaptive_max_pool1d( + input: Tensor, + output_size: _int | _size, +) -> tuple[Tensor, Tensor]: ... +@overload +def add( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def add( + self: Tensor, + alpha: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def add( + self: Tensor, + alpha: Number | _complex | PySymType, + other: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + add(input, other, *, alpha=1, out=None) -> Tensor + + Adds :attr:`other`, scaled by :attr:`alpha`, to :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i + \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to add to :attr:`input`. + + Keyword arguments: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) + >>> torch.add(a, 20) + tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) + + >>> b = torch.randn(4) + >>> b + tensor([-0.9732, -0.3497, 0.6245, 0.4022]) + >>> c = torch.randn(4, 1) + >>> c + tensor([[ 0.3743], + [-1.7724], + [-0.5811], + [-0.8017]]) + >>> torch.add(b, c, alpha=10) + tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], + [-18.6971, -18.0736, -17.0994, -17.3216], + [ -6.7845, -6.1610, -5.1868, -5.4090], + [ -8.9902, -8.3667, -7.3925, -7.6147]]) + """ + +@overload +def addbmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored + in :attr:`batch1` and :attr:`batch2`, + with a reduced add step (all matrix multiplications get accumulated + along the first dimension). + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the + same number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + .. math:: + out = \beta\ \text{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` + must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.addbmm(M, batch1, batch2) + tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], + [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], + [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) + """ + +@overload +def addcdiv( + self: Tensor, + value: Number | _complex | PySymType, + tensor1: Tensor, + tensor2: Tensor, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcdiv( + self: Tensor, + value: Number | _complex | PySymType, + tensor1: Tensor, + tensor2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcdiv( + input: Tensor, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addcdiv(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, + multiplies the result by the scalar :attr:`value` and adds it to :attr:`input`. + + .. warning:: + Integer division with addcdiv is no longer supported, and in a future + release addcdiv will perform a true division of tensor1 and tensor2. + The historic addcdiv behavior can be implemented as + (input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) + for integer inputs and as (input + value * tensor1 / tensor2) for float inputs. + The future addcdiv behavior is just the latter implementation: + (input + value * tensor1 / tensor2), for all dtypes. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} + + + The shapes of :attr:`input`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the numerator tensor + tensor2 (Tensor): the denominator tensor + + Keyword args: + value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcdiv(t, t1, t2, value=0.1) + tensor([[-0.2312, -3.6496, 0.1312], + [-1.0428, 3.4292, -0.1030], + [-0.5369, -0.9829, 0.0430]]) + """ + +@overload +def addcmul( + self: Tensor, + value: Number | _complex | PySymType, + tensor1: Tensor, + tensor2: Tensor, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addcmul( + self: Tensor, + value: Number | _complex | PySymType, + tensor1: Tensor, + tensor2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addcmul( + input: Tensor, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addcmul(input, tensor1, tensor2, *, value=1, out=None) -> Tensor + + Performs the element-wise multiplication of :attr:`tensor1` + by :attr:`tensor2`, multiplies the result by the scalar :attr:`value` + and adds it to :attr:`input`. + + .. math:: + \text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i + + The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be + :ref:`broadcastable `. + + For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be + a real number, otherwise an integer. + + Args: + input (Tensor): the tensor to be added + tensor1 (Tensor): the tensor to be multiplied + tensor2 (Tensor): the tensor to be multiplied + + Keyword args: + value (Number, optional): multiplier for :math:`tensor1 .* tensor2` + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(1, 3) + >>> t1 = torch.randn(3, 1) + >>> t2 = torch.randn(1, 3) + >>> torch.addcmul(t, t1, t2, value=0.1) + tensor([[-0.8635, -0.6391, 1.6174], + [-0.7617, -0.5879, 1.7388], + [-0.8353, -0.6249, 1.6511]]) + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. + The matrix :attr:`input` is added to the final result. + + If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a :math:`(n \times p)` tensor + and :attr:`out` will be a :math:`(n \times p)` tensor. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat1` and :attr:`mat2` and the added matrix :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operation has support for arguments with :ref:`sparse layouts`. If + :attr:`input` is sparse the result will have the same layout and if :attr:`out` + is provided it must have the same layout as :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2, 3) + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.addmm(M, mat1, mat2) + tensor([[-4.8716, 1.4671, -1.3746], + [ 0.7573, -3.9555, -2.8681]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): matrix to be added + mat1 (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def addmv( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat: Tensor, + vec: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + input: Tensor, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex | PySymType, + self: Tensor, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv( + beta: Number | _complex | PySymType, + self: Tensor, + mat: Tensor, + vec: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`mat` and + the vector :attr:`vec`. + The vector :attr:`input` is added to the final result. + + If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a 1-D tensor of size `n` and + :attr:`out` will be 1-D tensor of size `n`. + + :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between + :attr:`mat` and :attr:`vec` and the added tensor :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + Args: + input (Tensor): vector to be added + mat (Tensor): matrix to be matrix multiplied + vec (Tensor): vector to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(2) + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.addmv(M, mat, vec) + tensor([-0.3768, -5.5565]) + """ + +@overload +def addmv_( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addmv_( + input: Tensor, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addmv_( + beta: Number | _complex | PySymType, + self: Tensor, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addr( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + vec1: Tensor, + vec2: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + vec1: Tensor, + vec2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + input: Tensor, + vec1: Tensor, + vec2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex | PySymType, + self: Tensor, + vec1: Tensor, + vec2: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +@overload +def addr( + beta: Number | _complex | PySymType, + self: Tensor, + vec1: Tensor, + vec2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` + and adds it to the matrix :attr:`input`. + + Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the + outer product between :attr:`vec1` and :attr:`vec2` and the added matrix + :attr:`input` respectively. + + .. math:: + \text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2}) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector + of size `m`, then :attr:`input` must be + :ref:`broadcastable ` with a matrix of size + :math:`(n \times m)` and :attr:`out` will be a matrix of size + :math:`(n \times m)`. + + Args: + input (Tensor): matrix to be added + vec1 (Tensor): the first vector of the outer product + vec2 (Tensor): the second vector of the outer product + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> vec1 = torch.arange(1., 4.) + >>> vec2 = torch.arange(1., 3.) + >>> M = torch.zeros(3, 2) + >>> torch.addr(M, vec1, vec2) + tensor([[ 1., 2.], + [ 2., 4.], + [ 3., 6.]]) + """ + +def adjoint(input: Tensor) -> Tensor: + r""" + adjoint(input: Tensor) -> Tensor + Returns a view of the tensor conjugated and with the last two dimensions transposed. + + ``x.adjoint()`` is equivalent to ``x.transpose(-2, -1).conj()`` for complex tensors and + to ``x.transpose(-2, -1)`` for real tensors. + + Args: + {input} + + Example:: + + >>> x = torch.arange(4, dtype=torch.float) + >>> A = torch.complex(x, x).reshape(2, 2) + >>> A + tensor([[0.+0.j, 1.+1.j], + [2.+2.j, 3.+3.j]]) + >>> A.adjoint() + tensor([[0.-0.j, 2.-2.j], + [1.-1.j, 3.-3.j]]) + >>> (A.adjoint() == A.mH).all() + tensor(True) + """ + +def affine_grid_generator( + theta: Tensor, + size: Sequence[_int | SymInt], + align_corners: _bool, +) -> Tensor: ... +def alias_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.alias`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def all(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +@overload +def all( + input: Tensor, + dim: _size | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +@overload +def all( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + all(input: Tensor, *, out=None) -> Tensor + + Tests if all elements in :attr:`input` evaluate to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.all(a) + tensor(False, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.all(a) + tensor(False) + + .. function:: all(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if all elements in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(4, 2).bool() + >>> a + tensor([[True, True], + [True, False], + [True, True], + [True, True]], dtype=torch.bool) + >>> torch.all(a, dim=1) + tensor([ True, False, True, True], dtype=torch.bool) + >>> torch.all(a, dim=0) + tensor([ True, False], dtype=torch.bool) + """ + +def allclose( + input: Tensor, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, +) -> _bool: + r""" + allclose(input: Tensor, other: Tensor, rtol: float = 1e-05, atol: float = 1e-08, equal_nan: bool = False) -> bool + + This function checks if :attr:`input` and :attr:`other` satisfy the condition: + + .. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other}_i \rvert + + elementwise, for all elements of :attr:`input` and :attr:`other`. The behaviour of this function is analogous to + `numpy.allclose `_ + + Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + atol (float, optional): absolute tolerance. Default: 1e-08 + rtol (float, optional): relative tolerance. Default: 1e-05 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + + Example:: + + >>> torch.allclose(torch.tensor([10000., 1e-07]), torch.tensor([10000.1, 1e-08])) + False + >>> torch.allclose(torch.tensor([10000., 1e-08]), torch.tensor([10000.1, 1e-09])) + True + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')])) + False + >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]), equal_nan=True) + True + """ + +def alpha_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def alpha_dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: + r""" + alpha_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.alpha_dropout` + """ + +def amax( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amax(input, dim=None, keepdim=False, *, out=None) -> Tensor + + Returns the maximum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.8177, 1.4878, -0.2491, 0.9130], + [-0.7158, 1.1775, 2.0992, 0.4817], + [-0.0053, 0.0164, -1.3738, -0.0507], + [ 1.9700, 1.1106, -1.0318, -1.0816]]) + >>> torch.amax(a, 1) + tensor([1.4878, 2.0992, 0.0164, 1.9700]) + """ + +def amin( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amin(input, dim=None, keepdim=False, *, out=None) -> Tensor + + Returns the minimum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.6451, -0.4866, 0.2987, -1.3312], + [-0.5744, 1.2980, 1.8397, -0.2713], + [ 0.9128, 0.9214, -1.7268, -0.2995], + [ 0.9023, 0.4853, 0.9075, -1.6165]]) + >>> torch.amin(a, 1) + tensor([-1.3312, -0.5744, -1.7268, -1.6165]) + """ + +def aminmax( + input: Tensor, + *, + dim: _int | None = None, + keepdim: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.aminmax: + r""" + aminmax(input, *, dim=None, keepdim=False, out=None) -> (Tensor min, Tensor max) + + Computes the minimum and maximum values of the :attr:`input` tensor. + + Args: + input (Tensor): + The input tensor + + Keyword Args: + dim (Optional[int]): + The dimension along which to compute the values. If `None`, + computes the values over the entire :attr:`input` tensor. + Default is `None`. + keepdim (bool): + If `True`, the reduced dimensions will be kept in the output + tensor as dimensions with size 1 for broadcasting, otherwise + they will be removed, as if calling (:func:`torch.squeeze`). + Default is `False`. + out (Optional[Tuple[Tensor, Tensor]]): + Optional tensors on which to write the result. Must have the same + shape and dtype as the expected output. + Default is `None`. + + Returns: + A named tuple `(min, max)` containing the minimum and maximum values. + + Raises: + RuntimeError + If any of the dimensions to compute the values over has size 0. + + .. note:: + NaN values are propagated to the output if at least one value is NaN. + + .. seealso:: + :func:`torch.amin` computes just the minimum value + :func:`torch.amax` computes just the maximum value + + Example:: + + >>> torch.aminmax(torch.tensor([1, -3, 5])) + torch.return_types.aminmax( + min=tensor(-3), + max=tensor(5)) + + >>> # aminmax propagates NaNs + >>> torch.aminmax(torch.tensor([1, -3, 5, torch.nan])) + torch.return_types.aminmax( + min=tensor(nan), + max=tensor(nan)) + + >>> t = torch.arange(10).view(2, 5) + >>> t + tensor([[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]]) + >>> t.aminmax(dim=0, keepdim=True) + torch.return_types.aminmax( + min=tensor([[0, 1, 2, 3, 4]]), + max=tensor([[5, 6, 7, 8, 9]])) + """ + +def angle(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + angle(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the element-wise angle (in radians) of the given :attr:`input` tensor. + + .. math:: + \text{out}_{i} = angle(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + .. note:: Starting in PyTorch 1.8, angle returns pi for negative real numbers, + zero for non-negative real numbers, and propagates NaNs. Previously + the function would return zero for all real numbers and not propagate + floating-point NaNs. + + Example:: + + >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159 + tensor([ 135., 135, -45]) + """ + +@overload +def any(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _size | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def arange( + start: Number, + end: Number, + step: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number, + end: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + end: Number, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + end: Number | _complex | PySymType, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number | _complex | PySymType, + end: Number | _complex | PySymType, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +@overload +def arange( + start: Number | _complex | PySymType, + end: Number | _complex | PySymType, + step: Number | _complex | PySymType = 1, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + arange(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil` + with values from the interval ``[start, end)`` taken with common difference + :attr:`step` beginning from `start`. + + Note: When using floating-point dtypes (especially reduced precision types like ``bfloat16``), + the results may be affected by floating-point rounding behavior. Some values in the sequence + might not be exactly representable in certain floating-point formats, which can lead to + repeated values or unexpected rounding. For precise sequences, it is recommended to use + integer dtypes instead of floating-point dtypes. + + Note that non-integer :attr:`step` is subject to floating point rounding errors when + comparing against :attr:`end`; to avoid inconsistency, we advise subtracting a small epsilon from :attr:`end` + in such cases. + + .. math:: + \text{out}_{{i+1}} = \text{out}_{i} + \text{step} + + Args: + start (Number, optional): the starting value for the set of points. Default: ``0``. + end (Number): the ending value for the set of points + step (Number, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.arange(5) + tensor([ 0, 1, 2, 3, 4]) + >>> torch.arange(1, 4) + tensor([ 1, 2, 3]) + >>> torch.arange(1, 2.5, 0.5) + tensor([ 1.0000, 1.5000, 2.0000]) + """ + +def arccos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arccos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.acos`. + """ + +def arccos_(input: Tensor) -> Tensor: + r""" + arccos_(input) -> Tensor + + In-place version of :func:`torch.arccos` + """ + +def arccosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arccosh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.acosh`. + """ + +def arccosh_(input: Tensor) -> Tensor: + r""" + arccosh_(input) -> Tensor + + In-place version of :func:`torch.arccosh` + """ + +def arcsin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arcsin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.asin`. + """ + +def arcsin_(input: Tensor) -> Tensor: + r""" + arcsin_(input) -> Tensor + + In-place version of :func:`torch.arcsin` + """ + +def arcsinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arcsinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.asinh`. + """ + +def arcsinh_(input: Tensor) -> Tensor: + r""" + arcsinh_(input) -> Tensor + + In-place version of :func:`torch.arcsinh` + """ + +def arctan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arctan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.atan`. + """ + +def arctan2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + arctan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + Alias for :func:`torch.atan2`. + """ + +def arctan_(input: Tensor) -> Tensor: + r""" + arctan_(input) -> Tensor + + In-place version of :func:`torch.arctan` + """ + +def arctanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + arctanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.atanh`. + """ + +def arctanh_(input: Tensor) -> Tensor: + r""" + arctanh_(input) -> Tensor + + In-place version of :func:`torch.arctanh` + """ + +def argmax( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmax(input) -> LongTensor + + Returns the indices of the maximum value of all elements in the :attr:`input` tensor. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple maximal values then the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a) + tensor(0) + + .. function:: argmax(input, dim, keepdim=False) -> LongTensor + :noindex: + + Returns the indices of the maximum values of a tensor across a dimension. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmax of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a, dim=1) + tensor([ 0, 2, 0, 1]) + """ + +def argmin( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmin(input, dim=None, keepdim=False) -> LongTensor + + Returns the indices of the minimum value(s) of the flattened tensor or along a dimension + + This is the second value returned by :meth:`torch.min`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple minimal values then the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmin of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.1139, 0.2254, -0.1381, 0.3687], + [ 1.0100, -1.1975, -0.0102, -0.4732], + [-0.9240, 0.1207, -0.7506, -1.0213], + [ 1.7809, -1.2960, 0.9384, 0.1438]]) + >>> torch.argmin(a) + tensor(13) + >>> torch.argmin(a, dim=1) + tensor([ 2, 1, 3, 1]) + >>> torch.argmin(a, dim=1, keepdim=True) + tensor([[2], + [1], + [3], + [1]]) + """ + +@overload +def argsort( + input: Tensor, + *, + stable: _bool, + dim: _int = -1, + descending: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +@overload +def argsort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +def argwhere(input: Tensor) -> Tensor: + r""" + argwhere(input) -> Tensor + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + .. note:: + This function is similar to NumPy's `argwhere`. + + When :attr:`input` is on CUDA, this function causes host-device synchronization. + + Args: + {input} + + Example:: + + >>> t = torch.tensor([1, 0, 1]) + >>> torch.argwhere(t) + tensor([[0], + [2]]) + >>> t = torch.tensor([[1, 0, 1], [0, 1, 1]]) + >>> torch.argwhere(t) + tensor([[0, 0], + [0, 2], + [1, 1], + [1, 2]]) + """ + +def as_strided( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided(input, size, stride, storage_offset=None) -> Tensor + + Create a view of an existing `torch.Tensor` :attr:`input` with specified + :attr:`size`, :attr:`stride` and :attr:`storage_offset`. + + .. warning:: + Prefer using other view functions, like :meth:`torch.Tensor.view` or + :meth:`torch.Tensor.expand`, to setting a view's strides manually with + `as_strided`, as this function will throw an error on non-standard Pytorch + backends (that do not have a concept of stride) and the result will depend + on the current layout in memory. The constructed view must only refer to + elements within the Tensor's storage or a runtime error will be thrown. + If the generated view is "overlapped" (with multiple indices referring to + the same element in memory), the behavior of inplace operations on this view + is undefined (and might not throw runtime errors). + + Args: + input (Tensor): the input tensor. + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor. + If ``None``, the storage_offset of the output tensor will match the input tensor. + + Example:: + + >>> x = torch.randn(3, 3) + >>> x + tensor([[ 0.9039, 0.6291, 1.0795], + [ 0.1586, 2.1939, -0.4900], + [-0.1909, -0.7503, 1.9355]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2)) + >>> t + tensor([[0.9039, 1.0795], + [0.6291, 0.1586]]) + >>> t = torch.as_strided(x, (2, 2), (1, 2), 1) + tensor([[0.6291, 0.1586], + [1.0795, 2.1939]]) + """ + +def as_strided_( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided_(input, size, stride, storage_offset=None) -> Tensor + + In-place version of :func:`torch.as_strided` + """ + +def as_strided_copy( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.as_strided`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def as_strided_scatter( + input: Tensor, + src: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided_scatter(input, src, size, stride, storage_offset=None) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` along + the elements corresponding to the result of calling + input.as_strided(size, stride, storage_offset). + + This function returns a tensor with fresh storage; it does not + return a view. + + Args: + input (Tensor): the input tensor. + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + `torch.as_strided(input, size, stride, storage_offset)` + + Example:: + + >>> a = torch.arange(4).reshape(2, 2) + 1 + >>> a + tensor([[1, 2], + [3, 4]]) + >>> b = torch.zeros(3, 3) + >>> b + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> torch.as_strided_scatter(b, a, (2, 2), (1, 2)) + tensor([[1., 3., 2.], + [4., 0., 0.], + [0., 0., 0.]]) + """ + +def as_tensor( + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, +) -> Tensor: + r""" + as_tensor(data: Any, *, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) -> Tensor + + Converts :attr:`data` into a tensor, sharing data and preserving autograd + history if possible. + + If :attr:`data` is already a tensor with the requested dtype and device + then :attr:`data` itself is returned, but if :attr:`data` is a + tensor with a different dtype or device then it's copied as if using + `data.to(dtype=dtype, device=device)`. + + If :attr:`data` is a NumPy array (an ndarray) with the same dtype and device then a + tensor is constructed using :func:`torch.from_numpy`. + + If :attr:`data` is a CuPy array, the returned tensor will be located on the same device as the CuPy array unless + specifically overwritten by :attr:`device` or a default device. The device of the CuPy array is inferred from the + pointer of the array using `cudaPointerGetAttributes` unless :attr:`device` is provided with an explicit device index. + + .. seealso:: + + :func:`torch.tensor` never shares its data and creates a new "leaf tensor" (see :doc:`/notes/autograd`). + + + Args: + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + + + Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a, device=torch.device('cuda')) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([1, 2, 3]) + """ + +def asarray( + obj: Any, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + copy: _bool | None = None, + requires_grad: _bool | None = None, +) -> Tensor: + r""" + asarray(obj: Any, *, dtype: Optional[dtype], device: Optional[DeviceLikeType], copy: Optional[bool] = None, requires_grad: Optional[bool] = None) -> Tensor # noqa: B950 + + Converts :attr:`obj` to a tensor. + + :attr:`obj` can be one of: + + 1. a tensor + 2. a NumPy array or a NumPy scalar + 3. a DLPack capsule + 4. an object that implements Python's buffer protocol + 5. a scalar + 6. a sequence of scalars + + When :attr:`obj` is a tensor, NumPy array, or DLPack capsule the returned tensor will, + by default, have the same requires_grad as :attr:`obj` (defaulting to False), have the + same datatype, be on the same device, and share memory with it. These properties can be + controlled with the :attr:`dtype`, :attr:`device`, :attr:`copy`, and + :attr:`requires_grad` keyword arguments. If the returned tensor is of a different + datatype, on a different device, or a copy is requested then it will not share its + memory with :attr:`obj`. If :attr:`requires_grad` is ``True`` (or ``None``, and + :attr:`obj` was a tensor with requires_grad set), then the returned tensor will require + a gradient, and if :attr:`obj` is also a tensor with an autograd history then the + returned tensor will have the same history. + + When :attr:`obj` is not a tensor, NumPy array, or DLPack capsule but implements Python's + buffer protocol then the buffer is interpreted as an array of bytes grouped according to + the size of the datatype passed to the :attr:`dtype` keyword argument. (If no datatype is + passed then the default floating point datatype is used, instead.) The returned tensor + will have the specified datatype (or default floating point datatype if none is specified) + and, by default, be on the CPU device and share memory with the buffer. + + When :attr:`obj` is a NumPy scalar, the returned tensor will be a 0-dimensional tensor on + the CPU and that doesn't share its memory (i.e. ``copy=True``). By default datatype will + be the PyTorch datatype corresponding to the NumPy's scalar's datatype. + + When :attr:`obj` is none of the above but a scalar, or a sequence of scalars then the + returned tensor will, by default, infer its datatype from the scalar values, be on the + current default device, and not share its memory. + + .. seealso:: + + :func:`torch.tensor` creates a tensor that always copies the data from the input object. + :func:`torch.from_numpy` creates a tensor that always shares memory from NumPy arrays. + :func:`torch.frombuffer` creates a tensor that always shares memory from objects that + implement the buffer protocol. + :func:`torch.from_dlpack` creates a tensor that always shares memory from + DLPack capsules. + + Args: + obj (object): a tensor, NumPy array, DLPack Capsule, object that implements Python's + buffer protocol, scalar, or sequence of scalars. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the datatype of the returned tensor. + Default: ``None``, which causes the datatype of the returned tensor to be + inferred from :attr:`obj`. + copy (bool, optional): controls whether the returned tensor shares memory with :attr:`obj`. + Default: ``None``, which causes the returned tensor to share memory with :attr:`obj` + whenever possible. If ``True`` then the returned tensor does not share its memory. + If ``False`` then the returned tensor shares its memory with :attr:`obj` and an + error is thrown if it cannot. + device (:class:`torch.device`, optional): the device of the returned tensor. + Default: ``None``, which causes the device of :attr:`obj` to be used. Or, if + :attr:`obj` is a Python sequence, the current default device will be used. + requires_grad (bool, optional): whether the returned tensor requires grad. + Default: ``None``, which causes requires_grad for the returned tensor to be + inferred from :attr:`obj`. If ``True``, then the returned tensor will require + a gradient, and if :attr:`obj` is also a tensor with an autograd history then + the returned tensor will have the same history. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> # Shares memory with tensor 'a' + >>> b = torch.asarray(a) + >>> a.data_ptr() == b.data_ptr() + True + >>> # Forces memory copy + >>> c = torch.asarray(a, copy=True) + >>> a.data_ptr() == c.data_ptr() + False + + >>> a = torch.tensor([1., 2., 3.], requires_grad=True) + >>> b = a + 2 + >>> b + tensor([3., 4., 5.], grad_fn=) + >>> # Shares memory with tensor 'b', with no grad + >>> c = torch.asarray(b, requires_grad=False) + >>> c + tensor([3., 4., 5.]) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> d = torch.asarray(b, requires_grad=True) + >>> d + tensor([3., 4., 5.], grad_fn=) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> e = torch.asarray(b) + >>> e + tensor([3., 4., 5.], grad_fn=) + + >>> array = numpy.array([1, 2, 3]) + >>> # Shares memory with array 'array' + >>> t1 = torch.asarray(array) + >>> array.__array_interface__['data'][0] == t1.data_ptr() + True + >>> # Copies memory due to dtype mismatch + >>> t2 = torch.asarray(array, dtype=torch.float32) + >>> array.__array_interface__['data'][0] == t2.data_ptr() + False + + >>> scalar = numpy.float64(0.5) + >>> torch.asarray(scalar) + tensor(0.5000, dtype=torch.float64) + """ + +def asin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + asin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arcsine of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \sin^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5962, 1.4985, -0.4396, 1.4525]) + >>> torch.asin(a) + tensor([-0.6387, nan, -0.4552, nan]) + """ + +def asin_(input: Tensor) -> Tensor: + r""" + asin_(input) -> Tensor + + In-place version of :func:`torch.asin` + """ + +def asinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + asinh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic sine of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \sinh^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ]) + >>> torch.asinh(a) + tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ]) + """ + +def asinh_(input: Tensor) -> Tensor: + r""" + asinh_(input) -> Tensor + + In-place version of :func:`torch.asinh` + """ + +def atan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + atan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arctangent of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \tan^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.2341, 0.2539, -0.6256, -0.6448]) + >>> torch.atan(a) + tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) + """ + +def atan2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + atan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Element-wise arctangent of :math:`\text{input}_{i} / \text{other}_{i}` + with consideration of the quadrant. Returns a new tensor with the signed angles + in radians between vector :math:`(\text{other}_{i}, \text{input}_{i})` + and vector :math:`(1, 0)`. (Note that :math:`\text{other}_{i}`, the second + parameter, is the x-coordinate, while :math:`\text{input}_{i}`, the first + parameter, is the y-coordinate.) + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.9041, 0.0196, -0.3108, -2.4423]) + >>> torch.atan2(a, torch.randn(4)) + tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) + """ + +def atan_(input: Tensor) -> Tensor: + r""" + atan_(input) -> Tensor + + In-place version of :func:`torch.atan` + """ + +def atanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + atanh(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the inverse hyperbolic tangent of the elements of :attr:`input`. + + Note: + The domain of the inverse hyperbolic tangent is `(-1, 1)` and values outside this range + will be mapped to ``NaN``, except for the values `1` and `-1` for which the output is + mapped to `+/-INF` respectively. + + .. math:: + \text{out}_{i} = \tanh^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4).uniform_(-1, 1) + >>> a + tensor([ -0.9385, 0.2968, -0.8591, -0.1871 ]) + >>> torch.atanh(a) + tensor([ -1.7253, 0.3060, -1.2899, -0.1893 ]) + """ + +def atanh_(input: Tensor) -> Tensor: + r""" + atanh_(input) -> Tensor + + In-place version of :func:`torch.atanh` + """ + +def avg_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + ceil_mode: _bool = False, + count_include_pad: _bool = True, +) -> Tensor: ... +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices in :attr:`batch1` + and :attr:`batch2`. + :attr:`input` is added to the final result. + + :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same + number of matrices. + + If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a + :math:`(b \times m \times p)` tensor, then :attr:`input` must be + :ref:`broadcastable ` with a + :math:`(b \times n \times p)` tensor and :attr:`out` will be a + :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the + same as the scaling factors used in :meth:`torch.addbmm`. + + .. math:: + \text{out}_i = \beta\ \text{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) + + If :attr:`beta` is 0, then the content of :attr:`input` will be ignored, and `nan` and `inf` in + it will not be propagated. + + For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and + :attr:`alpha` must be real numbers, otherwise they should be integers. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + + Example:: + + >>> M = torch.randn(10, 3, 5) + >>> batch1 = torch.randn(10, 3, 4) + >>> batch2 = torch.randn(10, 4, 5) + >>> torch.baddbmm(M, batch1, batch2).size() + torch.Size([10, 3, 5]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the tensor to be added + batch1 (Tensor): the first batch of matrices to be multiplied + batch2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def bartlett_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + bartlett_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Bartlett window function. + + .. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.bartlett_window(L, periodic=True)`` equal to + ``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def bartlett_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + bartlett_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Bartlett window function. + + .. math:: + w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} + \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ + 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ + \end{cases}, + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.bartlett_window(L, periodic=True)`` equal to + ``torch.bartlett_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +def batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> Tensor: ... +def batch_norm_backward_elemt( + grad_out: Tensor, + input: Tensor, + mean: Tensor, + invstd: Tensor, + weight: Tensor | None, + sum_dy: Tensor, + sum_dy_xmu: Tensor, + count: Tensor, +) -> Tensor: ... +def batch_norm_backward_reduce( + grad_out: Tensor, + input: Tensor, + mean: Tensor, + invstd: Tensor, + weight: Tensor | None, + input_g: _bool, + weight_g: _bool, + bias_g: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def batch_norm_elemt( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + mean: Tensor, + invstd: Tensor, + eps: _float, + *, + out: Tensor | None = None, +) -> Tensor: ... +def batch_norm_gather_stats( + input: Tensor, + mean: Tensor, + invstd: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, + eps: _float, + count: _int, +) -> tuple[Tensor, Tensor]: ... +def batch_norm_gather_stats_with_counts( + input: Tensor, + mean: Tensor, + invstd: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, + eps: _float, + counts: Tensor, +) -> tuple[Tensor, Tensor]: ... +def batch_norm_stats(input: Tensor, eps: _float) -> tuple[Tensor, Tensor]: ... +def batch_norm_update_stats( + input: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + momentum: _float, +) -> tuple[Tensor, Tensor]: ... +@overload +def bernoulli( + input: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor + + Draws binary random numbers (0 or 1) from a Bernoulli distribution. + + The :attr:`input` tensor should be a tensor containing probabilities + to be used for drawing the binary random number. + Hence, all values in :attr:`input` have to be in the range: + :math:`0 \leq \text{input}_i \leq 1`. + + The :math:`\text{i}^{th}` element of the output tensor will draw a + value :math:`1` according to the :math:`\text{i}^{th}` probability value given + in :attr:`input`. + + .. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) + + The returned :attr:`out` tensor only has values 0 or 1 and is of the same + shape as :attr:`input`. + + :attr:`out` can have integral ``dtype``, but :attr:`input` must have floating + point ``dtype``. + + Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) + """ + +@overload +def bernoulli( + input: Tensor, + p: _float, + *, + generator: Generator | None = None, +) -> Tensor: + r""" + bernoulli(input: Tensor, *, generator: Optional[Generator], out: Optional[Tensor]) -> Tensor + + Draws binary random numbers (0 or 1) from a Bernoulli distribution. + + The :attr:`input` tensor should be a tensor containing probabilities + to be used for drawing the binary random number. + Hence, all values in :attr:`input` have to be in the range: + :math:`0 \leq \text{input}_i \leq 1`. + + The :math:`\text{i}^{th}` element of the output tensor will draw a + value :math:`1` according to the :math:`\text{i}^{th}` probability value given + in :attr:`input`. + + .. math:: + \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) + + The returned :attr:`out` tensor only has values 0 or 1 and is of the same + shape as :attr:`input`. + + :attr:`out` can have integral ``dtype``, but :attr:`input` must have floating + point ``dtype``. + + Args: + input (Tensor): the input tensor of probability values for the Bernoulli distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] + >>> a + tensor([[ 0.1737, 0.0950, 0.3609], + [ 0.7148, 0.0289, 0.2676], + [ 0.9456, 0.8937, 0.7202]]) + >>> torch.bernoulli(a) + tensor([[ 1., 0., 0.], + [ 0., 0., 0.], + [ 1., 1., 1.]]) + + >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 + >>> torch.bernoulli(a) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 + >>> torch.bernoulli(a) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.], + [ 0., 0., 0.]]) + """ + +def bilinear( + input1: Tensor, + input2: Tensor, + weight: Tensor, + bias: Tensor | None = None, +) -> Tensor: ... +def binary_cross_entropy_with_logits( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + pos_weight: Tensor | None = None, + reduction: _int = 1, +) -> Tensor: ... +def bincount( + input: Tensor, + weights: Tensor | None = None, + minlength: _int | SymInt = 0, +) -> Tensor: + r""" + bincount(input, weights=None, minlength=0) -> Tensor + + Count the frequency of each value in an array of non-negative ints. + + The number of bins (size 1) is one larger than the largest value in + :attr:`input` unless :attr:`input` is empty, in which case the result is a + tensor of size 0. If :attr:`minlength` is specified, the number of bins is at least + :attr:`minlength` and if :attr:`input` is empty, then the result is tensor of size + :attr:`minlength` filled with zeros. If ``n`` is the value at position ``i``, + ``out[n] += weights[i]`` if :attr:`weights` is specified else + ``out[n] += 1``. + + Note: + This operation may produce nondeterministic gradients when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + Arguments: + input (Tensor): 1-d int tensor + weights (Tensor): optional, weight for each value in the input tensor. + Should be of same size as input tensor. + minlength (int): optional, minimum number of bins. Should be non-negative. + + Returns: + output (Tensor): a tensor of shape ``Size([max(input) + 1])`` if + :attr:`input` is non-empty, else ``Size(0)`` + + Example:: + + >>> input = torch.randint(0, 8, (5,), dtype=torch.int64) + >>> weights = torch.linspace(0, 1, steps=5) + >>> input, weights + (tensor([4, 3, 6, 3, 4]), + tensor([ 0.0000, 0.2500, 0.5000, 0.7500, 1.0000]) + + >>> torch.bincount(input) + tensor([0, 0, 0, 2, 2, 0, 1]) + + >>> input.bincount(weights) + tensor([0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 0.0000, 0.5000]) + """ + +def binomial( + count: Tensor, + prob: Tensor, + generator: Generator | None = None, +) -> Tensor: ... +@overload +def bitwise_and( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_and( + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_and( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_and(input, other, *, out=None) -> Tensor + + Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical AND. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([1, 0, 3], dtype=torch.int8) + >>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ False, True, False]) + """ + +@overload +def bitwise_left_shift( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +@overload +def bitwise_left_shift( + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +@overload +def bitwise_left_shift( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_left_shift(input, other, *, out=None) -> Tensor + + Computes the left arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i << \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_left_shift(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 24], dtype=torch.int8) + """ + +def bitwise_not(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + bitwise_not(input, *, out=None) -> Tensor + + Computes the bitwise NOT of the given input tensor. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical NOT. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_not(torch.tensor([-1, -2, 3], dtype=torch.int8)) + tensor([ 0, 1, -4], dtype=torch.int8) + """ + +@overload +def bitwise_or( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_or( + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_or( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_or(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical OR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -2, 3], dtype=torch.int8) + >>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, True, False]) + """ + +@overload +def bitwise_right_shift( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_right_shift( + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_right_shift( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_right_shift(input, other, *, out=None) -> Tensor + + Computes the right arithmetic shift of :attr:`input` by :attr:`other` bits. + The input tensor must be of integral type. This operator supports + :ref:`broadcasting to a common shape ` and + :ref:`type promotion `. + In any case, if the value of the right operand is negative or is greater + or equal to the number of bits in the promoted left operand, the behavior is undefined. + + The operation applied is: + + .. math:: + \text{out}_i = \text{input}_i >> \text{other}_i + + Args: + input (Tensor or Scalar): the first input tensor + other (Tensor or Scalar): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_right_shift(torch.tensor([-2, -7, 31], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-1, -7, 3], dtype=torch.int8) + """ + +@overload +def bitwise_xor( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def bitwise_xor( + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def bitwise_xor( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bitwise_xor(input, other, *, out=None) -> Tensor + + Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of + integral or Boolean types. For bool tensors, it computes the logical XOR. + + Args: + input: the first input tensor + other: the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8)) + tensor([-2, -2, 0], dtype=torch.int8) + >>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False])) + tensor([ True, False, False]) + """ + +@overload +def blackman_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + blackman_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Blackman window function. + + .. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.blackman_window(L, periodic=True)`` equal to + ``torch.blackman_window(L + 1, periodic=False)[:-1]``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def blackman_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + blackman_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Blackman window function. + + .. math:: + w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.blackman_window(L, periodic=True)`` equal to + ``torch.blackman_window(L + 1, periodic=False)[:-1]``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def bmm( + input: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bmm(input, mat2, *, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored in :attr:`input` + and :attr:`mat2`. + + :attr:`input` and :attr:`mat2` must be 3-D tensors each containing + the same number of matrices. + + If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a + :math:`(b \times m \times p)` tensor, :attr:`out` will be a + :math:`(b \times n \times p)` tensor. + + .. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + + Keyword Args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) + + .. function:: bmm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword Args: + out (Tensor, optional): the output tensor. + """ + +@overload +def bmm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bmm(input, mat2, *, out=None) -> Tensor + + Performs a batch matrix-matrix product of matrices stored in :attr:`input` + and :attr:`mat2`. + + :attr:`input` and :attr:`mat2` must be 3-D tensors each containing + the same number of matrices. + + If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` is a + :math:`(b \times m \times p)` tensor, :attr:`out` will be a + :math:`(b \times n \times p)` tensor. + + .. math:: + \text{out}_i = \text{input}_i \mathbin{@} \text{mat2}_i + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + + Keyword Args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.randn(10, 3, 4) + >>> mat2 = torch.randn(10, 4, 5) + >>> res = torch.bmm(input, mat2) + >>> res.size() + torch.Size([10, 3, 5]) + + .. function:: bmm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword Args: + out (Tensor, optional): the output tensor. + """ + +def broadcast_to(input: Tensor, size: Sequence[_int | SymInt]) -> Tensor: + r""" + broadcast_to(input, shape) -> Tensor + + Broadcasts :attr:`input` to the shape :attr:`\shape`. + Equivalent to calling ``input.expand(shape)``. See :meth:`~Tensor.expand` for details. + + Args: + input (Tensor): the input tensor. + shape (list, tuple, or :class:`torch.Size`): the new shape. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> torch.broadcast_to(x, (3, 3)) + tensor([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]) + """ + +@overload +def bucketize( + input: Tensor, + boundaries: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + + Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the + boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size + as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that + this behavior is opposite the behavior of + `numpy.digitize `_. + More formally, the returned index satisfies the following rules: + + .. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + + Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + + Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) + """ + +@overload +def bucketize( + self: Number | _complex | PySymType, + boundaries: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, +) -> Tensor: + r""" + bucketize(input, boundaries, *, out_int32=False, right=False, out=None) -> Tensor + + Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the + boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size + as :attr:`input`. If :attr:`right` is False (default), then the left boundary is open. Note that + this behavior is opposite the behavior of + `numpy.digitize `_. + More formally, the returned index satisfies the following rules: + + .. list-table:: + :widths: 15 85 + :header-rows: 1 + + * - :attr:`right` + - *returned index satisfies* + * - False + - ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]`` + * - True + - ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]`` + + Args: + input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + boundaries (Tensor): 1-D tensor, must contain a strictly increasing sequence, or the return value is undefined. + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): determines the behavior for values in :attr:`boundaries`. See the table above. + out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided. + + + Example:: + + >>> boundaries = torch.tensor([1, 3, 5, 7, 9]) + >>> boundaries + tensor([1, 3, 5, 7, 9]) + >>> v = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> v + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.bucketize(v, boundaries) + tensor([[1, 3, 4], + [1, 3, 4]]) + >>> torch.bucketize(v, boundaries, right=True) + tensor([[2, 3, 5], + [2, 3, 5]]) + """ + +def can_cast(from_: _dtype, to: _dtype) -> _bool: + r""" + can_cast(from_, to) -> bool + + Determines if a type conversion is allowed under PyTorch casting rules + described in the type promotion :ref:`documentation `. + + Args: + from\_ (dtype): The original :class:`torch.dtype`. + to (dtype): The target :class:`torch.dtype`. + + Example:: + + >>> torch.can_cast(torch.double, torch.float) + True + >>> torch.can_cast(torch.float, torch.int) + False + """ + +def cat( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cat(tensors, dim=0, *, out=None) -> Tensor + + Concatenates the given sequence of tensors in :attr:`tensors` in the given dimension. + All tensors must either have the same shape (except in the concatenating + dimension) or be a 1-D empty tensor with size ``(0,)``. + + :func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` + and :func:`torch.chunk`. + + :func:`torch.cat` can be best understood via examples. + + .. seealso:: + + :func:`torch.stack` concatenates the given sequence along a new dimension. + + Args: + tensors (sequence of Tensors): Non-empty tensors provided must have the same shape, + except in the cat dimension. + + dim (int, optional): the dimension over which the tensors are concatenated + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 0) + tensor([[ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497], + [ 0.6580, -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497]]) + >>> torch.cat((x, x, x), 1) + tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, + -1.0969, -0.4614], + [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, + -0.5790, 0.1497]]) + """ + +def ccol_indices_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +def ceil(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + ceil(input, *, out=None) -> Tensor + + Returns a new tensor with the ceil of the elements of :attr:`input`, + the smallest integer greater than or equal to each element. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + .. math:: + \text{out}_{i} = \left\lceil \text{input}_{i} \right\rceil + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.6341, -1.4208, -1.0900, 0.5826]) + >>> torch.ceil(a) + tensor([-0., -1., -1., 1.]) + """ + +def ceil_(input: Tensor) -> Tensor: + r""" + ceil_(input) -> Tensor + + In-place version of :func:`torch.ceil` + """ + +def celu( + input: Tensor, + alpha: Number | _complex | PySymType = 1.0, +) -> Tensor: ... +def celu_( + input: Tensor, + alpha: Number | _complex | PySymType = 1.0, +) -> Tensor: ... +def channel_shuffle(input: Tensor, groups: _int | SymInt) -> Tensor: ... +def cholesky_inverse( + input: Tensor, + upper: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cholesky_inverse(L, upper=False, *, out=None) -> Tensor + + Computes the inverse of a complex Hermitian or real symmetric + positive-definite matrix given its Cholesky decomposition. + + Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, + and :math:`L` its Cholesky decomposition such that: + + .. math:: + + A = LL^{\text{H}} + + where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, + and the transpose when :math:`L` is real-valued. + + Computes the inverse matrix :math:`A^{-1}`. + + Supports input of float, double, cfloat and cdouble dtypes. + Also supports batches of matrices, and if :math:`A` is a batch of matrices + then the output has the same batch dimensions. + + Args: + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False`` + + Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + + Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> torch.cholesky_inverse(L) + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + >>> A.inverse() + tensor([[ 1.9314, 1.2251, -0.0889], + [ 1.2251, 2.4439, 0.2122], + [-0.0889, 0.2122, 0.1412]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> torch.dist(torch.inverse(A), torch.cholesky_inverse(L)) + tensor(5.6358e-7) + """ + +def cholesky_solve( + input: Tensor, + input2: Tensor, + upper: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cholesky_solve(B, L, upper=False, *, out=None) -> Tensor + + Computes the solution of a system of linear equations with complex Hermitian + or real symmetric positive-definite lhs given its Cholesky decomposition. + + Let :math:`A` be a complex Hermitian or real symmetric positive-definite matrix, + and :math:`L` its Cholesky decomposition such that: + + .. math:: + + A = LL^{\text{H}} + + where :math:`L^{\text{H}}` is the conjugate transpose when :math:`L` is complex, + and the transpose when :math:`L` is real-valued. + + Returns the solution :math:`X` of the following linear system: + + .. math:: + + AX = B + + Supports inputs of float, double, cfloat and cdouble dtypes. + Also supports batches of matrices, and if :math:`A` or :math:`B` is a batch of matrices + then the output has the same batch dimensions. + + Args: + B (Tensor): right-hand side tensor of shape `(*, n, k)` + where :math:`*` is zero or more batch dimensions + L (Tensor): tensor of shape `(*, n, n)` where `*` is zero or more batch dimensions + consisting of lower or upper triangular Cholesky decompositions of + symmetric or Hermitian positive-definite matrices. + upper (bool, optional): flag that indicates whether :math:`L` is lower triangular + or upper triangular. Default: ``False``. + + Keyword args: + out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`. + + Example:: + + >>> A = torch.randn(3, 3) + >>> A = A @ A.T + torch.eye(3) * 1e-3 # Creates a symmetric positive-definite matrix + >>> L = torch.linalg.cholesky(A) # Extract Cholesky decomposition + >>> B = torch.randn(3, 2) + >>> torch.cholesky_solve(B, L) + tensor([[ -8.1625, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + >>> A.inverse() @ B + tensor([[ -8.1626, 19.6097], + [ -5.8398, 14.2387], + [ -4.3771, 10.4173]]) + + >>> A = torch.randn(3, 2, 2, dtype=torch.complex64) + >>> A = A @ A.mH + torch.eye(2) * 1e-3 # Batch of Hermitian positive-definite matrices + >>> L = torch.linalg.cholesky(A) + >>> B = torch.randn(2, 1, dtype=torch.complex64) + >>> X = torch.cholesky_solve(B, L) + >>> torch.dist(X, A.inverse() @ B) + tensor(1.6881e-5) + """ + +def choose_qparams_optimized( + input: Tensor, + numel: _int, + n_bins: _int, + ratio: _float, + bit_width: _int, +) -> tuple[Tensor, Tensor]: ... +def chunk(input: Tensor, chunks: _int, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + chunk(input: Tensor, chunks: int, dim: int = 0) -> Tuple[Tensor, ...] + + Attempts to split a tensor into the specified number of chunks. Each chunk is a view of + the input tensor. + + + .. note:: + + This function may return fewer than the specified number of chunks! + + .. seealso:: + + :func:`torch.tensor_split` a function that always returns exactly the specified number of chunks + + If the tensor size along the given dimension :attr:`dim` is divisible by :attr:`chunks`, + all returned chunks will be the same size. + If the tensor size along the given dimension :attr:`dim` is not divisible by :attr:`chunks`, + all returned chunks will be the same size, except the last one. + If such division is not possible, this function may return fewer + than the specified number of chunks. + + Arguments: + input (Tensor): the tensor to split + chunks (int): number of chunks to return + dim (int): dimension along which to split the tensor + + Example: + >>> torch.arange(11).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10])) + >>> torch.arange(12).chunk(6) + (tensor([0, 1]), + tensor([2, 3]), + tensor([4, 5]), + tensor([6, 7]), + tensor([8, 9]), + tensor([10, 11])) + >>> torch.arange(13).chunk(6) + (tensor([0, 1, 2]), + tensor([3, 4, 5]), + tensor([6, 7, 8]), + tensor([ 9, 10, 11]), + tensor([12])) + """ + +@overload +def clamp( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clamp(input, min=None, max=None, *, out=None) -> Tensor + + Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. + Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + + .. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + + If :attr:`min` is ``None``, there is no lower bound. + Or, if :attr:`max` is ``None`` there is no upper bound. + + + .. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + + Args: + input (Tensor): the input tensor. + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + """ + +@overload +def clamp( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clamp(input, min=None, max=None, *, out=None) -> Tensor + + Clamps all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]`. + Letting min_value and max_value be :attr:`min` and :attr:`max`, respectively, this returns: + + .. math:: + y_i = \min(\max(x_i, \text{min\_value}_i), \text{max\_value}_i) + + If :attr:`min` is ``None``, there is no lower bound. + Or, if :attr:`max` is ``None`` there is no upper bound. + + + .. note:: + If :attr:`min` is greater than :attr:`max` :func:`torch.clamp(..., min, max) ` + sets all elements in :attr:`input` to the value of :attr:`max`. + + Args: + input (Tensor): the input tensor. + min (Number or Tensor, optional): lower-bound of the range to be clamped to + max (Number or Tensor, optional): upper-bound of the range to be clamped to + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.7120, 0.1734, -0.0478, -0.0922]) + >>> torch.clamp(a, min=-0.5, max=0.5) + tensor([-0.5000, 0.1734, -0.0478, -0.0922]) + + >>> min = torch.linspace(-1, 1, steps=4) + >>> torch.clamp(a, min=min) + tensor([-1.0000, 0.1734, 0.3333, 1.0000]) + """ + +@overload +def clamp_( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, +) -> Tensor: + r""" + clamp_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clamp` + """ + +@overload +def clamp_( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, +) -> Tensor: + r""" + clamp_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clamp` + """ + +@overload +def clamp_max( + input: Tensor, + max: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max( + input: Tensor, + max: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Tensor) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Number | _complex | PySymType) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Tensor) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Number | _complex | PySymType) -> Tensor: ... +@overload +def clip( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clip(input, min=None, max=None, *, out=None) -> Tensor + + Alias for :func:`torch.clamp`. + """ + +@overload +def clip( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + clip(input, min=None, max=None, *, out=None) -> Tensor + + Alias for :func:`torch.clamp`. + """ + +@overload +def clip_( + input: Tensor, + min: Tensor | None = None, + max: Tensor | None = None, +) -> Tensor: + r""" + clip_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clip` + """ + +@overload +def clip_( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, +) -> Tensor: + r""" + clip_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clip` + """ + +def clone( + input: Tensor, + *, + memory_format: memory_format | None = None, +) -> Tensor: + r""" + clone(input, *, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of :attr:`input`. + + .. note:: + + This function is differentiable, so gradients will flow back from the + result of this operation to :attr:`input`. To create a tensor without an + autograd relationship to :attr:`input` see :meth:`~Tensor.detach`. + + In addition, when ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense (contiguous) format. + + Args: + input (Tensor): the input tensor. + + Keyword args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned tensor. Default: ``torch.preserve_format``. + """ + +def col_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.col_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def column_stack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + column_stack(tensors, *, out=None) -> Tensor + + Creates a new tensor by horizontally stacking the tensors in :attr:`tensors`. + + Equivalent to ``torch.hstack(tensors)``, except each zero or one dimensional tensor ``t`` + in :attr:`tensors` is first reshaped into a ``(t.numel(), 1)`` column before being stacked horizontally. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.column_stack((a, b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + >>> a = torch.arange(5) + >>> b = torch.arange(10).reshape(5, 2) + >>> torch.column_stack((a, b, b)) + tensor([[0, 0, 1, 0, 1], + [1, 2, 3, 2, 3], + [2, 4, 5, 4, 5], + [3, 6, 7, 6, 7], + [4, 8, 9, 8, 9]]) + """ + +def combinations( + input: Tensor, + r: _int = 2, + with_replacement: _bool = False, +) -> Tensor: + r""" + combinations(input: Tensor, r: int = 2, with_replacement: bool = False) -> seq + + Compute combinations of length :math:`r` of the given tensor. The behavior is similar to + python's `itertools.combinations` when `with_replacement` is set to `False`, and + `itertools.combinations_with_replacement` when `with_replacement` is set to `True`. + + Arguments: + input (Tensor): 1D vector. + r (int, optional): number of elements to combine + with_replacement (bool, optional): whether to allow duplication in combination + + Returns: + Tensor: A tensor equivalent to converting all the input tensors into lists, do + `itertools.combinations` or `itertools.combinations_with_replacement` on these + lists, and finally convert the resulting list into tensor. + + Example:: + + >>> a = [1, 2, 3] + >>> list(itertools.combinations(a, r=2)) + [(1, 2), (1, 3), (2, 3)] + >>> list(itertools.combinations(a, r=3)) + [(1, 2, 3)] + >>> list(itertools.combinations_with_replacement(a, r=2)) + [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] + >>> tensor_a = torch.tensor(a) + >>> torch.combinations(tensor_a) + tensor([[1, 2], + [1, 3], + [2, 3]]) + >>> torch.combinations(tensor_a, r=3) + tensor([[1, 2, 3]]) + >>> torch.combinations(tensor_a, with_replacement=True) + tensor([[1, 1], + [1, 2], + [1, 3], + [2, 2], + [2, 3], + [3, 3]]) + """ + +def complex( + real: Tensor, + imag: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + complex(real, imag, *, out=None) -> Tensor + + Constructs a complex tensor with its real part equal to :attr:`real` and its + imaginary part equal to :attr:`imag`. + + Args: + real (Tensor): The real part of the complex tensor. Must be half, float or double. + imag (Tensor): The imaginary part of the complex tensor. Must be same dtype + as :attr:`real`. + + Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + + Example:: + + >>> real = torch.tensor([1, 2], dtype=torch.float32) + >>> imag = torch.tensor([3, 4], dtype=torch.float32) + >>> z = torch.complex(real, imag) + >>> z + tensor([(1.+3.j), (2.+4.j)]) + >>> z.dtype + torch.complex64 + """ + +def concat( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concat(tensors, dim=0, *, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +def concatenate( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concatenate(tensors, axis=0, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +def conj(input: Tensor) -> Tensor: + r""" + conj(input) -> Tensor + + Returns a view of :attr:`input` with a flipped conjugate bit. If :attr:`input` has a non-complex dtype, + this function just returns :attr:`input`. + + .. note:: + :func:`torch.conj` performs a lazy conjugation, but the actual conjugated tensor can be materialized + at any time using :func:`torch.resolve_conj`. + + .. warning:: In the future, :func:`torch.conj` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> x.is_conj() + False + >>> y = torch.conj(x) + >>> y.is_conj() + True + """ + +def conj_physical(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + conj_physical(input, *, out=None) -> Tensor + + Computes the element-wise conjugate of the given :attr:`input` tensor. + If :attr:`input` has a non-complex dtype, this function just returns :attr:`input`. + + .. note:: + This performs the conjugate operation regardless of the fact conjugate bit is set or not. + + .. warning:: In the future, :func:`torch.conj_physical` may return a non-writeable view for an :attr:`input` of + non-complex dtype. It's recommended that programs not modify the tensor returned by :func:`torch.conj_physical` + when :attr:`input` is of non-complex dtype to be compatible with this change. + + .. math:: + \text{out}_{i} = conj(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.conj_physical(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j])) + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + """ + +def conj_physical_(input: Tensor) -> Tensor: + r""" + conj_physical_(input) -> Tensor + + In-place version of :func:`torch.conj_physical` + """ + +def constant_pad_nd( + input: Tensor, + pad: Sequence[_int | SymInt], + value: Number | _complex | PySymType = 0, +) -> Tensor: ... +@overload +def conv1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +@overload +def conv3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: str = "valid", + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, + groups: _int | SymInt = 1, +) -> Tensor: ... +def conv_tbc( + input: Tensor, + weight: Tensor, + bias: Tensor, + pad: _int = 0, +) -> Tensor: ... +def conv_transpose1d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def conv_transpose2d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def conv_transpose3d( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, + stride: _int | SymInt | Sequence[_int | SymInt] = 1, + padding: _int | SymInt | Sequence[_int | SymInt] = 0, + output_padding: _int | SymInt | Sequence[_int | SymInt] = 0, + groups: _int | SymInt = 1, + dilation: _int | SymInt | Sequence[_int | SymInt] = 1, +) -> Tensor: ... +def convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + transposed: _bool, + output_padding: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +@overload +def copysign( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + copysign(input, other, *, out=None) -> Tensor + + Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + + .. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} + + + Supports :ref:`broadcasting to a common shape `, + and integer and float inputs. + + Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + + .. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + """ + +@overload +def copysign( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + copysign(input, other, *, out=None) -> Tensor + + Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + + .. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} + + + Supports :ref:`broadcasting to a common shape `, + and integer and float inputs. + + Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + + .. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + """ + +def corrcoef(input: Tensor) -> Tensor: + r""" + corrcoef(input) -> Tensor + + Estimates the Pearson product-moment correlation coefficient matrix of the variables given by the :attr:`input` matrix, + where rows are the variables and columns are the observations. + + .. note:: + + The correlation coefficient matrix R is computed using the covariance matrix C as given by + :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }` + + .. note:: + + Due to floating point rounding, the resulting array may not be Hermitian and its diagonal elements may not be 1. + The real and imaginary values are clipped to the interval [-1, 1] in an attempt to improve this situation. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Returns: + (Tensor) The correlation coefficient matrix of the variables. + + .. seealso:: + + :func:`torch.cov` covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 1, 2], [2, 1, 0]]) + >>> torch.corrcoef(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> x = torch.randn(2, 4) + >>> x + tensor([[-0.2678, -0.0908, -0.3766, 0.2780], + [-0.5812, 0.1535, 0.2387, 0.2350]]) + >>> torch.corrcoef(x) + tensor([[1.0000, 0.3582], + [0.3582, 1.0000]]) + >>> torch.corrcoef(x[0]) + tensor(1.) + """ + +def cos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + cos(input, *, out=None) -> Tensor + + Returns a new tensor with the cosine of the elements of :attr:`input` given in radians. + + .. math:: + \text{out}_{i} = \cos(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 1.4309, 1.2706, -0.8562, 0.9796]) + >>> torch.cos(a) + tensor([ 0.1395, 0.2957, 0.6553, 0.5574]) + """ + +def cos_(input: Tensor) -> Tensor: + r""" + cos_(input) -> Tensor + + In-place version of :func:`torch.cos` + """ + +def cosh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + cosh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic cosine of the elements of + :attr:`input`. + + .. math:: + \text{out}_{i} = \cosh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.1632, 1.1835, -0.6979, -0.7325]) + >>> torch.cosh(a) + tensor([ 1.0133, 1.7860, 1.2536, 1.2805]) + """ + +def cosh_(input: Tensor) -> Tensor: + r""" + cosh_(input) -> Tensor + + In-place version of :func:`torch.cosh` + """ + +def cosine_embedding_loss( + input1: Tensor, + input2: Tensor, + target: Tensor, + margin: _float = 0.0, + reduction: _int = 1, +) -> Tensor: ... +def cosine_similarity( + x1: Tensor, + x2: Tensor, + dim: _int = 1, + eps: _float = 1e-08, +) -> Tensor: ... +@overload +def count_nonzero(input: Tensor, dim: _int | None = None) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +@overload +def count_nonzero(input: Tensor, dim: _size) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +def cov( + input: Tensor, + *, + correction: _int = 1, + fweights: Tensor | None = None, + aweights: Tensor | None = None, +) -> Tensor: + r""" + cov(input, *, correction=1, fweights=None, aweights=None) -> Tensor + + Estimates the covariance matrix of the variables given by the :attr:`input` matrix, where rows are + the variables and columns are the observations. + + A covariance matrix is a square matrix giving the covariance of each pair of variables. The diagonal contains + the variance of each variable (covariance of a variable with itself). By definition, if :attr:`input` represents + a single variable (Scalar or 1D) then its variance is returned. + + The sample covariance of the variables :math:`x` and :math:`y` is given by: + + .. math:: + \text{cov}(x,y) = \frac{\sum^{N}_{i = 1}(x_{i} - \bar{x})(y_{i} - \bar{y})}{\max(0,~N~-~\delta N)} + + where :math:`\bar{x}` and :math:`\bar{y}` are the simple means of the :math:`x` and :math:`y` respectively, and + :math:`\delta N` is the :attr:`correction`. + + If :attr:`fweights` and/or :attr:`aweights` are provided, the weighted covariance + is calculated, which is given by: + + .. math:: + \text{cov}_w(x,y) = \frac{\sum^{N}_{i = 1}w_i(x_{i} - \mu_x^*)(y_{i} - \mu_y^*)} + {\max(0,~\sum^{N}_{i = 1}w_i~-~\frac{\sum^{N}_{i = 1}w_ia_i}{\sum^{N}_{i = 1}w_i}~\delta N)} + + where :math:`w` denotes :attr:`fweights` or :attr:`aweights` (``f`` and ``a`` for brevity) based on whichever is + provided, or :math:`w = f \times a` if both are provided, and + :math:`\mu_x^* = \frac{\sum^{N}_{i = 1}w_ix_{i} }{\sum^{N}_{i = 1}w_i}` is the weighted mean of the variable. If not + provided, ``f`` and/or ``a`` can be seen as a :math:`\mathbb{1}` vector of appropriate size. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Keyword Args: + correction (int, optional): difference between the sample size and sample degrees of freedom. + Defaults to Bessel's correction, ``correction = 1`` which returns the unbiased estimate, + even if both :attr:`fweights` and :attr:`aweights` are specified. ``correction = 0`` + will return the simple average. Defaults to ``1``. + fweights (tensor, optional): A Scalar or 1D tensor of observation vector frequencies representing the number of + times each observation should be repeated. Its numel must equal the number of columns of :attr:`input`. + Must have integral dtype. Ignored if ``None``. Defaults to ``None``. + aweights (tensor, optional): A Scalar or 1D array of observation vector weights. + These relative weights are typically large for observations considered "important" and smaller for + observations considered less "important". Its numel must equal the number of columns of :attr:`input`. + Must have floating point dtype. Ignored if ``None``. Defaults to ``None``. + + Returns: + (Tensor) The covariance matrix of the variables. + + .. seealso:: + + :func:`torch.corrcoef` normalized covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 2], [1, 1], [2, 0]]).T + >>> x + tensor([[0, 1, 2], + [2, 1, 0]]) + >>> torch.cov(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> torch.cov(x, correction=0) + tensor([[ 0.6667, -0.6667], + [-0.6667, 0.6667]]) + >>> fw = torch.randint(1, 10, (3,)) + >>> fw + tensor([1, 6, 9]) + >>> aw = torch.rand(3) + >>> aw + tensor([0.4282, 0.0255, 0.4144]) + >>> torch.cov(x, fweights=fw, aweights=aw) + tensor([[ 0.4169, -0.4169], + [-0.4169, 0.4169]]) + """ + +def cross( + input: Tensor, + other: Tensor, + dim: _int | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cross(input, other, dim=None, *, out=None) -> Tensor + + + Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` + and :attr:`other`. + + Supports input of float, double, cfloat and cdouble dtypes. Also supports batches + of vectors, for which it computes the product along the dimension :attr:`dim`. + In this case, the output has the same batch dimensions as the inputs. + + .. warning:: + If :attr:`dim` is not given, it defaults to the first dimension found + with the size 3. Note that this might be unexpected. + + This behavior is deprecated and will be changed to match that of :func:`torch.linalg.cross` + in a future release. + + .. seealso:: + :func:`torch.linalg.cross` which has dim=-1 as default. + + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + dim (int, optional): the dimension to take the cross-product in. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 3) + >>> a + tensor([[-0.3956, 1.1455, 1.6895], + [-0.5849, 1.3672, 0.3599], + [-1.1626, 0.7180, -0.0521], + [-0.1339, 0.9902, -2.0225]]) + >>> b = torch.randn(4, 3) + >>> b + tensor([[-0.0257, -1.4725, -1.2251], + [-1.1479, -0.7005, -1.9757], + [-1.3904, 0.3726, -1.1836], + [-0.9688, -0.7153, 0.2159]]) + >>> torch.cross(a, b, dim=1) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + >>> torch.cross(a, b) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + """ + +def crow_indices_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.crow_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +def cudnn_affine_grid_generator( + theta: Tensor, + N: _int, + C: _int, + H: _int, + W: _int, +) -> Tensor: ... +def cudnn_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + exponential_average_factor: _float, + epsilon: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def cudnn_convolution( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + allow_tf32: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def cudnn_convolution_add_relu( + input: Tensor, + weight: Tensor, + z: Tensor, + alpha: Number | _complex | PySymType | None, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def cudnn_convolution_relu( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def cudnn_convolution_transpose( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + allow_tf32: _bool, +) -> Tensor: ... +def cudnn_grid_sampler(input: Tensor, grid: Tensor) -> Tensor: ... +def cudnn_is_acceptable(input: Tensor) -> _bool: ... +def cummax( + input: Tensor, + dim: _int, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummax: + r""" + cummax(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = max(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284, + 1.9946, -0.8209]) + >>> torch.cummax(a, dim=0) + torch.return_types.cummax( + values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696, + 1.9946, 1.9946]), + indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8])) + """ + +def cummin( + input: Tensor, + dim: _int, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.cummin: + r""" + cummin(input, dim, *, out=None) -> (Tensor, LongTensor) + Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of + elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index + location of each maximum value found in the dimension :attr:`dim`. + + .. math:: + y_i = min(x_1, x_2, x_3, \dots, x_i) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762, + 0.9165, 1.6684]) + >>> torch.cummin(a, dim=0) + torch.return_types.cummin( + values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298, + -1.3298, -1.3298]), + indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4])) + """ + +def cumprod( + input: Tensor, + dim: _int, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumprod(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative product of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 \times x_2\times x_3\times \dots \times x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> a + tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126, + -0.2129, -0.4206, 0.1968]) + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065, + 0.0014, -0.0006, -0.0001]) + + >>> a[5] = 0.0 + >>> torch.cumprod(a, dim=0) + tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000, + 0.0000, -0.0000, -0.0000]) + """ + +def cumsum( + input: Tensor, + dim: _int, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + cumsum(input, dim, *, dtype=None, out=None) -> Tensor + + Returns the cumulative sum of elements of :attr:`input` in the dimension + :attr:`dim`. + + For example, if :attr:`input` is a vector of size N, the result will also be + a vector of size N, with elements. + + .. math:: + y_i = x_1 + x_2 + x_3 + \dots + x_i + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(1, 20, (10,)) + >>> a + tensor([13, 7, 3, 10, 13, 3, 15, 10, 9, 10]) + >>> torch.cumsum(a, dim=0) + tensor([13, 20, 23, 33, 46, 49, 64, 74, 83, 93]) + """ + +@overload +def cumulative_trapezoid(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Cumulatively computes the `trapezoidal rule `_ + along :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. + + For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` + and this function is that, :func:`torch.trapezoid` returns a value for each integration, + where as this function returns a cumulative value for every spacing within the integration. This + is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) + """ + +@overload +def cumulative_trapezoid( + y: Tensor, + *, + dx: Number | _complex | PySymType = 1, + dim: _int = -1, +) -> Tensor: + r""" + cumulative_trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Cumulatively computes the `trapezoidal rule `_ + along :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. + + For more details, please read :func:`torch.trapezoid`. The difference between :func:`torch.trapezoid` + and this function is that, :func:`torch.trapezoid` returns a value for each integration, + where as this function returns a cumulative value for every spacing within the integration. This + is analogous to how `.sum` returns a value and `.cumsum` returns a cumulative sum. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Cumulatively computes the trapezoidal rule in 1D, spacing is implicitly 1. + >>> y = torch.tensor([1, 5, 10]) + >>> torch.cumulative_trapezoid(y) + tensor([3., 10.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> (1 + 5) / 2 + 3.0 + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.cumulative_trapezoid(y, dx=2) + tensor([6., 21.]) + + >>> # Cumulatively computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([6., 28.5]) + + >>> # Computes the same trapezoidal rule directly up to each element to verify + >>> ((3 - 1) * (1 + 5)) / 2 + 6.0 + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.cumulative_trapezoid(y) + tensor([[ 0.5, 2.], + [ 3.5, 8.], + [ 6.5, 14.]]) + + >>> # Cumulatively computes the trapezoidal rule for each column of the matrix + >>> torch.cumulative_trapezoid(y, dim=0) + tensor([[ 1.5, 2.5, 3.5], + [ 6.0, 8.0, 10.0]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[2., 5.], + [2., 5.], + [2., 5.]]) + + >>> # Cumulatively computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.cumulative_trapezoid(y, x) + tensor([[1., 2.], + [2., 4.], + [3., 6.]]) + """ + +def deg2rad(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + deg2rad(input, *, out=None) -> Tensor + + Returns a new tensor with each of the elements of :attr:`input` + converted from angles in degrees to radians. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([[180.0, -180.0], [360.0, -360.0], [90.0, -90.0]]) + >>> torch.deg2rad(a) + tensor([[ 3.1416, -3.1416], + [ 6.2832, -6.2832], + [ 1.5708, -1.5708]]) + """ + +def deg2rad_(input: Tensor) -> Tensor: + r""" + deg2rad_(input) -> Tensor + + In-place version of :func:`torch.deg2rad` + """ + +@overload +def dequantize(input: Tensor) -> Tensor: + r""" + dequantize(tensor) -> Tensor + + Returns an fp32 Tensor by dequantizing a quantized Tensor + + Args: + tensor (Tensor): A quantized Tensor + + .. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + + Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + + Args: + tensors (sequence of Tensors): A list of quantized Tensors + """ + +@overload +def dequantize( + tensors: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: + r""" + dequantize(tensor) -> Tensor + + Returns an fp32 Tensor by dequantizing a quantized Tensor + + Args: + tensor (Tensor): A quantized Tensor + + .. function:: dequantize(tensors) -> sequence of Tensors + :noindex: + + Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors + + Args: + tensors (sequence of Tensors): A list of quantized Tensors + """ + +def det(input: Tensor) -> Tensor: + r""" + det(input) -> Tensor + + Alias for :func:`torch.linalg.det` + """ + +def detach(input: Tensor) -> Tensor: ... +def detach_(input: Tensor) -> Tensor: + r""" + detach_(input) -> Tensor + + In-place version of :func:`torch.detach` + """ + +def detach_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.detach`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def diag( + input: Tensor, + diagonal: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + diag(input, diagonal=0, *, out=None) -> Tensor + + - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. + - If :attr:`input` is a matrix (2-D tensor), then returns a 1-D tensor with + the diagonal elements of :attr:`input`. + + The argument :attr:`diagonal` controls which diagonal to consider: + + - If :attr:`diagonal` = 0, it is the main diagonal. + - If :attr:`diagonal` > 0, it is above the main diagonal. + - If :attr:`diagonal` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.diagonal` always returns the diagonal of its input. + + :func:`torch.diagflat` always constructs a tensor with diagonal elements + specified by the input. + + Examples: + + Get the square matrix where the input vector is the diagonal:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.5950,-0.0872, 2.3298]) + >>> torch.diag(a) + tensor([[ 0.5950, 0.0000, 0.0000], + [ 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 2.3298]]) + >>> torch.diag(a, 1) + tensor([[ 0.0000, 0.5950, 0.0000, 0.0000], + [ 0.0000, 0.0000,-0.0872, 0.0000], + [ 0.0000, 0.0000, 0.0000, 2.3298], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + Get the k-th diagonal of a given matrix:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-0.4264, 0.0255,-0.1064], + [ 0.8795,-0.2429, 0.1374], + [ 0.1029,-0.6482,-1.6300]]) + >>> torch.diag(a, 0) + tensor([-0.4264,-0.2429,-1.6300]) + >>> torch.diag(a, 1) + tensor([ 0.0255, 0.1374]) + """ + +def diag_embed( + input: Tensor, + offset: _int = 0, + dim1: _int = -2, + dim2: _int = -1, +) -> Tensor: + r""" + diag_embed(input, offset=0, dim1=-2, dim2=-1) -> Tensor + + Creates a tensor whose diagonals of certain 2D planes (specified by + :attr:`dim1` and :attr:`dim2`) are filled by :attr:`input`. + To facilitate creating batched diagonal matrices, the 2D planes formed by + the last two dimensions of the returned tensor are chosen by default. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + The size of the new matrix will be calculated to make the specified diagonal + of the size of the last input dimension. + Note that for :attr:`offset` other than :math:`0`, the order of :attr:`dim1` + and :attr:`dim2` matters. Exchanging them is equivalent to changing the + sign of :attr:`offset`. + + Applying :meth:`torch.diagonal` to the output of this function with + the same arguments yields a matrix identical to input. However, + :meth:`torch.diagonal` has different default dimensions, so those + need to be explicitly specified. + + Args: + input (Tensor): the input tensor. Must be at least 1-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: -2. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: -1. + + Example:: + + >>> a = torch.randn(2, 3) + >>> torch.diag_embed(a) + tensor([[[ 1.5410, 0.0000, 0.0000], + [ 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -2.1788]], + + [[ 0.5684, 0.0000, 0.0000], + [ 0.0000, -1.0845, 0.0000], + [ 0.0000, 0.0000, -1.3986]]]) + + >>> torch.diag_embed(a, offset=1, dim1=0, dim2=2) + tensor([[[ 0.0000, 1.5410, 0.0000, 0.0000], + [ 0.0000, 0.5684, 0.0000, 0.0000]], + + [[ 0.0000, 0.0000, -0.2934, 0.0000], + [ 0.0000, 0.0000, -1.0845, 0.0000]], + + [[ 0.0000, 0.0000, 0.0000, -2.1788], + [ 0.0000, 0.0000, 0.0000, -1.3986]], + + [[ 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.0000]]]) + """ + +def diagflat(input: Tensor, offset: _int = 0) -> Tensor: + r""" + diagflat(input, offset=0) -> Tensor + + - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor + with the elements of :attr:`input` as the diagonal. + - If :attr:`input` is a tensor with more than one dimension, then returns a + 2-D tensor with diagonal elements equal to a flattened :attr:`input`. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. + offset (int, optional): the diagonal to consider. Default: 0 (main + diagonal). + + Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([-0.2956, -0.9068, 0.1695]) + >>> torch.diagflat(a) + tensor([[-0.2956, 0.0000, 0.0000], + [ 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.1695]]) + >>> torch.diagflat(a, 1) + tensor([[ 0.0000, -0.2956, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.9068, 0.0000], + [ 0.0000, 0.0000, 0.0000, 0.1695], + [ 0.0000, 0.0000, 0.0000, 0.0000]]) + + >>> a = torch.randn(2, 2) + >>> a + tensor([[ 0.2094, -0.3018], + [-0.1516, 1.9342]]) + >>> torch.diagflat(a) + tensor([[ 0.2094, 0.0000, 0.0000, 0.0000], + [ 0.0000, -0.3018, 0.0000, 0.0000], + [ 0.0000, 0.0000, -0.1516, 0.0000], + [ 0.0000, 0.0000, 0.0000, 1.9342]]) + """ + +def diagonal( + input: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, +) -> Tensor: + r""" + diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor + + Returns a partial view of :attr:`input` with the its diagonal elements + with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension + at the end of the shape. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Applying :meth:`torch.diag_embed` to the output of this function with + the same arguments yields a diagonal matrix with the diagonal entries + of the input. However, :meth:`torch.diag_embed` has different default + dimensions, so those need to be explicitly specified. + + Args: + input (Tensor): the input tensor. Must be at least 2-dimensional. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + + .. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1. + + Examples:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0854, 1.1431, -0.1752], + [ 0.8536, -0.0905, 0.0360], + [ 0.6927, -0.3735, -0.4945]]) + + + >>> torch.diagonal(a) + tensor([-1.0854, -0.0905, -0.4945]) + + + >>> torch.diagonal(a, 1) + tensor([ 1.1431, 0.0360]) + + >>> b = torch.randn(2, 5) + >>> b + tensor([[-1.7948, -1.2731, -0.3181, 2.0200, -1.6745], + [ 1.8262, -1.5049, 0.4114, 1.0704, -1.2607]]) + + >>> torch.diagonal(b, 1, 1, 0) + tensor([1.8262]) + + >>> x = torch.randn(2, 5, 4, 2) + >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2) + tensor([[[-1.2631, 0.3755, -1.5977, -1.8172], + [-1.1065, 1.0401, -0.2235, -0.7938]], + + [[-1.7325, -0.3081, 0.6166, 0.2335], + [ 1.0500, 0.7336, -0.3836, -1.1015]]]) + """ + +def diagonal_copy( + input: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.diagonal`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def diagonal_scatter( + input: Tensor, + src: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, +) -> Tensor: + r""" + diagonal_scatter(input, src, offset=0, dim1=0, dim2=1) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` along + the diagonal elements of :attr:`input`, with respect to :attr:`dim1` + and :attr:`dim2`. + + This function returns a tensor with fresh storage; it does not + return a view. + + The argument :attr:`offset` controls which diagonal to consider: + + - If :attr:`offset` = 0, it is the main diagonal. + - If :attr:`offset` > 0, it is above the main diagonal. + - If :attr:`offset` < 0, it is below the main diagonal. + + Args: + input (Tensor): the input tensor. Must be at least 2-dimensional. + src (Tensor): the tensor to embed into :attr:`input`. + offset (int, optional): which diagonal to consider. Default: 0 + (main diagonal). + dim1 (int, optional): first dimension with respect to which to + take diagonal. Default: 0. + dim2 (int, optional): second dimension with respect to which to + take diagonal. Default: 1. + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.diagonal(input, offset, dim1, dim2)`` + + Examples:: + + >>> a = torch.zeros(3, 3) + >>> a + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + + >>> torch.diagonal_scatter(a, torch.ones(3), 0) + tensor([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]]) + + >>> torch.diagonal_scatter(a, torch.ones(2), 1) + tensor([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) + """ + +def diff( + input: Tensor, + n: _int = 1, + dim: _int = -1, + prepend: Tensor | None = None, + append: Tensor | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + diff(input, n=1, dim=-1, prepend=None, append=None) -> Tensor + + Computes the n-th forward difference along the given dimension. + + The first-order differences are given by `out[i] = input[i + 1] - input[i]`. Higher-order + differences are calculated by using :func:`torch.diff` recursively. + + Args: + input (Tensor): the tensor to compute the differences on + n (int, optional): the number of times to recursively compute the difference + dim (int, optional): the dimension to compute the difference along. + Default is the last dimension. + prepend, append (Tensor, optional): values to prepend or append to + :attr:`input` along :attr:`dim` before computing the difference. + Their dimensions must be equivalent to that of input, and their shapes + must match input's shape except on :attr:`dim`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 3, 2]) + >>> torch.diff(a) + tensor([ 2, -1]) + >>> b = torch.tensor([4, 5]) + >>> torch.diff(a, append=b) + tensor([ 2, -1, 2, 1]) + >>> c = torch.tensor([[1, 2, 3], [3, 4, 5]]) + >>> torch.diff(c, dim=0) + tensor([[2, 2, 2]]) + >>> torch.diff(c, dim=1) + tensor([[1, 1], + [1, 1]]) + """ + +def digamma(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + digamma(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.digamma`. + """ + +def dist( + input: Tensor, + other: Tensor, + p: Number | _complex | PySymType = 2, +) -> Tensor: + r""" + dist(input, other, p=2) -> Tensor + + Returns the p-norm of (:attr:`input` - :attr:`other`) + + The shapes of :attr:`input` and :attr:`other` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + other (Tensor): the Right-hand-side input tensor + p (float, optional): the norm to be computed + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([-1.5393, -0.8675, 0.5916, 1.6321]) + >>> y = torch.randn(4) + >>> y + tensor([ 0.0967, -1.0511, 0.6295, 0.8360]) + >>> torch.dist(x, y, 3.5) + tensor(1.6727) + >>> torch.dist(x, y, 3) + tensor(1.6973) + >>> torch.dist(x, y, 0) + tensor(4.) + >>> torch.dist(x, y, 1) + tensor(2.6537) + """ + +def div( + input: Tensor | Number, + other: Tensor | Number, + *, + rounding_mode: str | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + div(input, other, *, rounding_mode=None, out=None) -> Tensor + + Divides each element of the input ``input`` by the corresponding element of + :attr:`other`. + + .. math:: + \text{out}_i = \frac{\text{input}_i}{\text{other}_i} + + .. note:: + By default, this performs a "true" division like Python 3. + See the :attr:`rounding_mode` argument for floor division. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + Always promotes integer types to the default scalar type. + + Args: + input (Tensor): the dividend + other (Tensor or Number): the divisor + + Keyword args: + rounding_mode (str, optional): Type of rounding applied to the result: + + * None - default behavior. Performs no rounding and, if both :attr:`input` and + :attr:`other` are integer types, promotes the inputs to the default scalar type. + Equivalent to true division in Python (the ``/`` operator) and NumPy's ``np.true_divide``. + * ``"trunc"`` - rounds the results of the division towards zero. + Equivalent to C-style integer division. + * ``"floor"`` - rounds the results of the division down. + Equivalent to floor division in Python (the ``//`` operator) and NumPy's ``np.floor_divide``. + + out (Tensor, optional): the output tensor. + + Examples:: + + >>> x = torch.tensor([ 0.3810, 1.2774, -0.2972, -0.3719, 0.4637]) + >>> torch.div(x, 0.5) + tensor([ 0.7620, 2.5548, -0.5944, -0.7438, 0.9274]) + + >>> a = torch.tensor([[-0.3711, -1.9353, -0.4605, -0.2917], + ... [ 0.1815, -1.0111, 0.9805, -1.5923], + ... [ 0.1062, 1.4581, 0.7759, -1.2344], + ... [-0.1830, -0.0313, 1.1908, -1.4757]]) + >>> b = torch.tensor([ 0.8032, 0.2930, -0.8113, -0.2308]) + >>> torch.div(a, b) + tensor([[-0.4620, -6.6051, 0.5676, 1.2639], + [ 0.2260, -3.4509, -1.2086, 6.8990], + [ 0.1322, 4.9764, -0.9564, 5.3484], + [-0.2278, -0.1068, -1.4678, 6.3938]]) + + >>> torch.div(a, b, rounding_mode='trunc') + tensor([[-0., -6., 0., 1.], + [ 0., -3., -1., 6.], + [ 0., 4., -0., 5.], + [-0., -0., -1., 6.]]) + + >>> torch.div(a, b, rounding_mode='floor') + tensor([[-1., -7., 0., 1.], + [ 0., -4., -2., 6.], + [ 0., 4., -1., 5.], + [-1., -1., -2., 6.]]) + """ + +@overload +def divide( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide( + input: Tensor, + other: Tensor, + *, + rounding_mode: str | None, + out: Tensor | None = None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide( + input: Tensor, + other: Number | _complex | PySymType, + *, + rounding_mode: str | None, +) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +@overload +def divide(input: Tensor, other: Number | _complex | PySymType) -> Tensor: + r""" + divide(input, other, *, rounding_mode=None, out=None) -> Tensor + + Alias for :func:`torch.div`. + """ + +def dot( + input: Tensor, + tensor: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + dot(input, tensor, *, out=None) -> Tensor + + Computes the dot product of two 1D tensors. + + .. note:: + + Unlike NumPy's dot, torch.dot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + + Args: + input (Tensor): first tensor in the dot product, must be 1D. + tensor (Tensor): second tensor in the dot product, must be 1D. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + + >>> t1, t2 = torch.tensor([0, 1]), torch.tensor([2, 3]) + >>> torch.dot(t1, t2) + tensor(3) + """ + +def dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def dsmm(input: Tensor, mat2: Tensor) -> Tensor: ... +@overload +def dsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + dsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors + depthwise according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) + (the split dimension is 2), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.dsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + """ + +@overload +def dsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + dsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with three or more dimensions, into multiple tensors + depthwise according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=2) + (the split dimension is 2), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.dsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(2, 2, 4) + >>> t + tensor([[[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.]], + [[ 8., 9., 10., 11.], + [12., 13., 14., 15.]]]) + >>> torch.dsplit(t, 2) + (tensor([[[ 0., 1.], + [ 4., 5.]], + [[ 8., 9.], + [12., 13.]]]), + tensor([[[ 2., 3.], + [ 6., 7.]], + [[10., 11.], + [14., 15.]]])) + + >>> torch.dsplit(t, [3, 6]) + (tensor([[[ 0., 1., 2.], + [ 4., 5., 6.]], + [[ 8., 9., 10.], + [12., 13., 14.]]]), + tensor([[[ 3.], + [ 7.]], + [[11.], + [15.]]]), + tensor([], size=(2, 2, 0))) + """ + +def dstack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + dstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence depthwise (along third axis). + + This is equivalent to concatenation along the third axis after 1-D and 2-D tensors have been reshaped by :func:`torch.atleast_3d`. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.dstack((a,b)) + tensor([[[1, 4], + [2, 5], + [3, 6]]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.dstack((a,b)) + tensor([[[1, 4]], + [[2, 5]], + [[3, 6]]]) + """ + +def embedding( + weight: Tensor, + indices: Tensor, + padding_idx: _int | SymInt = -1, + scale_grad_by_freq: _bool = False, + sparse: _bool = False, +) -> Tensor: ... +@overload +def embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool, + mode: _int, + sparse: _bool, + per_sample_weights: Tensor | None, + include_last_offset: _bool, + padding_idx: _int | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def embedding_bag( + weight: Tensor, + indices: Tensor, + offsets: Tensor, + scale_grad_by_freq: _bool = False, + mode: _int = 0, + sparse: _bool = False, + per_sample_weights: Tensor | None = None, + include_last_offset: _bool = False, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def embedding_renorm_( + input: Tensor, + indices: Tensor, + max_norm: _float, + norm_type: _float, +) -> Tensor: ... +@overload +def empty( + size: Sequence[_int | SymInt], + *, + memory_format: memory_format | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +@overload +def empty( + *size: _int | SymInt, + memory_format: memory_format | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor + + Returns a tensor filled with uninitialized data. The shape of the tensor is + defined by the variable argument :attr:`size`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + + Example:: + + >>> torch.empty((2,3), dtype=torch.int64) + tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], + [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) + """ + +def empty_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns an uninitialized tensor with the same size as :attr:`input`. + ``torch.empty_like(input)`` is equivalent to + ``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + When ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense format. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> a=torch.empty((2,3), dtype=torch.int32, device = 'cuda') + >>> torch.empty_like(a) + tensor([[0, 0, 0], + [0, 0, 0]], device='cuda:0', dtype=torch.int32) + """ + +def empty_permuted( + size: Sequence[_int | SymInt], + physical_layout: _size, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_permuted(size, physical_layout, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates an uninitialized, non-overlapping and dense tensor with the + specified :attr:`size`, with :attr:`physical_layout` specifying how the + dimensions are physically laid out in memory (each logical dimension is listed + from outermost to innermost). :attr:`physical_layout` is a generalization + of NCHW/NHWC notation: if each dimension is assigned a number according to + what order they occur in size (N=0, C=1, H=2, W=3), then NCHW is ``(0, 1, 2, 3)`` + while NHWC is ``(0, 2, 3, 1)``. Equivalently, the strides of the output + tensor ``t`` are such that ``t.stride(physical_layout[i]) == contiguous_strides[i]`` + (notably, this function is *not* equivalent to ``torch.empty(size).permute(physical_layout)``). + + Unlike :func:`torch.empty_strided`, this is guaranteed to produce a dense + tensor with no overlaps. If possible, prefer using this function over + :func:`torch.empty_strided` or manual use of :func:`torch.as_strided`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + physical_layout (tuple of int): the ordering of dimensions physically in memory + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Examples: + + >>> torch.empty((2, 3, 5, 7)).stride() + (105, 35, 7, 1) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 1, 2, 3)).stride() + (105, 35, 7, 1) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).dim_order() + (0, 2, 3, 1) + """ + +def empty_quantized( + size: _size, + qtensor: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def empty_strided( + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates a tensor with the specified :attr:`size` and :attr:`stride` and filled with undefined data. + + .. warning:: + If the constructed tensor is "overlapped" (with multiple indices referring to the same element + in memory) its behavior is undefined. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + stride (tuple of int): the strides of the output tensor + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> a = torch.empty_strided((2, 3), (1, 2)) + >>> a + tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07], + [0.0000e+00, 0.0000e+00, 3.0705e-41]]) + >>> a.stride() + (1, 2) + >>> a.size() + torch.Size([2, 3]) + """ + +@overload +def eq( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + eq(input, other, *, out=None) -> Tensor + + Computes element-wise equality + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) + """ + +@overload +def eq( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + eq(input, other, *, out=None) -> Tensor + + Computes element-wise equality + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) + """ + +def equal(input: Tensor, other: Tensor) -> _bool: + r""" + equal(input, other) -> bool + + ``True`` if two tensors have the same size and elements, ``False`` otherwise. + + .. note:: + + Tensors containing NaNs are never equal to each other. Additionally, this function does not + differentiate between the data types of the tensors during comparison. For more thorough tensor checks, + use :meth:`torch.testing.assert_close`. + + Example:: + + >>> torch.equal(torch.tensor([1, 2]), torch.tensor([1, 2])) + True + >>> torch.equal(torch.tensor([3, torch.nan]), torch.tensor([3, torch.nan])) + False + >>> torch.equal(torch.tensor([1, 2, 3], dtype=torch.int32), torch.tensor([1, 2, 3], dtype=torch.float32)) + True + """ + +def erf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erf(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erf`. + """ + +def erf_(input: Tensor) -> Tensor: + r""" + erf_(input) -> Tensor + + In-place version of :func:`torch.erf` + """ + +def erfc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erfc(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erfc`. + """ + +def erfc_(input: Tensor) -> Tensor: + r""" + erfc_(input) -> Tensor + + In-place version of :func:`torch.erfc` + """ + +def erfinv(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + erfinv(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.erfinv`. + """ + +def exp(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + exp(input, *, out=None) -> Tensor + + Returns a new tensor with the exponential of the elements + of the input tensor :attr:`input`. + + .. math:: + y_{i} = e^{x_{i}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.exp(torch.tensor([0, math.log(2.)])) + tensor([ 1., 2.]) + """ + +def exp2(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + exp2(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.exp2`. + """ + +def exp2_(input: Tensor) -> Tensor: + r""" + exp2_(input) -> Tensor + + In-place version of :func:`torch.exp2` + """ + +def exp_(input: Tensor) -> Tensor: + r""" + exp_(input) -> Tensor + + In-place version of :func:`torch.exp` + """ + +def expand_copy( + input: Tensor, + size: Sequence[_int | SymInt], + *, + implicit: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.Tensor.expand`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def expm1(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + expm1(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.expm1`. + """ + +def expm1_(input: Tensor) -> Tensor: + r""" + expm1_(input) -> Tensor + + In-place version of :func:`torch.expm1` + """ + +@overload +def eye( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +@overload +def eye( + n: _int | SymInt, + m: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +def fake_quantize_per_channel_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized per channel using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`, across the channel specified by :attr:`axis`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), in ``torch.float32`` + scale (Tensor): quantization scale, per channel in ``torch.float32`` + zero_point (Tensor): quantization zero_point, per channel in ``torch.int32`` or ``torch.half`` or ``torch.float32`` + axis (int32): channel axis + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized per channel ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(2, 2, 2) + >>> x + tensor([[[-0.2525, -0.0466], + [ 0.3491, -0.2168]], + + [[-0.5906, 1.6258], + [ 0.6444, -0.0542]]]) + >>> scales = (torch.randn(2) + 1) * 0.05 + >>> scales + tensor([0.0475, 0.0486]) + >>> zero_points = torch.zeros(2).to(torch.int32) + >>> zero_points + tensor([0, 0]) + >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255) + tensor([[[0.0000, 0.0000], + [0.3405, 0.0000]], + + [[0.0000, 1.6134], + [0.6323, 0.0000]]]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: _float, + zero_point: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, + output: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, + output: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex | PySymType, + weight_zero_point: Number | _complex | PySymType, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight_fp32_activation( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex | PySymType, + weight_zero_point: Number | _complex | PySymType, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_quantize_weight( + input: Tensor, +) -> tuple[Tensor, Tensor, _float, _int]: ... +def fbgemm_pack_gemm_matrix_fp16(input: Tensor) -> Tensor: ... +@overload +def fbgemm_pack_quantized_matrix(input: Tensor) -> Tensor: ... +@overload +def fbgemm_pack_quantized_matrix(input: Tensor, K: _int, N: _int) -> Tensor: ... +def feature_alpha_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def feature_alpha_dropout_( + input: Tensor, + p: _float, + train: _bool, +) -> Tensor: + r""" + feature_alpha_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.feature_alpha_dropout` + """ + +def feature_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def feature_dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: + r""" + feature_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.feature_dropout` + """ + +@overload +def fill(input: Tensor, value: Tensor) -> Tensor: ... +@overload +def fill(input: Tensor, value: Number | _complex | PySymType) -> Tensor: ... +@overload +def fill_(input: Tensor, value: Tensor) -> Tensor: + r""" + fill_(input, value) -> Tensor + + In-place version of :func:`torch.fill` + """ + +@overload +def fill_(input: Tensor, value: Number | _complex | PySymType) -> Tensor: + r""" + fill_(input, value) -> Tensor + + In-place version of :func:`torch.fill` + """ + +def fix(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + fix(input, *, out=None) -> Tensor + + Alias for :func:`torch.trunc` + """ + +def fix_(input: Tensor) -> Tensor: + r""" + fix_(input) -> Tensor + + In-place version of :func:`torch.fix` + """ + +def flatten( + input: Tensor, + start_dim: _int = 0, + end_dim: _int = -1, +) -> Tensor: + r""" + flatten(input, start_dim=0, end_dim=-1) -> Tensor + + Flattens :attr:`input` by reshaping it into a one-dimensional tensor. If :attr:`start_dim` or :attr:`end_dim` + are passed, only dimensions starting with :attr:`start_dim` and ending with :attr:`end_dim` are flattened. + The order of elements in :attr:`input` is unchanged. + + Unlike NumPy's flatten, which always copies input's data, this function may return the original object, a view, + or copy. If no dimensions are flattened, then the original object :attr:`input` is returned. Otherwise, if input can + be viewed as the flattened shape, then that view is returned. Finally, only if the input cannot be viewed as the + flattened shape is input's data copied. See :meth:`torch.Tensor.view` for details on when a view will be returned. + + .. note:: + Flattening a zero-dimensional tensor will return a one-dimensional view. + + Args: + input (Tensor): the input tensor. + start_dim (int): the first dim to flatten + end_dim (int): the last dim to flatten + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.flatten(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + >>> torch.flatten(t, start_dim=1) + tensor([[1, 2, 3, 4], + [5, 6, 7, 8]]) + """ + +def flip(input: Tensor, dims: _size) -> Tensor: + r""" + flip(input, dims) -> Tensor + + Reverse the order of an n-D tensor along given axis in dims. + + .. note:: + `torch.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flip` is expected to be slower than `np.flip`. + + Args: + input (Tensor): the input tensor. + dims (a list or tuple): axis to flip on + + Example:: + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[ 0, 1], + [ 2, 3]], + + [[ 4, 5], + [ 6, 7]]]) + >>> torch.flip(x, [0, 1]) + tensor([[[ 6, 7], + [ 4, 5]], + + [[ 2, 3], + [ 0, 1]]]) + """ + +def fliplr(input: Tensor) -> Tensor: + r""" + fliplr(input) -> Tensor + + Flip tensor in the left/right direction, returning a new tensor. + + Flip the entries in each row in the left/right direction. + Columns are preserved, but appear in a different order than before. + + Note: + Requires the tensor to be at least 2-D. + + .. note:: + `torch.fliplr` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.fliplr`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.fliplr` is expected to be slower than `np.fliplr`. + + Args: + input (Tensor): Must be at least 2-dimensional. + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.fliplr(x) + tensor([[1, 0], + [3, 2]]) + """ + +def flipud(input: Tensor) -> Tensor: + r""" + flipud(input) -> Tensor + + Flip tensor in the up/down direction, returning a new tensor. + + Flip the entries in each column in the up/down direction. + Rows are preserved, but appear in a different order than before. + + Note: + Requires the tensor to be at least 1-D. + + .. note:: + `torch.flipud` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flipud`, + which returns a view in constant time. Since copying a tensor's data is more work than viewing that data, + `torch.flipud` is expected to be slower than `np.flipud`. + + Args: + input (Tensor): Must be at least 1-dimensional. + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.flipud(x) + tensor([[2, 3], + [0, 1]]) + """ + +@overload +def float_power( + input: Tensor, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +@overload +def float_power( + self: Number | _complex | PySymType, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +@overload +def float_power( + input: Tensor, + exponent: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + float_power(input, exponent, *, out=None) -> Tensor + + Raises :attr:`input` to the power of :attr:`exponent`, elementwise, in double precision. + If neither input is complex returns a ``torch.float64`` tensor, + and if one or more inputs is complex returns a ``torch.complex128`` tensor. + + .. note:: + This function always computes in double precision, unlike :func:`torch.pow`, + which implements more typical :ref:`type promotion `. + This is useful when the computation needs to be performed in a wider or more precise dtype, + or the results of the computation may contain fractional values not representable in the input dtypes, + like when an integer base is raised to a negative integer exponent. + + Args: + input (Tensor or Number): the base value(s) + exponent (Tensor or Number): the exponent value(s) + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randint(10, (4,)) + >>> a + tensor([6, 4, 7, 1]) + >>> torch.float_power(a, 2) + tensor([36., 16., 49., 1.], dtype=torch.float64) + + >>> a = torch.arange(1, 5) + >>> a + tensor([ 1, 2, 3, 4]) + >>> exp = torch.tensor([2, -3, 4, -5]) + >>> exp + tensor([ 2, -3, 4, -5]) + >>> torch.float_power(a, exp) + tensor([1.0000e+00, 1.2500e-01, 8.1000e+01, 9.7656e-04], dtype=torch.float64) + """ + +def floor(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + floor(input, *, out=None) -> Tensor + + Returns a new tensor with the floor of the elements of :attr:`input`, + the largest integer less than or equal to each element. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + .. math:: + \text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.8166, 1.5308, -0.2530, -0.2091]) + >>> torch.floor(a) + tensor([-1., 1., -1., -1.]) + """ + +def floor_(input: Tensor) -> Tensor: + r""" + floor_(input) -> Tensor + + In-place version of :func:`torch.floor` + """ + +def floor_divide( + input: Tensor | Number, + other: Tensor | Number, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + floor_divide(input, other, *, out=None) -> Tensor + + .. note:: + + Before PyTorch 1.13 :func:`torch.floor_divide` incorrectly performed + truncation division. To restore the previous behavior use + :func:`torch.div` with ``rounding_mode='trunc'``. + + Computes :attr:`input` divided by :attr:`other`, elementwise, and floors + the result. + + .. math:: + \text{{out}}_i = \text{floor} \left( \frac{{\text{{input}}_i}}{{\text{{other}}_i}} \right) + + + + Supports broadcasting to a common shape, type promotion, and integer and float inputs. + + Args: + input (Tensor or Number): the dividend + other (Tensor or Number): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([4.0, 3.0]) + >>> b = torch.tensor([2.0, 2.0]) + >>> torch.floor_divide(a, b) + tensor([2.0, 1.0]) + >>> torch.floor_divide(a, 1.4) + tensor([2.0, 2.0]) + """ + +def fmax( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmax(input, other, *, out=None) -> Tensor + + Computes the element-wise maximum of :attr:`input` and :attr:`other`. + + This is like :func:`torch.maximum` except it handles NaNs differently: + if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the maximum. + Only if both elements are NaN is NaN propagated. + + This function is a wrapper around C++'s ``std::fmax`` and is similar to NumPy's ``fmax`` function. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and floating-point inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([9.7, float('nan'), 3.1, float('nan')]) + >>> b = torch.tensor([-2.2, 0.5, float('nan'), float('nan')]) + >>> torch.fmax(a, b) + tensor([9.7000, 0.5000, 3.1000, nan]) + """ + +def fmin( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmin(input, other, *, out=None) -> Tensor + + Computes the element-wise minimum of :attr:`input` and :attr:`other`. + + This is like :func:`torch.minimum` except it handles NaNs differently: + if exactly one of the two elements being compared is a NaN then the non-NaN element is taken as the minimum. + Only if both elements are NaN is NaN propagated. + + This function is a wrapper around C++'s ``std::fmin`` and is similar to NumPy's ``fmin`` function. + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and floating-point inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([2.2, float('nan'), 2.1, float('nan')]) + >>> b = torch.tensor([-9.3, 0.1, float('nan'), float('nan')]) + >>> torch.fmin(a, b) + tensor([-9.3000, 0.1000, 2.1000, nan]) + """ + +@overload +def fmod( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmod(input, other, *, out=None) -> Tensor + + Applies C++'s `std::fmod `_ entrywise. + The result has the same sign as the dividend :attr:`input` and its absolute value + is less than that of :attr:`other`. + + This function may be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + + .. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + + .. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + + Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + """ + +@overload +def fmod( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + fmod(input, other, *, out=None) -> Tensor + + Applies C++'s `std::fmod `_ entrywise. + The result has the same sign as the dividend :attr:`input` and its absolute value + is less than that of :attr:`other`. + + This function may be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + + When the divisor is zero, returns ``NaN`` for floating point dtypes + on both CPU and GPU; raises ``RuntimeError`` for integer division by + zero on CPU; Integer division by zero on GPU may return any value. + + .. note:: + + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + + .. seealso:: + + :func:`torch.remainder` which implements Python's modulus operator. + This one is defined using division rounding down the result. + + Args: + input (Tensor): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([-1., -0., -1., 1., 0., 1.]) + >>> torch.fmod(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) + """ + +def frac(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + frac(input, *, out=None) -> Tensor + + Computes the fractional portion of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = \text{input}_{i} - \left\lfloor |\text{input}_{i}| \right\rfloor * \operatorname{sgn}(\text{input}_{i}) + + Example:: + + >>> torch.frac(torch.tensor([1, 2.5, -3.2])) + tensor([ 0.0000, 0.5000, -0.2000]) + """ + +def frac_(input: Tensor) -> Tensor: + r""" + frac_(input) -> Tensor + + In-place version of :func:`torch.frac` + """ + +def frexp( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.frexp: + r""" + frexp(input, *, out=None) -> (Tensor mantissa, Tensor exponent) + + Decomposes :attr:`input` into mantissa and exponent tensors + such that :math:`\text{input} = \text{mantissa} \times 2^{\text{exponent}}`. + + The range of mantissa is the open interval (-1, 1). + + Supports float inputs. + + Args: + input (Tensor): the input tensor + + + Keyword args: + out (tuple, optional): the output tensors + + Example:: + + >>> x = torch.arange(9.) + >>> mantissa, exponent = torch.frexp(x) + >>> mantissa + tensor([0.0000, 0.5000, 0.5000, 0.7500, 0.5000, 0.6250, 0.7500, 0.8750, 0.5000]) + >>> exponent + tensor([0, 1, 2, 2, 3, 3, 3, 3, 4], dtype=torch.int32) + >>> torch.ldexp(mantissa, exponent) + tensor([0., 1., 2., 3., 4., 5., 6., 7., 8.]) + """ + +def frobenius_norm( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def from_file( + filename: str, + shared: _bool | None = None, + size: _int | None = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + from_file(filename, shared=None, size=0, *, dtype=None, layout=None, device=None, pin_memory=False) + + Creates a CPU tensor with a storage backed by a memory-mapped file. + + If ``shared`` is True, then memory is shared between processes. All changes are written to the file. + If ``shared`` is False, then changes to the tensor do not affect the file. + + ``size`` is the number of elements in the Tensor. If ``shared`` is ``False``, then the file must contain + at least ``size * sizeof(dtype)`` bytes. If ``shared`` is ``True`` the file will be created if needed. + + .. note:: + Only CPU tensors can be mapped to files. + + .. note:: + For now, tensors with storages backed by a memory-mapped file cannot be created in pinned memory. + + + Args: + filename (str): file name to map + shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the + underlying `mmap(2) call `_) + size (int): number of elements in the tensor + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> t = torch.randn(2, 5, dtype=torch.float64) + >>> t.numpy().tofile('storage.pt') + >>> t_mapped = torch.from_file('storage.pt', shared=False, size=10, dtype=torch.float64) + """ + +def from_numpy(ndarray) -> Tensor: + r""" + from_numpy(ndarray) -> Tensor + + Creates a :class:`Tensor` from a :class:`numpy.ndarray`. + + The returned tensor and :attr:`ndarray` share the same memory. Modifications to + the tensor will be reflected in the :attr:`ndarray` and vice versa. The returned + tensor is not resizable. + + It currently accepts :attr:`ndarray` with dtypes of ``numpy.float64``, + ``numpy.float32``, ``numpy.float16``, ``numpy.complex64``, ``numpy.complex128``, + ``numpy.int64``, ``numpy.int32``, ``numpy.int16``, ``numpy.int8``, ``numpy.uint8``, + and ``bool``. + + .. warning:: + Writing to a tensor created from a read-only NumPy array is not supported and will result in undefined behavior. + + Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.from_numpy(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + """ + +def frombuffer( + buffer: Any, + *, + dtype: _dtype, + count: int = -1, + offset: int = 0, + requires_grad: _bool = False, +) -> Tensor: + r""" + frombuffer(buffer, *, dtype, count=-1, offset=0, requires_grad=False) -> Tensor + + Creates a 1-dimensional :class:`Tensor` from an object that implements + the Python buffer protocol. + + Skips the first :attr:`offset` bytes in the buffer, and interprets the rest of + the raw bytes as a 1-dimensional tensor of type :attr:`dtype` with :attr:`count` + elements. + + Note that either of the following must be true: + + 1. :attr:`count` is a positive non-zero number, and the total number of bytes + in the buffer is more than :attr:`offset` plus :attr:`count` times the size + (in bytes) of :attr:`dtype`. + + 2. :attr:`count` is negative, and the length (number of bytes) of the buffer + subtracted by the :attr:`offset` is a multiple of the size (in bytes) of + :attr:`dtype`. + + The returned tensor and buffer share the same memory. Modifications to + the tensor will be reflected in the buffer and vice versa. The returned + tensor is not resizable. + + .. note:: + This function increments the reference count for the object that + owns the shared memory. Therefore, such memory will not be deallocated + before the returned tensor goes out of scope. + + .. warning:: + This function's behavior is undefined when passed an object implementing + the buffer protocol whose data is not on the CPU. Doing so is likely to + cause a segmentation fault. + + .. warning:: + This function does not try to infer the :attr:`dtype` (hence, it is not + optional). Passing a different :attr:`dtype` than its source may result + in unexpected behavior. + + Args: + buffer (object): a Python object that exposes the buffer interface. + + Keyword args: + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + count (int, optional): the number of desired elements to be read. + If negative, all the elements (until the end of the buffer) will be + read. Default: -1. + offset (int, optional): the number of bytes to skip at the start of + the buffer. Default: 0. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> import array + >>> a = array.array('i', [1, 2, 3]) + >>> t = torch.frombuffer(a, dtype=torch.int32) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> # Interprets the signed char bytes as 32-bit integers. + >>> # Each 4 signed char elements will be interpreted as + >>> # 1 signed 32-bit integer. + >>> import array + >>> a = array.array('b', [-1, 0, 0, 0]) + >>> torch.frombuffer(a, dtype=torch.int32) + tensor([255], dtype=torch.int32) + """ + +@overload +def full( + size: _size, + fill_value: Number | _complex, + *, + out: Tensor | None = None, + layout: _layout = strided, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +@overload +def full( + size: _size, + fill_value: Number | _complex, + *, + names: list[str | None], + layout: _layout = strided, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +@overload +def full( + size: Sequence[_int | SymInt], + fill_value: Number | _complex | PySymType, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a tensor of size :attr:`size` filled with :attr:`fill_value`. The + tensor's dtype is inferred from :attr:`fill_value`. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + fill_value (Scalar): the value to fill the output tensor with. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.full((2, 3), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + """ + +def full_like( + input: Tensor, + fill_value: Number | _complex | PySymType, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full_like(input, fill_value, \*, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`. + ``torch.full_like(input, fill_value)`` is equivalent to + ``torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + fill_value: the number to fill the output tensor with. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> x = torch.ones(2, 3) + >>> torch.full_like(x, 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + >>> torch.full_like(x, 7) + tensor([[7., 7., 7.], + [7., 7., 7.]]) + >>> torch.full_like(x, 0.5, dtype=torch.int32) + tensor([[0, 0, 0], + [0, 0, 0]], dtype=torch.int32) + >>> y = torch.randn(3, 4, dtype=torch.float64) + >>> torch.full_like(y, -1.0) + tensor([[-1., -1., -1., -1.], + [-1., -1., -1., -1.], + [-1., -1., -1., -1.]], dtype=torch.float64) + """ + +def fused_moving_avg_obs_fake_quant( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> Tensor: ... +def gather( + input: Tensor, + dim: _int, + index: Tensor, + *, + sparse_grad: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + + Gathers values along an axis specified by `dim`. + + For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + + :attr:`input` and :attr:`index` must have the same number of dimensions. + It is also required that ``index.size(d) <= input.size(d)`` for all + dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. + Note that ``input`` and ``index`` do not broadcast against each other. + When :attr:`index` is empty, we always return an empty output with the same shape + without further error checking. + + Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + + Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + + Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) + """ + +def gcd( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gcd(input, other, *, out=None) -> Tensor + + Computes the element-wise greatest common divisor (GCD) of :attr:`input` and :attr:`other`. + + Both :attr:`input` and :attr:`other` must have integer types. + + .. note:: + This defines :math:`gcd(0, 0) = 0`. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.gcd(a, b) + tensor([1, 2, 5]) + >>> c = torch.tensor([3]) + >>> torch.gcd(a, c) + tensor([1, 1, 3]) + """ + +def gcd_(input: Tensor, other: Tensor) -> Tensor: + r""" + gcd_(input, other) -> Tensor + + In-place version of :func:`torch.gcd` + """ + +@overload +def ge( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ge(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \geq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) + """ + +@overload +def ge( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ge(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \geq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than or equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, True], [False, True]]) + """ + +def geqrf( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.geqrf: + r""" + geqrf(input, *, out=None) -> (Tensor, Tensor) + + This is a low-level function for calling LAPACK's geqrf directly. This function + returns a namedtuple (a, tau) as defined in `LAPACK documentation for geqrf`_ . + + Computes a QR decomposition of :attr:`input`. + Both `Q` and `R` matrices are stored in the same output tensor `a`. + The elements of `R` are stored on and above the diagonal. + Elementary reflectors (or Householder vectors) implicitly defining matrix `Q` + are stored below the diagonal. + The results of this function can be used together with :func:`torch.linalg.householder_product` + to obtain the `Q` matrix or + with :func:`torch.ormqr`, which uses an implicit representation of the `Q` matrix, + for an efficient matrix-matrix multiplication. + + See `LAPACK documentation for geqrf`_ for further details. + + .. note:: + See also :func:`torch.linalg.qr`, which computes Q and R matrices, and :func:`torch.linalg.lstsq` + with the ``driver="gels"`` option for a function that can solve matrix equations using a QR decomposition. + + Args: + input (Tensor): the input matrix + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, Tensor). Ignored if `None`. Default: `None`. + + .. _LAPACK documentation for geqrf: + http://www.netlib.org/lapack/explore-html/df/dc5/group__variants_g_ecomputational_ga3766ea903391b5cf9008132f7440ec7b.html + """ + +def ger( + input: Tensor, + vec2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ger(input, vec2, *, out=None) -> Tensor + + Alias of :func:`torch.outer`. + + .. warning:: + This function is deprecated and will be removed in a future PyTorch release. + Use :func:`torch.outer` instead. + """ + +def get_default_dtype() -> _dtype: + r""" + get_default_dtype() -> torch.dtype + + Get the current default floating point :class:`torch.dtype`. + + Example:: + + >>> torch.get_default_dtype() # initial default for floating point is torch.float32 + torch.float32 + >>> torch.set_default_dtype(torch.float64) + >>> torch.get_default_dtype() # default is now changed to torch.float64 + torch.float64 + """ + +def get_num_interop_threads() -> _int: + r""" + get_num_interop_threads() -> int + + Returns the number of threads used for inter-op parallelism on CPU + (e.g. in JIT interpreter) + """ + +def get_num_threads() -> _int: + r""" + get_num_threads() -> int + + Returns the number of threads used for parallelizing CPU operations + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Number | _complex | PySymType | None = None, + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex | PySymType], + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex | PySymType], + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor], + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Number | _complex | PySymType, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor], + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def greater( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.gt`. + """ + +@overload +def greater( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.gt`. + """ + +@overload +def greater_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ge`. + """ + +@overload +def greater_equal( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ge`. + """ + +def grid_sampler( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def grid_sampler_2d( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def grid_sampler_3d( + input: Tensor, + grid: Tensor, + interpolation_mode: _int, + padding_mode: _int, + align_corners: _bool, +) -> Tensor: ... +def group_norm( + input: Tensor, + num_groups: _int, + weight: Tensor | None = None, + bias: Tensor | None = None, + eps: _float = 1e-05, + cudnn_enabled: _bool = True, +) -> Tensor: ... +@overload +def gru( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def gru( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def gru_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +@overload +def gt( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} > \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + + Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) + """ + +@overload +def gt( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} > \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + + Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) + """ + +@overload +def hamming_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + beta: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hann_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def hann_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +def hardshrink( + input: Tensor, + lambd: Number | _complex | PySymType = 0.5, + *, + out: Tensor | None = None, +) -> Tensor: ... +def hash_tensor( + input: Tensor, + dim: _int | _size = (), + *, + keepdim: _bool = False, + mode: _int = 0, + out: Tensor | None = None, +) -> Tensor: + r""" + hash_tensor(input, *, mode=0) -> Tensor + + Returns a hash of all elements in the :attr:`input` tensor. + + Currently only mode=0 (reduction via xor) is supported. The output will always + be of type ``torch.uint64``. The elements of ``input`` are upcasted to their + 64 bit float / integer equivalent and bitcasted to ``torch.uint64`` before + reduction via xor. + + Args: + input (Tensor): the input tensor. + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.1918, -1.1813, 0.3373]]) + >>> torch.hash_tensor(a) + tensor(13822780554648485888, dtype=torch.uint64) + + .. function:: hash_tensor(input, dim, *, keepdim=False, mode=0) -> Tensor + :noindex: + + Returns the hash of each row of the :attr:`input` tensor in the given + dimension :attr:`dim` given by mode. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(2, 4) + >>> a + tensor([[ 0.1317, -0.5554, -1.4724, -1.1391], + [ 0.0778, -0.6070, 0.6375, 0.1798]]) + >>> torch.hash_tensor(a, 1) + tensor([9233691267014066176, 9255993250844508160], dtype=torch.uint64) + """ + +def heaviside( + input: Tensor, + values: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + heaviside(input, values, *, out=None) -> Tensor + + Computes the Heaviside step function for each element in :attr:`input`. + The Heaviside step function is defined as: + + .. math:: + \text{{heaviside}}(input, values) = \begin{cases} + 0, & \text{if input < 0}\\ + values, & \text{if input == 0}\\ + 1, & \text{if input > 0} + \end{cases} + + + Args: + input (Tensor): the input tensor. + values (Tensor): The values to use where :attr:`input` is zero. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.tensor([-1.5, 0, 2.0]) + >>> values = torch.tensor([0.5]) + >>> torch.heaviside(input, values) + tensor([0.0000, 0.5000, 1.0000]) + >>> values = torch.tensor([1.2, -2.0, 3.5]) + >>> torch.heaviside(input, values) + tensor([0., -2., 1.]) + """ + +def hinge_embedding_loss( + input: Tensor, + target: Tensor, + margin: _float = 1.0, + reduction: _int = 1, +) -> Tensor: ... +def histc( + input: Tensor, + bins: _int = 100, + min: Number | _complex | PySymType = 0, + max: Number | _complex | PySymType = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + histc(input, bins=100, min=0, max=0, *, out=None) -> Tensor + + Computes the histogram of a tensor. + + The elements are sorted into equal width bins between :attr:`min` and + :attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and + maximum values of the data are used. + + Elements lower than min and higher than max and ``NaN`` elements are ignored. + + Args: + input (Tensor): the input tensor. + bins (int): number of histogram bins + min (Scalar): lower end of the range (inclusive) + max (Scalar): upper end of the range (inclusive) + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: Histogram represented as a tensor + + Example:: + + >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) + tensor([ 0., 2., 1., 0.]) + """ + +@overload +def histogram( + input: Tensor, + bins: Tensor, + *, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogram( + input: Tensor, + bins: _int = 100, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _int, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _size, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: tuple[Tensor, ...] | list[Tensor], + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +def hsmm(input: Tensor, mat2: Tensor) -> Tensor: ... +@overload +def hsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +@overload +def hsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +def hspmm( + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hspmm(mat1, mat2, *, out=None) -> Tensor + + Performs a matrix multiplication of a :ref:`sparse COO matrix + ` :attr:`mat1` and a strided matrix :attr:`mat2`. The + result is a (1 + 1)-dimensional :ref:`hybrid COO matrix + `. + + Args: + mat1 (Tensor): the first sparse matrix to be matrix multiplied + mat2 (Tensor): the second strided matrix to be matrix multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +def hstack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence horizontally (column wise). + + This is equivalent to concatenation along the first axis for 1-D tensors, and along the second axis for all other tensors. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.hstack((a,b)) + tensor([1, 2, 3, 4, 5, 6]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.hstack((a,b)) + tensor([[1, 4], + [2, 5], + [3, 6]]) + """ + +def hypot( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hypot(input, other, *, out=None) -> Tensor + + Given the legs of a right triangle, return its hypotenuse. + + .. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}^{2} + \text{other}_{i}^{2}} + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.hypot(torch.tensor([4.0]), torch.tensor([3.0, 4.0, 5.0])) + tensor([5.0000, 5.6569, 6.4031]) + """ + +def i0(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + i0(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.i0`. + """ + +def i0_(input: Tensor) -> Tensor: + r""" + i0_(input) -> Tensor + + In-place version of :func:`torch.i0` + """ + +def igamma( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + igamma(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.gammainc`. + """ + +def igammac( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + igammac(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.gammaincc`. + """ + +def imag(input: Tensor) -> Tensor: + r""" + imag(input) -> Tensor + + Returns a new tensor containing imaginary values of the :attr:`self` tensor. + The returned tensor and :attr:`self` share the same underlying storage. + + .. warning:: + :func:`imag` is only supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.imag + tensor([ 0.3553, -0.7896, -0.0633, -0.8119]) + """ + +def index_add( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + index_add(input: Tensor, dim: int, index: Tensor, source: Tensor, *, alpha: Union[Number, _complex] = 1, out: Optional[Tensor]) -> Tensor # noqa: B950 + + See :meth:`~Tensor.index_add_` for function description. + """ + +def index_copy( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_copy(input: Tensor, dim: int, index: Tensor, source: Tensor, *, out: Optional[Tensor]) -> Tensor + + See :meth:`~Tensor.index_copy_` for function description. + """ + +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Tensor, +) -> Tensor: ... +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, +) -> Tensor: ... +def index_put( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def index_put_( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def index_reduce( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + reduce: str, + *, + include_self: _bool = True, + out: Tensor | None = None, +) -> Tensor: + r""" + index_reduce(input: Tensor, dim: int, index: Tensor, source: Tensor, reduce: str, *, include_self: bool = True, out: Optional[Tensor]) -> Tensor # noqa: B950 + + See :meth:`~Tensor.index_reduce_` for function description. + """ + +def index_select( + input: Tensor, + dim: _int, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_select(input, dim, index, *, out=None) -> Tensor + + Returns a new tensor which indexes the :attr:`input` tensor along dimension + :attr:`dim` using the entries in :attr:`index`. + + The returned tensor has the same number of dimensions as the original tensor + (:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length + of :attr:`index`; other dimensions have the same size as in the original tensor. + + .. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) + """ + +def indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def init_num_threads() -> None: ... +def inner( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + inner(input, other, *, out=None) -> Tensor + + Computes the dot product for 1D tensors. For higher dimensions, sums the product + of elements from :attr:`input` and :attr:`other` along their last dimension. + + .. note:: + + If either :attr:`input` or :attr:`other` is a scalar, the result is equivalent + to `torch.mul(input, other)`. + + If both :attr:`input` and :attr:`other` are non-scalars, the size of their last + dimension must match and the result is equivalent to `torch.tensordot(input, + other, dims=([-1], [-1]))` + + Args: + input (Tensor): First input tensor + other (Tensor): Second input tensor + + Keyword args: + out (Tensor, optional): Optional output tensor to write result into. The output + shape is `input.shape[:-1] + other.shape[:-1]`. + + Example:: + + # Dot product + >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1])) + tensor(7) + + # Multidimensional input tensors + >>> a = torch.randn(2, 3) + >>> a + tensor([[0.8173, 1.0874, 1.1784], + [0.3279, 0.1234, 2.7894]]) + >>> b = torch.randn(2, 4, 3) + >>> b + tensor([[[-0.4682, -0.7159, 0.1506], + [ 0.4034, -0.3657, 1.0387], + [ 0.9892, -0.6684, 0.1774], + [ 0.9482, 1.3261, 0.3917]], + + [[ 0.4537, 0.7493, 1.1724], + [ 0.2291, 0.5749, -0.2267], + [-0.7920, 0.3607, -0.3701], + [ 1.3666, -0.5850, -1.7242]]]) + >>> torch.inner(a, b) + tensor([[[-0.9837, 1.1560, 0.2907, 2.6785], + [ 2.5671, 0.5452, -0.6912, -1.5509]], + + [[ 0.1782, 2.9843, 0.7366, 1.5672], + [ 3.5115, -0.4864, -1.2476, -4.4337]]]) + + # Scalar input + >>> torch.inner(a, torch.tensor(2)) + tensor([[1.6347, 2.1748, 2.3567], + [0.6558, 0.2469, 5.5787]]) + """ + +def instance_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + use_input_stats: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> Tensor: ... +def int_repr(input: Tensor) -> Tensor: ... +def inverse(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + inverse(input, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.inv` + """ + +def is_complex(input: Tensor) -> _bool: + r""" + is_complex(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a complex data type i.e., + one of ``torch.complex64``, and ``torch.complex128``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex64)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex128)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_complex(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + False + """ + +def is_conj(input: Tensor) -> _bool: + r""" + is_conj(input) -> (bool) + + Returns True if the :attr:`input` is a conjugated tensor, i.e. its conjugate bit is set to `True`. + + Args: + input (Tensor): the input tensor. + """ + +def is_distributed(input: Tensor) -> _bool: ... +def is_floating_point(input: Tensor) -> _bool: + r""" + is_floating_point(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a floating point data type i.e., + one of ``torch.float64``, ``torch.float32``, ``torch.float16``, and ``torch.bfloat16``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0])) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.complex64)) + False + """ + +def is_grad_enabled() -> _bool: + r""" + is_grad_enabled() -> (bool) + + Returns True if grad mode is currently enabled. + """ + +def is_inference(input: Tensor) -> _bool: + r""" + is_inference(input) -> (bool) + + Returns True if :attr:`input` is an inference tensor. + + A non-view tensor is an inference tensor if and only if it was + allocated during inference mode. A view tensor is an inference + tensor if and only if the tensor it is a view of is an inference tensor. + + For details on inference mode please see + `Inference Mode `_. + + Args: + input (Tensor): the input tensor. + """ + +def is_inference_mode_enabled() -> _bool: + r""" + is_inference_mode_enabled() -> (bool) + + Returns True if inference mode is currently enabled. + """ + +def is_neg(input: Tensor) -> _bool: ... +def is_nonzero(input: Tensor) -> _bool: + r""" + is_nonzero(input) -> (bool) + + Returns True if the :attr:`input` is a single element tensor which is not equal to zero + after type conversions. + i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or + ``torch.tensor([False])``. + Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case + of sparse tensors). + + Args: + input (Tensor): the input tensor. + + Examples:: + + >>> torch.is_nonzero(torch.tensor([0.])) + False + >>> torch.is_nonzero(torch.tensor([1.5])) + True + >>> torch.is_nonzero(torch.tensor([False])) + False + >>> torch.is_nonzero(torch.tensor([3])) + True + >>> torch.is_nonzero(torch.tensor([1, 3, 5])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with no values is ambiguous + """ + +def is_same_size(input: Tensor, other: Tensor) -> _bool: ... +def is_signed(input: Tensor) -> _bool: ... +def is_vulkan_available() -> _bool: ... +def isclose( + input: Tensor, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, +) -> Tensor: + r""" + isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + Returns a new tensor with boolean elements representing if each element of + :attr:`input` is "close" to the corresponding element of :attr:`other`. + Closeness is defined as: + + .. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{rtol} \times \lvert \text{other}_i \rvert + \texttt{atol} + + + where :attr:`input` and :attr:`other` are finite. Where :attr:`input` + and/or :attr:`other` are nonfinite they are close if and only if + they are equal, with NaNs being considered equal to each other when + :attr:`equal_nan` is True. + + Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + rtol (float, optional): relative tolerance. Default: 1e-05 + atol (float, optional): absolute tolerance. Default: 1e-08 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + + Examples:: + + >>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4))) + tensor([ True, False, False]) + >>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5) + tensor([True, True]) + """ + +def isfinite(input: Tensor) -> Tensor: + r""" + isfinite(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element is `finite` or not. + + Real values are finite when they are not NaN, negative infinity, or infinity. + Complex values are finite when both their real and imaginary parts are finite. + + Args: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is finite and False elsewhere + + Example:: + + >>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([True, False, True, False, False]) + """ + +@overload +def isin( + elements: Tensor, + test_elements: Tensor, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +@overload +def isin( + element: Number | _complex | PySymType, + test_elements: Tensor, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +@overload +def isin( + elements: Tensor, + test_element: Number | _complex | PySymType, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +def isinf(input: Tensor) -> Tensor: + r""" + isinf(input) -> Tensor + + Tests if each element of :attr:`input` is infinite + (positive or negative infinity) or not. + + .. note:: + Complex values are infinite when their real or imaginary part is + infinite. + + Args: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is infinite and False elsewhere + + Example:: + + >>> torch.isinf(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([False, True, False, True, False]) + """ + +def isnan(input: Tensor) -> Tensor: + r""" + isnan(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element of :attr:`input` + is NaN or not. Complex values are considered NaN when either their real + and/or imaginary part is NaN. + + Arguments: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is NaN and False elsewhere + + Example:: + + >>> torch.isnan(torch.tensor([1, float('nan'), 2])) + tensor([False, True, False]) + """ + +def isneginf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + isneginf(input, *, out=None) -> Tensor + Tests if each element of :attr:`input` is negative infinity or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isneginf(a) + tensor([ True, False, False]) + """ + +def isposinf(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + isposinf(input, *, out=None) -> Tensor + Tests if each element of :attr:`input` is positive infinity or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([-float('inf'), float('inf'), 1.2]) + >>> torch.isposinf(a) + tensor([False, True, False]) + """ + +def isreal(input: Tensor) -> Tensor: + r""" + isreal(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element of :attr:`input` is real-valued or not. + All real-valued types are considered real. Complex values are considered real when their imaginary part is 0. + + Arguments: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is real and False elsewhere + + Example:: + + >>> torch.isreal(torch.tensor([1, 1+1j, 2+0j])) + tensor([True, False, True]) + """ + +def istft( + input: Tensor, + n_fft: _int, + hop_length: _int | None = None, + win_length: _int | None = None, + window: Tensor | None = None, + center: _bool = True, + normalized: _bool = False, + onesided: _bool | None = None, + length: _int | None = None, + return_complex: _bool = False, +) -> Tensor: ... +@overload +def kaiser_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +@overload +def kaiser_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +@overload +def kaiser_window( + window_length: _int, + periodic: _bool, + beta: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + kaiser_window(window_length, periodic=True, beta=12.0, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Computes the Kaiser window with window length :attr:`window_length` and shape parameter :attr:`beta`. + + Let I_0 be the zeroth order modified Bessel function of the first kind (see :func:`torch.i0`) and + ``N = L - 1`` if :attr:`periodic` is False and ``L`` if :attr:`periodic` is True, + where ``L`` is the :attr:`window_length`. This function computes: + + .. math:: + out_i = I_0 \left( \beta \sqrt{1 - \left( {\frac{i - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta ) + + Calling ``torch.kaiser_window(L, B, periodic=True)`` is equivalent to calling + ``torch.kaiser_window(L + 1, B, periodic=False)[:-1])``. + The :attr:`periodic` argument is intended as a helpful shorthand + to produce a periodic window as input to functions like :func:`torch.stft`. + + .. note:: + If :attr:`window_length` is one, then the returned window is a single element tensor containing a one. + + + Args: + window_length (int): length of the window. + periodic (bool, optional): If True, returns a periodic window suitable for use in spectral analysis. + If False, returns a symmetric window suitable for use in filter design. + beta (float, optional): shape parameter for the window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + """ + +def kl_div( + input: Tensor, + target: Tensor, + reduction: _int = 1, + *, + log_target: _bool = False, +) -> Tensor: ... +def kron( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + kron(input, other, *, out=None) -> Tensor + + Computes the Kronecker product, denoted by :math:`\otimes`, of :attr:`input` and :attr:`other`. + + If :attr:`input` is a :math:`(a_0 \times a_1 \times \dots \times a_n)` tensor and :attr:`other` is a + :math:`(b_0 \times b_1 \times \dots \times b_n)` tensor, the result will be a + :math:`(a_0*b_0 \times a_1*b_1 \times \dots \times a_n*b_n)` tensor with the following entries: + + .. math:: + (\text{input} \otimes \text{other})_{k_0, k_1, \dots, k_n} = + \text{input}_{i_0, i_1, \dots, i_n} * \text{other}_{j_0, j_1, \dots, j_n}, + + where :math:`k_t = i_t * b_t + j_t` for :math:`0 \leq t \leq n`. + If one tensor has fewer dimensions than the other it is unsqueezed until it has the same number of dimensions. + + Supports real-valued and complex-valued inputs. + + .. note:: + This function generalizes the typical definition of the Kronecker product for two matrices to two tensors, + as described above. When :attr:`input` is a :math:`(m \times n)` matrix and :attr:`other` is a + :math:`(p \times q)` matrix, the result will be a :math:`(p*m \times q*n)` block matrix: + + .. math:: + \mathbf{A} \otimes \mathbf{B}=\begin{bmatrix} + a_{11} \mathbf{B} & \cdots & a_{1 n} \mathbf{B} \\ + \vdots & \ddots & \vdots \\ + a_{m 1} \mathbf{B} & \cdots & a_{m n} \mathbf{B} \end{bmatrix} + + where :attr:`input` is :math:`\mathbf{A}` and :attr:`other` is :math:`\mathbf{B}`. + + Arguments: + input (Tensor) + other (Tensor) + + Keyword args: + out (Tensor, optional): The output tensor. Ignored if ``None``. Default: ``None`` + + Examples:: + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.ones(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 1., 0., 0.], + [1., 1., 0., 0.], + [0., 0., 1., 1.], + [0., 0., 1., 1.]]) + + >>> mat1 = torch.eye(2) + >>> mat2 = torch.arange(1, 5).reshape(2, 2) + >>> torch.kron(mat1, mat2) + tensor([[1., 2., 0., 0.], + [3., 4., 0., 0.], + [0., 0., 1., 2.], + [0., 0., 3., 4.]]) + """ + +def kthvalue( + input: Tensor, + k: _int | SymInt, + dim: _int = -1, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.kthvalue: + r""" + kthvalue(input, k, dim=None, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th + smallest element of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each element found. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors + are the same size as :attr:`input`, except in the dimension :attr:`dim` where + they are of size 1. Otherwise, :attr:`dim` is squeezed + (see :func:`torch.squeeze`), resulting in both the :attr:`values` and + :attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor. + + .. note:: + When :attr:`input` is a CUDA tensor and there are multiple valid + :attr:`k` th values, this function may nondeterministically return + :attr:`indices` for any of them. + + Args: + input (Tensor): the input tensor. + k (int): k for the k-th smallest element + dim (int, optional): the dimension to find the kth value along + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) + can be optionally given to be used as output buffers + + Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.kthvalue(x, 4) + torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3)) + + >>> x=torch.arange(1.,7.).resize_(2,3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.]]) + >>> torch.kthvalue(x, 2, 0, True) + torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]])) + """ + +def layer_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None = None, + bias: Tensor | None = None, + eps: _float = 1e-05, + cudnn_enable: _bool = True, +) -> Tensor: ... +def lcm( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lcm(input, other, *, out=None) -> Tensor + + Computes the element-wise least common multiple (LCM) of :attr:`input` and :attr:`other`. + + Both :attr:`input` and :attr:`other` must have integer types. + + .. note:: + This defines :math:`lcm(0, 0) = 0` and :math:`lcm(0, a) = 0`. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([5, 10, 15]) + >>> b = torch.tensor([3, 4, 5]) + >>> torch.lcm(a, b) + tensor([15, 20, 15]) + >>> c = torch.tensor([3]) + >>> torch.lcm(a, c) + tensor([15, 30, 15]) + """ + +def lcm_(input: Tensor, other: Tensor) -> Tensor: + r""" + lcm_(input, other) -> Tensor + + In-place version of :func:`torch.lcm` + """ + +def ldexp( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ldexp(input, other, *, out=None) -> Tensor + + Multiplies :attr:`input` by 2 ** :attr:`other`. + + .. math:: + \text{{out}}_i = \text{{input}}_i * 2^\text{{other}}_i + + + Typically this function is used to construct floating point numbers by multiplying + mantissas in :attr:`input` with integral powers of two created from the exponents + in :attr:`other`. + + Args: + input (Tensor): the input tensor. + other (Tensor): a tensor of exponents, typically integers. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.ldexp(torch.tensor([1.]), torch.tensor([1])) + tensor([2.]) + >>> torch.ldexp(torch.tensor([1.0]), torch.tensor([1, 2, 3, 4])) + tensor([ 2., 4., 8., 16.]) + """ + +def ldexp_(input: Tensor, other: Tensor) -> Tensor: + r""" + ldexp_(input, other) -> Tensor + + In-place version of :func:`torch.ldexp` + """ + +@overload +def le( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + le(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \leq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + + Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) + """ + +@overload +def le( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + le(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \leq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or Scalar): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than or equal to + :attr:`other` and False elsewhere + + Example:: + + >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[True, False], [True, True]]) + """ + +@overload +def lerp( + input: Tensor, + end: Tensor, + weight: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lerp(input, end, weight, *, out=None) + + Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based + on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + + .. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) + + The shapes of :attr:`start` and :attr:`end` must be + :ref:`broadcastable `. If :attr:`weight` is a tensor, then + the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + + Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + """ + +@overload +def lerp( + input: Tensor, + end: Tensor, + weight: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lerp(input, end, weight, *, out=None) + + Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based + on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor. + + .. math:: + \text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i) + + The shapes of :attr:`start` and :attr:`end` must be + :ref:`broadcastable `. If :attr:`weight` is a tensor, then + the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable `. + + Args: + input (Tensor): the tensor with the starting points + end (Tensor): the tensor with the ending points + weight (float or tensor): the weight for the interpolation formula + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> start = torch.arange(1., 5.) + >>> end = torch.empty(4).fill_(10) + >>> start + tensor([ 1., 2., 3., 4.]) + >>> end + tensor([ 10., 10., 10., 10.]) + >>> torch.lerp(start, end, 0.5) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + >>> torch.lerp(start, end, torch.full_like(start, 0.5)) + tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) + """ + +@overload +def less( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.lt`. + """ + +@overload +def less( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.lt`. + """ + +@overload +def less_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.le`. + """ + +@overload +def less_equal( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + less_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.le`. + """ + +def lgamma(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + lgamma(input, *, out=None) -> Tensor + + Computes the natural logarithm of the absolute value of the gamma function on :attr:`input`. + + .. math:: + \text{out}_{i} = \ln |\Gamma(\text{input}_{i})| + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.arange(0.5, 2, 0.5) + >>> torch.lgamma(a) + tensor([ 0.5724, 0.0000, -0.1208]) + """ + +@overload +def linspace( + start: Number, + end: Number, + steps: _int | None = None, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Tensor, + end: Tensor, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Number | _complex | PySymType, + end: Tensor, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Tensor, + end: Number | _complex | PySymType, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +@overload +def linspace( + start: Number | _complex | PySymType, + end: Number | _complex | PySymType, + steps: _int, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :attr:`start` to :attr:`end`, inclusive. That is, the value are: + + .. math:: + (\text{start}, + \text{start} + \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \ldots, + \text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{\text{steps} - 1}, + \text{end}) + + + From PyTorch 1.11 linspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + + Example:: + + >>> torch.linspace(3, 10, steps=5) + tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) + >>> torch.linspace(-10, 10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=5) + tensor([-10., -5., 0., 5., 10.]) + >>> torch.linspace(start=-10, end=10, steps=1) + tensor([-10.]) + """ + +def log(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log(input, *, out=None) -> Tensor + + Returns a new tensor with the natural logarithm of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{e} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) * 5 + >>> a + tensor([4.7767, 4.3234, 1.2156, 0.2411, 4.5739]) + >>> torch.log(a) + tensor([ 1.5637, 1.4640, 0.1952, -1.4226, 1.5204]) + """ + +def log10(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log10(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the logarithm to the base 10 of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{10} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.5224, 0.9354, 0.7257, 0.1301, 0.2251]) + + + >>> torch.log10(a) + tensor([-0.2820, -0.0290, -0.1392, -0.8857, -0.6476]) + """ + +def log10_(input: Tensor) -> Tensor: + r""" + log10_(input) -> Tensor + + In-place version of :func:`torch.log10` + """ + +def log1p(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log1p(input, *, out=None) -> Tensor + + Returns a new tensor with the natural logarithm of (1 + :attr:`input`). + + .. math:: + y_i = \log_{e} (x_i + 1) + + .. note:: This function is more accurate than :func:`torch.log` for small + values of :attr:`input` + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.0090, -0.9923, 1.0249, -0.5372, 0.2492]) + >>> torch.log1p(a) + tensor([ nan, -4.8653, 0.7055, -0.7705, 0.2225]) + """ + +def log1p_(input: Tensor) -> Tensor: + r""" + log1p_(input) -> Tensor + + In-place version of :func:`torch.log1p` + """ + +def log2(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + log2(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the logarithm to the base 2 of the elements + of :attr:`input`. + + .. math:: + y_{i} = \log_{2} (x_{i}) + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(5) + >>> a + tensor([ 0.8419, 0.8003, 0.9971, 0.5287, 0.0490]) + + + >>> torch.log2(a) + tensor([-0.2483, -0.3213, -0.0042, -0.9196, -4.3504]) + """ + +def log2_(input: Tensor) -> Tensor: + r""" + log2_(input) -> Tensor + + In-place version of :func:`torch.log2` + """ + +def log_(input: Tensor) -> Tensor: + r""" + log_(input) -> Tensor + + In-place version of :func:`torch.log` + """ + +def log_softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, + *, + out: Tensor | None = None, +) -> Tensor: ... +def logaddexp( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logaddexp(input, other, *, out=None) -> Tensor + + Logarithm of the sum of exponentiations of the inputs. + + Calculates pointwise :math:`\log\left(e^x + e^y\right)`. This function is useful + in statistics where the calculated probabilities of events may be so small as to + exceed the range of normal floating point numbers. In such cases the logarithm + of the calculated probability is stored. This function allows adding + probabilities stored in such a fashion. + + This op should be disambiguated with :func:`torch.logsumexp` which performs a + reduction on a single tensor. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logaddexp(torch.tensor([-1.0]), torch.tensor([-1.0, -2, -3])) + tensor([-0.3069, -0.6867, -0.8731]) + >>> torch.logaddexp(torch.tensor([-100.0, -200, -300]), torch.tensor([-1.0, -2, -3])) + tensor([-1., -2., -3.]) + >>> torch.logaddexp(torch.tensor([1.0, 2000, 30000]), torch.tensor([-1.0, -2, -3])) + tensor([1.1269e+00, 2.0000e+03, 3.0000e+04]) + """ + +def logaddexp2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logaddexp2(input, other, *, out=None) -> Tensor + + Logarithm of the sum of exponentiations of the inputs in base-2. + + Calculates pointwise :math:`\log_2\left(2^x + 2^y\right)`. See + :func:`torch.logaddexp` for more details. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword arguments: + out (Tensor, optional): the output tensor. + """ + +def logcumsumexp( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logcumsumexp(input, dim, *, out=None) -> Tensor + Returns the logarithm of the cumulative summation of the exponentiation of + elements of :attr:`input` in the dimension :attr:`dim`. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logcumsumexp}(x)_{ij} = \log \sum\limits_{k=0}^{j} \exp(x_{ik}) + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to do the operation over + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(10) + >>> torch.logcumsumexp(a, dim=0) + tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811, + 1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475])) + """ + +def logdet(input: Tensor) -> Tensor: + r""" + logdet(input) -> Tensor + + Calculates log determinant of a square matrix or batches of square matrices. + + It returns ``-inf`` if the input has a determinant of zero, and ``NaN`` if it has + a negative determinant. + + .. note:: + Backward through :meth:`logdet` internally uses SVD results when :attr:`input` + is not invertible. In this case, double backward through :meth:`logdet` will + be unstable in when :attr:`input` doesn't have distinct singular values. See + :func:`torch.linalg.svd` for details. + + .. seealso:: + + :func:`torch.linalg.slogdet` computes the sign (resp. angle) and natural logarithm of the + absolute value of the determinant of real-valued (resp. complex) square matrices. + + Arguments: + input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more + batch dimensions. + + Example:: + + >>> A = torch.randn(3, 3) + >>> torch.det(A) + tensor(0.2611) + >>> torch.logdet(A) + tensor(-1.3430) + >>> A + tensor([[[ 0.9254, -0.6213], + [-0.5787, 1.6843]], + + [[ 0.3242, -0.9665], + [ 0.4539, -0.0887]], + + [[ 1.1336, -0.4025], + [-0.7089, 0.9032]]]) + >>> A.det() + tensor([1.1990, 0.4099, 0.7386]) + >>> A.det().log() + tensor([ 0.1815, -0.8917, -0.3031]) + """ + +def logical_and( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_and(input, other, *, out=None) -> Tensor + + Computes the element-wise logical AND of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute AND with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_and(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, False]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_and(a, b) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b.double()) + tensor([False, False, True, False]) + >>> torch.logical_and(a.double(), b) + tensor([False, False, True, False]) + >>> torch.logical_and(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([False, False, True, False]) + """ + +def logical_not(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + logical_not(input, *, out=None) -> Tensor + + Computes the element-wise logical NOT of the given input tensor. If not specified, the output tensor will have the bool + dtype. If the input tensor is not a bool tensor, zeros are treated as ``False`` and non-zeros are treated as ``True``. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_not(torch.tensor([True, False])) + tensor([False, True]) + >>> torch.logical_not(torch.tensor([0, 1, -10], dtype=torch.int8)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1.5, -10.], dtype=torch.double)) + tensor([ True, False, False]) + >>> torch.logical_not(torch.tensor([0., 1., -10.], dtype=torch.double), out=torch.empty(3, dtype=torch.int16)) + tensor([1, 0, 0], dtype=torch.int16) + """ + +def logical_or( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_or(input, other, *, out=None) -> Tensor + + Computes the element-wise logical OR of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute OR with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_or(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([ True, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_or(a, b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b.double()) + tensor([ True, True, True, False]) + >>> torch.logical_or(a.double(), b) + tensor([ True, True, True, False]) + >>> torch.logical_or(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, True, False]) + """ + +def logical_xor( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logical_xor(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the element-wise logical XOR of the given input tensors. Zeros are treated as ``False`` and nonzeros are + treated as ``True``. + + Args: + input (Tensor): the input tensor. + other (Tensor): the tensor to compute XOR with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.logical_xor(torch.tensor([True, False, True]), torch.tensor([True, False, False])) + tensor([False, False, True]) + >>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8) + >>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8) + >>> torch.logical_xor(a, b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b.double()) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a.double(), b) + tensor([ True, True, False, False]) + >>> torch.logical_xor(a, b, out=torch.empty(4, dtype=torch.bool)) + tensor([ True, True, False, False]) + """ + +def logit( + input: Tensor, + eps: _float | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logit(input, eps=None, *, out=None) -> Tensor + + Alias for :func:`torch.special.logit`. + """ + +def logit_(input: Tensor, eps: _float | None = None) -> Tensor: + r""" + logit_(input, eps=None) -> Tensor + + In-place version of :func:`torch.logit` + """ + +@overload +def logspace( + start: Number, + end: Number, + steps: _int | None = None, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Tensor, + end: Tensor, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Number | _complex | PySymType, + end: Tensor, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Tensor, + end: Number | _complex | PySymType, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +@overload +def logspace( + start: Number | _complex | PySymType, + end: Number | _complex | PySymType, + steps: _int, + base: _float = 10.0, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + logspace(start, end, steps, base=10.0, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + + Creates a one-dimensional tensor of size :attr:`steps` whose values are evenly + spaced from :math:`{{\text{{base}}}}^{{\text{{start}}}}` to + :math:`{{\text{{base}}}}^{{\text{{end}}}}`, inclusive, on a logarithmic scale + with base :attr:`base`. That is, the values are: + + .. math:: + (\text{base}^{\text{start}}, + \text{base}^{(\text{start} + \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \ldots, + \text{base}^{(\text{start} + (\text{steps} - 2) * \frac{\text{end} - \text{start}}{ \text{steps} - 1})}, + \text{base}^{\text{end}}) + + + + From PyTorch 1.11 logspace requires the steps argument. Use steps=100 to restore the previous behavior. + + Args: + start (float or Tensor): the starting value for the set of points. If `Tensor`, it must be 0-dimensional + end (float or Tensor): the ending value for the set of points. If `Tensor`, it must be 0-dimensional + steps (int): size of the constructed tensor + base (float, optional): base of the logarithm function. Default: ``10.0``. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the data type to perform the computation in. + Default: if None, uses the global default dtype (see torch.get_default_dtype()) + when both :attr:`start` and :attr:`end` are real, + and corresponding complex dtype when either is complex. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.logspace(start=-10, end=10, steps=5) + tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) + >>> torch.logspace(start=0.1, end=1.0, steps=5) + tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) + >>> torch.logspace(start=0.1, end=1.0, steps=1) + tensor([1.2589]) + >>> torch.logspace(start=2, end=2, steps=1, base=2) + tensor([4.0]) + """ + +def logsumexp( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + logsumexp(input, dim, keepdim=False, *, out=None) + + Returns the log of summed exponentials of each row of the :attr:`input` + tensor in the given dimension :attr:`dim`. The computation is numerically + stabilized. + + For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is + + .. math:: + \text{logsumexp}(x)_{i} = \log \sum_j \exp(x_{ij}) + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints): the dimension or dimensions to reduce. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> torch.logsumexp(a, 1) + tensor([1.4907, 1.0593, 1.5696]) + >>> torch.dist(torch.logsumexp(a, 1), torch.log(torch.sum(torch.exp(a), 1))) + tensor(1.6859e-07) + """ + +@overload +def lstm( + data: Tensor, + batch_sizes: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def lstm( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor, Tensor]: ... +def lstm_cell( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> tuple[Tensor, Tensor]: ... +@overload +def lt( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} < \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + + Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) + """ + +@overload +def lt( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} < \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is less than :attr:`other` and False elsewhere + + Example:: + + >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, False], [True, False]]) + """ + +def lu_solve( + input: Tensor, + LU_data: Tensor, + LU_pivots: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + lu_solve(b, LU_data, LU_pivots, *, out=None) -> Tensor + + Returns the LU solve of the linear system :math:`Ax = b` using the partially pivoted + LU factorization of A from :func:`~linalg.lu_factor`. + + This function supports ``float``, ``double``, ``cfloat`` and ``cdouble`` dtypes for :attr:`input`. + + .. warning:: + + :func:`torch.lu_solve` is deprecated in favor of :func:`torch.linalg.lu_solve`. + :func:`torch.lu_solve` will be removed in a future PyTorch release. + ``X = torch.lu_solve(B, LU, pivots)`` should be replaced with + + .. code:: python + + X = linalg.lu_solve(LU, pivots, B) + + Arguments: + b (Tensor): the RHS tensor of size :math:`(*, m, k)`, where :math:`*` + is zero or more batch dimensions. + LU_data (Tensor): the pivoted LU factorization of A from :meth:`~linalg.lu_factor` of size :math:`(*, m, m)`, + where :math:`*` is zero or more batch dimensions. + LU_pivots (IntTensor): the pivots of the LU factorization from :meth:`~linalg.lu_factor` of size :math:`(*, m)`, + where :math:`*` is zero or more batch dimensions. + The batch dimensions of :attr:`LU_pivots` must be equal to the batch dimensions of + :attr:`LU_data`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> A = torch.randn(2, 3, 3) + >>> b = torch.randn(2, 3, 1) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> x = torch.lu_solve(b, LU, pivots) + >>> torch.dist(A @ x, b) + tensor(1.00000e-07 * + 2.8312) + """ + +def lu_unpack( + LU_data: Tensor, + LU_pivots: Tensor, + unpack_data: _bool = True, + unpack_pivots: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.lu_unpack: + r""" + lu_unpack(LU_data, LU_pivots, unpack_data=True, unpack_pivots=True, *, out=None) -> (Tensor, Tensor, Tensor) + + Unpacks the LU decomposition returned by :func:`~linalg.lu_factor` into the `P, L, U` matrices. + + .. seealso:: + + :func:`~linalg.lu` returns the matrices from the LU decomposition. Its gradient formula is more efficient + than that of doing :func:`~linalg.lu_factor` followed by :func:`~linalg.lu_unpack`. + + Args: + LU_data (Tensor): the packed LU factorization data + LU_pivots (Tensor): the packed LU factorization pivots + unpack_data (bool): flag indicating if the data should be unpacked. + If ``False``, then the returned ``L`` and ``U`` are empty tensors. + Default: ``True`` + unpack_pivots (bool): flag indicating if the pivots should be unpacked into a permutation matrix ``P``. + If ``False``, then the returned ``P`` is an empty tensor. + Default: ``True`` + + Keyword args: + out (tuple, optional): output tuple of three tensors. Ignored if `None`. + + Returns: + A namedtuple ``(P, L, U)`` + + Examples:: + + >>> A = torch.randn(2, 3, 3) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # We can recover A from the factorization + >>> A_ = P @ L @ U + >>> torch.allclose(A, A_) + True + + >>> # LU factorization of a rectangular matrix: + >>> A = torch.randn(2, 3, 2) + >>> LU, pivots = torch.linalg.lu_factor(A) + >>> P, L, U = torch.lu_unpack(LU, pivots) + >>> # P, L, U are the same as returned by linalg.lu + >>> P_, L_, U_ = torch.linalg.lu(A) + >>> torch.allclose(P, P_) and torch.allclose(L, L_) and torch.allclose(U, U_) + True + """ + +def margin_ranking_loss( + input1: Tensor, + input2: Tensor, + target: Tensor, + margin: _float = 0.0, + reduction: _int = 1, +) -> Tensor: ... +@overload +def masked_fill(input: Tensor, mask: Tensor, value: Tensor) -> Tensor: ... +@overload +def masked_fill( + input: Tensor, + mask: Tensor, + value: Number | _complex | PySymType, +) -> Tensor: ... +def masked_scatter(input: Tensor, mask: Tensor, source: Tensor) -> Tensor: ... +def masked_select( + input: Tensor, + mask: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + masked_select(input, mask, *, out=None) -> Tensor + + Returns a new 1-D tensor which indexes the :attr:`input` tensor according to + the boolean mask :attr:`mask` which is a `BoolTensor`. + + The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need + to match, but they must be :ref:`broadcastable `. + + .. note:: The returned tensor does **not** use the same storage + as the original tensor + + Args: + input (Tensor): the input tensor. + mask (BoolTensor): the tensor containing the binary mask to index with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.3552, -2.3825, -0.8297, 0.3477], + [-1.2035, 1.2252, 0.5002, 0.6248], + [ 0.1307, -2.0608, 0.1244, 2.0139]]) + >>> mask = x.ge(0.5) + >>> mask + tensor([[False, False, False, False], + [False, True, True, True], + [False, False, False, True]]) + >>> torch.masked_select(x, mask) + tensor([ 1.2252, 0.5002, 0.6248, 2.0139]) + """ + +def matmul( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matmul(input, other, *, out=None) -> Tensor + + Matrix product of two tensors. + + The behavior depends on the dimensionality of the tensors as follows: + + - If both tensors are 1-dimensional, the dot product (scalar) is returned. + - If both arguments are 2-dimensional, the matrix-matrix product is returned. + - If the first argument is 1-dimensional and the second argument is 2-dimensional, + a 1 is prepended to its dimension for the purpose of the matrix multiply. + After the matrix multiply, the prepended dimension is removed. + - If the first argument is 2-dimensional and the second argument is 1-dimensional, + the matrix-vector product is returned. + - If both arguments are at least 1-dimensional and at least one argument is + N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first + argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the + batched matrix multiply and removed after. If the second argument is 1-dimensional, a + 1 is appended to its dimension for the purpose of the batched matrix multiply and removed after. + + The first N-2 dimensions of each argument, the batch dimensions, are + :ref:`broadcast ` (and thus must be broadcastable). + The last 2, the matrix dimensions, are handled as in the matrix-matrix product. + + For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times m)` tensor and :attr:`other` is a :math:`(k \times m \times p)` + tensor, the batch dimensions are :math:`(j \times 1)` and :math:`(k)`, + and the matrix dimensions are :math:`(n \times m)` and :math:`(m \times p)`. + :attr:`out` will be a :math:`(j \times k \times n \times p)` tensor. + + This operation has support for arguments with :ref:`sparse layouts`. In particular the + matrix-matrix (both arguments 2-dimensional) supports sparse arguments with the same restrictions + as :func:`torch.mm` + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: + + The 1-dimensional dot product version of this function does not support an :attr:`out` parameter. + + Arguments: + input (Tensor): the first tensor to be multiplied + other (Tensor): the second tensor to be multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> # vector x vector + >>> tensor1 = torch.randn(3) + >>> tensor2 = torch.randn(3) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([]) + >>> # matrix x vector + >>> tensor1 = torch.randn(3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([3]) + >>> # batched matrix x broadcasted vector + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3]) + >>> # batched matrix x batched matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(10, 4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + >>> # batched matrix x broadcasted matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + """ + +def matrix_exp(input: Tensor) -> Tensor: + r""" + matrix_exp(A) -> Tensor + + Alias for :func:`torch.linalg.matrix_exp`. + """ + +def matrix_power( + input: Tensor, + n: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matrix_power(input, n, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.matrix_power` + """ + +@overload +def max(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.max: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +def max_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def max_pool1d_with_indices( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> tuple[Tensor, Tensor]: ... +def max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def maximum( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + maximum(input, other, *, out=None) -> Tensor + + Computes the element-wise maximum of :attr:`input` and :attr:`other`. + + .. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`maximum` is not supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.maximum(a, b) + tensor([3, 2, 4]) + """ + +@overload +def mean( + input: Tensor, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + mean(input, *, dtype=None) -> Tensor + + .. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + + Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + + Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + + .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + + Returns the mean value of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) + """ + +@overload +def mean( + input: Tensor, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + mean(input, *, dtype=None) -> Tensor + + .. note:: + If the `input` tensor is empty, ``torch.mean()`` returns ``nan``. + This behavior is consistent with NumPy and follows the definition + that the mean over an empty set is undefined. + + + Returns the mean value of all elements in the :attr:`input` tensor. Input must be floating point or complex. + + Args: + input (Tensor): + the input tensor, either of floating point or complex dtype + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.2294, -0.5481, 1.3288]]) + >>> torch.mean(a) + tensor(0.3367) + + .. function:: mean(input, dim, keepdim=False, *, dtype=None, out=None) -> Tensor + :noindex: + + Returns the mean value of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.nanmean` computes the mean value of `non-NaN` elements. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.3841, 0.6320, 0.4254, -0.7384], + [-0.9644, 1.0131, -0.6549, -1.4279], + [-0.2951, -1.3350, -0.7694, 0.5600], + [ 1.0842, -0.9580, 0.3623, 0.2343]]) + >>> torch.mean(a, 1) + tensor([-0.0163, -0.5085, -0.4599, 0.1807]) + >>> torch.mean(a, 1, True) + tensor([[-0.0163], + [-0.5085], + [-0.4599], + [ 0.1807]]) + """ + +@overload +def median(input: Tensor) -> Tensor: + r""" + median(input) -> Tensor + + Returns the median of the values in :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + + .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size + as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the outputs tensor having 1 fewer dimension than :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) + """ + +@overload +def median( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.median: + r""" + median(input) -> Tensor + + Returns the median of the values in :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements. In this case the lower of the two medians is returned. To + compute the mean of both medians, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + This function produces deterministic (sub)gradients unlike ``median(dim=0)`` + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.5219, -1.5212, 0.2202]]) + >>> torch.median(a) + tensor(0.2202) + + .. function:: median(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, and ``indices`` contains the index of the median values found in the dimension :attr:`dim`. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size + as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the outputs tensor having 1 fewer dimension than :attr:`input`. + + .. note:: + The median is not unique for :attr:`input` tensors with an even number + of elements in the dimension :attr:`dim`. In this case the lower of the + two medians is returned. To compute the mean of both medians in + :attr:`input`, use :func:`torch.quantile` with ``q=0.5`` instead. + + .. warning:: + ``indices`` does not necessarily contain the first occurrence of each + median value found, unless it is unique. + The exact implementation details are device-specific. + Do not expect the same result when run on CPU and GPU in general. + For the same reason do not expect the gradients to be deterministic. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.randn(4, 5) + >>> a + tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], + [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], + [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], + [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) + >>> torch.median(a, 1) + torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3])) + """ + +@overload +def min(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.min: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +def minimum( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + minimum(input, other, *, out=None) -> Tensor + + Computes the element-wise minimum of :attr:`input` and :attr:`other`. + + .. note:: + If one of the elements being compared is a NaN, then that element is returned. + :func:`minimum` is not supported for tensors with complex dtypes. + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2, -1)) + >>> b = torch.tensor((3, 0, 4)) + >>> torch.minimum(a, b) + tensor([1, 0, -1]) + """ + +def miopen_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + exponential_average_factor: _float, + epsilon: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def miopen_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +def miopen_convolution_add_relu( + input: Tensor, + weight: Tensor, + z: Tensor, + alpha: Number | _complex | PySymType | None, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def miopen_convolution_relu( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + stride: Sequence[_int | SymInt], + padding: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def miopen_convolution_transpose( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + output_padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +@overload +def miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, Tensor]: ... +def miopen_depthwise_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, +) -> Tensor: ... +def miopen_rnn( + input: Tensor, + weight: tuple[Tensor, ...] | list[Tensor], + weight_stride0: _int, + hx: Tensor, + cx: Tensor | None, + mode: _int, + hidden_size: _int, + num_layers: _int, + batch_first: _bool, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_sizes: _size, + dropout_state: Tensor | None, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: ... +def mkldnn_adaptive_avg_pool2d( + input: Tensor, + output_size: _int | _size, + *, + out: Tensor | None = None, +) -> Tensor: ... +def mkldnn_convolution( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, +) -> Tensor: ... +def mkldnn_linear_backward_weights( + grad_output: Tensor, + input: Tensor, + weight: Tensor, + bias_defined: _bool, +) -> tuple[Tensor, Tensor]: ... +def mkldnn_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def mkldnn_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def mkldnn_rnn_layer( + input: Tensor, + weight0: Tensor, + weight1: Tensor, + weight2: Tensor, + weight3: Tensor, + hx_: Tensor, + cx_: Tensor, + reverse: _bool, + batch_sizes: _size, + mode: _int, + hidden_size: _int, + num_layers: _int, + has_biases: _bool, + bidirectional: _bool, + batch_first: _bool, + train: _bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +@overload +def mm(input: Tensor, mat2: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + mm(input, mat2, *, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Supports strided and sparse 2-D tensors as inputs, autograd with + respect to strided inputs. + + This operation has support for arguments with :ref:`sparse layouts`. + If :attr:`out` is provided its layout will be used. Otherwise, the result + layout will be deduced from that of :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) + + .. function:: mm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +@overload +def mm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mm(input, mat2, *, out=None) -> Tensor + + Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`mat2` is a + :math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. + + .. note:: This function does not :ref:`broadcast `. + For broadcasting matrix products, see :func:`torch.matmul`. + + Supports strided and sparse 2-D tensors as inputs, autograd with + respect to strided inputs. + + This operation has support for arguments with :ref:`sparse layouts`. + If :attr:`out` is provided its layout will be used. Otherwise, the result + layout will be deduced from that of :attr:`input`. + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat1 = torch.randn(2, 3) + >>> mat2 = torch.randn(3, 3) + >>> torch.mm(mat1, mat2) + tensor([[ 0.4851, 0.5037, -0.3633], + [-0.0760, -3.6705, 2.4784]]) + + .. function:: mm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +def mode( + input: Tensor, + dim: _int = -1, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.mode: + r""" + mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the mode + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`, i.e. a value which appears most often + in that row, and ``indices`` is the index location of each mode value found. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2], + ... [0, 3, 0, 0, 2, 0, 1], + ... [2, 2, 2, 0, 0, 0, 3], + ... [2, 2, 3, 0, 1, 1, 0], + ... [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) + """ + +@overload +def moveaxis(input: Tensor, source: _int, destination: _int) -> Tensor: + r""" + moveaxis(input, source, destination) -> Tensor + + Alias for :func:`torch.movedim`. + + This function is equivalent to NumPy's moveaxis function. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def moveaxis(input: Tensor, source: _size, destination: _size) -> Tensor: + r""" + moveaxis(input, source, destination) -> Tensor + + Alias for :func:`torch.movedim`. + + This function is equivalent to NumPy's moveaxis function. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.moveaxis(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.moveaxis(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.moveaxis(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.moveaxis(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def movedim(input: Tensor, source: _int, destination: _int) -> Tensor: + r""" + movedim(input, source, destination) -> Tensor + + Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` + to the position(s) in :attr:`destination`. + + Other dimensions of :attr:`input` that are not explicitly moved remain in + their original order and appear at the positions not specified in :attr:`destination`. + + Args: + input (Tensor): the input tensor. + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +@overload +def movedim(input: Tensor, source: _size, destination: _size) -> Tensor: + r""" + movedim(input, source, destination) -> Tensor + + Moves the dimension(s) of :attr:`input` at the position(s) in :attr:`source` + to the position(s) in :attr:`destination`. + + Other dimensions of :attr:`input` that are not explicitly moved remain in + their original order and appear at the positions not specified in :attr:`destination`. + + Args: + input (Tensor): the input tensor. + source (int or tuple of ints): Original positions of the dims to move. These must be unique. + destination (int or tuple of ints): Destination positions for each of the original dims. These must also be unique. + + Examples:: + + >>> t = torch.randn(3,2,1) + >>> t + tensor([[[-0.3362], + [-0.8437]], + + [[-0.9627], + [ 0.1727]], + + [[ 0.5173], + [-0.1398]]]) + >>> torch.movedim(t, 1, 0).shape + torch.Size([2, 3, 1]) + >>> torch.movedim(t, 1, 0) + tensor([[[-0.3362], + [-0.9627], + [ 0.5173]], + + [[-0.8437], + [ 0.1727], + [-0.1398]]]) + >>> torch.movedim(t, (1, 2), (0, 1)).shape + torch.Size([2, 1, 3]) + >>> torch.movedim(t, (1, 2), (0, 1)) + tensor([[[-0.3362, -0.9627, 0.5173]], + + [[-0.8437, 0.1727, -0.1398]]]) + """ + +def msort(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + msort(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Sorts the elements of the :attr:`input` tensor along its first dimension + in ascending order by value. + + .. note:: `torch.msort(t)` is equivalent to `torch.sort(t, dim=0)[0]`. + See also :func:`torch.sort`. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.randn(3, 4) + >>> t + tensor([[-0.1321, 0.4370, -1.2631, -1.1289], + [-2.0527, -1.1250, 0.2275, 0.3077], + [-0.0881, -0.1259, -0.5495, 1.0284]]) + >>> torch.msort(t) + tensor([[-2.0527, -1.1250, -1.2631, -1.1289], + [-0.1321, -0.1259, -0.5495, 0.3077], + [-0.0881, 0.4370, 0.2275, 1.0284]]) + """ + +def mul( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mul(input, other, *, out=None) -> Tensor + + Multiplies :attr:`input` by :attr:`other`. + + + .. math:: + \text{out}_i = \text{input}_i \times \text{other}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to multiply input by. + + Keyword args: + out (Tensor, optional): the output tensor. + + Examples:: + + >>> a = torch.randn(3) + >>> a + tensor([ 0.2015, -0.4255, 2.6087]) + >>> torch.mul(a, 100) + tensor([ 20.1494, -42.5491, 260.8663]) + + >>> b = torch.randn(4, 1) + >>> b + tensor([[ 1.1207], + [-0.3137], + [ 0.0700], + [ 0.8378]]) + >>> c = torch.randn(1, 4) + >>> c + tensor([[ 0.5146, 0.1216, -0.5244, 2.2382]]) + >>> torch.mul(b, c) + tensor([[ 0.5767, 0.1363, -0.5877, 2.5083], + [-0.1614, -0.0382, 0.1645, -0.7021], + [ 0.0360, 0.0085, -0.0367, 0.1567], + [ 0.4312, 0.1019, -0.4394, 1.8753]]) + """ + +def multinomial( + input: Tensor, + num_samples: _int | SymInt, + replacement: _bool = False, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + multinomial(input, num_samples, replacement=False, *, generator=None, out=None) -> LongTensor + + Returns a tensor where each row contains :attr:`num_samples` indices sampled + from the multinomial (a stricter definition would be multivariate, + refer to :class:`torch.distributions.multinomial.Multinomial` for more details) + probability distribution located in the corresponding row + of tensor :attr:`input`. + + .. note:: + The rows of :attr:`input` do not need to sum to one (in which case we use + the values as weights), but must be non-negative, finite and have + a non-zero sum. + + Indices are ordered from left to right according to when each was sampled + (first samples are placed in first column). + + If :attr:`input` is a vector, :attr:`out` is a vector of size :attr:`num_samples`. + + If :attr:`input` is a matrix with `m` rows, :attr:`out` is an matrix of shape + :math:`(m \times \text{num\_samples})`. + + If replacement is ``True``, samples are drawn with replacement. + + If not, they are drawn without replacement, which means that when a + sample index is drawn for a row, it cannot be drawn again for that row. + + .. note:: + When drawn without replacement, :attr:`num_samples` must be lower than + number of non-zero elements in :attr:`input` (or the min number of non-zero + elements in each row of :attr:`input` if it is a matrix). + + Args: + input (Tensor): the input tensor containing probabilities + num_samples (int): number of samples to draw + replacement (bool, optional): whether to draw with replacement or not + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights + >>> torch.multinomial(weights, 2) + tensor([1, 2]) + >>> torch.multinomial(weights, 5) # ERROR! + RuntimeError: cannot sample n_sample > prob_dist.size(-1) samples without replacement + >>> torch.multinomial(weights, 4, replacement=True) + tensor([ 2, 1, 1, 1]) + """ + +@overload +def multiply( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + multiply(input, other, *, out=None) + + Alias for :func:`torch.mul`. + """ + +@overload +def multiply(input: Tensor, other: Number | _complex | PySymType) -> Tensor: + r""" + multiply(input, other, *, out=None) + + Alias for :func:`torch.mul`. + """ + +def mv(input: Tensor, vec: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + mv(input, vec, *, out=None) -> Tensor + + Performs a matrix-vector product of the matrix :attr:`input` and the vector + :attr:`vec`. + + If :attr:`input` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of + size :math:`m`, :attr:`out` will be 1-D of size :math:`n`. + + .. note:: This function does not :ref:`broadcast `. + + Args: + input (Tensor): matrix to be multiplied + vec (Tensor): vector to be multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> mat = torch.randn(2, 3) + >>> vec = torch.randn(3) + >>> torch.mv(mat, vec) + tensor([ 1.0404, -0.6361]) + """ + +def mvlgamma( + input: Tensor, + p: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mvlgamma(input, p, *, out=None) -> Tensor + + Alias for :func:`torch.special.multigammaln`. + """ + +def nan_to_num( + input: Tensor, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None) -> Tensor + + Replaces :literal:`NaN`, positive infinity, and negative infinity values in :attr:`input` + with the values specified by :attr:`nan`, :attr:`posinf`, and :attr:`neginf`, respectively. + By default, :literal:`NaN`\ s are replaced with zero, positive infinity is replaced with the + greatest finite value representable by :attr:`input`'s dtype, and negative infinity + is replaced with the least finite value representable by :attr:`input`'s dtype. + + Args: + input (Tensor): the input tensor. + nan (Number, optional): the value to replace :literal:`NaN`\s with. Default is zero. + posinf (Number, optional): if a Number, the value to replace positive infinity values with. + If None, positive infinity values are replaced with the greatest finite value representable by :attr:`input`'s dtype. + Default is None. + neginf (Number, optional): if a Number, the value to replace negative infinity values with. + If None, negative infinity values are replaced with the lowest finite value representable by :attr:`input`'s dtype. + Default is None. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.tensor([float('nan'), float('inf'), -float('inf'), 3.14]) + >>> torch.nan_to_num(x) + tensor([ 0.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0) + tensor([ 2.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) + >>> torch.nan_to_num(x, nan=2.0, posinf=1.0) + tensor([ 2.0000e+00, 1.0000e+00, -3.4028e+38, 3.1400e+00]) + """ + +def nan_to_num_( + input: Tensor, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, +) -> Tensor: + r""" + nan_to_num_(input, nan=0.0, posinf=None, neginf=None) -> Tensor + + In-place version of :func:`torch.nan_to_num` + """ + +def nanmean( + input: Tensor, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + nanmean(input, dim=None, keepdim=False, *, dtype=None, out=None) -> Tensor + + Computes the mean of all `non-NaN` elements along the specified dimensions. + Input must be floating point or complex. + + This function is identical to :func:`torch.mean` when there are no `NaN` values + in the :attr:`input` tensor. In the presence of `NaN`, :func:`torch.mean` will + propagate the `NaN` to the output whereas :func:`torch.nanmean` will ignore the + `NaN` values (`torch.nanmean(a)` is equivalent to `torch.mean(a[~a.isnan()])`). + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor, either of floating point or complex dtype + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + out (Tensor, optional): the output tensor. + + .. seealso:: + + :func:`torch.mean` computes the mean value, propagating `NaN`. + + Example:: + + >>> x = torch.tensor([[torch.nan, 1, 2], [1, 2, 3]]) + >>> x.mean() + tensor(nan) + >>> x.nanmean() + tensor(1.8000) + >>> x.mean(dim=0) + tensor([ nan, 1.5000, 2.5000]) + >>> x.nanmean(dim=0) + tensor([1.0000, 1.5000, 2.5000]) + + # If all elements in the reduced dimensions are NaN then the result is NaN + >>> torch.tensor([torch.nan]).nanmean() + tensor(nan) + """ + +@overload +def nanmedian(input: Tensor) -> Tensor: + r""" + nanmedian(input) -> Tensor + + Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. + When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, + while this function will return the median of the non-``NaN`` elements in :attr:`input`. + If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + + .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values + found in the dimension :attr:`dim`. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has + one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the + median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) + """ + +@overload +def nanmedian( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.nanmedian: + r""" + nanmedian(input) -> Tensor + + Returns the median of the values in :attr:`input`, ignoring ``NaN`` values. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in :attr:`input`. + When :attr:`input` has one or more ``NaN`` values, :func:`torch.median` will always return ``NaN``, + while this function will return the median of the non-``NaN`` elements in :attr:`input`. + If all the elements in :attr:`input` are ``NaN`` it will also return ``NaN``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.tensor([1, float('nan'), 3, 2]) + >>> a.median() + tensor(nan) + >>> a.nanmedian() + tensor(2.) + + .. function:: nanmedian(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` contains the median of each row of :attr:`input` + in the dimension :attr:`dim`, ignoring ``NaN`` values, and ``indices`` contains the index of the median values + found in the dimension :attr:`dim`. + + This function is identical to :func:`torch.median` when there are no ``NaN`` values in a reduced row. When a reduced row has + one or more ``NaN`` values, :func:`torch.median` will always reduce it to ``NaN``, while this function will reduce it to the + median of the non-``NaN`` elements. If all the elements in a reduced row are ``NaN`` then it will be reduced to ``NaN``, too. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out ((Tensor, Tensor), optional): The first tensor will be populated with the median values and the second + tensor, which must have dtype long, with their indices in the dimension + :attr:`dim` of :attr:`input`. + + Example:: + + >>> a = torch.tensor([[2, 3, 1], [float('nan'), 1, float('nan')]]) + >>> a + tensor([[2., 3., 1.], + [nan, 1., nan]]) + >>> a.median(0) + torch.return_types.median(values=tensor([nan, 1., nan]), indices=tensor([1, 1, 1])) + >>> a.nanmedian(0) + torch.return_types.nanmedian(values=tensor([2., 1., 1.]), indices=tensor([0, 1, 0])) + """ + +@overload +def nanquantile( + input: Tensor, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, + computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did + not exist. If all values in a reduced row are ``NaN`` then the quantiles for + that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) + """ + +@overload +def nanquantile( + input: Tensor, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + nanquantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + This is a variant of :func:`torch.quantile` that "ignores" ``NaN`` values, + computing the quantiles :attr:`q` as if ``NaN`` values in :attr:`input` did + not exist. If all values in a reduced row are ``NaN`` then the quantiles for + that reduction will be ``NaN``. See the documentation for :func:`torch.quantile`. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of quantile values in the range [0, 1] + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([float('nan'), 1, 2]) + >>> t.quantile(0.5) + tensor(nan) + >>> t.nanquantile(0.5) + tensor(1.5000) + >>> t = torch.tensor([[float('nan'), float('nan')], [1, 2]]) + >>> t + tensor([[nan, nan], + [1., 2.]]) + >>> t.nanquantile(0.5, dim=0) + tensor([1., 2.]) + >>> t.nanquantile(0.5, dim=1) + tensor([ nan, 1.5000]) + """ + +def nansum( + input: Tensor, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + nansum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements, treating Not a Numbers (NaNs) as zero. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.tensor([1., 2., float('nan'), 4.]) + >>> torch.nansum(a) + tensor(7.) + + .. function:: nansum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`, treating Not a Numbers (NaNs) as zero. + If :attr:`dim` is a list of dimensions, reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> torch.nansum(torch.tensor([1., float("nan")])) + tensor(1.) + >>> a = torch.tensor([[1, 2], [3., float("nan")]]) + >>> torch.nansum(a) + tensor(6.) + >>> torch.nansum(a, dim=0) + tensor([4., 2.]) + >>> torch.nansum(a, dim=1) + tensor([3., 3.]) + """ + +@overload +def narrow( + input: Tensor, + dim: _int, + start: Tensor, + length: _int | SymInt, +) -> Tensor: + r""" + narrow(input, dim, start, length) -> Tensor + + Returns a new tensor that is a narrowed version of :attr:`input` tensor. The + dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The + returned tensor and :attr:`input` tensor share the same underlying storage. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) + """ + +@overload +def narrow( + input: Tensor, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, +) -> Tensor: + r""" + narrow(input, dim, start, length) -> Tensor + + Returns a new tensor that is a narrowed version of :attr:`input` tensor. The + dimension :attr:`dim` is input from :attr:`start` to ``start + length``. The + returned tensor and :attr:`input` tensor share the same underlying storage. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int or Tensor): index of the element to start the narrowed dimension + from. Can be negative, which means indexing from the end of `dim`. If + `Tensor`, it must be an 0-dim integral `Tensor` (bools not allowed) + length (int): length of the narrowed dimension, must be weakly positive + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> torch.narrow(x, -1, torch.tensor(-1), 1) + tensor([[3], + [6], + [9]]) + """ + +def narrow_copy( + input: Tensor, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + narrow_copy(input, dim, start, length, *, out=None) -> Tensor + + Same as :meth:`Tensor.narrow` except this returns a copy rather + than shared storage. This is primarily for sparse tensors, which + do not have a shared-storage narrow method. + + Args: + input (Tensor): the tensor to narrow + dim (int): the dimension along which to narrow + start (int): index of the element to start the narrowed dimension from. Can + be negative, which means indexing from the end of `dim` + length (int): length of the narrowed dimension, must be weakly positive + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> torch.narrow_copy(x, 0, 0, 2) + tensor([[ 1, 2, 3], + [ 4, 5, 6]]) + >>> torch.narrow_copy(x, 1, 1, 2) + tensor([[ 2, 3], + [ 5, 6], + [ 8, 9]]) + >>> s = torch.arange(16).reshape(2, 2, 2, 2).to_sparse(2) + >>> torch.narrow_copy(s, 0, 0, 1) + tensor(indices=tensor([[0, 0], + [0, 1]]), + values=tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]), + size=(1, 2, 2, 2), nnz=2, layout=torch.sparse_coo) + + .. seealso:: + + :func:`torch.narrow` for a non copy variant + """ + +def native_batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + momentum: _float, + eps: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor]: ... +def native_channel_shuffle(input: Tensor, groups: _int | SymInt) -> Tensor: ... +def native_dropout( + input: Tensor, + p: _float, + train: _bool | None, +) -> tuple[Tensor, Tensor]: ... +def native_group_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + N: _int | SymInt, + C: _int | SymInt, + HxW: _int | SymInt, + group: _int, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +def native_layer_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None, + bias: Tensor | None, + eps: _float, +) -> tuple[Tensor, Tensor, Tensor]: ... +@overload +def native_norm( + input: Tensor, + p: Number | _complex | PySymType | None, + dim: _int | _size, + keepdim: _bool, + dtype: _dtype | None, +) -> Tensor: ... +@overload +def native_norm( + input: Tensor, + p: Number | _complex | PySymType = 2, +) -> Tensor: ... +@overload +def ne( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ne(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \neq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) + """ + +@overload +def ne( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ne(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} \neq \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is not equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [True, False]]) + """ + +def neg(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + neg(input, *, out=None) -> Tensor + + Returns a new tensor with the negative of the elements of :attr:`input`. + + .. math:: + \text{out} = -1 \times \text{input} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.neg(a) + tensor([-0.0090, 0.2262, 0.0682, 0.2866, -0.3940]) + """ + +def neg_(input: Tensor) -> Tensor: + r""" + neg_(input) -> Tensor + + In-place version of :func:`torch.neg` + """ + +def negative(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + negative(input, *, out=None) -> Tensor + + Alias for :func:`torch.neg` + """ + +def negative_(input: Tensor) -> Tensor: + r""" + negative_(input) -> Tensor + + In-place version of :func:`torch.negative` + """ + +def nextafter( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + nextafter(input, other, *, out=None) -> Tensor + + Return the next floating-point value after :attr:`input` towards :attr:`other`, elementwise. + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> eps = torch.finfo(torch.float32).eps + >>> torch.nextafter(torch.tensor([1.0, 2.0]), torch.tensor([2.0, 1.0])) == torch.tensor([eps + 1, 2 - eps]) + tensor([True, True]) + """ + +@overload +def nonzero( + input: Tensor, + *, + as_tuple: Literal[False] = False, + out: Tensor | None = None, +) -> Tensor: + r""" + nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + + .. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + + **When** :attr:`as_tuple` **is** ``False`` **(default)**: + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + **When** :attr:`as_tuple` **is** ``True``: + + Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, + each containing the indices (in that dimension) of all non-zero elements of + :attr:`input` . + + If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` + tensors of size :math:`z`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + As a special case, when :attr:`input` has zero dimensions and a nonzero scalar + value, it is treated as a one-dimensional tensor with one element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (LongTensor, optional): the output tensor containing indices + + Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + + Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) + """ + +@overload +def nonzero( + input: Tensor, + *, + as_tuple: Literal[True], +) -> tuple[Tensor, ...]: + r""" + nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors + + .. note:: + :func:`torch.nonzero(..., as_tuple=False) ` (default) returns a + 2-D tensor where each row is the index for a nonzero value. + + :func:`torch.nonzero(..., as_tuple=True) ` returns a tuple of 1-D + index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]`` + gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor + contains nonzero indices for a certain dimension. + + See below for more details on the two behaviors. + + When :attr:`input` is on CUDA, :func:`torch.nonzero() ` causes + host-device synchronization. + + **When** :attr:`as_tuple` **is** ``False`` **(default)**: + + Returns a tensor containing the indices of all non-zero elements of + :attr:`input`. Each row in the result contains the indices of a non-zero + element in :attr:`input`. The result is sorted lexicographically, with + the last index changing the fastest (C-style). + + If :attr:`input` has :math:`n` dimensions, then the resulting indices tensor + :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + **When** :attr:`as_tuple` **is** ``True``: + + Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`, + each containing the indices (in that dimension) of all non-zero elements of + :attr:`input` . + + If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n` + tensors of size :math:`z`, where :math:`z` is the total number of + non-zero elements in the :attr:`input` tensor. + + As a special case, when :attr:`input` has zero dimensions and a nonzero scalar + value, it is treated as a one-dimensional tensor with one element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (LongTensor, optional): the output tensor containing indices + + Returns: + LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output + tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for + each dimension, containing the indices of each nonzero element along that + dimension. + + Example:: + + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) + tensor([[ 0], + [ 1], + [ 2], + [ 4]]) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]])) + tensor([[ 0, 0], + [ 1, 1], + [ 2, 2], + [ 3, 3]]) + >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True) + (tensor([0, 1, 2, 4]),) + >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], + ... [0.0, 0.4, 0.0, 0.0], + ... [0.0, 0.0, 1.2, 0.0], + ... [0.0, 0.0, 0.0,-0.4]]), as_tuple=True) + (tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3])) + >>> torch.nonzero(torch.tensor(5), as_tuple=True) + (tensor([0]),) + """ + +def nonzero_static( + input: Tensor, + *, + size: _int | SymInt, + fill_value: _int = -1, + out: Tensor | None = None, +) -> Tensor: + r""" + nonzero_static(input, *, size, fill_value=-1) -> Tensor + + Returns a 2-D tensor where each row is the index for a non-zero value. + The returned Tensor has the same `torch.dtype` as `torch.nonzero()`. + + Args: + input (Tensor): the input tensor. + + Keyword args: + size (int): the size of non-zero elements expected to be included in the out + tensor. Pad the out tensor with `fill_value` if the `size` is larger + than total number of non-zero elements, truncate out tensor if `size` + is smaller. The size must be a non-negative integer. + fill_value (int, optional): the value to fill the output tensor with when `size` is larger + than the total number of non-zero elements. Default is `-1` to represent + invalid index. + + Example:: + + # Example 1: Padding + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 4 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0], + [ 1, 1], + [ -1, -1]], dtype=torch.int64) + + # Example 2: Truncating + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0]], dtype=torch.int64) + + # Example 3: 0 size + >>> input_tensor = torch.tensor([10]) + >>> static_size = 0 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(0, 1), dtype=torch.int64) + + # Example 4: 0 rank input + >>> input_tensor = torch.tensor(10) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(2, 0), dtype=torch.int64) + """ + +def norm_except_dim(v: Tensor, pow: _int = 2, dim: _int = 0) -> Tensor: ... +@overload +def normal( + mean: Tensor, + std: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: Tensor, + std: _float = 1, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: _float, + std: Tensor, + *, + generator: Generator | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def normal( + mean: _float, + std: _float, + size: Sequence[_int | SymInt], + *, + generator: Generator | None = None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + normal(mean, std, *, generator=None, out=None) -> Tensor + + Returns a tensor of random numbers drawn from separate normal distributions + whose mean and standard deviation are given. + + The :attr:`mean` is a tensor with the mean of + each output element's normal distribution + + The :attr:`std` is a tensor with the standard deviation of + each output element's normal distribution + + The shapes of :attr:`mean` and :attr:`std` don't need to match, but the + total number of elements in each tensor need to be the same. + + .. note:: When the shapes do not match, the shape of :attr:`mean` + is used as the shape for the returned output tensor + + .. note:: When :attr:`std` is a CUDA tensor, this function synchronizes + its device with the CPU. + + Args: + mean (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) + tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, + 8.0505, 8.1408, 9.0563, 10.0566]) + + .. function:: normal(mean=0.0, std, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the means are shared among all drawn + elements. + + Args: + mean (float, optional): the mean for all distributions + std (Tensor): the tensor of per-element standard deviations + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) + tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) + + .. function:: normal(mean, std=1.0, *, out=None) -> Tensor + :noindex: + + Similar to the function above, but the standard deviations are shared among + all drawn elements. + + Args: + mean (Tensor): the tensor of per-element means + std (float, optional): the standard deviation for all distributions + + Keyword args: + out (Tensor, optional): the output tensor + + Example:: + + >>> torch.normal(mean=torch.arange(1., 6.)) + tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) + + .. function:: normal(mean, std, size, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + :noindex: + + Similar to the function above, but the means and standard deviations are shared + among all drawn elements. The resulting tensor has size given by :attr:`size`. + + Args: + mean (float): the mean for all distributions + std (float): the standard deviation for all distributions + size (int...): a sequence of integers defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.normal(2, 3, size=(1, 4)) + tensor([[-1.3987, -1.9544, 3.6048, 0.7909]]) + """ + +@overload +def not_equal( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + not_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ne`. + """ + +@overload +def not_equal( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + not_equal(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.ne`. + """ + +@overload +def nuclear_norm( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def nuclear_norm( + input: Tensor, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def numel(self: Tensor) -> _int: + r""" + numel(input: Tensor) -> int + + Returns the total number of elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(1, 2, 3, 4, 5) + >>> torch.numel(a) + 120 + >>> a = torch.zeros(4,4) + >>> torch.numel(a) + 16 + """ + +@overload +def ones( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +@overload +def ones( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.ones(2, 3) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + + >>> torch.ones(5) + tensor([ 1., 1., 1., 1., 1.]) + """ + +def ones_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + ones_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor filled with the scalar value `1`, with the same size as + :attr:`input`. ``torch.ones_like(input)`` is equivalent to + ``torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.ones_like(input, out=output)`` is equivalent to + ``torch.ones(input.size(), out=output)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword arguments: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> input = torch.empty(2, 3) + >>> torch.ones_like(input) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.]]) + """ + +def orgqr( + input: Tensor, + input2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + orgqr(input, tau) -> Tensor + + Alias for :func:`torch.linalg.householder_product`. + """ + +def ormqr( + input: Tensor, + input2: Tensor, + input3: Tensor, + left: _bool = True, + transpose: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + ormqr(input, tau, other, left=True, transpose=False, *, out=None) -> Tensor + + Computes the matrix-matrix multiplication of a product of Householder matrices with a general matrix. + + Multiplies a :math:`m \times n` matrix `C` (given by :attr:`other`) with a matrix `Q`, + where `Q` is represented using Householder reflectors `(input, tau)`. + See `Representation of Orthogonal or Unitary Matrices`_ for further details. + + If :attr:`left` is `True` then `op(Q)` times `C` is computed, otherwise the result is `C` times `op(Q)`. + When :attr:`left` is `True`, the implicit matrix `Q` has size :math:`m \times m`. + It has size :math:`n \times n` otherwise. + If :attr:`transpose` is `True` then `op` is the conjugate transpose operation, otherwise it's a no-op. + + Supports inputs of float, double, cfloat and cdouble dtypes. + Also supports batched inputs, and, if the input is batched, the output is batched with the same dimensions. + + .. seealso:: + :func:`torch.geqrf` can be used to form the Householder representation `(input, tau)` of matrix `Q` + from the QR decomposition. + + .. note:: + This function supports backward but it is only fast when ``(input, tau)`` do not require gradients + and/or ``tau.size(-1)`` is very small. + `` + + Args: + input (Tensor): tensor of shape `(*, mn, k)` where `*` is zero or more batch dimensions + and `mn` equals to `m` or `n` depending on the :attr:`left`. + tau (Tensor): tensor of shape `(*, min(mn, k))` where `*` is zero or more batch dimensions. + other (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions. + left (bool): controls the order of multiplication. + transpose (bool): controls whether the matrix `Q` is conjugate transposed or not. + + Keyword args: + out (Tensor, optional): the output Tensor. Ignored if `None`. Default: `None`. + + .. _Representation of Orthogonal or Unitary Matrices: + https://www.netlib.org/lapack/lug/node128.html + """ + +def outer( + input: Tensor, + vec2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + outer(input, vec2, *, out=None) -> Tensor + + Outer product of :attr:`input` and :attr:`vec2`. + If :attr:`input` is a vector of size :math:`n` and :attr:`vec2` is a vector of + size :math:`m`, then :attr:`out` must be a matrix of size :math:`(n \times m)`. + + .. note:: This function does not :ref:`broadcast `. + + Args: + input (Tensor): 1-D input vector + vec2 (Tensor): 1-D input vector + + Keyword args: + out (Tensor, optional): optional output matrix + + Example:: + + >>> v1 = torch.arange(1., 5.) + >>> v2 = torch.arange(1., 4.) + >>> torch.outer(v1, v2) + tensor([[ 1., 2., 3.], + [ 2., 4., 6.], + [ 3., 6., 9.], + [ 4., 8., 12.]]) + """ + +def pairwise_distance( + x1: Tensor, + x2: Tensor, + p: _float = 2, + eps: _float = 1e-06, + keepdim: _bool = False, +) -> Tensor: ... +def pdist(input: Tensor, p: _float = 2) -> Tensor: ... +def permute(input: Tensor, dims: _size) -> Tensor: + r""" + permute(input, dims) -> Tensor + + Returns a view of the original tensor :attr:`input` with its dimensions permuted. + + Args: + input (Tensor): the input tensor. + dims (torch.Size, tuple of int or list of int): the desired ordering of dimensions. + + Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> torch.permute(x, (2, 0, 1)).size() + torch.Size([5, 2, 3]) + """ + +def permute_copy( + input: Tensor, + dims: _size, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.permute`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def pinverse(input: Tensor, rcond: _float = 1e-15) -> Tensor: + r""" + pinverse(input, rcond=1e-15) -> Tensor + + Alias for :func:`torch.linalg.pinv` + """ + +def pixel_shuffle(input: Tensor, upscale_factor: _int) -> Tensor: ... +def pixel_unshuffle(input: Tensor, downscale_factor: _int) -> Tensor: ... +def poisson(input: Tensor, generator: Generator | None = None) -> Tensor: + r""" + poisson(input, generator=None) -> Tensor + + Returns a tensor of the same size as :attr:`input` with each element + sampled from a Poisson distribution with rate parameter given by the corresponding + element in :attr:`input` i.e., + + .. math:: + \text{out}_i \sim \text{Poisson}(\text{input}_i) + + :attr:`input` must be non-negative. + + Args: + input (Tensor): the input tensor containing the rates of the Poisson distribution + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + + Example:: + + >>> rates = torch.rand(4, 4) * 5 # rate parameter between 0 and 5 + >>> torch.poisson(rates) + tensor([[9., 1., 3., 5.], + [8., 6., 6., 0.], + [0., 4., 5., 3.], + [2., 1., 4., 2.]]) + """ + +def poisson_nll_loss( + input: Tensor, + target: Tensor, + log_input: _bool, + full: _bool, + eps: _float, + reduction: _int, +) -> Tensor: ... +def polar( + abs: Tensor, + angle: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + polar(abs, angle, *, out=None) -> Tensor + + Constructs a complex tensor whose elements are Cartesian coordinates + corresponding to the polar coordinates with absolute value :attr:`abs` and angle + :attr:`angle`. + + .. math:: + \text{out} = \text{abs} \cdot \cos(\text{angle}) + \text{abs} \cdot \sin(\text{angle}) \cdot j + + .. note:: + `torch.polar` is similar to + `std::polar `_ + and does not compute the polar decomposition + of a complex tensor like Python's `cmath.polar` and SciPy's `linalg.polar` do. + The behavior of this function is undefined if `abs` is negative or NaN, or if `angle` is + infinite. + + + Args: + abs (Tensor): The absolute value the complex tensor. Must be float or double. + angle (Tensor): The angle of the complex tensor. Must be same dtype as + :attr:`abs`. + + Keyword args: + out (Tensor): If the inputs are ``torch.float32``, must be + ``torch.complex64``. If the inputs are ``torch.float64``, must be + ``torch.complex128``. + + Example:: + + >>> import numpy as np + >>> abs = torch.tensor([1, 2], dtype=torch.float64) + >>> angle = torch.tensor([np.pi / 2, 5 * np.pi / 4], dtype=torch.float64) + >>> z = torch.polar(abs, angle) + >>> z + tensor([(0.0000+1.0000j), (-1.4142-1.4142j)], dtype=torch.complex128) + """ + +def polygamma( + n: _int, + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + polygamma(n, input, *, out=None) -> Tensor + + Alias for :func:`torch.special.polygamma`. + """ + +def positive(input: Tensor) -> Tensor: + r""" + positive(input) -> Tensor + + Returns :attr:`input`. + Throws a runtime error if :attr:`input` is a bool tensor. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> t = torch.randn(5) + >>> t + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + >>> torch.positive(t) + tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) + """ + +@overload +def pow( + input: Tensor, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +@overload +def pow( + self: Number | _complex | PySymType, + exponent: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +@overload +def pow( + input: Tensor, + exponent: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + pow(input, exponent, *, out=None) -> Tensor + + Takes the power of each element in :attr:`input` with :attr:`exponent` and + returns a tensor with the result. + + :attr:`exponent` can be either a single ``float`` number or a `Tensor` + with the same number of elements as :attr:`input`. + + When :attr:`exponent` is a scalar value, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ \text{exponent} + + When :attr:`exponent` is a tensor, the operation applied is: + + .. math:: + \text{out}_i = x_i ^ {\text{exponent}_i} + + When :attr:`exponent` is a tensor, the shapes of :attr:`input` + and :attr:`exponent` must be :ref:`broadcastable `. + + Args: + input (Tensor): the input tensor. + exponent (float or tensor): the exponent value + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) + >>> torch.pow(a, 2) + tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) + >>> exp = torch.arange(1., 5.) + + >>> a = torch.arange(1., 5.) + >>> a + tensor([ 1., 2., 3., 4.]) + >>> exp + tensor([ 1., 2., 3., 4.]) + >>> torch.pow(a, exp) + tensor([ 1., 4., 27., 256.]) + + .. function:: pow(self, exponent, *, out=None) -> Tensor + :noindex: + + :attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor. + The returned tensor :attr:`out` is of the same shape as :attr:`exponent` + + The operation applied is: + + .. math:: + \text{out}_i = \text{self} ^ {\text{exponent}_i} + + Args: + self (float): the scalar base value for the power operation + exponent (Tensor): the exponent tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> exp = torch.arange(1., 5.) + >>> base = 2 + >>> torch.pow(base, exp) + tensor([ 2., 4., 8., 16.]) + """ + +def prelu(input: Tensor, weight: Tensor) -> Tensor: ... +@overload +def prod(input: Tensor, *, dtype: _dtype | None = None) -> Tensor: + r""" + prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + + Returns the product of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + + .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the product of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensor having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) + """ + +@overload +def prod( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + prod(input: Tensor, *, dtype: Optional[_dtype]) -> Tensor + + Returns the product of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[-0.8020, 0.5428, -1.5854]]) + >>> torch.prod(a) + tensor(0.6902) + + .. function:: prod(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the product of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensor having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 2) + >>> a + tensor([[ 0.5261, -0.3837], + [ 1.1857, -0.2498], + [-1.1646, 0.0705], + [ 1.1131, -1.0629]]) + >>> torch.prod(a, 1) + tensor([-0.2018, -0.2962, -0.0821, -1.1831]) + """ + +def promote_types(type1: _dtype, type2: _dtype) -> _dtype: + r""" + promote_types(type1, type2) -> dtype + + Returns the :class:`torch.dtype` with the smallest size and scalar kind that is + not smaller nor of lower kind than either `type1` or `type2`. See type promotion + :ref:`documentation ` for more information on the type + promotion logic. + + Args: + type1 (:class:`torch.dtype`) + type2 (:class:`torch.dtype`) + + Example:: + + >>> torch.promote_types(torch.int32, torch.float32) + torch.float32 + >>> torch.promote_types(torch.uint8, torch.long) + torch.long + """ + +def put( + input: Tensor, + index: Tensor, + source: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def q_per_channel_axis(input: Tensor) -> _int: ... +def q_per_channel_scales(input: Tensor) -> Tensor: ... +def q_per_channel_zero_points(input: Tensor) -> Tensor: ... +def q_scale(input: Tensor) -> _float: ... +def q_zero_point(input: Tensor) -> _int: ... +@overload +def quantile( + input: Tensor, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +@overload +def quantile( + input: Tensor, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +def quantize_per_channel( + input: Tensor, + scales: Tensor, + zero_points: Tensor, + axis: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor + + Converts a float tensor to a per-channel quantized tensor with given scales and zero points. + + Arguments: + input (Tensor): float tensor to quantize + scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)`` + zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)`` + axis (int): dimension on which apply per-channel quantization + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor + + Example:: + + >>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]]) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8) + tensor([[-1., 0.], + [ 1., 2.]], size=(2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_channel_affine, + scale=tensor([0.1000, 0.0100], dtype=torch.float64), + zero_point=tensor([10, 0]), axis=0) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr() + tensor([[ 0, 10], + [100, 200]], dtype=torch.uint8) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: _float, + zero_point: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + tensors: tuple[Tensor, ...] | list[Tensor], + scales: Tensor, + zero_points: Tensor, + dtype: _dtype, +) -> tuple[Tensor, ...]: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +def quantize_per_tensor_dynamic( + input: Tensor, + dtype: _dtype, + reduce_range: _bool, +) -> Tensor: + r""" + quantize_per_tensor_dynamic(input, dtype, reduce_range) -> Tensor + + Converts a float tensor to a quantized tensor with scale and zero_point calculated + dynamically based on the input. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8`` + reduce_range (bool): a flag to indicate whether to reduce the range of quantized + data by 1 bit, it's required to avoid instruction overflow for some hardwares + + Returns: + Tensor: A newly (dynamically) quantized tensor + + Example:: + + >>> t = torch.quantize_per_tensor_dynamic(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.quint8, False) + >>> print(t) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.011764705882352941, + zero_point=85) + >>> t.int_repr() + tensor([ 0, 85, 170, 255], dtype=torch.uint8) + """ + +def quantized_batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + mean: Tensor, + var: Tensor, + eps: _float, + output_scale: _float, + output_zero_point: _int, +) -> Tensor: + r""" + quantized_batch_norm(input, weight=None, bias=None, mean, var, eps, output_scale, output_zero_point) -> Tensor + + Applies batch normalization on a 4D (NCHW) quantized tensor. + + .. math:: + + y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta + + Arguments: + input (Tensor): quantized tensor + weight (Tensor): float tensor that corresponds to the gamma, size C + bias (Tensor): float tensor that corresponds to the beta, size C + mean (Tensor): float mean value in batch normalization, size C + var (Tensor): float tensor for variance, size C + eps (float): a value added to the denominator for numerical stability. + output_scale (float): output quantized tensor scale + output_zero_point (int): output quantized tensor zero_point + + Returns: + Tensor: A quantized tensor with batch normalization applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_batch_norm(qx, torch.ones(2), torch.zeros(2), torch.rand(2), torch.rand(2), 0.00001, 0.2, 2) + tensor([[[[-0.2000, -0.2000], + [ 1.6000, -0.2000]], + + [[-0.4000, -0.4000], + [-0.4000, 0.6000]]], + + + [[[-0.2000, -0.2000], + [-0.2000, -0.2000]], + + [[ 0.6000, -0.4000], + [ 0.6000, -0.4000]]]], size=(2, 2, 2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=2) + """ + +def quantized_gru_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> Tensor: ... +def quantized_lstm_cell( + input: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> tuple[Tensor, Tensor]: ... +def quantized_max_pool1d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: + r""" + quantized_max_pool1d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + + Applies a 1D max pooling over an input quantized tensor composed of several input planes. + + Arguments: + input (Tensor): quantized tensor + kernel_size (list of int): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + + Returns: + Tensor: A quantized tensor with max_pool1d applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool1d(qx, [2]) + tensor([[0.0000], + [1.5000]], size=(2, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) + """ + +def quantized_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: + r""" + quantized_max_pool2d(input, kernel_size, stride=[], padding=0, dilation=1, ceil_mode=False) -> Tensor + + Applies a 2D max pooling over an input quantized tensor composed of several input planes. + + Arguments: + input (Tensor): quantized tensor + kernel_size (``list of int``): the size of the sliding window + stride (``list of int``, optional): the stride of the sliding window + padding (``list of int``, optional): padding to be added on both sides, must be >= 0 and <= kernel_size / 2 + dilation (``list of int``, optional): The stride between elements within a sliding window, must be > 0. Default 1 + ceil_mode (bool, optional): If True, will use ceil instead of floor to compute the output shape. + Defaults to False. + + + Returns: + Tensor: A quantized tensor with max_pool2d applied. + + Example:: + + >>> qx = torch.quantize_per_tensor(torch.rand(2, 2, 2, 2), 1.5, 3, torch.quint8) + >>> torch.quantized_max_pool2d(qx, [2,2]) + tensor([[[[1.5000]], + + [[1.5000]]], + + + [[[0.0000]], + + [[0.0000]]]], size=(2, 2, 1, 1), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=1.5, zero_point=3) + """ + +def quantized_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size = (), + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: _bool = False, +) -> Tensor: ... +def quantized_rnn_relu_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> Tensor: ... +def quantized_rnn_tanh_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor, + b_hh: Tensor, + packed_ih: Tensor, + packed_hh: Tensor, + col_offsets_ih: Tensor, + col_offsets_hh: Tensor, + scale_ih: Number | _complex | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> Tensor: ... +def rad2deg(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + rad2deg(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with each of the elements of :attr:`input` + converted from angles in radians to degrees. + + Args: + input (Tensor): the input tensor. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([[3.142, -3.142], [6.283, -6.283], [1.570, -1.570]]) + >>> torch.rad2deg(a) + tensor([[ 180.0233, -180.0233], + [ 359.9894, -359.9894], + [ 89.9544, -89.9544]]) + """ + +def rad2deg_(input: Tensor) -> Tensor: + r""" + rad2deg_(input) -> Tensor + + In-place version of :func:`torch.rad2deg` + """ + +@overload +def rand( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a tensor filled with random numbers from a uniform distribution + on the interval :math:`[0, 1)` + + The shape of the tensor is defined by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.rand(4) + tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) + >>> torch.rand(2, 3) + tensor([[ 0.8237, 0.5781, 0.6879], + [ 0.3816, 0.7249, 0.0998]]) + """ + +@overload +def rand_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def rand_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint( + low: _int, + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + + Returns a tensor filled with random numbers from a normal distribution + with mean `0` and variance `1` (also called the standard normal + distribution). + + .. math:: + \text{out}_{i} \sim \mathcal{N}(0, 1) + + For complex dtypes, the tensor is i.i.d. sampled from a `complex normal distribution`_ with zero mean and + unit variance as + + .. math:: + \text{out}_{i} \sim \mathcal{CN}(0, 1) + + This is equivalent to separately sampling the real :math:`(\operatorname{Re})` and imaginary + :math:`(\operatorname{Im})` part of :math:`\text{out}_i` as + + .. math:: + \operatorname{Re}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}),\quad + \operatorname{Im}(\text{out}_{i}) \sim \mathcal{N}(0, \frac{1}{2}) + + The shape of the tensor is defined by the variable argument :attr:`size`. + + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randn(4) + tensor([-2.1436, 0.9966, 2.3426, -0.6366]) + >>> torch.randn(2, 3) + tensor([[ 1.5954, 2.8929, -1.0923], + [ 1.1719, -0.4709, -0.1996]]) + + .. _complex normal distribution: https://en.wikipedia.org/wiki/Complex_normal_distribution + """ + +@overload +def randn_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randperm( + n: _int | SymInt, + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +@overload +def randperm( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +def range( + start: Number, + end: Number, + step: Number = 1, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1` + with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is + the gap between two values in the tensor. + + .. math:: + \text{out}_{i+1} = \text{out}_i + \text{step}. + + .. warning:: + This function is deprecated and will be removed in a future release because its behavior is inconsistent with + Python's range builtin. Instead, use :func:`torch.arange`, which produces values in [start, end). + + Args: + start (float, optional): the starting value for the set of points. Default: ``0``. + end (float): the ending value for the set of points + step (float, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.range(1, 4) + tensor([ 1., 2., 3., 4.]) + >>> torch.range(1, 4, 0.5) + tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000]) + """ + +def ravel(input: Tensor) -> Tensor: + r""" + ravel(input) -> Tensor + + Return a contiguous flattened tensor. A copy is made only if needed. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.ravel(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + """ + +def real(input: Tensor) -> Tensor: + r""" + real(input) -> Tensor + + Returns a new tensor containing real values of the :attr:`self` tensor. + The returned tensor and :attr:`self` share the same underlying storage. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + """ + +def reciprocal(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + reciprocal(input, *, out=None) -> Tensor + + Returns a new tensor with the reciprocal of the elements of :attr:`input` + + .. math:: + \text{out}_{i} = \frac{1}{\text{input}_{i}} + + .. note:: + Unlike NumPy's reciprocal, torch.reciprocal supports integral inputs. Integral + inputs to reciprocal are automatically :ref:`promoted ` to + the default scalar type. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.4595, -2.1219, -1.4314, 0.7298]) + >>> torch.reciprocal(a) + tensor([-2.1763, -0.4713, -0.6986, 1.3702]) + """ + +def reciprocal_(input: Tensor) -> Tensor: + r""" + reciprocal_(input) -> Tensor + + In-place version of :func:`torch.reciprocal` + """ + +def relu(input: Tensor) -> Tensor: ... +def relu_(input: Tensor) -> Tensor: ... +@overload +def remainder( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +@overload +def remainder(self: Number | _complex | PySymType, other: Tensor) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +@overload +def remainder( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + remainder(input, other, *, out=None) -> Tensor + + Computes + `Python's modulus operation `_ + entrywise. The result has the same sign as the divisor :attr:`other` and its absolute value + is less than that of :attr:`other`. + + It may also be defined in terms of :func:`torch.div` as + + .. code:: python + + torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer and float inputs. + + .. note:: + Complex inputs are not supported. In some cases, it is not mathematically + possible to satisfy the definition of a modulo operation with complex numbers. + See :func:`torch.fmod` for how division by zero is handled. + + .. seealso:: + + :func:`torch.fmod` which implements C++'s `std::fmod `_. + This one is defined in terms of division rounding towards zero. + + Args: + input (Tensor or Scalar): the dividend + other (Tensor or Scalar): the divisor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) + tensor([ 1., 0., 1., 1., 0., 1.]) + >>> torch.remainder(torch.tensor([1, 2, 3, 4, 5]), -1.5) + tensor([ -0.5000, -1.0000, 0.0000, -0.5000, -1.0000 ]) + """ + +def renorm( + input: Tensor, + p: Number | _complex | PySymType, + dim: _int, + maxnorm: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + renorm(input, p, dim, maxnorm, *, out=None) -> Tensor + + Returns a tensor where each sub-tensor of :attr:`input` along dimension + :attr:`dim` is normalized such that the `p`-norm of the sub-tensor is lower + than the value :attr:`maxnorm` + + .. note:: If the norm of a row is lower than `maxnorm`, the row is unchanged + + Args: + input (Tensor): the input tensor. + p (float): the power for the norm computation + dim (int): the dimension to slice over to get the sub-tensors + maxnorm (float): the maximum norm to keep each sub-tensor under + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.ones(3, 3) + >>> x[1].fill_(2) + tensor([ 2., 2., 2.]) + >>> x[2].fill_(3) + tensor([ 3., 3., 3.]) + >>> x + tensor([[ 1., 1., 1.], + [ 2., 2., 2.], + [ 3., 3., 3.]]) + >>> torch.renorm(x, 1, 0, 5) + tensor([[ 1.0000, 1.0000, 1.0000], + [ 1.6667, 1.6667, 1.6667], + [ 1.6667, 1.6667, 1.6667]]) + """ + +@overload +def repeat_interleave( + input: Tensor, + repeats: Tensor, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +@overload +def repeat_interleave( + repeats: Tensor, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +@overload +def repeat_interleave( + input: Tensor, + repeats: _int | SymInt, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, +) -> Tensor: + r""" + repeat_interleave(input, repeats, dim=None, *, output_size=None) -> Tensor + + Repeat elements of a tensor. + + .. warning:: + + This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``. + + Args: + input (Tensor): the input tensor. + repeats (Tensor or int): The number of repetitions for each element. + repeats is broadcasted to fit the shape of the given axis. + dim (int, optional): The dimension along which to repeat values. + By default, use the flattened input array, and return a flat output + array. + + Keyword args: + output_size (int, optional): Total output size for the given axis + ( e.g. sum of repeats). If given, it will avoid stream synchronization + needed to calculate output shape of the tensor. + + Returns: + Tensor: Repeated tensor which has the same shape as input, except along the given axis. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat_interleave(2) + tensor([1, 1, 2, 2, 3, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.repeat_interleave(y, 2) + tensor([1, 1, 2, 2, 3, 3, 4, 4]) + >>> torch.repeat_interleave(y, 3, dim=1) + tensor([[1, 1, 1, 2, 2, 2], + [3, 3, 3, 4, 4, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0) + tensor([[1, 2], + [3, 4], + [3, 4]]) + >>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0, output_size=3) + tensor([[1, 2], + [3, 4], + [3, 4]]) + + If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be + `tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times, + `1` appears `n2` times, `2` appears `n3` times, etc. + + .. function:: repeat_interleave(repeats, *) -> Tensor + :noindex: + + Repeats 0 repeats[0] times, 1 repeats[1] times, 2 repeats[2] times, etc. + + Args: + repeats (Tensor): The number of repetitions for each element. + + Returns: + Tensor: Repeated tensor of size `sum(repeats)`. + + Example:: + + >>> torch.repeat_interleave(torch.tensor([1, 2, 3])) + tensor([0, 1, 1, 2, 2, 2]) + """ + +def reshape(input: Tensor, shape: Sequence[_int | SymInt]) -> Tensor: + r""" + reshape(input, shape) -> Tensor + + Returns a tensor with the same data and number of elements as :attr:`input`, + but with the specified shape. When possible, the returned tensor will be a view + of :attr:`input`. Otherwise, it will be a copy. Contiguous inputs and inputs + with compatible strides can be reshaped without copying, but you should not + depend on the copying vs. viewing behavior. + + See :meth:`torch.Tensor.view` on when it is possible to return a view. + + A single dimension may be -1, in which case it's inferred from the remaining + dimensions and the number of elements in :attr:`input`. + + Args: + input (Tensor): the tensor to be reshaped + shape (tuple of int): the new shape + + Example:: + + >>> a = torch.arange(4.) + >>> torch.reshape(a, (2, 2)) + tensor([[ 0., 1.], + [ 2., 3.]]) + >>> b = torch.tensor([[0, 1], [2, 3]]) + >>> torch.reshape(b, (-1,)) + tensor([ 0, 1, 2, 3]) + """ + +def resize_as_( + input: Tensor, + the_template: Tensor, + *, + memory_format: memory_format | None = None, +) -> Tensor: ... +def resize_as_sparse_(input: Tensor, the_template: Tensor) -> Tensor: ... +def resolve_conj(input: Tensor) -> Tensor: + r""" + resolve_conj(input) -> Tensor + + Returns a new tensor with materialized conjugation if :attr:`input`'s conjugate bit is set to `True`, + else returns :attr:`input`. The output tensor will always have its conjugate bit set to `False`. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> y.is_conj() + True + >>> z = y.resolve_conj() + >>> z + tensor([-1 - 1j, -2 - 2j, 3 + 3j]) + >>> z.is_conj() + False + """ + +def resolve_neg(input: Tensor) -> Tensor: + r""" + resolve_neg(input) -> Tensor + + Returns a new tensor with materialized negation if :attr:`input`'s negative bit is set to `True`, + else returns :attr:`input`. The output tensor will always have its negative bit set to `False`. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) + >>> y = x.conj() + >>> z = y.imag + >>> z.is_neg() + True + >>> out = z.resolve_neg() + >>> out + tensor([-1., -2., 3.]) + >>> out.is_neg() + False + """ + +@overload +def result_type(tensor: Tensor, other: Tensor) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type( + scalar: Number | _complex | PySymType, + tensor: Tensor, +) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type( + tensor: Tensor, + other: Number | _complex | PySymType, +) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +@overload +def result_type( + scalar1: Number | _complex | PySymType, + scalar2: Number | _complex | PySymType, +) -> _dtype: + r""" + result_type(tensor1, tensor2) -> dtype + + Returns the :class:`torch.dtype` that would result from performing an arithmetic + operation on the provided input tensors. See type promotion :ref:`documentation ` + for more information on the type promotion logic. + + Args: + tensor1 (Tensor or Number): an input tensor or number + tensor2 (Tensor or Number): an input tensor or number + + Example:: + + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0) + torch.float32 + >>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1)) + torch.uint8 + """ + +def rms_norm( + input: Tensor, + normalized_shape: Sequence[_int | SymInt], + weight: Tensor | None = None, + eps: _float | None = None, +) -> Tensor: ... +@overload +def rnn_relu( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def rnn_relu( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def rnn_relu_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +@overload +def rnn_tanh( + data: Tensor, + batch_sizes: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, +) -> tuple[Tensor, Tensor]: ... +@overload +def rnn_tanh( + input: Tensor, + hx: Tensor, + params: tuple[Tensor, ...] | list[Tensor], + has_biases: _bool, + num_layers: _int, + dropout: _float, + train: _bool, + bidirectional: _bool, + batch_first: _bool, +) -> tuple[Tensor, Tensor]: ... +def rnn_tanh_cell( + input: Tensor, + hx: Tensor, + w_ih: Tensor, + w_hh: Tensor, + b_ih: Tensor | None = None, + b_hh: Tensor | None = None, +) -> Tensor: ... +def roll( + input: Tensor, + shifts: _int | SymInt | Sequence[_int | SymInt], + dims: _int | _size = (), +) -> Tensor: + r""" + roll(input, shifts, dims=None) -> Tensor + + Roll the tensor :attr:`input` along the given dimension(s). Elements that are + shifted beyond the last position are re-introduced at the first position. If + :attr:`dims` is `None`, the tensor will be flattened before rolling and then + restored to the original shape. + + Args: + input (Tensor): the input tensor. + shifts (int or tuple of ints): The number of places by which the elements + of the tensor are shifted. If shifts is a tuple, dims must be a tuple of + the same size, and each dimension will be rolled by the corresponding + value + dims (int or tuple of ints): Axis along which to roll + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2) + >>> x + tensor([[1, 2], + [3, 4], + [5, 6], + [7, 8]]) + >>> torch.roll(x, 1) + tensor([[8, 1], + [2, 3], + [4, 5], + [6, 7]]) + >>> torch.roll(x, 1, 0) + tensor([[7, 8], + [1, 2], + [3, 4], + [5, 6]]) + >>> torch.roll(x, -1, 0) + tensor([[3, 4], + [5, 6], + [7, 8], + [1, 2]]) + >>> torch.roll(x, shifts=(2, 1), dims=(0, 1)) + tensor([[6, 5], + [8, 7], + [2, 1], + [4, 3]]) + """ + +def rot90(input: Tensor, k: _int = 1, dims: _size = (0, 1)) -> Tensor: + r""" + rot90(input, k=1, dims=(0, 1)) -> Tensor + + Rotate an n-D tensor by 90 degrees in the plane specified by dims axis. + Rotation direction is from the first towards the second axis if k > 0, and from the second towards the first for k < 0. + + Args: + input (Tensor): the input tensor. + k (int): number of times to rotate. Default value is 1 + dims (a list or tuple): axis to rotate. Default value is [0, 1] + + Example:: + + >>> x = torch.arange(4).view(2, 2) + >>> x + tensor([[0, 1], + [2, 3]]) + >>> torch.rot90(x, 1, [0, 1]) + tensor([[1, 3], + [0, 2]]) + + >>> x = torch.arange(8).view(2, 2, 2) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.rot90(x, 1, [1, 2]) + tensor([[[1, 3], + [0, 2]], + + [[5, 7], + [4, 6]]]) + """ + +@overload +def round(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + round(input, *, decimals=0, out=None) -> Tensor + + Rounds elements of :attr:`input` to the nearest integer. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + The return type of output is same as that of input's dtype. + + .. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + + .. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + + Args: + input (Tensor): the input tensor. + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) + """ + +@overload +def round( + input: Tensor, + *, + decimals: _int, + out: Tensor | None = None, +) -> Tensor: + r""" + round(input, *, decimals=0, out=None) -> Tensor + + Rounds elements of :attr:`input` to the nearest integer. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + The return type of output is same as that of input's dtype. + + .. note:: + This function implements the "round half to even" to + break ties when a number is equidistant from two + integers (e.g. `round(2.5)` is 2). + + When the :attr:\`decimals\` argument is specified the + algorithm used is similar to NumPy's `around`. This + algorithm is fast but inexact and it can easily + overflow for low precision dtypes. + Eg. `round(tensor([10000], dtype=torch.float16), decimals=3)` is `inf`. + + .. seealso:: + :func:`torch.ceil`, which rounds up. + :func:`torch.floor`, which rounds down. + :func:`torch.trunc`, which rounds towards zero. + + Args: + input (Tensor): the input tensor. + decimals (int): Number of decimal places to round to (default: 0). + If decimals is negative, it specifies the number of positions + to the left of the decimal point. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> torch.round(torch.tensor((4.7, -2.3, 9.1, -7.7))) + tensor([ 5., -2., 9., -8.]) + + >>> # Values equidistant from two integers are rounded towards the + >>> # nearest even value (zero is treated as even) + >>> torch.round(torch.tensor([-0.5, 0.5, 1.5, 2.5])) + tensor([-0., 0., 2., 2.]) + + >>> # A positive decimals argument rounds to that decimal place + >>> torch.round(torch.tensor([0.1234567]), decimals=3) + tensor([0.1230]) + + >>> # A negative decimals argument rounds to the left of the decimal + >>> torch.round(torch.tensor([1200.1234567]), decimals=-3) + tensor([1000.]) + """ + +@overload +def round_(input: Tensor) -> Tensor: + r""" + round_(input, *, decimals=0) -> Tensor + + In-place version of :func:`torch.round` + """ + +@overload +def round_(input: Tensor, *, decimals: _int) -> Tensor: + r""" + round_(input, *, decimals=0) -> Tensor + + In-place version of :func:`torch.round` + """ + +def row_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def row_stack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + row_stack(tensors, *, out=None) -> Tensor + + Alias of :func:`torch.vstack`. + """ + +def rrelu( + input: Tensor, + lower: Number | _complex | PySymType = 0.125, + upper: Number | _complex | PySymType = 0.3333333333333333, + training: _bool = False, + generator: Generator | None = None, +) -> Tensor: ... +def rrelu_( + input: Tensor, + lower: Number | _complex | PySymType = 0.125, + upper: Number | _complex | PySymType = 0.3333333333333333, + training: _bool = False, + generator: Generator | None = None, +) -> Tensor: ... +def rsqrt(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + rsqrt(input, *, out=None) -> Tensor + + Returns a new tensor with the reciprocal of the square-root of each of + the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \frac{1}{\sqrt{\text{input}_{i}}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.0370, 0.2970, 1.5420, -0.9105]) + >>> torch.rsqrt(a) + tensor([ nan, 1.8351, 0.8053, nan]) + """ + +def rsqrt_(input: Tensor) -> Tensor: + r""" + rsqrt_(input) -> Tensor + + In-place version of :func:`torch.rsqrt` + """ + +@overload +def rsub( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def rsub( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +def saddmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number = 1, + alpha: Number = 1, + out: Tensor | None = None, +) -> Tensor: ... +def scalar_tensor( + s: Number | _complex | PySymType, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + reduce: str, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + *, + reduce: str, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +@overload +def scatter( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +def scatter_add( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter_add(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_add_` + """ + +def scatter_reduce( + input: Tensor, + dim: _int, + index: Tensor, + src: Tensor, + reduce: str, + *, + include_self: _bool = True, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter_reduce(input, dim, index, src, reduce, *, include_self=True) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` + """ + +@overload +def searchsorted( + sorted_sequence: Tensor, + input: Tensor, + *, + out_int32: _bool = False, + right: _bool = False, + side: str | None = None, + sorter: Tensor | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + + Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the + corresponding values in :attr:`values` were inserted before the indices, when sorted, the order + of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. + Return a new tensor with the same size as :attr:`values`. More formally, + the returned index satisfies the following rules: + + .. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + + Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted. PyTorch does not validate this condition when :attr:`sorter` is + not provided, and the behavior is undefined if the sequence is not sorted. + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + + Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) + """ + +@overload +def searchsorted( + sorted_sequence: Tensor, + self: Number | _complex | PySymType, + *, + out_int32: _bool = False, + right: _bool = False, + side: str | None = None, + sorter: Tensor | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + searchsorted(sorted_sequence, values, *, out_int32=False, right=False, side=None, out=None, sorter=None) -> Tensor + + Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the + corresponding values in :attr:`values` were inserted before the indices, when sorted, the order + of the corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved. + Return a new tensor with the same size as :attr:`values`. More formally, + the returned index satisfies the following rules: + + .. list-table:: + :widths: 12 10 78 + :header-rows: 1 + + * - :attr:`sorted_sequence` + - :attr:`right` + - *returned index satisfies* + * - 1-D + - False + - ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]`` + * - 1-D + - True + - ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]`` + * - N-D + - False + - ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]`` + * - N-D + - True + - ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]`` + + Args: + sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost* + dimension unless :attr:`sorter` is provided, in which case the sequence does not + need to be sorted. PyTorch does not validate this condition when :attr:`sorter` is + not provided, and the behavior is undefined if the sequence is not sorted. + values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s). + + Keyword args: + out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise. + Default value is False, i.e. default output data type is torch.int64. + right (bool, optional): if False, return the first suitable location that is found. If True, return the + last such index. If no suitable index found, return 0 for non-numerical value + (eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence` + (one pass the last index of the *innermost* dimension). In other words, if False, + gets the lower bound index for each value in :attr:`values` on the corresponding + *innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper + bound index instead. Default value is False. :attr:`side` does the same and is + preferred. It will error if :attr:`side` is set to "left" while this is True. + side (str, optional): the same as :attr:`right` but preferred. "left" corresponds to False for :attr:`right` + and "right" corresponds to True for :attr:`right`. It will error if this is set to + "left" while :attr:`right` is True. Default value is None. + out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided. + sorter (LongTensor, optional): if provided, a tensor matching the shape of the unsorted + :attr:`sorted_sequence` containing a sequence of indices that sort it in the + ascending order on the innermost dimension + + + Example:: + + >>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]) + >>> sorted_sequence + tensor([[ 1, 3, 5, 7, 9], + [ 2, 4, 6, 8, 10]]) + >>> values = torch.tensor([[3, 6, 9], [3, 6, 9]]) + >>> values + tensor([[3, 6, 9], + [3, 6, 9]]) + >>> torch.searchsorted(sorted_sequence, values) + tensor([[1, 3, 4], + [1, 2, 4]]) + >>> torch.searchsorted(sorted_sequence, values, side='right') + tensor([[2, 3, 5], + [1, 3, 4]]) + + >>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9]) + >>> sorted_sequence_1d + tensor([1, 3, 5, 7, 9]) + >>> torch.searchsorted(sorted_sequence_1d, values) + tensor([[1, 3, 4], + [1, 3, 4]]) + """ + +def segment_reduce( + data: Tensor, + reduce: str, + *, + lengths: Tensor | None = None, + indices: Tensor | None = None, + offsets: Tensor | None = None, + axis: _int = 0, + unsafe: _bool = False, + initial: Number | _complex | PySymType | None = None, +) -> Tensor: + r""" + segment_reduce(data: Tensor, reduce: str, *, lengths: Tensor | None = None, indices: Tensor | None = None, offsets: Tensor | None = None, axis: _int = 0, unsafe: _bool = False, initial: Number | _complex | None = None) -> Tensor # noqa: B950 + + Perform a segment reduction operation on the input tensor along the specified axis. + + Args: + data (Tensor): The input tensor on which the segment reduction operation will be performed. + reduce (str): The type of reduction operation. Supported values are ``sum``, ``mean``, ``max``, ``min``, ``prod``. + + Keyword args: + lengths (Tensor, optional): Length of each segment. Default: ``None``. + offsets (Tensor, optional): Offset of each segment. Default: ``None``. + axis (int, optional): The axis perform reduction. Default: ``0``. + unsafe (bool, optional): Skip validation If `True`. Default: ``False``. + initial (Number, optional): The initial value for the reduction operation. Default: ``None``. + + Example:: + + >>> data = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=torch.float32, device='cuda') + >>> lengths = torch.tensor([2, 1], device='cuda') + >>> torch.segment_reduce(data, 'max', lengths=lengths) + tensor([[ 5., 6., 7., 8.], + [ 9., 10., 11., 12.]], device='cuda:0') + """ + +def select(input: Tensor, dim: _int, index: _int | SymInt) -> Tensor: + r""" + select(input, dim, index) -> Tensor + + Slices the :attr:`input` tensor along the selected dimension at the given index. + This function returns a view of the original tensor with the given dimension removed. + + .. note:: If :attr:`input` is a sparse tensor and returning a view of + the tensor is not possible, a RuntimeError exception is + raised. In this is the case, consider using + :func:`torch.select_copy` function. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension to slice + index (int): the index to select with + + .. note:: + + :meth:`select` is equivalent to slicing. For example, + ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and + ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. + """ + +def select_copy( + input: Tensor, + dim: _int, + index: _int | SymInt, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.select`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def select_scatter( + input: Tensor, + src: Tensor, + dim: _int, + index: _int | SymInt, +) -> Tensor: + r""" + select_scatter(input, src, dim, index) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` at the given index. + This function returns a tensor with fresh storage; it does not create a view. + + + Args: + input (Tensor): the input tensor. + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into. + index (int): the index to select with + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + ``torch.select(input, dim, index)`` + + Example:: + + >>> a = torch.zeros(2, 2) + >>> b = torch.ones(2) + >>> a.select_scatter(b, 0, 0) + tensor([[1., 1.], + [0., 0.]]) + """ + +def selu(input: Tensor) -> Tensor: ... +def selu_(input: Tensor) -> Tensor: ... +def set_flush_denormal(mode: _bool) -> _bool: + r""" + set_flush_denormal(mode) -> bool + + Disables denormal floating numbers on CPU. + + Returns ``True`` if your system supports flushing denormal numbers and it + successfully configures flush denormal mode. :meth:`~torch.set_flush_denormal` + is supported on x86 architectures supporting SSE3 and AArch64 architecture. + + Args: + mode (bool): Controls whether to enable flush denormal mode or not + + Example:: + + >>> torch.set_flush_denormal(True) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor([ 0.], dtype=torch.float64) + >>> torch.set_flush_denormal(False) + True + >>> torch.tensor([1e-323], dtype=torch.float64) + tensor(9.88131e-324 * + [ 1.0000], dtype=torch.float64) + """ + +def set_num_interop_threads(num: _int) -> None: + r""" + set_num_interop_threads(int) + + Sets the number of threads used for interop parallelism + (e.g. in JIT interpreter) on CPU. + + .. warning:: + Can only be called once and before any inter-op parallel work + is started (e.g. JIT execution). + """ + +def set_num_threads(num: _int) -> None: + r""" + set_num_threads(int) + + Sets the number of threads used for intraop parallelism on CPU. + + .. warning:: + To ensure that the correct number of threads is used, set_num_threads + must be called before running eager, JIT or autograd code. + """ + +def sgn(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sgn(input, *, out=None) -> Tensor + + This function is an extension of torch.sign() to complex tensors. + It computes a new tensor whose elements have + the same angles as the corresponding elements of :attr:`input` and + absolute values (i.e. magnitudes) of one for complex tensors and + is equivalent to torch.sign() for non-complex tensors. + + .. math:: + \text{out}_{i} = \begin{cases} + 0 & |\text{{input}}_i| == 0 \\ + \frac{{\text{{input}}_i}}{|{\text{{input}}_i}|} & \text{otherwise} + \end{cases} + + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([3+4j, 7-24j, 0, 1+2j]) + >>> t.sgn() + tensor([0.6000+0.8000j, 0.2800-0.9600j, 0.0000+0.0000j, 0.4472+0.8944j]) + """ + +def sigmoid(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sigmoid(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.expit`. + """ + +def sigmoid_(input: Tensor) -> Tensor: + r""" + sigmoid_(input) -> Tensor + + In-place version of :func:`torch.sigmoid` + """ + +def sign(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sign(input, *, out=None) -> Tensor + + Returns a new tensor with the signs of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \operatorname{sgn}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> a + tensor([ 0.7000, -1.2000, 0.0000, 2.3000]) + >>> torch.sign(a) + tensor([ 1., -1., 0., 1.]) + """ + +def signbit(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + signbit(input, *, out=None) -> Tensor + + Tests if each element of :attr:`input` has its sign bit set or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> torch.signbit(a) + tensor([ False, True, False, False]) + >>> a = torch.tensor([-0.0, 0.0]) + >>> torch.signbit(a) + tensor([ True, False]) + + .. note:: + signbit handles signed zeros, so negative zero (-0) returns True. + """ + +def sin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sin(input, *, out=None) -> Tensor + + Returns a new tensor with the sine of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \sin(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5461, 0.1347, -2.7266, -0.2746]) + >>> torch.sin(a) + tensor([-0.5194, 0.1343, -0.4032, -0.2711]) + """ + +def sin_(input: Tensor) -> Tensor: + r""" + sin_(input) -> Tensor + + In-place version of :func:`torch.sin` + """ + +def sinc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sinc(input, *, out=None) -> Tensor + + Alias for :func:`torch.special.sinc`. + """ + +def sinc_(input: Tensor) -> Tensor: + r""" + sinc_(input) -> Tensor + + In-place version of :func:`torch.sinc` + """ + +def sinh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sinh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic sine of the elements of + :attr:`input`. + + .. math:: + \text{out}_{i} = \sinh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.5380, -0.8632, -0.1265, 0.9399]) + >>> torch.sinh(a) + tensor([ 0.5644, -0.9744, -0.1268, 1.0845]) + """ + +def sinh_(input: Tensor) -> Tensor: + r""" + sinh_(input) -> Tensor + + In-place version of :func:`torch.sinh` + """ + +def slice_copy( + input: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.slice`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def slice_inverse( + input: Tensor, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, +) -> Tensor: ... +def slice_scatter( + input: Tensor, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + slice_scatter(input, src, dim=0, start=None, end=None, step=1) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` at the given + dimension. + This function returns a tensor with fresh storage; it does not create a view. + + + Args: + input (Tensor): the input tensor. + src (Tensor): The tensor to embed into :attr:`input` + dim (int): the dimension to insert the slice into + start (Optional[int]): the start index of where to insert the slice + end (Optional[int]): the end index of where to insert the slice + step (int): the how many elements to skip in + + Example:: + + >>> a = torch.zeros(8, 8) + >>> b = torch.ones(2, 8) + >>> a.slice_scatter(b, start=6) + tensor([[0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [0., 0., 0., 0., 0., 0., 0., 0.], + [1., 1., 1., 1., 1., 1., 1., 1.], + [1., 1., 1., 1., 1., 1., 1., 1.]]) + + >>> b = torch.ones(8, 2) + >>> a.slice_scatter(b, dim=1, start=2, end=6, step=2) + tensor([[0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.], + [0., 0., 1., 0., 1., 0., 0., 0.]]) + """ + +def slogdet( + input: Tensor, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.slogdet: + r""" + slogdet(input) -> (Tensor, Tensor) + + Alias for :func:`torch.linalg.slogdet` + """ + +def smm(input: Tensor, mat2: Tensor) -> Tensor: + r""" + smm(input, mat) -> Tensor + + Performs a matrix multiplication of the sparse matrix :attr:`input` + with the dense matrix :attr:`mat`. + + Args: + input (Tensor): a sparse matrix to be matrix multiplied + mat (Tensor): a dense matrix to be matrix multiplied + """ + +def softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + softmax(input, dim, *, dtype=None) -> Tensor + + Alias for :func:`torch.nn.functional.softmax`. + """ + +@overload +def sort( + input: Tensor, + *, + stable: _bool | None, + dim: _int = -1, + descending: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +@overload +def sort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +def sparse_bsc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSC (Block Compressed Sparse + Column)) ` with specified 2-dimensional blocks at the + given :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in BSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncolblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + index in values and row_indices depending on where the given + column starts. Each successive number in the tensor subtracted + by the number before it denotes the number of elements in a + given column. + row_indices (array_like): Row block coordinates of each block in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial blocks for the tensor. Can be a list, + tuple, NumPy ``ndarray``, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 1, 2] + >>> row_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 1, 2]), + row_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsc) + """ + +def sparse_bsr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSR (Block Compressed Sparse Row)) + ` with specified 2-dimensional blocks at the given + :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix + multiplication operations in BSR format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrowblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + block index in values and col_indices depending on where the + given row block starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + blocks in a given row. + col_indices (array_like): Column block coordinates of each block + in values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize == + values.shape[1:3]``. If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 1, 2] + >>> col_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 1, 2]), + col_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsr) + """ + +def sparse_compressed_tensor( + compressed_indices: Tensor | list, + plain_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_compressed_tensor(compressed_indices, plain_indices, values, size=None, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in Compressed Sparse format - CSR, + CSC, BSR, or BSC - ` with specified values at + the given :attr:`compressed_indices` and :attr:`plain_indices`. Sparse + matrix multiplication operations in Compressed Sparse format are + typically faster than that for sparse tensors in COO format. Make you + have a look at :ref:`the note on the data type of the indices + `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + compressed_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, compressed_dim_size + 1)``. The last element of + each batch is the number of non-zero elements or blocks. This + tensor encodes the index in ``values`` and ``plain_indices`` + depending on where the given compressed dimension (row or + column) starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + elements or blocks in a given compressed dimension. + plain_indices (array_like): Plain dimension (column or row) + coordinates of each element or block in values. (B+1)-dimensional + tensor with the same length as values. + + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types. that + represents a (1+K)-dimensional (for CSR and CSC layouts) or + (1+2+K)-dimensional tensor (for BSR and BSC layouts) where + ``K`` is the number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize[0] == + blocksize[1] == 1`` for CSR and CSC formats. If not provided, + the size will be inferred as the minimum size big enough to + hold all non-zero elements or blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + layout (:class:`torch.layout`, required): the desired layout of + returned tensor: :attr:`torch.sparse_csr`, + :attr:`torch.sparse_csc`, :attr:`torch.sparse_bsr`, or + :attr:`torch.sparse_bsc`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> compressed_indices = [0, 2, 4] + >>> plain_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_compressed_tensor(torch.tensor(compressed_indices, dtype=torch.int64), + ... torch.tensor(plain_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double, layout=torch.sparse_csr) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def sparse_coo_tensor( + indices: Tensor, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, + is_coalesced: _bool | None = None, +) -> Tensor: + r""" + sparse_coo_tensor(indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) -> Tensor + + Constructs a :ref:`sparse tensor in COO(rdinate) format + ` with specified values at the given + :attr:`indices`. + + .. note:: + + This function returns an :ref:`uncoalesced tensor + ` when :attr:`is_coalesced` is + unspecified or ``None``. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + indices (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor` + internally. The indices are the coordinates of the non-zero values in the matrix, and thus + should be two-dimensional where the first dimension is the number of tensor dimensions and + the second dimension is the number of non-zero values. + values (array_like): Initial values for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not + provided the size will be inferred as the minimum size big enough to hold all non-zero + elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if None, infers data type from :attr:`values`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + is_coalesced (bool, optional): When``True``, the caller is + responsible for providing tensor indices that correspond to a + coalesced tensor. If the :attr:`check_invariants` flag is + False, no error will be raised if the prerequisites are not + met and this will lead to silently incorrect results. To force + coalescing please use :meth:`coalesce` on the resulting + Tensor. + Default: None: except for trivial cases (e.g. nnz < 2) the + resulting Tensor has is_coalesced set to ``False```. + + Example:: + + >>> i = torch.tensor([[0, 1, 1], + ... [2, 0, 2]]) + >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) + >>> torch.sparse_coo_tensor(i, v, [2, 4]) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 4), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v) # Shape inference + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 3), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v, [2, 4], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, + layout=torch.sparse_coo) + + # Create an empty sparse tensor with the following invariants: + # 1. sparse_dim + dense_dim = len(SparseTensor.shape) + # 2. SparseTensor._indices().shape = (sparse_dim, nnz) + # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) + # + # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and + # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0,)), + size=(1,), nnz=0, layout=torch.sparse_coo) + + # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and + # sparse_dim = 1 + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0, 2)), + size=(1, 2), nnz=0, layout=torch.sparse_coo) + + .. _torch.sparse: https://pytorch.org/docs/stable/sparse.html + """ + +def sparse_csc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSC (Compressed Sparse Column) + ` with specified values at the given + :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in CSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncols + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and row_indices depending on where the given column + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + column. + row_indices (array_like): Row coordinates of each element in + values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 2, 4] + >>> row_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 2, 4]), + row_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csc) + """ + +def sparse_csr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSR (Compressed Sparse Row) ` with specified + values at the given :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix multiplication operations + in CSR format are typically faster than that for sparse tensors in COO format. Make you have a look + at :ref:`the note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrows + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and col_indices depending on where the given row + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + row. + col_indices (array_like): Column coordinates of each element in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 2, 4] + >>> col_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def split_copy( + input: Tensor, + split_size: _int | SymInt, + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def split_with_sizes( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: ... +def split_with_sizes_copy( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split_with_sizes`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def spmm(input: Tensor, mat2: Tensor) -> Tensor: ... +def sqrt(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sqrt(input, *, out=None) -> Tensor + + Returns a new tensor with the square-root of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.sqrt(a) + tensor([ nan, 1.0112, 0.2883, 0.6933]) + """ + +def sqrt_(input: Tensor) -> Tensor: + r""" + sqrt_(input) -> Tensor + + In-place version of :func:`torch.sqrt` + """ + +def square(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + square(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the square of the elements of :attr:`input`. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.square(a) + tensor([ 4.3077, 1.0457, 0.0069, 0.2310]) + """ + +def square_(input: Tensor) -> Tensor: + r""" + square_(input) -> Tensor + + In-place version of :func:`torch.square` + """ + +@overload +def squeeze(input: Tensor) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze(input: Tensor, dim: _int) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze(input: Tensor, dim: _size) -> Tensor: + r""" + squeeze(input: Tensor, dim: Optional[Union[int, List[int]]]) -> Tensor + + Returns a tensor with all specified dimensions of :attr:`input` of size `1` removed. + + For example, if `input` is of shape: + :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `input.squeeze()` + will be of shape: :math:`(A \times B \times C \times D)`. + + When :attr:`dim` is given, a squeeze operation is done only in the given + dimension(s). If `input` is of shape: :math:`(A \times 1 \times B)`, + ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` + will squeeze the tensor to the shape :math:`(A \times B)`. + + .. note:: The returned tensor shares the storage with the input tensor, + so changing the contents of one will change the contents of the other. + + .. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)` + will also remove the batch dimension, which can lead to unexpected + errors. Consider specifying only the dims you wish to be squeezed. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): if given, the input will be squeezed + only in the specified dimensions. + + .. versionchanged:: 2.0 + :attr:`dim` now accepts tuples of dimensions. + + Example:: + + >>> x = torch.zeros(2, 1, 2, 1, 2) + >>> x.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x) + >>> y.size() + torch.Size([2, 2, 2]) + >>> y = torch.squeeze(x, 0) + >>> y.size() + torch.Size([2, 1, 2, 1, 2]) + >>> y = torch.squeeze(x, 1) + >>> y.size() + torch.Size([2, 2, 1, 2]) + >>> y = torch.squeeze(x, (1, 2, 3)) + torch.Size([2, 2, 2]) + """ + +@overload +def squeeze_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def squeeze_copy( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def squeeze_copy( + input: Tensor, + dim: _size, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.squeeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def sspaddmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def sspaddmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +@overload +def sspaddmm( + beta: Number | _complex | PySymType, + self: Tensor, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + sspaddmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor + + Matrix multiplies a sparse tensor :attr:`mat1` with a dense tensor + :attr:`mat2`, then adds the sparse tensor :attr:`input` to the result. + + Note: This function is equivalent to :func:`torch.addmm`, except + :attr:`input` and :attr:`mat1` are sparse. + + Args: + input (Tensor): a sparse matrix to be added + mat1 (Tensor): a sparse matrix to be matrix multiplied + mat2 (Tensor): a dense matrix to be matrix multiplied + + Keyword args: + beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) + alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) + out (Tensor, optional): the output tensor. + """ + +def stack( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + stack(tensors, dim=0, *, out=None) -> Tensor + + Concatenates a sequence of tensors along a new dimension. + + All tensors need to be of the same size. + + .. seealso:: + + :func:`torch.cat` concatenates the given sequence along an existing dimension. + + Arguments: + tensors (sequence of Tensors): sequence of tensors to concatenate + dim (int, optional): dimension to insert. Has to be between 0 and the number + of dimensions of concatenated tensors (inclusive). Default: 0 + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]) + >>> torch.stack((x, x)) # same as torch.stack((x, x), dim=0) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]], + + [[ 0.3367, 0.1288, 0.2345], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x)).size() + torch.Size([2, 2, 3]) + >>> torch.stack((x, x), dim=1) + tensor([[[ 0.3367, 0.1288, 0.2345], + [ 0.3367, 0.1288, 0.2345]], + + [[ 0.2303, -1.1229, -0.1863], + [ 0.2303, -1.1229, -0.1863]]]) + >>> torch.stack((x, x), dim=2) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + >>> torch.stack((x, x), dim=-1) + tensor([[[ 0.3367, 0.3367], + [ 0.1288, 0.1288], + [ 0.2345, 0.2345]], + + [[ 0.2303, 0.2303], + [-1.1229, -1.1229], + [-0.1863, -0.1863]]]) + """ + +@overload +def std( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std(input: Tensor, unbiased: _bool = True) -> Tensor: + r""" + std(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the standard deviation over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std(a, dim=1, keepdim=True) + tensor([[1.0311], + [0.7477], + [1.2204], + [0.9087]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def std_mean( + input: Tensor, + unbiased: _bool = True, +) -> tuple[Tensor, Tensor]: + r""" + std_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the standard deviation and mean over the dimensions specified by + :attr:`dim`. :attr:`dim` can be a single dimension, list of dimensions, or + ``None`` to reduce over all dimensions. + + The standard deviation (:math:`\sigma`) is calculated as + + .. math:: \sigma = \sqrt{\frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2} + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (std, mean) containing the standard deviation and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.std_mean(a, dim=0, keepdim=True) + (tensor([[1.2620, 1.0028, 1.0957, 0.6038]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def sub( + input: Tensor | Number | _complex, + other: Tensor | Number | _complex, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def sub( + self: Tensor, + alpha: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def sub( + self: Tensor, + alpha: Number | _complex | PySymType, + other: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + sub(input, other, *, alpha=1, out=None) -> Tensor + + Subtracts :attr:`other`, scaled by :attr:`alpha`, from :attr:`input`. + + .. math:: + \text{{out}}_i = \text{{input}}_i - \text{{alpha}} \times \text{{other}}_i + + + Supports :ref:`broadcasting to a common shape `, + :ref:`type promotion `, and integer, float, and complex inputs. + + Args: + input (Tensor): the input tensor. + other (Tensor or Number): the tensor or number to subtract from :attr:`input`. + + Keyword args: + alpha (Number): the multiplier for :attr:`other`. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor((1, 2)) + >>> b = torch.tensor((0, 1)) + >>> torch.sub(a, b, alpha=2) + tensor([1, 0]) + """ + +@overload +def subtract( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + subtract(input, other, *, alpha=1, out=None) -> Tensor + + Alias for :func:`torch.sub`. + """ + +@overload +def subtract( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: + r""" + subtract(input, other, *, alpha=1, out=None) -> Tensor + + Alias for :func:`torch.sub`. + """ + +@overload +def sum(input: Tensor, *, dtype: _dtype | None = None) -> Tensor: + r""" + sum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + .. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + + .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) + """ + +@overload +def sum( + input: Tensor, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + r""" + sum(input, *, dtype=None) -> Tensor + + Returns the sum of all elements in the :attr:`input` tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + .. note:: Use the `dtype` argument if you need the result in a specific tensor type. + Otherwise, the result type may be automatically promoted (e.g., from `torch.int32` to `torch.int64`). + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.1133, -0.9567, 0.2958]]) + >>> torch.sum(a) + tensor(-0.5475) + + .. function:: sum(input, dim, keepdim=False, *, dtype=None) -> Tensor + :noindex: + + Returns the sum of each row of the :attr:`input` tensor in the given + dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + If specified, the input tensor is casted to :attr:`dtype` before the operation + is performed. This is useful for preventing data type overflows. Default: None. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], + [-0.2993, 0.9138, 0.9337, -1.6864], + [ 0.1132, 0.7892, -0.1003, 0.5688], + [ 0.3637, -0.9906, -0.4752, -1.5197]]) + >>> torch.sum(a, 1) + tensor([-0.4598, -0.1381, 1.3708, -2.6217]) + >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) + >>> torch.sum(b, (2, 1)) + tensor([ 435., 1335., 2235., 3135.]) + """ + +def svd( + input: Tensor, + some: _bool = True, + compute_uv: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.svd: + r""" + svd(input, some=True, compute_uv=True, *, out=None) -> (Tensor, Tensor, Tensor) + + Computes the singular value decomposition of either a matrix or batch of + matrices :attr:`input`. The singular value decomposition is represented as a + namedtuple `(U, S, V)`, such that :attr:`input` :math:`= U \text{diag}(S) V^{\text{H}}`. + where :math:`V^{\text{H}}` is the transpose of `V` for real inputs, + and the conjugate transpose of `V` for complex inputs. + If :attr:`input` is a batch of matrices, then `U`, `S`, and `V` are also + batched with the same batch dimensions as :attr:`input`. + + If :attr:`some` is `True` (default), the method returns the reduced singular + value decomposition. In this case, if the last two dimensions of :attr:`input` are + `m` and `n`, then the returned `U` and `V` matrices will contain only + `min(n, m)` orthonormal columns. + + If :attr:`compute_uv` is `False`, the returned `U` and `V` will be + zero-filled matrices of shape `(m, m)` and `(n, n)` + respectively, and the same device as :attr:`input`. The argument :attr:`some` + has no effect when :attr:`compute_uv` is `False`. + + Supports :attr:`input` of float, double, cfloat and cdouble data types. + The dtypes of `U` and `V` are the same as :attr:`input`'s. `S` will + always be real-valued, even if :attr:`input` is complex. + + .. warning:: + + :func:`torch.svd` is deprecated in favor of :func:`torch.linalg.svd` + and will be removed in a future PyTorch release. + + ``U, S, V = torch.svd(A, some=some, compute_uv=True)`` (default) should be replaced with + + .. code:: python + + U, S, Vh = torch.linalg.svd(A, full_matrices=not some) + V = Vh.mH + + ``_, S, _ = torch.svd(A, some=some, compute_uv=False)`` should be replaced with + + .. code:: python + + S = torch.linalg.svdvals(A) + + .. note:: Differences with :func:`torch.linalg.svd`: + + * :attr:`some` is the opposite of + :func:`torch.linalg.svd`'s :attr:`full_matrices`. Note that + default value for both is `True`, so the default behavior is + effectively the opposite. + * :func:`torch.svd` returns `V`, whereas :func:`torch.linalg.svd` returns + `Vh`, that is, :math:`V^{\text{H}}`. + * If :attr:`compute_uv` is `False`, :func:`torch.svd` returns zero-filled + tensors for `U` and `Vh`, whereas :func:`torch.linalg.svd` returns + empty tensors. + + .. note:: The singular values are returned in descending order. If :attr:`input` is a batch of matrices, + then the singular values of each matrix in the batch are returned in descending order. + + .. note:: The `S` tensor can only be used to compute gradients if :attr:`compute_uv` is `True`. + + .. note:: When :attr:`some` is `False`, the gradients on `U[..., :, min(m, n):]` + and `V[..., :, min(m, n):]` will be ignored in the backward pass, as those vectors + can be arbitrary bases of the corresponding subspaces. + + .. note:: The implementation of :func:`torch.linalg.svd` on CPU uses LAPACK's routine `?gesdd` + (a divide-and-conquer algorithm) instead of `?gesvd` for speed. Analogously, + on GPU, it uses cuSOLVER's routines `gesvdj` and `gesvdjBatched`. + + .. note:: The returned `U` will not be contiguous. The matrix (or batch of matrices) will + be represented as a column-major matrix (i.e. Fortran-contiguous). + + .. warning:: The gradients with respect to `U` and `V` will only be finite when the input does not + have zero nor repeated singular values. + + .. warning:: If the distance between any two singular values is close to zero, the gradients with respect to + `U` and `V` will be numerically unstable, as they depends on + :math:`\frac{1}{\min_{i \neq j} \sigma_i^2 - \sigma_j^2}`. The same happens when the matrix + has small singular values, as these gradients also depend on `S^{-1}`. + + .. warning:: For complex-valued :attr:`input` the singular value decomposition is not unique, + as `U` and `V` may be multiplied by an arbitrary phase factor :math:`e^{i \phi}` on every column. + The same happens when :attr:`input` has repeated singular values, where one may multiply + the columns of the spanning subspace in `U` and `V` by a rotation matrix + and `the resulting vectors will span the same subspace`_. + Different platforms, like NumPy, or inputs on different device types, + may produce different `U` and `V` tensors. + + Args: + input (Tensor): the input tensor of size `(*, m, n)` where `*` is zero or more + batch dimensions consisting of `(m, n)` matrices. + some (bool, optional): controls whether to compute the reduced or full decomposition, and + consequently, the shape of returned `U` and `V`. Default: `True`. + compute_uv (bool, optional): controls whether to compute `U` and `V`. Default: `True`. + + Keyword args: + out (tuple, optional): the output tuple of tensors + + Example:: + + >>> a = torch.randn(5, 3) + >>> a + tensor([[ 0.2364, -0.7752, 0.6372], + [ 1.7201, 0.7394, -0.0504], + [-0.3371, -1.0584, 0.5296], + [ 0.3550, -0.4022, 1.5569], + [ 0.2445, -0.0158, 1.1414]]) + >>> u, s, v = torch.svd(a) + >>> u + tensor([[ 0.4027, 0.0287, 0.5434], + [-0.1946, 0.8833, 0.3679], + [ 0.4296, -0.2890, 0.5261], + [ 0.6604, 0.2717, -0.2618], + [ 0.4234, 0.2481, -0.4733]]) + >>> s + tensor([2.3289, 2.0315, 0.7806]) + >>> v + tensor([[-0.0199, 0.8766, 0.4809], + [-0.5080, 0.4054, -0.7600], + [ 0.8611, 0.2594, -0.4373]]) + >>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t())) + tensor(8.6531e-07) + >>> a_big = torch.randn(7, 5, 3) + >>> u, s, v = torch.svd(a_big) + >>> torch.dist(a_big, torch.matmul(torch.matmul(u, torch.diag_embed(s)), v.mT)) + tensor(2.6503e-06) + + .. _the resulting vectors will span the same subspace: + (https://en.wikipedia.org/wiki/Singular_value_decomposition#Singular_values,_singular_vectors,_and_their_relation_to_the_SVD) + """ + +def swapaxes(input: Tensor, axis0: _int, axis1: _int) -> Tensor: + r""" + swapaxes(input, axis0, axis1) -> Tensor + + Alias for :func:`torch.transpose`. + + This function is equivalent to NumPy's swapaxes function. + + Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapaxes(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) + """ + +def swapdims(input: Tensor, dim0: _int, dim1: _int) -> Tensor: + r""" + swapdims(input, dim0, dim1) -> Tensor + + Alias for :func:`torch.transpose`. + + This function is equivalent to NumPy's swapaxes function. + + Examples:: + + >>> x = torch.tensor([[[0,1],[2,3]],[[4,5],[6,7]]]) + >>> x + tensor([[[0, 1], + [2, 3]], + + [[4, 5], + [6, 7]]]) + >>> torch.swapdims(x, 0, 1) + tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + >>> torch.swapdims(x, 0, 2) + tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) + """ + +def sym_constrain_range( + size: Number | _complex | PySymType, + *, + min: _int | None = None, + max: _int | None = None, +) -> None: ... +def sym_constrain_range_for_size( + size: Number | _complex | PySymType, + *, + min: _int | None = None, + max: _int | None = None, +) -> None: ... +def t(input: Tensor) -> Tensor: + r""" + t(input) -> Tensor + + Expects :attr:`input` to be <= 2-D tensor and transposes dimensions 0 + and 1. + + 0-D and 1-D tensors are returned as is. When input is a 2-D tensor this + is equivalent to ``transpose(input, 0, 1)``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x = torch.randn(()) + >>> x + tensor(0.1995) + >>> torch.t(x) + tensor(0.1995) + >>> x = torch.randn(3) + >>> x + tensor([ 2.4320, -0.4608, 0.7702]) + >>> torch.t(x) + tensor([ 2.4320, -0.4608, 0.7702]) + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 0.4875, 0.9158, -0.5872], + [ 0.3938, -0.6929, 0.6932]]) + >>> torch.t(x) + tensor([[ 0.4875, 0.3938], + [ 0.9158, -0.6929], + [-0.5872, 0.6932]]) + + See also :func:`torch.transpose`. + """ + +def t_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.t`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def take( + input: Tensor, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + take(input, index) -> Tensor + + Returns a new tensor with the elements of :attr:`input` at the given indices. + The input tensor is treated as if it were viewed as a 1-D tensor. The result + takes the same shape as the indices. + + Args: + input (Tensor): the input tensor. + index (LongTensor): the indices into tensor + + Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> torch.take(src, torch.tensor([0, 2, 5])) + tensor([ 4, 5, 8]) + """ + +def take_along_dim( + input: Tensor, + indices: Tensor, + dim: _int | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + take_along_dim(input, indices, dim=None, *, out=None) -> Tensor + + Selects values from :attr:`input` at the 1-dimensional indices from :attr:`indices` along the given :attr:`dim`. + + If :attr:`dim` is None, the input array is treated as if it has been flattened to 1d. + + Functions that return indices along a dimension, like :func:`torch.argmax` and :func:`torch.argsort`, + are designed to work with this function. See the examples below. + + .. note:: + This function is similar to NumPy's `take_along_axis`. + See also :func:`torch.gather`. + + Args: + input (Tensor): the input tensor. + indices (LongTensor): the indices into :attr:`input`. Must have long dtype. + dim (int, optional): dimension to select along. Default: `None`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([[10, 30, 20], [60, 40, 50]]) + >>> max_idx = torch.argmax(t) + >>> torch.take_along_dim(t, max_idx) + tensor([60]) + >>> sorted_idx = torch.argsort(t, dim=1) + >>> torch.take_along_dim(t, sorted_idx, dim=1) + tensor([[10, 20, 30], + [40, 50, 60]]) + """ + +def tan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + tan(input, *, out=None) -> Tensor + + Returns a new tensor with the tangent of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \tan(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.2027, -1.7687, 0.4412, -1.3856]) + >>> torch.tan(a) + tensor([-2.5930, 4.9859, 0.4722, -5.3366]) + """ + +def tan_(input: Tensor) -> Tensor: + r""" + tan_(input) -> Tensor + + In-place version of :func:`torch.tan` + """ + +def tanh(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + tanh(input, *, out=None) -> Tensor + + Returns a new tensor with the hyperbolic tangent of the elements + of :attr:`input`. + + .. math:: + \text{out}_{i} = \tanh(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.8986, -0.7279, 1.1745, 0.2611]) + >>> torch.tanh(a) + tensor([ 0.7156, -0.6218, 0.8257, 0.2553]) + """ + +def tanh_(input: Tensor) -> Tensor: + r""" + tanh_(input) -> Tensor + + In-place version of :func:`torch.tanh` + """ + +def tensor( + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Constructs a tensor with no autograd history (also known as a "leaf tensor", see :doc:`/notes/autograd`) by copying :attr:`data`. + + .. warning:: + + When working with tensors prefer using :func:`torch.Tensor.clone`, + :func:`torch.Tensor.detach`, and :func:`torch.Tensor.requires_grad_` for + readability. Letting `t` be a tensor, ``torch.tensor(t)`` is equivalent to + ``t.detach().clone()``, and ``torch.tensor(t, requires_grad=True)`` + is equivalent to ``t.detach().clone().requires_grad_(True)``. + + .. seealso:: + + :func:`torch.as_tensor` preserves autograd history and avoids copies where possible. + :func:`torch.from_numpy` creates a tensor that shares storage with a NumPy array. + + Args: + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + + Example:: + + >>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) + tensor([[ 0.1000, 1.2000], + [ 2.2000, 3.1000], + [ 4.9000, 5.2000]]) + + >>> torch.tensor([0, 1]) # Type inference on data + tensor([ 0, 1]) + + >>> torch.tensor([[0.11111, 0.222222, 0.3333333]], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) # creates a double tensor on a CUDA device + tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0') + + >>> torch.tensor(3.14159) # Create a zero-dimensional (scalar) tensor + tensor(3.1416) + + >>> torch.tensor([]) # Create an empty tensor (of size (0,)) + tensor([]) + """ + +@overload +def tensor_split( + input: Tensor, + tensor_indices_or_sections: Tensor, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +@overload +def tensor_split( + input: Tensor, + sections: _int | SymInt, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +@overload +def tensor_split( + input: Tensor, + indices: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + tensor_split(input, indices_or_sections, dim=0) -> List of Tensors + + Splits a tensor into multiple sub-tensors, all of which are views of :attr:`input`, + along dimension :attr:`dim` according to the indices or number of sections specified + by :attr:`indices_or_sections`. This function is based on NumPy's + :func:`numpy.array_split`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + dim (int, optional): dimension along which to split the tensor. Default: ``0`` + + Example:: + + >>> x = torch.arange(8) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7])) + + >>> x = torch.arange(7) + >>> torch.tensor_split(x, 3) + (tensor([0, 1, 2]), tensor([3, 4]), tensor([5, 6])) + >>> torch.tensor_split(x, (1, 6)) + (tensor([0]), tensor([1, 2, 3, 4, 5]), tensor([6])) + + >>> x = torch.arange(14).reshape(2, 7) + >>> x + tensor([[ 0, 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12, 13]]) + >>> torch.tensor_split(x, 3, dim=1) + (tensor([[0, 1, 2], + [7, 8, 9]]), + tensor([[ 3, 4], + [10, 11]]), + tensor([[ 5, 6], + [12, 13]])) + >>> torch.tensor_split(x, (1, 6), dim=1) + (tensor([[0], + [7]]), + tensor([[ 1, 2, 3, 4, 5], + [ 8, 9, 10, 11, 12]]), + tensor([[ 6], + [13]])) + """ + +def threshold( + input: Tensor, + threshold: Number | _complex | PySymType, + value: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +def threshold_( + input: Tensor, + threshold: Number | _complex | PySymType, + value: Number | _complex | PySymType, +) -> Tensor: ... +def tile(input: Tensor, dims: Sequence[_int | SymInt]) -> Tensor: + r""" + tile(input, dims) -> Tensor + + Constructs a tensor by repeating the elements of :attr:`input`. + The :attr:`dims` argument specifies the number of repetitions + in each dimension. + + If :attr:`dims` specifies fewer dimensions than :attr:`input` has, then + ones are prepended to :attr:`dims` until all dimensions are specified. + For example, if :attr:`input` has shape (8, 6, 4, 2) and :attr:`dims` + is (2, 2), then :attr:`dims` is treated as (1, 1, 2, 2). + + Analogously, if :attr:`input` has fewer dimensions than :attr:`dims` + specifies, then :attr:`input` is treated as if it were unsqueezed at + dimension zero until it has as many dimensions as :attr:`dims` specifies. + For example, if :attr:`input` has shape (4, 2) and :attr:`dims` + is (3, 3, 2, 2), then :attr:`input` is treated as if it had the + shape (1, 1, 4, 2). + + .. note:: + + This function is similar to NumPy's tile function. + + Args: + input (Tensor): the tensor whose elements to repeat. + dims (tuple): the number of repetitions per dimension. + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.tile((2,)) + tensor([1, 2, 3, 1, 2, 3]) + >>> y = torch.tensor([[1, 2], [3, 4]]) + >>> torch.tile(y, (2, 2)) + tensor([[1, 2, 1, 2], + [3, 4, 3, 4], + [1, 2, 1, 2], + [3, 4, 3, 4]]) + """ + +def topk( + input: Tensor, + k: _int | SymInt, + dim: _int = -1, + largest: _bool = True, + sorted: _bool = True, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.topk: + r""" + topk(input, k, dim=None, largest=True, sorted=True, *, out=None) -> (Tensor, LongTensor) + + Returns the :attr:`k` largest elements of the given :attr:`input` tensor along + a given dimension. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`largest` is ``False`` then the `k` smallest elements are returned. + + A namedtuple of `(values, indices)` is returned with the `values` and + `indices` of the largest `k` elements of each row of the `input` tensor in the + given dimension `dim`. + + The boolean option :attr:`sorted` if ``True``, will make sure that the returned + `k` elements are themselves sorted + + .. note:: + When using `torch.topk`, the indices of tied elements are not guaranteed to be stable + and may vary across different invocations. + + Args: + input (Tensor): the input tensor. + k (int): the k in "top-k" + dim (int, optional): the dimension to sort along + largest (bool, optional): controls whether to return largest or + smallest elements + sorted (bool, optional): controls whether to return the elements + in sorted order + + Keyword args: + out (tuple, optional): the output tuple of (Tensor, LongTensor) that can be + optionally given to be used as output buffers + + Example:: + + >>> x = torch.arange(1., 6.) + >>> x + tensor([ 1., 2., 3., 4., 5.]) + >>> torch.topk(x, 3) + torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2])) + """ + +def trace(input: Tensor) -> Tensor: + r""" + trace(input) -> Tensor + + Returns the sum of the elements of the diagonal of the input 2-D matrix. + + Example:: + + >>> x = torch.arange(1., 10.).view(3, 3) + >>> x + tensor([[ 1., 2., 3.], + [ 4., 5., 6.], + [ 7., 8., 9.]]) + >>> torch.trace(x) + tensor(15.) + """ + +def transpose(input: Tensor, dim0: _int, dim1: _int) -> Tensor: + r""" + transpose(input, dim0, dim1) -> Tensor + + Returns a tensor that is a transposed version of :attr:`input`. + The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. + + If :attr:`input` is a strided tensor then the resulting :attr:`out` + tensor shares its underlying storage with the :attr:`input` tensor, so + changing the content of one would change the content of the other. + + If :attr:`input` is a :ref:`sparse tensor ` then the + resulting :attr:`out` tensor *does not* share the underlying storage + with the :attr:`input` tensor. + + If :attr:`input` is a :ref:`sparse tensor ` with compressed + layout (SparseCSR, SparseBSR, SparseCSC or SparseBSC) the arguments + :attr:`dim0` and :attr:`dim1` must be both batch dimensions, or must + both be sparse dimensions. The batch dimensions of a sparse tensor are the + dimensions preceding the sparse dimensions. + + .. note:: + Transpositions which interchange the sparse dimensions of a `SparseCSR` + or `SparseCSC` layout tensor will result in the layout changing between + the two options. Transposition of the sparse dimensions of a ` SparseBSR` + or `SparseBSC` layout tensor will likewise generate a result with the + opposite layout. + + + Args: + input (Tensor): the input tensor. + dim0 (int): the first dimension to be transposed + dim1 (int): the second dimension to be transposed + + Example:: + + >>> x = torch.randn(2, 3) + >>> x + tensor([[ 1.0028, -0.9893, 0.5809], + [-0.1669, 0.7299, 0.4942]]) + >>> torch.transpose(x, 0, 1) + tensor([[ 1.0028, -0.1669], + [-0.9893, 0.7299], + [ 0.5809, 0.4942]]) + + See also :func:`torch.t`. + """ + +def transpose_copy( + input: Tensor, + dim0: _int, + dim1: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.transpose`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def trapezoid(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Computes the `trapezoidal rule `_ along + :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified. + + + Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, + the default computation is + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`dx` is specified the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + + effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, + assuming :attr:`x` is also a one-dimensional tensor with + elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. + The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` + and :attr:`y`, the function computes the difference between consecutive elements along + dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have + the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. + After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. + See the examples below for details. + + .. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) + """ + +@overload +def trapezoid( + y: Tensor, + *, + dx: Number | _complex | PySymType = 1, + dim: _int = -1, +) -> Tensor: + r""" + trapezoid(y, x=None, *, dx=None, dim=-1) -> Tensor + + Computes the `trapezoidal rule `_ along + :attr:`dim`. By default the spacing between elements is assumed to be 1, but + :attr:`dx` can be used to specify a different constant spacing, and :attr:`x` can be + used to specify arbitrary spacing along :attr:`dim`. Only one of :attr:`x` or :attr:`dx` should be specified. + + + Assuming :attr:`y` is a one-dimensional tensor with elements :math:`{y_0, y_1, ..., y_n}`, + the default computation is + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`dx` is specified the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) + \end{aligned} + + effectively multiplying the result by :attr:`dx`. When :attr:`x` is specified, + assuming :attr:`x` is also a one-dimensional tensor with + elements :math:`{x_0, x_1, ..., x_n}`, the computation becomes + + .. math:: + \begin{aligned} + \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) + \end{aligned} + + When :attr:`x` and :attr:`y` have the same size, the computation is as described above and no broadcasting is needed. + The broadcasting behavior of this function is as follows when their sizes are different. For both :attr:`x` + and :attr:`y`, the function computes the difference between consecutive elements along + dimension :attr:`dim`. This effectively creates two tensors, `x_diff` and `y_diff`, that have + the same shape as the original tensors except their lengths along the dimension :attr:`dim` is reduced by 1. + After that, those two tensors are broadcast together to compute final output as part of the trapezoidal rule. + See the examples below for details. + + .. note:: + The trapezoidal rule is a technique for approximating the definite integral of a function + by averaging its left and right Riemann sums. The approximation becomes more accurate as + the resolution of the partition increases. + + Arguments: + y (Tensor): Values to use when computing the trapezoidal rule. + x (Tensor): If specified, defines spacing between values as specified above. + + Keyword arguments: + dx (float): constant spacing between values. If neither :attr:`x` or :attr:`dx` + are specified then this defaults to 1. Effectively multiplies the result by its value. + dim (int): The dimension along which to compute the trapezoidal rule. + The last (inner-most) dimension by default. + + Examples:: + + >>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 + >>> y = torch.tensor([1, 5, 10]) + >>> torch.trapezoid(y) + tensor(10.5) + + >>> # Computes the same trapezoidal rule directly to verify + >>> (1 + 10 + 10) / 2 + 10.5 + + >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 + >>> # NOTE: the result is the same as before, but multiplied by 2 + >>> torch.trapezoid(y, dx=2) + 21.0 + + >>> # Computes the trapezoidal rule in 1D with arbitrary spacing + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + 28.5 + + >>> # Computes the same trapezoidal rule directly to verify + >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 + 28.5 + + >>> # Computes the trapezoidal rule for each row of a 3x3 matrix + >>> y = torch.arange(9).reshape(3, 3) + tensor([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> torch.trapezoid(y) + tensor([ 2., 8., 14.]) + + >>> # Computes the trapezoidal rule for each column of the matrix + >>> torch.trapezoid(y, dim=0) + tensor([ 6., 8., 10.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with the same arbitrary spacing + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([1, 3, 6]) + >>> torch.trapezoid(y, x) + array([5., 5., 5.]) + + >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix + >>> # with different arbitrary spacing per row + >>> y = torch.ones(3, 3) + >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) + >>> torch.trapezoid(y, x) + array([2., 4., 6.]) + """ + +@overload +def trapz(y: Tensor, *, dx: _float = 1, dim: _int = -1) -> Tensor: + r""" + trapz(y, x=None, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +@overload +def trapz(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + trapz(y, x=None, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +def triangular_solve( + input: Tensor, + A: Tensor, + upper: _bool = True, + transpose: _bool = False, + unitriangular: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.triangular_solve: + r""" + triangular_solve(b, A, upper=True, transpose=False, unitriangular=False, *, out=None) -> (Tensor, Tensor) + + Solves a system of equations with a square upper or lower triangular invertible matrix :math:`A` + and multiple right-hand sides :math:`b`. + + In symbols, it solves :math:`AX = b` and assumes :math:`A` is square upper-triangular + (or lower-triangular if :attr:`upper`\ `= False`) and does not have zeros on the diagonal. + + `torch.triangular_solve(b, A)` can take in 2D inputs `b, A` or inputs that are + batches of 2D matrices. If the inputs are batches, then returns + batched outputs `X` + + If the diagonal of :attr:`A` contains zeros or elements that are very close to zero and + :attr:`unitriangular`\ `= False` (default) or if the input matrix is badly conditioned, + the result may contain `NaN` s. + + Supports input of float, double, cfloat and cdouble data types. + + .. warning:: + + :func:`torch.triangular_solve` is deprecated in favor of :func:`torch.linalg.solve_triangular` + and will be removed in a future PyTorch release. + :func:`torch.linalg.solve_triangular` has its arguments reversed and does not return a + copy of one of the inputs. + + ``X = torch.triangular_solve(B, A).solution`` should be replaced with + + .. code:: python + + X = torch.linalg.solve_triangular(A, B) + + Args: + b (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where + :math:`*` is zero of more batch dimensions + A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)` + where :math:`*` is zero or more batch dimensions + upper (bool, optional): whether :math:`A` is upper or lower triangular. Default: ``True``. + transpose (bool, optional): solves `op(A)X = b` where `op(A) = A^T` if this flag is ``True``, + and `op(A) = A` if it is ``False``. Default: ``False``. + unitriangular (bool, optional): whether :math:`A` is unit triangular. + If True, the diagonal elements of :math:`A` are assumed to be + 1 and not referenced from :math:`A`. Default: ``False``. + + Keyword args: + out ((Tensor, Tensor), optional): tuple of two tensors to write + the output to. Ignored if `None`. Default: `None`. + + Returns: + A namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient` + is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b` + (or whatever variant of the system of equations, depending on the keyword arguments.) + + Examples:: + + >>> A = torch.randn(2, 2).triu() + >>> A + tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]]) + >>> b = torch.randn(2, 3) + >>> b + tensor([[-0.0210, 2.3513, -1.5492], + [ 1.5429, 0.7403, -1.0243]]) + >>> torch.triangular_solve(b, A) + torch.return_types.triangular_solve( + solution=tensor([[ 1.7841, 2.9046, -2.5405], + [ 1.9320, 0.9270, -1.2826]]), + cloned_coefficient=tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]])) + """ + +def tril( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + tril(input, diagonal=0, *, out=None) -> Tensor + + Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0813, -0.8619, 0.7105], + [ 0.0935, 0.1380, 2.2112], + [-0.3409, -0.9828, 0.0289]]) + >>> torch.tril(a) + tensor([[-1.0813, 0.0000, 0.0000], + [ 0.0935, 0.1380, 0.0000], + [-0.3409, -0.9828, 0.0289]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461], + [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]]) + >>> torch.tril(b, diagonal=1) + tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]]) + >>> torch.tril(b, diagonal=-1) + tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]]) + """ + +def tril_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + tril_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the lower triangular part of a :attr:`row`-by- + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.tril_indices(3, 3) + >>> a + tensor([[0, 1, 1, 2, 2, 2], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, -1) + >>> a + tensor([[1, 2, 2, 3, 3, 3], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], + [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]]) + """ + +def triplet_margin_loss( + anchor: Tensor, + positive: Tensor, + negative: Tensor, + margin: _float = 1.0, + p: _float = 2, + eps: _float = 1e-06, + swap: _bool = False, + reduction: _int = 1, +) -> Tensor: ... +def triu( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + triu(input, diagonal=0, *, out=None) -> Tensor + + Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.3480, -0.5211, -0.4573]]) + >>> torch.triu(a) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.0000, -1.0680, 0.6602], + [ 0.0000, 0.0000, -0.4573]]) + >>> torch.triu(a, diagonal=1) + tensor([[ 0.0000, 0.5207, 2.0049], + [ 0.0000, 0.0000, 0.6602], + [ 0.0000, 0.0000, 0.0000]]) + >>> torch.triu(a, diagonal=-1) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.0000, -0.5211, -0.4573]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=1) + tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=-1) + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]]) + """ + +def triu_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + triu_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the upper triangular part of a :attr:`row` by + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.triu_indices(3, 3) + >>> a + tensor([[0, 0, 0, 1, 1, 2], + [0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, -1) + >>> a + tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3], + [0, 1, 2, 0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1], + [1, 2, 2]]) + """ + +def true_divide( + input: Tensor | Number, + other: Tensor | Number, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + true_divide(dividend, divisor, *, out) -> Tensor + + Alias for :func:`torch.div` with ``rounding_mode=None``. + """ + +def trunc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + trunc(input, *, out=None) -> Tensor + + Returns a new tensor with the truncated integer values of + the elements of :attr:`input`. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 3.4742, 0.5466, -0.8008, -0.9079]) + >>> torch.trunc(a) + tensor([ 3., 0., -0., -0.]) + """ + +def trunc_(input: Tensor) -> Tensor: + r""" + trunc_(input) -> Tensor + + In-place version of :func:`torch.trunc` + """ + +def unbind(input: Tensor, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + unbind(input, dim=0) -> seq + + Removes a tensor dimension. + + Returns a tuple of all slices along a given dimension, already without it. + + Arguments: + input (Tensor): the tensor to unbind + dim (int): dimension to remove + + Example:: + + >>> torch.unbind(torch.tensor([[1, 2, 3], + >>> [4, 5, 6], + >>> [7, 8, 9]])) + (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9])) + """ + +def unbind_copy( + input: Tensor, + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.unbind`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def unflatten( + input: Tensor, + dim: _int, + sizes: Sequence[_int | SymInt], +) -> Tensor: + r""" + unflatten(input, dim, sizes) -> Tensor + + Expands a dimension of the input tensor over multiple dimensions. + + .. seealso:: + + :func:`torch.flatten` the inverse of this function. It coalesces several dimensions into one. + + Args: + input (Tensor): the input tensor. + dim (int): Dimension to be unflattened, specified as an index into + ``input.shape``. + sizes (Tuple[int]): New shape of the unflattened dimension. + One of its elements can be `-1` in which case the corresponding output + dimension is inferred. Otherwise, the product of ``sizes`` *must* + equal ``input.shape[dim]``. + + Returns: + A View of input with the specified dimension unflattened. + + Examples:: + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (2, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(3, 4, 1), 1, (-1, 2)).shape + torch.Size([3, 2, 2, 1]) + >>> torch.unflatten(torch.randn(5, 12, 3), -2, (2, 2, 3, 1, 1)).shape + torch.Size([5, 2, 2, 3, 1, 1, 3]) + """ + +def unfold_copy( + input: Tensor, + dimension: _int, + size: _int, + step: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.unfold`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def unique_dim( + input: Tensor, + dim: _int, + sorted: _bool = True, + return_inverse: _bool = False, + return_counts: _bool = False, +) -> tuple[Tensor, Tensor, Tensor]: ... +def unsafe_chunk( + input: Tensor, + chunks: _int, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + unsafe_chunk(input, chunks, dim=0) -> List of Tensors + + Works like :func:`torch.chunk` but without enforcing the autograd restrictions + on inplace modification of the outputs. + + .. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. + """ + +def unsafe_split( + input: Tensor, + split_size: _int | SymInt, + dim: _int = 0, +) -> tuple[Tensor, ...]: + r""" + unsafe_split(tensor, split_size_or_sections, dim=0) -> List of Tensors + + Works like :func:`torch.split` but without enforcing the autograd restrictions + on inplace modification of the outputs. + + .. warning:: + This function is safe to use as long as only the input, or only the outputs + are modified inplace after calling this function. It is user's + responsibility to ensure that is the case. If both the input and one or more + of the outputs are modified inplace, gradients computed by autograd will be + silently incorrect. + """ + +def unsafe_split_with_sizes( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: ... +def unsqueeze(input: Tensor, dim: _int) -> Tensor: + r""" + unsqueeze(input, dim) -> Tensor + + Returns a new tensor with a dimension of size one inserted at the + specified position. + + The returned tensor shares the same underlying data with this tensor. + + A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)`` + can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze` + applied at :attr:`dim` = ``dim + input.dim() + 1``. + + Args: + input (Tensor): the input tensor. + dim (int): the index at which to insert the singleton dimension + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4]) + >>> torch.unsqueeze(x, 0) + tensor([[ 1, 2, 3, 4]]) + >>> torch.unsqueeze(x, 1) + tensor([[ 1], + [ 2], + [ 3], + [ 4]]) + """ + +def unsqueeze_copy( + input: Tensor, + dim: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.unsqueeze`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def values_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.values`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def vander( + x: Tensor, + N: _int | None = None, + increasing: _bool = False, +) -> Tensor: + r""" + vander(x, N=None, increasing=False) -> Tensor + + Generates a Vandermonde matrix. + + The columns of the output matrix are elementwise powers of the input vector :math:`x^{(N-1)}, x^{(N-2)}, ..., x^0`. + If increasing is True, the order of the columns is reversed :math:`x^0, x^1, ..., x^{(N-1)}`. Such a + matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde. + + Arguments: + x (Tensor): 1-D input tensor. + N (int, optional): Number of columns in the output. If N is not specified, + a square array is returned :math:`(N = len(x))`. + increasing (bool, optional): Order of the powers of the columns. If True, + the powers increase from left to right, if False (the default) they are reversed. + + Returns: + Tensor: Vandermonde matrix. If increasing is False, the first column is :math:`x^{(N-1)}`, + the second :math:`x^{(N-2)}` and so forth. If increasing is True, the columns + are :math:`x^0, x^1, ..., x^{(N-1)}`. + + Example:: + + >>> x = torch.tensor([1, 2, 3, 5]) + >>> torch.vander(x) + tensor([[ 1, 1, 1, 1], + [ 8, 4, 2, 1], + [ 27, 9, 3, 1], + [125, 25, 5, 1]]) + >>> torch.vander(x, N=3) + tensor([[ 1, 1, 1], + [ 4, 2, 1], + [ 9, 3, 1], + [25, 5, 1]]) + >>> torch.vander(x, N=3, increasing=True) + tensor([[ 1, 1, 1], + [ 1, 2, 4], + [ 1, 3, 9], + [ 1, 5, 25]]) + """ + +@overload +def var( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var(input: Tensor, unbiased: _bool = True) -> Tensor: + r""" + var(input, dim=None, *, correction=1, keepdim=False, out=None) -> Tensor + + Calculates the variance over the dimensions specified by :attr:`dim`. :attr:`dim` + can be a single dimension, list of dimensions, or ``None`` to reduce over all + dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var(a, dim=1, keepdim=True) + tensor([[1.0631], + [0.5590], + [1.4893], + [0.8258]]) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +@overload +def var_mean( + input: Tensor, + unbiased: _bool = True, +) -> tuple[Tensor, Tensor]: + r""" + var_mean(input, dim=None, *, correction=1, keepdim=False, out=None) -> (Tensor, Tensor) + + Calculates the variance and mean over the dimensions specified by :attr:`dim`. + :attr:`dim` can be a single dimension, list of dimensions, or ``None`` to + reduce over all dimensions. + + The variance (:math:`\sigma^2`) is calculated as + + .. math:: \sigma^2 = \frac{1}{\max(0,~N - \delta N)}\sum_{i=0}^{N-1}(x_i-\bar{x})^2 + + where :math:`x` is the sample set of elements, :math:`\bar{x}` is the + sample mean, :math:`N` is the number of samples and :math:`\delta N` is + the :attr:`correction`. + + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + Keyword args: + correction (int): difference between the sample size and sample degrees of freedom. + Defaults to `Bessel's correction`_, ``correction=1``. + + .. versionchanged:: 2.0 + Previously this argument was called ``unbiased`` and was a boolean + with ``True`` corresponding to ``correction=1`` and ``False`` being + ``correction=0``. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + out (Tensor, optional): the output tensor. + + Returns: + A tuple (var, mean) containing the variance and mean. + + Example: + + >>> a = torch.tensor( + ... [[ 0.2035, 1.2959, 1.8101, -0.4644], + ... [ 1.5027, -0.3270, 0.5905, 0.6538], + ... [-1.5745, 1.3330, -0.5596, -0.6548], + ... [ 0.1264, -0.5080, 1.6420, 0.1992]] + ... ) # fmt: skip + >>> torch.var_mean(a, dim=0, keepdim=True) + (tensor([[1.5926, 1.0056, 1.2005, 0.3646]]), + tensor([[ 0.0645, 0.4485, 0.8707, -0.0665]])) + + .. _Bessel's correction: https://en.wikipedia.org/wiki/Bessel%27s_correction + """ + +def vdot( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + vdot(input, other, *, out=None) -> Tensor + + Computes the dot product of two 1D vectors along a dimension. + + In symbols, this function computes + + .. math:: + + \sum_{i=1}^n \overline{x_i}y_i. + + where :math:`\overline{x_i}` denotes the conjugate for complex + vectors, and it is the identity for real vectors. + + .. note:: + + Unlike NumPy's vdot, torch.vdot intentionally only supports computing the dot product + of two 1D tensors with the same number of elements. + + .. seealso:: + + :func:`torch.linalg.vecdot` computes the dot product of two batches of vectors along a dimension. + + Args: + input (Tensor): first tensor in the dot product, must be 1D. Its conjugate is used if it's complex. + other (Tensor): second tensor in the dot product, must be 1D. + + Keyword args: + + .. note:: out (Tensor, optional): the output tensor. + + + Example:: + + >>> torch.vdot(torch.tensor([2, 3]), torch.tensor([2, 1])) + tensor(7) + >>> a = torch.tensor((1 +2j, 3 - 1j)) + >>> b = torch.tensor((2 +1j, 4 - 0j)) + >>> torch.vdot(a, b) + tensor([16.+1.j]) + >>> torch.vdot(b, a) + tensor([16.-1.j]) + """ + +def view_as_complex(input: Tensor) -> Tensor: + r""" + view_as_complex(input) -> Tensor + + Returns a view of :attr:`input` as a complex tensor. For an input complex + tensor of :attr:`size` :math:`m1, m2, \dots, mi, 2`, this function returns a + new complex tensor of :attr:`size` :math:`m1, m2, \dots, mi` where the last + dimension of the input tensor is expected to represent the real and imaginary + components of complex numbers. + + .. warning:: + :func:`view_as_complex` is only supported for tensors with + :class:`torch.dtype` ``torch.float64`` and ``torch.float32``. The input is + expected to have the last dimension of :attr:`size` 2. In addition, the + tensor must have a `stride` of 1 for its last dimension. The strides of all + other dimensions must be even numbers. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, 2) + >>> x + tensor([[ 1.6116, -0.5772], + [-1.4606, -0.9120], + [ 0.0786, -1.7497], + [-0.6561, -1.6623]]) + >>> torch.view_as_complex(x) + tensor([(1.6116-0.5772j), (-1.4606-0.9120j), (0.0786-1.7497j), (-0.6561-1.6623j)]) + """ + +def view_as_complex_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view_as_complex`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def view_as_real(input: Tensor) -> Tensor: + r""" + view_as_real(input) -> Tensor + + Returns a view of :attr:`input` as a real tensor. For an input complex tensor of + :attr:`size` :math:`m1, m2, \dots, mi`, this function returns a new + real tensor of size :math:`m1, m2, \dots, mi, 2`, where the last dimension of size 2 + represents the real and imaginary components of complex numbers. + + .. warning:: + :func:`view_as_real` is only supported for tensors with ``complex dtypes``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.4737-0.3839j), (-0.2098-0.6699j), (0.3470-0.9451j), (-0.5174-1.3136j)]) + >>> torch.view_as_real(x) + tensor([[ 0.4737, -0.3839], + [-0.2098, -0.6699], + [ 0.3470, -0.9451], + [-0.5174, -1.3136]]) + """ + +def view_as_real_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view_as_real`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def view_copy( + input: Tensor, + dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def view_copy( + input: Tensor, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.view`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def vsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + vsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors + vertically according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) + (the split dimension is 0), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.vsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + """ + +@overload +def vsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + vsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with two or more dimensions, into multiple tensors + vertically according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + This is equivalent to calling torch.tensor_split(input, indices_or_sections, dim=0) + (the split dimension is 0), except that if :attr:`indices_or_sections` is an integer + it must evenly divide the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.vsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.vsplit(t, 2) + (tensor([[0., 1., 2., 3.], + [4., 5., 6., 7.]]), + tensor([[ 8., 9., 10., 11.], + [12., 13., 14., 15.]])) + >>> torch.vsplit(t, [3, 6]) + (tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.]]), + tensor([[12., 13., 14., 15.]]), + tensor([], size=(0, 4))) + """ + +def vstack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + vstack(tensors, *, out=None) -> Tensor + + Stack tensors in sequence vertically (row wise). + + This is equivalent to concatenation along the first axis after all 1-D tensors have been reshaped by :func:`torch.atleast_2d`. + + Args: + tensors (sequence of Tensors): sequence of tensors to concatenate + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([1, 2, 3]) + >>> b = torch.tensor([4, 5, 6]) + >>> torch.vstack((a,b)) + tensor([[1, 2, 3], + [4, 5, 6]]) + >>> a = torch.tensor([[1],[2],[3]]) + >>> b = torch.tensor([[4],[5],[6]]) + >>> torch.vstack((a,b)) + tensor([[1], + [2], + [3], + [4], + [5], + [6]]) + """ + +@overload +def where(condition: Tensor) -> tuple[Tensor, ...]: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + self: Number | _complex | PySymType, + other: Tensor, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + input: Tensor, + other: Number | _complex | PySymType, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def where( + condition: Tensor, + self: Number | _complex | PySymType, + other: Number | _complex | PySymType, +) -> Tensor: + r""" + where(condition, input, other, *, out=None) -> Tensor + + Return a tensor of elements selected from either :attr:`input` or :attr:`other`, depending on :attr:`condition`. + + The operation is defined as: + + .. math:: + \text{out}_i = \begin{cases} + \text{input}_i & \text{if } \text{condition}_i \\ + \text{other}_i & \text{otherwise} \\ + \end{cases} + + .. note:: + The tensors :attr:`condition`, :attr:`input`, :attr:`other` must be :ref:`broadcastable `. + + Arguments: + condition (BoolTensor): When True (nonzero), yield input, otherwise yield other + input (Tensor or Scalar): value (if :attr:`input` is a scalar) or values selected at indices + where :attr:`condition` is ``True`` + other (Tensor or Scalar): value (if :attr:`other` is a scalar) or values selected at indices + where :attr:`condition` is ``False`` + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`input`, :attr:`other` + + Example:: + + >>> x = torch.randn(3, 2) + >>> y = torch.ones(3, 2) + >>> x + tensor([[-0.4620, 0.3139], + [ 0.3898, -0.7197], + [ 0.0478, -0.1657]]) + >>> torch.where(x > 0, 1.0, 0.0) + tensor([[0., 1.], + [1., 0.], + [1., 0.]]) + >>> torch.where(x > 0, x, y) + tensor([[ 1.0000, 0.3139], + [ 0.3898, 1.0000], + [ 0.0478, 1.0000]]) + >>> x = torch.randn(2, 2, dtype=torch.double) + >>> x + tensor([[ 1.0779, 0.0383], + [-0.8785, -1.1089]], dtype=torch.float64) + >>> torch.where(x > 0, x, 0.) + tensor([[1.0779, 0.0383], + [0.0000, 0.0000]], dtype=torch.float64) + + .. function:: where(condition) -> tuple of LongTensor + :noindex: + + ``torch.where(condition)`` is identical to + ``torch.nonzero(condition, as_tuple=True)``. + + .. note:: + See also :func:`torch.nonzero`. + """ + +@overload +def xlogy( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy( + self: Number | _complex | PySymType, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy( + input: Tensor, + other: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + xlogy(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.special.xlogy`. + """ + +@overload +def xlogy_(input: Tensor, other: Tensor) -> Tensor: + r""" + xlogy_(input, other) -> Tensor + + In-place version of :func:`torch.xlogy` + """ + +@overload +def xlogy_(input: Tensor, other: Number | _complex | PySymType) -> Tensor: + r""" + xlogy_(input, other) -> Tensor + + In-place version of :func:`torch.xlogy` + """ + +def zero_(input: Tensor) -> Tensor: ... +@overload +def zeros( + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +@overload +def zeros( + *size: _int | SymInt, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the shape defined + by the variable argument :attr:`size`. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + Can be a variable number of arguments or a collection like a list or tuple. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.zeros(2, 3) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + + >>> torch.zeros(5) + tensor([ 0., 0., 0., 0., 0.]) + """ + +def zeros_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + zeros_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor filled with the scalar value `0`, with the same size as + :attr:`input`. ``torch.zeros_like(input)`` is equivalent to + ``torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. warning:: + As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, + the old ``torch.zeros_like(input, out=output)`` is equivalent to + ``torch.zeros(input.size(), out=output)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> input = torch.empty(2, 3) + >>> torch.zeros_like(input) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]]) + """ diff --git a/.venv/lib/python3.12/site-packages/torch/__config__.py b/.venv/lib/python3.12/site-packages/torch/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..1187fab3713996932d4f3bad71bac243c6baff35 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__config__.py @@ -0,0 +1,22 @@ +import torch + + +def show() -> str: + """ + Return a human-readable string with descriptions of the + configuration of PyTorch. + """ + return torch._C._show_config() + + +# TODO: In principle, we could provide more structured version/config +# information here. For now only CXX_FLAGS is exposed, as Timer +# uses them. +def _cxx_flags() -> str: + """Returns the CXX_FLAGS used when building PyTorch.""" + return torch._C._cxx_flags() + + +def parallel_info() -> str: + r"""Returns detailed string with parallelization settings""" + return torch._C._parallel_info() diff --git a/.venv/lib/python3.12/site-packages/torch/__future__.py b/.venv/lib/python3.12/site-packages/torch/__future__.py new file mode 100644 index 0000000000000000000000000000000000000000..f172ee3c8fe223aa316667f37f356e5b6658d20e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__future__.py @@ -0,0 +1,75 @@ +_overwrite_module_params_on_conversion: bool = False +_swap_module_params_on_conversion: bool = False + + +def set_overwrite_module_params_on_conversion(value: bool) -> None: + """ + Sets whether to assign new tensors to the parameters instead of changing the + existing parameters in-place when converting an ``nn.Module``. + + When enabled, the following methods will assign new parameters to the module: + + #. ``module.{device}()`` (e.g. :meth:`nn.Module.cuda()`) for moving a module between devices + #. ``module.{dtype}()`` (e.g. :meth:`nn.Module.float()`) for converting a module to a different dtype + #. :meth:`nn.Module.to` + #. :meth:`nn.Module.to_empty` + + Args: + value (bool): Whether to assign new tensors or not. + + """ + global _overwrite_module_params_on_conversion + _overwrite_module_params_on_conversion = value + + +def get_overwrite_module_params_on_conversion() -> bool: + """ + Returns whether to assign new tensors to the parameters instead of changing the + existing parameters in-place when converting an :class:`torch.nn.Module`. Defaults to ``False``. + + See :func:`~torch.__future__.set_overwrite_module_params_on_conversion` for more information. + """ + return _overwrite_module_params_on_conversion + + +def set_swap_module_params_on_conversion(value: bool) -> None: + """ + Sets whether to use :func:`~torch.utils.swap_tensors` instead of setting ``.data`` to + change the existing parameters in-place when converting an ``nn.Module`` and instead + of ``param.copy_(state_dict[key])`` when loading a state dict into an ``nn.Module``. + + .. note:: + This function takes precedence over :func:`~torch.__future__.get_overwrite_module_params_on_conversion` + + When enabled, the following methods will swap the existing parameters in-place: + + #. ``module.{device}()`` (e.g. :meth:`nn.Module.cuda()`) for moving a module between devices + #. ``module.{dtype}()`` (e.g. :meth:`nn.Module.float()`) for converting a module to a different dtype + #. :meth:`nn.Module.to` + #. :meth:`nn.Module.to_empty` + #. :meth:`nn.Module.load_state_dict` + + The semantics for :meth:`~nn.Module.load_state_dict` when this is set are as follows: + + #. For each parameter/buffer, its corresponding ``state_dict['key']`` is transformed via + :meth:`~torch.Tensor.module_load` (i.e. ``res = param.module_load(state_dict['key'])``) + #. If necessary, ``res`` will be wrapped in an :class:`~nn.Parameter` + #. The parameter/buffer in the module will be swapped via :func:`~torch.utils.swap_tensors` + with ``res`` + + Args: + value (bool): Whether to use :func:`~torch.utils.swap_tensors` or not. + + """ + global _swap_module_params_on_conversion + _swap_module_params_on_conversion = value + + +def get_swap_module_params_on_conversion() -> bool: + """ + Returns whether to use :func:`~torch.utils.swap_tensors` instead of setting .data to + change the existing parameters in-place when converting an ``nn.Module``. Defaults to ``False``. + + See :func:`~torch.__future__.set_swap_module_params_on_conversion` for more information. + """ + return _swap_module_params_on_conversion diff --git a/.venv/lib/python3.12/site-packages/torch/__init__.py b/.venv/lib/python3.12/site-packages/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f69b12c7b98759b6c44e80ad4f7ac23aa40884d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__init__.py @@ -0,0 +1,3539 @@ +""" +The torch package contains data structures for multi-dimensional +tensors and defines mathematical operations over these tensors. +Additionally, it provides many utilities for efficient serialization of +Tensors and arbitrary types, and other useful utilities. + +It has a CUDA counterpart, that enables you to run your tensor computations +on an NVIDIA GPU with compute capability >= 3.0. +""" + +import builtins +import ctypes +import functools +import glob +import importlib +import inspect +import math +import os +import platform +import sys +import textwrap +import threading +import typing +import typing_extensions +import warnings +from collections.abc import Callable as _Callable, Sequence as _Sequence +from types import ModuleType as _ModuleType +from typing import ( + Any as _Any, + get_origin as _get_origin, + overload as _overload, + TYPE_CHECKING, + TypeAlias as _TypeAlias, + TypeGuard as _TypeGuard, + TypeVar as _TypeVar, +) +from typing_extensions import ( + deprecated as _deprecated, + LiteralString as _LiteralString, + Never as _Never, + ParamSpec as _ParamSpec, + Self as _Self, + TypeIs as _TypeIs, +) + + +# As a bunch of torch.packages internally still have this check +# we need to keep this. @todo: Remove tests that rely on this check as +# they are likely stale. +def _running_with_deploy() -> builtins.bool: + return False + + +from torch._utils import ( + _functionalize_sync as _sync, + _import_dotted_name, + classproperty, +) +from torch._utils_internal import ( + get_file_path, + prepare_multiprocessing_environment, + profiler_allow_cudagraph_cupti_lazy_reinit_cuda12, + USE_GLOBAL_DEPS, + USE_RTLD_GLOBAL_WITH_LIBTORCH, +) +from torch.torch_version import __version__ as __version__ + + +if TYPE_CHECKING: + import sympy + + from torch.distributed._local_tensor import LocalIntNode + from torch.fx.experimental._constant_symnode import ConstantIntNode + from torch.fx.experimental.dynamic_spec import ParamsSpec, ShapesSpec + from torch.fx.experimental.sym_node import SymNode + from torch.nested._internal.nested_int import NestedIntNode + from torch.types import BoolLikeType, Device, FloatLikeType, IntLikeType, PySymType + + _SymNodeLike = SymNode | NestedIntNode | ConstantIntNode | LocalIntNode + + +__all__ = [ + "BoolStorage", + "BoolTensor", + "ByteStorage", + "ByteTensor", + "CharStorage", + "CharTensor", + "DoubleStorage", + "DoubleTensor", + "FloatStorage", + "FloatTensor", + "GradScaler", + "IntStorage", + "IntTensor", + "LongStorage", + "LongTensor", + "ShortStorage", + "ShortTensor", + "SymBool", + "SymFloat", + "SymInt", + "Tensor", + "TypedStorage", + "UntypedStorage", + "are_deterministic_algorithms_enabled", + "autocast", + "chunk", + "compile", + "cond", + "enable_grad", + "export", + "get_default_device", + "get_deterministic_debug_mode", + "get_device_module", + "get_float32_matmul_precision", + "get_rng_state", + "inference_mode", + "initial_seed", + "is_deterministic_algorithms_warn_only_enabled", + "is_storage", + "is_tensor", + "is_warn_always_enabled", + "load", + "lobpcg", + "manual_seed", + "matmul", + "no_grad", + "rand", + "randn", + "save", + "seed", + "set_default_device", + "set_default_tensor_type", + "set_deterministic_debug_mode", + "set_float32_matmul_precision", + "set_printoptions", + "set_rng_state", + "set_warn_always", + "split", + "stack", + "sym_float", + "sym_fresh_size", + "sym_int", + "sym_ite", + "sym_max", + "sym_min", + "sym_not", + "sym_sum", + "thread_safe_generator", + "typename", + "unravel_index", + "use_deterministic_algorithms", + "vmap", +] + +# Please keep this list sorted +if __all__ != sorted(__all__): + raise AssertionError("__all__ must be kept sorted") + +################################################################################ +# Load the extension module +################################################################################ + +# If PyTorch was built against the ROCm runtime wheels, then there will be +# a _rocm_init module and it will define an initialize() function which can +# prepare ROCm for use. See general documentation on ROCm runtime wheels: +# https://github.com/ROCm/TheRock/blob/main/docs/packaging/python_packaging.md +# Since this module is only ever added to the wheel if built for such a +# deployment, it is always safe to attempt. +try: + from . import _rocm_init # type: ignore[attr-defined] +except ImportError: + pass +else: + _rocm_init.initialize() + del _rocm_init + + +if sys.platform == "win32": + + def _load_dll_libraries() -> None: + import importlib.util + import sysconfig + + from torch.version import cuda as cuda_version + + pfiles_path = os.getenv("ProgramFiles", r"C:\Program Files") + py_dll_path = os.path.join(sys.exec_prefix, "Library", "bin") + th_dll_path = os.path.join(os.path.dirname(__file__), "lib") + # Anchor the DLL dir on the compiled _C extension rather than __file__: + # editable installs (e.g. scikit-build-core) run this __init__ from the + # source tree, whose lib/ is empty, while _C and its dependent DLLs live + # in the installed tree. In a wheel install both resolve to the same dir. + _spec = importlib.util.find_spec("torch._C") + if _spec is not None and _spec.origin: + th_dll_path = os.path.join(os.path.dirname(_spec.origin), "lib") + usebase_path = os.path.join( + sysconfig.get_config_var("userbase"), "Library", "bin" + ) + py_root_bin_path = os.path.join(sys.exec_prefix, "bin") + + # When users create a virtualenv that inherits the base environment, + # we will need to add the corresponding library directory into + # DLL search directories. Otherwise, it will rely on `PATH` which + # is dependent on user settings. + if sys.exec_prefix != sys.base_exec_prefix: + base_py_dll_path = os.path.join(sys.base_exec_prefix, "Library", "bin") + else: + base_py_dll_path = "" + + dll_paths = [ + p + for p in ( + th_dll_path, + py_dll_path, + base_py_dll_path, + usebase_path, + py_root_bin_path, + ) + if os.path.exists(p) + ] + + if not builtins.any( + os.path.exists(os.path.join(p, "nvToolsExt64_1.dll")) for p in dll_paths + ): + nvtoolsext_dll_path = os.path.join( + os.getenv( + "NVTOOLSEXT_PATH", + os.path.join(pfiles_path, "NVIDIA Corporation", "NvToolsExt"), + ), + "bin", + "x64", + ) + else: + nvtoolsext_dll_path = "" + + if cuda_version and builtins.all( + not glob.glob(os.path.join(p, "cudart64*.dll")) for p in dll_paths + ): + cuda_version_1 = cuda_version.replace(".", "_") + cuda_path_var = "CUDA_PATH_V" + cuda_version_1 + default_path = os.path.join( + pfiles_path, "NVIDIA GPU Computing Toolkit", "CUDA", f"v{cuda_version}" + ) + cuda_path = os.path.join(os.getenv(cuda_path_var, default_path), "bin") + else: + cuda_path = "" + + dll_paths.extend( + p for p in (nvtoolsext_dll_path, cuda_path) if os.path.exists(p) + ) + + kernel32 = ctypes.WinDLL("kernel32.dll", use_last_error=True) + with_load_library_flags = hasattr(kernel32, "AddDllDirectory") + prev_error_mode = kernel32.SetErrorMode(0x0001) + + kernel32.LoadLibraryW.restype = ctypes.c_void_p + if with_load_library_flags: + kernel32.LoadLibraryExW.restype = ctypes.c_void_p + + for dll_path in dll_paths: + os.add_dll_directory(dll_path) + + try: + ctypes.CDLL("vcruntime140.dll") + ctypes.CDLL("msvcp140.dll") + if platform.machine() != "ARM64": + ctypes.CDLL("vcruntime140_1.dll") + except OSError: + print( + textwrap.dedent( + """ + Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure. + It can be downloaded at https://aka.ms/vs/17/release/vc_redist.x64.exe + """ + ).strip() + ) + + dlls = glob.glob(os.path.join(th_dll_path, "*.dll")) + path_patched = False + for dll in dlls: + is_loaded = False + if with_load_library_flags: + res = kernel32.LoadLibraryExW(dll, None, 0x00001100) + last_error = ctypes.get_last_error() + if res is None and last_error != 126: + err = ctypes.WinError(last_error) + err.strerror += ( + f' Error loading "{dll}" or one of its dependencies.' + ) + raise err + elif res is not None: + is_loaded = True + if not is_loaded: + if not path_patched: + os.environ["PATH"] = ";".join(dll_paths + [os.environ["PATH"]]) + path_patched = True + res = kernel32.LoadLibraryW(dll) + if res is None: + err = ctypes.WinError(ctypes.get_last_error()) + err.strerror += ( + f' Error loading "{dll}" or one of its dependencies.' + ) + raise err + + kernel32.SetErrorMode(prev_error_mode) + + _load_dll_libraries() + del _load_dll_libraries + + +def _get_cuda_dep_paths(path: str, lib_folder: str, lib_name: str) -> list[str]: + # Libraries can either be in + # path/nvidia/lib_folder/lib or + # path/nvidia/cuXX/lib (since CUDA 13.0) or + # path/lib_folder/lib + from torch.version import cuda as cuda_version + + nvidia_lib_paths = glob.glob( + os.path.join(path, "nvidia", lib_folder, "lib", lib_name) + ) + if cuda_version is not None: + maj_cuda_version = cuda_version.split(".")[0] + nvidia_lib_paths += glob.glob( + os.path.join(path, "nvidia", f"cu{maj_cuda_version}", "lib", lib_name) + ) + lib_paths = glob.glob(os.path.join(path, lib_folder, "lib", lib_name)) + + return nvidia_lib_paths + lib_paths + + +def _preload_cuda_lib(lib_folder: str, lib_name: str, required: bool = True) -> None: # type: ignore[valid-type] + """Preloads cuda library if it could not be found otherwise.""" + # Should only be called on Linux if default path resolution have failed + if platform.system() != "Linux": + raise AssertionError(f"Should only be called on Linux, got {platform.system()}") + + lib_path = None + for path in sys.path: + candidate_lib_paths = _get_cuda_dep_paths(path, lib_folder, lib_name) + if candidate_lib_paths: + lib_path = candidate_lib_paths[0] + break + if not lib_path and required: + raise ValueError(f"{lib_name} not found in the system path {sys.path}") + if lib_path: + ctypes.CDLL(lib_path) + + +def _preload_cuda_deps(err: OSError | None = None, required: bool = True) -> None: + cuda_libs: list[tuple[str, str]] = [ + # NOTE: Order matters! We must preload libcublasLt BEFORE libcublas to prevent + # libcublas from loading a mismatched system-wide libcublasLt via its RUNPATH. + # Without this, if a different CUDA Toolkit version exists in the system PATH, + # libcublas may load the wrong libcublasLt, causing symbol errors or runtime failures. + ("cublas", "libcublasLt.so.*[0-9]"), + ("cublas", "libcublas.so.*[0-9]"), + ("cudnn", "libcudnn.so.*[0-9]"), + ("cuda_nvrtc", "libnvrtc.so.*[0-9]"), + ("cuda_nvrtc", "libnvrtc-builtins.so.*[0-9]"), + ("cuda_runtime", "libcudart.so.*[0-9]"), + ("cuda_cupti", "libcupti.so.*[0-9]"), + ("cufft", "libcufft.so.*[0-9]"), + ("curand", "libcurand.so.*[0-9]"), + ("nvjitlink", "libnvJitLink.so.*[0-9]"), + ("cusparse", "libcusparse.so.*[0-9]"), + ("cusparselt", "libcusparseLt.so.*[0-9]"), + ("cusolver", "libcusolver.so.*[0-9]"), + ("nccl", "libnccl.so.*[0-9]"), + ("nvshmem", "libnvshmem_host.so.*[0-9]"), + ("cufile", "libcufile.so.*[0-9]"), + ] + # If error is passed, re-raise it if it's not about one of the abovementioned + # libraries + if err is not None and not [ + lib for _, lib in cuda_libs if lib.split(".", 1)[0] in err.args[0] + ]: + raise err + + # Otherwise, try to preload dependencies from site-packages. With + # required=False each lib is best-effort: a partial install that only ships + # some of these wheels (e.g. just a cupti wheel alongside a system CUDA) + # preloads the ones present instead of aborting on the first missing one. + for lib_folder, lib_name in cuda_libs: + _preload_cuda_lib(lib_folder, lib_name, required=required) + + # libnvToolsExt is Optional Dependency + _preload_cuda_lib("nvtx", "libnvToolsExt.so.*[0-9]", required=False) + + +# See Note [Global dependencies] +def _load_global_deps() -> None: + if platform.system() == "Windows": + return + + # Determine the file extension based on the platform + lib_ext = ".dylib" if platform.system() == "Darwin" else ".so" + lib_name = f"libtorch_global_deps{lib_ext}" + here = os.path.abspath(__file__) + global_deps_lib_path = os.path.join(os.path.dirname(here), "lib", lib_name) + + # In scikit-build-core editable installs with redirect mode, native libs are + # installed to the dist package location rather than relative to __file__. + if not os.path.exists(global_deps_lib_path): + try: + from importlib.metadata import distribution + + installed = distribution("torch").locate_file( + os.path.join("torch", "lib", lib_name) + ) + # The importlib metadata SimplePath protocol was missing the exists + # method in older versions; however, the actual Path implementation + # has it and newer versions of importlib metadata have added it to + # the protocol, making the following ignore unnecessary from + # importlib_metadata 7.0.1 and Python 3.13 onwards. + # pyrefly: ignore[missing-attribute] + if installed.exists(): + global_deps_lib_path = str(installed) + except Exception: + pass + + try: + ctypes.CDLL(global_deps_lib_path, mode=ctypes.RTLD_GLOBAL) + # Workaround slim-wheel CUDA dependency bugs in cusparse and cudnn by preloading nvjitlink + # and nvrtc. In CUDA-12.4+ cusparse depends on nvjitlink, but does not have rpath when + # shipped as wheel, which results in OS picking wrong/older version of nvjitlink library + # if `LD_LIBRARY_PATH` is defined, see https://github.com/pytorch/pytorch/issues/138460 + # Similar issue exist in cudnn that dynamically loads nvrtc, unaware of its relative path. + # See https://github.com/pytorch/pytorch/issues/145580 + try: + with open("/proc/self/maps") as f: + _maps = f.read() + + # libtorch_global_deps.so always depends in cudart, check if its installed and loaded + if "libcudart.so" not in _maps: + return + # If all above-mentioned conditions are met, preload CUDA dependencies. + # Only libtorch_global_deps is loaded so far (it pulls libcudart, not + # the rest); libtorch_cpu, which DT_NEEDEDs the other CUDA libs, is + # imported below via torch._C. So be best-effort and front-load any + # component wheels that ARE present now, before that import, so they + # win libtorch_cpu's DT_NEEDED soname lookups (e.g. a newer cupti + # wheel over a system copy). A missing wheel must not abort -- rpath + # will satisfy libtorch_cpu's DT_NEEDED for whatever isn't preloaded. + _preload_cuda_deps(required=False) + except Exception: + pass + + except OSError as err: + # Can happen for wheel with cuda libs as PYPI deps + # As PyTorch is not purelib, but nvidia-*-cu12 is + _preload_cuda_deps(err) + ctypes.CDLL(global_deps_lib_path, mode=ctypes.RTLD_GLOBAL) + + +if (USE_RTLD_GLOBAL_WITH_LIBTORCH or os.getenv("TORCH_USE_RTLD_GLOBAL")) and ( + platform.system() != "Windows" +): + # Do it the hard way. You might want to load libtorch with RTLD_GLOBAL in a + # few circumstances: + # + # 1. You're in a build environment (e.g., fbcode) where + # libtorch_global_deps is not available, but you still need + # to get mkl to link in with RTLD_GLOBAL or it will just + # not work. + # + # 2. You're trying to run PyTorch under UBSAN and you need + # to ensure that only one copy of libtorch is loaded, so + # vptr checks work properly + # + # If you're using this setting, you must verify that all the libraries + # you load consistently use the same libstdc++, or you may have + # mysterious segfaults. + # + old_flags = sys.getdlopenflags() + sys.setdlopenflags(os.RTLD_GLOBAL | os.RTLD_LAZY) + + from torch._C import * # noqa: F403 + + sys.setdlopenflags(old_flags) + del old_flags + +else: + # Easy way. You want this most of the time, because it will prevent + # C++ symbols from libtorch clobbering C++ symbols from other + # libraries, leading to mysterious segfaults. + # + # If building in an environment where libtorch_global_deps isn't available + # like parts of fbsource, but where RTLD_GLOBAL causes segfaults, you will + # want USE_RTLD_GLOBAL_WITH_LIBTORCH = False and USE_GLOBAL_DEPS = False + # + # See Note [Global dependencies] + if USE_GLOBAL_DEPS: + _load_global_deps() + from torch._C import * # noqa: F403 + + +_PrimType = _TypeVar("_PrimType") +_SymType = _TypeVar("_SymType") +_SymIteT = _TypeVar("_SymIteT") +_BecomesIntPrimType = _TypeVar("_BecomesIntPrimType") +_BecomesIntSymType = _TypeVar("_BecomesIntSymType") +# Operand type for bitwise ops: IntLikeType for SymInt; BoolLikeType for SymBool. +_BitwiseLikeType = _TypeVar("_BitwiseLikeType") +# Operand types that promote the result to SymFloat. _Never for SymFloat +# (no further promotion); float | SymFloat for SymInt and SymBool. +_FloatPromotionType = _TypeVar("_FloatPromotionType") +_LikeNumber: _TypeAlias = "torch.types.Number | torch.types.PySymType" + + +class _SymTypingMagicAlsoBool( + typing.Generic[ + _PrimType, _BecomesIntPrimType, _BecomesIntSymType, _FloatPromotionType + ] +): + # Magic methods installed by torch.fx.experimental.sym_node + # From sym_node: also_bool_magic_methods + + __LikeType: _TypeAlias = ( + _PrimType | _Self | _BecomesIntPrimType | _BecomesIntSymType + ) + _BecomesIntLikeType: _TypeAlias = _BecomesIntPrimType | _BecomesIntSymType + + @_overload + def __eq__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __eq__(self, other: object) -> builtins.bool: ... + + def __eq__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + @_overload + def __ne__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __ne__(self, other: object) -> builtins.bool: ... + + def __ne__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + # bool_becomes_int_magic_methods + + @_overload + def __add__(self, other: __LikeType) -> _BecomesIntSymType: ... + + @_overload + def __add__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __add__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + # Tensor + SymT -> Tensor + # prim|SymT + SymT -> SymT + @_overload + def __radd__(self, other: "torch.Tensor") -> "torch.Tensor": ... + + @_overload + def __radd__( + self, other: _PrimType | _BecomesIntPrimType | _BecomesIntSymType + ) -> _BecomesIntSymType: ... + + @_overload + def __radd__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __radd__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + @_overload + def __sub__(self, other: __LikeType) -> _BecomesIntSymType: ... + + @_overload + def __sub__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __sub__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + # Tensor - SymT = Tensor + # prim|SymT - SymT = SymT + @_overload + def __rsub__(self, other: "torch.Tensor") -> "torch.Tensor": ... + + @_overload + def __rsub__( + self, other: _PrimType | _BecomesIntPrimType | _BecomesIntSymType + ) -> _BecomesIntSymType: ... + + @_overload + def __rsub__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __rsub__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + @_overload + def __mul__(self, other: __LikeType) -> _BecomesIntSymType: ... + + @_overload + def __mul__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __mul__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + @_overload + def __rmul__(self, other: __LikeType) -> _BecomesIntSymType: ... + + @_overload + def __rmul__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __rmul__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + +class _SymTypingMagic( + _SymTypingMagicAlsoBool[_PrimType, _PrimType, _SymType, _FloatPromotionType], + typing.Generic[_PrimType, _SymType, _FloatPromotionType], +): + # Magic methods installed by torch.fx.experimental.sym_node + # From sym_node: + # magic_methods + # - only_float_magic_methods + # - bitwise_ops + # - only_bool_magic_methods + # - also_bool_magic_methods + # - bool_becomes_int_magic_methods + + __LikeType: _TypeAlias = _PrimType | _Self + + # Ordering comparisons: only on ordered types (SymInt/SymFloat), not SymBool. + @_overload + def __ge__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __ge__(self, other: object) -> builtins.bool: ... + + def __ge__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + @_overload + def __gt__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __gt__(self, other: object) -> builtins.bool: ... + + def __gt__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + @_overload + def __le__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __le__(self, other: object) -> builtins.bool: ... + + def __le__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + @_overload + def __lt__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __lt__(self, other: object) -> builtins.bool: ... + + def __lt__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + def __abs__(self) -> _Self: + raise TypeError("type stub not overridden") + + def __ceil__(self) -> "SymInt": + raise TypeError("type stub not overridden") + + def __float_pow__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __rfloat_pow__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __float_truediv__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __rfloat_truediv__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __floor__(self) -> "SymInt": + raise TypeError("type stub not overridden") + + def __int_floordiv__(self, other: _LikeNumber) -> "SymInt": + raise TypeError("type stub not overridden") + + def __rint_floordiv__(self, other: _LikeNumber) -> "SymInt": + raise TypeError("type stub not overridden") + + def __int_truediv__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __rint_truediv__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __lshift__(self, other: "IntLikeType") -> _Self: + raise TypeError("type stub not overridden") + + def __rlshift__(self, other: "IntLikeType") -> _Self: + raise TypeError("type stub not overridden") + + @_overload + def __mod__(self, other: __LikeType) -> _SymType: ... + + @_overload + def __mod__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __mod__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + @_overload + def __rmod__(self, other: __LikeType) -> _SymType: ... + + @_overload + def __rmod__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __rmod__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + def __neg__(self) -> _Self: + raise TypeError("type stub not overridden") + + def __pos__(self) -> _Self: + raise TypeError("type stub not overridden") + + def __pow_by_natural__(self, other: "IntLikeType") -> "SymInt": + raise TypeError("type stub not overridden") + + def __rpow_by_natural__(self, other: "IntLikeType") -> "SymInt": + raise TypeError("type stub not overridden") + + def __rshift__(self, other: "IntLikeType") -> _Self: + raise TypeError("type stub not overridden") + + def __rrshift__(self, other: "IntLikeType") -> _Self: + raise TypeError("type stub not overridden") + + def __sym_acos__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_asin__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_atan__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_cos__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_cosh__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_float__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_max__(self, other: _LikeNumber) -> _LikeNumber: + raise TypeError("type stub not overridden") + + def __sym_min__(self, other: _LikeNumber) -> _LikeNumber: + raise TypeError("type stub not overridden") + + def __sym_sin__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_sinh__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_sqrt__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_tan__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_tanh__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __trunc__(self) -> "SymInt": + raise TypeError("type stub not overridden") + + +class _SymTypingMagicBitwise(typing.Generic[_BitwiseLikeType]): + # Magic methods installed by torch.fx.experimental.sym_node + # From sym_node: bitwise_ops + + def __and__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + def __rand__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + def __or__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + def __ror__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + def __xor__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + def __rxor__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + +class SymInt( + _SymTypingMagic[builtins.int, "SymInt", "FloatLikeType"], + _SymTypingMagicBitwise["IntLikeType"], +): + """ + Like an int (including magic methods), but redirects all operations on the + wrapped node. This is used in particular to symbolically record operations + in the symbolic shape workflow. + """ + + def __init__(self, node: "_SymNodeLike") -> None: + # This field MUST be named node; C++ binding code assumes that this + # class has a field named node that stores SymNode + self.node = typing.cast("SymNode", node) + + def __bool__(self) -> builtins.bool: + return builtins.bool(self != 0) + + def __int__(self) -> builtins.int: + # pyrefly: ignore[missing-attribute] # duck-typed: not on NestedIntNode/ConstantIntNode/LocalIntNode + return self.node.int_() + + def __index__(self) -> builtins.int: + # pyrefly: ignore[missing-attribute] # duck-typed: not on NestedIntNode/ConstantIntNode/LocalIntNode + return self.node.int_() + + # Magic methods installed by torch.fx.experimental.sym_node + + def __round__(self, ndigits: builtins.int | None = None) -> "SymInt": + return self + + def __truediv__(self, other: object) -> "SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__float_truediv__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + return self.__int_truediv__(other) + + def __rtruediv__(self, other: object) -> "SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__rfloat_truediv__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + return self.__rint_truediv__(other) + + @_overload + def __floordiv__(self, other: "builtins.int | SymInt") -> "SymInt": ... + + @_overload + def __floordiv__(self, other: "builtins.float | SymFloat") -> "SymFloat": ... + + def __floordiv__(self, other: object) -> "SymInt | SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(math.floor(sym_float(self) / other)) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + return self.__int_floordiv__(other) + + @_overload + def __rfloordiv__(self, other: "builtins.int | SymInt") -> "SymInt": ... + + @_overload + def __rfloordiv__(self, other: "builtins.float | SymFloat") -> "SymFloat": ... + + def __rfloordiv__(self, other: object) -> "SymInt | SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(math.floor(other / sym_float(self))) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + return self.__rint_floordiv__(other) + + # nb: complex is impossible to handle correctly lol, with + # negative base and integral float need to diverge semantics and + # just always return complex. Neener neener pretend this problem + # doesn't exist + def __pow__(self, other: object) -> "SymInt | SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__pow__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + # Guards! This guard is necessary because we need to know it to + # determine the output type of this operation + if other >= 0: + return self.__pow_by_natural__(other) + else: + # Mercifully, when the exponent is negative, Python just promotes + # to doubles and does a float pow: + # + # if (Py_SIZE(b) < 0 && c == NULL) { + # /* if exponent is negative and there's no modulus: + # return a float. This works because we know + # that this calls float_pow() which converts its + # arguments to double. */ + # Py_DECREF(a); + # Py_DECREF(b); + # return PyFloat_Type.tp_as_number->nb_power(v, w, x); + # } + return sym_float(self).__pow__(sym_float(other)) + + def __rpow__(self, other: object) -> "SymInt | SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__rpow__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + if self >= 0: # self is exponent + return self.__rpow_by_natural__(other) + else: + return sym_float(self).__rpow__(sym_float(other)) + + def __repr__(self) -> str: + return self.node._graph_repr() + + def _sympy_(self) -> "sympy.Basic": + # pyrefly: ignore[missing-attribute] # duck-typed: not on NestedIntNode/ConstantIntNode/LocalIntNode + return self.node.expr + + def __hash__(self) -> builtins.int: + if self.node.is_nested_int(): + # pyrefly: ignore[missing-attribute] # narrowed by is_nested_int(); only NestedIntNode/SymNode reach here + return hash(self.node.nested_int()) + else: + # We could support constant SymInts as well, but not doing it for now + raise TypeError("unhashable type: non-nested SymInt") + # TODO: Force specialization + # This can't be done because the TypeError here is load bearing + # for einops + # https://github.com/arogozhnikov/einops/blob/6181e1e95dc58c00a3143c1726da1c6ee0463164/einops/einops.py#L237 + # return hash(builtins.int(self)) + + def as_integer_ratio(self) -> tuple["SymInt", builtins.int]: + """Represent this int as an exact integer ratio""" + return self, 1 + + def bit_length(self) -> builtins.int: + # TODO: A more relaxed guard is possible here, where you guard to + # allow all integer quantities which would result in the same bit + # length. We can also just make a dedicated Sympy function for + # computing this quantity and represent it symbolically. + return builtins.int(self).bit_length() + + def conjugate(self) -> "SymInt": + return self + + def has_hint(self) -> builtins.bool: + return self.node.has_hint() + + @property + def hint(self) -> builtins.int | None: + return typing.cast(builtins.int | None, self.node.hint) + + @property + def constant(self) -> builtins.int | None: + return typing.cast(builtins.int | None, self.node.constant) + + +class SymFloat(_SymTypingMagic[builtins.float, "SymFloat", _Never]): + """ + Like a float (including magic methods), but redirects all operations on the + wrapped node. This is used in particular to symbolically record operations + in the symbolic shape workflow. + """ + + def __init__(self, node: "SymNode") -> None: + # This field MUST be named node; C++ binding code assumes that this + # class has a field named node that stores SymNode + self.node = node + + def __truediv__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + return self.__float_truediv__(sym_float(other)) + + def __rtruediv__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + return self.__rfloat_truediv__(sym_float(other)) + + def __floordiv__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + return sym_float(math.floor(self / sym_float(other))) + + def __rfloordiv__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + return sym_float(math.floor(sym_float(other) / self)) + + def __bool__(self) -> builtins.bool: + return self.node.bool_() + + def __float__(self) -> builtins.float: + return self.node.guard_float("", 0) + + def __int__(self) -> builtins.int: + return self.__trunc__().__int__() + + # Symbolic power does NOT work with negative base, this is to avoid + # potential complex outputs + def __pow__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + torch._check(self >= 0) + return self.__float_pow__(other) + + def __rpow__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + torch._check(other >= 0) + return self.__rfloat_pow__(other) + + # Magic methods installed by torch.fx.experimental.sym_node + + @_overload + def __round__(self) -> "SymInt": ... + + @_overload + def __round__(self, ndigits: "IntLikeType") -> "SymFloat": ... + + def __round__(self, ndigits: "IntLikeType | None" = None) -> "SymFloat | SymInt": + raise TypeError("type stub not overridden") + + # def __sym_int__(self) -> "SymInt": + # raise TypeError("type stub not overridden") + + def __sym_log2__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def is_integer(self) -> builtins.bool: + """Return True if the float is an integer.""" + raise TypeError("type stub not overridden") + + def as_integer_ratio(self) -> tuple[builtins.int, builtins.int]: + """Represent this float as an exact integer ratio""" + return builtins.float(self).as_integer_ratio() + + def __repr__(self) -> str: + return self.node._graph_repr() + + def _sympy_(self) -> "sympy.Basic": + return self.node.expr + + def __hash__(self) -> builtins.int: + return hash(builtins.float(self)) + + def conjugate(self) -> "SymFloat": + """Returns the complex conjugate of the float.""" + return self + + def hex(self) -> str: + """Returns the hexadecimal representation of the float.""" + return self.node.guard_float("", 0).hex() + + def has_hint(self) -> builtins.bool: + return self.node.has_hint() + + @property + def hint(self) -> builtins.float | None: + return typing.cast(builtins.float | None, self.node.hint) + + @property + def constant(self) -> builtins.float | None: + return typing.cast(builtins.float | None, self.node.constant) + + +class SymBool( + _SymTypingMagicAlsoBool[builtins.bool, builtins.int, "SymInt", "FloatLikeType"], + _SymTypingMagicBitwise["BoolLikeType"], +): + """ + Like a bool (including magic methods), but redirects all operations on the + wrapped node. This is used in particular to symbolically record operations + in the symbolic shape workflow. + + Unlike regular bools, regular boolean operators will force extra guards instead + of symbolically evaluate. Use the bitwise operators instead to handle this. + """ + + def __init__(self, node: "SymNode") -> None: + # This field MUST be named node; C++ binding code assumes that this + # class has a field named node that stores SymNode + self.node = node + + def __bool__(self) -> builtins.bool: + return self.node.bool_() + + def __int__(self) -> builtins.int: + return builtins.int(self.node.bool_()) + + # Magic methods installed by torch.fx.experimental.sym_node + + # We very carefully define __sym_not__, and not a number of other + # plausible alternatives: + # + # - We do not override __not__ because this is not a real magic + # method; you cannot override the meaning of the not builtin in + # Python. We use the name 'sym_not' to clarify that in user code you + # cannot use the builtin not or operator.not_ or operator.__not__ and + # hit this magic method; you must use our custom sym_not operator. + # + # - We do not override the __invert__ method because SymBool is + # meant to be usable in situations where bool is expected. However, + # bitwise negation ~a does the wrong thing with booleans (because + # bool is a subclass of int, so ~1 = -2 which is not falseish.) + # This would be a giant footgun, so we get around it by defining + # our own operator. Note that bitwise and/or do the right thing, + # so we reuse the conventional operators there for readability. + # + def __sym_not__(self) -> "SymBool": + raise TypeError("type stub not overridden") + + def __sym_ite__(self, then_val: _SymIteT, else_val: _SymIteT) -> _SymIteT: + raise TypeError("type stub not overridden") + + def __repr__(self) -> str: + return self.node._graph_repr() + + def _sympy_(self) -> "sympy.Basic": + return self.node.expr + + def __hash__(self) -> builtins.int: + if self.node.is_constant(): + return hash(self.node.bool_()) + else: + # Force specialization + return hash(builtins.bool(self)) + + def __sym_float__(self) -> "SymFloat": + """ + Provides a SymFloat representation (0.0 or 1.0) for this SymBool. + Called by torch.sym_float() when casting SymBool to float. + """ + from torch.fx.experimental.sym_node import wrap_node + + # pyrefly: ignore[bad-return] + return wrap_node(self.node.sym_float()) + + @property + def hint(self) -> builtins.bool | None: + return typing.cast(builtins.bool | None, self.node.hint) + + @property + def constant(self) -> builtins.bool | None: + return typing.cast(builtins.bool | None, self.node.constant) + + +@_overload +def sym_not(a: "BoolLikeType") -> "BoolLikeType": ... + + +@_overload +def sym_not(a: object) -> object: ... + + +def sym_not(a: object) -> object: + r"""SymInt-aware utility for logical negation. + + Args: + a (SymBool or bool): Object to negate + """ + import sympy + + if overrides.has_torch_function_unary(a): + # pyrefly: ignore[bad-argument-type] + return overrides.handle_torch_function(sym_not, (a,), a) + if hasattr(a, "__sym_not__"): + return a.__sym_not__() # type: ignore[attr-defined] + if isinstance(a, sympy.Basic): + return ~a # type: ignore[operator] + return not a + + +@_overload +def sym_float(a: "PySymType") -> "SymFloat": ... + + +@_overload +def sym_float(a: object) -> "FloatLikeType": ... + + +def sym_float(a: object) -> "FloatLikeType": + r"""SymInt-aware utility for float casting. + + Args: + a (SymInt, SymFloat, or object): Object to cast + """ + if overrides.has_torch_function_unary(a): + # pyrefly: ignore[bad-argument-type] + return overrides.handle_torch_function(sym_float, (a,), a) + if isinstance(a, SymFloat): + return a + elif hasattr(a, "__sym_float__"): + return a.__sym_float__() # type: ignore[attr-defined] + return builtins.float(a) # type: ignore[arg-type] + + +@_overload +def sym_int(a: "PySymType") -> "IntLikeType": ... + + +@_overload +def sym_int(a: object) -> builtins.int: ... + + +def sym_int(a: object) -> "IntLikeType": + r"""SymInt-aware utility for int casting. + + Args: + a (SymInt, SymFloat, or object): Object to cast + """ + if overrides.has_torch_function_unary(a): + # pyrefly: ignore[bad-argument-type] + return overrides.handle_torch_function(sym_int, (a,), a) + if isinstance(a, SymInt): + return a + elif isinstance(a, SymFloat): + return math.trunc(a) + return builtins.int(a) # type: ignore[arg-type] + + +@_overload +def sym_max(a: "IntLikeType", b: "IntLikeType") -> "IntLikeType": ... + + +@_overload +def sym_max( + a: "IntLikeType | FloatLikeType", b: "IntLikeType | FloatLikeType" +) -> "FloatLikeType": ... + + +def sym_max( + a: "IntLikeType | FloatLikeType", b: "IntLikeType | FloatLikeType" +) -> "IntLikeType | FloatLikeType": + """ + SymInt-aware utility for max which avoids branching on a < b. + Unlike builtins.max(), this only works for int/float, and it always + promotes to float if any argument is float (unlike builtins.max, which + will faithfully preserve the type of the input argument). + """ + if overrides.has_torch_function((a, b)): + # pyrefly: ignore[bad-argument-type] + return overrides.handle_torch_function(sym_max, (a, b), a, b) + if isinstance(a, (SymInt, SymFloat)): + return a.__sym_max__(b) # type: ignore[return-value] + elif isinstance(b, (SymInt, SymFloat)): + # Due to promotion semantics, this is operator is commutative: + # max(1, 1.0) === max(1.0, 1) === 1.0 + return b.__sym_max__(a) # type: ignore[return-value] + # TODO: Probably can make bool work too, just lazy + + all_types, float_types = __all_and_float_types() + + if not isinstance(a, all_types): + raise AssertionError(f"expected {all_types}, got {type(a)}") + if not isinstance(b, all_types): + raise AssertionError(f"expected {all_types}, got {type(b)}") + if isinstance(a, float_types) or isinstance(b, float_types): + return builtins.float(builtins.max(a, b)) # type: ignore[call-overload] + else: + return builtins.max(a, b) # type: ignore[call-overload] + + +def __all_and_float_types() -> tuple[tuple[type, ...], tuple[type, ...]]: + try: + import numpy as np + + all_types: tuple[type, ...] = ( + np.integer, + np.floating, + builtins.int, + builtins.float, + ) + float_types: tuple[type, ...] = (np.floating, builtins.float) + except ModuleNotFoundError: + all_types = (builtins.int, builtins.float) + float_types = (builtins.float,) + + return all_types, float_types + + +@_overload +def sym_min(a: "IntLikeType", b: "IntLikeType") -> "IntLikeType": ... + + +@_overload +def sym_min( + a: "IntLikeType | FloatLikeType", b: "IntLikeType | FloatLikeType" +) -> "FloatLikeType": ... + + +def sym_min( + a: "IntLikeType | FloatLikeType", b: "IntLikeType | FloatLikeType" +) -> "IntLikeType | FloatLikeType": + """SymInt-aware utility for min().""" + if overrides.has_torch_function((a, b)): + # pyrefly: ignore[bad-argument-type] + return overrides.handle_torch_function(sym_min, (a, b), a, b) + if isinstance(a, (SymInt, SymFloat)): + return a.__sym_min__(b) # type: ignore[return-value] + elif isinstance(b, (SymInt, SymFloat)): + return b.__sym_min__(a) # type: ignore[return-value] + + all_types, float_types = __all_and_float_types() + + if not isinstance(a, all_types): + raise AssertionError(f"expected {all_types}, got {type(a)}") + if not isinstance(b, all_types): + raise AssertionError(f"expected {all_types}, got {type(b)}") + if isinstance(a, float_types) or isinstance(b, float_types): + return builtins.float(builtins.min(a, b)) # type: ignore[call-overload] + else: + return builtins.min(a, b) # type: ignore[call-overload] + + +def sym_sum( + *args: "IntLikeType | _Sequence[IntLikeType]", +) -> "IntLikeType": + """ + N-ary add which is faster to compute for long lists than iterated binary + addition. Only does something special for integers. + + Accepts both ``sym_sum([a, b, c])`` and ``sym_sum(a, b, c)``. + """ + # Normalise: accept both sym_sum([a, b, c]) and sym_sum(a, b, c). + items: _Sequence[IntLikeType] = args # type: ignore[assignment] + if len(args) == 1 and isinstance(args[0], (list, tuple)): + items = args[0] + + if overrides.has_torch_function(items): + return overrides.handle_torch_function(sym_sum, items, items) + + found = None + for a in items: + if not isinstance(a, (SymInt, builtins.int)): + return builtins.sum(items) + if isinstance(a, SymInt): + found = a.node + if found is None: + return builtins.sum(items) + + from torch.fx.experimental.sym_node import to_node, wrap_node + + # pyrefly: ignore[missing-attribute, bad-argument-type, bad-return] # found is a SymNode in practice (LocalIntNode also has sym_sum) + return wrap_node(found.sym_sum([to_node(found, a) for a in items])) + + +# Drop in replacement for math.sqrt, math.sin, math.cos etc +def _get_sym_math_fn(name: str) -> _Callable[[_Any], _Any]: + def fn(a: _Any) -> _Any: + if overrides.has_torch_function_unary(a): + return overrides.handle_torch_function(fn, (a,), a) + if isinstance(a, SymInt): + a = torch.sym_float(a) + if hasattr(a, f"__sym_{name}__"): + return getattr(a, f"__sym_{name}__")() + return getattr(math, name)(a) + + return fn + + +__fn, __name, __sym_name = None, "", "" +for __name in ( + "sqrt", + "cos", + "cosh", + "sin", + "sinh", + "tan", + "tanh", + "asin", + "acos", + "atan", + "log2", +): + __sym_name = f"_sym_{__name}" + __fn = _get_sym_math_fn(__name) + __fn.__qualname__ = __fn.__name__ = __sym_name + globals()[__sym_name] = __fn + + +del __fn, __name, __sym_name, _get_sym_math_fn + +# Adding temporary shortcut +sym_sqrt = globals()["_sym_sqrt"] +__all__.append("sym_sqrt") + + +def sym_ite(b: "BoolLikeType", t: _SymIteT, f: _SymIteT) -> _SymIteT: + """SymInt-aware utility for ternary operator (``t if b else f``.)""" + if overrides.has_torch_function((b, t, f)): + return overrides.handle_torch_function(sym_ite, (b, t, f), b, t, f) + if not isinstance(b, (SymBool, builtins.bool)): + raise AssertionError(f"expected SymBool or bool, got {type(b)}") + if type(t) is not type(f): + raise AssertionError(f"type mismatch: {type(t)} vs {type(f)}") + if isinstance(b, SymBool): + return b.__sym_ite__(t, f) + return t if b else f + + +# Create a fresh unbacked int, from an (possibly unbacked int) expression. +def sym_fresh_size(expr: "IntLikeType") -> "IntLikeType": + return typing.cast("IntLikeType", torch.tensor(expr).item()) + + +# Check to see if we can load C extensions, and if not provide some guidance +# on what the problem might be. +try: + # _initExtension is chosen (arbitrarily) as a sentinel. + from torch._C import _initExtension +except ImportError: + import torch._C as _C_for_compiled_check + + if _C_for_compiled_check.__file__ is None: + raise ImportError( + textwrap.dedent( + """ + Failed to load PyTorch C extensions: + It appears that PyTorch has loaded the `torch/_C` folder + of the PyTorch repository rather than the C extensions which + are expected in the `torch._C` namespace. This can occur when + using the `install` workflow. e.g. + $ python -m pip install --no-build-isolation -v . && python -c "import torch" + + This error can generally be solved using the `develop` workflow + $ python -m pip install --no-build-isolation -v -e . && python -c "import torch" # This should succeed + or by running Python from a different directory. + """ + ).strip() + ) from None + raise # If __file__ is not None the cause is unknown, so just re-raise. + +# The torch._C submodule is already loaded via `from torch._C import *` above +# Make an explicit reference to the _C submodule to appease linters +from torch import _C as _C + + +__name, __obj = "", None +for __name in dir(_C): + if __name[0] != "_" and not __name.endswith("Base"): + __all__.append(__name) + __obj = getattr(_C, __name) + if callable(__obj) or inspect.isclass(__obj): + if __obj.__module__ != __name__: # "torch" + # TODO: fix their module from C++ side + if __name not in { + "DisableTorchFunctionSubclass", + "DisableTorchFunction", + "Generator", + }: + __obj.__module__ = __name__ # "torch" + elif __name == "TensorBase": + # issue 109438 / pr 109940. Prevent TensorBase from being copied into torch. + delattr(sys.modules[__name__], __name) + +del __name, __obj + +if not TYPE_CHECKING: + # issue 38137 and python issue 43367. Submodules of a C extension are + # non-standard, and attributes of those submodules cannot be pickled since + # pickle expect to be able to import them as "from _C.sub import attr" + # which fails with "_C is not a package + def _import_extension_to_sys_modules(module, memo=None): + if memo is None: + memo = set() + if module in memo: + return + memo.add(module) + module_name = module.__name__ + for name in dir(module): + member = getattr(module, name) + member_name = getattr(member, "__name__", "") + if inspect.ismodule(member) and member_name.startswith(module_name): + sys.modules.setdefault(member_name, member) + # Recurse for submodules (e.g., `_C._dynamo.eval_frame`) + _import_extension_to_sys_modules(member, memo) + + _import_extension_to_sys_modules(_C) + del _import_extension_to_sys_modules + +################################################################################ +# Define basic utilities +################################################################################ + + +def typename(obj: object, /) -> str: + """ + String representation of the type of an object. + + This function returns a fully qualified string representation of an object's type. + Args: + obj (object): The object whose type to represent + Returns: + str: the type of the object `o` + Example: + >>> x = torch.tensor([1, 2, 3]) + >>> torch.typename(x) + 'torch.LongTensor' + >>> torch.typename(torch.nn.Parameter) + 'torch.nn.parameter.Parameter' + """ + if isinstance(obj, torch.Tensor): + return obj.type() + + module = getattr(obj, "__module__", "") or "" + qualname = "" + + if hasattr(obj, "__qualname__"): + qualname = obj.__qualname__ # type: ignore[attr-defined] + elif hasattr(obj, "__name__"): + qualname = obj.__name__ # type: ignore[attr-defined] + else: + module = obj.__class__.__module__ or "" + qualname = obj.__class__.__qualname__ + + if module in {"", "builtins"}: + return qualname + return f"{module}.{qualname}" + + +def is_tensor(obj: object, /) -> _TypeIs["torch.Tensor"]: + r"""Returns True if `obj` is a PyTorch tensor. + + Args: + obj (object): Object to test + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> torch.is_tensor(x) + True + + """ + return isinstance(obj, torch.Tensor) + + +def is_storage(obj: object, /) -> _TypeGuard["TypedStorage | UntypedStorage"]: + r"""Returns True if `obj` is a PyTorch storage object. + + Args: + obj (Object): Object to test + Example:: + + >>> import torch + >>> # UntypedStorage (recommended) + >>> tensor = torch.tensor([1, 2, 3]) + >>> storage = tensor.untyped_storage() + >>> torch.is_storage(storage) + True + >>> + >>> # TypedStorage (legacy) + >>> warnings.filterwarnings("ignore", message=".*TypedStorage is deprecated") # docs: hide + >>> typed_storage = torch.TypedStorage(5, dtype=torch.float32) + >>> torch.is_storage(typed_storage) + True + >>> + >>> # regular tensor (should return False) + >>> torch.is_storage(tensor) + False + >>> + >>> # non-storage object + >>> torch.is_storage([1, 2, 3]) + False + """ + return type(obj) in _storage_classes + + +_GLOBAL_DEVICE_CONTEXT = threading.local() + + +def get_default_device() -> "torch.device": + r"""Gets the default ``torch.Tensor`` to be allocated on ``device``""" + global _GLOBAL_DEVICE_CONTEXT + + from torch.overrides import _get_current_function_mode_stack + from torch.utils._device import DeviceContext + + def _get_device_with_index(device: "torch.device") -> "torch.device": + if device.index is not None: + return device + else: + # TODO: Call like get_device_index() method corresponding to + # each device type + return torch.tensor([]).device + + # Get device from any active DeviceContext. + device_mode = next( + filter( + lambda mode: isinstance(mode, DeviceContext), + reversed(_get_current_function_mode_stack()), + ), + None, + ) + if device_mode: + device = device_mode.device + return _get_device_with_index(device) + + device_context = getattr(_GLOBAL_DEVICE_CONTEXT, "device_context", None) + if device_context is not None: + return _get_device_with_index(device_context.device) + return torch.device("cpu") + + +def set_default_device(device: "Device") -> None: + """Sets the default ``torch.Tensor`` to be allocated on ``device``. This + does not affect factory function calls which are called with an explicit + ``device`` argument. Factory calls will be performed as if they + were passed ``device`` as an argument. + + To only temporarily change the default device instead of setting it + globally, use ``with torch.device(device):`` instead. + + The default device is initially ``cpu``. If you set the default tensor + device to another device (e.g., ``cuda``) without a device index, tensors + will be allocated on whatever the current device for the device type, + even after :func:`torch.cuda.set_device` is called. + + .. warning:: + + This function imposes a slight performance cost on every Python + call to the torch API (not just factory functions). If this + is causing problems for you, please comment on + https://github.com/pytorch/pytorch/issues/92701 + + .. note:: + + This doesn't affect functions that create tensors that share the same memory as the input, like: + :func:`torch.from_numpy` and :func:`torch.frombuffer` + + Args: + device (:class:`torch.device`, str, int, or None): the device to set as + default, or ``None`` to clear the override. An integer is + interpreted as an index for the current accelerator. + + Example:: + + >>> # xdoctest: +SKIP("requires cuda, changes global state") + >>> torch.get_default_device() + device(type='cpu') + >>> torch.set_default_device('cuda') # current device is 0 + >>> torch.get_default_device() + device(type='cuda', index=0) + >>> torch.set_default_device('cuda') + >>> torch.cuda.set_device('cuda:1') # current device is 1 + >>> torch.get_default_device() + device(type='cuda', index=1) + >>> torch.set_default_device('cuda:1') + >>> torch.get_default_device() + device(type='cuda', index=1) + + """ + global _GLOBAL_DEVICE_CONTEXT + if hasattr(_GLOBAL_DEVICE_CONTEXT, "device_context"): + device_context = _GLOBAL_DEVICE_CONTEXT.device_context + if device_context is not None: + device_context.__exit__(None, None, None) + + if device is None: + device_context = None + else: + from torch.utils._device import DeviceContext + + device_context = DeviceContext(device) + device_context.__enter__() + _GLOBAL_DEVICE_CONTEXT.device_context = device_context + + +def set_default_tensor_type(t: type["torch.Tensor"] | str, /) -> None: + r""" + .. warning:: + + This function is deprecated as of PyTorch 2.1, please use :func:`torch.set_default_dtype()` and + :func:`torch.set_default_device()` as alternatives. + + Sets the default ``torch.Tensor`` type to floating point tensor type + ``t``. This type will also be used as default floating point type for + type inference in :func:`torch.tensor`. + + The default floating point tensor type is initially ``torch.FloatTensor``. + + Args: + t (type or string): the floating point tensor type or its name + + Example:: + + >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?") + >>> torch.tensor([1.2, 3]).dtype # initial default for floating point is torch.float32 + torch.float32 + >>> torch.set_default_tensor_type(torch.DoubleTensor) + >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor + torch.float64 + + """ + if isinstance(t, str): + t = _import_dotted_name(t) + _C._set_default_tensor_type(t) + + +def set_default_dtype(d: "torch.dtype", /) -> None: + r""" + + Sets the default floating point dtype to :attr:`d`. Supports floating point dtype + as inputs. Other dtypes will cause torch to raise an exception. + + When PyTorch is initialized its default floating point dtype is torch.float32, + and the intent of set_default_dtype(torch.float64) is to facilitate NumPy-like + type inference. The default floating point dtype is used to: + + 1. Implicitly determine the default complex dtype. When the default floating type is float16, + the default complex dtype is complex32. For float32, the default complex dtype is complex64. + For float64, it is complex128. For bfloat16, an exception will be raised because + there is no corresponding complex type for bfloat16. + 2. Infer the dtype for tensors constructed using Python floats or complex Python + numbers. See examples below. + 3. Determine the result of type promotion between bool and integer tensors and + Python floats and complex Python numbers. + + Args: + d (:class:`torch.dtype`): the floating point dtype to make the default. + + Example: + >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?") + >>> # initial default for floating point is torch.float32 + >>> # Python floats are interpreted as float32 + >>> torch.tensor([1.2, 3]).dtype + torch.float32 + >>> # initial default for floating point is torch.complex64 + >>> # Complex Python numbers are interpreted as complex64 + >>> torch.tensor([1.2, 3j]).dtype + torch.complex64 + + >>> torch.set_default_dtype(torch.float64) + >>> # Python floats are now interpreted as float64 + >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor + torch.float64 + >>> # Complex Python numbers are now interpreted as complex128 + >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor + torch.complex128 + + >>> torch.set_default_dtype(torch.float16) + >>> # Python floats are now interpreted as float16 + >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor + torch.float16 + >>> # Complex Python numbers are now interpreted as complex128 + >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor + torch.complex32 + + """ + _C._set_default_dtype(d) + + +def use_deterministic_algorithms( + mode: builtins.bool, + *, + warn_only: builtins.bool = False, +) -> None: + r"""Sets whether PyTorch operations must use "deterministic" + algorithms. That is, algorithms which, given the same input, and when + run on the same software and hardware, always produce the same output. + When enabled, operations will use deterministic algorithms when available, + and if only nondeterministic algorithms are available they will throw a + :class:`RuntimeError` when called. + + .. note:: This setting alone is not always enough to make an application + reproducible. Refer to :ref:`reproducibility` for more information. + + .. note:: :func:`torch.set_deterministic_debug_mode` offers an alternative + interface for this feature. + + The following normally-nondeterministic operations will act + deterministically when ``mode=True``: + + * :class:`torch.nn.Conv1d` when called on CUDA tensor + * :class:`torch.nn.Conv2d` when called on CUDA tensor + * :class:`torch.nn.Conv3d` when called on CUDA tensor + * :class:`torch.nn.ConvTranspose1d` when called on CUDA tensor + * :class:`torch.nn.ConvTranspose2d` when called on CUDA tensor + * :class:`torch.nn.ConvTranspose3d` when called on CUDA tensor + * :class:`torch.nn.ReplicationPad1d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReplicationPad2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReplicationPad3d` when attempting to differentiate a CUDA tensor + * :func:`torch.bmm` when called on sparse-dense CUDA tensors + * :func:`torch.cumsum` when called on a CUDA tensor when dtype is floating point or complex + * :func:`torch.Tensor.__getitem__` when attempting to differentiate a CPU tensor + and the index is a list of tensors + * :func:`torch.Tensor.index_put` with ``accumulate=False`` + * :func:`torch.Tensor.index_put` with ``accumulate=True`` when called on a CPU + tensor + * :func:`torch.Tensor.put_` with ``accumulate=True`` when called on a CPU + tensor + * :func:`torch.Tensor.scatter_add_` when called on a CUDA tensor + * :func:`torch.gather` when called on a CUDA tensor that requires grad + * :func:`torch.index_add` when called on CUDA tensor + * :func:`torch.index_select` when attempting to differentiate a CUDA tensor + * :func:`torch.repeat_interleave` when attempting to differentiate a CUDA tensor + * :func:`torch.Tensor.index_copy` when called on a CPU or CUDA tensor + * :func:`torch.Tensor.scatter` when `src` type is Tensor and called on CUDA tensor + * :func:`torch.Tensor.scatter_reduce` when ``reduce='sum'`` or ``reduce='mean'`` and called on CUDA tensor + * :class:`torch.nn.MaxPool3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.Embedding` when attempting to differentiate a CUDA tensor + + The following normally-nondeterministic operations will throw a + :class:`RuntimeError` when ``mode=True``: + + * :class:`torch.nn.AvgPool3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.AdaptiveAvgPool2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.AdaptiveAvgPool3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.AdaptiveMaxPool2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.FractionalMaxPool2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.FractionalMaxPool3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.MaxUnpool1d` + * :class:`torch.nn.MaxUnpool2d` + * :class:`torch.nn.MaxUnpool3d` + * :func:`torch.nn.functional.interpolate` when attempting to differentiate a CUDA tensor + and one of the following modes is used: + + - ``linear`` + - ``bilinear`` + - ``bicubic`` + - ``trilinear`` + + * :class:`torch.nn.ReflectionPad1d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReflectionPad2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReflectionPad3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.NLLLoss` when called on a CUDA tensor + * :class:`torch.nn.CTCLoss` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.EmbeddingBag` when attempting to differentiate a CUDA tensor when + ``mode='max'`` + * :func:`torch.Tensor.put_` when ``accumulate=False`` + * :func:`torch.Tensor.put_` when ``accumulate=True`` and called on a CUDA tensor + * :func:`torch.histc` when called on a CUDA tensor + * :func:`torch.bincount` when called on a CUDA tensor and ``weights`` + tensor is given + * :func:`torch.median` with indices output when called on a CUDA tensor + * :func:`torch.nn.functional.grid_sample` when attempting to differentiate a CUDA tensor + * :func:`torch.Tensor.scatter_reduce` when ``reduce='prod'`` and called on CUDA tensor + * :func:`torch.Tensor.resize_` when called with a quantized tensor + + In addition, several operations fill uninitialized memory when this setting + is turned on and when + :attr:`torch.utils.deterministic.fill_uninitialized_memory` is turned on. + See the documentation for that attribute for more information. + + Note that deterministic operations tend to have worse performance than + nondeterministic operations. + + + When this setting is turned on, the Inductor deterministic mode is also tuned on + automatically. In deterministic mode, Inductor would avoid doing on device benchmarking + that affect numerics. This includes: + + - don't pad matmul input shapes. Without enabling deterministic mode, Inductor would do + benchmarking to check if padding matmul shape is beneficial. + - don't autotune templates. Inductor has templates for kernels like matmul/conv/attention. + Without enabling deterministic mode, Inductor would do autotuning to + pick the best configs for those templates and adopt it if it's faster + than the kernel in eager mode. In deterministic mode, we pick the eager kernel. + - don't autotune triton configs for reduction. Reduction numerics are + very sensitive to triton configs. In deterministic mode, Inductor + will use some heuristics to pick the most promising configs rather + than do autotuning. + - Skip autotuning for reduction in coordinate descent tuning. + - Don't benchmark for the computation/communication reordering pass + - Disable the feature that dynamically scale down RBLOCK triton config for higher + occupancy. + + + .. note:: + + This flag does not detect or prevent nondeterministic behavior caused + by calling an inplace operation on a tensor with an internal memory + overlap or by giving such a tensor as the :attr:`out` argument for an + operation. In these cases, multiple writes of different data may target + a single memory location, and the order of writes is not guaranteed. + + Args: + mode (:class:`bool`): If True, makes potentially nondeterministic + operations switch to a deterministic algorithm or throw a runtime + error. If False, allows nondeterministic operations. + + Keyword args: + warn_only (:class:`bool`, optional): If True, operations that do not + have a deterministic implementation will throw a warning instead of + an error. Default: ``False`` + + Example:: + + >>> # xdoctest: +SKIP + >>> torch.use_deterministic_algorithms(True) + + # Backward mode nondeterministic error + >>> torch.nn.AvgPool3d(1)(torch.randn(3, 4, 5, 6, requires_grad=True).cuda()).sum().backward() + ... + RuntimeError: avg_pool3d_backward_cuda does not have a deterministic implementation... + """ + import torch._inductor.config as inductor_config + + inductor_config.deterministic = mode + _C._set_deterministic_algorithms(mode, warn_only=warn_only) + + +def are_deterministic_algorithms_enabled() -> builtins.bool: + r"""Returns True if the global deterministic flag is turned on. Refer to + :func:`torch.use_deterministic_algorithms` documentation for more details. + """ + return _C._get_deterministic_algorithms() + + +def is_deterministic_algorithms_warn_only_enabled() -> builtins.bool: + r"""Returns True if the global deterministic flag is set to warn only. + Refer to :func:`torch.use_deterministic_algorithms` documentation for more + details. + """ + return _C._get_deterministic_algorithms_warn_only() + + +def set_deterministic_debug_mode(debug_mode: builtins.int | str) -> None: + r"""Sets the debug mode for deterministic operations. + + .. note:: This is an alternative interface for + :func:`torch.use_deterministic_algorithms`. Refer to that function's + documentation for details about affected operations. + + Args: + debug_mode(str or int): If "default" or 0, don't error or warn on + nondeterministic operations. If "warn" or 1, warn on + nondeterministic operations. If "error" or 2, error on + nondeterministic operations. + """ + + # NOTE: builtins.int is used here because int in this scope resolves + # to torch.int + if not isinstance(debug_mode, (builtins.int, str)): + raise TypeError(f"debug_mode must be str or int, but got {type(debug_mode)}") + + if isinstance(debug_mode, str): + if debug_mode == "default": + debug_mode = 0 + elif debug_mode == "warn": + debug_mode = 1 + elif debug_mode == "error": + debug_mode = 2 + else: + raise RuntimeError( + "invalid value of debug_mode, expected one of `default`, " + f"`warn`, `error`, but got {debug_mode}" + ) + + if debug_mode == 0: + _C._set_deterministic_algorithms(False) + elif debug_mode == 1: + _C._set_deterministic_algorithms(True, warn_only=True) + elif debug_mode == 2: + _C._set_deterministic_algorithms(True) + else: + raise RuntimeError( + f"invalid value of debug_mode, expected 0, 1, or 2, but got {debug_mode}" + ) + + +def get_deterministic_debug_mode() -> builtins.int: + r"""Returns the current value of the debug mode for deterministic + operations. Refer to :func:`torch.set_deterministic_debug_mode` + documentation for more details. + """ + + if _C._get_deterministic_algorithms(): + if _C._get_deterministic_algorithms_warn_only(): + return 1 + else: + return 2 + else: + return 0 + + +def get_float32_matmul_precision() -> str: + r"""Returns the current value of float32 matrix multiplication precision. Refer to + :func:`torch.set_float32_matmul_precision` documentation for more details. + """ + return _C._get_float32_matmul_precision() + + +def set_float32_matmul_precision(precision: str) -> None: + r"""Sets the internal precision of float32 matrix multiplications. + + Running float32 matrix multiplications in lower precision may significantly increase + performance, and in some programs the loss of precision has a negligible impact. + + Supports three settings: + + * "highest", float32 matrix multiplications use the float32 datatype (24 mantissa + bits with 23 bits explicitly stored) for internal computations. + * "high", float32 matrix multiplications either use the TensorFloat32 datatype (10 + mantissa bits explicitly stored) or treat each float32 number as the sum of two bfloat16 numbers + (approximately 16 mantissa bits with 14 bits explicitly stored), if the appropriate fast matrix multiplication + algorithms are available. Otherwise float32 matrix multiplications are computed + as if the precision is "highest". See below for more information on the bfloat16 + approach. + * "medium", float32 matrix multiplications use the bfloat16 datatype (8 mantissa + bits with 7 bits explicitly stored) for internal computations, if a fast matrix multiplication algorithm + using that datatype internally is available. Otherwise float32 + matrix multiplications are computed as if the precision is "high". + + When using "high" precision, float32 multiplications may use a bfloat16-based algorithm + that is more complicated than simply truncating to some smaller number mantissa bits + (e.g. 10 for TensorFloat32, 7 for bfloat16 explicitly stored). Refer to [Henry2019]_ for a complete + description of this algorithm. To briefly explain here, the first step is to realize + that we can perfectly encode a single float32 number as the sum of three bfloat16 + numbers (because float32 has 23 mantissa bits while bfloat16 has 7 explicitly stored, and both have the + same number of exponent bits). This means that the product of two float32 numbers can + be exactly given by the sum of nine products of bfloat16 numbers. We can then trade + accuracy for speed by dropping some of these products. The "high" precision algorithm + specifically keeps only the three most significant products, which conveniently excludes + all of the products involving the last 8 mantissa bits of either input. This means that + we can represent our inputs as the sum of two bfloat16 numbers rather than three. + Because bfloat16 fused-multiply-add (FMA) instructions are typically >10x faster than + float32 ones, it's faster to do three multiplications and 2 additions with bfloat16 + precision than it is to do a single multiplication with float32 precision. + + .. [Henry2019] http://arxiv.org/abs/1904.06376 + + .. note:: + + This does not change the output dtype of float32 matrix multiplications, + it controls how the internal computation of the matrix multiplication is performed. + + .. note:: + + This does not change the precision of convolution operations. Other flags, + like `torch.backends.cudnn.allow_tf32`, may control the precision of convolution + operations. + + .. note:: + + This flag currently only affects one native device type: CUDA. + If "high" or "medium" are set then the TensorFloat32 datatype will be used + when computing float32 matrix multiplications, equivalent to setting + `torch.backends.cuda.matmul.allow_tf32 = True`. When "highest" (the default) + is set then the float32 datatype is used for internal computations, equivalent + to setting `torch.backends.cuda.matmul.allow_tf32 = False`. + + Args: + precision(str): can be set to "highest" (default), "high", or "medium" (see above). + + """ + _C._set_float32_matmul_precision(precision) + + +def set_warn_always(b: builtins.bool, /) -> None: + r"""When this flag is False (default) then some PyTorch warnings may only + appear once per process. This helps avoid excessive warning information. + Setting it to True causes these warnings to always appear, which may be + helpful when debugging. + + Args: + b (:class:`bool`): If True, force warnings to always be emitted + If False, set to the default behaviour + """ + _C._set_warnAlways(b) + + +def is_warn_always_enabled() -> builtins.bool: + r"""Returns True if the global warn_always flag is turned on. Refer to + :func:`torch.set_warn_always` documentation for more details. + """ + return _C._get_warnAlways() + + +################################################################################ +# Define error checking functions +################################################################################ + +# These error checking functions must be kept consistent with their C++ +# equivalents. Their C++ equivalents are mentioned where applicable. + + +def _check_with( + error_type: type[BaseException], + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None, +) -> None: + if not isinstance(cond, (builtins.bool, SymBool)): + if isinstance(cond, torch.Tensor): + raise TypeError( + "cond must be a bool, but got a Tensor. " + "For tensor conditions, use torch._check_tensor_all() " + "to assert that all elements are true." + ) + raise TypeError(f"cond must be a bool, but got {type(cond)}") + + from torch.fx.experimental.symbolic_shapes import expect_true + + if expect_true(cond): + return + + # error_type must be a subclass of Exception and not subclass of Warning + if not issubclass(error_type, Exception) or issubclass(error_type, Warning): + raise AssertionError( + f"error_type must be a subclass of Exception but not Warning, got {error_type}" + ) + + if message is None: + message_evaluated = ( + "Expected cond to be True, but got False. (Could this error " + "message be improved? If so, please report an enhancement request " + "to PyTorch.)" + ) + + else: + # message may be a callable (deferred construction) or a plain + # str/object; both are accepted. + message_evaluated = str(message() if callable(message) else message) + + raise error_type(message_evaluated) + + +def _check( + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``RuntimeError`` + + C++ equivalent: ``TORCH_CHECK`` + + Args: + cond (:class:`bool`): If False, throw error + + message (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_with(RuntimeError, cond, message) + + +@_deprecated( + "_check_is_size will be removed in a future PyTorch release along with guard_size_oblivious. \ + Use _check(i >= 0) instead.", + category=FutureWarning, +) +def _check_is_size( + i: "IntLikeType", + message: _LiteralString | _Callable[[], object] | None = None, + *, + max: "IntLikeType | None" = None, +) -> None: + """Checks that a given integer is a valid size (i.e., is non-negative). + You should use this over ``_check(i >= 0)`` because it can prevent + ``GuardOnDataDependentSymNode`` exceptions by opting yourself into alternate + semantics for ``guard_size_oblivious`` tests that treat values 0 and 1 + equivalently to all other values. + + When max is not None, this specifies an upper bound equivalent to + ``_check(i <= max)``. This bound is also subject to alternate semantics: + in ``guard_size_oblivious`` tests, we assume that a constant max bound is + treated equivalently to all other values. Symbolic max bounds are not yet + supported. + + NB: Do NOT use this in contexts where a -1 size would be valid (indicating + to infer the size from context, or if you should wrap-around or truncate). + Only use this if the only valid value is an honest to goodness size. + """ + # This is responsible for the expect_true + _check(i >= 0, message) + from torch.fx.experimental.symbolic_shapes import _advise_is_size + + _advise_is_size(i) # type: ignore[arg-type] + + if max is not None: + _check(i <= max, message) + + from torch.fx.experimental.symbolic_shapes import _advise_is_bounded + + _advise_is_bounded(i, max) # type: ignore[arg-type] + + +def _check_index( + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``IndexError`` + + C++ equivalent: ``TORCH_CHECK_INDEX`` + + Args: + cond (:class:`bool`): If False, throw error + + message (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_with(IndexError, cond, message) + + +def _check_value( + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``ValueError`` + + C++ equivalent: ``TORCH_CHECK_VALUE`` + + Args: + cond (:class:`bool`): If False, throw error + + message (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_with(ValueError, cond, message) + + +def _check_type( + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``TypeError`` + + C++ equivalent: ``TORCH_CHECK_TYPE`` + + Args: + cond (:class:`bool`): If False, throw error + + message (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_with(TypeError, cond, message) + + +def _check_not_implemented( + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``NotImplementedError`` + + C++ equivalent: ``TORCH_CHECK_NOT_IMPLEMENTED`` + + Args: + cond (:class:`bool`): If False, throw error + + message (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_with(NotImplementedError, cond, message) + + +def _check_tensor_all_with( + error_type: type[BaseException], + cond: "torch.Tensor", + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + if not is_tensor(cond): + raise TypeError(f"cond must be a tensor, but got {type(cond)}") + + if not cond.dtype == torch.bool: + raise TypeError(f"cond tensor must have dtype torch.bool, but got {cond.dtype}") + + _check_with(error_type, cond._is_all_true().item(), message) # type: ignore[arg-type] + + +# C++ equivalent: `TORCH_CHECK_TENSOR_ALL` +def _check_tensor_all( + cond: "torch.Tensor", + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + r"""Throws error containing an optional message if the specified condition + is False. + + Error type: ``RuntimeError`` + + C++ equivalent: ``TORCH_CHECK_TENSOR_ALL`` + + Args: + cond (:class:`torch.Tensor`): Tensor of dtype ``torch.bool``. If any + element is ``False``, throw error + + message (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_tensor_all_with(RuntimeError, cond, message) + + +################################################################################ +# Define numeric constants +################################################################################ + +# For Python Array API (https://data-apis.org/array-api/latest/API_specification/constants.html) and +# NumPy consistency (https://numpy.org/devdocs/reference/constants.html) +from math import e, inf, nan, pi + + +newaxis: None = None + +__all__.extend(["e", "pi", "nan", "inf", "newaxis"]) + +################################################################################ +# Define Storage and Tensor classes +################################################################################ + +from torch._tensor import Tensor # usort: skip + +# needs to be after torch.Tensor is defined to avoid circular dependencies +from torch import storage as storage # usort: skip +from torch.storage import ( + _LegacyStorage, + _StorageBase, + _warn_typed_storage_removal, + TypedStorage, + UntypedStorage, +) + + +# NOTE: New Storage classes should never be added. When adding a new +# dtype, use torch.storage.TypedStorage directly. +class ByteStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.uint8 + + +class DoubleStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.double + + +class FloatStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.float + + +class HalfStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.half + + +class LongStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.long + + +class IntStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.int + + +class ShortStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.short + + +class CharStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.int8 + + +class BoolStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.bool + + +class BFloat16Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.bfloat16 + + +class ComplexDoubleStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.cdouble + + +class ComplexFloatStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.cfloat + + +class QUInt8Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.quint8 + + +class QInt8Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.qint8 + + +class QInt32Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.qint32 + + +class QUInt4x2Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.quint4x2 + + +class QUInt2x4Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.quint2x4 + + +_storage_classes: set[type[TypedStorage | UntypedStorage]] = { + UntypedStorage, + DoubleStorage, + FloatStorage, + LongStorage, + IntStorage, + ShortStorage, + CharStorage, + ByteStorage, + HalfStorage, + BoolStorage, + QUInt8Storage, + QInt8Storage, + QInt32Storage, + BFloat16Storage, + ComplexFloatStorage, + ComplexDoubleStorage, + QUInt4x2Storage, + QUInt2x4Storage, + TypedStorage, +} + +# The _tensor_classes set is initialized by the call to initialize_python_bindings. +_tensor_classes: set[type["torch.Tensor"]] = set() + +# If you edit these imports, please update torch/__init__.py.in as well +from torch import amp as amp, random as random, serialization as serialization +from torch._tensor_str import set_printoptions +from torch.amp import autocast, GradScaler +from torch.random import ( + get_rng_state, + initial_seed, + manual_seed, + seed, + set_rng_state, + thread_safe_generator, +) +from torch.serialization import load, save + + +################################################################################ +# Initialize extension +################################################################################ + + +# Shared memory manager needs to know the exact location of manager executable +def _manager_path() -> bytes: + if platform.system() == "Windows": + return b"" + path = get_file_path("torch", "bin", "torch_shm_manager") + prepare_multiprocessing_environment(get_file_path("torch")) + if not os.path.exists(path): + raise RuntimeError("Unable to find torch_shm_manager at " + path) + return path.encode("utf-8") + + +_C._initExtension(_manager_path()) # pyrefly: ignore[bad-argument-type] + +del _manager_path + +# Appease the type checker: it can't deal with direct setting of globals(). +# Note that we will see "too many" functions when reexporting this way; there +# is not a good way to fix this problem. Perhaps, try to redesign VariableFunctions +# so that this import is good enough +if TYPE_CHECKING: + # Some type signatures pulled in from _VariableFunctions here clash with + # signatures already imported. For now these clashes are ignored; see + # PR #43339 for details. + from torch._C._VariableFunctions import * # type: ignore[assignment, misc] # noqa: F403 + + # Fixup segment_reduce visibility + _segment_reduce = segment_reduce + del segment_reduce # noqa: F821 + +# Ops not to be exposed in `torch` namespace, +# mostly helper ops. +PRIVATE_OPS = ("unique_dim",) + +__name, __obj = "", None +for __name in dir(_C._VariableFunctions): + if __name.startswith("__") or __name in PRIVATE_OPS: + continue + __obj = getattr(_C._VariableFunctions, __name) + __obj.__module__ = __name__ # "torch" + # Hide some APIs that should not be public + if __name == "segment_reduce": + # TODO: Once the undocumented FC window is passed, remove the line below + globals()[__name] = __obj + __name = "_" + __name + globals()[__name] = __obj + if not __name.startswith("_"): + __all__.append(__name) + +del __name, __obj + +################################################################################ +# Add torch.dtype instances to the public API +################################################################################ + +import torch + + +__all__.extend( + # pyrefly: ignore [unresolvable-dunder-all] + name + for name in dir(torch) + if isinstance(getattr(torch, name), torch.dtype) +) + +################################################################################ +# Import TorchDynamo's lazy APIs to avoid circular dependencies +################################################################################ + +# needs to be before from torch.functional import * to avoid circular dependencies +from torch._compile import _disable_dynamo # usort: skip + +################################################################################ +# Import interface functions defined in Python +################################################################################ + +# needs to be after the above ATen bindings so we can overwrite from Python side +from torch import _VF as _VF, functional as functional # usort: skip +from torch.functional import * # usort: skip # noqa: F403 + +################################################################################ +# Remove unnecessary members +################################################################################ + +del _StorageBase +del _LegacyStorage + +################################################################################ +# Define _assert +################################################################################ + + +# needs to be before the submodule imports to avoid circular dependencies +def _assert(condition: object, message: object) -> None: + r"""A wrapper around Python's assert which is symbolically traceable.""" + if type(condition) is not torch.Tensor and overrides.has_torch_function( + (condition,) + ): + return overrides.handle_torch_function( + _assert, (condition,), condition, message + ) + if not condition: + raise AssertionError(message) + + +################################################################################ +# Import most common subpackages +################################################################################ + +# Use the redundant form so that type checkers know that these are a part of +# the public API. The "regular" import lines are there solely for the runtime +# side effect of adding to the imported module's members for other users. + +# needs to be before import torch.nn as nn to avoid circular dependencies +from torch.autograd import ( # usort: skip + enable_grad as enable_grad, + inference_mode as inference_mode, + no_grad as no_grad, + set_grad_enabled as set_grad_enabled, +) + +from torch import ( + __config__ as __config__, + __future__ as __future__, + _awaits as _awaits, + accelerator as accelerator, + autograd as autograd, + backends as backends, + cpu as cpu, + cuda as cuda, + distributed as distributed, + distributions as distributions, + fft as fft, + futures as futures, + hub as hub, + jit as jit, + linalg as linalg, + mps as mps, + mtia as mtia, + multiprocessing as multiprocessing, + nested as nested, + nn as nn, + optim as optim, + overrides as overrides, + profiler as profiler, + sparse as sparse, + special as special, + testing as testing, + types as types, + utils as utils, + version as version, + xpu as xpu, +) +from torch.signal import windows as windows + + +# Quantized, sparse, AO, etc. should be last to get imported, as nothing +# is expected to depend on them. +from torch import ao as ao # usort: skip + +# nn.quant* depends on ao -- so should be after those. +import torch.nn.intrinsic +import torch.nn.qat +import torch.nn.quantizable +import torch.nn.quantized + + +_C._init_names(list(_storage_classes)) + +# attach docstrings to torch and tensor functions +from torch import _size_docs, _storage_docs, _tensor_docs, _torch_docs + + +del _torch_docs, _tensor_docs, _storage_docs, _size_docs + + +def compiled_with_cxx11_abi() -> builtins.bool: + r"""Returns whether PyTorch was built with _GLIBCXX_USE_CXX11_ABI=1""" + return True + + +from torch import _library as _library, _ops as _ops + + +# Import the ops and classes "namespace" +from torch._ops import ops as ops # usort: skip +from torch._classes import classes as classes # usort: skip + +sys.modules.setdefault(f"{__name__}.ops", ops) +sys.modules.setdefault(f"{__name__}.classes", classes) + +if hasattr(torch._C, "_c10d_init"): + from torch.distributed.distributed_c10d import _register_process_group_opaque_type + + _register_process_group_opaque_type() + del _register_process_group_opaque_type + +# quantization depends on torch.fx and torch.ops +# Import quantization +from torch import quantization as quantization # usort: skip + +# Import the quasi random sampler +from torch import quasirandom as quasirandom # usort: skip + +# If you are seeing this, it means that this call site was not checked if +# the memory format could be preserved, and it was switched to old default +# behaviour of contiguous +legacy_contiguous_format = contiguous_format # defined by _C._initExtension() + +# Register fork handler to initialize OpenMP in child processes (see gh-28389) +from torch.multiprocessing._atfork import register_after_fork + + +register_after_fork(torch.get_num_threads) +del register_after_fork + +# Import tools that require fully imported torch (for applying +# torch.jit.script as a decorator, for instance): +from torch._lobpcg import lobpcg as lobpcg + + +# These were previously defined in native_functions.yaml and appeared on the +# `torch` namespace, but we moved them to c10 dispatch to facilitate custom +# class usage. We add these lines here to preserve backward compatibility. +quantized_lstm = ops.aten.quantized_lstm +quantized_gru = ops.aten.quantized_gru + +# Import experimental masked operations support. See +# [RFC-0016](https://github.com/pytorch/rfcs/pull/27) for more +# information. +from torch import masked as masked + +# Import removed ops with error message about removal +from torch._linalg_utils import ( # type: ignore[misc] + _symeig as symeig, + cholesky, + eig, + lstsq, + matrix_rank, + qr, + solve, +) +from torch.utils.dlpack import from_dlpack, to_dlpack + + +class _TorchCompileInductorWrapper: + compiler_name = "inductor" + + def __init__( + self, + mode: str | None, + options: dict[str, _Any] | None, + dynamic: builtins.bool | None, + name: str | None = None, + ) -> None: + from torch._inductor.compiler_bisector import CompilerBisector + + self.config: dict[str, _Any] = {} + self.dynamic = dynamic + self.name = name + self.apply_mode(mode) + self.apply_options(options) + self.apply_options(CompilerBisector.get_config_change("inductor")) + + cuda_version = None + if hasattr(torch, "version"): + from torch.torch_version import TorchVersion + + cuda_version = TorchVersion(getattr(torch.version, "cuda", "0.0")) + + if self.config.get("triton.cudagraphs", False) and ( + (cuda_version and cuda_version < "12.6") + or not profiler_allow_cudagraph_cupti_lazy_reinit_cuda12() + ): + os.environ["DISABLE_CUPTI_LAZY_REINIT"] = "1" + # FIXME: CUDA Graph does not work well with CUPTI teardown. + # 1) crashes on 1st lazy CUPTI re-init after teardown (CUDA 11) + # 2) crashes on 2nd non-lazy CUPTI re-init after teardown (CUDA 12) + # Workaround: turn off CUPTI teardown when using CUDA Graphs. + os.environ["TEARDOWN_CUPTI"] = "0" + + def __eq__(self, other: object) -> builtins.bool: + return ( + isinstance(other, _TorchCompileInductorWrapper) + and self.config == other.config + and self.dynamic == other.dynamic + and self.name == other.name + ) + + def apply_mode(self, mode: str | None) -> None: + if mode and mode != "default": + from torch._inductor import list_mode_options + + self.apply_options(list_mode_options(mode, self.dynamic)) + + def apply_options(self, options: dict[str, _Any] | None) -> None: + if not options: + return + + from torch._inductor import config + + current_config: dict[str, _Any] = config.get_config_copy() + + for key, val in options.items(): + attr_name = key.replace("-", "_") + if attr_name not in current_config: + raise RuntimeError( + f"Unexpected optimization option {key}, known options are {list(current_config.keys())}" + ) + attr_type = config.get_type(attr_name) # type: ignore[attr-defined] + # Subscriptable generic types don't support isinstance so skip the type + # check. There doesn't seem to be a good way of checking membership without + # 3rd party libraries. + if _get_origin(attr_type) is None: + if not isinstance(val, attr_type): + val_type_str = type(val).__name__ + expected_type_str = type(current_config[attr_name]).__name__ + raise RuntimeError( + f"Unexpected type of attr {key}, got {val_type_str} should be {expected_type_str}" + ) + self.config[attr_name] = val + + def __call__( + self, + model_: _Any, + inputs_: _Any, + *, + config_patches: dict[str, _Any] | None = None, + ) -> _Any: + from torch._inductor.compile_fx import compile_fx + + all_patches = {**self.config, **(config_patches or {})} + return compile_fx( + model_, + inputs_, + config_patches=all_patches, + compile_region_name=self.name, + ) + + def get_compiler_config(self) -> dict[str, _Any]: + from torch._inductor.compile_fx import get_patched_config_dict + + return get_patched_config_dict(config_patches=self.config) + + def reset(self) -> None: + from torch._inductor import config + + if "triton.cudagraphs" in self.config or config.triton.cudagraphs: + if self.config.get("triton.cudagraphs", True): + from torch._inductor.cudagraph_trees import reset_cudagraph_trees + + reset_cudagraph_trees() + + +class _TorchCompileAOTInductorWrapper(_TorchCompileInductorWrapper): + compiler_name = "aotinductor" + + def __init__( + self, + mode: str | None, + options: dict[str, _Any] | None, + dynamic: builtins.bool | None, + name: str | None = None, + ) -> None: + super().__init__(mode, options, dynamic, name) + self.apply_options({"cpp_wrapper": True}) + self.apply_options({"aot_inductor.package": True}) + + def __call__( + self, + model_: _Any, + inputs_: _Any, + *, + config_patches: dict[str, _Any] | None = None, + ) -> _Any: + from contextlib import nullcontext + from unittest import mock + + from torch._guards import detect_fake_mode + from torch._inductor.virtualized import V + + fake_mode = detect_fake_mode(inputs_) + ctx = ( + mock.patch.object(fake_mode, "allow_non_fake_inputs", True) + if fake_mode + else nullcontext() + ) + with ( + V.set_aot_compilation(True), + ctx, + torch._inductor.config.patch("enable_autograd_for_aot", True), + ): + return super().__call__(model_, inputs_, config_patches=config_patches) + + +class _TorchCompileWrapper: + def __init__( + self, + backend: str | _Callable[..., _Any], + mode: str | None, + options: dict[str, _Any] | None, + dynamic: builtins.bool | None, + ) -> None: + from torch._dynamo.backends.registry import lookup_backend + + if isinstance(backend, str): + self.compiler_name = backend + elif hasattr(backend, "__name__"): + self.compiler_name = backend.__name__ + else: + self.compiler_name = str(backend) + self.dynamic = dynamic + self.compiler_fn = lookup_backend(backend) + self.kwargs: dict[str, _Any] = {} + # only pass the args if they non-empty + if mode and mode != "default": + self.kwargs["mode"] = mode + if options: + self.kwargs["options"] = options + + def __eq__(self, other: object) -> builtins.bool: + return ( + isinstance(other, _TorchCompileWrapper) + and self.compiler_fn == other.compiler_fn + and self.kwargs == other.kwargs + and self.dynamic == other.dynamic + ) + + def __call__(self, model_: _Any, inputs_: _Any) -> _Any: + return self.compiler_fn(model_, inputs_, **self.kwargs) + + def reset(self) -> None: + if hasattr(self.compiler_fn, "reset"): + self.compiler_fn.reset() + + +_InputT = _ParamSpec("_InputT") +_RetT = _TypeVar("_RetT") + + +@_overload +def compile( + model: _Callable[_InputT, _RetT], + *, + fullgraph: builtins.bool = False, + dynamic: builtins.bool | None = None, + backend: str | _Callable[..., _Any] = "inductor", + mode: str | None = None, + options: dict[str, str | builtins.int | builtins.bool | _Callable[..., _Any]] + | None = None, + name: str | None = None, + disable: builtins.bool = False, + dynamic_shapes: _Any = None, +) -> _Callable[_InputT, _RetT]: ... + + +@_overload +def compile( + model: None = None, + *, + fullgraph: builtins.bool = False, + dynamic: builtins.bool | None = None, + backend: str | _Callable[..., _Any] = "inductor", + mode: str | None = None, + options: dict[str, str | builtins.int | builtins.bool | _Callable[..., _Any]] + | None = None, + name: str | None = None, + disable: builtins.bool = False, + dynamic_shapes: _Any = None, +) -> _Callable[[_Callable[_InputT, _RetT]], _Callable[_InputT, _RetT]]: ... + + +def compile( + model: _Callable[_InputT, _RetT] | None = None, + *, + fullgraph: builtins.bool = False, + dynamic: builtins.bool | None = None, + backend: str | _Callable[..., _Any] | None = None, + mode: str | None = None, + options: dict[str, str | builtins.int | builtins.bool | _Callable[..., _Any]] + | None = None, + name: str | None = None, + disable: builtins.bool = False, + recompile_limit: builtins.int | None = None, + isolate_recompiles: builtins.bool = False, + dynamic_shapes: _Any = None, +) -> ( + _Callable[[_Callable[_InputT, _RetT]], _Callable[_InputT, _RetT]] + | _Callable[_InputT, _RetT] +): + """ + Optimizes given model/function using TorchDynamo and specified backend. + If you are compiling an :class:`torch.nn.Module`, you can also use :meth:`torch.nn.Module.compile` + to compile the module inplace without changing its structure. + + Concretely, for every frame executed within the compiled region, we will attempt + to compile it and cache the compiled result on the code object for future + use. A single frame may be compiled multiple times if previous compiled + results are not applicable for subsequent calls (this is called a "guard + failure"), you can use TORCH_LOGS=guards to debug these situations. + Multiple compiled results can be associated with a frame up to + ``torch._dynamo.config.recompile_limit``, which defaults to 8; at which + point we will fall back to eager. Note that compile caches are per + *code object*, not frame; if you dynamically create multiple copies of a + function, they will all share the same code cache. + + Args: + model (Callable or None): Module/function to optimize + fullgraph (bool): If False (default), torch.compile attempts to discover compilable regions + in the function that it will optimize. If True, then we require that the entire function be + capturable into a single graph. If this is not possible (that is, if there are graph breaks), + then this will raise an error. This also opts into unbacked semantics, notably it will turn on + capture_scalar_outputs and capture_dynamic_output_shape_ops on by default. + dynamic (bool or None): Use dynamic shape tracing. When this is True, we will up-front attempt + to generate a kernel that is as dynamic as possible to avoid recompilations when + sizes change. This may not always work as some operations/optimizations will + force specialization; use TORCH_LOGS=dynamic to debug overspecialization. + When this is False, we will NEVER generate dynamic kernels, we will always specialize. + By default (None), we automatically detect if dynamism has occurred and compile a more + dynamic kernel upon recompile. + backend (str or Callable): backend to be used + + - "inductor" is the default backend, which is a good balance between performance and overhead + + - Non experimental in-tree backends can be seen with `torch._dynamo.list_backends()` + + - Experimental or debug in-tree backends can be seen with `torch._dynamo.list_backends(None)` + + - To register an out-of-tree custom backend: + https://docs.pytorch.org/docs/main/user_guide/torch_compiler/torch.compiler_custom_backends.html#registering-custom-backends + mode (str): Can be either "default", "reduce-overhead", "max-autotune" or "max-autotune-no-cudagraphs" + + - "default" is the default mode, which is a good balance between performance and overhead + + - "reduce-overhead" is a mode that reduces the overhead of python with CUDA graphs, + useful for small batches. Reduction of overhead can come at the cost of more memory + usage, as we will cache the workspace memory required for the invocation so that we + do not have to reallocate it on subsequent runs. Reduction of overhead is not guaranteed + to work; today, we only reduce overhead for CUDA only graphs which do not mutate inputs. + There are other circumstances where CUDA graphs are not applicable; use TORCH_LOGS=perf_hints + to debug. + + - "max-autotune" is a mode that leverages Triton or template based matrix multiplications + on supported devices and Triton based convolutions on GPU. + It enables CUDA graphs by default on GPU. + + - "max-autotune-no-cudagraphs" is a mode similar to "max-autotune" but without CUDA graphs + + - To see the exact configs that each mode sets you can call `torch._inductor.list_mode_options()` + + options (dict): A dictionary of options to pass to the backend. Some notable ones to try out are + + - `epilogue_fusion` which fuses pointwise ops into templates. Requires `max_autotune` to also be set + + - `max_autotune` which will profile to pick the best matmul configuration + + - `fallback_random` which is useful when debugging accuracy issues + + - `shape_padding` which pads matrix shapes to better align loads on GPUs especially for tensor cores + + - `triton.cudagraphs` which will reduce the overhead of python with CUDA graphs + + - `trace.enabled` which is the most useful debugging flag to turn on + + - `trace.graph_diagram` which will show you a picture of your graph after fusion + + - `guard_filter_fn` that controls which dynamo guards are saved with compilations. + This is an unsafe feature and there is no backward compatibility guarantee provided + for dynamo guards as data types. + For stable helper functions to use, see the documentation in `torch.compiler`, for example: + - `torch.compiler.skip_guard_on_inbuilt_nn_modules_unsafe` + - `torch.compiler.skip_guard_on_all_nn_modules_unsafe` + - `torch.compiler.keep_tensor_guards_unsafe` + + - For inductor you can see the full list of configs that it supports by calling `torch._inductor.list_options()` + name (str or None): Optional identifier for the compiled region. When supported by downstream + tooling, this is surfaced on wrapped compiled-region higher-order operators and other debug metadata. + disable (bool): Turn torch.compile() into a no-op for testing + recompile_limit (int or None): Maximum number of recompilations allowed for this + ``torch.compile()`` call before falling back to eager. If None (default), uses + the global ``torch._dynamo.config.recompile_limit`` (default 8). With + ``fullgraph=True``, exceeding the limit raises ``FailOnRecompileLimitHit``. + isolate_recompiles (bool): If True, this ``torch.compile()`` call tracks + recompilations independently. By default, all ``torch.compile()`` calls on the + same function share a single set of compiled entries, so one call's + recompilations count against every other call's limit. With + ``isolate_recompiles=True``, each call gets its own isolated set of entries. + Lookups for an isolated compile call will still fall back to entries from + non-isolated compile calls (BC-friendly reuse), but new compilations are + stored separately. ``recompile_limit`` is checked per-region; + ``accumulated_recompile_limit`` is a global cap across all regions. + Default-strategy behavior is asymmetric: SKIP decisions (from + ``skip_code``, ``@torch._dynamo.skip``, FX-generated code, etc.) are + inherited by isolated regions — those remain skipped. RUN_ONLY persisted + by a non-isolated region hitting its recompile limit does NOT bleed + into isolated regions — each region manages its own RUN_ONLY state. + Default False. + + Example:: + + @torch.compile(options={"triton.cudagraphs": True}, fullgraph=True) + def foo(x): + return torch.sin(x) + torch.cos(x) + + """ + import sysconfig + + _C._log_api_usage_once("torch.compile") + if sys.version_info >= (3, 15): + raise RuntimeError("torch.compile is not supported on Python 3.15+") + elif sysconfig.get_config_var("Py_GIL_DISABLED") == 1 and sys.version_info < ( + 3, + 13, + 3, + ): + raise RuntimeError( + "torch.compile is not supported on Python < 3.13.3 built with GIL disabled. " + "Please use Python 3.13.3+." + ) + + if backend is None: + from torch._dynamo.backends.registry import get_default_backend + + backend = get_default_backend() + + # Auto-wrap ParamsSpec → ShapesSpec for convenience + if dynamic_shapes is not None: + from torch.fx.experimental.dynamic_spec import ParamsSpec, ShapesSpec + + if isinstance(dynamic_shapes, ParamsSpec): + dynamic_shapes = ShapesSpec(dynamic_shapes) + + # If ``model`` carries an ``@dynamic_spec(...)`` decorator, the attached + # ``ShapesSpec`` is used as ``dynamic_shapes``. Passing both raises. + if model is not None: + from torch.fx.experimental.dynamic_spec import _resolve_dynamic_shapes + + dynamic_shapes = _resolve_dynamic_shapes(model, dynamic_shapes) + + # Decorator mode + if model is None: + + def fn(model: _Callable[_InputT, _RetT]) -> _Callable[_InputT, _RetT]: + if model is None: + raise RuntimeError("Model can't be None") + return compile( # pyrefly: ignore # no-matching-overload + model, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + name=name, + disable=disable, + recompile_limit=recompile_limit, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + return fn + + if mode is not None and options is not None: + raise RuntimeError( + "Either mode or options can be specified, but both can't be specified at the same time." + ) + if mode is None and options is None: + mode = "default" + + from torch._inductor.compiler_bisector import CompilerBisector + + if bisect_backend := CompilerBisector.get_backend(): + import torch._inductor.config as inductor_config + + # don't override the backend for use cases like vllm + # which leverages their custom backend. + if not ( + inductor_config.test_configs.bisect_keep_custom_backend_for_inductor + and bisect_backend == "inductor" + and not isinstance(backend, str) + ): + backend = bisect_backend + + guard_filter_fn = None + use_aoti = False + if options and isinstance(options, dict): + guard_filter_fn = options.pop("guard_filter_fn", None) + use_aoti = options.pop("use_aoti", False) + + if torch.compiler.is_exporting(): + from torch._higher_order_ops.utils import _in_hop_compile + + if not _in_hop_compile(): + warnings.warn( + "torch.compile is ignored when called inside torch.export region", + stacklevel=2, + ) + # torch.compile is a no-op when inside torch.export region + return model + + if backend == "inductor": + if use_aoti: + backend = _TorchCompileAOTInductorWrapper(mode, options, dynamic, name) + else: + backend = _TorchCompileInductorWrapper(mode, options, dynamic, name) + else: + backend = _TorchCompileWrapper(backend, mode, options, dynamic) + + return torch._dynamo.optimize( + backend=backend, + nopython=fullgraph, + dynamic=dynamic, + disable=disable, + guard_filter_fn=guard_filter_fn, + recompile_limit=recompile_limit, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + )(model) # type: ignore[return-value] + + +def _register_device_module(device_type: str, module: _ModuleType) -> None: + r"""Register an external runtime module of the specific :attr:`device_type` + supported by torch. + + After the :attr:`module` is registered correctly, the user can refer + the external runtime module as part of torch with attribute torch.xxx. + """ + # Make sure the device_type represent a supported device type for torch. + device_type = torch.device(device_type).type + m = sys.modules[__name__] + if hasattr(m, device_type): + raise RuntimeError( + f"The runtime module of '{device_type}' has already " + f"been registered with '{getattr(m, device_type)}'" + ) + setattr(m, device_type, module) + torch_module_name = ".".join([__name__, device_type]) + sys.modules[torch_module_name] = module + + +from torch import ( + export as export, + func as func, + library as library, + return_types as return_types, +) +from torch._higher_order_ops import cond as cond, while_loop as while_loop +from torch.func import vmap as vmap + + +if not TYPE_CHECKING: + # register python metas for distributed ops + # Only import if distributed is available (USE_DISTRIBUTED=1) + if hasattr(torch._C, "_c10d_init"): + import torch.distributed._meta_registrations as coll_meta_registrations + + del coll_meta_registrations + from torch import _meta_registrations + +# Enable CUDA Sanitizer +if "TORCH_CUDA_SANITIZER" in os.environ: + import torch.cuda._sanitizer as csan + + csan.enable_cuda_sanitizer() + +# Populate magic methods on SymInt and SymFloat +import torch.fx.experimental.sym_node +from torch import compiler as compiler, fx as fx + + +class _TritonLibrary: + lib = torch.library.Library("triton", "DEF") + ops_table: dict[tuple[str, str], _Callable[..., _Any]] = {} + + @classmethod + def registerOp( + cls, + op_key: str, + full_schema: str, + op_impl: _Callable[..., _Any], + dispatch_key: str, + ) -> _Callable[..., _Any]: + if (op_key, dispatch_key) not in cls.ops_table: + cls.lib.define(full_schema) + cls.lib.impl("triton::" + op_key, op_impl, dispatch_key) + cls.ops_table[(op_key, dispatch_key)] = op_impl + + return cls.ops_table[(op_key, dispatch_key)] + + +# Deprecated attributes +_deprecated_attrs = { + "has_mps": torch.backends.mps.is_built, + "has_cuda": torch.backends.cuda.is_built, + "has_cudnn": torch.backends.cudnn.is_available, + "has_mkldnn": torch.backends.mkldnn.is_available, +} + +if TYPE_CHECKING: + # Import the following modules during type checking to enable code intelligence features, + # such as auto-completion in tools like pylance, even when these modules are not explicitly + # imported in user code. + from torch import ( + _dynamo as _dynamo, + _inductor as _inductor, + _subclasses as _subclasses, + onnx as onnx, + ) + +else: + _lazy_modules = { + "_dynamo", + "_inductor", + "_export", + # ONNX must be imported after _dynamo, _ops, _subclasses, fx, func and jit + "onnx", + } + + def __getattr__(name: str) -> _Any: + # Deprecated attrs + replacement = _deprecated_attrs.get(name) + if replacement is not None: + import warnings + + warnings.warn( + f"'{name}' is deprecated, please use '{replacement.__module__}.{replacement.__name__}()'", + stacklevel=2, + ) + return replacement() + + # Lazy modules + if name in _lazy_modules: + return importlib.import_module(f".{name}", __name__) + + # set_vital + if name == "set_vital": + import warnings + + warnings.warn(f"'{name}' is deprecated, please do not call", stacklevel=2) + return lambda *args: None + + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") + + +@functools.cache +def get_device_module(device: "torch.device | str | None" = None) -> _ModuleType: + """ + Returns the module associated with a given device(e.g., torch.device('cuda'), "mtia:0", "xpu", ...). + If no device is given, return the module for the current accelerator or CPU if none is present. + """ + if isinstance(device, torch.device): + device_module_name = device.type + elif isinstance(device, str): + device_module_name = torch.device(device).type + elif device is None: + # Use the current accelerator's type, falling back to CPU when none is available. + acc = torch._C._accelerator_getAccelerator() + device_module_name = acc.type if acc is not None else "cpu" + else: + raise RuntimeError( + f"Invalid value of device '{device}', expect torch.device, str, or None" + ) + device_module = getattr(torch, device_module_name, None) + if device_module is None: + raise RuntimeError( + f"Device '{device_module_name}' does not have a corresponding module registered as 'torch.{device_module_name}'." + ) + return device_module + + +def _constrain_as_size( + symbol: "IntLikeType", + min: builtins.int | None = None, + max: builtins.int | None = None, +) -> None: + """ + This indicates that a given int is size-like, and can be used in any context where a size is expected. + You will typically use this when reading out integers from Tensors, e.g., max.item() or lengths.tolist() + which then need to be used as tensor constructors. Providing these assertions to PyTorch can help resolve + GuardOnDataDependentSymNode errors upon export, since we cannot guard on unbacked SymInts. + + This function has unusual semantics in some circumstances in framework + code, we will treat this int as >= 2 (when we do a size-oblivious guard). + This makes it easier to use the unbacked int in size contexts, + as we will often attempt to guard on a size being zero/one + (e.g., when computing the contiguity of a tensor, or testing if + broadcasting can occur), which will not work on unbacked SymInts. + However, if we conservatively assume that the size is not zero/one, we will + end up with a graph that will still work even if the size is zero/one. + + For more details, see https://docs.google.com/document/d/1HSuTTVvYH1pTew89Rtpeu84Ht3nQEFTYhAX3Ypa_xJs/edit + ``` + """ + # pyrefly: ignore[bad-argument-type] + torch.sym_constrain_range_for_size(symbol, min=min, max=max) + + +def _import_device_backends() -> None: + """ + Leverage the Python plugin mechanism to load out-of-the-tree device extensions. + See this RFC: https://github.com/pytorch/pytorch/issues/122468 + """ + from importlib.metadata import entry_points + + group_name = "torch.backends" + backend_extensions = entry_points(group=group_name) + + for backend_extension in backend_extensions: + try: + # Load the extension + entrypoint = backend_extension.load() + # Call the entrypoint + entrypoint() + except Exception as err: + raise RuntimeError( + f"Failed to load the backend extension: {backend_extension.name}. " + f"You can disable extension auto-loading with TORCH_DEVICE_BACKEND_AUTOLOAD=0." + ) from err + + +def _is_device_backend_autoload_enabled() -> builtins.bool: + """ + Whether autoloading out-of-the-tree device extensions is enabled. + The switch depends on the value of the environment variable + `TORCH_DEVICE_BACKEND_AUTOLOAD`. + + Returns: + bool: Whether to enable autoloading the extensions. Enabled by default. + + Examples: + >>> torch._is_device_backend_autoload_enabled() + True + """ + # enabled by default + return os.getenv("TORCH_DEVICE_BACKEND_AUTOLOAD", "1") == "1" + + +def _as_tensor_fullprec(t: object) -> "torch.Tensor": + """ + Like torch.as_tensor, but when given Python data types it will keep + them in full precision. Used for calling convention for Dynamo. + Python scalars (float, int) are always created on CPU to avoid being + affected by DeviceContext. + """ + ty = type(t) + if ty is builtins.float: + return torch.as_tensor(t, dtype=torch.float64, device="cpu") + elif ty is builtins.int: + return torch.as_tensor(t, dtype=torch.int64, device="cpu") + else: + return torch.as_tensor(t) + + +# `_import_device_backends` should run after the definitions above to ensure +# all the other functions in this module that may be accessed by an autoloaded +# backend are defined. +if _is_device_backend_autoload_enabled(): + _import_device_backends() + +from torch import _logging + + +# Keep `TORCH_LOGS` initialization after backend autoload so backends can +# register their log names before `TORCH_LOGS` is parsed and validated. +_logging._init_logs() + +# Register all registered custom / override ops in torch/_native +import torch._native diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_VF.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_VF.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0d20ca7ac060b53676c7bf49bd357299ccb0bac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_VF.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/__config__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/__config__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40eb5754aafcfdc1584806077bf3cb595168c843 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/__config__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/__future__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/__future__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12eee04f60a29517b2f3be296e382adc6e87af73 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/__future__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d8fc052c25f59eb434c045c9e8e7b7747af0809 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__pycache__/__init__.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:968f7c68c8907b2bc9ab1adf9dd860ddc600ed7e7d5f0fe41d6596c9c76b76a5 +size 145169 diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_appdirs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_appdirs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..744d5333ed55c17e5001963d84596f676333c73b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_appdirs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_classes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_classes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1302811ca92e8e3600ca3a4ce87eb193c1310df7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_classes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..830015ceb91f2f64cc15a449397deb32ebf4b661 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_class_base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_class_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..681d9d5c4d77981163f2238791fe447c63739c1a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_class_base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f6c36e8b8cb8a8de13e6acdcc7ac432a6c2465f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_environment.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_environment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..367112314f477145aeb4ee26a181240cdbc0299d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_environment.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_guards.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_guards.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ee52a494a69dc459d75ab4d4c6f487a5e8a530d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_guards.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_jit_internal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_jit_internal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29b688800ac4e50b2a59347f0f312d9ef9abe9bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_jit_internal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_linalg_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_linalg_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8eb8be7a1326e504f28e62a137c378ea68c50974 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_linalg_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_lobpcg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_lobpcg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a28eff03d4c47a2147b87c4dc9d2514e7aced70 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_lobpcg.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_lowrank.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_lowrank.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ec7d8ed4abfb8ec7e6822d298aff4addd13672 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_lowrank.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_meta_registrations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_meta_registrations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09d0a6ed095be6bd23541c336ace9c34648eacf2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__pycache__/_meta_registrations.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca8404f648182f9be25a92e09ffb354fb710ad274f556560bfd61b97edfa1576 +size 430296 diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_opaque_base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_opaque_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9812f464c1de1631535ae45ca8d3823f273f2a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_opaque_base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5089e7ed0a3a0d0d6f6ad31849dd003b55820e16 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43361ef9ac4a20c1811bcde50cb52ec658e654ea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile_driver.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile_driver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f968ec00c83aa1b3961347c620b43a786e56b57 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile_driver.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_python_dispatcher.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_python_dispatcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d3e6944e3da52b4776ce9cb494498f95a682f0d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_python_dispatcher.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_size_docs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_size_docs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79200025b5804baa8bd98bcd7be51ed3ceae1744 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_size_docs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_sources.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_sources.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee6ad076b71e650f8a243eb4b7161db86b78803e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_sources.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_storage_docs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_storage_docs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..074ec074f5f5a68d2f4162be4e49bc6ead07be91 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_storage_docs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_streambase.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_streambase.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2838d72defa3ad10d9397642ef7664f042590739 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_streambase.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b013c08997f96d3f25961ab69ec8216ac78dd730 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_docs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_docs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c72a009a7242534e257b7ff6cf5f98b0a9a52034 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_docs.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a66420718dd30504cb5975f2844e25783ebec7442c9606696fcad328c125e99d +size 146282 diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_iterator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_iterator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f864f455b40a01471c05a1d37c991f0a6ac0485 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_iterator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_str.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_str.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70c1b9a73860eb07b0b65aee704f1e7f56d71890 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_str.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_thread_safe_fork.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_thread_safe_fork.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b2d096ecfbcf48a91f7fa17cc1b0e22665e1219 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_thread_safe_fork.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_torch_docs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_torch_docs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e724a9d5fd702a335fb25c7e053dbc517a3688aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__pycache__/_torch_docs.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43967e160908aa312ed44c07e7c0c303b76b3c5287b4f365ac3c68f8d8dc730c +size 468356 diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01f7383c405702556872385513e7c1347787f4b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils_internal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils_internal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42e144d14a2d4db10ab1d6e5696fdf828d22bca0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils_internal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_vmap_internals.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_vmap_internals.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84ab15bb65b690ba93b46c180e791f26a42546a4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_vmap_internals.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_weights_only_unpickler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_weights_only_unpickler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a2515497eec3388cd6290bb1b90890f3c41f44a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_weights_only_unpickler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/functional.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/functional.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aca5456550ab6ca7b5b0ed6bcd9d343d473a3c53 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/functional.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/hub.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/hub.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..553db869f31fbf2b749e38bf2e8d989b9b039d39 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/hub.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/library.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/library.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2d1e105b83eafed600e3b1d37086c5934dabde4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/library.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e899475812ccf64f098be88417b14c32dd08bcb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__pycache__/overrides.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93e036d0c3777f60525f1e7d28b3a79b65602052b318f05bd1aa5a2b4dda25a0 +size 259003 diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/quasirandom.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/quasirandom.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f48c3fa4a01433ab2dde84052a3cf4805ef91bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/quasirandom.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/random.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/random.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..596f9d2ad012a06f952eb6e1082d15badfcf0d0b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/random.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/return_types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/return_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd260503a9d26fd0badfe4e131c3dbdf4b8c17c2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/return_types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/serialization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/serialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..706bc384c5e609cf8cb6f4ec8f568f87d318436a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/serialization.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/storage.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/storage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d99ccf380835cdb762423f0c23a2e7cdd5e15fa9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/storage.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/torch_version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/torch_version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84423d5fbe482113658b7a3f8bfe15a67b0c084f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/torch_version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff878749aa2b05333cd235f307f46ce59061b30d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78cc984c1fa1af4e052d8d667d975791a0a0db54 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_appdirs.py b/.venv/lib/python3.12/site-packages/torch/_appdirs.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8ad9487e255ad2ebac86b2fbe9245f72657332 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_appdirs.py @@ -0,0 +1,666 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright (c) 2005-2010 ActiveState Software Inc. +# Copyright (c) 2013 Eddy Petrișor + +# flake8: noqa + +""" +This file is directly from +https://github.com/ActiveState/appdirs/blob/3fe6a83776843a46f20c2e5587afcffe05e03b39/appdirs.py + +The license of https://github.com/ActiveState/appdirs copied below: + + +# This is the MIT license + +Copyright (c) 2010 ActiveState Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +""" + +"""Utilities for determining application-specific dirs. + +See for details and usage. +""" +# Dev Notes: +# - Windows "Known Folders": https://learn.microsoft.com/en-us/windows/win32/shell/csidl +# - macOS File System Programming Guide: https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/Introduction/Introduction.html +# - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + +__version__ = "1.4.4" +__version_info__ = tuple(int(segment) for segment in __version__.split(".")) + + +import os +import sys + + +unicode = str + +if sys.platform.startswith("java"): + import platform + + os_name = platform.java_ver()[3][0] + if os_name.startswith("Windows"): # "Windows XP", "Windows 7", etc. + system = "win32" + elif os_name.startswith("Mac"): # "Mac OS X", etc. + system = "darwin" + else: # "Linux", "SunOS", "FreeBSD", etc. + # Setting this to "linux2" is not ideal, but only Windows or Mac + # are actually checked for and the rest of the module expects + # *sys.platform* style strings. + system = "linux2" +else: + system = sys.platform + + +def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user data directories are: + Mac OS X: ~/Library/Application Support/ + Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined + Win XP (not roaming): C:\Documents and Settings\\Application Data\\ + Win XP (roaming): C:\Documents and Settings\\Local Settings\Application Data\\ + Win 7 (not roaming): C:\Users\\AppData\Local\\ + Win 7 (roaming): C:\Users\\AppData\Roaming\\ + + For Unix, we follow the XDG spec and support $XDG_DATA_HOME. + That means, by default "~/.local/share/". + """ + if system == "win32": + if appauthor is None: + appauthor = appname + const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" + path = os.path.normpath(_get_win_folder(const)) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + elif system == "darwin": + path = os.path.expanduser("~/Library/Application Support/") + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): + r"""Return full path to the user-shared data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "multipath" is an optional parameter only applicable to *nix + which indicates that the entire list of data dirs should be + returned. By default, the first item from XDG_DATA_DIRS is + returned, or '/usr/local/share/', + if XDG_DATA_DIRS is not set + + Typical site data directories are: + Mac OS X: /Library/Application Support/ + Unix: /usr/local/share/ or /usr/share/ + Win XP: C:\Documents and Settings\All Users\Application Data\\ + Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) + Win 7: C:\ProgramData\\ # Hidden, but writeable on Win 7. + + For Unix, this is using the $XDG_DATA_DIRS[0] default. + + WARNING: Do not use this on Windows. See the Vista-Fail note above for why. + """ + if system == "win32": + if appauthor is None: + appauthor = appname + path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + elif system == "darwin": + path = os.path.expanduser("/Library/Application Support") + if appname: + path = os.path.join(path, appname) + else: + # XDG default for $XDG_DATA_DIRS + # only first, if multipath is False + path = os.getenv( + "XDG_DATA_DIRS", os.pathsep.join(["/usr/local/share", "/usr/share"]) + ) + pathlist = [ + os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) + ] + if appname: + if version: + appname = os.path.join(appname, version) + pathlist = [os.sep.join([x, appname]) for x in pathlist] + + if multipath: + path = os.pathsep.join(pathlist) + else: + path = pathlist[0] + return path + + if appname and version: + path = os.path.join(path, version) + return path + + +def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific config dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user config directories are: + Mac OS X: ~/Library/Preferences/ + Unix: ~/.config/ # or in $XDG_CONFIG_HOME, if defined + Win *: same as user_data_dir + + For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. + That means, by default "~/.config/". + """ + if system == "win32": + path = user_data_dir(appname, appauthor, None, roaming) + elif system == "darwin": + path = os.path.expanduser("~/Library/Preferences/") + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): + r"""Return full path to the user-shared data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "multipath" is an optional parameter only applicable to *nix + which indicates that the entire list of config dirs should be + returned. By default, the first item from XDG_CONFIG_DIRS is + returned, or '/etc/xdg/', if XDG_CONFIG_DIRS is not set + + Typical site config directories are: + Mac OS X: same as site_data_dir + Unix: /etc/xdg/ or $XDG_CONFIG_DIRS[i]/ for each value in + $XDG_CONFIG_DIRS + Win *: same as site_data_dir + Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) + + For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False + + WARNING: Do not use this on Windows. See the Vista-Fail note above for why. + """ + if system == "win32": + path = site_data_dir(appname, appauthor) + if appname and version: + path = os.path.join(path, version) + elif system == "darwin": + path = os.path.expanduser("/Library/Preferences") + if appname: + path = os.path.join(path, appname) + else: + # XDG default for $XDG_CONFIG_DIRS + # only first, if multipath is False + path = os.getenv("XDG_CONFIG_DIRS", "/etc/xdg") + pathlist = [ + os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) + ] + if appname: + if version: + appname = os.path.join(appname, version) + pathlist = [os.sep.join([x, appname]) for x in pathlist] + + if multipath: + path = os.pathsep.join(pathlist) + else: + path = pathlist[0] + return path + + +def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): + r"""Return full path to the user-specific cache dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "opinion" (boolean) can be False to disable the appending of + "Cache" to the base app data dir for Windows. See + discussion below. + + Typical user cache directories are: + Mac OS X: ~/Library/Caches/ + Unix: ~/.cache/ (XDG default) + Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache + Vista: C:\Users\\AppData\Local\\\Cache + + On Windows the only suggestion in the MSDN docs is that local settings go in + the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming + app data dir (the default returned by `user_data_dir` above). Apps typically + put cache data somewhere *under* the given dir here. Some examples: + ...\Mozilla\Firefox\Profiles\\Cache + ...\Acme\SuperApp\Cache\1.0 + OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. + This can be disabled with the `opinion=False` option. + """ + if system == "win32": + if appauthor is None: + appauthor = appname + path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + if opinion: + path = os.path.join(path, "Cache") + elif system == "darwin": + path = os.path.expanduser("~/Library/Caches") + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def user_state_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific state dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user state directories are: + Mac OS X: same as user_data_dir + Unix: ~/.local/state/ # or in $XDG_STATE_HOME, if defined + Win *: same as user_data_dir + + For Unix, we follow this Debian proposal + to extend the XDG spec and support $XDG_STATE_HOME. + + That means, by default "~/.local/state/". + """ + if system in ["win32", "darwin"]: + path = user_data_dir(appname, appauthor, None, roaming) + else: + path = os.getenv("XDG_STATE_HOME", os.path.expanduser("~/.local/state")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): + r"""Return full path to the user-specific log dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "opinion" (boolean) can be False to disable the appending of + "Logs" to the base app data dir for Windows, and "log" to the + base cache dir for Unix. See discussion below. + + Typical user log directories are: + Mac OS X: ~/Library/Logs/ + Unix: ~/.cache//log # or under $XDG_CACHE_HOME if defined + Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Logs + Vista: C:\Users\\AppData\Local\\\Logs + + On Windows the only suggestion in the MSDN docs is that local settings + go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in + examples of what some windows apps use for a logs dir.) + + OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` + value for Windows and appends "log" to the user cache dir for Unix. + This can be disabled with the `opinion=False` option. + """ + if system == "darwin": + path = os.path.join(os.path.expanduser("~/Library/Logs"), appname) + elif system == "win32": + path = user_data_dir(appname, appauthor, version) + version = False + if opinion: + path = os.path.join(path, "Logs") + else: + path = user_cache_dir(appname, appauthor, version) + version = False + if opinion: + path = os.path.join(path, "log") + if appname and version: + path = os.path.join(path, version) + return path + + +class AppDirs: + """Convenience wrapper for getting application dirs.""" + + def __init__( + self, appname=None, appauthor=None, version=None, roaming=False, multipath=False + ): + self.appname = appname + self.appauthor = appauthor + self.version = version + self.roaming = roaming + self.multipath = multipath + + @property + def user_data_dir(self): + return user_data_dir( + self.appname, self.appauthor, version=self.version, roaming=self.roaming + ) + + @property + def site_data_dir(self): + return site_data_dir( + self.appname, self.appauthor, version=self.version, multipath=self.multipath + ) + + @property + def user_config_dir(self): + return user_config_dir( + self.appname, self.appauthor, version=self.version, roaming=self.roaming + ) + + @property + def site_config_dir(self): + return site_config_dir( + self.appname, self.appauthor, version=self.version, multipath=self.multipath + ) + + @property + def user_cache_dir(self): + return user_cache_dir(self.appname, self.appauthor, version=self.version) + + @property + def user_state_dir(self): + return user_state_dir(self.appname, self.appauthor, version=self.version) + + @property + def user_log_dir(self): + return user_log_dir(self.appname, self.appauthor, version=self.version) + + +# ---- internal support stuff + + +def _get_win_folder_from_registry(csidl_name): + """This is a fallback technique at best. I'm not sure if using the + registry for this guarantees us the correct answer for all CSIDL_* + names. + """ + import winreg as _winreg + + shell_folder_name = { + "CSIDL_APPDATA": "AppData", + "CSIDL_COMMON_APPDATA": "Common AppData", + "CSIDL_LOCAL_APPDATA": "Local AppData", + }[csidl_name] + + key = _winreg.OpenKey( + _winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", + ) + dir, _type = _winreg.QueryValueEx(key, shell_folder_name) + return dir + + +def _get_win_folder_with_pywin32(csidl_name): + from win32com.shell import shell, shellcon + + dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) + # Try to make this a unicode path because SHGetFolderPath does + # not return unicode strings when there is unicode data in the + # path. + try: + dir = unicode(dir) + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in dir: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + try: + import win32api + + dir = win32api.GetShortPathName(dir) + except ImportError: + pass + except UnicodeError: + pass + return dir + + +def _get_win_folder_with_ctypes(csidl_name): + import ctypes + + csidl_const = { + "CSIDL_APPDATA": 26, + "CSIDL_COMMON_APPDATA": 35, + "CSIDL_LOCAL_APPDATA": 28, + }[csidl_name] + + buf = ctypes.create_unicode_buffer(1024) + ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in buf: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + buf2 = ctypes.create_unicode_buffer(1024) + if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): + buf = buf2 + + return buf.value + + +def _get_win_folder_with_jna(csidl_name): + import array + + from com.sun import jna + from com.sun.jna.platform import win32 + + buf_size = win32.WinDef.MAX_PATH * 2 + buf = array.zeros("c", buf_size) + shell = win32.Shell32.INSTANCE + shell.SHGetFolderPath( + None, + getattr(win32.ShlObj, csidl_name), + None, + win32.ShlObj.SHGFP_TYPE_CURRENT, + buf, + ) + dir = jna.Native.toString(buf.tostring()).rstrip("\0") + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in dir: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + buf = array.zeros("c", buf_size) + kernel = win32.Kernel32.INSTANCE + if kernel.GetShortPathName(dir, buf, buf_size): + dir = jna.Native.toString(buf.tostring()).rstrip("\0") + + return dir + + +if system == "win32": + try: + import win32com.shell + + _get_win_folder = _get_win_folder_with_pywin32 + except ImportError: + try: + from ctypes import windll + + _get_win_folder = _get_win_folder_with_ctypes + except ImportError: + try: + import com.sun.jna + + _get_win_folder = _get_win_folder_with_jna + except ImportError: + _get_win_folder = _get_win_folder_from_registry + + +# ---- self test code + +if __name__ == "__main__": + appname = "MyApp" + appauthor = "MyCompany" + + props = ( + "user_data_dir", + "user_config_dir", + "user_cache_dir", + "user_state_dir", + "user_log_dir", + "site_data_dir", + "site_config_dir", + ) + + print(f"-- app dirs {__version__} --") + + print("-- app dirs (with optional 'version')") + dirs = AppDirs(appname, appauthor, version="1.0") + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") + + print("\n-- app dirs (without optional 'version')") + dirs = AppDirs(appname, appauthor) + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") + + print("\n-- app dirs (without optional 'appauthor')") + dirs = AppDirs(appname) + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") + + print("\n-- app dirs (with disabled 'appauthor')") + dirs = AppDirs(appname, appauthor=False) + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") diff --git a/.venv/lib/python3.12/site-packages/torch/_awaits/__init__.py b/.venv/lib/python3.12/site-packages/torch/_awaits/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8d2bf058c08847bd09afc905bc88e6823bc917 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_awaits/__init__.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from typing import Generic, TypeVar + +import torch + +# pyrefly: ignore [bad-dunder-all] +__all__ = ['Await'] + +W = TypeVar("W") + +class _PyAwaitMeta(type(torch._C._Await), type(Generic)): # type: ignore[misc, no-redef] + pass + +class _Await(torch._C._Await, Generic[W], metaclass=_PyAwaitMeta): + r""" + Wrapper around a ``torch._C.Await`` which encapsulates delayed execution + of a callable. All manipulations happen with functions ``torch.jit._awaitable``, + ``torch.jit._awaitable_wait``, ``torch.jit._awaitable_nowait``. + + Torch scriptable manipulations: + ``torch.jit._awaitable(func, *args)`` + Creates ``Await[W]`` object, where W is return type of func. + + Returns: + ``torch.jit._awaitable_wait(Await[W])`` + Returns the result of the function, specified at ``_awaitable``, with specified arguments. + + Returns: + The result of type ``W`` of the function call. The result is owned by ``Await[W]`` + and returned on all following ``_awaitable_wait`` calls. + + + ``torch.jit._awaitable_nowait(W)`` + Returns: + Trivial ``Await[W]`` with specified result. + + + Only in eager mode: + ``fn() -> Callable[Tuple[Any], W]`` + Returns: + Specified at ``_awaitable`` python function ``func``. + + ``args() -> Tuple[Any]`` + Returns: + Specified at ``_awaitable`` python args. + + ``is_nowait() -> _bool`` + Returns: + ``True`` if this object was created via ``_awaitable_nowait`` call (trivial `Await[W]`). + + In eager mode ``Await[W]`` can be used as ``W`` i.e. attributes of W can be called on ``Await[W]``, + ``_awaitable_wait()`` call will be transparently added. + """ diff --git a/.venv/lib/python3.12/site-packages/torch/_awaits/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_awaits/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00c5364e3d97162646807893fc37c3c5d42e3e37 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_awaits/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_classes.py b/.venv/lib/python3.12/site-packages/torch/_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..a811c7c30be612bf0a89e5c8a5473e9d54d02ba3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_classes.py @@ -0,0 +1,56 @@ +import types +from typing import Any + +import torch._C + + +class _ClassNamespace(types.ModuleType): + def __init__(self, name: str) -> None: + super().__init__("torch.classes" + name) + self.name = name + + def __getattr__(self, attr: str) -> Any: + proxy = torch._C._get_custom_class_python_wrapper(self.name, attr) + if proxy is None: + raise RuntimeError(f"Class {self.name}.{attr} not registered!") + return proxy + + +class _Classes(types.ModuleType): + __file__ = "_classes.py" + + def __init__(self) -> None: + super().__init__("torch.classes") + + def __getattr__(self, name: str) -> _ClassNamespace: + namespace = _ClassNamespace(name) + setattr(self, name, namespace) + return namespace + + @property + def loaded_libraries(self) -> Any: + return torch.ops.loaded_libraries + + def load_library(self, path: str) -> None: + """ + Loads a shared library from the given path into the current process. + + The library being loaded may run global initialization code to register + custom classes with the PyTorch JIT runtime. This allows dynamically + loading custom classes. For this, you should compile your class + and the static registration code into a shared library object, and then + call ``torch.classes.load_library('path/to/libcustom.so')`` to load the + shared object. + + After the library is loaded, it is added to the + ``torch.classes.loaded_libraries`` attribute, a set that may be inspected + for the paths of all libraries loaded using this function. + + Args: + path (str): A path to a shared library to load. + """ + torch.ops.load_library(path) + + +# The classes "namespace" +classes = _Classes() diff --git a/.venv/lib/python3.12/site-packages/torch/_compile.py b/.venv/lib/python3.12/site-packages/torch/_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7d715883d58588c7f991a7393f016d2320213c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_compile.py @@ -0,0 +1,60 @@ +""" +APIs related to torch.compile which lazily import torch._dynamo to avoid +circular dependencies. +""" + +import functools +from collections.abc import Callable +from typing import overload, TypeVar +from typing_extensions import ParamSpec + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + + +@overload +def _disable_dynamo( + fn: Callable[_P, _T], recursive: bool = True +) -> Callable[_P, _T]: ... + + +@overload +def _disable_dynamo( + fn: None = None, recursive: bool = True +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: ... + + +def _disable_dynamo( + fn: Callable[_P, _T] | None = None, recursive: bool = True +) -> Callable[_P, _T] | Callable[[Callable[_P, _T]], Callable[_P, _T]]: + """ + This API should be only used inside torch, external users should still use + torch._dynamo.disable. The main goal of this API is to avoid circular + imports issues that is common while using _dynamo.disable inside torch + itself. + + This API avoids it by lazily importing torch._dynamo from the import time to + the invocation of the decorated function. + """ + if fn is not None: + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _T: + # cache this on the first invocation to avoid adding too much overhead. + disable_fn = getattr(fn, "__dynamo_disable", None) + if disable_fn is None: + import torch._dynamo + + # We can safely turn off functools.wraps here because the inner + # already wraps fn in the outer scope. + disable_fn = torch._dynamo.disable(fn, recursive, wrapping=False) + fn.__dynamo_disable = disable_fn # type: ignore[attr-defined] + + return disable_fn(*args, **kwargs) + + return inner + else: + # decorator usage like @_disable_dynamo(recursive=False). The resulting + # object expects the original decorated function as the arg. + return functools.partial(_disable_dynamo, recursive=recursive) diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_class_base.py b/.venv/lib/python3.12/site-packages/torch/_custom_class_base.py new file mode 100644 index 0000000000000000000000000000000000000000..051cf5cc623fe9a13a17e25d56e8089cf772e4ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_custom_class_base.py @@ -0,0 +1,43 @@ +# Cached lazily on first __instancecheck__ miss to avoid an import cycle at +# module load (FakeScriptObject's module imports torch, which imports us). +_FakeScriptObject_cls: type | None = None + + +class CustomClassBaseMeta(type): + def __instancecheck__(cls, instance): + # When checking against CustomClassBase itself (not a concrete subclass), + # delegate to the registration system which correctly covers all + # custom classes (constant types, metaclass-only symbolic types, and + # FakeScriptObject wrappers). + if cls is CustomClassBase: + from torch._library.opaque_object import is_custom_class_obj + + return is_custom_class_obj(instance) + + if super().__instancecheck__(instance): + return True + + # Check FakeScriptObject before hasattr to avoid triggering custom + # __getattr__ on arbitrary user objects (e.g. dict-like objects that + # raise KeyError on unknown attributes). + # e.g. test/dynamo/test_dynamic_shapes.py -k test_user_getattr1_dynamic_shapes + global _FakeScriptObject_cls + if _FakeScriptObject_cls is None: + from torch._library.fake_class_registry import FakeScriptObject + + _FakeScriptObject_cls = FakeScriptObject + if isinstance(instance, _FakeScriptObject_cls) and hasattr( + instance, "real_obj" + ): + return super().__instancecheck__(instance.real_obj) + + return False + + +class CustomClassBase(metaclass=CustomClassBaseMeta): + pass + + +# Backward compatibility aliases +OpaqueBaseMeta = CustomClassBaseMeta +OpaqueBase = CustomClassBase diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/__init__.py b/.venv/lib/python3.12/site-packages/torch/_custom_op/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d4ba5ac94a4d7583875af83a6dfde5ee1b373ae Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/autograd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/autograd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25743e9c90ee5c8e669e62f94ea249188e0316b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/autograd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36f48e4aad1a6b4f1f96cc59f019d9e6018e6259 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/autograd.py b/.venv/lib/python3.12/site-packages/torch/_custom_op/autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..e4dffbd4c026627f7c8ac7c6a1fb988b96c187a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_custom_op/autograd.py @@ -0,0 +1,314 @@ +# mypy: allow-untyped-defs +import functools +from collections import namedtuple + +import torch +import torch.utils._pytree as pytree + + +# NOTE [CustomOp autograd kernel indirection] +# We register `inner` as the autograd kernel for this custom_op. +# `inner` either calls the autograd formula registered by the user, +# or goes into an `autograd_not_implemented` kernel. +# +# The reason why this indirection exists is +# so that we can swap out the autograd kernel (the PyTorch dispatcher +# doesn't actually allow us to do this). By default, we want +# the `autograd_not_implemented` behavior, but then the user may come +# and register something that is actually a backward formula +def autograd_kernel_indirection(custom_op): + autograd_fallback = autograd_not_implemented(custom_op) + + def inner(*args, **kwargs): + if custom_op._has_impl("autograd"): + kernel = custom_op._get_impl("autograd").func + return kernel(*args, **kwargs) + # As explained in NOTE ["backward", "save_for_backward", and "autograd"], + # after the user gives us "backward" and "save_for_backward", we generate + # the "autograd" impl. If the user only provided one, then we tell + # the user they've done something wrong. + if custom_op._has_impl("save_for_backward") or custom_op._has_impl("backward"): + missing = ( + "save_for_backward" if custom_op._has_impl("backward") else "backward" + ) + found = "save_for_backward" if missing == "backward" else "backward" + loc = custom_op._get_impl(found).location + raise RuntimeError( + f"We found a '{found}' registration for {custom_op} at " + f"{loc} but were unable to find a '{missing}' registration. " + f"To use the CustomOp API to register a backward formula, " + f"please provide us both a backward function and a " + f"'save for backward' function via `impl_backward` and " + f"`impl_save_for_backward` respectively." + ) + return autograd_fallback(*args, **kwargs) + + return inner + + +# TODO(#101191): Use the actual C++ autograd not implemented fallback, +# or change the default autograd fallback to the autograd not implemented fallback. +def autograd_not_implemented(custom_op): + def kernel(*args, **kwargs): + if torch.is_grad_enabled() and pytree.tree_any( + lambda x: isinstance(x, torch.Tensor) and x.requires_grad, (args, kwargs) + ): + raise RuntimeError("Autograd has not been implemented for operator") + with torch._C._AutoDispatchBelowAutograd(): + return custom_op(*args, **kwargs) + + return kernel + + +def mark_non_differentiable(ctx, output, output_differentiability): + # Output types are restricted to be: + # - Tensor + # - Tensor[] + # - int, bool, Scalar, float + # See _check_can_register_backward + if output_differentiability is not None: + if not isinstance(output, tuple): + tuple_output = (output,) + else: + tuple_output = output # type: ignore[assignment] + if len(output_differentiability) != len(tuple_output): + raise AssertionError( + f"output_differentiability length {len(output_differentiability)} " + f"!= output length {len(tuple_output)}" + ) + non_differentiable_tensors = [] + for idx, (differentiable, out) in enumerate( + zip(output_differentiability, tuple_output) + ): + if isinstance(out, torch.Tensor): + if not differentiable: + non_differentiable_tensors.append(out) + continue + if isinstance(out, list): + if not differentiable: + non_differentiable_tensors.extend(out) + continue + if differentiable: + raise RuntimeError( + f"With output_differentiability={output_differentiability}. " + f"At idx {idx}, we received an object of type {type(out)} that " + f"is not a Tensor, so it cannot have been marked as differentiable in " + f"output_differentiability." + ) + if non_differentiable_tensors: + ctx.mark_non_differentiable(*non_differentiable_tensors) + + +def construct_autograd_kernel( + schema, + output_differentiability, + custom_op, + op_overload, + save_for_backward_fn, + backward_fn, +): + def apply(*args): + flat_args, spec = pytree.tree_flatten(args) + out_spec = None + + def forward(ctx, *flat_args): + ctx.set_materialize_grads(True) + args = pytree.tree_unflatten(list(flat_args), spec) + with torch._C._AutoDispatchBelowAutograd(): + output = op_overload(*args) + + # We use the info about args to give better error messages in backward + args_info = namedtuple_args(schema, pytree.tree_map(type, args)) + + save_for_backward_fn_inputs = namedtuple_args(schema, args) + to_save = save_for_backward_fn(save_for_backward_fn_inputs, output) + + save_pytree_for_backward(ctx, (to_save, args_info)) + mark_non_differentiable(ctx, output, output_differentiability) + + nonlocal out_spec + flat_output, out_spec = pytree.tree_flatten(output) + return tuple(flat_output) + + def backward(ctx, *flat_grad_output): + if out_spec is None: + raise AssertionError("out_spec is unexpectedly None") + grads = pytree.tree_unflatten(list(flat_grad_output), out_spec) + saved, args_info = unpack_saved(ctx) + # There is nothing on the ctx object for now, it is just there so + # that we can add additional things in the future. + inner_ctx = object() + if not isinstance(grads, tuple): + grads = (grads,) + grad_inputs_dict = backward_fn(inner_ctx, saved, *grads) + + # Massage the grad_inputs_dict to a form acceptable by + # autograd.Function. + validate_grad_inputs_dict(grad_inputs_dict, custom_op, args_info) + return grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info) + + generated_cls = gen_autograd_function( + custom_op._opname + "_customop", forward, backward + ) + + flat_output = generated_cls.apply(*flat_args) + if out_spec is None: + raise AssertionError("out_spec is unexpectedly None") + return pytree.tree_unflatten(list(flat_output), out_spec) + + return apply + + +def gen_autograd_function(name, forward, backward): + generated_cls = type( + name, + (torch.autograd.Function,), + { + "forward": staticmethod(forward), + "backward": staticmethod(backward), + }, + ) + return generated_cls + + +@functools.lru_cache +def namedtuple_args_cls(schema): + attribs = [arg.name for arg in schema.arguments.flat_all] + name = str(schema.name) + "_args" + # mypy doesn't support dynamic namedtuple name + tuple_cls = namedtuple(name, attribs) # type: ignore[misc] + return tuple_cls + + +def namedtuple_args(schema, args): + if not isinstance(args, tuple): + raise AssertionError(f"expected tuple, got {type(args)}") + tuple_cls = namedtuple_args_cls(schema) + return tuple_cls(*args) + + +def validate_grad_inputs_dict(grad_inputs_dict, forward_op, args_info): + def error(what): + backward = forward_op._get_impl("backward") + raise RuntimeError( + f"In the backward function defined for {forward_op} at " + f"{backward.location} using the CustomOp API, {what}" + ) + + if not isinstance(grad_inputs_dict, dict): + error( + f"expected the output of the backward function to be a dict but " + f"got {type(grad_inputs_dict)}" + ) + + expected_keys = { + arg.name + for arg in forward_op._schema.arguments.flat_all + if arg.type.is_tensor_like() + } + actual_keys = grad_inputs_dict.keys() + if expected_keys != actual_keys: + error( + f"expected the returned grad_input dict to have keys " + f"{expected_keys} but got {actual_keys}. The backward " + f"function must return a gradient (can be None) for each arg " + f"to the CustomOp that may be a Tensor or Sequence[Tensor]. " + f"Args declared to be non-Tensor-like types should not appear " + f"in the grad_input dict" + ) + + for name, grad in grad_inputs_dict.items(): + arg_info = getattr(args_info, name) + + if isinstance(arg_info, list): + if not isinstance(grad, (tuple, list)): + error( + f"for input '{name}' expected the grad_input dict to " + f"hold a list of gradients but got object of type " + f"{type(grad)}." + ) + if len(grad) != len(arg_info): + error( + f"for input '{name}' expected the grad_input dict to " + f"hold a list of {len(arg_info)} gradients but got " + f"{len(grad)}" + ) + for idx, (g, info) in enumerate(zip(grad, arg_info)): + if g is None: + continue + if not isinstance(g, torch.Tensor): + error( + f"for input '{name}' expected the grad_input dict to " + f"hold a list of None or Tensor gradients but got " + f"object of {type(g)} at index {idx}" + ) + if not issubclass(info, torch.Tensor): + error( + f"for input '{name}', got a Tensor as the gradient " + f"for the {idx}-th value but expected None because " + f"the {idx}-th value was not a Tensor (it was " + f"type {arg_info}" + ) + continue + + if grad is None: + continue + if not isinstance(grad, torch.Tensor): + error( + f"got object of type {type(grad)} as the gradient for input " + f"'{name}', " + f"but expected the gradient to be either None or a Tensor" + ) + if not issubclass(arg_info, torch.Tensor): + error( + f"got a Tensor as the gradient for input '{name}' but " + f"expected None as the gradient because input '{name}' " + f"was not a Tensor (it was type {arg_info})." + ) + + +def grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info): + result = [] + for name, arg_info in args_info._asdict().items(): + if name not in grad_inputs_dict: + result.append(pytree.tree_map(lambda x: None, arg_info)) + continue + result.append(grad_inputs_dict[name]) + return tuple(pytree.tree_leaves(result)) + + +# Saves "stuff" (a pytree) onto the ctx object. Use unpack_saved to unpack it. +# autograd.Function prefers that users use ctx.save_for_backward to +# save Tensors (to avoid reference cycles) and for non-Tensors to go onto the +# ctx object. +def save_pytree_for_backward(ctx, stuff): + flat_stuff, spec = pytree.tree_flatten(stuff) + num_elts = len(flat_stuff) + tensor_idxs = [ + idx for idx, thing in enumerate(flat_stuff) if isinstance(thing, torch.Tensor) + ] + non_tensor_idxs = [ + idx + for idx, thing in enumerate(flat_stuff) + if not isinstance(thing, torch.Tensor) + ] + tensors = [thing for thing in flat_stuff if isinstance(thing, torch.Tensor)] + non_tensors = [thing for thing in flat_stuff if not isinstance(thing, torch.Tensor)] + + ctx.spec = spec + ctx.num_elts = num_elts + ctx.save_for_backward(*tensors) + ctx.tensor_idxs = tensor_idxs + ctx.saved_non_tensors = non_tensors + ctx.non_tensor_idxs = non_tensor_idxs + + +# Inverse operation to save_pytree_for_backward +def unpack_saved(ctx): + flat_stuff = [None] * ctx.num_elts + for tensor, idx in zip(ctx.saved_tensors, ctx.tensor_idxs): + flat_stuff[idx] = tensor + for non_tensor, idx in zip(ctx.saved_non_tensors, ctx.non_tensor_idxs): + flat_stuff[idx] = non_tensor + stuff = pytree.tree_unflatten(flat_stuff, ctx.spec) + return stuff diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/impl.py b/.venv/lib/python3.12/site-packages/torch/_custom_op/impl.py new file mode 100644 index 0000000000000000000000000000000000000000..03a76244f8353a05d46606e93778b18991257552 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_custom_op/impl.py @@ -0,0 +1,718 @@ +# mypy: allow-untyped-defs +import dataclasses +import functools +import inspect +import sys +import typing +import warnings +import weakref + +import torch +import torch._C as _C +import torch._library.infer_schema +import torch.library as library +from torch._library.infer_schema import infer_schema +from torch.library import get_ctx +from torchgen.model import ( + BaseTy, + BaseType, + FunctionSchema, + ListType, + OperatorName, + SchemaKind, +) + +from .autograd import autograd_kernel_indirection, construct_autograd_kernel + + +""" +torch._custom_op is deprecated. We shipped a production-ready version of it into torch.library. +Please use those APIs instead. +""" + +__all__ = ["custom_op", "CustomOp", "get_ctx"] + + +SUPPORTED_DEVICE_TYPE_TO_KEY = { + "cpu": "CPU", + "cuda": "CUDA", +} + +# We will not let users register CustomOps with anything that could look like +# PyTorch internals to avoid confusion. +RESERVED_NS = { + "prim", + "prims", + "aten", + "at", + "torch", + "pytorch", +} + + +def warn_deprecated(): + warnings.warn( + "torch._custom_op is deprecated and will be removed in PyTorch 2.6, please " + "use the equivalent torch.library API instead.", + DeprecationWarning, + stacklevel=2, + ) + + +def custom_op(qualname: str, manual_schema: str | None = None) -> typing.Callable: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + warn_deprecated() + + def inner(func): + if not inspect.isfunction(func): + raise ValueError( + f"custom_op(...)(func): Expected `func` to be a Python " + f"function, got: {type(func)}" + ) + + ns, name = parse_qualname(qualname) + validate_namespace(ns) + if func.__name__ != name: + raise ValueError( + f"custom_op(qualname='{qualname}', ...)(func): expected `func` " + f"to have name '{name}' but got '{func.__name__}'. " + f"Please either change the name of `func` or the qualname that " + f"is passed to `custom_op`" + ) + + schema = ( + infer_schema(func, mutates_args=()) + if manual_schema is None + else manual_schema + ) + schema_str = f"{name}{schema}" + function_schema = FunctionSchema.parse(schema_str) + validate_schema(function_schema) + if manual_schema is not None: + validate_function_matches_schema(function_schema, func) + + lib = library.Library(ns, "FRAGMENT") + lib.define(schema_str) + ophandle = find_ophandle_or_throw(ns, function_schema.name) + result = CustomOp( + lib, ns, function_schema, name, ophandle, _private_access=True + ) + + result.__name__ = func.__name__ # pyrefly: ignore [bad-assignment] + result.__module__ = func.__module__ + result.__doc__ = func.__doc__ + + library.impl(lib, result._opname, "Autograd")( + autograd_kernel_indirection(weakref.proxy(result)) + ) + + torch._C._dispatch_set_report_error_callback( + ophandle, functools.partial(report_error_callback, weakref.proxy(result)) + ) + + return result + + return inner + + +# Global dictionary holding references to all CustomOp objects +# Yes, it keeps all CustomOps alive (see NOTE [CustomOp lifetime]) +# Used to query the CustomOp associated with a specific C++ dispatcher operator. +# An example usage is FakeTensor: FakeTensor checks if a specific operator +# has an implementation registered via the CustomOp API. +# Indexed by qualname (e.g. aten::foo) +global_registry: dict[str, "CustomOp"] = {} + + +class CustomOp: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + + def __init__( + self, lib, cpp_ns, schema, operator_name, ophandle, *, _private_access=False + ): + super().__init__() + warn_deprecated() + if not _private_access: + raise RuntimeError( + "The CustomOp constructor is private and we do not guarantee " + "BC for it. Please use custom_op(...) to create a CustomOp object" + ) + name = f"{cpp_ns}::{operator_name}" + self._schema = schema + self._cpp_ns = cpp_ns + self._lib: library.Library = lib + self._ophandle: _C._DispatchOperatorHandle = ophandle + # Has the name of the op, e.g. "foo". We cache here for convenience. + self._opname: str = operator_name + # this is _opname but with namespace. e.g. "custom::foo" + self._qualname: str = name + self.__name__ = None # mypy requires this + # NB: Some of these impls are registered as kernels to DispatchKeys. + # Modifying the _impls dict directly won't do anything in that case. + self._impls: dict[str, FuncAndLocation | None] = {} + # See NOTE [CustomOp autograd kernel indirection] + self._registered_autograd_kernel_indirection = False + + global_registry[self._qualname] = self + + def _register_autograd_kernel_indirection(self): + if self._registered_autograd_kernel_indirection: + raise AssertionError("autograd kernel indirection already registered") + self._lib.impl( + self._opname, autograd_kernel_indirection(weakref.proxy(self)), "Autograd" + ) + self._registered_autograd_kernel_indirection = True + + # Records the impl and the source location in self._impls + # Note that this doesn't cause torch.library to use the impl, that + # needs to be done in a separate self._lib.impl call. + def _register_impl(self, kind, func, stacklevel=2): + if self._has_impl(kind): + func_and_location = self._impls[kind] + if func_and_location is None: + raise AssertionError("func_and_location is unexpectedly None") + location = func_and_location.location + raise RuntimeError( + f"Attempting to register a {kind} impl for operator {self._qualname} " + f"that already has a {kind} impl registered from Python at " + f"{location}. This is not supported." + ) + frame = inspect.getframeinfo(sys._getframe(stacklevel)) + location = f"{frame.filename}:{frame.lineno}" + self._impls[kind] = FuncAndLocation(func, location) + + def _get_impl(self, kind): + return self._impls[kind] + + def _has_impl(self, kind): + return kind in self._impls + + def _destroy(self): + # NOTE: [CustomOp lifetime] + # A CustomOp, once created, lives forever. The mechanism is that the + # global registry holds a reference to it. However, to make testing + # easier, we want to be able to destroy CustomOp objects. + # CustomOp._destroy does the job, though it leaves the CustomOp + # in a garbage state. + del self._lib + + opnamespace = getattr(torch.ops, self._cpp_ns) + if hasattr(opnamespace, self._opname): + delattr(opnamespace, self._opname) + + del global_registry[self._qualname] + + def __repr__(self): + return f'' + + def __call__(self, *args, **kwargs): + # Bypass torch.ops.* and directly do OperatorHandle::callBoxed. + # Using torch.ops.* is a bit of a pain (it can be slow and it has lifetime + # issues from caching operators that make testing CustomOp difficult). + result = _C._dispatch_call_boxed(self._ophandle, *args, **kwargs) + return result + + def impl( + self, + device_types: str | typing.Iterable[str], + _stacklevel=2, + ) -> typing.Callable: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + if isinstance(device_types, str): + device_types = [device_types] + for device_type in device_types: + validate_device_type(device_type) + + def inner(f): + for device_type in set(device_types): + self._check_doesnt_have_library_impl(device_type) + self._register_impl(device_type, f, stacklevel=_stacklevel) + dispatch_key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type] + library.impl(self._lib, self._opname, dispatch_key)(f) + return f + + return inner + + def _check_doesnt_have_library_impl(self, device_type): + if self._has_impl(device_type): + return + key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type] + if _C._dispatch_has_computed_kernel_for_dispatch_key(self._qualname, key): + raise RuntimeError( + f"impl(..., device_types={device_type}): the operator {self._qualname} " + f"already has an implementation for this device type via a " + f"pre-existing torch.library or TORCH_LIBRARY registration." + ) + + def impl_factory(self) -> typing.Callable: + r"""Register an implementation for a factory function.""" + + def inner(f): + self._register_impl("factory", f) + library.impl(self._lib, self._opname, "BackendSelect")(f) + return f + + return inner + + def impl_abstract(self, _stacklevel=2) -> typing.Callable: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + + def inner(f): + self._check_doesnt_have_library_meta_impl() + self._register_impl("abstract", f, stacklevel=_stacklevel) + location = self._get_impl("abstract").location + + qualname = self._qualname + + # Handle DispatchKey.Meta registration + @functools.wraps(f) + def f_with_ctx(*args, **kwargs): + def error_on_ctx(): + raise RuntimeError( + f"Attempted to call get_ctx() for the meta implementation " + f"for {qualname}." + f"You have presumably called get_ctx() because the operator " + f"has a data-dependent output shape; if so, there is no " + f"such meta implementation and this error is the correct " + f"behavior. Otherwise, please remove the call to get_ctx() " + f"in the implementation registered with impl_abstract " + f"at {location}" + ) + + with torch._library.fake_impl.set_ctx_getter(error_on_ctx): + return f(*args, **kwargs) + + self._lib.impl(self._opname, f_with_ctx, "Meta") + return f + + return inner + + def _check_can_register_backward(self): + def error(detail): + raise RuntimeError( + f"Cannot use torch._custom_ops APIs to register backward " + f"formula for {detail}. Got operator " + f"{self._qualname} with schema: {schema}" + ) + + schema = self._schema + if schema.kind() != SchemaKind.functional: + error("non-functional operator") + + rets = schema.returns + if not schema.returns: + error("operator with no returns") + + if len(rets) <= 0: + raise AssertionError(f"expected at least one return, got {len(rets)}") + is_non_mutating_view = any( + r.annotation is not None and not r.annotation.is_write for r in rets + ) + if is_non_mutating_view: + error("operator that returns views") + + # We make assumptions about the schema's return types. + allowed_return_types = { + BaseType(BaseTy.int): "int", + BaseType(BaseTy.SymInt): "SymInt", + BaseType(BaseTy.bool): "bool", + BaseType(BaseTy.float): "float", + BaseType(BaseTy.Tensor): "Tensor", + ListType(BaseType(BaseTy.Tensor), None): "List[Tensor]", + } + for ret in schema.returns: + if ret.type in allowed_return_types: + continue + error( + f"operator with return not in {list(allowed_return_types.values())} (got {ret.type})" + ) + + def _check_doesnt_have_library_autograd_impl(self): + if self._registered_autograd_kernel_indirection: + return + + if _C._dispatch_has_kernel_for_dispatch_key( + self._qualname, "CompositeImplicitAutograd" + ): + raise RuntimeError( + f"impl_backward/impl_save_for_backward: the operator {self._qualname} " + f"already has an implementation for this device type via a " + f"pre-existing registration to DispatchKey::CompositeImplicitAutograd." + f"CompositeImplicitAutograd operators do not need an autograd formula; " + f"instead, the operator will decompose into its constituents and those " + f"can have autograd formulas defined on them." + ) + + # We can improve this by adding "all Autograd keys", but + # realistically people will just be using this API for CPU/CUDA for now. + for key in ["Autograd", "AutogradCPU", "AutogradCUDA"]: + if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, key): + raise RuntimeError( + f"impl_backward/impl_save_for_backward: " + f"the operator {self._qualname} already has an Autograd kernel " + f"registered to DispatchKey::{key} via a pre-existing " + f"torch.library or TORCH_LIBRARY registration. Please either " + f"remove those registrations or don't use the torch._custom_ops APIs" + ) + + def _check_doesnt_have_library_meta_impl(self): + if self._has_impl("abstract"): + return + + # If the user's operator is CompositeExplicitAutograd, + # allow them to impl_abstract. This is being pragmatic + # (existing custom ops may have CompositeExplicitAutograd + # registration that don't work with Meta kernels, so this + # gives them an escape hatch). + if _C._dispatch_has_kernel_for_dispatch_key( + self._qualname, "CompositeExplicitAutograd" + ) and not _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"): + return + + # Otherwise, if the user's already has a Meta kernel or their + # op is CompositeImplicitAutograd or some other alias dispatch key, + # raise. + + # Special case for CompositeImplicitAutograd + if _C._dispatch_has_kernel_for_dispatch_key( + self._qualname, "CompositeImplicitAutograd" + ): + raise RuntimeError( + f"impl_abstract(...): the operator {self._qualname} " + f"already has an implementation for this device type via a " + f"pre-existing registration to DispatchKey::CompositeImplicitAutograd." + f"CompositeImplicitAutograd operators do not need an abstract impl; " + f"instead, the operator will decompose into its constituents and those " + f"can have abstract impls defined on them." + ) + + if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"): + raise RuntimeError( + f"impl_abstract(...): the operator {self._qualname} " + f"already has a DispatchKey::Meta implementation via a " + f"pre-existing torch.library or TORCH_LIBRARY registration. " + f"Please either remove that registration or don't call impl_abstract." + ) + + # NOTE ["backward", "save_for_backward", and "autograd"] + # As a part of the explicit autograd API, a user must provide us + # a "save_for_backward" function and a "backward" function. + # When both of these have been provided, then we automatically + # construct the "autograd" kernel. + def _register_autograd_kernel(self): + if not self._has_impl("backward"): + raise AssertionError("backward impl must be registered first") + if not self._has_impl("save_for_backward"): + raise AssertionError("save_for_backward impl must be registered first") + kernel = construct_autograd_kernel( + self._schema, + self._output_differentiability, + self, + get_op(self._qualname), + self._get_impl("save_for_backward").func, + self._get_impl("backward").func, + ) + self._register_impl("autograd", kernel) + + def impl_save_for_backward(self, _stacklevel=2): + r"""Register a function that tells us what to save for backward. + + Please see impl_backward for more details. + """ + + def inner(f): + self._check_can_register_backward() + self._check_doesnt_have_library_autograd_impl() + if not self._registered_autograd_kernel_indirection: + self._register_autograd_kernel_indirection() + self._register_impl("save_for_backward", f, stacklevel=_stacklevel) + if self._has_impl("backward"): + self._register_autograd_kernel() + + return inner + + def impl_backward(self, output_differentiability=None, _stacklevel=2): + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + if output_differentiability is not None: + + def yell(): + raise RuntimeError( + f"impl_backward(output_differentiability): expected " + f"output_differentiability to be a list of bools with " + f"length equal to the number of outputs of this CustomOp " + f"got: {output_differentiability}" + ) + + if not isinstance(output_differentiability, list): + yell() + for diff in output_differentiability: + if not isinstance(diff, bool): + yell() + if len(self._schema.returns) != len(output_differentiability): + yell() + + def inner(f): + self._check_can_register_backward() + self._check_doesnt_have_library_autograd_impl() + if not self._registered_autograd_kernel_indirection: + self._register_autograd_kernel_indirection() + self._register_impl("backward", f, stacklevel=_stacklevel) + self._output_differentiability = output_differentiability + if self._has_impl("save_for_backward"): + self._register_autograd_kernel() + + return inner + + +@dataclasses.dataclass +class FuncAndLocation: + func: typing.Callable + location: str + + +def find_ophandle_or_throw(cpp_ns: str, operator_name: OperatorName): + overload_name = ( + "" if operator_name.overload_name is None else operator_name.overload_name + ) + return _C._dispatch_find_schema_or_throw( + f"{cpp_ns}::{str(operator_name.name)}", overload_name + ) + + +def validate_namespace(ns: str) -> None: + if "." in ns: + raise ValueError( + f'custom_op(..., ns="{ns}"): expected ns to not contain any . (and be a ' + f"valid variable name)" + ) + if ns in RESERVED_NS: + raise ValueError( + f"custom_op(..., ns='{ns}'): '{ns}' is a reserved namespace, " + f"please choose something else. " + ) + + +def validate_schema(schema: FunctionSchema) -> None: + if not torch._library.utils.is_functional_schema(schema): + raise ValueError( + f"custom_op only supports functional operators " + f"(ops that do not mutate any inputs, do not return " + f"views of the inputs, and has at least one return). " + f"Got the following non-functional schema: {schema}" + ) + + # For simplicity: don't allow self arguments + if schema.arguments.self_arg is not None: + raise ValueError( + f"custom_op does not support arguments named 'self'. Please " + f"rename your argument. Got: {schema}" + ) + + +def parse_qualname(qualname: str) -> tuple[str, str]: + names = qualname.split("::", 1) + if len(names) != 2: + raise ValueError( + f"Expected there to be a namespace in {qualname}, i.e. The " + f"operator name should look something like ns::foo" + ) + if "." in names[1]: + raise ValueError( + f"The torch.custom_ops APIs do not handle overloads, " + f"i.e. operator names with '.' in them. " + f"Please name your operator something like ns::foo. " + f"Got: {qualname}" + ) + return names[0], names[1] + + +def validate_device_type(device_type: str) -> None: + if device_type not in SUPPORTED_DEVICE_TYPE_TO_KEY: + raise ValueError( + f"CustomOp.impl(device_types=[{device_type}, ...]): we only support device_type " + f"in {SUPPORTED_DEVICE_TYPE_TO_KEY.keys()}." + ) + + +def supported_param(param: inspect.Parameter) -> bool: + return param.kind in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + ) + + +def validate_function_matches_schema( + schema: FunctionSchema, func: typing.Callable +) -> None: + sig = inspect.signature(func) + + if not all(supported_param(p) for p in sig.parameters.values()): + raise ValueError( + f"custom_op(..., manual_schema)(func): positional-only args, " + f"varargs, and kwargs are not supported. Please rewrite `func` " + f"to not have them. Got `func` with signature: {sig}" + ) + + if ( + any( + p.annotation is not inspect.Parameter.empty for p in sig.parameters.values() + ) + or sig.return_annotation is not inspect.Signature.empty + ): + raise ValueError( + f"custom_op(..., manual_schema)(func): When passing in a manual " + f"schema, we expect `func` to have no type annotations to avoid " + f"ambiguity. Got `func` with signature: {sig}" + ) + + positional = [ + (name, param) + for name, param in sig.parameters.items() + if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + ] + kwargonly = [ + (name, param) + for name, param in sig.parameters.items() + if param.kind == inspect.Parameter.KEYWORD_ONLY + ] + + def error(): + raise ValueError( + f"custom_op(..., manual_schema)(func): When passing in a manual " + f"schema, we expect `func`'s signature to match `manual_schema` " + f"(aside from type annotations). " + f"func's signature: {sig}, manual_schema: {schema}" + ) + + def error_default_args(): + raise ValueError( + f"custom_op(..., manual_schema)(func): " + f"neither func nor manual_schema should have default " + f"arguments. Got " + f"func's signature: {sig}, manual_schema: {schema}" + ) + + def compare(sig_args, schema_args): + if len(sig_args) != len(schema_args): + error() + for (name, param), arg in zip(sig_args, schema_args): + if name != arg.name: + error() + if param.default is not inspect.Parameter.empty or arg.default is not None: + error_default_args() + + compare(positional, schema.arguments.flat_positional) + compare(kwargonly, schema.arguments.flat_kwarg_only) + + +def report_error_callback(custom_op: typing.Any, key: str) -> None: + if key == "Undefined": + raise NotImplementedError( + f"{custom_op}: There were no Tensor inputs to this operator " + f"(e.g. you passed an empty list of Tensors). If your operator is a " + f"factory function (that is, it takes no Tensors and constructs " + f"a new one), then please use CustomOp.impl_factory to register " + f"an implementation for it" + ) + if key == "Meta": + raise NotImplementedError( + f"{custom_op}: when running with device='Meta' tensors: there is no " + f"abstract impl registered for this CustomOp. Please register one via " + f"CustomOp.impl_abstract to get this CustomOp to work with Meta tensors" + ) + if key in ("CPU", "CUDA"): + device = key.lower() + raise NotImplementedError( + f"{custom_op}: when running with device='{device}' tensors: there is no " + f"{device} impl registered for this CustomOp. Please register one via " + f"CustomOp.impl(device_type='{device}')" + ) + raise NotImplementedError( + f"{custom_op}: No implementation for dispatch key {key}. It is likely " + f"that we have not added this functionality yet, please either open an " + f"issue or if you're feeling adventurous, use the low-level " + f"torch.library API" + ) + + +def custom_op_from_existing(op): + ns = op.namespace + lib = torch.library.Library(ns, "FRAGMENT") + name = op.name().split("::")[-1] + schema_str = str(op._schema) + # CustomOp expects the schema string without the namespace + schema_str = schema_str.rsplit("::", maxsplit=1)[-1] + schema = FunctionSchema.parse(schema_str) + return CustomOp(lib, ns, schema, name, op, _private_access=True) + + +def get_op(qualname): + def error_not_found(): + raise ValueError( + f"Could not find the operator {qualname}. Please make sure you have " + f"already registered the operator and (if registered from C++) " + f"loaded it via torch.ops.load_library." + ) + + ns, name = parse_qualname(qualname) + if not hasattr(torch.ops, ns): + error_not_found() + opnamespace = getattr(torch.ops, ns) + if not hasattr(opnamespace, name): + error_not_found() + packet = getattr(opnamespace, name) + if not hasattr(packet, "default"): + error_not_found() + return packet.default + + +def _find_custom_op(qualname, also_check_torch_library=False): + if qualname in global_registry: + return global_registry[qualname] + if not also_check_torch_library: + raise RuntimeError( + f'Could not find custom op "{qualname}". Did you register it via ' + f"the torch._custom_ops API?" + ) + overload = get_op(qualname) + result = custom_op_from_existing(overload) + return result + + +def get_abstract_impl(qualname): + if qualname not in torch._custom_op.impl.global_registry: + return None + custom_op = torch._custom_op.impl.global_registry[qualname] + if custom_op is None: + return None + if not custom_op._has_impl("abstract"): + return None + return custom_op._get_impl("abstract").func + + +def _custom_op_with_schema(qualname, schema, needs_fixed_stride_order=True): + ns, name = qualname.split("::") + schema_str = f"{name}{schema}" + function_schema = FunctionSchema.parse(schema_str) + validate_schema(function_schema) + tags = [torch._C.Tag.needs_fixed_stride_order] if needs_fixed_stride_order else [] + lib = library.Library(ns, "FRAGMENT") + lib.define(schema_str, tags=tags) + ophandle = find_ophandle_or_throw(ns, function_schema.name) + result = CustomOp(lib, ns, function_schema, name, ophandle, _private_access=True) + result._register_autograd_kernel_indirection() + + torch._C._dispatch_set_report_error_callback( + ophandle, functools.partial(report_error_callback, weakref.proxy(result)) + ) + return get_op(qualname) diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_ops.py b/.venv/lib/python3.12/site-packages/torch/_custom_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5203da640fa58e9ab7bf6785eb26ae1186059bee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_custom_ops.py @@ -0,0 +1,326 @@ +# mypy: allow-untyped-defs +import inspect + +from torch._custom_op.impl import ( + _custom_op_with_schema, + _find_custom_op, + infer_schema, + parse_qualname, + validate_namespace, +) +from torch.library import get_ctx + + +__all__ = [ + "custom_op", + "impl", + "impl_abstract", + "get_ctx", + "impl_save_for_backward", + "impl_backward", +] + + +def custom_op(qualname, func_or_schema=None): + r"""Register a new custom operator + + In PyTorch, defining an op (short for "operator") is a two step-process: + - we need to define the op (by providing an operator name and schema) + - we need to implement behavior for how the operator interacts with + various PyTorch subsystems, like CPU/CUDA Tensors, Autograd, etc. + + This entrypoint defines the custom operator (the first step) + you must then perform the second step by calling various + ``impl_*`` APIs. + + This API may be used as a decorator (see examples). + + For a detailed guide on custom ops, please see + https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk + + Arguments: + qualname (str): Should be a string that looks like + "namespace::operator_name". Operators in PyTorch need a namespace to + avoid name collisions; a given operator may only be created once. + If you are writing a Python library, we recommend the namespace to + be the name of your top-level module. + func_or_schema (Union[Callable, str]): Each PyTorch operator needs a + schema that tells PyTorch the types of the inputs/outputs. + If this is a Callable, we will automatically infer the schema from + the type annotations on the function (see examples). Otherwise, + if you don't want to use type annotations, you may provide us the + schema string. + + Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> import torch + >>> import numpy as np + >>> from torch import Tensor + >>> + >>> # Step 1: define the custom op. + >>> # We need to provide the API a "prototype function" + >>> # (a function that returns NotImplementedError), from which + >>> # we will infer the types of the inputs and outputs. + >>> @torch._custom_ops.custom_op("mylibrary::numpy_sin") + >>> def numpy_sin(x: Tensor) -> Tensor: + >>> raise NotImplementedError + >>> + >>> # The custom op is now accessible via the torch.ops module: + >>> torch.ops.mylibrary.numpy_sin + >>> + >>> # Step 2: Register an implementation for various PyTorch subsystems + >>> + >>> # Register an implementation for CPU tensors + >>> @torch._custom_ops.impl("mylibrary::numpy_sin", device_types="cpu") + >>> def numpy_sin_impl_cpu(x): + >>> return torch.from_numpy(np.sin(x.numpy())) + >>> + >>> # Register an implementation for CUDA tensors + >>> @torch._custom_ops.impl("mylibrary::numpy_sin", device_types="cuda") + >>> def numpy_sin_impl_cuda(x): + >>> return torch.from_numpy(np.sin(x.cpu().numpy())).to(x.device) + >>> + >>> x = torch.randn(3) + >>> torch.ops.mylibrary.numpy_sin(x) # calls numpy_sin_impl_cpu + >>> + >>> x_cuda = x.cuda() + >>> torch.ops.mylibrary.numpy_sin(x) # calls numpy_sin_impl_cuda + + """ + ns, name = parse_qualname(qualname) + validate_namespace(ns) + + def inner(func): + if not inspect.isfunction(func): + raise ValueError( + f"custom_op(...)(func): Expected `func` to be a Python " + f"function, got: {type(func)}" + ) + + if func.__name__ != name: + raise ValueError( + f"custom_op(qualname='{qualname}', ...)(func): expected `func` " + f"to have name '{name}' but got '{func.__name__}'. " + f"Please either change the name of `func` or the qualname that " + f"is passed to `custom_op`" + ) + + schema = infer_schema(func, mutates_args=()) + _custom_op_with_schema(qualname, schema) + return func + + if func_or_schema is None: + return inner + if isinstance(func_or_schema, str): + _custom_op_with_schema(qualname, func_or_schema) + else: + return inner(func_or_schema) + + +def impl(qualname, *, device_types=("cpu", "cuda"), func=None): + r"""Register an implementation for a device type for this custom op. + + If the op is passed multiple Tensor inputs with different device + types, it will dispatch to the registered implementation for the highest + priority device type among those present. + The supported device types, in order of priority, are {'cuda', 'cpu'}. + + This API may be used as a decorator (see examples). + + For a detailed guide on custom ops, please see + https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk + + Arguments: + device_types (str or Iterable[str]): the device type(s) to register the function for. + + Example:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> import torch + >>> import numpy as np + >>> from torch import Tensor + >>> + >>> # Step 1: define the custom op. + >>> # We need to provide the API a "prototype function" + >>> # (a function that returns NotImplementedError), from which + >>> # we will infer the types of the inputs and outputs. + >>> @torch._custom_ops.custom_op("mylibrary::numpy_cos") + >>> def numpy_cos(x: Tensor) -> Tensor: + >>> raise NotImplementedError + >>> + >>> # The custom op is now accessible via the torch.ops module: + >>> torch.ops.mylibrary.numpy_cos + >>> + >>> # Step 2: Register an implementation for various PyTorch subsystems + >>> + >>> # Register an implementation for CPU tensors + >>> @torch._custom_ops.impl("mylibrary::numpy_cos", device_types="cpu") + >>> def numpy_cos_impl_cpu(x): + >>> return torch.from_numpy(np.cos(x.numpy())) + >>> + >>> # Register an implementation for CUDA tensors + >>> @torch._custom_ops.impl("mylibrary::numpy_cos", device_types="cuda") + >>> def numpy_cos_impl_cuda(x): + >>> return torch.from_numpy(np.cos(x.cpu().numpy())).to(x.device) + >>> + >>> x = torch.randn(3) + >>> torch.ops.mylibrary.numpy_cos(x) # calls numpy_cos_impl_cpu + >>> + >>> x_cuda = x.cuda() + >>> torch.ops.mylibrary.numpy_cos(x) # calls numpy_cos_impl_cuda + + """ + + def inner(func): + custom_op = _find_custom_op(qualname, also_check_torch_library=True) + custom_op.impl(device_types, _stacklevel=3)(func) + return func + + if func is None: + return inner + return inner(func) + + +def impl_abstract(qualname, *, func=None): + r"""Register an abstract implementation for this operator. + + An "abstract implementation" specifies the behavior of this operator on + Tensors that carry no data. Given some input Tensors with certain properties + (sizes/strides/storage_offset/device), it specifies what the properties of + the output Tensors are. + + The abstract implementation has the same signature as the operator. + It is run for both FakeTensors and meta tensors. To write an abstract + implementation, assume that all Tensor inputs to the operator are + regular CPU/CUDA/Meta tensors, but they do not have storage, and + you are trying to return regular CPU/CUDA/Meta tensor(s) as output. + The abstract implementation must consist of only PyTorch operations + (and may not directly access the storage or data of any input or + intermediate Tensors). + + This API may be used as a decorator (see examples). + + For a detailed guide on custom ops, please see + https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk + + Examples:: + >>> import numpy as np + >>> from torch import Tensor + >>> + >>> # Example 1: an operator without data-dependent output shape + >>> @torch._custom_ops.custom_op("mylibrary::custom_linear") + >>> def custom_linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor: + >>> raise NotImplementedError + >>> + >>> @torch._custom_ops.impl_abstract("mylibrary::custom_linear") + >>> def custom_linear_abstract(x, weight): + >>> assert x.dim() == 2 + >>> assert weight.dim() == 2 + >>> assert bias.dim() == 1 + >>> assert x.shape[1] == weight.shape[1] + >>> assert weight.shape[0] == bias.shape[0] + >>> assert x.device == weight.device + >>> + >>> return (x @ weight.t()) + bias + >>> + >>> # Example 2: an operator with data-dependent output shape + >>> @torch._custom_ops.custom_op('mylibrary::custom_nonzero') + >>> def custom_nonzero(x: Tensor) -> Tensor: + >>> ... + >>> + >>> @torch._custom_ops.impl_abstract("mylibrary::custom_nonzero") + >>> def custom_nonzero_abstract(x): + >>> # Number of nonzero-elements is data-dependent. + >>> # Since we cannot peek at the data in an abstract impl, + >>> # we use the ctx object to construct a new symint that + >>> # represents the data-dependent size. + >>> ctx = torch._custom_ops.get_ctx() + >>> nnz = ctx.create_unbacked_symint() + >>> shape = [x.dim(), nnz] + >>> result = x.new_empty(shape, dtype=torch.long) + >>> return result + >>> + >>> @torch._custom_ops.impl("mylibrary::custom_nonzero") + >>> def custom_nonzero_impl(x): + >>> x_np = to_numpy(x) + >>> res = np.stack(np.nonzero(x_np), axis=1) + >>> # unbacked symbolic ints in PyTorch must be >= 2, so we + >>> # constrain the range to at least 2 + >>> if res.shape[0] <= 1: + >>> raise RuntimeError("not supported") + >>> return torch.tensor(res, device=x.device) + + """ + import torch.library + + return torch.library.register_fake(qualname, func, _stacklevel=2) + + +def impl_save_for_backward(qualname, *, func=None): + r"""Register a function that tells us what to save for backward. + + Please see :func:`impl_backward` for more details. + """ + + def inner(func): + custom_op = _find_custom_op(qualname, also_check_torch_library=True) + custom_op.impl_save_for_backward(_stacklevel=3)(func) + return func + + if func is None: + return inner + return inner(func) + + +def impl_backward(qualname, output_differentiability=None, *, func=None): + r"""Registers a backward formula for an operator. + + In order for an operator to work with autograd, you need to register + a backward formula. There are two pieces to this: + 1. You must give us a function to specify what to save for backward. + Call this the "save for backward" function. + 2. You must give us a function that computes gradients. Call this the + "backward" function. + + Use `impl_save_for_backward` to define a "save for backward" function + that specifies what gets saved for backward. The function should accept + two arguments ``(inputs, output)`` and return the quantities to be saved + for backward. + + During runtime, when you call the operator in a forwards pass, PyTorch + will invoke the "save for backward" function with the inputs and output + of the operator. + + Use `impl_backward` to define the "backward" function. The backward + function must accept ``(ctx, saved, *grads)``: + - ``ctx`` is a context object where we may provide information + - ``saved`` is exactly what gets returned from the "save for backward" + function + - ``grads`` is one or more gradients. The number of gradients matches + the number of outputs of the operator. + + The backward function must return a dict that maps the name of + an input to the operator to its corresponding gradient. All inputs that + were declared to be Tensors in the operator definition must be accounted + for in the dict. The gradient may be a Tensor or None. + + For a detailed guide on custom ops, please see + https://docs.google.com/document/d/1aGWtgxV3HppuxQAdddyPrs74_aEntpkYt9MalnCKnhk + + """ + + def inner(func): + custom_op = _find_custom_op(qualname, also_check_torch_library=True) + custom_op.impl_backward(output_differentiability, _stacklevel=3)(func) + return func + + if func is None: + return inner + return inner(func) + + +def _destroy(qualname): + """De-registers a custom op. For testing purposes only""" + custom_op = _find_custom_op(qualname) + custom_op._destroy() diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/__init__.py b/.venv/lib/python3.12/site-packages/torch/_decomp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3083ba8222499cacc0ee35206090ac5eda8e0213 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_decomp/__init__.py @@ -0,0 +1,571 @@ +# mypy: allow-untyped-defs +import inspect +import typing +from collections import defaultdict +from collections.abc import Callable, Sequence +from functools import lru_cache, partial, wraps +from itertools import chain +from typing import Optional, TYPE_CHECKING, TypeVar, Union +from typing_extensions import ParamSpec + + +if TYPE_CHECKING: + from torch.export.decomp_utils import CustomDecompTable + +import torch +import torch.library +from torch._ops import HigherOrderOperator, OperatorBase, OpOverload, OpOverloadPacket +from torch._prims_common import CustomOutParamAnnotation +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.utils import _pytree as pytree + + +__all__ = [ + "decomposition_table", + "pre_autograd_decomposition_table", + "meta_table", + "register_decomposition", + "get_decompositions", + "core_aten_decompositions", + "_should_decompose_because_unsafe_op", +] + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +# TODO: relax key type here; torch registrations should be possible to; but +# right now this type is accurate +global_decomposition_table: dict[str, dict[torch._ops.OperatorBase, Callable]] = ( + defaultdict(dict) +) + +decomposition_table = global_decomposition_table["post_autograd"] +pre_autograd_decomposition_table = global_decomposition_table["pre_autograd"] +meta_table = global_decomposition_table["meta"] + + +def _should_decompose_because_unsafe_op(op: torch._ops.OperatorBase) -> bool: + """ + Returns True if the op must always decompose in export/compile tracing system + + In export, we always decompose certain CIA ops that are tagged with + maybe_aliasing_or_mutating because we statically need to know if the op is + mutating or not. But these CIA ops could have different behaviour in runtime. + + native_batch_norm is a prim op which has a wrong schema and it needs to be replaced + with correct schema. But until then, we will force decompose it via this tag. + """ + if not isinstance(op, torch._ops.OpOverload): + return False + if torch.Tag.maybe_aliasing_or_mutating in op.tags: + return True + return op is torch.ops.aten.native_batch_norm.default + + +def _add_op_to_registry(registry, op, fn): + """ + This is an internal API for adding an op to the decomposition table. + + If op is OpOverload, it will be added to the registry directly. + If op is OpOverloadPacket, all the valid overload_ops in the packet will be added to the registry. + """ + overloads: list[torch._ops.OpOverload] = [] + if isinstance(op, HigherOrderOperator): + # There's no concept of overloads for HigherOrderOperator + registry[op] = fn + return + elif isinstance(op, OpOverload): + overloads.append(op) + else: + if not isinstance(op, OpOverloadPacket): + raise AssertionError(f"expected OpOverloadPacket, got {type(op)}") + overloads.extend(op.op_overloads()) + + for op_overload in overloads: + if op_overload in registry: + raise RuntimeError(f"duplicate registrations for {op_overload}") + # TorchScript dumps a bunch of extra nonsense overloads + # which don't have corresponding dispatcher entries, we need + # to filter those out, e.g aten.add.float_int + if torch._C._dispatch_has_kernel(op_overload.name()): + registry[op_overload] = fn + schema = op_overload._schema + if registry is decomposition_table: + torch._C._fake_dispatch_register_decomp( + schema.name, schema.overload_name + ) + elif registry is meta_table: + torch._C._fake_dispatch_register_meta(schema.name, schema.overload_name) + elif registry is pre_autograd_decomposition_table: + # pre-autograd decomp not used by C++ faketensor + pass + elif any(registry is t for t in global_decomposition_table.values()): + raise AssertionError( + f"decomposition registry {registry!r} is not mirrored into " + "the C++ fake dispatch tables" + ) + + +def _convert_out_params(f): + out_annotation = f.__annotations__.get("out") + + # If there are no out params, do not wrap the function. + if not out_annotation: + return f + + # Hack to detect when out is a Tuple. There seems to be no pretty way of doing this + if getattr(out_annotation, "__origin__", None) is tuple: + sig = inspect.signature(f) + out_names = sig.return_annotation._fields + # If out is a tuple, we need to register a function that unpacks all the out + # elements as this is what native_functions.yaml expects + + @wraps(f) + def _fn(*args, **kwargs): + out_kwargs = tuple(kwargs.pop(o, None) for o in out_names) + # Either all of the out kwargs are set or none of them + is_none = out_kwargs[0] is None + if not all((o is None) == is_none for o in out_kwargs): + raise AssertionError( + f"all out kwargs must be set or none of them, got {out_kwargs}" + ) + return f(*args, **kwargs, out=None if is_none else out_kwargs) + + out_params = [ + inspect.Parameter( + o, + kind=inspect.Parameter.KEYWORD_ONLY, + default=None, + annotation=t, + ) + for o, t in zip(out_names, typing.get_args(out_annotation)) + ] + # Drop the out parameter and concatenate the new kwargs in the signature + params = chain((v for k, v in sig.parameters.items() if k != "out"), out_params) + _fn.__signature__ = inspect.Signature( # type: ignore[attr-defined] + parameters=params, # type: ignore[arg-type] + return_annotation=sig.return_annotation, + ) + # Drop the out parameter and concatenate the new kwargs in the annotations + _fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"} + for o in out_params: + _fn.__annotations__[o.name] = o.annotation + + # Propagate that this function is wrapped by `out_wrapper` + _fn._torch_decompositions_out_wrapper = f._torch_decompositions_out_wrapper # type: ignore[attr-defined] + + return _fn + + # Alternatively, there may be a single tensor out parameter with a name + # other than "out". This will need special treatment and is indicated by an + # annotation, which we will remove here so it is not exposed after wrapping. + custom_out_param_name = f.__annotations__.pop(CustomOutParamAnnotation, None) + if custom_out_param_name: + + @wraps(f) + def _fn(*args, **kwargs): + out_kwarg = kwargs.pop(custom_out_param_name, None) + return f(*args, **kwargs, out=out_kwarg) + + out_param = inspect.Parameter( + custom_out_param_name, + kind=inspect.Parameter.KEYWORD_ONLY, + default=None, + annotation=out_annotation, + ) + + # Drop the out parameter and concatenate the new kwarg in the signature + sig = inspect.signature(f) + params = chain( + (v for k, v in sig.parameters.items() if k != "out"), (out_param,) + ) + _fn.__signature__ = inspect.Signature( # type: ignore[attr-defined] + parameters=params, # type: ignore[arg-type] + return_annotation=sig.return_annotation, + ) + + # Drop the out parameter and concatenate the new kwargs in the annotations + _fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"} + _fn.__annotations__[out_param.name] = out_param.annotation + + return _fn + + return f + + +def register_decomposition( + aten_op, registry=None, *, type="post_autograd", unsafe=False +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + """ + A decorator to register a function as a decomposition to the Python + decomposition table. Use it like this:: + + @register_decomposition(torch.ops.aten.clamp_min) + def clamp_min(x): + return torch.clamp(self, min=min) + + If you are writing a new decomposition, consider contributing it + directly to PyTorch in torch._decomp.decompositions. + + This API is experimental; we are almost certainly going to extend + the API when we make decompositions eligible for use in transforms (e.g., + autograd) and not just backend tracing, where we then need to know if a + decomposition can be used to simulate a transform. + + By default, we also will register it to the Meta key of dispatcher, + and replace the c++ Meta implementation if there is already one. + + unsafe kwarg is for reuse of this function for registering non-function + things + """ + + if type not in {"post_autograd", "pre_autograd", "meta"}: + raise AssertionError( + f"type must be one of post_autograd, pre_autograd, or meta, got {type}" + ) + + def decomposition_decorator(fn: Callable[_P, _T]) -> Callable[_P, _T]: + orig_fn = fn + if not unsafe: + fn = _convert_out_params(fn) + + nonlocal registry + if registry is None: + registry = global_decomposition_table[type] + + def register(op): + _add_op_to_registry(registry, op, fn) + + # To handle allowing multiple aten_ops at once + pytree.tree_map_(register, aten_op) + return orig_fn + + return decomposition_decorator + + +def get_decompositions( + aten_ops: Sequence[torch._ops.OperatorBase | OpOverloadPacket], + type: str = "post_autograd", +) -> dict[torch._ops.OperatorBase, Callable]: + """ + Retrieve a dictionary of decompositions corresponding to the list of + operator overloads and overload packets passed as input. Overload + packets will include all decomposed overloads in the packet. If there is + no decomposition for a requested operator, it is silently ignored. + + This API is experimental; we are almost certainly going to give an alternate, + more recommended formulation, where a user provides the set of operators + they know how to implement, and we provide decompositions for everything + not in this set. + """ + if type not in {"post_autograd", "pre_autograd", "meta"}: + raise AssertionError( + f"type must be one of post_autograd, pre_autograd, or meta, got {type}" + ) + + registry = global_decomposition_table[type] + packets_to_overloads = defaultdict(list) + + for opo in registry: + if isinstance(opo, (OpOverload, OpOverloadPacket)): + packets_to_overloads[opo.overloadpacket].append(opo) + decompositions: dict[torch._ops.OperatorBase, Callable] = {} + for op in aten_ops: + if isinstance(op, OpOverloadPacket) and op in packets_to_overloads: + for op_overload in packets_to_overloads[op]: + decompositions[op_overload] = registry[op_overload] + elif isinstance(op, (torch._ops.OperatorBase)) and op in registry: + decompositions[op] = registry[op] + return decompositions + + +def remove_decompositions( + decompositions: dict[torch._ops.OperatorBase, Callable], + aten_ops: Sequence[OpOverload | OpOverloadPacket], +) -> None: + """ + Given a dictionary of decompositions obtained from get_decompositions(), removes + operators associated with a list of operator overloads and overload packets passed + as input. If the decomposition dictionary does not contain a decomposition that is + specified to be removed, it is silently ignored. + """ + for op in aten_ops: + if isinstance(op, OpOverloadPacket): + for opo in op.op_overloads(): + decompositions.pop(opo, None) + elif isinstance(op, OpOverload): + decompositions.pop(op, None) + + +# populate the table +import torch._decomp.decompositions +import torch._refs + + +def core_aten_decompositions() -> "CustomDecompTable": + from torch.export.exported_program import default_decompositions + + return default_decompositions() + + +# See NOTE [Core ATen Ops] +# +# list was copied from torch/_inductor/decomposition.py +# excluding decompositions that results in prim ops +# Resulting opset of decomposition is core aten ops +def _core_aten_decompositions_post_autograd() -> dict[ + torch._ops.OperatorBase, Callable +]: + aten = torch.ops.aten + return get_decompositions( + [ + aten.addcdiv, + aten.addcdiv_, + aten.addcmul, + aten.addcmul_, + aten.addr, + aten.affine_grid_generator, + aten.alias_copy, + aten.all, + aten.aminmax, + aten.arange.default, + aten.arange.start, + aten.avg_pool2d_backward, + aten.baddbmm, + aten.binary_cross_entropy, + aten.binary_cross_entropy_backward, + aten.binary_cross_entropy_with_logits, + aten.block_diag, + aten.bernoulli.p, + aten.bernoulli.default, + aten.celu, + aten.celu_, + aten.channel_shuffle, + aten.clamp_max, + aten.clamp_min, + aten.col2im, + aten.count_nonzero, + aten.linalg_cross, + aten.cudnn_batch_norm, + aten.cudnn_batch_norm_backward, + aten.miopen_batch_norm_backward, + aten.deg2rad, + aten.deg2rad_, + aten.detach, + aten.diag_embed, + aten.diagonal_backward, + aten.diagonal_copy, + aten.dot, + aten.vdot, + aten.elu_, + aten.elu_backward, + aten._embedding_bag, + aten.embedding_dense_backward, + aten.empty_like, + aten._euclidean_dist.default, + aten.expand_as, + aten.expand_copy, + aten.eye, + aten.fill, + aten.fill_, + aten.floor_divide, + aten.frac, + aten.frac_, + aten._fused_moving_avg_obs_fq_helper, + aten.gelu_, + aten.gelu_backward, + aten.glu, + aten.glu_backward, + aten.hardshrink, + aten.hardsigmoid, + aten.hardsigmoid_, + aten.hardsigmoid_backward, + aten.hardswish, + aten.hardswish_, + aten.hardswish_backward, + aten.hardtanh_, + aten.hardtanh_backward, + aten.hann_window, + aten.heaviside, + aten.heaviside_, + aten.huber_loss, + aten.huber_loss_backward, + aten.im2col, + aten.index_add.out, + aten.index_add.default, + aten.index_add_, + aten.index_copy.out, + aten.index_copy.default, + aten.index_copy_, + aten.index_fill.int_Scalar, + aten.index_fill.int_Tensor, + aten.index_fill.int_Scalar_out, + aten.index_fill.int_Tensor_out, + aten.index_fill_, + aten.isin, + aten.isneginf, + aten.isposinf, + aten.l1_loss, + aten._lazy_clone, + aten._test_parallel_materialize, + aten.leaky_relu_, + aten.leaky_relu_backward, + aten.lerp, + aten.lerp_, + aten.linalg_vector_norm, + aten.linspace, + aten.logaddexp, + aten.logaddexp2, + aten.logit, + aten.logit_, + aten.logit_backward, + aten.log_sigmoid_backward, + aten.log_sigmoid_forward, + aten._log_softmax_backward_data, + aten.logspace, + aten.logsumexp.default, + aten.masked_fill, + aten.masked_fill_, + aten.max_unpool2d, + aten.max_unpool3d, + aten.mish, + aten.mish_, + aten.mish_backward, + aten.mse_loss, + aten.mse_loss_backward, + aten.multi_margin_loss, + aten.multilabel_margin_loss_forward, + aten.mv, + aten.mvlgamma, + aten.mvlgamma_, + aten.nansum, + aten.nan_to_num, + aten.nan_to_num_, + aten.narrow, + aten.native_batch_norm_backward, + aten.native_dropout_backward, + aten.native_group_norm_backward, + aten.native_layer_norm_backward, + aten._fused_rms_norm, + aten._fused_rms_norm_backward, + aten.new_empty, + aten.new_full, + aten.new_ones, + aten.new_zeros, + aten.nll_loss2d_forward, + aten.nll_loss2d_backward, + aten.nll_loss_backward, + aten.nll_loss_forward, + aten.norm.ScalarOpt_dtype, + aten.norm.Scalar, + aten.norm.ScalarOpt_dim_dtype, + aten.norm.ScalarOpt_dim, + aten.norm.dtype_out, + aten.norm.out, + aten.norm.ScalarOpt_dtype_out, + aten.norm.Scalar_out, + aten.ones, + aten.ones_like, + aten.pixel_shuffle, + aten.pixel_unshuffle, + aten._prelu_kernel, + aten._prelu_kernel_backward, + aten._reshape_alias, + aten.rad2deg, + aten.rad2deg_, + aten.reflection_pad1d, + aten.reflection_pad1d_backward, + aten.reflection_pad2d, + aten.reflection_pad2d_backward, + aten.reflection_pad3d, + aten.reflection_pad3d_backward, + aten.replication_pad1d, + aten.replication_pad2d, + aten.replication_pad3d, + aten.renorm, + aten.renorm_, + aten.replication_pad2d, + aten.resize_as, + aten.roll, + aten.rot90, + aten.rrelu_with_noise, + aten.rrelu_with_noise_, + aten.rsub, + aten._safe_softmax, + aten._scaled_dot_product_flash_attention_for_cpu.default, + aten.select_backward, + aten.select_scatter, + aten.sgn, + aten.sgn_, + aten.sigmoid_backward, + aten.silu, + aten.silu_, + aten.silu_backward.grad_input, + aten.silu_backward, + aten.sinc, + aten.sinc_, + aten.slice_backward, + aten.smooth_l1_loss, + aten.smooth_l1_loss_backward, + aten.soft_margin_loss, + aten.soft_margin_loss_backward, + aten._softmax_backward_data, + aten.softplus, + aten.softplus_backward, + aten.softshrink, + aten.special_entr, + aten.special_log_ndtr, + aten.special_xlog1py, + aten.split.Tensor, + aten.split_with_sizes_copy, + aten.squeeze_copy, + aten.squeeze.default, + aten.squeeze.dim, + aten.std.correction, + aten.std.out, + aten.std.correction_out, + aten.std_mean.correction, + aten.std_mean.correction_out, + aten.stack, + aten.sum.default, + aten.sum.out, + aten.t, + aten.t_copy, + aten.take, + aten.tanh_backward, + aten.threshold, + aten.threshold_, + aten.threshold_backward, + aten.trace, + aten.transpose.int, + aten.transpose_copy, + aten.tril, + aten.tril_, + aten.triu, + aten.triu_, + aten.unbind, + aten.unfold_backward, + aten.unfold_copy, + aten._unsafe_index, + aten._unsafe_index_put, + aten._unsafe_masked_index, + aten._unsafe_masked_index_put_accumulate, + aten.unsafe_split.Tensor, + aten.unsafe_split_with_sizes, + aten.unsqueeze_copy, + aten._unsafe_view, + aten.upsample_linear1d, + aten.upsample_bilinear2d.out, + aten.upsample_trilinear3d.out, + aten.upsample_nearest2d_backward, + aten.view_as_complex, + aten.xlogy, + aten.xlogy_, + aten.zero, + aten.zero_, + aten.zeros, + aten.zeros_like, + aten._chunk_cat, + aten._weight_norm_interface, + ] + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3042b6dbc42e2fc0b5ada783622ff14a6be133a0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1038608847176f5fd13b67e2a99e21d8bdf1428 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1727002c793d917760fda14fe2ef9ae3f2c26f9ea597a55fdddec5ac57540701 +size 282721 diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_jvp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_jvp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da2b6030104fa12b9f4168491eb14d470a59b4f4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_jvp.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_rng.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_rng.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..249879b77f73818d363843bf955dcfe395ce8749 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_rng.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions.py b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions.py new file mode 100644 index 0000000000000000000000000000000000000000..63be1dabca1dd2a0591511f673dd25f5d130d313 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions.py @@ -0,0 +1,6305 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import functools +import itertools +import numbers +import operator +import sys +from collections.abc import Callable, Iterable +from contextlib import nullcontext +from enum import Enum +from functools import partial, reduce +from itertools import chain, product +from typing import Any, cast + +import torch +import torch._meta_registrations +import torch._prims as prims +import torch._prims_common as utils +import torch.nn.functional as F +from torch import sym_float, sym_int, Tensor +from torch._decomp import register_decomposition +from torch._higher_order_ops.out_dtype import out_dtype +from torch._prims_common import ( + IntLike, + NumberType, + suggest_memory_format, + TensorLike, + TensorSequenceType, +) +from torch._prims_common.wrappers import ( + _maybe_convert_to_dtype, + _maybe_resize_out, + _safe_copy_out, + out_wrapper, +) +from torch.utils import _pytree as pytree +from torch.utils._pytree import tree_map + + +DispatchKey = torch._C.DispatchKey # type: ignore[attr-defined] + +# None of these functions are publicly accessible; get at them +# from torch._decomps +__all__: list[str] = [] + +aten = torch._ops.ops.aten + + +class Reduction(Enum): + NONE = 0 + MEAN = 1 + SUM = 2 + + +# This wraps a decomposition and performs various type promotion logic within it, depending on the strategy provided +# We're currently reusing ELEMENTWISE_TYPE_PROMOTION_KIND, although some of the usages are on non-elementwise ops +# Will need to validate the non-elementwise uses +def type_casts( + f: Callable, + type_promotion: utils.ELEMENTWISE_TYPE_PROMOTION_KIND, + compute_dtype_only: bool = False, + include_non_tensor_args: bool = False, +): + @functools.wraps(f) + def inner(*args, **kwargs): + allowed_types = ( + (Tensor, torch.types._Number) if include_non_tensor_args else (Tensor,) + ) # type: ignore[arg-type] + flat_args = [ + x + for x in pytree.arg_tree_leaves(*args, **kwargs) + if isinstance(x, allowed_types) + ] + computation_dtype, result_dtype = utils.elementwise_dtypes( + *flat_args, type_promotion_kind=type_promotion + ) + + # TODO: pretty sure this is not quite right + def increase_prec(x): + if isinstance(x, Tensor): + return x.to(computation_dtype) + else: + return x + + def decrease_prec(x): + if isinstance(x, Tensor): + return x.to(result_dtype) + else: + return x + + r = f(*tree_map(increase_prec, args), **tree_map(increase_prec, kwargs)) + if compute_dtype_only: + return r + else: + return tree_map(decrease_prec, r) + + return inner + + +compute_only_pw_cast_for_opmath = partial( + type_casts, + type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + compute_dtype_only=True, +) +pw_cast_for_opmath = partial( + type_casts, type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT +) +pw_cast_for_opmath_non_tensor_args = partial( + type_casts, + type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + include_non_tensor_args=True, +) +pw_cast_for_int_to_real = partial( + type_casts, type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT +) + + +# This expands x until x.dim() == dim. Might be useful as an operator +def _unsqueeze_to_dim(x: Tensor, dim: int) -> Tensor: + for _ in range(dim - x.dim()): + x = x.unsqueeze(-1) + return x + + +@register_decomposition(aten.tanh_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def tanh_backward(out_grad: Tensor, y: Tensor): + return out_grad * (1 - y * y).conj_physical() + + +@register_decomposition(aten.sigmoid_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def sigmoid_backward(out_grad: Tensor, y: Tensor): + return out_grad * (y * (1 - y)).conj_physical() + + +@register_decomposition(aten.softplus_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def softplus_backward(out_grad: Tensor, x: Tensor, beta: float, threshold: float): + z = (x * beta).exp() + return torch.where((x * beta) > threshold, out_grad, out_grad * z / (z + 1.0)) + + +@register_decomposition(aten.elu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def elu_backward( + grad_output: Tensor, + alpha: float, + scale: float, + input_scale: float, + is_result: bool, + self_or_result: Tensor, +): + negcoef = alpha * scale + poscoef = scale + negiptcoef = input_scale + if is_result: + return torch.where( + self_or_result <= 0, + grad_output * negiptcoef * (self_or_result + negcoef), + grad_output * poscoef, + ) + else: + return torch.where( + self_or_result <= 0, + grad_output * negiptcoef * negcoef * torch.exp(self_or_result * negiptcoef), + grad_output * poscoef, + ) + + +@register_decomposition([aten.fill.Scalar]) +def fill_scalar(self, value): + return torch.full_like(self, value) + + +@register_decomposition([aten.fill.Tensor]) +def fill_tensor(self, value: Tensor): + torch._check( + value.dim() == 0, + lambda: f"fill only supports 0-dimension value tensor but got tensor with {value.dim()} dimensions", + ) + return aten.copy(self, value) + + +@register_decomposition(aten.hardsigmoid) +@out_wrapper() +@pw_cast_for_opmath +def hardsigmoid(self: Tensor) -> Tensor: + return torch.clamp(torch.clamp(self + 3, min=0), max=6) / 6 + + +@register_decomposition(aten.hardsigmoid_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def hardsigmoid_backward(grad_output: Tensor, self: Tensor): + return torch.where( + (self > -3.0) & (self < 3.0), + grad_output * (1.0 / 6.0), + 0.0, + ) + + +@register_decomposition(aten.hardtanh_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def hardtanh_backward( + grad_output: Tensor, self: Tensor, min_val: float, max_val: float +): + # Compare in opmath (compute) dtype to match the eager kernel, which casts + # self to opmath_t before comparing against the float bounds. Comparing in + # the low-precision input dtype would round the bound and misclassify + # boundary values (e.g. bf16(0.7) == 0.69921875 vs max_val=0.7). + return torch.where((self <= min_val) | (self >= max_val), 0.0, grad_output) + + +@register_decomposition(aten.hardswish) +@out_wrapper() +@pw_cast_for_opmath +def hardswish(self: Tensor) -> Tensor: + return self * torch.clamp(torch.clamp(self + 3, min=0), max=6) / 6 + + +@register_decomposition(aten.hardswish_backward) +@out_wrapper() +@pw_cast_for_opmath +def hardswish_backward(grad_output: Tensor, self: Tensor) -> Tensor: + return torch.where( + self <= -3, + 0.0, + torch.where(self < 3, grad_output * ((self / 3) + 0.5), grad_output), + ) + + +@register_decomposition(aten.threshold_backward) +@out_wrapper("grad_input") +def threshold_backward(grad_output: Tensor, self: Tensor, threshold: float): + return torch.where(self <= threshold, 0, grad_output) + + +@register_decomposition(aten.leaky_relu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def leaky_relu_backward( + grad_output: Tensor, self: Tensor, negative_slope: float, self_is_result: bool +): + return torch.where(self > 0, grad_output, grad_output * negative_slope) + + +@register_decomposition(aten.gelu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def gelu_backward(grad: Tensor, self: Tensor, approximate: str = "none"): + M_SQRT2 = 1.41421356237309504880 + M_SQRT1_2 = 0.70710678118654752440 + M_2_SQRTPI = 1.12837916709551257390 + if approximate == "tanh": + kBeta = M_SQRT2 * M_2_SQRTPI * 0.5 + kKappa = 0.044715 + x_sq = self * self + x_cube = x_sq * self + inner = kBeta * (self + kKappa * x_cube) + tanh_inner = torch.tanh(inner) + + left = 0.5 * self + right = 1 + tanh_inner + + left_derivative = 0.5 * right + + tanh_derivative = 1 - tanh_inner * tanh_inner + inner_derivative = kBeta * (1 + 3 * kKappa * x_sq) + right_derivative = left * tanh_derivative * inner_derivative + + return grad * (left_derivative + right_derivative) + else: + kAlpha = M_SQRT1_2 + kBeta = M_2_SQRTPI * M_SQRT1_2 * 0.5 + cdf = 0.5 * (1 + torch.erf(self * kAlpha)) + pdf = kBeta * torch.exp(self * self * -0.5) + return grad * (cdf + self * pdf) + + +@register_decomposition(aten.mish_backward) +@pw_cast_for_opmath +def mish_backward(grad_output: Tensor, input: Tensor): + input_tanh_softplus = torch.tanh(F.softplus(input)) + input_sigmoid = torch.sigmoid(input) + out = input * input_sigmoid * (1 - input_tanh_softplus * input_tanh_softplus) + return grad_output * (input_tanh_softplus + out) + + +@register_decomposition(aten.silu) +@out_wrapper() +@pw_cast_for_opmath +def silu(self: Tensor) -> Tensor: + return self * torch.sigmoid(self) + + +@register_decomposition(aten.silu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def silu_backward(grad_output: Tensor, self: Tensor) -> Tensor: + sigmoid = torch.sigmoid(self) + return grad_output * sigmoid * (1 + self * (1 - sigmoid)) + + +@register_decomposition(aten._prelu_kernel) +def _prelu_kernel(self: Tensor, weight: Tensor) -> Tensor: + return torch.where(self > 0, self, weight * self) + + +@register_decomposition(aten._prelu_kernel_backward) +def _prelu_kernel_backward( + grad_output: Tensor, + self: Tensor, + weight: Tensor, +) -> tuple[Tensor, Tensor]: + input_grad = torch.where(self > 0, grad_output, weight * grad_output) + weight_grad = torch.where(self > 0, 0.0, self * grad_output) + return (input_grad, weight_grad) + + +@register_decomposition(aten.rrelu_with_noise_backward) +@out_wrapper() +@pw_cast_for_opmath +def rrelu_with_noise_backward( + grad_output: Tensor, + self: Tensor, + noise: Tensor, + lower: float, + upper: float, + training: bool, + self_is_result: bool, +) -> Tensor: + if training: + return grad_output.mul(noise) + else: + negative_slope = (lower + upper) / 2 + return aten.leaky_relu_backward( + grad_output, self, negative_slope, self_is_result + ) + + +@register_decomposition(aten.log_sigmoid_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def log_sigmoid_backward(grad_output: Tensor, self: Tensor, buffer: Tensor) -> Tensor: + in_negative = self < 0 + max_deriv = torch.where(in_negative, 1, 0) + sign = torch.where(in_negative, 1, -1) + # On CPU, forward saves buffer = exp(-|x|); reuse it to match the native kernel. + # On CUDA/XPU, buffer is empty so we recompute. + z = buffer if buffer.numel() > 0 else torch.exp(-torch.abs(self)) + return grad_output * (max_deriv - sign * (z / (1 + z))) + + +@register_decomposition(aten.ldexp) +@out_wrapper() +def ldexp(self: Tensor, other: Tensor) -> Tensor: + two_dtype = ( + torch.float32 + if utils.is_integer_dtype(self.dtype) or utils.is_boolean_dtype(self.dtype) + else self.dtype + ) + two_tensor = self.new_full((), 2.0, dtype=two_dtype) + return self * torch.pow(two_tensor, other) + + +def apply_loss_reduction(loss: Tensor, reduction: int): + if reduction == Reduction.MEAN.value: + return torch.mean(loss) + elif reduction == Reduction.SUM.value: + return torch.sum(loss) + else: + return loss + + +def to_real_dtype(dtype: torch.dtype): + if dtype == torch.complex32: + return torch.float16 + elif dtype == torch.complex64: + return torch.float32 + elif dtype == torch.complex128: + return torch.float64 + + +# TODO: None of these loss castings are quite correct, see +# https://github.com/pytorch/pytorch/issues/76870. Also, the ATen kernels +# perform the pointwise portion in opmath, but don't maintain it between the +# pointwise portion and the reduction + + +@register_decomposition(aten.mse_loss) +@out_wrapper() +@pw_cast_for_opmath +def mse_loss( + self: Tensor, target: Tensor, reduction: int = Reduction.MEAN.value +) -> Tensor: + loss = (self - target) ** 2 + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.mse_loss_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def mse_loss_backward( + grad_output: Tensor, input: Tensor, target: Tensor, reduction: int +): + norm = 2.0 / input.numel() if reduction == Reduction.MEAN.value else 2.0 + return norm * (input - target) * grad_output + + +@register_decomposition(aten._safe_softmax) +def safe_softmax(self, dim, dtype=None): + out = torch.softmax(self, dim=dim, dtype=dtype) + masked = self.eq(float("-inf")) + masked_rows = torch.all(masked, dim=dim, keepdim=True) + zeros = torch.zeros_like(out) + return torch.where(masked_rows, zeros, out) + + +@register_decomposition(aten.smooth_l1_loss) +@out_wrapper() +@pw_cast_for_opmath +def smooth_l1_loss( + self: Tensor, + target: Tensor, + reduction: int = Reduction.MEAN.value, + beta: float = 1.0, +): + loss = (self - target).abs() + + loss = torch.where(loss < beta, 0.5 * loss**2 / beta, loss - 0.5 * beta) + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.smooth_l1_loss_backward.default) +@pw_cast_for_opmath +def smooth_l1_loss_backward( + grad_output: Tensor, self: Tensor, target: Tensor, reduction: int, beta: float +): + norm = 1.0 / self.numel() if reduction == Reduction.MEAN.value else 1.0 + x = self - target + abs_x = torch.abs(x) + norm_grad = norm * grad_output + return torch.where( + abs_x < beta, + norm_grad * x / beta, + norm_grad * torch.sign(x), + ) + + +@register_decomposition(aten.smooth_l1_loss_backward.grad_input) +@pw_cast_for_opmath +def smooth_l1_loss_backward_out( + grad_output: Tensor, + self: Tensor, + target: Tensor, + reduction: int, + beta: float, + grad_input: Tensor, +): + result = smooth_l1_loss_backward(grad_output, self, target, reduction, beta) + _maybe_resize_out(grad_input, result.shape) + return _safe_copy_out(copy_from=result, copy_to=grad_input, exact_dtype=True) + + +@register_decomposition(aten.huber_loss_backward.default) +@pw_cast_for_opmath +def huber_loss_backward( + grad_output: Tensor, self: Tensor, target: Tensor, reduction: int, delta: float +): + norm = 1.0 / self.numel() if reduction == Reduction.MEAN.value else 1.0 + x = self - target + return torch.where( + x < -delta, + -norm * grad_output * delta, + torch.where(x > delta, norm * grad_output * delta, norm * x * grad_output), + ) + + +# We cannot use @out_wrapper() here, because the output tensor is not named 'out', it's 'grad_input' +@register_decomposition(aten.huber_loss_backward.out) +@pw_cast_for_opmath +def huber_loss_backward_out( + grad_output: Tensor, + self: Tensor, + target: Tensor, + reduction: int, + delta: float, + grad_input: Tensor, +): + result = huber_loss_backward(grad_output, self, target, reduction, delta) + _maybe_resize_out(grad_input, result.shape) + return _safe_copy_out(copy_from=result, copy_to=grad_input, exact_dtype=True) + + +def _nll_loss_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, + total_weight: Tensor, +) -> Tensor: + channel_dim = 0 if self.dim() < 2 else 1 + if reduction == Reduction.MEAN.value: + grad_output = grad_output / total_weight + + # When self is 1D (no batch dim), the C++ kernel only uses target[0]. + # Reduce target to a scalar so the subsequent unsqueeze produces a 1D + # tensor matching self's dimensionality. + if self.dim() == 1 and target.dim() > 0: + target = target[0] + + target = target.unsqueeze(channel_dim) + safe_target = torch.where(target != ignore_index, target, 0) + grad_input = torch.zeros_like(self) + grad_input = torch.scatter(grad_input, channel_dim, safe_target, -1.0) + + if grad_input.dim() > grad_output.dim() > 0: + grad_output = grad_output.unsqueeze(channel_dim) + + if weight is not None: + new_shape = [1 for _ in range(self.dim())] + new_shape[channel_dim] = weight.shape[0] + weight = weight.reshape(new_shape) + grad_output = grad_output * weight + + grad_output = torch.where(target != ignore_index, grad_output, 0) + + return grad_input * grad_output + + +@register_decomposition(aten.glu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def glu_backward(grad_output: Tensor, self: Tensor, dim: int) -> Tensor: + if self.dim() <= 0: + raise AssertionError("glu does not support 0-dimensional tensors") + wrap_dim = utils.canonicalize_dim(self.dim(), dim) + nIn = self.size(wrap_dim) + if nIn % 2 != 0: + raise AssertionError( + f"Halving dimension must be even, but dimension {wrap_dim} is size {nIn}" + ) + inputSize = nIn // 2 + firstHalf = self.narrow(wrap_dim, 0, inputSize) + secondHalf = self.narrow(wrap_dim, inputSize, inputSize) + gradInputFirstHalf = torch.sigmoid(secondHalf) + gradInputSecondHalf = ( + (1.0 - gradInputFirstHalf) * gradInputFirstHalf * firstHalf * grad_output + ) + gradInputFirstHalf = gradInputFirstHalf * grad_output + return torch.cat([gradInputFirstHalf, gradInputSecondHalf], dim=wrap_dim) + + +@register_decomposition(aten.nll_loss_backward) +@out_wrapper("grad_input") +def nll_loss_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, + total_weight: Tensor, +) -> Tensor: + if not (0 <= self.dim() <= 2): + raise AssertionError(f"input tensor should be 1D or 2D, got {self.dim()}D") + if target.dim() > 1: + raise AssertionError( + f"0D or 1D target tensor expected, multi-target not supported, got {target.dim()}D" + ) + + no_batch_dim = self.dim() == 1 and target.dim() == 0 + if not (no_batch_dim or (self.shape[0] == target.shape[0])): + raise AssertionError( + f"size mismatch (got input: {self.shape}, target: {target.shape})" + ) + if total_weight.numel() != 1: + raise AssertionError( + f"expected total_weight to be a single element tensor, got: " + f"{total_weight.shape} ({total_weight.numel()} elements)" + ) + + if weight is not None and weight.numel() != self.shape[-1]: + raise AssertionError( + "weight tensor should be defined either for all or no classes" + ) + + if reduction == Reduction.NONE.value and self.dim() == 2: + if not (grad_output.dim() == 1 and grad_output.shape[0] == self.shape[0]): + raise AssertionError( + f"Expected a tensor of dimension 1 and tensor.size[0] == {self.shape[0]} but " + f"got: dimension {grad_output.dim()} and tensor.size[0] == {grad_output.shape[0]}" + ) + else: + if not (grad_output.dim() <= 1 and grad_output.numel() == 1): + raise AssertionError( + f"Expected a single element grad_output tensor, but got: {grad_output.shape}" + ) + + return _nll_loss_backward( + grad_output, self, target, weight, reduction, ignore_index, total_weight + ) + + +@register_decomposition(aten.nll_loss2d_backward) +@out_wrapper("grad_input") +def nll_loss2d_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, + total_weight: Tensor, +) -> Tensor: + if self.dim() != 4: + raise AssertionError( + f"only batches of spatial inputs supported (4D tensors), but got input of dimension: {self.dim()}" + ) + + if target.dim() != 3: + raise AssertionError( + f"only batches of spatial targets supported (3D tensors) but got targets of dimension: {target.dim()}" + ) + + if not ( + self.shape[0] == target.shape[0] + and self.shape[2] == target.shape[1] + and self.shape[3] == target.shape[2] + ): + raise AssertionError( + f"size mismatch (got input: {self.shape}, target: {target.shape}" + ) + + if total_weight.numel() != 1: + raise AssertionError( + f"expected total_weight to be a single element tensor, " + f"got: {total_weight.shape} ( {total_weight.numel()}, elements)" + ) + + return _nll_loss_backward( + grad_output, self, target, weight, reduction, ignore_index, total_weight + ) + + +@register_decomposition(aten.binary_cross_entropy) +@out_wrapper() +@pw_cast_for_opmath +def binary_cross_entropy( + self: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + # We cannot currently model this without introducing data-dependent control flow + # TORCH_CHECK( + # (input_val >= 0) && (input_val <= 1), + # "all elements of input should be between 0 and 1" + # ) + loss = (target - 1) * torch.maximum( + torch.log1p(-self), self.new_full((), -100) + ) - target * torch.maximum(torch.log(self), self.new_full((), -100)) + if weight is not None: + loss = loss * weight + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.binary_cross_entropy_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def binary_cross_entropy_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + EPSILON = 1e-12 + result = grad_output * (self - target) / torch.clamp(self * (1 - self), min=EPSILON) + if weight is not None: + result = result * weight + if reduction == Reduction.MEAN.value: + result = result / self.numel() + return result + + +@register_decomposition(aten.soft_margin_loss) +@out_wrapper() +@pw_cast_for_opmath +def soft_margin_loss( + input: Tensor, + target: Tensor, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + loss = torch.log1p(torch.exp(-input * target)) + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.soft_margin_loss_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def soft_margin_loss_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + grad_input = target * grad_output * (torch.sigmoid(target * self) - 1) + if reduction == Reduction.MEAN.value: + grad_input = grad_input / self.numel() + return grad_input + + +@register_decomposition(aten.dist) +@out_wrapper() +def dist(input: Tensor, other: Tensor, p: float = 2): + return aten.norm(input - other, p=p) + + +@register_decomposition(aten._euclidean_dist) +@out_wrapper() +def _euclidean_dist(x1: Tensor, x2: Tensor) -> Tensor: + x1_norm = x1.pow(2).sum(-1, True) + x1_pad = torch.ones_like(x1_norm, memory_format=torch.contiguous_format) + x2_norm = x2.pow(2).sum(-1, True) + x2_pad = torch.ones_like(x2_norm, memory_format=torch.contiguous_format) + x1_ = torch.cat([x1.mul(-2), x1_norm, x1_pad], -1) + x2_ = torch.cat([x2, x2_pad, x2_norm], -1) + result = x1_.matmul(x2_.mT) + return result.clamp_min(0).sqrt() + + +@register_decomposition(aten.slice_backward) +@out_wrapper() +def slice_backward( + grad_output: Tensor, + input_sizes: list[int], + dim: int, + start: int, + end: int, + step: int, +): + grad_input = grad_output.new_zeros(input_sizes) + return torch.slice_scatter(grad_input, grad_output, dim, start, end, step) + + +@register_decomposition(aten.slice.Tensor) +def slice_forward( + # Tensor(a) self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1 + self: Tensor, + dim: int = 0, + start: int | None = None, + end: int | None = None, + step: int = 1, +): + from torch.fx.experimental.symbolic_shapes import statically_known_true + + ndim = self.dim() + if ndim == 0: + raise RuntimeError("slice() cannot be applied to a 0-dim tensor.") + dim = utils.canonicalize_dim(self.dim(), dim) + sizes = list(self.size()) + strides = list(self.stride()) + + if step <= 0: + raise RuntimeError("slice step must be positive") + + start_val = start if start is not None else 0 + end_val = end if end is not None else sys.maxsize # 2^63 - 1 + + if start_val < 0: + start_val += sizes[dim] + + if end_val < 0: + end_val += sizes[dim] + + if start_val < 0: + start_val = 0 + elif start_val > sizes[dim]: + start_val = sizes[dim] + + if statically_known_true(end_val == sys.maxsize): + end_val = sizes[dim] + elif end_val < start_val: + end_val = start_val + elif end_val > sizes[dim]: + end_val = sizes[dim] + + storage_offset = self.storage_offset() + start_val * strides[dim] + len = end_val - start_val + sizes[dim] = (len + step - 1) // step + strides[dim] *= step + + if self.is_quantized: + raise NotImplementedError( + "Slice decomposition for quantized tensors aren't implemented" + ) + else: + return self.as_strided(sizes, strides, storage_offset) + + +def _normalize_start_end( + x: Tensor, dim: int, start: int | None, end: int | None +) -> tuple[int, int]: + """ + Normalize start and end such that both are in the range + [0, x.get_size()[dim]] and start <= end. + """ + dim_size = x.shape[dim] + + def clamp_wrap(val, lower, upper, default) -> int: + if val is None: + return default + if val < 0: + val = val + dim_size + return min(max(val, lower), upper) + + start = clamp_wrap(start, 0, dim_size, 0) + end = clamp_wrap(end, start, dim_size, dim_size) + return start, end + + +# This is not in torch._refs because aten.index used by +# aten._unsafe_masked_index does not have a decomposition. +@register_decomposition(aten.slice_scatter) +@out_wrapper() +def slice_scatter( + input: Tensor, + src: Tensor, + dim: int = 0, + start: int | None = None, + end: int | None = None, + step: int = 1, +): + dim = utils.canonicalize_dim(input.ndim, dim) + dim_size = input.shape[dim] + start, end = _normalize_start_end(input, dim, start, end) + + src_size = list(input.shape) + src_size[dim] = (end - start + (step - 1)) // step + src = src.expand(src_size) + + if start == 0 and end == dim_size and step == 1: + return src.clone() + + indices: list[Tensor | None] = [None] * input.dim() + idx = torch.arange(dim_size, device=input.device) + indices[dim] = (idx - start) // step + + mask = torch.ones(dim_size, device=input.device, dtype=torch.bool) + if start != 0: + mask = torch.logical_and(mask, idx >= start) + + if end != dim_size: + mask = torch.logical_and(mask, idx < end) + + if step != 1: + mask = torch.logical_and(mask, (idx - start) % step == 0) + + mask_shape = [1] * input.dim() + mask_shape[dim] = -1 + mask = mask.view(mask_shape) + return aten.where(mask, aten._unsafe_masked_index(src, mask, indices, 0), input) + + +@register_decomposition(aten.select_backward) +@out_wrapper() +def select_backward(grad_output: Tensor, input_sizes: list[int], dim: int, index: int): + grad_input = grad_output.new_zeros(input_sizes) + return torch.select_scatter(grad_input, grad_output, dim, index) + + +@register_decomposition(aten.diagonal_backward) +@out_wrapper() +def diagonal_backward( + grad_output: Tensor, input_sizes: list[int], offset: int, dim1: int, dim2: int +): + grad_input = grad_output.new_zeros(input_sizes) + return torch.diagonal_scatter(grad_input, grad_output, offset, dim1, dim2) + + +def _cast_grad_to_input_dtype( + grad_output: Tensor, grad_input: Tensor, input_dtype: torch.dtype +): + if grad_output.dtype != input_dtype: + grad_input = grad_input.to(input_dtype) + return grad_input + + +@register_decomposition(aten._softmax_backward_data) +@out_wrapper("grad_input") +@compute_only_pw_cast_for_opmath +def _softmax_backward_data( + grad_output: Tensor, output: Tensor, dim: int, input_dtype: torch.dtype +): + new_grad_output = grad_output * output + grad_input = new_grad_output - output * torch.sum( + new_grad_output, dim=dim, keepdim=True + ) + + # CPU kernel doesn't respect input_dtype, but following check doesn't work for meta tensor + # if grad_output.device == torch.device("cpu"): + # return grad_input.contiguous() + + return _cast_grad_to_input_dtype(grad_output, grad_input, input_dtype).contiguous() + + +@register_decomposition(aten._log_softmax_backward_data) +@out_wrapper() +@compute_only_pw_cast_for_opmath +def _log_softmax_backward_data( + grad_output: Tensor, output: Tensor, dim: int, input_dtype: torch.dtype +): + grad_input = grad_output - torch.exp(output) * torch.sum( + grad_output, dim=dim, keepdim=True + ) + return _cast_grad_to_input_dtype(grad_output, grad_input, input_dtype) + + +def _im2col_col2im_indices_along_dim( + input_d, kernel_d, dilation_d, padding_d, stride_d, device +): + """Utility function to implement im2col and col2im""" + blocks_d = input_d + padding_d * 2 - dilation_d * (kernel_d - 1) + + arange_kw = partial(torch.arange, dtype=torch.int64, device=device) + + # Stride kernel over input and find starting indices along dim d + blocks_d_indices = arange_kw(0, blocks_d, stride_d).unsqueeze(0) + + # Apply dilation on kernel and find its indices along dim d + kernel_grid = arange_kw(0, kernel_d * dilation_d, dilation_d).unsqueeze(-1) + + # Broadcast and add kernel starting positions (indices) with + # kernel_grid along dim d, to get block indices along dim d + return blocks_d_indices + kernel_grid + + +@register_decomposition(aten.im2col) +@out_wrapper() +def im2col( + input: Tensor, + kernel_size: list[int], + dilation: list[int], + padding: list[int], + stride: list[int], +) -> Tensor: + torch._check(len(kernel_size) == 2, lambda: "im2col(): only 2D kernel supported") + torch._check(len(dilation) == 2, lambda: "im2col(): only 2D dilation supported") + torch._check(len(padding) == 2, lambda: "im2col(): only 2D padding supported") + torch._check(len(stride) == 2, lambda: "im2col(): only 2D stride supported") + + def check_positive(param, param_name, strict=True): + cond = all(p > 0 for p in param) if strict else all(p >= 0 for p in param) + torch._check( + cond, lambda: f"{param_name} should be greater than zero, but got {param}" + ) + + check_positive(kernel_size, "kernel_size") + check_positive(dilation, "dilation") + check_positive(dilation, "padding", strict=False) + check_positive(stride, "stride") + + shape = input.shape + ndim = len(shape) + torch._check( + ndim in (3, 4) and all(d != 0 for d in shape[-3:]), + lambda: "Expected 3D or 4D (batch mode) tensor for input with possible 0 batch size " + f"and non-zero dimensions, but got: {tuple(shape)}", + ) + output_size = tuple( + 1 + (out + 2 * pad - dil * (ker - 1) - 1) // st + for out, pad, dil, ker, st in zip( + shape[-2:], padding, dilation, kernel_size, stride + ) + ) + torch._check( + all(c > 0 for c in output_size), + lambda: f"Given an input with spatial size {tuple(shape[-2:])}, " + f"kernel_size={kernel_size}, dilation={dilation}, " + f"padding={padding}, stride={stride}, " + "the calculated shape of the array of sliding blocks " + f"is {output_size}, but its components must be at least one.", + ) + batched_input = ndim == 4 + if not batched_input: + input = input.unsqueeze(0) + + batch_dim, channel_dim, input_h, input_w = input.shape + + stride_h, stride_w = stride + padding_h, padding_w = padding + dilation_h, dilation_w = dilation + kernel_h, kernel_w = kernel_size + + blocks_row_indices = _im2col_col2im_indices_along_dim( + input_h, kernel_h, dilation_h, padding_h, stride_h, input.device + ) + blocks_col_indices = _im2col_col2im_indices_along_dim( + input_w, kernel_w, dilation_w, padding_w, stride_w, input.device + ) + + # Note that F.pad takes (padding_left, padding_right, padding_top, padding_bottom) + # ugh + padded_input = F.pad(input, (padding_w, padding_w, padding_h, padding_h)) + + blocks_row_indices = blocks_row_indices.unsqueeze(-1).unsqueeze(-1) + output = padded_input[:, :, blocks_row_indices, blocks_col_indices] + output = output.permute(0, 1, 2, 4, 3, 5) + num_blocks_row = blocks_row_indices.size(1) + num_blocks_col = blocks_col_indices.size(1) + output = output.reshape( + batch_dim, channel_dim * kernel_h * kernel_w, num_blocks_row * num_blocks_col + ) + + if not batched_input: + output = output.squeeze(0) + return output + + +@register_decomposition(aten.col2im) +@out_wrapper() +@pw_cast_for_opmath +def col2im( + input: Tensor, + output_size: list[int], + kernel_size: list[int], + dilation: list[int], + padding: list[int], + stride: list[int], +) -> Tensor: + torch._check(len(output_size) == 2, lambda: "only 2D output_size supported") + torch._check(len(kernel_size) == 2, lambda: "only 2D kernel supported") + torch._check(len(dilation) == 2, lambda: "only 2D dilation supported") + torch._check(len(padding) == 2, lambda: "only 2D padding supported") + torch._check(len(stride) == 2, lambda: "only 2D stride supported") + + def check_positive(param, param_name, strict=True): + cond = all(p > 0 for p in param) if strict else all(p >= 0 for p in param) + torch._check( + cond, lambda: f"{param_name} should be greater than zero, but got {param}" + ) + + check_positive(kernel_size, "kernel_size") + check_positive(dilation, "dilation") + check_positive(padding, "padding", strict=False) + check_positive(stride, "stride") + check_positive(output_size, "output_size") + + shape = input.shape + ndim = len(shape) + torch._check( + ndim in (2, 3) and all(d != 0 for d in shape[-2:]), + lambda: "Expected 2D or 3D (batch mode) tensor for input with possible 0 batch size " + f"and non-zero dimensions, but got: {tuple(shape)}", + ) + prod_kernel_size = kernel_size[0] * kernel_size[1] + torch._check( + shape[-2] % prod_kernel_size == 0, + lambda: "Expected size of input's first non-batch dimension to be divisible by the " + f"product of kernel_size, but got input.shape[-2] = {shape[-2]} and " + f"kernel_size={kernel_size}", + ) + col = [ + 1 + (out + 2 * pad - dil * (ker - 1) - 1) // st + for out, pad, dil, ker, st in zip( + output_size, padding, dilation, kernel_size, stride + ) + ] + L = col[0] * col[1] + torch._check( + shape[-1] == L, + lambda: f"Given output_size={output_size}, kernel_size={kernel_size}, " + f"dilation={dilation}, padding={padding}, stride={stride}, " + f"expected input.size(-1) to be {L} but got {shape[-1]}.", + ) + torch._check( + L > 0, + lambda: f"Given output_size={output_size}, kernel_size={kernel_size}, " + f"dilation={dilation}, padding={padding}, stride={stride}, " + f"expected input.size(-1) to be {L} but got {shape[-1]}.", + ) + batched_input = ndim == 3 + if not batched_input: + input = input.unsqueeze(0) + + shape = input.shape + + out_h, out_w = output_size + stride_h, stride_w = stride + padding_h, padding_w = padding + dilation_h, dilation_w = dilation + kernel_h, kernel_w = kernel_size + + # col2im is defined as the backwards of im2col, so we differentiate its decomposition by hand + input = input.reshape([shape[0], shape[1] // prod_kernel_size] + kernel_size + col) + input = input.permute(0, 1, 2, 4, 3, 5) + + indices_row = _im2col_col2im_indices_along_dim( + out_h, kernel_h, dilation_h, padding_h, stride_h, input.device + ) + indices_row = _unsqueeze_to_dim(indices_row, 4) + indices_col = _im2col_col2im_indices_along_dim( + out_w, kernel_w, dilation_w, padding_w, stride_w, input.device + ) + + output_padded_size = [o + 2 * p for o, p in zip(output_size, padding)] + output = input.new_zeros( + [shape[0], shape[1] // prod(kernel_size)] + output_padded_size + ) + idx = (None, None, indices_row, indices_col) + output = aten._unsafe_index_put(output, idx, input, accumulate=True) + output = F.pad(output, (-padding_w, -padding_w, -padding_h, -padding_h)) + + if not batched_input: + output = output.squeeze(0) + return output + + +@register_decomposition(aten.native_dropout_backward) +@out_wrapper() +def native_dropout_backward(grad_output: Tensor, mask: Tensor, scale: float): + # According to the CUDA kernel implementation we should have this test; + # but it seems to fail tests! + # torch._check(mask.dtype == torch.bool, lambda: f"Mask should be Bool Scalar Type {mask.dtype}") + + # Mimicking CUDA kernel's behavior for output stride: output follow input's memory format + # This different from TensorIterator's behavior + r = (grad_output * (mask.type_as(grad_output) * scale)).clone( + memory_format=utils.suggest_memory_format(grad_output) + ) + return r + + +@register_decomposition(aten.unfold_backward) +@out_wrapper() +def unfold_backward( + grad: Tensor, input_size: list[int], dimension: int, size: int, step: int +) -> Tensor: + torch._check_value(step > 0, lambda: f"step is {step} but must be > 0") + if len(input_size) == 0: + return torch.squeeze_copy(grad, 0) + dim = utils.canonicalize_dim(len(input_size), dimension) + grad_input = grad.new_zeros(input_size) + + def _vectorized_index_put() -> Tensor: + idx = torch.arange(input_size[dim], device=grad.device, dtype=torch.int32) + idx = idx.unfold(0, size, step).flatten() + source = grad.movedim(-1, dim + 1).flatten(dim, dim + 1) + index = (None,) * dim + (idx,) + return aten._unsafe_index_put( + grad_input, index, source, accumulate=True + ).contiguous() + + if step >= size: + return _vectorized_index_put() + + from torch.fx.experimental.symbolic_shapes import statically_known_true + + def _is_canonical_grad_shape() -> bool: + if grad.dim() != len(input_size) + 1: + return False + if not statically_known_true(grad.size(-1) == size): + return False + + n_folds = (input_size[dim] - size) // step + 1 + if not statically_known_true(grad.size(dim) == n_folds): + return False + + return all( + source_dim == dim + or statically_known_true(grad.size(source_dim) == dim_size) + for source_dim, dim_size in enumerate(input_size) + ) + + if _is_canonical_grad_shape(): + return _vectorized_index_put() + + def _sym_min_if_needed(a, b): + if statically_known_true(a <= b): + return a + if statically_known_true(b <= a): + return b + return torch.sym_min(a, b) + + def _sym_max_if_needed(a, b): + if statically_known_true(a >= b): + return a + if statically_known_true(b >= a): + return b + return torch.sym_max(a, b) + + def _reshape_source(source: Tensor, target_shape: list[int]) -> Tensor: + ndim = len(target_shape) + source_ndim = source.dim() + if source_ndim > ndim: + return source.expand(target_shape) + + dim_offset = ndim - source_ndim + view_shape = [1] * ndim + for source_dim in range(source_ndim): + target_dim = dim if source_dim == dim else source_dim + dim_offset + if target_dim < 0 or target_dim >= ndim: + return source.expand(target_shape) + if statically_known_true(view_shape[target_dim] == 1): + view_shape[target_dim] = source.shape[source_dim] + else: + # Multiple grad dimensions may align to the unfolded input + # dimension after select(); only singleton collisions can + # still be reshaped and broadcast to the target shape. + torch._check( + source.shape[source_dim] == 1, + lambda: "unfold_backward grad shape is not broadcastable " + "to input_size", + ) + + return source.reshape(view_shape).expand(target_shape) + + input_dim_size = input_size[dim] + grad_dim_size = grad.size(dim) + # Descending offsets make each grad_input element accumulate overlapping + # windows in increasing fold-index order, matching native numerics. + for offset in reversed(range(size)): + max_valid_len = _sym_max_if_needed( + (input_dim_size - offset + step - 1) // step, 0 + ) + valid_len = _sym_min_if_needed(grad_dim_size, max_valid_len) + idx = torch.arange(valid_len, device=grad.device, dtype=torch.int32) + idx = idx * step + offset + source = grad.select(-1, offset).narrow(dim, 0, valid_len) + source_shape = list(input_size) + source_shape[dim] = valid_len + source = _reshape_source(source, source_shape) + grad_input = aten.index_add(grad_input, dim, idx, source) + + return grad_input.contiguous() + + +@register_decomposition(aten.logit_backward.default) +@pw_cast_for_opmath +def logit_backward( + grad_output: Tensor, self: Tensor, eps: float | None = None +) -> Tensor: + if eps is not None: + lo = eps + hi = 1.0 - lo + return torch.where( + torch.logical_and(self >= lo, self <= hi), + grad_output / (self * (1.0 - self)), + 0.0, + ) + else: + return torch.where( + torch.logical_and(self >= 0.0, self <= 1.0), + grad_output / (self * (1.0 - self)), + self.new_full((), float("nan")), + ) + + +@register_decomposition(aten.dropout) +@aten.dropout.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.dropout.default.py_impl(DispatchKey.Autograd) +def dropout(input: Tensor, p: float, train: bool | None): + if train and p != 0: + return aten.native_dropout(input, p, train)[0] + else: + return input + + +@register_decomposition(aten.native_dropout) +@out_wrapper("out0", "out1") +def native_dropout(input: Tensor, p: float, train: bool | None): + if train and p != 0: + if p == 1: + return (torch.zeros_like(input), torch.zeros_like(input, dtype=torch.bool)) + if not input.dtype.is_floating_point: + raise RuntimeError( + "result type Float can't be cast to the desired output type Long" + ) + bool_mask = torch.rand_like(input) > p + res = bool_mask * input * float(1.0 / (1.0 - p)) + return (res, bool_mask) + else: + return (input, torch.ones_like(input, dtype=torch.bool)) + + +@register_decomposition(aten._softmax) +@out_wrapper() +def _softmax(x: Tensor, dim: int, half_to_float: bool): + # eager softmax returns a contiguous tensor. Ensure that decomp also returns + # a contiguous tensor. + x = x.contiguous() + if half_to_float: + if x.dtype != torch.half: + raise AssertionError( + f"half_to_float is True but x.dtype is {x.dtype}, expected torch.half" + ) + computation_dtype, result_dtype = utils.elementwise_dtypes( + x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + x = x.to(computation_dtype) + x_max = _softmax_unbacked_safe_amax(x, dim) + unnormalized = torch.exp(x - x_max) + result = unnormalized / torch.sum(unnormalized, dim, keepdim=True) + if not half_to_float: + result = result.to(result_dtype) + return result + + +def _softmax_unbacked_safe_amax(x: Tensor, dim: int) -> Tensor: + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if x.ndim == 0: + return torch.amax(x, dim, keepdim=True) + + canonical_dim = utils.canonicalize_dim(x.ndim, dim) + if guard_or_false(x.shape[canonical_dim] > 0): + return torch.amax(x, dim, keepdim=True) + + # Plain amax has no identity, so it cannot reduce over an empty dim. + # With unbacked sizes this becomes a deferred runtime assert, but eager + # softmax handles empty inputs. Pad a single -inf, the identity for max: + # it never wins for non-empty input and makes empty input well-defined. + pad_shape = list(x.shape) + pad_shape[canonical_dim] = 1 + x = torch.cat((x, x.new_full(pad_shape, float("-inf"))), dim=dim) + return torch.amax(x, dim, keepdim=True) + + +@register_decomposition(aten._log_softmax) +@out_wrapper(exact_dtype=True) +def _log_softmax(x: Tensor, dim: int, half_to_float: bool): + # eager log_softmax returns a contiguous tensor. Ensure that decomp also + # returns a contiguous tensor. + x = x.contiguous() + if half_to_float: + if x.dtype != torch.half: + raise AssertionError( + f"half_to_float is True but x.dtype is {x.dtype}, expected torch.half" + ) + computation_dtype, result_dtype = utils.elementwise_dtypes( + x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + x = x.to(computation_dtype) + x_max = _softmax_unbacked_safe_amax(x, dim) + shifted = x - x_max + shifted_logsumexp = torch.log(torch.sum(torch.exp(shifted), dim, keepdim=True)) + result = shifted - shifted_logsumexp + if not half_to_float: + result = result.to(result_dtype) + return result + + +@register_decomposition(aten.embedding) +@out_wrapper() +def embedding( + weight: Tensor, + indices: Tensor, + padding_idx: int = -1, + scale_grad_by_freq: bool = False, + sparse: bool = False, +) -> Tensor: + if weight.dim() != 2: + raise AssertionError(f"'weight' must be 2-D, got {weight.dim()}-D") + # Nb. scale_grad_by_freq is not used in the forward + if indices.ndim <= 1: + # We need this one as weight[indices] calls item() in these cases + out = weight.index_select(0, indices) + if indices.ndim == 0: + out = out.squeeze(0) + return out + else: + return weight[indices] + + +@register_decomposition(aten.embedding_dense_backward) +@out_wrapper() +def embedding_dense_backward( + grad_output: Tensor, + indices: Tensor, + num_weights: int, + padding_idx: int, + scale_grad_by_freq: bool, +): + computation_dtype, result_dtype = utils.elementwise_dtypes( + grad_output, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + grad_output = grad_output.to(computation_dtype) + indices = _maybe_convert_to_dtype(indices, torch.long) # type: ignore[assignment] + valid_indices = (indices >= 0) & (indices < num_weights) + if scale_grad_by_freq: + counts = indices.new_zeros((num_weights,)) + ones = torch.ones_like(indices) + counts = aten._unsafe_masked_index_put_accumulate( + counts, valid_indices, [indices], ones + ) + grad_weights_scale = aten._unsafe_masked_index( + counts, valid_indices, [indices], 1 + ) + grad_output = grad_output / grad_weights_scale.unsqueeze(-1) + + mask = _unsqueeze_to_dim(valid_indices & (indices != padding_idx), grad_output.ndim) + grad_weight = grad_output.new_zeros( + (num_weights,) + grad_output.shape[indices.ndim :] + ) + return aten._unsafe_masked_index_put_accumulate( + grad_weight, mask, [indices], grad_output + ).to(result_dtype) + + +def prod(x: list[int]): + r = 1 + for i in x: + r *= i + return r + + +def _pad_chunk( + tensors: list[Tensor], + dim: int, + num_chunks: int, +) -> list[Tensor]: + padded_tensors = [] + for tensor in tensors: + tensor_size = tensor.size() + pad_along_dim = (tensor_size[dim] + num_chunks - 1) // num_chunks * num_chunks + if pad_along_dim != tensor_size[dim]: + # Use aten.constant_pad_nd instead of copy_ for functionalization + pad = [0] * 2 * (tensor.ndim - dim - 1) + [ + 0, + pad_along_dim - tensor_size[dim], + ] + tensor = aten.constant_pad_nd(tensor, pad, 0) + view_size = tensor_size[:dim] + torch.Size([num_chunks, -1]) + padded_tensors.append(tensor.reshape(view_size)) + return padded_tensors + + +def have_same_ndims(tensors: list[Tensor]): + ndim = tensors[0].ndim + for tensor in tensors: + if tensor.ndim != ndim: + return False + return True + + +def leading_dimension_matches(tensors: list[Tensor], dim: int): + leading_dim_sizes = tensors[0].size()[:dim] + for tensor in tensors: + torch._check( + tensor.size()[:dim] == leading_dim_sizes, + lambda: "_chunk_cat expects same sizes of 0,...,dim-1 dimensions for all tensors", + ) + + +def _preprocess_chunk_cat_inputs( + tensors: list[Tensor], + dim: int, + num_chunks: int, +): + torch._check(num_chunks >= 1, lambda: "_chunk_cat expects positive num_chunks") + torch._check( + len(tensors) > 0, lambda: "_chunk_cat expects a non-empty input tensor list" + ) + expected_dtype = tensors[0].dtype + expected_device = tensors[0].device + for tensor in tensors: + torch._check(tensor.numel() > 0, lambda: "_chunk_cat expects non-empty tensor") + torch._check( + tensor.dtype == expected_dtype, + lambda: "_chunk_cat expects all input tensors with the same dtype", + ) + torch._check( + tensor.device == expected_device, + lambda: "_chunk_cat expects all inputs tensors on the same device", + ) + if have_same_ndims(tensors): + dim = utils.canonicalize_dim(tensors[0].dim(), dim) + else: + torch._check( + dim >= 0, + lambda: "_chunk_cat expects non-negative dim when input tensors have different ndims", + ) + for tensor in tensors: + torch._check( + dim < tensor.ndim, + lambda: "_chunk_cat expects dim < ndim for all input tensors", + ) + leading_dimension_matches(tensors, dim) + return dim + + +@register_decomposition([aten._chunk_cat.default, aten._chunk_cat.out]) +def _chunk_cat( + tensors: list[Tensor], + dim: int, + num_chunks: int, + out: Tensor | None = None, +) -> Tensor: + dim = _preprocess_chunk_cat_inputs(tensors, dim, num_chunks) + padded_tensors = _pad_chunk(tensors, dim, num_chunks) + if out is None: + return torch.cat(padded_tensors, dim + 1) + else: + torch.cat(padded_tensors, dim + 1, out=out) + return out + + +# out_wrapper currently does not allow optional outputs +@register_decomposition( + [aten.split_with_sizes_copy.default, aten.split_with_sizes_copy.out] +) +def split_with_sizes_copy( + self: Tensor, + split_sizes: list[int], + dim: int = 0, + out: list[Tensor] | None = None, +) -> list[Tensor] | None: + splits = aten.split_with_sizes(self, split_sizes, dim=dim) + if out is None: + return [s.clone(memory_format=torch.contiguous_format) for s in splits] + else: + for output, split in zip(out, splits): + _maybe_resize_out(output, split.shape) + _safe_copy_out(copy_from=split, copy_to=output, exact_dtype=True) + return None + + +@register_decomposition(aten.unsafe_split.Tensor) +def unsafe_split(input: Tensor, split_size: int, dim: int = 0) -> tuple[Tensor, ...]: + return aten.split.Tensor(input, split_size, dim) + + +@register_decomposition(aten.unsafe_split_with_sizes.default) +def unsafe_split_with_sizes( + input: Tensor, split_sizes: list[int], dim: int = 0 +) -> tuple[Tensor, ...]: + return aten.split_with_sizes.default(input, split_sizes, dim) + + +@register_decomposition(aten.split.Tensor) +def split(self: Tensor, split_size: int, dim: int = 0) -> tuple[Tensor, ...]: + input_sizes = self.shape + dim_size = input_sizes[dim] + torch._check( + split_size >= 0, + lambda: f"split expects split_size be non-negative, but got split_size={split_size}", + ) + if dim_size == 0: + return (self.detach(),) + torch._check( + split_size > 0, + lambda: "split_size can only be 0 if dimension size is 0, " + f"but got dimension size of {dim_size}", + ) + chunks = (dim_size + split_size - 1) // split_size + + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import guard_int + + chunks = guard_int(chunks) + split_sizes = [split_size for i in range(chunks)] + split_sizes[-1] = split_size - (split_size * chunks - dim_size) + return torch.split(self, split_sizes, dim) + + +@aten.tensor_split.tensor_indices_or_sections.py_impl( + DispatchKey.CompositeImplicitAutograd +) +def tensor_split_tensor_indices_or_sections_py_impl( + self: Tensor, + tensor_indices_or_sections: Tensor, + dim: int = 0, +) -> tuple[Tensor, ...]: + if tensor_indices_or_sections.device.type != "cpu": + raise AssertionError( + f"tensor_indices_or_sections must be on CPU, got {tensor_indices_or_sections.device}" + ) + if tensor_indices_or_sections.dtype != torch.int64: + raise AssertionError( + f"tensor_indices_or_sections must be int64, got {tensor_indices_or_sections.dtype}" + ) + split_dim = tensor_indices_or_sections.dim() + torch._check( + split_dim == 1 or split_dim == 0, + lambda: "tensor_split expected tensor_indices_or_sections to be a zero-dimensional " + f"or one-dimensional tensor, but got a tensor with {split_dim} dims", + ) + if split_dim == 0: + sections = tensor_indices_or_sections.item() + if not isinstance(sections, IntLike): + raise AssertionError( + f"Expected sections to be IntLike, got {type(sections).__name__}" + ) + return self.tensor_split(sections, dim) + else: + ctx = nullcontext + if (fake_mode := torch._guards.detect_fake_mode()) and ( + shape_env := fake_mode.shape_env + ): + ctx = shape_env.ignore_fresh_unbacked_symbols # type: ignore[assignment] + # In fake tensor prop, we end up calling slice() with these unbacked indices. + # Because slice has flexible semantics, the unbacked handling generates new output sizes + # for each slice, effectively clobbering over these index symbols. + # To avoid PendingUnbackedSymbolNotFound errors, we tell the compiler it's fine to not bind these. + with ctx(): + indices = [i.item() for i in tensor_indices_or_sections] + # WARNING: Tempted to torch._check(x>0) on the indices here? You + # can't: tensor_split works with negative values in indices: + # + # >>> torch.tensor_split(torch.randn(10), torch.tensor([-5, 5])) + # (tensor([ 0.3540, 2.1074, -0.8507, 1.1639, 0.3055]), tensor([]), + # tensor([-0.4285, 1.0692, -0.1776, 0.9362, 1.6143])) + # + # Sorry, I don't make the rules. Explicitly do the item call in user + # code if you KNOW that they are non-negative. + return self.tensor_split(indices, dim) + + +# TODO: this doesn't appear to have enough precision in bfloat16 +@register_decomposition([aten.addmm.default, aten.addmm.out]) +@out_wrapper(exact_dtype=True) +@pw_cast_for_opmath +def addmm(self: Tensor, mat1: Tensor, mat2: Tensor, beta: int = 1, alpha: int = 1): + if not self.is_floating_point() and not self.is_complex(): + beta = int(beta) + alpha = int(alpha) + out = alpha * torch.mm(mat1, mat2) + if beta == 0: + return out + + # The output of aten.addmm is contiguous, we need to match this behavior in the decomposition. + # The original implementation 'beta * self + out' would return a strided tensor if `self` is strided. + # We thus use `out`, the output of torch.mm, which is always contiguous, as the first argument for addition. + # This is relying on TensorIterator's behavior that it takes higher precedence on the stride of first input. + # Alternative, we can write `(beta * self + out).contiguous()`, but it introduces another copy in some cases. + # This implementation is not ideal, and we should revisit this when we have a better solution. + return out + beta * self + + +@register_decomposition([aten.addmm.dtype, aten.addmm.dtype_out]) +@out_wrapper(exact_dtype=True) +def addmm_dtype( + self: Tensor, + mat1: Tensor, + mat2: Tensor, + out_dtype: torch.dtype, + beta: int = 1, + alpha: int = 1, +): + out = alpha * torch.mm(mat1, mat2, out_dtype=out_dtype) + if beta == 0: + return out + return out + beta * self.to(out_dtype) + + +@register_decomposition(aten._addmm_activation) +@out_wrapper() +@pw_cast_for_opmath +def _addmm_activation( + self: Tensor, + mat1: Tensor, + mat2: Tensor, + beta: int = 1, + alpha: int = 1, + use_gelu: bool = False, +): + out = addmm(self, mat1, mat2, beta, alpha) + if use_gelu: + if self.is_cuda: + return aten.gelu(out, approximate="tanh") + else: + return aten.gelu(out) + return aten.relu(out) + + +@pw_cast_for_opmath +def _addmv_impl(self: Tensor, mat1: Tensor, vec: Tensor, beta: int = 1, alpha: int = 1): + if not self.is_floating_point() and not self.is_complex(): + beta = int(beta) + alpha = int(alpha) + out = alpha * torch.mv(mat1, vec) + if beta == 0: + return out + if out.numel() == 0: # handle empty matrix + return beta * self + return out + beta * self + + +@register_decomposition(aten.addmv) +@out_wrapper(exact_dtype=True) +def addmv(self: Tensor, mat1: Tensor, vec: Tensor, beta: int = 1, alpha: int = 1): + torch._check( + self.dtype == mat1.dtype and mat1.dtype == vec.dtype, + lambda: f"addmv input tensors must have the same dtype, but got {self.dtype}, {mat1.dtype}, and {vec.dtype}", + ) + return _addmv_impl(self, mat1, vec, beta, alpha) + + +@register_decomposition(aten.native_group_norm_backward.default) +@pw_cast_for_opmath +def native_group_norm_backward( + grad_output: Tensor, + input: Tensor, + mean: Tensor, + rstd: Tensor, + gamma: Tensor | None, + N: int, + C: int, + HxW: int, + group: int, + output_mask: list[bool], +) -> tuple[Tensor | None, Tensor | None, Tensor | None]: + utils.check_same_device( + grad_output, input, mean, rstd, allow_cpu_scalar_tensors=False + ) + utils.check_same_shape(input, grad_output, allow_cpu_scalar_tensors=False) + utils.check_same_shape(mean, rstd, allow_cpu_scalar_tensors=False) + torch._check( + input.numel() == N * C * HxW, + lambda: f"Expect input to have {N * C * HxW} elements", + ) + torch._check( + mean.shape == (N, group), + lambda: f"Expect mean to have shape ({N}, {group}, but got {mean.shape}", + ) + torch._check( + gamma is None or gamma.numel() == C, + lambda: f"Expect gamma to have {C} elements but got {gamma.numel() if gamma is not None else -1}", + ) + + cpg = C // group + torch._check( + C == cpg * group, + lambda: f"Expect number of channels {C} to be evenly-divisible by number of groups {group}", + ) + + # Compute Internal gradients + ds = torch.mul(grad_output, input).reshape(N, C, HxW).sum(dim=[2]) + db = grad_output.reshape(N, C, HxW).sum(dim=[2]) + + d_input: Tensor | None = None + d_gamma: Tensor | None = None + d_bias: Tensor | None = None + if output_mask[0]: + s = 1.0 / (HxW * cpg) + if gamma is not None: + ds_val = torch.mul(ds, gamma.unsqueeze(0)).reshape(N, group, cpg).sum(2) + db_val = torch.mul(db, gamma.unsqueeze(0)).reshape(N, group, cpg).sum(2) + c1 = torch.mul( + rstd.unsqueeze(-1), + gamma.reshape(1, group, cpg), + ) + else: + ds_val = ds.reshape(N, group, cpg).sum(2) + db_val = db.reshape(N, group, cpg).sum(2) + c1 = torch.mul( + rstd.unsqueeze(-1), + torch.ones((1, group, cpg), device=rstd.device), + ) + c2 = torch.addcmul(-ds_val, db_val, mean) * rstd * rstd * rstd * s + c3 = -c2 * mean - db_val * rstd * s + + c1 = c1.unsqueeze(-1) + c2 = _unsqueeze_to_dim(c2, 4) + c3 = _unsqueeze_to_dim(c3, 4) + d_input = ( + torch.mul(grad_output.reshape(N, group, cpg, HxW), c1) + + torch.mul(input.reshape(N, group, cpg, HxW), c2) + + c3 + ) + d_input = d_input.reshape(input.shape).to(input.dtype) + if output_mask[1]: + d_gamma = ( + ( + (ds.view(N, group, cpg) - db.view(N, group, cpg) * mean.unsqueeze(-1)) + * rstd.unsqueeze(-1) + ) + .sum(dim=[0]) + .reshape(C) + ) + if output_mask[2]: + d_bias = db.sum(dim=[0]) + + return (d_input, d_gamma, d_bias) + + +# out_wrapper currently does not allow optional outputs +@register_decomposition(aten.native_group_norm_backward.out) +def native_group_norm_backward_out( + grad_output: Tensor, + input: Tensor, + mean: Tensor, + rstd: Tensor, + gamma: Tensor | None, + N: int, + C: int, + HxW: int, + group: int, + output_mask: list[bool], + *, + out0: torch.Tensor, + out1: torch.Tensor, + out2: torch.Tensor, +) -> tuple[Tensor | None, Tensor | None, Tensor | None]: + result = native_group_norm_backward( + grad_output, input, mean, rstd, gamma, N, C, HxW, group, output_mask + ) + grad_input = (out0, out1, out2) + for i, r in enumerate(result): + if r is not None: + _maybe_resize_out(grad_input[i], r.shape) + _safe_copy_out(copy_from=r, copy_to=grad_input[i], exact_dtype=True) + + return grad_input + + +def _maybe_cast(x: Tensor | None, dtype) -> Tensor | None: + if x is not None: + return x.to(dtype) + return x + + +# TODO: Take a closer look at the type promotion semantics +@register_decomposition(aten.native_layer_norm_backward.default) +def native_layer_norm_backward( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + mean: Tensor, + rstd: Tensor, + weight: Tensor | None, + bias: Tensor | None, + output_mask: list[bool], +) -> tuple[Tensor | None, Tensor | None, Tensor | None]: + input_shape = input.shape + input_ndim = input.dim() + computation_dtype = utils.get_computation_dtype(input.dtype) + grad_out_cast, input_cast, weight_cast, bias_cast = ( + x.to(computation_dtype, memory_format=torch.contiguous_format) + if x is not None + else x + for x in (grad_out, input, weight, bias) + ) + if grad_out_cast is None: + raise AssertionError("grad_out_cast should not be None") + + axis = input_ndim - len(normalized_shape) + inner_dims = input_shape[axis:] + outer_dims = input_shape[:axis] + inner_dim_indices: list[int] = [] + outer_dim_indices: list[int] = [] + for i in range(input_ndim): + if i >= axis: + inner_dim_indices.append(i) + else: + outer_dim_indices.append(i) + + N = prod(inner_dims) # type: ignore[arg-type] + M = prod(outer_dims) # type: ignore[arg-type] + from torch.fx.experimental.symbolic_shapes import statically_known_true + + if statically_known_true(M == 0) or statically_known_true(N == 0): + return ( + input.new_zeros(input_shape) if output_mask[0] else None, + input.new_zeros(input_shape[axis:]) if output_mask[1] else None, + input.new_zeros(input_shape[axis:]) if output_mask[2] else None, + ) + mean = _unsqueeze_to_dim(mean, input_cast.dim()) # type: ignore[union-attr] + rstd = _unsqueeze_to_dim(rstd, input_cast.dim()) # type: ignore[union-attr] + if input_cast is None: + raise AssertionError("input_cast should not be None") + x_hat = (input_cast - mean) * rstd + if weight_cast is not None: + grad_x_hat = grad_out_cast * weight_cast + else: + grad_x_hat = grad_out_cast + a = grad_x_hat * N + b = torch.sum(grad_x_hat, inner_dim_indices, True) + c1 = torch.mul(grad_x_hat, x_hat) + c2 = torch.sum(c1, inner_dim_indices, True) + c3 = torch.mul(x_hat, c2) + + inner = a - b - c3 + d_input: Tensor | None = None + d_weight: Tensor | None = None + d_bias: Tensor | None = None + if output_mask[0]: + d_input = (rstd / N) * inner + + if output_mask[1] and weight_cast is not None: + if len(outer_dim_indices) > 0: + d_weight = torch.sum(grad_out_cast * x_hat, outer_dim_indices, False) + else: + d_weight = grad_out_cast * x_hat + + if output_mask[2] and bias_cast is not None: + if len(outer_dim_indices) > 0: + d_bias = torch.sum(grad_out_cast, outer_dim_indices, False) + else: + d_bias = grad_out_cast.clone() + + return ( + _maybe_cast(d_input, input.dtype), + _maybe_cast(d_weight, weight.dtype if weight is not None else None), + _maybe_cast(d_bias, bias.dtype if bias is not None else None), + ) + + +# out_wrapper currently does not allow optional outputs +@register_decomposition(aten.native_layer_norm_backward.out) +def native_layer_norm_backward_out( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + mean: Tensor, + rstd: Tensor, + weight: Tensor | None, + bias: Tensor | None, + output_mask: list[bool], + *, + out0: torch.Tensor, + out1: torch.Tensor, + out2: torch.Tensor, +) -> tuple[Tensor | None, Tensor | None, Tensor | None]: + result = native_layer_norm_backward( + grad_out, input, normalized_shape, mean, rstd, weight, bias, output_mask + ) + grad_input = (out0, out1, out2) + for i, r in enumerate(result): + if r is not None: + _maybe_resize_out(grad_input[i], r.shape) + _safe_copy_out(copy_from=r, copy_to=grad_input[i], exact_dtype=True) + + return grad_input + + +@register_decomposition(aten._fused_rms_norm.default) +def _fused_rms_norm( + input: Tensor, + normalized_shape: list[int], + weight: Tensor | None, + eps: float | None, +) -> tuple[Tensor, Tensor]: + dims_to_reduce: list[int] = [] + for i in range(len(normalized_shape)): + dims_to_reduce.append(input.dim() - i - 1) + + # upcast is needed for fp16 and bf16 + computation_dtype = utils.get_computation_dtype(input.dtype) + upcasted_input = input.to(computation_dtype) + + # computation_dtype would be one of [Double, Float, ComplexFloat, ComplexDouble] + if eps is None: + if computation_dtype in (torch.float32, torch.complex64): + eps_val = torch.finfo(torch.float32).eps + else: + eps_val = torch.finfo(torch.float64).eps + else: + eps_val = eps + + rqrst_input = torch.rsqrt( + # NB: don't inplace here, will violate functional IR invariant + # NB: carefully use the Scalar overload of add to ensure compatibility with the C++ decomp + torch.ops.aten.add.Scalar( + torch.pow(upcasted_input, 2).mean(dim=dims_to_reduce, keepdim=True), eps_val + ) + ) + + upcasted_result = upcasted_input.mul(rqrst_input) + + if weight is not None: + upcasted_result = upcasted_result.mul(weight) + + # NB: nested should be dead here, just here for fidelity + is_nested = input.is_nested or (weight is not None and weight.is_nested) + memory_format = utils.suggest_memory_format(input) + is_channels_last = memory_format in ( + torch.channels_last, + torch.channels_last_3d, + ) + + if not is_nested and not is_channels_last: + upcasted_result = upcasted_result.contiguous() + rqrst_input = rqrst_input.contiguous() + + # Cast normalized result back to original input type + result = upcasted_result.type_as(input) + + return result, rqrst_input + + +@register_decomposition(aten._fused_rms_norm_backward.default) +def _fused_rms_norm_backward( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + rstd: Tensor, + weight: Tensor | None, + output_mask: list[bool], +) -> tuple[Tensor | None, Tensor | None]: + input_shape = input.shape + input_ndim = input.dim() + computation_dtype = utils.get_computation_dtype(input.dtype) + + grad_out_cast = grad_out.to( + computation_dtype, memory_format=torch.contiguous_format + ) + input_cast = input.to(computation_dtype, memory_format=torch.contiguous_format) + weight_cast = ( + weight.to(computation_dtype, memory_format=torch.contiguous_format) + if weight is not None + else None + ) + if grad_out_cast is None: + raise AssertionError("grad_out_cast should not be None") + + axis = input_ndim - len(normalized_shape) + inner_dims = input_shape[axis:] + outer_dims = input_shape[:axis] + inner_dim_indices: list[int] = [] + outer_dim_indices: list[int] = [] + for i in range(input_ndim): + if i >= axis: + inner_dim_indices.append(i) + else: + outer_dim_indices.append(i) + + N = prod(inner_dims) # type: ignore[arg-type] + M = prod(outer_dims) # type: ignore[arg-type] + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(M == 0) or guard_or_false(N == 0): + return ( + input.new_zeros(input_shape) if output_mask[0] else None, + input.new_zeros(input_shape[axis:]) if output_mask[1] else None, + ) + + rstd = _unsqueeze_to_dim(rstd, input_cast.dim()) # type: ignore[union-attr] + if weight_cast is not None: + grad_x_hat = grad_out_cast * weight_cast + else: + grad_x_hat = grad_out_cast + + d_input: Tensor | None = None + d_weight: Tensor | None = None + + x_hat = input_cast * rstd + + if output_mask[0]: + sum_val = torch.sum(x_hat * grad_x_hat, dim=inner_dim_indices, keepdim=True) + d_input = (grad_x_hat - (x_hat / N) * sum_val) * rstd + + if output_mask[1] and weight_cast is not None: + d_weight_full_shape = grad_out_cast * x_hat + if len(outer_dim_indices) > 0: + d_weight = torch.sum( + d_weight_full_shape, dim=outer_dim_indices, keepdim=False + ) + else: + d_weight = d_weight_full_shape + + return ( + _maybe_cast(d_input, input.dtype), + _maybe_cast(d_weight, input.dtype), + ) + + +def native_batch_norm_helper( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: bool, + momentum: float, + eps: float, + functional: bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor | None, Tensor | None]: + reduction_dims = [0] + list(range(2, input.dim())) + computation_dtype = utils.get_computation_dtype(input.dtype) + new_running_mean = running_mean + new_running_var = running_var + if training: + computation_dtype = utils.get_computation_dtype(input.dtype) + input_acc = input.to(dtype=computation_dtype) + biased_var, mean = torch.var_mean( + input_acc, dim=reduction_dims, correction=0, keepdim=True + ) + rstd = torch.rsqrt(biased_var + eps) + + output = (input - mean) * rstd + + save_mean = torch.squeeze(mean, reduction_dims) + save_rstd = torch.squeeze(rstd, reduction_dims) + if running_mean is not None: + new_running_mean = momentum * save_mean + (1 - momentum) * running_mean + if not functional: + running_mean.copy_(new_running_mean) + if running_var is not None: + n = input.numel() / input.shape[1] + # This doesn't strictly match eager's numerics, which accumulates var sum and then directly applies the correction + # But... that would require re-implementing var here, for negligible numerics gain on a tensor whose + # numerics probably don't matter. + squeezed_var = torch.squeeze(biased_var, reduction_dims) + unbiased_var = squeezed_var * (n / (n - 1)) + new_running_var = momentum * unbiased_var + (1 - momentum) * running_var + if not functional: + running_var.copy_(new_running_var) + else: + if running_mean is None or running_var is None: + raise AssertionError( + "running_mean and running_var must not be None in eval mode" + ) + running_mean = running_mean.to(dtype=computation_dtype, copy=True) + new_running_mean = running_mean + running_var = running_var.to(dtype=computation_dtype, copy=True) + new_running_var = running_var + mean = running_mean + invstd = torch.rsqrt(running_var + eps) + # Very annoying inconsistency where CPU and CUDA give different shapes + if input.device.type != "cpu": + save_mean = running_mean + save_rstd = invstd + else: + save_mean = input.new_zeros((0,)) + save_rstd = input.new_zeros((0,)) + mean = _unsqueeze_to_dim(mean, input.dim() - 1) + invstd = _unsqueeze_to_dim(invstd, input.dim() - 1) + output = (input - mean) * invstd + + if weight is not None: + weight = weight.flatten() + weight = _unsqueeze_to_dim(weight, input.dim() - 1) + output = output * weight + + if bias is not None: + bias = bias.flatten() + bias = _unsqueeze_to_dim(bias, input.dim() - 1) + output = output + bias + + if input.device.type == "cpu": + save_mean = save_mean.to(dtype=input.dtype) + save_rstd = save_rstd.to(dtype=input.dtype) + return ( + output.to(dtype=input.dtype), + save_mean, + save_rstd, + new_running_mean, + new_running_var, + ) + + +@register_decomposition(aten.native_batch_norm) +@out_wrapper("out", "save_mean", "save_invstd") +def native_batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, training, momentum, eps, False + ) + return output, save_mean, save_rstd + + +# TODO: this decomposition is NOT here to stay. We would much prefer replacing native_batch_norm +# with our new correctly schema'd _native_batch_norm_legit and its variants, but +# we cannot do that immediately in the C++ because it would be forwards incompatible +# with some mobile use cases. +# +# Since this change is most impactful for aot autograd/functionalization, we simply +# register this decomposition on the Autograd key for the python dispatcher (which is +# currently only used by aot autograd/functionalization and no one else, really). +# In two weeks or so, we should remove this decomposition and phase out the current native_batch_norm +# to be _native_batch_norm_legit and have the right schema (stating that there are input mutations). +@aten.native_batch_norm.default.py_impl(DispatchKey.Autograd) +@aten.native_batch_norm.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def native_batch_norm_decomposition( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + if running_mean is None and running_var is None: + return aten._native_batch_norm_legit( + input, weight, bias, training, momentum, eps + ) + if running_mean is None: + raise RuntimeError( + "running_mean is None, but running_var is provided. " + "They should both be None or both be provided." + ) + if running_var is None: + raise RuntimeError( + "running_var is None, but running_mean is provided. " + "They should both be None or both be provided." + ) + if training: + # HACK: batch norm consolidation should clean this up so this op doesn't take in a training arg. + return aten._native_batch_norm_legit( + input, weight, bias, running_mean, running_var, training, momentum, eps + ) + else: + return aten._native_batch_norm_legit_no_training( + input, weight, bias, running_mean, running_var, momentum, eps + ) + + +@aten.unsafe_chunk.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def unsafe_chunk_py_impl(tensor, chunks, dim=0) -> list[Tensor]: + dim_size = tensor.size(dim) + split_size = (dim_size + chunks - 1) // chunks + + if split_size == 0 and dim_size == 0: + split_sizes = [split_size for _ in range(chunks)] + split_sizes[chunks - 1] = split_size - (split_size * chunks - dim_size) + return torch.ops.aten.unsafe_split_with_sizes.default(tensor, split_sizes, dim) + return torch.ops.aten.unsafe_split.Tensor(tensor, split_size, dim) + + +@register_decomposition(aten._native_batch_norm_legit_no_training.default) +def _native_batch_norm_legit_no_training( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + return aten._native_batch_norm_legit.default( + input, + weight, + bias, + running_mean, + running_var, + False, # training + momentum, + eps, + ) + + +@register_decomposition(aten._native_batch_norm_legit.default) +def _native_batch_norm_legit( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, training, momentum, eps, False + ) + return output, save_mean, save_rstd + + +@register_decomposition(aten._native_batch_norm_legit.no_stats) +def _native_batch_norm_legit_no_stats( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, weight, bias, None, None, training, momentum, eps, False + ) + return output, save_mean, save_rstd + + +@register_decomposition(aten._native_batch_norm_legit_functional.default) +def _native_batch_norm_legit_functional( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: + ( + output, + save_mean, + save_rstd, + new_running_mean, + new_running_var, + ) = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, training, momentum, eps, True + ) + if new_running_mean is None: + raise AssertionError("new_running_mean should not be None") + if new_running_var is None: + raise AssertionError("new_running_var should not be None") + return output, save_mean, save_rstd, new_running_mean, new_running_var + + +def _get_batch_norm_reserve_tensor( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + eps: float, + training: bool, +) -> Tensor: + """ + Return a reserve tensor for batch norm, used only by cudnn to pass forward state to the + backward pass. This is needed for `_batch_norm_with_update` and `_batch_norm_no_update`, + which support a variety of backends including cudnn. We create this tensor here to get + the correct shape in the traced graph if we detect that will call the cudnn kernel, + and rely on DCE to avoid materializing this tensor. + """ + backend = torch._C._select_batch_norm_backend( # type: ignore[attr-defined] + input, weight, bias, running_mean, running_var, True, eps + ) + reserve_size = 0 + if backend == torch._C._BatchNormBackend.Cudnn: # type: ignore[attr-defined] + reserve_size = torch._C._get_cudnn_batch_norm_reserve_space_size( # type: ignore[attr-defined] + input, training + ) + return torch.empty( + reserve_size, dtype=torch.uint8, layout=input.layout, device=input.device + ) + + +@register_decomposition(aten._batch_norm_with_update.default) +def _batch_norm_with_update( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, + weight, + bias, + running_mean, + running_var, + True, # training + momentum, + eps, + False, # functional + ) + reserve = _get_batch_norm_reserve_tensor( + input, weight, bias, running_mean, running_var, eps, training=True + ) + return output, save_mean, save_rstd, reserve + + +@register_decomposition(aten._batch_norm_with_update_functional.default) +def _batch_norm_with_update_functional( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: + ( + output, + save_mean, + save_rstd, + new_rm, + new_rv, + ) = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, True, momentum, eps, True + ) + reserve = _get_batch_norm_reserve_tensor( + input, weight, bias, running_mean, running_var, eps, training=True + ) + if new_rm is None: + raise AssertionError("new_running_mean should not be None") + if new_rv is None: + raise AssertionError("new_running_var should not be None") + return (output, save_mean, save_rstd, reserve, new_rm, new_rv) + + +@register_decomposition(aten._batch_norm_no_update.default) +def _batch_norm_no_update( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, + weight, + bias, + running_mean, + running_var, + False, # training + momentum, + eps, + False, # functional + ) + reserve = _get_batch_norm_reserve_tensor( + input, weight, bias, running_mean, running_var, eps, training=False + ) + return output, save_mean, save_rstd, reserve + + +@register_decomposition(aten._fused_dropout) +@out_wrapper("out0", "out1") +def _fused_dropout_decomposition(input, p, generator=None): + if generator is not None: + raise AssertionError( + f"generator must be None for _fused_dropout decomposition, got {generator}" + ) + computation_dtype, result_dtype = utils.elementwise_dtypes( + input, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + input_acc = input.to(computation_dtype) + mask = (torch.rand_like(input_acc) < p).to(dtype=torch.uint8) + scale = torch.scalar_tensor(1.0, dtype=computation_dtype, device=input.device) / p + res = mask.to(computation_dtype) * input_acc * scale + return (res.to(result_dtype), mask) + + +@register_decomposition(aten._to_copy) +@out_wrapper() +def _to_copy( + x: Tensor | NumberType, + *, + dtype: torch.dtype | None = None, + layout=None, + device: torch.device | None = None, + pin_memory: bool = False, + non_blocking: bool = False, + memory_format: torch.memory_format | None = None, +): + if layout and layout != torch.strided: + raise AssertionError(f"layout must be None or torch.strided, got {layout}") + if pin_memory: + raise AssertionError( + "pin_memory=True is not supported in _to_copy decomposition" + ) + if not isinstance(x, (torch.Tensor, int, float, bool, complex)): + raise AssertionError(f"x must be Tensor or scalar, got {type(x).__name__}") + if device is None and dtype is None and memory_format is None: + if isinstance(x, torch.Tensor): + return x.clone() + else: + return x + dtype_converted = False + + if isinstance(x, torch.Tensor): + x_tensor = x + else: + x_tensor = torch.scalar_tensor(x) + + if device is not None and device != x_tensor.device: + # When both dtype and device change, decide where to do the dtype + # conversion. The general heuristic is to convert on the faster + # device (i.e. avoid conversions on cpu when the source is a gpu). + # However, we must convert on the *source* device when the target + # device does not support the source dtype – e.g. copying a float64 + # tensor to an XPU device that lacks fp64 hardware would otherwise + # create an unsupported intermediate buffer on the target device. + if dtype is not None: + convert_before_transfer = False + if device.type == "cpu": + # Source is accelerator, target is CPU – convert on the + # (faster) source device before the transfer. + convert_before_transfer = True + elif x_tensor.dtype == torch.float64: + # The target device may not support float64 (e.g. Intel Arc + # consumer GPUs). Convert to the requested dtype on the + # source device to avoid creating an unsupported fp64 + # intermediate buffer on the target device. + from torch._inductor.utils import device_supports_fp64 + + if not device_supports_fp64(device): + convert_before_transfer = True + + if convert_before_transfer: + x_tensor = torch._prims.convert_element_type(x_tensor, dtype) + dtype_converted = True + x_tensor = torch._prims.device_put(x_tensor, device, non_blocking) + + if dtype is not None and not dtype_converted: + x_tensor = torch._prims.convert_element_type(x_tensor, dtype) + dtype_converted = True + + if memory_format is not None: # no ref/prim for memory format + return torch.clone(x_tensor, memory_format=memory_format) + return x_tensor + + +# Questionable decompositions +# This is only valid if we're running the graph without autograd, such as if the backward pass has been traced. +# Note that this decomposition causes issues with in-place ops +@register_decomposition([aten.detach, aten.lift, aten.lift_fresh]) +@out_wrapper() +def nop_decomposition(x): + return aten.alias(x) + + +# Also register to the Autograd dispatch key, so this decomp can run above autograd. +# native_batch_norm needs to decompose into other ops before autograd. +@aten.cudnn_batch_norm.default.py_impl(DispatchKey.Autograd) +@register_decomposition(aten.cudnn_batch_norm) +@out_wrapper("out0", "out1", "out2", "out3") +def cudnn_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: bool, + exponential_average_factor: float, + epsilon: float, +): + a, b, c = aten.native_batch_norm( + input, + weight, + bias, + running_mean, + running_var, + training, + exponential_average_factor, + epsilon, + ) + # Cudnn return running mean and variance when training is True + if training: + return (a, b, c, input.new_zeros((0,), dtype=torch.uint8)) + return ( + a, + weight.new_zeros((0,)), + weight.new_zeros((0,)), + input.new_zeros((0,), dtype=torch.uint8), + ) + + +def _broadcast_batch_norm_backward(x, broadcast_mask): + for axis, mask in enumerate(broadcast_mask): + if mask == 1 and not (axis < x.ndim and x.shape[axis] == mask): + x = x.unsqueeze(axis) + return x + + +@register_decomposition(aten.batch_norm_backward.default) +def batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_invstd: Tensor | None, + train: bool, + eps: float, + output_mask: list[bool], + reserve: Tensor, +) -> tuple[Tensor, Tensor | None, Tensor | None]: + return native_batch_norm_backward( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_invstd, + train, + eps, + output_mask, + ) + + +@register_decomposition(aten.native_batch_norm_backward.default) +def native_batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_invstd: Tensor | None, + train: bool, + eps: float, + output_mask: list[bool], +) -> tuple[Tensor, Tensor | None, Tensor | None]: + input_dtype = input.dtype + if weight is not None: + weight_dtype = weight.dtype + else: + weight_dtype = input_dtype + computation_dtype = utils.get_computation_dtype(input.dtype) + ( + grad_out_cast, + input_cast, + weight_cast, + running_mean_cast, + running_var_cast, + save_mean_cast, + save_invstd_cast, + ) = ( + x.to(computation_dtype) if x is not None else x + for x in ( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_invstd, + ) + ) + input_shape = input.shape + input_rank = input.dim() + if input_rank < 2: + raise AssertionError(f"rank of the input must be at least 2, got {input_rank}") + + axis = 1 + num_features = prod(list(input_shape)) / input_shape[axis] + mean = save_mean_cast + invstd = save_invstd_cast + if train: + if mean is None or invstd is None: + raise AssertionError("mean and invstd must not be None in training mode") + + else: + if running_mean_cast is None or running_var_cast is None: + raise AssertionError( + "running_mean_cast and running_var_cast must not be None in eval mode" + ) + mean = running_mean_cast + invstd = torch.rsqrt(running_var_cast + eps) + + broadcast_mask: list[int] = [1] * input_rank + broadcast_mask[axis] = input_shape[axis] + + reduction_axes: list[int] = [] + for i in range(input_rank): + if i != axis: + reduction_axes.append(i) + + mean = _broadcast_batch_norm_backward(mean, broadcast_mask) # type: ignore[arg-type] + norm = 1.0 / num_features + grad_output_sum = torch.sum(grad_out_cast, reduction_axes) # type: ignore[arg-type] + dot_p = torch.sum(grad_out_cast * (input_cast - mean), reduction_axes) # type: ignore[operator] + + grad_mean = _broadcast_batch_norm_backward(grad_output_sum * norm, broadcast_mask) + proj_scale = _broadcast_batch_norm_backward( + torch.mul(dot_p * norm, invstd * invstd), # type: ignore[operator] + broadcast_mask, + ) + + if weight_cast is None: + grad_scale = _broadcast_batch_norm_backward(invstd, broadcast_mask) * 1.0 # type: ignore[arg-type] + else: + grad_scale = _broadcast_batch_norm_backward( + invstd * weight_cast, broadcast_mask + ) + + if train: + proj = (input_cast - mean) * proj_scale # type: ignore[operator] + grad_input = ((grad_out_cast - proj) - grad_mean) * grad_scale + else: + grad_input = grad_out_cast * grad_scale + + if output_mask[1]: + grad_weight = dot_p * invstd + else: + grad_weight = None # "None" doesn't work with vjp, should use zeros for vjp + + if output_mask[2]: + grad_bias = grad_output_sum + else: + grad_bias = None # "None" doesn't work with vjp, should use zeros for vjp + + return ( + grad_input.to(input_dtype), + _maybe_cast(grad_weight, weight_dtype), + _maybe_cast(grad_bias, weight_dtype), + ) + + +# out_wrapper currently does not allow optional outputs +@register_decomposition(aten.native_batch_norm_backward.out) +def native_batch_norm_backward_out( + grad_out: Tensor, + input: Tensor, + weight: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_invstd: Tensor | None, + train: bool, + eps: float, + output_mask: list[bool], + *, + out0: torch.Tensor, + out1: torch.Tensor, + out2: torch.Tensor, +) -> tuple[Tensor, Tensor | None, Tensor | None]: + result = native_batch_norm_backward( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_invstd, + train, + eps, + output_mask, + ) + grad_input = (out0, out1, out2) + for i, r in enumerate(result): + if r is not None: + _maybe_resize_out(grad_input[i], r.shape) + _safe_copy_out(copy_from=r, copy_to=grad_input[i], exact_dtype=True) + + return grad_input + + +@register_decomposition(aten.miopen_batch_norm_backward) +@out_wrapper("out0", "out1", "out2") +def miopen_batch_norm_backward( + input: Tensor, + grad_output: Tensor, + weight: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_var: Tensor | None, + epsilon: float, +): + return aten.native_batch_norm_backward( + grad_output, + input, + weight, + running_mean, + running_var, + save_mean, + save_var, + True, + epsilon, + [True, True, True], + ) + + +@register_decomposition(aten.cudnn_batch_norm_backward) +@out_wrapper("out0", "out1", "out2") +def cudnn_batch_norm_backward( + input: Tensor, + grad_output: Tensor, + weight: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_var: Tensor | None, + epsilon: float, + reserveSpace: Tensor, +): + return aten.native_batch_norm_backward( + grad_output, + input, + weight, + running_mean, + running_var, + save_mean, + save_var, + True, + epsilon, + [True, True, True], + ) + + +@register_decomposition(aten._adaptive_avg_pool2d) +@out_wrapper() +@pw_cast_for_opmath +def adaptive_avg_pool2d(input: Tensor, output_size: tuple[int, int]): + # Preconditions + device = input.device + shape = input.shape + ndim = len(shape) + torch._check( + ndim in (3, 4), + lambda: f"adaptive_avg_pool2d(): Expected 3D or 4D tensor, but got {ndim}", + ) + for d in input.shape[-2:]: + torch._check( + d != 0, + lambda: "adaptive_avg_pool2d(): Expected input to have non-zero size for " + f"non-batch dimensions, but input has shape {tuple(shape)}.", + ) + + # Optimisation (we should also do this in the kernel implementation) + if shape[-2] % output_size[-2] == 0 and shape[-1] % output_size[-1] == 0: + stride = tuple(i // o for i, o in zip(shape[-2:], output_size)) + kernel = tuple( + i - (o - 1) * s for i, o, s in zip(shape[-2:], output_size, stride) + ) + return torch.nn.functional.avg_pool2d(input, kernel, stride) + + def start_index(a, b, c): + return torch.div(a * c, b, rounding_mode="trunc") + + def end_index(a, b, c): + return torch.div((a + 1) * c + b - 1, b, rounding_mode="trunc") + + def compute_idx(in_size, out_size): + orange = torch.arange(out_size, device=device, dtype=torch.int64) + i0 = start_index(orange, out_size, in_size) + # Let length = end_index - start_index, i.e. the length of the pooling kernels + # length.max() can be computed analytically as follows: + maxlength = in_size // out_size + 1 + in_size_mod = in_size % out_size + # adaptive = True iff there are kernels with different lengths + adaptive = not (in_size_mod == 0 or out_size % in_size_mod == 0) + if adaptive: + maxlength += 1 + elif in_size_mod == 0: + maxlength -= 1 + + range_max = torch.arange(maxlength, device=device, dtype=torch.int64) + idx = i0.unsqueeze(-1) + range_max + if adaptive: + # Need to clamp to avoid accessing out-of-bounds memory + # TODO make minimum accept scalars + maxval = torch.scalar_tensor( + in_size - 1, dtype=idx.dtype, device=idx.device + ) + idx = torch.minimum(idx, maxval) + + # Compute the length + i1 = end_index(orange, out_size, in_size) + length = i1 - i0 + else: + length = maxlength + return idx, length, range_max, adaptive + + # length is not None if it's constant, otherwise we'll need to compute it + idxh, length_h, range_max_h, adaptive_h = compute_idx(shape[-2], output_size[-2]) + idxw, length_w, range_max_w, adaptive_w = compute_idx(shape[-1], output_size[-1]) + + vals = input[..., _unsqueeze_to_dim(idxh, 4), idxw] + # Shortcut for the simpler case + if not adaptive_h and not adaptive_w: + return torch.mean(vals, dim=(-3, -1)) + + def maybe_mask(vals, length, range_max, adaptive, dim): + if isinstance(length, IntLike): + return vals, length + else: + # zero-out the things we didn't really want to select + if dim >= 0: + raise AssertionError(f"dim should be negative when masking, got {dim}") + # hack + mask = range_max >= length.unsqueeze(-1) + if dim == -2: + mask = _unsqueeze_to_dim(mask, 4) + vals = torch.masked_fill(vals, mask, 0.0) + # Compute the length of each window + length = _unsqueeze_to_dim(length, -dim) + return vals, length + + vals, length_h = maybe_mask( + vals, length_h, range_max_h, adaptive=adaptive_h, dim=-2 + ) + vals, length_w = maybe_mask( + vals, length_w, range_max_w, adaptive=adaptive_w, dim=-1 + ) + + # We unroll the sum as we assume that the kernels are going to be small + ret = None + for i, j in product(range(vals.shape[-3]), range(vals.shape[-1])): + if ret is None: + ret = vals[..., i, :, j] + else: + ret = ret + vals[..., i, :, j] + return ret / (length_h * length_w) + + +def _max_pool_nd_with_indices( + self: Tensor, + kernel_size: list[int], + stride: list[int], + padding: list[int], + dilation: list[int], + ceil_mode: bool, + n_dim: int, +) -> tuple[Tensor, Tensor]: + def _expand(val: list[int] | int, default: list[int] | None = None) -> list[int]: + if not isinstance(val, (list, tuple)): + return [val] * n_dim + if not val: + torch._check(default is not None, lambda: "default must be provided") + return default # type: ignore[return-value] + return val * n_dim if len(val) == 1 else list(val) + + ks = _expand(kernel_size) + st = _expand(stride, default=ks) + pa = _expand(padding) + di = _expand(dilation) + + torch._check( + self.ndim in (n_dim + 1, n_dim + 2), + lambda: f"Expected {n_dim + 1}D or {n_dim + 2}D input, got {self.ndim}D", + ) + + is_batched = self.ndim == n_dim + 2 + if not is_batched: + self = self.unsqueeze(0) + + input_sizes = list(self.shape[-n_dim:]) + device = self.device + + output_sizes = [ + torch._meta_registrations.pooling_output_shape( + input_sizes[d], ks[d], pa[d], st[d], di[d], ceil_mode + ) + for d in range(n_dim) + ] + + # Pad with -inf so out-of-bounds positions never win the max. For integer + # types, iinfo.min is a valid data value, so padding with it causes ties + # in argmax that produce wrong indices. Promote to a wider type so the + # sentinel is strictly below any representable value in the original dtype. + dtype = self.dtype + promoted = False + if dtype is torch.bool: + fill_value = 0.0 + elif dtype.is_floating_point: + fill_value = float("-inf") + else: + info = torch.iinfo(dtype) + if info.bits < 32: + self = self.to(torch.int32) + elif info.bits < 64: + self = self.to(torch.int64) + fill_value = float(info.min - 1) if info.bits < 64 else float(info.min) + promoted = True + + # Compute asymmetric padding: left = pa[d], right may be larger for ceil_mode + pad_args: list[int] = [] + for d in reversed(range(n_dim)): # F.pad takes last dim first + left = pa[d] + needed = (output_sizes[d] - 1) * st[d] + (ks[d] - 1) * di[d] + 1 + right = max(0, needed - (input_sizes[d] + 2 * pa[d])) + pa[d] + pad_args.extend([left, right]) + x = F.pad(self, pad_args, value=fill_value) + + # Build index tensor per spatial dim: + # idx[out_pos, ker_pos] = out_pos * stride + ker_pos * dilation + # Reshape each for broadcasting into the Cartesian product of all dims + idx_tensors = [] + for d in range(n_dim): + idx = ( + torch.arange(output_sizes[d], device=device, dtype=torch.int64).unsqueeze(1) + * st[d] + + torch.arange(ks[d], device=device, dtype=torch.int64).unsqueeze(0) * di[d] + ) + shape = [1] * (2 * n_dim) + shape[2 * d] = output_sizes[d] + shape[2 * d + 1] = ks[d] + idx_tensors.append(idx.reshape(shape)) + + # Advanced indexing gathers all pooling windows at once via broadcasting. + # Result: (N, C, out_0, k_0, out_1, k_1, ..., out_{n-1}, k_{n-1}) + windows = x[(Ellipsis, *idx_tensors)] + + # Permute to (N, C, out_0, ..., out_{n-1}, k_0, ..., k_{n-1}) + n_batch = 2 + perm = list(range(n_batch)) + perm += [n_batch + 2 * d for d in range(n_dim)] + perm += [n_batch + 2 * d + 1 for d in range(n_dim)] + windows = windows.permute(perm) + + # Flatten kernel dims and take the max + out_shape = list(windows.shape[: n_batch + n_dim]) + windows = windows.reshape(*out_shape, -1) + values, local_argmax = windows.max(dim=-1) + + # Convert local_argmax in [0, prod(ks)) to per-dim kernel offsets + kernel_pos = [] + remaining = local_argmax + for d in range(n_dim): + divisor = 1 + for dd in range(d + 1, n_dim): + divisor *= ks[dd] + kernel_pos.append(remaining // divisor) + remaining = remaining % divisor + + # Compute flat index into the original (unpadded) input spatial volume + orig_coords = [] + for d in range(n_dim): + shape = [1] * (n_batch + n_dim) + shape[n_batch + d] = output_sizes[d] + out_pos = torch.arange( + output_sizes[d], device=device, dtype=torch.int64 + ).reshape(shape) + orig_coords.append(out_pos * st[d] + kernel_pos[d] * di[d] - pa[d]) + + flat_indices = orig_coords[0] + for d in range(1, n_dim): + flat_indices = flat_indices * input_sizes[d] + orig_coords[d] + + if promoted: + values = values.to(dtype) + + if not is_batched: + values = values.squeeze(0) + flat_indices = flat_indices.squeeze(0) + + return values, flat_indices + + +@register_decomposition(aten.max_pool2d_with_indices) +@out_wrapper("out", "indices") +def max_pool2d_with_indices( + self: Tensor, + kernel_size: list[int], + stride: list[int] = [], # noqa: B006 + padding: list[int] = [0], # noqa: B006 + dilation: list[int] = [1], # noqa: B006 + ceil_mode: bool = False, +) -> tuple[Tensor, Tensor]: + return _max_pool_nd_with_indices( + self, kernel_size, stride, padding, dilation, ceil_mode, n_dim=2 + ) + + +@register_decomposition(aten.max_pool3d_with_indices) +@out_wrapper("out", "indices") +def max_pool3d_with_indices( + self: Tensor, + kernel_size: list[int], + stride: list[int] = [], # noqa: B006 + padding: list[int] = [0], # noqa: B006 + dilation: list[int] = [1], # noqa: B006 + ceil_mode: bool = False, +) -> tuple[Tensor, Tensor]: + return _max_pool_nd_with_indices( + self, kernel_size, stride, padding, dilation, ceil_mode, n_dim=3 + ) + + +@register_decomposition(aten.adaptive_max_pool2d) +@out_wrapper("out", "indices") +def adaptive_max_pool2d( + input: Tensor, + output_size: tuple[int, int], +) -> tuple[Tensor, Tensor]: + ndim = input.ndim + torch._check( + ndim in (3, 4), + lambda: f"adaptive_max_pool2d(): Expected 3D or 4D tensor, but got {ndim}D", + ) + for i in range(1, ndim): + torch._check( + input.size(i) > 0, + lambda: ( + "adaptive_max_pool2d(): Expected input to have non-zero size for non-batch dimensions, " + f"but input has sizes {input.shape} with dimension {i} being empty" + ), + ) + + h_in = input.shape[-2] + w_in = input.shape[-1] + h_out, w_out = output_size + + # Case 1: empty output + if h_out == 0 or w_out == 0: + output_shape = list(input.shape[:-2]) + [h_out, w_out] + return ( + input.new_empty(output_shape), + input.new_empty(output_shape, dtype=torch.int64), + ) + + # Case 2: global pooling (output_size == (1, 1)) + # Equivalent to amax over spatial dims. argmax on the flattened spatial + # plane produces flat indices encoded as ih*W+iw. + if h_out == 1 and w_out == 1: + values = torch.amax(input, dim=(-2, -1), keepdim=True) + indices = torch.argmax(input.flatten(-2), dim=-1).unsqueeze(-1).unsqueeze(-1) + return values, indices + + # Case 3: evenly divisible -- delegate to max_pool2d_with_indices + if h_in % h_out == 0 and w_in % w_out == 0: + kernel_size = [h_in // h_out, w_in // w_out] + return aten.max_pool2d_with_indices(input, kernel_size) + + # Case 4: general (non-evenly-divisible, output_size > 1) + return NotImplemented + + +@register_decomposition(aten.adaptive_max_pool3d) +@out_wrapper("out", "indices") +def adaptive_max_pool3d( + input: Tensor, + output_size: tuple[int, int, int], +) -> tuple[Tensor, Tensor]: + ndim = input.ndim + torch._check( + ndim in (4, 5), + lambda: f"adaptive_max_pool3d(): Expected 4D or 5D tensor, but got {ndim}D", + ) + for i in range(1, ndim): + torch._check( + input.size(i) > 0, + lambda: ( + "adaptive_max_pool3d(): Expected input to have non-zero size for non-batch dimensions, " + f"but input has sizes {input.shape} with dimension {i} being empty" + ), + ) + + d_in = input.shape[-3] + h_in = input.shape[-2] + w_in = input.shape[-1] + d_out, h_out, w_out = output_size + + # Case 1: empty output + if d_out == 0 or h_out == 0 or w_out == 0: + output_shape = list(input.shape[:-3]) + [d_out, h_out, w_out] + return ( + input.new_empty(output_shape), + input.new_empty(output_shape, dtype=torch.int64), + ) + + # Case 2: global pooling (output_size == (1, 1, 1)) + # Equivalent to amax over spatial dims. argmax on the flattened spatial + # volume produces flat indices encoded as + # id*H*W + ih*W + iw. + if d_out == 1 and h_out == 1 and w_out == 1: + values = torch.amax(input, dim=(-3, -2, -1), keepdim=True) + indices = ( + torch.argmax(input.flatten(-3), dim=-1) + .unsqueeze(-1) + .unsqueeze(-1) + .unsqueeze(-1) + ) + return values, indices + + # Case 3: evenly divisible -- delegate to max_pool3d_with_indices + if d_in % d_out == 0 and h_in % h_out == 0 and w_in % w_out == 0: + kernel_size = [d_in // d_out, h_in // h_out, w_in // w_out] + return aten.max_pool3d_with_indices(input, kernel_size) + + # Case 4: general (non-evenly-divisible, output_size > 1) + return NotImplemented + + +def _max_unpoolnd( + self: TensorLike, indices: TensorLike, output_size: list[int], dim: int +): + # If the input tensors self and indices came from max_pool call as + # required by the documentation, this operation is deterministic + # because that ensures that if there are two entries in `indices` + # tensor that are equal, the corresponding values in `self` are also + # equal. If this condition is not satisfied, the operation is + # non-deterministic as one of the different values in `self` 'wins'. + utils.alert_not_deterministic(f"max_unpooling{dim}d_forward_out") + for i, size in enumerate(output_size): + torch._check( + size >= 0, + lambda i=i, size=size: ( + f"max_unpooling{dim}d(): output_size must contain non-negative " + f"spatial dimensions, but got output_size[{i}]={size}" + ), + ) + + # The native CPU kernel (aten/src/ATen/native/MaxUnpooling.cpp) and the XPU + # kernel (torch-xpu-ops MaxUnpoolingKernels.cpp) preserve the input's memory + # format via suggest_memory_format, while the CUDA kernel and the 3d kernels + # always return contiguous output. + def _restride(t: TensorLike) -> TensorLike: + if dim == 2 and self.device.type in ("cpu", "xpu"): + return t.contiguous(memory_format=utils.suggest_memory_format(self)) + return t + + output_shape = list(self.shape[:-dim]) + list(output_size) + if any(s == 0 for s in output_shape): + # The native CPU kernel still applies the memory format to the empty + # output (resize_ runs before the numel()==0 guard); mirror it here. + return _restride(self.new_zeros(output_shape)) + nc = reduce(operator.mul, self.shape[:-dim]) + hw = reduce(operator.mul, output_size) + indices_nc_shape = [1] * self.ndim + indices_nc_shape[:-dim] = self.shape[:-dim] + indices_flat = ( + indices + aten.arange(nc, device=self.device).view(indices_nc_shape) * hw + ).reshape(-1) + + output = self.new_zeros(output_shape) + result = aten._unsafe_index_put( + output.reshape(-1), [indices_flat], self.reshape(-1), accumulate=False + ).view(output.shape) + return _restride(result) + + # Match the CPU max_unpool2d layout behavior: the native 4D path resizes + # the output with self.suggest_memory_format(), preserving channels-last. + # The 3D path uses the default contiguous layout. + # For compile, FakeTensor preserves the real device here. + # The only edge-case we see is direct meta calls, which follow meta strides + # and may differ from CPU eager layout. + if dim == 2 and self.ndim == 4 and self.device.type == "cpu": + result = result.contiguous(memory_format=utils.suggest_memory_format(self)) + + return result + + +@register_decomposition(aten.max_unpool2d) +@out_wrapper() +def max_unpool2d( + self: TensorLike, + indices: TensorLike, + output_size: list[int], +): + torch._check( + indices.dtype == torch.int64, + lambda: f"elements in indices should be type int64 but got: {indices.dtype}", + ) + torch._check( + len(output_size) == 2, + lambda: ( + f"There should be exactly two elements (height, width) in output_size, " + f"but got {len(output_size)} elements." + ), + ) + + torch._check( + self.ndim in (3, 4), + lambda: ( + f"Input to max_unpooling2d should be a 3d or 4d Tensor, " + f"but got a tensor with {self.ndim} dimensions." + ), + ) + torch._check( + self.shape == indices.shape, + lambda: ( + f"Expected shape of indices to be same as that of the input tensor ({self.shape}) " + f"but got indices tensor with shape: {indices.shape}" + ), + ) + + for i in range(1, self.ndim): + torch._check( + self.size(i) > 0, + lambda: ( + f"max_unpooling2d(): " + f"Expected input to have non-zero size for non-batch dimensions, " + f"but got {self.shape} with dimension {i} being empty." + ), + ) + + return _max_unpoolnd(self, indices, output_size, 2) + + +@register_decomposition(aten.max_unpool3d) +@out_wrapper() +def max_unpool3d( + input: TensorLike, + indices: TensorLike, + output_size: list[int], + stride: list[int], + padding: list[int], +): + torch._check( + indices.dtype == torch.int64, lambda: "elements in indices should be type int64" + ) + torch._check( + input.ndim in (4, 5), + lambda: f"Input to max_unpooling3d should be a 4d or 5d Tensor, but got a tensor with {input.ndim} dimensions.", + ) + torch._check( + len(output_size) == 3, + lambda: ( + f"There should be exactly three elements (depth, height, width) in output_size, " + f"but got {len(output_size)} elements." + ), + ) + torch._check( + len(stride) == 3, + lambda: f"There should be exactly three elements (depth, height, width) in stride, but got: {len(stride)} elements.", + ) + torch._check( + len(padding) == 3, + lambda: f"There should be exactly three elements (depth, height, width) in padding, but got: {len(padding)} elements.", + ) + torch._check( + input.shape == indices.shape, + lambda: ( + f"Expected shape of indices to be same as that of the input tensor ({input.shape}) " + f"but got indices tensor with shape: {indices.shape}" + ), + ) + + for i in range(1, input.ndim): + torch._check( + input.size(i) > 0, + lambda: ( + f"max_unpooling3d(): " + f"Expected input to have non-zero size for non-batch dimensions, " + f"but got {input.shape} with dimension {i} being empty." + ), + ) + + torch._check( + stride[0] > 0 and stride[1] > 0 and stride[2] > 0, + lambda: f"strides should be greater than zero, but got stride: {stride}", + ) + + return _max_unpoolnd(input, indices, output_size, 3) + + +@register_decomposition(aten.index_add_) +def index_add_( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + alpha: NumberType = 1, +): + return _index_add(x, dim, index, tensor, inplace=True, alpha=alpha) + + +@register_decomposition(aten.index_add) +@out_wrapper() +def index_add( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + alpha: NumberType = 1, +): + return _index_add(x, dim, index, tensor, inplace=False, alpha=alpha) + + +def _index_add( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + inplace: bool, + alpha: NumberType = 1, +): + dim = utils.canonicalize_dims(x.ndim, dim) + torch._check( + x.device == index.device and x.device == tensor.device, + lambda: ( + f"index_add(): self, index and source expected to be in the same device, " + f"but got (self) {x.device}, (index) {index.device}, " + f"and (source) {tensor.device}" + ), + ) + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + index_size = index.size(0) if index.ndim == 1 else 1 + tensor_size = tensor.size(dim) if tensor.ndim > 0 else 1 + torch._check( + tensor_size == index_size, + lambda: f"Number of indices ({index_size}) should be equal to tensor.size(dim) ({tensor_size}), for {dim=}", + ) + if alpha != 1: + python_type = utils.dtype_to_type(x.dtype) + torch._check( + python_type is bool + or utils.is_weakly_lesser_type(type(alpha), python_type), + lambda: f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!", + ) + tensor = tensor * alpha + # Treat scalars as elements of \R^1 + zero_dim = x.ndim == 0 + x1 = x.unsqueeze(0) if zero_dim else x + idx = (None,) * dim + (index,) + index_put = aten.index_put_ if inplace else aten.index_put + out = index_put(x1, idx, tensor, accumulate=True) + if inplace: + return x + else: + return out.squeeze(0) if zero_dim else out.contiguous() + + +@register_decomposition(aten.pad_sequence.default) +@aten.pad_sequence.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def pad_sequence(sequences, batch_first=False, padding_value=0.0, padding_side="right"): + torch._check(len(sequences) > 0, lambda: "received an empty list of sequences") + torch._check( + padding_side == "left" or padding_side == "right", + lambda: f"Expected padding_side to be one of left or right, but got {padding_side}.", + ) + sequences_size = len(sequences) + max_size = sequences[0].size() + trailing_dims = max_size[1:] + # Fold with sym_max (not Python max, which does pairwise `>` comparisons) + # so symbolic/unbacked sequence lengths don't trigger a data-dependent guard. + max_len = reduce(torch.sym_max, (x.size(0) for x in sequences)) + if batch_first: + out_dims = (sequences_size, max_len) + else: + out_dims = (max_len, sequences_size) + out_dims = out_dims + trailing_dims + out = sequences[0].new_full(out_dims, padding_value) + dim_paddings = (0, 0) * len(trailing_dims) + for i in range(sequences_size): + currseq = sequences[i].to(dtype=out.dtype) + pad_amount = max_len - currseq.size(0) + if padding_side == "right": + row = aten.constant_pad_nd( + currseq, dim_paddings + (0, pad_amount), padding_value + ) + else: + row = aten.constant_pad_nd( + currseq, dim_paddings + (pad_amount, 0), padding_value + ) + if batch_first: + out = aten.select_scatter(out, row, dim=0, index=i) + else: + out = aten.select_scatter(out, row, dim=1, index=i) + return out + + +@register_decomposition(aten.index_copy_) +def index_copy_(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike): + return _index_copy(x, dim, index, tensor, inplace=True) + + +@register_decomposition(aten.index_copy) +@out_wrapper() +def index_copy(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike): + return _index_copy(x, dim, index, tensor, inplace=False) + + +def _index_copy( + x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike, *, inplace: bool +): + from torch.fx.experimental.symbolic_shapes import sym_eq + + dim = utils.canonicalize_dims(x.ndim, dim) + torch._check( + x.device == index.device and x.device == tensor.device, + lambda: ( + f"index_copy(): self, index and source expected to be in the same device, " + f"but got (self) {x.device}, (index) {index.device}, " + f"and (source) {tensor.device}" + ), + ) + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + num_indices = index.numel() + if tensor.ndim == 0: + torch._check( + num_indices == 1, + lambda: ( + "index_copy_(): When source is scalar, index should have " + f"one element (got {num_indices})" + ), + ) + elif x.ndim != 0: + torch._check( + tensor.ndim == x.ndim, + lambda: ( + "index_copy_(): When source and destination are not scalars, " + "their dimensionality must match. Source dimensionality " + f"({tensor.ndim}), destination dimensionality ({x.ndim})" + ), + ) + + x_sliced_shape = x.shape[:dim] + x.shape[dim + 1 :] if x.ndim > 0 else () + tensor_sliced_shape = ( + tensor.shape[:dim] + tensor.shape[dim + 1 :] if tensor.ndim > 0 else () + ) + torch._check( + sym_eq(x_sliced_shape, tensor_sliced_shape), + lambda: ( + "index_copy_(): Source/destination tensor must have same slice shapes. " + f"Destination slice shape: {x_sliced_shape} at dimension {dim} " + f"and source slice shape: {tensor_sliced_shape} at dimension 0." + ), + ) + if tensor.ndim != 0: + torch._check( + num_indices == tensor.size(dim), + lambda: ( + f"index_copy_(): Number of indices ({num_indices}) should be " + f"equal to source.size(dim) ({tensor.size(dim)})" + ), + ) + # Treat scalars as elements of \R^1 + zero_dim = x.ndim == 0 + x1 = x.unsqueeze(0) if zero_dim else x + index = index.unsqueeze(0) if index.ndim == 0 else index + idx = (None,) * dim + (index,) + index_put = aten.index_put_ if inplace else aten.index_put + out = index_put(x1, idx, tensor) + if inplace: + return x + else: + return out.squeeze(0) if zero_dim else out.contiguous() + + +# nb: Should use acc_t, not op_math +@register_decomposition(aten.log_sigmoid_forward) +@out_wrapper("output", "buffer") +@pw_cast_for_opmath +def log_sigmoid_forward(self: Tensor) -> tuple[Tensor, Tensor]: + min = torch.minimum(self.new_zeros(()), self) + z = torch.exp(-torch.abs(self)) + if self.is_cuda or self.is_xpu: + buffer = self.new_zeros((0,)) + else: + buffer = z + return min - torch.log1p(z), buffer + + +@register_decomposition(aten.uniform) +@out_wrapper() +def uniform( + x: Tensor, + low: bool | int | float = 0.0, + high: bool | int | float = 1.0, + generator: torch.Generator | None = None, +): + return prims._uniform_helper( + x.shape, + stride=x.stride(), + low=sym_float(low), + high=sym_float(high), + dtype=x.dtype, + device=x.device, + generator=generator, + ) + + +@register_decomposition(aten.uniform_) +def uniform_(self, low=0, high=1, generator=None): + return self.copy_(uniform(self, low, high, generator)) + + +# aten/src/ATen/native/UpSample.cpp compute_output_size +def upsample_compute_output_size(input_size, output_size, scale_factors): + spatial_dimensions = len(input_size) - 2 + if output_size is not None: + torch._check( + scale_factors is None, + lambda: "Must specify exactly one of output_size and scale_factors", + ) + torch._check(len(output_size) == spatial_dimensions, lambda: "") + return output_size + if scale_factors is not None: + # NB: this isn't necessary lol + torch._check( + output_size is None, + lambda: "Must specify exactly one of output_size and scale_factors", + ) + torch._check(len(scale_factors) == spatial_dimensions, lambda: "") + output_size = [] + for i, s in enumerate(scale_factors): + if int(s) == s: + output_size.append(input_size[i + 2] * int(s)) + else: + output_size.append(sym_int(input_size[i + 2] * s)) + return output_size + torch._check( + False, lambda: "Must specify exactly one of output_size and scale_factors" + ) + + +def get_scale_value(scales, idx): + if scales is None: + return None + return scales[idx] + + +@register_decomposition(aten.upsample_nearest1d.vec) +@register_decomposition(aten.upsample_nearest2d.vec) +@register_decomposition(aten.upsample_nearest3d.vec) +@aten.upsample_nearest1d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest1d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_nearest2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest2d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_nearest3d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest3d.vec.py_impl(DispatchKey.Autograd) +def _upsample_nearest_vec( + input: Tensor, + output_size: list[int] | None, + scale_factors: list[float] | None, +) -> Tensor: + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scales = ( + scale_factors if scale_factors else [None] * len(osize) # type: ignore[list-item] + ) + return _upsample_nearest(input, osize, scales) + + +@register_decomposition(aten._upsample_nearest_exact1d.vec) +@register_decomposition(aten._upsample_nearest_exact2d.vec) +@register_decomposition(aten._upsample_nearest_exact3d.vec) +@aten._upsample_nearest_exact1d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact1d.vec.py_impl(DispatchKey.Autograd) +@aten._upsample_nearest_exact2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact2d.vec.py_impl(DispatchKey.Autograd) +@aten._upsample_nearest_exact3d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact3d.vec.py_impl(DispatchKey.Autograd) +def _upsample_nearest_exact_vec( + input: Tensor, + output_size: list[int] | None, + scale_factors: list[float] | None, +) -> Tensor: + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scales = ( + scale_factors if scale_factors else [None] * len(osize) # type: ignore[list-item] + ) + return _upsample_nearest(input, osize, scales, exact=True) + + +def _compute_upsample_nearest_indices(input, output_size, scales, exact=False): + # For each dim in output_size, compute the set of input indices used + # to produce the upsampled output. + indices = [] + num_spatial_dims = len(output_size) + offset = 0.5 if exact else 0.0 + + for d in range(num_spatial_dims): + # Math matches aten/src/ATen/native/cpu/UpSampleKernel.cpp + # + # Indices are computed as following: + # scale = isize / osize + # Case: exact=False + # input_index = floor(output_index * scale) + # Same as OpenCV INTER_NEAREST + # + # Case: exact=False + # index_f32 = (output_index + 0.5) * scale - 0.5 + # input_index = round(index_f32) + # Same as Pillow and Scikit-Image/Scipy ndi.zoom + osize = output_size[d] + isize = input.shape[-num_spatial_dims + d] + + # check for scales[d] > 0 is in compute_scales_value in aten/src/ATen/native/UpSample.h + scale = ( + isize / (isize * scales[d]) + if scales[d] is not None and scales[d] > 0 + else isize / osize + ) + + output_indices = torch.arange(osize, dtype=torch.float32, device=input.device) + input_indices = ((output_indices + offset) * scale).to(torch.int64) + for _ in range(num_spatial_dims - 1 - d): + input_indices = input_indices.unsqueeze(-1) + indices.append(input_indices) + return indices + + +@register_decomposition([aten.upsample_nearest1d.default, aten.upsample_nearest1d.out]) +@aten.upsample_nearest1d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest1d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest1d( + input: Tensor, + output_size: list[int], + scales: float | None = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales]) + + +@register_decomposition( + [aten._upsample_nearest_exact1d.default, aten._upsample_nearest_exact1d.out] +) +@aten._upsample_nearest_exact1d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact1d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest_exact1d( + input: Tensor, + output_size: list[int], + scales: float | None = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales], exact=True) + + +@register_decomposition([aten.upsample_nearest2d.default, aten.upsample_nearest2d.out]) +@aten.upsample_nearest2d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest2d( + input: Tensor, + output_size: list[int], + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales_h, scales_w]) + + +@register_decomposition( + [aten._upsample_nearest_exact2d.default, aten._upsample_nearest_exact2d.out] +) +@aten._upsample_nearest_exact2d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def _upsample_nearest_exact2d( + input: Tensor, + output_size: list[int], + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales_h, scales_w], exact=True) + + +@register_decomposition([aten.upsample_nearest3d.default, aten.upsample_nearest3d.out]) +@aten.upsample_nearest3d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest3d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest3d( + input: Tensor, + output_size: list[int], + scales_d: float | None = None, + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales_d, scales_h, scales_w]) + + +@register_decomposition( + [aten._upsample_nearest_exact3d.default, aten._upsample_nearest_exact3d.out] +) +@aten._upsample_nearest_exact3d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact3d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def _upsample_nearest_exact3d( + input: Tensor, + output_size: list[int], + scales_d: float | None = None, + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_nearest( + input, output_size, [scales_d, scales_h, scales_w], exact=True + ) + + +@pw_cast_for_opmath +def _upsample_nearest( + input: Tensor, + output_size: list[int], + scales: list[float | None], + exact: bool = False, +) -> Tensor: + spatial_indices = _compute_upsample_nearest_indices( + input, output_size, scales, exact=exact + ) + + indices = [None, None] + spatial_indices + result = aten._unsafe_index(input, indices) + + if result.ndim in (4, 5): + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + + # following "heuristic: only use channels_last path when it's faster than the contiguous path" + n_channels = input.shape[1] + if result.ndim == 4 and input.device.type == "cuda" and n_channels < 4: + memory_format = torch.contiguous_format + + result = result.contiguous(memory_format=memory_format) + return result + + +def gather_params(params, has_biases, has_projections): + if has_biases and has_projections: + group_size = 5 + elif has_biases: + group_size = 4 + elif has_projections: + group_size = 3 + else: + group_size = 2 + + if len(params) % group_size != 0: + raise AssertionError( + f"len(params)={len(params)} is not divisible by group_size={group_size}" + ) + return [ + tuple(params[i : i + group_size]) for i in range(0, len(params), group_size) + ] + + +def params_hiddens(params, hiddens, i, bidirectional): + if bidirectional: + cur_params, cur_hidden = params[2 * i], hiddens[2 * i] + bidir_params, bidir_hidden = params[2 * i + 1], hiddens[2 * i + 1] + else: + cur_params, cur_hidden = params[i], hiddens[i] + bidir_params, bidir_hidden = None, None + + return cur_params, cur_hidden, bidir_params, bidir_hidden + + +def update_hidden_for_packed(cur_hidden, last_batch_size, batch_size, hiddens): + if last_batch_size <= batch_size: + raise AssertionError( + f"last_batch_size ({last_batch_size}) must be > batch_size ({batch_size})" + ) + hiddens.append(cur_hidden.narrow(0, batch_size, last_batch_size - batch_size)) + return cur_hidden.narrow(0, 0, batch_size) + + +def update_hidden_for_packed_reverse( + cur_hidden, last_batch_size, batch_size, inp_hidden +): + if last_batch_size == batch_size: + return cur_hidden + if last_batch_size >= batch_size: + raise AssertionError( + f"last_batch_size ({last_batch_size}) must be < batch_size ({batch_size})" + ) + return torch.concat( + ( + cur_hidden, + inp_hidden.narrow(0, last_batch_size, batch_size - last_batch_size), + ) + ) + + +def one_layer_rnn_data( + inp, hidden, params, has_biases, hidden_fn, batch_sizes, reverse=False +): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + + step_output = [] + hiddens: list[torch.Tensor] = [] + + last_batch_size = batch_sizes[-1] if reverse else batch_sizes[0] + cur_hidden = hidden.narrow(0, 0, last_batch_size) + split_inp = torch.split(inp, list(batch_sizes)) + if reverse: + split_inp = split_inp[::-1] + for inp in split_inp: + i = inp.shape[0] + + if last_batch_size == i: + pass # don't update cur_hidden + # this will only happen when reverse=False, since batch sizes are sorted largest -> smallest + elif reverse: + cur_hidden = update_hidden_for_packed_reverse( + cur_hidden, last_batch_size, i, hidden + ) + else: + cur_hidden = update_hidden_for_packed( + cur_hidden, last_batch_size, i, hiddens + ) + + cur_hidden = hidden_fn(inp, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias) + last_batch_size = i + step_output.append(cur_hidden) + + if reverse: + step_output.reverse() + else: + hiddens.append(cur_hidden) + hiddens.reverse() + + out = torch.cat(step_output, 0) + hidden_out = torch.cat(hiddens, 0) if not reverse else cur_hidden + return out, hidden_out + + +def rnn_cell(nonlinearity): + def inner(i, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + return nonlinearity(F.linear(cur_hidden, hh_weight, hh_bias) + i) + + return inner + + +def rnn_cell_data(nonlinearity): + def inner(i, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + i = F.linear(i, ih_weight, ih_bias) + return nonlinearity(F.linear(cur_hidden, hh_weight, hh_bias) + i) + + return inner + + +def one_layer_rnn(inp, hidden, params, has_biases, hidden_fn, reverse=False): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + + precomputed_input = F.linear(inp, ih_weight, ih_bias) + precomputed_input = precomputed_input.flip(0) if reverse else precomputed_input + cur_hidden = hidden.unsqueeze(0) + step_output = [] + for i in precomputed_input: + cur_hidden = hidden_fn(i, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias) + step_output.append(cur_hidden) + + if reverse: + step_output.reverse() + + out = torch.cat(step_output, 0) + + return out, cur_hidden.squeeze(0) + + +def mkldnn_one_layer_lstm(inp, hidden, params, has_biases, reverse=False): + w0 = params[0] + w1 = params[1] + if has_biases: + w2 = params[2] + w3 = params[3] + else: + w2 = torch.zeros(w0.size()) + w3 = torch.zeros(w1.size()) + + hx = hidden[0].unsqueeze(0) + cx = hidden[1].unsqueeze(0) + + batch_sizes: list[int] = [] + mode = 2 # third_party/ideep/include/ideep/abstract_types.hpp: ideep::rnn_kind::LSTM = 2 + hidden_size = hx.size(2) + num_layers = 1 + + # _rnn_helper already handles bidirectional and batch_first so we hard-code them to False here + bidirectional = False + batch_first = False + + train = False + # If batch_first, inp has been permuted in _rnn_helper. Convert to contiguous here. + # Same as aten/src/ATen/native/mkldnn/RNN.cpp: mkldnn_rnn: input = input.contiguous(); + inp = inp.contiguous() + hx = hx.contiguous() + cx = cx.contiguous() + outputs = torch.ops.aten.mkldnn_rnn_layer.default( + inp, + w0, + w1, + w2, + w3, + hx, + cx, + reverse, + batch_sizes, + mode, + hidden_size, + num_layers, + has_biases, + bidirectional, + batch_first, + train, + ) + y, hy, cy = outputs[0], outputs[1], outputs[2] + return y, (hy.squeeze(0), cy.squeeze(0)) + + +def _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + layer_fn, +): + input = input.transpose(0, 1) if batch_first else input + final_hiddens = [] + + for i in range(num_layers): + cur_params, cur_hidden, bidir_params, bidir_hidden = params_hiddens( + params, hidden, i, bidirectional + ) + dropout = dropout if (train and num_layers < i - 1) else 0.0 + fwd_inp, fwd_hidden = layer_fn(input, cur_hidden, cur_params, has_biases) + final_hiddens.append(fwd_hidden) + + if bidirectional: + bwd_inp, bwd_hidden = layer_fn( + input, bidir_hidden, bidir_params, has_biases, reverse=True + ) + final_hiddens.append(bwd_hidden) + + if bidirectional: + input = torch.cat([fwd_inp, bwd_inp], fwd_inp.dim() - 1) # type: ignore[possibly-undefined] + else: + input = fwd_inp + + if dropout != 0 and train and i < num_layers - 1: + input = torch.dropout(input, dropout, train=True) + + input = input.transpose(0, 1) if batch_first else input + return input, final_hiddens + + +@register_decomposition(aten.rnn_tanh.input) +@aten.rnn_tanh.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_tanh.input.py_impl(DispatchKey.Autograd) +def rnn_tanh_input( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + partial(one_layer_rnn, hidden_fn=rnn_cell(torch.tanh)), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.rnn_relu.input) +@aten.rnn_relu.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_relu.input.py_impl(DispatchKey.Autograd) +def rnn_relu_input( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + partial(one_layer_rnn, hidden_fn=rnn_cell(torch.relu)), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.rnn_relu.data) +@aten.rnn_relu.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_relu.data.py_impl(DispatchKey.Autograd) +def rnn_relu_data( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + data, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial( + one_layer_rnn_data, + batch_sizes=batch_sizes, + hidden_fn=rnn_cell_data(torch.relu), + ), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.rnn_tanh.data) +@aten.rnn_tanh.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_tanh.data.py_impl(DispatchKey.Autograd) +def rnn_tanh_data( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + data, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial( + one_layer_rnn_data, + batch_sizes=batch_sizes, + hidden_fn=rnn_cell_data(torch.tanh), + ), + ) + return out, torch.stack(final_hiddens, 0) + + +def lstm_cell(inp, hx, cx, hh_weight, hh_bias, hr_weight, chunk_dim): + gates = F.linear(hx, hh_weight, hh_bias) + inp + chunked_gates = gates.chunk(4, chunk_dim) + in_gate = chunked_gates[0].sigmoid() + forget_gate = chunked_gates[1].sigmoid() + cell_gate = chunked_gates[2].tanh() + out_gate = chunked_gates[3].sigmoid() + cy = forget_gate * cx + (in_gate * cell_gate) + hy = out_gate * cy.tanh() + hy = hy if hr_weight is None else F.linear(hy, hr_weight, None) + + return hy, cy + + +def one_layer_lstm(inp, hidden, params, has_biases, reverse=False): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + hr_weight = ( + params[4] if len(params) == 5 else params[2] if len(params) == 3 else None + ) + + hx = hidden[0].unsqueeze(0) + cx = hidden[1].unsqueeze(0) + + precomputed_input = F.linear(inp, ih_weight, ih_bias) + precomputed_input = precomputed_input.flip(0) if reverse else precomputed_input + step_output = [] + for inp in precomputed_input: + hx, cx = lstm_cell(inp, hx, cx, hh_weight, hh_bias, hr_weight, chunk_dim=2) + step_output.append(hx) + + if reverse: + step_output.reverse() + + out = torch.cat(step_output, 0) + + return out, (hx.squeeze(0), cx.squeeze(0)) + + +def one_layer_lstm_data(inp, hidden, params, has_biases, batch_sizes, reverse=False): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + hr_weight = ( + params[4] if len(params) == 5 else params[2] if len(params) == 3 else None + ) + + step_output = [] + hiddens = [] + + last_batch_size = batch_sizes[-1] if reverse else batch_sizes[0] + split_inp = torch.split(inp, list(batch_sizes)) + if reverse: + split_inp = split_inp[::-1] + + orig_hx = hidden[0] + orig_cx = hidden[1] + hx, cx = ( + orig_hx.narrow(0, 0, last_batch_size), + orig_cx.narrow(0, 0, last_batch_size), + ) + + for inp in split_inp: + i = inp.shape[0] + inp = F.linear(inp, ih_weight, ih_bias) + + # this will only happen when reverse=False, since batch sizes are sorted largest -> smallest + if i < last_batch_size: + hiddens.append( + ( + hx.narrow(0, i, last_batch_size - i), + cx.narrow(0, i, last_batch_size - i), + ) + ) + hx, cx = hx.narrow(0, 0, i), cx.narrow(0, 0, i) + + # this will only happen when reverse=True + if i > last_batch_size: + hx = torch.concat( + (hx, orig_hx.narrow(0, last_batch_size, i - last_batch_size)), 0 + ) + cx = torch.concat( + (cx, orig_cx.narrow(0, last_batch_size, i - last_batch_size)), 0 + ) + + hx, cx = lstm_cell(inp, hx, cx, hh_weight, hh_bias, hr_weight, chunk_dim=1) + last_batch_size = i + step_output.append(hx) + + if reverse: + step_output.reverse() + hidden_out = (hx, cx) + else: + hiddens.append((hx, cx)) + hiddens.reverse() + hidden0, hidden1 = zip(*hiddens) + hidden_out = torch.cat(hidden0, 0), torch.cat(hidden1, 0) + + out = torch.cat(step_output, 0) + return out, hidden_out + + +def select_one_layer_lstm_function(input, hx, params): + r"""Check whether we could use decompose lstm with mkldnn_rnn_layer. + All the below conditions need to be met: + * ``torch._C._get_mkldnn_enabled()`` returns ``True``. + * All the input args are on CPU. + * The dtypes of args are either torch.float or torch.bfloat16. + * Inference. + * ``has_projections`` returns ``False``. + + Args: + * input: the input sequence to LSTM + * hx: a tuple of the input hidden state and cell state ``(h_0, c_0)`` to LSTM + * params: the weight and bias tensors of LSTM + """ + + def use_mkldnn(input, hx, params): + if not torch._C._get_mkldnn_enabled(): + return False + + tensors = [input] + list(hx) + list(chain.from_iterable(params)) + devices = {t.device for t in tensors} + if len(devices) != 1: + return False + + device = devices.pop() + if device != torch.device("cpu"): + return False + # With autocast, possible to have mixed dtype here + dtypes = {t.dtype for t in tensors} + for dtype in dtypes: + if dtype not in [torch.float, torch.bfloat16]: + return False + + if input.requires_grad: + return False + + has_projections = hx[0].size(2) != hx[1].size(2) + if has_projections: + return False + + return True + + # mkldnn_one_layer_lstm does not depend on seq_len while one_layer_lstm + # will expand over the seq_len dim + if use_mkldnn(input, hx, params): + return mkldnn_one_layer_lstm + else: + return one_layer_lstm + + +@register_decomposition(aten.lstm.input) +@aten.lstm.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.lstm.input.py_impl(DispatchKey.Autograd) +def lstm_impl( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + if len(hx) != 2: + raise AssertionError(f"lstm expects two hidden states, got {len(hx)}") + params = gather_params(params, has_biases, hx[0].size(2) != hx[1].size(2)) + hidden = list(zip(hx[0], hx[1])) + layer_fn = select_one_layer_lstm_function(input, hx, params) + out, final_hiddens = _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + layer_fn, + ) + final_hiddens = list(zip(*final_hiddens)) + return out, torch.stack(final_hiddens[0], 0), torch.stack(final_hiddens[1], 0) + + +@register_decomposition(aten.lstm.data) +@aten.lstm.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.lstm.data.py_impl(DispatchKey.Autograd) +def lstm_data_impl( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + if len(hx) != 2: + raise AssertionError(f"lstm expects two hidden states, got {len(hx)}") + params = gather_params(params, has_biases, hx[0].size(2) != hx[1].size(2)) + hidden = list(zip(hx[0], hx[1])) + out, final_hiddens = _rnn_helper( + data, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial(one_layer_lstm_data, batch_sizes=batch_sizes), + ) + final_hiddens = list(zip(*final_hiddens)) + return out, torch.stack(final_hiddens[0], 0), torch.stack(final_hiddens[1], 0) + + +def gru_cell(inp, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + chunked_igates = inp.chunk(3, 1) + chunked_hgates = F.linear(cur_hidden, hh_weight, hh_bias).chunk(3, 2) + reset_gate = (chunked_hgates[0] + chunked_igates[0]).sigmoid() + input_gate = (chunked_hgates[1] + chunked_igates[1]).sigmoid() + new_gate = (chunked_igates[2] + (chunked_hgates[2] * reset_gate)).tanh() + return (cur_hidden - new_gate) * input_gate + new_gate + + +def gru_cell_data(inp, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + chunked_igates = F.linear(inp, ih_weight, ih_bias).chunk(3, 1) + chunked_hgates = F.linear(cur_hidden, hh_weight, hh_bias).chunk(3, 1) + reset_gate = (chunked_hgates[0] + chunked_igates[0]).sigmoid() + input_gate = (chunked_hgates[1] + chunked_igates[1]).sigmoid() + new_gate = (chunked_igates[2] + (chunked_hgates[2] * reset_gate)).tanh() + return (cur_hidden - new_gate) * input_gate + new_gate + + +@register_decomposition(aten.gru.data) +@aten.gru.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.gru.data.py_impl(DispatchKey.Autograd) +def gru_impl_data( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + data, + hx.unbind(0), + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial(one_layer_rnn_data, batch_sizes=batch_sizes, hidden_fn=gru_cell_data), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.gru.input) +@aten.gru.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.gru.input.py_impl(DispatchKey.Autograd) +def gru_impl( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + input, + hx.unbind(0), + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + partial(one_layer_rnn, hidden_fn=gru_cell), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten._upsample_bilinear2d_aa.vec) +@aten._upsample_bilinear2d_aa.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_bilinear2d_aa.vec.py_impl(DispatchKey.Autograd) +def upsample_bilinear2d_aa_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scale_h = get_scale_value(scale_factors, 0) + scale_w = get_scale_value(scale_factors, 1) + return torch.ops.aten._upsample_bilinear2d_aa( + input, osize, align_corners, scale_h, scale_w + ) + + +@register_decomposition(aten._upsample_bicubic2d_aa.vec) +@aten._upsample_bicubic2d_aa.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_bicubic2d_aa.vec.py_impl(DispatchKey.Autograd) +def upsample_bicubic2d_aa_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scale_h = get_scale_value(scale_factors, 0) + scale_w = get_scale_value(scale_factors, 1) + return torch.ops.aten._upsample_bicubic2d_aa( + input, osize, align_corners, scale_h, scale_w + ) + + +@register_decomposition(aten._upsample_lanczos2d_aa.vec) +@aten._upsample_lanczos2d_aa.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_lanczos2d_aa.vec.py_impl(DispatchKey.Autograd) +def upsample_lanczos2d_aa_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scale_h = get_scale_value(scale_factors, 0) + scale_w = get_scale_value(scale_factors, 1) + return torch.ops.aten._upsample_lanczos2d_aa( + input, osize, align_corners, scale_h, scale_w + ) + + +@register_decomposition(aten.upsample_bilinear2d.vec) +@register_decomposition(aten.upsample_trilinear3d.vec) +@aten.upsample_linear1d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_linear1d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_bilinear2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_bilinear2d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_trilinear3d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_trilinear3d.vec.py_impl(DispatchKey.Autograd) +def _upsample_linear_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scales = scale_factors if scale_factors else [None] * len(osize) + return _upsample_linear(input, osize, align_corners, scales) + + +@register_decomposition([aten.upsample_linear1d.default, aten.upsample_linear1d.out]) +@out_wrapper() +def upsample_linear1d( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales_w: float | None = None, +) -> Tensor: + return _upsample_linear(input, output_size, align_corners, [scales_w]) + + +@register_decomposition( + [aten.upsample_bilinear2d.default, aten.upsample_bilinear2d.out] +) +@aten.upsample_bilinear2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper() +def upsample_bilinear2d( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_linear(input, output_size, align_corners, [scales_h, scales_w]) + + +@register_decomposition( + [aten.upsample_trilinear3d.default, aten.upsample_trilinear3d.out] +) +@out_wrapper() +def upsample_trilinear3d( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales_d: float | None = None, + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_linear( + input, output_size, align_corners, [scales_d, scales_h, scales_w] + ) + + +def _compute_scale(in_size, out_size, align_corners, scale=None): + if align_corners: + return (in_size - 1.0) / (out_size - 1.0) if out_size > 1 else 0 + else: + return 1.0 / scale if scale is not None and scale > 0 else in_size / out_size + + +def _compute_source_index(scale, dst_index, align_corners): + if align_corners: + return scale * dst_index + else: + return scale * (dst_index + 0.5) - 0.5 + + +def _sum_tensors_uint8( + src: Iterable[Tensor], weights: Iterable[Tensor], weights_precision: Tensor +) -> Tensor: + output = _sum_tensors( + s.to(torch.int32) * c.to(torch.int32) for s, c in zip(src, weights) + ) + (1 << (weights_precision - 1)) + output = output >> weights_precision + return torch.clamp(output, 0, 255).to(torch.uint8) + + +def _compute_weight_precision(weights: TensorSequenceType) -> Tensor: + max_weight = torch.stack(weights).max() + max_weight_precision = 22 + precisions = torch.arange(max_weight_precision, device=max_weight.device) + values = 0.5 + max_weight * (1 << (precisions + 1)) + mask = values >= (1 << 15) + return max_weight_precision - mask.sum() + + +@pw_cast_for_opmath +def _upsample_linear( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales: list[float | None], +) -> Tensor: + # get dimensions of original image + n_channels = input.shape[1] + inp_sizes = input.shape[2:] + n_dims = len(inp_sizes) + + _, dtype = utils.elementwise_dtypes( + input, + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + + def get_values(inp_size, out_size, scales, nsqueeze): + # First Calculate scaling factor + scale_factor = _compute_scale(inp_size, out_size, align_corners, scales) + # We have to create arange with int64 dtype and use .to in order to avoid + # additional kernels creation in inductor and get a perf slowdown + i = torch.arange(out_size, device=input.device).to(dtype=dtype) + + x_f32 = _compute_source_index(scale_factor, i, align_corners).clamp(min=0.0) + x_f32 = x_f32.reshape(x_f32.shape[0], *[1] * (nsqueeze)) + x = x_f32.to(torch.int64) + xp1 = (x + 1).clamp(max=inp_size - 1) + return x_f32, x, xp1 + + values = [ + get_values(inp_size, out_size, scales, n_dims - 1 - i) + for i, (inp_size, out_size, scales) in enumerate( + zip(inp_sizes, output_size, scales) + ) + ] + xs_f32, xs, xp1s = list(zip(*values)) + + vs = [] + for a in product(*[[0, 1]] * n_dims): + idx = [None, None] + [xs[k] if a[k] == 0 else xp1s[k] for k in range(n_dims)] + v = aten._unsafe_index(input, idx) + v = _maybe_convert_to_dtype(v, dtype) + vs.append(v) + + for i in reversed(range(n_dims)): + xscale = (xs_f32[i] - xs[i]).clamp(0.0, 1.0).to(dtype) + vs = [ + # x1 * (1 - alpha) + x2 * alpha == x1 + (x2 - x1) * alpha + v1 + torch.mul(v2 - v1, xscale) + for v1, v2 in zip(vs[::2], vs[1::2]) + ] + + if len(vs) != 1: + raise AssertionError(f"Expected vs to have exactly 1 element, got {len(vs)}") + result = vs[0] + + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + + # following "heuristic: only use channels_last path when it's faster than the contiguous path" + if input.device.type == "cuda" and n_channels < 16: + memory_format = torch.contiguous_format + + if not isinstance(result, torch.Tensor): + raise AssertionError( + f"Expected result to be a Tensor, got {type(result).__name__}" + ) + + result = result.contiguous(memory_format=memory_format) + + if not input.is_floating_point(): + result = result.round() + + return result + + +# We should be applying decompositions after all transformations +@register_decomposition(aten.is_same_size.default) +def is_same_size(a: Tensor, b: Tensor) -> bool: + return a.shape == b.shape + + +@register_decomposition([aten._reshape_alias, aten._unsafe_view]) +@out_wrapper() +def _reshape_alias(x, shape, *args): + return aten.view(x, shape) + + +@register_decomposition([aten._unsafe_index]) +def _unsafe_index(x, indices): + return aten.index(x, indices) + + +@register_decomposition([aten._unsafe_index_put]) +def _unsafe_index_put(x, indices, value, accumulate=False): + return aten.index_put(x, indices, value, accumulate) + + +@register_decomposition([aten._unsafe_masked_index]) +def _unsafe_masked_index(x, mask, indices, fill): + for index in indices: + if index is not None: + torch._check( + index.dtype in [torch.long, torch.int], + lambda: "tensors used as indices must be long or int tensors", + ) + + torch._check( + mask.dtype == torch.bool, + lambda: "tensors used as masks must be bool tensors", + ) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(x.numel() == 0): + meta_result = torch._meta_registrations.meta_index_Tensor(x, indices) + return x.new_full(meta_result.shape, fill) + + for i in range(len(indices)): + index = indices[i] + if index is not None: + indices[i] = index.clamp(min=0, max=x.size(i) - 1) + + return aten._unsafe_index(x, indices).masked_fill(~mask, fill) + + +@register_decomposition([aten._unsafe_masked_index_put_accumulate]) +def _unsafe_masked_index_put_accumulate(x, mask, indices, values): + for index in indices: + if index is not None: + torch._check( + index.dtype in [torch.long, torch.int], + lambda: "tensors used as indices must be long or int tensors", + ) + + torch._check( + mask.dtype == torch.bool, + lambda: "tensors used as masks must be bool tensors", + ) + + if x.numel() == 0: + return x.clone() + + for i in range(len(indices)): + index = indices[i] + if index is not None: + indices[i] = index.clamp(min=-x.size(i), max=x.size(i) - 1) + + masked_value = values.masked_fill(~mask, 0) + return aten._unsafe_index_put(x, indices, masked_value, accumulate=True) + + +def _nll_loss_forward( + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, +) -> tuple[Tensor, Tensor]: + # self can be [N, C] or [C] + # target can be [N] or [] + + n_dims = self.dim() + channel_dim = 1 + if n_dims < 2: + channel_dim = 0 + + if weight is not None: + if n_dims > 1: + shape = [ + 1, + ] * n_dims + shape[channel_dim] = weight.shape[0] + w = weight.view(shape) + else: + w = weight + self = self * w + safe_target = torch.where(target != ignore_index, target, 0) + safe_target_ = safe_target.unsqueeze(channel_dim) + # target can be [N, 1] or [1] + + result = -torch.gather(self, channel_dim, safe_target_).squeeze(channel_dim) + + result = torch.where(target != ignore_index, result, 0) + + if reduction == Reduction.NONE.value and n_dims > 1: + total_weight = self.new_full((), 0.0) + return result, total_weight + + if weight is not None: + # pyrefly: ignore [unbound-name] + w = w.expand(self.shape) + wsum = torch.gather(w, channel_dim, safe_target_).squeeze(channel_dim) + wsum = torch.where(target != ignore_index, wsum, 0) + total_weight = wsum.sum() + else: + total_weight = (target != ignore_index).sum().to(self) + + if reduction == Reduction.SUM.value: + result = result.sum() + elif reduction == Reduction.MEAN.value: + result = result.sum() / total_weight + + return result, total_weight + + +@register_decomposition(aten.nll_loss_forward) +@out_wrapper("output", "total_weight") +def nll_loss_forward( + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, +) -> tuple[Tensor, Tensor]: + if not (self.dim() > 0 and self.dim() <= 2): + raise AssertionError(f"input tensor should be 1D or 2D, got {self.dim()}D") + if target.dim() > 1: + raise AssertionError( + f"0D or 1D target tensor expected, multi-target not supported, got {target.dim()}D" + ) + + no_batch_dim = self.dim() == 1 and target.dim() == 0 + if not no_batch_dim: + torch._check( + self.shape[0] == target.shape[0], + lambda: f"size mismatch (got input: {self.shape}, target: {target.shape})", + ) + + n_classes = self.shape[-1] + + if weight is not None and not (weight.dim() == 1 and weight.numel() == n_classes): + raise AssertionError( + f"weight tensor should be defined either for all {n_classes} classes or no classes " + f"but got weight tensor of shape: {weight.shape}" + ) + + return _nll_loss_forward(self, target, weight, reduction, ignore_index) + + +@register_decomposition(aten.nll_loss2d_forward) +@out_wrapper("output", "total_weight") +def nll_loss2d_forward( + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, +) -> tuple[Tensor, Tensor]: + return _nll_loss_forward(self, target, weight, reduction, ignore_index) + + +# These are adapted from aten/src/ATen/native/UpSample.h, which is based on +# https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm +def _upsample_cubic_convolution1(x: Tensor, A: float) -> Tensor: + return ((A + 2) * x - (A + 3)) * x * x + 1 + + +def _upsample_cubic_convolution2(x: Tensor, A: float) -> Tensor: + return ((A * x - 5 * A) * x + 8 * A) * x - 4 * A + + +def _upsample_get_cubic_coefficients(t: Tensor) -> TensorSequenceType: + A = -0.75 + + if t.device == torch.device("cpu"): + tt1 = torch.stack([t, 1.0 - t], dim=0) + tt2 = torch.stack([t + 1.0, 2.0 - t], dim=0) + w03 = _upsample_cubic_convolution2(tt2, A) + w12 = _upsample_cubic_convolution1(tt1, A) + w0, w3 = torch.unbind(w03, dim=0) + w1, w2 = torch.unbind(w12, dim=0) + return w0, w1, w2, w3 + else: + return ( + _upsample_cubic_convolution2(t + 1.0, A), + _upsample_cubic_convolution1(t, A), + _upsample_cubic_convolution1(1.0 - t, A), + _upsample_cubic_convolution2(2.0 - t, A), + ) + + +def _upsample_cubic_interp1d(coeffs: TensorSequenceType, ts: Tensor) -> Tensor: + coeffs2 = _upsample_get_cubic_coefficients(ts) + return _sum_tensors(c1 * c2 for (c1, c2) in zip(coeffs, coeffs2)) + + +# Need this instead of just sum() to keep mypy happy +def _sum_tensors(ts: Iterable[Tensor]) -> Tensor: + return reduce(torch.add, ts) + + +def _linspace_from_neg_one( + num_steps: int, align_corners: bool, dtype: torch.dtype, device: torch.device +): + if num_steps <= 1: + return torch.tensor(0, device=device, dtype=dtype) + + a = ((num_steps - 1) / num_steps) if not align_corners else 1 + return torch.linspace(-a, a, steps=num_steps, device=device, dtype=dtype) + + +def _make_base_grid_4d(theta: Tensor, h: int, w: int, align_corners: bool): + dtype = theta.dtype + device = theta.device + + # Using padding and summation generates a single kernel vs using torch.stack where 3 kernels generated + # corresponding to each individual tensor: grid_x, grid_y, grid_one + grid_x = _linspace_from_neg_one(w, align_corners, dtype, device).view(1, w, 1) + grid_y = _linspace_from_neg_one(h, align_corners, dtype, device).view(h, 1, 1) + grid_one = torch.ones((1, 1, 1), dtype=dtype, device=device) + + # this is just a temporary hack and we should use torch.stack here once #104480 is merged + grid_x = torch.nn.functional.pad(grid_x, pad=(0, 2), mode="constant", value=0) + grid_y = torch.nn.functional.pad(grid_y, pad=(1, 1), mode="constant", value=0) + grid_one = torch.nn.functional.pad(grid_one, pad=(2, 0), mode="constant", value=0) + return grid_x + grid_y + grid_one + + +def _make_base_grid_5d(theta: Tensor, d: int, h: int, w: int, align_corners: bool): + dtype = theta.dtype + device = theta.device + + grid_x = _linspace_from_neg_one(w, align_corners, dtype, device).view(1, 1, w, 1) + grid_y = _linspace_from_neg_one(h, align_corners, dtype, device).view(1, h, 1, 1) + grid_z = _linspace_from_neg_one(d, align_corners, dtype, device).view(d, 1, 1, 1) + grid_one = torch.ones((1, 1, 1, 1), dtype=dtype, device=device) + + # this is just a temporary hack and we should use torch.stack here once #104480 is merged + grid_x = torch.nn.functional.pad(grid_x, pad=(0, 3), mode="constant", value=0) + grid_y = torch.nn.functional.pad(grid_y, pad=(1, 2), mode="constant", value=0) + grid_z = torch.nn.functional.pad(grid_z, pad=(2, 1), mode="constant", value=0) + grid_one = torch.nn.functional.pad(grid_one, pad=(3, 0), mode="constant", value=0) + return grid_x + grid_y + grid_z + grid_one + + +def _affine_grid_generator_4d(theta: Tensor, size: list[int], align_corners: bool): + n, _, h, w = size + base_grid = _make_base_grid_4d(theta, h, w, align_corners=align_corners) + # base_grid shape is (h, w, 3) and theta shape is (n, 2, 3) + # We do manually a matrix multiplication which is faster than mm() + # (h * w, 3, 1) * (n, 1, 3, 2) -> (n, h * w, 2) + grid = (base_grid.view(-1, 3, 1) * theta.mT.unsqueeze(1)).sum(-2) + return grid.view(n, h, w, 2) + + +def _affine_grid_generator_5d(theta: Tensor, size: list[int], align_corners: bool): + n, _, d, h, w = size + base_grid = _make_base_grid_5d(theta, d, h, w, align_corners=align_corners) + # base_grid shape is (d, h, w, 4) and theta shape is (n, 3, 4) + # We do manually a matrix multiplication which is faster than mm() + # (d * h * w, 4, 1) * (n, 1, 4, 3) -> (n, h * w, 3) + grid = (base_grid.view(-1, 4, 1) * theta.mT.unsqueeze(1)).sum(-2) + return grid.view(n, d, h, w, 3) + + +@register_decomposition(aten.affine_grid_generator) +@out_wrapper() +@pw_cast_for_opmath +def affine_grid_generator(theta: Tensor, size: list[int], align_corners: bool): + torch._check( + len(size) in (4, 5), + lambda: "affine_grid_generator needs 4d (spatial) or 5d (volumetric) inputs.", + ) + if len(size) == 4: + return _affine_grid_generator_4d(theta, size, align_corners=align_corners) + else: + return _affine_grid_generator_5d(theta, size, align_corners=align_corners) + + +def _grid_sampler_2d( + a: Tensor, + grid: Tensor, + interpolation_mode: int = 0, + padding_mode: int = 0, + align_corners: bool = False, + _expand_grid: bool = True, +) -> Tensor: + # This method is a copy of grid_sampler_2d implementation and introduced with additional arg _expand_grid to + # optionally expand the input grid for performance reasons. + # Experimenting locally it was found that compiled CUDA code is accelerated by ~5x + # and CPU code by ~2x on bicubic mode, if we expand the grid from (N, H, W, 2) into (N, C, H, W, 2) + # However, this leads to a slowdown around ~0.8x on CPU bilinear mode, channels first. + # Thus we apply this hack to not expand the grid for this case. + + torch._check( + interpolation_mode in (0, 1, 2), + lambda: f"Invalid interpolation mode {interpolation_mode}", + ) + torch._check( + padding_mode in (0, 1, 2), lambda: f"Invalid padding mode {padding_mode}" + ) + + def unnormalize(coords: Tensor, size: int) -> Tensor: + # Rescale coordinates from [-1, 1] to: + # [0, size - 1] if align_corners is True + # [-.5, size -.5] if align_corners is False + mul = (size * 0.5 - 0.5) if align_corners else (size * 0.5) + ofs = size * 0.5 - 0.5 + return coords * mul + ofs + + # Reflects coordinates until they fall between low and high (inclusive). + # The bounds are passed as twice their value so that half-integer values + # can be represented as ints. + def reflect_coordinates(coords: Tensor, twice_low: int, twice_high: int) -> Tensor: + if twice_low == twice_high: + return torch.zeros_like(coords) + coords_min = twice_low / 2 + coords_span = (twice_high - twice_low) / 2 + coords2 = (coords - coords_min).abs() + extra = torch.fmod(coords2, coords_span) + flips = (coords2 / coords_span).floor().to(dtype=torch.int8) + return torch.where( + flips & 1 == 0, extra + coords_min, coords_span + coords_min - extra + ) + + def compute_coordinates(coords: Tensor, size: int) -> Tensor: + if padding_mode == 0: # Zero + return coords + elif padding_mode == 1: # Borders + return torch.clamp(coords, 0, size - 1) + else: # padding_mode == 2, Reflection + if align_corners: + coords_reflected = reflect_coordinates(coords, 0, 2 * (size - 1)) + else: + coords_reflected = reflect_coordinates(coords, -1, 2 * size - 1) + return torch.clamp(coords_reflected, 0, size - 1) + + def compute_source_index(coords: Tensor, size: int) -> Tensor: + coords_un = unnormalize(coords, size) + return compute_coordinates(coords_un, size) + + N, C, iH, iW = a.shape + _, oH, oW, two = grid.shape + if two != 2: + raise AssertionError( + f"grid last dimension must be 2 (for x,y coords), got {two}" + ) + + from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_and + + int32_max = torch.iinfo(torch.int32).max + # CUDA/XPU codegen can keep bounded coordinate indices in int32. CPU keeps + # the historical int64 path, and dynamic shapes fall back if we cannot guard. + use_32bit_indices = a.device.type in ("cuda", "xpu") and guard_or_false( + sym_and(iH <= int32_max, iW <= int32_max) + ) + index_dtype = torch.int32 if use_32bit_indices else torch.int64 + + if _expand_grid: + # Let's expand grid to [N, C, oH, oW, 2] + # This allows generating a single triton cuda kernel instead of two kernels. + # Two kernels are due source indices, weights have shape (N, 1, oH, oW), xnumel=N*oH*oW + # and output has shape (N, C, oH, oW), xnumel=N*C*oH*oW + # Expanding grid to (N, C, oH, oW, two) unifies xnumel to N*C*oH*oW + grid = grid.view(N, 1, oH, oW, two).expand(N, C, oH, oW, 2) + + def in_bounds_cond(xs: Tensor, ys: Tensor) -> Tensor: + return torch.logical_and( + 0 <= xs, torch.logical_and(xs < iW, torch.logical_and(0 <= ys, ys < iH)) + ) + + N_idx = torch.arange(N, device=a.device).view(N, 1, 1, 1) + C_idx = torch.arange(C, device=a.device).view(1, C, 1, 1) + + def clip(xs: Tensor, ys: Tensor, ws: Tensor) -> TensorSequenceType: + cond = in_bounds_cond(xs, ys) + # To clip to inside valid coordinates, we map the coordinates + # to (x, y) = (0, 0) and also set the weight to 0 + # We also change the shape of the tensor to the appropriate one for + # broadcasting with N_idx, C_idx for the purposes of advanced indexing + c = C if _expand_grid else 1 + return tuple( + torch.where(cond, t, 0).view(N, c, oH, oW) + for t in (xs.to(dtype=index_dtype), ys.to(dtype=index_dtype), ws) + ) + + def get_summand(ix: Tensor, iy: Tensor, w) -> Tensor: + # Perform clipping, index into input tensor and multiply by weight + idx_x, idx_y, w_ = clip(ix, iy, w) + return a[N_idx, C_idx, idx_y, idx_x] * w_ + + x = grid[..., 0] + y = grid[..., 1] + + if interpolation_mode == 0: # Bilinear + ix = compute_source_index(x, iW) + iy = compute_source_index(y, iH) + + ix_nw, iy_nw = ix.floor(), iy.floor() + ix_ne, iy_ne = ix_nw + 1, iy_nw + ix_sw, iy_sw = ix_nw, iy_nw + 1 + ix_se, iy_se = ix_ne, iy_sw + + w_nw = (ix_se - ix) * (iy_se - iy) + w_ne = (ix - ix_sw) * (iy_sw - iy) + w_sw = (ix_ne - ix) * (iy - iy_ne) + w_se = (ix - ix_nw) * (iy - iy_nw) + + return _sum_tensors( + get_summand(ix, iy, w) + for (ix, iy, w) in ( + (ix_nw, iy_nw, w_nw), + (ix_ne, iy_ne, w_ne), + (ix_sw, iy_sw, w_sw), + (ix_se, iy_se, w_se), + ) + ) + elif interpolation_mode == 1: # Nearest + ix = compute_source_index(x, iW) + iy = compute_source_index(y, iH) + + ix_nearest = ix.round() + iy_nearest = iy.round() + + return get_summand(ix_nearest, iy_nearest, 1) + else: # interpolation_mode == 2, Bicubic + ix = unnormalize(x, iW) + iy = unnormalize(y, iH) + + ix_nw = ix.floor() + iy_nw = iy.floor() + + tx = ix - ix_nw + ty = iy - iy_nw + + if not _expand_grid: + tx = tx.unsqueeze(1) + ty = ty.unsqueeze(1) + + def get_value_bounded(ix: Tensor, iy: Tensor) -> Tensor: + x = compute_coordinates(ix, iW) + y = compute_coordinates(iy, iH) + return get_summand(x, y, 1) + + def get_coeff(ofs: int) -> Tensor: + iy_ofs = iy_nw + (ofs - 1) + cs = ( + get_value_bounded(ix_nw - 1, iy_ofs), + get_value_bounded(ix_nw, iy_ofs), + get_value_bounded(ix_nw + 1, iy_ofs), + get_value_bounded(ix_nw + 2, iy_ofs), + ) + return _upsample_cubic_interp1d(cs, tx) + + coeffs = tuple(get_coeff(ofs) for ofs in range(4)) + return _upsample_cubic_interp1d(coeffs, ty) + + +@register_decomposition(aten.grid_sampler_2d) +@out_wrapper() +@pw_cast_for_opmath +def grid_sampler_2d( + a: Tensor, + grid: Tensor, + interpolation_mode: int = 0, + padding_mode: int = 0, + align_corners: bool = False, +) -> Tensor: + return _grid_sampler_2d( + a, + grid=grid, + interpolation_mode=interpolation_mode, + padding_mode=padding_mode, + align_corners=align_corners, + ) + + +@register_decomposition(aten.mv) +@out_wrapper(exact_dtype=True) +@pw_cast_for_opmath +def mv(self, vec): + torch._check( + self.dim() == 2 and vec.dim() == 1, + lambda: f"matrix @ vector expected, got {self.dim()}, {vec.dim()}", + ) + torch._check( + self.size(1) == vec.size(0), + lambda: f"size mismatch, got input ({self.size(0)}x{self.size(1)}), vec ({vec.size(0)})", + ) + return (self * vec).sum(dim=1) + + +@register_decomposition(aten.binary_cross_entropy_with_logits) +@out_wrapper() +def binary_cross_entropy_with_logits( + self, target, weight=None, pos_weight=None, reduction=Reduction.MEAN.value +): + if pos_weight is not None: + log_weight = (pos_weight - 1) * target + 1 + loss = (1 - target) * self - (log_weight * F.logsigmoid(self)) + else: + loss = (1 - target) * self - F.logsigmoid(self) + + if weight is not None: + loss = loss * weight + + # this is to align the resulted data type with the in-place + # operation in binary_cross_entropy_with_logits of aten/src/ATen/native/Loss.cpp + loss = loss.to(target.dtype) + return apply_loss_reduction(loss, reduction) + + +def should_fold(tensor1: torch.Tensor, tensor2: torch.Tensor, is_out: bool) -> bool: + # For comments of the logic of this function see eager in /native/LinearAlgebra.cpp + + t1, t2 = (tensor1, tensor2) if tensor1.ndim >= tensor2.ndim else (tensor2, tensor1) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if not (t1.ndim >= 3 and t2.ndim <= 2): + return False + if t2.requires_grad and not is_out: + return True + if tensor1.ndim == 2: + return False + if guard_or_false(sym_numel(t1) == 0): + return True + + t1_shape = t1.shape + t1_stride = t1.stride() + + # Check the contiguous, we can skip the dim with size of 1 + # as aten: https://github.com/pytorch/pytorch/blob/e201460f8aa1510b4c4686627d57b69756c4b916/aten/src/ATen/TensorGeometry.cpp#L17 + expected_stride = [1] + for size in reversed(t1_shape[1:]): + expected_stride.append(size * expected_stride[-1]) + return all( + guard_or_false(size == 1) or guard_or_false(left == right) + for left, right, size in zip( + t1_stride, list(reversed(expected_stride)), t1_shape + ) + ) + + +@aten.matmul.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.matmul.out.py_impl(DispatchKey.CompositeImplicitAutograd) +@out_wrapper(pass_is_out=True) +def matmul(tensor1, tensor2, *, is_out=False): + from torch.fx.experimental.symbolic_shapes import guard_or_false, guard_or_true + + dim_tensor1 = tensor1.dim() + dim_tensor2 = tensor2.dim() + if dim_tensor1 == 0 or dim_tensor2 == 0: + raise AssertionError( + f"matmul does not support 0-dimensional tensors, got dims: {dim_tensor1} and {dim_tensor2}" + ) + if dim_tensor1 == 1 and dim_tensor2 == 1: + return torch.dot(tensor1, tensor2) + elif dim_tensor1 == 2 and dim_tensor2 == 1: + return torch.mv(tensor1, tensor2) + elif dim_tensor1 == 1 and dim_tensor2 == 2: + return torch.squeeze(torch.mm(torch.unsqueeze(tensor1, 0), tensor2), 0) + elif dim_tensor1 == 2 and dim_tensor2 == 2: + return torch.mm(tensor1, tensor2) + elif should_fold(tensor1, tensor2, is_out): + # dim_tensor1 >=3 && (dim_tensor2 == 1 || dim_tensor2 == 2) || + # dim_tensor2 >=3 && (dim_tensor1 == 1 || dim_tensor1 == 2) + # and some condition on the strides is fulfilled + + # optimization: use mm instead of bmm by folding the batch of the larger tensor + # into its leading matrix dimension + transpose = dim_tensor2 > dim_tensor1 + t1 = tensor2.mT if transpose else tensor1 + t2 = ( + tensor2 if not transpose else (tensor1.t() if dim_tensor1 == 2 else tensor1) + ) + # Invariant: t1.dim() >= 3 && (t2.dim() == 1 || t2.dim() == 2) + # and t1 and t2 are matmul-compatible + + # Why not t1.view(-1, sizes_1[-1])? + # If the last dim is 0, then view(-1, 0) won't work because the -1 becomes ambiguous. + # This can happen in e.g. [3, 5, 0] @ [0, 0]. + sizes_1 = t1.shape + output_shape = list(sizes_1[:-1]) + folded_dim1 = reduce(operator.mul, output_shape) + + # Readjust output_shape if we are multiplying by a matrix + t2_is_matrix = t2.dim() == 2 + if t2_is_matrix: + output_shape.append(t2.shape[1]) + + # This will almost always be a view. + # It may not be a view if t2->requires_grad(). See should_fold in aten/ for an explanation + t1_folded = t1.reshape(folded_dim1, sizes_1[-1]) + if t2_is_matrix: + # This copies if we perform a 2D @ 3D and the first tensor requires_grad + # See should_fold native/LinearAlgebra.cpp for why. + output = torch.ops.aten._unsafe_view(t1_folded.mm(t2), output_shape) + return output.mT.contiguous() if transpose else output + else: + return torch.ops.aten._unsafe_view(t1_folded.mv(t2), output_shape) + + elif dim_tensor1 >= 1 and dim_tensor2 >= 1: + # We are multiplying b1 x n x m1 by x2 x m2 x p (where b1 can be a list); + # we track m1 vs m2 separately even though they must match for nicer error messages + n = tensor1.size(-2) if dim_tensor1 > 1 else 1 + m1 = tensor1.size(-1) + batch_tensor1 = tensor1.shape[:-2] + m2 = tensor2.size(-2) if dim_tensor2 > 1 else tensor2.size(-1) + p = tensor2.size(-1) if dim_tensor2 > 1 else 1 + + batch_tensor2: list[int] = [] + # TODO: handling of slice + for i in range(dim_tensor2 - 2): + batch_tensor2.append(tensor2.size(i)) + + # Same optimization for the gradients as that in should_fold + # If we're going to broadcast, we force it to go through the should_fold branch + if ( + dim_tensor1 == 3 + and dim_tensor2 == 3 + and guard_or_true(batch_tensor1[0] != batch_tensor2[0]) + ): + if guard_or_false(batch_tensor1[0] == 1) and tensor1.requires_grad: + return matmul(tensor1.squeeze(0), tensor2) + if guard_or_false(batch_tensor2[0] == 1) and tensor2.requires_grad: + return matmul(tensor1, tensor2.squeeze(0)) + + # expand the batch portion (i.e. cut off matrix dimensions and expand rest) + expand_batch_portion = list( + torch.broadcast_shapes(batch_tensor1, batch_tensor2) + ) + + tensor1_expand_size = expand_batch_portion + [n, m1] + + expand_batch_product = prod(expand_batch_portion) + + # HACK: We need reshape with symint support + tensor1_expanded = tensor1.expand(tensor1_expand_size).reshape( + expand_batch_product, n, m1 + ) + + vector_rhs = dim_tensor2 == 1 + if vector_rhs: + tensor2_expand_size = expand_batch_portion + [m2] + tensor2_expanded = ( + tensor2.expand(tensor2_expand_size) + .reshape(expand_batch_product, m2) + .unsqueeze(2) + ) + else: + tensor2_expand_size = expand_batch_portion + [m2, p] + tensor2_expanded = tensor2.expand(tensor2_expand_size).reshape( + expand_batch_product, m2, p + ) + + output_shape = expand_batch_portion + if dim_tensor1 > 1: + output_shape.append(n) + + if dim_tensor2 > 1: + output_shape.append(p) + + if vector_rhs: + return tensor1_expanded.bmm(tensor2_expanded).squeeze(-1).view(output_shape) + else: + return tensor1_expanded.bmm(tensor2_expanded).view(output_shape) + else: + torch._check(False, lambda: "both arguments to matmul need to be at least 1D") + + +@register_decomposition([aten.upsample_bicubic2d.default, aten.upsample_bicubic2d.out]) +@aten.upsample_bicubic2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper() +@pw_cast_for_opmath +def upsample_bicubic2d_default( + input: Tensor, + output_size: tuple[int, int], + align_corners: bool, + scale_h: float | None = None, + scale_w: float | None = None, +) -> Tensor: + # get dimensions of original image + _, _, in_h, in_w = input.shape + + # Calculate horizontal and vertical scaling factor + h_scale_factor = _compute_scale(in_h, output_size[0], align_corners, scale_h) + w_scale_factor = _compute_scale(in_w, output_size[1], align_corners, scale_w) + + _, dtype = utils.elementwise_dtypes( + input, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + # We have to create arange with int64 dtype and use .to in order to avoid + # additional kernels creation in inductor and get a perf slowdown + i = torch.arange(output_size[0], device=input.device).to(dtype=dtype) + j = torch.arange(output_size[1], device=input.device).to(dtype=dtype) + + x_float = _compute_source_index(w_scale_factor, j, align_corners) + y_float = _compute_source_index(h_scale_factor, i, align_corners) + y_float = y_float.unsqueeze(-1) + + x = x_float.floor() + y = y_float.floor() + + # We should also clamp xscale/yscale + # See guard_index_and_lambda in UpSample.h + yscale = (y_float - y).clamp(0.0, 1.0) + xscale = (x_float - x).clamp(0.0, 1.0) + x = x.to(torch.int64) + y = y.to(torch.int64) + + iys_ofs = (y - 1, y, y + 1, y + 2) + ixs_ofs = (x - 1, x, x + 1, x + 2) + + weights_x = _upsample_get_cubic_coefficients(xscale) + weights_y = _upsample_get_cubic_coefficients(yscale) + + weights_precision_x, weights_precision_y = None, None + if input.dtype == torch.uint8: + weights_precision_x = _compute_weight_precision(weights_x) + weights_precision_y = _compute_weight_precision(weights_y) + + weights_x = [ + (w * (1 << weights_precision_x) + torch.sign(w) * 0.5).to(torch.int16) + for w in weights_x + ] + weights_y = [ + (w * (1 << weights_precision_y) + torch.sign(w) * 0.5).to(torch.int16) + for w in weights_y + ] + + def load_bounded(ys, xs): + y_idx = torch.clamp(ys, 0, in_h - 1) + x_idx = torch.clamp(xs, 0, in_w - 1) + v = aten._unsafe_index(input, [None, None, y_idx, x_idx]) + return v + + def get_x_interp(y): + src_x = tuple(load_bounded(y, x_ofs) for x_ofs in ixs_ofs) + if input.dtype == torch.uint8: + if weights_precision_x is None: + raise AssertionError( + "weights_precision_x must not be None for uint8 input" + ) + return _sum_tensors_uint8(src_x, weights_x, weights_precision_x) + return _sum_tensors(c1 * c2 for (c1, c2) in zip(src_x, weights_x)) + + src_y = tuple(get_x_interp(y_ofs) for y_ofs in iys_ofs) + if input.dtype == torch.uint8: + if weights_precision_y is None: + raise AssertionError("weights_precision_y must not be None for uint8 input") + result = _sum_tensors_uint8(src_y, weights_y, weights_precision_y) + else: + result = _sum_tensors(c1 * c2 for (c1, c2) in zip(src_y, weights_y)) + + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + result = result.contiguous(memory_format=memory_format) + return result + + +@register_decomposition(aten.upsample_bicubic2d.vec) +@aten.upsample_bicubic2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_bicubic2d.vec.py_impl(DispatchKey.Autograd) +@out_wrapper() +@pw_cast_for_opmath +def upsample_bicubic2d_vec( + a: Tensor, + output_size: tuple[int, int] | None, + align_corners: bool, + scale_factors: tuple[float, float] | None = None, +) -> Tensor: + torch._check( + bool(output_size) + bool(scale_factors) == 1, + lambda: "Must specify exactly one of output_size and scale_factors.", + ) + if output_size is None: + if scale_factors is None: + raise AssertionError( + "scale_factors must not be None when output_size is None" + ) + output_size = cast( + tuple[int, int], + tuple( + sym_int(sym_float(w) * scale) + for w, scale in zip(a.shape[2:], scale_factors) + ), + ) + scale_h, scale_w = scale_factors if scale_factors else (None, None) + return upsample_bicubic2d_default(a, output_size, align_corners, scale_h, scale_w) + + +@register_decomposition(aten.reflection_pad1d) +@register_decomposition(aten.reflection_pad2d) +@register_decomposition(aten.reflection_pad3d) +@pw_cast_for_opmath +@out_wrapper() +def _reflection_pad(a: Tensor, padding: tuple[int, ...]) -> Tensor: + def idx(left, middle, right): + dim_idx = torch.arange(-left, middle + right, device=a.device) + return middle - 1 - (middle - 1 - dim_idx.abs()).abs() + + return _reflection_or_replication_pad( + a, + padding, + idx, + ) + + +@register_decomposition(aten.replication_pad1d) +@register_decomposition(aten.replication_pad2d) +@register_decomposition(aten.replication_pad3d) +@pw_cast_for_opmath +@out_wrapper() +def _replication_pad(a: Tensor, padding: tuple[int, ...]) -> Tensor: + def idx(left, middle, right): + dim_idx = torch.arange(-left, middle + right, device=a.device) + return torch.clamp(dim_idx, 0, middle - 1) + + return _reflection_or_replication_pad( + a, + padding, + idx, + ) + + +def _reflection_or_replication_pad( + a: Tensor, + padding: tuple[int, ...], + idx_fn: Callable[[int, int, int], Tensor], +) -> Tensor: + dim = len(padding) // 2 + torch._check( + a.dim() in (dim + 1, dim + 2), + lambda: f"reflection_pad{dim}d requires {dim + 1}D or {dim + 2}D input", + ) + inp_shape = a.shape[-dim:] + nc_dim = a.dim() - dim + + padding_left = [padding[2 * (dim - 1 - i)] for i in range(dim)] + padding_right = [padding[2 * (dim - 1 - i) + 1] for i in range(dim)] + + result = a + for i in range(dim): + idx: list[Any] = [None] * result.dim() + idx[i + nc_dim] = idx_fn(padding_left[i], inp_shape[i], padding_right[i]) + result = aten._unsafe_index(result, idx) + + # Convert output to correct memory format, if necessary. + # Use the original input (a), not result, because _unsafe_index can + # produce non-standard strides — so suggest_memory_format(result) may + # not reflect the desired output format. + # + # CPU vs CUDA/XPU/MPS eager behavior differs: + # CPU: allocates output via at::empty_like with suggest_memory_format, + # preserving the input's format (e.g. channels_last). + # CUDA/XPU/MPS: kernel writes to a flat contiguous buffer with linear indexing, + # always producing contiguous output regardless of input format. + if a.device.type in ("cuda", "mps", "xpu"): + memory_format = torch.contiguous_format + else: + memory_format = utils.suggest_memory_format(a) + result = result.contiguous(memory_format=memory_format) + return result + + +@register_decomposition(aten.reflection_pad1d_backward) +@register_decomposition(aten.reflection_pad2d_backward) +@register_decomposition(aten.reflection_pad3d_backward) +@out_wrapper("grad_input") +def _reflection_pad_backward(grad_output, x, padding): + dim = len(padding) // 2 + + dhw = [h - 1 for h in x.shape[-dim:]] + + padding_left = [padding[2 * (dim - 1 - i)] for i in range(dim)] + padding_right = [padding[2 * (dim - 1 - i) + 1] for i in range(dim)] + + indices = [] + for i in range(x.ndim): + view_shape = [1] * x.ndim + view_shape[i] = -1 + indices.append(torch.arange(x.shape[i], device=x.device).view(view_shape)) + + b = indices[:-dim] + xyz = indices[-dim:] + + def index_range_condition(index_range): + i, lb, ub = index_range + return torch.logical_and(i >= lb, i <= ub) + + # Areas after reflection: + # + # top-left | top | top-right + # ----------------------------------------- + # left | center | right + # ----------------------------------------- + # bottom-left | bottom | bottom-right + # + # The center area is the original matrix. Other areas are reflections. + + center = [xyz[i] + padding_left[i] for i in range(dim)] + left_reflect = [padding_left[i] - xyz[i] for i in range(dim)] + right_reflect = [2 * dhw[i] + padding_left[i] - xyz[i] for i in range(dim)] + + # Accumulate gradients from different areas + # If some of the padding is negative, center load is not always valid + range_c = [ + (center[i], 0, dhw[i] + padding_left[i] + padding_right[i]) for i in range(dim) + ] + cond = functools.reduce( + aten.logical_and, [index_range_condition(range_c[i]) for i in range(dim)] + ) + grad = aten._unsafe_masked_index(grad_output, cond, b + center, 0.0) + + def accumulate(grad, out, index_ranges): + # If the upper bound is less than the lower bound, we can get rid of one accumulation. + # This happens when the padding size is zero. + for i in range(dim): + upper_less_than_lower = index_ranges[i][2] < index_ranges[i][1] + if isinstance(upper_less_than_lower, bool) and upper_less_than_lower: + return grad + + cond = functools.reduce( + aten.logical_and, + [index_range_condition(index_range) for index_range in index_ranges], + ) + g = aten._unsafe_masked_index(grad_output, cond, b + out, 0.0) + return grad + g + + for area in itertools.product(*[[-1, 0, 1] for _ in range(dim)]): + if area == tuple([0] * dim): + # center, this is already done. + continue + + outs = [] + index_ranges = [] + + for i in range(dim): + if area[i] == 0: + out = center[i] + index_range = range_c[i] + elif area[i] == -1: + out = left_reflect[i] + index_range = (xyz[i], 1, padding_left[i]) + elif area[i] == 1: + out = right_reflect[i] + index_range = (xyz[i], dhw[i] - padding_right[i], dhw[i] - 1) + + outs.append(out) # type: ignore[possibly-undefined] + index_ranges.append(index_range) # type: ignore[possibly-undefined] + + grad = accumulate(grad, outs, index_ranges) + + return grad + + +@register_decomposition(aten.aminmax) +@out_wrapper("min", "max", exact_dtype=True) +def aminmax(self, *, dim=None, keepdim=False): + # pyrefly: ignore [bad-argument-type] + amin = torch.amin(self, dim=dim, keepdim=keepdim) + # pyrefly: ignore [bad-argument-type] + amax = torch.amax(self, dim=dim, keepdim=keepdim) + return amin, amax + + +@register_decomposition(aten.nansum) +@out_wrapper() +def nansum(self, dim=None, keepdim=False, *, dtype=None): + return aten.sum(torch.where(torch.isnan(self), 0, self), dim, keepdim, dtype=dtype) + + +@register_decomposition([aten.arange.default, aten.arange.out]) +@out_wrapper() +def arange_default( + end: NumberType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: torch.device | None = None, + pin_memory: bool = False, +): + return aten.arange.start_step( + 0, end, 1, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_decomposition([aten.arange.start]) +def arange_start( + start: NumberType, + end: NumberType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: torch.device | None = None, + pin_memory: bool = False, +): + return aten.arange.start_step( + start, end, 1, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_decomposition(out_dtype) +def out_dtype_decomp(*args, **kwargs): + from torch._higher_order_ops.out_dtype import out_dtype_dense + + return out_dtype_dense(*args, **kwargs) + + +@register_decomposition(aten.multi_margin_loss) +@aten.multi_margin_loss.default.py_impl(DispatchKey.Autograd) +@out_wrapper() +def multi_margin_loss( + input: Tensor, + target: Tensor, + p: NumberType = 1, + margin: NumberType = 1, + weight: Tensor | None = None, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + input = torch.atleast_2d(input) + target = torch.atleast_1d(target) + nframe = input.shape[0] + dim = input.shape[1] + torch._check(p == 1 or p == 2, lambda: "only p == 1 and p == 2 supported") + torch._check( + input.ndim == 2 and dim != 0, + lambda: f"Expected non-empty vector or matrix with optional 0-dim batch size, but got: {input.shape}", + ) + torch._check( + target.ndim == 1 and target.numel() == nframe, + lambda: f"inconsistent target size, expected {nframe} but got {target.shape}", + ) + if weight is not None: + weight = torch.atleast_1d(weight) + torch._check( + weight.ndim == 1 and weight.numel() == dim, # type: ignore[union-attr] + lambda: f"inconsistent weight size, expected {dim} but got {weight.shape}", # type: ignore[union-attr] + ) + # Keep 1D target for weight indexing + target_1d = target + target = target.unsqueeze(1) + u = torch.gather(input, dim=1, index=target) + z = margin - u + input + z = z.clamp_min(0) + z = z if p == 1 else z * z + if weight is not None: + # Use 1D indexing to avoid issues with advanced indexing in inductor + z = z * weight[target_1d].unsqueeze(1) + idx = torch.arange(dim, device=input.device) + z = torch.where(idx != target, z, 0) + if reduction == Reduction.MEAN.value: + return z.mean() + elif reduction == Reduction.SUM.value: + return z.sum() / z.shape[1] + else: + return z.mean(dim=1) + + +@register_decomposition(aten.multilabel_margin_loss_forward) +@aten.multilabel_margin_loss_forward.default.py_impl(DispatchKey.Autograd) +@out_wrapper("output", "is_target") +def multilabel_margin_loss_forward( + input: Tensor, + target: Tensor, + reduction: int, +) -> tuple[Tensor, Tensor]: + orig_input_shape = input.shape + orig_target_shape = target.shape + input = torch.atleast_2d(input) + target = torch.atleast_2d(target) + dim = input.shape[1] + torch._check( + len(orig_input_shape) <= 2 and dim != 0, + lambda: f"Expected non-empty vector or matrix with optional 0-dim batch size, but got: {orig_input_shape}", + ) + torch._check( + len(orig_target_shape) <= 2 and orig_target_shape == orig_input_shape, + lambda: f"inconsistent target size: {orig_target_shape} for input of size: {orig_input_shape}", + ) + # ignores labels after the first -1, detects when -1 is not present + idx = torch.arange(dim, device=target.device) + is_end = target == -1 + end_idx = torch.amin(torch.where(is_end, idx, dim), dim=-1, keepdim=True) + # target indices + target_mask = idx < end_idx + # masks target to be able to use gather, which doesn't allow -1 + tidx0 = torch.where(target_mask, target, 0) + u = torch.gather(input, dim=-1, index=tidx0) + # is_target + tidx1 = torch.where(target_mask, target, -1) + is_target = torch.any(idx == tidx1.unsqueeze(dim=-1), dim=1) + # loss + z = 1.0 - u.T.unsqueeze(dim=-1) + input + z = z.clamp_min(0) + z = z / dim + # masks loss + z = torch.where(is_target, 0, z) + # drops contributions from padded target slots (positions at/after the first -1) + z = torch.where(target_mask.T.unsqueeze(dim=-1), z, 0) + # reduction + if reduction == Reduction.MEAN.value: + z = z.sum(dim=(0, -1)).mean() + elif reduction == Reduction.SUM.value: + z = z.sum() + else: + z = z.sum(dim=(0, -1)) + # result + is_target = is_target.to(input.dtype).reshape(orig_target_shape) + return z, is_target + + +# scaled_dot_product_attention used to be decomposed in pre-autograd, given that +# it calls _scaled_dot_product_attention_math and +# _scaled_dot_product_attention_math only has a CompositeImplicitAutograd +# kernel. As a result it's decomposed into ops with finer granularity. +# However recent PRs (#103826 #105131 #115913) added new logic in +# scaled_dot_product_attention and now it calls +# _scaled_dot_product_flash_attention_for_cpu in export path. This results +# in _scaled_dot_product_flash_attention_for_cpu showing up in export result. +# This decomposition ensures scaled_dot_product_attention is still decomposed +# the same way as before, i.e., going through +# _scaled_dot_product_attention_math. Notice that this decomp rule should be +# excluded by inductor. +@register_decomposition(aten._scaled_dot_product_flash_attention_for_cpu.default) +def scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: float = 0.0, + is_causal: bool = False, + *, + attn_mask: Tensor | None = None, + scale: float | None = None, +) -> tuple[Tensor, Tensor]: + torch._check( + torch.is_floating_point(query), + lambda: f"query must be FP32, FP64, BF16, FP16 but got {query.dtype}", + ) + torch._check( + query.dim() == 4 and key.dim() == 4 and value.dim() == 4, + lambda: f"q, k, v must be a 4 dimensional tensor, got {query.dim()}, {key.dim()}, {value.dim()}", + ) + torch._check( + dropout_p == 0.0, lambda: f"dropout probability must be zero, got {dropout_p}" + ) + torch._check( + query.shape[3] == value.shape[3] and key.shape[3] == value.shape[3], + lambda: "q, k, v should have the same head size", + ) + + output, attn = aten._scaled_dot_product_attention_math.default( + query, + key, + value, + attn_mask=attn_mask, + dropout_p=dropout_p, + is_causal=is_causal, + dropout_mask=None, + scale=scale, + enable_gqa=query.size(1) != key.size(1), + ) + # Why this change? + # In pre-dispatch export scaled_dot_product_attention is executed via + # * flash_attention. + # flash_attention allocates output tensor as (N, H, L, E) (see PR #134656) + # assume x: [N, H, L, E] is the output sdpa + # In MHA code, this output is then permuted via (2, 0, 1, 3) to get + # (L, N, H, E) dim tensor + # x = x.permute(2, 0, 1, 3).contiguous() and the viewed via + # x = x.view(L * N, H * E) + # During pre autograd dispatch call to contiguous is not traced because + # flash_attention output after the x.permute is already contiguous + # on which the view is valid + # However, during 2nd stage export, post-dispatch, we run _match variant + # instead of flash* to get the decomposition. _match variant returns + # x: [N, H, L, E] applying x.permute(2, 0, 1, 3) returns + # x: [L, N, H, E] and without converting this to contiguous tensor + # subsequent view is not valid and the export fails + # solution is to maintain the return tensor view from the decomp to be + # exactly same as *flash* variant. + + # Really the invariant you want to maintain is: + # pre-dispatch op-output and its decomposed representation must + # return tensor with same view and dims + output = ( + output.permute(2, 0, 1, 3) + .contiguous(memory_format=torch.contiguous_format) + .permute(1, 2, 0, 3) + ) + return output, attn + + +def register_inplace(aten_op, outplace_op): + @register_decomposition(aten_op) + def inplace_op(*args, **kwargs): + out = outplace_op(*args, **kwargs) + return args[0].copy_(out) + + return inplace_op + + +@register_decomposition([aten.baddbmm]) +@out_wrapper(exact_dtype=True) +@pw_cast_for_opmath +def baddbmm(self, batch1, batch2, beta=1, alpha=1): + if not self.is_floating_point() and not self.is_complex(): + beta = int(beta) + alpha = int(alpha) + result = torch.bmm(batch1, batch2) + if not isinstance(alpha, numbers.Number) or alpha != 1: + result = result * alpha + if beta == 0: + return result + if not isinstance(beta, numbers.Number) or beta != 1: + self = self * beta + return self + result + + +@register_decomposition(aten.floor_divide) +@out_wrapper() +def floor_divide(self, other): + return torch.div(self, other, rounding_mode="floor") + + +@register_decomposition(aten.sym_numel) +def sym_numel(t): + return functools.reduce(operator.mul, t.shape, 1) + + +@register_decomposition([aten.sum.default, aten.sum.out]) +def sum_default( + self: Tensor, + *, + dtype: torch.dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + if out is None: + return aten.sum.dim_IntList(self, [], dtype=dtype) + else: + return aten.sum.IntList_out(self, [], dtype=dtype, out=out) + + +@register_decomposition([aten.squeeze.default, aten.squeeze.dim]) +def squeeze_default(self: Tensor, dim: int | None = None): + # handle a scalar directly + if not isinstance(self, torch.Tensor): + return self + # perform squeeze + if dim is None: + return aten.squeeze.dims(self, list(range(self.dim()))) + else: + return aten.squeeze.dims(self, [dim]) + + +@register_decomposition(torch.ops.aten._weight_norm_interface) +def _weight_norm_interface(v, g, dim=0): + # https://github.com/pytorch/pytorch/blob/852f8526c52190125446adc9a6ecbcc28fb66182/aten/src/ATen/native/WeightNorm.cpp#L58 + keep_dim = tuple(i for i in range(len(v.shape)) if i != dim) + # align with cuda behavior, keep norm in 'float' when g is 'bfloat16' + norm_dtype = torch.float if g.dtype == torch.bfloat16 else None + norm = v.norm(2, keep_dim, keepdim=True, dtype=norm_dtype) + return v * (g / norm.to(g.dtype)), norm + + +@register_decomposition(aten.isin) +@out_wrapper() +def isin(elements, test_elements, *, assume_unique=False, invert=False): + # handle when either elements or test_elements are Scalars (they can't both be) + if not isinstance(elements, torch.Tensor): + elements = torch.scalar_tensor(elements, device=test_elements.device) + if not isinstance(test_elements, torch.Tensor): + if invert: + return torch.ne(elements, test_elements) + else: + return torch.eq(elements, test_elements) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(test_elements.numel() < 10.0 * pow(elements.numel(), 0.145)): + return isin_default(elements, test_elements, invert=invert) + else: + return isin_sorting( + elements, test_elements, assume_unique=assume_unique, invert=invert + ) + + +@register_decomposition(aten.bernoulli.default) +def bernoulli( + self: torch.Tensor, + *, + generator: torch.Generator | None = None, +) -> torch.Tensor: + if generator is None: + raw_p = torch.rand(self.size(), dtype=torch.float32, device=self.device) + else: + raw_p = torch.rand( + self.size(), + generator=generator, + dtype=torch.float32, + device=self.device, + ) + p = (raw_p < self).to(self.dtype) + return p + + +def isin_default(elements, test_elements, *, invert=False): + if elements.numel() == 0: + return torch.empty_like(elements, dtype=torch.bool) + if test_elements.ndim == 0: + res = elements == test_elements + return ~res if invert else res + expanded_elem_shape = elements.shape + (1,) * test_elements.ndim + x = elements.view(expanded_elem_shape) + dim = tuple(range(-1, -test_elements.ndim - 1, -1)) + res = (x == test_elements).any(dim=dim) + return ~res if invert else res + + +def isin_sorting(elements, test_elements, *, assume_unique=False, invert=False): + elements_flat = elements.flatten() + test_elements_flat = test_elements.flatten() + if assume_unique: + # This is the same as the aten implementation. For + # assume_unique=False, we cannot use unique() here, so we use a + # version with searchsorted instead. + all_elements = torch.cat([elements_flat, test_elements_flat]) + sorted_elements, sorted_order = torch.sort(all_elements, stable=True) + + duplicate_mask = sorted_elements[1:] == sorted_elements[:-1] + duplicate_mask = torch.constant_pad_nd(duplicate_mask, [0, 1], False) + + if invert: + duplicate_mask = duplicate_mask.logical_not() + + mask = torch.empty_like(duplicate_mask) + mask = mask.index_copy(0, sorted_order, duplicate_mask) + + return mask[0 : elements.numel()].reshape(elements.shape) + else: + sorted_test_elements, _ = torch.sort(test_elements_flat) + idx = torch.searchsorted(sorted_test_elements, elements_flat) + test_idx = torch.where(idx < sorted_test_elements.numel(), idx, 0) + cmp = sorted_test_elements[test_idx] == elements_flat + cmp = cmp.logical_not() if invert else cmp + return cmp.reshape(elements.shape) + + +@register_decomposition(aten.take) +@out_wrapper() +def take(self, index): + flattened = self.reshape(-1) + return flattened[index] + + +@register_decomposition(aten.resize_as) +def resize_as(self, other, memory_format=None): + if memory_format is None: + memory_format = torch.contiguous_format + if memory_format == torch.preserve_format: + memory_format = suggest_memory_format(other) + return aten.resize(self, other.shape, memory_format=memory_format) + + +@register_decomposition(aten.max_pool2d_with_indices_backward) +def max_pool2d_with_indices_backward( + grad_output: Tensor, + self: Tensor, + kernel_size, + stride, + padding, + dilation, + ceil_mode: bool, + indices: Tensor, +): + """ + Decomposition of max_pool2d_with_indices_backward using scatter_add. + + This replaces the native implementation with a high-level decomposition + that uses scatter_add for gradient accumulation. The scatter-based approach + provides automatic optimization opportunities for Inductor and handles all + pooling configurations without requiring specialized fallback paths. + + Algorithm: + For each output gradient position, use the corresponding index from the + forward pass to scatter the gradient to the input position. When multiple + output positions select the same input position as max, scatter_add + automatically accumulates their gradients. + + Complexity: O(B * C * H_out * W_out) + Independent of kernel size, unlike traditional O(B * C * H_in * W_in * K²) + approaches that iterate over input positions and kernel windows. + + Known Limitations: + - FP16/BF16: Uses FP32 accumulation internally to preserve precision when + many gradients accumulate to the same position (overlapping pooling windows). + This adds slight overhead but ensures numerical stability. + - Deterministic mode: Falls back to native implementation to ensure + consistent results across runs + + Args: + grad_output: Gradient w.r.t. pooling output [B, C, H_out, W_out] + self: Original input tensor (for shape) [B, C, H_in, W_in] + kernel_size: Pooling kernel size + stride: Pooling stride + padding: Pooling padding + dilation: Pooling dilation + ceil_mode: Whether to use ceil for output size calculation + indices: Indices from forward pass (per-channel linear positions) + + Returns: + Gradient w.r.t. input [B, C, H_in, W_in] + """ + # Use native kernel in deterministic mode + if torch.are_deterministic_algorithms_enabled(): + return NotImplemented + + if grad_output.is_xpu: + return NotImplemented + + # MPS: Use native kernel. scatter_add has correctness issues on macOS 14 + # (#163327) and numerical differences on macOS 15+. + if grad_output.device.type == "mps": + return NotImplemented + + # Get spatial dimensions + in_height = self.size(-2) + in_width = self.size(-1) + out_height = grad_output.size(-2) + out_width = grad_output.size(-1) + + # Handle both 3D (C, H, W) and 4D (B, C, H, W) cases by treating 3D as 4D + is_batched = self.dim() == 4 + if not is_batched: + self = self.unsqueeze(0) + grad_output = grad_output.unsqueeze(0) + indices = indices.unsqueeze(0) + + batch_size = self.size(0) + channels = self.size(1) + + # For FP16/BF16, use FP32 accumulation to avoid precision loss + # This is critical when many gradients accumulate to the same position + # (overlapping pooling windows with large kernels or stride < kernel_size) + use_fp32_accum = grad_output.dtype in (torch.float16, torch.bfloat16) + accum_dtype = torch.float32 if use_fp32_accum else grad_output.dtype + + # Create grad_input with correct accumulation dtype from the start + grad_input_flat = torch.zeros( + batch_size * channels, + in_height * in_width, + dtype=accum_dtype, + device=grad_output.device, + ) + + # Reshape grad_output and indices to (B*C, H_out*W_out) + grad_output_flat = grad_output.reshape( + batch_size * channels, out_height * out_width + ) + indices_flat = indices.reshape(batch_size * channels, out_height * out_width) + + # Convert grad_output to accumulation dtype if needed + if use_fp32_accum: + grad_output_flat = grad_output_flat.to(torch.float32) + + # Scatter gradients to input positions + grad_input_flat = grad_input_flat.scatter_add(1, indices_flat, grad_output_flat) + + # Reshape back to original input shape + grad_input = grad_input_flat.reshape(batch_size, channels, in_height, in_width) + + # Convert back to original dtype if we used FP32 accumulation + if use_fp32_accum: + grad_input = grad_input.to(grad_output.dtype) + + # Preserve memory format from input (channels_last vs channels_first) + memory_format = utils.suggest_memory_format(self) + grad_input = grad_input.contiguous(memory_format=memory_format) + + # Remove batch dimension for 3D case + if not is_batched: + grad_input = grad_input.squeeze(0) + + return grad_input + + +@register_decomposition([aten.hann_window.default, aten.hann_window.out]) +@out_wrapper() +def hann_window( + window_length: int, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: torch.device | None = None, + pin_memory: bool | None = None, +) -> Tensor: + """hann_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False) -> Tensor + + Returns a Hann window of size :attr:`window_length` with ``periodic=True``. + + Equivalent to :func:`torch.hann_window` with ``periodic=True``. + + Args: + window_length (int): the size of returned window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): desired dtype. Default: global default. + layout (:class:`torch.layout`, optional): desired layout. Default: ``torch.strided``. + device (:class:`torch.device`, optional): desired device. Default: current device. + pin_memory (bool, optional): if ``True``, pins the returned tensor. Default: ``False``. + """ + return aten.hann_window.periodic( + window_length, + True, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + ) + + +@register_decomposition([aten.hann_window.periodic, aten.hann_window.periodic_out]) +@out_wrapper() +def hann_window_periodic( + window_length: int, + periodic: bool = True, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: torch.device | None = None, + pin_memory: bool | None = None, +) -> Tensor: + r"""hann_window(window_length, periodic=True, *, dtype=None, layout=None, device=None, pin_memory=False) -> Tensor + + Returns a Hann window of size :attr:`window_length`. + + .. math:: + w[n] = 0.5 - 0.5 \cos\!\left(\frac{2\pi n}{N-1}\right) + + where :math:`N` is ``window_length + 1`` when ``periodic=True`` (for spectral analysis), + or ``window_length`` when ``periodic=False`` (symmetric window). + + Low-precision dtypes (``bfloat16``, ``float16``) are computed in ``float32`` then cast. + + Args: + window_length (int): the size of returned window. + periodic (bool, optional): if ``True``, returns a periodic window for use with STFT. + Default: ``True``. + + Keyword args: + dtype (:class:`torch.dtype`, optional): desired dtype. Default: global default. + layout (:class:`torch.layout`, optional): desired layout. Default: ``torch.strided``. + device (:class:`torch.device`, optional): desired device. Default: current device. + pin_memory (bool, optional): if ``True``, pins the returned tensor. Default: ``False``. + """ + dtype = dtype if dtype is not None else torch.get_default_dtype() + if window_length == 0: + return torch.empty( + (0,), dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + if window_length == 1: + return torch.ones( + (1,), dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + compute_dtype = utils.get_computation_dtype(dtype) + n = window_length + 1 if periodic else window_length + t = torch.arange( + n, + dtype=compute_dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + ) + t = t * (2.0 * torch.pi / (n - 1)) + t = torch.cos(t) + t = t * -0.5 + 0.5 + window = t.narrow(0, 0, window_length) if periodic else t + return window.to(dtype) + + +register_inplace(aten.addbmm_, aten.addbmm) +register_inplace(aten.addmm_, aten.addmm) +register_inplace(aten.addmv_, aten.addmv) +register_inplace(aten.baddbmm_, aten.baddbmm) +register_inplace(aten.fill_, aten.fill) +register_inplace(aten.gelu_, aten.gelu) +register_inplace(aten.hardswish_, aten.hardswish) +register_inplace(aten.hardtanh_, aten.hardtanh) +register_inplace(aten.hardsigmoid_, aten.hardsigmoid) +register_inplace(aten.__iand__, aten.__and__) +register_inplace(aten.__ilshift__, aten.__lshift__) +register_inplace(aten.index_put_, aten.index_put) +register_inplace(aten.index_reduce_, aten.index_reduce) +register_inplace(aten.__ior__, aten.__or__) +register_inplace(aten.__irshift__, aten.__rshift__) +register_inplace(aten.__ixor__, aten.__xor__) +register_inplace(aten.ldexp_, aten.ldexp) +register_inplace(aten.leaky_relu_, aten.leaky_relu) +register_inplace(aten.logit_, aten.logit) +register_inplace(aten.relu_, aten.relu) +register_inplace(aten.renorm_, aten.renorm) +register_inplace(aten.round_, aten.round) +register_inplace(aten.scatter_, aten.scatter) +register_inplace(aten.scatter_add_, aten.scatter_add) +register_inplace(aten.scatter_reduce_, aten.scatter_reduce) +register_inplace(aten.silu_, aten.silu) + + +@aten.one_hot.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def one_hot(self: Tensor, num_classes: int = -1) -> Tensor: + if num_classes == -1: + num_classes = int(self.max().item()) + 1 + # _assert_async is side-effectful and won't be DCE'd + aten._assert_async.msg( + torch.all(self >= 0), + "one_hot: Class values must be non-negative.", + ) + aten._assert_async.msg( + torch.all(self < num_classes), + "one_hot: Class values must be smaller than num_classes.", + ) + return ( + self.unsqueeze(-1) + == torch.arange(num_classes, dtype=self.dtype, device=self.device) + ).to(torch.int64) diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_jvp.py b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_jvp.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3d4ecb77e074ebe680cdcd099a1f700960a5b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_jvp.py @@ -0,0 +1,345 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import inspect +from collections.abc import Callable + +import torch +import torch._decomp +from torch import Tensor +from torch._prims_common.wrappers import _maybe_remove_out_wrapper + + +decomposition_table = torch._decomp.decomposition_table +decomposition_table_for_jvp: dict[torch._ops.OperatorBase, Callable] = {} +register_decomposition = torch._decomp.register_decomposition +aten = torch.ops.aten + +# NOTE: [forward-mode AD decompositions mechanism] +# +# The mechanism is in VariableType, +# IF any inputs have forward grad +# AND there is no forward AD formula implemented +# AND the functions are actually differentiable +# run the decomposition +# See run_jit_decomposition_with_args_for_jvp +# We currently use python decompositions that we torchscript. +# +# Note that we would be building the backward graph at the decomposed level +# too, but that is OK, because we would've errored out otherwise anyway. +# +# TODO: The mechanism we are using to register decompositions doesn't +# seem to be exclusively used for jvp. So open question here is whether +# torch/csrc/jit/runtime/decomposition_registry.cpp is being used for other things. +# If that is the case, we may go down the decomposition path unexpectedly +# (and possibly produce an unintelligible error) vs erroring out earlier and +# printing that the forward AD formula is not implemented. +# +# The solution to this may be to have an explicit whitelist to control when +# to enable the decomposition. + + +def maybe_register_decomposition(op): + def decorator(f): + try: + return register_decomposition(op)(f) + except Exception: + return f + + return decorator + + +# Functions where we need a special decomposition for jvp but there's another version that +# should be used more generally (ex. for jvp we need to recompute the mean and variance for +# the backwards of a normalization function. Without jvp, it should use the saved value) +decomposition_table_for_jvp = {} + + +def register_decomposition_for_jvp(fn): + return register_decomposition(fn, registry=decomposition_table_for_jvp) + + +def _register_jit_decomposition_for_jvp(decomp, use_python=False): + if decomp in decomposition_table_for_jvp: + decomposition_table_used = decomposition_table_for_jvp + elif decomp in decomposition_table: + decomposition_table_used = decomposition_table + else: + raise RuntimeError(f"could not find decomposition for {decomp}") + decomp_fn = decomposition_table_used[decomp] + + # `out_wrapper` extends a decompositions signature with + # an `out` parameter. However jit will use the unwrapped function's + # signature instead so we need to unwrap here to prevent an error + decomp_fn = _maybe_remove_out_wrapper(decomp_fn) + + if use_python: + decomp_fn = torch.jit.ignore(decomp_fn) + sig = inspect.signature(decomp_fn) + + # Create a string wrapping the function from the signature + # example output: + # def wrapped_decomp(x: torch.Tensor, y: int, z: int): + # return decomp_fn(x, y, z) + # Thanks copilot! + def get_function_def(sig): + param_def = [f"{param_str}" for param_str in sig.parameters.values()] + param_use = [f"{param_str}" for param_str in sig.parameters] + + return f"def wrapped_decomp({', '.join(param_def)}):\n return decomp_fn({', '.join(param_use)})\n" + + f_str = get_function_def(sig) + graph = torch.jit.CompilationUnit(f_str).wrapped_decomp.graph + else: + graph = torch.jit.script(decomp_fn).graph + torch.jit._register_decomposition(decomp, graph) + + +# The only decompositions here are temporary or hacks for the purposes of jvp + + +# TODO: do these also belong here? +@maybe_register_decomposition(aten.trace.default) +def trace(self: Tensor) -> Tensor: + return torch.sum(torch.diag(self)) + + +@maybe_register_decomposition(aten.log_sigmoid_forward.default) +def log_sigmoid_forward(self: Tensor) -> tuple[Tensor, Tensor]: + min = torch.minimum(self.new_zeros(()), self) + z = torch.exp(-torch.abs(self)) + if self.is_cuda or self.is_xpu: + buffer = self.new_zeros((0,)) + else: + buffer = z + return min - torch.log1p(z), buffer + + +def recompute_mean_var( + input: Tensor, rstd: Tensor, inner_dim_indices: list[int], keepdim: bool +): + # for most norm decompositions, it will be the same as the core version except for here. + # We recompute the mean and variance so that they track gradients through input + + var, mean = torch.var_mean( + input, dim=inner_dim_indices, correction=0, keepdim=keepdim + ) + eps = torch.pow(1 / rstd, 2) - var # this makes me so sad inside + eps = eps.detach() + rstd = torch.rsqrt(var + eps) + return mean, rstd + + +@register_decomposition_for_jvp(aten.native_layer_norm_backward) +def native_layer_norm_backward( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + mean: Tensor, + rstd: Tensor, + weight: Tensor | None, + bias: Tensor | None, + output_mask: list[bool], +) -> tuple[Tensor | None, Tensor | None, Tensor | None]: + input_shape = input.shape + input_ndim = input.dim() + + axis = input_ndim - len(normalized_shape) + inner_dims = input_shape[axis:] + outer_dims = input_shape[:axis] + inner_dim_indices = list(range(axis, input_ndim)) + outer_dim_indices = list(range(axis)) + + N = 1 + for i in inner_dims: + N *= i + M = 1 + for i in outer_dims: + M *= i + if M <= 0 or N <= 0: + return ( + input.new_zeros(input_shape), + input.new_zeros(input_shape[axis:]), + input.new_zeros(input_shape[axis:]), + ) + + mean_, rstd_ = recompute_mean_var(input, rstd, inner_dim_indices, keepdim=True) + + x_hat = (input - mean_) * rstd_ + if weight is not None: + grad_x_hat = grad_out * weight + else: + grad_x_hat = grad_out + a = grad_x_hat * N + b = torch.sum(grad_x_hat, inner_dim_indices, True) + c1 = torch.mul(grad_x_hat, x_hat) + c2 = torch.sum(c1, inner_dim_indices, True) + c3 = torch.mul(x_hat, c2) + inner = a - b - c3 + + if output_mask[0]: + d_input: Tensor | None = (rstd_ / N) * inner + else: + d_input = torch.zeros_like(input) # should be None but doesn't work with vjp + + if output_mask[1] and weight is not None: + if len(outer_dim_indices) > 0: + d_weight: Tensor | None = torch.sum( + grad_out * x_hat, outer_dim_indices, False + ) + else: + d_weight = grad_out * x_hat + elif weight is not None: + d_weight = torch.zeros_like(weight) # should be None but doesn't work with vjp + else: + d_weight = torch.zeros(()) # should be None but doesn't work with vjp + + if output_mask[2] and bias is not None: + if len(outer_dim_indices) > 0: + d_bias: Tensor | None = torch.sum(grad_out, outer_dim_indices, False) + else: + d_bias = grad_out.clone() + elif bias is not None: + d_bias = torch.zeros_like(bias) # should be None but doesn't work with vjp + else: + d_bias = torch.zeros(()) # should be None but doesn't work with vjp + + return (d_input, d_weight, d_bias) + + +def prod(x: list[int]): + r = 1 + for i in x: + r *= i + return r + + +@register_decomposition_for_jvp(aten.native_batch_norm_backward) +def native_batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_invstd: Tensor | None, + train: bool, + eps: float, + output_mask: list[bool], +) -> tuple[Tensor, Tensor | None, Tensor | None]: + input_shape = input.shape + input_rank = input.dim() + if input_rank < 2: + raise AssertionError(f"rank of the input must be at least 2, got {input_rank}") + + axis = 1 + num_features = prod(input_shape) / input_shape[axis] # type: ignore[arg-type] + mean = save_mean + invstd = save_invstd + if train: + if save_mean is None or save_invstd is None: + raise AssertionError( + "when train=True, save_mean and save_invstd are required" + ) + + reduciton_dims = [0] + list(range(2, input.dim())) + if invstd is None: + raise AssertionError("invstd must not be None for typing") + mean, invstd = recompute_mean_var(input, invstd, reduciton_dims, keepdim=False) + else: + if running_mean is None or running_var is None: + raise AssertionError( + "running_mean and running_var must not be None when train=False" + ) + mean = running_mean + invstd = torch.rsqrt(running_var + eps) + + if invstd is None or mean is None: + raise AssertionError( + f"invstd and mean must not be None, got invstd={invstd}, mean={mean}" + ) + + broadcast_mask = [1] * input_rank + broadcast_mask[axis] = input_shape[axis] + + reduction_axes: list[int] = [] + for i in range(input_rank): + if i != axis: + reduction_axes.append(i) + + mean = torch.reshape(mean, broadcast_mask) + norm = 1.0 / num_features + grad_output_sum = torch.sum(grad_out, reduction_axes) + dot_p = torch.sum(grad_out * (input - mean), reduction_axes) + + grad_mean = torch.reshape(grad_output_sum * norm, broadcast_mask) + proj_scale = torch.reshape(torch.mul(dot_p * norm, invstd * invstd), broadcast_mask) + + if weight is None: + grad_scale = torch.reshape(invstd, broadcast_mask) * 1.0 + else: + grad_scale = torch.reshape(invstd * weight, broadcast_mask) + + if train: + proj = (input - mean) * proj_scale + grad_input = ((grad_out - proj) - grad_mean) * grad_scale + else: + grad_input = grad_out * grad_scale + + if output_mask[1]: + grad_weight = dot_p * invstd + elif weight is not None: + grad_weight = torch.zeros_like( + weight + ) # should be None but doesn't work with vjp + else: + grad_weight = torch.zeros(()) # should be None but doesn't work with vjp + + if output_mask[2]: + grad_bias = grad_output_sum + else: + grad_bias = torch.zeros_like( + grad_output_sum + ) # should be None but doesn't work with vjp + + return (grad_input, grad_weight, grad_bias) + + +@register_decomposition_for_jvp(aten.batch_norm_backward) +def batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_var: Tensor | None, + update: bool, + eps: float, + output_mask: list[bool], + reserve: Tensor, +) -> tuple[Tensor, Tensor | None, Tensor | None]: + return native_batch_norm_backward( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_var, + update, + eps, + output_mask, + ) + + +_register_jit_decomposition_for_jvp(torch.ops.aten.trace.default, use_python=True) +_register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss2d_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten._log_softmax_backward_data.default) +_register_jit_decomposition_for_jvp(torch.ops.aten._softmax_backward_data.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.log_sigmoid_forward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.native_layer_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.native_batch_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.cudnn_batch_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.batch_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.miopen_batch_norm_backward.default) diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_rng.py b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_rng.py new file mode 100644 index 0000000000000000000000000000000000000000..bd2f189c8071a54d30ca3d366c818cd95ccecf9a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_rng.py @@ -0,0 +1,273 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import functools +from collections import defaultdict +from collections.abc import Callable + +import torch +import torch._decomp as decomp +from torch._decomp import get_decompositions +from torch._ops import OpOverload + + +aten = torch.ops.aten + +rng_decompositions: dict[str, dict[OpOverload, Callable]] = defaultdict(dict) + + +def register_rng_decomposition(aten_op): + return decomp.register_decomposition(aten_op, rng_decompositions) + + +def throw_on_non_cuda(device): + raise RuntimeError( + f"You are trying to functionalize a {device.type} RNG operator but {device.type} does not " + f"use Philox/counter-based RNG. Therefore, functionalizing a {device.type} RNG operator is " + "not supported. We are discussing the possibility of a Philox-based RNG implementation for CPU." + ) + + +# TODO - We have to register many more distributions here, and also higher level +# ops like dropout which have fused implementation and can hide the rand inside. +@register_rng_decomposition(aten.rand) +def rand(shape, dtype=None, layout=torch.strided, device=None, pin_memory=False): + if device and device.type != "cuda": + throw_on_non_cuda(device) + seed, offset = PhiloxStateTracker.get_state_as_tuple() + dtype = dtype or torch.float32 + out, offset_jump = torch.ops.rngprims.philox_rand( + shape, seed, offset, None, device, dtype + ) + PhiloxStateTracker.advance_offset(offset_jump) + return out + + +@register_rng_decomposition(aten.rand_like) +def rand_like( + x: torch.Tensor, + dtype=None, + layout=None, + device=None, + pin_memory=False, + memory_format=torch.preserve_format, +): + device = device or x.device + if device.type != "cuda": + throw_on_non_cuda(device) + dtype = dtype or x.dtype + seed, offset = PhiloxStateTracker.get_state_as_tuple() + out, offset_jump = torch.ops.rngprims.philox_rand( + x.shape, seed, offset, None, device, dtype + ) + PhiloxStateTracker.advance_offset(offset_jump) + return out + + +class PhiloxState: + """ + Represents a PhiloxRngState - (seed, offset) where offset = base_offset + + relative_offset. seed and base_offset basically point to the rng state just + before tracing starts. relative offset tracks the totally consumed offset at + trace time. + """ + + def __init__(self) -> None: + self.reset() + + def reset(self): + self.seed = torch.tensor(()) + self.base_offset = torch.tensor(()) + self.relative_offset = 0 + self.offset_advanced_at_least_once = False + + def validate_state(self): + if self.seed.numel() == 0 or self.base_offset.numel() == 0: + raise AssertionError( + f"seed and base_offset must not be empty, got " + f"seed.numel()={self.seed.numel()}, base_offset.numel()={self.base_offset.numel()}" + ) + + def advance_offset(self, consumed_offset): + self.offset_advanced_at_least_once = True + self.relative_offset = self.relative_offset + consumed_offset + + def set_state(self, seed, base_offset, relative_offset=0): + self.seed = seed + self.base_offset = base_offset + self.relative_offset = relative_offset + + def get_state_as_tuple(self): + self.validate_state() + return (self.seed, self.base_offset + self.relative_offset) + + def get_state_as_tensor(self): + # Only needed because we override get_rng_state. + self.validate_state() + return torch.stack([self.seed, self.base_offset + self.relative_offset]) + + def set_state_from_tensor(self, state): + # Only needed because we override set_rng_state. + self.seed, self.base_offset = torch.unbind(state) + self.relative_offset = 0 + + +class PhiloxStateTracker: + """ + Singleton class to track the philox rng state during AOT Autograd tracing. + For each aot tracing instance, AOT Autograd resets this tracker and keeps + track of both forward and backward offsets. At runtime, we only care about + the total consumed forward and backward offsets. For dynamic shapes, these + offsets are a function of input shapes. Therefore, the AOT generated graphs + have additional outputs that compute total consumed forward and backward + offsets. + """ + + running_state: PhiloxState + fwd_state: PhiloxState + bwd_state: PhiloxState + + def __enter__(self): + PhiloxStateTracker.reset() + return self + + def __exit__(self, exc_type, exc_cal, exc_tb): + PhiloxStateTracker.reset() + + @classmethod + def reset(cls): + cls.running_state = PhiloxState() + cls.fwd_state = PhiloxState() + cls.bwd_state = PhiloxState() + + @classmethod + def mark_beginning_of_forward(cls): + # Tells the tracker to use fwd_state as the running state + cls.running_state = cls.fwd_state + + @classmethod + def mark_beginning_of_backward(cls): + # Tells the tracker to use bwd_state as the running state + cls.running_state = cls.bwd_state + + @classmethod + def record_state(cls, seed, offset, mode): + # Records the seed and offset tensors. These tensors are used to invoke + # the philox_rand functional primitives. + if mode == "forward": + cls.fwd_state.set_state(seed, offset) + cls.mark_beginning_of_forward() + else: + if mode != "backward": + raise AssertionError(f"mode must be 'backward', got {mode}") + cls.bwd_state.set_state(seed, offset) + + @classmethod + def get_state_as_tensor(cls): + # The only reason this exists is because we override get_rng_state and + # set_rng_state during tracing. get_rng_state expects a tensor output, + # so return (seed, offset) tuple upset other parts of the program like + # ctx.saved_tensors. + + # A bad consequence is that if user saves and restores rng state, we + # have little bit of ugliness in the generated code, where we first + # concat the (seed, offset) to create a tensor for get_rng_state, and + # then split it back to get (seed, offset) tuple in set_rng_state. + + # TODO: Investigate if there is a better way to wrap the tuple in a + # false Tensor object, and then desugar it later on. + return cls.running_state.get_state_as_tensor() + + @classmethod + def get_state_as_tuple(cls): + return cls.running_state.get_state_as_tuple() + + @classmethod + def set_state_from_tensor(cls, x): + # This is only needed because we override set_rng_state. Look at the + # comment in get_state_from_tensor method. + cls.running_state.set_state_from_tensor(x) + + @classmethod + def advance_offset(cls, consumed_offset): + cls.running_state.advance_offset(consumed_offset) + + @classmethod + def get_current_relative_offset(cls): + return cls.running_state.relative_offset + + @staticmethod + def multiple_of_4(offset): + # torch cuda rng state offset must be a multiple of 4. For inductor, as + # we sum up all the numel, the result might not be a multiple of 4. This + # method achieves that. + return (offset + 3) // 4 * 4 + + @classmethod + def get_updated_fwd_offset(cls): + # Short circuit if no rand ops were observed + if not cls.fwd_state.offset_advanced_at_least_once: + return cls.fwd_state.base_offset + return cls.multiple_of_4( + cls.fwd_state.base_offset + cls.fwd_state.relative_offset + ) + + @classmethod + def get_updated_bwd_offset(cls): + # Short circuit if no rand ops were observed + if not cls.bwd_state.offset_advanced_at_least_once: + return cls.bwd_state.base_offset + return cls.multiple_of_4( + cls.bwd_state.base_offset + cls.bwd_state.relative_offset + ) + + +# Adding more decompositions which eventually use rand_like inside decomps. +# Adding these in rng_decompositions ensures the functionalization of rand_like +# ops used in these decomps. The list is copied from inductor codebase, which +# uses it for similar purpose. +# +# Caution - These decomps do not have same accuracy as that of eager. However, +# we can't just disable them with a config flag like fallback_random, because +# for functionalization of rng ops, we have to decompose these ops. +extra_random_decomps = get_decompositions( + [ + aten.cauchy, + aten.cauchy_, + aten.exponential, + aten.exponential_, + aten.geometric, + aten.geometric_, + aten.native_dropout, + aten.normal, + aten.normal_, + aten.normal_functional, + aten.log_normal, + aten.log_normal_, + aten.rrelu_with_noise, + aten.rrelu_with_noise_, + aten.uniform, + aten.uniform_, + ] +) +register_extra_random_decomp = functools.partial( + decomp.register_decomposition, registry=extra_random_decomps +) + + +@register_extra_random_decomp([aten.bernoulli_]) +def bernoulli_(self, p=0.5): + if self.device == torch.device("cpu"): + return NotImplemented + return self.copy_(torch.rand_like(self, dtype=torch.float32) < p) + + +@register_extra_random_decomp([aten.bernoulli.p]) +def bernoulli_p(self, p=0.5, *, generator=None): + if self.device == torch.device("cpu"): + return NotImplemented + if generator is not None: + raise AssertionError(f"generator must be None, got {generator}") + return torch.rand_like(self, dtype=torch.float32) < p + + +rng_decompositions.update(extra_random_decomps) # type: ignore[arg-type] diff --git a/.venv/lib/python3.12/site-packages/torch/_dispatch/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dispatch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0df6213e3d2324fa6cede1a74750055e16dd9f5b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/python.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49df8b5482667c6f53c22876df52fb51fdb2ef06 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/python.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dispatch/python.py b/.venv/lib/python3.12/site-packages/torch/_dispatch/python.py new file mode 100644 index 0000000000000000000000000000000000000000..ef6d1d652bf2da3b966945c01770b7743e366a7f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dispatch/python.py @@ -0,0 +1,204 @@ +import itertools +import unittest.mock +from collections.abc import Callable, Generator, Iterator +from contextlib import contextmanager +from typing import TypeVar +from typing_extensions import ParamSpec + +import torch +import torch._C +import torch._ops +import torch.utils._python_dispatch +import torch.utils._pytree as pytree +from torch._C import DispatchKey + + +__all__ = ["enable_python_dispatcher", "no_python_dispatcher", "enable_pre_dispatch"] + +no_python_dispatcher = torch._C._DisablePythonDispatcher +enable_python_dispatcher = torch._C._EnablePythonDispatcher +enable_pre_dispatch = torch._C._EnablePreDispatch + +CROSSREF_FUNCTIONALIZE = False + +_P = ParamSpec("_P") +_T = TypeVar("_T") +_R = TypeVar("_R") + + +def all_py_loaded_overloads() -> Iterator[torch._ops.OpOverload]: + """ + Warning: the set of overloads this will report is very subtle. It is precisely + the set of torch.ops functions that have actually been accessed from Python + (e.g., we actually called torch.ops.aten.blah at some point. This is DIFFERENT + from the set of registered operators, which will in general be a larger set, + as this would include all operators which we ran C++ static initializers or + Python operator registration on. This does not eagerly populate the list on + torch.ops.aten; this list is lazy! + + In other words, this is good for traversing over everything that has an + OpOverload object allocated in Python. We use it for cache invalidation, but + don't rely on this list being complete. + + Note that even if we did report all C++ registered overloads, this isn't guaranteed + to be complete either, as a subsequent lazy load of a library which triggers more + registrations could add more things to the set. + """ + for ns in torch.ops: + packets = getattr(torch.ops, ns) + for op_name in packets: + packet = getattr(packets, op_name) + for overload in packet: + yield getattr(packet, overload) + + +@contextmanager +def suspend_functionalization() -> Generator[None, None, None]: + f_tls = torch._C._dispatch_tls_is_dispatch_key_included( + torch._C.DispatchKey.Functionalize + ) + f_rv = torch._C._functionalization_reapply_views_tls() + if f_tls: + torch._disable_functionalization() + try: + yield + finally: + if f_tls: + torch._enable_functionalization(reapply_views=f_rv) + + +def check_tensor_metadata_matches( + nv: torch.Tensor, rv: torch.Tensor, desc: Callable[[], str] +) -> None: + if not callable(desc): + raise AssertionError(f"desc must be callable, got {type(desc)}") + if nv.size() != rv.size(): + raise AssertionError(f"{desc()}: sizes {nv.size()} != {rv.size()}") + if nv.dtype != rv.dtype: + raise AssertionError(f"{desc()}: dtype {nv.dtype} != {rv.dtype}") + same_strides, idx = torch._prims_common.check_significant_strides( + nv, rv, only_cuda=False + ) + if not same_strides: + raise AssertionError( + f"{desc()}: strides {nv.stride()} != {rv.stride()} (mismatch at index {idx})" + ) + + +def check_metadata_matches(n: object, r: object, desc: Callable[[], str]) -> None: + if not callable(desc): + raise AssertionError(f"desc must be callable, got {type(desc)}") + n_vals, _n_spec = pytree.tree_flatten(n) + r_vals, _r_spec = pytree.tree_flatten(r) + # TODO: test the specs match; empirically sometimes we have a tuple + # on one side and a list on the other + if len(n_vals) != len(r_vals): + raise AssertionError(f"{len(n_vals)} != {len(r_vals)}") + for i, nv, rv in zip(range(len(n_vals)), n_vals, r_vals): + if not isinstance(rv, torch.Tensor): + continue + check_tensor_metadata_matches(nv, rv, lambda: f"{desc()} output {i}") + + +class Lit: + def __init__(self, s: str) -> None: + self.s = s + + def __repr__(self) -> str: + return self.s + + +def _fmt(a: object) -> object: + if isinstance(a, torch.Tensor): + return Lit( + f"torch.empty_strided({tuple(a.size())}, {a.stride()}, dtype={a.dtype})" + ) + else: + return a + + +def make_crossref_functionalize( + op: torch._ops.OpOverload[_P, _T], final_key: DispatchKey +) -> Callable[_P, _T] | DispatchKey: + from torch._subclasses.fake_tensor import FakeTensorMode + + # This case is pretty weird, suppress it for now + if op is torch.ops.aten.lift_fresh.default: + return final_key + + def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T: + fake_mode = FakeTensorMode() + + def fakeify_defun(t: _R) -> _R | torch._subclasses.fake_tensor.FakeTensor: + if isinstance(t, torch.Tensor): + if torch._is_functional_tensor(t): + r = torch._from_functional_tensor(t) + # NB: This assumes that the inner tensor sizes/strides match + # the outer tensor sizes/strides. This doesn't necessarily have to + # be the case, see discussion at + # https://github.com/pytorch/pytorch/pull/87610/files/401ddeda1d769bedc88a12de332c7357b60e51a4#r1007264456 + if t.size() != r.size(): + raise AssertionError(f"size mismatch: {t.size()} != {r.size()}") + if t.stride() != r.stride(): + raise AssertionError( + f"stride mismatch: {t.stride()} != {r.stride()}" + ) + else: + r = t + # TODO: suppress guards + return fake_mode.from_tensor(r) + return t + + def maybe_detach(t: _R) -> _R | torch.Tensor: + if isinstance(t, torch.Tensor): + return t.detach() + else: + return t + + # TODO: This probably does the wrong thing if you're running other + # substantive modes with the normal op outside here + with ( + torch.utils._python_dispatch._disable_current_modes(), + suspend_functionalization(), + ): + f_args, f_kwargs = pytree.tree_map(fakeify_defun, (args, kwargs)) + orig_f_args, orig_f_kwargs = pytree.tree_map( + maybe_detach, (f_args, f_kwargs) + ) + with fake_mode: + f_r = op(*f_args, **f_kwargs) # pyrefly: ignore [invalid-param-spec] + r = op._op_dk(final_key, *args, **kwargs) + + def desc() -> str: + fmt_args = ", ".join( + itertools.chain( + (repr(pytree.tree_map(_fmt, a)) for a in orig_f_args), + ( + f"{k}={pytree.tree_map(_fmt, v)}" + for k, v in orig_f_kwargs.items() + ), + ) + ) + return f"{op}({fmt_args})" + + check_metadata_matches(f_r, r, desc) + return r + + return handler + + +# NB: enabling this is slow, don't do it in a hot loop. This is purely +# for debugging purposes. +@contextmanager +def enable_crossref_functionalize() -> Generator[None, None, None]: + for op in all_py_loaded_overloads(): + op._uncache_dispatch(torch._C.DispatchKey.Functionalize) + try: + with ( + enable_python_dispatcher(), + unittest.mock.patch("torch._dispatch.python.CROSSREF_FUNCTIONALIZE", True), + ): + yield + finally: + for op in all_py_loaded_overloads(): + op._uncache_dispatch(torch._C.DispatchKey.Functionalize) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b78f3361a3334fc694689c5416d60091c99c9e83 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__init__.py @@ -0,0 +1,248 @@ +""" +TorchDynamo is a Python-level JIT compiler designed to make unmodified PyTorch programs faster. +TorchDynamo hooks into the frame evaluation API in CPython (PEP 523) to dynamically modify Python +bytecode right before it is executed. It rewrites Python bytecode in order to extract sequences of +PyTorch operations into an FX Graph which is then just-in-time compiled with a customizable backend. +It creates this FX Graph through bytecode analysis and is designed to mix Python execution with +compiled backends to get the best of both worlds: usability and performance. This allows it to +seamlessly optimize PyTorch programs, including those using modern Python features. +""" + +import torch + +from . import ( + aot_compile, + bytecode_debugger, + config, + convert_frame, + eval_frame, + functional_export, + resume_execution, +) +from .backends.registry import list_backends, lookup_backend, register_backend +from .callback import callback_handler, on_compile_end, on_compile_start +from .code_context import code_context +from .convert_frame import replay +from .decorators import ( + allow_c_slot, + allow_in_graph, + assume_constant_result, + disable, + disable_nested_graph_breaks, + disallow_in_graph, + dont_skip_tracing, + error_on_graph_break, + forbid_in_graph, + graph_break, + is_dynamo_disable_recursive, + mark_dynamic, + mark_static, + mark_static_address, + maybe_mark_dynamic, + nonstrict_trace, + override_cudagraphs, + override_optimization_hint, + patch_dynamo_config, + run, + set_stance, + skip_frame, + step_unsupported, + substitute_in_graph, +) +from .eval_frame import ( + _reset_guarded_backend_cache, + explain, + export, + is_dynamo_supported, + is_inductor_supported, + optimize, + optimize_assert, + OptimizedModule, + reset_code, +) + +# pyrefly: ignore [deprecated] +from .external_utils import is_compiling +from .mutation_guard import GenerationTracker +from .pgo import reset_code_state +from .symbolic_convert import TensorifyState +from .utils import ( + graph_break_reasons, + guard_failures, + orig_code_map, + register_hook_for_recompile_user_context, + reset_frame_count, + reset_recompile_user_contexts, +) + + +# Register polyfill functions +from .polyfills import loader as _ # usort: skip + + +__all__ = [ + "allow_c_slot", + "allow_in_graph", + "assume_constant_result", + "bytecode_debugger", + "config", + "disable", + "disable_nested_graph_breaks", + "disallow_in_graph", + "dont_skip_tracing", + "export", + "explain", + "forbid_in_graph", + "graph_break", + "is_compiling", + "is_dynamo_disable_recursive", + "list_backends", + "lookup_backend", + "mark_dynamic", + "maybe_mark_dynamic", + "mark_static", + "mark_static_address", + "nonstrict_trace", + "override_optimization_hint", + "optimize", + "optimize_assert", + "OptimizedModule", + "patch_dynamo_config", + "register_backend", + "replay", + "reset", + "reset_recompile_user_contexts", + "run", + "override_cudagraphs", + "error_on_graph_break", + "set_recursion_limit", + "set_stance", + "skip_frame", + "step_unsupported", + "substitute_in_graph", +] + +# allowlist this for weights_only load of NJTs +torch.serialization.add_safe_globals([torch._dynamo.decorators._DimRange]) + +if torch.manual_seed is torch.random.manual_seed: + import torch.jit._builtins + + # Wrap manual_seed with the disable decorator. + # Can't do it at its implementation due to dependency issues. + torch.manual_seed = torch._disable_dynamo(torch.manual_seed) + # Add the new manual_seed to the builtin registry. + torch.jit._builtins._register_builtin(torch.manual_seed, "aten::manual_seed") + + +def reset() -> None: + """ + Clear all compile caches and restore initial state. This function is intended + to reset Dynamo's state *as if* you had started a fresh process invocation, which + makes it good for testing scenarios where you want to behave as if you started + a new process. It does NOT affect any file system caches. + + NB: this does NOT reset logging state. Don't use this to test logging + initialization/reinitialization. + """ + # TODO: https://github.com/pytorch/pytorch/issues/139200 + import logging + + log = logging.getLogger(__name__) + log.info("torch._dynamo.reset") + with convert_frame.compile_lock: + reset_code_caches() + convert_frame.input_codes.clear() + reset_code_state() + convert_frame.output_codes.clear() + orig_code_map.clear() + guard_failures.clear() + graph_break_reasons.clear() + resume_execution.ContinueExecutionCache.cache.clear() + _reset_guarded_backend_cache() + reset_frame_count() + torch._dynamo.compiled_autograd.reset() + convert_frame.FRAME_COUNTER = 0 + convert_frame.FRAME_COMPILE_COUNTER.clear() + callback_handler.clear() + GenerationTracker.clear() + TensorifyState.clear() + torch._dynamo.utils.warn_once_cache.clear() + torch._C._autograd._saved_tensors_hooks_set_tracing(False) + + # Reset cudagraph trees unconditionally since they are global state + # not tied to a specific backend instance + from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table + from torch._higher_order_ops.wrap import inductor_code_side_table + + kernel_side_table.reset_table() + inductor_code_side_table.reset_table() + + # The fake tensor dispatch cache is process-global (shared across + # FakeTensorMode instances), so it survives into later compiles. That + # is normally fine since it caches pure metadata propagation, but if a + # meta kernel errantly mutates input metadata (a bug, e.g. #191283), + # the mutation happens only on cache miss: a compile that failed cold + # can then "succeed" when retried in the same process, which test + # harness reruns misclassify as flakiness. + from torch._subclasses.fake_tensor import FakeTensorMode + + FakeTensorMode.cache_clear() + + if torch.cuda.is_initialized(): + from torch._inductor.cudagraph_trees import reset_cudagraph_trees + + reset_cudagraph_trees() + + +def reset_code_caches() -> None: + """ + Clears in-memory code cache, which is what stores compiled products. This + resets less state than :func:`reset` and is mostly only used for testing + purposes. + """ + # TODO: https://github.com/pytorch/pytorch/issues/139200 + import logging + + log = logging.getLogger(__name__) + log.info("torch._dynamo.reset_code_caches") + """Clear compile caches that are keyed by code objects""" + with convert_frame.compile_lock: + reset_code_state() + for weak_code in ( + convert_frame.input_codes.seen + convert_frame.output_codes.seen + ): + code = weak_code() + if code: + reset_code(code) + code_context.clear() + + +def get_recursion_limit() -> int: + """ + Returns the internal dynamo recursion limit set by `torch._dynamo.set_recursion_limit`. + + Returns -1 if no c recursion limit has been set. + """ + return torch._C._dynamo.eval_frame.get_c_recursion_limit() + + +def set_recursion_limit(limit: int) -> None: + """ + Sets an internal dynamo recursion limit. The limit must be >= 1, or -1 to reset + to the default (unset) state. + + This is possibly needed in Python 3.12-3.13 since there is a separate C recursion limit + that is not visible at the Python level. If you are getting RecursionErrors during + Dynamo compilation and `sys.setrecursionlimit()` doesn't help, this function may alleviate + the issue. + + NOTE: this function does NOT call `sys.setrecursionlimit()` - the user is expected to manually + call this if required. This is because the 2 recursion limits are not sync'd up - e.g. in + Python 3.12, functions can be inline-evaluated, which apparently doesn't use up the C stack. + + WARNING: increasing the recursion limit to an arbitrary large value may cause segfaults + due to stack overflows! You can try also try to manually increase the stack size, e.g. + with `$ ulimit -s ...` + """ + torch._C._dynamo.eval_frame.set_c_recursion_limit(limit) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e4c83eb6bf1909e3fdb3fdaf325d2e3ef4382ca Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/_trace_wrapped_higher_order_op.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/_trace_wrapped_higher_order_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ac6b9d6b54e42103de84df6c529169d5f71f579 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/_trace_wrapped_higher_order_op.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74571126f1f0f52c876d380f0215dd4ba16a09a5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile_types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9004e431117b14c9124dcd77d452ffd560f52e00 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile_types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e245842b99c498e543c5dc1e6071032cc4424cf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_debugger.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_debugger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..065fa38192de856086d38a0d414f9f90a4d6d65e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_debugger.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_transformation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_transformation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..434328b5bd6746c38fd2e9f1d4c0770f29b78c71 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_transformation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/cache_size.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/cache_size.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d5dfb05d21b49499f429d6b986596c03c0dda77 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/cache_size.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/callback.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/callback.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecf433344d3c4dc93d22863243f8170b8ab4599d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/callback.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/code_context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/code_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15ff7f90f99b45c66dd1ef50caaa09255e4df7e8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/code_context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..145f6b30b1c10e870e3eb578021d9df8e8d77c73 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/compiled_autograd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/compiled_autograd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94d64ed19edd7bf954488ed8da4a6befc7b260be Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/compiled_autograd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comprehension_graph_break.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comprehension_graph_break.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c3cbcef6117a0c48ecd4d3522664d3a8f9943d3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comprehension_graph_break.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comptime.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comptime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9230ca80e731596878dda5790ef91c5a167f285 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comptime.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b284c17128478c1bf5224b120a1166faae5c5b5b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/convert_frame.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/convert_frame.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a54890b77b634f0aa0a9f3e5b34d9ff3308b6134 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/convert_frame.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f13294cca599c924873fb74f40c0efad223b6513096f07a1e9057f250764c8ed +size 107944 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/create_parameter_op.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/create_parameter_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b6550216a90f92a02e23f3af14ce5e39fd6820f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/create_parameter_op.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/current_scope_id.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/current_scope_id.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9f463ea2f3a611f6a9a8fd7f87c6e1b5732b061 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/current_scope_id.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dce_extra_outputs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dce_extra_outputs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..082e00e253854cc2f8c16f87063b19419c1e37d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dce_extra_outputs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/debug_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/debug_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ff6979fb99eef8b5941961ce63baa908c501529 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/debug_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/decorators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/decorators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69f02ad8412d0bfb86d8061094bd3112973ac6d2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/decorators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/device_interface.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/device_interface.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49c18f8a2ab24f98fd659b358a75a4d83eb4bb27 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/device_interface.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/distributed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/distributed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..644ca48ee8f61bb9721568fd899e2ca9f518bb6b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/distributed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dynamo_profiler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dynamo_profiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd86f241b5d7700a94e590df1c3992099da73b32 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dynamo_profiler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/eval_frame.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/eval_frame.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..788eaedec379d71bd12e27bde3ea52fdf557edc6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/eval_frame.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:780fe33841e8adc2efe5e6aaafce34c737dc5d9734a362221bf05b2179a38b48 +size 117609 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/exc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/exc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f746e0f7095763a99fb0fd4c9c28a23afe60c6a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/exc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/external_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/external_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5224638802d6496a5b576141302159c318fd330 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/external_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/funcname_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/funcname_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02fbf761185b450fb9e8fc6cfb90d0227f28b49e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/funcname_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/functional_export.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/functional_export.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f69b11927bad6aed0df45b9c4dafb747f25ffe3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/functional_export.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_break_hints.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_break_hints.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29364cd09c079e892e2f4bcd5a798440f08540a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_break_hints.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_bytecode_inputs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_bytecode_inputs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..badd6c07f1faf9c26b92c74e10246aa0b03527d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_bytecode_inputs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_deduplication.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_deduplication.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c0a01243bfe06a012f08c1c7aaa37c35d857ace Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_deduplication.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_id_filter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_id_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8b0c10a60d4eeb504296c647982f1629b2a7f28 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_id_filter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_region_tracker.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_region_tracker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..755491c0e98f148ab06b5ffaa30df98660e21d54 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_region_tracker.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9485bd1c1361c782783de6b4304f40c9b8b8924 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/guards.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/guards.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53fd2e8fb28b73d239253213152d204cd6873109 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/guards.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c156a0208730d2502ddd33a68c8a945e11fd20bfd6562558c026d8bcf66fe4d8 +size 231994 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/hooks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/hooks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..febd15378d598566e206cee8ed34aeb0ddbcc07c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/hooks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/logging.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/logging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2442e19402babfb525d289ee48e115b1076a6075 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/logging.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/metrics_context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/metrics_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b50d1d575436f98c62184beb3dfa257b7a61045c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/metrics_context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/mutation_guard.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/mutation_guard.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ea2181a21feb15e3d4e823d550db164c8cec379 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/mutation_guard.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/output_graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/output_graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51e453ccfd251a8a5dbecad60f0129431439a2ac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/output_graph.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b319ca877d70fcb91dca8172d5b37319a8367fe4daf24ecd6e5b6fa49c083f36 +size 197649 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/package.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/package.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdd8556e8ffd0611d54af2be38fffa88ec1bbe8e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/package.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/pgo.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/pgo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a8436bab6513939b38dda4397b86b2dd641d578 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/pgo.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/precompile_context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/precompile_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95723f88c948d8972814dc01ac402932fd4f4dc5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/precompile_context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/profiler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/profiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca56ae625c47c3ebe92fe09a17bb5067a7e2fa9f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/profiler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/replay_record.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/replay_record.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e1111ad61e541c48be2f1cad0ff150692ffd27e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/replay_record.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/resume_execution.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/resume_execution.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f33de6c3bcaec454d5f1270b6754d4c8aa47f102 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/resume_execution.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/side_effects.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/side_effects.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbd6dde8d0f19921f1bef980266d992969b867ca Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/side_effects.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/source.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b435308024508964f27c8869ac4a3881abd9f05 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/source.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43a1e09e2c90ea356cc89cbbbed48ccbc5e03172 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55b5f8811040d6de5cfebb1cbc549beef5bddc045900031ec2379f0af07214a9 +size 275231 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/tensor_version_op.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/tensor_version_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa7357afa997bf7dea436868cb5a49e14e18eb59 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/tensor_version_op.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_case.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_case.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..490dd221c0905dcae2325218cc239514612aec5a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_case.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_dont_skip_tracing_functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_dont_skip_tracing_functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..309d201c789cdd238a37d547068f47af430f336d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_dont_skip_tracing_functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_minifier_common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_minifier_common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3dd32cd5e6ce7b46468f9dc5839b22ffecbc7c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_minifier_common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/testing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/testing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad09dce3d8a885d3a9b89cd78a4ed282c4686cc9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/testing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c4a487d32b2cc7aebd6a1c264325db677ba6c19 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52cb06863669e3b0875b16d4deab3118b3f70a0bb90d1a901fcbb1ec157e5264 +size 135986 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..639e3d307000f3f991e48fd6e9bd3dd05fc8d7d7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3edc45911c81d2b0dc4e32c9dada201218691100 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/utils.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79cd173ba5bf24936e876d554394374a63bfc9f057b45930c091f863bea43542 +size 259838 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py new file mode 100644 index 0000000000000000000000000000000000000000..4f9d1d370ecbc0802432e5f19246e05f7e9fc678 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py @@ -0,0 +1,287 @@ +"""trace_wrapped(*args, fn) is equivalent to fn(*args), but with a twist: +if you make_fx trace through this call, we will not actually trace into fn; instead, +we will directly insert it as a call_function to fn in the graph. +(Unlike make_fx, Dynamo WILL inline into fn.) +You can think of this as a one off allow_in_graph equivalent for proxy tensor tracing. + +Because proxy tensor tracing does not actually run the function, there are +requirements on the behavior of fn. We are still figuring it out, but here is the current state: + +1) fn SHOULD only take a single argument, which must be a tensor +2) fn MUST return a new tensor with the same metadata as the original tensor + (e.g., zeros_like(input) is a permissible implementation of fn). + This is verified via an extra assert that is inserted into the traced graph. +3) fn MAY have side effects, but it MAY NOT perform metadata mutation on other tensors + participating in proxy tensor tracing (it MAY mutate other tensors, it MAY mutate Python state) +These requirements stem from the requirement that we need to continue performing proxy tensor tracing, +which assumes accurate fake tensor metadata, without actually running fn. +In the future, we may allow for a "meta" function associated with fn to allow for more interesting input-output patterns. + +Note that tensors / Python state are allowed to be mutated. +This relaxed constraint is not always sound, but it is sound for backward tracing with fake +tensors as it takes place in AOTAutograd, as the backward pass is guaranteed not to depend on concrete +tensor values (via fake tensor) or Python state (because the autograd engine doesn't depend on Python). + +The intended use case for this function is to allow AOTAutograd to defer complex +backward hooks to compiled autograd. AOTAutograd performs a make_fx trace which preserves +the function call as is in the graph, and only when we Dynamo through the backward graph in +compiled autograd do we inline into the function. +""" + +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import autograd_not_implemented +from torch._ops import HigherOrderOperator, OpOverload +from torch._subclasses import FakeTensorMode +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.overrides import TorchFunctionMode +from torch.utils._python_dispatch import _get_current_dispatch_mode +from torch.utils._pytree import tree_map_only + + +Tensor = torch.Tensor + + +__all__ = ["trace_wrapped"] + + +@torch.library.custom_op("flex_lib::zeros_and_scatter", mutates_args=()) # type: ignore[misc] +def zeros_and_scatter( + shape: list[int], + indices: list[Tensor], + vals: Tensor, +) -> Tensor: + """Custom Op so that we can register a custom lowering for the new_output + scatter in the backwards pass""" + if not indices: + if shape: + raise RuntimeError( + "zeros_and_scatter with no indices only supports scalar outputs" + ) + return vals.sum() + grad = torch.zeros(shape, device=vals.device, dtype=vals.dtype) + return torch.ops.aten.index_put(grad, indices, vals, accumulate=True) + + +@zeros_and_scatter.register_fake # type: ignore[misc] +def _( + shape: list[int], + indices: list[Tensor], + vals: Tensor, +) -> Tensor: + return vals.new_empty(shape) + + +@zeros_and_scatter.register_vmap # type: ignore[misc] +def _(info, indims, shape, indices, value): # type: ignore[no-untyped-def] + """The batching rule is special in that it returns a tensor that is not batched""" + indices_indims: list[int | None] = indims[1] if indims[1] is not None else [] + expanded_indices = [] + for idx, idx_indim in zip(indices, indices_indims): + # The index is not being batched, we should unsqueeze and expand to val + if idx_indim is None: + expanded_indices.append(idx.expand(value.shape)) + else: + # the index is being part of the vmap batch, it should be the same size as val + if idx.shape != value.shape: + raise AssertionError( + f"idx shape {idx.shape} must match value shape {value.shape}" + ) + expanded_indices.append(idx) + + out = torch.ops.flex_lib.zeros_and_scatter( + shape, + expanded_indices, + value, + ) + return out, None + + +class ModIndex(torch.autograd.Function): + generate_vmap_rule = True + + @staticmethod + # pyrefly: ignore [bad-override] + def forward(x: Tensor, indices: list[Tensor]) -> Tensor: + if not indices: + if x.ndim != 0: + raise RuntimeError( + "mod_index with no indices only supports scalar tensors" + ) + return x + return torch.ops.aten.index(x, indices) + + @staticmethod + def setup_context(ctx: Any, inputs: tuple[Any, ...], output: Any) -> None: + x, indices = inputs + ctx.save_for_backward(*indices) + ctx.input_shape = x.shape + + @staticmethod + def backward(ctx, gradOut): # type: ignore[no-untyped-def] + indices = ctx.saved_tensors + return ( + torch.ops.flex_lib.zeros_and_scatter( + ctx.input_shape, + indices, + gradOut, + ), + None, + ) + + @classmethod + @torch._export.wrappers.allow_in_pre_dispatch_graph + def apply(cls, *args, **kwargs): # type: ignore[no-untyped-def] + return super().apply(*args, **kwargs) + + +mod_index = ModIndex.apply + + +class TransformGetItemToIndex(TorchFunctionMode): + # This is needed since we want to support calling + # A[q_idx], where q_idx is a scalar tensor in score_mod. + # Today, when q_idx is a scalar tensor, we implicitly convert it to a python + # scalar and create a view. We do not want that behavior in this case, so we + # use this torchfunctionmode to override that behavior for score_mod + # wherever we're running it. + # + # We also convert integer indices to 0-D tensors so that temp[0] produces + # the same backward graph as temp[0 * q_idx] (zeros_and_scatter with atomic_add). + def __torch_function__( + self, + func: OpOverload, + types: tuple[torch._C._TensorMeta, ...], + args: tuple[object, ...] = (), + kwargs: dict[str, object] | None = None, + ) -> object: + if func is torch.Tensor.__getitem__: + tensor_to_index = args[0] + if not isinstance(tensor_to_index, torch.Tensor): + raise AssertionError( + f"expected torch.Tensor, got {type(tensor_to_index)}" + ) + index_args = pytree.tree_leaves(args[1]) + if all(isinstance(x, (torch.Tensor, int)) for x in index_args): + converted_indices = [ + torch.tensor(x, dtype=torch.int64, device=tensor_to_index.device) + if isinstance(x, int) + else x + for x in index_args + ] + return mod_index(tensor_to_index, converted_indices) + return func(*args, **(kwargs or {})) + + +def trace_wrapped(*args: Any, **kwargs: Any) -> Any: + with torch.no_grad(): + return _trace_wrapped_op(*args, **kwargs) + + +class TraceWrapped(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("trace_wrapped") + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + # pyrefly: ignore [missing-attribute] + return super().__call__(*args, **kwargs) + + +# TODO(jansel): need to ensure this does not get DCEed +_trace_wrapped_op = TraceWrapped() + + +def _assert_meta( + grad: torch.Tensor, + size: tuple[int, ...], + stride: tuple[int, ...], + dtype: torch.dtype, +) -> torch.Tensor: + if grad.size() != size: + raise AssertionError("size mismatch") + if grad.stride() != stride: + raise AssertionError("stride mismatch") + if grad.dtype != dtype: + raise AssertionError("dtype mismatch") + return grad + + +@_trace_wrapped_op.py_impl(ProxyTorchDispatchMode) +def inner_trace( + mode: ProxyTorchDispatchMode, + *args: Any, + bw_state: BackwardState | None = None, + **kwargs: Any, +) -> Any: + def self_invoke(*args: Any, **dyn_kwargs: Any) -> Any: + with torch.no_grad(): + return _trace_wrapped_op(*args, **dyn_kwargs, **kwargs) + + def unwrap_proxies(x: Any) -> Any: + if isinstance(x, torch.Tensor): + return mode.tracer.unwrap_proxy(x) # type: ignore[union-attr] + if isinstance(x, (list, tuple)): + return type(x)(map(unwrap_proxies, x)) + if x is None: + return None + raise AssertionError(f"unhandled type: {type(x)}") + + proxy_kwargs = {} + if bw_state is not None: + if not isinstance(bw_state, BackwardState): + raise AssertionError(f"expected BackwardState, got {type(bw_state)}") + if bw_state.proxy is None: + raise AssertionError("bw_state.proxy must not be None") + proxy_kwargs["bw_state"] = bw_state.proxy + out_proxy = mode.tracer.create_proxy( + "call_function", + self_invoke, + unwrap_proxies(args), + proxy_kwargs, + name="trace_wrapped", + ) + + if args[0] is None: + grad = args[1] # module backward hooks + else: + grad = args[0] # other backward hooks + grad = tree_map_only(torch.Tensor, torch.empty_like, grad) + track_tensor_tree(grad, out_proxy, constant=None, tracer=mode.tracer) + return grad + + +@_trace_wrapped_op.py_impl(FakeTensorMode) +def inner_fake(*args: Any, **kwargs: Any) -> None: + raise RuntimeError("This op should never be invoked here") + + +@_trace_wrapped_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def _trace_wrapped_op_dense(*args: Any, fn: Any, **kwargs: Any) -> Any: + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + return fn(*args, **kwargs) + + +_trace_wrapped_op.py_impl(DispatchKey.Autograd)( + autograd_not_implemented(_trace_wrapped_op, deferred_error=True) +) + + +@_trace_wrapped_op.py_functionalize_impl +def _trace_wrapped_functionalized(ctx: Any, *args: Any, **kwargs: Any) -> Any: + unwrapped_args = ctx.unwrap_tensors(args) + with ctx.redispatch_to_next(): + return ctx.wrap_tensors(_trace_wrapped_op(*unwrapped_args, **kwargs)) + + +def autograd_function_backward_rewritten(original_backward: Any) -> Any: + def new_backward(ctx: Any, *grads: Any) -> Any: + # pyrefly: ignore [bad-assignment] + grads = [g.contiguous() for g in grads] + return original_backward(ctx, *grads) + + return new_backward diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..10079dde9b5e13a2d6669ad4a9134e20a63deb25 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile.py @@ -0,0 +1,550 @@ +import dataclasses +import importlib +import inspect +import io +import logging +import os +import pickle +import tempfile +import types +from collections.abc import Callable, Sequence +from contextlib import AbstractContextManager, ExitStack, nullcontext +from dataclasses import dataclass +from typing import Any, Optional, TYPE_CHECKING + +import torch +import torch.fx +from torch._dynamo.convert_frame import GraphRuntimeEnv +from torch._dynamo.graph_utils import _graph_device_type +from torch._dynamo.package import SystemInfo + +from . import convert_frame +from .aot_compile_types import ( + BundledAOTAutogradSerializableCallable, + SerializableCallable, +) +from .hooks import Hooks + + +if TYPE_CHECKING: + from .guards import GuardManagerWrapper + from .package import SerializedCode, SourceInfo + + +log = logging.getLogger(__name__) + + +def bind_locals( + signature: inspect.Signature, *args: Any, **kwargs: Any +) -> dict[str, Any]: + bound_arguments = signature.bind(*args, **kwargs) + bound_arguments.apply_defaults() + return bound_arguments.arguments + + +@dataclass +class CompileArtifacts: + signature: inspect.Signature + guard_manager: Optional["GuardManagerWrapper"] + guards_state: bytes + backend_id: str + compiled_fn: SerializableCallable + original_code: types.CodeType + runtime_env: GraphRuntimeEnv + source_info: "SourceInfo" + device_type: str + backend_name: str + system_info: SystemInfo = dataclasses.field(default_factory=SystemInfo.current) + + def check_compatibility(self) -> None: + current_system = SystemInfo.current() + current_system.check_compatibility(self.system_info, self.device_type) + + +class AOTCompilePickler(pickle.Pickler): + def __init__(self, external_data: dict[str, object], buf: io.BytesIO) -> None: + super().__init__(buf) + self.external_data = external_data + self.id_map: dict[int, str] = { + id(value): key for key, value in external_data.items() + } + self.errors = {} + + def persistent_id(self, obj: object) -> int | str | None: + if id(obj) in self.id_map: + return self.id_map[id(obj)] + elif isinstance(obj, torch.nn.Module): + self.errors[id(obj)] = obj + return id(obj) + else: + return None + + @classmethod + def _unpickle_cell(cls, val: object) -> object: + def _() -> object: + return val + + if _.__closure__ is None: + raise AssertionError("closure must not be None") + return _.__closure__[0] + + @classmethod + # pyrefly: ignore [implicit-any] + def _unpickle_bound_method(cls, func: Callable, base: object) -> types.MethodType: + return types.MethodType(func, base) + + @classmethod + def _unpickle_module(cls, name: str) -> types.ModuleType: + return importlib.import_module(name) + + @classmethod + def _unpickle_code(cls, serialized_code: "SerializedCode") -> types.CodeType: + from torch._dynamo.package import SerializedCode + + return SerializedCode.to_code_object(serialized_code) + + @classmethod + def _unpickle_nested_function( + cls, + code: types.CodeType, + module: str, + qualname: str, + argdefs: tuple[object, ...] | None, + closure: tuple[types.CellType, ...] | None, + ) -> types.FunctionType: + f_globals = importlib.import_module(module).__dict__ + return types.FunctionType(code, f_globals, qualname, argdefs, closure) + + # pyrefly: ignore [bad-override] + def reducer_override(self, obj: Any) -> Any: + if isinstance(obj, type((lambda x: lambda: x)(0).__closure__[0])): # type: ignore[index] # noqa: PLC3002 + return type(self)._unpickle_cell, (obj.cell_contents,) + elif inspect.iscode(obj): + from torch._dynamo.package import SerializedCode + + return type(self)._unpickle_code, (SerializedCode.from_code_object(obj),) + + elif inspect.ismodule(obj): + return type(self)._unpickle_module, (obj.__name__,) + elif inspect.ismethod(obj): + """ + By default, pickle will call getattr() directly on the self object + for pickling bounded methods, this is not what we want, instead we + always want to serialize the original function and the self object + in their original form. + """ + func = obj.__func__ + method_self = obj.__self__ + inner_func = getattr(method_self, func.__name__) + if inspect.ismethod(inner_func): + inner_func = inner_func.__func__ + if func is not inner_func: + return type(self)._unpickle_bound_method, (func, method_self) + elif inspect.isfunction(obj): + if "" in obj.__qualname__: + return type(self)._unpickle_nested_function, ( + obj.__code__, + obj.__module__, + obj.__qualname__, + obj.__defaults__, + obj.__closure__, + ) + + return NotImplemented + + +class AOTCompileUnpickler(pickle.Unpickler): + def __init__(self, external_data: dict[str, object], file: io.BytesIO) -> object: + super().__init__(file) + self.external_data = external_data + + def persistent_load(self, key: str) -> object: + if key not in self.external_data: + raise RuntimeError( + f"Missing required external reference to data: {key}. " + "Please load AOT compiled function with " + "`external_data=`" + f"{self.external_data}" + ) + return self.external_data[key] + + +@dataclass +class AOTCompileSaveResult: + serialized_data: bytes + + +def atomic_write_binary(file_path: str, data: bytes): + dir_name = os.path.dirname(file_path) or "." + + with tempfile.NamedTemporaryFile( + dir=dir_name, delete=False, mode="wb" + ) as temp_file: + temp_path = temp_file.name + temp_file.write(data) + temp_file.flush() + os.fsync(temp_file.fileno()) + + os.replace(temp_path, file_path) + + +@dataclass +class AOTCompiledFunction: + _artifacts: CompileArtifacts + _guard_check_enabled: bool = True + _extra_globals: dict[str, object] | None = None + + def prepare_f_locals(self, *args: object, **kwargs: object) -> dict[str, object]: + f_locals: dict[str, object] = {} + env = self._artifacts.runtime_env + if env.closure: + if not env.bytecode.co_freevars or len(env.closure) != len( + env.bytecode.co_freevars + ): + raise AssertionError("closure length must match co_freevars length") + f_locals = { + name: cell.cell_contents + for name, cell in zip(env.bytecode.co_freevars, env.closure) + } + f_locals.update(bind_locals(self._artifacts.signature, *args, **kwargs)) + return f_locals + + def guard_check(self, *args: Any, **kwargs: Any) -> bool: + f_locals = self.prepare_f_locals(*args, **kwargs) + if self._artifacts.guard_manager is None: + raise AssertionError("guard_manager must not be None") + return self._artifacts.guard_manager.check(f_locals) + + def __post_init__(self) -> None: + from .package import load_guard_manager, load_guards_state + + self._artifacts.check_compatibility() + + self.fn = self._artifacts.runtime_env.forward_callable( + self._artifacts.backend_id, + self._artifacts.compiled_fn, + extra_globals=self._extra_globals, + ) + + if self._artifacts.guard_manager is None: + guards_state = load_guards_state(self._artifacts.guards_state) + self._artifacts.guard_manager = load_guard_manager( + guards_state, + self._artifacts.original_code, + self.fn.__globals__, + ) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + if self._artifacts.guard_manager is None: + raise AssertionError("guard_manager must not be None") + if self._guard_check_enabled and not self.guard_check(*args, **kwargs): + f_locals = self.prepare_f_locals(*args, **kwargs) + reason = str(self._artifacts.guard_manager.check_verbose(f_locals)) + raise RuntimeError(f"GuardManager check failed, reason: {reason}") + return self.fn(*args, **kwargs) + + def source_info(self) -> "SourceInfo": + return self._artifacts.source_info + + def save_compiled_function( + self, path: str, external_data: dict[str, Any] | None = None + ) -> AOTCompileSaveResult: + result = type(self).serialize(self, external_data) + atomic_write_binary(path, result.serialized_data) + return result + + @classmethod + def serialize( + cls, fn: "AOTCompiledFunction", external_data: dict[str, Any] | None = None + ) -> AOTCompileSaveResult: + from torch._dynamo.package import SerializedCode + + state = fn._artifacts.__dict__.copy() + state["guard_manager"] = None + state["runtime_env"] = dataclasses.replace( + state["runtime_env"], + bytecode=SerializedCode.from_code_object(state["runtime_env"].bytecode), + ) + compiled_fn = state["compiled_fn"] + state["compiled_fn"] = ( + type(compiled_fn).deserialize_compile_artifacts, + type(compiled_fn).serialize_compile_artifacts(compiled_fn), + ) + state["original_code"] = SerializedCode.from_code_object(state["original_code"]) + buf = io.BytesIO() + pickler = AOTCompilePickler(external_data or {}, buf) + pickler.dump(state) + if pickler.errors: + raise RuntimeError( + f"Failed to serialize the following objects: {list(pickler.errors.values())}\n" + "Please mark these as external data by using `external_data={'key': ...}`" + ) + return AOTCompileSaveResult(serialized_data=buf.getvalue()) + + @classmethod + def deserialize( + cls, + data: bytes, + f_globals: dict[str, object] | None = None, + external_closure_data: dict[str, Any] | None = None, + ) -> "AOTCompiledFunction": + from torch._dynamo.package import SerializedCode + + f = io.BytesIO(data) + f.seek(0) + unpickler = AOTCompileUnpickler(external_closure_data or {}, f) + state = unpickler.load() + f.close() + state["runtime_env"] = dataclasses.replace( + state["runtime_env"], + bytecode=SerializedCode.to_code_object(state["runtime_env"].bytecode), + ) + deserializer, compiled_fn_state = state["compiled_fn"] + with torch._inductor.config.patch(enable_autograd_for_aot=True): + state["compiled_fn"] = deserializer(compiled_fn_state) + state["original_code"] = SerializedCode.to_code_object(state["original_code"]) + + artifacts = CompileArtifacts(**state) + return cls(artifacts, _extra_globals=f_globals) + + def disable_guard_check(self) -> None: + self._guard_check_enabled = False + + +def aot_compile_fullgraph( + model: Any, + example_inputs: tuple[tuple[Any, ...], dict[str, Any]], + hooks: Hooks, + backend: Callable[[torch.fx.GraphModule, list[torch.Tensor]], SerializableCallable], + dynamic: bool | None = None, +) -> AOTCompiledFunction: + from torch._dynamo.guards import CheckFunctionManager + from torch._dynamo.package import SourceInfo + from torch._dynamo.utils import dynamo_timed, get_metrics_context + from torch._dynamo.variables.torch_function import ( + torch_function_mode_stack_state_mgr, + ) + from torch._guards import TracingContext + + args, kwargs = example_inputs + + dynamic_ctx = nullcontext() + if dynamic is not None: + from torch._dynamo.eval_frame import set_enable_dynamic + + dynamic_ctx = set_enable_dynamic(dynamic) + + with ( + get_metrics_context(), + dynamo_timed("fullgraph_capture"), + torch._functorch.config.patch(strict_autograd_cache=True), + dynamic_ctx, + torch_function_mode_stack_state_mgr, + ): + capture_output = convert_frame.fullgraph_capture(model, args, kwargs) + graph_capture_output = capture_output.graph_capture_output + if graph_capture_output.output_graph is None: + raise AssertionError("output_graph must not be None") + + if not hooks.guard_filter_fn: + from torch._dynamo.types import GuardFilterEntry + + def new_guard_filter_fn( + guard_entries: Sequence[GuardFilterEntry], + ) -> Sequence[bool]: + return [ + ( + not ( + g.is_global + or g.guard_type + in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES + ) + ) + for g in guard_entries + ] + + hooks.guard_filter_fn = new_guard_filter_fn + + fn, _ = convert_frame.get_traced_fn(model) + + backend_input = capture_output.backend_input + if backend_input is None: + raise AssertionError("backend_input must not be None") + backend_input.graph_module._backend_id = backend_input.backend_id # type: ignore[assignment] + device_type = _graph_device_type(backend_input.graph_module.graph) + if ( + backend_input.fake_mode.shape_env + is not graph_capture_output.output_graph.shape_env + ): + raise AssertionError( + "fake_mode.shape_env must be the same as output_graph.shape_env" + ) + tracing_context = TracingContext(backend_input.fake_mode) + tracing_context.tensor_to_context = backend_input.tensor_to_context + with ( + torch._guards.tracing(tracing_context), + torch._functorch.config.patch( + { + "strict_autograd_cache": True, + "bypass_autograd_cache_key": True, + "bundled_autograd_cache": True, + "force_non_lazy_backward_lowering": True, + "force_autograd_cache": True, + } + ), + ): + compiled_fn = backend( + backend_input.graph_module, backend_input.example_inputs + ) + # If Inductor backend or AOTAutograd-based backend is used, + # wrap the compiled_fn for serialization. + # TODO: this should be replaced once we make the backend return the SerializableCallable directly. + if ( + isinstance(backend, torch._TorchCompileInductorWrapper) + or ( + hasattr(backend, "compiler_fn") + and isinstance( + backend.compiler_fn, torch._dynamo.backends.common.AotAutograd + ) + ) + or ( + hasattr(compiled_fn, "serialize") + and compiled_fn.serialize is not None + ) + ): + compiled_fn = BundledAOTAutogradSerializableCallable(compiled_fn) + + if not isinstance(compiled_fn, SerializableCallable): + if hasattr(backend, "compiler_fn"): + compiler_fn = backend.compiler_fn + else: + compiler_fn = backend + raise RuntimeError( + f"Compiled function type {type(compiled_fn)} (produced " + + f"from backend {compiler_fn}) does not implement SerializableCallable." + ) + + # Temporarily restore the mode stack so guard expressions that + # reference modes can evaluate, matching the compile_inner path. + build_guards_ctx = ExitStack() + if torch_function_mode_stack_state_mgr.stack: + build_guards_ctx.enter_context( + torch_function_mode_stack_state_mgr.temp_restore_stack() + ) + with build_guards_ctx: + check_fn = graph_capture_output.build_guards( + fn.__code__, hooks=hooks, save=True, strict_error=True + ) + + if check_fn.guards_state is None: + raise AssertionError("guards_state must not be None") + + source_info = SourceInfo(inlined_sources=set()) + for traced_code in graph_capture_output.traced_code: + source_info.add_code(traced_code) + + artifacts = CompileArtifacts( + signature=convert_frame._get_signature(fn), + guard_manager=check_fn.guard_manager, + guards_state=check_fn.guards_state, + backend_id=backend_input.backend_id, + compiled_fn=compiled_fn, + original_code=fn.__code__, + runtime_env=graph_capture_output.get_runtime_env(), + source_info=source_info, + device_type=device_type, + backend_name=getattr(backend, "compiler_name", "unknown"), + ) + aot_compiled_fn = AOTCompiledFunction( + _artifacts=artifacts, _extra_globals=fn.__globals__ + ) + + return aot_compiled_fn + + +@dataclass +class ModelInput: + """ + WIP type: represents a single model input + Which consists of a tuple of arguments and a set of contexts in which to run the model. + + For each ModelInput, we'll compile one full graph of the model, and then use the guards generated + to dispatch between the compiled graphs. + + + """ + + args: tuple[Any] + kwargs: dict[str, Any] + contexts: list[AbstractContextManager[Any]] + + +@dataclass +class AOTCompiledModel: + # Represents a single forward function of a model along with dispatch + # compiled_results is serializable. We require the model to deserialize again. + model: torch.nn.Module + compiled_results: list[AOTCompiledFunction] + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + for result in self.compiled_results: + if result.guard_check(self.model, *args, **kwargs): + return result(self.model, *args, **kwargs) + # All guards failed, just run one of them and throw the guard check error. + return self.compiled_results[0](self.model, *args, **kwargs) + + def serialize(self) -> bytes: + data: list[bytes] = [] + for result in self.compiled_results: + data.append(AOTCompiledFunction.serialize(result).serialized_data) + return pickle.dumps(data) + + @classmethod + def deserialize(cls, model: torch.nn.Module, data: bytes) -> "AOTCompiledModel": + from torch._dynamo.utils import get_metrics_context + from torch._guards import compile_context, CompileContext + + results: list[bytes] = pickle.loads(data) + compiled_results = [] + for result in results: + with ( + compile_context(CompileContext(convert_frame.get_compile_id({}))), + get_metrics_context(), + ): + compiled_results.append(AOTCompiledFunction.deserialize(result)) + return cls(model, compiled_results) + + +def aot_compile_module( + model: torch.nn.Module, + inputs: list[ModelInput], + hooks: Hooks, + backend: Callable[[torch.fx.GraphModule, list[torch.Tensor]], SerializableCallable], +) -> AOTCompiledModel: + """ + Compiles a single nn.Module with any number of inputs, and returns a compiled forward function. + """ + + def compile_single_graph(model_input: ModelInput) -> AOTCompiledFunction: + example_inputs = (model_input.args, model_input.kwargs) + orig_forward = model.forward + with ExitStack() as stack: + for ctx in model_input.contexts: + stack.enter_context(ctx) + return aot_compile_fullgraph( + orig_forward, + example_inputs, + hooks=hooks, + backend=backend, + ) + + # pyrefly: ignore [implicit-any] + compiled_results = [] + for model_input in inputs: + log.info("Compiling input %s..", model_input) + compiled_results.append(compile_single_graph(model_input)) + + if len(compiled_results) == 0: + raise AssertionError("Expected at least one compiled result") + + return AOTCompiledModel(model, compiled_results) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile_types.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile_types.py new file mode 100644 index 0000000000000000000000000000000000000000..19ed258ac2b191ee20c40e957e8b4ec4beb32e8a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile_types.py @@ -0,0 +1,221 @@ +import abc +import importlib +import pickle +from typing import Any + +import torch + + +def _serialize_triton_kernel(kernel: Any) -> tuple[str, str]: + """ + Serialize a triton kernel by extracting its module path and function name. + Returns (module_path, function_name) tuple. + + Triton JITFunction objects contain unpicklable _thread.RLock objects, so we + serialize the import path instead and reimport on load. + + Raises: + RuntimeError: If the kernel cannot be serialized (missing attributes). + """ + fn = getattr(kernel, "fn", None) + module_path = fn and getattr(fn, "__module__", None) + func_name = fn and getattr(fn, "__name__", None) + if fn is None or module_path is None or func_name is None: + raise RuntimeError( + f"Kernel fn missing __module__ or __name__: " + f"module={module_path}, name={func_name}. " + f"Cannot serialize for precompilation." + ) + return (module_path, func_name) + + +def _deserialize_triton_kernel(kernel_info: tuple[str, str]) -> Any: + """ + Deserialize a triton kernel by reimporting from its module. + kernel_info is (module_path, function_name) tuple. + """ + module_path, func_name = kernel_info + module = importlib.import_module(module_path) + kernel = getattr(module, func_name) + return kernel + + +# Note: [Triton Kernel Side Table Serialization] +# +# When dynamo captures user-defined triton kernels, it creates FX graph nodes +# (triton_kernel_wrapper_mutation/functional) with a `kernel_idx` parameter that +# references the global `kernel_side_table` in triton_kernel_wrap.py. This side +# table maps integer indices to actual triton kernel objects. +# +# For kernels that go through inductor's codegen path, this is fine - inductor +# looks up the kernel from the side table at codegen time and embeds the kernel +# source code directly into the generated wrapper. The compiled code doesn't +# need the side table at runtime. +# +# However, not all triton kernels go through inductor codegen. When using +# regional_inductor, only annotated regions are compiled by inductor. Triton +# kernels outside these regions are executed via the FX interpreter, which +# calls the higher-order op directly and needs the kernel to be in the side +# table at runtime. +# +# When serializing/deserializing bundled AOT artifacts across process boundaries, +# the kernel_side_table is empty in the new process, causing: +# AssertionError: Kernel index X not found in id_to_kernel +# +# To fix this, we capture the kernel_side_table state during serialization and +# restore it during deserialization. Kernels are serialized by their import path +# (module_path, function_name) since triton JITFunction objects contain +# unpicklable RLock objects. + + +class SerializableCallable(abc.ABC): + @classmethod + @abc.abstractmethod + def serialize_compile_artifacts(cls, fn: Any) -> bytes: + pass + + @classmethod + @abc.abstractmethod + def deserialize_compile_artifacts(cls, data: bytes) -> Any: + pass + + @abc.abstractmethod + def __call__(self, *args: Any, **kwargs: Any) -> Any: + pass + + +class GraphModuleSerializableCallable(SerializableCallable): + def __init__(self, graph_module: torch.fx.GraphModule) -> None: + if not isinstance(graph_module, torch.fx.GraphModule): + raise AssertionError( + f"Expected torch.fx.GraphModule, got {type(graph_module)}" + ) + self.graph_module = graph_module + + @classmethod + def serialize_compile_artifacts( + cls, fn: "GraphModuleSerializableCallable" + ) -> bytes: + from torch.fx._graph_pickler import GraphPickler, Options + + state = fn.__dict__.copy() + + graph_module = state["graph_module"] + for node in graph_module.graph.nodes: + node.meta.pop("nn_module_stack", None) + node.meta.pop("source_fn_stack", None) + node.meta.pop("example_value", None) + + state["graph_module"] = GraphPickler.dumps( + graph_module, Options(ops_filter=None) + ) + return pickle.dumps(state) + + @classmethod + def deserialize_compile_artifacts(cls, data: bytes) -> Any: + from torch._subclasses import FakeTensorMode + from torch.fx._graph_pickler import GraphPickler + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + state = pickle.loads(data) + + fake_mode = FakeTensorMode(shape_env=ShapeEnv()) + state["graph_module"] = GraphPickler.loads(state["graph_module"], fake_mode) + if not isinstance(state["graph_module"], torch.fx.GraphModule): + raise AssertionError( + f"Expected deserialized graph_module to be torch.fx.GraphModule, " + f"got {type(state['graph_module'])}" + ) + state["graph_module"].recompile() + + return cls(**state) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self.graph_module.forward(*args, **kwargs) + + +class BundledAOTAutogradSerializableCallable(SerializableCallable): + """ + Represents a serializable callable generated by compile_fx. + This class wraps around the compiled function generated by AOTAutograd. + + TODO: Instead of using PrecompileContext to grab it from AOTAutograd, + this object should be what's *returned* by aot_module_simplified. + We'll do that refactor in a later PR. + """ + + def __init__(self, compiled_fn: Any) -> None: + """ + Takes in a BundledAOTAutogradCacheArtifact, which is the serialized form + of a compiled function generated by AOTAutograd. + """ + if not hasattr(compiled_fn, "serialize"): + raise AssertionError( + f"compiled_fn must have a 'serialize' method, got {type(compiled_fn)}" + ) + self.compiled_fn = compiled_fn + + def __getattr__(self, attr: Any) -> Any: + return getattr(self.compiled_fn, attr) + + @classmethod + def serialize_compile_artifacts( + cls, fn: "BundledAOTAutogradSerializableCallable" + ) -> bytes: + from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table + + # See Note: [Triton Kernel Side Table Serialization] + # Capture triton kernel side table state BEFORE serialization. + triton_kernels: dict[int, tuple[str, str]] = { + idx: _serialize_triton_kernel(kernel) + for idx, kernel in kernel_side_table.id_to_kernel.items() + } + triton_constant_args: dict[int, dict[str, Any]] = dict( + kernel_side_table.constant_args + ) + + with torch._functorch.config.patch("bundled_autograd_cache", True): + serialized_entry = fn.compiled_fn.serialize() + # Bundle the triton kernel side table with the serialized entry + bundle = (serialized_entry, triton_kernels, triton_constant_args) + result = pickle.dumps(bundle) + return result + + @classmethod + def deserialize_compile_artifacts(cls, data: bytes) -> Any: + from torch._functorch._aot_autograd.aot_autograd_result import ( + deserialize_bundled_cache_entry, + ) + from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table + + bundle = pickle.loads(data) + + # Handle both old format (just entry) and new format (entry, kernels, const_args) + if isinstance(bundle, tuple) and len(bundle) == 3: + entry, triton_kernels, triton_constant_args = bundle + else: + # Backwards compatibility with old serialized artifacts + entry = bundle + # pyrefly: ignore [implicit-any] + triton_kernels = {} + # pyrefly: ignore [implicit-any] + triton_constant_args = {} + + # See Note: [Triton Kernel Side Table Serialization] + # Restore triton kernel side table BEFORE deserializing the compiled function. + # The compiled function may reference kernels by index if any triton kernels + # don't go through inductor codegen (e.g., triton kernels outside of + # regional_inductor compiled regions). + for idx, kernel_info in triton_kernels.items(): + kernel = _deserialize_triton_kernel(kernel_info) + kernel_side_table.id_to_kernel[idx] = kernel + kernel_side_table.kernel_to_id[kernel] = idx + + for idx, args in triton_constant_args.items(): + kernel_side_table.constant_args[idx] = args + + compiled_fn = deserialize_bundled_cache_entry(entry) + return cls(compiled_fn) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self.compiled_fn(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7e764b3f09c6c0548e7f6f5150ec915384a58a9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed876cc385eddcbd99bb1c633d6cbc447a2b3cf8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/cudagraphs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/cudagraphs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..031014ba8427cd1f5e8de4ee6e364690bef441a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/cudagraphs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/debugging.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/debugging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05ce1f3e4fe1e1e238882e52393dff9c7541cb23 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/debugging.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/distributed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/distributed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e6dc19b76d45014fa191128a7903984a23789a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/distributed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/inductor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/inductor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a642840668923e83e8987266fcae9dfa63ebe11 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/inductor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/onnxrt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/onnxrt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfbdc8900192b5ef56e9642e2ed254bb5ce95703 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/onnxrt.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/registry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93671ab48d865bc7262ec16e0b9d7ade13df3d89 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/registry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tensorrt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tensorrt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1eac2338f917221350c2f4654e2ed15cae09818 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tensorrt.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/torchxla.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/torchxla.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..748e18b52dcc6b0a7c751a6181f12660ccac5694 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/torchxla.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tvm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tvm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb9eb6ad0237a95d07313690d6cfbc998282870b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tvm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/common.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/common.py new file mode 100644 index 0000000000000000000000000000000000000000..8512144eb5790664cf458fd1744271d56320e2a2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/common.py @@ -0,0 +1,215 @@ +""" +This module provides common utilities and base classes for TorchDynamo backends. + +Key components: +- AotAutograd: Base class for implementing AOT (Ahead-of-Time) autograd backends +- Backend utilities for handling: + - Fake tensor conversion + - Device/dtype detection from inputs + - Memory efficient fusion + - Graph flattening + - Common compiler configurations + +The utilities here are used by various backend implementations to handle +common operations and provide consistent behavior across different backends. +AOT autograd functionality is particularly important as it enables ahead-of-time +optimization of both forward and backward passes. +""" + +from __future__ import annotations + +import contextlib +import functools +import logging +from typing import Any, TYPE_CHECKING +from typing_extensions import ParamSpec, Required, TypedDict, TypeVar, Unpack +from unittest.mock import patch + +import torch +from torch._dynamo import disable +from torch._dynamo.exc import TensorifyScalarRestartAnalysis +from torch._dynamo.utils import counters, defake, flatten_graph_inputs +from torch._functorch.aot_autograd import ( + aot_module_simplified, + SerializableAOTDispatchCompiler, +) +from torch.utils._python_dispatch import _disable_current_modes + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._inductor.compile_fx import CompilerConfigExtra + from torch._ops import OpOverload + + +log = logging.getLogger(__name__) + +P = ParamSpec("P") +R = TypeVar("R") + + +class AotAutogradKwargs(TypedDict, total=False): + """Keyword arguments accepted by AotAutograd and forwarded verbatim to + aot_module_simplified. decompositions may also be a zero-arg thunk returning + the decomposition table (a workaround for circular imports); AotAutograd + resolves it to the table before forwarding.""" + + fw_compiler: Required[Callable[..., Any]] + bw_compiler: Callable[..., Any] | None + inference_compiler: Callable[..., Any] | None + partition_fn: Callable[..., Any] + decompositions: ( + dict[OpOverload, Callable[..., Any]] + | Callable[[], dict[OpOverload, Callable[..., Any]]] + ) + keep_inference_input_mutations: bool + compiler_config_extra: CompilerConfigExtra | None + ignore_shape_env: bool + disable_functionalization: bool + pre_grad_passes: Callable[..., Any] | None + compile_region_name: str | None + + +class AotAutograd: + def __init__(self, **kwargs: Unpack[AotAutogradKwargs]) -> None: + self.__name__ = "compiler_fn" + self.kwargs: AotAutogradKwargs = kwargs + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: Sequence[Any], **kwargs: Any + ) -> Callable[..., Any]: + if kwargs: + log.warning("aot_autograd-based backend ignoring extra kwargs %s", kwargs) + + if any(isinstance(x, (list, tuple, dict)) for x in example_inputs): + return flatten_graph_inputs( + gm, + example_inputs, + self, + ) + + # Hack to get around circular import problems with aot_eager_decomp_partition + decompositions = self.kwargs.get("decompositions") + if callable(decompositions): + self.kwargs["decompositions"] = decompositions() + + # NB: don't delete counter increment + counters["aot_autograd"]["total"] += 1 + + def wrap_bw_compiler(bw_compiler_fn: Callable[P, R]) -> Callable[..., R]: + def _wrapped_bw_compiler(*args: P.args, **kwargs: P.kwargs) -> R: + # Note [Wrapping bw_compiler in disable] + # The two disables here: + # - stop TorchDynamo from trying to compile the bw_compiler function itself + # - stop TorchDynamo from trying to compile our the generated backwards pass bw_compiler produces + + return disable( + disable( + bw_compiler_fn, reason="do not trace backward compiler function" + )(*args, **kwargs), # type: ignore[misc] + reason="do not trace generated backwards pass", + ) + + _wrapped_bw_compiler._is_wrapped_bw_compiler = ( # pyrefly: ignore [missing-attribute] + True + ) + return _wrapped_bw_compiler + + bw_compiler = self.kwargs.get("bw_compiler") or self.kwargs["fw_compiler"] + + if isinstance(bw_compiler, SerializableAOTDispatchCompiler): + if not getattr(bw_compiler.compiler_fn, "_is_wrapped_bw_compiler", False): + bw_compiler.compiler_fn = wrap_bw_compiler(bw_compiler.compiler_fn) + elif not getattr(bw_compiler, "_is_wrapped_bw_compiler", False): + bw_compiler = wrap_bw_compiler(bw_compiler) + + self.kwargs["bw_compiler"] = bw_compiler + self.kwargs["inference_compiler"] = ( + self.kwargs.get("inference_compiler") or self.kwargs["fw_compiler"] + ) + + from functorch.compile import nop + from torch._inductor.debug import enable_aot_logging + + # debug asserts slow down compile time noticeably, + # So only default them on when the aot_eager backend is used. + if self.kwargs.get("fw_compiler", None) is nop: + patch_config: contextlib.AbstractContextManager[Any] = patch( + "functorch.compile.config.debug_assert", True + ) + else: + patch_config = contextlib.nullcontext() + + try: + # NB: NOT cloned! + with enable_aot_logging(), patch_config: + # The decompositions thunk is resolved to a concrete table by the + # callable check above, but pyrefly cannot narrow that through the + # TypedDict subscript assignment, so the spread looks ill-typed. + cg = aot_module_simplified( + gm, + example_inputs, + **self.kwargs, # pyrefly: ignore [bad-argument-type] + ) + counters["aot_autograd"]["ok"] += 1 + return disable(cg, reason="do not trace AOT-compiled graph") + except TensorifyScalarRestartAnalysis: + raise + except Exception: + counters["aot_autograd"]["not_ok"] += 1 + raise + + +def aot_autograd(**kwargs: Unpack[AotAutogradKwargs]) -> AotAutograd: + return AotAutograd(**kwargs) + + +def mem_efficient_fusion_kwargs(use_decomps: bool) -> dict[str, Any]: + from functorch.compile import ( + default_decompositions, + min_cut_rematerialization_partition, + ts_compile, + ) + + kwargs = { + # these are taken from memory_efficient_fusion() + "fw_compiler": ts_compile, + "bw_compiler": ts_compile, + "partition_fn": min_cut_rematerialization_partition, + } + + if use_decomps: + # pyrefly: ignore [bad-typed-dict-key] + kwargs["decompositions"] = default_decompositions + + return kwargs + + +def fake_tensor_unsupported(fn: Callable[[Any, list[Any], Any], R]) -> Any: + """ + Decorator for backends that need real inputs. We swap out fake + tensors for zero tensors. + """ + + @functools.wraps(fn) + def wrapper(model: Any, inputs: Any, **kwargs: Any) -> Any: + with _disable_current_modes(): + inputs = list(map(defake, inputs)) + return fn(model, inputs, **kwargs) # type: ignore[call-arg] + + return wrapper + + +def device_from_inputs(example_inputs: Iterable[Any]) -> torch.device: + for x in example_inputs: + if isinstance(x, torch.Tensor): + return x.device + return torch.device("cpu") # Default fallback + + +def dtype_from_inputs(example_inputs: Iterable[Any]) -> torch.dtype: + for x in example_inputs: + if isinstance(x, torch.Tensor): + return x.dtype + return torch.float32 # Default fallback diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/cudagraphs.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/cudagraphs.py new file mode 100644 index 0000000000000000000000000000000000000000..b6af7eaa74210345e99820b8313a2bbfc6492d61 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/cudagraphs.py @@ -0,0 +1,318 @@ +""" +This module implements CUDA graphs support for TorchDynamo backends. + +CUDA graphs allow for capturing and replaying GPU operations, which can significantly +reduce CPU overhead in GPU-accelerated PyTorch models. This module provides: + +- CUDA graph creation and management for both forward and backward passes +- Input mutation detection and handling +- Device compatibility checking +- Stack trace management for debugging +- Integration with TorchInductor's cudagraph trees + +The backend supports two main modes: +1. cudagraphs: Full CUDA graph support with both forward and backward pass optimization +2. cudagraphs_inner: Lower-level CUDA graph implementation used for benchmarking + +Key components: +- CudagraphsBackend: Main backend class for CUDA graph integration +- Mutation detection utilities to ensure graph safety +- Device mapping and compatibility checks +- Stack trace collection for debugging +""" + +import functools +import logging +from collections import defaultdict +from collections.abc import Callable, Sequence +from typing import Any + +import torch +import torch.fx +from torch._dynamo import config +from torch._dynamo.backends.common import aot_autograd +from torch._dynamo.backends.debugging import boxed_nop +from torch._inductor.cudagraph_utils import ( + BoxedDeviceIndex, + check_multiple_devices_or_any_cpu_nodes, + format_default_skip_message, + get_mutation_stack_trace, + get_placeholder_info, + log_cudagraph_skip_and_bump_counter, +) +from torch._inductor.utils import ( + BoxedBool, + count_tangents, + get_first_incompatible_cudagraph_node, + num_fw_fixed_arguments, + output_node, +) +from torch.multiprocessing.reductions import StorageWeakRef + +from .registry import register_backend + + +log = logging.getLogger(__name__) + + +def find_input_mutations(g: torch.fx.Graph) -> set[int]: + def meta_fk(meta: dict[str, Any]) -> Any: + return meta["val"] if "val" in meta else meta["fake_result"] + + inputs = defaultdict(set) + input_idx = 0 + mutated_inputs = set() + for n in g.nodes: + if n.op == "placeholder": + if isinstance(meta_fk(n.meta), torch.Tensor): + inputs[StorageWeakRef(meta_fk(n.meta)._typed_storage())].add(input_idx) + input_idx += 1 + elif n.op == "call_function": + if not hasattr(n.target, "_schema"): + continue + + schema = n.target._schema + for i, arg in enumerate(schema.arguments): + if i < len(n.args): + argument = n.args[i] + else: + if arg.name not in n.kwargs: + continue + argument = n.kwargs[arg.name] + mut_arg = False + if arg.alias_info: + if arg.alias_info.is_write: + mut_arg = True + if mut_arg: + # TODO: not correct for args that contain tensors in a struct + # like list + mutated_inputs |= inputs[ + StorageWeakRef(meta_fk(argument.meta)._typed_storage()) + ] + + # TODO: error on unrecognized nodes + return mutated_inputs + + +def get_device_node_mapping( + gm: torch.fx.GraphModule, +) -> dict[torch.device, torch.fx.Node]: + device_node_mapping: dict[torch.device, torch.fx.Node] = {} + for n in gm.graph.nodes: + t = n.meta.get("val", None) + if isinstance(t, torch.Tensor) and t.device not in device_node_mapping: + device_node_mapping[t.device] = n + return device_node_mapping + + +def check_for_mutation_ignore_cuda_graph_managed_tensor( + aot_model: torch.fx.GraphModule, num_fixed: int +) -> str | None: + mutation_indices = find_input_mutations(aot_model.graph) - set(range(num_fixed)) + if not mutation_indices: + return None + + placeholders = get_placeholder_info(aot_model.graph) + return get_mutation_stack_trace(placeholders, mutation_indices) + + +def check_for_skip(aot_model: torch.fx.GraphModule, num_fixed: int) -> str | None: + if not config.cudagraph_backend_support_input_mutation: + if mut_skip := check_for_mutation_ignore_cuda_graph_managed_tensor( + aot_model, num_fixed + ): + return mut_skip + + if skip := check_multiple_devices_or_any_cpu_nodes( + get_device_node_mapping(aot_model) + ): + return skip + + if node := get_first_incompatible_cudagraph_node(aot_model): + return format_default_skip_message(f"incompatible op ({node.name})") + + return None + + +def get_device_index(gm: torch.fx.GraphModule) -> int: + device = next(iter(get_device_node_mapping(gm))) + if device.type != "cuda": + raise AssertionError(f"Expected CUDA device, got {device.type}") + return device.index + + +def get_stack_traces(gm: torch.fx.GraphModule) -> list[str | None]: + output = output_node(gm) + if len(output.args) != 1: + raise AssertionError( + f"Expected output node to have 1 arg, got {len(output.args)}" + ) + args = output.args[0] + if not hasattr(args, "__iter__"): + return [] + return [ + (arg.stack_trace if isinstance(arg, torch.fx.node.Node) else None) + for arg in args # type: ignore[union-attr] + ] + + +def cudagraphs(dynamo_model: torch.fx.GraphModule, dynamo_inputs: Sequence[Any]) -> Any: + from torch._inductor.cudagraph_trees import cudagraphify_impl + + do_cudagraphs = BoxedBool(True) + boxed_device_index = BoxedDeviceIndex(None) + + def forward_cudagraphs( + aot_model: torch.fx.GraphModule, + aot_inputs: list[Any], + is_inference: bool = False, + ) -> Any: + interp = boxed_nop(aot_model, aot_inputs) + fixed = num_fw_fixed_arguments(len(dynamo_inputs), len(aot_inputs)) + if skip_msg := check_for_skip(aot_model, fixed): + BoxedBool.disable(do_cudagraphs) + log_cudagraph_skip_and_bump_counter( + f"skipping cudagraphs due to {skip_msg}" + ) + return interp + + boxed_device_index.set(get_device_index(aot_model)) + out = cudagraphify_impl( + interp, + aot_inputs, + range(fixed), + device_index=boxed_device_index.value, + is_backward=False, + is_inference=is_inference, + stack_traces=get_stack_traces(aot_model), + placeholders=get_placeholder_info(aot_model.graph), + mutated_input_idxs=find_input_mutations(aot_model.graph), + ) + out._boxed_call = True # type: ignore[attr-defined] + return out + + def backward_cudagraphs( + aot_model: torch.fx.GraphModule, aot_inputs: list[Any] + ) -> Any: + interp = boxed_nop(aot_model, aot_inputs) + if not do_cudagraphs: + return aot_model + + fixed = count_tangents(aot_model) + if skip_msg := check_for_skip(aot_model, fixed): + log_cudagraph_skip_and_bump_counter( + f"skipping cudagraphs due to {skip_msg}" + ) + + # See [Backward Generation Handling] + device_idx = boxed_device_index.value + if device_idx is None: + device_idx = 0 # Default to device 0 if not set + manager = torch._inductor.cudagraph_trees.get_manager( + device_idx, create_if_none_exists=False + ) + if manager is None: + raise AssertionError("cudagraph manager must exist for backward") + + def fn(inputs: list[Any]) -> Any: + # pyrefly: ignore [missing-attribute] + manager.set_to_running_backward() + return aot_model(inputs) + + fn._boxed_call = True # type: ignore[attr-defined] + return fn + + out = cudagraphify_impl( + interp, + aot_inputs, + range(fixed), + device_index=get_device_index(aot_model), + is_backward=True, + is_inference=False, + stack_traces=get_stack_traces(aot_model), + placeholders=get_placeholder_info(aot_model.graph), + mutated_input_idxs=find_input_mutations(aot_model.graph), + ) + out._boxed_call = True # type: ignore[attr-defined] + return out + + aot_cudagraphs = aot_autograd( + fw_compiler=forward_cudagraphs, + bw_compiler=backward_cudagraphs, + inference_compiler=functools.partial(forward_cudagraphs, is_inference=True), + keep_inference_input_mutations=torch._dynamo.config.cudagraph_backend_keep_input_mutation, + ) + return aot_cudagraphs(dynamo_model, dynamo_inputs) + + +class CudagraphsBackend: + compiler_name = "cudagraphs" + + @staticmethod + def reset() -> None: + from torch._inductor.cudagraph_trees import reset_cudagraph_trees + + reset_cudagraph_trees() + + @staticmethod + def __call__( + model: torch.fx.GraphModule, inputs: Sequence[Any], **kwargs: Any + ) -> Any: + if kwargs: + log.warning("cudagraphs backend ignoring extra kwargs %s", kwargs) + return cudagraphs(model, inputs) + + +# aot_cudagraphs only applies CUDA graphs to the graph. It is also helpful +# for debugging and can serve as a perf baseline. +register_backend(name="cudagraphs", compiler_fn=CudagraphsBackend()) + + +def cudagraphs_inner( + model: Callable[..., Any], + inputs: Sequence[Any], + copy_outputs: bool = True, + copy_inputs: bool = True, +) -> Callable[..., Sequence[Any]]: + """This isn't registered as a backend, but is used in some benchmarks""" + if not isinstance(inputs, (list, tuple)): + raise AssertionError( + f"Expected inputs to be a list or tuple, got {type(inputs)}" + ) + if copy_inputs: + static_inputs = [torch.zeros_like(x) for x in inputs] + else: + static_inputs = list(inputs) + + # warmup + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + model(*inputs) + stream.synchronize() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + + # record + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + static_outputs = model(*static_inputs) + if not isinstance(static_outputs, (list, tuple)): + static_outputs = (static_outputs,) + + def run(*new_inputs: Any) -> Sequence[Any]: + if len(static_inputs) != len(new_inputs): + raise AssertionError( + f"Expected {len(static_inputs)} inputs, got {len(new_inputs)}" + ) + if copy_inputs: + for dst, src in zip(static_inputs, new_inputs): + dst.copy_(src) + graph.replay() + if copy_outputs: + return [x.clone() for x in static_outputs] + else: + return static_outputs + + return run diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/debugging.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/debugging.py new file mode 100644 index 0000000000000000000000000000000000000000..63c9728091c92c675753b1f763312dc7647ec729 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/debugging.py @@ -0,0 +1,742 @@ +""" +This module provides debugging backends for TorchDynamo to help diagnose and troubleshoot +compilation and execution issues. It includes: + +Key Debugging Backends: +- eager: Simple pass-through backend that runs models in eager mode +- eager_noexcept: Similar to eager but with additional exception handling +- eager_debug: Adds schema validation checks for custom operators +- aot_eager: Uses AOT Autograd with nop compiler for debugging +- aot_eager_decomp_partition: Uses TorchInductor decompositions for debugging +- torchscript: Compiles using TorchScript for debugging JIT-related issues + +Testing and Development Tools: +- Backends for inducing specific errors (compile/runtime/accuracy) +- ExplainOutput class for detailed graph compilation analysis +- Utilities for cross-referencing and mode management +- Tools for graph detail inspection and break reason analysis + +These backends are primarily used for: +1. Debugging graph breaks and compilation failures +2. Testing error handling and recovery mechanisms +3. Analyzing performance bottlenecks +4. Validating operator schemas and decompositions +""" + +import dataclasses +import functools +import logging +from collections.abc import Callable, Iterable +from importlib import import_module +from typing import Any, TYPE_CHECKING + +import torch +from functorch.compile import min_cut_rematerialization_partition +from torch import _guards +from torch._dynamo.output_graph import GraphCompileReason +from torch._functorch import config as functorch_config +from torch._functorch.compilers import ts_compile +from torch._inductor.output_code import OutputCode + +from .common import aot_autograd +from .registry import CompiledFn, CompilerFn, register_debug_backend as register_backend + + +if TYPE_CHECKING: + from torch.fx.node import Target + + +log = logging.getLogger(__name__) + + +@register_backend +def eager( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + if kwargs: + log.warning("eager backend ignoring extra kwargs %s", kwargs) + + if torch._functorch.config.force_autograd_cache: + from torch._dynamo.aot_compile_types import GraphModuleSerializableCallable + + return GraphModuleSerializableCallable(gm) + return gm.forward + + +def make_eager_backend_with_torch_function_mode( + mode: torch.overrides.TorchFunctionMode, +) -> Callable[..., Any]: + return make_eager_backend_with_torch_function_modes([mode]) + + +def make_eager_backend_with_torch_function_modes( + modes: Iterable[torch.overrides.TorchFunctionMode], +) -> Callable[..., Any]: + """Used to trace HOPs (cond and while) for eager execution, the metadata + TF mode mutates vars outside of the scope of the HOP, and we can't have graph breaks + in the HOP, so we need to externally run this mode and not trace it.""" + from contextlib import ExitStack + + def fn( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any + ) -> Callable[..., Any]: + def wrapper(*args: Any, **kwargs: Any) -> Any: + with ExitStack() as stack: + for mode in modes: + stack.enter_context(mode) + return gm.forward(*args, **kwargs) + + return wrapper + + return fn + + +@register_backend +def eager_noexcept( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + if kwargs: + log.warning("eager_noexcept backend ignoring extra kwargs %s", kwargs) + + # This backend is intended to check that dynamo-generated GraphModules + # do not cause errors. + def inner(*args: Any) -> Any: + try: + return gm(*args) + except Exception as e: + raise torch._dynamo.exc.TorchDynamoException( + "Unexpected exception when running generated GraphModule" + ) from e + + return inner + + +@register_backend +def pre_dispatch_eager( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> torch.fx.GraphModule: + if kwargs: + log.warning("pre_dispatch_eager backend ignoring extra kwargs %s", kwargs) + + from torch.fx.experimental.proxy_tensor import make_fx + + def runnable_gm(*args: Any) -> Any: + return torch.fx.Interpreter(gm).run(*args) + + pre_dispatch_gm = make_fx(runnable_gm, pre_dispatch=True)(*fake_tensor_inputs) + pre_dispatch_gm.print_readable() + + return pre_dispatch_gm + + +@register_backend +def eager_debug( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + if kwargs: + log.warning("eager_debug backend ignoring extra kwargs %s", kwargs) + + from torch._subclasses.schema_check_mode import SchemaCheckMode + + # We could add more debugging bits here. + # Right now, this backend can be used to check for and error on + # custom dispatcher ops that have incorrect schemas. + def inner(*args: Any) -> Any: + with SchemaCheckMode(): + return torch.fx.Interpreter(gm).run(*args) + + return inner + + +@register_backend(name="ts") # type: ignore[misc] +def torchscript( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor] +) -> torch.jit.ScriptModule: + from torch.fx._lazy_graph_module import _unwrap_lazy_graph_module + + return torch.jit.script(_unwrap_lazy_graph_module(gm)) + + +def invoke_subgraph_inner_compiler( + subgraph: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> Callable[..., Any]: + """Inner compiler that wraps forward/backward graphs in invoke_subgraph HOP. + + This is used as the fw_compiler/bw_compiler for aot_autograd. When the resulting + function is traced by make_fx, it emits an invoke_subgraph HOP instead of inlining. + """ + from torch._dynamo import disable + from torch._higher_order_ops.invoke_subgraph import invoke_subgraph_infer + + # pyrefly: ignore [deprecated] + @torch._dynamo.allow_in_graph + @disable + def invoke_subgraph_wrapper_unboxed(*operands: Any) -> Any: + return invoke_subgraph_infer(subgraph, *operands) + + # NB: The direct to unboxed path is broken, you MUST DO THIS + + def invoke_subgraph_wrapper(args: list[Any]) -> Any: + # `allow_in_graph` is untyped and its `list` branch leaks a + # `list | fn` union into the inferred return; as the outer decorator + # here that makes `invoke_subgraph_wrapper_unboxed` look non-callable. + # pyrefly: ignore [not-callable] + return invoke_subgraph_wrapper_unboxed(*args) + + invoke_subgraph_wrapper._boxed_call = True # type: ignore[attr-defined] + + return invoke_subgraph_wrapper + + +# I cannot say how many times I had to revert to this vibe coded version of +# the code, which worked, and the cleaner versions of the code did not work, +# so I'm leaving this here until we fix the rest of the bugs. +''' +# Counter for unique subgraph names in invoke_subgraph backend +_invoke_subgraph_counter = 0 + + +def invoke_subgraph_inner_compiler_good( + fx_g: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> Callable[..., Any]: + """Inner compiler that wraps forward/backward graphs in invoke_subgraph HOP. + + This is used as the fw_compiler/bw_compiler for aot_autograd. When the resulting + function is traced by make_fx, it emits an invoke_subgraph HOP instead of inlining. + """ + from torch._higher_order_ops.invoke_subgraph import ( + invoke_subgraph as invoke_subgraph_hop, + ) + from torch.fx.experimental.proxy_tensor import get_proxy_mode + + global _invoke_subgraph_counter + _invoke_subgraph_counter += 1 + name = f"invoke_subgraph_{_invoke_subgraph_counter}" + + from torch._dynamo import disable + + # Check if fx_g uses boxed calling convention + fx_g_is_boxed = getattr(fx_g, "_boxed_call", False) + + @disable + @torch._dynamo.allow_in_graph + def invoke_subgraph_wrapper_unboxed(*args: Any) -> Any: + proxy_mode = get_proxy_mode() + if proxy_mode is not None: + # When being traced by make_fx, emit invoke_subgraph HOP + return invoke_subgraph_hop(fx_g, name, *args) # type: ignore[arg-type] + else: + # Normal execution path - call fx_g with proper calling convention + if fx_g_is_boxed: + return fx_g(list(args)) + else: + return fx_g(*args) + + # Wrap to handle boxed arguments (list of args) as expected by AOTAutograd + def invoke_subgraph_wrapper(args: list[Any]) -> Any: + return invoke_subgraph_wrapper_unboxed(*args) + + invoke_subgraph_wrapper._boxed_call = True # type: ignore[attr-defined] + return invoke_subgraph_wrapper +''' + + +@register_backend +def invoke_subgraph( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + """Backend that wraps forward/backward graphs in invoke_subgraph HOP when traced by make_fx. + + This backend uses AOTAutograd to partition into forward/backward graphs, then wraps + each in an invoke_subgraph HOP. This is useful for recursive Dynamo tracing scenarios + where you want the compiled subgraph to appear as invoke_subgraph HOPs in the outer + trace rather than being inlined. + + Requires: + - torch._dynamo.config.force_compile_during_fx_trace = True + (this implicitly overrides error_on_nested_fx_trace) + """ + if kwargs: + log.warning("invoke_subgraph backend ignoring extra kwargs %s", kwargs) + + # Use AOTAutograd to partition into forward/backward + return aot_autograd( + fw_compiler=invoke_subgraph_inner_compiler, + bw_compiler=invoke_subgraph_inner_compiler, + partition_fn=min_cut_rematerialization_partition, + keep_inference_input_mutations=True, + )(gm, fake_tensor_inputs) + + +@dataclasses.dataclass +class AOTEagerOutputCode(OutputCode): + """ + An OutputCode that wraps a GraphModule for eager-mode execution. + + This allows non-inductor backends (like aot_eager) to participate in + the bundled autograd cache and aot_compile serialization flow. + """ + + gm: torch.fx.GraphModule | None = None + _serialized_gm: bytes | None = dataclasses.field(default=None, init=False) + + def __call__(self, inputs: Any) -> Any: + if self.gm is None: + raise AssertionError("gm must not be None") + return self.gm.forward(inputs) + + def prepare_for_serialization(self) -> None: + from torch.fx._graph_pickler import GraphPickler, Options + + if self.gm is None: + raise AssertionError("gm must not be None") + for node in self.gm.graph.nodes: + node.meta.pop("nn_module_stack", None) + node.meta.pop("source_fn_stack", None) + node.meta.pop("example_value", None) + + self._serialized_gm = GraphPickler.dumps(self.gm, Options(ops_filter=None)) + self.gm = None + + def post_compile(self, *args: Any, **kwargs: Any) -> None: + if self.gm is None and self._serialized_gm is not None: + from torch._subclasses import FakeTensorMode + from torch.fx._graph_pickler import GraphPickler + from torch.fx.experimental.symbolic_shapes import ShapeEnv + from torch.fx.graph import _BoxedCodeGen + + fake_mode = FakeTensorMode(shape_env=ShapeEnv()) + gm = GraphPickler.loads(self._serialized_gm, fake_mode) + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"Expected torch.fx.GraphModule, got {type(gm)}") + self.gm = gm + self.gm.graph.set_codegen(_BoxedCodeGen()) + self.gm.recompile() + self._serialized_gm = None + + def set_triton_bundle(self, triton_bundle: Any) -> None: + pass + + +# used boxed call to discard inputs when they are no longer needed +def boxed_nop( + fx_g: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> Callable[..., Any]: + from torch.fx.graph import _BoxedCodeGen + + # Set the graph to use boxed codegen + fx_g.graph.set_codegen(_BoxedCodeGen()) + fx_g.recompile() + + if functorch_config.force_autograd_cache or functorch_config.bundled_autograd_cache: + result = AOTEagerOutputCode(gm=fx_g) + result._boxed_call = True # type: ignore[attr-defined] + return result + + # Wrap the forward method in a function so we can set _boxed_call attribute + forward_fn = fx_g.forward + + def run(args: Any) -> Any: + from torch.utils._debug_mode import DebugInterpreter, get_active_debug_mode + + if ( + debug_mode := get_active_debug_mode() + ) is not None and debug_mode.run_compile_with_interpreter: + return DebugInterpreter(fx_g, backend="aot_eager").run(*args) + return forward_fn(args) + + run._boxed_call = True # type: ignore[attr-defined] + return run + + +def boxed_nop_with_mode( + fx_g: torch.fx.GraphModule, + example_inputs: list[torch.Tensor], + *, + mode: torch.overrides.TorchFunctionMode, +) -> Callable[..., Any]: + from torch.fx.graph import _BoxedCodeGen + + # Set the graph to use boxed codegen + fx_g.graph.set_codegen(_BoxedCodeGen()) + fx_g.recompile() + + # Create a wrapper that runs with the mode + forward_fn = fx_g.forward + + def run(args: Any) -> Any: + with mode: + return forward_fn(args) + + run._boxed_call = True # type: ignore[attr-defined] + return run + + +def fake_crossref_boxed_nop( + fx_g: torch.fx.GraphModule, + example_inputs: list[torch.Tensor], + ignore_op_fn: Callable[[torch._ops.OpOverload], bool] | None = None, +) -> Callable[..., Any]: + from torch.fx.graph import _BoxedCodeGen + + # Set the graph to use boxed codegen + fx_g.graph.set_codegen(_BoxedCodeGen()) + fx_g.recompile() + + # Create a wrapper that runs with the mode + forward_fn = fx_g.forward + + def run(args: Any) -> Any: + with torch._subclasses.CrossRefFakeMode(ignore_op_fn): + return forward_fn(args) + + run._boxed_call = True # type: ignore[attr-defined] + return run + + +def ignore_builtins(op: torch._ops.OpOverload) -> bool: + return op.namespace in ("aten", "prims", "prim") + + +def get_nop_func() -> Callable[ + [torch.fx.GraphModule, list[torch.Tensor]], Callable[..., Any] +]: + if not torch._functorch.config.fake_tensor_crossref: + return boxed_nop + elif torch._functorch.config.fake_tensor_crossref == "all": + return fake_crossref_boxed_nop + else: + if torch._functorch.config.fake_tensor_crossref != "custom_ops": + raise AssertionError( + f"Expected fake_tensor_crossref to be 'custom_ops', " + f"got {torch._functorch.config.fake_tensor_crossref!r}" + ) + return functools.partial(fake_crossref_boxed_nop, ignore_op_fn=ignore_builtins) + + +# Useful for debugging purpose +# aot_eager uses AOT Autograd backend with nop compiler. It is helpful in debugging. +def aot_eager( + gm: torch.fx.GraphModule, + fake_tensor_inputs: list[torch.Tensor], + fw_compiler: Callable[..., Any] | None = None, + bw_compiler: Callable[..., Any] | None = None, + **kwargs: Any, +) -> Callable[..., Any]: + return aot_autograd( + fw_compiler=fw_compiler or boxed_nop, + bw_compiler=bw_compiler or boxed_nop, + partition_fn=min_cut_rematerialization_partition, + keep_inference_input_mutations=True, + )(gm, fake_tensor_inputs, **kwargs) + + +register_backend(name="aot_eager", compiler_fn=aot_eager) + +aot_eager_default_partitioner = aot_autograd( + fw_compiler=boxed_nop, keep_inference_input_mutations=True +) +register_backend( + name="aot_eager_default_partitioner", compiler_fn=aot_eager_default_partitioner +) + + +# Uses TorchInductor AOT Autograd decomps and partitioner to isolate aot vs +# inductor problems. +# aot_eager_decomp_partition just replaces the inductor compiler with nop to help +# isolate inductor vs aot_eager errors +def aot_eager_decomp_partition( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + if kwargs: + log.warning( + "aot_eager_decomp_partition backend ignoring extra kwargs %s", kwargs + ) + + from torch._inductor.compiler_bisector import CompilerBisector + + config_patches = {"unlift_effect_tokens": True} + if bisect_changes := CompilerBisector.get_config_change( + "aot_eager_decomp_partition" + ): + config_patches.update(bisect_changes) # type: ignore[arg-type] + + with functorch_config.patch(config_patches): + return aot_autograd( + # these are taken from memory_efficient_fusion() + fw_compiler=get_nop_func(), + bw_compiler=get_nop_func(), + # NB: lambda here is to delay import of inductor + decompositions=lambda: import_module( + "torch._inductor.compile_fx" + ).select_decomp_table(), + partition_fn=functools.partial( + min_cut_rematerialization_partition, compiler="inductor" + ), + )(gm, fake_tensor_inputs) + + +register_backend( + name="aot_eager_decomp_partition", compiler_fn=aot_eager_decomp_partition +) + + +# aot_eager_decomp_partition_with_mode is similar as aot_eager_decomp_partition, +# except that it takes a TorchDispatchMode mode and run the fw/bw in the mode +def aot_eager_decomp_partition_with_mode( + gm: torch.fx.GraphModule, + fake_tensor_inputs: list[torch.Tensor], + mode: Any, + **kwarg: Any, +) -> Callable[..., Any]: + return aot_autograd( + # these are taken from memory_efficient_fusion() + fw_compiler=functools.partial(boxed_nop_with_mode, mode=mode), + bw_compiler=functools.partial(boxed_nop_with_mode, mode=mode), + # NB: lambda here is to delay import of inductor + decompositions=lambda: import_module( + "torch._inductor.compile_fx" + ).select_decomp_table(), + partition_fn=functools.partial( + min_cut_rematerialization_partition, compiler="inductor" + ), + )(gm, fake_tensor_inputs) + + +register_backend( + name="aot_eager_decomp_partition_with_mode", + compiler_fn=aot_eager_decomp_partition_with_mode, # type: ignore[arg-type] +) + + +def aot_eager_decomp_partition_crossref( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + # if the config is set, respect it, otherwise only test custom_ops. + # custom_op bad metas always manifest as an error whereas aten will only sometimes. + # by default, use the less noisy option + config_val = ( + "custom_ops" + if not functorch_config.fake_tensor_crossref + else functorch_config.fake_tensor_crossref + ) + with functorch_config.patch(fake_tensor_crossref=config_val): + return aot_eager_decomp_partition(gm, fake_tensor_inputs, **kwargs) + + +register_backend( + name="aot_eager_decomp_partition_crossref", + compiler_fn=aot_eager_decomp_partition_crossref, +) + + +# AOT Autograd with torchscript backend. Default partitioner. +# aot_ts uses torchscript backend. We can use this with both nnc and nvfuser +# by using the relevant fuser with torch.jit.fuser(...) +aot_ts = aot_autograd(fw_compiler=ts_compile) +register_backend(name="aot_ts", compiler_fn=aot_ts) + +# These buggy backends are used for inducing bugs so that we can test +# our repro extraction / minifier scripts + + +class ReluCompileError(Exception): + pass + + +class TestingOnlyCompileError(Exception): + pass + + +@register_backend +def relu_compile_error_TESTING_ONLY( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> torch.fx.GraphModule: + for node in gm.graph.nodes: + if node.target is torch.relu: + raise ReluCompileError + return gm + + +@register_backend +def relu_runtime_error_TESTING_ONLY( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> torch.fx.GraphModule: + for node in gm.graph.nodes: + if node.target is torch.relu: + node.target = torch._assert + node.args = (False, "ReluRuntimeError") + gm.recompile() + return gm + + +@register_backend +def relu_accuracy_error_TESTING_ONLY( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> torch.fx.GraphModule: + for node in gm.graph.nodes: + if node.target is torch.relu: + node.target = torch.add + node.args = (node.args[0], 1) + gm.recompile() + + return gm + + +@register_backend +def non_leaf_compile_error_TESTING_ONLY( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> torch.fx.GraphModule: + # Require at least one non-trivial thing in the graph, + # see https://github.com/pytorch/pytorch/issues/102898 + for node in gm.graph.nodes: + if node.op == "call_function": + break + else: + return gm + for t in example_inputs: + if not t.is_leaf: + raise TestingOnlyCompileError + return gm + + +@dataclasses.dataclass +class ExplainOutput: + """ + This is the output of :func:`torch._dynamo.explain()` + There is no reason to create this class directly. + """ + + graphs: list[torch.fx.GraphModule] + graph_count: int + graph_break_count: int + break_reasons: list[GraphCompileReason] + op_count: int + ops_per_graph: list[list["Target"]] | None = None + out_guards: list[_guards.Guard] | None = None + compile_times: str | None = None + + def __str__(self) -> str: + output = f"Graph Count: {self.graph_count}\n" + output += f"Graph Break Count: {self.graph_break_count}\n" + output += f"Op Count: {self.op_count}\n" + + output += "Break Reasons:\n" + for idx, break_reason in enumerate(self.break_reasons): + output += f" Break Reason {idx + 1}:\n" + output += f" Reason: {break_reason.reason}\n" + output += " User Stack:\n" + for frame_summary in break_reason.user_stack: + output += f" {frame_summary}\n" + + if self.ops_per_graph is not None: + output += "Ops per Graph:\n" + for idx, ops in enumerate(self.ops_per_graph): + output += f" Ops {idx + 1}:\n" + for op in ops: + output += f" {op}\n" + + if self.out_guards is not None: + output += "Out Guards:\n" + for i, guard in enumerate(self.out_guards): + output += f" Guard {i + 1}:\n" + output += f" {str(guard)}" + + if self.compile_times is not None: + output += f"Compile Times: {self.compile_times}\n" + return output + + +def _explain_graph_detail( + gm: torch.fx.GraphModule, + graphs: list[torch.fx.GraphModule], + op_count: int, + ops_per_graph: list[list["Target"]], + break_reasons: list[GraphCompileReason], +) -> tuple[ + torch.fx.GraphModule, + list[torch.fx.GraphModule], + int, + list[list["Target"]], + list[GraphCompileReason], +]: + """ + This function is a utility which processes a torch.fx.GraphModule and + accumulates information about its ops, graph breaks, and other details. It + is intended to be used by the ExplainWithBackend class and + `torch._dynamo.explain()` to provide details from Dynamo's graph capture. + + Parameters: + gm (torch.fx.GraphModule): The GraphModule to be processed. + graphs (list): A list that accumulates all the GraphModules processed. + op_count (int): The total count of operations in all GraphModules processed so far. + ops_per_graph (list): A list that accumulates the operations of each GraphModule. + break_reasons (list): A list that accumulates the reasons for breaks in each GraphModule. + + Returns: + tuple: A tuple containing the processed GraphModule, the updated lists of graphs, + operations per graph, and break reasons, and the updated operation count. + """ + graphs.append(gm) + ops = [node.target for node in gm.graph.nodes if node.op == "call_function"] + op_count += len(ops) + ops_per_graph.append(ops) + if gm.compile_subgraph_reason.graph_break: # type: ignore[union-attr] + break_reasons.append(gm.compile_subgraph_reason) # type: ignore[arg-type] + + return gm, graphs, op_count, ops_per_graph, break_reasons + + +class ExplainWithBackend: + """ + This class is intended to be used as a backend for `torch.compile`. It is + composable with other backends. When used in this way, it accumulates + information about graph breaks, ops, and other info and provides a string + representation summarizing this information. + + Attributes: + backend (str): The name of the backend to use for optimization. + graphs (list): A list of the graphs captured by TorchDynamo. + op_count (int): The total number of operations in all optimized graphs. + break_reasons (list): A list of graph break reasons with stack traces. + + Example Usage: + def fn(x): + x = torch.sigmoid(x) + return x + + torch._dynamo.reset() + eb = ExplainWithBackend("inductor") + optimized_fn = torch.compile(fn, backend=eb) + result = optimized_fn(torch.randn(5)) + print(eb.output()) + """ + + def __init__(self, backend: CompilerFn | str) -> None: + from .registry import lookup_backend + + self.backend = lookup_backend(backend) + self.graphs: list[torch.fx.GraphModule] = [] + self.op_count = 0 + self.break_reasons: list[GraphCompileReason] = [] + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> CompiledFn: + ops_per_graph: list[list[Target]] = [] + gm, self.graphs, self.op_count, _, self.break_reasons = _explain_graph_detail( + gm, self.graphs, self.op_count, ops_per_graph, self.break_reasons + ) + return self.backend(gm, example_inputs) + + def output(self) -> ExplainOutput: + graph_count = len(self.graphs) + output = ExplainOutput( + self.graphs, + graph_count, + graph_count - 1, + self.break_reasons, + self.op_count, + ) + + return output diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/distributed.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..f09ce836273288eb345cb86f1afae3d1cd0f32af --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/distributed.py @@ -0,0 +1,647 @@ +""" +This module implements distributed training optimizations for TorchDynamo backends. + +It provides functionality to optimize models wrapped in DistributedDataParallel (DDP) +by intelligently splitting compiled graphs to align with DDP's gradient synchronization +boundaries. Key features include: + +- Graph partitioning based on parameter bucket sizes +- Optimization of allreduce operations for distributed training +- Support for parameter ignoring and buffer handling +- Submodule compilation and management +- Debugging utilities for distributed training + +The main component is the DDPOptimizer class, which handles graph splitting and +recompilation to enable efficient distributed training while maintaining the benefits +of compilation. +""" + +import logging +import traceback +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Any, TYPE_CHECKING +from unittest import mock + +import torch +from torch import fx +from torch._dynamo.backends.registry import CompiledFn, CompilerFn +from torch._dynamo.output_graph import GraphCompileReason +from torch._dynamo.utils import deepcopy_to_fake_tensor, detect_fake_mode +from torch._logging import trace_structured +from torch.fx.node import Node + + +if TYPE_CHECKING: + from torch._functorch._aot_autograd.schemas import ViewAndMutationMeta + + +# Regular log messages should go through 'log'. +# ddp_graph_log is a separate artifact logger reserved for dumping graphs. +# See docs/source/logging.rst for more info. +log = logging.getLogger(__name__) +ddp_graph_log = torch._logging.getArtifactLogger(__name__, "ddp_graphs") + + +def args_str(args: Any) -> str: + # a debug helper + if torch.is_tensor(args): + return f"T[{args.shape}]" + elif isinstance(args, tuple): + return f"tuple({', '.join([args_str(x) for x in args])})" + elif isinstance(args, list): + return f"list({', '.join([args_str(x) for x in args])})" + else: + return str(args) + + +@dataclass +class Bucket: + size: int = 0 + params: list[str] = field(default_factory=list) + nodes: list[fx.Node] = field(default_factory=list) + + # param_ids is just used for unit testing + param_ids: list[int] = field(default_factory=list) + + # keep track of any buckets that were extended for logging purposes + opcount_increased_to_capture_external_output: int = 0 + paramsize_before_opcount_increase: int = 0 + + +def bucket_has_external_output(bucket: Bucket) -> bool: + nodes_in_bucket = set() + # we want to iterate in reverse order, but clumsi-luckily the bucket.nodes list was already created backwards + # so we don't reverse it here + for node in bucket.nodes: + # assume node.op != output, since those are filtered in the original iteration + nodes_in_bucket.add(node) + for user in node.users: + if user not in nodes_in_bucket: + return True + return False + + +def pretty_print_buckets(buckets: list[Bucket], bucket_bytes_cap: int) -> None: + headers = ("Index", "Size (b)", "Param Names") + rows: list[tuple[int | None, int | None, str]] = [] + # pyrefly: ignore [implicit-any] + extended_buckets = [] + for idx, bucket in enumerate(reversed(buckets)): + if len(bucket.params) > 0: + rows.append((idx, bucket.size, bucket.params[0])) + rows.extend((None, None, param) for param in bucket.params[1:]) + if bucket.opcount_increased_to_capture_external_output > 0: + extended_buckets.append( + ( + idx, + bucket.opcount_increased_to_capture_external_output, + bucket.size - bucket.paramsize_before_opcount_increase, + ) + ) + + if rows: + log.info( + "\nDDPOptimizer used bucket cap %s and created %d buckets. Enable debug logs for detailed bucket info.", + bucket_bytes_cap, + len(buckets), + ) + + if extended_buckets: + log.warning( + "Some buckets were extended beyond their requested parameter capacities" + " in order to ensure each subgraph has an output node, required for fx graph partitioning." + " This can be the case when a subgraph would have only contained nodes performing inplace mutation," + " and returning no logical outputs. This should not be a problem, unless it results in too few graph" + " partitions for optimal DDP performance." + ) + + try: + from tabulate import tabulate + + log.debug( + "\nDDPOptimizer produced the following bucket assignments:\n%s", + tabulate(rows, headers=headers, tablefmt="simple_grid"), + ) + + if extended_buckets: + log.warning( + "DDPOptimizer extended these buckets to ensure per-subgraph output nodes:\n%s", + tabulate( + extended_buckets, + headers=("Index", "Extra Ops", "Extra Param Size (b)"), + tablefmt="simple_grid", + ), + ) + except ImportError: + log.debug( + "Please `pip install tabulate` in order to display ddp bucket sizes and diagnostic information." + ) + else: + log.debug("DDPOptimizer captured no parameters and did not split this graph.") + + +def has_higher_order_op(gm: fx.GraphModule) -> bool: + # Check if there is a higher order op in the graph + for node in gm.graph.nodes: + if node.op == "get_attr": + maybe_param = getattr(gm, node.target) + if isinstance(maybe_param, torch.fx.GraphModule): + return True + return False + + +def propagate_metadata(orig_gm: fx.GraphModule, split_gm: fx.GraphModule) -> None: + # Only propagate to partition submodules, not to HOP body subgraphs (e.g. + # wrap_body_*) which are also hoisted as top-level children by split_module + # and carry their own metadata (e.g. _checkpoint_context_fn for SAC). + partition_names = split_gm.meta["partition_names"] + for name, module in split_gm.named_modules(): + if name in partition_names: + # TODO: add split id to CompileId: https://github.com/pytorch/tlparse/pull/83/files#r1880649384 + module.meta = orig_gm.meta + module._param_name_to_source = orig_gm._param_name_to_source + + +def propagate_dynamo_source(orig_gm: fx.GraphModule, split_gm: fx.GraphModule) -> None: + name_to_dynamo_source = {} + for node in orig_gm.graph.find_nodes(op="placeholder"): + name_to_dynamo_source[node.name] = node._dynamo_source + + partition_names = split_gm.meta["partition_names"] + for name, module in split_gm.named_modules(): + if name in partition_names: + for node in module.graph.find_nodes(op="placeholder"): + # non-placeholder in original_gm may become placeholder in submodules + node._dynamo_source = name_to_dynamo_source.get(node.name) + + +class DDPOptimizerContext: + def __init__(self) -> None: + self.curr_bucket: int = -1 + self.metadata_per_bucket: list[ViewAndMutationMeta] = [] + + +# compile each of the partitioned submodules using the user-provided compiler +class SubmodCompiler(torch.fx.interpreter.Interpreter): + def __init__( + self, + module: fx.GraphModule, + compiler: CompilerFn, + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode, + **compiler_configs: Any, + ) -> None: + super().__init__(module) + self.compiler = compiler + self.compiler_configs = compiler_configs + self.fake_mode = fake_mode + # See Note [DDPOptimizer and fw_metadata] + ctx = torch._guards.TracingContext.try_get() + if ctx is not None: + ctx.ddp_optimizer_ctx = DDPOptimizerContext() + + def compile_submod( + self, input_mod: fx.GraphModule, args: list[torch.Tensor], kwargs: Any + ) -> Any: + """ + Compile the submodule, + using a wrapper to make sure its output is always a tuple, + which is required by AotAutograd based compilers + """ + if len(kwargs) != 0: + raise AssertionError("We assume only args for these modules") + + class WrapperModule(torch.nn.Module): + def __init__( + self, submod: Callable[..., Any], unwrap_singleton_tuple: bool + ) -> None: + super().__init__() + self.submod = submod + self.unwrap_singleton_tuple = unwrap_singleton_tuple + + def forward(self, *args: Any) -> Any: + x = self.submod(*args) + # TODO(whc) + # for some reason the isinstance check is necessary if I split one node per submod + # - even though I supposedly wrapped the output in a tuple in those cases, the real + # compiled module was still returning a tensor + if self.unwrap_singleton_tuple and isinstance(x, (tuple, list)): + return x[0] + return x + + unwrap_singleton_tuple = False + for sn in input_mod.graph.nodes: + if sn.op == "output": + if not isinstance(sn.args[0], tuple): + unwrap_singleton_tuple = True + sn.args = (sn.args,) + + input_mod.recompile() + input_mod.compile_subgraph_reason = GraphCompileReason( # type: ignore[assignment] + "DDPOptimizer intentional graph-break (See Note [DDPOptimizer])." + " Set `torch._dynamo.config.optimize_ddp = False` to disable.", + [ + # it's close to useless to get a real stacktrace here, and quite verbose. + traceback.FrameSummary(__file__, 0, "DDPOptimizer"), + ], + ) + + wrapper = WrapperModule( + self.compiler(input_mod, args, **self.compiler_configs), + unwrap_singleton_tuple, + ) + return wrapper + + # Note: + # + # The way distributed works today around fake tensors can be somewhat confusing. + # Some of these codepaths are shared in both runtime, and compile time. The presence + # of a fake_mode, read off of fake tensor inputs, dictates how we will operate. + # + # A few things to keep in mind: + # + # 1) We invoke `compile_submod` with a real module. The output of that gets stored + # on the graph via `self.module.add_submodule(n.target, compiled_submod_real)`. + # + # 2) When running a call_module targeted node, if we have a fake_mode, we fakify the + # module we got from self.fetch_attr(n.target). Regardless of fake_mode, we then execute it. + # + # 3) Fake tensors should always be around during compile time. + # + # 4) Fake tensors should never be around at runtime. + # + # 5) We end up with a compilation mode that takes a real submodule and fake tensors, + # to match what aot_autograd expects. See Note: [Fake Modules and AOTAutograd] + def run_node(self, n: Node) -> Any: + args, kwargs = self.fetch_args_kwargs_from_env(n) + new_args = [] + if not self.fake_mode: + raise AssertionError("fake_mode must be set") + for arg in args: + if isinstance(arg, torch.Tensor) and not isinstance( + arg, torch._subclasses.FakeTensor + ): + new_args.append(torch._dynamo.utils.to_fake_tensor(arg, self.fake_mode)) + else: + new_args.append(arg) + + log.debug("run_node %s, %s got args %s", n.op, n.target, args_str(args)) + if not isinstance(args, tuple): + raise AssertionError(f"Expected args to be a tuple, got {type(args)}") + if not isinstance(kwargs, dict): + raise AssertionError(f"Expected kwargs to be a dict, got {type(kwargs)}") + + if n.op == "call_module": + real_mod = self.fetch_attr(str(n.target)) + if self.fake_mode: + curr_submod = deepcopy_to_fake_tensor(real_mod, self.fake_mode) + else: + curr_submod = real_mod + + ddp_graph_log.debug("\n---%s graph---\n%s", n.target, curr_submod.graph) + + # When calling the compiler on the submod, inputs (new_args) are expected to + # be FakeTensors already since Dynamo would have made them FakeTensors in the + # non-DDP flow. However, the parameters are _not_ expected to be FakeTensors, + # since this wrapping happens during compilation + + # Note: Returning Fake Tensors on First AOT Autograd Call + # + # Inductor will optimize strides of outputs when it deems it profitable. + # For instance, converting to channels last. When we split the graph here + # into multiple inductor compilations, we need to make sure that the + # output strides of one compilation is appropriately passed to the subsequent + # compilations. However, the mapping from inductor output to dynamo output + # is non-trivial due to aot_autograd's deduping, de-aliasing, mutation, re-writing, + # subclass handling, etc. In order to replay all this logic we set a flag such that + # the first invocation of inductor in aot_autograd will return Fake Tensors with + # appropriate strides. Then, all of aot autograd's runtime logic is replayed. + # This gives us the appropriately strided outputs here which will reflect runtime strides. + + class FakeifyFirstAOTInvocationGuard: + def __init__(self) -> None: + self.tc = torch._guards.TracingContext.try_get() + if not self.tc: + raise AssertionError("TracingContext must be set") + self.tc.fakify_first_call = True + + def __del__(self) -> None: + self.tc.fakify_first_call = False # type: ignore[union-attr] + + # For aot_eager and other backends, tracing context is not set + has_tracing_context = torch._guards.TracingContext.try_get() is not None + if has_tracing_context: + g = FakeifyFirstAOTInvocationGuard() # noqa: F841 + + from torch._dynamo.utils import counters + + init = counters["aot_autograd"]["total"] + compiled_submod_real = self.compile_submod(real_mod, new_args, kwargs) + + # TODO - better way of doing this? + # Only aot autograd handles fakifying first call + invoked_aot_autograd = init != counters["aot_autograd"]["total"] + + # We update the original (outer) graph with a call into the compiled module + # instead of the uncompiled one. + self.module.delete_submodule(n.target) # type: ignore[operator] + n.target = "compiled_" + n.target # type: ignore[operator] + self.module.add_submodule(n.target, compiled_submod_real) # type: ignore[operator] + + # Finally, we have to produce inputs for use compiling the next submodule, + # and these need to be FakeTensors, so we execute the module under fake_mode + # Because parameters are not fake we patch fake tensor mode to allow non fake inputs + with ( + self.fake_mode, + mock.patch.object(self.fake_mode, "allow_non_fake_inputs", True), + ): + if has_tracing_context and invoked_aot_autograd: + tracing_ctx = torch._guards.TracingContext.try_get() + if tracing_ctx is None: + raise AssertionError("TracingContext must not be None") + # DDPOptimizer maintains 1 dynamo graph -> N AOT graphs + # Dynamo only has 1 tracing context, so it needs to maintain all N AOT metadata instances + ddp_ctx = tracing_ctx.ddp_optimizer_ctx + if ddp_ctx is None: + raise AssertionError("ddp_optimizer_ctx must not be None") + if tracing_ctx.fw_metadata is None: + raise AssertionError("fw_metadata must not be None") + ddp_ctx.curr_bucket += 1 + ddp_ctx.metadata_per_bucket.append(tracing_ctx.fw_metadata) + + out = compiled_submod_real(*new_args, **kwargs) + # output should be fake or subclass + if not all( + (not isinstance(t, torch.Tensor) or type(t) is not torch.Tensor) + for t in (out if isinstance(out, (list, tuple)) else [out]) + ): + raise AssertionError( + "Output should be fake or subclass, not plain torch.Tensor" + ) + return out + else: + return curr_submod(*new_args, **kwargs) + else: + # placeholder or output nodes don't need to get compiled, just executed + return getattr(self, n.op)(n.target, new_args, kwargs) + + +class DDPOptimizer: + """Note [DDPOptimizer] + DDPOptimizer applies when dynamo compiles models wrapped in DistributedDataParallel (DDP), + breaking the dynamo graph into chunks to compile separately, with the breaks aligning to + the boundaries of gradient-allreduce buckets chosen by DDP. + + Background/Motivation + - DDP uses allreduce collectives to synchronize partial gradients computed on different workers + - DDP groups gradient allreduces into 'buckets' to optimize communication efficiency of all-reduce + - Parameters grouped into buckets are assumed to be adjacent in time, so they become ready + at around the same time during backward and thus can share the same allreduce efficiently + - Allreduces must overlap with backward compute for optimal training performance + - DDP schedules allreduces using 'hooks' fired from the c++ autograd engine in pytorch, which + operates when individual grads become 'ready' + - Dynamo+AOTAutograd produces a single fused graph that runs 'atomically' from the perspective of the + autograd engine, such that all gradients become 'ready' at the same time. Hooks fire after the whole + fused backward function executes, preventing any overlap of compute and communication + + Algorithm + - DDPOptimizer starts off with an FX graph traced by dynamo which represents forward. It can traverse + this graph in reverse order to determine the true order that gradients will become ready during backward. + - Parameter sizes are counted in reverse order, up to a bucket size limit, at which point a new bucket is started + and a graph break introduced + - Each of the subgraphs is compiled by the compiler provided to dynamo by the user, and then fused back together + into an outer module that is returned to the user + + Notes + - It would be better to enforce (by adding an API to DDP) that the bucket splits chosen here are used by DDP, + and that DDP does not need to detect or optimize bucket order by observing execution at runtime, as it does + in eager. + - If Dynamo can't capture a whole graph for the portion of the model wrapped by DDP, this algorithm will currently + produce splits that do not necessarily align with the buckets used by DDP. This should result in performance + degradation approaching the baseline case where graph-splits are not used, but not worse. + - If the backend compiler fails to compile a single subgraph, it will execute eagerly despite the rest of the + subgraphs being compiled + - DDP has a 'parameters_and_buffers_to_ignore' field, which DDPOptimizer attempts to honor by reading markers + left by DDP on individual parameters. In cases where other transformations, such as reparameterization, are + also used, the ignore markers could be lost. If DDPOptimizer fails to ignore a parameter ignored by DDP, + it is not catastrophic but could impact performance by choosing sub-optimal bucket splits. + - DDPOptimizer always ignores all buffers, regardless of their ignore flag, since buffers do not require gradients, + and therefore aren't allreduced by DDP. (They are broadcast during forward, but this is not covered by + DDPOptimizer) + + Debugging + - Generally, it is easiest to debug DDPOptimizer in a single process program, using pdb. + - In many cases, the log messages are helpful (they show bucket size assignments)- + just set TORCH_LOGS env to include any of 'dynamo', 'distributed', or 'dist_ddp'. + - See `benchmarks/dynamo/distributed.py` for a simple harness that will run a toy model or a torchbench model + in a single process (or with torchrun, in multiple processes) + + Args: + bucket_bytes_cap (int): Controls the size of buckets, in bytes, used to determine graphbreaks. Should be + set to match the equivalent parameter on the original DDP module. + + backend_compile_fn (callable): A dynamo compiler function, to be invoked to compile each subgraph. + + first_bucket_cap (int): Controls the size of the first bucket. Should match DDP's first bucket cap. DDP + special-cases the first bucket size since it is sometimes optimal to start a small allreduce early. + + """ + + def __init__( + self, + bucket_bytes_cap: int, + backend_compile_fn: CompilerFn, + first_bucket_cap: int | None = None, + ) -> None: + if first_bucket_cap is not None: + self.first_bucket_cap = first_bucket_cap + elif torch.distributed.is_available(): + # this constant comes from C10D lib which is not always built + self.first_bucket_cap = torch.distributed._DEFAULT_FIRST_BUCKET_BYTES + else: + self.first_bucket_cap = bucket_bytes_cap + + self.bucket_bytes_cap = bucket_bytes_cap + if self.first_bucket_cap > self.bucket_bytes_cap: + raise AssertionError( + "First bucket should be smaller/equal to other buckets to get comms warmed up ASAP" + ) + + self.backend_compile_fn = backend_compile_fn + + def _ignore_parameter(self, parameter: torch.nn.Parameter) -> bool: + return hasattr(parameter, "_ddp_ignored") and parameter._ddp_ignored + + def add_param(self, bucket: Bucket, param: torch.nn.Parameter, name: str) -> None: + bucket.size += param.untyped_storage().nbytes() + bucket.params.append(name) + bucket.param_ids.append(id(param)) + + def add_module_params_to_bucket( + self, + mod: torch.nn.Module, + bucket: Bucket, + processed_modules: set[torch.nn.Module], + prefix: str, + ) -> None: + processed_modules.add(mod) + for name, param in mod.named_parameters(): + if param.requires_grad and not self._ignore_parameter(param): + self.add_param(bucket, param, f"{prefix}_{name}") + + def add_param_args(self, bucket: Bucket, node: fx.Node) -> None: + for arg in node.args: + if not isinstance(arg, torch.fx.node.Node): + continue + if arg.op != "placeholder": + continue + param = arg.meta["example_value"] + if ( + isinstance(param, torch.nn.Parameter) + and param.requires_grad + and not self._ignore_parameter(param) + ): + self.add_param(bucket, param, str(arg.target)) + + def compile_fn( + self, + gm: fx.GraphModule, + example_inputs: list[torch.Tensor], + **compiler_configs: Any, + ) -> CompiledFn: + """ + Implements graph splitting, first determining a set of buckets by counting + parameter sizes in reverse graph order, then invoking the user/backend compiler + to compile each subgraph. Finally, stitches compiled graphs into one graphmodule + and returns its callable. + """ + # 1: compute the partition map according to DDP bucket logic + buckets = [Bucket()] # (size, param_names) + processed_modules: set[torch.nn.Module] = set() + for node in reversed(gm.graph.nodes): + if node.op in ("output", "placeholder"): + continue + + if ( + buckets[0].size >= self.bucket_bytes_cap + or len(buckets) == 1 + and buckets[0].size >= self.first_bucket_cap + ): + if bucket_has_external_output(buckets[0]): + buckets.insert(0, Bucket()) + else: + # continue building this bucket past the point of filling its parameter capacity, + # to increase chances it contains at least one node that is either a global output or + # passed as input to a subsequent graph + + if buckets[0].opcount_increased_to_capture_external_output == 0: + buckets[0].paramsize_before_opcount_increase = buckets[0].size + buckets[0].opcount_increased_to_capture_external_output += 1 + + if node.op == "call_function": + self.add_param_args(buckets[0], node) + + elif node.op == "call_module": + target_mod = gm.get_submodule(node.target) + if target_mod not in processed_modules: + self.add_module_params_to_bucket( + target_mod, buckets[0], processed_modules, node.target + ) + elif node.op == "call_method": + if isinstance(node.args[0].target, str): + target_mod = None + try: + target_mod = gm.get_submodule(node.args[0].target) + except AttributeError: + pass + if target_mod is not None and target_mod not in processed_modules: + self.add_module_params_to_bucket( + target_mod, buckets[0], processed_modules, node.target + ) + # This handles situations like tmp = torch.mm(x, self.weight.t()) + # t: "f32[512, 512]" = l_self_seq_2_weight.t(); l_self_seq_2_weight = None + # tmp: "f32[512, 512]" = torch.mm(input_2, t); input_2 = t = None + self.add_param_args(buckets[0], node) + + elif node.op == "get_attr": + maybe_param = getattr(gm, node.target) + if ( + isinstance(maybe_param, torch.nn.Parameter) + and maybe_param.requires_grad + and not self._ignore_parameter(maybe_param) + ): + self.add_param(buckets[0], maybe_param, node.target) + + # All nodes have to be mapped to a bucket, even if they don't have their own params + # Ignored params still end up in buckets, we just don't count them towards the capacity + buckets[0].nodes.append(node) + + if len(buckets) > 1 and buckets[0].size == 0: + # we collected a small preamble graph with ops that don't include parameters, fuse it back + buckets[1].nodes.extend(buckets[0].nodes) + if len(buckets[0].params) != 0: + raise AssertionError("Params should be empty if size is 0") + del buckets[0] + + # stash buckets for testing/debugging purposes + self.buckets = buckets + pretty_print_buckets(buckets, self.bucket_bytes_cap) + + if len(buckets) == 1: + # bypass split/fuse logic if there is only one bucket + return self.backend_compile_fn(gm, example_inputs, **compiler_configs) + + # 2: partition the graphmodule according to bucket capacity + partition_map = {} + for idx, b in enumerate(buckets): + for node in b.nodes: + partition_map[node] = idx + + split_gm = fx.passes.split_module.split_module( + gm, + None, # type: ignore[arg-type] + lambda node: partition_map[node], + ) + + # See note [Assumption on Dynamo Metadata] + propagate_dynamo_source(gm, split_gm) + propagate_metadata(gm, split_gm) + + debug_str = ( + f"\n---orig graph---\n{gm.graph}\n" + + f"\n---split graph---\n{split_gm.graph}\n" + ) + for name, module in split_gm.named_modules(): + if "." not in name and len(name): + # only print the submod graphs, not their children + debug_str += f"\n---{name} graph---\n{module.graph}\n" + debug_str += "\n---------------\n" + ddp_graph_log.debug(debug_str) + + trace_structured( + "optimize_ddp_split_graph", + payload_fn=lambda: split_gm.print_readable(print_output=False), + ) + for name, module in split_gm.named_modules(): + if "." not in name and len(name): + trace_structured( + "optimize_ddp_split_child", + lambda: {"name": name}, + payload_fn=lambda: module.print_readable(print_output=False), + ) + + fake_mode = detect_fake_mode(example_inputs) + if fake_mode is None: + fake_mode = torch._subclasses.fake_tensor.FakeTensorMode() + + submod_compiler = SubmodCompiler( + split_gm, self.backend_compile_fn, fake_mode, **compiler_configs + ) + with torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing(): + submod_compiler.run(*example_inputs) + split_gm.recompile() + + ddp_graph_log.debug( + "\n---final graph---\n%s\n---------------\n", split_gm.graph + ) + return split_gm diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/inductor.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/inductor.py new file mode 100644 index 0000000000000000000000000000000000000000..ae62dd56678b8349d27fe909f12482b884ca596c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/inductor.py @@ -0,0 +1,31 @@ +""" +This module provides the TorchInductor backend integration for TorchDynamo. + +TorchInductor is a compiler backend that generates optimized code for both CPU and GPU. +This module lazily imports and registers the TorchInductor compiler to avoid loading it +into memory when it is not being used. This helps reduce memory overhead when using +other backends. + +The inductor backend can be used with torch.compile(): + model = torch.compile(model, backend="inductor") +""" + +from typing import Any + +from torch._dynamo import register_backend +from torch._dynamo.utils import dynamo_timed + + +@register_backend +def inductor(*args: Any, **kwargs: Any) -> Any: + with dynamo_timed("inductor_import", log_pt2_compile_event=True): + # do import here to avoid loading inductor into memory when it is not used + # The AsyncCompile subproc pool can be slow to start, so warm it up as early + # as possible. + from torch._inductor.async_compile import maybe_warm_pool + + maybe_warm_pool() + + from torch._inductor.compile_fx import compile_fx + + return compile_fx(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/onnxrt.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/onnxrt.py new file mode 100644 index 0000000000000000000000000000000000000000..93490e64f4ae2044d0c641f8171e733ed7a8e141 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/onnxrt.py @@ -0,0 +1,39 @@ +# This backend is maintained by ONNX team. To direct issues +# to the right people, please tag related GitHub issues with `module: onnx`. +# +# Maintainers' Github IDs: wschin, xadupre +# from torch.onnx._internal.onnxruntime import ( +# is_onnxrt_backend_supported, +# torch_compile_backend, +# ) + +# from .registry import register_backend + +""" +Placeholder for onnxruntime backend for dynamo +""" + +# def has_onnxruntime(): +# # FIXME: update test/dynamo/test_backends.py to call is_onnxrt_backend_supported() +# return is_onnxrt_backend_supported() + + +# if is_onnxrt_backend_supported(): +# register_backend(name="onnxrt", compiler_fn=torch_compile_backend) +# else: + +# def information_displaying_backend(*args, **kwargs): +# raise ImportError( +# "onnxrt is not registered as a backend. " +# "Please make sure all dependencies such as " +# "numpy, onnx, onnxscript, and onnxruntime-training are installed. " +# "Suggested procedure to fix dependency problem:\n" +# " (1) pip or conda install numpy onnx onnxscript onnxruntime-training.\n" +# " (2) Open a new python terminal.\n" +# " (3) Call the API `torch.onnx.is_onnxrt_backend_supported()`:\n" +# " (4) If it returns `True`, then you can use `onnxrt` backend.\n" +# " (5) If it returns `False`, please execute the package importing section in " +# "torch/onnx/_internal/onnxruntime.py under pdb line-by-line to see which import fails." +# ) + +# register_backend(name="onnxrt", compiler_fn=information_displaying_backend) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/registry.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..4b41922873e91a3b973baecc560e9eec11ef94c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/registry.py @@ -0,0 +1,229 @@ +""" +This module implements TorchDynamo's backend registry system for managing compiler backends. + +The registry provides a centralized way to register, discover and manage different compiler +backends that can be used with torch.compile(). It handles: + +- Backend registration and discovery through decorators and entry points +- Lazy loading of backend implementations +- Lookup and validation of backend names +- Categorization of backends using tags (debug, experimental, etc.) + +Key components: +- CompilerFn: Type for backend compiler functions that transform FX graphs +- _BACKENDS: Registry mapping backend names to entry points +- _COMPILER_FNS: Registry mapping backend names to loaded compiler functions +- _BACKEND_TAGS: Registry mapping backend names to their tags + +Example usage: + @register_backend + def my_compiler(fx_graph, example_inputs): + # Transform FX graph into optimized implementation + return compiled_fn + + # Use registered backend + torch.compile(model, backend="my_compiler") + +The registry also supports discovering backends through setuptools entry points +in the "torch_dynamo_backends" group. Example: +``` +setup.py +--- +from setuptools import setup + +setup( + name='my_torch_backend', + version='0.1', + packages=['my_torch_backend'], + entry_points={ + 'torch_dynamo_backends': [ + # name = path to entry point of backend implementation + 'my_compiler = my_torch_backend.compiler:my_compiler_function', + ], + }, +) +``` +``` +my_torch_backend/compiler.py +--- +def my_compiler_function(fx_graph, example_inputs): + # Transform FX graph into optimized implementation + return compiled_fn +``` +Using `my_compiler` backend: +``` +import torch + +model = ... # Your PyTorch model +optimized_model = torch.compile(model, backend="my_compiler") +``` +""" + +import functools +import logging +from collections.abc import Callable, Sequence +from importlib.metadata import EntryPoint +from typing import Any, Protocol + +import torch +from torch import fx + + +log = logging.getLogger(__name__) + + +class CompiledFn(Protocol): + def __call__(self, *args: torch.Tensor) -> tuple[torch.Tensor, ...]: ... + + +CompilerFn = Callable[[fx.GraphModule, list[torch.Tensor]], CompiledFn] + +_BACKENDS: dict[str, EntryPoint | None] = {} +_COMPILER_FNS: dict[str, CompilerFn] = {} +_BACKEND_TAGS: dict[str, tuple[str, ...]] = {} +_default_backend: str | CompilerFn = "inductor" + + +def register_backend( + compiler_fn: CompilerFn | None = None, + name: str | None = None, + tags: Sequence[str] = (), +) -> Callable[..., Any]: + """ + Decorator to add a given compiler to the registry to allow calling + `torch.compile` with string shorthand. Note: for projects not + imported by default, it might be easier to pass a function directly + as a backend and not use a string. + + Args: + compiler_fn: Callable taking a FX graph and fake tensor inputs + name: Optional name, defaults to `compiler_fn.__name__` + tags: Optional set of string tags to categorize backend with + """ + if compiler_fn is None: + # @register_backend(name="") syntax + return functools.partial(register_backend, name=name, tags=tags) # type: ignore[return-value] + if not callable(compiler_fn): + raise AssertionError(f"compiler_fn must be callable, got {type(compiler_fn)}") + name = name or compiler_fn.__name__ + if name in _COMPILER_FNS: + raise AssertionError(f"duplicate name: {name}") + if name not in _BACKENDS: + _BACKENDS[name] = None + _COMPILER_FNS[name] = compiler_fn + _BACKEND_TAGS[name] = tuple(tags) + return compiler_fn + + +register_debug_backend = functools.partial(register_backend, tags=("debug",)) +register_experimental_backend = functools.partial( + register_backend, tags=("experimental",) +) + + +def lookup_backend(compiler_fn: str | CompilerFn) -> CompilerFn: + """Expand backend strings to functions""" + if isinstance(compiler_fn, str): + if compiler_fn not in _BACKENDS: + _lazy_import() + if compiler_fn not in _BACKENDS: + import difflib + + from ..exc import InvalidBackend + + suggestions = difflib.get_close_matches(compiler_fn, list_backends(), n=2) + raise InvalidBackend(name=compiler_fn, suggestions=suggestions) + + if compiler_fn not in _COMPILER_FNS: + entry_point = _BACKENDS[compiler_fn] + if entry_point is not None: + register_backend(compiler_fn=entry_point.load(), name=compiler_fn) + compiler_fn = _COMPILER_FNS[compiler_fn] + return compiler_fn + + +# NOTE: can't type this due to public api mismatch; follow up with dev team +def list_backends(exclude_tags=("debug", "experimental")) -> list[str]: # type: ignore[no-untyped-def] + """ + Return valid strings that can be passed to: + + torch.compile(..., backend="name") + """ + _lazy_import() + exclude_tags_set = set(exclude_tags or ()) + + backends = [ + name + for name in _BACKENDS + if not exclude_tags_set.intersection(_BACKEND_TAGS.get(name, ())) + ] + return sorted(backends) + + +@functools.cache +def _lazy_import() -> None: + from .. import backends + from ..utils import import_submodule + + import_submodule(backends) + + from ..repro.after_dynamo import dynamo_minifier_backend + + if dynamo_minifier_backend is None: + raise AssertionError("dynamo_minifier_backend failed to load") + + _discover_entrypoint_backends() + + +@functools.cache +def _discover_entrypoint_backends() -> None: + # importing here so it will pick up the mocked version in test_backends.py + from importlib.metadata import entry_points + + group_name = "torch_dynamo_backends" + eps = entry_points(group=group_name) + # pyrefly: ignore [bad-index] + eps_dict = {name: eps[name] for name in eps.names} + for backend_name in eps_dict: + _BACKENDS[backend_name] = eps_dict[backend_name] + + +def _is_registered_backend(compiler_fn: CompilerFn) -> bool: + """ + Check if the given compiler function is a registered backend. + Custom backends (user-provided callables not in the registry) return False. + """ + # Ensure backends are loaded + _lazy_import() + + # Check if it's directly a registered backend function + if compiler_fn in _COMPILER_FNS.values(): + return True + + if isinstance(compiler_fn, torch._TorchCompileInductorWrapper): + return True + + # _TorchCompileWrapper wraps either a registered backend or a custom callable + if isinstance(compiler_fn, torch._TorchCompileWrapper): + return compiler_fn.compiler_fn in _COMPILER_FNS.values() + + return False + + +def set_default_backend(backend: str | CompilerFn | None) -> None: + """Set the default backend used by torch.compile when no backend is explicitly specified. + + Pass None to reset to the default ("inductor"). + """ + global _default_backend + if backend is None: + _default_backend = "inductor" + return + if not isinstance(backend, str) and not callable(backend): + raise TypeError(f"backend must be a string or callable, got {type(backend)}") + _default_backend = backend + + +def get_default_backend() -> str | CompilerFn: + """Return the current default backend for torch.compile.""" + return _default_backend diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tensorrt.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tensorrt.py new file mode 100644 index 0000000000000000000000000000000000000000..493e21a9dfc5fe929fdeefdf6153834d470ab561 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tensorrt.py @@ -0,0 +1,12 @@ +# import torch # type: ignore[import] +# from .common import device_from_inputs, fake_tensor_unsupported # type: ignore[import] +# from .registry import register_backend # type: ignore[import] + +""" +Placeholder for TensorRT backend for dynamo via torch-tensorrt +""" + +# @register_backend +# def tensorrt(gm, example_inputs): +# import torch_tensorrt # type: ignore[import] +# pass diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/torchxla.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/torchxla.py new file mode 100644 index 0000000000000000000000000000000000000000..60d7b87bd0876a85702c07db7c82cd804ee608d1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/torchxla.py @@ -0,0 +1,55 @@ +import logging +from collections.abc import Callable +from typing import Any + +import torch +from functorch.compile import make_boxed_func +from torch import fx + +from ..backends.common import aot_autograd +from .registry import CompiledFn, register_backend, register_experimental_backend + + +log = logging.getLogger(__name__) + + +@register_experimental_backend +def openxla_eval( + model: fx.GraphModule, fake_tensor_inputs: list[torch.Tensor] +) -> CompiledFn: + return xla_backend_helper(model, fake_tensor_inputs, boxed=False) + + +def openxla_eval_boxed( + model: fx.GraphModule, fake_tensor_inputs: list[torch.Tensor] +) -> Callable[..., Any]: + return xla_backend_helper(model, fake_tensor_inputs, boxed=True) + + +def xla_backend_helper( + model: fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], boxed: bool = False +) -> Callable[..., Any]: + try: + import torch_xla.core.dynamo_bridge as bridge + except ImportError as e: + raise ImportError( + "Please follow the instruction in https://github.com/pytorch/xla#pytorchxla to install torch_xla" + ) from e + + compiled_graph = None + + def fwd(*args: torch.Tensor) -> Any: + nonlocal model + nonlocal compiled_graph + if compiled_graph is None: + compiled_graph = bridge.extract_compiled_graph(model, args) + del model + return compiled_graph(*args) + + return make_boxed_func(fwd) if boxed else fwd + + +openxla = aot_autograd( + fw_compiler=openxla_eval_boxed, +) +register_backend(name="openxla", compiler_fn=openxla) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tvm.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tvm.py new file mode 100644 index 0000000000000000000000000000000000000000..8093cedc7a50ab4374f7598fcf9319e0bf2678f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tvm.py @@ -0,0 +1,50 @@ +""" +This module provides TVM backend integration for TorchDynamo. + +Apache TVM is a deep learning compiler framework that can optimize and execute +models on various hardware backends. The backend compiles graphs through TVM's +relax frontend and can be used with torch.compile(): + + model = torch.compile(model, backend="tvm") + +Tuning and target selection are configured through a TVM pipeline: + + pipeline = tvm.relax.get_pipeline("static_shape_tuning", target="llvm", total_trials=2000) + model = torch.compile(model, backend="tvm", options={"pipeline": pipeline}) +""" + +import importlib.util +from collections.abc import Callable +from types import MappingProxyType +from typing import Any + +import torch +from torch import fx + +from .common import fake_tensor_unsupported +from .registry import register_backend + + +@register_backend +@fake_tensor_unsupported # type: ignore[arg-type] +def tvm( + gm: fx.GraphModule, + example_inputs: list[torch.Tensor], + *, + options: MappingProxyType[str, Any] | None = None, +) -> Callable[..., Any]: + try: + from tvm.relax.frontend.torch import relax_dynamo # type: ignore[import] + except ImportError as e: + raise ImportError( + "Please install apache-tvm to use the tvm backend. " + "See https://tvm.apache.org/docs/install/index.html for instructions." + ) from e + + pipeline = options.get("pipeline", None) if options else None + return relax_dynamo(pipeline=pipeline)(gm, example_inputs) + + +def has_tvm() -> bool: + # avoid the heavy tvm import just to check availability + return importlib.util.find_spec("tvm") is not None diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_analysis.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..e43235062d853ddd19a5dac86e691fa8db584429 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_analysis.py @@ -0,0 +1,290 @@ +""" +This module provides utilities for analyzing and optimizing Python bytecode. +Key functionality includes: +- Dead code elimination +- Jump instruction optimization +- Stack size analysis and verification +- Live variable analysis +- Line number propagation and cleanup +- Exception table handling for Python 3.11+ + +The utilities in this module are used to analyze and transform bytecode +for better performance while maintaining correct semantics. +""" + +import bisect +import dataclasses +import dis +import itertools +import sys +from typing import Any, TYPE_CHECKING + + +if TYPE_CHECKING: + # TODO(lucaskabela): consider moving Instruction into this file + # and refactoring in callsite; that way we don't have to guard this import + from .bytecode_transformation import Instruction + +TERMINAL_OPCODES = { + dis.opmap["RETURN_VALUE"], + dis.opmap["JUMP_FORWARD"], + dis.opmap["RAISE_VARARGS"], + # TODO(jansel): double check exception handling +} +TERMINAL_OPCODES.add(dis.opmap["RERAISE"]) +if sys.version_info >= (3, 11): + TERMINAL_OPCODES.add(dis.opmap["JUMP_BACKWARD"]) + TERMINAL_OPCODES.add(dis.opmap["JUMP_FORWARD"]) +else: + TERMINAL_OPCODES.add(dis.opmap["JUMP_ABSOLUTE"]) + +if (3, 12) <= sys.version_info < (3, 14): + TERMINAL_OPCODES.add(dis.opmap["RETURN_CONST"]) +if sys.version_info >= (3, 13): + TERMINAL_OPCODES.add(dis.opmap["JUMP_BACKWARD_NO_INTERRUPT"]) +JUMP_OPCODES = set(dis.hasjrel + dis.hasjabs) +JUMP_OPNAMES = {dis.opname[opcode] for opcode in JUMP_OPCODES} +HASLOCAL = set(dis.haslocal) +HASFREE = set(dis.hasfree) + +stack_effect = dis.stack_effect + + +def get_indexof(insts: list["Instruction"]) -> dict["Instruction", int]: + """ + Get a mapping from instruction memory address to index in instruction list. + Additionally checks that each instruction only appears once in the list. + """ + # pyrefly: ignore [implicit-any] + indexof = {} + for i, inst in enumerate(insts): + if inst in indexof: + raise AssertionError( + f"duplicate instruction at index {i} in instruction list" + ) + indexof[inst] = i + return indexof + + +def remove_dead_code(instructions: list["Instruction"]) -> list["Instruction"]: + """Dead code elimination""" + indexof = get_indexof(instructions) + live_code = set() + + def find_live_code(start: int) -> None: + for i in range(start, len(instructions)): + if i in live_code: + return + live_code.add(i) + inst = instructions[i] + if inst.exn_tab_entry: + find_live_code(indexof[inst.exn_tab_entry.target]) + if inst.opcode in JUMP_OPCODES: + if inst.target is None: + raise AssertionError( + f"jump instruction {inst.opname} has no target" + ) + find_live_code(indexof[inst.target]) + if inst.opcode in TERMINAL_OPCODES: + return + + find_live_code(0) + + # change exception table entries if start/end instructions are dead + # assumes that exception table entries have been propagated, + # e.g. with bytecode_transformation.propagate_inst_exn_table_entries, + # and that instructions with an exn_tab_entry lies within its start/end. + if sys.version_info >= (3, 11): + live_idx = sorted(live_code) + for i, inst in enumerate(instructions): + if i in live_code and inst.exn_tab_entry: + # find leftmost live instruction >= start + start_idx = bisect.bisect_left( + live_idx, indexof[inst.exn_tab_entry.start] + ) + if start_idx >= len(live_idx): + raise AssertionError( + "no live instruction found at or after exn_tab_entry start" + ) + # find rightmost live instruction <= end + end_idx = ( + bisect.bisect_right(live_idx, indexof[inst.exn_tab_entry.end]) - 1 + ) + if end_idx < 0: + raise AssertionError( + "no live instruction found at or before exn_tab_entry end" + ) + if not (live_idx[start_idx] <= i <= live_idx[end_idx]): + raise AssertionError( + f"instruction {i} not within live range " + f"[{live_idx[start_idx]}, {live_idx[end_idx]}]" + ) + inst.exn_tab_entry.start = instructions[live_idx[start_idx]] + inst.exn_tab_entry.end = instructions[live_idx[end_idx]] + + return [inst for i, inst in enumerate(instructions) if i in live_code] + + +def remove_pointless_jumps(instructions: list["Instruction"]) -> list["Instruction"]: + """Eliminate jumps to the next instruction""" + pointless_jumps = { + id(a) + for a, b in itertools.pairwise(instructions) + if a.opname == "JUMP_ABSOLUTE" and a.target is b + } + return [inst for inst in instructions if id(inst) not in pointless_jumps] + + +def propagate_line_nums(instructions: list["Instruction"]) -> None: + """Ensure every instruction has line number set in case some are removed""" + cur_line_no = None + + def populate_line_num(inst: "Instruction") -> None: + nonlocal cur_line_no + if inst.starts_line: + cur_line_no = inst.starts_line + + inst.starts_line = cur_line_no + + for inst in instructions: + populate_line_num(inst) + + +def remove_extra_line_nums(instructions: list["Instruction"]) -> None: + """Remove extra starts line properties before packing bytecode""" + + cur_line_no = None + + def remove_line_num(inst: "Instruction") -> None: + nonlocal cur_line_no + if inst.starts_line is None: + return + elif inst.starts_line == cur_line_no: + inst.starts_line = None + else: + cur_line_no = inst.starts_line + + for inst in instructions: + remove_line_num(inst) + + +@dataclasses.dataclass +class ReadsWrites: + reads: set[Any] + writes: set[Any] + visited: set[Any] + + +def livevars_analysis( + instructions: list["Instruction"], instruction: "Instruction" +) -> set[Any]: + indexof = get_indexof(instructions) + must = ReadsWrites(set(), set(), set()) + may = ReadsWrites(set(), set(), set()) + + def walk(state: ReadsWrites, start: int) -> None: + if start in state.visited: + return + state.visited.add(start) + + for i in range(start, len(instructions)): + inst = instructions[i] + if inst.opcode in HASLOCAL or inst.opcode in HASFREE: + if "LOAD" in inst.opname or "DELETE" in inst.opname: + if inst.argval not in must.writes: + state.reads.add(inst.argval) + elif "STORE" in inst.opname: + state.writes.add(inst.argval) + elif inst.opname == "MAKE_CELL": + pass + else: + raise NotImplementedError(f"unhandled {inst.opname}") + if inst.exn_tab_entry: + walk(may, indexof[inst.exn_tab_entry.target]) + if inst.opcode in JUMP_OPCODES: + if inst.target is None: + raise AssertionError( + f"jump instruction {inst.opname} has no target" + ) + walk(may, indexof[inst.target]) + state = may + if inst.opcode in TERMINAL_OPCODES: + return + + walk(must, indexof[instruction]) + return must.reads | may.reads + + +@dataclasses.dataclass +class FixedPointBox: + value: bool = True + + +@dataclasses.dataclass +class StackSize: + low: int | float + high: int | float + fixed_point: FixedPointBox + + def zero(self) -> None: + self.low = 0 + self.high = 0 + self.fixed_point.value = False + + def offset_of(self, other: "StackSize", n: int) -> None: + prior = (self.low, self.high) + self.low = min(self.low, other.low + n) + self.high = max(self.high, other.high + n) + if (self.low, self.high) != prior: + self.fixed_point.value = False + + def exn_tab_jump(self, depth: int) -> None: + prior = (self.low, self.high) + self.low = min(self.low, depth) + self.high = max(self.high, depth) + if (self.low, self.high) != prior: + self.fixed_point.value = False + + +def stacksize_analysis(instructions: list["Instruction"]) -> int | float: + if not instructions: + raise AssertionError("instructions list must not be empty") + fixed_point = FixedPointBox() + stack_sizes = { + inst: StackSize(float("inf"), float("-inf"), fixed_point) + for inst in instructions + } + stack_sizes[instructions[0]].zero() + + for _ in range(100): + if fixed_point.value: + break + fixed_point.value = True + + for inst, next_inst in zip(instructions, instructions[1:] + [None]): + stack_size = stack_sizes[inst] + if inst.opcode not in TERMINAL_OPCODES: + if next_inst is None: + raise AssertionError(f"missing next inst: {inst}") + eff = stack_effect(inst.opcode, inst.arg, jump=False) + stack_sizes[next_inst].offset_of(stack_size, eff) + if inst.opcode in JUMP_OPCODES: + if inst.target is None: + raise AssertionError(f"missing target: {inst}") + stack_sizes[inst.target].offset_of( + stack_size, stack_effect(inst.opcode, inst.arg, jump=True) + ) + if inst.exn_tab_entry: + # see https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt + # on why depth is computed this way. + depth = inst.exn_tab_entry.depth + int(inst.exn_tab_entry.lasti) + 1 + stack_sizes[inst.exn_tab_entry.target].exn_tab_jump(depth) + + low = min(x.low for x in stack_sizes.values()) + high = max(x.high for x in stack_sizes.values()) + + if not fixed_point.value: + raise AssertionError("failed to reach fixed point") + if low < 0: + raise AssertionError(f"stack size analysis produced negative low value: {low}") + return high diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_debugger.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_debugger.py new file mode 100644 index 0000000000000000000000000000000000000000..ef8c35a92b5fb76bf88cbd93b9b55af0afb7fbf2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_debugger.py @@ -0,0 +1,1151 @@ +""" +Bytecode debugger for Dynamo-optimized code. + +This module provides a pdb-like debugger for stepping through Python bytecode +one instruction at a time, with the ability to inspect the value stack, +locals, and globals. + +Usage: + >>> # xdoctest: +SKIP + >>> import torch + >>> + >>> @torch.compile + >>> def my_fn(x): + ... return x + 1 + >>> + >>> with torch._dynamo.bytecode_debugger.debug(): + ... my_fn(torch.randn(3)) # Debugger activates on Dynamo-generated code + +Programmatic breakpoints (for Dynamo developers): + In PyCodegen, use create_breakpoint() to insert a debugger stop: + + from torch._dynamo.bytecode_transformation import create_breakpoint + codegen.extend_output(create_breakpoint()) +""" + +from __future__ import annotations + +import dis +import sys +import types +from contextlib import contextmanager +from dataclasses import dataclass, field +from typing import Any, cast, TYPE_CHECKING + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + from typing_extensions import Self + +from .bytecode_transformation import convert_instruction, Instruction, instruction_size + + +# Python 3.12+ has sys.monitoring for efficient instruction-level tracing +_HAS_SYS_MONITORING = hasattr(sys, "monitoring") + + +# Sentinel for breakpoints inserted by PyCodegen via create_breakpoint() +class _BreakpointMarker: + """Sentinel constant that signals the debugger to break. + + Usage in PyCodegen: + from torch._dynamo.bytecode_transformation import create_breakpoint + codegen.extend_output(create_breakpoint()) + """ + + __slots__ = () + _instance: _BreakpointMarker | None = None + + def __new__(cls) -> Self: + if cls._instance is None: + cls._instance = cast("_BreakpointMarker", object.__new__(cls)) + return cls._instance + + def __repr__(self) -> str: + return "" + + +BREAKPOINT_MARKER = _BreakpointMarker() + + +# Import NULL_STACK_VALUE sentinel from C++ module +# This is returned by _get_frame_value_stack_with_depth for NULL stack slots +from torch._C._dynamo.eval_frame import NULL_STACK_VALUE + + +@dataclass +class CodeInfo: + """Per-code-object data shared across all frames executing the same code.""" + + code: types.CodeType + instructions: list[Instruction] + offset_to_inst: dict[int, Instruction] + offset_to_index: dict[int, int] + index_width: int + offset_width: int + breakpoints: set[int] = field(default_factory=set) + + +@dataclass +class DebuggerState: + """Per-frame debugging state.""" + + code_info: CodeInfo + frame: types.FrameType + current_offset: int = -1 # -1 indicates first instruction not yet seen + current_stack_depth: int = 0 # Tracked dynamically + first_instruction_seen: bool = False + step_mode: bool = True + step_count: int = 0 # Remaining steps for "s [n]" command (0 = prompt each time) + user_locals: dict[str, Any] = field( + default_factory=dict + ) # User-defined variables from debugger + last_command: str = "s" # Last command for repeat on empty input + list_index: int | None = ( + None # Current position for 'l' command (None = use current) + ) + + @property + def code(self) -> types.CodeType: + return self.code_info.code + + @property + def instructions(self) -> list[Instruction]: + return self.code_info.instructions + + @property + def offset_to_inst(self) -> dict[int, Instruction]: + return self.code_info.offset_to_inst + + @property + def offset_to_index(self) -> dict[int, int]: + return self.code_info.offset_to_index + + @property + def index_width(self) -> int: + return self.code_info.index_width + + @property + def offset_width(self) -> int: + return self.code_info.offset_width + + @property + def breakpoints(self) -> set[int]: + return self.code_info.breakpoints + + +class _DebugContext: + """Internal debug context that manages the debugging session.""" + + def __init__(self) -> None: + self._code_info: dict[types.CodeType, CodeInfo] = {} + self._frame_states: dict[types.FrameType, DebuggerState] = {} + self._active = False + self._tracked_codes: set[types.CodeType] = set() + self._old_trace: Callable[..., Any] | None = None + self._prev_callback: Callable[..., Any] | None = None + self._return_from_frame: types.FrameType | None = None + self._stop_after_return: bool = False + self._next_in_frame: types.FrameType | None = None + self._next_count: int = 0 + self._verbose: bool = False + self._stop_at_new_code: bool = True + self._quitting: bool = False + if _HAS_SYS_MONITORING: + self._tool_id = sys.monitoring.DEBUGGER_ID + + def get_instructions(self, code: types.CodeType | None = None) -> list[Instruction]: + """Get the list of instructions for a tracked code object. + + Args: + code: The code object to get instructions for. If None, returns + instructions from the most recently tracked code object. + + Returns: + List of instructions, or empty list if the code is not tracked. + """ + if not self._code_info: + return [] + if code is None: + info = next(reversed(self._code_info.values())) + else: + info = self._code_info.get(code) + if info is None: + return [] + return info.instructions + + def get_tracked_codes(self) -> list[types.CodeType]: + """Get all code objects that have been tracked by the debugger.""" + return list(self._code_info.keys()) + + @staticmethod + def is_programmatic_breakpoint(inst: Instruction) -> bool: + return inst.opname == "LOAD_CONST" and inst.argval is BREAKPOINT_MARKER + + def _get_or_create_code_info(self, code: types.CodeType) -> CodeInfo: + """Get or create CodeInfo for a code object.""" + if code not in self._code_info: + # Use dis.get_instructions directly to preserve original offsets. + # cleaned_instructions strips EXTENDED_ARG and recalculates offsets, + # which would cause mismatches with offsets reported by callbacks. + instructions = [convert_instruction(i) for i in dis.get_instructions(code)] + + # In 3.11+, instructions have inline cache entries that occupy + # bytecode space (e.g. BINARY_OP is 2 bytes + 2 bytes cache). + # dis.get_instructions only reports the instruction start offset, + # but sys.monitoring RAISE reports offsets within cache entries. + # Map the full byte range of each instruction so lookups succeed. + offset_to_inst: dict[int, Instruction] = {} + offset_to_index: dict[int, int] = {} + for i, inst in enumerate(instructions): + if inst.offset is not None: + inst_size = instruction_size(inst) + for off in range(inst.offset, inst.offset + inst_size, 2): + offset_to_inst[off] = inst + offset_to_index[off] = i + + max_index = len(instructions) - 1 if instructions else 0 + max_offset = max( + (inst.offset for inst in instructions if inst.offset is not None), + default=0, + ) + + # Pre-populate breakpoints from BREAKPOINT_MARKER instructions + programmatic_breakpoints: set[int] = { + i + for i, inst in enumerate(instructions) + if self.is_programmatic_breakpoint(inst) + } + + self._code_info[code] = CodeInfo( + code=code, + instructions=instructions, + offset_to_inst=offset_to_inst, + offset_to_index=offset_to_index, + index_width=max(1, len(str(max_index))), + offset_width=max(1, len(str(max_offset))), + breakpoints=programmatic_breakpoints, + ) + return self._code_info[code] + + def _get_or_create_frame_state( + self, code: types.CodeType, frame: types.FrameType + ) -> DebuggerState: + """Get or create per-frame DebuggerState.""" + if frame not in self._frame_states: + code_info = self._get_or_create_code_info(code) + self._frame_states[frame] = DebuggerState(code_info=code_info, frame=frame) + return self._frame_states[frame] + + def _find_frame_for_code(self, code: types.CodeType) -> types.FrameType | None: + """Walk the stack to find the frame executing the given code.""" + f: types.FrameType | None = sys._getframe() + while f is not None: + if f.f_code is code: + return f + f = f.f_back + return None + + def _build_tracked_frame_stack(self, state: DebuggerState) -> list[DebuggerState]: + """Build list of tracked ancestor frames, outermost-first. + + Walks f_back from the current execution frame to find all ancestor + frames whose code is tracked by the debugger. Returns the corresponding + DebuggerState objects with the execution state (state) last. + """ + ancestors: list[DebuggerState] = [] + f: types.FrameType | None = state.frame.f_back + while f is not None: + ancestor_state = self._frame_states.get(f) + if ancestor_state is not None: + ancestors.append(ancestor_state) + f = f.f_back + ancestors.reverse() + ancestors.append(state) + return ancestors + + def _format_instruction( + self, state: DebuggerState, offset: int, mark_current: bool = True + ) -> str: + """Format an instruction for display.""" + inst = state.offset_to_inst.get(offset) + iw, ow = state.index_width, state.offset_width + if inst is None: + return f" [{offset:{ow}d}]: " + + index = state.offset_to_index.get(offset, -1) + marker = ">>>" if mark_current and offset == state.current_offset else " " + bp_marker = ( + "*" if state.offset_to_index.get(offset, -1) in state.breakpoints else " " + ) + arg_str = f" {inst.argval}" if inst.arg is not None else "" + return f"{marker}{bp_marker} {index:{iw}d} [{offset:{ow}d}]: {inst.opname}{arg_str}" + + def _format_header(self, state: DebuggerState) -> str: + """Format the header line for instruction listings.""" + iw, ow = state.index_width, state.offset_width + return f" {'#':>{iw}} [{'offset':>{ow}}]" + + def _print_context( + self, state: DebuggerState, before: int = 3, after: int = 3 + ) -> None: + """Print instructions around the current position.""" + current_idx = state.offset_to_index.get(state.current_offset, 0) + start = max(0, current_idx - before) + end = min(len(state.instructions), current_idx + after + 1) + + print(f"\nInstruction {current_idx} at offset {state.current_offset}:") + print(self._format_header(state)) + for i in range(start, end): + inst = state.instructions[i] + if inst.offset is not None: + print(self._format_instruction(state, inst.offset)) + print() + + def _safe_stack_depth(self, state: DebuggerState, is_current_frame: bool) -> int: + """Compute a safe stack depth for reading frame values. + + For parent frames suspended at a CALL instruction, CPython has already + popped (and DECREF'd) the call arguments. The tracked depth still + includes those consumed entries, so reading them would dereference + dangling pointers. Adjust by the current instruction's stack_effect. + """ + depth = state.current_stack_depth + if not is_current_frame and state.current_offset >= 0: + inst = state.offset_to_inst.get(state.current_offset) + if inst is not None: + try: + effect = dis.stack_effect(inst.opcode, inst.arg) + if effect < 0: + depth = max(0, depth + effect) + except (ValueError, TypeError): + pass + return depth + + def _print_stack(self, state: DebuggerState, is_current_frame: bool = True) -> None: + """Print the current value stack.""" + from torch._C._dynamo.eval_frame import _get_frame_value_stack_with_depth + + depth = self._safe_stack_depth(state, is_current_frame) + try: + stack = _get_frame_value_stack_with_depth(state.frame, depth) + except Exception as e: + print(f"\nStack: (error reading stack: {e})") + return + print("\nStack (TOS at end):") + if not stack: + print(" (empty)") + else: + for i, value in enumerate(stack): + if value is NULL_STACK_VALUE: + addr = "0x0" + else: + addr = f"0x{id(value):x}" + print(f" [{i}] {addr} {value!r}") + print() + + def _print_locals(self, state: DebuggerState) -> None: + """Print local variables.""" + print("\nLocals:") + locals_dict = state.frame.f_locals + if not locals_dict: + print(" (none)") + else: + for name, value in locals_dict.items(): + print(f" {name} = {value!r}") + print() + + def _print_globals(self, state: DebuggerState, pattern: str | None = None) -> None: + """Print global variables.""" + print("\nGlobals:") + for name, value in state.frame.f_globals.items(): + if pattern and pattern not in name: + continue + if name.startswith("__") and name.endswith("__"): + continue + if isinstance(value, types.ModuleType): + continue + print(f" {name} = {value!r}") + print() + + def _disassemble(self, state: DebuggerState) -> None: + """Print the full disassembly.""" + print(f"\nDisassembly ({len(state.instructions)} instructions):") + print(self._format_header(state)) + for inst in state.instructions: + if inst.offset is not None: + print(self._format_instruction(state, inst.offset, mark_current=False)) + print() + + def _print_help(self) -> None: + """Print help message.""" + print("\nCommands:") + print(" s [n] - Step n instructions (default 1), stepping into calls") + print(" n [n] - Step n instructions (default 1), stepping over calls") + print(" c, cont - Continue until breakpoint or exception") + print(" r - Continue until current function's return instruction") + print( + " v, verbose - Toggle verbose mode (print each instruction before executing)" + ) + print(" Use with 'c' to find segfaults - last printed = culprit") + print(" u [count] - Move up the call stack (toward caller) for inspection") + print(" d [count] - Move down the call stack (toward callee)") + print(" bt, w - Print tracked frame backtrace") + print(" p - Print expression") + print(" l [first[, last]] - List instructions (like pdb)") + print(" l . - List around current instruction") + print(" ll - Disassemble all bytecode") + print(" stack - Print value stack") + print(" locals - Print local variables") + print(" globals - Print global variables") + print(" b - Set breakpoint at instruction n (see # column)") + print(" b - List breakpoints") + print(" cl - Clear breakpoint at instruction n") + print(" q, quit - Exit debugger") + print(" - Evaluate Python expression (like pdb)") + print() + print("Special variables: __stack__ (list of stack values, TOS at end)") + print("Note: Debugger stops on exceptions and shows the failing instruction.") + print() + + def _get_stack_for_eval( + self, state: DebuggerState, is_current_frame: bool = True + ) -> list[Any]: + """Get the current stack for use in expression evaluation.""" + from torch._C._dynamo.eval_frame import _get_frame_value_stack_with_depth + + depth = self._safe_stack_depth(state, is_current_frame) + try: + return _get_frame_value_stack_with_depth(state.frame, depth) + except Exception: + return [] + + def _build_eval_locals( + self, state: DebuggerState, is_current_frame: bool = True + ) -> dict[str, Any]: + """Build locals dict for expression evaluation, including user-defined variables.""" + eval_locals = dict(state.frame.f_locals) + eval_locals.update(state.user_locals) + eval_locals["__stack__"] = self._get_stack_for_eval(state, is_current_frame) + return eval_locals + + def _interactive_prompt(self, state: DebuggerState) -> None: + """Interactive prompt during debugging.""" + frame_stack = self._build_tracked_frame_stack(state) + view_index = len(frame_stack) - 1 + view_state = frame_stack[view_index] + + self._print_context(view_state) + + while True: + try: + cmd = input("(bdb) ").strip() + except (EOFError, KeyboardInterrupt): + print("\nExiting debugger.") + self._quitting = True + raise KeyboardInterrupt from None + + if not cmd: + cmd = state.last_command + else: + state.last_command = cmd + + parts = cmd.split(maxsplit=1) + action = parts[0].lower() + arg = parts[1] if len(parts) > 1 else "" + + if action in ("s", "step"): + state.step_mode = True + self._stop_at_new_code = True + # Parse optional count argument (e.g., "s 3" to step 3 times) + if arg: + try: + count = int(arg) + state.step_count = ( + count - 1 + ) # -1 because we're about to execute one + except ValueError: + print(f"Invalid count: {arg}") + continue + else: + state.step_count = 0 + return + + elif action in ("n", "next"): + self._next_in_frame = view_state.frame + if arg: + try: + count = int(arg) + self._next_count = count - 1 + except ValueError: + print(f"Invalid count: {arg}") + continue + else: + self._next_count = 0 + state.step_mode = False + self._stop_at_new_code = False + return + + elif action in ("c", "cont", "continue"): + state.step_mode = False + self._stop_at_new_code = False + self._stop_after_return = False + return + + elif action in ("r", "return"): + self._return_from_frame = state.frame + state.step_mode = False + self._stop_at_new_code = False + return + + elif action in ("u", "up"): + count = 1 + if arg: + try: + count = int(arg) + except ValueError: + print(f"Invalid count: {arg}") + continue + new_index = view_index - count + if new_index < 0: + new_index = 0 + print("Oldest tracked frame") + view_index = new_index + view_state = frame_stack[view_index] + print(f"> {view_state.code.co_name}") + self._print_context(view_state) + + elif action in ("d", "down"): + count = 1 + if arg: + try: + count = int(arg) + except ValueError: + print(f"Invalid count: {arg}") + continue + max_index = len(frame_stack) - 1 + new_index = view_index + count + if new_index > max_index: + new_index = max_index + print("Newest tracked frame") + view_index = new_index + view_state = frame_stack[view_index] + print(f"> {view_state.code.co_name}") + self._print_context(view_state) + + elif action in ("bt", "w", "where"): + for i, fs in enumerate(frame_stack): + marker = ">" if i == view_index else " " + idx = fs.offset_to_index.get(fs.current_offset, -1) + inst = fs.offset_to_inst.get(fs.current_offset) + inst_str = inst.opname if inst else "" + print( + f" {marker} [{i}] {fs.code.co_name} instruction {idx} ({inst_str})" + ) + + elif action in ("v", "verbose"): + self._verbose = not self._verbose + status = "enabled" if self._verbose else "disabled" + print(f"Verbose mode {status}.") + + elif action in ("l", "list"): + # Like pdb: + # - 'l' continues from last position (or centers on current if first time) + # - 'l .' centers on current instruction + # - 'l N' lists 11 instructions starting at N + # - 'l first, last' lists range (if last < first, last is a count) + num_lines = 11 # pdb default + start: int | None = None + end: int | None = None + + if arg == ".": + # Reset to current instruction + view_state.list_index = None + elif arg: + # Check for range syntax: "first, last" or "first,last" + if "," in arg: + parts = arg.split(",", 1) + try: + first = int(parts[0].strip()) + second = int(parts[1].strip()) + if second < first: + # second is a count + start = first + end = first + second + else: + start = first + end = second + 1 # inclusive + except ValueError: + print(f"Invalid range: {arg}") + continue + else: + # Single number: start at that instruction + try: + start = int(arg) + end = start + num_lines + except ValueError: + print(f"Invalid argument: {arg}") + continue + + if start is None: + if view_state.list_index is None: + # Center on current instruction + current_idx = view_state.offset_to_index.get( + view_state.current_offset, 0 + ) + start = max(0, current_idx - num_lines // 2) + else: + start = view_state.list_index + end = start + num_lines + + if end is None: + raise AssertionError("end must be set before listing instructions") + end = min(len(view_state.instructions), end) + if start >= len(view_state.instructions): + print("(End of bytecode)") + else: + print(self._format_header(view_state)) + for i in range(start, end): + inst = view_state.instructions[i] + if inst.offset is not None: + print(self._format_instruction(view_state, inst.offset)) + print() + view_state.list_index = end + + elif action == "ll": + self._disassemble(view_state) + + elif action == "locals": + self._print_locals(view_state) + + elif action == "globals": + self._print_globals(view_state, arg if arg else None) + + elif action == "stack": + is_current = view_state is frame_stack[-1] + self._print_stack(view_state, is_current_frame=is_current) + + elif action == "b": + if arg: + try: + index = int(arg) + num_instructions = len(view_state.instructions) + if index < 0 or index >= num_instructions: + print( + f"Invalid instruction number: {index} " + f"(must be 0-{num_instructions - 1})" + ) + else: + view_state.breakpoints.add(index) + print(f"Breakpoint set at instruction {index}") + except ValueError: + print(f"Invalid instruction number: {arg}") + else: + print("\nBreakpoints:") + if not view_state.breakpoints: + print(" (none)") + else: + for bp_index in sorted(view_state.breakpoints): + if bp_index < len(view_state.instructions): + inst = view_state.instructions[bp_index] + if inst.offset is not None: + print( + f" {self._format_instruction(view_state, inst.offset, mark_current=False)}" + ) + print() + + elif action == "cl": + if arg: + try: + index = int(arg) + num_instructions = len(view_state.instructions) + if index < 0 or index >= num_instructions: + print( + f"Invalid instruction number: {index} " + f"(must be 0-{num_instructions - 1})" + ) + elif index in view_state.breakpoints: + view_state.breakpoints.discard(index) + print(f"Breakpoint cleared at instruction {index}") + else: + print(f"No breakpoint at instruction {index}") + except ValueError: + print(f"Invalid instruction number: {arg}") + + elif action == "p": + if arg: + try: + is_current = view_state is frame_stack[-1] + frame_globals = view_state.frame.f_globals + eval_locals = self._build_eval_locals( + view_state, is_current_frame=is_current + ) + result = eval(arg, frame_globals, eval_locals) + print(f"{arg} = {result!r}") + except Exception as e: + print(f"Error evaluating '{arg}': {e}") + else: + print("Usage: p ") + + elif action in ("h", "help", "?"): + self._print_help() + + elif action in ("q", "quit", "exit"): + print("Exiting debugger.") + self._quitting = True + raise KeyboardInterrupt + + else: + # Try to execute as Python code (like pdb) + is_current = view_state is frame_stack[-1] + frame_globals = view_state.frame.f_globals + eval_locals = self._build_eval_locals( + view_state, is_current_frame=is_current + ) + + try: + # First try as expression (eval) + result = eval(cmd, frame_globals, eval_locals) + if result is not None: + print(repr(result)) + except SyntaxError: + # If not a valid expression, try as statement (exec) + try: + keys_before = set(eval_locals.keys()) + ids_before = {k: id(v) for k, v in eval_locals.items()} + exec(cmd, frame_globals, eval_locals) + # Capture any new or modified variables into user_locals + for key in eval_locals: + is_new = key not in keys_before + is_user_var = key in view_state.user_locals + is_modified = id(eval_locals[key]) != ids_before.get(key) + if ( + is_new or is_user_var or is_modified + ) and key != "__stack__": + view_state.user_locals[key] = eval_locals[key] + except Exception as e: + print(f"*** {type(e).__name__}: {e}") + except Exception as e: + print(f"*** {type(e).__name__}: {e}") + + def _handle_instruction( + self, code: types.CodeType, offset: int, frame: types.FrameType | None = None + ) -> None: + """Common instruction handling logic for both tracing backends.""" + if frame is None: + frame = self._find_frame_for_code(code) + if frame is None: + raise AssertionError( + f"Could not find frame for code object {code.co_name}" + ) + state = self._get_or_create_frame_state(code, frame) + + # Update stack depth based on the previous instruction's effect. + # The callback is called BEFORE instruction at 'offset' executes, + # so we need to apply the effect of the previous instruction first. + previous_offset = state.current_offset + if previous_offset >= 0: + prev_inst = state.offset_to_inst.get(previous_offset) + if prev_inst is not None: + # Detect if a jump was taken: current offset != sequential next + prev_index = state.offset_to_index.get(previous_offset, -1) + expected_next_index = prev_index + 1 + current_index = state.offset_to_index.get(offset, -1) + did_jump = current_index != expected_next_index + + try: + effect = dis.stack_effect( + prev_inst.opcode, prev_inst.arg, jump=did_jump + ) + state.current_stack_depth += effect + if state.current_stack_depth < 0: + raise RuntimeError( + f"Stack depth went negative after {prev_inst.opname} " + f"at offset {previous_offset}: depth={state.current_stack_depth}" + ) + except (ValueError, TypeError): + pass + + state.current_offset = offset + state.list_index = None # Reset list position when stepping + + # After 'r' command completes, resume stepping at the next instruction + if self._stop_after_return: + self._stop_after_return = False + state.step_mode = True + state.step_count = 0 + self._stop_at_new_code = True + + # After 'n', resume stepping when we reach that frame + if self._next_in_frame is not None and frame is self._next_in_frame: + if self._next_count > 0: + # More steps remaining — re-arm for the next instruction in this frame + self._next_count -= 1 + else: + self._next_in_frame = None + state.step_mode = True + state.step_count = 0 + self._stop_at_new_code = True + if _HAS_SYS_MONITORING: + sys.monitoring.restart_events() + + # First instruction - print header and enter step mode (unless suppressed) + if not state.first_instruction_seen: + state.first_instruction_seen = True + if not self._stop_at_new_code: + state.step_mode = False + if state.step_mode: + print(f"\n=== Entering Dynamo-generated code: {code.co_name} ===") + self._print_help() + elif self._verbose: + print(f"\n=== Entering Dynamo-generated code: {code.co_name} ===") + + # Verbose mode: print each instruction before executing (for segfault debugging) + if self._verbose: + inst = state.offset_to_inst.get(offset) + if inst: + idx = state.offset_to_index.get(offset, -1) + arg_str = f" {inst.argval}" if inst.arg is not None else "" + print(f"Running [{idx}] {inst.opname}{arg_str}", flush=True) + + inst = state.offset_to_inst.get(offset) + + # Check if current instruction has a breakpoint (by index) + current_index = state.offset_to_index.get(offset, -1) + hit_breakpoint = current_index in state.breakpoints + + # 'r' command: stop at RETURN_VALUE/RETURN_CONST in the target frame + # so the user can inspect the return value on the stack before returning. + hit_return_target = False + if self._return_from_frame is not None and frame is self._return_from_frame: + if inst is not None and inst.opname in ("RETURN_VALUE", "RETURN_CONST"): + self._return_from_frame = None + # After stepping past the return, stop in the caller + self._stop_after_return = True + hit_return_target = True + + # Check if we should stop + # If step_count > 0, we're in the middle of "N s" and should continue + if state.step_count > 0: + state.step_count -= 1 + # But still stop for breakpoints and return targets + if hit_breakpoint or hit_return_target: + state.step_count = 0 # Cancel remaining steps + else: + return # Continue without prompting + + should_stop = state.step_mode or hit_breakpoint or hit_return_target + if should_stop: + if hit_breakpoint: + if inst is not None and self.is_programmatic_breakpoint(inst): + print("Breakpoint hit (programmatic)") + else: + print(f"Breakpoint hit at instruction {current_index}") + elif hit_return_target: + print(f"About to return from {code.co_name}") + self._interactive_prompt(state) + + def _handle_return( + self, code: types.CodeType, retval: object, frame: types.FrameType | None = None + ) -> None: + """Common return handling logic.""" + if self._quitting: + return + print(f"\n=== {code.co_name} returned: {retval!r} ===") + + # For sys.monitoring, we don't get the frame directly, but since + # the frame that's currently returning is the one whose PY_RETURN just + # fired, code identity is sufficient to match. + if self._return_from_frame is not None and ( + frame is self._return_from_frame + or (frame is None and code is self._return_from_frame.f_code) + ): + self._return_from_frame = None + self._stop_after_return = True + if _HAS_SYS_MONITORING: + sys.monitoring.restart_events() + if self._next_in_frame is not None and ( + frame is self._next_in_frame + or (frame is None and code is self._next_in_frame.f_code) + ): + self._next_in_frame = None + self._stop_after_return = True + if _HAS_SYS_MONITORING: + sys.monitoring.restart_events() + + # Clean up frame state to avoid holding dead frame references + if frame is not None: + self._frame_states.pop(frame, None) + else: + # sys.monitoring path: find and remove matching frame state by code + for f, s in list(self._frame_states.items()): + if s.code is code: + self._frame_states.pop(f, None) + break + + def _handle_exception( + self, code: types.CodeType, offset: int, exception: BaseException + ) -> None: + """Common exception handling logic.""" + if self._quitting: + return + frame = self._find_frame_for_code(code) + if frame is None: + return + state = self._frame_states.get(frame) + if state is None: + return + + # If we're waiting for this frame to return, the return was interrupted + if self._return_from_frame is not None and ( + frame is self._return_from_frame or code is self._return_from_frame.f_code + ): + self._return_from_frame = None + + # If we're waiting for next-in-frame, the execution was interrupted + if self._next_in_frame is not None and ( + frame is self._next_in_frame or code is self._next_in_frame.f_code + ): + self._next_in_frame = None + self._stop_at_new_code = True + + state.current_offset = offset + + inst = state.offset_to_inst.get(offset) + inst_str = inst.opname if inst else "" + current_index = state.offset_to_index.get(offset, -1) + + print(f"\n=== Exception raised at instruction {current_index}: {inst_str} ===") + print(f"=== {type(exception).__name__}: {exception} ===") + self._interactive_prompt(state) + + # ========================================================================= + # Python 3.12+ implementation using sys.monitoring + # ========================================================================= + + def _dynamo_code_callback(self, code: types.CodeType) -> None: + """Called by C++ before executing Dynamo-generated code.""" + if code in self._tracked_codes: + return + self._tracked_codes.add(code) + + if _HAS_SYS_MONITORING: + # Enable INSTRUCTION and PY_RETURN events for this specific code object + # RAISE must be a global event (cannot be set locally) + sys.monitoring.set_local_events( + self._tool_id, + code, + sys.monitoring.events.INSTRUCTION | sys.monitoring.events.PY_RETURN, + ) + # For settrace, we enable opcode tracing when we see the frame + + # Pre-create code info for this code + self._get_or_create_code_info(code) + + def _monitoring_return_callback( + self, code: types.CodeType, instruction_offset: int, retval: object + ) -> None: + """Callback for PY_RETURN events (sys.monitoring).""" + self._handle_return(code, retval) + + def _monitoring_instruction_callback( + self, code: types.CodeType, offset: int + ) -> object: + """Callback for INSTRUCTION events (sys.monitoring).""" + self._handle_instruction(code, offset) + return sys.monitoring.DISABLE + + def _monitoring_raise_callback( + self, code: types.CodeType, offset: int, exception: BaseException + ) -> object: + """Callback for RAISE events (sys.monitoring).""" + # Only handle exceptions from tracked Dynamo-generated code + if code not in self._tracked_codes: + return None + self._handle_exception(code, offset, exception) + # Cannot return DISABLE for global events like RAISE + return None + + # ========================================================================= + # Python 3.11 and below implementation using sys.settrace + # ========================================================================= + + def _settrace_callback( + self, frame: types.FrameType, event: str, arg: Any + ) -> Callable[..., Any] | None: + """Trace function for sys.settrace.""" + code = frame.f_code + + # Only trace Dynamo-generated code + if code not in self._tracked_codes: + return self._settrace_callback + + if event == "call": + # Enable opcode tracing for this frame + frame.f_trace_opcodes = True + return self._settrace_callback + + elif event == "opcode": + # Get the current instruction offset + offset = frame.f_lasti + self._handle_instruction(code, offset, frame) + return self._settrace_callback + + elif event == "return": + self._handle_return(code, arg, frame) + return self._settrace_callback + + elif event == "exception": + # arg is (exception_type, exception_value, traceback) + offset = frame.f_lasti + exc_type, exc_value, exc_tb = arg + self._handle_exception(code, offset, exc_value) + return self._settrace_callback + + return self._settrace_callback + + # ========================================================================= + # Context manager implementation + # ========================================================================= + + def __enter__(self) -> Self: + """Start the debug context.""" + from torch._C._dynamo.eval_frame import ( + get_bytecode_debugger_callback, + set_bytecode_debugger_callback, + ) + + self._active = True + self._prev_callback = get_bytecode_debugger_callback() + self._code_info.clear() + self._frame_states.clear() + self._tracked_codes.clear() + + if _HAS_SYS_MONITORING: + # Python 3.12+: Use sys.monitoring + try: + sys.monitoring.use_tool_id(self._tool_id, "bytecode_debugger") + except ValueError: + pass + + # Register callbacks (events enabled per-code via set_local_events) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.INSTRUCTION, + self._monitoring_instruction_callback, + ) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.PY_RETURN, + self._monitoring_return_callback, + ) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.RAISE, + self._monitoring_raise_callback, + ) + # RAISE must be a global event (cannot be local) + sys.monitoring.set_events(self._tool_id, sys.monitoring.events.RAISE) + else: + # Python 3.11 and below: Use sys.settrace + self._old_trace = sys.gettrace() + sys.settrace(self._settrace_callback) + + # Set the C callback that will be called before executing Dynamo code + set_bytecode_debugger_callback(self._dynamo_code_callback) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> bool: + """End the debug context.""" + if not self._active: + return False + from torch._C._dynamo.eval_frame import set_bytecode_debugger_callback + + self._active = False + prev = self._prev_callback + set_bytecode_debugger_callback(prev) + + if _HAS_SYS_MONITORING: + if prev is None: + sys.monitoring.set_events(self._tool_id, 0) + try: + sys.monitoring.free_tool_id(self._tool_id) + except ValueError: + pass + else: + # Restore outer context's monitoring callbacks and events + if not isinstance(prev, types.MethodType): + raise AssertionError( + f"Expected prev callback to be a MethodType, got {type(prev)}" + ) + outer = cast("_DebugContext", prev.__self__) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.INSTRUCTION, + outer._monitoring_instruction_callback, + ) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.PY_RETURN, + outer._monitoring_return_callback, + ) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.RAISE, + outer._monitoring_raise_callback, + ) + sys.monitoring.set_events(self._tool_id, sys.monitoring.events.RAISE) + for code in outer._tracked_codes: + sys.monitoring.set_local_events( + self._tool_id, + code, + sys.monitoring.events.INSTRUCTION + | sys.monitoring.events.PY_RETURN, + ) + else: + # Python 3.11 and below: Restore old trace + sys.settrace(self._old_trace) + + return False # Don't suppress exceptions + + +@contextmanager +def debug() -> Generator[_DebugContext, None, None]: + """ + Context manager for debugging Dynamo-generated bytecode. + + Any Dynamo-generated code executed within this context will trigger + the interactive bytecode debugger. + + Example: + >>> # xdoctest: +SKIP + >>> import torch + >>> + >>> @torch.compile + >>> def my_fn(x): + ... return x + 1 + >>> + >>> with torch._dynamo.bytecode_debugger.debug(): + ... my_fn(torch.randn(3)) + """ + ctx = _DebugContext() + try: + with ctx: + yield ctx + except KeyboardInterrupt: + print("\n=== Debug session ended ===") + + +def breakpoint() -> None: + """Programmatic breakpoint for user code. + + Place this in code compiled by Dynamo. During tracing, Dynamo inserts a + BREAKPOINT_MARKER into the compiled bytecode. When the bytecode debugger + is active, execution pauses at this marker. + """ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_transformation.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_transformation.py new file mode 100644 index 0000000000000000000000000000000000000000..53414504974269855da42a43313d423c9d56f6ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_transformation.py @@ -0,0 +1,2110 @@ +""" +This module provides utilities for analyzing, transforming and manipulating Python bytecode. +It includes functionality for: +- Converting between different bytecode formats and versions +- Virtualizing jumps and managing jump targets +- Handling exception tables and their entries +- Managing instruction offsets and extended arguments +- Providing a clean API for bytecode modification and transformation +- Supporting Python version-specific bytecode features +- Generating bytecode from template functions + +The module is designed to work across different Python versions (3.7+) and handles +version-specific bytecode differences transparently. +""" + +import copy +import dataclasses +import dis +import functools +import itertools +import re +import sys +import types +import uuid +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from typing import Any, cast, Optional, TYPE_CHECKING + +from . import config +from .bytecode_analysis import ( + get_indexof, + propagate_line_nums, + remove_extra_line_nums, + stacksize_analysis, +) +from .utils import is_safe_constant + + +if TYPE_CHECKING: + from .output_graph import DynamoTracerOutput + + +@dataclasses.dataclass(slots=True) +class InstructionExnTabEntry: + start: "Instruction" + end: "Instruction" + target: "Instruction" + depth: int + lasti: bool + + def __repr__(self) -> str: + return ( + f"InstructionExnTabEntry(start={self.start.short_inst_repr()}, " + f"end={self.end.short_inst_repr()}, " + f"target={self.target.short_inst_repr()}, " + f"depth={self.depth}, lasti={self.lasti})" + ) + + def __eq__(self, o: object) -> bool: + if not isinstance(o, InstructionExnTabEntry): + return False + return ( + self.start is o.start + and self.end is o.end + and self.target is o.target + and self.depth == o.depth + and self.lasti == o.lasti + ) + + +@dataclasses.dataclass(slots=True) +class Instruction: + """A mutable version of dis.Instruction""" + + opcode: int + opname: str + arg: int | None + argval: Any + offset: int | None = None + starts_line: int | None = None + is_jump_target: bool = False + + positions: Optional["dis.Positions"] = None + # extra fields to make modification easier: + target: Optional["Instruction"] = None + exn_tab_entry: InstructionExnTabEntry | None = None + argrepr: str | None = None + + def __hash__(self) -> int: + return id(self) + + def __eq__(self, other: object) -> bool: + return id(self) == id(other) + + def short_inst_repr(self) -> str: + return f"Instruction(opname={self.opname}, offset={self.offset})" + + def copy_positions(self, other: "Instruction") -> None: + self.starts_line = other.starts_line + self.positions = other.positions + + +if sys.version_info >= (3, 13): + + def convert_instruction(i: dis.Instruction) -> Instruction: + return Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.line_number, + i.is_jump_target, + i.positions, + ) + +elif sys.version_info >= (3, 11): + + def convert_instruction(i: dis.Instruction) -> Instruction: + return Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.starts_line, + i.is_jump_target, + i.positions, + ) + +else: + + def convert_instruction(i: dis.Instruction) -> Instruction: + return Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.starts_line, + i.is_jump_target, + None, + ) + + +class _NotProvided: + def __repr__(self) -> str: + return "_NotProvided" + + +if sys.version_info >= (3, 12): + + def inst_has_op_bits(name: str) -> bool: + return name in ("LOAD_ATTR", "LOAD_GLOBAL", "LOAD_SUPER_ATTR") + +elif sys.version_info >= (3, 11): + + def inst_has_op_bits(name: str) -> bool: + return name == "LOAD_GLOBAL" + +else: + + def inst_has_op_bits(name: str) -> bool: + return False + + +def create_instruction( + name: str, + *, + arg: int | None = None, + argval: Any | None = _NotProvided, + target: Instruction | None = None, +) -> Instruction: + """ + At most one of `arg`, `argval`, and `target` can be not None/_NotProvided. + This is to prevent ambiguity, e.g. does + create_instruction("LOAD_CONST", 5) + mean load the constant at co_consts[5], or load the constant 5? + + If `arg` is not provided, it will be computed during assembly from + `argval` or `target`. + + Bits in the args of instructions LOAD_GLOBAL, LOAD_ATTR (3.12+), and LOAD_SUPER_ATTR + modify the behavior of the instruction. In this case, we allow both `arg` + and `argval` to be set. The value of `arg` here is expected to be the value of + the op bits and the true value of `arg` will be computed during assembly. + If `arg` is not set, the bits are assumed to be 0. + """ + + # allow for instructions with op bits to have both arg and argval specified + if inst_has_op_bits(name): + if target is not None: + raise RuntimeError("target cannot be specified for instruction") + if arg is None: + arg = 0 + else: + cnt = (arg is not None) + (argval is not _NotProvided) + (target is not None) + if cnt > 1: + raise RuntimeError( + "only one of arg, argval, and target can be not None/_NotProvided" + ) + if arg is not None and not isinstance(arg, int): + raise RuntimeError("instruction arg must be int or None") + return Instruction( + opcode=dis.opmap[name], opname=name, arg=arg, argval=argval, target=target + ) + + +# Python 3.11 remaps +def create_jump_absolute(target: Instruction) -> Instruction: + inst = "JUMP_FORWARD" if sys.version_info >= (3, 11) else "JUMP_ABSOLUTE" + return create_instruction(inst, target=target) + + +def is_jump_absolute(target: Instruction) -> bool: + return target.opname in ("JUMP_FORWARD", "JUMP_ABSOLUTE") + + +def create_load_const(val: Any, checked: bool = True) -> Instruction: + """ + In general we should only create `LOAD_CONST` for immutable objects, but + sometimes it's convenient _and safe_ for Dynamo create `LOAD_CONST` for + mutable objects. In such cases, use `checked=False`. + """ + if checked: + if not is_safe_constant(val): + raise AssertionError(f"unsafe constant {val}") + return create_instruction("LOAD_CONST", argval=val) + + +def create_breakpoint() -> list[Instruction]: + """ + Create instructions that trigger the bytecode debugger to stop. + + Usage: + codegen.extend_output(create_breakpoint()) + + When the bytecode debugger is active, execution will pause at this point. + At runtime, these instructions have no effect on program state. + """ + from .bytecode_debugger import BREAKPOINT_MARKER + + return [ + create_instruction("LOAD_CONST", argval=BREAKPOINT_MARKER), + create_instruction("POP_TOP"), + ] + + +def create_dup_top() -> Instruction: + if sys.version_info >= (3, 11): + return create_instruction("COPY", arg=1) + return create_instruction("DUP_TOP") + + +def create_rot_n(n: int) -> list[Instruction]: + """ + Returns a "simple" sequence of instructions that rotates TOS to the n-th + position in the stack. For Python < 3.11, returns a single ROT_* + instruction. If no such instruction exists, an error is raised and the + caller is expected to generate an equivalent sequence of instructions. + For Python >= 3.11, any rotation can be expressed as a simple sequence of + swaps. + """ + if n <= 1: + # don't rotate + return [] + + if sys.version_info >= (3, 11): + # rotate can be expressed as a sequence of swap operations + # e.g. rotate 3 is equivalent to swap 3, swap 2 + return [create_instruction("SWAP", arg=i) for i in range(n, 1, -1)] + + if n <= 4: + return [create_instruction("ROT_" + ["TWO", "THREE", "FOUR"][n - 2])] + return [create_instruction("ROT_N", arg=n)] + + +def add_push_null( + inst_or_insts: Instruction | list[Instruction], +) -> list[Instruction]: + """ + Appends or prepends a PUSH_NULL instruction to `inst_or_insts`, + depending on Python version. Used when you know that + `inst_or_insts` generates a callable that will be called. + + NOTE: Assumes `inst_or_insts` is a single instruction or sequence of + instructions that pushes exactly 1 object to the stack that is to + be called. It is important that you include ALL instructions that + construct the callable - not just the first instruction/a prefix. + + Will attempt to use the NULL push bit for instructions + with such bits (LOAD_GLOBAL 3.11+, LOAD_ATTR 3.12+, LOAD_SUPER_ATTR). + In this case, instructions WILL be modified. + """ + if isinstance(inst_or_insts, Instruction): + insts: list[Instruction] = [inst_or_insts] + else: + if not isinstance(inst_or_insts, list): + raise AssertionError( + f"expected inst_or_insts to be a list, got {type(inst_or_insts)}" + ) + insts = inst_or_insts + + def inst_has_bit_set(idx: int) -> bool: + if insts[idx].arg is None: + raise AssertionError(f"expected insts[{idx}].arg to be not None") + return insts[idx].arg & 1 == 1 # type: ignore[operator] + + def set_inst_bit(idx: int) -> None: + if insts[idx].arg is None: + raise AssertionError(f"expected insts[{idx}].arg to be not None") + insts[idx].arg |= 1 # type: ignore[operator] + + if sys.version_info >= (3, 13): + # In 3.13, NULL follows the callable + if inst_has_op_bits(insts[-1].opname) and not inst_has_bit_set(-1): + # All insts with op bits have the push_null bit as the last one. + # Only set the bit if it hasn't been set - otherwise, we need + # to add another PUSH_NULL. + set_inst_bit(-1) + else: + insts = insts + [create_instruction("PUSH_NULL")] + elif sys.version_info >= (3, 12): + # LOAD_ATTR/LOAD_SUPER_ATTR at the end + # We assume that `insts` will only load 1 object, so + # LOAD_GLOBAL at the end doesn't need to be checked + if inst_has_op_bits(insts[-1].opname) and not inst_has_bit_set(-1): + set_inst_bit(-1) + elif insts[0].opname == "LOAD_GLOBAL" and not inst_has_bit_set(0): + set_inst_bit(0) + else: + insts = [create_instruction("PUSH_NULL")] + insts + elif sys.version_info >= (3, 11): + # 3.11 introduced NULL preceding callable + if inst_has_op_bits(insts[0].opname) and not inst_has_bit_set(0): + set_inst_bit(0) + else: + insts = [create_instruction("PUSH_NULL")] + insts + return insts + + +def add_push_null_call_function_ex( + inst_or_insts: Instruction | list[Instruction], +) -> list[Instruction]: + """Like add_push_null, but the low bit of LOAD_ATTR/LOAD_SUPER_ATTR + is not set, due to an expected CALL_FUNCTION_EX instruction. + """ + if isinstance(inst_or_insts, Instruction): + insts: list[Instruction] = [inst_or_insts] + else: + if not isinstance(inst_or_insts, list): + raise AssertionError( + f"expected inst_or_insts to be a list, got {type(inst_or_insts)}" + ) + insts = inst_or_insts + + if sys.version_info < (3, 11): + return insts + + idx = -1 if sys.version_info >= (3, 13) else 0 + if insts[idx].opname == "LOAD_GLOBAL": + if insts[idx].arg is None: + raise AssertionError( + f"expected insts[{idx}].arg to be not None for LOAD_GLOBAL" + ) + if insts[idx].arg & 1 == 0: # type: ignore[operator] + insts[idx].arg |= 1 # type: ignore[operator] + return insts + + if sys.version_info >= (3, 13): + insts = insts + [create_instruction("PUSH_NULL")] + else: + insts = [create_instruction("PUSH_NULL")] + insts + + return insts + + +def create_call_function(nargs: int, push_null: bool) -> list[Instruction]: + """ + Creates a sequence of instructions that makes a function call. + + `push_null` is used in Python 3.11+ only. It is used in codegen when + a function call is intended to be made with the NULL + fn convention, + and we know that the NULL has not been pushed yet. We will push a + NULL and rotate it to the correct position immediately before making + the function call. + + `push_null` should be True if no NULL is pushed for the callable. + Conversely, `push_null` should be False if a NULL was pushed for the callable. + Prefer using `push_null=False` when possible since we will not need to rotate + NULL to the right place, which is less efficient. + + Generally, you should codegen a function by using `add_push_null` then + `create_call_function` with `push_null=False`. + + Example of when to set push_null False: + + insts = [ + create_instruction("LOAD_GLOBAL", argval="torch"), + create_instruction("LOAD_ATTR", argval="nn"), + create_instruction("LOAD_ATTR", argval="functional"), + create_instruction("LOAD_ATTR", argval="relu"), + ] + insts = add_push_null(insts) + insts.append(create_instruction("LOAD_FAST", argval="x")) + insts.extend(create_call_function(1, False)) + + Example of when to set push_null True: + + insts = [create_instruction("LOAD_FAST", x)] + for should_wrap, wrapper_name in wrappers: + if should_wrap: + insts.extend([ + create_instruction("LOAD_GLOBAL", argval="wrapper1"), + create_instruction("SWAP", arg=2), + *create_call_function(1, True), + ) + """ + if sys.version_info >= (3, 11): + output = [] + if push_null: + output.append(create_instruction("PUSH_NULL")) + # 3.13 swapped NULL and callable + rots = nargs + 1 if sys.version_info >= (3, 13) else nargs + 2 + output.extend(create_rot_n(rots)) + if sys.version_info < (3, 12): + output.append(create_instruction("PRECALL", arg=nargs)) + output.append(create_instruction("CALL", arg=nargs)) + return output + return [create_instruction("CALL_FUNCTION", arg=nargs)] + + +def create_call_function_ex( + has_kwargs: bool, push_null: bool, ignore_314_kwargs_push: bool = False +) -> list[Instruction]: + """ + Assumes that in 3.14+, if has_kwargs=False, there is NOT a NULL + on the TOS for the kwargs. This utility function will add a PUSH_NULL. + + If the caller has already pushed a NULL for the kwargs, then set ignore_314_kwargs_push=True + so we don't push another NULL for the kwargs. + """ + if sys.version_info >= (3, 11): + output = [] + if ( + sys.version_info >= (3, 14) + and not has_kwargs + and not ignore_314_kwargs_push + ): + output.append(create_instruction("PUSH_NULL")) + has_kwargs = True + if push_null: + output.append(create_instruction("PUSH_NULL")) + # 3.13 swapped NULL and callable + # if flags == 1, 2 values popped - otherwise if flags == 0, 1 value + rots = ( + int(has_kwargs) + 2 + if sys.version_info >= (3, 13) + else int(has_kwargs) + 3 + ) + output.extend(create_rot_n(rots)) + output.append(create_instruction("CALL_FUNCTION_EX", arg=int(has_kwargs))) + return output + return [create_instruction("CALL_FUNCTION_EX", arg=int(has_kwargs))] + + +def create_call_method(nargs: int) -> list[Instruction]: + if sys.version_info >= (3, 12): + return [create_instruction("CALL", arg=nargs)] + if sys.version_info >= (3, 11): + return [ + create_instruction("PRECALL", arg=nargs), + create_instruction("CALL", arg=nargs), + ] + return [create_instruction("CALL_METHOD", arg=nargs)] + + +def create_load_method(name: str) -> Instruction: + if sys.version_info >= (3, 12): + # in 3.12, create a LOAD_ATTR instruction with the low bit set + return create_instruction("LOAD_ATTR", arg=1, argval=name) + return create_instruction("LOAD_METHOD", argval=name) + + +def create_setup_with(target: Instruction) -> Instruction: + opname = "BEFORE_WITH" if sys.version_info >= (3, 11) else "SETUP_WITH" + return create_instruction(opname, target=target) + + +def create_swap(n: int) -> list[Instruction]: + if sys.version_info >= (3, 11): + return [create_instruction("SWAP", arg=n)] + # in Python < 3.11, SWAP is a macro that expands to multiple instructions + if n == 1: + return [] + elif n == 2: + return [create_instruction("ROT_TWO")] + elif n == 3: + return [create_instruction("ROT_THREE"), create_instruction("ROT_TWO")] + """ + e.g. swap "a" and "b" in this stack: + 0 a 1 2 3 b + 0 a [1 2 3 b] + 0 a [1 2 3 b] [1 2 3 b] + 0 a [1 2 3 b] [1 2 3 b] -1 + 0 a [1 2 3 b] b + 0 b a [1 2 3 b] + 0 b a [1 2 3 b] [1 2 3 b] + 0 b [1 2 3 b] a [1 2 3 b] + 0 b [1 2 3 b] a [1 2 3 b] -1 + 0 b [1 2 3 a] + 0 b [1 2 3 a] [1 2 3 a] + 0 b [1 2 3 a] [1 2 3 a] reverse + 0 b [a 3 2 1] None + 0 b [a 3 2 1] + 0 b 1 2 3 a + """ + return [ + create_instruction("BUILD_LIST", arg=n - 1), + create_instruction("DUP_TOP"), + create_instruction("LOAD_CONST", argval=-1), + create_binary_subscr(), + create_instruction("ROT_THREE"), + create_instruction("DUP_TOP"), + create_instruction("ROT_THREE"), + create_instruction("LOAD_CONST", argval=-1), + create_instruction("STORE_SUBSCR"), + create_instruction("DUP_TOP"), + create_load_method("reverse"), + *create_call_method(0), + create_instruction("POP_TOP"), + create_instruction("UNPACK_SEQUENCE", arg=n - 1), + ] + + +def get_call_callable_depth(opname: str, arg: int) -> int: + """Return the depth of the callable from TOS for a call instruction. + + Depth is 1-indexed: TOS = 1, below-TOS = 2, etc. This encodes the + per-version stack layouts for every call instruction variant. + + Note: on 3.11-3.12, CPython's CALL can have either NULL or self at the + bottom depending on function vs method call. Dynamo's LOAD_METHOD + normalizes method calls to NULL + bound_method, so the bottom is always + NULL and the callable is always at depth arg + 1. + + Stack layouts (bottom-to-top within the call's frame): + CALL (3.13+): callable NULL arg0 ... argN-1 + CALL (3.11-3.12): NULL callable arg0 ... argN-1 + CALL_KW (3.13+): callable NULL arg0 ... argN-1 kw_names + CALL_FUNCTION (3.10): callable arg0 ... argN-1 + CALL_FUNCTION_KW (3.10): callable arg0 ... argN-1 kw_names + CALL_FUNCTION_EX: + 3.14+: callable NULL args_tuple kwargs_or_null + 3.13: callable NULL args_tuple [kwargs_dict] + 3.11-3.12: NULL callable args_tuple [kwargs_dict] + 3.10: callable args_tuple [kwargs_dict] + """ + if opname in ("CALL", "CALL_KW"): + kw_extra = 1 if opname == "CALL_KW" else 0 + if sys.version_info >= (3, 13): + return arg + 2 + kw_extra + else: + # 3.11-3.12: NULL is always at bottom (Dynamo normalizes + # LOAD_METHOD to NULL + bound_method) + return arg + 1 + kw_extra + elif opname in ("CALL_FUNCTION", "CALL_FUNCTION_KW"): + kw_extra = 1 if opname == "CALL_FUNCTION_KW" else 0 + return arg + 1 + kw_extra + elif opname == "CALL_FUNCTION_EX": + if sys.version_info >= (3, 14): + return 4 + elif sys.version_info >= (3, 13): + return 3 + (arg & 1) + elif sys.version_info >= (3, 11): + return 2 + (arg & 1) + else: + return 2 + (arg & 1) + else: + raise ValueError(f"not a call instruction: {opname}") + + +def create_binary_slice( + start: int | None, end: int | None, store: bool = False +) -> list[Instruction]: + """ + BINARY_SLICE and STORE_SLICE (if `set` is True) for all Python versions + """ + if sys.version_info >= (3, 14): + subscr_inst = ( + create_instruction("STORE_SUBSCR") if store else create_binary_subscr() + ) + return [ + create_load_const(slice(start, end)), + subscr_inst, + ] + elif sys.version_info >= (3, 12): + inst_name = "STORE_SLICE" if store else "BINARY_SLICE" + return [ + create_load_const(start), + create_load_const(end), + create_instruction(inst_name), + ] + else: + inst_name = "STORE_SUBSCR" if store else "BINARY_SUBSCR" + return [ + create_load_const(start), + create_load_const(end), + create_instruction("BUILD_SLICE", arg=2), + create_instruction(inst_name), + ] + + +def create_copy(i: int) -> list[Instruction]: + if sys.version_info >= (3, 11): + return [create_instruction("COPY", arg=i)] + if i == 1: + return [create_instruction("DUP_TOP")] + # COPY 4 + # 0 1 2 3 + # 3 1 2 0 + # 3 1 2 0 0 + # 0 1 2 0 3 + # 0 1 2 3 0 + return [ + *create_swap(i), + create_dup_top(), + *create_swap(i + 1), + *create_swap(2), + ] + + +# mainly for debugging generated bytecode +def create_print_on_stack(depth: int) -> list[Instruction]: + return [ + *add_push_null(create_instruction("LOAD_CONST", argval=print)), + *create_copy(depth + (2 if sys.version_info >= (3, 11) else 1)), + *create_call_function(1, False), + create_instruction("POP_TOP"), + ] + + +# mainly for debugging generated bytecode +def create_print_value(value: Any) -> list[Instruction]: + return [ + *add_push_null(create_instruction("LOAD_CONST", argval=print)), + create_instruction("LOAD_CONST", argval=value), + *create_call_function(1, False), + create_instruction("POP_TOP"), + ] + + +def create_binary_subscr() -> Instruction: + if sys.version_info < (3, 14): + return create_instruction("BINARY_SUBSCR") + # https://github.com/python/cpython/blob/0e46c0499413bc5f9f8336fe76e2e67cf93f64d8/Include/opcode.h#L36 + return create_instruction("BINARY_OP", arg=26) + + +def create_build_tuple(n: int) -> Instruction: + if sys.version_info >= (3, 14) and n == 0: + return create_load_const(()) + return create_instruction("BUILD_TUPLE", arg=n) + + +def linetable_writer( + first_lineno: int, +) -> tuple[list[int], Callable[[int, int], None], Callable[[int], None]]: + """ + Used to create typing.CodeType.co_linetable + See https://github.com/python/cpython/blob/3.10/Objects/lnotab_notes.txt + This is the internal format of the line number table for Python 3.10 + """ + if sys.version_info[:2] != (3, 10): + raise AssertionError( + f"linetable_writer requires Python 3.10, got {sys.version_info[:2]}" + ) + linetable: list[int] = [] + lineno = first_lineno + lineno_delta = 0 + byteno = 0 + + def _update(byteno_delta: int, lineno_delta: int) -> None: + while byteno_delta != 0 or lineno_delta != 0: + byte_offset = max(0, min(byteno_delta, 254)) + line_offset = max(-127, min(lineno_delta, 127)) + if byte_offset == 0 and line_offset == 0: + raise AssertionError("byte_offset and line_offset cannot both be 0") + byteno_delta -= byte_offset + lineno_delta -= line_offset + linetable.extend((byte_offset, line_offset & 0xFF)) + + def update(lineno_new: int, byteno_new: int) -> None: + nonlocal lineno, lineno_delta, byteno + byteno_delta = byteno_new - byteno + byteno = byteno_new + _update(byteno_delta, lineno_delta) + lineno_delta = lineno_new - lineno + lineno = lineno_new + + def end(total_bytes: int) -> None: + _update(total_bytes - byteno, lineno_delta) + + return linetable, update, end + + +def encode_varint(n: int) -> list[int]: + """ + 6-bit chunk encoding of an unsigned integer + See https://github.com/python/cpython/blob/3.11/Objects/locations.md + """ + if n < 0: + raise AssertionError(f"encode_varint requires non-negative n, got {n}") + b = [n & 63] + n >>= 6 + while n > 0: + b[-1] |= 64 + b.append(n & 63) + n >>= 6 + return b + + +if sys.version_info >= (3, 11): + + def linetable_311_writer( + first_lineno: int, + ) -> tuple[list[int], Callable[[dis.Positions | None, int], None]]: + """ + Used to create typing.CodeType.co_linetable + See https://github.com/python/cpython/blob/3.11/Objects/locations.md + This is the internal format of the line number table for Python 3.11 + """ + if sys.version_info < (3, 11): + raise AssertionError( + f"linetable_311_writer requires Python 3.11+, got {sys.version_info}" + ) + linetable = [] + lineno = first_lineno + + def update(positions: dis.Positions | None, inst_size: int) -> None: + nonlocal lineno + lineno_new = positions.lineno if positions else None + + def _update(delta: int, size: int) -> None: + if not (0 < size <= 8): + raise AssertionError(f"size must be in range (0, 8], got {size}") + # first byte - use 13 (no column info) is positions is + # malformed, otherwise use 14 (long form) + other_varints: tuple[int, ...] = () + if ( + positions + and positions.lineno is not None + and positions.end_lineno is not None + and positions.col_offset is not None + and positions.end_col_offset is not None + ): + linetable.append(0b1_1110_000 + size - 1) + # for whatever reason, column offset needs `+ 1` + # https://github.com/python/cpython/blob/1931c2a438c50e6250725c84dff94fc760b9b951/Python/compile.c#L7603 + other_varints = ( + positions.end_lineno - positions.lineno, + positions.col_offset + 1, + positions.end_col_offset + 1, + ) + else: + linetable.append(0b1_1101_000 + size - 1) + # encode signed int + if delta < 0: + delta = ((-delta) << 1) | 1 + else: + delta <<= 1 + # encode unsigned int + linetable.extend(encode_varint(delta)) + for n in other_varints: + linetable.extend(encode_varint(n)) + + if lineno_new is None: + lineno_delta = 0 + else: + lineno_delta = lineno_new - lineno + lineno = lineno_new + while inst_size > 8: + _update(lineno_delta, 8) + inst_size -= 8 + _update(lineno_delta, inst_size) + + return linetable, update + + +@dataclasses.dataclass(slots=True) +class ExceptionTableEntry: + start: int + end: int + target: int + depth: int + lasti: bool + + +def encode_exception_table_varint(n: int) -> list[int]: + """ + Similar to `encode_varint`, but the 6-bit chunks are ordered in reverse. + """ + if n < 0: + raise AssertionError( + f"encode_exception_table_varint requires non-negative n, got {n}" + ) + b = [n & 63] + n >>= 6 + while n > 0: + b.append(n & 63) + n >>= 6 + b.reverse() + for i in range(len(b) - 1): + b[i] |= 64 + return b + + +def decode_exception_table_varint(bytes_iter: Iterator[int]) -> int: + """ + Inverse of `encode_exception_table_varint`. + """ + b = next(bytes_iter) + val = b & 63 + while b & 64: + val <<= 6 + b = next(bytes_iter) + val |= b & 63 + return val + + +def check_exception_table(tab: list[ExceptionTableEntry]) -> None: + """ + Verifies that a list of ExceptionTableEntries will make a well-formed + jump table: entries are non-empty, sorted, and do not overlap. + """ + for i in range(len(tab) - 1): + if not ( + tab[i].start <= tab[i].end + and tab[i].end < tab[i + 1].start + and tab[i + 1].start <= tab[i + 1].end + ): + raise AssertionError( + f"exception table entries are not well-formed at index {i}: " + f"entry[{i}]=(start={tab[i].start}, end={tab[i].end}), " + f"entry[{i + 1}]=(start={tab[i + 1].start}, end={tab[i + 1].end})" + ) + + +def parse_exception_table(exntab: bytes) -> list[ExceptionTableEntry]: + """ + Parse the exception table according to + https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt + """ + exntab_iter = iter(exntab) + tab = [] + try: + while True: + start = decode_exception_table_varint(exntab_iter) * 2 + length = decode_exception_table_varint(exntab_iter) * 2 + end = start + length - 2 + target = decode_exception_table_varint(exntab_iter) * 2 + dl = decode_exception_table_varint(exntab_iter) + depth = dl >> 1 + lasti = bool(dl & 1) + tab.append(ExceptionTableEntry(start, end, target, depth, lasti)) + except StopIteration: + check_exception_table(tab) + return tab + + +def assemble_exception_table(tab: list[ExceptionTableEntry]) -> bytes: + """ + Inverse of parse_exception_table - encodes list of exception + table entries into bytes. + """ + b = [] + for entry in tab: + first_entry = encode_exception_table_varint(entry.start // 2) + first_entry[0] |= 1 << 7 + b.extend(first_entry) + length = entry.end - entry.start + 2 + b.extend(encode_exception_table_varint(length // 2)) + b.extend(encode_exception_table_varint(entry.target // 2)) + dl = (entry.depth << 1) + entry.lasti + b.extend(encode_exception_table_varint(dl)) + return bytes(b) + + +def assemble(instructions: list[Instruction], firstlineno: int) -> tuple[bytes, bytes]: + """Do the opposite of dis.get_instructions()""" + code: list[int] = [] + if sys.version_info >= (3, 11): + lnotab, update_lineno = linetable_311_writer(firstlineno) + num_ext = 0 + for i, inst in enumerate(instructions): + if inst.opname == "EXTENDED_ARG": + inst_size = 1 + num_ext += 1 + # copy positions from the actual instruction + for j in (1, 2, 3): + if instructions[i + j].opname != "EXTENDED_ARG": + inst.positions = instructions[i + j].positions + break + else: + inst_size = instruction_size(inst) // 2 + num_ext + num_ext = 0 + update_lineno(inst.positions, inst_size) + num_ext = 0 + arg = inst.arg or 0 + code.extend((inst.opcode, arg & 0xFF)) + for _ in range(instruction_size(inst) // 2 - 1): + code.extend((0, 0)) + else: + lnotab, update_lineno, end = linetable_writer(firstlineno) + + for inst in instructions: + if inst.starts_line is not None: + update_lineno(inst.starts_line, len(code)) + arg = inst.arg or 0 + code.extend((inst.opcode, arg & 0xFF)) + + end(len(code)) + + return bytes(code), bytes(lnotab) + + +def _get_instruction_by_offset( + offset_to_inst: dict[int, Instruction], offset: int +) -> Instruction | None: + """ + Get the instruction located at a given offset, accounting for EXTENDED_ARGs + """ + for n in (0, 2, 4, 6): + if offset_to_inst[offset + n].opcode != dis.EXTENDED_ARG: + return offset_to_inst[offset + n] + return None + + +def virtualize_jumps(instructions: Iterable[Instruction]) -> None: + """Replace jump targets with pointers to make editing easier""" + jump_targets = { + inst.offset: inst for inst in instructions if inst.offset is not None + } + + for inst in instructions: + if inst.opcode in dis.hasjabs or inst.opcode in dis.hasjrel: + inst.target = _get_instruction_by_offset(jump_targets, inst.argval) + + +_REL_JUMPS = set(dis.hasjrel) + + +def flip_jump_direction(instruction: Instruction) -> None: + if sys.version_info < (3, 11): + raise RuntimeError("Cannot flip jump direction in Python < 3.11") + if "FORWARD" in instruction.opname: + instruction.opname = instruction.opname.replace("FORWARD", "BACKWARD") + elif "BACKWARD" in instruction.opname: + instruction.opname = instruction.opname.replace("BACKWARD", "FORWARD") + else: + raise AttributeError("Instruction is not a forward or backward jump") + instruction.opcode = dis.opmap[instruction.opname] + if instruction.opcode not in _REL_JUMPS: + raise AssertionError( + f"expected {instruction.opname} to be a relative jump instruction" + ) + + +def _get_instruction_front(instructions: list[Instruction], idx: int) -> Instruction: + """ + i.e. get the first EXTENDED_ARG instruction (if any) when targeting + instructions[idx] with a jump. + """ + target = instructions[idx] + for offset in (1, 2, 3): + if idx >= offset and instructions[idx - offset].opcode == dis.EXTENDED_ARG: + target = instructions[idx - offset] + else: + break + return target + + +def devirtualize_jumps(instructions: list[Instruction]) -> None: + """Fill in args for virtualized jump target after instructions may have moved""" + jumps = set(dis.hasjabs).union(set(dis.hasjrel)) + + # check for negative jump args and fix them + for inst in instructions: + if inst.opcode in jumps: + if inst.opcode not in dis.hasjabs: + if inst.target is None: + raise AssertionError( + f"jump instruction {inst.opname} has no target" + ) + if inst.target.offset is None: + raise AssertionError(f"jump target for {inst.opname} has no offset") + if inst.offset is None: + raise AssertionError( + f"jump instruction {inst.opname} has no offset" + ) + if inst.target.offset < inst.offset: + if sys.version_info < (3, 11): + raise RuntimeError("Got negative jump offset for Python < 3.11") + # forward jumps become backward + if "FORWARD" in inst.opname: + flip_jump_direction(inst) + else: + # backward jumps become forward + if sys.version_info >= (3, 11) and "BACKWARD" in inst.opname: + flip_jump_direction(inst) + + # jump instruction size may have changed due to flips + update_offsets(instructions) + indexof = get_indexof(instructions) + + # compute jump instruction arg + for inst in instructions: + if inst.opcode in jumps: + if inst.target is None: + raise AssertionError(f"jump instruction {inst.opname} has no target") + target = _get_instruction_front(instructions, indexof[inst.target]) + if inst.opcode in dis.hasjabs: + if sys.version_info < (3, 11): + # `arg` is expected to be bytecode offset, whereas `offset` is byte offset. + # Divide since bytecode is 2 bytes large. + if target.offset is None: + raise AssertionError("absolute jump target has no offset") + inst.arg = int(target.offset / 2) + else: + raise RuntimeError("Python 3.11+ should not have absolute jumps") + else: # relative jump + # byte offset between target and next instruction + if target.offset is None: + raise AssertionError("relative jump target has no offset") + if inst.offset is None: + raise AssertionError( + f"relative jump instruction {inst.opname} has no offset" + ) + inst.arg = abs( + int(target.offset - inst.offset - instruction_size(inst)) + ) + # pyrefly: ignore [unsupported-operation] + inst.arg //= 2 + inst.argval = target.offset + inst.argrepr = f"to {target.offset}" + + +def virtualize_exception_table( + exn_tab_bytes: bytes, instructions: list[Instruction] +) -> None: + """Replace exception table entries with pointers to make editing easier""" + exn_tab = parse_exception_table(exn_tab_bytes) + offset_to_inst = {cast(int, inst.offset): inst for inst in instructions} + offsets = sorted(offset_to_inst.keys()) + end_offset_idx = 0 + exn_tab_iter = iter(exn_tab) + try: + + def step() -> tuple[ExceptionTableEntry, InstructionExnTabEntry]: + nonlocal end_offset_idx + entry = next(exn_tab_iter) + # find rightmost offset <= entry.end, since entry.end may not be + # an actual instruction, e.g. if the end instruction is LOAD_GLOBAL, + # which takes more than 2 bytes, then entry.end points to the end + # of the LOAD_GLOBAL instruction, not the beginning. + while ( + end_offset_idx < len(offsets) and offsets[end_offset_idx] <= entry.end + ): + end_offset_idx += 1 + if end_offset_idx <= 0: + raise AssertionError( + "end_offset_idx must be positive in exception table virtualization" + ) + end_offset = offsets[end_offset_idx - 1] + inst_entry = InstructionExnTabEntry( + _get_instruction_by_offset(offset_to_inst, entry.start), # type: ignore[arg-type] + _get_instruction_by_offset(offset_to_inst, end_offset), # type: ignore[arg-type] + _get_instruction_by_offset(offset_to_inst, entry.target), # type: ignore[arg-type] + entry.depth, + entry.lasti, + ) + return entry, inst_entry + + entry, inst_entry = step() + for inst in instructions: + if inst.offset is None: + raise AssertionError( + f"instruction {inst.opname} has no offset during exception " + "table virtualization" + ) + while inst.offset > entry.end: + entry, inst_entry = step() + if inst.offset >= entry.start: + inst.exn_tab_entry = copy.copy(inst_entry) + except StopIteration: + pass + + +def compute_exception_table( + instructions: list[Instruction], +) -> list[ExceptionTableEntry]: + """Compute exception table in list format from instructions with exn_tab_entries""" + exn_dict: dict[tuple[int, int], tuple[int, int, bool]] = {} + indexof = get_indexof(instructions) + + for inst in instructions: + if inst.exn_tab_entry: + # account for prefixed EXTENDED_ARGS + start = _get_instruction_front( + instructions, indexof[inst.exn_tab_entry.start] + ).offset + if start is None: + raise AssertionError( + "exception table entry start instruction has no offset" + ) + # point to the last 2 bytes of the end instruction + end = ( + cast(int, inst.exn_tab_entry.end.offset) + + instruction_size(inst.exn_tab_entry.end) + - 2 + ) + if end is None: + raise AssertionError( + "exception table entry end instruction has no offset" + ) + target = _get_instruction_front( + instructions, indexof[inst.exn_tab_entry.target] + ).offset + if target is None: + raise AssertionError( + "exception table entry target instruction has no offset" + ) + key = (start, end) + val = (target, inst.exn_tab_entry.depth, inst.exn_tab_entry.lasti) + if key in exn_dict: + if exn_dict[key] != val: + raise AssertionError( + f"conflicting exception table entries for range " + f"{key}: {exn_dict[key]} vs {val}" + ) + exn_dict[key] = val + + # Dynamo may construct nested exception table entries for convenience, + # but Python expects exception table entries to not overlap. + # NOTE: below, "keys" refer to old instruction entries' starts and ends, + # and "entries" refer to the generated exception table entries. + + # Sort keys by increasing start, then decreasing end + keys_sorted = sorted(exn_dict.keys(), key=lambda t: (t[0], -t[1])) + # smallest byte that the next exception table entry can start at + nexti = 0 + # stack of current nested keys + key_stack: list[tuple[int, int]] = [] + exn_tab: list[ExceptionTableEntry] = [] + + def pop() -> None: + """ + Pop the key_stack and append an exception table entry if possible. + """ + nonlocal nexti + if key_stack: + key = key_stack.pop() + if nexti <= key[1]: + exn_tab.append( + ExceptionTableEntry(max(key[0], nexti), key[1], *exn_dict[key]) + ) + nexti = key[1] + 2 + + for key in keys_sorted: + # pop keys that are no longer nested over the current key + while key_stack and key_stack[-1][1] < key[0]: + pop() + if key_stack: + # create an entry covering to the current key, if possible + if not (key_stack[-1][0] <= key[0] <= key[1] <= key_stack[-1][1]): + raise AssertionError( + f"exception table key {key} is not properly nested within " + f"parent {key_stack[-1]}" + ) + left = max(nexti, key_stack[-1][0]) + if left < key[0]: + exn_tab.append( + ExceptionTableEntry(left, key[0] - 2, *exn_dict[key_stack[-1]]) + ) + nexti = key[0] + key_stack.append(key) + while key_stack: + pop() + check_exception_table(exn_tab) + return exn_tab + + +def check_inst_exn_tab_entries_nested( + tab: list[InstructionExnTabEntry], indexof: dict[Instruction, int] +) -> None: + """ + Checks `tab` is a properly sorted list of nested InstructionExnTabEntry's, + i.e. no entries partially overlap. + "Properly sorted" means entries are sorted by increasing starts, then + decreasing ends. + """ + entry_stack: list[tuple[int, int]] = [] + for entry in tab: + key = (indexof[entry.start], indexof[entry.end]) + while entry_stack and entry_stack[-1][1] < key[0]: + entry_stack.pop() + if entry_stack: + if not (entry_stack[-1][0] <= key[0] <= key[1] <= entry_stack[-1][1]): + raise AssertionError( + f"exception table entry {key} is not properly nested " + f"within parent {entry_stack[-1]}" + ) + entry_stack.append(key) + + +def propagate_inst_exn_table_entries(instructions: list[Instruction]) -> None: + """ + Copies exception table entries to all instructions in an entry's range. + Supports nested exception table entries. + """ + indexof = get_indexof(instructions) + entries: dict[tuple[int, int], InstructionExnTabEntry] = {} + for inst in instructions: + if inst.exn_tab_entry: + key = ( + indexof[inst.exn_tab_entry.start], + indexof[inst.exn_tab_entry.end], + ) + if key in entries: + if inst.exn_tab_entry != entries[key]: + raise AssertionError( + f"conflicting exn_tab_entry for instruction at key {key}" + ) + entries[key] = inst.exn_tab_entry + sorted_entries = [ + entries[key] for key in sorted(entries.keys(), key=lambda t: (t[0], -t[1])) + ] + check_inst_exn_tab_entries_nested(sorted_entries, indexof) + # Propagation of nested entries works since nested entries come later + # in sorted order. + for entry in sorted_entries: + for i in range(indexof[entry.start], indexof[entry.end] + 1): + instructions[i].exn_tab_entry = copy.copy(entry) + + +def check_inst_exn_tab_entries_valid(instructions: list[Instruction]) -> None: + """ + Checks that exn_tab_entries of instructions are valid. + An entry's start, end, and target must be in instructions. + Instructions with an exn_tab_entry are located within + the entry's start and end instructions. + Instructions do not share exn_tab_entries. + + Implicitly checks for no duplicate instructions. + """ + indexof = get_indexof(instructions) + exn_tab_entry_set = set() + for i, inst in enumerate(instructions): + if inst.exn_tab_entry: + if sys.version_info < (3, 11): + raise AssertionError("exn_tab_entry is only supported in Python 3.11+") + if id(inst.exn_tab_entry) in exn_tab_entry_set: + raise AssertionError( + f"duplicate exn_tab_entry at instruction index {i}" + ) + exn_tab_entry_set.add(id(inst.exn_tab_entry)) + entry = inst.exn_tab_entry + if entry.start not in indexof: + raise AssertionError( + "exn_tab_entry start instruction not found in instructions" + ) + if entry.end not in indexof: + raise AssertionError( + "exn_tab_entry end instruction not found in instructions" + ) + if entry.target not in indexof: + raise AssertionError( + "exn_tab_entry target instruction not found in instructions" + ) + if not (indexof[entry.start] <= i <= indexof[entry.end]): + raise AssertionError( + f"instruction at index {i} is outside its exn_tab_entry " + f"range [{indexof[entry.start]}, {indexof[entry.end]}]" + ) + + +def strip_extended_args(instructions: list[Instruction]) -> None: + instructions[:] = [i for i in instructions if i.opcode != dis.EXTENDED_ARG] + + +# Overwrites old_inst with a sequence of new instructions. +# This is necessary in order to preserve jump targets to the old +# instruction, exception table entries, and positions. +# Returns the modified sequence of instructions (including the modified +# old instruction!) that can be manipulated elsewhere. +def overwrite_instruction( + old_inst: Instruction, new_insts: list[Instruction] +) -> list[Instruction]: + # update old_inst.exn_tab_entry.end if necessary + if ( + old_inst.exn_tab_entry + and old_inst.exn_tab_entry.end is old_inst + and len(new_insts) > 1 + ): + old_inst.exn_tab_entry.end = new_insts[-1] + # preserve exception table entries and positions + for inst in new_insts[1:]: + inst.exn_tab_entry = copy.copy(old_inst.exn_tab_entry) + inst.positions = old_inst.positions + # modify old_inst in-place to preserve jump target + old_inst.opcode = new_insts[0].opcode + old_inst.opname = new_insts[0].opname + old_inst.arg = new_insts[0].arg + old_inst.argval = new_insts[0].argval + old_inst.target = new_insts[0].target + return [old_inst] + new_insts[1:] + + +def remove_load_call_method(instructions: list[Instruction]) -> list[Instruction]: + """LOAD_METHOD puts a NULL on the stack which causes issues, so remove it""" + if sys.version_info >= (3, 11): + raise AssertionError( + "remove_load_call_method should not be called on Python 3.11+" + ) + rewrites = {"LOAD_METHOD": "LOAD_ATTR", "CALL_METHOD": "CALL_FUNCTION"} + for inst in instructions: + if inst.opname in rewrites: + inst.opname = rewrites[inst.opname] + inst.opcode = dis.opmap[inst.opname] + return instructions + + +def remove_jump_if_none(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + if "_NONE" in inst.opname: + is_op = create_instruction("IS_OP", arg=int("NOT" in inst.opname)) + # need both argval and arg set correctly now (not later) + is_op.argval = is_op.arg + + if sys.version_info < (3, 12): + jump_op = create_instruction( + ( + "POP_JUMP_FORWARD_IF_TRUE" + if "FORWARD" in inst.opname + else "POP_JUMP_BACKWARD_IF_TRUE" + ), + target=inst.target, + ) + else: + jump_op = create_instruction("POP_JUMP_IF_TRUE", target=inst.target) + + replace_insts = [ + create_instruction("LOAD_CONST", argval=None), + is_op, + jump_op, + ] + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +def remove_binary_store_slice(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + new_insts.append(inst) + if inst.opname in ("BINARY_SLICE", "STORE_SLICE"): + # new instruction + if sys.version_info >= (3, 14) and inst.opname == "BINARY_SLICE": + subscr_inst = create_binary_subscr() + else: + subscr_inst = create_instruction(inst.opname.replace("SLICE", "SUBSCR")) + if inst.exn_tab_entry and inst.exn_tab_entry.end is inst: + inst.exn_tab_entry.end = subscr_inst + subscr_inst.exn_tab_entry = copy.copy(inst.exn_tab_entry) + subscr_inst.positions = inst.positions + # modify inst in-place to preserve jump target + inst.opcode = dis.opmap["BUILD_SLICE"] + inst.opname = "BUILD_SLICE" + inst.arg = 2 + inst.argval = 2 + new_insts.append(subscr_inst) + instructions[:] = new_insts + + +def remove_load_attr_method_variant(instructions: list[Instruction]) -> None: + """On 3.12+, LOAD_ATTR with arg%2==1 is the method variant that pushes 2 + values (NULL/self + method). Normalize it to a non-method LOAD_ATTR + (1 value) followed by PUSH_NULL (+ SWAP on 3.12 where NULL goes below + the callable). This lets break_graph_if_unsupported handle LOAD_ATTR + uniformly as a single-output instruction.""" + new_insts: list[Instruction] = [] + for inst in instructions: + if inst.opname == "LOAD_ATTR" and inst.arg is not None and inst.arg % 2: + replace_insts = [ + create_instruction("LOAD_ATTR", arg=inst.arg & ~1, argval=inst.argval), + create_instruction("PUSH_NULL"), + ] + if sys.version_info < (3, 13): + replace_insts.append(create_instruction("SWAP", arg=2)) + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +FUSED_INSTS = { + "LOAD_FAST_LOAD_FAST": ("LOAD_FAST", "LOAD_FAST"), + "LOAD_FAST_BORROW_LOAD_FAST_BORROW": ("LOAD_FAST_BORROW", "LOAD_FAST_BORROW"), + "STORE_FAST_STORE_FAST": ("STORE_FAST", "STORE_FAST"), + "STORE_FAST_LOAD_FAST": ("STORE_FAST", "LOAD_FAST"), +} + + +def remove_fused_load_store(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + if inst.opname in FUSED_INSTS: + inst0, inst1 = FUSED_INSTS[inst.opname] + argval0, argval1 = inst.argval + + replace_insts = [ + create_instruction(inst0, argval=argval0), + create_instruction(inst1, argval=argval1), + ] + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +# adds GRAPH_BREAK_IF_LEAF (not a real instruction) before RETURN_* instructions +# for testing purposes +def add_graph_break_if_leaf_instructions(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + if "RETURN" in inst.opname: + replace_insts = [ + create_instruction("NOP", argval="GRAPH_BREAK_IF_LEAF"), + create_instruction(inst.opname, argval=inst.argval), + ] + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +def remove_graph_break_if_leaf_instructions(instructions: list[Instruction]) -> None: + new_insts = [] + for inst, next_inst in itertools.pairwise(instructions): + if ( + inst.opname == "NOP" + and inst.argval == "GRAPH_BREAK_IF_LEAF" + and next_inst.opname.startswith("RETURN") + ): + # remove this instruction and update all other instructions' jump targets + for i in range(len(instructions)): + if instructions[i].target is inst: + instructions[i].target = next_inst + if instructions[i].exn_tab_entry: + # linter is mistakenly complaining that None has no attribute "..." + # but this codepath only runs if instructions[i] is not None + if instructions[i].exn_tab_entry.start is inst: # type: ignore[union-attr] + instructions[i].exn_tab_entry.start = next_inst # type: ignore[union-attr] + if instructions[i].exn_tab_entry.end is inst: # type: ignore[union-attr] + instructions[i].exn_tab_entry.end = next_inst # type: ignore[union-attr] + if instructions[i].exn_tab_entry.target is inst: # type: ignore[union-attr] + instructions[i].exn_tab_entry.target = next_inst # type: ignore[union-attr] + else: + new_insts.append(inst) + new_insts.append(instructions[-1]) + instructions[:] = new_insts + + +def explicit_super(code: types.CodeType, instructions: list[Instruction]) -> None: + """convert super() with no args into explicit arg form""" + cell_and_free = (code.co_cellvars or ()) + (code.co_freevars or ()) + if not len(code.co_varnames): + # A function with no argument cannot contain a valid "super()" call + return + output = [] + for idx, inst in enumerate(instructions): + output.append(inst) + if inst.opname == "LOAD_GLOBAL" and inst.argval == "super": + nexti = instructions[idx + 1] + if nexti.arg == 0 and ( + (sys.version_info >= (3, 12) and nexti.opname == "CALL") + or ( + sys.version_info >= (3, 11) + and sys.version_info < (3, 12) + and nexti.opname == "PRECALL" + ) + or (sys.version_info < (3, 11) and nexti.opname == "CALL_FUNCTION") + ): + if "__class__" not in cell_and_free: + raise AssertionError( + "__class__ not found in cell_and_free for super() call" + ) + output.append(create_instruction("LOAD_DEREF", argval="__class__")) + first_var = code.co_varnames[0] + if first_var in cell_and_free: + output.append(create_instruction("LOAD_DEREF", argval=first_var)) + else: + output.append(create_instruction("LOAD_FAST", argval=first_var)) + nexti.arg = 2 + nexti.argval = 2 + if nexti.opname == "PRECALL": + # also update the following CALL instruction + call_inst = instructions[idx + 2] + call_inst.arg = 2 + call_inst.argval = 2 + + instructions[:] = output + + +def fix_extended_args(instructions: list[Instruction]) -> int: + """Fill in correct argvals for EXTENDED_ARG ops""" + output: list[Instruction] = [] + + def maybe_pop_n(n: int) -> None: + for _ in range(n): + if output and output[-1].opcode == dis.EXTENDED_ARG: + output.pop() + + for inst in instructions: + if inst.opcode == dis.EXTENDED_ARG: + # Leave this instruction alone for now so we never shrink code + inst.arg = 0 + elif inst.arg and inst.arg > 0xFFFFFF: + maybe_pop_n(3) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 24)) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 16)) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8)) + elif inst.arg and inst.arg > 0xFFFF: + maybe_pop_n(2) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 16)) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8)) + elif inst.arg and inst.arg > 0xFF: + maybe_pop_n(1) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8)) + output.append(inst) + + added = len(output) - len(instructions) + if added < 0: + raise AssertionError( + f"fix_extended_args removed instructions (added={added}), " + "expected non-negative" + ) + instructions[:] = output + return added + + +def instruction_size(inst: Instruction) -> int: + import torch + + if sys.version_info >= (3, 11): + return 2 * (torch._C._dynamo.eval_frame.py_opcode_caches[inst.opcode] + 1) + return 2 + + +def check_offsets(instructions: Sequence[Instruction]) -> None: + offset = 0 + for inst in instructions: + if inst.offset != offset: + raise AssertionError( + f"instruction {inst.opname} has offset {inst.offset}, expected {offset}" + ) + offset += instruction_size(inst) + + +def update_offsets(instructions: Sequence[Instruction]) -> None: + offset = 0 + for inst in instructions: + inst.offset = offset + + offset += instruction_size(inst) + + +def debug_bytes(*args: bytes) -> str: + index = range(max(map(len, args))) + result = [ + " ".join(f"{x:03}" for x in arg) + for arg in [index] + + list(args) + + [[int(a != b) for a, b in zip(args[-1], args[-2])]] + ] + + return "bytes mismatch\n" + "\n".join(result) + + +def debug_checks(code: types.CodeType) -> None: + """Make sure our assembler produces same bytes as we start with""" + dode, _ = transform_code_object(code, lambda x, y: None, safe=True) + if code.co_code != dode.co_code: + raise AssertionError(debug_bytes(code.co_code, dode.co_code)) + # TODO: reenable after better understanding how to handle sourceless + # (None) codes + # assert list(code.co_lines()) == list(dode.co_lines()), ( + # "line table mismatch via co_lines()" + # ) + + +HAS_LOCAL = set(dis.haslocal) +HAS_NAME = set(dis.hasname) +HAS_FREE = set(dis.hasfree) +HAS_CONST = set(dis.hasconst) + + +def get_const_index(code_options: dict[str, Any], val: Any) -> int: + for i, v in enumerate(code_options["co_consts"]): + # NOTE: stronger comparison is required, since we have + # examples where two values compare equal but have + # different semantic meaning in some cases, e.g. + # 0.0 == -0.0 but have different effects in torch.copysign. + if val is v: + return i + code_options["co_consts"] += (val,) + return len(code_options["co_consts"]) - 1 + + +def fix_vars( + instructions: list[Instruction], + code_options: dict[str, Any], + varname_from_oparg: Callable[..., Any] | None = None, +) -> None: + # compute instruction arg from argval if arg is not provided + names = {name: idx for idx, name in enumerate(code_options["co_names"])} + + def get_name_index(name: str) -> int: + try: + idx = names[name] + except KeyError: + # Add a missing item to co_names + idx = names[name] = len(names) + code_options["co_names"] = (*code_options["co_names"], name) + if len(code_options["co_names"]) != len(names): + raise AssertionError( + f"co_names length {len(code_options['co_names'])} does not " + f"match names dict length {len(names)}" + ) from None + return idx + + if sys.version_info < (3, 11): + if varname_from_oparg is not None: + raise AssertionError("varname_from_oparg should be None for Python < 3.11") + varnames = {name: idx for idx, name in enumerate(code_options["co_varnames"])} + freenames = { + name: idx + for idx, name in enumerate( + code_options["co_cellvars"] + code_options["co_freevars"] + ) + } + else: + if not callable(varname_from_oparg): + raise AssertionError("varname_from_oparg must be callable for Python 3.11+") + allnames = {} + for idx in itertools.count(): + try: + name = varname_from_oparg(idx) + allnames[name] = idx + except IndexError: + break + varnames = {name: allnames[name] for name in code_options["co_varnames"]} + freenames = { + name: allnames[name] + for name in code_options["co_cellvars"] + code_options["co_freevars"] + } + for i in range(len(instructions)): + + def should_compute_arg() -> bool: + # argval is prioritized over arg + return instructions[i].argval is not _NotProvided + + if instructions[i].opname == "LOAD_GLOBAL": + # 3.11 LOAD_GLOBAL requires both arg and argval - see create_instruction + if instructions[i].argval is _NotProvided: + raise AssertionError("LOAD_GLOBAL instruction must have argval set") + if sys.version_info >= (3, 11): + if instructions[i].arg is None: + raise AssertionError( + "LOAD_GLOBAL instruction must have arg set in Python 3.11+" + ) + instructions[i].arg = (get_name_index(instructions[i].argval) << 1) + ( + cast(int, instructions[i].arg) % 2 + ) + else: + instructions[i].arg = get_name_index(instructions[i].argval) + elif instructions[i].opname == "LOAD_ATTR": + # 3.12 LOAD_ATTR requires both arg and argval, like LOAD_GLOBAL + if instructions[i].argval is _NotProvided: + raise AssertionError("LOAD_ATTR instruction must have argval set") + if sys.version_info >= (3, 12): + if instructions[i].arg is None: + raise AssertionError( + "LOAD_ATTR instruction must have arg set in Python 3.12+" + ) + instructions[i].arg = (get_name_index(instructions[i].argval) << 1) + ( + cast(int, instructions[i].arg) % 2 + ) + else: + instructions[i].arg = get_name_index(instructions[i].argval) + elif instructions[i].opname == "LOAD_SUPER_ATTR": + if instructions[i].arg is None: + raise AssertionError("LOAD_SUPER_ATTR instruction must have arg set") + if instructions[i].argval is _NotProvided: + raise AssertionError("LOAD_SUPER_ATTR instruction must have argval set") + # Copy low bit, force second bit on for explicit super (the "+ 2") + instructions[i].arg = ( + (get_name_index(instructions[i].argval) << 2) + + (cast(int, instructions[i].arg) % 2) + + 2 + ) + elif instructions[i].opname in FUSED_INSTS: + if sys.version_info < (3, 13): + raise AssertionError( + f"fused instruction {instructions[i].opname} requires Python 3.13+" + ) + if not isinstance(instructions[i].argval, tuple): + raise AssertionError( + f"fused instruction {instructions[i].opname} argval must be a tuple, " + f"got {type(instructions[i].argval)}" + ) + if len(instructions[i].argval) != 2: + raise AssertionError( + f"fused instruction {instructions[i].opname} argval must have " + f"length 2, got {len(instructions[i].argval)}" + ) + arg_tuple = tuple( + varnames[name] if name in varnames else freenames[name] + for name in instructions[i].argval + ) + instructions[i].arg = (arg_tuple[0] << 4) + (arg_tuple[1] & 15) + elif instructions[i].opcode in HAS_LOCAL: + if should_compute_arg(): + if ( + sys.version_info >= (3, 13) + and instructions[i].argval not in varnames + ): + # instructions like LOAD_FAST used for both local and free vars + instructions[i].arg = freenames[instructions[i].argval] + else: + instructions[i].arg = varnames[instructions[i].argval] + elif instructions[i].opcode in HAS_NAME: + if should_compute_arg(): + arg = get_name_index(instructions[i].argval) + if ( + sys.version_info >= (3, 15) + and instructions[i].opname == "IMPORT_NAME" + ): + arg <<= 2 + # Set the second bit to ensure eager imports, since lazy imports are only valid at module scope + arg |= 0x02 + instructions[i].arg = arg + elif instructions[i].opcode in HAS_FREE: + if should_compute_arg(): + instructions[i].arg = freenames[instructions[i].argval] + elif instructions[i].opcode in HAS_CONST: + # NOTE: only update argval if arg is not provided. This assumes + # that any additions to co_consts are appended. + if instructions[i].arg is None: + # cannot use a dictionary since consts may not be hashable + idx = get_const_index(code_options, instructions[i].argval) + if idx < 0: + raise AssertionError( + f"failed to find constant index for {instructions[i].argval}" + ) + instructions[i].arg = idx + + +def clear_instruction_args(instructions: list[Instruction]) -> None: + # Clear the instruction arg for instructions that have argvals. + # Useful for using dis'd bytecode within generated bytecode. + for inst in instructions: + if ( + inst.argval is not _NotProvided + and ( + inst.opcode in HAS_LOCAL + or inst.opcode in HAS_NAME + or inst.opcode in HAS_FREE + or inst.opcode in HAS_CONST + ) + and inst.opname not in ("LOAD_GLOBAL", "LOAD_ATTR", "LOAD_SUPER_ATTR") + ): + inst.arg = None + + +@functools.lru_cache +def get_code_keys() -> list[str]: + # Python 3.11 changes to code keys are not fully documented. + # See https://github.com/python/cpython/blob/3.11/Objects/clinic/codeobject.c.h#L24 + # for new format. + keys = ["co_argcount"] + keys.append("co_posonlyargcount") + keys.extend( + [ + "co_kwonlyargcount", + "co_nlocals", + "co_stacksize", + "co_flags", + "co_code", + "co_consts", + "co_names", + "co_varnames", + "co_filename", + "co_name", + ] + ) + if sys.version_info >= (3, 11): + keys.append("co_qualname") + keys.append("co_firstlineno") + keys.append("co_linetable") + if sys.version_info >= (3, 11): + # not documented, but introduced in https://github.com/python/cpython/issues/84403 + keys.append("co_exceptiontable") + keys.extend( + [ + "co_freevars", + "co_cellvars", + ] + ) + return keys + + +def transform_code_object( + code: types.CodeType, + transformations: Callable[ + [list[Instruction], dict[str, Any]], Optional["DynamoTracerOutput"] + ], + safe: bool = False, +) -> tuple[types.CodeType, Optional["DynamoTracerOutput"]]: + keys = get_code_keys() + code_options = {k: getattr(code, k) for k in keys} + if len(code_options["co_varnames"]) != code_options["co_nlocals"]: + raise AssertionError( + f"co_varnames length {len(code_options['co_varnames'])} does not " + f"match co_nlocals {code_options['co_nlocals']}" + ) + + instructions = cleaned_instructions(code, safe) + # propagate line nums again for added instructions + propagate_line_nums(instructions) + + tracer_output = transformations(instructions, code_options) + _, bytecode = clean_and_assemble_instructions(instructions, keys, code_options) + return bytecode, tracer_output + + +def clean_and_assemble_instructions( + instructions: list[Instruction], keys: list[str], code_options: dict[str, Any] +) -> tuple[list[Instruction], types.CodeType]: + remove_graph_break_if_leaf_instructions(instructions) + # also implicitly checks for no duplicate instructions + check_inst_exn_tab_entries_valid(instructions) + + code_options["co_nlocals"] = len(code_options["co_varnames"]) + varname_from_oparg = None + if sys.version_info >= (3, 11): + # temporary code object with updated names + tmp_code = types.CodeType(*[code_options[k] for k in keys]) + varname_from_oparg = tmp_code._varname_from_oparg # type: ignore[attr-defined] + fix_vars(instructions, code_options, varname_from_oparg=varname_from_oparg) + + dirty = True + while dirty: + update_offsets(instructions) + devirtualize_jumps(instructions) + # this pass might change offsets, if so we need to try again + dirty = bool(fix_extended_args(instructions)) + + remove_extra_line_nums(instructions) + bytecode, lnotab = assemble(instructions, code_options["co_firstlineno"]) + + code_options["co_linetable"] = lnotab + code_options["co_code"] = bytecode + code_options["co_stacksize"] = stacksize_analysis(instructions) + if set(keys) - {"co_posonlyargcount"} != set(code_options.keys()) - { + "co_posonlyargcount" + }: + raise AssertionError( + f"code_options keys mismatch: expected {set(keys) - {'co_posonlyargcount'}}, " + f"got {set(code_options.keys()) - {'co_posonlyargcount'}}" + ) + if sys.version_info >= (3, 11): + code_options["co_exceptiontable"] = assemble_exception_table( + compute_exception_table(instructions) + ) + + return instructions, types.CodeType(*[code_options[k] for k in keys]) + + +def populate_kw_names_argval(instructions: Sequence[Instruction], consts: Any) -> None: + for inst in instructions: + if inst.opname == "KW_NAMES": + inst.argval = consts[inst.arg] + + +# If safe=True, we do not make any bytecode modifications. +# Mainly used for debugging bytecode_transformation (see debug_checks) +def cleaned_instructions(code: types.CodeType, safe: bool = False) -> list[Instruction]: + instructions = _cached_cleaned_instructions(code, safe) + # We have a lot of code that implicitly mutates the instruction array. We + # could do better here by making the copies explicit when necessary. + return _clone_instructions(instructions) + + +# Copy an instructions array, making sure to remap the individual instruction targets. +def _clone_instructions(instructions: Sequence[Instruction]) -> list[Instruction]: + # This is super hot and this is the fastest way to do this (tried copy.copy + # and dataclasses.replace). + copied = [ + Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.starts_line, + i.is_jump_target, + i.positions, + i.target, + i.exn_tab_entry, + i.argrepr, + ) + for i in instructions + ] + + remap = dict(zip(instructions, copied)) + # Handle `None` in the remapper so we don't need an extra `if`. + remap[None] = None # type: ignore[index, assignment] + + for i in copied: + i.target = remap[i.target] # type: ignore[index] + if entry := i.exn_tab_entry: + i.exn_tab_entry = InstructionExnTabEntry( + remap[entry.start], + remap[entry.end], + remap[entry.target], + entry.depth, + entry.lasti, + ) + return copied + + +@functools.lru_cache +def _cached_cleaned_instructions( + code: types.CodeType, safe: bool = False +) -> Sequence[Instruction]: + instructions = list(map(convert_instruction, dis.get_instructions(code))) + # propagate now in case we remove some instructions + propagate_line_nums(instructions) + check_offsets(instructions) + if sys.version_info >= (3, 11): + populate_kw_names_argval(instructions, code.co_consts) + virtualize_exception_table(code.co_exceptiontable, instructions) + virtualize_jumps(instructions) + strip_extended_args(instructions) + if not safe: + if sys.version_info < (3, 11): + remove_load_call_method(instructions) + if sys.version_info < (3, 12): + explicit_super(code, instructions) + if sys.version_info >= (3, 11): + remove_jump_if_none(instructions) + if sys.version_info >= (3, 12): + remove_binary_store_slice(instructions) + remove_load_attr_method_variant(instructions) + if sys.version_info >= (3, 13): + remove_fused_load_store(instructions) + if config.debug_force_graph_break_on_leaf_return: + add_graph_break_if_leaf_instructions(instructions) + if sys.version_info >= (3, 11): + update_offsets(instructions) + devirtualize_jumps(instructions) + return instructions + + +_unique_id_counter = itertools.count() + + +def unique_id(name: str, with_uuid: bool = False) -> str: + ret = f"{name}_{next(_unique_id_counter)}" + if with_uuid: + ret += f"_{uuid.uuid4()}".replace("-", "_") + return ret + + +COMPILED_FN_PREFIX = "__compiled_fn" +_COMPILED_FN_NAME_RE = re.compile( + rf"^{COMPILED_FN_PREFIX}_\d+_" + r"[0-9a-f]{8}_[0-9a-f]{4}_[0-9a-f]{4}_[0-9a-f]{4}_[0-9a-f]{12}$" +) + + +def make_compiled_fn_name() -> str: + return unique_id(COMPILED_FN_PREFIX, with_uuid=True) + + +def is_compiled_fn_name(name: str) -> bool: + return _COMPILED_FN_NAME_RE.fullmatch(name) is not None + + +def is_generator(code: types.CodeType) -> bool: + co_generator = 0x20 + return (code.co_flags & co_generator) > 0 + + +def bytecode_from_template( + fn: Callable[..., Any], + varname_map: Mapping[Any, Any] | None = None, + noreturn: bool = True, + noprefix: bool = True, +) -> list[Instruction]: + """Generates bytecode from a template function `fn` for use in + dynamo bytecode generation. + + For example, we can generate Python-version-independent bytecode + for looping through a dictionary and copying the values to a new dictionary. + + def template(d1, d2): + for k, v in d1.items(): + d2[k] = v + + + or a try block: + + def template(): + try: + dummy1 + except: + dummy2 + raise + dummy3 + + Args: + fn: a function template to generate bytecode from + varname_map: a mapping of `fn`'s varnames to new names. This + map will be applied to the generated bytecode's varnames. + For example, local variables in `fn` can be replaced with + new names that are generated by `OutputGraph.new_var`. + noreturn: remove all RETURN_* bytecodes and replace them with a jump + to the end of the bytecode. NOTE: any items pushed to the stack + for return WILL remain on the stack! Append a POP_TOP if you don't want + that item to be present. + noprefix: remove prefix bytecodes (all bytecode before the first RESUME, inclusive). + """ + insts = cleaned_instructions(fn.__code__) + clear_instruction_args(insts) + + if noprefix: + for i, inst in enumerate(insts): + if inst.opname == "RESUME": + insts = insts[i + 1 :] + break + + for inst in insts: + # If we don't reset starts_line, then the generated + # bytecode's line number will be based on fn's. + inst.starts_line = None + inst.positions = None + if varname_map and inst.argval in varname_map: + inst.argval = varname_map[inst.argval] + + if noreturn: + if sys.version_info >= (3, 12): + # replace RETURN_CONST with LOAD_CONST RETURN_VALUE + new_insts = [] + for inst in insts: + if inst.opname == "RETURN_CONST": + inst.opcode = dis.opmap["LOAD_CONST"] + inst.opname = "LOAD_CONST" + new_insts.append(inst) + # no need to propagate target/exn table + new_insts.append(create_instruction("RETURN_VALUE")) + else: + new_insts.append(inst) + insts = new_insts + + # pyrefly: ignore [implicit-any] + returns = [] + for inst in insts: + if inst.opname == "RETURN_VALUE": + returns.append(inst) + + if len(returns) == 1 and returns[0] is insts[-1]: + # only 1 return at the end - just pop it + insts.pop(-1) + elif len(returns) > 0: + # create jump target - if the last inst is a return, + # we can replace it with a NOP and make that the jump target. + if insts[-1] is returns[-1]: + insts[-1].opname = "NOP" + insts[-1].opcode = dis.opmap["NOP"] + insts[-1].arg = None + insts[-1].argval = _NotProvided + returns.pop(-1) + else: + insts.append(create_instruction("NOP")) + + # replace returns with jumps + for inst in returns: + # don't replace inst with new instruction + # due to targeting/exn table/etc. + jump_inst = create_jump_absolute(insts[-1]) + inst.opname = jump_inst.opname + inst.opcode = jump_inst.opcode + inst.arg = jump_inst.arg + inst.argval = jump_inst.argval + inst.target = jump_inst.target + + return insts diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/cache_size.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/cache_size.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd8d18eafad0f89c303d911dbef1a116c11938f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/cache_size.py @@ -0,0 +1,197 @@ +import logging +import weakref +from dataclasses import dataclass +from typing import Any + +from torch._guards import CompileId + +from . import config +from .types import DynamoFrameType + + +log: logging.Logger = logging.getLogger(__name__) +""" +[Note on cache size limit] + +Background - TorchDynamo cache is a linked list. Each cache entry is a +(guard_manager, out_code, next pointer). These are stored on the f_code's co_extra +scratch space. When a frame is invoked, we walk this linked list and run +guard_manager in each cache_entry to decide if the frame needs recompilation. If none +of the guard_manager's returns True, we recompile and add a new entry. To ensure we +don't end up recompiling infinitely, we put limits on the cache size. + +There are two limits +1) recompile_limit +2) accumulated_recompile_limit + + +Earlier we used to have only one limit - maximum number of entries in 1 cache line +(which is now represented by (2) above). So, why do we need two limits? Let's try +to understand that. + +In general, we want our cache limit value to be a small number (e.g. 8 or even +lower). This ensures that for frames that cause too many recompilations fall to +eager quickly. However, there is another problem that prevents us from lowering +the value of recompile_limit. This is due to ID_MATCH'd guards. Today, we put +ID_MATCH guards on nn module if there is a graph break. This means we will have +many recompilations for the same code object because the ID_MATCH guard fails +for different instances of the nn module. This is a common pattern in how models +are authored. Therefore, this requires us to keep the recompile_limit high. + +We resolve this by introducing these two limits. The first limit (1) limits the +number of cache entries that have an ID_MATCH'd guard for an nn module instance. +And, (2)nd limit becomes a safeguard mechanism to have a maximum compilations +for a code object. One important question is - what is the limit for the code +object that does not have any ID_MATCH guard? For such code objects, we choose +(1) as the cache size limit. + +Let's take an example to understand how these limits help. Suppose, we have 16 +instances of a nn module and we ID_MATCH on the self object. Further, suppose +the inputs to these functions have varying batch size, leading to one +recompilation. In total, there will be 32 recompilations, and therefore 32 cache +entries on the forward code object. In the older case when we had only 1 limit, +our cache size limit must be >= 32 to capture all these recompilations. Now, +suppose there is a separate function in the same program which is very dynamic +and unsuitable for compilation. Such a function will need to undergo 32 +compilations to burst the cache and fallback to eager. These 32 recompilations +are too many and we want to fallback for these compilation-unfriendly functions +sooner. + +In the new scenario, we can have (1) recompile_limit = 2, (2) +accumulated_recompile_limit = 32. This means that each ID_MATCH'd object can +have maximum of two cache entries, and the maximum number of cache entries +(irrespective of ID_MATCH obj) is 32. This covers the case of forward code +object which has 32 recompilations. For the other function, the one unsuitable +for recompilation, our limit is 2. So, we will burst the cache in just 2 +recompilations. In this manner, these 2 limits help us resolve the tension +mentioned earlier. +""" + + +@dataclass +class CacheSizeRelevantForFrame: + """ + We track the number of cache entries that have same id_match objects as the + given frame. + + TODO(janimesh) - Consider adding a map from tuple_of_match_ids to count - + https://github.com/pytorch/pytorch/pull/107496#discussion_r1304564682 - this + could be useful for debugging as well. + """ + + # Number of CacheEntry objects in this region's cache list + num_cache_entries: int = 0 + + # Number of CacheEntry objects having same ID_MATCH'd objects as given frame. + num_cache_entries_with_same_id_matched_objs: int = 0 + + # Total cache entries across ALL regions on this code object. + # Used for accumulated_recompile_limit which is a global safety cap. + total_cache_entries_all_regions: int = 0 + + def will_compilation_exceed(self, limit: int) -> bool: + # Checks if a compilation will exceed the given limit (that's why >=). + return ( + self.will_compilation_exceed_accumulated_limit() + or self.will_compilation_exceed_specific_limit(limit) + ) + + def will_compilation_exceed_accumulated_limit(self) -> bool: + # accumulated_recompile_limit is a global safety cap across all regions. + return ( + self.total_cache_entries_all_regions >= config.accumulated_recompile_limit + ) + + def will_compilation_exceed_specific_limit(self, limit: int) -> bool: + return self.num_cache_entries_with_same_id_matched_objs >= limit + + +def _get_weakref_from_f_locals( + frame: DynamoFrameType, local_name: str +) -> weakref.ref[Any] | None: + obj = frame.f_locals.get(local_name, None) + weak_id = None + try: + weak_id = weakref.ref(obj) + except TypeError: + pass # cannot weakref bool object + return weak_id + + +def _has_same_id_matched_objs(frame: DynamoFrameType, cache_entry: Any) -> bool: + """ + Checks if the ID_MATCH'd objects saved on cache_entry are same as the ones + in frame.f_locals. + """ + if not cache_entry: + return False + + for ( + local_name, + weakref_from_cache_entry, + ) in cache_entry.guard_manager.id_matched_objs.items(): + if weakref_from_cache_entry() is not None: + weakref_from_frame = _get_weakref_from_f_locals(frame, local_name) + if weakref_from_frame is not weakref_from_cache_entry: + return False + + # Also covers the case where no ID_MATCH objects are saved in frame.f_locals + return True + + +def compute_cache_size( + frame: DynamoFrameType, + cache_entries: list[Any], + total_cache_entries_all_regions: int = 0, +) -> CacheSizeRelevantForFrame: + # cache_entries is already scoped to a single isolate_recompiles region. + # recompile_limit is checked per-region. accumulated_recompile_limit uses + # total_cache_entries_all_regions as a global safety cap. + num_cache_entries = 0 + num_cache_entries_with_same_id_matched_objs = 0 + + for cache_entry in cache_entries: + num_cache_entries += 1 + if _has_same_id_matched_objs(frame, cache_entry): + num_cache_entries_with_same_id_matched_objs += 1 + + return CacheSizeRelevantForFrame( + num_cache_entries, + num_cache_entries_with_same_id_matched_objs, + max(total_cache_entries_all_regions, num_cache_entries), + ) + + +def is_recompilation(cache_size: CacheSizeRelevantForFrame) -> bool: + """ + If the frame (earlier parsed by compute_cache_size) has more than 1 cache + entry with same ID_MATCH'd objects, then its a recompilation. + """ + # Note that you can have multiple entries in the cache but still not a + # recompile, e.g., you can have 64 nn module instances, each one having an + # ID_MATCH guard, and each one having just 1 cache entry in the cache. In + # this case, we can have 64 entries in the cache, but no recompilation + # because there is only one entry for each id_matched_obj. + return cache_size.will_compilation_exceed(1) + + +def exceeds_recompile_limit( + cache_size: CacheSizeRelevantForFrame, compile_id: CompileId +) -> tuple[bool, str]: + """ + Checks if we are exceeding the cache size limit. + """ + if cache_size.will_compilation_exceed_accumulated_limit(): + return True, "accumulated_recompile_limit" + if cache_size.will_compilation_exceed_specific_limit(config.recompile_limit): + return True, "recompile_limit" + # NOTE this check is needed in the case that the frame's cache doesn't grow + # and we keep recompiling. This can happen if the guard guard_manager becomes invalidated, + # e.g. due to guarded objects being freed. This technically makes the + # will_compilation_exceed_accumulated_limit check unnecessary, but we will keep the + # check in case we have a better fix in the future. + if compile_id.frame_compile_id is None: + raise AssertionError("compile_id.frame_compile_id must not be None") + if compile_id.frame_compile_id >= config.accumulated_recompile_limit: + return True, "accumulated_recompile_limit" + return False, "" diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/callback.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..5723d849876f0597b33e0a6686e46e3851487458 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/callback.py @@ -0,0 +1,175 @@ +""" +This module provides callback management functionality for TorchDynamo's compilation process. + +It implements a thread-safe system for registering, managing and executing callbacks that run +at the start and end of TorchDynamo compilations. Key features include: + +- Registration and deregistration of compilation callbacks +- Thread-safe callback handling with proper locking mechanisms +- Prevention of duplicate callback execution when configured +- Decorator utilities for easy callback registration +- Context manager for controlled callback lifecycle + +The module centers around the CompilationCallbackHandler class which maintains separate +lists for start and end callbacks, manages their execution order, and ensures thread-safety. +Utility decorators @on_compile_start and @on_compile_end provide a convenient way to +register compilation hooks. + +Example usage: + @on_compile_start + def my_start_callback(): + print("Starting compilation") + + @on_compile_end + def my_end_callback(): + print("Compilation complete") +""" + +import enum +import threading +from collections.abc import Callable, Generator +from contextlib import contextmanager +from dataclasses import dataclass, field +from typing import Any + + +class CallbackTrigger(enum.Enum): + # most common case, dynamo attempts to trace a new frame + DYNAMO = 1 + # backward compilation can be deferred to runtime + LAZY_BACKWARD = 2 + # some backends autotune at runtime + TRITON_AUTOTUNING = 3 # Temporarily disabled due to spam + # cudagraphs record at runtime + CUDAGRAPH_RECORDING = 4 + + +@dataclass +class CallbackArgs: + callback_trigger: CallbackTrigger + compile_id: str + + +@dataclass +class CompilationCallbackHandler: + start_callbacks: list[Callable[[CallbackArgs], None]] = field(default_factory=list) + end_callbacks: list[Callable[[CallbackArgs], None]] = field(default_factory=list) + + __pending_callbacks_counter: int = field(default=0, init=False, repr=False) + __pending_callbacks_counter_lock: threading.Lock = field( + default_factory=threading.Lock, init=False, repr=False + ) + + def register_start_callback( + self, callback: Callable[[CallbackArgs], None] + ) -> Callable[[CallbackArgs], None]: + """ + Register a callback function to be called when the compilation starts. + + Args: + - callback (Callable): The callback function to register. + """ + self.start_callbacks.append(callback) + return callback + + def register_end_callback( + self, callback: Callable[[CallbackArgs], None] + ) -> Callable[[CallbackArgs], None]: + """ + Register a callback function to be called when the compilation ends. + + Args: + - callback (Callable): The callback function to register. + """ + self.end_callbacks.append(callback) + return callback + + def remove_start_callback(self, callback: Callable[[CallbackArgs], None]) -> None: + """ + Remove a registered start callback function. + + Args: + - callback (Callable): The callback function to remove. + """ + self.start_callbacks.remove(callback) + + def remove_end_callback(self, callback: Callable[[CallbackArgs], None]) -> None: + """ + Remove a registered end callback function. + + Args: + - callback (Callable): The callback function to remove. + """ + self.end_callbacks.remove(callback) + + def run_start_callbacks(self, args: CallbackArgs) -> None: + """ + Execute all registered start callbacks. + """ + for callback in self.start_callbacks: + callback(args) + + def run_end_callbacks(self, args: CallbackArgs) -> None: + """ + Execute all registered end callbacks. + """ + for callback in self.end_callbacks: + callback(args) + + @contextmanager + def install_callbacks( + self, trigger: CallbackTrigger, compile_id: str + ) -> Generator[None, Any, Any]: + """ + Context manager to install the callbacks and run them when the context is exited. + """ + args = CallbackArgs(trigger, compile_id) + try: + with self.__pending_callbacks_counter_lock: + self.__pending_callbacks_counter += 1 + if self.__pending_callbacks_counter == 1: + self.run_start_callbacks(args) + yield + finally: + with self.__pending_callbacks_counter_lock: + if self.__pending_callbacks_counter <= 0: + raise AssertionError( + "Pending callbacks counter cannot become negative." + ) + if self.__pending_callbacks_counter == 1: + self.run_end_callbacks(args) + self.__pending_callbacks_counter -= 1 + + def clear(self) -> None: + """ + Clear all registered callbacks. + """ + self.start_callbacks.clear() + self.end_callbacks.clear() + if self.__pending_callbacks_counter != 0: + raise AssertionError( + f"Cannot clear callbacks while {self.__pending_callbacks_counter} are pending" + ) + + +callback_handler = CompilationCallbackHandler() + + +def on_compile_start( + callback: Callable[[CallbackArgs], None], +) -> Callable[[CallbackArgs], None]: + """ + Decorator to register a callback function for the start of the compilation. + """ + callback_handler.register_start_callback(callback) + return callback + + +def on_compile_end( + callback: Callable[[CallbackArgs], None], +) -> Callable[[CallbackArgs], None]: + """ + Decorator to register a callback function for the end of the compilation. + """ + callback_handler.register_end_callback(callback) + return callback diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/code_context.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/code_context.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a0a55752828277a5ea30622bde5e5436c821ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/code_context.py @@ -0,0 +1,61 @@ +""" +This module provides thread-safe code context management for TorchDynamo using weak references. + +The CodeContextDict class maintains a mapping between Python code objects and their associated +context data, using weak references to automatically clean up entries when code objects are +garbage collected. This prevents memory leaks while allowing context data to be associated +with code objects throughout their lifecycle. + +Key features: +- Thread-safe context storage and retrieval +- Automatic cleanup using weak references +- Safe context management for Python code objects +- Memory-leak prevention + +Example usage: + code_obj = compile('x = 1', '', 'exec') + + # Store context + context = code_context.get_context(code_obj) + context['metadata'] = {'optimized': True} + + # Retrieve context + if code_context.has_context(code_obj): + ctx = code_context.get_context(code_obj) + # Use context data... + + # Remove context + ctx = code_context.pop_context(code_obj) +""" + +import types +from typing import Any + +from .utils import ExactWeakKeyDictionary + + +class CodeContextDict: + def __init__(self) -> None: + self.code_context: ExactWeakKeyDictionary = ExactWeakKeyDictionary() + + def has_context(self, code: types.CodeType) -> bool: + return code in self.code_context + + def get_context(self, code: types.CodeType) -> dict[str, Any]: + ctx = self.code_context.get(code) + if ctx is None: + # pyrefly: ignore [implicit-any] + ctx = {} + self.code_context[code] = ctx + return ctx + + def pop_context(self, code: types.CodeType) -> dict[str, Any]: + ctx = self.get_context(code) + self.code_context._remove_id(id(code)) + return ctx + + def clear(self) -> None: + self.code_context.clear() + + +code_context: CodeContextDict = CodeContextDict() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/codegen.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..9679284fefecd9c1bedf35e1f9b6b58710f475cf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/codegen.py @@ -0,0 +1,829 @@ +""" +This module provides utilities for generating Python bytecode in PyTorch's Dynamo system. +It includes functionality for: +- Constructing bytecode sequences for Python operations +- Managing stack operations and variable tracking +- Handling graph outputs and their conversions +- Supporting different Python versions (3.11+, 3.12+, 3.13+) +- Converting high-level operations to low-level bytecode instructions +- Managing constant loading and attribute access +- Supporting function creation and closure handling +""" + +import collections +import dataclasses +import re +import sys +import types +from collections import Counter, deque +from collections.abc import Callable, Iterable +from typing import Any, TYPE_CHECKING, Union + +import torch.nn +from torch._library.opaque_object import is_opaque_constant_type +from torch.utils._ordered_set import OrderedSet + +from . import config, graph_break_hints, utils +from .bytecode_transformation import ( + add_push_null, + add_push_null_call_function_ex, + create_binary_subscr, + create_build_tuple, + create_call_function, + create_call_function_ex, + create_call_method, + create_dup_top, + create_instruction, + create_load_const, + create_load_method, + create_rot_n, + Instruction, +) +from .exc import unimplemented +from .source import AttrSource, ChainedSource, DictGetItemSource, Source +from .utils import is_safe_constant, rot_n_helper +from .variables.base import ValueMutationExisting, VariableTracker +from .variables.functions import ( + ContextlibContextManagerLocalGeneratorObjectVariable, + LocalGeneratorObjectVariable, +) +from .variables.lazy import ComputedLazyConstantVariable +from .variables.nn_module import NNModuleVariable +from .variables.script_object import CustomClassObjectVariable +from .variables.tensor import ( + NumpyNdarrayVariable, + SymNodeVariable, + TensorVariable, + UnspecializedPythonVariable, +) +from .variables.torch_function import TensorWithTFOverrideVariable + + +if TYPE_CHECKING: + from torch._dynamo.variables.builder import GraphArg + + from .symbolic_convert import InstructionTranslatorBase + + +@dataclasses.dataclass +class GraphOutputEntry: + index: int + variable: VariableTracker + + +class PyCodegen: + """ + Helper class uses for constructing Python bytecode + """ + + def __init__( + self, + tx: "InstructionTranslatorBase", + root: torch.nn.Module | None = None, + graph_output_var: str | None = None, + tempvars: dict[VariableTracker | Source, Any] | None = None, + overridden_sources: dict[Source, Source] | None = None, + ) -> None: + self.root = root + self.top_of_stack: VariableTracker | Source | None = None + self.uses: Counter[VariableTracker | Source] = collections.Counter() + self.graph_outputs: dict[int, GraphOutputEntry] = {} + self._output: list[Instruction] = [] + # This determines which VariableTracker/Source should be stored as + # locals, and maps the VariableTracker/Source to the local variable + # name. Note that it could map to None initially, in which case we'll + # overwrite it to map to real temporary names via `add_cache`. + self.tempvars: dict[VariableTracker | Source, Any] = tempvars or {} + self.tx = tx + self.graph_output_var = graph_output_var + self.code_options = self.tx.output.code_options + self.cell_and_freevars = self.tx.cell_and_freevars + self.new_var = self.tx.output.new_var + self.value_from_source: bool = True + # This serves as a way for codegen to use a different source; we need + # this because sometimes we can't easily modify the original source + # without affecting other components, e.g., guards. + self.overridden_sources: dict[Source, Source] = overridden_sources or {} + self.pycodes = [] + + def add_pycode(self, pycode: str, *args): + if not config.generate_pycode: + return + for a in args: + if isinstance(a, VariableTracker): + a.realize() + self.pycodes.append(pycode.format(*[a.reconstruct_pycode(self) for a in args])) + + def restore_stack( + self, stack_values: list[Any], *, value_from_source: bool = True + ) -> None: + prev = self.value_from_source + self.value_from_source &= value_from_source + try: + self.foreach(stack_values) + # `restore_stack` is called once per codegen pass (e.g. pass1 for + # use tracking, pass2 for actual emission). Reset the stack counter + # so each pass produces the same `__stackN` names. + self.tx.reset_pycode_varname_counter("stack") + for v in stack_values: + self.add_pycode(f"{self.tx.new_pycode_varname('stack')} = {{}}", v) + finally: + self.value_from_source = prev + + def graph_output_vars(self) -> list[VariableTracker]: + return [x.variable for x in self.graph_outputs.values()] + + def call_reconstruct( + self, value: Union[VariableTracker, Source, "GraphArg"] + ) -> None: + res = value.reconstruct(self) + if res is not None: + raise AssertionError(f"reconstruct!=None {value}") + + def add_push_null( + self, gen_fn: Callable[[], None], call_function_ex: bool = False + ) -> None: + """ + `gen_fn` generates instructions via PyCodegen methods + that push a single callable to the stack. + + `add_push_null` pushes a NULL to the stack before or after the + instructions generated by `gen_fn`, depending on Python version. + + Will attempt to use the NULL push bit for instructions + with such bits (LOAD_GLOBAL 3.11+, LOAD_ATTR 3.12+, LOAD_SUPER_ATTR). + """ + old_len = len(self._output) + if sys.version_info < (3, 13): + # gen_fn may DUP_TOP instead if TOS is not cleared. + # Will cause problems since NULL will be pushed right + # before the generated instructions in <= 3.12 + self.clear_tos() + gen_fn() + # inplace modify self._output + added_insts = self._output[old_len:] + del self._output[old_len:] + if call_function_ex: + self._output.extend(add_push_null_call_function_ex(added_insts)) + else: + self._output.extend(add_push_null(added_insts)) + if sys.version_info >= (3, 13): + # NULL will be at top of stack + self.clear_tos() + + def __call__( + self, value: VariableTracker | Source | None, allow_cache: bool = True + ) -> None: + """ + Generate code such that top-of-stack (TOS) is set to value. + + `allow_cache` controls the behavior in the following manner. `value` can + either be a VariableTracker or a Source. + + If `value` is a `Source`, `allow_cache` must be True (invariant asserted + below). If the source was reconstructed earlier, we will reuse the + generated code by loading from top of stack or tempvars. + + If `value` is a `VariableTracker`, we have the following cases: + + 1) `allow_cache=True` + a) If the value.source is not None, we will emit the code based on + `value.source` to handle aliasing. + b) If value.source is None (example reconstructing a local list + returned by the compiled function), we will reconstruct the variable + tracker (w/o any source) to emit bytecode that generates a new + python object. + + In both cases of value.source being None or not, if the value was + reconstructed earlier, we will reuse the generated code by loading from + top of stack or tempvars. + + 2) `allow_cache=False` - This is a special case (allow_cache defaults to + True). + a) If the value.source is not None, we reconstruct the variable + tracker and emit a new python object. You might wonder what about + aliasing? The place where we use this config also has the followup + code where the original python object is assigned to this new python + value to handle aliasing (check side_effects.py and search for + allow_cache=False). + + b) If value.source is None, this is not allowed + + Notable effects: + 1. `self.top_of_stack` will be set to `value`, if we don't codegen + `value` based on source. + 2. `self.uses[value]` will increment, unless (a). we codegen via + `top_of_stack` or cached `tempvars`, or (b). `value` has special VT + types like `NNModuleVariable`, etc. + """ + if value is None: + raise AssertionError("value must not be None") + if isinstance(value, Source): + # If the source needs to be overridden, use the new one. + source = self.overridden_sources.get(value, value) + if allow_cache is not True: + raise AssertionError("allow_cache must be True for Source") + if self.top_of_stack is value: + self._output.append(create_dup_top()) + return + + if self.tempvars.get(source) is not None: + self._output.append(self.create_load(self.tempvars[source])) + self.top_of_stack = source + return + + self.uses[source] += 1 + try: + self.call_reconstruct(source) + except NotImplementedError: + unimplemented( + gb_type="Reconstruction failure: source.reconstruct not implemented", + context=str(source), + explanation=f"Dynamo has no bytecode reconstruction implemented for {type(source)} variable {source}.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + if source in self.tempvars: + self._output.append(create_dup_top()) + self.add_cache(source) + self.top_of_stack = source + + return + + if not isinstance(value, VariableTracker): + raise AssertionError(f"expected VariableTracker, got {type(value)}") + output = self._output + graph_outputs = self.graph_outputs + + if allow_cache: + if self.top_of_stack is value: + output.append(create_dup_top()) + return + + if self.tempvars.get(value) is not None: + output.append(self.create_load(self.tempvars[value])) + self.top_of_stack = value + return + + if value.is_realized() and isinstance( + value, ContextlibContextManagerLocalGeneratorObjectVariable + ): + unimplemented( + gb_type="reconstructing @contextmanager object", + context=f"object: {value}", + explanation="Returning a @contextmanager object from a compiled function is not supported.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + # Dynamo normally prefers codegen from source to account for aliasing. + if ( + value.source is not None + and allow_cache + and not ( + value.is_realized() and isinstance(value, LocalGeneratorObjectVariable) + ) + ): + # There's a corner case for export: for instance, if the computation + # graph is just identity on an input tensor, Dynamo would just emit + # a `LOAD_FAST` from the input source, rather than generating an + # identity FX graph. + # + # However, export wants to maximize graph capture; in the case + # above, export _wants to_ obtain an identity FX graph (despite it + # appears unnecessarily expensive for `torch.compile`), so we have + # the following option to override Dynamo's preference for codegen + # from source. Moreover, this option applies recursively, for cases + # like input tensor being returned in a new dictionary. + # + # And why the `ValueMutationExisting` check? Not sure, so leaving it + # to keep the old behavior, as when `value_from_source` was + # introduced. TODO sort out the invariants among side effect, + # codegen and export. + if ( + isinstance(value.mutation_type, ValueMutationExisting) + or self.value_from_source + ): + return self(value.source) + + if isinstance(value, ComputedLazyConstantVariable) and not value.is_realized(): + # Recompute from the operands at runtime instead of burning in the value + self.uses[value] += 1 + self.call_reconstruct(value) + if allow_cache and value in self.tempvars: + self._output.append(create_dup_top()) + self.add_cache(value) + elif value.is_python_constant() and is_safe_constant( + value.as_python_constant() + ): + output.append(self.create_load_const(value.as_python_constant())) + elif isinstance(value, TensorWithTFOverrideVariable): + graph_outputs_key = self.add_graph_output(value) + + self.add_push_null( + lambda: self.load_import_from(utils.__name__, "to_subclass") + ) + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.append( + self.create_load_global( + value.global_mangled_class_name(self.tx), # type: ignore[arg-type] + add=True, + ) + ) + output.extend(create_call_function(2, False)) + elif ( + isinstance(value, SymNodeVariable) + and value.python_type() is float + and not self.tx.export + ): + # This is a little unusual; force the output convention to be a + # Tensor here. Don't do this for export because this is + # apparently load bearing for export tests (but I am a bit + # doubtful it actually works in the real world) + # NB: It works to add_graph_output on a computed expression + # as_tensor here, because we memoize as_tensor calls on + # SymNodeVariable! + graph_outputs_key = self.add_graph_output( + value.as_tensor(self.tx, torch.float64) + ) + + def gen_fn() -> None: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.append(self.create_load_attr("item")) + + self.add_push_null(gen_fn) + output.extend(create_call_function(0, False)) + elif isinstance( + value, + ( + TensorVariable, + SymNodeVariable, + UnspecializedPythonVariable, + NumpyNdarrayVariable, + CustomClassObjectVariable, + ), + ): + graph_outputs_key = self.add_graph_output(value) + + if isinstance(value, NumpyNdarrayVariable): + self.add_push_null( + lambda: self.load_import_from(utils.__name__, "to_numpy_helper") + ) + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.extend(create_call_function(1, False)) + elif isinstance(value, UnspecializedPythonVariable) and value.need_unwrap: + + def gen_fn() -> None: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.append(self.create_load_attr("item")) + + self.add_push_null(gen_fn) + output.extend(create_call_function(0, False)) + elif isinstance(value, CustomClassObjectVariable): + try: + py_value = value.as_python_constant() + except NotImplementedError: + py_value = None + + if is_opaque_constant_type(type(py_value)): + self.add_push_null( + lambda: self.load_import_from( + "torch._library.fake_class_registry", + "maybe_unwrap_fake_script_object", + ) + ) + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.extend(create_call_function(1, False)) + else: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + else: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + elif isinstance(value, NNModuleVariable): + parts = value.module_key.split(".") + if parts[0] in self.code_options["co_varnames"]: + output.append(self.create_load(parts[0])) + parts = parts[1:] + else: + if self.root is None: + raise AssertionError("self.root must not be None") + output.append(self.create_load_const_unchecked(self.root)) + for part in parts: + output.append(self.create_load_attr(part)) + else: + self.uses[value] += 1 + try: + self.call_reconstruct(value) + except NotImplementedError as e: + unimplemented( + gb_type="Reconstruction failure", + context=str(value), + explanation=f"Dynamo has no bytecode reconstruction implemented for sourceless variable {value}.", + hints=[ + "If Dynamo is attempting to trace a return statement and your code is attempting to return a variable " + "that Dynamo cannot reconstruct, then remove it from the return statement.", + *graph_break_hints.CAUSED_BY_EARLIER_GRAPH_BREAK, + "Report an issue to PyTorch if you need reconstrtuction support. Note that objects that don't have " + "reconstruction rules may be fundamentally unreconstructable.", + ], + from_exc=e, + ) + if allow_cache and value in self.tempvars: + self._output.append(create_dup_top()) + self.add_cache(value) + + self.top_of_stack = value + + def add_graph_output(self, value: VariableTracker) -> int: + graph_outputs_key = id(value.as_proxy()) + if graph_outputs_key not in self.graph_outputs: + self.graph_outputs[graph_outputs_key] = GraphOutputEntry( + len(self.graph_outputs), value + ) + return graph_outputs_key + + def load_graph_output(self, index: int) -> None: + output = self._output + if self.graph_output_var is None: + raise AssertionError("graph_output_var must not be None") + output.append(self.create_load(self.graph_output_var)) + output.append(self.create_load_const(index)) + output.append(self.create_binary_subscr()) + + def add_cache(self, value: VariableTracker | Source) -> None: + var = self.new_var() + self.tempvars[value] = var + self._output.append(self.create_store(var)) + + def foreach(self, items: Iterable[VariableTracker | Source]) -> None: + for i in items: + self(i) + + def create_binary_subscr(self) -> Instruction: + return create_binary_subscr() + + def setup_globally_cached(self, name: str, value: Any) -> list[Instruction]: + """Store value in a new global""" + name = re.sub(r"[^a-zA-Z0-9_]+", "_", name) + f_globals = self.tx.f_globals + if name in f_globals: + if id(f_globals[name]) != id(value): + raise AssertionError( + f"f_globals[{name!r}] already exists with a different identity" + ) + else: + f_globals[name] = value + return [self.create_load_global(name, add=True)] + + def clear_tos(self) -> None: + self.top_of_stack = None + + def append_output(self, inst: Instruction) -> None: + if not isinstance(inst, Instruction): + raise AssertionError(f"expected Instruction, got {type(inst)}") + self._output.append(inst) + self.clear_tos() + + def extend_output(self, insts: list[Instruction]) -> None: + if not all(isinstance(x, Instruction) for x in insts): + raise AssertionError("all elements of insts must be Instruction instances") + self._output.extend(insts) + self.clear_tos() + + def get_instructions(self) -> list[Instruction]: + return self._output + + def get_pycode(self) -> list[str] | None: + if not config.generate_pycode: + return None + return self.pycodes + + def create_load(self, name: str) -> Instruction: + if name not in self.code_options["co_varnames"]: + raise AssertionError(f"{name} missing") + return create_instruction("LOAD_FAST", argval=name) + + def create_load_closure(self, name: str) -> Instruction: + if name not in self.cell_and_freevars(): + raise AssertionError(f"{name!r} not in cell_and_freevars") + inst_name = "LOAD_FAST" if sys.version_info >= (3, 13) else "LOAD_CLOSURE" + return create_instruction(inst_name, argval=name) + + def create_load_deref(self, name: str) -> Instruction: + if name not in self.cell_and_freevars(): + raise AssertionError(f"{name!r} not in cell_and_freevars") + return create_instruction("LOAD_DEREF", argval=name) + + def create_store(self, name: str) -> Instruction: + if name not in self.code_options["co_varnames"]: + raise AssertionError(f"{name} missing") + return create_instruction("STORE_FAST", argval=name) + + def create_store_deref(self, name: str) -> Instruction: + if name not in self.cell_and_freevars(): + raise AssertionError(f"{name!r} not in cell_and_freevars") + return create_instruction("STORE_DEREF", argval=name) + + def create_load_global(self, name: str, add: bool = False) -> Instruction: + if add: + self.tx.output.update_co_names(name) + if name not in self.code_options["co_names"]: + raise AssertionError(f"{name} not in co_names") + return create_instruction("LOAD_GLOBAL", argval=name) + + def create_load_const(self, value: Any) -> Instruction: + return create_load_const(value) + + def create_load_const_unchecked(self, value: Any) -> Instruction: + return create_load_const(value, checked=False) + + def load_method(self, name: str) -> None: + self.tx.output.update_co_names(name) + self.append_output(create_load_method(name)) + + def call_method(self, nargs: int) -> None: + self.extend_output(create_call_method(nargs)) + + def create_list_append(self) -> list[Instruction]: + # Append TOS to the list at TOS-1, leaving the list on the stack + # (same stack effect as LIST_APPEND with arg=1). + # + # The bare LIST_APPEND opcode does not lock the list and so requires + # the target be uniquely owned (refcnt == 1) on free-threaded builds. + # Dynamo can't enforce this, so instead use LIST_EXTEND, which does + # lock + return [ + create_instruction("BUILD_LIST", arg=1), + create_instruction("LIST_EXTEND", arg=1), + ] + + def create_load_attr(self, name: str) -> Instruction: + if name not in self.code_options["co_names"]: + self.code_options["co_names"] += (name,) + return create_instruction("LOAD_ATTR", argval=name) + + def load_attr(self, name: str) -> None: + self.append_output(self.create_load_attr(name)) + + def create_load_attrs(self, names: str) -> list[Instruction]: + return [self.create_load_attr(name) for name in names.split(".")] + + def create_store_attr(self, name: str) -> Instruction: + if name not in self.code_options["co_names"]: + self.code_options["co_names"] += (name,) + return create_instruction("STORE_ATTR", argval=name) + + def store_attr(self, name: str) -> None: + self.append_output(self.create_store_attr(name)) + + def load_function_name( + self, fn_name: str, push_null: bool, num_on_stack: int = 0 + ) -> list[Instruction]: + """Load the global fn_name on the stack num_on_stack down""" + output = [] + if push_null and sys.version_info >= (3, 11): + output.extend(add_push_null(self.create_load_global(fn_name, add=True))) + if num_on_stack > 0: + output.extend( + [ + *self.rot_n(num_on_stack + 2), + *self.rot_n(num_on_stack + 2), + ] + ) + else: + output.extend( + [ + self.create_load_global(fn_name, add=True), + *self.rot_n(num_on_stack + 1), + ] + ) + return output + + def rot_n(self, n: int) -> list[Instruction]: + try: + return create_rot_n(n) + except AttributeError: + # desired rotate bytecode doesn't exist, generate equivalent bytecode + return [ + create_build_tuple(n), + self.create_load_const_unchecked(rot_n_helper(n)), + *create_rot_n(2), + *create_call_function_ex(False, False), + create_instruction("UNPACK_SEQUENCE", arg=n), + ] + + def pop_null(self) -> list[Instruction]: + # POP_TOP doesn't work for null, so we pop nulls by pushing in a + # nop function, calling it (which consumes the null), and popping the result. + if sys.version_info < (3, 11): + raise AssertionError("pop_null requires Python 3.11+") + return [ + self.create_load_const_unchecked(lambda: None), + # 3.13 swapped NULL and callable + *( + (create_instruction("SWAP", arg=2),) + if sys.version_info >= (3, 13) + else () + ), + *create_call_function(0, False), + create_instruction("POP_TOP"), + ] + + def pop_top(self) -> None: + self.append_output(create_instruction("POP_TOP")) + + def call_function(self, nargs: int, push_null: bool) -> None: + self.extend_output(create_call_function(nargs, push_null=push_null)) + + def dup_top(self) -> None: + self.append_output(create_dup_top()) + + def store(self, varname: str) -> None: + self.append_output(self.create_store(varname)) + + def load_deref(self, varname: str) -> None: + self.append_output(self.create_load_deref(varname)) + + def make_function_with_closure( + self, + fn_name: str, + code: types.CodeType, + ) -> None: + """Creates a closure with code object `code`. + + Expects the TOS to be the tuple of cells to use for this closure. + TOS will be popped to create the closure. + Args: + - fn_name: name of the function + - code: code object of the function + (does not include the tuple of cells on the TOS) + """ + output = self._output + + output.append(self.create_load_const(code)) + if sys.version_info < (3, 11): + output.append(self.create_load_const(fn_name)) + if sys.version_info >= (3, 13): + output.extend( + [ + create_instruction("MAKE_FUNCTION"), + create_instruction("SET_FUNCTION_ATTRIBUTE", arg=0x08), + ] + ) + else: + output.append(create_instruction("MAKE_FUNCTION", arg=0x08)) + + self.clear_tos() + + def create_load_python_module(self, mod: types.ModuleType) -> Instruction: + """ + Generate a LOAD_GLOBAL instruction to fetch a given python module. + """ + output = self.tx.output + global_scope = output.global_scope + name = re.sub(r"^.*[.]", "", mod.__name__) + if global_scope.get(name, None) is mod: + return self.create_load_global(name, add=True) + prefix = f"___module_{name}" + global_name = self.tx.output.install_global_by_id(prefix, mod) + return self.create_load_global(global_name, add=True) + + def mark_source_temp(self, source: Source) -> None: + """ + Mark a source as a temp variable, so that it can be reused. + """ + if source not in self.tempvars: + self.tempvars[source] = None + + def make_call_generated_code(self, fn_name: str) -> None: + """Call the generated code function stored in fn_name""" + self.extend_output(self.load_function_name(fn_name, True)) + + graphargs = self.tx.output.graphargs + + def extract_nested_sources(source: Source) -> list[Source]: + nested_sources: list[Source] = [] + if isinstance(source, ChainedSource): + nested_sources.append(source.base) + if isinstance(source, DictGetItemSource) and isinstance( + source.index, Source + ): + nested_sources.append(source.index) + return nested_sources + + def collect_temp_sources(sources: deque[Source], codegen: PyCodegen) -> None: + seen_sources: OrderedSet[Source] = OrderedSet() + while sources: + current_source = sources.popleft() + if current_source in seen_sources: + # This source is used at least twice, so it can be reused + codegen.mark_source_temp(current_source) + # Don't trace source further. This prevents us from marking too + # many nodes as temp sources. + continue + seen_sources.add(current_source) + sources.extend(extract_nested_sources(current_source)) + + # Collect all the sources that are used more than once, so that we can + # generate tmp variables in the generated pre-graph bytecode. This + # essentially implements CSE. + collect_temp_sources( + deque([arg.source for arg in graphargs if arg.source is not None]), self + ) + + cm_var = None + if config.record_runtime_overhead: + # Record the pregraph bytecode start + self.add_push_null( + lambda: self.load_import_from( + utils.__name__, "record_pregraph_bytecode_enter" + ) + ) + self.extend_output(create_call_function(0, False)) + cm_var = self.new_var() + self.store(cm_var) + + arg_varnames = [] + for i, arg in enumerate(graphargs): + arg_varname = self.tx.new_pycode_varname("arg") + arg_varnames.append(arg_varname) + if arg.pass_arg_as_tensor: + self.add_push_null( + lambda: self.extend_output( + [ + self.create_load_python_module(torch), + self.create_load_attr("_as_tensor_fullprec"), + ] + ) + ) + self.call_reconstruct(arg) + self.extend_output(create_call_function(1, False)) + self.add_pycode(f"{arg_varname} = torch._as_tensor_fullprec({{}})", arg) + else: + self.call_reconstruct(arg) + self.add_pycode(f"{arg_varname} = {{}}", arg) + + if config.record_runtime_overhead: + # Record the pregraph bytecode end + self.add_push_null( + lambda: self.load_import_from( + utils.__name__, "record_pregraph_bytecode_exit" + ) + ) + if cm_var is None: + raise AssertionError("cm_var must not be None") + self.extend_output([self.create_load(cm_var)]) + self.extend_output(create_call_function(1, False)) + self.pop_top() + + self.extend_output(create_call_function(len(graphargs), False)) + self.add_pycode( + f"__graph_out = {fn_name}({', '.join(arg_varnames)})", + ) + + def create_import_name(self, module_name: str) -> Instruction: + return create_instruction("IMPORT_NAME", argval=module_name) + + def load_import_from(self, module_name: str, object_name: str) -> None: + source = AttrSource(self.tx.import_source(module_name), object_name) + # Note: This approach is somewhat aggressive because typically, a source is marked + # as a tempvar only when it is used more than once. In this case, we're marking it + # as a tempvar without performing that analysis. However, this is a simple solution, + # and in many cases, load imports are reused multiple times. + self.mark_source_temp(source) + self(source) + + def create_call_function_kw( + self, nargs: int, kw_names: Iterable[str], push_null: bool + ) -> list[Instruction]: + if sys.version_info >= (3, 13): + output = create_call_function(nargs, push_null) + if output[-1].opname != "CALL": + raise AssertionError( + f"expected last instruction to be CALL, got {output[-1].opname}" + ) + output.insert(-1, self.create_load_const(kw_names)) + output[-1] = create_instruction("CALL_KW", arg=nargs) + return output + elif sys.version_info >= (3, 11): + output = create_call_function(nargs, push_null) + if sys.version_info >= (3, 12): + idx = -1 + expected_inst = "CALL" + else: + idx = -2 + expected_inst = "PRECALL" + if output[idx].opname != expected_inst: + raise AssertionError( + f"expected instruction at index {idx} to be {expected_inst}, " + f"got {output[idx].opname}" + ) + kw_names_inst = create_instruction("KW_NAMES", argval=kw_names) + output.insert(idx, kw_names_inst) + return output + return [ + self.create_load_const(kw_names), + create_instruction("CALL_FUNCTION_KW", arg=nargs), + ] + + def create_delete(self, value: object) -> Instruction: + return create_instruction("DELETE_FAST", argval=value) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/compiled_autograd.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/compiled_autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..9edb103a6a51dfd6a1444b2af560107d8decb051 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/compiled_autograd.py @@ -0,0 +1,1794 @@ +""" +Provides functionality for compiling PyTorch's autograd (automatic differentiation) system. + +This module implements compiled autograd, which traces and optimizes backward pass +computations at runtime. The key components are: + +- AutogradCompilerInstance: Traces and compiles autograd graphs using FX +- Context managers (_enable/_disable): Control when compiled autograd is active +- Utility functions: Support graph manipulation, tensor operations, and hooks + +Compiled autograd can significantly improve backward pass performance by removing +Python overhead and enabling additional optimizations. It works by capturing +backward computations into an FX graph that can be compiled and optimized, +while maintaining the same semantics as eager mode autograd. +""" + +import contextlib +import functools +import itertools +import operator +import time +from collections import Counter, defaultdict +from collections.abc import Callable, Generator, Sequence +from typing import Any, cast, Literal, Protocol, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.external_utils import ( + call_accumulate_grad, + call_backward, + call_hook, + FakeCompiledAutogradEngine, + unwrap_maybe_dynamic_int, +) +from torch._dynamo.source import GetItemSource, LocalSource +from torch._dynamo.utils import ( + counters, + get_chromium_event_logger, + lazy_format_graph_code, + set_locals_to_steal, +) +from torch._functorch._aot_autograd.runtime_wrappers import ( + AutogradLazyBackwardCompileInfo, + CachedAutogradLazyBackwardCompileInfo, +) +from torch._guards import compile_context, CompileContext, CompileId, Source +from torch._logging import getArtifactLogger, trace_structured +from torch._prims_common import clone_preserve_strides +from torch._subclasses import FakeTensorMode +from torch._subclasses.fake_tensor import FakeTensor +from torch.fx import GraphModule +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import ( + disable_autocast_cache, + disable_proxy_modes_tracing, + fetch_object_proxy, + ProxyTorchDispatchMode, + PythonKeyTracer, + track_tensor_tree, +) +from torch.fx.experimental.symbolic_shapes import DimDynamic, ShapeEnv +from torch.fx.traceback import preserve_node_meta, set_stack_trace +from torch.types import FloatLikeType, IntLikeType +from torch.utils._ordered_set import OrderedSet +from torch.utils._traceback import CapturedTraceback + + +if TYPE_CHECKING: + from torch._functorch._aot_autograd.schemas import SubclassMeta, ViewAndMutationMeta + from torch.fx.proxy import Proxy + + +TURN_OFF_MSG = """You can turn off compiled autograd by either: +1. Moving the unsupported autograd call outside of the torch.compile'd region. +2. Wrapping the unsupported autograd call in the torch._dynamo.compiled_autograd._disable() context manager. +3. Setting torch._dynamo.config.compiled_autograd=False for the torch.compile call containing the unsupported autograd call. +4. Setting torch._dynamo.config.compiled_autograd=False at the start of the program.""" + +compiled_autograd_log = getArtifactLogger(__name__, "compiled_autograd") +verbose_log = getArtifactLogger(__name__, "compiled_autograd_verbose") + +# The kind of autograd hook being proxied. Threaded through proxy_call_hook into +# the fx node's kwargs, where the graph post-processing passes read it back to +# match nodes (e.g. node.kwargs["hook_type"] == "post_hook"). +HookType = Literal[ + "unpack_hook", + "tensor_pre_hook", + "pre_hook", + "post_hook", + "post_acc_grad_hook", +] + + +def snapshot_verbose_logging_enabled() -> bool: + return torch._logging._internal.log_state.is_artifact_enabled( + "compiled_autograd_verbose" + ) + + +def snapshot_cudagraph_enabled() -> bool: + return torch._inductor.config.triton.cudagraphs + + +def maybe_clone(x: torch.Tensor | None) -> torch.Tensor | None: + if x is not None: + return clone_preserve_strides(x) + return x + + +class _AOTCompiledFunction(Protocol): + """Structural type for the AOTAutograd autograd.Function subclass that + compiled autograd retraces. The concrete class is generated locally inside + AOTAutograd, so we describe only the private attributes consumed here. + """ + + _lazy_backward_info: ( + AutogradLazyBackwardCompileInfo | CachedAutogradLazyBackwardCompileInfo | None + ) + metadata: "ViewAndMutationMeta" + maybe_subclass_metadata: "SubclassMeta | None" + _aot_id: int + _bw_prologue_fn: Callable[..., Any] + _bw_epilogue_fn: Callable[..., Any] + + +def extract_bw_module(CompiledFunction: _AOTCompiledFunction) -> GraphModule: + if isinstance( + CompiledFunction._lazy_backward_info, AutogradLazyBackwardCompileInfo + ): + return cast(GraphModule, CompiledFunction._lazy_backward_info.bw_module) + elif isinstance( + CompiledFunction._lazy_backward_info, CachedAutogradLazyBackwardCompileInfo + ): + with torch._subclasses.fake_tensor.unset_fake_temporarily(): + return CompiledFunction._lazy_backward_info.bw_module_fn() + else: + raise AssertionError( + "Unexpected Lazy Backward Compilation Info Type. Please file an issue." + ) + + +# Note: [Anomaly Mode Semantics in Compiled Autograd] +# In the eager autograd engine, anomaly mode is able to detect NaNs +# after each node. This is useful, because the executed code with +# and without anomaly mode are the same. So assuming determinism, +# a NaN in regular mode should also happen in anomaly mode. +# +# With torch.compile, following eager semantics would require inserting +# runtime asserts to check for NaNs, which could prevent some fusions. +# This results in different code being run with and without anomaly mode. +# So different semantics are needed, this implementation below will check +# for NaNs at the end of the autograd call, instead of after each node +class NaNChecker: + def __init__(self, accumulate_grad: bool) -> None: + self.accumulate_grad = accumulate_grad + self.params_indices: list[int] = [] + self.params_to_check: dict[str, torch.Tensor] = {} + self.output_names: list[str] = [] + + def prep_with_graph(self, graph: torch.fx.Graph) -> None: + inputs_node = next(iter(graph.nodes)) + acc_grad_nodes = graph.find_nodes( + op="call_function", target=call_accumulate_grad + ) + output_nodes = graph.find_nodes(op="output")[0].args[0] + if self.accumulate_grad != bool(acc_grad_nodes): + raise AssertionError( + f"accumulate_grad mismatch: expected {self.accumulate_grad}, " + f"got {bool(acc_grad_nodes)} acc_grad_nodes" + ) + if self.accumulate_grad != (not output_nodes): + raise AssertionError( + f"accumulate_grad mismatch with output_nodes: expected {self.accumulate_grad}, " + f"got {not output_nodes}" + ) + + for node in acc_grad_nodes: + param_node = node.args[0] + # AccumulateGrad always saves a reference to the param + # so Compiled Autograd will always lift the param and + # this should always be true + if param_node.target is not operator.getitem: + raise AssertionError( + f"Expected param_node target to be operator.getitem, got {param_node.target}" + ) + if param_node.args[0] is not inputs_node: # type: ignore[possibly-undefined] + raise AssertionError("Expected param_node.args[0] to be inputs_node") + if not isinstance(param_node.args[1], int): + raise AssertionError( + f"Expected param_node.args[1] to be int, got {type(param_node.args[1])}" + ) + self.params_indices.append(param_node.args[1]) + + self.output_names = [node.name for node in output_nodes] + + def prep_with_inputs(self, inputs: tuple[torch.Tensor, ...]) -> None: + if not self.accumulate_grad: + # Using .grad, nothing to prep + return + + # Using .backward, we must check existing grads on params if any + for idx in self.params_indices: + grad = inputs[idx].grad + if grad is not None: + if torch.isnan(grad).any(): + raise AssertionError( + f"Compiled autograd running under anomaly mode with inputs[{idx}] already " + f"having NaN gradient. This is not supported. {TURN_OFF_MSG}" + ) + + self.params_to_check[f"inputs[{idx}]"] = inputs[idx] + + def check(self, out: tuple[torch.Tensor, ...]) -> None: + if self.accumulate_grad: + # Using .backward, graph outputs are empty + if out: + raise AssertionError( + "Expected empty output for accumulate_grad backward" + ) + nan_params: list[str] = [] + for inputs_str, param in self.params_to_check.items(): + if param.grad is None: # not true for autograd.grad + raise AssertionError( + "Expected param.grad to be non-None for backward mode" + ) + if torch.isnan(param.grad).any(): + nan_params.append(inputs_str) + + if nan_params: + raise RuntimeError( + f"Compiled Autograd returned NaN gradients for parameters: {','.join(nan_params)}." + ) + else: + # Using .grad, graph outputs are grads + nan_grads: list[str] = [] + for i, grad in enumerate(out): + if torch.isnan(grad).any(): + nan_grads.append(self.output_names[i]) + + if nan_grads: + raise RuntimeError( + f"Compiled Autograd returned NaN gradients for output nodes: {','.join(nan_grads)}." + ) + + +# We lazily bind "functional backward" variants for PyTorch built-in autograd +# nodes to this class. Example: torch._dynamo.compiled_autograd.ops.MulBackward0 +# Each "functional backward" is bound the first time the node's apply_with_saved +# function is called. It's possible to avoid lazy binding and instead bind +# all of this upfront (perhaps at import time) via codegen changes. +class OpNamespace: + def __init__(self) -> None: + self.custom_function_name_counter: Counter[str] = Counter() + + def add( + self, + name: str, + fn: Callable[..., Any], + is_custom_function: bool, + is_traceable: bool, + ) -> str: + if is_custom_function: + name = "CppNode" + name + count = self.custom_function_name_counter[name] + self.custom_function_name_counter[name] += 1 + name = f"{name}{count}" + + if hasattr(self, name): + raise AssertionError(f"Op with name '{name}' already exists") + result = Op(name, fn, is_custom_function) + if is_traceable: + # pyrefly: ignore [deprecated] + setattr(self, name, torch._dynamo.allow_in_graph(result)) + else: + # C++ autograd function was not marked as traceable + # Dynamo can't dry run it at compile time, so must fallback to eager + @torch._dynamo.disable # type: ignore[misc] + def run_non_traceable_cpp_in_eager(*args: Any, **kwargs: Any) -> Any: + return result(*args, **kwargs) + + setattr(self, name, run_non_traceable_cpp_in_eager) + return name + + def get(self, name: str) -> Any: + return getattr(self, name) + + +class Op: + def __init__( + self, name: str, fn: Callable[..., Any], is_custom_function: bool + ) -> None: + self.fn = fn + self.is_custom_function = is_custom_function + self.__name__ = name + self.__module__ = "torch._dynamo.compiled_autograd.ops" + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self.fn(*args, **kwargs) + + def __repr__(self) -> str: + return self.__module__ + "." + self.__name__ + + +ops = OpNamespace() + + +_graph_placeholders = ["inputs", "sizes", "scalars", "hooks", "packed_data"] +_impure_targets = OrderedSet( + [ + call_hook, + call_backward, + FakeCompiledAutogradEngine._exec_final_callbacks_stub, + call_accumulate_grad, + ] +) + +COMPILE_COUNTER = itertools.count() + + +def make_compile_context(compiled_autograd_id: int) -> Any: + return compile_context( + CompileContext( + CompileId( + compiled_autograd_id=compiled_autograd_id, + frame_id=None, + frame_compile_id=None, + ) + ) + ) + + +class AutogradCompilerInstance: + def __init__(self, compiler_fn: Callable[..., Any]) -> None: + self.compiler_fn = compiler_fn + self.stack = contextlib.ExitStack() + self.close = self.stack.close + self.shape_env = ShapeEnv() + self.fake_tensor_mode = FakeTensorMode( + allow_fallback_kernels=True, + allow_non_fake_inputs=True, + shape_env=self.shape_env, + ) + self.fx_tracer = PythonKeyTracer() + self.proxy_mode = ProxyTorchDispatchMode(self.fx_tracer, "symbolic") + self.hooks_proxy: Proxy | None = None + + def wrap_fake(self, x: torch.Tensor, source: Source | None) -> FakeTensor: + if not isinstance(x, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(x)}") + return self.fake_tensor_mode.from_tensor(x, source=source) + + @staticmethod + def source(name: str, idx: Any) -> GetItemSource: + return GetItemSource(LocalSource(name), idx) + + def begin_capture( + self, + inputs: list[torch.Tensor], + sizes: list[int], + scalars: list[IntLikeType | FloatLikeType], + origins: list[list[tuple[int, str]]], + accumulate_grad: bool, + check_nans: bool, + ) -> tuple[str, list[torch.Tensor], list[IntLikeType], list[FloatLikeType]]: + counters["compiled_autograd"]["captures"] += 1 + self.id = next(COMPILE_COUNTER) + self.aot_id_counter: dict[int, int] = defaultdict(int) + self.compile_context = make_compile_context(self.id) + self.compile_context.__enter__() + self.nan_checker = NaNChecker(accumulate_grad) if check_nans else None + self.start_time_ns = time.time_ns() + get_chromium_event_logger().log_event_start( + "compiled_autograd", + self.start_time_ns, + {"graph_id": self.id}, + log_pt2_compile_event=True, + ) + self.fx_tracer.root = torch.nn.Module() + self.fx_tracer.graph = torch.fx.Graph(tracer_cls=PythonKeyTracer) + self.fx_tracer.tensor_attrs = {} + self.symnode_proxy_lookup = {} + ( + args_proxy, + self.sizes_proxy, + self.scalars_proxy, + self.hooks_proxy, + self.packed_data_proxy, + ) = ( + self.fx_tracer.create_proxy("placeholder", name, (), {}) + for name in _graph_placeholders + ) + + self.stack.enter_context(preserve_node_meta()) + inputs_origins, sizes_origins, scalars_origins = origins + + # Turn on PythonDispatcher during initial trace to make it identifiable + # that tracing is happening, which is needed to prevent hashing symints + self.stack.enter_context(enable_python_dispatcher()) + + # tensor inputs to fake tensors + x = inputs[0] # mypy will complain about unbound x + try: + for idx, x in enumerate(inputs): + inputs[idx] = self.wrap_fake(x, self.source("inputs", idx)) + except Exception as e: + raise NotImplementedError( + f"Found tensor of type {type(x)}, which is not supported by FakeTensorMode. {TURN_OFF_MSG}" + ) from e + self.bind_objects_to_proxies(inputs, args_proxy, inputs_origins) + + # size inputs to symints + sym_sizes = [ + self.shape_env.create_unspecified_symint_and_symbol( + val, + self.source("sizes", idx), + DimDynamic.DYNAMIC, + ) + for idx, val in enumerate(sizes) + ] + + # We want to mark every size as dynamic, but since there's no way to + # mark a primitive `int` as dynamic, we need to wrap it in a tensor. + # In the graph, we unwrap it with `unwrap_maybe_dynamic_int` back into a primitive. + proxies = [self.sizes_proxy[i] for i in range(len(sym_sizes))] # type: ignore[index] + for i, symint in enumerate(sym_sizes): + proxies[i] = self.fx_tracer.create_proxy( + "call_function", + unwrap_maybe_dynamic_int, + (proxies[i],), + {}, + ) + if not isinstance(symint, int): + self.symnode_proxy_lookup[symint.node] = proxies[i] + proxies = self.bind_objects_to_proxies(sym_sizes, proxies, sizes_origins) + + for idx, val in enumerate(scalars): + source = self.source("scalars", idx) + if isinstance(val, int): + scalars[idx] = self.shape_env.create_unspecified_symint_and_symbol( + val, + source, + DimDynamic.DYNAMIC, + ) + elif isinstance(val, float): + scalars[idx] = self.shape_env.create_symfloatnode( + self.shape_env.create_unspecified_symbol( + val, + source=source, + dynamic_dim=DimDynamic.DYNAMIC, + ), + hint=val, + source=source, + ) + else: + raise AssertionError("Unexpected scalar type: ", type(val)) + self.bind_objects_to_proxies(scalars, self.scalars_proxy, scalars_origins) + for i, symval in enumerate(scalars): + self.symnode_proxy_lookup[symval.node] = self.scalars_proxy[i] # type: ignore[union-attr] + + # TODO(jansel): are all these modes needed? + self.stack.enter_context(self.fake_tensor_mode) + self.stack.enter_context(self.proxy_mode) + self.stack.enter_context(disable_autocast_cache()) + # Needed to make sure we don't accidentally specialize any symbols + if self.fake_tensor_mode.shape_env is None: + raise AssertionError("fake_tensor_mode.shape_env must not be None") + env = self.fake_tensor_mode.shape_env + self.stack.enter_context( + torch.fx.experimental.symbolic_shapes._suppress_guards(env) + ) + # pyrefly: ignore [bad-return] + return ( + str(CompileContext.current_compile_id()), + inputs, + sym_sizes, + scalars, # type: ignore[return-value] + ) + + def log_compile_reasons( + self, + compile_reasons: list[str], + ) -> None: + if not compile_reasons: + raise AssertionError("compile_reasons must not be empty") + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "compiled_autograd_compile_reasons", + "encoding": "json", + }, + payload_fn=lambda: compile_reasons, + ) + + def proxy_call_aot_backward( + self, + pinputs: Sequence[Any], + psaved_tensors: Sequence[torch.Tensor], + saved_tensors: Sequence[torch.Tensor], + pctx: "Proxy", + ctx: torch.autograd.function.BackwardCFunction, + maybe_backward_state_idx: int | None, + opaque_object_indices: list[int], + ) -> Sequence[Any]: + # The AOTBackward call consists of three things: the prologue, the + # backward graph, and the epilogue. + # Our strategy is: + # - allow_in_graph the prologue (in the CA graph and Dynamo graph), + # - copy-paste the backward graph into the CA graph so that CA passes and Dynamo can see it + # - trace directly through the epilogue. Anything that gets baked in is + # constant metadata (for example, metadata about the number of outputs, or removing + # RNG arguments or effect tokens). + # If Dynamo graph capture were better, then we could add a node for the prologue + # into the CA graph and have Dynamo trace into it. + + psymints = [ + self.to_proxy(e) + for e in ctx._get_compiled_autograd_symints() # type: ignore[attr-defined] + ] + + popaque_objects = [ + self.hooks_proxy[idx] # type: ignore[index] + for idx in opaque_object_indices + ] + + # NOTE: we should only close over constants + CompiledFunction: _AOTCompiledFunction = ctx._forward_cls # type: ignore[attr-defined] + bw_module = extract_bw_module(CompiledFunction) + metadata = CompiledFunction.metadata + maybe_subclass_metadata = CompiledFunction.maybe_subclass_metadata + aot_id = CompiledFunction._aot_id + bw_prologue_fn = CompiledFunction._bw_prologue_fn + bw_epilogue_fn = CompiledFunction._bw_epilogue_fn + del CompiledFunction + + if torch.is_grad_enabled(): + for output_alias_info in metadata.output_info: + if output_alias_info.requires_grad: + raise RuntimeError( + "torch.compile does not currently support higher order gradients." + ) + + @torch._dynamo.allow_in_graph # type: ignore[misc] + def call_aot_bwd_prologue( + ctx_saved_tensors: Sequence[torch.Tensor], + ctx_symints: Sequence[IntLikeType], + ctx_opaque_objs: Sequence[Any], + flat_args: Sequence[Any], + ) -> Any: + return bw_prologue_fn( + ctx_saved_tensors, + ctx_symints, + ctx_opaque_objs, + flat_args, + ) + + pgrads = self.fx_tracer.create_proxy( + kind="call_function", + # pyrefly: ignore [bad-argument-type] + target=call_aot_bwd_prologue, + args=( + psaved_tensors, + psymints, + popaque_objects, + pinputs, + ), + kwargs={}, + ) + + pbackward_state = None + if maybe_backward_state_idx is not None: + pbackward_state = self.hooks_proxy[maybe_backward_state_idx] # type: ignore[index] + + # Copy-paste the AOT backward graph into the compiled autograd graph + def copy_paste_aot_backward_graph() -> list[torch.Tensor]: + def num_inputs(graph: torch.fx.Graph) -> int: + num_args = 0 + for node in graph.nodes: + if node.op == "placeholder": + num_args += 1 + continue + else: + break + return num_args + + # set up the proxy inputs to bw_module + # the calling convention is: [*symints, *args (primals and tangents), backward_state] + num_args = num_inputs(bw_module.graph) + pall_args = [ + pgrads[i] for i in range(num_args - int(pbackward_state is not None)) + ] + # replace the symints with our symints + symints = ctx._get_compiled_autograd_symints() # type: ignore[attr-defined] + if len(symints) != len(ctx.symints): # type: ignore[attr-defined] + raise AssertionError( + f"symints length mismatch: {len(symints)} vs {len(ctx.symints)}" # type: ignore[attr-defined] + ) + psymints = [self.to_proxy(e) for e in symints] + pall_args[: len(symints)] = psymints + # Add backward_state + if pbackward_state is not None: + pall_args.append(pbackward_state) + + # run over all nodes of the aot_backward graph. + # copy and paste them all into the compiled autograd graph. + args_idx = 0 + # pyrefly: ignore [implicit-any] + value_remap = {} + poutputs: list[torch.fx.Proxy] | None = None + + # names of nodes must appear only once in the fx.Graph + # dedup AOT backwards that appear multiple times + deduped_aot_id = str(aot_id) + if self.aot_id_counter[aot_id]: + deduped_aot_id += f"_{self.aot_id_counter[aot_id]}" + self.aot_id_counter[aot_id] += 1 + + def make_unique(node_name: str) -> str: + # make it both informative and unique + return f"aot{deduped_aot_id}_{node_name}" + + for node in bw_module.graph.nodes: + if node.op == "placeholder": + ph = pall_args[args_idx].node + ph.name = make_unique(node.name) + value_remap[node] = ph + args_idx += 1 + elif node.op == "output": + if len(node.args) != 1: + raise AssertionError( + f"Expected output node to have 1 arg, got {len(node.args)}" + ) + poutputs = [ + torch.fx.Proxy(value_remap[n], self.fx_tracer) + if isinstance(n, torch.fx.Node) + else n + for n in node.args[0] + ] + elif node.op == "get_attr": + name = node.target + qualname = self.fx_tracer.get_fresh_qualname(name) + setattr(self.fx_tracer.root, qualname, getattr(bw_module, name)) + result = self.fx_tracer.create_node("get_attr", qualname, (), {}) + result.name = make_unique(node.name) + value_remap[node] = result + elif node.op == "call_function": + if node.target is torch.ops.aten.view.default: + # this aot bwd graph is being lazily compiled + # we must manually apply the view_to_reshape post grad pass + # since it was already applied to the aot fwd, and baked into the gradients + node.target = torch.ops.aten.reshape.default + result = self.fx_tracer.graph.node_copy( + node, lambda n: value_remap[n] + ) + result.name = make_unique(node.name) + value_remap[node] = result + elif node.op == "call_module": + name = node.target + qualname = self.fx_tracer.get_fresh_qualname(name) + setattr(self.fx_tracer.root, qualname, getattr(bw_module, name)) + result = self.fx_tracer.graph.node_copy( + node, lambda n: value_remap[n] + ) + result.target = qualname + value_remap[node] = result + else: + raise AssertionError("shouldn't get here") + + if poutputs is None: + raise AssertionError("No output node found in backward graph") + + # In general we don't know what the shapes of the outputs are, so allocate + # some dummy sizes for them. + def dummy() -> torch.Tensor: + with disable_proxy_modes_tracing(): + return torch.zeros(0, 0, 0, 0, 123) + + outputs = [ + dummy() if isinstance(o, torch.fx.Proxy) else o for o in poutputs + ] + self.bind_objects_to_proxies(outputs, poutputs) + return outputs + + outputs = copy_paste_aot_backward_graph() + + if maybe_subclass_metadata is not None: + + def proxy_subclass_constructor( + subclass_meta: Any, + is_runtime: bool, + unwrapped_args: Sequence[Any], + ) -> torch.Tensor: + @torch._dynamo.allow_in_graph # type: ignore[misc] + def make_subclass(*unwrapped_args: Any) -> Any: + return subclass_meta.creation_fn( + unwrapped_args, is_runtime=is_runtime + ) + + punwrapped_args = pytree.tree_map(self.to_proxy, unwrapped_args) + + poutput = self.fx_tracer.create_proxy( + kind="call_function", + # pyrefly: ignore [bad-argument-type] + target=make_subclass, + args=tuple(punwrapped_args), + kwargs={}, + ) + + output = self.allocate_dummy() + self.bind_objects_to_proxies([output], [poutput]) + return output + + results = bw_epilogue_fn( + outputs, make_subclass_override=proxy_subclass_constructor + ) + else: + results = bw_epilogue_fn(outputs) + + presults = pytree.tree_map(self.to_proxy, results) + return presults + + def proxy_call_backward( + self, + inputs: Sequence[Any], + output_metadatas: Sequence[Any], + saved_tensors: Sequence[torch.Tensor], + backward_idx: int, + ctx: torch.autograd.function.BackwardCFunction, + maybe_backward_state_idx: int | None, + opaque_object_indices: list[int], + ) -> tuple[torch.Tensor | None, ...]: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before proxy_call_backward") + pctx = self.hooks_proxy[backward_idx] # type: ignore[index] + pinputs = self.to_proxy(inputs) + psaved_tensors = self.to_proxy(saved_tensors) + if hasattr(ctx._forward_cls, "_aot_id"): # type: ignore[attr-defined] + # AOT backward + proxies = self.proxy_call_aot_backward( + pinputs, + psaved_tensors, + saved_tensors, + pctx, + ctx, + maybe_backward_state_idx, + opaque_object_indices, + ) + else: + if getattr(ctx._forward_cls, "boxed_grads_call", False): # type: ignore[attr-defined] + raise RuntimeError( + f"boxed_grads_call=True on {ctx._forward_cls.__name__} " # type: ignore[attr-defined] + "is not supported with compiled autograd. " + ) + proxies = self.fx_tracer.create_proxy( + kind="call_function", + target=call_backward, + args=( + pctx, + psaved_tensors, + *pinputs, + ), + kwargs={}, + ) + if proxies is None: + raise AssertionError("proxies must not be None after backward call") + + with disable_proxy_modes_tracing(): + # create fake Tensors + grad_ins: list[torch.Tensor | None] = [] + for idx, output_metadata in enumerate(output_metadatas): + if output_metadata is None or proxies[idx] is None: + grad_ins.append(None) + continue + + layout, device, dtype, size = output_metadata + grad_ins.append( + torch.empty(size=size, dtype=dtype, layout=layout, device=device) + ) + self.bind_objects_to_proxies(grad_ins, proxies) + return tuple(grad_ins) + + def call_copy_slices_prologue( + self, + inputs: Sequence[Any], + base_sizes: Sequence[Any], + base_strides: Sequence[Any], + base_storage_offset: Any, + view_sizes: Sequence[Any], + view_strides: Sequence[Any], + view_storage_offset: Any, + ) -> Sequence[torch.Tensor]: + args = ( + inputs, + self.to_proxy(base_sizes), + self.to_proxy(base_strides), + self.to_proxy(base_storage_offset), + self.to_proxy(view_sizes), + self.to_proxy(view_strides), + self.to_proxy(view_storage_offset), + ) + return self.proxy_call(copy_slices_prologue, args, [None] * 3) + + def call_copy_slices_epilogue( + self, + needs_input_grad: Sequence[bool], + result: torch.Tensor, + res: Sequence[Any], + grad_slice: torch.Tensor, + ) -> Sequence[torch.Tensor]: + return self.proxy_call( + copy_slices_epilogue, + (needs_input_grad, result, res, grad_slice), + [None] * len(needs_input_grad), + ) + + def allocate_dummy(self) -> torch.Tensor: + with disable_proxy_modes_tracing(): + # Weird quantity so it's easy to grep + return torch.zeros([0, 123456789]) + + def allocate_dummy_like(self, x: torch.Tensor) -> torch.Tensor: + with disable_proxy_modes_tracing(): + return torch.empty_like(x) + + def bind_function( + self, + fn_name: str, + fn: Callable[..., Any], + is_custom_function: bool, + is_traceable: bool, + ) -> str: + """Binds ops.fn_name = fn""" + return ops.add(fn_name, fn, is_custom_function, is_traceable) + + def apply_functional( + self, + fn_name: str, + grads: Sequence[Any], + args: Any, + output_metadata: Sequence[Any], + ) -> Sequence[torch.Tensor]: + """Proxies a call to ops.fn_name(grads, *args) into the graph""" + op = ops.get(fn_name) + return self.proxy_call(op, (grads, *args), output_metadata) + + def proxy_call( + self, fn: Callable[..., Any], args: Any, output_metadata: Sequence[Any] + ) -> Sequence[torch.Tensor]: + """Proxies a call to fn(*args) into the graph""" + proxy_args = pytree.tree_map(lambda e: self.to_proxy(e), args) + proxy_out = self.fx_tracer.create_proxy( + "call_function", fn, args=proxy_args, kwargs={} + ) + result = [self.allocate_dummy() for _ in output_metadata] + self.bind_objects_to_proxies(result, [proxy_out[i] for i in range(len(result))]) + return result + + def validate_outputs( + self, _: Any, outputs: Sequence[Any], args: Any, output_metadata: Sequence[Any] + ) -> Sequence[torch.Tensor]: + """Proxies a call to ops.validate_outputs(outputs, *args) into the graph""" + op = ops.get("validate_outputs") + proxy_args = pytree.tree_map(self.to_proxy, (outputs, *args)) + new_proxy_outputs = self.fx_tracer.create_proxy( + "call_function", op, args=proxy_args, kwargs={} + ) + if len(output_metadata) != len(outputs): + raise AssertionError( + f"output_metadata length ({len(output_metadata)}) != outputs length ({len(outputs)})" + ) + self.bind_objects_to_proxies(outputs, new_proxy_outputs) + return outputs + + def accumulate(self, old_var: Any, new_var: Any) -> torch.Tensor: + old_var_proxy = self.to_proxy(old_var) + new_var_proxy = self.to_proxy(new_var) + proxy_out = self.fx_tracer.create_proxy( + "call_function", torch.add, args=(old_var_proxy, new_var_proxy), kwargs={} + ) + result = self.allocate_dummy() + self.bind_objects_to_proxies([result], [proxy_out]) + return result + + def accumulate_grad( + self, + variable: torch.Tensor, + variable_grad: torch.Tensor | None, + grad: torch.Tensor | bool, + has_post_hooks: bool | None = None, + ) -> torch.Tensor | None: + old_call = has_post_hooks is None + if has_post_hooks is None: + # Backward compatibility for extensions built before current grad + # became an explicit capture argument. + has_post_hooks = bool(grad) + grad = variable_grad # type: ignore[assignment] + variable_grad = variable.grad + + proxy_out = self.fx_tracer.create_proxy( + "call_function", + call_accumulate_grad, + args=( + self.to_proxy(variable), + self.to_proxy(variable_grad), + self.to_proxy(grad), + has_post_hooks, + ), + kwargs={}, + ) + result = self.allocate_dummy_like(variable) + self.bind_objects_to_proxies([result], [proxy_out]) + variable.grad = result + if old_call: + return None + return result + + def proxy_call_hook( + self, hook: Callable[..., Any], *args: Any, hook_type: HookType + ) -> torch.fx.Proxy: + return self.fx_tracer.create_proxy( + "call_function", + call_hook, + ( + hook, + *[self.to_proxy(x) for x in args], + ), + {"hook_type": hook_type}, + ) + + def unpack_hook(self, hook_id: int, data_id: int) -> torch.Tensor: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before unpack_hook") + hook = self.hooks_proxy[hook_id] # type: ignore[index] + data = self.packed_data_proxy[data_id] # type: ignore[index] + proxy = self.proxy_call_hook( + hook, + data, + hook_type="unpack_hook", + ) + out = self.allocate_dummy() + self.bind_objects_to_proxies([out], [proxy]) + return out + + def tensor_pre_hook( + self, inputs: list[torch.Tensor], hook_id: int, i: int + ) -> list[torch.Tensor]: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before tensor_pre_hook") + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxy = self.proxy_call_hook( + hook, + inputs[i], + hook_type="tensor_pre_hook", + ) + with disable_proxy_modes_tracing(): + inputs[i] = maybe_clone(inputs[i]) # type: ignore[assignment] + self.bind_objects_to_proxies([inputs[i]], [proxy]) + return inputs + + def cpp_tensor_pre_hook( + self, inputs: list[torch.Tensor], hook_id: int, i: int + ) -> list[torch.Tensor]: + proxy = self.fx_tracer.create_proxy( + "call_function", + torch._C._dynamo.compiled_autograd.call_cpp_tensor_pre_hooks, + (hook_id, self.to_proxy(inputs[i])), + {}, + ) + with disable_proxy_modes_tracing(): + inputs[i] = maybe_clone(inputs[i]) # type: ignore[assignment] + self.bind_objects_to_proxies([inputs[i]], [proxy]) + return inputs + + def pre_hook(self, inputs: Sequence[Any], hook_id: int) -> list[torch.Tensor]: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before pre_hook") + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxies = self.proxy_call_hook( + hook, + inputs, + hook_type="pre_hook", + ) + with disable_proxy_modes_tracing(): + inputs = [maybe_clone(x) for x in inputs] + self.bind_objects_to_proxies(inputs, proxies) + return inputs + + def post_hook( + self, outputs: list[torch.Tensor], inputs: Sequence[torch.Tensor], hook_id: int + ) -> list[torch.Tensor]: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before post_hook") + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxies = self.proxy_call_hook( + hook, + outputs, + inputs, + hook_type="post_hook", + ) + with disable_proxy_modes_tracing(): + outputs = [maybe_clone(x) for x in outputs] # type: ignore[misc] + self.bind_objects_to_proxies(outputs, proxies) + return outputs + + def post_acc_grad_hook( + self, input: torch.Tensor, hook_id: int + ) -> list[torch.Tensor]: + if not isinstance(input, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(input)}") + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before post_acc_grad_hook") + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxy = self.proxy_call_hook( + hook, + input, + hook_type="post_acc_grad_hook", + ) + with disable_proxy_modes_tracing(): + res = [maybe_clone(input)] + self.bind_objects_to_proxies(res, [proxy]) + return res # type: ignore[return-value] + + # Note: [Compiled autograd and cudagraphs] + # Eager autograd backward implements scalars as 0-dim tensors, see DivBackward0::other_. + # When compiled autograd traces those nodes, it lifts the scalar tensors, resulting in a graph + # with some cpu 0-dim tensor inputs. To prevent the entire graph from skipping cudagraph, we move the + # scalar tensors to cuda. This works because ATen/prims ops will accept cuda 0-dim tensors too. + def move_graph_nodes_to_cuda(self, graph: torch.fx.Graph) -> list[int]: + to_move: dict[int, torch.fx.Node] = {} + has_cuda_inputs = False + nodes = list(graph.nodes) + if nodes[0].target != "inputs": + raise AssertionError( + f"Expected first node target to be 'inputs', got '{nodes[0].target}'" + ) + inputs = nodes[0] + inputs_users = list(inputs.users.keys()) + # input access nodes should immediately follow placeholder nodes + first_getitem_idx = len(_graph_placeholders) + if nodes[first_getitem_idx] != inputs_users[0]: + raise AssertionError("First getitem node does not match first inputs user") + last_getitem_idx = first_getitem_idx + len(inputs_users) - 1 + if nodes[last_getitem_idx] != inputs_users[-1]: + raise AssertionError("Last getitem node does not match last inputs user") + # getitem nodes on inputs + for i, node in enumerate(inputs_users): + if not has_cuda_inputs and node.meta["val"].device.type == "cuda": + has_cuda_inputs = True + continue + + is_cpu = node.meta["val"].device.type == "cpu" + is_scalar = len(node.meta["val"].size()) == 0 + if is_cpu and is_scalar: + node_users = list(node.users.keys()) + # We can only move the cpu scalar if it is not exposed to user code. + if all( + ( + isinstance(user.target, torch._ops.OpOverload) + and user.target.namespace in ("prims", "aten") + ) + or ( + isinstance(user.target, Op) + and not user.target.is_custom_function + ) + for user in node_users + ): + # all users are prims/aten, can move safely + to_move[i] = node + + # only move cpu scalars to cuda if there were cuda activations in this graph, + # this is to handle the case where cudagraphs is enabled on a cpu-only graph + if has_cuda_inputs: + for node in to_move.values(): + verbose_log.debug("Moving node %s from cpu to cuda", node) + node.meta["val"] = node.meta["val"].cuda() + + # return runtime indices we need to move to cuda + return list(to_move.keys()) + + return [] + + def is_sym_node(self, node: Any) -> bool: + return ( + isinstance(node, torch.fx.Node) + and node.op == "call_function" + and node.target + in [torch.ops.aten.sym_size.int, torch.ops.aten.sym_numel.default] + ) + + def dce(self) -> None: + # Most of these removed nodes would have been removed during Dynamo and AOTDispatch + # Remove some of these nodes earlier to improve compilation speed + + # Dynamo guards will error instead of creating aliasing guards unless we unpack them in the graph + unpack_nodes: OrderedSet[torch.fx.Node] = OrderedSet() + i: int | None = None + for i, node in enumerate(self.fx_tracer.graph.find_nodes(op="placeholder")): + unpack_nodes.update(node.users.keys()) + if i != len(_graph_placeholders) - 1: + raise AssertionError( + f"Expected {len(_graph_placeholders) - 1} placeholders, got {i}" + ) + + def is_impure(node: torch.fx.Node) -> bool: + if node in unpack_nodes or ( + node.op == "call_function" and node.target in _impure_targets + ): + return True + return node.is_impure() + + before = len(self.fx_tracer.graph.nodes) + self.fx_tracer.graph.eliminate_dead_code(is_impure) + after = len(self.fx_tracer.graph.nodes) + verbose_log.debug("DCE removed %d nodes", before - after) + + def remove_unused_sizes(self) -> set[int]: + used_sizes = [] + unused_sizes = [] + + # seek placeholder, should be at nodes[1] + it = iter(self.fx_tracer.graph.nodes) + next(it) + sizes_node = next(it) + if sizes_node.name != "sizes": + raise AssertionError( + f"Expected placeholder 'sizes', got '{sizes_node.name}'" + ) + + for getitem_node in sizes_node.users: + if getitem_node.target is not operator.getitem: + raise AssertionError( + f"Expected operator.getitem target, got {getitem_node.target}" + ) + if getitem_node.users: + used_sizes.append(getitem_node) + else: + # remove from the graph + unused_sizes.append(getitem_node) + + used_sizes_idx: set[int] = set() + for used in used_sizes: + if not isinstance(used.args, tuple): + raise AssertionError( + f"Expected used.args to be tuple, got {type(used.args)}" + ) + if used.args[0] != sizes_node: + raise AssertionError("Expected used.args[0] to be sizes_node") + if not isinstance(used.args[1], int): + raise AssertionError( + f"Expected used.args[1] to be int, got {type(used.args[1])}" + ) + next_size_idx = len(used_sizes_idx) + # used later reindex the runtime sizes arg + used_sizes_idx.add(used.args[1]) + # reindex the graph + used.args = (used.args[0], next_size_idx) + + for unused in unused_sizes: + self.fx_tracer.graph.erase_node(unused) + + return used_sizes_idx + + def create_graph_module(self, id: str) -> GraphModule: + return GraphModule(self.fx_tracer.root, self.fx_tracer.graph, id) + + def end_capture(self, outputs: Any) -> tuple[Callable[..., Any], Any]: + self.fx_tracer.create_proxy( + "call_function", + FakeCompiledAutogradEngine._exec_final_callbacks_stub, + (), + {}, + ) + self.stack.close() + self.fx_tracer.create_node( + "output", + "output", + (self.fx_tracer.create_arg(self.to_proxy(outputs)),), + {}, + ) + runtime_inputs_to_move: list[int] = [] + if snapshot_cudagraph_enabled(): + runtime_inputs_to_move = self.move_graph_nodes_to_cuda(self.fx_tracer.graph) + + # We traced using dummy tensors. Delete all the metadata of the dummy tensors. + # It's probably better to refactor this class to use a different tracer + # than the make_fx tracer, but that is a larger change. + for node in self.fx_tracer.graph.nodes: + for field in ["tensor_meta", "example_value", "val"]: + if field in node.meta: + del node.meta[field] + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "compiled_autograd_graph_pre_reordering", + "encoding": "string", + }, + payload_fn=lambda: GraphModule( + self.fx_tracer.root, + self.fx_tracer.graph, + f"CompiledAutograd{self.id}PreReordering", + ).print_readable(print_output=False), + ) + self.delay_unpack_hook_nodes() + self.reorder_tensor_pre_hook_nodes() + self.reorder_pre_hook_nodes_to_schedule_asap() + self.reorder_accumulate_grad_nodes() + self.reorder_pre_hook_nodes_to_mimic_eager() + self.reorder_post_acc_grad_hook_nodes() + self.reorder_post_hook_nodes() + # TODO(yf225): work around: remove dead codes like `sym_size` and `sym_numel` which are not used downstream. e.g. + # ``` + # sym_numel_default = torch.ops.aten.sym_numel.default(sum_109); sum_109 = None + # eq_115 = 16 == sym_numel_default; sym_numel_default = eq_115 = None + # sym_size_int_39 = torch.ops.aten.sym_size.int(getitem_112, 1); getitem_112 = None + # eq_116 = 16 == sym_size_int_39; eq_116 = None + # eq_117 = 16 == sym_size_int_39; sym_size_int_39 = eq_117 = None + # ``` + # Proper fix is Richard's Python compiled autograd effort which will avoid calling make_fx and + # should prevent these ops from going into the CA graph. + self.dce() + if self.nan_checker: + self.nan_checker.prep_with_graph(self.fx_tracer.graph) + + # keep only sizes that are actually used in the graph + used_sizes_idx = self.remove_unused_sizes() + + graph = self.create_graph_module(f"CompiledAutograd{self.id}") + set_locals_to_steal(graph, ["inputs"]) + lazy_graph_code = lazy_format_graph_code( + "Compiled autograd graph", + graph, + include_device=True, + include_stride=True, + colored=True, + ) + compiled_autograd_log.info("%s", lazy_graph_code) + verbose_log.debug("%s", lazy_graph_code) + trace_structured( + "compiled_autograd_graph", + payload_fn=lambda: graph.print_readable(print_output=False), + ) + + def runtime_wrapper( + compiled_fn: Callable[..., Any], + inputs: Any, + sizes: Any, + scalars: Any, + hooks: Any, + packed_inputs: Any, + ) -> tuple[Any, Any]: + global in_compiled_autograd_region + try: + in_compiled_autograd_region = True + + if self.nan_checker: + self.nan_checker.prep_with_inputs(inputs) + + filtered_sizes = [] + for idx, integer in enumerate(sizes): + if idx in used_sizes_idx: + # can't create negative size + if integer > 0: + filtered_sizes.append(torch.empty(0, integer)) + torch._dynamo.maybe_mark_dynamic(filtered_sizes[-1], 1) + else: + filtered_sizes.append(integer) + + for i in runtime_inputs_to_move: + inputs[i] = inputs[i].pin_memory().cuda(non_blocking=True) + + with _disable(), make_compile_context(self.id): + out = compiled_fn( + inputs, filtered_sizes, scalars, hooks, packed_inputs + ) + if self.nan_checker: + self.nan_checker.check(out) + return out + finally: + in_compiled_autograd_region = False + + get_chromium_event_logger().log_event_end( + "compiled_autograd", + time.time_ns(), + {"graph_id": self.id}, + self.start_time_ns, + log_pt2_compile_event=True, + ) + self.compile_context.__exit__(None, None, None) + return runtime_wrapper, self.compiler_fn(graph) + + @staticmethod + def get_all_nodes(args: Sequence[Any]) -> list[torch.fx.Node]: + # filter out non-Node args, like None + nodes = [n for n in args if type(n) is torch.fx.Node] + return nodes + + @staticmethod + def is_placeholder(node: torch.fx.Node) -> bool: + if node.op == "placeholder" or ( + node.op == "call_function" + and node.target is operator.getitem + and node.args[0].op == "placeholder" # type: ignore[union-attr, arg-type] + ): + return True + return False + + def reorder_accumulate_grad_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the accumulate_grad_ nodes to get pushed to the end of + the graph. This differs from eager mode, which schedules them as soon as possible. This + pass attempts to reorder the graph to mimic eager behavior. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_accumulate_grad + ): + param_node, variable_grad_node, grad_node = ( + node.args[0], + node.args[1], + node.args[2], + ) + getitem_node = None + if ( + isinstance(grad_node, torch.fx.Node) + and grad_node.target is operator.getitem + ): + getitem_node = grad_node + grad_node = getitem_node.args[0] + + arg = max( + self.get_all_nodes([param_node, variable_grad_node, grad_node]) + ) # last arg + if arg is not node.prev and not self.is_placeholder(arg): + arg.append(node) + if getitem_node is not None: + arg.append(getitem_node) + + def delay_unpack_hook_nodes(self) -> None: + """ + We can delay unpack hooks until they are needed, even later than in the eager autograd engine. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "unpack_hook": + continue + + first_user = min(node.users) + first_user.prepend(node) + + def reorder_tensor_pre_hook_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the tensor_pre_hook nodes to get pushed + to the end of the graph. This differs from eager mode, which schedules + them as soon as possible. This pass attempts to reorder the graph to + mimic eager behavior. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "tensor_pre_hook": + continue + + getitem_node = node.args[0] + input_node = node.args[1] # tensor_pre_hook handle only one grad tensor + + if input_node is not node.prev and not self.is_placeholder(input_node): + input_node.append(getitem_node) + getitem_node.append(node) + + def reorder_pre_hook_nodes_to_schedule_asap(self) -> None: + """ + In this function, we schedule the pre hooks as soon as possible. This + does not match eager behavior (schedule pre hook right before its + registered node), but it can make acc grad be scheduled properly when + the pre hooks are registered to them. After reordering acc grad node, we + will reorder the pre hooks again to mimic eager behavior. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "pre_hook": + continue + + getitem_node = node.args[0] + # pre_hook handle a tuple of grad tensors + input_nodes = self.get_all_nodes(node.args[1]) + + to_remove = [] + to_append = [] + hook_block = [node] # contain the hook and hook args getitem + for n in input_nodes: + if n.op == "call_function" and n.target is operator.getitem: + to_append.append(n.args[0]) + to_remove.append(n) + hook_block.append(n) + for a, b in zip(to_remove, to_append): + input_nodes.remove(a) + input_nodes.append(b) # type: ignore[arg-type] + + arg = max(input_nodes) # last input + if arg is not node.prev and not self.is_placeholder(arg): + arg.append(getitem_node) + for n in hook_block: + getitem_node.append(n) + + def reorder_pre_hook_nodes_to_mimic_eager(self) -> None: + """ + Usage of AOTAutograd causes all the pre_hook nodes to get pushed to the + end of the graph. This differs from eager mode, which schedules them + right before their registered node execution. This pass attempts to + reorder the graph to mimic eager behavior. + """ + pre_hooks = [] + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "pre_hook": + continue + pre_hooks.append(node) + + for node in reversed(pre_hooks): + hook_getitem_node = node.args[0] + + users = list(node.users.keys()) + if len(users) == 0: + continue + + # users are all getitem ops and they are used by same registered node + if not all( + user.op == "call_function" and user.target is operator.getitem + for user in users + ): + raise AssertionError( + "Expected all users of pre_hook to be operator.getitem call_function nodes" + ) + registered_node = next(iter(users[0].users.keys())) + + if registered_node is not node.next: + registered_node.prepend(hook_getitem_node) + registered_node.prepend(node) + for getitem in users: + registered_node.prepend(getitem) + + def reorder_post_acc_grad_hook_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the post_acc_grad_hook nodes to get + pushed to the end of the graph. This differs from eager mode, which + schedules them as soon as possible. This pass attempts to reorder the + graph to mimic eager behavior. + """ + post_acc_grad_hooks = [] + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "post_acc_grad_hook": + continue + post_acc_grad_hooks.append(node) + + # nodes in post_acc_grad_hooks are in topo order. For hooks registered + # to same node, we should keep their relative order + for node in reversed(post_acc_grad_hooks): + getitem_node = node.args[0] + param_node = node.args[1] # post_acc_grad_hook handle one param + + # find the corresponding acc_grad node + acc_grad_node = None + for n in list(param_node.users.keys()): + if n.op == "call_function" and n.target is call_accumulate_grad: + acc_grad_node = n + break + + if acc_grad_node is None: + raise AssertionError( + "post_acc_grad_hook must have corresponding acc grad node" + ) + + # append post_acc_grad_hook after acc_grad node + acc_grad_node.append(getitem_node) + getitem_node.append(node) + + def reorder_post_hook_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the post_hook nodes to get pushed to the + end of the graph. This differs from eager mode, which schedules them as + soon as possible. This pass attempts to reorder the graph to mimic eager + behavior. + """ + post_hooks = [] + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "post_hook": + continue + post_hooks.append(node) + + for node in reversed(post_hooks): + getitem_node = node.args[0] + output_nodes = node.args[1] + input_nodes = node.args[2] + + if len(output_nodes) > 0: + continue + + # pyrefly: ignore [implicit-any] + input_nodes_and_users = [] + input_nodes_and_users.extend(list(input_nodes)) + for input_node in input_nodes: + input_nodes_and_users.extend( + user + for user in list(input_node.users.keys()) + if not ( + user.op == "call_function" + and user.target is call_hook + and node.kwargs.get("hook_type", None) == "post_hook" + ) + ) + + arg = max(input_nodes_and_users) # last input users + if arg.op == "call_function" and arg.target is call_accumulate_grad: + param_node = arg.args[0] + post_acc_grad_hook_node = None + for n in list(param_node.users.keys()): + if ( + n.op == "call_function" + and n.target is call_hook + and n.kwargs.get("hook_type", None) == "post_acc_grad_hook" + ): + post_acc_grad_hook_node = n + + if post_acc_grad_hook_node is not None: + post_acc_grad_hook_node.append(getitem_node) + getitem_node.append(node) + continue + + if arg is not node.prev and not self.is_placeholder(arg): + arg.append(getitem_node) + getitem_node.append(node) + + def to_proxy(self, t: Any) -> Any: + if t is None: + return None + if isinstance(t, list): + return [self.to_proxy(x) for x in t] + if isinstance(t, tuple): + return tuple(self.to_proxy(x) for x in t) + if isinstance(t, (torch.SymInt, torch.SymFloat)): + return self.symnode_proxy_lookup[t.node] + if not isinstance(t, torch.Tensor): + # constant types like device, dtype, str + return t + proxy_tensor = fetch_object_proxy(self.fx_tracer, t) + if not isinstance( + proxy_tensor, torch.fx.experimental.proxy_tensor._ProxyTensor + ): + raise AssertionError(f"Expected _ProxyTensor, got {type(proxy_tensor)}") + return proxy_tensor.proxy + + def bind_objects_to_proxies( + self, + objects: Sequence[Any], + proxies: Any, + origins: list[tuple[int, str]] | None = None, + ) -> Sequence[Any]: + if isinstance(proxies, torch.fx.Proxy): + if origins: + if len(origins) != len(objects): + raise AssertionError( + f"origins length ({len(origins)}) != objects length ({len(objects)})" + ) + bound_proxies = [] + for i in range(len(objects)): + nodecall_index, node_name = origins[i] + self.set_node_origin(node_name, nodecall_index, None) + bound_proxies.append(proxies[i]) # type: ignore[index] + proxies = bound_proxies + else: + proxies = [proxies[i] for i in range(len(objects))] # type: ignore[index] + + if len(objects) != len(proxies): + raise AssertionError( + f"objects length ({len(objects)}) != proxies length ({len(proxies)})" + ) + track_tensor_tree(objects, proxies, constant=None, tracer=self.fx_tracer) + return proxies + + def bind_backward_state(self, index: int) -> BackwardState: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before bind_backward_state") + proxy = self.hooks_proxy[index] # type: ignore[index] + bw_state = BackwardState() + track_tensor_tree(bw_state, proxy, constant=None, tracer=self.fx_tracer) + return bw_state + + def set_node_origin( + self, + node_name: str, + nodecall_index: int, + pyobj: torch.autograd.Function | None, + ) -> None: + maybe_aot_id = "" + if pyobj is not None: + forward_cls = pyobj._forward_cls # type: ignore[attr-defined] + if hasattr(forward_cls, "_aot_id"): + # backward was created by AOT Dispatcher + if forward_cls._lazy_backward_info is None: + raise RuntimeError( + """This compiled backward function was saved by AOTAutogradCache, which does not support + compiled autograd. Please turn off AOTAutogradCache using `TORCHINDUCTOR_AUTOGRAD_CACHE=0`.""" + ) + maybe_aot_id = forward_cls._aot_id + new_code = f"{node_name}{maybe_aot_id} (NodeCall {nodecall_index})" + raw_stack_trace = CapturedTraceback.extract().format()[-1] + new_stack_trace = raw_stack_trace.replace( + "raw_stack_trace = CapturedTraceback.extract().format()[-1]", new_code + ) + set_stack_trace(new_stack_trace) + + +# state of the autograd engine dispatch, kept in sync by enable/disable context managers +compiled_autograd_enabled = False + +# global flag to check if compiled autograd is enabled but Dynamo stance is "force_eager" +compiled_autograd_enabled_force_eager = False + +# global flag to check if we are processing graphs produced from a compiled autograd graph +in_compiled_autograd_region = False + +active_disable_ctx = False + +depth = 0 + + +@contextlib.contextmanager +def _enable( + compiler_fn: Callable[..., Any], + dynamic: bool = True, + ignore_active_disable_ctx: bool = True, +) -> Generator[None, None, None]: + # The entrypoint to enable CA. + # It is recommended to enable via `torch._dynamo.config.compiled_autograd = True` rather + # than using this context manager directly. If you are torch.compiling the corresponding + # forward pass, make sure they are wrapped under this context as well. + # + # Example: + # def train(model, inputs, target): + # compiled_model = torch.compile(model) + # pred = compiled_model(data) + # loss = compute_loss(pred, target) + # loss.backward() + # + # with _enable(compiler_fn): + # train(model, inputs, target) + # + # Inputs: + # - compiler_fn: The wrapper that will consume the compiled autograd graph, e.g. `torch.compile` + # - dynamic: Whether compiled autograd will treat tensors in the autograd graph (params, activations) as dynamic. + # This doesn't affect the dynamic configuration of the compilation wrapper. + + if not ignore_active_disable_ctx and active_disable_ctx: + yield + else: + if dynamic: + if type(dynamic) is not bool: + raise AssertionError( + f"Expected dynamic to be bool, got {type(dynamic)}" + ) + + from torch._dynamo import eval_frame + + if eval_frame._stance.stance == "force_eager": + # If user explicitly sets Dynamo stance to "force_eager", we want Compiled Autograd + # to fall back to eager as well. + global compiled_autograd_enabled_force_eager + compiled_autograd_enabled_force_eager = True + try: + yield + finally: + compiled_autograd_enabled_force_eager = False + else: + # we need to import this, because user might not have imported it if they directly use this context manager + # we need to lazily import it, because of circular dependencies + if torch.cuda.is_available(): + from torch._inductor import cudagraph_trees # noqa: F401 + + ( + prior_compiler, + prior_dynamic, + ) = torch._C._dynamo.compiled_autograd.set_autograd_compiler( + functools.partial(AutogradCompilerInstance, compiler_fn), dynamic + ) + if snapshot_verbose_logging_enabled(): + torch._C._dynamo.compiled_autograd.set_verbose_logger(verbose_log) # type:ignore[arg-type] + global compiled_autograd_enabled + compiled_autograd_enabled = True + global depth + prior_depth = depth + depth += 1 + try: + with torch.autograd.set_multithreading_enabled(False): + yield + finally: + if not prior_compiler: + compiled_autograd_enabled = False + torch._C._dynamo.compiled_autograd.set_autograd_compiler( + prior_compiler, prior_dynamic + ) + depth -= 1 + if depth != prior_depth: + raise AssertionError( + "Nested Compiled Autograd Contexts must return before their parent context" + ) + + +@contextlib.contextmanager +def _disable() -> Generator[None, None, None]: + ( + prior_compiler, + prior_dynamic, + ) = torch._C._dynamo.compiled_autograd.set_autograd_compiler(None, False) + global compiled_autograd_enabled + compiled_autograd_enabled = False + global active_disable_ctx + if not active_disable_ctx: + active_disable_ctx = True + try: + yield + finally: + if prior_compiler: + compiled_autograd_enabled = True + active_disable_ctx = False + torch._C._dynamo.compiled_autograd.set_autograd_compiler( + prior_compiler, prior_dynamic + ) + + +# return to starting state of a new process +def reset() -> None: + global compiled_autograd_enabled + compiled_autograd_enabled = False + if in_compiled_autograd_region: + raise AssertionError("Cannot reset while in_compiled_autograd_region is True") + torch._C._dynamo.compiled_autograd.set_autograd_compiler(None, False) + torch._C._dynamo.compiled_autograd.set_verbose_logger(None) + torch._C._dynamo.compiled_autograd.clear_cache() + global COMPILE_COUNTER + COMPILE_COUNTER = itertools.count() + + +# Reimplementation of part of CopySlices::apply in Python. +# The shared code is really similar so we're not going to try to deduplicate. +def copy_slices_prologue( + inputs: Sequence[torch.Tensor], + base_sizes: Sequence[IntLikeType], + base_strides: Sequence[IntLikeType], + base_storage_offset: IntLikeType, + view_sizes: Sequence[IntLikeType], + view_strides: Sequence[IntLikeType], + view_storage_offset: IntLikeType, +) -> list[torch.Tensor]: + grad = inputs[0] + result = grad.new_empty_strided(base_sizes, base_strides) + if grad is None: + raise AssertionError("grad must not be None in copy_slices_prologue") + result.copy_(grad) + offset = view_storage_offset - base_storage_offset + grad_slice = result.as_strided(view_sizes, view_strides, offset) + return [result, grad_slice, grad_slice.clone(memory_format=torch.contiguous_format)] + + +# Reimplementation of part of CopySlices::apply in Python. +# The shared code is really similar so we're not going to try to deduplicate. +def copy_slices_epilogue( + needs_input_grad: Sequence[bool], + result: torch.Tensor, + res: Sequence[torch.Tensor | None], + grad_slice: torch.Tensor, +) -> list[torch.Tensor | None]: + grad_inputs: list[torch.Tensor | None] = [None] * len(needs_input_grad) + for i in range(len(needs_input_grad)): + if needs_input_grad[i]: + if res[i] is None: + continue + if i == 0: + to_copy = res[i] + if to_copy is None: + raise AssertionError( + "res[0] must not be None for needs_input_grad[0]" + ) + grad_slice.copy_(to_copy) + grad_inputs[i] = result + else: + grad_inputs[i] = res[i] + return grad_inputs diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/comprehension_graph_break.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/comprehension_graph_break.py new file mode 100644 index 0000000000000000000000000000000000000000..df34beb74120756cbc3d9c267ce5a101660bdaab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/comprehension_graph_break.py @@ -0,0 +1,672 @@ +from __future__ import annotations + +import copy +import dataclasses +import dis +import functools +import logging +import sys +from collections import Counter +from typing import Any, TYPE_CHECKING + + +if TYPE_CHECKING: + import types + + from .symbolic_convert import InstructionTranslatorBase + +from .bytecode_transformation import ( + create_copy, + create_dup_top, + create_instruction, + create_swap, + Instruction, + unique_id, +) +from .codegen import PyCodegen +from .exc import unimplemented +from .graph_break_hints import DYNAMO_BUG +from .output_graph import GraphCompileReason, StackLocalsMetadata +from .variables.misc import NullVariable, UnknownVariable + + +log = logging.getLogger(__name__) + + +@functools.cache +def _get_comprehension_bytecode_prefix() -> list[str]: + """Get the bytecode instructions that precede BUILD_LIST in a list comprehension.""" + + if sys.version_info < (3, 12): + raise AssertionError( + f"comprehension bytecode prefix requires Python 3.12+, got {sys.version_info}" + ) + + def fn() -> list[int]: + return [i for i in range(1)] # noqa: C416 + + insts = [inst.opname for inst in dis.get_instructions(fn)] + + start_idx = len(insts) - 1 - insts[::-1].index("LOAD_FAST_AND_CLEAR") + end_idx = insts.index("BUILD_LIST") + + return insts[start_idx:end_idx] + + +@dataclasses.dataclass +class ComprehensionAnalysis: + """Metadata about a comprehension's bytecode structure. + + Attributes: + end_ip: Instruction pointer after all comprehension bytecode + result_var: Name of result variable, or None if result stays on stack + result_on_stack: True if result stays on stack (discarded, returned, or in expression) + iterator_vars: Variables from LOAD_FAST_AND_CLEAR (need restoration) + walrus_vars: Variables assigned via walrus operator (:=) inside comprehension + captured_vars: Variables read from outer scope via LOAD_FAST inside comprehension + """ + + end_ip: int + result_var: str | None + result_on_stack: bool + iterator_vars: list[str] + walrus_vars: list[str] + captured_vars: list[str] + + +def _is_comprehension_start(tx: InstructionTranslatorBase) -> bool: + """Detect if we're at the start of a list/dict comprehension in 3.12+. + + In Python 3.12+, comprehensions are inlined with a bytecode pattern that + precedes BUILD_LIST/BUILD_MAP. + """ + if sys.version_info < (3, 12): + raise AssertionError( + f"comprehension start detection requires Python 3.12+, got {sys.version_info}" + ) + + if tx.instruction_pointer is None: + raise AssertionError("instruction_pointer must not be None") + ip = tx.instruction_pointer - 1 + + pattern = _get_comprehension_bytecode_prefix() + prefix = [inst.opname for inst in tx.instructions[ip - len(pattern) : ip]] + + return prefix == pattern + + +def _find_comprehension_end_for_ip(tx: InstructionTranslatorBase) -> int: + """Find the instruction pointer of the outermost END_FOR for current comprehension.""" + if sys.version_info < (3, 12): + raise AssertionError( + f"comprehension END_FOR search requires Python 3.12+, got {sys.version_info}" + ) + if tx.instruction_pointer is None: + raise AssertionError("instruction_pointer must not be None") + + nesting_depth = 0 + for search_ip in range(tx.instruction_pointer, len(tx.instructions)): + inst = tx.instructions[search_ip] + if inst.opname == "FOR_ITER": + nesting_depth += 1 + elif inst.opname == "END_FOR": + nesting_depth -= 1 + if nesting_depth == 0: + return search_ip + return -1 + + +def _analyze_comprehension(tx: InstructionTranslatorBase) -> ComprehensionAnalysis: + """Analyze comprehension bytecode to determine result handling pattern.""" + if sys.version_info < (3, 12): + raise AssertionError( + f"comprehension analysis requires Python 3.12+, got {sys.version_info}" + ) + if tx.instruction_pointer is None: + raise AssertionError("instruction_pointer must not be None") + + start_ip = tx.instruction_pointer - 1 # BUILD_LIST/BUILD_MAP + + iterator_vars: list[str] = [] + walrus_vars: list[str] = [] + captured_vars: list[str] = [] + defined_inside: set[str] = set() + + # Collect iterator variables from LOAD_FAST_AND_CLEAR before BUILD_LIST/BUILD_MAP + iter_scan_ip = start_ip - 1 + while iter_scan_ip >= 0: + inst = tx.instructions[iter_scan_ip] + if inst.opname == "LOAD_FAST_AND_CLEAR": + iterator_vars.insert(0, inst.argval) + iter_scan_ip -= 1 + elif inst.opname in ("SWAP", "GET_ITER"): + iter_scan_ip -= 1 + else: + break + defined_inside.update(iterator_vars) + + end_for_ip = _find_comprehension_end_for_ip(tx) + if end_for_ip == -1: + unimplemented( + gb_type="Comprehension analysis failed: No END_FOR", + context="", + explanation="Could not find END_FOR instruction in comprehension bytecode.", + hints=[], + ) + + # Find first FOR_ITER to know where loop body starts + for_iter_ip = next( + i + for i in range(start_ip, end_for_ip) + if tx.instructions[i].opname == "FOR_ITER" + ) + + # Single pass through loop body to detect walrus vars and captured vars + for body_ip in range(for_iter_ip + 1, end_for_ip): + inst = tx.instructions[body_ip] + + # Detect walrus pattern: COPY 1 followed by STORE_FAST + if inst.opname == "COPY" and inst.arg == 1 and body_ip + 1 < end_for_ip: + next_inst = tx.instructions[body_ip + 1] + if next_inst.opname == "STORE_FAST": + var_name = next_inst.argval + if var_name not in iterator_vars and var_name not in walrus_vars: + walrus_vars.append(var_name) + defined_inside.add(var_name) + + # Track variables defined inside the loop + if inst.opname == "STORE_FAST": + defined_inside.add(inst.argval) + + # Detect LOAD_FAST referencing outer variables + elif inst.opname.startswith("LOAD_FAST"): + var_names = ( + inst.argval if isinstance(inst.argval, tuple) else (inst.argval,) + ) + for var_name in var_names: + if var_name not in defined_inside and var_name not in captured_vars: + captured_vars.append(var_name) + + # Extract pre_store_ops: all opcodes from END_FOR+1 until first STORE_FAST + pre_store_ops: list[str] = [] + scan_ip = end_for_ip + 1 + # In 3.13 END_FOR is followed by POP_TOP to pop the iter. In 3.12, END_FOR is responsible for doing the pop, and in + # 3.14+ POP_ITER is used instead. We skip over the mandatory POP_TOP in 3.13 to avoid confusing the analysis below + # (which looks for an additional POP_TOP if the result is discarded). + if sys.version_info[:2] == (3, 13): + scan_ip += 1 + while ( + scan_ip < len(tx.instructions) + and tx.instructions[scan_ip].opname != "STORE_FAST" + ): + pre_store_ops.append(tx.instructions[scan_ip].opname) + scan_ip += 1 + + store_fast_ip = scan_ip + + # Skip all STORE_FASTs (iteration-variable restores plus an optional result + # assignment) to find the end of the comprehension epilogue. + while ( + scan_ip < len(tx.instructions) + and tx.instructions[scan_ip].opname == "STORE_FAST" + ): + scan_ip += 1 + + # The comprehension epilogue always restores the iteration variables that + # were saved by LOAD_FAST_AND_CLEAR (one STORE_FAST each). The disposition + # of the result is determined relative to those restores: + # - a POP_TOP right after the loop teardown discards the result + # (bare statement) + # - one extra STORE_FAST beyond the iteration vars is a result + # assignment (the extra store may reuse an iteration var's name) + # - no extra store leaves the result on the stack (returned/consumed) + # We use this to classify the handling of the result as discarded, stored, + # or returned/consumed + n_iter = len(iterator_vars) + store_targets = Counter( + tx.instructions[i].argval for i in range(store_fast_ip, scan_ip) + ) + + result_var: str | None = None + if pre_store_ops[-1:] == ["POP_TOP"]: # discarded + result_var = None + result_on_stack = False + elif store_targets.total() > n_iter: # stored + store_targets.subtract(iterator_vars) + if store_targets.total() != 1: + unimplemented( + gb_type="Comprehension analysis failed: ambiguous result store", + context=f"store_targets={store_targets}, iterator_vars={iterator_vars}", + explanation="Expected exactly one comprehension result assignment.", + hints=DYNAMO_BUG, + ) + result_var = next(iter(store_targets)) + result_on_stack = False + elif store_targets.total() == n_iter: # returned/consumed + result_var = None + result_on_stack = True + else: + unimplemented( + gb_type="Comprehension analysis failed: No matches", + context=f"pre_store_ops={pre_store_ops}, store_targets={store_targets}, " + f"iterator_vars={iterator_vars}", + explanation="Comprehension does not match any known bytecode pattern.", + hints=DYNAMO_BUG, + ) + + return ComprehensionAnalysis( + end_ip=scan_ip, + result_var=result_var, + # pyrefly: ignore [unbound-name] + result_on_stack=result_on_stack, + iterator_vars=iterator_vars, + walrus_vars=walrus_vars, + captured_vars=captured_vars, + ) + + +def _handle_comprehension_graph_break( + tx: InstructionTranslatorBase, inst: Instruction +) -> None: + """Handle list/dict comprehension graph break. + + Builds a synthetic function wrapping the comprehension bytecode, + calls it via codegen_call_resume, then chains into the resume + function for the post-comprehension code. + """ + if sys.version_info < (3, 12): + raise AssertionError( + f"comprehension graph break requires Python 3.12+, got {sys.version_info}" + ) + if tx.instruction_pointer is None: + raise AssertionError("instruction_pointer must not be None") + + start_ip = tx.instruction_pointer - 1 # BUILD_LIST/BUILD_MAP + analysis = _analyze_comprehension(tx) + stack_pops = 1 + len(analysis.iterator_vars) + reason = GraphCompileReason("comprehension_graph_break", [tx.frame_summary()]) + log.debug("comprehension triggered compile") + + # --- Step 1: Compile the graph up to the comprehension --- + + all_stack_locals_metadata = tx.output.compile_subgraph( + tx, + reason=reason, + stack_pops=stack_pops, + ) + # Record which stack_pops items are NULL before popn loses the info. + # NULLs on the CPython stack can't be passed as function arguments. + stack_pops_null_mask = [ + isinstance(tx.stack[len(tx.stack) - stack_pops + i], NullVariable) + for i in range(stack_pops) + ] + + tx.popn(stack_pops) + meta = all_stack_locals_metadata[0] + cg = PyCodegen(tx.output.root_tx) + + # Runtime stack after compile_subgraph: + # cells, [frame_values], *(non-popped items), *(stack_pops items w/ NULLs) + # frame_values[0] = [frame N locals] (no stack items yet) + + nonnull_count = sum(1 for m in stack_pops_null_mask if not m) + + # live_stack_depth: stack items above cells/frame_values excluding NULLs + # that compile_subgraph didn't codegen (tracked in stack_null_idxes). + live_stack_depth = len(tx.stack) - len(meta.stack_null_idxes) + + # --- Step 2: Pop stack_pops items and append non-nulls to frame_values[0] --- + # SWAP each item to TOS then LIST_APPEND or pop_null; fv_list stays at + # TOS throughout. Items append in TOS-first (reversed) order; + # _build_comprehension_fn compensates by loading in reverse. + cg.extend_output( + [ + # frame_values[0] to TOS + *create_copy(live_stack_depth + stack_pops + 1), + cg.create_load_const(0), + cg.create_binary_subscr(), + ] + ) + for i in reversed(range(stack_pops)): + cg.extend_output(create_swap(2)) + if stack_pops_null_mask[i]: + cg.extend_output(cg.pop_null()) + else: + cg.extend_output(cg.create_list_append()) + cg.extend_output([create_instruction("POP_TOP")]) + + # Stack: cells, [frame_values], *(non-popped items) + + # --- Step 3: Build comprehension function --- + new_code, fn_name = _build_comprehension_fn( + tx, + analysis, + start_ip, + stack_pops, + stack_pops_null_mask, + nonnull_count, + meta, + ) + + # --- Step 4: Extract [cells[0]] and [frame_values[0]] for codegen_call_resume --- + cg.extend_output( + [ + *create_copy(live_stack_depth + 2), + cg.create_load_const(0), + cg.create_binary_subscr(), + create_instruction("BUILD_LIST", arg=1), + *create_copy(live_stack_depth + 2), + cg.create_load_const(0), + cg.create_binary_subscr(), + create_instruction("BUILD_LIST", arg=1), + ] + ) + + # Stack: ..., *(non-popped), [cells[0]], [frame_values[0]] + + # --- Step 5: Call comprehension function via codegen_call_resume --- + tx.codegen_call_resume([new_code], [fn_name], cg) + + # Stack: ..., *(non-popped), comp_result + + # --- Step 6: Remove appended stack_pops items from frame_values[0] --- + if nonnull_count > 0: + frame_values_pos = live_stack_depth + 1 + 1 # +1 result, +1 frame_values + cg.extend_output( + [ + *create_copy(frame_values_pos), + cg.create_load_const(0), + cg.create_binary_subscr(), + # frame_values[0] on TOS + create_dup_top(), + # frame_values[0], frame_values[0] + cg.create_load_const(-nonnull_count), + cg.create_load_const(None), + create_instruction("BUILD_SLICE", arg=2), + create_instruction("DELETE_SUBSCR"), + # del frame_values[0][-nonnull_count:] + create_instruction("POP_TOP"), + ] + ) + + # --- Step 7: Pass comprehension outputs to frame_values[0] --- + # Walrus vars first, then result_var. + vars_to_pass = analysis.walrus_vars + ( + [analysis.result_var] if analysis.result_var else [] + ) + + existing_vars: dict[str, int] = {} + for var_name in vars_to_pass: + tx.symbolic_locals[var_name] = UnknownVariable() + if var_name in meta.locals_names: + existing_vars[var_name] = meta.locals_names[var_name] + else: + # The var was cleared to NULL at the break (e.g. a comprehension + # iteration variable reused as the result target). We are binding + # it to a real value, so drop the NULL restoration; otherwise the + # resume function would reset it to NULL and clobber the result. + if var_name in meta.locals_null_keys: + meta.locals_null_keys.remove(var_name) + meta.locals_names[var_name] = len(meta.locals_names) + + fv_depth = live_stack_depth + 2 # comp_result + frame_values + + # --- Walrus vars: extract from comp_result tuple --- + if analysis.walrus_vars: + # comp_result is (result, *walrus_vars). + cg.extend_output( + [ + *create_copy(fv_depth), + cg.create_load_const(0), + cg.create_binary_subscr(), + ] + ) + # Stack: ..., comp_tuple, fv0 + for j, walrus_var in enumerate(analysis.walrus_vars): + cg.extend_output( + [ + *create_copy(2), + cg.create_load_const(j + 1), + cg.create_binary_subscr(), + ] + ) + # Stack: ..., comp_tuple, fv0, walrus_value + if walrus_var in existing_vars: + # fv0[idx] = walrus_value + cg.extend_output( + [ + *create_copy(2), # copy fv0 + cg.create_load_const(existing_vars[walrus_var]), + create_instruction("STORE_SUBSCR"), + ] + ) + else: + cg.extend_output(cg.create_list_append()) + # Stack: ..., comp_tuple, fv0 + cg.extend_output( + [ + create_instruction("POP_TOP"), # pop fv0 + # Extract the result from the tuple. + cg.create_load_const(0), + cg.create_binary_subscr(), + ] + ) + # Stack: ..., result + + # --- Result: keep on stack, overwrite/append to fv[0], or discard --- + if analysis.result_on_stack: + tx.push(UnknownVariable()) + elif analysis.result_var: + cg.extend_output( + [ + *create_copy(fv_depth), + cg.create_load_const(0), + cg.create_binary_subscr(), + # Stack: ..., result, fv0 + ] + ) + if analysis.result_var in existing_vars: + cg.extend_output( + [ + cg.create_load_const(existing_vars[analysis.result_var]), + create_instruction("STORE_SUBSCR"), + # fv0[idx] = result + ] + ) + else: + cg.extend_output( + [ + *create_swap(2), + *cg.create_list_append(), + create_instruction("POP_TOP"), + ] + ) + else: + cg.extend_output([create_instruction("POP_TOP")]) + + # Stack: cells, [frame_values], *(non-popped stack) + tx.output.add_output_instructions(cg.get_instructions()) + + # --- Step 8: Create resume function chain --- + resume_inst = tx.instructions[analysis.end_ip] + tx.output.add_output_instructions( + tx.create_call_resume_at(resume_inst, all_stack_locals_metadata) + ) + + tx.instruction_pointer = None + + +def _build_comprehension_fn( + tx: InstructionTranslatorBase, + analysis: ComprehensionAnalysis, + start_ip: int, + stack_pops: int, + stack_pops_null_mask: list[bool], + nonnull_count: int, + meta: StackLocalsMetadata, +) -> tuple[types.CodeType, str]: + """Build a synthetic function wrapping comprehension bytecode. + + Uses the same calling convention as resume functions created by + create_resume / ContinueExecutionCache.generate: the first two args + are __nested_resume_fns and __nested_frame_values (ignored here), + followed by stack items and live locals. + + Returns (code, name) where name is the global name for the function. + """ + from .bytecode_transformation import transform_code_object + from .eval_frame import skip_code + from .resume_execution import CO_VARARGS, CO_VARKEYWORDS + + # Args follow frame_values layout: locals first, then stack_pops items + # (appended to end of frame_values[0] by the caller). + # codegen_call_resume unpacks frame_values[0] as positional args. + argnames = tuple(k for k in meta.locals_names if k not in tx.cell_and_freevars()) + args = ( + ["__nested_resume_fns", "__nested_frame_values"] + + list(argnames) + + [f"___stack{i}" for i in range(nonnull_count)] + ) + + freevars = tuple( + sorted(list(tx.f_code.co_cellvars or []) + list(tx.f_code.co_freevars or [])) + ) + + lineno = tx.lineno if tx.lineno is not None else tx.f_code.co_firstlineno + fn_name = unique_id(f"__comprehension_{tx.f_code.co_name}_at_{lineno}") + + comprehension_body_vars = ( + analysis.iterator_vars + + analysis.walrus_vars + + ([analysis.result_var] if analysis.result_var else []) + + analysis.captured_vars + ) + + def update(instructions: list[Instruction], code_options: dict[str, Any]) -> None: + code_options["co_name"] = fn_name + if sys.version_info >= (3, 11): + code_options["co_qualname"] = fn_name + code_options["co_firstlineno"] = lineno + code_options["co_cellvars"] = () + code_options["co_freevars"] = freevars + code_options["co_argcount"] = len(args) + code_options["co_posonlyargcount"] = 0 + code_options["co_kwonlyargcount"] = 0 + code_options["co_varnames"] = tuple( + args + [v for v in comprehension_body_vars if v not in args] + ) + code_options["co_flags"] = code_options["co_flags"] & ~( + CO_VARARGS | CO_VARKEYWORDS + ) + + prefix: list[Instruction] = [] + if freevars: + prefix.append(create_instruction("COPY_FREE_VARS", arg=len(freevars))) + prefix.append(create_instruction("RESUME", arg=0)) + + # Push stack_pops items onto operand stack so the comprehension + # bytecode finds them where it expects (iterator + saved vars). + # NULL positions get PUSH_NULL, non-null get LOAD_FAST. + # Items were appended to frame_values[0] in TOS-first order, + # so load in reverse to reconstruct the original stack layout. + nonnull_i = nonnull_count - 1 + for i in range(stack_pops): + if stack_pops_null_mask[i]: + prefix.append(create_instruction("PUSH_NULL")) + else: + prefix.append( + create_instruction("LOAD_FAST", argval=f"___stack{nonnull_i}") + ) + nonnull_i -= 1 + + comp_insts = _copy_comprehension_bytecode(tx, start_ip, analysis.end_ip) + + # Epilogue: ensure result is on stack, pack walrus vars, return. + epilogue: list[Instruction] = [] + if not analysis.result_on_stack: + if analysis.result_var: + epilogue.append( + create_instruction("LOAD_FAST", argval=analysis.result_var) + ) + else: + epilogue.append(create_instruction("LOAD_CONST", argval=None)) + if analysis.walrus_vars: + for var_name in analysis.walrus_vars: + epilogue.append(create_instruction("LOAD_FAST", argval=var_name)) + epilogue.append( + create_instruction( + "BUILD_TUPLE", + arg=1 + len(analysis.walrus_vars), + ) + ) + epilogue.append(create_instruction("RETURN_VALUE")) + + instructions[:] = prefix + comp_insts + epilogue + + new_code, _ = transform_code_object(tx.f_code, update) + skip_code(new_code) + + # Install as global + tx.output.install_resume_function_global(fn_name, new_code, tx.f_globals) + + return new_code, fn_name + + +def _copy_comprehension_bytecode( + tx: InstructionTranslatorBase, start_ip: int, end_ip: int +) -> list[Instruction]: + """Copy comprehension bytecode instructions, updating jump targets.""" + inst_map: dict[Instruction, Instruction] = {} + copied_insts: list[Instruction] = [] + + for ip in range(start_ip, end_ip): + original_inst = tx.instructions[ip] + copied_inst = copy.copy(original_inst) + copied_inst.exn_tab_entry = None + inst_map[original_inst] = copied_inst + copied_insts.append(copied_inst) + + for copied_inst in copied_insts: + if copied_inst.target is not None and copied_inst.target in inst_map: + copied_inst.target = inst_map[copied_inst.target] + + return copied_insts + + +def maybe_setup_comprehension_speculation( + tx: InstructionTranslatorBase, inst: Instruction +) -> bool: + """ + Handle comprehension start for Python 3.12+ BUILD_LIST/BUILD_MAP with argval 0. + Returns True if a graph break was triggered and the caller should return early. + """ + if not (sys.version_info >= (3, 12) and inst.argval == 0): + return False + + if not _is_comprehension_start(tx): + return False + + can_speculate = ( + all(b.can_restore() for b in tx.block_stack) + and not tx.one_graph + and not tx.error_on_graph_break + and not tx.is_tracing_resume_prologue + and not tx.active_generic_context_managers + and tx.output.current_tracer.parent is None + ) + + if can_speculate and tx.parent is not None: + can_speculate = tx._can_speculate_comprehension_nested() + # Only set up speculation at depth 0 (outermost comprehension) + if can_speculate and tx._comprehension_depth == 0: + speculation = tx.speculate() + if speculation.failed(tx): + _handle_comprehension_graph_break(tx, inst) + return True + tx.current_speculation = speculation + end_for_ip = _find_comprehension_end_for_ip(tx) + if end_for_ip < 0: + raise AssertionError("failed to find END_FOR for comprehension") + tx._comprehension_end_for_ips.add(end_for_ip) + tx._comprehension_depth += 1 + return False diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/comptime.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/comptime.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c5c71da86bc0b7c6e5a66f3ec70da906991a78 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/comptime.py @@ -0,0 +1,439 @@ +""" +This module provides the public comptime interface to TorchDynamo, enabling users to execute +arbitrary Python code during symbolic evaluation of their programs. + +The comptime interface allows inspection and modification of TorchDynamo's compilation +process while it is running. This can be useful for: + +- Debugging compilation issues +- Inspecting intermediate state +- Adding custom guards or graph breaks +- Analyzing symbolic shapes and values + +Example usage: + + import torch + from torch._dynamo.comptime import comptime + + def my_model(x): + # Print the compile-time known information about x + comptime.print(x) + + # Print the current FX graph being constructed + comptime.print_graph() + + # Force a value to be treated as static + if comptime(lambda ctx: ctx.get_local("x").is_dynamic()): + comptime.force_static(x) + + # Add a manual graph break + comptime.graph_break() + +Note: While this API provides significant flexibility, it intentionally avoids +exposing internal implementation details of TorchDynamo to maintain compatibility +across versions. +""" + +import builtins +import dis +import time +import traceback +from collections.abc import Callable +from typing import Any, TextIO + +import torch +from torch._dynamo.symbolic_convert import InstructionTranslatorBase +from torch._dynamo.variables.base import VariableTracker +from torch._subclasses.fake_tensor import FakeTensor +from torch.fx.experimental.symbolic_shapes import free_symbols + +from .exc import unimplemented +from .variables import CellVariable +from .variables.tensor import SymNodeVariable + + +class ComptimeVar: + """ + A ComptimeVar represents a Python value, at some particular point + in time, in the Python code we are symbolically evaluating with + torchdynamo. This must be distinguished from a runtime value, as + at compile-time there are some properties of the variable we + do not know (for example, if the ComptimeVar represents a Tensor, + we only know metadata about the tensor; we do NOT know what the + actual data in the Tensor is.) + """ + + def __init__(self, v: VariableTracker) -> None: + self.__variable = v + + def as_proxy(self) -> VariableTracker | list[VariableTracker]: + """ + Returns an fx.Proxy (or tuple/list of fx.Proxy) representing + this variable in the FX graph we are assembling to pass + to the user compiler. + + This method only works for variables we actually track in + the FX graph, aka Tensors (and ints, if you are compiling + with dynamic shapes). In particular, if you have a list + or tuple of tensors, you will get a list/tuple of proxies + (not a single proxy representing the entire list/tuple). + """ + return self.__variable.as_proxy() + + def is_proxy(self) -> bool: + """ + Returns True if as_proxy() would succeed. + """ + return self.__variable.is_proxy() + + def as_fake(self) -> FakeTensor | torch.SymInt: + """ + Returns a "fake" value (either a FakeTensor or a SymInt) + representing the variable in question. This only works + for variables that denote Tensor or int. You can use + this to query metadata; e.g., v.as_fake().size(0) will + tell you the compile-time known size of the tensor. + + WARNING: Do NOT mutate the returned tensor. + """ + return self.__variable.as_proxy().node.meta["example_value"] + + def size(self, dim: int | None = None) -> int | torch.SymInt: + """ + Returns the size of the tensor (if dim is None) or the size + at the dimension dim. The returned size may be a SymInt. + """ + return self.as_fake().size(dim) # type: ignore[union-attr, return-value] + + def python_type(self) -> type: + """ + Returns what type(v) would have returned for the variable + at compile time. + """ + return self.__variable.python_type() + + def as_python_constant(self) -> Any: + """ + Returns the Python value this variable would have, but only if it is + completely known at compile-time (e.g., it is constant). + + WARNING: Do NOT mutate the returned constant. The returned constant + may or may not correspond to the actual value this variable may take + on at runtime; for example, if the variable in question is a constant + list, we may return a copy of that list. + """ + return self.__variable.as_python_constant() + + def is_python_constant(self) -> bool: + """ + Returns True if as_python_constant would succeed. + """ + return self.__variable.is_python_constant() + + def is_dynamic(self) -> bool: + if isinstance(self.__variable, SymNodeVariable): + fs = free_symbols(self.__variable.sym_num) + return bool(fs) + return False + + def force_static(self) -> None: + """ + Forces that a value is static, inducing a guard on its specific value + """ + if isinstance(self.__variable, SymNodeVariable): + self.__variable.evaluate_expr() + elif self.__variable.is_python_constant(): + # TODO: Maybe complain if this isn't a int/bool/float variable + pass + else: + raise AssertionError( + f"cannot force {self.__variable} ({type(self.__variable)}) static" + ) + + def _i_will_not_complain_if_bc_breaks_VariableTracker(self) -> VariableTracker: + """ + Returns the internal data structure VariableTracker that Dynamo uses + to represent variables at compile time. There are no BC guarantees on + this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if you rely on + it. + """ + return self.__variable + + def __repr__(self) -> str: + return self.__variable.debug_repr() + + # TODO: API for adding a custom guard + + +class ComptimeContext: + """ + This context class provides access to a public API for Dynamo's internals. + If there is something here you would find useful that is missing, please + file a feature request at https://github.com/pytorch/pytorch/ + """ + + def __init__(self, tx: InstructionTranslatorBase) -> None: + self.__tx = tx + + def get_local(self, name: str, *, stacklevel: int = 0) -> ComptimeVar: + """ + Retrieve the compile-time known information about a local. + """ + tx = self.__get_tx(stacklevel) + var = tx.symbolic_locals[name] + + # Auto-dereference when accessing cell locals in python. + if isinstance(var, CellVariable): + return ComptimeVar(tx.output.side_effects.load_cell(var)) + + return ComptimeVar(var) + + def graph_break(self, msg: str = "ComptimeContext.graph_break") -> None: + """ + Manually trigger a graph break + """ + unimplemented( + gb_type="ComptimeContext graph break", + context=msg, + explanation=f"Manually triggered ComptimeContext graph break with message {msg}.", + hints=[], + ) + + def graph(self) -> torch.fx.Graph: + """ + Retrieve the partially constructed FX graph that would be + passed to the user compiler after compilation. + """ + return self.__tx.output.graph + + def assert_static(self, val: ComptimeVar) -> None: + """ + Asserts that the int is static (and not dynamic, per dynamic shapes) + """ + if val.is_dynamic(): + raise AssertionError( + "expected static but got dynamic (run with TORCH_LOGS=dynamic for more info)" + ) + + def print_graph(self, *, verbose: bool = True, file: TextIO | None = None) -> None: + """ + Print the partially constructed FX graph that would be passed + to the user compiler after compilation. + """ + print( + self.__tx.output.graph.python_code("self", verbose=verbose).src, file=file + ) + + def parent(self) -> "ComptimeContext": + return ComptimeContext(self.__tx.parent) # type: ignore[arg-type] + + def __get_tx(self, stacklevel: int) -> Any: + tx = self.__tx + # pyrefly: ignore [bad-assignment, non-convergent-recursion] + for _ in range(stacklevel): + tx = tx.parent # type: ignore[assignment] + return tx + + def print(self, val: Any, *, file: TextIO | None = None) -> None: + print(repr(val), file=file) + + def print_disas(self, *, file: TextIO | None = None, stacklevel: int = 0) -> None: + """ + Print the current series of opcodes being executed (not including + parent frames), including where you are in the particular opcode + stream. + """ + tx = self.__get_tx(stacklevel) + print( + dis.Bytecode( + tx.f_code, + current_offset=tx.instructions[tx.instruction_pointer].offset, + ).dis(), + file=file, + ) + + def print_value_stack( + self, *, file: TextIO | None = None, stacklevel: int = 0 + ) -> None: + """ + Print the current Python value stack. Note that this is NOT the same + as the traceback; use print_bt() to print that. Note that at + stacklevel=0, this will typically be empty, as comptime cannot + currently be used in an expression context where there would be + intermediates on the stack. If you would find this useful, please + file a bug at https://github.com/pytorch/pytorch/ + + NB: Stack grows downwards in our print + """ + tx = self.__get_tx(stacklevel) + for s in tx.stack: + print(f"- {s.debug_repr()}", file=file) + + def print_locals(self, *, file: TextIO | None = None, stacklevel: int = 0) -> None: + """ + Print all of the locals available in the current context. + By default this view is very limited; you can get more information + about any individual local using get_local(). + """ + tx = self.__get_tx(stacklevel) + for k, v in tx.symbolic_locals.items(): + print(f"{k} = {v.debug_repr()}", file=file) + + def print_bt(self, *, file: TextIO | None = None, stacklevel: int = 0) -> None: + """ + Print the user code backtrace, starting at the beginning of the + frame Dynamo started evaluating. Note that this MAY NOT go all + the way to the torch.compile invocation, as we may have done + a graph break and are compiling an intermediate frame as the + starting point. If you think the other behavior would be better, + file a bug at https://github.com/pytorch/pytorch/ + """ + stack = [] + tx = self.__get_tx(stacklevel) + while tx is not None: + stack.append(tx.frame_summary()) + tx = getattr(tx, "parent", None) + print( + "".join(traceback.StackSummary.from_list(reversed(stack)).format()), + file=file, + ) + + def print_guards(self, *, file: TextIO | None = None) -> None: + """ + Print the currently installed guards for the Dynamo context. + This does NOT include guards associated with variables that + may or may not be installed in the future if those variables + are used. + """ + # TODO: improve print format, current guard format is extremely + # verbose + print( + "\n".join(f"{repr(guard)}" for guard in sorted(self.__tx.output.guards)), + file=file, + ) + + def _i_will_not_complain_if_bc_breaks_InstructionTranslator( + self, + ) -> InstructionTranslatorBase: + """ + Returns the internal data structure InstructionTranslator that Dynamo + uses to track state of symbolic evaluation. There are no BC + guarantees on this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if + you rely on it. + """ + return self.__tx + + def sleep(self, sec: int | float) -> None: + time.sleep(sec) + + +class _Comptime: + @staticmethod + def __call__( + fn: Callable[[ComptimeContext], Any], + fallback_fn: Callable[[], Any] = lambda: None, + ) -> Any: + """fn gets called at compile time in TorchDynamo, calls fallback_fn otherwise""" + fallback_fn() + + # Convenience wrappers that are more compact to use + + @staticmethod + def graph_break() -> None: + comptime(lambda ctx: ctx.graph_break()) + + @staticmethod + def print(e: Any) -> None: + comptime(lambda ctx: ctx.print(ctx.get_local("e")), lambda: print(e)) + + @staticmethod + def print_graph() -> None: + comptime(lambda ctx: ctx.print_graph()) + + @staticmethod + def print_disas(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_disas( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + @staticmethod + def print_value_stack(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_value_stack( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + # This is a more useful variant of print_value_stack that can be used + # in an expression context; e.g., x + print_value_stack_and_return(y + z), + # you will see x on the stack prior to the addition operation + @staticmethod + def print_value_stack_and_return(e: Any, *, stacklevel: int = 0) -> Any: + comptime( + lambda ctx: ctx.print_value_stack( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + return e + + @staticmethod + def print_locals(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_locals( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + @staticmethod + def print_bt(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_bt( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + @staticmethod + def print_guards() -> None: + comptime(lambda ctx: ctx.print_guards()) + + @staticmethod + def assert_static(val: Any) -> None: + comptime(lambda ctx: ctx.assert_static(ctx.get_local("val"))) + + @staticmethod + def force_static(val: Any) -> None: + comptime(lambda ctx: ctx.get_local("val").force_static()) + + @staticmethod + def breakpoint() -> None: + """ + Like pdb breakpoint(), but drop into pdb whenever this line + of code is compiled by dynamo. Use it by putting + this in your model code:: + + from torch._dynamo.comptime import comptime + + comptime.breakpoint() + + And then, inside pdb, you can access 'ctx' to query things + about the compilation context:: + + (Pdb) !ctx.print_bt() + (Pdb) !ctx.print_locals() + (Pdb) p ctx.get_local("attention").as_fake() + """ + + def inner(inner_ctx: ComptimeContext) -> None: + ctx = inner_ctx.parent() # noqa: F841 + builtins.breakpoint() + + comptime(inner) + + @staticmethod + def sleep(sec: int | float) -> None: + comptime(lambda ctx: ctx.sleep(ctx.get_local("sec").as_python_constant())) + + +comptime = _Comptime() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/config.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6759a6a1d9486d2bf8110df949a766ad00d1c758 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/config.py @@ -0,0 +1,942 @@ +""" +Configuration module for TorchDynamo compiler and optimization settings. + +This module contains various configuration flags and settings that control TorchDynamo's +behavior, including: + +- Runtime behavior flags (e.g., guard settings, specialization options) +- Debugging and development options +- Performance tuning parameters +- Feature toggles for experimental features +""" + +import getpass +import os +import sys +import sysconfig +import tempfile +from collections.abc import Callable +from os.path import abspath, dirname +from typing import Any, Literal, TYPE_CHECKING + +from torch._environment import is_fbcode +from torch.utils._config_module import Config, get_tristate_env, install_config_module + + +# to configure logging for dynamo, aot, and inductor +# use the following API in the torch._logging module +# torch._logging.set_logs(dynamo=, aot=, inductor) +# or use the environment variable TORCH_LOGS="dynamo,aot,inductor" (use a prefix + to indicate higher verbosity) +# see this design doc for more detailed info +# Design doc: https://docs.google.com/document/d/1ZRfTWKa8eaPq1AxaiHrq4ASTPouzzlPiuquSBEJYwS8/edit# +# the name of a file to write the logs to +# [@compile_ignored: debug] +log_file_name: str | None = None + +# [@compile_ignored: debug] Verbose will print full stack traces on warnings and errors +verbose = os.environ.get("TORCHDYNAMO_VERBOSE", "0") == "1" + +# [@compile_ignored: runtime_behaviour] verify the correctness of optimized backend +verify_correctness = False + +# Override backend for specific graphs (for debugging/bisecting). +# Format: "filter1:backend1;filter2:backend2;..." where filter can be: +# - Individual IDs: "0,5,10" +# - Ranges: "10-20" (inclusive) +# - Comparisons: ">10", ">=10", "<5", "<=5" +# Backends can be: "eager", "aot_eager", "inductor", etc. +# Examples: +# ">10:eager" - Run graphs with frame_id > 10 in dynamo eager backend +# "<=5:aot_eager;>5:inductor" - First 6 graphs use aot_eager, rest use inductor +# [@compile_ignored: debug] +debug_backend_override: str = os.environ.get("TORCH_COMPILE_OVERRIDE_BACKENDS", "") + +# Override inductor config for specific graphs (for debugging/bisecting). +# Format: "filter1:config1;filter2:config2;..." where filter uses same syntax as +# debug_backend_override, and config is "key=value" or "key=value,key2=value2". +# Examples: +# "0-5:triton.cudagraph_skip_dynamic_graphs=False" - Disable skip for graphs 0-5 +# ">10:triton.cudagraphs=False" - Disable cudagraphs for graphs > 10 +# [@compile_ignored: debug] +debug_inductor_config_override: str = os.environ.get( + "TORCH_COMPILE_OVERRIDE_INDUCTOR_CONFIGS", "" +) + +# Override dynamo config for specific graphs (for debugging/bisecting). +# Format: "filter1:config1;filter2:config2;..." where filter uses same syntax as +# debug_backend_override, and config is "key=value" or "key=value,key2=value2". +# Examples: +# "0-5:specialize_float=True" - Specialize floats for graphs 0-5 +# ">10:automatic_dynamic_shapes=False" - Disable dynamic shapes for graphs > 10 +# [@compile_ignored: debug] +debug_dynamo_config_override: str = os.environ.get( + "TORCH_COMPILE_OVERRIDE_DYNAMO_CONFIGS", "" +) + +# Validate that fake_fn and real_fn in @leaf_function decorators produce outputs +# with matching shapes and dtypes in eager mode. Helps catch mismatches early. +# Disabled by default to avoid runtime overhead. +# [@compile_ignored: debug] +leaf_function_validate_outputs = False + +# Check for escaped gradients in @leaf_function. When a leaf_function closes over +# a tensor with requires_grad=True, gradients won't flow back to it. This check +# walks the autograd graph to detect such cases and raises an error. +# Disabled by default to avoid runtime overhead. Enable for debugging. +# [@compile_ignored: debug] +leaf_function_check_escaped_gradients = False + +# need this many ops to create an FX graph (deprecated: not used) +minimum_call_count = 1 + +# turn on/off DCE pass (deprecated: always true) +dead_code_elimination = None + +# Enable or disable side effect replay after graph execution. +# When False, mutations to Python objects (lists, dicts, attributes) won't be +# replayed after the compiled graph runs. This can cause correctness issues +# if your code depends on these mutations being visible. This should probably +# never be False by default. At the moment, only export will need it. +replay_side_effects = True + +# Generate Python code strings for compiled graph calls. +# When enabled, the generated Python code will be stored in output_pycode. +# [@compile_ignored: debug] +generate_pycode = False + +# Configure side effect warning level +# If `info` (default): allow side effects and log to TORCH_LOGS="side_effects" and tlparse +# If `silent`, we allow side effects, no logs are made. +# If `warn`, we allow side effects but issue warnings +# If `error`, we error on side effects +# NOTE: it is NOT safe to change this config during compilation! +side_effect_replay_policy = "info" + +# disable (for a function) when cache reaches this size + +# controls the maximum number of cache entries with a guard on same ID_MATCH'd +# object. It also controls the maximum size of cache entries if they don't have +# any ID_MATCH'd guards. +# [@compile_ignored: runtime_behaviour] +recompile_limit = 8 + +# [@compile_ignored: runtime_behaviour] safeguarding to prevent horrible recomps +accumulated_recompile_limit = 256 + +skip_code_recursive_on_recompile_limit_hit: bool = Config( + default=True, deprecated=True, deprecation_message="does not do anything" +) + +# raise a hard error if cache limit is hit. If you are on a model where you +# know you've sized the cache correctly, this can help detect problems when +# you regress guards/specialization. This works best when recompile_limit = 1. +# This flag is incompatible with: suppress_errors. +# [@compile_ignored: runtime_behaviour] +fail_on_recompile_limit_hit = False + +cache_size_limit: int = Config(alias="torch._dynamo.config.recompile_limit") +accumulated_cache_size_limit: int = Config( + alias="torch._dynamo.config.accumulated_recompile_limit" +) + +skip_code_recursive_on_cache_limit_hit: bool = Config( + alias="torch._dynamo.config.skip_code_recursive_on_recompile_limit_hit", + deprecated=True, + deprecation_message="does not do anything", +) + +fail_on_cache_limit_hit: bool = Config( + alias="torch._dynamo.config.fail_on_recompile_limit_hit" +) + +# whether or not to specialize on int inputs. This only has an effect with +# dynamic_shapes; when dynamic_shapes is False, we ALWAYS specialize on int +# inputs. Note that assume_static_by_default will also cause ints to get +# specialized, so this is mostly useful for export, where we want inputs +# to be dynamic, but accesses to ints should NOT get promoted into inputs. +specialize_int = False + +# Whether or not to specialize on float inputs. Dynamo will always promote +# float inputs into Tensor inputs, but at the moment, backends inconsistently +# support codegen on float (this is to be fixed). +specialize_float = False + +# Max ops per ComputedLazyConstantVariable chain before realizing under guards; 0 disables +computed_lazy_constant_max_nodes = 64 + +# legacy config, does nothing now! +dynamic_shapes = True + +use_lazy_graph_module = ( + os.environ.get("TORCH_COMPILE_USE_LAZY_GRAPH_MODULE", "1") == "1" +) + +# This is a temporarily flag, which changes the behavior of dynamic_shapes=True. +# When assume_static_by_default is True, we only allocate symbols for shapes marked dynamic via mark_dynamic. +# NOTE - this flag can be removed once we can run dynamic_shapes=False w/ the mark_dynamic API +# see [Note - on the state of mark_dynamic] +assume_static_by_default = True + +# Internal: Shape specification patched during tracing by enter_exit_hooks. +# Set via torch.compile(dynamic_shapes=...), not directly by users. +_dynamic_shapes_spec = None + +# This flag changes how dynamic_shapes=True works, and is meant to be used in conjunction +# with assume_static_by_default=True. +# With this flag enabled, we always compile a frame as fully static for the first time, and, if we fail +# any guards due to wobbles in shape, we recompile with *all* the wobbled shapes as being marked dynamic. +automatic_dynamic_shapes = ( + os.environ.get("TORCH_DYNAMO_AUTOMATIC_DYNAMIC_SHAPES", "1") == "1" +) + +# Valid options: "dynamic", "unbacked" +automatic_dynamic_shapes_mark_as: Literal["dynamic", "unbacked"] = "dynamic" + +# When True, adds exclusion guards for tensor dims and scalars that transition +# from static to dynamic via automatic_dynamic_shapes. +# +# Invariant: when enabled, automatic_dynamic recompilation preserves graph +# selection — inputs that matched a previous static cache entry will continue +# to use that entry, not be intercepted by a newer dynamic entry. This holds +# as long as recompilations are caused solely by the same variable being +# observed with different static values (progressive dynamism). A recompilation +# triggered by a different reason (e.g., a guard failure unrelated to shape +# transitions) will clear the exclusion state for that entry. +# +# Mechanism: the exclusion guard rejects inputs matching the prior static +# graph's sizes, so those inputs fall through to the more specialized static +# graph instead of being captured by the newer dynamic graph. +# +# Scope: applies only to graph-input-level dimension and scalar transitions. +# Does NOT handle data-dependent branching (if x.size(0) > k), graph breaks, +# or other recompilation triggers where no dimension actually transitions. +automatic_dynamic_exclusion_guard = False + +# log graph in/out metadata +# This is only turned on for export today since we +# know we are tracing a flat callable. later, this +# can extended to other use cases as well. +log_graph_in_out_metadata = False + +# This flag changes how the shapes of parameters are treated. +# If this flag is set to True, then the shapes of torch.nn.Parameter as well as of torch.Tensor are attempted to be dynamic +# If this flag is set to False, then the shapes of torch.nn.Parameter are assumed to be static, +# while the shapes of torch.Tensor are assumed to be dynamic. +force_parameter_static_shapes = True + +# This flag ensures that the shapes of a nn module are always assumed to be static +# If the flag is set to True, then the shapes of a nn.module are assumed to be static +# If the flag is set to False, then the shapes of a nn.module can be dynamic +force_nn_module_property_static_shapes = True + +# Typically, if you mark_dynamic a dimension, we will error if the dimension +# actually ended up getting specialized. This knob changes the behavior so +# that we don't error at all. This is helpful for our CI where I'm using a +# heuristic to mark batch dimensions as dynamic and the heuristic may get it +# wrong. +allow_ignore_mark_dynamic = False + +# Set this to False to assume nn.Modules() contents are immutable (similar assumption as freezing) +guard_nn_modules = True + +# Uses CPython internal dictionary tags to detect mutation. There is some +# overlap between guard_nn_modules_using_dict_tags and guard_nn_modules flag. +# guard_nn_modules unspecializes the nn module instance and adds guard for each +# relevant member of the nn modules. On the other hand, +# guard_nn_modules_using_dict_tags specializes on each nn module instance but +# uses low overhead dict version matching to detect mutations, obviating the +# need to guard on members of the nn modules. With +# guard_nn_modules_using_dict_tags, the guard_nn_modules is not really required +# but kept around for debugging and discussing unspecializing nn module +# variables. +# TODO(janimesh, voz): Remove both of these flags (or at least guard_nn_modules) +# once we have reached stability for the guard_nn_modules_using_dict_tags. +guard_nn_modules_using_dict_tags = True + +# Flag to enable preparation for graph freezing, so that the named parameters and +# buffers are passed as params_flat in tracing context by AOT autograd. +# Non-Inductor backends can use this list for graph freezing. +prepare_freezing = os.environ.get("TORCHDYNAMO_PREPARE_FREEZING", "0") == "1" + +# NOTE this has been deprecated, it does nothing now. +traceable_tensor_subclasses: set[type[Any]] = set() + +# If a tensor subclass is put into this set, Dynamo will model its instances in +# a very conservative and limited way (most likely causing lots of graph breaks +# if one apply tensor ops on these instances). This is useful if you encounter +# internal compiler errors from Dynamo which are caused by tensor subclasses, +# and you are willing to tolerate potential graph breaks rather than hard error. +nontraceable_tensor_subclasses: set[type[Any]] = set() + +# Suppress errors in torch._dynamo.optimize, instead forcing a fallback to eager. +# This is a good way to get your model to work one way or another, but you may +# lose optimization opportunities this way. Devs, if your benchmark model is failing +# this way, you should figure out why instead of suppressing it. +# This flag is incompatible with: fail_on_recompile_limit_hit. +suppress_errors = bool(os.environ.get("TORCHDYNAMO_SUPPRESS_ERRORS", False)) + +# Record and write an execution record of the current frame to a file +# if an exception is encountered +# @compile_ignored[debug] +replay_record_enabled = os.environ.get("TORCH_COMPILE_REPLAY_RECORD", "0") == "1" + +# Rewrite assert statement in python with torch._assert +rewrite_assert_with_torch_assert = True + +# Disable dynamo +disable = os.environ.get("TORCH_COMPILE_DISABLE", "0") == "1" + +# [@compile_ignored: runtime_behaviour] Get a cprofile trace of Dynamo +cprofile = os.environ.get("TORCH_COMPILE_CPROFILE", False) + +# Enable Dynamo profiler. When enabled, prints pstats output showing +# time spent tracing each user function. Set to True to enable, or set to a +# file path to save the .prof file for snakeviz. +# [@compile_ignored: runtime_behaviour] +dynamo_profiler: bool | str = os.environ.get("TORCH_COMPILE_DYNAMO_PROFILER", False) + +# Legacy config, does nothing now! +skipfiles_inline_module_allowlist: dict[Any, Any] = {} +"""Allowlist of inline modules to skip during compilation. + +Legacy configuration that previously controlled which modules could be +inlined during tracing. This configuration is deprecated and no longer used. + +:type: dict[Any, Any] +:default: {} + +.. deprecated:: + This configuration is deprecated and does nothing now. + +.. note:: + DEPRECATED: This setting has no effect on current behavior. +""" + +# If a string representing a PyTorch module is in this ignorelist, +# the `allowed_functions.is_allowed` function will not consider it +# when creating a list of PyTorch functions that will appear in +# FX IR. +allowed_functions_module_string_ignorelist = { + "torch.distributions", + "torch.testing", + "torch._refs", + "torch._prims", + "torch._decomp", +} + +# Debug Flag to try minifier at different stages. Possible values are {None, "aot", "dynamo"} +# None - Minifier is switched off +# dynamo - Runs minifier on the TorchDynamo produced graphs, if compilation fails +# aot - Runs minifier on the Aot Autograd produced graphs, if compilation fails +# [@compile_ignored: debug] +repro_after = os.environ.get("TORCHDYNAMO_REPRO_AFTER", None) + +# Compiler compilation debug info +# 1: Dumps the original graph out to repro.py if compilation fails +# 2: Dumps a minifier_launcher.py if compilation fails. +# 3: Always dumps a minifier_launcher.py. Good for segfaults. +# 4: Dumps a minifier_launcher.py if the accuracy fails. +# [@compile_ignored: debug] +repro_level = int(os.environ.get("TORCHDYNAMO_REPRO_LEVEL", 2)) + +# By default, we try to detect accuracy failure by running both forward +# and backward of a torchdynamo produced graph (if you are using repro_after +# 'dynamo'). This setting forces us to only test the forward graph and +# not the backward graph. This can be helpful if you're trying to debug +# an inference only problem, but the minifier seems to be choking on the +# backwards step +# TODO: Detect this situation automatically so the user doesn't need +# to manually configure this +# [@compile_ignored: debug] +repro_forward_only = os.environ.get("TORCHDYNAMO_REPRO_FORWARD_ONLY") == "1" + +# The tolerance we should use when testing if a compiled graph +# has diverged so that we should treat it as an accuracy failure +# [@compile_ignored: debug] +repro_tolerance = 1e-3 + + +# Whether to ignore non-floating point values when checking accuracy. +# Checking accuracy of non-floating point values such as boolean tensors +# can lead to false positives. +# [@compile_ignored: debug] +repro_ignore_non_fp = os.environ.get("TORCHDYNAMO_REPRO_IGNORE_NON_FP") == "1" + +# If True, when testing if two models are the same, we will test them against +# a third fp64 reference and only report a problem if the RMSE relative to the +# fp64 is greater. However, this will use more memory; you may disable this +# if memory usage is too high. +# [@compile_ignored: runtime_behaviour] +same_two_models_use_fp64 = True + +# Not all backends support scalars. Some calls on torch.Tensor (like .item()) return a scalar type. +# When this flag is set to False, we introduce a graph break instead of capturing. +# This requires dynamic_shapes to be True. +capture_scalar_outputs = os.environ.get("TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS") == "1" + +# Not all backends support operators that have dynamic output shape (e.g., +# nonzero, unique). When this flag is set to False, we introduce a graph +# break instead of capturing. This requires dynamic_shapes to be True. +# If you set this to True, you probably also want capture_scalar_outputs +# (these are separated for historical reasons). +capture_dynamic_output_shape_ops = ( + os.environ.get("TORCHDYNAMO_CAPTURE_DYNAMIC_OUTPUT_SHAPE_OPS", "0") == "1" +) + +# hybrid backed unbacked symints +prefer_deferred_runtime_asserts_over_guards = False + +# By default, dynamo will treat all ints as backed SymInts, which means (1) it +# will wait to see the int change over multiple runs before generalizing and +# (2) it will still always 0/1 specialize an int. When true, this knob +# forces dynamo to treat _length_per_key and _offset_per_key on +# KeyedJaggedTensor from torchrec as size-like unbacked SymInts, so that +# they (1) generalize immediately and (2) unsoundly never compare equal to +# 0/1. This is not on by default as AOTAutograd/Inductor cannot currently +# compile this code; however, this can be useful for export. +force_unspec_int_unbacked_size_like_on_torchrec_kjt = False + +# Currently, Dynamo will always specialize on int members of NN module. +# However, there could be cases where this is undesirable, e.g., when tracking +# step count leading to constant recompilation and eventually eager fallback. +# Setting this flag to True will allow int members to be potentially unspecialized +# through dynamic shape mechanism. +# Defaults to False for BC. +allow_unspec_int_on_nn_module = False + +# Specify how to optimize a compiled DDP module. The flag accepts a boolean +# value or a string. There are 3 modes. +# 1. "ddp_optimizer" (or True): with "ddp_optimizer", Dynamo will automatically +# split model graph into pieces to match DDP bucket sizes to allow DDP +# comm/compute overlap. +# 2. "python_reducer" (experimental): this optimization requires the usage +# of compiled_autograd. With "python_reducer", DDP will disable the C++ reducer +# and use the Python reducer to allow compiled_autograd to trace the +# communication and allow comm/compute overlap without graph-breaks. +# 3. "no_optimization" (or False): Dynamo won't split the model graph, nor +# will Python reducer be used. With this mode, there will be no graph-breaks +# and the original DDP C++ reducer will be used. There will no comm/compute +# overlap. This mode CANNOT be used with compiled_autograd. +# Note that to avoid breaking the existing usage, mode 1 and mode 4 can be +# specified with a boolean value. True is using ddp_optimizer and False is +# no optimization. +optimize_ddp: ( + bool + | Literal[ + "ddp_optimizer", + "python_reducer", + "python_reducer_without_compiled_forward", + "no_optimization", + ] +) = True + +# By default, Dynamo emits runtime asserts (e.g. torch._check) in the graph. +# In some cases those asserts could be performance costly +# E.g. torch._check(tensor[0].item() > 2) for tensor on cuda will require cuda sync. +# Setting this to True keeps them hinting to symbolic shapes engine, +# but not be emitted in the graph. +do_not_emit_runtime_asserts: bool = ( + os.environ.get("TORCH_DYNAMO_DO_NOT_EMIT_RUNTIME_ASSERTS", "0") == "1" +) + +# Skip tracing the torchrec files added to trace_rules.FBCODE_SKIP_DIRS +skip_torchrec = True + +# Don't apply most trace_rules.py rules +dont_skip_tracing = False + +# No longer used +optimize_ddp_lazy_compile = False + +# lambda guarding on object aliasing to improve opportunity for dict tag +# optimization +use_lamba_guard_for_object_aliasing = False + +# Whether to skip guarding on FSDP-managed modules +skip_fsdp_guards = True + +# Make dynamo skip guarding on hooks on nn modules +# Note: unsafe: if your model actually has hooks and you remove them, or doesn't and you add them, +# dynamo will not notice and will execute whichever version you first compiled. +skip_nnmodule_hook_guards = True + +# Make dynamo skip no tensor aliasing guard on parameters +# Note: unsafe: if you compile a function with different parameters as inputs, +# and then later pass on the same parameter as two inputs, dynamo will not +# notice and lead to incorrect result. +skip_no_tensor_aliasing_guards_on_parameters = True + +# Considers a tensor immutable if it is one of the values of a dictionary, and +# the dictionary tag is same across invocation calls. +skip_tensor_guards_with_matching_dict_tags = True + +# Skips guards on func.__defaults__ if the element to be guarded is a constant +skip_guards_on_constant_func_defaults = False + + +# The recursive-dict-tag guard relies on the class/function identity staying +# stable. We therefore assume that the following function dunder attributes +# are **never rebound** to a different object: +# +# • __code__ • __closure__ +# • __defaults__ • __kwdefaults__ +# • __annotations__ • __mro__ +# +# It is fine to mutate the objects they already point to (e.g. tweak an element +# inside __defaults__), but assignments like +# +# foo.__defaults__ = (3, 4) # REBIND - NOT SUPPORTED +# +# would invalidate the optimization. This type of rebinding is rare, so we +# assume that the rebinding never happens for guard purposes. Set the flag +# below to False only in environments where such rebinding is known to occur. +assume_dunder_attributes_remain_unchanged = True + +# Speedup guard execution of nested nn modules by recursively checking for dict +# tags to avoid full guard execution. +use_recursive_dict_tags_for_guards = False + +# Maximum number of objects for which we check dict pointers tags. This is +# useful for regional compilation. +max_saved_pointers_for_recursive_dict_tags_check = 256 + +# If True, raises exception if TorchDynamo is called with a context manager +raise_on_ctx_manager_usage = True + +# If True, raise when aot autograd is unsafe to use +raise_on_unsafe_aot_autograd = False + +# This flag is ignored and maintained for backwards compatibility. +error_on_nested_jit_trace = True + +# If true, error with a better message if we symbolically trace over a +# dynamo-optimized function. If false, silently suppress dynamo. +error_on_nested_fx_trace = True + +# If true, force dynamo compilation even when inside FX symbolic tracing. +# This allows nested compilation where the outer tracer (e.g., make_fx) can +# trace over dynamo-compiled functions. Use with error_on_nested_fx_trace=False. +force_compile_during_fx_trace = False + +# Disables graph breaking on rnn. YMMV with backends. +allow_rnn = False + +# If true, enables feature that captures PyTorch sparsity in the +# exported FX graph. This flag should become the default eventually +# and be removed, but currently provides a way to fall back to old +# graph breaking behavior. +capture_sparse_compute = True + +# If true, error if we try to compile a function that has +# been seen before. +# [@compile_ignored: runtime_behaviour] +error_on_recompile = False + +# [@compile_ignored: debug] Whether to report any guard failures (deprecated: does not do anything) +report_guard_failures = True + +# [@compile_ignored: debug] root folder of the project +base_dir = dirname(dirname(dirname(abspath(__file__)))) + +# Trace through NumPy or graphbreak +trace_numpy = True + +# Trace through torch.autograd.grad or graphbreak +trace_autograd_ops = False + +# Default NumPy dtypes when tracing with torch.compile +# We default to 64bits. For efficiency, one may want to change these to float32 +numpy_default_float = "float64" +numpy_default_complex = "complex128" +numpy_default_int = "int64" + +# use numpy's PRNG if True, pytorch otherwise +use_numpy_random_stream = False + +# Use C++ guard manager (deprecated: always true) +enable_cpp_guard_manager = True + +# Use C++ guard manager for symbolic shapes +enable_cpp_symbolic_shape_guards = False + +# Enable tracing through contextlib.contextmanager +enable_trace_contextlib = True + +# Enable tracing through unittest +enable_trace_unittest = False + +# Enable tracing LOAD_BUILD_CLASS bytecode +enable_trace_load_build_class = False + +enable_faithful_generator_behavior = Config( # type: ignore[var-annotated] + default=True, + deprecated=True, + deprecation_message="does not do anything, generators are always traced lazily", +) + +# Inline inbuilt nn modules +inline_inbuilt_nn_modules = Config( # type: ignore[var-annotated] + default=True, + justknob="pytorch/compiler:inline_inbuilt_nn_modules", + deprecated=True, + deprecation_message="does not do anything, inline_inbuilt_nn_modules is always True", +) + +# Resume tracing in nested frames if a nested graph break occurs +# Old behavior is to bubble up the graph break to the top level frame. +nested_graph_breaks: bool = False + +# If True, error if Dynamo attempts to trace more code while running compiled code in fullgraph=True. +# If Dynamo determines that it should skip tracing the code (either at the C/C++ or Python level), +# no error will be raised. +# Set to false if force falling back to eager is desired. +error_on_dynamo_callback_in_fullgraph_compiled_code = False + +# Install "free" tensor variables (globals, non-locals, nn module attributes) +# as graph attributes. This is useful for export, as it +# produces a consistent number of inputs to the graph. +install_free_tensors = False + +# Temporary flag to control the turning of install_free_tensors to True for +# export. We will remove this flag in a few weeks when stable. +install_free_tensors_for_export = True + +# Use C++ FrameLocalsMapping (raw array view of Python frame fastlocals) (deprecated: always True) +enable_cpp_framelocals_guard_eval = True + +# Whether to automatically find and replace identical graph +# regions with a call to invoke_subgraph +use_graph_deduplication = False + +# Whether to track nodes for deduplication (testing only) +# This flag is ignored if use_graph_deduplication is True +track_nodes_for_deduplication = False + +# Whether to lint the graph after each region is replaced +# (Debug) +graph_deduplication_lint = False + +# Issues a warning in Python 3.13.0 for possibly slower guard evaluation and +# instructs user to attempt using 3.13.1+, where the CPython bug is fixed. +# Should be disabled in dynamo-wrapped tests since some tests check that no warnings are issued. +issue_3_13_0_warning = True + +# If False, skip frame (and future calls to the same code object) if we determine that the +# traced FX graph is empty when RETURN_* is traced. +allow_empty_graphs = False + +# Used for testing - forces all top-level functions to be nested when traced with Dynamo. +# There are slight differences between this config and wrap_top_frame. +debug_force_nested_calls = False + +# Used for testing - forces a graph break when a function +# that doesn't make any Dynamo-inlined calls returns +debug_force_graph_break_on_leaf_return = False + +# Used for testing - causes CompileCounter.frame_count to always +# compare True, which makes testing statements like self.assertEqual(CompileCounter.frame_count, n) +# always pass. +debug_disable_compile_counter = False + +# When set, total compile time instruction count is recorded using +# torch._dynamo.utilsCompileTimeInstructionCounter. +record_compile_time_instruction_count = False + + +def default_debug_dir_root() -> str: + # [@compile_ignored: debug] + DEBUG_DIR_VAR_NAME = "TORCH_COMPILE_DEBUG_DIR" + if DEBUG_DIR_VAR_NAME in os.environ: + return os.path.join(os.environ[DEBUG_DIR_VAR_NAME], "torch_compile_debug") + elif is_fbcode(): + return os.path.join( + tempfile.gettempdir(), getpass.getuser(), "torch_compile_debug" + ) + else: + return os.path.join(os.getcwd(), "torch_compile_debug") + + +# [@compile_ignored: debug] +debug_dir_root = default_debug_dir_root() + +# [@compile_ignored: debug] +_save_config_ignore = { + "repro_after", + "repro_level", + # workaround: "cannot pickle PyCapsule" + "constant_functions", + # workaround: "cannot pickle module" + "skipfiles_inline_module_allowlist", +} + +# for backend="cudagraphs", mutations on input be sent to the cudagraph backend +# or replayed in aot_autograd epilogue. default is False because mutation on inputs +# can prevent cudagraphing. +cudagraph_backend_keep_input_mutation = False + +# enable cudagraph support for mutated inputs from prior cudagraph pool +cudagraph_backend_support_input_mutation = False + +# When True, only ops that have the torch.Tag.pt2_compliant tag +# will be allowed into the graph; all other ops will be disallowed +# and will fall back to eager-mode PyTorch. Useful to ensure +# correctness of custom ops. +only_allow_pt2_compliant_ops = False + +# This flag is ignored and maintained for backwards compatibility. +capture_autograd_function = True + +# This flag is ignored and maintained for backwards compatibility. +capture_func_transforms = True + +# Enable capturing torch.profiler.record_function ops in the graph +# When True, profiler ops are emitted to the graph and preserved through +# compilation (make_fx, functionalization). When False, profiler ops +# are treated as nullcontext. +capture_profiler_record_function: bool = False + +# If to log Dynamo compilation metrics into log files (for OSS) and Scuba tables (for fbcode). +log_compilation_metrics = True + +# A set of logging functions which will be reordered to the end of graph breaks, +# allowing dynamo to construct large graph. Note that there are some +# limitations to this, such as how it does not correctly print objects that were +# mutated after the print statement. +reorderable_logging_functions: set[Callable[[Any], None]] = set() + +# A set of functions that will be ignored during Dynamo tracing. +# These functions will NOT run, will NOT be reordered, and will NOT +# cause graph breaks. They act as full no-ops. +# Ignored functions can take any arguments, but MUST return None. +# Functions should either be module-level functions, +# `logging.Logger.` (ignores all method for all logging.Logger instances) +# or `logger_obj.` (ignores method only for logger_obj logging.Logger instance). +# Other functions may or may not be ignored due to implementation details. If you want to ignore a function +# that `ignore_logging_functions` is failing to ignore, please submit an issue. +ignore_logging_functions: set[Callable[..., Any]] = set() + +# Backwards compat: `ignore_logger_methods` now aliases `ignore_logging_functions`. +# Existing code that used `ignore_logger_methods` will continue to work. +ignore_logger_methods: set[Callable[..., Any]] = Config( + alias="torch._dynamo.config.ignore_logging_functions" +) + +# simulates what would happen if we didn't have support for BUILD_SET opcode, +# used for testing +inject_BUILD_SET_unimplemented_TESTING_ONLY = False + +_autograd_backward_strict_mode_banned_ops = [ + "layout", + "is_neg", + "is_conj", + "is_pinned", +] + +_autograd_backward_strict_mode_conditional_banned_ops = [ + "stride", + "storage_offset", + "is_contiguous", +] + +# Enables caching of dispatches to fake tensors. +fake_tensor_cache_enabled = ( + os.environ.get("TORCH_FAKE_TENSOR_DISPATCH_CACHE", "1") == "1" +) + +# Enables cross checking between the fake tensor cache and dispatch. +fake_tensor_cache_crosscheck_enabled = ( + os.environ.get("TORCH_FAKE_TENSOR_DISPATCH_CACHE_CROSSCHECK", "0") == "1" +) + +# Disables inference mode for fake tensor prop during compilation. At runtime, +# the inference_mode is still respected. +fake_tensor_disable_inference_mode = True + +# Experimental feature for running automatic caching precompile. +# Enables automatic DynamoCache save/load +caching_precompile = os.environ.get("TORCH_CACHING_PRECOMPILE", "0") == "1" + +strict_precompile = os.environ.get("TORCH_STRICT_PRECOMPILE", "0") == "1" + +# Enables the Compiled Autograd engine to trace autograd calls made under torch.compile(). +# Note: AOTAutograd will still trace and partition an AOT backward graph local to that +# compiled region. But AOTAutograd traces without knowledge of backward hooks which are +# coordinated by the Autograd engine, and under the hood, it uses the torch.autograd.grad +# API, so it cannot capture gradient accumulation operations (AccumulateGrad). +# +# Compiled Autograd will trace all autograd operations as seen by the Autograd engine. +# This flag will also lift certain restrictions during the forward trace such as +# registering backward hooks on tensors contained within the compiled region. +compiled_autograd = False + +# We have small decompositions for some optimizer ops such as +# addcmul and foreach_addcmul which avoid item() graph breaks by decomposing +# into their constituent ops. This flag controls whether we use these decompositions +# This can affect numerics for non-inductor backends. +enable_dynamo_decompositions = True + + +# Checks if we should graph break when seeing nn parameter constructors +# in dynamo; this is so that we clearly fail and ask users to move outside +# the function as opposed to trying to support the ctor with unclear semantics +# See https://github.com/pytorch/pytorch/issues/157452 for more context +graph_break_on_nn_param_ctor = True + +# If True, enable calling torch.compile inside __torch_dispatch__ handlers. +# When enabled: +# 1. __torch_dispatch__ methods are automatically wrapped with torch._dynamo.disable +# 2. torch.compile is skipped when active TorchDispatchModes are on the stack +# (unless they have ignore_compile_internals=True) +# This allows torch.compile to work inside dispatch mode handlers once all +# ambient modes have been "consumed". +# See https://github.com/pytorch/pytorch/issues/155331 for more context. +inline_torch_dispatch_torch_compile = True + +# Eager AC/SAC reapplies the mutations (like global dict mutations) in the +# backward during the recomputation of forward. torch.compile has no easy way to +# reapply python mutations in the backward. But many users might be ok to skip +# reapplication of side effects in the backward. They can set this config flag +# to accept this eager and compile divergence. +skip_fwd_side_effects_in_bwd_under_checkpoint = False + + +# Overrides torch.compile() kwargs for Compiled Autograd: +compiled_autograd_kwargs_override: dict[str, Any] = {} +"""Overrides torch.compile() kwargs for Compiled Autograd. + +This dictionary allows overriding specific torch.compile() keyword arguments +when using Compiled Autograd. Only certain overrides are currently supported. + +:type: dict[str, Any] +:default: {} + +Example:: + + torch._dynamo.config.compiled_autograd_kwargs_override = { + "fullgraph": True + } + +.. note:: + Currently only the "fullgraph" kwarg override is supported. Other kwargs + may be added in future versions. +""" + + +# Enables use of collectives *during* compilation to synchronize behavior +# across ranks. Today, this is used solely to modify automatic_dynamic_shapes +# behavior, making it so that we infer that if an input is dynamic by +# inspecting whether or not its input size varies across ranks. Because +# this synchronization uses collectives, all ranks must run compilation at +# the same time; ranks must not diverge with graph breaks. This can be most +# reliably achieved by ensuring PT2 only is run on SPMD programs. If this +# invariant is inviolated, you will likely deadlock NCCL and encounter a +# NCCL timeout. +enable_compiler_collectives = os.environ.get("TORCH_COMPILER_COLLECTIVES", "0") == "1" + +# Allow for experimental support of compiled p2p ops +enable_p2p_compilation = ( + os.environ.get("TORCHDYNAMO_ENABLE_P2P_COMPILATION", "0") == "1" +) + +# Enables a local, filesystem "profile" which can be used for automatic +# dynamic decisions, analogous to profile-guided optimization. This config +# ONLY has an effect if torch.compiler.config.workflow_id is specified, +# which specifies the name of the profile we will save/load. +# +# The idea is that if we observe that a particular input is dynamic over +# multiple iterations on one run, we can save a profile with this information +# so the next time we run we can just make it dynamic the first time around, +# skipping an unnecessary static compilation. The profile can be soundly +# stale, if it is wrong, it just means we may make more things dynamic than +# was actually necessary (NB: this /can/ cause a failure if making something +# dynamic causes the compiler to stop working because you tickled a latent +# bug.) +# +# The profile is ONLY guaranteed to work if the user source code is 100% +# unchanged. Applying the profile if there are user code changes is only +# best effort otherwise. In particular, we identify particular code objects +# by filename, line number and name of their function, so adding/removing newlines +# will typically cause cache misses. We continuously update the profile, +# so if we only discover something is dynamic on the second run, we will update +# the profile for subsequent runs. +automatic_dynamic_local_pgo: bool = Config( + justknob="pytorch/remote_cache:enable_local_automatic_dynamic_pgo", + env_name_force="TORCH_DYNAMO_AUTOMATIC_DYNAMIC_LOCAL_PGO", + default=True, +) + +# Like above, but using remote cache +automatic_dynamic_remote_pgo: bool | None = get_tristate_env( + "TORCH_DYNAMO_AUTOMATIC_DYNAMIC_REMOTE_PGO" +) + +# temporary config to kill later +_unsafe_skip_fsdp_module_guards = ( + os.environ.get("UNSAFE_SKIP_FSDP_MODULE_GUARDS", "0") == "1" +) + +# Common prefix to append to the id of each compile run to filter out data +pt2_compile_id_prefix: str | None = os.environ.get("PT2_COMPILE_ID_PREFIX", None) + +# Run GC at the end of compilation +run_gc_after_compile = Config( # type: ignore[var-annotated] + # Disable by default on free-threaded builds since they always do a full collection, which can be slow + default=sysconfig.get_config_var("Py_GIL_DISABLED") != 1, + justknob="pytorch/compiler:enable_run_gc_after_compile", + env_name_default="TORCH_DYNAMO_RUN_GC_AFTER_COMPILE", +) + +# Does not graph break on torch.autograd._profiler_enabled if set to True. We +# want this flag to be True by default, but there is an unsolved bug that causes +# distributed jobs to timeout with Kineto profiler when this is set to True. +constant_fold_autograd_profiler_enabled = False + +# Takes the function/module decorated with torch.compile and passes it through a +# wrapper. This ensures that nn.module hooks are also compiled in the same frame. +wrap_top_frame = False + +# Flag to record runtime overhead in profile traces. Used for pre-graph bytecode +# and AOTAutograd runtime wrapper. +record_runtime_overhead = True + +# Flag to enable the use of torch.compile().aot_compile() API. Should be always True. +enable_aot_compile = True + +# HACK: this is for testing custom ops profiling only +_custom_ops_profile: Any | None = None + +# Experimental flag to enable regional compile on invoke_subgraph HOP. +# For testing only! +enable_invoke_subgraph_regional_compile: bool = False + +# When True, run a post-tracing pass that inlines all invoke_subgraph HOPs +# back into the parent graph, producing a flat FX graph. Useful when +# downstream compilers (like vllm-compile) don't support HOPs or prefer a +# flat graph. +inline_invoke_subgraph: bool = False + +# Inline invoke_subgraph HOPs that are referenced by exactly one call site. +# Single-use subgraphs add overhead without deduplication benefit. +inline_single_use_invoke_subgraph: bool = True + +# Clear WeakIdRef entries from TracingContext.tensor_to_context and +# MetaTensorDescriber.lookup_tensor at the end of compile. These weakrefs +# can block torch.utils.swap_tensors from working after compile. +# - None (default): clear for registered backends (inductor, eager, etc.), +# don't clear for custom backends (to support standalone_compile, etc.) +# - True: always clear regardless of backend +# - False: never clear regardless of backend +invalidate_compile_context_weakrefs: bool | None = None + +# Reorder and rename output graph nodes into a canonical topological order so +# that structurally equivalent graphs (e.g., same model traced with different +# dict iteration orders across distributed ranks) produce identical FX graphs. +canonicalize_output_graph_node_order: bool = False + +if TYPE_CHECKING: + from torch.utils._config_typing import * # noqa: F403 + + def _make_closure_patcher(**changes: Any) -> Any: ... + + +install_config_module(sys.modules[__name__]) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..14e6026eba0a8f5d9a5986c031c981c3a28dad5e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py @@ -0,0 +1,2658 @@ +""" +This module implements TorchDynamo's core frame conversion functionality, transforming Python +frames into FX graphs. It handles: + +- Frame analysis and bytecode transformation +- Guard creation and management for dynamic behaviors +- Cache management for recompilation +- Error handling and fallback mechanisms + +Key classes: +- ConvertFrame: Main entry point for frame conversion with error handling +- ConvertFrameAssert: Implements core frame to graph conversion logic +- Tracker: Tracks input/output code objects during conversion +- CatchErrorsWrapper: Provides error handling and suppression logic + +The conversion process preserves program semantics while enabling optimizations +through torch.compile() and related systems. + +NOTE: _torchdynamo_orig_backend is used for convert frame wrappers to identify the inner wrapped function. +By going down the _torchdynamo_orig_backend chain, one can recover the original unwrapped backend, +which is checked for during the Dynamo cache lookup. +""" + +from __future__ import annotations + +import collections +import contextlib +import cProfile +import dataclasses +import dis +import functools +import gc +import importlib +import inspect +import itertools +import logging +import os +import pstats +import random # noqa: F401 -- eval_frame_cpp.cpp imports random at runtime; torch.package needs this to detect the dependency +import subprocess +import sys +import tempfile +import threading +import time +import traceback +import types +import typing +import unittest.mock as mock +import weakref +from dataclasses import dataclass +from pathlib import Path +from types import CellType, CodeType, FunctionType, ModuleType +from typing import Any, cast, NoReturn, TypeVar +from typing_extensions import ParamSpec +from weakref import ReferenceType + +import torch +import torch._logging +from torch._C._dynamo.guards import GlobalStateGuard +from torch._dynamo.callback import CallbackTrigger +from torch._dynamo.distributed import get_compile_pg +from torch._dynamo.symbolic_convert import TensorifyState +from torch._guards import compile_context, CompileContext, CompileId, tracing +from torch._higher_order_ops.utils import _in_hop_compile +from torch._logging import structured +from torch._utils_internal import ( + compile_time_strobelight_meta, + maybe_upload_prof_stats_to_manifold, + signpost_event, +) +from torch.fx._lazy_graph_module import _use_lazy_graph_module +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + GuardOnDataDependentSymNode, +) +from torch.fx.graph_module import _forward_from_src as original_forward_from_src +from torch.monitor import _WaitCounter +from torch.nn.parallel.distributed import DistributedDataParallel +from torch.utils._python_dispatch import ( + _disable_current_modes, + any_torch_dispatch_mode_on_stack, + is_in_any_mode_without_ignore_compile_internals, + is_traceable_wrapper_subclass, +) +from torch.utils._traceback import CapturedTraceback, format_traceback_short + +from . import config, decorators, exc, graph_break_hints, trace_rules +from .backends.registry import _is_registered_backend +from .bytecode_analysis import remove_dead_code, remove_pointless_jumps +from .bytecode_transformation import ( + check_inst_exn_tab_entries_valid, + Instruction, + is_generator, + propagate_inst_exn_table_entries, + transform_code_object, +) +from .cache_size import ( + CacheSizeRelevantForFrame, + compute_cache_size, + exceeds_recompile_limit, + is_recompilation, +) +from .code_context import code_context +from .eval_frame import ( + _get_cache_entries_for_region, + _get_total_cache_entry_count, + add_skip_reason, + always_optimize_code_objects, + Constraint, + dynamo_tls, + get_eval_frame_isolate_recompiles_id, + innermost_backend, + skip_code, + TorchPatcher, +) +from .exc import ( + augment_exc_message, + BackendCompilerFailed, + FailOnRecompileLimitHit, + format_error_msg, + InternalTorchDynamoError, + PackageError, + ResumePrologueTracingError, + ShortenTraceback, + TorchRuntimeError, + UncapturedHigherOrderOpError, + unimplemented, + Unsupported, + UserError, +) +from .graph_bytecode_inputs import reset_user_object_tracking +from .guards import ( + CheckFunctionManager, + get_and_maybe_log_recompilation_reasons, + GuardedCode, +) +from .hooks import Hooks +from .output_graph import CodeOptions, DynamoTracerOutput, OutputGraphCommon +from .pgo import ( + _log_size_mismatch_recompile, + log_frame_dynamic_whitelist, + put_code_state, +) +from .replay_record import ExecutionRecord +from .resume_execution import TORCH_DYNAMO_RESUME_IN_PREFIX +from .symbolic_convert import ( + DistributedState, + ExceptionStack, + InstructionTranslator, + LocalState, + SpeculationLog, +) +from .trace_rules import is_numpy +from .types import ConvertFrameReturn, FrameAction, FrameExecStrategy, wrap_guarded_code +from .utils import ( + _get_error_on_graph_break, + chromium_event_timed, + CleanupManager, + CompileTimeInstructionCounter, + counters, + dynamo_timed, + format_bytecode, + gen_record_file_name, + get_hook_for_recompile_user_context, + get_metrics_context, + increment_frame, + is_namedtuple, + istype, + LazyString, + maybe_disable_inference_mode, + maybe_disable_inference_mode_for_fake_prop, + orig_code_map, + reset_graph_break_dup_checker, + setup_compile_debug, + to_int_us, + troubleshooting_url, + write_record_to_file, +) +from .variables.torch_function import torch_function_mode_stack_state_mgr + + +np: ModuleType | None +try: + import numpy as np +except ModuleNotFoundError: + np = None + + +if typing.TYPE_CHECKING: + from collections.abc import Callable + + from torch.utils.weak import WeakIdKeyDictionary + + from .backends.registry import CompilerFn + from .package import CompilePackage + from .repro.after_dynamo import WrapBackendDebug + from .types import BytecodeHook, CacheEntry, DynamoFrameType + from .variables.builder import FrameStateSizeEntry + + +log = logging.getLogger(__name__) +bytecode_log = torch._logging.getArtifactLogger(__name__, "bytecode") +graph_break_log = torch._logging.getArtifactLogger(__name__, "graph_breaks") + + +compile_lock = threading.RLock() + +_T = TypeVar("_T") +_P = ParamSpec("_P") + + +class TODO_UNKNOWN: + pass + + +def _clear_fake_mode_weakrefs( + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode | None, +) -> None: + """Clear WeakIdRef entries from a FakeTensorMode's describer.""" + if fake_mode is None: + return + describer = fake_mode.fake_tensor_converter.meta_converter.describer + describer.lookup_tensor.clear() + describer.lookup_storage.clear() + + +def clear_compile_context_weakrefs( + tracer_output: DynamoTracerOutput | None, + compiler_fn: CompilerFn, +) -> None: + """Clear WeakIdRef entries that can block swap_tensors after compile.""" + should_clear = config.invalidate_compile_context_weakrefs + if should_clear is None: + should_clear = _is_registered_backend(innermost_backend(compiler_fn)) + if not should_clear or not tracer_output: + return + # Use output_graph_for_cleanup which is set even on error paths + # (output_graph is None when the compilation errored). + output_graph = tracer_output.output_graph_for_cleanup + if output_graph is None: + return + tc = output_graph.tracing_context + tc.tensor_to_context.clear() + _clear_fake_mode_weakrefs(tc.fake_mode) + if hasattr(output_graph, "_old_fake_mode"): + _clear_fake_mode_weakrefs(output_graph._old_fake_mode) + + +class Tracker: + def __init__(self) -> None: + self.seen: list[ReferenceType[CodeType]] = [] + self.seen_ids: set[int] = set() + + def add(self, strong_obj: CodeType) -> None: + idx = id(strong_obj) + if idx not in self.seen_ids: + obj = weakref.ref(strong_obj, lambda _: self.seen_ids.remove(idx)) + self.seen.append(obj) + self.seen_ids.add(idx) + + def __contains__(self, item: CodeType) -> bool: + return id(item) in self.seen_ids + + def clear(self) -> None: + self.seen.clear() + self.seen_ids.clear() + + +input_codes = Tracker() +output_codes = Tracker() + +initial_global_state: GlobalStateGuard | None = None + + +@functools.wraps(original_forward_from_src) +def fx_forward_from_src_skip_result( + src: str, globals: dict[str, Any], co_fields: dict[str, str] | None = None +) -> FunctionType: + # we monkey patch FX to prevent infinite loop of trying to convert + # our generated code + result = original_forward_from_src(src, globals, co_fields) + skip_code(result.__code__) + return result + + +def log_dynamo_start(code: CodeType, skip: int = 0) -> list[str]: + convert_frame_intern = structured.intern_string(__file__) + captured_tb = CapturedTraceback.extract(skip=4 + skip).summary() + frames_interned = structured.from_traceback(captured_tb) + # Extract and filter the stack + stack = list( + itertools.takewhile( + lambda f: f["filename"] != convert_frame_intern, + frames_interned, + ) + ) + [ + { + "line": code.co_firstlineno, + "name": code.co_name, + "filename": structured.intern_string(code.co_filename), + } + ] + # Initialize the ChromiumEventLogger on start + torch._logging.trace_structured( + "dynamo_start", + lambda: {"stack": stack}, + ) + + # Capture stack separately without using from_traceback to get the actual filenames + stack_strings = [ + f"Line: {frame.lineno}, Name: {frame.name}, Filename: {frame.filename}" + for frame in captured_tb + if frame.filename != convert_frame_intern + ] + [ + f"Line: {code.co_firstlineno}, Name: {code.co_name}, Filename: {code.co_filename}" + ] + return stack_strings + + +def preserve_global_state(fn: Callable[_P, _T]) -> Callable[_P, _T]: + """ + Context manager to: + 1) Save/restore torch.is_grad_enabled() state + 2) Save/restore torch random state + 3) Monkey patch torch.fx.graph_module._forward_from_src + + NOTE: Python random state is preserved in eval_frame_cpp.cpp instead, + so that it wraps more of the compilation pipeline. + """ + + @functools.wraps(fn) + def _fn(*args: _P.args, **kwargs: _P.kwargs) -> _T: + guards = GlobalStateGuard() + prior_grad_mode = torch.is_grad_enabled() + + # Just in case we get left in a bad dispatch state we want to restore + # it. This can happen because the dispatch bits aren't a true + # stack/counter - so we can't just increment/decrement them as we enter + # and leave. + with ( + torch._C._PreserveDispatchKeyGuard(), + maybe_disable_inference_mode(), + maybe_disable_inference_mode_for_fake_prop(), + ): + prior_inference_mode = torch.is_inference_mode_enabled() + prior_deterministic = torch.are_deterministic_algorithms_enabled() + prior_warn_only = torch.is_deterministic_algorithms_warn_only_enabled() + prior_mobile_allocator_state = ( + torch._C._is_default_mobile_cpu_allocator_set() + ) + prior_dtype = torch.get_default_dtype() + torch_rng_state = torch.random.get_rng_state() + cuda_rng_state = None + if torch.cuda.is_available(): + with torch._C.DisableTorchFunction(): + cuda_rng_state = torch.cuda.get_rng_state() + cuda_matmul_fp32_prec = torch._C._get_fp32_precision_getter( + "cuda", "matmul" + ) + prior_fwd_from_src = torch.fx.graph_module._forward_from_src + torch.fx.graph_module._forward_from_src = fx_forward_from_src_skip_result + cleanup = setup_compile_debug() + exit_stack = contextlib.ExitStack() + exit_stack.enter_context( + torch.fx._symbolic_trace._maybe_revert_all_patches() + ) + reset_user_object_tracking() + try: + return fn(*args, **kwargs) + finally: + cleanup.close() + exit_stack.close() + torch._C._set_grad_enabled(prior_grad_mode) + torch.autograd.grad_mode._enter_inference_mode(prior_inference_mode) + torch.use_deterministic_algorithms( + prior_deterministic, warn_only=prior_warn_only + ) + torch.random.set_rng_state(torch_rng_state) + torch.set_default_dtype(prior_dtype) + curr_mobile_allocator_state = ( + torch._C._is_default_mobile_cpu_allocator_set() + ) + if prior_mobile_allocator_state != curr_mobile_allocator_state: + torch._C._unset_default_mobile_cpu_allocator() + if cuda_rng_state is not None: + with torch._C.DisableTorchFunction(): + torch.cuda.set_rng_state(cuda_rng_state) + torch._C._set_fp32_precision_setter( + "cuda", "matmul", cuda_matmul_fp32_prec + ) + torch.fx.graph_module._forward_from_src = prior_fwd_from_src + if not guards.check(): + raise AssertionError( + f"Global {guards.reason()}state changed while dynamo tracing, please report a bug" + ) + + _fn._torchdynamo_orig_backend = fn # type: ignore[attr-defined] + return _fn + + +@TorchPatcher.suppress_torch_distributed_warnings +def has_tensor_in_frame(frame: DynamoFrameType) -> bool: + """Check if the frame has torch.* related bits""" + # Check if the function was decorated using torch._dynamo.optimize + if frame.f_code in always_optimize_code_objects: + return True + + # Check if there is global import of torch.* + for co_name in frame.f_code.co_names: + if co_name in frame.f_globals: + obj = frame.f_globals[co_name] + if isinstance(obj, ModuleType) and ( + obj.__name__.startswith("torch.") or obj is torch + ): + return True + # ... or a global import of numpy.* + if np and config.trace_numpy and (obj is np or is_numpy(obj)): + return True + + seen_ids: dict[int, bool] = {} + + def has_tensor(obj: object) -> bool: + """Recursively check if the obj has a tensor""" + obj_id = id(obj) + if obj_id in seen_ids: + return seen_ids[obj_id] + seen_ids[obj_id] = False + + if isinstance(obj, (torch.Tensor, torch.nn.Module)) or ( + istype(obj, type) and issubclass(obj, torch.nn.Module) + ): + seen_ids[obj_id] = True + return seen_ids[obj_id] + elif ( + config.trace_numpy + and np + and (istype(obj, np.ndarray) or isinstance(obj, np.generic)) + ): + seen_ids[obj_id] = True + return seen_ids[obj_id] + elif istype(obj, (list, tuple)): + seen_ids[obj_id] = any(has_tensor(v) for v in obj) + return seen_ids[obj_id] + elif istype(obj, dict): + # Some packages like pytest can be updated during runtime. So, make a + # copy of values to avoid issues like "RuntimeError: dictionary + # changed size during iteration" + values = list(obj.values()) + seen_ids[obj_id] = any(has_tensor(v) for v in values) + return seen_ids[obj_id] + elif istype(obj, (str, int, float, type(None), bool)): + seen_ids[obj_id] = False + return seen_ids[obj_id] + elif is_namedtuple(obj) and hasattr(obj, "_fields"): + seen_ids[obj_id] = any(has_tensor(getattr(obj, v)) for v in obj._fields) + return seen_ids[obj_id] + else: + # if config.debug: + # print( + # f"Assuming that object of type {type(obj)} does not have a tensor" + # ) + return False + + # Check if the passed arguments are of type Tensor + for value in frame.f_locals.values(): + if has_tensor(value): + return True + + return False + + +def exception_handler( + e: Exception, + code: CodeType, + frame: DynamoFrameType | None = None, + export: bool = False, +) -> None: + record_filename = None + if hasattr(e, "exec_record"): + record_filename = gen_record_file_name(e, code) + write_record_to_file(record_filename, e.exec_record) + e.record_filename = record_filename # type: ignore[attr-defined] + + augment_exc_message(e, export=export) + + +FRAME_COUNTER = 0 +FRAME_COMPILE_COUNTER: typing.Counter[int | FrameStateSizeEntry] = collections.Counter() + + +def maybe_cprofile(func: Callable[_P, _T]) -> Callable[_P, _T]: + if config.cprofile: + return cprofile_wrapper(func) + return func + + +def cprofile_wrapper(func: Callable[_P, _T]) -> Callable[_P, _T]: + @functools.wraps(func) + def profile_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T: + trace_id = CompileContext.current_trace_id() + if not trace_id: + raise AssertionError("Trace id is None") + profile_path = Path( + os.path.join( + tempfile.gettempdir(), + f"{func.__name__}_{str(trace_id).replace('/', '_')}.profile", + ) + ) + prof = cProfile.Profile() + try: + start_ts = time.time() + # runcall calls prof.enable() and prof.disable(), so do NOT call + # enable outside. This leads to issues like + # ValueError: Another profiling tool is already active + # pyrefly: ignore [bad-argument-type] + retval = prof.runcall(func, *args, **kwargs) + profile_latency = time.time() - start_ts + except ValueError: + log.exception("failed to enable cProfile") + profile_latency = 0 + retval = func(*args, **kwargs) + log.warning( + "### Cprofile for %s trace id [%s] took %.3f seconds ###", + func.__name__, + trace_id, + profile_latency, + ) + ps = pstats.Stats(prof) + try: + prof.dump_stats(profile_path) + except OSError: + log.exception("Cannot write to %s", profile_path) + log.warning("Raw profile at %s", profile_path) + svg_path = profile_path.with_suffix(".svg") + try: + with subprocess.Popen( + [ + "gprof2dot", + "-f", + "pstats", + "--node-label=total-time-percentage", + "--node-label=self-time-percentage", + "--node-label=total-time", + str(profile_path), + ], + stdout=subprocess.PIPE, + ) as gprof2dot_process: + subprocess.check_call( + ["dot", "-Tsvg", "-o", str(svg_path)], + stdin=gprof2dot_process.stdout, + ) + log.warning("Generated SVG from profile at %s", svg_path) + except FileNotFoundError: + log.warning( + "Failed to generate SVG from profile -- dumping stats instead." + "Try installing gprof2dot and dot for a better visualization" + ) + ps.sort_stats(pstats.SortKey.TIME).print_stats(20) + ps.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(20) + + if manifold_link := maybe_upload_prof_stats_to_manifold( + str(profile_path) + ): # fb-only + torch._logging.trace_structured( + "link", + lambda: {"name": "cprofile_manifold_url", "url": manifold_link}, + ) + return retval + + return profile_wrapper + + +@dataclass +class ConvertFrameBox: + error_on_graph_break: bool | None = None + + +def get_compile_id( + frame_state: dict[str, int | FrameStateSizeEntry], +) -> CompileId: + global FRAME_COUNTER + if "_id" not in frame_state: + frame_state["_id"] = FRAME_COUNTER + FRAME_COUNTER += 1 + frame_id = frame_state["_id"] + if not isinstance(frame_id, int): + raise AssertionError(f"frame_id must be an int, got {type(frame_id)}") + + frame_compile_id = FRAME_COMPILE_COUNTER[frame_id] + FRAME_COMPILE_COUNTER[frame_id] += 1 + + compiled_autograd_id = None + if prior := CompileContext.current_compile_id(): + compiled_autograd_id = prior.compiled_autograd_id + return CompileId( + compiled_autograd_id=compiled_autograd_id, + frame_id=frame_id, + frame_compile_id=frame_compile_id, + ) + + +class ConvertFrameAssert: + def __init__( + self, + compiler_fn: CompilerFn, + one_graph: bool = True, + export: bool = False, + export_constraints: Any | None = None, + package: CompilePackage | None = None, + recompile_limit: int | None = None, + ) -> None: + # assert export_constraints is None + reset_graph_break_dup_checker() + self._torchdynamo_orig_backend = compiler_fn + self._one_graph = one_graph + self._export = export + self._export_constraints = export_constraints + self._package = package + self._recompile_limit = recompile_limit + self._box = ConvertFrameBox() + + @property + def _clone_with_backend(self) -> Callable[[CompilerFn], ConvertFrameAssert]: + return lambda backend: convert_frame_assert( + backend, + self._one_graph, + self._export, + self._export_constraints, + recompile_limit=self._recompile_limit, + ) + + def __call__( + self, + frame: DynamoFrameType, + cache_entry: CacheEntry | None, + hooks: Hooks, + frame_state: dict[str, int | FrameStateSizeEntry], + *, + skip: int = 0, + ) -> ConvertFrameReturn: + increment_frame() + code = frame.f_code + + isolate_recompiles_id = get_eval_frame_isolate_recompiles_id() + cache_entries = _get_cache_entries_for_region(code, isolate_recompiles_id) + # For recompile-reason logging: lookup() also checks the default (-1) + # bucket for isolated regions, so include those entries here to avoid + # dropping their guard-failure reasons. + if isolate_recompiles_id >= 0: + cache_entries_for_reasons = cache_entries + _get_cache_entries_for_region( + code, -1 + ) + else: + cache_entries_for_reasons = cache_entries + total_count = _get_total_cache_entry_count(code) + cache_size = compute_cache_size(frame, cache_entries, total_count) + input_codes.add(code) + if code in output_codes: + return ConvertFrameReturn( + skip_reason="frame is already Dynamo-generated code" + ) + if ( + os.environ.get("TORCHDYNAMO_DEBUG_FUNCTION") + and os.environ.get("TORCHDYNAMO_DEBUG_FUNCTION") != code.co_name + ): + return ConvertFrameReturn( + skip_reason="function name does not match TORCHDYNAMO_DEBUG_FUNCTION filter" + ) + if code.co_name == "" and code.co_filename.endswith( + ( + "transformers/file_utils.py", + "transformers/utils/generic.py", + "diffusers/utils/outputs.py", + ) + ): + # not needed, but cleans up torchbench error stats + return ConvertFrameReturn( + skip_reason="skipping generator expression in transformers/diffusers" + ) + if code.co_name == "__setattr__": + return ConvertFrameReturn(skip_reason="__setattr__ frames are not compiled") + if code.co_name == "__init__" and code.co_filename.startswith( + os.path.dirname(torch.optim.__file__) + ): + return ConvertFrameReturn( + skip_reason="torch.optim __init__ frames are not compiled" + ) + + # Check if the frame is generated by an exec builtin call + # TODO - Running exec generated frame seems propagates f_globals to the + # next frames. + if code.co_name == "" and code.co_filename == "": + return ConvertFrameReturn(skip_reason="frame was generated by exec()") + + if ( + code.co_name == "" + and code.co_filename == "" + and not bool(frame.f_builtins) + ): + # namedtuple subclass constructor. Empty builtins cause issue with + # len keyword in LIST_LEN guard. + return ConvertFrameReturn(skip_reason="frame is a namedtuple constructor") + + if is_generator(code): + unimplemented( + gb_type="Attempt to trace generator", + context="", + explanation="Generators cannot be compiled directly with `torch.compile`.", + hints=[ + "Call a generator from inside of a non-generator Python function and " + "compile that function instead.", + *graph_break_hints.FUNDAMENTAL, + ], + ) + + if not has_tensor_in_frame(frame): + return ConvertFrameReturn( + skip_reason="no tensor-related objects found in frame" + ) + + # skip tracing non-recursive disabled functions + # detect if the previous frame (non-convert_frame) is a non-recursive disable wrapper + prev_frame = sys._getframe() + # pyrefly: ignore [bad-assignment] + while ( + prev_frame + and "torch/_dynamo/convert_frame.py" in prev_frame.f_code.co_filename + ): + prev_frame = prev_frame.f_back # type: ignore[assignment] + if ( + prev_frame + and prev_frame.f_code is decorators._nonrecursive_disable_wrapper_code + ): + return ConvertFrameReturn( + apply_to_code=False, + skip_reason="tracing is non-recursively disabled for this frame", + ) + + global initial_global_state + # Save the previous initial_global_state to handle nested compilations + # (e.g., compiled autograd running during graph execution can trigger + # nested compilations that would otherwise overwrite the outer state) + prev_initial_global_state = initial_global_state + initial_global_state = GlobalStateGuard() + + compile_id = get_compile_id(frame_state) + frame_id = compile_id.frame_id + + signpost_event( + "dynamo", + "_convert_frame_assert._compile", + { + "co_name": code.co_name, + "frame_id": frame_id, + "compile_id": str(compile_id), + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + "cache_size": cache_size.num_cache_entries_with_same_id_matched_objs, + "accumulated_cache_size": cache_size.num_cache_entries, + }, + ) + + # Record traced frames, skipping Dynamo generated ones. + if not code.co_name.startswith(TORCH_DYNAMO_RESUME_IN_PREFIX): + info = f"{code.co_name} {code.co_filename}:{code.co_firstlineno}" + dynamo_tls.traced_frame_infos.append(info) + + try: + compile_ctx = compile_context(CompileContext(compile_id)) + # When recompile_limit is set, temporarily override the global + # config so the existing exceeds_recompile_limit check uses it. + recompile_ctx = ( + config.patch(recompile_limit=self._recompile_limit) + if self._recompile_limit is not None + else contextlib.nullcontext() + ) + with compile_ctx, recompile_ctx: + result = _compile( + frame.f_code, + frame.f_globals, + frame.f_locals, + frame.f_builtins, + frame.closure, + self._torchdynamo_orig_backend, + self._one_graph, + self._export, + self._export_constraints, + hooks, + cache_entry, + cache_entries, + cache_entries_for_reasons, + cache_size, + frame, + frame_state=frame_state, + compile_id=compile_id, + skip=skip + 1, + package=self._package, + convert_frame_box=self._box, + ) + finally: + # Restore the previous initial_global_state for nested compilation handling + initial_global_state = prev_initial_global_state + + if config.caching_precompile and self._package is not None: + from .package import DynamoCache + + # Record that the dynamo package has changed + DynamoCache.record_package(self._package) + return result + + +def convert_frame_assert( + compiler_fn: CompilerFn, + one_graph: bool = True, + export: bool = False, + export_constraints: Any | None = None, + package: CompilePackage | None = None, + recompile_limit: int | None = None, +) -> ConvertFrameAssert: + """Fully convert a frame into an FX graph, raising an exception if we fail.""" + return ConvertFrameAssert( + compiler_fn, + one_graph, + export, + export_constraints, + package, + recompile_limit, + ) + + +from collections import OrderedDict + +from torch.utils.hooks import RemovableHandle + + +# we have to use `OrderedDict` to make `RemovableHandle` work. +_bytecode_hooks: dict[int, BytecodeHook] = OrderedDict() +_BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY = "bytecode_hook_side_effects" + + +def get_compiled_code_side_effects( + code: types.CodeType, +) -> tuple[str, ...] | None: + """Return Dynamo's replayed Python side-effect sources for compiled code. + + Returns ``None`` when ``code`` was not produced by Dynamo or no metadata was + attached to it. + """ + if not code_context.has_context(code): + return None + side_effects = code_context.get_context(code).get( + _BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY + ) + if side_effects is None: + return None + return side_effects + + +def compiled_code_has_side_effects(code: types.CodeType) -> bool: + """Return whether Dynamo recorded replayed Python side effects for compiled code.""" + return bool(get_compiled_code_side_effects(code)) + + +def _copy_code_context(src_code: types.CodeType, dst_code: types.CodeType) -> None: + if not code_context.has_context(src_code): + return + src_context = code_context.get_context(src_code) + if _BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY in src_context: + code_context.get_context(dst_code)[_BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY] = ( + src_context[_BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY] + ) + + +def register_bytecode_hook(hook: BytecodeHook) -> RemovableHandle: + """Register hooks for bytecode generated by Dynamo. The hook can do some + logging, as well as return a new code object to be used. Hooks can query + `get_compiled_code_side_effects(new_code)` for replayed Python side effect + sources. Please refer to `BytecodeHook` for the hook signature. + """ + handle = RemovableHandle(_bytecode_hooks) + _bytecode_hooks[handle.id] = hook + return handle + + +# TODO - We want to run preserve_node_meta context manager here, but the CI +# fails (its unclear if the failures were flaky) +# @torch.fx.traceback.preserve_node_meta() +@preserve_global_state +def trace_frame( + code: types.CodeType, + globals: dict[str, object], + locals: dict[str, object], + builtins: dict[str, object], + closure: tuple[CellType], + compiler_fn: CompilerFn, + tf_mode_stack: list[torch.overrides.TorchFunctionMode], + one_graph: bool, + speculation_log: SpeculationLog, + instructions: list[Instruction], + code_options: CodeOptions, + *, + export: bool = False, + export_constraints: Any | None = None, + frame_state: dict[str, int | FrameStateSizeEntry] | None = None, + distributed_state: DistributedState | None = None, + package: CompilePackage | None = None, +) -> DynamoTracerOutput: + from torch.fx.experimental.validator import bisect, translation_validation_enabled + + if ( + torch.cuda.is_available() + and hasattr(torch._C, "_cuda_isCurrentStreamCapturing") + and not isinstance(torch._C._cuda_isCurrentStreamCapturing, type) + and torch.cuda.is_current_stream_capturing() + and not _in_hop_compile() + ): + raise exc.TorchRuntimeError( + "torch.compile cannot JIT compile during CUDA graph capture. " + "Execute warmup iterations outside of CUDA graph capture to trigger " + "compilation, then capture the graph after compilation has completed." + ) + + speculation_log.restart() # type: ignore[has-type] + exn_vt_stack = ExceptionStack() + tracer = InstructionTranslator( + instructions, + code, + locals, + globals, + builtins, + closure, + tf_mode_stack, + code_options, + compiler_fn, + one_graph, + export, + export_constraints, + frame_state=frame_state, + speculation_log=speculation_log, # type: ignore[has-type] + exn_vt_stack=exn_vt_stack, + distributed_state=distributed_state, # type: ignore[has-type] + package=package, + ) + + def run_tracer() -> None: + try: + tracer.output.mark_bytecode_tracing_start() + with tracing(tracer.output.tracing_context), tracer.set_current_tx(): + tracer.run() + except exc.UnspecializeRestartAnalysis: + speculation_log.clear() # type: ignore[has-type] + raise + except ( + exc.SpeculationRestartAnalysis, + exc.TensorifyScalarRestartAnalysis, + exc.SkipFrame, + ): + raise + except Exception: + if translation_validation_enabled(): + bisect(tracer.output.shape_env) + raise + finally: + tracer.output.call_cleanup_hooks() + tracer.f_locals = {} + + try: + run_tracer() + tracer_output = DynamoTracerOutput(tracer) + output = tracer_output.output_graph + if output is None: + raise AssertionError("tracer output_graph must not be None") + if not output.output_instructions: + raise AssertionError("output_graph must have output_instructions") + instructions[:] = output.output_instructions + code_options.update(output.code_options) + propagate_inst_exn_table_entries(instructions) + check_inst_exn_tab_entries_valid(instructions) + instructions[:] = remove_pointless_jumps(remove_dead_code(instructions)) + except Exception as e: + e._torch_dynamo_tracer_output = DynamoTracerOutput(tracer, error=True) # type: ignore[attr-defined] + raise + return tracer_output + + +@dataclass +class DynamoOutput: + """ + Represents the core data returned from a single dynamo run, including: + - Guards, wrapped inside tracer_output.output_graph.guards + - Generated bytecode + - Other information needed for compilation. + This data structure should capture all the "interesting" information dynamo + produces on the frontend side before it enters user backend. + """ + + tracer_output: DynamoTracerOutput + bytecode: types.CodeType + pycode: list[list[str] | None] + last_attempt_start_time: float | None + + def build_guards( + self, + code: types.CodeType, + hooks: Hooks | None = None, + save: bool = False, + cache_entries: list[CacheEntry] | None = None, + strict_error: bool = False, + ) -> CheckFunctionManager: + output_graph = self.tracer_output.output_graph + if output_graph is None: + raise AssertionError("output_graph must not be None when building guards") + return CheckFunctionManager( + code, + output_graph, + cache_entries, + hooks.guard_fail_fn if hooks else None, + hooks.guard_filter_fn if hooks else None, + save_guards=save, + strict_error=strict_error, + ) + + def graph_capture_output( + self, + argdefs: tuple[Any, ...] | None = None, + kwdefaults: dict[str, Any] | None = None, + ) -> GraphCaptureOutput: + output_graph = self.tracer_output.output_graph + if output_graph is None: + raise AssertionError( + "output_graph must not be None when producing graph capture output" + ) + return GraphCaptureOutput( + OutputGraphCommon( + output_graph.dump_guards_state(), + output_graph.import_sources, + output_graph.shape_env, + output_graph.export_metadata, + output_graph.tracked_fakes_id_to_source, + ), + output_graph.import_sources, + output_graph.traced_code, + self.bytecode, + self.pycode, + self.tracer_output.closure, + argdefs, + kwdefaults, + self.tracer_output.f_globals, + ) + + +@dataclass +class BackendInput: + """ + Represents core data structure that dynamo will pass to a backend, including: + - Graph module + - Example inputs + - The FakeTensorMode used for compiling graph. + This data structure should capture all the information dynamo produces + on for the user backend. + """ + + backend_id: str + graph_module: torch.fx.GraphModule + example_inputs: Any + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode + tensor_to_context: WeakIdKeyDictionary + + +@dataclass(frozen=True) +class GraphRuntimeEnv: + bytecode: types.CodeType + pycode: list[list[str] | None] + import_sources: dict[str, str] + used_globals: dict[str, Any] + closure: tuple[Any, ...] | None + argdefs: tuple[Any, ...] | None + kwdefaults: dict[str, Any] | None = None + external_refs: set[str] = dataclasses.field(default_factory=set) + + def forward_callable( + self, + backend_id: str, + compiled_fn: Callable[..., Any], + *, + extra_globals: dict[str, Any] | None = None, + use_python_codegen: bool = False, + ) -> Callable[..., Any]: + import_sources = { + alias: importlib.import_module(module_name) + for alias, module_name in self.import_sources.items() + } + f_globals = { + **import_sources, + **self.used_globals, + **(extra_globals or {}), + backend_id: compiled_fn, + } + + # check that all external references are available + self._check_external_refs(f_globals) + + if use_python_codegen: + bytecode = self._build_python_wrapper(f_globals, backend_id) + else: + bytecode = self.bytecode + + fn = types.FunctionType( + bytecode, + f_globals, + closure=self.closure, + argdefs=self.argdefs, + ) + if self.kwdefaults: + fn.__kwdefaults__ = self.kwdefaults + return fn + + def _build_python_wrapper_source(self) -> str: + """Build Python source for the wrapper function from generated pycode.""" + pycode_parts = [p for p in self.pycode if p is not None] + if not pycode_parts: + raise RuntimeError("No Python code generated from Dynamo.") + orig_code = self.bytecode + argcount = orig_code.co_argcount + varnames = orig_code.co_varnames[:argcount] + argnames = ", ".join(varnames) + + func_lines = ["def __generate_func__():"] + func_lines.append(f" def __dynamo_func__({argnames}):") + for part in pycode_parts: + for line in part: + func_lines.append(f" {line}") + func_lines.append(" return __ret") + func_lines.append(" return __dynamo_func__") + func_lines.append("__dynamo_generated_func__ = __generate_func__()") + return "\n".join(func_lines) + + def _build_python_wrapper( + self, f_globals: dict[str, Any], backend_id: str + ) -> types.CodeType: + """Build a Python code object from the generated pycode strings.""" + func_source = self._build_python_wrapper_source() + # Execute to get the function, then extract its code + namespace: dict[str, Any] = f_globals.copy() + # exec() should be fine because we only define a function in the scope + # without actually running the code inside the function, so in theory + # it should be safe. + exec(func_source, namespace) + func = namespace["__dynamo_generated_func__"] + return func.__code__ + + def _check_external_refs(self, f_globals: dict[str, Any]) -> None: + # pyrefly: ignore [implicit-any] + missing_refs = [] + for ref in self.external_refs: + if ref not in f_globals: + missing_refs.append(ref) + + if missing_refs: + raise RuntimeError( + f"Missing required external references: {missing_refs}. " + "Please load AOT compiled function with `f_globals=`" + ) + + +def _safe_builtins_dict(builtins_dict: dict[str, Any]) -> dict[str, Any]: + """Filter a builtins dict to only picklable entries for serialization.""" + import pickle + + result = {} + for k, v in builtins_dict.items(): + try: + pickle.dumps(v) + result[k] = v + except Exception: + pass + return result + + +@dataclass +class GraphCaptureOutput: + """ + Minimal version of DynamoOutput + """ + + output_graph: OutputGraphCommon + import_sources: dict[str, str] + traced_code: list[CodeType] + bytecode: CodeType + pycode: list[list[str] | None] + closure: tuple[Any, ...] | None + argdefs: tuple[Any, ...] | None + kwdefaults: dict[str, Any] | None + f_globals: dict[str, Any] + + def build_guards( + self, + code: types.CodeType, + hooks: Hooks | None = None, + save: bool = False, + cache_entries: list[CacheEntry] | None = None, + strict_error: bool = False, + ) -> CheckFunctionManager: + return CheckFunctionManager( + code, + self.output_graph, + cache_entries, + hooks.guard_fail_fn if hooks else None, + hooks.guard_filter_fn if hooks else None, + save_guards=save, + strict_error=strict_error, + ) + + def get_runtime_env(self) -> GraphRuntimeEnv: + from torch._dynamo.source import get_global_source_name + + used_globals = {} + for ( + source + ) in self.output_graph.export_metadata.graph_input_idx_to_local_source.values(): + global_name = get_global_source_name(source) + if global_name is None: + continue + if global_name in self.f_globals: + used_globals[global_name] = self.f_globals[global_name] + + # Scan bytecode for all external references + external_refs = self._get_external_refs(self.bytecode) + + # Best-effort serialization of builtins referenced by the bytecode. + # Similar to how guards prune __builtins_dict__ to only used entries. + import builtins as _builtins + + for ref in external_refs: + if ref not in used_globals: + if ref.startswith("__builtins_dict__") and ref in self.f_globals: + used_globals[ref] = _safe_builtins_dict(self.f_globals[ref]) + elif hasattr(_builtins, ref): + used_globals[ref] = getattr(_builtins, ref) + + return GraphRuntimeEnv( + bytecode=self.bytecode, + pycode=self.pycode, + import_sources=self.import_sources, + used_globals=used_globals, + closure=self.closure, + argdefs=self.argdefs, + kwdefaults=self.kwdefaults, + external_refs=external_refs, + ) + + @staticmethod + def _get_external_refs(bytecode: types.CodeType) -> set[str]: + import dis + + external_refs: set[str] = set() + + # Get all instructions from the bytecode + for instruction in dis.get_instructions(bytecode): + # LOAD_GLOBAL loads a global variable or a builtin + if instruction.opname == "LOAD_GLOBAL": + if instruction.argval: + external_refs.add(instruction.argval) + # LOAD_NAME loads a name (used in module-level code, less common in functions) + elif instruction.opname == "LOAD_NAME": + if instruction.argval: + external_refs.add(instruction.argval) + + return external_refs + + +@dataclass +class CaptureOutput: + """ + CaptureOutput should represent all the information produced from torch + compiler for a single graph capture. This intends to be consumed by + various compiler frontends so that we can share as much compiler internals + as possible and avoid great divergence between different stacks. + This data structure should eventually contain all the information compiler + produces as more refactors happens to converge different compiler + frontends. + """ + + graph_capture_output: GraphCaptureOutput + # BackendInput can be None when dynamo didn't compile any graph (no tensor op) + backend_input: BackendInput | None + + def forward_callable( + self, + *, + compiled_fn: Callable[..., Any] | None = None, + extra_globals: dict[str, Any] | None = None, + use_python_codegen: bool = False, + ) -> Callable[..., Any]: + runtime_env = self.graph_capture_output.get_runtime_env() + if self.backend_input is None: + raise AssertionError("backend_input must not be None") + backend_id = self.backend_input.backend_id + compiled_fn = compiled_fn or self.backend_input.graph_module + return runtime_env.forward_callable( + backend_id, + compiled_fn, + extra_globals=extra_globals, + use_python_codegen=use_python_codegen, + ) + + +def get_traced_fn(mod: Any) -> tuple[FunctionType, object | None]: + """ + Utility function to get the function to trace, and optionally a bound self + object, from a callable (nn.Module, function, or method). + """ + import inspect + + if isinstance(mod, torch.nn.Module): + resolved_forward = mod.forward + if hasattr(resolved_forward, "__self__"): + # pyrefly: ignore [missing-attribute] + resolved_forward = resolved_forward.__func__ + + resolved_call = mod.__call__ + if hasattr(resolved_call, "__self__"): + resolved_call = resolved_call.__func__ + + # Mirrored from NNModuleVariable.call_function: + # https://github.com/pytorch/pytorch/blob/main/torch/_dynamo/variables/nn_module.py#L1035 + if ( + len(mod._forward_pre_hooks) == 0 + and len(mod._forward_hooks) == 0 + and len(torch.nn.modules.module._global_forward_pre_hooks) == 0 + and len(torch.nn.modules.module._global_forward_hooks) == 0 + and len(mod._backward_pre_hooks) == 0 + and len(mod._backward_hooks) == 0 + and len(torch.nn.modules.module._global_backward_pre_hooks) == 0 + and len(torch.nn.modules.module._global_backward_hooks) == 0 + and resolved_forward != torch.nn.Module.forward # has forward impl + and resolved_call == torch.nn.Module.__call__ # no custom __call__ impl + ): + # We cannot trace __call__ by default because it will break + # the legacy dynamo export. If we want to revisit this, + # feel free to remove this path and try unittests in + # test_strict_export_v2.py + mod = mod.forward + elif isinstance(mod, torch.fx.GraphModule): + mod = mod._call_impl + else: + mod = mod.__call__ + + if hasattr(mod, "__self__"): + return mod.__func__, mod.__self__ + elif inspect.isfunction(mod): + return mod, None + else: + raise RuntimeError(f"Unsupported model code type {mod}") + + +def _get_signature(fn: Any) -> inspect.Signature: + return inspect.signature(fn, follow_wrapped=False) + + +def _get_frame( + mod: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, +) -> FrameInfo: + """ + Create a frame to trace, given a model, args, and optional kwargs. + """ + import builtins + + fn, self_opt = get_traced_fn(mod) + if self_opt is not None: + args = (self_opt,) + args + if kwargs is None: + kwargs = {} + + signature = _get_signature(fn) + bound_arguments = signature.bind(*args, **kwargs) + bound_arguments.apply_defaults() + f_locals = bound_arguments.arguments + + closure = fn.__closure__ or () + freevars = fn.__code__.co_freevars + if freevars or closure: + if len(closure) != len(freevars): + raise AssertionError( + f"closure length ({len(closure)}) must match freevars length ({len(freevars)})" + ) + f_locals.update( + {name: cell.cell_contents for name, cell in zip(freevars, closure)} + ) + + return FrameInfo( + fn.__code__, + fn.__globals__, + f_locals, + builtins.__dict__, + closure=fn.__closure__ or (), # type: ignore[arg-type] + argdefs=fn.__defaults__, + kwdefaults=fn.__kwdefaults__, + ) + + +def fullgraph_capture( + mod: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + constraints: list[Constraint] | None = None, + _is_export_deprecated_do_not_use: bool = False, +) -> CaptureOutput: + """ + This API captures a full graph for a model, given example inputs to trace with. + + Specifically, it takes a callable (nn.Module, method, or function), args, and + optional kwargs, and returns Dynamo-captured graph along with other important + compile-time information. This serves as the common graph-capture mechanism + for different torch compiler AOT frontends (e.g. AOT precompile, export). + + Note that this API doesn't apply context managers like metrics context, + and the expectation is that the caller will apply them depending + on the use case. + + The CaptureOutput is separated into two parts: + 1. Frontend specific information, which includes: + - guards + - generated bytecode + - other information tracked by OutputGraphCommon. + 2. Backend specific information (indexed by unique backend id) such as: + - fx graph + - example inputs + """ + frame = _get_frame(mod, args, kwargs) + + with compile_context(CompileContext(get_compile_id({}))): + return _fullgraph_capture_frame( + frame, + constraints=constraints, + _is_export_deprecated_do_not_use=_is_export_deprecated_do_not_use, + ) + + +@dataclass +class FrameInfo: + code: types.CodeType + globals: dict[str, object] + locals: dict[str, object] + builtins: dict[str, object] + closure: tuple[CellType] + argdefs: tuple[Any, ...] | None + kwdefaults: dict[str, Any] | None + + +def _fullgraph_capture_frame( + frame: FrameInfo, + *, + constraints: list[Constraint] | None = None, + _is_export_deprecated_do_not_use: bool = False, +) -> CaptureOutput: + from torch._guards import TracingContext + + backend_input: BackendInput | None = None + + def fullgraph_compiler( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> torch.fx.GraphModule: + nonlocal backend_input + tracing_context = TracingContext.get() + fake_mode = tracing_context.fake_mode + tensor_to_context = tracing_context.tensor_to_context + if fake_mode is None: + raise AssertionError("fake_mode must not be None") + if not isinstance(gm.meta["backend_id"], str): + raise AssertionError( + f"gm.meta['backend_id'] must be a str, got {type(gm.meta['backend_id'])}" + ) + backend_input = BackendInput( + gm.meta["backend_id"], gm, example_inputs, fake_mode, tensor_to_context + ) + return gm + + try: + # TODO with torch._dynamo.config.patch(generate_pycode=True): + dynamo_output = compile_frame( + frame.code, + frame.globals, + frame.locals, + frame.builtins, + frame.closure, + compiler_fn=fullgraph_compiler, + export=_is_export_deprecated_do_not_use, + export_constraints=constraints, # type: ignore[arg-type] + one_graph=True, + restart_reasons=set(), + ) + # https://github.com/pytorch/pytorch/blob/main/torch/_dynamo/eval_frame.py#L831 + except (Unsupported, UncapturedHigherOrderOpError, UserError) as e: + augment_exc_message(e) + if config.verbose: + raise + # strip internal tracebacks from causes + cur_exn: BaseException = e + while cur_exn.__cause__ is not None: + cur_exn.__cause__.with_traceback(None) + cur_exn = cur_exn.__cause__ + + raise e.with_traceback(None) from e.__cause__ # User compiler error + + return CaptureOutput( + dynamo_output.graph_capture_output(frame.argdefs, frame.kwdefaults), + backend_input, + ) + + +# Called by eval_frame_cpp.cpp in order to raise an error if Dynamo attempts to compile_frame +def get_fail_callback(callback: ConvertFrameProtocol) -> ConvertFrameProtocol: + fail_callback = getattr(callback, "_dynamo_fail_callback", None) + if fail_callback is not None: + return fail_callback + + def compile_frame_error(*args: Any, **kwargs: Any) -> NoReturn: + raise RuntimeError( + "Dynamo: expected not to compile nested code - this happens because " + "a Dynamo callback was triggered and succeeded in compiling " + "when running fullgraph=True compiled code." + ) + + def fail_callback(*args: Any, **kwargs: Any) -> ConvertFrameReturn: + with mock.patch(__name__ + ".compile_frame", compile_frame_error): + return callback(*args, **kwargs) + + # pyrefly: ignore [missing-attribute] + callback._dynamo_fail_callback = fail_callback + return fail_callback + + +def compile_frame( # type: ignore[return] + code: types.CodeType, + globals: dict[str, object], + locals: dict[str, object], + builtins: dict[str, object], + closure: tuple[CellType], + compiler_fn: CompilerFn, + one_graph: bool, + restart_reasons: set[str], + *, + export: bool = False, + export_constraints: Any | None = None, + frame_state: dict[str, int | FrameStateSizeEntry] | None = None, + distributed_state: DistributedState | None = None, + package: CompilePackage | None = None, + # pyrefly: ignore [bad-return] +) -> DynamoOutput: + """ + A helper function taking a frame and backend, then return the generated bytecode + and guards as a common data structure. + This is a shared interface for multiple compiler frontends (e.g. torch.compile, + torch.export) that needs to capture a graph out of python code. + """ + # This is shared across restarts + speculation_log = SpeculationLog() + + def transform( + instructions: list[Instruction], code_options: dict[str, Any] + ) -> DynamoTracerOutput: + tf_mode_stack: list[torch.overrides.TorchFunctionMode] = list( + torch_function_mode_stack_state_mgr.stack + ) + tracer_output = trace_frame( + code, + globals, + locals, + builtins, + closure, + compiler_fn, + tf_mode_stack, + one_graph, + speculation_log, + instructions, + cast(CodeOptions, code_options), + export=export, + export_constraints=export_constraints, + frame_state=frame_state, + distributed_state=distributed_state, + package=package, + ) + + if tracer_output is None: + raise AssertionError("tracer_output must not be None after transform") + return tracer_output + + last_attempt_start_time = None + for attempt in itertools.count(): + CompileContext.get().attempt = attempt + + try: + with dynamo_timed(f"compile_attempt_{attempt}", log_pt2_compile_event=True): + bytecode, tracer_output = transform_code_object(code, transform) + if tracer_output is None: + raise AssertionError( + "tracer_output must not be None after transform_code_object" + ) + if tracer_output.output_graph is None: + raise AssertionError( + "tracer_output.output_graph must not be None after transform_code_object" + ) + return DynamoOutput( + tracer_output=tracer_output, + bytecode=bytecode, + pycode=tracer_output.output_graph.output_pycode, + last_attempt_start_time=last_attempt_start_time, + ) + except exc.RestartAnalysis as e: + if not isinstance(e, exc.TensorifyScalarRestartAnalysis): + TensorifyState.clear() + log.info( + "Restarting analysis due to %s", + LazyString(format_traceback_short, e.__traceback__), + ) + # Clean up the failed tracer output's graph to break reference cycles + failed_tracer_output = getattr(e, "_torch_dynamo_tracer_output", None) + if failed_tracer_output: + failed_tracer_output._cleanup_output_graph() + # If restart reason is None just log the type of the exception + restart_reasons.add(e.restart_reason or str(type(e))) + # We now have a new "last attempt", reset the clock + last_attempt_start_time = time.time() + if attempt > 100: + unimplemented( + gb_type="Excessive RestartAnalysis() calls", + context="", + explanation="Dynamo attempted to trace the same frame 100+ times. " + "Giving up on compiling as the compile time tradeoff is likely not " + "worth the performance gain.", + hints=[], + ) + except exc.SkipFrame as e: + if not isinstance(e, exc.TensorifyScalarRestartAnalysis): + TensorifyState.clear() + # Clean up the failed tracer output's graph to break reference cycles + failed_tracer_output = getattr(e, "_torch_dynamo_tracer_output", None) + if failed_tracer_output: + failed_tracer_output._cleanup_output_graph() + raise + + +def _compile( + code: CodeType, + globals: dict[str, object], + locals: dict[str, object], + builtins: dict[str, object], + closure: tuple[CellType], + compiler_fn: CompilerFn, + one_graph: bool, + export: bool, + export_constraints: Any | None, + hooks: Hooks, + cache_entry: CacheEntry | None, + cache_entries: list[CacheEntry], + cache_entries_for_reasons: list[CacheEntry], + cache_size: CacheSizeRelevantForFrame, + frame: DynamoFrameType | None = None, + frame_state: dict[str, int | FrameStateSizeEntry] | None = None, + *, + compile_id: CompileId, + skip: int = 0, + package: CompilePackage | None = None, + # Can be used to record things for the caller, both + # in the case of normal and exception code paths + convert_frame_box: ConvertFrameBox | None = None, +) -> ConvertFrameReturn: + from torch.fx.experimental.validator import ( + BisectValidationException, + ValidationException, + ) + + # Only nonlocal defs here please! + # Time spent compiling this frame before restarting or failing analysis + dynamo_time_before_restart: float = 0.0 + + @compile_time_strobelight_meta(phase_name="compile_inner") + def compile_inner( + code: CodeType, one_graph: bool, hooks: Hooks + ) -> tuple[ConvertFrameReturn, DynamoTracerOutput | None]: + with contextlib.ExitStack() as stack: + # Hold _is_compiling_flag True for the duration of compilation so + # torch.compiler.is_compiling() is observable in code that runs + # during the compile session but is not directly Dynamo-traced + # (wrapper-subclass __torch_dispatch__ invoked by AOTAutograd, + # make_fx invoked from a custom backend, etc.). Export sets the + # flag itself via _compiling_state_context, so skip there. + if not export: + stack.enter_context(torch.compiler._compile_session_context()) + stack.enter_context( + torch._dynamo.callback_handler.install_callbacks( + CallbackTrigger.DYNAMO, str(CompileContext.current_compile_id()) + ) + ) + stack.enter_context(CompileTimeInstructionCounter.record()) + stack.enter_context(torch_function_mode_stack_state_mgr) + result = _compile_inner(code, one_graph, hooks) + if torch._C._len_torch_function_stack() != 0: + raise AssertionError( + "Torch function mode stack state changed while dynamo tracing, please report a bug" + ) + return result + + return ( + ConvertFrameReturn(), + None, + ) # dead, but see https://github.com/python/mypy/issues/7577 + + @maybe_cprofile + def _compile_inner( + code: CodeType, + one_graph: bool, + hooks: Hooks, + ) -> tuple[ConvertFrameReturn, DynamoTracerOutput]: + nonlocal dynamo_time_before_restart + last_attempt_start_time = start_time = time.time() + + def log_bytecode( + prefix: str, name: str, filename: str, line_no: int, code: CodeType + ) -> None: + if bytecode_log.isEnabledFor(logging.DEBUG): + bytecode_log.debug( + format_bytecode(prefix, name, filename, line_no, code) + ) + + log_bytecode( + "ORIGINAL BYTECODE", + code.co_name, + code.co_filename, + code.co_firstlineno, + code, + ) + # Dump the ORIGINAL bytecode of resumption frame into TORCH_TRACE + # log file, so that it is parsed by tlparse tool. + is_resumption_frame = "torch_dynamo_resume_in" in code.co_name + if is_resumption_frame: + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": code.co_name + "_ORIGINAL_BYTECODE", + "encoding": "string", + }, + payload_fn=lambda: dis.Bytecode(code).dis(), + ) + out_code = None + from .graph_id_filter import get_dynamo_config_override_for_compile_id + + dynamo_config_override = get_dynamo_config_override_for_compile_id( + compile_id, config.debug_dynamo_config_override + ) + try: + with ( + config.patch(dynamo_config_override) + if dynamo_config_override + else contextlib.nullcontext() + ): + dynamo_output = compile_frame( + code, + globals, + locals, + builtins, + closure, + compiler_fn, + one_graph, + restart_reasons, + export=export, + export_constraints=export_constraints, + frame_state=frame_state, + distributed_state=distributed_state, + package=package, + ) + except exc.SkipFrame as e: + if one_graph: + log.debug("No graph captured with export/fullgraph=True") + if e._torch_dynamo_tracer_output is None: + raise AssertionError( + "SkipFrame exception must have _torch_dynamo_tracer_output set" + ) from None + return ( + ConvertFrameReturn( + skip_reason=f"Dynamo decided to skip the frame while tracing: {e}" + ), + e._torch_dynamo_tracer_output, + ) + + if distributed_state is not None and distributed_state.all_states is None: # type: ignore[has-type] + raise AssertionError( + "compiler collective wasn't run before compilation completed" + ) + out_code = dynamo_output.bytecode + tracer_output = dynamo_output.tracer_output + if dynamo_output.last_attempt_start_time is not None: + last_attempt_start_time = dynamo_output.last_attempt_start_time + + if out_code is None: + raise AssertionError("out_code must not be None after compilation") + log_bytecode( + "MODIFIED BYTECODE", + code.co_name, + code.co_filename, + code.co_firstlineno, + out_code, + ) + # Dump the MODIFIED bytecode of resumption frame into TORCH_TRACE + # log file, so that it is parsed by tlparse tool. + if is_resumption_frame: + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": code.co_name + "_MODIFIED_BYTECODE", + "encoding": "string", + }, + payload_fn=lambda: dis.Bytecode(out_code).dis(), + ) + + if tracer_output.output_graph is None: + raise AssertionError("tracer_output.output_graph must not be None") + output = tracer_output.output_graph + code_context.get_context(out_code)[_BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY] = ( + tuple(output.get_replayed_side_effect_source_refs()) + ) + + for idx, hook in enumerate(_bytecode_hooks.values()): + with dynamo_timed(f"bytecode_hooks_{idx}", log_pt2_compile_event=True): + hook_output = hook(code, out_code) + if hook_output is not None: + if hook_output is not out_code: + _copy_code_context(out_code, hook_output) + out_code = hook_output + + orig_code_map[out_code] = code + output_codes.add(out_code) + dynamo_time_before_restart = last_attempt_start_time - start_time + + from .bytecode_debugger import BREAKPOINT_MARKER + + if BREAKPOINT_MARKER in out_code.co_consts: + from torch._C._dynamo.eval_frame import register_breakpoint_code + + register_breakpoint_code(out_code) + + # Tests for new code objects. + # The rationale for these tests can be found in torch/csrc/dynamo/eval_frame.c + # Only test once the code object is created. + # They are not tested during runtime. + + def count_args(code: CodeType) -> int: + import inspect + + return ( + code.co_argcount + + code.co_kwonlyargcount + + bool(code.co_flags & inspect.CO_VARARGS) + + bool(code.co_flags & inspect.CO_VARKEYWORDS) + ) + + if out_code is None: + raise AssertionError( + "out_code must not be None after bytecode hook processing" + ) + + total_argcount_old = count_args(code) + total_argcount_new = count_args(out_code) + if ( + code.co_varnames[:total_argcount_old] + != out_code.co_varnames[:total_argcount_new] + ): + msg = "arg mismatch: " + msg += f"old code object has args {code.co_varnames[:total_argcount_old]}, " + msg += ( + f"new code object has args {out_code.co_varnames[:total_argcount_new]}" + ) + raise AssertionError(msg) + + if code.co_freevars != out_code.co_freevars: + msg = "free var mismatch: " + msg += f"old code object has free var {code.co_freevars}, " + msg += f"new code object has free var {out_code.co_freevars}" + raise AssertionError(msg) + + if code.co_cellvars != out_code.co_cellvars: + msg = "cell var mismatch: " + msg += f"old code object has cell var {code.co_cellvars}, " + msg += f"new code object has cell var {out_code.co_cellvars}" + raise AssertionError(msg) + + # Skipping Dynamo on a frame without any extracted graph. + # This does not affect eager functionality. But this is necessary + # for export for cases where Dynamo-reconstructed bytecode can create + # new function frames, confusing export in thinking that there + # are extra graphs now. + + if output.export and output.is_empty_graph(): + return ( + ConvertFrameReturn(skip_reason="export mode produced an empty graph"), + tracer_output, + ) + + if output.guards is None: + raise AssertionError("output.guards must not be None") + CleanupManager.instance[out_code] = output.cleanups + nonlocal cache_entry + # Temporarily restore the mode stack so guard expressions that + # reference modes can evaluate. DisableTorchFunction prevents + # __torch_function__ dispatch during guard construction so modes + # with mutable state aren't triggered. + build_guards_ctx = contextlib.ExitStack() + if torch_function_mode_stack_state_mgr.stack: + build_guards_ctx.enter_context( + torch_function_mode_stack_state_mgr.temp_restore_stack() + ) + with dynamo_timed("build_guards", log_pt2_compile_event=True), build_guards_ctx: + check_fn = dynamo_output.build_guards( + code, + hooks=hooks, + save=package is not None, + cache_entries=cache_entries, + ) + + if package is not None: + if check_fn.guards_state is None: + raise AssertionError("check_fn.guards_state must not be None") + package.add_guarded_code(check_fn.guards_state, out_code) + package.add_inlined_source(output.tracing_context.traced_code) + package.update_device_type(output.current_tracer.graph) + + compile_id_str = str(compile_id) if compile_id is not None else "Unknown" + annotation_str = "Torch-Compiled Region: " + compile_id_str + guarded_code = GuardedCode( + out_code, + check_fn.guard_manager, # type: ignore[arg-type] + compile_id, + annotation_str, + ) + + if not output.is_empty_graph() and hooks.guard_export_fn is not None: + # We should not run the guard_export_fn when Dynamo does not + # generate any graph. This can happen in export when TorchDynamo + # generated bytecode has some reconstruction logic for mutated + # variables which can trigger TorchDynamo on the children frames but + # they are benign and do not generate any new graphs. + hooks.guard_export_fn(output.guards) + + return wrap_guarded_code(guarded_code), tracer_output + + metrics_context = get_metrics_context() + package_code_context = ( + package.code_context(code) if package is not None else contextlib.nullcontext() + ) + with ( + _use_lazy_graph_module(config.use_lazy_graph_module), + compile_context(CompileContext(compile_id)), + chromium_event_timed( + "dynamo", reset_event_log_on_exit=True, log_pt2_compile_event=True + ), + _WaitCounter("pytorch.wait_counter.entire_forward_compile").guard(), + metrics_context, + dynamo_timed( + "_compile.compile_inner", + phase_name="entire_frame_compile", + dynamo_compile_column_us="dynamo_cumulative_compile_time_us", + ), + package_code_context, + ): + restart_reasons: set[str] = set() + if compile_pg := get_compile_pg(): + distributed_state = DistributedState(compile_pg, LocalState()) + else: + distributed_state = None + + # Check recompilations + recompile_reason: str | None = None + if is_recompilation(cache_size) and frame: + reasons = get_and_maybe_log_recompilation_reasons( + cache_entries_for_reasons, frame, innermost_backend(compiler_fn) + ) + recompile_reason = ( + "Unable to find recompilation reasons" if not reasons else reasons[0] + ) + metrics_context.update_outer( + { + "recompile_reason": recompile_reason, + "inline_inbuilt_nn_modules_candidate": False, + } + ) + + recompile_user_contexts = get_hook_for_recompile_user_context() + if recompile_user_contexts: + # cap each user context to N chars for data retention purposes. N=256 + # is chosen to be large enough to capture the most important info. + user_contexts_msg = { + user_context()[:256] for user_context in recompile_user_contexts + } + metrics_context.set("recompile_user_contexts", user_contexts_msg) + + exceeded, limit_type = exceeds_recompile_limit(cache_size, compile_id) + if exceeded: + + def format_func_info(code: CodeType) -> str: + return f"'{code.co_name}' ({code.co_filename}:{code.co_firstlineno})" + + # NS: Don't add period at the end of string, as it'll be added to URL + # rendering it incorrect + log.warning( + "torch._dynamo hit config.%s (%s)\n" + " function: %s\n" + " last reason: %s\n" + 'To log all recompilation reasons, use TORCH_LOGS="recompiles".\n' + "To diagnose recompilation issues, see %s", + limit_type, + getattr(config, limit_type), + format_func_info(code), + recompile_reason, + troubleshooting_url, + ) + + def raise_unimplemented_cache_limit_exceeded() -> NoReturn: + unimplemented( + gb_type="Dynamo recompile limit exceeded", + context=f"Limit type: {limit_type}", + explanation="Dynamo attempted to recompile the code object too many times, " + f"exceeding the {limit_type} cache size limit (currently set to {getattr(config, limit_type)}). " + "Excessive recompilations can degrade " + "performance due to the compilation overhead of each recompilation.", + hints=[ + "To monitor recompilations, enable TORCH_LOGS=recompiles. " + "If recompilations are expected, consider " + f"increasing torch._dynamo.config.{limit_type} to an appropriate value.", + f"See {troubleshooting_url} for tips on dealing with recompilations.", + ], + ) + + try: + raise_unimplemented_cache_limit_exceeded() + except Unsupported as e: + if config.fail_on_recompile_limit_hit: + raise FailOnRecompileLimitHit( + "Hard failure due to fail_on_recompile_limit_hit" + ) from e + elif one_graph: + raise FailOnRecompileLimitHit( + "Hard failure due to fullgraph=True" + ) from e + else: + # Set frame execution strategy to RUN_ONLY for this recompile limit case + e.frame_exec_strategy = FrameExecStrategy( + FrameAction.RUN_ONLY, FrameAction.RUN_ONLY + ) + raise + + log.debug( + "torchdynamo start compiling %s %s:%s, stack (elided %s frames):\n%s", + code.co_name, + code.co_filename, + code.co_firstlineno, + skip + 2, + # -2: omit current frame, omit contextlib decorator + "".join(CapturedTraceback.extract(skip=2 + skip).format()), + ) + # -4: -2 as above, plus trace_structured frames + # + # NB: the frame looks like this: + # + # # handled by skip argument + # torch/_dynamo/convert_frame.py:1069 in catch_errors + # torch/_dynamo/convert_frame.py:910 in _convert_frame + # torch/_dynamo/convert_frame.py:464 in _convert_frame_assert + # torch/_utils_internal.py:70 in wrapper_function + # + # # 2 current frame and context lib + # env/lib/python3.10/contextlib.py:79 in inner + # torch/_dynamo/convert_frame.py:776 in _compile + # + # # 2 extra here + # torch/_logging/_internal.py:1064 in trace_structured + # torch/_dynamo/convert_frame.py:780 in + stack_trace = log_dynamo_start(code, skip) + start_time_ns = time.time_ns() + fail_type: str | None = None + fail_reason: str | None = None + exception_stack_trace: list[str] | None = None + fail_user_frame_filename: str | None = None + fail_user_frame_lineno: int | None = None + torch._dynamo.utils.ReinplaceCounters.clear() + guarded_code = None + tracer_output = None + + if ( + config.debug_backend_override + or config.debug_dynamo_config_override + or config.debug_inductor_config_override + ): + # Eagerly validate config override strings before entering the + # compilation try/except so that typos surface as clean ValueErrors + # instead of being wrapped as InternalTorchDynamoError. + from .graph_id_filter import ( + _validate_backend_names, + _validate_dynamo_config_keys, + _validate_inductor_config_keys, + ) + + if err := _validate_backend_names(config.debug_backend_override): + raise ValueError(err) + if err := _validate_dynamo_config_keys(config.debug_dynamo_config_override): + raise ValueError(err) + if err := _validate_inductor_config_keys( + config.debug_inductor_config_override + ): + raise ValueError(err) + + try: + guarded_code, tracer_output = compile_inner(code, one_graph, hooks) + + # NB: We only put_code_state in success case. Success case here + # does include graph breaks; specifically, if a graph break still + # resulted in a partially compiled graph, we WILL return here. An + # Unsupported exception will only bubble to the top level if we + # are unable to compile the frame at all. In this case, there's + # no point in uploading the code state, because we will always + # fail exactly the same way even without the update. (It's useful + # to upload for graph break though, because this can prevent + # extra graph break compilations.) + put_code_state() + if ( + tracer_output + and (output_graph := tracer_output.output_graph) + and output_graph.has_outputs() + ): + log_frame_dynamic_whitelist(code) + if recompile_reason and "size mismatch at index" in recompile_reason: + _log_size_mismatch_recompile() + + clear_compile_context_weakrefs(tracer_output, compiler_fn) + return guarded_code + except Exception as e: + # NB: e's msg is mutated here to add user stack, but we DON'T want + # that stack in the Scuba logged fail_reason. So we grab the fail + # info here and add it to the metrics context below. + fail_type = type(e).__qualname__ + fail_reason = str(e) + exception_stack_trace = [traceback.format_exc()] + exception_handler(e, code, frame, export=export) + # NB: this is the post-mutation exception + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_error", + "encoding": "string", + }, + payload_fn=lambda: traceback.format_exc(), + ) + fail_user_frame_filename, fail_user_frame_lineno = exc.get_exc_message( + e, compile_id + ) + tracer_output = getattr(e, "_torch_dynamo_tracer_output", None) + if isinstance( + e, + ( + Unsupported, + UserError, + TorchRuntimeError, + BackendCompilerFailed, + AssertionError, + IndexError, # dim out-of-range from canonicalize_dim/maybe_wrap_dim + ConstraintViolationError, + GuardOnDataDependentSymNode, + ValidationException, + UncapturedHigherOrderOpError, + BisectValidationException, + ShortenTraceback, + PackageError, + ResumePrologueTracingError, + ), + ): + raise + else: + # Rewrap for clarity + raise InternalTorchDynamoError( + f"{type(e).__qualname__}: {str(e)}" + ).with_traceback(e.__traceback__) from None + finally: + # === WARNING WARNING WARNING === + # If you commit a bug here, it will suppress writing to + # dynamo_compile table, and we will not have telemetry. + # Be extra careful when making changes here! + + if torch._dynamo.config.run_gc_after_compile: + with dynamo_timed("gc", dynamo_compile_column_us="gc_time_us"): + log.info("run_gc_after_compile: running gc") + gc.collect(1) + + output = None + if tracer_output: + output = tracer_output.output_graph + if output: + # pyrefly: ignore [implicit-any] + output.local_scope = {} + # tracer should already be None, keep an extra check here just in case. + if tracer := output.root_tx: + # pyrefly: ignore [implicit-any] + tracer.f_locals = {} + + from .utils import curr_frame + + frame_key = str(curr_frame) + if fail_reason is None and output is not None: + guard_count = len(output.guards) + shape_env_guard_count = len(output.shape_env.guards) + graph_op_count = output.count_calls() + graph_node_count = len(output.graph.nodes) + graph_node_shapes = output.get_graph_sizes_structured() + graph_input_count = len(output.placeholders) + non_compliant_ops = {op.__qualname__ for op in output.non_compliant_ops} + compliant_custom_ops = { + op.__qualname__ for op in output.compliant_custom_ops + } + torch._dynamo.utils.ReinplaceCounters.log() + else: + guard_count = None + shape_env_guard_count = None + graph_op_count = None + graph_node_count = None + # pyrefly: ignore [implicit-any] + graph_node_shapes = {} + graph_input_count = None + non_compliant_ops = set({}) + compliant_custom_ops = set({}) + restart_reasons = set() + # If compilation failed, the entire time is wasted + dynamo_time_before_restart = (time.time_ns() - start_time_ns) / 1e9 + + metrics = { + "frame_key": frame_key, + "co_name": code.co_name, + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + "cache_size": cache_size.num_cache_entries_with_same_id_matched_objs, + "accumulated_cache_size": cache_size.num_cache_entries, + "guard_count": guard_count, + "shape_env_guard_count": shape_env_guard_count, + "graph_op_count": graph_op_count, + "graph_node_count": graph_node_count, + "graph_input_count": graph_input_count, + "fail_type": fail_type, + "fail_reason": fail_reason, + "fail_user_frame_filename": fail_user_frame_filename, + "fail_user_frame_lineno": fail_user_frame_lineno, + "non_compliant_ops": non_compliant_ops, + "compliant_custom_ops": compliant_custom_ops, + "restart_reasons": restart_reasons, + "dynamo_time_before_restart_s": dynamo_time_before_restart, + "has_guarded_code": guarded_code is not None, + "specialize_float": config.specialize_float, + "is_forward": True, + "dynamo_compile_time_before_restart_us": to_int_us( + dynamo_time_before_restart + ), + "stack_trace": stack_trace, + "graph_node_shapes": str(graph_node_shapes), + "exception_stack_trace": exception_stack_trace, + } + # TODO: replace with CompileEventLogger.compilation_metrics + # There are some columns here not in PT2 Compile Events + # so we need to slightly change it + metrics_context.update_outer(metrics) + # === END WARNING WARNING WARNING === + + # If tracer is available, then tracer.error_on_graph_break reflects value of + # global symbolic_convert.error_on_graph_break at the time of the graph break - + # symbolic_convert.error_on_graph_break may have been (correctly) changed during cleanup. + # If tracer is unavailable, then fallback to symbolic_convert.error_on_graph_break. + if convert_frame_box: + convert_frame_box.error_on_graph_break = ( + tracer_output.error_on_graph_break + if tracer_output + else _get_error_on_graph_break() + ) + + # Cleanup guards unless if in export, which will return guards + # Make sure to do this after collecting metrics + if ( + tracer_output is not None + and tracer_output.output_graph is not None + and not tracer_output.output_graph.export + ): + tracer_output.output_graph.tracing_context.guards_context.dynamo_guards.clear() + + clear_compile_context_weakrefs(tracer_output, compiler_fn) + + +class ConvertFrame: + def __init__( + self, + compiler_fn: CompilerFn, + hooks: Hooks, + package: CompilePackage | None = None, + recompile_limit: int | None = None, + ) -> None: + self._torchdynamo_orig_backend = compiler_fn + self._inner_convert = convert_frame_assert( + compiler_fn, + one_graph=False, + package=package, + recompile_limit=recompile_limit, + ) + self._hooks = hooks + self._recompile_limit = recompile_limit + + @property + def _clone_with_backend(self) -> Callable[[WrapBackendDebug], ConvertFrame]: + # Used by DDPOptimizer to swap in its own backend. + return lambda backend: convert_frame( + backend, + self._hooks, + recompile_limit=self._recompile_limit, + ) + + def __call__( + self, + frame: DynamoFrameType, + cache_entry: CacheEntry | None, + hooks: Hooks, + frame_state: dict[str, int | FrameStateSizeEntry], + skip: int = 0, + ) -> ConvertFrameReturn: + input_codes.add(frame.f_code) + counters["frames"]["total"] += 1 + try: + result = self._inner_convert( + frame, cache_entry, hooks, frame_state, skip=skip + 1 + ) + counters["frames"]["ok"] += 1 + return result + except Exception as e: + # Do not allow errors to be suppressed if we're tracing a resume function prologue + if isinstance(e, ResumePrologueTracingError): + raise + + error_on_graph_break = ( + self._inner_convert._box.error_on_graph_break is not None + ) + if error_on_graph_break is None: + raise AssertionError("error_on_graph_break must not be None") from None + if self._inner_convert._box.error_on_graph_break: + # NOTE we _might_ have to wrap the current in a custom exception + # in order to correctly bubble up to the top-level compile wrapper in + # eval_frame.py. But re-raising seems to work for now because exceptions from tracing + # a nested call that results in a top-level frame compile will be handled by the caller + # as an observed exception - we don't expect that exception to be suppressed. + raise + + # These two exception types are "soft" failure, in the sense that + # we know this is due to something we didn't implement all the + # way, scare the user less about it. That being said, if you + # are trying to understand why a graph break happened, it's still + # important to have this information, so offer it. + # + # NB: NotImplementedError used to be on this list, but actually + # it is impossible for it to reach here, as it is converted into + # InternalTorchDynamoError. This behavior seemed reasonable + # to me (ezyang, Aug 2023) so I kept it, but maybe at some point + # someone wanted these to also get suppressed. If so, you'll + # need to make these exceptions not get wrapped + + # We intentionally don't want to suppress error here. + if isinstance(e, UncapturedHigherOrderOpError): + raise + + soft_fail = isinstance(e, (Unsupported, UserError)) + code = frame.f_code + # Log soft failure that was not already logged by symbolic_convert. + # This happens e.g. for graph breaks that are raised in convert_frame.py + # TODO(williamwen42) Unsupported exn's from tracing are handled and logged by symbolic_convert.py + # Unsupported exn's caught here should be from convert_frame.py - figure out a better way + # to log these. + if ( + soft_fail + and not getattr(e, "logged", False) + and graph_break_log.isEnabledFor(logging.DEBUG) + ): + # Log this message in the graph break. Also use the string + # "skip: " to tell that the whole frame is falling back to + # eager. + if hasattr(e, "compile_id") and hasattr(e, "real_stack"): + with compile_context(CompileContext(e.compile_id)): # type: ignore[attr-defined] + user_stack = e.real_stack + user_stack_formatted = "".join( + traceback.format_list(user_stack) + ) + frame_info = exc.format_frame_info(code) + user_stack_trace = ( + "Graph break: torch.compile cannot properly resume from this graph break, which results in a skip.\n" + f"torch.compile will skip tracing the frame {frame_info} and fall back to eager.\n" + "The graph break occurred in the following user code:\n" + f"{user_stack_formatted}" + ) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_graph_break_reason", + "encoding": "string", + }, + payload_fn=lambda: f"{user_stack_trace}\n{traceback.format_exc()}", + ) + graph_break_log.debug( + user_stack_trace, + exc_info=True, + stack_info=config.verbose, + ) + + if not config.suppress_errors and not soft_fail: + raise + + # Suppress the error. NB: It's very important to do the + # suppression logging HERE, where the actual suppression + # happens. Previously it was somewhere else and so it was + # possible to accidentally not log at all. + record_filename = getattr(e, "record_filename", None) + code = frame.f_code + error_msg = format_error_msg(e, code, record_filename, frame) + + if soft_fail: + log.info(error_msg, exc_info=True) + else: + log.warning(error_msg, exc_info=True) + + # Check if the exception has a specific frame execution strategy + if ( + isinstance(e, exc.TorchDynamoException) + and e.frame_exec_strategy is not None + ): + return ConvertFrameReturn( + frame_exec_strategy=e.frame_exec_strategy, + skip_reason="compilation failed with a custom frame execution strategy", + ) + + return ConvertFrameReturn( + skip_reason="an error was suppressed during compilation" + ) + + +def convert_frame( + compiler_fn: CompilerFn, + hooks: Hooks, + package: CompilePackage | None = None, + recompile_limit: int | None = None, +) -> ConvertFrame: + """Try to convert a frame into an FX graph, if error leave frame unmodified""" + return ConvertFrame( + compiler_fn, + hooks, + package=package, + recompile_limit=recompile_limit, + ) + + +# TODO mlazos: add support for same args, or record them +def replay(filename: str) -> None: + from .backends.debugging import eager + + original_replay_val = config.replay_record_enabled + config.replay_record_enabled = False + with open(filename, "rb") as in_file: + record = ExecutionRecord.load(in_file) + record.globals = dict(itertools.chain(record.globals.items(), globals().items())) + + with decorators.error_on_graph_break(False): + try: + _compile( + record.code, + record.globals, + record.locals, + record.builtins, + record.closure, + compiler_fn=eager, + one_graph=False, + export=False, + export_constraints=None, + hooks=Hooks(), + cache_entry=None, + cache_entries=[], + cache_entries_for_reasons=[], + cache_size=CacheSizeRelevantForFrame(0, 0), + frame=None, + frame_state={}, + compile_id=CompileId(frame_id=42, frame_compile_id=999), + ) + finally: + config.replay_record_enabled = original_replay_val + + +def first_real_inst_idx(code: CodeType) -> int: + if sys.version_info < (3, 11): + return 0 + for inst in dis.get_instructions(code): + if inst.opname == "RESUME": + return inst.offset // 2 + raise RuntimeError("RESUME instruction not found in code") + + +class ConvertFrameProtocol(typing.Protocol): + def __call__( + self, + frame: DynamoFrameType, + cache_entry: CacheEntry | None, + hooks: Hooks, + frame_state: dict[str, int | FrameStateSizeEntry], + *, + skip: int = 0, + ) -> ConvertFrameReturn: ... + + +class CatchErrorsWrapper: + def __init__(self, callback: ConvertFrameProtocol, hooks: Hooks) -> None: + functools.wraps(callback)(self) + self._torchdynamo_orig_backend = callback + self.hooks = hooks + + def _handle_skip( + self, result: ConvertFrameReturn, frame: DynamoFrameType + ) -> ConvertFrameReturn: + if result.skip_reason is not None and result.guarded_code is None: + log.debug( + "skipping: %s (reason: %s, file: %s)", + frame.f_code.co_name, + result.skip_reason, + frame.f_code.co_filename, + ) + add_skip_reason(result.skip_reason, frame) + return result + + def __call__( + self, + frame: DynamoFrameType, + cache_entry: CacheEntry | None, + frame_state: dict[str, int | FrameStateSizeEntry], + ) -> ConvertFrameReturn: + if frame_state is None: + raise AssertionError("frame_state must not be None") + input_codes.add(frame.f_code) + + is_skipfile = trace_rules.check(frame.f_code, frame=frame) + if sys.version_info >= (3, 13): + has_started_execution = frame.f_lasti > first_real_inst_idx(frame.f_code) + else: + has_started_execution = frame.f_lasti >= first_real_inst_idx(frame.f_code) + + # Check if we should skip due to torch dispatch mode. + # When inline_torch_dispatch_torch_compile is True (new behavior), we walk + # the stack to check for active modes. When False (old behavior), we use + # the global flag that tracks if we're inside any mode. + if config.inline_torch_dispatch_torch_compile: + should_skip_for_dispatch_mode = any_torch_dispatch_mode_on_stack() + else: + should_skip_for_dispatch_mode = ( + is_in_any_mode_without_ignore_compile_internals() + ) + + if ( + # TODO: the first condition is not covered by any test + has_started_execution + or is_skipfile + or config.disable + or ( + should_skip_for_dispatch_mode + and not getattr(self._torchdynamo_orig_backend, "_export", False) + ) + ): + apply_to_code = True + if has_started_execution: + skip_reason = "frame has already started executing" + elif is_skipfile: + skip_reason = "frame is in the Dynamo skipfiles list" + elif config.disable: + skip_reason = "Dynamo tracing is disabled" + else: + skip_reason = ( + "non-infra torch dispatch mode present, this is not" + " supported today in torch.compile" + ) + apply_to_code = False + return self._handle_skip( + ConvertFrameReturn( + apply_to_code=apply_to_code, skip_reason=skip_reason + ), + frame, + ) + + if ( + frame.f_code.co_filename == "" and frame.f_code.co_name == "__new__" + ) or ( + frame.f_code.co_filename.endswith("collections/__init__.py") + and frame.f_code.co_name == "_make" + ): + return self._handle_skip( + ConvertFrameReturn( + skip_reason="frame is a namedtuple __new__/_make constructor" + ), + frame, + ) + + if ( + frame.f_code.co_name == "__init__" + and frame.f_code.co_argcount > 0 + and frame.f_code.co_varnames + and is_traceable_wrapper_subclass( + frame.f_locals.get(frame.f_code.co_varnames[0]) + ) + ): + return self._handle_skip( + ConvertFrameReturn( + skip_reason="__init__ of a traceable wrapper subclass cannot be traced" + ), + frame, + ) + + if torch._dynamo.utils.get_optimize_ddp_mode() == "ddp_optimizer": + ddp_module = DistributedDataParallel._get_active_ddp_module() + if ddp_module: + with compile_lock: + from torch._dynamo.backends.distributed import DDPOptimizer + + ddp_optimizer = DDPOptimizer( + bucket_bytes_cap=ddp_module.bucket_bytes_cap, + backend_compile_fn=self._torchdynamo_orig_backend._torchdynamo_orig_backend, # type: ignore[attr-defined] + ) + if not hasattr( + self._torchdynamo_orig_backend, "_clone_with_backend" + ): + raise AssertionError( + "DDPOptimizer only supports callback fns that know how to clone themselves." + ) + hijacked_callback = ( + self._torchdynamo_orig_backend._clone_with_backend( + ddp_optimizer.compile_fn, + ) + ) + return self._handle_skip( + hijacked_callback(frame, cache_entry, self.hooks, frame_state), + frame, + ) + + with compile_lock, _disable_current_modes(): + # skip=1: skip this frame + result = self._torchdynamo_orig_backend( + frame, cache_entry, self.hooks, frame_state, skip=1 + ) + return self._handle_skip(result, frame) + + +def catch_errors_wrapper( + callback: ConvertFrameProtocol, hooks: Hooks +) -> CatchErrorsWrapper: + return CatchErrorsWrapper(callback, hooks) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/create_parameter_op.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/create_parameter_op.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2481ffda7713de95678ffc1bf50e3ccec39a1d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/create_parameter_op.py @@ -0,0 +1,70 @@ +import threading +from collections.abc import Generator +from contextlib import contextmanager +from typing import Any + +import torch + + +# See [Note: Metadata mutation in proxy tracing] for why sacrificial parameter mutates +# metadata during proxy tracing and we should remove the sacrificial parameter logic. +doc = """ +This is used when dynamo traces torch.nn.Parameter, which normally would not trace properly +with AOTAutograd. We instead create a placeholder torch.nn.Parameter before the graph, which +becomes a graph arg and has no storage backing it. At the point in the graph where the parameter +actually should be created we mutate this sacrificial placeholder into it. This allows gradients +to flow into the parameter as if it were an input to the graph (which is the only thing we are +allowed to compute gradients on). +""".strip() + + +class TracableCreateParameter(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx: Any, tensor: Any, placeholder: Any) -> torch.nn.Parameter: + if tensor.requires_grad: + tensor = tensor.detach() + return placeholder.set_(tensor) + + @staticmethod + def backward(ctx: Any, *grad_outputs: torch.Tensor) -> tuple[None, torch.Tensor]: + grad = grad_outputs[0] + return None, grad # grad flows to placeholder + + +def tracable_create_parameter( + tensor: torch.Tensor, placeholder: torch.nn.Parameter +) -> torch.nn.Parameter: + with torch.set_grad_enabled(placeholder.requires_grad): + out = TracableCreateParameter.apply(tensor, placeholder) + return out + + +def new_parameter_placeholder( + size: tuple[int, ...], dtype: torch.dtype, device: torch.device, requires_grad: bool +) -> torch.nn.Parameter: + """Create a placeholder to be passed to the above functions""" + result = torch.nn.Parameter( + torch.empty(size, dtype=dtype, device=device), requires_grad=requires_grad + ) + # TODO(jansel): alloc followed by free is inefficient, need a way to allocate an unbacked tensor. + # Allocating a zero tensor would cause assert failures in autograd. + result.untyped_storage().resize_(0) + return result + + +_TLS = threading.local() + + +@contextmanager +def do_not_convert_to_tracable_parameter() -> Generator[bool, None, None]: + old_flag = getattr(_TLS, "convert_tracable_parameter", True) + _TLS.convert_tracable_parameter = False + try: + yield False + finally: + _TLS.convert_tracable_parameter = old_flag + + +def can_convert_to_tracable_parameter() -> bool: + return getattr(_TLS, "convert_tracable_parameter", True) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/current_scope_id.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/current_scope_id.py new file mode 100644 index 0000000000000000000000000000000000000000..74a5f4888c64629f3225118d91b52ba05e000ce0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/current_scope_id.py @@ -0,0 +1,42 @@ +""" +Provides thread-local scope identification for SubgraphTracer instances. + +This module implements a thread-safe mechanism for tracking nested tracing contexts, +which is essential when multiple SubgraphTracer instances are active. The scope ID +helps identify which tracer context is currently active when direct access to the +InstructionTranslator is difficult. + +Key components: +- Thread-local scope ID storage (_current_scope_id) +- Getter function (current_scope_id) to safely access the current scope +- Context manager (enter_new_scope) for managing nested scope transitions + +The scope ID increments when entering a new context and decrements when exiting, +allowing proper tracking of nested tracing operations across different threads. +""" + +import contextlib +import threading +from collections.abc import Generator + + +# Global variable to identify which SubgraphTracer we are in. +# It is sometimes difficult to find an InstructionTranslator to use. +_current_scope_id = threading.local() + + +def current_scope_id() -> int: + global _current_scope_id + if not hasattr(_current_scope_id, "value"): + _current_scope_id.value = 1 + return _current_scope_id.value + + +@contextlib.contextmanager +def enter_new_scope() -> Generator[None, None, None]: + global _current_scope_id + try: + _current_scope_id.value = current_scope_id() + 1 + yield + finally: + _current_scope_id.value = current_scope_id() - 1 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/dce_extra_outputs.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/dce_extra_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..4650d3de710481f0f37a7da37e6d1cabd454a305 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/dce_extra_outputs.py @@ -0,0 +1,228 @@ +""" +DCE pass for unused extra outputs in HOP subgraphs. + +When enable_side_effects_with_extra_outputs is True, HOPs like invoke_subgraph and +checkpoint (tag_activation_checkpoint) +return all intermediate tensors/symints as extra outputs to support side effects. +However, many of these extra outputs may not actually be used in the parent graph. + +This pass removes unused extra outputs by: +1. Collecting all callers for each subgraph +2. Checking if each output is used by all callers +3. Removing unused outputs from the subgraph's output node +4. Updating the HOP call and getitem indices in all call sites + +""" + +import collections +import operator + +import torch + + +# HOPs that may have extra outputs that can be DCE'd +_HOPS_WITH_EXTRA_OUTPUTS = { + torch.ops.higher_order.invoke_subgraph, + torch.ops.higher_order.tag_activation_checkpoint, + # torch.ops.higher_order.autograd_function_apply, +} + + +def dce_hop_extra_outputs(gm: torch.fx.GraphModule) -> bool: + """ + Remove unused extra outputs from HOP calls in all submodules. + + For each subgraph output, check if any caller has a getitem for that index + with users. If no caller uses it, remove the output. + If the user in caller is an output node, to simplify the algorithm, we do not recursively check + if the caller's output is used further up in the call chain. + + Args: + gm: The GraphModule to optimize + + Returns: + True if any modifications were made, False otherwise + """ + # Collect all subgraph usages: subgraph_id -> list of (parent_gm, subgraph_name, hop_node) + subgraph_id_to_callers: dict[ + int, list[tuple[torch.fx.GraphModule, str, torch.fx.Node]] + ] = collections.defaultdict(list) + _collect_all_subgraph_usages(gm, subgraph_id_to_callers) + + if not subgraph_id_to_callers: + return False + + modified = False + + for callers in subgraph_id_to_callers.values(): + parent_gm, subgraph_name, _ = callers[0] + subgraph = getattr(parent_gm, subgraph_name) + + if not isinstance(subgraph, torch.fx.GraphModule): + continue + + output_node = next(n for n in subgraph.graph.nodes if n.op == "output") + output_args = output_node.args[0] + if not isinstance(output_args, (tuple, list)): + continue + + num_outputs = len(output_args) + used_indices: set[int] = set() + + # Check which outputs are used by any caller + for idx in range(num_outputs): + if _is_output_used(idx, callers): + used_indices.add(idx) + + # DCE if some outputs are unused + if 0 < len(used_indices) < num_outputs: + if _dce_subgraph(subgraph, callers, used_indices): + modified = True + + return modified + + +def _collect_all_subgraph_usages( + gm: torch.fx.GraphModule, + subgraph_id_to_callers: dict[ + int, list[tuple[torch.fx.GraphModule, str, torch.fx.Node]] + ], +) -> None: + """Recursively collect all HOP usages across the graph tree.""" + for node in gm.graph.nodes: + if node.op == "call_function" and node.target in _HOPS_WITH_EXTRA_OUTPUTS: + subgraph_attr = node.args[0] + if ( + isinstance(subgraph_attr, torch.fx.Node) + and subgraph_attr.op == "get_attr" + ): + subgraph_name = subgraph_attr.target + if not isinstance(subgraph_name, str): + raise AssertionError( + f"Expected subgraph_name to be str, got {type(subgraph_name)}" + ) + subgraph = getattr(gm, subgraph_name, None) + if isinstance(subgraph, torch.fx.GraphModule): + subgraph_id = id(subgraph) + subgraph_id_to_callers[subgraph_id].append( + (gm, subgraph_name, node) + ) + _collect_all_subgraph_usages(subgraph, subgraph_id_to_callers) + + +def _is_output_used( + output_idx: int, + callers: list[tuple[torch.fx.GraphModule, str, torch.fx.Node]], +) -> bool: + """Check if output_idx is used by ANY caller (has a getitem with users).""" + for _parent_gm, _subgraph_name, hop_node in callers: + for user in hop_node.users: + if user.op == "call_function" and user.target == operator.getitem: + if user.args[1] == output_idx and len(user.users) > 0: + return True + return False + + +def _dce_subgraph( + subgraph: torch.fx.GraphModule, + callers: list[tuple[torch.fx.GraphModule, str, torch.fx.Node]], + used_indices: set[int], +) -> bool: + """ + DCE a subgraph by removing unused output indices. + + Updates the subgraph's output node, all getitem nodes in callers, + and example_value metadata on HOP nodes. + """ + output_node = next(n for n in subgraph.graph.nodes if n.op == "output") + old_outputs = list(output_node.args[0]) + + # Check if this is the forward subgraph of autograd_function_apply + # For autograd_function_apply, the fwd subgraph must return (output, saved_values, ...) + # where indices 0 and 1 are ALWAYS required by the runtime + # is_autograd_fwd = any( + # node.target == torch.ops.higher_order.autograd_function_apply + # for node in hop_nodes + # ) + is_autograd_fwd = False + + # For autograd_function_apply forward subgraph, indices 0 (output) and 1 (saved_values) + # are ALWAYS used by the runtime, even if not explicitly accessed via getitem + if is_autograd_fwd and len(old_outputs) >= 2: + used_indices.add(0) # output + used_indices.add(1) # saved_values + + # Nothing to DCE if all outputs are used or no outputs are used + if len(used_indices) >= len(old_outputs) or len(used_indices) == 0: + return False + + # Build mapping from old indices to new indices + old_to_new: dict[int, int] = {} + new_outputs = [] + new_idx = 0 + + for old_idx in range(len(old_outputs)): + if old_idx in used_indices: + old_to_new[old_idx] = new_idx + new_outputs.append(old_outputs[old_idx]) + new_idx += 1 + + # Update subgraph output node + # Create a new output node with the filtered outputs + with subgraph.graph.inserting_before(output_node): + new_output_node = subgraph.graph.output(tuple(new_outputs)) + output_node.replace_all_uses_with(new_output_node) + subgraph.graph.erase_node(output_node) + + for parent_gm, _, hop_node in callers: + # Update getitem nodes to use new indices + for user in list(hop_node.users): + if user.op == "call_function" and user.target == operator.getitem: + old_idx = user.args[1] + if not isinstance(old_idx, int): + raise AssertionError( + f"Expected getitem index to be int, got {type(old_idx)}" + ) + + if old_idx not in old_to_new: + if len(list(user.users)) != 0: + raise AssertionError( + f"Expected unused getitem node at index {old_idx} to have no users" + ) + parent_gm.graph.erase_node(user) + continue + + new_idx = old_to_new[old_idx] + # Create a new getitem node with the new index + with parent_gm.graph.inserting_before(user): + new_getitem = parent_gm.graph.call_function( + operator.getitem, args=(user.args[0], new_idx) + ) + # Copy metadata from old node + new_getitem.meta = user.meta.copy() + user.replace_all_uses_with(new_getitem) + parent_gm.graph.erase_node(user) + + # Update example_value metadata on hop_node + if "example_value" in hop_node.meta: + old_example = hop_node.meta["example_value"] + if not isinstance(old_example, (tuple, list)): + raise AssertionError( + f"Expected example_value to be tuple or list, got {type(old_example)}" + ) + new_example = tuple( + old_example[old_idx] + for old_idx in range(len(old_outputs)) + if old_idx in used_indices + ) + hop_node.meta["example_value"] = new_example + + # Recompile subgraph and all modified parent graphs + subgraph.graph.lint() + subgraph.recompile() + + for parent_gm in {caller[0] for caller in callers}: + parent_gm.graph.lint() + parent_gm.recompile() + + return True diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/debug_utils.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/debug_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e9b9dac5da5249d04e5af18033cae97d61473924 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/debug_utils.py @@ -0,0 +1,1238 @@ +""" +Debug utilities for TorchDynamo compilation and execution. + +This module provides various debugging tools and utilities for TorchDynamo, including: + +- Minification support for reducing test cases while preserving bugs +- Input/output handling via InputReader and InputWriter for reproducible testing +- Accuracy checking between original and compiled models +- Neural network module string conversion via NNModuleToString +- Profiling tools and system information collection +- Buck build system integration for Meta-internal testing + +Key classes: +- InputReader/InputWriter: Handle serialization of model inputs/outputs +- NNModuleToString: Converts nn.Modules to string representations +- BuckTargetWriter: Manages Buck build system integration +""" + +from __future__ import annotations + +import atexit +import copy +import cProfile +import functools +import getpass +import inspect +import itertools +import logging +import os +import re +import subprocess +import sys +import tempfile +import textwrap +from collections import Counter +from importlib import import_module +from typing import Any, cast, TYPE_CHECKING, TypeVar + +import torch +import torch._prims_common as utils +import torch._subclasses.meta_utils +from torch import Tensor +from torch._dynamo.testing import rand_strided +from torch._inductor.cpp_builder import normalize_path_separator +from torch._prims_common import is_float_dtype +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._config_module import ConfigModule +from torch.utils._content_store import ContentStoreReader, ContentStoreWriter + +from . import config +from .utils import clone_inputs, get_debug_dir, warn_once + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from torch.hub import tqdm + from torch.storage import UntypedStorage + + +log = logging.getLogger(__name__) + +T = TypeVar("T") + + +inductor_config = import_module("torch._inductor.config") +use_buck = inductor_config.is_fbcode() + +if use_buck: + import libfb.py.build_info + + +# pyrefly: ignore [implicit-any] +extra_deps = [] +extra_imports = "" +cur_target = "" +if use_buck: + extra_deps = [ + "//caffe2/torch/fb/sparsenn:sparsenn_operators_gpu", + "//caffe2/torch/fb/sparsenn:sparsenn_operators", + "//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpu", + "//deeplearning/fbgemm/fbgemm_gpu:sparse_ops", + ] + cur_target = libfb.py.build_info.BuildInfo.get_build_rule().replace("fbcode:", "//") # type: ignore[possibly-undefined] + # Preload common fbcode custom-op libraries so repros that use those ops + # work out of the box. Best-effort: a repro whose graph doesn't use these + # ops (or that is run outside a buck target linking them) must not fail + # just because the library isn't present. + _extra_deps_list = "\n".join(f' "{x}",' for x in extra_deps) + extra_imports = ( + f"for _extra_dep in [\n{_extra_deps_list}\n]:\n" + " try:\n" + " torch.ops.load_library(_extra_dep)\n" + " except OSError:\n" + " pass\n" + ) + + +BUCK_CMD_PREFIX = ["buck2", "run", "@mode/dev-nosan"] + + +class BuckTargetWriter: + def __init__(self, filename: str) -> None: + self.subdir, self.py_file = os.path.split(os.path.abspath(filename)) + self.target = self.py_file.replace(".py", "") + + # Get main_module path from fbcode + self.path = f"{self.subdir.replace('/', '.')}.{self.target}" + self.path = self.path[self.path.find("fbcode.") :] + self.path = self.path[7:] + + # Get cmd line path + tmp = self.subdir + tmp = tmp[tmp.find("fbcode/") :][7:] + self.cmd_line_path = f"//{tmp}:{self.target}" + + def build(self) -> str: + extra_cpp_deps = "\n".join([f' "{x}",' for x in extra_deps]) + return textwrap.dedent( + f""" +load("@fbcode_macros//build_defs:python_binary.bzl", "python_binary") + +python_binary( + name="{self.target}", + srcs = ["{self.py_file}"], + compile = False, + deps = [ + "//caffe2:torch", + "//caffe2:libtorch", + "//caffe2/functorch:functorch", + "//triton:triton", + "{cur_target}", + ], + cpp_deps = [ +{extra_cpp_deps} + ], + main_module = "{self.path}", + par_style = "xar", +) +""" + ) + + def write(self, print_msg: bool = True) -> list[str]: + target_file = os.path.join(self.subdir, "TARGETS") + with open(target_file, "w") as fd: + fd.write(self.build()) + # log.warning("Wrote isolation TARGETS file at %s", target_file) + cmd_split = BUCK_CMD_PREFIX + [self.cmd_line_path] + if print_msg: + log.warning( + "Found an example that reproduces the error. Run this cmd to repro - %s", + " ".join(cmd_split), + ) + return cmd_split + + +def minifier_dir() -> str: + path = os.path.join(get_debug_dir(), "minifier") + if path is None: + path = f"{tempfile.gettempdir()}/minifier_{getpass.getuser()}" + if not os.path.exists(path): + os.makedirs(path, exist_ok=True) + return path + + +MAX_CONSTANT_NUMEL_INLINE = 4 + + +class UnsupportedNNModuleError(AssertionError): + pass + + +class NNModuleToString: + fake_quant_modules = { + "torch.ao.quantization.fake_quantize.FakeQuantize", + "torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize", + } + + qat_conv_modules = { + "torch.ao.nn.qat.modules.conv.Conv1d", + "torch.ao.nn.qat.modules.conv.Conv2d", + "torch.ao.nn.qat.modules.conv.Conv3d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBn1d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBn2d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBn3d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU1d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU3d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvReLU1d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvReLU3d", + } + + qat_linear_modules = { + "torch.ao.nn.qat.modules.linear.Linear", + "torch.ao.nn.intrinsic.qat.modules.linear_relu.LinearReLU", + } + + # x86 currently aliases fbgemm in repr, so emit fbgemm as the canonical + # constructor for both until those default qconfigs diverge. + default_qat_qconfig_backends = ("fbgemm", "x86", "qnnpack", "onednn") + + safe_reprs = [ + torch.nn.Linear, + torch.nn.Conv1d, + torch.nn.Conv2d, + torch.nn.Conv3d, + torch.nn.BatchNorm1d, + torch.nn.BatchNorm2d, + torch.nn.BatchNorm3d, + torch.nn.LayerNorm, + torch.nn.Dropout, + torch.nn.Softmax, + torch.nn.ReLU, + torch.nn.GELU, + torch.nn.Identity, + torch.nn.MaxPool2d, + torch.nn.Embedding, + torch.nn.Tanh, + torch.nn.ConvTranspose1d, + torch.nn.GLU, + torch.nn.LSTM, + torch.nn.Flatten, + torch.nn.AdaptiveAvgPool2d, + ] + + @staticmethod + def can_convert_to_string(gm: torch.fx.GraphModule) -> bool: + cant_convert = set() + for _, module in gm.named_children(): + # Nested GraphModules (e.g. torch.cond / torch.while_loop subgraphs) + # are serialized recursively by convert(). + if isinstance(module, torch.fx.GraphModule): + continue + if NNModuleToString._module_constructor_string(module) is None: + cant_convert.add(module) + + if len(cant_convert) > 0: + log.warning( + "Cannot safely convert some modules to strings - %s", cant_convert + ) + return False + return True + + @staticmethod + def _module_type_name(module: torch.nn.Module) -> str: + return f"{type(module).__module__}.{type(module).__name__}" + + @staticmethod + def _type_name(type_: type[object]) -> str: + return f"{type_.__module__}.{type_.__name__}" + + @staticmethod + def _fake_quant_constructor(module: torch.nn.Module) -> str | None: + module_type = NNModuleToString._module_type_name(module) + if module_type not in NNModuleToString.fake_quant_modules: + return None + + observer = module.activation_post_process # type: ignore[attr-defined] + quant_min = cast(int, module.quant_min) # type: ignore[attr-defined] + quant_max = cast(int, module.quant_max) # type: ignore[attr-defined] + if getattr(observer, "reduce_range", False): + quant_min *= 2 + quant_max = quant_max * 2 + 1 + args = [ + f"observer={NNModuleToString._type_name(type(observer))}", + f"quant_min={quant_min!r}", + f"quant_max={quant_max!r}", + f"dtype={module.dtype!r}", # type: ignore[attr-defined] + f"qscheme={module.qscheme!r}", # type: ignore[attr-defined] + f"is_dynamic={module.is_dynamic!r}", # type: ignore[attr-defined] + ] + if hasattr(observer, "reduce_range"): + args.append(f"reduce_range={observer.reduce_range!r}") + if hasattr(observer, "ch_axis"): + args.append(f"ch_axis={observer.ch_axis!r}") + return f"{module_type}({', '.join(args)})" + + @staticmethod + def _qat_qconfig_constructor(module: torch.nn.Module) -> str | None: + qconfig = getattr(module, "qconfig", None) + for backend in NNModuleToString.default_qat_qconfig_backends: + try: + default_qconfig = torch.ao.quantization.get_default_qat_qconfig(backend) + except AssertionError: + continue + if repr(qconfig) == repr(default_qconfig): + return ( + "qconfig=torch.ao.quantization.get_default_qat_qconfig" + f"({backend!r})" + ) + return None + + @staticmethod + def _qat_conv_constructor(module: torch.nn.Module) -> str | None: + module_type = NNModuleToString._module_type_name(module) + if module_type not in NNModuleToString.qat_conv_modules: + return None + qconfig = NNModuleToString._qat_qconfig_constructor(module) + if qconfig is None: + return None + + args = [ + repr(module.in_channels), # type: ignore[attr-defined] + repr(module.out_channels), # type: ignore[attr-defined] + f"kernel_size={module.kernel_size!r}", # type: ignore[attr-defined] + f"stride={module.stride!r}", # type: ignore[attr-defined] + f"padding={module.padding!r}", # type: ignore[attr-defined] + f"dilation={module.dilation!r}", # type: ignore[attr-defined] + f"groups={module.groups!r}", # type: ignore[attr-defined] + f"bias={module.bias is not None}", # type: ignore[attr-defined] + f"padding_mode={module.padding_mode!r}", # type: ignore[attr-defined] + ] + bn = getattr(module, "bn", None) + if bn is not None: + args.extend( + [ + f"eps={bn.eps!r}", + f"momentum={bn.momentum!r}", + f"freeze_bn={module.freeze_bn!r}", # type: ignore[attr-defined] + ] + ) + args.append(qconfig) + return f"{module_type}({', '.join(args)})" + + @staticmethod + def _qat_linear_constructor(module: torch.nn.Module) -> str | None: + module_type = NNModuleToString._module_type_name(module) + if module_type not in NNModuleToString.qat_linear_modules: + return None + qconfig = NNModuleToString._qat_qconfig_constructor(module) + if qconfig is None: + return None + + args = [ + repr(module.in_features), # type: ignore[attr-defined] + repr(module.out_features), # type: ignore[attr-defined] + f"bias={module.bias is not None}", # type: ignore[attr-defined] + qconfig, + ] + return f"{module_type}({', '.join(args)})" + + @staticmethod + def _can_emit_module_constructor(module: torch.nn.Module, module_str: str) -> bool: + if type(module) not in NNModuleToString.safe_reprs: + return False + + try: + compile(f"mod = {module_str}", "", "exec") + except SyntaxError: + return False + return True + + @staticmethod + def _module_constructor_string( + module: torch.nn.Module, *, allow_unsafe_repr: bool = False + ) -> str | None: + module_str = repr(module) + if NNModuleToString._can_emit_module_constructor(module, module_str): + return module_str + constructor_str = ( + NNModuleToString._fake_quant_constructor(module) + or NNModuleToString._qat_conv_constructor(module) + or NNModuleToString._qat_linear_constructor(module) + ) + if constructor_str is not None: + return constructor_str + if allow_unsafe_repr: + return module_str + return None + + @staticmethod + def convert(gm: torch.fx.GraphModule, *, allow_unsafe_repr: bool = False) -> str: + from torch.nn.modules.module import _addindent + + tab = " " * 4 + + # Higher-order ops (torch.cond, torch.while_loop, ...) attach their + # subgraphs as nested GraphModule children. These have no + # constructor-style repr, so serialize each nested GraphModule as its + # own top-level class (defined before Repro so it is in scope) and + # instantiate it in __init__. Leaf nn.Modules use the constructor-string + # path below. + subgraph_classes: dict[int, str] = {} + subgraph_defs: list[str] = [] + + def register_subgraph(name_hint: str, sub: torch.fx.GraphModule) -> str: + # Reserve the name before recursing so nested/shared subgraphs are + # deduplicated by identity and cannot recurse infinitely. + if id(sub) in subgraph_classes: + return subgraph_classes[id(sub)] + class_name = f"{name_hint}_{len(subgraph_classes)}" + subgraph_classes[id(sub)] = class_name + body = emit_module_body(sub) + subgraph_defs.append(f"class {class_name}(torch.nn.Module):\n{body}") + return class_name + + def emit_module_body(module: torch.nn.Module) -> str: + model_str = ( + f"{tab}def __init__(self) -> None:\n{tab * 2}super().__init__()\n" + ) + + for module_name, child in module.named_children(): + if isinstance(child, torch.fx.GraphModule): + class_name = register_subgraph(module_name, child) + model_str += f"{tab * 2}self.{module_name} = {class_name}()\n" + continue + module_str = NNModuleToString._module_constructor_string( + child, allow_unsafe_repr=allow_unsafe_repr + ) + if module_str is None: + raise UnsupportedNNModuleError( + f"Cannot convert module to string: {child!r}" + ) + # module should be a core torch.nn.Module, so all parameters + # and buffers should be on the same device. + example_param = next(child.parameters(), None) + example_tensor = ( + example_param + if example_param is not None + else next(child.buffers(), None) + ) + if example_tensor is not None and example_tensor.device.type != "cpu": + module_str = f'{module_str}.to("{example_tensor.device}")' + model_str += f"{tab * 2}self.{module_name} = {module_str}\n" + + for buffer_name, buffer in module._buffers.items(): + if buffer is None: + continue + # Serialize full data for small buffers + if buffer.numel() <= MAX_CONSTANT_NUMEL_INLINE: + from torch._tensor_str import PRINT_OPTS + + if PRINT_OPTS.threshold < MAX_CONSTANT_NUMEL_INLINE: + raise AssertionError( + f"PRINT_OPTS.threshold ({PRINT_OPTS.threshold}) must be >= " + f"MAX_CONSTANT_NUMEL_INLINE ({MAX_CONSTANT_NUMEL_INLINE})" + ) + tensor_str = repr(buffer) + elif torch.is_floating_point(buffer): + tensor_str = ( + f"torch.randn({list(buffer.shape)}, dtype={buffer.dtype})" + ) + else: + tensor_str = f"torch.randint(1, size={list(buffer.shape)}, dtype={buffer.dtype})" + if buffer.device.type != "cpu": + tensor_str = f'{tensor_str}.to("{buffer.device}")' + model_str += ( + f"{tab * 2}self.register_buffer('{buffer_name}', {tensor_str})\n" + ) + + for param_name, param in module._parameters.items(): + if param is None: + continue + maybe_device = "" + if param.device.type != "cpu": + maybe_device = f', device="{param.device}"' + tensor_str = f"torch.nn.Parameter(torch.randn({list(param.shape)}, dtype={param.dtype}{maybe_device}))" + model_str += f"{tab * 2}self.{param_name} = {tensor_str}\n" + + model_str += f"{_addindent(module.code, len(tab))}\n" + return model_str + + repro_class = f"class Repro(torch.nn.Module):\n{emit_module_body(gm)}" + # Subgraph classes must be defined before Repro instantiates them. + return "\nfrom torch.nn import *\n" + "\n".join(subgraph_defs + [repro_class]) + + +@functools.cache # subprocess is expensive +def _cuda_system_info_comment() -> str: + if not torch.cuda.is_available(): + return "# torch.cuda.is_available()==False, no GPU info collected\n" + + model_str = "# CUDA Info: \n" + try: + if torch.version.hip is None: + cuda_version_out = subprocess.check_output(["nvcc", "--version"]) + cuda_version_lines = cuda_version_out.decode().split("\n") + comment = "".join([f"# {s} \n" for s in cuda_version_lines if s != ""]) + model_str += f"{comment}\n" + else: + model_str += "# Not searching for nvcc on ROCM setup\n" + except (OSError, subprocess.CalledProcessError): + model_str += "# nvcc not found\n" + + gpu_names = Counter( + torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count()) + ) + + model_str += "# GPU Hardware Info: \n" + for name, count in gpu_names.items(): + model_str += f"# {name} : {count} \n" + model_str += "\n" + return model_str + + +def generate_env_vars_string(*, stable_output: bool = False) -> str: + """ + Generate a string configuration for environment variables related to Dynamo, Inductor, and Triton. + """ + if stable_output: + return "# env var omitted due to stable_output=True" + + allow_list = ["TORCH", "DYNAMO", "INDUCTOR", "TRITON"] + skip_list = ["TRITON_LIBDEVICE_PATH", "TRITON_PTXAS_PATH", "TRITON_LIBCUDA_PATH"] + repro_env_vars = ["TORCHDYNAMO_REPRO_AFTER", "TORCHDYNAMO_REPRO_LEVEL"] + + def filter(key: str) -> bool: + return ( + any(string in key for string in allow_list) + and key not in skip_list + and key not in repro_env_vars + ) + + config_lines = [ + f"""os.environ['{key}'] = '{value.replace("'", '"')}'""" + for key, value in os.environ.items() + if filter(key) + ] + # Repro scripts should not recursively generate more repro scripts when run. + config_lines.extend(f"os.environ.pop('{key}', None)" for key in repro_env_vars) + config_string = "\n".join(config_lines) + return normalize_path_separator(f"""\ +import os +{config_string} + """) + + +def generate_config_string(*, stable_output: bool = False) -> str: + import torch._functorch.config + import torch._inductor.config + from torch._inductor.codegen import common + + if stable_output: + return "# config omitted due to stable_output=True" + + # Third-party Inductor backends can register their own ConfigModule. + # Repros need to replay non-default values from those modules, and + # ConfigModule.codegen_config() emits assignments but not the module import. + extra_codegen_configs = [] + for c in common.custom_backend_codegen_configs.values(): + if isinstance(c, ConfigModule): + codegen_config = c.codegen_config() + if codegen_config: + extra_codegen_configs.append(f"import {c.__name__}\n{codegen_config}") + extra_codegen_configs_str = "\n".join(extra_codegen_configs) + + experimental_config = torch.fx.experimental._config.codegen_config() # type: ignore[attr-defined] + + return f"""\ +import torch._dynamo.config +import torch._inductor.config +import torch._functorch.config +import torch.fx.experimental._config +{torch._dynamo.config.codegen_config()} +{torch._inductor.config.codegen_config()} +{torch._functorch.config.codegen_config()} +{experimental_config} +{extra_codegen_configs_str} +""" + + +def get_minifier_repro_path() -> str: + return os.path.join(minifier_dir(), "minifier_launcher.py") + + +def helper_for_dump_minify(contents: str) -> None: + minified_repro_path = get_minifier_repro_path() + log.warning("Writing minified repro to:\n%s", minified_repro_path) + + if use_buck: + BuckTargetWriter(minified_repro_path).write() + try: + with open(minified_repro_path, "w") as fd: + fd.write(contents) + + except OSError as e: + log.exception("") + raise NotImplementedError(f"Could not write to {minified_repro_path}") from e + + +class AccuracyError(Exception): + pass + + +def clone_inputs_retaining_gradness(example_inputs: Sequence[Any]) -> list[Any]: + """ + This clone inputs is different from utils clone_input. In case of minifier, + all the tensors are leaf tensors while creating a new graph. So, we set the + requires_grad field w/o checking the leafness of the tensor. + """ + cloned_inputs = clone_inputs(example_inputs) + for idx in range(len(example_inputs)): + if isinstance(cloned_inputs[idx], torch.Tensor): + cloned_inputs[idx].requires_grad_(example_inputs[idx].requires_grad) + return cloned_inputs # type: ignore[return-value] + + +def run_fwd_maybe_bwd( + gm: torch.fx.GraphModule, + args: Sequence[Any], + only_fwd: bool = False, + disable_clone: bool = False, +) -> Any: + """ + Runs a forward and possibly backward iteration for a given mod and args. + + When disable_clone is True, we will use args as-is without cloning. + This is higher fidelity but we may destroy the args in the process. + """ + from .testing import collect_results, reduce_to_scalar_loss, requires_bwd_pass + + gm = copy.deepcopy(gm) + if not disable_clone: + args = clone_inputs_retaining_gradness(args) + + if hasattr(gm, "zero_grad"): + gm.zero_grad(True) + + # TorchInductor returned callable expects lists. So, may need a boxed calling convention. + out = gm(args) if getattr(gm, "_boxed_call", False) else gm(*args) + + if only_fwd: + return out + if requires_bwd_pass(out): + loss = reduce_to_scalar_loss(out) + loss.backward() + return collect_results(gm, out, None, args) + + +def same_two_models( + gm: torch.fx.GraphModule, + opt_gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + only_fwd: bool = False, + *, + require_fp64: bool = False, + ignore_non_fp: bool = False, +) -> bool: + """ + Check two models have same accuracy. + + require_fp64: if True, raise an error if we unable to calculate the fp64 reference + ignore_non_fp: if True, do not compare outputs which are not floating point. This + is mostly useful for the minifier (which wants to avoid quantizing floating point + error into integer/boolean error) + """ + from .utils import same + + ref = run_fwd_maybe_bwd(gm, example_inputs, only_fwd) + + fp64_ref = None + if config.same_two_models_use_fp64: + try: + fp64_model, fp64_examples = cast_to_fp64( + copy.deepcopy(gm), clone_inputs_retaining_gradness(example_inputs) + ) + fp64_ref = run_fwd_maybe_bwd(fp64_model, fp64_examples, only_fwd) + except Exception: + if require_fp64: + raise RuntimeError( # noqa: B904 + "Could not generate fp64 outputs, workaround with torch._dynamo.config.same_two_models_use_fp64 = False" + ) + log.warning("Could not generate fp64 outputs") + + try: + res = run_fwd_maybe_bwd(opt_gm, example_inputs, only_fwd) + except Exception: + # This means that the minified graph is bad/exposes a different problem. + # As we are checking accuracy here, lets log the exception and return True. + log.exception( + "While minifying the program in accuracy minification mode, " + "ran into a runtime exception which is likely an unrelated issue." + " Skipping this graph." + ) + return True + + passing = same( + ref, + res, + fp64_ref, + tol=config.repro_tolerance, + equal_nan=True, + ignore_non_fp=ignore_non_fp, + ) + return passing + + +def cast_dtype_args_to_fp64(model: torch.fx.GraphModule) -> torch.fx.GraphModule: + for node in model.graph.nodes: + if ( + node.op == "call_function" + and node.target is torch.ops.prims.convert_element_type.default + ): + if len(node.args) != 2: + raise AssertionError( + f"Expected node to have 2 args, got {len(node.args)}" + ) + if is_float_dtype(node.args[1]) and node.args[1] != torch.float64: + node.args = (node.args[0], torch.float64) + if node.op == "call_function": + dtype = node.kwargs.get("dtype") + if dtype is not None and is_float_dtype(dtype): + new_kwargs = dict(node.kwargs) + new_kwargs["dtype"] = torch.float64 + node.kwargs = new_kwargs + + model.graph.lint() + model.recompile() + return model + + +def cast_to( + dtype: torch.dtype, model: torch.fx.GraphModule, inputs: list[Any] +) -> tuple[torch.fx.GraphModule, list[Any]]: + from torch.utils._pytree import tree_map + + model = model.to(dtype) + if dtype == torch.float64: + # If casting to fp64 for accuracy comparison, we need to + # replace dtype arguments embedded in the graph with fp64 + model = cast_dtype_args_to_fp64(model) + + inputs = tree_map( + lambda x: x.to(dtype) + if isinstance(x, torch.Tensor) and x.is_floating_point() + else x, + inputs, + ) + return model, inputs + + +def cast_to_fp64( + model: torch.fx.GraphModule, inputs: list[Any] +) -> tuple[torch.fx.GraphModule, list[Any]]: + return cast_to(torch.float64, model, inputs) + + +def backend_accuracy_fails( + gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + compiler_fn: Callable[[torch.fx.GraphModule, list[Any]], torch.fx.GraphModule], + only_fwd: bool = False, + *, + require_fp64: bool = False, + ignore_non_fp: bool = False, +) -> bool: + try: + compiled_gm = compiler_fn( + copy.deepcopy(gm), clone_inputs_retaining_gradness(example_inputs) + ) + return not same_two_models( + gm, + compiled_gm, + example_inputs, + only_fwd, + require_fp64=require_fp64, + ignore_non_fp=ignore_non_fp, + ) + except Exception: + # This means that the minified graph is bad/exposes a different problem. + # As we are checking accuracy here, lets log the exception and return False. + log.exception( + "While minifying the program in accuracy minification mode, " + "ran into a runtime exception which is likely an unrelated issue." + " Skipping this graph" + ) + return False + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# REPRO SUPPORT CODE +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# Helper functions for computing what the default values of tensor +# values should be. These all coincide with factory functions, e.g., torch.empty + + +def _stride_or_default( + stride: torch._prims_common.StrideType | None, + *, + shape: torch._prims_common.ShapeType, +) -> torch._prims_common.StrideType: + return stride if stride is not None else utils.make_contiguous_strides_for(shape) + + +def _mk_defaulter(d: T) -> Callable[[T | None], T]: + return lambda x: x if x is not None else d + + +_dtype_or_default = _mk_defaulter(torch.float32) +_device_or_default = _mk_defaulter(torch.device("cpu")) +_storage_offset_or_default = _mk_defaulter(0) +_requires_grad_or_default = _mk_defaulter(False) +_is_leaf_or_default = _mk_defaulter(False) + + +class NopInputReader: + def __init__(self) -> None: + self.total = 0 + + def storage( + self, + storage_hash: str | None, + nbytes: int, + *, + device: torch._prims_common.DeviceLikeType | None = None, + dtype_hint: torch.dtype | None = None, + ) -> None: + self.total += 1 + + def tensor(self, *args: Any, **kwargs: Any) -> torch.Tensor | None: + pass + + def symint(self, *args: Any, **kwargs: Any) -> int | None: + pass + + def const(self, name: str) -> None: + pass + + def unsupported(self, name: str) -> None: + pass + + def generator(self, device_type: str, device_index: int) -> None: + pass + + def opaque(self, script_class_name: str) -> None: + self.total += 1 + + +# TODO: Support bundling the entire repro into a zip file for ease of +# transferring around +class InputReader: + def __init__( + self, save_dir: str | None = None, *, pbar: tqdm | None = None + ) -> None: + # If None, we will generate random data instead. It's important + # to natively support this use case as it will allow people to + # share repros without including the real data, if the problem + # reproduces even on random data. + if save_dir is None: + log.warning("no save_dir specified, will generate random data") + self.store = ContentStoreReader(save_dir) if save_dir is not None else None + self.args: list[Any] = [] + self.pbar = pbar + + def storage( + self, + storage_hash: str | None, + nbytes: int, + *, + device: torch._prims_common.DeviceLikeType | None = None, + dtype_hint: torch.dtype | None = None, + ) -> UntypedStorage: + if self.pbar is not None: + self.pbar.update(1) + device = _device_or_default(device) # type: ignore[arg-type] + dtype_hint = _dtype_or_default(dtype_hint) + if self.store is not None and storage_hash is not None: + try: + storage = self.store.read_storage(storage_hash) + except FileNotFoundError: + pass + else: + if device != storage.device: + log.warning("device mismatch: %s != %s", device, storage.device) + # TODO: transfer it to the right device? But failing this + # way would be very mysterious! Would have been better + # not to store device in the serialized format... + return storage + warn_once(f"could not load {storage_hash}, generating random data instead") + shape = (nbytes // dtype_hint.itemsize,) + stride = _stride_or_default(None, shape=shape) + return rand_strided(shape, stride, dtype_hint, device).untyped_storage() + + def tensor( + self, + storage: UntypedStorage, + shape: torch._prims_common.ShapeType, + stride: torch._prims_common.StrideType | None = None, + *, + storage_offset: int | None = None, + dtype: torch.dtype | None = None, + requires_grad: bool | None = None, + is_leaf: bool | None = None, + **metadata: Any, + ) -> torch.Tensor: + stride = _stride_or_default(stride, shape=shape) + storage_offset = _storage_offset_or_default(storage_offset) + dtype = _dtype_or_default(dtype) + is_leaf = _is_leaf_or_default(is_leaf) + requires_grad = _requires_grad_or_default(requires_grad) + t = torch.tensor( + [], dtype=dtype, device=storage.device, requires_grad=requires_grad + ) + with torch.no_grad(): + t.set_(storage, storage_offset, shape, stride) + if not is_leaf: + # Fake up some autograd history in a very naughty way + with torch.enable_grad(): + t = t.clone(memory_format=torch.preserve_format) + with torch.no_grad(): + t.set_(storage, storage_offset, shape, stride) + if torch._subclasses.meta_utils.safe_is_leaf(t) != is_leaf: + raise AssertionError( + f"Tensor leaf status mismatch: safe_is_leaf(t) = " + f"{torch._subclasses.meta_utils.safe_is_leaf(t)}, expected {is_leaf}" + ) + torch._utils.set_tensor_metadata(t, metadata) + self.args.append(t) + return t # for BC + + def symint(self, val: Any, *, expr: str | None = None) -> Any: + self.args.append(val) + if expr is not None: + if not hasattr(self, "symint_exprs"): + self.symint_exprs: dict[int, str] = {} + self.symint_exprs[len(self.args) - 1] = expr + return val # for BC + + def const(self, name: str) -> None: + self.args.append(None) + + def unsupported(self, name: str) -> None: + self.args.append(None) + + def generator(self, device_type: str, device_index: int) -> Any: + device = torch.device(device_type, device_index) + gen = torch.Generator(device=device) + self.args.append(gen) + return gen + + def opaque(self, script_class_name: str) -> None: + self.args.append(None) + + +# Here is our writer strategy: +# 1. We will stream all of the inputs to disk +# 2. You can now deterministically randomize the inputs, or reload +# the inputs from disk +# 3. You can YOLO run the script without the inputs, in which case +# we'll fill the inputs with random data and pray. This is the +# legacy behavior, but it's also useful if you want to find out +# if we're so broken even random inputs trigger it +# 4. We could offer an in process "check if the randomized thing +# works too" but this is delicate so we don't do it + + +def _serialize_storage_nbytes(nbytes: int | torch.SymInt) -> str: + if isinstance(nbytes, torch.SymInt): + from torch.fx.experimental.symbolic_shapes import SymExprPrinter + + return SymExprPrinter().doprint(nbytes.node.expr) + return repr(nbytes) + + +class InputWriter: + def __init__(self, save_dir: str | None, *, stable_hash: bool = False) -> None: + self._lines: list[str] = [] + # TODO: consider ensuring tensor and storage counters line up? + self.storage_counter = itertools.count() + self.save_dir = save_dir + self.store = ( + ContentStoreWriter(save_dir, stable_hash=stable_hash) + if save_dir is not None + else None + ) + self.seen_storages: dict[StorageWeakRef, str] = {} + + def lines(self) -> list[str]: + r = [ + "def load_args(reader):", + ] + r.extend(f" {l}" for l in self._lines) + # In case we need to change the internal format of load_args + # in an FC-breaking way + r.append("load_args._version = 0") + return r + + # Storages are untyped, but we need to initialize them with data if + # we don't have the real data, so we give a hint saying what kind + # of initialization may be appropriate + # + # If we had a FakeTensor, device_hint tells us what device should be + def storage( + self, + untyped_storage: UntypedStorage, + *, + device_hint: torch._prims_common.DeviceLikeType | None = None, + dtype_hint: torch.dtype | None = None, + ) -> str: + ws = StorageWeakRef(untyped_storage) + v = self.seen_storages.get(ws) + if v is not None: + return v + v = f"buf{next(self.storage_counter)}" + maybe_dtype_hint = "" + if _dtype_or_default(None) != _dtype_or_default(dtype_hint): + maybe_dtype_hint = f", dtype_hint={dtype_hint!r}" + # TODO: being optional on device is kind of pointless as the default + # is CPU but most repros we care about are CUDA + maybe_device = "" + device = untyped_storage.device + if device.type == "meta": + if device_hint is None: + raise AssertionError( + "device_hint must be provided when storage device is 'meta'" + ) + device = device_hint # type: ignore[assignment] + if _device_or_default(None) != device: + maybe_device = f", device={device!r}" + nbytes = untyped_storage.nbytes() + nbytes_source = _serialize_storage_nbytes(nbytes) + storage_hash = None + if self.store is not None and untyped_storage.device.type != "meta": + storage_hash = self.store.write_storage(untyped_storage) + self._lines.append( + f"{v} = reader.storage({storage_hash!r}, {nbytes_source}{maybe_device}{maybe_dtype_hint})" + ) + self.seen_storages[ws] = v + return v + + def tensor(self, name: str, t: torch.Tensor) -> None: + from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq + + storage = self.storage( + t.untyped_storage(), dtype_hint=t.dtype, device_hint=t.device + ) + args = [] + # NB: this is positional, must come first + if not statically_known_true( + sym_eq(_stride_or_default(None, shape=t.shape), t.stride()) + ): + args.append(str(tuple(t.stride()))) + if _dtype_or_default(None) != t.dtype: + args.append(f"dtype={t.dtype!r}") + if not statically_known_true( + _storage_offset_or_default(None) == t.storage_offset() + ): + args.append(f"storage_offset={t.storage_offset()!r}") + tensor_metadata = torch._utils.get_tensor_metadata(t) + if tensor_metadata: + args.extend(f"{k}={v!r}" for k, v in tensor_metadata.items()) + if _requires_grad_or_default(None) != t.requires_grad: + args.append(f"requires_grad={t.requires_grad!r}") + is_leaf = torch._subclasses.meta_utils.safe_is_leaf(t) + if _is_leaf_or_default(None) != is_leaf: + args.append(f"is_leaf={is_leaf!r}") + self._lines.append( + "reader.tensor(" + + ", ".join([storage, str(tuple(t.shape)), *args]) + + f") # {name}" + ) + + def unsupported(self, name: str, arg: Any) -> None: + # NB: Try hard not to /print/ a tensor, that will be very slow + self._lines.append( + f"reader.unsupported({name!r}) # unsupported type for dumping: {type(arg)}" + ) + # Best effort dump as much useful stuff we can lol, in case you want + # to repair the repro + if isinstance(arg, (list, tuple)): + self._lines.append('"""') + for i, a in enumerate(arg): + name_i = f"{name}[{i}]" + if isinstance(a, torch.Tensor): + self.tensor(name_i, a) + elif isinstance(a, (int, torch.SymInt)): + self.symint(name_i, a) + else: + self.unsupported(name_i, a) + self._lines.append('"""') + + # write out that the arg was filtered out as it is constant + def const(self, name: str) -> None: + self._lines.append( + f"reader.const({name!r}) # {name}, filtered out during compilation" + ) + + # TODO: this doesn't actually symint atm + def symint(self, name: str, val: Any) -> None: + if isinstance(val, torch.SymInt): + expr_str = str(val.node.expr) + hint = val.node.hint + self._lines.append(f"reader.symint({hint!r}, expr={expr_str!r}) # {name}") + else: + self._lines.append(f"reader.symint({val!r}) # {name}") + + def generator(self, name: str, arg: torch._C.Generator) -> None: + device = arg.device + self._lines.append( + f"reader.generator({device.type!r}, {device.index!r}) # {name}" + ) + + def opaque(self, name: str, script_class_name: str) -> None: + self._lines.append(f"reader.opaque({script_class_name!r}) # {name}") + + +def aot_graph_input_parser( + func: Callable[[list[Tensor]], list[Tensor]], + device: str = "cuda", + sym_shapes: dict[str, int] | None = None, + default_sym_shape: int | None = None, +) -> dict[str, Any]: + """ + Takes in a function which has been printed with print_readable() and constructs kwargs to run it. + + Handles Tensor inputs, Symints, and a graph module which might have tensor constants. + + Consider a function `forward` defined as follows: + + def forward(self, primals_1: "f32[1001, 6]", primals_2: "f32[s0]", primals_3: "Sym(s0)",): + _tensor_constant0: "i64[4190]" = self._tensor_constant0 + # Further implementation + + kwargs = aot_graph_input_parser(forward) + forward(**kwargs) + """ + + from torch.utils._dtype_abbrs import dtype_abbrs + + dtype_map: dict[str, torch.dtype] = { + value: key for key, value in dtype_abbrs.items() + } + dtype_pattern: str = "|".join(dtype_abbrs.values()) + + # Extracting the source code from the function + source = inspect.getsource(func) + + # Regular expressions + tensor_assignment_regex = rf"(_tensor_constant\d+): \"({dtype_pattern})\[\s*(.*?)\s*\]\" = self\.(_tensor_constant\d+)" + tensor_regex = rf"({dtype_pattern})\[\s*(.*?)\s*\]" + sym_shape_regex = r"Sym\((s\d+)\)" + + class TensorContainer: + "Container for tensors as attributes" + + # Dictionary for tensors from annotations + kwargs: dict[str, Any] = {} + + sym_shapes_dict: dict[str, int] = sym_shapes or {} + + def get_sym_int(symint: str) -> int: + torch._check( + symint in sym_shapes_dict or default_sym_shape is not None, + lambda: f"{symint} not in symbolic_shapes and default sym shape not passed in", + ) + return sym_shapes_dict.get(symint, default_sym_shape) # type: ignore[return-value] + + def gen_tensor(shape: torch._prims_common.ShapeType, dtype: torch.dtype) -> Tensor: + # Resolve symbolic shapes to concrete values + resolved_shape = [] + dynamic_dims = [] + for i, dim in enumerate(shape): + dim = dim.strip() # type: ignore[attr-defined] + if "s" in dim: + s = get_sym_int(dim) + resolved_shape.append(s) + dynamic_dims.append(i) + else: + if dim: + resolved_shape.append(int(dim)) + + constructor = torch.randn if dtype.is_floating_point else torch.zeros + out = constructor(resolved_shape, dtype=dtype, device=device) # type: ignore[call-arg] + for d in dynamic_dims: + torch._dynamo.mark_dynamic(out, d) + return out + + # Parse function annotations for tensor generation + annotations = func.__annotations__ + for param, annotation in annotations.items(): + # Skip 'return' annotation + if param == "return": + continue + + match = re.search(tensor_regex, annotation) + if match: + data_type, shape_str = match.groups() + shape = tuple(shape_str.split(",")) + dtype = dtype_map[data_type] + # pyrefly: ignore [bad-argument-type] + kwargs[param] = gen_tensor(shape, dtype) + + match = re.search(sym_shape_regex, annotation) + if match: + kwargs[param] = get_sym_int(match.group(1)) + + if "self" in inspect.signature(func).parameters: + container = TensorContainer() + kwargs["self"] = container + for match in re.finditer(tensor_assignment_regex, source): + attr_name, data_type, shape_str, _ = match.groups() + shape = tuple(shape_str.split(",")) + dtype = dtype_map[data_type] + # pyrefly: ignore [bad-argument-type] + setattr(container, attr_name, gen_tensor(shape, dtype)) + + return kwargs + + +def profile_to_file(filename: str) -> Callable[[T], T]: + """ + Decorator to cProfile a given function and save the result to disk on process exit. + + Args: + filename: filename to save profile to + """ + prof = cProfile.Profile() + filename = os.path.abspath(os.path.expanduser(filename)) + + def decorator(fn: Any) -> Any: + @functools.wraps(fn) + def wrapper(*args: Any, **kwargs: Any) -> Any: + prof.enable() + try: + return fn(*args, **kwargs) + finally: + prof.disable() + + return wrapper + + def save_it() -> None: + prof.dump_stats(filename) + sys.stderr.write( + textwrap.dedent( + f"""\ + Wrote profile to {filename}, view with: + + snakeviz {filename} + + """ + ) + ) + + atexit.register(save_it) + return decorator diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/decorators.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..91e4ac517c4f4826418d2ea0d82114ecdedd9881 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/decorators.py @@ -0,0 +1,1890 @@ +""" +This module provides decorators and utilities for controlling TorchDynamo's behavior during compilation. +""" + +import functools +import inspect +import weakref +from collections.abc import Callable +from dataclasses import dataclass +from types import TracebackType +from typing import Any, overload, Protocol, TYPE_CHECKING, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch.utils._pytree as pytree +from torch._custom_class_base import CustomClassBase +from torch._vendor.packaging.version import InvalidVersion, Version +from torch.compiler import is_compiling +from torch.utils._contextlib import _DecoratorContextManager +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils._typing_utils import not_none + +from .._utils_internal import justknobs_check +from . import trace_rules, variables +from .comptime import comptime +from .eval_frame import ( + _set_stance, + DisableContext, + DynamoStance, + innermost_fn, + RunOnlyContext, + skip_code, + StanceStr, +) +from .external_utils import ( + get_nonrecursive_disable_wrapper, + wrap_dunder_call_ctx_manager, +) +from .utils import ( + _get_cudagraph_override, + _get_error_on_graph_break, + _set_cudagraph_override, + _set_error_on_graph_break, + allow_lru_cache_wrapper_trace_without_warning, + is_function, + is_lru_cache_wrapped_function, +) + + +justknobs_check._dynamo_marked_constant = True # type: ignore[attr-defined] + +if TYPE_CHECKING: + from types import FunctionType + + from torch._C._dynamo.eval_frame import ( # noqa: F401 + reset_code, + set_eval_frame, + set_guard_complete_hook, + set_guard_error_hook, + unsupported, + ) + + from .variables import VariableTracker +else: + for name in dir(torch._C._dynamo.eval_frame): + if name.startswith("__"): + continue + globals()[name] = getattr(torch._C._dynamo.eval_frame, name) + + +_P = ParamSpec("_P") +_R = TypeVar("_R") +FuncType = Callable[..., Any] +F = TypeVar("F", bound=FuncType) + + +def run(fn: Callable[_P, _R] | None = None) -> Any: + """Don't do any dynamic compiles, just use prior optimizations""" + if fn is not None: + fn = innermost_fn(fn) + if not callable(fn): + raise AssertionError("fn must be callable") + return RunOnlyContext()(fn) + return RunOnlyContext() + + +def disable(fn=None, recursive=True, *, reason=None, wrapping=True): # type: ignore[no-untyped-def] + """ + Decorator to disable TorchDynamo + + If recursive=True, Dynamo is completely skipped on the decorated function + frame as well as the recursively invoked functions. + + If recursive=False, Dynamo skips frames associated with the function code, + but still process recursively invoked frames. + + If reason is provided, it will be printed when Dynamo attempts to trace the disabled function. + """ + if recursive: + if fn is not None: + fn = innermost_fn(fn) + if not callable(fn): + raise AssertionError("fn must be callable") + return DisableContext(msg=reason, wrapping=wrapping)(fn) + return DisableContext(msg=reason, wrapping=wrapping) + else: + + def wrap(fn: Callable[_P, _R]) -> Callable[_P, _R]: + fn = innermost_fn(fn) + if not callable(fn): + raise AssertionError("fn must be callable") + + nonrecursive_disable_wrapper = get_nonrecursive_disable_wrapper(fn) + nonrecursive_disable_wrapper._torchdynamo_disable = True # type: ignore[attr-defined] + nonrecursive_disable_wrapper._torchdynamo_disable_msg = reason # type: ignore[attr-defined] + nonrecursive_disable_wrapper._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + nonrecursive_disable_wrapper._torchdynamo_wrapper_id = id( # type: ignore[attr-defined] + nonrecursive_disable_wrapper + ) + nonrecursive_disable_wrapper._torchdynamo_disable_recursive = False # type: ignore[attr-defined] + return nonrecursive_disable_wrapper + + if fn is None: + return wrap + return wrap(fn) + + +_nonrecursive_disable_wrapper_code = disable(lambda: None, recursive=False).__code__ # type: ignore[attr-defined] +skip_code(_nonrecursive_disable_wrapper_code) + + +def skip(fn: Callable[_P, _R] | None = None) -> Callable[..., Any]: + """ + Skip frames associated with the function code, but still process recursively + invoked frames + """ + if fn is None: + return skip + fn = innermost_fn(fn) + if not callable(fn): + raise AssertionError("fn must be callable") + skip_code(fn.__code__) + fn._torchdynamo_disable = True # type: ignore[attr-defined] + return fn + + +class set_stance(_DecoratorContextManager): + """ + Decorator, context manager, function to set the current stance of the compiler. + + Stances documented in corresponding function in torch/compiler/__init__.py + """ + + _dynamo_forbidden = True + + def __init__( + self, + stance: StanceStr = "default", + *, + skip_guard_eval_unsafe: bool = False, + force_backend: str | Callable[..., Any] | None = None, + ) -> None: + if force_backend is not None and stance != "default": + raise RuntimeError("non-default stance cannot have force_backend set") + + self.stance = DynamoStance(stance, skip_guard_eval_unsafe, force_backend) + self.prev = _set_stance(self.stance) + + def __call__(self, fn: F) -> F: + _set_stance(self.prev) + wrapper = super().__call__(fn) + # forbid wrapper in graph + wrapper._dynamo_forbidden = True # type: ignore[attr-defined] + return wrapper + + def __enter__(self) -> None: + _set_stance(self.stance) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + _set_stance(self.prev) + + def clone(self) -> "set_stance": + return self.__class__(self.stance.stance, force_backend=self.stance.backend) + + +def assume_constant_result(fn): # type: ignore[no-untyped-def] + fn._dynamo_marked_constant = True # type: ignore[attr-defined] + return fn + + +def allow_in_graph(fn): # type: ignore[no-untyped-def] + """ + Tells the compiler frontend (Dynamo) to skip symbolic introspection of the function + and instead directly write it to the graph when encountered. + + See :func:`torch.compiler.allow_in_graph`'s docstring for the full documentation + + WARNING: this API can be a footgun, please read the documentation carefully. + """ + if isinstance(fn, (list, tuple)): + return [allow_in_graph(x) for x in fn] + if not callable(fn): + raise AssertionError("allow_in_graph expects a callable") + if trace_rules.lookup_callable(fn) != variables.TorchInGraphFunctionVariable: + fn_id = id(fn) + trace_rules._disallowed_callable_ids.remove(fn_id) + trace_rules._allowed_callable_ids.add(fn_id) + + # Avoid id reuse which creates subtle bugs. + def deregister() -> None: + trace_rules._allowed_callable_ids.remove(fn_id) + + weakref.finalize(fn, deregister) + return fn + + +# pyrefly: ignore [implicit-any] +def _check_mutually_exclusive_decorators(fn: Callable, decorator_name: str) -> None: + mutually_exclusive = { + "leaf_function": trace_rules.is_leaf_function, + "nonstrict_trace": trace_rules.is_nonstrict_trace_callable, + } + + for other_name, check_fn in mutually_exclusive.items(): + if other_name != decorator_name and check_fn(fn): + first, second = sorted([decorator_name, other_name]) + raise ValueError( + f"Function {fn} cannot be both marked as @{first} and " + f"@{second}. Please use only one decorator." + ) + + +def nonstrict_trace(traceable_fn: Callable[_P, _R]) -> Callable[_P, _R]: + """ + Decorator to mark a function as nonstrict-traceable for dynamo. + + See :func:`torch.compiler.nonstrict_trace` for the full documentation. + """ + if not callable(traceable_fn): + raise AssertionError("nonstrict_trace expects a callable") + + _check_mutually_exclusive_decorators(traceable_fn, "nonstrict_trace") + + @functools.wraps(traceable_fn) + def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: + return traceable_fn(*args, **kwargs) + + wrapped_id = id(wrapped) + + # This line allows us to reuse much of the `allow_in_graph` impl. + trace_rules._allowed_callable_ids.add(wrapped_id) + + # This line allows us to diverge the impl from `allow_in_graph`. + trace_rules._nonstrict_trace_callable_ids.add(wrapped_id) + + # Avoid id reuse which creates subtle bugs. + def deregister() -> None: + trace_rules._allowed_callable_ids.remove(wrapped_id) + trace_rules._nonstrict_trace_callable_ids.remove(wrapped_id) + + weakref.finalize(wrapped, deregister) + + return wrapped + + +def _invoke_leaf_function_python( + real_impl: Callable[..., Any], + fake_impl: Callable[..., Any], + args: tuple[Any, ...], + kwargs: dict[str, Any], + mutates_args: frozenset[str] | None = None, + hook_fn: Callable[..., Any] | None = None, + hook_fake_fn: Callable[..., Any] | None = None, +) -> Any: + """Call invoke_leaf_function HOP directly from Python. + + This enables @leaf_function to work with make_fx + without relying on Dynamo to intercept the call. + """ + from torch._higher_order_ops.invoke_leaf_function import ( + _LeafCallable, + convert_modules_to_states, + invoke_leaf_function, + make_leaf_function_wrappers, + store_makefx_modules, + ) + + captured_modules: list[torch.nn.Module] = [] + seen_module_ids: dict[int, int] = {} # id(module) -> position in captured_modules + for val in pytree.tree_flatten( + (args, kwargs), is_leaf=lambda x: isinstance(x, torch.nn.Module) + )[0]: + if isinstance(val, torch.nn.Module) and id(val) not in seen_module_ids: + seen_module_ids[id(val)] = len(captured_modules) + captured_modules.append(val) + + global_indices = store_makefx_modules(captured_modules) + module_to_index = { + mod_id: global_indices[pos] for mod_id, pos in seen_module_ids.items() + } + + processed = convert_modules_to_states((args, kwargs), module_to_index) + flat_args, input_spec = pytree.tree_flatten(processed) + + # Single-element mutable list so the wrappers can write back the output + # TreeSpec. Read captured_out_spec[0] after the wrappers have been called. + captured_out_spec: list[pytree.TreeSpec | None] = [None] + wrapped_real, wrapped_fake = make_leaf_function_wrappers( + real_impl, fake_impl, captured_out_spec + ) + + real_fn_callable = _LeafCallable(wrapped_real) + fake_fn_callable = _LeafCallable(wrapped_fake) + + if hook_fn is not None: + real_fn_callable._leaf_hook_real_fn = hook_fn # type: ignore[attr-defined] + real_fn_callable._leaf_hook_fake_fn = hook_fake_fn # type: ignore[attr-defined] + + mutated_flat_indices = "" + if mutates_args: + from torch._higher_order_ops.invoke_leaf_function import ( + _resolve_mutated_flat_indices, + ) + + mutated_flat_indices = _resolve_mutated_flat_indices( + real_impl, mutates_args, len(flat_args), input_spec + ) + + flat_out = invoke_leaf_function( + real_fn_callable, fake_fn_callable, input_spec, mutated_flat_indices, *flat_args + ) + + if captured_out_spec[0] is None: + raise AssertionError("captured_out_spec was not set by leaf function wrappers") + return pytree.tree_unflatten(flat_out, captured_out_spec[0]) + + +@overload +def leaf_function(fn: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +@overload +def leaf_function( + *, mutates_args: set[str] +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... + + +def leaf_function( + fn: Callable[_P, _R] | None = None, *, mutates_args: set[str] | None = None +) -> Callable[_P, _R] | Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """ + Decorator to mark a function as a leaf function for :func:`torch.compile`. + + A leaf function appears as an opaque operation in the compiled graph. During + compilation, Dynamo and AOT autograd do not trace into it. At runtime, the + original eager Python code is executed directly. + + Quick Start: + Suppose we want to log per-sample statistics during the forward pass:: + + def compute_and_log_stats(x): + stats = x.mean(dim=1) + logger.info(f"Per-sample means: {stats}") + return (stats,) + + With ``torch.compile(..., fullgraph=True)``, this fails because + ``logger.info`` causes a graph break. To fix it, follow the steps below: + + 1. Decorate your function with ``@leaf_function`` + 2. Define a shape-inference function using ``@your_fn.register_fake`` + + Concrete implementation:: + + >>> import logging + >>> import torch + >>> from torch._dynamo.decorators import leaf_function + >>> + >>> logging.basicConfig(level=logging.INFO) + >>> logger = logging.getLogger(__name__) + >>> + >>> @leaf_function + ... def compute_and_log_stats(x): + ... stats = x.mean(dim=1) # Shape: (x.shape[0],) + ... logger.info(f"Per-sample means: {stats}") + ... return (stats,) + ... + >>> @compute_and_log_stats.register_fake + ... def compute_and_log_stats_fake(x): + ... # Match the output shape: (x.shape[0],) + ... return (x.new_empty(x.shape[0]),) + ... + >>> def fn(x): + ... return compute_and_log_stats(x) + ... + >>> x = torch.randn(3, 4) + >>> compiled_fn = torch.compile(fn, backend="aot_eager", fullgraph=True) + >>> out = compiled_fn(x)[0] + + When to Use: + Use ``leaf_function`` when you need eager execution semantics that tracing + cannot preserve: + + - **Non-traceable code**: The function consists of code that Dynamo or + AOT Autograd cannot trace. + - **Runtime side effects**: Operations that must happen exactly once per call + at runtime (e.g., logging, external library calls). + + If your function has a static computation graph and no runtime side effects, + prefer :func:`allow_in_graph` or :func:`nonstrict_trace` instead. They allow AOT autograd + to trace through and potentially optimize the code. + + Usage: + **Inputs and Outputs**: + - Both inputs and outputs must use pytree-compatible types. + Tensors, Python primitives (int, float, bool, str), and built-in containers + (list, tuple, dict) are supported by default. + + Note: We recommend leaf_functions only accept and return tensors. Though primitive + types (int, float, bool, str) are supported in inputs and outputs, they may cause + surprising behavior: primitive inputs are guarded and may trigger recompilation, + while primitive output values are captured from the fake implementation at compile time and + remain fixed for all subsequent executions. Even though the real function runs + at runtime, its primitive return values are silently replaced with the compile-time + values from the fake implementation. + + Example:: + + # BAD: primitive output varies at runtime + counter = 0 + + + @leaf_function + def count_calls(x): + global counter + counter += 1 + return (x, counter) + + + @count_calls.register_fake + def count_calls_fake(x): + return (x, 999) # placeholder value + + + # At runtime: real function runs (counter increments to 1, 2, 3, ...) + # But returned count is always 999 (from fake implementation at compile time) + + - User-defined classes must be registered via :func:`torch.utils._pytree.register_pytree_node` + or :func:`torch.utils._pytree.register_dataclass`. + + - :class:`torch.nn.Module` can also be passed as input; its parameters and buffers + are tracked for autograd. The module must exist outside the compile region. + Running the module multiple times must not modify its parameters, buffers, or attributes. + + **register_fake (required)**: + Since the function body is not traced, you must + provide a shape-inference function via ``@fn.register_fake``. It runs at compile + time with FakeTensor inputs (tensors with no data, only metadata) and must + satisfy the following requirements: + + - Must have the same input and output signature (e.g., same pytree structure, same tensor metadata + such as shapes, dtypes, device, strides) as the real function + - Must be runnable with FakeTensor inputs + - Must only use its explicit arguments (no closures over tensors or modules) + + Note: The input and output signature must be determinable at compile time. + If your function's output structure depends on runtime values, adjust the leaf function + boundary until outputs become predictable. + + To validate that your fake implementation matches the real function's outputs, set + ``torch._dynamo.config.leaf_function_validate_outputs = True``. + + **register_multi_grad_hook (optional)**: + You can register a backward hook via ``@fn.register_multi_grad_hook`` + to run code when gradients have been computed for all requires_grad + tensor inputs during backward. The hook fires exactly once per + backward pass. The hook receives only the gradients of the leaf + function's requires_grad tensor inputs, in the order they appeared; + non-tensor arguments and tensors without ``requires_grad`` are not + forwarded to the hook. The hook must return ``None``. The hook is + called as a leaf function itself, so it is also opaque to the + compiler. + + Example:: + + >>> @leaf_function + ... def debug_log(t): + ... return None + ... + >>> @debug_log.register_fake + ... def debug_log_fake(t): + ... return None + ... + >>> @debug_log.register_multi_grad_hook + ... def debug_log_hook(t_grad): + ... print(f"[bwd] norm={t_grad.norm().item()}") + ... + >>> x = torch.randn(4, requires_grad=True) + >>> debug_log(x) # no assignment needed + >>> (x * 2).sum().backward() + [bwd] norm=... + + Limitations: + Currently, inductor backend and :func:`torch.export.export` are not yet supported. + + Training / Autograd: + Training is supported automatically if your leaf function is differentiable + in eager mode (e.g., it's implemented with PyTorch ops, :class:`torch.autograd.Function`, + or differentiable custom ops). + + **Restriction**: Calling ``.backward()`` *inside* the leaf function is not + supported. + + **Escaped gradients check**: If the leaf function closes over a tensor with + ``requires_grad=True``, gradients will not flow back to it (only explicit inputs + receive gradients). To detect such cases, set + ``torch._dynamo.config.leaf_function_check_escaped_gradients = True``. + When enabled, a ``RuntimeError`` is raised with details about the escaped tensors. + + Internally, inputs and outputs are detached from the outer autograd graph at the + leaf function boundary. The leaf function builds its own local autograd + graph. In backward, gradients propagate through this local graph to the + leaf function's inputs. If a :class:`torch.nn.Module` is passed in as input, the gradients + will also flow back to its parameters and buffers. + + How leaf_function Works: + Understanding this helps avoid pitfalls: + + 1. **Compilation**: Dynamo and AOT autograd do not trace into the leaf function. + Only your fake implementation runs during compilation to determine output signatures, + shapes, and dtypes. The real function runs at runtime as eager Python. + + 2. **Isolation**: Mutations to shared state (globals, closures) may not be + visible across the boundary between leaf functions and compiled regions. Pass data + explicitly as function arguments and return results as outputs. + + Dangerous Patterns: + These patterns may cause silent incorrectness or errors: + + - **Side effects between leaf functions and compiled regions**: Mutations to + Python state inside a leaf function may not be visible to the compiled + region, and vice versa. The compiled graph may reorder or eliminate + operations in ways that break assumptions about side effect ordering. + + Bad:: + + # Compiled region + self.counter += 1 + y = my_leaf_fn(self, x) # Don't depend on self.counter inside leaf_fn + + y = my_leaf_fn(self, x) + result = self.state # Don't depend on state mutated by leaf_fn + + Logging/printing inside the leaf function is fine since it doesn't affect + correctness. + + - **In-place mutations on inputs**: Undeclared in-place mutations on input + tensors are detected and will raise an error. Either declare mutations via + ``mutates_args`` or clone inputs before mutating. + + Bad:: + + @leaf_function + def my_leaf_fn(x): + x.add_(1) # Will raise: "Undeclared in-place mutation" + return (x,) + + Good:: + + @leaf_function(mutates_args={"buf"}) + def my_leaf_fn(x, buf): + buf.add_(1) # OK: declared in mutates_args + return (x + buf,) + + For pytree args (lists, tuples, dicts of tensors), use the parameter name + to declare mutation on all contained tensors:: + + @leaf_function(mutates_args={"buffers"}) + def my_leaf_fn(x, buffers): + for buf in buffers: + buf.add_(1) # OK: 'buffers' declared in mutates_args + return (x + sum(buffers),) + + Or use bracket notation for fine-grained control:: + + @leaf_function(mutates_args={"buffers[0]"}) + def my_leaf_fn(x, buffers): + buffers[0].add_(1) # OK: 'buffers[0]' declared + return (x + buffers[1],) # buffers[1] is not cloned + + - **Closures in fake implementation**: Tensors or modules captured from enclosing scopes + in the fake implementation will cause compilation errors. The real function can + close over them if they don't require gradient, but the fake implementation must + only use its arguments. + + Bad:: + + weight = torch.randn(3, 3) + + + @leaf_function + def my_leaf_fn(x): + return (x @ weight,) + + + @my_leaf_fn.register_fake + def my_leaf_fn_fake(x): + return (x @ weight,) # Error: weight used in fake implementation + + Good:: + + weight = torch.randn(3, 3) + + + @leaf_function + def my_leaf_fn(x): + return (x @ weight,) # OK: real function can use closure + + + @my_leaf_fn.register_fake + def my_leaf_fn_fake(x): + return (x @ torch.empty_like(x),) # OK: uses only args + + Example:: + Wrapping a linear function with logging as a leaf_function. Gradients + flow back because the inner operations are differentiable:: + + >>> import torch + >>> import torch.nn.functional as F + >>> from torch._dynamo.decorators import leaf_function + >>> + >>> @leaf_function + ... def custom_forward(linear, x): + ... # Logging at runtime + ... print(f"Input: shape={x.shape}, mean={x.mean().item():.4f}") + ... out = F.linear(x, linear.weight, linear.bias) + ... print(f"Output: shape={out.shape}, norm={out.norm().item():.4f}") + ... return (out,) + ... + >>> @custom_forward.register_fake + ... def custom_forward_fake(linear, x): + ... # Return tensor with correct shape: (batch, out_features) + ... return (x.new_empty(x.shape[0], linear.weight.shape[0]),) + ... + >>> class MyModel(torch.nn.Module): + ... def __init__(self): + ... super().__init__() + ... self.linear = torch.nn.Linear(10, 20) + ... def forward(self, x): + ... return custom_forward(self.linear, x) + ... + >>> model = MyModel() + >>> compiled = torch.compile(model, backend="aot_eager", fullgraph=True) + >>> x = torch.randn(32, 10, requires_grad=True) + >>> out = compiled(x)[0] + >>> out.sum().backward() # Gradients flow to model.linear.weight/bias and x + + Args: + fn: The function being decorated. + mutates_args: Set of Python expressions (as strings) identifying arguments + that the function mutates in-place. Each string is evaluated against + the function's parameters. Examples: ``'buf'`` for a plain tensor, + ``'model.running_mean'`` for an nn.Module buffer, + ``'buffers'`` to mark all tensors in a list, ``'buffers[0]'`` for a + specific element, ``'state["key"]'`` for a dict entry. + """ + if fn is None: + return functools.partial(leaf_function, mutates_args=mutates_args) + + from . import trace_rules + + _check_mutually_exclusive_decorators(fn, "leaf_function") + + if mutates_args: + import inspect + import re + + params = set(inspect.signature(fn).parameters) + for expr in mutates_args: + root = re.split(r"[.\[]", expr, maxsplit=1)[0] + if root not in params: + raise ValueError( + f"mutates_args expression '{expr}' refers to parameter '{root}', " + f"which is not a parameter of '{fn.__name__}'. " + f"Available parameters: {', '.join(params)}" + ) + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + if inner._torchdynamo_leaf_fake_fn is None: # type: ignore[attr-defined] + raise ValueError( + f"leaf_function '{getattr(fn, '__name__', fn)}' " + "requires a fake implementation. Please provide one using the @.register_fake " + "decorator. See the leaf_function docstring for details." + ) + + return _invoke_leaf_function_python( + fn, # pyrefly: ignore [bad-argument-type] + # pyrefly: ignore [bad-argument-type] + inner._torchdynamo_leaf_fake_fn, + args, + kwargs, + mutates_args=inner._torchdynamo_leaf_mutates_args, # pyrefly: ignore [missing-attribute] + hook_fn=inner._torchdynamo_leaf_hook_fn, # type: ignore[attr-defined] + hook_fake_fn=inner._torchdynamo_leaf_hook_fake_fn, # type: ignore[attr-defined] + ) # type: ignore[attr-defined] + + inner._torchdynamo_leaf_real_fn = fn # type: ignore[attr-defined] + inner._torchdynamo_leaf_fake_fn = None # type: ignore[attr-defined] + inner._torchdynamo_leaf_mutates_args = ( # pyrefly: ignore [missing-attribute] + frozenset(mutates_args) if mutates_args else frozenset() + ) # type: ignore[attr-defined] + inner._torchdynamo_leaf_hook_fn = None # type: ignore[attr-defined] + inner._torchdynamo_leaf_hook_fake_fn = None # type: ignore[attr-defined] + + # Follow nonstrict_trace implementation + wrapped_id = id(inner) + trace_rules._allowed_callable_ids.add(wrapped_id) + trace_rules._leaf_function_ids.add(wrapped_id) + + def deregister() -> None: + trace_rules._allowed_callable_ids.remove(wrapped_id) + trace_rules._leaf_function_ids.remove(wrapped_id) + + weakref.finalize(inner, deregister) + + def register_fake_setter(fake_fn: Callable[..., Any]) -> Callable[..., Any]: + inner._torchdynamo_leaf_fake_fn = fake_fn # type: ignore[attr-defined] + return inner + + inner.register_fake = register_fake_setter # type: ignore[attr-defined] + + def register_hook_setter(hook_fn: Callable[..., Any]) -> Callable[..., Any]: + inner._torchdynamo_leaf_hook_fn = hook_fn # type: ignore[attr-defined] + inner._torchdynamo_leaf_hook_fake_fn = lambda *args, **kwargs: None # type: ignore[attr-defined] + return inner + + inner.register_multi_grad_hook = register_hook_setter # type: ignore[attr-defined] + + return inner + + +def _disallow_in_graph_helper(throw_if_not_allowed: bool) -> Callable[..., Any]: + def inner(fn: Any) -> Any: + if isinstance(fn, (list, tuple)): + return [disallow_in_graph(x) for x in fn] + if not callable(fn): + raise AssertionError("disallow_in_graph expects a callable") + if ( + throw_if_not_allowed + and trace_rules.lookup_callable(fn) + != variables.TorchInGraphFunctionVariable + and trace_rules.lookup(fn) != variables.TorchInGraphFunctionVariable + ): + raise RuntimeError( + "disallow_in_graph is expected to be used on an already allowed callable (like torch.* ops). " + "Allowed callables means callables that TorchDynamo puts as-is in the extracted graph." + ) + trace_rules._allowed_callable_ids.remove(id(fn)) + trace_rules._nonstrict_trace_callable_ids.remove(id(fn)) + trace_rules._disallowed_callable_ids.add(id(fn)) + return fn + + return inner + + +def disallow_in_graph(fn: Callable[..., Any]) -> Any: + """ + Customize which functions TorchDynamo will exclude in the generated + graph and force a graph break on. + :: + + torch._dynamo.disallow_in_graph(torch.sub) + + + @torch._dynamo.optimize(...) + def fn(a): + x = torch.add(x, 1) + x = torch.sub(x, 1) + x = torch.add(x, 1) + return x + + + fn(...) + + Will break the graph on `torch.sub`, and give two graphs each with a + single `torch.add()` op. + """ + return _disallow_in_graph_helper(throw_if_not_allowed=True)(fn) + + +@_disallow_in_graph_helper(throw_if_not_allowed=False) +def graph_break(msg: str = "") -> None: + """Force a graph break""" + + +# NOTE: primarily used for internal debugging purposes! +@_disallow_in_graph_helper(throw_if_not_allowed=False) +def skip_frame(msg: str = "") -> None: + """Force a skipped frame""" + + +@_disallow_in_graph_helper(throw_if_not_allowed=False) +def step_unsupported(msg: str = "") -> None: + """Force a step unsupported graph break, which results in compiling + the traced FX graph so far, then skipping the rest of the frame. + In order to get expected behavior, there should be at least 2 ops + and a part of the code not contained in any try/with blocks.""" + + +def forbid_in_graph(fn: Any) -> Any: + """ + Customize which functions TorchDynamo will assert are not present while tracing. + + If you want a graph break on this function instead, use disallow_in_graph. + TODO(voz): We now have allow_in_graph, disallow_in_graph, forbid_in_graph - some more robust + documentation would not be amiss. + """ + if isinstance(fn, (list, tuple)): + return [forbid_in_graph(x) for x in fn] + if not callable(fn): + raise AssertionError("forbid_in_graph applies only to callables") + # pyrefly: ignore [missing-attribute] + fn._dynamo_forbidden = True + return fn + + +def substitute_in_graph( + original_fn: Callable[_P, _R], + *, + can_constant_fold_through: bool = False, + skip_signature_check: bool = False, + # type that is embedded in the Python interpreter + is_embedded_type: bool = False, # internal use only +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """ + Register a polyfill handler for a function, usually a C function from the C extension, to be + used in place of the original function when inlining the original function in the graph. + + .. note:: + + The polyfill handler is only used when inlining the original function. It is not used when + the original function is called directly. In the eager mode, the decorated function calls + the performant C function rather than the polyfill handler. + + The polyfill handler is a function that will be called in place of the original function when + inlining the original function. The polyfill handler should have the same signature and the same + behavior as the original function. + + Args: + original_fn (callable): The original function, usually a C function, to register a polyfill + handler for. + can_constant_fold_through (bool, optional): Whether the polyfill handler can be constant + folded through. That is, if the polyfill handler is a pure function and its arguments + are constant, the result of the polyfill handler can be constant folded during the + compilation. Defaults to ``False``. + skip_signature_check (bool, optional): Whether to skip the signature check between the + original function and the polyfill handler. Defaults to ``False``. + + Returns: + A decorator that registers the polyfill handler for the original function. + + Example:: + + >>> # xdoctest: +SKIP("conflict with the tests: duplicate polyfill handlers") + >>> import operator + >>> operator.indexOf([1, 2, 3, 4, 5], 3) + 2 + >>> torch.compile(operator.indexOf, fullgraph=True)([1, 2, 3, 4, 5], 3) + Traceback (most recent call last): + ... + torch._dynamo.exc.Unsupported: ... + + >>> @torch.compiler.substitute_in_graph(operator.indexOf) + ... def indexOf(a, b, /): + ... for i, item in enumerate(a): + ... if item is b or item == b: + ... return i + ... raise ValueError("sequence.index(x): x not in sequence") + >>> + >>> torch.compile(operator.indexOf, fullgraph=True)([1, 2, 3, 4, 5], 3) + 2 + """ + if not is_function(original_fn) and not ( + is_embedded_type and inspect.isclass(original_fn) + ): + raise TypeError( + f"substitute_in_graph expects a function but got {type(original_fn)!r}" + ) + if is_embedded_type: + if not inspect.isclass(original_fn): + raise TypeError( + f"substitute_in_graph expects a class but got {type(original_fn)!r}" + ) + + from .variables.builder import ITERTOOLS_POLYFILLED_TYPE_IDS, ITERTOOLS_TYPE_IDS + + if id(original_fn) in ITERTOOLS_TYPE_IDS: + ITERTOOLS_POLYFILLED_TYPE_IDS.add(id(original_fn)) + + def wrapper(traceable_fn: Callable[_P, _R]) -> Callable[_P, _R]: + if not is_function(traceable_fn): + raise TypeError( + f"@substitute_in_graph(...) expects a function but got {type(traceable_fn)!r}" + ) + + if not skip_signature_check: + try: + original_sig = inspect.signature(original_fn) + except ValueError: + pass + else: + traceable_sig = inspect.signature(traceable_fn) + + def sig_ident( + sig: inspect.Signature, + ) -> tuple[tuple[str, ...], set[str], dict[str, Any]]: + # Ignore annotations for parameters and return type + return ( + tuple( + p.name + for p in sig.parameters.values() + if ( + p.kind + not in { + p.KEYWORD_ONLY, + # the name of *args and **kwargs is not important + p.VAR_POSITIONAL, + p.VAR_KEYWORD, + } + ) + ), + { + p.name + for p in sig.parameters.values() + if p.kind == p.KEYWORD_ONLY + }, + { + p.name: p.default + for p in sig.parameters.values() + # the name of *args and **kwargs is not important + if p.kind not in {p.VAR_POSITIONAL, p.VAR_KEYWORD} + }, + ) + + wildcard_sig = inspect.signature(lambda *args, **kwargs: None) + + if ( + sig_ident(original_sig) != sig_ident(traceable_sig) + and sig_ident(original_sig) != sig_ident(wildcard_sig) + and sig_ident(traceable_sig) != sig_ident(wildcard_sig) + ): + raise TypeError( + f"Signature mismatch between {original_fn} and {traceable_fn}: " + f"{original_sig} != {traceable_sig}" + ) + + from torch._dynamo.guards import GuardBuilder + from torch._dynamo.trace_rules import ( + _polyfilled_function_ids, + get_torch_obj_rule_map, + ) + from torch._dynamo.variables import PolyfilledFunctionVariable + from torch._dynamo.variables.builder import VariableBuilder + + id_dispatch_map = VariableBuilder._id_dispatch() + if id(original_fn) in id_dispatch_map: + raise ValueError( + f"Duplicate dispatch rule for {original_fn}: " + "already registered in VariableBuilder's id dispatch map" + ) + + if id(original_fn) in _polyfilled_function_ids: + raise ValueError(f"Duplicate polyfilled object {original_fn}") + + rule_map: dict[Any, type[VariableTracker]] = get_torch_obj_rule_map() + if original_fn in rule_map: + raise ValueError( + f"Duplicate object {original_fn} with different rules: " + f"{PolyfilledFunctionVariable}, {rule_map[original_fn]}" + ) + + polyfill_handlers: dict[Callable[..., Any], FunctionType] + polyfill_handlers = PolyfilledFunctionVariable._get_polyfill_handlers() + if original_fn in polyfill_handlers: + raise ValueError( + f"Duplicate polyfill handlers for {original_fn}: " + f"already handled by {polyfill_handlers[original_fn]}" + ) + + # Need to wrap the function because we may cannot assign __torch_dynamo_polyfill__ to a + # C++ function. + @functools.wraps(traceable_fn) + def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: + return original_fn(*args, **kwargs) + + def dispatch_fn( + self: VariableBuilder, value: Callable[_P, _R] + ) -> PolyfilledFunctionVariable: + if inspect.isclass(value): + guard_type = GuardBuilder.CLASS_MATCH + elif inspect.ismodule(value): + guard_type = GuardBuilder.MODULE_MATCH + else: + guard_type = GuardBuilder.ID_MATCH + guards = self.install_guards(guard_type) + if guards is None: + raise AssertionError("install_guards returned None") + return PolyfilledFunctionVariable( + value, + source=self.source, + **guards, + ) + + id_dispatch_map[id(original_fn)] = id_dispatch_map[id(wrapped)] = dispatch_fn + _polyfilled_function_ids.add(id(original_fn)) + _polyfilled_function_ids.add(id(wrapped)) + rule_map[original_fn] = rule_map[wrapped] = PolyfilledFunctionVariable + polyfill_handlers[original_fn] = polyfill_handlers[wrapped] = wrapped # type: ignore[assignment] + + wrapped.__torch_dynamo_original__ = original_fn # type: ignore[attr-defined] + wrapped.__torch_dynamo_polyfill__ = traceable_fn # type: ignore[attr-defined] + wrapped.__torch_dynamo_can_constant_fold_through__ = can_constant_fold_through # type: ignore[attr-defined] + + return wrapped # type: ignore[return-value] + + return wrapper + + +# Helper function to flatten a tensor subclass and apply a function to +# all inner tensors that match the outer dim. Used to reduce duplication +# across the various marking APIs. +def _apply_func_to_inner_tensors_of_same_dim( + func: Callable[..., Any], t: object, *args: Any, **kwargs: Any +) -> None: + if not is_traceable_wrapper_subclass(t): + raise AssertionError(f"Expected a traceable wrapper subclass, got {type(t)}") + + attrs, _ctx = t.__tensor_flatten__() + if not isinstance(t, torch.Tensor): + raise AssertionError(f"Expected a Tensor, got {type(t)}") + for attr in attrs: + match getattr(t, attr): + case torch.Tensor() as inner: + if inner.dim() == t.dim(): + func(inner, *args, **kwargs) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + +@dataclass(frozen=True, slots=True) +class _DimRange: + """ + This represents a dimension of a tensor and the corresponding + min and max values it can take. Don't create this + class directly; instead, use :func:`mark_dynamic`. + """ + + dim: int + min: int + max: int + + +@forbid_in_graph +def mark_unbacked( + t: Any, + index: int | list[Any] | tuple[Any], + hint_override: int | None = None, + strict: bool = False, + specialize_on: list[Any] | None = None, + shape_id: str | None = None, + min: int | None = None, + max: int | None = None, +) -> None: + """ + Mark a tensor as having an unbacked dimension. This changes the semantics of operations: + - The size of the specified dimension will always be reported as not equal to zero or one. + - Assertions on this index will be turned into runtime asserts. + - Attempting to get the real value of this dimension will raise an exception. + - In effect, this dimension is treated as data-dependent (its value is unknown). + + Args: + t (Any): The tensor to mark as having an unbacked dimension. + index (int or list/tuple of int): The dimension(s) to mark as unbacked. Can be a single + integer or a list/tuple of integers. Calls are additive: mark_unbacked(x, 0) followed + by mark_unbacked(x, 1) marks both dims. + hint_override (Optional[int], default=None): An optional integer to override the size hint for this dimension. + This is only used by the inductor backend for size hint queries, such as during autotuning. + NOTE: changing hint_override values will cause FxGraphCache misses, since hint overrides + affect inductor codegen decisions and are included in the cache key via + ShapeEnv.var_to_hint_override. + strict (bool, default=False): If True, an error will be raised if the unbacked dimension is specialized. + By default (strict=False), specialization is allowed and will proceed without error. + specialize_on (Optional[list[Any]], default=None): A list of specialization criteria (e.g., lambdas) for this dimension. + If provided, Dynamo will generate specialized compiled regions for each criterion in addition to a generic trace. + shape_id (Optional[str], default=None): An optional identifier to group unbacked dimensions together. + All unbacked dimensions with the same shape_id will share the same unbacked symbol. This is useful when multiple tensors + are known to have the same batch size at runtime. A runtime assertion is added + to ensure this property at runtime. + min (Optional[int], default=None): Minimum value constraint for this dimension. + If provided, a runtime check will be added to ensure the dimension is >= min. + max (Optional[int], default=None): Maximum value constraint for this dimension. + If provided, a runtime check will be added to ensure the dimension is <= max. + """ + if torch.distributed.is_available() and isinstance( + t, torch.distributed.tensor.DTensor + ): + # apply on inner tensor sizes/strides + mark_unbacked(t._local_tensor, index, shape_id=shape_id) + else: + # You could have copied the mark_dynamic behavior but I'm not convinced + # it's what you want + if is_traceable_wrapper_subclass(t): + raise AssertionError("not implemented yet") + + if isinstance(index, int): + if strict: + if not hasattr(t, "_dynamo_strict_unbacked_indices"): + t._dynamo_strict_unbacked_indices = set() + + t._dynamo_strict_unbacked_indices.add(index) + t._has_dynamo_dim_marking = True # type: ignore[attr-defined] + return + + if not hasattr(t, "_specialized_on"): + # pyrefly: ignore [implicit-any] + t._specialize_on = {} + + if not hasattr(t, "_dynamo_unbacked_indices"): + t._dynamo_unbacked_indices = set() + + if not hasattr(t, "_dynamo_hint_overrides"): + # pyrefly: ignore [implicit-any] + t._dynamo_hint_overrides = {} + + if hint_override: + t._dynamo_hint_overrides[index] = hint_override + + if min is not None or max is not None: + if not hasattr(t, "_dynamo_unbacked_bounds"): + # pyrefly: ignore [implicit-any] + t._dynamo_unbacked_bounds = {} + t._dynamo_unbacked_bounds[index] = (min, max) + + if shape_id is not None: + if not hasattr(t, "_dynamo_shape_ids"): + # pyrefly: ignore [implicit-any] + t._dynamo_shape_ids = {} + t._dynamo_shape_ids[index] = shape_id + + # FX tracers don't respect @forbid_in_graph and choke on the following error since it passes in proxies: + # TypeError: 'Attribute' object does not support item assignment + + if isinstance(t._specialize_on, dict): + t._specialize_on[index] = specialize_on if specialize_on is not None else [] + + t._dynamo_unbacked_indices.add(index) + t._has_dynamo_dim_marking = True # type: ignore[attr-defined] + return + + if not isinstance(index, (list, tuple)): + raise AssertionError( + f"Expected index to be int, list, or tuple, got {type(index)}" + ) + for i in index: + mark_unbacked(t, i, shape_id=shape_id, min=min, max=max) + + +@forbid_in_graph +def mark_dynamic( + t: Any, + index: int | list[Any] | tuple[Any], + *, + hint_override: int | None = None, + min: int | None = None, + max: int | None = None, + specialize_on: list[Any] | None = None, +) -> None: + """ + Mark a tensor as having a dynamic dim and set corresponding min and max range for the dim. + + [Note - on the state of mark_dynamic] + + The behavior of having a dynamic dimension on a tensor is governed by a few factors: + + 1) torch._dynamo.config dynamic_shapes True or False. + a) dynamic_shapes=True - dynamic_shapes must be True for mark_dynamic to work. + a) dynamic_shapes=False - This config will raise an exception when used in conjunction with + mark_dynamic. We will eventually support this. + + 2) If the dimension is fully constrained - as in, it does not allow more than a single value + in both eager (torch.compile, torch._dynamo.optimize) mode and export mode (torch._dynamo.export), + we will raise an error + + 3) If the dimension is partially constrained - allowing at least 2 values but not the full unbounded + range of shapes, in eager we will pass it through, but export will raise an error. + + 4) Attempts to trace this function will explicitly raise. As such, all calls to mark_dynamic must be made + before torch.compile. + + 5) If hint_override is passed, the hint_override for the specified dimension will replace the provided value + from the first example input as the official size hint. Note: changing hint_override values will cause + FxGraphCache misses, since hint overrides affect inductor codegen decisions (autotuning, reduction + strategy, etc.) and are included in the cache key via ShapeEnv.var_to_hint_override. + + 6) If specialize_on is passed in, we will perform a single generic Dynamo trace followed by + multiple specialized compilations in addition to a single generic compilation. NB: For now we only support + per dimension specialization, or in other words we do not generate a cross product of specializations. + At runtime, we will dispatch to a specialized compiled region if the input matches the specialization criteria. + + For example: + mark_dynamic(..., specialize_on=[ + lambda x: x == 8, + lambda x: x == 16 + ]) + + This approach results in one Dynamo trace and two backend compilations. When the input dimension equals 8 or 16 + at runtime, execution will be directed to the specialized compiled region. Performance measurements indicate + 2-8x speedups depending on the specific specialization and model architecture. + """ + if is_traceable_wrapper_subclass(t): + # default behavior: mirror mark_dynamic() on all inner tensors with same dim as t + # TODO: Make this configurable via a supported public API + _apply_func_to_inner_tensors_of_same_dim( + mark_dynamic, t, index, min=min, max=max + ) + + if isinstance(index, int): + if not hasattr(t, "_dynamo_dynamic_indices"): + t._dynamo_dynamic_indices = set() + + t._dynamo_dynamic_range = set() + + # pyrefly: ignore [implicit-any] + t._dynamo_hint_overrides = {} + + if not hasattr(t, "_specialize_on"): + # pyrefly: ignore [implicit-any] + t._specialize_on = {} + + if hint_override: + t._dynamo_hint_overrides[index] = hint_override + # TODO(voz): Should we bounds check? + + t._dynamo_dynamic_indices.add(index) + t._dynamo_dynamic_range.add(_DimRange(index, min, max)) # type: ignore[arg-type] + t._has_dynamo_dim_marking = True # type: ignore[attr-defined] + + # FX tracers don't respect @forbid_in_graph and choke on the following error since it passes in proxies: + # TypeError: 'Attribute' object does not support item assignment + + if isinstance(t._specialize_on, dict): + t._specialize_on[index] = specialize_on if specialize_on is not None else [] + + return + + if not isinstance(index, (list, tuple)): + raise AssertionError( + f"Expected index to be int, list, or tuple, got {type(index)}" + ) + for i in index: + mark_dynamic(t, i, min=min, max=max, specialize_on=specialize_on) + + +@forbid_in_graph +def maybe_mark_dynamic(t: Any, index: int | list[Any] | tuple[Any]) -> None: + """ + Mark a tensor as having a dynamic dim, but don't enforce it (i.e., if this + dimension ends up getting specialized, don't error). + """ + if is_traceable_wrapper_subclass(t): + # default behavior: mirror maybe_mark_dynamic() on all inner tensors with same dim as t + # TODO: Make this configurable via a supported public API + _apply_func_to_inner_tensors_of_same_dim(maybe_mark_dynamic, t, index) + + if isinstance(index, int): + if not hasattr(t, "_dynamo_weak_dynamic_indices"): + t._dynamo_weak_dynamic_indices = set() + # TODO(voz): Should we bounds check? + + t._dynamo_weak_dynamic_indices.add(index) + t._has_dynamo_dim_marking = True # type: ignore[attr-defined] + return + + if not isinstance(index, (list, tuple)): + raise AssertionError( + f"Expected index to be int, list, or tuple, got {type(index)}" + ) + for i in index: + maybe_mark_dynamic(t, i) + + +def mark_static(t: Any, index: int | list[Any] | tuple[Any] | None = None) -> None: + """ + Mark a tensor as having a static dim or mark a nn module class as static. + + For tensors + =========== + This will prevent us from attempting to compile it dynamically + when dynamic=True; this can improve trace-time performance. + + This has lower precedence than mark_dynamic. + + Unlike mark_dynamic, this can be done inside a graph, in which case it + induces specialization on the tensor. + + For nn.Module classes + ===================== + For static nn.Module classes, TorchDynamo assumes that the module instance + attributes will not be modified after compilation. This will ensure that + TorchDynamo keeps integer attributes CONSTANT and not symints. + + From TorchDynamo implementation side, the instances of static-marked + nn.Module class will be converted to UnspecializedBuiltinNNModuleVariable, + which have the same properties. + + Note that we still have to guard on the attributes, because different + instances of the nn.Module can have different values of the attributes. The + key point here is that the attributes are static. + """ + if is_compiling(): + if index is None: + for s in t.size(): + comptime.force_static(s) + else: + comptime.force_static(t.size(index)) + return + + if is_traceable_wrapper_subclass(t): + # default behavior: mirror mark_static() on all inner tensors with same dim as t + # TODO: Make this configurable via a supported public API + _apply_func_to_inner_tensors_of_same_dim(mark_static, t, index) + + if not isinstance(t, torch.Tensor) and issubclass(t, torch.nn.Module): + t._dynamo_marked_static = True + # pyrefly: ignore [bad-return] + return t + + if not isinstance(t, torch.Tensor): + raise TypeError( + f"mark_static expects a tensor/nn.Module class but received {type(t)}" + ) + + if isinstance(index, int): + if not hasattr(t, "_dynamo_static_indices"): + t._dynamo_static_indices = set() # type: ignore[attr-defined] + # TODO(voz): Should we bounds check? + t._dynamo_static_indices.add(index) # type: ignore[attr-defined] + t._has_dynamo_dim_marking = True # type: ignore[attr-defined] + elif index is None: + for i in range(t.dim()): + mark_static(t, i) + else: + if not isinstance(index, (list, tuple)): + raise AssertionError( + f"Expected index to be int, list, or tuple, got {type(index)}" + ) + for i in index: + mark_static(t, i) + + +@forbid_in_graph +def mark_static_address(t: Any, guard: bool = False) -> None: + """ + Marks an input tensor whose address should be treated as constant across calls to the + same dynamo-compiled function. This indicates to cudagraphs that an extra allocation + is not needed for this input. The data_ptr will be guarded if guard=True, and cause a full + recompile if the data_ptr changes. Note: If this address changes, cudagraphs will re-record + if guard=False. + """ + if not isinstance(t, torch.Tensor): + raise TypeError(f"mark_static_address expects a tensor but received {type(t)}") + + if guard: + t._dynamo_static_input_type = "guarded" # type: ignore[attr-defined] + else: + t._dynamo_static_input_type = "unguarded" # type: ignore[attr-defined] + + +def _patch_einops_symint_compat(einops_mod: Any) -> None: + """Backport the SymInt lru_cache fix from einops 0.7.0 into einops <= 0.6.1.""" + for name in ("_reconstruct_from_shape", "_prepare_transformation_recipe"): + cached = getattr(einops_mod, name) + uncached = cached.__wrapped__ + + def make_wrapper(cached_fn: Any, uncached_fn: Any) -> Any: + @functools.wraps(cached_fn) + def wrapper(*args: Any, **kwargs: Any) -> Any: + try: + return cached_fn(*args, **kwargs) + except TypeError: + return uncached_fn(*args, **kwargs) + + return wrapper + + setattr(einops_mod, name, make_wrapper(cached, uncached)) + + +_EINOPS_DYNAMO_TRACING_MIN_VERSION = Version("0.8.2") +# Known pure parser/shape helpers in einops 0.8.2. Keep this explicit so +# unrelated or future lru_cache wrappers continue through the normal warning path. +_EINOPS_LRU_CACHE_WRAPPER_ALLOWLIST = ( + ( + "einops.einops", + ( + "_reconstruct_from_shape", + "_prepare_transformation_recipe", + "_compactify_pattern_for_einsum", + ), + ), + ("einops.packing", ("analyze_pattern",)), +) + + +def _einops_supports_dynamo_tracing(einops_mod: Any) -> bool: + try: + return Version(einops_mod.__version__) >= _EINOPS_DYNAMO_TRACING_MIN_VERSION + except InvalidVersion: + return False + + +def _allow_lru_cache_trace_without_warning_for_einops() -> None: + import importlib + + for module_name, attr_names in _EINOPS_LRU_CACHE_WRAPPER_ALLOWLIST: + try: + module = importlib.import_module(module_name) + except ImportError: + continue + + for attr_name in attr_names: + obj = getattr(module, attr_name, None) + if is_lru_cache_wrapped_function(obj): + allow_lru_cache_wrapper_trace_without_warning(obj) + + +# Dynamo can trace through einops 0.8.2+ directly (no allow_in_graph needed). +# Older versions still need the allow_in_graph registration below. +def _allow_in_graph_einops() -> None: + import einops + + if _einops_supports_dynamo_tracing(einops): + if hasattr(einops, "einops") and hasattr(einops.einops, "get_backend"): + # trigger backend registration up front to avoid a later guard failure + # that would otherwise cause a recompilation + einops.rearrange(torch.empty(1), "i -> i") + # einops uses lru_cache for pure library-internal recipe helpers. Mark + # only those wrappers so general lru_cache warnings are unchanged. + _allow_lru_cache_trace_without_warning_for_einops() + return + + try: + # requires einops > 0.6.1, torch >= 2.0 + from einops._torch_specific import ( # type: ignore[attr-defined] # noqa: F401 + _ops_were_registered_in_torchdynamo, + ) + + # einops > 0.6.1 will call the op registration logic as it is imported. + except ImportError: + # einops <= 0.6.1 doesn't handle unhashable SymInt in its lru_cache'd + # helpers. Backport the try/except TypeError fallback from einops 0.7.0+ + # so allow_in_graph works during fake tensor validation. + _patch_einops_symint_compat(einops.einops) # type: ignore[attr-defined] + allow_in_graph(einops.rearrange) + allow_in_graph(einops.reduce) + if hasattr(einops, "repeat"): + allow_in_graph(einops.repeat) # available since einops 0.2.0 + if hasattr(einops, "einsum"): + allow_in_graph(einops.einsum) # available since einops 0.5.0 + if hasattr(einops, "pack"): + allow_in_graph(einops.pack) # available since einops 0.6.0 + if hasattr(einops, "unpack"): + allow_in_graph(einops.unpack) # available since einops 0.6.0 + + +# Note: this carefully avoids eagerly import einops. +trace_rules.add_module_init_func("einops", _allow_in_graph_einops) + + +class _ConfigPatchProtocol(Protocol): + """The config.patch() context manager object wrapped by DynamoConfigPatchProxy.""" + + changes: dict[str, Any] + + def __enter__(self) -> None: ... + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: ... + + +# Proxy class for torch._dynamo.config patching - so dynamo can identify context managers/decorators +# created by patch_dynamo_config, compared to ones created by a raw torch._dynamo.config.patch. +class DynamoConfigPatchProxy: + def __init__(self, config_patch: _ConfigPatchProtocol) -> None: + self.config_patch = config_patch + + @property + def changes(self) -> dict[str, Any]: + return self.config_patch.changes + + # Decorator implementation that simply sets up `self` as a context manager. + # Placed in external_utils so that we can trace through it. + __call__ = wrap_dunder_call_ctx_manager + + def __enter__(self) -> None: + return self.config_patch.__enter__() + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + return self.config_patch.__exit__(exc_type, exc_val, exc_tb) + + +# Criteria for patchable config: +# - Config values must be constants (i.e. int, float, str, bool, None). +# - in particular, NO list, set, dict. +# - Traceable config patches are only useful for configs that change dynamo behavior +# from symbolic_convert and below. +# - e.g. patching recompile_limit won't really do anything. +# - For patching configs that affect Dynamo behavior above symbolic_convert, +# ensure that Dynamo behaves soundly even if tracing is done with different config. +# - e.g. be careful if patching guard-related configs as configs may have changed +# between guard creation and evaluation. +_allowed_config_patches = ( + "verbose", + "verify_correctness", + "rewrite_assert_with_torch_assert", + "capture_scalar_outputs", + "allow_unspec_int_on_nn_module", + "skip_torchrec", + "dont_skip_tracing", + "nested_graph_breaks", +) + +from . import config + + +for name in _allowed_config_patches: + if not hasattr(config, name): + raise AssertionError(f"nonexistent config: {name}") +del config + + +def _patch_dynamo_config_check(changes: dict[str, Any]) -> None: + for k, v in changes.items(): + if k not in _allowed_config_patches: + raise ValueError( + f"patch_dynamo_config does not support patching config {k}" + ) + if not torch._dynamo.utils.is_safe_constant(v): + raise ValueError( + f"patch_dynamo_config does not support patching config {k} " + f"with non-safe-constant value {v}" + ) + + +# TODO: also implement nonrecursive patch_dynamo_config/dont_skip_tracing. +# Unlike config.patch, we also need to accept tuple as input in order to +# deal with context manager reconstruction. +def patch_dynamo_config( + arg1: str | dict[str, Any] | tuple[tuple[str, Any], ...] | None = None, + arg2: Any = None, + **kwargs: Any, +) -> DynamoConfigPatchProxy: + """ + A wrapper around torch._dynamo.config.patch that can be traced by Dynamo to + temporarily change config values DURING tracing. + + See _allowed_config_patches for the list of allowed config patches. + + Arguments are the same as with torch._dynamo.config.patch. + + Can be used as a decorator or a context manager. + + User code SHOULD NOT MODIFY the return value of this function. + + WARNING: changing Dynamo config during tracing can lead to unpredictable tracing behavior! + Proceed only as advised! + """ + if isinstance(arg1, tuple): + arg1 = dict(arg1) + config_patch = torch._dynamo.config.patch(arg1, arg2, **kwargs) + _patch_dynamo_config_check(config_patch.changes) + # check for valid patching using config_patch.changes + return DynamoConfigPatchProxy(config_patch) + + +@overload +def dont_skip_tracing(fn: None = None) -> DynamoConfigPatchProxy: ... + + +@overload +def dont_skip_tracing(fn: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +def dont_skip_tracing(fn: Any | None = None) -> Any: + """ + Context manager/decorator to trace into functions intentionally marked by developers to be skipped + when tracing. + + This decorator will also apply to recursively invoked functions. + """ + ctx = patch_dynamo_config(dont_skip_tracing=True) + if fn: + return ctx(fn) + return ctx + + +@overload +def disable_nested_graph_breaks(fn: None = None) -> DynamoConfigPatchProxy: ... + + +@overload +def disable_nested_graph_breaks(fn: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +def disable_nested_graph_breaks(fn: Any | None = None) -> Any: + """ + Context manager/decorator to disable nested graph breaks when tracing + this function and any nested functions. Used when nested graph breaks + is causing problems. + """ + ctx = patch_dynamo_config(nested_graph_breaks=False) + if fn: + return ctx(fn) + return ctx + + +class ErrorOnGraphBreakDecoratorContextManager: + def __init__(self, error_on_graph_break: bool) -> None: + self.error_on_graph_break = error_on_graph_break + self.prev_error_on_graph_break: list[bool | None] = [] + + __call__ = wrap_dunder_call_ctx_manager + + def __enter__(self) -> None: + current_error_on_graph_break = _get_error_on_graph_break() + if current_error_on_graph_break != self.error_on_graph_break: + self.prev_error_on_graph_break.append(current_error_on_graph_break) + _set_error_on_graph_break(self.error_on_graph_break) + else: + self.prev_error_on_graph_break.append(None) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + prev_error_on_graph_break = self.prev_error_on_graph_break.pop() + if prev_error_on_graph_break is not None: + _set_error_on_graph_break(prev_error_on_graph_break) + + +def error_on_graph_break( + error_on_graph_break: bool, +) -> ErrorOnGraphBreakDecoratorContextManager: + """ + Context manager/decorator to toggle torch.compile's `error_on_graph_break` setting at compile time. + + If `fullgraph` is set, then `error_on_graph_break` does nothing + (i.e. `fullgraph = True` takes higher precedence). If `fullgraph` is False, then + `error_on_graph_break` determines whether `torch.compile` throws an error upon + encountering a graph break, or attempts to continue tracing. + + `error_on_graph_break` can be toggled during compile time with this decorator to allow graph breaks in some + compiled regions but not others. One key difference from `fullgraph` is that `error_on_graph_break = True` + does NOT guarantee that a single graph is captured from the compiled function. + + The default value of torch.compile's `error_on_graph_break` setting is False. + """ + return ErrorOnGraphBreakDecoratorContextManager(error_on_graph_break) + + +class CudagraphOverrideContextManager: + """Context manager that overrides cudagraph recording during tracing.""" + + def __init__(self, fwd: bool | None = None, bwd: bool | None = None) -> None: + self.fwd = fwd + self.bwd = bwd + self.prev_cudagraph_override: list[tuple[bool | None, bool | None] | None] = [] + + __call__ = wrap_dunder_call_ctx_manager + + def __enter__(self) -> None: + # Set the override at runtime so it follows the dynamic call stack. + # Dynamo handles the lexical `with` symbolically and does not run this + # __enter__ at trace time; it runs when the generated/resumed bytecode + # re-enters the context, before invoking callees that are compiled as + # separate frames. OutputGraph seeds its annotation from this value via + # _get_cudagraph_override. Mirrors ErrorOnGraphBreakDecoratorContextManager. + self.prev_cudagraph_override.append(_get_cudagraph_override()) + _set_cudagraph_override((self.fwd, self.bwd)) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + _set_cudagraph_override(self.prev_cudagraph_override.pop()) + + +def override_cudagraphs( + fwd: bool | None = None, bwd: bool | None = None +) -> CudagraphOverrideContextManager: + """ + Context manager/decorator to override cudagraph recording for compiled graphs. + + When used as a context manager, overrides cudagraphs for all graph segments + within the block (including across graph breaks). + + When used as a decorator, marks a function so that any compiled graph + inlining it will have cudagraphs overridden. + + Args: + fwd: If False, disable cudagraphs for forward. If True, force enable. + If None, don't override. + bwd: If False, disable cudagraphs for backward. If True, force enable. + If None, don't override. + """ + return CudagraphOverrideContextManager(fwd=fwd, bwd=bwd) + + +def override_optimization_hint(x: Any, val: int) -> None: + """Override the optimization hint for a scalar unbacked symbol. + + When the compiler or runtime needs a non-guarding integer hint for an + unbacked ``SymInt`` — for example during FX passes, graph partitioning, + or inductor autotuning — it calls + ``_optimization_hint_base`` + (see ``torch/fx/experimental/_size_hinting.py``). By default + that function uses internal heuristics to choose a hint and a global fixed + fallback; + this function lets user code override that choice. This is similar to + the ``hint_override`` parameter in ``mark_unbacked``, but applies to + symbols that already exist (e.g. from ``.item()`` calls). + + Typical usage:: + + u = x.item() # unbacked SymInt + torch._dynamo.override_optimization_hint(u, 42) + # From now on, any call to shape_env.optimization_hint(u, ...) + # returns 42 instead of the default heuristic value. + + This updates ``shape_env.var_to_hint_override`` so that any consumer + of ``_optimization_hint_base`` sees *val* as the hint for the + unbacked symbol behind *x*. + + Works both eagerly (during FX passes or outside dynamo) and inside + ``torch.compile`` regions. + + Behavior during compilation: + The dynamo handler applies the hint as a **side effect** on + ``shape_env.var_to_hint_override`` during tracing. No FX graph + node is emitted — the call is fully consumed at trace time and + does not appear in the pre-grad, joint, or post-autograd graphs. + ``FXGraphCache`` includes ``var_to_hint_override`` in its cache + key, so cache hits/misses correctly reflect hint changes. + + .. note:: + + To maximize performance, it is recommended to pass hints for + **all** unbacked symbols in the program to guide optimizations. + + Args: + x: A ``torch.SymInt`` wrapping an unbacked symbol (e.g. from + ``.item()``), or a plain ``int``. If *x* is a plain ``int`` + the call is a no-op. + val: The integer hint value to record. + """ + if not isinstance(val, int): + raise TypeError( + f"override_optimization_hint expects val to be an int, got {type(val)}" + ) + if isinstance(x, int): + return + if not isinstance(x, torch.SymInt): + raise TypeError( + f"override_optimization_hint expects a torch.SymInt or int, got {type(x)}" + ) + shape_env = not_none(x.node.shape_env) + expr = x.node.expr + import sympy + + if not isinstance(expr, sympy.Symbol): + raise ValueError( + f"override_optimization_hint expects a single unbacked symbol, " + f"got derived expression: {expr}" + ) + if not shape_env.is_unbacked_symint(expr): + raise ValueError( + f"override_optimization_hint expects an unbacked symbol, " + f"but {expr} is backed" + ) + shape_env._set_unbacked_var_to_hint_override(x, val) + + +def is_dynamo_disable_recursive(method: Callable[[Any], Any]) -> bool | None: + """ + Check if a method is marked as `dynamo_disable` recursively. It returns: + - True if disable(recursive=True) + - False if disable(recursive=False) + - None if method is not a disable decorator + """ + return getattr(method, "_torchdynamo_disable_recursive", None) + + +_HASH_SLOTS = ("__hash__",) +_RICHCOMPARE_SLOTS = ("__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__") + + +def allow_c_slot( + tp: type, + *, + tp_hash: bool = True, + tp_richcompare: bool = True, +) -> type: + """Register a C extension type's slots as safe to call at trace time. + + By default, ``torch.compile`` graph-breaks when it encounters ``hash()`` + or comparison operators on a C extension type with custom C slots (e.g., + types defined in C extension modules). This function tells Dynamo that the + type's C slots are safe to evaluate during tracing, avoiding graph breaks. + + The slot functions must satisfy these requirements: + + - **Pure**: depends only on the object's value, with no observable side + effects (no I/O, no mutation of global state). + - **Deterministic**: returns the same result for the same object across + calls within a process. + - **Immutable objects**: the object's state must not change after + construction in a way that affects the slot's return value. + + Builtin types (``int``, ``str``, etc.) and Python-level dunder methods + are already handled and do not need registration. This API is only needed + for C extension types whose C slots Dynamo cannot trace into. + + Args: + tp: The C extension type whose C slots should be allowed. + tp_hash: Register ``__hash__`` as safe (default True). + tp_richcompare: Register comparison dunders as safe (default True). + + Returns: + The type, unchanged (so it can be used as a decorator). + + Example:: + + import torch._dynamo + from my_extension import MyType + + # Register all slots (hash + comparison) + torch._dynamo.allow_c_slot(MyType) + + # Register only hash + torch._dynamo.allow_c_slot(MyType, tp_richcompare=False) + + # Register only comparison + torch._dynamo.allow_c_slot(MyType, tp_hash=False) + """ + from .variables.user_defined import _safe_c_slots + + if not isinstance(tp, type): + raise TypeError(f"allow_c_slot expects a type, got {type(tp).__name__}") + safe = _safe_c_slots() + dunders = () + if tp_hash: + dunders += _HASH_SLOTS + if tp_richcompare: + dunders += _RICHCOMPARE_SLOTS + for dunder in dunders: + fn = getattr(tp, dunder, None) + if fn is not None and fn is not getattr(object, dunder, None): + safe.add(fn) + return tp diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/device_interface.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/device_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..2a892269d32a48d0518cf6ff1149a2933921ed03 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/device_interface.py @@ -0,0 +1,681 @@ +""" +Device abstraction layer for TorchDynamo and Inductor backends. + +This module provides a unified interface for different hardware backends (CUDA, XPU, +CPU, MPS, MTIA) through a common device interface. Key components include: + +- DeviceInterface: Base class defining the common API for all device types +- Device-specific implementations: CudaInterface, XpuInterface, CpuInterface, MpsInterface, MtiaInterface +- Device registration system for managing available backends +- Worker APIs for multi-processing scenarios +- Stream and event management across different devices +- Device property caching for worker processes + +The abstraction layer enables device-agnostic code in TorchDynamo while allowing +specialized implementations for each hardware backend's unique features. +""" + +import inspect +import time +from collections import namedtuple +from collections.abc import Callable, Iterable +from dataclasses import dataclass +from typing import Any, Literal + +import torch +from torch.utils._pallas import has_torch_tpu + + +get_cuda_stream: Callable[[int], int] | None +if torch.cuda._is_compiled(): + from torch._C import _cuda_getCurrentRawStream as get_cuda_stream +else: + get_cuda_stream = None + +# Recording the device properties in the main process but used in worker process. +caching_worker_device_properties: dict[str, Any] = {} +caching_worker_current_devices: dict[str, int] = {} + + +class DeviceInterface: + """ + This is a simple device runtime interface for Inductor. It enables custom + backends to be integrated with Inductor in a device-agnostic semantic. + """ + + class device: + def __new__(cls, device: torch.types.Device) -> Any: + raise NotImplementedError + + class Event: + def __new__(cls, *args: Any, **kwargs: Any) -> Any: + raise NotImplementedError( + "Event should be inherited from torch.Event, otherwise, it couldn't be captured by dynamo." + ) + + class Stream: + def __new__(cls, *args: Any, **kwargs: Any) -> Any: + raise NotImplementedError( + "Stream should be inherited from torch.Stream, otherwise, it couldn't be captured by dynamo." + ) + + class Worker: + """ + Worker API to query device properties that will work in multi processing + workers that cannot use the GPU APIs (due to processing fork() and + initialization time issues). Properties are recorded in the main process + before we fork the workers. + """ + + @staticmethod + def set_device(device: int) -> None: + raise NotImplementedError + + @staticmethod + def current_device() -> int: + raise NotImplementedError + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + raise NotImplementedError + + @staticmethod + def current_device() -> int: + raise NotImplementedError + + @staticmethod + def set_device(device: torch.types.Device) -> None: + raise NotImplementedError + + @staticmethod + def maybe_exchange_device(device: int) -> int: + raise NotImplementedError + + @staticmethod + def exchange_device(device: int) -> int: + raise NotImplementedError + + @staticmethod + def device_count() -> int: + raise NotImplementedError + + @staticmethod + def is_available() -> bool: + raise NotImplementedError + + @staticmethod + def stream(stream: torch.Stream) -> Any: + raise NotImplementedError + + @staticmethod + def current_stream() -> torch.Stream: + raise NotImplementedError + + @staticmethod + def set_stream(stream: torch.Stream) -> None: + raise NotImplementedError + + @staticmethod + def _set_stream_by_id(stream_id: int, device_index: int, device_type: int) -> None: + raise NotImplementedError + + @staticmethod + def get_raw_stream(device_idx: int) -> int: + raise NotImplementedError + + @staticmethod + def synchronize(device: torch.types.Device = None) -> None: + raise NotImplementedError + + @classmethod + def get_device_properties(cls, device: torch.types.Device = None) -> Any: + return cls.Worker.get_device_properties(device) + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> Any: + raise NotImplementedError + + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + raise NotImplementedError + + @classmethod + def is_dtype_supported( + cls, dtype: torch.dtype, including_emulation: bool = False + ) -> bool: + return dtype != torch.bfloat16 or cls.is_bf16_supported(including_emulation) + + @staticmethod + def memory_allocated(device: torch.types.Device = None) -> int: + raise NotImplementedError + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + """ + Returns True if the device has Triton support, False otherwise, even if + the appropriate Triton backend is not available. + """ + return False + + @classmethod + def raise_if_triton_unavailable(cls, device: torch.types.Device = None) -> None: + """ + Raises a `TritonUnavailableError` with human-readable instructions if + the Triton backend for the given device (or the default device if + `device` is `None`) is not built. Implementations may raise a + different, more specific error when the device itself is not + Triton-capable (e.g. CUDA raises `GPUTooOldForTriton`), so callers + that only want an availability answer should check + `is_triton_capable()` first. + + The caller should ensure the presence of the 'triton' package before + calling this method. + """ + from torch._dynamo.exc import TritonUnavailableError + + if not cls.is_triton_capable(): + raise TritonUnavailableError( + "This device is not capable of supporting Triton" + ) + + +class DeviceGuard: + """ + This class provides a context manager for device switching. This is a stripped + down version of torch.{device_name}.device. + + The context manager changes the current device to the given device index + on entering the context and restores the original device on exiting. + The device is switched using the provided device interface. + """ + + def __init__( + self, device_interface: type[DeviceInterface], index: int | None + ) -> None: + self.device_interface = device_interface + self.idx = index + self.prev_idx = -1 + + def __enter__(self) -> None: + if self.idx is not None: + self.prev_idx = self.device_interface.exchange_device(self.idx) + + def __exit__(self, type: Any, value: Any, traceback: Any) -> Literal[False]: + if self.idx is not None: + self.idx = self.device_interface.maybe_exchange_device(self.prev_idx) + return False + + +class CudaInterface(DeviceInterface): + device = torch.cuda.device # type: ignore[assignment] + + # register Event and Stream class into the backend interface + # make sure Event and Stream are implemented and inherited from the torch.Event and torch.Stream + Event = torch.cuda.Event # type: ignore[assignment] + Stream = torch.cuda.Stream # type: ignore[assignment] + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def set_device(device: int) -> None: + caching_worker_current_devices["cuda"] = device + + @staticmethod + def current_device() -> int: + if "cuda" in caching_worker_current_devices: + return caching_worker_current_devices["cuda"] + return torch.cuda.current_device() + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + if device is not None: + if isinstance(device, str): + device = torch.device(device) + if device.type != "cuda": + raise AssertionError( + f"Expected device type 'cuda', got '{device.type}'" + ) + if isinstance(device, torch.device): + device = device.index + if device is None: + device = CudaInterface.Worker.current_device() + + if "cuda" not in caching_worker_device_properties: + device_prop = [ + torch.cuda.get_device_properties(i) + for i in range(torch.cuda.device_count()) + ] + caching_worker_device_properties["cuda"] = device_prop + + return caching_worker_device_properties["cuda"][device] + + current_device = staticmethod(torch.cuda.current_device) + set_device = staticmethod(torch.cuda.set_device) + device_count = staticmethod(torch.cuda.device_count) + stream = staticmethod(torch.cuda.stream) # type: ignore[assignment] + current_stream = staticmethod(torch.cuda.current_stream) + set_stream = staticmethod(torch.cuda.set_stream) # type: ignore[assignment] + _set_stream_by_id = staticmethod(torch.cuda._set_stream_by_id) # type: ignore[assignment] + synchronize = staticmethod(torch.cuda.synchronize) + get_device_properties = staticmethod(torch.cuda.get_device_properties) # type: ignore[assignment] + get_raw_stream = staticmethod(get_cuda_stream) # type: ignore[assignment, arg-type] + exchange_device = staticmethod(torch.cuda._exchange_device) # type: ignore[arg-type, has-type] + maybe_exchange_device = staticmethod(torch.cuda._maybe_exchange_device) # type: ignore[arg-type, has-type] + memory_allocated = staticmethod(torch.cuda.memory_allocated) + is_bf16_supported = staticmethod(torch.cuda.is_bf16_supported) # type: ignore[arg-type] + + # Can be mock patched by @patch decorator. + @staticmethod + def is_available() -> bool: + return torch.cuda.is_available() + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> int | str: + if torch.version.hip is None: + major, min = torch.cuda.get_device_capability(device) + return major * 10 + min + else: + return torch.cuda.get_device_properties(device).gcnArchName.split(":", 1)[0] + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + # Use the Worker API (device properties cached in the main process + # before fork) instead of torch.cuda.get_device_properties directly, so + # the capability check stays safe when called from spawn-based compile + # workers. + return ( + torch.version.hip is not None + or CudaInterface.Worker.get_device_properties(device).major >= 7 + ) + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + from torch._dynamo.exc import TritonUnavailableError + from torch._inductor.exc import GPUTooOldForTriton + + if not CudaInterface.is_triton_capable(device): + device_props = torch.cuda.get_device_properties(device) + raise GPUTooOldForTriton(device_props, inspect.currentframe()) + + import triton.backends + + if torch.version.hip is not None: + if "amd" not in triton.backends.backends: + raise TritonUnavailableError("triton not built with the 'amd' backend") + elif "nvidia" not in triton.backends.backends: + raise TritonUnavailableError("triton not built with the 'nvidia' backend") + + +get_mtia_stream: Callable[[int], int] | None +if torch.mtia._is_compiled(): + from torch._C import _mtia_getCurrentRawStream as get_mtia_stream +else: + get_mtia_stream = None + + +class MtiaInterface(DeviceInterface): + device = torch.mtia.device # type: ignore[assignment] + Event = torch.mtia.Event # type: ignore[assignment] + Stream = torch.mtia.Stream # type: ignore[assignment] + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def set_device(device: int) -> None: + caching_worker_current_devices["mtia"] = device + + @staticmethod + def current_device() -> int: + if "mtia" in caching_worker_current_devices: + return caching_worker_current_devices["mtia"] + return torch.mtia.current_device() + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + if device is not None: + if isinstance(device, str): + device = torch.device(device) + if device.type != "mtia": + raise AssertionError( + f"Expected device type 'mtia', got '{device.type}'" + ) + if isinstance(device, torch.device): + device = device.index + if device is None: + device = MtiaInterface.Worker.current_device() + + if "mtia" not in caching_worker_device_properties: + device_prop = [ + torch.mtia.get_device_properties(i) + for i in range(torch.mtia.device_count()) + ] + caching_worker_device_properties["mtia"] = device_prop + + return caching_worker_device_properties["mtia"][device] + + current_device = staticmethod(torch.mtia.current_device) + set_device = staticmethod(torch.mtia.set_device) # type: ignore[assignment] + device_count = staticmethod(torch.mtia.device_count) + stream = staticmethod(torch.mtia.stream) # type: ignore[assignment] + current_stream = staticmethod(torch.mtia.current_stream) + set_stream = staticmethod(torch.mtia.set_stream) # type: ignore[assignment] + _set_stream_by_id = staticmethod(torch.mtia._set_stream_by_id) # type: ignore[assignment] + synchronize = staticmethod(torch.mtia.synchronize) + get_device_properties = staticmethod(torch.mtia.get_device_properties) # type: ignore[assignment] + get_raw_stream = staticmethod(get_mtia_stream) # type: ignore[assignment, arg-type] + exchange_device = staticmethod(torch.mtia._exchange_device) # type: ignore[arg-type, has-type] + maybe_exchange_device = staticmethod(torch.mtia._maybe_exchange_device) # type: ignore[arg-type, has-type] + memory_allocated = staticmethod(torch.mtia.memory_allocated) # type: ignore[assignment] + is_bf16_supported = staticmethod(torch.mtia.is_bf16_supported) # type: ignore[arg-type] + + # Can be mock patched by @patch decorator. + @staticmethod + def is_available() -> bool: + ret = torch.mtia.is_available() + return ret + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> Any: + cc = torch.mtia.get_device_capability(device) + return cc + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + return True + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + import triton.backends + + from torch._dynamo.exc import TritonUnavailableError + + if "mtia" not in triton.backends.backends: + raise TritonUnavailableError("triton not built with the 'mtia' backend") + + +get_xpu_stream: Callable[[int], int] | None +if torch.xpu._is_compiled(): + from torch._C import _xpu_getCurrentRawStream as get_xpu_stream +else: + get_xpu_stream = None + + +class XpuInterface(DeviceInterface): + device = torch.xpu.device # type: ignore[assignment] + Event = torch.xpu.Event # type: ignore[assignment] + Stream = torch.xpu.Stream # type: ignore[assignment] + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def set_device(device: int) -> None: + caching_worker_current_devices["xpu"] = device + + @staticmethod + def current_device() -> int: + if "xpu" in caching_worker_current_devices: + return caching_worker_current_devices["xpu"] + return torch.xpu.current_device() + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + if device is not None: + if isinstance(device, str): + device = torch.device(device) + if device.type != "xpu": + raise AssertionError( + f"Expected device type 'xpu', got '{device.type}'" + ) + if isinstance(device, torch.device): + device = device.index + if device is None: + device = XpuInterface.Worker.current_device() + + if "xpu" not in caching_worker_device_properties: + device_prop = [ + torch.xpu.get_device_properties(i) + for i in range(torch.xpu.device_count()) + ] + caching_worker_device_properties["xpu"] = device_prop + + return caching_worker_device_properties["xpu"][device] + + current_device = staticmethod(torch.xpu.current_device) + set_device = staticmethod(torch.xpu.set_device) + device_count = staticmethod(torch.xpu.device_count) # type: ignore[has-type] + stream = staticmethod(torch.xpu.stream) # type: ignore[assignment] + current_stream = staticmethod(torch.xpu.current_stream) + set_stream = staticmethod(torch.xpu.set_stream) # type: ignore[assignment] + _set_stream_by_id = staticmethod(torch.xpu._set_stream_by_id) # type: ignore[assignment] + synchronize = staticmethod(torch.xpu.synchronize) + get_device_properties = staticmethod(torch.xpu.get_device_properties) # type: ignore[assignment] + get_raw_stream = staticmethod(get_xpu_stream) # type: ignore[assignment, arg-type] + exchange_device = staticmethod(torch.xpu._exchange_device) # type: ignore[arg-type, has-type] + maybe_exchange_device = staticmethod(torch.xpu._maybe_exchange_device) # type: ignore[arg-type, has-type] + memory_allocated = staticmethod(torch.xpu.memory_allocated) + + # Can be mock patched by @patch decorator. + @staticmethod + def is_available() -> bool: + return torch.xpu.is_available() + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> Any: + cc = torch.xpu.get_device_capability(device) + return cc + + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return torch.xpu.is_bf16_supported() + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + return True + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + import triton.backends + + from torch._dynamo.exc import TritonUnavailableError + + if "intel" not in triton.backends.backends: + raise TritonUnavailableError("triton not built with the 'intel' backend") + + +@dataclass +class CpuDeviceProperties: + multi_processor_count: int + + +class CpuInterface(DeviceInterface): + # pyrefly: ignore [bad-override] + class Event(torch.Event): + def __init__(self, enable_timing: bool = True) -> None: + self.time = 0.0 + + def elapsed_time(self, other: Any) -> float: + return (other.time - self.time) * 1000 + + def record(self, stream: Any = None) -> None: + self.time = time.perf_counter() + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def get_device_properties( + device: torch.types.Device = None, + ) -> CpuDeviceProperties: + import multiprocessing + + cpu_count = multiprocessing.cpu_count() + return CpuDeviceProperties(cpu_count) + + @staticmethod + def is_available() -> bool: + return True + + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return True + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> str: + return "" + + @staticmethod + def get_raw_stream(device_idx: Any) -> int: + return 0 + + @staticmethod + def current_device() -> int: + return 0 + + @staticmethod + def synchronize(device: torch.types.Device = None) -> None: + pass + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + return True + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + import triton.backends + + from torch._dynamo.exc import TritonUnavailableError + + if "cpu" not in triton.backends.backends: + raise TritonUnavailableError("triton not built with the 'cpu' backend") + + +class MpsInterface(DeviceInterface): + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return True + + @classmethod + def is_dtype_supported( + cls, dtype: torch.dtype, including_emulation: bool = False + ) -> bool: + if dtype in [torch.float64, torch.complex128]: + return False + return True + + @staticmethod + def is_available() -> bool: + return torch.backends.mps.is_available() + + @staticmethod + def current_device() -> int: + return 0 + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> str: + return "" + + @staticmethod + def synchronize(device: torch.types.Device = None) -> None: + torch.mps.synchronize() + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + return namedtuple("MPSProperties", ["multi_processor_count"])( + torch.backends.mps.get_core_count() # type: ignore[arg-type] + ) + + @staticmethod + def current_device() -> int: + return 0 + + +class TpuInterface(DeviceInterface): + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return True + + @classmethod + def is_dtype_supported( + cls, dtype: torch.dtype, including_emulation: bool = False + ) -> bool: + return dtype not in ( + torch.float64, + torch.complex32, + torch.complex64, + torch.complex128, + torch.half, + ) + + @staticmethod + def is_available() -> bool: + return has_torch_tpu() + + @staticmethod + def current_device() -> int: + return 0 + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> str: + return "" + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + return namedtuple("TPUProperties", ["multi_processor_count"])( + 1 # type: ignore[arg-type] + ) + + @staticmethod + def current_device() -> int: + return 0 + + +device_interfaces: dict[str, type[DeviceInterface]] = {} +_device_initialized = False + + +def register_interface_for_device( + device: str | torch.device, device_interface: type[DeviceInterface] +) -> None: + if isinstance(device, torch.device): + device = device.type + device_interfaces[device] = device_interface + + +def get_interface_for_device(device: str | torch.device) -> type[DeviceInterface]: + if isinstance(device, torch.device): + device = device.type + if not _device_initialized: + init_device_reg() + if device in device_interfaces: + return device_interfaces[device] + raise NotImplementedError(f"No interface for device {device}") + + +def get_registered_device_interfaces() -> Iterable[tuple[str, type[DeviceInterface]]]: + if not _device_initialized: + init_device_reg() + return device_interfaces.items() + + +def init_device_reg() -> None: + global _device_initialized + register_interface_for_device("cuda", CudaInterface) + for i in range(torch.cuda.device_count()): + register_interface_for_device(f"cuda:{i}", CudaInterface) + + register_interface_for_device("xpu", XpuInterface) + for i in range(torch.xpu.device_count()): + register_interface_for_device(f"xpu:{i}", XpuInterface) + + register_interface_for_device("mtia", MtiaInterface) + for i in range(torch.mtia.device_count()): + register_interface_for_device(f"mtia:{i}", MtiaInterface) + + register_interface_for_device("cpu", CpuInterface) + register_interface_for_device("mps", MpsInterface) + register_interface_for_device("tpu", TpuInterface) + + _device_initialized = True diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/distributed.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..54450f5d98a16b2a33c66d1ee69482f35dcdbd33 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/distributed.py @@ -0,0 +1,58 @@ +""" +Manages process groups for distributed compilation in TorchDynamo. + +This module handles the initialization and management of process groups used for +distributed compilation. Key features: + +- Lazy initialization of compilation process groups +- Only creates groups when distributed mode is enabled and available +- Integrates with compiler_collectives configuration setting +- Provides a single global process group for compilation coordination + +The process group is created only when needed and if the distributed environment +is properly initialized, making it safe to import and use this module even in +non-distributed scenarios. +""" + +import torch.distributed as dist + +from . import config + + +_COMPILE_PG: dist.ProcessGroup | None = None +_GUARD_PG: dist.ProcessGroup | None = None + + +def get_compile_pg() -> dist.ProcessGroup | None: + if ( + config.enable_compiler_collectives + and dist.is_available() + and dist.is_initialized() + ): + global _COMPILE_PG + if _COMPILE_PG is None: + # , timeout=datetime.timedelta(seconds=2) + compile_pg = dist.distributed_c10d._new_group_with_tag( + pg_tag="pt2_compile_pg" + ) + if compile_pg == dist.GroupMember.NON_GROUP_MEMBER: + raise AssertionError("Compiler process group must include all ranks") + _COMPILE_PG = compile_pg + return _COMPILE_PG + + return None + + +# NB: Unlike get_compile_pg, this is only called when guard collectives were +# explicitly requested +def get_guard_pg() -> dist.ProcessGroup | None: + if dist.is_available() and dist.is_initialized(): + global _GUARD_PG + if _GUARD_PG is None: + guard_pg = dist.distributed_c10d._new_group_with_tag(pg_tag="pt2_guard_pg") + if guard_pg == dist.GroupMember.NON_GROUP_MEMBER: + raise AssertionError("Guard process group must include all ranks") + _GUARD_PG = guard_pg + return _GUARD_PG + + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/dynamo_profiler.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/dynamo_profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..7c645b7f17071a56373b33a62d683286efaa96a5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/dynamo_profiler.py @@ -0,0 +1,426 @@ +""" +Dynamo Profiler - tracks where Dynamo spends time during compilation. + +This module provides profiling functionality for Dynamo tracing, showing per-function +cumtime (inclusive) and tottime (exclusive) in a cProfile-compatible format. +The output can be visualized with tools like snakeviz. + +Usage: + # Enable via config (prints pstats output): + torch._dynamo.config.dynamo_profiler = True + + # Or save to file for snakeviz: + torch._dynamo.config.dynamo_profiler = "/tmp/dynamo.prof" + # Then: snakeviz /tmp/dynamo.prof +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, TYPE_CHECKING + + +if TYPE_CHECKING: + import pstats + + +@dataclass +class FunctionTraceTiming: + """ + Timing data for a single inlined function trace. + + Follows cProfile conventions: + - cumtime: total time in function including all subcalls (inclusive) + - tottime: time in function excluding subcalls (exclusive) + - caller info: who called this function (for building call graph) + """ + + # Function identification + func_name: str + filename: str + firstlineno: int + # Timing data (in nanoseconds) - cProfile-style + cumtime_ns: int # Inclusive time (includes subcalls) + tottime_ns: int # Exclusive time (excludes subcalls) + # Code stats (for comparing tracing overhead vs function complexity) + bytecode_count: int + # Nesting depth when this function was traced + inline_depth: int + # Caller information (for building call graph edges) + caller_func_name: str | None = None + caller_filename: str | None = None + caller_firstlineno: int | None = None + # Whether this is a primitive (non-recursive) call + # A call is primitive if the function doesn't appear anywhere in the call stack + is_primitive_call: bool = True + # Full call stack at the time of this call (for proper snakeviz drill-down) + # Each entry is (func_name, filename, firstlineno) + call_stack: tuple[tuple[str, str, int], ...] = () + + # Backwards compatibility alias + @property + def trace_time_ns(self) -> int: + return self.cumtime_ns + + @property + def trace_time_ms(self) -> float: + return self.cumtime_ns / 1e6 + + @property + def cumtime_ms(self) -> float: + return self.cumtime_ns / 1e6 + + @property + def tottime_ms(self) -> float: + return self.tottime_ns / 1e6 + + @property + def caller_key(self) -> tuple[str, int, str] | None: + """Return caller as a pstats-compatible key tuple.""" + if self.caller_func_name is not None: + return ( + self.caller_filename or "", + self.caller_firstlineno or 0, + self.caller_func_name, + ) + return None + + @property + def func_key(self) -> tuple[str, int, str]: + """Return this function as a pstats-compatible key tuple.""" + return (self.filename, self.firstlineno, self.func_name) + + def __repr__(self) -> str: + return ( + f"FunctionTraceTiming({self.func_name} at {self.filename}:{self.firstlineno}, " + f"cumtime={self.cumtime_ms:.2f}ms, tottime={self.tottime_ms:.2f}ms, " + f"bytecode={self.bytecode_count}, depth={self.inline_depth})" + ) + + +@dataclass +class ProfilerStackEntry: + """Stack entry for tracking function timing in the Dynamo profiler.""" + + func_name: str + filename: str + firstlineno: int + start_time_ns: int + child_time_ns: int # Accumulated time spent in traced children + is_primitive_call: bool = True # Whether this is a non-recursive call + + +class DynamoProfilerState: + """State for Dynamo profiler tracking function trace timings.""" + + def __init__(self) -> None: + self.timings: list[FunctionTraceTiming] = [] + self.stack: list[ProfilerStackEntry] = [] + + def record_timing(self, timing: FunctionTraceTiming) -> None: + """Record timing data for a traced function.""" + self.timings.append(timing) + + def get_timings(self) -> list[FunctionTraceTiming]: + """Get all recorded timings.""" + return self.timings + + def push( + self, func_name: str, filename: str, firstlineno: int, start_time_ns: int + ) -> None: + """Push a new entry onto the timing stack.""" + # Check if this function already exists in the stack (indirect recursion) + is_primitive = not any( + entry.func_name == func_name + and entry.filename == filename + and entry.firstlineno == firstlineno + for entry in self.stack + ) + self.stack.append( + ProfilerStackEntry( + func_name=func_name, + filename=filename, + firstlineno=firstlineno, + start_time_ns=start_time_ns, + child_time_ns=0, + is_primitive_call=is_primitive, + ) + ) + + def pop(self) -> ProfilerStackEntry | None: + """Pop the top entry from the timing stack.""" + if self.stack: + return self.stack.pop() + return None + + def add_child_time(self, child_cumtime_ns: int) -> None: + """Add the child's cumulative time to the parent's child_time accumulator.""" + if self.stack: + self.stack[-1].child_time_ns += child_cumtime_ns + + def get_current_caller(self) -> tuple[str, str, int] | None: + """Get the current caller (top of stack) as (func_name, filename, firstlineno).""" + if self.stack: + entry = self.stack[-1] + return (entry.func_name, entry.filename, entry.firstlineno) + return None + + def get_call_stack(self) -> tuple[tuple[str, str, int], ...]: + """Get the full current call stack as tuple of (func_name, filename, firstlineno).""" + return tuple( + (entry.func_name, entry.filename, entry.firstlineno) for entry in self.stack + ) + + def generate_pstats( + self, output_file: str | None = None, print_raw: bool = False + ) -> pstats.Stats: + """Generate pstats.Stats object from recorded timings. + + Args: + output_file: Optional file path to save the stats. + print_raw: If True, print raw aggregate timings before returning. + """ + import cProfile + import io + import logging + import pstats + + log = logging.getLogger(__name__) + + # Aggregate by (filename, lineno, func_name) + aggregated: dict[tuple[str, int, str], dict[str, Any]] = {} + # caller_edges[callee_key][caller_key] -> edge stats + caller_edges: dict[ + tuple[str, int, str], dict[tuple[str, int, str], dict[str, Any]] + ] = {} + + for t in self.timings: + key = (t.filename, t.firstlineno, t.func_name) + + if key not in aggregated: + aggregated[key] = { + "ncalls": 0, + "pcalls": 0, + "tottime": 0.0, + "cumtime": 0.0, + } + caller_edges[key] = {} + + agg = aggregated[key] + agg["ncalls"] += 1 + agg["tottime"] += t.tottime_ns / 1e9 + + if t.is_primitive_call: + agg["pcalls"] += 1 + agg["cumtime"] += t.cumtime_ns / 1e9 + + # Build caller edge + if t.caller_filename is not None: + caller_key = ( + t.caller_filename, + t.caller_firstlineno or 0, + t.caller_func_name or "", + ) + if caller_key not in caller_edges[key]: + caller_edges[key][caller_key] = { + "ncalls": 0, + "pcalls": 0, + "tottime": 0.0, + "cumtime": 0.0, + } + edge = caller_edges[key][caller_key] + edge["ncalls"] += 1 + edge["tottime"] += t.tottime_ns / 1e9 + # Always add cumtime to edges for visualization (gprof2dot) + # Function-level cumtime is already correct (only primitive calls) + edge["cumtime"] += t.cumtime_ns / 1e9 + if t.is_primitive_call: + edge["pcalls"] += 1 + + if print_raw: + sorted_items = sorted( + aggregated.items(), key=lambda x: x[1]["cumtime"], reverse=True + ) + print("\n=== Aggregate Timings (raw) ===") + print( + f"{'ncalls':>8} {'pcalls':>8} {'tottime':>12} {'cumtime':>12} function" + ) + print("-" * 80) + total_cumtime = 0.0 + total_tottime = 0.0 + for (filename, lineno, func_name), agg in sorted_items: + ncalls = agg["ncalls"] + pcalls = agg["pcalls"] + tottime = agg["tottime"] * 1000 # convert to ms + cumtime = agg["cumtime"] * 1000 + total_cumtime += cumtime + total_tottime += tottime + short_file = filename.split("/")[-1] if "/" in filename else filename + print( + f"{ncalls:>8} {pcalls:>8} {tottime:>10.2f}ms {cumtime:>10.2f}ms " + f"{func_name} ({short_file}:{lineno})" + ) + print("-" * 80) + print( + f"Total timings: {len(self.timings)}, unique functions: {len(aggregated)}" + ) + print( + f"Sum tottime: {total_tottime:.2f}ms, Sum cumtime: {total_cumtime:.2f}ms" + ) + + # Ensure caller-only functions have a top-level entry. + # gprof2dot expects every function referenced as a caller to also + # exist as a top-level entry in the stats dict with timing data. + for key in list(caller_edges.keys()): + for caller_key in caller_edges[key]: + if caller_key not in aggregated: + aggregated[caller_key] = { + "ncalls": 0, + "pcalls": 0, + "tottime": 0.0, + "cumtime": 0.0, + } + caller_edges[caller_key] = {} + + # Build the stats dict in pstats format + stats_dict: dict[ + tuple[str, int, str], tuple[int, int, float, float, dict[Any, Any]] + ] = {} + + for key, agg in aggregated.items(): + callers: dict[tuple[str, int, str], tuple[int, int, float, float]] = {} + for caller_key, edge in caller_edges[key].items(): + callers[caller_key] = ( + edge["ncalls"], + edge["pcalls"], + edge["tottime"], + edge["cumtime"], + ) + + stats_dict[key] = ( + agg["pcalls"], + agg["ncalls"], + agg["tottime"], + agg["cumtime"], + callers, + ) + + # Create a pstats.Stats object + dummy_profile = cProfile.Profile() + dummy_profile.enable() + dummy_profile.disable() + stats = pstats.Stats(dummy_profile, stream=io.StringIO()) + + stats.stats = stats_dict # type: ignore[attr-defined] + stats.total_calls = sum(s[1] for s in stats_dict.values()) # type: ignore[attr-defined] + stats.prim_calls = sum(s[0] for s in stats_dict.values()) # type: ignore[attr-defined] + stats.total_tt = sum(s[2] for s in stats_dict.values()) # type: ignore[attr-defined] + + if output_file: + stats.dump_stats(output_file) + log.info( + "Saved pstats to %s. Visualize with: snakeviz %s", + output_file, + output_file, + ) + + return stats + + def generate_svg( + self, profile_file: str, svg_file: str | None = None + ) -> str | None: + """Generate an SVG call graph from a profile file using gprof2dot and graphviz. + + Args: + profile_file: Path to the pstats profile file. + svg_file: Optional path for the output SVG. If not provided, uses + profile_file with .svg extension. + + Returns: + Path to the generated SVG file, or None if generation failed. + """ + import os + import shutil + import subprocess + + if not shutil.which("gprof2dot"): + print("gprof2dot not found. Install with: pip install gprof2dot") + return None + + if not shutil.which("dot"): + print("graphviz 'dot' not found. Install graphviz package.") + return None + + if svg_file is None: + svg_file = profile_file.rsplit(".", 1)[0] + ".svg" + + try: + # gprof2dot -f pstats profile.prof | dot -Tsvg -o profile.svg + gprof2dot = subprocess.Popen( + [ + "gprof2dot", + "-f", + "pstats", + "--node-label=total-time-percentage", + "--node-label=self-time-percentage", + "--node-label=total-time", + profile_file, + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + dot = subprocess.Popen( + ["dot", "-Tsvg", "-o", svg_file], + stdin=gprof2dot.stdout, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + gprof2dot.stdout.close() # type: ignore[union-attr] + _, dot_err = dot.communicate() + _, gprof2dot_err = gprof2dot.communicate() + + if gprof2dot.returncode != 0: + print(f"gprof2dot failed: {gprof2dot_err.decode()}") + return None + + if dot.returncode != 0: + print(f"graphviz dot failed: {dot_err.decode()}") + return None + + if not os.path.isfile(svg_file): + print(f"SVG file was not created: {svg_file}") + return None + + print(f"SVG call graph saved to: {svg_file}") + return svg_file + + except Exception as e: + print(f"Failed to generate SVG: {e}") + return None + + def dump_stats( + self, output_file: str | None = None, generate_svg: bool = True + ) -> None: + """Print profiler stats to stdout and optionally save to file. + + Args: + output_file: Optional path to save the pstats profile. + generate_svg: If True and output_file is provided, also generate an SVG + call graph using gprof2dot and graphviz. + """ + import sys + + if not self.timings: + return + + stats = self.generate_pstats(output_file, print_raw=True) + print("\n=== Dynamo Profiler (pstats) ===") + stats.stream = sys.stdout # type: ignore[attr-defined] + stats.sort_stats("cumulative").print_stats() + + if output_file: + print(f"\nProfile saved to: {output_file}") + print(f"Visualize with: snakeviz {output_file}") + + if generate_svg: + self.generate_svg(output_file) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..7ac5841ae06971160885f851e215bdedd223501e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py @@ -0,0 +1,2965 @@ +# mypy: disable-error-code="method-assign" + +""" +This module implements the core frame evaluation handler for TorchDynamo's compilation system. +The eval frame handler intercepts Python bytecode execution at runtime to enable dynamic +compilation and optimization of PyTorch code. + +Key components defined here: +- Frame evaluation handlers that intercept and analyze Python execution frames +- Guards management for tracking dependencies and invalidating compiled code +- Optimization contexts and decorators (optimize, run_once, disable, etc.) +- Export functionality for saving optimized graphs +- Backend compiler integrations and callback management + +Functions in this file are responsible for modifying the eval frame handler at RUNTIME. +Therefore, all functions in this file are hot and performance-critical. Functions that +only execute at compile time should be placed in torch._dynamo.convert_frame. + +The eval frame handler is the core mechanism that enables TorchDynamo to dynamically +intercept, analyze and optimize PyTorch code during execution. It works by registering +a custom frame evaluation function that gets called for every Python frame, allowing +us to detect PyTorch operations and trigger compilation as needed. +""" + +from __future__ import annotations + +import atexit +import contextlib +import functools +import inspect +import itertools +import logging +import os +import sys +import sysconfig +import textwrap +import threading +import traceback +import types +import unittest +import warnings +import weakref +from collections.abc import Generator, Sized +from dataclasses import dataclass +from enum import Enum +from os.path import dirname, join +from typing import Any, cast, Literal, NamedTuple, TYPE_CHECKING +from unittest.mock import patch + +import sympy + +import torch +import torch.fx +import torch.utils._pytree as pytree +import torch.utils.checkpoint +from torch import _guards + +# see discussion at https://github.com/pytorch/pytorch/issues/120699 +from torch._C._dynamo.eval_frame import ( # noqa: F401 + get_eval_frame_isolate_recompiles_id, + reset_code, + set_code_exec_strategy, + set_eval_frame, + set_eval_frame_isolate_recompiles_id, + set_fullgraph_compiled_frame_count, + set_fullgraph_error_on_nested_compile, + set_guard_complete_hook, + set_guard_error_hook, + set_skip_guard_eval_unsafe, + unsupported, +) +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.types import ( + CompilerConfig, + CompilerConfigProvider, + ConvertFrameReturn, + FrameAction, + FrameExecStrategy, +) +from torch._export.utils import _compiling_state_context +from torch._library.opaque_object import is_custom_class +from torch._subclasses.fake_tensor import unset_fake_temporarily +from torch._utils_internal import DISABLE_JUSTKNOBS, justknobs_check, log_export_usage +from torch.export.dynamic_shapes import ( + _combine_args, + _DimHint, + _DimHintType, + _IntWrapper, + _process_dynamic_shapes, + _RelaxedConstraint, + Constraint, +) +from torch.fx import GraphModule, traceback as fx_traceback +from torch.fx.experimental._dynamism import ( + clone_and_convert_to_meta, + track_dynamism_across_examples, +) +from torch.fx.experimental.dynamic_spec import ( + _coerce_to_shapes_spec, + ParamsSpec, + ShapesSpec, +) +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + DimDynamic, + ShapeEnv, + StatelessSymbolicContext, +) +from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo + +from . import config, convert_frame, distributed, external_utils, trace_rules, utils +from .backends.registry import CompilerFn, lookup_backend +from .code_context import code_context +from .exc import ( + CondOpArgsMismatchError, + ShortenTraceback, + UncapturedHigherOrderOpError, + Unsupported, + UserError, + UserErrorType, +) +from .hooks import Hooks +from .mutation_guard import install_generation_tagging_init +from .utils import ( + _get_error_on_graph_break, + _set_error_on_graph_break, + common_constant_types, + compile_times, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._dynamo.package import CompilePackage + from torch._dynamo.repro.after_dynamo import WrapBackendDebug + from torch._subclasses import fake_tensor + from torch.export._trace import _DynamicShapesInput + from torch.fx.node import Argument, Node, Target + + from .types import ( + CacheEntry, + DynamoCallback, + DynamoFrameType, + GuardFail, + GuardFilterEntry, + ) + + +log = logging.getLogger(__name__) + +_next_isolate_recompiles_id = itertools.count() + + +always_optimize_code_objects = utils.ExactWeakKeyDictionary() +null_context = contextlib.nullcontext + + +# See https://github.com/python/typing/pull/240 +class Unset(Enum): + token = 0 + + +cached_backends: dict[int, CompilerFn] = {} + +unset = Unset.token + +_in_optimized_module = False + + +if DISABLE_JUSTKNOBS: + _maybe_set_eval_frame = set_eval_frame +else: + + def _maybe_set_eval_frame(callback: DynamoCallback) -> DynamoCallback: + # A wrapper on set_eval_frame that is guarded by a Justknob. + # Users can disable torchDynamo by setting the JK to False. + if not justknobs_check("pytorch/compiler:enable_compiler_set_eval_frame"): + torch._dynamo.utils.warn_once( + "Dynamo disabled by Justknob: enable_compiler_set_eval_frame, skipping set_eval_frame" + ) + return callback + else: + return set_eval_frame(callback) + + +# The set of valid stance strings accepted by torch.compiler.set_stance. Kept as +# a shared alias so producers (set_stance) and the exhaustive consumer +# (_callback_from_stance) stay in sync at type-check time. +StanceStr = Literal[ + "default", + "eager_then_compile", + "aot_eager_then_compile", + "force_eager", + "eager_on_recompile", + "fail_on_recompile", +] + + +@dataclass +class DynamoStance: + stance: StanceStr = "default" + skip_guard_eval_unsafe: bool = False + backend: str | Callable[..., Any] | None = None + + +_stance = DynamoStance() +_force_eager_nested_compile = threading.local() + + +@contextlib.contextmanager +def _use_eager_on_nested_compile() -> Generator[None, None, None]: + """Run torch.compile wrappers eagerly inside compiler-internal tracing.""" + prior = getattr(_force_eager_nested_compile, "depth", 0) + _force_eager_nested_compile.depth = prior + 1 + try: + yield + finally: + _force_eager_nested_compile.depth = prior + + +def _is_eager_on_nested_compile() -> bool: + return getattr(_force_eager_nested_compile, "depth", 0) > 0 + + +def _set_stance(stance: DynamoStance) -> DynamoStance: + global _stance + + from torch._C._dynamo.eval_frame import get_eval_frame_callback + + callback = get_eval_frame_callback() + + if callback is not False and callback is not None: + raise RuntimeError("attempted to set_stance in a torch.compile region") + + prior = _stance + _stance = stance + return prior + + +_set_stance._dynamo_forbidden = True # type: ignore[attr-defined] + +_EXAMPLE_INPUTS: dict[str, list[Any]] | None = None + + +def get_example_inputs(key: str) -> list[Any]: + global _EXAMPLE_INPUTS + if _EXAMPLE_INPUTS is None: + _EXAMPLE_INPUTS = {} + + if key not in _EXAMPLE_INPUTS: + _EXAMPLE_INPUTS[key] = [] + + return _EXAMPLE_INPUTS[key] + + +@contextlib.contextmanager +def _set_in_optimized_module() -> Generator[None, None, None]: + # Set in dynamo's OptimizedModule forward, to have better coverage than is_compiling(). + # Prevents graph-breaking forward hooks from being registered & traced. + # TODO(pianpwk): subsume this flag with better is_compiling() coverage + global _in_optimized_module + _old_in_optimized_module = ( + _in_optimized_module # do we need this? can we just set it to False after + ) + _in_optimized_module = True + try: + yield + finally: + _in_optimized_module = _old_in_optimized_module + + +def _is_in_optimized_module() -> bool: + global _in_optimized_module + return _in_optimized_module + + +def _callback_from_stance(callback: DynamoCallback) -> DynamoCallback: + if _stance.stance == "default": + # force_backend + if _stance.backend is not None and callback not in (False, None): + callback = _create_wrapped_callback(get_compiler_fn(_stance.backend)) + + return callback + elif _stance.stance == "eager_then_compile": + if callback not in (False, None): + return _create_delayed_compile_callback(callback, _stance.stance) + return callback + elif _stance.stance == "aot_eager_then_compile": + if callback not in (False, None): + return _create_delayed_compile_callback(callback, _stance.stance) + return callback + elif _stance.stance == "force_eager": + # disable + return None + elif _stance.stance == "eager_on_recompile": + # run mode + return False + elif _stance.stance == "fail_on_recompile": + if callback in (False, None): + return callback + + def fail_callback( + frame: DynamoFrameType, *args: Any, **kwargs: Any + ) -> ConvertFrameReturn: + if trace_rules.check(frame.f_code): + return ConvertFrameReturn() + if not convert_frame.has_tensor_in_frame(frame): + return ConvertFrameReturn() + + from torch._C._dynamo.eval_frame import ( + _debug_get_cache_entry_list, + _debug_get_precompile_entries, + ) + from torch._dynamo.guards import get_and_maybe_log_recompilation_reasons + + message = ( + "Detected recompile when torch.compile stance is 'fail_on_recompile'. " + + f"filename: '{frame.f_code.co_filename}', " + + f"function name: '{frame.f_code.co_name}', " + + f"line number: {frame.f_lineno}" + ) + cache_entries = _debug_get_cache_entry_list(frame.f_code) + if cache_entries: + reasons = get_and_maybe_log_recompilation_reasons( + cache_entries, + frame, + innermost_backend(callback), # pyrefly: ignore [bad-argument-type] + skip_logging=True, + ) + if reasons: + failures = textwrap.indent("\n".join(reasons), "- ") + guard_failure_details = ( + f"triggered by the following guard failure(s):\n{failures}" + ) + message += f"\n{textwrap.indent(guard_failure_details, ' ')}" + precompile_entries = _debug_get_precompile_entries(frame.f_code) + if len(precompile_entries) > 0: + message += "\nFailed on the following precompiled guards: " + for entry in precompile_entries: + message += f"\n{entry.guard_manager}{entry.guard_manager.check_verbose(frame.f_locals)}" # type: ignore[attr-defined] + raise RuntimeError(message) + + # to prevent cache miss due to different backend + fail_callback._torchdynamo_orig_backend = callback # type: ignore[attr-defined] + + return fail_callback + else: + raise RuntimeError(f"invalid torch.compile stance '{_stance}'") + + +def _create_wrapped_callback( + compiler_fn: CompilerFn, +) -> convert_frame.CatchErrorsWrapper: + hooks = Hooks() + return convert_frame.catch_errors_wrapper( + convert_frame.convert_frame( # type: ignore[arg-type] + compiler_fn, + hooks, + ), + hooks, + ) + + +def _get_or_add_example_inputs(frame: DynamoFrameType) -> list[Any]: + key = frame.f_code.co_filename + str(frame.f_code.co_firstlineno) + example_inputs = get_example_inputs(key) + + if len(example_inputs) < 2: + example_inputs.append(clone_and_convert_to_meta(frame.f_locals)) + + return example_inputs + + +def _create_delayed_compile_callback( + callback: DynamoCallback, stance: StanceStr +) -> Callable[..., Any]: + def callback_fn(*args: Any, **kwargs: Any) -> convert_frame.ConvertFrameReturn: + frame = args[0] + example_inputs = _get_or_add_example_inputs(frame) + + if len(example_inputs) == 1: + if stance == "eager_then_compile": + return ConvertFrameReturn( + frame_exec_strategy=FrameExecStrategy( + FrameAction.DEFAULT, FrameAction.DEFAULT + ) + ) + elif stance == "aot_eager_then_compile": + aot_eager_fn = get_compiler_fn("aot_eager") + return _create_wrapped_callback(aot_eager_fn)(*args, **kwargs) + + dynamism = track_dynamism_across_examples(example_inputs) + code_context.get_context(frame.f_code)["dynamism"] = dynamism + compiler_fn = callback._torchdynamo_orig_backend._torchdynamo_orig_backend # type: ignore[union-attr] + return _create_wrapped_callback(compiler_fn)(*args, **kwargs) + + # to prevent cache miss due to different backend + callback_fn._torchdynamo_orig_backend = callback # type: ignore[attr-defined] + + return callback_fn + + +def _is_skip_guard_eval_unsafe_stance() -> bool: + return _stance.skip_guard_eval_unsafe + + +def _reset_guarded_backend_cache() -> None: + global cached_backends + for backend in cached_backends.values(): + if hasattr(backend, "reset"): + backend.reset() + cached_backends.clear() + + +DONT_WRAP_FILES = { + # For tracing into fx modules + inspect.getsourcefile(GraphModule), + join(dirname(dirname(__file__)), "onnx/_internal/fx/dynamo_graph_extractor.py"), +} + + +def _debug_get_cache_entry_list( + code: types.CodeType | Callable[..., Any], +) -> list[CacheEntry]: + """ + Given a code object or a callable object, retrieve the cache entries + stored in this code. + """ + if callable(code): + code = code.__code__ + return torch._C._dynamo.eval_frame._debug_get_cache_entry_list(code) + + +def _get_cache_entries_for_region( + code: types.CodeType | Callable[..., Any], + isolate_recompiles_id: int, +) -> list[CacheEntry]: + """ + Return the cache entries for a specific isolate_recompiles region on + ``code``, in LRU order (most-recently-used first). + + Pass ``isolate_recompiles_id=-1`` to get the default (non-isolated) + bucket; pass a region's id (as exposed via + ``opt._isolate_recompiles_id``) to get that region's bucket. + + Returns only entries owned by the requested bucket. During an actual + lookup, isolated regions also fall back read-only to the default + bucket for BC-friendly reuse — this helper does not include those + fallback entries. + """ + if callable(code): + code = code.__code__ + return torch._C._dynamo.eval_frame._get_cache_entries_for_region( + code, isolate_recompiles_id + ) + + +def _get_total_cache_entry_count( + code: types.CodeType | Callable[..., Any], +) -> int: + """Total cache entries across all isolate_recompiles regions for a code object.""" + if callable(code): + code = code.__code__ + return torch._C._dynamo.eval_frame._get_total_cache_entry_count(code) + + +class OptimizedModule(torch.nn.Module): + """ + Wraps the original nn.Module object and later patches its + forward method to optimized self.forward method. + """ + + _torchdynamo_orig_callable: Callable[..., Any] + get_compiler_config: Callable[[], CompilerConfig | None] + + _opt_mod_attributes = { + "_orig_mod", + "dynamo_ctx", + "_torchdynamo_orig_callable", + "_torchdynamo_wrapper_id", + "get_compiler_config", + "forward", + "_forward", + "__dict__", + "named_children_walk", + "_super_module_initialized", + } + + @staticmethod + def _forward_has_skip_rule(mod: torch.nn.Module) -> bool: + return isinstance(mod.forward, types.MethodType) and trace_rules.check( + mod.forward + ) + + @staticmethod + def _should_wrap_module_call_impl(fn: Any) -> bool: + if getattr(fn, "__name__", "") != "_call_impl": + return False + + mod = getattr(fn, "__self__", None) + if not isinstance(mod, torch.nn.Module): + return False + return OptimizedModule._forward_has_skip_rule(mod) + + def __init__(self, mod: torch.nn.Module, dynamo_ctx: _TorchDynamoContext) -> None: + # NOTE: this must go first, because attribute reads/writes of `self` + # uses `_orig_mod`, and sometimes users override `Module.__init__` to + # do attribute reads/writes on `self`. + # + # We also can't use regular setattr because `super().__setattr__` will + # complain for module value before `super().__init__()` + object.__setattr__(self, "_orig_mod", mod) + self._super_module_initialized = False + super().__init__() + self._super_module_initialized = True + + # Installs the params/buffer + self._orig_mod = mod # `super().__setattr__` will register this module + self.dynamo_ctx = dynamo_ctx + self._initialize() + self.training = self._orig_mod.training + + def __len__(self) -> int: + # Proxy the len call to the original module + # pyrefly: ignore [unsafe-overlap] + if isinstance(self._orig_mod, Sized): + return len(self._orig_mod) + # Mimic python's default behavior for objects without a length + raise TypeError(f"{type(self._orig_mod).__name__} does not support len()") + + def _initialize(self) -> None: + # Do this stuff in constructor to lower overhead slightly + if isinstance(self.dynamo_ctx, DisableContext): + # No need to check trace rules + self.forward = self.dynamo_ctx(self._orig_mod.__call__) + elif config.wrap_top_frame or self._forward_has_skip_rule(self._orig_mod): + # This may be a torch.nn.* instance in trace_rules.py which + # won't trigger a frame evaluation workaround to add an extra + # frame we can capture + self.forward = self.dynamo_ctx(external_utils.wrap_inline(self._orig_mod)) + else: + # Invoke hooks outside of dynamo then pickup the inner frame + self.forward = self.dynamo_ctx(self._orig_mod.__call__) + + if inspect.getattr_static(self._orig_mod, "_initialize_hook", None) is not None: + self._forward = self.forward + self.forward = self._call_lazy_check + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + if torch.nn.modules.module._has_any_global_hook(): + warnings.warn( + "Using `torch.compile(module)` when there are global hooks on " + "modules (e.g., from `register_module_forward_hook`); this will" + " cause the hooks to fire an extra time for the " + "`OptimizedModule` created by `torch.compile(module)`. If this " + "causes undesired behavior, please try using `module.compile()`" + ", or use the per-module hooks instead", + stacklevel=2, + ) + with _set_in_optimized_module(): + return super().__call__(*args, **kwargs) + + def _aot_compile(self, inputs: list[torch._dynamo.aot_compile.ModelInput]) -> None: + """ + Experimental: AOT Compile a set of inputs and use that as the forward function + """ + model = self._orig_mod + hooks = self.dynamo_ctx._hooks + if hooks is None: + raise AssertionError("hooks must not be None for AOT compilation") + if not config.enable_aot_compile: + raise RuntimeError( + "AOT Compile is not enabled, please set torch._dynamo.config.enable_aot_compile=True" + ) + if not self.dynamo_ctx.fullgraph: + raise RuntimeError( + "Graph breaks are not supported with aot compile. Please use torch.compile(fullgraph=True)." + ) + + if not callable(self.dynamo_ctx.callback): + raise RuntimeError("aot compile requires a callable dynamo callback.") + + backend = innermost_backend(self.dynamo_ctx.callback) + from torch._dynamo.aot_compile import aot_compile_module + + self.forward = aot_compile_module(model, inputs, hooks, backend) + + def _save_aot_compiled_module(self, path: str | None = None) -> bytes: + if not config.enable_aot_compile: + raise RuntimeError( + "AOT Compile is not enabled, please set torch._dynamo.config.enable_aot_compile=True" + ) + from torch._dynamo.aot_compile import AOTCompiledModel + + if not isinstance(self.forward, AOTCompiledModel): + raise AssertionError( + f"Expected self.forward to be AOTCompiledModel, got {type(self.forward)}" + ) + result: bytes = self.forward.serialize() + if path is not None: + with open(path, "wb") as f: + f.write(result) + return result + + def _load_aot_compiled_module(self, data: bytes) -> None: + if not config.enable_aot_compile: + raise RuntimeError( + "AOT Compile is not enabled, please set torch._dynamo.config.enable_aot_compile=True" + ) + from torch._dynamo.aot_compile import AOTCompiledModel + + compiled_forward = AOTCompiledModel.deserialize(self._orig_mod, data) + if not isinstance(compiled_forward, AOTCompiledModel): + raise AssertionError( + f"Expected compiled_forward to be AOTCompiledModel, got {type(compiled_forward)}" + ) + self.forward = compiled_forward + + def __reduce__( + self, + ) -> tuple[type[OptimizedModule], tuple[torch.nn.Module, _TorchDynamoContext]]: + return (self.__class__, (self._orig_mod, self.dynamo_ctx)) + + def __getstate__(self) -> dict[str, Any]: + state = dict(self.__dict__) + state.pop("forward", None) + state.pop("__call__", None) + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__ = state + self._initialize() + + @property + # pyrefly: ignore [bad-override] + def training(self) -> bool: + return self._orig_mod.training + + @training.setter + def training(self, value: bool) -> None: + # Ignore the `training` mutation in `super().__init__()`, since that's + # setting the default on `nn.Module`, but we are mirroring the + # `training` attr in `self._orig_mod`. + if self._super_module_initialized: + self._orig_mod.training = value + + def __getattr__(self, name: str) -> Any: + if name == "_orig_mod": + return self._modules["_orig_mod"] + return getattr(self._orig_mod, name) + + def __setattr__(self, name: str, value: Any) -> None: + # Allow patching over class attributes + if hasattr(type(self), name): + return super().__setattr__(name, value) + + if name in OptimizedModule._opt_mod_attributes: + return super().__setattr__(name, value) + return setattr(self._orig_mod, name, value) + + def __delattr__(self, name: str) -> None: + # This mirrors `__setattr__` + if hasattr(type(self), name): + return super().__delattr__(name) + + if name in OptimizedModule._opt_mod_attributes: + return super().__delattr__(name) + return delattr(self._orig_mod, name) + + def _call_lazy_check(self, *args: Any, **kwargs: Any) -> Any: + if ( + inspect.getattr_static(self._orig_mod, "_initialize_hook", None) is not None + and inspect.getattr_static(self._orig_mod, "_infer_parameters", None) + is not None + and callable(self._orig_mod._infer_parameters) + ): + # In the case of a lazy module, we want to run + # the pre-hooks which initialize it. + # Afterwards, lazy module deletes its pre-hooks + # to avoid treating it as lazy on subsequent recompile. + self._orig_mod._infer_parameters(self._orig_mod, args, kwargs) + return self._forward(*args, **kwargs) + + def __dir__(self) -> list[str]: + orig_mod_attrs = self._orig_mod.__dir__() + return orig_mod_attrs + [ + attr for attr in super().__dir__() if attr not in orig_mod_attrs + ] + + +def remove_from_cache(f: Any) -> None: + """ + Make sure f.__code__ is not cached to force a recompile + """ + if isinstance(f, types.CodeType): + reset_code(f) + elif hasattr(f, "__code__"): + reset_code(f.__code__) + elif hasattr(getattr(f, "forward", None), "__code__"): + reset_code(f.forward.__code__) + else: + from . import reset # type: ignore[attr-defined] + + reset() + log.warning("could not determine __code__ for %s", f) + + +def nothing() -> None: + pass + + +def always_false() -> bool: + return False + + +def _static_getattr(obj: Any, name: str, default: Any = None) -> Any: + # Not inspect.getattr_static: this runs while the eval frame callback is + # installed, so its Python frames land in Dynamo's frame counters. + try: + return object.__getattribute__(obj, name) + except AttributeError: + return default + + +def innermost_fn(fn: Callable[..., Any]) -> Callable[..., Any]: + """ + In case of nesting of _TorchDynamoContext calls, find the innermost + function. TorchDynamo caches on fn.__code__ object, so its necessary to find + the innermost function to pass on the optimize, run, disable etc. + """ + # Probe statically so these lookups never run a user-defined __getattr__, + # which may not tolerate unknown names. + unaltered_fn = fn + while ( + _static_getattr(unaltered_fn, "_torchdynamo_orig_callable") is not None + # Only follow the chain if _torchdynamo_wrapper_id matches id(fn). + # This prevents following chains in two cases: + # 1. Bound methods: id(bound_method) != id(wrapper_function), so we + # won't unwrap through __func__ and lose the self binding. + # 2. functools.wraps copies: When functools.wraps copies + # _torchdynamo_orig_callable from a wrapped function, the copied + # _torchdynamo_wrapper_id won't match the outer wrapper's id. + and _static_getattr(unaltered_fn, "_torchdynamo_wrapper_id") == id(unaltered_fn) + ): + # pyrefly: ignore [missing-attribute] + unaltered_fn = unaltered_fn._torchdynamo_orig_callable + if not callable(unaltered_fn): + raise AssertionError( + f"A callable function is expected, but {type(unaltered_fn)} is provided." + ) + return unaltered_fn + + +def innermost_backend(fn: Callable[..., Any]) -> Callable[..., Any]: + """ + Unwrap backend wrapper chain via _torchdynamo_orig_backend to find the + innermost backend function. + """ + while hasattr(fn, "_torchdynamo_orig_backend"): + fn = fn._torchdynamo_orig_backend + if not callable(fn): + raise AssertionError( + f"A callable function is expected, but {type(fn)} is provided." + ) + return fn + + +def make_set_enable_dynamic(enable: bool) -> Any: + if not isinstance(enable, bool): + raise AssertionError(f"Expected enable to be a bool, got {type(enable)}") + if enable: + # Assume everything is dynamic by default + return config._make_closure_patcher(assume_static_by_default=False) + else: + return config._make_closure_patcher( + automatic_dynamic_shapes=False, assume_static_by_default=True + ) + + +@contextlib.contextmanager +def set_enable_dynamic(enable: bool) -> Generator[None, None, None]: + cleanup = make_set_enable_dynamic(enable)() + try: + yield + finally: + cleanup() + + +# A thread local storage that serves to store information as Dynamo traces +# through a user provided function. +class DynamoTLS(threading.local): + # Each string is a summary of a frame Dynamo attempted to trace, stored in + # temporal order. + traced_frame_infos: list[str] = [] + + # Accumulated skip reasons during a fullgraph compile_wrapper call. + # Each entry is a formatted string like "fn (file.py:42): reason". + # None when not collecting (fullgraph not active). + skip_reasons: list[str] | None = None + + +dynamo_tls = DynamoTLS() + + +def reset_skip_reasons() -> None: + dynamo_tls.skip_reasons = [] + + +def add_skip_reason(reason: str, frame: DynamoFrameType) -> None: + if dynamo_tls.skip_reasons is not None: + code = frame.f_code + dynamo_tls.skip_reasons.append( + f"{code.co_name} ({code.co_filename}:{code.co_firstlineno}): {reason}" + ) + + +def get_skip_reasons() -> list[str]: + return dynamo_tls.skip_reasons or [] + + +def clear_dynamo_tls() -> None: + dynamo_tls.traced_frame_infos.clear() + dynamo_tls.skip_reasons = None + + +@atexit.register +def _log_traced_frames() -> None: + """ + At program exit, log all of the frames Dynamo has attempted to trace from, + excluding the continuation frames generated by Dynamo. + """ + msg = "\n".join(dynamo_tls.traced_frame_infos) + msg = textwrap.indent(msg, " * ") + msg = f"TorchDynamo attempted to trace the following frames: [\n{msg}\n]" + log.info(msg) + + +def guard_collectives_hook(guard_eval_result: bool) -> bool: + import torch.distributed as dist + from torch._dynamo.utils import dynamo_timed + + # guard_eval_result == True ==> cache hit + if pg := distributed.get_guard_pg(): + with dynamo_timed( + "guard_collective", log_pt2_compile_event=False, log_waitcounter=True + ): + log.debug("guard_collective %s", guard_eval_result) + # TODO: a bit awkward to time, this isn't inside of the dynamo compile region + all_results = [None] * pg.size() + dist.all_gather_object(all_results, guard_eval_result, group=pg) + # True = everyone hit, OK to run + # False = someone missed, force recompile everywhere + res = all(all_results) + log.debug("guard_collective %s -> %s", guard_eval_result, res) + return res + return guard_eval_result + + +_not_set = object() + + +class _TorchDynamoContext: + def __init__( + self, + callback: DynamoCallback, + on_enter: Callable[[], Any] = nothing, + backend_ctx_ctor: Callable[ + [], contextlib.AbstractContextManager[Any] + ] = null_context, + patch_fn: Callable[[], Any] = nothing, + first_ctx: bool = False, + *, + fullgraph: bool = False, + error_on_graph_break: bool | None = None, + export: bool = False, + dynamic: bool | None = None, + compiler_config: CompilerConfig | None = None, + package: CompilePackage | None = None, + hooks: Hooks | None = None, + isolate_recompiles: bool = False, + dynamic_shapes: ShapesSpec | ParamsSpec | dict[str, Any] | None = None, + ) -> None: + super().__init__() + if not (callable(callback) or callback is False or callback is None): + raise AssertionError( + f"callback must be callable, False, or None, got {type(callback)}" + ) + # Normalize the shorthand forms: dict / ParamsSpec / ShapesSpec all + # land here as a ShapesSpec (or None). + dynamic_shapes = _coerce_to_shapes_spec(dynamic_shapes) + self.callback: DynamoCallback = callback + self._backend_ctx_ctor = backend_ctx_ctor + self.prior: Unset | DynamoCallback = unset + self.first_ctx = first_ctx + self.fullgraph = fullgraph + self.error_on_graph_break = error_on_graph_break + self.export = export + self._dynamic = dynamic + self._dynamic_shapes = dynamic_shapes + self.compiler_config = compiler_config + self.cleanup_fns: list[Callable[[], Any]] = [] + self.enter_exit_hooks = [] + self._package = package + self._hooks = hooks + self._isolate_recompiles_id = ( + next(_next_isolate_recompiles_id) if isolate_recompiles else -1 + ) + patch_fn() + + # Save the backends so that we can reset them during torch._dynamo.reset + backend = innermost_backend(callback) # type: ignore[arg-type] + cached_backends.setdefault(id(backend), backend) # type: ignore[arg-type] + + if dynamic is not None and dynamic_shapes is not None: + raise ValueError( + "`dynamic` and `dynamic_shapes` cannot both be set. " + "`dynamic_shapes` controls dynamic behavior." + ) + + if dynamic is not None: + self.enter_exit_hooks.append(make_set_enable_dynamic(dynamic)) + + if dynamic_shapes is not None: + self.enter_exit_hooks.append( + config._make_closure_patcher(_dynamic_shapes_spec=dynamic_shapes) + ) + + if on_enter is not nothing: + # this case is not common + def call_on_enter() -> Callable[[], None]: + on_enter() + return nothing + + self.enter_exit_hooks.append(call_on_enter) + + if backend_ctx_ctor is not contextlib.nullcontext: + # this case is not common + def call_backend_ctx() -> functools.partial[bool | None]: + ctx = backend_ctx_ctor() + ctx.__enter__() + return functools.partial(ctx.__exit__, None, None, None) + + self.enter_exit_hooks.append(call_backend_ctx) + + def __enter__(self) -> None: + if config.raise_on_ctx_manager_usage: + raise RuntimeError( + "torch._dynamo.optimize(...) is used with a context manager. " + "Please refer to https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html " + "to use torch._dynamo.optimize(...) as an annotation/decorator. " + ) + self.prior = set_eval_frame(None) + self.cleanup_fns = [enter() for enter in self.enter_exit_hooks] + self.prior_skip_guard_eval_unsafe = set_skip_guard_eval_unsafe( + _is_skip_guard_eval_unsafe_stance() + ) + _maybe_set_eval_frame(_callback_from_stance(self.callback)) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> bool | None: + if self.prior is unset: + raise AssertionError("__exit__ called without matching __enter__") + set_eval_frame(None) + set_skip_guard_eval_unsafe(self.prior_skip_guard_eval_unsafe) + for cleanup in self.cleanup_fns: + cleanup() + self.cleanup_fns.clear() + _maybe_set_eval_frame(_callback_from_stance(self.prior)) + self.prior = unset + return None + + def __call__(self, fn: Any) -> Any: + if isinstance(fn, staticmethod): + return staticmethod(self(fn.__func__)) + + # public api for compiler config/options + def get_compiler_config() -> CompilerConfig | None: + return self.compiler_config + + from .package import DynamoCache + + # If self._package is lazily initialized, we should check the dynamo cache now + if config.caching_precompile: + if self._package is not None and not self._package.is_initialized(): + fn_key = fn.forward if isinstance(fn, torch.nn.Module) else fn + result = DynamoCache.load(fn_key) + if result is None: + # Create a fresh CompilePackage + self._package.initialize(fn_key, None, ignore_inlined_sources=False) + else: + try: + self._package.initialize( + fn_key, result.dynamo, ignore_inlined_sources=False + ) + self._package.install(result.backends) + except RuntimeError: + log.warning( + "Failed to load entry from dynamo cache", exc_info=True + ) + self._package.initialize( + fn_key, None, ignore_inlined_sources=False + ) + + fn = innermost_fn(fn) + + def aot_compile(example_inputs: tuple[tuple[Any, ...], dict[str, Any]]) -> Any: + from torch._dynamo.aot_compile import aot_compile_fullgraph + + if torch._inductor.config.force_disable_caches: + raise RuntimeError( + "Cannot precompile with torch._inductor.config.force_disable_caches=True; caching is required." + ) + + if not self.fullgraph: + raise RuntimeError( + "Graph breaks are not supported with aot compile. Please use torch.compile(fullgraph=True)." + ) + + if not callable(self.callback): + raise RuntimeError("aot compile requires a callable dynamo callback.") + + if self._hooks is None: + raise AssertionError("hooks must not be None for AOT compilation") + + return aot_compile_fullgraph( + fn, + example_inputs, + hooks=self._hooks, + backend=innermost_backend(self.callback), + dynamic=self._dynamic, + ) + + # add context containing GraphModule to any GraphModule forward functions + if isinstance(fn, GraphModule): + # add context containing GraphModule to any GraphModule forward functions + code_context.get_context(fn.forward.__code__)["orig_graphmodule"] = ( + weakref.ref(fn) + ) + + # Optimize the forward method of torch.nn.Module object + if isinstance(fn, torch.nn.Module): + if type(fn) is torch.jit._script.RecursiveScriptModule: + raise RuntimeError( + "torch.compile does not support compiling torch.jit.script or " + "torch.jit.freeze models directly.\n\n" + "Workaround: compile the original eager module instead:\n" + " model = torch.nn.Linear(3, 3)\n" + " compiled_model = torch.compile(model) # compile the eager module\n\n" + "torch.jit.script and torch.jit.freeze are deprecated in favor of " + "torch.compile. See https://pytorch.org/docs/main/jit.html for details." + ) + mod = fn + new_mod = OptimizedModule(mod, self) + # Save the function pointer to find the original callable while nesting + # of decorators. + new_mod._torchdynamo_orig_callable = mod.forward + new_mod._torchdynamo_wrapper_id = id(new_mod) + + # when compiling torch.nn.Module, + # provide public api OptimizedModule.get_compiler_config() + # check mod, not new_mod: OptimizedModule.__getattr__ delegates to mod + if inspect.getattr_static(mod, "get_compiler_config", None) is not None: + raise AssertionError( + "new_mod already has a get_compiler_config attribute" + ) + new_mod.get_compiler_config = get_compiler_config + + return new_mod + + if inspect.isclass(fn): + # User has wrapped the class with compile/disable decorator. Apply + # disable to init/call method. + cls_obj = fn + cls_obj.__call__ = self(cls_obj.__call__) + if issubclass(cls_obj, torch.nn.Module): + # NN module variable tracker directly inlines the _call_impl. + cls_obj._call_impl = self(cls_obj._call_impl) + return cls_obj + + if not callable(fn): + raise AssertionError( + f"A callable function is expected, but {type(fn)} is provided." + ) + + # NOTE [Top-level TorchInGraph and polyfilled functions] + # Some callables (e.g. torch.exp) are represented as TorchInGraphFunctionVariable + # when traced inside a frame. When such a function is passed directly to + # torch.compile, we detect it here so we can force it through wrap_inline. + # Similarly, functions registered via substitute_in_graph have a polyfill + # that Dynamo can trace, so they also need wrap_inline. + from .variables import TorchInGraphFunctionVariable + + rule = trace_rules.lookup(fn) + top_level_in_graph = isinstance(rule, type) and issubclass( + rule, TorchInGraphFunctionVariable + ) + has_polyfill = trace_rules.is_polyfilled_callable(fn) + + try: + filename = inspect.getsourcefile(fn) + except TypeError: + filename = None + should_wrap_module_call_impl = OptimizedModule._should_wrap_module_call_impl(fn) + if config.debug_force_nested_calls and filename not in DONT_WRAP_FILES: + fn = external_utils.wrap_inline(fn) + # Create a new code object for `fn` so that functions have different + # recompilation caches. + # Copy hack since deepcopy doesn't actually give a new code object + fn.__code__ = fn.__code__.replace(co_varnames=fn.__code__.co_varnames) # type: ignore[attr-defined] + elif config.wrap_top_frame or ( + ( + # exec/eval'd Python functions also report no source file + # but can be traced directly; wrapping collapses them onto + # wrap_inline's shared `inner` code (#124269). + (filename is None and not inspect.isfunction(fn)) + or trace_rules.check(fn) + or top_level_in_graph + or has_polyfill + ) + and ( + getattr(fn, "__name__", "") + not in ["_call_impl", "_wrapped_call_impl", "_lazy_forward"] + or should_wrap_module_call_impl + ) + and filename not in DONT_WRAP_FILES + ): + # call to a builtin without a frame for us to capture + fn = external_utils.wrap_inline(fn) + + def do_nothing(*arg: Any, **kwargs: Any) -> None: + pass + + callback: Callable[..., Any] = do_nothing + if hasattr(self, "callback"): + callback = self.callback # type: ignore[assignment] + + is_jit_tracing = torch._C._is_tracing + is_fx_symbolic_tracing = torch.fx._symbolic_trace.is_fx_symbolic_tracing + + @functools.wraps(fn) + def compile_wrapper(*args: Any, **kwargs: Any) -> Any: + # NB: function calls here could change global state (e.g. random state) + # and that can result in different behavior between eager and compiled! + # In particular, we don't have control over internal functions like justknobs_check + # called in _maybe_set_eval_frame. + # Unlike in eval_frame_cpp.cpp/convert_frame.py, we don't attempt to restore global state + # due to additional overhead costs. + prior = set_eval_frame(None) + prior_error_on_nested_compile: bool | None = None + fullgraph_count_enabled = False + # Fake propagation and AOT metadata collection execute user + # subclass code under active fake/functional modes. Nested compile + # must run the original function in those regions. Still honor + # explicit/internal requests to compile during FX tracing: HOP export + # depends on its internal compile to preserve HOPs, and some tests + # intentionally enable force_compile_during_fx_trace to get nested + # subgraphs. + if ( + _is_eager_on_nested_compile() + and not config.force_compile_during_fx_trace + ): + from torch._higher_order_ops.utils import _in_hop_compile + + if not _in_hop_compile(): + try: + return fn(*args, **kwargs) + finally: + _maybe_set_eval_frame(prior) + + if self.fullgraph: + prior_error_on_nested_compile = set_fullgraph_error_on_nested_compile( + torch._dynamo.config.error_on_dynamo_callback_in_fullgraph_compiled_code + ) + if not self.export: + fullgraph_count_enabled = set_fullgraph_compiled_frame_count(0) < 0 + if fullgraph_count_enabled: + reset_skip_reasons() + try: + # We shouldn't compile inside kernel invocation. + if tracing_context := torch._guards.TracingContext.try_get(): + if ( + tracing_context.fake_mode is not None + and tracing_context.fake_mode.in_kernel_invocation + ): + return fn(*args, **kwargs) + # Skip nested compile during export (but not HOP internal compile) + # Only skip if there's an active TracingContext (nested), not for top-level export + if ( + torch.compiler.is_exporting() + and not config.force_compile_during_fx_trace + ): + from torch._higher_order_ops.utils import _in_hop_compile + + if not _in_hop_compile(): + if torch._guards.TracingContext.try_get() is not None: + return fn(*args, **kwargs) + # Skip nested compile - just inline the function + if ( + is_fx_symbolic_tracing() + and not config.force_compile_during_fx_trace + ): + if config.error_on_nested_fx_trace: + raise RuntimeError( + "Detected that you are using FX to symbolically trace " + "a dynamo-optimized function. This is not supported at the moment." + ) + else: + return fn(*args, **kwargs) + + if is_jit_tracing(): + raise RuntimeError( + "Detected that you are using FX to torch.jit.trace " + "a dynamo-optimized function. This is not supported at the moment." + ) + + cleanups = [enter() for enter in self.enter_exit_hooks] + prior_skip_guard_eval_unsafe = set_skip_guard_eval_unsafe( + _is_skip_guard_eval_unsafe_stance() + ) + prior_isolate_recompiles_id = set_eval_frame_isolate_recompiles_id( + self._isolate_recompiles_id + ) + prior_error_on_graph_break = None + if not self.fullgraph and self.error_on_graph_break is not None: + current_error_on_graph_break = _get_error_on_graph_break() + if current_error_on_graph_break != self.error_on_graph_break: + prior_error_on_graph_break = current_error_on_graph_break + _set_error_on_graph_break(self.error_on_graph_break) + + # Ensure that if an assertion occurs after graph pushes + # something onto the DynamicLayerStack then we pop it off (the + # constructed graph code isn't guarded with try/finally). + # + # This used to be a context but putting a `with` here is a noticeable + # perf regression (#126293) + saved_dynamic_layer_stack_depth = ( + torch._C._functorch.get_dynamic_layer_stack_depth() + ) + + _maybe_set_eval_frame(_callback_from_stance(callback)) + + # Snapshot the local dispatch key set onto a C++ thread-local + # stack so it can be restored after the compiled call, matching + # the old _ForceDispatchKeyGuard behavior. Keeping the snapshot + # in C++ avoids constructing pybind11 DispatchKeySet / + # context-manager instances on every compiled call. The restore + # runs in the outer finally below (after the inner finally, i.e. + # after pop_dynamic_layer_stack) so the save/restore stack stays + # balanced even if the inner finally itself raises (e.g. the + # fullgraph "found no compiled frames" error). + torch._C._dynamo_save_local_dispatch_key_set() + try: + call_succeeded = False + try: + result = fn(*args, **kwargs) + call_succeeded = True + except (Unsupported, UncapturedHigherOrderOpError, UserError) as e: + if config.verbose: + raise + # strip internal tracebacks from causes + cur_exn: BaseException = e + while cur_exn.__cause__ is not None: + cur_exn.__cause__.with_traceback(None) + cur_exn = cur_exn.__cause__ + + raise e.with_traceback( + None + ) from e.__cause__ # User compiler error + except ShortenTraceback as e: + # Failures in the backend likely don't have useful + # data in the TorchDynamo frames, so we strip them out. + raise e.remove_dynamo_frames() from None # see TORCHDYNAMO_VERBOSE=1 + finally: + # Restore the dynamic layer stack depth if necessary. + set_eval_frame(None) + if fullgraph_count_enabled and call_succeeded: + count = set_fullgraph_compiled_frame_count(-1) + if count == 0 and _stance.stance == "default": + skip_reasons = get_skip_reasons() + msg = "torch.compile with fullgraph=True found no compiled frames." + if skip_reasons: + reasons_str = "\n".join( + f" - {r}" for r in skip_reasons + ) + msg += f" Skipped frames:\n{reasons_str}" + else: + msg += ( + " Compilation was not attempted and no cached compiled" + " code was found." + ) + raise RuntimeError(msg) + if prior_error_on_graph_break is not None: + _set_error_on_graph_break(prior_error_on_graph_break) + if prior_error_on_nested_compile is not None: + set_fullgraph_error_on_nested_compile( + prior_error_on_nested_compile + ) + torch._C._functorch.pop_dynamic_layer_stack_and_undo_to_depth( + saved_dynamic_layer_stack_depth + ) + + set_skip_guard_eval_unsafe(prior_skip_guard_eval_unsafe) + set_eval_frame_isolate_recompiles_id( + prior_isolate_recompiles_id + ) + for cleanup in cleanups: + cleanup() + finally: + # Restore the local dispatch key set snapshotted above. In an + # outer finally so it runs even if the inner finally raised, + # keeping the save/restore stack balanced. + torch._C._dynamo_restore_local_dispatch_key_set() + return result + finally: + if fullgraph_count_enabled: + set_fullgraph_compiled_frame_count(-1) + dynamo_tls.skip_reasons = None + _maybe_set_eval_frame(prior) + + # hooks to properly handle inlining + if self.error_on_graph_break is not None: + compile_wrapper._torchdynamo_inline = ( # type: ignore[attr-defined] + external_utils.wrap_inline_with_error_on_graph_break( + fn, self.error_on_graph_break + ) + ) + else: + compile_wrapper._torchdynamo_inline = fn # type: ignore[attr-defined] + # Save the function pointer to find the original callable while nesting + # of decorators. + compile_wrapper._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + compile_wrapper._torchdynamo_wrapper_id = id(compile_wrapper) # type: ignore[attr-defined] + compile_wrapper._isolate_recompiles_id = self._isolate_recompiles_id # type: ignore[attr-defined] + + # when compiling user function instead of nn.Module + # provide public api _fn.get_compiler_config() + if hasattr(compile_wrapper, "get_compiler_config"): + raise AssertionError( + "compile_wrapper already has a get_compiler_config attribute" + ) + compile_wrapper.get_compiler_config = get_compiler_config # type: ignore[attr-defined] + if torch._dynamo.config.enable_aot_compile: + compile_wrapper.aot_compile = aot_compile # type: ignore[attr-defined] + + # If the function is called using torch._dynamo.optimize decorator, we + # should prevent any type of skipping. + if callback not in (None, False): + if not hasattr(fn, "__code__"): + raise RuntimeError( + textwrap.dedent( + """ + + torch._dynamo.optimize is called on a non function object. + If this is a callable class, please wrap the relevant code into a function and optimize the + wrapper function. + + >> class CallableClass: + >> def __init__(self) -> None: + >> super().__init__() + >> self.relu = torch.nn.ReLU() + >> + >> def __call__(self, x): + >> return self.relu(torch.sin(x)) + >> + >> def print_hello(self): + >> print("Hello world") + >> + >> mod = CallableClass() + + If you want to optimize the __call__ function and other code, wrap that up in a function + + >> def wrapper_fn(x): + >> y = mod(x) + >> return y.sum() + + and then optimize the wrapper_fn + + >> opt_wrapper_fn = torch._dynamo.optimize(wrapper_fn) + """ + ) + ) + always_optimize_code_objects[fn.__code__] = True + + return compile_wrapper + + +class OptimizeContext(_TorchDynamoContext): + def __init__( + self, + callback: DynamoCallback, + backend_ctx_ctor: Callable[[], contextlib.AbstractContextManager[Any]], + first_ctx: bool = False, + *, + fullgraph: bool = False, + error_on_graph_break: bool | None = None, + export: bool = False, + dynamic: bool | None = None, + compiler_config: CompilerConfig | None = None, + rebuild_ctx: Callable[[], OptimizeContext | _NullDecorator] | None = None, + package: CompilePackage | None = None, + hooks: Hooks | None = None, + isolate_recompiles: bool = False, + dynamic_shapes: ShapesSpec | ParamsSpec | dict[str, Any] | None = None, + ) -> None: + def on_enter() -> None: + install_generation_tagging_init() + + super().__init__( + callback=callback, + on_enter=on_enter, + backend_ctx_ctor=backend_ctx_ctor, + patch_fn=TorchPatcher.patch, + first_ctx=first_ctx, + fullgraph=fullgraph, + error_on_graph_break=error_on_graph_break, + export=export, + dynamic=dynamic, + compiler_config=compiler_config, + package=package, + hooks=hooks, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + if config.compiled_autograd: + _dynamic = self._dynamic + if _dynamic is None: + _dynamic = not torch._dynamo.config.assume_static_by_default + + def call_compiled_autograd() -> functools.partial[bool | None]: + if rebuild_ctx is None: + raise AssertionError( + "rebuild_ctx must not be None for compiled autograd" + ) + compiler_fn = rebuild_ctx() + ctx = torch._dynamo.compiled_autograd._enable( + compiler_fn, + # pyrefly: ignore [bad-argument-type] + dynamic=_dynamic, + ignore_active_disable_ctx=False, + ) + ctx.__enter__() + return functools.partial(ctx.__exit__, None, None, None) + + self.enter_exit_hooks.append(call_compiled_autograd) + + def __call__(self, fn: Any) -> Any: + result = super().__call__(fn) + result._is_torch_compile = True # type: ignore[attr-defined] + return result + + def __reduce__( + self, + ) -> tuple[type[OptimizeContext], tuple[Any, ...], dict[str, Any]]: + return ( + self.__class__, + (self.callback, self._backend_ctx_ctor, self.first_ctx), + { + "export": self.export, + "dynamic": self._dynamic, + "compiler_config": self.compiler_config, + }, + ) + + +class RunOnlyContext(_TorchDynamoContext): + def __init__(self) -> None: + # cudagraph trees relies on generation increment + def on_enter() -> None: + torch._dynamo.mutation_guard.GenerationTracker.generation += 1 + + super().__init__(callback=False, on_enter=on_enter) + + def __reduce__(self) -> tuple[type[RunOnlyContext], tuple[Any, ...]]: + return (self.__class__, ()) + + +class DisableContext(_TorchDynamoContext): + def __init__(self, msg: str | None = None, wrapping: bool = True) -> None: + super().__init__(callback=None) + self.msg = msg + self.wrapping = wrapping + + def __call__(self, fn: Callable[..., Any]) -> Callable[..., Any]: + # Earlier this code was in the base class _TorchDynamoContext. But we + # moved it here to have better code organization. For disable, we just + # want the callback to be None. We don't have to check trace_rules or + # create any wrapper. + fn = innermost_fn(fn) + + if isinstance(fn, torch.nn.Module): + mod = fn + new_mod = OptimizedModule(mod, self) + new_mod._torchdynamo_orig_callable = mod.forward + new_mod._torchdynamo_wrapper_id = id(new_mod) + return new_mod + + if isinstance(fn, type): + # User has wrapped the class with compile/disable decorator. Apply + # disable to init/call method. + cls_obj = fn + # Disable on init is useful for reconstruction of bytecodes where we + # want to prevent Dynamo from tracing into the init function. Check + # test_reconstruction in test_model_output.py. + cls_obj.__init__ = self(cls_obj.__init__) # type: ignore[misc] + cls_obj.__call__ = self(cls_obj.__call__) + if issubclass(cls_obj, torch.nn.Module): + # NN module variable tracker directly inlines the _call_impl. Disable it. + cls_obj._call_impl = self(cls_obj._call_impl) + return cls_obj + + if not callable(fn): + raise AssertionError( + f"A callable function is expected, but {type(fn)} is provided." + ) + + def _fn(*args: Any, **kwargs: Any) -> Any: + # Hot path (e.g. around custom operators); keep it minimal. + prior = set_eval_frame(None) + try: + # disable => self.callback is None; _callback_from_stance(None) is + # None ("off") for most stances but False (run-only) for + # eager_on_recompile. Install only when non-None (skips the + # justknob-guarded _maybe_set_eval_frame on the common path). + callback = _callback_from_stance(self.callback) + if callback is not None: + _maybe_set_eval_frame(callback) + try: + # Only export needs the annotation work. + if torch.compiler.is_exporting(): + fn_name = getattr(fn, "__name__", type(fn).__name__) + # Skip annotation for __torch_dispatch__ (internal detail). + if fn_name != "__torch_dispatch__": + with fx_traceback.annotate( + { + "_torchdynamo_disable": True, + "_torchdynamo_disable_recursive": True, + "_torchdynamo_disable_method": fn_name, + } + ): + return fn(*args, **kwargs) + return fn(*args, **kwargs) + finally: + if callback is not None: + set_eval_frame(None) + finally: + # Restore via _maybe_set_eval_frame so re-installing honors the + # enable_compiler_set_eval_frame killswitch; skip when prior None. + if prior is not None: + _maybe_set_eval_frame(prior) + + # Under some circumstances (e.g. precompile) we can end up calling @disable + # decorator in generated bytecode and trigger recompile. This is due to the + # fact that the old callback from torch.compile() is still active and under + # this circumstance we will trigger a failure with set_stance("fail_on_recompile"). + # Therefore we want to skip calling into any frame in this case. + if self.wrapping: + _fn = functools.wraps(fn)(_fn) + + _fn._torchdynamo_disable = True # type: ignore[attr-defined] + _fn._torchdynamo_disable_msg = self.msg # type: ignore[attr-defined] + + # Save the function pointer to find the original callable while nesting + # of decorators. + _fn._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + _fn._torchdynamo_wrapper_id = id(_fn) # type: ignore[attr-defined] + + _fn._torchdynamo_disable_recursive = True # type: ignore[attr-defined] + + return _fn + + def __reduce__(self) -> tuple[type[DisableContext], tuple[Any, ...]]: + return (self.__class__, ()) + + +def _optimize_catch_errors( + compile_fn: convert_frame.ConvertFrameProtocol, + hooks: Hooks, + backend_ctx_ctor: Callable[ + [], contextlib.AbstractContextManager[Any] + ] = null_context, + fullgraph: bool = False, + error_on_graph_break: bool | None = None, + export: bool = False, + dynamic: bool | None = None, + compiler_config: CompilerConfig | None = None, + rebuild_ctx: Callable[[], OptimizeContext | _NullDecorator] | None = None, + package: CompilePackage | None = None, + isolate_recompiles: bool = False, + dynamic_shapes: ShapesSpec | ParamsSpec | dict[str, Any] | None = None, +) -> OptimizeContext: + return OptimizeContext( + convert_frame.catch_errors_wrapper(compile_fn, hooks), + backend_ctx_ctor=backend_ctx_ctor, + first_ctx=True, + fullgraph=fullgraph, + error_on_graph_break=error_on_graph_break, + export=export, + dynamic=dynamic, + compiler_config=compiler_config, + rebuild_ctx=rebuild_ctx, + package=package, + hooks=hooks, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + +def get_compiler_fn( + compiler_fn: str | Callable[..., Any] | None, +) -> WrapBackendDebug: + from .repro.after_dynamo import wrap_backend_debug + + if compiler_fn is None: + # Special case None to avoid crashing in hasattr + compiler_str = None + elif hasattr(compiler_fn, "compiler_name"): + compiler_str = compiler_fn.compiler_name # type: ignore[union-attr] + if not isinstance(compiler_str, str): + raise AssertionError( + f"Expected compiler_name to be a str, got {type(compiler_str)}" + ) + elif isinstance(compiler_fn, str): + compiler_str = compiler_fn + else: + compiler_str = None + compiler_fn = lookup_backend(compiler_fn) # type: ignore[arg-type] + return wrap_backend_debug(compiler_fn, compiler_str) + + +class _NullDecorator(contextlib.nullcontext): # type: ignore[type-arg] + def __call__(self, fn: Callable[..., Any]) -> Callable[..., Any]: + if not callable(fn): + raise AssertionError( + f"A callable function is expected, but {type(fn)} is provided." + ) + return fn + + +# Make dynamo graph to have same input/output spec as user code +def argument_names( + f_sig: inspect.Signature, + args: list[Any] | tuple[Any, ...], + kwargs: dict[str, Any], +) -> list[str]: + def signature_to_fullargspec(sig: inspect.Signature) -> inspect.FullArgSpec: + # Get a list of Parameter objects from the Signature object + params = list(sig.parameters.values()) + # Separate positional arguments, keyword-only arguments and varargs/varkw + args = [ + p.name for p in params if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + ] + kwonlyargs = [ + p.name for p in params if p.kind == inspect.Parameter.KEYWORD_ONLY + ] + varargs = next( + (p.name for p in params if p.kind == inspect.Parameter.VAR_POSITIONAL), + None, + ) + varkw = next( + (p.name for p in params if p.kind == inspect.Parameter.VAR_KEYWORD), + None, + ) + # Get default values for positional arguments and keyword-only arguments + defaults = tuple( + p.default + for p in params + if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + and p.default is not inspect.Parameter.empty + ) + kwonlydefaults = { + p.name: p.default + for p in params + if p.kind == inspect.Parameter.KEYWORD_ONLY + and p.default is not inspect.Parameter.empty + } + # Get annotations for parameters and return value + # pyrefly: ignore [implicit-any] + annotations = {} + if sig.return_annotation: + annotations = {"return": sig.return_annotation} + for parameter in params: + annotations[parameter.name] = parameter.annotation + # Return a FullArgSpec object with the extracted attributes + return inspect.FullArgSpec( + args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations + ) + + fullargspec = signature_to_fullargspec(f_sig) + + # 1. Map `args` 1-to-1 to positional arguments in original signature. + input_strs = fullargspec.args[: len(args)] + + if len(args) > len(fullargspec.args): + # 2. If there are more arguments left in `args`, they map to varargs in original + # signature. Assign names as {varargs}_0, {varargs}_1, ... + if fullargspec.varargs is None: + raise AssertionError("More arguments than expected") + input_strs += [ + f"{fullargspec.varargs}_{i}" for i in range(len(args) - len(input_strs)) + ] + elif len(args) < len(fullargspec.args): + # 3. If there are fewer arguments in `args` than `fullargspec.args`, + # it implies these are arguments either with default values, or provided in + # `kwargs`. The former can be safely ignored. Because Dynamo.export does not + # export them as part of the function signature. The latter will be handled + # in the next step. + for unprovided_arg in fullargspec.args[ + len(args) : -len(fullargspec.defaults or []) + ]: + if unprovided_arg not in kwargs: + raise AssertionError(f"Missing argument {unprovided_arg}") + + # 4. Keyword arguments provided in `kwargs`. + input_strs += list(kwargs.keys()) + + # 5. Keyword-only arguments with default values if not provided are not exported + # as part of the function signature. + for kwonly_arg in fullargspec.kwonlyargs: + kwonlydefaults = fullargspec.kwonlydefaults or {} + if kwonly_arg not in kwargs and kwonly_arg not in kwonlydefaults: + raise AssertionError(f"Missing keyword only argument {kwonly_arg}") + + return input_strs + + +def check_if_dynamo_supported() -> None: + if sys.version_info >= (3, 15): + raise RuntimeError("Python 3.15+ not yet supported for torch.compile") + elif sysconfig.get_config_var("Py_GIL_DISABLED") == 1 and sys.version_info < ( + 3, + 13, + 3, + ): + raise RuntimeError( + "torch.compile is not supported on Python < 3.13.3 built with GIL disabled. " + "Please use Python 3.13.3+." + ) + + +def is_dynamo_supported() -> bool: + try: + check_if_dynamo_supported() + return True + except Exception: + return False + + +def check_if_inductor_supported() -> None: + check_if_dynamo_supported() + + +def is_inductor_supported() -> bool: + try: + check_if_inductor_supported() + return True + except Exception: + return False + + +def check_for_incompatible_configs() -> None: + # Some of the configs should be mutually exclusive + if config.suppress_errors and config.fail_on_recompile_limit_hit: + raise AssertionError( + "Dynamo configs suppress_error and fail_on_recompile_limit_hit can not both be active at the same time." + ) + + +def optimize(*args: Any, **kwargs: Any) -> OptimizeContext | _NullDecorator: + def rebuild_ctx() -> OptimizeContext | _NullDecorator: + ca_kwargs_override = config.compiled_autograd_kwargs_override + if ca_kwargs_override: + # NOTE: The process of translating other `torch.compile` kwargs to `torch._dynamo.optimize` kwargs + # is more complicated, we will add it in the future when needed. + if set(ca_kwargs_override.keys()) != {"fullgraph"}: + raise AssertionError( + f"Only `fullgraph` kwarg override is supported for now, but got {ca_kwargs_override.keys()}" + ) + kwargs["nopython"] = ca_kwargs_override["fullgraph"] + return optimize(*args, **kwargs) + + return _optimize(rebuild_ctx, *args, **kwargs) + + +def _optimize( + rebuild_ctx: Callable[[], OptimizeContext | _NullDecorator], + backend: str | Callable[..., Any] = "inductor", + *, + nopython: bool = False, + error_on_graph_break: bool | None = None, + guard_export_fn: Callable[[_guards.GuardsSet], None] | None = None, + guard_fail_fn: Callable[[GuardFail], None] | None = None, + guard_filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] + | None = None, + disable: bool = False, + dynamic: bool | None = None, + package: CompilePackage | None = None, + recompile_limit: int | None = None, + isolate_recompiles: bool = False, + dynamic_shapes: ShapesSpec | ParamsSpec | dict[str, Any] | None = None, +) -> OptimizeContext | _NullDecorator: + """ + The main entrypoint of TorchDynamo. Do graph capture and call + backend() to optimize extracted graphs. + + Args: + backend: One of the two things: + - Either, a function/callable taking a torch.fx.GraphModule and + example_inputs and returning a python callable that runs the + graph faster. + One can also provide additional context for the backend, like + torch.jit.fuser("fuser2"), by setting the backend_ctx_ctor attribute. + See AOTAutogradMemoryEfficientFusionWithContext for the usage. + - Or, a string backend name in `torch._dynamo.list_backends()` + nopython: If True, graph breaks will be errors and there will + be a single whole-program graph. + error_on_graph_break: If not None, the current `error_on_graph_break` setting is set to the given value. + See `torch._dynamo.error_on_graph_break()` for more details on what `error_on_graph_break` means. + + Unlike `nopython=True` (i.e. `fullgraph=True`), there is no guarantee of a single whole-program graph. + If `nopython` is True, `error_on_graph_break` does nothing. + disable: If True, turn this decorator into a no-op + dynamic: If True, upfront compile as dynamic a kernel as possible. If False, + disable all dynamic shapes support (always specialize). If None, automatically + detect when sizes vary and generate dynamic kernels upon recompile. + recompile_limit: Maximum number of recompilations for this region. + If None, uses ``torch._dynamo.config.recompile_limit``. + isolate_recompiles: If True, this compile call gets its own isolated + cache so recompilations are tracked independently from other + compile calls on the same function. + + Example Usage:: + + @torch._dynamo.optimize() + def toy_example(a, b): ... + """ + check_if_dynamo_supported() + check_for_incompatible_configs() + # Note: The hooks object could be global instead of passed around, *however* that would make + # for a confusing API usage and plumbing story wherein we nest multiple .optimize calls. + # There is some prior art around this, w/r/t nesting backend calls are enforced to be the same + # compiler, however, this feels onerous for callback and hooks, and it feels better to give our users an + # easier to understand UX at the cost of a little more plumbing on our end. + hooks = Hooks( + guard_export_fn=guard_export_fn, + guard_fail_fn=guard_fail_fn, + guard_filter_fn=guard_filter_fn, + ) + torch._C._log_api_usage_once("torch._dynamo.optimize") + if ( + disable + or os.environ.get("TORCHDYNAMO_DISABLE", "") == "1" + or (not justknobs_check("pytorch/compiler:enable_dynamo")) + ): + return _NullDecorator() + + if nopython and not config.debug_force_graph_break_on_leaf_return: + return optimize_assert( + backend, + dynamic=dynamic, + hooks=hooks, + rebuild_ctx=rebuild_ctx, + package=package, + recompile_limit=recompile_limit, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + backend = get_compiler_fn(backend) + + # Find if backend has any extra context manager + backend_ctx_ctor = getattr(backend, "backend_ctx_ctor", null_context) + + # The backend function is stashed in the callable returned by + # _optimize_catch_errors in the field _torchdynamo_orig_backend. This can + # be used by eval_frame.c to insert a guard on the backend. + + # With CachingPrecompile, instantiate an uninitialized CompilePackage + # which gets initialized by _optimize_catch_errors.__call__ once we have a function + if config.caching_precompile and package is None: + from .package import CompilePackage + + package = CompilePackage(fn=None, dynamo=None, ignore_inlined_sources=False) + + return _optimize_catch_errors( + convert_frame.convert_frame( + backend, + hooks, + package=package, + recompile_limit=recompile_limit, + ), + hooks, + backend_ctx_ctor, + fullgraph=False, + error_on_graph_break=error_on_graph_break + and not config.debug_force_graph_break_on_leaf_return, + dynamic=dynamic, + compiler_config=( + cast(CompilerConfigProvider, backend).get_compiler_config() + if hasattr(backend, "get_compiler_config") + else None + ), + rebuild_ctx=rebuild_ctx, + package=package, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + +# TODO(voz): Consider making "explain" output alongside a run / part of a run +@patch("torch._dynamo.symbolic_convert.explain", True) +def explain(f: Callable[..., Any], *extra_args: Any, **extra_kwargs: Any) -> Any: + from .backends.debugging import ExplainOutput + + def inner(*args: Any, **kwargs: Any) -> ExplainOutput: + # TODO(voz): Do we want a decorator for this? + from . import reset # type: ignore[attr-defined] + + reset() + + graphs: list[torch.fx.GraphModule] = [] + break_reasons: list[Any] = [] + op_count: int = 0 + ops_per_graph: list[list[Target]] = [] + out_guards: list[_guards.Guard] = [] + + def dynamo_graph_accumulating_compiler( + gm: torch.fx.GraphModule, example_inputs: Any + ) -> Callable[..., Any]: + from .backends.debugging import _explain_graph_detail + + nonlocal graphs + nonlocal op_count + nonlocal ops_per_graph + nonlocal break_reasons + + gm, graphs, op_count, ops_per_graph, break_reasons = _explain_graph_detail( + gm, graphs, op_count, ops_per_graph, break_reasons + ) + + return gm.forward + + def guard_export_print(guards: Iterable[_guards.Guard]) -> None: + nonlocal out_guards + out_guards.extend(guards) + + opt_f = optimize( + dynamo_graph_accumulating_compiler, + nopython=False, + guard_export_fn=guard_export_print, + )(f) + # TODO(voz): We may have instances of `f` that mutate inputs, we should track sideeffects and reject. + opt_f(*args, **kwargs) + + graph_count = len(graphs) + graph_break_count = graph_count - 1 + compile_time = compile_times(repr="str") + + # TODO(voz): Do we want a decorator for this? + reset() + + return ExplainOutput( + graphs, + graph_count, + graph_break_count, + break_reasons, + op_count, + ops_per_graph, + out_guards, + compile_time, + ) + + if extra_args or extra_kwargs: + warnings.warn( + "explain(f, *args, **kwargs) is deprecated, use explain(f)(*args, **kwargs) instead. " + "If you don't migrate, we may break your explain call in the future if your user defined kwargs " + "conflict with future kwargs added to explain(f).", + FutureWarning, + stacklevel=2, + ) + return inner(*extra_args, **extra_kwargs) + else: + return inner + + +class FlattenInputOutputSignature(torch.fx.Transformer): + def __init__( + self, + m: torch.fx.GraphModule, + flat_args: list[Any], + matched_input_elements_positions: list[int], + flat_results: Sequence[Any], + matched_output_elements_positions: list[int], + example_fake_inputs: list[torch.Tensor], + flat_args_dynamic_dims: list[set[int]], + fake_mode: fake_tensor.FakeTensorMode | None = None, + ) -> None: + super().__init__(m) + + if len(flat_args_dynamic_dims) != len(flat_args): + raise AssertionError( + f"flat_args_dynamic_dims length ({len(flat_args_dynamic_dims)}) " + f"must match flat_args length ({len(flat_args)})" + ) + matched_input_elements_to_fake = { + val: example_fake_inputs[ix] + for ix, val in enumerate(matched_input_elements_positions) + } + + self.new_args = [] + for i in range(len(flat_args)): + arg = super().placeholder(f"arg{i}", (), {}) + if i in matched_input_elements_to_fake: + arg.node.meta["val"] = matched_input_elements_to_fake[i] + else: + # Fill node.meta["val"] with faketensor from the input, + # if it's not found in matched_input_elements_positions + if fake_mode is not None and isinstance(flat_args[i], torch.Tensor): + # TODO(zhxchen17) Also preserve all the user constraints here. + arg.node.meta["val"] = fake_mode.from_tensor( + flat_args[i], + symbolic_context=StatelessSymbolicContext( + dynamic_sizes=[ + ( + DimDynamic.DYNAMIC + if d in flat_args_dynamic_dims[i] + else DimDynamic.STATIC + ) + for d in range(len(flat_args[i].shape)) + ], + constraint_sizes=[None] * len(flat_args[i].shape), + ), + ) + elif isinstance(flat_args[i], _IntWrapper): + arg.node.meta["val"] = flat_args[i].val + else: + arg.node.meta["val"] = flat_args[i] + + self.new_args.append(arg) + self.old_args_gen = (self.new_args[i] for i in matched_input_elements_positions) + self.matched_output_elements_positions = matched_output_elements_positions + self.flat_results = flat_results + + def placeholder( + self, target: Target, args: tuple[Argument, ...], kwargs: dict[str, Any] + ) -> Any: + arg = next(self.old_args_gen) + if "val" in self.current_node.meta: + arg.node.meta["val"] = self.current_node.meta["val"] + if "tensor_dict" in self.current_node.meta: + arg.node.meta["tensor_dict"] = self.current_node.meta["tensor_dict"] + if "example_value" in self.current_node.meta: + # NB: intentionally do not use set_example_value + arg.node.meta["example_value"] = self.current_node.meta["example_value"] + if "unbacked_bindings" in self.current_node.meta: + arg.node.meta["unbacked_bindings"] = self.current_node.meta[ + "unbacked_bindings" + ] + return arg + + def output( + self, target: Target, args: tuple[Argument, ...], kwargs: dict[str, Any] + ) -> Any: + dynamo_result_flat = args[0] + lookup = [*dynamo_result_flat, *self.new_args] # type: ignore[misc] + # pyrefly: ignore [implicit-any] + new_results_flat = [] + for i in range(len(self.flat_results)): + if self.matched_output_elements_positions[i] is not None: + new_results_flat.append( + lookup[self.matched_output_elements_positions[i]] + ) + else: + const_val = self.flat_results[i] + if not isinstance(const_val, tuple(common_constant_types)): + raise AssertionError( + f"Expected const_val to be a common constant type, got {type(const_val)}" + ) + new_results_flat.append(const_val) + return super().output(target, (new_results_flat,), {}) + + def run_node(self, n: Node) -> Any: + self.current_node = n + result_proxy = super().run_node(n) + if "val" in self.current_node.meta: + result_proxy.node.meta["val"] = self.current_node.meta["val"] + if "example_value" in self.current_node.meta: + # NB: intentionally do not use set_example_value + result_proxy.node.meta["example_value"] = self.current_node.meta[ + "example_value" + ] + if "unbacked_bindings" in self.current_node.meta: + result_proxy.node.meta["unbacked_bindings"] = self.current_node.meta[ + "unbacked_bindings" + ] + if self.current_node.op != "output": + result_proxy.node._rename( + getattr(self.current_node, "name", result_proxy.node.name) + ) + return result_proxy + + def transform(self) -> torch.fx.GraphModule: + result_gm = super().transform() + if "dynamo_flat_name_to_original_fqn" in self.module.meta: # type: ignore[operator] + result_gm.meta["dynamo_flat_name_to_original_fqn"] = self.module.meta[ # type: ignore[index] + "dynamo_flat_name_to_original_fqn" # type: ignore[index] + ] + if "dynamo_compile_id" in self.module.meta: # type: ignore[operator] + result_gm.meta["dynamo_compile_id"] = self.module.meta["dynamo_compile_id"] # type: ignore[index] + return result_gm + + +class ExportResult(NamedTuple): + graph_module: torch.fx.GraphModule + guards: _guards.GuardsSet + # NB: Do not add new fields without overriding __iter__; people are + # destructuring so it is BC-breaking + + +# NOTE: this function only supports graphs created by Dynamo's OutputGraph module +def check_signature_rewritable(graph: torch.fx.GraphModule) -> None: + # pyrefly: ignore [implicit-any] + input_errors = [] + for node in graph.graph.find_nodes(op="placeholder"): + # set in OutputGraph._call_user_compiler + if not hasattr(node, "_dynamo_source"): + raise AssertionError("node is missing _dynamo_source attribute") + if not hasattr(graph, "_source_to_user_stacks"): + raise AssertionError("graph is missing _source_to_user_stacks attribute") + + # NOTE: We can safely ignore these type warnings if and only if + # the function is made from OutputGraph (checked in the assertions) + source = node._dynamo_source # type: ignore[attr-defined] + user_stacks = graph._source_to_user_stacks.get(source) # type: ignore[operator, union-attr] + if user_stacks is None: + continue + if len(user_stacks) == 0: + raise AssertionError("user_stacks must not be empty") + # In some cases we may not have a useful stack. Look for a + # useful stack + stack = None + for s in user_stacks: + if len(s) == 0: + continue + stack = s + break + if stack is None: + msg = f"{source.name}, a closed over free variable" + else: + tb = "".join(traceback.format_list(stack)) + extra = "" + if len(user_stacks) > 1: + extra = f"(elided {len(user_stacks) - 1} more accesses)" + msg = f"{source.name}, accessed at:\n{tb}{extra}" + # TODO: option to print ALL of the stack traces at once + input_errors.append(msg) + + if input_errors: + raise UserError( + UserErrorType.INVALID_INPUT, + "Cannot export model which references tensors that are neither " + "buffers/parameters/constants nor are direct inputs. For each tensor, if you'd " + "like this tensor to be an explicit input, add it as a dummy argument " + "to the top-level model definition you are exporting; if you would " + "like its value to be embedded as an exported constant, wrap its access " + "in a function marked with @assume_constant_result.\n\n" + + "\n\n".join(input_errors), + ) + + +def check_user_input_output(flat_values: list[Any], error_type: UserErrorType) -> None: + supported_types = [ + torch.Tensor, + torch.SymInt, + torch.SymFloat, + torch.SymBool, + torch._C.ScriptObject, + _IntWrapper, + ] + list(common_constant_types) + + def is_supported_type(val: Any) -> bool: + return isinstance(val, tuple(supported_types)) or is_custom_class(type(val)) + + value_type = "input" if error_type == UserErrorType.INVALID_INPUT else "output" + # We only check that the outputs are not None. Inputs can be None. + for v in flat_values: + if not is_supported_type(v): + if error_type == UserErrorType.INVALID_INPUT and v is None: + continue + + raise UserError( + error_type, + f"It looks like one of the {value_type}s with type `{type(v)}` " + "is not supported or pytree-flattenable. \n" + f"Exported graphs {value_type}s can only contain the " + f"following supported types: {supported_types}. \n" + "If you are using a custom class object, " + "please register a pytree_flatten/unflatten function " + "using `torch.utils._pytree.register_pytree_node` or " + "`torch.export.register_dataclass`.", + ) + + +def rewrite_signature( + f_sig: inspect.Signature, + graph: torch.fx.GraphModule, + fake_mode: fake_tensor.FakeTensorMode | None, + flat_args: list[Any], + in_spec: pytree.TreeSpec, + example_fake_inputs: list[Any], + graph_captured_input: Iterable[Any], + graph_captured_output: Iterable[Any] | None, + dynamo_traced_result: Any, + flat_args_dynamic_dims: list[set[int]], +) -> torch.fx.GraphModule: + orig_args, orig_kwargs = pytree.tree_unflatten(flat_args, in_spec) + + check_user_input_output(flat_args, UserErrorType.INVALID_INPUT) + flat_results_traced, out_spec_traced = pytree.tree_flatten(dynamo_traced_result) + check_user_input_output(flat_results_traced, UserErrorType.INVALID_OUTPUT) + + def check_optional_input_and_error(f_sig: inspect.Signature) -> None: + # Check if function has optional input. + for name, param in f_sig.parameters.items(): + if param.default is not inspect.Parameter.empty: + import torch._dynamo.graph_break_hints as graph_break_hints + from torch._dynamo.exc import unimplemented + + log.error( + "Parameter %s is optional with a default value of %s", + name, + param.default, + ) + unimplemented( + gb_type="rewrite_signature: cannot trace optional function input", + context="", + explanation=f"Parameter {name} is optional with a default value of {param.default}. This is not supported yet.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + def produce_matching( + debug_type: str, sources: Iterable[Any], candidates: Iterable[Any] + ) -> list[int | None]: + matched_elements_positions: list[int | None] = [] + dict_of_source_vals = {} + for i, val in enumerate(sources): + dict_of_source_vals[id(val)] = i + + for val in candidates: + if isinstance(val, tuple(common_constant_types)): + matched_elements_positions.append(None) + elif id(val) not in dict_of_source_vals: + if debug_type == "inputs": + check_optional_input_and_error(f_sig) + raise AssertionError( + f"Unexpectedly found a {type(val)} in the {debug_type}.\n" + 'Please file an issue along with a paste of the logs from TORCH_LOGS="+export"', + ) + else: + matched_elements_positions.append(dict_of_source_vals[id(val)]) + + return matched_elements_positions + + matched_input_elements_positions = produce_matching( + "inputs", flat_args, graph_captured_input + ) + + if graph_captured_output is None: + raise AssertionError("graph_captured_output must not be None") + matched_output_elements_positions = produce_matching( + "outputs", list(graph_captured_output) + flat_args, flat_results_traced + ) + + new_graph = FlattenInputOutputSignature( + graph, + flat_args, + matched_input_elements_positions, # type: ignore[arg-type] + flat_results_traced, + matched_output_elements_positions, # type: ignore[arg-type] + example_fake_inputs, + flat_args_dynamic_dims, + fake_mode, + ).transform() + + new_graph.graph._codegen = _PyTreeCodeGen( + _PyTreeInfo( + argument_names(f_sig, orig_args, orig_kwargs), + in_spec, + out_spec_traced, + ) + ) + new_graph.recompile() + return new_graph + + +def export( + f: Callable[..., Any], + *extra_args: Any, + aten_graph: bool = False, + pre_dispatch: bool = False, + decomposition_table: dict[torch._ops.OpOverload, Callable[..., Any]] | None = None, + tracing_mode: str = "symbolic", + dynamic_shapes: _DynamicShapesInput = None, + specialize_float: bool = True, + assume_static_by_default: bool = False, + same_signature: bool = True, + disable_constraint_solver: bool = False, + prefer_deferred_runtime_asserts_over_guards: bool = False, + _log_export_usage: bool = True, + constraints: list[Constraint] | None = None, + **extra_kwargs: Any, +) -> Callable[..., ExportResult]: + """ + Export an input function f to a format that can be executed outside of PyTorch using the FX graph. + + Args: + f (callable): A PyTorch function to be exported. + + aten_graph (bool): If True, exports a graph with ATen operators. + If False, exports a graph with Python operators. Default is False. + + pre_dispatch (bool): If True, exports a graph with ATen operators, + but before any logic in the PyTorch dispatcher has run. + This can be useful if you want to apply further transformations on a graph before running it + through autograd, autocast, or any other functionalities that are integrated into the dispatcher. + This flag is only valid if aten_graph=True is set. + Default is False. + + decomposition_table (dict): A dictionary that maps operators to their decomposition functions. + Required if aten_graph or tracing_mode is specified. Default is None. + + tracing_mode (str): If "symbolic", turn on dynamic shapes support. Default is "symbolic". + + dynamic_shapes: + An optional argument where the type should either be: + 1) a dict from argument names of ``f`` to their dynamic shape specifications, + 2) a tuple that specifies dynamic shape specifications for each input in original order. + If you are specifying dynamism on keyword args, you will need to pass them in the order that + is defined in the original function signature. + + The dynamic shape of a tensor argument can be specified as either + (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is + not required to include static dimension indices in this dict, but when they are, + they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None, + where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions + are denoted by None. Arguments that are dicts or tuples / lists of tensors are + recursively specified by using mappings or sequences of contained specifications. + + **ShapesSpec API.** ``dynamic_shapes`` may also be a + :class:`torch.fx.experimental.dynamic_spec.ShapesSpec` (or its + shorthand :class:`torch.fx.experimental.dynamic_spec.ParamsSpec`) -- + the same spec API exposed via ``dynamic_shapes=`` in + :func:`torch.compile`. See :func:`torch.export.export` for usage + and semantics, and :mod:`torch.fx.experimental.dynamic_spec` for + full details. + + same_signature (bool): If True, rewrite the returned graph's signature to be the same as f. + + disable_constraint_solver (bool): Whether the dim constraint solver must be disabled. + + Returns: + A function that given args and kwargs, returns a tuple of (graph, guards) + Graph: An FX graph representing the execution of the input PyTorch function with the provided arguments and options. + Guards: The guards we accumulated during tracing f above + + Raises: + AssertionError: If decomposition_table is specified without setting aten_graph=True, + or if graph breaks during tracing in export. + + AssertionError: If Dynamo input and output is not consistent with traced input/output. + + Note - this headerdoc was authored by ChatGPT, with slight modifications by the author. + """ + if config.debug_force_graph_break_on_leaf_return: + raise unittest.SkipTest("Cannot force graph break on export") + + # `dynamic_shapes` is overloaded: it accepts the Dim-based dict/tuple/list + # spec, OR the new ShapesSpec/ParamsSpec API. If the latter is passed, we + # route it through dynamo's `dynamic_shapes` mechanism and skip the legacy + # constraint processing. + from torch.fx.experimental.dynamic_spec import ( + _SHAPES_SPEC_VS_DEFERRED_RUNTIME_ASSERTS_MSG, + ) + + dyn_spec: ShapesSpec | ParamsSpec | None = None + if isinstance(dynamic_shapes, (ShapesSpec, ParamsSpec)): + if constraints: + raise ValueError( + "`dynamic_shapes=ShapesSpec(...)` cannot be combined with " + "`constraints`. ShapesSpec controls dynamic behavior on its own." + ) + if prefer_deferred_runtime_asserts_over_guards: + raise ValueError(_SHAPES_SPEC_VS_DEFERRED_RUNTIME_ASSERTS_MSG) + # ParamsSpec is normalized to ShapesSpec downstream in OptimizeContext. + dyn_spec = dynamic_shapes + dynamic_shapes = None + + if _log_export_usage: + log_export_usage(event="export.private_api", flags={"_dynamo"}) + + # Deal with "local variable referenced before assignment" + _f = f + _specialize_float = specialize_float + _assume_static_by_default = assume_static_by_default + _constraints = constraints + + def inner(*args: Any, **kwargs: Any) -> ExportResult: + if not _constraints: + combined_args = _combine_args(_f, args, kwargs) + constraints = _process_dynamic_shapes(combined_args, dynamic_shapes) + else: + constraints = _constraints + + f = _f + specialize_float = _specialize_float + assume_static_by_default = _assume_static_by_default + check_if_dynamo_supported() + torch._C._log_api_usage_once("torch._dynamo.export") + if decomposition_table is not None: + if not aten_graph: + raise AssertionError( + "Specifying a decomposition_table table or tracing mode is illegal without setting aten_graph=True" + ) + if pre_dispatch: + if not aten_graph: + raise AssertionError( + "pre_dispatch=True can only be used when aten_graph=True" + ) + f = innermost_fn(f) + call_to_inspect = f.forward if isinstance(f, torch.nn.Module) else f + original_signature = inspect.signature(call_to_inspect) # type: ignore[arg-type] + graph = None + out_guards = None + graph_captured_input = None + graph_captured_result: tuple[torch.Tensor, ...] | None = None + fake_mode = None + result_traced = None + + def guard_export_print(guards: _guards.GuardsSet) -> None: + nonlocal out_guards + if out_guards is not None: + raise AssertionError( + "whole graph export entails exactly one guard export" + ) + out_guards = guards + + example_inputs: list[Any] = [] + + def dynamo_normalization_capturing_compiler( + gm: torch.fx.GraphModule, inner_example_inputs: list[Any] + ) -> Callable[..., Any]: + nonlocal graph + if graph is not None: + raise AssertionError( + "Tried to emit a second graph during export. Tracing through 'f' must produce a single graph." + ) + graph = gm + + nonlocal fake_mode, example_inputs + # NB: do NOT pass inner_example_inputs here, we are detecting the + # Dynamo allocated fake mode, which should be DISTINCT from a + # potential outer ambient fake mode which the user provided. + # example_inputs is always the user specified inputs, so they + # would have the wrong fake mode attached to them + fake_mode = _guards.detect_fake_mode() + example_inputs = inner_example_inputs + + def result_capturing_wrapper(*graph_inputs: Any) -> Any: + nonlocal graph_captured_result + nonlocal graph_captured_input + + graph_captured_input = graph_inputs + if graph is None: + raise AssertionError( + "graph must not be None in result_capturing_wrapper" + ) + + named_parameters = dict(graph.named_parameters(remove_duplicate=False)) + named_buffers = dict(graph.named_buffers(remove_duplicate=False)) + + ambient_fake_mode = ( + _guards.detect_fake_mode(graph_inputs) + if _guards.detect_fake_mode(graph_inputs) is not None + else fake_mode + ) + + # We reran fake tensor propagation, but we didn't do + # anything with the resulting unbacked SymInts. Drop them + # from the pending list. + # NB: this is wrong if graph_captured_result has + # data-dependent output size! + ignore_fresh_unbacked = null_context() + if ambient_fake_mode is None: + raise AssertionError("ambient_fake_mode must not be None") + if shape_env := ambient_fake_mode.shape_env: + ignore_fresh_unbacked = shape_env.ignore_fresh_unbacked_symbols() # type: ignore[assignment] + + with ( + ambient_fake_mode, + enable_python_dispatcher(), + ignore_fresh_unbacked, + ): + params_and_buffers = { + **named_parameters, + **named_buffers, + } + fake_params_buffers = {} + + for name, value in params_and_buffers.items(): + fake_params_buffers[name] = ambient_fake_mode.from_tensor( + value, static_shapes=True + ) + + from torch._export.non_strict_utils import ( + key_path_to_source, + KeyPath, + ) + + def fakify_with_ambient( + path: KeyPath, t: torch.Tensor | _IntWrapper | Any + ) -> Any: + if isinstance(t, torch.Tensor): + # pyrefly: ignore [missing-attribute] + return ambient_fake_mode.from_tensor(t, static_shapes=True) + elif isinstance(t, _IntWrapper): + if ( + t.dynamism is not None + and isinstance(t.dynamism, _DimHint) + and t.dynamism.type + in ( + _DimHintType.DYNAMIC, + _DimHintType.AUTO, + ) + ): # type: ignore[union-attr] + source = key_path_to_source(path) + symint = ambient_fake_mode.shape_env.create_unspecified_symint_and_symbol( # type: ignore[union-attr] + t.val, source, DimDynamic.DYNAMIC + ) + return symint + else: + return t.val + else: + return t + + fake_graph_inputs = pytree.tree_map_with_path( + fakify_with_ambient, graph_inputs + ) + graph_captured_result = torch.func.functional_call( + graph, + fake_params_buffers, # type: ignore[arg-type] + fake_graph_inputs, # type: ignore[arg-type] + ) + + return graph_captured_result + + return result_capturing_wrapper + + # Note: This is needed by rewrite_signature. We need to put it before + # optimize_assert since user program may mutate the inputs. + flat_args, in_spec = pytree.tree_flatten((args, kwargs)) + + remove_from_cache(f) + constraint_violation_error = None + if tracing_mode != "symbolic": + assume_static_by_default = True + with ( + config.patch( + specialize_int=True, + specialize_float=specialize_float, + assume_static_by_default=assume_static_by_default, + automatic_dynamic_shapes=False, + capture_dynamic_output_shape_ops=True, + capture_scalar_outputs=True, + constant_fold_autograd_profiler_enabled=True, + prefer_deferred_runtime_asserts_over_guards=prefer_deferred_runtime_asserts_over_guards, + # install_free_tensors ensures that params and buffers are still + # added as graph attributes, and makes Dynamo emits graphs that + # follow export pytree-able input requirements + install_free_tensors=config.install_free_tensors_for_export, + ), + _compiling_state_context(), + ): + opt_f = optimize_assert( + dynamo_normalization_capturing_compiler, + hooks=Hooks( + guard_export_fn=guard_export_print, + guard_fail_fn=None, + ), + export=True, + export_constraints=constraints, + dynamic_shapes=dyn_spec, + )(f) + # TODO(voz): We may have instances of `f` that mutate inputs, we should track sideeffects and reject. + try: + result_traced = opt_f(*args, **kwargs) + except ConstraintViolationError as e: + constraint_violation_error = e + remove_from_cache(f) + + if ( + not disable_constraint_solver + and (shape_env := getattr(fake_mode, "shape_env", None)) is not None + and (dim_constraints := shape_env.dim_constraints) is not None + and not isinstance( + call_to_inspect, (torch._ops.OpOverloadPacket, torch._ops.OpOverload) + ) + and not trace_rules.check(call_to_inspect) + ): + dim_constraints.solve() + + forced_specializations = dim_constraints.forced_specializations() + + msg = dim_constraints.prettify_results( + original_signature, + dynamic_shapes, + constraint_violation_error, + forced_specializations, + ) + if constraint_violation_error: + constraint_violation_error.args = ( + constraint_violation_error.args[0] + msg, + ) + else: + if forced_specializations: + constraint_violation_error = ConstraintViolationError(msg) + else: + log.info( + "Summary of dimension constraints:%s", + msg, + ) + + # Error if we have any constraints on static values + + for k in shape_env.var_to_range: + if isinstance(k, sympy.Integer): + constraint_violation_error = ConstraintViolationError( + f"{''.join(traceback.format_list(shape_env.var_to_stack[k]))}\n" + "It appears that you're trying to set a constraint on a " + f"value which we evaluated to have a static value of {k}. " + 'Set TORCH_LOGS="+export" for more information.' + ) + if constraint_violation_error: + raise constraint_violation_error + + if graph is None: + if not same_signature: + raise AssertionError( + "Failed to produce a graph during tracing as no tensor operations were found and same_signature is False." + ) + # If the module does not contain any tensor computation, we would create a graph with inputs and outputs. + # To be consistent with the graph traced by dynamo, `graph` will have only tensor inputs as placeholders + # and tensor outputs as output nodes. non-tensor inputs and outputs will be added when rewriting signature. + # We will also construct the `example_inputs`, `graph_captured_input`, and `graph_captured_result` corresponding + # to `graph`. + example_inputs = [] + graph_captured_input = () + graph_captured_result = () + fake_mode = torch._subclasses.FakeTensorMode( + shape_env=ShapeEnv(), export=True + ) + if out_guards is None: + out_guards = _guards.GuardsSet() + if out_guards is None: # suppress mypy error + raise AssertionError("out_guards must not be None") + parameter_names = list(original_signature.parameters.keys()) + fx_graph = torch.fx.Graph() + for i, name in enumerate(parameter_names): + if torch.is_tensor(flat_args[i]): + node = fx_graph.placeholder(name) + node.meta["val"] = fake_mode.from_tensor( + flat_args[i], static_shapes=True + ) + graph_captured_input = graph_captured_input + (flat_args[i],) + example_inputs.append(flat_args[i]) + fx_graph.output(graph_captured_result) + module = torch.nn.Module() + graph = torch.fx.GraphModule(module, fx_graph) + log.info( + "Failed to capture a graph during tracing as no tensor operations were found.:\n\n%s", + graph.print_readable(print_output=False, colored=True), + ) + else: + if out_guards is None: + raise AssertionError("Failed to produce guards during tracing") + if fake_mode is None: + raise AssertionError("fake_mode must not be None after tracing") + + log.info( + "Dynamo captured graph:\n\n%s", + graph.print_readable(print_output=False, colored=True), + ) + + # This check need to happened before aten_graph + # because placeholder's _source_node attribute is not preserved by make_fx + if same_signature: + check_signature_rewritable(graph) + + # NB: This is mostly hitting the cache; Dynamo already converted these + example_fake_inputs = [ + fake_mode.from_tensor(t) if isinstance(t, torch.Tensor) else t + for t in example_inputs + ] + + if aten_graph: + # Running graph with interpreter is needed for propagating the stack_trace + def graph_with_interpreter(*args: Any) -> Any: + with torch.fx.traceback.preserve_node_meta(): + return torch.fx.Interpreter(graph).run(*args) # type: ignore[arg-type] + + with unset_fake_temporarily(), enable_python_dispatcher(), fake_mode: + try: + graph = make_fx( + graph_with_interpreter, + decomposition_table=decomposition_table, + tracing_mode="real", + _allow_non_fake_inputs=True, + pre_dispatch=pre_dispatch, + _allow_fake_constant=False, + )(*example_fake_inputs) + except CondOpArgsMismatchError as e: + # Wrap the internal error to the user-facing error + raise UserError( # noqa: B904 + UserErrorType.DYNAMIC_CONTROL_FLOW, + str(e), + case_name="cond_operands", + ) + + if graph is None: + raise AssertionError("graph must not be None after tracing") + for node in graph.graph.find_nodes(op="get_attr"): + if isinstance(getattr(graph, node.target), torch.Tensor): # type: ignore[arg-type] + node.meta["val"] = fake_mode.from_tensor( + getattr(graph, node.target), # type: ignore[arg-type] + static_shapes=True, + ) + + if same_signature: + flat_args_dynamic_dims = [ + { + c.dim + for c in (constraints or ()) + if ( + c.t_id == id(x) + and not isinstance(c, _RelaxedConstraint) + and c.constraint_range.vr.lower != c.constraint_range.vr.upper + ) + } + for x in flat_args + ] + graph = rewrite_signature( + original_signature, + graph, + fake_mode, + flat_args, + in_spec, + example_fake_inputs, + graph_captured_input, # type: ignore[arg-type] + graph_captured_result, + result_traced, # type: ignore[possibly-undefined] + flat_args_dynamic_dims, + ) + return ExportResult(graph, out_guards) + + if extra_args or extra_kwargs: + warnings.warn( + "export(f, *args, **kwargs) is deprecated, use export(f)(*args, **kwargs) instead. " + "If you don't migrate, we may break your export call in the future if your user defined kwargs " + "conflict with future kwargs added to export(f).", + FutureWarning, + stacklevel=2, + ) + return inner(*extra_args, **extra_kwargs) # type: ignore[return-value] + else: + return inner + + +def optimize_assert(*args: Any, **kwargs: Any) -> OptimizeContext: + if "rebuild_ctx" in kwargs and kwargs["rebuild_ctx"] is not None: + # called from optimize + rebuild_ctx = kwargs["rebuild_ctx"] + del kwargs["rebuild_ctx"] + else: + + def rebuild_ctx() -> OptimizeContext: + return optimize_assert(*args, **kwargs) + + return _optimize_assert(rebuild_ctx, *args, **kwargs) + + +def _optimize_assert( + rebuild_ctx: Callable[[], OptimizeContext], + backend: str | Callable[..., Any] | None, + *, + hooks: Hooks = Hooks(None, None, None), + export: bool = False, + export_constraints: Any | None = None, + dynamic: bool | None = None, + package: CompilePackage | None = None, + recompile_limit: int | None = None, + isolate_recompiles: bool = False, + dynamic_shapes: ShapesSpec | ParamsSpec | dict[str, Any] | None = None, +) -> OptimizeContext: + """ + Guarantees single-graph capture. + The same as `torch._dynamo.optimize(backend)` but ignores + symbolic_convert.error_on_graph_break setting. + + Used for fullgraph=True and export, since we must always error on graph breaks and ignore + symbolic_convert.error_on_graph_break. Can also be used for testing. + """ + backend = get_compiler_fn(backend) + + # Find if backend has any extra context manager + backend_ctx_ctor = getattr(backend, "backend_ctx_ctor", null_context) + + if config.caching_precompile and package is None: + # Create an uninitialized package that will be set/filled by + # _OptimizeContext.__call__ + # We need to instantiate the object here because the same CompilePackage + # needs to be shared between convert_frame_assert + # and OptimizeContext. + from .package import CompilePackage + + package = CompilePackage(fn=None, dynamo=None, ignore_inlined_sources=False) + + return _optimize_catch_errors( + convert_frame.convert_frame_assert( + backend, + export=export, + export_constraints=export_constraints, + package=package, + recompile_limit=recompile_limit, + ), + hooks, + backend_ctx_ctor, + fullgraph=True, + export=export, + dynamic=dynamic, + rebuild_ctx=rebuild_ctx, + package=package, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + +class TorchPatcher: + @staticmethod + @functools.cache + def patch() -> None: + # A better way to disable the following would be decorate the source + # functions with @torch._disable_dynamo. However, this causes issues + # with torch.deploy internally. + from .decorators import disable + + torch.jit.trace = disable( + torch.jit.trace, reason="tracing into TorchScript not fully supported" + ) + torch.jit.trace_module = disable( + torch.jit.trace_module, + reason="tracing into TorchScript not fully supported", + ) + torch.jit._get_trace_graph = disable( + torch.jit._get_trace_graph, + reason="tracing into TorchScript not fully supported", + ) + torch.fx._symbolic_trace.Tracer.trace = disable( + torch.fx._symbolic_trace.Tracer.trace, + reason="tracing into FX not fully supported", + ) + torch.distributions.Distribution.set_default_validate_args(False) + + from torch.optim import ( + adadelta, + adagrad, + adam, + adamax, + adamw, + asgd, + lbfgs, + nadam, + radam, + rmsprop, + rprop, + sgd, + sparse_adam, + ) + + optimizer_modules = { + adadelta, + adagrad, + adam, + adamax, + adamw, + asgd, + lbfgs, + nadam, + radam, + rmsprop, + rprop, + sgd, + sparse_adam, + } + + for opt_mod in optimizer_modules: + opt_name = opt_mod.__name__.split(".")[-1] + fused_fn_name = f"_fused_{opt_name}" + + if hasattr(opt_mod, fused_fn_name): + setattr( + opt_mod, + fused_fn_name, + disable( + getattr(opt_mod, fused_fn_name), + reason="don't trace into fused optimizer", + ), + ) + + optimizer_classes = [ + opt + for opt in torch.optim.__dict__.values() + if inspect.isclass(opt) and issubclass(opt, torch.optim.Optimizer) + ] + + # Note: we don't support sparsity or tracing through backwards + excluded_optimizer_classes = { + torch.optim.SparseAdam, + torch.optim.LBFGS, + } + + for opt in optimizer_classes: + if opt in excluded_optimizer_classes: + opt.step = disable( + opt.step, reason=f"optimizer {opt} step not supported" + ) + + if hasattr(opt, "_init_group"): + opt._init_group = disable( + opt._init_group, reason=f"optimizer {opt} _init_group not supported" + ) + + @staticmethod + def suppress_torch_distributed_warnings( + fn: Callable[..., Any], + ) -> Callable[..., Any]: + def inner_fn(*args: Any, **kwargs: Any) -> Any: + with torch._logging.hide_warnings( + torch._logging._internal.user_warning_filter + ): + return fn(*args, **kwargs) + + return inner_fn + + +def skip_code(code: types.CodeType) -> None: + set_code_exec_strategy( + code, FrameExecStrategy(FrameAction.SKIP, FrameAction.DEFAULT) + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/exc.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/exc.py new file mode 100644 index 0000000000000000000000000000000000000000..0f7cbec1ca41eb96da0baac1489750227cc82675 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/exc.py @@ -0,0 +1,1050 @@ +from __future__ import annotations + + +"""Exception handling and error reporting for TorchDynamo. + +This module provides a comprehensive set of exception classes and utilities for error +handling in TorchDynamo. It includes: + +Base Exceptions: + - TorchDynamoException: Base class for all TorchDynamo-specific exceptions + - Various specialized subclasses for different error scenarios + +User Error Handling: + - UserError: Exceptions for user-facing errors in TorchDynamo usage + - UserErrorType: Enumeration of different categories of user errors + - Formatted error messages with debugging information + +Observed Exceptions: + - Classes for handling exceptions observed during tracing + - Special handling for StopIteration, LookupError, etc. + - Exception state management during compilation + + When an exception is raised inside a ``torch.compile`` region, + TorchDynamo does **not** immediately propagate it to the caller. + Instead, Dynamo symbolically traces the exception so that + ``try``/``except`` blocks inside the compiled function can be + captured in the FX graph and reasoned about statically. + + Common Python exception types are wrapped in ``ObservedException`` + subclasses (e.g. ``StopIteration`` → ``ObservedUserStopIteration``, + ``KeyError`` → ``ObservedKeyError``). The full mapping is defined in + ``observed_exception_map``. For exception types not present in that + map, :func:`get_dynamo_observed_exception` creates a new + ``ObservedException`` subclass dynamically at tracing time. + + If an observed exception is **not caught** inside the compiled region + it propagates out and is re-raised as the original exception type in + eager mode, preserving the original traceback for the user. + + .. note:: + This behaviour means that exception-based control flow (e.g. + ``StopIteration`` from a custom iterator, ``KeyError`` from a + dict access) is generally supported inside ``torch.compile`` + regions. However, raising or catching exceptions that depend on + *data-dependent* conditions may still cause a graph break because + Dynamo cannot statically determine which branch will be taken at + compile time. + +Error Formatting: + - Stack trace filtering and formatting + - Error message augmentation + - Debugging utilities for error reporting +""" + +import json +import logging +import re +import sys +import textwrap +import types +import typing +from enum import auto, Enum +from functools import lru_cache +from pathlib import Path +from traceback import format_exc, format_list, FrameSummary, StackSummary +from typing import Any, NoReturn, TYPE_CHECKING + +import torch._guards +from torch._utils_internal import get_file_path_2 + +from . import config +from .utils import counters + + +if TYPE_CHECKING: + from torch._dynamo.variables import VariableTracker + from torch._guards import CompileId + + from .output_graph import DynamoTracerOutput + from .symbolic_convert import InstructionTranslatorBase + from .types import DynamoFrameType, FrameExecStrategy + + +def exportdb_error_message(case_name: str) -> str: + return ( + "For more information about this error, see: " + + "https://pytorch.org/docs/main/generated/exportdb/index.html#" + + case_name.replace("_", "-") + ) + + +log = logging.getLogger(__name__) +graph_breaks_log = torch._logging.getArtifactLogger(__name__, "graph_breaks") + + +_EXCEPTION_STATE_ATTRS_TO_DROP = frozenset( + ( + "_torch_dynamo_tracer_output", + "first_useful_frame", + "frame_exec_strategy", + ) +) + + +def _safe_exception_args(args: tuple[Any, ...]) -> tuple[Any, ...]: + return args + + +class _SerializedException(RuntimeError): + _dynamo_original_exception_type: str + + def __init__(self, exc: BaseException) -> None: + super().__init__(str(exc)) + self._dynamo_original_exception_type = ( + f"{type(exc).__module__}.{type(exc).__qualname__}" + ) + + +def _safe_inner_exception(exc: BaseException) -> _SerializedException: + return _SerializedException(exc) + + +def _safe_exception_state(state: dict[str, Any]) -> dict[str, Any]: + result: dict[str, Any] = {} + for name, value in state.items(): + if name in _EXCEPTION_STATE_ATTRS_TO_DROP or isinstance(value, types.FrameType): + result[name] = None + elif name == "inner_exception" and isinstance(value, BaseException): + result[name] = _safe_inner_exception(value) + else: + result[name] = value + return result + + +def _reconstruct_torch_dynamo_exception( + exc_type: type[TorchDynamoException], args: tuple[Any, ...] +) -> TorchDynamoException: + exc = exc_type.__new__(exc_type) + BaseException.__init__(exc, *args) + return exc + + +class TorchDynamoException(RuntimeError): + """Base exception class for all TorchDynamo-specific exceptions. + + Attributes: + _torch_dynamo_tracer_output: Optional tracer output attached to the exception + frame_exec_strategy: Optional frame execution strategy to control how convert_frame + should handle this exception. When set, convert_frame will use this strategy + instead of the default behavior. This allows exceptions to signal specific + execution strategies (e.g., SKIP, RUN_ONLY) without requiring separate + exception types for control flow. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._torch_dynamo_tracer_output: DynamoTracerOutput | None = None + self.frame_exec_strategy: FrameExecStrategy | None = None + + def __reduce__(self) -> tuple[Any, ...]: + return ( + _reconstruct_torch_dynamo_exception, + (type(self), _safe_exception_args(self.args)), + self.__getstate__(), + ) + + def __getstate__(self) -> dict[str, Any]: + return _safe_exception_state(self.__dict__) + + def __setstate__(self, state: dict[str, Any] | None, /) -> None: + if state is not None: + self.__dict__.update(state) + + +class InternalTorchDynamoError(TorchDynamoException): + pass + + +class ResumePrologueTracingError(TorchDynamoException): + pass + + +class RestartAnalysis(TorchDynamoException): + restart_reason: str | None + + def __init__(self, *args: Any, restart_reason: str | None = None) -> None: + self.restart_reason = restart_reason + super().__init__(*args) + + +class SpeculationRestartAnalysis(RestartAnalysis): + pass + + +class AutogradGradRestartAnalysis(RestartAnalysis): + """Raised when autograd.grad consumed grad_fns that are returned. + + On restart, autograd.grad will graph break instead of being traced. + """ + + +class RequiresGradRestartAnalysis(RestartAnalysis): + """Raised when a source-less requires_grad_() intermediate leaks as output. + + On restart, requires_grad_() will graph break instead of being traced, + preserving partial acceleration for code before the call. + """ + + +class UnspecializeRestartAnalysis(RestartAnalysis): + pass + + +class CompileCollectiveRestartAnalysis(RestartAnalysis): + pass + + +class TensorifyScalarRestartAnalysis(RestartAnalysis): + pass + + +# Used (primarily for backends) to skip tracing the current frame +# and all future invocations of it. +# NOTE: this does NOT cause a graph break, and thus no graph break messages +# will be issued! +class SkipFrame(TorchDynamoException): + pass + + +class TorchRuntimeError(TorchDynamoException): + def __init__(self, msg: str, real_stack: StackSummary | None = None) -> None: + super().__init__(msg) + self.msg = msg + self.real_stack = ( + real_stack + if real_stack is not None + else torch._guards.TracingContext.extract_stack() + ) + + +class InvalidBackend(TorchDynamoException): + def __init__(self, name: str, suggestions: list[str] | None = None) -> None: + msg = f"Invalid backend: {name!r}" + msg += ( + f", did you mean: {', '.join(map(repr, suggestions))}?" + if suggestions + else "." + ) + msg += " See `torch._dynamo.list_backends()` for available backends." + super().__init__(msg) + + +class ResetRequired(TorchDynamoException): + def __init__(self) -> None: + super().__init__( + textwrap.dedent( + """ + Must call `torch._dynamo.reset()` before changing backends. Detected two calls to + `torch.compile()` with a different backend compiler arguments. + """ + ) + ) + + +class ShortenTraceback(TorchDynamoException): + def __init__( + self, *args: Any, first_useful_frame: types.FrameType | None, **kwargs: Any + ) -> None: + super().__init__(*args, **kwargs) + self.first_useful_frame = first_useful_frame + + def remove_dynamo_frames(self) -> typing.Self: + tb = self.__traceback__ + if self.first_useful_frame is None or tb is None or config.verbose: + return self + while tb.tb_frame is not self.first_useful_frame: + tb = tb.tb_next + if tb is None: + raise AssertionError("internal error, please report a bug") + return self.with_traceback(tb) + + +class BackendCompilerFailed(ShortenTraceback): + def __init__( + self, + backend_fn: Any, + inner_exception: Exception, + first_useful_frame: types.FrameType | None, + ) -> None: + self.backend_name = getattr(backend_fn, "__name__", "?") + self.inner_exception = inner_exception + msg = f"backend={self.backend_name!r} raised:\n{type(inner_exception).__name__}: {inner_exception}" + super().__init__(msg, first_useful_frame=first_useful_frame) + + +# NOTE: important invariant! Almost any exception handler that handles Unsupported +# should NOT suppress the exception if skip_frame is set! +# skip_frame is used by symbolic_convert.py to bubble up Unsupported exceptions to convert_frame to cause +# a frame skip. Once the Unsupported exn is in convert_frame, we will always skip, so skip_frame +# won't be checked +class Unsupported(TorchDynamoException): + def __init__( + self, + msg: str, + # TODO: make this argument required once we remove Unsupported subclasses + gb_type: str = "", + skip_frame: bool = False, + *, + case_name: str | None = None, + real_stack: StackSummary | None = None, + ) -> None: + super().__init__(msg) + if not real_stack: + real_stack = torch._guards.TracingContext.extract_stack() + self.real_stack = real_stack + self.msg = msg + self.skip_frame = skip_frame + self.category: str | None = None + self.add_to_stats() + self.gb_type: str | None = gb_type + self.logged = False + + def remove_from_stats(self) -> None: + if self.category is None: + raise AssertionError("category must be set before removing from stats") + counters[self.category][self.msg] -= 1 + if counters[self.category][self.msg] <= 0: + del counters[self.category][self.msg] + + def add_to_stats(self, category: str = "unimplemented") -> None: + self.category = category + counters[category][self.msg] += 1 + + +class UnknownPropertiesDuringBackwardTrace(TorchDynamoException): + pass + + +class RecompileError(TorchDynamoException): + pass + + +class InfiniteGeneratorError(TorchDynamoException): + # Raised when the number of yielded values is greater than MAX_ITERATOR_LIMIT + pass + + +class CondOpArgsMismatchError(TorchDynamoException): + """ + Internal error from cond() due to arguments mismatch. + """ + + +class UserErrorType(Enum): + DYNAMIC_CONTROL_FLOW = auto() + ANTI_PATTERN = auto() + STANDARD_LIBRARY = auto() + CONSTRAINT_VIOLATION = auto() + DYNAMIC_DIM = auto() + INVALID_INPUT = auto() + INVALID_OUTPUT = auto() + UNSUPPORTED_ALIASED_MUTATED_DYNAMIC_INPUTS = auto() + + +class UserError(TorchDynamoException): + def __init__( + self, error_type: UserErrorType, msg: str, case_name: str | None = None + ) -> None: + """ + Type of errors that would be valid in Eager, but not supported in TorchDynamo. + The error message should tell user about next actions. + + error_type: Type of user error + msg: Actionable error message + case_name: (Optional) Unique name (snake case) for the usage example in exportdb. + """ + if case_name is not None: + if not isinstance(case_name, str): + raise AssertionError(f"case_name must be a str, got {type(case_name)}") + if msg.endswith("."): + msg += " " + else: + msg += "\n" + msg += exportdb_error_message(case_name) + super().__init__(msg) + self.real_stack = torch._guards.TracingContext.extract_stack() + self.skip_frame = False + self.logged = False + self.error_type = error_type + self.msg = msg + self.message = msg + + +# debug exception thrown when tracing torch._dynamo.step_unsupported() +class StepUnsupported(TorchDynamoException): + def __init__(self, msg: str, real_stack: StackSummary | None = None) -> None: + super().__init__(msg) + self.msg = msg + if not real_stack: + real_stack = torch._guards.TracingContext.extract_stack() + self.real_stack = real_stack + self.logged = False + + +class UnsafeScriptObjectError(TorchDynamoException): + pass + + +class UncapturedHigherOrderOpError(TorchDynamoException): + def __init__(self, msg: str, real_stack: StackSummary | None = None) -> None: + super().__init__(msg) + self.msg = msg + self.real_stack = ( + real_stack + if real_stack is not None + else torch._guards.TracingContext.extract_stack() + ) + + +# TODO: I'm a little uncertain about what error classification we should have +# for this. This is potentially a user error, but regressions in +# specialization in PyTorch proper could also trigger this problem +class FailOnRecompileLimitHit(Exception): + pass + + +class PackageError(TorchDynamoException): + pass + + +class ObservedException(TorchDynamoException): + # An exception observed during the tracing. This exception is used by Dynamo to handle exceptions. + def __init__( + self, *args: Any, real_stack: StackSummary | None = None, **kwargs: Any + ) -> None: + super().__init__(*args, **kwargs) + self.real_stack: StackSummary = ( + real_stack + if real_stack is not None + else torch._guards.TracingContext.extract_stack() + ) + + +class ObservedUserStopIteration(ObservedException): + # An UserStopIteration exception observed during the Dynamo tracing (e.g Dynamo tracing __next__) + value: Any | None + + # Reference `StopIteration_init` in CPython + # https://github.com/python/cpython/blob/3.11/Objects/exceptions.c#L568-L584 + def __init__( + self, *args: Any, real_stack: StackSummary | None = None, **kwargs: Any + ) -> None: + super().__init__("unhandled `raise StopIteration`", real_stack=real_stack) + if len(args) > 0: + self.value = args[0] + else: + self.value = None + + +class ObservedLookupError(ObservedException): + # A LookupError exception to be raised from inside Dynamo tracing. This can happen on __getitem__ + pass + + +class ObservedIndexError(ObservedLookupError): + # An IndexError exception to be raised from inside Dynamo tracing. This can happen on list __getitem__ + pass + + +class ObservedKeyError(ObservedLookupError): + # A KeyError exception to be raised from inside Dynamo tracing. This can happen on dict __getitem__ + pass + + +class ObservedGeneratorExit(ObservedException): + pass + + +class ObservedAttributeError(ObservedException): + # An AttributeError exception to be raised from inside Dynamo tracing. This can happen on user defined object __getattr__ + pass + + +class ObservedRuntimeError(ObservedException): + # A RuntimeError exception to be raised from inside Dynamo tracing. This can happen on generator.throw(..) method + pass + + +class ObservedNotImplementedError(ObservedException): + pass + + +class ObservedTypeError(ObservedException): + # A TypeError exception to be raised from inside Dynamo tracing. This can happen on generator.send(..) method + pass + + +class FakeTensorObservedException(ObservedException): + pass + + +observed_exception_map = { + StopIteration: ObservedUserStopIteration, + LookupError: ObservedLookupError, + IndexError: ObservedIndexError, + GeneratorExit: ObservedGeneratorExit, + KeyError: ObservedKeyError, + AttributeError: ObservedAttributeError, + RuntimeError: ObservedRuntimeError, + NotImplementedError: ObservedNotImplementedError, + TypeError: ObservedTypeError, +} + + +class UnhandledDescriptorError(NotImplementedError): + """Raised by object_generic_getattr when a descriptor type is not + recognized by _resolve_descriptor_get. Subclasses NotImplementedError + so callers that catch NotImplementedError (e.g., generic_getattr's + graph-break fallback) still work, but callers that want to + distinguish unhandled descriptors from other NotImplementedErrors can + catch this specifically. + """ + + +class TritonUnavailableError(RuntimeError): + """ + Raised by DeviceInterface.raise_if_triton_unavailable to signal that a + device cannot run Triton (e.g. no Triton backend was built for it). + + Subclasses RuntimeError so existing callers that catch RuntimeError keep + working, while callers that only want to react to Triton unavailability - + such as has_triton() - can catch this specific type instead of swallowing + every RuntimeError, which would hide unrelated bugs. + """ + + +def get_dynamo_observed_exception(exc_type: type[Exception]) -> type[ObservedException]: + if exc_type not in observed_exception_map: + name = getattr(exc_type, "__name__", str(exc_type)) + observed_exception_map[exc_type] = type( # type: ignore[assignment] + f"Observed{name}Error", (ObservedException,), {} + ) + # pyrefly: ignore [bad-index] + return observed_exception_map[exc_type] + + +def raise_observed_exception( + exc_type: type[Exception], + tx: InstructionTranslatorBase, + *, + args: list[VariableTracker] | list[str] | None = None, + kwargs: dict[str, VariableTracker] | None = None, +) -> NoReturn: + from .variables.builder import SourcelessBuilder + + if args: + args_ = [ + SourcelessBuilder.create(tx, arg) if isinstance(arg, str) else arg + for arg in args + ] + else: + args_: list[VariableTracker] = [] + + # CPython here raises an exception. Since there is no python code, we have to manually setup the exception + # stack and raise the exception. + exception_vt = SourcelessBuilder.create(tx, exc_type).call_function( + tx, args_, kwargs or {} + ) + tx.do_raise(exception_vt, None) + + +def raise_type_error(tx: InstructionTranslatorBase, msg: str) -> NoReturn: + """Raise a TypeError as an observed exception during tracing.""" + raise_observed_exception(TypeError, tx, args=[msg]) + + +def raise_value_error(tx: InstructionTranslatorBase, msg: str) -> NoReturn: + """Raise a ValueError as an observed exception during tracing.""" + raise_observed_exception(ValueError, tx, args=[msg]) + + +def handle_observed_exception(tx: Any) -> None: + # This is essentially exception handling code, equivalent of this pseudo code + # + # try: + # ... somebody raising StopIteration + # except StopIteration + # pass + # + # If this was going through the python code, we would have called exception_handler method, but FOR_ITER + # handles the exception completely in CPython. For example for 3.11, the resulting bytecode is + # + # + # 6 46 LOAD_GLOBAL 2 (StopIteration) + # 58 RAISE_VARARGS 1 + # >> 60 PUSH_EXC_INFO + + # 7 62 LOAD_GLOBAL 2 (StopIteration) + # 74 CHECK_EXC_MATCH + # 76 POP_JUMP_FORWARD_IF_FALSE 3 (to 84) + # 78 POP_TOP + + # 8 80 POP_EXCEPT + # + + # Fortunately this translates to a simple pop from the exn_vt_stack + tx.exn_vt_stack.clear_current_exception() + + +# These exceptions are ok to fallback to eager/graph_break. +exceptions_allowed_to_be_fallback = ( + torch._subclasses.fake_tensor.DataDependentOutputException, + torch._subclasses.fake_tensor.DynamicOutputShapeException, + torch._subclasses.fake_tensor.UnsupportedOperatorException, + torch._subclasses.fake_tensor.UnsupportedFakeTensorException, + torch._subclasses.fake_tensor.UnsupportedMutationAliasingException, +) + + +def unimplemented_with_warning( + e: Exception, + code: types.CodeType, + *, + gb_type: str, + context: str, + explanation: str, + hints: list[str], +) -> NoReturn: + # This function calls unimplemented internally and eventually graph breaks + # or falls to eager. unimplemented itself does not print any user warnings, + # i.e., its very silent. This helper function is intended when an error is + # encountered in the torch.compile stack which is worth showing as warning + # to the user. For example, if AOT Autograd backend fails with a fake tensor + # exception, its ok to fallback to eager but not silently. Here, we can use + # this function to log the message and the stack trace. + graph_break_msg = format_error_msg_verbose(e, code) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_graph_break_reason", + "encoding": "string", + }, + payload_fn=lambda: graph_break_msg, + ) + graph_breaks_log.debug("%s", graph_break_msg) + _unimplemented = unimplemented + # to prevent a graph break registry entry + _unimplemented( + gb_type=gb_type, + context=context, + explanation=explanation, + hints=hints, + from_exc=e, + log_warning=True, + ) + + +def format_graph_break_message( + gb_type: str, + context: str, + explanation: str, + hints: list[str], +) -> str: + explanation = textwrap.indent(explanation, " ").lstrip() + hints_str = "\n".join( + " Hint: " + textwrap.indent(hint, " ").lstrip() for hint in hints + ) + context = textwrap.indent(context, " ").lstrip() + + msg = f"""\ +{gb_type} + Explanation: {explanation} +{hints_str} + + Developer debug context: {context}""" + documentation_link = get_gbid_documentation_link(gb_type) + + if documentation_link: + msg += f"\n\n For more details about this graph break, please visit: {documentation_link}" + + return msg + + +@lru_cache(maxsize=1) +def _load_gb_type_to_gb_id_map() -> dict[str, Any]: + """ + Loads the gb_type to gb_id map from the graph break registry from JSON file with caching. + + Includes historical gb_type (mapping behavior of duplicate gb_types with different gb_ids is undefined). + """ + try: + script_dir = Path(__file__).resolve().parent + registry_path = get_file_path_2( + "", str(script_dir), "graph_break_registry.json" + ) + with open(registry_path) as f: + registry = json.load(f) + except Exception: + log.exception("Error accessing the registry file") + # pyrefly: ignore [implicit-any] + registry = {} + + mapping = {} + for k, v in registry.items(): + for entry in v: + mapping[entry["Gb_type"]] = k + + return mapping + + +def get_gbid_documentation_link(gb_type: str) -> str | None: + """ + Retrieves the GBID documentation link for a given graph break type. + + Args: + gb_type: The graph break type to look up. + + Returns: + A string containing the documentation URL if found, otherwise None. + """ + GRAPH_BREAK_SITE_URL = ( + "https://meta-pytorch.github.io/compile-graph-break-site/gb/" # @lint-ignore + ) + + gb_type_to_gb_id_map = _load_gb_type_to_gb_id_map() + + if gb_type in gb_type_to_gb_id_map: + return ( + f"{GRAPH_BREAK_SITE_URL}gb{gb_type_to_gb_id_map[gb_type].lstrip('GB')}.html" + ) + + return None + + +_NOTHING = object() + + +def unimplemented( + *, + gb_type: str, + context: str, + explanation: str, + hints: list[str], + from_exc: Any = _NOTHING, + log_warning: bool = False, + skip_frame: bool = False, +) -> NoReturn: + """ + Called within dynamo to cause a graph break. + Args: + gb_type: Context-free graph break type. It should be a short string without any + information specific to the tracing context (i.e. no dynamically-generated strings) + context: Developer context for the graph break. It can contain tracing context/dynamic strings. + explanation: User-facing context-dependent explanation for the graph break. Can be dynamic. + hints: List of user-facing hints for the graph break. + """ + + msg = format_graph_break_message(gb_type, context, explanation, hints) + + if log_warning: + log.warning(msg) + if from_exc is not _NOTHING: + past_real_stack = None + if hasattr(from_exc, "real_stack"): + past_real_stack = from_exc.real_stack + if isinstance(from_exc, Unsupported): + msg = f"{from_exc.msg}\n\n*** While handling this graph break, another graph break occurred: ***\n\n{msg}" + # noqa: GB_REGISTRY + raise Unsupported(msg, gb_type, skip_frame, real_stack=past_real_stack) + # noqa: GB_REGISTRY + raise Unsupported( + msg, gb_type, skip_frame, real_stack=past_real_stack + ) from from_exc + # noqa: GB_REGISTRY + raise Unsupported(msg, gb_type, skip_frame) + + +# KeyError has special handling for its args +# see https://github.com/python/cpython/blob/3.11/Objects/exceptions.c#L2534 for details +class KeyErrorMsg: + def __init__(self, value: Any) -> None: + self.value = value + + def __str__(self) -> str: + return str(self.value) + + def __repr__(self) -> str: + return self.__str__() + + +def augment_exc_message_with_hop_name(exc: Exception, msg: str) -> str: + # Add HOP context right after before the explanation if present; + # otherwise after the message + if hasattr(exc, "_hop_name"): + lines = msg.partition("\n Explanation:") + msg = ( + f"{lines[0]}\n Higher Order Operator: {exc._hop_name}{lines[1]}{lines[2]}" # type: ignore[attr-defined] + ) + + return msg + + +def augment_exc_message(exc: Exception, msg: str = "\n", export: bool = False) -> None: + import traceback + + exc.innermost_user_frame_summary = None # type: ignore[attr-defined] + + real_stack = get_real_stack(exc) + if real_stack is not None and len(real_stack) > 0: + exc.innermost_user_frame_summary = real_stack[-1] # type: ignore[attr-defined] + msg += f"\nfrom user code:\n {''.join(traceback.format_list(real_stack))}" + + if config.replay_record_enabled and hasattr(exc, "record_filename"): + msg += ( + f"\nLast frame execution written to {exc.record_filename}. To run only this frame while debugging, run\ + torch._dynamo.replay('{exc.record_filename}').\n" + ) + + if not config.verbose and hasattr(exc, "real_stack"): + msg += ( + "\nSet TORCHDYNAMO_VERBOSE=1 for the internal stack trace " + "(please do this especially if you're reporting a bug to PyTorch). " + 'For even more developer context, set TORCH_LOGS="+dynamo"\n' + ) + + if hasattr(exc, "inner_exception") and hasattr( + exc.inner_exception, "minifier_path" + ): + if hasattr(exc.inner_exception, "buck_command"): + msg += ( + f"\nMinifier script written to {exc.inner_exception.minifier_path}. Run " + f"this buck command to find the smallest traced graph " + f"which reproduces this error: {exc.inner_exception.buck_command}\n" + ) + else: + msg += ( + f"\nMinifier script written to {exc.inner_exception.minifier_path}. Run " + "this script to find the smallest traced graph which reproduces this error.\n" + ) + + old_msg = "" if len(exc.args) == 0 else str(exc.args[0]) + + old_msg = augment_exc_message_with_hop_name(exc, old_msg) + + if isinstance(exc, KeyError): + exc.args = (KeyErrorMsg(old_msg + msg),) + exc.args[1:] + else: + new_msg = old_msg + msg + exc.args = (new_msg,) + exc.args[1:] + + +def get_exc_message( + e: Exception, compile_id: CompileId +) -> tuple[str | None, int | None]: + filename = None + lineno = None + if e.innermost_user_frame_summary is not None: # type: ignore[attr-defined] + filename = e.innermost_user_frame_summary.filename # type: ignore[attr-defined] + lineno = e.innermost_user_frame_summary.lineno # type: ignore[attr-defined] + e.compile_id = compile_id # type: ignore[attr-defined] + return filename, lineno + + +def _extract_stack_with_positions() -> StackSummary: + # traceback.extract_stack() does not populate colno/end_colno on + # FrameSummary, even though the data is available on live frames via + # f_lasti + co_positions(). This means traceback.format_list() never + # renders caret annotations for stacks captured this way. We do it + # manually here so that "stack above dynamo" frames get carets. + stack = StackSummary() + frame = sys._getframe(1) + while frame is not None: + code = frame.f_code + # colno/end_colno kwargs were added to FrameSummary in 3.11 + kwargs: dict[str, Any] = {} + if sys.version_info >= (3, 11) and frame.f_lasti >= 0: + positions = list(code.co_positions()) + idx = frame.f_lasti // 2 + if idx < len(positions): + _, _, kwargs["colno"], kwargs["end_colno"] = positions[idx] + stack.append( + FrameSummary( + code.co_filename, + frame.f_lineno, + code.co_name, + lookup_line=False, + **kwargs, + ) + ) + frame = frame.f_back + stack.reverse() + return stack + + +def get_stack_above_dynamo() -> StackSummary: + return filter_stack(_extract_stack_with_positions()) + + +def get_real_stack( + exc: Exception, frame: DynamoFrameType | None = None +) -> StackSummary | None: + real_stack = getattr(exc, "real_stack", None) + if real_stack is None: + return None + + # NB: it's possible for real_stack to be []; we still attempt to + # report a stack anyway because the stack_above_dynamo may still + # be useful for debugging + + if frame is not None: + # NB: frame is PyInterpreterFrame on Python 3.11 and later, + # not a TRUE frame object. You can't actually feed it + # to traceback because it doesn't have enough information. + # To solve this problem, we technically should just materialize + # the frame, the same way _PyFrame_GetFrameObject would do + # (but we cannot actually do this, because this populates + # frame_obj field, which default eval frame doesn't like). + # + # Fortunately, in this case, we can hack it: there's no need + # to actually use the truly top frame, we can just extract + # from where we are right now and rely on filter_stack to + # get rid of all the dynamo frames. For ease of testing + # we apply this behavior to ALL Python versions + stack_above_dynamo = get_stack_above_dynamo() + else: + stack_above_dynamo = StackSummary() + + return StackSummary.from_list(stack_above_dynamo + real_stack) + + +# filter out all frames after entering dynamo +def filter_stack(stack: StackSummary) -> StackSummary: + user_stack = StackSummary() + for frame in stack: + if frame.filename is None: + continue + if "convert_frame" in frame.filename: + break + if "eval_frame" in frame.filename or ( + frame.line and "torch._dynamo.optimize(" in frame.line + ): + continue + user_stack.append(frame) + + return user_stack + + +def remove_resume_prefix(name: str) -> str: + from .resume_execution import TORCH_DYNAMO_RESUME_IN_PREFIX + + match = re.match(f"{TORCH_DYNAMO_RESUME_IN_PREFIX}_(\\w+)_at_\\d+", name) + if match: + return match.group(1) + return name + + +def collapse_resume_frames(stack: StackSummary | list[FrameSummary]) -> StackSummary: + """ + When we graph break, we create a resume function and make a regular Python call + to it, which gets intercepted by Dynamo. This behavior is normally shown in the + traceback, which can be confusing to a user. So we can filter out resume frames + for better traceback clarity. + + Example: + File "..." line 3, in f + + File "..." line 5, in torch_dynamo_resume_in_f_at_80 + + File "..." line 10, in torch_dynamo_resume_in_f_at_120 + + + becomes + File "..." line 10, in f + + """ + + new_stack = StackSummary() + for frame in stack: + if frame.filename is None: + continue + name = remove_resume_prefix(frame.name) + if new_stack and name and new_stack[-1].name == name: + new_stack[-1] = frame + frame.name = name + else: + frame.name = name + new_stack.append(frame) + + return new_stack + + +def format_error_msg_verbose( + exc: Exception, + code: types.CodeType, + record_filename: str | None = None, + frame: DynamoFrameType | None = None, +) -> str: + msg = ( + f"WON'T CONVERT {code.co_name} {code.co_filename} line {code.co_firstlineno}\n" + ) + msg += "=" * 10 + " TorchDynamo Stack Trace " + "=" * 10 + "\n" + msg += format_exc() + real_stack = get_real_stack(exc, frame) + if real_stack is not None: + msg += ( + "\n" + + "=" * 10 + + " The above exception occurred while processing the following code " + + "=" * 10 + + "\n\n" + ) + msg += "".join(format_list(real_stack)) + msg += "\n" + msg += "=" * 10 + + return msg + + +def format_frame_info(code: types.CodeType) -> str: + return ( + f"{getattr(code, 'co_name', '')} " + f"({getattr(code, 'co_filename', '')} " + f"line {getattr(code, 'co_firstlineno', 0)})" + ) + + +def format_skip_frame_message(code: types.CodeType | None, reason: str) -> str: + if code is not None: + frame_info = format_frame_info(code) + return ( + f"torch.compile intentionally decided to skip the frame {frame_info} and fall back to eager.\n" + f"Reason: {reason}" + ) + else: + return ( + f"torch.compile intentionally decided to skip the frame and fall back to eager.\n" + f"Reason: {reason}" + ) + + +def format_error_msg( + exc: Exception, + code: types.CodeType, + record_filename: str | None = None, + frame: DynamoFrameType | None = None, +) -> str: + if config.verbose: + return format_error_msg_verbose(exc, code, record_filename, frame) + return f"WON'T CONVERT {code.co_name} {code.co_filename}\ + line {code.co_firstlineno} \ndue to: \n{format_exc()}" diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/external_utils.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/external_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c054a6e0488280b599dd21c09bf1aff58c10aadf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/external_utils.py @@ -0,0 +1,296 @@ +""" +This module contains utility functions that are explicitly allowed to be called during +TorchDynamo compilation. These functions are carefully vetted to ensure they work +correctly within the TorchDynamo tracing and compilation process. + +Key functionality groups: + +- Compilation State: + Functions for checking compilation state (is_compiling) + +- Function Wrapping: + Utilities for wrapping functions (wrap_inline, wrap_numpy) to work with + TorchDynamo compilation + +- Autograd Hooks: + Functions and classes for handling autograd hooks and backward passes + (call_hook, FakeBackwardCFunction, etc.) + +- Tensor Operations: + Utility functions for tensor operations and transformations +""" + +import functools +import warnings +from collections.abc import Callable +from typing import Any, TYPE_CHECKING, TypeVar +from typing_extensions import deprecated, ParamSpec + +import torch +import torch.utils._pytree as pytree + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +if TYPE_CHECKING: + # TorchScript does not support `@deprecated` + # This is a workaround to avoid breaking TorchScript + @deprecated( + "`torch._dynamo.external_utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.", + category=FutureWarning, + ) + def is_compiling() -> bool: + return torch.compiler.is_compiling() + +else: + + def is_compiling() -> bool: + """ + Indicates whether we are tracing/compiling with torch.compile() or torch.export(). + """ + # NOTE: With `@torch.compile(backend="eager")`, torch._dynamo.is_compiling() will get traced + # and return true. torch.compiler.is_compiling() is skipped and will return false. + return torch.compiler.is_compiling() + + +def wrap_inline(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """ + Create an extra frame around fn that is not in skipfiles. + """ + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + return fn(*args, **kwargs) + + return inner + + +def call_hook( + hook: Callable[..., torch.Tensor | None], *args: Any, **kwargs: Any +) -> torch.Tensor: + """ + Used by compiled autograd to handle hook returning None. + """ + result = hook(*args) + if result is None: + return args[0] + elif kwargs.get("hook_type") == "post_acc_grad_hook": + raise RuntimeError("Tensor post accumulate grad hooks should return None.") + return result + + +def wrap_numpy(f: Callable[_P, _R]) -> Callable[_P, _R]: + r"""Decorator that turns a function from ``np.ndarray``s to ``np.ndarray``s into a function + from ``torch.Tensor``s to ``torch.Tensor``s. + """ + if not np: + return f + + @functools.wraps(f) + def wrap(*args: _P.args, **kwargs: _P.kwargs) -> pytree.PyTree: + args, kwargs = pytree.tree_map_only( + torch.Tensor, lambda x: x.numpy(), (args, kwargs) + ) + out = f(*args, **kwargs) + # pyrefly: ignore [missing-attribute] + return pytree.tree_map_only(np.ndarray, lambda x: torch.as_tensor(x), out) + + return wrap + + +class FakeBackwardCFunction: + def __init__( + self, + real: torch.autograd.function.BackwardCFunction, + saved_tensors: list[torch.Tensor], + ) -> None: + self.real = real + self.saved_tensors = saved_tensors + + def __getattr__(self, name: str) -> Any: + if name == "saved_variables": + warnings.warn( + "'saved_variables' is deprecated; use 'saved_tensors'", + DeprecationWarning, + ) + return self.saved_tensors + + return getattr(self.real, name) + + +def call_backward( + backward_c_function: torch.autograd.function.BackwardCFunction, + saved_tensors: list[torch.Tensor], + *args: Any, +) -> torch.Tensor | tuple[torch.Tensor, ...]: + fake = FakeBackwardCFunction(backward_c_function, saved_tensors) + grads = fake._forward_cls.backward(fake, *args) # type: ignore[attr-defined] + + if not isinstance(grads, tuple): + grads = (grads,) + + return grads + + +def normalize_as_list(x: Any) -> list[Any]: + if isinstance(x, tuple): + return list(x) + elif isinstance(x, list): + return x + return [x] + + +def untyped_storage_size(x: torch.Tensor) -> int: + return x.untyped_storage().size() + + +class FakeCompiledAutogradEngine: + @staticmethod + def queue_callback( + final_callbacks: list[Callable[[], None]], cb: Callable[[], None] + ) -> None: + final_callbacks.append(cb) + + @staticmethod + def exec_final_callbacks(final_callbacks: list[Callable[[], None]]) -> None: + i = 0 + while i < len(final_callbacks): + cb = final_callbacks[i] + cb() + i += 1 + final_callbacks.clear() + + @staticmethod + def _exec_final_callbacks_stub() -> None: + pass + + +def call_hook_from_backward_state( + *args: Any, bw_state: Any, hook_name: str, **kwargs: Any +) -> Any: + return getattr(bw_state, hook_name)(*args, **kwargs) + + +def call_module_hooks_from_backward_state( + _: Any, result: Any, *args: Any, bw_state: Any, hooks_name: str, module_name: str +) -> Any: + module = getattr(bw_state, module_name) + hooks = getattr(bw_state, hooks_name) + for hook in hooks: + new_result = hook(module, result, *args) + if new_result is not None: + result = new_result + return result + + +# used for torch._dynamo.disable(recursive=False) +def get_nonrecursive_disable_wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]: + # wrap function to get the right error message + # this function is in external_utils so that convert_frame doesn't skip it. + @functools.wraps(fn) + def nonrecursive_disable_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + if torch.compiler.is_exporting(): + raise RuntimeError( + "Non-recursive torch.compiler.disable is not supported with torch.export." + ) + return fn(*args, **kwargs) + + return nonrecursive_disable_wrapper + + +def wrap_dunder_call_ctx_manager(self: Any, func: Callable[_P, _R]) -> Callable[_P, _R]: + """ + Apply self as a ctx manager around a call to func + """ + + # NOTE: do not functools.wraps(func) because we don't ever want this frame to be skipped! + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with self: + return func(*args, **kwargs) + + return inner + + +# Use only on ints marked dynamic via torch.empty(0, integer) +# Currently only way to mark ints as dynamic: https://github.com/pytorch/pytorch/issues/129623 +def unwrap_maybe_dynamic_int(x: torch.Tensor | int) -> int: + if isinstance(x, torch.Tensor): + # x.size() is expected to be [0, dynamic_int] + return x.size(1) + return x + + +def call_accumulate_grad( + variable: torch.Tensor, + variable_grad: torch.Tensor | None, + grad: torch.Tensor | bool, + has_post_hooks: bool | None = None, +) -> torch.Tensor | None: + if has_post_hooks is None: + # Backward compatibility for graphs captured before current grad became + # an explicit argument. + has_post_hooks = bool(grad) + grad = variable_grad # type: ignore[assignment] + variable_grad = variable.grad + updated_grad = torch._dynamo.compiled_autograd.ops.AccumulateGrad( # type: ignore[attr-defined] + [grad], variable, variable_grad, has_post_hooks + ) + variable.grad = updated_grad[0] + return variable.grad + + +def wrap_inline_with_error_on_graph_break( + fn: Callable[_P, _R], error_on_graph_break: bool +) -> Callable[_P, _R]: + # NB: need multiple definitions in order to prevent `fullgraph` from + # being a freevar of wrapper + # NOTE: do not functools.wraps(fn) because we don't ever want these wrappers to be skipped! + if error_on_graph_break: + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with torch._dynamo.error_on_graph_break(True): + return fn(*args, **kwargs) + + else: + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with torch._dynamo.error_on_graph_break(False): + return fn(*args, **kwargs) + + return wrapper + + +def filter_out_const_values(tup: tuple[Any, ...], masks: list[bool]) -> tuple[Any, ...]: + """ + masks is a list of bools, where True means the corresponding element in tup + is a const value. Filter out the const values. + """ + out = [] + for mask_idx, mask in enumerate(masks): + if not mask: + out.append(tup[mask_idx]) + return tuple(out) + + +def insert_const_values_with_mask( + tup: tuple[Any, ...], masks: list[bool], values: tuple[Any, ...] +) -> tuple[Any, ...]: + """ + masks and values are of same length. For indices where the mask is True, use + the const_values to fill in. + """ + out = [] + idx = 0 + for mask_idx, mask in enumerate(masks): + if mask: + out.append(values[mask_idx]) + else: + out.append(tup[idx]) + idx += 1 + return tuple(out) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/funcname_cache.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/funcname_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..6aa935cd6749269236e3feb646ba0c7fb8c89b27 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/funcname_cache.py @@ -0,0 +1,74 @@ +""" +This module provides functionality for caching and looking up fully qualified function +and class names from Python source files by line number. + +It uses Python's tokenize module to parse source files and tracks function/class +definitions along with their nesting to build fully qualified names (e.g. 'class.method' +or 'module.function'). The results are cached in a two-level dictionary mapping: + + filename -> (line_number -> fully_qualified_name) + +Example usage: + name = get_funcname("myfile.py", 42) # Returns name of function/class at line 42 + clearcache() # Clear the cache if file contents have changed + +The parsing is done lazily when a file is first accessed. Invalid Python files or +IO errors are handled gracefully by returning empty cache entries. +""" + +import tokenize + + +cache: dict[str, dict[int, str]] = {} + + +def clearcache() -> None: + cache.clear() + + +def _add_file(filename: str) -> None: + try: + with tokenize.open(filename) as f: + tokens = list(tokenize.generate_tokens(f.readline)) + except (OSError, tokenize.TokenError): + cache[filename] = {} + return + + # NOTE: undefined behavior if file is not valid Python source, + # since tokenize will have undefined behavior. + result: dict[int, str] = {} + # current full funcname, e.g. xxx.yyy.zzz + cur_name = "" + cur_indent = 0 + significant_indents: list[int] = [] + + for i, token in enumerate(tokens): + if token.type == tokenize.INDENT: + cur_indent += 1 + elif token.type == tokenize.DEDENT: + cur_indent -= 1 + # possible end of function or class + if significant_indents and cur_indent == significant_indents[-1]: + significant_indents.pop() + # pop the last name + cur_name = cur_name.rpartition(".")[0] + elif ( + token.type == tokenize.NAME + and i + 1 < len(tokens) + and tokens[i + 1].type == tokenize.NAME + and (token.string == "class" or token.string == "def") + ): + # name of class/function always follows class/def token + significant_indents.append(cur_indent) + if cur_name: + cur_name += "." + cur_name += tokens[i + 1].string + result[token.start[0]] = cur_name + + cache[filename] = result + + +def get_funcname(filename: str, lineno: int) -> str | None: + if filename not in cache: + _add_file(filename) + return cache[filename].get(lineno, None) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/functional_export.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/functional_export.py new file mode 100644 index 0000000000000000000000000000000000000000..84be0697c0b189f3c2d2fbd885d68eb0d82ef847 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/functional_export.py @@ -0,0 +1,1104 @@ +from __future__ import annotations + +import inspect +import logging +import sys +import traceback +import types +from collections import namedtuple +from contextlib import nullcontext +from typing import Any, cast, TYPE_CHECKING, TypeVar + +import sympy + +import torch +import torch.fx +import torch.utils._pytree as pytree +from torch._dynamo.convert_frame import CaptureOutput, fullgraph_capture, get_traced_fn +from torch._dynamo.decorators import disable as dynamo_disable +from torch._dynamo.eval_frame import argument_names, check_user_input_output +from torch._dynamo.exc import UserErrorType +from torch._dynamo.source import GetItemSource +from torch._dynamo.utils import dynamo_timed, get_metrics_context +from torch._export.utils import _compiling_state_context +from torch._guards import detect_fake_mode, Source, TracingContext +from torch.export.dynamic_shapes import _RelaxedConstraint, Constraint +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + DimDynamic, + StatelessSymbolicContext, +) +from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._dynamo.output_graph import OutputReturnInfo + from torch._subclasses.fake_tensor import FakeTensorMode + from torch.export._trace import _DynamicShapesInput + from torch.fx import Node + from torch.fx.node import Argument, Target + +from torch.fx.experimental._spec_binding import _bind_spec_to_args +from torch.fx.experimental.dynamic_spec import ( + _coerce_to_shapes_spec, + IntermediateSpec, + ParamsSpec, + ShapesSpec, +) + + +T = TypeVar("T") +log = logging.getLogger(__name__) + + +def post_process_error_msg( + constraint_violation_error: ConstraintViolationError, + func: Callable[..., Any], + args: Any, + kwargs: Any, +) -> ConstraintViolationError: + """ + Because we trace a different callable, the sources are all messed up. + Manually patch them so the error message looks correct. + """ + from torch.export._unlift import _get_input_paths, _replace_sources + + orig_sig = inspect.signature(func) + flat_input_paths = _get_input_paths((args, kwargs), orig_sig) + if constraint_violation_error.args: + constraint_violation_error.args = ( + _replace_sources(constraint_violation_error.args[0], flat_input_paths), + ) + return constraint_violation_error + + +EXPORT_ROOT_REPLACEMENTS = [ + ("__export_root_", "_"), + ("_export_root.", ""), + ("._export_root", ""), +] + + +def clean_export_root_string(text: str) -> str: + """Generic utility to clean export_root patterns from strings.""" + result = text + for pattern, replacement in EXPORT_ROOT_REPLACEMENTS: + result = result.replace(pattern, replacement) + return result + + +def clean_nn_module_stack_and_source_fn( + graph_module: torch.fx.GraphModule, is_inline_builtin: bool = False +) -> torch.fx.GraphModule: + """ + Clean up nn_module_stack metadata by removing export_root references. + + Removes the _export_root module references from nn_module_stack metadata + in graph nodes, which are artifacts from the export process. Fixes two patterns: + + 1. Keys: Removes "__export_root_" and "__modules['_export_root']_" prefixes + - Normal case: "L__self____export_root_child" -> "L__self__child" + - inline_builtin case: Uses numeric ID strings like "140468831433840" + + 2. Values: Removes "._export_root" and "._modules['_export_root']" from child names + e.g., "L['self']._export_root.child" -> "L['self'].child" + e.g., "L['self']._modules['_export_root'].child" -> "L['self'].child" + + Also removes the root export entry "L__self____export_root" entirely. + + Args: + graph_module: The GraphModule to clean up + is_inline_builtin: If True, keys are numeric ID strings and self references + (L['self']) are filtered out + + Returns: + The cleaned GraphModule (modified in-place) + """ + + def _process_nn_module_stack( + nn_module_stack: dict[str, tuple[str, T]], + ) -> dict[str, tuple[str, T]]: + if "L__self____export_root" in nn_module_stack: + del nn_module_stack["L__self____export_root"] + + # Clean up remaining entries + cleaned_stack = {} + for key, (child_name, child_class) in nn_module_stack.items(): + # Clean key by removing export_root patterns + clean_key = clean_export_root_string(key) + + # Clean child_name by removing export_root patterns + clean_name = clean_export_root_string(child_name) + + # Skip self reference for inline builtin case + if is_inline_builtin and clean_name == "L['self']": + continue + + cleaned_stack[clean_key] = (clean_name, child_class) + return cleaned_stack + + def _process_source_fn(source_fn_stack: Iterable[T]) -> Iterable[T]: + cleaned_stack = [] + for item in source_fn_stack: + if isinstance(item, tuple) and len(item) == 2: + name, cls = item + if isinstance(name, str): + clean_name = clean_export_root_string(name) + cleaned_stack.append((clean_name, cls)) + else: + cleaned_stack.append(item) + else: + # pyrefly: ignore [bad-argument-type] + cleaned_stack.append(item) + # pyrefly: ignore [bad-return] + return cleaned_stack + + for node in graph_module.graph.nodes: + if "nn_module_stack" in node.meta: + node.meta["nn_module_stack"] = _process_nn_module_stack( + node.meta["nn_module_stack"].copy() + ) + + source_fn_stack = node.meta.get("source_fn_stack", None) + if source_fn_stack: + node.meta["source_fn_stack"] = _process_source_fn(source_fn_stack.copy()) + + if "dynamo_flat_name_to_original_fqn" in graph_module.meta: + # Clean up flat name to original fqn mapping + clean_name_to_original_fqn = {} + for flat_name, original_fqn in graph_module.meta[ + "dynamo_flat_name_to_original_fqn" + ].items(): + clean_name_to_original_fqn[clean_export_root_string(flat_name)] = ( + clean_export_root_string(original_fqn) + ) + graph_module.meta["dynamo_flat_name_to_original_fqn"] = ( + clean_name_to_original_fqn + ) + + return graph_module + + +def clean_export_root(graph_module: torch.fx.GraphModule) -> None: + """Remove export_root artifacts from FX graph in-place""" + + # Unlike getattr node, call_module can be invoked multiple times + # In those cases, we should fix all invocations of call_module + clean_named_module_map: dict[str, str] = {} + + # Update get_attr nodes in-place + for node in graph_module.graph.nodes: + if node.op == "get_attr": + old_target = node.target + new_target = clean_export_root_string(old_target) + if new_target != old_target: + node.target = new_target + if not hasattr(graph_module, old_target): + raise AssertionError( + f"graph_module missing attribute {old_target!r}" + ) + # Move the parameter to the new name + param = torch.fx.graph_module._get_attr(graph_module, old_target) + torch.fx.graph_module._assign_attr(param, graph_module, new_target) + torch.fx.graph_module._del_attr(graph_module, old_target) + # Dynamo will only have one nested level + if node.op == "call_module": + old_target = node.target + if not isinstance(old_target, str): + raise AssertionError( + f"expected old_target to be str, got {type(old_target)}" + ) + new_target = clean_export_root_string(old_target) + if not isinstance(new_target, str): + raise AssertionError( + f"expected new_target to be str, got {type(new_target)}" + ) + new_name = clean_export_root_string(node.name) + if new_target == old_target: + continue + + # if this module has already been cleaned before, just lookup from map. + if old_target in clean_named_module_map: + node.target = clean_named_module_map[old_target] + node.name = new_name + continue + target = graph_module.get_submodule(old_target) + graph_module.delete_submodule(old_target) + graph_module.add_submodule(new_target, target) + node.target = new_target + node.name = new_name + clean_named_module_map[old_target] = new_target + + +class ModuleToTrace(torch.nn.Module): + def __init__(self, foo: Any, in_spec: Any) -> None: + super().__init__() + self._export_root = foo + self.in_spec = in_spec + + def forward(self, *flat_args: Any) -> ExportTracerOutput: + args, kwargs = pytree.tree_unflatten(flat_args, self.in_spec) + res = self._export_root(*args, **kwargs) + out_flat, out_spec = pytree.tree_flatten(res) + return ExportTracerOutput(out_flat, out_spec) + + +ExportTracerOutput = namedtuple("ExportTracerOutput", ["flat_args", "out_spec"]) + + +# mypy: disable-error-code="no-untyped-def,var-annotated,assignment,index,operator" +class DynamoGraphTransformer(torch.fx.Transformer): + """Graph transformer for dynamo export that flattens inputs/outputs without complex matching.""" + + def __init__( + self, + module: torch.fx.GraphModule, + flat_inputs: list[Any], + flat_args_dynamic_dims: list[set[int]], + graph_input_order: dict[int, int], + graph_output_map: dict[int, OutputReturnInfo], + fake_mode: FakeTensorMode | None = None, + graph_inputs: dict[int, Source | None] | None = None, + ) -> None: + super().__init__(module) + + if len(flat_args_dynamic_dims) != len(flat_inputs): + raise AssertionError( + f"flat_args_dynamic_dims length ({len(flat_args_dynamic_dims)}) " + f"must match flat_inputs length ({len(flat_inputs)})" + ) + + self.flat_inputs = flat_inputs + self.flat_args_dynamic_dims = flat_args_dynamic_dims + self.graph_input_order = graph_input_order + self.graph_output_map = graph_output_map + self.fake_mode = fake_mode + self.graph_inputs = graph_inputs or {} + + # Get original placeholders and output + self.placeholders = [n for n in module.graph.nodes if n.op == "placeholder"] + self.output_node = next(n for n in module.graph.nodes if n.op == "output") + + # Create new flattened input placeholders + self.new_input_nodes: dict[int, torch.fx.Node] = {} + self._create_flattened_inputs() + + # Iterator for replacing old placeholders + self.old_to_new_mapping = {} + self._create_placeholder_mapping() + + def _create_flattened_inputs(self) -> None: + """Create new placeholder nodes for flattened inputs with proper fake tensors.""" + for i in range(len(self.flat_inputs)): + placeholder = super().placeholder(f"arg_{i}", (), {}) + + # Check if this user input (index i) maps to a graph placeholder + if i in self.graph_input_order: + # graph_input_order[i] gives us which graph placeholder this user input corresponds to + graph_placeholder_idx = self.graph_input_order[i] + if graph_placeholder_idx < len(self.placeholders): + orig_placeholder = self.placeholders[graph_placeholder_idx] + # Copy other metadata but not "val" yet + for key, value in orig_placeholder.meta.items(): + if key != "val": + placeholder.node.meta[key] = value + + # Always ensure we have proper "val" metadata from fake tensor + if self.fake_mode is not None and isinstance( + self.flat_inputs[i], torch.Tensor + ): + placeholder.node.meta["val"] = self.fake_mode.from_tensor( + self.flat_inputs[i], + symbolic_context=StatelessSymbolicContext( + dynamic_sizes=[ + ( + DimDynamic.DYNAMIC + if d in self.flat_args_dynamic_dims[i] + else DimDynamic.STATIC + ) + for d in range(len(self.flat_inputs[i].shape)) + ], + constraint_sizes=[None] * len(self.flat_inputs[i].shape), + ), + ) + elif hasattr(self.flat_inputs[i], "val"): # _IntWrapper case + placeholder.node.meta["val"] = self.flat_inputs[i].val + else: + placeholder.node.meta["val"] = self.flat_inputs[i] + + # pyrefly: ignore [unsupported-operation] + self.new_input_nodes[i] = placeholder + + def _create_placeholder_mapping(self) -> None: + """Create mapping from old placeholders to new ones.""" + # graph_input_order maps: user_input_index -> graph_placeholder_index + # We need to create: old_graph_placeholder -> new_user_input_placeholder + for user_input_idx, graph_placeholder_idx in self.graph_input_order.items(): + if graph_placeholder_idx < len(self.placeholders): + old_placeholder = self.placeholders[graph_placeholder_idx] + new_placeholder = self.new_input_nodes[user_input_idx] + self.old_to_new_mapping[old_placeholder] = new_placeholder + + def placeholder( + self, target: Target, args: tuple[Argument, ...], kwargs: dict[str, Any] + ) -> Any: + """Replace old placeholders with new flattened ones.""" + # Return the corresponding new placeholder + if self.current_node in self.old_to_new_mapping: + new_arg = self.old_to_new_mapping[self.current_node] + + # Copy over additional metadata from current node, but don't overwrite "val" + for key in ["tensor_dict", "example_value", "unbacked_bindings"]: + if key in self.current_node.meta: + new_arg.node.meta[key] = self.current_node.meta[key] + + # Only copy "val" if we don't already have a good one + if "val" in self.current_node.meta and "val" not in new_arg.node.meta: + new_arg.node.meta["val"] = self.current_node.meta["val"] + + return new_arg + else: + # Convert captured objects (e.g., opaque objects from closures) to + # get_attr nodes + placeholder_idx = self.placeholders.index(self.current_node) + if placeholder_idx in self.graph_inputs: + source = self.graph_inputs[placeholder_idx] + if not isinstance(source, GetItemSource): + example_val = self.current_node.meta.get( + "val" + ) or self.current_node.meta.get("example_value") + if example_val is not None: + attr_name = f"_captured_{placeholder_idx}" + if isinstance(example_val, torch.Tensor): + self.module.register_buffer(attr_name, example_val) + else: + setattr(self.module, attr_name, example_val) + result = self.tracer.create_proxy("get_attr", attr_name, (), {}) + result.node.meta = self.current_node.meta.copy() + result.node.meta["val"] = example_val + return result + return super().placeholder(target, args, kwargs) + + def output( + self, target: Target, args: Sequence[Any], kwargs: dict[str, Any] + ) -> Any: + """Transform output according to graph_output_map.""" + original_outputs = args[0] + + # Build new output list based on graph_output_map + new_outputs = [] + for i in sorted(self.graph_output_map.keys()): + output_type, val = self.graph_output_map[i] + + if output_type == "graph_out": + new_outputs.append(original_outputs[cast(int, val)]) + elif output_type == "input": + input_idx = cast(GetItemSource, val).index + new_outputs.append(self.new_input_nodes[input_idx]) + elif output_type == "constant": + new_outputs.append(val) + + return super().output(target, (tuple(new_outputs),), {}) + + def run_node(self, n: Node) -> Any: + """Run node transformation and preserve metadata.""" + self.current_node = n + result = super().run_node(n) + + # Copy important metadata + if hasattr(result, "node") and result.node is not n: + for key in ["val", "example_value", "unbacked_bindings"]: + if key in n.meta: + result.node.meta[key] = n.meta[key] + + # Preserve node names (except output) + if n.op != "output" and hasattr(n, "name"): + result.node._rename(n.name) + + return result + + def transform(self) -> torch.fx.GraphModule: + """Perform the graph transformation and copy module metadata.""" + result_gm = super().transform() + + # Copy module metadata like the original implementation + if hasattr(self.module, "meta"): + # pyrefly: ignore [unsupported-operation] + if "dynamo_flat_name_to_original_fqn" in self.module.meta: + # pyrefly: ignore [bad-index] + result_gm.meta["dynamo_flat_name_to_original_fqn"] = self.module.meta[ + # pyrefly: ignore [bad-index] + "dynamo_flat_name_to_original_fqn" + ] + # pyrefly: ignore [unsupported-operation] + if "dynamo_compile_id" in self.module.meta: + # pyrefly: ignore [bad-index] + result_gm.meta["dynamo_compile_id"] = self.module.meta[ + # pyrefly: ignore [bad-index] + "dynamo_compile_id" + ] + + return result_gm + + +def _suggest_or_raise_constraint_violation( + module_to_trace: torch.nn.Module, + orig_callable: Callable[..., Any], + fake_mode: FakeTensorMode | None, + graph_capture_output: CaptureOutput, + args: Any, + kwargs: Any, + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None, +) -> None: + constraint_violation_error = None + try: + # Check if we have any constraint violations + fn, _ = get_traced_fn(module_to_trace) + graph_capture_output.graph_capture_output.build_guards(fn.__code__) + except ConstraintViolationError as e: + constraint_violation_error = e + + if ( + (shape_env := getattr(fake_mode, "shape_env", None)) is not None + and (dim_constraints := shape_env.dim_constraints) is not None + and not isinstance( + module_to_trace.forward, + torch._ops.OpOverloadPacket | torch._ops.OpOverload, + ) + ): + dim_constraints.solve() + + forced_specializations = dim_constraints.forced_specializations() + + msg = dim_constraints.prettify_results( + inspect.signature(orig_callable), # type: ignore[attr-defined] + dynamic_shapes, + constraint_violation_error, + forced_specializations, + ) + if constraint_violation_error: + if constraint_violation_error.args: + constraint_violation_error.args = ( + constraint_violation_error.args[0] + msg, + ) + else: + constraint_violation_error.args = (msg,) + else: + if forced_specializations: + constraint_violation_error = ConstraintViolationError(msg) + else: + log.info( + "Summary of dimension constraints:%s", + msg, + ) + + # Error if we have any constraints on static values + + for k in shape_env.var_to_range: + if isinstance(k, sympy.Integer): + constraint_violation_error = ConstraintViolationError( + f"{''.join(traceback.format_list(shape_env.var_to_stack[k]))}\n" + "It appears that you're trying to set a constraint on a " + f"value which we evaluated to have a static value of {k}. " + 'Set TORCH_LOGS="+export" for more information.' + ) + if constraint_violation_error: + constraint_violation_error = post_process_error_msg( + constraint_violation_error, orig_callable, args, kwargs + ) + raise constraint_violation_error + + +def _normalize_shuffle_graph(shuffle_gm: torch.fx.GraphModule) -> None: + shuffle_gm.graph.eliminate_dead_code() + shuffle_gm.recompile() + for name, buffer in list(shuffle_gm.named_buffers()): + delattr(shuffle_gm, name) + setattr(shuffle_gm, name, buffer) + + +def normalize_graph_module(gm: torch.fx.GraphModule) -> None: + for node in gm.graph.nodes: + if node.op == "placeholder": + node.meta["val"] = node.meta["example_value"] + + +class InputProcessor: + def __init__( + self, + root: object, + num_args: int, + kwarg_names: list[str], + ) -> None: + self.root = root + self.num_args = num_args + self.kwarg_names = kwarg_names + + def __call__( + self, inputs: tuple[object, ...] + ) -> tuple[tuple[object, ...], dict[str, object]]: + args = inputs + # pyrefly: ignore [implicit-any] + kwargs = {} + if len(args) > self.num_args: + kwargs = dict(zip(self.kwarg_names, args[self.num_args :])) + args = args[: self.num_args] + if self.root is not None: + if isinstance(self.root, torch.fx.GraphModule): + if not isinstance(self.root.graph._codegen, _DynamoBytecodeCodeGen): + raise AssertionError( + f"expected _DynamoBytecodeCodeGen, got {type(self.root.graph._codegen)}" + ) + if not hasattr( + self.root.graph._codegen.dynamo_bytecode_flatten, "input_processor" + ): + raise AssertionError( + "dynamo_bytecode_flatten missing input_processor attribute" + ) + if ( + self.root.graph._codegen.dynamo_bytecode_flatten.input_processor + is not self + ): + raise AssertionError( + "dynamo_bytecode_flatten.input_processor is not self" + ) + args = (self.root, *args) + return args, kwargs + + +class Yield(Exception): + pass + + +class DynamoBytecodeFlatten: + def __init__( + self, + input_processor: InputProcessor, + out: CaptureOutput, + f_globals: dict[str, object], + ) -> None: + self.input_processor = input_processor + self.out = out + self.f_globals = f_globals + self.gm_inputs: tuple[Any, ...] | None = None + + @dynamo_disable(reason="do not trace internal dynamo graph capture") # type: ignore[misc] + def __call__(self, *inputs: object) -> object: + def backend_dummy(*example_inputs: object) -> None: + self.gm_inputs = example_inputs + raise Yield + + args, kwargs = self.input_processor(inputs) + try: + self.out.forward_callable( + compiled_fn=backend_dummy, extra_globals=self.f_globals + )(*args, **kwargs) + except Yield: + if self.gm_inputs is None: + raise AssertionError("gm_inputs must not be None after Yield") from None + return self.gm_inputs + raise RuntimeError + + +class DynamoBytecodeUnflatten: + def __init__( + self, + input_processor: InputProcessor, + out: CaptureOutput, + f_globals: dict[str, object], + ) -> None: + self.input_processor = input_processor + self.out = out + self.f_globals = f_globals + + @dynamo_disable(reason="do not trace internal dynamo graph capture") # type: ignore[misc] + def __call__( + self, flat_outs: Sequence[object], inputs: tuple[object, ...] + ) -> object: + def backend_dummy(*example_inputs: object) -> Sequence[object]: + return flat_outs + + args, kwargs = self.input_processor(inputs) + with torch._C._DisableTorchDispatch(): + results = self.out.forward_callable( + compiled_fn=backend_dummy, extra_globals=self.f_globals + )(*args, **kwargs) + return results + + +def create_fx_graph_from_captured_output( + out: CaptureOutput, mod: Any, args: tuple[Any, ...], kwargs: dict[str, Any] +) -> torch.fx.GraphModule: + if out.backend_input is None: + raise AssertionError("out.backend_input must not be None") + backend_input = out.backend_input + + _, root = torch._dynamo.convert_frame.get_traced_fn(mod) + + flat_real_args = pytree.tree_leaves((args, kwargs)) + torch._dynamo.eval_frame.check_user_input_output( + flat_real_args, UserErrorType.INVALID_INPUT + ) + f_globals = out.graph_capture_output.f_globals + + graph_module = backend_input.graph_module + if isinstance(root, torch.nn.Module): + graph_module._parameters = root._parameters + graph_module._buffers = root._buffers + if not all(not hasattr(graph_module, m) for m in root._modules): + raise AssertionError( + "graph_module already has attributes conflicting with root._modules" + ) + graph_module._modules.update(root._modules) + graph_module._non_persistent_buffers_set = root._non_persistent_buffers_set + if sys.version_info >= (3, 14): + import annotationlib # added in 3.14 + + annotations = annotationlib.get_annotations(torch.nn.Module) + else: + annotations = getattr(torch.nn.Module, "__annotations__", None) + for name, value in root.__dict__.items(): + if annotations and name not in annotations: + graph_module.__dict__[name] = value + graph_module._forward_hooks = root._forward_hooks.copy() + graph_module._forward_pre_hooks = root._forward_pre_hooks.copy() + graph_module._backward_hooks = root._backward_hooks.copy() + graph_module._backward_pre_hooks = root._backward_pre_hooks.copy() + if graph_module._forward_hooks or graph_module._forward_pre_hooks: + # Even forward hooks are traced through, they still capture a bunch + # of state through closure. We need to make sure these data are + # accessible through the captured module (but the hooks should be + # disabled). + if getattr(graph_module, "_wrapped_call", None) is None: + raise AssertionError("graph_module._wrapped_call must not be None") + if not isinstance( + graph_module._wrapped_call, torch.fx.graph_module._WrappedCall + ): + raise AssertionError( + f"expected _WrappedCall, got {type(graph_module._wrapped_call)}" + ) + if graph_module._wrapped_call.cls_call is not None: + raise AssertionError("graph_module._wrapped_call.cls_call must be None") + + def dynamo_wrapped_call(self, *args: object, **kwargs: object) -> object: + if "forward" in self.__dict__: + raise AssertionError("'forward' should not be in self.__dict__") + + fwd_hooks = self._forward_hooks + fwd_pre_hooks = self._forward_pre_hooks + original_forward = type(self).forward + + def patched_forward(self, *args: object, **kwargs: object) -> object: + self._forward_hooks = fwd_hooks + self._forward_pre_hooks = fwd_pre_hooks + return original_forward(self, *args, **kwargs) + + try: + self.forward = types.MethodType(patched_forward, self) + # pyrefly: ignore [implicit-any] + self._forward_hooks = {} + # pyrefly: ignore [implicit-any] + self._forward_pre_hooks = {} + # pyrefly: ignore [invalid-argument] + return super(type(self), self).__call__(*args, **kwargs) + finally: + self.__dict__.pop("forward") + self._forward_hooks = fwd_hooks + self._forward_pre_hooks = fwd_pre_hooks + + # pyrefly: ignore [bad-assignment] + graph_module._wrapped_call.cls_call = dynamo_wrapped_call + + root = graph_module if isinstance(root, torch.nn.Module) else root + input_processor = InputProcessor(root, len(args), list(kwargs.keys())) + dynamo_bytecode_flatten = DynamoBytecodeFlatten(input_processor, out, f_globals) + dynamo_bytecode_unflatten = DynamoBytecodeUnflatten(input_processor, out, f_globals) + + graph_module.graph._codegen = _DynamoBytecodeCodeGen( + argument_names(inspect.signature(mod), args, kwargs), + dynamo_bytecode_flatten, + dynamo_bytecode_unflatten, + ) # type: ignore[attr-defined] + normalize_graph_module(graph_module) + if hasattr(graph_module, "_dynamo_bytecode_flatten"): + raise AssertionError( + "graph_module already has _dynamo_bytecode_flatten attribute" + ) + if hasattr(graph_module, "_dynamo_bytecode_unflatten"): + raise AssertionError( + "graph_module already has _dynamo_bytecode_unflatten attribute" + ) + # pyrefly: ignore [bad-argument-type] + graph_module._dynamo_bytecode_flatten = dynamo_bytecode_flatten + # pyrefly: ignore [bad-argument-type] + graph_module._dynamo_bytecode_unflatten = dynamo_bytecode_unflatten + delattr(graph_module, "_param_name_to_source") + graph_module.recompile() + graph_module.meta["module_call_specs"] = ( + out.graph_capture_output.output_graph.export_metadata.module_call_spec + ) + if out.backend_input is None: + raise AssertionError("out.backend_input must not be None for fake_mode") + graph_module.meta["fake_mode"] = out.backend_input.fake_mode # type: ignore[attr-defined] + graph_module.meta["fake_mode"].allow_non_fake_inputs = True + tracing_context = TracingContext(graph_module.meta["fake_mode"]) + tracing_context.tensor_to_context = out.backend_input.tensor_to_context # type: ignore[attr-defined] + graph_module.meta["tracing_context"] = tracing_context + return graph_module + + +class _DynamoBytecodeCodeGen(torch.fx.graph.CodeGen): + def __init__( + self, + orig_arg_names: list[str], + dynamo_bytecode_flatten: DynamoBytecodeFlatten, + dynamo_bytecode_unflatten: DynamoBytecodeUnflatten, + ) -> None: + super().__init__() + self.orig_arg_names = orig_arg_names + self.dynamo_bytecode_flatten = dynamo_bytecode_flatten + self.dynamo_bytecode_unflatten = dynamo_bytecode_unflatten + self.wrap_tuple = False + self._inputs: tuple[Any, ...] | None = None + + def process_inputs(self, *inputs: Any) -> Any: + self._inputs = inputs + results = self.dynamo_bytecode_flatten(*inputs) + fake_mode = detect_fake_mode() + if fake_mode is not None and pytree.tree_any( + lambda x: isinstance(x, torch.Tensor) and not fake_mode.is_our_fake(x), + results, + ): + # Bytecode replay can recover tensors captured from module + # attributes as extra FX placeholder values. These tensors are not + # visible in AOTAutograd's user-facing call signature, so allow the + # active FakeTensorMode to convert them at dispatch time. This must + # remain enabled for AOT's backward trace too, since autograd can + # save the recovered tensors from the forward. + fake_mode.allow_non_fake_inputs = True + return results + + def process_outputs(self, outputs: Any) -> Any: + if self._inputs is None: + raise AssertionError("process_outputs called before process_inputs") + results = self.dynamo_bytecode_unflatten(outputs, self._inputs) + if self.wrap_tuple: + results = (results,) + self._inputs = None + return results + + def gen_fn_def( + self, + free_vars: list[str], + maybe_return_annotation: str, + *, + expanded_def: bool = False, + ) -> str: + fn_args = self.orig_arg_names + has_orig_self = (fn_args[0] == "self") if len(fn_args) > 0 else False + if has_orig_self: + free_vars.insert(0, "self") + # Rename any non-first `self` in fn_args to a unique name. The base + # CodeGen.gen_fn_def prepends `"self"` for the GraphModule's bound- + # method receiver whenever fn_args[0] != "self", which collides with + # a schema param literally named `self` (e.g. `aten.where.self(Tensor + # cond, Tensor self, Tensor other)` -> `def forward(self, cond, self, + # other)` -> `SyntaxError: duplicate argument 'self' in function + # definition`). Both the function-def arg list (via super().gen_fn_def) + # and the body binding (via gen_var_bindings) reference fn_args, so + # the rename is consistent end-to-end. + fn_args = list(fn_args) + first_pos = 1 if has_orig_self else 0 + for i in range(first_pos, len(fn_args)): + if fn_args[i] == "self": + new_name = "self_" + while new_name in fn_args: + new_name += "_" + fn_args[i] = new_name + fn_definition = super().gen_fn_def( + fn_args[:], maybe_return_annotation, expanded_def=expanded_def + ) + + if len(free_vars) > 0: # pytree has placeholders in it + fn_definition += self.gen_var_bindings(fn_args, free_vars, expanded_def) + return fn_definition + + def gen_var_bindings( + self, fn_args: list[str], free_vars: list[str], expanded_def: bool + ) -> str: + without_annotation = [x.split(":")[0].split("#")[0] for x in free_vars] + if len(fn_args) == 0: + fn_signature = "" + elif len(fn_args) == 1: + fn_signature = f"{fn_args[0]}, " + else: + fn_signature = f"{', '.join(fn_args)}" + return f""" + _fn_args = ({fn_signature}) + {", ".join(without_annotation)}, = self._dynamo_bytecode_flatten(*_fn_args)""" + + def generate_output( + self, + output_args: torch.fx.node.Argument, + *, + descs: object | None = None, + repr_fn: Any | None = None, + ) -> str: + if repr_fn is None: + repr_fn = repr + # pyrefly: ignore [not-iterable] + returned = f"self._dynamo_bytecode_unflatten(({', '.join([repr_fn(a) for a in output_args])},), _fn_args)" + if self.wrap_tuple: + returned = f"({returned},)" + return f"return {returned}" + + +def dynamo_graph_capture_for_export( + fn: Callable[..., Any], + constraints: list[Constraint] | None = None, +) -> Callable[..., Any]: + if isinstance(fn, torch._ops.OpOverload): + + def default_annotation(arg: torch.Argument) -> str: + if arg.has_default_value(): + return f"={arg.default_value!r}" + return "" + + has_kwarg_only = False + arg_list = [] + for arg in fn._schema.arguments: + if arg.kwarg_only and not has_kwarg_only: + has_kwarg_only = True + arg_list.append("*") + arg_list.append(arg.name + default_annotation(arg)) + func_str = f""" +def op_overload_wrapper({", ".join(arg_list)}): + return op({", ".join([f"{arg.name}={arg.name}" for arg in fn._schema.arguments])}) +""" + out = {} + exec(func_str, {"op": fn}, out) + fn = out["op_overload_wrapper"] # type: ignore[assignment] + + def inner(*args: Any, **kwargs: Any) -> Any: + if torch._dynamo.config.install_free_tensors: + raise AssertionError("install_free_tensors must be False") + with ( + _compiling_state_context(), + torch._dynamo.config.patch( + replay_side_effects=False, side_effect_replay_policy="warn" + ), + get_metrics_context(), + dynamo_timed("fullgraph_capture"), + ): + out = fullgraph_capture( + fn, + args, + kwargs, + constraints=constraints, + ) + graph_module = create_fx_graph_from_captured_output(out, fn, args, kwargs) + return graph_module + + return inner + + +def _dynamo_graph_capture_for_export( + mod: Callable[..., Any], + *, + constraints: list[Constraint] | None = None, + dynamic_shapes: _DynamicShapesInput = None, +) -> Callable[..., torch.fx.GraphModule]: + """ + Improved dynamo graph capture using transformer approach with proper fake tensor handling. + + This function creates a capture instance that handles: + 1. PyTree flattening/unflattening with proper input ordering + 2. Dynamo graph capture with export-specific context + 3. FX graph transformation for export compatibility + 4. Proper fake tensor metadata preservation + 5. Dynamic dimension constraint handling + + Notable improvements over manual approach: + - Uses FX Transformer for cleaner graph manipulation + - Properly handles fake tensor metadata and dynamic dimensions + - Preserves all necessary metadata for export + - More robust error handling and edge case management + + TODO: + 1. Are we actually gonna run the bytecode? + 2. Need to attach guards + """ + + _constraints = constraints + + def inner(*args: Any, **kwargs: Any) -> torch.fx.GraphModule: + # This sets the is_exporting flag when building guards. + with _compiling_state_context(): + # Only a ShapesSpec/ParamsSpec object opts into the new spec API. + # A bare dict/tuple in export's `dynamic_shapes` is now bound to + # the Dim export API. + # TODO: inspect dictionary leaves and enable dict for ParamsSpec + # here too, like make_fx and compile. + user_spec: ShapesSpec | None = None + if isinstance(dynamic_shapes, (ShapesSpec, ParamsSpec)): + user_spec = _coerce_to_shapes_spec(dynamic_shapes) + flattened_spec: ShapesSpec | None = None + if user_spec is not None: + # _bind_spec_to_args also flattens (args, kwargs) for us. + leaf_specs, flat_inputs, in_spec = _bind_spec_to_args( + mod, args, kwargs, user_spec + ) + flattened_spec = ShapesSpec( + # leaf_specs is list[LeafSpec]; cast around list invariance + # (ParamsSpec wants list[IntermediateSpec]). + ParamsSpec({"*args": cast(list[IntermediateSpec], leaf_specs)}), + assumptions=user_spec._assumptions or None, + ) + else: + flat_inputs, in_spec = pytree.tree_flatten((args, kwargs)) + check_user_input_output(flat_inputs, UserErrorType.INVALID_INPUT) + module_to_trace = ModuleToTrace(mod, in_spec) + orig_callable = mod.forward if isinstance(mod, torch.nn.Module) else mod + + constraints: list[Constraint] | None = _constraints + + from . import reset # type: ignore[attr-defined] + + reset() + + dynamo_config_ctx = torch._dynamo.config.patch( + specialize_int=True, + specialize_float=True, + assume_static_by_default=True, + automatic_dynamic_shapes=False, + capture_dynamic_output_shape_ops=True, + capture_scalar_outputs=True, + constant_fold_autograd_profiler_enabled=True, + log_graph_in_out_metadata=True, + # install_free_tensors ensures that params and buffers are still + # added as graph attributes, and makes Dynamo emits graphs that + # follow export pytree-able input requirements In future, if we + # fully rely on bytecode for the runtime, we can turn this flag + # off. + install_free_tensors=torch._dynamo.config.install_free_tensors_for_export, + ) + + # If a user spec was supplied, re-key it to the intermediate + # ModuleToTrace.forward(*flat_args) layout and expose via + # ``torch._dynamo.config._dynamic_shapes_spec`` for the variable + # builder. + shapes_spec_in_use = user_spec is not None + shapes_spec_ctx = nullcontext() + if flattened_spec is not None: + shapes_spec_ctx = torch._dynamo.config.patch( + _dynamic_shapes_spec=flattened_spec + ) + + with ( + get_metrics_context(), + dynamo_timed("fullgraph_capture"), + dynamo_config_ctx, + shapes_spec_ctx, + ): + out = fullgraph_capture( + module_to_trace, + tuple(flat_inputs), + constraints=_constraints, + _is_export_deprecated_do_not_use=True, + ) + + if out.graph_capture_output.output_graph is None: + raise AssertionError( + "output_graph must not be None after fullgraph_capture" + ) + + example_inputs: list[Any] = [] + if out.backend_input is not None: + graph = out.backend_input.graph_module + fake_mode = out.backend_input.fake_mode + example_inputs = out.backend_input.example_inputs + else: + graph = torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph()) + graph.graph.output(None) + graph.recompile() + fake_mode = None + + # ShapesSpec is unbacked based, constraint violations are not + # relevant. + if not shapes_spec_in_use: + _suggest_or_raise_constraint_violation( + module_to_trace, + orig_callable, + fake_mode, + out, + args, + kwargs, + dynamic_shapes, # type: ignore[arg-type] + ) + + # Extract export metadata from the new location + export_metadata = out.graph_capture_output.output_graph.export_metadata + graph_inputs = export_metadata.graph_input_idx_to_local_source + graph_output_map = export_metadata.output_return_type + out_spec = export_metadata.out_spec + module_call_spec = export_metadata.module_call_spec + + # Compute dynamic dimensions for each input based on constraints + flat_args_dynamic_dims = [ + { + c.dim + for c in (constraints or ()) + if ( + c.t_id == id(x) + and not isinstance(c, _RelaxedConstraint) + and c.constraint_range.vr.lower != c.constraint_range.vr.upper + ) + } + for x in flat_inputs + ] + + # Create input order mapping from dynamo's internal order to user order + # Only process inputs that come from function arguments (GetItemSource). + # Skip inputs that come from other sources like closures (e.g., captured + # opaque objects like DeviceMesh). + graph_input_order: dict[int, int] = {} + for inp in graph_inputs: + source = graph_inputs[inp] + if isinstance(source, torch._dynamo.source.GetItemSource): + graph_input_order[source.index] = len(graph_input_order) + + for real_idx, graph_idx in graph_input_order.items(): + flat_inputs[real_idx] = example_inputs[graph_idx] + + # Use FX transformer to rebuild the graph cleanly + transformed_graph = DynamoGraphTransformer( + graph, + flat_inputs, + flat_args_dynamic_dims, + graph_input_order, + graph_output_map, + fake_mode, + graph_inputs, + ).transform() + + # Set up PyTree codegen for proper input/output handling + transformed_graph.graph._codegen = _PyTreeCodeGen( + _PyTreeInfo( + argument_names(inspect.signature(orig_callable), args, kwargs), # type: ignore[attr-defined, arg-type] + in_spec, + out_spec, + ) + ) + transformed_graph.recompile() + + clean_nn_module_stack_and_source_fn(transformed_graph, True) + clean_export_root(transformed_graph) + + transformed_graph.meta["module_call_specs"] = module_call_spec + transformed_graph.meta["fake_mode"] = fake_mode + + return transformed_graph + + return inner diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_hints.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_hints.py new file mode 100644 index 0000000000000000000000000000000000000000..b04f37b3bbc48800cb96b896d5036b97c2ba0ca1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_hints.py @@ -0,0 +1,32 @@ +USER_ERROR = [ + "Your code may result in an error when running in eager. " + "Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. " + 'You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance("force_eager")`. ' +] +DYNAMO_BUG = [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch.", +] +DIFFICULT = [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance.", +] +FUNDAMENTAL = [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through " + "your code. Consider finding a workaround.", +] +SUPPORTABLE = [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you " + "encounter this graph break often and it is causing performance issues.", +] +CAUSED_BY_EARLIER_GRAPH_BREAK = [ + "This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one.", +] +INFERENCE_MODE = [ + "Avoid using `tensor.is_inference()` and `torch.is_inference_mode_enabled()` in your compile code. " + "This is primarily used in conjunction with `torch.inference_mode`. Consider using `torch.no_grad` instead " + "because `torch.no_grad` leads to same improvements as `inference_mode` when `torch.compile` is used.", +] +SPARSE_TENSOR = [ + "Sparse tensor operations are not yet fully supported in torch.compile with fullgraph=True. " + "Consider using fullgraph=False to allow graph breaks, or move sparse tensor creation " + "outside the compiled region.", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_registry.json b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_registry.json new file mode 100644 index 0000000000000000000000000000000000000000..bbfc54b899106b40990908625f6487467122c3da --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_registry.json @@ -0,0 +1,6431 @@ +{ + "GB0000": [ + { + "Gb_type": "All __torch_function__ overrides returned NotImplemented due to TypeError from user code", + "Context": "fn={fn}, args={args}, kwargs={kwargs}", + "Explanation": "All __torch_function__ overrides for function {fn} returned NotImplemented", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0001": [ + { + "Gb_type": "Argument of `as_subclass` must be a non-dispatcher-style tensor subclass", + "Context": "{self}.as_subclass({cls})", + "Explanation": "Currently not supported", + "Hints": [ + "Avoid this call or move it outside `torch.compile` region", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Argument of `as_subclass` must be a non-dispatcher-style tensor subclass", + "Context": "{self}.as_subclass({cls})", + "Explanation": "Currently not supported", + "Hints": [ + "Avoid this call or move it outside `torch.compile` regione", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0002": [ + { + "Gb_type": "Assertion failed on symbolic shapes", + "Context": "str(sym_expr)", + "Explanation": "", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0003": [ + { + "Gb_type": "Attempt to trace generator", + "Context": "", + "Explanation": "Generators cannot be compiled directly with `torch.compile`.", + "Hints": [ + "Call a generator from inside of a non-generator Python function and ", + "compile that function instead.", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0004": [ + { + "Gb_type": "Attempted super().__delattr__() on an object without mutation tracking", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo needs to track mutations on an object before `super().__delattr__` can be used on it. But the object ({self.objvar}) doesn't have attribute mutation tracking enabled.", + "Hints": [ + "Ensure the object is tracked by Dynamo's side effect system.", + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB4774": [ + { + "Gb_type": "torch.map: f mutates pos_args", + "Context": "pos_args={pos_args_mutated}", + "Explanation": "map only supports in-place mutation of xs (each iteration sees a storage-disjoint slice). pos_args are loop-invariant: every iteration sees the same tensor, so a mutation makes iterations depend on each other, breaking map's independence contract and introducing a data race under any parallel lowering. Use scan or while_loop if sequential buffer updates are required.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB2861": [ + { + "Gb_type": "Untraceable C tp_hash", + "Context": "hash_impl {self}", + "Explanation": "{cls.__name__} defines a C __hash__ that Dynamo cannot trace into.", + "Hints": [ + "Use torch._dynamo.allow_c_slot({cls.__name__}) to ", + "register it as safe if its slots are pure and ", + "deterministic.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Untraceable C tp_hash", + "Context": "hash_impl {self}", + "Explanation": "{cls.__name__} defines a C __hash__ that Dynamo cannot trace into.", + "Hints": [ + "Use torch._dynamo.allow_c_hash({cls.__name__}) to ", + "register it as safe if its __hash__ is pure and ", + "deterministic.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Untraceable C tp_hash", + "Context": "hash_impl {self}", + "Explanation": "{cls.__name__} defines a C __hash__ that Dynamo cannot trace into.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0005": [ + { + "Gb_type": "Attempted to a str() method implemented in C/C++", + "Context": "", + "Explanation": "{type(arg.value)} has a C/C++ based str method. This is not supported.", + "Hints": [ + "Write the str method in Python" + ] + } + ], + "GB0006": [ + { + "Gb_type": "Attempted to call a super() attribute that is not a function or method", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo does not know how to trace the call `super().{name}()` because `super().{name}` is not a function or method attribute.", + "Hints": [ + "Ensure the attribute accessed via `super()` is a standard method or function." + ] + } + ], + "GB0007": [ + { + "Gb_type": "Attempted to call function marked as skipped", + "Context": "module: {module_name}, qualname: {qualname}, skip reason: {reason}", + "Explanation": "explanation", + "Hints": [] + } + ], + "GB0008": [ + { + "Gb_type": "Attempted to inline function marked as skipped", + "Context": "qualname: {fn_qualname}, name: {func.get_name()}, filename: `{func.get_filename()}`, skip reason: {result.reason}", + "Explanation": "Dynamo developers have intentionally marked that the function `{fn_qualname}` should not be traced.", + "Hints": [] + } + ], + "GB0009": [ + { + "Gb_type": "Attempted to inline function marked as skipped (SkipFunctionVariable)", + "Context": "Attempted to inline a SkipFunctionVariable {func}", + "Explanation": "Attempted to inline a function that was previously determined to be marked as intentionally skipped.", + "Hints": [] + } + ], + "GB0010": [ + { + "Gb_type": "Attempted to read a deleted variable", + "Context": "item: {item}, name: {name}", + "Explanation": "", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0871": [ + { + "Gb_type": "Non-constant __hash__ return", + "Context": "hash_impl {self}", + "Explanation": "__hash__ returned a non-constant {type(result).__name__}.", + "Hints": [ + "Ensure that your custom __hash__ function returns an integer.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0011": [ + { + "Gb_type": "Attempted to read undefined local variable", + "Context": "LOAD_FAST {name}", + "Explanation": "Could not find a local variable with name `{name}`", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB2019": [ + { + "Gb_type": "Unsupported autograd.Function context `mark_dirty`", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo only supports tracing ctx.mark_dirty inside autograd.Function.apply.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0012": [ + { + "Gb_type": "Attempted to read undefined local variable (implicit)", + "Context": "LOAD_FAST {name}", + "Explanation": "Could not find an implicit local variable with name `{name}`", + "Hints": [ + "This happens in dict/list comprehensions", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0013": [ + { + "Gb_type": "Attempted to represent unregistered RemovableHandle", + "Context": "", + "Explanation": "Dynamo attempted to build a representation of a torch.utils.hooks.RemovableHandle, which is not supported. This happens because the RemovableHandle was created in another frame.", + "Hints": [] + } + ], + "GB0014": [ + { + "Gb_type": "Attempted to wrap RNN, GRU, or LSTM", + "Context": "str(value)", + "Explanation": "Dynamo does not support RNN, GRU, or LSTM.", + "Hints": [ + "Set torch._dynamo.config.allow_rnn=True to enable experimental support for RNN, GRU, and LSTM in Dynamo", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Attempted to wrap RNN, GRU, or LSTM", + "Context": "str(value)", + "Explanation": "Dynamo does not support RNN, GRU, or LSTM.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0015": [ + { + "Gb_type": "Attempted to wrap sparse Tensor", + "Context": "", + "Explanation": "torch.compile does not support sparse Tensors", + "Hints": [ + "Sparse tensor operations are not yet fully supported in torch.compile with fullgraph=True. Consider using fullgraph=False to allow graph breaks, or move sparse tensor creation outside the compiled region." + ] + } + ], + "GB0016": [ + { + "Gb_type": "Attempted to wrap strided NestedTensor", + "Context": "", + "Explanation": "torch.compile does not support strided NestedTensor", + "Hints": [] + } + ], + "GB0017": [ + { + "Gb_type": "Attempted to wrap torch._higher_order_ops.invoke_subgraph", + "Context": "", + "Explanation": "Directly using invoke_subgraph is not supported. Use nested_compile_region", + "Hints": [] + } + ], + "GB0018": [ + { + "Gb_type": "Attempted to wrap unbacked SymInt", + "Context": "", + "Explanation": "Unbacked SymInt input is not supported yet.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0019": [ + { + "Gb_type": "AutogradFunctionContextVariable escaped Dynamo-traced region", + "Context": "", + "Explanation": "We cannot reconstruct a torch.autograd.Function's context object.", + "Hints": [] + } + ], + "GB0020": [ + { + "Gb_type": "BUILD_STRING key conflict", + "Context": "format_string_parts: {format_string_parts}, kwargs: {kwargs}, part.sym_kwargs: {part.sym_kwargs}", + "Explanation": "Failed to build format string due to key conflict", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0021": [ + { + "Gb_type": "BUILD_STRING type error", + "Context": "str(part)", + "Explanation": "Format string part type is not correct - expected constant or format string.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0022": [ + { + "Gb_type": "Bad import result", + "Context": "typestr(value)", + "Explanation": "Import result is not a Python module.", + "Hints": [] + } + ], + "GB1273": [ + { + "Gb_type": "Unsupported attribute assignment on traceback object", + "Context": "call_setattr {self} {attr}", + "Explanation": "Dynamo does not support setting the attribute '{attr}' on tracked traceback objects. Only `tb_next` is supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0023": [ + { + "Gb_type": "Builtin `operator.*` comparison with constant `self` failed", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "\"Failed to compare {self} with {other}, \" + f\"because {other} is not a Python constant or its mutation check fails.\"", + "Hints": [] + } + ], + "GB0024": [ + { + "Gb_type": "CLEANUP_THROW with StopIteration", + "Context": "", + "Explanation": "Received StopIteration when handling generator.throw/close. This is not supported.", + "Hints": [] + } + ], + "GB0025": [ + { + "Gb_type": "Call to `torch._dynamo.graph_break()`", + "Context": "Called `torch._dynamo.graph_break()` with args `{args}`, kwargs `{kwargs}`", + "Explanation": "User-inserted graph break. Message: {graph_break_msg}", + "Hints": [ + "Remove the `torch._dynamo.graph_break()` call." + ] + } + ], + "GB7054": [ + { + "Gb_type": "backward() with non-leaf tensor", + "Context": "backward(inputs=[...]) with non-leaf tensor: {var}", + "Explanation": "backward(inputs=[...]) with non-leaf tensors is not yet supported.", + "Hints": [ + "Only pass leaf tensors (parameters, graph inputs) to backward(inputs=...)" + ] + }, + { + "Gb_type": "backward() with non-leaf tensor", + "Context": "backward(inputs=[...]) with non-leaf tensor", + "Explanation": "backward(inputs=[...]) with non-leaf tensors is not yet supported.", + "Hints": [ + "Only pass leaf tensors (parameters, graph inputs) to backward(inputs=...)" + ] + } + ], + "GB0026": [ + { + "Gb_type": "Calling subclass default constructor with more than tensor argument", + "Context": "{self.value}(args={args}, kwargs={kwargs})", + "Explanation": "Currently not supported", + "Hints": [ + "Avoid this constructor call or move it outside ", + "`torch.compile` region", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Calling subclass default constructor with more than tensor argument", + "Context": "{self.value}(args={args}, kwargs={kwargs})", + "Explanation": "Currently not supported", + "Hints": [ + "Avoid this constructor call or move it outside ", + "`torch.compile` regione", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0027": [ + { + "Gb_type": "Cannot check Tensor object identity without its fake value", + "Context": "str(fake_tensor)", + "Explanation": "TensorVariable is missing a fake example_value.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0028": [ + { + "Gb_type": "Caught non-Exception value", + "Context": "str(exc_instance)", + "Explanation": "Except expects to receive an object of Exception type but received {exc_instance}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0029": [ + { + "Gb_type": "Compilation of intermediate hooks requires compiled autograd", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo must be in compiled_autograd to register hooks.", + "Hints": [ + "Consider using torch.autograd.Function with a custom backward() method instead of register_hook()." + ] + } + ], + "GB0030": [ + { + "Gb_type": "ComptimeContext graph break", + "Context": "msg", + "Explanation": "Manually triggered ComptimeContext graph break with message {msg}.", + "Hints": [] + } + ], + "GB0031": [ + { + "Gb_type": "Custom __getattribute__ in nn.Module attribute access", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Dynamo could not trace through the custom `__getattribute__` method on this `nn.Module`.", + "Hints": [ + "Simplify your `__getattribute__` implementation, ", + "or replace it with a targeted `@property`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Custom __getattribute__ in nn.Module attribute access", + "Context": "getattro_impl {self} {name}", + "Explanation": "Dynamo could not trace through the custom `__getattribute__` method on this `nn.Module`.", + "Hints": [ + "Simplify your `__getattribute__` implementation, ", + "or replace it with a targeted `@property`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Custom __getattribute__ in nn.Module attribute access", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo could not trace through the custom `__getattribute__` method on this `nn.Module`.", + "Hints": [ + "Simplify your `__getattribute__` implementation, ", + "or replace it with a targeted `@property`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Custom __getattribute__ in nn.Module attribute access", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo does not support checking key existence on `nn.Module` instances that have a custom `__getattribute__` method defined.", + "Hints": [ + "Avoid defining `__getattribute__` in your module.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0032": [ + { + "Gb_type": "Custom __getattribute__ in nn.Module dict key check", + "Context": "has_key_in_generic_dict {self} {key}", + "Explanation": "Dynamo does not support checking key existence on `nn.Module` instances that have a custom `__getattribute__` method defined.", + "Hints": [ + "Avoid defining `__getattribute__` in your module.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0033": [ + { + "Gb_type": "Data dependent operator", + "Context": "str(cause.func)", + "Explanation": "Operator `{cause.func}` has a non-Tensor output whose value is dependent on the data of Tensor inputs.", + "Hints": [] + } + ], + "GB0034": [ + { + "Gb_type": "Data-dependent assertion failed (cannot compile partial graph)", + "Context": "value: {value}", + "Explanation": "Dynamo has determined when encountering a data-dependent assert failure that it should not compile the partial graph.", + "Hints": [ + "Use `torch._assert()` to raise a hard AssertionError when the check fails. ", + "This error will propagate back the user code ", + "that called the compiled function (i.e. Dynamo will not trace any exception handling).", + "Remove the assert statement.", + "Move the assert statement outside of any context managers in order to graph break with ", + "partial graph compilation (if fullgraph=False).", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0035": [ + { + "Gb_type": "Data-dependent branching with non-constant __bool__", + "Context": "value: {value}, result: {result}", + "Explanation": "Attempted to perform data-dependent branching on a user-defined object with non-constant truthiness.", + "Hints": [] + }, + { + "Gb_type": "Data-dependent branching with non-constant __bool__", + "Context": "method: {x}, result: {result}", + "Explanation": "Attempted to perform data-dependent branching on a user-defined object with a __bool__ method that did not return a constant.", + "Hints": [] + } + ], + "GB0036": [ + { + "Gb_type": "Dynamic shape operator", + "Context": "str(cause.func)", + "Explanation": "Operator `{cause.func}`'s output shape depends on input Tensor data.", + "Hints": [ + "Enable tracing of dynamic shape operators with ", + "`torch._dynamo.config.capture_dynamic_output_shape_ops = True`" + ] + } + ], + "GB6999": [ + { + "Gb_type": "unsupported variable type for __dict__ access", + "Context": "VariableTracker type: {type(vt)}", + "Explanation": "Dynamo does not know how to get __dict__ from {type(vt)}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB2444": [ + { + "Gb_type": "MAKE_CELL on a free variable name", + "Context": "MAKE_CELL {inst.argval}", + "Explanation": "An inlined comprehension creates a cell whose name `{inst.argval}` is also a free variable of the enclosing function.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0037": [ + { + "Gb_type": "Dynamic shape operator (no meta kernel)", + "Context": "str(cause.func)", + "Explanation": "Operator `{cause.func}` does not have a meta kernel that supports dynamic output shapes", + "Hints": [ + "Please report an issue to PyTorch" + ] + } + ], + "GB0038": [ + { + "Gb_type": "Dynamic slicing with Tensor arguments", + "Context": "SliceVariable start: {start}, stop: {stop}, step: {step}", + "Explanation": "Creating slices with Tensor arguments is not supported. e.g. `l[:x]`, where `x` is a 1-element tensor.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0039": [ + { + "Gb_type": "Dynamo recompile limit exceeded", + "Context": "Limit type: {limit_type}", + "Explanation": "Dynamo attempted to recompile the code object too many times, exceeding the {limit_type} cache size limit (currently set to {getattr(config, limit_type)}). Excessive recompilations can degrade performance due to the compilation overhead of each recompilation.", + "Hints": [ + "To monitor recompilations, enable TORCH_LOGS=recompiles. ", + "If recompilations are expected, consider ", + "increasing torch._dynamo.config.{limit_type} to an appropriate value.", + "See {troubleshooting_url} for tips on dealing with recompilations." + ] + }, + { + "Gb_type": "Dynamo cache limit exceeded", + "Context": "Limit type: {limit_type}", + "Explanation": "Dynamo attempted to recompile the code object too many times, exceeding the {limit_type} cache size limit.Giving up on compiling as the compile time tradeoff is likely not worth the performance gain.", + "Hints": [] + } + ], + "GB0040": [ + { + "Gb_type": "Encountered aliasing during higher order op tracing", + "Context": "context", + "Explanation": "Higher order ops do not support aliasing. Found in {name}", + "Hints": [ + "Replace `return input` with `return input.clone()` to avoid aliasing.", + "Consider using the debug context to change user code to avoid aliasing.", + "Please open an issue." + ] + }, + { + "Gb_type": "Encountered aliasing during higher order op tracing", + "Context": "context", + "Explanation": "Higher order ops do not support aliasing. Found in {source_target.name}", + "Hints": [ + "Replace `return input` with `return input.clone()` to avoid aliasing.", + "Consider using the debug context to change user code to avoid aliasing.", + "Please open an issue." + ] + } + ], + "GB0041": [ + { + "Gb_type": "Encountered input mutation during higher order op tracing", + "Context": "context", + "Explanation": "Higher order ops do not support input mutation. Found in {name}", + "Hints": [ + "Consider using the debug context to change user code to avoid mutation.", + "Please open an issue." + ] + }, + { + "Gb_type": "Encountered input mutation during higher order op tracing", + "Context": "context", + "Explanation": "Higher order ops do not support input mutation. Found in {source_target.name}", + "Hints": [ + "Consider using the debug context to change user code to avoid mutation.", + "Please open an issue." + ] + } + ], + "GB0042": [ + { + "Gb_type": "Encountered non user function variable during invoke_subgraph HOP tracing", + "Context": "str(fn_vt)", + "Explanation": "invoke_subgraph does not support non user function variable", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0043": [ + { + "Gb_type": "Encountered non-PT2-compliant op", + "Context": "", + "Explanation": "msg + + err_epilogue", + "Hints": [] + } + ], + "GB0044": [ + { + "Gb_type": "Encountered strided NestedTensor in automatic dynamic dim determination", + "Context": "", + "Explanation": "torch.compile does not support strided NestedTensor", + "Hints": [] + } + ], + "GB0045": [ + { + "Gb_type": "Encountered tensor.is_inference() during tracing", + "Context": "", + "Explanation": "tensor.is_inference() is not supported", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0046": [ + { + "Gb_type": "Encountered torch.is_inference_mode_enabled during tracing", + "Context": "", + "Explanation": "torch.is_inference_mode_enabled() is not supported", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0047": [ + { + "Gb_type": "Encountered unconverted argument when attempting to inline", + "Context": "func: {func}, arg: {v}", + "Explanation": "An argument to an inlined function was not successfully converted to a VariableTracker.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB5696": [ + { + "Gb_type": "Comprehension graph break with extra stack values", + "Context": "", + "Explanation": "Cannot use comprehension optimization when there are extra values on the stack and variables need to be passed to the resume function.", + "Hints": [] + } + ], + "GB0048": [ + { + "Gb_type": "Error getting associated real value", + "Context": "call_id {self}", + "Explanation": "Dynamo encountered an error while trying to get the associated real value.", + "Hints": [] + } + ], + "GB0049": [ + { + "Gb_type": "Error when attempting to resolve op packet", + "Context": "", + "Explanation": "str(e)", + "Hints": [] + } + ], + "GB0050": [ + { + "Gb_type": "Exception with bad expected type", + "Context": "str(expected_exc_types)", + "Explanation": "`except ...` has unsupported type {expected_exc_types}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4880": [ + { + "Gb_type": "missing_mp_subscript", + "Context": "mp_subscript_impl not defined for {type(self).__name__}", + "Explanation": "Dynamo does not yet support subscripting '{self.python_type_name()}'.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9741": [ + { + "Gb_type": "skip frame due to being in functorh mode", + "Context": "", + "Explanation": "torch.compile cannot be run in context: {functorch_subclass_name}. Skipping frame.", + "Hints": [] + }, + { + "Gb_type": "skip frame due to being in functorch mode", + "Context": "", + "Explanation": "torch.compile cannot be run in context: {functorch_subclass_name}. Skipping frame.", + "Hints": [] + } + ], + "GB7000": [ + { + "Gb_type": "graph break in loop", + "Context": "frame skipped: {format_frame_info(code)}", + "Explanation": "torch.compile detected a graph break in a for/while loop. Skipping the frame and falling back to eager, as graph breaks in loops are not supported.", + "Hints": [ + "This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one." + ] + } + ], + "GB3326": [ + { + "Gb_type": "invalid ptr argument for create_tma_descriptor", + "Context": "args = {args}, kwargs = {kwargs}", + "Explanation": "Expected `ptr` argument of `create_{self.rank}d_tma_descriptor`to be from a `.data_ptr()` call, represented internally by `DataPtrVariable`", + "Hints": [ + "`torch.compile` may fail to internally represent result of `.data_ptr()` ", + "with `DataPtrVariable` due to a graph break between the `.data_ptr()` call and ", + "`create_{self.rank}d_tma_descriptor`. Please ensure there were no graph breaks ", + "between these two calls." + ] + } + ], + "GB4297": [ + { + "Gb_type": "Call to `torch._dynamo.skip_frame()`", + "Context": "Called `torch._dynamo.skip_frame()` with args `{args}`, kwargs `{kwargs}`. Skipping frame {format_frame_info(tx.f_code)}.", + "Explanation": "User-inserted skip frame. Message: {skip_frame_msg}", + "Hints": [ + "Remove the `torch._dynamo.skip_frame()` call." + ] + } + ], + "GB0051": [ + { + "Gb_type": "Exception with non-type expectation", + "Context": "str(expected_type)", + "Explanation": "`except ...` expects a non-type: {expected_type}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0052": [ + { + "Gb_type": "Excessive RestartAnalysis() calls", + "Context": "", + "Explanation": "Dynamo attempted to trace the same frame 100+ times. Giving up on compiling as the compile time tradeoff is likely not worth the performance gain.", + "Hints": [] + } + ], + "GB8593": [ + { + "Gb_type": "flex_gemm: unexpected kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "flex_gemm internal HOP expects positional args only.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7072": [ + { + "Gb_type": "flex_gemm: improper args/kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "flex_gemm expects 5 positional arguments: gemm_op, body_fn, args, kwargs, kernel_options. args is expected to be list/tuple and kwargs/kernel_options are expected to be dicts.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0053": [ + { + "Gb_type": "FSDP with use_orig_params=False", + "Context": "", + "Explanation": "Dynamo only supports FSDP with use_orig_params=True", + "Hints": [] + } + ], + "GB5195": [ + { + "Gb_type": "elementwise_dtypes unsupported arg type", + "Context": "str(arg)", + "Explanation": "elementwise_dtypes requires tensor or constant arguments, got {type(arg).__name__}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0054": [ + { + "Gb_type": "Failed to construct Enum variable", + "Context": "value: {value_vt}, allowed enum values: {list(cls_type)}", + "Explanation": "Attempted to construct an Enum value that is non-constant (e.g. int, string) or is not an acceptable value for the Enum. Acceptable values for Enum `{cls_type}`: {list(cls_type)}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0055": [ + { + "Gb_type": "Failed to convert args/kwargs to proxy", + "Context": "call_function args: {typestr(*args)} {typestr(*list(kwargs.values()))}", + "Explanation": "Missing `as_proxy()` implementation for some arg/kwarg.", + "Hints": [] + } + ], + "GB0056": [ + { + "Gb_type": "Failed to mutate tensor data attribute", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo only supports mutating `.data` of tensor created outside `torch.compile` region", + "Hints": [ + "Don't mutate `.data` on this tensor, or move ", + "the mutation out of `torch.compile` region" + ] + }, + { + "Gb_type": "Failed to mutate tensor data attribute", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo only supports mutating `.data` of tensor created outside `torch.compile` region", + "Hints": [ + "Don't mutate `.data` on this tensor, or move ", + "the mutation out of `torch.compile` region" + ] + } + ], + "GB0057": [ + { + "Gb_type": "Failed to raise exception", + "Context": "str(exc)", + "Explanation": "Attempted to raise a non-Exception type/value.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7299": [ + { + "Gb_type": "_autograd_grad with lost grad_fn linkage", + "Context": "outputs lost autograd linkage during tracing", + "Explanation": "_autograd_grad() received tensors whose grad_fn was lost during tracing - this silently produces zero gradients.", + "Hints": [ + "Compile the full transform instead of the returned ", + "closure: torch.compile(lambda x: torch.func.vjp(f, x))", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0058": [ + { + "Gb_type": "Failed to set tensor attribute", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo doesn't support setting these tensor attributes", + "Hints": [ + "Don't mutate attribute '{name}' on tensors, or ", + "move the mutation out of `torch.compile` region" + ] + }, + { + "Gb_type": "Failed to set tensor attribute", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo doesn't support setting these tensor attributes", + "Hints": [ + "Don't mutate attribute '{name}' on tensors, or ", + "move the mutation out of `torch.compile` region" + ] + } + ], + "GB0059": [ + { + "Gb_type": "Failed to trace builtin operator", + "Context": "builtin {fn.__name__} {arg_types} {has_kwargs}", + "Explanation": "Dynamo does not know how to trace builtin operator `{fn.__name__}` with argument types {real_arg_types} (has_kwargs {has_kwargs})", + "Hints": [ + "Avoid calling builtin `{fn.__name__}` with argument types {real_arg_types}. ", + "Consider using an equivalent alternative function/method to `{fn.__name__}`.", + "If you are attempting to call a logging function (e.g. `print`), ", + "you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.", + "Please report an issue to PyTorch." + ] + } + ], + "GB6270": [ + { + "Gb_type": "Unhandled tensor method", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Tensor method `{name}` is not defined on {check_type.__name__} and does not have an explicit handler in TensorVariable.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8656": [ + { + "Gb_type": "Opaque object with custom __getattr__ not supported", + "Context": "{real_obj_type.__name__} with custom __getattr__", + "Explanation": "Dynamo does not support opaque objects types with custom __getattr__ methods", + "Hints": [] + } + ], + "GB0061": [ + { + "Gb_type": "Failed to unpack object for BUILD_LIST_UNPACK", + "Context": "str(seq)", + "Explanation": "{seq} cannot be unpacked into a list for the BUILD_LIST_UNPACK bytecode (`[*x, *y, ...]`).", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4197": [ + { + "Gb_type": "Unsupported Tensor.share_memory_() call", + "Context": "call_method {self} share_memory_", + "Explanation": "Dynamo does not support Tensor.share_memory_() which modifies tensor storage for IPC", + "Hints": [ + "Move share_memory_() call outside the compiled region. ", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0062": [ + { + "Gb_type": "Failed to unpack object for UNPACK_EX", + "Context": "str(seq)", + "Explanation": "{seq} cannot be unpacked into a list for the UNPACK_EX bytecode.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0063": [ + { + "Gb_type": "Failed to unpack object for UNPACK_SEQUENCE", + "Context": "str(seq)", + "Explanation": "{seq} cannot be unpacked into a list for the UNPACK_SEQUENCE bytecode (i.e. `a, b, c = d`).", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0064": [ + { + "Gb_type": "Fake tensor propagation exception", + "Context": "str(e.reason)", + "Explanation": "msg", + "Hints": [] + } + ], + "GB2736": [ + { + "Gb_type": "builtin isinstance() with custom type check on tensor", + "Context": "isinstance({arg}, {isinstance_type})", + "Explanation": "Dynamo cannot soundly trace arbitrary custom __instancecheck__ or __subclasscheck__ hooks on tensor values because the hook may read external mutable state.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4636": [ + { + "Gb_type": "Call to `torch._dynamo.step_unsupported()`", + "Context": "", + "Explanation": "User-inserted step_unsupported.", + "Hints": [ + "Remove the `torch._dynamo.step_unsupported()` call." + ] + } + ], + "GB0065": [ + { + "Gb_type": "Graph break in inlined function", + "Context": "", + "Explanation": "Graph breaks in an inlined call are not supported.", + "Hints": [] + } + ], + "GB0066": [ + { + "Gb_type": "Graph break under GenericContextWrappingVariable", + "Context": "Active generic context managers: {self.active_generic_context_managers}", + "Explanation": "Attempted to graph break in an active context manager(s) that doesn't support graph breaking.", + "Hints": [ + "Move the offending context manager(s) to outside the compiled region.", + "This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one." + ] + } + ], + "GB0067": [ + { + "Gb_type": "HOP: Unsafe side effect", + "Context": "Attempted to mutate {item}", + "Explanation": "Mutating a variable from outside the scope of this HOP is not supported.", + "Hints": [ + "If the HOP is activation checkpointing (torch.utils.checkpoint.checkpoint), this points to a ", + "side effect in forward method. Eager activation checkpointing replays that side-effect while ", + "recomputing the forward in the backward. If you are ok with side-effect not replayed in the ", + "backward, try setting `torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True`" + ] + }, + { + "Gb_type": "HOP: Unsafe side effect", + "Context": "Attempted to mutate {item}", + "Explanation": "Mutating a variable from outside the scope of this HOP is not supported.", + "Hints": [ + "If the HOP is activation checkpointing, try setting ", + "`torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True`" + ] + }, + { + "Gb_type": "HigherOrderOperator: Mutating a variable not in the current scope (SideEffects)", + "Context": "", + "Explanation": "This is not supported.", + "Hints": [] + } + ], + "GB9493": [ + { + "Gb_type": "C-implemented special method without VariableTracker model", + "Context": "name={name}, type={self.python_type_name()}, attr={type_attr}", + "Explanation": "'{self.python_type_name()}' implements '{name}' in C and Dynamo has no model for it.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0068": [ + { + "Gb_type": "Illegal method invocation in strict mode", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo currently does not support this method ({name}) invocation in strict mode.", + "Hints": [] + } + ], + "GB0069": [ + { + "Gb_type": "Import failure", + "Context": "module_name: {module_name}, fromlist: {fromlist}, level={level}", + "Explanation": "Failure when attempting to import.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0070": [ + { + "Gb_type": "Indexing list with non-scalar tensor", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Attempted to index list-like object with tensor with > 1 element.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0071": [ + { + "Gb_type": "Inline attempt with __self__", + "Context": "str(func)", + "Explanation": "Attempted to inline a function with the `__self__` attribute. Dynamo is expected to decompose method calls into function calls with a `self` argument.", + "Hints": [] + } + ], + "GB0072": [ + { + "Gb_type": "Inplace op on input tensor", + "Context": "", + "Explanation": "Attempted to trace an inplace view op on input tensor {typestr(self.value)}.", + "Hints": [ + "Ensure you do not modify input tensor in place.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB7230": [ + { + "Gb_type": "iter() with no arguments", + "Context": "iter()", + "Explanation": "iter() requires at least one argument", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "iter() with no arguments", + "Context": "iter()", + "Explanation": "iter() requires at least one argument", + "Hints": [] + } + ], + "GB0073": [ + { + "Gb_type": "Invoking an nn.Module inside a HigherOrderOperator", + "Context": "", + "Explanation": "This is not supported.", + "Hints": [] + } + ], + "GB0074": [ + { + "Gb_type": "Invoking an nn.Module inside a higher order operator", + "Context": "Higher order op name: {self.source_target}", + "Explanation": "This is not supported.", + "Hints": [] + } + ], + "GB2069": [ + { + "Gb_type": "Comprehension analysis failed: ambiguous result store", + "Context": "store_targets={store_targets}, iterator_vars={iterator_vars}", + "Explanation": "Expected exactly one comprehension result assignment.", + "Hints": [] + } + ], + "GB6012": [ + { + "Gb_type": "Cannot trace user-defined __len__", + "Context": "{self.python_type_name()}.__len__()", + "Explanation": "Dynamo cannot trace len() on {self.python_type_name()} because the __len__ method is either not traceable (e.g., defined in C or built-in) or returns a non-constant value.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0075": [ + { + "Gb_type": "LOAD_BUILD_CLASS bytecode not supported", + "Context": "", + "Explanation": "Dynamo does not support tracing classes that are defined in the compiled region.", + "Hints": [ + "Move the class definition out of the compiled region or set `torch._dynamo.config.enable_trace_load_build_class=True`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0076": [ + { + "Gb_type": "LOAD_FAST_CHECK on uninitialized variable", + "Context": "inst.argval", + "Explanation": "Attempted to load uninitialized local variable {inst.argval}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0077": [ + { + "Gb_type": "Length mismatch when unpacking object for UNPACK_SEQUENCE", + "Context": "expected length: {inst.argval}, actual: {len(val)}", + "Explanation": "{seq} unpacked to a list for the UNPACK_SEQUENCE bytecode (i.e. `a, b, c = d`) with unexpected length.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0078": [ + { + "Gb_type": "Limitation of `nonstrict_trace", + "Context": "{self}", + "Explanation": "msg", + "Hints": [ + "make sure definition of {fn_name} is outside ", + "`torch.compile` region" + ] + } + ], + "GB3775": [ + { + "Gb_type": "nb_int_impl not implemented", + "Context": "{type(self).__name__} has nb_int slot but no nb_int_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_int C slot but the corresponding VariableTracker doesn't implement nb_int_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0079": [ + { + "Gb_type": "Missing CALL_INTRINSIC_1 handler", + "Context": "CALL_INTRINSIC_1 operand: {inst.argval}", + "Explanation": "No handler implemented for CALL_INTRINSIC_1 {inst.argval} instruction.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0755": [ + { + "Gb_type": "nb_negative_impl not implemented", + "Context": "{type(self).__name__} has nb_negative slot but no nb_negative_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_negative C slot but the corresponding VariableTracker doesn't implement nb_negative_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB7596": [ + { + "Gb_type": "Indexing torch.Size with non-scalar tensor", + "Context": "get_item_dyn {self} {arg}", + "Explanation": "Attempted to index torch.Size with a tensor that is not a scalar constant.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0080": [ + { + "Gb_type": "Missing FakeTensor example value", + "Context": "str(node)", + "Explanation": "`FakeTensor` example value was required for {node} but not available.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0081": [ + { + "Gb_type": "Missing attribute when running call_method node", + "Context": "", + "Explanation": "make_error_message(\"attribute not defined\")", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "Missing attribute when running call_method node", + "Context": "", + "Explanation": "make_error_message(\"attribute not defined\")", + "Hints": [] + } + ], + "GB0082": [ + { + "Gb_type": "Missing bytecode handler", + "Context": "{opname} with args {args}", + "Explanation": "Dynamo does not know how to handle the bytecode instruction `{opname}`.", + "Hints": [ + "Do not trace code that produces the `{opname}` bytecode instruction ", + "(see https://docs.python.org/3/library/dis.html for bytecode semantics).", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0083": [ + { + "Gb_type": "Module-level backwards hooks require compiled autograd.", + "Context": "", + "Explanation": "", + "Hints": [ + "Enable compiled autograd by setting torch._dynamo.config.compiled_autograd = True." + ] + } + ], + "GB0084": [ + { + "Gb_type": "Non-constant attribute given to `super().__delattr__()`", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo requires the attribute name passed to `super().__delattr__(...)` to be a constant (string).", + "Hints": [ + "Ensure the attribute name is a string literal or a constant variable." + ] + } + ], + "GB0085": [ + { + "Gb_type": "Non-function or method in subclass of torch.autograd.Function", + "Context": "call_apply {self} {args} {kwargs}", + "Explanation": "Dynamo requires the `forward` attribute of a `torch.autograd.Function` subclass to be a standard Python function or method. Found type `{type(fn).__name__}` instead.", + "Hints": [ + "Ensure the `forward` method is defined as a regular ", + "function or instance method." + ] + } + ], + "GB0086": [ + { + "Gb_type": "Not a Python constant", + "Context": "guard_as_python_constant {self}", + "Explanation": "Failed to convert {self} into a Python constant.", + "Hints": [] + } + ], + "GB0087": [ + { + "Gb_type": "NotImplementedError/UnsupportedFakeTensorException when running FX node", + "Context": "", + "Explanation": "make_error_message(e)", + "Hints": [] + } + ], + "GB0088": [ + { + "Gb_type": "Observed exception", + "Context": "raised exception {curr_exc.debug_repr()}", + "Explanation": "observed_exn_gb_explanation", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "Observed exception", + "Context": "raised exception {curr_exc.python_type_name()}({curr_exc.args})", + "Explanation": "observed_exn_gb_explanation", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0089": [ + { + "Gb_type": "Observed exception (EXCEPT_HANDLER)", + "Context": "str(raised_exception)", + "Explanation": "observed_exn_gb_explanation + \" This graph break is unexpected.\"", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0090": [ + { + "Gb_type": "Operator does not support running with fake tensors", + "Context": "unsupported operator: {cause.func}", + "Explanation": "", + "Hints": [ + "{import_suggestion}see ", + "https://docs.google.com/document/d/1GgvOe7C8_NVOMLOCwDaYV1mXXyHMXY7ExoewHqooxrs/edit#heading=h.64r4npvq0w0", + " for how to fix" + ] + } + ], + "GB0091": [ + { + "Gb_type": "Read uninitialized cell", + "Context": "str(cellvar)", + "Explanation": "Attempted to read a cell variable that has not been populated yet.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0092": [ + { + "Gb_type": "Reconstruction failure", + "Context": "str(value)", + "Explanation": "Dynamo has no bytecode reconstruction implemented for sourceless variable {value}.", + "Hints": [ + "If Dynamo is attempting to trace a return statement and your code is attempting to return a variable ", + "that Dynamo cannot reconstruct, then remove it from the return statement.", + "Report an issue to PyTorch if you need reconstrtuction support. Note that objects that don't have ", + "reconstruction rules may be fundamentally unreconstructable.", + "This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one." + ] + } + ], + "GB0093": [ + { + "Gb_type": "Reconstruction failure: source.reconstruct not implemented", + "Context": "str(source)", + "Explanation": "Dynamo has no bytecode reconstruction implemented for {type(source)} variable {source}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0094": [ + { + "Gb_type": "SEND with bad type", + "Context": "TOS type: {typestr(receiver)}", + "Explanation": "Attempted to SEND with unsupported type {typestr(receiver)}.", + "Hints": [] + }, + { + "Gb_type": "SEND with bad type", + "Context": "TOS type: {typestr(tos)}", + "Explanation": "Attempted to SEND with unsupported type {typestr(tos)}.", + "Hints": [] + } + ], + "GB0095": [ + { + "Gb_type": "Set Exception object `__traceback__` attribute to not-`None`", + "Context": "call_setattr {self} {name}", + "Explanation": "Dynamo does not support setting the attribute '__traceback__' on tracked exception objects to anything other than None.", + "Hints": [ + "Avoid setting '__traceback__' on exception objects ", + "within traced code, or set it to None." + ] + } + ], + "GB5173": [ + { + "Gb_type": "Tensor device mismatch", + "Context": "{op} {node.target}", + "Explanation": "str(cause)", + "Hints": [ + "Move inputs, parameters, and buffers to the same device." + ] + } + ], + "GB0096": [ + { + "Gb_type": "Should not compile partial graph (STORE_ATTR)", + "Context": "", + "Explanation": "Dynamo has determined when encountering an unsupported STORE_ATTR instruction (i.e. `obj.attr = val`) that it should not compile the partial graph.", + "Hints": [] + } + ], + "GB5748": [ + { + "Gb_type": "autograd.grad with external GradientEdge", + "Context": "context", + "Explanation": "torch.autograd.grad() cannot be used with GradientEdge inputs passed from outside the compiled region. The GradientEdge contains a reference to an autograd node that was created before torch.compile started tracing, so Dynamo cannot trace through its computation.", + "Hints": [ + "Move the autograd.grad() call outside the torch.compile region.", + "Or use tensor inputs directly instead of GradientEdge objects.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "autograd.grad with external GradientEdge", + "Context": "", + "Explanation": "torch.autograd.grad() cannot be used with GradientEdge inputs passed from outside the compiled region. The GradientEdge contains an autograd node that was created outside the compiled region boundary.", + "Hints": [ + "Move the autograd.grad() call outside the torch.compile region.", + "Or use tensor inputs directly instead of GradientEdge objects.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0097": [ + { + "Gb_type": "Side effect on existing deque with limited maxlen", + "Context": "", + "Explanation": "This is not supported.", + "Hints": [ + "Don't use a deque with `maxlen` specified." + ] + } + ], + "GB0098": [ + { + "Gb_type": "Skip calling `torch.compiler.disable()`d function", + "Context": "str(self.value)", + "Explanation": "Skip calling function `{self.value}` since it was wrapped with `torch.compiler.disable` (reason: {msg})", + "Hints": [ + "Remove the `torch.compiler.disable` call" + ] + } + ], + "GB0099": [ + { + "Gb_type": "Skip inlining `torch.compiler.disable()`d function", + "Context": "str(func.get_function())", + "Explanation": "Skip inlining function {func.get_function()} since it was wrapped with `torch.compiler.disable` (reason: {msg})", + "Hints": [ + "Remove the `torch.compiler.disable` call" + ] + } + ], + "GB0100": [ + { + "Gb_type": "Storing Tensor hook handle in globals", + "Context": "name", + "Explanation": "This is not supported.", + "Hints": [] + } + ], + "GB0101": [ + { + "Gb_type": "Storing Tensor hook handle in globals (inline call)", + "Context": "inst.argval", + "Explanation": "This is not supported.", + "Hints": [] + } + ], + "GB0102": [ + { + "Gb_type": "Strict mode banned op", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Getattr invocation '{name}' in strict mode is not supported.", + "Hints": [ + "Remove `{name}` from the list of banned ops by ", + "setting `torch._dynamo.config._autograd_backward_strict_mode_banned_ops`." + ] + }, + { + "Gb_type": "Strict mode banned op", + "Context": "getattro_impl {self} {name}", + "Explanation": "Getattr invocation '{name}' in strict mode is not supported.", + "Hints": [ + "Remove `{name}` from the list of banned ops by ", + "setting `torch._dynamo.config._autograd_backward_strict_mode_banned_ops`." + ] + }, + { + "Gb_type": "Strict mode banned op", + "Context": "var_getattr {self} {name}", + "Explanation": "Getattr invocation '{name}' in strict mode is not supported.", + "Hints": [ + "Remove `{name}` from the list of banned ops by ", + "setting `torch._dynamo.config._autograd_backward_strict_mode_banned_ops`." + ] + } + ], + "GB0103": [ + { + "Gb_type": "Tensor subclass overridden method call", + "Context": "{name}", + "Explanation": "`torch.compile` currently can't trace this", + "Hints": [ + "Avoid calling {name} of tensor subclass in torch.compile region", + "Renaming method `{name}` of type {self.class_type}", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0104": [ + { + "Gb_type": "Tensor with grad_fn()", + "Context": "tp_getattro_impl {self} grad_fn", + "Explanation": "Dynamo does not support tracing tensors with a grad_fn directly.", + "Hints": [] + }, + { + "Gb_type": "Tensor with grad_fn()", + "Context": "getattro_impl {self} grad_fn", + "Explanation": "Dynamo does not support tracing tensors with a grad_fn directly.", + "Hints": [] + }, + { + "Gb_type": "Tensor with grad_fn()", + "Context": "var_getattr {self} grad_fn", + "Explanation": "Dynamo does not support tracing tensors with a grad_fn directly.", + "Hints": [] + } + ], + "GB0105": [ + { + "Gb_type": "Tensor.numpy() with trace_numpy=False", + "Context": "call_method {self} numpy", + "Explanation": "`Tensor.numpy()` was called, but the `trace_numpy` configuration was manually disabled.", + "Hints": [ + "Set `torch._dynamo.config.trace_numpy = True` to allow ", + "Dynamo to trace through NumPy." + ] + } + ], + "GB0106": [ + { + "Gb_type": "Tensor.numpy() without NumPy installed", + "Context": "call_method {self} numpy", + "Explanation": "`Tensor.numpy()` was called, but the NumPy library is not available in the current environment.", + "Hints": [ + "Ensure NumPy is installed in your Python environment." + ] + } + ], + "GB0107": [ + { + "Gb_type": "Tensor.random_ op", + "Context": "Tensor.random_(args={args}, kwargs={kwargs})", + "Explanation": "This is currently not supported.", + "Hints": [ + "Use the out-of-place version of this op", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Tensor.random_ op", + "Context": "Tensor.{name}(args={args}, kwargs={kwargs})", + "Explanation": "This is currently not supported.", + "Hints": [ + "Use the out-of-place version of this op", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0108": [ + { + "Gb_type": "Tensor.retain_grad() with AOTDispatcher", + "Context": "tp_getattro_impl {self} retain_grad", + "Explanation": "`Tensor.retain_grad()` does not work with AOTDispatcher.", + "Hints": [] + }, + { + "Gb_type": "Tensor.retain_grad() with AOTDispatcher", + "Context": "getattro_impl {self} retain_grad", + "Explanation": "`Tensor.retain_grad()` does not work with AOTDispatcher.", + "Hints": [] + }, + { + "Gb_type": "Tensor.retain_grad() with AOTDispatcher", + "Context": "var_getattr {self} retain_grad", + "Explanation": "`Tensor.retain_grad()` does not work with AOTDispatcher.", + "Hints": [] + } + ], + "GB0109": [ + { + "Gb_type": "Tensor.tolist() with non-integer tensor", + "Context": "call_method {self} to_list", + "Explanation": "Dynamo currently does not support tracing `tolist()` on non-integer tensors.", + "Hints": [ + "Ensure the input tensor to `tolist()` is an integer ", + "type (e.g., int8, int16, int32, int64)." + ] + } + ], + "GB0110": [ + { + "Gb_type": "Tensor.uniform_ op called with `from` keyword", + "Context": "Tensor.uniform_(args={args}, kwargs={kwargs})", + "Explanation": "This is currently not supported.", + "Hints": [ + "Avoid using the `from` keyword.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Tensor.uniform_ op called with `from` keyword", + "Context": "Tensor.{name}(args={args}, kwargs={kwargs})", + "Explanation": "This is currently not supported.", + "Hints": [ + "Avoid using the `from` keyword.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0111": [ + { + "Gb_type": "TypeError from user code", + "Context": "call_function({self.value}, {args}, {kwargs})", + "Explanation": "msg", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0112": [ + { + "Gb_type": "TypeError when making fake tensor call", + "Context": "TypeError {node.target}: {cause}", + "Explanation": "", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "TypeError when making fake tensor call", + "Context": "TypeError {node.target}: {cause}", + "Explanation": "", + "Hints": [] + } + ], + "GB0113": [ + { + "Gb_type": "Unable to resolve super getattr", + "Context": "", + "Explanation": "Dynamo failed to trace attribute `{name}` accessed via `super()` (for type `{self.typevar}` and object `{self.objvar}`) because the resolved attribute type is not supported.", + "Hints": [ + "Ensure the attribute exists in the parent class.", + "Check the arguments passed to `super()`." + ] + } + ], + "GB0114": [ + { + "Gb_type": "Unexpected failure during itertools.accumulate() iteration", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Unexpected failure in invoking function during accumulate. Failed running func {func}({item}{acc})", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0115": [ + { + "Gb_type": "Unexpected failure during itertools.groupby() iteration", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Unexpected failure in invoking function during groupby", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4778": [ + { + "Gb_type": "nested function with non-constructible closure in output", + "Context": "as_python_constant for out_spec {out_spec}", + "Explanation": "Cannot return a nested function with closure from a compiled function. Dynamo failed to construct the function defined in the compiled region with closure objects.", + "Hints": [ + "Define the function at module scope instead of inside another function ", + "Ensure that all closure variables are constants." + ] + }, + { + "Gb_type": "nested function with closure in output", + "Context": "as_python_constant for out_spec", + "Explanation": "Cannot return a nested function with closure from a compiled function. Dynamo cannot reconstruct the function.", + "Hints": [ + "Define the function at module scope instead of inside another function" + ] + } + ], + "GB1752": [ + { + "Gb_type": "Missing tp_iteritem", + "Context": "_tp_iteritem on {self.python_type_name()}", + "Explanation": "Dynamo does not support virtual iteration on {self.python_type_name()}. Add tp_iteritem_impl to this VariableTracker subclass.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB6441": [ + { + "Gb_type": "unsupported torch.cuda.MemPool attribute", + "Context": "torch.cuda.MemPool.{name}", + "Explanation": "Dynamo only supports reading torch.cuda.MemPool.id.", + "Hints": [] + } + ], + "GB0116": [ + { + "Gb_type": "Unexpected type in sourceless builder", + "Context": "{value_type.__module__}.{value_type.__qualname__}", + "Explanation": "SourcelessBuilder.create does not know how to wrap {value_type}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0117": [ + { + "Gb_type": "Unhandled args for method", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo encountered an error while calling the method `{name}`.", + "Hints": [] + } + ], + "GB7650": [ + { + "Gb_type": "torch.Generator method", + "Context": "torch.Generator.{name}", + "Explanation": "torch.Generator.{name}() is a stateful RNG operation that cannot be soundly traced in the FX graph.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0118": [ + { + "Gb_type": "Unimplemented next() call", + "Context": "next({self})", + "Explanation": "This abstract method must be implemented", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB1576": [ + { + "Gb_type": "COW tensor check on Python tensor subclass", + "Context": "torch._C._is_cow_tensor on Python tensor subclass", + "Explanation": "Dynamo cannot safely evaluate COW state for Python tensor subclasses because their storage semantics are controlled by __torch_dispatch__.", + "Hints": [ + "Avoid checking COW state on tensor subclasses inside ", + "torch.compile regions." + ] + } + ], + "GB0119": [ + { + "Gb_type": "Uninitialized nn.Module", + "Context": "typestr(value)", + "Explanation": "Attempted to trace an uninitialized nn.Module of type {typestr(value)}.", + "Hints": [ + "Ensure your nn.Module instance has called `super().__init__()`.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0120": [ + { + "Gb_type": "Unreachable sub-generator code", + "Context": "", + "Explanation": "Should only be encountered while implementing generator support.", + "Hints": [] + } + ], + "GB0121": [ + { + "Gb_type": "UnspecializedNNModuleVariable missing method", + "Context": "call_method: {self} {name} {args} {kwargs}", + "Explanation": "Dynamo does not support tracing method {name} of nn.Module {self.value}", + "Hints": [ + "Dynamo does not really define unspecialized nn.Module very well.", + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0122": [ + { + "Gb_type": "Unsupported SourceType", + "Context": "MutationType.__init__ {self} {typ}", + "Explanation": "Dynamo does not support the type `{typ}`", + "Hints": [ + "This branch is not supposed to be reachable.", + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0123": [ + { + "Gb_type": "Unsupported Tensor.backward() call", + "Context": "call_method {self} backward {gradient} {retain_graph} {create_graph} {inputs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.backward()` when trace_autograd_ops is off.", + "Hints": [ + "Set torch._dynamo.trace_autograd_ops=True" + ] + }, + { + "Gb_type": "Unsupported Tensor.backward() call", + "Context": "call_method {self} backward {gradient} {retain_graph} {create_graph} {inputs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.backward()`.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB5976": [ + { + "Gb_type": "Data pointer comparison", + "Context": "tp_richcompare_impl {self} {op} {other}", + "Explanation": "Dynamo can only trace data pointer comparisons when it can prove both operands have the same data pointer.", + "Hints": [] + }, + { + "Gb_type": "Data pointer comparison", + "Context": "richcompare_impl {self} {op} {other}", + "Explanation": "Dynamo can only trace data pointer comparisons when it can prove both operands have the same data pointer.", + "Hints": [] + }, + { + "Gb_type": "Data pointer comparison", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo can only trace data pointer comparisons when it can prove both operands have the same data pointer.", + "Hints": [] + } + ], + "GB4695": [ + { + "Gb_type": "torch.jit.script/freeze modules unsupported", + "Context": "str(value)", + "Explanation": "Dynamo does not support tracing into torch.jit.script or torch.jit.freeze modules because they execute in the TorchScript runtime, not Python. Replace the ScriptModule submodule with the original eager nn.Module.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0124": [ + { + "Gb_type": "Unsupported Tensor.item() call with capture_scalar_outputs=False", + "Context": "call_method {self} item {args} {kwargs}", + "Explanation": "Dynamo does not support tracing `Tensor.item()` with config.capture_scalar_outputs=False.", + "Hints": [ + "Set `torch._dynamo.config.capture_scalar_outputs = True` ", + "or `export TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS=1` ", + "to include these operations in the captured graph." + ] + } + ], + "GB0125": [ + { + "Gb_type": "Unsupported Tensor.requires_grad_() call", + "Context": "call_method {self} requires_grad_", + "Explanation": "Dynamo does not support changes to a Tensor's `requires_grad` through calling `requires_grad_()`.", + "Hints": [] + } + ], + "GB0126": [ + { + "Gb_type": "Unsupported Tensor.resize_() call", + "Context": "call_method {self} resize_ {args} {kwargs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.resize_()`.", + "Hints": [] + } + ], + "GB9528": [ + { + "Gb_type": "Attempted to reconstruct a nested function with closure which is not supported", + "Context": "str(self.fn_name)", + "Explanation": "Shouldn't reconstruct {str(self.fn_name)}, a nested function with closure", + "Hints": [ + "Define the function at module level" + ] + } + ], + "GB0127": [ + { + "Gb_type": "Unsupported Tensor.resize_as_() call", + "Context": "call_method {self} resize_as_ {args} {kwargs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.resize_as_()`.", + "Hints": [] + } + ], + "GB9186": [ + { + "Gb_type": "using `torch.autograd.grad` with `torch._dynamo.config.trace_autograd_ops=False`", + "Context": "trace_autograd_ops={config.trace_autograd_ops}", + "Explanation": "Attempted to call `torch.autograd.grad` with config `torch._dynamo.config.trace_autograd_ops` set to `False`.", + "Hints": [ + "Change `torch._dynamo.config.trace_autograd_ops` to `True`." + ] + } + ], + "GB0128": [ + { + "Gb_type": "Unsupported Tensor.set_() call", + "Context": "call_method {self} set_ {args} {kwargs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.set_()` overloads that include more than one argument.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0129": [ + { + "Gb_type": "Unsupported Tensor.sparse_resize_() call", + "Context": "call_method {self} sparse_resize_ {args} {kwargs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.sparse_resize_()`.", + "Hints": [] + } + ], + "GB0130": [ + { + "Gb_type": "Unsupported Tensor.sparse_resize_and_clear_() call", + "Context": "call_method {self} sparse_resize_and_clear_ {args} {kwargs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.sparse_resize_and_clear_()`.", + "Hints": [] + } + ], + "GB0131": [ + { + "Gb_type": "Unsupported __setitem__/__setattr__/__delitem__/__delattr__ inline attempt", + "Context": "code name: {code.co_name}, args: {args}", + "Explanation": "Attempted to inline {code.co_name} where first argument (self) is not a user-defined object.", + "Hints": [] + }, + { + "Gb_type": "Unsupported __setitem__/__setattr__ inline attempt", + "Context": "code name: {code.co_name}, args: {args}", + "Explanation": "Attempted to inline {code.co_name} where first argument (self) is not a user-defined object.", + "Hints": [] + } + ], + "GB4413": [ + { + "Gb_type": "HOP: Non-nullified side effect", + "Context": "Attribute '{name}' was not restored to its original value", + "Explanation": "Attribute '{name}' on an outer-scope object was changed from {original} to {current} inside a higher-order op subgraph. Dynamo only supports mutations that are undone before the subgraph exits (e.g., context managers that save/restore a flag). If you intentionally want this side effect, move the mutation outside of the higher-order op.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + }, + { + "Gb_type": "HOP: Non-nullified side effect", + "Context": "Attribute '{name}' was not restored to its original value", + "Explanation": "A variable from an outer scope was mutated inside a higher-order op subgraph and not restored to its original value. This is not supported. If using a context manager, ensure it fully restores the original state on exit.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0132": [ + { + "Gb_type": "Unsupported `func` in itertools.accumulate", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to get the function to use for itertools.accumulate. itertools.accumulate expects the `func` as the second argument or as a keyword argument.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4026": [ + { + "Gb_type": "triton.set_allocator not supported", + "Context": "triton.set_allocator called inside compiled region", + "Explanation": "triton.set_allocator is not supported inside torch.compile. It modifies global Triton allocator state and cannot be traced.", + "Hints": [ + "Move triton.set_allocator() outside of the torch.compile region ", + "(call it before the compiled function)." + ] + } + ], + "GB0133": [ + { + "Gb_type": "Unsupported arguments for itertools.accumulate", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace itertools.accumulate with args: {args} and kwargs: {kwargs}. itertools.accumulate expects an iterable, an optional binary function for accumulation, and an optional initial value to set the starting state.", + "Hints": [ + "Make sure the arguments to itertools.accumulate are correct.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0134": [ + { + "Gb_type": "Unsupported arguments for itertools.groupby", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace itertools.groupby with args: {args} and kwargs: {kwargs}. itertools.groupby expects an iterable to group and an optional key function to determine groupings.", + "Hints": [ + "Make sure the arguments to itertools.groupby are correct.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0135": [ + { + "Gb_type": "Unsupported attribute assignment on Exception object", + "Context": "call_setattr {self} {attr}", + "Explanation": "Dynamo does not support setting the attribute '{attr}' on tracked exception objects. Only `__context__`, `__cause__`, `__suppress_context__`, and `__traceback__` are supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Unsupported attribute assignment on Exception object", + "Context": "call_setattr {self} {name}", + "Explanation": "Dynamo does not support setting the attribute '{name}' on tracked exception objects. Only `__context__`, `__cause__`, `__suppress_context__`, and `__traceback__` are supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0136": [ + { + "Gb_type": "Unsupported attribute for range() object", + "Context": "var_getattr {self} {name}", + "Explanation": "Expected attribute to be one of {','.join(fields)} but got {name}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0137": [ + { + "Gb_type": "Unsupported attribute for slice() object", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Expected attribute to be one of {','.join(fields)} but got {name}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "Unsupported attribute for slice() object", + "Context": "getattro_impl {self} {name}", + "Explanation": "Expected attribute to be one of {','.join(fields)} but got {name}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "Unsupported attribute for slice() object", + "Context": "var_getattr {self} {name}", + "Explanation": "Expected attribute to be one of {','.join(fields)} but got {name}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0138": [ + { + "Gb_type": "Unsupported autograd.Function context `save_for_backward`", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo requires the `saved_tensors` attribute to be initialized on the `autograd.Function` context object.", + "Hints": [ + "Ensure that the `saved_tensors` attribute is properly ", + "initialized before calling `save_for_backward`. ", + "`save_for_backward` only supported on a newly constructed `torch.autograd.function.FunctionCtx`." + ] + } + ], + "GB0139": [ + { + "Gb_type": "Unsupported autograd.Function context method", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo does not support calling the method `{name}` on `autograd.Function` context objects. Supported methods are `__setattr__`, `save_for_backward`, `mark_dirty` and `mark_non_differentiable`.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0140": [ + { + "Gb_type": "Unsupported autograd.Function method", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo does not support calling the method `{name}` directly on the `torch.autograd.Function` instance. Supported methods include `apply`, `backward`, static methods, and class methods.", + "Hints": [ + "Ensure the method is decorated with `@staticmethod` ", + "or `@classmethod` if it's meant to be called on the class." + ] + } + ], + "GB1380": [ + { + "Gb_type": "Illegal __getitem__ invocation in strict mode", + "Context": "mp_subscript_impl {self} {key}", + "Explanation": "Dynamo currently does not support __getitem__ invocation in strict mode.", + "Hints": [] + } + ], + "GB4240": [ + { + "Gb_type": "unsupported __getitem__", + "Context": "mp_subscript_impl {self} {key}", + "Explanation": "Dynamo does not know how to handle __getitem__ on {self}", + "Hints": [] + } + ], + "GB0141": [ + { + "Gb_type": "Unsupported call_id() without source", + "Context": "call_id {self}", + "Explanation": "call_id() not supported for sourceless TensorVariable.", + "Hints": [] + } + ], + "GB0142": [ + { + "Gb_type": "Unsupported context manager", + "Context": "Attempted SETUP_WITH/BEFORE_WITH/LOAD_SPECIAL on {ctx}", + "Explanation": "Dynamo does not know how to enter a `{ctx.python_type_name()}` context manager.", + "Hints": [ + "Avoid using the unsupported context manager.", + "If the context manager seems like it should be supported (e.g. torch.set_grad_enabled), then ", + "it may be the case that it was created outside the compiled region, which Dynamo does not support. ", + "Supported context managers can cross graph break boundaries only if they are local non-closure ", + "variables, or are intermediate values.", + "File an issue to PyTorch. Simple context managers can potentially be supported, ", + "but note that context managers can't be supported in general" + ] + }, + { + "Gb_type": "Unsupported context manager", + "Context": "Attempted SETUP_WITH/BEFORE_WITH on {ctx}", + "Explanation": "Dynamo does not know how to enter a `{ctx.python_type_name()}` context manager.", + "Hints": [ + "Avoid using the unsupported context manager.", + "If the context manager seems like it should be supported (e.g. torch.set_grad_enabled), then ", + "it may be the case that it was created outside the compiled region, which Dynamo does not support. ", + "Supported context managers can cross graph break boundaries only if they are local non-closure ", + "variables, or are intermediate values.", + "File an issue to PyTorch. Simple context managers can potentially be supported, ", + "but note that context managers can't be supported in general" + ] + } + ], + "GB1075": [ + { + "Gb_type": "torch.scan: combine_fn mutates init or xs", + "Context": "init={init_part}, xs={xs_part}", + "Explanation": "scan only supports in-place mutation of additional_inputs (loop-invariant tensors). init is the *initial* carry only -- from step 1 on the driver feeds combine_fn's returned carry, so an in-place write to init would only affect step 0. xs[t] is a fresh, storage-disjoint slice each step, so a mutation cannot be observed by step t+1. Update the carry via the combine_fn return value; for in-place lifted buffers use additional_inputs.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0998": [ + { + "Gb_type": "source-less COW tensor check", + "Context": "torch._C._is_cow_tensor on source-less tensor", + "Explanation": "Dynamo cannot safely guard COW state for an intermediate tensor without a source.", + "Hints": [ + "Avoid checking COW state on intermediate tensors inside ", + "torch.compile regions." + ] + } + ], + "GB0143": [ + { + "Gb_type": "Unsupported conversion for slice assignment", + "Context": "call_method {self} {name} {args}", + "Explanation": "Missing dynamo support for converting {value} into a list for slice assignment.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0144": [ + { + "Gb_type": "Unsupported custom jvp", + "Context": "call_apply {self} {args} {kwargs}", + "Explanation": "Dynamo does not support tracing `torch.autograd.Function` subclasses that define a custom `jvp` method.", + "Hints": [ + "Remove the custom `jvp` method if possible.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0145": [ + { + "Gb_type": "Unsupported custom vjp", + "Context": "call_apply {self} {args} {kwargs}", + "Explanation": "Dynamo does not support tracing `torch.autograd.Function` subclasses that define a custom `vjp` method.", + "Hints": [ + "Remove the custom `vjp` method if possible.", + "Use standard `backward` instead if applicable.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0146": [ + { + "Gb_type": "Unsupported event method", + "Context": "str(name)", + "Explanation": "Dynamo doesn't support tracing the {method_name} method. We currently support wait, record, synchronize, and query.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0147": [ + { + "Gb_type": "Unsupported function call", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace the function `{self.debug_repr()}`", + "Hints": [ + "Avoid calling `{self.debug_repr()}` in your code.", + "Please report an issue to PyTorch." + ] + } + ], + "GB0148": [ + { + "Gb_type": "Unsupported function call (delayed)", + "Context": "source: {self.source}", + "Explanation": "Dynamo determined that a graph break should occur when calling `{name}`. Reason: {self.msg}", + "Hints": [] + }, + { + "Gb_type": "Unsupported function call (delayed)", + "Context": "source: {self.source}", + "Explanation": "Dynamo determined that a graph break should occur when calling `{self.source.name}`. Reason: {self.msg}", + "Hints": [] + } + ], + "GB9672": [ + { + "Gb_type": "unsupported type.__dict__['{attr_name}'].__get__ call", + "Context": "call_function {self}, args: {args}, kwargs: {kwargs}", + "Explanation": "`torch.compile` only supports calling type.__dict__['{attr_name}'].__get__ on a single constant argument (i.e. a type).", + "Hints": [ + "Make sure your call to type.__dict__['{attr_name}'].__get__ only has ", + "one positional argument (no keyword arguments).", + "Make sure the argument to type.__dict__['{attr_name}'].__get__ is a constant ", + "(i.e. type). For example, `object`, `int`, `MyCustomClass`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0149": [ + { + "Gb_type": "Unsupported functorch tracing attempt", + "Context": "", + "Explanation": "msg", + "Hints": [] + } + ], + "GB0150": [ + { + "Gb_type": "Unsupported hasattr call", + "Context": "call_obj_hasattr {self} {name}", + "Explanation": "Dynamo does not know how to trace the function `{self.debug_repr()}`", + "Hints": [ + "Avoid calling `hasattr({self.__class__.__name__}, {name})` in your code.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8587": [ + { + "Gb_type": "COW tensor check after COW-state-changing op", + "Context": "torch._C._is_cow_tensor after _lazy_clone", + "Explanation": "Dynamo cannot safely fold a COW state check after an op in the current graph may have changed that tensor's COW state.", + "Hints": [ + "Move the COW state check before _lazy_clone or outside ", + "the torch.compile region." + ] + } + ], + "GB0151": [ + { + "Gb_type": "Unsupported inspect call", + "Context": "inspect_parameter_names {self}", + "Explanation": "Dynamo does not know how to trace the function `{self.debug_repr()}`", + "Hints": [] + } + ], + "GB0152": [ + { + "Gb_type": "Unsupported key type for itertools.groupby", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace itertools.groupby with key type: {str(type(key))}. We only support grouping keys that are constants (int, float, str, etc.)", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0153": [ + { + "Gb_type": "Unsupported key type for nn.Module.__getitem__", + "Context": "mp_subscript_impl: {self} {key}", + "Explanation": "Dynamo does not support getitem on `nn.Module` with non-constant key.", + "Hints": [] + }, + { + "Gb_type": "Unsupported key type for nn.Module.__getitem__", + "Context": "call_method: {self} {name} {args} {kwargs}", + "Explanation": "Dynamo does not support getitem on `nn.Module` with non-constant key.", + "Hints": [] + } + ], + "GB4411": [ + { + "Gb_type": "missing sq_contains", + "Context": "sq_contains_impl not implemented for {self.python_type_name()}", + "Explanation": "Dynamo does not know how to check if `{item.debug_repr()}` is in `{self.debug_repr()}`.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "missing sq_contains", + "Context": "sq_contains not implemented for {self.python_type_name()}", + "Explanation": "Dynamo does not know how to check if `{item.debug_repr()}` is in `{self.debug_repr()}`.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0154": [ + { + "Gb_type": "Unsupported kwargs for itertools.accumulate", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Expected kwargs: 'initial', 'func', but got {','.join(set(kwargs.keys()) - {'initial', 'func'})}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0155": [ + { + "Gb_type": "Unsupported kwargs for itertools.groupby", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Expected kwargs: 'key', but got {','.join(set(kwargs.keys()) - {'key'})}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9522": [ + { + "Gb_type": "hasattr() on unsupported type", + "Context": "hasattr({obj}, {attr})", + "Explanation": "hasattr() is not supported on type {obj.python_type_name()}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "hasattr() on unsupported type", + "Context": "hasattr({obj}, {attr})", + "Explanation": "hasattr() is not supported on type {type(obj).__name__}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB2412": [ + { + "Gb_type": "Unsupported attribute", + "Context": "attr_unsupported {vt} {name}", + "Explanation": "{type(vt).__name__} does not support attribute '{name}'", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0156": [ + { + "Gb_type": "Unsupported method call", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace method `{name}` of class `{self.python_type_name()}`", + "Hints": [] + } + ], + "GB0157": [ + { + "Gb_type": "Unsupported ndarray attribute access", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + }, + { + "Gb_type": "Unsupported ndarray attribute access", + "Context": "getattro_impl {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + }, + { + "Gb_type": "Unsupported ndarray attribute access", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + } + ], + "GB0158": [ + { + "Gb_type": "Unsupported ndarray method call", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "`ndarray.{name}()` is not modelled in `torch._numpy`.", + "Hints": [] + } + ], + "GB0159": [ + { + "Gb_type": "Unsupported ndarray.__version__ access", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + }, + { + "Gb_type": "Unsupported ndarray.__version__ access", + "Context": "getattro_impl {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + }, + { + "Gb_type": "Unsupported ndarray.__version__ access", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + } + ], + "GB0160": [ + { + "Gb_type": "Unsupported next() call", + "Context": "next({self})", + "Explanation": "Dynamo does not know how to trace calling `next()` on variable `{self}`.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0161": [ + { + "Gb_type": "Unsupported nn.Module attribute type", + "Context": "nn.Module subclass: {typestr(base)}, name: {name}, attribute type: {typestr(subobj)}", + "Explanation": "Dynamo does not support tracing nn.Module attributes of type `{typestr(subobj)}`", + "Hints": [ + "Refactor your code so that `{name}` (type `{typestr(subobj)}`) is not an attribute of `{typestr(base)}`", + "Currently supported attribute types are methods, classmethods, staticmethods, ", + "properties, constants, and tensors.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0162": [ + { + "Gb_type": "Unsupported super().__init__() call", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo encountered a super().__init__() call on {objvar} that resolved to a `torch.nn.Module.__init__()` call that we cannot trace.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB2533": [ + { + "Gb_type": "reconstructing @contextmanager object", + "Context": "object: {value}", + "Explanation": "Returning a @contextmanager object from a compiled function is not supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB7312": [ + { + "Gb_type": "failed to bind arguments when attempting to inline", + "Context": "func='{func.get_name()}' {func.get_filename()}:{func.get_code().co_firstlineno}; args = {[arg.python_type() for arg in args]}; kwargs = {kwargs}", + "Explanation": "Argument mismatch when attempting to trace function {func.get_name()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4841": [ + { + "Gb_type": "Unsupported python_type() call", + "Context": "{obj} does not implement python_type()", + "Explanation": "This VariableTracker does not implement python_type(), which is required for object protocol operations.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB8335": [ + { + "Gb_type": "Generator reconstruction with mutations", + "Context": "mutating object: {item}", + "Explanation": "Cannot reconstruct a generator with variable mutations. Dynamo needs to fully exhaust the generator, which may cause unintended variable modifications.", + "Hints": [ + "Remove mutations from the generator.", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB2549": [ + { + "Gb_type": "infinite generator detected", + "Context": "", + "Explanation": "Dynamo traced the YIELD_VALUE bytecode too many times. This could mean that we have attempted to trace an infinite generator.", + "Hints": [ + "If you are sure that your generator is not infinite, please report a bug at {PT2_ISSUE_TRACKER_URL}.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB1177": [ + { + "Gb_type": "nn.Module mutation in HigherOrderOp", + "Context": "nn.Module: {obj}", + "Explanation": "Inplace modifying nn.Module params/buffers inside HigherOrderOps is not allowed.", + "Hints": [ + "Remove the mutation or move it outside of the HigherOrderOp.", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB6210": [ + { + "Gb_type": "leaf_function: nn.Module argument without source", + "Context": "module type: {type(arg.value).__name__}", + "Explanation": "leaf_function received an nn.Module argument that cannot be traced back to its origin. This typically happens when the module is created dynamically inside the compiled region.", + "Hints": [ + "Ensure the nn.Module is created outside the compiled function ", + "and passed as an argument.", + "If the module is a class attribute, access it via self.module_name." + ] + } + ], + "GB7637": [ + { + "Gb_type": "non-string key in object __dict__", + "Context": "key={key_value}", + "Explanation": "Dynamo expects object __dict__ keys to be strings.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB5904": [ + { + "Gb_type": "unsupported __getitem__ (sq_item)", + "Context": "sq_item_impl {self} {key}", + "Explanation": "Dynamo does not know how to handle sq_item on {self}", + "Hints": [] + } + ], + "GB0163": [ + { + "Gb_type": "Unsupported tensor subclass attribute access", + "Context": "{name}", + "Explanation": "`torch.compile` currently can't trace this", + "Hints": [ + "Avoid accessing {name} of tensor subclass in torch.compile region", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0164": [ + { + "Gb_type": "Unsupported tensor subclass overridden attribute access", + "Context": "{name}", + "Explanation": "`torch.compile` only support tracing certain types of overridden tensor subclass attributes", + "Hints": [ + "Avoid accessing {name} of tensor subclass in torch.compile region", + "Renaming attribute `{name}` of type {self.class_type}", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0569": [ + { + "Gb_type": "repr() on tensor", + "Context": "repr() on {self.python_type_name()}", + "Explanation": "Tensor repr requires actual runtime values which are not available during tracing.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0165": [ + { + "Gb_type": "Unsupported torch._C._ImperativeEngine method", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo only supports the `queue_callback` method on a torch._C._ImperativeEngine instance, but found: `{name}`.", + "Hints": [] + } + ], + "GB6276": [ + { + "Gb_type": "Comprehension analysis failed: No END_FOR", + "Context": "", + "Explanation": "Could not find END_FOR instruction in comprehension bytecode.", + "Hints": [] + } + ], + "GB9898": [ + { + "Gb_type": "Comprehension analysis failed: No matches", + "Context": "pre_store_ops={pre_store_ops}, store_targets={store_targets}, iterator_vars={iterator_vars}", + "Explanation": "Comprehension does not match any known bytecode pattern.", + "Hints": [] + }, + { + "Gb_type": "Comprehension analysis failed: No matches", + "Context": "pre_store_ops={pre_store_ops}, post_store_op={post_store_op}", + "Explanation": "Comprehension does not match any known bytecode pattern.", + "Hints": [] + } + ], + "GB0166": [ + { + "Gb_type": "Unsupported torch._C._ImperativeEngine.queue_callback()", + "Context": "call_method {self} {name}", + "Explanation": "queue_callback() is only supported when Compiled Autograd is enabled with fullgraph=True.", + "Hints": [] + } + ], + "GB0167": [ + { + "Gb_type": "Variadic function call with bad args/kwargs type", + "Context": "args type: {typestr(argsvars)}, kwargs type: {typestr(kwargsvars)}", + "Explanation": "Expected args to be a list and kwargs to be a dict", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0168": [ + { + "Gb_type": "Variadic function call with bad flags", + "Context": "flags: {inst.argval}", + "Explanation": "Attempted to call a variadic function (CALL_FUNCTION_EX) with bad flags {inst.argval}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB7694": [ + { + "Gb_type": "torch.switch: unsupported branch return type (constant)", + "Context": "str(ret_val)", + "Explanation": "Constants returned from branches must be int or None.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0169": [ + { + "Gb_type": "Write to immutable cell", + "Context": "cellvar: {cellvar}, value: {value}", + "Explanation": "Dynamo doesn't support writing to immutable/sourceless cell variables.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0170": [ + { + "Gb_type": "Data-dependent branching", + "Context": "attempted to jump with {value}", + "Explanation": "\"Detected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). \" \"Dynamo does not support tracing dynamic control flow.\" + trace_info", + "Hints": [] + }, + { + "Gb_type": "Data-dependent branching", + "Context": "attempted to jump with {value}", + "Explanation": "Detected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). Dynamo does not support tracing dynamic control flow.", + "Hints": [ + "Use `torch.cond` to express dynamic control flow.", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + }, + { + "Gb_type": "Data-dependent branching", + "Context": "attempted to jump with {value}", + "Explanation": "_explanation", + "Hints": [ + "Use `torch.cond` to express dynamic control flow.", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + }, + { + "Gb_type": "Data-dependent branching", + "Context": "attempted to jump with {value}", + "Explanation": "_explanation", + "Hints": [] + }, + { + "Gb_type": "_gb_type", + "Context": "attempted to jump with {value}", + "Explanation": "_explanation", + "Hints": [] + } + ], + "GB0171": [ + { + "Gb_type": "assert with non-string message", + "Context": "str(args)", + "Explanation": "Dynamo only supports asserts with string messages", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0172": [ + { + "Gb_type": "async_op=True for distributed collectives", + "Context": "{self.fn}, args={args}, kwargs={kwargs}", + "Explanation": "`torch.compile` doesn't support `async_op=True for {self.fn}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0173": [ + { + "Gb_type": "backward_state does not support export", + "Context": "", + "Explanation": "Compiled autograd doesn't work with `torch.export`.", + "Hints": [] + } + ], + "GB0174": [ + { + "Gb_type": "bad args to builtin cast()", + "Context": "got args {args} {kwargs}", + "Explanation": "Dynamo expects exactly 2 args to builtin cast().", + "Hints": [ + "Ensure your call to cast() has exactly 2 arguments." + ] + } + ], + "GB0175": [ + { + "Gb_type": "builtin isinstance() cannot determine type of argument", + "Context": "isinstance({arg}, {isinstance_type_var})", + "Explanation": "Dynamo doesn't have a rule to determine the type of argument {arg}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + }, + { + "Gb_type": "builtin isinstance() cannot determine type of argument", + "Context": "isinstance({arg}, {isinstance_type})", + "Explanation": "Dynamo doesn't have a rule to determine the type of argument {arg}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0176": [ + { + "Gb_type": "call_id() without associated real value", + "Context": "call_id {self}", + "Explanation": "Dynamo could not find an associated real value for the tensor.", + "Hints": [] + } + ], + "GB0177": [ + { + "Gb_type": "can't handle functions not implemented in python ", + "Context": "{fn}", + "Explanation": "Dynamo can only handle functions defined in python", + "Hints": [ + "Move usage of this function out of `torch.compile` region", + "Avoid using `tensor.is_inference()` and `torch.is_inference_mode_enabled()` in your compile code. This is primarily used in conjunction with `torch.inference_mode`. Consider using `torch.no_grad` instead because `torch.no_grad` leads to same improvements as `inference_mode` when `torch.compile` is used." + ] + } + ], + "GB0178": [ + { + "Gb_type": "constant fold exception", + "Context": "attempted to run function {fn} with arguments {args}", + "Explanation": "Encountered exception when attempting to constant fold.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0179": [ + { + "Gb_type": "copy.deepcopy()", + "Context": "copy.deepcopy({x})", + "Explanation": "Dynamo does not support copy.deepcopy()", + "Hints": [ + "Avoid calling copy.deepcopy()", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0180": [ + { + "Gb_type": "dataclass fields failure", + "Context": "obj: {obj}; variable type: {type(obj)}", + "Explanation": "Dataclass fields handling fails for {obj}. Expected it to be a user-defined object.", + "Hints": [] + } + ], + "GB0181": [ + { + "Gb_type": "dtype mismatch between tensor and its gradient", + "Context": "tensor dtype: {value.dtype}; grad dtype: {grad_str}", + "Explanation": "Inconsistent dtype between tensor and its gradient. This can happen in FSDP and crashes meta tensor creation.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "dtype mismatch between tensor and its gradient", + "Context": "tensor dtype: {value.dtype}; grad dtype: {safe_grad(value).dtype}", + "Explanation": "Inconsistent dtype between tensor and its gradient. This can happen in FSDP and crashes meta tensor creation.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0182": [ + { + "Gb_type": "failed to broadcast when attempting Tensor comparison op", + "Context": "{op.__name__}({left}, {right})", + "Explanation": "Dynamo was unable to broad cast the arguments {left}, {right} when attempting to trace the comparison op {op.__name__}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0183": [ + { + "Gb_type": "failed to call dict.fromkeys()", + "Context": "{user_cls.__name__}.fromkeys(): {args} {kwargs}", + "Explanation": "Failed to call {user_cls.__name__}.fromkeys() because arguments could not be automatically converted to a list, or some dict key is not hashable.", + "Hints": [ + "Manually convert the argument to a list.", + "Ensure all keys are hashable." + ] + } + ], + "GB7489": [ + { + "Gb_type": "Unsupported argument type in tensor method call", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo could not create a proxy for an argument in the call to Tensor.{name}(). This usually means an unsupported type was passed as an argument to a tensor method.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB3840": [ + { + "Gb_type": "leaf_function without fake_fn", + "Context": "fn={fn}", + "Explanation": "The leaf_function decorator requires a fake_fn to be provided, but none was found on the decorated function.", + "Hints": [ + "Ensure the function is decorated with @leaf_function(fake_fn)" + ] + } + ], + "GB0184": [ + { + "Gb_type": "failed to call str() on user defined object", + "Context": "str(arg)", + "Explanation": "User defined object has no __str__ or __repr__ method", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9648": [ + { + "Gb_type": "Missing tp_richcompare_impl override", + "Context": "tp_richcompare_impl {self} {op}", + "Explanation": "{type(self).__name__} does not implement tp_richcompare_impl. Add a tp_richcompare_impl override to {type(self).__name__}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + }, + { + "Gb_type": "Missing richcompare_impl override", + "Context": "richcompare_impl {self} {op}", + "Explanation": "{type(self).__name__} does not implement richcompare_impl. Add a richcompare_impl override to {type(self).__name__}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0185": [ + { + "Gb_type": "failed to convert numpy.ndarray to Tensor", + "Context": "str(value)", + "Explanation": "Exception encountered when attempting to convert numpy.ndarray to Tensor", + "Hints": [] + } + ], + "GB0186": [ + { + "Gb_type": "functools.partial() with non-literal keyword", + "Context": "non-literal keyword: {k}", + "Explanation": "functools.partial() expects literal/string keywords", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB2483": [ + { + "Gb_type": "tp_str_impl not implemented", + "Context": "{type(self).__name__} has no tp_str_impl override for {self.python_type_name()}", + "Explanation": "Dynamo does not implement __str__ for {self.python_type_name()} in {type(self).__name__}.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "str_impl not implemented", + "Context": "{type(self).__name__} has no str_impl override for {self.python_type_name()}", + "Explanation": "Dynamo does not implement __str__ for {self.python_type_name()} in {type(self).__name__}.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0187": [ + { + "Gb_type": "functools.wraps", + "Context": "{fn}", + "Explanation": "`torch.compile` can't trace `functools.wraps` on functions defined outside the compile region", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1319": [ + { + "Gb_type": "Reconstruct user defined class without a source", + "Context": "Class: {var.python_type().__name__}", + "Explanation": "Cannot reconstruct an instance of {var.python_type().__name__} that escapes the compiled region. This happens when the class is defined dynamically (e.g., inside the compiled function) and the class object itself has no source that can be reconstructed. To fix this, move the class definition outside the compiled function or prevent the object from escaping the compiled region.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB5491": [ + { + "Gb_type": "Failed to mutate tensor data attribute across devices with different shape/strides", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo only supports cross-device `.data` mutation when shape and strides match", + "Hints": [ + "Don't mutate `.data` on this tensor, or move ", + "the mutation out of `torch.compile` region" + ] + } + ], + "GB0188": [ + { + "Gb_type": "getattr with no source", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Dynamo does not know how to access an attribute on an `nn.Module` instance that lacks a source. This is usually an internal error in Dynamo.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + }, + { + "Gb_type": "getattr with no source", + "Context": "getattro_impl {self} {name}", + "Explanation": "Dynamo does not know how to access an attribute on an `nn.Module` instance that lacks a source. This is usually an internal error in Dynamo.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + }, + { + "Gb_type": "getattr with no source", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo does not know how to access an attribute on an `nn.Module` instance that lacks a source. This is usually an internal error in Dynamo.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0189": [ + { + "Gb_type": "getattr() on nn.Module with pending mutation", + "Context": "getattr({self}, {name})", + "Explanation": "Intentionally graph breaking on getattr() on a nn.Module with a pending mutation", + "Hints": [] + }, + { + "Gb_type": "getattr() on nn.Module with pending mutation", + "Context": "getattr({obj}, {name}, {default})", + "Explanation": "Intentionally graph breaking on getattr() on a nn.Module with a pending mutation", + "Hints": [] + } + ], + "GB0190": [ + { + "Gb_type": "getattr() with non-constant name argument", + "Context": "getattr({obj}, {name_var}, {default})", + "Explanation": "getattr() with non-constant name argument is not supported", + "Hints": [ + "Ensure the name argument of getattr() is a string" + ] + } + ], + "GB0191": [ + { + "Gb_type": "id() with unsupported args", + "Context": "str(args)", + "Explanation": "Dynamo doesn't know how to trace id() call with args {args}", + "Hints": [ + "Supported args are Tensors, and functions/nn.Modules/user-defined objects ", + "from outside the compiled region.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1042": [ + { + "Gb_type": "backward() with in-graph created tensor", + "Context": "backward(inputs=[...]) with in-graph created tensor: {var}", + "Explanation": "backward(inputs=[...]) with tensors created inside the compiled function is not yet supported.", + "Hints": [ + "Only pass tensors that are inputs to the compiled function or captured from outside" + ] + } + ], + "GB0192": [ + { + "Gb_type": "input iterator to itertools.cycle has too many items", + "Context": "next({self})", + "Explanation": "Has reached internal Dynamo max iterator limit: {MAX_ITERATOR_LIMIT}", + "Hints": [] + } + ], + "GB0193": [ + { + "Gb_type": "invalid call to builtin op handler", + "Context": "invalid args to {self_handler}: {args} {kwargs}", + "Explanation": "Encountered TypeError when trying to handle op {fn.__name__}", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0194": [ + { + "Gb_type": "isinstance() called on user defined object with C extensions", + "Context": "isinstance({arg}, {isinstance_type})", + "Explanation": "User-defined object with C extensions can have torch.Tensor attributes; intentionally graph breaking.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0195": [ + { + "Gb_type": "issubclass() with non-constant arguments", + "Context": "issubclass({left_ty}, {right_ty})", + "Explanation": "issubclass() with non-constant arguments not supported.", + "Hints": [ + "Make sure your arguments are types.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0196": [ + { + "Gb_type": "key not found in dict", + "Context": "Key {arg.value}", + "Explanation": "msg", + "Hints": [ + "Check if the key exists in the dictionary before accessing it.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB1739": [ + { + "Gb_type": "Unsupported member type on OpaqueObject", + "Context": "value={real_obj}, attr={name}, member_type={member_type}", + "Explanation": "Member type '{member_type}' is not supported for this operation.", + "Hints": [] + } + ], + "GB0197": [ + { + "Gb_type": "list elements are pointing to the list itself", + "Context": "", + "Explanation": "Dynamo does not support lists whose items reference to itself", + "Hints": [ + "Avoid using self referential list" + ] + } + ], + "GB0198": [ + { + "Gb_type": "mapping proxy affected by dictionary mutation", + "Context": "Source: {self.source}, Dict mutation detected", + "Explanation": "msg", + "Hints": [ + "Avoid modifying dictionaries that might be referenced by mapping proxy objects", + "Or avoid using the mapping proxy objects after modifying its underlying dictionary" + ] + } + ], + "GB0199": [ + { + "Gb_type": "mapping proxy cannot be reconstructed", + "Context": "Source: {self.source}", + "Explanation": "msg", + "Hints": [ + "Use a mapping proxy constructed in the same `torch.compile` region.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9192": [ + { + "Gb_type": "Unsupported kwargs for itertools.zip_longest", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Expected kwargs: 'fillvalue', but got {','.join(set(kwargs.keys()) - {'fillvalue'})}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0200": [ + { + "Gb_type": "missing BUILD_SET handler", + "Context": "", + "Explanation": "Missing BUILD_SET bytecode handler (for testing purposes).", + "Hints": [] + } + ], + "GB6215": [ + { + "Gb_type": "Unresolved GetAttrVariable comparison", + "Context": "tp_richcompare_impl {self} {op}", + "Explanation": "Cannot compare {self} because the attribute could not be resolved to a concrete value.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Unresolved GetAttrVariable comparison", + "Context": "richcompare_impl {self} {op}", + "Explanation": "Cannot compare {self} because the attribute could not be resolved to a concrete value.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8843": [ + { + "Gb_type": "Opaque object member with method-type USE_REAL returned a reference-type opaque object.", + "Context": "Opaque object type: {real_obj_type}. Method name: '{name}'", + "Explanation": "To properly guard reference-type opaque objects, we must lift them as inputs to the graph. In order to do this, they must all have a source, meaning they come from a global value or are an attribute of an input.", + "Hints": [ + "Register member '{name}' with MemberType.INLINED in ", + "register_custom_class({real_obj_type}, members=...)." + ] + }, + { + "Gb_type": "Opaque object member with method-type USE_REAL returned a reference-type opaque object.", + "Context": "Opaque object type: {value_type}. Method name: '{name}'", + "Explanation": "To properly guard reference-type opaque objects, we must lift them as inputs to the graph. In order to do this, they must all have a source, meaning they come from a global value or are an attribute of an input.", + "Hints": [ + "Register member '{name}' with MemberType.INLINED in ", + "register_custom_class({value_type}, members=...)." + ] + } + ], + "GB0201": [ + { + "Gb_type": "namedtuple construction", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "`torch.compile` only support certain input types for namedtuple", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0202": [ + { + "Gb_type": "non-const argument in nn.Module method", + "Context": "call_method: {self} {name} {args} {kwargs}", + "Explanation": "Dynamo does not support calling method `{name}` of ``nn.Module`` {module} with non-constant arguments.", + "Hints": [] + } + ], + "GB4393": [ + { + "Gb_type": "issubclass() with unsupported arguments", + "Context": "issubclass({derived}, {cls})", + "Explanation": "Arguments to issubclass() must be backed by python values.", + "Hints": [ + "Make sure your arguments are types.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0203": [ + { + "Gb_type": "non-const keys in dict_keys", + "Context": "non-const keys: {[k for k in value if not ConstantVariable.is_literal(k)]}", + "Explanation": "Dynamo expects dict_keys keys to be constants.", + "Hints": [ + "Ensure your dict_keys keys are constants (e.g. int, float, strings)" + ] + } + ], + "GB0204": [ + { + "Gb_type": "non-const keys in mappingproxy", + "Context": "non-const keys: {[k for k in value.keys() if not ConstantVariable.is_literal(k)]}", + "Explanation": "Dynamo expects mappingproxy keys to be constants.", + "Hints": [ + "Ensure your mappingproxy keys are constants (e.g. int, float, strings)" + ] + } + ], + "GB0205": [ + { + "Gb_type": "proxy not set", + "Context": "as_proxy {self}", + "Explanation": "Dynamo requires the autograd.Function context to be initialized with a proxy.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB6183": [ + { + "Gb_type": "torch.map: f mutates a captured tensor", + "Context": "freevars={freevars_mutated}", + "Explanation": "map only supports in-place mutation of xs. A tensor captured from the enclosing scope (lifted parameter) is loop-invariant: every iteration sees the same tensor, so a mutation makes iterations depend on each other, breaking map's independence contract and introducing a data race under any parallel lowering. Pass the buffer through xs, or use scan / while_loop if sequential buffer updates are required.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9198": [ + { + "Gb_type": "Attempted to call repr() method implemented in C/C++", + "Context": "", + "Explanation": "{type(arg.value)} has a C/C++ based repr method. This is not supported.", + "Hints": [ + "Write the repr method in Python" + ] + } + ], + "GB0206": [ + { + "Gb_type": "setattr() on Tensor.requires_grad", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "setattr() on Tensor.requires_grad not supported. Mutating requires_grad can introduce a new leaf from non-leaf or vice versa in the middle of the graph, which AOTAutograd does not currently know how to handle.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0207": [ + { + "Gb_type": "sort with non-constant keys", + "Context": "str(self.key)", + "Explanation": "Cannot perform sort whose key comparison is not a compile-time constant. Key type: {self.key.python_type()}. Most notably, we cannot sort with Tensor or SymInt keys, but we can sort ints.", + "Hints": [ + "Use something else as the key.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "sort with non-constant keys", + "Context": "str(first_non_constant_key)", + "Explanation": "Cannot perform sort with non-constant key. First non-constant key type: {python_type}. Most notably, we cannot sort with Tensor or SymInt keys, but we can sort ints.", + "Hints": [ + "Use something else as the key." + ] + } + ], + "GB0208": [ + { + "Gb_type": "torch.* op returned non-Tensor", + "Context": "example_value type: {typestr(example_value)}; op: {proxy.node.op}; target: {proxy.node.target}", + "Explanation": "torch.* ops that return a non-Tensor cannot be traced into the Dynamo FX graph output", + "Hints": [] + } + ], + "GB2520": [ + { + "Gb_type": "assume_constant_result argument conversion failed", + "Context": "function {name}, variable type {type(x).__name__}", + "Explanation": "Cannot convert argument of type {type(x).__name__} to a Python constant for function {name} marked with torch._dynamo.assume_constant_result. The variable tracker does not support constant conversion.", + "Hints": [ + "Remove torch._dynamo.assume_constant_result from this function", + "Ensure all arguments passed to the function can be converted to constants" + ] + } + ], + "GB0781": [ + { + "Gb_type": "unsupported __setitem__ (sq_ass_item)", + "Context": "sq_ass_item_impl {self} {key} {value}", + "Explanation": "Dynamo does not know how to handle sq_ass_item on {self}", + "Hints": [] + } + ], + "GB0209": [ + { + "Gb_type": "torch.autograd._unsafe_preserve_version_counter escaped from compiled region", + "Context": "str(self)", + "Explanation": "Dynamo doesn't support compiling a region that returns a torch.autograd._unsafe_preserve_version_counter context manager.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0210": [ + { + "Gb_type": "torch.distributed package is not available!", + "Context": "", + "Explanation": "The PyTorch package doesn't include torch.distributed when building from source.", + "Hints": [ + "Set USE_DISTRIBUTED=1 to enable it when building PyTorch from source." + ] + } + ], + "GB2977": [ + { + "Gb_type": "wrap_jit_function: missing _torchdynamo_inline", + "Context": "type: {type(value).__name__}", + "Explanation": "Dynamo expected a JIT function with a _torchdynamo_inline attribute, but the object does not have one.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0211": [ + { + "Gb_type": "torch.nn.Module with a non-function custom __getattr__", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Dynamo detected a nn.Module object with a custom `__getattr__` method, but this method is not a standard Python function (e.g., it might be implemented in C/C++). Dynamo cannot currently trace into such non-standard `__getattr__` methods.", + "Hints": [ + "Avoid using objects with non-standard __getattr__ methods ", + "within the compiled region. If possible, implement ", + "__getattr__ as a standard Python function.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "torch.nn.Module with a non-function custom __getattr__", + "Context": "getattro_impl {self} {name}", + "Explanation": "Dynamo detected a nn.Module object with a custom `__getattr__` method, but this method is not a standard Python function (e.g., it might be implemented in C/C++). Dynamo cannot currently trace into such non-standard `__getattr__` methods.", + "Hints": [ + "Avoid using objects with non-standard __getattr__ methods ", + "within the compiled region. If possible, implement ", + "__getattr__ as a standard Python function.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "torch.nn.Module with a non-function custom __getattr__", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo detected a nn.Module object with a custom `__getattr__` method, but this method is not a standard Python function (e.g., it might be implemented in C/C++). Dynamo cannot currently trace into such non-standard `__getattr__` methods.", + "Hints": [ + "Avoid using objects with non-standard __getattr__ methods ", + "within the compiled region. If possible, implement ", + "__getattr__ as a standard Python function.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0212": [ + { + "Gb_type": "torch.profiler object escaped from compiled region", + "Context": "str(self)", + "Explanation": "Dynamo doesn't support compiling a region that returns a torch.profiler context manager.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0213": [ + { + "Gb_type": "unimplemented builtin op on tensor arguments", + "Context": "partial tensor op: {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace builtin operator {self.fn} with tensor arguments", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0214": [ + { + "Gb_type": "unsupported SymNode comparison op", + "Context": "{op.__name__}({left}, {right})", + "Explanation": "Dynamo does not support the comparison op {op.__name__} with SymNode arguments {left}, {right}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0215": [ + { + "Gb_type": "unsupported Tensor comparison op", + "Context": "{op.__name__}({left}, {right})", + "Explanation": "Dynamo does not support the comparison op {op.__name__} with Tensor arguments {left}, {right}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0216": [ + { + "Gb_type": "unsupported grid type for triton hop check_grid", + "Context": "grid type = {type(grid)}", + "Explanation": "`torch.compile` only supports list-like grid for check_grid", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9458": [ + { + "Gb_type": "sq_repeat_impl not implemented", + "Context": "{type(self).__name__} has sq_repeat slot but no sq_repeat_impl override", + "Explanation": "The type {self.python_type_name()} has an sq_repeat C slot but the corresponding VariableTracker doesn't implement sq_repeat_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9561": [ + { + "Gb_type": "sq_inplace_repeat_impl not implemented", + "Context": "{type(self).__name__} has sq_inplace_repeat slot but no sq_inplace_repeat_impl override", + "Explanation": "The type {self.python_type_name()} has an sq_inplace_repeat C slot but the corresponding VariableTracker doesn't implement sq_inplace_repeat_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0217": [ + { + "Gb_type": "unsupported hasattr operation", + "Context": "Class {cls}", + "Explanation": "msg", + "Hints": [ + "Consider using a regular dictionary instead", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0218": [ + { + "Gb_type": "unsupported index(Tensor)", + "Context": "", + "Explanation": "Dynamo does not support tracing builtin index() on a Tensor", + "Hints": [] + } + ], + "GB0219": [ + { + "Gb_type": "Backend compiler exception", + "Context": "Backend: {name}\nException:{str(e)}\nTraceback:\n{self.root_tx.format_frame_summary()}", + "Explanation": "Backend compiler `{name}` failed with {str(e)}. Adding a graph break.", + "Hints": [ + "Report an issue to the backend compiler repo." + ] + } + ], + "GB0220": [ + { + "Gb_type": "Failed to mutate tensor data attribute to different dtype", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo only supports mutating `.data` of tensor to a new one with the same dtype", + "Hints": [ + "Don't mutate `.data` on this tensor, or move ", + "the mutation out of `torch.compile` region" + ] + }, + { + "Gb_type": "Failed to mutate tensor data attribute to different dtype", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo only supports mutating `.data` of tensor to a new one with the same dtype", + "Hints": [ + "Don't mutate `.data` on this tensor, or move ", + "the mutation out of `torch.compile` region" + ] + } + ], + "GB4271": [ + { + "Gb_type": "__class__ assignment on user-defined object", + "Context": "object={self}, value={value}", + "Explanation": "Dynamo does not support reassigning __class__ on user-defined objects.", + "Hints": [ + "Move the __class__ assignment outside of the torch.compile region." + ] + } + ], + "GB0221": [ + { + "Gb_type": "non-generator contextlib.contextmanager", + "Context": "str(self.vt.get_code())", + "Explanation": "Cannot compile function decorated with `@contextlib.contextmanager` that is not a generator, i.e. does not use `yield`", + "Hints": [ + "Use `yield` in the function body instead of `return`.", + "Remove the `@contextlib.contextmanager` decorator." + ] + } + ], + "GB0222": [ + { + "Gb_type": "Attempted to wrap a set with tensors", + "Context": "Python set containing torch.Tensor elements", + "Explanation": "Dynamo cannot trace sets of tensors. To get a stable ordering, Dynamo needs to convert the set into a list and the order might not be stable if the set contains tensors.", + "Hints": [ + "Use a dictionary where the keys are tensors.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB2669": [ + { + "Gb_type": "Comprehension graph break in resume function with captured variables", + "Context": "str(analysis.captured_vars)", + "Explanation": "Cannot use comprehension optimization inside a resume function when there are captured variables. This can cause issues with deeply nested source chains.", + "Hints": [] + } + ], + "GB0223": [ + { + "Gb_type": "torch.compile call with > 1 args", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Attempted to call `torch.compile` with > 1 args. Dynamo does not support this.", + "Hints": [ + "Remove the torch.compile call or its additional args.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0224": [ + { + "Gb_type": "Attempted to call torch in-graph function on only torch.SymInt arguments", + "Context": "fn={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Attempted to call {str(self.value)} (that should be put in the FX graph) on only torch.SymInt arguments. Dynamo does not support this.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0225": [ + { + "Gb_type": "Attempted to use tensor creation function with requires_grad=True", + "Context": "fn={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Create the tensor outside the compiled region.", + "Do not set `requires_grad=True`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0226": [ + { + "Gb_type": "`torch.nn.Parameter()` with unsupported data type", + "Context": "data={data}", + "Explanation": "Called `torch.nn.Parameter()` with non-Tensor argument.", + "Hints": [ + "Ensure the argument to `torch.nn.Parameter()` is a `torch.Tensor`.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0227": [ + { + "Gb_type": "Attempted to use torch.nn.Parameter constructor with tensor subclass", + "Context": "str(data)", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0228": [ + { + "Gb_type": "`torch.nn.Parameter`: cannot convert to traceable tracable", + "Context": "", + "Explanation": "convert_tracable_parameter is set to False.", + "Hints": [ + "Check usage of context manager: do_not_convert_to_tracable_parameter", + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0229": [ + { + "Gb_type": "Unexpected type of data placeholder op for parameter construction", + "Context": "data_node.op={data_node.op}", + "Explanation": "Data node op should be placeholder or get_attr.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0230": [ + { + "Gb_type": "Attempted to use torch.use_deterministic_algorithms(warn_only=True)", + "Context": "mode={mode}, warn_only={warn_only}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Remove param warn_only in function call torch.use_deterministic_algorithms.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9760": [ + { + "Gb_type": "torch.switch: improper operands contents", + "Context": "str(operands)", + "Explanation": "Expected `operands` to be a list/tuple of pytrees that only consists of tensor leaves.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0231": [ + { + "Gb_type": "call `torch.from_numpy` with `torch._dynamo.config.trace_numpy=False`", + "Context": "trace_numpy={config.trace_numpy}", + "Explanation": "Attempted to call `torch.from_numpy` with config `torch._dynamo.config.trace_numpy` set to `False`.", + "Hints": [ + "Change `torch._dynamo.config.trace_numpy` to `True`." + ] + } + ], + "GB6890": [ + { + "Gb_type": "Missing hash_impl override", + "Context": "hash_impl {self}", + "Explanation": "{type(self).__name__} wraps {type(real_val).__name__} which has a non-default tp_hash. Add a hash_impl override to {type(self).__name__}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB4749": [ + { + "Gb_type": "Hashability mismatch", + "Context": "raise_unhashable {arg}", + "Explanation": "Dynamo thinks {arg_type.__name__} is unhashable, but its __hash__ is not None. This likely indicates a missing or incorrect is_hashable() override.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0232": [ + { + "Gb_type": "`torch.from_numpy` with NumPy unavailable", + "Context": "", + "Explanation": "Attempted to call `torch.numpy` but NumPy could not be imported.", + "Hints": [ + "Check NumPy version and installation in your environment.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7151": [ + { + "Gb_type": "generator function over a skipped function", + "Context": "str(self.vt)", + "Explanation": "Cannot trace a generator whose underlying function is skipped by Dynamo (e.g. defined in a skip-listed module), since its body cannot be symbolically traced.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0233": [ + { + "Gb_type": "Attempted to use strided NestedTensor", + "Context": "layout={layout}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Change layout=torch.jagged.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0234": [ + { + "Gb_type": "Attempted to pop from empty torch function mode stack", + "Context": "", + "Explanation": "Called `torch._C._pop_torch_function_stack` when torch function mode stack is empty.", + "Hints": [ + "Do not pop from empty torch function mode stack.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0235": [ + { + "Gb_type": "`torch.nn.Parameter` with non-constant Tensor attributes", + "Context": "data={data}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Ensure the Tensor argument's shape, dtype, and device are correct.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0808": [ + { + "Gb_type": "vectorcall_maybe on C method descriptor", + "Context": "name={name}, type={self.python_type_name()}, method={method}", + "Explanation": "Cannot trace special method '{name}' implemented in C on user-defined type '{self.python_type_name()}'.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB6025": [ + { + "Gb_type": "Failed to trace list()", + "Context": "list({arg_types})", + "Explanation": "Dynamo does not know how to construct a list from argument types {arg_types}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0236": [ + { + "Gb_type": "Invalid input type for nonstrict_trace-ed function", + "Context": "Encountered input of type <{type_name}>.", + "Explanation": "For `nonstrict_trace`-ed functions, only basic types (e.g., torch.Tensor, int, float) or pytree containers of those are allowed as inputs. The provided argument contains an unsupported type.", + "Hints": [ + "Use one of the following to register the type with pytree:\n", + "* `torch.utils._pytree.register_constant`\n", + "* `torch.utils._pytree.register_dataclass`\n", + "* `torch.utils._pytree.register_pytree_node`" + ] + } + ], + "GB0237": [ + { + "Gb_type": "non-constant `requires_grad` argument to `torch.nn.Parameter`", + "Context": "requires_grad={requires_grad}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Change `requires_grad` to be a bool.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0238": [ + { + "Gb_type": "Input marked with `pytree.register_constant` constructed in the `torch.compile` region", + "Context": "Input={input_spec_vt}, offending type <{type_name}>.", + "Explanation": "Calling a `nonstrict_trace`-ed function with an input that contains an object of type <{type_name}>, which was marked with `pytree.register_constant`. However, the object was constructed _inside_ the `torch.compile` region. This is not supported.", + "Hints": [ + "Construct the object _outside_ the `torch.compile` region, or submit an issue to GitHub.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0467": [ + { + "Gb_type": "setattr() on unsupported type", + "Context": "setattr({obj}, {name_var}, {val})", + "Explanation": "setattr() is not supported on type {obj.python_type_name()}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "setattr() on unsupported type", + "Context": "setattr({obj}, {name_var}, {val})", + "Explanation": "setattr() is not supported on type {type(obj).__name__}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0239": [ + { + "Gb_type": "Invalid use of pytree_flatten with nonstrict_trace-ed function", + "Context": "Input={input_spec_vt}, offending type <{type_name}>.", + "Explanation": "Calling a `nonstrict_trace`-ed function where one of the inputs has been registered with a `pytree_flatten` that places an object of type <{type_name}> into the context.", + "Hints": [ + "Modifying the `pytree_flatten` to avoid placing the object into the context.", + "Apply one of the following to <{type_name}>:\n", + "* `torch.utils._pytree.register_constant`\n", + "* `torch.utils._pytree.register_dataclass`\n", + "* `torch.utils._pytree.register_pytree_node`", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0240": [ + { + "Gb_type": "Shape mismatch with out= list of tensor variants", + "Context": "fn={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Shape mismatch when calling {self.value} with `out=`. Provided `out=` shape: {saved_out_shape}. Actual shape: {fake_out.shape}.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0241": [ + { + "Gb_type": "Attempted to call op with non-contiguous `out=` list of tensors", + "Context": "self.value={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8949": [ + { + "Gb_type": "STORE_GLOBAL in non-module globals", + "Context": "name", + "Explanation": "Dynamo cannot safely replay global writes for an inlined function whose globals dict is not the registered module __dict__.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0242": [ + { + "Gb_type": "Attempted to call op with non-contiguous `out=` tensor", + "Context": "self.value={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0243": [ + { + "Gb_type": "Attempted to use `torch.nn.modules.utils._ntuple` with unsupported argument type", + "Context": "value={value}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Change use of _ntuple with argument as constant or tensor." + ] + } + ], + "GB0244": [ + { + "Gb_type": "Attempted to use `torch.nn.Parameter()` with export", + "Context": "", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Do not use `torch.nn.Parameter()` with export.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0245": [ + { + "Gb_type": "Attempted to use `nested_tensor` with non-list input", + "Context": "tensor_list={tensor_list}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Change `nested_tensor` with list input.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0246": [ + { + "Gb_type": "Attempted to use `torch.nn.functional.one_hot` with data-dependent output shape", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Explicitly set the `num_classes` param of the function call ", + "`torch.nn.functional.one_hot` to something other than -1." + ] + } + ], + "GB0247": [ + { + "Gb_type": "Shape mismatch with out= tensor variant", + "Context": "fn={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Shape mismatch when calling {self.value} with `out=`. Provided `out=` shape: {saved_out_shapes}. Actual shape: {fake_out.shape}.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0811": [ + { + "Gb_type": "missing tp_iter", + "Context": "tp_iter_impl not implemented for {self.python_type_name()}", + "Explanation": "Dynamo does not know how to iterate over `{self.debug_repr()}`.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0248": [ + { + "Gb_type": "improper torch.get_device_module arguments", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "torch.get_device_module accepts 1 optional argument `device`", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB3069": [ + { + "Gb_type": "Custom op missing fake impl during tracing", + "Context": "{node.target}", + "Explanation": "A custom operator was defined and register_fake'd inside the compiled function, then called before the register_fake side effect was applied.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0249": [ + { + "Gb_type": "bad device argument to torch.accelerator.current_stream", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "bad device argument to torch.get_device_module", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "bad device argument to torch.accelerator.current_stream", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "bad device argument to torch.get_device_module", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0250": [ + { + "Gb_type": "ndarray.astype(object)", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "`ndarray.astype('O')` or `ndarray.astype(object)` is not supported by torch.compile, as there is no equivalent to object type in torch.Tensor. This will be executed eagerly.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0251": [ + { + "Gb_type": "Unsupported output type for nonstrict_trace-ed function", + "Context": "Function: {fn.__name__}", + "Explanation": "For `nonstrict_trace`-ed functions, only basic types (e.g., torch.Tensor, int, list) are allowed as output. The result of this call contains an unsupported type.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0252": [ + { + "Gb_type": "could not find name in object's mro", + "Context": "name={name}, object type={type(self.value)}, mro={type(self.value).__mro__}", + "Explanation": "Could not find name `{name}` in mro {type(self.value).__mro__}", + "Hints": [ + "Ensure the name `{name}` is defined somewhere in {self.value}'s type hierarchy.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9860": [ + { + "Gb_type": "P2POp mutation", + "Context": "object={self}, name={name}, value={value}", + "Explanation": "Dynamo does not support mutating torch.distributed.P2POp instances.", + "Hints": [ + "Construct a new torch.distributed.P2POp instead of mutating an existing one inside torch.compile." + ] + } + ], + "GB0253": [ + { + "Gb_type": "call_method on generator", + "Context": "object={self.value}, method={name}, args={args}, kwargs={kwargs}", + "Explanation": "Detected a method call to a user-defined generator object. This is not fully supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "call_method on generator", + "Context": "object={self.value}, method={name}, args={args}, kwargs={kwargs}", + "Explanation": "Detected a method call to a user-defined generator object. This is not fully supported.", + "Hints": [ + "Set `torch._dynamo.config.enable_faithful_generator_behavior = False`. Note that this ", + "may cause silent incorrectness, since we will eagerly unpack generators instead of lazily ", + "evaluating them." + ] + } + ], + "GB0254": [ + { + "Gb_type": "non-const setattr name on user-defined object", + "Context": "object={self}, name={name}, value={value}", + "Explanation": "Detected a call to `setattr` of a user-defined object with a non-constant name.", + "Hints": [ + "Ensure that the name is a string." + ] + } + ], + "GB0255": [ + { + "Gb_type": "attempted to call sourceless user-defined object as a method", + "Context": "object={self.value}, function={func}, args={args}, kwargs={kwargs}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Ensure the user-defined object {self.value} is constructed outside the compiled region." + ] + } + ], + "GB0256": [ + { + "Gb_type": "User-defined object with non-function __getattr__", + "Context": "object={self.value}, name={name}, getattr_fn={getattr_fn}", + "Explanation": "Found a non-function __getattr__ {getattr_fn} from a user-defined object {self.value} when attempting to getattr `{name}`", + "Hints": [ + "Ensure the object's __getattr__ is a function type." + ] + } + ], + "GB0257": [ + { + "Gb_type": "TypedDict with optional keys", + "Context": "str(self.value)", + "Explanation": "Dynamo does not support tracing TypedDict with optional keys", + "Hints": [ + "Avoid using TypedDict with optional keys", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "TypedDict with optional keys", + "Context": "str(self.value)", + "Explanation": "Dynamo does not support tracing TypedDict with optional keys", + "Hints": [ + "Avoid using TypedDict with optional keys", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0258": [ + { + "Gb_type": "collections.deque() with bad arguments", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Detected call to collections.deque() with bad arguments.", + "Hints": [ + "Fix the call to collections.deque().", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0259": [ + { + "Gb_type": "collections.deque() with bad iterable argument", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Call to collections.deque() has an iterable argument that Dynamo cannot convert to a list.", + "Hints": [ + "Use a simpler sequence type that Dynamo can convert to a list ", + "(e.g. list, tuple, list iterator, etc.)", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0260": [ + { + "Gb_type": "missing args to functools.partial", + "Context": "", + "Explanation": "functools.partial requires at least one argument", + "Hints": [ + "Fix the functools.partial call.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0261": [ + { + "Gb_type": "User-defined object method with non-function __func__", + "Context": "object={self.value}, name={name}, method={dynamic_subobj}, method.__self__={dynamic_subobj.__self__}, method.__func__={dynamic_subobj.__func__}", + "Explanation": "Method {dynamic_subobj} (name={name}) of user-defined object {self.value} has a __func__ ({dynamic_subobj.__func__}) that is not a function type.", + "Hints": [ + "Ensure that the method's __func__ is a function type." + ] + } + ], + "GB4927": [ + { + "Gb_type": "autograd.grad consumed returned tensor's grad_fn", + "Context": "Leaked output tensors: {leaked_str}", + "Explanation": "torch.autograd.grad() consumes grad_fns that are needed by tensors returned from this compiled function. This would cause 'backward through graph a second time' errors.\n The following returned tensors have consumed grad_fns: {leaked_str}", + "Hints": [ + "Detach the problematic tensor(s) before returning: e.g. `{leaked[0]}.detach()`", + "Call .detach() on the tensor before returning.", + "If you need to backward through the returned tensor, use retain_graph=True in autograd.grad()." + ] + }, + { + "Gb_type": "autograd.grad consumed returned tensor's grad_fn", + "Context": "", + "Explanation": "torch.autograd.grad() consumes grad_fns that are needed by tensors returned from this compiled function. This would cause 'backward through graph a second time' errors.", + "Hints": [ + "If you don't need to backward through the returned tensor, ", + "call .detach() before returning: `return loss.detach()`", + "If you need to backward through the returned tensor, use retain_graph=True in autograd.grad()." + ] + }, + { + "Gb_type": "autograd.grad consumed returned tensor's grad_fn", + "Context": "", + "Explanation": "torch.autograd.grad() consumes grad_fns that are needed by tensors returned from this compiled function. This would cause 'backward through graph a second time' errors.", + "Hints": [ + "If you don't need to backward through the returned tensor, call .detach() before returning: `return loss.detach()`", + "If you need to backward through the returned tensor, use retain_graph=True in autograd.grad()." + ] + } + ], + "GB6663": [ + { + "Gb_type": "autograd.grad with unsupported argument type", + "Context": "got {type(var).__name__}", + "Explanation": "torch.autograd.grad() received an argument of type {type(var).__name__} which is not supported. Expected tensor or sequence of tensors.", + "Hints": [ + "Ensure outputs and inputs arguments are tensors or sequences of tensors." + ] + } + ], + "GB1381": [ + { + "Gb_type": "autograd.grad with already consumed grad_fn", + "Context": "double consumed grad_fns: {len(double_consumed)}", + "Explanation": "torch.autograd.grad() is trying to consume grad_fns that were already consumed by a previous autograd.grad() call. This would cause 'backward through graph a second time' errors at runtime.", + "Hints": [ + "Use retain_graph=True in the first autograd.grad() call if you ", + "need to compute gradients through the same graph multiple times." + ] + } + ], + "GB6297": [ + { + "Gb_type": "autograd.Function.apply: duplicate tensor input", + "Context": "", + "Explanation": "Dynamo does not support tracing autograd.Function.apply when the same tensor is passed to multiple forward inputs.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0262": [ + { + "Gb_type": "unsupported contextlib.* API", + "Context": "{self.value}", + "Explanation": "{self.value} not supported. This may be due to its use of context-specific operations that are not supported in Dynamo yet (i.e. Exception handling)", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0263": [ + { + "Gb_type": "attempted to trace contextlib.contextmanager", + "Context": "args={args}", + "Explanation": "Tracing contextlib.contextmanager is disabled.", + "Hints": [ + "Set torch._dynamo.config.enable_trace_contextlib = True" + ] + } + ], + "GB0264": [ + { + "Gb_type": "Attempted to use `torch.nn.Parameter()` constructor with Dynamo", + "Context": "", + "Explanation": "Dynamo does not support this", + "Hints": [ + "Try to construct `torch.nn.Parameter()` outside the compiled region.", + "If this is not possible, turn `graph_break_on_nn_param_ctor` off", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9840": [ + { + "Gb_type": "Can't extract message from torch._check*()", + "Context": "str(message_vt)", + "Explanation": "The message argument of torch._check*() must be a string, None, or a function.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Can't extract message from torch._check*()", + "Context": "str(message_vt)", + "Explanation": "The message argument of torch._check*() must be a string, None, or a function defined within the torch.compile region.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Can't extract message from torch._check*()", + "Context": "str(message_vt)", + "Explanation": "The message argument of torch._check*() must be a function defined within the torch.compile region.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9158": [ + { + "Gb_type": "Can't convert torch._check*() message closure", + "Context": "str(message_vt)", + "Explanation": "The message argument of torch._check*() must be a function whose closure variables are Python constants.", + "Hints": [ + "Remove closure variables that reference non-constant values, e.g. ", + "remove references to tensor `x` in `lambda: f'{x} failed check'`", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB5849": [ + { + "Gb_type": "non-constant key in object __dict__", + "Context": "key={key.vt}", + "Explanation": "Dynamo expects object __dict__ replacement keys to be constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB3241": [ + { + "Gb_type": "C-level descriptor delete on user-defined object", + "Context": "object={self}, name={name_str}, descriptor={descriptor}", + "Explanation": "Dynamo does not yet model this C-level descriptor deleter for user-defined objects.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0265": [ + { + "Gb_type": "FakeScriptObject missing method implementation", + "Context": "value={self.value}, method={name}", + "Explanation": "TorchScript object {self.value} doesn't define the method {name}.", + "Hints": [ + "Ensure the method {name} is implemented in {self.value}.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0266": [ + { + "Gb_type": "Weird method call on TorchScript object", + "Context": "value={self.value}, method={name}", + "Explanation": "This particular method call ({name}) is not supported (e.g. calling `__setattr__`). Most method calls to TorchScript objects should be supported.", + "Hints": [ + "Avoid calling this method." + ] + } + ], + "GB0267": [ + { + "Gb_type": "Attempted to access non-callable attribute of TorchScript object", + "Context": "value={self.value}, method={name}", + "Explanation": "Attribute accesses of TorchScript objects to non-callable attributes are not supported.", + "Hints": [ + "Use method calls instead of attribute access." + ] + } + ], + "GB0268": [ + { + "Gb_type": "Unsupported kwargs for itertools.product", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Expected kwargs: 'repeat', but got {','.join(set(kwargs.keys()) - {'repeat'})}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB6017": [ + { + "Gb_type": "executorch_call_delegate: first arg not supported", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "executorch_call_delegate expects the first argument to be a nn.Module (got {args[0]})", + "Hints": [] + } + ], + "GB0269": [ + { + "Gb_type": "Forced graph break on leaf function", + "Context": "", + "Explanation": "Forced graph break on non-inlining function for nested graph break testing purposes", + "Hints": [ + "Set torch._dynamo.config.debug_force_graph_break_on_leaf_return = False" + ] + }, + { + "Gb_type": "Forced graph break on leaf function", + "Context": "", + "Explanation": "Forced graph break for nested graph break testing purposes", + "Hints": [ + "Set torch._dynamo.config.debug_force_graph_break_on_leaf_return = False" + ] + } + ], + "GB0270": [ + { + "Gb_type": "unimplemented builtin op vars() with no arguments", + "Context": "vars: {self} {args}", + "Explanation": "Dynamo does not know how to trace builtin operator {self.fn} with no arguments", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0271": [ + { + "Gb_type": "Class attribute mutation when the __dict__ was already materialized", + "Context": "str(self.value)", + "Explanation": "Dynamo does not support tracing mutations on a class when its __dict__ is materialized", + "Hints": [] + }, + { + "Gb_type": "Class attribute mutation when the __dict__ was already materialized", + "Context": "str(self.value)", + "Explanation": "Dynamo does not support tracing mutations on a class when its __dict__ is materialized", + "Hints": [] + } + ], + "GB0272": [ + { + "Gb_type": "Failed to make weakref to User Object when storing by ID", + "Context": "user_objected: {obj}", + "Explanation": "Object does not allow us to make a weakref to it", + "Hints": [] + }, + { + "Gb_type": "Failed to make weakref to User Object", + "Context": "user_objected: {obj}", + "Explanation": "Object does not allow us to make a weakref to it", + "Hints": [] + } + ], + "GB0273": [ + { + "Gb_type": "Keyword args passed to exception constructor", + "Context": "{self} with kwargs {init_kwargs}", + "Explanation": "Dynamo does not know how to handle keyword args passed to an exception constructor", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0682": [ + { + "Gb_type": "Non-constant GetAttrVariable hash", + "Context": "hash_impl {self}", + "Explanation": "Cannot hash {self} because Dynamo doesn't know how to represent the type of the getattr() result, which is not a constant.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0274": [ + { + "Gb_type": "Attempted to reconstruct context manager's __enter__ method", + "Context": "str(self.ctx)", + "Explanation": "Attempted to reconstruct context manager {type_str} while tracing `with ...:`", + "Hints": [ + "It is likely there is a graph break while tracing `with ctx:` ", + "but outside the actual `ctx.__enter__()` method. ", + "`torch.compile` does not expect this to happen.", + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0275": [ + { + "Gb_type": "torch._dynamo.step_unsupported() with empty checkpoint", + "Context": "", + "Explanation": "traced torch._dynamo.step_unsupported(), but there is no checkpoint to step_graph_break from. This graph break is used for debugging only.", + "Hints": [ + "Remove the torch._dynamo.step_unsupported() call.", + "Include at least one checkpoint: (1) include at least 2 ops and (2) make sure there is some ", + "line of code that is not in a try/with block, and has an empty Python stack.", + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB2473": [ + { + "Gb_type": "torch.cuda.use_mem_pool graph break", + "Context": "str(self)", + "Explanation": "Dynamo doesn't support graph breaks inside torch.cuda.use_mem_pool.", + "Hints": [] + } + ], + "GB4996": [ + { + "Gb_type": "torch.cuda.use_mem_pool with non-constant device", + "Context": "device={device}", + "Explanation": "Dynamo requires the device argument to torch.cuda.use_mem_pool to be a Python constant.", + "Hints": [] + } + ], + "GB6604": [ + { + "Gb_type": "Missing CALL_INTRINSIC_2 handler", + "Context": "CALL_INTRINSIC_2 operand: {inst.argval}", + "Explanation": "No handler implemented for CALL_INTRINSIC_2 {inst.argval} instruction.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0276": [ + { + "Gb_type": "Failed to make weakref to User Object", + "Context": "user_object: {value}", + "Explanation": "Object does not allow us to make a weakref to it", + "Hints": [] + } + ], + "GB0277": [ + { + "Gb_type": "Attempted to wrap sparse Tensor with VariableTracker", + "Context": "context", + "Explanation": "torch.compile does not support sparse Tensors with VariableTracker", + "Hints": [ + "Sparse tensor operations are not yet fully supported in torch.compile with fullgraph=True. Consider using fullgraph=False to allow graph breaks, or move sparse tensor creation outside the compiled region." + ] + } + ], + "GB0278": [ + { + "Gb_type": "Unsupported dict type for fromkeys()", + "Context": "{user_cls.__name__}.fromkeys(): {args} {kwargs}", + "Explanation": "Failed to call {user_cls.__name__}.fromkeys() because {user_cls.__name__} is not any type of dict, OrderedDict, or defaultdict", + "Hints": [ + "Ensure {user_cls.__name__} is a type of dict, OrderedDict, or defaultdict." + ] + } + ], + "GB6622": [ + { + "Gb_type": "list_richcompare_nonconst", + "Context": "element comparison produced {type(eq_result).__name__}", + "Explanation": "Cannot determine list/tuple comparison at compile time when element comparison produces a non-constant result.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB5565": [ + { + "Gb_type": "list_richcompare_ordering_symbolic", + "Context": "lexicographic ordering with symbolic element comparison", + "Explanation": "Cannot determine list/tuple ordering at compile time when element comparison is symbolic.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB5017": [ + { + "Gb_type": "missing tp_init", + "Context": "tp_init_impl not implemented for {self.python_type_name()}", + "Explanation": "Dynamo does not know how to trace __init__ on `{self.debug_repr()}`.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0279": [ + { + "Gb_type": "torch.fx.traceback.annotate escaped from compiled region", + "Context": "str(self)", + "Explanation": "Dynamo doesn't support graph break on torch.fx.traceback.annotate.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB7324": [ + { + "Gb_type": "returning intermediate with requires_grad_()", + "Context": "graph output depends on source-less requires_grad_()", + "Explanation": "msg", + "Hints": [ + "If you only need the tensor values without gradients, ", + "call .detach() before returning.", + "Consume the gradient inside the compiled function ", + "(call backward() and use .grad), ", + "or move requires_grad_() outside torch.compile." + ] + } + ], + "GB0280": [ + { + "Gb_type": "1-arg super not implemented", + "Context": "", + "Explanation": "Dynamo failed to trace attribute `{name}` accessed via `super()` (for type `{self.typevar}` and object `{self.objvar}`) because one-argument of super() is not supported.", + "Hints": [ + "Use two-argument super(type, object_or_type)." + ] + } + ], + "GB3383": [ + { + "Gb_type": "Pydantic dataclass constructor", + "Context": "{self.value}", + "Explanation": "Dynamo graph breaks on pydantic dataclass constructors because validation mutates the instance outside traced bytecode.", + "Hints": [] + } + ], + "GB0281": [ + { + "Gb_type": "Invalid or non-const argument in nn.Module __getitem__", + "Context": "mp_subscript_impl: {self} {key}", + "Explanation": "Dynamo does not support calling method `__getitem__` of ``nn.Module`` {module} with a non-constant or non-(str, int) key.", + "Hints": [ + "Use constant arguments of type str or int for __getitem__" + ] + }, + { + "Gb_type": "Invalid or non-const argument in nn.Module __getitem__", + "Context": "call_method: {self} {name} {args} {kwargs}", + "Explanation": "Dynamo does not support calling method `{name}` of ``nn.Module`` {module} with a non-constant or non-(str, int) key.", + "Hints": [ + "Use constant arguments of type str or int for __getitem__" + ] + } + ], + "GB7685": [ + { + "Gb_type": "Attribute not found on opaque class", + "Context": "class={self.value}, attr={name}", + "Explanation": "The attribute '{name}' does not exist on opaque class {self.value}.", + "Hints": [ + "Ensure '{name}' is a valid attribute of {type(self.value)}." + ] + } + ], + "GB9567": [ + { + "Gb_type": "Unsupported descriptor on opaque class", + "Context": "class={self.value}, attr={name}, descriptor={type_name}", + "Explanation": "The attribute '{name}' is a descriptor of type '{type_name}' which is not supported.", + "Hints": [ + "Only staticmethod, property, and pybind11_static_property are supported.", + "Consider accessing this attribute outside of the compiled region." + ] + } + ], + "GB0282": [ + { + "Gb_type": "Placement with custom __getattr__ not supported", + "Context": "{value_type.__name__} with custom __getattr__", + "Explanation": "Dynamo does not support Placement types with custom __getattr__ methods", + "Hints": [ + "Use Placement types without custom __getattr__ methods", + "Move the Placement usage outside the compiled region" + ] + } + ], + "GB0283": [ + { + "Gb_type": "Failed to make weakref to graph-created external object", + "Context": "user_object: {example_value}", + "Explanation": "Object does not allow us to make a weakref to it", + "Hints": [] + } + ], + "GB0284": [ + { + "Gb_type": "cannot resume from torch._dynamo.step_unsupported()", + "Context": "", + "Explanation": "traced torch._dynamo.step_unsupported(), but Dynamo is instructed to error on graph break. This graph break is used for debugging only.", + "Hints": [ + "Remove the torch._dynamo.step_unsupported() call.", + "Make sure fullgraph=False and error_on_graph_break=False.", + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0285": [ + { + "Gb_type": "unsupported arguments to torch.accelerator.current_stream", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "torch.accelerator.current_stream accepts one optional argument `device`", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0286": [ + { + "Gb_type": "bad device argument to torch.get_device_module", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0287": [ + { + "Gb_type": "unsupported type.__dict__['__annotations__'].__get__ call", + "Context": "call_function {self}, args: {args}, kwargs: {kwargs}", + "Explanation": "`torch.compile` only supports calling type.__dict__['__annotations__'].__get__ on a single constant argument (i.e. a type).", + "Hints": [ + "Make sure your call to type.__dict__['__annotations__'] only has ", + "one positional argument (no keyword arguments).", + "Make sure the argument to type.__dict__['__annotations__'] is a constant ", + "(i.e. type). For example, `object`, `int`, `MyCustomClass`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4818": [ + { + "Gb_type": "call to a callable object with no traceable __call__", + "Context": "object={self.value}", + "Explanation": "Dynamo could not trace a Python `__call__` method on this object.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0288": [ + { + "Gb_type": "Can't extract message from torch._check()", + "Context": "str(message_vt)", + "Explanation": "The second argument of torch._check() must be a function defined within the torch.compile region that does not reference a non-local variable.", + "Hints": [ + "Make sure the message function is defined in the torch.compile region.", + "Remove any closure variables, e.g. ", + "remove references to closure variable `x` in `lambda: f'{x} failed check'`", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0289": [ + { + "Gb_type": "unsupported method call on `typing` variable", + "Context": "typing variable: {self.value}, method name: {name}, args: {args}, kwargs: {kwargs}", + "Explanation": "`torch.compile` does not support method call `{name}` on `typing` variable f{self.value}.", + "Hints": [ + "Avoid calling the {name} method on {self.value}.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4372": [ + { + "Gb_type": "autograd_function_kwonly_args", + "Context": "forward() has keyword-only args: {set(kwargs) - set(self.fn_cls.forward.__code__.co_varnames)}", + "Explanation": "autograd.Function.apply does not support keyword-only arguments in forward().", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0290": [ + { + "Gb_type": "attempted to trace numpy.* function as a method", + "Context": "numpy function: {self.value}, args: {args}, kwargs: {kwargs}", + "Explanation": "Tracing numpy.* functions as methods is not supported.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB7906": [ + { + "Gb_type": "Missing len_impl", + "Context": "len({type(self).__name__})", + "Explanation": "Dynamo does not support len() on {type(self).__name__}. Add len_impl to this VariableTracker subclass.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0291": [ + { + "Gb_type": "logging.Logger method not supported for non-export cases", + "Context": "method: {self.value}.{name}, args: {args}, kwargs: {kwargs}", + "Explanation": "For non-export cases, logging.Logger methods are only supported if the logger has a source and the method is registered as reorderable.", + "Hints": [ + "If you do not need this logging side effect, add the exact method being called to `torch._dynamo.config.ignore_logging_functions`. Dynamo will skip the call and return `None`.", + "For example, for `logger.{name}(...)`, use `torch._dynamo.config.ignore_logging_functions.add(logger.{name})`. If `{name}` is defined on the logger class, add the class method `{logger_cls_name}.{name}` to ignore this method for all instances of that class.", + "Dynamo does not trace into logging.Logger method bodies, so only the method you call directly (`{name}`) is checked against the ignore set. Ignoring a method that `{name}` calls internally has no effect.", + "If you need the log side effect to run, then you can try one of (1) create the logger outside the compiled region and add the method to `torch._dynamo.config.reorderable_logging_functions` (e.g. `torch._dynamo.config.reorderable_logging_functions.add(logger.{name})`) so that it runs after the compiled region, as long as it is called without kwargs and its arguments are tensors, constants, or string formatters, (2) `torch._higher_order_ops.print(...)`, (3) wrap the logging call in a custom op (marked as mutable), or (4) preserve the logging contents and move the logging call outside the compiled region." + ] + }, + { + "Gb_type": "logging.Logger method not supported for non-export cases", + "Context": "method: {self.value}.{name}, args: {args}, kwargs: {kwargs}", + "Explanation": "logging.Logger methods are not supported for non-export cases.", + "Hints": [ + "If you do not need this logging side effect, add the exact method being called to `torch._dynamo.config.ignore_logging_functions`. Dynamo will skip the call and return `None`.", + "For example, for `logger.{name}(...)`, use `torch._dynamo.config.ignore_logging_functions.add(logger.{name})`. If `{name}` is defined on the logger class, add the class method `{logger_cls_name}.{name}` to ignore this method for all instances of that class.", + "Dynamo does not trace into logging.Logger method bodies, so only the method you call directly (`{name}`) is checked against the ignore set. Ignoring a method that `{name}` calls internally has no effect.", + "If you need the log side effect to run, then you can try one of (1) `torch._higher_order_ops.print(...)`, (2) wrap the logging call in a custom op (marked as mutable), or (3) preserve the logging contents and move the logging call outside the compiled region." + ] + }, + { + "Gb_type": "logging.Logger method not supported for non-export cases", + "Context": "method: {self.value}.{name}, args: {args}, kwargs: {kwargs}", + "Explanation": "logging.Logger methods are not supported for non-export cases.", + "Hints": [ + "Add the logging method to `torch._dynamo.config.ignore_logging_functions`." + ] + }, + { + "Gb_type": "logging.Logger method not supported for non-export cases", + "Context": "method: {self.value}.{name}, args: {args}, kwargs: {kwargs}", + "Explanation": "logging.Logger methods are not supported for non-export cases.", + "Hints": [ + "Add the logging method to `torch._dynamo.config.ignore_logger_methods." + ] + } + ], + "GB0292": [ + { + "Gb_type": "constant-like method call with unsupported return type", + "Context": "{self._error_prefix}.{name}(*{args}, **{kwargs}) returned {result}", + "Explanation": "Attempted to call {self._error_prefix}.{name}, got unsupported return value {result}.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0293": [ + { + "Gb_type": "attempted to trace numpy function with config.trace_numpy=False", + "Context": "numpy function: {self.value}, args: {args}, kwargs: {kwargs}", + "Explanation": "Attempted to trace numpy function {self.value} while `torch._dynamo.config.trace_numpy` was set to False.", + "Hints": [ + "Set `torch._dynamo.config.trace_numpy` to True to trace numpy functions." + ] + } + ], + "GB0294": [ + { + "Gb_type": "attempted to trace numpy function unsupported by PyTorch", + "Context": "numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + "Explanation": "Can't find numpy numpy function {self.value} in torch._numpy.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0295": [ + { + "Gb_type": "cannot reconstruct NullVariable in Python < 3.11", + "Context": "", + "Explanation": "Attempted to generate PUSH_NULL instruction in Python < 3.11; where this instruction does not exist.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0296": [ + { + "Gb_type": "attempted to reorder a debugging function that can't actually be reordered", + "Context": "fn: {self.value}, args: {args}, kwargs: {kwargs}", + "Explanation": "`torch.compile` can only reorder functions that are called without keyword arguments and whose arguments are Tensors, constants, or string formatters.", + "Hints": [ + "Avoid calling the logging function {self.value} with args that are not supported." + ] + }, + { + "Gb_type": "attempted to reorder a debugging function that can't actually be reordered", + "Context": "fn: {self.value}, args: {args}, kwargs: {kwargs}", + "Explanation": "`torch.compile` can only reorder functions where the arguments are Tensors, constants, or string formatters.", + "Hints": [ + "Avoid calling the logging function {self.value} with args that are not supported." + ] + } + ], + "GB2464": [ + { + "Gb_type": "autograd.Function.apply: mark_dirty input not returned", + "Context": "", + "Explanation": "Dynamo only supports ctx.mark_dirty when each dirty input is also returned from forward.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0297": [ + { + "Gb_type": "random.Random() with improper arguments", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "random.Random() with > 1 arg or with kwargs is not supported.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0298": [ + { + "Gb_type": "attempted to trace torch._numpy.random function with config.use_numpy_random_stream=True", + "Context": "numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + "Explanation": "Attempted to trace {self.value} when `torch._dynamo.config.use_numpy_random_stream` is set to True.", + "Hints": [ + "Set `torch._dynamo.config.use_numpy_random_stream` to False.", + "Avoid calling {self.value}." + ] + } + ], + "GB0299": [ + { + "Gb_type": "constant-like method call with non-constant args", + "Context": "{self._error_prefix}.{name}(*{args}, **{kwargs})", + "Explanation": "Attempted to call {self._error_prefix}.{name} with non-constant args.", + "Hints": [ + "Ensure that the args to the method call are constant (int, str, etc.)." + ] + } + ], + "GB0300": [ + { + "Gb_type": "numpy function that produces a const collection type encountered non-const arguments", + "Context": "numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + "Explanation": "numpy function {self.value} that produces a const collection type (e.g. np.dtype, np.iinfo/np.finfo) received arguments that are not constant.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9300": [ + { + "Gb_type": "P2P compilation disabled for batch_isend_irecv", + "Context": "{self.fn}", + "Explanation": "P2P compilation is disabled.", + "Hints": [ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable." + ] + } + ], + "GB5282": [ + { + "Gb_type": "COW tensor check after mutation", + "Context": "torch._C._is_cow_tensor after tensor mutation", + "Explanation": "Dynamo cannot safely fold a COW state check after the tensor's state may have changed inside the compiled frame.", + "Hints": [ + "Move the COW state check before tensor mutations or ", + "outside the torch.compile region." + ] + } + ], + "GB2696": [ + { + "Gb_type": "P2P compilation disabled for isend/irecv", + "Context": "{self.fn}", + "Explanation": "P2P compilation is disabled.", + "Hints": [ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable." + ] + } + ], + "GB9277": [ + { + "Gb_type": "unsupported function.__get__ call", + "Context": "call_function {self}, args: {args}, kwargs: {kwargs}", + "Explanation": "Dynamo only supports function.__get__(func, obj[, cls]) where func is a user-defined function.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1750": [ + { + "Gb_type": "P2P compilation disabled for P2POp construction", + "Context": "torch.distributed.P2POp", + "Explanation": "P2P compilation is disabled.", + "Hints": [ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable." + ] + } + ], + "GB3343": [ + { + "Gb_type": "Cannot reconstruct P2POpVariable", + "Context": "P2POpVariable.reconstruct", + "Explanation": "P2POpVariable does not support reconstruction.", + "Hints": [] + } + ], + "GB0301": [ + { + "Gb_type": "HOP: non torch.Tensor leaf", + "Context": "args types: {[type(a.realize()) for a in args]}", + "Explanation": "Expected all leaves to be of torch.Tensor type.", + "Hints": [] + } + ], + "GB0302": [ + { + "Gb_type": "HOP: non-callable variable", + "Context": "arg name: {arg_name}, func_var type: {str(func_var)}", + "Explanation": "{arg_name} should be a callable but is of type {str(func_var)}.", + "Hints": [] + } + ], + "GB0303": [ + { + "Gb_type": "torch.while_loop: improper args/kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "torch.while_loop expects 4 positional arguments (got {len(args)}) and no keyword arguments (got {len(kwargs)}) Usage: while_loop(cond_fn, body_fn, operands)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0304": [ + { + "Gb_type": "torch.while_loop: improper additional_inputs", + "Context": "str(additional_inputs)", + "Explanation": "Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0305": [ + { + "Gb_type": "invalid set_subgraph_inputs and sub_kwargs settings", + "Context": "set_subgraph_inputs: {set_subgraph_inputs}, sub_kwargs: {sub_kwargs}", + "Explanation": "`sub_kwargs` cannot be used when `set_subgraph_inputs` is not set to 'automatic'.", + "Hints": [ + "Use `set_subgraph_inputs='automatic'` when passing `sub_kwargs`.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7510": [ + { + "Gb_type": "nb_positive_impl not implemented", + "Context": "{type(self).__name__} has nb_positive slot but no nb_positive_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_positive C slot but the corresponding VariableTracker doesn't implement nb_positive_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0306": [ + { + "Gb_type": "unsupported HigherOrderOperator", + "Context": "str(value)", + "Explanation": "Unable to create higher order operator variable for {value.__name__}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0307": [ + { + "Gb_type": "unsupported HigherOrderOperator function call", + "Context": "str(self.value)", + "Explanation": "Unable to trace calling higher order operator variable for {self.value.__name__}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0308": [ + { + "Gb_type": "torch.while_loop: unsupported cond_fn return type", + "Context": "str(cond_r)", + "Explanation": "Expected cond_fn to return a scalar tensor or a bool but got {cond_r_meta.shape}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4608": [ + { + "Gb_type": "richcompare identity fallback undetermined", + "Context": "generic_richcompare({v}, {w}, {op})", + "Explanation": "Cannot determine object identity for comparison fallback.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "richcompare identity fallback undetermined", + "Context": "generic_richcompare({lhs}, {rhs}, {op})", + "Explanation": "Cannot determine object identity for comparison fallback.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9316": [ + { + "Gb_type": "Comparison on compile-time-only id or hash value", + "Context": "FakeIdVariable({self.value}) {op} {type(other).__name__}", + "Explanation": "Cannot compare a compile-time-only id() or hash() value. The comparison will run eagerly.", + "Hints": [ + "Avoid comparing id() or hash() of objects created inside ", + "the compiled region against other values.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1220": [ + { + "Gb_type": "Untraceable C tp_richcompare", + "Context": "tp_richcompare_impl {self} {op}", + "Explanation": "{cls.__name__} defines a C comparison method that Dynamo cannot trace into.", + "Hints": [ + "Use torch._dynamo.allow_c_slot({cls.__name__}) to ", + "register it as safe if its comparison methods are pure ", + "and deterministic.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Untraceable C tp_richcompare", + "Context": "richcompare_impl {self} {op}", + "Explanation": "{cls.__name__} defines a C comparison method that Dynamo cannot trace into.", + "Hints": [ + "Use torch._dynamo.allow_c_slot({cls.__name__}) to ", + "register it as safe if its comparison methods are pure ", + "and deterministic.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0309": [ + { + "Gb_type": "torch.cond: improper args/kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "torch.cond expects 4 positional arguments (got {len(args)}) and no keyword arguments (got {len(kwargs)}) Usage: cond(pred, cond_fn, body_fn, operands)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB2078": [ + { + "Gb_type": "Attempted to access unregistered member on an OpaqueObject", + "Context": "value={real_obj}, attr={name}", + "Explanation": "Member '{name}' is not registered for this opaque object type.", + "Hints": [ + "Register '{name}' with a MemberType in register_custom_class(members=...)." + ] + }, + { + "Gb_type": "Attempted to access unregistered member on an OpaqueObject", + "Context": "value={self.value}, attr={name}", + "Explanation": "Member '{name}' is not registered for this opaque object type.", + "Hints": [ + "Register '{name}' with a MemberType in register_custom_class(members=...)." + ] + } + ], + "GB5458": [ + { + "Gb_type": "Custom metaclass with __getattribute__", + "Context": "type({self.value}) = {metacls}", + "Explanation": "Dynamo does not trace attribute access on classes whose metaclass overrides __getattribute__", + "Hints": [] + } + ], + "GB0310": [ + { + "Gb_type": "torch.cond: improper predicate", + "Context": "str(pred)", + "Explanation": "Expected `pred` to be a bool or a boolean tensor with a single item but got {str(type(pred))} with original python type {str(pred.python_type())}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0311": [ + { + "Gb_type": "torch.cond: improper operands", + "Context": "str(operands)", + "Explanation": "Expected `operands` to be a list/tuple but got {operands.python_type()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0312": [ + { + "Gb_type": "torch.cond: improper operands contents", + "Context": "str(operands)", + "Explanation": "Expected `operands` to be a list/tuple of pytrees that only consists of tensor leaves.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0313": [ + { + "Gb_type": "torch.cond: differing branch outputs", + "Context": "true_spec: {true_spec.treespec}, false_spec: {false_spec.treespec}, same_spec: {same_spec}", + "Explanation": "Expected branches to return the same pytree structure.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0314": [ + { + "Gb_type": "HOP body output unsupported", + "Context": "non-tensor outputs: {non_tensor_output}", + "Explanation": "HigherOrderOperator body's output must consist of tensors or ints/bools only but got {out.python_type()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4315": [ + { + "Gb_type": "RuntimeError when making fake tensor call", + "Context": "", + "Explanation": "msg", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB2922": [ + { + "Gb_type": "RuntimeError when trying to get real value from fx.Node", + "Context": "", + "Explanation": "", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB6735": [ + { + "Gb_type": "torch.library.wrap_triton call with > 1 args", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Attempted to call `wrap_triton`/`capture_triton` with > 1 args. Dynamo does not support this.", + "Hints": [ + "Remove the wrap_triton/capture_triton call or its additional args.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "torch.library.wrap_triton call with > 1 args", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Attempted to call `torch.library.wrap_triton` or `torch._library.capture_triton` with > 1 args. Dynamo does not support this.", + "Hints": [ + "Remove the wrap_triton/capture_triton call or its additional args.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0315": [ + { + "Gb_type": "torch.associative_scan: improper xs", + "Context": "str(xs)", + "Explanation": "Expected xs to be a list/tuple but got {xs.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB9625": [ + { + "Gb_type": "traceback.tb_lasti not supported", + "Context": "{self} accessing 'tb_lasti'", + "Explanation": "Dynamo does not support accessing the tb_lasti attribute of traceback objects.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0316": [ + { + "Gb_type": "torch.associative_scan: improper additional_inputs", + "Context": "str(additional_inputs)", + "Explanation": "Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0317": [ + { + "Gb_type": "torch.associative_scan: zero-sized tensor", + "Context": "str(xs_vars[0])", + "Explanation": "associative_scan() operator doesn't support zero-sized tensors during tracing.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0318": [ + { + "Gb_type": "torch.associative_scan: combine_fn improper number of leaves", + "Context": "str(_combine_treespec.as_python_constant())", + "Explanation": "combine_fn needs to produce one pytree for the output but combine_fn produces the pytree {_combine_treespec.as_python_constant()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0319": [ + { + "Gb_type": "torch.associative_scan: mismatched input/output tree structure", + "Context": "xs: {xs_treespec.as_python_constant()}, output: {_combine_treespec.as_python_constant()}", + "Explanation": "The tree structure of the xs and the outs of the combine_fn are expected to be identical, but got xs: {xs_treespec.as_python_constant()} vs output: {_combine_treespec.as_python_constant()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0320": [ + { + "Gb_type": "torch.scan: improper xs", + "Context": "str(xs)", + "Explanation": "Expected xs to be a list/tuple but got {xs.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB6815": [ + { + "Gb_type": "ContextVar mutation not supported", + "Context": "ContextVar('{self.cv_obj.name}').{name}()", + "Explanation": "ContextVar.{name}() is not yet supported inside torch.compile. Move the .{name}() call outside the compiled region.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB6066": [ + { + "Gb_type": "ContextVar.get() with non-constant default", + "Context": "ContextVar('{self.cv_obj.name}').get(...)", + "Explanation": "ContextVar.get() default argument must be a compile-time constant inside torch.compile.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0321": [ + { + "Gb_type": "torch.scan: improper init", + "Context": "str(init)", + "Explanation": "Expected init to be a list/tuple with at least one element but got {init.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0322": [ + { + "Gb_type": "torch.scan: no init leaves", + "Context": "", + "Explanation": "Expected init leaves.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB4399": [ + { + "Gb_type": "untraceable user-defined __str__", + "Context": "Could not trace __str__ override for {type(self.value).__name__}", + "Explanation": "Dynamo could not safely trace this user-defined __str__ override.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1297": [ + { + "Gb_type": "Reconstruction failure (self-referential)", + "Context": "str(self)", + "Explanation": "Dynamo tried to reconstruct sourceless variable {self}, but it is self-referential. Dynamo must manually implement reconstruction rules for self-referentiable sourceless variables.", + "Hints": [ + "If Dynamo is attempting to trace a return statement and your code is attempting to return a variable ", + "that Dynamo cannot reconstruct, then remove it from the return statement.", + "Remove the self-reference in the variable. A self-referring list, for example, is `l = []; l.append(l)`.", + "Report an issue to PyTorch if you need self-referential reconstrtuction support.", + "This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one." + ] + } + ], + "GB1501": [ + { + "Gb_type": "sparse_grad_accumulate_grad", + "Context": "accumulate_grad_ with sparse gradient", + "Explanation": "Sparse gradients are not supported in compiled autograd", + "Hints": [] + } + ], + "GB1724": [ + { + "Gb_type": "autograd.grad with non-constant dict key", + "Context": "non-constant key in {arg_name}", + "Explanation": "autograd.grad/backward dict inputs must have constant keys.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4234": [ + { + "Gb_type": "nb_invert_impl not implemented", + "Context": "{type(self).__name__} has nb_invert slot but no nb_invert_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_invert C slot but the corresponding VariableTracker doesn't implement nb_invert_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0323": [ + { + "Gb_type": "torch.scan: improper additional_inputs", + "Context": "str(additional_inputs)", + "Explanation": "Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0324": [ + { + "Gb_type": "torch.scan: zero-sized tensor", + "Context": "str(xs_vars[0])", + "Explanation": "associative_scan() operator doesn't support zero-sized tensors during tracing.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB1140": [ + { + "Gb_type": "_autograd_grad with unsupported argument type", + "Context": "got {type(var).__name__}", + "Explanation": "_autograd_grad() received an argument of type {type(var).__name__} which is not supported. Expected tensor or sequence of tensors.", + "Hints": [ + "Ensure outputs and inputs arguments are tensors or sequences of tensors." + ] + } + ], + "GB0325": [ + { + "Gb_type": "torch.map: kwargs not supported", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "torch.map expects no keyword arguments (got {len(kwargs)})", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0326": [ + { + "Gb_type": "torch.map: improper inputs", + "Context": "str(sample_shape)", + "Explanation": "torch.map doesn't support scalar or non-zero sized tensors during tracing.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB8435": [ + { + "Gb_type": "missing_mp_subscript_impl", + "Context": "mp_subscript_impl not defined for {type(self).__name__}", + "Explanation": "'{self.python_type_name()}' subscript is not yet supported by Dynamo.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8977": [ + { + "Gb_type": "Invalid call to __build_class__", + "Context": "Non-constant args to __build_class__: {args} {kwargs}", + "Explanation": "Cannot trace class definition: the class body function is unsupported or the base class argument are not compile-time constants", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0327": [ + { + "Gb_type": "executorch_call_delegate: kwargs not supported", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "executorch_call_delegate expects no keyword arguments (got {len(kwargs)})", + "Hints": [] + } + ], + "GB0328": [ + { + "Gb_type": "torch.func.functional_call capture is disabled", + "Context": "", + "Explanation": "torch.func.functional_call capture is disabled", + "Hints": [ + "Set `torch._dynamo.config.inline_inbuilt_nn_modules=True` to enable." + ] + } + ], + "GB9548": [ + { + "Gb_type": "nb_absolute_impl not implemented", + "Context": "{type(self).__name__} has nb_absolute slot but no nb_absolute_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_absolute C slot but the corresponding VariableTracker doesn't implement nb_absolute_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0329": [ + { + "Gb_type": "WrapHigherOrderVariable: kwargs unexpected", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "kwargs should have been flattened into lifted args.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0330": [ + { + "Gb_type": "wrap_with_set_grad_enabled: unexpected kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "wrap_with_set_grad_enabled expects no keyword arguments (got {len(kwargs)}).", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0331": [ + { + "Gb_type": "wrap_with_set_grad_enabled: non-constant grad_enabled", + "Context": "str(grad_enabled)", + "Explanation": "wrap_with_set_grad_enabled expects grad_enabled argument to be a constant.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0332": [ + { + "Gb_type": "wrap_with_set_grad_enabled: unexpected freevars", + "Context": "str(body_lifted_freevars)", + "Explanation": "wrap_with_set_grad_enabled expects no freevars.", + "Hints": [] + } + ], + "GB8165": [ + { + "Gb_type": "torch.switch: improper args/kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "torch.switch expects 3 positional arguments (got {len(args)}) and no keyword arguments (got {len(kwargs)}) Usage: switch(index, branches, operands)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9509": [ + { + "Gb_type": "torch.switch: improper index", + "Context": "str(index)", + "Explanation": "Expected index to be an int or a tensor with a single item but got {str(type(index))} with original python type {str(index.python_type())}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB8206": [ + { + "Gb_type": "torch.switch: improper operands", + "Context": "str(operands)", + "Explanation": "Expected operands to be a list/tuple but got {operands.python_type()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB5884": [ + { + "Gb_type": "torch.switch: improper branches", + "Context": "str(branches)", + "Explanation": "Expected branches to be a list/tuple of callables.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4307": [ + { + "Gb_type": "torch.switch: empty branches", + "Context": "str(branches)", + "Explanation": "Expected at least one branch.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7020": [ + { + "Gb_type": "COW tensor check during export", + "Context": "torch._C._is_cow_tensor during export", + "Explanation": "Dynamo cannot safely export COW-state-dependent control flow because COW state is not represented in the exported graph.", + "Hints": [ + "Avoid checking COW state inside torch.export regions." + ] + } + ], + "GB7905": [ + { + "Gb_type": "COW tensor check on FakeTensor", + "Context": "torch._C._is_cow_tensor on FakeTensor", + "Explanation": "Dynamo cannot safely evaluate COW state from a FakeTensor because COW state is not represented in FakeTensor metadata.", + "Hints": [ + "Avoid checking COW state on FakeTensors inside ", + "torch.compile regions." + ] + }, + { + "Gb_type": "COW tensor check on FakeTensor", + "Context": "torch._C._is_cow_tensor on FakeTensor", + "Explanation": "Dynamo cannot safely evaluate COW state from a FakeTensor because COW state is not represented in FakeTensor metadata.", + "Hints": [ + "Avoid checking COW state inside torch.export regions." + ] + } + ], + "GB5687": [ + { + "Gb_type": "min/max with non-constant key", + "Context": "str(keyval)", + "Explanation": "Cannot compute {self.fn.__name__}() whose key comparison is not a compile-time constant. Key type: {keyval.python_type()}. Most notably, Tensor or SymInt keys are unsupported, but ints work.", + "Hints": [ + "Use something else as the key.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9203": [ + { + "Gb_type": "torch.switch: differing branch outputs", + "Context": "branch{i}: {spec_a.treespec}, branch{i + 1}: {spec_b.treespec}, same_spec: {same_spec}", + "Explanation": "Expected branches to return the same pytree structure.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0333": [ + { + "Gb_type": "wrap_with_autocast: unexpected kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "wrap_with_autocast expects no keyword arguments (got {len(kwargs)}).", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0334": [ + { + "Gb_type": "wrap_with_autocast: unexpected freevars", + "Context": "str(body_lifted_freevars)", + "Explanation": "wrap_with_autocast expects no freevars.", + "Hints": [] + } + ], + "GB0335": [ + { + "Gb_type": "hints_wrapper: improper args/kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "hints_wrapper expects 3 positional arguments (got {len(args)}) and 1 keyword argument (got {len(kwargs)}). Usage: hints_wrapper(body_fn, args, kwargs, hints=...). args is expected to be list/tuple and kwargs is expected to be a dict.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0336": [ + { + "Gb_type": "out_dtype: unexpected kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "out_dtype expects no keyword arguments (got {len(kwargs)}).", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0337": [ + { + "Gb_type": "strict_mode: unexpected kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "strict_mode higher order op expects no keyword arguments (got {len(kwargs)}).", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0338": [ + { + "Gb_type": "invoke_subgraph: kwargs unexpected", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "kwargs should have been flattened into lifted args.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0339": [ + { + "Gb_type": "torch.while_loop: infinite loop detected", + "Context": "str(cond_r)", + "Explanation": "Infinite loop detected because while_loop's cond_fn always returns the same value {pred}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB1824": [ + { + "Gb_type": "torch.switch: unsupported branch return type", + "Context": "str(ret_val)", + "Explanation": "Expected branches to return a possibly nested pytree of tensor or constant int/None leaves.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0340": [ + { + "Gb_type": "torch.cond: unsupported branch return type", + "Context": "str(ret_val)", + "Explanation": "Expected branches to return a possibly nested pytree of tensors or constant ints.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0341": [ + { + "Gb_type": "torch.associative_scan: improper args", + "Context": "args: {args}", + "Explanation": "torch.associative_scan expects 2 positional arguments (got {len(args)}) Usage: associative_scan(combine_fn, xs)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0342": [ + { + "Gb_type": "torch.scan: improper combine_fn", + "Context": "str(combine_fn_var)", + "Explanation": "Expected combine_fn to be wrapped as functools.partial in scan user-facing api or a graph module if we're re-exporting but got {combine_fn_var.python_type()}.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0343": [ + { + "Gb_type": "torch.scan: improper combine_fn number of returns", + "Context": "str(combine_result_vars)", + "Explanation": "Expect combine_fn to return a tuple (next_carry, y) but got {combine_result_vars}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4501": [ + { + "Gb_type": "Reconstruction of FakeIdVariable", + "Context": "str(self.value)", + "Explanation": "A fake id produced by id() on a compile-time container cannot be reconstructed across a graph break.", + "Hints": [ + "Avoid using id() on containers in code that may graph-break." + ] + } + ], + "GB7786": [ + { + "Gb_type": "missing_mp_ass_subscript", + "Context": "mp_ass_subscript_impl not defined for {self.python_type_name()}", + "Explanation": "Dynamo does not yet support item assignment on '{self.python_type_name()}'.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4198": [ + { + "Gb_type": "Attempted to copy.deepcopy a tensor", + "Context": "copy.deepcopy({self})", + "Explanation": "Dynamo does not support copy.deepcopy() on tensors.", + "Hints": [ + "Avoid calling copy.deepcopy() on tensors inside compiled regions." + ] + } + ], + "GB0344": [ + { + "Gb_type": "wrap_with_autocast: expected constant arg", + "Context": "str(args)", + "Explanation": "wrap_with_autocast expects device_type, dtype, enabled, and cache_enabled arguments to be constants.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0345": [ + { + "Gb_type": "strict_mode: improper args", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "strict_mode higher order op expects flat inputs (list/tuple/dict/set)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "strict_mode: improper args", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "strict_mode higher order op expects flat inputs (list/tuple/dict)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7502": [ + { + "Gb_type": "Unsupported user-defined object construction during side-effect tracking", + "Context": "class={user_cls}, base={base_cls}, error={exc}", + "Explanation": "Dynamo could not construct an example object for side-effect replay using the class __new__ method.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB3697": [ + { + "Gb_type": "C-level descriptor setattr on user-defined object", + "Context": "object={self}, name={name_str}, descriptor={descriptor}", + "Explanation": "Dynamo does not yet model this C-level descriptor setter for user-defined objects.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB2404": [ + { + "Gb_type": "Unsupported object.__new__ user-defined class construction", + "Context": "class={self.value}, error={exc}", + "Explanation": "Dynamo could not construct an example object for side-effect replay using object.__new__.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0346": [ + { + "Gb_type": "autograd.Function.apply: non-function or method forward", + "Context": "str(fn)", + "Explanation": "Expected {method_name} to be a function or method.", + "Hints": [] + }, + { + "Gb_type": "autograd.Function.apply: non-function or method forward", + "Context": "str(self.fwd_graph)", + "Explanation": "Expected forward function to be a function or method.", + "Hints": [] + } + ], + "GB0347": [ + { + "Gb_type": "autograd.Function.apply: _materialize_non_diff_grads mutation", + "Context": "", + "Explanation": "Mutations to autograd.Function.ctx._materialize_non_diff_grads are not supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0348": [ + { + "Gb_type": "autograd.Function.apply: non-function or method backward", + "Context": "str(self.bwd_graph)", + "Explanation": "Expected backward function to be a function or method.", + "Hints": [] + } + ], + "GB8887": [ + { + "Gb_type": "NamedTupleVariable.__setattr__ bad args", + "Context": "{len(args)} args and {len(kwargs)} kwargs", + "Explanation": "Expected exactly 2 positional args for __setattr__.", + "Hints": [] + } + ], + "GB0349": [ + { + "Gb_type": "cannot unwrap variable for check_meta_consistency", + "Context": "str(var)", + "Explanation": "Expected {var} to be TensorVariable, SymNodeVariable, or ConstantVariable", + "Hints": [] + } + ], + "GB3006": [ + { + "Gb_type": "tp_as_number slot not implemented", + "Context": "{tp_slot_name}({self.python_type_name()}, {other.python_type_name()}, reverse={reverse})", + "Explanation": "The type {self.python_type_name()} does not implement the {tp_slot_name}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0350": [ + { + "Gb_type": "torch.cond: unsupported branch return type (constant non-int)", + "Context": "str(ret_val)", + "Explanation": "Constants returned from branches must be ints.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0351": [ + { + "Gb_type": "HOP body taking non-Tensor as input", + "Context": "str(sub_args)", + "Explanation": "{description} with body that accepts non-Tensors as input. Got type {a.python_type()} at index {idx}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0352": [ + { + "Gb_type": "autograd.Function.apply: non-function or method backward (2)", + "Context": "str(self.bwd_fn)", + "Explanation": "Expected backward function to be a function or method.", + "Hints": [] + }, + { + "Gb_type": "autograd.Function.apply: non-function or method backward (2)", + "Context": "str(self.bwd_graph)", + "Explanation": "Expected backward function to be a function or method.", + "Hints": [] + } + ], + "GB0353": [ + { + "Gb_type": "rewrite_signature: cannot trace optional function input", + "Context": "", + "Explanation": "Parameter {name} is optional with a default value of {param.default}. This is not supported yet.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4347": [ + { + "Gb_type": "Missing tp_iternext", + "Context": "next({self.python_type_name()})", + "Explanation": "Dynamo does not support next() on {self.python_type_name()}. Add tp_iternext_impl to this VariableTracker subclass.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0354": [ + { + "Gb_type": "failed to find name in frame builtins", + "Context": "", + "Explanation": "Failed to find name `{argval}` in frame's builtins.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB7444": [ + { + "Gb_type": "register_hook with stride-dependent code", + "Context": "Hook accesses grad metadata (e.g. is_contiguous)", + "Explanation": "register_hook callbacks that branch on gradient metadata are not supported because grad properties are unknown at trace time.", + "Hints": [] + } + ], + "GB0355": [ + { + "Gb_type": "non-single Tensor return unsupported", + "Context": "api: {api}, ret: {ret}", + "Explanation": "{api} over function that returns something other than one Tensor.", + "Hints": [] + } + ], + "GB7968": [ + { + "Gb_type": "repr() on non-constant list-like", + "Context": "repr() on {type(self).__name__} with non-constant elements", + "Explanation": "Dynamo could not safely evaluate repr() for this list-like object because one or more elements are not Python constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1584": [ + { + "Gb_type": "repr() on nested function with non-constructible closure", + "Context": "repr() on nested function {self.fn_name.as_python_constant()}: {e}", + "Explanation": "Dynamo could not safely evaluate repr() for this nested function because it could not reconstruct its closure as Python constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB5380": [ + { + "Gb_type": "repr() on non-constant set", + "Context": "repr() on {type(self).__name__} with non-constant elements", + "Explanation": "Dynamo could not safely evaluate repr() for this set because one or more elements are not Python constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB6053": [ + { + "Gb_type": "tp_repr_impl not implemented", + "Context": "{type(self).__name__} has tp_repr slot but no tp_repr_impl override", + "Explanation": "The type {self.python_type_name()} has a tp_repr C slot but the corresponding VariableTracker doesn't implement tp_repr_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "repr_impl not implemented", + "Context": "{type(self).__name__} has tp_repr slot but no repr_impl override", + "Explanation": "The type {self.python_type_name()} has a tp_repr C slot but the corresponding VariableTracker doesn't implement repr_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8315": [ + { + "Gb_type": "repr() on non-constant dict", + "Context": "repr() on {type(self).__name__} with non-constant keys or values", + "Explanation": "Dynamo could not safely evaluate repr() for this dict-like object because one or more keys or values are not Python constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1275": [ + { + "Gb_type": "repr() on non-constant dict view", + "Context": "repr() on {type(self).__name__} with non-constant backing dict", + "Explanation": "Dynamo could not safely evaluate repr() for this dict view because its backing dict could not be materialized as a Python constant.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB2852": [ + { + "Gb_type": "untraceable user-defined __repr__", + "Context": "Could not trace __repr__ override for {type(self.value).__name__}", + "Explanation": "Dynamo could not safely trace this user-defined __repr__ override.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0459": [ + { + "Gb_type": "repr() on non-constant defaultdict", + "Context": "repr() on defaultdict with non-constant default_factory or values", + "Explanation": "Dynamo could not safely evaluate repr() for this defaultdict because its default_factory or contents are not Python constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0356": [ + { + "Gb_type": "failed to handle argument for FlexAttentionBackward HOP", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "Missing Dynamo support for FlexAttentionBackward HOP argument.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB7425": [ + { + "Gb_type": "Comprehension with captured tensor not in local slot", + "Context": "", + "Explanation": "Cannot use comprehension optimization when a captured tensor variable is not stored in its expected local slot.", + "Hints": [] + } + ], + "GB0357": [ + { + "Gb_type": "UnspecializedNNModuleVariable wrapped around ScriptModules unsupported", + "Context": "str(value)", + "Explanation": "ScriptModules aren't supported in UnspecializedNNModuleVariable because their .forward function isn't a static member of their type.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB8985": [ + { + "Gb_type": "requires_grad_() intermediate leaked as output", + "Context": "call_method {self} requires_grad_", + "Explanation": "An intermediate tensor with requires_grad_() called on it (or a tensor derived from it) is returned from the compiled region. Graph breaking here to preserve partial acceleration.", + "Hints": [ + "Call .detach() before returning if you only need values.", + "Consume the gradient inside the compiled function ", + "(call backward() and use .grad), ", + "or move requires_grad_() outside torch.compile." + ] + } + ], + "GB0358": [ + { + "Gb_type": "optimizer: pending mutation on parameter", + "Context": "variable: {variable}, parameter: {p}", + "Explanation": "Pending mutations on a parameter (e.g. due to using closure) require a graph break.", + "Hints": [] + } + ], + "GB0359": [ + { + "Gb_type": "unsupported torch._C._SDPAParams attribute", + "Context": "name: {name}", + "Explanation": "Unable to fetch attribute {name} from torch._C._SDPAParams.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0360": [ + { + "Gb_type": "torch.fx.experimental.symbolic_shapes.guard_scalar branch not supported", + "Context": "expr: {expr}", + "Explanation": "Expected `expr` to be a symbolic variable or constant.", + "Hints": [] + } + ], + "GB7286": [ + { + "Gb_type": "nb_float_impl not implemented", + "Context": "{type(self).__name__} has nb_float slot but no nb_float_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_float C slot but the corresponding VariableTracker doesn't implement nb_float_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0361": [ + { + "Gb_type": "triton kernel unsupported feature", + "Context": "", + "Explanation": "Encountered triton kernel unsupported feature: {msg}", + "Hints": [] + } + ], + "GB0362": [ + { + "Gb_type": "Attempted to access attributes/methods on an OpaqueObject", + "Context": "value={self.value}, attr={name}", + "Explanation": "Attribute/method access of OpaqueObjects is not supported.", + "Hints": [ + "Use custom operators instead of direct attribute/method access." + ] + } + ], + "GB9137": [ + { + "Gb_type": "non-constant typing subscript", + "Context": "TypingVariable[{key}]", + "Explanation": "Cannot subscript typing construct {self.value} with a non-constant key.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0363": [ + { + "Gb_type": "An opaque object was created in the middle of the program.", + "Context": "Opaque object type: {self.value}.", + "Explanation": "Opaque objects cannot be created inside the torch.compile region. They must be created before entering the compiled function.", + "Hints": [ + "Please create the opaque object before calling torch.compile ", + "and pass it in as an argument or as a global variable." + ] + }, + { + "Gb_type": "An opaque object was created in the middle of the program.", + "Context": "Opaque object types: {self.value}", + "Explanation": "Opaque objects cannot be created inside the torch.compile region. They must be created before entering the compiled function.", + "Hints": [ + "Please create the opaque object before calling torch.compile ", + "and pass it in as an argument or as a global variable." + ] + } + ], + "GB0364": [ + { + "Gb_type": "User-defined object with overridden __hash__", + "Context": "hashing object of type={type(obj)} and variable tracker {vt}", + "Explanation": "Found a user-defined object {vt} with overridden __hash__ when attempting to hash it", + "Hints": [ + "Dynamo does not support hashing user-defined objects with overridden __hash__", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0365": [ + { + "Gb_type": "Dynamo cannot determine whether the underlying object is hashable", + "Context": "is_python_hashable {self}", + "Explanation": "Dynamo does not know whether the underlying python object for {self} is hashable", + "Hints": [ + "Consider using a different type of object as the dictionary key instead of {type_self}.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0366": [ + { + "Gb_type": "Dynamo cannot determine the hash of an object", + "Context": "get_python_hash {self}", + "Explanation": "Dynamo does not know the hash of the underlying python object for {self}", + "Hints": [ + "Consider using a different type of object as the dictionary key instead of {self.python_type()}.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0442": [ + { + "Gb_type": "backward() with empty inputs", + "Context": "backward(inputs=[...]) resulted in no valid leaf tensors", + "Explanation": "backward(inputs=[...]) requires at least one valid leaf tensor.", + "Hints": [ + "Ensure at least one tensor in inputs is a leaf (requires_grad=True, no grad_fn)" + ] + } + ], + "GB0367": [ + { + "Gb_type": "Dynamo cannot determine the equality comparison of an object", + "Context": "is_python_equal {self}", + "Explanation": "Dynamo does not know the equality comparison of the underlying python object for {self}", + "Hints": [ + "Consider using a different type of object as the dictionary key instead of {self.python_type()}.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0368": [ + { + "Gb_type": "Frozen dataclass with __post_init__", + "Context": "dataclass={dataclass_cls.__name__}", + "Explanation": "Cannot reconstruct frozen dataclass with __post_init__ method, as it may have side effects that would be incorrectly replayed.", + "Hints": [ + "Remove the __post_init__ method from the frozen dataclass.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0369": [ + { + "Gb_type": "Frozen dataclass with missing field", + "Context": "dataclass={dataclass_cls.__name__}, field={field.name}", + "Explanation": "Cannot reconstruct frozen dataclass: field '{field.name}' was not tracked during tracing.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0370": [ + { + "Gb_type": "record_function escaped from compiled region", + "Context": "str(self)", + "Explanation": "Dynamo doesn't support graph break inside record_function region.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB3934": [ + { + "Gb_type": "missing sq_concat", + "Context": "sq_concat not defined for {type(self).__name__}", + "Explanation": "Dynamo does not yet support concatenating '{self.python_type_name()}' and '{other.python_type_name()}'", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB2544": [ + { + "Gb_type": "missing sq_inplace_concat", + "Context": "sq_inplace_concat not defined for {type(self).__name__}", + "Explanation": "Dynamo does not yet support inplace concat of '{self.python_type_name()}' and '{other.python_type_name()}'", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0371": [ + { + "Gb_type": "autograd.grad with output that requires grad", + "Context": "context", + "Explanation": "The compiled function uses torch.autograd.grad() and returns a tensor that still requires gradients and is connected to the autograd.grad() computation. This would cause aot_autograd to attempt 'backward through graph a second time', which is not supported.", + "Hints": [ + "Call .detach() on the output tensor before returning it from the compiled function.", + "For example: `return loss.detach(), grads` instead of `return loss, grads`.", + "Or set create_graph=False in autograd.grad() if you don't need higher-order gradients.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "autograd.grad with output that requires grad", + "Context": "", + "Explanation": "The compiled function uses torch.autograd.grad() and returns a tensor that still requires gradients. This may cause aot_autograd to attempt 'backward through graph a second time', which is not supported.", + "Hints": [ + "Call .detach() on the output tensor before returning it from the compiled function.", + "For example: `return loss.detach(), grads` instead of `return loss, grads`.", + "Or set create_graph=False in autograd.grad() if you don't need higher-order gradients." + ] + } + ], + "GB0372": [ + { + "Gb_type": "autograd.grad with external grad_fn", + "Context": "context", + "Explanation": "torch.autograd.grad() cannot trace through the autograd graph because it's output depends on a tensor that was created outside the compiled region and has a grad_fn attached. The autograd graph extends beyond the compiled region boundary, which Dynamo cannot trace.", + "Hints": [ + "If you don't need gradients to flow back to the original tensor outside ", + "the compiled region, detach the input: `tensor.detach().requires_grad_(True)`.", + "Otherwise, move the autograd.grad() call outside the compiled region.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "autograd.grad with external grad_fn", + "Context": "context", + "Explanation": "torch.autograd.grad() cannot trace through the autograd graph because the '{arg_name}' argument depends on a tensor that was created outside the compiled region and has a grad_fn attached. The autograd graph extends beyond the compiled region boundary, which Dynamo cannot trace.", + "Hints": [ + "Detach the input tensor before passing to the compiled function: ", + "`tensor.detach().requires_grad_(True)` to make it a leaf tensor.", + "Or call `.detach()` on the tensor before using it in autograd.grad().", + "Or move the autograd.grad() call outside the compiled region.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "autograd.grad with external grad_fn", + "Context": "", + "Explanation": "torch.autograd.grad() cannot be used when the compiled function receives tensors with grad_fn created outside the compiled region. The autograd graph cannot extend beyond the compiled region boundary.", + "Hints": [ + "Detach the input tensor before passing to the compiled function: `tensor.detach().requires_grad_(True)` to make it a leaf tensor.", + "Or move the autograd.grad() call outside the compiled region.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0373": [ + { + "Gb_type": "autograd.grad with compiled autograd", + "Context": "compiled_autograd is currently enabled", + "Explanation": "torch.autograd.grad() inside torch.compile is not supported when compiled autograd is enabled. These two features have conflicting requirements for how the autograd graph is traced.", + "Hints": [ + "Disable compiled autograd by removing the compiled_autograd context manager.", + "Or move the autograd.grad() call outside the torch.compile region.", + "Or restructure your code so autograd.grad() and compiled_autograd don't overlap." + ] + }, + { + "Gb_type": "autograd.grad with compiled autograd", + "Context": "torch.autograd.grad()", + "Explanation": "torch.autograd.grad() inside torch.compile is not supported when compiled autograd is enabled. These two features have conflicting requirements for how the autograd graph is traced.", + "Hints": [ + "Disable compiled autograd by removing the compiled_autograd context manager.", + "Or move the autograd.grad() call outside the torch.compile region." + ] + } + ], + "GB0374": [ + { + "Gb_type": "Sparse tensor creation not supported", + "Context": "function: {fn_name}", + "Explanation": "torch.compile does not support sparse tensor creation functions like {fn_name}. Sparse tensors require specialized handling that is not yet implemented in the compiler.", + "Hints": [ + "Sparse tensor operations are not yet fully supported in torch.compile with fullgraph=True. Consider using fullgraph=False to allow graph breaks, or move sparse tensor creation outside the compiled region." + ] + } + ], + "GB0375": [ + { + "Gb_type": "Attempted to wrap a dual tensor input", + "Context": "", + "Explanation": "torch.compile does not support input tensors that carry a forward-mode AD tangent; compiled code would silently drop the tangent.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0376": [ + { + "Gb_type": "Call to `torch._dynamo.disable()`", + "Context": "Called `torch._dynamo.disable()` with args `{args}`, kwargs `{kwargs}`", + "Explanation": "`torch._dynamo.disable()` was called inside a compiled region. This API disables compilation when used as a decorator or wrapper outside the compiled region.", + "Hints": [ + "Move the `torch._dynamo.disable()` call outside the compiled function and apply it to the function that should run eagerly.", + "Use `torch._dynamo.graph_break()` to intentionally insert a graph break at this point." + ] + } + ], + "GB0377": [ + { + "Gb_type": "Call to `torch.compiler.disable()`", + "Context": "Called `torch.compiler.disable()` with args `{args}`, kwargs `{kwargs}`", + "Explanation": "`torch.compiler.disable()` was called inside a compiled region. This API disables compilation when used as a decorator or wrapper outside the compiled region.", + "Hints": [ + "Move the `torch.compiler.disable()` call outside the compiled function and apply it to the function that should run eagerly.", + "Use `torch._dynamo.graph_break()` to intentionally insert a graph break at this point." + ] + } + ], + "GB9899": [ + { + "Gb_type": "unsupported attribute of tracked type", + "Context": "{vt.python_type_name()}.{name} on {vt}", + "Explanation": "Dynamo does not support accessing `{name}` on `{vt.python_type_name()}` objects.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ] +} diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_bytecode_inputs.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_bytecode_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..a8575bc939fd02ff507d25d96602f1066f454335 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_bytecode_inputs.py @@ -0,0 +1,116 @@ +import weakref +from collections.abc import Callable +from typing import Any + +from torch._dynamo.source import Source + + +PyCodegen = Any + +# This file is to handle types that we don't want to support +# as explicit FX graph inputs. This uses a sidetable which +# we populate in bytecode and is loaded during graph execution + +# We use a dynamo-generated index as a level of indirection +# this allows us to register objects externally in pre-graph bytecode that we want +# to pass to the graph, but not support their types as graph inputs +index_to_bytecode_constructor: dict[int, Callable[[PyCodegen], None]] = {} + +index_to_external_object_weakref: dict[int, weakref.ReferenceType[Any]] = {} + +keep_alive: list[Any] = [] + + +def has_user_objects() -> bool: + return bool(index_to_bytecode_constructor) + + +def stash_graph_created_object(obj: Any) -> Any: + keep_alive.append(obj) + return obj + + +CURRENT_STREAM_INDEX = 0 + + +def set_external_object_by_index(index: int, value: Any) -> None: + """Update an entry in the external object registry at runtime.""" + keep_alive.append(value) + index_to_external_object_weakref[index] = weakref.ref(value) + + +def get_external_object_by_index(index: int) -> Any: + if index not in index_to_external_object_weakref: + raise AssertionError("Index not registered in index_to_user_object_weakref") + obj = index_to_external_object_weakref[index]() + if obj is None: + raise AssertionError("User object is no longer alive") + return index_to_external_object_weakref[index]() + + +def store_user_object_weakrefs(*args: Any) -> None: + global index_to_external_object_weakref + index_to_external_object_weakref.clear() + index_to_external_object_weakref.update( + {i: weakref.ref(arg) for i, arg in enumerate(args)} + ) + + +def reset_user_object_tracking() -> None: + index_to_bytecode_constructor.clear() + index_to_external_object_weakref.clear() + keep_alive.clear() + + +def register_graph_created_object( + example_value: Any, construct_fn: Callable[[int, PyCodegen], None] +) -> int: + global index_to_bytecode_constructor + global keep_alive + keep_alive.append(example_value) + index = len(index_to_bytecode_constructor) + index_to_bytecode_constructor[index] = lambda cg: construct_fn(index, cg) + try: + index_to_external_object_weakref[index] = weakref.ref(example_value) + except TypeError as e: + from .exc import unimplemented + + unimplemented( + gb_type="Failed to make weakref to graph-created external object", + context=f"user_object: {example_value}", + explanation="Object does not allow us to make a weakref to it", + hints=[], + from_exc=e, + ) + return index + + +# Register a user object to be used in the graph +def register_user_object(value: Any, source: Source) -> int: + global index_to_bytecode_constructor + index = len(index_to_bytecode_constructor) + index_to_bytecode_constructor[index] = lambda cg: cg(source) + try: + index_to_external_object_weakref[index] = weakref.ref(value) + except TypeError as e: + from .exc import unimplemented + + unimplemented( + gb_type="Failed to make weakref to User Object", + context=f"user_object: {value}", + explanation="Object does not allow us to make a weakref to it", + hints=[], + from_exc=e, + ) + return index + + +# Register a callback so invoke_leaf_function can retrieve nn.Module instances at runtime. +# We use a callback pattern instead of having invoke_leaf_function import get_external_object_by_index +# directly, because higher-order ops should not depend on dynamo (dynamo depends on them, not vice versa). +from torch._higher_order_ops.invoke_leaf_function import ( + set_leaf_function_module_retriever, +) + + +set_leaf_function_module_retriever(get_external_object_by_index) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_deduplication.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_deduplication.py new file mode 100644 index 0000000000000000000000000000000000000000..84d254b882c9550a31db70c34f3c33122df8dc8c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_deduplication.py @@ -0,0 +1,633 @@ +""" +This module implements graph deduplication functionality for TorchDynamo's optimization pipeline. +Graph deduplication identifies identical subgraphs in the computational graph and merges them +to reduce redundancy and improve performance. The process involves analyzing regions of the graph, +identifying structurally equivalent regions, and replacing them with a single shared implementation. +This optimization is particularly effective for models with repeated patterns or similar computational +structures across different parts of the network. +""" + +import logging +import operator +from collections import defaultdict, deque +from collections.abc import Generator, Iterable + +import torch +import torch.fx +from torch._dynamo import config +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._ordered_set import OrderedSet + +from .graph_region_tracker import Node, Region +from .graph_utils import _detect_cycles, _get_flat_args, _get_flat_args_unique + + +# Represents an index into the region +# to select a node and then +# an index into that node's +# flattened arguments +UsageIndex = tuple[int, int] + +log = logging.getLogger(__name__) + +last_node_to_additional_deps: dict[Node, OrderedSet[Node]] | None = None + + +def apply_graph_deduplication(output_graph) -> dict[str, torch.fx.GraphModule]: # type: ignore[no-untyped-def] + """ + This is the main entry point for applying the graph deduplication pass. \ +Deduplication occurs in two phases: + 1. Subgraph creation: + Subgraph creation works by taking one representative region from each region \ +group and creating a subgraph from it, which will then be used to replace all regions \ +in the group. This is implemented by first copying all nodes of the region to the new \ +subgraph and then finding all inputs which are not within the region and creating placeholders \ +for them. For the outputs, all regions in a region group need to be scanned to ensure the \ +largest set of outputs is found, and then an output node is created which returns \ +a tuple of all outputs. + + 2. Graph replacement: + To replace each region with the extracted subgraph, the node index in the region \ +and argument index within the node's flattened args and kwargs are recorded once during \ +subgraph creation. This allows us to determine which (external to the region) nodes and \ +in which order these nodes are passed as inputs. For the outputs, getitem nodes are created \ +for each output, and all nodes in the region with external outputs are replaced by the proper \ +getitem node. Finally, all original nodes are erased (there should be no uses of these \ +left in the graph). + +The deduplication mutates the output_graph argument in place. + +Returns a mapping of nodes to their subgraph output replacement node to remap outputs +when they are created in output_graph. + """ + + duplicated_region_groups = output_graph.region_tracker.get_identical_regions( + output_graph.graph + ) + node_to_mutated_arg_positions = ( + output_graph.region_tracker.node_to_mutated_arg_positions + ) + node_to_additional_deps = _populate_additional_deps( + output_graph.graph, output_graph.region_tracker.node_to_mutated_arg_positions + ) + + sub_gms: dict[str, torch.fx.GraphModule] = {} + + for region_group in duplicated_region_groups: + inds_with_external_users = _get_all_output_indices(region_group) + region = region_group[0] + ( + subgraph, + external_node_usages, + node_usage_to_tuple_elems, + ind_to_tuple_spec, + ) = _create_subgraph(region, inds_with_external_users) + + # Ignore regions with no args for now, could they possibly be evaluated at compile time? + if not list(external_node_usages): + continue + + sub_gm = torch.fx.GraphModule(output_graph.nn_modules, subgraph) + subgraph_name = output_graph.install_subgraph("subgraph", sub_gm) + sub_gms[subgraph_name] = sub_gm + with output_graph.graph.inserting_before(): + get_subgraph_node = output_graph.graph.create_node( + "get_attr", subgraph_name, (), {} + ) + + for region in region_group: + _replace_region_with_subgraph( + output_graph.graph, + region, + get_subgraph_node, + external_node_usages, + node_usage_to_tuple_elems, + ind_to_tuple_spec, + inds_with_external_users, + subgraph_name, + node_to_additional_deps, + node_to_mutated_arg_positions, + ) + + # This is to expose the updated node_to_additional_deps to tests + global last_node_to_additional_deps + last_node_to_additional_deps = node_to_additional_deps + + _stable_topological_sort( + output_graph.graph, + node_to_additional_deps, + ) + return sub_gms + + +def _replace_region_with_subgraph( + graph: torch.fx.Graph, + region: Region, + get_subgraph_node: Node, + external_node_usages: Iterable[OrderedSet[UsageIndex]], + node_usage_to_tuple_elems: dict[UsageIndex, OrderedSet[int]], + ind_to_tuple_spec: dict[int, dict[tuple[int, ...], int]], + inds_with_external_users: list[int], + subgraph_name: str, + node_to_additional_deps: dict[Node, OrderedSet[Node]], + node_to_mutated_arg_positions: dict[Node, OrderedSet[int]], +) -> None: + sub_args = [] + flattened_getitem_nodes: OrderedSet[Node] = OrderedSet() + for usages in external_node_usages: + usage = next(iter(usages)) + node_ind, usage_ind = usage + node = region[node_ind] + flattened_args_kwargs = _get_flat_args(node, {}) + for user_ind, node_usage_ind in usages: + user = region[user_ind] + if user in node_to_mutated_arg_positions: + if node_usage_ind in node_to_mutated_arg_positions[user]: + log.debug( + "NYI: Failed to substitute region %s due to mutation", region + ) + return + if usage in node_usage_to_tuple_elems: + tuple_elems = [region[i] for i in node_usage_to_tuple_elems[usage]] + flattened_getitem_nodes.update(tuple_elems) + sub_args.extend(tuple_elems) + else: + sub_args.append(flattened_args_kwargs[usage_ind]) + + # Input/Output aliasing not supported in HOPs today + # Note: we should use the nodes in the original graph (the region here) + # because we use the original traced example values for this check + if _has_aliasing( + region, sub_args, inds_with_external_users, flattened_getitem_nodes + ): + return + + invoke_args = (get_subgraph_node, subgraph_name, *sub_args) + + invoke_subgraph_node = graph.create_node( + "call_function", + torch.ops.higher_order.invoke_subgraph, + invoke_args, # type: ignore[arg-type] + {}, + ) + + ind = 0 + flattened_output_nodes: OrderedSet[Node] = OrderedSet() + for external_user_ind in inds_with_external_users: + node = region[external_user_ind] + if _is_tuple_node(node): + tuple_spec = ind_to_tuple_spec[external_user_ind] + flattened_output_nodes.update( + _replace_tuple_outputs( + node, ind, tuple_spec, invoke_subgraph_node, graph + ) + ) + ind += len(tuple_spec) + else: + subgraph_output = graph.create_node( + "call_function", operator.getitem, (invoke_subgraph_node, ind), {} + ) + node.replace_all_uses_with(subgraph_output, propagate_meta=True) + ind += 1 + + # Erase in reverse topological order + for node in reversed(region): + if node in flattened_getitem_nodes: + # Don't erase these, since they will still be used + continue + + if node not in flattened_output_nodes: + graph.erase_node(node) + + # Remove any nodes with additional deps + # This is safe; we've guaranteed that there is + # no input mutation, so all additional deps + # will be internal to the subgraph + node_to_additional_deps.pop(node, None) + for deps in node_to_additional_deps.values(): + try: + deps.remove(node) + deps.add(invoke_subgraph_node) + except KeyError: + pass + + if config.graph_deduplication_lint: + print(_detect_cycles(graph, node_to_additional_deps)) + _stable_topological_sort(graph, node_to_additional_deps) + graph.lint() + + +def _get_external_inputs( + region: Region, +) -> dict[Node, OrderedSet[UsageIndex]]: + external_node_to_usages = defaultdict[Node, OrderedSet[UsageIndex]](OrderedSet) + region_unique = set(region) + for node_ind, node in enumerate(region): + flattened_args_kwargs = _get_flat_args(node, {}) + for arg_ind, in_node in enumerate(flattened_args_kwargs): + if isinstance(in_node, Node) and in_node not in region_unique: + # in_node may occur in multiple nodes' flat_args + # track this so we can check if the arg is mutated + # Previously, we only needed to track one occurrence + # to be able to map that node to a placeholder + external_node_to_usages[in_node].add((node_ind, arg_ind)) + + return external_node_to_usages + + +def _get_all_output_indices(regions: list[Region]) -> list[int]: + # Scan all regions to get the set of all possible output nodes indices in the region + # perhaps we can record this information during region creation for more efficiency? + inds_with_external_users: set[int] = set() + for region in regions: + _get_inds_with_external_users(region, inds_with_external_users) + + return sorted(inds_with_external_users) + + +def _get_inds_with_external_users(region: Region, inds_unique: set[int]) -> None: + for ind, node in enumerate(region): + for user in node.users: + if user not in region: + if ind not in inds_unique: + inds_unique.add(ind) + + +def _create_subgraph( + region: Region, + inds_with_external_users: list[int], +) -> tuple[ + torch.fx.Graph, + list[OrderedSet[UsageIndex]], + dict[UsageIndex, OrderedSet[int]], + dict[int, dict[tuple[int, ...], int]], +]: + subgraph: torch.fx.Graph = torch.fx.Graph() + external_input_to_usages = _get_external_inputs(region) + external_node_usages = list[OrderedSet[UsageIndex]]() + region_to_subgraph_node = {} + flattened_getitem_nodes: OrderedSet[Node] = OrderedSet() + node_usage_to_tuple_elems: dict[UsageIndex, OrderedSet[int]] = {} + + for node, usage_indices in external_input_to_usages.items(): + # We don't handle tuples as inputs today + if _is_tuple_node(node): + # If a node is a tuple we will possibly create multiple placeholders for them + # and track which nodes we won't copy into the subgraph because they are flattened away + # Later, when replacing each region with this subgraph, we will create a getitem node + # externally which will perform the flattening on the outer nodes. + flattened_node_indices = _get_flattened_node_indices(node, region) + for ind in flattened_node_indices: + placeholder = subgraph.placeholder( + f"supgraph_input_{node.name}_flattened_{ind}" + ) + region_to_subgraph_node[region[ind]] = placeholder + flattened_getitem_nodes.add(region[ind]) + node_usage_to_tuple_elems[next(iter(usage_indices))] = ( + flattened_node_indices + ) + else: + placeholder = subgraph.placeholder(f"subgraph_input_{node.name}") + region_to_subgraph_node[node] = placeholder + + external_node_usages.append(usage_indices) + + def map_arg(node: Node) -> Node: + if node in region_to_subgraph_node: + return region_to_subgraph_node[node] + else: + return node + + def copy_to_subgraph(node: Node) -> Node: + subgraph_node = subgraph.node_copy(node, lambda old: map_arg(old)) + region_to_subgraph_node[node] = subgraph_node + return subgraph_node + + output_list = [] + ind_to_tuple_spec = {} + for ind, node in enumerate(region): + if node not in flattened_getitem_nodes: + subgraph_node = copy_to_subgraph(node) + if ind in inds_with_external_users: + # flatten tuple outputs by generating a getitem node tree + if _is_tuple_node(node): + getitem_nodes, ind_to_tuple_spec[ind] = _create_getitem_nodes( + node, subgraph_node, subgraph + ) + output_list.extend(getitem_nodes) + else: + output_list.append(subgraph_node) + + subgraph.output(tuple(output_list)) + + return subgraph, external_node_usages, node_usage_to_tuple_elems, ind_to_tuple_spec + + +def _stable_topological_sort_impl( + graph: torch.fx.Graph, + node_to_additional_deps: dict[Node, OrderedSet[Node]], + do_sort: bool = True, + region: OrderedSet[Node] | None = None, +) -> bool: + # Nodes are in exactly one of these four collections: + + # - Nodes in `pending` are waiting to be processed (in reverse order): + pending = list(reversed(region or graph.nodes)) + + # - Nodes in `ready` have been processed and are already in the correct + # order. When sorting a region, nodes outside the region are + # implicitly ready (filtered out in the waiting_for check below). + ready: set[Node] = set() + + # - `waiting` is a mapping from a dependency to nodes which depend on that + # dependency. + waiting = defaultdict(list) + + # - `outputs` are always at the end of the graph + outputs = OrderedSet[Node]() + + has_additional_deps = bool(node_to_additional_deps) + + # The cursor indicates the last processed node so we can add new nodes + # after it. + cursor = None + while pending: + node = pending.pop() + + if node.op == "output": + outputs.add(node) + if node.users: + raise AssertionError("output nodes should have no users") + continue + + # node._input_nodes is maintained by FX and already contains the + # unique set of input nodes — avoid rebuilding it via map_arg. + if has_additional_deps: + deps = _get_flat_args_unique(node, node_to_additional_deps) + else: + deps = node._input_nodes + + last_unready = None + for x in deps: + if x not in ready and (region is None or x in region): + last_unready = x + if last_unready is not None: + # We have unprocessed input nodes. Wait for the last unready + # arg so an already sorted list will only recheck this node once. + waiting[last_unready].append(node) + else: + ready.add(node) + if cursor and cursor.next is not node and do_sort: + cursor.append(node) + cursor = node + # Mark the nodes that have been waiting for this node to finish as + # ready to check again. + pending.extend(reversed(waiting.pop(node, ()))) + + ready.update(outputs) + expected_len = len(region) if region is not None else len(graph.nodes) + return not waiting and len(ready) == expected_len + + +def _stable_topological_sort( + graph: torch.fx.Graph, + node_to_additional_deps: dict[Node, OrderedSet[Node]], +) -> None: + if not _stable_topological_sort_impl(graph, node_to_additional_deps): + raise AssertionError("stable topological sort failed") + + +def _stable_topological_sort_region( + graph: torch.fx.Graph, + region: OrderedSet[Node], +) -> None: + if not _stable_topological_sort_impl(graph, {}, region=region): + raise AssertionError("stable topological sort of region failed") + + +def _has_cycle( + graph: torch.fx.Graph, + node_to_additional_deps: dict[Node, OrderedSet[Node]], +) -> bool: + return not _stable_topological_sort_impl( + graph, node_to_additional_deps, do_sort=False + ) + + +def _populate_additional_deps( + graph: torch.fx.Graph, node_to_mutated_arg_positions: dict[Node, OrderedSet[int]] +) -> dict[Node, OrderedSet[Node]]: + node_to_additional_deps: dict[Node, OrderedSet[Node]] = defaultdict(OrderedSet) + _add_mutation_dependencies(node_to_mutated_arg_positions, node_to_additional_deps) + _add_global_state_dependencies(graph, node_to_additional_deps) + return node_to_additional_deps + + +def _add_global_state_dependencies( + graph: torch.fx.Graph, node_to_additional_deps: dict[Node, OrderedSet[Node]] +) -> None: + import torch.amp + + all_nodes = list(graph.nodes) + + # These are targets of the nodes which need to stay in the same relative place in the graph + global_state_targets = {torch.amp._enter_autocast, torch.amp._exit_autocast} + all_nodes_dep_on: list[Node] = [] + + def prev_cur_nodes( + all_nodes: list[Node], + ) -> Generator[tuple[list[Node], Node], None, None]: + prev_nodes: list[Node] = [] + next_nodes = list(reversed(all_nodes)) + + while next_nodes: + cur_node = next_nodes.pop() + yield prev_nodes, cur_node + prev_nodes.append(cur_node) + + for prev_nodes, cur_node in prev_cur_nodes(all_nodes): + args_unique = _get_flat_args_unique(cur_node, {}) + new_deps = [n for n in all_nodes_dep_on if n not in args_unique] + + if new_deps: + additional_deps = node_to_additional_deps[cur_node] + additional_deps.update(new_deps) + + if cur_node.target in global_state_targets: + additional_deps = node_to_additional_deps[cur_node] + additional_deps.update(n for n in prev_nodes if n not in args_unique) + all_nodes_dep_on.append(cur_node) + + +def _add_mutation_dependencies( + node_to_mutated_arg_positions: dict[Node, OrderedSet[int]], + node_to_additional_deps: dict[Node, OrderedSet[Node]], +) -> None: + for node, indices in node_to_mutated_arg_positions.items(): + flat_args_kwargs = _get_flat_args(node, {}) + + # for all mutated args, + # add dependency on usages which occur after node to ensure + # node will always be ordered before them + # also add node as a dependency on usages which + # occur before node to ensure node is ordered after them + for index in indices: + mutated_arg = flat_args_kwargs[index] + for user in mutated_arg.users: + if user is node: + continue + + elif user < node: + node_to_additional_deps[node].add(user) + + elif user > node: + node_to_additional_deps[user].add(node) + + +def _has_aliasing( + region: Region, + inputs: list[Node], + inds_with_external_users: list[int], + flattened_getitem_nodes: OrderedSet[Node], +) -> bool: + input_storages: dict[StorageWeakRef, Node] = dict() + for node in inputs: + if node in flattened_getitem_nodes: + continue + example_value = node.meta["example_value"] + if isinstance(example_value, torch.Tensor): + storage = StorageWeakRef(example_value._typed_storage()) + if storage in input_storages: + # input-input aliasing + log.debug( + "NYI: Failed to substitute region %s due to input-output aliasing detected at nodes %s, %s", + region, + input_storages[storage], + node, + ) + return True + input_storages[storage] = node + output_storages: dict[StorageWeakRef, Node] = dict() + for i in inds_with_external_users: + out_node = region[i] + if out_node in flattened_getitem_nodes: + continue + if out_node: + example_value = out_node.meta["example_value"] + if isinstance(example_value, list): + raise AssertionError("expected example_value to not be a list") + if isinstance(example_value, torch.Tensor): + storage = StorageWeakRef(example_value._typed_storage()) + if storage in output_storages: + # output-output aliasing + log.debug( + "NYI: Failed to substitute region %s due to output-output aliasing detected at nodes %s, %s", + region, + output_storages[storage], + out_node, + ) + return True + output_storages[storage] = out_node + intersected_storages = input_storages.keys() & output_storages.keys() + if len(intersected_storages) > 0: + # input-output aliasing + aliased = [ + (input_storages[s], output_storages[s]) for s in intersected_storages + ] + aliased = ", ".join([f"{i} and {o}" for i, o in aliased]) + log.debug( + "NYI: Failed to substitute region %s due to input-output aliasing detected at nodes %s", + region, + aliased, + ) + return True + return False + + +def _is_tuple_node(node: Node) -> bool: + return isinstance(node.meta["example_value"], tuple) + + +def _get_children_getitems(node: Node) -> Generator[Node, None, None]: + for user in node.users: + if user.target is operator.getitem and isinstance(user.args[1], int): + yield user + + +def _get_flattened_node_indices(node: Node, region: Region) -> OrderedSet[int]: + """Returns an ordered set of indices, each representing a node in the region which will be flattened""" + flattened_node_to_ind = {n: i for i, n in enumerate(region)} + node_indices: OrderedSet[int] = OrderedSet() + queue = deque(_get_children_getitems(node)) + while queue: + cur_node = queue.popleft() + if any(user in region for user in cur_node.users): + node_indices.add(flattened_node_to_ind[cur_node]) + for child in _get_children_getitems(cur_node): + queue.append(child) + return node_indices + + +def _create_getitem_nodes( + node: Node, subgraph_tuple_node: Node, subgraph: torch.fx.Graph +) -> tuple[list[Node], dict[tuple[int, ...], int]]: + tup = node.meta["example_value"] + if not isinstance(tup, tuple): + raise AssertionError("_get_getitem_children expects tuple") + + getitem_nodes: list[Node] = [] + queue = deque([(e, (i,), subgraph_tuple_node) for i, e in enumerate(tup)]) + path_to_output_index = {} + + while queue: + cur_elem, path, parent = queue.popleft() + + with subgraph.inserting_after(parent): + new_getitem_node = subgraph.create_node( + "call_function", operator.getitem, (parent, path[-1]), {} + ) + new_getitem_node.meta["example_value"] = cur_elem + + path_to_output_index[path] = len(getitem_nodes) + getitem_nodes.append(new_getitem_node) + + if isinstance(cur_elem, tuple): + queue.extend( + [(e, path + (i,), new_getitem_node) for i, e in enumerate(cur_elem)] # type: ignore[arg-type,misc] + ) + + return getitem_nodes, path_to_output_index # type: ignore[return-value] + + +def _replace_tuple_outputs( + node: Node, + output_index: int, + tuple_spec: dict[tuple[int, ...], int], + invoke_subgraph_node: Node, + graph: torch.fx.Graph, +) -> OrderedSet[Node]: + if not _is_tuple_node(node): + raise AssertionError("_replace_tuple_outputs expects a tuple node") + + queue = deque((c, (c.args[1],)) for c in _get_children_getitems(node)) + erased_nodes: OrderedSet[Node] = OrderedSet() + while queue: + cur_node, path = queue.pop() + + for c in _get_children_getitems(cur_node): + queue.append((c, path + (c.args[1],))) # type: ignore[return-value, arg-type] + + with graph.inserting_after(invoke_subgraph_node): + subgraph_output = graph.create_node( + "call_function", + operator.getitem, + (invoke_subgraph_node, output_index + tuple_spec[path]), # type: ignore[index] + {}, + ) + cur_node.replace_all_uses_with(subgraph_output, propagate_meta=True) + graph.erase_node(cur_node) + erased_nodes.add(cur_node) + + graph.erase_node(node) + erased_nodes.add(node) + return erased_nodes diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_id_filter.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_id_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..c5349d53a44f7e578dfc6f604ad5732f3efce796 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_id_filter.py @@ -0,0 +1,474 @@ +# mypy: disallow-untyped-defs + +from __future__ import annotations + +import functools +import logging +import re +import warnings +from typing import Any, Generic, TYPE_CHECKING, TypeVar + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torch._guards import CompileId + + +log = logging.getLogger(__name__) + + +class GraphIdFilter: + """ + A filter for matching graph IDs based on various conditions. + Supports individual IDs, ranges, and comparison operators. + """ + + def __init__(self, filter_str: str) -> None: + self._explicit_ids: frozenset[int] = frozenset() + self._conditions: list[tuple[str, int]] = [] + self._parse(filter_str) + + def _parse(self, filter_str: str) -> None: + if not filter_str or not filter_str.strip(): + return + + explicit_ids: set[int] = set() + conditions: list[tuple[str, int]] = [] + + # Pattern for comparison operators (>=, >, <=, <) followed by a number + cmp_pattern = re.compile(r"^(>=|>|<=|<)(\d+)$") + # Pattern for ranges like "10-20" + range_pattern = re.compile(r"^(\d+)-(\d+)$") + + for part in filter_str.split(","): + part = part.strip() + if not part: + continue + + if match := cmp_pattern.match(part): + conditions.append((match.group(1), int(match.group(2)))) + elif match := range_pattern.match(part): + start, end = int(match.group(1)), int(match.group(2)) + explicit_ids.update(range(start, end + 1)) + else: + try: + explicit_ids.add(int(part)) + except ValueError: + log.warning("Invalid graph ID filter: %s", part) + + self._explicit_ids = frozenset(explicit_ids) + self._conditions = conditions + + def __contains__(self, graph_id: int) -> bool: + """Check if the given graph ID matches this filter.""" + if graph_id in self._explicit_ids: + return True + + for op, val in self._conditions: + if op == ">" and graph_id > val: + return True + elif op == ">=" and graph_id >= val: + return True + elif op == "<" and graph_id < val: + return True + elif op == "<=" and graph_id <= val: + return True + + return False + + def __repr__(self) -> str: + # pyrefly: ignore [implicit-any] + parts = [] + if self._explicit_ids: + parts.append(f"ids={sorted(self._explicit_ids)}") + if self._conditions: + parts.append(f"conditions={self._conditions}") + return f"GraphIdFilter({', '.join(parts) if parts else 'empty'})" + + +T = TypeVar("T") + + +class _GraphRouterBase(Generic[T]): + """ + Base class for routing graphs to different values based on their IDs. + + The router parses a configuration string with rules in the format: + "filter1:value1;filter2:value2;..." + + Rules are evaluated in order, and the first matching rule wins. + """ + + def __init__(self, config_str: str, rule_type: str) -> None: + self._rules: list[tuple[GraphIdFilter, T]] = [] + self._values: list[T | None] = [] + self._overflow_value: T | None = None + self._rule_type = rule_type + self._parse(config_str) + self._precompute() + + def _parse_value_str(self, value_str: str) -> T | None: + """Parse a value string into the appropriate type. Returns None to skip.""" + raise NotImplementedError + + def _parse(self, config_str: str) -> None: + if not config_str or not config_str.strip(): + return + + rule_strs = config_str.split(";") + for rule_str in rule_strs: + rule_str = rule_str.strip() + if not rule_str: + continue + + colon_idx = rule_str.find(":") + if colon_idx == -1: + log.warning( + "Invalid %s override rule (missing ':'): %s", + self._rule_type, + rule_str, + ) + continue + + filter_str = rule_str[:colon_idx].strip() + value_str = rule_str[colon_idx + 1 :].strip() + + if not filter_str or not value_str: + log.warning("Invalid %s override rule: %s", self._rule_type, rule_str) + continue + + value = self._parse_value_str(value_str) + if value is not None: + self._rules.append((GraphIdFilter(filter_str), value)) + + def _precompute(self) -> None: + if not self._rules: + return + + # Find max ID from explicit IDs and comparison thresholds + max_id = 0 + for f, _ in self._rules: + if f._explicit_ids: + max_id = max(max_id, *f._explicit_ids) + for _, val in f._conditions: + max_id = max(max_id, val) + + # Pre-compute values for IDs 0 to max_id + for i in range(max_id + 1): + self._values.append(self._match_rules(i)) + + # For IDs > max_id, the result is constant (only unbounded conditions apply) + self._overflow_value = self._match_rules(max_id + 1) + + def _match_rules(self, graph_id: int) -> T | None: + for f, value in self._rules: + if graph_id in f: + return value + return None + + def get_value_for_graph(self, graph_id: int) -> T | None: + """Get the value for a given graph ID. Returns None if no rule matches.""" + if graph_id < len(self._values): + return self._values[graph_id] + return self._overflow_value + + def is_empty(self) -> bool: + """Check if no rules are configured.""" + return len(self._rules) == 0 + + +class GraphBackendRouter(_GraphRouterBase[Any]): + """ + Routes graphs to different backends based on their IDs. + + The router parses a configuration string with rules in the format: + "filter1:backend1;filter2:backend2;..." + + If a graph ID matches multiple rules with different backends, a ValueError + is raised. + + Examples: + "0-5:eager;>5:inductor" - IDs 0-5 use eager, rest use inductor + ">10:aot_eager" - IDs > 10 use aot_eager + "<=3:eager;4-10:aot_eager" - IDs 0-3 use eager, 4-10 use aot_eager + + Supported backends include "eager", "aot_eager", "aot_eager_decomp_partition", + "inductor", and any other registered backend. + """ + + def __init__(self, config_str: str) -> None: + self._backend_names: dict[int, str] = {} + super().__init__(config_str, "backend") + + def _parse_value_str(self, value_str: str) -> Any | None: + """Look up a backend by name.""" + from .backends.registry import lookup_backend + from .eval_frame import cached_backends + + backend = lookup_backend(value_str) + + # Register the backend so its reset() is called during torch._dynamo.reset() + if backend is None: + raise AssertionError("Invalid override backend: " + value_str) + cached_backends.setdefault(id(backend), backend) + self._backend_names[id(backend)] = value_str + return backend + + def _match_rules(self, graph_id: int) -> Any | None: + """Match rules with conflict detection for overlapping filters.""" + matches = {id(backend): backend for f, backend in self._rules if graph_id in f} + if len(matches) > 1: + names = [self._backend_names[bid] for bid in matches] + raise ValueError( + f"Conflicting backend override for graph {graph_id}: matched {names}" + ) + if matches: + return next(iter(matches.values())) + return None + + def __repr__(self) -> str: + if not self._rules: + return "GraphBackendRouter(empty)" + return f"GraphBackendRouter({self._rules})" + + +class GraphConfigRouter(_GraphRouterBase[dict[str, Any]]): + """ + Routes graphs to different inductor configs based on their IDs. + + The router parses a configuration string with rules in the format: + "filter1:config1;filter2:config2;..." + + All matching rules are aggregated: configs from all matching rules are merged + into a single dict. Conflicting keys (same key, different value) raise an error. + Config format is "key=value" or "key1=value1,key2=value2" for multiple settings. + + Examples: + "0-5:triton.cudagraph_skip_dynamic_graphs=False" + ">10:triton.cudagraphs=False,triton.cudagraph_trees=False" + + With "0:a=1;>=0:b=2", graph 0 gets {"a": 1, "b": 2} (both rules match). + With "0:a=1;>=0:a=2", graph 0 raises an error (conflicting values for "a"). + With "0:a=1;>=0:a=1", graph 0 gets {"a": 1} (same value is not a conflict). + """ + + def __init__(self, config_str: str) -> None: + super().__init__(config_str, "config") + + @staticmethod + def _parse_scalar_value(value_str: str) -> Any: + """Parse a string value into the appropriate Python type.""" + value_str = value_str.strip() + if value_str.lower() == "true": + return True + if value_str.lower() == "false": + return False + if value_str.lower() == "none": + return None + try: + if "." in value_str: + return float(value_str) + return int(value_str) + except ValueError: + return value_str + + def _match_rules(self, graph_id: int) -> dict[str, Any] | None: + """Aggregate configs from all matching rules. Conflicts raise an error.""" + result: dict[str, Any] = {} + for f, value in self._rules: + if graph_id in f: + for k, v in value.items(): + if k in result and result[k] != v: + raise ValueError( + f"Conflicting config override for graph {graph_id}: " + f"key '{k}' has value {result[k]!r} and {v!r}" + ) + result[k] = v + return result if result else None + + def _parse_value_str(self, value_str: str) -> dict[str, Any] | None: + """Parse a config string like 'key1=val1,key2=val2' into a dict.""" + result: dict[str, Any] = {} + for item in value_str.split(","): + item = item.strip() + if not item: + continue + if "=" not in item: + log.warning("Invalid config item (missing '='): %s", item) + continue + key, value = item.split("=", 1) + result[key.strip()] = self._parse_scalar_value(value) + return result if result else None + + def __repr__(self) -> str: + if not self._rules: + return "GraphConfigRouter(empty)" + return f"GraphConfigRouter({self._rules})" + + +def _get_override_for_compile_id( + compile_id: CompileId | None, + config_str: str, + create_router: Callable[[str], _GraphRouterBase[T]], + label: str, +) -> T | None: + """ + Get the override value for a given CompileId. + + Returns the value from the router, or None if no override applies. + """ + if compile_id is None or not config_str: + return None + + graph_id = compile_id.frame_id + if graph_id is None: + return None + + router = create_router(config_str) + value = router.get_value_for_graph(graph_id) + if value is not None: + log.info("Overriding %s: %s", label, value) + return value + + +@functools.lru_cache +def _create_backend_router(config_str: str) -> GraphBackendRouter: + """Create and cache GraphBackendRouter instances based on config string.""" + return GraphBackendRouter(config_str) + + +@functools.lru_cache +def _validate_backend_names(config_str: str) -> str | None: + """Return an error message if any backend name is invalid, else None.""" + if not config_str or not config_str.strip(): + return None + from .backends.registry import lookup_backend + + for rule_str in config_str.split(";"): + rule_str = rule_str.strip() + if not rule_str or ":" not in rule_str: + continue + backend_name = rule_str[rule_str.find(":") + 1 :].strip() + if not backend_name: + continue + try: + lookup_backend(backend_name) + except Exception: + return ( + f"TORCH_COMPILE_OVERRIDE_BACKENDS: " + f"'{backend_name}' is not a valid backend, " + f"see `torch._dynamo.list_backends()` for available backends" + ) + return None + + +@functools.lru_cache +def _validate_inductor_config_keys(config_str: str) -> str | None: + """Return an error message if any config key is invalid, else None.""" + router = GraphConfigRouter(config_str) + from torch._inductor import config + + for _, config_dict in router._rules: + for key in config_dict: + if not hasattr(config, key): + return ( + f"TORCH_COMPILE_OVERRIDE_INDUCTOR_CONFIGS: " + f"'{key}' is not a valid torch._inductor.config option" + ) + return None + + +@functools.lru_cache +def _validate_dynamo_config_keys(config_str: str) -> str | None: + """Return an error message if any config key is invalid, else None.""" + router = GraphConfigRouter(config_str) + from torch._dynamo import config + + for _, config_dict in router._rules: + for key in config_dict: + if not hasattr(config, key): + return ( + f"TORCH_COMPILE_OVERRIDE_DYNAMO_CONFIGS: " + f"'{key}' is not a valid torch._dynamo.config option" + ) + return None + + +@functools.lru_cache +def _create_inductor_config_router(config_str: str) -> GraphConfigRouter: + """Create and cache GraphConfigRouter for inductor config overrides.""" + return GraphConfigRouter(config_str) + + +@functools.lru_cache +def _create_dynamo_config_router(config_str: str) -> GraphConfigRouter: + """Create and cache GraphConfigRouter for dynamo config overrides. + + Warns that dynamo config overrides are keyed by frame ID and some configs + can affect graph breaks, which may shift frame IDs. + """ + router = GraphConfigRouter(config_str) + if not router.is_empty(): + warnings.warn( + "TORCH_COMPILE_OVERRIDE_DYNAMO_CONFIGS is set. Dynamo config overrides are " + "keyed by frame ID. Some dynamo configs can affect graph breaks, " + "which may alter the number of frames and shift frame IDs, causing " + "overrides to target the wrong graphs.", + ) + return router + + +def get_backend_override_for_compile_id( + compile_id: CompileId | None, + config_str: str, +) -> Any: + """ + Get the backend override for a given CompileId. + + Returns the backend function to use, or None if no override applies. + """ + return _get_override_for_compile_id( + compile_id, + config_str, + _create_backend_router, + "torch.compile backend", + ) + + +def get_inductor_config_override_for_compile_id( + compile_id: CompileId | None, + config_str: str, +) -> dict[str, Any] | None: + """ + Get the inductor config override for a given CompileId. + + Returns a dict of config patches to apply, or None if no override applies. + """ + return _get_override_for_compile_id( + compile_id, + config_str, + _create_inductor_config_router, # type: ignore[arg-type] + "inductor config", + ) + + +def get_dynamo_config_override_for_compile_id( + compile_id: CompileId | None, + config_str: str, +) -> dict[str, Any] | None: + """ + Get the dynamo config override for a given CompileId. + + Returns a dict of config patches to apply, or None if no override applies. + """ + return _get_override_for_compile_id( + compile_id, + config_str, + _create_dynamo_config_router, # type: ignore[arg-type] + "dynamo config", + ) + + +# Keep old name for backwards compatibility +_create_router = _create_backend_router diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_region_tracker.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_region_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..325840dcdd8e6d700b3a41d99b05195c9cdf949c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_region_tracker.py @@ -0,0 +1,507 @@ +""" +This module provides functionality for tracking and managing regions in computational graphs. +It supports graph optimization by identifying and grouping similar regions based on their +structure and behavior. The module implements algorithms for: + +1. Tracking nodes and their relationships in the computational graph +2. Identifying identical or similar regions across the graph +3. Managing graph regions for optimization purposes +4. Supporting deduplication and other graph transformation passes + +The core functionality revolves around the GraphRegionTracker class which maintains +mappings between nodes and their duplicates, enabling efficient graph analysis and +optimization operations. +""" + +from __future__ import annotations + +import copyreg +import io +import logging +import math +import operator +import pickle +from collections import defaultdict, deque +from dataclasses import fields +from typing import Any, TYPE_CHECKING, TypeVar + +import torch._logging +import torch.fx +from torch._subclasses.fake_tensor import FakeTensor +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_flatten + +from .graph_utils import _get_flat_args_unique + + +T = TypeVar("T") + + +if TYPE_CHECKING: + from collections.abc import Callable + + from .symbolic_convert import InstructionTranslatorBase + + +Node = torch.fx.Node +Region = list[Node] +IdenticalNodes = list[Node] +GlobalStateKey = tuple[ + bool, + bool, + int, + tuple[bool, bool], + tuple[bool, bool], + torch.dtype, + bool, + bool, + bool, + bool, +] + +log = logging.getLogger(__name__) +graph_expansion_log = torch._logging.getArtifactLogger( + __name__, "graph_region_expansion" +) + + +def debug_log(msg: str, *args) -> None: # type: ignore[no-untyped-def] + graph_expansion_log.debug(msg, *args) + + +def _extract_tensor_metadata_for_node_hash( + x: torch.Tensor, +) -> tuple[Callable[[T], T], tuple[Any, ...]]: + from torch._inductor.codecache import _ident, extract_tensor_metadata_for_cache_key + + out = [] + metadata = extract_tensor_metadata_for_cache_key(x) + for field in fields(metadata): + out.append(getattr(metadata, field.name)) + + return (_ident, tuple(out)) + + +class NodeHashException(Exception): + pass + + +class InputPickler(pickle.Pickler): + def __init__(self) -> None: + from torch._inductor.codecache import _ident + + stream = io.BytesIO() + self._stream = stream + super().__init__(stream) + self.dispatch_table = copyreg.dispatch_table.copy() + self.dispatch_table.update( + { + FakeTensor: _extract_tensor_metadata_for_node_hash, + torch.SymInt: lambda x: (_ident, (str(x),)), + torch.SymBool: lambda x: (_ident, (str(x),)), + torch.SymFloat: lambda x: (_ident, (str(x),)), + } + ) + self.fast = True + + def dumps(self, obj: Any) -> bytes: + """ + Pickle an object and return a byte string. + """ + try: + self.dump(obj) + return self._stream.getvalue() + except (TypeError, AttributeError) as e: + raise NodeHashException from e + finally: + self._stream.seek(0) + self._stream.truncate(0) + + +def _extract_args(arg: Any) -> Any: + if isinstance(arg, Node): + return arg.meta.get("example_value") + elif isinstance(arg, (torch.Tensor, int)): + return arg + else: + return None + + +def _normalize_args( + node: Node, +) -> tuple[tuple[str, ...], tuple[Any | None, ...]]: + flat_args, _ = tree_flatten(node.args) + sorted_kwargs = sorted(node.kwargs.items(), key=operator.itemgetter(0)) + sorted_keys = tuple(sorted(node.kwargs.keys())) + flat_kwargs, _ = tree_flatten(sorted_kwargs) + all_args = flat_args + flat_kwargs + return (sorted_keys, tuple(_extract_args(arg) for arg in all_args)) + + +def _sort_with_ref_region( + index_to_rank: dict[int, int], regions: list[list[Any]] +) -> None: + # sort topologically + # we need to handle edge cases where some nodes have no dependencies + # so first we map each node to its ranking + ref_region = regions[0] + sorted_indices = sorted(range(len(ref_region)), key=lambda i: index_to_rank[i]) + for region in regions: + region[:] = [region[i] for i in sorted_indices] + + +def get_global_state_key() -> GlobalStateKey: + return ( + torch.is_grad_enabled(), + torch.is_inference_mode_enabled(), + torch.get_num_threads(), + torch._C._get_cublas_allow_fp16_reduced_precision_reduction(), + torch._C._get_cublas_allow_bf16_reduced_precision_reduction(), + torch.get_default_dtype(), + torch.are_deterministic_algorithms_enabled(), + torch._C._get_cublas_allow_tf32(), + torch.is_deterministic_algorithms_warn_only_enabled(), + torch._C._autograd._saved_tensors_hooks_is_enabled(), # type: ignore[attr-defined] + ) + + +# This is typical BFS with the caveat +# that a node's children need to be explicitly +# added with the add_children() method +# The flow is yield a node and check if it's valid for all regions +# if not valid, discard and continue onto the next node +# Note: this iterates backward through the graph by looking at args/kwargs +# of a node +class BackwardBfsArgIter: + def __init__(self, origin: Node) -> None: + self._cur: Node | None = origin + self._queue: deque[Node | None] = deque() + + @staticmethod + def create(origin: Node) -> BackwardBfsArgIter: + it = BackwardBfsArgIter(origin) + it.add_children(origin) + # pop the origin node, since it is the origin of + # the region and does not need to be considered for addition + if not it.next(): + raise AssertionError("expected origin node to be popped from iterator") + return it + + def next(self) -> Node | None: + ret = self._cur + if not self._queue: + self._cur = None + else: + self._cur = self._queue.popleft() + return ret + + def peek(self) -> Node | None: + return self._cur + + def add_children(self, node: Node) -> None: + flat_args = _get_flat_args_unique(node, {}) + for arg in flat_args: + if isinstance(arg, Node): + self._append(arg) + + def _append(self, arg: Node) -> None: + if self._cur is None: + self._cur = arg + else: + self._queue.append(arg) + + def __str__(self) -> str: + return f"BackwardBfsArgIter(cur={self._cur}, queue={self._queue})" + + +class GraphRegionTracker: + """ + GraphRegionTracker tracks each node added to the output graph and generates a key based on the source location, + instruction pointer, input shapes, and global state at the time the node is inserted into the graph. Nodes with + the same key are grouped together in a list of identical nodes (the value of node_to_duplicates). + + hash_to_duplicates: Dict[str, IdenticalNodes] - A dictionary mapping the key to a list of identical nodes + node_to_duplicates: Dict[Node, IdenticalNodes] - A dictionary mapping a node to the list of identical nodes it belongs to + input_pickler: InputPickler - An instance of InputPickler used to generate a node hash + """ + + def __init__(self) -> None: + self.hash_to_duplicates: dict[str, IdenticalNodes] = defaultdict(list) + self.node_to_duplicates: dict[Node, IdenticalNodes] = {} + # Note: position is in flattened args/kwargs list + self.node_to_mutated_arg_positions: dict[Node, OrderedSet[int]] = {} + self.input_pickler = InputPickler() + + def _hash_node( + self, filename: str, lineno: int, instruction_pointer: int | None, node: Node + ) -> str: + from torch._inductor.codecache import sha256_hash + + key = ( + get_global_state_key(), + filename, + lineno, + instruction_pointer, + _normalize_args(node), + ) + return sha256_hash(self.input_pickler.dumps(key)) + + def _is_identical(self, n0: Node, n1: Node) -> bool: + return ( + n0 in self.node_to_duplicates + and n1 in self.node_to_duplicates + and self.node_to_duplicates[n0] is self.node_to_duplicates[n1] + and n0 is not n1 + ) + + def track_node(self, tx: InstructionTranslatorBase, node: Node) -> None: + """ + The main entry point for tracking a node. This function will hash the node argument and group + nodes with the same hash together. It updates the hash_to_duplicates and node_to_duplicates dictionaries + to track the new node. + """ + try: + if ( + node not in self.node_to_duplicates + ): # don't allow nodes to be added twice + duplicates = self.hash_to_duplicates[ + self._hash_node( + tx.f_code.co_filename, tx.lineno, tx.instruction_pointer, node + ) + ] + duplicates.append(node) + self.node_to_duplicates[node] = duplicates + except NodeHashException as e: + log.debug("Unable to hash node %s with exception %s", node, e) + + def track_node_mutations( + self, + node: Node, + flat_args_kwargs: list[Any], + id_to_initial_version: dict[int, int], + ) -> None: + """ + This function tracks which argument positions are mutated by the given node. Subgraph HOP does not support + input mutations today so we will skip regions which have inputs that are mutated. + """ + mutated_arg_positions = OrderedSet[int]() + for i, arg in enumerate(flat_args_kwargs): + val_id = id(arg) + if ( + val_id in id_to_initial_version + and id_to_initial_version[val_id] != arg._version + ): + mutated_arg_positions.add(i) + + if mutated_arg_positions: + self.node_to_mutated_arg_positions[node] = mutated_arg_positions + + def add_node_mutation( + self, + node: Node, + arg_pos: int, + ) -> None: + if node in self.node_to_mutated_arg_positions: + self.node_to_mutated_arg_positions[node].add(arg_pos) + else: + self.node_to_mutated_arg_positions[node] = OrderedSet([arg_pos]) + + def get_identical_regions(self, graph: torch.fx.Graph) -> list[list[Region]]: + """ + This function is responsible for extracting the largest regions of identical nodes from the given graph. + **Note**: This function assumes the nodes that have been tracked with track_node are in the provided graph argument. + + The algorithm proceeds as follows: + The nodes tracked via track_node above are organized into region groups. The initial region groups look like this: + [[IdenticalNode1], [IdenticalNode2], [IdenticalNode3]] and each sublist is called a region. For each region group + (starting at the topologically latest region group), the inner regions are gradually expanded one node at time from + the flattened args and kwargs of the node in each region provided that for all regions in the group, the nodes being + added are also identical (ie have the same key computed by track_node). This is checked by verifying that the two + nodes have the same identical node list in node_to_duplicates. + """ + topological_ranking = {node: i for i, node in enumerate(graph.nodes)} + region_groups_with_rank = [] + # needed to detect if replacing a region will create cycles + node_to_recursive_ancestors = _populate_recursive_ancestor_map(graph) + + # Create region groups; a region group is a group + # of regions that are all identical. In this initial state + # each region in the group is a single node, and we discard + # groups that are only a single region. + # We track the topological ranking to start with groups later in the graph + # the reason for this is that we will necessarily create the largest groups first. + for group in self.hash_to_duplicates.values(): + if len(group) > 1: + # pyrefly: ignore [implicit-any] + region_group = [] + min_rank = math.inf + + for node in group: + # some nodes aren't in the topo ranking? + if node in topological_ranking: + min_rank = min(min_rank, topological_ranking[node]) + region_group.append([node]) + + if len(region_group) > 1: + region_groups_with_rank.append((region_group, min_rank)) + + region_groups_with_rank.sort(key=lambda rg: -rg[1]) + region_groups = [rg for rg, _ in region_groups_with_rank] + + # We start from regions later in the graph and expand them earlier + # as a result, we will create the largest regions first and they won't + # overlap. + seen_nodes: set[Node] = set() + for region_group in region_groups: + fully_expand_region_group( + region_group, + seen_nodes, + node_to_recursive_ancestors, + self._is_identical, + ) + # sort topologically + # we need to handle edge cases where some nodes have no dependencies + # so first we map each node to its ranking, + ref_region = region_group[0] + index_to_rank = { + index: topological_ranking[n] for index, n in enumerate(ref_region) + } + _sort_with_ref_region(index_to_rank, region_group) + + return [ + region_group for region_group in region_groups if len(region_group[0]) > 1 + ] + + def __str__(self) -> str: + return f"GraphRegionTracker(hash_to_duplicates={self.hash_to_duplicates}, node_to_duplicates={self.node_to_duplicates})" + + +class RegionWrapper: + """Holds state for regions e.g. ancestors and new candidate nodes for consideration""" + + def __init__( + self, region: Region, node_to_recursive_ancestors: dict[Node, set[Node]] + ) -> None: + if len(region) != 1: + raise AssertionError("all regions should start with one node") + node = region[0] + self.node_to_recursive_ancestors = node_to_recursive_ancestors + self.iter = BackwardBfsArgIter.create(node) + self.nodes_unique = OrderedSet([node]) + self.ancestors = set(node_to_recursive_ancestors[node]) + self.region = region + + def next_candidate(self) -> Node | None: + return self.iter.next() + + def will_inclusion_create_cycle(self, node: Node) -> bool: + external_users = [user for user in node.users if user not in self.nodes_unique] + for user in external_users: + if user in self.ancestors: + return True + + return False + + def add(self, node: Node) -> None: + self.nodes_unique.add(node) + self.region.append(node) + self.iter.add_children(node) + self.ancestors.update(self.node_to_recursive_ancestors[node]) + + +def fully_expand_region_group( + regions: list[Region], + seen_nodes: set[Node], + node_to_recursive_ancestors: dict[Node, set[Node]], + is_identical_fn: Callable[[Node, Node], bool], +) -> None: + debug_log("--------------------------------------------------") + debug_log("expanding new region group: %s", regions) + + # All regions should start with 1 node + if not all(len(region) == 1 for region in regions): + raise AssertionError("all regions should start with one node") + region_wrappers = [ + RegionWrapper(region, node_to_recursive_ancestors) for region in regions + ] + + nodes_to_add = OrderedSet[Node]() + current_node = region_wrappers[0].next_candidate() + + # No children + if current_node is None: + return + + # Loop incrementally adding new nodes to each region + # regions are only expanded if the node to add is valid + # for ALL regions + while current_node: + add_to_all_regions = not region_wrappers[0].will_inclusion_create_cycle( + current_node + ) + nodes_to_add.clear() + nodes_to_add.add(current_node) + for region_wrapper in region_wrappers[1:]: + candidate = region_wrapper.next_candidate() + + debug_log("--------------------") + debug_log( + "considering candidate: %s, cur_node: %s", candidate, current_node + ) + + if not candidate or not add_to_all_regions: + add_to_all_regions = False + continue + + debug_log( + "candidate in previously claimed nodes?: %s", candidate in seen_nodes + ) + debug_log("is_identical: %s", is_identical_fn(candidate, current_node)) + + add_to_all_regions &= ( + candidate not in seen_nodes + and candidate not in nodes_to_add + and candidate.op != "placeholder" + and candidate.op != "get_attr" + and is_identical_fn(candidate, current_node) + and not region_wrapper.will_inclusion_create_cycle(candidate) + ) + nodes_to_add.add(candidate) + + debug_log(f"add_to_all_regions: {add_to_all_regions}") + debug_log("--------------------") + + if add_to_all_regions: + if len(region_wrappers) != len(nodes_to_add): + raise AssertionError( + "Number of nodes to add must equal the number of regions" + ) + for region_wrapper, node in zip(region_wrappers, nodes_to_add): + region_wrapper.add(node) + debug_log("adding %s's children", node) + debug_log("%s %s", node.args, list(node.kwargs.items())) + seen_nodes.add(node) + + current_node = region_wrappers[0].next_candidate() + + # Ensure regions are sorted in topological order + for region in regions: + region.reverse() + + debug_log("end expand new region group: %s", regions) + debug_log("--------------------------------------------------") + + +def _populate_recursive_ancestor_map(graph: torch.fx.Graph) -> dict[Node, set[Node]]: + node_to_recursive_ancestors: dict[Node, set[Node]] = {} + for node in graph.nodes: + node_to_recursive_ancestors[node] = set() + for node in graph.nodes: + all_args = _get_flat_args_unique(node, {}) + for arg in all_args: + if isinstance(arg, Node): + node_to_recursive_ancestors[node].update( + node_to_recursive_ancestors[arg] + ) + node_to_recursive_ancestors[node].add(arg) + return node_to_recursive_ancestors diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_utils.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..68aea6f96e102b8d0f4808ffeacd4fa95f4cd023 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_utils.py @@ -0,0 +1,117 @@ +from typing import Any + +import torch +from torch.fx import Graph, map_arg, Node +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_flatten + + +# flattens with support for slices +# Note: a better way to do this would +# be register/unregister slices as pytree nodes +# but there is no unregister API in the pytorch +# pytree impl +def _get_flat_args( + node: Node, node_to_additional_deps: dict[Node, OrderedSet[Node]] +) -> list[Node]: + args = list[Any]() + map_arg((node.args, node.kwargs), args.append) + if node in node_to_additional_deps: + args.extend(node_to_additional_deps[node]) + return args + + +def _get_flat_args_unique( + node: Node, node_to_additional_deps: dict[Node, OrderedSet[Node]] +) -> OrderedSet[Node]: + args = OrderedSet[Node]() + map_arg((node.args, node.kwargs), args.add) + if node in node_to_additional_deps: + args.update(node_to_additional_deps[node]) + return args + + +def _detect_cycles( + graph: Graph, node_to_additional_deps: dict[Node, OrderedSet[Node]] +) -> str: + # States: 0=Unvisited, 1=Visiting, 2=Visited(Safe) + state: dict[Node, int] = {} + + for root in reversed(graph.nodes): + if root in state: + continue + + # Stack holds (current_node, children_iterator). + # Using an iterator allows us to pause and resume processing a node's children. + stack = [(root, iter(_get_flat_args_unique(root, node_to_additional_deps)))] + state[root] = 1 # Visiting + + while stack: + parent, children = stack[-1] + + try: + child = next(children) + + if not isinstance(child, Node): + continue + + child_state = state.get(child, 0) + + if child_state == 1: + # Back-edge: child is on the current DFS path -> cycle + cycle_path = [node for node, _ in stack] + [child] + return f"cycle detected in path: {cycle_path}" + + if child_state == 0: + state[child] = 1 + stack.append( + ( + child, + iter(_get_flat_args_unique(child, node_to_additional_deps)), + ) + ) + # child_state == 2 means already verified safe; skip. + + except StopIteration: + # All children processed — mark safe and pop. + stack.pop() + state[parent] = 2 + + return "no cycle detected" + + +def _graph_device_type(graph: Graph | None) -> str: + if graph is None: + return "cpu" + + def _device_type(x: Any) -> str: + if isinstance(x, torch.device): + return x.type + if isinstance(x, torch.Tensor): + return x.device.type + return "cpu" + + def _flatten_meta(node: Node, key: str) -> list[Any]: + if key not in node.meta: + return [] + flat, _ = tree_flatten(node.meta[key]) + return flat + + for node in graph.nodes: + for key in ("val", "example_value"): + for obj in _flatten_meta(node, key): + return _device_type(obj) + + # Check for device conversions + if node.op == "call_method": + for gpu in ["cuda", "xpu"]: + if node.target == gpu: + return gpu + if node.target == "to" and gpu in node.args: + return gpu + + # Check args/kwargs for non-CPU device specs + flat_args, _ = tree_flatten((node.args, node.kwargs)) + for obj in flat_args: + return _device_type(obj) + return "cpu" diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/guards.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/guards.py new file mode 100644 index 0000000000000000000000000000000000000000..af820ad0862d5e9a5e33415602d52f04b5a0b1a4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/guards.py @@ -0,0 +1,5783 @@ +""" +Core guard system for Dynamo that detects when compiled code needs to be recompiled due to +changes in program state. Guards are conditions that must remain true for previously-compiled +code to be valid for reuse. + +This module provides the infrastructure for creating, managing and checking guards, including: +- Guard creation and composition +- Guard state management and invalidation +- Guard checking and failure handling +- Utilities for guard optimization and debugging +- Integration with Dynamo's compilation caching + +The guard system is critical for Dynamo's ability to efficiently reuse compiled code while +maintaining correctness by detecting when recompilation is necessary due to changes in +program state, tensor properties, or control flow. +""" + +from __future__ import annotations + +import ast +import builtins +import collections +import dataclasses +import enum +import functools +import importlib +import inspect +import io +import itertools +import logging +import math +import pickle +import sys +import textwrap +import traceback +import types +import warnings +import weakref +from contextlib import contextmanager +from copy import deepcopy +from inspect import currentframe +from typing import Any, cast, NamedTuple, NoReturn, TYPE_CHECKING +from typing_extensions import LiteralString, TypeAliasType, TypeVar +from weakref import ReferenceType + +import torch +import torch.overrides +import torch.utils._device +from torch._C._dynamo.eval_frame import code_framelocals_names +from torch._C._dynamo.guards import ( + check_obj_id, + check_type_id, + ClosureGuardAccessor, + CodeGuardAccessor, + dict_version, + DictGetItemGuardAccessor, + DictGuardManager, + FuncDefaultsGuardAccessor, + FuncKwDefaultsGuardAccessor, + GetAttrGuardAccessor, + GetGenericDictGuardAccessor, + GuardAccessor, + GuardDebugInfo, + GuardManager, + install_no_tensor_aliasing_guard, + install_object_aliasing_guard, + install_storage_overlapping_guard, + install_symbolic_shape_guard, + LeafGuard, + profile_guard_manager, + RelationalGuard, + RootGuardManager, + TupleGetItemGuardAccessor, + TypeDictGuardAccessor, + TypeGuardAccessor, + TypeMROGuardAccessor, +) +from torch._dynamo.source import ( + get_global_source_name, + get_local_source_name, + IndexedSource, + is_from_flatten_script_object_source, + is_from_local_source, + is_from_optimizer_source, + is_from_skip_guard_source, + is_from_unspecialized_builtin_nn_module_source, + TensorProperty, + TensorPropertySource, +) +from torch._dynamo.utils import CompileEventLogger, get_metrics_context +from torch._guards import ( + CompileContext, + CompileId, + DuplicateInputs, + Guard, + GuardBuilderBase, + GuardEnvExpr, + GuardSource, + Source, + StorageOverlap, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import get_opaque_obj_info, is_opaque_constant_type +from torch._logging import structured +from torch._utils_internal import justknobs_check +from torch.fx.experimental.symbolic_shapes import ( + _CppShapeGuardsHelper, + _ShapeGuardsHelper, + EqualityConstraint, + is_symbolic, + SYMPY_INTERP, +) +from torch.utils import _pytree as pytree +from torch.utils._indented_buffer import IndentedBuffer +from torch.utils._ordered_set import OrderedSet +from torch.utils._traceback import format_frame, report_compile_source_on_error +from torch.utils.weak import TensorWeakRef + +from . import config, convert_frame, exc +from .eval_frame import set_guard_error_hook +from .source import ( + AttrProxySource, + AttrSource, + CallFunctionNoArgsSource, + CallMethodItemSource, + CellContentsSource, + ChainedSource, + ClosureSource, + CodeSource, + ConstantSource, + ConstDictKeySource, + ContextVarGetSource, + CurrentStreamSource, + DataclassFieldsSource, + DefaultsSource, + DictGetItemSource, + DictSubclassGetItemSource, + DynamicScalarSource, + FlattenScriptObjectSource, + FloatTensorSource, + FSDPNNModuleSource, + GenericAttrSource, + GetItemSource, + GlobalSource, + GlobalStateSource, + GlobalWeakRefSource, + GradSource, + ImportSource, + ListGetItemSource, + LocalSource, + NamedTupleFieldsSource, + NNModuleSource, + NonSerializableSetGetItemSource, + NumpyTensorSource, + OptimizerSource, + ScriptObjectQualifiedNameSource, + ShapeEnvSource, + SubclassAttrListSource, + TorchFunctionModeStackSource, + TupleIteratorGetItemSource, + TypeDictSource, + TypeMROSource, + TypeSource, + UnspecializedBuiltinNNModuleSource, + UnspecializedNNModuleSource, + UnspecializedParamBufferSource, + UnwrapCollectiveTensorSource, + WeakRefCallSource, +) +from .types import ( # noqa: F401 + CacheEntry, + DynamoFrameType, + ExtraState, + GuardedCode, + GuardFail, + GuardFilterEntry, + GuardFn, +) +from .utils import ( + builtin_dict_keys, + common_constant_types, + dataclass_fields, + dict_keys, + get_current_stream, + get_torch_function_mode_stack, + get_torch_function_mode_stack_at, + guard_failures, + istype, + key_is_id, + key_to_id, + normalize_count_iter, + normalize_range_iter, + orig_code_map, + set_getitem, + tuple_iterator_getitem, + tuple_iterator_len, + verify_guard_fn_signature, +) + + +if TYPE_CHECKING: + from collections.abc import Callable + + GuardCheckGetMetadataFn = Callable[[Guard, Any], Any] + GuardCheckEvalFn = Callable[[Any, Any], bool] + + +guard_manager_testing_hook_fn: Callable[[Any, Any, Any], Any] | None = None +_COUNT_ITERATOR_TYPE = type(itertools.count()) + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from collections.abc import Generator, KeysView, Sequence, Sized + + from sympy import Symbol + + from torch._C import DispatchKeySet + from torch._dynamo.output_graph import OutputGraphCommon, OutputGraphGuardsState + from torch._dynamo.package import SerializedCode + from torch.utils._python_dispatch import TraceableWrapperSubclass + +T = TypeVar("T") +log = logging.getLogger(__name__) +guards_log = torch._logging.getArtifactLogger(__name__, "guards") +recompiles_log = torch._logging.getArtifactLogger(__name__, "recompiles") +recompiles_verbose_log = torch._logging.getArtifactLogger( + __name__, "recompiles_verbose" +) +verbose_guards_log = torch._logging.getArtifactLogger(__name__, "verbose_guards") + + +def _sequence_length(value: object) -> int: + if isinstance(value, set): + return set.__len__(value) + if isinstance(value, frozenset): + return frozenset.__len__(value) + return len(cast("Sized", value)) + + +_COW_TENSOR_UNSUPPORTED = object() + + +def _try_is_cow_tensor(value: object) -> bool | object: + if not isinstance(value, torch.Tensor): + return _COW_TENSOR_UNSUPPORTED + if torch._C._dispatch_keys(value).has(torch._C.DispatchKey.Python): + return _COW_TENSOR_UNSUPPORTED + return torch._C._is_cow_tensor(value) # pyrefly: ignore[missing-attribute] + + +def _cow_tensor_matches(value: object, expected: object) -> bool: + if not isinstance(expected, bool): + return False + actual = _try_is_cow_tensor(value) + return actual is not _COW_TENSOR_UNSUPPORTED and actual == expected + + +dunder_attrs_assumed_constants = ( + "__defaults__", + "__kwdefaults__", + "__code__", + "__closure__", + "__annotations__", + "__func__", + "__mro__", +) + + +def get_framelocals_idx(code: types.CodeType, var_name: str) -> int: + # Refer to index in the frame's localsplus directly. + # NOTE: name order for a code object doesn't change. + # NOTE: we need to find the LAST matching index because <= 3.10 contains + # duplicate names in the case of cells: a name can be both local and cell + # and will take up 2 slots of the frame's localsplus. The correct behavior + # is to refer to the cell, which has a higher index. + framelocals_names_reversed = code_framelocals_names_reversed_cached(code) + framelocals_idx = ( + len(framelocals_names_reversed) - framelocals_names_reversed.index(var_name) - 1 + ) + return framelocals_idx + + +class IndentedBufferWithPrefix(IndentedBuffer): + def prefix(self) -> str: + return "| " * (self._indent * self.tabwidth) + + def writeline(self, line: str, skip_prefix: bool = False) -> None: # type: ignore[override] + if skip_prefix: + super().writeline(line) + else: + super().writeline("+- " + line) + + +class GuardManagerWrapper: + """ + A helper class that contains the root guard manager. An instance of this + class is stored in the Dynamo cache entry, so that the cache entry can + access the RootGuardManager stored in the "root" attribute and directly call + the check_nopybind from C++. + """ + + def __init__( + self, + root: RootGuardManager | None = None, + local_state: Any | None = None, + ) -> None: + if root is None: + self.root = RootGuardManager() + else: + self.root = root + + if local_state is not None: + self.root.set_local_state(local_state) + + self.diff_guard_root: RootGuardManager | None = None + self.closure_vars: dict[str, Any] | None = None + self.args: list[str] | None = None + self.code_parts: list[str] = [] + self.verbose_code_parts: list[str] | None = None + self.global_scope: dict[str, Any] | None = None + self.guard_fail_fn: Callable[[GuardFail], None] | None = None + self.cache_entry: CacheEntry | None = None + self.extra_state: ExtraState | None = None + self.id_matched_objs: dict[str, ReferenceType[object]] = {} + self.no_tensor_aliasing_sources: list[str] = [] + + self.printed_relational_guards: set[RelationalGuard] = set() + + self.diff_guard_sources: OrderedSet[str] = OrderedSet() + + @contextmanager + def _preserve_printed_relational_guards(self) -> Generator[None, None, None]: + self.printed_relational_guards = set() + try: + yield + finally: + self.printed_relational_guards = set() + + # TODO: clarify what fn and attributes guard manager has to get the right things here + def collect_diff_guard_sources(self) -> OrderedSet[str]: + # At the time of finalize, we have only marked guard managers with + # TENSOR_MATCH guards as diff guard managers. So, we do a tree traversal + # and collect all the nodes in the tree (branches) that lead to tensor + # guards. + + # After a recompilation, some of guard managers will have a fail_count > + # 0, so we collect them as well. Later on, we accumulate the diff guard + # sources for all the guard managers. + + def visit_dict_manager(node: DictGuardManager) -> bool: + is_diff_guard_node = ( + node.get_source() in self.diff_guard_sources or node.fail_count() > 0 + ) + for _idx, (key_mgr, val_mgr) in sorted( + node.get_key_value_managers().items() + ): + is_diff_guard_node |= visit(key_mgr) | visit(val_mgr) + + if is_diff_guard_node: + self.diff_guard_sources.add(node.get_source()) + + return is_diff_guard_node + + def visit_manager(node: GuardManager) -> bool: + if isinstance(node, DictGuardManager): + raise AssertionError( + f"Expected non-DictGuardManager node, got {type(node)}" + ) + + is_diff_guard_node = ( + node.get_source() in self.diff_guard_sources or node.fail_count() > 0 + ) + for child_mgr in node.get_child_managers(): + is_diff_guard_node |= visit(child_mgr) + + if is_diff_guard_node: + self.diff_guard_sources.add(node.get_source()) + + return is_diff_guard_node + + def visit(node: GuardManager) -> bool: + if node is None: + return False + if isinstance(node, DictGuardManager): + return visit_dict_manager(node) + return visit_manager(node) + + visit(self.root) + + return self.diff_guard_sources + + def finalize(self) -> None: + if config.use_recursive_dict_tags_for_guards and justknobs_check( + "pytorch/compiler:use_recursive_dict_tags_for_guards" + ): + self.find_tag_safe_roots() + self.prepare_diff_guard_manager() + + def prepare_diff_guard_manager(self) -> None: + self.collect_diff_guard_sources() + self.populate_diff_guard_manager() + + def find_tag_safe_roots(self) -> None: + """ + Identify ``tag safe nodes`` and ``tag safe roots`` within a guard tree. + + ----------------------------------------------------------------------- + tag safe node + ----------------------------------------------------------------------- + A *tag safe node* is a ``GuardManager`` whose guarded value satisfies one + of the following conditions: + + 1. Immutable value - The value is intrinsically immutable according to + ``is_immutable_object``. Tensors are considered immutable. To ensure + that symbolic guards run, we also check that the GuardManager has no + accessors. + + 2. Nested tag safe dictionary - The value is a ``dict`` whose keys and + values are all tag safe nodes (checked recursively). Such dictionaries + allow entire nested structures to be skipped once their identity tag + matches. + + 3. Pure ``nn.Module`` - The value is an ``nn.Module`` whose sole + accessor is ``GetGenericDictGuardAccessor``—i.e., it only exposes its + ``__dict__`` and nothing else that could mutate between runs. + + For every tag safe node, verifying the identity/tag of just the top-level + dictionary is enough to guarantee the entire subtree is unchanged, enabling + a *fast-path* guard check. + + ----------------------------------------------------------------------- + tag safe root + ----------------------------------------------------------------------- + A ``tag safe root`` is a tag safe node whose parent is not tag safe. + These boundary nodes mark the points where guard evaluation can safely + prune traversal: if a tag-safe root's dictionary tag matches, the entire + subtree beneath it is skipped. + + One strong requirement for tag safe root is for the guarded object to + support weakref. Refer to more details in the Recursive dict tag + matching note. In short, we need to save the weakref of the object on + first invocation, and check if it is still valid in later iterations, to + apply recursive dict tag optimizations. `dict` objects do NOT support + weakref. Therefore, as of now, we only mark nn module related guard + managers as tag safe roots. + + Algorithm + --------- + The search runs in post-order traversal + + 1. Visit leaves and classify them as tag safe or not. + 2. Propagate tag-safety upward: a parent dictionary becomes tag safe only if + all of its children are already tag-safe. + 3. Propagate tag-safe-rootness upward: if the whole subtree is tag safe, + the current node becomes the new tag safe root, otherwise propagate the + subtree tag safe roots. + 4. Collect every tag safe node and, by inspecting parent tags, label the + subset that are tag safe roots. + """ + + def check_tag_safety( + node: GuardManager, accepted_accessors: tuple[type[GuardAccessor], ...] + ) -> bool: + accessors = node.get_accessors() + child_mgrs = node.get_child_managers() + return all( + isinstance(accessor, accepted_accessors) and mgr.is_tag_safe() + for accessor, mgr in zip(accessors, child_mgrs) + ) + + def visit_dict_manager(node: DictGuardManager) -> list[GuardManager]: + # Just recurse through the key and value dict managers and check if + # all of them are tag safe nodes. + if not issubclass(node.get_type_of_guarded_value(), dict): + raise AssertionError( + f"Expected dict subclass, got {node.get_type_of_guarded_value()}" + ) + + tag_safe_roots = [] + is_subtree_tag_safe = True + + # Recurse to get the tag safe roots from subtree. + for _idx, (key_mgr, val_mgr) in sorted( + node.get_key_value_managers().items() + ): + if key_mgr is not None: + visit(key_mgr) + if val_mgr is not None: + tag_safe_roots.extend(visit(val_mgr)) + + for key_mgr, val_mgr in node.get_key_value_managers().values(): + if key_mgr: + is_subtree_tag_safe &= key_mgr.is_tag_safe() + + if val_mgr: + is_subtree_tag_safe &= val_mgr.is_tag_safe() + + if is_subtree_tag_safe: + node.mark_tag_safe() + return tag_safe_roots + + def visit_manager(node: GuardManager) -> list[GuardManager]: + if isinstance(node, DictGuardManager): + raise AssertionError( + f"Expected non-DictGuardManager node, got {type(node)}" + ) + + # Collect the subtree tag safe roots + tag_safe_roots = [] + for child_mgr in node.get_child_managers(): + tag_safe_roots.extend(visit(child_mgr)) + + if node.is_guarded_value_immutable(): + # If the node guards a tensor, mark it tag safe only if there + # are no accessors. Presence of accessors means presence of + # symbolic shape guards. + if issubclass(node.get_type_of_guarded_value(), torch.Tensor): + if node.has_no_accessors() and not node.has_object_aliasing_guard(): + node.mark_tag_safe() + elif any( + a.repr() == "PythonLambdaGuardAccessor" + for a in node.get_accessors() + ): + # PythonLambdaGuardAccessor produces ephemeral objects + # (e.g., ___from_numpy converts np.float64 to a temporary + # tensor). These must not be stashed by the tag-safe + # recording pass since they are freed after each check. + pass + else: + node.mark_tag_safe() + elif issubclass(node.get_type_of_guarded_value(), dict): + accessors = node.get_accessors() + child_mgrs = node.get_child_managers() + is_subtree_tag_safe = all( + isinstance(accessor, DictGetItemGuardAccessor) and mgr.is_tag_safe() + for accessor, mgr in zip(accessors, child_mgrs) + ) + if is_subtree_tag_safe: + node.mark_tag_safe() + elif issubclass(node.get_type_of_guarded_value(), torch.nn.Module): + is_subtree_tag_safe = check_tag_safety( + node, (GetGenericDictGuardAccessor, TypeGuardAccessor) + ) + if is_subtree_tag_safe: + node.mark_tag_safe() + # Return the current node as tag safe root, discarding the + # subtree tag safe roots. + return [ + node, + ] + elif ( + node.get_type_of_guarded_value() + in ( + types.FunctionType, + types.MethodType, + staticmethod, + classmethod, + ) + and config.assume_dunder_attributes_remain_unchanged + ): + # Assumption: callers will not reassign the attributes + # func.__code__, func.__closure__, func.__defaults__, or func.__kwdefaults__. + # Mutating the objects those attributes point to is fine; + # rebinding the attribute itself is not. + # Example ─ allowed: foo.__defaults__[0].bar = 99 + # forbidden: foo.__defaults__ = (3, 4) + is_subtree_tag_safe = check_tag_safety( + node, + ( + CodeGuardAccessor, + ClosureGuardAccessor, + FuncDefaultsGuardAccessor, + FuncKwDefaultsGuardAccessor, + GetAttrGuardAccessor, + ), + ) + + for accessor in node.get_accessors(): + if isinstance(accessor, GetAttrGuardAccessor): + is_subtree_tag_safe &= ( + accessor.get_attr_name() in dunder_attrs_assumed_constants + ) + + if is_subtree_tag_safe: + node.mark_tag_safe() + elif issubclass(node.get_type_of_guarded_value(), types.CellType): + is_subtree_tag_safe = check_tag_safety(node, (GetAttrGuardAccessor,)) + + is_subtree_tag_safe &= all( + isinstance(accessor, GetAttrGuardAccessor) + and accessor.get_attr_name() == "cell_contents" + for accessor in node.get_accessors() + ) + if is_subtree_tag_safe: + node.mark_tag_safe() + elif ( + issubclass(node.get_type_of_guarded_value(), tuple) + and node.get_source().endswith(dunder_attrs_assumed_constants) + and config.assume_dunder_attributes_remain_unchanged + ): + # We trust tuples obtained from a function's __closure__ or + # __defaults__. Any *other* tuple-valued attribute can be + # silently replaced—for example: + # + # foo.bar = (1, 2) # original + # foo.bar = (3, 4) # rebinding that our dict-tag optimisation won't see + # + # Therefore only tuples from __closure__ / __defaults__ participate in the + # recursive-dict-tag optimization; all others are ignored. + is_subtree_tag_safe = check_tag_safety( + node, (TupleGetItemGuardAccessor,) + ) + if is_subtree_tag_safe: + node.mark_tag_safe() + elif issubclass(node.get_type_of_guarded_value(), type): + is_subtree_tag_safe = check_tag_safety( + node, (TypeDictGuardAccessor, TypeMROGuardAccessor) + ) + if is_subtree_tag_safe: + node.mark_tag_safe() + + return tag_safe_roots + + def visit(node: GuardManager) -> list[GuardManager]: + if node is None: + return [] + if isinstance(node, DictGuardManager): + return visit_dict_manager(node) + return visit_manager(node) + + tag_safe_roots = visit(self.root) + for node in tag_safe_roots: + if issubclass(node.get_type_of_guarded_value(), torch.nn.Module): + node.mark_tag_safe_root() + + def populate_diff_guard_manager(self) -> None: + self.diff_guard_root = self.clone_with_chosen_sources(self.diff_guard_sources) + + # Ensure that C++ side points to the updated diff guard manager. + # When a new GuardManagerWrapper is created, it does not have a + # cache_entry attribute, so it relies on the CacheEntry constructor to + # set the diff_guard_root in C++. But once it is saved in the Dynamo + # cache, C++ side adds a cache_entry attribute. On recompiles, this + # cache_entry is visible, so we update the C++ side to point to the + # update guard manager. + if self.cache_entry: + self.cache_entry.update_diff_guard_root_manager() + + def clone_with_chosen_sources( + self, chosen_sources: OrderedSet[str] + ) -> RootGuardManager: + def filter_fn(node_mgr: GuardManager) -> bool: + return node_mgr.get_source() in chosen_sources + + return self.root.clone_manager(filter_fn) + + def get_guard_lines(self, guard: LeafGuard) -> list[str]: + guard_name = guard.__class__.__name__ + parts = guard.verbose_code_parts() + parts = [guard_name + ": " + part for part in parts] + return parts + + def get_manager_line( + self, guard_manager: GuardManager, accessor_str: str | None = None + ) -> str: + source = guard_manager.get_source() + t = guard_manager.__class__.__name__ + s = t + ": source=" + source + if accessor_str: + s += ", " + accessor_str + s += f", type={guard_manager.get_type_of_guarded_value()}" + s += f", tag_safe=({guard_manager.is_tag_safe()}, {guard_manager.is_tag_safe_root()})" + return s + + def construct_dict_manager_string( + self, mgr: DictGuardManager, body: IndentedBufferWithPrefix + ) -> None: + for idx, (key_mgr, val_mgr) in sorted(mgr.get_key_value_managers().items()): + body.writeline(f"KeyValueManager pair at index={idx}") + with body.indent(): + if key_mgr: + body.writeline(f"KeyManager: {self.get_manager_line(key_mgr)}") + self.construct_manager_string(key_mgr, body) + + if val_mgr: + body.writeline(f"ValueManager: {self.get_manager_line(val_mgr)}") + self.construct_manager_string(val_mgr, body) + + def construct_manager_string( + self, mgr: GuardManager, body: IndentedBufferWithPrefix + ) -> None: + with body.indent(): + for guard in mgr.get_leaf_guards(): + if isinstance(guard, RelationalGuard): + if guard not in self.printed_relational_guards: + self.printed_relational_guards.add(guard) + + body.writelines(self.get_guard_lines(guard)) + else: + body.writelines( + [ + guard.__class__.__name__, + ] + ) + else: + body.writelines(self.get_guard_lines(guard)) + + # This works for both DictGuardManager and SubclassedDictGuardManager + if isinstance(mgr, DictGuardManager): + self.construct_dict_manager_string(mgr, body) + + # General case of GuardManager/RootGuardManager + for accessor, child_mgr in zip( + mgr.get_accessors(), mgr.get_child_managers() + ): + body.writeline( + self.get_manager_line(child_mgr, f"accessed_by={accessor.repr()}") + ) + self.construct_manager_string(child_mgr, body) + + def __str__(self) -> str: + with self._preserve_printed_relational_guards(): + body = IndentedBufferWithPrefix() + body.tabwidth = 1 + body.writeline("", skip_prefix=True) + body.writeline("TREE_GUARD_MANAGER:", skip_prefix=True) + body.writeline("RootGuardManager") + self.construct_manager_string(self.root, body) + if hasattr(self.root, "get_epilogue_lambda_guards"): + for guard in self.root.get_epilogue_lambda_guards(): + body.writelines(self.get_guard_lines(guard)) + return body.getvalue() + + def check(self, x: Any) -> bool: + # Only needed for debugging purposes. + return self.root.check(x) + + def check_verbose(self, x: Any) -> GuardDebugInfo: + # Only needed for debugging purposes. + return self.root.check_verbose(x) + + def populate_code_parts_for_debugging(self) -> None: + # This should be called when the guard manager is fully populated + relational_guards_seen = set() + + def get_code_parts(leaf_guard: LeafGuard) -> list[str]: + code_parts = [] + for verbose_code_part in leaf_guard.verbose_code_parts(): + code_part = verbose_code_part.split("#")[0].rstrip() + code_parts.append(code_part) + return code_parts + + def visit(mgr: GuardManager) -> None: + nonlocal relational_guards_seen + for guard in mgr.get_leaf_guards(): + if isinstance(guard, RelationalGuard): + if guard not in relational_guards_seen: + self.code_parts.extend(get_code_parts(guard)) + relational_guards_seen.add(guard) + else: + self.code_parts.extend(get_code_parts(guard)) + + for child_mgr in mgr.get_child_managers(): + visit(child_mgr) + + visit(self.root) + + +def from_numpy(a: Any) -> torch.Tensor: + # If not numpy array, piggy back on e.g. tensor guards to check type + # Re-enable torch function since we disable it on leaf guards + # we need it to properly construct the tensor if a default device is set + with torch.overrides._enable_torch_function(): + # pyrefly: ignore [missing-attribute] + return torch.as_tensor(a) if isinstance(a, (np.generic, np.ndarray)) else a + + +_async_collective_tensor_type: type | None = None + + +def unwrap_async_collective_tensor(x: torch.Tensor) -> torch.Tensor: + # Backing callable for UnwrapCollectiveTensorSource: yield an + # AsyncCollectiveTensor's inner tensor and leave everything else unchanged, + # so a graph traced on an ACT input is guarded against the unwrapped tensor. + # Runs on the guard-eval hot path, so memoize the ACT type once resolved. + global _async_collective_tensor_type + if _async_collective_tensor_type is None: + from torch._functorch._aot_autograd.utils import ( + get_loaded_async_collective_tensor_type, + ) + + _async_collective_tensor_type = get_loaded_async_collective_tensor_type() + if ( + _async_collective_tensor_type is not None + and type(x) is _async_collective_tensor_type + ): + return x.elem # type: ignore[attr-defined] + return x + + +# For user stack printing +@functools.cache +def uninteresting_files() -> set[str]: + import torch._dynamo.external_utils + import torch._dynamo.polyfills + + mods = [torch._dynamo.external_utils, torch._dynamo.polyfills] + + from torch._dynamo.polyfills.loader import POLYFILLED_MODULES + + # pyrefly: ignore [bad-argument-type] + mods.extend(POLYFILLED_MODULES) + + return {inspect.getfile(m) for m in mods} + + +_CLOSURE_VARS: dict[str, object] | None = None + + +def _get_closure_vars() -> dict[str, object]: + global _CLOSURE_VARS + if _CLOSURE_VARS is None: + _CLOSURE_VARS = { + "___check_type_id": check_type_id, + "___check_obj_id": check_obj_id, + "___odict_getitem": collections.OrderedDict.__getitem__, + "___key_to_id": key_to_id, + "___dict_version": dict_version, + "___dict_contains": lambda a, b: dict.__contains__(b, a), + "___tuple_iterator_len": tuple_iterator_len, + "___normalize_count_iter": normalize_count_iter, + "___normalize_range_iter": normalize_range_iter, + "___tuple_iterator_getitem": tuple_iterator_getitem, + "___set_getitem": set_getitem, + "___dataclass_fields": dataclass_fields, + "___namedtuple_fields": lambda x: x._fields, + "___get_torch_function_mode_stack_at": get_torch_function_mode_stack_at, + "___get_current_stream": get_current_stream, + "___cow_tensor_matches": _cow_tensor_matches, + "__math_isnan": math.isnan, + "__numpy_isnan": None if np is None else np.isnan, + "inf": float("inf"), + "__load_module": importlib.import_module, + "utils_device": torch.utils._device, + "device": torch.device, + "___from_numpy": from_numpy, + "___unwrap_async_collective_tensor": unwrap_async_collective_tensor, + "___as_tensor": torch._as_tensor_fullprec, + "torch": torch, + "inspect": inspect, + } + return _CLOSURE_VARS + + +def _ast_unparse(node: ast.AST) -> str: + return ast.unparse(node).replace("\n", "") + + +strip_function_call = torch._C._dynamo.strip_function_call + + +def _safe_type_repr(t: type[Any]) -> str: + return type.__repr__(t) + + +def get_verbose_code_part(code_part: str, guard: Guard | None) -> str: + extra = "" + if guard is not None: + if guard.user_stack: + for fs in reversed(guard.user_stack): + if fs.filename not in uninteresting_files(): + extra = f" # {format_frame(fs, line=True)}" + if len(extra) > 1024: + # For fx graphs, the line can be very long in case of + # torch.stack ops, where many inputs are set to None + # after the operation. This increases the size of the + # guards log file. In such cases, do not print the line + # contents. + extra = f" # {format_frame(fs)}" + break + elif guard.stack: + summary = guard.stack.summary() + if len(summary) > 0: + extra = f" # {format_frame(summary[-1])}" + else: + extra = " # " + return f"{code_part:<60}{extra}" + + +def get_verbose_code_parts( + code_parts: str | list[str], + guard: Guard | None, + recompile_hint: str | None = None, +) -> list[str]: + if not isinstance(code_parts, list): + code_parts = [code_parts] + + verbose_code_parts = [ + get_verbose_code_part(code_part, guard) for code_part in code_parts + ] + + # For CellContentsSource (or any source with a CellContentsSource ancestor), + # add a hint explaining which closure variable is being checked. + # This helps users understand which closure variable caused the guard failure. + if guard is not None: + closure_hint = _get_closure_var_hint(guard.originating_source) + if closure_hint: + recompile_hint = ( + f"{closure_hint}, {recompile_hint}" if recompile_hint else closure_hint + ) + + if recompile_hint: + verbose_code_parts = [ + f"{part} (HINT: {recompile_hint})" for part in verbose_code_parts + ] + + return verbose_code_parts + + +def _get_closure_var_hint(source: Source | None) -> str | None: + """ + Walk up the source chain to find a CellContentsSource ancestor. + Returns a hint like 'guard on "varname".attr' or None if not found. + """ + if source is None: + return None + + full_name = source.name + current: Source | None = source + while current is not None: + if isinstance(current, CellContentsSource) and current.freevar_name: + # Compute the path suffix by comparing names + # e.g., full_name="x.__closure__[0].cell_contents.scale" + # current.name="x.__closure__[0].cell_contents" + # suffix=".scale" + path_suffix = full_name[len(current.name) :] + return f'guard on "{current.freevar_name}"{path_suffix}' + current = current.base if isinstance(current, ChainedSource) else None + return None + + +def convert_int_to_concrete_values(dim: Any) -> int | None: + if dim is None: + return None + if not is_symbolic(dim): + return dim + else: + if not isinstance(dim, torch.SymInt): + raise AssertionError(f"Expected torch.SymInt, got {type(dim)}") + return dim.node.maybe_as_int() + + +def convert_to_concrete_values(size_or_stride: Sequence[Any]) -> list[int | None]: + return [convert_int_to_concrete_values(dim) for dim in size_or_stride] + + +def get_tensor_guard_code_part( + value: torch.Tensor, + name: str, + sizes: list[int | None], + strides: list[int | None], + pytype: type, + dispatch_keys: DispatchKeySet, +) -> str: + dispatch_key = ( + dispatch_keys | torch._C._dispatch_tls_local_include_set() + ) - torch._C._dispatch_tls_local_exclude_set() + dtype = value.dtype + device_index = value.device.index + requires_grad = value.requires_grad + guard_str = ( + f"check_tensor({name}, {pytype.__qualname__}, {dispatch_key}, {dtype}, " + f"device={device_index}, requires_grad={requires_grad}, size={sizes}, stride={strides})" + ) + return guard_str + + +def get_key_index(dct: dict[Any, Any], key: object) -> int: + # Ensure that we call dict.keys and not value.keys (which can call + # overridden keys method). In the C++ guards, we relied on PyDict_Next + # to traverse the dictionary, which uses the internal data structure and + # does not call the overridden keys method. + return list(builtin_dict_keys(dct)).index(key) + + +def get_key_index_source(source: Any, index: Any) -> str: + return f"list(dict.keys({source}))[{index}]" + + +def raise_local_type_error(obj: object) -> NoReturn: + raise TypeError( + f"Type {type(obj)} for object {obj} cannot be saved " + + "into torch.compile() package since it's defined in local scope. " + + "Please define the class at global scope (top level of a module)." + ) + + +def should_optimize_getattr_on_nn_module(value: object) -> bool: + return isinstance(value, torch.nn.Module) + + +@dataclasses.dataclass(frozen=True) +class NNModuleAttrAccessorInfo: + # Represents where is the attr name is present in the nn module attribute + # access + + # Tells that the attribute can be accessed via __dict__ + present_in_generic_dict: bool = False + + # Either the actual name or _parameters/_buffers/_modules + l1_key: str | None = None + + # Actual parameter/buffer/submodule name + l2_key: str | None = None + + +def getitem_on_dict_manager( + source: DictGetItemSource | DictSubclassGetItemSource, + base_guard_manager: DictGuardManager, + base_example_value: Any, + example_value: Any, + guard_manager_enum: GuardManagerType, +) -> GuardManager: + base_source_name = source.base.name + if isinstance(source.index, ConstDictKeySource): + index = source.index.index + else: + if not isinstance(base_example_value, dict): + raise AssertionError(f"Expected dict, got {type(base_example_value)}") + index = get_key_index(base_example_value, source.index) + + key_source = get_key_index_source(base_source_name, index) + + # Ensure that we call dict.keys and not value.keys (which can call + # overridden keys method). In the C++ guards, we relied on PyDict_Next + # to traverse the dictionary, which uses the internal data structure and + # does not call the overridden keys method. + key_example_value = list(builtin_dict_keys(base_example_value))[index] + if isinstance(key_example_value, (int, str)): + value_source = f"{base_source_name}[{key_example_value!r}]" + else: + value_source = f"{base_source_name}[{key_source}]" + if not isinstance(source.index, ConstDictKeySource): + # We have to insert a key manager guard here + # TODO - source debug string is probably wrong here. + base_guard_manager.get_key_manager( + index=index, + source=key_source, + example_value=source.index, + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ).add_equals_match_guard( + source.index, [f"{key_source} == {key_example_value!r}"], None + ) + + return base_guard_manager.get_value_manager( + index=index, + source=value_source, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + + +def match_on_id_for_tensor(guard: Guard) -> bool: + source = guard.originating_source + # For numpy tensors, always use TENSOR_MATCH because __from_numpy leads + # to a new tensor every time and therefore id differs. + if isinstance(source, NumpyTensorSource): + return False + + if guard.is_specialized_nn_module(): + return True + + return source.is_dict_key() and not isinstance(source, GradSource) + + +# The ready to eval generated code (possibly multiple parts) for a guard, plus +# the original guard object that created it for provenance +@dataclasses.dataclass +class GuardCodeList: + code_list: list[str] + guard: Guard + + +class GuardManagerType(enum.Enum): + GUARD_MANAGER = 1 + DICT_GUARD_MANAGER = 2 + + +@functools.cache +def code_framelocals_names_reversed_cached(code: types.CodeType) -> list[str]: + return list(reversed(code_framelocals_names(code))) + + +class GuardCheckSpec(NamedTuple): + """Lightweight guard evaluation for subgraph reuse during tracing. + + WHY IS THIS NEEDED? + Normal guards are collected during tracing, installed via GuardBuilder, and + evaluated in C++ at runtime. GuardCheckSpec serves a different purpose: we + want to evaluate a guard *during tracing* to check whether a previously + traced partial subgraph can be reused. The guard is collected during the + first trace of subgraph and then evaluated with a new source value before we + begin tracing the second subgraph. + + Existing C++ guards don't satisfy this need because they're designed for + runtime evaluation, not mid-trace comparisons with different source values. + + NB - This separate spec table *increases maintenance burden*, but each + handler is small and the number of guard types is finite, so it's tractable. + + get_metadata_fn: (guard, value) -> metadata — captures the minimum + information from the guarded value at build time. + eval_fn: (value, metadata) -> bool — re-evaluates the guard at lookup + time using a fresh value and the previously saved metadata. + """ + + get_metadata_fn: GuardCheckGetMetadataFn + eval_fn: GuardCheckEvalFn + + +SKIP_GUARD = object() + + +# Used by TENSOR_MATCH guard check spec +def extract_tensor_metadata(t: torch.Tensor) -> tuple[Any, ...]: + return (t.shape, t.stride(), t.dtype, t.device, t.requires_grad) + + +def _subclass_metadata_contains_tensor(metadata: Any) -> bool: + if isinstance(metadata, torch.Tensor): + return True + + node_type = pytree._get_node_type(metadata) + if node_type not in pytree.SUPPORTED_NODES: + return False + + if isinstance(metadata, collections.abc.Mapping): + for key in metadata: + if _subclass_metadata_contains_tensor(key): + return True + + children, _ = pytree.SUPPORTED_NODES[node_type].flatten_fn(metadata) + for child in children: + if _subclass_metadata_contains_tensor(child): + return True + return False + + +def _validate_default_subclass_metadata_guard(metadata: Any, cls: type[Any]) -> None: + if not _subclass_metadata_contains_tensor(metadata): + return + + raise exc.InternalTorchDynamoError( + f"Tensor subclass {cls.__module__}.{cls.__qualname__} returned Tensor " + "metadata from __tensor_flatten__() but does not define " + "__metadata_guard__. Dynamo's default tensor subclass metadata guard " + "uses Python equality, which is not valid for Tensor metadata. Move " + "tensor values to the inner tensor names returned by " + "__tensor_flatten__(), or define a classmethod __metadata_guard__" + "(original_metadata, current_metadata) to compare tensor metadata " + "explicitly." + ) + + +# Used by TENSOR_SUBCLASS_METADATA_MATCH guard check spec. +# Unlike check_dtensor_spec below, this pair is only reached at trace time: +# TENSOR_SUBCLASS_METADATA_MATCH has its own inlined metadata_checker closure +# for the C++ path, so narrowing with a typing.cast is free here. +def extract_subclass_metadata(guard: Any, value: object) -> tuple[Any, ...]: + cls = type(value) + has_custom_guard = hasattr(value, "__metadata_guard__") + metadata = cast("TraceableWrapperSubclass", value).__tensor_flatten__()[1] + if not has_custom_guard: + _validate_default_subclass_metadata_guard(metadata, cls) + metadata = deepcopy(metadata) + return (metadata, cls, has_custom_guard) + + +# Used by TENSOR_SUBCLASS_METADATA_MATCH guard check spec +def check_subclass_metadata(value: object, metadata: tuple[Any, ...]) -> bool: + saved_metadata, cls, has_custom_guard = metadata + subclass_metadata = cast("TraceableWrapperSubclass", value).__tensor_flatten__()[1] + if has_custom_guard: + return cls.__metadata_guard__(saved_metadata, subclass_metadata) + return subclass_metadata == saved_metadata + + +# Used by DTENSOR_SPEC_MATCH guard check spec +def extract_dtensor_spec(guard: Any, value: object) -> Any: + return deepcopy(value) + + +# Used by DTENSOR_SPEC_MATCH guard check spec +def check_dtensor_spec(value: object, metadata: Any) -> bool: + # DTENSOR_SPEC_MATCH's lambda guard calls this on every guard evaluation, + # so narrow with a suppression rather than a typing.cast, which would be a + # real call on the check path. + # pyrefly: ignore[missing-attribute] + return value._check_equals(metadata, skip_shapes=True) + + +# Used by OPAQUE_OBJ_GUARD_FN_MATCH guard check spec +def extract_opaque_obj(guard: Any, value: object) -> Any: + opaque_info = get_opaque_obj_info(type(value)) + if not opaque_info or not opaque_info.guard_fn: + return None + return deepcopy(opaque_info.guard_fn(value)) + + +# Used by OPAQUE_OBJ_GUARD_FN_MATCH guard check spec +def check_opaque_obj(value: object, metadata: Any) -> bool: + if metadata is None: + return True + opaque_info = get_opaque_obj_info(type(value)) + if not opaque_info or not opaque_info.guard_fn: + return metadata is None + return opaque_info.guard_fn(value) == metadata + + +# Used by CLOSURE_MATCH guard check spec +def extract_closure(guard: Any, value: object) -> Any: + if type(value) is types.FunctionType and hasattr(value, "__code__"): + return value.__code__ + return id(value) + + +# Used by CLOSURE_MATCH guard check spec +def check_closure(value: object, metadata: Any) -> bool: + if type(value) is types.FunctionType and hasattr(value, "__code__"): + return value.__code__ is metadata + return id(value) == metadata + + +def _constant_subclass_base_value(value: object) -> Any: + """Extract the base constant value from a constant subclass instance.""" + from .variables.user_defined import _CONSTANT_BASE_TYPES + + for t in _CONSTANT_BASE_TYPES: + if isinstance(value, t): + return t(value) # pyrefly: ignore[bad-argument-type] + raise TypeError(f"Not a constant subclass: {type(value)}") + + +def _guard_create_fn_keyword(guard: Guard, name: str) -> Any: + """Read a keyword bound into a guard's create_fn functools.partial.""" + create_fn = guard.create_fn + if not isinstance(create_fn, functools.partial): + raise TypeError(f"Guard create_fn is not a functools.partial: {create_fn}") + return create_fn.keywords[name] + + +def register_guard_check_spec( + get_metadata_fn: GuardCheckGetMetadataFn, + eval_fn: GuardCheckEvalFn, +): + """Attach a GuardCheckSpec to a guard method for auto-dispatch.""" + handler = GuardCheckSpec(get_metadata_fn=get_metadata_fn, eval_fn=eval_fn) + + def decorator(fn): + fn.guard_check_spec = handler + return fn + + return decorator + + +def skip_guard_check_spec(fn): + """Mark a guard method as skipped during auto-cache dispatch.""" + fn.guard_check_spec = SKIP_GUARD + return fn + + +class UnsupportedGuardCheckSpec: + """Sentinel for guards with no check spec yet. + + Raises NotImplementedError if get_metadata_fn/eval_fn are accidentally called. + """ + + def __init__(self, name: str) -> None: + self._name = name + + @property + def get_metadata_fn(self): + raise NotImplementedError(f"Guard check spec not implemented for {self._name}") + + @property + def eval_fn(self): + raise NotImplementedError(f"Guard check spec not implemented for {self._name}") + + +def unsupported_guard_check_spec(fn): + """Mark a guard method as unsupported for auto-cache dispatch.""" + fn.guard_check_spec = UnsupportedGuardCheckSpec(fn.__name__) + return fn + + +class GuardBuilder(GuardBuilderBase): + def __init__( + self, + f_code: types.CodeType, + id_ref: Callable[[object, str], int], + source_ref: Callable[[Source], str], + lookup_weakrefs: Callable[[object], weakref.ref[object] | None], + local_scope: dict[str, object], + global_scope: dict[str, object], + guard_manager: GuardManagerWrapper, + check_fn_manager: CheckFunctionManager, + save_guards: bool = False, + runtime_global_scope: dict[str, object] | None = None, + guard_filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] + | None = None, + ) -> None: + self.f_code = f_code + self.id_ref = id_ref + self.source_ref = source_ref + self.lookup_weakrefs = lookup_weakrefs + self.scope: dict[str, dict[str, object]] = {"L": local_scope, "G": global_scope} + self.src_get_value_cache: dict[Source, object] = {} + self.runtime_global_scope = runtime_global_scope or global_scope + self.scope["__builtins__"] = builtins.__dict__.copy() + for ( + name, + package_module, + ) in torch.package.package_importer._package_imported_modules.items(): + name = name.replace(">", "_").replace("<", "_").replace(".", "_dot_") + # Write the package module into the scope so that we can import it + self.scope["__builtins__"][name] = package_module + # Write the demangled name to the scope so that we can use it + self.scope[name] = package_module + self.guard_manager = guard_manager + + self.argnames: list[str] = [] + # Code is python expression strings generated for each guard + self.code: list[GuardCodeList] = [] + # shape_env_code is only used by builder and is used for + # shape env code. This exists only because we need to make sure + # shape env guards get run after tensor match guards (since the + # tensor match guards make sure we actually have tensors) + self.shape_env_code: list[GuardCodeList] = [] + + # Collect the guard managers and debug info to insert no tensor aliasing + # guards. + self.no_tensor_aliasing_names: list[str] = [] + self.no_tensor_aliasing_guard_managers: list[GuardManager] = [] + + self.check_fn_manager: CheckFunctionManager = check_fn_manager + + self.guard_tree_values: dict[int, Any] = {} + self.save_guards = save_guards + self.guard_filter_fn = guard_filter_fn + + # Collect the ids of dicts which need key order guarding. source_name is + # not sufficient because for nn modules, we can have different sources + # to access the same object - self._module["param"] is same as + # self.param. + self.key_order_guarded_dict_ids = set() + if self.check_fn_manager.output_graph is None: + raise AssertionError("check_fn_manager.output_graph must not be None") + for source in self.check_fn_manager.output_graph.guard_on_key_order: + dict_obj = self.get(source) + self.key_order_guarded_dict_ids.add(id(dict_obj)) + + # Keep track of weak references of objects with ID_MATCH guard. This + # info is stored alongside optimized_code and guard_manager and is used to + # limit the number of cache entries with same ID_MATCH'd object. + self.id_matched_objs: dict[str, ReferenceType[object]] = {} + + # Save the guard managers to avoid repeatedly traversing sources. + self._cached_guard_managers: dict[str, GuardManager] = {} + self._cached_duplicate_input_guards: set[tuple[str, str]] = set() + self.object_aliasing_guard_codes: list[tuple[str, str]] = [] + self.guard_nn_modules = config.guard_nn_modules and justknobs_check( + "pytorch/compiler:guard_nn_modules" + ) + self.already_added_code_parts: OrderedSet[str] = OrderedSet() + + def guard_on_dict_keys_and_ignore_order( + self, example_value: dict[Any, Any], guard: Guard + ) -> None: + dict_mgr = self.get_guard_manager(guard) + if isinstance(dict_mgr, DictGuardManager): + raise NotImplementedError( + "Not expecting a DictGuardManager. Seems like Dynamo incorrectly " + f"added the dict to tx.output.guard_on_key_order for {guard.name}" + ) + + # Iterate over the dicts and install a dict_getitem_manager. + dict_source = guard.originating_source.name + + # Ensure that we call dict.keys and not value.keys (which can call + # overridden keys method). In the C++ guards, we relied on PyDict_Next + # to traverse the dictionary, which uses the internal data structure and + # does not call the overridden keys method. + for key in builtin_dict_keys(example_value): + value = example_value[key] + value_source = DictGetItemSource(guard.originating_source, index=key) + guard_manager_enum = self.get_guard_manager_type( + value_source, example_value + ) + dict_mgr.dict_getitem_manager( + key=key, + source=f"{dict_source}[{key!r}]", + example_value=value, + guard_manager_enum=guard_manager_enum, + ) + + def guard_on_dict_keys_and_order(self, value: dict[Any, Any], guard: Guard) -> None: + # Add key managers for the DictGuardManager. Then add either an + # ID_MATCH or EQUALS_MATCH guard on the key. + dict_mgr = self.get_guard_manager(guard) + if not isinstance(dict_mgr, DictGuardManager): + raise NotImplementedError( + "Expecting a DictGuardManager. Seems like Dynamo forgot " + f"to set the right guard manager enum for {guard.name}" + ) + if not isinstance(dict_mgr, DictGuardManager): + raise AssertionError(f"Expected DictGuardManager, got {type(dict_mgr)}") + + # Ensure that we call dict.keys and not value.keys (which can call + # overridden keys method). In the C++ guards, we relied on PyDict_Next + # to traverse the dictionary, which uses the internal data structure and + # does not call the overridden keys method. + for idx, key in enumerate(builtin_dict_keys(value)): + key_source = get_key_index_source(guard.name, idx) + key_manager = dict_mgr.get_key_manager( + index=idx, + source=key_source, + example_value=key, + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ) + if key_is_id(key): + # Install ID_MATCH guard + id_val = self.id_ref(key, key_source) + key_manager.add_id_match_guard( + id_val, + get_verbose_code_parts( + f"__check_obj_id({key_source}, {id_val})", guard + ), + guard.user_stack, + ) + else: + # Install EQUALS_MATCH guard + key_manager.add_equals_match_guard( + key, + get_verbose_code_parts(f"{key_source} == {key!r}", guard), + guard.user_stack, + ) + + @staticmethod + def _get_generic_dict_manager_example_value(example_value: Any) -> Any | None: + # due to a bug in 3.13.0 (introduced by https://github.com/python/cpython/pull/116115, + # reported in https://github.com/python/cpython/issues/125608, + # fixed by https://github.com/python/cpython/pull/125611), we cannot take + # advantage of __dict__ versions to speed up guard checks. + if ( + config.issue_3_13_0_warning + and sys.version_info >= (3, 13) + and sys.version_info < (3, 13, 1) + ): + warnings.warn( + "Guards may run slower on Python 3.13.0. Consider upgrading to Python 3.13.1+.", + RuntimeWarning, + ) + return None + return example_value + + def getattr_on_nn_module( + self, + source: AttrSource, + base_guard_manager: GuardManager, + base_example_value: Any, + example_value: Any, + base_source_name: str, + source_name: str, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: + """ + This tries to avoid calling the expensive nn module custom getattr method by + checking if the attribute is accessible via __dict__. For attributes that + are not accessible via __dict__ (like descriptors), we fallback to + PyObject_GetAttr. + + There are two cases that we optimize for + 1) attributes present directly in __dict__, e.g training. + 2) parameters/buffers/modules - they can be accessed via _parameters, + _buffers, _modules keys in __dict__. For example, mod.linear can be + accessed as mod.__dict__["_parameters"]["linear"] + + The most common and expensive case for nn module guards is of type + mod.submod1.submod2.submod3.training. We avoid the python getattr of nn + modules by going through the __dict__. + """ + + def getitem_on_dict_mgr( + mgr: GuardManager, + key: Any, + source_name: str, + base_example_value: Any, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: + if isinstance(mgr, DictGuardManager): + # Case where the user code relies on key order, e.g., + # named_parameters + index = get_key_index(base_example_value, key) + + # Install the key manager and add equals match guard + key_source = f"list(dict.keys({source_name}))[{index!r}]" + mgr.get_key_manager( + index=index, + source=key_source, + example_value=key, + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ).add_equals_match_guard(key, [f"{key_source} == {key!r}"], None) + + # Install the value manager + return mgr.get_value_manager( + index=index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + return mgr.dict_getitem_manager( + key=key, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + + attr_name = source.member + mod_dict = base_example_value.__dict__ + + all_class_attribute_names: set[str] = set() + for x in inspect.getmro(base_example_value.__class__): + all_class_attribute_names.update(x.__dict__.keys()) + + accessor_info = NNModuleAttrAccessorInfo(False, None, None) + + if attr_name in mod_dict: + accessor_info = NNModuleAttrAccessorInfo(True, attr_name, None) + elif "_parameters" in mod_dict and attr_name in mod_dict["_parameters"]: + accessor_info = NNModuleAttrAccessorInfo(True, "_parameters", attr_name) + elif "_buffers" in mod_dict and attr_name in mod_dict["_buffers"]: + accessor_info = NNModuleAttrAccessorInfo(True, "_buffers", attr_name) + elif ( + attr_name not in all_class_attribute_names + and "_modules" in mod_dict + and attr_name in mod_dict["_modules"] + ): + # Check test_attr_precedence test - instance attributes always take precedence unless its an nn.Module. + accessor_info = NNModuleAttrAccessorInfo(True, "_modules", attr_name) + + if not accessor_info.present_in_generic_dict: + # The attribute can be accessed by __getattribute__ call, so rely on + # PyObject_GetAttr + return base_guard_manager.getattr_manager( + attr=source.member, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + if not accessor_info.l1_key: + raise AssertionError("accessor_info.l1_key must not be empty") + l1_key = accessor_info.l1_key + l2_key = accessor_info.l2_key + + # Set source strings for debug info + mod_dict_source = f"{base_source_name}.__dict__" + l1_source_name = l2_source_name = None + l1_value = l2_value = None + l1_guard_manager_enum = l2_guard_manager_enum = None + if l2_key: + l1_source = AttrSource(source.base, l1_key) + l1_source_name = l1_source.name + l1_value = mod_dict[l1_key] + # do not guard on key order for _parameters etc unless the user code + # actually needs the key order (e.g. calling named_parameters) + l1_guard_manager_enum = self.get_guard_manager_type(l1_source, l1_value) + + l2_source_name = source_name + l2_value = example_value + l2_guard_manager_enum = self.get_guard_manager_type( + source, example_value + ) + else: + l1_source_name = source_name + l1_value = example_value + l1_guard_manager_enum = self.get_guard_manager_type( + source, example_value + ) + + # Get __dict__ accessor. No need to guard on dict key order, so use base + # Guard Manager + mod_generic_dict_manager = base_guard_manager.get_generic_dict_manager( + source=mod_dict_source, + example_value=self._get_generic_dict_manager_example_value(mod_dict), + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ) + + l1_mgr = getitem_on_dict_mgr( + mgr=mod_generic_dict_manager, + key=l1_key, + source_name=l1_source_name, + base_example_value=mod_dict, + example_value=l1_value, + guard_manager_enum=l1_guard_manager_enum, + ) + + if l2_key: + if l2_source_name is None or l2_guard_manager_enum is None: + raise AssertionError( + "l2_source_name and l2_guard_manager_enum must not be None" + ) + return getitem_on_dict_mgr( + mgr=l1_mgr, + key=l2_key, + source_name=l2_source_name, + base_example_value=l1_value, + example_value=l2_value, + guard_manager_enum=l2_guard_manager_enum, + ) + return l1_mgr + + def requires_key_order_guarding(self, source: Source) -> bool: + source_name = source.name + if source_name == "": + return False + obj_id = id(self.get(source)) + return obj_id in self.key_order_guarded_dict_ids + + def get_guard_manager_type( + self, + source: Source, + example_value: KeysView[Any] + | set[Any] + | frozenset[Any] + | dict[Any, Any] + | None, + ) -> GuardManagerType: + guard_manager_enum = GuardManagerType.GUARD_MANAGER + if self.requires_key_order_guarding(source): + # Fix this if condition + if isinstance(example_value, dict_keys): + guard_manager_enum = GuardManagerType.DICT_GUARD_MANAGER + elif isinstance(example_value, (set, frozenset)): + # we don't need to guard on key order for set/frozenset + # but the if above will be true for these types as set is + # implemented using a dict in Dynamo + guard_manager_enum = GuardManagerType.GUARD_MANAGER + else: + if not isinstance(example_value, dict): + raise AssertionError(f"Expected dict, got {type(example_value)}") + guard_manager_enum = GuardManagerType.DICT_GUARD_MANAGER + return guard_manager_enum + + def manager_guards_on_keys(self, mgr_enum: GuardManagerType) -> bool: + return mgr_enum == GuardManagerType.DICT_GUARD_MANAGER + + def get_global_guard_manager(self) -> GuardManager: + return self.guard_manager.root.globals_dict_manager( + f_globals=self.runtime_global_scope, + source="G", + example_value=self.scope["G"], + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ) + + def get_guard_manager_from_source(self, source: Source) -> GuardManager: + root_guard_manager = self.guard_manager.root + + example_value = None + source_name = source.name + + if source_name != "" and source_name in self._cached_guard_managers: + return self._cached_guard_managers[source_name] + + if source_name != "": + example_value = self.get(source) + self.guard_tree_values[id(example_value)] = example_value + + guard_manager_enum = self.get_guard_manager_type(source, example_value) + + # Get base manager related information + base_source_name = None + base_example_value = None + base_guard_manager = None + base_guard_manager_enum = GuardManagerType.GUARD_MANAGER + if isinstance(source, ChainedSource): + base_source_name = source.base.name + base_example_value = self.get(source.base) + base_guard_manager = self.get_guard_manager_from_source(source.base) + base_guard_manager_enum = self.get_guard_manager_type( + source.base, base_example_value + ) + + # Use istype instead of isinstance to check for exact type of source. + if istype(source, LocalSource): + framelocals_idx = get_framelocals_idx(self.f_code, source.local_name) + out = root_guard_manager.framelocals_manager( + key=(source.local_name, framelocals_idx), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GlobalSource): + # Global manager accepts a dict but it is not a DictGuardManager + # because globals dict is big and we typically guard on a very + # selected items on globals. + out = self.get_global_guard_manager().dict_getitem_manager( + key=source.global_name, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GlobalWeakRefSource): + out = self.get_global_guard_manager().global_weakref_manager( + global_name=source.global_name, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GlobalStateSource): + # Don't do anything here. We guard on global state completely in + # C++. So just return the root mgr. + return root_guard_manager + elif istype(source, ShapeEnvSource): + return root_guard_manager + elif istype(source, TypeSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.type_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, TypeDictSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.type_dict_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, TypeMROSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.type_mro_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype( + source, + ( + OptimizerSource, + NNModuleSource, + UnspecializedNNModuleSource, + UnspecializedBuiltinNNModuleSource, + FSDPNNModuleSource, + ), + ): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager + elif istype(source, ImportSource): + module = importlib.import_module(source.module_name) + out = root_guard_manager.lambda_manager( + python_lambda=lambda _, m=module: m, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, TorchFunctionModeStackSource): + out = root_guard_manager.lambda_manager( + python_lambda=lambda _: get_torch_function_mode_stack_at( + source._get_index() + ), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, CurrentStreamSource): + out = root_guard_manager.lambda_manager( + python_lambda=lambda _: get_current_stream(source.device), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GradSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.grad_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GenericAttrSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.generic_getattr_manager( + attr=source.member, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype( + source, (AttrSource, CellContentsSource, UnspecializedParamBufferSource) + ): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + if not isinstance(source, AttrSource): + raise AssertionError(f"Expected AttrSource, got {type(source)}") + if should_optimize_getattr_on_nn_module(base_example_value): + if not base_source_name: + raise AssertionError("base_source_name must not be empty") + out = self.getattr_on_nn_module( + source, + base_guard_manager, + base_example_value, + example_value, + base_source_name, + source_name, + guard_manager_enum, + ) + else: + out = base_guard_manager.getattr_manager( + attr=source.member, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, (DictGetItemSource, DictSubclassGetItemSource)): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + if not isinstance(base_example_value, (dict, collections.OrderedDict)): + raise AssertionError( + f"Expected dict or OrderedDict, got {type(base_example_value)}" + ) + if not isinstance(source, (DictGetItemSource, DictSubclassGetItemSource)): + raise AssertionError( + f"Expected DictGetItemSource or DictSubclassGetItemSource, got {type(source)}" + ) + if isinstance(base_guard_manager, DictGuardManager): + if not self.manager_guards_on_keys(base_guard_manager_enum): + raise AssertionError("DictGuardManager must guard on keys") + out = getitem_on_dict_manager( + source, + base_guard_manager, + base_example_value, + example_value, + guard_manager_enum, + ) + else: + if isinstance(source.index, ConstDictKeySource): + raise RuntimeError( + "Expecting clean index here. Likely Dynamo forgot to mark" + " a dict as guard_on_key_order" + ) + out = base_guard_manager.dict_getitem_manager( + key=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, TensorPropertySource): + out = getattr( + base_guard_manager, + f"tensor_property_{source.prop.name.lower()}_manager", + )( + idx=source.idx, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, IndexedSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + + out = base_guard_manager.indexed_manager( + idx=source.idx, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, ListGetItemSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.list_getitem_manager( + key=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GetItemSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + if isinstance(base_example_value, (dict, collections.OrderedDict)): + raise AssertionError("Use DictGetItemSource") + if isinstance(base_example_value, list) and not source.index_is_slice: + out = base_guard_manager.list_getitem_manager( + key=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif isinstance(base_example_value, tuple) and not source.index_is_slice: + out = base_guard_manager.tuple_getitem_manager( + key=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + index = source.index + if source.index_is_slice: + index = source.unpack_slice() + out = base_guard_manager.getitem_manager( + key=index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, DefaultsSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + if not base_source_name: + raise AssertionError("base_source_name must not be empty") + if not callable(base_example_value): + raise AssertionError("base_example_value must be callable") + if not source.is_kw: + out = base_guard_manager.func_defaults_manager( + source=base_source_name, + example_value=base_example_value.__defaults__, + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ).getitem_manager( + key=source.idx_key, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + # kwdefauts is a dict, so use a DictGuardManager + kwdefaults = base_example_value.__kwdefaults__ + if base_source_name is None: + raise AssertionError("base_source_name must not be None") + kw_source = base_source_name + ".__kwdefaults__" + + # kwdefaults is a dict. No need to guard on dict order. + dict_mgr = base_guard_manager.func_kwdefaults_manager( + source=kw_source, + example_value=kwdefaults, + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ) + if isinstance(dict_mgr, DictGuardManager): + raise AssertionError("Expected non-DictGuardManager for kwdefaults") + + out = dict_mgr.dict_getitem_manager( + key=source.idx_key, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, NumpyTensorSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=from_numpy, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, SubclassAttrListSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x.__tensor_flatten__()[0], + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, UnwrapCollectiveTensorSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=unwrap_async_collective_tensor, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, FlattenScriptObjectSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x.__obj_flatten__(), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, ScriptObjectQualifiedNameSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x._type().qualified_name(), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, AttrProxySource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x.get_base(), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, CallMethodItemSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x.item(), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, ContextVarGetSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + if source.has_default: + default_val = source.default_value + out = base_guard_manager.lambda_manager( + python_lambda=lambda x, d=default_val: x.get(d), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x.get(), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, FloatTensorSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: torch._as_tensor_fullprec(x), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, TupleIteratorGetItemSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.tuple_iterator_getitem_manager( + index=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif isinstance(source, ConstDictKeySource): + if not isinstance(base_guard_manager, DictGuardManager): + raise AssertionError( + "ConstDictKeySource can only work on DictGuardManager" + ) + out = base_guard_manager.get_key_manager( + index=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, NonSerializableSetGetItemSource): + if not base_guard_manager: + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.set_getitem_manager( + index=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, WeakRefCallSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.weakref_call_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, CallFunctionNoArgsSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.call_function_no_args_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, DataclassFieldsSource): + if not base_guard_manager: + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: dataclass_fields(x), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, NamedTupleFieldsSource): + if not base_guard_manager: + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x._fields, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, CodeSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.code_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, ClosureSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.closure_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, DynamicScalarSource): + if not base_guard_manager: + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: int(x), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + raise AssertionError( + f"missing guard manager builder {source} - {source.name}" + ) + + self._cached_guard_managers[source.name] = out + return out + + def get_guard_manager(self, guard: Guard) -> GuardManager: + return self.get_guard_manager_from_source(guard.originating_source) + + def add_python_lambda_leaf_guard_to_root( + self, + code_parts: list[str], + verbose_code_parts: list[str], + closure_vars: dict[str, object] | None = None, + is_epilogue: bool = True, + ) -> None: + if closure_vars is None: + closure_vars = _get_closure_vars() + # Adds a lambda leaf guard to the root guard manager. It wraps the + # code_parts in a function object which is then passed on to the leaf + # guard. + make_guard_fn_args = ", ".join(closure_vars.keys()) + _guard_body, pycode = build_guard_function(code_parts, make_guard_fn_args) + out: dict[str, Any] = {} + globals_for_guard_fn = {"G": self.scope["G"]} + guards_log.debug("Python shape guard function:\n%s", pycode) + exec(pycode, globals_for_guard_fn, out) + guard_fn = out["___make_guard_fn"](*closure_vars.values()) + if is_epilogue: + # Epilogue guards are run after all the other guards have finished. + # If epilogue guards contain a getattr or getitem access, one of the + # other guards would fail preventing the epilogue guards to run. + self.guard_manager.root.add_epilogue_lambda_guard( + guard_fn, + verbose_code_parts, + None, + ) + else: + self.guard_manager.root.add_lambda_guard(guard_fn, verbose_code_parts, None) + + # Warning: use this with care! This lets you access what the current + # value of the value you are guarding on is. You probably don't want + # to actually durably save this value though (because it's specific + # to this frame!) Instead, you should be reading out some property + # (like its type) which is what you permanently install into the + # guard code. + def get( + self, + guard_or_source: Guard | Source, + closure_vars: dict[str, Any] | None = None, + ) -> Any: + if isinstance(guard_or_source, Source): + src = guard_or_source + else: + src = guard_or_source.originating_source + if closure_vars is None: + closure_vars = _get_closure_vars() + ret = src.get_value(self.scope, closure_vars, self.src_get_value_cache) + return ret + + # Registers the usage of the source name referenced by the + # string (or stored in the Guard) as being guarded upon. It's important + # to call this before generating some code that makes use of 'guard', + # because without this call, we won't actually bind the variable + # you reference in the actual guard closure (oops!) + def arg_ref(self, guard: str | Guard) -> str: + name: str + if isinstance(guard, str): + name = guard + else: + name = guard.name + base = strip_function_call(name) + if base not in self.argnames: + is_valid = torch._C._dynamo.is_valid_var_name(base) + if is_valid: + if is_valid == 2: + log.warning("invalid var name: %s", guard) + self.argnames.append(base) + + return name + + def _guard_on_attribute( + self, + guard: Guard, + attr_name: str, + guard_fn: Callable[[GuardBuilderBase, Guard], Any], + ) -> None: + if attr_name == "__code__": + attr_source = CodeSource(guard.originating_source) + else: + attr_source = AttrSource(guard.originating_source, attr_name) # type: ignore[assignment] + # Copy the stack info + new_guard = Guard( + attr_source, guard_fn, stack=guard.stack, user_stack=guard.user_stack + ) + new_guard.create(self) + + # Note: the order of the guards in this file matters since we sort guards on the same object by lineno + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: ( + _guard_create_fn_keyword(guard, "attr"), + hasattr(value, _guard_create_fn_keyword(guard, "attr")), + ), + eval_fn=lambda value, metadata: hasattr(value, metadata[0]) == metadata[1], + ) + def HASATTR(self, guard: Guard, attr: str | None = None) -> None: + if attr is None: + raise AssertionError("attr must not be None for HASATTR guard") + source = guard.originating_source + if isinstance(source, NNModuleSource): + source = source.base + + ref = self.arg_ref(guard) + val = hasattr(self.get(guard), attr) + code = None + if val: + code = f"hasattr({ref}, {attr!r})" + else: + code = f"not hasattr({ref}, {attr!r})" + + if code in self.already_added_code_parts: + return + + self._set_guard_export_info( + guard, [code], provided_guarded_object=self.get(guard) + ) + + base_manager = self.get_guard_manager_from_source(source) + if val: + # Just install a getattr manager. GetAttrGuardAccessor itself + # acts as hasattr guard. + attr_source = AttrSource(source, attr) + example_value = self.get(attr_source) + base_example_value = self.get(guard) + guard_manager_enum = self.get_guard_manager_type(attr_source, example_value) + + # if the base value is nn.Module, check if we can speedup the + # guard by going through __dict__ attrs. + if should_optimize_getattr_on_nn_module(base_example_value): + self.getattr_on_nn_module( + attr_source, + base_manager, + base_example_value, + example_value, + source.name, + attr_source.name, + guard_manager_enum, + ) + else: + base_manager.getattr_manager( + attr=attr, + source=guard.name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + base_manager.add_no_hasattr_guard( + attr, get_verbose_code_parts(code, guard), guard.user_stack + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _guard_create_fn_keyword(guard, "attr"), + eval_fn=lambda value, metadata: metadata not in value.__dict__, + ) + def NOT_PRESENT_IN_GENERIC_DICT( + self, guard: Guard, attr: str | None = None + ) -> None: + if attr is None: + raise AssertionError( + "attr must not be None for NOT_PRESENT_IN_GENERIC_DICT guard" + ) + ref = self.arg_ref(guard) + val = self.get(guard) + + base_manager = self.get_guard_manager(guard) + + code = f"not ___dict_contains({attr!r}, {ref}.__dict__)" + if code in self.already_added_code_parts: + return + + mod_dict_source = f"{guard.name}.__dict__" + mod_generic_dict_manager = base_manager.get_generic_dict_manager( + source=mod_dict_source, + example_value=self._get_generic_dict_manager_example_value(val.__dict__), + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ) + + mod_generic_dict_manager.add_dict_contains_guard( + False, + attr, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: type(value), + eval_fn=lambda value, metadata: type(value) is metadata, + ) + def TYPE_MATCH(self, guard: Guard) -> None: + # ___check_type_id is same as `id(type(x)) == y` + value = self.get(guard) + if ( + isinstance( # noqa: ISINSTANCE_FAKE_TENSOR + value, torch._subclasses.FakeTensor + ) + and value.pytype + ): + t = value.pytype + else: + t = type(value) + + if t.__qualname__ != t.__name__: + # Type match guards must be local scope, this is + # raised in self.serialize_guards + guard._unserializable = True + + obj_id = self.id_ref(t, f"type({guard.name})") + type_repr = _safe_type_repr(t) + code = f"___check_type_id({self.arg_ref(guard)}, {obj_id}), type={type_repr}" + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_type_match_guard( + obj_id, + get_verbose_code_parts( + code, guard, recompile_hint=f"type {t.__qualname__}" + ), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: type( + value.real_obj if isinstance(value, FakeScriptObject) else value + ), + eval_fn=lambda value, metadata: type( + value.real_obj if isinstance(value, FakeScriptObject) else value + ) + is metadata, + ) + def FAKE_SCRIPT_TYPE_MATCH(self, guard: Guard) -> None: + # Like TYPE_MATCH, but for sources that may resolve to either a + # FakeScriptObject (during outer AOTAutograd tracing) or the + # underlying real opaque object (at runtime). The C++ leaf guard + # unwraps FakeScriptObject before comparing types. + value = self.get(guard) + if isinstance(value, FakeScriptObject): + t = type(value.real_obj) + else: + t = type(value) + + if t.__qualname__ != t.__name__: + guard._unserializable = True + + obj_id = self.id_ref(t, f"type({guard.name})") + type_repr = _safe_type_repr(t) + code = f"___check_fake_script_type({self.arg_ref(guard)}, {obj_id}), type={type_repr}" + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_fake_script_type_match_guard( + FakeScriptObject, + obj_id, + get_verbose_code_parts( + code, guard, recompile_hint=f"type {t.__qualname__}" + ), + guard.user_stack, + ) + + # Dict versions change on any mutation, so a version captured during one + # trace is meaningless for a later subgraph reuse check. + @unsupported_guard_check_spec + def DICT_VERSION(self, guard: Guard) -> None: + # ___check_dict_version is same as `dict_version(x) == y` + ref = self.arg_ref(guard) + val = self.get(guard) + version = dict_version(self.get(guard)) + code = f"___dict_version({ref}) == {version}" + self._set_guard_export_info(guard, [code]) + + # TODO(anijain2305) - Delete this when DictGuardManager uses tags + # for dicts. + self.get_guard_manager(guard).add_dict_version_guard( + val, get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _guard_create_fn_keyword(guard, "key"), + eval_fn=lambda value, metadata: metadata in value, + ) + def DICT_CONTAINS(self, guard: Guard, key: str) -> None: + dict_ref = self.arg_ref(guard) + + code = f"___dict_contains({key!r}, {dict_ref})" + if code in self.already_added_code_parts: + return + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_dict_contains_guard( + True, + key, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _guard_create_fn_keyword(guard, "key"), + eval_fn=lambda value, metadata: metadata not in value, + ) + def DICT_NOT_CONTAINS(self, guard: Guard, key: str) -> None: + dict_ref = self.arg_ref(guard) + + code = f"not ___dict_contains({key!r}, {dict_ref})" + if code in self.already_added_code_parts: + return + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_dict_contains_guard( + False, + key, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _guard_create_fn_keyword(guard, "key"), + eval_fn=lambda value, metadata: metadata in value, + ) + def SET_CONTAINS(self, guard: Guard, key: object) -> None: + set_ref = self.arg_ref(guard) + item = key + + code = f"set.__contains__({set_ref}, {item!r})" + if code in self.already_added_code_parts: + return + + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_set_contains_guard( + True, + item, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _guard_create_fn_keyword(guard, "key"), + eval_fn=lambda value, metadata: metadata not in value, + ) + def SET_NOT_CONTAINS(self, guard: Guard, key: object) -> None: + set_ref = self.arg_ref(guard) + item = key + + code = f"not set.__contains__({set_ref}, {item!r})" + if code in self.already_added_code_parts: + return + + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_set_contains_guard( + False, + item, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value == metadata, + ) + def BOOL_MATCH(self, guard: Guard) -> None: + # checks val == True or val == False + ref = self.arg_ref(guard) + val = self.get(guard) + if not istype(val, bool): + raise AssertionError(f"Expected bool, got {type(val)}") + code = [f"{ref} == {val!r}"] + self._set_guard_export_info(guard, code) + + if val: + self.get_guard_manager(guard).add_true_match_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + else: + self.get_guard_manager(guard).add_false_match_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _try_is_cow_tensor(value), + eval_fn=lambda value, metadata: _cow_tensor_matches(value, metadata), + ) + def COW_TENSOR_MATCH(self, guard: Guard) -> None: + expected = _try_is_cow_tensor(self.get(guard)) + if not isinstance(expected, bool): + raise AssertionError("COW_TENSOR_MATCH requires a plain Tensor") + + def guard_fn(x: object) -> bool: + return _cow_tensor_matches(x, expected) + + code = f"___cow_tensor_matches({self.arg_ref(guard)}, {expected!r})" + self._set_guard_export_info(guard, [code]) + self.get_guard_manager(guard).add_lambda_guard( + guard_fn, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: None, + eval_fn=lambda value, metadata: value is None, + ) + def NONE_MATCH(self, guard: Guard) -> None: + # checks `val is None` + ref = self.arg_ref(guard) + val = self.get(guard) + if val is not None: + raise AssertionError(f"Expected None, got {type(val)}") + code = [f"{ref} is None"] + self._set_guard_export_info(guard, code) + + self.get_guard_manager(guard).add_none_match_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def ID_MATCH(self, guard: Guard, recompile_hint: str | None = None) -> None: + # TODO - Run a CI with the following uncommented to find the remaining places + # val = self.get(guard) + # if inspect.isclass(val): + # raise AssertionError(f"{guard.name} is a class, use CLASS_MATCH guard") + # if inspect.ismodule(val): + # raise AssertionError(f"{guard.name} is a module, use MODULE_MATCH guard") + return self.id_match_unchecked(guard, recompile_hint) + + def id_match_unchecked( + self, guard: Guard, recompile_hint: str | None = None + ) -> None: + # ___check_obj_id is same as `id(x) == y` + if isinstance(guard.originating_source, TypeSource): + # optional optimization to produce cleaner/faster guard code + return self.TYPE_MATCH( + Guard(guard.originating_source.base, GuardBuilder.TYPE_MATCH) # type: ignore[arg-type] + ) + + ref = self.arg_ref(guard) + val = self.get(guard) + id_val = self.id_ref(val, guard.name) + type_repr = _safe_type_repr(val if inspect.isclass(val) else type(val)) + code = f"___check_obj_id({ref}, {id_val}), type={type_repr}" + self._set_guard_export_info(guard, [code], provided_func_name="ID_MATCH") + self.get_guard_manager(guard).add_id_match_guard( + id_val, + get_verbose_code_parts(code, guard, recompile_hint), + guard.user_stack, + ) + + # Keep track of ID_MATCH'd objects. This will be used to modify the + # cache size logic + if isinstance(guard.originating_source, LocalSource): + # TODO(anijain2305) - This is currently restricted to nn.Module objects + # because many other ID_MATCH'd objects fail - like DeviceMesh. + # Increase the scope of ID_MATCH'd objects. + if isinstance(val, torch.nn.Module): + local_name = guard.originating_source.local_name + weak_id = self.lookup_weakrefs(val) + if weak_id is not None: + self.id_matched_objs[local_name] = weak_id + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: None, + eval_fn=lambda value, metadata: value is not None, + ) + def NOT_NONE_MATCH(self, guard: Guard, value: object | None = None) -> None: + ref = self.arg_ref(guard) + val = self.get(guard) + if not isinstance(val, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(val)}") + code = f"{ref} is not None" + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_not_none_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value.raw_repr(), + eval_fn=lambda value, metadata: value.raw_repr() == metadata, + ) + def DISPATCH_KEY_SET_MATCH(self, guard: Guard) -> None: + ref = self.arg_ref(guard) + val = self.get(guard) + if not isinstance(val, torch._C.DispatchKeySet): + raise AssertionError(f"Expected DispatchKeySet, got {type(val)}") + code_parts = f"{ref}.raw_repr() == {val!r}.raw_repr()" + + self.get_guard_manager(guard).add_dispatch_key_set_guard( + val, + get_verbose_code_parts(code_parts, guard), + guard.user_stack, + ) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def DUAL_LEVEL(self, guard: Guard) -> None: + # Invalidate dual level if current dual level is different than the one + # in the fx graph + if self.check_fn_manager.output_graph is None: + raise AssertionError("check_fn_manager.output_graph must not be None") + dual_level = self.check_fn_manager.output_graph.dual_level + code = [f"torch.autograd.forward_ad._current_level == {dual_level}"] + self._set_guard_export_info(guard, code) + self.guard_manager.root.add_dual_level_match_guard( + dual_level, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def FUNCTORCH_STACK_MATCH(self, guard: Guard) -> None: + # Invalidate functorch code if current level is different than + # the one when FX graph was generated + if self.check_fn_manager.output_graph is None: + raise AssertionError("check_fn_manager.output_graph must not be None") + cis = self.check_fn_manager.output_graph.functorch_layers + states = [ci.get_state() for ci in cis] + code = [f"torch._functorch.pyfunctorch.compare_functorch_state({states})"] + self._set_guard_export_info(guard, code) + + # TODO(anijain2305) - Consider this moving this guard to C++ + compare_fn = torch._functorch.pyfunctorch.compare_functorch_state + + def fn(x: object) -> bool: + return compare_fn(states) + + self.guard_manager.root.add_lambda_guard( + fn, get_verbose_code_parts(code, guard), guard.user_stack + ) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def AUTOGRAD_SAVED_TENSORS_HOOKS(self, guard: Guard) -> None: + get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks + are_inline_hooks = ( + torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable + ) + + def hooks_ids_fn( + hooks: tuple[Callable[[torch.Tensor], Any], Callable[[Any], torch.Tensor]], + ) -> tuple[int, ...] | None: + if not are_inline_hooks(hooks): + return None + + return tuple(map(id, hooks)) + + guard_hooks_ids = hooks_ids_fn(get_hooks()) + + code = [ + f"torch._functorch.aot_autograd.utils.top_saved_tensors_hooks ids == {guard_hooks_ids}" + ] + self._set_guard_export_info(guard, code) + + def fn(x: object) -> bool: + return guard_hooks_ids == hooks_ids_fn(get_hooks()) + + self.guard_manager.root.add_lambda_guard( + fn, get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=extract_subclass_metadata, + eval_fn=check_subclass_metadata, + ) + def TENSOR_SUBCLASS_METADATA_MATCH(self, guard: Guard) -> None: + value = self.get(guard) + + # Deepcopying SymInts result in an error from copying FakeTensors. + # Instead we just always assume the metadata is the same. + class _AnyCompare: + def __eq__(self, other: object) -> bool: + return True + + def __ne__(self, other: object) -> bool: + return False + + metadata = value.__tensor_flatten__()[1] + has_custom_guard = hasattr(value, "__metadata_guard__") + if has_custom_guard: + verify_guard_fn_signature(value) + cls = type(value) + else: + _validate_default_subclass_metadata_guard(metadata, type(value)) + + original_metadata = deepcopy( + pytree.tree_map_only(torch.SymInt, lambda _: _AnyCompare(), metadata) + ) + # Either arm runs on every guard evaluation, so they narrow the opaque + # guarded value with a suppression rather than a typing.cast, which + # would be a real call on the check path. + if has_custom_guard: + + def metadata_checker(x: object) -> bool: + return cls.__metadata_guard__( + original_metadata, + x.__tensor_flatten__()[1], # pyrefly: ignore[missing-attribute] + ) + + else: + + def metadata_checker(x: object) -> bool: + # pyrefly: ignore[missing-attribute] + return x.__tensor_flatten__()[1] == original_metadata + + global_name = f"___check_metadata_{id(metadata_checker)}_c{CompileContext.current_compile_id()}" + self.get_guard_manager(guard).add_lambda_guard( + metadata_checker, + get_verbose_code_parts(global_name, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=extract_dtensor_spec, + eval_fn=check_dtensor_spec, + ) + def DTENSOR_SPEC_MATCH(self, guard: Guard) -> None: + # Copied from DTensor __metadata_guard__ + # TODO - Consider moving this to C++ if stable + expected = extract_dtensor_spec(guard, self.get(guard)) + + def guard_fn(x: object) -> bool: + return check_dtensor_spec(x, expected) + + code = f"__dtensor_spec_{id(guard_fn)}" + self.get_guard_manager(guard).add_lambda_guard( + guard_fn, get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=extract_opaque_obj, + eval_fn=check_opaque_obj, + ) + def OPAQUE_OBJ_GUARD_FN_MATCH(self, guard: Guard) -> None: + """Guard on the values returned by the opaque object's guard_fn.""" + + value = self.get(guard) + original_values = extract_opaque_obj(guard, value) + + if original_values is None: + return + + def opaque_guard_checker(x: object) -> bool: + return check_opaque_obj(x, original_values) + + global_name = f"___check_opaque_guard_fn_{id(opaque_guard_checker)}_c{CompileContext.current_compile_id()}" + self.get_guard_manager(guard).add_lambda_guard( + opaque_guard_checker, + get_verbose_code_parts(global_name, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value == metadata, + ) + def EQUALS_MATCH(self, guard: Guard, recompile_hint: str | None = None) -> None: + ref = self.arg_ref(guard) + val = self.get(guard) + if np: + np_types: tuple[type[Any], ...] = ( + np.int8, + np.int16, + np.int32, + np.int64, + np.uint8, + np.uint16, + np.uint32, + np.uint64, + np.float16, + np.float32, + np.float64, + ) + else: + np_types = () + + ok_mutable_types = (list, set) + + ok_types = tuple( + common_constant_types + | { + type, + tuple, + frozenset, + slice, + range, + dict_keys, + torch.Size, + torch.Stream, + torch.cuda.streams.Stream, + *np_types, + *ok_mutable_types, + } + ) + + if torch.distributed.is_available(): + from torch.distributed.device_mesh import _MeshLayout, DeviceMesh + from torch.distributed.tensor.placement_types import ( + _StridedShard, + Partial, + Replicate, + Shard, + ) + + ok_types = ok_types + ( + Shard, + Replicate, + Partial, + DeviceMesh, + _StridedShard, + _MeshLayout, + ) + + from torch.export.dynamic_shapes import _IntWrapper + + ok_types = ok_types + (_IntWrapper,) + + import torch.utils._pytree as pytree + + if not ( + isinstance(val, ok_types) + or pytree.is_constant_class(type(val)) + or is_opaque_constant_type(type(val)) + ): + raise AssertionError(f"Unexpected type {type(val)}") + + # Special case for nan because float("nan") == float("nan") evaluates to False + if istype(val, float) and math.isnan(val): + code = [f"(type({ref}) is float and __math_isnan({ref}))"] + self._set_guard_export_info(guard, code) + + self.get_guard_manager(guard).add_float_is_nan_guard( + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + return + + # Python math library doesn't support complex nan, so we need to use numpy + # pyrefly: ignore [missing-attribute] + if istype(val, complex) and np.isnan(val): + code = [f"(type({ref}) is complex and __numpy_isnan({ref}))"] + self._set_guard_export_info(guard, code) + + self.get_guard_manager(guard).add_complex_is_nan_guard( + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + return + + # Construct a debug string to put into the c++ equals match guard. + code = [f"{ref} == {val!r}"] + if istype(val, ok_mutable_types): + # C++ guards perform a pointer equality check to speedup guards, but the assumption is that the object + # is immutable. For a few corner cases like sets and lists, we make a deepcopy to purposefully fail the + # pointer equality check. + val = deepcopy(val) + + verbose_code_parts = get_verbose_code_parts(code, guard) + if recompile_hint: + verbose_code_parts = [ + f"{part} (HINT: {recompile_hint})" for part in verbose_code_parts + ] + + self.get_guard_manager(guard).add_equals_match_guard( + val, verbose_code_parts, guard.user_stack + ) + self._set_guard_export_info(guard, code) + return + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value == metadata, + ) + def CONSTANT_MATCH(self, guard: Guard) -> None: + val = self.get(guard) + if istype(val, bool): + self.BOOL_MATCH(guard) + elif val is None: + self.NONE_MATCH(guard) + elif istype(val, types.CodeType): + self.ID_MATCH(guard) + else: + self.EQUALS_MATCH(guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _constant_subclass_base_value(value), + eval_fn=lambda value, metadata: _constant_subclass_base_value(value) + == metadata, + ) + def CONSTANT_SUBCLASS_MATCH(self, guard: Guard) -> None: + """Guard for subclasses of constant types (int, float, str, etc.). + + Extracts the base value using the base type's converter (e.g., + int.__int__) to avoid calling user-overridden __eq__. + """ + from .variables.user_defined import _CONSTANT_BASE_TYPES + + val = self.get(guard) + ref = self.arg_ref(guard) + + # Find the constant base type + base_type = None + for t in _CONSTANT_BASE_TYPES: + if isinstance(val, t): + base_type = t + break + if base_type is None: + raise AssertionError(f"No constant base type found for {type(val)}") + + base_value = base_type(val) + code = [f"{base_type.__name__}({ref}) == {base_value!r}"] + + def check_fn(x: object) -> bool: + # Mirrors _constant_subclass_base_value: base_type is a union of + # int/float/str, none of which typecheck against an opaque arg, + # but x is an instance of base_type by construction. + return base_type(x) == base_value # pyrefly: ignore[bad-argument-type] + + self.get_guard_manager(guard).add_lambda_guard( + check_fn, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def NN_MODULE(self, guard: Guard) -> None: + # don't support this in serialization because it uses unsupported ID_MATCH + self.ID_MATCH(guard, "[inline-inbuilt-nn-modules-candidate]") + val = self.get(guard) + if hasattr(val, "training"): + if not istype(val.training, bool): + raise AssertionError( + f"Expected val.training to be bool, got {type(val.training)}" + ) + if not self.guard_nn_modules: + # If guard_nn_modules is true, we will guard on the right set of guards + self._guard_on_attribute(guard, "training", GuardBuilder.CONSTANT_MATCH) # type: ignore[arg-type] + else: + exc.unimplemented( + gb_type="Attempted to guard on uninitialized nn.Module", + context="", + explanation="Attempted to setup an NN_MODULE guard on uninitialized " + f"nn.Module subclass `{type(val)}`.", + hints=[ + "Ensure the `nn.Module` subclass instance has called `super().__init__()`.", + ], + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def FUNCTION_MATCH(self, guard: Guard) -> None: + """things like torch.add and user defined functions""" + # don't support this in serialization because it uses unsupported ID_MATCH + return self.ID_MATCH(guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def CLASS_MATCH(self, guard: Guard) -> None: + """Equals ID_MATCH on classes - better readability than directly calling ID_MATCH""" + val = self.get(guard) + if not inspect.isclass(val): + raise AssertionError( + f"{guard.name} is not a class, but CLASS_MATCH is used" + ) + self.id_match_unchecked(guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def MODULE_MATCH(self, guard: Guard) -> None: + """Equals ID_MATCH on modules - better readability than directly calling ID_MATCH""" + val = self.get(guard) + if not inspect.ismodule(val): + raise AssertionError( + f"{guard.name} is not a module, but MODULE_MATCH is used" + ) + self.id_match_unchecked(guard) + + @register_guard_check_spec( + get_metadata_fn=extract_closure, + eval_fn=check_closure, + ) + def CLOSURE_MATCH(self, guard: Guard) -> None: + """matches a closure by __code__ id.""" + # don't support this in serialization because it uses unsupported FUNCTION_MATCH + val = self.get(guard) + # Strictly only want user-defined functions + if type(val) is types.FunctionType and hasattr(val, "__code__"): + # No explicit HASATTR guard needed for __code__ — the getattr + # accessor installed by CONSTANT_MATCH implicitly guards hasattr. + self._guard_on_attribute(guard, "__code__", GuardBuilder.CONSTANT_MATCH) # type: ignore[arg-type] + else: + self.FUNCTION_MATCH(guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def BUILTIN_MATCH(self, guard: Guard) -> None: + if self.save_guards: + # Record which builtin variables are used for pruning later. + if isinstance(guard.originating_source, DictGetItemSource): + self.check_fn_manager.used_builtin_vars.add( + guard.originating_source.index + ) + return self.id_match_unchecked(guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _sequence_length(value), + eval_fn=lambda value, metadata: _sequence_length(value) == metadata, + ) + def SEQUENCE_LENGTH(self, guard: Guard) -> None: + # This guard is used to check length of PySequence objects like list, + # tuple, collections.deque etc + ref = self.arg_ref(guard) + value = self.get(guard) + length = _sequence_length(value) + + if not isinstance(value, dict): + # C++ DICT_LENGTH checks for type + self.TYPE_MATCH(guard) + + code = [] + if isinstance(value, set): + code.append(f"set.__len__({ref}) == {length}") + elif isinstance(value, frozenset): + code.append(f"frozenset.__len__({ref}) == {length}") + elif length == 0: + code.append(f"not {ref}") + else: + code.append(f"len({ref}) == {length}") + + self._set_guard_export_info(guard, code) + if isinstance(value, dict): + self.get_guard_manager(guard).add_dict_length_check_guard( + length, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + else: + self.get_guard_manager(guard).add_length_check_guard( + length, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: tuple_iterator_len(value), + eval_fn=lambda value, metadata: tuple_iterator_len(value) == metadata, + ) + def TUPLE_ITERATOR_LEN(self, guard: Guard) -> None: + ref = self.arg_ref(guard) + value = self.get(guard) + t = type(value) + + code = [] + code.append(f"___tuple_iterator_len({ref}) == {tuple_iterator_len(value)}") + self._set_guard_export_info(guard, code) + + t = type(value) + obj_id = self.id_ref(t, f"type({guard.name})") + + self.get_guard_manager(guard).add_tuple_iterator_length_guard( + tuple_iterator_len(value), + obj_id, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: normalize_range_iter(value), + eval_fn=lambda value, metadata: normalize_range_iter(value) == metadata, + ) + def RANGE_ITERATOR_MATCH(self, guard: Guard) -> None: + ref = self.arg_ref(guard) + value = self.get(guard) + t = type(value) + + code = [] + normalized_range_iter = normalize_range_iter(value) + code.append(f"___normalize_range_iter({ref}) == {normalized_range_iter}") + self._set_guard_export_info(guard, code) + + t = type(value) + obj_id = self.id_ref(t, f"type({guard.name})") + + start, stop, step = normalized_range_iter + self.get_guard_manager(guard).add_range_iterator_match_guard( + start, + stop, + step, + obj_id, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: (type(value), normalize_count_iter(value)), + eval_fn=lambda value, metadata: ( + type(value) is metadata[0] and normalize_count_iter(value) == metadata[1] + ), + ) + def COUNT_ITERATOR_MATCH(self, guard: Guard) -> None: + ref = self.arg_ref(guard) + value = self.get(guard) + count_type = type(value) + normalized_count_iter = normalize_count_iter(value) + + def guard_fn(x: object) -> bool: + return ( + type(x) is count_type + and normalize_count_iter(x) == normalized_count_iter + ) + + code = [f"___normalize_count_iter({ref}) == {normalized_count_iter}"] + self._set_guard_export_info(guard, code) + self.get_guard_manager(guard).add_lambda_guard( + guard_fn, get_verbose_code_parts(code, guard), guard.user_stack + ) + + # Multi-source guard (two inputs aliasing) — not expressible as a + # single source → value check. + # TODO(voz): Deduplicate w/ AOTAutograd dupe input guards + @skip_guard_check_spec + def DUPLICATE_INPUT(self, guard: Guard, source_b: Source) -> None: + if is_from_skip_guard_source( + guard.originating_source + ) or is_from_skip_guard_source(source_b): + return + + if self.save_guards: + if name := get_local_source_name(source_b): + self.check_fn_manager.additional_used_local_vars.add(name) + if name := get_global_source_name(source_b): + self.check_fn_manager.additional_used_global_vars.add(name) + + ref_a = self.arg_ref(guard) + ref_b = self.arg_ref(source_b.name) + + if is_from_optimizer_source( + guard.originating_source + ) or is_from_optimizer_source(source_b): + return + + # Check that the guard has not been inserted already + key = (ref_a, ref_b) + if key in self._cached_duplicate_input_guards: + return + + self._cached_duplicate_input_guards.add((ref_a, ref_b)) + self._cached_duplicate_input_guards.add((ref_b, ref_a)) + + code = [f"{ref_b} is {ref_a}"] + self._set_guard_export_info(guard, code) + + if config.use_lamba_guard_for_object_aliasing: + # Save the code part so that we can install a lambda guard at the + # end. Read the Note - On Lambda guarding of object aliasing - to + # get more information. + code_part = code[0] + verbose_code_part = get_verbose_code_parts(code_part, guard)[0] + self.object_aliasing_guard_codes.append((code_part, verbose_code_part)) + else: + install_object_aliasing_guard( + self.get_guard_manager(guard), + self.get_guard_manager_from_source(source_b), + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: None, + eval_fn=lambda value, metadata: value is not None, + ) + def WEAKREF_ALIVE(self, guard: Guard) -> None: + code = [f"{self.arg_ref(guard)} is not None"] + + self._set_guard_export_info(guard, code) + self.get_guard_manager(guard).add_not_none_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: list(value.keys()), + eval_fn=lambda value, metadata: list(value.keys()) == metadata, + ) + def MAPPING_KEYS_CHECK(self, guard: Guard) -> None: + """Guard on the key order of types.MappingProxyType object""" + ref = self.arg_ref(guard) + value = self.get(guard) + + code = [] + code.append(f"list({ref}.keys()) == {list(value.keys())}") + self._set_guard_export_info(guard, code) + self.get_guard_manager(guard).add_mapping_keys_guard( + value, code, guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: list(dict.keys(value)), + eval_fn=lambda value, metadata: list(dict.keys(value)) == metadata, + ) + def DICT_KEYS_MATCH(self, guard: Guard) -> None: + """Insert guard to check that the keys of a dict are same""" + ref = self.arg_ref(guard) + value = self.get(guard) + + # SUPPORTED_NODES normally uses DICT_VERSION (PEP 509) as an O(1) fast + # path. That guard cannot be serialized, so when saving we fall through + # to keys-match and stick the choice on the Guard. Load rebuilds with + # save_guards=False but sees the pickled flag, so it keeps keys-match + # instead of re-promoting to DICT_VERSION. + if value is torch.utils._pytree.SUPPORTED_NODES: + if self.save_guards: + guard._force_dict_keys_match = True + if not guard._force_dict_keys_match: + self.DICT_VERSION(guard) + return + + self.SEQUENCE_LENGTH(guard) + + code = [] + # Ensure that we call dict.keys and not value.keys (which can call + # overridden keys method). In the C++ guards, we relied on PyDict_Next + # to traverse the dictionary, which uses the internal data structure and + # does not call the overridden keys method. + code.append(f"list(dict.keys({ref})) == {list(builtin_dict_keys(value))!r}") + self._set_guard_export_info(guard, code) + + if self.requires_key_order_guarding(guard.originating_source): + self.guard_on_dict_keys_and_order(value, guard) + else: + self.guard_on_dict_keys_and_ignore_order(value, guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: None, + eval_fn=lambda value, metadata: len(value) == 0, + ) + def EMPTY_NN_MODULE_HOOKS_DICT(self, guard: Guard) -> None: + """Special guard to skip guards on empty hooks. This is controlled by skip_nnmodule_hook_guards""" + if config.skip_nnmodule_hook_guards: + # This is unsafe if you add/remove a hook on nn module variable + return + self.SEQUENCE_LENGTH(guard) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def GRAD_MODE(self, guard: Guard) -> None: + pass # we always guard on this via GlobalStateGuard() + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def DETERMINISTIC_ALGORITHMS(self, guard: Guard) -> None: + pass # we always guard on this via GlobalStateGuard() + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def FSDP_TRAINING_STATE(self, guard: Guard) -> None: + pass # we always guard on this via GlobalStateGuard() + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def GLOBAL_STATE(self, guard: Guard) -> None: + output_graph = self.check_fn_manager.output_graph + if output_graph is None: + raise AssertionError("output_graph must not be None") + global_state = output_graph.global_state_guard + self.check_fn_manager.global_state = global_state + + code = [ + f"___check_global_state() against {self.check_fn_manager.global_state.__getstate__()}" + ] + + self.guard_manager.root.add_global_state_guard( + global_state, code, guard.user_stack + ) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def TORCH_FUNCTION_STATE(self, guard: Guard) -> None: + if self.check_fn_manager.torch_function_mode_stack is None: + raise AssertionError("torch_function_mode_stack must not be None") + self.check_fn_manager.torch_function_mode_stack_check_fn = ( + make_torch_function_mode_stack_guard( + self.check_fn_manager.torch_function_mode_stack + ) + ) + self.guard_manager.root.add_torch_function_mode_stack_guard( + self.check_fn_manager.torch_function_mode_stack, + ["___check_torch_function_mode_stack()"], + guard.user_stack, + ) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def DEFAULT_DEVICE(self, guard: Guard) -> None: + """Guard on CURRENT_DEVICE per torch.utils._device""" + if guard.source is not GuardSource.GLOBAL: + raise AssertionError(f"Expected GuardSource.GLOBAL, got {guard.source}") + + if self.check_fn_manager.output_graph is None: + raise AssertionError("check_fn_manager.output_graph must not be None") + code = [ + f"utils_device.CURRENT_DEVICE == {self.check_fn_manager.output_graph.current_device!r}" + ] + self._set_guard_export_info(guard, code) + + self.get_guard_manager(guard).add_default_device_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + + @skip_guard_check_spec + def SHAPE_ENV(self, guard: Guard) -> None: + from torch._dynamo.output_graph import OutputGraphCommon + + if guard.name != "": + raise AssertionError(f"Expected empty guard name, got {guard.name!r}") + output_graph = self.check_fn_manager.output_graph + if output_graph is None: + raise AssertionError("output_graph must not be None") + if self.check_fn_manager.shape_code_parts is not None: + shape_code_parts = self.check_fn_manager.shape_code_parts + python_code_parts = shape_code_parts.python_code_parts + verbose_code_parts = shape_code_parts.verbose_code_parts + if shape_code_parts.cpp_code_parts is not None: + cpp_code_parts = shape_code_parts.cpp_code_parts + python_fallback = shape_code_parts.python_fallback + else: + # Let's handle ShapeEnv guards. To do this, we will resolve + # shape variables to sources from tracked_fakes. This must happen after + # tensor checks. + # NB: self.output_graph can be None in the debug_nops tests + if not isinstance(output_graph, OutputGraphCommon): + raise AssertionError( + f"Expected OutputGraphCommon, got {type(output_graph)}" + ) + if output_graph.shape_env is None: + raise AssertionError("output_graph.shape_env must not be None") + fs = output_graph.shape_env.tracked_fakes or [] + input_contexts = [a.symbolic_context for a in fs] + + def get_sources(t_id: int, dim: int) -> list[Source]: + # Looks up base sources mapped to a tensor id and uses them to create + # sources for the corresponding tensor dimension. + return [ + TensorPropertySource(source, TensorProperty.SIZE, dim) + # pyrefly: ignore [missing-attribute] + for source in output_graph.tracked_fakes_id_to_source[t_id] + ] + + if output_graph.export_constraints: + names: dict[str, tuple[int, int]] = {} + source_pairs: list[tuple[Source, Source]] = [] + derived_equalities: list[ # type: ignore[type-arg] + # pyrefly: ignore [implicit-any] + tuple[Source, Source | Symbol, Callable] + ] = [] + phantom_symbols: dict[str, Symbol] = {} + relaxed_sources: set[Source] = set() + for constraint in output_graph.export_constraints: # type: ignore[attr-defined] + if constraint.t_id in output_graph.tracked_fakes_id_to_source: + torch.export.dynamic_shapes._process_equalities( + constraint, + get_sources, + output_graph.shape_env, + names, + source_pairs, + derived_equalities, + phantom_symbols, + relaxed_sources, + ) + else: + log.warning("Untracked tensor used in export constraints") + equalities_inputs = EqualityConstraint( + source_pairs=source_pairs, + derived_equalities=derived_equalities, + phantom_symbols=list(phantom_symbols.values()), + relaxed_sources=relaxed_sources, + warn_only=False, + ) + else: + equalities_inputs = None + + def _get_code_parts(langs: tuple[str, ...]) -> list[_ShapeGuardsHelper]: + # pyrefly: ignore [missing-attribute] + return output_graph.shape_env.produce_guards_verbose( + [a.fake for a in fs], # type: ignore[misc] + [a.source for a in fs], + input_contexts=input_contexts, # type: ignore[arg-type] + equalities_inputs=equalities_inputs, + source_ref=self.source_ref, + # Export keeps static. + # pyrefly: ignore [missing-attribute] + ignore_static=(not output_graph.export), + langs=langs, + ) + + if config.enable_cpp_symbolic_shape_guards: + try: + # For exporting we need the python code parts + python_code_parts, verbose_code_parts, cpp_code_parts = ( + _get_code_parts(("python", "verbose_python", "cpp")) # type: ignore[assignment] + ) + python_fallback = False + except OverflowError: + # Cannot use int64_t + python_fallback = True + python_code_parts, verbose_code_parts = _get_code_parts( + ("python", "verbose_python") + ) + else: + python_fallback = True + python_code_parts, verbose_code_parts = _get_code_parts( + ("python", "verbose_python") + ) + + # When exporting, we may work with the shape constraints some more in + # postprocessing, so don't freeze yet + if not output_graph.export: + output_graph.shape_env.freeze() + + if self.save_guards: + # For SHAPE_ENV we want to skip serializing the entire ShapeEnv so instead + # we directly serialize the generated code here. + maybe_cpp_code_parts = locals().get("cpp_code_parts") + if maybe_cpp_code_parts is not None and not isinstance( + maybe_cpp_code_parts, _CppShapeGuardsHelper + ): + raise AssertionError( + f"Expected None or _CppShapeGuardsHelper, got {type(maybe_cpp_code_parts)}" + ) + maybe_shape_env_sources = ( + [] + if maybe_cpp_code_parts is None + else list(maybe_cpp_code_parts.source_to_symbol.keys()) + ) + self.check_fn_manager.shape_code_parts = ShapeCodeParts( + python_code_parts=python_code_parts, + verbose_code_parts=verbose_code_parts, + cpp_code_parts=maybe_cpp_code_parts, + python_fallback=python_fallback, + shape_env_sources=maybe_shape_env_sources, + ) + + for code in python_code_parts.exprs: + self._set_guard_export_info(guard, [code]) + + # Make ShapeEnv guards available for testing. + if compile_context := CompileContext.try_get(): + compile_context.shape_env_guards.extend(verbose_code_parts.exprs) + + int_source_to_symbol = [] + float_source_to_symbol = [] + + if not python_fallback: + if not cpp_code_parts: # type: ignore[possibly-undefined] + raise AssertionError( + "cpp_code_parts must be set when not using python_fallback" + ) + code_parts, source_to_symbol = ( + # pyrefly: ignore [unbound-name] + cpp_code_parts.exprs, + # pyrefly: ignore [unbound-name, missing-attribute] + cpp_code_parts.source_to_symbol, + ) + + if not code_parts: + return + + for source, symbol in source_to_symbol.items(): + if isinstance(source, ConstantSource): + python_fallback = True + else: + example_value = self.get( + source, + closure_vars={**SYMPY_INTERP, **_get_closure_vars()}, + ) + if isinstance(example_value, int): + int_source_to_symbol.append((source, symbol)) + elif isinstance(example_value, float): + float_source_to_symbol.append((source, symbol)) + else: + # SymInts/SymFloats go through python guard as we only support + # int64_t/double in C++ guards for now. + python_fallback = True + + if not python_fallback: + import ctypes + + from torch._inductor.codecache import CppCodeCache + + if not cpp_code_parts: # type: ignore[possibly-undefined] + raise AssertionError( + "cpp_code_parts must be set when not using python_fallback" + ) + code_parts, source_to_symbol = ( + # pyrefly: ignore [unbound-name] + cpp_code_parts.exprs, + # pyrefly: ignore [unbound-name, missing-attribute] + cpp_code_parts.source_to_symbol, + ) + + source_to_symbol = dict(int_source_to_symbol + float_source_to_symbol) + try: + guard_managers = [ + self.get_guard_manager_from_source(IndexedSource(source, i)) + for i, source in enumerate(source_to_symbol) + ] + + int_symbols_str = ", ".join( + f"{symbol} = int_values[{i}]" + for i, (_, symbol) in enumerate(int_source_to_symbol) + ) + float_symbols_str = ", ".join( + f"{symbol} = float_values[{i}]" + for i, (_, symbol) in enumerate(float_source_to_symbol) + ) + + if int_symbols_str: + int_symbols_str = f"int64_t {int_symbols_str};" + if float_symbols_str: + float_symbols_str = f"double {float_symbols_str};" + + func_str = textwrap.dedent( + f""" + #include + #include + #include + #include + + #if defined(_MSC_VER) + # define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport) + #else + # define EXTERN_DLL_EXPORT extern "C" + #endif + + EXTERN_DLL_EXPORT int8_t guard(int64_t *int_values, double *float_values) {{ + {int_symbols_str} + {float_symbols_str} + return ({") && (".join(code_parts)}); + }} + """ + ) + guards_log.debug( + "C++ shape guard function: %s %s", + func_str, + verbose_code_parts.exprs, + ) + clib = CppCodeCache.load(func_str) + cguard = ctypes.cast(clib.guard, ctypes.c_void_p).value + if not cguard: + raise AssertionError("Failed to load C++ shape guard function") + except torch._inductor.exc.InvalidCxxCompiler: + # No valid C++ compiler to compile the shape guard + pass + else: + install_symbolic_shape_guard( + guard_managers, + len(int_source_to_symbol), + len(float_source_to_symbol), + cguard, + clib, + verbose_code_parts.exprs, + guard.user_stack, + ) + return + + # Install all the symbolic guards in one python lambda guard. These are run + # at the very end of the RootGuardManager via epilogue guards. + # TODO(anijain2305,williamwen42) - Consider moving this to C++. + if python_code_parts.exprs: + self.add_python_lambda_leaf_guard_to_root( + python_code_parts.exprs, + verbose_code_parts.exprs, + closure_vars={**SYMPY_INTERP, **_get_closure_vars()}, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: extract_tensor_metadata(value), + eval_fn=lambda value, metadata: ( + isinstance(value, torch.Tensor) + and extract_tensor_metadata(value) == metadata + ), + ) + def TENSOR_MATCH(self, guard: Guard, value: Any | None = None) -> None: + if config._unsafe_skip_fsdp_module_guards and guard.is_fsdp_module(): + return + # For tensors that are part of the Dynamo extracted Fx graph module, an + # ID_MATCH suffices. + if match_on_id_for_tensor(guard): + self.ID_MATCH(guard) + else: + if isinstance(value, TensorWeakRef): + value = value() + + value = value if value is not None else self.get(guard) + + pytype = type(value) + dispatch_keys = torch._C._dispatch_keys(value) + if isinstance( # noqa: ISINSTANCE_FAKE_TENSOR + value, torch._subclasses.FakeTensor + ): + if value.pytype is not None: + pytype = value.pytype + if value.dispatch_keys is not None: + dispatch_keys = value.dispatch_keys + + if not isinstance(value, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(value)}") + + if config.log_compilation_metrics and isinstance(value, torch.nn.Parameter): + metrics_context = get_metrics_context() + if metrics_context.in_progress(): + metrics_context.increment("param_numel", value.numel()) + metrics_context.increment("param_bytes", value.nbytes) + metrics_context.increment("param_count", 1) + + tensor_name = self.arg_ref(guard) + # [Note - On Export Tensor Guards] + # + # In eager mode, tensor guards are evaluated through C++, in guards.cpp + # see [Note - On Eager Tensor Guards] for more info. + # + # In export mode, we instead maintain parallel logic between C++ and python + # here, with an exception of checking the dispatch key - with the idea that a dispatch key + # is an entirely runtime notion that would make no sense to keep in an exported graph. + # + # Now, this idea is okay, but to paraphrase @ezyang, this mental model is sufficient for now, although + # not entirely true. + # For example, suppose one of the input tensors had the negative dispatch key. + # You should end up with a graph that is specialized for tensors that have a negative dispatch key. + # If you allow a Tensor that does NOT have this bit set, you will accidentally run it "as if" it were negated. + # Now, negative key only shows up for complex numbers, and most likely, the exported to target doesn't + # support this feature at all, but the point stands that :some: tensor state only shows up on dispatch key. + # TODO(voz): Either populate a dispatch_key check into the guards, or error on users passing in an unsupported + # subset of keys during export. + # + # The list of tensor fields and calls we care about can be found in `terms` below. + # TODO(voz): We are missing storage offset in all our tensor guards? + code: list[str] = [] + if self.check_fn_manager.output_graph is None: + raise AssertionError("check_fn_manager.output_graph must not be None") + if self.check_fn_manager.output_graph.export: + self.TYPE_MATCH(guard) + terms = [ + "dtype", + "device", + "requires_grad", + "ndimension", + ] + + for term in terms: + term_src = AttrSource(guard.originating_source, term) + if term == "ndimension": + term = "ndimension()" + term_src = CallFunctionNoArgsSource(term_src) + real_value = self.get(term_src) + if istype(real_value, (torch.device, torch.dtype)): + # copy pasted from EQUALS_MATCH + code.append(f"str({tensor_name}.{term}) == {str(real_value)!r}") + else: + code.append(f"{tensor_name}.{term} == {real_value}") + else: + guard_manager = self.get_guard_manager(guard) + + # skip_no_tensor_aliasing_guards_on_parameters bring + # unsoundness. If you compile a function with two different + # parameters, but later on you pass on same tensor as two + # different outputs (aliasing), Dynamo will not detect this. + # But we deliberately take this soundness hit because this + # usecase is quite rare and there is substantial reduction in + # guard overhead. + # For numpy tensors, since those are ephemeral, we don't have to + # insert aliasing guards on them + if not ( + config.skip_no_tensor_aliasing_guards_on_parameters + and ( + istype(value, torch.nn.Parameter) + or is_from_unspecialized_builtin_nn_module_source( + guard.originating_source + ) + ) + ) and not isinstance(guard.originating_source, NumpyTensorSource): + # Keep track of all the tensor guard managers to insert + # NoAliasing check at the end. + self.no_tensor_aliasing_names.append(tensor_name) + self.no_tensor_aliasing_guard_managers.append(guard_manager) + + output_graph = self.check_fn_manager.output_graph + metadata = output_graph.input_source_to_sizes_strides[ + guard.originating_source + ] + size = convert_to_concrete_values(metadata["size"]) + stride = convert_to_concrete_values(metadata["stride"]) + + verbose_code_parts = get_verbose_code_parts( + get_tensor_guard_code_part( + value, + tensor_name, + size, + stride, + pytype, + dispatch_keys, + ), + guard, + ) + user_stack = guard.user_stack + guard_manager.add_tensor_match_guard( + value, + size, # type: ignore[arg-type] + stride, # type: ignore[arg-type] + tensor_name, + verbose_code_parts, + user_stack, + pytype, + dispatch_keys, + ) + + # We consider TENSOR_MATCH guard to be important enough to be + # included in diff guard manager by default. + if not isinstance(value, torch.nn.Parameter): + self.guard_manager.diff_guard_sources.add(guard.name) + + if guard.source is None: + raise AssertionError("guard.source must not be None") + + # [Note: Dimension Marking Guards] + # Guards for user explicit dynamism (mark_dynamic, mark_unbacked, mark_static..). + # + # Marking APIs express additive constraints: mark_dynamic(x, [0]) means + # "ensure dim 0 is dynamic" — it says nothing about other dims. If you + # want a dim to NOT be dynamic, explicitly mark it static (or unbacked). + # + # Guard semantics (subset matching): + # - Compiled WITH attribute, runtime HAS attribute → runtime markings + # must be a SUBSET of compiled markings. This means the compiled graph + # can satisfy the requested marking. + # - Compiled WITH attribute, runtime NO attribute → pass (unspecified = don't care) + # - Compiled WITHOUT attribute, runtime HAS attribute → recompile (new marking) + # + # Passing an empty list [] to any marking API is a no-op (same as not calling + # the function at all). Calls are additive. + # + # Examples: + # 1. Compile with mark_dynamic(x, [0,1]), call with mark_dynamic(x, [0]) → no recompile (subset) + # 2. Compile with mark_dynamic(x, [0]), call with mark_dynamic(x, [0,1]) → recompile (not a subset) + # 3. Compile with mark_dynamic(x, [0]), call with plain tensor → no recompile (unspecified = don't care) + # 4. Compile with plain tensor, call with mark_dynamic(x, [0]) → recompile (new marking added) + # + # _dynamo_weak_dynamic_indices vs _dynamo_propagated_dynamic_indices: + # _dynamo_weak_dynamic_indices is the user-facing attribute, set via + # maybe_mark_dynamic(), and guarded on like the other dimension marking + # attributes above. + # _dynamo_propagated_dynamic_indices is a compiler-internal attribute set by + # AOTAutograd's mark_dynamo_propagated_dynamic_indices() to propagate dynamism across + # graph breaks. It is NOT guarded on. When AOTAutograd discovers that an + # output dimension is symbolic, it stamps this attribute on the output tensor + # so that Dynamo treats those dims as weakly dynamic when the tensor appears + # as input to a subsequent graph. Using a separate unguarded attribute avoids + # spurious guard failures when the compiler mutates an input tensor's + # attributes through an input-aliased output. + # + # Collect dimension marking guard info for a single C++ guard. + dim_marking_attrs = ( + "_dynamo_dynamic_indices", + "_dynamo_weak_dynamic_indices", + "_dynamo_unbacked_indices", + "_dynamo_strict_unbacked_indices", + "_dynamo_static_indices", + ) + + expected_attrs: dict[str, set[int]] = {} + absent_attrs: list[str] = [] + for attr_name in dim_marking_attrs: + if hasattr(value, attr_name): + expected_attrs[attr_name] = getattr(value, attr_name) + code_part = f"((getattr({tensor_name}, '{attr_name}', set()).issubset({getattr(value, attr_name)!r})) if hasattr({tensor_name}, '{attr_name}') else True)" + code.append(code_part) + else: + absent_attrs.append(attr_name) + code_part = f"hasattr({tensor_name}, '{attr_name}') == False" + code.append(code_part) + + # Dependent attributes: checked only when _dynamo_unbacked_indices is present. + dependent_attrs: dict[str, tuple[dict[int, Any] | None, str]] = {} + dep_attr_names = ("_dynamo_shape_ids", "_dynamo_unbacked_bounds") + gate_attr = "_dynamo_unbacked_indices" + if hasattr(value, gate_attr): + for attr_name in dep_attr_names: + attr_value = getattr(value, attr_name, None) + dependent_attrs[attr_name] = (attr_value, gate_attr) + code_part = f"((getattr({tensor_name}, '{attr_name}', None) == {attr_value!r}) if hasattr({tensor_name}, '{gate_attr}') else True)" + code.append(code_part) + + # Install a single C++ guard for all dimension marking attributes. + if expected_attrs or absent_attrs or dependent_attrs: + self.get_guard_manager(guard).add_dimension_marking_guard( + expected_attrs, + absent_attrs, + dependent_attrs, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + if len(code) > 0: + self._set_guard_export_info(guard, code) + + # A util that in the case of export, adds data onto guards + def _set_guard_export_info( + self, + guard: Guard, + code_list: list[str], + provided_guarded_object: object | None = None, + provided_func_name: str | None = None, + ) -> None: + # WARNING: It is important that cur_frame/caller do NOT stay in + # the current frame, because they will keep things live longer + # than they should. See TestMisc.test_release_module_memory + cur_frame = currentframe() + if cur_frame is None: + raise AssertionError("currentframe() returned None") + caller = cur_frame.f_back + del cur_frame + if caller is None: + raise AssertionError("caller frame must not be None") + func_name = provided_func_name or caller.f_code.co_name + del caller + # We use func_name for export, so might as well get a nice defensive check out of it + if func_name not in self.__class__.__dict__: + raise AssertionError( + f"_produce_guard_code must be called from inside GuardedCode. Called from {func_name}" + ) + + # Not all guards have names, some can be installed globally (see asserts on HAS_GRAD) + if provided_guarded_object is None: + name = guard.name + guarded_object = None if not name else self.get(guard) + else: + guarded_object = provided_guarded_object + + guarded_object_type = ( + weakref.ref(type(guarded_object)) if guarded_object is not None else None + ) + obj_ref = None + # Not necessary to have weakref for Enum type, but there is a bug that + # makes hasattr(guarded_object.__class__, "__weakref__") return True. + supports_weakref = ( + getattr(guarded_object.__class__, "__weakrefoffset__", 0) != 0 + ) + # See D64140537 for why we are checking for tuple. + if supports_weakref and not isinstance( + guarded_object, (enum.Enum, tuple, weakref.ProxyTypes) + ): + obj_ref = weakref.ref(guarded_object) + + guard.set_export_info( + func_name, + guarded_object_type, + code_list, + obj_ref, + ) + + +# Common Sub-Expression Elimination for Python expressions. +# +# There are 2 steps to this pass: +# 1. Count the frequency of each sub-expression (i.e. inner +# node in the AST tree) +# +# 2. Replace those that occur more than once by a fresh variable 'v'. +# 'v' will be defined in the 'preface' list (output argument to +# 'NodeTransformer') +# +# NB: the use of 'ast.unparse' while visiting the nodes makes this pass +# quadratic on the depth of the tree. +# +# NB: this pass creates a new variable for each AST node that is repeated +# more than 'USE_THRESHOLD'. e.g. if 'a.b.c.d' is used 10 times, 'a.b.c' +# and 'a.b' are also used 10 times. So, there will be a new variable for +# each of them. +class PyExprCSEPass: + # Maximum number of times a given expression can be used without being + # replaced by a fresh variable. + USE_THRESHOLD = 1 + + # Ad-Hoc: AST nodes this pass focuses on. + ALLOWED_NODE_TYPES = (ast.Attribute, ast.Call, ast.Subscript) + + @dataclasses.dataclass + class Config: + expr_count: dict[str, int] + expr_to_name: dict[str, str] + + class ExprCounter(ast.NodeVisitor): + def __init__(self, config: PyExprCSEPass.Config) -> None: + self._config = config + + def visit(self, node: ast.AST) -> None: + if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES): + self._config.expr_count[_ast_unparse(node)] += 1 + super().visit(node) + + class Replacer(ast.NodeTransformer): + def __init__( + self, + config: PyExprCSEPass.Config, + gen_name: Callable[[], str], + ) -> None: + super().__init__() + self._config = config + self._gen_name = gen_name + self.preface: list[str] = [] + + def visit(self, node: ast.AST) -> Any: + if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES): + expr = _ast_unparse(node) + + # Replacement only occurs if a given expression is used more + # than once. + if self._config.expr_count[expr] > PyExprCSEPass.USE_THRESHOLD: + if expr not in self._config.expr_to_name: + # Parent 'visit' is called so that we CSE the inner expressions first. + # + # The resulting expression is used as right-hand-side of the variable + # assignment. i.e. we are CSE-ing the children before the parents. + # + # Indexing still uses the old 'node', since that's what was counted + # by the 'NodeVisitor'. + node_ = super().visit(node) + expr_ = _ast_unparse(node_) + var_name = self._gen_name() + self.preface.append(f"{var_name} = {expr_}") + self._config.expr_to_name[expr] = var_name + else: + var_name = self._config.expr_to_name[expr] + return ast.Name(var_name, ast.Load()) + + return super().visit(node) + + def __init__(self) -> None: + self._counter = 0 + self._config = self.Config( + expr_count=collections.defaultdict(lambda: 0), expr_to_name={} + ) + + def _new_var(self, prefix: str = "_var") -> str: + name = f"{prefix}{self._counter}" + self._counter += 1 + return name + + def count(self, exprs: list[str]) -> None: + counter = self.ExprCounter(self._config) + for e in exprs: + try: + counter.visit(ast.parse(e)) + except SyntaxError as ex: + log.exception("Failed to visit expr at line %s.\n%s", ex.lineno, e) + raise + + def replace(self, expr: str) -> tuple[list[str], str]: + replacer = self.Replacer(self._config, self._new_var) + new_node = replacer.visit(ast.parse(expr)) + return replacer.preface, _ast_unparse(new_node) + + +def must_add_nn_module_guards(guard: Guard) -> bool: + # For config.guard_nn_modules=False, we can skip all the guards that + # originate from inside of nn module except for a few categories. + return ( + # Guard for defaults + isinstance(guard.originating_source, DefaultsSource) + # Guard using dict tags if the config flag is set + or ( + config.guard_nn_modules_using_dict_tags + and guard.create_fn is GuardBuilder.NN_MODULE + ) + ) + + +class DeletedGuardManagerWrapper(GuardManagerWrapper): + def __init__(self, reason: str) -> None: + super().__init__() + self.invalidation_reason = reason + + def populate_diff_guard_manager(self) -> None: + self.diff_guard_root = None + + +@dataclasses.dataclass +class ShapeCodeParts: + python_code_parts: _ShapeGuardsHelper + verbose_code_parts: _ShapeGuardsHelper + cpp_code_parts: _CppShapeGuardsHelper | None + python_fallback: bool + shape_env_sources: list[Source] + + +@dataclasses.dataclass +class GuardsState: + output_graph: OutputGraphGuardsState + shape_code_parts: ShapeCodeParts | None + local_state: Any | None = None + + +class _Missing: + def __init__(self, reason: str | None = None) -> None: + self._reason = reason + + def __repr__(self) -> str: + return f"_Missing({self._reason})" + + def __str__(self) -> str: + return f"_Missing({self._reason})" + + # Sometimes _Missing object is used as the callable with functools.partial, + # so we add a dummy __call__ here to bypass TypeError from partial(). + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return _Missing() + + +@functools.cache +def _get_unsupported_types() -> tuple[type, ...]: + # We only do ID_MATCH on C objects which is already banned from guards serialization. + ret: tuple[type, ...] = ( + torch._C.Stream, + weakref.ReferenceType, + ) + try: + ret += (torch._C._distributed_c10d.ProcessGroup,) + except AttributeError: + pass + return ret + + +class GuardsStatePickler(pickle.Pickler): + def __init__( + self, + guard_tree_values: dict[int, Any], + empty_values: dict[int, Any], + missing_values: dict[int, Any], + *args: Any, + **kwargs: Any, + ) -> None: + super().__init__(*args, **kwargs) + self.fake_mode = torch._subclasses.FakeTensorMode() + self.tensor_converter = torch._subclasses.fake_tensor.FakeTensorConverter() + self.guard_tree_values = guard_tree_values + self.empty_values = empty_values + self.missing_values = missing_values + + @classmethod + def _unpickle_module(cls, state: Any) -> torch.nn.Module: + mod = torch.nn.Module() + mod.__setstate__(state) + return mod + + @classmethod + def _unpickle_tensor( + cls, + meta_tensor: torch.Tensor, + device: torch.device, + pytype: type, + dispatch_keys_raw: int, + grad: torch.Tensor, + ) -> torch.Tensor: + fake_mode = torch._subclasses.FakeTensorMode() + tensor_converter = torch._subclasses.fake_tensor.FakeTensorConverter() + ret = tensor_converter.from_meta_and_device( + fake_mode, + meta_tensor, + device, + pytype, + torch._C.DispatchKeySet.from_raw_repr(dispatch_keys_raw), + ) + ret.grad = grad + return ret + + @classmethod + def _unpickle_traceable_wrapper_subclass( + cls, + meta_tensor: torch.Tensor, + device: torch.device, + pytype: type, + dispatch_keys_raw: int, + ctx: Any, + inner_data: list[tuple[str, Any]], + ) -> torch.Tensor: + inner_tensors = dict(inner_data) + + outer_size, outer_stride = meta_tensor.shape, meta_tensor.stride() + # Use the recorded pytype, not type(meta_tensor): a transparent wrapper + # subclass (e.g. AsyncCollectiveTensor) whose __torch_dispatch__ desugars + # ops to its inner tensor makes torch.empty_like() return a plain Tensor, + # so meta_tensor loses the subclass type and Tensor.__tensor_unflatten__ + # does not exist. + out = pytype.__tensor_unflatten__( # type: ignore[attr-defined] + inner_tensors, ctx, outer_size, outer_stride + ) + out.pytype = pytype + out.dispatch_keys = torch._C.DispatchKeySet.from_raw_repr(dispatch_keys_raw) + return out + + @classmethod + def _unpickle_python_module(cls, alias: str) -> types.ModuleType: + return importlib.import_module(alias) + + @classmethod + def _unpickle_dispatch_key_set(cls, raw_repr: int) -> torch._C.DispatchKeySet: + return torch._C.DispatchKeySet.from_raw_repr(raw_repr) + + @classmethod + def _unpickle_functorch_interpreter( + cls, json: bytes + ) -> torch._C._functorch.CInterpreter: + return torch._C._functorch.CInterpreter.deserialize(json) + + @classmethod + def _unpickle_mapping_proxy( + cls, d: dict[Any, Any] + ) -> types.MappingProxyType[Any, Any]: + return types.MappingProxyType(d) + + @classmethod + def _unpickle_dict_keys(cls, elems: list[Any]) -> Any: + return dict.fromkeys(elems).keys() + + @classmethod + def _unpickle_count_iter(cls, item: int, step: int) -> itertools.count[int]: + return itertools.count(item, step) + + @classmethod + def _unpickle_fsdp_module_type( + cls, original_type: type[torch.nn.Module] + ) -> type[torch.nn.Module]: + return torch.distributed.fsdp._fully_shard._fully_shard.get_cls_to_fsdp_cls()[ + original_type + ] + + @classmethod + def _unpickle_ddp_module( + cls, state: dict[str, Any] + ) -> torch.nn.parallel.DistributedDataParallel: + ty = torch.nn.parallel.DistributedDataParallel + ddp = ty.__new__(ty) + torch.nn.Module.__setstate__(ddp, state) + return ddp + + @classmethod + def _unpickle_c_op(cls, name: str) -> Any: + return getattr(torch.ops._C, name) + + @classmethod + def _unpickle_op(cls, namespace: str, opname: str, overloadname: str) -> Any: + return getattr(getattr(getattr(torch.ops, namespace), opname), overloadname) + + @classmethod + def _unpickle_bound_method(cls, func: Any, base: Any) -> Any: + return types.MethodType(func, base) + + @staticmethod + def _unpickle_sdp_backend(name: str) -> torch.nn.attention.SDPBackend: + # Reconstruct from the Python-facing enum namespace + return getattr(torch.nn.attention.SDPBackend, name) + + @classmethod + def _unpickle_cell(cls, val: Any) -> Any: + def _() -> Any: + return val + + if _.__closure__ is None: + raise AssertionError("Closure must not be None when unpickling cell") + return _.__closure__[0] + + @classmethod + def _unpickle_named_tuple_type( + cls, name: str, fields: tuple[str, ...] + ) -> type[NamedTuple]: + # pyrefly: ignore [bad-return] + return collections.namedtuple(name, fields) + + @classmethod + def _unpickle_code(cls, serialized_code: SerializedCode) -> types.CodeType: + from torch._dynamo.package import SerializedCode + + return SerializedCode.to_code_object(serialized_code) + + @classmethod + def _unpickle_nested_function( + cls, + code: types.CodeType, + module: str, + qualname: str, + argdefs: tuple[object, ...] | None, + closure: tuple[types.CellType, ...] | None, + ) -> types.FunctionType: + f_globals = importlib.import_module(module).__dict__ + return types.FunctionType(code, f_globals, qualname, argdefs, closure) + + # pyrefly: ignore [bad-override] + def reducer_override( + self, obj: Any + ) -> tuple[Callable[..., Any], tuple[Any, ...]] | Any: + import sympy + + if id(obj) in self.empty_values: + return type(obj).__new__, (type(obj),) + + if inspect.iscode(obj): + from torch._dynamo.package import SerializedCode + + return type(self)._unpickle_code, (SerializedCode.from_code_object(obj),) + + if id(obj) in self.missing_values: + return _Missing, ("missing values",) + + if isinstance(obj, torch.Tensor) and obj.device.type != "meta": + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + if id(obj) not in self.guard_tree_values: + return _Missing, ("tensor guard tree",) + + if is_traceable_wrapper_subclass(obj): + # inner_data is a list of tuples of: + # (inner attr name, unpickle func, tuple of func inputs) + # This supports traceable wrapper subclass inner tensors. + inner_data = [] + attrs, ctx = obj.__tensor_flatten__() + # recursively call for inner tensor components + for attr in attrs: + inner = getattr(obj, attr) + if isinstance(inner, torch.Tensor): + self.guard_tree_values[id(inner)] = inner + inner_data.append((attr, inner)) + + return type(self)._unpickle_traceable_wrapper_subclass, ( + torch.empty_like(obj, device="meta"), + obj.device, + type(obj), + torch._C._dispatch_keys(obj).raw_repr(), + ctx, + inner_data, + ) + + # For FakeTensors, use pytype if set, otherwise default to + # torch.Tensor. This is important for cross-compilation where + # we compile with fake tensors but run with real tensors. + pytype = type(obj) + if isinstance( # noqa: ISINSTANCE_FAKE_TENSOR + obj, torch._subclasses.FakeTensor + ): + pytype = obj.pytype if obj.pytype is not None else torch.Tensor + + return type(self)._unpickle_tensor, ( + torch.empty_like(obj, device="meta", requires_grad=obj.requires_grad), + obj.device, + pytype, + torch._C._dispatch_keys(obj).raw_repr(), + obj.grad, + ) + + elif isinstance(obj, torch.nn.Module): + if id(obj) not in self.guard_tree_values: + return _Missing, ("module guard tree",) + + for attr in obj.__dict__.values(): + if isinstance(attr, (torch.Tensor, torch.nn.Module)): + continue + if id(attr) in self.guard_tree_values: + continue + if callable(attr): + continue + self.missing_values[id(attr)] = attr + + # DDP module is a special case because it tries to restore unneeded + # data in custom __setstate__. We cannot skip ddp module because it + # is often a toplevel module. + if isinstance(obj, torch.nn.parallel.DistributedDataParallel): + return type(self)._unpickle_ddp_module, (obj.__getstate__(),) + + if type(obj).__qualname__ == type(obj).__name__: + return NotImplemented + if obj.__class__.__getstate__ == torch.nn.Module.__getstate__: + return type(self)._unpickle_module, (obj.__getstate__(),) + + elif inspect.ismodule(obj): + return type(self)._unpickle_python_module, (obj.__name__,) + + elif isinstance(obj, torch._C.DispatchKeySet): + return type(self)._unpickle_dispatch_key_set, (obj.raw_repr(),) + + elif isinstance(obj, torch._C._functorch.CInterpreter): + return type(self)._unpickle_functorch_interpreter, (obj.serialize(),) + + elif ( + inspect.isclass(obj) + and issubclass(obj, sympy.Function) + and hasattr(obj, "_torch_handler_name") + ): + if not hasattr(obj, "_torch_unpickler"): + raise AssertionError( + f"sympy Function subclass {obj} must have _torch_unpickler attribute" + ) + return obj._torch_unpickler, (obj._torch_handler_name,) + + elif ( + inspect.isclass(obj) + and issubclass(obj, tuple) + and hasattr(obj, "_fields") + and obj.__qualname__ != obj.__name__ + ): + return type(self)._unpickle_named_tuple_type, (obj.__name__, obj._fields) + + elif isinstance(obj, torch.SymInt): + raise RuntimeError(f"Cannot serialize SymInt {obj} (node: {obj.node})") + + elif isinstance(obj, types.MappingProxyType): + return type(self)._unpickle_mapping_proxy, (obj.copy(),) + + elif type(obj) is _COUNT_ITERATOR_TYPE: + item, step = normalize_count_iter(obj) + if item is not NotImplemented and step is not NotImplemented: + return type(self)._unpickle_count_iter, (item, step) + + elif isinstance(obj, torch._dynamo.utils.dict_keys): + return type(self)._unpickle_dict_keys, (list(obj),) + + elif isinstance( + obj, torch._ops.OpOverloadPacket + ) and obj._qualified_op_name.startswith("_C::"): + return type(self)._unpickle_c_op, (obj.__name__,) + + elif isinstance(obj, torch._ops.OpOverload): + return type(self)._unpickle_op, ( + obj.namespace, + obj._opname, + obj._overloadname, + ) + + elif ( + obj.__class__.__module__ == "builtins" + and obj.__class__.__name__ == "PyCapsule" + ): + # Skipping PyCapsule since there isn't much to be guarded about them. + return _Missing, ("capsule",) + + elif isinstance(obj, _get_unsupported_types()): + return _Missing, ("unsupported",) + + elif inspect.isfunction(obj): + if "" in obj.__qualname__: + return type(self)._unpickle_nested_function, ( + obj.__code__, + obj.__module__, + obj.__qualname__, + obj.__defaults__, + obj.__closure__, + ) + if obj.__module__ in sys.modules: + f = sys.modules[obj.__module__] + for name in obj.__qualname__.split("."): + f = getattr(f, name, None) # type: ignore[assignment] + if f is not obj: + return _Missing, ("fqn mismatch",) + elif inspect.ismethod(obj): + func = obj.__func__ + method_self = obj.__self__ + inner_func = getattr(method_self, func.__name__) + if inspect.ismethod(inner_func): + inner_func = inner_func.__func__ + if func is not inner_func: + return type(self)._unpickle_bound_method, (func, method_self) + + elif isinstance(obj, type((lambda x: lambda: x)(0).__closure__[0])): # type: ignore[index] # noqa: PLC3002 + return type(self)._unpickle_cell, (obj.cell_contents,) + + if hasattr(torch.distributed, "distributed_c10d") and isinstance( + obj, torch.distributed.distributed_c10d.Work + ): + if id(obj) not in self.guard_tree_values: + return _Missing, ("distributed_c10d.Work",) + + if isinstance(obj, torch.nn.attention.SDPBackend): + return type(self)._unpickle_sdp_backend, (obj.name,) + + if type(obj).__qualname__ != type(obj).__name__ and not isinstance(obj, tuple): + raise torch._dynamo.exc.PackageError( + f"Type {type(obj)} for object {obj} cannot be saved " + + "into torch.compile() package since it's defined in local scope. " + + "Please define the class at global scope (top level of a module)." + ) + + if ( + inspect.isclass(obj) + and hasattr(torch.distributed, "fsdp") + and issubclass(obj, torch.distributed.fsdp._fully_shard.FSDPModule) + ): + if obj is not torch.distributed.fsdp._fully_shard.FSDPModule: + original_type = obj.__mro__[2] + if not issubclass(original_type, torch.nn.Module): + raise AssertionError( + f"Expected nn.Module subclass, got {original_type}" + ) + if ( + original_type + not in torch.distributed.fsdp._fully_shard._fully_shard.get_cls_to_fsdp_cls() + ): + raise AssertionError( + f"{original_type} not found in FSDP cls-to-fsdp-cls mapping" + ) + return type(self)._unpickle_fsdp_module_type, (original_type,) + + return NotImplemented + + +def make_guard_filter_entry(guard: Guard, builder: GuardBuilder) -> GuardFilterEntry: + MISSING = object() + name = strip_local_scope(guard.name) + if name == "": + has_value = False + value = MISSING + else: + try: + # Guard evaluation is expected to fail when we guard on + # things like "not hasattr(x, 'foo')". In cases like this, + # we don't have a well defined value because such thing + # doesn't exist. + value = builder.get(guard) + has_value = True + except: # noqa: E722 + value = MISSING + has_value = False + is_global = get_global_source_name(guard.originating_source) is not None + return GuardFilterEntry( + name=name, + has_value=has_value, + value=value, + guard_type=guard.create_fn_name(), + derived_guard_types=(tuple(guard.guard_types) if guard.guard_types else ()), + is_global=is_global, + orig_guard=guard, + ) + + +def pickle_guards_state( + state: GuardsState, + builder: GuardBuilder, +) -> bytes: + buf = io.BytesIO() + empty_values = {} + missing_values = {} + guard_tree_values = builder.guard_tree_values + + leaves = pytree.tree_leaves(state.output_graph.local_scope) + for leaf in leaves: + if inspect.ismethod(leaf) and hasattr(leaf, "__self__"): + base = leaf.__self__ + if id(base) not in guard_tree_values: + try: + type(base).__new__(type(base)) + empty_values[id(base)] = base + except: # noqa: E722 + pass + elif id(leaf) not in guard_tree_values: + # TODO See if we have lift this branch as the first one. + # Prune more objects in pytree hierarchy. + missing_values[id(leaf)] = leaf + pickler = GuardsStatePickler(guard_tree_values, empty_values, missing_values, buf) + + if all( + torch.compiler.keep_portable_guards_unsafe( + [ + make_guard_filter_entry(guard, builder) + for guard in state.output_graph.guards + ] + ) + ): + # Prune more values in AOT precompile when complex pickling structure is not needed. + state.output_graph.guard_on_key_order = set() + state.output_graph.global_scope = {} + + try: + pickler.dump(state) + except AttributeError as e: + raise torch._dynamo.exc.PackageError(str(e)) from e + return buf.getvalue() + + +# NB: Naively, you'd expect this to only be a function that produces +# the callable that constitutes the guard. However, there is some +# delicate handling for invalidating this check function when the +# locals/globals get invalidated, so there's some extra state +# we have to hold in this manager class. +class CheckFunctionManager: + def __init__( + self, + f_code: types.CodeType, + output_graph: OutputGraphCommon, + cache_entries: list[CacheEntry] | None = None, + guard_fail_fn: Callable[[GuardFail], None] | None = None, + guard_filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] + | None = None, + shape_code_parts: ShapeCodeParts | None = None, + runtime_global_scope: dict[str, Any] | None = None, + save_guards: bool = False, + strict_error: bool = False, + guard_build_local_state: Any | None = None, + ) -> None: + guards = output_graph.guards if output_graph else None + self._weakrefs: dict[int, ReferenceType[object]] = {} + + existing_diff_guard_sources = ( + update_diff_guard_managers_for_existing_cache_entries(cache_entries or []) + ) + self.output_graph: OutputGraphCommon | None = output_graph + if self.output_graph is None: + raise AssertionError("output_graph must not be None") + + # Only used for serialization. + self.shape_code_parts = shape_code_parts + + # NB: Until we trace device contexts, we need to use the stack recorded at the beginning of tracing + # in case a set default device call was made in the graph. + self.torch_function_mode_stack = ( + output_graph.torch_function_mode_stack if output_graph else None + ) + self.used_builtin_vars: OrderedSet[str] = OrderedSet() + self.additional_used_local_vars: OrderedSet[str] = OrderedSet() + self.additional_used_global_vars: OrderedSet[str] = OrderedSet() + self.runtime_global_scope = runtime_global_scope + self.guard_build_local_state = guard_build_local_state + self.global_state: torch._C._dynamo.guards.GlobalStateGuard | None = None + self.torch_function_mode_stack_check_fn: Callable[[], bool] | None = None + + if not justknobs_check("pytorch/compiler:guard_nn_modules"): + log.warning("guard_nn_modules is turned off using justknobs killswitch") + + # TODO Be more explicit about the behavior for the users. + if torch._dynamo.config.caching_precompile: + _guard_filter_fn = guard_filter_fn or (lambda gs: [True for g in gs]) + + def guard_filter_fn(guards: Sequence[GuardFilterEntry]) -> Sequence[bool]: + ret = [] + for keep, g in zip(_guard_filter_fn(guards), guards): + if not keep: + ret.append(False) + elif ( + g.guard_type + in ( + "ID_MATCH", + "CLOSURE_MATCH", + "WEAKREF_ALIVE", + "DICT_VERSION", + ) + or "ID_MATCH" in g.derived_guard_types + or "DICT_VERSION" in g.derived_guard_types + ): + log.warning( + "%s guard on %s is dropped with caching_precompile=True.", + g.guard_type, + g.orig_guard.name, + ) + ret.append(False) + else: + ret.append(True) + return ret + + sorted_guards = sorted(guards or (), key=Guard.sort_key) + + # Disable __torch_function__ dispatch during guard construction so + # modes with mutable state aren't triggered. We exit the context + # before the guard sanity check so GlobalStateGuard.check() sees + # the true runtime state. + with torch._C.DisableTorchFunction(): + if guard_filter_fn: + # If we're filtering guards, we need to build it an extra time first + # because filtering depends on the builder/guard_manager results + builder, guard_manager = self.build_guards( + sorted_guards, + existing_diff_guard_sources, + f_code, + output_graph, + False, + ) + + filter_results = guard_filter_fn( + [make_guard_filter_entry(guard, builder) for guard in sorted_guards] + ) + if len(filter_results) != len(sorted_guards): + raise AssertionError( + f"filter_results length ({len(filter_results)}) != " + f"sorted_guards length ({len(sorted_guards)})" + ) + if not all(type(x) is bool for x in filter_results): + raise AssertionError("All filter_results entries must be bool") + sorted_guards = [ + guard for i, guard in enumerate(sorted_guards) if filter_results[i] + ] + + # Redo the guards because filtering relies on the results from the last guard builder. + builder, guard_manager = self.build_guards( + sorted_guards, + existing_diff_guard_sources, + f_code, + output_graph, + save_guards, + guard_filter_fn=guard_filter_fn, + ) + + self.guard_manager = guard_manager + self.compile_check_fn(builder, sorted_guards, guard_fail_fn) + + # Keep track of weak references of objects with ID_MATCH guard. This + # info is stored alongside optimized_code and guard_manager and is used to + # limit the number of cache entries with same ID_MATCH'd object. + # TODO(anijain2305) - Currently this information is stored as an attr on + # the guard_manager itself to avoid changing CacheEntry data structure in + # eval_frame.c. In future, we should probably replace guard_manager with a + # queryable data structure such that this information is already present + # in some form. + self.guard_manager.id_matched_objs = builder.id_matched_objs + + guards_log.debug("%s", self.guard_manager) + self.guard_manager.id_matched_objs = builder.id_matched_objs + + # Check that the guard returns True. False means that we will always + # recompile. + # TODO(anijain2305, ydwu4) - Skipping export because of following test + # python -s test/dynamo/test_export.py -k test_export_with_symbool_inputs + latency = 0.0 + + # Non-strict tracing can compile with fake inputs whose unbacked sizes + # cannot be used to evaluate guards eagerly. Keep the runtime guards, + # but skip this same-frame sanity check in that tracing context. + if ( + not output_graph.skip_guards_check + and not output_graph.export + and not torch.compiler._is_non_strict_tracing() + ): + if not self.guard_manager.check(output_graph.local_scope): + reasons = get_guard_fail_reason_helper( + self.guard_manager, + output_graph.local_scope, + CompileContext.current_compile_id(), + backend=None, # no need to set this because we are trying to find the offending guard entry + ) + raise AssertionError( + "Guard failed on the same frame it was created. This is a bug - please create an issue." + f"Guard fail reason: {reasons}" + ) + + if guard_manager_testing_hook_fn is not None: + guard_manager_testing_hook_fn( + self.guard_manager, output_graph.local_scope, builder + ) + + # NB for developers: n_iters is chosen to be 1 to prevent excessive + # increase in compile time. We first do a cache flush to measure the + # guard latency more accurately. This cache flush is expensive. + # Note - If you are working on a guard optimization, it might be a + # good idea to increase this number for more stability during + # development. + latency = profile_guard_manager( + self.guard_manager.root, output_graph.local_scope, 1 + ) + guards_log.debug("Guard eval latency = %s us", f"{latency:.2f}") + # Note: We use `increment_toplevel` instead of `compilation_metric` + # here. This is because, in scenarios where `torch._dynamo.reset` + # is invoked, the same frame ID and compile ID may be reused during + # a new compilation cycle. This behavior causes issues with + # `compilation_metric`, as it expects the metric field to be empty. + # Ideally, we would overwrite the existing entry in such cases, but + # we currently lack an API to support overwriting metrics. However, + # since these situations are rare and typically impractical to + # account for, we simply increment at the toplevel instead. + CompileEventLogger.increment_toplevel("guard_latency_us", int(latency)) + + self.guards_state: bytes | None = None + if save_guards: + from torch._dynamo.output_graph import OutputGraphCommon + + if not isinstance(self.output_graph, OutputGraphCommon): + raise AssertionError( + f"Expected OutputGraphCommon, got {type(self.output_graph)}" + ) + try: + self.guards_state = self.serialize_guards( + builder, sorted_guards, self.output_graph + ) + except exc.PackageError as e: + if torch._dynamo.config.strict_precompile or strict_error: + raise e + self.output_graph.bypass_package( + f"Guard evaluation failed: {str(e)}", + traceback=traceback.format_exc().split("\n"), + ) + + # TODO: don't do the string rep, do something more structured here + torch._logging.trace_structured( + "dynamo_cpp_guards_str", + payload_fn=lambda: f"{self.guard_manager}\nGuard latency = {latency:.2f} us", + ) + # NB - We have to very careful of cleaning up here. Because of the + # invalidate function, we can create a weakref finalizer that keeps + # `self` alive for very long. Sometimes by mistake, we can run + # invalidate for a type/object (check id_ref method) that Python can + # leak by design, preventing us from calling the finalizer. In that + # case, the `self` will be alive even though the cache entry will be + # deleted (check invalidate method), which can cause a memory leak, + # e.g., not setting output_graph = None can keep hold of nn_modules. + self._weakrefs.clear() + self.output_graph = None + + UNSUPPORTED_SERIALIZATION_GUARD_TYPES: tuple[LiteralString, ...] = ( + "DICT_VERSION", + "NN_MODULE", + "ID_MATCH", + "FUNCTION_MATCH", + "CLASS_MATCH", + "MODULE_MATCH", + "CLOSURE_MATCH", + "WEAKREF_ALIVE", + ) + + def serialize_guards( + self, + builder: GuardBuilder, + sorted_guards: list[Guard], + output_graph: OutputGraphCommon, + ) -> bytes: + # We check whether our list of guards are serializable here + for guard in sorted_guards: + guard_type = guard.create_fn_name() + derived_guard_types = tuple(guard.guard_types) if guard.guard_types else () + # BUILTIN_MATCH calls TYPE_MATCH sometimes, so we need to check both for + # a chance that the guard is unserializable + if guard_type in ("TYPE_MATCH", "BUILTIN_MATCH"): + if guard._unserializable: + # Only call builder.get again if we know we're going to throw + obj = builder.get(guard) + raise_local_type_error(obj) + elif ( + guard_type in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES + ): + raise torch._dynamo.exc.PackageError( + f"{guard_type} guard cannot be serialized." + ) + elif failed := next( + ( + i + for i in derived_guard_types + if i in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES + ), + None, + ): + # Just raise the first failed guard name + raise torch._dynamo.exc.PackageError( + f"{failed} guard cannot be serialized." + ) + + builtins_dict_name = output_graph.name_of_builtins_dict_key_in_fglobals or "" + used_global_vars = set() + used_local_vars = set() + + def prune_variable(source: Source) -> None: + if name := get_global_source_name(source): + if not isinstance(name, str): + raise AssertionError(f"Expected str, got {type(name)}") + # Leave out the builtins dict key, as we will special handle + # it later because the guarded code rarely use the entire + # builtin dict in the common case. + if name != builtins_dict_name: + used_global_vars.add(name) + elif name := get_local_source_name(source): + if not isinstance(name, str): + raise AssertionError(f"Expected str, got {type(name)}") + used_local_vars.add(name) + + output_graph_guards_state = output_graph.dump_guards_state() + # Only serialize the global variables that are actually used in guards. + for guard in sorted_guards: + if isinstance(guard.originating_source, ShapeEnvSource): + if not self.shape_code_parts: + raise AssertionError( + "shape_code_parts must be set for ShapeEnvSource guards" + ) + for source in self.shape_code_parts.shape_env_sources: + prune_variable(source) + else: + prune_variable(guard.originating_source) + + for source in output_graph.guard_on_key_order: + prune_variable(source) + + def normalize_create_fn(x: Callable[..., None]) -> Callable[..., None]: + if isinstance(x, functools.partial): + + def _ref(x: Any) -> Any: + if isinstance(x, (TensorWeakRef, weakref.ref)): + return x() + return x + + new_args = tuple(_ref(a) for a in x.args) + new_keywords = {k: _ref(v) for k, v in x.keywords.items()} + return functools.partial(x.func, *new_args, **new_keywords) + + return x + + global_scope_state = { + k: v + for k, v in output_graph_guards_state.global_scope.items() + if k in used_global_vars or k in self.additional_used_global_vars + } + global_scope_state[builtins_dict_name] = { + k: v + # pyrefly: ignore [missing-attribute] + for k, v in output_graph_guards_state.global_scope[ + builtins_dict_name + ].items() # type: ignore[attr-defined] + if k in self.used_builtin_vars + } + output_graph_guards_state = dataclasses.replace( + output_graph_guards_state, + local_scope={ + k: v + for k, v in output_graph_guards_state.local_scope.items() + if k in used_local_vars or k in self.additional_used_local_vars + }, + global_scope=global_scope_state, + _guards=torch._guards.GuardsSet( + OrderedSet( + dataclasses.replace( + guard, + obj_weakref=None, + guarded_class_weakref=None, + create_fn=normalize_create_fn(guard.create_fn), + ) + for guard in sorted_guards + ) + ), + input_source_to_sizes_strides=pytree.tree_map( + convert_int_to_concrete_values, + output_graph_guards_state.input_source_to_sizes_strides, + ), + skip_guards_check=True, + ) + guards_state = GuardsState( + output_graph=output_graph_guards_state, + shape_code_parts=self.shape_code_parts, + local_state=self.guard_manager.root.get_local_state(), + ) + + return pickle_guards_state(guards_state, builder) + + def build_guards( + self, + sorted_guards: list[Guard], + existing_diff_guard_sources: OrderedSet[str], + f_code: types.CodeType, + output_graph: OutputGraphGuardsState, + save_guards: bool, + guard_filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] + | None = None, + ) -> tuple[GuardBuilder, GuardManagerWrapper]: + guard_manager = GuardManagerWrapper(local_state=self.guard_build_local_state) + guard_manager.diff_guard_sources = existing_diff_guard_sources + + w_builder = None + + def source_ref(source: Source) -> str: + guard_source = source.guard_source + if guard_source is GuardSource.CONSTANT: + # No need to track constants + return source.name + if not w_builder: + raise AssertionError("w_builder must be set before calling source_ref") + r_builder = w_builder() + if r_builder is None: + raise AssertionError("GuardBuilder has been garbage collected") + return r_builder.arg_ref(source.name) + + builder = GuardBuilder( + f_code, + self.id_ref, + source_ref, + self.lookup_weakrefs, + output_graph.local_scope, + output_graph.global_scope, + guard_manager, + self, + save_guards, + runtime_global_scope=self.runtime_global_scope, + guard_filter_fn=guard_filter_fn, + ) + + # Break retain cycle. See test_release_scope_memory + def cleanup_builder(weak_b: weakref.ref[GuardBuilder]) -> None: + b = weak_b() + if b: + b.scope = None # type: ignore[assignment] + + # Break retain cycle. See test_release_input_memory + w_builder = weakref.ref(builder, cleanup_builder) + + guard_on_nn_modules = config.guard_nn_modules and justknobs_check( + "pytorch/compiler:guard_nn_modules" + ) + + for guard in sorted_guards: + # guard_types/code_list are per-build export info, but they + # accumulate on the shared Guard objects across builds. Reset them + # so results from a previous build (e.g. the pre-filtering build or + # an earlier non-save CheckFunctionManager) don't leak into this + # build; serialize_guards relies on them to detect unserializable + # guards, and a non-save build may derive different guards (e.g. + # DICT_VERSION for SUPPORTED_NODES) than a save build. + guard.guard_types = None + guard.code_list = None + + if ( + not guard_on_nn_modules + and guard.is_specialized_nn_module() + # Default func args must be guarded on. + # TODO: we could make use of 'DefaultsSource' and offer a .guard.is_defaults() API + and "__defaults__" not in guard.name + and "__kwdefaults__" not in guard.name + and (config.skip_nnmodule_hook_guards or "hooks" not in guard.name) + ): + continue + + guard.create(builder) + return builder, guard_manager + + def compile_check_fn( + self, + builder: GuardBuilder, + guards_out: list[Guard], + guard_fail_fn: Callable[[GuardFail], None] | None, + ) -> None: + # see parallel handling of ".0" / "___implicit0" in _eval_frame.c + largs = builder.argnames + largs += ["**___kwargs_ignored"] + + guards_log.debug("GUARDS:") + + # pyrefly: ignore [implicit-any] + code_parts = [] + verbose_code_parts = [] + structured_guard_fns: list[Callable[[], dict[str, Any]]] = [] + + # Add compile id info in the guard manager for debugging purpose + self.guard_manager.root.attach_compile_id( + str(CompileContext.current_compile_id()) + ) + + # Clear references to torch_function modes held in the list + self.torch_function_mode_stack = None + + def add_code_part( + code_part: str, guard: Guard | None, log_only: bool = False + ) -> None: + verbose_code_part = get_verbose_code_part(code_part, guard) + guards_log.debug("%s", verbose_code_part) + + structured_guard_fns.append( + lambda: { + "code": code_part, + "stack": ( + structured.from_traceback(guard.stack.summary()) + if guard and guard.stack + else None + ), + "user_stack": ( + structured.from_traceback(guard.user_stack) + if guard and guard.user_stack + else None + ), + } + ) + + if verbose_guards_log.isEnabledFor(logging.DEBUG): + maybe_stack = "" + maybe_user_stack = "" + if guard is not None: + if guard.stack: + maybe_stack = f"\nStack:\n{''.join(guard.stack.format())}" + if guard.user_stack: + maybe_user_stack = ( + f"\nUser stack:\n{''.join(guard.user_stack.format())}" + ) + verbose_guards_log.debug( + "Guard: %s%s%s", + code_part, + maybe_stack, + maybe_user_stack, + ) + + if not log_only: + code_parts.append(code_part) + verbose_code_parts.append(verbose_code_part) + + seen = set() + for gcl in builder.code: + for code in gcl.code_list: + if code not in seen: + # If Cpp guard manager is enabled, we don't need to add to + # code_parts. + add_code_part(code, gcl.guard, True) + seen.add(code) + + no_tensor_aliasing_names = builder.no_tensor_aliasing_names + check_tensors_fn = None + check_tensors_verbose_fn = None + + if len(no_tensor_aliasing_names) > 1: + # Install tensor aliasing guard. TENSOR_MATCH guards are already + # installed for cpp guard manager. + install_no_tensor_aliasing_guard( + builder.no_tensor_aliasing_guard_managers, + no_tensor_aliasing_names, + ["check_no_aliasing(" + ", ".join(no_tensor_aliasing_names) + ")"], + None, + ) + + # Note - On Lambda guarding of object aliasing + # We previously installed object-aliasing guards as relational guards, + # but that undermined the recursive-dict guard optimization: placing the + # aliasing guard at a leaf prevented the parent dict node from + # qualifying as a recursive-dict guard root. Because aliasing guards are + # rare, we now emit them as epilogue guards via a small Python lambda. + # This repeats the access in Python—adding a bit of work—but the + # overhead is outweighed by the gains from enabling recursive-dict guard + # optimization. + if ( + config.use_lamba_guard_for_object_aliasing + and builder.object_aliasing_guard_codes + ): + aliasing_code_parts, aliasing_verbose_code_parts = map( + list, zip(*builder.object_aliasing_guard_codes) + ) + builder.add_python_lambda_leaf_guard_to_root( + aliasing_code_parts, aliasing_verbose_code_parts + ) + + aotautograd_guards: list[GuardEnvExpr] = ( + self.output_graph.aotautograd_guards if self.output_graph else [] + ) + + # TODO(anijain2305) - There is a duplicate logic in Dynamo to find + # aliased input tensors. So most probably we don't need this here. + # Revisit. + for guard in aotautograd_guards: + if isinstance(guard, DuplicateInputs): + source_a = guard.input_source_a + source_b = guard.input_source_b + code_part = f"{source_a.name} is {source_b.name}" + install_object_aliasing_guard( + builder.get_guard_manager_from_source(source_a), + builder.get_guard_manager_from_source(source_b), + [code_part], + None, + ) + add_code_part(code_part, None, True) + elif isinstance(guard, StorageOverlap): + overlapping_guard_managers = [ + builder.get_guard_manager_from_source(s) + for s in guard.overlapping_sources + ] + non_overlapping_guard_managers = [ + builder.get_guard_manager_from_source(s) + for s in guard.non_overlapping_sources + ] + code_part = ( + """check_overlapping(""" + f"""overlapping=[{", ".join(s.name for s in guard.overlapping_sources)}], """ + f"""non_overlapping=[{", ".join(s.name for s in guard.non_overlapping_sources)}])""" + ) + install_storage_overlapping_guard( + overlapping_guard_managers, + non_overlapping_guard_managers, + [code_part], + None, + ) + add_code_part(code_part, None, True) + else: + raise RuntimeError(f"Unknown GuardEnvExpr: {guard}") + + # TODO: the "guard" here is actually just the top level SHAPE_ENV + # which is useless. Get ShapeEnv to pass in more provenance. + for gcl in builder.shape_env_code: + for code in gcl.code_list: + # Shape env guards are already added for CPP guard manager in + # SHAPE_ENV implementation. + add_code_part(code, gcl.guard, True) + + # OK, all done generating guards + if structured_guard_fns: + torch._logging.trace_structured( + "dynamo_guards", payload_fn=lambda: [f() for f in structured_guard_fns] + ) + + if convert_frame.initial_global_state is None: + # we should only hit this case in NopTests() + check_global_state = convert_frame.GlobalStateGuard().check + else: + check_global_state = getattr(self.global_state, "check", None) + closure_vars = { + "___check_tensors": check_tensors_fn, + "___check_tensors_verbose": check_tensors_verbose_fn, + "___check_global_state": check_global_state, + "___check_torch_function_mode_stack": self.torch_function_mode_stack_check_fn, + **SYMPY_INTERP, + **_get_closure_vars(), + } + + self.guard_manager.finalize() + + globals_for_guard_fn = {"G": builder.scope["G"]} + # Guard manager construction is complete. Ensure we did not miss to + # insert a guard in cpp guard manager. + if len(code_parts) != 0: + raise AssertionError( + f"Expected all code_parts to be consumed, but {len(code_parts)} remain" + ) + + self.guard_manager.closure_vars = closure_vars + self.guard_manager.args = largs + self.guard_manager.populate_code_parts_for_debugging() + self.guard_manager.verbose_code_parts = verbose_code_parts + # Grab only G, but preserve "G" because guards access it as "G" + self.guard_manager.global_scope = globals_for_guard_fn + self.guard_manager.guard_fail_fn = guard_fail_fn + # will be populated by a non-owning reference to CacheEntry/ExtraState + # when the CacheEntry is constructed + self.guard_manager.cache_entry = None + self.guard_manager.extra_state = None + self.guard_manager.no_tensor_aliasing_sources = no_tensor_aliasing_names + + def invalidate(self, obj_str: str) -> None: + # Some tests reveal that CheckFunctionManager has no attribute + # guard_manager, but this case should not be of any concern. + # This case doesn't seem easy to repro. + if ( + hasattr(self, "guard_manager") + and not isinstance(self.guard_manager, DeletedGuardManagerWrapper) + and (cache_entry := self.guard_manager.cache_entry) is not None + and (extra_state := self.guard_manager.extra_state) is not None + ): + if not isinstance(cache_entry, CacheEntry): + raise AssertionError(f"Expected CacheEntry, got {type(cache_entry)}") + + if not isinstance(extra_state, ExtraState): + raise AssertionError(f"Expected ExtraState, got {type(extra_state)}") + reason = f"Cache line invalidated because {obj_str} got deallocated" + deleted_guard_manager = DeletedGuardManagerWrapper(reason) + + extra_state.invalidate(cache_entry, deleted_guard_manager) + self.guard_manager = deleted_guard_manager + + def id_ref(self, obj: object, obj_str: str) -> int: + """add a weakref, return the id""" + try: + if id(obj) not in self._weakrefs: + # We will clear the _weakrefs dict at the end of __init__ + # function, which will delete the callbacks as well. Therefore, + # we are using a finalizer which is kept alive. + self._weakrefs[id(obj)] = weakref.ref(obj) + weakref.finalize( + obj, functools.partial(self.invalidate, obj_str=obj_str) + ) + except TypeError: + pass # cannot weakref bool object + return id(obj) + + def lookup_weakrefs(self, obj: object) -> weakref.ref[object] | None: + """Lookup the _weakrefs created in id_ref function for ID_MATCH'd objects""" + if id(obj) in self._weakrefs: + return self._weakrefs[id(obj)] + return None + + +def build_guard_function(code_parts: list[str], closure_args: str) -> tuple[str, str]: + from torch.utils._indented_buffer import IndentedBuffer + + csepass = PyExprCSEPass() + try: + csepass.count(code_parts) + + def replace(expr: str) -> tuple[list[str], str]: + return csepass.replace(expr) + + except RecursionError: + # If we hit recursion limits during CSE analysis, fall back to a no-op replace function + # This can happen with extremely complex guard expressions + def replace(expr: str) -> tuple[list[str], str]: + return [], expr + + # Generate the inner body of the guard function. + # i.e. if-chain of the guard expressions. + guard_body = IndentedBuffer() + for expr in code_parts: + preface, expr = replace(expr) + guard_body.writelines(preface) + guard_body.writeline(f"if not ({expr}):") + with guard_body.indent(): + guard_body.writeline("return False") + + # Wrap the inner body into the actual guard function. + guard = IndentedBuffer() + guard.writeline("def guard(L):") + with guard.indent(): + guard.splice(guard_body) + guard.writeline("return True") + + # Wrap the whole guard function into another function + # with the closure variables. + make_guard_fn = IndentedBuffer() + make_guard_fn.writeline(f"def ___make_guard_fn({closure_args}):") + with make_guard_fn.indent(): + make_guard_fn.splice(guard) + make_guard_fn.writeline("return guard") + + return guard_body.getvalue(), make_guard_fn.getvalue() + + +def is_recompiles_enabled() -> bool: + return torch._logging._internal.log_state.is_artifact_enabled("recompiles") + + +def is_recompiles_verbose_enabled() -> bool: + return torch._logging._internal.log_state.is_artifact_enabled("recompiles_verbose") + + +# this will only be used if cpp guards are disabled +def make_torch_function_mode_stack_guard( + initial_stack: list[torch.overrides.TorchFunctionMode], +) -> Callable[[], bool]: + types = [type(x) for x in initial_stack] + + def check_torch_function_mode_stack() -> bool: + cur_stack = get_torch_function_mode_stack() + + if len(cur_stack) != len(types): + return False + + for ty, mode in zip(types, cur_stack): + if ty is not type(mode): + return False + + return True + + return check_torch_function_mode_stack + + +Scope = TypeAliasType("Scope", dict[str, object]) + + +def recompilation_reason_for_no_tensor_aliasing_guard( + guard_manager: GuardManagerWrapper, scope: Scope +) -> list[str]: + if guard_manager.global_scope is None: + raise AssertionError("guard_manager.global_scope must not be None") + global_scope = dict(guard_manager.global_scope) + ids_to_source = collections.defaultdict(list) + for tensor_source in guard_manager.no_tensor_aliasing_sources: + global_scope["__compile_source__"] = tensor_source + tensor_id = id(eval(tensor_source, global_scope, scope)) + ids_to_source[tensor_id].append(tensor_source) + + duplicate_tensors = [ + f"{ids_to_source[key]}" for key in ids_to_source if len(ids_to_source[key]) > 1 + ] + + reason = ", ".join(duplicate_tensors) + return [f"Duplicate tensors found: {reason}"] + + +def strip_local_scope(s: str) -> str: + """ + Replace occurrences of L[...] with just the inner content. + Handles both single and double quotes. + + This is to generate user friendly recompilation messages. + """ + import re + + pattern = r"L\[\s*['\"](.*?)['\"]\s*\]" + return re.sub(pattern, r"\1", s) + + +def format_user_stack_trace( + user_stack: traceback.StackSummary | None, +) -> str: + """ + Format the user stack trace for display in guard failure messages. + + Returns a formatted string representation of the stack trace, + or an empty string if no user stack is available. + """ + if user_stack is None or len(user_stack) == 0: + return "" + + lines: list[str] = [] + for frame in user_stack: + filename = frame.filename + lineno = frame.lineno + name = frame.name + source_line = frame.line.strip() if frame.line else "" + lines.append(f' File "{filename}", line {lineno}, in {name}') + if source_line: + lines.append(f" {source_line}") + return "\n".join(lines) + + +def describe_backend(backend: Callable[..., object] | None) -> str: + """Return a human-readable string describing a backend callable for debugging.""" + if backend is None: + return "None" + + # _TorchCompileWrapper is the internal wrapper created by torch.compile(). + # It has structured fields that are more informative than generic introspection. + from torch import _TorchCompileWrapper + + if isinstance(backend, _TorchCompileWrapper): + details = f"compiler={backend.compiler_name!r}, dynamic={backend.dynamic!r}" + if backend.kwargs: + details += f", kwargs={backend.kwargs!r}" + return f"_TorchCompileWrapper({details}) (id={id(backend):#x})" + + actual = backend + prefix = "" + if isinstance(actual, functools.partial): + prefix = "functools.partial wrapping " + actual = actual.func + + qualname = getattr(actual, "__qualname__", None) + module = getattr(actual, "__module__", None) + + if qualname and module: + name = f"{module}.{qualname}" + elif qualname: + name = qualname + elif hasattr(actual, "__name__"): + name = actual.__name__ + else: + name = type(actual).__name__ + + code = getattr(actual, "__code__", None) + location = ( + f" defined at {code.co_filename}:{code.co_firstlineno}" + if code is not None + else "" + ) + + return f"{prefix}{name}{location} (id={id(backend):#x})" + + +def get_guard_fail_reason_helper( + guard_manager: GuardManagerWrapper, + f_locals: dict[str, object], + compile_id: CompileId | None, + backend: Callable[..., object] | None, +) -> str: + """ + Return the reason why `guard_manager` failed. + Updates `guard_failures` with the generated reason. + Only the first failed check of guard_manager is reported. + """ + + if guard_manager.global_scope is None: + raise AssertionError("guard_manager.global_scope must not be None") + if guard_manager.closure_vars is None: + raise AssertionError("guard_manager.closure_vars must not be None") + scope = {"L": f_locals, "G": guard_manager.global_scope["G"]} + scope.update(guard_manager.closure_vars) + reasons: list[str] = [] + + cache_entry_backend = None + if guard_manager.cache_entry: + cache_entry_backend = guard_manager.cache_entry.backend + + no_tensor_aliasing_check_failed = False + + verbose_code_parts: list[str] = [] + guard_debug_info = guard_manager.check_verbose(f_locals) + user_stack_str = "" + + # For test_export_with_map_cond, the check_verbose fail even without the + # C++ guard manager. We need to fix the issue to remove the comment. + # assert not guard_debug_info.result + if not guard_debug_info.result: + verbose_code_parts = guard_debug_info.verbose_code_parts + # verbose_code_parts is either the actual reason (e.g. in case of + # TENSOR_MATCH) or it could be a list of verbose_code_part that we + # passed to the leaf guard at construction time. If its a list, we + # walk through this list and find the guard that failed. This is + # very important for symbolic shape guards which are currently + # installed as a lambda guard and can encompass a long list of code_parts. + + if len(verbose_code_parts) == 1: + if "Duplicate tensor found" in verbose_code_parts[0]: + no_tensor_aliasing_check_failed = True + else: + reasons = verbose_code_parts + verbose_code_parts = [] + + # Format user stack trace if available and recompile logging is enabled + if guard_debug_info.user_stack: + user_stack_str = format_user_stack_trace(guard_debug_info.user_stack) + elif cache_entry_backend != backend: + # None of the guard entries failed - a backend match issue + cached_desc = describe_backend(cache_entry_backend) + new_desc = describe_backend(backend) + reason = ( + f"BACKEND_MATCH failure: torch.compile detected different backend callables." + f" Cached backend: {cached_desc}." + f" New backend: {new_desc}." + " If this is unexpected, wrap your backend in functools.partial (or reuse the" + " same cached backend) to avoid creating a new backend function each time." + " More details: https://github.com/pytorch/pytorch/issues/168373" + ) + reasons.append(reason) + else: + # Unexpected recompilation - points to a bug + reason = ( + "Unexpected recompilation: runtime guards failed even though they passed" + " during recompilation-reason analysis." + " Please open an issue with a minimal repro:" + " https://github.com/pytorch/pytorch" + ) + reasons.append(reason) + + if no_tensor_aliasing_check_failed: + reasons = recompilation_reason_for_no_tensor_aliasing_guard( + guard_manager, scope + ) + else: + for part in verbose_code_parts: + global_scope = dict(guard_manager.global_scope) + global_scope["__compile_source__"] = part + with report_compile_source_on_error(): + try: + fail_reason = eval(part, global_scope, scope) + except Exception: + if is_recompiles_verbose_enabled(): + continue + else: + raise + # Only ___check_tensors knows how to return a fancy fail reason; + # for everything else we just report the code that failed + + if isinstance(fail_reason, bool) and not fail_reason: + fail_reason = part + if isinstance(fail_reason, str): + reasons.append(fail_reason) + if not is_recompiles_verbose_enabled(): + break + + # Build reason string - simple format for normal logging + # Use singular "reason" when there's only one, plural "reasons" for multiple + if len(reasons) == 1: + reason_str = f"{compile_id}: {reasons[0]}" + else: + reason_str = f"{compile_id}: " + "; ".join(reasons) + if user_stack_str: + reason_str += f"\nUser stack trace:\n{user_stack_str}" + return strip_local_scope(reason_str) + + +def get_guard_fail_reason( + guard_manager: GuardManagerWrapper, + code: types.CodeType, + f_locals: dict[str, object], + compile_id: CompileId, + backend: Callable[..., object], + skip_logging: bool = False, +) -> str: + if isinstance(guard_manager, DeletedGuardManagerWrapper): + return f"{compile_id}: {guard_manager.invalidation_reason}" + reason_str = get_guard_fail_reason_helper( + guard_manager, f_locals, compile_id, backend + ) + if skip_logging: + return reason_str + guard_failures[orig_code_map[code]].append(reason_str) + + try: + if guard_manager.guard_fail_fn is not None: + guard_manager.guard_fail_fn( + GuardFail(reason_str or "unknown reason", orig_code_map[code]) + ) + except Exception: + log.exception( + "Failure in guard_fail_fn callback - raising here will cause a NULL Error on guard eval", + ) + + return reason_str + + +def get_and_maybe_log_recompilation_reasons( + cache_entries: list[CacheEntry], + frame: DynamoFrameType, + backend: Callable[..., object], + skip_logging: bool = False, +) -> list[str]: + """ + Return the list of guard failure reasons using cache entries. + Logs the recompilation reason if `recompiles` logging is enabled. + Raises a RecompileError if `config.error_on_recompile` is enabled. + """ + # pyrefly: ignore [implicit-any] + reasons = [] + for cache_entry in cache_entries: + reason = get_guard_fail_reason( + cache_entry.guard_manager, + cache_entry.code, + frame.f_locals, + cache_entry.compile_id, + backend, + skip_logging, + ) + if reason: + reasons.append(reason) + + code = frame.f_code + + if skip_logging: + return reasons + # at least one of "recompiles" or "recompiles_verbose" is enabled + do_recompiles_log = is_recompiles_enabled() or is_recompiles_verbose_enabled() + + if do_recompiles_log or config.error_on_recompile: + if is_recompiles_verbose_enabled(): + failures = "\n\n".join( + f"guard {i} failures:\n" + textwrap.indent(reason, "- ") + for i, reason in enumerate(reasons) + ) + else: + failures = textwrap.indent("\n".join(reasons), "- ") + guard_failure_details = ( + f"triggered by the following guard failure(s):\n{failures}" + ) + message = ( + f"Recompiling function {code.co_name} in {code.co_filename}:{code.co_firstlineno}\n" + f"{textwrap.indent(guard_failure_details, ' ')}" + ) + if do_recompiles_log: + if is_recompiles_verbose_enabled(): + recompiles_verbose_log.debug(message) + else: + recompiles_log.debug(message) + if config.error_on_recompile: + raise exc.RecompileError(message) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "recompile_reasons", + "encoding": "json", + }, + payload_fn=lambda: reasons[0] if len(reasons) == 1 else reasons, + ) + + return reasons + + +def update_diff_guard_managers_for_existing_cache_entries( + cache_entries: list[CacheEntry], +) -> OrderedSet[str]: + # On the first pass, go through the cache entries and accumulate the diff + # guard sources. Different guard managers can fail with different sources. + # So, we collect all of them first. + acc_diff_guard_sources: OrderedSet[str] = OrderedSet() + for cache_entry in cache_entries: + acc_diff_guard_sources.update( + cache_entry.guard_manager.collect_diff_guard_sources() + ) + + # On the second pass, set the diff_guard_sources for each cache line to the + # accumulated value. And the re-populate the diff guard manager. + for cache_entry in cache_entries: + cache_entry.guard_manager.diff_guard_sources = acc_diff_guard_sources + cache_entry.guard_manager.populate_diff_guard_manager() + + # return the accumulated sources to set up the new cache line. + return acc_diff_guard_sources + + +def guard_error_hook( + guard_manager: GuardFn, + code: types.CodeType, + f_locals: dict[str, object], + index: int, + last: bool, +) -> None: + print( + f"ERROR RUNNING GUARDS {code.co_name} {code.co_filename}:{code.co_firstlineno}" + ) + print("lambda " + ", ".join(guard_manager.args) + ":") + print(" ", " and\n ".join(guard_manager.code_parts)) + + print(guard_manager) + + local_scope = {"L": f_locals, **guard_manager.closure_vars} + for guard in guard_manager.code_parts: + try: + eval(guard, guard_manager.global_scope, local_scope) + except: # noqa: E722 + print(f"Malformed guard:\n{guard}") + + +set_guard_error_hook(guard_error_hook) + + +def unique(seq: Sequence[T]) -> Generator[T, None, None]: + seen = set() + for x in seq: + if x not in seen: + yield x + seen.add(x) + + +def make_dupe_guard( + obj_source: Source, dupe_source: Source | None +) -> functools.partial[Any] | None: + # Note - we may end up in a situation where we invoke something like + # def fn(x, y) + # with fn(x, x) + # Prior to the addition of tracking to all relevant objects, we would handle this just fine by + # eagerly re-entering VB and rewrapping inputs, correctly creating graphargs and placeholders. However, + # with tracking on inputs, duplicate inputs or aliased relationships may end up getting erased here - + # In the fn(x, x) example call above look like a graph with a single input. + # In order to ensure that we do not reuse fn(x, x) for fn(x, y), we create a duplicate input guard. + + # Note - we may not have a source, that is fine, it just means we had an object that is safe to have + # leave unsourced - like a local list created and discharged entirely within a local scope. + if dupe_source and dupe_source != obj_source: + ser_source_is_local = is_from_local_source(dupe_source) + source_is_local = is_from_local_source(obj_source) + if is_from_flatten_script_object_source( + dupe_source + ) or is_from_flatten_script_object_source(obj_source): + raise exc.UnsafeScriptObjectError( + f"{obj_source.name} is aliasing {dupe_source.name}. This is not supported." + f" Please do a clone for corresponding input." + ) + + # Note - both must be local, or global, or we will run afoul of a lack of merging in how we currently + # reconcile guards builder scopes in compile_check_fn. This technically means we miss a guard here, + # so maybe we should do this refactor before we land this... + # TODO(voz): Combine local and global guard builders. + if ser_source_is_local == source_is_local: + # Note - this is a little aggressive - these being duplicate input does not always matter. + # However, this should always be a sound guard to add here. + return functools.partial(GuardBuilder.DUPLICATE_INPUT, source_b=dupe_source) + return None + + +def install_guard(*guards: Guard, skip: int = 0) -> None: + """ + Add dynamo guards to the current tracing context. + + Args: + guards: guard(s) to add + skip: number of stack frames to ignore for debug stack trace + """ + from torch._guards import TracingContext + + guards_context = TracingContext.get().guards_context + if guards_context.skip_install: + return + + collect_debug_stack = guards_log.isEnabledFor( + logging.DEBUG + ) or verbose_guards_log.isEnabledFor(logging.DEBUG) + add = guards_context.dynamo_guards.add + for guard in guards: + if not isinstance(guard, Guard): + raise AssertionError(f"Expected Guard, got {type(guard)}") + if is_from_skip_guard_source(guard.originating_source): + continue + add(guard, collect_debug_stack=collect_debug_stack, skip=skip + 1) + + +# --------------------------------------------------------------------------- +# Guard check spec dispatch table — built by scanning GuardBuilder methods +# for the guard_check_spec attribute set by the decorators above. +GUARD_VALUE_DISPATCH: dict[str, GuardCheckSpec | object] = { + name: handler + for name in dir(GuardBuilder) + if (handler := getattr(getattr(GuardBuilder, name), "guard_check_spec", None)) + is not None +} + +# Validate that every guard method has an explicit guard_check_spec. +# Guard methods are identified by: uppercase name, callable, and first +# non-self parameter is 'guard'. +MISSING_GUARD_SPECS = [ + _name + for _name in dir(GuardBuilder) + if _name[0].isupper() + and not _name.startswith("_") + and callable(_method := getattr(GuardBuilder, _name, None)) + and len(_params := list(inspect.signature(_method).parameters)) >= 2 + and _params[1] == "guard" + and not hasattr(_method, "guard_check_spec") +] +if MISSING_GUARD_SPECS: + raise RuntimeError( + f"GuardBuilder methods missing guard_check_spec decorator: " + f"{', '.join(MISSING_GUARD_SPECS)}. Use @register_guard_check_spec, " + f"@skip_guard_check_spec, or @unsupported_guard_check_spec." + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/hooks.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..a3074f5916592807c9d7d503f310e61a9868d5b4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/hooks.py @@ -0,0 +1,26 @@ +"""Hook system for Dynamo's guard functionality. + +This module provides a way to register callback functions that are triggered during +guard-related operations. + +The Hooks class manages two types of hook functions: +- guard_export_fn: Called when guards need to be exported, taking a GuardsSet as input +- guard_fail_fn: Called when a guard check fails, taking a GuardFail object as input +These hooks enable customization of guard export and failure handling behaviors. +""" + +import dataclasses +from collections.abc import Callable, Sequence + +from torch._guards import GuardsSet + +from .types import GuardFail, GuardFilterEntry + + +@dataclasses.dataclass +class Hooks: + guard_export_fn: Callable[[GuardsSet], None] | None = None + guard_fail_fn: Callable[[GuardFail], None] | None = None + guard_filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] | None = ( + None + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/logging.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..74862962adaa10f294408fd8dbe172dcdc71d743 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/logging.py @@ -0,0 +1,73 @@ +"""Logging utilities for Dynamo and Inductor. + +This module provides specialized logging functionality including: +- Step-based logging that prepends step numbers to log messages +- Progress bar management for compilation phases +- Centralized logger management for Dynamo and Inductor components + +The logging system helps track the progress of compilation phases and provides structured +logging output for debugging and monitoring. +""" + +import itertools +import logging +from collections.abc import Callable +from typing import Any + +from torch.hub import _Faketqdm, tqdm + + +# Disable progress bar by default, not in dynamo config because otherwise get a circular import +disable_progress = True + + +# Return all loggers that torchdynamo/torchinductor is responsible for +def get_loggers() -> list[logging.Logger]: + return [ + logging.getLogger("torch.fx.experimental.symbolic_shapes"), + logging.getLogger("torch._dynamo"), + logging.getLogger("torch._inductor"), + ] + + +# Creates a logging function that logs a message with a step # prepended. +# get_step_logger should be lazily called (i.e. at runtime, not at module-load time) +# so that step numbers are initialized properly. e.g.: + +# @functools.cache +# def _step_logger(): +# return get_step_logger(logging.getLogger(...)) + +# def fn(): +# _step_logger()(logging.INFO, "msg") + +_step_counter = itertools.count(1) + +# Update num_steps if more phases are added: Dynamo, AOT, Backend +# This is very inductor centric +# _inductor.utils.has_triton() gives a circular import error here + +if not disable_progress: + try: + import triton # noqa: F401 + + num_steps = 3 + except ImportError: + num_steps = 2 + pbar = tqdm(total=num_steps, desc="torch.compile()", delay=0) + + +def get_step_logger(logger: logging.Logger) -> Callable[..., None]: + if not disable_progress: + pbar.update(1) + if not isinstance(pbar, _Faketqdm): + pbar.set_postfix_str(f"{logger.name}") + + step = next(_step_counter) + + def log(level: int, msg: str, **kwargs: Any) -> None: + if "stacklevel" not in kwargs: + kwargs["stacklevel"] = 2 + logger.log(level, "Step %s: %s", step, msg, **kwargs) + + return log diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/metrics_context.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/metrics_context.py new file mode 100644 index 0000000000000000000000000000000000000000..db17f21ee5cc7d5a8d6504c5c77148b63cc6192e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/metrics_context.py @@ -0,0 +1,252 @@ +"""Metrics collection and management system for Dynamo. + +This module provides context managers for gathering and reporting metrics during +compilation and runtime. + +It includes two main components: +- MetricsContext: A context manager for collecting metrics during compilation, supporting + nested contexts and various metric types (counters, sets, key-value pairs) +- RuntimeMetricsContext: A specialized context for runtime metrics collection that doesn't + require explicit context management + +The metrics system enables comprehensive monitoring and analysis of both compilation and +execution performance. +""" + +from __future__ import annotations + +import heapq +import logging +import time +from collections.abc import Callable +from typing import Any, TYPE_CHECKING, TypeAlias +from typing_extensions import Self + + +if TYPE_CHECKING: + from collections.abc import Iterator + +from torch.utils._traceback import CapturedTraceback + + +log = logging.getLogger(__name__) + + +class TopN: + """ + Helper to record a list of metrics, keeping only the top N "most expensive" elements. + """ + + def __init__(self, at_most: int = 25) -> None: + self.at_most = at_most + self.heap: list[tuple[int, Any]] = [] + + def add(self, key: Any, val: int) -> None: + # Push if we haven't reached the max size, else push and pop the smallest + fn = heapq.heappush if len(self.heap) < self.at_most else heapq.heappushpop + fn(self.heap, (val, key)) + + def __len__(self) -> int: + return len(self.heap) + + def __iter__(self) -> Iterator[tuple[Any, int]]: + return ((key, val) for val, key in sorted(self.heap, reverse=True)) + + +OnExitType: TypeAlias = Callable[ + [int, int, dict[str, Any], type[BaseException] | None, BaseException | None], + None, +] + + +class MetricsContext: + def __init__(self, on_exit: OnExitType) -> None: + """ + Use this class as a contextmanager to create a context under which to accumulate + a set of metrics, e.g., metrics gathered during a compilation. On exit of the + contextmanager, call the provided 'on_exit' function and pass a dictionary of + all metrics set during the lifetime of the contextmanager. + """ + self._on_exit = on_exit + self._metrics: dict[str, Any] = {} + self._start_time_ns: int = 0 + self._level: int = 0 + self._edits: list[tuple[CapturedTraceback, set[str]]] = [] + + def __enter__(self) -> Self: + """ + Initialize metrics recording. + """ + if self._level == 0: + # In case of recursion, track at the outermost context. + self._metrics = {} + self._start_time_ns = time.time_ns() + + self._level += 1 + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + _traceback: Any, + ) -> None: + """ + At exit, call the provided on_exit function. + """ + self._level -= 1 + if self._level < 0: + raise AssertionError("MetricsContext level cannot become negative") + if self._level == 0: + try: + end_time_ns = time.time_ns() + self._on_exit( + self._start_time_ns, end_time_ns, self._metrics, exc_type, exc_value + ) + except Exception: + log.exception("Unexpected exception logging compilation metrics") + + def in_progress(self) -> bool: + """ + True if we've entered the context. + """ + return self._level > 0 + + def increment(self, metric: str, value: int) -> None: + """ + Increment a metric by a given amount. + """ + if self._level == 0: + raise RuntimeError(f"Cannot increment {metric} outside of a MetricsContext") + if metric not in self._metrics: + self._metrics[metric] = 0 + self._metrics[metric] += value + + def _render_edits(self, pred: set[str]) -> str: + return "\n\n" + "\n\n".join( + "Previous Traceback:\n" + "".join(e.format()) + for e, k in self._edits + if k & pred + ) + + def set(self, metric: str, value: Any, overwrite: bool = False) -> None: + """ + Set a metric to a given value. Raises if the metric has been assigned previously + in the current context. + """ + if self._level == 0: + raise RuntimeError(f"Cannot set {metric} outside of a MetricsContext") + if metric in self._metrics and not overwrite: + raise RuntimeError( + self._render_edits({metric}) + + f"\n\nRuntimeError: Metric '{metric}' has already been set in the current context " + "(see above for current and previous traceback)." + ) + self._edits.append((CapturedTraceback.extract(skip=1), {metric})) + self._metrics[metric] = value + + def set_key_value(self, metric: str, key: str, value: Any) -> None: + """ + Treats a given metric as a dictionary and set the k and value within it. + Note that the metric must be a dictionary or not present. + + We allow this to be called multiple times (i.e. for features, it's not uncommon + for them to be used multiple times within a single compilation). + """ + if self._level == 0: + raise RuntimeError(f"Cannot set {metric} outside of a MetricsContext") + if metric not in self._metrics: + self._metrics[metric] = {} + self._metrics[metric][key] = value + + def update(self, values: dict[str, Any], overwrite: bool = False) -> None: + """ + Set multiple metrics directly. This method does NOT increment. Raises if any + metric has been assigned previously in the current context and overwrite is + not set to True. + """ + if self._level == 0: + raise RuntimeError("Cannot update metrics outside of a MetricsContext") + existing = self._metrics.keys() & values.keys() + if existing and not overwrite: + raise RuntimeError( + self._render_edits(set(values.keys())) + + f"\n\nRuntimeError: Metric(s) {existing} have already been set in the current context. " + "(see above for current and previous traceback)." + ) + self._edits.append((CapturedTraceback.extract(skip=1), set(values.keys()))) + self._metrics.update(values) + + def update_outer(self, values: dict[str, Any]) -> None: + """ + Update, but only when at the outermost context. + """ + if self._level == 0: + raise RuntimeError("Cannot update metrics outside of a MetricsContext") + if self._level == 1: + self.update(values) + + def add_to_set(self, metric: str, value: Any) -> None: + """ + Records a metric as a set() of values. + """ + if self._level == 0: + raise RuntimeError(f"Cannot add {metric} outside of a MetricsContext") + if metric not in self._metrics: + self._metrics[metric] = set() + self._metrics[metric].add(value) + + def add_top_n(self, metric: str, key: Any, val: int) -> None: + """ + Records a metric as a TopN set of values. + """ + if self._level == 0: + return + if metric not in self._metrics: + self._metrics[metric] = TopN() + self._metrics[metric].add(key, val) + + +class RuntimeMetricsContext: + def __init__(self, on_exit: OnExitType) -> None: + """ + Similar to MetricsContext, but used to gather the runtime metrics that are + decoupled from compilation, where there's not a natural place to insert a + context manager. + """ + self._on_exit = on_exit + self._metrics: dict[str, Any] = {} + self._start_time_ns: int = 0 + + def increment( + self, metric: str, value: int, extra: dict[str, Any] | None = None + ) -> None: + """ + Increment a metric by a given amount. + """ + if not self._metrics: + # Start timing on the first entry + self._start_time_ns = time.time_ns() + if metric not in self._metrics: + self._metrics[metric] = 0 + self._metrics[metric] += value + + if extra: + for k, v in extra.items(): + if k not in self._metrics and v is not None: + self._metrics[k] = v + + def finish(self) -> None: + """ + Call the on_exit function with the metrics gathered so far and reset. + """ + if self._metrics: + try: + end_time_ns = time.time_ns() + self._on_exit( + self._start_time_ns, end_time_ns, self._metrics, None, None + ) + except Exception: + log.exception("Unexpected exception logging runtime metrics") + finally: + self._metrics = {} diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/mutation_guard.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/mutation_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..5e4f6abbe066057146231c3d243639446cdf4a0a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/mutation_guard.py @@ -0,0 +1,162 @@ +"""Mutation tracking and dynamic module detection system for Dynamo. + +This module provides mechanisms to track and respond to mutations in PyTorch modules +and detect dynamically created or modified modules. + +Key components: +- MutationTracker: Tracks mutations to objects and invalidates associated cached code +- GenerationTracker: Tracks module creation timing to identify dynamic instances +- Patching system for nn.Module to detect mutations and dynamic creation + +The system ensures that Dynamo's optimizations remain valid by detecting and responding +to runtime changes in module state and structure. +""" + +import functools +import inspect +import weakref +from collections.abc import MutableMapping +from typing import Any + +import torch.nn +from torch.nn import Module + +from . import config +from .utils import ExactWeakKeyDictionary, nn_module_has_global_hooks + + +unpatched_nn_module_init = torch.nn.Module.__init__ + + +class MutationTracker: + db: ExactWeakKeyDictionary = ExactWeakKeyDictionary() + + def __init__(self) -> None: + self.mutation_count: int = 0 + self.watchers: list[weakref.ReferenceType[Any]] = [] + + def on_mutation(self, name: str) -> None: + self.mutation_count += 1 + tmp = self.watchers + self.watchers = [] + for ref in tmp: + guarded = ref() + if guarded is not None: + guarded.invalidate(ref) + + def track(self, guarded_code: Any) -> None: + self.watchers.append(weakref.ref(guarded_code)) + + +def watch(obj: Any, guarded_code: Any) -> None: + """invalidate guarded_code when obj is mutated""" + ensure_patched(type(obj)) + + if obj not in MutationTracker.db: + MutationTracker.db[obj] = MutationTracker() + tracker = MutationTracker.db[obj] + tracker.track(guarded_code) + + +def ensure_patched(cls: Any) -> None: + if getattr(cls, "___needs_mutation_patch", True): + cls.___needs_mutation_patch = False + original_setattr = cls.__setattr__ + + @functools.wraps(original_setattr) + def custom_setattr(self: Any, key: str, value: Any) -> None: + try: + MutationTracker.db[self].on_mutation(key) + except KeyError: + pass + return original_setattr(self, key, value) + + cls.__setattr__ = custom_setattr + + +class GenerationTracker: + generation: int = 0 + dynamic_classes: ExactWeakKeyDictionary = ExactWeakKeyDictionary() + generation_values: ExactWeakKeyDictionary = ExactWeakKeyDictionary() + + @classmethod + def tag(cls, obj: Any) -> None: + cls.generation_values[obj] = cls.generation + + @staticmethod + def mark_class_dynamic(cls: type[torch.nn.Module]) -> None: + if not issubclass(cls, torch.nn.Module): + raise AssertionError(f"Expected a torch.nn.Module subclass, got {cls}") + GenerationTracker.dynamic_classes[cls] = True + + @classmethod + def get_generation_value(cls, obj: Any) -> int: + if obj not in cls.generation_values: + return -1 + return cls.generation_values[obj] + + @classmethod + def check(cls, obj: Any) -> bool: + return ( + obj in cls.generation_values + and cls.generation_values[obj] == cls.generation + ) + + @classmethod + def clear(cls) -> None: + cls.generation = 0 + cls.dynamic_classes = ExactWeakKeyDictionary() + cls.generation_values = ExactWeakKeyDictionary() + + +def is_dynamic_nn_module(obj: Any, is_export: bool) -> bool: + """Check for nn.Modules() created dynamically or mutated""" + if isinstance(obj, torch.nn.Module) and ( + "forward" in obj.__dict__ or isinstance(obj, (dict, MutableMapping)) + ): + # A monkey patched `.forward` indicates something wacky is going on + # Similarly a nn module also subclassed as a dict is unusual. + return True + try: + return inspect.getattr_static(obj, "torchdynamo_force_dynamic") + except AttributeError: + pass + if isinstance(obj, torch.nn.Module) and ( + not is_export or config.install_free_tensors + ): + return True + + if isinstance(obj, torch.nn.Module) and nn_module_has_global_hooks(): + return True + dyn = GenerationTracker.dynamic_classes.get(type(obj)) or GenerationTracker.check( + obj + ) + return dyn + + +def install_generation_tagging_init() -> None: + """ + Monkey patch torch.nn.Module.__init__ and torch.nn.Module.__setstate__ + so we can detect nn.Module instances created dynamically inside forward methods. + """ + + if getattr(Module, "___needs_generation_tag_patch", True): + init = Module.__init__ + + def patched_init(self: Module, *args: Any, **kwargs: Any) -> None: + init(self, *args, **kwargs) + GenerationTracker.tag(self) + + Module.__init__ = patched_init # type: ignore[method-assign] + + setstate = Module.__setstate__ + + def patched_setstate(self: Module, state: Any) -> None: + setstate(self, state) + GenerationTracker.tag(self) + + Module.__setstate__ = patched_setstate # type: ignore[method-assign] + + Module.___needs_generation_tag_patch = False # type: ignore[attr-defined] + + GenerationTracker.generation += 1 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/output_graph.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/output_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..b46ab6ae4b3608510fb542b413550ed1dfd90cbd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/output_graph.py @@ -0,0 +1,4861 @@ +""" +Core graph building functionality for PyTorch's Dynamo system. This module contains +the essential components for constructing and managing FX graphs during compilation: + +- OutputGraph: Manages the overall graph construction and compilation process. It owns + a SubgraphTracer and handles graph compilation, execution, and state management. + OutputGraph also manages features like graph deduplication, symbolic shape handling, + and tracking of side effects. + +- SubgraphTracer: Handles the actual FX graph construction by tracing Python code. + It supports advanced features like higher-order operators through nested tracers, + lifting of free variables, and handling of symbolic shapes. + +The module supports key Dynamo features including: +- Higher-order operators through nested SubgraphTracers +- Graph deduplication for optimization +- Symbolic shape handling and propagation +- Side effect tracking and management +- Guard insertion and management +""" + +import collections +import contextlib +import copy +import dataclasses +import functools +import inspect +import itertools +import logging +import operator +import re +import sys +import time +import traceback +import types +import warnings +import weakref +from collections.abc import Callable, Generator, Sequence +from dataclasses import dataclass, field as dc_field +from types import CodeType +from typing import ( + Any, + cast, + Literal, + NamedTuple, + Optional, + TYPE_CHECKING, + TypedDict, + Union, +) +from typing_extensions import NotRequired, ParamSpec, TypeVar + +import sympy + +import torch._guards +import torch._logging +import torch.distributed as dist +import torch.nn +import torch.utils._pytree as pytree +from torch import fx, Tensor +from torch._C._dynamo import guards +from torch._dynamo.exc import ShortenTraceback, TensorifyScalarRestartAnalysis +from torch._guards import ( + CompileContext, + CompileId, + GlobalContextCheckpointState, + Source, + tracing, + TracingContext, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch._subclasses.fake_tensor import FakeTensor +from torch._utils_internal import signpost_event +from torch.export.dynamic_shapes import _ConstraintTarget +from torch.fx._lazy_graph_module import _make_graph_module # type: ignore[attr-defined] +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.symbolic_shapes import ( + free_symbols, + guard_scalar, + is_symbolic, + ShapeEnv, + Specialization, + uninteresting_files, +) +from torch.fx.node import Target +from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from . import config, exc, logging as torchdynamo_logging, variables +from .backends.registry import CompiledFn, CompilerFn +from .bytecode_transformation import ( + create_binary_slice, + create_binary_subscr, + create_build_tuple, + create_call_function, + create_dup_top, + create_instruction, + create_load_const, + create_rot_n, + create_swap, + Instruction, + make_compiled_fn_name, + unique_id, +) +from .code_context import code_context +from .codegen import PyCodegen +from .current_scope_id import enter_new_scope +from .device_interface import get_interface_for_device +from .exc import ( + BackendCompilerFailed, + exceptions_allowed_to_be_fallback, + SkipFrame, + unimplemented, + unimplemented_with_warning, +) +from .graph_bytecode_inputs import has_user_objects, index_to_bytecode_constructor +from .graph_deduplication import apply_graph_deduplication +from .graph_id_filter import ( + get_backend_override_for_compile_id, + get_inductor_config_override_for_compile_id, +) +from .graph_region_tracker import GraphRegionTracker +from .guards import GuardBuilder, install_guard +from .mutation_guard import is_dynamic_nn_module +from .side_effects import AttributeMutationExisting, SideEffects, ValueMutationExisting +from .source import ( + _get_source_debug_name, + AttrSource, + BackwardStateSource, + ConstantSource, + DictGetItemSource, + GetItemSource, + GlobalStateSource, + is_constant_source, + is_from_local_source, + LocalSource, + NumpyTensorSource, + ParamBufferSource, + ShapeEnvSource, + SyntheticLocalSource, + TensorProperty, + TensorPropertySource, +) +from .utils import ( + _extract_tensor_dict, + _get_cudagraph_override, + checkpoint_params, + CleanupHook, + clone_inputs, + compilation_time_metrics, + count_calls, + counters, + dynamo_timed, + get_chromium_event_logger, + get_instruction_source_311, + get_locals_to_steal, + get_static_address_type, + get_unique_name_wrt, + graph_break_reasons, + increment_op_count, + istype, + lazy_format_graph_code, + LazyString, + nn_module_proxy, + same, + set_example_value, +) +from .variables.builder import ( + BackwardStateGraphArg, + GraphArg, + TrackedFake, + wrap_fx_proxy, +) +from .variables.ctx_manager import ContextWrappingVariable +from .variables.functions import ClosureConversionError, VariableTracker +from .variables.lists import BaseListVariable +from .variables.misc import NullVariable +from .variables.nn_module import NNModuleVariable +from .variables.tensor import ( + NumpyNdarrayVariable, + SymNodeVariable, + UnspecializedPythonVariable, +) +from .variables.torch_function import TensorWithTFOverrideVariable +from .variables.user_defined import UserDefinedDictVariable + + +if TYPE_CHECKING: + from torch._dynamo.dynamo_profiler import DynamoProfilerState + from torch._dynamo.package import CompilePackage + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.functions import LocalGeneratorObjectVariable + from torch._inductor import _CudagraphAnnotation + from torch.multiprocessing.reductions import StorageWeakRef + +log = logging.getLogger(__name__) +graph_tabular_log = torch._logging.getArtifactLogger(__name__, "graph") +graph_code_log = torch._logging.getArtifactLogger(__name__, "graph_code") +graph_sizes_log = torch._logging.getArtifactLogger(__name__, "graph_sizes") +trace_call_log = torch._logging.getArtifactLogger(__name__, "trace_call") + +RootGuardManager = guards.RootGuardManager + +TensorMetadataDim = int | torch.SymInt | None +TensorMetadataSequence = Sequence[TensorMetadataDim] +OutputReturnKind = Literal["graph_out", "input", "constant"] + + +class SizesStridesInfo(TypedDict): + size: TensorMetadataSequence + stride: TensorMetadataSequence + values_size: NotRequired[TensorMetadataSequence] + values_stride: NotRequired[TensorMetadataSequence] + + +class CodeOptions(TypedDict): + co_argcount: int + co_posonlyargcount: int + co_kwonlyargcount: int + co_nlocals: int + co_stacksize: int + co_flags: int + co_code: bytes + co_consts: tuple[object, ...] + co_names: tuple[str, ...] + co_varnames: tuple[str, ...] + co_filename: str + co_name: str + co_qualname: NotRequired[str] + co_firstlineno: int + co_linetable: bytes + co_exceptiontable: NotRequired[bytes] + co_freevars: tuple[str, ...] + co_cellvars: tuple[str, ...] + + +class OutputReturnInfo(NamedTuple): + kind: OutputReturnKind + value: object + + +# Capture fn pointer at import time +# This is to guard against trying to mark the iterated tensors +# as static in case user overrides fn ptr +og_module_named_buffers_fn_ptr = torch.nn.Module.named_buffers +og_module_named_parameters_fn_ptr = torch.nn.Module.named_parameters + + +def _wrap_with_inductor_config( + compiler_fn: Any, config_patches: dict[str, Any] +) -> Callable[..., Any]: + """ + Wrap a compiler function to apply inductor config patches during compilation. + + Passes config_patches as a keyword argument so that compile_fx can + propagate them to backward compilation via its inner_compile wrapping. + """ + + def wrapped(gm: Any, example_inputs: Any) -> Any: + return compiler_fn(gm, example_inputs, config_patches=config_patches) + + # Preserve function metadata for logging + wrapped.__name__ = getattr(compiler_fn, "__name__", "") + wrapped.__wrapped__ = compiler_fn # type: ignore[attr-defined] + return wrapped + + +@dataclass(frozen=True) +class AliasingInfo: + has_aliasing: bool + msg: str + + +@dataclass(frozen=True) +class MutationInfo: + has_mutation: bool + msg: str + mutated_input_indices: tuple[int, ...] = () + + +def collect_reachable_grad_fns( + tensors_with_sources: list[tuple[torch.Tensor, str | None]], + stop_at: set[torch.autograd.graph.Node] | None = None, +) -> set[torch.autograd.graph.Node]: + """Collect all grad_fns reachable from tensors' autograd graphs. + + Performs a DFS traversal and collects all visited grad_fns. + Optionally stops traversal nodes in stop_at set. This signals the + autograd.grad boundary. + + Args: + tensors_with_sources: List of (tensor, source_name) tuples to start search from. + stop_at: Optional set of grad_fns where traversal should stop (excluded from result). + + Returns: + Set of all reachable grad_fns. + """ + if stop_at is None: + stop_at = set() + + visited: set[torch.autograd.graph.Node] = set() + stack: list[torch.autograd.graph.Node] = [] + + for tensor, _ in tensors_with_sources: + if isinstance(tensor, torch.Tensor): + grad_fn = tensor.grad_fn + if grad_fn is not None: + stack.append(grad_fn) + + while stack: + node = stack.pop() + if node in visited: + continue + # Stop traversal at stop_at nodes and don't include them + # in consumed grad_fn list. + if node in stop_at: + continue + visited.add(node) + for next_fn, _ in node.next_functions: + if next_fn is not None: + stack.append(next_fn) + return visited + + +@functools.cache +def _step_logger() -> Any: + return torchdynamo_logging.get_step_logger(log) + + +@dataclass +class GraphCompileReason: + """Stores why a given output graph was compiled; i.e. what caused the graph break.""" + + reason: str + user_stack: list[traceback.FrameSummary] + + # Indicates if this was a graph break reason due to graph break. + graph_break: bool = True + + def __post_init__(self) -> None: + if self.graph_break: + graph_break_reasons.append(self) + + +def _get_gen_rand_values_fn(random_calls: Any) -> Callable[[], list[Any]]: + def _gen_rand_values() -> list[Any]: + return [fn(*args, **kwargs) for fn, args, kwargs in random_calls] + + return _gen_rand_values + + +class FakeRootModule(torch.nn.Module): + """Trick the constructor of fx.GraphModule""" + + def __init__(self, nn_modules: dict[str, torch.nn.Module]) -> None: + super().__init__() + for k, v in nn_modules.items(): + setattr(self, k, v) + + def __repr__(self) -> str: + return "FakeRootModule(...)" + + def add_nn_modules(self, nn_modules: dict[str, torch.nn.Module]) -> None: + for k, v in nn_modules.items(): + setattr(self, k, v) + + +class WrapperBackend: + def __init__(self, backend: CompilerFn) -> None: + self.backend: CompilerFn = backend + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> CompiledFn: + self.restore = checkpoint_params(gm) + self.gm = gm + copy_gm = copy.deepcopy(self.gm) + self.candidate = self.backend(copy_gm, example_inputs) + + if self.candidate is None or self.candidate is self.gm.forward: + return self.gm.forward + + if not config.verify_correctness: + return self.candidate + + # if verify_correctness=True + try: + correct = self.gm.forward(*clone_inputs(example_inputs)) + result = self.candidate(*clone_inputs(example_inputs)) + + # TODO: replace `same` function with the one in testing + if same(correct, result): + return self.candidate + + raise RuntimeError(f"incorrect results of backend {self}") + + except Exception: + log.exception("error in verify_correctness") + raise + finally: + self.restore() + + +Scope = dict[str, object] + + +@dataclass +class BytecodeTracingTimings: + """Accumulated wall-clock time (ns) for major components during Dynamo + bytecode tracing that are not related to variable trackers. Each field + is an int accumulator that gets bumped via ``time.time_ns()`` in the + corresponding hot-path wrapper. To add a new timer, add a field here + and wire up the wrapper in the relevant function.""" + + get_fake_value_ns: int = 0 + create_proxy_ns: int = 0 + wrap_to_fake_tensor_and_record_ns: int = 0 + variable_builder_call_ns: int = 0 + + def report_and_reset(self) -> None: + """Flush accumulated timings to the bytecode_tracing chromium event + and to compilation_time_metrics, then reset all counters.""" + chromium_log = get_chromium_event_logger() + # pyrefly: ignore [implicit-any] + event_data = {} + for f in dataclasses.fields(self): + ns_val = getattr(self, f.name) + if ns_val > 0: + key = f.name.removesuffix("_ns") + event_data[f"{key}_time_s"] = ns_val / 1e9 + compilation_time_metrics.setdefault(key, []).append(ns_val / 1e9) + setattr(self, f.name, 0) + if event_data: + chromium_log.try_add_event_data("bytecode_tracing", **event_data) + + +@dataclass +class OutputGraphGuardsState: + """ + A base class containing fields that are considered "persistent" when we + want to save all the important state for reconstrucing guards in a different + process. Normally we don't need to add states here, but we may have to when + the information is needed to serialize the guards, so the fields here are + supposed to be serializable as a requirement. + """ + + local_scope: Scope + global_scope: Scope + # This records the initial torch function mode stack for guarding + torch_function_mode_stack: list[torch.overrides.TorchFunctionMode] + guard_on_key_order: set[Source] + # Map from graph input's `Source` to sizes / strides metadata + input_source_to_sizes_strides: dict[Source, SizesStridesInfo] + dual_level: int + functorch_layers: list[torch._functorch.pyfunctorch.FuncTorchInterpreter] + current_device: torch.device | None + global_state_guard: torch._C._dynamo.guards.GlobalStateGuard + _guards: torch._guards.GuardsSet + _aotautograd_guards: list[torch._guards.GuardEnvExpr] + + # Whether or not the guards should be checked for correctness + + export: bool = False + skip_guards_check: bool = False + export_constraints: bool = False + name_of_builtins_dict_key_in_fglobals: str | None = None + + @property + def shape_env(self) -> ShapeEnv: + raise AssertionError(f"shape_env shouldn't be accessed from {type(self)}") + + @property + def guards(self) -> torch._guards.GuardsSet: + return self._guards + + @property + def aotautograd_guards(self) -> list[torch._guards.GuardEnvExpr]: + return self._aotautograd_guards + + def dump_guards_state(self) -> "OutputGraphGuardsState": + # Dump a serializable version of self without extras + return OutputGraphGuardsState( + local_scope=self.local_scope, + global_scope=self.global_scope, + torch_function_mode_stack=self.torch_function_mode_stack, + guard_on_key_order=self.guard_on_key_order, + input_source_to_sizes_strides=self.input_source_to_sizes_strides, + dual_level=self.dual_level, + functorch_layers=self.functorch_layers, + current_device=self.current_device, + global_state_guard=self.global_state_guard, + name_of_builtins_dict_key_in_fglobals=self.name_of_builtins_dict_key_in_fglobals, + export=self.export, + export_constraints=self.export_constraints, + _guards=self.guards, + _aotautograd_guards=self.aotautograd_guards, + skip_guards_check=self.skip_guards_check, + ) + + +@dataclass +class StackLocalsMetadata: + """ + Stores metadata for a frame's stack and locals for the purposes of building resume functions + """ + + num_stack: int = 0 # number of stack elements, minus removed NULLs + locals_names: dict[str, int] = dc_field( + default_factory=dict + ) # order of locals codegen'd to the stack + stack_null_idxes: list[int] = dc_field(default_factory=list) + locals_null_keys: list[str] = dc_field(default_factory=list) + stack_ctx_args: list[tuple[int, tuple[object, ...]]] = dc_field( + default_factory=list + ) + stack_ctx_idxes_orig: list[int] = dc_field(default_factory=list) + locals_ctx_args: list[tuple[str, tuple[object, ...]]] = dc_field( + default_factory=list + ) + + +# TODO we should expand this to make it work for atribtrary in/out +@dataclass +class ExportMetaData: + # maps graph input index to its' source which is later + # used in export to map to correct user input. In its' flat form, + # just looks like GetItem(base=LocalSource("foo", idx=0)) + graph_input_idx_to_local_source: dict[int, Source | None] = dc_field( + default_factory=dict + ) + # maps user output idx to what type of output it is. There are 3 options: + # 1) graph out + # 2) user input + # 3) constants + output_return_type: dict[int, OutputReturnInfo] = dc_field(default_factory=dict) + # output spec of the traced function + out_spec: torch.utils._pytree.TreeSpec | torch.utils._pytree.LeafSpec = ( + torch.utils._pytree._LEAF_SPEC + ) + module_call_spec: dict[ + str, + dict[str, torch.utils._pytree.TreeSpec | torch.utils._pytree.LeafSpec], + ] = dc_field(default_factory=dict) + + +def _canonical_key(node: fx.Node, canonical_idx: dict[fx.Node, int]) -> object: + """Canonical heap key for Dynamo output graph nodes. + + Placeholders are sorted by grapharg source name; all other ops delegate + to the shared ``_canonical_node_key``. + """ + if node.op == "placeholder": + grapharg = node.meta.get("grapharg") + if grapharg is not None and grapharg.source is not None: + source_name = grapharg.source.name + else: + source_name = "" + return (0, source_name) + from torch.fx.passes.canonicalize import _canonical_node_key + + return _canonical_node_key(node, canonical_idx) + + +def _canonicalize_graph(graph: fx.Graph) -> None: + """Canonicalize a Dynamo output graph's node order and names. + + Delegates to ``torch.fx.passes.canonicalize.canonicalize_graph`` with + Dynamo-specific key generation and barrier detection. + """ + from torch.fx.passes.canonicalize import _is_safe_to_reorder, canonicalize_graph + + canonicalize_graph(graph, _canonical_key, _is_safe_to_reorder) + + +def get_builtins_dict(global_scope: Scope) -> dict[str, Any]: + # f_globals["__builtins__"] can be a dict or a module. This is an + # implementation detail - + # https://docs.python.org/3/library/builtins.html. + + # This makes guarding on any builtin messy because the guard check_fn + # has to check if the __builtins__ is a module or dict, and then access + # by either using getattr or getitem respectively. + + # To solve this problem, we insert a new entry in f_globals which points + # to the builtins __dict__ and then we guard any builtin on this dict. + # To avoid any collision with the pre-existing keys, we use the + # install_global to give us a unique dict key. + + f_builtins = global_scope["__builtins__"] + if not isinstance(f_builtins, dict): + f_builtins = f_builtins.__dict__ + return f_builtins + + +class OutputGraphCommon(OutputGraphGuardsState): + """ + A minimal interface for full graph capture. It is intended to be + the target of any tracer that feeds into backends. + + Currently dynamo's OutputGraph is the only known implementation + of this interface, used by (aot) precompile and (strict) export. + Importantly, that implementation also contains many other fields + that are using during tracing but not included in this interface + because they are not used once tracing is complete. + + It should be safe to assume that (caching) precompile also uses + this interface. + + In the future, we want make_fx, used by (non-strict) export, to + also implement this interface. + + The serializable part of this interface is OutputGraphGuardsState. + We do not need to serialize other parts; however it will pay to + be disciplined about what those other parts are, especially since + we want other tracers to be able to meaningfully implement them, + and we should generally try to cut them down when possible. + """ + + def __init__( + self, + output_graph_guards_state: OutputGraphGuardsState, + import_sources: dict[str, str] | None = None, + shape_env: ShapeEnv | None = None, + export_metadata: ExportMetaData | None = None, + tracked_fakes_id_to_source: dict[int, list[Source]] | None = None, + output_pycode: list[list[str] | None] | None = None, + ) -> None: + super().__init__( + output_graph_guards_state.local_scope, + output_graph_guards_state.global_scope, + output_graph_guards_state.torch_function_mode_stack, + output_graph_guards_state.guard_on_key_order, + output_graph_guards_state.input_source_to_sizes_strides, + output_graph_guards_state.dual_level, + output_graph_guards_state.functorch_layers, + output_graph_guards_state.current_device, + output_graph_guards_state.global_state_guard, + output_graph_guards_state._guards, + output_graph_guards_state._aotautograd_guards, + output_graph_guards_state.export, + output_graph_guards_state.skip_guards_check, + output_graph_guards_state.export_constraints, + output_graph_guards_state.name_of_builtins_dict_key_in_fglobals, + ) + + self.import_sources = import_sources or {} + # The following fields are currently known to be used by clients. + # In particular, we need: + # - shape_env, for building guards + # - export_metadata, for un/flattening inputs and outputs + # - tracked_fakes_id_to_source, for processing tensor dim constraints + self._shape_env = shape_env or ShapeEnv() # private for inheritance + self.export_metadata = export_metadata or ExportMetaData() + self.tracked_fakes_id_to_source: dict[int, list[Source]] = ( + tracked_fakes_id_to_source or {} + ) + self.output_pycode = output_pycode or [] + + @property + def shape_env(self) -> ShapeEnv: + return self._shape_env + + def bypass_package(self, reason: str = "", **kwargs: Any) -> None: + # NOTE: currently there are no tests for this but it is reachable + # when building guards, so technically necessary to include here. + # It is unclear whether we should include packaging altogether. + raise NotImplementedError + + +class OutputGraph(OutputGraphCommon): + """ + Wrapper class to hold outputs of InstructionTranslator. Mainly the + generated fx.Graph. + + OutputGraph is 1:1 with a frame being processed. Each frame is associated + with some root InstructionTranslator. When user code calls a function, + we construct a InliningInstructionTranslator that continues to write into + the root InstructionTranslator's OutputGraph. + """ + + side_effects: SideEffects + + def __init__( + self, + code_options: CodeOptions, + compiler_fn: CompilerFn | None, + root_tx: "InstructionTranslatorBase", + export: bool, + export_constraints: Sequence[_ConstraintTarget], + frame_state: Any, + local_scope: Scope, + global_scope: Scope, + f_code: CodeType, + torch_function_mode_stack: list[torch.overrides.TorchFunctionMode], + package: Optional["CompilePackage"], + one_graph: bool = False, + ) -> None: + OutputGraphGuardsState.__init__( + self, + local_scope, + global_scope, + torch_function_mode_stack, + guard_on_key_order=set(), + input_source_to_sizes_strides={}, + dual_level=torch.autograd.forward_ad._current_level, + functorch_layers=torch._functorch.pyfunctorch.retrieve_all_functorch_interpreters(), + current_device=torch.utils._device.CURRENT_DEVICE, + # initial_global_state is only None during NopTest. + global_state_guard=torch._dynamo.convert_frame.initial_global_state + or torch._C._dynamo.guards.GlobalStateGuard(), + # These are set by @property instead, just initialize them as blank + _guards=torch._guards.GuardsSet(), + _aotautograd_guards=[], + ) + self.tracers = [SubgraphTracer(self, is_export=export)] + # Map from graph input's `Source` to its `VariableTracker` to + # de-duplicate graph inputs by source and reuse the tracker + self.input_source_to_var: dict[Source, VariableTracker] = {} + # List of TensorVariables that are leaf tensors created in-graph + # (e.g., nn.Parameter via tracable_create_parameter). These need to be + # tracked separately from input_source_to_var for backward() auto-detection. + self.leaf_var_creation_order: list[VariableTracker] = [] + self.export = export + self.export_constraints = export_constraints # type: ignore[assignment] + self.frame_state = frame_state + self.cleanup_hooks: list[Callable[[], Any]] = [] + # compile_id is an id number for the current torch.compile + self.compile_id: int = next(_compile_id_counter) + # Set of globals installed via install_global* APIs + self.installed_globals: set[str] = set() + + # TODO: maybe should just pass the entire f_code in here? Not + # sure... + self.co_fields = { + "co_name": f_code.co_name, + "co_filename": f_code.co_filename, + "co_firstlineno": f_code.co_firstlineno, + } + + # The cudagraph annotation is normally set while tracing an + # `override_cudagraphs` context manager / decorator within this + # frame (see CudagraphOverrideVariable). Seed it here from any + # runtime-active override so a callee compiled as a separate frame + # (e.g. because it contains a graph break and cannot be inlined) + # inherits the override that lives lexically in a caller's frame. + # NOTE: we intentionally do not guard on the override state, so the + # override is sticky per code object (first compile wins): a function + # reached both inside and outside an override keeps whichever override + # was active when it first compiled. + self.cudagraph_annotation: _CudagraphAnnotation | None = None + if (_override := _get_cudagraph_override()) is not None: + from torch._inductor import _CudagraphAnnotation as _CGA + + self.cudagraph_annotation = _CGA(fwd=_override[0], bwd=_override[1]) + + self.region_tracker = GraphRegionTracker() + self._emit_debugger_breakpoint: bool = False + self._shallow_copy_placeholder_snapshots: dict[torch.fx.Node, torch.Tensor] = {} + + # tracked_fakes says where any tensor that was wrapped to fake came + # from. It is similar to GraphArg, in that all GraphArgs will get + # will get added to TrackedFakes, but TrackedFakes also contains + # GraphArgs that got pruned, and things like Tensor attributes which + # aren't explicit graph inputs. Used by shape guard + self.tracked_fakes: list[TrackedFake] = [] + + shape_env = ShapeEnv( + # Reference Cycle! + # Share a reference to the list of TrackedFake. + # + # ShapeEnv needs this in order to be able to reproduce the call + # to produce_guards at an arbitrary time point. That is because + # TrackedFake instances may have its metadata changed throughout + # the program execution. + tracked_fakes=self.tracked_fakes, + # We want to allow capture scalar outputs and allow_dynamic_output_shape_ops when fullgraph=True + allow_scalar_outputs=one_graph or config.capture_scalar_outputs, + allow_dynamic_output_shape_ops=one_graph + or config.capture_dynamic_output_shape_ops, + prefer_deferred_runtime_asserts_over_guards=config.prefer_deferred_runtime_asserts_over_guards, + co_fields=self.co_fields, + ) + + # In export mode, we force the shape_env to strictly disallow any constraining + # of the user marked dynamic dims + import torch._functorch.config as _config + + with _config.patch(fake_tensor_allow_unsafe_data_ptr_access=False): + fake_mode = torch._subclasses.FakeTensorMode( + shape_env=shape_env, + # TODO (tmanlaibaatar) Remove this once we always lift params and buffers + allow_non_fake_inputs=bool(self.export), + export=self.export, + ) + self.tracing_context: TracingContext = TracingContext(fake_mode) + self.tracing_context.traced_code.append(f_code) + self.tracing_context.cudagraph_annotation = self.cudagraph_annotation + self.traced_code = self.tracing_context.traced_code + self.dynamo_compile_id: CompileId | None = CompileContext.current_compile_id() + self.init_ambient_guards() + + # Wire ShapesSpec.assumptions BEFORE any input is processed. Each + # assumption is appended to `_shape_spec_pending_assumptions`; + if config._dynamic_shapes_spec is not None: + from torch.fx.experimental.symbolic_shapes import _wire_spec_assumptions + + _wire_spec_assumptions(self.shape_env, config._dynamic_shapes_spec) + + # Map each tensor id to a list of sources. This is necessary because + # tensor ids cannot be recovered from tracked fakes (in general). + # We use this map to interpret (i.e., check for violations of) constraints, + # specifically equality constraints, which have shared tensor ids in them. + # This map should also be generally useful, e.g., for (de)serialization. + self.tracked_fakes_id_to_source: dict[int, list[Source]] = ( + collections.defaultdict(list) + ) + # Stores the full fqn of a param or buffer to the relevant source. + self.param_name_to_source: dict[str, Source] | None = {} + self.side_effects = SideEffects(self) + # Generators created while tracing this frame. Tracked here (not on + # SideEffects) because SideEffects is cloned/swapped during HOP + # speculation and graph-break restore; the OutputGraph is the single + # instance that lives for the whole frame. Closed in compile_subgraph. + self.local_generators: list[LocalGeneratorObjectVariable] = [] + # Cached variable trackers. This makes symbolic analysis of LOAD_GLOBAL + # and LOAD_ATTR for same python objects free. + self.variable_tracker_cache: dict[Source, VariableTracker] = {} + # Cache for sources resolved via MRO walk, keyed by id(obj). + # When the same descriptor (e.g. property) is reached from multiple + # subclasses, we reuse the first source to avoid redundant guards. + # We thought of rolling this in variable_tracker_cache but here + # different sources point to the same object, we also don't want it to + # go through the side effects cache because even though these objects + # are same, we don't want OBJECT_ALIASING guards on them. For these + # objects, we have DICT_CONTAINS absent guards on the mro walk, so there + # is no need of the OBJECT_ALIASING guards. + self.mro_source_cache: dict[tuple[int, str], DictGetItemSource] = {} + # Tracks (id(klass), attr_name) pairs that already have a + # DICT_CONTAINS absent guard installed during MRO walks. When + # multiple subclasses share the same intermediate MRO class, we + # only need to guard the absence once per (class, attr) pair. + self.guarded_mro_absent_keys: set[tuple[int, str]] = set() + # Cache for inspect.signature results: function -> VariableTracker + self.signature_cache: dict[Any, VariableTracker] = {} + self.unique_var_id = itertools.count() + self.code_options: CodeOptions = cast(CodeOptions, dict(code_options)) + self.output_instructions: list[Instruction] = [] + self.output_pycode: list[list[str] | None] = [] + # used to track nodes that are added between calls of copy_graphstate + # and restore_graphstate + self.timestamp = 0 + + # Maps stream id (id(stream_value)) → user stack trace for input + # mutations on that stream. Used to error when an event records on a + # stream that already has an input mutation (the epilogue copy_() + # wouldn't be captured). We key by id() of the underlying + # torch.Stream so we can peek lazy variables without realizing them. + self._input_mutation_streams: dict[int, traceback.StackSummary] = {} + self._last_checked_input_versions: dict[int, int] | None = None + + # A list of register_finalizer_fns to apply to the output graph module + self.register_finalizer_fns: list[Callable[[fx.GraphModule], None]] = [] + + # Not checkpointed + self.compiler_fn: CompilerFn | None = compiler_fn + self.root_tx = root_tx + + # Profiler state for tracking function trace timings + self.profiler_state: DynamoProfilerState | None = None + + self.package = package + # Given a source, what are the user stacks of all locations that + # accessed it? + # + # For efficiency, we only populate this: + # - During export, and + # - If the source could potentially lead to a spurious export input + # + # Feel free to populate this more frequently if other use-cases arise, + # but be aware that we have to generate full stacks for each + # recording! + self.source_to_user_stacks: dict[Source, list[traceback.StackSummary]] = {} + + self._current_tx: list[InstructionTranslatorBase] = [] + self.cleanups: list[CleanupHook] = [] + self.should_exit = False + self.unspec_variable_map: dict[str, UnspecializedPythonVariable] = {} + + # This returns false if TF Overall (both mode and subclass) is disabled OR that TF Mode stack is empty + self.torch_function_mode_enabled = torch._C._is_torch_function_mode_enabled() + + # Used to wrap the compiled graph at runtime with + # DisableTorchFunctionSubclass to prevent double dispatch. + self.torch_function_subclass_inlined = False + + # Tracks if the output graph has a user defined allowed function in the + # graph. This is used later to determine if we should fallback to eager + # for certain exceptions. THe idea is that if the user has applied + # allow_in_graph, they would like to see the error instead of falling + # back for backend errors. + self.has_user_defined_allowed_in_graph = False + + # Tracks ALL grad_fn nodes that are consumed by torch.autograd.grad(outputs, inputs). + # This is the set of all nodes reachable from outputs' grad_fns, excluding inputs' grad_fns + # (since autograd.grad stops at inputs without consuming them). + # Used to detect returning tensors connected to consumed grad_fns (would cause + # "backward through graph a second time" error in aot_autograd). + self.autograd_grad_consumed_grad_fns: set[torch.autograd.graph.Node] = set() + + # Tracks a list of called ops that were not tagged with "pt2_compliant_tag". + # This information is useful for logging. + self.non_compliant_ops: set[torch._ops.OpOverload] = set({}) + + # Tracks a list of called custom ops that were tagged with "pt2_compliant_tag". + # This information is useful for logging. + self.compliant_custom_ops: set[torch._ops.OpOverload] = set({}) + + # We save the global torch state here to be restored in case of graph + # breaks. The relevant issue is seen here + # https://github.com/pytorch/pytorch/pull/100570#issuecomment-1543427086 + # where inlining of a function changes the global state (because of the + # presence of torch.no_grad) and there is a graph break. + self.save_global_state() + + # Tracks the original FQNs of the constant tensors from the original graph, + # i.e. buffers and parameters. + self.dynamo_flat_name_to_original_fqn: dict[str, str] = {} + + # All calls to random() are replaced with a single call to __gen_rand_values + # functions that returns a tuple of random values for each original call. + # random_calls tracks calls to random() and random_values_var stores the name of + # the variable that stores __gen_rand_values results. + self.random_calls: list[ + tuple[Callable[..., object], tuple[object, ...], dict[str, object]] + ] = [] + self.random_values_var: Any = None + + # Bytecode to insert right before we call the graph + self.pregraph_bytecode: list[Instruction] = [] + + # Maps SyntheticLocalSource → (fn, args, arg_sources) for hoisted + # graph inputs created by synthetic_graph_input, so invoke_subgraph + # reuse can recreate them on cache hit. arg_sources allows stamp-out + # to resolve new ctor arg values via source replacement. + self.synthetic_source_ctor_info: dict[ + SyntheticLocalSource, + tuple[ + Callable[..., Any], tuple[Any, ...], tuple[Source | None, ...] | None + ], + ] = {} + + # Use to pass values to backward hooks when using compiled autograd + self.backward_state: dict[str, VariableTracker] = {} + self.backward_state_proxy: torch.fx.Proxy | None = None + self.backward_state_var: str | None = None + + # pyrefly: ignore [bad-override] + self.name_of_builtins_dict_key_in_fglobals: str = ( + self.install_builtins_dict_in_fglobals() + ) + + self.compiler_trace_stack = contextlib.ExitStack() + + self.bytecode_tracing_timings = BytecodeTracingTimings() + + # These are the ambient, currently-global saved_tensor_hooks stashed in autograd, + # that are set for the entire duration of the compiled region. + # This is an invariant today because we graph break on the saved_tensor_hook + # context manager inside a compiled region + self.saved_tensors_hooks_subgraph_names: list[str] | None = ( + self.maybe_install_saved_tensors_hooks_subgraphs() + ) + + # mangled alias -> module fqn name + self.import_sources: dict[str, str] = {} + + self.export_metadata = ExportMetaData() + + # Set of inlined unspecialized modules names to generate the + # dynamo_flat_name_to_original_fqn mapping. + self.used_inlined_inbuilt_modules_names: OrderedSet[str] = OrderedSet() + + self.attr_source_cache: dict[tuple[Source, str], AttrSource] = {} + self._cached_replayed_side_effect_source_refs: tuple[str, ...] | None = None + + def track_generator(self, gen: "LocalGeneratorObjectVariable") -> None: + self.local_generators.append(gen) + + def close_local_generators(self, tx: "InstructionTranslatorBase") -> None: + from .symbolic_convert import temporarely_allow_writes_to_output_graph + + with temporarely_allow_writes_to_output_graph(tx): + for gen in list(self.local_generators): + gen.call_method(tx, "close", [], {}) + + def get_replayed_side_effect_source_refs( + self, *, populate_export_metadata: bool = False + ) -> list[str]: + """Return Python-side effect sources that Dynamo replays outside the FX graph.""" + if ( + not populate_export_metadata + and not self.side_effects.id_to_variable + and self._cached_replayed_side_effect_source_refs is not None + ): + return list(self._cached_replayed_side_effect_source_refs) + + from torch.export._trace import _ExportModuleSpecTrackerDict + + potential_side_effects = [] + for var in self.side_effects._get_modified_vars(): + if hasattr(var, "mutation_type"): + mut_type = var.mutation_type + # Skip codegen-specific mutations that never materialize as + # externally visible Python side effects. + if isinstance( + mut_type, (AttributeMutationExisting, ValueMutationExisting) + ): + if isinstance(var, UserDefinedDictVariable) and isinstance( + var.value, _ExportModuleSpecTrackerDict + ): + if populate_export_metadata: + if var._base_vt is None: + raise AssertionError("var._base_vt must not be None") + for ( + k, + v, + ) in ( + var._base_vt.items.items() # pyrefly: ignore[missing-attribute] + ): + # pyrefly: ignore [implicit-any] + specs = {} + # pyrefly: ignore[missing-attribute] + for k_spec, val in v.items.items(): + specs[k_spec.vt.as_python_constant()] = ( + val.as_python_constant() + ) + if ["in_spec", "out_spec"] != list(specs.keys()): + raise AssertionError( + f"Expected specs keys to be ['in_spec', 'out_spec'], got {list(specs.keys())}" + ) + self.export_metadata.module_call_spec[ + # pyrefly: ignore[missing-attribute] + k.vt.as_python_constant() + ] = specs + # export uses tracepoint pass to dump submodule inp/out spec + # into global state, so we filter it here + if not ( + isinstance(var, UserDefinedDictVariable) + and isinstance(var.value, _ExportModuleSpecTrackerDict) + ): + potential_side_effects.append(var) + + return [_get_source_debug_name(var.source) for var in potential_side_effects] + + def get_chained_attr_source(self, base: Source, path: str) -> AttrSource: + parts = path.split(".") + key = (base, parts[0]) + if key not in self.attr_source_cache: + self.attr_source_cache[key] = AttrSource(base, parts[0]) + result = self.attr_source_cache[key] + for part in parts[1:]: + key = (result, part) + if key not in self.attr_source_cache: + self.attr_source_cache[key] = AttrSource(result, part) + result = self.attr_source_cache[key] + return result + + def get_chained_param_buffer_source( + self, base: Source, path: str + ) -> "ParamBufferSource": + parts = path.rsplit(".", 1) + if len(parts) == 1: + return ParamBufferSource(base, path) + intermediate_base = self.get_chained_attr_source(base, parts[0]) + return ParamBufferSource(intermediate_base, parts[1]) + + def mark_bytecode_tracing_start(self) -> None: + self.compiler_trace_stack.enter_context( + dynamo_timed( + "bytecode_tracing", + log_pt2_compile_event=True, + ) + ) + # Start profiler timing for the root function + if config.dynamo_profiler: + from torch._dynamo.dynamo_profiler import DynamoProfilerState + + if self.profiler_state is None: + self.profiler_state = DynamoProfilerState() + code = self.root_tx.f_code + self.profiler_state.push( + code.co_name, + code.co_filename, + code.co_firstlineno, + time.time_ns(), + ) + + def mark_bytecode_tracing_stop(self) -> None: + self.bytecode_tracing_timings.report_and_reset() + self.compiler_trace_stack.close() + # Record profiler timing for the root function and dump stats + if config.dynamo_profiler and self.profiler_state is not None: + from torch._dynamo.dynamo_profiler import FunctionTraceTiming + + stack_entry = self.profiler_state.pop() + trace_end_ns = time.time_ns() + if stack_entry is not None: + cumtime_ns = trace_end_ns - stack_entry.start_time_ns + tottime_ns = cumtime_ns - stack_entry.child_time_ns + timing = FunctionTraceTiming( + func_name=stack_entry.func_name, + filename=stack_entry.filename, + firstlineno=stack_entry.firstlineno, + cumtime_ns=cumtime_ns, + tottime_ns=tottime_ns, + bytecode_count=len(self.root_tx.f_code.co_code), + inline_depth=0, + caller_func_name=None, + caller_filename=None, + caller_firstlineno=None, + is_primitive_call=stack_entry.is_primitive_call, + call_stack=(), + ) + self.profiler_state.record_timing(timing) + + # Dump profiler stats + output_file = None + if isinstance(config.dynamo_profiler, str): + output_file = config.dynamo_profiler + self.profiler_state.dump_stats(output_file) + + def install_builtins_dict_in_fglobals(self) -> str: + f_builtins = get_builtins_dict(self.global_scope) + return self.install_global("__builtins_dict__", f_builtins) + + def add_backward_state_hook( + self, hook: VariableTracker, prefix: str = "hook" + ) -> tuple[str, torch.fx.Proxy]: + name = f"{prefix}{len(self.backward_state)}" + if name in self.backward_state: + raise AssertionError( + f"backward_state hook name '{name}' already registered" + ) + self.backward_state[name] = hook + return name, self.get_backward_state_proxy() + + def get_backward_state_proxy(self) -> torch.fx.Proxy: + if self.backward_state_proxy is None: + if self.export: + unimplemented( + gb_type="backward_state does not support export", + context="", + explanation="Compiled autograd doesn't work with `torch.export`.", + hints=[], + ) + example_value = BackwardState() + self.backward_state_proxy = self.root_tracer.create_graph_input( + "dynamo_backward_state", + type(example_value), + example_value, + source=BackwardStateSource(), + ) + self.backward_state_proxy.node.meta["grapharg"] = BackwardStateGraphArg() + self.backward_state_var = self.new_var() + return self.backward_state_proxy + + # This gets its own helper function so guards DEBUG logs are more informative + def init_ambient_guards(self) -> None: + # Register a SHAPE_ENV guard to make sure we setup shape guards + # that show up in ShapeEnv + self.guards.add(ShapeEnvSource().make_guard(GuardBuilder.SHAPE_ENV)) + + self.guards.add( + GlobalStateSource().make_guard(GuardBuilder.DETERMINISTIC_ALGORITHMS) + ) + + self.guards.add(GlobalStateSource().make_guard(GuardBuilder.GRAD_MODE)) + + self.guards.add(GlobalStateSource().make_guard(GuardBuilder.DEFAULT_DEVICE)) + + self.guards.add(GlobalStateSource().make_guard(GuardBuilder.GLOBAL_STATE)) + self.guards.add( + GlobalStateSource().make_guard(GuardBuilder.TORCH_FUNCTION_STATE) + ) + + ci = torch._C._functorch.peek_interpreter_stack() + if ci is not None: + self.guards.add( + GlobalStateSource().make_guard(GuardBuilder.FUNCTORCH_STACK_MATCH) + ) + if not torch._dynamo.compiled_autograd.in_compiled_autograd_region: + self.guards.add( + GlobalStateSource().make_guard( + GuardBuilder.AUTOGRAD_SAVED_TENSORS_HOOKS + ) + ) + + def maybe_install_saved_tensors_hooks_subgraphs(self) -> list[str] | None: + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + return None + + get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks + are_inline_hooks = ( + torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable + ) + hooks = get_hooks() + if not are_inline_hooks(hooks): + return None + + # If GraphModule provided by user contains fx.wrap, + # We can only rely on user provided cache hash in this case. + # If user did not provide cache hash - then we always bypass cache. + + pack_gm, unpack_gm = hooks + pack_subgraph_name = self.install_subgraph( + "saved_tensors_hooks_pack", + torch.fx.GraphModule(self.nn_modules, pack_gm.graph), + ) + unpack_subgraph_name = self.install_subgraph( + "saved_tensors_hooks_unpack", + torch.fx.GraphModule(self.nn_modules, unpack_gm.graph), + ) + if pack_subgraph_name != "saved_tensors_hooks_pack_0": + raise AssertionError( + f"Expected pack_subgraph_name to be 'saved_tensors_hooks_pack_0', got '{pack_subgraph_name}'" + ) + if unpack_subgraph_name != "saved_tensors_hooks_unpack_0": + raise AssertionError( + f"Expected unpack_subgraph_name to be 'saved_tensors_hooks_unpack_0', got '{unpack_subgraph_name}'" + ) + return [pack_subgraph_name, unpack_subgraph_name] + + def synthetic_graph_input( + self, + fn: Callable[..., Any], + args: tuple[Any, ...], + ctor_arg_sources: tuple[Source | None, ...] | None = None, + ) -> VariableTracker: + """ + call fn(*args) before the graph runs and turn the result into a fake input. + """ + example_value = fn(*args) + varname = self.new_var() + cg = PyCodegen(self.root_tx) + cg.add_push_null( + lambda: cg.load_import_from( + fn.__module__, + fn.__name__, + ) + ) + if ctor_arg_sources: + cg.foreach( + src if src is not None else variables.ConstantVariable.create(val) + for val, src in zip(args, ctor_arg_sources) + ) + else: + cg.foreach(map(variables.ConstantVariable.create, args)) + cg.call_function(len(args), False) + cg.store(varname) + self.pregraph_bytecode.extend(cg.get_instructions()) + source = SyntheticLocalSource(varname) + self.synthetic_source_ctor_info[source] = (fn, args, ctor_arg_sources) + result = VariableTracker.build(self.root_tx, example_value, source) + # Realize the VT because we will delete the guards on it in the next line. + result = result.realize() + TracingContext.get().guards_context.dynamo_guards.remove_guards_with_source( + source + ) + return result + + def add_cleanup_hook(self, fn: Callable[[], Any]) -> None: + self.cleanup_hooks.append(fn) + + def call_cleanup_hooks(self) -> None: + for hook in reversed(self.cleanup_hooks): + hook() + self.cleanup_hooks.clear() + + @property + def root_tracer(self) -> "SubgraphTracer": + return self.tracers[0] + + @property + def current_tracer(self) -> "SubgraphTracer": + return self.tracers[-1] + + def is_root_tracer(self) -> bool: + # Helper to tell if we are inside the higher order operator tracing. + return len(self.tracers) == 1 + + def check_input_mutation_on_current_stream( + self, tx: "InstructionTranslatorBase" + ) -> None: + """Record which stream index has input mutations by comparing current + tensor versions against the versions captured at graph input creation.""" + if not hasattr(tx, "symbolic_stream_state"): + return + if not tx.symbolic_stream_state.in_stream_context(): + return + + tracer = self.root_tracer + if self._last_checked_input_versions is None: + self._last_checked_input_versions = dict( + enumerate(tracer._input_versions_at_beginning) + ) + + cur_stream_index = tx.symbolic_stream_state.cur_stream_id() + input_idx = 0 + for node in tracer.graph.nodes: + if node.op != "placeholder": + break + example_value = node.meta.get("example_value") + if not isinstance(example_value, torch.Tensor): + continue + prev_version = self._last_checked_input_versions.get(input_idx) + cur_version = example_value._version + if prev_version is not None and cur_version > prev_version: + if cur_stream_index not in self._input_mutation_streams: + self._input_mutation_streams[cur_stream_index] = ( + TracingContext.extract_stack() + ) + self._last_checked_input_versions[input_idx] = cur_version + input_idx += 1 + + _EVENT_INPUT_MUTATION_FIX = ( + "To fix this, either:\n" + " 1. Move the input mutation after the event.record() call.\n" + " 2. Record the event outside the compiled region:\n" + " compiled_fn(x)\n" + " event.record(stream) # after torch.compile returns\n" + " 3. Insert a graph break before recording:\n" + " torch._dynamo.graph_break()\n" + " event.record(stream)\n" + " 4. Record the event on a stream that has no input mutations." + ) + + def check_event_record_after_input_mutation(self, stream_index: int) -> None: + """Error if an event is being recorded on a stream that already has + an input mutation. Called at record time so ordering is naturally + respected — records before mutations won't trigger this.""" + if stream_index not in self._input_mutation_streams: + return + + mutation_stack = self._input_mutation_streams[stream_index] + record_stack = TracingContext.extract_stack() + + msg = ( + "An event was recorded on a stream where a graph input was " + "previously mutated. The input mutation is applied via copy_() " + "in the runtime epilogue after the graph executes, so the event " + "would not capture the mutation, leading to incorrect " + "synchronization.\n\n" + "Input mutation occurred here:\n" + f"{''.join(mutation_stack.format())}\n" + "Event record occurred here:\n" + f"{''.join(record_stack.format())}\n" + self._EVENT_INPUT_MUTATION_FIX + ) + raise RuntimeError(msg) + + @property + def graph(self) -> torch.fx.Graph: + return self.current_tracer.graph + + # TODO(rzou): can delete after we refactor speculate_subgraph to use nested GraphTracer. + @graph.setter + def graph(self, value: torch.fx.Graph) -> None: + self.current_tracer.graph = value + + @property + def input_name_to_proxy(self) -> dict[str, fx.Proxy]: + return self.current_tracer.input_name_to_proxy + + @property + def real_value_cache(self) -> dict[fx.Node, torch.Tensor]: + return self.current_tracer.real_value_cache + + @property + def bound_symbols(self) -> dict[sympy.Symbol, Union[torch.fx.Proxy, "LazyProxy"]]: + return self.current_tracer.bound_symbols + + # If you are here, and you're looking for create_graph_input, + # to avoid ambiguity, please call one of the following: + # - self.current_tracer.create_graph_input + # - self.root_tracer.create_graph_input + # See NOTE [HigherOrderOperator tracing design] for more context. + + def create_proxy(self, *args: Any, **kwargs: Any) -> torch.fx.Proxy: + return self.current_tracer.create_proxy(*args, **kwargs) + + def create_node(self, *args: Any, **kwargs: Any) -> torch.fx.Node: + return self.current_tracer.create_node(*args, **kwargs) + + def remove_node(self, *args: Any, **kwargs: Any) -> None: + return self.current_tracer.remove_node(*args, **kwargs) + + @contextlib.contextmanager + def subtracer( + self, + source_target: Target | None, + prior_tracer: Optional["SubgraphTracer"], + description: str | None = None, + ) -> Generator["SubgraphTracer", None, None]: + new_scope_ctx = enter_new_scope() + try: + if prior_tracer: + # Lineage MUST stay preserved + if prior_tracer.parent is not self.current_tracer: + raise AssertionError( + "prior_tracer.parent must be the current tracer to preserve lineage" + ) + new_scope_ctx.__enter__() + tracer = ( + prior_tracer + if prior_tracer + else SubgraphTracer( + self, + parent=self.current_tracer, + source_target=source_target, + is_export=self.current_tracer.is_export, + description=description, + ) + ) + self.tracers.append(tracer) + yield tracer + finally: + new_scope_ctx.__exit__(None, None, None) + self.tracers.pop() + + @property + def output(self) -> "OutputGraph": + return self + + @property + def fake_mode(self) -> torch._subclasses.FakeTensorMode: + if self.tracing_context.fake_mode is None: + raise AssertionError("tracing_context.fake_mode must not be None") + return self.tracing_context.fake_mode + + @property + def shape_env(self) -> ShapeEnv: + if self.tracing_context.fake_mode is None: + raise AssertionError("tracing_context.fake_mode must not be None") + if self.tracing_context.fake_mode.shape_env is None: + raise AssertionError("tracing_context.fake_mode.shape_env must not be None") + return self.tracing_context.fake_mode.shape_env + + @property + def guards(self) -> torch._guards.GuardsSet: + return self.tracing_context.guards_context.dynamo_guards + + @property + def nn_modules(self) -> dict[str, Any]: + return self.tracing_context.module_context.nn_modules + + @property + def aotautograd_guards(self) -> list[torch._guards.GuardEnvExpr]: + return self.tracing_context.guards_context.aotautograd_guards + + def save_global_state( + self, out: dict[str, tuple[Callable[..., Any], bool]] | None = None + ) -> None: + """ + Saves to out if it is provided. Else saves to the tracing context's global_state. + """ + global_state = cast( + dict[str, tuple[Callable[..., Any], bool]], + ( + out + if out is not None + else self.tracing_context.global_context.global_state + ), + ) + + global_state["grad_enabled"] = (torch.set_grad_enabled, torch.is_grad_enabled()) + + gpu_type = ( + acc.type if (acc := torch.accelerator.current_accelerator()) else "cuda" + ) + global_state["autocast_enabled"] = ( + functools.partial(torch.set_autocast_enabled, gpu_type), + torch.is_autocast_enabled(gpu_type), + ) + global_state["autocast_cpu_enabled"] = ( + functools.partial(torch.set_autocast_enabled, "cpu"), + torch.is_autocast_enabled("cpu"), + ) + global_state["autocast_gpu_dtype"] = ( # type:ignore[assignment] + functools.partial(torch.set_autocast_dtype, gpu_type), + torch.get_autocast_dtype(gpu_type), + ) + global_state["autocast_cpu_dtype"] = ( # type:ignore[assignment] + functools.partial(torch.set_autocast_dtype, "cpu"), + torch.get_autocast_dtype("cpu"), + ) + global_state["autocast_cache_enabled"] = ( + torch.set_autocast_cache_enabled, + torch.is_autocast_cache_enabled(), + ) + + def push_tx(self, tx: "InstructionTranslatorBase") -> None: + self._current_tx.append(tx) + + def pop_tx(self) -> "InstructionTranslatorBase": + return self._current_tx.pop() + + @property + def current_tx(self) -> "InstructionTranslatorBase": + return self.root_tx if not self._current_tx else self._current_tx[-1] + + def resolve_source_value(self, source: Source) -> Any: + """ + Resolve the runtime value a Source points to using root_tx's frame. + + Useful to inspect the python object associated with the source during + debugging. Will also be used by invoke subgraph caching later on. + """ + return source.get_value( + {"G": self.root_tx.f_globals, "L": self.root_tx.f_locals}, + {}, + {}, # type: ignore[arg-type] + ) + + def count_calls(self) -> int: + return count_calls(self.graph) + + def is_empty_graph(self) -> bool: + return len(list(self.graph.nodes)) == 0 + + def has_outputs(self) -> bool: + return len([x for x in self.graph.nodes if x.op == "output"]) > 0 + + def get_submodule(self, keys: str) -> torch.nn.Module | Any: + if not keys: + raise AssertionError("keys must be a non-empty string") + obj: torch.nn.Module | dict[str, torch.nn.Module] = self.nn_modules + for k in keys.split("."): + if isinstance(obj, dict): + obj = obj[k] + else: + obj = getattr(obj, k) + return obj + + def new_var(self, name: str = "tmp") -> str: + existing = set(self.code_options["co_varnames"]) + # In common case, this will be O(1) + while True: + var = f"{name}_{next(self.unique_var_id)}" + if var not in existing: + self.code_options["co_varnames"] += (var,) + return var + + def update_co_names(self, name: str) -> None: + """Ensure self.code_options.co_names contains name""" + if name not in self.code_options["co_names"]: + self.code_options["co_names"] += (name,) + + @staticmethod + def module_key_name(*names: Any) -> str: + # create a new unique name + name = "_".join(map(str, names)) + # Strip _buffers[..]/_parameters[..]/_modules[..] names + name = re.sub( + r"\._(?:modules|parameters|buffers)\[(['\"])([^'\"\]]+)\1\]", r".\2", name + ) + # Replace getattr(a, b) with a.b + name = re.sub( + r"getattr\(\s*([^,]+?)\s*,\s*(['\"])([^'\"]+)\2\s*\)", r"\1.\3", name + ) + # Strip the guard lookup L/G access + name = re.sub(r"^[GL]\['?(.*?)'?\]$", r"\1", name) + # e.g. replace abc.xyz[123].qkv with abc.xyz_123.qkv + name = re.sub(r"\[(\d+)\]", r"_\g<1>", name) + # e.g. replace abc.xyz_123.qkv with abc_xyz_123_qkv + name = re.sub(r"[^a-zA-Z0-9]", "_", name) + + if not name or not name[0].isalpha(): + name = "sub" + name + + return name + + def register_static_attr_and_return_proxy( + self, attr_prefix: str, attr_value: Any + ) -> fx.Proxy: + # Check if the module already exists, if it does, return the already + # added proxy. This is important for executorch tests. + if isinstance(attr_value, torch.nn.Module): + for name, mod in self.nn_modules.items(): + if mod is attr_value: + proxy = self.create_proxy("get_attr", name, (), {}) + return proxy + + attr_name = get_unique_name_wrt(attr_prefix, self.nn_modules) + # TODO `nn_modules` has been historically overloaded to store a lot more + # than just nn module objects, fix that. + self.nn_modules[attr_name] = attr_value + proxy = self.create_proxy("get_attr", attr_name, (), {}) + set_example_value(proxy.node, attr_value) + return proxy + + def register_attr_or_module( + self, + target: torch.nn.Module | torch.Tensor | Any, + *names: Any, + **options: Any, + ) -> VariableTracker: + if is_dynamic_nn_module(target, self.export): + # Instead of returning UnspecializedNNModuleVariable, call + # VariableTracker.build so that it is tracked for mutation. + return VariableTracker.build(self.current_tx, target, **options) + + options = dict(options) + if "source" not in options: + raise AssertionError("'source' must be provided in options") + source = options["source"] + if isinstance(source, ParamBufferSource): + raise AssertionError( + f"source must not be a ParamBufferSource, got {source}" + ) + + if isinstance(target, torch.Tensor): + tracer = self.current_tracer + if not self.is_root_tracer(): + # For higher order ops, we don't want to insert the get_attr in + # innermost graph. Instead, we want to raise the params/buffers + # as inputs to the higher-order graph, and register them as + # get_attrs in the root tracer. + + # Note that Dynamo will still call lift_tracked_freevar_to_input + # when these inputs are encountered for the inner graph. The + # only difference is what happens at the root tracer for + # nn.Parameters vs free inputs. The free inputs are registered + # as placeholders in the root graph, whereas the nn.Parameters + # are registered as get_attr nodes in the root graph. + tracer = self.root_tracer + + def wrap_name(module_key: str) -> VariableTracker: + if self.param_name_to_source is None: + raise AssertionError("param_name_to_source must not be None") + self.param_name_to_source[module_key] = source + + # Check if the attr has already been registered. This can happen + # when two different sources point to the same tensor. + if self.root_tx is None: + raise AssertionError("root_tx must not be None") + if target in self.root_tx.output.side_effects: + return self.root_tx.output.side_effects[target] + + if get_static_address_type(target) == "guarded" and not isinstance( + source, NumpyTensorSource + ): + install_guard(source.make_guard(GuardBuilder.ID_MATCH)) + elif not is_constant_source(source): + install_guard(source.make_guard(GuardBuilder.TENSOR_MATCH)) + + vt = wrap_fx_proxy( + self.root_tx, + tracer.create_proxy("get_attr", module_key, (), {}), + example_value=target, + **options, + ) + + # Track the object so to avoid duplicate registration in case of + # different sources pointing to the same tensor object. + vt = self.root_tx.output.side_effects.track_object_existing(target, vt) + + if "tensor_dict" in vt.as_proxy().node.meta: + raise AssertionError( + "'tensor_dict' already exists in proxy node meta" + ) + # pyrefly: ignore [bad-argument-type] + vt.as_proxy().node.meta["tensor_dict"] = _extract_tensor_dict(target) + + return vt + + elif isinstance(target, torch.nn.Module): + if not isinstance(target, torch.nn.Module): + raise AssertionError( + f"target must be a torch.nn.Module, got {type(target)}" + ) + + if source: + install_guard(source.make_guard(GuardBuilder.NN_MODULE)) + + def wrap_name(module_key: str) -> VariableTracker: + # pyrefly: ignore [bad-argument-type] + return NNModuleVariable(type(target), module_key, target, **options) + + else: + # This is Dynamo created graph module, e.g., graph module coming + # from higher order ops. NNModuleVariable tracker can't be + # sourceless, so let's return a unspecializedNNModule variable + # tracker. + def wrap_name(module_key: str) -> VariableTracker: + # pyrefly: ignore[bad-argument-type] + return variables.UnspecializedNNModuleVariable(target, **options) + + elif isinstance(target, (torch.SymInt, torch.SymFloat)): + # HACKY CODE REGION BEGIN + # WE ARE PIGGYBACKING ON EXISTING INFRA TO REGISTER ATTRS + # This ultimately gets written to self.nn_modules, which is unfortunate + # Attrs that are tensors and symints and such need to be migrated to have their + # own storage + # alas, this is like this for now + + def wrap_name(module_key: str) -> VariableTracker: + return SymNodeVariable.create( + self.root_tx, + self.create_proxy("get_attr", module_key, (), {}), + sym_num=target, + **options, + ) + + # HACKY CODE REGION END + elif is_custom_class(type(target)): + # HACKY CODE REGION BEGIN + # Same as SymInt/SymFloat above: piggybacking on self.nn_modules + # to store opaque objects as graph attributes. + + tracer = self.current_tracer + if not self.is_root_tracer(): + tracer = self.root_tracer + + def wrap_name(module_key: str) -> VariableTracker: + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + self.fake_mode, target + ) + proxy = tracer.create_proxy("get_attr", module_key, (), {}) + set_example_value(proxy.node, fake_script_obj) + return torch._dynamo.variables.script_object.CustomClassObjectVariable.create( + proxy, fake_script_obj, tx=self.root_tx, **options + ) + + # HACKY CODE REGION END + + else: + + def wrap_name(module_key: str) -> VariableTracker: + self.output.update_co_names(module_key) + self.global_scope[module_key] = target + return VariableTracker.build( + self, # type: ignore[arg-type] + target, + ConstantSource(source_name=module_key), + ) + + for k, v in self.nn_modules.items(): + if v is target: + # it already exists + return wrap_name(k) + + name = OutputGraph.module_key_name(*names) + name = get_unique_name_wrt(name, self.nn_modules, self.global_scope) + self.nn_modules[name] = target + if isinstance(target, torch.nn.Module): + + def register_leaf_name(leaf_name: str) -> None: + if self.param_name_to_source is None: + raise AssertionError("param_name_to_source must not be None") + new_source = self.get_chained_param_buffer_source(source, leaf_name) + new_name = f"{name}.{leaf_name}" + self.param_name_to_source[new_name] = new_source + if isinstance(source, LocalSource): + self.dynamo_flat_name_to_original_fqn[ + OutputGraph.module_key_name(new_source.name) + ] = leaf_name + + # annoying, but there are cases when we do not have parameters + # see test_nn_moduledict_contains + if hasattr(target, "_parameters"): + for leaf_name, _ in target.named_parameters(): + register_leaf_name(leaf_name) + if hasattr(target, "_buffers"): + for leaf_name, _ in target.named_buffers(): + register_leaf_name(leaf_name) + + return wrap_name(name) + + def handle_aliases_for_stolen_lists( + self, tx: "InstructionTranslatorBase" + ) -> tuple[list[Instruction], dict[Source, Source]]: + # If list inputs are stolen, but still needed after the function call, create aliases to keep them alive + maybe_gm = self.local_scope.get("self") + stolen_list_names = get_locals_to_steal(maybe_gm) + if not stolen_list_names: + return [], {} + + alias_insts = [] + needs_alias: dict[str, list[VariableTracker]] = {} + + queue = [ + *tx.stack, + *tx.symbolic_locals.values(), + *self.side_effects.store_attr_mutations.keys(), + ] + + while queue: + x = queue.pop() + if isinstance(x, BaseListVariable): + if not isinstance(x.items, list): + raise AssertionError(f"x.items must be a list, got {type(x.items)}") + queue += x.items + continue + + if not ( + ( + x not in self.side_effects.store_attr_mutations + or isinstance(x.mutation_type, AttributeMutationExisting) + ) + and isinstance(x.source, GetItemSource) + and isinstance(x.source.base, LocalSource) + and x.source.base.local_name in stolen_list_names + ): + continue + + stolen_name = x.source.base.local_name + if stolen_name not in needs_alias: + needs_alias[stolen_name] = [] + needs_alias[stolen_name].append(x) + + # pyrefly: ignore [implicit-any] + visited = {} + overridden_sources: dict[Source, Source] = {} + for arg in self.graphargs: + if not ( + isinstance(arg._example, list) + and isinstance(arg.source, LocalSource) + and arg.source.local_name in needs_alias + ): + continue + + # arg is a list that will be cleared by the compiled function + list_name = arg.source.local_name + if list_name not in self.code_options["co_varnames"]: + raise AssertionError(f"'{list_name}' not found in co_varnames") + for x in needs_alias[list_name]: + # Skip if already handled. + if x.source in overridden_sources: + continue + + # A small codegen optimization because we might have different + # VariableTrackers that share the same source. + if x.source is None: + raise AssertionError("x.source must not be None") + list_idx = x.source.index # type: ignore[attr-defined] + if list_idx not in visited: + alias_name = self.new_var( + f"{list_name}_ref" + ) # self.new_var already adds unique id suffix + + visited[list_idx] = alias_name + # bytecode of `alias_name = list_name[list_idx]` + alias_insts.extend( + [ + create_instruction("LOAD_FAST", argval=list_name), + create_load_const(list_idx), + create_binary_subscr(), + create_instruction("STORE_FAST", argval=alias_name), + ] + ) + + # operate on alias, handled by suffix codegen + if x.source is None: + raise AssertionError("x.source must not be None") + old_source = x.source + overridden_sources[old_source] = LocalSource(visited[list_idx]) + + # NOTE: we need `overridden_sources` because (1) we want to codegen for + # these list items to use the new local source, but (2) we want to avoid + # updating `source` in place because that might break invariants in + # other parts of Dynamo like guards. + return alias_insts, overridden_sources + + def _get_stack_values_to_restore( + self, tx: "InstructionTranslatorBase", stack_pops: int + ) -> tuple[list[VariableTracker], StackLocalsMetadata]: + """ + Gets the stack + locals values belonging to tx that need to be restored. + + Also prunes dead tx locals and realizes all VTs in the tx's stack. + + NullVariables in stack/locals will NOT be restored, unless they are the top `stack_pops` + elements of the stack - it is expected that the next instruction to run will pop the top + `stack_pops` elements of the stack, so we should codegen NULLs. + + Returns: + - stack_values: stack and locals values that need to be restored + - meta: locations of NULLs and ContextWrappingVariables in the stack/locals + (ignores the top `stack_pops` values on the stack) + """ + tx.prune_dead_locals() + + stack_values = [] + meta = StackLocalsMetadata() + + def ctx_exit_check(var: VariableTracker) -> None: + if type.__instancecheck__(variables.WithExitFunctionVariable, var): + raise AssertionError( + "Attempted to reconstruct WithExitFunctionVariable outside the stack" + ) + + # realize any unrealized tensor VTs in case they + # need to be added to self.nn_modules as attributes + for i, value in enumerate(tx.stack): + # Allow lazy constants through for values being returned (top of stack) + allow_lazy_constant = len(tx.stack) - i <= stack_pops + variables.LazyVariableTracker.realize_all( + value, allow_lazy_constant=allow_lazy_constant + ) + # Do not allow non-stack WithExitFunctionVariable reconstructions + if not isinstance(value, variables.WithExitFunctionVariable): + VariableTracker.visit(ctx_exit_check, value) + # ignore top `stack_pops` values on the stack + if allow_lazy_constant: + stack_values.append(value) + continue + if isinstance(value, NullVariable): + meta.stack_null_idxes.append(i) + else: + stack_values.append(value) + if isinstance(value, ContextWrappingVariable): + target_values = ( + () if value.target_values is None else tuple(value.target_values) + ) + # NOTE: track index in stack after NULLs have been removed + meta.stack_ctx_args.append((len(stack_values) - 1, target_values)) + meta.stack_ctx_idxes_orig.append(i) + + meta.num_stack = len(stack_values) + + # Cells are codegen'd by codegen_cells from the symbolic_cellvars + # registry. A symbolic_locals entry whose name is also a cell/free var + # is either the cell itself (shared slot) or a colliding fast local + # (e.g. an inlined comprehension iteration variable shadowing a + # nonlocal); both are skipped here, consistent with resume argname + # generation in create_call_resume_at. + cell_and_freevars = set(tx.cellvars() + tx.freevars()) + + # NB: Typically (i.e., for graph compile from RETURN_VALUE), + # symbolic_locals will be empty at this point, as prune_dead_locals + # will clear out all of symbolic_locals because RETURN_VALUE is the + # last instruction and no more locals are used. The fanciness here + # is only needed for partial graphs. + # NOTE: All cell and free variables are represented as CellVariable, + # so checks for NULLs and context managers in the case of codegen'ing resume + # functions will not be performed on them. This is expected behavior. + for k, v in tx.symbolic_locals.items(): + # Do not reconstruct WithExitFunctionVariable! + VariableTracker.visit(ctx_exit_check, v) + # Note! this explicitly uses .local_name for matching + # Failure to do so will cause spurious registrations in val_to_names. + # This will in turn result in spurious variables showing up in the graph. + # This was very tricky to debug. For an example, dump the graph at call_user_compiler + # while running test_subgraphs.py + # Do not include top-frame unmodified locals here - otherwise, the compiled graph may + # erroneously include them as part of the return. We manually codegen them afterward. + if ( + isinstance(v.source, LocalSource) + and v.source.local_name == k + and tx is self.root_tx + ): + continue + # Do not load cell/free vars (real cells are handled by + # codegen_cells; a colliding fast local sharing a cell's name is + # skipped to match resume argname generation). + if k in cell_and_freevars: + continue + # Do not load variable if it is NULL. + if sys.version_info >= (3, 12): + # NOTE: do not use isinstance, since it realizes lazy VT's + # Continuation function will load the NULL for v. + if type.__instancecheck__(NullVariable, v): + meta.locals_null_keys.append(k) + continue + else: + # A variable should never be NULL in < 3.12 + if type.__instancecheck__(NullVariable, v): + raise AssertionError( + "variable should never be NULL in Python < 3.12" + ) + meta.locals_names[k] = len(meta.locals_names) + if isinstance(v, ContextWrappingVariable): + target_values = ( + () if v.target_values is None else tuple(v.target_values) + ) + meta.locals_ctx_args.append((k, target_values)) + stack_values.append(v) + + return stack_values, meta + + def compile_subgraph( + self, + tx: "InstructionTranslatorBase", + reason: GraphCompileReason, + stack_pops: int = 0, + ) -> list[StackLocalsMetadata]: + """ + Compiles the current subgraph, with inputs w.r.t. self.root_tx, and codegens: + - Call the compiled subgraph + - Apply side effects + - Codegen stack and locals + - Store the locals + + Python does not allow NULL to be an arg to a function, so we do not codegen NULLs on the stack, + unless the value is one of the top `stack_pops` values on the stack (these values are expected to be + popped immediately after this generated code. The prologue of the resume function is expected to restore + any dropped NULLs. + + Returns stack indices and locals keys where we dropped NULLs, and where we found inactive context manager objects. + """ + + if self.root_tx is None: + raise AssertionError("root_tx must not be None") + + # Finalize shapes_spec wiring: errors if any spec assumption/derived + # check still has unbound IntVar dependencies (i.e. an IntVar + # appears in an expression but never as a bare-IntVar input slot). + if config._dynamic_shapes_spec is not None: + from torch.fx.experimental.symbolic_shapes import _finalize_spec_wiring + + _finalize_spec_wiring(self.shape_env) + + if not config.nested_graph_breaks: + # expect to only compile 1 frame + if self.root_tx is not tx: + raise AssertionError( + "root_tx must be tx when nested_graph_breaks is disabled" + ) + + # bytecode tracing has finished. Pop the context manager for dynamo_timed + self.mark_bytecode_tracing_stop() + + self.compile_subgraph_reason = reason + self.should_exit = True + + log.debug("COMPILING GRAPH due to %s", reason) + + # prefix instructions (Python 3.11+) + prefix_insts: list[Instruction] = [] + if sys.version_info >= (3, 11): + for inst in self.root_tx.prefix_insts: + if inst.opname == "COPY_FREE_VARS": + prefix_insts.append( + create_instruction( + "COPY_FREE_VARS", + arg=len(self.root_tx.code_options["co_freevars"]), + ) + ) + else: + inst_copy = copy.copy(inst) + # Prefix instructions are copied without the original + # exception table range; generated bytecode owns a new body. + inst_copy.exn_tab_entry = None + prefix_insts.append(inst_copy) + + # stack values and restore vars for each frame are pushed in reverse order + # i.e. last element corresponds to root frame (1), + # first element corresponds to current frame (N) + all_stack_values = [] + # pyrefly: ignore [implicit-any] + all_stack_locals_metas = [] + cur_tx: InstructionTranslatorBase | None = tx + while cur_tx is not None: + # this should have been checked by the caller + if not all(block.can_restore() for block in cur_tx.block_stack): + raise AssertionError( + "all blocks in cur_tx.block_stack must be restorable" + ) + + stack_values, meta = self._get_stack_values_to_restore( + cur_tx, stack_pops if cur_tx is tx else 0 + ) + all_stack_values.append(stack_values) + all_stack_locals_metas.append(meta) + + # Exit from all context manager variables to make sure global state is restored + for block in reversed(cur_tx.block_stack): + block.exit(cur_tx, is_graph_break=reason.graph_break) + + cur_tx = cur_tx.parent + + # "Garbage collect the heap". + self.side_effects.prune_dead_object_new(tx) + + self.add_output_instructions(prefix_insts) + + if self._emit_debugger_breakpoint: + from .bytecode_transformation import create_breakpoint + + self.add_output_instructions(create_breakpoint()) + self._emit_debugger_breakpoint = False + + if self.pregraph_bytecode and self.export: + raise AssertionError("export does not support pregraph_bytecode") + self.add_output_instructions(self.pregraph_bytecode) + + alias_insts, overridden_sources = self.handle_aliases_for_stolen_lists( + self.root_tx + ) + self.add_output_instructions(alias_insts) + + self.cleanup_graph() + + # Use nn.Module "proxies" in the constructed GraphModule so that + # the resulting GM does not hold additional strong references to the original modules. + # This prevents a strong ref cycle where Dynamo created code holds on to references + # to modules that also have Dynamo code cache invalidation checks. + # When cache invalidation runs, the generated GM will be invalidated, which also deletes + # the proxies. + nn_modules_proxies = { + name: nn_module_proxy(mod) for name, mod in self.nn_modules.items() + } + root = FakeRootModule(nn_modules_proxies) + + from .decorators import disable + + # to handle random calls + if len(self.random_calls) > 0: + random_calls_instructions = [] + self.random_values_var = self.new_var("random_values") + rand_fn = disable( + _get_gen_rand_values_fn(self.random_calls), + reason="do not trace into Dynamo rng recovery function", + ) + rand_fn_name = self.install_global("__gen_rand_values", rand_fn) + codegen = PyCodegen( + self.root_tx, root, overridden_sources=overridden_sources + ) + random_calls_instructions.extend( + codegen.load_function_name(rand_fn_name, True) + ) + random_calls_instructions.extend(create_call_function(0, False)) + random_calls_instructions.append( + codegen.create_store(self.random_values_var), + ) + self.add_output_instructions(random_calls_instructions) + + # Codegen stack convention before the unsupported instruction + # NOTE: in these comment blocks, "locals" EXCLUDE free and cell vars. + # NOTE: stack/locals/cells must be codegen'd BEFORE the unsupported instruction, since the latter + # can arbitrarily mutate the former. + # [frame N cells, .., frame 1 cells], + # [ + # frame N locals, + # frame N-1 stack + locals, + # ..., + # frame 1 stack + locals, + # ], frame N stack + + # see symbolic_convert.py for + # codegen stack convention after the unsupported instruction + # NOTE: cells will be loaded into continuation functions directly by symbolic_convert + + # this determines the order that values are codegen'd to the stack + stack_values_flat = [val for vals in all_stack_values for val in vals] + stored_graph_output_var = False + graph_output_var = None + + # call compiled fx graph and codegen all values - stack and locals + can_use_fast_path = ( + self.root_tx is tx # single frame + and stack_values_flat + and all( + not isinstance( + v, + ( + UnspecializedPythonVariable, + NumpyNdarrayVariable, + TensorWithTFOverrideVariable, + ), + ) + and not (isinstance(v, SymNodeVariable) and v.python_type() is float) + for v in stack_values_flat + ) + and all(x.is_tensor() for x in stack_values_flat) + and len(set(stack_values_flat)) == len(stack_values_flat) + and self.side_effects.is_empty() + and not tx.debug_locals + and not self.backward_state + and not all_stack_locals_metas[-1].stack_null_idxes + and not all_stack_locals_metas[-1].locals_null_keys + ) + + # Generators that don't escape the frame must still have their finally + # blocks run at frame exit (CPython does this via tp_finalize on GC). + if can_use_fast_path and self.local_generators: + self.close_local_generators(tx) + can_use_fast_path = self.side_effects.is_empty() + + if can_use_fast_path: + # optimization to generate better code in a common case + + # codegen cells + # no side effects, so no new cells created - no need to call side_effects.codegen_save_tempvars + cell_cg = PyCodegen(self.root_tx) + self.codegen_cells(tx, cell_cg) + instructions, pycode = self.compile_and_call_fx_graph( + tx, list(reversed(stack_values_flat)), root + ) + self.add_output_instructions( + [ + # load in reverse since UNPACK_SEQUENCE will reverse + *instructions, + *cell_cg.get_instructions(), + *create_swap(2), + create_instruction("UNPACK_SEQUENCE", arg=len(stack_values_flat)), + ], + pycode=pycode, + ) + # function output will be moved to the correct places below + else: + graph_output_var = self.new_var("graph_out") + # load stack values in a flat manner - we will codegen bytecode to place them correctly + # according to our convention above + pass1 = PyCodegen( + self.root_tx, + root, + graph_output_var, + overridden_sources=overridden_sources, + ) + self.codegen_suffix(tx, stack_values_flat, pass1, False) + + # Close all generators opened while tracing. Needs to be done after + # pass1, as PyCodegen might try to reconstruct the generator, which + # sets LocalGeneratorObjectVariable.remaining_items + self.close_local_generators(tx) + + # Use `pass1.uses` to selectively cache multi-user variables into a + # temporary local source. This (a). speeds up loading VTs with long + # chained source, and (b). avoids redundantly saving single-user VT + # into a temporary local. + tempvars = {} # type: ignore[var-annotated] + for val, count in pass1.uses.items(): + # If it's already a local source, no need to cache it + if count > 1 and not istype(val, (SyntheticLocalSource, LocalSource)): + tempvars[val] = None + pass2 = PyCodegen( + self.root_tx, + root, + graph_output_var, + tempvars=tempvars, + overridden_sources=overridden_sources, + ) + self.codegen_suffix(tx, stack_values_flat, pass2, True) + + if ( + torch._dynamo.config.log_graph_in_out_metadata + and stack_values_flat + and len(stack_values_flat) == 1 + ): + vt = stack_values_flat[0] + if ( + isinstance(vt, torch._dynamo.variables.NamedTupleVariable) + and vt.tuple_cls + is torch._dynamo.functional_export.ExportTracerOutput + ): + flat_returns = vt.items[0] + out_spec = vt.items[1] + if not isinstance( + flat_returns, torch._dynamo.variables.ListVariable + ): + raise AssertionError("flat_returns must be a ListVariable") + + vt_to_graph_out_idx: dict[VariableTracker, int] = {} + for value in pass2.graph_outputs.values(): + if not isinstance( + value, torch._dynamo.codegen.GraphOutputEntry + ): + raise AssertionError( + f"graph output value must be a GraphOutputEntry, got {type(value)}" + ) + variable: VariableTracker = value.variable + vt_to_graph_out_idx[variable] = value.index + + output_return_type = self.export_metadata.output_return_type + for idx, vt in enumerate(flat_returns.items): + if vt in vt_to_graph_out_idx: + output_return_type[idx] = OutputReturnInfo( + "graph_out", vt_to_graph_out_idx[vt] + ) + elif ( + vt.source is not None + and (source := getattr(vt.source, "base", None)) # type: ignore[assignment] + and getattr(source, "is_input", False) + ): + output_return_type[idx] = OutputReturnInfo( + "input", vt.source + ) + elif vt.is_python_constant(): + output_return_type[idx] = OutputReturnInfo( + "constant", vt.as_python_constant() + ) + else: + raise AssertionError( + f"Encountered unrecognized type {vt} at output {idx}" + ) + try: + self.export_metadata.out_spec = out_spec.as_python_constant() + except ClosureConversionError as e: + unimplemented( + gb_type="nested function with non-constructible closure in output", + context=f"as_python_constant for out_spec {out_spec}", + explanation=( + "Cannot return a nested function with closure from a compiled function. " + "Dynamo failed to construct the function defined in the compiled region with closure objects." + ), + hints=[ + "Define the function at module scope instead of inside another function ", + "Ensure that all closure variables are constants.", + ], + from_exc=e, + ) + + output = [] + subgraph_pycode = None + if count_calls(self.graph) != 0 or len(pass2.graph_outputs) != 0: + instructions, subgraph_pycode = self.compile_and_call_fx_graph( + tx, pass2.graph_output_vars(), root + ) + output.extend(instructions) + + if len(pass2.graph_outputs) != 0: + output.append(pass2.create_store(graph_output_var)) + stored_graph_output_var = True + else: + output.append(create_instruction("POP_TOP")) + else: + # NB: Important to run compiler collective even when there is + # a graph break + self.run_compiler_collective() + self.add_output_instructions(output, pycode=subgraph_pycode) + self.add_output_instructions( + pass2.get_instructions(), pycode=pass2.get_pycode() + ) + + # store all stack and locals for each frame + # current state of the stack: + # all cells, + # *(frame N stack), *(frame N locals), + # ..., + # *(frame 1 stack), *(frame 1 locals) + + self.add_output_instructions( + [ + create_instruction( + "BUILD_LIST", + arg=len(stack_values_flat) - all_stack_locals_metas[0].num_stack, + ), + ] + ) + + # current state of the stack: + # all cells, + # *(frame N stack), [ + # *(frame N locals), + # *(frame N-1 stack), *(frame N-1 locals), + # ... + # *(frame 1 stack), *(frame 1 locals), + # ] + # iterate current frame (N) to root frame (1) + # sliding window over frame stack/locals + start_idx = 0 + end_idx = 0 + for i, meta in enumerate(all_stack_locals_metas): + # do not pack frame N's stack into the value list + n_vals = len(meta.locals_names) + if i != 0: + n_vals += meta.num_stack + if n_vals == 0: + self.add_output_instructions( + [ + create_instruction("BUILD_LIST", arg=0), + *create_swap(2), + ] + ) + # [], stack_values_flat + else: + end_idx += n_vals + self.add_output_instructions( + [ + create_dup_top(), + *create_binary_slice(start_idx, end_idx), + *create_swap(2), + ] + ) + start_idx += n_vals + # stack_values_flat[x:y], stack_values_flat + + # add root frame's unmodified locals here + if i == len(all_stack_locals_metas) - 1: + root_cg = PyCodegen(self.root_tx) + unmodified_locals_names: dict[str, int] = {} + for k, v in self.root_tx.symbolic_locals.items(): + if isinstance(v.source, LocalSource) and v.source.local_name == k: + root_cg.append_output(root_cg.create_load(k)) + unmodified_locals_names[k] = len(meta.locals_names) + len( + unmodified_locals_names + ) + self.add_output_instructions( + root_cg.get_instructions() + + [ + create_instruction( + "BUILD_LIST", arg=len(unmodified_locals_names) + ), + # arg=2 because we already swapped the locals list back + create_instruction("LIST_EXTEND", arg=2), + ] + ) + meta.locals_names.update(unmodified_locals_names) + + # *(frame N stack), metas[0] stack + locals, ..., metas[i] stack + locals, stack_values_flat + + # current state of the stack: + # all cells, + # *(frame N stack), + # frame N locals, + # frame N-1 stack, frame N-1 locals, + # ... + # frame 1 stack, frame 1 locals, + # stack_values_flat + # + + self.add_output_instructions( + [ + create_instruction("POP_TOP"), + create_instruction("BUILD_LIST", arg=len(all_stack_locals_metas)), + *create_rot_n(all_stack_locals_metas[0].num_stack + 1), + ] + ) + + # final state of the stack before running the unsupported bytecode: + # all cells, + # [ + # [frame N locals], + # [frame N-1 stack + locals], + # ..., + # [frame 1 stack + locals], + # ], *(frame N stack) + + if graph_output_var and stored_graph_output_var: + self.add_output_instructions( + [create_instruction("DELETE_FAST", argval=graph_output_var)] + ) + + if torch._dynamo.config.side_effect_replay_policy in ["warn", "error"]: + side_effect_refs = self.get_replayed_side_effect_source_refs( + populate_export_metadata=True + ) + if side_effect_refs: + if torch._dynamo.config.side_effect_replay_policy == "warn": + warnings.warn( + f"While compiling, we found certain side effects happened in the model.forward. " + f"Here are the list of potential sources you can double check: {side_effect_refs}" + ) + else: + raise RuntimeError( + f"While compiling, we found certain side effects happened in the model.forward. " + f"Here are the list of potential sources you can double check: {side_effect_refs}" + ) + + return all_stack_locals_metas + + def codegen_cells(self, tx: "InstructionTranslatorBase", cg: PyCodegen) -> None: + # no need to codegen if reason.graph_break is False (since we won't resume) + if self.compile_subgraph_reason.graph_break: + tx_cnt = 0 + cur_tx: InstructionTranslatorBase | None = tx + while cur_tx is not None: + # NOTE: we generate cells in the same order as resume_execution.py: sorted freevars + cellvars + # Emitting `LOAD_FAST/LOAD_CLOSURE` with names in `co_freevars` + # requires that in the generated bytecode, these cells would keep + # their original local names, which we ensure via + # `CellVariable.local_name`. + freevars = tuple(sorted(cur_tx.cell_and_freevars())) + for cell in freevars: + if cur_tx is self.root_tx: # root frame + cg.append_output(cg.create_load_closure(cell)) + else: # nested frame + if not cur_tx.post_prune_cell_and_freevars: + raise AssertionError( + "cur_tx.post_prune_cell_and_freevars must be set for nested frames" + ) + var = cur_tx.post_prune_cell_and_freevars[cell] + if isinstance(var, NullVariable): + raise AssertionError("Can't codegen null cell") + cg(var) + cg.append_output(create_build_tuple(len(freevars))) + cur_tx = cur_tx.parent + tx_cnt += 1 + cg.append_output(create_instruction("BUILD_LIST", arg=tx_cnt)) + else: + cg.append_output(create_instruction("BUILD_LIST", arg=0)) + + def codegen_suffix( + self, + tx: "InstructionTranslatorBase", + stack_values: list[VariableTracker], + cg: PyCodegen, + log_side_effects: bool, + ) -> None: + # NOTE: `codegen_save_tempvars` must run first to update `source` fields + # for variables with `AttributeMutationNew`, as they don't implement + # `reconstruct` themselves. + self.side_effects.codegen_save_tempvars(cg) + if self.backward_state: + if self.export: + raise AssertionError("backward_state is not supported in export mode") + for name, val in self.backward_state.items(): + cg(val) + if self.backward_state_var is None: + raise AssertionError( + "backward_state_var must not be None when backward_state is set" + ) + cg.append_output(cg.create_load(self.backward_state_var)) + cg.store_attr(name) + if config.replay_side_effects: + self.side_effects.codegen_hooks(cg) + + # TODO get debug_locals working for nested graph breaks + # Return variables used for logging at the end + for debug_var, args in tx.debug_locals: + cg.add_push_null(lambda: cg(debug_var)) + for arg in args: + cg(arg) + cg.extend_output(create_call_function(len(args), False)) + cg.extend_output([create_instruction("POP_TOP")]) + + # codegen cells before we apply side effects + self.codegen_cells(tx, cg) + + cg.restore_stack(stack_values, value_from_source=not tx.export) + self.side_effects.codegen_update_mutated(cg, log_side_effects) + + def cleanup_graph(self) -> None: + """ + Remove "creation_timestamp" from node meta + + Remove this pattern from the graph: + torch._C._set_grad_enabled(False) + torch._C._set_grad_enabled(True) + """ + if not self.should_exit: + raise AssertionError("should_exit must be True before cleanup_graph") + nodes = list(self.graph.nodes) + for node in nodes: + node.meta.pop("creation_timestamp", None) + + grad_enabled = torch.is_grad_enabled() + for node1, node2 in itertools.pairwise(nodes): + if ( + node1.target is torch._C._set_grad_enabled + and tuple(node1.args) == (not grad_enabled,) + and not node1._erased + ): + grad_enabled = node1.args[0] + if ( + node2.target is torch._C._set_grad_enabled + and tuple(node2.args) == (not grad_enabled,) + and not node2._erased + ): + grad_enabled = node2.args[0] + self.graph.erase_node(node1) + self.graph.erase_node(node2) + + def bypass_package(self, reason: str = "", **kwargs: Any) -> None: + """ + Do not save this output graph to the CompilePackage + """ + if not self.package: + return + if torch._dynamo.config.strict_precompile: + raise torch._dynamo.exc.PackageError( + "Detected a package bypass: %s", reason + ) + log.warning("Detected a package bypass: %s", reason) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "precompile_cache_bypass", + "encoding": "json", + }, + payload_fn=lambda: { + # precede with underscore so it always appear first in JSON in tlparse + "_reason": reason, + **kwargs, + }, + ) + self.package.bypass_current_entry() + self.package = None + + def get_graph_sizes_structured(self) -> dict[str, list[int | str]]: + ret: dict[str, list[int | str]] = {} + for node in self.graph.nodes: + example_value = node.meta.get("example_value", None) + if torch._subclasses.fake_tensor.is_fake_tensor(example_value): + size = example_value.shape + ret[node.name] = [s if isinstance(s, int) else repr(s) for s in size] + return ret + + def get_graph_sizes(self, name: str) -> str: + graph_sizes_str = "TRACED GRAPH TENSOR SIZES\n" + graph_sizes_str += f"===== {name} =====\n" + for node in self.graph.nodes: + example_value = node.meta.get("example_value", None) + if torch._subclasses.fake_tensor.is_fake_tensor(example_value): + size = example_value.shape + graph_sizes_str += f"{node.name}: {tuple(size)}\n" + concrete_size = [] + has_symint = False + for sz in size: + if isinstance(sz, int): + concrete_size.append(sz) + elif isinstance(sz, torch.SymInt): + has_symint = True + concrete_size.append(sz.node.hint) + else: + break + else: + if has_symint: + graph_sizes_str += ( + f"{node.name} (concrete): {tuple(concrete_size)}\n" + ) + return graph_sizes_str + + @contextlib.contextmanager + def restore_global_state(self) -> Any: + """ + Momentarily restores the global state to what it was prior to tracing the current output + """ + prior_global_state = self.tracing_context.global_context.copy_graphstate() + current_global_state: dict[str, tuple[Any, bool]] = {} + self.save_global_state(out=current_global_state) + try: + # Set to state prior to tracing the graph + self.tracing_context.global_context.restore_graphstate(prior_global_state) + yield + finally: + # Reset to state at the current time (e.g. before calling the user compiler) + self.tracing_context.global_context.restore_graphstate( + GlobalContextCheckpointState(current_global_state) + ) + + def run_compiler_collective(self) -> None: + tx = self.root_tx + if tx is None: + raise AssertionError("root_tx must not be None") + if (ds := tx.distributed_state) is not None and ds.all_states is None: + compile_pg = ds.compile_pg + + log.info("compiler_collective %s", ds.local_state) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "compiler_collective", + "encoding": "string", + }, + payload_fn=lambda: ds.local_state.render(), + ) + device_types = compile_pg._device_types + if len(device_types) != 1: + raise AssertionError( + "Expect only one device type but got {}".format( + "+".join(device_types) + ) + ) + with ( + get_interface_for_device(device_types.pop()).device( # type: ignore[attr-defined] + compile_pg.rank() % torch.accelerator.device_count() + ), + dynamo_timed("compiler_collective", log_pt2_compile_event=True), + ): + all_states: list[Any] = [None] * compile_pg.size() + + dist.all_gather_object(all_states, ds.local_state, group=compile_pg) + + ds.all_states = all_states + # Clear speculation log, because are tracing may diverge due to + # this information from the compiler collective + tx.speculation_log.clear() + raise exc.CompileCollectiveRestartAnalysis + + def _validate_outputs_safe_for_autograd_nodes( + self, rv: list["VariableTracker"], tx: "InstructionTranslatorBase" + ) -> None: + """ + Validate that if torch.autograd.grad is used in the graph and outputs + require grad, we trigger AutogradGradRestartAnalysis only if the output is connected + to the autograd.grad computation. + + rv here refers to list of variables that are being returned from dynamo graph. + + See Note [Tracing autograd.grad in dynamo] + """ + if not self.autograd_grad_consumed_grad_fns: + return + + from .variables.tensor import TensorVariable + + for var in rv: + if not isinstance(var, TensorVariable) or not var.requires_grad: + continue + + fake_tensor = var.as_proxy().node.meta.get("example_value") + if not torch._subclasses.fake_tensor.is_fake_tensor(fake_tensor): + raise AssertionError( + f"expected example_value to be a FakeTensor, got {type(fake_tensor)}" + ) + if fake_tensor.grad_fn is None: + continue + + # Traverse the entire autograd graph of the returned tensor to check + # if any node was consumed by autograd.grad + reachable_grad_fns = collect_reachable_grad_fns([(fake_tensor, None)]) + if reachable_grad_fns & self.autograd_grad_consumed_grad_fns: + # Record info about the leaked tensor for the error message + tensor_name = str(var.source) if var.source else var.proxy.node.name + tx.speculation_log.autograd_grad_leaked_tensors.append(tensor_name) + + if tx.speculation_log.autograd_grad_leaked_tensors: + # Set the flag to graph break at autograd.grad on retry + tx.speculation_log.graph_break_on_autograd_grad = True + raise exc.AutogradGradRestartAnalysis( + restart_reason="autograd.grad consumed grad_fns of returned tensors" + ) + + def _check_requires_grad_intermediate_outputs( + self, rv: list["VariableTracker"], tx: "InstructionTranslatorBase" + ) -> None: + """Skip frame if a source-less requires_grad_() intermediate leaks as output. + + AOTAutograd's functionalization drops requires_grad_() on intermediates, + so returning them (or tensors derived from them) produces wrong results. + We detect this via FX graph reachability: find the requires_grad_() nodes + for source-less intermediates, then check if any output is downstream. + """ + from .variables.tensor import TensorVariable + + # Collect FX nodes for source-less requires_grad_() intermediates + tainted_nodes: set[torch.fx.Node] = set() + for v in self.leaf_var_creation_order: + if isinstance(v, TensorVariable) and not v.source: + tainted_nodes.add(v.as_proxy().node) + + if not tainted_nodes: + return + + # Propagate taint forward through the FX graph + for node in self.graph.nodes: + if node in tainted_nodes: + continue + if any(inp in tainted_nodes for inp in node.all_input_nodes): + tainted_nodes.add(node) + + # Check leaked outputs: tainted + requires_grad means the output + # carries autograd state that AOTAutograd would silently drop. + # Detached outputs (requires_grad=False) are fine — no autograd to lose. + for var in rv: + if ( + isinstance(var, TensorVariable) + and var.requires_grad + and var.as_proxy().node in tainted_nodes + ): + msg = ( + "An intermediate tensor that had requires_grad_() called " + "on it (or a tensor derived from it) is being returned " + "from the compiled region. AOTAutograd's functionalization " + "drops the requires_grad_() effect on graph outputs, " + "producing wrong results. If you only need the tensor " + "values without gradients, call .detach() before returning." + ) + if tx.one_graph: + unimplemented( + gb_type="returning intermediate with requires_grad_()", + context="graph output depends on source-less requires_grad_()", + explanation=msg, + hints=[ + "If you only need the tensor values without gradients, " + "call .detach() before returning.", + "Consume the gradient inside the compiled function " + "(call backward() and use .grad), " + "or move requires_grad_() outside torch.compile.", + ], + ) + else: + tx.speculation_log.graph_break_on_requires_grad_ = True + raise exc.RequiresGradRestartAnalysis( + restart_reason="source-less requires_grad_() intermediate leaked as output" + ) + + def compile_and_call_fx_graph( + self, + tx: "InstructionTranslatorBase", + rv: list[VariableTracker], + root: FakeRootModule, + ) -> tuple[list[Instruction], list[str] | None]: + """ + Generate code from self.graph and return the Instruction()s to + call that generated code. + + Code is generated w.r.t. self.root_tx. + tx is only used for preserving GraphModule metadata + + Returns a tuple of (instructions, pycode) where pycode is a string + representation of the generated Python code if generate_pycode_prologue + is enabled, otherwise None. + """ + with torch._guards.TracingContext.clear_frame(): + from .decorators import disable + + if not self.should_exit: + raise AssertionError( + "should_exit must be True before call_user_compiler" + ) + + self.run_compiler_collective() + if count_calls(self.graph) == 0 and len(rv) == 0: + return [], None + + name = make_compiled_fn_name() + + if not isinstance(rv, list): + raise AssertionError(f"rv must be a list, got {type(rv)}") + if not isinstance(root, FakeRootModule): + raise AssertionError(f"root must be a FakeRootModule, got {type(root)}") + + # Error on source-less requires_grad_() outputs. + # Must run before autograd validation since detaching resolves the + # "consumed grad_fn" conflict for backward-consumed intermediates. + self._check_requires_grad_intermediate_outputs(rv, tx) + + # Check if autograd.grad is used with outputs that require grad + # This would cause double backward issues in aot_autograd + self._validate_outputs_safe_for_autograd_nodes(rv, tx) + + output_node = self.create_node( + "output", + "output", + (self.current_tracer.create_arg(tuple(x.as_proxy() for x in rv)),), + {}, + ) + sub_gms = self.dedup_pass() + root.add_nn_modules(sub_gms) # type: ignore[arg-type] + + self.current_tracer._maybe_preserve_original_meta(tx, output_node) + if not config.do_not_emit_runtime_asserts: + # There is a rare scenario where codegen_suffix adds a new entry + # to self.nn_modules while `root` knows only about the + # nn_modules at the time of its creation. This causes failures + # while creating the graph module because self.graph and root + # are out of sync. This only happens for `get_attr` nodes, so + # here we clean up the get_attr nodes that are unused. + with dynamo_timed("insert_deferred_runtime_asserts"): + for attr in dir(root): + subgraph = getattr(root, attr) + if isinstance(subgraph, fx.GraphModule): + insert_deferred_runtime_asserts( + subgraph, + self.shape_env, + name, + export=self.export, + ) + self.remove_unused_get_attr_nodes() + insert_deferred_runtime_asserts( + fx.GraphModule(root, self.graph), + self.shape_env, + name, + export=self.export, + ) + # NB: deferred runtime asserts can keep graphargs live, so make sure + # those are inserted before pruning + self.remove_unused_graphargs() + ncalls = count_calls(self.graph) + counters["stats"]["calls_captured"] += ncalls + + self.remove_tensorify_specialized_graphargs() + + # free a bit of memory + self.real_value_cache.clear() + + # CA backward graphs have side-effecting ops (call_accumulate_grad, + # call_hook) that is_impure() doesn't flag, and a fixed positional + # placeholder layout that must not be reordered. + # + # Export canonicalizes in torch.export._trace._produce_aten_artifact + # so both strict and non-strict export produce the same node order. + if ( + config.canonicalize_output_graph_node_order + and not self.export + and not torch.compiler.is_exporting() + and not torch._dynamo.compiled_autograd.in_compiled_autograd_region + ): + _canonicalize_graph(self.graph) + + gm = _make_graph_module(root, self.graph) + + from .dce_extra_outputs import dce_hop_extra_outputs + + dce_hop_extra_outputs(gm) + + # Saved tensors hooks are not used by the graph. + # GraphModule by default only copies used in the graph submodules. + # Copying them into the result graph manually. + if self.saved_tensors_hooks_subgraph_names: + for subgraph_name in self.saved_tensors_hooks_subgraph_names: + setattr(gm, subgraph_name, getattr(root, subgraph_name)) + + for register_finalizer in self.register_finalizer_fns: + register_finalizer(gm) + + if next(gm.parameters(), None) is not None: + # If dynamo produces a graph with parameters, skip package stuff + # Bypass output graph + self.bypass_package( + "Graph contains named parameters due to static addresses.", + gm=gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + if self.package is not None: + gm._backend_id = name # pyrefly: ignore[bad-argument-type] + + # pyrefly: ignore[bad-argument-type] + gm.compile_subgraph_reason = self.compile_subgraph_reason + # pyrefly: ignore[bad-argument-type] + gm.meta["dynamo_flat_name_to_original_fqn"] = ( + self.dynamo_flat_name_to_original_fqn.copy() + ) + gm.meta["dynamo_compile_id"] = self.dynamo_compile_id + gm.meta["backend_id"] = name + + if self.cudagraph_annotation is not None: + gm.meta["cudagraph_annotation"] = self.cudagraph_annotation + + graph_code_log.debug( + "%s", + lazy_format_graph_code( + name, gm, include_stride=True, include_device=True, colored=True + ), + ) + torch._logging.trace_structured( + "dynamo_output_graph", + lambda: {"sizes": self.get_graph_sizes_structured()}, + payload_fn=lambda: gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + self.call_cleanup_hooks() + old_fake_mode = self.tracing_context.fake_mode + if old_fake_mode is None: + raise AssertionError("old_fake_mode must not be None") + # Store old_fake_mode so it can be cleared at end of compile + self._old_fake_mode = old_fake_mode + if not self.export: + import torch._functorch.config as _config + + with _config.patch(fake_tensor_allow_unsafe_data_ptr_access=False): + # TODO(voz): The way export uses gm, and fake tensors, is not supported with us resetting + + # Why create a new FakeTensorMode? + # + # The reason this needs to be done is because when we do Dynamo tracing, fake + # tensors can have their metadata mutated. Thus, the fake tensor we allocated + # for any given tensor may no longer be valid for the beginning trace of the + # graph. Nor is it convenient to "clone" the input tensors before mutating them, + # since you have to preserve aliasing. So we just reconstruct the FakeTensorMode + # from scratch when we go to AOTAutograd. But the ShapeEnv must be preserved as + # Dynamo made decisions about what is dynamic or not / guards from the user code + # that is not in graph. + backend_fake_mode = torch._subclasses.FakeTensorMode( + shape_env=old_fake_mode.shape_env, + ) + # TODO(voz): Ostensibly, this should be scoped and + # restore back to old_fake_mode, but doing so currently violates + # a lot of fake_tensor ownership assumptions and runs afoul of detect_fake_mode + self.tracing_context.fake_mode = backend_fake_mode + + example_inputs = self.example_inputs() + + # Restore placeholder metadata mutated by + # in-graph shallow_copy_data_. + if self._shallow_copy_placeholder_snapshots: + placeholders = gm.graph.find_nodes(op="placeholder") + placeholder_to_idx = {n: i for i, n in enumerate(placeholders)} + for node, snapshot in self._shallow_copy_placeholder_snapshots.items(): + node.meta["example_value"] = snapshot + idx = placeholder_to_idx[node] + example_inputs[idx].fake_device = snapshot.fake_device # type: ignore[union-attr] + + gm.graph.lint() + with self.restore_global_state(): + compiled_fn = self.call_user_compiler(gm, example_inputs) + + from torch.fx._lazy_graph_module import _LazyGraphModule + + if isinstance(compiled_fn, _LazyGraphModule) or ( + isinstance(getattr(compiled_fn, "__self__", None), _LazyGraphModule) + and compiled_fn.__name__ == "_lazy_forward" # type: ignore[attr-defined] + ): + # Since dynamo will run the forward method for the GraphModule shortly + # anyways, it does not hurt to do the real recompilation here if + # this is a _LazyGraphModule. This makes it easier for dynamo to + # optimize a _LazyGraphModule. + + lazy_gm = ( + compiled_fn + if isinstance(compiled_fn, _LazyGraphModule) + else compiled_fn.__self__ # type: ignore[attr-defined] + ) + + _LazyGraphModule.force_recompile(lazy_gm) + + if not isinstance(compiled_fn, _LazyGraphModule): + # replace compiled_fn with the real forward method + compiled_fn = lazy_gm.forward + + if not self.export: + # Run after every non-export backend compile, not only the + # registered backends covered by convert_frame weakref cleanup. + # Backends have already consumed the graph, so non-CPU Dynamo + # tracing constants no longer need to keep real tensors alive. + old_fake_mode.fake_tensor_converter.clear_non_cpu_constants() + + if self.package is not None: + self.package.add_backend_id(name, compiled_fn) + + # If __torch_function__ subclass dispatch was inlined during + # tracing, wrap the compiled graph to disable __torch_function__ + # at runtime, preventing double dispatch (the C++ dispatcher + # would otherwise re-trigger __torch_function__ on subclass + # inputs that the graph already handles). + if self.torch_function_subclass_inlined: + real_compiled_fn = compiled_fn + + def _tf_disabled_wrapper(*args, **kwargs): + with torch._C.DisableTorchFunctionSubclass(): + return real_compiled_fn(*args, **kwargs) + + compiled_fn = _tf_disabled_wrapper + + compiled_fn = disable( + compiled_fn, reason="do not trace Dynamo-compiled graph" + ) + + counters["stats"]["unique_graphs"] += 1 + if old_fake_mode.shape_env is None: + raise AssertionError("old_fake_mode.shape_env must not be None") + if specializations := old_fake_mode.shape_env.specializations: + specialization_guards = [] + specialization_cache: dict[Specialization, Callable[[Any], Any]] = {} + sources = [a.source for a in self.graphargs] + for specialization in specializations: + source_index = sources.index(specialization.source) + check_fn_source = inspect.getsource(specialization.check_fn).strip() + # Required because the LABDA_GUARD API requires a root guard manager + unused_root_guard_manager = RootGuardManager() + check_fn = guards.LAMBDA_GUARD( # type: ignore[attr-defined] + unused_root_guard_manager, + specialization.check_fn, + [check_fn_source], + None, # user_stack + ) + + log.debug( + "Compiling backend specialized graph with specialization=%s", + check_fn_source, + ) + + specialization_guards.append( + ( + functools.partial( + lambda idx, args, check_fn=check_fn: check_fn( + args[idx] + ), + source_index, + ), + specialization, + ) + ) + + @torch._dynamo.disable(reason="do not trace Dynamo-compiled graph") # type: ignore[misc] + def specialized_dispatch(*args: Any, **kwargs: Any) -> Any: + for check_fn, specialization in specialization_guards: + if check_fn(args): + if specialization in specialization_cache: + return specialization_cache[specialization]( + *args, **kwargs + ) + + with self.shape_env.patch_source_specialization( + specialization.source, specialization.check_fn + ): + # Modify gm so AOTAutogradCache key changes per specialization + gm.meta["specialization"] = specialization + example_inputs: list[Tensor] = list(args) + with tracing(self.tracing_context): + specialization_cache[specialization] = ( + self.call_user_compiler(gm, example_inputs) + ) + + return specialization_cache[specialization](*args, **kwargs) + return compiled_fn(*args, **kwargs) + + # This is safe because we pre-process name to be unique + self.install_global_unsafe(name, specialized_dispatch) + else: + # This is safe because we pre-process name to be unique + self.install_global_unsafe(name, compiled_fn) + + if self.root_tx is None: + raise AssertionError("root_tx must not be None") + cg = PyCodegen(self.root_tx) + + if has_user_objects(): + # NB: This is where we store possible user objects before running the graph + # index_to_user_object_weakref is the function used in the graph to translate + # the dynamo-generated index into the actual object passed to the compiled function. + # We generate bytecode to store all user objects at the proper index in the below + # call. + cg.add_push_null( + lambda: cg.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, + "store_user_object_weakrefs", + ) + ) + + tmp_vars = [] + for constructor in index_to_bytecode_constructor.values(): + constructor(cg) + var_name = ( + self.new_var() + ) # keep alive any user objects for the rest of the frame + # TODO: we could omit this for objects we create but shouldn't be too much overhead for now + cg.store(var_name) + tmp_vars.append(var_name) + + for var_name in tmp_vars: + cg.append_output(cg.create_load(var_name)) + + cg.call_function(len(index_to_bytecode_constructor), False) + cg.pop_top() + + for idx, arg in enumerate(self.graphargs): + self.export_metadata.graph_input_idx_to_local_source[idx] = arg.source + + cg.make_call_generated_code(name) + + return cg.get_instructions(), cg.get_pycode() + + @property + def placeholders(self) -> list[fx.Node]: + return self.graph.find_nodes(op="placeholder") + + @property + def graphargs(self) -> list[GraphArg]: + return [node.meta["grapharg"] for node in self.placeholders] + + def call_user_compiler( + self, gm: fx.GraphModule, example_inputs: list[Tensor] + ) -> CompiledFn: + with dynamo_timed( + "OutputGraph.call_user_compiler", + phase_name="backend_compile", + log_pt2_compile_event=True, + log_waitcounter=True, + waitcounter_name_override="compile_aot_autograd", + dynamo_compile_column_us="aot_autograd_cumulative_compile_time_us", + ): + return self._call_user_compiler(gm, example_inputs) + + def _call_user_compiler( + self, gm: fx.GraphModule, example_inputs: list[Tensor] + ) -> CompiledFn: + if self.compiler_fn is None: + raise AssertionError("compiler_fn must not be None") + tot = 0 + placeholders = [] + for node in gm.graph.nodes: + if node.op in ("call_function", "call_method", "call_module"): + tot += 1 + if node.op == "placeholder": + placeholders.append(node) + increment_op_count(tot) + for pl in placeholders: + if not hasattr(pl, "_dynamo_source"): + arg = pl.meta["grapharg"] + # TODO: Why isn't this stored in meta :think: + # NOTE: can't move these into meta: https://github.com/pytorch/pytorch/issues/141640 + pl._dynamo_source = arg.source + + # NOTE: can't move these into meta: https://github.com/pytorch/pytorch/issues/141640 + gm._param_name_to_source = self.param_name_to_source # type: ignore[assignment] + gm._source_to_user_stacks = self.source_to_user_stacks # type: ignore[assignment] + + # Check for per-graph backend override (for debugging/bisecting) + compiler_fn = ( + get_backend_override_for_compile_id( + self.dynamo_compile_id, config.debug_backend_override + ) + or self.compiler_fn + ) + + # Check for per-graph inductor config override (for debugging/bisecting) + inductor_config_override = get_inductor_config_override_for_compile_id( + self.dynamo_compile_id, config.debug_inductor_config_override + ) + if inductor_config_override: + compiler_fn = _wrap_with_inductor_config( + compiler_fn, inductor_config_override + ) + + name = ( + compiler_fn.__name__ + if hasattr(compiler_fn, "__name__") + else "" + ) + from torch._higher_order_ops.passes.inline_invoke_subgraph import ( + inline_invoke_subgraph, + inline_single_use_invoke_subgraph, + ) + + if config.inline_invoke_subgraph: + gm = inline_invoke_subgraph(gm) + elif config.inline_single_use_invoke_subgraph: + gm = inline_single_use_invoke_subgraph(gm) + + try: + _step_logger()(logging.INFO, f"calling compiler function {name}") + if config.verify_correctness: + compiler_fn = WrapperBackend(compiler_fn) + compiled_fn = compiler_fn(gm, example_inputs) + _step_logger()(logging.INFO, f"done compiler function {name}") + if not callable(compiled_fn): + raise AssertionError("compiler_fn did not return callable") + except (TensorifyScalarRestartAnalysis, ShortenTraceback, IndexError): + # Re-raise IndexError so dim out-of-range errors from tensor ops + # propagate to the user as IndexError, not BackendCompilerFailed. + raise + except exceptions_allowed_to_be_fallback as e: + if self.has_user_defined_allowed_in_graph: + raise BackendCompilerFailed( + self.compiler_fn, e, inspect.currentframe() + ).with_traceback(e.__traceback__) from None + unimplemented_with_warning( + e, + self.root_tx.f_code, + gb_type="Backend compiler exception", + context=f"Backend: {name}\nException:{str(e)}\nTraceback:\n{self.root_tx.format_frame_summary()}", + explanation=f"Backend compiler `{name}` failed with {str(e)}. Adding a graph break.", + hints=[ + "Report an issue to the backend compiler repo.", + ], + ) + except SkipFrame: + # The backend compiler has requested that we skip the frame, instead of + # aborting execution. + raise + except Exception as e: + raise BackendCompilerFailed( + self.compiler_fn, e, inspect.currentframe() + ).with_traceback(e.__traceback__) from None + + signpost_event( + "dynamo", + "OutputGraph.call_user_compiler", + { + **self.co_fields, + "op_count": tot, + "node_count": len(gm.graph.nodes), + "input_count": len(placeholders), + }, + ) + + # pyrefly: ignore [bad-return] + return compiled_fn + + def dedup_pass(self) -> dict[str, torch.fx.GraphModule]: + if torch._dynamo.config.use_graph_deduplication: + return apply_graph_deduplication(self) + else: + return {} + + def install_subgraph(self, name: str, sub_gm: torch.fx.GraphModule) -> str: + next_name = get_unique_name_wrt(name, self.nn_modules, requires_suffix=True) + sub_gm.__name__ = next_name # type: ignore[assignment] + sub_gm.torchdynamo_force_dynamic = False # type: ignore[assignment] + # This graph module is not present in the user space, so it can't be + # accessed by a source. Set source=None. + self.register_attr_or_module(sub_gm, next_name, source=None) + return next_name + + def example_inputs(self) -> list[torch.Tensor]: + result = [arg.example for arg in self.graphargs] + # pyrefly: ignore[bad-return] + return result + + def remove_unused_get_attr_nodes(self) -> None: + for node in sorted(self.graph.find_nodes(op="get_attr"), reverse=True): + if len(list(node.users)) == 0: + self.remove_node(node) + + def remove_unused_graphargs(self) -> None: + # NB: It's OK to drop GraphArg for symbols that ended up being + # specialized iff they are not used in runtime assertions. You don't + # even have to make a guard for it, because ShapeEnv produce_guards + # operates on tracked_fakes, which never gets pruned. + # That being said, you'll get marginally better generated + # guard code if you promote the guard into a Dynamo guard (since that + # allows for the guard to be done using C++ guards.) If we get + # ShapeEnv guards to go into C++ guards, this will stop being a thing + # though! + + if not self.should_exit: + raise AssertionError("should_exit must be True before finalize") + + # Miniature DCE pass, but only for obviously trivial operations + def is_static_true(b_node: fx.node.Argument) -> bool: + if b_node is True: + return True + if not isinstance(b_node, fx.Node): + return False + b = b_node.meta.get("example_value") + if b is None: + return False + if b is True: + return True + if ( + isinstance(b, torch.SymBool) + and (r := b.node.maybe_as_bool()) is not None + ): + return r + # TODO: We can also technically remove all cases when the input + # doesn't have unbacked inputs, since it's all in the ShapeEnv + return False + + def is_symnode_arg(a: fx.node.Argument) -> bool: + from torch.fx.experimental.sym_node import SymTypes + + if isinstance(a, (int, float, bool)): + return True + if isinstance(a, fx.Node): + return isinstance(a.meta.get("example_value"), SymTypes) + return False + + # NB: We assume that you cannot do mutations on int/float/bool, + # because they are immutable types, and therefore is always safe to + # DCE. + def is_symnode_compute_node(node: fx.Node) -> bool: + from torch.fx.experimental.sym_node import SymTypes + + if node.op != "call_function": + return False + # TODO: I don't think it's possible to have a bare int/float here? + if not isinstance(node.meta.get("example_value"), SymTypes): + return False + # TODO: This will bail here if you ever end up with a more complicated + # computation function, like sum(list_of_ints), even though it + # should be DCE'able + if not all(is_symnode_arg(a) for a in node.args): + return False + if not all(is_symnode_arg(a) for a in node.kwargs.values()): + return False + return True + + from torch.fx.experimental.symbolic_shapes import is_accessor_node + + for node in reversed(list(self.graph.nodes)): + if len(list(node.users)) == 0: + if ( + node.op == "get_attr" + or (node.op == "call_function" and node.target is operator.getitem) + or ( + node.op == "call_function" + and node.target is torch._check + and is_static_true(node.args[0]) + ) + or is_symnode_compute_node(node) + or is_accessor_node(node) + ): + self.remove_node(node) + + def placeholder_binds_symbol(node: fx.Node) -> sympy.Symbol | None: + arg = node.meta["grapharg"] + example = arg.example + if isinstance(example, torch.SymInt) and isinstance( + example.node.expr, sympy.Symbol + ): + return example.node.expr + return None + + def remove_unused(node: fx.Node) -> None: + log.debug("REMOVE UNUSED GRAPHARG %s", node.meta["grapharg"].source.name) + # I'm not really sure why you need to delete these from the + # node since the node is going to get removed + del node.meta["grapharg"] + self.remove_node(node) + self.real_value_cache.pop(node, None) + + used_symbols: set[sympy.Symbol] = set() + + def update_used_symbols( + used_symbols: set[sympy.Symbol], fake: torch.SymInt | torch.Tensor + ) -> None: + used_symbols |= free_symbols(fake) + + recheck_placeholders = [] + for node in self.placeholders: + binds_symbol = placeholder_binds_symbol(node) is not None + # Don't delete symbol bindings yet + if binds_symbol: + if not node.users: + recheck_placeholders.append(node) + else: + if not node.users and not isinstance( + node.meta["grapharg"], BackwardStateGraphArg + ): + remove_unused(node) + else: + # Register the free symbols as uses + arg = node.meta["grapharg"] + if isinstance(arg, BackwardStateGraphArg): + continue + if isinstance(node.meta["grapharg"].example, torch.ScriptObject): + real_script_obj = node.meta["grapharg"].example + fake_script_obj = node.meta["grapharg"].example_strong_ref + if not torch._library.fake_class_registry.tracing_with_real( + real_script_obj + ): + flat_dict = dict(real_script_obj.__obj_flatten__()) # type: ignore[attr-defined] + for attr in flat_dict: + fake_attr_val = getattr( + fake_script_obj.wrapped_obj, attr + ) + pytree.tree_map_only( + (torch.SymInt, torch.Tensor), + lambda t: update_used_symbols(used_symbols, t), + fake_attr_val, + ) + continue + if is_custom_class(type(node.meta["grapharg"].example)): + continue + fake = ( + arg.fake_tensor if arg.fake_tensor is not None else arg.example + ) + update_used_symbols(used_symbols, fake) + + # After removing unused graphargs, prune unused binds_symbol + for node in recheck_placeholders: + symbol = placeholder_binds_symbol(node) + if symbol is not None: + if symbol not in used_symbols: + remove_unused(node) + else: + # Make sure we delete later occurrences of the same symbol + used_symbols.remove(symbol) + + def remove_tensorify_specialized_graphargs(self) -> None: + # This is a pretty interesting function. Basically we have this problem + # where our compiler tends to choke when we have unused inputs. The way + # we support dynamic float arguments is by doing a joint fx pass and + # tensorifying away as many symfloats as we can. For the remaining symfloats + # we have no choice but to specialize... HOWEVER at that point in time + # we can no longer remove graph inputs. So our sledgehammer solution is to + # save the state of what inputs we should have specialized in dynamo and + # restart analysis. This function incorporates this "view from the future" + # state and specializes inputs that we know we won't be able to tensorify + # away in the joint pass. In principle we shouldn't choke on unused inputs + # and so this shouldn't be necessary. In practice CUDA graphs choke on + # unused inputs so we need this for now. + + # Import here to prevent circular import + from torch._dynamo.symbolic_convert import TensorifyState + + for node in self.graph.nodes: + example_value = node.meta.get("example_value") + if ( + isinstance(example_value, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR + and example_value.item_memo is not None + and hasattr(example_value.item_memo.node._expr, "name") + and all(u.target == "item" for u in node.users) + and TensorifyState.should_specialize( + # We use _expr instead of expr b/c we want the symbol not the replacement + example_value.item_memo.node._expr.name + ) + ): + for u in list(node.users): + u.replace_all_uses_with(guard_scalar(example_value.item_memo)) + self.remove_node(u) + self.remove_node(node) + + def add_output_instructions( + self, prefix: list[Instruction], pycode: list[str] | None = None + ) -> None: + """ + We call this on the creation of a new compiled subgraph that is inserted + before user code. + An optional pycode argument can be passed to add python codegen along with + the bytecode. The generated python code should match the bytecode behavior + from the `prefix` argument. + """ + self.output_instructions.extend(prefix) + if not isinstance(pycode, (list, type(None))): + raise AssertionError("pycode must be a list of python code or None") + self.output_pycode.append(pycode) + self.should_exit = True + + def install_resume_function_global( + self, + name: str, + code: types.CodeType, + f_globals: dict[str, Any], + ) -> None: + """Install a resume function as a global. + + When the code has freevars, installs a factory that creates the + function with correct globals and closure (since MAKE_FUNCTION + inherits the current frame's globals, which is wrong for resume + functions from inlined frames). Otherwise installs the function + directly. + """ + if code.co_freevars: + + def _make_fn( + closure: tuple[types.CellType, ...], + ) -> types.FunctionType: + return types.FunctionType(code, f_globals, name, None, closure) + + self.install_global_unsafe(name, _make_fn) + else: + self.install_global_unsafe( + name, + types.FunctionType(code, f_globals, name), + ) + + def install_global_unsafe(self, name: str, value: Any) -> None: + """ + WARNING: prefer the safer `install_global_by_id/install_global`. + torch.compile instances should be independent of each other; + one footgun is to have one instance depend on the existence of + a global installed by another instance. This can happen if we mangle + a global the same way across both instances. + """ + if name in self.installed_globals: + raise AssertionError(f"global '{name}' is already installed") + self.installed_globals.add(name) + self.cleanups.append(CleanupHook.create(self.global_scope, name, value)) + + def install_global_by_id(self, prefix: str, value: Any) -> str: + """ + Installs a global if it hasn't been installed already. + This is determined by (prefix, id(value)) pair. + + Returns the name of the newly installed global. + """ + # NB: need self.compile_id to distinguish this global + # from another global created in a different torch.compile instance + name = f"{prefix}_{id(value)}_c{self.compile_id}" + if name in self.installed_globals: + return name + self.install_global_unsafe(name, value) + return name + + def install_global(self, prefix: str, value: Any) -> str: + """ + Installs a global, generating a unique name for it. + + Returns the name of the newly installed global. + """ + # NB: unique_id is unique, even across torch.compile instances + name = unique_id(prefix) + self.install_global_unsafe(name, value) + return name + + def cleanup(self) -> None: + # There is a reference cycle between tracer and OutputGraph, causing + # some of the tensor objects to be held alive for longer than necessary. + self.root_tx = None # type: ignore[assignment] + self.local_generators.clear() + self.nn_modules.clear() + self.used_inlined_inbuilt_modules_names.clear() + self.param_name_to_source = None + + for node in self.graph.nodes: + if "grapharg" in node.meta: + del node.meta["grapharg"] + self.real_value_cache.clear() + self.input_name_to_proxy.clear() + self._cached_replayed_side_effect_source_refs = tuple( + self.get_replayed_side_effect_source_refs() + ) + self.side_effects.clear() + self.variable_tracker_cache.clear() + self.mro_source_cache.clear() + self.guarded_mro_absent_keys.clear() + self.signature_cache.clear() + self.register_finalizer_fns.clear() + self.dynamo_flat_name_to_original_fqn.clear() + self.tracing_context.clear() + self.input_source_to_var.clear() + self.leaf_var_creation_order.clear() + self.unspec_variable_map.clear() + self.backward_state.clear() + + def add_graph_finalizer( + self, register_finalizer: Callable[[fx.GraphModule], None] + ) -> None: + self.register_finalizer_fns.append(register_finalizer) + + def example_value_from_input_node(self, node: torch.fx.Node) -> Any: + """Extract the non-fake example tensor""" + if node.op == "placeholder": + return node.meta["grapharg"].example + if node.op != "get_attr": + raise AssertionError(f"expected node.op to be 'get_attr', got '{node.op}'") + return self.nn_modules[node.target] # type: ignore[index] + + def add_fqn_info_for_inlined_modules( + self, inlined_module: torch.nn.Module, source: Source + ) -> None: + name = OutputGraph.module_key_name(source.name) + name = get_unique_name_wrt( + name, self.used_inlined_inbuilt_modules_names, self.global_scope + ) + self.used_inlined_inbuilt_modules_names.add(name) + + def register_leaf_name(leaf_name: str) -> None: + if self.param_name_to_source is None: + raise AssertionError("param_name_to_source must not be None") + new_source = self.get_chained_param_buffer_source(source, leaf_name) + new_name = f"{name}.{leaf_name}" + self.param_name_to_source[new_name] = new_source + if isinstance(source, LocalSource): + self.dynamo_flat_name_to_original_fqn[ + OutputGraph.module_key_name(new_source.name) + ] = leaf_name + + # annoying, but there are cases when we do not have parameters + # see test_nn_moduledict_contains + if hasattr(inlined_module, "_parameters"): + if ( + callable(inlined_module.named_parameters) + and inlined_module.named_parameters.__func__ # type: ignore[attr-defined] + is og_module_named_parameters_fn_ptr + ): + for leaf_name, _ in inlined_module.named_parameters(): + register_leaf_name(leaf_name) + if hasattr(inlined_module, "_buffers"): + if ( + callable(inlined_module.named_buffers) + and inlined_module.named_buffers.__func__ # type: ignore[attr-defined] + is og_module_named_buffers_fn_ptr + ): + for leaf_name, _ in inlined_module.named_buffers(): + register_leaf_name(leaf_name) + + +class DynamoTracerOutput: + error_on_graph_break: bool + is_tracing_resume_prologue: bool + output_graph: OutputGraph | None + # output_graph_for_cleanup is set even when there's an error, to allow + # cleanup of graph nodes to break reference cycles + output_graph_for_cleanup: OutputGraph | None + closure: tuple[Any, ...] | None + f_globals: dict[str, Any] + + def __init__( + self, tracer: "InstructionTranslatorBase", error: Any | None = None + ) -> None: + self.error_on_graph_break = tracer.error_on_graph_break + self.is_tracing_resume_prologue = tracer.is_tracing_resume_prologue + self.closure = tracer.closure + self.f_globals = tracer.f_globals + self.output_graph_for_cleanup = tracer.output + if error: + self.output_graph = None + else: + self.output_graph = tracer.output + + def _cleanup_output_graph(self) -> None: + output_graph = self.output_graph_for_cleanup + if output_graph: + # Lazy import to avoid a circular import (convert_frame imports + # output_graph at module load time). + from .convert_frame import _clear_fake_mode_weakrefs + + # A discarded restart/skip attempt fakified real tensors and built + # guards on them, leaving weakrefs on the real params that block + # torch.utils.swap_tensors after compile (issue #186796): guard + # create_fn partials hold a TensorWeakRef, and tensor_to_context / + # the describer memos / grapharg examples hold WeakIdRef/weakref. + # The end-of-compile clear_compile_context_weakrefs only clears the + # final attempt's tracing_context, never these discarded attempts, + # and never touches guards. Unlike that final clear (which is gated + # by config.invalidate_compile_context_weakrefs), the discard-path + # clear is unconditional: a discarded attempt has no consumers, so + # dropping its weakrefs can never break anything downstream. + # Drop grapharg examples first, before clearing nodes drops the meta. + for node in output_graph.graph.nodes: + if "grapharg" in node.meta: + del node.meta["grapharg"] + for tracer in output_graph.tracers: + tracer.graph._clear_nodes() + output_graph.guards.clear() + tc = output_graph.tracing_context + tc.tensor_to_context.clear() + # Clear the describer weakrefs from both the current tracing_context + # fake_mode and the _old_fake_mode saved during compile: on a + # backend-raised restart (e.g. TensorifyScalarRestartAnalysis), + # tracing_context.fake_mode has already been swapped to a fresh + # empty backend fake_mode, so the real-param weakrefs live on + # _old_fake_mode instead. + _clear_fake_mode_weakrefs(tc.fake_mode) + if hasattr(output_graph, "_old_fake_mode"): + _clear_fake_mode_weakrefs(output_graph._old_fake_mode) + # Also clear tracked_fakes to break the + # FakeTensorMode -> ShapeEnv -> TrackedFake -> FakeTensor cycle. + if tc.fake_mode and tc.fake_mode.shape_env: + tc.fake_mode.shape_env.tracked_fakes = None + + +err_epilogue = ( + "With the current config, we will graph break " + "(and fall back to eager-mode PyTorch) on all ops " + "that have do not have the 'pt2_compliant_tag'. " + "Please see the following doc for how to mark this op as PT2 compliant " + "https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html" +) + + +def check_pt2_compliant_op( + output_graph: OutputGraph, kind: str, target: Any, args: Any, kwargs: Any +) -> None: + if kind != "call_function": + return + + def encountered_compliant_op(target: torch._ops.OpOverload) -> None: + if target.namespace in {"prim", "prims", "aten"}: + return + output_graph.compliant_custom_ops.add(target) + + def encountered_non_compliant_op(target: torch._ops.OpOverload, msg: str) -> None: + output_graph.non_compliant_ops.add(target) + if config.only_allow_pt2_compliant_ops: + unimplemented( + gb_type="Encountered non-PT2-compliant op", + context="", + explanation=msg + " " + err_epilogue, + hints=[], + ) + + if isinstance(target, torch._ops.OpOverload): + if torch.Tag.pt2_compliant_tag in target.tags: + encountered_compliant_op(target) + return + encountered_non_compliant_op( + target, + f"Encountered the torch.ops.OpOverload {target} that is not PT2 compliant.", + ) + return + + if isinstance(target, torch._ops.OpOverloadPacket): + overloads = tuple(target.overloads()) + # Optimization: Overload resolution is expensive. + # If there's only one overload, we know what it will resolve to. + if len(overloads) == 1: + op = getattr(target, overloads[0]) + if torch.Tag.pt2_compliant_tag in op.tags: + encountered_compliant_op(op) + return + encountered_non_compliant_op( + op, + f"Encountered the non-overloaded " + f"torch.ops.OpOverloadPacket {target} " + f"that is not PT2 compliant. ", + ) + return + + args, kwargs = torch._dynamo.utils.get_fake_values_from_nodes( + output_graph.current_tx, (args, kwargs), False + ) + try: + overload = torch._C._jit_resolve_packet( + target._qualified_op_name, *args, **kwargs + ) + except RuntimeError as e: + unimplemented( + gb_type="Error when attempting to resolve op packet", + context="", + explanation=str(e), + hints=[], + ) + + op = getattr(target, overload) + if torch.Tag.pt2_compliant_tag in op.tags: + encountered_compliant_op(op) + else: + encountered_non_compliant_op( + op, + f"Encountered the torch.ops.OpOverloadPacket {target} " + f"which resolves to the overload ({overload}) that is " + f"not PT2 compliant.", + ) + + +_compile_id_counter = itertools.count() + +P = ParamSpec("P") +R = TypeVar("R") + + +class LazyProxy: + def __init__( + self, + tracer: "SubgraphTracer", + fn: Callable[P, R], + *args: P.args, + **kwargs: P.kwargs, + ) -> None: + self.tracer = tracer + # pyrefly: ignore [invalid-type-var] + self.fn = fn + self.args = args + self.kwargs = kwargs + + def __call__(self) -> Any: + return self.fn(*self.args, **self.kwargs) + + +class SubgraphTracer(fx.Tracer): + """ + Holds an FX graph that is being traced. OutputGraph owns a SubgraphTracer + and the separation of responsibilities is that SubgraphTracer is + responsible for building the graph while OutputGraph is responsible for + compiling and executing the graph. + """ + + def __init__( + self, + output_graph: "OutputGraph", + parent: Optional["SubgraphTracer"] = None, + is_export: bool = False, + source_target: Target | None = None, + description: str | None = None, + ) -> None: + super().__init__() + self.output_graph = weakref.proxy(output_graph) + self.graph = torch.fx.Graph() + + # See note [Export inputs must be explicitly passed in] + self.is_export = is_export + # Map from graph input name to its placeholder proxy object, where the + # map's keys give all current placeholder node names and can be used to + # create unique node names + self.input_name_to_proxy: dict[str, fx.Proxy] = {} + # Node => computed real value (see utils.get_real_value) + self.real_value_cache: dict[fx.Node, torch.Tensor] = {} + + # SubgraphTracers can be nested. See NOTE [HigherOrderOperator tracing design] + self.parent = parent + self.source_target = source_target + self.description = description + # A dict mapping previously free variables (Proxy objects) + # to new Proxy objects that wrap inputs to this subgraph. + # + # This dict maps proxies in outer graphs to placeholders in current graph. + # It serves two purposes: + # - Proxies are associated with VariableTrackers. If we see + # the same VariableTracker twice (and it is a free variable), + # then we want to use the same Proxy in the current subgraph to + # record the tracing. + # - If we are tracing a HigherOrderOperator's body_fn, then we + # need to keep track of what free variables were lifted so we can + # rewrite the HigherOrderOperator call using the traced body_fn. + # Dicts maintain the order of args for the HigherOrderOperator call. + self.lifted_freevars: dict[fx.Proxy, fx.Proxy] = {} + + # map basic symbols (unbacked and unbacked) to their bound proxies. + # There are only two cases where bound_symbols will be recorded: + # 1. when we create_graph_input for a backed SymInt that's basic symbol + # 2. when we track_produced_symints for intermediate results + # bound_symbols always map the symbol to the proxy whose + # tracer is the current tracer that's readily accessible in current tracer's graph. + self.bound_symbols: dict[sympy.Symbol, torch.fx.Proxy | LazyProxy] = {} + + # Maps _DynamicScalar object ids to allocated SymInt nodes, for symbol reuse + self.dynamic_scalar_nodes: dict[int, torch.SymInt] = {} + + self.prev_inst = None + # True if we want to allow externally visible side-effects (doesn't throw error on their existence) + # during this tracer's tracing. This is currently only used by experimental AC out-of-tree + # via torch._dynamo.utils._disable_side_effect_safety_checks_for_current_subtracer. + # Note: Externally visible side-effects are allowed if this flag OR the above flag is True. + self.unsafe_allow_externally_visible_side_effects = False + self.traced_with_externally_visible_side_effects = False + # True if we want to allow side effects by returning them as extra outputs from the subgraph. + # This is set when enable_side_effects_in_hop=True for HOPs like invoke_subgraph + # and checkpoint (when skip_fwd_side_effects_in_bwd_under_checkpoint config is True). + self.allow_side_effects_in_hop = False + # User code stack at the point where an externally-visible side effect + # was first detected and allowed (not raised). None means no side + # effect; non-None means one occurred. + self.side_effect_stack: traceback.StackSummary | None = None + # All sources accessed via VariableBuilder (and cell loads) during + # this subtracer's trace. Used by invoke_subgraph reuse to collect + # guards and detect mutations on captured variables. + self.traced_sources: OrderedSet[Source] = OrderedSet() + + # True if this tracer is currently tracing (reconstructing) into a Python generator + self.is_reconstructing_generator = False + + self.debug_level: int = parent.debug_level + 1 if parent is not None else 0 + + self._cur_code = None + self._orig_gm_meta: list[Any] | None = None + self._orig_gm_lineno_map: dict[int, int | None] | None = None + self._orig_gm_firstlineno: int | None = None + # Each SubgraphTracer is associated with a source target, which indicates + # which operator this subgraph is attached to. We compute a source_fn_stack + # based on the source target. For the root tracer, it's set to []. + # This is useful for debugging and transforming the exported graph. + if self.parent is None: + self.source_fn_stack: list[Any] = [] + elif source_target is None: + self.source_fn_stack = self.parent.source_fn_stack[:] + else: + self.source_fn_stack = self.parent.source_fn_stack + [ + (self.graph._target_to_str(source_target), source_target) + ] + + # This is used to create a unique name for the placeholder + self._used_names: OrderedSet[str] = OrderedSet() + # Stores the versions of the input tensors at the time they are inserted + # as placeholders in the graph. This is used to track input mutation. + self._input_versions_at_beginning: list[int] = [] + if torch.is_inference_mode_enabled(): + raise RuntimeError( + "Inference mode is supposed to be disabled during compilation. Please open an issue." + ) + + self.tracked_proxyable_vt: OrderedSet[VariableTracker] = OrderedSet() + + def record_proxyable_vt(self, vt: VariableTracker) -> None: + self.tracked_proxyable_vt.add(vt) + + # preserve original meta if it is available + def _maybe_preserve_original_meta( + self, tx: "InstructionTranslatorBase", node: fx.Node + ) -> None: + if ( + self._orig_gm_meta + and self._orig_gm_lineno_map + and self._orig_gm_firstlineno + ): + lineno = tx.current_instruction.starts_line + node_idx = None + if lineno is not None: + node_idx = self._orig_gm_lineno_map.get( + lineno - self._orig_gm_firstlineno, None + ) + if node_idx is not None: + meta = self._orig_gm_meta[node_idx] + for field in fx.proxy._COPY_META_FIELDS: + if field in meta: + node.meta[field] = meta[field] + if "stack_trace" in meta: + node.meta["stack_trace"] = meta["stack_trace"] + + def create_proxy( + self, + kind: str, + target: Any, + args: Any, + kwargs: Any, + name: str | None = None, + type_expr: Any | None = None, + proxy_factory_fn: Callable[[fx.Node], fx.Proxy] | None = None, + ) -> fx.Proxy: + _t0 = time.time_ns() + try: + return self._create_proxy( + kind, target, args, kwargs, name, type_expr, proxy_factory_fn + ) + finally: + self.output_graph.bytecode_tracing_timings.create_proxy_ns += ( + time.time_ns() - _t0 + ) + + def _create_proxy( + self, + kind: str, + target: Any, + args: Any, + kwargs: Any, + name: str | None = None, + type_expr: Any | None = None, + proxy_factory_fn: Callable[[fx.Node], fx.Proxy] | None = None, + ) -> fx.Proxy: + # NOTE: [Nested SubgraphTracer and free_variable handling] + # -------------------------------------------------------- + # Read NOTE [HigherOrderOperator tracing design] first. + # + # Let's say we're in the middle of introspecting the body of a possibly + # nested HigherOrderOperator, and we see a free variable. + # + # There are two cases: + # 1. We see a free variable that is already tracked by Dynamo. + # 2. We see a free variable that has not been tracked by Dynamo + # + # In case 1, we call `maybe_lift_tracked_freevar_to_input` (below) + # which will lift the freevar to be an input of this subgraph + # and also recursively lift it to be an input on the parent(s). + # + # In case 2, before the call to `create_proxy`, the InstructionTranslator + # will see the freevar when it gets loaded by Python bytecode. + # E.g. for Python 3.11 the bytecodes that may do this are LOAD_DEREF or + # LOAD_GLOBAL. + # There, the InstructionTranslator asks Dynamo to begin tracking the + # freevar by building a new Variable. + # Building a new Variable automatically lifts the freevar to be an + # input of the root SubgraphTracer. + # + # The implications for the code below are: + # - We will always be in Case 1 when we get to this code. + # - Any "free variable" we encounter here is guaranteed to already be + # bound, that is, it is either a graph input of the root graph, or + # some local variable of the root graph or a subgraph. + # - The additional work we need to do here is *only* that we need to + # lift this free variable into inputs (recursively) of each nested + # higher-order-op subgraph until we hit the subgraph where the free + # variable is bound + if self.parent is not None: + flat_args, tree_spec = pytree.tree_flatten((args, kwargs)) + new_flat_args = [] + for arg in flat_args: + maybe_new_arg = self.maybe_lift_tracked_freevar_to_input(arg) + new_flat_args.append(maybe_new_arg) + + args, kwargs = pytree.tree_unflatten(new_flat_args, tree_spec) + + rv = super().create_proxy( + kind, + target, + args, + kwargs, + name, + type_expr, + proxy_factory_fn, # type: ignore[arg-type] + ) + + # append stack trace to fx node + tx = self.output_graph.current_tx + + # log detailed location of line of code in 3.11 + if sys.version_info >= (3, 11) and kind in ( + "call_function", + "call_method", + "call_module", + ): + cur_inst = tx.current_instruction + if ( + cur_inst is not self.prev_inst + and cur_inst.positions is not None + and cur_inst.positions.lineno is not None + ): + tx_code = tx.f_code + header = tx.get_line_of_code_header(lineno=cur_inst.positions.lineno) + + def get_trace_call_log_str() -> str: + line = get_instruction_source_311(tx_code, cur_inst).rstrip() + return f"TRACE FX call {rv.node.name} from {header}\n{line}" + + trace_call_log.debug("%s", LazyString(get_trace_call_log_str)) + self.prev_inst = cur_inst + + # update reference to original meta if we're tracing a new code object + is_retracing = False + if tx.f_code is not self._cur_code: + orig_graphmodule_maybe = code_context.get_context(tx.f_code).get( + "orig_graphmodule", lambda: None + )() + if isinstance(orig_graphmodule_maybe, torch.fx.GraphModule): + is_retracing = True + self._orig_gm_meta = [ + nd.meta for nd in orig_graphmodule_maybe.graph.nodes + ] + self._orig_gm_lineno_map = orig_graphmodule_maybe._lineno_map + self._orig_gm_firstlineno = ( + orig_graphmodule_maybe.forward.__code__.co_firstlineno + ) + else: + self._orig_gm_meta = None + self._orig_gm_lineno_map = None + self._orig_gm_firstlineno = None + nn_module_stack = tx.nn_module_stack + if nn_module_stack: + rv.node.meta["nn_module_stack"] = nn_module_stack.copy() + + if kind in {"call_function", "call_method"}: + stack = (rv.node.name, target) + if nn_module_stack: + # Current codebase assumes that the nn_module_stack has the + # builtin modules in the stack. + current_nn_module = list(rv.node.meta["nn_module_stack"].values())[-1][ + 1 + ] + if current_nn_module.__module__.startswith( + ("torch.nn.modules", "torch.ao.") + ) and not current_nn_module.__module__.startswith( + "torch.nn.modules.container" + ): + stack = (rv.node.name, current_nn_module) + + rv.node.meta["source_fn_stack"] = self.source_fn_stack + [stack] + elif kind == "call_module": + if self.parent is not None: + unimplemented( + gb_type="Invoking an nn.Module inside a higher order operator", + context=f"Higher order op name: {self.source_target}", + explanation="This is not supported.", + hints=[], + ) + # For modules we store the class + rv.node.meta["source_fn_stack"] = self.source_fn_stack + [ + ( + rv.node.name, + next( + ty + for k, (_, ty) in rv.node.meta["nn_module_stack"].items() + if k.split("@")[0] == target + ), + ) + ] + + self._maybe_preserve_original_meta(tx, rv.node) + + if not is_retracing: + if "nn_module_stack" not in rv.node.meta: + nn_module_stack = tx.nn_module_stack + if nn_module_stack: + rv.node.meta["nn_module_stack"] = nn_module_stack.copy() + + if "source_fn_stack" not in rv.node.meta: + if kind in {"call_function", "call_method"}: + rv.node.meta["source_fn_stack"] = self.source_fn_stack + [ + (rv.node.name, target) + ] + elif kind == "call_module": + if self.parent is not None: + unimplemented( + gb_type="Invoking an nn.Module inside a HigherOrderOperator", + context="", + explanation="This is not supported.", + hints=[], + ) + # For modules we store the class + rv.node.meta["source_fn_stack"] = self.source_fn_stack + [ + ( + rv.node.name, + rv.node.meta["nn_module_stack"][target][1], + ) + ] + + if "stack_trace" not in rv.node.meta: + frame_summaries: list[traceback.FrameSummary] = [] + while tx: + # Avoid frame summaries from inside the torch/nn/modules. This ensures that we keep the stack trace of + # the user code. + if not tx.is_co_filename_from_nn_modules(): + frame_summaries.append(tx.frame_summary()) + tx = getattr(tx, "parent", None) + + filtered_frame_summaries = [ + frame + for frame in frame_summaries + if frame.filename not in uninteresting_files() + ] + + # Reverse the frame_summaries, such that the innermost frame is at the last + filtered_frame_summaries.reverse() + + # official from_list stub doesn't have new-style type + msgs = traceback.StackSummary.from_list(filtered_frame_summaries).format() + rv.node.stack_trace = "".join(msgs) + + if ( + torch._dynamo.config.use_graph_deduplication + or torch._dynamo.config.track_nodes_for_deduplication + ): + self.output_graph.region_tracker.track_node( + self.output_graph.current_tx, rv.node + ) + return rv + + def create_node( + self, + kind: str, + target: Target, + args: Any = None, + kwargs: Any = None, + name: str | None = None, + type_expr: Any | None = None, + ) -> fx.Node: + check_pt2_compliant_op(self.output_graph, kind, target, args, kwargs) + if self.parent is not None: + flat_args = pytree.arg_tree_leaves(*args, **kwargs) + for arg in flat_args: + if not isinstance(arg, torch.fx.Node): + continue + if arg.graph != self.graph: + raise AssertionError( + "create_node using arg not from this SubgraphTracer" + ) + + node = super().create_node(kind, target, args, kwargs, name, type_expr) + node.meta["creation_timestamp"] = self.output_graph.timestamp + self._used_names.add(node.name) + return node + + # Note: we did not override erase_node since + # we call self.graph.erase_node elsewhere + def remove_node(self, node: fx.Node) -> None: + if len(node.users) > 0: + user_graph_nodes: list[torch.fx.Node] = [] + for user in node.users: + # For the case where user.graph == self.graph, that is a real bug and will raise + # properly. + if user.graph != self.graph: + # This is a nested graph, which needs to be deleted. + # If we do not do this, we will raise on attempting to remove this. + # As we only get here during restoration cleanup, this is sound. + user_graph_nodes.extend(reversed(list(user.graph.nodes))) + for other_graph_node in user_graph_nodes: + other_graph_node.graph.erase_node(other_graph_node) + self.graph.erase_node(node) + self.input_name_to_proxy.pop(node.name, None) + + # when before=True, we will insert this input before the most recent + # inserted proxy. This is a hack to get around an ordering problem, + # where we first insert a tensor argument, and then insert bindings + # for SymInts that may occur in the tensor argument. + # Remove this if https://github.com/pytorch/pytorch/issues/99007 gets + # fixed. + def create_graph_input( + self, + name: str, + type_expr: Any, + example_value: Any, + before: bool = False, + source: Source | None = None, + ) -> fx.Proxy: + if isinstance(example_value, torch.Tensor): + self._input_versions_at_beginning.append(example_value._version) + log.debug( + "create_graph_input %s %s %s at debug_level %s before=%s", + name, + source.name if source is not None else "(none)", + example_value, + self.debug_level, + before, + ) + if source is None: + if self.parent is None: + raise AssertionError( + f"you are required to provide a source for inputs {name} example_val {example_value} on the root tracer" + ) + + # Note [Export inputs must be explicitly passed in] + # In eager, we are generally OK with adding graph inputs whenever we + # want, because we take care of writing the bytecode that knows how + # to source all the inputs. + # + # In export, this is bad, because you want a self-contained export + # object which only depends on the inputs you explicitly passed to it. + # So we are a bit more strict about what sources can become inputs + # in export + if self.is_export and self.parent is None: + if source is None: + raise AssertionError( + "source must not be None for export root tracer inputs" + ) + if not is_from_local_source(source, only_allow_input=True): + self.output_graph.source_to_user_stacks.setdefault(source, []).append( + TracingContext.extract_stack() + ) + + # _used_names contains the names of all the nodes in the graph, + # including intermediates. This ensures that we do not have a name + # collision. + name = get_unique_name_wrt(name, self._used_names) + if self.input_name_to_proxy: + prev_name = next(reversed(self.input_name_to_proxy)) + node = self.input_name_to_proxy[prev_name].node + if before: + ctx = self.graph.inserting_before(node) + else: + ctx = self.graph.inserting_after(node) + else: + ctx = self.graph.inserting_before(None) + with ctx: + proxy = self.create_proxy("placeholder", name, (), {}, type_expr=type_expr) + set_example_value(proxy.node, example_value) + if self.input_name_to_proxy and before: + k, v = self.input_name_to_proxy.popitem() + self.input_name_to_proxy[name] = proxy + self.input_name_to_proxy[k] = v + else: + self.input_name_to_proxy[name] = proxy + + # For placeholder nodes, `name` is passed as a str to the target, + # and then torch.fx decides the node.name. So, record the `target` + # name as well in the _used_names to prevent any collision. + self._used_names.add(name) + + # NOTE: [Auto lift basic free symbols when create_graph_input] + # There are two sources of basic symbols: + # + # - They can come from inputs, e.g. when an input tensor is specified as dynamic. We handle + # this case by intercepting at create_graph_input. Whenever we call create_graph_input, we + # try to also lift the basic symbols in example values as graph input. + # + # 1. When create_graph_input for a tensor that has symbolic shapes, + # we look for basic symbols in its size and stride, we check if the symbol is bound + # in current graph (i.e. bound_symbols), if it's not bound, we'll create a placeholder + # for it then recursively check its parent, creates ph if not bound at parent until. + # reachting the top-level, where we require a source is attached to the proxy. + # + # 2. When create_graph_input for a tensor that contains compound exprs, + # for example, if an input to subgraph takes size [s1+s2//8], we'll look for the + # the free basic symbols in the sizes and lift all of them following 1. + # + # 3. When create_graph_input for a symint. The following invariants hold: + # a. if symint's expr is a basic symbol, we only lift it once. + # b. if symint's expr is compuned, we lift the expr as a single input. We won't lift The basic symbols + # in the compuned expr are NOT lifted. Because if the basic symbols are used inside the subgraph + # they will be lifted according to 3.a + # + # - They can come from intermediate results: + # For example, data-dependent operators such as t.item(), t.nonzero(), where basic symbols + # might be created. For this purpose, we track the basic symbols of intermediate results + # immediately after they're created at wrap_fx_proxy with track_produced_symints. Notice + # that for basic symbols that're already tracked by create_graph_input, we won't track it again. + # + # Also see NOTE: [Export inputs must be explicitly passed in] + is_strict_export = self.is_export + # Use is_exporting() (not is_compiling()) to detect non-strict + # export. is_compiling() is now also True during regular + # torch.compile sessions, but only export sets is_exporting(). + is_non_strict_export = torch.compiler.is_exporting() + if not is_strict_export and not is_non_strict_export: + if isinstance(example_value, torch.Tensor): + self._lift_basic_symbols(example_value, source) + elif isinstance(example_value, (list, tuple)): + for i, e in enumerate(example_value): + if not isinstance(e, torch.Tensor): + continue + + e_source = None + if source: + e_source = GetItemSource( + base=source, + index=i, + index_is_slice=False, + ) + + self._lift_basic_symbols(e, e_source) + + # Bound the symbol to ph if example_value is a SymInt with basic symbol. + if isinstance(example_value, torch.SymInt) and isinstance( + example_value.node.expr, sympy.Symbol + ): + self.bound_symbols[example_value.node.expr] = proxy + return proxy + + # See NOTE: [Nested SubgraphTracer and free_variable handling] for more details + def lift_tracked_freevar_to_input(self, proxy: fx.Proxy) -> LazyProxy | fx.Proxy: + # You're doing something wrong if we are the root SubgraphTracer because + # Dynamo adds tensors to graph inputs before creating a proxy for them. + if self.parent is None: + raise AssertionError( + "lift_tracked_freevar_to_input should not be called on root SubgraphTracer" + ) + + example_value = proxy.node.meta["example_value"] + + # To avoid lifting the same symbol twice, we check whether basic symbols has been tracked. + # For example, the basic symbols may have already been lifted for current subgraph when + # we automatically lift basic symbols in the sizes/strides of a tensor t. + # Suppose parent graph calls sz = t.size()[0], it creates + # a proxy in parent and the subgraph accesses sz via closure. sz's proxy is not tracked + # in current sub-tracer so we may lift the same symbol twice. + if ( + isinstance(example_value, torch.SymInt) + and example_value.node.expr in self.bound_symbols + ): + return self.bound_symbols[example_value.node.expr] + + # Proxies are associated with VariableTracker. + # It is possible that we've already lifted the Proxy to be an input. + # If that is the case, just return the already lifted Proxy. + if proxy in self.lifted_freevars: + return self.lifted_freevars[proxy] + + # We first lift proxy to parent's graph then lift to current graph's input + # so that when we bind symints of the sizes in current graph, those symints + # would already be lifted as inputs to parent graph. + if proxy.tracer != self.parent: + self.parent.lift_tracked_freevar_to_input(proxy) + + # Wrapper subclasses (e.g. DTensor) from dynamo-disabled regions may not + # have had track_produced_symints called, causing _lift_basic_symbols to + # hit "Source of 'sN' is None" when lifting inner tensor symbols. + if ( + isinstance(example_value, torch.Tensor) + and is_traceable_wrapper_subclass(example_value) + and proxy.tracer is self.parent + ): + self.parent.track_produced_symints(example_value, proxy) + + example_value = proxy.node.meta["example_value"] + type_expr = ( + type(example_value.real_obj) + if isinstance(example_value, FakeScriptObject) + else type(example_value) + ) + new_proxy = self.create_graph_input(proxy.node.name, type_expr, example_value) + self.lifted_freevars[proxy] = new_proxy + return new_proxy + + def maybe_lift_tracked_freevar_to_input(self, arg: Any) -> Any: + """ + If arg is a free variable, then lift it to be an input. + Returns the new lifted arg (if arg was a freevar), else the + original arg. + """ + if not isinstance(arg, torch.fx.Proxy): + # Note: arg can be a python built-in slice type e.g. + # x[:max_seq] is represented as get_item(t, (slice(None, max_seq, None))) + # we need to also look into the slice variable itself to lift the + # proxies there. + if isinstance(arg, slice): + return slice( + *( + self.maybe_lift_tracked_freevar_to_input(sub_arg) + for sub_arg in (arg.start, arg.stop, arg.step) + ) + ) + else: + return arg + elif arg.tracer == self: + return arg + return self.lift_tracked_freevar_to_input(arg) + + # See NOTE: [Auto lift basic free symbols when create_graph_input] for overall design + # You MUST call this API every time when creating a proxy in wrap_fx_proxy for a call + # that produced symints or tensors with unbacked symint shapes. + # This function is used to track the symints with its proxies created during + # dynamo tracing so that subgraph knows how to bind a symbol input with parent's proxy. + # LazyProxy are created for tensor shapes that're unbacked so that we don't create proxies + # for symbols that're not going to be used, the LazyProxy will be turned into a proxy + # when it's lifted as input to subgraph. + def track_produced_symints( + self, example_value: Any, e_proxy: LazyProxy | torch.fx.Proxy + ) -> None: + # When binding the symbols in an example_value, we bind the symbols + # to the proxy's associated Tracer instead of current tracer. + # This is because: + # 1. We may be calling wrap_tensors during speculate_subgraph because + # the variables are lazily realized. The proxy are top-level phs but + # current tracer is a subtracer. + # 2. For autograd.Function, we trace the backward graph with a new tracer + # whose parent is the forward tracer, but we're using all the proxies created + # in forward tracer to trace the backward. + # For example, forward calls save_for_backward for a input tensor t. + # Backward calls t.tolist(). In this case, all the proxies that backward tracer + # sees are from parent tracer (i.e. the forward tracer). (e.g. t[0].item()) + # See test_validate_outputs_unbacked for repro on 2. + tracer = e_proxy.tracer + if not isinstance(tracer, SubgraphTracer): + raise AssertionError(f"tracer must be a SubgraphTracer, got {type(tracer)}") + + def need_bind(s: Any) -> bool: + from torch.fx.experimental.symbolic_shapes import is_symbolic + + return ( + is_symbolic(s) + and isinstance(s.node.expr, sympy.Symbol) + and s.node.expr not in self.bound_symbols + ) + + def _proxy_with_example_value( + example_value: Any, *args: Any, **kwargs: Any + ) -> fx.Proxy: + # We need to insert proxy for creating sym_size/sym_stride/sym_storage right after e_proxy + nonlocal e_proxy + e_proxy = e_proxy() if isinstance(e_proxy, LazyProxy) else e_proxy + if not isinstance(e_proxy, torch.fx.Proxy): + raise AssertionError( + f"e_proxy must be an fx.Proxy, got {type(e_proxy)}" + ) + with tracer.graph.inserting_after(e_proxy.node): + proxy = tracer.create_proxy(*args, **kwargs) + set_example_value(proxy.node, example_value) + return proxy + + if isinstance(example_value, torch.Tensor): + for i, s in enumerate(example_value.size()): + if need_bind(s): + log.debug( + "track_produced_symints %s for %s.size()[%s] at debug_level %s", + s, + e_proxy, + i, + tracer.debug_level, + ) + lazy_proxy = LazyProxy( + tracer, + _proxy_with_example_value, + s, + "call_function", + torch.ops.aten.sym_size.int, + (e_proxy, i), + {}, + type_expr=type(s), + ) + self.track_produced_symints(s, lazy_proxy) + + storage_offset = example_value.storage_offset() + if need_bind(storage_offset): + log.debug( + "track_produced_symints %s for %s.storage_offset() at debug_level %s", + storage_offset, + e_proxy, + tracer.debug_level, + ) + lazy_proxy = LazyProxy( + tracer, + _proxy_with_example_value, + storage_offset, + "call_function", + torch.ops.aten.sym_storage_offset, + (e_proxy,), + {}, + type_expr=type(storage_offset), + ) + self.track_produced_symints(storage_offset, lazy_proxy) + + if example_value.layout is torch.strided: + for i, s in enumerate(example_value.stride()): + if need_bind(s): + log.debug( + "track_produced_symints %s for %s.stride()[%s] at debug_level %s", + s, + e_proxy, + i, + tracer.debug_level, + ) + lazy_proxy = LazyProxy( + tracer, + _proxy_with_example_value, + s, + "call_function", + torch.ops.aten.sym_stride.int, + (e_proxy, i), + {}, + type_expr=type(s), + ) + self.track_produced_symints(s, lazy_proxy) + + elif example_value.layout is torch.sparse_coo: + self.track_produced_symints(example_value._indices(), e_proxy) + self.track_produced_symints(example_value._values(), e_proxy) + elif example_value.layout in {torch.sparse_csr, torch.sparse_bsr}: + self.track_produced_symints(example_value.crow_indices(), e_proxy) + self.track_produced_symints(example_value.col_indices(), e_proxy) + elif example_value.layout in {torch.sparse_csc, torch.sparse_bsc}: + self.track_produced_symints(example_value.ccol_indices(), e_proxy) + self.track_produced_symints(example_value.row_indices(), e_proxy) + if is_traceable_wrapper_subclass(example_value): + attrs, ctx = example_value.__tensor_flatten__() + for attr in attrs: + inner_t = getattr(example_value, attr) + self.track_produced_symints(inner_t, getattr(e_proxy, attr)) + elif isinstance(example_value, torch.SymInt): + if need_bind(example_value): + expr = example_value.node.expr + tracer.bound_symbols[expr] = e_proxy + + # See Note [Auto lift basic free symbols when create_graph_input] + def _lift_basic_symbols( + self, example_value: torch.SymInt | torch.Tensor, src: Source | None + ) -> None: + # The before arg is for inserting symints in the sizes/strides of a tensor + # before the tensor. This ordering ensures that when we look at the tensor's + # symbols, they're already lifted/tracked. E.g. this assumption is used + # in insert_deferred_runtime_asserts. + def _lift_symbols_in_symint( + s: int | torch.SymInt, + source: Source | None, + before: bool = False, + ) -> None: + if not is_symbolic(s): + return + + if not isinstance(s, torch.SymInt): + raise AssertionError(f"s must be a SymInt, got {type(s)}") + self_to_be_bound = self.lookup_unbound_symbols(s) + if len(self_to_be_bound) == 0: + return + + # For subgraph + if self.parent is not None: + # Recursively lift symbols in symint until top-level. + self.parent._lift_basic_symbols(s, source) + for s0 in self_to_be_bound: + parent_proxy = self.parent.bound_symbols[s0] + example_val = parent_proxy.node.meta["example_value"] # type: ignore[union-attr] + if not isinstance(example_val, torch.SymInt): + raise AssertionError( + f"example_val must be a SymInt, got {type(example_val)}" + ) + ph = self.create_graph_input( + str(s0), + type(example_val), + example_val, + before=before, + source=source, + ) + log.debug( + "_lift_symbols_in_symint %s from %s at debug_level %s", + s0, + source.name if source is not None else "subgraph inputs", + self.debug_level, + ) + self.lifted_freevars[parent_proxy] = ph # type: ignore[index] + # For root_tracer: + else: + if len(self_to_be_bound) != 1: + raise AssertionError( + f"For root tracer, we only expect to bind basic symbols (compound symbols " + f"should be cached before) but got unbound symbols {self_to_be_bound} in {s}" + ) + if source is None: + raise AssertionError( + f"Source of '{s}' is None when lifting it to input of top-level. If it's an unbacked symbol, " + "this could be because it's not tracked with lazy_bind_unbacked_symbols. " + f"Otherwise, should provide a source when create_graph_input for `{s}` at root tracer." + ) + s0 = next(iter(self_to_be_bound)) + ph = self.create_graph_input( + str(s0), + type(s), + s, + before=before, + source=source, + ) + log.debug( + "_lift_symbols_in_symint %s from %s at debug_level %s", + s, + source.name if source is not None else "subgraph inputs", + self.debug_level, + ) + ph.node.meta["grapharg"] = GraphArg( + source, + s, + pass_arg_as_tensor=False, + fake_tensor=None, + is_tensor=False, + ) + + if isinstance(example_value, torch.Tensor): + for i, s in enumerate(example_value.size()): + _lift_symbols_in_symint( + s, + ( + TensorPropertySource(src, TensorProperty.SIZE, i) + if src is not None + else None + ), + before=True, + ) + if example_value.layout is torch.strided: + for i, s in enumerate(example_value.stride()): + _lift_symbols_in_symint( + s, + ( + TensorPropertySource(src, TensorProperty.STRIDE, i) + if src is not None + else None + ), + before=True, + ) + _lift_symbols_in_symint( + example_value.storage_offset(), + ( + TensorPropertySource(src, TensorProperty.STORAGE_OFFSET) + if src is not None + else None + ), + before=True, + ) + elif example_value.layout is torch.sparse_coo: + self._lift_basic_symbols(example_value._indices(), src) + self._lift_basic_symbols(example_value._values(), src) + elif example_value.layout in {torch.sparse_csr, torch.sparse_bsr}: + self._lift_basic_symbols(example_value.crow_indices(), src) + self._lift_basic_symbols(example_value.col_indices(), src) + elif example_value.layout in {torch.sparse_csc, torch.sparse_bsc}: + self._lift_basic_symbols(example_value.ccol_indices(), src) + self._lift_basic_symbols(example_value.row_indices(), src) + if is_traceable_wrapper_subclass(example_value): + attrs, ctx = example_value.__tensor_flatten__() + for attr in attrs: + inner_t = getattr(example_value, attr) + self._lift_basic_symbols( + inner_t, AttrSource(src, attr) if src is not None else None + ) + elif isinstance(example_value, torch.SymInt): + _lift_symbols_in_symint( + example_value, + src, + ) + + # Lookup the proxy in current tracer for each symbol in expressions of s, + # See Note [Auto lift basic free symbols when create_graph_input] + def lookup_unbound_symbols(self, s: torch.SymInt) -> list[sympy.Symbol]: + free_symbols = s.node.expr.free_symbols + if len(free_symbols) == 0: + return [] + + to_be_bound = [] + for s0 in free_symbols: + if s0 not in self.bound_symbols: + to_be_bound.append(s0) + continue + + proxy = self.bound_symbols[s0] + if isinstance(proxy, LazyProxy): + proxy = proxy() + self.bound_symbols[s0] = proxy + if not isinstance(proxy, torch.fx.Proxy) or proxy.tracer is not self: + raise AssertionError( + f"The proxy of symbol {s0} doesn't belong to current tracer." + ) + # Sort the symbols so that we can have a deterministic lifting order + return sorted(to_be_bound, key=lambda s: s.name) + + def has_input_mutation(self) -> MutationInfo: + input_versions_at_beginning = self._input_versions_at_beginning + input_nodes = [] + tensor_placeholder_indices = [] + + input_versions_at_end = [] + for placeholder_idx, node in enumerate(self.graph.nodes): + if node.op == "placeholder": + example_value = node.meta["example_value"] + if isinstance(example_value, torch.Tensor): + input_versions_at_end.append(example_value._version) + input_nodes.append(node) + tensor_placeholder_indices.append(placeholder_idx) + else: + break + + mutated_inputs = [ + i + for i, (v1, v2) in enumerate( + zip(input_versions_at_beginning, input_versions_at_end) + ) + if v1 != v2 + ] + + if mutated_inputs: + mutated_nodes = [input_nodes[i] for i in mutated_inputs] + mutated_input_indices = tuple( + tensor_placeholder_indices[i] for i in mutated_inputs + ) + msg = f"Input mutation detected at {mutated_nodes}" + return MutationInfo(True, msg, mutated_input_indices) + + return MutationInfo(False, "", ()) + + def has_aliasing(self) -> AliasingInfo: + from torch._dynamo.variables.higher_order_ops import get_tensor_storages + from torch._higher_order_ops.utils import _collect_fake_inputs + + input_storages: dict[StorageWeakRef, torch.fx.Node] = dict() + + for node in self.graph.nodes: + if node.op == "placeholder": + example_value = _collect_fake_inputs([node])[0] + if isinstance(example_value, torch.Tensor): + for storage in get_tensor_storages(example_value): + if storage in input_storages: + # input-input aliasing + msg = f"Input-to-input aliasing detected at nodes {input_storages[storage]} and {node}" + return AliasingInfo(True, msg) + input_storages[storage] = node + else: + break + + output_storages: dict[StorageWeakRef, torch.fx.Node] = dict() + out_nodes = self.graph.find_nodes(op="output")[0] + for out_node in pytree.tree_leaves(out_nodes.args[0]): + if out_node: + example_value = _collect_fake_inputs([out_node])[0] + if isinstance(example_value, list): + raise AssertionError("example_value must not be a list") + if isinstance(example_value, torch.Tensor): + for storage in get_tensor_storages(example_value): + if storage in output_storages: + # output-output aliasing + msg = f"Output-to-output aliasing detected at nodes {output_storages[storage]} and {out_node}" + return AliasingInfo(True, msg) + output_storages[storage] = out_node + + intersected_storages = input_storages.keys() & output_storages.keys() + if len(intersected_storages) > 0: + # input-output aliasing + aliased = [ + (input_storages[s], output_storages[s]) for s in intersected_storages + ] + aliased = ", ".join([f"{i} and {o}" for i, o in aliased]) + msg = f"Input-to-output aliasing detected at nodes {aliased}" + return AliasingInfo(True, msg) + + return AliasingInfo(False, "") + + +# NOTE: [HigherOrderOperator tracing design] +# Ignoring HigherOrderOperators for a moment, +# OutputGraph represents the graph being built by Dynamo that may be compiled +# and executed. It holds a root SubgraphTracer where the FX graph is built. +# +# HigherOrderOperators are operators that take functions as their arguments. +# When Dynamo encounters a HigherOrderOperator, then it attempts to introspect +# the function passed to it (call this the "body function"), capture it into a +# GraphModule, and rewrite the call to the HigherOrderOperator to use the +# GraphModule. +# +# The way we handle the capture of body functions is through having +# (possibly nested) SubgraphTracers, one per body function. +# +# Mechanically, we do the introspection by: +# - Creating a new SubgraphTracer via OutputGraph.subtracer +# - Executing the body function. +# This constructs the graph of the body function in the new SubgraphTracer +# while modifying the state of the OutputGraph. For example: +# - the OutputGraph can receive new GraphArgs (if we discover any new +# untracked Tensors) +# - side effects from the body function get accumulated into +# OutputGraph.side_effects +# - guards produced by the body function get accumulated into OutputGraph.guards +# +# The traced function has some special properties that make it easier for us +# to transform later down the line: +# - we lift all free variables to being inputs. +# +# If the introspection fails (due to the existence of graph breaks), then +# we roll back the current OutputGraph state and graph break on the +# HigherOrderOperator. diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/package.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/package.py new file mode 100644 index 0000000000000000000000000000000000000000..03a1007b465273a932913de8059263ae6b096e4c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/package.py @@ -0,0 +1,1299 @@ +""" +This module provides the infrastructure for creating and managing compile package +for torch.compile. We mainly have two abstractions here: + - CompilePackage: Overarching data structure for store and lookup a list of compiled codes. + - CodeCacheEntry: Data structure for a single code being compiled by torch.compile. +The caching behavior is always under user control explicitly so that a stronger guarantee can +be provided about cache hit for a specific compiled model. Users can load the compile package +from a different process or host. +""" + +import abc +import ast +import contextlib +import dataclasses +import functools +import hashlib +import importlib +import inspect +import itertools +import json +import logging +import os +import pickle +import platform +import shutil +import sys +import types +from collections.abc import Callable, Generator, Iterator +from contextlib import nullcontext +from typing import Any, NewType, Optional, TYPE_CHECKING, Union +from typing_extensions import Never + +import torch +from torch._dynamo.exc import PackageError +from torch._dynamo.graph_utils import _graph_device_type +from torch.utils.weak import WeakIdKeyDictionary + +from .bytecode_transformation import ( + COMPILED_FN_PREFIX, + get_code_keys, + is_compiled_fn_name, +) +from .utils import CleanupHook, counters, dynamo_timed, increment_frame + + +logger = logging.getLogger(__name__) + + +if TYPE_CHECKING: + from .guards import GuardManagerWrapper, GuardsState + + +_CODE_CACHE = WeakIdKeyDictionary() + + +def _code_cache(fn: Callable[..., Any]) -> Callable[..., Any]: + def _( + cls: type[Any], code: Union["SerializedCode", types.CodeType] + ) -> Union["SerializedCode", types.CodeType]: + if code in _CODE_CACHE: + return _CODE_CACHE[code] + res = fn(cls, code) + _CODE_CACHE[code] = res + return res + + return _ + + +@dataclasses.dataclass(frozen=True) +class SerializedCode: + co_argcount: int + co_posonlyargcount: int + co_kwonlyargcount: int + co_nlocals: int + co_stacksize: int + co_flags: int + co_code: bytes + co_consts: tuple[Any, ...] + co_names: tuple[str, ...] + co_varnames: tuple[str, ...] + co_filename: str + co_name: str + co_firstlineno: int + co_cellvars: tuple[str, ...] + co_freevars: tuple[str, ...] + co_linetable: bytes | None = None + co_qualname: str | None = None + co_exceptiontable: bytes | None = None + co_lnotab: str | None = None + + @classmethod + @_code_cache + def from_code_object(cls, code: types.CodeType) -> "SerializedCode": + kwargs = {key: getattr(code, key) for key in get_code_keys()} + kwargs["co_consts"] = tuple( + cls.from_code_object(c) if isinstance(c, types.CodeType) else c + for c in kwargs["co_consts"] + ) + return cls(**kwargs) + + @classmethod + @_code_cache + def to_code_object(cls, serialized_code: "SerializedCode") -> types.CodeType: + kwargs = {key: getattr(serialized_code, key) for key in get_code_keys()} + kwargs["co_consts"] = tuple( + cls.to_code_object(c) if isinstance(c, SerializedCode) else c + for c in kwargs["co_consts"] + ) + return types.CodeType( + *kwargs.values(), + ) + + +@dataclasses.dataclass +class _GuardedCodeCacheEntry: + """ + Contains the serializable information associated with a single compilation in dynamo. + To restore an execution of compiled code, we will need to serialize the following data: + - Dynamo bytecode for mapping Python inputs/outputs. + - Dynamo guards. + """ + + guards_state: bytes + dynamo_code: SerializedCode + + +def load_guards_state(guards_state: bytes) -> Any: + try: + import torch.distributed.fsdp._fully_shard._fully_shard as _fully_shard + + ctx = _fully_shard.disable_fsdp_module_new_init() + except ImportError: + ctx = nullcontext() # type: ignore[assignment] + with ctx: + return pickle.loads(guards_state) + + +def load_guard_manager( + guards_state: "GuardsState", + target_code: types.CodeType, + runtime_global_scope: Any, +) -> "GuardManagerWrapper": + from .output_graph import OutputGraphCommon + + return torch._dynamo.guards.CheckFunctionManager( + target_code, + OutputGraphCommon(guards_state.output_graph), + shape_code_parts=guards_state.shape_code_parts, + runtime_global_scope=runtime_global_scope, + guard_build_local_state=getattr(guards_state, "local_state", None), + ).guard_manager + + +_BackendId = NewType("_BackendId", str) # __compiled_fn +_FunctionId = NewType("_FunctionId", str) # __resume_at + + +def _backend_ids_from_code(code: types.CodeType) -> Iterator[_BackendId]: + for name in code.co_names: + if is_compiled_fn_name(name): + yield _BackendId(name) + for const in code.co_consts: + if isinstance(const, types.CodeType): + yield from _backend_ids_from_code(const) + + +@dataclasses.dataclass(frozen=True) +class InlinedSource: + module: str + firstlineno: int + lastlineno: int + checksum: str + content: str + + +@functools.cache +def _get_module_content(module: types.ModuleType) -> str: + return inspect.getsource(module) + + +@dataclasses.dataclass +class SourceInfo: + inlined_sources: set[InlinedSource] + + def add_code(self, code: types.CodeType) -> None: + module = inspect.getmodule(code) + if module is None: + return + sourcelines, firstlineno = inspect.getsourcelines(code) + lastlineno = firstlineno + len(sourcelines) + source = "".join(sourcelines) + if source != "".join(_get_sourcelines(module, firstlineno, lastlineno)): + raise AssertionError( + f"Source mismatch for {module.__name__} " + f"(line {firstlineno}-{lastlineno})" + ) + self.inlined_sources.add( + InlinedSource( + module=module.__name__, + firstlineno=firstlineno, + lastlineno=lastlineno, + checksum=_hash_source(source), + content=_get_module_content(module), + ) + ) + + +@dataclasses.dataclass +class _DynamoCodeCacheEntry: + """ + Contains the serializable information associated with a single code object + in dynamo. To restore an execution of compiled code, we will need the following + ingredients: + 1. The "original" code object, which serves as the entry point for eager + execution, i.e. the code only executed when there's no cache entry hit. + 2. The python module name this code object belongs to, for identifying the + enclosing global scope to inject compiled and resume functions. + 3. A list of function names that pointing to this code object. There could be + multiple function objects pointing to the same code such as recursive functions. + 4. A list of guarded code that eval frame dispatches to. + 5. A list of imported module objects unioned from all compiled branches. + 6. A list of "backends" (compiled fx graph) unioned from all compiled branches. + 7. A string path used to access the original code object users defined. + A code object can be accessed by "{python_module}.{function_name}.{code_source}" . + 8. A boolean flag indicating whether the function is installed to global scope. + 9. A boolean flag indicating whether the function has a compile id. + 10. Whether or not this code entry was bypassed + """ + + python_code: SerializedCode + python_module: str + function_names: list[_FunctionId] + guarded_codes: list[_GuardedCodeCacheEntry] + import_sources: dict[str, str] + backend_ids: list[_BackendId] + code_source: str | None + install_to_global: bool + has_compile_id: bool = False + bypassed: bool = False + + +def _lookup_code(entry: _DynamoCodeCacheEntry) -> types.CodeType: + if len(entry.function_names) != 1: + raise AssertionError( + f"Expected exactly one function name, got {len(entry.function_names)}" + ) + fn: Any = sys.modules[entry.python_module] + parts = entry.function_names[0].split(".") + for part in parts: + fn = getattr(fn, part) + if entry.code_source: + parts = entry.code_source.split(".") + for part in parts: + if part.endswith("]"): + index_begin = part.rfind("[") + if not isinstance(index_begin, int): + raise AssertionError( + f"Expected int for index_begin, got {type(index_begin)}" + ) + if index_begin < 0: + raise AssertionError( + f"Expected non-negative index_begin, got {index_begin}" + ) + attr = getattr(fn, part[:index_begin], None) + if attr is None: + raise PackageError(f"Cannot find source for code entry {entry}") + fn = attr[ast.literal_eval(part[index_begin + 1 : -1])] + else: + fn = getattr(fn, part) + else: + raise PackageError(f"Cannot find source for code entry {entry}") + if not isinstance(fn, types.CodeType): + raise AssertionError( + f"Expected CodeType, got {type(fn)} for code entry {entry}" + ) + return fn + + +def _raise_resolution_error(code: types.CodeType, scope: Any) -> Never: + raise PackageError( + f"Cannot resolve a fully qualified name for {code}. Lookup scope: {scope}" + ) + + +def _get_code_source(code: types.CodeType) -> tuple[str, str]: + """ + Given a code object, return a fully qualified name which will be used as + a serialized handle to access the code object from the new process. + This is normally a straightforward process, but there are some corner cases: + 1. When a function is defined with decorator, then this function will be captured + inside a closure with the wrapper object. + 2. When a function is defined as a nested function, then the code object will be + stored on the co_consts field of the parent code object by Python compiler. + This function handles all of the corner cases above. + """ + + module = inspect.getmodule(code) + if module is None: + raise PackageError(f"Cannot find module for code {code}") + + toplevel: Any = module + if sys.version_info >= (3, 11): + parts = code.co_qualname.split(".") + + for part in parts: + if not hasattr(toplevel, part): + _raise_resolution_error(code, toplevel) + toplevel = getattr(toplevel, part) + if inspect.isfunction(toplevel) or inspect.ismethod(toplevel): + break + seen = set() + + def _find_code_source(obj: Any) -> str | None: + nonlocal toplevel + nonlocal seen + if obj in seen: + return None + + seen.add(obj) + + if inspect.iscode(obj): + if obj is code: + return "" + + for i, const in enumerate(obj.co_consts): + if (res := _find_code_source(const)) is not None: + return f".co_consts[{i}]{res}" + + if inspect.ismethod(obj): + if (res := _find_code_source(obj.__func__)) is not None: + toplevel = obj + return f".__func__{res}" + + if inspect.isfunction(obj): + if (res := _find_code_source(obj.__code__)) is not None: + toplevel = obj + return f".__code__{res}" + if obj.__closure__ is not None: + for i, cell in enumerate(obj.__closure__): + try: + cell_contents = cell.cell_contents + except ValueError: + continue + if not ( + inspect.isfunction(cell_contents) + or inspect.iscode(cell_contents) + or inspect.ismethod(cell_contents) + ): + continue + if (res := _find_code_source(cell_contents)) is not None: + toplevel = obj + return f".__closure__[{i}].cell_contents{res}" + + if sys.version_info < (3, 11): + if inspect.ismodule(obj): + for value in obj.__dict__.values(): + if not ( + inspect.isfunction(value) + or inspect.isclass(value) + or inspect.ismethod(value) + ): + continue + if (res := _find_code_source(value)) is not None: + return res + + if inspect.isclass(obj): + for name in itertools.chain(obj.__dict__.keys(), dir(obj)): + try: + value = getattr(obj, name) + except AttributeError: + continue + if not ( + inspect.isfunction(value) + or inspect.isclass(value) + or inspect.ismethod(value) + ): + continue + if (res := _find_code_source(value)) is not None: + if value.__name__ != name: + _raise_resolution_error(code, toplevel) + return res + return None + + code_source = _find_code_source(toplevel) + if code_source is None: + _raise_resolution_error(code, toplevel) + return toplevel.__qualname__, code_source.strip(".") + + +@dataclasses.dataclass(frozen=True) +class SystemInfo: + """ + System information including Python, PyTorch, and GPU details. + This information is used to ensure compiled artifacts can only be loaded + with compatible system configurations. + """ + + python_version: str + torch_version: str + toolkit_version: str | None + triton_version: tuple[int, int] | None + gpu_name: str | None + CHECK_GPUS = ("cuda", "xpu") + + @classmethod + def current(cls) -> "SystemInfo": + """Create a SystemInfo instance with current system information.""" + # Get GPU name if CUDA or XPU is available + gpu_name = None + from torch.utils._triton import get_triton_version + + gpu_name, toolkit_version = None, None + for device_type in cls.CHECK_GPUS: + if getattr(torch, device_type).is_available(): + try: + gpu_name = getattr(torch, device_type).get_device_name() + toolkit_version = getattr(torch.version, device_type) + break + except Exception: + pass + + return cls( + python_version=platform.python_version(), + torch_version=torch.__version__, + toolkit_version=toolkit_version, + triton_version=get_triton_version((0, 0)), + gpu_name=gpu_name, + ) + + def check_compatibility( + self, other: "SystemInfo", device_type: str = "cpu" + ) -> None: + """ + Check if this SystemInfo is compatible with another SystemInfo. + Raises RuntimeError if incompatible. + """ + if self.python_version != other.python_version: + raise RuntimeError( + f"Compile package was created with a different Python version: {self.python_version}" + ) + + if self.torch_version != other.torch_version: + raise RuntimeError( + f"Compile package was created with a different PyTorch version: {self.torch_version}" + ) + if device_type in self.CHECK_GPUS: + if not getattr(torch, device_type).is_available(): + raise RuntimeError(f"{device_type} is not available") + + if self.toolkit_version != other.toolkit_version: + raise RuntimeError( + f"Compile package was created with a different toolkit version: {self.toolkit_version}" + ) + + if ( + other.triton_version != (0, 0) + and self.triton_version != other.triton_version + ): + raise RuntimeError( + f"Compile package was created with a different Triton version: {self.triton_version}" + ) + + # Check GPU name if CUDA/XPU was used + if other.gpu_name is not None and self.gpu_name != other.gpu_name: + raise RuntimeError( + f"Compile package was created with different GPU: " + f"cached={self.gpu_name}, current={other.gpu_name}" + ) + + +@dataclasses.dataclass +class _DynamoCacheEntry: + codes: list[_DynamoCodeCacheEntry] + source_info: SourceInfo + device_type: str + system_info: SystemInfo = dataclasses.field(default_factory=SystemInfo.current) + fn_name: str | None = None + fn_first_lineno: str | None = None + + @property + def backend_ids(self) -> set[_BackendId]: + return {backend_id for code in self.codes for backend_id in code.backend_ids} + + def check_versions(self) -> None: + """Check if the current system is compatible with the system used to create this cache entry.""" + current_system_info = SystemInfo.current() + self.system_info.check_compatibility(current_system_info, self.device_type) + + def debug_info(self) -> dict[str, Any]: + if len(self.codes) == 0: + raise AssertionError("Expected at least one code entry") + return { + "num_codes": str(len(self.codes)), + "fn_name": self.fn_name, + "fn_first_lineno": self.fn_first_lineno, + "device_type": self.device_type, + "backend_ids": list(self.backend_ids), + } + + +from torch.compiler._cache import ( + CacheArtifact, + CacheArtifactFactory, + CacheArtifactRecorder, +) + + +@CacheArtifactFactory.register +class PrecompileCacheArtifact(CacheArtifact): + def populate_cache(self) -> None: + DynamoCache._write_to_local_cache(self.content, self.key) + + @staticmethod + def type() -> str: + return "precompile" + + +@dataclasses.dataclass +class PrecompileCacheEntry: + """ + A full cache entry for caching precompile, for a toplevel torch.compile. + Consists of a _DynamoCacheEntry, which contains all the dynamo related contents, + and a set of backends content. In general, the backend content here will always + be of type precompile_context.BackendCacheArtifact + """ + + dynamo: _DynamoCacheEntry + backends: dict[_BackendId, Any] + + @staticmethod + def from_cache_entry( + cache_entry: _DynamoCacheEntry, backends: dict[_BackendId, Any] + ) -> Optional["PrecompileCacheEntry"]: + backend_content: dict[_BackendId, Any] = {} + + for code in cache_entry.codes: + for backend_id in code.backend_ids: + if backend_id not in backends: + logger.warning("Backend not found") + debug_str = json.dumps( + { + "entry": cache_entry.debug_info(), + "missing_backend": backend_id, + } + ) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_cache_bypass", + "encoding": "json", + }, + payload_fn=lambda: debug_str, + expect_trace_id=False, + ) + code.bypassed = True + break + else: + backend_content[backend_id] = backends[backend_id] + + return PrecompileCacheEntry(dynamo=cache_entry, backends=backend_content) + + +def _hash_source(source: str) -> str: + sha256_hash = hashlib.sha256() + sha256_hash.update(source.encode()) + return sha256_hash.hexdigest() + + +def _get_sourcelines( + m: types.ModuleType, firstlineno: int, lastlineno: int +) -> list[str]: + return inspect.getsourcelines(m)[0][firstlineno - 1 : lastlineno - 1] + + +def _hash_sourcelines(m: types.ModuleType, firstlineno: int, lastlineno: int) -> str: + return _hash_source("".join(_get_sourcelines(m, firstlineno, lastlineno))) + + +def _compile_frame_context( + code: types.CodeType, +) -> contextlib.AbstractContextManager[None]: + from torch._dynamo.convert_frame import get_compile_id, log_dynamo_start + from torch._guards import compile_context, CompileContext + + # Each code represents a new compile frame + # recompiles on the same frame are all saved + # under the same cache entry, so we don't have recompile ids + # i.e. If cold start had 0/0, 0/1, 1/0, 1/1, these would be + # collapsed into 0/0, 1/0 on warm. + # pyrefly: ignore [deprecated] + @contextlib.contextmanager + def _ctx() -> Iterator[None]: + increment_frame() + compile_id = get_compile_id(frame_state={}) + with ( + compile_context(CompileContext(compile_id)), + dynamo_timed( + "_compile.compile_inner", + phase_name="entire_frame_compile", + dynamo_compile_column_us="dynamo_cumulative_compile_time_us", + # TODO: save all relevant compilation metrics + metadata={ + "frame_key": str(torch._dynamo.utils.curr_frame), + "co_name": code.co_name, + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + }, + ), + ): + log_dynamo_start(code) + yield + + return _ctx() + + +class CompilePackage: + """ + CompilePackage is considered a low level component and should not be directly exposed to + end users. It has the following interface: + + 1. `CompilePackage.__init__()` which optionally takes previously serialized dynamo states. + a. when `dynamo` argument is None, it will construct a brand new CompilePackage object. + b. when `dynamo` argument is not None, it will load a pre-compiled dynamo state. + 2. `package.save()` which dumps the dynamo and backend states to a DynamoCacheEntry object. + 3. `package.install(backends) which will handle all the side-effectful global scope + updates with compiled functions and resume functions. + """ + + def __init__( + self, + fn: Callable[..., Any] | None, + dynamo: _DynamoCacheEntry | None = None, + ignore_inlined_sources: bool = False, + ) -> None: + self._innermost_fn = None + self._codes: dict[types.CodeType, _DynamoCodeCacheEntry] = {} + + self._current_entry: _DynamoCodeCacheEntry | None = None + self._installed_globals: dict[types.ModuleType, list[str]] = {} + # device_type that model compiled with. + self._device_type = "cpu" + + # For debugging/testing purpose only. + self._cached_backends: dict[_BackendId, Any] = {} + self._source_info: SourceInfo = SourceInfo(inlined_sources=set()) + self._resume_codes: set[types.CodeType] = set() + self._initialized = False + if fn is not None: + self.initialize(fn, dynamo, ignore_inlined_sources) + self.uninstall() + self.validate() + + def is_initialized(self) -> bool: + return self._initialized + + def initialize( + self, + fn: Any, + dynamo: _DynamoCacheEntry | None = None, + ignore_inlined_sources: bool = False, + ) -> None: + from .eval_frame import innermost_fn + + if self._initialized: + raise AssertionError("CompilePackage is already initialized") + self._source_info = SourceInfo(inlined_sources=set()) + self._innermost_fn = innermost_fn(fn) # type: ignore[assignment] + if self._innermost_fn is None: + raise AssertionError("innermost_fn returned None") + if dynamo is not None: + if not isinstance(dynamo, _DynamoCacheEntry): + raise AssertionError(f"Expected _DynamoCacheEntry, got {type(dynamo)}") + dynamo.check_versions() + if not ignore_inlined_sources: + for code in dynamo.source_info.inlined_sources: + m = importlib.import_module(code.module) + checksum = _hash_sourcelines(m, code.firstlineno, code.lastlineno) + if checksum != code.checksum: + raise RuntimeError( + f"Source code changes detected for {code.module} (line {code.firstlineno} - line {code.lastlineno})" + ) + + self._source_info = dynamo.source_info + + main, *codes = dynamo.codes + self._codes = {self._innermost_fn.__code__: main} + for code in codes: + self._codes[SerializedCode.to_code_object(code.python_code)] = code + else: + self._add_function( + self._innermost_fn.__code__, self._innermost_fn.__module__ + ) + self._initialized = True + + def _add_function( + self, + python_code: types.CodeType, + python_module: str, + function_name: _FunctionId | None = None, + code_source: str | None = None, + install_to_global: bool = False, + ) -> None: + if python_code not in self._codes: + code = _DynamoCodeCacheEntry( + python_code=SerializedCode.from_code_object(python_code), + python_module=python_module, + function_names=[], + guarded_codes=[], + import_sources={}, + backend_ids=[], + code_source=code_source, + install_to_global=install_to_global, + ) + self._codes[python_code] = code + else: + code = self._codes[python_code] + if code.python_module != python_module: + raise AssertionError( + f"python_module mismatch: {code.python_module} != {python_module}" + ) + if code.install_to_global != install_to_global: + raise AssertionError( + f"install_to_global mismatch: {code.install_to_global} != {install_to_global}" + ) + if code.code_source != code_source: + raise AssertionError( + f"code_source mismatch: {code.code_source} != {code_source}" + ) + + if function_name is not None: + code.function_names.append(function_name) + + @property + def cached_backends(self) -> dict[_BackendId, Any]: + return self._cached_backends + + @functools.cached_property + def source_id(self) -> str: + if self._innermost_fn is None: + raise AssertionError("_innermost_fn is not set") + return CompilePackage.source_id_from_fn(self._innermost_fn) + + def _add_user_function(self, code: types.CodeType) -> None: + function_name, code_source = _get_code_source(code) + module = inspect.getmodule(code) + if module is None: + raise PackageError(f"Cannot find module for code {code}") + self._add_function( + code, + module.__name__, + function_name=_FunctionId(function_name), + code_source=code_source, + ) + + @contextlib.contextmanager + def code_context(self, code: types.CodeType) -> Generator[None, None, None]: + if self._current_entry is not None: + raise AssertionError("_current_entry is already set in code_context") + + # Sometimes user code cannot be inlined in dynamo resulting in extra user code + # being compiled. We should record these as when they are actually invoked. + if code not in self._codes: + self._add_user_function(code) + + entry = self._codes[code] + self._current_entry = entry + try: + yield + finally: + entry.has_compile_id = True + self._current_entry = None + + def add_guarded_code( + self, + guards_state: bytes, + dynamo_code: types.CodeType, + ) -> None: + if self._current_entry is None: + raise AssertionError("_current_entry is not set in add_guarded_code") + if self._current_entry.bypassed: + return + guarded_code_entry = _GuardedCodeCacheEntry( + guards_state=guards_state, + dynamo_code=SerializedCode.from_code_object(dynamo_code), + ) + self._current_entry.guarded_codes.append(guarded_code_entry) + for backend_id in _backend_ids_from_code(dynamo_code): + self._add_backend_id(backend_id) + + def add_inlined_source(self, sources: list[types.CodeType]) -> None: + if self._current_entry is None: + raise AssertionError("_current_entry is not set in add_inlined_source") + if self._current_entry.bypassed: + return + for code in sources: + if code in self._resume_codes: + continue + self._source_info.add_code(code) + + def update_device_type(self, graph: torch.fx.Graph | None) -> None: + self._device_type = _graph_device_type(graph) + + def bypass_current_entry(self) -> None: + if self._current_entry is None: + raise AssertionError("_current_entry is not set in bypass_current_entry") + self._current_entry.bypassed = True + + def add_resume_function( + self, + python_code: types.CodeType, + python_module: str, + function_name: str, + ) -> None: + self._add_function( + python_code, + python_module, + function_name=_FunctionId(function_name), + install_to_global=True, + ) + self._resume_codes.add(python_code) + + def add_import_source(self, alias: str, module_name: str) -> None: + if self._current_entry is None: + raise AssertionError("_current_entry is not set in add_import_source") + self._current_entry.import_sources[alias] = module_name + + def _add_backend_id( + self, backend_id: _BackendId, backend: Any | None = None + ) -> None: + if self._current_entry is None: + raise AssertionError("_current_entry is not set in add_backend_id") + if backend_id not in self._current_entry.backend_ids: + self._current_entry.backend_ids.append(backend_id) + if backend is not None: + self._cached_backends[backend_id] = backend + + def add_backend_id(self, backend_id: str, backend: Any | None = None) -> None: + if not backend_id.startswith(f"{COMPILED_FN_PREFIX}_"): + raise AssertionError( + f"backend_id must start with '{COMPILED_FN_PREFIX}_', got '{backend_id}'" + ) + self._add_backend_id(_BackendId(backend_id), backend) + + def validate(self) -> None: + if self._current_entry is not None: + raise AssertionError("_current_entry should be None during validate") + if self._innermost_fn is None: + raise AssertionError("_innermost_fn is not set during validate") + if not self._initialized: + raise AssertionError("CompilePackage is not initialized during validate") + if next(iter(self._codes)) is not self._innermost_fn.__code__: + raise AssertionError( + "First code entry does not match _innermost_fn.__code__" + ) + + def _install_global(self, module: types.ModuleType, name: str, value: Any) -> None: + # A pre-reset compile in this process may still own `name` via a + # CleanupHook that hasn't fired yet. We're taking over the binding now, + # so that hook must not delete it once its code object is collected. + CleanupHook.disown(module.__dict__, name) + module.__dict__[name] = value + self._installed_globals.setdefault(module, []).append(name) + + def uninstall(self) -> None: + from torch._C._dynamo.eval_frame import _reset_precompile_entries + + if self._innermost_fn is None: + raise AssertionError("_innermost_fn is not set in uninstall") + for module, names in self._installed_globals.items(): + for name in names: + module.__dict__.pop(name, None) + + self._installed_globals = {} + + _reset_precompile_entries(self._innermost_fn.__code__) + + def install(self, backends: dict[_BackendId, Any]) -> None: + """ + Sync the package states to the compiled function. This includes the following actions: + 1. Clean up the previously installed states. + 2. Install the compiled functions to global scopes. + 3. Install the precompiled cache entries to ExtraStates on the code object. + """ + from torch._C._dynamo.eval_frame import _load_precompile_entry + + from .convert_frame import input_codes + from .output_graph import get_builtins_dict + + self.uninstall() + for code, entry in self._codes.items(): + context = ( + _compile_frame_context(code) + if entry.has_compile_id + else contextlib.nullcontext() + ) + with context: + module = sys.modules[entry.python_module] + for alias, module_name in entry.import_sources.items(): + self._install_global( + module, alias, importlib.import_module(module_name) + ) + target_code = code + if entry.install_to_global: + for function_name in entry.function_names: + if code.co_freevars: + # Resume functions with freevars need a factory + # that takes a closure tuple, matching + # install_resume_function_global in output_graph.py. + f_globals = module.__dict__ + fn_name = function_name + + def _make_fn( + closure: tuple[types.CellType, ...], + _code: types.CodeType = code, + _globals: dict[str, Any] = f_globals, + _name: str = fn_name, + ) -> types.FunctionType: + return types.FunctionType( + _code, _globals, _name, None, closure + ) + + self._install_global(module, function_name, _make_fn) + else: + fn = types.FunctionType( + code, module.__dict__, function_name + ) + self._install_global(module, function_name, fn) + if entry.code_source: + target_code = _lookup_code(entry) + + if entry.bypassed: + # If the entry is bypassed, do not install backends + # or guarded codes. + continue + + input_codes.add(target_code) + for backend_id in entry.backend_ids: + if backend_id not in backends: + raise RuntimeError( + f"Backend {backend_id} is not found in the given backends" + ) + with dynamo_timed( + "after_deserialization", phase_name="backend_compile" + ): + backend = backends[backend_id].after_deserialization() + self._install_global( + module, + backend_id, + torch._dynamo.disable(backend), + ) + + if len(entry.guarded_codes) == 0: + # Dynamo generates empty graph for trivial functions, should just skip them + # in these cases. + torch._dynamo.eval_frame.skip_code(target_code) + + for guarded_code in entry.guarded_codes: + with dynamo_timed("precompile_load_guards"): + guards_state = load_guards_state(guarded_code.guards_state) + runtime_global_scope = sys.modules[entry.python_module].__dict__ + # The installed builtins dict might be absent from the runtime + # while loading guards. Populate it if it's missing. + if ( + builtin_dict_name + := guards_state.output_graph.name_of_builtins_dict_key_in_fglobals + ): + # A pre-reset compile's CleanupHook may still own this + # name even when we're about to leave its value alone + # below (same dict object every compile in this + # module), so it must not delete it once collected. + CleanupHook.disown(runtime_global_scope, builtin_dict_name) + builtins_dict = get_builtins_dict(runtime_global_scope) + if builtin_dict_name in runtime_global_scope: + if ( + runtime_global_scope[builtin_dict_name] + is not builtins_dict + ): + raise AssertionError( + f"Builtins dict mismatch for key '{builtin_dict_name}'" + ) + else: + runtime_global_scope[builtin_dict_name] = builtins_dict + if not isinstance(guards_state, torch._dynamo.guards.GuardsState): + raise AssertionError( + f"Expected GuardsState, got {type(guards_state)}" + ) + with dynamo_timed("precompile_build_guards"): + guard_manager = load_guard_manager( + guards_state, target_code, runtime_global_scope + ) + _load_precompile_entry( + target_code, + guard_manager, + SerializedCode.to_code_object(guarded_code.dynamo_code), + ) + + def cache_entry(self) -> _DynamoCacheEntry: + self.validate() + if self._innermost_fn is None: + raise AssertionError("_innermost_fn is not set in cache_entry") + return _DynamoCacheEntry( + codes=list(self._codes.values()), + source_info=self._source_info, + device_type=self._device_type, + fn_name=self._innermost_fn.__qualname__, + fn_first_lineno=self._innermost_fn.__code__.co_firstlineno, + ) + + @staticmethod + def source_id_from_fn(fn: Callable[..., Any]) -> str: + from .eval_frame import innermost_fn + + innermost_fn_ = innermost_fn(fn) + + sha256_hash = hashlib.sha256() + sha256_hash.update(innermost_fn_.__qualname__.encode()) + sha256_hash.update(str(innermost_fn_.__code__.co_firstlineno).encode()) + return sha256_hash.hexdigest() + + +_Backends = dict[_BackendId, Any] + + +class DynamoStore(abc.ABC): + """ + A DynamoStore tracks active CompilePackages, and provides methods to store and retrieve them. + + This is an abstract base class for different storage implementations. + """ + + def record_package(self, package: CompilePackage) -> None: + """ + Records a package to PrecompileContext, so that it can be serialized later. + """ + from torch._dynamo.precompile_context import PrecompileContext + + cache_entry = package.cache_entry() + PrecompileContext.record_dynamo_cache_entry( + cache_entry=cache_entry, key=package.source_id + ) + + def record_eager_backend(self, backend_id: _BackendId, backend: Any) -> None: + """ + Records eager fx graphs to PrecompileContext for testing purposes. + """ + from torch._dynamo.precompile_context import ( + EagerCacheArtifact, + PrecompileContext, + ) + + result = EagerCacheArtifact(key=backend_id, content=backend) + PrecompileContext.record_artifact(result) + + @abc.abstractmethod + def clear(self) -> None: ... + + @abc.abstractmethod + def write( + self, + cache_entry: PrecompileCacheEntry, + path: str, + ) -> None: + """ + Abstract method to write dynamo cache entry and backends to storage. + + Args: + dynamo: The dynamo cache entry to write + backends: Dictionary of backend content to write + path: Path or key to identify where to write the data + """ + ... + + def save_cache_entry(self, cache_entry: _DynamoCacheEntry, key: str) -> None: + """ + Saves a package to a given path. Grabs backends from PrecompileContext. + """ + from torch._dynamo.precompile_context import ( + BackendCacheArtifact, + PrecompileContext, + ) + + backend_content: _Backends = {} + for backend_id in cache_entry.backend_ids: + serialized_backend = PrecompileContext.serialize_artifact_by_key(backend_id) + if serialized_backend is None: + raise RuntimeError( + f"Backend {backend_id} is not found in the given backends" + ) + if not isinstance(serialized_backend, BackendCacheArtifact): + raise AssertionError( + f"Expected BackendCacheArtifact, got {type(serialized_backend)}" + ) + backend_content[backend_id] = serialized_backend + + entry = PrecompileCacheEntry(cache_entry, backend_content) + + self.write(entry, key) + + def save_package(self, package: CompilePackage, key: str) -> None: + """ + Saves a package to a given path. Grabs backends from PrecompileContext. + """ + self.record_package(package) + cache_entry = package.cache_entry() + self.save_cache_entry(cache_entry, key) + + @abc.abstractmethod + def read(self, path: str) -> PrecompileCacheEntry: + """ + Abstract method to read dynamo cache entry and backends from storage. + + Args: + path: Path or key to identify where to read the data from + + Returns: + A tuple containing (dynamo_cache_entry, backend_content) + """ + ... + + def load_cache_entry(self, key: str) -> PrecompileCacheEntry: + from torch._dynamo.precompile_context import ( + BackendCacheArtifact, + PrecompileContext, + ) + + precompile_entry = self.read(key) + for backend in precompile_entry.backends.values(): + if not isinstance(backend, BackendCacheArtifact): + raise AssertionError( + f"Expected BackendCacheArtifact, got {type(backend)}" + ) + PrecompileContext.record_artifact(backend) + + return precompile_entry + + def load_package( + self, fn: Any, key: str + ) -> tuple[CompilePackage, dict[_BackendId, Any]]: + """ + Loads a package from a given path and returns it plus a list of deserialized backends + """ + entry = self.load_cache_entry(key) + package = CompilePackage(fn, entry.dynamo) + return package, entry.backends + + +class InMemoryDynamoStore(DynamoStore): + """ + A DynamoStore implementation that keeps state about CompilePackages in memory. + """ + + def __init__(self) -> None: + self.packages: dict[str, PrecompileCacheEntry] = {} + + def clear(self) -> None: + self.packages.clear() + + def write( + self, + cache_entry: PrecompileCacheEntry, + path: str, + ) -> None: + """ + Store the dynamo cache entry and backends in memory instead of writing to disk. + """ + self.packages[path] = cache_entry + + def read(self, path: str) -> PrecompileCacheEntry: + """ + Read dynamo cache entry and backends from memory. + """ + if path not in self.packages: + raise RuntimeError(f"No package found with key {path}") + + return self.packages[path] + + +class DiskDynamoStore(DynamoStore): + """ + A DynamoStore implementation that keeps state about CompilePackages on disk. + """ + + def __init__(self, path_prefix: str = "") -> None: + """ + Initialize a DiskDynamoStore with a path prefix. + + Args: + path_prefix: Prefix directory for where to put CompilePackages on disk + """ + self._path_prefix = path_prefix + + def path_prefix(self) -> str: + return self._path_prefix + + def clear(self) -> None: + """ + Clear all CompilePackages from disk. + """ + if self.path_prefix(): + shutil.rmtree(self.path_prefix(), ignore_errors=True) + + def write( + self, + cache_entry: PrecompileCacheEntry, + path: str, + ) -> None: + """ + Write dynamo cache entry and backends to disk. + """ + try: + pickled_content: bytes = pickle.dumps(cache_entry) + CacheArtifactRecorder(PrecompileCacheArtifact.type(), path).record( + pickled_content + ) + self._write_to_local_cache(pickled_content, path) + except Exception as e: + raise RuntimeError(f"Failed to save package to {path}: {e}") from e + + def _write_to_local_cache(self, pickled_content: bytes, path: str) -> None: + from torch._inductor.codecache import write_atomic + + path = os.path.join(self.path_prefix(), path) if self.path_prefix() else path + try: + os.makedirs(path, exist_ok=True) + write_atomic(os.path.join(path, "entry"), pickled_content) + except Exception as e: + raise RuntimeError(f"Failed to save package to {path}: {e}") from e + + def read(self, path: str) -> PrecompileCacheEntry: + """ + Read dynamo cache entry and backends from disk. + """ + path = os.path.join(self.path_prefix(), path) if self.path_prefix() else path + try: + with open(os.path.join(path, "entry"), "rb") as f: + pickled_content = f.read() + entry = pickle.loads(pickled_content) + return entry + except Exception as e: + raise RuntimeError(f"Failed to load package from path {path}: {e}") from e + + +class DiskDynamoCache(DiskDynamoStore): + """ + Special DiskDynamoStore which adds some helper functions for automatically + tracking paths of packages + """ + + def save(self, package: CompilePackage) -> None: + """ + Saves a package to a given path. Grabs backends from PrecompileContext. + """ + key = package.source_id + logger.info("Saving CompilePackage for %s", package.source_id) + super().save_package(package, key) + + def load(self, fn: Callable[..., Any]) -> PrecompileCacheEntry | None: + """ + Loads a package from a given path and returns it plus a list of deserialized backends + """ + key = CompilePackage.source_id_from_fn(fn) + logger.info("Loading CompilePackage for %s", key) + path = os.path.join(self.path_prefix(), key) + if os.path.exists(path): + try: + result = super().load_cache_entry(key) + counters["dynamo_cache"]["dynamo_cache_hit"] += 1 + return result + except Exception: + counters["dynamo_cache"]["dynamo_cache_error"] += 1 + logger.warning("Failed to load package from path %s", exc_info=True) + return None + logger.info("No package found for %s", key) + counters["dynamo_cache"]["dynamo_cache_miss"] += 1 + return None + + def load_and_install_package(self, fn: Callable[..., Any]) -> CompilePackage | None: + """ + Load directly into a package and install backends + """ + results = self.load(fn) + if results is None: + return None + else: + package = CompilePackage(fn, results.dynamo) + package.install(results.backends) + return package + + def path_prefix(self) -> str: + return os.path.join(cache_dir(), "dynamo") + + +def cache_dir() -> str: + from torch._inductor.runtime.cache_dir_utils import cache_dir + + return cache_dir() + + +DynamoCache = DiskDynamoCache(os.path.join(cache_dir(), "dynamo")) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/pgo.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/pgo.py new file mode 100644 index 0000000000000000000000000000000000000000..1437a3e931fb37718d244436bbdad4d5e93e79dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/pgo.py @@ -0,0 +1,1093 @@ +""" +Profile Guided Optimization (PGO) implementation for Dynamo. + +This module provides functionality for caching and managing code state profiles +that guide optimization decisions in Dynamo. It implements both local and remote +caching mechanisms for storing profile information across runs, handles profile +merging across distributed ranks, and manages the lifecycle of profile data +during compilation. The profiles track dynamic vs static properties of tensors +and help Dynamo make better specialization decisions. +""" + +from __future__ import annotations + +import base64 +import copy +import dataclasses +import enum +import functools +import logging +import os +import pickle +import re +import zlib +from collections import defaultdict +from typing import TYPE_CHECKING, TypeVar +from typing_extensions import override, Self + +import torch._dynamo.config +import torch._utils_internal +import torch.compiler.config +import torch.distributed as dist +from torch._dynamo.utils import ( + CompileEventLogger, + dynamo_timed, + set_feature_use, + warn_once, +) +from torch._environment import is_fbcode +from torch._logging._internal import trace_structured_artifact +from torch.compiler._cache import ( + CacheArtifact, + CacheArtifactFactory, + CacheArtifactRecorder, +) +from torch.utils._ordered_set import OrderedSet + + +if TYPE_CHECKING: + import types + + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._inductor.remote_cache import JsonDataTy, RemoteCache + + +class ReservedWorkflowIdUserError(ValueError): + pass + + +log = logging.getLogger(__name__) +symbolic_shape_log = logging.getLogger("torch.fx.experimental.symbolic_shapes") + +LOCK_TIMEOUT = 10 + +# How does in memory representation work? Concretely, this module is +# responsible for holding GLOBAL state representing the state it holds, no +# other copies permitted. So we retire frame_state entirely and store it +# here. This should be reset when Dynamo is reset. We never GC information +# (similar to how the filesystem doesn't get cleaned up except by tmp +# cleaner), so the expectation is the information is relatively cheap and we +# don't mind leaking it. + + +# How exactly did we design the cache key? Here are some of the questions: +# +# - JOB_ID: Do we have a unique identifier for the "training run" (such that +# it stays the same if we're running the same code, and changes if we're +# running something different). +# +# - RANK: Are we sharing the cache across ranks, or does each rank get +# an individual cache? +# +# We choose to require job_id for PGO cache. This is to prevent +# situations where unrelated invocations of PyTorch unpredictably cause +# changes to each other's behavior. With a job_id, at least you know there +# is some "state" associated with it. (State dict might be another way to +# tell if a run is related or not.) You can opt-in to YOLO everything +# aliases everything by passing a shared job_id for all your invocations. +# +# We choose to NOT share PGO cache across ranks. With no RANK_SHARING, there +# is never contention between runs, so we can leisurely update a bundle with +# information we need. Because we are grouped by job_id, we can have a single +# consolidated bundle for everything (or not; maybe worry about O(n^2) IO if +# we updated every compile--let's just instrument this.) Can even take a +# filelock for extra safety (expect no contention); expect 50ns overhead from +# uncontended filelock. +# +# If we did share ranks, everyone is storming to modify the same cache files. +# We can do this by having folks atomic write to a CAS-store and then having +# readers do on-the-fly merging (this can be implemented in remote using +# prefix iteration). As an optional optimization, one rank can be elected to +# handling bundling post facto (ideally, this is done async, after quiescence, +# without compiler collective need to wait for everyone to finish writing +# their bits.) Not sure how you can avoid a listdir because if some rank shows +# up with some new entries we need to pull them in ASAP (unless you want to +# delay bundling). +# +# But compiler collectives fill a similar niche: compilers chat with each +# other so rank 0 has collected everything. So elect rank 0 only to write the +# bundle. Don't even need CAS-store atomic write; just one rank writing an +# updating bundles. The point is that use compiler collectives to share +# profiles across ranks, but use the PGO cache to persist profiles per rank +# across attempts. No need to have one mechanism to do everything. + + +@functools.cache +def _hash_containing_file(filepath: str) -> str: + # if the file does not exist we consider filepath to be the hash. + if not os.path.exists(filepath): + return filepath + + with open(filepath, "rb") as file: + content = file.read() + crc32_value = zlib.crc32(content) + hash = format(crc32_value & 0xFFFFFFFF, "08x") + return hash + + +def _get_closure_content(content: types.CellType) -> object: + if callable(content) and hasattr(content, "__code__"): + return content.__code__ + return None + + +def _get_cell_hash_content(content: types.CellType) -> object: + # Safely extract cell contents without blowing up the entire tuple hash + try: + return _get_closure_content(content.cell_contents) + except ValueError: + return None + + +@dataclasses.dataclass(frozen=True) +class CodeId: + filename: str + firstlineno: int + name: str + # When a job restart, the code can be copied to a different path than the previous attempt. In that case + # self.filename will have a different value, we do not want to consider those differences. Instead we + # hash the content of the file and use it as an identifier of the file. + # + # self.filename is kept in the object to give readable information/pointer to the actual file, in a local + # code state it will refer to the first seen file path. + file_hash: str + closure_hash: int | None = None + + # Exclude file name. + def __eq__(self, other: object) -> bool: + if not isinstance(other, CodeId): + return False + return ( + self.file_hash == other.file_hash + and self.firstlineno == other.firstlineno + and self.name == other.name + and self.closure_hash == other.closure_hash + ) + + # Ensure if two CodeIds are the same, then they have the same hash by excluding filename. + def __hash__(self) -> int: + return hash((self.file_hash, self.name, self.firstlineno, self.closure_hash)) + + def __str__(self) -> str: + return f"hash({self.file_hash}){self.filename}:{self.firstlineno}:{self.name}" + + @staticmethod + def make( + code: types.CodeType, closure: tuple[types.CellType, ...] | None = None + ) -> CodeId: + closure_hash = None + if closure: + closure_hash = hash(tuple(_get_cell_hash_content(c) for c in closure)) + + return CodeId( + code.co_filename, + code.co_firstlineno, + code.co_name, + _hash_containing_file(code.co_filename), + closure_hash, + ) + + +@dataclasses.dataclass +class CodeState: + automatic_dynamic: defaultdict[str, FrameStateSizeEntry] = dataclasses.field( + default_factory=lambda: defaultdict(FrameStateSizeEntry) + ) + + +_INIT_CODE_STATE: defaultdict[CodeId, CodeState] | None = None +_CODE_STATE: defaultdict[CodeId, CodeState] | None = None +_LOGGED_DYNAMIC_ALLOWLIST: bool = False +_KNOWN_DYNAMIC_SOURCES: set[str] = set() + + +@dataclasses.dataclass(frozen=True) +class InferStride: + """ + Denotes the quantity stride[dim] * size[dim], which is what the stride would + be for the next physical dimension that results in a contiguous layout. + + For example, given size = [2, 3], stride = [3, 1], we can replace this with + stride = [InferStride(1), 1], because InferStride(1) = stride[1] * size[1] = 1 * 3 = 3 + + Indirecting the representation in this way is important for the join operation + on strides as if we join [2, 3][3, 1] and [2, 4][4, 1], + we don't want [2, None][None, 1] which would get eventually symbolized into + [2, s0][s1, 1] (notice that the relationship between s0 and s1 is broken). + If we instead rewrite the expressions as InferStride so we have [2, 3][InferStride(1), 1] + and [2, 4][InferStride(1), 1] we now join to [2, None][InferStride(1), 1] will + result in [2, s0][s0, 1], as desired. + """ + + dim: int + + +_T = TypeVar("_T") + + +class AutoUnset(enum.Enum): + """ + The identity element of our semilattice, a generic "don't know" element that + is always subsumed when we get more information. + """ + + token = 0 + + +auto_unset = AutoUnset.token + + +class AutoDynamic(enum.Enum): + """ + The top element of our (bounded) semilattice, whenever you merge this with + any other element you always get it again + """ + + token = 0 + + +auto_dynamic = AutoDynamic.token + + +@dataclasses.dataclass +class FrameStateSizeEntry: + scalar: int | AutoDynamic | AutoUnset = dataclasses.field(default=auto_unset) + # NB: We don't have cases where we have a known dimensionality but + # we know NOTHING about the individual sizes + size: AutoDynamic | AutoUnset | tuple[int | AutoDynamic, ...] = dataclasses.field( + default=auto_unset + ) + stride: AutoDynamic | AutoUnset | tuple[int | AutoDynamic | InferStride, ...] = ( + dataclasses.field(default=auto_unset) + ) + excluded_sizes: tuple[int | None, ...] | None = dataclasses.field( + default=None, compare=False + ) + excluded_scalar: int | None = dataclasses.field(default=None, compare=False) + + def render(self) -> str: + # Special cases + def render_single(s: int | AutoDynamic | AutoUnset | InferStride) -> str: + if s is auto_dynamic: + return "?" + elif s is auto_unset: + # This basically shouldn't happen, this is for debugging + return "auto unset" + elif isinstance(s, InferStride): + return f"S({s.dim})" + else: + return str(s) + + def render_tuple(ss: tuple[int | AutoDynamic | InferStride, ...]) -> str: + return "[" + ", ".join(render_single(s) for s in ss) + "]" + + # Common cases + if self.size is auto_dynamic and self.stride is auto_dynamic: + if self.scalar is auto_dynamic: + return "fully dynamic scalar or tensor" + else: + return f"scalar {self.scalar}" + elif self.scalar is auto_dynamic: + if isinstance(self.size, tuple) and isinstance(self.stride, tuple): + return f"tensor size={render_tuple(self.size)} stride={render_tuple(self.stride)}" + + # Fallback + return f"unusual {repr(self)}" + + def __post_init__(self) -> None: + if isinstance(self.scalar, torch.SymInt): + raise AssertionError(self.scalar) + if isinstance(self.size, tuple): + for s in self.size: + if isinstance(s, torch.SymInt): + raise AssertionError(s) + if isinstance(self.stride, tuple): + for s1 in self.stride: + if isinstance(s1, torch.SymInt): + raise AssertionError(s1) + + def is_size_dynamic(self, dim: int) -> bool: + if self.size is auto_dynamic: + return True + if self.size is auto_unset: + return False + return self.size[dim] is auto_dynamic + + def is_stride_dynamic(self, dim: int) -> bool: + # At the moment, dynamic strides is a bit buggy. Good test case + # here is `PYTORCH_TEST_WITH_DYNAMO=1 python test/test_autograd.py + # TestAutograd.test_gradcheck_jacobian_mismatch` + # + # This if statement preserves historical behavior, which is that we + # ONLY make strides dynamic if the size is exactly static everywhere. + # We could potentially relax this but in general we should be very + # careful about when to infer dynamic strides. + # + # Actually, the existing algorithm is already somewhat problematic. + # Suppose a tensor that is sometimes: + # f32[2, 3, 5][15, 5, 1] and other times + # f32[2, 3, 5][5, 10, 1] (specifically, dim 0 and 1 are physically transposed). + # If we infer strides should be (DYNAMIC, DYNAMIC, 1). But this is + # silly: we really should have just guarded on dim order. + if not ( + isinstance(self.size, tuple) and all(type(s) is int for s in self.size) + ): + return False + if self.stride is auto_dynamic: + return True + if self.stride is auto_unset: + return False + return self.stride[dim] is auto_dynamic + + @staticmethod + def _munge_symint(xs: tuple[int, ...]) -> tuple[AutoDynamic | int, ...]: + return tuple(auto_dynamic if isinstance(x, torch.SymInt) else x for x in xs) + + @classmethod + def make_scalar(cls, x: int) -> FrameStateSizeEntry: + return FrameStateSizeEntry(scalar=x, size=auto_dynamic, stride=auto_dynamic) + + @classmethod + def make_tensor( + cls, size: tuple[int, ...], stride: tuple[int, ...] + ) -> FrameStateSizeEntry: + return FrameStateSizeEntry( + scalar=auto_dynamic, + size=cls._munge_symint(size), + stride=cls._munge_symint(stride), + ) + + @classmethod + def make_size(cls, size: tuple[int, ...]) -> FrameStateSizeEntry: + return FrameStateSizeEntry( + scalar=auto_unset, + size=cls._munge_symint(size), + stride=auto_unset, + ) + + @staticmethod + def _merge_atom(x: _T, y: _T) -> AutoDynamic | _T: + if x is auto_unset: + return y + if y is auto_unset: + return x + if x is auto_dynamic or y is auto_dynamic or x != y: + return auto_dynamic + return x + + @classmethod + def _merge_atom_tup( + cls, + xs: AutoDynamic | AutoUnset | tuple[_T, ...], + ys: AutoDynamic | AutoUnset | tuple[_T, ...], + ) -> AutoDynamic | AutoUnset | tuple[AutoDynamic | _T, ...]: + if xs is auto_unset: + return ys + if ys is auto_unset: + return xs + if xs is auto_dynamic or ys is auto_dynamic: + return auto_dynamic + if len(xs) != len(ys): + return auto_dynamic + return tuple(cls._merge_atom(x, y) for x, y in zip(xs, ys)) + + def __ior__(self, other: Self) -> Self: + # Record current static sizes before merge. For dims that become + # dynamic, the exclusion guard will reject these values so inputs + # fall through to the earlier, more specialized cache entry. + # Already-dynamic dims become None and are ignored by the guard. + # When no dim transitions, clear stale excluded_sizes so later + # compilations don't inherit exclusions from earlier transitions. + new_size = self._merge_atom_tup(self.size, other.size) + if isinstance(self.size, tuple): + if new_size != self.size: + self.excluded_sizes = tuple( + s if type(s) is int else None for s in self.size + ) + elif self.excluded_sizes is not None: + self.excluded_sizes = None + self.size = new_size + # Same idea for scalars: record the static value about to become dynamic. + # Re-derive like excluded_sizes: only set when transitioning from a + # concrete int, clear when already dynamic. + if ( + type(self.scalar) is int + and type(other.scalar) is int + and self.scalar != other.scalar + ): + self.excluded_scalar = self.scalar + elif self.scalar is auto_dynamic and self.excluded_scalar is not None: + self.excluded_scalar = None + self.scalar = self._merge_atom(self.scalar, other.scalar) + self.stride = self._merge_atom_tup(self.stride, other.stride) + return self + + +def update_automatic_dynamic( + tx: InstructionTranslatorBase, + name: str, + entry: FrameStateSizeEntry, + *, + is_unspecialized_nn_module: bool = False, +) -> FrameStateSizeEntry: + code_id = CodeId.make(tx.f_code, tx.closure) + frame_state = get_code_state()[code_id] + if torch._dynamo.config.automatic_dynamic_shapes: + is_update = name in frame_state.automatic_dynamic + mut_entry = frame_state.automatic_dynamic[name] + old_entry = copy.copy(mut_entry) + mut_entry |= entry + + # Do some logs (damn, I spend more code logging than I do actually doing + # the updates lol) + if is_update and old_entry.scalar != mut_entry.scalar: + symbolic_shape_log.info( + "marking %s as dynamic (from automatic dynamic/PGO)", + name, + ) + log.debug( + "automatic dynamic int %s val %s != %s", + name, + entry.scalar, + old_entry.scalar, + ) + CompileEventLogger.instant( + "automatic_dynamic", + { + "name": name, + "dim_changed": "scalar", + "reason": "scalar change", + "cached": str(old_entry.scalar), + "new": str(entry.scalar), + }, + ) + if is_unspecialized_nn_module: + log.info( + "%s is converted to a symbolic integer. It is an attribute of a " + "user defined nn module class. If you wish to keep it static, you can " + "mark the nn module class as `torch._dynamo.mark_static`.", + name, + ) + + def log_tup( + tup_name: str, short_reason: str, long_reason: str, i: int | None = None + ) -> None: + entry_tup = ( + getattr(entry, tup_name) if i is None else getattr(entry, tup_name)[i] + ) + old_entry_tup = ( + getattr(old_entry, tup_name) + if i is None + else getattr(old_entry, tup_name)[i] + ) + symbolic_shape_log.info( + "marking %s as dynamic (from automatic dynamic/PGO)", + name, + ) + log.debug( + "automatic dynamic %s %s %s %s != %s", + tup_name, + name, + short_reason, + # NB: We used to only report len(...) here for dim mismatch + entry_tup, + old_entry_tup, + ) + CompileEventLogger.instant( + "automatic_dynamic", + { + "name": name, + "dim_changed": "all" if i is None else i, + "reason": long_reason, + "cached": str(old_entry_tup), + "new": str(entry_tup), + }, + ) + + if is_update and old_entry.size != mut_entry.size: + if isinstance(old_entry.size, tuple) and isinstance(entry.size, tuple): + if len(old_entry.size) != len(entry.size): + log_tup("size", "dim", "dimensionality change") + else: + for i in range(len(entry.size)): + if old_entry.size[i] != entry.size[i]: + log_tup("size", f"size({i})", "size change", i) + else: + log_tup("size", "other", "other") + + if is_update and old_entry.stride != mut_entry.stride: + if isinstance(old_entry.stride, tuple) and isinstance(entry.stride, tuple): + if len(old_entry.stride) != len(entry.stride): + log_tup("stride", "dim", "dimensionality change") + else: + for i in range(len(entry.stride)): + if old_entry.stride[i] != entry.stride[i]: + log_tup("stride", f"stride({i})", "stride change", i) + else: + log_tup("stride", "other", "other") + else: + old_entry = frame_state.automatic_dynamic[name] + log.debug( + "automatic dynamic is off, overwriting int %s val %s -> %s", + name, + old_entry.scalar, + entry.scalar, + ) + frame_state.automatic_dynamic[name] = entry + mut_entry = entry + + return mut_entry + + +def process_automatic_dynamic( + tx: InstructionTranslatorBase, + name: str, + entry: FrameStateSizeEntry, + *, + is_unspecialized_nn_module: bool = False, +) -> FrameStateSizeEntry: + if (st := tx.distributed_state) is None: + return update_automatic_dynamic( + tx, + name, + entry, + is_unspecialized_nn_module=is_unspecialized_nn_module, + ) + elif st.all_states is None: + # Preflight, always pretend as if it's static. The point here + # is we want to get through the preflight quickly, and static + # will run faster. The preexisting frame state will get + # applied anyway after we do compiler collectives. + # TODO: I'm not sure if we should just bong the entire pgo + # state here, it kind of depends if we're going to have other + # things that talk in compiler collective. Also, the PGO + # state, if we've already inferred something is automatic + # dynamic, will have lost the actual input sizes, which might + # be useful for debugging purposes (e.g., observing 0/1 + # specialization). Bonging the entire PGO state here would + # let us delete this logic here; the compiler collective + # would just directly update_automatic_dynamic + st.local_state.automatic_dynamic[name] = entry + return entry + else: + # Apply the updates. NB: all_states includes the local state + # too. + res = None + for sub_state in st.all_states: + if name in sub_state.automatic_dynamic: + res = update_automatic_dynamic( + tx, + name, + sub_state.automatic_dynamic[name], + is_unspecialized_nn_module=is_unspecialized_nn_module, + ) + if res is None: + raise AssertionError( + "expected at least one matching automatic_dynamic entry across ranks" + ) + return res + + +def format_cache_key(key: str) -> str: + # NB: We always use global rank for keys, even though they are overkill + # for local only cache + rank = None + if dist.is_available() and dist.is_initialized(): + rank = dist.get_rank() + + tag = torch.compiler.config.cache_key_tag + return f"{key}:{rank}:{tag}" + + +def get_cache_key() -> str | None: + # TODO: info versions of these logs that log only once + if torch.compiler.config.force_disable_caches: + warn_once( + "dynamo_pgo force disabled by torch.compiler.config.force_disable_caches" + ) + return None + + # NB: We namespace the cache keys so that only user-specified job id + # can alias with each other. + if (r := torch.compiler.config.job_id) is not None: + if r.startswith("mast:"): + raise ReservedWorkflowIdUserError( + "torch.compiler.config.job_id with prefix 'mast:' is reserved for " + "automatically generated job id associated with a specific MAST job " + "name and version." + ) + return format_cache_key(r) + + if (name_version := torch._utils_internal.get_mast_job_name_version()) is not None: + mast_job_name, mast_job_version = name_version + return format_cache_key(f"mast:{mast_job_name}:{mast_job_version}") + + return None + + +def get_extra_cache_key(sticky_key: str) -> str | None: + if torch.compiler.config.force_disable_caches: + warn_once( + "dynamo_pgo force disabled by torch.compiler.config.force_disable_caches" + ) + return None + + return format_cache_key(sticky_key) + + +# This solely controls local PGO +def code_state_path(cache_key: str) -> str | None: + if not torch._dynamo.config.automatic_dynamic_local_pgo: + log.debug("automatic_dynamic_local_pgo not enabled") + return None + + from torch._inductor.runtime.runtime_utils import cache_dir + + code_state_key = re.sub(r'[<>:"/\\|?*]', "_", f"code_state_{cache_key}.pkl") + return os.path.join(cache_dir(), "dynamo", code_state_key) + + +def should_use_remote_dynamo_pgo_cache() -> bool: + if torch.compiler.config.force_disable_caches: + return False + + if (r := torch._dynamo.config.automatic_dynamic_remote_pgo) is not None: + return r + + if not is_fbcode(): + return False + + if torch._utils_internal.is_fb_unit_test(): + return False + + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + except ModuleNotFoundError: + return False + + return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int( + "pytorch/remote_cache:dynamo_pgo_version" + ) + + +def get_remote_cache() -> RemoteCache[JsonDataTy] | None: + from torch._inductor.remote_cache import create_cache + + if not should_use_remote_dynamo_pgo_cache(): + return None + + return create_cache( + "dynamo-pgo", + is_fbcode(), + "FbRemoteDynamoPGOCache", + "RemoteDynamoPGOCache", + ) + + +def _collect_dynamic_sources(code_state: CodeState) -> OrderedSet[str]: + dynamic_sources: OrderedSet[str] = OrderedSet() + for src, fs in code_state.automatic_dynamic.items(): + dynamic = False + if isinstance(fs.size, tuple): + dynamic = auto_dynamic in fs.size # type: ignore[operator] + elif fs.scalar == auto_dynamic: + dynamic = True + if dynamic: + dynamic_sources.add(src) + return dynamic_sources + + +def _collect_missing_sources(all_sources: OrderedSet[str]) -> OrderedSet[str]: + from torch._dynamo.variables.builder import is_dynamic_source + + global _KNOWN_DYNAMIC_SOURCES + missing_sources: OrderedSet[str] = OrderedSet() + for src in all_sources: + if src in _KNOWN_DYNAMIC_SOURCES: + continue + elif is_dynamic_source(src): + _KNOWN_DYNAMIC_SOURCES.add(src) + continue + missing_sources.add(src) + return missing_sources + + +def log_frame_dynamic_whitelist(f_code: types.CodeType) -> None: + global _KNOWN_DYNAMIC_SOURCES + code_id = CodeId.make(f_code, None) + frame_state = get_code_state()[code_id] + all_dynamic_sources = _collect_dynamic_sources(frame_state) + frame_whitelist = ",".join(all_dynamic_sources) + missing_whitelist = ",".join(_collect_missing_sources(all_dynamic_sources)) + if frame_whitelist: + with dynamo_timed(name := "pgo.dynamic_whitelist", log_pt2_compile_event=True): + CompileEventLogger.pt2_compile( + name, + recompile_dynamic_whitelist=frame_whitelist, + missing_dynamic_whitelist=missing_whitelist, + ) + + +def _log_size_mismatch_recompile() -> None: + global _LOGGED_DYNAMIC_ALLOWLIST + if not _LOGGED_DYNAMIC_ALLOWLIST: + torch._utils_internal.add_mlhub_insight( + category="dynamic_shapes_analysis", + insight="Dynamic shape recompilation detected", + insight_description="PGO detected a recompilation due to dynamic shapes. \ + Please follow the instruction from the action link to reduce \ + recompilation overhead.", + ) + # add mlhub insight only once per rank + _LOGGED_DYNAMIC_ALLOWLIST = True + + +def render_code_state(cs: defaultdict[CodeId, CodeState]) -> str: + code_state_str = "\n".join( + f"{k}:\n" + + "\n".join( + f" {src}: {fs.render()}" for src, fs in v.automatic_dynamic.items() + ) + for k, v in cs.items() + ) + dynamic_sources: OrderedSet[str] = OrderedSet() + for state in cs.values(): + dynamic_sources.update(_collect_dynamic_sources(state)) + if dynamic_sources: + code_state_str += ( + "\n\nPGO detected a recompilation due to dynamic shapes. " + "To reduce shape recompilations by compiling dynamically to start, " + f'set environment variable TORCH_COMPILE_DYNAMIC_SOURCES="{",".join(dynamic_sources)}"' + ) + return code_state_str + + +@CacheArtifactFactory.register +class PGOCacheArtifact(CacheArtifact): + @override + def populate_cache(self) -> None: + meta = write_local_impl( + self._rewrite_cache_key_for_mega_cache(self.key), self.content + ) + if meta is None: + raise AssertionError( + "write_local_impl returned None during PGO cache population" + ) + + @override + @staticmethod + def type() -> str: + return "pgo" + + @staticmethod + def _rewrite_cache_key_for_mega_cache(original_key: str) -> str: + """ + The PGO cache artifact key for a MAST job contains the job name and the version. + When we want to use the cache artifact on a different MAST job, we need to + update the key to use the new MAST job's name and version. + """ + if not original_key.startswith("mast:"): + # if original_key is overridden, then don't change it + return original_key + if (new_key := get_cache_key()) is not None: + return new_key + return original_key + + +def hit(key: str, ty: str) -> defaultdict[CodeId, CodeState]: + global _INIT_CODE_STATE + if not isinstance(_CODE_STATE, defaultdict): + raise AssertionError( + f"expected _CODE_STATE to be a defaultdict, got {type(_CODE_STATE)}" + ) + log.info("get_code_state %s hit %s, %d entries", key, ty, len(_CODE_STATE)) + trace_structured_artifact( + f"get_{ty}_code_state", + "string", + lambda: render_code_state(_CODE_STATE), # type: ignore[arg-type] + ) + set_feature_use("pgo", True) + _INIT_CODE_STATE = copy.deepcopy(_CODE_STATE) + return _CODE_STATE + + +def get_local_code_state(cache_key: str) -> defaultdict[CodeId, CodeState] | None: + global _CODE_STATE + path = code_state_path(cache_key) + if path is not None and os.path.exists(path): + with dynamo_timed( + name := "pgo.get_local_code_state", log_pt2_compile_event=True + ): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + # Read lock not necessary as we always write atomically write to + # the actual location + with open(path, "rb") as f: + try: + content = f.read() + _CODE_STATE = pickle.loads(content) + CompileEventLogger.pt2_compile(name, cache_size_bytes=f.tell()) + except Exception: + log.warning( + "get_code_state failed while reading %s", path, exc_info=True + ) + else: + CacheArtifactRecorder(PGOCacheArtifact.type(), cache_key).record( + content + ) + return hit(path, "local") + return None + + +def lookup_remote_cache_entry( + remote_cache: RemoteCache[JsonDataTy], + cache_key: str, + event_name: str | None = None, +) -> defaultdict[CodeId, CodeState] | None: + code_state = None + try: + cache_data = remote_cache.get(cache_key) + except Exception: + log.warning("get_code_state failed remote read on %s", cache_key, exc_info=True) + else: + if cache_data is not None: + try: + if not isinstance(cache_data, dict): + raise AssertionError( + f"expected cache_data to be a dict, got {type(cache_data)}" + ) + data = cache_data["data"] + if not isinstance(data, str): + raise AssertionError( + f"expected cache_data['data'] to be a str, got {type(data)}" + ) + payload = base64.b64decode(data) + if event_name is not None: + CompileEventLogger.pt2_compile( + event_name, cache_size_bytes=len(payload) + ) + code_state = pickle.loads(payload) + except Exception: + log.warning( + "get_code_state failed parsing remote result on %s", + cache_key, + exc_info=True, + ) + else: + CacheArtifactRecorder(PGOCacheArtifact.type(), cache_key).record( + payload + ) + else: + log.info("get_code_state remote miss on %s", cache_key) + return code_state + + +def get_remote_code_state(cache_key: str) -> defaultdict[CodeId, CodeState] | None: + global _CODE_STATE + remote_cache = get_remote_cache() + if remote_cache is not None: + with dynamo_timed( + name := "pgo.get_remote_code_state", + log_pt2_compile_event=True, + dynamo_compile_column_us="pgo_get_remote_code_state_time_us", + ): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + code_state = lookup_remote_cache_entry(remote_cache, cache_key, name) + if code_state is not None: + _CODE_STATE = code_state + return hit(cache_key, "remote") + return None + + +def get_extra_remote_code_state(cache_key: str) -> None: + """ + Reads an additional PGO profile from the given cache key, and merges it with the default PGO profile. + """ + global _CODE_STATE + if _CODE_STATE is None: + raise AssertionError( + "_CODE_STATE must be initialized before reading extra remote code state" + ) + + remote_cache = get_remote_cache() + if remote_cache is not None: + with dynamo_timed( + name := "pgo.get_extra_remote_code_state", + log_pt2_compile_event=True, + dynamo_compile_column_us="pgo_get_remote_code_state_time_us", + ): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + code_state = lookup_remote_cache_entry(remote_cache, cache_key) + log.info( + "get_extra_code_state %s hit, %d entries", + cache_key, + len(code_state) if code_state is not None else 0, + ) + if code_state is not None: + if _CODE_STATE: + raise AssertionError( + "expected _CODE_STATE to be empty before merging extra remote state" + ) + _CODE_STATE = code_state + # log to tlparse + trace_structured_artifact( + "get_extra_remote_code_state", + "string", + lambda: render_code_state(code_state), + ) + + +def get_code_state() -> defaultdict[CodeId, CodeState]: + global _CODE_STATE, _INIT_CODE_STATE + if _CODE_STATE is not None: + return _CODE_STATE + + # Initialize it (even if we don't look up profile) + _CODE_STATE = defaultdict(CodeState) + + cache_key = get_cache_key() + if cache_key is None: + return _CODE_STATE + + # Attempt local + local_code_state = get_local_code_state(cache_key) + + # Attempt remote + if local_code_state is None: + get_remote_code_state(cache_key) + + # Attempt additional remote if neither local/default remote succeeded + if ( + not _CODE_STATE + and (sticky_read := torch.compiler.config.pgo_extra_read_key) is not None + ): + extra_read_key = get_extra_cache_key(sticky_read) + if extra_read_key is not None: + get_extra_remote_code_state(extra_read_key) + + log.info("get_code_state using default") + + if _CODE_STATE is None: + raise AssertionError("_CODE_STATE should have been initialized above") + return _CODE_STATE + + +def put_code_state() -> None: + if _CODE_STATE is None: + log.info("put_code_state: never initialized, will not write") + return + + if _CODE_STATE == _INIT_CODE_STATE: + log.info("put_code_state: no change, skipping") + return + + cache_key = get_cache_key() + if cache_key is None: + log.info("put_code_state: no cache key, skipping") + return + + put_local_code_state(cache_key) + put_remote_code_state(cache_key) + if (sticky_write := torch.compiler.config.pgo_extra_write_key) is not None: + extra_write_key = get_extra_cache_key(sticky_write) + if extra_write_key is not None: + put_remote_code_state(extra_write_key) + + +def write_local_impl(cache_key: str, pickled_code: bytes) -> tuple[str, int] | None: + path = code_state_path(cache_key) + + if path is None: + return None + + # If the user isn't misusing our API, we should have exclusive access to + # this directory. But it's not too hard + + tmp_path = path + ".tmp" + lock_path = path + ".lock" + # We /mostly/ don't need the lock but the tmp file could be clobbered + # TODO: use a safe tempfile create to eliminate lock + from torch.utils._filelock import FileLock + + os.makedirs(os.path.dirname(path), exist_ok=True) + + with FileLock(lock_path, timeout=LOCK_TIMEOUT): + with open(tmp_path, "wb") as f: + f.write(pickled_code) + size = f.tell() + os.replace(tmp_path, path) + return path, size + + +def put_local_code_state(cache_key: str) -> None: + with dynamo_timed(name := "pgo.put_local_code_state", log_pt2_compile_event=True): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + if _CODE_STATE is None: + raise AssertionError( + "_CODE_STATE must be initialized before writing local code state" + ) + + pickled_code = pickle.dumps(_CODE_STATE) + + CacheArtifactRecorder(PGOCacheArtifact.type(), cache_key).record(pickled_code) + + meta = write_local_impl(cache_key, pickled_code) + if meta is None: + log.info("put_code_state: local cache disabled") + return + path, size = meta + + CompileEventLogger.pt2_compile(name, cache_size_bytes=size) + log.info("put_code_state: wrote local %s, %d entries", path, len(_CODE_STATE)) + trace_structured_artifact( + "put_local_code_state", + "string", + lambda: render_code_state(_CODE_STATE), + ) + + +def put_remote_code_state(cache_key: str, extra_code_state: bool = False) -> None: + event_name = ( + "put_remote_code_state" + if not extra_code_state + else "put_extra_remote_code_state" + ) + with dynamo_timed( + name := f"pgo.{event_name}", + log_pt2_compile_event=True, + dynamo_compile_column_us="pgo_put_remote_code_state_time_us", + ): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + if _CODE_STATE is None: + raise AssertionError( + "_CODE_STATE must be initialized before writing remote code state" + ) + + remote_cache = get_remote_cache() + + if remote_cache is None: + log.info("%s: remote cache disabled", event_name) + return + + content = pickle.dumps(_CODE_STATE) + CompileEventLogger.pt2_compile(name, cache_size_bytes=len(content)) + cache_data: JsonDataTy = { + "data": base64.b64encode(content).decode("ascii"), + } + remote_cache.put(cache_key, cache_data) + log.info( + "%s: wrote remote %s, %d entries", event_name, cache_key, len(_CODE_STATE) + ) + # TODO: don't log this multiple times + trace_structured_artifact( + event_name, + "string", + lambda: render_code_state(_CODE_STATE), + ) + + +# NB: this does NOT reset the cached code state on disk +def reset_code_state() -> None: + global _CODE_STATE, _INIT_CODE_STATE, _LOGGED_DYNAMIC_ALLOWLIST + _CODE_STATE = None + _INIT_CODE_STATE = None + _LOGGED_DYNAMIC_ALLOWLIST = False diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d4a07c009d4ccaef660505a55bf12cb2c9588cb7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__init__.py @@ -0,0 +1,569 @@ +""" +Python polyfills for common builtins. +""" + +# NOTE: 1. Please do not import any submodule in the directory here to avoid circular imports. +# 2. While adding a new polyfill module, also add it to POLYFILLED_MODULE_NAMES in loader.py. +# Add it in the TYPE_CHECKING block below as well. + +import types +from collections import OrderedDict +from collections.abc import Callable, Hashable, Iterable, Iterator, Mapping, Sequence +from itertools import repeat as _repeat +from operator import eq, ge, gt, le, lt, ne +from typing import Any, TYPE_CHECKING, TypeGuard, TypeVar +from typing_extensions import TypeIs + +import torch + + +T = TypeVar("T") +U = TypeVar("U") +C = TypeVar("C") + + +if TYPE_CHECKING: + from ..utils import dict_keys + + # Load by torch._dynamo.polyfills.loader + # See also the POLYFILLED_MODULE_NAMES in torch/_dynamo/polyfills/loader.py + # Put the submodules here to avoid circular imports + from . import ( + _collections as _collections, + builtins as builtins, + functools as functools, + io as io, + itertools as itertools, + operator as operator, + os as os, + pytree as pytree, + struct as struct, + sys as sys, + torch_c_nn as torch_c_nn, + traceback as traceback, + ) + +from torch.overrides import BaseTorchFunctionMode + + +# These classes handle support for TorchFunctionModes across +# graph breaks +# Today the TorchFunctionMode enter (for the classes we support) +# simply pushes the mode onto the stack. Since after this occurs +# the stack is mutated, and we replay these mutations, we don't need +# any cleanup logic to be run once the graph break occurs, we simply replay +# these mutations to ensure at the graph break the torch function mode stack is correct +# and reconstruct the torch function mode stack normally +# when we compile the resume function on the other side of the break. +# However, to ensure we exit properly +# in the resume function, we need to re-enter the contexts as we do other contexts. +# These contexts do nothing on enter, but provide the correct exit logic to ensure +# the stack state is correct. +class NoEnterTorchFunctionMode(BaseTorchFunctionMode): + def __enter__(self) -> None: + pass + + +# Used by WrappedUserFunctionVariable and similar to inline decorated function +# calls with bytecode backing. Without this, the context enter/exit happens in +# Python-level VT code, so a nested graph break inside `fn` would skip applying +# the context in the compiled fn/resume. By inlining through this polyfill, the +# `with` statement has real bytecode that the resume function can continue from. +def _fn_with_ctx(ctx: Any, fn: Callable[..., T], *args: Any, **kwargs: Any) -> T: + with ctx: + return fn(*args, **kwargs) + + +def index( + iterator: Iterator[T], item: T, start: int = 0, end: int | None = None +) -> int: + from itertools import islice + + for i, elem in islice(enumerate(iterator), start, end): + if elem is item or elem == item: + return i + # This will not run in dynamo + raise ValueError(f"{item} is not in {type(iterator)}") + + +def repeat(item: T, count: int) -> Iterator[T]: + for _ in range(count): + yield item + + +def radians(x: float) -> float: + import math + + return math.pi / 180.0 * x + + +def impl_IS_MAPPING(a: object) -> TypeIs[Mapping[Any, Any]]: + return isinstance(a, Mapping) + + +def impl_MATCH_SEQUENCE(a: object) -> TypeGuard[Sequence[Any]]: + return isinstance(a, Sequence) and not isinstance(a, (str, bytes, bytearray)) + + +def _match_class_attr(obj: object, name: str, seen: set[str]) -> object: + if name in seen: + raise TypeError(f"{type(obj)} got multiple sub-patterns for attribute {name}") + + attr = getattr(obj, name) + seen.add(name) + return attr + + +def impl_MATCH_CLASS( + subject: object, cls: type, nargs: int, kwargs: tuple[str, ...] +) -> tuple[object, ...] | None: + if not isinstance(cls, type): + raise TypeError("called match pattern must be a class") + + if not isinstance(subject, cls): + return None + + typ = type(subject) + match_self = False + match_args = () + + attrs = [] + seen = set() + + if nargs: + if hasattr(typ, "__match_args__"): + match_args = typ.__match_args__ + + if not isinstance(match_args, tuple): + raise TypeError( + f"{typ}.__match_args__ must be a tuple, (got {type(match_args)})" + ) + + for name in match_args[:nargs]: + if not isinstance(name, str): + raise TypeError( + f"__match_args__ elements must be strings (got {type(name)})" + ) + attrs.append(_match_class_attr(subject, name, seen)) + else: + # We should somehow check if the type has TPFLAGS_MATCH_SELF set + # match_self is only true if TPFLAGS_MATCH_SELF is set, but there is + # no way to check for it directly in Python. So we assume it is set + # if there are no __match_args__ + match_self = True + attrs.append(subject) + + allowed = 1 if match_self else len(match_args) + if allowed < nargs: + raise TypeError( + f"accepts {allowed} positional sub-patterns ({nargs} given)" + ) + + for name in kwargs: + attrs.append(_match_class_attr(subject, name, seen)) + + return tuple(attrs) + + +def impl_MATCH_KEYS(obj: Mapping[T, U], keys: tuple[T, ...]) -> tuple[U, ...] | None: + if not isinstance(obj, Mapping): + raise AssertionError(f"Expected a Mapping, got {type(obj)}") + if all(key in obj for key in keys): + return tuple(obj[key] for key in keys) + else: + return None + + +def impl_CONTAINS_OP_fallback(a: T, b: Iterable[T]) -> bool: + # performs fallback "a in b" + # CPython: PySequence_Contains → _PySequence_IterSearch → PyObject_GetIter + # PyObject_GetIter itself falls back to PySequence_GetItem when tp_iter is NULL. + if hasattr(b, "__iter__"): + for x in b: + if x == a: + return True + return False + if hasattr(b, "__getitem__"): + i = 0 + while True: + try: + if b.__getitem__(i) == a: + return True + i += 1 + except IndexError: + return False + raise TypeError(f"argument of type {type(b)} is not iterable") + + +def accumulate_grad( + x: torch.Tensor, + variable_grad: torch.Tensor | None, + new_grad: torch.Tensor | None, +) -> torch.Tensor | None: + # polyfills according to the Gradient Layout Contract + if new_grad is None: + return variable_grad + new_grad_strided = torch.empty_like(x) + new_grad_strided.copy_(new_grad) + if variable_grad is None: + return new_grad_strided + elif variable_grad.is_sparse and not new_grad_strided.is_sparse: + return new_grad_strided + variable_grad + elif torch.is_grad_enabled(): + return variable_grad + new_grad_strided + else: + variable_grad.add_(new_grad_strided) + return variable_grad + + +def accumulate_grad_no_alias( + x: torch.Tensor, + variable_grad: torch.Tensor | None, + new_grad: torch.Tensor | None, +) -> torch.Tensor | None: + # Mirrors inductor::accumulate_grad_: same gradient layout logic as + # accumulate_grad, but the returned grad must not alias any input. + if new_grad is None: + if variable_grad is None: + return None + return variable_grad.clone() + new_grad_strided = torch.empty_like(x) + new_grad_strided.copy_(new_grad) + if variable_grad is None: + return new_grad_strided + elif variable_grad.is_sparse and not new_grad_strided.is_sparse: + return new_grad_strided + variable_grad + elif torch.is_grad_enabled(): + return variable_grad + new_grad_strided + else: + result = variable_grad.clone() + result.add_(new_grad_strided) + return result + + +# This mirrors +# https://github.com/python/cpython/blob/a1c52d1265c65bcf0d9edf87e143843ad54f9b8f/Objects/listobject.c#L3352-L3413 +def list_cmp( + op: Callable[[Any, Any], bool], left: Sequence[T], right: Sequence[T] +) -> bool: + """emulate `(1,2,3) > (1,2)` etc""" + + # Optimization: For equality, short-circuit if lengths differ + # This avoids iterating through elements and triggering guards on SymInts + left_len = len(left) + right_len = len(right) + + if op is eq and left_len != right_len: + return False + if op is ne and left_len != right_len: + return True + + # Apply `op` to the first pair that differ + for a, b in zip(left, right): + if a != b: + return op(a, b) + + # No more pairs to compare, so compare sizes. + return op(left_len, right_len) + + +def dict___eq__(d: dict[T, U], other: dict[T, U]) -> bool: + if (len(d) != len(other)) or (d.keys() != other.keys()): + return False + + if all(isinstance(a, OrderedDict) for a in (d, other)): + return list(d.items()) == list(other.items()) + + # CPython's dict_equal uses PyObject_RichCompareBool for value + # comparison, which has an identity shortcut (if v is w, eq is True). + # This matters for NaN: {k: nan} == {k: nan} is True when same nan. + for k, v in d.items(): + ov = other[k] + if v is not ov and v != ov: + return False + + return True + + +def dictview_richcompare( + op: Callable[[Any, Any], bool], self: Iterable[T], other: Iterable[T] +) -> bool: + """Mirrors dictview_richcompare for dict_keys/dict_items vs set/frozenset. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L5952-L6010 + Uses len() and ``in`` so that Dynamo traces through sq_length/sq_contains. + """ + len_self = len(self) # type: ignore[arg-type] + len_other = len(other) # type: ignore[arg-type] + + if op is eq: + if len_self != len_other: + return False + return all(item in other for item in self) + if op is ne: + if len_self != len_other: + return True + return not all(item in other for item in self) + if op is lt: + if len_self >= len_other: + return False + return all(item in other for item in self) + if op is le: + if len_self > len_other: + return False + return all(item in other for item in self) + if op is gt: + if len_self <= len_other: + return False + return all(item in self for item in other) + # ge + if len_self < len_other: + return False + return all(item in self for item in other) + + +def assert_dict_equal( + self_: Any, d1: dict[T, U], d2: dict[T, U], msg: str | None = None +) -> None: + self_.assertTrue(d1 == d2, msg) + + +def assert_multi_line_equal( + self_: Any, first: T, second: T, msg: str | None = None +) -> None: + return self_.assertTrue(first == second, msg) + + +# The original impl. uses difflib +def assert_sequence_equal( + self_: Any, + seq1: Sequence[T], + seq2: Sequence[T], + msg: str | None = None, + seq_type: type[Any] | None = None, +) -> None: + return self_.assertTrue(seq1 == seq2, msg) + + +def getattr_and_trace(*args: Any, **kwargs: Any) -> Any: + wrapper_obj = args[0] + attr_name = args[1] + fn = getattr(wrapper_obj, attr_name) + return fn(*args[2:], **kwargs) + + +def getattr_and_trace_no_nested_graph_breaks(*args: Any, **kwargs: Any) -> Any: + with torch._dynamo.disable_nested_graph_breaks(): + return getattr_and_trace(*args, **kwargs) + + +def mapping_get(obj: Mapping[T, U], key: T, value: U | None = None, /) -> U | None: + try: + return obj.__getitem__(key) + except KeyError: + return value + + +def instantiate_user_defined_class_object( + cls: type[T], /, *args: Any, **kwargs: Any +) -> T: + obj = cls.__new__(cls, *args, **kwargs) + + # Only call __init__ if the object's type is a subclass of cls. + # CPython uses PyType_IsSubtype(Py_TYPE(obj), type) at the C level, which does NOT + # go through metaclass __instancecheck__. Using isinstance() here would be wrong + # for classes with custom __instancecheck__ (e.g. torch.ByteStorage). + # Reference: https://github.com/python/cpython/blob/3.12/Objects/typeobject.c#L1670-L1673 + if issubclass(type(obj), cls): + obj.__init__(*args, **kwargs) + return obj + + +def mutable_mapping_update( + self, + data: Mapping[T, U] | Iterable[tuple[T, U]] = (), + /, + **kwargs: Any, +) -> None: + if isinstance(data, Mapping): + # Merge standard mapping with PyMapping_Items + for key, value in data.items(): + self[key] = value + # FIXME: Enabling the `elif`-branch below needs too many `VariableClass.call_obj_hasattr` changes. + # >>> class Foo: + # ... def __init__(self): + # ... self.keys = lambda: ['a', 'b', 'c'] # not required to be a method + # ... + # ... def __getitem__(self, key): + # ... return 0 + # ... + # >>> dict(Foo()) + # {'a': 0, 'b': 0, 'c': 0} + # + # > This is a rare case, so we comment it out for now. + # + # elif hasattr(data, "keys"): + # # Merge mapping-like object with PyMapping_Keys + PyObject_GetItem + # for key in data.keys(): + # self[key] = data[key] + else: + if not isinstance(data, Iterable): + raise TypeError(f"{type(data).__name__!r} object is not iterable") + # Likely a sequence of pairs + for key, value in data: + self[key] = value + + if kwargs: + for key, value in kwargs.items(): + self[key] = value + + +# Used with something like dict(obj) +def construct_dict( + cls: type[T], + data: Mapping[object, object] | Iterable[tuple[object, object]] = (), + /, + **kwargs: Any, +) -> T: + self = cls.__new__(cls) + mutable_mapping_update(self, data, **kwargs) + return self + + +def foreach_map_fn(*args: Any) -> Any: + op = args[0] + new_args: list[Any] = [] + at_least_one_list = False + for arg in args[1:]: + if not isinstance(arg, (list, tuple)): + new_args.append(_repeat(arg)) + else: + at_least_one_list = True + new_args.append(arg) + + # Just apply op once to args if there are no lists + if not at_least_one_list: + return op(*args[1:]) + + out = [] + for unpacked in zip(*new_args): + out.append(op(*unpacked)) + + return out + + +def foreach_lerp_inplace( + self, + end: list[torch.Tensor] | tuple[torch.Tensor, ...], + weight: float | int | torch.Tensor, +) -> None: + # Decompose lerp via addcmul_ for FMA. Uses the same dual-formula + # approach as CUDA's native lerp to get bitwise identical results: + # |w| < 0.5 (low): fma(w, diff, start) + # |w| >= 0.5 (high): fma(-(1-w), diff, end) + # For tensor weights (e.g. 0-dim tensor from tensor betas in Adam) the + # low formula is always used because the native lerp_scalar lowering + # would crash on float(weight) for symbolic expressions. + diff = torch._foreach_sub(end, self) + if isinstance(weight, torch.Tensor): + # Select base and weight for the dual formula before a single addcmul: + # low (|w| < 0.5): fma(w, diff, self) + # high (|w| >= 0.5): fma(-(1-w), diff, end) + mask = weight.abs() >= 0.5 + neg_omw = -(1.0 - weight) + w = torch.where(mask, neg_omw, weight) + bases = [torch.where(mask, e, s) for s, e in zip(self, end)] + w_list = [w] * len(diff) + torch._foreach_addcmul_(bases, w_list, diff) + for s, b in zip(self, bases): + s.copy_(b) + else: + abs_weight = weight if weight >= 0 else -weight + if abs_weight >= 0.5: + # High formula: end + (-(1-w)) * diff → fma(-(1-w), diff, end) + # Compute 1-w in target dtype to match CUDA rounding. + d0 = self[0] + neg_omw = -(1.0 - torch.tensor(weight, dtype=d0.dtype, device=d0.device)) + neg_omw_list = [neg_omw] * len(diff) + for s, e in zip(self, end): + s.copy_(e) + torch._foreach_addcmul_(self, neg_omw_list, diff) + else: + # Low formula: start + w * diff → fma(w, diff, start) + weights = [torch.full_like(d, weight) for d in diff] + torch._foreach_addcmul_(self, weights, diff) + return self + + +def foreach_pow_scalar( + scalar: Any, exps: Sequence[bool | complex | float | int] +) -> tuple[torch.Tensor, ...]: + return torch._foreach_pow([scalar for _ in exps], exps) + + +def predicate(obj: object) -> bool: + # This will cause the rest of dynamo to handle the if statement correctly, so we don't have to rewrite it here. + # We can't just use bool() here since we can't trace into that in general. + if obj: + return True + return False + + +def group_tensors_by_device_and_dtype( + tensorlistlist: list[list[torch.Tensor | None]], with_indices: bool = False +) -> dict[tuple[torch.device, torch.dtype], tuple[list[list[Any]], list[int]]]: + """Pure Python implementation of torch._C._group_tensors_by_device_and_dtype. + + Groups tensors by their device and dtype. This is useful before sending + tensors off to a foreach implementation, which requires tensors to be on + one device and dtype. + + Args: + tensorlistlist: A list of lists of tensors (tensors can be None). + with_indices: If True, track original indices in the output. + + Returns: + A dict mapping (device, dtype) tuples to (grouped_tensorlistlist, indices). + """ + # Result dict: (device, dtype) -> (list of lists, indices) + result: dict[ + tuple[torch.device, torch.dtype], tuple[list[list[Any]], list[int]] + ] = {} + + if not tensorlistlist or not tensorlistlist[0]: + return result + + num_lists = len(tensorlistlist) + num_tensors = len(tensorlistlist[0]) + + for idx in range(num_tensors): + # Find the first non-None tensor at this index to get device and dtype + first_tensor = None + for tlist in tensorlistlist: + if tlist is not None and idx < len(tlist) and tlist[idx] is not None: + first_tensor = tlist[idx] + break + + if first_tensor is None: + # All tensors at this index are None, skip + continue + + key = (first_tensor.device, first_tensor.dtype) + + if key not in result: + # Initialize empty lists for each tensorlist + result[key] = ([[] for _ in range(num_lists)], []) + + grouped_lists, indices = result[key] + + # Add tensors from each list at this index + for list_idx, tlist in enumerate(tensorlistlist): + if tlist is not None and idx < len(tlist): + grouped_lists[list_idx].append(tlist[idx]) + else: + grouped_lists[list_idx].append(None) + + if with_indices: + indices.append(idx) + + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..427a271f493224a80e4fa50483c765b61b3784dc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/_collections.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/_collections.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a521932add5a2c2f90f69612298fe2b8411b3d5d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/_collections.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/builtins.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/builtins.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42eb6c0cd04663940666c8af2c68bfd7a5f5bd89 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/builtins.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/copy.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/copy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c0cd8c79e92be21ffa4f01710f99fc37600542d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/copy.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/functools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/functools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55f99e07a24906f350d8c928bf678167abcad553 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/functools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/fx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/fx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f52bd963aaddb86c54bdf80673ce83cd4c3e16c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/fx.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/heapq.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/heapq.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5cac9ad868d12ad4f923990bbf0d77a871f5b1b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/heapq.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/io.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/io.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c0724ce358f75dcd33a49b0ef184401f1a735dd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/io.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/itertools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/itertools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8ec188d25e5e014c2bb2a13ff5146495a5b0d67 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/itertools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/loader.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/loader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..342a416d47488d1281a595a17468060caca4866f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/loader.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/operator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e8eafc3d4e2d6e4995a921e8b1864554aeb9ffa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/operator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/os.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/os.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c48f9bc2822c0b4d819cdb12aad93765a7f90823 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/os.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/pytree.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/pytree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b88403211efb488b7a468d1214f44e76db530b2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/pytree.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/struct.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/struct.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52de6d27ab44551b1c8e15d7ad296b79f072d94b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/struct.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/sys.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/sys.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5163b6312420c765ea1abdadf4c241578357f4e1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/sys.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf0515c87021bd7877e5adb7c0737bab9c88bace Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/tensor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/torch_c_nn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/torch_c_nn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56276131af86b3dfb5c8acfc5a48e651611fcd16 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/torch_c_nn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/traceback.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/traceback.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7cbd9729f9538ad0acb0add6622d6f0d5386fad Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/traceback.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/_collections.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..9773635ae30587b06bb9f6b82c003392767b3873 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/_collections.py @@ -0,0 +1,33 @@ +""" +Python polyfills for builtins +""" + +from collections.abc import Iterable, MutableMapping +from typing import TypeVar + +from ..decorators import substitute_in_graph + + +__all__ = [] + + +T = TypeVar("T") + + +try: + import _collections # type: ignore[import-not-found] + + @substitute_in_graph(_collections._count_elements) + def _count_elements( + mapping: MutableMapping[T, int], + iterable: Iterable[T], + ) -> None: + "Tally elements from the iterable." + mapping_get = mapping.get + for elem in iterable: + mapping[elem] = mapping_get(elem, 0) + 1 + + __all__.append("_count_elements") + +except ImportError: + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/builtins.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/builtins.py new file mode 100644 index 0000000000000000000000000000000000000000..5e7e4befc47014af1565bb8143de3792aa4d3852 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/builtins.py @@ -0,0 +1,181 @@ +""" +Python polyfills for builtins +""" + +from __future__ import annotations + +import builtins +import functools +import operator +import sys +import typing +from collections.abc import Callable +from typing import TYPE_CHECKING, TypeVar + +from ..decorators import substitute_in_graph + + +if TYPE_CHECKING: + from collections.abc import Iterable + + +__all__ = [ + "all", + "any", + "cast", + "enumerate", + "sum", +] + + +_T = TypeVar("_T") + + +@substitute_in_graph(builtins.all, can_constant_fold_through=True) +def all(iterable: Iterable[object], /) -> bool: + for elem in iterable: + if not elem: + return False + return True + + +@substitute_in_graph(builtins.any, can_constant_fold_through=True) +def any(iterable: Iterable[object], /) -> bool: + for elem in iterable: + if elem: + return True + return False + + +@substitute_in_graph(builtins.enumerate, is_embedded_type=True) # type: ignore[arg-type] +def enumerate(iterable: Iterable[_T], start: int = 0) -> Iterable[tuple[int, _T]]: + if not isinstance(start, int): + raise TypeError( + f"{type(start).__name__!r} object cannot be interpreted as an integer" + ) + + for x in iterable: + yield start, x + start += 1 + + +@substitute_in_graph(builtins.sum, can_constant_fold_through=True) # type: ignore[arg-type] +def sum(iterable: Iterable[_T], /, start: _T = 0) -> _T: # type: ignore[assignment] + return functools.reduce(operator.add, iterable, start) + + +# TODO(guilhermeleobas): Implement this iterator as a VariableTracker to see if +# it is faster than tracing through it +class _CallableIterator: + def __init__(self, fn, sentinel): # type: ignore[no-untyped-def] + self.fn = fn + self.sentinel = sentinel + self.exhausted = False + + def __iter__(self): # type: ignore[no-untyped-def] + return self + + def __next__(self): # type: ignore[no-untyped-def] + if self.exhausted: + raise StopIteration + + # The iterator created in this case will call object with no arguments + # for each call to its __next__() method; + r = self.fn() + + # CPython calliter_iternext (Objects/iterobject.c) re-reads it_callable / + # it_sentinel after the call returns. If a reentrant next() exhausted + # this iterator during fn() (gh-101892), it_sentinel is now NULL, so the + # sentinel comparison is skipped and StopIteration is raised regardless + # of the returned value. + if self.exhausted: + raise StopIteration + + # If the value returned is equal to sentinel, StopIteration will be raised + if r == self.sentinel: + self.exhausted = True + raise StopIteration + + # otherwise the value will be returned. + return r + + +class _SequenceIterator: + def __init__(self, iterable) -> None: + self.iterable = iterable + self.index = 0 + self.exhausted = False + + def __iter__(self) -> _SequenceIterator: + return self + + def __next__(self) -> object: + if self.exhausted: + raise StopIteration + + # CPython iter_iternext (Objects/iterobject.c): the index counter is a + # Py_ssize_t, so once it reaches PY_SSIZE_T_MAX (sys.maxsize) it cannot + # advance and every subsequent next() raises OverflowError. + if self.index == sys.maxsize: + raise OverflowError("iter index too large") + + try: + result = self.iterable.__getitem__(self.index) + self.index += 1 + return result + except (IndexError, StopIteration): + self.exhausted = True + raise StopIteration from None + + def __setstate__(self, state) -> None: + # CPython iter_setstate (Objects/iterobject.c): a negative index is + # clamped to 0, and the state is only applied while the iterator is + # live (it_seq != NULL), i.e. not yet exhausted. + if not self.exhausted: + self.index = max(state, 0) + + +def sequence_iterator(iterable) -> Iterable[object]: + if hasattr(iterable, "__getitem__"): + return _SequenceIterator(iterable) + raise TypeError(f"'{type(iterable)}' object is not iterable") + + +class _ReversedSequenceIterator: + # Mirrors CPython's reversed object (Objects/enumobject.c). Walks the + # sequence backwards via __getitem__, starting from len(seq) - 1. + def __init__(self, seq) -> None: + self.seq = seq + self.index = len(seq) - 1 + + def __iter__(self) -> _ReversedSequenceIterator: + return self + + def __next__(self) -> object: + if self.index < 0: + raise StopIteration + try: + result = self.seq[self.index] + except (IndexError, StopIteration): + self.index = -1 + raise StopIteration from None + self.index -= 1 + return result + + +def reversed_sequence_iterator(seq) -> Iterable[object]: + return _ReversedSequenceIterator(seq) + + +def callable_iterator(fn, sentinel, /): + # If the second argument, sentinel, is given, then object must be a + # callable object. + if not isinstance(fn, Callable): # type: ignore[arg-type] + raise TypeError("iter(v, w): v must be a callable") + + return _CallableIterator(fn, sentinel) + + +@substitute_in_graph(typing.cast, can_constant_fold_through=True) +def cast(typ: type, val: _T) -> _T: # type: ignore[type-var] + return val diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/copy.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/copy.py new file mode 100644 index 0000000000000000000000000000000000000000..b1210708ed8b694775b46f0cf6d58a36d476cfdf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/copy.py @@ -0,0 +1,65 @@ +""" +Python polyfills for copy +""" + +from __future__ import annotations + +from typing import TypeVar + +from ..decorators import substitute_in_graph + + +__all__ = [ + "reduce_ex_user_defined_object", +] + +T = TypeVar("T") + + +@substitute_in_graph(object.__reduce_ex__, skip_signature_check=True) # type: ignore[arg-type] +def reduce_ex_user_defined_object(obj: T, protocol: int, /) -> tuple: # type: ignore[type-arg] + """Traceable polyfill for object.__reduce_ex__ (protocol >= 2). + + Mirrors CPython's reduce_newobj (Objects/typeobject.c): builds the __new__ + arguments from __getnewargs_ex__/__getnewargs__, selects + copyreg.__newobj_ex__ vs __newobj__ based on whether kwargs are present, and + computes the pickle state (__getstate__ if overridden, else __dict__ if the + object has one, else None). copy._reconstruct rebuilds the object via + cls.__new__(cls, *args) and applies the state. + + This must not assume the object has a __dict__: tuple/slots objects such as + namedtuples have __slots__ = () and no __dict__, and reduce to + (copyreg.__newobj__, (cls, *values), None, None, None). + """ + import copyreg + + cls = type(obj) + + args: tuple # type: ignore[type-arg] + kwargs: dict # type: ignore[type-arg] + if hasattr(cls, "__getnewargs_ex__"): + args, kwargs = obj.__getnewargs_ex__() # type: ignore[attr-defined] + elif hasattr(cls, "__getnewargs__"): + args = obj.__getnewargs__() # type: ignore[attr-defined] + kwargs = {} + else: + args = () + kwargs = {} + + if kwargs: + func = copyreg.__newobj_ex__ # pyrefly: ignore[missing-attribute] + newargs = (cls, args, kwargs) + else: + func = copyreg.__newobj__ # pyrefly: ignore[missing-attribute] + newargs = (cls, *args) + + default_getstate = getattr(object, "__getstate__", None) + if getattr(cls, "__getstate__", None) is not default_getstate: + state = obj.__getstate__() + else: + try: + state = obj.__dict__ + except AttributeError: + state = None + + return (func, newargs, state, None, None) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/functools.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/functools.py new file mode 100644 index 0000000000000000000000000000000000000000..f48c7fb3a29276ee28ca7558379d25bb8c9ee89d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/functools.py @@ -0,0 +1,73 @@ +""" +Python polyfills for functools +""" + +import functools +from collections.abc import Callable, Iterable +from functools import _initial_missing # type: ignore[attr-defined] +from typing import Any, TypeVar + +from ..decorators import substitute_in_graph + + +__all__ = ["cmp_to_key", "reduce"] + + +_T = TypeVar("_T") +_U = TypeVar("_U") + + +class _KeyWrapper: + def __init__(self, mycmp: Callable[[Any, Any], int], obj: Any) -> None: + self.mycmp = mycmp + self.obj = obj + + def __lt__(self, other: "_KeyWrapper") -> bool: + return self.mycmp(self.obj, other.obj) < 0 + + def __gt__(self, other: "_KeyWrapper") -> bool: + return self.mycmp(self.obj, other.obj) > 0 + + def __eq__(self, other: object) -> bool: + return self.mycmp(self.obj, other.obj) == 0 # type: ignore[attr-defined] + + def __le__(self, other: "_KeyWrapper") -> bool: + return self.mycmp(self.obj, other.obj) <= 0 + + def __ge__(self, other: "_KeyWrapper") -> bool: + return self.mycmp(self.obj, other.obj) >= 0 + + __hash__ = None # type: ignore[assignment] + + +# Reference: https://docs.python.org/3/library/functools.html#functools.cmp_to_key +@substitute_in_graph(functools.cmp_to_key, skip_signature_check=True) +def cmp_to_key(mycmp: Callable[[Any, Any], int]) -> Callable[[Any], _KeyWrapper]: + return functools.partial(_KeyWrapper, mycmp) + + +# Reference: https://docs.python.org/3/library/functools.html#functools.reduce +@substitute_in_graph(functools.reduce) +def reduce( + function: Callable[[_U, _T], _U], + iterable: Iterable[_T], + initial: _U = _initial_missing, # type: ignore[assignment] + /, +) -> _U: + it = iter(iterable) + + value: _U + if initial is _initial_missing: + try: + value = next(it) # type: ignore[assignment] + except StopIteration: + raise TypeError( + "reduce() of empty iterable with no initial value", + ) from None + else: + value = initial + + for element in it: + value = function(value, element) + + return value diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/fx.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/fx.py new file mode 100644 index 0000000000000000000000000000000000000000..5a5ed97e0899d94fc4478de5acfa7879f5560ab2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/fx.py @@ -0,0 +1,41 @@ +from collections.abc import Callable +from typing import Any + +from torch._C import _fx_map_aggregate, _fx_map_arg +from torch.fx.immutable_collections import immutable_dict, immutable_list +from torch.fx.node import Node + +from ..decorators import substitute_in_graph + + +@substitute_in_graph(_fx_map_arg, can_constant_fold_through=True) +def map_arg(a: Any, fn: Callable[[Node], Any]) -> Any: + return map_aggregate(a, lambda x: fn(x) if isinstance(x, Node) else x) + + +@substitute_in_graph(_fx_map_aggregate, can_constant_fold_through=True) +def map_aggregate(a: Any, fn: Callable[[Any], Any]) -> Any: + result: Any + if isinstance(a, tuple): + it = (map_aggregate(elem, fn) for elem in a) + # Support NamedTuple (if it has `_fields`) by repacking into original type. + result = type(a)(*it) if hasattr(a, "_fields") else tuple(it) + elif isinstance(a, list): + result = immutable_list([map_aggregate(elem, fn) for elem in a]) + elif isinstance(a, dict): + result = immutable_dict([(k, map_aggregate(v, fn)) for k, v in a.items()]) + elif isinstance(a, slice): + result = slice( + map_aggregate(a.start, fn), + map_aggregate(a.stop, fn), + map_aggregate(a.step, fn), + ) + else: + result = fn(a) + return result + + +__all__ = [ + "map_arg", + "map_aggregate", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/heapq.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/heapq.py new file mode 100644 index 0000000000000000000000000000000000000000..feddb5723614f581fdd232a162feaf00a3ca2fae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/heapq.py @@ -0,0 +1,119 @@ +""" +Python polyfills for heapq +""" + +from __future__ import annotations + +import heapq +import importlib +import sys +from typing import TYPE_CHECKING, TypeVar + +from ..decorators import substitute_in_graph + + +if TYPE_CHECKING: + from types import ModuleType + + +_T = TypeVar("_T") + + +# Partially copied from CPython test/support/import_helper.py +# https://github.com/python/cpython/blob/bb8791c0b75b5970d109e5557bfcca8a578a02af/Lib/test/support/import_helper.py +def _save_and_remove_modules(names: set[str]) -> dict[str, ModuleType]: + orig_modules = {} + prefixes = tuple(name + "." for name in names) + for modname in list(sys.modules): + if modname in names or modname.startswith(prefixes): + orig_modules[modname] = sys.modules.pop(modname) + return orig_modules + + +def import_fresh_module(name: str, blocked: list[str]) -> ModuleType: + # Keep track of modules saved for later restoration as well + # as those which just need a blocking entry removed + names = {name, *blocked} + orig_modules = _save_and_remove_modules(names) + for modname in blocked: + sys.modules[modname] = None # type: ignore[assignment] + + try: + return importlib.import_module(name) + finally: + _save_and_remove_modules(names) + sys.modules.update(orig_modules) + + +# Import the pure Python heapq module, blocking the C extension +py_heapq = import_fresh_module("heapq", blocked=["_heapq"]) + + +__all__ = [ + "_heapify_max", + "_heappop_max", + "_heapreplace_max", + "heapify", + "heappop", + "heappush", + "heappushpop", + "heapreplace", + "merge", + "nlargest", + "nsmallest", +] + + +@substitute_in_graph(heapq._heapify_max) +def _heapify_max(heap: list[_T], /) -> None: + return py_heapq._heapify_max(heap) + + +@substitute_in_graph(heapq._heappop_max) # type: ignore[attr-defined] +def _heappop_max(heap: list[_T]) -> _T: + return py_heapq._heappop_max(heap) + + +@substitute_in_graph(heapq._heapreplace_max) # type: ignore[attr-defined] +def _heapreplace_max(heap: list[_T], item: _T) -> _T: + return py_heapq._heapreplace_max(heap, item) + + +@substitute_in_graph(heapq.heapify) +def heapify(heap: list[_T], /) -> None: + return py_heapq.heapify(heap) + + +@substitute_in_graph(heapq.heappop) +def heappop(heap: list[_T], /) -> _T: + return py_heapq.heappop(heap) + + +@substitute_in_graph(heapq.heappush) +def heappush(heap: list[_T], item: _T) -> None: + return py_heapq.heappush(heap, item) + + +@substitute_in_graph(heapq.heappushpop) +def heappushpop(heap: list[_T], item: _T) -> _T: + return py_heapq.heappushpop(heap, item) + + +@substitute_in_graph(heapq.heapreplace) +def heapreplace(heap: list[_T], item: _T) -> _T: + return py_heapq.heapreplace(heap, item) + + +@substitute_in_graph(heapq.merge) # type: ignore[arg-type] +def merge(*iterables, key=None, reverse=False): # type: ignore[no-untyped-def] + return py_heapq.merge(*iterables, key=key, reverse=reverse) + + +@substitute_in_graph(heapq.nlargest) # type: ignore[arg-type] +def nlargest(n, iterable, key=None): # type: ignore[no-untyped-def] + return py_heapq.nlargest(n, iterable, key=key) + + +@substitute_in_graph(heapq.nsmallest) # type: ignore[arg-type] +def nsmallest(n, iterable, key=None): # type: ignore[no-untyped-def] + return py_heapq.nsmallest(n, iterable, key=key) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/io.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/io.py new file mode 100644 index 0000000000000000000000000000000000000000..a75e062f46e4682cab4421d1ac4ef5fc8997ea1b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/io.py @@ -0,0 +1,30 @@ +""" +Python polyfills for _io +""" + +from __future__ import annotations + +import _io + +import sys +import warnings + +from ..decorators import substitute_in_graph + + +__all__ = ["text_encoding"] + + +# Copied from Lib/_pyio.py in the standard library +# pyrefly: ignore [bad-argument-type] +@substitute_in_graph(_io.text_encoding, can_constant_fold_through=True) +def text_encoding(encoding: str | None, stacklevel: int = 2, /) -> str: + if encoding is None: + encoding = "utf-8" if sys.flags.utf8_mode else "locale" + if sys.flags.warn_default_encoding: + warnings.warn( + "'encoding' argument not specified.", + EncodingWarning, + stacklevel + 1, + ) + return encoding diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/itertools.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..9db422c7f66428d4f285da521c5d12adacfb2248 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/itertools.py @@ -0,0 +1,374 @@ +""" +Python polyfills for itertools +""" + +from __future__ import annotations + +import itertools +import operator +import sys +from collections.abc import Callable +from typing import overload, TYPE_CHECKING, TypeAlias, TypeVar + +from ..decorators import substitute_in_graph + + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + + +__all__ = [ + "accumulate", + "combinations", + "combinations_with_replacement", + "compress", + "cycle", + "dropwhile", + "filterfalse", + "islice", + "pairwise", + "permutations", + "starmap", + "takewhile", + "tee", +] + +if sys.version_info >= (3, 12): + __all__.append("batched") + + +_T = TypeVar("_T") +_U = TypeVar("_U") +_Predicate: TypeAlias = Callable[[_T], object] +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.accumulate +@substitute_in_graph(itertools.accumulate, is_embedded_type=True) # type: ignore[arg-type] +def accumulate( + iterable: Iterable[_T], + func: Callable[[_T, _T], _T] | None = None, + *, + initial: _T | None = None, +) -> Iterator[_T]: + # call iter outside of the generator to match cpython behavior + iterator = iter(iterable) + if func is None: + func = operator.add + + def _accumulate(iterator: Iterator[_T]) -> Iterator[_T]: + total = initial + if total is None: + try: + total = next(iterator) + except StopIteration: + return + + yield total + for element in iterator: + total = func(total, element) + yield total + + return _accumulate(iterator) + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.combinations +@substitute_in_graph(itertools.combinations, is_embedded_type=True) # type: ignore[arg-type] +def combinations(iterable: Iterable[_T], r: int, /) -> Iterator[tuple[_T, ...]]: + pool = tuple(iterable) + n = len(pool) + + if r < 0: + raise ValueError("r must be non-negative") + + def _combinations() -> Iterator[tuple[_T, ...]]: + if r > n: + return + + indices = list(range(r)) + yield tuple(pool[i] for i in indices) + + while True: + for i in reversed(range(r)): + if indices[i] != i + n - r: + break + else: + return + + indices[i] += 1 + for j in range(i + 1, r): + indices[j] = indices[j - 1] + 1 + + yield tuple(pool[i] for i in indices) + + return _combinations() + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.compress +@substitute_in_graph(itertools.compress, is_embedded_type=True) # type: ignore[arg-type] +def compress(data: Iterable[_T], selectors: Iterable[_U], /) -> Iterator[_T]: + return (datum for datum, selector in zip(data, selectors) if selector) + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.cycle +@substitute_in_graph(itertools.cycle, is_embedded_type=True) # type: ignore[arg-type] +def cycle(iterable: Iterable[_T]) -> Iterator[_T]: + iterator = iter(iterable) + + def _cycle(iterator: Iterator[_T]) -> Iterator[_T]: + # pyrefly: ignore [implicit-any] + saved = [] + for element in iterable: + yield element + saved.append(element) + + while saved: + for element in saved: + yield element + + return _cycle(iterator) + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.dropwhile +@substitute_in_graph(itertools.dropwhile, is_embedded_type=True) # type: ignore[arg-type] +def dropwhile(predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Iterator[_T]: + # dropwhile(lambda x: x < 5, [1, 4, 6, 3, 8]) -> 6 3 8 + if not callable(predicate): + raise TypeError(f"'{type(predicate).__name__}' object is not callable") + + iterator = iter(iterable) + for x in iterator: + if not predicate(x): + yield x + break + + yield from iterator + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.takewhile +@substitute_in_graph(itertools.takewhile, is_embedded_type=True) # type: ignore[arg-type] +def takewhile(predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Iterator[_T]: + # takewhile(lambda x: x<5, [1,4,6,3,8]) → 1 4 + if not callable(predicate): + raise TypeError(f"'{type(predicate).__name__}' object is not callable") + + for x in iterable: + if not predicate(x): + break + yield x + + +@overload +def starmap( + function: Callable[[], _U], + iterable: Iterable[tuple[()]], + /, +) -> itertools.starmap[_U]: ... + + +@overload +def starmap( + function: Callable[[_T], _U], + iterable: Iterable[tuple[_T]], + /, +) -> itertools.starmap[_U]: ... + + +@overload +def starmap( + function: Callable[[_T, _T1], _U], + iterable: Iterable[tuple[_T, _T1]], + /, +) -> itertools.starmap[_U]: ... + + +@overload +def starmap( + function: Callable[[_T, _T1, _T2], _U], + iterable: Iterable[tuple[_T, _T1, _T2]], + /, +) -> itertools.starmap[_U]: ... + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.starmap +@substitute_in_graph(itertools.starmap, is_embedded_type=True) # type: ignore[arg-type] +# pyrefly: ignore [implicit-any] +def starmap(function: Callable[..., _T], iterable: Iterable, /) -> Iterable[_T]: + # starmap(pow, [(2,5), (3,2), (10,3)]) → 32 9 1000 + if not callable(function): + raise TypeError(f"'{type(function).__name__}' object is not callable") + + for args in iterable: + yield function(*args) + + +@substitute_in_graph(itertools.filterfalse, is_embedded_type=True) # type: ignore[arg-type] +def filterfalse(function: _Predicate[_T], iterable: Iterable[_T], /) -> Iterator[_T]: + it = iter(iterable) + if function is None: + return filter(operator.not_, it) + else: + return filter(lambda x: not function(x), it) + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.islice +@substitute_in_graph(itertools.islice, is_embedded_type=True) # type: ignore[arg-type] +def islice(iterable: Iterable[_T], /, *args: int | None) -> Iterator[_T]: + s = slice(*args) + start = 0 if s.start is None else s.start + stop = s.stop + step = 1 if s.step is None else s.step + if start < 0 or (stop is not None and stop < 0) or step <= 0: + raise ValueError( + "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.", + ) + + if stop is None: + # TODO: use indices = itertools.count() and merge implementation with the else branch + # when we support infinite iterators + next_i = start + for i, element in enumerate(iterable): + if i == next_i: + yield element + next_i += step + else: + indices = range(max(start, stop)) + next_i = start + for i, element in zip(indices, iterable): + if i == next_i: + yield element + next_i += step + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.pairwise +@substitute_in_graph(itertools.pairwise, is_embedded_type=True) # type: ignore[arg-type] +def pairwise(iterable: Iterable[_T], /) -> Iterator[tuple[_T, _T]]: + a = None + first = True + for b in iterable: + if first: + first = False + else: + yield a, b # type: ignore[misc] + a = b + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.permutations +@substitute_in_graph(itertools.permutations, is_embedded_type=True) # type: ignore[arg-type] +def permutations( + iterable: Iterable[_T], r: int | None = None, / +) -> Iterator[tuple[_T, ...]]: + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r + + if r < 0: + raise ValueError("r must be non-negative") + + def _permutations() -> Iterator[tuple[_T, ...]]: + if r > n: + return + + indices = list(range(n)) + cycles = list(range(n, n - r, -1)) + yield tuple(pool[i] for i in indices[:r]) + + while n: + for i in reversed(range(r)): + cycles[i] -= 1 + if cycles[i] == 0: + indices[i:] = indices[i + 1 :] + indices[i : i + 1] + cycles[i] = n - i + else: + j = cycles[i] + indices[i], indices[-j] = indices[-j], indices[i] + yield tuple(pool[i] for i in indices[:r]) + break + else: + return + + return _permutations() + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.tee +@substitute_in_graph(itertools.tee) +def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: + iterator = iter(iterable) + shared_link = [None, None] + + def _tee(link) -> Iterator[_T]: # type: ignore[no-untyped-def] + try: + while True: + if link[1] is None: + link[0] = next(iterator) + link[1] = [None, None] + value, link = link + yield value + except StopIteration: + return + + return tuple(_tee(shared_link) for _ in range(n)) + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement +@substitute_in_graph(itertools.combinations_with_replacement, is_embedded_type=True) # type: ignore[arg-type] +def combinations_with_replacement( + iterable: Iterable[_T], r: int, / +) -> Iterator[tuple[_T, ...]]: + if r < 0: + raise ValueError("r must be non-negative") + + pool = tuple(iterable) + n = len(pool) + + def _combinations_with_replacement() -> Iterator[tuple[_T, ...]]: + if r == 0: + yield () + return + if n == 0: + return + + indices = [0] * r + yield tuple(pool[i] for i in indices) + while True: + for i in range(r - 1, -1, -1): + if indices[i] != n - 1: + break + else: + return + indices[i:] = [indices[i] + 1] * (r - i) + yield tuple(pool[i] for i in indices) + + return _combinations_with_replacement() + + +if sys.version_info >= (3, 12): + # Reference: https://docs.python.org/3/library/itertools.html#itertools.batched + @substitute_in_graph(itertools.batched, is_embedded_type=True) # type: ignore[arg-type] + def batched(*args, **kwargs) -> Iterator[tuple[_T, ...]]: # type: ignore[no-untyped-def] + if len(args) != 2: + raise TypeError( + f"batched takes exactly 2 positional arguments({len(args)} given)" + ) + if kwargs.keys() - {"strict"}: + unexpected = next(iter(kwargs.keys() - {"strict"})) + raise TypeError( + f"batched() got an unexpected keyword argument '{unexpected}'" + ) + + iterable, n = args + strict = kwargs.get("strict", False) + n = operator.index(n) + if n < 1: + raise ValueError("n must be at least one") + + iterator = iter(iterable) + + def _batched(iterator: Iterator[_T]) -> Iterator[tuple[_T, ...]]: + while batch := tuple(islice(iterator, n)): + if strict and len(batch) != n: + raise ValueError("batched(): incomplete batch") + yield batch + + return _batched(iterator) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/loader.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..9defe564e45fb843db3113ac6fc7ff5e9ca8ddcf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/loader.py @@ -0,0 +1,49 @@ +# Used to load and initialize polyfill handlers when importing torch._dynamo +# Please add a new import when adding a new polyfill module. + +import importlib +from typing import TYPE_CHECKING + +import torch.utils._pytree as python_pytree + +from .. import polyfills, trace_rules + + +if TYPE_CHECKING: + from types import ModuleType + + +# See also the TYPE_CHECKING block in torch/_dynamo/polyfills/__init__.py +POLYFILLED_MODULE_NAMES: tuple[str, ...] = ( + "_collections", + "builtins", + "copy", + "functools", + "io", + "itertools", + "operator", + "os", + "struct", + "sys", + "fx", + "tensor", + "torch_c_nn", + "traceback", +) +if python_pytree._cxx_pytree_dynamo_traceable: + POLYFILLED_MODULE_NAMES += ("pytree",) + +POLYFILLED_MODULES: tuple["ModuleType", ...] = tuple( + importlib.import_module(f".{submodule}", package=polyfills.__name__) + for submodule in POLYFILLED_MODULE_NAMES +) + + +# Unregister the builtin functions from _builtin_function_ids to let them to be +# dispatched with the appropriate VariableTracker type. Otherwise, they will be +# dispatched with BuiltinVariable if present in _builtin_function_ids. +for polyfill_module in POLYFILLED_MODULES: + for polyfill_name in polyfill_module.__all__: + polyfill_handler = getattr(polyfill_module, polyfill_name) + original_fn = polyfill_handler.__torch_dynamo_original__ + trace_rules._builtin_function_ids.remove(id(original_fn)) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/operator.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/operator.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0eb3e64ae73724ab1996c8dc7fbd4dfb5c020d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/operator.py @@ -0,0 +1,132 @@ +""" +Python polyfills for operator +""" + +from __future__ import annotations + +import operator +from typing import Any, overload, TYPE_CHECKING, TypeVar +from typing_extensions import TypeVarTuple, Unpack + +from ..decorators import substitute_in_graph + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + +# Most unary and binary operators are handled by BuiltinVariable (e.g., `pos`, `add`) +__all__ = ["attrgetter", "concat", "countOf", "iconcat", "itemgetter", "methodcaller"] + + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_Ts = TypeVarTuple("_Ts") +_U = TypeVar("_U") +_U1 = TypeVar("_U1") +_U2 = TypeVar("_U2") +_Us = TypeVarTuple("_Us") + + +@overload +# pyrefly: ignore [inconsistent-overload] +def attrgetter(attr: str, /) -> Callable[[Any], _U]: ... + + +@overload +# pyrefly: ignore [inconsistent-overload] +def attrgetter( + attr1: str, attr2: str, /, *attrs: str +) -> Callable[[Any], tuple[_U1, _U2, Unpack[_Us]]]: ... + + +# Reference: https://docs.python.org/3/library/operator.html#operator.attrgetter +@substitute_in_graph(operator.attrgetter, is_embedded_type=True) # type: ignore[arg-type,misc] +def attrgetter(*attrs: str) -> Callable[[Any], Any | tuple[Any, ...]]: + if len(attrs) == 0: + raise TypeError("attrgetter expected 1 argument, got 0") + + if any(not isinstance(attr, str) for attr in attrs): + raise TypeError("attribute name must be a string") + + def resolve_attr(obj: Any, attr: str) -> Any: + for name in attr.split("."): + obj = getattr(obj, name) + return obj + + if len(attrs) == 1: + attr = attrs[0] + + def getter(obj: Any) -> Any: + return resolve_attr(obj, attr) + + else: + + def getter(obj: Any) -> tuple[Any, ...]: # type: ignore[misc] + return tuple(resolve_attr(obj, attr) for attr in attrs) + + return getter + + +# Reference: https://docs.python.org/3/library/operator.html#operator.concat +@substitute_in_graph(operator.concat, can_constant_fold_through=True) # type: ignore[arg-type] +def concat(a: Sequence[_T], b: Sequence[_T2], /) -> Sequence[_T | _T2]: + return a + b # type: ignore[operator] + + +# Reference: https://docs.python.org/3/library/operator.html#operator.countOf +@substitute_in_graph(operator.countOf, can_constant_fold_through=True) # type: ignore[arg-type,misc] +def countOf(a: Iterable[_T], b: _T, /) -> int: + return sum(it is b or it == b for it in a) + + +# Reference: https://docs.python.org/3/library/operator.html#operator.iconcat +@substitute_in_graph(operator.iconcat) # type: ignore[arg-type] +def iconcat(a: Sequence[_T], b: Sequence[_T2], /) -> Sequence[_T | _T2]: + a += b # type: ignore[operator] + return a # type: ignore[return-value] + + +@overload +# pyrefly: ignore [inconsistent-overload] +def itemgetter(item: _T, /) -> Callable[[Any], _U]: ... + + +@overload +# pyrefly: ignore [inconsistent-overload] +def itemgetter( + item1: _T1, item2: _T2, /, *items: Unpack[_Ts] +) -> Callable[[Any], tuple[_U1, _U2, Unpack[_Us]]]: ... + + +# Reference: https://docs.python.org/3/library/operator.html#operator.itemgetter +@substitute_in_graph(operator.itemgetter, is_embedded_type=True) # type: ignore[arg-type,misc] +def itemgetter(*items: Any) -> Callable[[Any], Any | tuple[Any, ...]]: + if len(items) == 0: + raise TypeError("itemgetter expected 1 argument, got 0") + + if len(items) == 1: + item = items[0] + + def getter(obj: Any) -> Any: + return obj[item] + + else: + + def getter(obj: Any) -> tuple[Any, ...]: # type: ignore[misc] + return tuple(obj[item] for item in items) + + return getter + + +# Reference: https://docs.python.org/3/library/operator.html#operator.methodcaller +@substitute_in_graph(operator.methodcaller, is_embedded_type=True) # type: ignore[arg-type] +def methodcaller(name: str, /, *args: Any, **kwargs: Any) -> Callable[[Any], Any]: + if not isinstance(name, str): + raise TypeError("method name must be a string") + + def caller(obj: Any) -> Any: + return getattr(obj, name)(*args, **kwargs) + + return caller diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/os.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/os.py new file mode 100644 index 0000000000000000000000000000000000000000..595b7f3636a0ec6d19f0df78fe7c49babe080435 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/os.py @@ -0,0 +1,37 @@ +""" +Python polyfills for os +""" + +from __future__ import annotations + +import os +from typing import AnyStr + +from ..decorators import substitute_in_graph + + +__all__ = ["fspath"] + + +# Copied from os.py in the standard library +# pyrefly: ignore [bad-argument-type] +@substitute_in_graph(os.fspath, can_constant_fold_through=True) +def fspath(path: AnyStr | os.PathLike[AnyStr]) -> AnyStr: + if isinstance(path, (str, bytes)): + return path + + path_type = type(path) + try: + path_repr = path_type.__fspath__(path) # type: ignore[arg-type] + except AttributeError: + if hasattr(path_type, "__fspath__"): + raise + raise TypeError( + f"expected str, bytes or os.PathLike object, not {path_type.__name__}", + ) from None + if isinstance(path_repr, (str, bytes)): + return path_repr # type: ignore[return-value] + raise TypeError( + f"expected {path_type.__name__}.__fspath__() to return str or bytes, " + f"not {type(path_repr).__name__}", + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/pytree.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/pytree.py new file mode 100644 index 0000000000000000000000000000000000000000..64eea6c7caaecda70209efcf52d84ed2959c0a89 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/pytree.py @@ -0,0 +1,823 @@ +# Owner(s): ["module: pytree"] + +""" +Python polyfills for torch.utils.pytree +""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass, field +from typing import Any, TYPE_CHECKING, TypeVar + +import optree +import optree._C +import optree.utils +from optree import ( + is_namedtuple, + is_namedtuple_class, + is_namedtuple_instance, + is_structseq, + is_structseq_class, + is_structseq_instance, + namedtuple_fields, + structseq_fields, +) + +import torch.utils._cxx_pytree as cxx_pytree # noqa: F401 # load the C++ extension module +import torch.utils._pytree as python_pytree +from torch.utils._pytree import BUILTIN_TYPES, STANDARD_DICT_TYPES + +from ..decorators import substitute_in_graph + + +if TYPE_CHECKING: + import builtins + from collections.abc import Callable, Iterable, Mapping + from typing_extensions import Self, TypeIs + + from torch.utils._cxx_pytree import PyTree + + +__all__ = [ + "is_namedtuple", + "is_namedtuple_class", + "is_namedtuple_instance", + "is_structseq", + "is_structseq_class", + "is_structseq_instance", + "namedtuple_fields", + "structseq_fields", + "treespec_leaf", + "treespec_tuple", + "treespec_dict", + "tree_is_leaf", + "tree_iter", + "tree_leaves", + "tree_flatten", + "tree_flatten_with_path", + "tree_structure", + "tree_unflatten", +] + + +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + + +@substitute_in_graph( + optree._C.is_dict_insertion_ordered, + can_constant_fold_through=True, +) +def _(*args: Any, **kwargs: Any) -> bool: + # In namespace 'torch', the dictionary is always traversed in insertion order. + # This function returns True. + raise ValueError( + "Should not be called directly " + "because the original function will be called in the constant fold path." + ) + + +__name = "" +for __name, __func in ( + ("is_namedtuple", is_namedtuple), + ("is_namedtuple_class", is_namedtuple_class), + ("is_namedtuple_instance", is_namedtuple_instance), + ("is_structseq", is_structseq), + ("is_structseq_class", is_structseq_class), + ("is_structseq_instance", is_structseq_instance), + ("namedtuple_fields", namedtuple_fields), + ("structseq_fields", structseq_fields), +): + globals()[__name] = substitute_in_graph( + __func, # type: ignore[arg-type] + can_constant_fold_through=True, + )(__func.__python_implementation__) # type: ignore[attr-defined] + del __func +del __name + + +@substitute_in_graph(optree.tree_is_leaf, can_constant_fold_through=True) # type: ignore[arg-type] +def tree_is_leaf( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> bool: + if (tree is None and none_is_leaf) or (is_leaf is not None and is_leaf(tree)): + return True + if optree.register_pytree_node.get(type(tree), namespace=namespace) is None: + return True + return False + + +@substitute_in_graph(optree.tree_iter, can_constant_fold_through=False) # type: ignore[arg-type] +def tree_iter( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> Iterable[Any]: + stack = [tree] + while stack: + node = stack.pop() + if tree_is_leaf( + node, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ): + yield node + continue + + children, *_ = optree.tree_flatten_one_level( + node, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + stack.extend(reversed(children)) + + +@substitute_in_graph(optree.tree_leaves, can_constant_fold_through=True) # type: ignore[arg-type] +def tree_leaves( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> list[Any]: + return list( + tree_iter( + tree, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + ) + + +class _Asterisk(str): + __slots__ = () + + def __new__(cls) -> Self: + return super().__new__(cls, "*") + + def __repr__(self) -> str: + return "*" # no quotes + + +_asterisk = _Asterisk() +del _Asterisk + + +@dataclass(frozen=True, repr=False, eq=False, unsafe_hash=False, slots=True) +class PyTreeSpec: + """Analog for :class:`optree.PyTreeSpec` in Python.""" + + _children: tuple[PyTreeSpec, ...] + _type: builtins.type | None + _metadata: Any + _entries: tuple[Any, ...] + _unflatten_func: Callable[[Any | None, Iterable[PyTree]], PyTree] | None + none_is_leaf: bool + namespace: str + + num_nodes: int = field(init=False) + num_leaves: int = field(init=False) + num_children: int = field(init=False) + + def __post_init__(self, /) -> None: + if self._type is None: + if len(self._children) != 0: + raise AssertionError("Leaf node must have no children") + if self._metadata is not None: + raise AssertionError("Leaf node must have no metadata") + if self._entries != (): + raise AssertionError("Leaf node must have no entries") + if self._unflatten_func is not None: + raise AssertionError("Leaf node must have no unflatten_func") + num_nodes = 1 + num_leaves = 1 + num_children = 0 + else: + if not callable(self._unflatten_func): + raise AssertionError( + "Non-leaf node must have a callable unflatten_func" + ) + num_nodes = 1 + num_leaves = 0 + for child in self._children: + num_nodes += child.num_nodes + num_leaves += child.num_leaves + num_children = len(self._children) + + object.__setattr__(self, "num_nodes", num_nodes) + object.__setattr__(self, "num_leaves", num_leaves) + object.__setattr__(self, "num_children", num_children) + + def __repr__(self, /) -> str: + def helper(treespec: PyTreeSpec) -> str: + if treespec.is_leaf(): + if treespec.type is not None: + raise AssertionError("Leaf treespec must have type None") + return _asterisk + + if treespec.type is None: + raise AssertionError("Non-leaf treespec must have a type") + if not callable(treespec._unflatten_func): + raise AssertionError( + "Non-leaf treespec must have a callable unflatten_func" + ) + children_representations = [ + helper(subspec) for subspec in treespec._children + ] + if ( + treespec.type in BUILTIN_TYPES + or (treespec.type is type(None) and not self.none_is_leaf) + or optree.is_namedtuple_class(treespec.type) + or optree.is_structseq_class(treespec.type) + ): + return treespec._unflatten_func( + treespec._metadata, + children_representations, + ) + return ( + f"CustomTreeNode({treespec.type.__name__}[{treespec._metadata!r}], " + f"[{', '.join(children_representations)}])" + ) + + inner = [ + str(helper(self)), + *(["NoneIsLeaf"] if self.none_is_leaf else []), + f"namespace={self.namespace!r}", + ] + return f"PyTreeSpec({', '.join(inner)})" + + def __len__(self, /) -> int: + return self.num_leaves + + def __eq__(self, other: Any, /) -> bool: + if not isinstance(other, PyTreeSpec): + return NotImplemented + if ( + self.none_is_leaf != other.none_is_leaf + or self.num_nodes != other.num_nodes + or self.num_leaves != other.num_leaves + or self._type is not other._type + or self._metadata != other._metadata + ): + return False + # A namespace mismatch is ignored if either side has an empty namespace, mirroring optree's + # `PyTreeSpec::EqualTo` (src/treespec/richcomparison.cpp). + if self.namespace and other.namespace and self.namespace != other.namespace: + return False + return self._children == other._children + + def __hash__(self, /) -> int: + node_type = self._type + if node_type in STANDARD_DICT_TYPES: + # Dict metadata is the (unhashable) list of keys; hash the keys instead. + node_data: Any = tuple(self._entries) + elif ( + node_type is None + or node_type in BUILTIN_TYPES + or optree.is_namedtuple_class(node_type) + or optree.is_structseq_class(node_type) + ): + node_data = self._metadata + else: + # Custom node metadata may be unhashable; hash the node type only, mirroring optree's + # `PyTreeSpec::HashValueImpl` (src/treespec/hashing.cpp). + node_data = None + # `namespace` is intentionally excluded: `__eq__` treats an empty namespace as a wildcard, + # so specs that compare equal must hash the same. + return hash( + ( + self.none_is_leaf, + node_type, + self.num_leaves, + self.num_nodes, + node_data, + self._children, + ) + ) + + @property + def type(self, /) -> builtins.type | None: + return self._type + + def is_leaf(self, /) -> bool: + return self.num_nodes == 1 and self.num_leaves == 1 + + def paths(self, /) -> list[tuple[Any, ...]]: + def helper(treespec: PyTreeSpec, path_prefix: list[Any]) -> None: + if treespec.is_leaf(): + paths.append(path_prefix) + return + + for entry, subspec in zip( + treespec._entries, + treespec._children, + strict=True, + ): + helper(subspec, path_prefix + [entry]) + + paths: list[list[Any]] = [] + helper(self, []) + return [tuple(path) for path in paths] + + def accessors(self, /) -> list[optree.PyTreeAccessor]: + def helper( + treespec: PyTreeSpec, + entry_path_prefix: list[optree.PyTreeEntry], + ) -> None: + if treespec.is_leaf(): + entry_paths.append(entry_path_prefix) + return + + node_type = treespec.type + if node_type is None: + raise AssertionError("Non-leaf treespec must have a type") + handler = optree.register_pytree_node.get( + node_type, namespace=treespec.namespace + ) + if handler is None: + raise AssertionError(f"No pytree handler registered for {node_type}") + kind: optree.PyTreeKind = handler.kind + path_entry_type: type[optree.PyTreeEntry] = handler.path_entry_type + + for entry, subspec in zip( + treespec._entries, + treespec._children, + strict=True, + ): + helper( + subspec, + entry_path_prefix + [path_entry_type(entry, node_type, kind)], + ) + + entry_paths: list[list[optree.PyTreeEntry]] = [] + helper(self, []) + return [optree.PyTreeAccessor(path) for path in entry_paths] + + def children(self, /) -> list[PyTreeSpec]: + return list(self._children) + + def child(self, index: int, /) -> PyTreeSpec: + return self._children[index] + + def entries(self, /) -> list[Any]: + return list(self._entries) + + def entry(self, index: int, /) -> Any: + return self._entries[index] + + def flatten_up_to(self, tree: PyTree, /) -> list[PyTree]: + def helper( + treespec: PyTreeSpec, + node: PyTree, + subtrees: list[PyTree], + ) -> None: + if treespec.is_leaf(): + subtrees.append(node) + return + + node_type = type(node) + if treespec.type not in BUILTIN_TYPES: + # Always require custom node types to match exactly + if node_type != treespec.type: + raise ValueError( + f"Type mismatch; " + f"expected {treespec.type!r}, but got {node_type!r}.", + ) + + children, metadata, *_ = optree.tree_flatten_one_level( + node, + none_is_leaf=self.none_is_leaf, + namespace=self.namespace, + ) + if len(children) != treespec.num_children: + raise ValueError( + f"Node arity mismatch; " + f"expected {treespec.num_children}, but got {len(children)}.", + ) + if metadata != treespec._metadata: + raise ValueError( + f"Node context mismatch for custom node type {treespec.type!r}.", + ) + else: + # For builtin dictionary types, we allow some flexibility + # Otherwise, we require exact matches + both_standard_dict = ( + treespec.type in STANDARD_DICT_TYPES + and node_type in STANDARD_DICT_TYPES + ) + if not both_standard_dict and node_type != treespec.type: + raise ValueError( + f"Node type mismatch; " + f"expected {treespec.type!r}, but got {node_type!r}.", + ) + if len(node) != treespec.num_children: + raise ValueError( + f"Node arity mismatch; " + f"expected {treespec.num_children}, but got {len(node)}.", + ) + + if both_standard_dict: + # dictionary types are compatible with each other + expected_keys = treespec.entries() + got_key_set = set(node) + expected_key_set = set(expected_keys) + if got_key_set != expected_key_set: + missing_keys = expected_key_set.difference(got_key_set) + extra_keys = got_key_set.difference(expected_key_set) + message = "" + if missing_keys: + message += f"; missing key(s): {missing_keys}" + if extra_keys: + message += f"; extra key(s): {extra_keys}" + raise ValueError(f"Node keys mismatch{message}.") + children = [node[key] for key in expected_keys] + else: + # node_type is treespec.type + children, metadata, *_ = optree.tree_flatten_one_level( + node, + none_is_leaf=self.none_is_leaf, + namespace=self.namespace, + ) + if ( + node_type is not deque # ignore mismatch of `maxlen` for deque + ) and metadata != treespec._metadata: + raise ValueError( + f"Node metadata mismatch for node type {treespec.type!r}; " + f"expected {treespec._metadata!r}, but got {metadata!r}.", # namedtuple type mismatch + ) + + for subtree, subspec in zip(children, treespec._children, strict=True): + helper(subspec, subtree, subtrees) + + subtrees: list[PyTree] = [] + helper(self, tree, subtrees) + return subtrees + + def unflatten(self, leaves: Iterable[Any], /) -> PyTree: + if not isinstance(leaves, (list, tuple)): + leaves = list(leaves) + if len(leaves) != self.num_leaves: + raise ValueError( + f"treespec.unflatten(leaves): `leaves` has length {len(leaves)} " + f"but the spec refers to a pytree that holds {self.num_leaves} " + f"items ({self}).", + ) + if self.is_leaf(): + return leaves[0] + + # Recursively unflatten the children + start = 0 + end = 0 + subtrees = [] + for subspec in self._children: + end += subspec.num_leaves + subtrees.append(subspec.unflatten(leaves[start:end])) + start = end + + if not callable(self._unflatten_func): + raise AssertionError("Non-leaf node must have a callable unflatten_func") + return self._unflatten_func(self._metadata, subtrees) + + +def _is_pytreespec_instance(obj: Any, /) -> TypeIs[PyTreeSpec | python_pytree.TreeSpec]: + return isinstance(obj, (PyTreeSpec, python_pytree.TreeSpec)) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.treespec_leaf, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def treespec_leaf( + *, + none_is_leaf: bool = False, + namespace: str = "", # unused +) -> PyTreeSpec: + return PyTreeSpec( + (), + None, + None, + (), + None, + none_is_leaf=none_is_leaf, + namespace="", + ) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.treespec_tuple, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def treespec_tuple( + iterable: Iterable[PyTreeSpec] = (), + /, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> PyTreeSpec: + children = tuple(iterable) + if any(not _is_pytreespec_instance(child) for child in children): + raise ValueError(f"Expected a tuple of PyTreeSpecs, got: {children!r}.") + if any(child.none_is_leaf != none_is_leaf for child in children): + raise ValueError( + "All children PyTreeSpecs must have the same `none_is_leaf` value " + f"as the parent; expected {none_is_leaf}, got: {children!r}.", + ) + if any(child.namespace not in (namespace, "") for child in children): + raise ValueError( + "All children PyTreeSpecs must have the same `namespace` value " + f"as the parent; expected {namespace!r}, got: {children!r}.", + ) + handler = optree.register_pytree_node.get(tuple, namespace=namespace) + if handler is None: + raise AssertionError("No pytree handler registered for tuple") + return PyTreeSpec( + tuple(children), + tuple, + None, + tuple(range(len(children))), + handler.unflatten_func, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.treespec_dict, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def treespec_dict( + mapping: Mapping[Any, PyTreeSpec] | Iterable[tuple[Any, PyTreeSpec]] = (), + /, + *, + none_is_leaf: bool = False, + namespace: str = "", + **kwargs: PyTreeSpec, +) -> PyTreeSpec: + dct = dict(mapping, **kwargs) + if any(not _is_pytreespec_instance(child) for child in dct.values()): + raise ValueError(f"Expected a dictionary of TreeSpecs, got: {dct!r}.") + if any(child.none_is_leaf != none_is_leaf for child in dct.values()): + raise ValueError( + "All children PyTreeSpecs must have the same `none_is_leaf` value " + f"as the parent; expected {none_is_leaf}, got: {dct!r}.", + ) + if any(child.namespace not in (namespace, "") for child in dct.values()): + raise ValueError( + "All children PyTreeSpecs must have the same `namespace` value " + f"as the parent; expected {namespace!r}, got: {dct!r}.", + ) + + ( + children, + metadata, + entries, + unflatten_func, + ) = optree.tree_flatten_one_level( # type: ignore[assignment,var-annotated] + dct, # type: ignore[arg-type] + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + return PyTreeSpec( + tuple(children), # type: ignore[arg-type] + dict, + metadata, + entries, + unflatten_func, # type: ignore[arg-type] + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.tree_flatten, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def tree_flatten( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> tuple[list[Any], PyTreeSpec]: + def helper(node: PyTree, leaves: list[Any]) -> PyTreeSpec: + if tree_is_leaf( + node, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ): + leaves.append(node) + return PyTreeSpec( + (), + None, + None, + (), + None, + none_is_leaf=none_is_leaf, + namespace="", + ) + + ( + children, + metadata, + entries, + unflatten_func, + ) = optree.tree_flatten_one_level( + node, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + + # Recursively flatten the children + subspecs = tuple(helper(child, leaves) for child in children) + return PyTreeSpec( + subspecs, + type(node), + metadata, + entries, + unflatten_func, # type: ignore[arg-type] + none_is_leaf=none_is_leaf, + namespace=namespace, + ) # type: ignore[arg-type] + + leaves: list[Any] = [] + treespec = helper(tree, leaves) + return leaves, treespec + + +@substitute_in_graph( # type: ignore[arg-type] + optree._C.flatten, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def _C_flatten( + tree: PyTree, + /, + leaf_predicate: Callable[[PyTree], bool] | None = None, + none_is_leaf: bool = False, + namespace: str = "", +) -> tuple[list[Any], PyTreeSpec]: + return tree_flatten( # type: ignore[return-value] + tree, + is_leaf=leaf_predicate, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.tree_flatten_with_path, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def tree_flatten_with_path( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> tuple[list[tuple[Any, ...]], list[Any], PyTreeSpec]: + leaves, treespec = tree_flatten( + tree, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + return treespec.paths(), leaves, treespec # type: ignore[return-value] + + +@substitute_in_graph( # type: ignore[arg-type] + optree._C.flatten_with_path, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def _C_flatten_with_path( + tree: PyTree, + /, + leaf_predicate: Callable[[PyTree], bool] | None = None, + none_is_leaf: bool = False, + namespace: str = "", +) -> tuple[list[tuple[Any, ...]], list[Any], PyTreeSpec]: + return tree_flatten_with_path( # type: ignore[return-value] + tree, + is_leaf=leaf_predicate, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.tree_structure, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def tree_structure( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> PyTreeSpec: + return tree_flatten( # type: ignore[return-value] + tree, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + )[1] + + +@substitute_in_graph( # type: ignore[arg-type] + optree.tree_unflatten, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def tree_unflatten(treespec: PyTreeSpec, leaves: Iterable[Any]) -> PyTree: + if not _is_pytreespec_instance(treespec): + raise TypeError( + f"Expected `treespec` to be an instance of " + f"PyTreeSpec but got item of type {type(treespec)}." + ) + return treespec.unflatten(leaves) + + +_none_registration = optree.register_pytree_node.get(type(None)) +if _none_registration is None: + raise AssertionError("No pytree handler registered for NoneType") + + +@substitute_in_graph( # type: ignore[arg-type] + _none_registration.unflatten_func, + can_constant_fold_through=True, + skip_signature_check=True, +) +def none_unflatten(_: None, children: Iterable[_T], /) -> None: + if len(list(children)) != 0: + raise ValueError("Expected no children.") + return None + + +with optree.dict_insertion_ordered(False, namespace="torch"): + _dict_registration = optree.register_pytree_node.get(dict) + if _dict_registration is None: + raise AssertionError("No pytree handler registered for dict") + + +@substitute_in_graph( # type: ignore[arg-type] + _dict_registration.flatten_func, + can_constant_fold_through=True, + skip_signature_check=True, +) +def dict_flatten( + dct: dict[_KT, _VT], / +) -> tuple[list[_VT], tuple[list[_KT], list[_KT]], tuple[_KT, ...]]: + sorted_keys = optree.utils.total_order_sorted(dct) + values = [dct[key] for key in sorted_keys] + original_keys = list(dct) + return values, (original_keys, sorted_keys), tuple(sorted_keys) + + +@substitute_in_graph( # type: ignore[arg-type] + _dict_registration.unflatten_func, + can_constant_fold_through=True, + skip_signature_check=True, +) +def dict_unflatten( + metadata: tuple[list[_KT], list[_KT]], + values: Iterable[_VT], + /, +) -> dict[_KT, _VT]: + original_keys, sorted_keys = metadata + d = dict.fromkeys(original_keys) + d.update(zip(sorted_keys, values, strict=True)) + return d # type: ignore[return-value] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/struct.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/struct.py new file mode 100644 index 0000000000000000000000000000000000000000..4077a7f05788e3c32dba6bba09f3c15eb603db64 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/struct.py @@ -0,0 +1,27 @@ +""" +Python polyfills for struct +""" + +from __future__ import annotations + +import struct +from typing import Any +from typing_extensions import Buffer + +from ..decorators import substitute_in_graph + + +__all__ = [ + "pack", + "unpack", +] + + +@substitute_in_graph(struct.pack, can_constant_fold_through=True) # type: ignore[arg-type] +def pack(format: bytes | str, /, *v: Any) -> bytes: + return struct.pack(format, *v) + + +@substitute_in_graph(struct.unpack, can_constant_fold_through=True) # type: ignore[arg-type] +def unpack(format: bytes | str, buffer: Buffer, /) -> tuple[Any, ...]: + return struct.unpack(format, buffer) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/sys.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/sys.py new file mode 100644 index 0000000000000000000000000000000000000000..d04a8b2febc64a1f4d340f1e7c337c7ac6876054 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/sys.py @@ -0,0 +1,39 @@ +""" +Python polyfills for sys +""" + +from __future__ import annotations + +import sys + +from ..decorators import substitute_in_graph + + +__all__ = [ + "intern", + "getrecursionlimit", +] + + +# pyrefly: ignore [bad-argument-type] +@substitute_in_graph(sys.intern, can_constant_fold_through=True) +def intern(string: str, /) -> str: + return string + + +@substitute_in_graph(sys.getrecursionlimit, can_constant_fold_through=True) +def getrecursionlimit() -> int: + return sys.getrecursionlimit() + + +if sys.version_info >= (3, 11): + + @substitute_in_graph(sys.get_int_max_str_digits, can_constant_fold_through=True) + def get_int_max_str_digits() -> int: + return sys.get_int_max_str_digits() + + @substitute_in_graph(sys.set_int_max_str_digits, can_constant_fold_through=True) + def set_int_max_str_digits(maxdigits: int) -> None: + sys.set_int_max_str_digits(maxdigits) + + __all__ += ["get_int_max_str_digits", "set_int_max_str_digits"] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/tensor.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..0fcad636200414e4cc0aa67fa0600463e5a9e1d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/tensor.py @@ -0,0 +1,51 @@ +from typing import Any + +import torch + +from ..decorators import substitute_in_graph + + +@substitute_in_graph( # type: ignore[arg-type] + torch.Tensor._make_subclass +) +def make_subclass( + cls: type[Any], data: torch.Tensor, requires_grad: bool = False, **kwargs: Any +) -> Any: + with torch._C.DisableTorchFunctionSubclass(): + # This is a rough approximation of `THPVariable_make_subclass`. It should + # suffice for most of Dynamo tracing purposes. + # https://github.com/pytorch/pytorch/blob/ccfde4dadfa3c342076a1ee387017f84dd4ad2f7/torch/csrc/autograd/python_variable.cpp#L597-L650 + if len(kwargs) != 0: + raise AssertionError( + "_make_subclass only supports requires_grad as keyword arg" + ) + data = data.detach() + + # Avoid unnecessary `requires_grad` mutation, which isn't supported in Dynamo. + if data.requires_grad != requires_grad: + data.requires_grad = requires_grad + + # Dynamo can't yet handle upcasting to base tensor type via `as_subclass`. + if cls is torch.Tensor: + return torch.Tensor(data) + + # Calling `as_subclass` because + # 1. Dynamo knows how to handle it + # 2. the C impls match at this point -- both `THPVariable_make_subclass` and + # `THPVariable_as_subclass` calls `THPVariable_NewWithVar`. + return data.as_subclass(cls) + + +@substitute_in_graph( # type: ignore[arg-type] + torch.Tensor.__new__ +) +def tensor_pynew( + cls: type[Any], data: torch.Tensor, requires_grad: bool = False, **kwargs: Any +) -> Any: + return make_subclass(cls, data, requires_grad, **kwargs) + + +__all__ = [ + "make_subclass", + "tensor_pynew", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/torch_c_nn.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/torch_c_nn.py new file mode 100644 index 0000000000000000000000000000000000000000..c2258adac4cd3c636172a822e0683caf5c2ede74 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/torch_c_nn.py @@ -0,0 +1,121 @@ +""" +Polyfills for torch._C._nn functions. +""" + +from typing import Any + +import torch +from torch.overrides import _is_torch_function_mode_enabled, _pop_mode_temporarily + +from ..decorators import substitute_in_graph + + +@substitute_in_graph(torch._C._nn._parse_to, skip_signature_check=True) +def _parse_to_polyfill( + *args: Any, **kwargs: Any +) -> tuple[torch.device, torch.dtype, bool, torch.memory_format]: + """ + Polyfill for torch._C._nn._parse_to that parses arguments to nn.Module.to(). + + Signature mirrors torch._C._nn._parse_to which accepts: + - to(device) - device as string or torch.device + - to(dtype) - dtype as torch.dtype + - to(tensor) - extracts device and dtype from tensor + - to(device=..., dtype=..., non_blocking=..., memory_format=...) + + Returns: + tuple: (device, dtype, non_blocking, memory_format) + """ + # Check for __torch_function__ mode and dispatch using handle_torch_function pattern + if _is_torch_function_mode_enabled(): + with _pop_mode_temporarily() as mode: + result = mode.__torch_function__( + torch._C._nn._parse_to, tuple(), args, kwargs or {} + ) + if result is not NotImplemented: + return result + + # Default implementation + device = None + dtype = None + non_blocking = False + memory_format = None + + # Handle positional arguments + if len(args) == 1: + arg = args[0] + # Check if it's a tensor + if isinstance(arg, torch.Tensor): + device = arg.device + dtype = arg.dtype + # Check if it's a dtype + elif isinstance(arg, torch.dtype): + dtype = arg + # Check if it's a device (string or torch.device) + elif isinstance(arg, (str, torch.device)): + device = torch.device(arg) if isinstance(arg, str) else arg + else: + raise TypeError( + f"to() received an invalid combination of arguments. Got: {type(arg)}" + ) + elif len(args) > 1: + raise TypeError( + f"to() received too many positional arguments. Got {len(args)}, expected at most 1" + ) + + # Handle keyword arguments + if "device" in kwargs: + device_arg = kwargs["device"] + if device_arg is not None: + device = ( + torch.device(device_arg) if isinstance(device_arg, str) else device_arg + ) + + if "dtype" in kwargs: + dtype = kwargs["dtype"] + + if "non_blocking" in kwargs: + non_blocking = kwargs["non_blocking"] + + if "memory_format" in kwargs: + memory_format = kwargs["memory_format"] + + # pyrefly: ignore[bad-return] + return (device, dtype, non_blocking, memory_format) + + +@substitute_in_graph(torch.__future__.get_swap_module_params_on_conversion) +def get_swap_module_params_on_conversion_polyfill() -> bool: + """ + Polyfill for torch.__future__.get_swap_module_params_on_conversion. + + Returns the actual value from the underlying global variable. + """ + # Access the module's global variable directly to avoid recursion + import torch.__future__ as torch_future + + return torch_future._swap_module_params_on_conversion + + +@substitute_in_graph(torch._has_compatible_shallow_copy_type) +def _has_compatible_shallow_copy_type_polyfill( + input: torch.Tensor, from_: torch.Tensor +) -> bool: + """ + Polyfill for torch._has_compatible_shallow_copy_type. + + Checks if two tensors have compatible types for shallow copying. + The C++ implementation checks if input's TensorImpl has compatible shallow copy type + with from_'s key_set. We approximate this by checking if both tensors are the same type. + """ + # Check if both tensors are the same type (handles both regular tensors and subclasses) + # This is more permissive than checking exact torch.Tensor type equality + # but properly handles subclasses by allowing same-type shallow copies + return type(input) is type(from_) + + +__all__ = [ + "_parse_to_polyfill", + "get_swap_module_params_on_conversion_polyfill", + "_has_compatible_shallow_copy_type_polyfill", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/traceback.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/traceback.py new file mode 100644 index 0000000000000000000000000000000000000000..f44f59ad0c444e9da3f4b218ac2c4b5be9e6276d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/traceback.py @@ -0,0 +1,39 @@ +""" +Python polyfills for traceback +""" + +import traceback +from traceback import StackSummary +from types import TracebackType + +from ..decorators import substitute_in_graph + + +__all__ = ["extract_tb", "clear_frames"] + + +@substitute_in_graph(traceback.extract_tb, can_constant_fold_through=True) +def extract_tb(tb: TracebackType | None, limit: int | None = None) -> StackSummary: + if tb is None: + return traceback.StackSummary.from_list([]) + # pyrefly: ignore [implicit-any] + frame_summary = [] + while tb is not None: + if limit: + if len(frame_summary) < limit: + frame_summary.append( + # pyrefly: ignore[missing-attribute] + tb.frame_summary + ) + else: + break + else: + frame_summary.append(tb.frame_summary) # pyrefly: ignore[missing-attribute] + tb = tb.tb_next + return traceback.StackSummary.from_list(frame_summary) + + +@substitute_in_graph(traceback.clear_frames, can_constant_fold_through=True) +def clear_frames(tb: TracebackType | None) -> None: + # no-op + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/precompile_context.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/precompile_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1f31f1a54b7a388083b12422cbb3196a75d4b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/precompile_context.py @@ -0,0 +1,232 @@ +import copy +import json +import logging +from abc import abstractmethod +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Generic, TypeVar + +import torch +from torch._dynamo.package import ( + _BackendId, + _DynamoCacheEntry, + DynamoCache, + PrecompileCacheEntry, +) + + +""" +Classes and implementations related to precompile +""" + +T = TypeVar("T") +logger = logging.getLogger(__name__) + + +@dataclass +class BackendCacheArtifact(Generic[T]): + """ + Represents a single serializable backend artifact from a dynamo backend. + Each BackendCacheArtifact has a key associated with it along with some + serializable content. + + Example implementation: + + class MyPrecompileCacheArtifact(PrecompileCacheArtifact[MySerializableType]): + my_field: int + + def after_deserialization(self) -> MySerializableType: + result = pickle.loads(self.content) + # Do some extra work post deserialization + result.my_post_deserialization_function(self.my_field) + return result + """ + + key: str + content: Any + + @abstractmethod + def after_deserialization(self) -> T: + """ + Code to be run after reading raw byte contents from disk. + Generally converts self.content from raw bytes back into its original form. + """ + ... + + def edit_contents(self, edit_fn: Callable[..., Any]) -> None: + """ + Edit the contents of the artifact. + """ + self.content = edit_fn(self.content) + + +class EagerCacheArtifact(BackendCacheArtifact[Any]): + def after_deserialization(self) -> Any: + return self.content + + +class BypassDynamoCacheEntry(Exception): + pass + + +class PrecompileContext: + """ + PrecompileContext is a special CacheArtifactManager for handling precompilation + It uses the same interface as CacheArtifactManager, but handles deserialization differently: instead + of placing each artifact into respective caches, it will stitch all the cache artifacts for a single key + together and place it into a global Precompile Cache. + + PrecompileContext has two main portions: dynamo_cache_entries and backend_cache_artifacts. + When saving, PrecompileContext.serialize() will serialize all dynamo cache entries along with any PrecompileCacheArtifacts that + are needed to save those dynamo cache entries. + + The following artifact types are supported by PrecompileContext: + - BundledAOTAutogradCacheArtifact + + """ + + # Protected by the compile_lock + # _backend_artifacts_by_key organizes results by the key of each artifact. + # Each object here must be serializable + _backend_artifacts_by_key: dict[_BackendId, BackendCacheArtifact[Any]] = {} + + # On call to `serialize()`, all cache artifacts in _dynamo_cache_entries are converted + # into DynamoCacheArtifacts and added to _new_cache_artifacts for serialization + _dynamo_cache_entries: dict[str, _DynamoCacheEntry] = {} + + @classmethod + def clear(cls) -> None: + cls._backend_artifacts_by_key.clear() + cls._dynamo_cache_entries.clear() + + @classmethod + def record_artifact( + cls, + artifact: BackendCacheArtifact[Any], + ) -> None: + """ + Records a backend artifact to be used with dynamo cache entries + """ + # Temporarily disable all dispatch modes (including FakeTensorMode) during + # deepcopy to avoid issues with cloning fake tensors (e.g., device mesh + # with meta tensors that fail when cloning due to device mismatches) + from torch.utils._mode_utils import no_dispatch + + with no_dispatch(): + cls._backend_artifacts_by_key[_BackendId(artifact.key)] = copy.deepcopy( + artifact + ) + + @classmethod + def record_dynamo_cache_entry( + cls, cache_entry: _DynamoCacheEntry, key: str + ) -> None: + cls._dynamo_cache_entries[key] = cache_entry + + @classmethod + def edit_artifact(cls, key: str, edit_fn: Callable[..., Any]) -> None: + """ + Edit the content of an existing artifact + """ + if key not in cls._backend_artifacts_by_key: + raise AssertionError(f"Key {key} not found in artifacts") + artifact = cls._backend_artifacts_by_key[_BackendId(key)] + artifact.edit_contents(edit_fn) + + @classmethod + def serialize_artifact_by_key(cls, key: str) -> BackendCacheArtifact[Any] | None: + """ + Return the backend cache artifact with the associated key + """ + return cls._backend_artifacts_by_key.get(_BackendId(key), None) + + @staticmethod + def dump_debug_info( + dynamo_entries: dict[str, _DynamoCacheEntry], + backend_artifacts: dict[_BackendId, BackendCacheArtifact[Any]], + ) -> dict[str, Any]: + """ + Return a JSON serializable debug dump of all entries in the precompile context + Called in serialize before serialization, and in populate_caches after deserialization + """ + # Print debug information + debug_info: defaultdict[str, list[Any]] = defaultdict(list) + for key, cache_entry in dynamo_entries.items(): + info = cache_entry.debug_info() + info["key"] = key + debug_info["dynamo"].append(info) + + for artifact in backend_artifacts.values(): + debug_info["backends"].append(artifact.key) + + return debug_info + + @classmethod + def save_to_dynamo_cache(cls) -> dict[str, Any]: + precompile_cache_entries, debug_info = cls.create_cache_entries() + for key, entry in precompile_cache_entries.items(): + DynamoCache.write(entry, key) + return debug_info + + @classmethod + def create_cache_entries( + cls, + ) -> tuple[dict[str, PrecompileCacheEntry], dict[str, Any]]: + """ + Grabs all the cache entries in the precompile context and + stitches them together into full PrecompileCacheEntries. + """ + dynamo_entries = cls._dynamo_cache_entries + backend_artifacts = cls._backend_artifacts_by_key + + num_artifacts = len(dynamo_entries) + + debug_info = PrecompileContext.dump_debug_info( + dynamo_entries, backend_artifacts + ) + debug_str = json.dumps( + { + "num_entries": num_artifacts, + "artifacts": debug_info, + }, + ) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_cache_entries", + "encoding": "json", + }, + payload_fn=lambda: debug_str, + expect_trace_id=False, + ) + + precompile_cache_entries = {} + + for key, cache_entry in dynamo_entries.items(): + try: + result = PrecompileCacheEntry.from_cache_entry( + cache_entry, backend_artifacts + ) + if result is not None: + precompile_cache_entries[key] = result + except Exception as e: + logger.warning("Failed to create cache entry %s", key, exc_info=True) + + error = e + data = json.dumps( + { + "key": key, + "error": str(error), + } + ) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_cache_exception", + "encoding": "json", + }, + payload_fn=lambda: data, + ) + continue + return precompile_cache_entries, debug_info diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/profiler.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..d1edd1ea9cfadede4d4337fd626e0df5151e8a9e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/profiler.py @@ -0,0 +1,177 @@ +""" +Dynamo profiling implementation. + +This module provides profiling functionality for Dynamo, including: +- ProfileMetrics: Class for collecting and aggregating performance metrics like + execution time, operator counts, and fusion statistics +- ProfileResult: Class for analyzing and reporting profiling results +- Utilities for tracking missed/uncaptured operations +- Functions for instrumenting FX graphs with profiling capabilities + +The profiler helps measure and optimize the performance of Dynamo-compiled code +by tracking both captured and total operations, timing, and graph statistics. +""" + +from __future__ import annotations + +import dataclasses +import os +from typing import Any +from typing_extensions import Self + +import torch + +from .utils import print_once + + +@dataclasses.dataclass +class ProfileMetrics: + microseconds: float = 0.0 + operators: int = 0 + fusions: int = 0 + graphs: int = 0 + + def __iadd__(self, other: Self) -> Self: + self.microseconds += other.microseconds + self.operators += other.operators + self.fusions += other.fusions + return self + + def __add__(self, other: ProfileMetrics) -> ProfileMetrics: + if not isinstance(other, ProfileMetrics): + raise AssertionError(f"Expected ProfileMetrics, got {type(other)}") + return ProfileMetrics( + self.microseconds + other.microseconds, + self.operators + other.operators, + self.fusions + other.fusions, + ) + + def __truediv__(self, other: Any) -> ProfileMetrics: + if isinstance(other, int): + other = ProfileMetrics(other, other, other) + return ProfileMetrics( + self.microseconds / max(1, other.microseconds), + # pyrefly: ignore [bad-argument-type] + self.operators / max(1, other.operators), + # pyrefly: ignore [bad-argument-type] + self.fusions / max(1, other.fusions), + ) + + def __str__(self) -> str: + return f"{self.operators:4.0%} ops {self.microseconds:4.0%} time" + + def tocsv(self) -> list[float]: + return [self.operators, self.microseconds] + + +class ProfileResult: + def __init__( + self, captured: ProfileMetrics, total: ProfileMetrics, unique_graphs: int + ) -> None: + self.captured: ProfileMetrics = captured or ProfileMetrics() + self.total: ProfileMetrics = total or ProfileMetrics() + self.unique_graphs: int = unique_graphs + + def __iadd__(self, other: Self) -> Self: + self.captured += other.captured + self.total += other.total + self.unique_graphs += other.unique_graphs + return self + + def percent(self) -> ProfileMetrics: + return self.captured / self.total + + def __str__(self) -> str: + return ( + f"{self.unique_graphs:2} graphs {self.captured.graphs:2} graph calls " + f"{self.captured.operators:4}/{self.total.operators:4} = " + + str(self.percent()) + ) + + def tocsv(self) -> list[Any]: + return [ + self.unique_graphs, + self.captured.graphs, + self.captured.operators, + self.total.operators, + ] + self.percent().tocsv() + + +def should_print_missing() -> bool: + return os.environ.get("TORCHDYNAMO_PRINT_MISSING") == "1" + + +def print_missing(stack: list[str]) -> None: + if any("/torch/autograd/profiler.py" in x for x in stack): + return + stack = [ + x for x in stack if ("> ".join(stack[-3:])) + + +class Profiler: + unique_graphs: int = 0 + + def __init__(self) -> None: + self.prof = torch.profiler.profile( + activities=[torch.profiler.ProfilerActivity.CPU], + with_stack=should_print_missing(), + ) + + def results(self) -> ProfileResult: + captured_regions = 0 + captured_ops = 0 + captured_microseconds = 0 + total_ops = 0 + total_microseconds = 0 + + last_op_end_time = -1 + captured_region_end_time = -1 + events = sorted(self.prof.events(), key=lambda x: x.time_range.start) + for e in events: + if e.name == "TORCHDYNAMO": + captured_region_end_time = e.time_range.end + captured_regions += 1 + # ignore `handle = torch.zeros(1)` in record_function.__init__() + total_ops -= 1 + elif e.time_range.start >= last_op_end_time: + last_op_end_time = e.time_range.end + if e.time_range.end <= captured_region_end_time: + captured_ops += 1 + captured_microseconds += e.time_range.elapsed_us() + elif should_print_missing(): + print_missing(e.stack) + total_ops += 1 + total_microseconds += e.time_range.elapsed_us() + else: + pass # ops recursively called from other ops (ignored) + + unique_graphs = Profiler.unique_graphs + Profiler.unique_graphs = 0 + # we counted one extra op that is part of the profiler setup code + total_ops -= 1 + + return ProfileResult( + captured=ProfileMetrics( + microseconds=captured_microseconds, + operators=captured_ops, + fusions=captured_ops - captured_regions, + graphs=captured_regions, + ), + total=ProfileMetrics( + microseconds=total_microseconds, + operators=total_ops, + fusions=total_ops - 1, + ), + unique_graphs=unique_graphs, + ) + + +def fx_insert_profiling(gm: torch.fx.GraphModule, example_inputs: list[Any]) -> Any: + def _wrapped(*args: Any) -> Any: + with torch.profiler.record_function("TORCHDYNAMO"): + return gm.forward(*args) + + Profiler.unique_graphs += 1 + return _wrapped diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/replay_record.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/replay_record.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb414b5aab2f47ab2b0fe2b63ed7e54375494f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/replay_record.py @@ -0,0 +1,143 @@ +from __future__ import annotations + + +""" +Python execution state recording and replay functionality. + +This module provides mechanisms for capturing and replaying Python execution state: + +- ModuleRecord: Tracks module access patterns and attribute usage +- DummyModule: Lightweight module substitute for replay +- ExecutionRecord: Manages execution context including globals, locals and builtins +- ExecutionRecorder: Records variable states and module access during execution + +The module enables serialization and reproduction of Python execution environments, +particularly useful for debugging and testing frameworks that need to capture +and recreate specific program states. +""" + +import dataclasses +from dataclasses import field +from types import CellType, CodeType, ModuleType +from typing import Any, cast, IO, TYPE_CHECKING +from typing_extensions import Self + +from torch.utils._import_utils import import_dill + + +if TYPE_CHECKING: + from io import BufferedReader, BufferedWriter + + from .output_graph import CodeOptions + + +dill = import_dill() + + +@dataclasses.dataclass +class ModuleRecord: + module: ModuleType + accessed_attrs: dict[str, Any] = field(default_factory=dict) + + +@dataclasses.dataclass +class DummyModule: + name: str + is_torch: bool = False + value: object = None + + @property + def __name__(self) -> str: + return self.name + + +@dataclasses.dataclass +class ExecutionRecord: + code: CodeType + closure: tuple[CellType] + globals: dict[str, Any] = field(default_factory=dict) + locals: dict[str, Any] = field(default_factory=dict) + builtins: dict[str, Any] = field(default_factory=dict) + # The replay record starts empty and gets populated by the translator before use. + code_options: CodeOptions = field(default_factory=lambda: cast("CodeOptions", {})) + + def dump(self, f: IO[str] | BufferedWriter) -> None: + if dill is None: + raise AssertionError("replay_record requires `pip install dill`") + dill.dump(self, f) + + @classmethod + def load(cls, f: IO[bytes] | BufferedReader) -> Self: + if dill is None: + raise AssertionError("replay_record requires `pip install dill`") + return dill.load(f) + + +@dataclasses.dataclass +class ExecutionRecorder: + LOCAL_MOD_PREFIX = "___local_mod_" + + code: CodeType + closure: tuple[CellType] + globals: dict[str, Any] = field(default_factory=dict) + locals: dict[str, Any] = field(default_factory=dict) + builtins: dict[str, Any] = field(default_factory=dict) + # The recorder starts empty and gets populated by the translator before use. + code_options: CodeOptions = field(default_factory=lambda: cast("CodeOptions", {})) + name_to_modrec: dict[str, ModuleRecord] = field(default_factory=dict) + + def add_local_var(self, name: str, var: Any) -> None: + if isinstance(var, ModuleType): + self.locals[name] = self._add_mod(var) + else: + self.locals[name] = var + + def add_global_var(self, name: str, var: Any) -> None: + if isinstance(var, ModuleType): + self.globals[name] = self._add_mod(var) + else: + self.globals[name] = var + + def add_local_mod(self, name: str, mod: ModuleType) -> None: + if not isinstance(mod, ModuleType): + raise AssertionError(f"Expected ModuleType, got {type(mod)}") + self.add_global_var(name, mod) + + def record_module_access(self, mod: ModuleType, name: str, val: Any) -> None: + if isinstance(val, ModuleType): + self.name_to_modrec[mod.__name__].accessed_attrs[name] = self._add_mod(val) + return + + if mod.__name__ in self.name_to_modrec: + self.name_to_modrec[mod.__name__].accessed_attrs[name] = val + + def get_record(self) -> ExecutionRecord: + return ExecutionRecord( + self.code, + self.closure, + ExecutionRecorder._resolve_modules(self.globals), + ExecutionRecorder._resolve_modules(self.locals), + self.builtins.copy(), + self.code_options.copy(), + ) + + def _add_mod(self, mod: ModuleType) -> ModuleRecord: + if mod.__name__ not in self.name_to_modrec: + self.name_to_modrec[mod.__name__] = ModuleRecord(mod) + + return self.name_to_modrec[mod.__name__] + + @classmethod + def _resolve_modules(cls, vars: dict[str, Any]) -> dict[str, Any]: + def resolve_module(var: Any) -> Any: + if not isinstance(var, ModuleRecord): + return var + + dummy_mod = DummyModule(var.module.__name__) + for attr_name, attr_value in var.accessed_attrs.items(): + attr_value = resolve_module(attr_value) + dummy_mod.__setattr__(attr_name, attr_value) + + return dummy_mod + + return {k: resolve_module(v) for k, v in vars.items()} diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f46acd36db4fbef5c6080443fd67e67bfcc9a38 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__init__.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import Protocol + + +class ReproOptions(Protocol): + """ + Read-only view of the argparse Namespace threaded through the repro_* + entrypoints in after_aot.py and after_dynamo.py. + + argparse populates the Namespace dynamically, so a Protocol (rather than a + concrete class) is the pragmatic fit: it documents the attributes those + functions actually read without asserting how the Namespace is built. Not + every attribute is populated for every subcommand -- e.g. after_dynamo + never sets tracing_mode -- but each repro_* function only reads the subset + that its own subparser defines. + """ + + # Shared across the after_aot and after_dynamo subparsers. + command: str + accuracy: str + save_dir: str | None + + # after_aot-only attributes. + tracing_mode: str | None + check_str: str | None + isolate: bool + offload_to_disk: bool + skip_saving_eager_intermediates: bool + skip_sanity: bool + max_granularity: int | None + stable_hash: bool + skip_saving_inductor_intermediates: bool + skip_saving_float64_intermediates: bool + skip_check_deterministic: bool + + # after_dynamo-only attributes. + backend: str | None + autocast: bool + only_fwd: bool diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb0b5ed7ea405462d32dee24d558c0d5853c5b6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_aot.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_aot.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..825d7554d86d1b7f83587817058978daf086f209 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_aot.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_dynamo.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_dynamo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ad87c81d3086a54ccfe5276ee61c234ebe4526f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_dynamo.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/aoti.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/aoti.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbedebe5c73ecffb63d57a70fac0ed3b8c0e2853 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/aoti.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_aot.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_aot.py new file mode 100644 index 0000000000000000000000000000000000000000..263a469da5dbb615afd91ce28e626a36bc8753a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_aot.py @@ -0,0 +1,1755 @@ +""" +Utilities for reproducing and debugging issues in PyTorch's Dynamo AOT compilation. + +This module provides tools and infrastructure for: +1. Generating minimal reproducible test cases ("repros") from failing compilations +2. Analyzing accuracy issues between eager and compiled execution +3. Minifying large models/inputs to isolate problematic patterns +4. Debugging compiler errors and accuracy divergences + +The main components include: +- Repro generation: Creates standalone Python files that reproduce compiler issues +- Minification: Reduces large graphs to minimal failing examples +- Accuracy analysis: Compares compiled vs eager execution, with fp64 reference +- Debug tools: Dumps graph state, tracks intermediates, analyzes divergences + +This is primarily used by PyTorch developers and researchers to debug issues in +the Dynamo AOT compilation pipeline, particularly for the Inductor backend. +""" + +from __future__ import annotations + +import argparse +import ast +import copy +import functools +import io +import logging +import os +import shutil +import subprocess +import sys +import textwrap +import types +import typing +import uuid +from importlib import import_module +from tempfile import TemporaryFile +from typing import Any, IO, TYPE_CHECKING, TypedDict +from typing_extensions import Unpack + +import sympy + + +try: + import triton.language as tl + from triton.runtime.autotuner import Autotuner, Heuristics + from triton.runtime.jit import JITFunction + + TritonConstexpr = tl.constexpr +except ImportError: + + class Autotuner: # type: ignore[no-redef] + pass + + class JITFunction: # type: ignore[no-redef] + pass + + class Heuristics: # type: ignore[no-redef] + pass + + class TritonConstexpr: # type: ignore[no-redef] + pass + + +import torch +import torch.fx as fx +import torch.nn as nn +from torch._dynamo.debug_utils import ( + _cuda_system_info_comment, + AccuracyError, + backend_accuracy_fails, + BuckTargetWriter, + cast_to_fp64, + extra_deps, + extra_imports, + generate_config_string, + generate_env_vars_string, + helper_for_dump_minify, + InputReader, + InputWriter, + MAX_CONSTANT_NUMEL_INLINE, + minifier_dir, + NNModuleToString, + NopInputReader, + same_two_models, +) +from torch._dynamo.utils import clone_inputs, counters, same +from torch._environment import is_fbcode +from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table +from torch._inductor.cpp_builder import normalize_path_separator +from torch._library.fake_class_registry import FakeScriptObject +from torch._ops import OpOverload +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.experimental.symbolic_shapes import ( + fx_placeholder_targets, + has_free_symbols, +) +from torch.hub import tqdm + +from .. import config + + +def _find_repeat_interleave_constraints( + gm: torch.fx.GraphModule, +) -> list[tuple[str, str]]: + """ + Find repeat_interleave operations with output_size constraints. + + Returns list of (repeats_placeholder_name, output_size_placeholder_name) pairs. + These represent constraints where sum(repeats) must equal output_size. + """ + constraints = [] + for node in gm.graph.nodes: + if ( + node.op != "call_function" + or "repeat_interleave" not in str(node.target) + or not node.args + ): + continue + + output_size_node = node.kwargs.get("output_size") + repeats_node = node.args[0] + + # Both must be FX nodes (not constants) and direct placeholders + if ( + isinstance(repeats_node, torch.fx.Node) + and isinstance(output_size_node, torch.fx.Node) + and repeats_node.op == "placeholder" + and output_size_node.op == "placeholder" + ): + constraints.append((str(repeats_node.target), str(output_size_node.target))) + + return constraints + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from torch._inductor.compile_fx import _CompileFxCallable, _CompileFxKwargs + from torch._inductor.output_code import OutputCode + from torch._inductor.utils import InputType + + from . import ReproOptions + + +log = logging.getLogger(__name__) + + +inductor_config = import_module("torch._inductor.config") + + +class GroupInfo(TypedDict): + size: int + rank: int + + +def _extract_distributed_info( + gm: torch.fx.GraphModule, +) -> dict[str, GroupInfo]: + """ + Extract process group information from distributed ops in the graph. + + Returns a dict mapping group names to dicts with 'size' and 'rank' keys. + Example: {'tp': {'size': 4, 'rank': 0}, 'dp': {'size': 2, 'rank': 0}} + """ + from torch.distributed import GroupName + from torch.fx.operator_schemas import normalize_function + + group_info: dict[str, GroupInfo] = {} + + for node in gm.graph.nodes: + if node.op != "call_function": + continue + if not isinstance(node.target, OpOverload): + continue + if node.target.namespace not in {"_c10d_functional", "c10d_functional"}: + continue + + opt_args_kwargs = normalize_function( + node.target, + args=node.args, + kwargs=node.kwargs, + normalize_to_only_use_kwargs=True, + ) + if opt_args_kwargs is None: + continue + _, kwargs = opt_args_kwargs + + group_name_ = kwargs.get("group_name") + if not isinstance(group_name_, str): + continue + group_name = typing.cast(GroupName, group_name_) + + if group_name in group_info: + continue + + from torch.distributed.distributed_c10d import ( + _get_group_size_by_name, + _resolve_process_group, + ) + + group_size = _get_group_size_by_name(group_name) + pg = _resolve_process_group(group_name) + rank = pg.rank() + group_info[group_name] = {"size": group_size, "rank": rank} + + return group_info + + +def setup_fake_process_groups( + group_info: dict[str, GroupInfo], +) -> None: + """ + Set up fake process groups for repro execution. + + Args: + group_info: dict mapping group_name -> {'size': group_size, 'rank': rank} + """ + import torch.distributed as dist + from torch.testing._internal.distributed.fake_pg import FakeStore + + if not group_info: + return + + world_size = max(info["size"] for info in group_info.values()) + + global_rank = 0 + for info in group_info.values(): + if info["size"] == world_size: + global_rank = info["rank"] + break + + store = FakeStore() + dist.init_process_group( + backend="fake", + rank=global_rank, + world_size=world_size, + store=store, + ) + + default_pg = dist.distributed_c10d._get_default_group() + torch._C._distributed_c10d._unregister_all_process_groups() + + for group_name, info in group_info.items(): + group_size = info["size"] + if group_size == world_size: + # pyrefly: ignore[bad-argument-type] + torch._C._distributed_c10d._register_process_group(group_name, default_pg) + else: + ranks = list(range(group_size)) + new_pg = dist.new_group(ranks) + # pyrefly: ignore[bad-argument-type] + torch._C._distributed_c10d._register_process_group(group_name, new_pg) + + +def generate_standalone_repro( + gm: torch.fx.GraphModule, + args: Sequence[Any], + *, + save_path: str | None = None, +) -> str: + """ + Generate a self-contained repro script from an FX graph. + """ + buf = io.StringIO() + save_graph_repro(buf, gm, args, "inductor", save_dir=None) + repro = buf.getvalue() + + if save_path is not None: + with open(save_path, "w") as f: + f.write(repro) + log.info("Saved standalone repro to %s", save_path) + + return repro + + +use_buck = is_fbcode() + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MAIN ENTRY POINT +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def wrap_compiler_debug( + unconfigured_compiler_fn: _CompileFxCallable, + compiler_name: str, +) -> _CompileFxCallable: + """ + Minifier for Fx Graph modules after Aot Autograd has finished. We wrap both + forward and backward call separately with the backend compiler_fn - like + inductor or nvfuser. Intercepting after Aot Autograd presents neat + abstraction, where all the params are lifted as graph inputs, making it easy + to save the graph as a string. + """ + + @functools.wraps(unconfigured_compiler_fn) + def debug_wrapper( + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType], + compile_region_name: str | None = None, + **kwargs: Unpack[_CompileFxKwargs], + ) -> OutputCode: + from torch._subclasses import FakeTensorMode + + compiler_fn = functools.partial( + unconfigured_compiler_fn, + compile_region_name=compile_region_name, + **kwargs, + ) + + from torch._functorch.aot_autograd import get_aot_graph_name + + graph_name = get_aot_graph_name() + + # TODO: why do we need to deepcopy the original graph? + orig_graph = copy.deepcopy(gm.graph) + if config.repro_after not in ("dynamo", "aot", None): + raise AssertionError( + f"repro_after must be 'dynamo', 'aot', or None, got {config.repro_after!r}" + ) + + try: + # Call the compiler_fn - which is either aot_autograd or inductor + # with fake inputs + inner_compiled_fn = compiler_fn(gm, example_inputs) + except Exception: + # TODO: Failures here are troublesome because no real inputs, + # need a different serialization strategy + if config.repro_after == "aot": + if config.repro_level == 1: + dump_compiler_graph_state( + fx.GraphModule(gm, orig_graph), + example_inputs, + compiler_name, + ) + elif config.repro_level == 2: + dump_to_minify( + fx.GraphModule(gm, orig_graph), + example_inputs, + compiler_name, + ) + log.error("CompilerError") + raise + + # We may run regular PyTorch compute that may trigger Dynamo, do NOT + # recursively attempt to accuracy minify in that case! + def deferred_for_real_inputs( + real_inputs: Sequence[InputType], **_kwargs: object + ) -> Any: + # This is a bit obscure: if we recursively try to accuracy minify + # the SAME function, this would trigger. But most of the time + # we should never hit this branch + if _kwargs: + raise AssertionError(f"Unexpected kwargs: {_kwargs}") + if config.repro_after != "aot": + if isinstance(inner_compiled_fn, str): + raise AssertionError("inner_compiled_fn should not be a string") + return inner_compiled_fn(real_inputs) + with config.patch(repro_after=None): + return inner_debug_fn(real_inputs) + + def inner_debug_fn(real_inputs: Sequence[InputType]) -> Any: + """ + Aot Autograd fw_compiler and bw_compiler can have fake tensors. So, + example_inputs can be fake tensors. We can call compiler_fn (which is + inductor or nvfuser) with fake tensors but the actually compiled_fn + should be called with real tensors. Therefore, the actual invocation + is deferred. + """ + # Copy the tensor attrs like shape, stride etc by converting to Fake Tensor + # because inductor clears the tensor list in its codegen. And example_inputs + # are available only for the first invocation. + fake_mode = FakeTensorMode() + copy_tensor_attrs = [ + fake_mode.from_tensor(x) if isinstance(x, torch.Tensor) else x + for x in real_inputs + ] + if config.repro_level == 3: + # Always dump the original module in case we have segfaults + dump_to_minify( + fx.GraphModule(gm, orig_graph), real_inputs, compiler_name + ) + + if config.repro_level == 4: + if compiler_name != "inductor": + raise NotImplementedError( + "Accuracy minification is supported for inductor only" + ) + failed = not same_two_models( + gm, + inner_compiled_fn, # type: ignore[arg-type] + real_inputs, + only_fwd=True, + ignore_non_fp=config.repro_ignore_non_fp, + ) + + if failed: + log.warning( + "Accuracy failed for the AOT Autograd graph %s", graph_name + ) + dump_compiler_graph_state( + fx.GraphModule(gm, orig_graph), + real_inputs, + f"{compiler_name}_accuracy", + ) + dump_to_minify( + fx.GraphModule(gm, orig_graph), + real_inputs, + f"{compiler_name}_accuracy", + ) + raise AccuracyError("Bad accuracy detected") + else: + # Call the compiled function with real inputs + return inner_compiled_fn(real_inputs) # type: ignore[operator] + else: + try: + # Call the compiled function with real inputs + out = inner_compiled_fn(real_inputs) # type: ignore[operator] + # sync cuda kernels to ensure IMA detection + if ( + any( + isinstance(arg, torch.Tensor) and arg.device.type != "cpu" + for arg in example_inputs + ) + and torch.accelerator.is_available() + ): + torch.accelerator.synchronize() + return out + except Exception: + if config.repro_level == 1: + dump_compiler_graph_state( + fx.GraphModule(gm, orig_graph), + copy_tensor_attrs, + compiler_name, + ) + elif config.repro_level == 2: + dump_to_minify( + fx.GraphModule(gm, orig_graph), + copy_tensor_attrs, + compiler_name, + ) + raise + + if config.repro_after == "aot": + compiled_fn = deferred_for_real_inputs + compiled_fn._boxed_call = True # type: ignore[attr-defined] + return compiled_fn # type: ignore[return-value] + else: + return inner_compiled_fn + + return debug_wrapper + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# DUMP REPROS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def maybe_fbcode_instructions() -> str: + if is_fbcode(): + extra_deps_formatted = "\n".join([f' "{dep}",' for dep in extra_deps]) + if len(extra_deps_formatted) > 0: + extra_deps_formatted = "\n" + extra_deps_formatted + return f"""\ +\"\"\" +To run this script in fbcode: +- Create a directory (//scripts/{{your_unixname}}/repro) +- Put this file in scripts/{{your_unixname}}/repro/fx_graph_runnable.py +- Add a TARGETS file that looks like the following +- `buck2 run //scripts/{{your_unixname}}/repro:repro` + +NOTE: you may need additional deps to actually be able to run the script. +``` +# Contents of TARGETS file +load("@fbcode_macros//build_defs:python_binary.bzl", "python_binary") + +python_binary( + name = "repro", + main_src = "fx_graph_runnable.py", + deps = [ + "//caffe2:torch",{extra_deps_formatted} + ], +) +``` +\"\"\" +""" + else: + return "" + + +def generate_custom_triton_kernel(kernel: Any) -> str: + res = "" + if isinstance(kernel, Autotuner): + # pyrefly: ignore [missing-attribute] + if isinstance(kernel.fn, Heuristics): + res += "ERROR: Repro will not work as intended, " + res += "triton.runtime.autotuner.Heuristics is not currently supported\n" + return res + + config_strs = [] + # pyrefly: ignore [missing-attribute] + for kernel_config in kernel.configs: + config_strs.append(f"""triton.Config( + {str(kernel_config.kwargs)}, + num_warps={kernel_config.num_warps}, + num_stages={kernel_config.num_stages}, + )""") + + config_str = ",".join(config_strs) + res += textwrap.dedent(f""" + @triton.autotune( + configs=[ + {config_str} + ], + key=[] + ) + """).strip() + + # pyrefly: ignore [missing-attribute] + src_code = kernel.src if isinstance(kernel, JITFunction) else kernel.fn.src + res += "\n@triton.jit\n" + res += src_code + res += "\n" + + return res + + +def generate_compiler_repro_string( + gm: torch.fx.GraphModule, + args: Sequence[Any], + *, + stable_output: bool = False, + save_dir: str | None = None, + stable_hash: bool = False, + has_distributed_ops: bool = False, +) -> str: + if save_dir is not None: + save_dir = normalize_path_separator(save_dir) + # Add distributed imports if needed + distributed_imports = "" + if has_distributed_ops: + distributed_imports = textwrap.dedent( + """ +import torch.distributed as dist +from torch.testing._internal.distributed.fake_pg import FakeStore + """ + ).strip() + + triton_imports = "" + + if len(kernel_side_table.id_to_kernel) > 0: + triton_imports = textwrap.dedent( + """ +import triton +import triton.language as tl + """ + ).strip() + + model_str = textwrap.dedent( + f""" +{generate_env_vars_string(stable_output=stable_output)} +import torch +from torch import tensor, device +import torch.fx as fx +from torch._dynamo.testing import rand_strided +import math +from math import inf +import torch._inductor.inductor_prims +{distributed_imports} +{triton_imports} + +{generate_config_string(stable_output=stable_output)} + +isolate_fails_code_str = None + +{extra_imports} + +{maybe_fbcode_instructions()} + """ + ) + model_str += textwrap.dedent( + """ +if "__compile_source__" in globals(): + import inspect as __after_aot_inspect + import linecache as __after_aot_linecache + __after_aot_filename = __after_aot_inspect.currentframe().f_code.co_filename + __after_aot_linecache.cache[__after_aot_filename] = ( + len(__compile_source__), + None, + __compile_source__.splitlines(True), + __after_aot_filename, + ) +""" + ) + if not stable_output: + model_str += f"# torch version: {torch.version.__version__}\n" + if hasattr(torch.version, "cuda"): + model_str += f"# torch cuda version: {torch.version.cuda}\n" + if hasattr(torch.version, "git_version"): + model_str += f"# torch git version: {torch.version.git_version}\n\n\n" + model_str += _cuda_system_info_comment() + + kernel_side_table_prefix = ( + "torch._higher_order_ops.triton_kernel_wrap.kernel_side_table" + ) + + def get_fn_name(kernel: Any) -> str: + fn: Any = kernel if isinstance(kernel, JITFunction) else kernel.fn + return fn.__name__.split(".")[-1] + + def get_triton_import_line(name: str, val: Any) -> str | None: + # User-defined Triton kernels are serialized from their source, not from + # their original Python module. If the source references a global + # imported from Triton, such as `from triton.language.extra import + # libdevice`, the standalone repro must recreate that import. + if name in ("triton", "tl"): + return None + + if isinstance(val, types.ModuleType): + module_name = val.__name__ + if module_name == "triton" or module_name.startswith("triton."): + return f"import {module_name} as {name}" + return None + + module_name = getattr(val, "__module__", None) + object_name = getattr(val, "__name__", None) + if ( + isinstance(module_name, str) + and (module_name == "triton" or module_name.startswith("triton.")) + and isinstance(object_name, str) + ): + if name == object_name: + return f"from {module_name} import {object_name}" + return f"from {module_name} import {object_name} as {name}" + + return None + + def write_kernel_dependencies( + kernel: Any, + written_constexpr_vars: set[str], + written_nested_kernels: set[str], + written_triton_imports: set[str], + ) -> str: + """Write out global triton imports, tl.constexpr vars, and nested kernels.""" + result = "" + jit_fn = kernel if isinstance(kernel, JITFunction) else kernel.fn + if not getattr(jit_fn, "fn", None) or not getattr(jit_fn, "src", None): + return result + + fn_globals = getattr(jit_fn.fn, "__globals__", {}) + src = jit_fn.src + full_src = src if src.strip().startswith("def ") else "def " + src + + referenced_names: set[str] = set() + called_names: set[str] = set() + for node in ast.walk(ast.parse(full_src)): + if isinstance(node, ast.Name): + referenced_names.add(node.id) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + called_names.add(node.func.id) + + # Only recreate globals that are safe and useful for a standalone + # Triton repro: imports anchored in the Triton package and simple + # constants. Other user globals remain unsupported here. + for name in sorted(referenced_names): + if name in written_constexpr_vars: + continue + val = fn_globals.get(name) + + import_line = get_triton_import_line(name, val) + if import_line is not None: + if import_line not in written_triton_imports: + result += import_line + "\n" + written_triton_imports.add(import_line) + continue + + if isinstance(val, TritonConstexpr) and getattr(val, "value", None): + result += f"{name} = tl.constexpr({val.value})\n" + elif isinstance(val, (int, float, str, bool)): + result += f"{name} = {val!r}\n" + else: + continue + written_constexpr_vars.add(name) + + # Write out nested kernel dependencies + for name in called_names: + val = fn_globals.get(name) + if not isinstance(val, JITFunction) or val is jit_fn: + continue + nested_fn_name = get_fn_name(val) + if nested_fn_name in written_nested_kernels: + continue + # Mark as written before recursing to prevent cycles + written_nested_kernels.add(nested_fn_name) + result += write_kernel_dependencies( + val, + written_constexpr_vars, + written_nested_kernels, + written_triton_imports, + ) + result += generate_custom_triton_kernel(val) + + return result + + written_nested_kernels: set[str] = set() + written_constexpr_vars: set[str] = set() + written_triton_imports: set[str] = { + "import triton", + "import triton.language as tl", + } + + model_str += f"{kernel_side_table_prefix}.reset_table()\n" + + for idx in kernel_side_table.id_to_kernel: + kernel = kernel_side_table.get_kernel(idx) + + try: + model_str += write_kernel_dependencies( + kernel, + written_constexpr_vars, + written_nested_kernels, + written_triton_imports, + ) + fn_name = get_fn_name(kernel) + + unique_name = f"{fn_name}_{idx}" + + kernel_code = generate_custom_triton_kernel(kernel) + kernel_code = kernel_code.replace( + f"def {fn_name}(", f"def {unique_name}(", 1 + ) + model_str += kernel_code + model_str += f"{kernel_side_table_prefix}.add_kernel({unique_name})\n" + except AttributeError as e: + model_str += "ERROR: Repro will not work as intended, " + model_str += f"User defined triton kernel exception: {e}\n" + + if len(kernel_side_table.constant_args) > 0: + model_str += f"{kernel_side_table_prefix}.constant_args={kernel_side_table.constant_args}\n" + + # This string is also emitted as a best-effort trace artifact during + # normal compilation, so unsupported modules must not mask compile errors. + model_str += NNModuleToString.convert(gm, allow_unsafe_repr=True) + + writer = InputWriter(save_dir, stable_hash=stable_hash) + # pyrefly: ignore [implicit-any] + used_syms = {} + + # Extract from graph placeholders and their corresponding arguments + placeholder_targets = fx_placeholder_targets(gm) + for placeholder, arg in zip(placeholder_targets, args): + if isinstance(arg, (int, torch.SymInt)): + writer.symint(placeholder, arg) + elif isinstance(arg, torch.Tensor): + # TODO: improve these names with FQN + writer.tensor(placeholder, arg) + elif arg is None: + writer.const(placeholder) + elif isinstance(arg, FakeScriptObject): + writer.opaque(placeholder, arg.script_class_name) + elif isinstance(arg, torch._C.Generator): + writer.generator(placeholder, arg) + else: + writer.unsupported(placeholder, arg) + + # Extract symbolic variables from the same arguments + + if ( + isinstance(arg, torch.SymInt) + # By checking sympy.Symbol, we are excluding any symbolic expressions. + # TODO: we may need to solve expressions to extract symbol definitions. + and isinstance(arg.node.expr, sympy.Symbol) + and arg.node.hint is not None + ): + used_syms[str(arg.node)] = arg.node.hint + elif isinstance(arg, torch.Tensor): + # Extract symbolic variables from tensor shapes and strides + for dim in arg.shape: + if ( + isinstance(dim, torch.SymInt) + and isinstance(dim.node.expr, sympy.Symbol) + and dim.node.hint is not None + ): + used_syms[str(dim.node)] = dim.node.hint + for stride in arg.stride(): + if ( + isinstance(stride, torch.SymInt) + and isinstance(stride.node.expr, sympy.Symbol) + and stride.node.hint is not None + ): + used_syms[str(stride.node)] = stride.node.hint + # Extract symbols from storage nbytes (can be a symbolic expression) + storage = arg.untyped_storage() + nbytes = storage.nbytes() + if isinstance(nbytes, torch.SymInt): + expr = nbytes.node.expr + shape_env = nbytes.node.shape_env + for sym in expr.free_symbols: + sym_name = str(sym) + if sym_name not in used_syms and shape_env is not None: + hint = shape_env.backed_var_to_val.get(sym) + if hint is not None: + used_syms[sym_name] = int(hint) + # Add symbolic variable definitions to the top of the generated code + if used_syms: + hint_lines = "\n".join( + f"{name} = {hint}" for name, hint in sorted(used_syms.items()) + ) + model_str = f"{hint_lines}\n\n{model_str}" + + # Add fixup code for repeat_interleave constraints + # When inputs are regenerated randomly, sum(repeats) != output_size + # This fixup adjusts the repeats tensor to satisfy the constraint + constraints = _find_repeat_interleave_constraints(gm) + if constraints: + placeholder_to_idx = {name: idx for idx, name in enumerate(placeholder_targets)} + for repeats_name, output_size_name in constraints: + repeats_idx = placeholder_to_idx.get(repeats_name) + output_size_idx = placeholder_to_idx.get(output_size_name) + if repeats_idx is not None and output_size_idx is not None: + # Guard with hasattr since NopInputReader doesn't have args + writer._lines.append( + "# Fixup: ensure sum(repeats) == output_size for repeat_interleave" + ) + writer._lines.append("if hasattr(reader, 'args'):") + writer._lines.append(f" _repeats = reader.args[{repeats_idx}]") + writer._lines.append( + f" _output_size = reader.args[{output_size_idx}]" + ) + writer._lines.append( + " if isinstance(_repeats, torch.Tensor) and _repeats.dtype == torch.int64:" + ) + writer._lines.append(" _n = _repeats.numel()") + writer._lines.append(" _repeats.fill_(_output_size // _n)") + writer._lines.append(" _repeats[:_output_size % _n] += 1") + + load_args_lines = writer.lines() + load_args_code = "\n".join(load_args_lines) + model_str += load_args_code + "\n" + + model_str += "mod = Repro()\n" + return model_str + + +def save_graph_repro( + fd: IO[Any], + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str, + *, + stable_output: bool = False, + save_dir: str | None = None, + command: str = "run", + accuracy: str | bool | None = None, + tracing_mode: str | None = None, + check_str: str | None = None, + stable_hash: bool = False, +) -> None: + if any( + isinstance(arg, torch.fx.experimental._backward_state.BackwardState) + for arg in args + ): + fd.write( + "Repro is not generated due to existence of BackwardState in graph input" + ) + return + + if save_dir is not None: + save_dir = normalize_path_separator(save_dir) + + # Extract distributed info from the graph + distributed_info = _extract_distributed_info(gm) + has_distributed_ops = len(distributed_info) > 0 + + fd.write( + generate_compiler_repro_string( + gm, + args, + stable_output=stable_output, + save_dir=save_dir, + stable_hash=stable_hash, + has_distributed_ops=has_distributed_ops, + ) + ) + if accuracy is None: + accuracy = "_accuracy" in compiler_name + if tracing_mode is None: + tracing_mode = "real" + if any( + has_free_symbols(a) for a in args if not isinstance(a, FakeScriptObject) + ): + tracing_mode = "symbolic" + fd.write("if __name__ == '__main__':\n") + fd.write(" from torch._dynamo.repro.after_aot import run_repro\n") + + # Add distributed initialization before run_repro if needed + if has_distributed_ops: + fd.write( + " from torch._dynamo.repro.after_aot import setup_fake_process_groups\n" + ) + fd.write(f" setup_fake_process_groups({distributed_info!r})\n") + + fd.write( + f" with torch.no_grad():\n" + f" run_repro(mod, load_args, accuracy={accuracy!r}, command={command!r}, " + f"save_dir={save_dir!r}, tracing_mode={tracing_mode!r}, check_str={check_str!r})\n" + f" # To run it separately, do \n" + f" # mod, args = run_repro(mod, load_args, accuracy={accuracy!r}, command='get_args', " + f"save_dir={save_dir!r}, tracing_mode={tracing_mode!r}, check_str={check_str!r})\n" + f" # mod(*args)" + ) + + # Add distributed cleanup after run_repro + if has_distributed_ops: + fd.write("\n dist.destroy_process_group()\n") + + +def dump_compiler_graph_state( + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str, + *, + accuracy: str | bool | None = None, +) -> None: + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + file_name = os.path.join(subdir, f"{len(gm.graph.nodes)}.py") + log.warning( + "Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name + ) + with open(file_name, "w") as fd: + save_graph_repro( + fd, gm, args, compiler_name, save_dir=subdir, accuracy=accuracy + ) + curdir = os.getcwd() + repro_path = os.path.join(curdir, "repro.py") + try: + shutil.copyfile(file_name, repro_path) + log.warning("Copying repro file for convenience to %s", repro_path) + if use_buck: + BuckTargetWriter(file_name).write() + except OSError: + log.warning("No write permissions for %s", repro_path) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# DUMP MINIFIER +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def dump_to_minify( + gm: torch.fx.GraphModule, args: Sequence[Any], compiler_name: str +) -> None: + out = io.StringIO() + # TODO: factor this out + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + save_graph_repro(out, gm, args, compiler_name, save_dir=subdir, command="minify") + return helper_for_dump_minify(out.getvalue()) + + +def isolate_fails( + fx_g: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str, + env: dict[str, Any] | None = None, + save_dir: str | None = None, + accuracy: bool | str | None = None, + tracing_mode: str | None = None, + check_str: str | None = None, +) -> bool: + if env is None: + env = {} + subdir = os.path.join(os.getcwd(), "isolate") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + file_name = os.path.join(subdir, f"{str(uuid.uuid4())[:5]}.py") + with open(file_name, "w") as fd: + save_graph_repro( + fd, + fx_g, + args, + compiler_name, + save_dir=save_dir, + command="minifier-query", + accuracy=accuracy, + tracing_mode=tracing_mode, + check_str=check_str, + ) + # with open(file_name, "r") as fd: + # print(fd.read()) + new_env = os.environ.copy() + new_env = {**new_env, **env} + if use_buck: + cmd = BuckTargetWriter(file_name).write(print_msg=False) + else: + cmd = [sys.executable, file_name] + with ( + TemporaryFile() as stdout, + TemporaryFile() as stderr, + subprocess.Popen( + cmd, + cwd=subdir, + stdout=stdout, + stderr=stderr, + env=new_env, + ) as p, + ): + p.wait() + + stdout.seek(0) + stderr.seek(0) + print( + textwrap.indent(stdout.read().decode("utf-8"), prefix=">> "), + file=sys.stdout, + ) + print( + textwrap.indent(stderr.read().decode("utf-8"), prefix=">> "), + file=sys.stderr, + ) + # print(f"Isolated test failed - {file_name}") + return p.returncode != 0 + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MINIFIER TOOLS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def inductor_fails( + fx_g: torch.fx.GraphModule, args: Sequence[Any], check_str: str | None = None +) -> bool: + has_gpu = any( + isinstance(arg, torch.Tensor) and arg.device.type != "cpu" for arg in args + ) + + def sync() -> None: + if has_gpu and torch.accelerator.is_available(): + # Ensures that segfaults are surfaced + torch.accelerator.synchronize() + + from torch._inductor.compile_fx import compile_fx_inner + + try: + result = fx_g(*args) + if not isinstance(result, (tuple, list)): + raise AssertionError( + f"Expected result to be a tuple or list, got {type(result)}" + ) + if any(isinstance(x, (tuple, list)) for x in result): + raise AssertionError("Result should not contain nested tuples or lists") + except Exception: + return False + + sync() + + try: + compile_args = _get_compile_args(fx_g, args) + compile_mod = compile_fx_inner(fx_g, compile_args) + if isinstance(compile_mod, str): + raise AssertionError("compile_fx_inner should not return a string") + compile_mod(args) + sync() + except Exception as e: + if check_str is not None and check_str not in repr(e): + return False + print(repr(e)) + return True + return False + + +def inductor_accuracy_fails( + fx_g: torch.fx.GraphModule, + args: Sequence[Any], + check_str: str | None = None, + *, + require_fp64: bool = False, + ignore_non_fp: bool = False, +) -> bool: + from torch._inductor.compile_fx import compile_fx_inner + + def _compile_with_symbolic_args( + gm: torch.fx.GraphModule, inputs: list[Any] + ) -> torch.fx.GraphModule: + return compile_fx_inner(gm, _get_compile_args(gm, inputs)) # type: ignore[return-value] + + return backend_aot_accuracy_fails( + fx_g, + args, # type: ignore[arg-type] + _compile_with_symbolic_args, # type: ignore[arg-type] + require_fp64=require_fp64, + ignore_non_fp=ignore_non_fp, + ) + + +backend_aot_accuracy_fails = functools.partial(backend_accuracy_fails, only_fwd=True) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# REPRO MAIN +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def _build_symbolic_wrapper( + mod: nn.Module, + args: list[Any], + symint_exprs: dict[int, str], +) -> tuple[nn.Module, list[Any]] | None: + """Build a wrapper module that preserves symbolic relationships. + + Returns (wrapper_module, wrapper_args) where wrapper_args has carrier + tensors in place of free-symbol symints, and the wrapper's forward() + extracts SymInts from carrier.size(0), computes derived expressions, + and delegates to the inner module. + + Returns None if the expressions don't contain free/derived structure + (nothing to do). + """ + import re + + free_sym_re = re.compile(r"^s\d+$") + free_positions: dict[int, str] = {} + derived_positions: dict[int, str] = {} + + for idx, expr_str in symint_exprs.items(): + if free_sym_re.fullmatch(expr_str): + free_positions[idx] = expr_str + else: + derived_positions[idx] = expr_str + + if not free_positions: + return None + + # Order: carrier tensors first, then all non-symint args in original order + free_order = sorted(free_positions.keys()) + free_sym_names = [free_positions[i] for i in free_order] + + # Precompile derived expressions + derived_compiled = { + idx: compile(expr_str, f"", "eval") + for idx, expr_str in derived_positions.items() + } + + n_args = len(args) + + class _SymIntWrapper(nn.Module): + def __init__(self, inner: nn.Module) -> None: + super().__init__() + self.inner = inner + + def forward(self, *flat_args: Any) -> Any: + carriers = flat_args[: len(free_order)] + other = flat_args[len(free_order) :] + + syms: dict[str, Any] = {} + for i, sym_name in enumerate(free_sym_names): + syms[sym_name] = carriers[i].size(0) + + for idx, code in sorted(derived_compiled.items()): + derived_positions[idx] # keep reference + syms[f"_derived_{idx}"] = eval(code, {"__builtins__": {}}, syms) + + other_iter = iter(other) + rebuilt = [] + for i in range(n_args): + if i in free_positions: + rebuilt.append(syms[free_positions[i]]) + elif i in derived_positions: + rebuilt.append(syms[f"_derived_{i}"]) + else: + rebuilt.append(next(other_iter)) + + return self.inner(*rebuilt) + + # Build wrapper args: carriers + non-symint args + wrapper_args: list[Any] = [] + for i in free_order: + hint = int(args[i]) if not isinstance(args[i], int) else args[i] + device = "cpu" + for a in args: + if isinstance(a, torch.Tensor) and a.is_cuda: + device = a.device + break + wrapper_args.append(torch.empty(hint, dtype=torch.int8, device=device)) + + for i, arg in enumerate(args): + if i not in free_positions and i not in derived_positions: + wrapper_args.append(arg) + + return _SymIntWrapper(mod), wrapper_args + + +def repro_common( + options: ReproOptions, mod: nn.Module, load_args: Any +) -> tuple[torch.fx.GraphModule, list[Any]]: + # Invariant for graphs we generate with the repro script + if any(mod.named_parameters()): + raise AssertionError("Repro graph should not have any parameters") + for n, b in mod.named_buffers(): + if b.numel() > MAX_CONSTANT_NUMEL_INLINE: + log.warning( + "Constant %s was not serialized, generated random data instead. " + "If you think this is affecting you, please comment on " + "https://github.com/pytorch/pytorch/issues/100468", + n, + ) + + if not hasattr(load_args, "_version"): + log.warning( + "load_args does not have a _version attribute, please file a bug to PyTorch " + "and describe how you generate this repro script" + ) + else: + if load_args._version > 0: + log.warning( + "load_args is version %s, but this version of PyTorch only supports " + "version 0. We will try to run it anyway but there may be an incompatibility; " + "if so, try upgrading your version of PyTorch.", + load_args._version, + ) + + nop_reader = NopInputReader() + load_args(nop_reader) + + with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar: + input_reader = InputReader(save_dir=options.save_dir, pbar=pbar) + load_args(input_reader) + args = input_reader.args + + # Turn mod into a GraphModule the slow way + # TODO: speed this up + # NOTE: symint_exprs (from reader.symint(val, expr=...)) are preserved + # in the repro script for documentation. A future improvement could use + # _build_symbolic_wrapper to reconstruct algebraic relationships between + # free and derived symints, but the arg reordering is fragile across + # different graph structures so we skip it for now. + mod = make_fx(mod, tracing_mode=options.tracing_mode)(*args) # type: ignore[arg-type] + + # pyrefly: ignore [bad-assignment] + torch._inductor.config.generate_intermediate_hooks = True + + return mod, args + + +def _get_compile_args(mod: torch.fx.GraphModule, args: Sequence[Any]) -> Sequence[Any]: + """Extract FakeTensor/SymInt args from the traced graph for compilation. + + When repro_common traces with tracing_mode='symbolic', the resulting + GraphModule's placeholder nodes carry FakeTensor/SymInt metadata. + compile_fx_inner needs these (not the concrete args) so that Inductor + generates proper symbolic-size bindings in the output code. + + For tracing_mode='real', concrete args are fine — we must NOT extract + FakeTensor metadata because different nodes may have FakeTensors from + different FakeTensorModes, causing a FakeTensorMode mismatch assertion + in Inductor. We detect symbolic tracing by checking for SymInt values, + which only exist when tracing_mode='symbolic'. + """ + placeholders = [n for n in mod.graph.nodes if n.op == "placeholder"] + if not placeholders: + return args + # Only extract metadata if the graph was traced with symbolic mode. + # SymInt values in placeholder metadata are the reliable indicator — + # FakeTensors appear in both real and symbolic modes, but only symbolic + # tracing creates SymInts for integer inputs. + has_symint = any(isinstance(n.meta.get("val"), torch.SymInt) for n in placeholders) + if not has_symint: + return args + return [n.meta.get("val", a) for n, a in zip(placeholders, args)] + + +ACCURACY_FAILS: dict[str, Callable[[torch.fx.GraphModule, Any], bool]] = { + "": inductor_fails, + # This might look inverted but it's not. strict_accuracy means "we will + # minify any time we see anything that diverges", whereas accuracy is more + # conservative, and will only minify if there is a meaningful fp64 + # divergence + "accuracy": functools.partial( + inductor_accuracy_fails, require_fp64=True, ignore_non_fp=True + ), + "strict_accuracy": inductor_accuracy_fails, +} + + +def repro_minifier_query(options: ReproOptions, mod: nn.Module, load_args: Any) -> None: + mod, args = repro_common(options, mod, load_args) + fail_fn = functools.partial( + ACCURACY_FAILS[options.accuracy], + check_str=options.check_str, # type: ignore[call-arg] + ) + if fail_fn(mod, args): + sys.exit(1) + else: + sys.exit(0) + + +def repro_minify(options: ReproOptions, mod: nn.Module, load_args: Any) -> None: + from functorch.compile import minifier + + mod, args = repro_common(options, mod, load_args) + compiler_name = "inductor_accuracy" if options.accuracy != "" else "inductor" + + favored_device = 1 if torch.cuda.device_count() >= 2 else 0 + env_variables = {"CUDA_VISIBLE_DEVICES": str(favored_device)} + + module_fails: Any + if options.isolate: + module_fails = functools.partial( + isolate_fails, + env=env_variables, + compiler_name=compiler_name, + save_dir=options.save_dir, + accuracy=options.accuracy, + tracing_mode=options.tracing_mode, + ) + else: + module_fails = ACCURACY_FAILS[options.accuracy] + + with config.patch(repro_after=None): + minifier( + mod, + args, + module_fails=functools.partial(module_fails, check_str=options.check_str), + dump_state=functools.partial( + dump_compiler_graph_state, compiler_name=compiler_name + ), + save_dir=options.save_dir, + offload_to_disk=options.offload_to_disk, + skip_offload=options.skip_saving_eager_intermediates, + skip_sanity=options.skip_sanity, + max_granularity=options.max_granularity, + ) + + +def repro_analyze(options: ReproOptions, mod: nn.Module, load_args: Any) -> None: + from torch._inductor.compile_fx import compile_fx_inner + from torch._inductor.hooks import intermediate_hook + + mod, args = repro_common(options, mod, load_args) + + # TODO: The logic for cloning inputs/models here is intentionally + # modeled off of run_fwd_maybe_bwd, but arguably it is better not to + # clone inputs (as you are doubling your effective GPU memory usage). + # It is certainly faster though! It probably makes sense to let the + # user specify the offload strategy. + + compile_mod = copy.deepcopy(mod) + compile_args = _get_compile_args(compile_mod, args) + with tqdm(desc="Compiling"): + compiled = compile_fx_inner(compile_mod, compile_args) + total = counters["inductor"]["intermediate_hooks"] + + known_names = set() + + def save_hook(name: str, val: Any) -> None: + known_names.add(name) + if not options.skip_saving_inductor_intermediates: + writer.write_tensor(os.path.join("inductor", name), val) + pbar.update(1) # type: ignore[has-type] + + # analyze stores and re-reads intermediates on disk, so a save_dir is + # required; --no-save-dir (save_dir=None) is invalid for this subcommand. + save_dir = options.save_dir + if save_dir is None: + raise RuntimeError("analyze requires a save_dir; do not pass --no-save-dir") + writer = torch.utils._content_store.ContentStoreWriter( + save_dir, stable_hash=options.stable_hash + ) + reader = torch.utils._content_store.ContentStoreReader(save_dir) + + new_args = clone_inputs(args) + with ( + intermediate_hook(save_hook), + tqdm(desc="Saving inductor intermediates", total=total) as pbar, + ): + if isinstance(compiled, str): + raise AssertionError("compile_fx_inner should not return a string") + compiled(new_args) # type: ignore[arg-type] + if new_args: + raise AssertionError("new_args should be empty after compiled() call") + + def compare_tuples(tuple1: tuple[Any], tuple2: tuple[Any]) -> str | None: + diff_indices = [i for i in range(len(tuple1)) if tuple1[i] != tuple2[i]] + diff_values = [(tuple1[i], tuple2[i]) for i in diff_indices] + + if not diff_values: + return None + else: + return " and ".join(f"{a} != {b}" for a, b in diff_values) + + def check_hook(name: str, val: Any) -> None: + meta = writer.compute_tensor_metadata(val) + meta2 = reader.read_tensor_metadata(os.path.join("inductor", name)) + reason = compare_tuples(meta, meta2) + if reason is not None: + pbar.write(f"NONDETERMINISTIC INDUCTOR at {name} ({reason})") + pbar.update(1) + + if not options.skip_check_deterministic: + new_args = clone_inputs(args) + with ( + intermediate_hook(check_hook), + tqdm(desc="Checking inductor determinism", total=total) as pbar, + ): + compiled(new_args) # type: ignore[arg-type] + if new_args: + raise AssertionError("new_args should be empty after compiled() call") + + class WriterInterp(fx.Interpreter): + def __init__(self, mod: torch.nn.Module, subdir: str) -> None: + super().__init__(mod) + self.subdir = subdir + + def run_node(self, n: torch.fx.Node) -> Any: + r = super().run_node(n) + name = n.name + if name in known_names: + pbar.update(1) + writer.write_tensor(os.path.join(self.subdir, name), r) + return r + + # NB: the module cast doesn't actually do anything, since there are no + # parameters/buffers on the module + if not options.skip_saving_float64_intermediates: + new_mod, new_args = cast_to_fp64(copy.deepcopy(mod), clone_inputs(args)) # type: ignore[arg-type] + with tqdm(desc="Saving float64 intermediates", total=total) as pbar: + WriterInterp(new_mod, "float64").boxed_run(new_args) + if new_args: + raise AssertionError("new_args should be empty after boxed_run() call") + + class ExactReaderInterp(fx.Interpreter): + def run_node(self, n: torch.fx.Node) -> Any: + r = super().run_node(n) + name = n.name + if name in known_names: + meta = writer.compute_tensor_metadata(r) + meta2 = reader.read_tensor_metadata(os.path.join("float64", name)) + reason = compare_tuples(meta, meta2) + if reason is not None: + pbar.write(f"NONDETERMINISTIC FLOAT64 at {name} ({reason})") + pbar.update(1) + return r + + # TODO: check eager determinism + + if not options.skip_check_deterministic: + new_mod, new_args = cast_to_fp64(copy.deepcopy(mod), clone_inputs(args)) # type: ignore[arg-type] + with tqdm(desc="Checking float64 determinism", total=total) as pbar: + ExactReaderInterp(new_mod).boxed_run(new_args) + if new_args: + raise AssertionError("new_args should be empty after boxed_run() call") + + # Now that we've saved everything, interp through the eager graph + # and do comparisons + class ReaderInterp(fx.Interpreter): + def run_node(self, n: torch.fx.Node) -> Any: + r = super().run_node(n) + name = n.name + if name in known_names: + inductor = reader.read_tensor(os.path.join("inductor", name)) + float64 = reader.read_tensor(os.path.join("float64", name)) + logged = False + + def log_error(msg: str, *args: Any) -> None: + nonlocal logged + logged = True + pbar.write(f"DIVERGED at {name}: {msg % args}") + + if not same( + r, + inductor, + float64, + tol=torch._dynamo.config.repro_tolerance, + equal_nan=True, + log_error=log_error, + ): + if not logged: + raise AssertionError("Divergence detected but not logged") + pbar.update(1) + return r + + with tqdm(desc="Checking divergence", total=total) as pbar: + ReaderInterp(mod).boxed_run(args) + if args: + raise AssertionError("args should be empty after boxed_run() call") + + +def repro_get_args( + options: ReproOptions, mod: nn.Module, load_args: Any +) -> tuple[torch.fx.GraphModule, list[Any]]: + mod, args = repro_common(options, mod, load_args) + return mod, args + + +def repro_run(options: ReproOptions, mod: nn.Module, load_args: Any) -> None: + from torch._inductor.compile_fx import compile_fx_inner + + mod, args = repro_common(options, mod, load_args) + + compile_mod = copy.deepcopy(mod) + compile_args = _get_compile_args(compile_mod, args) + compiled = compile_fx_inner(compile_mod, compile_args) + if isinstance(compiled, str): + raise AssertionError("compile_fx_inner should not return a string") + + if options.accuracy != "": + # We don't really respect --accuracy vs --strict-accuracy here, it + # seems counterintuitive + if not same_two_models( + mod, + compiled, # type: ignore[arg-type] + args, + only_fwd=True, + ignore_non_fp=config.repro_ignore_non_fp, + ): + raise AccuracyError("Bad accuracy detected") + else: + compiled(list(args)) + if ( + any( + isinstance(arg, torch.Tensor) and arg.device.type != "cpu" + for arg in args + ) + and torch.accelerator.is_available() + ): + torch.accelerator.synchronize() # ensure segfaults are surfaced + + +# TODO: lazily load the inputs or something, rather than cloning them +def run_repro( + mod: nn.Module, + load_args: Any, + *, + command: str = "run", + accuracy: bool | str = "", + save_dir: str | None = None, + tracing_mode: str | None = None, + patch_code: str | None = None, + check_str: str | None = None, + **kwargs: Any, +) -> Any: + for k in kwargs: + log.warning( + "Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch", + k, + ) + + if accuracy is True: + accuracy = "accuracy" + elif accuracy is False: + accuracy = "" + + if patch_code is not None: + log.warning( + "patch_code no longer works on this version of PyTorch, silently ignoring" + ) + + parser = argparse.ArgumentParser( + description=f"""\ +An after_aot repro script, typically triggering a bug in PyTorch Inductor. +When run with no arguments, this script defaults to running '{command}'. +Extra flags may be available; to find out more, try '{command} --help'. +There are also alternate subcommands available, see below. + +default settings on this script: + {accuracy=} + {tracing_mode=} + {save_dir=} + {check_str=} +""", + formatter_class=argparse.RawTextHelpFormatter, + ) + + def common_flags(parser: argparse.ArgumentParser) -> None: + accuracy_group = parser.add_mutually_exclusive_group() + accuracy_group.add_argument( + "--no-accuracy", + dest="accuracy", + action="store_const", + const="", + default=accuracy, + help="do not test accuracy, just run the module and see if it errors", + ) + accuracy_group.add_argument( + "--accuracy", + action="store_const", + const="accuracy", + default=accuracy, + help="""\ +test if the RMSE between the compiled module and the fp64 reference is greater +than eager and the fp64 reference. This is usually more reliable than the +standard allclose test, as we expect numeric differences from compiling, often +improving accuracy over eager. RMSE test allows for compiled module to +diverge greatly from eager, as long as this divergence moves it closer to the +'true' mathematical value of the network. Caveats: (1) double precision can +still suffer from rounding error, so it is not a perfect reference (see for +example 'Herbie: Automatically Improving Floating Point Accuracy') for +approaches that detect the necessary working precision and compute it in +arbitrary precision floating point; unfortunately, this is not practical for +tensor computation; (2) if there are not enough samples in the output being +compared, we may get unlucky and have an unlucky greater RMSE than eager; this +could be overcome by applying a more rigorous statistical test at some +p-value, which we leave for future work. +""", + ) + accuracy_group.add_argument( + "--strict-accuracy", + dest="accuracy", + action="store_const", + const="strict_accuracy", + default=accuracy, + help="""\ +by default, when doing accuracy minification we will reject reductions which +change the divergence from a floating point divergence to an integral/boolean +divergence. This is because some operations like ReLU involve temporarily +sharp boundaries that smooth out again afterwards; without requiring +divergence on floating point, the minifier will often fixate on divergent +boolean tensor even though this is not the true source of the divergence. +However, rejecting these reductions makes it more difficult for the minifier +to make progress. Using this option will let the minifier progress for ALL +divergences--you just might not end up with a useful repro in the end.""", + ) + + parser.add_argument( + "--save-dir", + type=str, + default=save_dir, + metavar="DIR", + help="directory where saved inputs live", + ) + parser.add_argument( + "--no-save-dir", + dest="save_dir", + action="store_const", + const=None, + help="don't use any directory for saved inputs", + ) + parser.add_argument( + "--tracing-mode", + type=str, + metavar="{real,fake,symbolic}", + default=tracing_mode, + help="how to trace the repro module into a GraphModule with metadata", + ) + + subparsers = parser.add_subparsers( + dest="command", metavar="{run,minify,analyze}", required=True + ) + + parser_run = subparsers.add_parser( + "run", + help="just run the repro", + ) + common_flags(parser_run) + + parser_minify = subparsers.add_parser( + "minify", help="run the minifier on the repro" + ) + common_flags(parser_minify) + parser_get_args = subparsers.add_parser("get_args", help="get the args") + common_flags(parser_get_args) + parser_minify_isolate = parser_minify.add_mutually_exclusive_group() + parser_minify_isolate.add_argument( + "--isolate", + action="store_true", + default=True, + help="run in separate processes to avoid interference (default)", + ) + parser_minify_isolate.add_argument( + "--no-isolate", + dest="isolate", + action="store_false", + help="speed up by running all compilation in same process", + ) + parser_minify.add_argument( + "--skip-saving-eager-intermediates", + action="store_true", + help="skip saving eager intermediates on --minify", + ) + # TODO: make this an option for --analyze too + parser_minify.add_argument( + "--offload-to-disk", + action="store_true", + help="during minification, offload delta debugging intermediates to disk. Use if you're OOMing", + ) + parser_minify.add_argument( + "--skip-sanity", + action="store_true", + help="skip sanity check at beginning of minification on original graph", + ) + parser_minify.add_argument( + "--max-granularity", + type=int, + default=None, + help="start at this granularity and work down; must be power of 2", + ) + parser_minify.add_argument( + "--check-str", + type=str, + default=check_str, + help="require minified program to fail with error containing this string", + ) + + parser_analyze = subparsers.add_parser( + "analyze", help="run the accuracy analyzer on the repro" + ) + common_flags(parser_analyze) + parser_analyze.add_argument( + "--skip-saving-inductor-intermediates", + action="store_true", + help="skip saving inductor intermediates on --analyze", + ) + parser_analyze.add_argument( + "--skip-saving-float64-intermediates", + action="store_true", + help="skip saving float64 intermediates", + ) + parser_analyze.add_argument( + "--skip-check-deterministic", + action="store_true", + help="skip checking that the network is deterministic", + ) + parser_analyze.add_argument( + "--stable-hash", + action="store_true", + help="use SHA-1 checksum instead of fast (but possibly unsound) hash", + ) + + # Run the repro in the context of minification, inverting exit code meaning + parser_minifier_query = subparsers.add_parser( + "minifier-query", + ) + common_flags(parser_minifier_query) + parser_minifier_query.add_argument( + "--check-str", + type=str, + default=check_str, + help="require minified program to fail with error containing this string", + ) + + args = None + if len(sys.argv) <= 1: + args = [command, *sys.argv[1:]] + + options = typing.cast("ReproOptions", parser.parse_args(args)) + COMMAND_FNS = { + "minify": repro_minify, + "analyze": repro_analyze, + "minifier-query": repro_minifier_query, + "run": repro_run, + "get_args": repro_get_args, + } + return COMMAND_FNS[options.command](options, mod, load_args) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_dynamo.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_dynamo.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5b2d232a613880c4c1a0d97975fb484b693291 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_dynamo.py @@ -0,0 +1,672 @@ +""" +Utilities for reproducing and debugging issues in Dynamo after graph capture. + +This file provides tools and infrastructure for debugging problems that occur +after Dynamo has captured the graph but before/during backend compilation. +Key components include: + +- Minification tools to reduce large graphs to minimal failing examples +- Accuracy testing to validate compiled graph outputs match eager mode +- Repro generation to create standalone reproduction scripts +- Debug backends for capturing and analyzing failures +- Utilities for saving/loading graph states and inputs + +The tools here focus specifically on the post-graph-capture stage, making them +useful for debugging backend compilation issues, AOTAutograd problems, and +accuracy discrepancies between compiled and eager execution. +""" + +import argparse +import copy +import functools +import logging +import os +import shutil +import sys +import textwrap +from collections.abc import Callable, Sequence +from importlib import import_module +from typing import Any, cast + +import torch +import torch.fx as fx +from torch._dynamo.debug_utils import ( + AccuracyError, + backend_accuracy_fails, + BUCK_CMD_PREFIX, + BuckTargetWriter, + extra_imports, + generate_config_string, + generate_env_vars_string, + helper_for_dump_minify, + InputReader, + InputWriter, + minifier_dir, + NNModuleToString, + NopInputReader, + run_fwd_maybe_bwd, + same_two_models, +) +from torch.fx.experimental.symbolic_shapes import fx_placeholder_targets +from torch.hub import tqdm + +from .. import config +from ..backends.registry import CompilerFn, lookup_backend, register_debug_backend +from ..debug_utils import clone_inputs_retaining_gradness +from ..types import CompilerConfigProvider +from . import ReproOptions + + +log = logging.getLogger(__name__) + + +inductor_config = import_module("torch._inductor.config") +use_buck = inductor_config.is_fbcode() + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MAIN ENTRY POINT +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def _accuracy_fails( + gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + compiler_fn: Callable[[torch.fx.GraphModule, list[Any]], torch.fx.GraphModule], +) -> bool: + return backend_accuracy_fails( + gm, + example_inputs, + compiler_fn, + only_fwd=config.repro_forward_only, + ignore_non_fp=config.repro_ignore_non_fp, + ) + + +class WrapBackendDebug: + def __init__( + self, unconfigured_compiler_fn: CompilerFn, compiler_name: str | None + ) -> None: + functools.wraps(unconfigured_compiler_fn)(self) + self._torchdynamo_orig_backend = unconfigured_compiler_fn + self._compiler_name = compiler_name + if hasattr(unconfigured_compiler_fn, "__name__"): + self.__name__ = unconfigured_compiler_fn.__name__ + if hasattr(unconfigured_compiler_fn, "compiler_name"): + self.__name__ = unconfigured_compiler_fn.compiler_name # type: ignore[attr-defined] + if hasattr(unconfigured_compiler_fn, "get_compiler_config"): + self.get_compiler_config = cast( + CompilerConfigProvider, unconfigured_compiler_fn + ).get_compiler_config + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[Any], **kwargs: Any + ) -> torch.fx.GraphModule: + compiler_fn = functools.partial(self._torchdynamo_orig_backend, **kwargs) + if config.repro_after not in ("dynamo", "aot", None): + raise AssertionError( + f"repro_after must be 'dynamo', 'aot', or None, got {config.repro_after!r}" + ) + + if config.repro_after == "dynamo": + + def add_paths(exc: Exception) -> None: + exc.minifier_path = os.path.join(minifier_dir(), "minifier_launcher.py") # type: ignore[attr-defined] + if use_buck: + exc.buck_command = " ".join( # type: ignore[attr-defined] + BUCK_CMD_PREFIX + + [BuckTargetWriter(exc.minifier_path).cmd_line_path] # type: ignore[attr-defined] + ) + + if config.repro_level == 3: + dump_to_minify_after_dynamo(gm, example_inputs, self._compiler_name) + + # Check for either accuracy (level 4) or other type of failures. + if config.repro_level == 4: + # Check Accuracy + compiled_gm = compiler_fn(copy.deepcopy(gm), example_inputs) + if _accuracy_fails(gm, example_inputs, compiler_fn): # type: ignore[arg-type] + log.warning( + "Accuracy failed for the TorchDynamo produced graph. Creating script to minify the error." + ) + dump_to_minify_after_dynamo( + fx.GraphModule(gm, copy.deepcopy(gm.graph)), + example_inputs, + self._compiler_name, + ) + exc = AccuracyError("Bad accuracy detected.") + add_paths(exc) + raise exc + else: + try: + compiled_gm = compiler_fn(copy.deepcopy(gm), example_inputs) + run_fwd_maybe_bwd(compiled_gm, example_inputs) # type: ignore[arg-type] + except Exception as exc: + log.warning( + "Compiled Fx GraphModule failed. Creating script to minify the error." + ) + if config.repro_level == 1: + dump_state_fn = functools.partial( + dump_backend_state, compiler_name=self._compiler_name + ) + dump_state_fn( + fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs + ) + elif config.repro_level == 2: + dump_to_minify_after_dynamo( + fx.GraphModule(gm, copy.deepcopy(gm.graph)), + example_inputs, + self._compiler_name, + ) + add_paths(exc) + raise + else: + compiled_gm = compiler_fn(gm, example_inputs) + + return compiled_gm # type: ignore[return-value] + + +def wrap_backend_debug( + unconfigured_compiler_fn: CompilerFn, compiler_name: str | None +) -> WrapBackendDebug: + """ + A minifier decorator that wraps the TorchDynamo produced Fx graph modules. + As opposed to wrap_compiler_debug, this wrapper intercepts at the + TorchDynamo produced Fx Graph Module. This makes it backend-agnostic to some + level, e.g., it is useful for minifying issues related to Aot Autograd + tracing. If an error is found, we minify and save the minified repro in + repro.tar.gz. + """ + return WrapBackendDebug(unconfigured_compiler_fn, compiler_name) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# REPRO DUMPERS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def generate_dynamo_fx_repro_string( + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str | None, + check_accuracy: bool = False, + *, + stable_output: bool = False, + save_dir: str | None = None, + command: str = "run", +) -> str: + """ + Generate a repro string for backend-agnostic minified version. + """ + + model_str = NNModuleToString.convert(gm) + + # TODO: Figure out why torch.compile'd hash isn't work on this codepath + writer = InputWriter(save_dir, stable_hash=True) + for placeholder, arg in zip(fx_placeholder_targets(gm), args): + if isinstance(arg, (int, torch.SymInt)): + writer.symint(placeholder, arg) + elif isinstance(arg, torch.Tensor): + # TODO: improve these names with FQN + writer.tensor(placeholder, arg) + else: + raise TypeError(f"arg is neither SymInt/int nor torch.Tensor, {arg}") + load_args = "\n".join(writer.lines()) + + return textwrap.dedent( + f""" +{generate_env_vars_string(stable_output=stable_output)} +import math +from math import inf +import torch +from torch import tensor, device +import torch.fx as fx +import torch._dynamo +from torch._dynamo.testing import rand_strided +from torch._dynamo.debug_utils import run_fwd_maybe_bwd + +{generate_config_string(stable_output=stable_output)} + +{extra_imports} + +{model_str} +mod = Repro() + +{load_args} + +if __name__ == '__main__': + from torch._dynamo.repro.after_dynamo import run_repro + run_repro(mod, load_args, accuracy={check_accuracy!r}, command={command!r}, + save_dir={save_dir!r}, autocast={torch.is_autocast_enabled()!r}, backend={compiler_name!r}) +""" + ) + + +def dump_backend_repro_as_file( + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str | None, + check_accuracy: bool = False, +) -> None: + """ + Saves the repro to a repro.py file + """ + curdir = os.getcwd() + subdir = os.path.join(os.getcwd(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + file_name = os.path.join(subdir, f"minified_{len(gm.graph.nodes)}_nodes.py") + log.warning( + "Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name + ) + + with open(file_name, "w") as fd: + fd.write( + generate_dynamo_fx_repro_string( + gm, args, compiler_name, check_accuracy, save_dir=subdir + ) + ) + latest_repro = os.path.join(curdir, "repro.py") + log.warning("Copying %s to %s for convenience", file_name, latest_repro) + + if use_buck: + BuckTargetWriter(latest_repro).write() + + shutil.copyfile(file_name, latest_repro) + + +def dump_backend_state( + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str | None, + check_accuracy: bool = False, +) -> None: + """ + Dumps the dynamo graph to repro the issue. + 1) It tries to convert Fx GraphModule to a string. If we can, it writes to a + repro.py file. + 2) If we can't convert Fx GraphModule to a string, we use to_folder to save + the module and save a tar file. + """ + if not NNModuleToString.can_convert_to_string(gm): + raise AssertionError("GraphModule cannot be converted to string") + return dump_backend_repro_as_file(gm, args, compiler_name, check_accuracy) + # return dump_backend_repro_as_tarfile(gm, args, compiler_name) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MINIFIER DUMPER +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def dump_to_minify_after_dynamo( + gm: torch.fx.GraphModule, args: Sequence[Any], compiler_name: str | None +) -> None: + # TODO: factor this out + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + helper_for_dump_minify( + generate_dynamo_fx_repro_string( + gm, + args, + compiler_name, + check_accuracy=config.repro_level == 4, + save_dir=subdir, + command="minify", + ) + ) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MINIFIER BACKENDS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +@register_debug_backend # type: ignore[arg-type] +def dynamo_minifier_backend( + gm: fx.GraphModule, example_inputs: Sequence[Any], compiler_name: str | None +) -> fx.GraphModule: + from functorch.compile import minifier + + compiler_fn = lookup_backend(compiler_name) # type: ignore[arg-type] + + # TODO: It's inconsistent to pass SymInt inputs but REAL tensors. + # We should pass ints and look at the GraphModule placeholders + # to resolve them to SymInt (if necessary) + example_inputs = [ + i.node.hint if isinstance(i, torch.SymInt) else i for i in example_inputs + ] + + try: + compiled_gm = compiler_fn(gm, example_inputs) + run_fwd_maybe_bwd(compiled_gm, example_inputs) # type: ignore[arg-type] + raise ValueError("No issue was detected") + except Exception as exc: + orig_failure = str(exc) + log.warning( + "Compiled Fx GraphModule failed. Creating script to minify the error." + ) + dump_state_fn = functools.partial( + dump_backend_state, compiler_name=compiler_name + ) + dump_state_fn(fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs) + fails_fn = functools.partial( + backend_fails, + compiler_fn=compiler_fn, + orig_failure=orig_failure, + ) + minifier( + gm, + example_inputs, + module_fails=fails_fn, + dump_state=dump_state_fn, + ) + return gm + + +@register_debug_backend # type: ignore[arg-type] +def dynamo_accuracy_minifier_backend( + gm: fx.GraphModule, example_inputs: Sequence[Any], compiler_name: str | None +) -> fx.GraphModule: + from functorch.compile import minifier + + compiler_fn = lookup_backend(compiler_name) # type: ignore[arg-type] + + # Set the eval mode to remove randomness. + gm.eval() + + # Check Accuracy + if _accuracy_fails(gm, example_inputs, compiler_fn): # type: ignore[arg-type] + log.warning("Accuracy failed for the TorchDynamo produced graph") + dump_state_fn = functools.partial( + dump_backend_state, compiler_name=compiler_name, check_accuracy=True + ) + fails_fn = functools.partial( + _accuracy_fails, + compiler_fn=compiler_fn, # type: ignore[arg-type] + ) + dump_state_fn(fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs) + minifier( + gm, + example_inputs, + module_fails=fails_fn, + dump_state=dump_state_fn, + ) + else: + log.error("Input graph does not fail accuracy testing") + return gm + + +def backend_fails( + gm: fx.GraphModule, + example_inputs: Sequence[Any], + compiler_fn: CompilerFn, + orig_failure: Sequence[Any], +) -> bool: + """ + Minifier uses this function to identify if the minified graph module fails + with the same error. + + One caveat is that minifier can potentially go into a wrong direction when + the resulting graph module fails for a different reason. To avoid this, we + save the string for the original exception and check similarity between new + and old exception. They can be somewhat different in some cases, when the + exception string depends on the failing node information. So, we have a + loose similarity metric to guide the minifier path. + """ + from difflib import SequenceMatcher + + try: + # Run the original gm to check eager validity + run_fwd_maybe_bwd(gm, clone_inputs_retaining_gradness(example_inputs)) + compiled_gm = compiler_fn(gm, example_inputs) # type: ignore[arg-type] + run_fwd_maybe_bwd(compiled_gm, clone_inputs_retaining_gradness(example_inputs)) # type: ignore[arg-type] + except Exception as e: + new_failure = str(e) + if SequenceMatcher(None, orig_failure, new_failure).ratio() > 0.5: + return True + return False + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# REPRO MAIN +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def run_load_args( + options: ReproOptions, mod: torch.nn.Module, load_args: Any +) -> list[Any]: + if not hasattr(load_args, "_version"): + log.warning( + "load_args does not have a _version attribute, please file a bug to PyTorch " + "and describe how you generate this repro script" + ) + else: + if load_args._version > 0: + log.warning( + "load_args is version %s, but this version of PyTorch only supports " + "version 0. We will try to run it anyway but there may be an incompatibility; " + "if so, try upgrading your version of PyTorch.", + load_args._version, + ) + + nop_reader = NopInputReader() + load_args(nop_reader) + + with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar: + input_reader = InputReader(save_dir=options.save_dir, pbar=pbar) + load_args(input_reader) + args = input_reader.args + + return args + + +def repro_minify(options: ReproOptions, mod: torch.nn.Module, load_args: Any) -> None: + # Setup debug minifier compiler + if not options.accuracy: + compiler_fn = lookup_backend("dynamo_minifier_backend") + else: + compiler_fn = lookup_backend("dynamo_accuracy_minifier_backend") + + if options.backend is None: + raise RuntimeError( + "Compiler name is None - this likely means that a custom compiler " + "was called by torchdynamo. Please remove this error, import your " + "custom compiler function, and replace the backend=None " + "line in run_repro to backend=" + ) + + dynamo_minifier_backend = functools.partial( + compiler_fn, + compiler_name=options.backend, # type: ignore[call-arg] + ) + opt_mod = torch._dynamo.optimize(dynamo_minifier_backend)(mod) + + args = run_load_args(options, mod, load_args) + device_type = next( + ( + a.device.type + for a in args + if isinstance(a, torch.Tensor) and a.device.type != "cpu" + ), + "cpu", + ) + with torch.amp.autocast(device_type, enabled=options.autocast): + opt_mod(*args) + + +def repro_run(options: ReproOptions, mod: torch.nn.Module, load_args: Any) -> None: + opt_mod = torch._dynamo.optimize(options.backend)(mod) + + if options.accuracy != "": + mod.eval() + opt_mod.eval() # type: ignore[union-attr] + + args = run_load_args(options, mod, load_args) + device_type = next( + ( + a.device.type + for a in args + if isinstance(a, torch.Tensor) and a.device.type != "cpu" + ), + "cpu", + ) + with torch.amp.autocast(device_type, enabled=options.autocast): + # TODO: disable clone + if not same_two_models(mod, mod, args): # type: ignore[arg-type] + raise AssertionError("Eager itself failed") + if not same_two_models( + mod, # type: ignore[arg-type] + opt_mod, # type: ignore[arg-type] + args, + only_fwd=config.repro_forward_only, + ignore_non_fp=config.repro_ignore_non_fp, + ): + raise AccuracyError("Dynamo failed") + else: + args = run_load_args(options, mod, load_args) + device_type = next( + ( + a.device.type + for a in args + if isinstance(a, torch.Tensor) and a.device.type != "cpu" + ), + "cpu", + ) + with torch.amp.autocast(device_type, enabled=options.autocast): + run_fwd_maybe_bwd(mod, args, only_fwd=options.only_fwd, disable_clone=True) # type: ignore[arg-type] + del args + + args = run_load_args(options, mod, load_args) + run_fwd_maybe_bwd( + opt_mod, # type: ignore[arg-type] + args, + only_fwd=options.only_fwd, + disable_clone=True, # type: ignore[arg-type] + ) + + +def run_repro( + mod: torch.nn.Module, + load_args: Any, + *, + command: str = "run", + accuracy: bool | str = "", + save_dir: str | None = None, + autocast: bool = False, + backend: str = "inductor", + **kwargs: Any, +) -> None: + for k in kwargs: + log.warning( + "Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch", + k, + ) + + if accuracy is True: + accuracy = "accuracy" + elif accuracy is False: + accuracy = "" + + parser = argparse.ArgumentParser( + description=f"""\ +An after_dynamo repro script, typically triggering a bug in Dynamo or +AOTAutograd. When run with no arguments, this script defaults to running +'{command}'. Extra flags may be available; to find out more, try '{command} +--help'. There are also alternate subcommands available, see below. + +default settings on this script: + {accuracy=} + {save_dir=} +""", + formatter_class=argparse.RawTextHelpFormatter, + ) + + def common_flags(parser: argparse.ArgumentParser) -> None: + accuracy_group = parser.add_mutually_exclusive_group() + accuracy_group.add_argument( + "--no-accuracy", + dest="accuracy", + action="store_const", + const="", + default=accuracy, + help="do not test accuracy, just run the module and see if it errors", + ) + accuracy_group.add_argument( + "--accuracy", + action="store_const", + const="accuracy", + default=accuracy, + help="test accuracy", + ) + parser.add_argument( + "--save-dir", + type=str, + default=save_dir, + metavar="DIR", + help="directory where saved inputs live", + ) + parser.add_argument( + "--no-save-dir", + dest="save_dir", + action="store_const", + const=None, + help="don't use any directory for saved inputs", + ) + parser.add_argument( + "--no-isolate", + dest="isolate", + action="store_false", + default=False, + help="no isolate (doesn't do anything for after_dynamo)", + ) + parser.add_argument( + "--autocast", + default=autocast, + action="store_true", + help="use torch.amp.autocast", + ) + parser.add_argument( + "--no-autocast", + dest="autocast", + action="store_false", + help="don't use torch.amp.autocast", + ) + parser.add_argument( + "--backend", + type=str, + default=backend, + metavar="BACKEND", + help="torch.compile backend to use", + ) + + subparsers = parser.add_subparsers( + dest="command", metavar="{run,minify}", required=True + ) + + parser_run = subparsers.add_parser( + "run", + help="just run the repro", + ) + common_flags(parser_run) + parser_run.add_argument( + "--only-fwd", + action="store_true", + help="don't run backwards compilation for testing", + ) + + parser_minify = subparsers.add_parser( + "minify", help="run the minifier on the repro" + ) + common_flags(parser_minify) + + args = None + if len(sys.argv) <= 1: + args = [command, *sys.argv[1:]] + + options = cast(ReproOptions, parser.parse_args(args)) + COMMAND_FNS = { + "minify": repro_minify, + "run": repro_run, + } + COMMAND_FNS[options.command](options, mod, load_args) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/aoti.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/aoti.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab8b76e82585ffef7a79ccc19b32171aa3df132 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/aoti.py @@ -0,0 +1,669 @@ +""" +Utilities for debugging and reproducing issues in Ahead of Time with Inductor (AOTI) compilation. + +This file provides tools and utilities for: +- Generating minimal reproducible test cases (minification) +- Handling exported programs and graph modules +- Creating debug repros for AOTI compilation issues +- Supporting both accuracy testing and error reproduction +- Managing configuration and environment for repro cases + +The main components include: +- Minification tools to reduce test cases while preserving errors +- Repro generation utilities for exported programs +- Error handling specific to AOTI compilation +- Command-line interface for running and managing repros +""" + +import argparse +import functools +import io +import logging +import os +import re +import shutil +import sys +import textwrap +from collections.abc import Sequence +from importlib import import_module +from typing import Any, IO + +import torch +from torch._dynamo.debug_utils import ( + _cuda_system_info_comment, + BuckTargetWriter, + extra_imports, + generate_config_string, + generate_env_vars_string, + helper_for_dump_minify, + InputReader, + minifier_dir, + NNModuleToString, + NopInputReader, +) +from torch.export import ExportedProgram +from torch.hub import tqdm + + +log = logging.getLogger(__name__) + + +inductor_config = import_module("torch._inductor.config") +use_buck = inductor_config.is_fbcode() + + +class AOTIMinifierError(Exception): + def __init__(self, original_exception: str | Exception) -> None: + additional_message = "This error is caused by a bug in the AOTI minifier, please report a bug to PyTorch" + full_message = f"{additional_message}: {str(original_exception)}" + super().__init__(full_message) + self.original_exception = original_exception + + +def dump_to_minify( + exported_program: ExportedProgram, + compiler_name: str, + command: str = "minify", + options: dict[str, Any] | None = None, +) -> None: + """ + If command is "minify": + Dump exported_program to `debug_dir/minifier/minifier_launcher.py`, with minify command. + If command is "run": + Dump exported_program to `cwd/repro.py`, with run command. + """ + if command not in ["minify", "run"]: + raise AssertionError(f"command must be 'minify' or 'run', got {command!r}") + + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + + if command == "minify": + out = io.StringIO() + save_graph_repro_ep( + out, + compiler_name, + exported_program=exported_program, + save_dir=subdir, + command="minify", + config_patches=options, + ) + return helper_for_dump_minify(out.getvalue()) + else: + curdir = os.getcwd() + file_name = os.path.join(curdir, "repro.py") + try: + with open(file_name, "w") as fd: + save_graph_repro_ep( + fd, + compiler_name, + exported_program=exported_program, + config_patches=options, + save_dir=subdir, + command="run", + module_in_comment=True, + ) + log.warning("Writing repro file to %s", file_name) + if use_buck: + BuckTargetWriter(file_name).write() + except OSError: + log.warning("No write permissions for %s", file_name) + + +def get_module_string(gm: torch.fx.GraphModule) -> str: + def _convert_to_comment(s_: str) -> str: + s = s_.split("\n") + if len(s) == 1: + return "# " + s_ + first = s.pop(0) + for i in range(len(s)): + line = s[i] + if line.strip() != "": + s[i] = "# " + line + else: + s[i] = "" + s = "\n".join(s) + s = first + "\n" + s + return s + + module_string = NNModuleToString.convert(gm, allow_unsafe_repr=True) + return _convert_to_comment(module_string) + + +def save_graph_repro_ep( + fd: IO[Any], + compiler_name: str, + *, + exported_program: ExportedProgram | None = None, + gm: torch.nn.Module | None = None, + args: tuple[Any] | None = None, + config_patches: dict[str, str] | None = None, + stable_output: bool = False, + save_dir: str | None = None, + command: str = "run", + accuracy: str | bool | None = None, + check_str: str | None = None, + module_in_comment: bool = False, + strict: bool = False, +) -> None: + # Save graph for reproducing the error. + # Either exported_program or gm will be saved, depending on which one is defined. + # Only one of exported_program and gm should be defined. + + if exported_program is None and gm is None: + raise AOTIMinifierError("One of exported_program and gm must be defined") + if exported_program is not None and gm is not None: + raise AOTIMinifierError("Only one of exported_program and gm can be defined") + if gm is not None and args is None: + raise AOTIMinifierError("If gm is defined, args should also be defined") + + if exported_program is None: + if gm is None: + raise AssertionError("gm must not be None when exported_program is None") + if args is None: + raise AssertionError("args must not be None when exported_program is None") + exported_program = torch.export.export(gm, args, strict=strict) + elif gm is None: + gm = exported_program.module(check_guards=False) + + # save a graph preview using gm + module_string = get_module_string(gm) # type: ignore[arg-type] + fd.write(module_string) + + # save a graph repro using exported_program + fd.write( + generate_compiler_repro_exported_program( + exported_program, + options=config_patches, + stable_output=stable_output, + save_dir=save_dir, + ) + ) + if accuracy is None: + accuracy = "_accuracy" in compiler_name + fd.write("if __name__ == '__main__':\n") + fd.write(" from torch._dynamo.repro.aoti import run_repro\n") + fd.write( + f" with torch.no_grad():\n" + f" run_repro(exported_program, config_patches=config_patches, accuracy={accuracy!r}, command={command!r}, " + f"save_dir={save_dir!r}, check_str={check_str!r})\n" + ) + + +def dump_compiler_graph_state( + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str, + *, + config_patches: dict[str, str] | None = None, + accuracy: str | bool | None = None, + strict: bool = False, +) -> None: + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + file_name = os.path.join(subdir, f"{len(gm.graph.nodes)}.py") + log.warning( + "Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name + ) + with open(file_name, "w") as fd: + save_graph_repro_ep( + fd, + compiler_name, + gm=gm, + args=tuple(args), + config_patches=config_patches, + save_dir=subdir, + accuracy=accuracy, + module_in_comment=True, + strict=strict, + ) + curdir = os.getcwd() + repro_path = os.path.join(curdir, "repro.py") + try: + shutil.copyfile(file_name, repro_path) + log.warning("Copying repro file for convenience to %s", repro_path) + if use_buck: + BuckTargetWriter(file_name).write() + except OSError: + log.warning("No write permissions for %s", repro_path) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# DUMP REPROS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def generate_compiler_repro_exported_program( + exported_program: ExportedProgram, + *, + options: dict[str, str] | None = None, + stable_output: bool = False, + save_dir: str | None = None, +) -> str: + model_str = textwrap.dedent( + f""" +{generate_env_vars_string(stable_output=stable_output)} +import torch +import torch._inductor.inductor_prims + +{generate_config_string(stable_output=stable_output)} + +isolate_fails_code_str = None + +{extra_imports} + + """ + ) + if not stable_output: + model_str += f"# torch version: {torch.version.__version__}\n" + if hasattr(torch.version, "cuda"): + model_str += f"# torch cuda version: {torch.version.cuda}\n" + if hasattr(torch.version, "git_version"): + model_str += f"# torch git version: {torch.version.git_version}\n\n\n" + model_str += _cuda_system_info_comment() + if save_dir: + ep_path = os.path.join(save_dir, "exported_program.pt2") + else: + ep_path = "exported_program.pt2" + torch.export.save(exported_program, ep_path) + + model_str += f"exported_program = torch.export.load('{ep_path}')\n" + model_str += "# print(exported_program.graph)\n" + model_str += f"config_patches={options}\n" + return model_str + + +def repro_load_args(load_args: Any, save_dir: str | None) -> tuple[Any]: + if not hasattr(load_args, "_version"): + log.warning( + "load_args does not have a _version attribute, please file a bug to PyTorch " + "and describe how you generate this repro script" + ) + else: + if load_args._version > 0: + log.warning( + "load_args is version %s, but this version of PyTorch only supports " + "version 0. We will try to run it anyway but there may be an incompatibility; " + "if so, try upgrading your version of PyTorch.", + load_args._version, + ) + + nop_reader = NopInputReader() + load_args(nop_reader) + + with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar: + input_reader = InputReader(save_dir=save_dir, pbar=pbar) + load_args(input_reader) + args = input_reader.args + + return tuple(args) + + +def repro_common( + options: Any, exported_program: ExportedProgram +) -> tuple[torch.fx.GraphModule, Any, Any]: + # pyrefly: ignore [bad-assignment] + torch._inductor.config.generate_intermediate_hooks = True + mod = exported_program.module(check_guards=False) + args, kwargs = exported_program.example_inputs + return mod, args, kwargs # type: ignore[return-value] + + +def repro_get_args( + options: Any, + exported_program: ExportedProgram, + config_patches: dict[str, Any] | None, +) -> tuple[torch.fx.GraphModule, Any, Any]: + mod, args, kwargs = repro_common(options, exported_program) + return mod, args, kwargs + + +def repro_run( + options: Any, + exported_program: ExportedProgram, + config_patches: dict[str, Any] | None, +) -> None: + from torch._inductor import _aoti_compile_and_package_inner + + gm, args, kwargs = repro_common(options, exported_program) + + from torch.cuda import synchronize + + _aoti_compile_and_package_inner( + gm, + args, + kwargs, + load_and_run=True, + check_accuracy=options.accuracy, + inductor_configs=config_patches, + ) + + need_sync = False + + for arg in args: + if isinstance(arg, torch.Tensor) and arg.is_cuda: + need_sync = True + break + + if need_sync: + synchronize() # ensure segfaults are surfaced + + +def export_for_aoti_minifier( + gm: torch.nn.Module, + tuple_inputs: tuple[Any], + strict: bool = False, + skip_export_error: bool = True, +) -> torch.nn.Module | None: + # Some graphs cannot be used for AOTI/export (illegal graphs), these should be + # considered as graphs that don't fail in the minifier, so the minifier keeps searching. + # In these cases, we return None. Otherwise, we return the exported graph module. + # This won't affect the minifier result because the minifier is only responsible for catching + # errors in AOTI, not export. + # + # Please add to this list of illegal graphs if you change the implementation here. + # - graph output is not allowed by export + # + # If skip_export_error=True, then the errors in export will not be raised, and the minifier + # will keep exploring and ignore this graph. + from torch._dynamo.exc import UserError, UserErrorType + + try: + ep = torch.export.export(gm, tuple_inputs, strict=strict) + gm = ep.module(check_guards=False) + return gm + except Exception as e: + if skip_export_error: + return None + if isinstance(e, UserError) and e.error_type == UserErrorType.INVALID_OUTPUT: + # graph output is not allowed by export when strict=True + return None + if isinstance(e, RuntimeError): + # graph output is not allowed by export when strict=False + pattern = r"Found .* in output, which is not a known type\." + if re.search(pattern, str(e)) is not None: + return None + raise AOTIMinifierError(e) from e + # we should never reach here + # pyrefly: ignore [unreachable] + return None + + +def repro_minify( + options: Any, + exported_program: ExportedProgram, + config_patches: dict[str, Any] | None, +) -> None: + from functorch.compile import minifier + from torch._inductor import _aoti_compile_and_package_inner + from torch._inductor.compile_fx import _aoti_flatten_inputs + + mod, args, kwargs = repro_common(options, exported_program) + + # update serialized_in_spec and serialized_out_spec + flat_example_inputs, inductor_configs = _aoti_flatten_inputs( + mod, args, kwargs, options=config_patches + ) + compiler_name = "aot_inductor" + if options.minifier_export_mode not in ["dynamo", "python"]: + raise AssertionError( + f"minifier_export_mode must be 'dynamo' or 'python', got {options.minifier_export_mode!r}" + ) + strict = options.minifier_export_mode == "dynamo" + skip_export_error = options.skip_export_error + + from torch.cuda import synchronize + + need_sync = False + + for arg in args: + if isinstance(arg, torch.Tensor) and arg.is_cuda: + need_sync = True + break + + def module_fails( + gm: torch.fx.GraphModule, + flat_example_inputs: list[Any], + check_str: str | None = None, + ) -> bool: + # Need to export first so the in_spec and out_spec are populated + tuple_inputs = tuple(flat_example_inputs) + # pyrefly: ignore [bad-assignment] + gm = export_for_aoti_minifier( + gm, tuple_inputs, strict=strict, skip_export_error=skip_export_error + ) + + # Some graphs cannot be used for AOTI/export (illegal graphs), these should be + # considered as graphs that don't fail in the minifier, so the minifier keeps searching. + if gm is None: + return False + + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"Expected torch.fx.GraphModule, got {type(gm)}") + + try: + _aoti_compile_and_package_inner( + gm, + tuple_inputs, + load_and_run=True, + check_accuracy=options.accuracy, + inductor_configs=inductor_configs, + ) + if need_sync: + synchronize() # ensure segfaults are surfaced + return False + except Exception as e: + if check_str is not None and check_str not in repr(e): + return False + return True + + minifier( + mod, + flat_example_inputs, + module_fails=functools.partial(module_fails, check_str=options.check_str), + dump_state=functools.partial( + dump_compiler_graph_state, + compiler_name=compiler_name, + config_patches=config_patches, + accuracy=options.accuracy, + strict=strict, + ), + save_dir=options.save_dir, + offload_to_disk=options.offload_to_disk, + skip_offload=options.skip_saving_eager_intermediates, + skip_sanity=options.skip_sanity, + max_granularity=options.max_granularity, + ) + + +def run_repro( + exported_program: ExportedProgram, + *, + config_patches: dict[str, str] | None = None, + command: str = "run", + accuracy: bool | str = "", + save_dir: str | None = None, + tracing_mode: str | None = None, + check_str: str | None = None, + minifier_export_mode: str = "python", + skip_export_error: bool = True, + **more_kwargs: Any, +) -> Any: + for k in more_kwargs: + log.warning( + "Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch", + k, + ) + + if accuracy is True: + accuracy = "accuracy" + elif accuracy is False: + accuracy = "" + + parser = argparse.ArgumentParser( + description=f"""\ +An AOTI repro script, typically triggering a bug in PyTorch AOTInductor. +When run with no arguments, this script defaults to running '{command}'. +Extra flags may be available; to find out more, try '{command} --help'. +There are also alternate subcommands available, see below. + +default settings on this script: + {accuracy=} + {tracing_mode=} + {save_dir=} + {check_str=} +""", + formatter_class=argparse.RawTextHelpFormatter, + ) + + def common_flags(parser: argparse.ArgumentParser) -> None: + accuracy_group = parser.add_mutually_exclusive_group() + accuracy_group.add_argument( + "--no-accuracy", + dest="accuracy", + action="store_const", + const="", + default=accuracy, + help="do not test accuracy, just run the module and see if it errors", + ) + accuracy_group.add_argument( + "--accuracy", + action="store_const", + const="accuracy", + default=accuracy, + help="""\ +test if the RMSE between the compiled module and the fp64 reference is greater +than eager and the fp64 reference. This is usually more reliable than the +standard allclose test, as we expect numeric differences from compiling, often +improving accuracy over eager. RMSE test allows for compiled module to +diverge greatly from eager, as long as this divergence moves it closer to the +'true' mathematical value of the network. Caveats: (1) double precision can +still suffer from rounding error, so it is not a perfect reference (see for +example 'Herbie: Automatically Improving Floating Point Accuracy') for +approaches that detect the necessary working precision and compute it in +arbitrary precision floating point; unfortunately, this is not practical for +tensor computation; (2) if there are not enough samples in the output being +compared, we may get unlucky and have an unlucky greater RMSE than eager; this +could be overcome by applying a more rigorous statistical test at some +p-value, which we leave for future work. +""", + ) + accuracy_group.add_argument( + "--strict-accuracy", + dest="accuracy", + action="store_const", + const="strict_accuracy", + default=accuracy, + help="""\ +by default, when doing accuracy minification we will reject reductions which +change the divergence from a floating point divergence to a integral/boolean +divergence. This is because some operations like ReLU involve temporarily +sharp boundaries that smooth out again afterwards; without requiring +divergence on floating point, the minifier will often fixate on divergent +boolean tensor even though this is not the true source of the divergence. +However, rejecting these reductions makes it more difficult for the minifier +to make process. Using this option will let the minifier progress for ALL +divergences--you just might not end up with a useful repro in the end.""", + ) + + parser.add_argument( + "--save-dir", + type=str, + default=save_dir, + metavar="DIR", + help="directory where saved inputs live", + ) + parser.add_argument( + "--no-save-dir", + dest="save_dir", + action="store_const", + const=None, + help="don't use any directory for saved inputs", + ) + + subparsers = parser.add_subparsers( + dest="command", metavar="{run,minify}", required=True + ) + + parser_run = subparsers.add_parser( + "run", + help="just run the repro", + ) + common_flags(parser_run) + + parser_minify = subparsers.add_parser( + "minify", help="run the minifier on the repro" + ) + common_flags(parser_minify) + parser_get_args = subparsers.add_parser("get_args", help="get the args") + common_flags(parser_get_args) + parser_minify.add_argument( + "--skip-saving-eager-intermediates", + action="store_true", + help="skip saving eager intermediates on --minify", + ) + parser_minify.add_argument( + "--offload-to-disk", + action="store_true", + help="during minification, offload delta debugging intermediates to disk. Use if you're OOMing", + ) + parser_minify.add_argument( + "--skip-sanity", + action="store_true", + help="skip sanity check at beginning of minification on original graph", + ) + parser_minify.add_argument( + "--max-granularity", + type=int, + default=None, + help="start at this granularity and work down; must be power of 2", + ) + parser_minify.add_argument( + "--check-str", + type=str, + default=check_str, + help="require minified program to fail with error containing this string", + ) + parser_minify.add_argument( + "--minifier-export-mode", + type=str, + default=minifier_export_mode, + help=( + "The export mode used in minifier, either dynamo or python." + "`dynamo` corresponds to strict=True, and `python` corresponds to strict=False." + ), + ) + parser_minify.add_argument( + "--skip-export-error", + type=bool, + default=skip_export_error, + help="Skip intermediate graphs that cannot be exported.", + ) + + # Run the repro in the context of minification, inverting exit code meaning + parser_minifier_query = subparsers.add_parser( + "minifier-query", + ) + common_flags(parser_minifier_query) + parser_minifier_query.add_argument( + "--check-str", + type=str, + default=check_str, + help="require minified program to fail with error containing this string", + ) + + args = None + if len(sys.argv) <= 1: + args = [command, *sys.argv[1:]] + + options = parser.parse_args(args) + COMMAND_FNS = { + "minify": repro_minify, + "run": repro_run, + "get_args": repro_get_args, + } + return COMMAND_FNS[options.command]( + options, exported_program, config_patches=config_patches + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/resume_execution.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/resume_execution.py new file mode 100644 index 0000000000000000000000000000000000000000..2cbcda514b2d36088b16dda4ca8ea2cf9255d8c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/resume_execution.py @@ -0,0 +1,784 @@ +""" +This module provides functionality for resuming Python execution at specific points in code, +primarily used by PyTorch Dynamo for control flow handling and optimization. It implements +bytecode transformation and execution state management to enable: + +- Resuming execution at arbitrary points in Python bytecode +- Managing context managers and their state across execution boundaries +- Transforming and generating new code objects with preserved execution state +- Supporting Python 3.11+ exception handling and block management +- Restoring torch function mode stacks and other execution context + +The module is critical for PyTorch Dynamo's ability to optimize code while preserving +Python semantics and execution state. +""" + +from __future__ import annotations + +import copy +import dataclasses +import sys +from typing import Any, cast, TYPE_CHECKING + +from .bytecode_transformation import ( + add_push_null, + bytecode_from_template, + create_binary_subscr, + create_call_function, + create_call_function_ex, + create_instruction, + create_jump_absolute, + create_load_const, + Instruction, + overwrite_instruction, + transform_code_object, + unique_id, +) +from .utils import ExactWeakKeyDictionary + + +if TYPE_CHECKING: + import types + from collections.abc import Callable, Iterable + from contextlib import AbstractContextManager + + from .output_graph import CodeOptions + + +# taken from code.h in cpython +CO_OPTIMIZED = 0x0001 +CO_NEWLOCALS = 0x0002 +CO_VARARGS = 0x0004 +CO_VARKEYWORDS = 0x0008 +CO_NESTED = 0x0010 +CO_GENERATOR = 0x0020 +CO_NOFREE = 0x0040 +CO_COROUTINE = 0x0080 +CO_ITERABLE_COROUTINE = 0x0100 +CO_ASYNC_GENERATOR = 0x0200 + +# trace_rules.py import this constant for consistency +TORCH_DYNAMO_RESUME_IN_PREFIX = "torch_dynamo_resume_in" +IS_TRACING_RESUME_PROLOGUE_VARNAME = "__is_tracing_resume_prologue" + + +# If is_resume - this codegen is for a resume function +def _initial_push_null(insts: list[Instruction]) -> None: + if sys.version_info >= (3, 11): + insts.append(create_instruction("PUSH_NULL")) + if sys.version_info < (3, 13): + insts.append(create_instruction("SWAP", arg=2)) + + +# Generates bytecode from template and splits the code where LOAD_FAST dummy is present. +def _bytecode_from_template_with_split( + template: Callable[..., Any], + stack_index: int, + varname_map: dict[str, Any] | None = None, +) -> tuple[list[Instruction], list[Instruction]]: + template_code = bytecode_from_template(template, varname_map=varname_map) + template_code.append(create_instruction("POP_TOP")) + + # adjust exception table entry depth + for inst in template_code: + if inst.exn_tab_entry: + inst.exn_tab_entry.depth += stack_index + + # search for LOAD_FAST dummy and replace it with 2 NOPs (we can break up the bytecode between them) + dummy_idx, dummy_inst = next( + ( + (i, inst) + for i, inst in enumerate(template_code) + if inst.opname in ("LOAD_FAST", "LOAD_FAST_BORROW") + and inst.argval == "dummy" + ), + (None, None), + ) + if dummy_idx is None: + raise AssertionError("LOAD_FAST dummy instruction not found in template code") + if dummy_inst is None: + raise AssertionError("LOAD_FAST dummy instruction instance is None") + + # replace LOAD_FAST dummy with first NOP marking exception area + overwrite_instruction(dummy_inst, [create_instruction("NOP")]) + + # POP_TOP follows LOAD_FAST dummy - replace with NOP marking end of exception area + if template_code[dummy_idx + 1].opname != "POP_TOP": + raise AssertionError( + f"Expected POP_TOP after LOAD_FAST dummy, got {template_code[dummy_idx + 1].opname}" + ) + overwrite_instruction(template_code[dummy_idx + 1], [create_instruction("NOP")]) + + return template_code[: dummy_idx + 1], template_code[dummy_idx + 1 :] + + +def _try_except_tf_mode_template(dummy: Any) -> None: + # NOTE: Make sure this name matches what is generated by symbolic_convert:import_source + # on torch._dynamo.utils. + # pyrefly: ignore [unknown-name] + global __import_torch_dot__dynamo_dot_utils + try: + dummy + except: + __import_torch_dot__dynamo_dot_utils._pop_torch_function_stack() # type: ignore[name-defined] + raise + + +@dataclasses.dataclass(frozen=True) +class ReenterWith: + stack_index: int + target_values: tuple[Any, ...] | None = None + + def try_except_torch_function_mode( + self, code_options: CodeOptions, cleanup: list[Instruction] + ) -> list[Instruction]: + """ + Codegen based off of: + try: + (rest) + except: + (pop the torch function mode that was pushed for this context) + raise + """ + setup_try_except, epilogue = _bytecode_from_template_with_split( + _try_except_tf_mode_template, + self.stack_index, + ) + cleanup[:] = epilogue + cleanup + + return setup_try_except + + # If we do not want to destroy the stack, we can do the same thing as a + # `SETUP_WITH` block, only that we store the context manager in a local_symbol + def try_finally( + self, code_options: CodeOptions, cleanup: list[Instruction] + ) -> list[Instruction]: + """ + Codegen based off of: + load args + enter context + try: + (rest) + finally: + exit context + """ + # NOTE: we assume that TOS is a context manager CLASS! + # pyrefly: ignore [implicit-any] + load_args = [] + if self.target_values: + load_args = [create_load_const(val) for val in self.target_values] + ctx_name = unique_id(f"___context_manager_{self.stack_index}") + if ctx_name not in code_options["co_varnames"]: + code_options["co_varnames"] += (ctx_name,) + for name in ["__enter__", "__exit__"]: + if name not in code_options["co_names"]: + code_options["co_names"] += (name,) + + create_ctx: list[Instruction] = [] + _initial_push_null(create_ctx) + create_ctx.extend( + [ + *load_args, + *create_call_function(len(load_args), False), + create_instruction("STORE_FAST", argval=ctx_name), + ] + ) + + def _template(ctx: AbstractContextManager[Any], dummy: Any) -> None: + ctx.__enter__() + try: + dummy + finally: + ctx.__exit__(None, None, None) + + setup_try_finally, epilogue = _bytecode_from_template_with_split( + _template, self.stack_index, varname_map={"ctx": ctx_name} + ) + cleanup[:] = epilogue + cleanup + return create_ctx + setup_try_finally + + def __call__( + self, code_options: dict[str, Any], cleanup: list[Instruction] + ) -> tuple[list[Instruction], Instruction | None]: + """ + Codegen based off of: + with ctx(args): + (rest) + """ + # NOTE: we assume that TOS is a context manager CLASS! + # pyrefly: ignore [implicit-any] + load_args = [] + if self.target_values: + load_args = [create_load_const(val) for val in self.target_values] + + create_ctx: list[Instruction] = [] + # Do not push NULL in Python 3.14+ since the NULL should be on the symbolic stack. + if sys.version_info < (3, 14): + _initial_push_null(create_ctx) + create_ctx.extend( + [ + *load_args, + *create_call_function(len(load_args), False), + ] + ) + + def _template(ctx: AbstractContextManager[Any], dummy: Any) -> None: + with ctx: + dummy + + setup_with, epilogue = _bytecode_from_template_with_split( + _template, self.stack_index + ) + cleanup[:] = epilogue + cleanup + + load_fast_ctx_inst = next( + ( + inst + for inst in setup_with + if inst.opname in ("LOAD_FAST", "LOAD_FAST_BORROW") + and inst.argval == "ctx" + ), + None, + ) + if load_fast_ctx_inst is None: + raise AssertionError("LOAD_FAST ctx instruction not found in setup_with") + # ctx already loaded on stack before the template - no need to LOAD_FAST + overwrite_instruction(load_fast_ctx_inst, [create_instruction("NOP")]) + + # 3.11+ only + push_exc_info_gen = ( + inst for inst in epilogue if inst.opname == "PUSH_EXC_INFO" + ) + push_exc_info_inst = next(push_exc_info_gen, None) + # expect only 1 PUSH_EXC_INFO in epilogue + if next(push_exc_info_gen, None) is not None: + raise AssertionError("Expected only 1 PUSH_EXC_INFO in epilogue") + + return create_ctx + setup_with, push_exc_info_inst + + +@dataclasses.dataclass +class ResumeFunctionMetadata: + code: types.CodeType + instructions: list[Instruction] = dataclasses.field(default_factory=list) + # Python 3.11+ fields + # NOTE: Python 3.11 removed blocks, but for our purposes, a "block" consists + # of instructions of all exception table entries that have the same target. + + # map from PUSH_EXC_INFO's in the prefix to original block target offset + prefix_block_target_offset_remap: list[int] = dataclasses.field( + default_factory=list + ) + # per-offset map from new block target offsets to original block target offsets + block_target_offset_remap: dict[tuple[int, int], dict[int, int]] = ( + dataclasses.field(default_factory=dict) + ) + + +def _filter_iter( + l1: Iterable[Any], + l2: Iterable[Any], + cond: Callable[[Any, Any], bool], +) -> list[Any]: + """ + Two-pointer conditional filter. + e.g. _filter_iter(insts, sorted_offsets, lambda i, o: i.offset == o) + returns the instructions with offsets in sorted_offsets + """ + it = iter(l2) + res: list[Instruction] = [] + try: + cur = next(it) + for val in l1: + if cond(val, cur): + res.append(val) + cur = next(it) + except StopIteration: + pass + return res + + +def _load_tuple_and_call(tup: tuple[Any, ...]) -> list[Instruction]: + insts: list[Instruction] = [] + _initial_push_null(insts) + insts.extend(create_load_const(val) for val in tup) + insts.extend(create_call_function(len(tup), False)) + return insts + + +class ContinueExecutionCache: + cache = ExactWeakKeyDictionary() + generated_code_metadata = ExactWeakKeyDictionary() + + @classmethod + def lookup( + cls, code: types.CodeType, lineno: int, init_offset: int, *key: Any + ) -> types.CodeType: + if code not in cls.cache: + cls.cache[code] = {} + key = tuple(key) + if key not in cls.cache[code]: + cls.cache[code][key] = cls.generate(code, lineno, init_offset, *key) + return cls.cache[code][key] + + @classmethod + def generate( + cls, + code: types.CodeType, + lineno: int, + init_offset: int, + resume_offset: int, + setup_fn_target_offsets: tuple[int, ...], # only used in Python 3.11+ + nstack: int, + argnames: tuple[str, ...], + argnames_null: tuple[str, ...], + setup_fns: tuple[ReenterWith, ...], + handle_inactive_ctx: bool, + stack_ctx_vars: tuple[tuple[int, tuple[Any, ...]], ...], + argnames_ctx_vars: tuple[tuple[str, tuple[Any, ...]], ...], + null_idxes: tuple[int, ...], + # mainly used to ensure distinct code objects per stack trace, + # which prevents excessive recompilation of inner frames + nested_code_objs: tuple[types.CodeType], + # Are we currently graph breaking on an instruction that doesn't push + # its result to the stack? If so, and we are not the leaf resume, then we need to pop + # the result of calling the next resume function. + pop_nested_resume_result: bool, + ) -> types.CodeType: + if resume_offset is None: + raise AssertionError("resume_offset must not be None") + if code.co_flags & ( + CO_GENERATOR | CO_COROUTINE | CO_ITERABLE_COROUTINE | CO_ASYNC_GENERATOR + ): + raise AssertionError( + "Cannot generate resume function for generator, coroutine, or async generator" + ) + if not (code.co_flags & CO_OPTIMIZED): + raise AssertionError("Code object must have CO_OPTIMIZED flag set") + if code in ContinueExecutionCache.generated_code_metadata: + return cls.generate_based_on_original_code_object( + code, + lineno, + init_offset, + resume_offset, + setup_fn_target_offsets, + nstack, + argnames, + argnames_null, + setup_fns, + handle_inactive_ctx, + stack_ctx_vars, + argnames_ctx_vars, + null_idxes, + nested_code_objs, + pop_nested_resume_result, + ) + + is_py311_plus = sys.version_info >= (3, 11) + meta = ResumeFunctionMetadata(code) + + def update( + instructions: list[Instruction], code_options: dict[str, Any] + ) -> None: + meta.instructions = copy.deepcopy(instructions) + + args = ["__nested_resume_fns", "__nested_frame_values"] + args += [f"___stack{i}" for i in range(nstack)] + args.extend(v for v in argnames if v not in args) + freevars = tuple(code_options["co_cellvars"] or []) + tuple( + code_options["co_freevars"] or [] + ) + freevars = tuple(sorted(freevars)) + code_options["co_name"] = ( + f"{TORCH_DYNAMO_RESUME_IN_PREFIX}_{code_options['co_name']}_at_{lineno}" + ) + if is_py311_plus: + qualified_path = code_options["co_qualname"].rsplit(".", maxsplit=1) + if len(qualified_path) == 1: + code_options["co_qualname"] = code_options["co_name"] + else: + if len(qualified_path) != 2: + raise AssertionError( + f"Expected qualified path to have 2 parts, got {len(qualified_path)}" + ) + module_name, co_name = qualified_path + code_options["co_qualname"] = ( + f"{module_name}.{TORCH_DYNAMO_RESUME_IN_PREFIX}_{co_name}_at_{lineno}" + ) + code_options["co_firstlineno"] = lineno + code_options["co_cellvars"] = () + code_options["co_freevars"] = freevars + code_options["co_argcount"] = len(args) + code_options["co_posonlyargcount"] = 0 + code_options["co_kwonlyargcount"] = 0 + code_options["co_varnames"] = tuple( + args + + [v for v in argnames_null if v not in args] + + [v for v in code_options["co_varnames"] if v not in args] + + [IS_TRACING_RESUME_PROLOGUE_VARNAME] + ) + code_options["co_flags"] = code_options["co_flags"] & ~( + CO_VARARGS | CO_VARKEYWORDS + ) + target = next(i for i in instructions if i.offset == resume_offset) + + prefix = [] + if is_py311_plus: + if freevars: + prefix.append( + create_instruction("COPY_FREE_VARS", arg=len(freevars)) + ) + prefix.append(create_instruction("RESUME", arg=0)) + + # Set is_tracing_resume_prologue to prevent graph breaks. + # This doesn't really do anything at runtime, but dynamo will trace this + # and will know that we're in a resume function prologue. + prefix.extend( + [ + create_instruction("LOAD_CONST", argval=True), + create_instruction( + "STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME + ), + ] + ) + + cleanup: list[Instruction] = [] + hooks = {fn.stack_index: fn for fn in setup_fns} + hook_target_offsets = { + fn.stack_index: setup_fn_target_offsets[i] + for i, fn in enumerate(setup_fns) + } + offset_to_inst = {inst.offset: inst for inst in instructions} + # map old hook targets to new targets generated by the hook + # pyrefly: ignore [implicit-any] + old_hook_target_remap = {} + stack_i = 0 + null_i = 0 + stack_ctx_vars_d = dict(stack_ctx_vars) # type: ignore[var-annotated,arg-type] + for i in range(nstack + len(null_idxes)): + if null_i < len(null_idxes) and null_idxes[null_i] == i: + prefix.append(create_instruction("PUSH_NULL")) + null_i += 1 + else: + prefix.append( + create_instruction("LOAD_FAST", argval=f"___stack{stack_i}") + ) + if handle_inactive_ctx and stack_i in stack_ctx_vars_d: + # NOTE: we assume that current stack var is a context manager CLASS! + # Load args for context variable and construct it + prefix.extend(_load_tuple_and_call(stack_ctx_vars_d[stack_i])) + stack_i += 1 + + if i in hooks: + hook = hooks.pop(i) + hook_insts, exn_target = hook(code_options, cleanup) + prefix.extend(hook_insts) + if is_py311_plus: + hook_target_offset = hook_target_offsets.pop(i) + old_hook_target = offset_to_inst[hook_target_offset] + meta.prefix_block_target_offset_remap.append(hook_target_offset) + old_hook_target_remap[old_hook_target] = exn_target + + if is_py311_plus: + # reverse the mapping since targets of later/nested contexts are inserted + # into the mapping later, but show up earlier in the prefix. + meta.prefix_block_target_offset_remap = list( + reversed(meta.prefix_block_target_offset_remap) + ) + + if hooks: + raise AssertionError(f"Unprocessed hooks remaining: {hooks}") + + # NOTE: we assume that local var is a context manager CLASS! + # initialize inactive context vars in argnames + if handle_inactive_ctx: + for name, vals in argnames_ctx_vars: + prefix.append(create_instruction("LOAD_FAST", argval=name)) + prefix.extend(_load_tuple_and_call(vals)) + prefix.append(create_instruction("STORE_FAST", argval=name)) + + # 3.12+: store NULL into variables that were NULL + if argnames_null: + if sys.version_info < (3, 12): + raise AssertionError( + f"argnames_null requires Python 3.12+, got {sys.version_info}" + ) + for v in argnames_null: + if v in args: + raise AssertionError( + f"argnames_null variable {v!r} should not be in args" + ) + prefix.extend( + [ + create_instruction("PUSH_NULL"), + create_instruction("STORE_FAST", argval=v), + ] + ) + + # Call nested resume function + if nested_code_objs: + prefix.extend( + [ + # set up __nested_resume_fns[-1] call + *add_push_null( + [ + create_instruction( + "LOAD_FAST", argval="__nested_resume_fns" + ), + create_instruction("LOAD_CONST", argval=-1), + create_binary_subscr(), + ] + ), + # del __nested_resume_fns[-1] + create_instruction("LOAD_FAST", argval="__nested_resume_fns"), + create_instruction("LOAD_CONST", argval=-1), + create_instruction("DELETE_SUBSCR"), + # load [__nested_resume_fns, __nested_frame_values] + create_instruction("LOAD_FAST", argval="__nested_resume_fns"), + create_instruction("LOAD_FAST", argval="__nested_frame_values"), + create_instruction("BUILD_LIST", arg=2), + # load __nested_frame_values[-1] + create_instruction("LOAD_FAST", argval="__nested_frame_values"), + create_instruction("LOAD_CONST", argval=-1), + create_binary_subscr(), + # create [ + # __nested_resume_fns, + # __nested_frame_values, + # *__nested_frame_values[-1], + # ] + create_instruction("LIST_EXTEND", arg=1), + # del __nested_frame_values[-1] + create_instruction("LOAD_FAST", argval="__nested_frame_values"), + create_instruction("LOAD_CONST", argval=-1), + create_instruction("DELETE_SUBSCR"), + # delete __nested values + create_instruction("DELETE_FAST", argval="__nested_resume_fns"), + create_instruction( + "DELETE_FAST", argval="__nested_frame_values" + ), + # Set is_tracing_resume_prologue back to allow graph breaks + # in the nested resume + create_instruction("LOAD_CONST", argval=False), + create_instruction( + "STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME + ), + # finish the call + *create_call_function_ex(False, False), + ] + ) + if pop_nested_resume_result: + # pop the result of calling the nested resume function + prefix.append(create_instruction("POP_TOP")) + else: + # Set is_tracing_resume_prologue back to allow graph breaks after the jump + prefix.extend( + [ + create_instruction("LOAD_CONST", argval=False), + create_instruction( + "STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME + ), + ] + ) + + prefix.append(create_jump_absolute(target)) + + # because the line number table monotonically increases from co_firstlineno + # remove starts_line for any instructions before the graph break instruction + # this will ensure the instructions after the break have the correct line numbers + for inst in instructions: + if inst.offset == target.offset: + break + inst.starts_line = None + if sys.version_info >= (3, 11): + inst.positions = None + + if cleanup: + prefix.extend(cleanup) + prefix.extend(cls.unreachable_codes(code_options)) + + # remap original instructions' exception table entries + if old_hook_target_remap: + # pyrefly: ignore [unbound-name] + if not is_py311_plus: + raise AssertionError("old_hook_target_remap requires Python 3.11+") + for inst in instructions: + if ( + inst.exn_tab_entry + and inst.exn_tab_entry.target in old_hook_target_remap + ): + inst.exn_tab_entry.target = old_hook_target_remap[ # type: ignore[assignment] + inst.exn_tab_entry.target + ] + + # TODO(jansel): add dead code elimination here + instructions[:] = prefix + instructions + + new_code, _ = transform_code_object(code, update) + ContinueExecutionCache.generated_code_metadata[new_code] = meta + return new_code + + @staticmethod + def unreachable_codes(code_options: dict[str, Any]) -> list[Instruction]: + """Codegen a `raise None` to make analysis work for unreachable code""" + return [ + create_load_const(None), + create_instruction("RAISE_VARARGS", arg=1), + ] + + @classmethod + def generate_based_on_original_code_object( + cls, + code: types.CodeType, + lineno: int, + init_offset: int, + resume_offset: int, + setup_fn_target_offsets: tuple[int, ...], + *args: Any, + ) -> types.CodeType: + """ + This handles the case of generating a resume into code generated + to resume something else. We want to always generate starting + from the original code object so that if control flow paths + converge we only generated 1 resume function (rather than 2^n + resume functions). + """ + + meta: ResumeFunctionMetadata = ContinueExecutionCache.generated_code_metadata[ + code + ] + + def find_orig_offset(cur_offset: int) -> int: + orig_offset = -1 + + def find_orig_offset_transform( + instructions: list[Instruction], code_options: dict[str, Any] + ) -> None: + nonlocal orig_offset + (target,) = (i for i in instructions if i.offset == cur_offset) + # match the functions starting at the last instruction as we have added a prefix + new_target_tuple = tuple( + i2 + for i1, i2 in zip( + reversed(instructions), reversed(meta.instructions) + ) + if i1 is target + ) + + if not new_target_tuple: + # Instruction with cur_offset in instructions was not found + # in the original code - orig_offset left as -1. + # Caller expected to handle this case. + return + + if len(new_target_tuple) != 1: + raise AssertionError( + f"Expected exactly 1 matching target, got {len(new_target_tuple)}" + ) + new_target = new_target_tuple[0] + + if target.opcode != new_target.opcode: + raise AssertionError( + f"Opcode mismatch: target has {target.opcode}, " + f"new_target has {new_target.opcode}" + ) + if new_target.offset is None: + raise AssertionError("new_target.offset must not be None") + orig_offset = new_target.offset + + transform_code_object(code, find_orig_offset_transform) + return orig_offset + + orig_init_offset = find_orig_offset(init_offset) + # It is fine if the initial instruction is not found in the original code; + # this means we graph broke in the prefix, which only happens with nested graph breaks. + # We should not be running into ambiguous graph break issues here. + orig_resume_offset = find_orig_offset(resume_offset) + if orig_resume_offset <= -1: + raise AssertionError( + "resume instruction not found in original code - this is a bug." + ) + + if sys.version_info >= (3, 11): + # setup_fn_target_offsets currently contains the target offset of + # each setup_fn, based on `code`. When we codegen the resume function + # based on the original code object, `meta.code`, the offsets in + # setup_fn_target_offsets must be based on `meta.code` instead. + offset_key = (orig_init_offset, orig_resume_offset) + # NOTE: we key by offset_key since the same resume function may graph + # break in multiple places and we need different block_target_offset_remap's + # for each graph break location. Keying by orig_resume_offset may not be enough + # if 2 graph breaks on different initial offsets resume on the same instruction + # (although this is rare and not tested anywhere). + if offset_key not in meta.block_target_offset_remap: + block_target_offset_remap = meta.block_target_offset_remap[ + offset_key + # pyrefly: ignore [implicit-any] + ] = {} + + def remap_block_offsets( + instructions: list[Instruction], code_options: dict[str, Any] + ) -> None: + # NOTE: each prefix block generates exactly one PUSH_EXC_INFO, + # so we can tell which block a prefix PUSH_EXC_INFO belongs to, + # by counting. Then we can use meta.prefix_block_target_offset_remap + # to determine where in the original code the PUSH_EXC_INFO offset + # replaced. + prefix_blocks: list[Instruction] = [] + for inst in instructions: + # NOTE meta.prefix_block_target_offset_remap is based off of how we codegen'd + # context managers at the prefix/prologue of the resume function. It is the same for + # every graph break in the same resume function, so we do not need to recompute + # for each graph break (unlike for meta.block_target_offset_remap) + if len(prefix_blocks) == len( + meta.prefix_block_target_offset_remap + ): + break + if inst.opname == "PUSH_EXC_INFO": + prefix_blocks.append(inst) + + # remap block target offsets for blocks generated in the resume prefix + for inst, o in zip( + prefix_blocks, meta.prefix_block_target_offset_remap + ): + block_target_offset_remap[cast(int, inst.offset)] = o + + # current bytecode targets are after the prefix PUSH_EXC_INFO's + cur_start_offset = ( + cast(int, prefix_blocks[-1].offset) if prefix_blocks else -1 + ) + # get the remaining block target offsets of the current bytecode + cur_inst_offsets = sorted( + n for n in setup_fn_target_offsets if n > cur_start_offset + ) + targets = _filter_iter( + instructions, cur_inst_offsets, lambda inst, o: inst.offset == o + ) + # The original code and resume code should have matching suffixes. + # Match the post-prefix block target offsets of the current resume code + # and the original code. + orig_targets = reversed( + _filter_iter( + zip(reversed(instructions), reversed(meta.instructions)), + reversed(targets), + lambda v1, v2: v1[0] is v2, + ) + ) + for orig, cur in zip(orig_targets, targets): + block_target_offset_remap[cur.offset] = orig[1].offset + + transform_code_object(code, remap_block_offsets) + + # if offset_key or offset is not in setup_fn_target_offsets, it is an error + # that needs to be fixed + setup_fn_target_offsets = tuple( + meta.block_target_offset_remap[offset_key][n] + for n in setup_fn_target_offsets + ) + return ContinueExecutionCache.lookup( + meta.code, + lineno, + orig_init_offset, + orig_resume_offset, + setup_fn_target_offsets, + *args, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/side_effects.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/side_effects.py new file mode 100644 index 0000000000000000000000000000000000000000..e7f366dadc852f3c69cfc1df91c0d63f59150ced --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/side_effects.py @@ -0,0 +1,2120 @@ +""" +Side effect tracking and management for TorchDynamo's compilation system. + +This module provides infrastructure for tracking and managing side effects that occur +during symbolic execution, including: + +- Tracking mutations to objects, attributes, and variables +- Managing context changes (cell variables, global namespace modifications) +- Handling aliasing and object identity preservation +- Managing stack frame state and local variable changes +- Tracking function calls with side effects + +Key classes: +- SideEffects: Main container for tracking all side effects during execution +- MutableSideEffects: Specialization for mutable object tracking +- AttributeMutation/ValueMutation: Track specific types of mutations +- Various specialized side effect classes for different scenarios + +The side effect system ensures that mutations performed during symbolic execution +are properly replayed during runtime, maintaining the correctness of compiled code +while enabling optimizations where safe. +""" + +import collections +import contextlib +import dataclasses +import enum +import inspect +import logging +import textwrap +import traceback +import weakref +from collections.abc import Callable, Generator, MutableMapping +from types import CellType +from typing import Any, TYPE_CHECKING + +import torch +import torch.nn +from torch._dynamo.variables.misc import AutogradFunctionContextVariable +from torch._library.utils import RegistrationHandle +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import is_structseq_class + +from . import config, graph_break_hints, utils, variables +from .bytecode_transformation import ( + bytecode_from_template, + create_call_function, + create_call_method, + create_instruction, + Instruction, +) +from .codegen import PyCodegen +from .exc import collapse_resume_frames, get_stack_above_dynamo, unimplemented +from .source import AttrSource, GlobalSource, LocalCellSource, Source, TempLocalSource +from .utils import ( + is_frozen_dataclass, + is_namedtuple_cls, + is_pybind11_enum_member, + nn_module_new, + object_new, +) +from .variables.base import ( + AttributeMutation, + AttributeMutationExisting, + AttributeMutationNew, + AttrMutationKind, + is_side_effect_safe, + ValueMutationExisting, + ValueMutationNew, + VariableTracker, +) +from .variables.user_defined import FrozenDataClassVariable + + +if TYPE_CHECKING: + from torch._dynamo.output_graph import OutputGraph + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.lists import ListVariable + + +side_effects_log = torch._logging.getArtifactLogger(__name__, "side_effects") + + +@dataclasses.dataclass(frozen=True) +class SideEffectReplayContext: + side_effects: "SideEffects" + codegen: PyCodegen + var: VariableTracker + suffixes: list[list[Instruction]] + log: Callable[[VariableTracker], None] + + +SideEffectReplayMatcher = Callable[[SideEffectReplayContext], bool] +SideEffectReplayCodegen = Callable[[SideEffectReplayContext], None] +SideEffectReplayHandlerDecorator = Callable[ + [SideEffectReplayCodegen], SideEffectReplayCodegen +] + + +@dataclasses.dataclass(frozen=True) +class SideEffectReplayHandler: + name: str + matcher: SideEffectReplayMatcher + codegen: SideEffectReplayCodegen + priority: int = 0 + + +class _SideEffectReplayRegistry: + def __init__(self) -> None: + self.handlers: list[SideEffectReplayHandler] = [] + + def register_handler(self, handler: SideEffectReplayHandler) -> RegistrationHandle: + self.handlers.append(handler) + + def deregister() -> None: + self.handlers.remove(handler) + + return RegistrationHandle(deregister) + + def lookup_handler( + self, ctx: SideEffectReplayContext + ) -> SideEffectReplayHandler | None: + matches = [handler for handler in self.handlers if handler.matcher(ctx)] + if not matches: + return None + matches.sort(key=lambda handler: handler.priority, reverse=True) + top = matches[0] + if len(matches) > 1 and matches[1].priority == top.priority: + names = [ + handler.name for handler in matches if handler.priority == top.priority + ] + raise RuntimeError( + f"Ambiguous side effect replay handler for " + f"{type(ctx.var).__name__}: {names}" + ) + return top + + +_side_effect_replay_registry = _SideEffectReplayRegistry() + + +def _register_side_effect_replay_handler( + handler: SideEffectReplayHandler, +) -> RegistrationHandle: + return _side_effect_replay_registry.register_handler(handler) + + +def register_side_effect_replay_handler( + *, + name: str, + matcher: SideEffectReplayMatcher, + priority: int = 0, +) -> SideEffectReplayHandlerDecorator: + def decorator( + codegen: SideEffectReplayCodegen, + ) -> SideEffectReplayCodegen: + _register_side_effect_replay_handler( + SideEffectReplayHandler( + name=name, + matcher=matcher, + codegen=codegen, + priority=priority, + ) + ) + return codegen + + return decorator + + +def _manual_dict_setitem( + dict_from: dict[Any, Any], dict_to: dict[Any, Any], mro_index: int +) -> None: + # Carefully calls the dict or OrderedDict `clear` or `__setitem__`. We have + # to be careful because we don't want to trigger the user defined object + # setitem or clear. The mro_index is used to find the dict/OrderedDict from + # the class mro. + dict_class = type(dict_to).__mro__[mro_index] + dict_class.clear(dict_to) # type: ignore[attr-defined] + for k, v in dict_from.items(): + dict_class.__setitem__(dict_to, k, v) # type: ignore[index] + + +def _manual_list_update(list_from: list[Any], list_to: list[Any]) -> None: + list.clear(list_to) + list.extend(list_to, list_from) + + +def _manual_deque_update(deque_from: Any, deque_to: Any) -> None: + # Call the deque methods directly, not any overridden subclass methods. + # deque_to keeps its (read-only) maxlen, so extend re-applies eviction. + collections.deque.clear(deque_to) + collections.deque.extend(deque_to, deque_from) + + +class SideEffects: + """ + Maintain records of mutations and provide methods to apply them during code generation. + + Handles tracking and applying side effects during PyTorch Dynamo compilation, + maintaining Python semantics by managing mutations, attribute modifications, + and other side effects that occur during program execution. + + Key responsibilities: + - Tracks mutations to Python objects, lists, and dictionaries that need to be + applied after an FX graph is run. + - Manages attribute modifications and deletions + - Handles tensor hooks and backward pass state + - Tracks cell variable mutations and global variable changes + - Ensures correct ordering and application of side effects after graph execution + + This ensures that optimized code behaves identically to the original Python code with + respect to object mutations and other side effects. + """ + + id_to_variable: dict[int, VariableTracker] + store_attr_mutations: dict[VariableTracker, dict[str, VariableTracker]] + attr_mutation_kinds: dict[VariableTracker, dict[str, AttrMutationKind]] + keepalive: list[object] + # Maps variable tracker to list of user stacks (StackSummary objects, formatted lazily) + mutation_user_stacks: dict[VariableTracker, list[traceback.StackSummary]] + + def __init__( + self, + output_graph: "OutputGraph", + id_to_variable: dict[int, VariableTracker] | None = None, + store_attr_mutations: dict[VariableTracker, dict[str, VariableTracker]] + | None = None, + attr_mutation_kinds: dict[VariableTracker, dict[str, AttrMutationKind]] + | None = None, + mutation_user_stacks: dict[VariableTracker, list[traceback.StackSummary]] + | None = None, + keepalive: list[object] | None = None, + save_for_backward: list[ + tuple[AutogradFunctionContextVariable, list[VariableTracker]] + ] + | None = None, + tensor_hooks: dict[ + int, + tuple[ + "variables.TensorVariable", + VariableTracker, + "variables.RemovableHandleVariable", + str, + ], + ] + | None = None, + ) -> None: + super().__init__() + self.output_graph_weakref = weakref.ref(output_graph) + self.id_to_variable = id_to_variable or {} + self.store_attr_mutations = store_attr_mutations or {} + self.attr_mutation_kinds = attr_mutation_kinds or {} + self.mutation_user_stacks = mutation_user_stacks or {} + self.keepalive = keepalive or [] + self.save_for_backward = save_for_backward or [] + self.tensor_hooks = tensor_hooks or {} + # Used by MappingProxyVariable to graph break in case of any mutated + # dict + self._has_existing_dict_mutation = False + # Track Compiled Autograd final callbacks that must be called at the end of Compiled Autograd backward graph. + # Only applicable if this graph is created from Dynamo tracing in Compiled Autograd. + self.ca_final_callbacks_var: ListVariable | None = None + + # Tracks VariableTracker objects whose mutations can be skipped. + # For normal mutated variables, Dynamo generates code to replay/reconstruct + # the mutations after graph execution. However, variables in this set have + # their mutations ignored - the mutations happen during + # execution but don't need to be replayed in the generated code. + # Used for temporary mutations in contexts like torch.func.functional_call, + # where module parameters/buffers are modified but later restored. + self.ignore_mutation_on_these_variables: set[VariableTracker] = set() + # Sources mutated during tracing: AttrSource for attribute + # mutations, var.source for value mutations (list/dict/etc). + self.mutated_sources: OrderedSet[Source] = OrderedSet() + + # Deferred side-effect checking for nullified attribute mutations. + # Maps (vt_id, attr_name) → (original_value, current_value). + # On validation, we check original == current. + self.deferred_attr_mutations: dict[tuple[int, str], tuple[object, object]] = {} + + def ignore_mutations_on(self, var: VariableTracker) -> None: + """Mutations to this variable will be executed but not tracked, + typically used for temporary mutations that are later restored.""" + self.ignore_mutation_on_these_variables.add(var) + + def stop_ignoring_mutations_on(self, var: VariableTracker) -> None: + """Remove a variable from the skip mutation set, restoring normal mutation tracking.""" + if var in self.ignore_mutation_on_these_variables: + self.ignore_mutation_on_these_variables.remove(var) + + @contextlib.contextmanager + def defer_side_effect_checks(self) -> Generator[None, None, None]: + """Defer outer-scope attribute mutation checks until tracing completes. + + Context managers that flip-flop a flag (set on enter, restore on exit) + produce no net side effect. Instead of failing immediately, we track + original and current values, then validate they match after tracing. + + Note: this context only validates that mutations were nullified — it + does NOT roll back store_attr_mutations. Callers must restore + side_effects separately (e.g., via prev_side_effects pattern) to + discard the mutations after the HOP. + """ + saved = self.deferred_attr_mutations + self.deferred_attr_mutations = {} + try: + yield + self.validate_deferred_attr_mutations() + finally: + self.deferred_attr_mutations = saved + + def snapshot_attr_mutation( + self, item: VariableTracker, name: str, value: VariableTracker + ) -> bool: + """Record an attribute mutation for deferred validation. + + Returns True if successfully deferred, False if we cannot read the + original value (tp_getattro_impl raises NotImplementedError) or the + original is not a python constant — caller should fall back to + check_allowed_side_effect. + """ + key = (id(item), name) + if not value.is_python_constant(): + raise AssertionError( + "value must be a python constant (guaranteed by caller store_attr)" + ) + current = value.as_python_constant() + if key in self.deferred_attr_mutations: + original = self.deferred_attr_mutations[key][0] + else: + output_graph = self.output_graph_weakref() + if output_graph is None: + raise AssertionError("output_graph weakref is dead") + tx = output_graph.current_tx + try: + original_vt = item.tp_getattro_impl(tx, name) # type: ignore[arg-type] + except NotImplementedError: + return False + if not original_vt.is_python_constant(): + return False + original = original_vt.as_python_constant() + self.deferred_attr_mutations[key] = (original, current) + return True + + def validate_deferred_attr_mutations(self) -> None: + """Check that all deferred attribute mutations were nullified.""" + for (_, name), (original, current) in self.deferred_attr_mutations.items(): + if original != current: + unimplemented( + gb_type="HOP: Non-nullified side effect", + context=f"Attribute '{name}' was not restored to its original value", + explanation=f"Attribute '{name}' on an outer-scope object was " + f"changed from {original!r} to {current!r} inside a " + "higher-order op subgraph. Dynamo only supports mutations " + "that are undone before the subgraph exits (e.g., context " + "managers that save/restore a flag). If you intentionally " + "want this side effect, move the mutation outside of the " + "higher-order op.", + hints=[*graph_break_hints.FUNDAMENTAL], + ) + + def _capture_user_stack(self, key: VariableTracker) -> None: + """Capture the current user stack from the instruction translator.""" + if config.side_effect_replay_policy == "silent": + return + if key not in self.mutation_user_stacks: + self.mutation_user_stacks[key] = [] + self.mutation_user_stacks[key].append( + torch._guards.TracingContext.extract_stack() + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SideEffects): + raise AssertionError(f"Expected SideEffects, got {type(other)}") + # NB: do NOT test keepalive + return ( + self.id_to_variable == other.id_to_variable + and self.store_attr_mutations == other.store_attr_mutations + and self.attr_mutation_kinds == other.attr_mutation_kinds + and self.save_for_backward == other.save_for_backward + and self.tensor_hooks == other.tensor_hooks + ) + + def diff(self, other: "SideEffects") -> str | None: + if self.id_to_variable != other.id_to_variable: + sk_itv = self.id_to_variable.keys() + ok_itv = other.id_to_variable.keys() + if sk_itv != ok_itv: + return f"id_to_variable keys: {sk_itv} != {ok_itv}" + # Feel free to augment this with more fancy diffing logic + # if needed for debugging + return "id_to_variable: unknown diff" + elif self.store_attr_mutations != other.store_attr_mutations: + sk_sam = self.store_attr_mutations.keys() + ok_sam = other.store_attr_mutations.keys() + if sk_sam != ok_sam: + return f"store_attr_mutations keys: {sk_sam} != {ok_sam}" + return "store_attr_mutations: unknown diff" + elif self.attr_mutation_kinds != other.attr_mutation_kinds: + return "attr_mutation_kinds: unknown diff" + elif self.save_for_backward != other.save_for_backward: + return "save_for_backward" + elif self.tensor_hooks != other.tensor_hooks: + return "tensor_hooks" + else: + return None + + def clone(self) -> "SideEffects": + """Create a shallow copy""" + ref = self.output_graph_weakref() + if ref is None: + raise AssertionError("output_graph weakref is dead during clone") + return self.__class__( + output_graph=ref, + id_to_variable=dict(self.id_to_variable), + store_attr_mutations={ + k: dict(v) for k, v in self.store_attr_mutations.items() + }, + attr_mutation_kinds={ + k: dict(v) for k, v in self.attr_mutation_kinds.items() + }, + mutation_user_stacks=self.mutation_user_stacks, + keepalive=list(self.keepalive), + save_for_backward=self.save_for_backward, + tensor_hooks=self.tensor_hooks, + ) + + def __contains__(self, item: object) -> bool: + return id(item) in self.id_to_variable + + def __getitem__(self, item: object) -> VariableTracker: + return self.id_to_variable[id(item)] + + def should_allow_externally_visible_side_effects_in_subtracer(self) -> bool: + output_graph = self.output_graph_weakref() + return bool( + output_graph + and output_graph.current_tx.output.current_tracer.unsafe_allow_externally_visible_side_effects + ) + + def should_allow_side_effects_in_hop(self) -> bool: + output_graph = self.output_graph_weakref() + return bool( + output_graph + and output_graph.current_tx.output.current_tracer.allow_side_effects_in_hop + ) + + def is_reconstructing_generator(self) -> bool: + output_graph = self.output_graph_weakref() + + return bool( + output_graph + and output_graph.current_tx.output.current_tracer.is_reconstructing_generator + ) + + def _maybe_record_side_effect(self, item: VariableTracker) -> None: + """Record the first externally-visible side effect on the current tracer.""" + if item.mutation_type is not None and not is_side_effect_safe( + item.mutation_type + ): + output_graph = self.output_graph_weakref() + if output_graph: + tracer = output_graph.current_tx.output.current_tracer + if tracer.side_effect_stack is None: + tracer.side_effect_stack = ( + torch._guards.TracingContext.extract_stack() + ) + + def check_allowed_side_effect(self, item: VariableTracker) -> bool: + from torch._dynamo.variables.misc import AutogradFunctionContextVariable + + # People do things like self.dim = dim inside autograd.Function. + # These are benign. + if isinstance(item, AutogradFunctionContextVariable): + return True + if self.should_allow_externally_visible_side_effects_in_subtracer(): + self._maybe_record_side_effect(item) + return True + if self.should_allow_side_effects_in_hop(): + self._maybe_record_side_effect(item) + return True + if self.is_reconstructing_generator(): + # This is missing the case where one mutates a tensor. See + # test_generator.py::test_reconstruct_generator_tensor_mutation + unimplemented( + gb_type="Generator reconstruction with mutations", + context=f"mutating object: {item}", + explanation="Cannot reconstruct a generator with variable mutations. " + "Dynamo needs to fully exhaust the generator, which may cause " + "unintended variable modifications.", + hints=[ + "Remove mutations from the generator.", + *graph_break_hints.FUNDAMENTAL, + ], + ) + if item.mutation_type is None: + raise AssertionError( + f"mutation_type is None for {item} in check_allowed_side_effect" + ) + if not is_side_effect_safe(item.mutation_type): + unimplemented( + gb_type="HOP: Unsafe side effect", + context=f"Attempted to mutate {item}", + explanation="Mutating a variable from outside the scope of this HOP is not supported.", + hints=[ + "If the HOP is activation checkpointing (torch.utils.checkpoint.checkpoint), this points to a " + "side effect in forward method. Eager activation checkpointing replays that side-effect while " + "recomputing the forward in the backward. If you are ok with side-effect not replayed in the " + "backward, try setting `torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True`", + ], + ) + return False + + def store_attr( + self, + item: VariableTracker, + name: str, + value: VariableTracker, + mutation_kind: AttrMutationKind = AttrMutationKind.GENERIC_SETATTR, + mutated_source: Source | None = None, + ) -> None: + if not self.is_attribute_mutation(item): + raise AssertionError( + f"Expected attribute mutation for {item} in store_attr" + ) + # For constant attribute mutations on outer-scope objects, defer + # the side-effect check and validate after tracing that the + # mutation was nullified (value restored to original). + deferred = False + if ( + isinstance(item.mutation_type, AttributeMutationExisting) + and not is_side_effect_safe(item.mutation_type) + and not isinstance(item, AutogradFunctionContextVariable) + and not self.should_allow_side_effects_in_hop() + and not self.should_allow_externally_visible_side_effects_in_subtracer() + and value.is_python_constant() + ): + deferred = self.snapshot_attr_mutation(item, name, value) + if not deferred: + self.check_allowed_side_effect(item) + if item not in self.store_attr_mutations: + self.store_attr_mutations[item] = {} + if item not in self.attr_mutation_kinds: + self.attr_mutation_kinds[item] = {} + self.store_attr_mutations[item][name] = value + self.attr_mutation_kinds[item][name] = mutation_kind + # Capture user stack for this mutation + self._capture_user_stack(item) + if mutated_source is not None: + self.mutated_sources.add(mutated_source) + else: + item_source = getattr(item, "source", None) + if item_source is not None: + self.mutated_sources.add(AttrSource(item_source, name)) + + def store_instance_dict_attr( + self, item: VariableTracker, name: str, value: VariableTracker + ) -> None: + # `obj.__dict__` ordering is observable (e.g. list(obj.__dict__)). When a + # key is re-added after being deleted, CPython appends it at the end + # rather than reusing its old slot. store_attr_mutations is an + # insertion-ordered dict, so a plain re-store of an existing key would + # keep the stale position; drop the deleted entry first so the new value + # re-inserts at the end. + if not isinstance(value, variables.DeletedVariable): + existing = self.store_attr_mutations.get(item, {}).get(name) + if isinstance(existing, variables.DeletedVariable): + # store_attr always writes both maps together, so the + # attr_mutation_kinds entry is guaranteed present here; use del + # for both to surface any invariant violation. + del self.store_attr_mutations[item][name] + del self.attr_mutation_kinds[item][name] + self.store_attr(item, name, value, AttrMutationKind.INSTANCE_DICT) + + def get_attr_mutation_kind( + self, item: VariableTracker, name: str + ) -> AttrMutationKind: + if name not in self.store_attr_mutations.get(item, ()): + return AttrMutationKind.GENERIC_SETATTR + if name not in self.attr_mutation_kinds.get(item, ()): + raise AssertionError(f"Missing attribute mutation kind for {item}.{name}") + return self.attr_mutation_kinds[item][name] + + def load_attr( + self, + item: VariableTracker, + name: str, + deleted_ok: bool = False, + check: bool = False, + ) -> VariableTracker: + if check: + if not self.is_attribute_mutation(item): + raise AssertionError( + f"Expected attribute mutation for {item} in load_attr" + ) + result = self.store_attr_mutations[item][name] + if not deleted_ok and isinstance(result, variables.DeletedVariable): + unimplemented( + gb_type="Attempted to read a deleted variable", + context=f"item: {item}, name: {name}", + explanation="", + hints=[*graph_break_hints.USER_ERROR], + ) + return result + + def store_cell(self, cellvar: VariableTracker, value: VariableTracker) -> None: + if cellvar.is_immutable(): + unimplemented( + gb_type="Write to immutable cell", + context=f"cellvar: {cellvar}, value: {value}", + explanation="Dynamo doesn't support writing to immutable/sourceless cell variables.", + hints=[*graph_break_hints.DIFFICULT], + ) + if not isinstance(cellvar, variables.CellVariable): + raise AssertionError( + f"Expected CellVariable, got {type(cellvar)} in store_cell" + ) + if not isinstance(value, variables.VariableTracker): + raise AssertionError( + f"Expected VariableTracker, got {type(value)} in store_cell" + ) + self.store_attr(cellvar, "cell_contents", value) + + def load_cell(self, cellvar: VariableTracker) -> VariableTracker: + if not isinstance(cellvar, variables.CellVariable): + raise AssertionError( + f"Expected CellVariable, got {type(cellvar)} in load_cell" + ) + # Track the cell_contents source during subgraph tracing so that + # mutations (e.g. nonlocal counter = 3) are detected by the reuse + # mechanism via set intersection with mutated_sources. + output_graph = self.output_graph_weakref() + if output_graph: + cell_source = getattr(cellvar, "source", None) + if cell_source is not None: + output_graph.current_tx.output.current_tracer.traced_sources.add( + AttrSource(cell_source, "cell_contents") + ) + if self.has_pending_mutation_of_attr(cellvar, "cell_contents"): + return self.load_attr(cellvar, "cell_contents", check=False) + if cellvar.pre_existing_contents: + return cellvar.pre_existing_contents + unimplemented( + gb_type="Read uninitialized cell", + context=str(cellvar), + explanation="Attempted to read a cell variable that has not been populated yet.", + hints=[*graph_break_hints.USER_ERROR], + ) + + def load_global(self, gvar: VariableTracker, name: str) -> VariableTracker: + if not isinstance(gvar, variables.VariableTracker): + raise AssertionError( + f"Expected VariableTracker, got {type(gvar)} in load_global" + ) + # This path serves the read out of side effects, bypassing + # VariableBuilder, so record the source here the way load_cell does -- + # otherwise a subgraph reading a rebound global has no traced source to + # intersect with mutated_sources and is wrongly considered reusable. + output_graph = self.output_graph_weakref() + if output_graph: + output_graph.current_tx.output.current_tracer.traced_sources.add( + GlobalSource(name) + ) + return self.load_attr(gvar, name) + + def store_global( + self, gvar: VariableTracker, name: str, value: VariableTracker + ) -> None: + if not isinstance(gvar, variables.VariableTracker): + raise AssertionError( + f"Expected VariableTracker for gvar, got {type(gvar)} in store_global" + ) + if not isinstance(value, variables.VariableTracker): + raise AssertionError( + f"Expected VariableTracker for value, got {type(value)} in store_global" + ) + # gvar is a per-global sentinel holder whose own source already names + # the global, so store_attr's default AttrSource(item.source, name) + # would name a nonexistent `G.G`. Record the source readers actually + # use, so mutated_sources intersects with traced_sources. + self.store_attr(gvar, name, value, mutated_source=GlobalSource(name)) + + @staticmethod + def cls_supports_mutation_side_effects(cls: type) -> bool: + return inspect.getattr_static(cls, "__getattribute__", None) in ( + object.__getattribute__, + dict.__getattribute__, + set.__getattribute__, + frozenset.__getattribute__, + int.__getattribute__, + str.__getattribute__, + list.__getattribute__, + tuple.__getattribute__, + collections.deque.__getattribute__, + BaseException.__getattribute__, + ) + + def is_attribute_mutation(self, item: VariableTracker) -> bool: + return isinstance(item.mutation_type, AttributeMutation) + + def has_pending_mutation(self, item: VariableTracker) -> bool: + return self.is_attribute_mutation(item) and bool( + self.store_attr_mutations.get(item) + ) + + def has_pending_mutation_of_attr( + self, + item: VariableTracker, + name: str, + mutation_kinds: AttrMutationKind | tuple[AttrMutationKind, ...] | None = None, + ) -> bool: + if not ( + self.is_attribute_mutation(item) + and name in self.store_attr_mutations.get(item, ()) + ): + return False + if mutation_kinds is None: + return True + mutation_kind = self.get_attr_mutation_kind(item, name) + if isinstance(mutation_kinds, AttrMutationKind): + return mutation_kind is mutation_kinds + return mutation_kind in mutation_kinds + + def is_modified(self, item: VariableTracker) -> bool: + if item.is_immutable(): + return False + if isinstance(item.mutation_type, (AttributeMutationNew, ValueMutationNew)): + return True + + if isinstance(item, variables.UserDefinedObjectVariable): + # Checks if the underlying dict or tuple vt has been modified + return item in self.store_attr_mutations or item.is_base_vt_modified(self) + + if self.is_attribute_mutation(item): + return item in self.store_attr_mutations + if item.mutation_type is None: + raise AssertionError(f"mutation_type is None for {item} in is_modified") + return item.mutation_type.is_modified # type: ignore[attr-defined] + + def _track_obj( + self, + item: object, + variable: VariableTracker, + mutation_type_cls: type = ValueMutationExisting, + ) -> VariableTracker: + """Start tracking an existing or new variable for mutation""" + if id(item) in self.id_to_variable: + raise AssertionError( + f"{variable} is already tracked for mutation. This could be " + "because you are not using VariableBuilder to construct " + "the variable tracker. " + f"Source of new object: {variable.source}. " + f"Source of previously tracked object: {self.id_to_variable[id(item)].source}." + ) + + variable.mutation_type = mutation_type_cls() + self.id_to_variable[id(item)] = variable + self.keepalive.append(item) + return variable + + track_mutable = _track_obj + + def track_object_existing( + self, + item: object, + variable: VariableTracker, + ) -> VariableTracker: + # TODO: Modify this API so that we preserve type info of + # variable + return self._track_obj( + item, + variable, + mutation_type_cls=AttributeMutationExisting, + ) + + def track_attribute_mutation_new(self, variable: VariableTracker) -> None: + """Register a sourceless VT (e.g. a synthetic exception) as a new + attribute-mutation object so its attribute mutations are codegen'd. + Keyed by the VT's id since there is no backing Python object.""" + if id(variable) in self.id_to_variable: + return + variable.mutation_type = AttributeMutationNew() + self.id_to_variable[id(variable)] = variable + self.keepalive.append(variable) + + def track_object_new( + self, + cls_source: Source | None, + user_cls: Any, + variable_cls: Any, + options: dict[str, Any], + ) -> VariableTracker: + obj = object_new(user_cls) + variable = variable_cls( + obj, + mutation_type=AttributeMutationNew(cls_source), + **options, + ) + self.id_to_variable[id(obj)] = variable + self.keepalive.append(obj) + return variable + + def get_variable_cls(self, user_cls: type) -> type: + from torch.overrides import TorchFunctionMode + + from .variables.ctx_manager import GenericContextWrappingVariable + from .variables.torch_function import TorchFunctionModeVariable + from .variables.user_defined import is_generic_ctx_manager_cls + + variable_cls: type[variables.UserDefinedObjectVariable] = ( + variables.UserDefinedObjectVariable + ) + if issubclass( + user_cls, TorchFunctionMode + ) and TorchFunctionModeVariable.is_supported_torch_function_mode(user_cls): + variable_cls = TorchFunctionModeVariable + elif is_generic_ctx_manager_cls(user_cls): + variable_cls = GenericContextWrappingVariable + elif issubclass(user_cls, torch.nn.Module): + variable_cls = variables.UnspecializedNNModuleVariable + elif issubclass(user_cls, collections.defaultdict): + variable_cls = variables.DefaultDictVariable + elif issubclass(user_cls, dict): + # Includes collections.OrderedDict and its subclasses; the + # UserDefinedDictVariable picks an OrderedDict-backed store. + variable_cls = variables.UserDefinedDictVariable + elif issubclass(user_cls, (set, frozenset)): + variable_cls = variables.UserDefinedSetVariable + elif issubclass(user_cls, tuple): + if is_namedtuple_cls(user_cls): + variable_cls = variables.UserDefinedTupleVariable.get_vt_cls(user_cls) + else: + variable_cls = variables.UserDefinedTupleVariable + elif issubclass(user_cls, list): + variable_cls = variables.UserDefinedListVariable + elif issubclass(user_cls, collections.deque): + variable_cls = variables.UserDefinedDequeVariable + elif issubclass(user_cls, MutableMapping): + variable_cls = variables.MutableMappingVariable + elif is_frozen_dataclass(user_cls): + variable_cls = FrozenDataClassVariable + elif issubclass(user_cls, BaseException): + variable_cls = variables.UserDefinedExceptionObjectVariable + elif issubclass( + user_cls, + variables.user_defined._CONSTANT_BASE_TYPES, + ): + variable_cls = variables.UserDefinedConstantVariable + elif variables.InspectVariable.is_matching_class(user_cls): + variable_cls = variables.InspectVariable + if not issubclass(variable_cls, variables.UserDefinedObjectVariable): + raise AssertionError( + f"Expected subclass of UserDefinedObjectVariable, got {variable_cls}" + ) + return variable_cls + + def get_example_value( + self, + base_cls_vt: VariableTracker, + cls_vt: VariableTracker, + init_args: list[VariableTracker], + ) -> Any: + user_cls = cls_vt.value # type: ignore[attr-defined] + if issubclass(user_cls, torch.nn.Module): + # TODO(anijain2305) - Is it possible to remove this specialization? + obj = nn_module_new(user_cls) + else: + if isinstance(base_cls_vt, variables.BuiltinVariable): + base_cls = base_cls_vt.fn + elif isinstance(base_cls_vt, variables.DictBuiltinVariable): + base_cls = dict + elif isinstance(base_cls_vt, variables.ListBuiltinVariable): + base_cls = list + elif isinstance(base_cls_vt, variables.UserDefinedClassVariable): + base_cls = base_cls_vt.value + else: + raise RuntimeError(f"Unexpected base_cls_vt {base_cls_vt}") + + if not variables.UserDefinedClassVariable.is_supported_new_method( + base_cls.__new__ + ): + raise AssertionError(f"Unsupported __new__ method for {base_cls}") + if is_structseq_class(user_cls): + # Structseq tp_new requires a sequence argument and rejects + # tuple.__new__, so create a dummy with None placeholders. + obj = user_cls([None] * user_cls.n_fields) + elif init_args and issubclass( + user_cls, + variables.user_defined._CONSTANT_BASE_TYPES, + ): + example_args = [arg.as_python_constant() for arg in init_args] + try: + obj = base_cls.__new__( # pyrefly: ignore[bad-specialization] + user_cls, *example_args + ) + except Exception: + # __new__ can raise (e.g., exceeding int str digit limits). + # Fall back to creating without args — the example value is + # only used for tracing, not for correctness. + obj = base_cls.__new__( # pyrefly: ignore[bad-specialization] + user_cls + ) + else: + try: + obj = base_cls.__new__(user_cls) + except TypeError as exc: + # Backstop for direct construction paths that bypass the + # UserDefinedClassVariable object.__new__ preflight. + unimplemented( + gb_type="Unsupported user-defined object construction during side-effect tracking", + context=f"class={user_cls}, base={base_cls}, error={exc}", + explanation=( + "Dynamo could not construct an example object for " + "side-effect replay using the class __new__ method." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + return obj + + def track_new_user_defined_object( + self, + base_cls_vt: VariableTracker, + cls_vt: VariableTracker, + init_args: list[VariableTracker], + *, + tx: "InstructionTranslatorBase | None" = None, + ) -> VariableTracker: + """ + Creates a UserDefinedObjectVariable (or its subclass) variable tracker + and mark it for attribute mutation tracking. + + Also records the variable trackers to call __new__ method on + reconstruction. Roughly, the reconstruction looks like this + base_cls_vt.__new__(user_cls, *init_args) + """ + cls_source = cls_vt.source + user_cls = cls_vt.value # type: ignore[attr-defined] + variable_cls = self.get_variable_cls(user_cls) + obj = self.get_example_value(base_cls_vt, cls_vt, init_args) + + kwargs: dict[str, Any] = {} + if tx is not None: + kwargs["tx"] = tx + variable = variable_cls( + obj, + cls_source=cls_vt.source, + base_cls_vt=base_cls_vt, + init_args=init_args, + mutation_type=AttributeMutationNew(cls_source), + **kwargs, + ) + self.id_to_variable[id(obj)] = variable + self.keepalive.append(obj) + return variable + + def track_cell_new( + self, + ) -> VariableTracker: + obj = object() + variable = variables.CellVariable( + mutation_type=AttributeMutationNew(), + ) + self.id_to_variable[id(obj)] = variable + self.keepalive.append(obj) + return variable + + def track_cell_existing( + self, source: Source | None, cell: CellType, contents: VariableTracker + ) -> VariableTracker: + variable = variables.CellVariable( + # We don't support mutation to cell without source because we need + # source to properly codegen the mutations. + mutation_type=None if source is None else AttributeMutationExisting(), + pre_existing_contents=contents, + source=source, + ) + self.id_to_variable[id(cell)] = variable + self.keepalive.append(cell) + return variable + + def track_global_existing(self, source: Source, item: object) -> VariableTracker: + variable = variables.NewGlobalVariable( + mutation_type=AttributeMutationExisting(), + source=source, + ) + self.id_to_variable[id(item)] = variable + self.keepalive.append(item) + return variable + + def track_save_for_backward( + self, ctx: VariableTracker, args: list[VariableTracker] + ) -> None: + if not isinstance(ctx, variables.AutogradFunctionContextVariable): + raise AssertionError( + f"Expected AutogradFunctionContextVariable, got {type(ctx)}" + ) + self.save_for_backward.append((ctx, args)) + + def track_runahead_tensor_and_symvar_side_effects( + self, other: "SideEffects" + ) -> None: + # In higher order ops we want to keep track of tensors seen in the + # speculate_subgraph so that we don't lift them again as a new input in + # other speculate_subgraph or in the root tracer. + for other_item in other.keepalive: + other_id = id(other_item) + other_variable = other.id_to_variable[other_id] + if other_id not in self.id_to_variable and isinstance( + other_variable, (variables.TensorVariable, variables.SymNodeVariable) + ): + self.track_object_existing(other_item, other_variable) + + def prune_dead_object_new(self, tx: "InstructionTranslatorBase") -> None: + # Avoid VT cycles from e.g., recursive function. + visited: set[VariableTracker] = set() + live_new_objects: set[VariableTracker] = set() + + def visit(var: VariableTracker) -> None: + if var in visited: + return + visited.add(var) + # Object may have been mutated, store this mutation. + if isinstance(var.mutation_type, AttributeMutationNew): + live_new_objects.add(var) + # It's possible that we have mutated the value of this variable + # to be another one. The new value is in store_attr_mutations. + # Also recurse through the new value to detect alive AttributeMutationNew. + if var in self.store_attr_mutations: + VariableTracker.visit( + visit, # noqa: F821 + self.store_attr_mutations[var], + ) + + def is_live(var: VariableTracker) -> bool: + if isinstance(var.mutation_type, AttributeMutationNew): + return var in live_new_objects + return True + + pre_existing_vars = [ + var + for var in self.id_to_variable.values() + if not isinstance(var.mutation_type, AttributeMutationNew) + ] + + # The only live side effects come from returns (tx.stack), any intermediates + # during a graph break (tx.symbolic_locals), and mutation on pre-existing variables. + # Recursively visit Variables and see if any of them have been mutated. + init_live_vars = [] + # gather stack/symbolic_locals for all tx's up the chain + cur_tx: InstructionTranslatorBase | None = tx + while cur_tx is not None: + init_live_vars.extend([cur_tx.stack, cur_tx.symbolic_locals]) + if cur_tx.parent is not None: + # for non-root tx'es, also keep the cells/freevars alive so they get codegen'd properly + # TODO see if we could prune dead cells - cell pruning information needs to be forwarded + # to the resume function creation as well. + if cur_tx.post_prune_cell_and_freevars is None: + raise AssertionError( + "post_prune_cell_and_freevars is None for non-root tx" + ) + init_live_vars.append(cur_tx.post_prune_cell_and_freevars) + cur_tx = cur_tx.parent + + # Generators tracked for close-on-exit have their close() called in + # compile_subgraph after pruning. + gen_reachable_new: set[VariableTracker] = set() + + def visit_gen(var: VariableTracker) -> None: + if isinstance(var.mutation_type, AttributeMutationNew): + gen_reachable_new.add(var) + + # Pass side_effects so the walk follows store_attr_mutations, and share + # one cache across all generators to dedup shared subiterators. + gen_visit_cache: dict[int, Any] = {} + for gen in tx.output.local_generators: + gen_tracer = gen.inline_tracer + VariableTracker.visit( + visit_gen, + [gen_tracer.stack, gen_tracer.symbolic_locals], + gen_visit_cache, + self, + ) + + VariableTracker.visit( + visit, + # TODO track from all possible sources. + init_live_vars + + [ + pre_existing_vars, + tx.output.backward_state, + self.tensor_hooks, + ], + ) + # Manually release the self-referential function, which indirectly + # captures certain `VariableTracker` and affects parts of PT test/logic + # that are sensitive to when certain objects get released. + del visit + + # NB: cell variable handling is tricky. + # cell variables must stay alive if any NestedUserFunctionVariable + # are live. "visit"-ing the NestedUserFunctionVariable visits + # the .closures field, from which we will see if we need to keep + # any mutations to cell variables alive. + + self.id_to_variable = { + k: v for k, v in self.id_to_variable.items() if is_live(v) + } + self.store_attr_mutations = { + k: v + for k, v in self.store_attr_mutations.items() + if is_live(k) or k in gen_reachable_new + } + self.attr_mutation_kinds = { + k: v + for k, v in self.attr_mutation_kinds.items() + if is_live(k) or k in gen_reachable_new + } + + def mutation(self, var: VariableTracker) -> None: + if var in self.ignore_mutation_on_these_variables: + return + + self.check_allowed_side_effect(var) + # Capture user stack for this mutation + self._capture_user_stack(var) + + if isinstance(var.mutation_type, ValueMutationExisting): + var.mutation_type.is_modified = True + if var.source is not None: + self.mutated_sources.add(var.source) + if var.source and isinstance(var, variables.ConstDictVariable): + self._has_existing_dict_mutation = True + + def has_existing_dict_mutation(self) -> bool: + return self._has_existing_dict_mutation + + def _get_modified_vars(self) -> list[VariableTracker]: + return [var for var in self.id_to_variable.values() if self.is_modified(var)] + + def codegen_save_tempvars(self, cg: PyCodegen) -> None: + # We must codegen modified VT to their source by default, so that + # mutation and aliasing are properly accounted for. + # + # Since newly constructed objects don't have a source, we manually + # codegen their construction and store them to a newly assigned local + # source. Note that `ValueMutationNew` isn't tracked by SideEffects. + for var in self._get_modified_vars(): + if not isinstance(var.mutation_type, AttributeMutationNew): + if var.source is None: + raise AssertionError( + f"Expected source for modified var {var} " + "with non-new mutation type" + ) + continue + + # Namedtuples/structseqs with no pending mutations should skip + # codegen_save_tempvars so that restore_stack handles them. In + # export, restore_stack uses value_from_source=False which makes + # child tensors become graph outputs. If we processed them here, + # add_cache would assign a TempLocalSource and restore_stack would + # load from cache with value_from_source=True, hiding the tensors + # from export. + if isinstance( + var, + (variables.NamedTupleVariable, variables.StructSequenceVariable), + ) and not self.has_pending_mutation(var): + continue + + # Sourceless enum members registered with AttributeMutationNew + # don't need __new__-based tempvar reconstruction -- they are + # reconstructible as constants. + if ( + var.is_python_constant() + and isinstance(var.mutation_type, AttributeMutationNew) + and isinstance(var, variables.UserDefinedObjectVariable) + and ( + isinstance( + var.value, + ( + enum.Enum, + torch.DispatchKey, + torch._C._functorch.TransformType, + ), + ) + or is_pybind11_enum_member(var.value) + ) + ): + continue + + if isinstance(var, variables.CellVariable): + # Cells created in the root frame are created either by + # `MAKE_CELL` or by them being in `co_cellvars`, so we only emit + # `make_cell` for the non-root-frame cells here. + # TODO generalize this so we never need to call `make_cell`. + if var.local_name is None: + cg.add_push_null( + lambda: cg.load_import_from(utils.__name__, "make_cell") + ) + cg.extend_output(create_call_function(0, False)) + cg.add_cache(var) + var.source = TempLocalSource(cg.tempvars[var]) # type: ignore[attr-defined] + elif var.source is None: + var.source = LocalCellSource(var.local_name) + elif var.is_tensor(): + # NOTE: for historical reasons we never assigned local sources + # to newly constructed tensor object, so we keep it that way. + # They are always loaded from output of the fx graph, so one can + # think of it as having a "OutputGraphSource" for codegen + # purposes. + # + # However, tensor subclass objects are different, because the + # reconstruction logic in `PyCodegen` loads the data tensor from + # graph output and then calls `as_subclass`, meaning we must + # assign a source to it to ensure we only reconstruct one + # subclass instance. + if isinstance( + var, variables.torch_function.TensorWithTFOverrideVariable + ): + # Don't codegen from temp source assigned from the 1st pass. + cg(var, allow_cache=False) + cg.add_cache(var) + # `add_cache` generates STORE and consumes TOS, but we never + # cleared it. TODO move this call into `add_cache` + cg.clear_tos() + var.source = TempLocalSource(cg.tempvars[var]) + elif isinstance(var, variables.AutogradFunctionContextVariable): + unimplemented( + gb_type="AutogradFunctionContextVariable escaped Dynamo-traced region", + context="", + explanation="We cannot reconstruct a torch.autograd.Function's context object.", + hints=[], + ) + elif isinstance(var, variables.ExceptionVariable): + # Exceptions cannot be built via object.__new__ (CPython rejects + # it), so reconstruct() constructs by calling the type. Cache + # the result so later references load the single instance; any + # __dict__ attributes replay in codegen_update_mutated. + var.reconstruct(cg) + cg.add_cache(var) + var.source = TempLocalSource(cg.tempvars[var]) + else: + # Reconstruct the bytecode for + # base_cls.__new__(user_cls, *args) + if isinstance(var, variables.UserDefinedObjectVariable): + + def load_new_method() -> None: + # pyrefly: ignore [missing-attribute] + if var.base_cls_vt is None: + raise AssertionError( + "base_cls_vt is None in load_new_method" + ) + cg(var.base_cls_vt) # type: ignore[attr-defined] + cg.extend_output([cg.create_load_attr("__new__")]) + + cg.add_push_null(load_new_method) + else: + cg.add_push_null( + lambda: cg.load_import_from(utils.__name__, "object_new") + ) + if var.mutation_type.cls_source is None: + unimplemented( + gb_type="Reconstruct user defined class without a source", + context=f"Class: {var.python_type().__name__}", + explanation=( + f"Cannot reconstruct an instance of {var.python_type().__name__} " + "that escapes the compiled region. This happens when the class is " + "defined dynamically (e.g., inside the compiled function) and the " + "class object itself has no source that can be reconstructed. " + "To fix this, move the class definition outside the compiled function " + "or prevent the object from escaping the compiled region." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + cg(var.mutation_type.cls_source) + + # Generate the args to the __new__ method + for arg in var.init_args: # type: ignore[attr-defined] + cg(arg) + + # Call the __new__ method + cg.extend_output(create_call_function(1 + len(var.init_args), False)) # type: ignore[attr-defined] + + cg.add_cache(var) + var.source = TempLocalSource(cg.tempvars[var]) + + # For frozen dataclasses, we must emit object.__setattr__ + # immediately after __new__ — before any other code can + # access the object. The suffix-based codegen in + # codegen_update_mutated runs too late: if intervening code + # calls __repr__ (e.g. f-strings), the attributes won't be + # set yet. + if ( + isinstance(var, variables.FrozenDataClassVariable) + and var in self.store_attr_mutations + ): + for name, value in self.store_attr_mutations[var].items(): + cg.load_import_from("builtins", "object") + cg.load_method("__setattr__") + cg(var.source) + cg(variables.ConstantVariable(name)) + cg(value) + cg.extend_output( + [*create_call_method(3), create_instruction("POP_TOP")] + ) + + for ctx, args in self.save_for_backward: + cg(ctx.source) + cg.load_method("save_for_backward") + for arg in args: + cg(arg) + cg.extend_output( + [ + *create_call_method(len(args)), + create_instruction("POP_TOP"), + ] + ) + + def register_hook( + self, + tensor: "variables.TensorVariable", + hook: VariableTracker, + handle: "variables.RemovableHandleVariable", + name: str, + ) -> None: + if not tensor.is_tensor(): + raise AssertionError( + f"Expected tensor variable, got {type(tensor)} in register_hook" + ) + if not isinstance(hook, variables.VariableTracker): + raise AssertionError(f"Expected VariableTracker for hook, got {type(hook)}") + if not isinstance(handle, variables.RemovableHandleVariable): + raise AssertionError( + f"Expected RemovableHandleVariable, got {type(handle)}" + ) + if not handle.is_mutable(): + raise AssertionError("handle must be mutable in register_hook") + if not hasattr(torch.Tensor, name): + raise AssertionError(f"torch.Tensor has no attribute '{name}'") + idx = len(self.tensor_hooks.keys()) + # duplicate index possible because of self.remove_hook() + while idx in self.tensor_hooks: + idx += 1 + self.tensor_hooks[idx] = (tensor, hook, handle, name) + if handle.idx: + raise AssertionError(f"handle.idx should be falsy, got {handle.idx}") + handle.idx = idx + + def remove_hook(self, idx: int) -> None: + del self.tensor_hooks[idx] + + def codegen_hooks(self, cg: PyCodegen) -> None: + for ( + tensor, + hook, + handle, + name, + ) in self.tensor_hooks.values(): + # Note: [On tensor.register_hook] + # + # register_hook on a tensor, AKA backward hooks, have slightly nuanced differences in how they are implemented + # when it comes to hooks on objects with sources (inputs, params) vs objects without sources (intermediaries). + # + # For tensors with a source, we bypass direct inclusion of register_hook calls in the graph. + # Instead, these are tracked and stashed as a global variable, enabling their association with tensors in + # the residuals. During dynamo's frame creation, these hooks are invoked seamlessly on known reconstructible/fetch-able + # tensors. Because a source indicates knowledge of this object outside the torch compile region, and + # because we are running residuals firmly before .backward() can be run, it is sound to invoke + # `register_hook` on a known tensor. + # + # For tensors without a source, we support a limited subset of hooks. Global functions only, and + # compiled_autograd must be enabled or we will graph break. + # + # Handling the Handle: When a user retains the register_hook result in a handle, we intercept the + # STORE_FAST operation to record the user-designated local variable name. This ensures the reconstructed + # bytecode retains this name. If no handle is defined, we simply pop the generated value to keep the + # stack intact. + # + # Dynamo Tensor Hooks Workflow: + # - Functions passed to register_hook are lifted globally. + # - For tensors with sources: + # - In the "side_effects" phase of codegen, we iterate over tensors with hooks to: + # - Generate the tensor. + # - Issue a register_hook call on the tensor, linking to the globally stored function. + # - Incorporate a handle if one was established in the eager phase. + # - For tensors without sources: + # - We don't generate any instructions for registering a hook. + # - Handles from intermediary hooks are NYI. + # - We produce a call function that utilizes the trace_wrapped higher order op, closing over it. + # - We then manually insert the call function above into the graph. + # - The handle's exact user-specified name, "user_code_variable_name", is discerned and associated during STORE_FAST. + if not tensor.source: + raise AssertionError( + "Hooks on non input tensors NYI - should not get here" + ) + + def gen_fn() -> None: + cg(tensor) + cg.extend_output([cg.create_load_attr(name)]) + + cg.add_push_null(gen_fn) + cg(hook) + cg.extend_output(create_call_function(1, False)) + + # Adding the handle to the cache means RemovableHandleVariable().reconstruct() will + # be associated with the return value of register_hook(). This consumes the top of stack. + cg.add_cache(handle) + + def get_ca_final_callbacks_var(self) -> "variables.ListVariable": + from .variables.base import ValueMutationNew + + if self.ca_final_callbacks_var is None: + self.ca_final_callbacks_var = variables.ListVariable( + [], mutation_type=ValueMutationNew() + ) + + return self.ca_final_callbacks_var + + def _format_side_effect_message(self, var: VariableTracker) -> str: + """Format a side effect log message with user stack.""" + if config.side_effect_replay_policy == "silent": + raise AssertionError( + "_format_side_effect_message should not be called " + "when side_effect_replay_policy is 'silent'" + ) + locations = self.mutation_user_stacks.get(var, []) + description = f"Mutating object of type {var.python_type_name()}" + source_info = " (no source)" + if var.source is not None: + if isinstance(var.source, TempLocalSource): + source_info = " (source: created in torch.compile region)" + elif isinstance(var, variables.CellVariable) and var.local_name is not None: + source_info = f" (source: {var.local_name})" + elif isinstance( + var, variables.torch_function.TorchFunctionModeStackVariable + ): + source_info = " (source: torch function mode stack mutation)" + else: + # NOTE: NotImplementedError from var.source.name is a bug and must be fixed! + source_info = f" (source name: {var.source.name})" + + if locations: + # Format and dedupe stacks using tuple representation for efficiency + seen = set() + unique_formatted_stacks: list[str] = [] + stack_above_dynamo = collapse_resume_frames(get_stack_above_dynamo()) + for stack in locations: + # Use tuple of frame info for fast deduplication + # Include position info (colno, end_lineno, end_colno) to distinguish + # multiple mutations on the same line (when available in Python 3.11+) + stack_tuple = tuple( + ( + f.filename, + f.lineno, + f.name, + f.line, + getattr(f, "colno", None), + getattr(f, "end_lineno", None), + getattr(f, "end_colno", None), + ) + for f in stack + ) + if stack_tuple not in seen: + seen.add(stack_tuple) + stack_augmented = collapse_resume_frames(stack_above_dynamo + stack) + unique_formatted_stacks.append( + "".join(traceback.format_list(stack_augmented)) + ) + formatted_lines: str = "\n********\n\n".join(unique_formatted_stacks) + log_str = f"{description}{source_info}\n\n{textwrap.indent(formatted_lines, ' ')}" + else: + log_str = ( + f"{description}{source_info} (unable to find user stacks for mutations)" + ) + + return log_str + + def _emit_side_effect_messages(self, side_effect_messages: list[str]) -> None: + if not side_effect_messages: + return + + for msg in side_effect_messages: + side_effects_log.debug(msg) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_side_effects", + "encoding": "string", + }, + payload_fn=lambda: "\n\n========================================\n\n".join( + side_effect_messages + ), + ) + + def codegen_update_mutated( + self, cg: PyCodegen, log_side_effects: bool = False + ) -> None: + side_effect_messages: list[str] = [] + + # NOTE: should only be called once per VT - only if a side effect actually gets codegen'd! + def _maybe_log_side_effect(var: VariableTracker) -> None: + if config.side_effect_replay_policy != "silent" and log_side_effects: + msg = self._format_side_effect_message(var) + side_effect_messages.append(msg) + + suffixes: list[list[Instruction]] = [] + for var in self._get_modified_vars(): + # When replay_side_effects=False, only update variables with TempLocalSource + if not config.replay_side_effects and not isinstance( + var.source, TempLocalSource + ): + continue + + ctx = SideEffectReplayContext( + side_effects=self, + codegen=cg, + var=var, + suffixes=suffixes, + log=_maybe_log_side_effect, + ) + handler = _side_effect_replay_registry.lookup_handler(ctx) + if handler is None: + raise AssertionError(type(var)) + handler.codegen(ctx) + + # do all the actual mutations at the very end to handle dependencies + for suffix in reversed(suffixes): + cg.extend_output(suffix) + + # Send batched structured trace for all side effects in this compilation + if log_side_effects and side_effect_messages: + self._emit_side_effect_messages(side_effect_messages) + + def log_side_effects_summary(self) -> None: + if config.side_effect_replay_policy == "silent": + return + if not side_effects_log.isEnabledFor(logging.DEBUG): + return + for var in self._get_modified_vars(): + msg = self._format_side_effect_message(var) + side_effects_log.debug(msg) + + def is_empty(self) -> bool: + return not ( + any(map(self.is_modified, self.id_to_variable.values())) + or self.tensor_hooks + or self.save_for_backward + or self.tensor_hooks + ) + + def clear(self) -> None: + self.keepalive.clear() + self.id_to_variable.clear() + + +@register_side_effect_replay_handler( + name="list_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.ListVariable), + priority=90, +) +def _codegen_list_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.ListVariable): + raise AssertionError(type(var)) + # old[:] = new + cg(var, allow_cache=False) # Don't codegen via source + cg(var.source) # type: ignore[attr-defined] + cg.extend_output( + [ + cg.create_load_const(None), + cg.create_load_const(None), + create_instruction("BUILD_SLICE", arg=2), + ] + ) + ctx.suffixes.append([create_instruction("STORE_SUBSCR")]) + ctx.log(var) + + +@register_side_effect_replay_handler( + name="deque_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.lists.DequeVariable), + priority=80, +) +def _codegen_deque_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.lists.DequeVariable): + raise AssertionError(type(var)) + # For limited maxlen, the order of operations matter for side effect, but we + # currently don't track the order, so no support. + if not var.maxlen.is_constant_none(): + unimplemented( + gb_type="Side effect on existing deque with limited maxlen", + context="", + explanation="This is not supported.", + hints=[ + "Don't use a deque with `maxlen` specified.", + ], + ) + + # old.extend(new), this runs last + cg(var.source) + cg.load_method("extend") + cg(var, allow_cache=False) # Don't codegen via source + ctx.suffixes.append( + [ + *create_call_method(1), + create_instruction("POP_TOP"), + ] + ) + + # old.clear(), this runs first + cg(var.source) + cg.load_method("clear") + ctx.suffixes.append( + [ + *create_call_method(0), + create_instruction("POP_TOP"), + ] + ) + ctx.log(var) + + +@register_side_effect_replay_handler( + name="const_dict_or_set_mutation", + matcher=lambda ctx: isinstance( + ctx.var, (variables.ConstDictVariable, variables.SetVariable) + ), + priority=70, +) +def _codegen_const_dict_or_set_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, (variables.ConstDictVariable, variables.SetVariable)): + raise AssertionError(type(var)) + # Reconstruct works as follow: + # (1) Skip codegen if there are no new items + # (2) codegen(...) each pair of key/value + # (3) create a new dictionary with the pairs of key/values above + # (4) clear the original dictionary + # + only if a key was removed from the input dict + # (5) update the original dictionary with the dict created in (2) + if var.has_new_items(): + cg(var.source) # type: ignore[attr-defined] + cg.load_method("update") + cg(var, allow_cache=False) # Don't codegen via source + + if var.should_reconstruct_all: + cg(var.source) # type: ignore[attr-defined] + cg.load_method("clear") + + ctx.suffixes.append( + [ + *create_call_method(1), # update + create_instruction("POP_TOP"), + ] + ) + + if var.should_reconstruct_all: + # clear will appear before "update" as the suffixes are applied in + # reverse order. + ctx.suffixes.append( + [ + *create_call_method(0), # clear + create_instruction("POP_TOP"), + ] + ) + ctx.log(var) + + +@register_side_effect_replay_handler( + name="torch_function_mode_stack_mutation", + matcher=lambda ctx: isinstance( + ctx.var, variables.torch_function.TorchFunctionModeStackVariable + ), + priority=60, +) +def _codegen_torch_function_mode_stack_mutation( + ctx: SideEffectReplayContext, +) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.torch_function.TorchFunctionModeStackVariable): + raise AssertionError(type(var)) + cg.add_push_null( + lambda: cg.load_import_from(utils.__name__, "set_torch_function_mode_stack") + ) + + cg.foreach(var.symbolic_stack) + cg.append_output(create_instruction("BUILD_LIST", arg=len(var.symbolic_stack))) + cg.call_function(1, False) + cg.append_output(create_instruction("POP_TOP")) + ctx.log(var) + + +@register_side_effect_replay_handler( + name="cell_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.CellVariable) + and ctx.var.local_name is not None, + priority=50, +) +def _codegen_cell_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.CellVariable): + raise AssertionError(type(var)) + if var.local_name is None: + raise AssertionError("cell mutation local name must be set") + # Emit more readable and performant bytecode. + # TODO generalize this for cells created during inlining. + if var in ctx.side_effects.store_attr_mutations: + contents_var = ctx.side_effects.load_cell(var) + cg(contents_var) + ctx.suffixes.append([cg.create_store_deref(var.local_name)]) + ctx.log(var) + + +def _codegen_user_defined_dict_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.UserDefinedDictVariable): + raise AssertionError(type(var)) + # Do dict related update manually here. The store_attr mutations will be + # applied later. + varname_map = {} + for name in _manual_dict_setitem.__code__.co_varnames: + varname_map[name] = cg.tx.output.new_var() + + try: + mro_index = type(var.value).__mro__.index(collections.OrderedDict) + except ValueError: + mro_index = type(var.value).__mro__.index(dict) + + cg.extend_output( + [ + create_instruction("LOAD_CONST", argval=mro_index), + create_instruction("STORE_FAST", argval=varname_map["mro_index"]), + ] + ) + + cg(var.source) # type: ignore[attr-defined] + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["dict_to"]), + ] + ) + + # Reconstruct all items - _manual_dict_setitem clears dict_to first, so we + # need every key/value, not just the ones that differ from original_items. + var._base_vt.should_reconstruct_all = True # type: ignore[union-attr] + cg(var._base_vt, allow_cache=False) # Don't codegen via source + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["dict_from"]), + ] + ) + + dict_update_insts = bytecode_from_template( + _manual_dict_setitem, varname_map=varname_map + ) + + ctx.suffixes.append( + [ + *dict_update_insts, + create_instruction("POP_TOP"), + ] + ) + ctx.log( + var._base_vt # pyrefly: ignore[bad-argument-type] + ) + + +def _codegen_user_defined_list_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.UserDefinedListVariable): + raise AssertionError(type(var)) + # Update the list to the updated items. Be careful in calling the list + # methods and not the overridden methods. + varname_map = {} + for name in _manual_list_update.__code__.co_varnames: + varname_map[name] = cg.tx.output.new_var() + + cg(var.source) # type: ignore[attr-defined] + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["list_to"]), + ] + ) + + cg(var._base_vt, allow_cache=False) # Don't codegen via source + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["list_from"]), + ] + ) + + list_update_insts = bytecode_from_template( + _manual_list_update, varname_map=varname_map + ) + + ctx.suffixes.append( + [ + *list_update_insts, + create_instruction("POP_TOP"), + ] + ) + ctx.log( + var._base_vt # pyrefly: ignore[bad-argument-type] + ) + + +def _codegen_user_defined_deque_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.UserDefinedDequeVariable): + raise AssertionError(type(var)) + # Update the deque to the updated items. Be careful in calling the deque + # methods and not the overridden methods. + varname_map = {} + for name in _manual_deque_update.__code__.co_varnames: + varname_map[name] = cg.tx.output.new_var() + + cg(var.source) # type: ignore[attr-defined] + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["deque_to"]), + ] + ) + + cg(var._base_vt, allow_cache=False) # Don't codegen via source + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["deque_from"]), + ] + ) + + deque_update_insts = bytecode_from_template( + _manual_deque_update, varname_map=varname_map + ) + + ctx.suffixes.append( + [ + *deque_update_insts, + create_instruction("POP_TOP"), + ] + ) + ctx.log( + var._base_vt # pyrefly: ignore[bad-argument-type] + ) + + +def _skip_attribute_mutation_replay(var: VariableTracker) -> bool: + # FrozenDataClassVariable attributes were emitted in codegen_save_tempvars + # right after __new__. Skip here to avoid double-emitting. + if isinstance(var.mutation_type, AttributeMutationNew) and isinstance( + var, variables.FrozenDataClassVariable + ): + return True + + # Sourceless enum members: mutations (like _inverted_ caching) already + # happened on the real object during tracing. + return ( + var.is_python_constant() + and isinstance(var.mutation_type, AttributeMutationNew) + and isinstance(var, variables.UserDefinedObjectVariable) + and ( + isinstance( + var.value, + ( + enum.Enum, + torch.DispatchKey, + torch._C._functorch.TransformType, + ), + ) + or is_pybind11_enum_member(var.value) + ) + ) + + +@register_side_effect_replay_handler( + name="attribute_mutation", + matcher=lambda ctx: ctx.side_effects.is_attribute_mutation(ctx.var), + priority=40, +) +def _codegen_attribute_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + side_effects = ctx.side_effects + if _skip_attribute_mutation_replay(var): + return + + if ( + isinstance(var, variables.UserDefinedDictVariable) + and side_effects.is_modified( + var._base_vt # pyrefly: ignore[bad-argument-type] + ) + and var._base_vt.has_new_items() # type: ignore[union-attr] + ): + _codegen_user_defined_dict_mutation(ctx) + elif isinstance( + var, variables.UserDefinedListVariable + ) and side_effects.is_modified( + var._base_vt # pyrefly: ignore[bad-argument-type] + ): + _codegen_user_defined_list_mutation(ctx) + elif isinstance( + var, variables.UserDefinedDequeVariable + ) and side_effects.is_modified( + var._base_vt # pyrefly: ignore[bad-argument-type] + ): + _codegen_user_defined_deque_mutation(ctx) + + # Applying mutations involves two steps: 1) Push all reconstructed objects + # onto the stack. 2) Call STORE_ATTR to apply the mutations. + # + # Dynamo must ensure that mutations are applied in the same order as in the + # original program. Therefore, two reverse operations occur below. + # + # The first reverse operation concerns `suffixes`. We apply suffixes in + # reverse order due to the way Python handles the stack. In Step 1, we push + # all reconstructed objects onto the stack, but the item at the top of the + # stack refers to the last attribute in the mutation order. If not fixed, + # this will apply the mutations of attributes in the reverse order. To + # account for this reversal, we iterate through the mutable attributes in + # reverse order. + side_effect_occurred = False + for name, value in reversed(side_effects.store_attr_mutations.get(var, {}).items()): + mutation_kind = side_effects.get_attr_mutation_kind(var, name) + if isinstance(var, variables.NewGlobalVariable): + cg.tx.output.update_co_names(name) + cg(value) + if not isinstance(var.source, GlobalSource): # type: ignore[attr-defined] + raise AssertionError( + f"Expected GlobalSource for NewGlobalVariable, " + f"got {type(var.source)}" # type: ignore[attr-defined] + ) + ctx.suffixes.append([create_instruction("STORE_GLOBAL", argval=name)]) + side_effect_occurred = True + elif isinstance(value, variables.DeletedVariable): + if ( + isinstance(var, variables.UserDefinedObjectVariable) + and mutation_kind is AttrMutationKind.INSTANCE_DICT + ): + original_dict = getattr(getattr(var, "value", None), "__dict__", {}) + # If the key only existed in the traced instance dict, the + # add/delete sequence is a replay no-op. + if name in original_dict: + cg.add_push_null( + lambda: cg.load_import_from( + utils.__name__, + "object_delattr_ignore_descriptor", + ) + ) + cg(var.source) # type: ignore[attr-defined] + cg(variables.ConstantVariable(name)) + ctx.suffixes.append( + [ + *create_call_function(2, False), + create_instruction("POP_TOP"), + ] + ) + side_effect_occurred = True + # GENERIC_SETATTR deletions on UDOV fall through to the normal + # DELETE_ATTR path below so descriptor semantics are preserved + # during replay. + elif isinstance(var.mutation_type, AttributeMutationExisting) and hasattr( + getattr(var, "value", None), name + ): + cg.tx.output.update_co_names(name) + cg(var.source) + ctx.suffixes.append([create_instruction("DELETE_ATTR", argval=name)]) + side_effect_occurred = True + elif ( + isinstance(var, variables.UserDefinedObjectVariable) + and mutation_kind is AttrMutationKind.INSTANCE_DICT + ): + cg.add_push_null( + lambda: cg.load_import_from( + utils.__name__, "object_setattr_ignore_descriptor" + ) + ) + cg(var.source) # type: ignore[attr-defined] + cg(variables.ConstantVariable(name)) + cg(value) + ctx.suffixes.append( + [ + *create_call_function(3, False), + create_instruction("POP_TOP"), + ] + ) + side_effect_occurred = True + elif ( + isinstance(var, variables.UserDefinedObjectVariable) + and var.needs_slow_setattr() + ): + # __setattr__ is defined on this object, so call object.__setattr__ + # directly. + cg.load_import_from("builtins", "object") + cg.load_method("__setattr__") + cg(var.source) # type: ignore[attr-defined] + cg(variables.ConstantVariable(name)) + cg(value) + ctx.suffixes.append([*create_call_method(3), create_instruction("POP_TOP")]) + side_effect_occurred = True + else: + cg.tx.output.update_co_names(name) + cg(value) + cg(var) + ctx.suffixes.append([create_instruction("STORE_ATTR", argval=name)]) + side_effect_occurred = True + + if side_effect_occurred: + ctx.log(var) + + +@register_side_effect_replay_handler( + name="list_iterator_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.ListIteratorVariable), + priority=30, +) +def _codegen_list_iterator_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.ListIteratorVariable): + raise AssertionError(type(var)) + for _ in range(var.index): + cg.add_push_null(lambda: cg.load_import_from(utils.__name__, "iter_next")) + cg(var.source) # type: ignore[attr-defined] + cg.call_function(1, False) + cg.pop_top() + ctx.log(var) + + +@register_side_effect_replay_handler( + name="count_iterator_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.CountIteratorVariable), + priority=20, +) +def _codegen_count_iterator_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.CountIteratorVariable): + raise AssertionError(type(var)) + for _ in range(var.advance_count): + cg.add_push_null(lambda: cg.load_import_from(utils.__name__, "iter_next")) + cg(var.source) # type: ignore[attr-defined] + cg.call_function(1, False) + cg.pop_top() + ctx.log(var) + + +@register_side_effect_replay_handler( + name="random_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.RandomVariable), + priority=10, +) +def _codegen_random_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.RandomVariable): + raise AssertionError(type(var)) + + def gen_fn() -> None: + cg(var.source) # type: ignore[attr-defined] + cg.load_attr("setstate") + + cg.add_push_null(gen_fn) + cg(var.wrap_state(var.random.getstate())) + + ctx.suffixes.append( + [ + *create_call_function(1, False), # setstate + create_instruction("POP_TOP"), + ] + ) + ctx.log(var) + + +@contextlib.contextmanager +def allow_side_effects_in_hop( + tx: "InstructionTranslatorBase", +) -> Generator[None, None, None]: + """Context manager to temporarily allow side effects with extra outputs. + + This is used for special cases (like FSDP functions) that need to perform + side effects even when the general policy is to disallow them. + """ + orig_val = tx.output.current_tracer.allow_side_effects_in_hop + try: + tx.output.current_tracer.allow_side_effects_in_hop = True + yield + finally: + tx.output.current_tracer.allow_side_effects_in_hop = orig_val + + +@contextlib.contextmanager +def allow_externally_visible_side_effects_in_subtracer( + tx: "InstructionTranslatorBase", +) -> Generator[None, None, None]: + orig_val = tx.output.current_tracer.unsafe_allow_externally_visible_side_effects + try: + tx.output.current_tracer.unsafe_allow_externally_visible_side_effects = True + tx.output.current_tracer.traced_with_externally_visible_side_effects = True + yield + finally: + tx.output.current_tracer.unsafe_allow_externally_visible_side_effects = orig_val + + +@contextlib.contextmanager +def disallow_side_effects_in_generator( + tx: "InstructionTranslatorBase", +) -> Generator[None, None, None]: + orig_val = tx.output.current_tracer.is_reconstructing_generator + try: + tx.output.current_tracer.is_reconstructing_generator = True + yield + finally: + tx.output.current_tracer.is_reconstructing_generator = orig_val diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/source.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/source.py new file mode 100644 index 0000000000000000000000000000000000000000..ee3005a8400865006c45c6c20846ac01b124e94b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/source.py @@ -0,0 +1,1440 @@ +""" +This module provides Source classes that track the origins of values in PyTorch Dynamo. +Sources represent where values come from (e.g. local variables, globals, attributes) and +are used for guard generation and code reconstruction during compilation. + +The module includes specialized sources for: +- Local variables and synthetic locals +- Global variables and constants +- Object attributes and method calls +- NN module specialization (specialized vs unspecialized) +- Random values and tensor properties +- Default argument handling +- FSDP (Fully Sharded Data Parallel) modules + +Sources play a key role in Dynamo's guard system by tracking value origins for +guard generation, and in code reconstruction by providing methods to rebuild +the code needed to recreate values. +""" + +import dataclasses +import enum +import functools +from collections.abc import Callable +from typing import Any, TYPE_CHECKING + +from torch import device as device_type +from torch._guards import ( + ChainedSource, + dataclass_with_cached_hash, + Guard, + GuardSource, + Source, +) + +from . import utils +from .bytecode_transformation import ( + create_binary_subscr, + create_build_tuple, + create_call_function, +) + + +if TYPE_CHECKING: + from .codegen import PyCodegen + +# It shouldn't be supported to construct an NNModuleVariable inside an FSDP module, +# so those cases are omitted intentionally + +# represents nn.Modules tracked with NNModuleVariable (specialized is implicit in the variable name) +_GUARD_SOURCE_SPECIALIZED_NN_MODULE = { + GuardSource.LOCAL: GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + GuardSource.GLOBAL: GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, + # Just to ensure that guard_source() works + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE, +} + +# represents nn.Modules tracked with UnspecializedNNModuleVariable +_GUARD_SOURCE_UNSPECIALIZED_NN_MODULE = { + GuardSource.LOCAL: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + # this happens for an UnspecializedNNModule submodule on a NNModuleVariable + GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + # Just to ensure that guard_source() works + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE, +} + +# represents nn.Modules tracked with UnspecializedBuiltinNNModuleVariable +_GUARD_SOURCE_UNSPECIALIZED_BUILTIN_NN_MODULE = { + GuardSource.LOCAL: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + # Just to ensure that guard_source() works + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE, +} + +_GUARD_SOURCE_FSDP_MODULE = { + GuardSource.LOCAL: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL: GuardSource.GLOBAL_FSDP_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_FSDP_MODULE, + GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_FSDP_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_FSDP_MODULE, +} + + +def is_constant_source(source: Source) -> bool: + if isinstance(source, ConstantSource): + return True + try: + if source.guard_source == GuardSource.CONSTANT: + return True + except NotImplementedError: + pass + + return False + + +def _get_source_debug_name(source: Source | None) -> str: + if source is None: + return "" + else: + try: + return source.name + except NotImplementedError: + return "" + + +def _esc_str(s: Any, apply_repr: bool = False) -> str: + """ + Escapes curly brackets for format strings. + e.g. "frozenset({0})" becomes "frozenset({{0}})". + This is used by _name_template for example, because it's + expected to return a format string, but we may wish to include + strings that should not be accidentally formatted. + """ + if apply_repr: + s = repr(s) + else: + s = str(s) + return s.replace("{", "{{").replace("}", "}}") + + +@dataclass_with_cached_hash(frozen=True) +class LocalSource(Source): + local_name: str + + # Whether this local is an input to the root frame. + is_input: bool = False + + # Whether we know this input is dynamic (based on example_inputs) + # For non tensors, we simply look at the first index of the tuple + dynamism: frozenset[str] | None = None + + # Whether the item at this source is the _content_ of a cell that is + # dereferenced from the root frame, i.e., it's a part of the `co_cellvars` + # or `co_freevars`. + is_derefed_cell_contents: bool = False + + # Whether this local is the function's varargs (``*args``) parameter. + # Set from ``co_flags & CO_VARARGS`` at frame-entry time. Element accesses + # like ``args[N]`` produce a ``GetItemSource`` whose base has this flag. + # Useful for distinguishing ``*args`` from a regular list-typed input. + # ``repr=False`` so the vast majority of locals (which are not varargs) do + # not get a noisy ``is_varargs=False`` in every debug string. + is_varargs: bool = dataclasses.field(default=False, repr=False) + + # Whether this local is the function's varkw (``**kwargs``) parameter. + # Set from ``co_flags & CO_VARKEYWORDS`` at frame-entry time. Element + # accesses like ``kwargs["k"]`` produce a ``DictGetItemSource`` whose base + # has this flag. ``repr=False`` for the same reason as ``is_varargs``. + is_varkw: bool = dataclasses.field(default=False, repr=False) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.is_derefed_cell_contents: + codegen.load_deref(self.local_name) + else: + codegen.append_output(codegen.create_load(self.local_name)) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + return self.local_name + + @property + def guard_source(self) -> GuardSource: + return GuardSource.LOCAL + + @functools.cached_property + def _name_template(self) -> str: + return f"L[{_esc_str(self.local_name, apply_repr=True)}]" + + +@dataclass_with_cached_hash(frozen=True) +class TempLocalSource(Source): + # like LocalSource, but cannot be guarded on + local_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.append_output(codegen.create_load(self.local_name)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.TEMP_LOCAL + + @property + def _name_template(self) -> str: + raise NotImplementedError( + "Cannot create guard on TempLocalSource - this is an internal Dynamo bug. Please file an issue on GitHub." + ) + + +@dataclass_with_cached_hash(frozen=True) +class SyntheticLocalSource(Source): + local_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.append_output(codegen.create_load(self.local_name)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.SYNTHETIC_LOCAL + + @functools.cached_property + def _name_template(self) -> str: + return f"SYNTHETIC_LOCAL[{_esc_str(self.local_name, apply_repr=True)}]" + + +@dataclass_with_cached_hash(frozen=True) +class RandomValueSource(Source): + random_call_index: int + + @property + def guard_source(self) -> GuardSource: + return GuardSource.RANDOM_VALUE + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.append_output(codegen.create_load(codegen.tx.output.random_values_var)) + codegen.append_output(codegen.create_load_const(self.random_call_index)) + codegen.append_output(create_binary_subscr()) + + @functools.cached_property + def _name_template(self) -> str: + return f"random_value_{_esc_str(self.random_call_index)}" + + +@dataclass_with_cached_hash(frozen=True) +class GlobalSource(Source): + global_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.append_output(codegen.create_load_global(self.global_name, add=True)) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + return self.global_name + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + @functools.cached_property + def _name_template(self) -> str: + return f"G[{_esc_str(self.global_name, apply_repr=True)}]" + + +@dataclass_with_cached_hash(frozen=True) +class GlobalWeakRefSource(Source): + global_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.append_output( + codegen.create_load_global(self.global_name, add=True) + ) + ) + codegen.extend_output(create_call_function(0, False)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + @functools.cached_property + def _name_template(self) -> str: + return f"G[{_esc_str(self.global_name, apply_repr=True)}]()" + + +@dataclass_with_cached_hash(frozen=True) +class WeakRefCallSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(self.base)) + codegen.extend_output(create_call_function(0, False)) + + @property + def _name_template(self) -> str: + return "{0}()" + + +@dataclass_with_cached_hash(frozen=True) +class CallFunctionNoArgsSource(WeakRefCallSource): + pass + + +@dataclass_with_cached_hash(frozen=True) +class AttrSource(ChainedSource): + member: str + + def __post_init__(self) -> None: + if not self.base: + raise AssertionError( + "Can't construct an AttrSource without a valid base source" + ) + if "." in self.member: + raise AssertionError( + f"AttrSource member must not contain '.', got {self.member!r}. " + "Use OutputGraph.get_chained_attr_source() for dotted paths." + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs(self.member)) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + base = self.base.reconstruct_pycode(codegen) + if self.member.isidentifier(): + return f"{base}.{self.member}" + else: + return f"getattr({base}, {self.member!r})" + + @functools.cached_property + def _name_template(self) -> str: + if not self.member.isidentifier(): + return f"getattr({{0}}, {_esc_str(self.member, apply_repr=True)})" + return f"{{0}}.{_esc_str(self.member)}" + + +@dataclass_with_cached_hash(frozen=True) +class CellContentsSource(AttrSource): + """ + Source for closure cell contents that also stores the freevar name. + This allows guard failure messages to show which variable the closure cell refers to. + """ + + freevar_name: str = dataclasses.field(default="") + + def __post_init__(self) -> None: + if not self.base: + raise AssertionError( + "Can't construct a CellContentsSource without a valid base source" + ) + if self.member != "cell_contents": + raise AssertionError( + "CellContentsSource should only be used for cell_contents" + ) + + +@dataclass_with_cached_hash(frozen=True) +class GenericAttrSource(ChainedSource): + member: str + + def __post_init__(self) -> None: + if not self.base: + raise AssertionError( + "Can't construct a GenericAttrSource without a valid base source" + ) + if "." in self.member: + raise AssertionError( + f"GenericAttrSource member must not contain '.', got {self.member!r}. " + "Use OutputGraph.get_chained_attr_source() for dotted paths." + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs(self.member)) + + @functools.cached_property + def _name_template(self) -> str: + return ( + f"object.__getattribute__({{0}}, {_esc_str(self.member, apply_repr=True)})" + ) + + +# Represents obj.__dict__ where obj is a type object +@dataclass_with_cached_hash(frozen=True) +class TypeDictSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("__dict__")) + + @property + def _name_template(self) -> str: + # type(ob).__dict__ can return a proxy of the dict. But in the C++ + # guard accessor, we use type->tp_dict which is a dict. So, + # forcefully pass a dict object to ensure that the GuardManager + # registers that it's working on a dict object. + return "dict({0}.__dict__)" + + +# Represents obj.__mro__ where object is type object +@dataclass_with_cached_hash(frozen=True) +class TypeMROSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("__mro__")) + + @property + def _name_template(self) -> str: + return "{0}.__mro__" + + +@dataclass_with_cached_hash(frozen=True) +class LocalCellSource(Source): + """ + Conceptually, this class is `LocalSource` for cell objects implicitly + generated by Python (e.g., captured variables). + """ + + local_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Although `LOAD_FAST` and `LOAD_CLOSURE` have the same semantics, + # Dynamo's bytecode transformation differentiates them slightly, so we + # always emit `LOAD_CLOSURE` here. + codegen.append_output(codegen.create_load_closure(self.local_name)) + + # All the other methods are intentionally unimplemented because e.g., a + # local cell object should never be used for guards. + + +# Represents obj.__code__ where object is type object +@dataclass_with_cached_hash(frozen=True) +class CodeSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("__code__")) + + @property + def _name_template(self) -> str: + return "{0}.__code__" + + +# Represents obj.__closure__ where object is type object +@dataclass_with_cached_hash(frozen=True) +class ClosureSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("__closure__")) + + @property + def _name_template(self) -> str: + return "{0}.__closure__" + + +# Represents tensor.grad source. It could be represented by AttrSource as well. +# But, we could access grad field on tensor directly in C++ without going +# through the Python bytecodes. Therefore, we use a separate source for grad +# field. +@dataclass_with_cached_hash(frozen=True) +class GradSource(ChainedSource): + member: str = "grad" + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs(self.member)) + + @functools.cached_property + def _name_template(self) -> str: + return f"{{0}}.{_esc_str(self.member)}" + + +@dataclass_with_cached_hash(frozen=True) +class ParamBufferSource(AttrSource): + @functools.cached_property + def guard_source(self) -> GuardSource: + return _GUARD_SOURCE_SPECIALIZED_NN_MODULE[self.base.guard_source] + + +# Special AttrSource to differentiate module._buffers or module._parameters +@dataclass_with_cached_hash(frozen=True) +class UnspecializedParamBufferSource(AttrSource): + pass + + +# This source is intended to be used in places where a source is needed but it is expected +# that the symbol will be simplified out later on. Symbols with ephemeral sources are +# prioritized to be simplified out when e.g. compared against a symbol without an ephemeral +# source. Guarding on this source is an error. +# +# Example: During subclass view fake-ification, any close-over ViewFunc state should be +# symbolicized / fake-ified to avoid invalid specialization during view replay. This source +# is useful for symbols utilized in the middle of the view chain that are not expected to be +# present within the final view shape metadata. +@dataclass_with_cached_hash(frozen=True) +class EphemeralSource(Source): + desc: str | None = None + + @property + def guard_source(self) -> GuardSource: + return GuardSource.EPHEMERAL + + @functools.cached_property + def _name_template(self) -> str: + desc = ": " + self.desc if self.desc is not None else "" + return f"" + + def make_guard(self, fn: Callable[..., Any]) -> Guard: + raise NotImplementedError + + def is_ephemeral(self) -> bool: + return True + + +@dataclass_with_cached_hash(frozen=True) +class SkipGuardSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + self.base.reconstruct(codegen) + + @property + def _name_template(self) -> str: + return "{0}" + + +class TensorProperty(enum.Enum): + SIZE = 0 + STRIDE = 1 + STORAGE_OFFSET = 2 + + def method_name(self) -> str: + if self is TensorProperty.SIZE: + return "size" + elif self is TensorProperty.STRIDE: + return "stride" + elif self is TensorProperty.STORAGE_OFFSET: + return "storage_offset" + else: + raise AssertionError(f"unhandled {_esc_str(self)}") + + +@dataclass_with_cached_hash(frozen=True) +class TensorPropertySource(ChainedSource): + prop: TensorProperty + idx: int | None = None # None for STORAGE_OFFSET + + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("TensorPropertySource base must not be None") + if self.prop is TensorProperty.STORAGE_OFFSET: + if self.idx is not None: + raise AssertionError( + "idx must be None for STORAGE_OFFSET TensorProperty" + ) + else: + if self.idx is None: + raise AssertionError( + f"idx must not be None for {self.prop} TensorProperty" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + utils.__name__, f"call_{_esc_str(self.prop.method_name())}" + ) + ) + codegen(self.base) + + if self.idx is not None: + codegen.append_output(codegen.create_load_const(self.idx)) + codegen.extend_output( + create_call_function(2 if self.idx is not None else 1, False) + ) + + @functools.cached_property + def _name_template(self) -> str: + if self.prop is TensorProperty.SIZE: + return f"{{0}}.size()[{_esc_str(self.idx)}]" + elif self.prop is TensorProperty.STRIDE: + return f"{{0}}.stride()[{_esc_str(self.idx)}]" + elif self.prop is TensorProperty.STORAGE_OFFSET: + if self.idx is not None: + raise AssertionError( + "idx must be None for STORAGE_OFFSET TensorProperty" + ) + return "{0}.storage_offset()" + else: + raise AssertionError(f"unhandled {_esc_str(self.prop)}") + + +@dataclass_with_cached_hash(frozen=True) +class IndexedSource(ChainedSource): + idx: int + + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("IndexedSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + raise NotImplementedError + + @functools.cached_property + def _name_template(self) -> str: + return f"({_esc_str(self.idx)}, {{0}})" + + +@dataclass_with_cached_hash(frozen=True) +class NegateSource(ChainedSource): + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("NegateSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + raise NotImplementedError + + @property + def _name_template(self) -> str: + # NB: use method call so that function stripping regexes work + return "{0}.__neg__()" + + +@dataclass_with_cached_hash(frozen=True) +class ConvertIntSource(ChainedSource): + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("ConvertIntSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + @property + def _name_template(self) -> str: + return "cast_symbool_to_symint_guardless({0})" + + +@dataclass_with_cached_hash(frozen=True) +class DynamicScalarSource(ChainedSource): + is_int: bool + + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("DynamicScalarSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Integer casting at reconstruction helps reduce the amount of DynamicInts returned + # to the user, in favor of plain ints. + # For example, a compiled region that only does int arithmetic could return a + # DynamicInt without the casting here. + codegen.add_push_null(lambda: codegen.load_import_from("builtins", "int")) + codegen(self.base) + codegen.extend_output(create_call_function(1, False)) + + @property + def _name_template(self) -> str: + return "int({0})" + + +@dataclass_with_cached_hash(frozen=True) +class FlattenScriptObjectSource(ChainedSource): + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("FlattenScriptObjectSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + @property + def _name_template(self) -> str: + return "{0}.__obj_flatten__()" + + +@dataclass_with_cached_hash(frozen=True) +class ScriptObjectQualifiedNameSource(ChainedSource): + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError( + "ScriptObjectQualifiedNameSource base must not be None" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + @property + def _name_template(self) -> str: + return "{0}._type().qualified_name()" + + +class AttrProxySource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + @property + def _name_template(self) -> str: + return "{0}.get_base()" + + +@dataclass_with_cached_hash(frozen=True) +class DefaultsSource(ChainedSource): + idx_key: int | str + is_kw: bool = False + field: str = dataclasses.field(init=False, repr=False, compare=False) + _name: str = dataclasses.field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + if not self.base: + raise AssertionError( + "Base must be a valid source in order to properly track and guard this Defaults to its origin." + ) + if self.is_kw: + if not isinstance(self.idx_key, str): + raise AssertionError( + f"idx_key must be a str for keyword defaults, got {type(self.idx_key)}" + ) + object.__setattr__(self, "field", "__kwdefaults__") + object.__setattr__( + self, + "_name", + f"{{0}}.{_esc_str(self.field)}['{_esc_str(self.idx_key)}']", + ) + else: + if not isinstance(self.idx_key, int): + raise AssertionError( + f"idx_key must be an int for positional defaults, got {type(self.idx_key)}" + ) + object.__setattr__(self, "field", "__defaults__") + object.__setattr__( + self, "_name", f"{{0}}.{_esc_str(self.field)}[{_esc_str(self.idx_key)}]" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs(self.field)) + codegen.append_output(codegen.create_load_const(self.idx_key)) + codegen.append_output(create_binary_subscr()) + + @functools.cached_property + def _name_template(self) -> str: + return self._name + + +@dataclass_with_cached_hash(frozen=True) +class GetItemSource(ChainedSource): + index: Any + index_is_slice: bool = False + + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("GetItemSource base must not be None") + if isinstance(self.index, slice): + # store the hashable version of the slice so the whole GetItemSource is hashable + super().__setattr__("index", self.index.__reduce__()) + super().__setattr__("index_is_slice", True) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + if self.index_is_slice: + codegen.append_output(codegen.create_load_const(self.unpack_slice())) + else: + codegen.append_output(codegen.create_load_const(self.index)) + codegen.append_output(create_binary_subscr()) + + def unpack_slice(self) -> slice: + if not self.index_is_slice: + raise AssertionError("unpack_slice called but index is not a slice") + slice_class, slice_args = self.index + return slice_class(*slice_args) + + @functools.cached_property + def _name_template(self) -> str: + # Index can be of following types + # 1) index is a slice - example 1:4 + # 2) index is a constant - example string, integer + if isinstance(self.index, Source): + raise AssertionError( + f"GetItemSource index must not be a Source, got {type(self.index)}" + ) + if self.index_is_slice: + return f"{{0}}[{_esc_str(self.unpack_slice(), apply_repr=True)}]" + else: + return f"{{0}}[{_esc_str(self.index, apply_repr=True)}]" + + +@dataclass_with_cached_hash(frozen=True) +class ConstDictKeySource(ChainedSource): + index: Any + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "dict_keys_getitem") + ) + codegen(self.base) + codegen.append_output(codegen.create_load_const(self.index)) + codegen.extend_output(create_call_function(2, False)) + + @functools.cached_property + def _name_template(self) -> str: + # The list creation will be CSE'd by PyExprCSEPass + return f"list(dict.keys({{0}}))[{_esc_str(self.index, apply_repr=True)}]" + + def is_dict_key(self) -> bool: + return True + + +@dataclass_with_cached_hash(frozen=True) +class NonSerializableSetGetItemSource(ChainedSource): + index: int + + def __post_init__(self) -> None: + from .variables import ConstantVariable + + if not ConstantVariable.is_literal(self.index): + raise AssertionError( + f"NonSerializableSetGetItemSource index must be a literal, got {self.index!r}" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "set_getitem") + ) + codegen(self.base) + codegen.append_output(codegen.create_load_const(self.index)) + codegen.extend_output(create_call_function(2, False)) + + def get_value( + self, + globals: dict[str, Any], + locals: dict[str, Any], + cache: dict[Source, Any], + ) -> Any: + if self in cache: + return cache[self] + value = utils.set_getitem( + self.base.get_value(globals, locals, cache), self.index + ) + cache[self] = value + return value + + @functools.cached_property + def _name_template(self) -> str: + # set ordering might not be stable + return f"___set_getitem({{0}}, {_esc_str(self.index, apply_repr=True)})" + + def is_dict_key(self) -> bool: + return False + + +# Used to access an item from the dictionary +@dataclass_with_cached_hash(frozen=True) +class DictGetItemSource(ChainedSource): + # Key to access in the dictionary. It can be one of the following types + # 1) ConstDictKeySource + # 2) constant - like string, integer + index: Any + + def __post_init__(self) -> None: + from .variables import ConstantVariable + + if not isinstance( + self.index, ConstDictKeySource + ) and not ConstantVariable.is_literal(self.index): + raise AssertionError( + f"DictGetItemSource index must be a ConstDictKeySource or literal, got {self.index!r}" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Load dict + codegen(self.base) + + # Load key + if isinstance(self.index, Source): + codegen(self.index) + else: + codegen.append_output(codegen.create_load_const(self.index)) + codegen.append_output(create_binary_subscr()) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + base = self.base.reconstruct_pycode(codegen) + if isinstance(self.index, ConstDictKeySource): + index = self.index.reconstruct_pycode(codegen) + else: + index = repr(self.index) + return f"{base}[{index}]" + + @functools.cached_property + def _name_template(self) -> str: + if isinstance(self.index, ConstDictKeySource): + return f"{{0}}[{_esc_str(self.index.name)}]" + else: + return f"{{0}}[{_esc_str(self.index, apply_repr=True)}]" + + +# Same as DictGetItemSource but used for dict.__getitem__ calls to ensure that +# torch.compile does not run the overridden __getitem__ method +@dataclass_with_cached_hash(frozen=True) +class DictSubclassGetItemSource(ChainedSource): + # Key to access in the dictionary. It can be one of the following types + # 1) ConstDictKeySource + # 2) constant - like string, integer + index: Any + + def __post_init__(self) -> None: + from .variables import ConstantVariable + + if not isinstance( + self.index, ConstDictKeySource + ) and not ConstantVariable.is_literal(self.index): + raise AssertionError( + f"DictSubclassGetItemSource index must be a ConstDictKeySource or literal, got {self.index!r}" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # reconstruct dict.__getitem__(dct, key) + + # Load dict.__getitem__ + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "dict_getitem") + ) + + # Load dict + codegen(self.base) + + # Load key + if isinstance(self.index, Source): + codegen(self.index) + else: + codegen.append_output(codegen.create_load_const(self.index)) + + codegen.extend_output(create_call_function(2, False)) + + @functools.cached_property + def _name_template(self) -> str: + if isinstance(self.index, ConstDictKeySource): + return f"dict.__getitem__({{0}}, {_esc_str(self.index.name)})" + else: + return f"{{0}}[{_esc_str(self.index, apply_repr=True)}]" + + +@dataclass_with_cached_hash(frozen=True) +class ListGetItemSource(GetItemSource): + """ + Same as GetItemSource with reconstruct and name overridden to be list specific. + """ + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Reconstruct list.__getitem__(lst, index) to avoid any side effects + # from possibly overridden __getitem__. + + # Load list.__getitem__ + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "list_getitem") + ) + + # Load the list + codegen(self.base) + + # Load the index + if self.index_is_slice: + raise RuntimeError( + "List[slice] is a temporary object and should not have a source" + ) + else: + codegen.append_output(codegen.create_load_const(self.index)) + + codegen.extend_output(create_call_function(2, False)) + + @functools.cached_property + def _name_template(self) -> str: + # Index can be of following types + # 1) index is a slice - example 1:4 + # 2) index is a constant - example string, integer + if isinstance(self.index, Source): + raise AssertionError( + f"ListGetItemSource index must not be a Source, got {type(self.index)}" + ) + if self.index_is_slice: + raise RuntimeError( + "List[slice] is a temporary object and should not have a source" + ) + else: + return f"list.__getitem__({{0}}, {_esc_str(self.index, apply_repr=True)})" + + +@dataclass_with_cached_hash(frozen=True) +class TupleIteratorGetItemSource(GetItemSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "tuple_iterator_getitem") + ) + codegen(self.base) + codegen.append_output(codegen.create_load_const(self.index)) + codegen.extend_output(create_call_function(2, False)) + + @functools.cached_property + def _name_template(self) -> str: + return ( + f"___tuple_iterator_getitem({{0}}, {_esc_str(self.index, apply_repr=True)})" + ) + + +@dataclass_with_cached_hash(frozen=True) +class NamedTupleFieldsSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("_fields")) + + @property + def _name_template(self) -> str: + return "___namedtuple_fields({0})" + + +@dataclass_with_cached_hash(frozen=True) +class DataclassFieldsSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "dataclass_fields") + ) + codegen(self.base) + codegen.extend_output(create_call_function(1, False)) + + @property + def _name_template(self) -> str: + return "___dataclass_fields({0})" + + +@dataclass_with_cached_hash(frozen=True) +class TypeSource(ChainedSource): + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("TypeSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("builtins", "type")) + codegen(self.base) + codegen.extend_output(create_call_function(1, False)) + + @property + def _name_template(self) -> str: + return "type({0})" + + +@dataclass_with_cached_hash(frozen=True) +class OptimizerSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + @property + def _name_template(self) -> str: + return "{0}" + + +@dataclass_with_cached_hash(frozen=True) +class NNModuleSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + return self.base.reconstruct_pycode(codegen) + + @functools.cached_property + def guard_source(self) -> GuardSource: + return _GUARD_SOURCE_SPECIALIZED_NN_MODULE[self.base.guard_source] + + @property + def _name_template(self) -> str: + return "{0}" + + +@dataclass_with_cached_hash(frozen=True) +class UnspecializedNNModuleSource(NNModuleSource): + @functools.cached_property + def guard_source(self) -> GuardSource: + return _GUARD_SOURCE_UNSPECIALIZED_NN_MODULE[self.base.guard_source] + + +@dataclass_with_cached_hash(frozen=True) +class UnspecializedBuiltinNNModuleSource(UnspecializedNNModuleSource): + @functools.cached_property + def guard_source(self) -> GuardSource: + return _GUARD_SOURCE_UNSPECIALIZED_BUILTIN_NN_MODULE[self.base.guard_source] + + +@dataclass_with_cached_hash(frozen=True) +class FSDPNNModuleSource(NNModuleSource): + @functools.cached_property + def guard_source(self) -> GuardSource: + return _GUARD_SOURCE_FSDP_MODULE[self.base.guard_source] + + +@dataclass_with_cached_hash(frozen=True) +class GlobalStateSource(Source): + @property + def _name_template(self) -> str: + return "" + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + +@dataclass_with_cached_hash(frozen=True) +class ImportSource(Source): + """Points to an imported module - used instead of GlobalSource + in case the user has overridden the module name in their local namespace""" + + module_name: str + + @functools.cached_property + def _name_template(self) -> str: + return f"__import__('{self.module_name}')" + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.extend_output( + [ + codegen.create_load_const(0), # level + create_build_tuple(0), # fromlist + codegen.create_import_name(self.module_name), + ] + ) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + +@dataclass_with_cached_hash(frozen=True) +class TorchFunctionModeStackSource(Source): + ind: int + + @functools.cached_property + def _name_template(self) -> str: + return f"___get_torch_function_mode_stack_at({_esc_str(self._get_index())})" + + def _get_index(self) -> int: + from .variables.torch_function import TorchFunctionModeStackVariable + + return TorchFunctionModeStackVariable.get_mode_index(self.ind) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + utils.__name__, "get_torch_function_mode_stack_at" + ) + ) + codegen.extend_output([codegen.create_load_const(self._get_index())]) + codegen.extend_output(create_call_function(1, False)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + +@dataclass_with_cached_hash(frozen=True) +class ConstantSource(Source): + source_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.append_output(codegen.create_load_global(self.source_name, add=False)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.CONSTANT + + @functools.cached_property + def _name_template(self) -> str: + return self.source_name + + def make_guard(self, fn: Any) -> Any: + raise NotImplementedError + + +@dataclass_with_cached_hash(frozen=True) +class NumpyTensorSource(ChainedSource): + @property + def _name_template(self) -> str: + return "___from_numpy({0})" + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("torch", "as_tensor")) + codegen(self.base) + codegen.extend_output(create_call_function(1, False)) + + +@dataclass_with_cached_hash(frozen=True) +class SubclassAttrListSource(ChainedSource): + @property + def _name_template(self) -> str: + return "{0}.__tensor_flatten__()[0]" + + +# Guard-only source that yields the inner tensor of an AsyncCollectiveTensor +# (ACT) and the base value unchanged for a plain Tensor. Used to guard on the +# unwrapped tensor so a graph traced on an ACT can be reused when the resolved +# plain Tensor is passed at runtime. See +# torch._dynamo.variables.builder.VariableBuilder.wrap_tensor. +@dataclass_with_cached_hash(frozen=True) +class UnwrapCollectiveTensorSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + "torch._dynamo.guards", "unwrap_async_collective_tensor" + ) + ) + codegen(self.base) + codegen.extend_output(create_call_function(1, False)) + + @property + def _name_template(self) -> str: + return "___unwrap_async_collective_tensor({0})" + + +# NB: We don't expect you to actually ever generate guards against this +# source, it is ephemeral +@dataclass_with_cached_hash(frozen=True) +class FloatTensorSource(ChainedSource): + @property + def _name_template(self) -> str: + return "___as_tensor({0})" + + +@dataclass_with_cached_hash(frozen=True) +class CallMethodItemSource(ChainedSource): + @property + def _name_template(self) -> str: + return "{0}.item()" + + +@dataclass_with_cached_hash(frozen=True) +class ContextVarGetSource(ChainedSource): + has_default: bool = False + default_value: Any = None + + def reconstruct(self, codegen: "PyCodegen") -> None: + def load_get_method(): + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("get")) + + codegen.add_push_null(load_get_method) + if self.has_default: + codegen.append_output(codegen.create_load_const(self.default_value)) + codegen.extend_output(create_call_function(1, False)) + else: + codegen.extend_output(create_call_function(0, False)) + + @functools.cached_property + def _name_template(self) -> str: + if self.has_default: + return f"{{0}}.get({_esc_str(self.default_value, apply_repr=True)})" + return "{0}.get()" + + +# This is a synthetic source that is associated with the singleton +# shape env guard we always register for all frames. We get the actual +# guard contents from the ambient ShapeEnv +@dataclass_with_cached_hash(frozen=True) +class ShapeEnvSource(Source): + @property + def _name_template(self) -> str: + return "" + + @property + def guard_source(self) -> GuardSource: + return GuardSource.SHAPE_ENV + + +@dataclass_with_cached_hash(frozen=True) +class CurrentStreamSource(Source): + device: device_type + + @functools.cached_property + def _name_template(self) -> str: + return f"___get_current_stream(torch.device('{_esc_str(self.device.type)}', {_esc_str(self.device.index)}))" + + def reconstruct(self, codegen: "PyCodegen") -> None: + num_args = 1 + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "get_current_stream") + ) + codegen.add_push_null(lambda: codegen.load_import_from("torch", "device")) + codegen.extend_output([codegen.create_load_const(self.device.type)]) + if self.device.index is not None: + num_args += 1 + codegen.extend_output([codegen.create_load_const(self.device.index)]) + codegen.extend_output(create_call_function(num_args, False)) + codegen.extend_output(create_call_function(1, False)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + +@dataclass_with_cached_hash(frozen=True) +class BackwardStateSource(Source): + @property + def _name_template(self) -> str: + return "" + + @property + def guard_source(self) -> GuardSource: + return GuardSource.BACKWARD_STATE + + +@functools.lru_cache +def get_local_source_name( + source: Source, *, only_allow_input: bool = False +) -> str | None: + if isinstance(source, ChainedSource): + return get_local_source_name(source.base, only_allow_input=only_allow_input) + if not isinstance(source, LocalSource): + return None + if only_allow_input and not source.is_input: + return None + return source.local_name + + +@functools.lru_cache +def is_from_local_source(source: Source, *, only_allow_input: bool = False) -> bool: + return get_local_source_name(source, only_allow_input=only_allow_input) is not None + + +@functools.lru_cache +def is_from_global_source(source: Source) -> bool: + return get_global_source_name(source) is not None + + +@functools.lru_cache +def get_global_source_name(source: Source | None) -> str | None: + if isinstance(source, ChainedSource): + return get_global_source_name(source.base) + if not isinstance(source, GlobalSource): + return None + return source.global_name + + +@functools.lru_cache +def is_from_nonlocal_source(source: Source) -> bool: + if isinstance(source, ChainedSource): + return is_from_nonlocal_source(source.base) + return ( + isinstance(source, LocalSource) + and source.is_derefed_cell_contents + and not source.is_input + ) + + +@functools.lru_cache +def is_from_closure_source(source: Source) -> bool: + if isinstance(source, ClosureSource): + return True + if isinstance(source, ChainedSource): + return is_from_closure_source(source.base) + return False + + +@functools.lru_cache +def is_from_source(source: Source, target: Source) -> bool: + if source == target: + return True + if isinstance(source, ChainedSource): + return is_from_source(source.base, target) + return False + + +@functools.lru_cache +def is_from_unspecialized_nn_module_source(source: Source) -> bool: + if isinstance(source, UnspecializedNNModuleSource): + return True + if isinstance(source, ChainedSource): + return is_from_unspecialized_nn_module_source(source.base) + return False + + +@functools.lru_cache +def is_from_unspecialized_builtin_nn_module_source(source: Source) -> bool: + if isinstance(source, UnspecializedBuiltinNNModuleSource): + return True + if isinstance(source, ChainedSource): + return is_from_unspecialized_builtin_nn_module_source(source.base) + return False + + +@functools.lru_cache +def is_from_unspecialized_param_buffer_source(source: Source) -> bool: + if isinstance(source, UnspecializedParamBufferSource): + return True + if isinstance(source, ChainedSource): + return is_from_unspecialized_param_buffer_source(source.base) + return False + + +@functools.lru_cache +def is_from_flatten_script_object_source(source: Source) -> bool: + if isinstance(source, FlattenScriptObjectSource): + return True + elif isinstance(source, ChainedSource): + return is_from_flatten_script_object_source(source.base) + return False + + +@functools.lru_cache +def is_from_optimizer_source(source: Source) -> bool: + if isinstance(source, OptimizerSource): + return True + if isinstance(source, ChainedSource): + return is_from_optimizer_source(source.base) + return False + + +# TODO: can probably write a generic "test this on everything in the chain" +# helper +@functools.lru_cache +def is_from_defaults(source: Source) -> bool: + if isinstance(source, DefaultsSource): + return True + + # Accessed with func.__kwdefaults__["foo"] + if ( + isinstance(source, DictGetItemSource) + and isinstance(source.base, AttrSource) + and source.base.member == "__kwdefaults__" + ): + return True + + # Accessed with func.__defaults__[0] + if ( + isinstance(source, GetItemSource) + and isinstance(source.base, AttrSource) + and source.base.member == "__defaults__" + ): + return True + + if isinstance(source, ChainedSource): + return is_from_defaults(source.base) + return False + + +@functools.lru_cache +def is_from_skip_guard_source(source: Source) -> bool: + if isinstance(source, SkipGuardSource): + return True + + if isinstance(source, ChainedSource): + return is_from_skip_guard_source(source.base) + + return False diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..44623bdd4a08c50adce9feaa4da79689d387efd2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py @@ -0,0 +1,6627 @@ +""" +Core module responsible for converting Python bytecode into TorchDynamo's symbolic execution format. + +This module implements the bytecode-level tracing system that allows TorchDynamo to analyze +and transform Python code. It converts Python bytecode instructions into a symbolic format +that tracks the flow of tensors and other values through the program. + +Key components: +- InstructionTranslatorBase: Base class for converting bytecode to symbolic execution +- InstructionTranslator: Main translator for function bytecode +- InliningInstructionTranslator: Handles inlining of called functions +- SpeculationLog: Manages state for speculative execution and rollback + +The symbolic conversion process handles: +- Control flow (loops, conditionals, etc.) +- Function inlining and call stack management +- Tracking of program values and side effects +- Graph breaks and resumption points +- Exception handling and stack frame management + +This is a core part of TorchDynamo's tracing system that enables ahead-of-time +optimization of PyTorch programs. +""" + +from __future__ import annotations + +import _warnings + +import contextlib +import copy +import dataclasses +import dis +import functools +import importlib +import inspect +import itertools +import linecache +import logging +import operator +import re +import sys +import threading +import time +import traceback +import types +import weakref +from collections import defaultdict, deque +from typing import Any, cast, NoReturn, TYPE_CHECKING, TypeAlias, TypeVar +from typing_extensions import TypeIs + +import torch +import torch._logging +from torch._dynamo.dynamo_profiler import DynamoProfilerState, FunctionTraceTiming +from torch._dynamo.exc import ( + FakeTensorObservedException, + get_dynamo_observed_exception, + ObservedException, + TensorifyScalarRestartAnalysis, +) +from torch._guards import InlinedCodeCache, tracing, TracingContext +from torch._logging.structured import dump_file +from torch.fx.experimental.symbolic_shapes import guard_bool +from torch.utils._functools import cache_method + +from . import ( + config, + exc, + graph_break_hints, + logging as torchdynamo_logging, + trace_rules, + variables, +) +from .bytecode_analysis import ( + get_indexof, + JUMP_OPNAMES, + livevars_analysis, + propagate_line_nums, +) +from .bytecode_transformation import ( + cleaned_instructions, + create_binary_slice, + create_call_function, + create_call_function_ex, + create_copy, + create_dup_top, + create_instruction, + create_jump_absolute, + create_rot_n, + create_swap, + get_call_callable_depth, + get_code_keys, + Instruction, + is_generator, + is_jump_absolute, + unique_id, +) +from .code_context import code_context +from .codegen import PyCodegen +from .comprehension_graph_break import maybe_setup_comprehension_speculation +from .exc import ( + augment_exc_message_with_hop_name, + BackendCompilerFailed, + collapse_resume_frames, + format_frame_info, + get_stack_above_dynamo, + raise_observed_exception, + raise_value_error, + ResumePrologueTracingError, + StepUnsupported, + unimplemented, + Unsupported, + UserError, +) +from .funcname_cache import get_funcname +from .guards import GuardBuilder, install_guard +from .output_graph import ( + CodeOptions, + GraphCompileReason, + OutputGraph, + StackLocalsMetadata, +) +from .polyfills import ( + impl_IS_MAPPING, + impl_MATCH_CLASS, + impl_MATCH_KEYS, + impl_MATCH_SEQUENCE, +) +from .replay_record import DummyModule, ExecutionRecorder +from .resume_execution import ( + ContinueExecutionCache, + IS_TRACING_RESUME_PROLOGUE_VARNAME, + ReenterWith, +) +from .source import ( + AttrSource, + DictGetItemSource, + GlobalSource, + GlobalWeakRefSource, + LocalCellSource, + LocalSource, + SkipGuardSource, + Source, +) +from .trace_rules import is_builtin_constant, is_forbidden +from .utils import ( + _get_error_on_graph_break, + counters, + FrameState, + get_fake_value, + get_instruction_source_311, + get_metrics_context, + graph_break_dup_warning_checker, + istype, + LazyString, + proxy_args_kwargs, + PySendResult, + unpack_iterable, +) +from .variables.base import SourceLocation, typestr, ValueMutationNew, VariableTracker +from .variables.builder import FrameStateSizeEntry, VariableBuilder, wrap_fx_proxy +from .variables.builtin import BuiltinVariable, DictBuiltinVariable +from .variables.constant import ConstantVariable +from .variables.ctx_manager import ( + ContextWrappingVariable, + GenericContextWrappingVariable, + WithEnterFunctionVariable, + WithExitFunctionVariable, +) +from .variables.dicts import ConstDictVariable +from .variables.functions import ( + BaseUserFunctionVariable, + CO_VARARGS, + CO_VARKEYWORDS, + LocalGeneratorFunctionVariable, + LocalGeneratorObjectVariable, + NestedUserFunctionVariable, + SkipFunctionVariable, + UserFunctionVariable, +) +from .variables.iter import MAX_ITERATOR_LIMIT +from .variables.lazy import LazyVariableTracker +from .variables.lists import ( + BaseListVariable, + ListIteratorVariable, + ListVariable, + SliceVariable, + TupleVariable, +) +from .variables.misc import ( + CellVariable, + NullVariable, + PythonModuleVariable, + TracebackVariable, + UnknownVariable, +) +from .variables.nn_module import NNModuleVariable, UnspecializedNNModuleVariable +from .variables.object_protocol import ( + generic_delitem, + generic_getattr, + generic_getiter, + generic_is_true, + generic_setitem, + pyiter_send, + pysequence_contains, +) +from .variables.sets import SetVariable +from .variables.streams import SymbolicStreamState +from .variables.tensor import supported_comparison_ops, SymNodeVariable, TensorVariable +from .variables.torch_function import ( + SymbolicTorchFunctionState, + TorchFunctionModeVariable, +) +from .variables.user_defined import ( + RemovableHandleVariable, + UserDefinedClassVariable, + UserDefinedExceptionClassVariable, + UserDefinedExceptionObjectVariable, + UserDefinedObjectVariable, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + from torch._subclasses.fake_tensor import FakeTensorMode + + from .package import CompilePackage + +log = logging.getLogger(__name__) +graph_break_log = torch._logging.getArtifactLogger(__name__, "graph_breaks") +trace_call_log = torch._logging.getArtifactLogger(__name__, "trace_call") +trace_source_log = torch._logging.getArtifactLogger(__name__, "trace_source") +trace_bytecode_log = torch._logging.getArtifactLogger(__name__, "trace_bytecode") +tls = threading.local() +compare_op_handlers: dict[str, Any] = { + k: BuiltinVariable(v).call_function for k, v in supported_comparison_ops.items() +} +handle_contains = BuiltinVariable(operator.contains).call_function +handle_not = BuiltinVariable(operator.not_).call_function +compare_op_handlers["in"] = lambda tx, args, _: handle_contains( + tx, [*reversed(args)], {} +) +compare_op_handlers["not in"] = lambda tx, args, _: handle_not( + tx, [handle_contains(tx, [*reversed(args)], {})], {} +) + +ExceptionVals: TypeAlias = ( + variables.ExceptionVariable | UserDefinedExceptionObjectVariable +) + +ExceptionTypes: TypeAlias = ( + variables.BuiltinVariable | UserDefinedExceptionClassVariable +) + + +@functools.cache +def _import_module(name: str) -> types.ModuleType: + """ + Import the named module and cache the result. importlib.import_module() + seems to do some filesystem checking to validate the name so not caching + this can be slow. + """ + return importlib.import_module(name) + + +def _registered_module_for_globals( + module_name: object, f_globals: dict[str, Any] +) -> tuple[str, types.ModuleType] | None: + if not isinstance(module_name, str) or module_name.startswith("namedtuple_"): + return None + + if "torch_package" in module_name: + module = torch.package.package_importer._package_imported_modules.get( + module_name + ) + else: + module = sys.modules.get(module_name) + + if isinstance(module, types.ModuleType) and module.__dict__ is f_globals: + return module_name, module + + return None + + +@dataclasses.dataclass +class SpeculationEntry: + filename: str + lineno: int + instruction_pointer: int + inst: Instruction # for debugging only + _failed: bool = False + # TX error_on_graph_break setting at the time of failure + error_on_graph_break: bool | None = None + reason: GraphCompileReason | None = None + + def fail_and_restart_analysis(self, error_on_graph_break: bool) -> None: + """ + Start tracing of the current frame over again, and don't take this branch. + """ + self._failed = True + self.error_on_graph_break = error_on_graph_break + if self.reason is not None: + restart_reason = self.reason.reason + else: + restart_reason = "Unknown fail_and_restart_analysis" + raise exc.SpeculationRestartAnalysis(restart_reason=restart_reason) + + def failed(self, tx: InstructionTranslatorBase) -> bool: + if self._failed: + if self.error_on_graph_break is None: + raise AssertionError( + "expected self.error_on_graph_break is not None to be true" + ) + tx.error_on_graph_break = self.error_on_graph_break + return True + return False + + +@dataclasses.dataclass +class SpeculationLog: + """ + SpeculationLog replaces the prior copy_graphstate/restore_graphstate + checkpointing. Rather than saving/restoring state, we restart the + dynamo conversion process over from the beginning -- but when we + hit the start of the speculation that failed, we instead generate + a graph break. + """ + + entries: list[SpeculationEntry] = dataclasses.field(default_factory=list) + index: int = 0 + # If True, graph break at autograd.grad instead of tracing it. + # Set when we detect that autograd.grad consumed grad_fns that are returned. + graph_break_on_autograd_grad: bool = False + # Names of output tensors whose grad_fns were consumed by autograd.grad. + autograd_grad_leaked_tensors: list[str] = dataclasses.field(default_factory=list) + # If True, graph break at requires_grad_() on source-less intermediates + # instead of tracing it. Set when we detect that such an intermediate + # leaks as a graph output with requires_grad=True. + graph_break_on_requires_grad_: bool = False + + def restart(self) -> None: + self.index = 0 + + def clear(self) -> None: + self.entries.clear() + self.index = 0 + + def next( + self, filename: str, lineno: int, instruction_pointer: int, inst: Instruction + ) -> SpeculationEntry: + """ + Lookup or create a SpeculationEntry() that is shared across + RestartAnalysis calls. Args are used only for debug checks. + """ + if len(self.entries) == self.index: + self.entries.append( + SpeculationEntry(filename, lineno, instruction_pointer, inst) + ) + entry = self.entries[self.index] + prev_entry_msg = "" + if self.index != 0: + prev_entry = self.entries[self.index - 1] + prev_entry_msg = ( + f"Previous instruction: {prev_entry.filename}:{prev_entry.lineno}" + f"({prev_entry.inst.opname} @ {prev_entry.instruction_pointer})\n" + ) + if not ( + entry.instruction_pointer == instruction_pointer + and entry.filename == filename + and entry.lineno == lineno + ): + raise SpeculationLogDivergence( + f""" +SpeculationLog diverged at index {self.index} (log had {len(self.entries)} entries): +- Expected: {entry.filename}:{entry.lineno} ({entry.inst.opname} at ip={entry.instruction_pointer}) +- Actual: {filename}:{lineno} ({inst.opname} at ip={instruction_pointer}) +{prev_entry_msg} +There are two usual reasons why this may have occurred: +- When Dynamo analysis restarted, the second run took a different path than + the first. If this occurred, the previous instruction is the critical instruction that + behaved differently. +- Speculation entries are only added under certain conditions (as seen in + step()), e.g., there must exist operators in the graph; those conditions may + have changed on restart. + +If this divergence was intentional, clear the speculation log before restarting (do NOT +do this for graph breaks, you will infinite loop). + +Otherwise, please submit a bug report, ideally including the contents of TORCH_LOGS=+dynamo +""" + ) + self.index += 1 + return entry + + +@dataclasses.dataclass +class LocalState: + automatic_dynamic: dict[str, FrameStateSizeEntry] = dataclasses.field( + default_factory=dict + ) + + def render(self) -> str: + return "\n".join( + f"{k}: {v.render()}" for k, v in self.automatic_dynamic.items() + ) + + +# Mutable box that is shared across restarts +@dataclasses.dataclass +class DistributedState: + compile_pg: Any + local_state: LocalState + all_states: list[LocalState] | None = None + + +class TensorifyState: + # These are the set of string symfloats names (eg. "zf0") that we collect + # from the tensorify_python_scalars.py joint fx pass to inform us about + # which float inputs we should specialize when we restart analysis. + force_specializations: set[str] = set() + + @classmethod + def specialize(cls, index: str) -> None: + cls.force_specializations.add(index) + + @classmethod + def should_specialize(cls, index: str) -> bool: + return index in cls.force_specializations + + @classmethod + def clear(cls) -> None: + cls.force_specializations.clear() + + @classmethod + def empty(cls) -> bool: + return len(cls.force_specializations) == 0 + + +@functools.cache +def _step_logger() -> Callable[..., None]: + return torchdynamo_logging.get_step_logger(log) + + +@contextlib.contextmanager +def save_and_restart_speculation_log( + tx: InstructionTranslatorBase, +) -> Generator[None, None, None]: + # When reconstructing a generator after a graph break, we advance it until + # it is fully exhausted. This process adds new entries to the speculation + # log that were not previously observed. Without temporarily clearing the + # speculation log, this could lead to a divergence error. + + entries = tx.speculation_log.entries + index = tx.speculation_log.index + try: + tx.speculation_log.entries = [] + tx.speculation_log.index = 0 + yield + finally: + tx.speculation_log.entries = entries + tx.speculation_log.index = index + + +@contextlib.contextmanager +def temporarely_allow_writes_to_output_graph( + tx: InstructionTranslatorBase, +) -> Generator[None, None, None]: + try: + tmp = tx.output.should_exit + tx.output.should_exit = False + yield + finally: + tx.output.should_exit = tmp + + +@dataclasses.dataclass +class BlockStackEntry: + # Current instruction that pushes something to block_stack + inst: Instruction + target: Instruction | None + stack_index: int + with_context: ContextWrappingVariable | GenericContextWrappingVariable | None = None + + def can_restore(self) -> bool: + return self.with_context is not None + + def resume_fn(self) -> ReenterWith: + if self.stack_index is None: + raise AssertionError("expected self.stack_index is not None to be true") + if ( + self.with_context + and hasattr(self.with_context, "target_values") + and self.with_context.target_values + ): + return ReenterWith( + self.stack_index - 1, tuple(self.with_context.target_values) + ) + else: + return ReenterWith(self.stack_index - 1) + + def exit( + self, tx: InstructionTranslatorBase, is_graph_break: bool + ) -> VariableTracker | None: + if self.with_context is None: + raise AssertionError("expected self.with_context is not None to be true") + if ( + is_graph_break and self.with_context.exit_on_graph_break() + ) or not is_graph_break: + return self.with_context.exit(tx) # type: ignore[arg-type] + return None + + +class SpeculationLogDivergence(AssertionError): + pass + + +class ReturnValueOp(Exception): + pass + + +class YieldValueOp(Exception): + """ + Signal to the symbolic tracer to stop and return control flow to the + caller + """ + + +def stack_op(fn: Callable[..., object]) -> Callable[..., Any]: + nargs = len(inspect.signature(fn).parameters) + fn_var = BuiltinVariable(fn) + + @functools.wraps(fn) + def impl(self: InstructionTranslator, inst: Instruction) -> None: + self.push(fn_var.call_function(self, self.popn(nargs), {})) + + return impl + + +def is_stdlib(mod: object) -> bool: + if not isinstance(mod, types.ModuleType): + return False + return mod.__name__.split(".")[0] in sys.stdlib_module_names + + +@functools.cache +def get_assert_bytecode_sequence(with_msg: bool) -> list[str]: + if with_msg: + + def fn(x: Any) -> None: + assert x, "msg" # noqa: S101 # function is to recognize assert statements in user code + else: + + def fn(x: Any) -> None: + assert x # noqa: S101 # function is to recognize assert statements in user code + + insts = [inst.opname for inst in dis.get_instructions(fn)] + + # expect to find POP_JUMP_[FORWARD_]IF_TRUE + begin_idx = next(i for i, inst in enumerate(insts) if inst.startswith("POP_JUMP")) + end_idx = insts.index("RAISE_VARARGS") + + return insts[begin_idx + 1 : end_idx + 1] + + +def _detect_and_normalize_assert_statement( + self: InstructionTranslatorBase, + truth_fn: Callable[[object], bool], + push: bool, +) -> bool: + # Detect if this jump instruction is assert and normalize the assert + # by pushing dummy error message when nothing is given. + # + # Python 3.9-3.13 assertion is in following format (minus small differences) + # 18 POP_JUMP_IF_TRUE 28 + # 20 LOAD_ASSERTION_ERROR + # 22 LOAD_CONST 3 ('Assert message') -> optional instruction + # 24 CALL_FUNCTION 1 -> optional instruction + # 26 RAISE_VARARGS + + if (truth_fn is not operator.truth) or push: + return False + + if not isinstance(self.instruction_pointer, int): + raise AssertionError( + "expected isinstance(self.instruction_pointer, int) to be true" + ) + current_instruction_pointer = self.instruction_pointer + + for with_msg in (False, True): + assert_insts = get_assert_bytecode_sequence(with_msg) + cur_insts = self.instructions[ + current_instruction_pointer : current_instruction_pointer + + len(assert_insts) + ] + cur_insts = [inst.opname for inst in cur_insts] + if cur_insts == assert_insts: + if with_msg: + load_const_idx = assert_insts.index("LOAD_CONST") + error_msg = self.instructions[ + current_instruction_pointer + load_const_idx + ].argval + else: + error_msg = "assertion error" + self.push(VariableTracker.build(self, error_msg)) + return True + + return False + + +explain = False + + +# [NOTE] graph break handling in symbolic_convert +# There are 4 possible graph break cases that InstructionTranslatorBase handles: +# 1. Regular graph breaks from CALL, BINARY_SUBSCR, etc. (implemented by break_graph_if_unsupported) +# 2. Data-dependent condition graph breaks (implemented by generic_jump) +# 4. All other unhandled graph breaks - unsupported step graph breaks (implemented in InstructionTranslatorBase.step) +# +# Graph breaks are handled in the following manner: +# 1. The Unsupported exception is caught. If we cannot compile a partial graph (should_compile_partial_graph() is False), +# then propagate the exception upward. For unsupported step graph breaks, the condition to abort partial compilation is +# more restrictive (see InstructionTranslatorBase.step). +# 2. If the Unsupported exception escapes symbolic_convert.py, then we are done. +# Otherwise, we want to attempt partial compilation. +# Log the graph break via log_graph_break. If we're handling a data-dependent graph break (type 2.), then we can immediately +# codegen the compiled graph and resume function and we're done. This is because the jump instruction we graph break on is +# limited in how it can manipulate Python state (say, in comparison, to CALL, which can modify Python state arbitrarily). +# Otherwise, we need to restart compilation. We need to restart because by processing the unsupported instruction, +# we may have modified the VariableTrackers, and we need all of our VariableTrackers to be in the state BEFORE tracing the +# unsupported instruction. +# 3. During the first compilation, we updated a speculation log, indicating points in the code that we can resume from. +# On the second compilation, we will stop tracing at the first speculation log that fails. Then we compile the partial +# graph and resume function. +# +# Logging invariants: +# 1. No logs need to be made if Unsupported escapes symbolic_convert.py. Python's default exception printing will +# print out all of the necessary information and no partial compilation will be attempted. +# 2. log_graph_break should be called as soon as Unsupported is caught and we determined we want to partial compile. +# This always happens on the first compilation, NOT the restart handling this graph +# 3. Any compile_subgraph call should be preceded immediately by a log in the form of "... triggered compile". + + +def get_node_source_info(n: torch.fx.Node) -> str: + """Extract the innermost user source location from an FX node's stack trace.""" + st = n.meta.get("stack_trace", "") or getattr(n, "stack_trace", "") + if not st: + return "" + trace_lines = st.strip().split("\n") + last_file_idx = -1 + for i, line in enumerate(trace_lines): + if line.strip().startswith("File "): + last_file_idx = i + if last_file_idx < 0: + return "" + file_line = trace_lines[last_file_idx].strip() + code = "" + if last_file_idx + 1 < len(trace_lines): + code = trace_lines[last_file_idx + 1].strip() + return f"{file_line}" + (f", code: {code}" if code else "") + + +def format_tensor_computation_trace(value: VariableTracker, max_lines: int = 20) -> str: + """Walk the FX graph backwards from a TensorVariable to show how it was + computed, with user source locations. Graph inputs (placeholders) are always + shown first, followed by operations in dataflow order ending at the branch + condition.""" + if not isinstance(value, TensorVariable): + return "" + try: + node = value.proxy.node + + # Collect operations and placeholders separately so placeholders (root + # cause) always appear first regardless of traversal order. + op_blocks: list[list[str]] = [] + placeholder_blocks: list[list[str]] = [] + visited: set[str] = set() + + def fmt_arg(a: object) -> str: + return a.name if isinstance(a, torch.fx.Node) else repr(a) + + def walk(n: torch.fx.Node) -> None: + if n.name in visited: + return + visited.add(n.name) + source = get_node_source_info(n) + + if n.op == "placeholder": + block = [] + if source: + block.append(f"# {source}") + block.append(f"{n.name}: graph input ({n.target})") + placeholder_blocks.append(block) + return + + if n.op == "call_function" and len(op_blocks) < max_lines: + target_name = getattr(n.target, "__name__", str(n.target)) + args_str = ", ".join(fmt_arg(a) for a in n.args) + block = [] + if source: + block.append(f"# {source}") + block.append(f"{n.name} = {target_name}({args_str})") + op_blocks.append(block) + + for a in n.args: + if isinstance(a, torch.fx.Node): + walk(a) + + walk(node) + + if not op_blocks and not placeholder_blocks: + return "" + + # Placeholders first (root cause), then ops in dataflow order (reversed + # from the DFS collection order) ending at the branch condition. + all_lines: list[str] = [] + for block in placeholder_blocks + list(reversed(op_blocks)): + all_lines.extend(block) + all_lines.append("") + + return ( + "\n\n The branch condition involves a tensor computed as follows:\n" + + "\n".join(f" {line}" for line in all_lines) + ) + except Exception: + log.debug("format_tensor_computation_trace failed", exc_info=True) + return "" + + +def generic_jump( + truth_fn: Callable[[object], bool], push: bool +) -> Callable[[InstructionTranslatorBase, Instruction], None]: + def raise_jump_graph_break(value: VariableTracker) -> NoReturn: + trace_info = format_tensor_computation_trace(value) + hints: list[str] = [] + if isinstance(value, TensorVariable): + try: + node = value.proxy.node + example = node.meta.get("example_value") + if ( + example is not None + and example.dim() == 0 + and example.dtype + in ( + torch.int32, + torch.int64, + ) + ): + hints.append( + "The branch condition uses a scalar integer tensor. " + "Consider rewriting the computation to use plain Python " + "ints (e.g. use int attributes instead of tensor buffers) " + "so the condition becomes a shape guard instead of " + "data-dependent branching." + ) + if ( + example is not None + and example.dim() == 0 + and example.dtype == torch.bool + ): + hints.append( + "For the common pattern `if tensor_cond: x = transform(x)` " + "(e.g. clamping inf/nan values), consider making the code " + "branchless by always applying the transform. Operations like " + "torch.clamp, torch.nan_to_num, and torch.where are typically " + "no-ops on well-behaved inputs and compile without graph breaks." + ) + # Detect boolean reductions (any/all) which are a telltale sign + # of `tensor.any() or other_tensor.any()` patterns. + # node.target is a str for call_method nodes (e.g. tensor.any()) + # and a callable for call_function nodes (e.g. torch.any()). + target_name = getattr(node.target, "__name__", None) or ( + node.target if isinstance(node.target, str) else None + ) + if target_name in ("any", "all", "bitwise_and", "bitwise_or"): + hints.append( + "Note: Python `or`/`and` between tensor expressions (e.g. " + "`tensor.any() or other_tensor.any()`) triggers implicit bool " + "conversion. Use `torch.logical_or`/`torch.logical_and` or the " + "`|`/`&` operators instead." + ) + except Exception: + pass + hints.extend(graph_break_hints.FUNDAMENTAL) + hints.append("Use `torch.cond` to express dynamic control flow.") + unimplemented( + gb_type="Data-dependent branching", + context=f"attempted to jump with {value}", + explanation="Detected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). " + "Dynamo does not support tracing dynamic control flow." + trace_info, + hints=hints, + ) + + def jump_graph_break( + self: InstructionTranslatorBase, + inst: Instruction, + value: VariableTracker, + extra_msg: str = "", + ) -> None: + if not self.should_compile_partial_graph(): + raise AssertionError( + "expected self.should_compile_partial_graph() to be true" + ) + + exc = None + try: + raise_jump_graph_break(value) + except (Unsupported, UserError) as e: + exc = e + + if exc is None: + raise AssertionError("expected exc is not None to be true") + + # compile a partial subgraph prefix then skip the rest of user code + if self.maybe_has_backedge(): + self.raise_loop_graph_break(self.f_code, exc) + + self.log_graph_break( + self.code_options, + reason=str(exc), + exc=exc, + ) + + self.push(value) + log.debug("generic_jump triggered compile") + all_stack_locals_metadata = self.output.compile_subgraph( + self, + reason=GraphCompileReason( + f"generic_jump {typestr(value)}{extra_msg}", [self.frame_summary()] + ), + stack_pops=1, + ) + self.pop() + + if_next = self.create_call_resume_at( + self.next_instruction, + all_stack_locals_metadata, + ) + if push: + self.push(value) + if inst.target is None: + raise AssertionError("expected inst.target is not None to be true") + if_jump = self.create_call_resume_at( + inst.target, + all_stack_locals_metadata, + ) + + if sys.version_info >= (3, 13): + # 3.13 requires stack[-1] to be bool type + self.output.add_output_instructions([create_instruction("TO_BOOL")]) + + jump_inst = create_instruction(inst.opname, target=if_jump[0]) + # For inlined frames, use the root frame's current instruction + # positions so the output code maps to the correct source line. + positions_inst = ( + self.output.root_tx.current_instruction if self.parent is not None else inst + ) + jump_inst.copy_positions(positions_inst) + self.output.add_output_instructions([jump_inst] + if_next + if_jump) + + def inner(self: InstructionTranslatorBase, inst: Instruction) -> None: + value: VariableTracker = self.pop() + if ( + config.rewrite_assert_with_torch_assert + and sys.flags.optimize == 0 + and _detect_and_normalize_assert_statement(self, truth_fn, push) + ): + error_msg: VariableTracker = self.pop() + # Skip over things like `assert True` + if value.is_python_constant(): + if bool(value.as_python_constant()): + return self.jump(inst) + elif self.should_compile_partial_graph(): + jump_graph_break(self, inst, value) + return + else: + unimplemented( + gb_type="Data-dependent assertion failed (cannot compile partial graph)", + context=f"value: {value}", + explanation="Dynamo has determined when encountering a data-dependent assert failure " + "that it should not compile the partial graph.", + hints=[ + *graph_break_hints.FUNDAMENTAL, + "Use `torch._assert()` to raise a hard AssertionError when the check fails. " + "This error will propagate back the user code " + "that called the compiled function (i.e. Dynamo will not trace any exception handling).", + "Remove the assert statement.", + "Move the assert statement outside of any context managers in order to graph break with " + "partial graph compilation (if fullgraph=False).", + ], + ) + + # TODO maybe should respect DtoH sync intention of users later?? + # Manually insert torch._assert_async instead of python assert and jump over + # assert related instructions as we don't need them anymore. + + # if we see Tensor as assert statement, no need to call scalar_tensor + if value.is_tensor(): + self.output.create_proxy( + "call_function", + torch._assert_async, + *proxy_args_kwargs((value, error_msg), {}), + ) + self.jump(inst) + return + + if isinstance(value, SymNodeVariable): + # if the assertion is normal shape expression. + # just install guard and bail out. + sym_expr = value.sym_num + if not isinstance(sym_expr, torch.SymBool): + sym_expr = sym_expr != 0 + + result = torch.fx.experimental.symbolic_shapes.expect_true(sym_expr) + if not result: + unimplemented( + gb_type="Assertion failed on symbolic shapes", + context=str(sym_expr), + explanation="", + hints=[*graph_break_hints.USER_ERROR], + ) + self.jump(inst) + return + + scalar_to_tensor_proxy = self.output.create_proxy( + "call_function", torch.scalar_tensor, *proxy_args_kwargs((value,), {}) + ) + + scalar_to_tensor = wrap_fx_proxy( + self, + scalar_to_tensor_proxy, + example_value=get_fake_value(scalar_to_tensor_proxy.node, self), + ) + + self.output.create_proxy( + "call_function", + torch._assert_async, + *proxy_args_kwargs((scalar_to_tensor, error_msg), {}), + ) + self.jump(inst) + return + + if value.is_python_constant(): + # ConstDictVariable is optimized to be very lazy about insertion of + # guards, so we have to manually insert a SEQUENCE_LENGTH guard + # here. + if isinstance(value, ConstDictVariable) and value.source: + install_guard(value.source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + if truth_fn(value.as_python_constant()): + if push: + self.push(value) + self.jump(inst) + elif value.is_tensor() and self.should_compile_partial_graph(): + jump_graph_break(self, inst, value) + elif isinstance(value, NNModuleVariable): + # Equivalent of "self.nn_module is not None" + mod = self.output.get_submodule(value.module_key) + if truth_fn(mod): + if push: + self.push(value) + self.jump(inst) + elif isinstance(value, UserDefinedObjectVariable): + result = generic_is_true(self, value) # type: ignore[arg-type] + if result.is_python_constant(): + if truth_fn(result.as_python_constant()): + if push: + self.push(value) + self.jump(inst) + elif isinstance(result, SymNodeVariable): + if truth_fn(result.evaluate_expr()): + if push: + self.push(value) + self.jump(inst) + else: + unimplemented( + gb_type="Data-dependent branching with non-constant __bool__", + context=f"value: {value}, result: {result}", + explanation="Attempted to perform data-dependent branching on a user-defined " + "object with non-constant truthiness.", + hints=[], + ) + elif isinstance(value, SymNodeVariable): + try: + # if the user is branching on a SymBool, guard on it + # if the user has code like: + # if size: + # ... + # then they are just testing truthiness: guard that the expr != 0 + if isinstance(value.sym_num, torch.SymBool): + eval_result = value.evaluate_expr(self.output) + else: + eval_result = guard_bool(value.sym_num != 0) + except exc.UserError as e: + if self.should_compile_partial_graph(): + return jump_graph_break(self, inst, value, extra_msg=f"\n{e}") + raise + if truth_fn(eval_result): + if push: + self.push(value) + self.jump(inst) + elif not value.is_tensor(): + result = generic_is_true(self, value) # type: ignore[arg-type] + if truth_fn(result): + if push: + self.push(value) + self.jump(inst) + elif isinstance(value, variables.BackwardHookVariable): + if truth_fn(True): + if push: + self.push(value) + self.jump(inst) + else: + from .source import is_constant_source + + if value.source is not None and is_constant_source(value.source): + if truth_fn(value.get_real_value()): # type: ignore[attr-defined] + if push: + self.push(value) + self.jump(inst) + else: + raise_jump_graph_break(value) + + return inner + + +def _reconstruct_block_stack( + tx: InstructionTranslatorBase, cg: PyCodegen, cleanup: list[Instruction] +) -> None: + """Generates bytecode to restore the block stack for running the unsupported instruction + in the compiled bytecode.""" + # Reconstruct the context variable CLASS in the block stack + all_txes: list[InstructionTranslatorBase] = [] + cur_tx: InstructionTranslatorBase | None = tx + while cur_tx is not None: + all_txes.append(cur_tx) + cur_tx = cur_tx.parent + for tx in reversed(all_txes): + for b in tx.block_stack: + # Don't exit any modes we have entered -- + # output bytecode will push/pop the tf mode stack, + # so we only need a try/except to pop on exception. + if isinstance(b.with_context, TorchFunctionModeVariable): + cg.extend_output( + b.resume_fn().try_except_torch_function_mode( + cg.code_options, cleanup + ) + ) + continue + if b.with_context is None: + raise AssertionError("expected b.with_context is not None to be true") + if not isinstance(b.with_context, (ContextWrappingVariable)): + raise AssertionError( + "expected isinstance(b.with_context, (ContextWrappingVariable)) to be true" + ) + b.with_context.reconstruct_type(cg) + cg.extend_output(b.resume_fn().try_finally(cg.code_options, cleanup)) + + +def _make_warnings_warn_wrapper(filename: str, lineno: int) -> Callable[..., Any]: + """Create a wrapper for warnings.warn that reports the given source location. + + When warnings.warn (stacklevel=1) inspects its caller frame, it sees the + wrapper's code object -- whose co_filename and line table point to the + original leaf-frame location. This preserves Python's per-location + warning dedup even when the call is inlined into a different frame by + nested graph breaks. + """ + import warnings + + # Use a lambda so all bytecode is on one line and co_firstlineno + # equals the body line (no off-by-one vs a multi-line def). + wrapper: Callable[..., Any] = lambda *args, **kwargs: warnings.warn(*args, **kwargs) # noqa: E731 + wrapper.__code__ = wrapper.__code__.replace( + co_filename=filename, + co_firstlineno=lineno, + ) + return wrapper + + +# NOTE: for the purposes of nested graph breaks, break_graph_if_unsupported only works on instructions +# with 0 or 1 outputs. If you wish to support bytecodes with 2+ outputs, either rewrite the instruction +# into a sequence of simpler instructions, or file an issue for consultation. +# There is an additional requirement that if the instruction causes a function call, e.g. STORE_ATTR, +# nothing should happen to the result of the function call. +def break_graph_if_unsupported( + *, push: bool, msg_prefix: str +) -> Callable[ + [Callable[..., None]], Callable[[InstructionTranslatorBase, Instruction], None] +]: + def decorator( + inner_fn: Callable[..., None], + ) -> Callable[[InstructionTranslatorBase, Instruction], None]: + @functools.wraps(inner_fn) + def wrapper(self: InstructionTranslatorBase, inst: Instruction) -> None: + prev_push = self.current_instruction_push + self.current_instruction_push = push + speculation = self.speculate() + if speculation.failed(self): + # no need to restore current_instruction_push if speculation failed + if speculation.reason is None: + raise AssertionError( + "expected speculation.reason is not None to be true" + ) + return handle_graph_break(self, inst, speculation.reason) + try: + return inner_fn(self, inst) + except (Unsupported, UserError) as excp: + if self.active_generic_context_managers: + # raise original graph break if fullgraph/error_on_graph_break=True + if self.one_graph or self.error_on_graph_break: + raise + + # We don't support graph break under GenericContextWrappingVariable, + # If there is, we roll back to the checkpoint and fall back. + if isinstance(excp, Unsupported): + excp.remove_from_stats() + unimplemented( + gb_type="Graph break under GenericContextWrappingVariable", + context=f"Active generic context managers: {self.active_generic_context_managers}", + explanation="Attempted to graph break in an active context manager(s) that doesn't support graph breaking.", + hints=[ + "Move the offending context manager(s) to outside the compiled region.", + *graph_break_hints.CAUSED_BY_EARLIER_GRAPH_BREAK, + ], + from_exc=excp, + ) + + if getattr(excp, "skip_frame", False): + raise + + if not self.should_compile_partial_graph(): + raise + + if self.maybe_has_backedge(): + self.raise_loop_graph_break(self.f_code, excp) + + self.log_graph_break( + self.code_options, + reason=f"{msg_prefix}:\n\n{str(excp)}", + exc=excp, + ) + + if isinstance(excp, Unsupported): + excp.remove_from_stats() + excp.add_to_stats("graph_break") + speculation.reason = GraphCompileReason( + getattr(excp, "msg", str(excp)), + getattr(excp, "real_stack", [self.frame_summary()]), + ) + finally: + self.current_instruction_push = prev_push + speculation.fail_and_restart_analysis(self.error_on_graph_break) + + def handle_graph_break( + self: InstructionTranslatorBase, + inst: Instruction, + reason: GraphCompileReason, + ) -> None: + if ( + sys.version_info >= (3, 11) + and sys.version_info < (3, 12) + and inst.opname == "CALL" + ): + # stack effect for PRECALL + CALL is split between the two instructions + stack_effect = dis.stack_effect( + dis.opmap["PRECALL"], inst.arg + ) + dis.stack_effect(dis.opmap["CALL"], inst.arg) + else: + stack_effect = dis.stack_effect(inst.opcode, inst.arg) + + # When warnings.warn is called from an inlined frame, replace + # it on the symbolic stack before compile_subgraph so the codegen + # naturally reconstructs the wrapper via LOAD_GLOBAL. + if self.parent is not None: + self._maybe_replace_warnings_warn_on_stack(inst) + + log.debug("%s triggered compile", inst.opname) + all_stack_locals_metadata = self.output.compile_subgraph( + self, reason=reason, stack_pops=int(push) - stack_effect + ) + cg = PyCodegen(self.output.root_tx) + cleanup: list[Instruction] = [] + _reconstruct_block_stack(self, cg, cleanup) + self.output.add_output_instructions(cg.get_instructions()) + del cg + + # For inlined frames, use the root frame's current instruction + # positions so the output code maps to the correct source line. + # The output code is always for the root function, so line numbers + # from inlined child frames would be wrong. + positions_inst = ( + self.output.root_tx.current_instruction + if self.parent is not None + else inst + ) + + if sys.version_info >= (3, 11) and inst.opname == "CALL": + kw_names = ( + self.kw_names.as_python_constant() + if self.kw_names is not None + else () + ) + if len(kw_names) > 0: + # KW_NAMES no longer used in 3.13 + if not (sys.version_info < (3, 13)): + raise AssertionError( + "expected sys.version_info < (3, 13) to be true" + ) + self.output.add_output_instructions( + [create_instruction("KW_NAMES", argval=kw_names)] + ) + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + call_insts = create_call_function(inst.arg, False) + call_insts[-1].copy_positions(positions_inst) + self.output.add_output_instructions(call_insts) + else: + # copy instruction, but without exception table data + if inst.target is not None: + raise AssertionError("expected inst.target is None to be true") + inst_copy = copy.copy(inst) + inst_copy.exn_tab_entry = None + inst_copy.copy_positions(positions_inst) + self.output.add_output_instructions([inst_copy]) + + self.output.add_output_instructions(cleanup) + + self.popn(int(push) - stack_effect) + if push: + self.push(UnknownVariable()) + self.output.add_output_instructions( + self.create_call_resume_at( + self.next_instruction, + all_stack_locals_metadata, + ) + ) + + return wrapper + + return decorator + + +class BytecodeDispatchTableMeta(type): + """Installs a `cls.dispatch_table` on every subclass to speed up calls to self.OPCODE()""" + + def __init__(cls: type, name: str, bases: Any, dct: Any) -> None: + super().__init__(name, bases, dct) # type: ignore[misc] + + def _missing(opname: str, *args: Any) -> None: + unimplemented( + gb_type="Missing bytecode handler", + context=f"{opname} with args {args}", + explanation=f"Dynamo does not know how to handle the bytecode instruction `{opname}`.", + hints=[ + f"Do not trace code that produces the `{opname}` bytecode instruction " + "(see https://docs.python.org/3/library/dis.html for bytecode semantics).", + *graph_break_hints.SUPPORTABLE, + ], + ) + + dispatch_table = { + op: getattr(cls, opname, functools.partial(_missing, opname)) + for opname, op in dis.opmap.items() + } + cls.dispatch_table = [dispatch_table.get(i) for i in range(2**8)] + + +def pyexception_class_check(val: VariableTracker) -> TypeIs[ExceptionTypes]: + # Mirror's CPython PyExceptionClass_Check + # https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Include/pyerrors.h#L60-L62 + if isinstance(val, variables.BuiltinVariable): + return issubclass(val.fn, BaseException) + return isinstance(val, UserDefinedExceptionClassVariable) + + +def pyexception_instance_check(val: VariableTracker) -> TypeIs[ExceptionVals]: + # Mirror's CPython PyExceptionInstance_Check + # https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Include/pyerrors.h#L64-L65 + return isinstance( + val, (variables.ExceptionVariable, UserDefinedExceptionObjectVariable) + ) + + +def pyerr_given_exception_match(err: VariableTracker, exc: type[BaseException]) -> bool: + # Mirror's PyErr_GivenExceptionMatch + if pyexception_class_check(err): + return issubclass(err.fn, exc) + if pyexception_instance_check(err): + return issubclass(err.exc_type, exc) + return False + + +def pygen_fetch_stopiteration_value(val: ExceptionVals) -> VariableTracker: + # Mirror's CPython PyGen_FetchStopIterationValue + if issubclass(val.exc_type, StopIteration): + return val.args[0] if val.args else ConstantVariable.create(None) + return ConstantVariable.create(None) + + +@dataclasses.dataclass +class Segment: + """ + One frame's slice of the exception stack, mirroring CPython's + `_PyErr_StackItem` (`gi_exc_state`). + + CPython represents the exc_state as a linked list of `_PyErr_StackItem`s, + where each item contains the exception type, value, and traceback for the + frame. We simulate this with a linked list of `Segment`s, where each + `Segment` is a list of `ExceptionVals` + """ + + items: list[ExceptionVals] = dataclasses.field(default_factory=list) + prev: Segment | None = dataclasses.field(default=None) + + +@dataclasses.dataclass +class ExceptionStack: + """ + Exception stack that it is shared among all InstructionTranslator instances + """ + + # Exception handling in CPython is a bit confusing and some of the bytecode + # have a slightly different behavior than what is documented. While reading + # the documentation, is important to notice that the terms "current exception" + # and "stack" sometimes refers to a C variable with the same name and the + # exception stack, respectively. + # + # The lifetime of an exception is (Python 3.11+): + # + tx._raise_exception_variable(...) := sets the current_exception variable + # + PUSH_EXC_INFO := pushes the current_exception to the *exception stack* + # + POP_EXCEPT := pops TOS from the *exception stack* + + _exc_stack: Segment = dataclasses.field(default_factory=Segment) + _current_exception: ExceptionVals | None = dataclasses.field(default=None) + + def push_segment(self, segment: Segment) -> None: + """Make `segment` the head, linking it to the current head (resume).""" + segment.prev = self._exc_stack + self._exc_stack = segment + + def pop_segment(self) -> Segment: + """Restore the head to the segment below (suspend).""" + segment = self._exc_stack + if segment.prev is None: + raise AssertionError("cannot pop the base exception segment") + self._exc_stack = segment.prev + segment.prev = None + return segment + + def clear_current_exception(self) -> None: + self._current_exception = None + + def set_raised_exception(self, val: ExceptionVals) -> None: + # Mirrors CPython's PyErr_SetRaisedException + self._current_exception = val + + def get_topmost_exception(self) -> ExceptionVals: + if not len(self): + raise AssertionError("expected len(self.exn_vt_stack) to be true") + return self.__getitem__(-1) + + def move_current_exception_to_stack(self) -> None: + if self._current_exception is None: + raise AssertionError( + "expected self._current_exception is not None to be true" + ) + self.append(self._current_exception) + self.clear_current_exception() + + def get_raised_exception(self) -> ExceptionVals: + # Mirrors CPython's PyErr_GetRaisedException() + if self._current_exception is None: + raise AssertionError( + "expected self._current_exception is not None to be true" + ) + return self._current_exception + + def _set_context_recursive( + self, val: ExceptionVals, prev_idx: int + ) -> ExceptionVals: + if (ctx := val.__context__) and not ctx.is_constant_none(): # type: ignore[union-attr] + return val + if len(self) + prev_idx > 0: + prev = self[prev_idx] + self._set_context_recursive(prev, prev_idx - 1) + if prev is not val: + val.set_context(prev) # type: ignore[union-attr, arg-type] + return val + + def _break_context_reference_cycle(self, val: ExceptionVals) -> None: + # See test_exceptions::test_raise_does_not_create_context_chain_cycle + # Based on https://github.com/python/cpython/blob/e635bf2e49797ecb976ce45a67fce2201a25ca68/Python/errors.c#L207-L228 + # As noted on CPython, this is O(chain length) but the context chains + # are usually very small + o = slow_o = val + slow_update_toggle = False # floyd's algorithm for detecting cycle + while True: + context = o.__context__ # type: ignore[union-attr] + if context.is_constant_none(): + break + + if context is val: + o.set_context(ConstantVariable.create(None)) # type: ignore[union-attr, arg-type] + break + + o = context # type: ignore[assignment] + if o is slow_o: + # pre-existing cycle - all exceptions on the path were + # visited and checked + break + + if slow_update_toggle: + # visited all exceptions + slow_o = slow_o.__context__ # type: ignore[union-attr, assignment] + slow_update_toggle = not slow_update_toggle + + def _set_context_and_break_context_reference_cycle( + self, val: ExceptionVals + ) -> None: + # set Exception.__context__ + self._set_context_recursive(val, len(self) - 1) + self._break_context_reference_cycle(val) + + def pop(self) -> ExceptionVals: + return self._exc_stack.items.pop() + + def append(self, val: ExceptionVals) -> None: + self._exc_stack.items.append(val) + + def __len__(self) -> int: + n = 0 + segment: Segment | None = self._exc_stack + while segment is not None: + n += len(segment.items) + segment = segment.prev + return n + + def __getitem__(self, index: int) -> ExceptionVals: + # Global indexing over the segment chain: `prev` segments (lower) + # concatenated with the head segment (upper), so `[-1]` falls through + # to the caller when the head segment is empty. + n = len(self) + if index < 0: + index += n + if not 0 <= index < n: + raise IndexError("exception stack index out of range") + segment = self._exc_stack + base = n - len(segment.items) + while index < base: + if segment.prev is None: + raise AssertionError("expected segment.prev to not be None") + segment = segment.prev + base -= len(segment.items) + return segment.items[index - base] + + def __str__(self) -> str: + return f"{self._exc_stack=} - {self._current_exception=}" + + __repr__ = __str__ + + +class InstructionTranslatorBase( + metaclass=BytecodeDispatchTableMeta, +): + output: OutputGraph + symbolic_locals: dict[str, VariableTracker] + # Registry of this frame's cells (cellvars + freevars), recorded at frame + # setup. `symbolic_locals` models localsplus slot contents, which + # fast-local ops may legitimately clobber (LOAD_FAST_AND_CLEAR in inlined + # comprehensions evicts a merged cell slot; a comprehension iteration + # variable shadowing an enclosing `nonlocal` reuses the cell's name for a + # distinct fast slot). The registry survives such slot traffic so cell + # lookups and cell codegen at a graph break never depend on what the slot + # happens to hold. See `_cellvar` for the resolution rule. + symbolic_cellvars: dict[str, VariableTracker] + symbolic_globals: dict[str, VariableTracker] + symbolic_torch_function_state: SymbolicTorchFunctionState + symbolic_stream_state: SymbolicStreamState + post_prune_cell_and_freevars: dict[str, VariableTracker] | None + stack: list[VariableTracker] + instruction_pointer: int | None + current_instruction: Instruction + current_instruction_push: bool + block_stack: list[BlockStackEntry] + lineno: int + kw_names: ConstantVariable | None + accept_prefix_inst: bool + prefix_insts: list[Instruction] + inline_depth: int + inconsistent_side_effects: bool + current_speculation: SpeculationEntry | None + dispatch_table: list[Any] + exn_vt_stack: ExceptionStack + exec_recorder: ExecutionRecorder | None + strict_checks_fn: Callable[[VariableTracker], bool] | None + start_point: int | None + # Does this function make no inlined function calls? + has_no_inlined_calls: bool + parent: InstructionTranslatorBase | None + # Does this tx currently have a child tx tracing? + # Used to correctly implement should_compile_partial_graph + is_child_tracer_active: bool + debug_locals: list[tuple[VariableTracker, list[VariableTracker]]] + package: CompilePackage | None + latest_bytecode_queue: deque[str] + # Store the latest bytecode before graph_break() call by user + + def mark_inconsistent_side_effects(self) -> None: + """ + InstructionTranslator has encountered instructions which may cause + dynamo to see a different version of history from eager + See: https://github.com/pytorch/pytorch/issues/110765 + """ + self.inconsistent_side_effects = True + + def maybe_has_backedge(self) -> bool: + # This function employs a heuristic. It does not reliably detect a backedge. + # The heuristic is straightforward: starting from the current instruction and + # continuing to the end, if any jump instruction targets an instruction before + # the current one, there might be a backedge. + + # Python 3.12 introduced changes to bytecode that group common paths in + # blockstacks (with or try...else) and allow for early returns. Consequently, + # there can be multiple RETURN_VALUE instructions. Another heuristic is to + # halt detection upon encountering the first RETURN_VALUE or RETURN_CONST. + + # These heuristics can result in both false positives and negatives, but + # in either case, the Dynamo code remains valid. For false positives + # (where an edge is incorrectly marked as a backedge), Dynamo will + # graph break with a frame skip instead of potentially applying optimizations. For + # false negatives (where an edge that should be marked as a backedge + # isn't), multiple graphs may be generated if there's a break in the + # graph during a for loop. In general, its better to have fewer false + # negatives so that Dynamo does not skip the whole frame. + + # If any parent tx has a backedge, then return True + cur_tx: InstructionTranslatorBase | None = self + while cur_tx is not None: + cur_offset = cur_tx.current_instruction.offset + if cur_tx.instruction_pointer is None: + raise AssertionError( + "expected cur_tx.instruction_pointer is not None to be true" + ) + for inst in cur_tx.instructions[cur_tx.instruction_pointer :]: + if inst.opname in ("RETURN_VALUE", "RETURN_CONST"): + break + if inst.opname in JUMP_OPNAMES: + jump_offset = inst.argval + if jump_offset < cur_offset: + return True + cur_tx = cur_tx.parent + return False + + def cellvars(self) -> tuple[str, ...]: + return self.code_options["co_cellvars"] + + def freevars(self) -> tuple[str, ...]: + return self.code_options["co_freevars"] + + def new_pycode_varname(self, prefix: str) -> str: + """Generate a fresh, unique pycode-local variable name for the given prefix.""" + name = f"__{prefix}{next(self._pycode_varname_counter[prefix])}" + self._pycode_last_varname[prefix] = name + return name + + def reset_pycode_varname_counter(self, prefix: str) -> None: + self._pycode_varname_counter[prefix] = itertools.count(0) + + def get_pycode_last_varname(self, prefix: str) -> str: + """Return the most recently generated pycode varname for the given prefix.""" + return self._pycode_last_varname[prefix] + + def cell_and_freevars(self) -> tuple[str, ...]: + if not hasattr(self, "_cell_and_freevars"): + self._cell_and_freevars = self.cellvars() + self.freevars() + return self._cell_and_freevars + + def _register_cells(self) -> None: + # Record this frame's cells in the symbolic_cellvars registry. A free + # var that shares its name with a fast local occupies a second, + # distinct localsplus slot in CPython (e.g. an inlined comprehension + # iteration variable shadowing an enclosing `nonlocal`); it is removed + # from symbolic_locals so fast-local ops on the name can't touch it. + # Cellvars that match a fast local are merged into one slot by CPython, + # so they (and non-colliding cells) stay in symbolic_locals as slot + # contents too. Idempotent: re-registering is a no-op. + fastlocals = set(self.f_code.co_varnames) + for name in self.cell_and_freevars(): + if name in self.symbolic_locals: + self.symbolic_cellvars[name] = self.symbolic_locals[name] + for name in self.f_code.co_freevars: + if name in fastlocals: + self.symbolic_locals.pop(name, None) + + def prune_dead_locals(self) -> None: + # keep cell and freevar references alive + self.post_prune_cell_and_freevars = { + name: self._cellvar(name) for name in self.cell_and_freevars() + } + # Only keep the locals that must remain on the stack. + reads = livevars_analysis(self.instructions, self.current_instruction) + # inspect.signature() renames ".N" to "implicitN" for comprehension + # iterator variables because dotted names aren't valid identifiers. + # Normalize reads to match symbolic_locals keys. + normalized_reads = set() + for r in reads: + normalized_reads.add(r.replace(".", "implicit") if r.startswith(".") else r) + self.symbolic_locals = { + k: v for k, v in self.symbolic_locals.items() if k in normalized_reads + } + + def call_function( + self, + fn: VariableTracker, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> None: + if not isinstance(fn, VariableTracker): + raise AssertionError("expected isinstance(fn, VariableTracker) to be true") + if not isinstance(args, list): + raise AssertionError("expected isinstance(args, list) to be true") + if not isinstance(kwargs, dict): + raise AssertionError("expected isinstance(kwargs, dict) to be true") + if not all( + isinstance(x, VariableTracker) + for x in itertools.chain(args, kwargs.values()) + ): + raise AssertionError( + "expected all( isinstance(x, VariableTracker) for x in itertools.chain(args, kwargs.values()) ) to be true" + ) + inner_fn = None + if hasattr(fn, "value"): + inner_fn = fn.value + if hasattr(fn, "fn"): + inner_fn = fn.fn + if inner_fn is not None and callable(inner_fn) and is_forbidden(inner_fn): + raise AssertionError(f"Attempt to trace forbidden callable {inner_fn}") + self.push(fn.call_function(self, args, kwargs)) # type: ignore[arg-type] + + def inline_generator_function( + self, + fn: BaseUserFunctionVariable, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """ + Redirect the call to the generator "call_function" + """ + if not isinstance(fn, LocalGeneratorFunctionVariable): + fn = LocalGeneratorFunctionVariable(fn) + return fn.call_function(self, args, kwargs) # type: ignore[arg-type] + + def inline_user_function_return( + self, + fn: BaseUserFunctionVariable, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + allow_nested_graph_breaks: bool = False, + ) -> Any: + """ + A call to some user defined function by inlining it. + """ + if is_generator(fn.get_code()): + return self.inline_generator_function(fn, args, kwargs) + else: + return InliningInstructionTranslator.inline_call( + self, + fn, + args, + kwargs, + allow_nested_graph_breaks=allow_nested_graph_breaks, + ) + + def get_line_of_code_header(self, lineno: int | None = None) -> str: + if lineno is None: + lineno = self.lineno + inline_depth_str = ( + f" (inline depth: {self.inline_depth})" if self.inline_depth > 0 else "" + ) + funcname = get_funcname(self.f_code.co_filename, lineno) + funcname_str = "" if funcname is None else f" ({funcname})" + return f"{self.f_code.co_filename}:{lineno} in {self.f_code.co_name}{funcname_str}{inline_depth_str}" + + def get_log_starts_line_log_str(self) -> str: + log_str = f"TRACE starts_line {self.get_line_of_code_header()}\n" + line = linecache.getline(self.f_code.co_filename, self.lineno).rstrip() + log_str += f" {line}" + return log_str + + def starts_line(self, lineno: int) -> None: + if self.lineno == lineno: + return + self.lineno = lineno + TracingContext.set_current_loc( + self.f_code.co_filename, lineno, self.f_code.co_name + ) + + if self.is_trace_source_log_enabled: + trace_source_log.debug("%s", LazyString(self.get_log_starts_line_log_str)) + + def step(self) -> bool: + """Process exactly one instruction, return False we should exit""" + self.error_on_graph_break = _get_error_on_graph_break() + + ip = self.instruction_pointer + if ip is None: + return False + self.current_instruction = inst = self.instructions[ip] + self.instruction_pointer = ip + 1 + + if inst.starts_line: + self.starts_line(inst.starts_line) + + tc = TracingContext.try_get() + if tc is not None: + tc.loc_in_frame_positions = inst.positions + + if ( + not self.stack + and self.should_compile_partial_graph() + and self.is_non_empty_graph() + ): + self.current_speculation = self.speculate() + if self.current_speculation.failed(self): + self.step_graph_break(inst) + return False + + if self.is_trace_bytecode_log_enabled: + trace_bytecode_log.debug( + "TRACE %s %s %s", inst.opname, inst.argval, repr(self.stack) + ) + + # Store the latest 20 bytecode execution for the process, + # Used repr for byte processing and limiting the length to 2048 + if config.verbose: + try: + stack_repr = repr(self.stack) + except ValueError: + # Handle large integers that exceed sys.int_info.str_digits_check_threshold + stack_repr = "" + self.latest_bytecode_queue.append( + f"TRACE {inst.opname} {repr(inst.argval)} {stack_repr}" + ) + + self.update_block_stack(inst) + + try: + self.dispatch_table[inst.opcode](self, inst) + return not self.output.should_exit + except TensorifyScalarRestartAnalysis: + raise + except exc.ObservedException as e: + self.exception_handler(e) + return True + except (ReturnValueOp, YieldValueOp): + return False + except (Unsupported, UserError, StepUnsupported) as e: + # More restrictive condition than should_compile_partial_graph: + # if this condition is true, then we SHOULD NOT attempt to find + # a previous checkpoint to resume from and try to resume - we should + # immediately error out. + # The condition is more restrictive because, it may be possible to resume significantly earlier + # in the code (the most recent speculation point). This happens, for example, in the case + # of a graph break in a try block. + if ( + self.one_graph + or self.error_on_graph_break + or self.is_tracing_resume_prologue + or getattr(e, "skip_frame", False) + ): + if isinstance(e, StepUnsupported): + unimplemented( + gb_type="cannot resume from torch._dynamo.step_unsupported()", + context="", + explanation="traced torch._dynamo.step_unsupported(), but Dynamo is instructed " + "to error on graph break. This graph break is used for debugging only.", + hints=[ + "Remove the torch._dynamo.step_unsupported() call.", + "Make sure fullgraph=False and error_on_graph_break=False.", + *graph_break_hints.DYNAMO_BUG, + ], + ) + raise + if self.current_speculation is None: + log.debug("empty checkpoint - cannot resume from graph break") + if isinstance(e, StepUnsupported): + unimplemented( + gb_type="torch._dynamo.step_unsupported() with empty checkpoint", + context="", + explanation="traced torch._dynamo.step_unsupported(), but there is no checkpoint " + "to step_graph_break from. This graph break is used for debugging only.", + hints=[ + "Remove the torch._dynamo.step_unsupported() call.", + "Include at least one checkpoint: (1) include at least 2 ops and (2) make sure there is some " + "line of code that is not in a try/with block, and has an empty Python stack.", + *graph_break_hints.DYNAMO_BUG, + ], + skip_frame=True, + ) + e.skip_frame = True + raise + reason = ( + "Encountered graph break that we cannot resume from. " + "Compiling up to the previous resumable state, " + "then skipping the rest of the function. " + f"Graph break encountered:\n\n{str(e)}" + ) + self.log_graph_break( + self.code_options, + reason=reason, + exc=e, + ) + + self.current_speculation.fail_and_restart_analysis(self.error_on_graph_break) + return False + + if sys.version_info >= (3, 11): + + def update_block_stack(self, inst: Instruction) -> None: + # 3.11+ no longer uses a block stack, but we still keep track of one + # so that we know which contexts are currently active. + # For our purposes, all exception table entries with the same target + # are considered to be part of the same "block". + # NOTE: we only keep track of with blocks that are not contained in try blocks. + # This is because we will not create continuation functions on graph breaks in try blocks, + # but we may for with blocks. We do not push blocks here since + # with blocks are pushed when handling BEFORE_WITH. + entry = inst.exn_tab_entry + if entry: + # Detect when we have exited the top with block. + # The with blocks on the block stack are not enclosed in try + # blocks, so a with block's cleanup code should be in the + # previous with block (if any). + if ( + len(self.block_stack) >= 2 + and entry.target is not self.block_stack[-1].target + and entry.target is self.block_stack[-2].target + ): + # exit the current block + self.block_stack.pop() + else: + # no longer in any block + # It is possible for NOPs to be between two instructions + # in the same block, but the NOPs are not covered by an + # exception table entry. In this case, assume that we + # are still in the same block. + # In 3.12+, JUMP_BACKWARD might also not be covered by + # an exception table entry, so we also assume that we + # are still in the same block. It is probably safe to do + # this in 3.11, even though we haven't encountered this case before. + # In 3.14+, NOT_TAKEN might also not be covered by an exn table entry. + if self.block_stack and inst.opname not in ( + "NOP", + "JUMP_BACKWARD", + "NOT_TAKEN", + ): + # If we really escape from a block and the current + # instruction is not in another block, then there + # should be no other nested blocks that we are in. + if len(self.block_stack) != 1: + raise AssertionError( + "expected len(self.block_stack) == 1 to be true" + ) + self.block_stack.pop() + + else: + + def update_block_stack(self, inst: Instruction) -> None: + pass + + @property + def next_instruction(self) -> Instruction: + if self.instruction_pointer is None: + raise AssertionError( + "expected self.instruction_pointer is not None to be true" + ) + return self.instructions[self.instruction_pointer] + + def step_graph_break(self, continue_inst: Instruction) -> None: + # generate code from checkpoint + if self.output.output_instructions: + raise AssertionError( + "expected not self.output.output_instructions to be true" + ) + if self.current_speculation is None: + raise AssertionError( + "expected self.current_speculation is not None to be true" + ) + # NOTE: adding an assert here since it seems like the only place + # where we call step_graph_break right now is when the stack is empty, + # so let's enforce that for now. + if self.stack: + raise AssertionError("expected not self.stack to be true") + # NOTE: if we support non-empty self.stack in the future, the `stack_pops` argument + # below should be set to the stack length to ensure that the stack is codegen'd + # for the rest of the function. + log.debug("step triggered compile") + all_stack_locals_metadata = self.output.compile_subgraph( + self, + reason=GraphCompileReason("step_unsupported", [self.frame_summary()]), + ) + # current frame state + # cells, + # [ + # frame N locals, + # frame N-1 stack + locals, + # ..., + # frame 1 stack + locals, + # ], + if self.parent: + from .eval_frame import skip_code + + # nested graph break + if not config.nested_graph_breaks: + raise AssertionError("expected config.nested_graph_breaks to be true") + cg = PyCodegen(self.output.root_tx) + + # codegen cells and frame values only for frame N + cg.extend_output( + [ + *create_copy(2), + cg.create_load_const(0), + cg.create_binary_subscr(), + create_instruction("BUILD_LIST", arg=1), + *create_copy(2), + cg.create_load_const(0), + cg.create_binary_subscr(), + create_instruction("BUILD_LIST", arg=1), + ] + ) + # No need to fix stack, since stack is assumed to be empty here. + # Do NOT handle_inactive_ctx because we will be skipping this resume code. + leaf_resume_code, leaf_resume_name = self.create_resume( + 0, continue_inst, all_stack_locals_metadata[0], [], cg, True, False + ) + skip_code(leaf_resume_code) + + cleanup: list[Instruction] = [] + _reconstruct_block_stack(self.parent, cg, cleanup) + + # current frame state + # cells, + # [ + # frame N locals, + # frame N-1 stack + locals, + # ..., + # frame 1 stack + locals, + # ], [frame N cells], [frame N locals], + self.codegen_call_resume([leaf_resume_code], [leaf_resume_name], cg) + + cg.extend_output(cleanup) + + # current frame state + # cells, + # [ + # frame N locals, + # frame N-1 stack + locals, + # ..., + # frame 1 stack + locals, + # ], leaf_resume result + + # pop frame N cells and locals + cg.extend_output( + [ + *create_copy(2), + cg.create_load_const(0), + create_instruction("DELETE_SUBSCR"), + *create_copy(3), + cg.create_load_const(0), + create_instruction("DELETE_SUBSCR"), + ] + ) + + # current frame state + # cells, frame_values, leaf_resume result + # extract frame N-1 stack + num_stack = all_stack_locals_metadata[1].num_stack + cg.extend_output( + [ + *create_copy(2), + cg.create_load_const(0), + cg.create_binary_subscr(), + *create_binary_slice(0, num_stack), + ] + ) + + # current frame state + # cells, frame_values, leaf_resume result, frame N-1 stack + # add the leaf_resume result to frame N-1 stack + cg.extend_output( + [ + *create_swap(2), + *cg.create_list_append(), + ] + ) + self.parent.push(UnknownVariable()) + all_stack_locals_metadata[1].num_stack += 1 + + # current frame state + # cells, frame_values, frame N-1 stack + leaf_resume result + # remove frame N-1 stack from frame_values + if num_stack > 0: + cg.extend_output( + # frame_values[0] = frame_values[0][num_stack:] + [ + *create_copy(2), + cg.create_load_const(0), + cg.create_binary_subscr(), + *create_binary_slice(num_stack, None), + *create_copy(3), + cg.create_load_const(0), + create_instruction("STORE_SUBSCR"), + ] + ) + + # current frame state + # cells, frame_values, frame N-1 stack + leaf_resume result + # unpack the stack (need to unpack twice since UNPACK_SEQUENCE unpacks in reverse order) + cg.extend_output( + [ + create_instruction("UNPACK_SEQUENCE", arg=num_stack + 1), + create_instruction("BUILD_LIST", arg=num_stack + 1), + create_instruction("UNPACK_SEQUENCE", arg=num_stack + 1), + ] + ) + + # call the remaining resume functions + # current frame state + # [frame N-1 cells, ..., frame 1 cells], + # [ + # frame N-1 locals, + # frame N-2 stack + locals, + # ..., + # frame 1 stack + locals, + # ], *(frame N-1 stack), leaf_resume result + self.output.add_output_instructions( + cg.get_instructions() + + self.parent.create_call_resume_at( + self.parent.next_instruction, all_stack_locals_metadata[1:] + ) + ) + else: + # NOTE: if WithExitFunctionVariable is reconstructed here, then the generated bytecode will be wrong. + # However, we don't expect this to happen since WithExitFunctionVariable can only be present on the stack, + # which must be empty in step graph breaks. + # If we do decide to support step graph breaks with WithExitFunctionVariable in the future, we should + # either call a skipped resume function as in the nested step graph break case, or reconstruct the + # proper context manager object from the class (like what we used to do historically in variables/ctx_manager.py). + + # pop cells + self.output.add_output_instructions( + [ + *create_swap(2), + create_instruction("POP_TOP"), + ] + ) + # load locals from frame values + cg = PyCodegen(self.output.root_tx) + self.output.add_output_instructions( + [ + cg.create_load_const(-1), + cg.create_binary_subscr(), + ] + ) + for local, idx in all_stack_locals_metadata[-1].locals_names.items(): + self.output.add_output_instructions( + [ + create_dup_top(), + cg.create_load_const(idx), + cg.create_binary_subscr(), + cg.create_store(local), + ] + ) + self.output.add_output_instructions( + [ + create_instruction("POP_TOP"), + create_jump_absolute(continue_inst), + *self.instructions, + ] + ) + + def run_ctx_mgr(self) -> Any: + # NB: Don't push the top level frame summary; set_current_loc will + # take care of it. However, DO make sure we attach real_stack to + # exceptions + return TracingContext.current_frame(None) + + def run(self) -> None: + with self.run_ctx_mgr(): + dump_file(self.f_code.co_filename) + try: + self.output.push_tx(self) + self.start_point = self.instruction_pointer + try: + while self.step(): + pass + except Exception as e: + if self.is_tracing_resume_prologue: + raise ResumePrologueTracingError( + "Error while tracing through a Dynamo-generated resume function prologue. " + "Errors are not allowed when tracing resume function prologues.\n" + f"{type(e).__qualname__}: {str(e)}" + ).with_traceback(e.__traceback__) from None + raise + except TensorifyScalarRestartAnalysis: + raise + except BackendCompilerFailed: + raise + except RuntimeError as e: + # If the root tx fails to handle the graph break, then the caller (convert_frame) + # will skip the frame and fall back to eager. + # This code path happens e.g. for bytecodes we don't support + # or when we are unable to resume from a graph break. + if ( + isinstance(e, (Unsupported, UserError)) + and isinstance(self, InstructionTranslator) + and not self.error_on_graph_break + and not self.one_graph + ): + # log graph break if we won't error + reason = ( + "Failed to handle graph break gracefully. " + "Skipping the function and falling back to eager. " + f"Graph break encountered:\n\n{str(e)}" + ) + self.log_graph_break( + self.code_options, + reason=reason, + exc=e, + ) + + if not isinstance(e, exc.RestartAnalysis): + self.output.side_effects.log_side_effects_summary() + + if hasattr(e, "msg") and "Data-dependent" in e.msg: + readable_graph = torch.fx.GraphModule( + self.output.nn_modules, self.output.graph + ).print_readable( + print_output=False, include_stride=True, include_device=True + ) + e.partial_fx_graph = readable_graph # type: ignore[attr-defined] + raise + + raise + except Exception as e: + if self.exec_recorder: + e.exec_record = self.exec_recorder.get_record() # type: ignore[attr-defined] + if not isinstance(e, exc.RestartAnalysis): + self.output.side_effects.log_side_effects_summary() + + raise + finally: + self.output.pop_tx() + # Cleanup the outputGraph to delete the held tensors. We perform the + # cleanup only for InstructionTranslator and not + # InliningInstructionTranslator. The InliningInstructionTranslator + # mutates the output object and is restored to original state if + # there was an exception. + if isinstance(self, InstructionTranslator): + self.output.cleanup() + + # Note that this call maybe redundant if compile_subgraph is + # called. This is ok, because calling exit stack close() + # twice is not an issue (second stop is a no op). + self.output.mark_bytecode_tracing_stop() + + def push(self, val: VariableTracker) -> None: + if not isinstance(val, VariableTracker): + raise AssertionError(f"push expects VariableTracker, got {typestr(val)}") + if val.source_location is None: + inst = self.current_instruction + if inst.positions is not None and inst.positions.lineno is not None: + val.set_source_location( + SourceLocation( + filename=self.f_code.co_filename, + lineno=inst.positions.lineno, + end_lineno=inst.positions.end_lineno, + col_offset=inst.positions.col_offset, + end_col_offset=inst.positions.end_col_offset, + ) + ) + elif inst.starts_line is not None: + val.set_source_location( + SourceLocation( + filename=self.f_code.co_filename, + lineno=inst.starts_line, + ) + ) + self.stack.append(val) + + def push_many(self, vals: list[VariableTracker]) -> None: + for val in vals: + self.push(val) + + def pop(self) -> VariableTracker: + return self.stack.pop() + + def popn(self, n: int) -> list[VariableTracker]: + return [*reversed([self.pop() for _ in range(n)])] + + def LOAD_FAST(self, inst: Instruction) -> None: + name = inst.argval + if self.exec_recorder and name in self.f_locals: + self.exec_recorder.add_local_var(name, self.f_locals[name]) + + try: + self.push(self.symbolic_locals[name].unwrap()) + except KeyError: + if name.startswith("."): + try: + # This happens in dict/list comprehensions + new_name = name.replace(".", "implicit") + self.push(self.symbolic_locals[new_name]) + except KeyError: + unimplemented( + gb_type="Attempted to read undefined local variable (implicit)", + context=f"LOAD_FAST {name}", + explanation=f"Could not find an implicit local variable with name `{name}`", + hints=[ + "This happens in dict/list comprehensions", + *graph_break_hints.USER_ERROR, + ], + ) + else: + unimplemented( + gb_type="Attempted to read undefined local variable", + context=f"LOAD_FAST {name}", + explanation=f"Could not find a local variable with name `{name}`", + hints=[*graph_break_hints.USER_ERROR], + ) + + # for continuation functions + if name.startswith("__stack"): + self.symbolic_locals.pop(name) + + def _cellvar(self, name: str) -> VariableTracker: + # The localsplus slot is authoritative while it holds a cell (a + # mid-function MAKE_CELL from an inlined comprehension can replace a + # merged cell slot's cell with a fresh one). Fall back to the registry + # when the slot doesn't hold a cell: either the name is a colliding + # free var that never lives in symbolic_locals, or the cell was + # temporarily evicted by LOAD_FAST_AND_CLEAR. + var = self.symbolic_locals.get(name) + # __instancecheck__ to avoid realizing lazy vts + if var is not None and type.__instancecheck__(CellVariable, var): + return var + return self.symbolic_cellvars[name] + + def LOAD_DEREF(self, inst: Instruction) -> None: + if inst.argval not in self.cell_and_freevars(): + raise AssertionError( + "expected inst.argval in self.cell_and_freevars() to be true" + ) + cell = self._cellvar(inst.argval) + contents_var = self.output.side_effects.load_cell(cell) + self.push(contents_var) + + if self.exec_recorder and inst.argval in self.f_locals: + self.exec_recorder.add_local_var(inst.argval, self.f_locals[inst.argval]) + + def STORE_FAST(self, inst: Instruction) -> None: + name = inst.argval + loaded_vt = self.pop() + loaded_vt.set_name_hint(name) + self.symbolic_locals[name] = loaded_vt + if name == IS_TRACING_RESUME_PROLOGUE_VARNAME: + val = loaded_vt.as_python_constant() + if type(val) is not bool: + raise AssertionError("expected type(val) is bool to be true") + self.is_tracing_resume_prologue = val + + def DELETE_FAST(self, inst: Instruction) -> None: + var = self.symbolic_locals.get(inst.argval) + if isinstance(var, TensorVariable): + self._maybe_emit_sync_dealloc(var) + del self.symbolic_locals[inst.argval] + + def _maybe_emit_sync_dealloc(self, var: TensorVariable) -> None: + from .variables.streams import get_current_stream, new_event + + device = var.device + if device is None or device.type not in ("cuda", "xpu"): + return + + node = var.proxy.node + alloc_stream = node.meta.get("custom", {}).get("stream", None) + + users = set(node.users.keys()) + if not users: + return + last_user = None + for n in self.output.graph.nodes: + if n in users: + last_user = n + if last_user is None or last_user.op == "output": + return + + last_use_stream = last_user.meta.get("custom", {}).get("stream", None) + if alloc_stream == last_use_stream: + return + + if alloc_stream is None: + alloc_stream = get_current_stream(device) + if last_use_stream is None: + last_use_stream = get_current_stream(device) + + event_idx = new_event() + self.output.create_proxy( + "call_function", + torch.ops.streams.record_event, + (event_idx, last_use_stream), + {}, + ) + self.output.create_proxy( + "call_function", + torch.ops.streams.sync_dealloc, + (event_idx, alloc_stream, var.as_proxy()), + {}, + ) + + def STORE_DEREF(self, inst: Instruction) -> None: # type: ignore[override] + if inst.argval not in self.cell_and_freevars(): + raise AssertionError( + "expected inst.argval in self.cell_and_freevars() to be true" + ) + cell = self._cellvar(inst.argval) + val = self.pop() + self.output.side_effects.store_cell(cell, val) + + if not isinstance(cell, CellVariable): + raise AssertionError( + "expected isinstance(cell, CellVariable) to be true" + ) # tame mypy + if cell.local_name is not None: + val.set_name_hint(cell.local_name) # type: ignore[attr-defined] + + def LOAD_CLOSURE(self, inst: Instruction) -> None: + # LOAD_CLOSURE pushes the cell object itself. + self.push(self._cellvar(inst.argval)) + + def _load_const(self, inst: Instruction) -> VariableTracker: + i = inst.arg + if i is None: + return ConstantVariable.create(value=inst.argval) # type: ignore[return-value] + val = self._constants_cache[i] + if not val: + self._constants_cache[i] = ConstantVariable.create(value=inst.argval) # type: ignore[call-overload] + val = self._constants_cache[i] + if val is None: + raise AssertionError("expected val is not None to be true") + return val + + def LOAD_CONST(self, inst: Instruction) -> None: + self.push(self._load_const(inst)) + + def _load_global(self, inst: Instruction) -> None: + name = inst.argval + + if self.exec_recorder: + if name in self.f_globals: + self.exec_recorder.add_global_var(name, self.f_globals[name]) + else: + if name not in self.f_builtins: + raise AssertionError("expected name in self.f_builtins to be true") + self.exec_recorder.builtins[name] = self.f_builtins[name] + + if name not in self.f_globals: + return self.load_builtin(inst) + + if name in self.symbolic_globals: + variable = self.output.side_effects[self.symbolic_globals[name]] + self.push(self.output.side_effects.load_global(variable, name)) + return + + value = self.f_globals[name] + self.push(VariableTracker.build(self, value, GlobalSource(name))) + + @functools.cached_property + def nn_modules_globals_vt(self) -> VariableTracker: + module_name = "torch.nn.modules.module" + module_source = self.import_source(module_name) + fglobals_value = _import_module(module_name) + return VariableTracker.build(self, fglobals_value, module_source) + + def LOAD_GLOBAL(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + if sys.version_info >= (3, 11) and sys.version_info < (3, 13) and inst.arg % 2: + self.PUSH_NULL(inst) + self._load_global(inst) + if sys.version_info >= (3, 13) and inst.arg % 2: + self.PUSH_NULL(inst) + + def STORE_GLOBAL(self, inst: Instruction) -> None: + value = self.pop() + name = inst.argval + source = GlobalSource(name) + if name not in self.symbolic_globals: + self.symbolic_globals[name] = object() # type: ignore[assignment] # sentinel object + variable = self.output.side_effects.track_global_existing( + source, self.symbolic_globals[name] + ) + if isinstance(value, RemovableHandleVariable): + unimplemented( + gb_type="Storing Tensor hook handle in globals", + context=name, + explanation="This is not supported.", + hints=[], + ) + self.output.side_effects.store_global(variable, name, value) + + # Cache note: This cache only exists for the duration of this + # InstructionTranslator - so it should be safe to do. + @cache_method + def import_source(self, module_name: str) -> GlobalSource: + """Create an alias to a module for use in guards""" + if "torch_package" in module_name: + value = torch.package.package_importer._package_imported_modules[ + module_name + ] + alias = ( + module_name.replace(">", "_").replace("<", "_").replace(".", "_dot_") + ) + else: + value = _import_module(module_name) + alias = f"__import_{module_name.replace('.', '_dot_')}" + + if self.package is not None: + self.package.add_import_source(alias, module_name) + self.output.import_sources[alias] = module_name + f_globals = self.output.global_scope + if not (alias not in f_globals or f_globals[alias] is value): + raise AssertionError( + "expected alias not in f_globals or f_globals[alias] is value to be true" + ) + f_globals[alias] = value + self.output.update_co_names(alias) + return GlobalSource(alias) + + def resolve_name(self, name: str, package: str, level: int) -> str: + """ + Copied from the Cpython implementation of __import__ + Resolve a relative module name to an absolute one. + https://github.com/python/cpython/blob/5a094f0255eea1db58fb2cf14c200971e64ec36e/Lib/importlib/_bootstrap.py#L902 + """ + bits = package.rsplit(".", level - 1) + if len(bits) < level: + raise ImportError("attempted relative import beyond top-level package") + base = bits[0] + return f"{base}.{name}" if name else base + + def calc_package(self) -> str: + """ + Copied from the Cpython implementation of __import__ + https://github.com/python/cpython/blob/5a094f0255eea1db58fb2cf14c200971e64ec36e/Lib/importlib/_bootstrap.py#L1090 + """ + package = self.f_globals.get("__package__") + spec = self.f_globals.get("__spec__") + if package is not None: + if spec is not None and package != spec.parent: + log.warning( + "__package__ != __spec__.parent (%r != %r)", + package, + spec.parent, + stacklevel=3, + ) + return package + elif spec is not None: + return spec.parent + else: + log.warning( + "can't resolve package from __spec__ or __package__, " + "falling back on __name__ and __path__", + stacklevel=3, + ) + package = self.f_globals["__name__"] + if "__path__" not in self.f_globals: + package = package.rpartition(".")[0] + return package + + def IMPORT_NAME(self, inst: Instruction) -> None: + level, fromlist = self.popn(2) + level = level.as_python_constant() + fromlist = fromlist.as_python_constant() + module_name = inst.argval + + # Are we replaying? if so, load recorded module + recorded_name = ( + f"{ExecutionRecorder.LOCAL_MOD_PREFIX}_{level}_{fromlist}_{module_name}" + ) + if recorded_name in self.f_globals: + value = self.f_globals[recorded_name] + source = GlobalSource(recorded_name) + else: + try: + value = __import__( + module_name, + fromlist=fromlist, + level=level, + globals=self.f_globals, + ) + except ImportError: + unimplemented( + gb_type="Import failure", + context=f"module_name: {module_name}, fromlist: {fromlist}, level={level}", + explanation="Failure when attempting to import.", + hints=[*graph_break_hints.USER_ERROR], + ) + + if level != 0: + pkg = self.calc_package() + module_name = self.resolve_name(module_name, pkg, level) + + # For __import__, when the name variable is of the form package.module, + # normally, the top-level package (the name up till the first dot) is + # returned, not the module named by module_name. However, when a + # non-empty fromlist argument is given, the module named by name is + # returned. Therefore, we set the source correctly here. + if not fromlist: + top_level_module_name = module_name.partition(".")[0] + source = self.import_source(top_level_module_name) + else: + source = self.import_source(module_name) + + if self.exec_recorder: + # pyrefly: ignore [unbound-name] + self.exec_recorder.add_local_mod(recorded_name, value) + + # pyrefly: ignore [unbound-name] + if isinstance(value, (types.ModuleType, DummyModule)): + # pyrefly: ignore [unbound-name, bad-argument-type] + self.push(PythonModuleVariable(value, source=source)) + else: + unimplemented( + gb_type="Bad import result", + # pyrefly: ignore [unbound-name] + context=typestr(value), + explanation="Import result is not a Python module.", + hints=[], + ) + + # fb internal 3.12 opcode + EAGER_IMPORT_NAME = IMPORT_NAME + + def IMPORT_FROM(self, inst: Instruction) -> None: + self.DUP_TOP(inst) + self._load_attr(inst.argval) + + # Cache note: This cache only exists for the duration of this + # InstructionTranslator - so it should be safe to do. + @cache_method + def load_builtin_from_argval(self, argval: Any) -> VariableTracker: + if argval not in self.f_builtins: + # Name is neither a global nor a builtin: matches CPython raising + # NameError with `name` set to the missing identifier. + raise_observed_exception( + NameError, + self, + args=[f"name '{argval}' is not defined"], + kwargs={"name": ConstantVariable.create(argval)}, + ) + val = self.f_builtins[argval] + + if callable(val): + builtins_source = GlobalSource( + self.output.name_of_builtins_dict_key_in_fglobals + ) + var_source = DictGetItemSource(builtins_source, argval) + return VariableTracker.build(self, val, var_source) + else: + if not is_builtin_constant(val): + raise AssertionError("expected is_builtin_constant(val) to be true") + return VariableTracker.build(self, val) + + def load_builtin(self, inst: Instruction) -> None: + self.push(self.load_builtin_from_argval(inst.argval)) + + def jump(self, inst: Instruction | BlockStackEntry) -> None: + if self.instruction_pointer is None: + raise AssertionError( + "expected self.instruction_pointer is not None to be true" + ) + if self.start_point is None: + raise AssertionError("expected self.start_point is not None to be true") + if inst.target is None: + raise AssertionError("expected inst.target is not None to be true") + get_metrics_context().increment( + "ir_count", self.instruction_pointer - self.start_point + ) + self.instruction_pointer = self.indexof[inst.target] + self.start_point = self.instruction_pointer + + JUMP_FORWARD = jump + JUMP_ABSOLUTE = jump + + POP_JUMP_IF_FALSE = generic_jump(operator.not_, False) + POP_JUMP_IF_TRUE = generic_jump(operator.truth, False) + JUMP_IF_FALSE_OR_POP = generic_jump(operator.not_, True) + JUMP_IF_TRUE_OR_POP = generic_jump(operator.truth, True) + + def SETUP_LOOP(self, inst: Instruction) -> None: + # only exists in python<=3.7 + if inst.target is None: + raise AssertionError("expected inst.target is not None to be true") + self.block_stack.append(BlockStackEntry(inst, inst.target, len(self.stack))) + + def SETUP_EXCEPT(self, inst: Instruction) -> None: + # only exists in python<=3.7 + if inst.target is None: + raise AssertionError("expected inst.target is not None to be true") + self.block_stack.append(BlockStackEntry(inst, inst.target, len(self.stack))) + + def POP_BLOCK(self, inst: Instruction) -> None: + self.block_stack.pop() + + def SETUP_WITH(self, inst: Instruction) -> None: + self.setup_or_before_with(inst) + + def SETUP_FINALLY(self, inst: Instruction) -> None: + if inst.target is None: + raise AssertionError("expected inst.target is not None to be true") + self.block_stack.append(BlockStackEntry(inst, inst.target, len(self.stack))) + + def FOR_ITER(self, inst: Instruction) -> None: + # in 3.15+, make sure TOS remains a null + if sys.version_info >= (3, 15): + null = self.pop() + it = self.pop().realize() + self.push(it) + if sys.version_info >= (3, 15): + self.push(null) + try: + val = it.next_variable(self) + self.push(val) + except ( + StopIteration, + exc.ObservedUserStopIteration, + exc.ObservedIndexError, + ) as e: + if isinstance(e, (exc.ObservedUserStopIteration, exc.ObservedIndexError)): + exc.handle_observed_exception(self) + + if sys.version_info >= (3, 12): + # CPython 3.12 actually jumps to the instruction after the END_FOR + # and performs the action of END_FOR as part of FOR_ITER. We jump + # to the END_FOR and run it, so we need to make sure 2 values are + # on the stack for it to pop. + self.push(ConstantVariable.create(None)) + else: + # pop the iterator in Python < 3.12 + self.pop() + self.jump(inst) + + def _create_exception_instance( + self, val: ExceptionTypes | ExceptionVals + ) -> ExceptionVals: + if pyexception_class_check(val): + # Create the instance of the exception type + # https://github.com/python/cpython/blob/3.11/Python/ceval.c#L6547-L6549 + type_name = val.python_type_name() + val = val.call_function(self, [], {}) # type: ignore[arg-type] + + if not issubclass(val.python_type(), BaseException): + exc.raise_type_error( + self, + f"calling {type_name} should have returned an instance of BaseException, not {val.python_type_name()}", + ) + if not pyexception_instance_check(val): + exc.raise_type_error( + self, + "exceptions must derive from BaseException", + ) + return val + + def set_exception_obj( + self, exception: ExceptionTypes, value: VariableTracker | None + ) -> ExceptionVals: + # Mirrors CPython PyErr_SetObject + # Note: This function is here rather than in ExceptionStack because we + # need an InstructionTranslator instance to create the exception instance + + # TODO(dynamo-team): check if exception is a subclass of BaseException + + # This function handles construction, normalization, implicit + # __context__ chaining and traceback attach. + # if value is specified, it can be either an exception instance or args + # to exception ctor + + if ( + value + and pyexception_instance_check(value) + and issubclass(value.exc_type, exception.fn) + ): + instance = value + else: + instance = exception.call_function(self, [value] if value else [], {}) + + if not isinstance(instance, ExceptionVals): + raise AssertionError("expected instance to be an instance of ExceptionVals") + + self._attach_traceback_to_exception(instance) + self.exn_vt_stack._set_context_and_break_context_reference_cycle(instance) + self.exn_vt_stack.set_raised_exception(instance) + return instance + + def _attach_traceback_to_exception(self, exc: ExceptionVals) -> None: + # based on CPython's PyTraceBack_Here impl + frame_summary = self.frame_summary() + tb = exc.tp_getattro_impl( + # pyrefly: ignore [bad-argument-type] + self, + "__traceback__", + ) + if not isinstance(tb, (ConstantVariable, TracebackVariable)): + raise AssertionError( + "expected isinstance( tb, (ConstantVariable, TracebackVariable) ) to be true" + ) # make pyrefly happy + new_tb = TracebackVariable.from_frame_summary(frame_summary, tb) + exc.call_method( + self, # type: ignore[bad-argument-type] + "__setattr__", + [VariableTracker.build(self, "__traceback__"), new_tb], + {}, + ) + + def _raise_observed_exception(self, exc_: ExceptionVals) -> NoReturn: + # Propagate `exc_` as an ObservedException to unwind the tracer to the + # handler, preserving the original raise location via python_stack. + observed_exception_type = get_dynamo_observed_exception(exc_.exc_type) # type: ignore[attr-defined, union-attr] + python_stack = getattr(exc_, "python_stack", None) + raise observed_exception_type( + f"raised exception {exc_.debug_repr()}", real_stack=python_stack + ) + + def do_raise( + self, + val: VariableTracker | None, + cause: VariableTracker | None, + ) -> NoReturn: + # Mirrors CPython's `do_raise` + # https://github.com/python/cpython/blob/704c4c79e8485c20fb59cea1acec005f365a4fca/Python/ceval.c#L1900 + + # User can raise exception in 3 ways + # 1) raise + # 2) raise + # 3) raise + + # bare raise + if val is None: + # reraise the exception on top of the exception stack + if not len(self.exn_vt_stack): + exc.raise_observed_exception( + RuntimeError, self, args=["No active exception to reraise"] + ) + val = self.exn_vt_stack.get_topmost_exception() + self.exn_vt_stack.set_raised_exception(val) + self._raise_observed_exception(val) + + # normalize type/value + if pyexception_class_check(val): + type_ = val + value = self._create_exception_instance(val) + elif pyexception_instance_check(val): + value = val + type_ = VariableTracker.build(self, val.python_type()) + else: + # not something we can raise + exc.raise_type_error(self, "exceptions must derive from BaseException") + + # normalize cause (`raise from `) + if cause: + if pyexception_class_check(cause): + fixed_cause = self._create_exception_instance(cause) + elif pyexception_instance_check(cause) or cause.is_constant_none(): + fixed_cause = cause + else: + exc.raise_type_error( + self, + "exception causes must derive from BaseException", + ) + value.call_method( + self, + "__setattr__", + [ConstantVariable.create("__cause__"), fixed_cause], + {}, + ) + + # Capture the python_stack when the exception is first raised. + # This preserves the original exception location even if the exception + # is later re-raised (e.g., in context manager cleanup). + # ExceptionVariable and UserDefinedExceptionObjectVariable both have + # a python_stack attribute. + if getattr(value, "python_stack", None) is None: + value.python_stack = torch._guards.TracingContext.extract_stack() # type: ignore[union-attr] + + exc_instance = self.set_exception_obj(type_, value) + self._raise_observed_exception(exc_instance) + + def RAISE_VARARGS(self, inst: Instruction) -> None: + if inst.arg == 0: + # bare raise; do_raise reraises the exception on top of the stack, + # or reports "No active exception to reraise" if the stack is empty + self.do_raise(None, None) + elif inst.arg == 1: + # raise TOS + val = self.stack[-1] # type: ignore[assignment] + self.do_raise(val, None) + else: + # raise .. from ... + cause = self.pop() + val = self.pop() # type: ignore[assignment] + self.do_raise(val, cause) + + def CLEANUP_THROW(self, inst: Instruction) -> None: + # https://github.com/python/cpython/pull/96010 + tos = self.stack[-1] + if not isinstance(tos, ExceptionVals): + raise AssertionError("expected isinstance(tos, ExceptionVals) to be true") + if issubclass(tos.exc_type, StopIteration): + self.popn(3) + self.push(ConstantVariable.create(None)) + self.push(tos.args[0] if tos.args else ConstantVariable.create(None)) + else: + self.RERAISE(inst) + + def RERAISE(self, inst: Instruction) -> None: + # https://docs.python.org/3/library/dis.html#opcode-RERAISE + # Re-raises the exception currently on top of the stack. If oparg is + # non-zero, pops an additional value from the stack which is used to + # set f_lasti of the current frame. + + if sys.version_info >= (3, 11): + # Re-raise the exception on top of the stack. + val = self.pop() + if not pyexception_instance_check(val): + raise AssertionError( + "expected _exception_instance_check(val) to be true" + ) + if inst.argval: + # RERAISE 1 + _ = self.pop() + self.exn_vt_stack.set_raised_exception(val) + else: + # RERAISE 0 + self.push(val) + self.exn_vt_stack.set_raised_exception(val) + self._raise_observed_exception(val) + else: + _exc = self.pop() + val = self.pop() + _tb = self.pop() + if not pyexception_instance_check(val): + raise AssertionError( + "expected _exception_instance_check(val) to be true" + ) + self.exn_vt_stack.set_raised_exception(val) + self._raise_observed_exception(val) + + def WITH_EXCEPT_START(self, inst: Instruction) -> None: + args: list[VariableTracker] = [] + if sys.version_info >= (3, 11): + fn_loc = 4 if sys.version_info < (3, 14) else 5 + # At the top of the stack are 4 values: + # - TOP = exc_info() + # - SECOND = previous exception + # - THIRD: lasti of exception in exc_info() + # - FOURTH: the context.__exit__ bound method + # We call FOURTH(type(TOP), TOP, GetTraceback(TOP)). + # Then we push the __exit__ return value. + # In Python 3.14+, there is a NULL placed between the context.__exit__ bound method and the lasti, + # that is, fn is now the 5th from TOS. + if not (len(self.stack) >= fn_loc): + raise AssertionError("expected len(self.stack) >= fn_loc to be true") + fn = self.stack[-fn_loc] + val = self.stack[-1] + if not pyexception_instance_check(val): + raise AssertionError( + "expected _exception_instance_check(val) to be true" + ) + typ = BuiltinVariable(val.exc_type) # type: ignore[attr-defined, union-attr] + tb = val.tp_getattro_impl( + # pyrefly: ignore[bad-argument-type] + self, + "__traceback__", + ) + if sys.version_info >= (3, 14): + if not isinstance(self.stack[-4], NullVariable): + args.append(self.stack[-4]) + else: + if not (len(self.stack) >= 7): + raise AssertionError("expected len(self.stack) >= 7 to be true") + fn = self.stack[-7] + val = self.stack[-2] + if not pyexception_instance_check(val): + raise AssertionError( + "expected _exception_instance_check(val) to be true" + ) + typ = BuiltinVariable(val.exc_type) # type: ignore[attr-defined] + + tb = val.tp_getattro_impl(self, "__traceback__") + + args += [typ, val, tb] + self.call_function(fn, args, {}) + + def exception_handler(self, raised_exception: ObservedException) -> None: + observed_exn_gb_explanation = ( + "Dynamo found no exception handler at the top-level compiled function " + "when encountering an exception. Exception will propagate outside the compiled region." + ) + + def bubble_exception_to_interpreter() -> None: + # Bubble the exception to the interpreter + if isinstance(raised_exception, FakeTensorObservedException): + from .exc import format_graph_break_message + + msg = format_graph_break_message( + "RuntimeError when making fake tensor call", + "", + str(raised_exception), + [*graph_break_hints.USER_ERROR], + ) + e = exc.TorchRuntimeError( + msg, getattr(raised_exception, "real_stack", None) + ) + raise e.with_traceback(raised_exception.__traceback__) from None + + curr_exc = self.exn_vt_stack.get_raised_exception() + dynamo_exc = exc.get_dynamo_observed_exception(curr_exc.python_type()) + if not isinstance(raised_exception, dynamo_exc): + raise AssertionError( + "expected isinstance(raised_exception, dynamo_exc) to be true" + ) # sanity check + unimplemented( + gb_type="Observed exception", + context=f"raised exception {curr_exc.debug_repr()}", + explanation=observed_exn_gb_explanation, + hints=[ + *graph_break_hints.USER_ERROR, + *graph_break_hints.SUPPORTABLE, + ], + from_exc=raised_exception, + ) + + if sys.version_info >= (3, 11): + exn_tab_entry = self.current_instruction.exn_tab_entry + if exn_tab_entry: + # Implementation is based on https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt + + # 1) pop values from the stack until it matches the stack depth + # for the handler + while len(self.stack) > exn_tab_entry.depth: + self.pop() + + # 2) if 'lasti' is true, then push the offset that the exception was raised at + if exn_tab_entry.lasti: + self.push( + VariableTracker.build(self, self.current_instruction.offset) + ) + + # 3) push the exception to the stack + self.push(self.exn_vt_stack.get_raised_exception()) + + # 4) jump to the handler + self.jump(exn_tab_entry) # type: ignore[arg-type] + else: + # No handler found. Bubble the exception to the parent + # instruction translator. We use special exception for this. + self.stack.clear() + + # attach traceback to the exception and set it as current exception + curr_exc = self.exn_vt_stack.get_raised_exception() + self._attach_traceback_to_exception(curr_exc) + + if type(self) is InstructionTranslator: + bubble_exception_to_interpreter() + raise raised_exception + else: + if len(self.block_stack): + # base implementation - https://github.com/python/cpython/blob/3.10/Python/ceval.c#L4455 + + block_stack_entry = self.block_stack.pop() + + while block_stack_entry.inst.opname == "EXCEPT_HANDLER": + # https://github.com/python/cpython/blob/3.10/Python/ceval.c#L1456 + self.popn(3) + self.exn_vt_stack.pop() + if len(self.block_stack) == 0: + # No handler found in this frame. Bubble the exception to the parent + # instruction translator. + self.stack.clear() + if type(self) is InstructionTranslator: + bubble_exception_to_interpreter() + + raise raised_exception + block_stack_entry = self.block_stack.pop() + + exception_var = self.exn_vt_stack.get_raised_exception() + self.exn_vt_stack.move_current_exception_to_stack() + + # 1) pop values from the stack until it matches the stack depth + # for the handler + while len(self.stack) > block_stack_entry.stack_index: + self.pop() + + # Push a dummy block stack entry of EXCEPT_HANDLER + # https://github.com/python/cpython/blob/3.10/Python/ceval.c#L1456 + except_handler_inst = Instruction(int(1e6), "EXCEPT_HANDLER", None, 0) + self.block_stack.append( + BlockStackEntry(except_handler_inst, None, len(self.stack)) + ) + + # Push old exception + if len(self.exn_vt_stack) >= 2: + old_exception = self.exn_vt_stack[-2] + + # Push the old exception on to stack - tb, value, type + # Traceback is currently mapped to UnknownVariable + self.push(variables.UnknownVariable()) + self.push(old_exception) + + self.push(variables.BuiltinVariable(old_exception.exc_type)) + else: + # Push empty exception tb, value, type + self.push(ConstantVariable.create(None)) + self.push(ConstantVariable.create(None)) + self.push(ConstantVariable.create(None)) + + # Push new exception - tb, val, type + # Traceback is currently mapped to UnknownVariable + self.push(variables.UnknownVariable()) + self.push(exception_var) + + self.push(variables.BuiltinVariable(exception_var.exc_type)) + + # Jump to target + self.jump(block_stack_entry) + else: + # No handler found. Bubble the exception to the parent + # instruction translator. We use special exception for this. + self.stack.clear() + if type(self) is InstructionTranslator: + bubble_exception_to_interpreter() + raise raised_exception + + def PUSH_EXC_INFO(self, inst: Instruction) -> None: + # https://docs.python.org/3/library/dis.html#opcode-PUSH_EXC_INFO + # Pops a value from the stack. Pushes the current exception to the top + # of the stack. Pushes the value originally popped back to the stack. + # + # The behavior of this opcode in CPython is a bit different than what it + # is described. It pops a value from the stack, pushes the top of the + # exception stack to the interpreter stack and moves the + # "current exception" to the exception stack. + # + # As an example, suppose the stack is in the following state: + # + stack = [..., ConstantVariable(1), ConstantVariable(2)] + # + current_exception = TypeError + # + exception_stack = [ValueError] + # + # After PUSH_EXC_INFO is executed + # + stack = [..., ConstantVariable(1), ValueError, ConstantVariable(2)] + # + current_exception = None + # + exception_stack = [ValueError, TypeError] + + val = self.pop() + if len(self.exn_vt_stack) == 0: + prev_exc: VariableTracker = ConstantVariable.create(None) + else: + prev_exc = self.exn_vt_stack[-1] + self.push(prev_exc) + self.push(val) + self.exn_vt_stack.move_current_exception_to_stack() + + def POP_EXCEPT(self, inst: Instruction) -> None: + if sys.version_info >= (3, 11): + _ = self.pop() + # This exception is handled and therefore we can clear the error indicator + if not len(self.exn_vt_stack): + raise AssertionError("expected len(self.exn_vt_stack) to be true") + self.exn_vt_stack.pop() + else: + if not (len(self.block_stack) > 0): + raise AssertionError("expected len(self.block_stack) > 0 to be true") + if self.block_stack[-1].inst.opname != "EXCEPT_HANDLER": + raise AssertionError( + "Bug in Dynamo tracing of exception handling." + "Top of the block stack is not EXCEPT_HANDLER." + ) + self.block_stack.pop() + + self.popn(3) + + # This exception is handled and therefore we can clear the error indicator + if not len(self.exn_vt_stack): + raise AssertionError("expected len(self.exn_vt_stack) to be true") + self.exn_vt_stack.pop() + + def check_if_exc_matches(self) -> bool: + if not (len(self.stack) >= 2): + raise AssertionError("expected len(self.stack) >= 2 to be true") + expected_exc_types = self.pop() + if sys.version_info >= (3, 11): + # CHECK_EXC_MATCH (which is used from 3.11 onwards) does not pop. + # This is the description from the disassembly doc + # + # Performs exception matching for ``except``. Tests whether the ``STACK[-2]`` + # is an exception matching ``STACK[-1]``. Pops ``STACK[-1]`` and pushes the boolean + # result of the test. + exc_instance = self.stack[-1] + else: + # This is used prior to 3.11 via opcode JUMP_IF_NOT_EXC_MATCH + # There is no documentation but here is the code pointer that does 2 pops + # https://github.com/python/cpython/blob/3.10/Python/ceval.c#L3650-L3665 + exc_instance = self.stack.pop() + + # Users can check exception in 3 ways + # 1) except NotImplementedError --> BuiltinVariable + # 2) except CustomException --> UserDefinedExceptionClassVariable + # 3) except (NotImplementedError, AttributeError) -> TupleVariable + + if not isinstance( + expected_exc_types, + ( + BuiltinVariable, + TupleVariable, + UserDefinedExceptionClassVariable, + UserDefinedExceptionObjectVariable, + ), + ): + unimplemented( + gb_type="Exception with bad expected type", + context=str(expected_exc_types), + explanation=f"`except ...` has unsupported type {expected_exc_types}.", + hints=[*graph_break_hints.USER_ERROR], + ) + + if sys.version_info >= (3, 11): + if not pyexception_instance_check(exc_instance): + unimplemented( + gb_type="Caught non-Exception value", + context=str(exc_instance), + explanation=f"Except expects to receive an object of Exception type but received {exc_instance}.", + hints=[*graph_break_hints.USER_ERROR], + ) + + if isinstance(expected_exc_types, TupleVariable): + expected_types = expected_exc_types.items + else: + expected_types = [ + expected_exc_types, + ] + + for expected_type in expected_types: + if not isinstance( + expected_type, + ( + BuiltinVariable, + UserDefinedExceptionObjectVariable, + UserDefinedExceptionClassVariable, + ), + ): + unimplemented( + gb_type="Exception with non-type expectation", + context=str(expected_type), + explanation=f"`except ...` expects a non-type: {expected_type}.", + hints=[*graph_break_hints.USER_ERROR], + ) + if pyexception_instance_check(exc_instance) and issubclass( + exc_instance.exc_type, # type: ignore[union-attr] + expected_type.fn, # type: ignore[attr-defined] + ): + return True + elif isinstance(exc_instance, variables.BuiltinVariable) and issubclass( + exc_instance.fn, + # pyrefly: ignore [invalid-argument] + expected_type.fn, + ): + return True + + return False + + def CHECK_EXC_MATCH(self, inst: Instruction) -> None: + self.push(VariableTracker.build(self, self.check_if_exc_matches())) + + def JUMP_IF_NOT_EXC_MATCH(self, inst: Instruction) -> None: + if not self.check_if_exc_matches(): + self.jump(inst) + + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace COMPARE_OP: a comparison operation, e.g. a == b", + ) + def COMPARE_OP(self, inst: Instruction) -> None: + if inst.argval == "exception match": + self.CHECK_EXC_MATCH(inst) + else: + self.push(compare_op_handlers[inst.argval](self, self.popn(2), {})) + + def GET_ITER(self, inst: Instruction) -> None: + # This is intentionally different from cpython 3.15+. Cpython creates virtual iterators for certain types + # (i.e. lists/tuples), represented on the stack by the iterable + an integer index. Other types call the + # builtin iter and are represented by iterator + null. We could mimic this in dynamo, but it becomes + # problematic for resuming from graph breaks in list comprehensions. Cpython uses tagged ints (not PyObject) to + # represent the index, and we can only restore boxed ints, which creates an invalid stack state. So instead of + # trying, we just always create a true iterator. + self.push(generic_getiter(self, self.pop())) + if sys.version_info >= (3, 15): + self.push(NullVariable()) + + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace CALL_FUNCTION: a call to a regular function, e.g. f(x, y)", + ) + def CALL_FUNCTION(self, inst: Instruction) -> None: + args = self.popn(inst.argval) + fn = self.pop() + self.call_function(fn, args, {}) + + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace CALL_FUNCTION_EX: a variadic function call, e.g. f(*args)", + ) + def CALL_FUNCTION_EX(self, inst: Instruction) -> None: + kwargsvars: VariableTracker + if inst.argval == 0: + kwargsvars = ConstDictVariable({}) + argsvars = self.pop() + elif inst.argval == 1 or sys.version_info >= (3, 14): + # Python 3.14+ removed the argval and replaced it with a possibly NULL kwargs + kwargsvars = self.pop() + if isinstance(kwargsvars, NullVariable): + kwargsvars = ConstDictVariable({}) + argsvars = self.pop() + else: + unimplemented( + gb_type="Variadic function call with bad flags", + context=f"flags: {inst.argval}", + explanation=f"Attempted to call a variadic function (CALL_FUNCTION_EX) with bad flags {inst.argval}", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + if sys.version_info >= (3, 13): + # 3.13 swapped null and callable + null = self.pop() + if not isinstance(null, NullVariable): + raise AssertionError( + "expected isinstance(null, NullVariable) to be true" + ) + + fn = self.pop() + + if sys.version_info >= (3, 11) and sys.version_info < (3, 13): + null = self.pop() + if not isinstance(null, NullVariable): + raise AssertionError( + "expected isinstance(null, NullVariable) to be true" + ) + + if not isinstance( + argsvars, + BaseListVariable, + ): + argsvars = TupleVariable(unpack_iterable(self, argsvars)) + + # Unpack for cases like fn(**obj) where obj is a map + if isinstance(kwargsvars, UserDefinedObjectVariable): + kwargsvars = DictBuiltinVariable.call_custom_dict(self, dict, kwargsvars) # type: ignore[arg-type] + + # pyrefly: ignore [unbound-name] + if not isinstance(argsvars, BaseListVariable) or not isinstance( + # pyrefly: ignore [unbound-name] + kwargsvars, + ConstDictVariable, + ): + unimplemented( + gb_type="Variadic function call with bad args/kwargs type", + # pyrefly: ignore [unbound-name] + context=f"args type: {typestr(argsvars)}, kwargs type: {typestr(kwargsvars)}", + explanation="Expected args to be a list and kwargs to be a dict", + hints=[*graph_break_hints.USER_ERROR], + ) + + # Map to a dictionary of str -> VariableTracker + # pyrefly: ignore [bad-assignment, unbound-name] + kwargsvars = kwargsvars.keys_as_python_constant() + # pyrefly: ignore [bad-argument-type, unbound-name] + self.call_function(fn, argsvars.items, kwargsvars) + + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace CALL_FUNCTION_KW: " + "a function call with keyword arguments, e.g. f(x=True)", + ) + def CALL_FUNCTION_KW(self, inst: Instruction) -> None: + argnames = self.pop() + args = self.popn(inst.argval) + fn = self.pop() + if not isinstance(argnames, TupleVariable): + raise AssertionError( + "expected isinstance(argnames, TupleVariable) to be true" + ) + if not argnames.is_python_constant(): + raise AssertionError("expected argnames.is_python_constant() to be true") + argnames = argnames.as_python_constant() + args, kwargs_list = args[: -len(argnames)], args[-len(argnames) :] + kwargs = dict(zip(argnames, kwargs_list)) + if len(kwargs) != len(argnames): + raise AssertionError("expected len(kwargs) == len(argnames) to be true") + self.call_function(fn, args, kwargs) + + def LOAD_METHOD_SUPER(self, inst: Instruction) -> None: + self.CALL_FUNCTION(dataclasses.replace(inst, argval=2)) + arg = inst.argval[0] + argval = self.code_options["co_names"][arg] + if sys.version_info < (3, 11): + self._load_attr(argval) + else: + self.LOAD_METHOD(dataclasses.replace(inst, argval=argval)) + + def LOAD_ATTR_SUPER(self, inst: Instruction) -> None: + self.CALL_FUNCTION(dataclasses.replace(inst, argval=2)) + arg = inst.argval[0] + argval = self.code_options["co_names"][arg] + self._load_attr(argval) + + def LOAD_METHOD(self, inst: Instruction) -> None: + self._load_attr(inst.argval) + obj = self.pop() + if sys.version_info >= (3, 13): + self.push(obj) + self.PUSH_NULL(inst) + elif sys.version_info >= (3, 11): + # always follow the NULL + fn convention, since if obj + # is actually a method, self is already bound to it, so it + # doesn't need to be passed in as an arg. + self.PUSH_NULL(inst) + self.push(obj) + else: + raise AssertionError( + "LOAD_METHOD should have been rewritten to LOAD_ATTR. We should never reach here." + ) + + def CALL_METHOD(self, inst: Instruction) -> None: + raise AssertionError( + "CALL_METHOD should have been rewritten to CALL_FUNCTION. This function should never be called." + ) + + def _load_attr(self, attr: Any) -> None: + obj = self.pop().realize() + try: + result = generic_getattr(self, obj, attr) + except Unsupported: + if not obj.is_python_constant(): + raise + source = AttrSource(obj.source, attr) if obj.source else None + result = VariableTracker.build( + self, getattr(obj.as_python_constant(), attr), source=source + ) + self.push(result) + + def LOAD_ATTR(self, inst: Instruction) -> None: + if sys.version_info >= (3, 12): + if inst.arg is None or inst.arg % 2 != 0: + raise AssertionError( + "LOAD_ATTR method variant should have been normalized by " + "remove_load_attr_method_variant in cleaned_instructions" + ) + self._load_attr(inst.argval) + + @break_graph_if_unsupported( + push=False, + msg_prefix="Encountered graph break when attempting to trace STORE_ATTR: storing an object's attribute, e.g. x.attr = y", + ) + def STORE_ATTR(self, inst: Instruction) -> None: + val, obj = self.popn(2) + VariableTracker.build(self, setattr).call_function( + self, # type: ignore[arg-type] + [obj, VariableTracker.build(self, inst.argval), val], + {}, + ) + + def DELETE_ATTR(self, inst: Instruction) -> None: + obj = self.pop() + self._maybe_sync_dealloc_attr(obj, inst.argval) + VariableTracker.build(self, delattr).call_function( + self, # type: ignore[arg-type] + [obj, VariableTracker.build(self, inst.argval)], + {}, + ) + + def _maybe_sync_dealloc_attr(self, obj: VariableTracker, name: str) -> None: + # Only check side_effects — a pure dict lookup with no observable + # side effects. We intentionally avoid tp_getattro_impl here because it + # can trigger __getattr__, add graph nodes, or cause graph breaks. + if self.output.side_effects.has_pending_mutation_of_attr(obj, name): + attr_var = self.output.side_effects.load_attr(obj, name) + if isinstance(attr_var, TensorVariable): + self._maybe_emit_sync_dealloc(attr_var) + + @staticmethod + def codegen_return_with_pops( + inst: Instruction, num_stack: int + ) -> list[Instruction]: + """ + Debug CPython expects the stack to be empty after the return. + Calling compile_subgraph will push cells and frame values to TOS. + This function will pop those 2 values from the stack before actually returning. + + Expects the stack to be: + cells, frame values, current frame stack (0 or 1 values) + + Pops cells and frame values, leaving the current frame stack as TOS. + A return instruction is included. + """ + insts = [] + # NOTE: Debug CPython expects the stack to be empty after the return. + # Expect the current stack to be in the state + # cells, frame values, current frame stack (0 or 1 values) + if not (num_stack <= 1): + raise AssertionError("expected num_stack <= 1 to be true") + if num_stack == 1: + insts.extend(create_swap(3)) + return_inst = ( + create_instruction("RETURN_VALUE") + if inst.opname == "RETURN_VALUE" + else create_instruction("RETURN_CONST", argval=inst.argval) + ) + insts.extend( + [create_instruction("POP_TOP"), create_instruction("POP_TOP"), return_inst] + ) + return insts + + def create_resume( + self, + idx: int, + resume_inst: Instruction, + meta: StackLocalsMetadata, + resume_codes: list[types.CodeType], + cg: PyCodegen, + is_leaf: bool, + handle_inactive_ctx: bool, + ) -> tuple[types.CodeType, str]: + """ + Creates the resume function for the frame corresponding to `self`. + + Expects the TOS to be: + [frame N cells, ..., frame 1 cells], + [ + frame N stack + locals, + ..., + frame 1 stack + locals + ] + + Some additional codegen may happen to prepare the frame stack + locals values for the generated resume function: + - inactive context variables in the stack and locals will be replaced by their types + - if the frame is a leaf frame, prune dead locals + + Regardless of codegen, the stack will be left in the same state as before. + + Args: + - idx: depth of this frame: 0 corresponds to the leaf frame (frame N), N-1 to the root frame (frame 1). + - resume_inst: the instruction that this frame should resume at + - meta: metadata for this frame returned from OutputGraph.compile_subgraph + - resume_codes: nested resume code objects generated from previous create_resume calls. + - cg: codegen object to output to + - is_leaf: True if `self` corresponds to the leaf frame. + - handle_inactive_ctx: If True, handles inactive context variables as described above. This is necessary + iff the resume function is traced + """ + # Handle inactive context variables. + # The resume function assumes that context variables are the class, NOT the object. + # e.g. torch.set_grad_enabled(True) will be reconstructed as torch.set_grad_enabled + # NOTE: if the unsupported instruction modifies the inactive context variable, it may + # result in silent incorrectness! + if handle_inactive_ctx: + for (j, _), j_orig in zip(meta.stack_ctx_args, meta.stack_ctx_idxes_orig): + # Replace the stack var with the context class + ctx = cast(ContextWrappingVariable, self.stack[j_orig]) + # frames[idx][j] = reconstructed_ctx + cg.append_output(create_dup_top()) + ctx.reconstruct_type(cg) + cg.extend_output( + [ + *create_swap(2), + cg.create_load_const(idx), + cg.create_binary_subscr(), + cg.create_load_const(j), + create_instruction("STORE_SUBSCR"), + ] + ) + + for name, _ in meta.locals_ctx_args: + # Replace the local with the context class + ctx = cast(ContextWrappingVariable, self.symbolic_locals[name]) + # frames[idx][meta.num_stack +meta.locals_names[name]] = reconstructed_ctx + cg.append_output(create_dup_top()) + ctx.reconstruct_type(cg) + cg.extend_output( + [ + *create_swap(2), + cg.create_load_const(idx), + cg.create_binary_subscr(), + cg.create_load_const(meta.num_stack + meta.locals_names[name]), + create_instruction("STORE_SUBSCR"), + ] + ) + + # If the resume instruction is a jump absolute, then resume + # at the target instead. This handles the case where we + # graph break again in a nested function before jump-resuming + # this frame. + if is_jump_absolute(resume_inst): + if not resume_inst.target: + raise AssertionError("expected resume_inst.target to be true") + resume_inst = resume_inst.target + + resume_name = unique_id(f"__resume_at_{resume_inst.offset}") + + # More locals may have been pruned in the current/leaf frame + # after the unsupported instruction (e.g. branch). + # There should not be any pruning in the other frames since + # the current instruction there should be a CALL. + if is_leaf: + reads = livevars_analysis(self.instructions, resume_inst) + # inspect.signature() renames ".N" to "implicitN" for comprehension + # iterator variables. Build a mapping to emit the bytecode name + # (.0) in argnames so the resume function's co_varnames matches + # the bytecode instructions. + implicit_to_bytecode: dict[str, str] = {} + for name in self.f_code.co_varnames: + if name.startswith("."): + implicit_to_bytecode[name.replace(".", "implicit")] = name + all_argnames = tuple( + implicit_to_bytecode.get(k, k) + for k in self.symbolic_locals + if implicit_to_bytecode.get(k, k) in reads + and k not in self.cell_and_freevars() + ) + argnames_null_set = { + implicit_to_bytecode.get(k, k) for k in meta.locals_null_keys + } + argnames = tuple(k for k in all_argnames if k not in argnames_null_set) + argnames_null = tuple(k for k in all_argnames if k in argnames_null_set) + + # codegen filter for current frame's locals + # current stack state: frames + cg.extend_output( + [ + create_dup_top(), + cg.create_load_const(idx), + cg.create_binary_subscr(), + create_dup_top(), + ] + ) + bytecode_to_implicit = {v: k for k, v in implicit_to_bytecode.items()} + for arg in argnames: + # current stack state: frames, frames[i], *(prev locals), frames[i] + locals_key = bytecode_to_implicit.get(arg, arg) + cg.extend_output( + [ + create_dup_top(), + cg.create_load_const( + meta.num_stack + meta.locals_names[locals_key] + ), + cg.create_binary_subscr(), + *create_swap(2), + ], + ) + # current stack state: frames, frames[i], *(frame i live locals), frames[i] + cg.extend_output( + [ + create_instruction("POP_TOP"), + create_instruction("BUILD_LIST", arg=len(argnames)), + *create_swap(2), + # frames, frames i live locals, frames[i] + *create_binary_slice(meta.num_stack, None, True), + # frames[i][num_stack:] = frame i live locals + ] + ) + # current stack state: frames + else: + argnames = tuple(meta.locals_names.keys()) + argnames_null = tuple(meta.locals_null_keys) + + if sys.version_info < (3, 12): + if len(argnames_null) != 0: + raise AssertionError("variables should not be NULL in < 3.12") + + # compile_subgraph did not codegen any NULLs, + # so we should not count NullVariables + stack_len = len(self.stack) - len(meta.stack_null_idxes) + + if self.current_instruction.offset is None: + raise AssertionError( + "expected self.current_instruction.offset is not None to be true" + ) + new_code: types.CodeType = ContinueExecutionCache.lookup( + self.f_code, + self.lineno, + self.current_instruction.offset, + resume_inst.offset, + # pyre: ignore[missing-attribute] + tuple(b.target.offset for b in self.block_stack), + stack_len, + argnames, + argnames_null, + tuple(b.resume_fn() for b in self.block_stack), + handle_inactive_ctx, + tuple(meta.stack_ctx_args), + tuple(meta.locals_ctx_args), + tuple(meta.stack_null_idxes), + tuple(resume_codes), + not self.current_instruction_push, + ) + + # Add original GraphModule context to the resume function to handle + # the case of a graph break while tracing a GraphModule + orig_graphmodule_maybe = code_context.get_context(self.f_code).get( + "orig_graphmodule", lambda: None + )() + if orig_graphmodule_maybe is not None: + code_context.get_context(new_code)["orig_graphmodule"] = weakref.ref( + orig_graphmodule_maybe + ) + + # add resume function to the global scope + self.output.install_resume_function_global( + resume_name, new_code, self.f_globals + ) + if self.package is not None: + self.package.add_resume_function( + new_code, self.f_globals["__name__"], resume_name + ) + + counters["resumes"][new_code.co_name] += 1 + + return new_code, resume_name + + def _maybe_replace_warnings_warn_on_stack(self, inst: Instruction) -> None: + """Replace warnings.warn on the symbolic stack with a wrapper that + preserves the leaf frame's source location for warning dedup. + + When nested graph breaks inline a warnings.warn call into the root + frame's bytecode, the root frame's line numbers defeat Python's + per-location warning dedup. This replaces the SkipFunctionVariable + for warnings.warn on the symbolic stack before compile_subgraph, so + the codegen naturally reconstructs the wrapper via LOAD_GLOBAL. + """ + if inst.arg is None: + return + + try: + depth = get_call_callable_depth(inst.opname, inst.arg) + except ValueError: + return + + callable_idx = len(self.stack) - depth + callable_var = self.stack[callable_idx] + if not ( + isinstance(callable_var, SkipFunctionVariable) + and callable_var.value is _warnings.warn + ): + return + + leaf_filename = self.f_code.co_filename + leaf_lineno = inst.positions.lineno if inst.positions else inst.starts_line + if leaf_lineno is None: + return + + wrapper = _make_warnings_warn_wrapper(leaf_filename, leaf_lineno) + wrapper_name = self.output.install_global("__warnings_warn_wrapper", wrapper) + self.stack[callable_idx] = SkipFunctionVariable( + wrapper, source=GlobalSource(wrapper_name) + ) + + def create_call_resume_at( + self, + inst: Instruction, + all_stack_locals_metadata: list[StackLocalsMetadata], + ) -> list[Instruction]: + """ + Codegen all resume function(s) from the frame stack starting at `self`, call them, + and return the result. + Assumes that the unsupported instruction has already been run. + + Expects the TOS to be: + [ + frame N locals, + frame N-1 stack + locals, + ..., + frame 1 stack + locals + ], *(frame N stack (post-unsupported instruction)) + + Leaves the result of calling the resume functions on the stack and returns it + (empty stack after return). + + Args: + - inst: the instruction of the current (deepest) frame to resume at + - all_stack_locals_metadata: metadata returned from OutputGraph.compile_subgraph - contains + metadata such as local names, NULL positions, stack length, etc. + """ + + self.instruction_pointer = None + + cg = PyCodegen(self.output.root_tx) + + # NOTE: We do not need to codegen frames whose resume instruction is RETURN_VALUE + # We could also do something similar for RETURN_CONST, but a lot more code is necessary + # since we would need to track RETURN_CONST values and inject the constant in the right places. + + # Filter out tx'es that are resuming on RETURN_*. + txes: list[InstructionTranslatorBase] = [] + idxes: list[int] = [] + resume_insts: list[Instruction] = [] + cur_tx: InstructionTranslatorBase | None = self + idx = 0 + while cur_tx is not None: + if cur_tx is self: + resume_inst = inst + else: + resume_inst = cur_tx.next_instruction + if resume_inst.opname != "RETURN_VALUE": + txes.append(cur_tx) + idxes.append(idx) + resume_insts.append(resume_inst) + + cur_tx = cur_tx.parent + idx += 1 + + current_num_stack = len(self.stack) - len( + all_stack_locals_metadata[0].stack_null_idxes + ) + + # Every tx is returning - no need to call a resume function. + if not txes: + # Pop everything but TOS, then return the TOS. + # Frame N's stack must have length >= 1 since it's about to RETURN_VALUE. + # Frame N actually should have stack length == 1, because debug CPython expects + # empty stacks after return, but there is no guarantee written down anywhere. + if not (current_num_stack >= 1): + raise AssertionError("expected current_num_stack >= 1 to be true") + cg.extend_output(create_swap(current_num_stack + 2)) + for _ in range(current_num_stack + 1): + cg.append_output(create_instruction("POP_TOP")) + cg.append_output(create_instruction("RETURN_VALUE")) + + return cg.get_instructions() + + # Let frame k be the deepest frame where the resume function is not RETURN_VALUE + # - If k == N, then the frame N stack is prepended to the frame N locals. + # - If k != N, then frame N's TOS is added to frame k's stack. + + # Rearrange the TOS to be compatible with create_resume and codegen_call_resume: + # [ + # frame N stack + locals, + # ..., + # frame 1 stack + locals + # ] + + # create the stack values that should be moved + if txes[0] is self: + # Frame N is non-returning, pack all of frame N's stack to + # be moved to frame N's frame values + cg.append_output(create_instruction("BUILD_LIST", arg=current_num_stack)) + # frame N stack is not yet on the frame N's frame values + stack_insert_idx = 0 + all_stack_locals_metadata[0].num_stack = current_num_stack + else: + # Frame N is returning. Let frame k be the deepest non-returning frame. + # Add frame N's TOS to frame k's stack. + # pop frame N stack except TOS + cg.extend_output(create_swap(current_num_stack)) + for _ in range(current_num_stack - 1): + cg.append_output(create_instruction("POP_TOP")) + cg.append_output(create_instruction("BUILD_LIST", arg=1)) + # frame k stack is already on frame k's frame values + stack_insert_idx = all_stack_locals_metadata[idxes[0]].num_stack + all_stack_locals_metadata[idxes[0]].num_stack += 1 + txes[0].push(UnknownVariable()) + + # move the predetermined stack value(s) to the deepest non-returning frame + cg.extend_output( + [ + *create_copy(2), + # frame_values, return_const, frame_values + cg.create_load_const(idxes[0]), + cg.create_binary_subscr(), + *create_binary_slice(stack_insert_idx, stack_insert_idx, True), + # frame_values[idxes[0]][stack_insert_idx:stack_insert_idx] = frame N stack/[return_const/TOS] + # frame_values left on top of stack + ] + ) + + # filter out frame values of skipped tx'es + filter_insts = [] + for idx in idxes: + filter_insts.extend( + [ + create_dup_top(), + cg.create_load_const(idx), + cg.create_binary_subscr(), + *create_swap(2), + ] + ) + # TOS: cells, frame_values[idxes[0]], ..., frame_values[idxes[...]], frame_values + filter_insts.extend( + [ + create_instruction("POP_TOP"), + create_instruction("BUILD_LIST", arg=len(idxes)), + ] + ) + # TOS: cells, filtered frame_values + + cg.extend_output(filter_insts) + # filter out cells of skipped tx'es using the same instructions in filter_insts, + # but with cells as TOS instead of frame values + cg.extend_output( + [ + *create_swap(2), + *copy.deepcopy(filter_insts), + *create_swap(2), + ] + ) + # TOS: filtered cells, filtered frame_values + + resume_codes: list[types.CodeType] = [] + resume_names = [] + for i, cur_tx in enumerate(txes): + resume_code, resume_name = cur_tx.create_resume( + i, + resume_insts[i], + all_stack_locals_metadata[idxes[i]], + resume_codes, + cg, + cur_tx is self, + True, + ) + resume_codes.append(resume_code) + resume_names.append(resume_name) + + self.codegen_call_resume(resume_codes, resume_names, cg) + cg.append_output(create_instruction("RETURN_VALUE")) + + return cg.get_instructions() + + @staticmethod + def codegen_call_resume( + resume_codes: list[types.CodeType], resume_names: list[str], cg: PyCodegen + ) -> None: + """ + Calls the provided resume functions. + + Expects the TOS to be in the state: + [frame N cells, ..., frame 1 cells], + [ + frame N stack + locals, + frame N-1 stack + locals, + ..., + frame 1 stack + locals + ] + + Pops the cells and frame values, leaving the result of calling the resume functions on TOS. + + Args: + - resume_codes: list of resume function code objects to call + - resume_names: list of the corresponding names of the resume functions + - cg: PyCodegen object to output instructions to + """ + # NOTE: We will load cells as we load resume functions + + # load resume functions except the root's + cg.extend_output(create_copy(2)) + for i, (name, code) in enumerate(zip(resume_names, resume_codes)): + if i == len(resume_names) - 1: + break + # stack: cells, frames, *(resume 1, ...), cells + if code.co_freevars: + cg.extend_output( + [ + create_dup_top(), + cg.create_load_const(i), + cg.create_binary_subscr(), + ] + ) + # Call the factory function (stored under resume_name) to + # create the resume function with correct globals and closure. + cg.extend_output( + [ + cg.create_load_global(name, add=True), + *create_swap(2), + *create_call_function(1, push_null=True), + ] + ) + else: + cg.extend_output(cg.load_function_name(name, False, 0)) + cg.extend_output(create_swap(2)) + cg.extend_output( + [ + create_instruction("POP_TOP"), + create_instruction("BUILD_LIST", arg=len(resume_codes) - 1), + ] + ) + + # stack: cells, frames, [resume 1, ..., resume N - 1] + # load root resume function + cg.extend_output(create_swap(3)) + if resume_codes[-1].co_freevars: + cg.extend_output( + [ + cg.create_load_const(-1), + cg.create_binary_subscr(), + ] + ) + # Call the factory function to create the resume function with + # correct globals and closure. + cg.extend_output( + [ + cg.create_load_global(resume_names[-1], add=True), + *create_swap(2), + *create_call_function(1, push_null=True), + ] + ) + cg.extend_output( + [ + *create_rot_n(3), + ] + ) + else: + cg.extend_output( + [ + create_instruction("POP_TOP"), + *cg.load_function_name(resume_names[-1], False), + *create_rot_n(3), + ] + ) + + # resume 1, [resume N, ..., resume 2], frames + + # load top level-frame; final stack state should be: + # first resume function (+ NULL), + # [ + # [resume N, ..., resume 2], + # [ + # frame N stack + locals, + # ..., + # frame 2 stack + locals, + # ], *(frame 1 stack + locals) + # ] + cg.extend_output( + [ + create_dup_top(), + create_dup_top(), + # frames, frames, frames + cg.create_load_const(-1), + cg.create_binary_subscr(), + # frames, frames, frames[-1] + *create_swap(2), + # frames, frames[-1], frames + cg.create_load_const(-1), + create_instruction("DELETE_SUBSCR"), + ] + ) + + # TOS: resume 1, remaining resumes, frames (popped), frame 1 stack + locals + cg.extend_output( + [ + *create_rot_n(3), + create_instruction("BUILD_LIST", arg=2), + *create_swap(2), + # [resumes, frames (popped)], frame 1 stack + locals + create_instruction("LIST_EXTEND", arg=1), + ] + ) + + # TOS: resume 1, [remaining resumes, frames, *(frame 1 stack + locals)] + cg.extend_output(create_call_function_ex(False, True)) + + def should_compile_partial_graph(self) -> bool: + if sys.version_info >= (3, 11): + # Do not compile if current instruction's block is not the top with block + entry = self.current_instruction.exn_tab_entry + if entry and ( + not self.block_stack or entry.target is not self.block_stack[-1].target + ): + return False + return ( + all(b.can_restore() for b in self.block_stack) + and not self.one_graph + # Only the leaf tracer's error_on_graph_break should be used + and (self.is_child_tracer_active or not self.error_on_graph_break) + and not self.is_tracing_resume_prologue + and not self.active_generic_context_managers + and not self.skip_one_hop_torch_function_depth + # Do not allow nested graph breaks in HOPs + and self.output.current_tracer.parent is None + ) + + @break_graph_if_unsupported( + push=False, + msg_prefix="Encountered graph break when attempting to trace STORE_SUBSCR: trying to store subscript, e.g. x[key] = y", + ) + def STORE_SUBSCR(self, inst: Instruction) -> None: + val, obj, key = self.popn(3) + generic_setitem(self, obj, key, val) + + def DELETE_SUBSCR(self, inst: Instruction) -> None: + obj, key = self.popn(2) + # Check for tensor items using side-effect-free internal lookups + # only. We avoid call_method("__getitem__") because it can execute + # user code and add unwanted graph nodes. + self._maybe_sync_dealloc_subscr(obj, key) + generic_delitem(self, obj, key) + + def _maybe_sync_dealloc_subscr( + self, obj: VariableTracker, key: VariableTracker + ) -> None: + from .variables.dicts import ConstDictVariable + from .variables.lists import BaseListVariable + + # TODO(dynamo-team): Refactor this to use sq_item / mp_ass_subscript + + item_var = None + try: + if isinstance(obj, BaseListVariable): + item_var = obj.getitem_const( + self, # pyrefly: ignore [bad-argument-type] + key, + ) + elif isinstance(obj, ConstDictVariable): + item_var = obj.maybe_getitem_const(key) + except Exception: + pass + if isinstance(item_var, TensorVariable): + self._maybe_emit_sync_dealloc(item_var) + + def BUILD_TUPLE(self, inst: Instruction) -> None: + items = self.popn(inst.argval) + self.push(TupleVariable(items)) + + def BUILD_SLICE(self, inst: Instruction) -> None: + items = self.popn(inst.argval) + self.push(SliceVariable(items, tx=self)) # type: ignore[arg-type] + + def _can_speculate_comprehension_nested(self) -> bool: + """Check if comprehension speculation is allowed in nested context. + + For the base class (non-inlined), this always returns False. + """ + return False + + def BUILD_LIST(self, inst: Instruction) -> None: + if maybe_setup_comprehension_speculation(self, inst): + return + + items = self.popn(inst.argval) + self.push(VariableTracker.build(self, items)) + + def BUILD_SET(self, inst: Instruction) -> None: + if config.inject_BUILD_SET_unimplemented_TESTING_ONLY: + unimplemented( + gb_type="missing BUILD_SET handler", + context="", + explanation="Missing BUILD_SET bytecode handler (for testing purposes).", + hints=[], + ) + items = self.popn(inst.argval) + new_set = SetVariable(items, mutation_type=ValueMutationNew()) + self.push(new_set) + + def BUILD_LIST_UNPACK(self, inst: Instruction, cls: type = ListVariable) -> None: + seqs = self.popn(inst.argval) + items = [] + for seq in seqs: + try: + items.extend(unpack_iterable(self, seq)) + except NotImplementedError: + unimplemented( + gb_type="Failed to unpack object for BUILD_LIST_UNPACK", + context=str(seq), + explanation=f"{seq} cannot be unpacked into a list for the BUILD_LIST_UNPACK " + "bytecode (`[*x, *y, ...]`).", + hints=[*graph_break_hints.USER_ERROR], + ) + self.push(cls(items, mutation_type=ValueMutationNew())) + + def BUILD_TUPLE_UNPACK(self, inst: Instruction) -> None: + self.BUILD_LIST_UNPACK(inst, cls=TupleVariable) + + BUILD_TUPLE_UNPACK_WITH_CALL = BUILD_TUPLE_UNPACK + + def BUILD_MAP(self, inst: Instruction) -> None: + if maybe_setup_comprehension_speculation(self, inst): + return + + items = self.popn(inst.argval * 2) + d = dict(zip(items[::2], items[1::2])) + self.push(VariableTracker.build(self, d)) + + def BUILD_MAP_UNPACK(self, inst: Instruction) -> None: + items = self.popn(inst.argval) + # ensure everything is a dict + items = [ + VariableTracker.build(self, dict).call_function(self, [x], {}) + for x in items + ] # type: ignore[arg-type] + result: dict[Any, Any] = {} + for x in items: + if not isinstance(x, ConstDictVariable): + raise AssertionError( + "expected isinstance(x, ConstDictVariable) to be true" + ) + result.update(x.items) + self.push( + VariableTracker.build( + self, + result, + ) + ) + + BUILD_MAP_UNPACK_WITH_CALL = BUILD_MAP_UNPACK + + def BUILD_CONST_KEY_MAP(self, inst: Instruction) -> None: + keys = self.pop() + values = self.popn(inst.argval) + if not isinstance(keys, TupleVariable): + raise AssertionError("expected isinstance(keys, TupleVariable) to be true") + if not keys.is_python_constant(): + raise AssertionError("expected keys.is_python_constant() to be true") + + keys = unpack_iterable(self, keys) + if len(keys) != len(values): + raise AssertionError("expected len(keys) == len(values) to be true") + + self.push( + VariableTracker.build( + self, + dict(zip(keys, values)), + ) + ) + + def MAP_ADD(self, inst: Instruction) -> None: + k, v = self.popn(2) + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg].realize() + if not isinstance(obj, ConstDictVariable): + raise AssertionError( + "expected isinstance(obj, ConstDictVariable) to be true" + ) + generic_setitem(self, obj, k, v) + + def SET_ADD(self, inst: Instruction) -> None: + v = self.pop() + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg] + if not isinstance(obj, SetVariable): + raise AssertionError("expected isinstance(obj, SetVariable) to be true") + if not obj.is_mutable(): + raise AssertionError("expected obj.is_mutable() to be true") + obj.call_method(self, "add", [v], {}) # type: ignore[arg-type] + + def SET_UPDATE(self, inst: Instruction) -> None: + v = self.pop() + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg] + if not isinstance(obj, SetVariable): + raise AssertionError("expected isinstance(obj, SetVariable) to be true") + if not obj.is_mutable(): + raise AssertionError("expected obj.is_mutable() to be true") + obj.call_method(self, "update", [v], {}) # type: ignore[arg-type] + + def LIST_APPEND(self, inst: Instruction) -> None: + v = self.pop() + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg].realize() + if not isinstance(obj, ListVariable): + raise AssertionError("expected isinstance(obj, ListVariable) to be true") + if not obj.is_mutable(): + raise AssertionError("expected obj.is_mutable() to be true") + self.output.side_effects.mutation(obj) + obj.items.append(v) + + def MAKE_FUNCTION(self, inst: Instruction) -> None: + flags = inst.arg + if sys.version_info < (3, 11): + fn_name = self.pop() + code = self.pop() + if sys.version_info >= (3, 11): + # MAKE_FUNCTION behavior actually changed in 3.11, see + # https://github.com/python/cpython/pull/93189/ + if not hasattr(code.value, "co_qualname"): # type: ignore[attr-defined] + raise AssertionError( + 'expected hasattr(code.value, "co_qualname") to be true' + ) + fn_name = VariableTracker.build(self, code.value.co_qualname) # type: ignore[attr-defined] + defaults = None + closure = None + annotations = None + kwdefaults = None + + if sys.version_info < (3, 13): + # in 3.13, this is handled in SET_FUNCTION_ATTRIBUTE + if flags is not None: + if flags & 0x08: + closure = self.pop() + if flags & 0x04: + annotations = self.pop() + if flags & 0x02: + kwdefaults = self.pop() + if flags & 0x01: + defaults = self.pop() + + fn = NestedUserFunctionVariable( + fn_name, + code, + self.f_globals, + defaults, + kwdefaults, + closure, + ) + if annotations: + if not isinstance(annotations, TupleVariable): + raise AssertionError( + "expected isinstance(annotations, TupleVariable) to be true" + ) + # Convert the attribute to a dictionary before assigning it + # https://github.com/python/cpython/blob/28fb13cb33d569720938258db68956b5f9c9eb40/Objects/funcobject.c#L574-L594 + items = annotations.items + ann = ConstDictVariable( + dict(zip(items[::2], items[1::2], strict=True)), + mutation_type=ValueMutationNew(), + ) + fn.annotations = ann + self.push(fn) + + def UNPACK_SEQUENCE(self, inst: Instruction) -> None: + seq = self.pop() + val = unpack_iterable(self, seq) + if len(val) < inst.argval: + raise_value_error( + self, + f"not enough values to unpack (expected {inst.argval}, got {len(val)})", + ) + if len(val) > inst.argval: + raise_value_error( + self, + f"too many values to unpack (expected {inst.argval})", + ) + for i in reversed(val): + self.push(i) + + def UNPACK_EX(self, inst: Instruction) -> None: + if not (0 <= inst.argval <= 0xFFFF): + raise AssertionError("expected 0 <= inst.argval <= 0xFFFF to be true") + prefix = inst.argval & 0xFF # low byte + suffix = inst.argval >> 8 # high byte + seq = self.pop() + if iterator := generic_getiter(self, seq): # type: ignore[bad-argument-type] + vals = unpack_iterable(self, iterator) + if len(vals) < prefix + suffix: + raise_value_error( + self, + f"not enough values to unpack (expected at least {prefix + suffix}, got {len(vals)})", + ) + vals_prefix = vals[:prefix] + vals_list = vals[prefix : len(vals) - suffix] + vals_suffix = vals[len(vals) - suffix :] + for item in reversed(vals_suffix): + self.push(item) + self.push(ListVariable(vals_list, mutation_type=ValueMutationNew())) + for item in reversed(vals_prefix): + self.push(item) + else: + unimplemented( + gb_type="Failed to unpack object for UNPACK_EX", + context=str(seq), + explanation=f"{seq} cannot be unpacked into a list for the UNPACK_EX bytecode.", + hints=[*graph_break_hints.USER_ERROR], + ) + + @break_graph_if_unsupported( + push=False, msg_prefix="Encountered intentional debugging graph break" + ) + def graph_break_on_leaf_function(self, inst: Instruction) -> None: + if self.has_no_inlined_calls: + unimplemented( + gb_type="Forced graph break on leaf function", + context="", + explanation="Forced graph break on non-inlining function for " + "nested graph break testing purposes", + hints=[ + "Set torch._dynamo.config.debug_force_graph_break_on_leaf_return = False", + ], + ) + + def NOP(self, inst: Instruction) -> None: + # Dynamo-specific testing behavior + if inst.argval == "GRAPH_BREAK_IF_LEAF": + self.graph_break_on_leaf_function(inst) + + def POP_TOP(self, inst: Instruction) -> None: + self.pop() + + def ROT_TWO(self, inst: Instruction) -> None: + a = self.pop() + b = self.pop() + self.push(a) + self.push(b) + + def ROT_THREE(self, inst: Instruction) -> None: + a = self.pop() + b = self.pop() + c = self.pop() + self.push(a) + self.push(c) + self.push(b) + + def ROT_FOUR(self, inst: Instruction) -> None: + a = self.pop() + b = self.pop() + c = self.pop() + d = self.pop() + self.push(a) + self.push(d) + self.push(c) + self.push(b) + + def DUP_TOP(self, inst: Instruction) -> None: + a = self.pop() + self.push(a) + self.push(a) + + def DUP_TOP_TWO(self, inst: Instruction) -> None: + a = self.pop() + b = self.pop() + self.push(b) + self.push(a) + self.push(b) + self.push(a) + + def _convert_value(self, value: VariableTracker, flag: int) -> VariableTracker: + if flag == 1: + return VariableTracker.build(self, str).call_function(self, [value], {}) # type: ignore[arg-type] + elif flag == 2: + return VariableTracker.build(self, repr).call_function(self, [value], {}) # type: ignore[arg-type] + elif flag == 3: + return VariableTracker.build(self, ascii).call_function(self, [value], {}) # type: ignore[arg-type] + return value + + def _format_value(self, fmt_spec: VariableTracker, flags: int) -> None: + value = self.pop() + if isinstance(value, SymNodeVariable): + from torch._dynamo.variables.lazy import ( + LazySymNodeFormatString, + LazyVariableTracker, + ) + + value = LazyVariableTracker.create( + LazySymNodeFormatString(value, fmt_spec), source=None + ) + self.push(value) + return + + value = self._convert_value(value, flags & 0x03) + + # For plain f"{obj}" (no conversion, empty format spec, default + # __format__), eagerly evaluate str() via generic_str to capture + # the current symbolic state. This avoids deferring to + # StringFormatVariable whose reconstruct runs before mutations + # are replayed in the epilogue. + # Skip when __format__ is overridden since format(obj, "") may + # differ from str(obj) in that case. + if ( + (flags & 0x03) == 0 + and fmt_spec.is_python_constant() + and fmt_spec.as_python_constant() == "" + ): + realized = value.realize() + try: + py_type = realized.python_type() + except NotImplementedError: + py_type = None + if py_type is not None and py_type.__format__ is object.__format__: + try: + from .variables.object_protocol import generic_str + + str_result = generic_str(self, realized) + self.push(str_result) + return + except Unsupported: + if self.output.should_exit: + raise + + fmt_var = VariableTracker.build( + self, "{:" + fmt_spec.as_python_constant() + "}" + ) + + self.call_function(BuiltinVariable(str.format), [fmt_var, value], {}) + + def FORMAT_VALUE(self, inst: Instruction) -> None: + flags = inst.arg + if flags is None: + raise AssertionError("expected flags is not None to be true") + if (flags & 0x04) == 0x04: + fmt_spec = self.pop() + else: + fmt_spec = VariableTracker.build(self, "") + return self._format_value(fmt_spec, flags) + + def BUILD_STRING(self, inst: Instruction) -> None: + format_string_parts: list[str] = [] + args: list[VariableTracker] = [] + kwargs: dict[str, VariableTracker] = {} + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + for part in self.popn(inst.arg): + if part.is_python_constant(): + format_string_parts.append("{}") + args.append(part) + elif isinstance(part, variables.StringFormatVariable): + format_string_parts.append(part.format_string) + args.extend(part.sym_args) + if set(kwargs.keys()) & set(part.sym_kwargs.keys()): + unimplemented( + gb_type="BUILD_STRING key conflict", + context=f"format_string_parts: {format_string_parts}, kwargs: {kwargs}, part.sym_kwargs: {part.sym_kwargs}", + explanation="Failed to build format string due to key conflict", + hints=[*graph_break_hints.USER_ERROR], + ) + kwargs.update(part.sym_kwargs) + else: + unimplemented( + gb_type="BUILD_STRING type error", + context=str(part), + explanation="Format string part type is not correct - expected constant or format string.", + hints=[*graph_break_hints.USER_ERROR], + ) + self.push( + variables.StringFormatVariable.create( + "".join(format_string_parts), args, kwargs + ) + ) + + def IS_OP(self, inst: Instruction) -> None: + if not (inst.argval == 0 or inst.argval == 1): + raise AssertionError( + "expected inst.argval == 0 or inst.argval == 1 to be true" + ) + argval = "is" if inst.argval == 0 else "is not" + self.push(compare_op_handlers[argval](self, self.popn(2), {})) + + def CONTAINS_OP(self, inst: Instruction) -> None: + if not (inst.argval == 0 or inst.argval == 1): + raise AssertionError( + "expected inst.argval == 0 or inst.argval == 1 to be true" + ) + left, right = self.popn(2) + op = inst.argval + self.push(pysequence_contains(self, right, left)) # type: ignore[bad-argument-type] + if op == 1: + self.UNARY_NOT(inst) + + def LIST_EXTEND(self, inst: Instruction) -> None: + v = self.pop() + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg] + if not isinstance(obj, ListVariable): + raise AssertionError("expected isinstance(obj, ListVariable) to be true") + if not obj.is_mutable(): + raise AssertionError("expected obj.is_mutable() to be true") + obj.call_method(self, "extend", [v], {}) # type: ignore[arg-type] + + def LIST_TO_TUPLE(self, inst: Instruction) -> None: + self.push( + VariableTracker.build(self, tuple).call_function(self, [self.pop()], {}) + ) # type: ignore[arg-type] + + def STOPITERATION_ERROR(self, inst: Instruction) -> None: + # wrap the generator body in a try: ... except StopIteration: ... which + # converts the StopIteration into a RuntimeError + # https://peps.python.org/pep-0479/ + # https://github.com/python/cpython/pull/99006 + # https://github.com/python/cpython/commit/28187141cc34063ef857976ddbca87ba09a882c2 + val = self.stack[-1] + if not pyexception_instance_check(val): + raise AssertionError( + f"expected _exception_instance_check(val) to be true, got {val}" + ) + if val.exc_type is StopIteration: # type: ignore[union-attr] + new_val = VariableTracker.build(self, RuntimeError).call_function( + self, # type: ignore[arg-type] + [VariableTracker.build(self, "generator raised StopIteration")], + {}, + ) + new_val.call_method( + self, + "__setattr__", + [VariableTracker.build(self, "__context__"), val], + {}, + ) + new_val.call_method( + self, "__setattr__", [VariableTracker.build(self, "__cause__"), val], {} + ) + self.stack[-1] = new_val + + def DICT_MERGE(self, inst: Instruction) -> None: + v = self.pop() + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg].realize() + if not isinstance(obj, ConstDictVariable): + raise AssertionError( + "expected isinstance(obj, ConstDictVariable) to be true" + ) + if not obj.is_mutable(): + raise AssertionError("expected obj.is_mutable() to be true") + obj.call_method(self, "update", [v], {}) # type: ignore[arg-type] + + DICT_UPDATE = DICT_MERGE + + def GEN_START(self, inst: Instruction) -> None: + self.pop() + + def GET_LEN(self, inst: Instruction) -> None: + tos = self.stack[-1] + if tos.is_python_constant(): + self.push(VariableTracker.build(self, len(tos.as_python_constant()))) + else: + self.push(tos.call_method(self, "__len__", [], {})) + + def MATCH_MAPPING(self, inst: Instruction) -> None: + """ + If STACK[-1] is an instance of collections.abc.Mapping, push True. + Otherwise, push False + """ + tos = self.stack[-1] + self.push( + self.inline_user_function_return( + VariableTracker.build(self, impl_IS_MAPPING), + [tos], + {}, + ) + ) + + def MATCH_SEQUENCE(self, inst: Instruction) -> None: + tos = self.stack[-1] + self.push( + self.inline_user_function_return( + VariableTracker.build(self, impl_MATCH_SEQUENCE), + [tos], + {}, + ) + ) + + def MATCH_CLASS(self, inst: Instruction) -> None: + subject, cls, names = self.popn(3) + arg = VariableTracker.build(self, inst.arg) + self.push( + self.inline_user_function_return( + VariableTracker.build(self, impl_MATCH_CLASS), + [subject, cls, arg, names], + {}, + ) + ) + + if sys.version_info < (3, 11): + # for versions < 3.11, also push the boolean result + tos = self.stack[-1] + self.push(VariableTracker.build(self, not istype(tos, ConstantVariable))) + + def MATCH_KEYS(self, inst: Instruction) -> None: + keys = self.stack[-1] + obj = self.stack[-2] + + if not isinstance(keys, TupleVariable): + raise AssertionError("expected isinstance(keys, TupleVariable) to be true") + + self.push( + self.inline_user_function_return( + VariableTracker.build(self, impl_MATCH_KEYS), [obj, keys], {} + ) + ) + + if sys.version_info < (3, 11): + # for versions < 3.11, also push the boolean result + tos = self.stack[-1] + self.push(VariableTracker.build(self, not istype(tos, ConstantVariable))) + + def LOAD_ASSERTION_ERROR(self, inst: Instruction) -> None: + self.push(self.load_builtin_from_argval("AssertionError")) + + def LOAD_BUILD_CLASS(self, inst: Instruction) -> None: + self.push(self.load_builtin_from_argval("__build_class__")) + + UNARY_POSITIVE = stack_op(operator.pos) + UNARY_NEGATIVE = stack_op(operator.neg) + UNARY_NOT = stack_op(operator.not_) + UNARY_INVERT = stack_op(operator.invert) + + BINARY_POWER = stack_op(operator.pow) + BINARY_MULTIPLY = stack_op(operator.mul) + BINARY_MATRIX_MULTIPLY = stack_op(operator.matmul) + BINARY_FLOOR_DIVIDE = stack_op(operator.floordiv) + BINARY_TRUE_DIVIDE = stack_op(operator.truediv) + BINARY_MODULO = stack_op(operator.mod) + BINARY_REMAINDER = stack_op(operator.mod) + BINARY_ADD = stack_op(operator.add) + BINARY_SUBTRACT = stack_op(operator.sub) + + BINARY_SUBSCR = break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace BINARY_SUBSCR: a binary subscript, e.g. x[attr]", + )(stack_op(operator.getitem)) + BINARY_LSHIFT = stack_op(operator.lshift) + BINARY_RSHIFT = stack_op(operator.rshift) + BINARY_AND = stack_op(operator.and_) + BINARY_OR = stack_op(operator.or_) + BINARY_XOR = stack_op(operator.xor) + + INPLACE_POWER = stack_op(operator.ipow) + INPLACE_MULTIPLY = stack_op(operator.imul) + INPLACE_MATRIX_MULTIPLY = stack_op(operator.imatmul) + INPLACE_FLOOR_DIVIDE = stack_op(operator.ifloordiv) + INPLACE_TRUE_DIVIDE = stack_op(operator.itruediv) + INPLACE_MODULO = stack_op(operator.imod) + INPLACE_REMAINDER = stack_op(operator.imod) + INPLACE_ADD = stack_op(operator.iadd) + INPLACE_SUBTRACT = stack_op(operator.isub) + INPLACE_LSHIFT = stack_op(operator.ilshift) + INPLACE_RSHIFT = stack_op(operator.irshift) + INPLACE_AND = stack_op(operator.iand) + INPLACE_XOR = stack_op(operator.ixor) + INPLACE_OR = stack_op(operator.ior) + + # 3.11 opcodes + def RESUME(self, inst: Instruction) -> None: + if inst.arg == 0: + self.append_prefix_inst(inst) + self.accept_prefix_inst = False + elif sys.version_info >= (3, 15) and inst.arg == 4: + # https://github.com/python/cpython/blob/f31a89bb901067dd105b00cfa90523cf7ffdbbdd/Include/internal/pycore_opcode_utils.h#L90 + self.append_prefix_inst(inst) + else: + if self.accept_prefix_inst: + raise AssertionError("expected not self.accept_prefix_inst to be true") + + if sys.version_info >= (3, 11): + + def BINARY_OP(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + return _binary_op_lookup[inst.arg](self, inst) + + def PRECALL(self, inst: Instruction) -> None: + pass + + def KW_NAMES(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + kw_names = self.code_options["co_consts"][inst.arg] + if not isinstance(kw_names, tuple): + raise AssertionError("expected isinstance(kw_names, tuple) to be true") + for name in kw_names: + if not isinstance(name, str): + raise AssertionError("expected isinstance(name, str) to be true") + if self.kw_names is not None: + raise AssertionError("expected self.kw_names is None to be true") + self.kw_names = ConstantVariable.create(value=kw_names) # type: ignore[assignment] + + def PUSH_NULL(self, inst: Instruction) -> None: + self.push(NullVariable()) + + def _call(self, inst: Instruction, call_kw: bool = False) -> None: + # see https://docs.python.org/3.11/library/dis.html#opcode-CALL + # for convention + if call_kw: + # TOS is kw_names for CALL_KW instruction + if not (sys.version_info >= (3, 13)): + raise AssertionError("expected sys.version_info >= (3, 13) to be true") + kw_names = self.pop() + if not isinstance(kw_names, TupleVariable): + raise AssertionError( + "expected isinstance(kw_names, TupleVariable) to be true" + ) + if not kw_names.is_python_constant(): + raise AssertionError( + "expected kw_names.is_python_constant() to be true" + ) + kw_names = kw_names.as_python_constant() + else: + kw_names = self.kw_names.value if self.kw_names else () + + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + contents = self.popn(inst.arg + 2) + if sys.version_info >= (3, 13): + # NULL and callable swapped + fn = contents[0] + args = [] if isinstance(contents[1], NullVariable) else [contents[1]] + else: + if isinstance(contents[0], NullVariable): + fn = contents[1] + # pyrefly: ignore [implicit-any] + args = [] + else: + fn = contents[0] + args = [contents[1]] + + if kw_names: + args = args + contents[2 : -len(kw_names)] + + kwargs_list = contents[-len(kw_names) :] + + kwargs = dict(zip(kw_names, kwargs_list)) + + if len(kwargs) != len(kw_names): + raise AssertionError("expected len(kwargs) == len(kw_names) to be true") + else: + args = args + contents[2:] + # pyrefly: ignore [implicit-any] + kwargs = {} + + try: + # if call_function fails, need to set kw_names to None, otherwise + # a subsequent call may have self.kw_names set to an old value + self.call_function(fn, args, kwargs) + finally: + self.kw_names = None + + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace CALL: a function call, e.g. f(x, y)", + ) + def CALL(self, inst: Instruction) -> None: + self._call(inst) + + def COPY(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + self.push(self.stack[-inst.arg]) + + def SWAP(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + self.stack[-1], self.stack[-inst.arg] = self.stack[-inst.arg], self.stack[-1] + + JUMP_BACKWARD = jump + JUMP_BACKWARD_NO_INTERRUPT = jump + + POP_JUMP_FORWARD_IF_TRUE = generic_jump(operator.truth, False) + POP_JUMP_BACKWARD_IF_TRUE = generic_jump(operator.truth, False) + POP_JUMP_FORWARD_IF_FALSE = generic_jump(operator.not_, False) + POP_JUMP_BACKWARD_IF_FALSE = generic_jump(operator.not_, False) + + def CACHE(self, inst: Instruction) -> None: + pass + + def BEFORE_WITH(self, inst: Instruction) -> None: + self.setup_or_before_with(inst) + + def enter_ctx( + self, + ctx: ContextWrappingVariable | GenericContextWrappingVariable, + inst: Instruction, + ) -> VariableTracker: + if ( + isinstance(ctx, GenericContextWrappingVariable) + and not ctx.supports_graph_breaks() + ): + self.active_generic_context_managers.append(ctx) + + if sys.version_info >= (3, 11): + # See update_block_stack/create_resume for block stack details. + # Only push a block if the current instruction's block is a + # with block that is not nested in a try block - that is, the current + # instruction's block target is the same as the top block's target. + if inst.exn_tab_entry and ( + not self.block_stack + or inst.exn_tab_entry.target is not self.block_stack[-1].target + ): + target = None + else: + if self.next_instruction.exn_tab_entry is None: + raise AssertionError( + "expected self.next_instruction.exn_tab_entry is not None to be true" + ) + target = self.next_instruction.exn_tab_entry.target + else: + target = inst.target + + if target: + if isinstance(self, InstructionTranslator) or config.nested_graph_breaks: + self.block_stack.append( + BlockStackEntry(inst, target, len(self.stack), ctx) + ) + else: + self.block_stack.append(BlockStackEntry(inst, target, len(self.stack))) + + return ctx.enter(self) # type: ignore[arg-type] + + @staticmethod + def unsupported_ctx_graph_break(ctx: VariableTracker) -> NoReturn: + unimplemented( + gb_type="Unsupported context manager", + context=f"Attempted SETUP_WITH/BEFORE_WITH/LOAD_SPECIAL on {ctx}", + explanation=f"Dynamo does not know how to enter a `{ctx.python_type_name()}` context manager.", + hints=[ + "Avoid using the unsupported context manager.", + "If the context manager seems like it should be supported (e.g. torch.set_grad_enabled), then " + "it may be the case that it was created outside the compiled region, which Dynamo does not support. " + "Supported context managers can cross graph break boundaries only if they are local non-closure " + "variables, or are intermediate values.", + "File an issue to PyTorch. Simple context managers can potentially be supported, " + "but note that context managers can't be supported in general", + ], + ) + + def setup_or_before_with(self, inst: Instruction) -> None: + ctx = self.pop() + if not isinstance( + ctx, (ContextWrappingVariable, GenericContextWrappingVariable) + ): + self.unsupported_ctx_graph_break(ctx) + + # Need this redundant check for mypy + if not isinstance( + ctx, (ContextWrappingVariable, GenericContextWrappingVariable) + ): + raise AssertionError( + "expected isinstance( ctx, (ContextWrappingVariable, GenericContextWrappingVariable) ) to be true" + ) + + self.push(WithExitFunctionVariable(ctx, inst.target)) + self.push(self.enter_ctx(ctx, inst)) + + def append_prefix_inst(self, inst: Instruction) -> None: + if not self.accept_prefix_inst: + raise AssertionError("expected self.accept_prefix_inst to be true") + self.prefix_insts.append(inst) + + def MAKE_CELL(self, inst: Instruction) -> None: + if sys.version_info >= (3, 12) and not self.accept_prefix_inst: + # In 3.12+, MAKE_CELL is no longer necessarily a prefix instruction. + # It can be generated by inlined comprehensions. + # A mid-function MAKE_CELL replaces the slot's contents with a + # fresh cell (the frame-entry cell was saved on the stack by a + # preceding LOAD_FAST_AND_CLEAR and is restored by the + # comprehension epilogue). Only the slot is updated: the + # symbolic_cellvars registry keeps the frame-entry cell, and + # `_cellvar` prefers the slot while it holds a cell. + if inst.argval in self.f_code.co_freevars: + # The name refers to three localsplus slots at once (fast + # local + comprehension cell + free var, e.g. `nonlocal i` + # with `[lambda: i for i in ...]`). Dynamo tracks locals by + # name and cannot model two same-named cells; tracing on + # would silently target the wrong cell. + unimplemented( + gb_type="MAKE_CELL on a free variable name", + context=f"MAKE_CELL {inst.argval}", + explanation="An inlined comprehension creates a cell whose name " + f"`{inst.argval}` is also a free variable of the enclosing function.", + hints=[*graph_break_hints.DIFFICULT], + ) + if not isinstance(self.symbolic_locals[inst.argval], NullVariable): + raise AssertionError( + "expected isinstance(self.symbolic_locals[inst.argval], NullVariable) to be true" + ) + self.symbolic_locals[inst.argval] = ( + self.output.side_effects.track_cell_new() + ) + else: + self.append_prefix_inst(inst) + + def COPY_FREE_VARS(self, inst: Instruction) -> None: + self.append_prefix_inst(inst) + + def RETURN_GENERATOR(self, inst: Instruction) -> None: + self.append_prefix_inst(inst) + + # 3.12 opcodes + # BINARY/STORE_SLICE opcodes are broken down into + # BUILD_SLICE 2 and BINARY/STORE_SUBSCR + + def END_FOR(self, inst: Instruction) -> None: + if sys.version_info >= (3, 13): + self.pop() + else: + self.popn(2) + + # Decrement comprehension depth if exiting a comprehension layer + if sys.version_info >= (3, 12): + current_ip = self.indexof[inst] + if current_ip in self._comprehension_end_for_ips: + self._comprehension_end_for_ips.discard(current_ip) + self._comprehension_depth -= 1 + + def LOAD_FAST_CHECK(self, inst: Instruction) -> None: + if istype(self.symbolic_locals.get(inst.argval, None), NullVariable): + unimplemented( + gb_type="LOAD_FAST_CHECK on uninitialized variable", + context=inst.argval, + explanation=f"Attempted to load uninitialized local variable {inst.argval}", + hints=[*graph_break_hints.USER_ERROR], + ) + self.LOAD_FAST(inst) + + def LOAD_FAST_AND_CLEAR(self, inst: Instruction) -> None: + if inst.argval not in self.symbolic_locals: + self.push(NullVariable()) + else: + self.LOAD_FAST(inst) + self.symbolic_locals[inst.argval] = NullVariable() + + def LOAD_SUPER_ATTR(self, inst: Instruction) -> None: + self.CALL_FUNCTION(dataclasses.replace(inst, argval=2)) + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + if inst.arg & 1: + self.LOAD_METHOD(inst) + else: + self._load_attr(inst.argval) + + def CALL_INTRINSIC_1(self, inst: Instruction) -> None: + if inst.argval == 3: + # INTRINSIC_STOPITERATION_ERROR + self.STOPITERATION_ERROR(inst) + elif inst.argval == 5: + # INTRINSIC_UNARY_POSITIVE + self.UNARY_POSITIVE(inst) + elif inst.argval == 6: + # INTRINSIC_LIST_TO_TUPLE + items = unpack_iterable(self, self.pop()) + self.push(TupleVariable(items)) + elif inst.argval == 7: + # INTRINSIC_TYPEVAR + v = self.pop().as_python_constant() + tv = variables.TypingVariable(TypeVar(v)) + self.push(tv) + else: + unimplemented( + gb_type="Missing CALL_INTRINSIC_1 handler", + context=f"CALL_INTRINSIC_1 operand: {inst.argval}", + explanation=f"No handler implemented for CALL_INTRINSIC_1 {inst.argval} instruction.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def CALL_INTRINSIC_2(self, inst: Instruction) -> None: + arg2 = self.pop() + arg1 = self.pop() + if inst.argval == 4: + # INTRINSIC_SET_FUNCTION_TYPE_PARAMS + # same as => arg1.__type_params__ = arg2 + if not isinstance(arg1, BaseUserFunctionVariable): + raise AssertionError( + "expected isinstance(arg1, BaseUserFunctionVariable) to be true" + ) + arg1.call_method( + self, # pyrefly: ignore[bad-argument-type] + "__setattr__", + [ConstantVariable.create("__type_params__"), arg2], + {}, + ) + self.push(arg1) + else: + unimplemented( + gb_type="Missing CALL_INTRINSIC_2 handler", + context=f"CALL_INTRINSIC_2 operand: {inst.argval}", + explanation=f"No handler implemented for CALL_INTRINSIC_2 {inst.argval} instruction.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def END_SEND(self, inst: Instruction) -> None: + tos = self.pop() + self.pop() + if sys.version_info >= (3, 15): + self.pop() + self.push(tos) + + # 3.13 opcodes + # fused instructions LOAD_FAST_LOAD_FAST, STORE_FAST_STORE_FAST, STORE_FAST_LOAD_FAST + # are broken down. + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace CALL_KW: " + "a function call with keyword arguments, e.g. f(x=True)", + ) + def CALL_KW(self, inst: Instruction) -> None: + self._call(inst, call_kw=True) + + def TO_BOOL(self, inst: Instruction) -> None: + # TO_BOOL only precedes a conditional jump or UNARY_NOT (see compile.c in CPython) + # So we can skip this instruction as long as we remember to codegen a TO_BOOL + # before conditional jumps/UNARY_NOT. + if self.next_instruction.opname not in ( + "POP_JUMP_IF_TRUE", + "POP_JUMP_IF_FALSE", + "UNARY_NOT", + ): + raise AssertionError( + 'expected self.next_instruction.opname in ( "POP_JUMP_IF_TRUE", "POP_JUMP_IF_FALSE", "UNARY_NOT", ) to be true' + ) + + def SET_FUNCTION_ATTRIBUTE(self, inst: Instruction) -> None: + flags = inst.arg + if flags is None: + raise AssertionError("expected flags is not None to be true") + fn = self.pop() + if not isinstance(fn, NestedUserFunctionVariable): + raise AssertionError( + "expected isinstance(fn, NestedUserFunctionVariable) to be true" + ) + attr = self.pop() + + if flags & 0x10: + if not (sys.version_info >= (3, 14)): + raise AssertionError("expected sys.version_info >= (3, 14) to be true") + + # maybe use Format.VALUE_WITH_FAKE_GLOBALS instead? + # https://docs.python.org/3/library/annotationlib.html#annotationlib.Format.VALUE_WITH_FAKE_GLOBALS + attr = attr.call_function(self, [VariableTracker.build(self, 1)], {}) + fn.annotations = attr + elif flags & 0x08: + fn.closure = attr + elif flags & 0x04: + if not isinstance(attr, TupleVariable): + raise AssertionError( + "expected isinstance(attr, TupleVariable) to be true" + ) + # Convert the attribute to a dictionary before assigning it + # https://github.com/python/cpython/blob/28fb13cb33d569720938258db68956b5f9c9eb40/Objects/funcobject.c#L574-L594 + items = attr.items + ann = ConstDictVariable( + dict(zip(items[::2], items[1::2], strict=True)), + mutation_type=ValueMutationNew(), + ) + fn.annotations = ann + elif flags & 0x02: + fn.kwdefaults = attr + elif flags & 0x01: + fn.defaults = attr + + self.push(fn) + + def CONVERT_VALUE(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + self.push(self._convert_value(self.pop(), inst.arg)) + + def FORMAT_SIMPLE(self, inst: Instruction) -> None: + self._format_value(VariableTracker.build(self, ""), 0) + + def FORMAT_WITH_SPEC(self, inst: Instruction) -> None: + self._format_value(self.pop(), 0) + + # 3.14 opcodes + LOAD_FAST_BORROW = LOAD_FAST + NOT_TAKEN = NOP + + def POP_ITER(self, inst: Instruction) -> None: + self.pop() + if sys.version_info >= (3, 15): + self.pop() + + # See + # https://github.com/python/cpython/blob/805e3368d6d07e58430654d1365283924fdf4143/Python/ceval.c#L559 + # for the LOAD_SPECIAL table - make sure it matches for Python 3.14+ + _load_special_names = ( + "__enter__", + "__exit__", + "__aenter__", + "__aexit__", + ) + + def LOAD_SPECIAL(self, inst: Instruction) -> None: + if not isinstance(inst.arg, int): + raise AssertionError("expected LOAD_SPECIAL arg to be set to int") + attr = self._load_special_names[inst.arg] + if attr in ("__enter__", "__exit__"): + ctx = self.pop() + if not isinstance( + ctx, (ContextWrappingVariable, GenericContextWrappingVariable) + ): + self.unsupported_ctx_graph_break(ctx) + + # Need this redundant check for mypy + if not isinstance( + ctx, (ContextWrappingVariable, GenericContextWrappingVariable) + ): + raise AssertionError( + "expected isinstance( ctx, (ContextWrappingVariable, GenericContextWrappingVariable) ) to be true" + ) + if attr == "__enter__": + self.push(WithEnterFunctionVariable(ctx)) + self.PUSH_NULL(inst) + else: + # WithExitFunctionVariable doesn't really do anything with target for 3.11+ + self.push(WithExitFunctionVariable(ctx, None)) + self.PUSH_NULL(inst) + else: + # Implementation is similar to LOAD_METHOD for 3.13+ + self._load_attr(attr) + obj = self.pop() + self.push(obj) + self.PUSH_NULL(inst) + + def LOAD_SMALL_INT(self, inst: Instruction) -> None: + self.push(VariableTracker.build(self, inst.argval)) + + # See + # https://github.com/python/cpython/blob/f31a89bb901067dd105b00cfa90523cf7ffdbbdd/Python/pylifecycle.c#L881 + # for the common constants - make sure it matches for Python 3.14+. + _common_constants = ( + AssertionError, + NotImplementedError, + tuple, + all, + any, + list, + set, + None, + "", + True, + False, + -1, + ) + + def LOAD_COMMON_CONSTANT(self, inst: Instruction) -> None: + if not isinstance(inst.arg, int): + raise AssertionError("expected LOAD_COMMON_CONSTANT arg to be set to int") + self.push(VariableTracker.build(self, self._common_constants[inst.arg])) + + def is_non_empty_graph(self) -> bool: + if self.output.count_calls() > 1: + # perf optimization only + self.is_non_empty_graph = lambda: True # type: ignore[method-assign] + return True + return False + + def format_frame_summary( + self, additional_stack_frames: list[Any] | None = None + ) -> str: + if additional_stack_frames is None: + additional_stack_frames = [] + return "".join( + traceback.format_list( + [self.frame_summary()] + list(reversed(additional_stack_frames)) + ) + ) + + def frame_summary(self) -> traceback.FrameSummary: + positions = self.current_instruction.positions + # colno/end_colno kwargs were added to FrameSummary in 3.11 + kwargs: dict[str, Any] = {} + if sys.version_info >= (3, 11) and positions is not None: + kwargs["colno"] = positions.col_offset + kwargs["end_colno"] = positions.end_col_offset + return traceback.FrameSummary( + getattr(self.f_code, "co_filename", ""), + self.lineno, + getattr(self.f_code, "co_name", ""), + lookup_line=False, + **kwargs, + ) + + def is_co_filename_from_nn_modules(self) -> bool: + filename = getattr(self.f_code, "co_filename", "") + nn_modules_pattern = re.compile(r".*torch/nn/modules.*") + return nn_modules_pattern.match(filename) is not None + + def store_global_weakref_by_id(self, prefix: str, value: Any) -> str: + global_name = self.output.install_global_by_id(prefix, weakref.ref(value)) + install_guard( + GlobalWeakRefSource(global_name).make_guard(GuardBuilder.WEAKREF_ALIVE) + ) + return global_name + + @property + def fake_mode(self) -> FakeTensorMode | None: + return self.output.tracing_context.fake_mode + + @contextlib.contextmanager + def strict_translation_mode( + self, check_fn: Callable[[VariableTracker], bool] + ) -> Any: + """ + Strict mode is enabled on a per-VariableTracker level depending on the return value of check_fn(node). + """ + prior = self.strict_checks_fn + self.strict_checks_fn = check_fn + try: + yield + finally: + self.strict_checks_fn = prior + + def speculate(self) -> SpeculationEntry: + if self.instruction_pointer is None: + raise AssertionError( + "expected self.instruction_pointer is not None to be true" + ) + if not (self.instruction_pointer > 0): + raise AssertionError("expected self.instruction_pointer > 0 to be true") + return self.speculation_log.next( + self.f_code.co_filename, + self.lineno, + self.instruction_pointer - 1, + self.instructions[self.instruction_pointer - 1], + ) + + def _make_frame_loc( + self, filename: str, lineno: int | None, fallback_lineno: int + ) -> tuple[str, int]: + if lineno is None or lineno < 0: + return (filename, fallback_lineno) + return (filename, lineno) + + def _get_frame_loc_chain( + self, frame_loc: tuple[str, int] + ) -> tuple[tuple[str, int], ...]: + frame_loc_chain_list: list[tuple[str, int]] = [] + + if config.nested_graph_breaks: + current_tx: InstructionTranslatorBase | None = self.parent + while current_tx is not None: + parent_frame_loc = self._make_frame_loc( + current_tx.f_code.co_filename, + current_tx.lineno, + current_tx.f_code.co_firstlineno, + ) + frame_loc_chain_list.append(parent_frame_loc) + current_tx = current_tx.parent + + frame_loc_chain_list.reverse() + frame_loc_chain_list.append(frame_loc) + return tuple(frame_loc_chain_list) + + def _format_stack_source_attribution(self) -> str: + """Format bytecode source locations for stack values involved in a graph break.""" + seen: set[SourceLocation] = set() + parts: list[str] = [] + for vt in self.stack: + source_location = vt.source_location + if source_location is None: + continue + if source_location in seen: + continue + seen.add(source_location) + parts.append( + f" {vt!r} originated from:\n{source_location.format().rstrip()}" + ) + + if not parts: + return "" + return "Stack variable source attribution:\n" + "\n".join(parts) + + def log_graph_break( + self, + code_options: CodeOptions, + reason: str, + exc: Unsupported | UserError | StepUnsupported, + ) -> None: + if exc.logged: + return + + user_stack = getattr(exc, "real_stack", None) + + if user_stack is None: + user_stack = torch._guards.TracingContext.extract_stack() + + try: + if config.nested_graph_breaks and self.parent is not None: + frame_loc = self._make_frame_loc( + self.f_code.co_filename, + self.lineno, + self.f_code.co_firstlineno, + ) + else: + frame_loc = self._make_frame_loc( + user_stack[-1].filename, + user_stack[-1].lineno, + 0, + ) + except IndexError: + # first instruction + frame_loc = ( + code_options["co_filename"], + code_options["co_firstlineno"], + ) + frame_loc_chain = self._get_frame_loc_chain(frame_loc) + stack_above_dynamo_formatted = "" + if config.verbose: + stack_above_dynamo = get_stack_above_dynamo() + stack_above_dynamo_formatted = "".join( + traceback.format_list(stack_above_dynamo) + ) + else: + user_stack = get_stack_above_dynamo() + user_stack # type: ignore[assignment] + user_stack = collapse_resume_frames(user_stack) + user_stack_formatted = "".join(traceback.format_list(user_stack)) + + # Add HOP context after the first line of reason if present + if exc is not None: + reason = augment_exc_message_with_hop_name(exc, reason) + + stack_source_attribution = self._format_stack_source_attribution() + user_stack_trace_parts = [ + f"Graph break in user code at {frame_loc[0]}:{frame_loc[1]}", + f"Graph Break Reason: {reason}", + ] + if stack_source_attribution: + user_stack_trace_parts.extend(["", stack_source_attribution]) + user_stack_trace_parts.extend(["", "User code traceback:"]) + user_stack_trace = "\n".join(user_stack_trace_parts) + "\n" + + if config.verbose: + user_stack_trace += ( + f"{stack_above_dynamo_formatted}\n" + "========== most recent `torch.compile` tracing attempt started here ==========\n\n" + f"{user_stack_formatted}\n" + "NOTE: the most recent `torch.compile` tracing attempt might not be where you applied `torch.compile`! " + "This is due to how graph breaks are implemented - the optimized code object returned by Dynamo will call another " + "Dynamo-generated resume function and tracing is re-enabled by calling the resume function as a normal Python " + "function, which Dynamo intercepts as a top-level frame.\n" + ) + else: + user_stack_trace += str(user_stack_formatted) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_graph_break_reason", + "encoding": "string", + }, + payload_fn=lambda: f"{user_stack_trace}\n{traceback.format_exc()}", + ) + + # torch._dynamo.explain() formats this a little nicer, and presents a slightly + # more actionable user code pointer + gb_type = exc.gb_type if isinstance(exc, Unsupported) else type(exc) + if ( + graph_break_log.isEnabledFor(logging.DEBUG) + and not explain + and graph_break_dup_warning_checker.add((gb_type, frame_loc_chain)) # type: ignore[arg-type] + ): + # This log line MUST contain the string "Graph break in user code", + # This log line is exercised from + # python test/dynamo/test_exc.py -k test_graph_break_log + if config.verbose: + user_stack_trace += ( + "\nMost recent bytecode instructions traced (max 20):\n" + ) + user_stack_trace += "\n".join(self.latest_bytecode_queue) + "\n" + + graph_break_log.debug( + user_stack_trace, + ) + else: + # This log line MUST not contain the string "Graph break in user code", + # exercised by + # python test/dynamo/test_misc.py -k test_duplicate_graph_break_log + graph_break_log.debug( + "Graph break (user stack suppressed due to duplicate graph break) in user code at %s:%s\nGraph Break Reason: %s", + frame_loc[0], + frame_loc[1], + reason, + ) + + exc.logged = True + + @staticmethod + def raise_loop_graph_break( + code: types.CodeType, exc: Unsupported | UserError + ) -> NoReturn: + unimplemented( + gb_type="graph break in loop", + context=f"frame skipped: {format_frame_info(code)}", + explanation="torch.compile detected a graph break in a for/while loop. " + "Skipping the frame and falling back to eager, as graph breaks in loops are not supported.", + hints=[*graph_break_hints.CAUSED_BY_EARLIER_GRAPH_BREAK], + from_exc=exc, + skip_frame=True, + ) + + def __init__( + self, + output: OutputGraph, + instructions: list[Instruction], + f_locals: dict[str, Any], + f_globals: dict[str, Any], + f_builtins: dict[str, Any], + code_options: CodeOptions, + symbolic_locals: dict[str, VariableTracker], + symbolic_globals: dict[str, VariableTracker], + symbolic_torch_function_state: SymbolicTorchFunctionState, + symbolic_stream_state: SymbolicStreamState, + f_code: types.CodeType, + export: bool, + inline_depth: int, + speculation_log: SpeculationLog, + exn_vt_stack: ExceptionStack, + distributed_state: DistributedState | None, + # This determines whether to use the execution recorder. + closure: tuple[types.CellType] | None = None, + package: CompilePackage | None = None, + # Pre-computed indexof for cache reuse + indexof: dict[Instruction, int] | None = None, + ) -> None: + super().__init__() + self.speculation_log = speculation_log + self.distributed_state = distributed_state + + # Mutable state checkpointed by copy_graphstate() + self.output = output + self.symbolic_locals = symbolic_locals + self.symbolic_cellvars = {} + self.symbolic_globals = symbolic_globals + self.symbolic_torch_function_state = symbolic_torch_function_state + self.symbolic_stream_state = symbolic_stream_state + # used to keep cell/freevars alive after pruning symbolic_locals (prune_dead_locals) + # in order to generate any nested closures + self.post_prune_cell_and_freevars = None + self.stack: list[VariableTracker] = [] + self.instruction_pointer = 0 + self.start_point = None + self.current_instruction = create_instruction("NOP") + self.current_instruction_push = True + self.block_stack = [] + # states before SETUP_WITH for checkpointing and fallback + self.active_generic_context_managers: list[GenericContextWrappingVariable] = [] + self.skip_one_hop_torch_function_depth: int = 0 + self.lineno = -1 + self.kw_names = None + self.accept_prefix_inst = True + self.prefix_insts = [] + self.exn_vt_stack = exn_vt_stack + self.latest_bytecode_queue = deque(maxlen=20) + self._comprehension_depth = 0 + self._comprehension_end_for_ips: set[int] = set() + # Per-prefix counters for generating fresh pycode-local variable names. + self._pycode_varname_counter: defaultdict[str, itertools.count[int]] = ( + defaultdict(lambda: itertools.count(0)) + ) + # Per-prefix record of the most recently generated pycode varname. + self._pycode_last_varname: dict[str, str] = {} + + # Properties of the input/output code + self.instructions: list[Instruction] = instructions + self.indexof: dict[Instruction, int] = ( + indexof if indexof is not None else get_indexof(self.instructions) + ) + self.f_locals: dict[str, Any] = ( + f_locals # needed for recording accessed locals for replay + ) + self.f_globals: dict[str, Any] = f_globals + self.f_builtins: dict[str, Any] = f_builtins + self.code_options: CodeOptions = code_options + self.f_code: types.CodeType = f_code + self.closure = closure + # Inlined frames receive a fully-populated symbolic_locals (cells + # included); register their cells now. Root frames populate + # symbolic_locals after super().__init__ and register there. + self._register_cells() + + # Execution record for replaying errors + if closure is not None and config.replay_record_enabled: + self.exec_recorder = ExecutionRecorder( + code=f_code, + closure=closure, + code_options=code_options, + ) + else: + self.exec_recorder = None + # Stack of module being parsed, current nn.module is at the end of ordered dict. + # The first field of tuple is the fully qualified name of current module + # in original hierarchy. The second field is the type of current nn.module + self.nn_module_stack: dict[str, tuple[str, type[Any]]] = {} + self.num_calls: dict[str, int] = {} + # Flag to indicate whether tracing is used for export. + self.export = export + # NOTE: one_graph is used for export/fullgraph=True to always force errors on graph breaks. + # To toggle erroring/resuming on graph breaks during fullgraph=False compile, self.error_on_graph_break + # is used instead. Every step(), its value is updated to the global tls.error_on_graph_break. + # We mirror this value since cleanup may (correctly) inadvertently change tls.error_on_graph_break. + # This assumes that we cannot both trace a change to tls.error_on_graph_break and graph break on + # the same instruction. + self.one_graph = False + self.error_on_graph_break = False + # Also do not graph break when tracing resume function prologues + self.is_tracing_resume_prologue = False + + self.current_speculation = None + + self.strict_checks_fn = None + + self.has_no_inlined_calls = True + self.parent = None + self.is_child_tracer_active = False + self.debug_locals = [] + + self.package = package + + from .resume_execution import ( + CO_ASYNC_GENERATOR, + CO_COROUTINE, + CO_GENERATOR, + CO_ITERABLE_COROUTINE, + ) + + # This isn't really the right place to push None. But since we treat RETURN_GENERATOR as a no-op for + # non-generator frames, there needs to be something on the stack since the first instruction will be POP_TOP, + # which would error out with an empty stack + push_types = CO_COROUTINE | CO_ITERABLE_COROUTINE | CO_ASYNC_GENERATOR + if sys.version_info < (3, 11): + push_types |= CO_GENERATOR + if f_code.co_flags & (push_types): + self.push(BuiltinVariable(None)) + + self.inline_depth = inline_depth + self.inconsistent_side_effects = False + self._constants_cache: list[ConstantVariable | SliceVariable | None] = [ + None + ] * len(f_code.co_consts) + + self.is_trace_bytecode_log_enabled: bool | None = ( + trace_bytecode_log.isEnabledFor(logging.DEBUG) + ) + self.is_trace_source_log_enabled: bool | None = trace_source_log.isEnabledFor( + logging.DEBUG + ) + linecache.lazycache(f_code.co_filename, f_globals) + + +class InstructionTranslator(InstructionTranslatorBase): + @staticmethod + def current_tx() -> InstructionTranslator: + return tls.current_tx + + @contextlib.contextmanager + def set_current_tx(self) -> Any: + prior = getattr(tls, "current_tx", None) + tls.current_tx = self + try: + yield + finally: + if prior is not None: + tls.current_tx = prior + elif hasattr(tls, "current_tx"): + del tls.current_tx + + def __init__( + self, + instructions: list[Instruction], + f_code: types.CodeType, + f_locals: dict[str, Any], + f_globals: dict[str, Any], + f_builtins: dict[str, Any], + closure: tuple[Any, ...] | None, + torch_function_mode_stack: Any, + code_options: CodeOptions, + compiler_fn: Any, + one_graph: bool, + export: bool, + export_constraints: Any, + frame_state: Any, + speculation_log: SpeculationLog, + exn_vt_stack: ExceptionStack, + distributed_state: DistributedState | None, + package: CompilePackage | None, + ) -> None: + _step_logger()( + logging.INFO, + f"torchdynamo start tracing {f_code.co_name} {code_options['co_filename']}:{code_options['co_firstlineno']}", + ) + super().__init__( + output=OutputGraph( + code_options, + compiler_fn, + self, + export, + export_constraints, + frame_state, + local_scope=f_locals, + global_scope=f_globals, + f_code=f_code, + torch_function_mode_stack=torch_function_mode_stack, + one_graph=one_graph, + package=package, + ), + instructions=instructions, + f_locals=f_locals, + f_globals=f_globals, + f_builtins=f_builtins, + closure=closure, + code_options=code_options, + symbolic_locals={}, # set below + # A global var is inserted only after a STORE_GLOBAL happens to it + symbolic_globals={}, + symbolic_torch_function_state=None, # type: ignore[arg-type] # set below + symbolic_stream_state=None, # type: ignore[arg-type] # set below + f_code=f_code, + export=export, + inline_depth=0, + speculation_log=speculation_log, + exn_vt_stack=exn_vt_stack, + distributed_state=distributed_state, + package=package, + ) + + self._throw_if_in_functorch() + + # as soon as we create the tracing context we should keep it active, so any calls + # into dynamo apis can rely on finding it + with tracing(self.output.tracing_context), self.set_current_tx(): + self.one_graph: bool = one_graph + self.export = export + if self.export: + if not self.one_graph: + raise AssertionError( + "Export without one graph - something has gone wrong." + ) + + self.symbolic_locals = {} + # Populate `symbolic_locals` with non-cell variables. + cell_and_freevars: set[str] = set(self.cell_and_freevars()) + + # Identify the names of `*args` / `**kwargs` parameters (if any) + # via the function's `co_flags`. The varargs param (if present) + # comes immediately after `co_argcount + co_kwonlyargcount` + # entries in `co_varnames`; the varkw param comes right after. + varargs_name: str | None = None + varkw_name: str | None = None + _vararg_idx = f_code.co_argcount + f_code.co_kwonlyargcount + if f_code.co_flags & CO_VARARGS: + varargs_name = f_code.co_varnames[_vararg_idx] + _vararg_idx += 1 + if f_code.co_flags & CO_VARKEYWORDS: + varkw_name = f_code.co_varnames[_vararg_idx] + + # Skip inputs never read anywhere in the function: they cannot + # affect the graph or any resume suffix, so guards on them are + # wasteful. Export mode must keep all locals because realize_all() + # below needs them. locals()/vars() are handled in _call_frame_locals_snapshot + # which adds pruned entries back from tx.f_locals on demand. + if export: + function_live_names: set[str] | None = None + else: + function_live_names = livevars_analysis( + self.instructions, self.instructions[0] + ) + + dynamism = code_context.get_context(f_code).get("dynamism", None) + for name, value in f_locals.items(): + if name not in cell_and_freevars: + if ( + function_live_names is not None + and name not in function_live_names + and name != varargs_name + and name != varkw_name + ): + continue + local_dynamism = None + if dynamism: + local_dynamism = frozenset(dynamism.get(name, {}).items()) + var = LazyVariableTracker.create( + value, + LocalSource( + name, + is_input=True, + dynamism=local_dynamism, + is_varargs=(name == varargs_name), + is_varkw=(name == varkw_name), + ), + tx=self, + ) + self.symbolic_locals[name] = var + + # Populate `symbolic_locals` with cells created by this frame, + # effectively implementing the `MAKE_CELL` instructions. + side_effects = self.output.side_effects + for name in self.cellvars(): + if name in f_locals: + # This models cells that are also function inputs. + value = f_locals[name] + # NOTE: root frame inputs that are captured by a nested + # function become special cell objects -- they exist in + # `f_locals` as contents of the cells, rather than the cells + # objects themselves. + # + # In Dynamo, we choose to represent such input cell objects + # as newly created (rather than pre-existing) cell objects, + # because + # + # 1. The reason for representing a pre-existing cell object + # is to emit guard or codegen mutations. However, local + # cells should never be used for guards. Moreover, at this + # point these input cell objects should've never been + # accessed by anyone else, since Dynamo intercepts the frame + # right after its evaluation starts, i.e., right after these + # cell objects are created. So they should have no external + # reference, meaning no mutation needs to be propagated. + # + # 2. This conveniently allows codegen to prune away + # mutations to these cells, unless they escape the frame. + contents_source = LocalSource( + name, + is_input=True, + is_derefed_cell_contents=True, + ) + contents_var: VariableTracker = LazyVariableTracker.create( + value, contents_source, tx=self + ) + cell_var = side_effects.track_cell_new() + side_effects.store_cell(cell_var, contents_var) + else: + cell_var = side_effects.track_cell_new() + cell_var.local_name = name # type: ignore[attr-defined] + self.symbolic_locals[name] = cell_var + + # Populate `symbolic_locals` with cells captured by this frame, + # effectively implementing the `COPY_FREE_VARS` instruction. + if closure is None: + raise AssertionError("expected closure is not None to be true") + for name, cell in zip(self.freevars(), closure): + cell_source = LocalCellSource(name) + contents_source = LocalSource(name, is_derefed_cell_contents=True) + try: + contents_var = LazyVariableTracker.create( + cell.cell_contents, contents_source, tx=self + ) + except ValueError: + # Cell has not yet been assigned + contents_var = variables.DeletedVariable() + cell_var = side_effects.track_cell_existing( + cell_source, cell, contents_var + ) + cell_var.local_name = name # type: ignore[attr-defined] + self.symbolic_locals[name] = cell_var + + # symbolic_locals is now fully populated; register the frame's + # cells (base __init__ ran before this population). + self._register_cells() + + self.symbolic_torch_function_state = SymbolicTorchFunctionState( + torch_function_mode_stack, + skip_next=False, + ) + + self.symbolic_stream_state = SymbolicStreamState() + + if export: + # export gets confused if we never realize unused inputs + # in export mode just eagerly realize everything + self.symbolic_locals = variables.LazyVariableTracker.realize_all( + self.symbolic_locals + ) + self.symbolic_cellvars = variables.LazyVariableTracker.realize_all( + self.symbolic_cellvars + ) + + def _throw_if_in_functorch(self) -> None: + # Fallback to eager in case of a graph break inside vmap + eager = torch._dynamo.lookup_backend("eager") + compiler_fn = inspect.getattr_static( + self.output.compiler_fn, "compiler_fn", self.output.compiler_fn + ) + ci = torch._C._functorch.peek_interpreter_stack() + forbidden_keys = ( + torch._C._functorch.TransformType.Vmap, + torch._C._functorch.TransformType.Grad, + torch._C._functorch.TransformType.Jvp, + ) + + if ci is not None and ci.key() in forbidden_keys and compiler_fn is not eager: + name = ci.key().name.lower() + msg = ( + "If you are reaching here, it means dynamo failed for one of the following reasons:\n" + # Calling a torch.compiled function + f"- Calling torch.func.{name}(compiled_fn) function from eager mode is not supported. " + f"Ensure that torch.func.{name} is also wrapped within a torch.compile function. " + "For more information, see PyTorch issue #128711.\n" + # if it reaches here, it means Dynamo failed to inline a functorch function + f"- torch.func.{name}(fn) requires the function to be inlined by dynamo" + ) + unimplemented( + gb_type="Unsupported functorch tracing attempt", + context="", + explanation=msg, + hints=[], + ) + + def get_example_value(self, source: Source) -> Any: + if isinstance(source, LocalSource): + return self.f_locals[source.local_name] + if isinstance(source, GlobalSource): + return self.f_globals[source.global_name] + raise KeyError + + def symbolic_locals_contain_module_class(self) -> bool: + for v in self.symbolic_locals.values(): + if isinstance(v, UserDefinedClassVariable) and issubclass( + v.as_python_constant(), torch.nn.Module + ): + return True + return False + + def replace_tos_if_return_is_generator(self) -> None: + if ( + len(self.stack) + and (tos := self.stack[-1]) + and isinstance(tos, LocalGeneratorObjectVariable) + ): + self.stack[-1] = ListIteratorVariable( + unpack_iterable(self, tos), + mutation_type=ValueMutationNew(), + ) + + def _return(self, inst: Instruction) -> None: + self.replace_tos_if_return_is_generator() + if self.instruction_pointer is None: + raise AssertionError( + "expected self.instruction_pointer is not None to be true" + ) + if self.start_point is None: + raise AssertionError("expected self.start_point is not None to be true") + get_metrics_context().increment( + "ir_count", self.instruction_pointer - self.start_point + ) + + if ( + not config.allow_empty_graphs + and self.output.count_calls() == 0 + and not self.inconsistent_side_effects + and not self.symbolic_locals_contain_module_class() + and not self.export + and not self.one_graph + and not self.error_on_graph_break + and not self.is_tracing_resume_prologue + ): + raise exc.SkipFrame( + "No ops traced for the FX graph. `torch.compile` will skip the frame and fall back to eager.\n" + f"Frame info: {format_frame_info(self.f_code)}" + ) + + self.instruction_pointer = None + _step_logger()( + logging.INFO, + f"torchdynamo done tracing {self.f_code.co_name} ({inst.opname})", + ) + log.debug("return triggered compile") + all_stack_locals_metadata = self.output.compile_subgraph( + self, + reason=GraphCompileReason( + "return_value", [self.frame_summary()], graph_break=False + ), + # the value to be returned + stack_pops=1 if inst.opname == "RETURN_VALUE" else 0, + ) + # check that our stack/locals meta are correct: + # we should only be tracing 1 frame, and there should not be any NULLs on the stack + if len(all_stack_locals_metadata) != 1: + raise AssertionError( + "expected len(all_stack_locals_metadata) == 1 to be true" + ) + if all_stack_locals_metadata[0].stack_null_idxes: + raise AssertionError( + "expected not all_stack_locals_metadata[0].stack_null_idxes to be true" + ) + self.output.add_output_instructions( + self.codegen_return_with_pops(inst, all_stack_locals_metadata[0].num_stack), + [f"__ret = {self.get_pycode_last_varname('stack')}"] + if config.generate_pycode + else None, + ) + raise ReturnValueOp + + def RETURN_VALUE(self, inst: Instruction) -> None: + self._return(inst) + + def RETURN_CONST(self, inst: Instruction) -> None: + self._return(inst) + + +if sys.version_info >= (3, 11): + _binary_op_lookup = [ + getattr( + InstructionTranslator, + opname[3:] if "INPLACE" in opname else f"BINARY_{opname[3:]}", + ) + for opname, _ in dis._nb_ops # type: ignore[attr-defined] + ] + + +@contextlib.contextmanager +def profile_inline_call( + output: OutputGraph, + code: types.CodeType, + get_inline_depth: Callable[[], int], +) -> Generator[None, None, None]: + """ + Context manager for profiling inline calls. + + Args: + output: The OutputGraph containing profiler_state + code: The code object being inlined (for timing metadata) + get_inline_depth: Callable that returns inline_depth (called after work completes) + + Yields: + None (profiling happens around the with block) + """ + if not config.dynamo_profiler: + yield + return + + if output.profiler_state is None: + output.profiler_state = DynamoProfilerState() + + caller_info = output.profiler_state.get_current_caller() + call_stack = output.profiler_state.get_call_stack() + + output.profiler_state.push( + code.co_name, code.co_filename, code.co_firstlineno, time.time_ns() + ) + + trace_success = False + try: + yield + trace_success = True + finally: + stack_entry = output.profiler_state.pop() + trace_end_ns = time.time_ns() + + if trace_success and stack_entry is not None: + inline_depth = get_inline_depth() + cumtime_ns = trace_end_ns - stack_entry.start_time_ns + tottime_ns = cumtime_ns - stack_entry.child_time_ns + + timing = FunctionTraceTiming( + func_name=stack_entry.func_name, + filename=stack_entry.filename, + firstlineno=stack_entry.firstlineno, + cumtime_ns=cumtime_ns, + tottime_ns=tottime_ns, + bytecode_count=len(code.co_code), + inline_depth=inline_depth, + caller_func_name=caller_info[0] if caller_info else None, + caller_filename=caller_info[1] if caller_info else None, + caller_firstlineno=caller_info[2] if caller_info else None, + is_primitive_call=stack_entry.is_primitive_call, + call_stack=call_stack, + ) + output.profiler_state.record_timing(timing) + output.profiler_state.add_child_time(cumtime_ns) + + +class InliningInstructionTranslator(InstructionTranslatorBase): + """Trace and inline a called method""" + + symbolic_result: VariableTracker | None + # pyrefly: ignore [bad-override] + parent: InstructionTranslatorBase + + @classmethod + def inline_call( + cls, + parent: Any, + func: BaseUserFunctionVariable, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + allow_nested_graph_breaks: bool = False, + ) -> VariableTracker: + tracer = None + with profile_inline_call( + parent.output, func.get_code(), lambda: parent.inline_depth + 1 + ): + tracer = cls.build_inline_tracer( + parent, + func, + args, + kwargs, + allow_nested_graph_breaks=allow_nested_graph_breaks, + ) + return tracer.inline_call_() + + @staticmethod + def check_inlineable( + func: BaseUserFunctionVariable, + ) -> trace_rules.SkipResult: + if func.has_self(): + unimplemented( + gb_type="Inline attempt with __self__", + context=str(func), + explanation="Attempted to inline a function with the `__self__` attribute. " + "Dynamo is expected to decompose method calls into function calls with a `self` argument.", + hints=[], + ) + + if isinstance(func, UserFunctionVariable) and inspect.getattr_static( + func.get_function(), "_torchdynamo_disable", False + ): + msg = inspect.getattr_static( + func.get_function(), "_torchdynamo_disable_msg", None + ) + unimplemented( + gb_type="Skip inlining `torch.compiler.disable()`d function", + context=str(func.get_function()), + explanation=f"Skip inlining function {func.get_function()} since it was wrapped " + f"with `torch.compiler.disable` (reason: {msg})", + hints=[ + "Remove the `torch.compiler.disable` call", + ], + ) + + result = trace_rules.check_verbose(func, is_inlined_call=True) + if result.skipped: + from torch._dynamo.variables.misc import produce_trampoline_autograd_apply + + # _origin marks this as coming from an internal dynamo known function that is safe to + # trace through. + if ( + hasattr(func, "fn") + and hasattr(func.fn, "_origin") + and func.fn._origin is produce_trampoline_autograd_apply + ): + # Known sound + return trace_rules.SkipResult( + False, "allowlist in dynamo known function" + ) + fn_qualname = func.fn.__qualname__ if hasattr(func, "fn") else "" + hints = [ + f"Avoid calling the function `{fn_qualname}`.", + ] + if "_dynamo" not in func.get_filename(): + hints += [ + f"Apply `@torch._dynamo.dont_skip_tracing` to the function `{fn_qualname}` " + "to force tracing into the function. " + "More graph breaks may occur as a result of attempting to trace into the function.", + "Please file an issue to PyTorch.", + ] + unimplemented( + gb_type="Attempted to inline function marked as skipped", + context=f"qualname: {fn_qualname}, name: {func.get_name()}, " + f"filename: `{func.get_filename()}`, skip reason: {result.reason}", + explanation=f"Dynamo developers have intentionally marked that the function `{fn_qualname}` " + "should not be traced.", + hints=hints, + ) + + return result + + @staticmethod + def build_inline_tracer( + parent: Any, + func: BaseUserFunctionVariable, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + allow_nested_graph_breaks: bool = False, + ) -> InliningInstructionTranslator: + if not isinstance( + func, + ( + UserFunctionVariable, + NestedUserFunctionVariable, + LocalGeneratorFunctionVariable, + ), + ): + raise AssertionError( + "expected isinstance( func, ( UserFunctionVariable, NestedUserFunctionVariable, LocalGeneratorFunctionVariable, ), ) to be true" + ) + code: types.CodeType = func.get_code() + result = None + tracing_ctx = parent.output.tracing_context + + # Check if we have already identified this function to be inline-able. + # The exception is dont_skip_tracing flag which affects the inline + # behavior. If the flag is True, don't rely on previous results. + if not config.dont_skip_tracing and tracing_ctx: + if previous_result := tracing_ctx.previously_inlined_functions.get( + code, None + ): + result = previous_result + + if result is None: + result = InliningInstructionTranslator.check_inlineable(func) + if result.skipped is not False: + raise AssertionError("expected result.skipped is False to be true") + + if not config.dont_skip_tracing and tracing_ctx: + tracing_ctx.previously_inlined_functions[code] = result + + sub_locals = None + try: + sub_locals = func.bind_args(parent, args, kwargs) + except variables.functions.BindArgsTypeError as e: + exc.raise_type_error(parent, msg=e.args[0]) + + if sub_locals is None: + raise AssertionError("expected sub_locals is not None to be true") + + for v in itertools.chain(sub_locals.values()): + if not isinstance(v, VariableTracker): + unimplemented( + gb_type="Encountered unconverted argument when attempting to inline", + context=f"func: {func}, arg: {v}", + explanation="An argument to an inlined function was not successfully converted to a VariableTracker.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + if code.co_name in ( + "__setitem__", + "__setattr__", + "__delitem__", + "__delattr__", + ) and not ( + args + and isinstance( + args[0], + ( + variables.UserDefinedObjectVariable, + variables.UserDefinedClassVariable, + ), + ) + ): + unimplemented( + gb_type="Unsupported __setitem__/__setattr__/__delitem__/__delattr__ inline attempt", + context=f"code name: {code.co_name}, args: {args}", + explanation=f"Attempted to inline {code.co_name} where first argument (self) is not a user-defined object.", + hints=[], + ) + + suffix = "" + # TODO: mlazos, add support for enabling multiple artifact logs + # with a single alias + if torch._logging._internal.log_state.is_artifact_enabled("bytecode"): + suffix = f"\n{dis.Bytecode(code).dis()}" + if sys.version_info >= (3, 11): + cur_inst = parent.current_instruction + parent_code = parent.f_code + + def get_trace_call_log_str() -> str: + header = parent.get_line_of_code_header( + lineno=cur_inst.positions.lineno + ) + line = get_instruction_source_311(parent_code, cur_inst).rstrip() + return f"TRACE inlined call {code.co_name} from {header}\n{line}" + + trace_call_log.debug("%s", LazyString(get_trace_call_log_str)) + log.debug("INLINING %s%s, %s", code, suffix, result.reason) + + # Detect inline GraphModule calls in order to propagate node metadata, + # by checking if the first argument (self) is a variable tracking a GraphModule. + # For unrealized lazy VTs, use peek_type to skip non-Module args + # without realizing them (which would install unnecessary guards). + if args: + arg0 = args[0] + should_check = True + if isinstance(arg0, LazyVariableTracker) and not arg0.is_realized(): + if issubclass(arg0.peek_type(), torch.nn.Module): + arg0 = arg0.realize() + else: + should_check = False + + if should_check: + if isinstance(arg0, NNModuleVariable): + module = parent.output.get_submodule(arg0.module_key) + if isinstance(module, torch.fx.GraphModule): + code_context.get_context(module.forward.__code__)[ + "orig_graphmodule" + ] = weakref.ref(module) + elif isinstance(arg0, UnspecializedNNModuleVariable): + module = arg0.value + if isinstance(module, torch.fx.GraphModule): + code_context.get_context(module.forward.__code__)[ + "orig_graphmodule" + ] = weakref.ref(module) + + if isinstance(func, SkipFunctionVariable): + raise AssertionError( + "expected not isinstance(func, SkipFunctionVariable) to be true" + ) + tracer: InliningInstructionTranslator + if is_generator(code): + tracer = InliningGeneratorInstructionTranslator( + parent, + code, + sub_locals, + parent.symbolic_globals, + parent.symbolic_torch_function_state, + parent.symbolic_stream_state, + func, + allow_nested_graph_breaks=allow_nested_graph_breaks, + ) + else: + tracer = InliningInstructionTranslator( + parent, + code, + sub_locals, + parent.symbolic_globals, + parent.symbolic_torch_function_state, + parent.symbolic_stream_state, + func, + allow_nested_graph_breaks=allow_nested_graph_breaks, + ) + return tracer + + def inline_call_(self) -> VariableTracker: + parent = self.parent + parent.has_no_inlined_calls = False + parent.is_child_tracer_active = True + code = self.f_code + + strict_ctx: Any = contextlib.nullcontext() + if parent.strict_checks_fn: + strict_ctx = self.strict_translation_mode(parent.strict_checks_fn) + + try: + with strict_ctx: + self.run() + except exc.ObservedException as e: + msg = f"Observed exception DURING INLING {code} : {e}" + log.debug(msg) + # bubble up the exception to the parent frame. + raise + except (Unsupported, UserError) as e: + # If this graph break has skip_frame set, unset it + # since it refers to the current frame and not the parent. + e.skip_frame = False + raise + except Exception: + log.debug("FAILED INLINING %s", code) + raise + finally: + # Pass inlined tx's error_on_graph_break to parent. + # Deals with the case where the parent's error_on_graph_break is True + # while the inlined tx's error_on_graph_break was set to False. + parent.error_on_graph_break = self.error_on_graph_break + parent.is_child_tracer_active = False + + if self.output.should_exit: + # graph break + return ConstantVariable.create(None) # return dummy variable + + if self.symbolic_result is None: + raise AssertionError("expected self.symbolic_result is not None to be true") + + if self.f_globals is parent.f_globals: + # Merge symbolic_globals back if parent and child are in the same namespace + parent.symbolic_globals.update(self.symbolic_globals) + + parent.inconsistent_side_effects |= self.inconsistent_side_effects + + log.debug("DONE INLINING %s", code) + self.output.tracing_context.traced_code.append(code) + + if ( + is_generator(code) + and isinstance(self, InliningGeneratorInstructionTranslator) + and self.frame_state == FrameState.FRAME_CLEARED + ): + # When the generator returns None, we raise StopIteration + # pyrefly: ignore [implicit-any] + args = [] + if not self.symbolic_result.is_constant_none(): + args = [self.symbolic_result] + exc.raise_observed_exception(StopIteration, self, args=args) + else: + return self.symbolic_result + + def __init__( + self, + parent: InstructionTranslatorBase, + code: types.CodeType, + symbolic_locals: dict[str, VariableTracker], + symbolic_globals: dict[str, VariableTracker], + symbolic_torch_function_state: SymbolicTorchFunctionState, + symbolic_stream_state: SymbolicStreamState, + funcvar: BaseUserFunctionVariable | LocalGeneratorObjectVariable, + allow_nested_graph_breaks: bool = False, + ) -> None: + f_globals = funcvar.get_globals() + f_builtins = f_globals["__builtins__"] + if not isinstance(f_builtins, dict): + f_builtins = f_builtins.__dict__ + + # Get the cached code data. This cache combines instructions, indexof, and + # code_options to avoid recomputing them for frequently-inlined functions. + tracing_ctx = parent.output.tracing_context + cached = tracing_ctx.inlined_code_cache.get(code) if tracing_ctx else None + + if cached is not None: + instructions = cached.instructions + indexof = cached.indexof + code_options = cached.code_options + else: + instructions = cleaned_instructions(code) + propagate_line_nums(instructions) + indexof = get_indexof(instructions) + code_options = cast( + CodeOptions, {k: getattr(code, k) for k in get_code_keys()} + ) + if tracing_ctx: + tracing_ctx.inlined_code_cache[code] = InlinedCodeCache( + instructions=instructions, + indexof=indexof, + code_options=code_options, + ) + + super().__init__( + output=parent.output, + f_locals={}, + f_globals=f_globals, + f_builtins=f_builtins, + symbolic_locals=symbolic_locals, + symbolic_globals=symbolic_globals, + symbolic_torch_function_state=symbolic_torch_function_state, + symbolic_stream_state=symbolic_stream_state, + instructions=instructions, + code_options=code_options, + f_code=code, + export=parent.export, + inline_depth=parent.inline_depth + 1, + speculation_log=parent.speculation_log, + exn_vt_stack=parent.exn_vt_stack, + distributed_state=parent.distributed_state, + package=parent.package, + indexof=indexof, + ) + self.funcvar = funcvar + self.parent = parent + self.num_calls = parent.num_calls + self.symbolic_result = None + self.nn_module_stack = parent.nn_module_stack.copy() + self.one_graph = parent.one_graph + self._allow_nested_graph_breaks = allow_nested_graph_breaks + + @property + def fake_mode(self) -> FakeTensorMode | None: + return self.parent.fake_mode + + def run_ctx_mgr(self) -> Any: + return TracingContext.current_frame(self.parent.frame_summary()) + + def _can_speculate_comprehension_nested(self) -> bool: + """Check if comprehension speculation is allowed in this inlined context. + + Unlike should_compile_partial_graph(), this skips the exception table entry check. + """ + if not config.nested_graph_breaks: + return False + if not self._allow_nested_graph_breaks: + return False + if not self.funcvar.should_allow_nested_graph_breaks(): + return False + if not self.parent.should_compile_partial_graph(): + return False + return True + + def should_compile_partial_graph(self) -> bool: + if config.nested_graph_breaks: + if not self._allow_nested_graph_breaks: + return False + if not self.funcvar.should_allow_nested_graph_breaks(): + return False + if not self.parent.should_compile_partial_graph(): + return False + return super().should_compile_partial_graph() + return False # inlining functions is all-or-nothing + + def create_call_resume_at( + self, + inst: Instruction, + all_stack_locals_metadata: list[StackLocalsMetadata], + ) -> list[Instruction]: + if config.nested_graph_breaks: + return super().create_call_resume_at(inst, all_stack_locals_metadata) + unimplemented( + gb_type="Graph break in inlined function", + context="", + explanation="Graph breaks in an inlined call are not supported.", + hints=[], + ) + + def RETURN_VALUE(self, inst: Instruction) -> None: + self.symbolic_result = self.pop() + self.instruction_pointer = None + raise ReturnValueOp + + def RETURN_CONST(self, inst: Instruction) -> None: + self.symbolic_result = self._load_const(inst) + self.instruction_pointer = None + raise ReturnValueOp + + def get_globals_source_and_value( + self, name: str + ) -> tuple[Any, VariableTracker, Source]: + registered_module = _registered_module_for_globals( + self.f_globals.get("__name__"), self.f_globals + ) + if registered_module is not None: + module_name, fglobals_value = registered_module + module_source = self.import_source(module_name) + # Don't use lazy vt because we will do a setattr afterwards + # TODO: fix InstructionTranslator -> InstructionTranslatorBase + # pyrefly: ignore[bad-argument-type] + fglobals_vt = VariableBuilder(self, module_source)(fglobals_value) + global_source = AttrSource(module_source, name) + else: + globals_name = self.output.install_global_by_id( + "___unnamed_scope", self.f_globals + ) + globals_source = GlobalSource(globals_name) + fglobals_value = self.f_globals # type: ignore[assignment] + # Don't use lazy vt because we will do a setattr afterwards + # pyrefly: ignore[bad-argument-type] + fglobals_vt = VariableBuilder(self, globals_source)(fglobals_value) + global_source = DictGetItemSource(globals_source, name) # type: ignore[assignment] + + if is_stdlib(fglobals_value): + # Users don't inplace mutate a stdlib attribute (like inspect, + # collections), skip guards that originate from the stdlib modules. + global_source = SkipGuardSource(global_source) # type: ignore[assignment] + + return fglobals_value, fglobals_vt, global_source + + def _load_global(self, inst: Instruction) -> None: + name = inst.argval + if name not in self.f_globals: + return self.load_builtin(inst) + + if self.output.global_scope is self.f_globals: + # If the global scope matches that of the root frame, use handler in + # root frame instruction translator, to enforce consistency. + super()._load_global(inst) + else: + _, fglobals_vt, global_source = self.get_globals_source_and_value(name) + if self.output.side_effects.has_pending_mutation_of_attr(fglobals_vt, name): + self.push(self.output.side_effects.load_attr(fglobals_vt, name)) + else: + value = self.f_globals[name] + self.push(VariableTracker.build(self, value, global_source)) + + def STORE_GLOBAL(self, inst: Instruction) -> None: + if self.output.global_scope is self.f_globals: + # If the global scope matches that of the root frame, use handler in + # root frame instruction translator, to enforce consistency. + super().STORE_GLOBAL(inst) + else: + value = self.pop() + if isinstance(value, RemovableHandleVariable): + unimplemented( + gb_type="Storing Tensor hook handle in globals (inline call)", + context=inst.argval, + explanation="This is not supported.", + hints=[], + ) + name = inst.argval + _fglobals_value, fglobals_vt, global_source = ( + self.get_globals_source_and_value(name) + ) + if isinstance(global_source, DictGetItemSource): + unimplemented( + gb_type="STORE_GLOBAL in non-module globals", + context=name, + explanation=( + "Dynamo cannot safely replay global writes for an inlined " + "function whose globals dict is not the registered module " + "__dict__." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + self.output.side_effects.store_attr(fglobals_vt, name, value) + + +class InliningGeneratorInstructionTranslator(InliningInstructionTranslator): + generated_items: list[VariableTracker] + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.generated_items = [] + self.frame_state = FrameState.FRAME_CREATED + self.gi_exc_state = Segment() + + @contextlib.contextmanager + def link_gi_exc_state(self): + try: + self.exn_vt_stack.push_segment(self.gi_exc_state) + yield + finally: + self.exn_vt_stack.pop_segment() + + @contextlib.contextmanager + def temporarily_set_frame_state(self, state: FrameState): + saved_frame_state = self.frame_state + try: + self.frame_state = state + yield + finally: + self.frame_state = saved_frame_state + + def inline_call_(self) -> VariableTracker: + with profile_inline_call(self.output, self.f_code, lambda: self.inline_depth): + return super().inline_call_() + + def should_compile_partial_graph(self) -> bool: + # resuming on graph break on inlined generator not supported + return False + + def YIELD_VALUE(self, inst: Instruction) -> None: + top = self.pop() + self.generated_items.append(top) + prev = self.instructions[self.indexof[inst] - 1].opname + if inst.opname == "YIELD_FROM" or prev == "SEND": + self.frame_state = FrameState.FRAME_SUSPENDED_YIELD_FROM + else: + self.frame_state = FrameState.FRAME_SUSPENDED + if len(self.generated_items) > MAX_ITERATOR_LIMIT: + raise exc.InfiniteGeneratorError + self.symbolic_result = top + # Stop tracing + raise YieldValueOp + + def GET_YIELD_FROM_ITER(self, inst: Instruction) -> None: + tos = self.stack[-1] + if not isinstance(tos, ListIteratorVariable): + self.pop() + res = VariableTracker.build(self, iter).call_function(self, [tos], {}) # type: ignore[arg-type] + self.push(res) + + def RETURN_GENERATOR(self, inst: Instruction) -> None: + self.symbolic_result = self.funcvar + raise ReturnValueOp + + def RETURN_VALUE(self, inst: Instruction) -> None: + self.frame_state = FrameState.FRAME_CLEARED + return super().RETURN_VALUE(inst) + + def RETURN_CONST(self, inst: Instruction) -> None: + self.frame_state = FrameState.FRAME_CLEARED + return super().RETURN_CONST(inst) + + def YIELD_FROM(self, inst: Instruction) -> None: + # https://github.com/python/cpython/blob/1790e584142b5db070b74bc64777ad14e26608c2/Python/ceval.c#L2581 + if not sys.version_info[:2] == (3, 10): + raise AssertionError("Python 3.10 specific") + + if not (len(self.stack) >= 2): + raise AssertionError("expected len(self.stack) >= 2 to be true") + val = self.pop() + receiver = self.stack[-1] + + gen_status = None + try: + result = pyiter_send(self, receiver, val) + except exc.ObservedUserStopIteration: + gen_status = PySendResult.PYGEN_RETURN + raised = self.exn_vt_stack.get_raised_exception() + result = pygen_fetch_stopiteration_value(raised) + exc.handle_observed_exception(self) + except exc.ObservedException: + # PYGEN_ERROR + gen_status = PySendResult.PYGEN_ERROR + raise + else: + # PYGEN_NEXT + gen_status = PySendResult.PYGEN_NEXT + + if gen_status == PySendResult.PYGEN_RETURN: + self.pop() + self.push(result) + else: + # gen_status == PYGEN_NEXT + # Repeat the YIELD_FROM instruction in the next eval loop + if isinstance(self.instruction_pointer, int): + if not (self.instruction_pointer > 0): + raise AssertionError( + "expected self.instruction_pointer > 0 to be true" + ) + self.instruction_pointer -= 1 + else: + raise AssertionError( + "expected isinstance(self.instruction_pointer, int) to be true" + ) + self.push(result) + # Add the value to yield into generated_items and replace the top of the stack with None + self.YIELD_VALUE(inst) + + def SEND(self, inst: Instruction) -> None: + if not (len(self.stack) >= 2): + raise AssertionError("expected len(self.stack) >= 2 to be true") + + val = self.pop() + if sys.version_info >= (3, 15): + receiver = self.stack[-2] + else: + receiver = self.stack[-1] + + try: + val = pyiter_send(self, receiver, val) + except exc.ObservedUserStopIteration: + # To implement SEND, we have to look at the implementation + # when the iterator returns StopIteration. This translates to this code + # 3.11: https://github.com/python/cpython/blob/3.11/Python/ceval.c#L2613-L2619 + # 3.12: https://github.com/python/cpython/blob/3.12/Python/bytecodes.c#L863-L866 + # The implementation is different in 3.11 and 3.12. In 3.12, we rely + # on END_SEND to clean up. In 3.11, SEND does the cleanup as well. + ex = self.exn_vt_stack.get_raised_exception() + val = pygen_fetch_stopiteration_value(ex) + self.exn_vt_stack.clear_current_exception() + if sys.version_info < (3, 12): + self.pop() # Python 3.12 uses new opcode END_SEND + self.push(val) + self.jump(inst) + else: + self.push(val) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/tensor_version_op.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/tensor_version_op.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9bc8cf9b2a267046e91dd2923faf6174a1018e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/tensor_version_op.py @@ -0,0 +1,71 @@ +"""This module implements tensor version operations for Dynamo tracing. + +It provides primitives for handling tensor versioning during tracing, particularly in the +context of functionalization where version operations are handled eagerly on fake tensors. + +When we functionalize _tensor_version + _unsafe_set_version_counter, the ops disappear from +the traced graph. We run them eagerly on the fake tensors used for tracing, in order to get +past asserts that would fail in autograd. + +Why is this ok? +1) Versions on functional tensors do not make any sense since you cannot mutate a functional + tensor. +2) The whole point of version munging is to trick autograd into doing what we want, and after + AotAutograd there is no longer any need for these ops. + +Note this is similar to how no_grad is handled. +""" + +from contextlib import AbstractContextManager +from typing import Any + +import torch +from torch import SymInt +from torch._prims import _make_prim, RETURN_TYPE +from torch._subclasses import FakeTensorMode +from torch._subclasses.functional_tensor import FunctionalTensorMode + + +_tensor_version = _make_prim( + schema="_tensor_version(Tensor self) -> SymInt", + return_type=RETURN_TYPE.NEW, + meta=torch.ops.aten._version.default, + impl_aten=torch.ops.aten._version.default, + doc="Traceable unbacked SymInt version of torch.Tensor._version", +) + + +@_tensor_version.py_impl(FakeTensorMode) # type: ignore[misc] +def _tensor_version_fake(fake_mode: FakeTensorMode, self_tensor: Any) -> SymInt: + """ + The initial dynamo capture of _tensor_version + _unsafe_set_version_counter turns the + `._version` into an unbacked SymInt so that we don't need to specialize on the `._version` + of input tensors to the graph. + """ + if fake_mode.shape_env is None: + raise AssertionError("fake_mode.shape_env must not be None") + return fake_mode.shape_env.create_unbacked_symint() + + +_unsafe_set_version_counter = _make_prim( + schema="_unsafe_set_version_counter(Tensor[] tensors, SymInt[] versions) -> ()", + return_type=RETURN_TYPE.NEW, + meta=lambda self, version: None, + impl_aten=torch._C._autograd._unsafe_set_version_counter, + doc="Traceable+SymInt version of torch._C._autograd._unsafe_set_version_counter", +) +torch.fx.node.has_side_effect(_unsafe_set_version_counter) + + +@_tensor_version.py_impl(FunctionalTensorMode) # type: ignore[misc] +def _tensor_version_functional(mode: FunctionalTensorMode, self: Any) -> int: + return self._version + + +@_unsafe_set_version_counter.py_impl(FunctionalTensorMode) # type: ignore[misc] +def _unsafe_set_version_counter_functional( + ctx: AbstractContextManager[Any], + tensors: tuple[torch.Tensor, ...], + versions: tuple[int, ...], +) -> None: + torch._C._autograd._unsafe_set_version_counter(tensors, versions) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/test_case.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_case.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc7ec8df5a4aa32010f799dab7b4f62c4881bda --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_case.py @@ -0,0 +1,258 @@ +"""Testing utilities for Dynamo, providing a specialized TestCase class and test running functionality. + +This module extends PyTorch's testing framework with Dynamo-specific testing capabilities. +It includes: +- A custom TestCase class that handles Dynamo-specific setup/teardown +- Test running utilities with dependency checking +- Automatic reset of Dynamo state between tests +- Proper handling of gradient mode state +""" + +import contextlib +import importlib +import inspect +import logging +import os +import re +import sys +import unittest +from collections.abc import Callable +from typing import Any + +import torch +import torch.testing +from torch._dynamo import polyfills +from torch._logging._internal import trace_log +from torch.testing._internal.common_utils import ( # type: ignore[attr-defined] + IS_WINDOWS, + TEST_WITH_CROSSREF, + TEST_WITH_TORCHDYNAMO, + TestCase as TorchTestCase, +) + +from . import config, utils + + +log = logging.getLogger(__name__) + + +def run_tests(needs: str | tuple[str, ...] = ()) -> None: + from torch.testing._internal.common_utils import run_tests + + if TEST_WITH_TORCHDYNAMO or TEST_WITH_CROSSREF: + return # skip testing + + if ( + not torch.xpu.is_available() + and IS_WINDOWS + and os.environ.get("TORCHINDUCTOR_WINDOWS_TESTS", "0") == "0" + ): + return + + if isinstance(needs, str): + needs = (needs,) + for need in needs: + if need == "cuda": + if not torch.cuda.is_available(): + return + else: + try: + importlib.import_module(need) + except ImportError: + return + + run_tests() + + +class TestCase(TorchTestCase): + _exit_stack: contextlib.ExitStack + + @classmethod + def tearDownClass(cls) -> None: + cls._exit_stack.close() + super().tearDownClass() + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + cls._exit_stack = contextlib.ExitStack() # type: ignore[attr-defined] + cls._exit_stack.enter_context( # type: ignore[attr-defined] + config.patch( + raise_on_ctx_manager_usage=True, + suppress_errors=False, + log_compilation_metrics=False, + canonicalize_output_graph_node_order=True, + ), + ) + + def setUp(self) -> None: + self._prior_is_grad_enabled = torch.is_grad_enabled() + self._prior_nested_graph_breaks = config.nested_graph_breaks + config.nested_graph_breaks = True + super().setUp() + utils.counters.clear() + self.handler = logging.NullHandler() + trace_log.addHandler(self.handler) + + def tearDown(self) -> None: + trace_log.removeHandler(self.handler) + for k, v in utils.counters.items(): + log.debug("%s %s", k, v.most_common()) + utils.counters.clear() + torch._C._autograd._saved_tensors_hooks_enable() + super().tearDown() + if self._prior_is_grad_enabled is not torch.is_grad_enabled(): + log.warning("Running test changed grad mode") + torch.set_grad_enabled(self._prior_is_grad_enabled) + config.nested_graph_breaks = self._prior_nested_graph_breaks + + def before_cuda_memory_leak_check(self) -> None: + super().before_cuda_memory_leak_check() + utils.counters.clear() + + def assertEqual(self, x: Any, y: Any, *args: Any, **kwargs: Any) -> None: # type: ignore[override] + if config.debug_disable_compile_counter: + if isinstance(x, utils.CompileCounterInt) or isinstance( + y, utils.CompileCounterInt + ): + return + # skip checks like self.assertEqual(len(counters["graph_break"]), 1) + if ( + (cur_frame := inspect.currentframe()) + and (upper_frame := cur_frame.f_back) + and (upper_code := inspect.getframeinfo(upper_frame).code_context) + and "counters" in upper_code[0] + ): + return + return super().assertEqual(x, y, *args, **kwargs) + + def assertExpectedInline(self, *args: Any, **kwargs: Any) -> None: # type: ignore[override] + if config.debug_disable_compile_counter: + return + kwargs["skip"] = kwargs.get("skip", 0) + 1 + return super().assertExpectedInline(*args, **kwargs) + + +class CPythonTestCase(TestCase): + """ + Test class for CPython tests located in "test/cpython/v{Py_version}/*". + + This class enables specific features that are disabled by default, such as + tracing through unittest methods. + """ + + _stack: contextlib.ExitStack + dynamo_strict_nopython = True + + # Restore original unittest methods to simplify tracing CPython test cases. + assertEqual = unittest.TestCase.assertEqual # type: ignore[assignment] + assertNotEqual = unittest.TestCase.assertNotEqual # type: ignore[assignment] + assertTrue = unittest.TestCase.assertTrue + assertFalse = unittest.TestCase.assertFalse + assertIs = unittest.TestCase.assertIs + assertIsNot = unittest.TestCase.assertIsNot + assertIsNone = unittest.TestCase.assertIsNone + assertIsNotNone = unittest.TestCase.assertIsNotNone + assertIn = unittest.TestCase.assertIn + assertNotIn = unittest.TestCase.assertNotIn + assertIsInstance = unittest.TestCase.assertIsInstance + assertNotIsInstance = unittest.TestCase.assertNotIsInstance + assertAlmostEqual = unittest.TestCase.assertAlmostEqual + assertNotAlmostEqual = unittest.TestCase.assertNotAlmostEqual + assertGreater = unittest.TestCase.assertGreater + assertGreaterEqual = unittest.TestCase.assertGreaterEqual + assertLess = unittest.TestCase.assertLess + assertLessEqual = unittest.TestCase.assertLessEqual + assertRegex = unittest.TestCase.assertRegex + assertNotRegex = unittest.TestCase.assertNotRegex + assertCountEqual = unittest.TestCase.assertCountEqual + assertMultiLineEqual = polyfills.assert_multi_line_equal + assertSequenceEqual = polyfills.assert_sequence_equal + assertListEqual = unittest.TestCase.assertListEqual + assertTupleEqual = unittest.TestCase.assertTupleEqual + assertSetEqual = unittest.TestCase.assertSetEqual + # pyrefly: ignore [bad-override] + assertDictEqual = polyfills.assert_dict_equal + # pyrefly: ignore [bad-override] + assertRaises = unittest.TestCase.assertRaises + # pyrefly: ignore [bad-override] + assertRaisesRegex = unittest.TestCase.assertRaisesRegex + assertWarns = unittest.TestCase.assertWarns + assertWarnsRegex = unittest.TestCase.assertWarnsRegex + assertLogs = unittest.TestCase.assertLogs + fail = unittest.TestCase.fail + failureException = unittest.TestCase.failureException + + def compile_fn( + self, + fn: Callable[..., Any], + backend: str | Callable[..., Any], + nopython: bool, + ) -> Callable[..., Any]: + # We want to compile only the test function, excluding any setup code + # from unittest + + method = getattr(self, self._testMethodName) + method = torch._dynamo.optimize(backend, error_on_graph_break=nopython)(method) + + setattr(self, self._testMethodName, method) + return fn + + def _dynamo_test_key(self) -> str: + suffix = super()._dynamo_test_key() + test_cls = self.__class__ + test_file = inspect.getfile(test_cls).split(os.sep)[-1].split(".")[0] + py_ver = re.search(r"/v([\d_]+)/", inspect.getfile(test_cls)) + if py_ver: + py_ver = py_ver.group().strip(os.sep).replace("_", "").lstrip("v") # type: ignore[assignment] + else: + return suffix + return f"CPython{py_ver}-{test_file}-{suffix}" + + @classmethod + def tearDownClass(cls) -> None: + cls._stack.close() + super().tearDownClass() + + @classmethod + def setUpClass(cls) -> None: + # Skip test if python versions doesn't match + search_path = inspect.getfile(cls) + + cpython_test_regex = ( + re.escape(os.path.join("cpython") + os.path.sep) + r"v(\d)_(\d{2})" + ) + + m = re.search(cpython_test_regex, search_path) + if m: + test_py_ver = tuple(map(int, m.groups())) + py_ver = sys.version_info[:2] + if py_ver != test_py_ver: + expected = ".".join(map(str, test_py_ver)) + got = ".".join(map(str, py_ver)) + raise unittest.SkipTest( + f"Test requires Python {expected} but got Python {got}" + ) + else: + raise unittest.SkipTest( + f"Test requires a specific Python version but not found in path {inspect.getfile(cls)}" + ) + + super().setUpClass() + cls._stack = contextlib.ExitStack() # type: ignore[attr-defined] + cls._stack.enter_context( # type: ignore[attr-defined] + config.patch( + enable_trace_unittest=True, + enable_trace_load_build_class=True, + ), + ) + + @contextlib.contextmanager + def subTest(self, *args, **kwargs): + # pytest 9.x addSubTest uses typing._GenericAlias calls that + # Dynamo cannot trace. Use a no-op subTest instead. + yield + + # pyrefly: ignore [implicit-any] + def wrap_with_policy(self, method_name: str, policy: Callable) -> None: + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/test_dont_skip_tracing_functions.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_dont_skip_tracing_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..1edce5ff857fb2c0e35f4ac5debc42291a9d073e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_dont_skip_tracing_functions.py @@ -0,0 +1,40 @@ +""" +Functions used to test torch._dynamo.dont_skip_tracing. +This file is located in torch/_dynamo so that it is skipped by trace rules. +There is a special rule in trace_rules that doesn't skip this file when +dont_skip_tracing is active. +""" + +import torch + + +def f1(x: torch.Tensor) -> torch.Tensor: + return x + 1 + + +def f2(x: torch.Tensor) -> torch.Tensor: + return x + 1 + + +def f3(x: torch.Tensor) -> torch.Tensor: + return f2(x) + + +def f4(x: torch.Tensor) -> torch.Tensor: + x = f5(x, 1) + x = torch._dynamo.dont_skip_tracing(f6)(x) + x = f5(x, 8) + return x + + +def f5(x: torch.Tensor, n: int) -> torch.Tensor: + if torch.compiler.is_compiling(): + return x + n + return x + + +def f6(x: torch.Tensor) -> torch.Tensor: + x = f5(x, 2) + torch._dynamo.graph_break() + x = f5(x, 4) + return x diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/test_minifier_common.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_minifier_common.py new file mode 100644 index 0000000000000000000000000000000000000000..a61daba11d36fa8566b9f5640cf27b425daf3039 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_minifier_common.py @@ -0,0 +1,336 @@ +"""Common utilities for testing Dynamo's minifier functionality. + +This module provides the base infrastructure for running minification tests in Dynamo. +It includes: +- MinifierTestResult: A dataclass for storing and processing minifier test results +- MinifierTestBase: A base test class with utilities for: + - Running tests in isolated environments + - Managing temporary directories and configurations + - Executing minifier launcher scripts + - Running and validating reproduction scripts + - Supporting both compile-time and runtime error testing + +The minifier helps reduce failing Dynamo compilations to minimal reproductions. +""" + +import dataclasses +import io +import logging +import os +import re +import shutil +import subprocess +import sys +import tempfile +import traceback +from collections.abc import Sequence +from typing import Any +from unittest.mock import patch + +import torch +import torch._dynamo +import torch._dynamo.test_case +from torch._dynamo.trace_rules import _as_posix_path +from torch.utils._traceback import report_compile_source_on_error + + +def _decode_subprocess_output(output: bytes) -> str: + return output.decode("utf-8", errors="replace") + + +@dataclasses.dataclass +class MinifierTestResult: + minifier_code: str + repro_code: str + + def _get_module(self, t: str) -> str: + match = re.search(r"class Repro\(torch\.nn\.Module\):\s+([ ].*\n| *\n)+", t) + if match is None: + raise AssertionError("failed to find module") + r = match.group(0) + r = re.sub(r"\s+$", "\n", r, flags=re.MULTILINE) + r = re.sub(r"\n{3,}", "\n\n", r) + return r.strip() + + def get_exported_program_path(self) -> str | None: + # Extract the exported program file path from AOTI minifier's repro.py + # Regular expression pattern to match the file path + pattern = r'torch\.export\.load\(\s*["\'](.*?)["\']\s*\)' + # Search for the pattern in the text + match = re.search(pattern, self.repro_code) + # Extract and print the file path if a match is found + if match: + file_path = match.group(1) + return file_path + return None + + def minifier_module(self) -> str: + return self._get_module(self.minifier_code) + + def repro_module(self) -> str: + return self._get_module(self.repro_code) + + +class MinifierTestBase(torch._dynamo.test_case.TestCase): + DEBUG_DIR = tempfile.mkdtemp() + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + if not os.path.exists(cls.DEBUG_DIR): + cls.DEBUG_DIR = tempfile.mkdtemp() + cls._exit_stack.enter_context( # type: ignore[attr-defined] + torch._dynamo.config.patch(debug_dir_root=cls.DEBUG_DIR) + ) + # These configurations make new process startup slower. Disable them + # for the minification tests to speed them up. + cls._exit_stack.enter_context( # type: ignore[attr-defined] + torch._inductor.config.patch( + { + # https://github.com/pytorch/pytorch/issues/100376 + "pattern_matcher": False, + # multiprocess compilation takes a long time to warmup + "compile_threads": 1, + # https://github.com/pytorch/pytorch/issues/100378 + "cpp.vec_isa_ok": False, + } + ) + ) + + @classmethod + def tearDownClass(cls) -> None: + if os.getenv("PYTORCH_KEEP_TMPDIR", "0") != "1": + shutil.rmtree(cls.DEBUG_DIR) + else: + print(f"test_minifier_common tmpdir kept at: {cls.DEBUG_DIR}") + cls._exit_stack.close() # type: ignore[attr-defined] + + def _gen_codegen_fn_patch_code(self, device: str, bug_type: str) -> str: + if bug_type not in ("compile_error", "runtime_error", "accuracy"): + raise AssertionError( + f"bug_type must be one of compile_error, runtime_error, accuracy, got {bug_type!r}" + ) + return f"""\ +{torch._dynamo.config.codegen_config()} +{torch._inductor.config.codegen_config()} +torch._inductor.config.{"cpp" if device == "cpu" else "triton"}.inject_relu_bug_TESTING_ONLY = {bug_type!r} +""" + + def _maybe_subprocess_run( + self, args: Sequence[Any], *, isolate: bool, cwd: str | None = None + ) -> subprocess.CompletedProcess[bytes]: + from torch._inductor.cpp_builder import normalize_path_separator + + if not isolate: + if len(args) < 2: + raise AssertionError(f"expected at least 2 args, got {args}") + if args[0] != "python3": + raise AssertionError(f"expected args[0] to be 'python3', got {args}") + if args[1] == "-c": + if len(args) != 3: + raise AssertionError( + f"expected exactly 3 args for -c mode, got {args}" + ) + code = args[2] + args = ["-c"] + else: + if len(args) < 2: + raise AssertionError(f"expected at least 2 args, got {args}") + with open(args[1]) as f: + # Need normalize path of the code. + code = normalize_path_separator(f.read()) + args = args[1:] + + # WARNING: This is not a perfect simulation of running + # the program out of tree. We only interpose on things we KNOW we + # need to handle for tests. If you need more stuff, you will + # need to augment this appropriately. + + # NB: Can't use save_config because that will omit some fields, + # but we must save and reset ALL fields + dynamo_config = torch._dynamo.config.get_config_copy() + inductor_config = torch._inductor.config.get_config_copy() + try: + stderr = io.StringIO() + log_handler = logging.StreamHandler(stderr) + log = logging.getLogger("torch._dynamo") + log.addHandler(log_handler) + try: + prev_cwd = _as_posix_path(os.getcwd()) + if cwd is not None: + cwd = _as_posix_path(cwd) + os.chdir(cwd) + with patch("sys.argv", args), report_compile_source_on_error(): + exec(code, {"__name__": "__main__", "__compile_source__": code}) + rc = 0 + except Exception: + rc = 1 + traceback.print_exc(file=stderr) + finally: + log.removeHandler(log_handler) + if cwd is not None: + os.chdir(prev_cwd) # type: ignore[possibly-undefined] + # Make sure we don't leave buggy compiled frames lying + # around + torch._dynamo.reset() + finally: + torch._dynamo.config.load_config(dynamo_config) + torch._inductor.config.load_config(inductor_config) + + # TODO: return a more appropriate data structure here + return subprocess.CompletedProcess( + args, + rc, + b"", + stderr.getvalue().encode("utf-8"), + ) + else: + if cwd is not None: + cwd = _as_posix_path(cwd) + return subprocess.run(args, capture_output=True, cwd=cwd, check=False) + + # Run `code` in a separate python process. + # Returns the completed process state and the directory containing the + # minifier launcher script, if `code` outputted it. + def _run_test_code( + self, code: str, *, isolate: bool + ) -> tuple[subprocess.CompletedProcess[bytes], str | Any]: + proc = self._maybe_subprocess_run( + ["python3", "-c", code], isolate=isolate, cwd=self.DEBUG_DIR + ) + + print("test stdout:", _decode_subprocess_output(proc.stdout)) + stderr = _decode_subprocess_output(proc.stderr) + print("test stderr:", stderr) + repro_dir_match = re.search(r"(\S+)minifier_launcher.py", stderr) + if repro_dir_match is not None: + return proc, repro_dir_match.group(1) + return proc, None + + # Runs the minifier launcher script in `repro_dir` + def _run_minifier_launcher( + self, + repro_dir: str, + isolate: bool, + *, + minifier_args: Sequence[Any] = (), + repro_after: str | None = None, + ) -> tuple[subprocess.CompletedProcess[bytes], str]: + self.assertIsNotNone(repro_dir) + launch_file = _as_posix_path(os.path.join(repro_dir, "minifier_launcher.py")) + with open(launch_file) as f: + launch_code = f.read() + + self.assertTrue(os.path.exists(launch_file)) + + args = ["python3", launch_file, "minify", *minifier_args] + if not isolate and repro_after != "aot_inductor": + # AOTI minifier doesn't have --no-isolate flag. + # Everything in AOTI minifier is in no-isolate mode. + args.append("--no-isolate") + launch_proc = self._maybe_subprocess_run(args, isolate=isolate, cwd=repro_dir) + print("minifier stdout:", _decode_subprocess_output(launch_proc.stdout)) + stderr = _decode_subprocess_output(launch_proc.stderr) + print("minifier stderr:", stderr) + + self.assertNotIn("Input graph did not fail the tester", stderr) + + return launch_proc, launch_code + + # Runs the repro script in `repro_dir` + def _run_repro( + self, repro_dir: str, *, isolate: bool = True + ) -> tuple[subprocess.CompletedProcess[bytes], str]: + self.assertIsNotNone(repro_dir) + repro_file = _as_posix_path(os.path.join(repro_dir, "repro.py")) + with open(repro_file) as f: + repro_code = f.read() + + self.assertTrue(os.path.exists(repro_file)) + + repro_proc = self._maybe_subprocess_run( + ["python3", repro_file], isolate=isolate, cwd=repro_dir + ) + print("repro stdout:", _decode_subprocess_output(repro_proc.stdout)) + print("repro stderr:", _decode_subprocess_output(repro_proc.stderr)) + return repro_proc, repro_code + + # Template for testing code. + # `run_code` is the code to run for the test case. + # `patch_code` is the code to be patched in every generated file; usually + # just use this to turn on bugs via the config + def _gen_test_code(self, run_code: str, repro_after: str, repro_level: int) -> str: + repro_after_line = "" + if repro_after == "aot_inductor": + repro_after_line = ( + "torch._inductor.config.aot_inductor.dump_aoti_minifier = True" + ) + elif repro_after: + repro_after_line = f"""\ +torch._dynamo.config.repro_after = "{repro_after}" + """ + return f"""\ +import torch +import torch._dynamo +import torch._inductor +{_as_posix_path(torch._dynamo.config.codegen_config())} +{_as_posix_path(torch._inductor.config.codegen_config())} +{repro_after_line} +torch._dynamo.config.repro_level = {repro_level} +torch._inductor.config.aot_inductor.repro_level = {repro_level} +torch._dynamo.config.debug_dir_root = "{_as_posix_path(self.DEBUG_DIR)}" +{run_code} +""" + + # Runs a full minifier test. + # Minifier tests generally consist of 3 stages: + # 1. Run the problematic code + # 2. Run the generated minifier launcher script + # 3. Run the generated repro script + # + # If possible, you should run the test with isolate=False; use + # isolate=True only if the bug you're testing would otherwise + # crash the process + def _run_full_test( + self, + run_code: str, + repro_after: str, + expected_error: str | None, + *, + isolate: bool, + minifier_args: Sequence[Any] = (), + ) -> MinifierTestResult | None: + if isolate: + repro_level = 3 + elif expected_error is None or expected_error == "AccuracyError": + repro_level = 4 + else: + repro_level = 2 + test_code = self._gen_test_code(run_code, repro_after, repro_level) + print("running test", file=sys.stderr) + test_proc, repro_dir = self._run_test_code(test_code, isolate=isolate) + if expected_error is None: + # Just check that there was no error + self.assertEqual(test_proc.returncode, 0) + + self.assertIsNone(repro_dir) + return None + # NB: Intentionally do not test return code; we only care about + # actually generating the repro, we don't have to crash + + self.assertIn(expected_error, _decode_subprocess_output(test_proc.stderr)) + + self.assertIsNotNone(repro_dir) + print("running minifier", file=sys.stderr) + _minifier_proc, minifier_code = self._run_minifier_launcher( + repro_dir, + isolate=isolate, + minifier_args=minifier_args, + repro_after=repro_after, + ) + print("running repro", file=sys.stderr) + repro_proc, repro_code = self._run_repro(repro_dir, isolate=isolate) + + self.assertIn(expected_error, _decode_subprocess_output(repro_proc.stderr)) + self.assertNotEqual(repro_proc.returncode, 0) + return MinifierTestResult(minifier_code=minifier_code, repro_code=repro_code) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/testing.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..a69303583afc14f5e55370d1b528f9662863c6f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/testing.py @@ -0,0 +1,613 @@ +"""Testing utilities and infrastructure for Dynamo. + +This module provides a comprehensive set of testing utilities including: +- Test result collection and validation +- Graph manipulation and comparison tools +- Test case management and execution helpers +- Specialized test decorators for different Python versions and features +- RNG state management +- Compilation counting and monitoring +- Debug utilities for bytecode transformation + +The utilities in this module are used across Dynamo's test suite to ensure +consistent testing patterns and proper test isolation. +""" + +import contextlib +import dis +import functools +import logging +import os.path +import random +import re +import sys +import types +import unittest +from collections.abc import Callable, Generator, Sequence +from typing import Any, overload, TypeVar +from typing_extensions import ParamSpec +from unittest.mock import patch + +import torch +from torch import fx +from torch._dynamo.backends.debugging import aot_eager +from torch._dynamo.output_graph import OutputGraph + +from . import config, eval_frame, optimize_assert, reset +from .bytecode_transformation import ( + create_instruction, + debug_checks, + is_generator, + transform_code_object, +) +from .guards import CheckFunctionManager, CompileId, GuardedCode +from .types import ConvertFrameReturn, DynamoFrameType, wrap_guarded_code +from .utils import CompileCounterInt, same + + +np: types.ModuleType | None = None +try: + import numpy as np +except ModuleNotFoundError: + np = None + + +unsupported = eval_frame.unsupported +three = 3 + +log = logging.getLogger(__name__) + +_P = ParamSpec("_P") + + +def clone_me(x: torch.Tensor | None) -> torch.Tensor | None: + if x is None: + return None + return x.detach().clone().requires_grad_(x.requires_grad) + + +def remove_optimized_module_prefix(name: str) -> str: + return re.sub(r"^_orig_mod[.]", "", name) + + +def extract_graph_and_tracker(fn, *args, **kwargs): # type: ignore[no-untyped-def] + from torch._dynamo.symbolic_convert import InstructionTranslator + + gm = None + region_tracker = None + + def extract_graph_backend(_gm, *args, **kwargs): # type: ignore[no-untyped-def] + nonlocal gm + nonlocal region_tracker + gm = _gm + region_tracker = InstructionTranslator.current_tx().output.region_tracker + return _gm + + torch.compile(backend=extract_graph_backend, fullgraph=True)(fn)(*args, **kwargs) + return gm.graph, region_tracker # type: ignore[union-attr] + + +def extract_graph(fn, *args, **kwargs): # type: ignore[no-untyped-def] + backend = AotEagerAndRecordGraphs() + result = torch.compile(backend=backend)(fn)(*args, **kwargs) + return result, backend.graphs, backend.fw_graphs, backend.bw_graphs + + +def collect_results( + model: torch.nn.Module, prediction: Any, loss: Any, example_inputs: Any +) -> list[Any]: + results = [] + results.append(prediction) + results.append(loss) + # if isinstance(loss, torch.Tensor) and loss.item() > 1: + # log.warning( + # f"High loss value alert - {loss:.2f}. Can result in unstable gradients." + # ) + + grads = {} + params = {} + for name, param in model.named_parameters(): + if isinstance(model, eval_frame.OptimizedModule): + name = remove_optimized_module_prefix(name) + param_copy = param + grad = param.grad + # Treat None and zero grad as same + if param.grad is None: + grad = torch.zeros_like(param) + grads[name + ".grad"] = grad + params[name] = param_copy + results.append(grads) + results.append(params) + buffers = {} + for name, buffer in model.named_buffers(): + if isinstance(model, eval_frame.OptimizedModule): + name = remove_optimized_module_prefix(name) + buffers[name] = buffer + results.append(buffers) + for example in example_inputs: + if isinstance(example, (tuple, list)): + results.extend(inp.grad for inp in example if isinstance(inp, torch.Tensor)) + else: + if isinstance(example, torch.Tensor): + results.append(example.grad) + return results + + +def requires_bwd_pass(out: Any) -> bool: + if isinstance(out, torch.Tensor): + return out.requires_grad + elif isinstance(out, (list, tuple)): + return any(requires_bwd_pass(x) for x in out) + elif out is None: + return False + elif isinstance(out, int): + return False + raise NotImplementedError("Don't know how to reduce", type(out)) + + +@overload +def reduce_to_scalar_loss(out: torch.Tensor) -> torch.Tensor: ... + + +@overload +def reduce_to_scalar_loss( + out: list[Any] | tuple[Any, ...] | dict[Any, Any], +) -> float: ... + + +def reduce_to_scalar_loss(out: Any) -> torch.Tensor | float: + """Reduce the output of a model to get scalar loss""" + if isinstance(out, torch.Tensor): + # Mean does not work on integer tensors + return out.sum() / out.numel() + elif isinstance(out, (list, tuple)): + return sum(reduce_to_scalar_loss(x) for x in out) / len(out) + elif type(out).__name__ in ( + "MaskedLMOutput", + "Seq2SeqLMOutput", + "CausalLMOutputWithCrossAttentions", + ): + return reduce_to_scalar_loss(out.logits) + elif type(out).__name__ == "SquashedNormal": + return out.mean.sum() + elif isinstance(out, dict): + return sum(reduce_to_scalar_loss(value) for value in out.values()) / len( + out.keys() + ) + raise NotImplementedError("Don't know how to reduce", type(out)) + + +def debug_dir() -> str: + path = os.path.join(os.path.dirname(__file__), "../debug") + if not os.path.exists(path): + os.mkdir(path) + return path + + +def debug_dump(name: str, code: types.CodeType, extra: str = "") -> None: + with open(os.path.join(debug_dir(), name), "w") as fd: + fd.write( + f"{dis.Bytecode(code).info()}\n\n{dis.Bytecode(code).dis()}\n\n{extra}\n" + ) + + +def debug_insert_nops( + frame: DynamoFrameType, cache_size: int, hooks: Any, _: Any, *, skip: int = 0 +) -> ConvertFrameReturn: + """used to debug jump updates""" + + def insert_nops(instructions: list[Any], code_options: Any) -> None: + instructions.insert(0, create_instruction("NOP")) + instructions.insert(0, create_instruction("NOP")) + + metrics_context = torch._dynamo.utils.get_metrics_context() + with torch._dynamo.utils.dynamo_timed("debug_insert_nops"), metrics_context: + if is_generator(frame.f_code): + return ConvertFrameReturn() + + debug_checks(frame.f_code) + code, _ = transform_code_object(frame.f_code, insert_nops) + graph = OutputGraph( + # The nop-insertion path does not inspect code object attributes. + code_options={}, # type: ignore[arg-type] + compiler_fn=None, + root_tx=None, # type: ignore[arg-type] + export=False, + export_constraints=[], + frame_state={"_id": 0}, + # TODO: shouldn't this be f_locals/f_globals from frame? + local_scope=locals(), + global_scope=globals(), + f_code=frame.f_code, + torch_function_mode_stack=[], + package=None, + ) + + return wrap_guarded_code( + GuardedCode( + code, + CheckFunctionManager(frame.f_code, graph).guard_manager, # type: ignore[arg-type] + CompileId(frame_id=0, frame_compile_id=0), + ) + ) + + +class CompileCounter: + def __init__(self) -> None: + self.frame_count: int | CompileCounterInt = 0 + self.clear() + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + self.frame_count += 1 + for node in gm.graph.nodes: + if "call" in node.op: + self.op_count += 1 + return gm.forward + + def clear(self) -> None: + if config.debug_disable_compile_counter: + self.frame_count = CompileCounterInt(0) + else: + self.frame_count = 0 + self.op_count = 0 + + +class CompileCounterWithBackend: + def __init__(self, backend: str) -> None: + self.frame_count: int | CompileCounterInt = 0 + self.backend = backend + self.graphs: list[torch.fx.GraphModule] = [] + self.clear() + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + from .backends.registry import lookup_backend + + self.frame_count += 1 + for node in gm.graph.nodes: + if "call" in node.op: + self.op_count += 1 + self.graphs.append(gm) + return lookup_backend(self.backend)(gm, example_inputs) + + def clear(self) -> None: + if config.debug_disable_compile_counter: + self.frame_count = CompileCounterInt(0) + else: + self.frame_count = 0 + self.op_count = 0 + self.graphs = [] + + +# Equivalent to backend="eager", but also records graphs that +# we can assert on +class EagerAndRecordGraphs: + def __init__(self) -> None: + self.graphs: list[torch.fx.GraphModule] = [] + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + self.graphs.append(gm) + return gm.forward + + +class AotEagerAndRecordGraphs: + def __init__(self) -> None: + self.graphs: list[torch.fx.GraphModule] = [] + self.fw_graphs: list[torch.fx.GraphModule] = [] + self.bw_graphs: list[torch.fx.GraphModule] = [] + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + self.graphs.append(gm) + + def fw_compiler( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + self.fw_graphs.append(gm) + return gm.forward + + def bw_compiler( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + self.bw_graphs.append(gm) + return gm.forward + + return aot_eager( + gm, + example_inputs, + fw_compiler=fw_compiler, + bw_compiler=bw_compiler, + ) + + +class InductorAndRecordGraphs: + def __init__(self) -> None: + self.graphs: list[torch.fx.GraphModule] = [] + self.inductor_graphs: list[torch.fx.GraphModule] = [] + + def __call__(self, gm, example_inputs): # type: ignore[no-untyped-def] + import torch._inductor.compile_fx as compile_fx_mod + + self.graphs.append(gm) + + old_compile_fx_inner = compile_fx_mod._compile_fx_inner + + def patched(*args, **kwargs): # type: ignore[no-untyped-def] + self.inductor_graphs.append(args[0]) + return old_compile_fx_inner(*args, **kwargs) + + with patch.object(compile_fx_mod, "_compile_fx_inner", new=patched): + return compile_fx_mod.compile_fx(gm, example_inputs) + + +def strip_comment(code: str) -> str: + return re.sub(r"(?m)^ *#.*\n?", "", code) + + +def remove_trailing_space(code: str) -> str: + return "\n".join([line.rstrip() for line in code.split("\n")]) + + +def _squash_blank_lines(code: str) -> str: + lines = code.split("\n") + result: list[str] = [] + saw_blank = False + for line in lines: + if line.strip() == "": + if saw_blank: + continue + saw_blank = True + else: + saw_blank = False + result.append(line) + return "\n".join(result) + + +def normalize_gm(gm_str: str) -> str: + # strip comments as comments have path to files which may differ from + # system to system. + stripped = strip_comment(gm_str) + no_trailing = remove_trailing_space(stripped) + return _squash_blank_lines(no_trailing) + + +def empty_line_normalizer(code: str) -> str: + """ + Normalize code: remove empty lines. + """ + normal_code = re.sub(r"[\r\n]+", "\n", code) + return normal_code + + +def standard_test( + self: Any, + fn: Callable[..., Any], + nargs: int, + expected_ops: int | None = None, + expected_ops_dynamic: int | None = None, + expected_frame_count: int = 1, +) -> None: + if not config.assume_static_by_default and expected_ops_dynamic is not None: + expected_ops = expected_ops_dynamic + + actual = CompileCounter() + + args1 = [torch.randn(10, 10) for _ in range(nargs)] + args2 = [torch.randn(10, 10) for _ in range(nargs)] + correct1 = fn(*args1) + correct2 = fn(*args2) + reset() + opt_fn = optimize_assert(actual)(fn) + val1a = opt_fn(*args1) + val2a = opt_fn(*args2) + val1b = opt_fn(*args1) + val2b = opt_fn(*args2) + reset() + self.assertTrue(same(val1a, correct1)) + self.assertTrue(same(val1b, correct1)) + self.assertTrue(same(val2a, correct2)) + self.assertTrue(same(val2b, correct2)) + self.assertEqual(actual.frame_count, expected_frame_count) + if expected_ops is not None: + self.assertEqual(actual.op_count, expected_ops) + + +def dummy_fx_compile( + gm: fx.GraphModule, example_inputs: list[torch.Tensor] +) -> Callable[..., Any]: + return gm.forward + + +def format_speedup( + speedup: float, + pvalue: float, + is_correct: bool = True, + pvalue_threshold: float = 0.1, +) -> str: + if not is_correct: + return "ERROR" + if pvalue > pvalue_threshold: + return f"{speedup:.3f}x SAME" + return f"{speedup:.3f}x p={pvalue:.2f}" + + +def rand_strided( + size: Sequence[int], + stride: Sequence[int], + dtype: torch.dtype = torch.float32, + device: str | torch.device = "cpu", + extra_size: int = 0, +) -> torch.Tensor: + needed_size = extra_size + if all(s > 0 for s in size): + # only need to allocate if all sizes are non-zero + needed_size += ( + sum((shape - 1) * stride for shape, stride in zip(size, stride)) + 1 + ) + if dtype.is_floating_point: + if dtype == torch.float4_e2m1fn_x2: + buffer = torch.randint( + 0, 256, (needed_size,), dtype=torch.uint8, device=device + ).view(torch.float4_e2m1fn_x2) + elif dtype.itemsize == 1: + """ + normal distribution kernel is not implemented for fp8.. + Workaround that by creating a fp16 tensor and then cast. + """ + buffer = torch.randn(needed_size, dtype=torch.float16, device=device).to( + dtype=dtype + ) + else: + buffer = torch.randn(needed_size, dtype=dtype, device=device) + else: + buffer = torch.zeros(size=[needed_size], dtype=dtype, device=device) + return torch.as_strided(buffer, size, stride) + + +_T = TypeVar("_T") + + +def check_dynamic_shape_capture() -> bool: + # This also mirrors config from `test/dynamo/test_dynamic_shapes.py:make_dynamic_cls` + return not config.assume_static_by_default + + +def _make_fn_with_patches(fn: Callable[_P, _T], *patches: Any) -> Callable[_P, _T]: + @functools.wraps(fn) + def _fn(*args: _P.args, **kwargs: _P.kwargs) -> _T: + with contextlib.ExitStack() as stack: + for module, attr, val in patches: + stack.enter_context(patch.object(module, attr, val)) + + return fn(*args, **kwargs) + + return _fn + + +def make_test_cls_with_patches( + cls: type, + cls_prefix: str, + fn_suffix: str, + *patches: Any, + xfail_prop: str | None = None, + decorator: Callable[[Callable[..., Any]], Callable[..., Any]] = lambda x: x, +) -> type: + DummyTestClass = type(f"{cls_prefix}{cls.__name__}", cls.__bases__, {}) + DummyTestClass.__qualname__ = DummyTestClass.__name__ + + for name in dir(cls): + if name.startswith("test_"): + fn = getattr(cls, name) + if not callable(fn): + setattr(DummyTestClass, name, getattr(cls, name)) + continue + new_name = f"{name}{fn_suffix}" + new_fn = _make_fn_with_patches(fn, *patches) + new_fn.__name__ = new_name + if xfail_prop is not None and hasattr(fn, xfail_prop): + new_fn = unittest.expectedFailure(new_fn) + setattr(DummyTestClass, new_name, decorator(new_fn)) + # NB: Doesn't handle slots correctly, but whatever + elif not hasattr(DummyTestClass, name): + setattr(DummyTestClass, name, getattr(cls, name)) + + return DummyTestClass + + +# test Python 3.11+ specific features +def skipIfNotPy311(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if sys.version_info >= (3, 11): + return fn + # pyrefly: ignore [bad-return, bad-argument-type] + return unittest.skip(fn) + + +def skipIfNotPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if sys.version_info >= (3, 12): + return fn + return unittest.skip("Requires Python 3.12+")(fn) + + +def skipIfOnlyNotPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if sys.version_info >= (3, 13) or sys.version_info < (3, 12): + return unittest.skip("Requires Python 3.12")(fn) + return fn + + +def xfailIfPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if sys.version_info >= (3, 12): + return unittest.expectedFailure(fn) + return fn + + +def skipIfPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if sys.version_info >= (3, 12): + return unittest.skip("Not supported in Python 3.12+")(fn) + return fn + + +# Controls tests generated in test/inductor/test_torchinductor_dynamic_shapes.py +# and test/dynamo/test_dynamic_shapes.py +def expectedFailureDynamic(fn: Callable[_P, _T]) -> Callable[_P, _T]: + fn._expected_failure_dynamic = True # type: ignore[attr-defined] + return fn + + +# Controls tests generated in test/inductor/test_torchinductor_codegen_dynamic_shapes.py +def expectedFailureCodegenDynamic(fn: Callable[_P, _T]) -> Callable[_P, _T]: + fn._expected_failure_codegen_dynamic = True # type: ignore[attr-defined] + return fn + + +# Controls test generated in test/inductor/test_cpp_wrapper.py +def expectedFailureDynamicWrapper(fn: Callable[_P, _T]) -> Callable[_P, _T]: + fn._expected_failure_dynamic_wrapper = True # type: ignore[attr-defined] + return fn + + +def reset_rng_state(use_xla: bool = False) -> None: + torch.manual_seed(1337) + random.seed(1337) + if np: + np.random.seed(1337) + if use_xla: + import torch_xla.core.xla_model as xm + + xm.set_rng_state(1337, str(xm.xla_device())) + + +def _skipped_function_for_test_reconstruct( + f: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs +) -> _T: + return f(*args, **kwargs) + + +_testing_invoke_subgraph_inductor_compile_captured_gms = None + + +@contextlib.contextmanager +def _testing_capture_invoke_subgraph_inductor_compile_gms() -> Generator[ + list[torch.fx.GraphModule] +]: + """ + Context manager to capture graph modules compiled by invoke_subgraph_inductor_compile. + + Usage: + with _testing_capture_invoke_subgraph_inductor_compile_gms() as captured_gms: + # code that triggers invoke_subgraph_inductor_compile + pass + # captured_gms will contain the list of captured graph modules + """ + global _testing_invoke_subgraph_inductor_compile_captured_gms + # pyrefly: ignore [implicit-any] + _testing_invoke_subgraph_inductor_compile_captured_gms = [] + try: + yield _testing_invoke_subgraph_inductor_compile_captured_gms + finally: + _testing_invoke_subgraph_inductor_compile_captured_gms = None diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/trace_rules.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/trace_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..b72b316d99512e76306ffecc4e5c7b1c78975da6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/trace_rules.py @@ -0,0 +1,4276 @@ +""" +Tracing rules and policies for TorchDynamo compilation decisions. + +This module defines the rules that govern what code TorchDynamo should trace and compile +versus what should be executed eagerly. It contains functions and classes that determine: + +- Which modules, functions, and objects should be skipped during tracing +- Which parts of the code should cause graph breaks +- How to handle different Python libraries and third-party packages +- Rules for determining when to inline functions vs calling them eagerly + +Key components: +- Skip rules: Functions that return True if an object should be skipped during tracing +- Inlining rules: Policies for when to inline function calls during compilation +- Library-specific handling: Special cases for popular Python packages +- Performance heuristics: Rules that balance compilation overhead vs runtime benefits + +These rules are critical for TorchDynamo's ability to automatically determine +compilation boundaries and optimize PyTorch programs effectively. +""" + +import abc +import builtins +import contextlib +import copy +import dataclasses +import functools +import importlib +import inspect +import linecache +import operator +import os +import random +import re +import sys +import types +import typing +import unittest +from collections import defaultdict +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import torch +import torch._inductor.test_operators +import torch.distributed +import torch.utils._content_store +from torch._environment import is_fbcode +from torch.utils import _config_module + +from . import config +from .resume_execution import TORCH_DYNAMO_RESUME_IN_PREFIX +from .utils import ( + getfile, + hashable, + is_lru_cache_wrapped_function, + NP_SUPPORTED_MODULES, + unwrap_if_wrapper, +) +from .variables import ( + BuiltinVariable, + DictBuiltinVariable, + FunctionalCallVariable, + FunctorchHigherOrderVariable, + GetAttrBuiltinVariable, + HasAttrBuiltinVariable, + InspectSignatureVariable, + IterBuiltinVariable, + ListBuiltinVariable, + LocalGeneratorFunctionVariable, + LocalGeneratorObjectVariable, + NestedUserFunctionVariable, + PolyfilledFunctionVariable, + PyTreeGetNodeTypeFunctionVariable, + PyTreeTreeIsLeafFunctionVariable, + ReparametrizeModuleCallVariable, + SetAttrBuiltinVariable, + SkipFunctionVariable, + SparseTensorCreationSkipVariable, + TorchInGraphFunctionVariable, + UserFunctionVariable, + UserMethodVariable, +) +from .variables.base import VariableTracker + + +np: types.ModuleType | None = None +try: + import numpy as np +except ModuleNotFoundError: + pass + + +""" +A note on skip/inline rules: + +Dynamo consults this file to determine whether function should be inlined or skipped. + +A skip applies at the frame boundary, meaning dynamo either triggers a graph break +at the beginning of the frame or attempts to trace/inline the whole frame. When skipping +a frame, recursively called frames are still traced by dynamo unless also skipped. + +Skipfiles (skipped at the file level instead of function level) still apply on a +frame-by-frame boundary as dynamo traces, but apply to all functions in that file. + +@skip is a helper decorator that can be applied to your function to cause it to be +included here. + +Dynamo skip/inline rules & priorities are defined as follows: +* Inline is the default behavior and will be used unless explicitly skipped. +* Dynamo has two SKIPLIST: BUILTIN_SKIPLIST and THIRDPARTY_SKIPLIST. + * BUILTIN_SKIPLIST contains builtin python modules, such as abc, collections, etc. + * THIRDPARTY_SKIPLIST contains common third party libraries, such as numpy, pandas, etc. +* Functions in these two SKIPLISTs are always skipped, except: + * They have explicitly defined rule in `manual_torch_name_rule_map`; + * The corresponding python module has been put into MOD_INLINELIST. +* PyTorch(torch) is in the BUILTIN_SKIPLIST by default, but there are many cases + where we want inline the functions under torch namespace. + We should specify inline for the functions in `manual_torch_name_rule_map` or + put the corresponding python module into MOD_INLINELIST to make dynamo inline them. +* If you call functions under skipped modules/files, Dynamo will wrap these functions + as SkipFunctionVariable. There are a few functions(e.g, collections.OrderedDict) that + we have special handling at SkipFunctionVariable.call_function. + +Overall: *_INLINELIST has precedence over *_SKIPLIST has precedence over DEFAULT (inline) + +To figure out what the behavior is, check the following list in order: +* `manual_torch_name_rule_map` (Inline if YES) +* MOD_INLINELIST (Inline if YES) +* BUILTIN_SKIPLIST & THIRDPARTY_SKIPLIST (Skip if YES) +* MOD_SKIPLIST (Skip if YES) +* Inline by default + +In general, if you want to force inline a function or module, please consider adding +the function's python module to MOD_INLINELIST first. +Use the `manual_torch_name_rule_map` only when there are other functions under the same module that +you don't want to inline them. +""" + +""" +Map of function objects to their tracing rules (Dynamo variables). +* TorchInGraphFunctionVariable: The functions should be put into the FX graph or can be constant folded. E.g., + - torch.add: should be put into the FX graph. + - torch.is_floating_point: constant folded. +* SkipFunctionVariable: The objects should be skipped from tracing. +* UserFunctionVariable: The functions should be inlined. + +For developers: If you add/remove a torch level API, it may trigger failures from +test/dynamo/test_trace_rules.py:test_torch_name_rule_map_updated. To fix the failures: +If you are adding a new torch level API or Dynamo implementation: +* Add the name with the corresponding tracing rule to this map + if you are adding a new in graph function or Dynamo implementation for an existing function. +* Remove the object name from test/dynamo/test_trace_rules.ignored_c_binding_in_graph_function_names if it's there. + +If you are removing an existing torch level API: +* Remove the entry represented the API from this map or test/dynamo/test_trace_rules.ignored_c_binding_in_graph_function_names + depends on where it is. + + +""" +manual_torch_name_rule_map: dict[ + str, + type[TorchInGraphFunctionVariable] + | type[SkipFunctionVariable] + | type[UserFunctionVariable], +] = { + "torch.onnx.is_in_onnx_export": TorchInGraphFunctionVariable, + "torch.onnx.operators.shape_as_tensor": TorchInGraphFunctionVariable, + "torch.overrides.is_tensor_like": TorchInGraphFunctionVariable, + "torch._C._skip_one_hop_torch_function": TorchInGraphFunctionVariable, + "torch.jit.is_scripting": TorchInGraphFunctionVariable, + "torch.jit.is_tracing": TorchInGraphFunctionVariable, + "torch.jit.annotate": TorchInGraphFunctionVariable, + "torch.distributed.is_available": TorchInGraphFunctionVariable, + "torch.distributed.is_initialized": TorchInGraphFunctionVariable, + "torch.distributed.get_rank": TorchInGraphFunctionVariable, + "torch.distributed.get_world_size": TorchInGraphFunctionVariable, + "torch.distributed.tensor._api.DTensor#from_local": TorchInGraphFunctionVariable, + "torch.distributed.device_mesh.DeviceMesh#__init__": SkipFunctionVariable, + "torch/distributed/device_mesh.py#_create_sub_mesh": SkipFunctionVariable, + "torch.distributed.distributed_c10d._get_group_size_by_name": TorchInGraphFunctionVariable, + "torch.distributed.distributed_c10d._resolve_group_name_by_ranks_and_tag": TorchInGraphFunctionVariable, + "torch.distributed.distributed_c10d._get_group_tag": TorchInGraphFunctionVariable, + "torch.distributed.distributed_c10d.get_process_group_ranks": TorchInGraphFunctionVariable, + "torch.distributed.destroy_process_group": SkipFunctionVariable, + "torch._utils.is_compiling": TorchInGraphFunctionVariable, + "torch._utils._chunk_or_narrow_cat": UserFunctionVariable, + "torch._utils._maybe_view_chunk_cat": UserFunctionVariable, + "torch.fx._symbolic_trace.is_fx_tracing": TorchInGraphFunctionVariable, + "torch.fx._symbolic_trace.is_fx_symbolic_tracing": TorchInGraphFunctionVariable, + "torch.mps.is_available": TorchInGraphFunctionVariable, + "torch.mtia.is_available": TorchInGraphFunctionVariable, + "torch._dynamo.external_utils.is_compiling": TorchInGraphFunctionVariable, + "torch._dynamo.utils._disable_side_effect_safety_checks_for_current_subtracer": UserFunctionVariable, + "torch.compiler.is_compiling": TorchInGraphFunctionVariable, + "torch.compiler.is_dynamo_compiling": TorchInGraphFunctionVariable, + "torch.compiler.is_exporting": TorchInGraphFunctionVariable, + "torch._C._is_cow_tensor": TorchInGraphFunctionVariable, + "torch._dynamo.eval_frame._is_in_optimized_module": TorchInGraphFunctionVariable, + "torch._C._to_dlpack": SkipFunctionVariable, + "torch._C._group_tensors_by_device_and_dtype": TorchInGraphFunctionVariable, + "torch.to_dlpack": SkipFunctionVariable, + "torch._check": TorchInGraphFunctionVariable, + "torch._check_with": TorchInGraphFunctionVariable, + "torch._check_index": TorchInGraphFunctionVariable, + "torch._check_value": TorchInGraphFunctionVariable, + "torch._check_type": TorchInGraphFunctionVariable, + "torch._check_not_implemented": TorchInGraphFunctionVariable, + "torch._check_tensor_all_with": TorchInGraphFunctionVariable, + "torch._check_tensor_all": TorchInGraphFunctionVariable, + "torch._dynamo.decorators.override_optimization_hint": TorchInGraphFunctionVariable, + # We graph break on RNG state setters or getters like + # `torch.get_rng_state`, `torch.set_rng_state`, and + # `torch.Generator.manual_seed`. These functions are not aten + # operations and therefore they are completely ignored by the AOT + # dispatcher. As a result, the AOT graph does not have these setter + # or getter functions, producing an incorrect graph when it comes + # to rng states. + "torch.get_rng_state": SkipFunctionVariable, + "torch.cuda.get_rng_state": SkipFunctionVariable, + "torch.set_rng_state": SkipFunctionVariable, + "torch.cuda.set_rng_state": SkipFunctionVariable, + "torch.cuda.manual_seed": SkipFunctionVariable, + "torch.cuda.manual_seed_all": SkipFunctionVariable, + "torch.xpu.manual_seed": SkipFunctionVariable, + "torch.xpu.manual_seed_all": SkipFunctionVariable, + "torch.cuda.random.manual_seed": SkipFunctionVariable, + "torch.cuda.random.manual_seed_all": SkipFunctionVariable, + "torch.xpu.random.manual_seed": SkipFunctionVariable, + "torch.xpu.random.manual_seed_all": SkipFunctionVariable, + # https://github.com/pytorch/pytorch/issues/107187 + "torch.manual_seed": SkipFunctionVariable, + # https://github.com/pytorch/pytorch/issues/93501 + "torch.nn.utils.rnn.pack_padded_sequence": SkipFunctionVariable, + # https://github.com/pytorch/pytorch/issues/162374 + "torch.nn.utils.rnn.pad_packed_sequence": SkipFunctionVariable, + "torch.nn.Parameter": TorchInGraphFunctionVariable, + "torch.nn.Buffer": TorchInGraphFunctionVariable, + "torch.backends.cuda.SDPAParams": TorchInGraphFunctionVariable, + "torch._nested_tensor_from_mask": SkipFunctionVariable, + "torch.nested._internal.nested_tensor.nested_from_padded": TorchInGraphFunctionVariable, + "torch.nested.nested_tensor_from_jagged": UserFunctionVariable, + "torch.nested.nested_tensor_from_padded": UserFunctionVariable, + # torch.fx map utils + "torch.fx.node.map_aggregate": UserFunctionVariable, + "torch.fx.node.map_arg": UserFunctionVariable, + "torch.fx.immutable_collections._no_mutation": UserFunctionVariable, + "torch.fx.immutable_collections._immutable_list_flatten": UserFunctionVariable, + "torch.fx.immutable_collections._immutable_list_unflatten": UserFunctionVariable, + "torch.fx.immutable_collections._immutable_dict_flatten": UserFunctionVariable, + "torch.fx.immutable_collections._immutable_dict_unflatten": UserFunctionVariable, + # symbol operators implemented in Python + "torch.sym_not": TorchInGraphFunctionVariable, + "torch.sym_float": TorchInGraphFunctionVariable, + "torch.sym_int": TorchInGraphFunctionVariable, + "torch.sym_max": TorchInGraphFunctionVariable, + "torch.sym_min": TorchInGraphFunctionVariable, + "torch.sym_sqrt": TorchInGraphFunctionVariable, + "torch.sym_ite": TorchInGraphFunctionVariable, + "torch.sym_sum": TorchInGraphFunctionVariable, + "torch.sym_fresh_size": UserFunctionVariable, + "torch.Tensor#_make_wrapper_subclass": SkipFunctionVariable, + "torch.Tensor#__init__": SkipFunctionVariable, + "torch.Tensor#split": TorchInGraphFunctionVariable, + "torch.cuda.set_device": SkipFunctionVariable, + "torch.cuda.current_device": TorchInGraphFunctionVariable, + "torch.autograd.grad": TorchInGraphFunctionVariable, + "torch.autograd.grad_mode._enter_inference_mode": TorchInGraphFunctionVariable, + "torch.autograd.grad_mode._exit_inference_mode": TorchInGraphFunctionVariable, + "torch.autograd.backward": SkipFunctionVariable, + "torch.distributions.constraints.is_dependent": SkipFunctionVariable, + "torch.jit.isinstance": SkipFunctionVariable, + "torch._C.set_anomaly_enabled": SkipFunctionVariable, + "torch._C.set_autocast_cpu_dtype": SkipFunctionVariable, + "torch._C.set_autocast_cpu_enabled": SkipFunctionVariable, + "torch._C.set_autocast_gpu_dtype": SkipFunctionVariable, + "torch._C.set_autocast_ipu_dtype": SkipFunctionVariable, + "torch._C.set_autocast_ipu_enabled": SkipFunctionVariable, + "torch._C.set_autocast_xla_dtype": SkipFunctionVariable, + "torch._C.set_autocast_xla_enabled": SkipFunctionVariable, + "torch.resize_as_": SkipFunctionVariable, + "torch._functorch.predispatch._add_batch_dim": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._remove_batch_dim": TorchInGraphFunctionVariable, + "torch.resize_as_sparse_": SkipFunctionVariable, + "torch.get_default_device": TorchInGraphFunctionVariable, + # functorch/vmap + "torch._functorch.vmap._check_int_or_none": UserFunctionVariable, + "torch._functorch.vmap._check_out_dims_is_int_or_int_pytree": UserFunctionVariable, + "torch._functorch.vmap._check_randomness_arg": UserFunctionVariable, + "torch._functorch.vmap._chunked_vmap": UserFunctionVariable, + "torch._functorch.vmap._concat_chunked_outputs": UserFunctionVariable, + "torch._functorch.vmap._create_batched_inputs": UserFunctionVariable, + "torch._functorch.vmap._flat_vmap": UserFunctionVariable, + "torch._functorch.vmap._flatten_chunks_output": UserFunctionVariable, + "torch._functorch.vmap._get_chunked_inputs": UserFunctionVariable, + "torch._functorch.vmap._get_name": UserFunctionVariable, + "torch._functorch.vmap._maybe_remove_batch_dim": UserFunctionVariable, + "torch._functorch.vmap._num_outputs": UserFunctionVariable, + "torch._functorch.vmap._process_batched_inputs": UserFunctionVariable, + "torch._functorch.vmap._unwrap_batched": UserFunctionVariable, + "torch._functorch.vmap._validate_and_get_batch_size": UserFunctionVariable, + "torch._functorch.vmap.doesnt_support_saved_tensors_hooks": UserFunctionVariable, + "torch._functorch.vmap.get_chunk_sizes": UserFunctionVariable, + # lazy_load_decompositions uses a lock that is not supported yet in dynamo + # "torch._functorch.vmap.lazy_load_decompositions": UserFunctionVariable, + "torch._functorch.vmap.restore_vmap": UserFunctionVariable, + "torch._functorch.apis.vmap": UserFunctionVariable, + "torch._functorch.vmap.unwrap_batched": UserFunctionVariable, + "torch._functorch.vmap.vmap_impl": FunctorchHigherOrderVariable, + "torch._functorch.vmap.wrap_batched": UserFunctionVariable, + # functorch/grad + "torch._functorch.eager_transforms.grad_impl": FunctorchHigherOrderVariable, + "torch._functorch.apis.grad_and_value": UserFunctionVariable, + "torch._functorch.eager_transforms._as_tuple": UserFunctionVariable, + "torch._functorch.eager_transforms._check_unique_non_empty": UserFunctionVariable, + "torch._functorch.eager_transforms._create_differentiable": UserFunctionVariable, + "torch._functorch.eager_transforms._slice_argnums": UserFunctionVariable, + "torch._functorch.eager_transforms._undo_create_differentiable": UserFunctionVariable, + "torch._functorch.eager_transforms._validate_and_wrap_argnum": UserFunctionVariable, + "torch._functorch.eager_transforms._validate_and_wrap_argnums": UserFunctionVariable, + "torch._functorch.eager_transforms._wrap_all_tensors": UserFunctionVariable, + "torch._functorch.eager_transforms._wrap_tensor_for_grad": UserFunctionVariable, + # functorch/jacrev + "torch._functorch.eager_transforms.jacrev": FunctorchHigherOrderVariable, + "torch._functorch.eager_transforms.error_if_complex": UserFunctionVariable, + "torch._functorch.eager_transforms._chunked_standard_basis_for_": UserFunctionVariable, + "torch._functorch.eager_transforms._safe_zero_index": UserFunctionVariable, + # functorch/vjp + "torch._functorch.eager_transforms.vjp": FunctorchHigherOrderVariable, + "torch._functorch.eager_transforms._vjp_with_argnums": UserFunctionVariable, + "torch._functorch.eager_transforms.assert_non_empty_tensor_output": UserFunctionVariable, + # functorch/jvp + "torch._functorch.eager_transforms._jvp_with_argnums": UserFunctionVariable, + "torch._functorch.eager_transforms.jvp": FunctorchHigherOrderVariable, + "torch._functorch.eager_transforms._replace_args": UserFunctionVariable, + "torch._functorch.eager_transforms.safe_unpack_dual": UserFunctionVariable, + "torch._functorch.eager_transforms.assert_non_empty_list_of_tensors": UserFunctionVariable, + "torch._functorch.eager_transforms.assert_output_is_tensor_or_tensors": UserFunctionVariable, + "torch.autograd.forward_ad.enter_dual_level": UserFunctionVariable, + "torch.autograd.forward_ad.exit_dual_level": UserFunctionVariable, + "torch.autograd.forward_ad.make_dual": UserFunctionVariable, + "torch.autograd.forward_ad.unpack_dual": UserFunctionVariable, + "torch.autograd.graph.region_activation_memory_budget": UserFunctionVariable, + # functorch/linearize + "torch._functorch.eager_transforms.linearize": FunctorchHigherOrderVariable, + # functorch/jacfwd + "torch._functorch.eager_transforms.jacfwd": FunctorchHigherOrderVariable, + "torch._functorch.eager_transforms._construct_standard_basis_for": UserFunctionVariable, + "torch._functorch.eager_transforms.safe_unflatten": UserFunctionVariable, + # functorch/hessian + "torch._functorch.eager_transforms.hessian": FunctorchHigherOrderVariable, + # functional_call + "torch._functorch.functional_call.functional_call": FunctionalCallVariable, + "torch.nn.utils.stateless._groupby_tensor": TorchInGraphFunctionVariable, + "torch.nn.utils.stateless._reparametrize_module": ReparametrizeModuleCallVariable, + # functorch/deprecated + "torch._functorch.deprecated.jvp": UserFunctionVariable, + "torch._functorch.deprecated.hessian": UserFunctionVariable, + "torch._functorch.deprecated.jacfwd": UserFunctionVariable, + "torch._functorch.deprecated.jacrev": UserFunctionVariable, + "torch._functorch.deprecated.grad": UserFunctionVariable, + "torch._functorch.deprecated.grad_and_value": UserFunctionVariable, + "torch._functorch.deprecated.vjp": UserFunctionVariable, + # functorch/C++ bindings + "torch._C._functorch._wrap_for_grad": TorchInGraphFunctionVariable, + "torch._C._functorch._unwrap_for_grad": TorchInGraphFunctionVariable, + "torch._C._functorch._unwrap_batched": TorchInGraphFunctionVariable, + "torch._C._functorch.current_level": TorchInGraphFunctionVariable, + "torch._C._functorch.maybe_current_level": TorchInGraphFunctionVariable, + "torch._C._functorch.is_batchedtensor": TorchInGraphFunctionVariable, + "torch._C._functorch.peek_interpreter_stack": TorchInGraphFunctionVariable, + "torch._C._functorch.unwrap_if_dead": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._vmap_increment_nesting": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._vmap_decrement_nesting": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._jvp_increment_nesting": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._jvp_decrement_nesting": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._unwrap_for_grad": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._make_dual": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._unpack_dual": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._enter_dual_level": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._exit_dual_level": TorchInGraphFunctionVariable, + # everything else + "torch._functorch.pyfunctorch.coerce_cinterpreter": TorchInGraphFunctionVariable, + "torch._higher_order_ops.triton_kernel_wrap.do_prune_configs": UserFunctionVariable, + "torch._higher_order_ops.foreach_map.foreach_map": UserFunctionVariable, + "torch._constrain_as_size": UserFunctionVariable, + "torch._tensor._convert": UserFunctionVariable, + "torch.jit._unwrap_optional": UserFunctionVariable, + "torch.backends.mha.get_fastpath_enabled": UserFunctionVariable, + "torch._dynamo.dont_skip_tracing": UserFunctionVariable, + "torch._dynamo.mark_static": UserFunctionVariable, + "torch._dynamo.nonstrict_trace": UserFunctionVariable, + "torch._dynamo.bytecode_debugger.breakpoint": UserFunctionVariable, + "torch._dynamo.patch_dynamo_config": UserFunctionVariable, + "torch._dynamo.disable_nested_graph_breaks": UserFunctionVariable, + "torch._dynamo.error_on_graph_break": UserFunctionVariable, + "torch._dynamo.override_cudagraphs": UserFunctionVariable, + "torch.fx.experimental.symbolic_shapes.guard_size_oblivious": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.is_nested_int": UserFunctionVariable, + "torch.fx.experimental.symbolic_shapes.guarding_hint_or_throw": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.optimization_hint": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.guard_or_true": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.guard_or_false": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.statically_known_true": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.statically_known_false": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.sym_and": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.sym_or": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.guard_scalar": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.has_static_value": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.has_free_unbacked_symbols": TorchInGraphFunctionVariable, + "torch.cuda._get_device_properties": TorchInGraphFunctionVariable, + "torch.utils.hooks.BackwardHook": TorchInGraphFunctionVariable, + "torch.set_default_device": UserFunctionVariable, + "torch.sparse_bsc_tensor": SparseTensorCreationSkipVariable, + "torch.sparse_bsr_tensor": SparseTensorCreationSkipVariable, + "torch.sparse_csc_tensor": SparseTensorCreationSkipVariable, + "torch.sparse_csr_tensor": SparseTensorCreationSkipVariable, + "torch.sparse_compressed_tensor": SparseTensorCreationSkipVariable, + "torch._C._autograd._unsafe_set_version_counter": TorchInGraphFunctionVariable, + "torch.xpu.get_rng_state": SkipFunctionVariable, + "torch.xpu.set_rng_state": SkipFunctionVariable, + "torch.library.wrap_triton": TorchInGraphFunctionVariable, + "torch._library.capture_triton": TorchInGraphFunctionVariable, + # avoid skipping user defined modules in distributed unit tests + "torch/testing/_internal/common_fsdp.py#forward": UserFunctionVariable, + f"torch/testing/_internal/common_fsdp.py#{TORCH_DYNAMO_RESUME_IN_PREFIX}": UserFunctionVariable, + "torch/testing/_internal/distributed/_tensor/common_dtensor.py#forward": UserFunctionVariable, + f"torch/testing/_internal/distributed/_tensor/common_dtensor.py#{TORCH_DYNAMO_RESUME_IN_PREFIX}": UserFunctionVariable, + "torch/testing/_internal/common_distributed.py#forward": UserFunctionVariable, + f"torch/testing/_internal/common_distributed.py#{TORCH_DYNAMO_RESUME_IN_PREFIX}": UserFunctionVariable, + "torch.utils._pytree._get_node_type": PyTreeGetNodeTypeFunctionVariable, + "torch.utils._pytree.tree_is_leaf": PyTreeTreeIsLeafFunctionVariable, + # torch.utils._python_dispatch is in MOD_INLINELIST; override so the handler + # in variables/torch.py fires instead of graph-breaking on _len_torch_dispatch_stack. + "torch.utils._python_dispatch._get_current_dispatch_mode_stack": TorchInGraphFunctionVariable, + "torch._utils_internal.justknobs_check": UserFunctionVariable, + "inspect.signature": InspectSignatureVariable, +} + +# Keep this in sync with the stateful generator methods exposed from +# torch/csrc/Generator.cpp. +_GENERATOR_METHODS_THAT_GRAPH_BREAK = ( + "clone_state", + "get_offset", + "get_state", + "graphsafe_get_state", + "graphsafe_set_state", + "initial_seed", + "manual_seed", + "seed", + "set_offset", + "set_state", +) + +for generator_prefix in ("torch.default_generator", "torch._C.Generator"): + for method_name in _GENERATOR_METHODS_THAT_GRAPH_BREAK: + manual_torch_name_rule_map[f"{generator_prefix}#{method_name}"] = ( + SkipFunctionVariable + ) + + +# In graph functions (including constant folding) that are C bindings +torch_c_binding_in_graph_functions = dict.fromkeys( + [ + "math.acos", + "math.acosh", + "math.asin", + "math.asinh", + "math.atan", + "math.atan2", + "math.atanh", + "math.ceil", + "math.comb", + "math.copysign", + "math.cos", + "math.cosh", + "math.degrees", + "math.dist", + "math.erf", + "math.erfc", + "math.exp", + "math.expm1", + "math.fabs", + "math.factorial", + "math.floor", + "math.fmod", + "math.frexp", + "math.fsum", + "math.gamma", + "math.gcd", + "math.hypot", + "math.isclose", + "math.isfinite", + "math.isinf", + "math.isnan", + "math.isqrt", + "math.lcm", + "math.ldexp", + "math.lgamma", + "math.log", + "math.log10", + "math.log1p", + "math.log2", + "math.modf", + "math.nextafter", + "math.perm", + "math.pow", + "math.prod", + "math.radians", + "math.remainder", + "math.sin", + "math.sinh", + "math.tan", + "math.tanh", + "math.trunc", + "math.ulp", + "torch._adaptive_avg_pool2d", + "torch._adaptive_avg_pool3d", + "torch._add_batch_dim", + "torch._add_relu_", + "torch._add_relu", + "torch._addmm_activation", + "torch._aminmax", + "torch._amp_foreach_non_finite_check_and_unscale_", + "torch._amp_update_scale_", + "torch._assert_async", + "torch._assert_tensor_metadata", + "torch._batch_norm_impl_index", + "torch._C._accelerator_getAccelerator", + "torch._C._accelerator_getDeviceIndex", + "torch._C._accelerator_getStream", + "torch._C._accelerator_getAllocatorSettings", + "torch._C._accelerator_setAllocatorSettings", + "torch._C._accelerator_setStream", + "torch._C._accelerator_synchronizeDevice", + "torch._C._activate_gpu_trace", + "torch._C._add_cached_tensor", + "torch._C._add_docstr", + "torch._C._are_functorch_transforms_active", + "torch._C._autograd_init", + "torch._C._autograd._saved_tensors_hooks_disable", + "torch._C._autograd._saved_tensors_hooks_enable", + "torch._C._awaitable_nowait", + "torch._C._awaitable_wait", + "torch._C._awaitable", + "torch._C._backport_for_mobile_from_buffer_to_buffer", + "torch._C._backport_for_mobile_from_buffer", + "torch._C._backport_for_mobile_to_buffer", + "torch._C._backport_for_mobile", + "torch._C._broadcast_coalesced", + "torch._C._broadcast_out", + "torch._C._broadcast", + "torch._C._c10d_init", + "torch._C._calculate_package_version_based_on_upgraders", + "torch._C._can_use_flash_attention", + "torch._C._can_use_mem_efficient_attention", + "torch._C._can_use_cudnn_attention", + "torch._C._check_onnx_proto", + "torch._C._check_sparse_tensor_invariants", + "torch._C._collect_all", + "torch._C._commit_update", + "torch._C._compile_graph_to_code_table", + "torch._C._construct_CUDA_Tensor_From_Storage_And_Metadata", + "torch._C._construct_storage_from_data_pointer", + "torch._C._conv_determine_backend_memory_format", + "torch._C._cpu._init_amx", + "torch._C._cpu._get_cpu_capability", + "torch._C._crash_if_aten_asan", + "torch._C._crash_if_csrc_asan", + "torch._C._crash_if_csrc_ubsan", + "torch._C._crash_if_debug_asserts_fail", + "torch._C._crash_if_vptr_ubsan", + "torch._C._create_function_from_graph", + "torch._C._create_function_from_trace_with_dict", + "torch._C._create_function_from_trace", + "torch._C._create_graph_by_tracing", + "torch._C._create_module_with_type", + "torch._C._create_object_with_type", + "torch._C._cuda_attach_out_of_memory_observer", + "torch._C._cuda_beginAllocateCurrentStreamToPool", + "torch._C._cuda_canDeviceAccessPeer", + "torch._C._cuda_changeCurrentAllocator", + "torch._C._cuda_checkPoolLiveAllocations", + "torch._C._cuda_clearCublasWorkspaces", + "torch._C._cuda_cudaCachingAllocator_raw_alloc", + "torch._C._cuda_cudaCachingAllocator_raw_delete", + "torch._C._cuda_cudaHostAllocator", + "torch._C._cuda_customAllocator", + "torch._C._cuda_emptyCache", + "torch._C._cuda_endAllocateToPool", + "torch._C._cuda_exchangeDevice", + "torch._C._cuda_get_conv_benchmark_empty_cache", + "torch._C._cuda_get_cudnn_benchmark_limit", + "torch._C._cuda_get_sync_debug_mode", + "torch._C._cuda_getAllocator", + "torch._C._cuda_getAllocatorBackend", + "torch._C._cuda_getArchFlags", + "torch._C._cuda_getCheckpointState", + "torch._C._cuda_getCompiledVersion", + "torch._C._cuda_getCurrentBlasHandle", + "torch._C._cuda_getCurrentSolverHandle", + "torch._C._cuda_getCurrentRawStream", + "torch._C._cuda_getCurrentStream", + "torch._C._cuda_getDefaultStream", + "torch._C._cuda_getDevice", + "torch._C._cuda_getDeviceCount", + "torch._C._cuda_hasPrimaryContext", + "torch._C._cuda_hostMemoryStats", + "torch._C._cuda_init", + "torch._C._cuda_ipc_collect", + "torch._C._cuda_isCurrentStreamCapturing", + "torch._C._cuda_isHistoryEnabled", + "torch._C._cuda_isInBadFork", + "torch._C._cuda_jiterator_compile_and_launch_kernel", + "torch._C._cuda_maybeExchangeDevice", + "torch._C._cuda_memorySnapshot", + "torch._C._cuda_memoryStats", + "torch._C._cuda_record_memory_history_legacy", + "torch._C._cuda_record_memory_history", + "torch._C._cuda_releasePool", + "torch._C._cuda_resetAccumulatedHostMemoryStats", + "torch._C._cuda_resetAccumulatedMemoryStats", + "torch._C._cuda_resetPeakHostMemoryStats", + "torch._C._cuda_resetPeakMemoryStats", + "torch._C._cuda_set_cudnn_benchmark_limit", + "torch._C._cuda_set_sync_debug_mode", + "torch._C._cuda_setCheckpointPoolState", + "torch._C._cuda_setDevice", + "torch._C._cuda_setMemoryFraction", + "torch._C._cuda_setStream", + "torch._C._cuda_sleep", + "torch._C._cuda_synchronize", + "torch._C._cudnn_set_conv_benchmark_empty_cache", + "torch._C._cudnn.getCompileVersion", + "torch._C._cudnn.getRuntimeVersion", + "torch._C._cudnn.getVersionInt", + "torch._C._current_autograd_node", + "torch._C._current_graph_task_execution_order", + "torch._C._current_graph_task_id", + "torch._C._cxx_flags", + "torch._C._debug_get_fusion_group_inlining", + "torch._C._debug_only_are_vmap_fallback_warnings_enabled", + "torch._C._debug_only_display_vmap_fallback_warnings", + "torch._C._debug_set_autodiff_subgraph_inlining", + "torch._C._debug_set_fusion_group_inlining", + "torch._C._demangle", + "torch._C._disabled_torch_dispatch_impl", + "torch._C._dispatch_call_boxed", + "torch._C._dispatch_check_all_invariants", + "torch._C._dispatch_check_invariants", + "torch._C._dispatch_dump_table", + "torch._C._dispatch_dump", + "torch._C._dispatch_find_dangling_impls", + "torch._C._dispatch_find_schema_or_throw", + "torch._C._dispatch_get_all_op_names", + "torch._C._dispatch_get_backend_keyset_from_autograd", + "torch._C._dispatch_get_registrations_for_dispatch_key", + "torch._C._dispatch_has_backend_fallback", + "torch._C._dispatch_has_computed_kernel_for_dispatch_key", + "torch._C._dispatch_has_kernel_for_any_dispatch_key", + "torch._C._dispatch_has_kernel_for_dispatch_key", + "torch._C._dispatch_has_kernel", + "torch._C._dispatch_is_alias_key", + "torch._C._dispatch_is_included_in_alias", + "torch._C._dispatch_isTensorSubclassLike", + "torch._C._dispatch_key_for_device", + "torch._C._dispatch_key_name", + "torch._C._dispatch_key_parse", + "torch._C._dispatch_key_set", + "torch._C._dispatch_keys", + "torch._C._dispatch_keyset_full_after", + "torch._C._dispatch_keyset_full", + "torch._C._dispatch_keyset_to_string", + "torch._C._dispatch_library", + "torch._C._dispatch_num_backends", + "torch._C._dispatch_print_registrations_for_dispatch_key", + "torch._C._dispatch_pystub", + "torch._C._dispatch_set_report_error_callback", + "torch._C._dispatch_tls_is_dispatch_key_excluded", + "torch._C._dispatch_tls_is_dispatch_key_included", + "torch._C._dispatch_tls_local_exclude_set", + "torch._C._dispatch_tls_local_include_set", + "torch._C._dispatch_tls_set_dispatch_key_excluded", + "torch._C._dispatch_tls_set_dispatch_key_included", + "torch._C._dist_autograd_init", + "torch._C._dump_local_tls_set", + "torch._C._dump_upgraders_map", + "torch._C._enable_mobile_interface_call_export", + "torch._C._enter_dual_level", + "torch._C._error_if_any_worker_fails", + "torch._C._exit_dual_level", + "torch._C._export_operator_list", + "torch._C._export_opnames", + "torch._C._faulty_agent_init", + "torch._C._fft.fft_fft", + "torch._C._fft.fft_fft2", + "torch._C._fft.fft_fftfreq", + "torch._C._fft.fft_fftn", + "torch._C._fft.fft_fftshift", + "torch._C._fft.fft_hfft", + "torch._C._fft.fft_hfft2", + "torch._C._fft.fft_hfftn", + "torch._C._fft.fft_ifft", + "torch._C._fft.fft_ifft2", + "torch._C._fft.fft_ifftn", + "torch._C._fft.fft_ifftshift", + "torch._C._fft.fft_ihfft", + "torch._C._fft.fft_ihfft2", + "torch._C._fft.fft_ihfftn", + "torch._C._fft.fft_irfft", + "torch._C._fft.fft_irfft2", + "torch._C._fft.fft_irfftn", + "torch._C._fft.fft_rfft", + "torch._C._fft.fft_rfft2", + "torch._C._fft.fft_rfftfreq", + "torch._C._fft.fft_rfftn", + "torch._C._free_And_Remove_DeleterFn", + "torch._C._freeze_module", + "torch._C._from_dlpack", + "torch._C._functionality_to_backend_keys", + "torch._C._functionalization_reapply_views_tls", + "torch._C._functorch._grad_decrement_nesting", + "torch._C._functorch._grad_increment_nesting", + "torch._C._functorch.get_dynamic_layer_stack_depth", + "torch._C._functorch.set_inplace_requires_grad_allowed", + "torch._functorch.utils.unwrap_dead_wrappers", + "torch._C._fuse_to_static_module", + "torch._C._gather_out", + "torch._C._gather", + "torch._C._generate_upgraders_graph", + "torch._C._get_autograd_fallback_mode", + "torch._C._get_backcompat_broadcast_warn", + "torch._C._get_backcompat_keepdim_warn", + "torch._C._get_blas_preferred_backend", + "torch._C._get_caught_jit_exception_class_name", + "torch._C._get_caught_jit_exception_original_msg", + "torch._C._get_constant_bool_symnode", + "torch._C._get_cpp_backtrace", + "torch._C._get_cpu_capability", + "torch._C._get_cublas_allow_bf16_reduced_precision_reduction", + "torch._C._get_cublas_allow_fp16_reduced_precision_reduction", + "torch._C._get_cublas_allow_tf32", + "torch._C._get_cudnn_allow_tf32", + "torch._C._get_cudnn_benchmark", + "torch._C._get_miopen_immediate", + "torch._C._get_cudnn_deterministic", + "torch._C._get_cudnn_enabled", + "torch._C._get_custom_class_python_wrapper", + "torch._C._get_default_device", + "torch._C._get_deterministic_algorithms_warn_only", + "torch._C._get_deterministic_algorithms", + "torch._C._get_deterministic_fill_uninitialized_memory", + "torch._C._get_dispatch_mode", + "torch._C._get_dispatch_stack_at", + "torch._C._get_file_format", + "torch._C._get_flash_sdp_enabled", + "torch._C._get_float32_matmul_precision", + "torch._C._get_function_stack_at", + "torch._C._get_graph_executor_optimize", + "torch._C._get_linalg_preferred_backend", + "torch._C._get_rocm_fa_preferred_backend", + "torch._C._get_math_sdp_enabled", + "torch._C._get_math_sdp_allow_fp16_bf16_reduction", + "torch._C._get_max_operator_version", + "torch._C._get_mem_efficient_sdp_enabled", + "torch._C._get_mkldnn_enabled", + "torch._C._get_cudnn_sdp_enabled", + "torch._C._get_overrideable_sdp_enabled", + "torch._C._set_sdp_use_cudnn", + "torch._C._get_mobile_model_contained_types_from_buffer", + "torch._C._get_mobile_model_contained_types", + "torch._C._get_model_bytecode_version_from_buffer", + "torch._C._get_model_bytecode_version", + "torch._C._get_model_extra_files_from_buffer", + "torch._C._get_model_extra_files", + "torch._C._get_model_ops_and_info_from_buffer", + "torch._C._get_model_ops_and_info", + "torch._C._get_module_info_from_flatbuffer", + "torch._C._get_nnpack_enabled", + "torch._C._get_obj_in_tls", + "torch._C._get_operation_overload", + "torch._C._get_operator_version_map", + "torch._C._get_privateuse1_backend_name", + "torch._C._get_qengine", + "torch._C._get_schema", + "torch._C._get_sm_carveout_experimental", + "torch._C._get_nested_int", + "torch._C._get_tensor_metadata", + "torch._C._get_tracing_state", + "torch._C._get_upgrader_ranges", + "torch._C._get_upgraders_entry_map", + "torch._C._get_upgraders_map_size", + "torch._C._get_value_trace", + "torch._C._get_version_calculator_flag", + "torch._C._get_warnAlways", + "torch._C._graph_pool_handle", + "torch._C._hack_do_not_use_clone_module_with_class", + "torch._C._has_distributed", + "torch._C._has_Standard_Deleter", + "torch._C._has_storage", + "torch._C._has_tensorexpr_cpp_tests", + "torch._C._run_tensorexpr_cpp_tests", + "torch._C._has_torch_function_unary", + "torch._C._has_torch_function_variadic", + "torch._C._has_torch_function", + "torch._C._import_ir_module_from_package", + "torch._C._increment_version", + "torch._C._infer_size", + "torch._C._init_names", + "torch._C._initExtension", + "torch._C._is_alias_of", + "torch._C._is_any_autocast_enabled", + "torch._C._is_autocast_available", + "torch._C._is_cached_tensor", + "torch._C._is_flash_attention_available", + "torch._C._is_fwd_grad_enabled", + "torch._C._is_key_in_tls", + "torch._C._is_multithreading_enabled", + "torch._C._is_torch_function_enabled", + "torch._C._is_torch_function_mode_enabled", + "torch._C._is_torch_function_all_disabled", + "torch._C._is_tracing", + "torch._C._is_view_replay_enabled", + "torch._C._is_xnnpack_enabled", + "torch._C._itt.is_available", + "torch._C._itt.mark", + "torch._C._itt.rangePop", + "torch._C._itt.rangePush", + "torch._C._ivalue_debug_python_object", + "torch._C._ivalue_tags_match", + "torch._C._jit_assert_is_instance", + "torch._C._jit_can_fuse_on_cpu_legacy", + "torch._C._jit_can_fuse_on_cpu", + "torch._C._jit_can_fuse_on_gpu", + "torch._C._jit_cat_wo_conditionals", + "torch._C._jit_check_alias_annotation", + "torch._C._jit_clear_class_registry", + "torch._C._jit_debug_fuser_num_cached_kernel_specs", + "torch._C._jit_debug_module_iterators", + "torch._C._jit_decay_packed_param_input_types", + "torch._C._jit_decomposition_graph_for_node", + "torch._C._jit_differentiate", + "torch._C._jit_erase_non_input_shape_information", + "torch._C._jit_flatten", + "torch._C._jit_fuser_get_fused_kernel_code", + "torch._C._jit_get_all_schemas", + "torch._C._jit_get_custom_class_schemas", + "torch._C._jit_get_emit_hooks", + "torch._C._jit_get_inline_everything_mode", + "torch._C._jit_get_logging_option", + "torch._C._jit_get_num_profiled_runs", + "torch._C._jit_get_operation", + "torch._C._jit_get_schemas_for_operator", + "torch._C._jit_get_te_cuda_pointwise_block_count", + "torch._C._jit_get_te_cuda_pointwise_block_size", + "torch._C._jit_get_te_cuda_pointwise_loop_levels", + "torch._C._jit_get_te_generate_block_code", + "torch._C._jit_get_te_must_use_llvm_cpu", + "torch._C._jit_get_tracer_state_warn", + "torch._C._jit_has_cpp_tests", + "torch._C._jit_init", + "torch._C._jit_interpret_graph", + "torch._C._jit_is_onnx_log_enabled", + "torch._C._jit_is_script_object", + "torch._C._jit_llga_enabled", + "torch._C._jit_nvfuser_can_be_enabled", + "torch._C._jit_nvfuser_clear_comparison_callback", + "torch._C._jit_nvfuser_enabled", + "torch._C._jit_nvfuser_horizontal_mode", + "torch._C._jit_nvfuser_set_comparison_callback", + "torch._C._jit_nvfuser_single_node_mode", + "torch._C._jit_object_is_non_holding", + "torch._C._jit_onnx_convert_pattern_from_subblock", + "torch._C._jit_onnx_create_full_scope_name", + "torch._C._jit_onnx_list_model_parameters", + "torch._C._jit_onnx_log", + "torch._C._jit_opt_conditionals", + "torch._C._jit_override_can_fuse_on_cpu_legacy", + "torch._C._jit_override_can_fuse_on_cpu", + "torch._C._jit_override_can_fuse_on_gpu", + "torch._C._jit_pass_autocast", + "torch._C._jit_pass_batch_mm", + "torch._C._jit_pass_canonicalize_graph_fuser_ops", + "torch._C._jit_pass_canonicalize", + "torch._C._jit_pass_complete_shape_analysis", + "torch._C._jit_pass_concat_frozen_linear", + "torch._C._jit_pass_constant_loop_unrolling", + "torch._C._jit_pass_constant_pooling", + "torch._C._jit_pass_constant_propagation_immutable_types", + "torch._C._jit_pass_constant_propagation", + "torch._C._jit_pass_convert_frozen_ops_to_mkldnn", + "torch._C._jit_pass_create_autodiff_subgraphs", + "torch._C._jit_pass_create_functional_graphs", + "torch._C._jit_pass_cse", + "torch._C._jit_pass_custom_pattern_based_rewrite_graph", + "torch._C._jit_pass_custom_pattern_based_rewrite", + "torch._C._jit_pass_dbr_quant_remove_redundant_aliases", + "torch._C._jit_pass_dce_allow_deleting_nodes_with_side_effects", + "torch._C._jit_pass_dce", + "torch._C._jit_pass_decompose_ops", + "torch._C._jit_pass_dedup_module_uses", + "torch._C._jit_pass_erase_number_types", + "torch._C._jit_pass_erase_shape_information", + "torch._C._jit_pass_filter_non_tensor_arguments", + "torch._C._jit_pass_fixup_onnx_controlflow_node", + "torch._C._jit_pass_fold_convbn", + "torch._C._jit_pass_fold_frozen_conv_add_or_sub", + "torch._C._jit_pass_fold_frozen_conv_bn", + "torch._C._jit_pass_fold_frozen_conv_mul_or_div", + "torch._C._jit_pass_fold_frozen_linear_bn", + "torch._C._jit_pass_fold_prepacking_ops", + "torch._C._jit_pass_functional_to_inplace_activation", + "torch._C._jit_pass_fuse_add_relu", + "torch._C._jit_pass_fuse_addmm", + "torch._C._jit_pass_fuse_clamp_w_prepacked_linear_conv", + "torch._C._jit_pass_fuse_frozen_conv_add_relu", + "torch._C._jit_pass_fuse_linear", + "torch._C._jit_pass_fuse_quantized_add_relu", + "torch._C._jit_pass_fuse_tensorexprs", + "torch._C._jit_pass_fuse", + "torch._C._jit_pass_inline_fork_wait", + "torch._C._jit_pass_inline_functional_graphs", + "torch._C._jit_pass_inline", + "torch._C._jit_pass_inplace_to_functional_activation", + "torch._C._jit_pass_insert_observer_method_for_ondevice_ptq", + "torch._C._jit_pass_insert_observers", + "torch._C._jit_pass_insert_prepack_unpack", + "torch._C._jit_pass_insert_prepacked_ops", + "torch._C._jit_pass_insert_quant_dequant_for_ondevice_ptq", + "torch._C._jit_pass_insert_quant_dequant", + "torch._C._jit_pass_integer_value_refinement", + "torch._C._jit_pass_lint", + "torch._C._jit_pass_loop_unrolling", + "torch._C._jit_pass_lower_all_tuples", + "torch._C._jit_pass_lower_graph", + "torch._C._jit_pass_metal_fold_prepacking_ops", + "torch._C._jit_pass_metal_fuse_clamp_w_prepacked_conv", + "torch._C._jit_pass_metal_insert_prepacked_ops", + "torch._C._jit_pass_metal_optimize_for_mobile", + "torch._C._jit_pass_onnx_assign_output_shape", + "torch._C._jit_pass_onnx_assign_scoped_names_for_node_and_value", + "torch._C._jit_pass_onnx_autograd_function_process", + "torch._C._jit_pass_onnx_block", + "torch._C._jit_pass_onnx_cast_all_constant_to_floating", + "torch._C._jit_pass_onnx_clear_scope_records", + "torch._C._jit_pass_onnx_constant_fold", + "torch._C._jit_pass_onnx_deduplicate_initializers", + "torch._C._jit_pass_onnx_eliminate_unused_items", + "torch._C._jit_pass_onnx_eval_peephole", + "torch._C._jit_pass_onnx_function_extraction", + "torch._C._jit_pass_onnx_function_substitution", + "torch._C._jit_pass_onnx_graph_shape_type_inference", + "torch._C._jit_pass_onnx_lint", + "torch._C._jit_pass_onnx_node_shape_type_inference", + "torch._C._jit_pass_onnx_peephole", + "torch._C._jit_pass_onnx_preprocess_caffe2", + "torch._C._jit_pass_onnx_preprocess", + "torch._C._jit_pass_onnx_quantization_insert_permutes", + "torch._C._jit_pass_onnx_remove_inplace_ops_for_onnx", + "torch._C._jit_pass_onnx_remove_print", + "torch._C._jit_pass_onnx_scalar_type_analysis", + "torch._C._jit_pass_onnx_set_dynamic_input_shape", + "torch._C._jit_pass_onnx_track_scope_attributes", + "torch._C._jit_pass_onnx_unpack_quantized_weights", + "torch._C._jit_pass_onnx", + "torch._C._jit_pass_optimize_for_inference", + "torch._C._jit_pass_optimize_for_mobile", + "torch._C._jit_pass_optimize_frozen_graph", + "torch._C._jit_pass_pattern_based_rewrite", + "torch._C._jit_pass_peephole_list_idioms", + "torch._C._jit_pass_peephole", + "torch._C._jit_pass_prepare_division_for_onnx", + "torch._C._jit_pass_propagate_device", + "torch._C._jit_pass_propagate_dtype", + "torch._C._jit_pass_propagate_shapes_on_graph_and_build_compute", + "torch._C._jit_pass_propagate_shapes_on_graph", + "torch._C._jit_pass_quant_finalize_for_ondevice_ptq", + "torch._C._jit_pass_quant_finalize", + "torch._C._jit_pass_quant_fusion", + "torch._C._jit_pass_refine_integer_values", + "torch._C._jit_pass_refine_tuple_types", + "torch._C._jit_pass_remove_dropout", + "torch._C._jit_pass_remove_expands", + "torch._C._jit_pass_remove_inplace_ops", + "torch._C._jit_pass_remove_mutation", + "torch._C._jit_pass_replace_old_ops_with_upgraders", + "torch._C._jit_pass_replicate_dequantize", + "torch._C._jit_pass_run_decompositions", + "torch._C._jit_pass_specialize_autogradzero", + "torch._C._jit_pass_swap_functional_linear", + "torch._C._jit_pass_transform_conv1d_to_conv2d", + "torch._C._jit_pass_transpose_frozen_linear", + "torch._C._jit_pass_vulkan_fold_prepacking_ops", + "torch._C._jit_pass_vulkan_fuse_clamp_w_prepacked_conv", + "torch._C._jit_pass_vulkan_insert_prepacked_ops", + "torch._C._jit_pass_vulkan_optimize_for_mobile", + "torch._C._jit_register_decomposition_for_schema", + "torch._C._jit_register_shape_compute_graph_for_node", + "torch._C._jit_resolve_packet", + "torch._C._jit_run_cpp_tests", + "torch._C._jit_script_class_compile", + "torch._C._jit_script_compile_overload", + "torch._C._jit_script_compile", + "torch._C._jit_script_interface_compile", + "torch._C._jit_set_autocast_mode", + "torch._C._jit_set_bailout_depth", + "torch._C._jit_set_emit_hooks", + "torch._C._jit_set_fusion_strategy", + "torch._C._jit_set_inline_everything_mode", + "torch._C._jit_set_llga_enabled", + "torch._C._jit_set_logging_option", + "torch._C._jit_set_logging_stream", + "torch._C._jit_set_num_profiled_runs", + "torch._C._jit_set_nvfuser_enabled", + "torch._C._jit_set_nvfuser_guard_mode", + "torch._C._jit_set_nvfuser_horizontal_mode", + "torch._C._jit_set_nvfuser_single_node_mode", + "torch._C._jit_set_nvfuser_skip_node_kind", + "torch._C._jit_set_onnx_log_enabled", + "torch._C._jit_set_onnx_log_output_stream", + "torch._C._jit_set_profiling_executor", + "torch._C._jit_set_profiling_mode", + "torch._C._jit_set_symbolic_shapes_test_mode", + "torch._C._jit_set_te_cuda_pointwise_block_count", + "torch._C._jit_set_te_cuda_pointwise_block_size", + "torch._C._jit_set_te_cuda_pointwise_loop_levels", + "torch._C._jit_set_te_generate_block_code", + "torch._C._jit_set_te_must_use_llvm_cpu", + "torch._C._jit_set_texpr_dynamic_shape_enabled", + "torch._C._jit_set_texpr_fuser_enabled", + "torch._C._jit_set_texpr_reductions_enabled", + "torch._C._jit_set_tracer_state_warn", + "torch._C._jit_set_utf8_decoding_ignore", + "torch._C._jit_shape_compute_graph_for_node", + "torch._C._jit_symbolic_shapes_test_mode_enabled", + "torch._C._jit_texpr_dynamic_shape_enabled", + "torch._C._jit_texpr_fallback_allowed", + "torch._C._jit_texpr_fuser_enabled", + "torch._C._jit_texpr_reductions_enabled", + "torch._C._jit_texpr_set_fallback_allowed", + "torch._C._jit_to_backend_selective", + "torch._C._jit_to_backend", + "torch._C._jit_to_static_module", + "torch._C._jit_trace_graph", + "torch._C._jit_trace_module", + "torch._C._jit_tree_views.FalseLiteral", + "torch._C._jit_tree_views.NoneLiteral", + "torch._C._jit_tree_views.TrueLiteral", + "torch._C._jit_try_infer_type", + "torch._C._jit_unflatten", + "torch._C._last_executed_optimized_graph", + "torch._C._len_torch_dispatch_stack", + "torch._C._len_torch_function_stack", + "torch._C._linalg._linalg_eigvals", + "torch._C._linalg.linalg_cholesky_ex", + "torch._C._linalg.linalg_cholesky", + "torch._C._linalg.linalg_cond", + "torch._C._linalg.linalg_cross", + "torch._C._linalg.linalg_det", + "torch._C._linalg.linalg_diagonal", + "torch._C._linalg.linalg_eig", + "torch._C._linalg.linalg_eigh", + "torch._C._linalg.linalg_eigvals", + "torch._C._linalg.linalg_eigvalsh", + "torch._C._linalg.linalg_householder_product", + "torch._C._linalg.linalg_inv_ex", + "torch._C._linalg.linalg_inv", + "torch._C._linalg.linalg_ldl_factor_ex", + "torch._C._linalg.linalg_ldl_factor", + "torch._C._linalg.linalg_ldl_solve", + "torch._C._linalg.linalg_lstsq", + "torch._C._linalg.linalg_lu_factor_ex", + "torch._C._linalg.linalg_lu_factor", + "torch._C._linalg.linalg_lu_solve", + "torch._C._linalg.linalg_lu", + "torch._C._linalg.linalg_matmul", + "torch._C._linalg.linalg_matrix_exp", + "torch._C._linalg.linalg_matrix_norm", + "torch._C._linalg.linalg_matrix_power", + "torch._C._linalg.linalg_matrix_rank", + "torch._C._linalg.linalg_matrix_sqrth", + "torch._C._linalg.linalg_multi_dot", + "torch._C._linalg.linalg_norm", + "torch._C._linalg.linalg_pinv", + "torch._C._linalg.linalg_polar", + "torch._C._linalg.linalg_qr", + "torch._C._linalg.linalg_slogdet", + "torch._C._linalg.linalg_solve_ex", + "torch._C._linalg.linalg_solve_triangular", + "torch._C._linalg.linalg_solve", + "torch._C._linalg.linalg_svd", + "torch._C._linalg.linalg_svdvals", + "torch._C._linalg.linalg_tensorinv", + "torch._C._linalg.linalg_tensorsolve", + "torch._C._linalg.linalg_vander", + "torch._C._linalg.linalg_vecdot", + "torch._C._linalg.linalg_vector_norm", + "torch._C._llvm_enabled", + "torch._C._load_for_lite_interpreter_from_buffer", + "torch._C._load_for_lite_interpreter", + "torch._C._load_jit_module_from_bytes", + "torch._C._load_jit_module_from_file", + "torch._C._load_mobile_module_from_bytes", + "torch._C._load_mobile_module_from_file", + "torch._C._log_api_usage_metadata", + "torch._C._log_api_usage_once", + "torch._C._logging_set_logger", + "torch._C._meta_in_tls_dispatch_include", + "torch._C._mps_acquireEvent", + "torch._C._mps_currentAllocatedMemory", + "torch._C._mps_deviceSynchronize", + "torch._C._mps_driverAllocatedMemory", + "torch._C._mps_recommendedMaxMemory", + "torch._C._mps_elapsedTimeOfEvents", + "torch._C._mps_emptyCache", + "torch._C._mps_get_default_generator", + "torch._C._mps_is_available", + "torch._C._mps_is_in_bad_fork", + "torch._C._mps_is_on_macos_13_or_newer", + "torch._C._mps_profilerStartTrace", + "torch._C._mps_profilerStopTrace", + "torch._C._mps_queryEvent", + "torch._C._mps_recordEvent", + "torch._C._mps_releaseEvent", + "torch._C._mps_setMemoryFraction", + "torch._C._mps_synchronizeEvent", + "torch._C._mps_waitForEvent", + "torch._C._multiprocessing_init", + "torch._C._nccl_all_gather", + "torch._C._nccl_all_reduce", + "torch._C._nccl_broadcast", + "torch._C._nccl_init_rank", + "torch._C._nccl_reduce_scatter", + "torch._C._nccl_reduce", + "torch._C._nccl_unique_id", + "torch._C._nccl_version_suffix", + "torch._C._nccl_version", + "torch._C._nested.nested_tensor", + "torch._C._nested.nested_to_padded_tensor", + "torch._C._new_symbolic_shape_symbol", + "torch._C._nn_module_to_mobile", + "torch._C._nn._conv_depthwise2d", + "torch._C._nn._pad_circular", + "torch._C._nn._pad_enum", + "torch._C._nn._test_ambiguous_defaults", + "torch._C._nn._test_optional_filled_intlist", + "torch._C._nn._test_optional_floatlist", + "torch._C._nn._test_optional_intlist", + "torch._C._nn._test_string_default", + "torch._C._nn._test_warn_in_autograd", + "torch._C._nn._upsample_bicubic2d_aa", + "torch._C._nn._upsample_bilinear2d_aa", + "torch._C._nn._upsample_lanczos2d_aa", + "torch._C._nn._upsample_nearest_exact1d", + "torch._C._nn._upsample_nearest_exact2d", + "torch._C._nn._upsample_nearest_exact3d", + "torch._C._nn.adaptive_avg_pool2d", + "torch._C._nn.adaptive_avg_pool3d", + "torch._C._nn.adaptive_max_pool2d", + "torch._C._nn.adaptive_max_pool3d", + "torch._C._nn.avg_pool2d", + "torch._C._nn.avg_pool3d", + "torch._C._nn.binary_cross_entropy", + "torch._C._nn.col2im", + "torch._C._nn.conv_depthwise3d", + "torch._C._nn.cross_entropy_loss", + "torch._C._nn.elu_", + "torch._C._nn.elu", + "torch._C._nn.flatten_dense_tensors", + "torch._C._nn.fractional_max_pool2d", + "torch._C._nn.fractional_max_pool3d", + "torch._C._nn.gelu_", + "torch._C._nn.gelu", + "torch._C._nn.glu", + "torch._C._nn.hardsigmoid_", + "torch._C._nn.hardsigmoid", + "torch._C._nn.hardswish_", + "torch._C._nn.hardswish", + "torch._C._nn.hardtanh_", + "torch._C._nn.hardtanh", + "torch._C._nn.huber_loss", + "torch._C._nn.im2col", + "torch._C._nn.l1_loss", + "torch._C._nn.leaky_relu_", + "torch._C._nn.leaky_relu", + "torch._C._nn.linear", + "torch._C._nn.log_sigmoid", + "torch._C._nn.max_pool2d_with_indices", + "torch._C._nn.max_pool3d_with_indices", + "torch._C._nn.max_unpool2d", + "torch._C._nn.max_unpool3d", + "torch._C._nn.mish_", + "torch._C._nn.mish", + "torch._C._nn.mkldnn_linear", + "torch._C._nn.mkldnn_reorder_conv2d_weight", + "torch._C._nn.mkldnn_reorder_conv3d_weight", + "torch._C._nn.mse_loss", + "torch._C._nn.multi_margin_loss", + "torch._C._nn.multilabel_margin_loss", + "torch._C._nn.nll_loss_nd", + "torch._C._nn.nll_loss", + "torch._C._nn.nll_loss2d", + "torch._C._nn.one_hot", + "torch._C._nn.pad_sequence", + "torch._C._nn.pad", + "torch._C._nn.reflection_pad1d", + "torch._C._nn.reflection_pad2d", + "torch._C._nn.reflection_pad3d", + "torch._C._nn.relu6_", + "torch._C._nn.relu6", + "torch._C._nn.replication_pad1d", + "torch._C._nn.replication_pad2d", + "torch._C._nn.replication_pad3d", + "torch._C._nn.rrelu_with_noise_", + "torch._C._nn.rrelu_with_noise", + "torch._C._nn.scaled_dot_product_attention", + "torch._C._nn.silu_", + "torch._C._nn.silu", + "torch._C._nn.slow_conv_dilated2d", + "torch._C._nn.slow_conv_dilated3d", + "torch._C._nn.slow_conv_transpose2d", + "torch._C._nn.slow_conv_transpose3d", + "torch._C._nn.slow_conv3d", + "torch._C._nn.smooth_l1_loss", + "torch._C._nn.soft_margin_loss", + "torch._C._nn.softplus", + "torch._C._nn.softshrink", + "torch._C._nn.thnn_conv2d", + "torch._C._nn.unflatten_dense_tensors", + "torch._C._nn.upsample_bicubic2d", + "torch._C._nn.upsample_bilinear2d", + "torch._C._nn.upsample_linear1d", + "torch._C._nn.upsample_nearest1d", + "torch._C._nn.upsample_nearest2d", + "torch._C._nn.upsample_nearest3d", + "torch._C._nn.upsample_trilinear3d", + "torch._C._non_sym_sizes", + "torch._C._overlaps", + "torch._C._parallel_info", + "torch._C._parse_dispatch_key", + "torch._C._parse_source_def", + "torch._C._pop_torch_dispatch_stack", + "torch._C._pop_torch_function_stack", + "torch._C._propagate_and_assign_input_shapes", + "torch._C._propagate_shapes", + "torch._C._propagate_xla_data", + "torch._C._push_on_torch_dispatch_stack", + "torch._C._push_on_torch_function_stack", + "torch._C._quantize_ondevice_ptq_dynamic", + "torch._C._register_py_class_for_device", + "torch._C._remove_cached_tensor", + "torch._C._remove_worker_pids", + "torch._C._rename_privateuse1_backend", + "torch._C._replace_", + "torch._C._replace_overloaded_method_decl", + "torch._C._resolve_type_from_object", + "torch._C._resolve_type", + "torch._C._rocm_is_backward_pass", + "torch._C._rpc_init", + "torch._C._run_emit_module_hook", + "torch._C._save_jit_module_to_bytes", + "torch._C._save_jit_module", + "torch._C._save_mobile_module_to_bytes", + "torch._C._save_mobile_module", + "torch._C._save_parameters", + "torch._C._scatter_out", + "torch._C._scatter", + "torch._C._select_conv_backend", + "torch._C._select_batch_norm_backend", + "torch._C._set_autograd_fallback_mode", + "torch._C._set_backcompat_broadcast_warn", + "torch._C._set_backcompat_keepdim_warn", + "torch._C._set_blas_preferred_backend", + "torch._C._set_cached_tensors_enabled", + "torch._C._set_check_sparse_tensor_invariants", + "torch._C._set_conj", + "torch._C._set_cublas_allow_bf16_reduced_precision_reduction", + "torch._C._set_cublas_allow_fp16_reduced_precision_reduction", + "torch._C._set_cublas_allow_tf32", + "torch._C._set_cudnn_allow_tf32", + "torch._C._set_cudnn_benchmark", + "torch._C._set_cudnn_deterministic", + "torch._C._set_cudnn_enabled", + "torch._C._set_default_dtype", + "torch._C._set_default_mobile_cpu_allocator", + "torch._C._set_default_tensor_type", + "torch._C._set_deterministic_algorithms", + "torch._C._set_deterministic_fill_uninitialized_memory", + "torch._C._set_dispatch_mode", + "torch._C._set_float32_matmul_precision", + "torch._C._set_fwd_grad_enabled", + "torch._C._set_grad_enabled", + "torch._C._set_graph_executor_optimize", + "torch._C._set_linalg_preferred_backend", + "torch._C._set_rocm_fa_preferred_backend", + "torch._C._set_meta_in_tls_dispatch_include", + "torch._C._set_mkldnn_enabled", + "torch._C._set_multithreading_enabled", + "torch._C._set_neg", + "torch._C._set_nnpack_enabled", + "torch._C._set_print_stack_traces_on_fatal_signal", + "torch._C._set_qengine", + "torch._C._set_sdp_use_flash", + "torch._C._set_sdp_use_math", + "torch._C._set_math_sdp_allow_fp16_bf16_reduction", + "torch._C._set_sdp_use_mem_efficient", + "torch._C._set_sdp_use_overrideable", + "torch._C._set_should_use_format_with_string_table", + "torch._C._set_sm_carveout_experimental", + "torch._C._set_storage_access_error_msg", + "torch._C._set_tensor_metadata", + "torch._C._set_tracing_state", + "torch._C._set_value_trace", + "torch._C._set_view_replay_enabled", + "torch._C._set_warnAlways", + "torch._C._set_worker_pids", + "torch._C._set_worker_signal_handlers", + "torch._C._should_allow_numbers_as_tensors", + "torch._C._show_config", + "torch._C._sparse._sparse_addmm", + "torch._C._sparse._sparse_log_softmax", + "torch._C._sparse._sparse_mm_reduce_impl", + "torch._C._sparse._sparse_mm", + "torch._C._sparse._sparse_softmax", + "torch._C._sparse._spdiags", + "torch._C._sparse.sparse_sampled_addmm", + "torch._C._special.special_airy_ai", + "torch._C._special.special_bessel_j0", + "torch._C._special.special_bessel_j1", + "torch._C._special.special_bessel_y0", + "torch._C._special.special_bessel_y1", + "torch._C._special.special_chebyshev_polynomial_t", + "torch._C._special.special_chebyshev_polynomial_u", + "torch._C._special.special_chebyshev_polynomial_v", + "torch._C._special.special_chebyshev_polynomial_w", + "torch._C._special.special_digamma", + "torch._C._special.special_entr", + "torch._C._special.special_erf", + "torch._C._special.special_erfc", + "torch._C._special.special_erfcx", + "torch._C._special.special_erfinv", + "torch._C._special.special_exp2", + "torch._C._special.special_expit", + "torch._C._special.special_expm1", + "torch._C._special.special_gammainc", + "torch._C._special.special_gammaincc", + "torch._C._special.special_gammaln", + "torch._C._special.special_hermite_polynomial_h", + "torch._C._special.special_hermite_polynomial_he", + "torch._C._special.special_i0", + "torch._C._special.special_i0e", + "torch._C._special.special_i1", + "torch._C._special.special_i1e", + "torch._C._special.special_laguerre_polynomial_l", + "torch._C._special.special_legendre_polynomial_p", + "torch._C._special.special_log_ndtr", + "torch._C._special.special_log_softmax", + "torch._C._special.special_log1p", + "torch._C._special.special_logit", + "torch._C._special.special_logsumexp", + "torch._C._special.special_modified_bessel_i0", + "torch._C._special.special_modified_bessel_i1", + "torch._C._special.special_modified_bessel_k0", + "torch._C._special.special_modified_bessel_k1", + "torch._C._special.special_multigammaln", + "torch._C._special.special_ndtr", + "torch._C._special.special_ndtri", + "torch._C._special.special_polygamma", + "torch._C._special.special_psi", + "torch._C._special.special_round", + "torch._C._special.special_scaled_modified_bessel_k0", + "torch._C._special.special_scaled_modified_bessel_k1", + "torch._C._special.special_shifted_chebyshev_polynomial_t", + "torch._C._special.special_shifted_chebyshev_polynomial_u", + "torch._C._special.special_shifted_chebyshev_polynomial_v", + "torch._C._special.special_shifted_chebyshev_polynomial_w", + "torch._C._special.special_sinc", + "torch._C._special.special_softmax", + "torch._C._special.special_spherical_bessel_j0", + "torch._C._special.special_xlog1py", + "torch._C._special.special_xlogy", + "torch._C._special.special_zeta", + "torch._C._stash_obj_in_tls", + "torch._C._storage_id", + "torch._C._storage_Use_Count", + "torch._C._supported_qengines", + "torch._C._te.abs", + "torch._C._te.acos", + "torch._C._te.annotate_input_shapes", + "torch._C._te.asin", + "torch._C._te.atan", + "torch._C._te.atan2", + "torch._C._te.ceil", + "torch._C._te.Compute", + "torch._C._te.Compute2", + "torch._C._te.construct_codegen", + "torch._C._te.cos", + "torch._C._te.cosh", + "torch._C._te.erf", + "torch._C._te.erfc", + "torch._C._te.exp", + "torch._C._te.expm1", + "torch._C._te.fixup_missing_shape_info", + "torch._C._te.floor", + "torch._C._te.fmod", + "torch._C._te.frac", + "torch._C._te.ifThenElse", + "torch._C._te.is_graph_compilable", + "torch._C._te.isnan", + "torch._C._te.lgamma", + "torch._C._te.log", + "torch._C._te.log10", + "torch._C._te.log1p", + "torch._C._te.log2", + "torch._C._te.lower", + "torch._C._te.make_shapes_symbolic", + "torch._C._te.pow", + "torch._C._te.Reduce", + "torch._C._te.remainder", + "torch._C._te.remove_graph_output", + "torch._C._te.remove_unused_self_argument", + "torch._C._te.replace_list_output_with_tuple", + "torch._C._te.round", + "torch._C._te.rsqrt", + "torch._C._te.sigmoid", + "torch._C._te.simplify", + "torch._C._te.sin", + "torch._C._te.sinh", + "torch._C._te.sqrt", + "torch._C._te.tan", + "torch._C._te.tanh", + "torch._C._te.trim_graph", + "torch._C._te.trunc", + "torch._C._tensor_impl_raw_handle", + "torch._C._test_only_add_entry_to_op_version_map", + "torch._C._test_only_populate_upgraders", + "torch._C._test_only_remove_entry_to_op_version_map", + "torch._C._test_only_remove_upgraders", + "torch._C._to_functionality_key", + "torch._C._tracer_set_force_outplace", + "torch._C._tracer_set_get_unique_name_fn", + "torch._C._tracer_warn_use_python", + "torch._C._unset_default_mobile_cpu_allocator", + "torch._C._unset_dispatch_mode", + "torch._C._valgrind_supported_platform", + "torch._C._valgrind_toggle_and_dump_stats", + "torch._C._valgrind_toggle", + "torch._C._verbose.mkl_set_verbose", + "torch._C._verbose.mkldnn_set_verbose", + "torch._C._vmapmode_decrement_nesting", + "torch._C._vmapmode_increment_nesting", + "torch._C._warn_deprecation", + "torch._C._warn", + "torch._C._will_engine_execute_node", + "torch._C._wrap_tensor_impl", + "torch._C._xpu_emptyCache", + "torch._C._xpu_getArchFlags", + "torch._C._xpu_getCurrentStream", + "torch._C._xpu_getCurrentRawStream", + "torch._C._xpu_getDeviceCount", + "torch._C._xpu_getDevice", + "torch._C._xpu_getMemoryInfo", + "torch._C._xpu_getStreamFromExternal", + "torch._C._xpu_isInBadFork", + "torch._C._xpu_init", + "torch._C._xpu_memoryStats", + "torch._C._xpu_resetAccumulatedMemoryStats", + "torch._C._xpu_resetPeakMemoryStats", + "torch._C._xpu_setStream", + "torch._C._xpu_synchronize", + "torch._C.autocast_decrement_nesting", + "torch._C.autocast_increment_nesting", + "torch._C.clear_autocast_cache", + "torch._C.fork", + "torch._C.get_autocast_cpu_dtype", + "torch._C.get_autocast_dtype", + "torch._C.get_autocast_gpu_dtype", + "torch._C.get_autocast_ipu_dtype", + "torch._C.get_autocast_xla_dtype", + "torch._C.get_default_dtype", + "torch._C.get_num_interop_threads", + "torch._C.get_num_threads", + "torch._C.import_ir_module_from_buffer", + "torch._C.import_ir_module", + "torch._C.init_num_threads", + "torch._C.is_anomaly_check_nan_enabled", + "torch._C.is_anomaly_enabled", + "torch._C.is_autocast_cache_enabled", + "torch._C.is_autocast_cpu_enabled", + "torch._C.is_autocast_enabled", + "torch._C.is_autocast_ipu_enabled", + "torch._C.is_autocast_xla_enabled", + "torch._C.is_grad_enabled", + "torch._C.is_inference_mode_enabled", + "torch._C.merge_type_from_type_comment", + "torch._C.parse_ir", + "torch._C.parse_schema", + "torch._C.parse_type_comment", + "torch._C.set_autocast_cache_enabled", + "torch._C.set_autocast_enabled", + "torch._C.unify_type_list", + "torch._C.wait", + "torch._cast_Byte", + "torch._cast_Char", + "torch._cast_Double", + "torch._cast_Float", + "torch._cast_Half", + "torch._cast_Int", + "torch._cast_Long", + "torch._cast_Short", + "torch._choose_qparams_per_tensor", + "torch._chunk_cat", + "torch._coalesce", + "torch._compute_linear_combination", + "torch._conj_copy", + "torch._conj_physical", + "torch._conj", + "torch._convert_indices_from_coo_to_csr", + "torch._convert_indices_from_csr_to_coo", + "torch._convert_weight_to_int4pack", + "torch._convert_weight_to_int4pack_for_cpu", + "torch._convolution_mode", + "torch._convolution", + "torch._copy_from_and_resize", + "torch._copy_from", + "torch._cslt_compress", + "torch._cslt_sparse_mm", + "torch._ctc_loss", + "torch._cudnn_ctc_loss", + "torch._cudnn_init_dropout_state", + "torch._cudnn_rnn_flatten_weight", + "torch._cudnn_rnn", + "torch._cufft_clear_plan_cache", + "torch._cufft_get_plan_cache_max_size", + "torch._cufft_get_plan_cache_size", + "torch._cufft_set_plan_cache_max_size", + "torch._cummax_helper", + "torch._cummin_helper", + "torch._debug_has_internal_overlap", + "torch._dim_arange", + "torch._dirichlet_grad", + "torch._disable_functionalization", + "torch._dyn_quant_matmul_4bit", + "torch._dyn_quant_pack_4bit_weight", + "torch._efficientzerotensor", + "torch._embedding_bag_forward_only", + "torch._embedding_bag", + "torch._empty_affine_quantized", + "torch._empty_per_channel_affine_quantized", + "torch._enable_functionalization", + "torch._euclidean_dist", + "torch._fake_quantize_learnable_per_channel_affine", + "torch._fake_quantize_learnable_per_tensor_affine", + "torch._fake_quantize_per_tensor_affine_cachemask_tensor_qparams", + "torch._fft_c2c", + "torch._fft_c2r", + "torch._fft_r2c", + "torch._fill_mem_eff_dropout_mask_", + "torch._foobar", + "torch._foreach_abs_", + "torch._foreach_abs", + "torch._foreach_acos_", + "torch._foreach_acos", + "torch._foreach_add_", + "torch._foreach_add", + "torch._foreach_addcdiv_", + "torch._foreach_addcdiv", + "torch._foreach_addcmul_", + "torch._foreach_addcmul", + "torch._foreach_asin_", + "torch._foreach_asin", + "torch._foreach_atan_", + "torch._foreach_atan", + "torch._foreach_ceil_", + "torch._foreach_ceil", + "torch._foreach_clamp_max_", + "torch._foreach_clamp_max", + "torch._foreach_clamp_min_", + "torch._foreach_clamp_min", + "torch._foreach_clone", + "torch._foreach_copy_", + "torch._foreach_cos_", + "torch._foreach_cos", + "torch._foreach_cosh_", + "torch._foreach_cosh", + "torch._foreach_div_", + "torch._foreach_div", + "torch._foreach_erf_", + "torch._foreach_erf", + "torch._foreach_erfc_", + "torch._foreach_erfc", + "torch._foreach_exp_", + "torch._foreach_exp", + "torch._foreach_expm1_", + "torch._foreach_expm1", + "torch._foreach_floor_", + "torch._foreach_floor", + "torch._foreach_frac_", + "torch._foreach_frac", + "torch._foreach_lerp_", + "torch._foreach_lerp", + "torch._foreach_lgamma_", + "torch._foreach_lgamma", + "torch._foreach_log_", + "torch._foreach_log", + "torch._foreach_log10_", + "torch._foreach_log10", + "torch._foreach_log1p_", + "torch._foreach_log1p", + "torch._foreach_log2_", + "torch._foreach_log2", + "torch._foreach_maximum_", + "torch._foreach_maximum", + "torch._foreach_minimum_", + "torch._foreach_minimum", + "torch._foreach_mul_", + "torch._foreach_mul", + "torch._foreach_neg_", + "torch._foreach_neg", + "torch._foreach_norm", + "torch._foreach_pow_", + "torch._foreach_pow", + "torch._foreach_reciprocal_", + "torch._foreach_reciprocal", + "torch._foreach_round_", + "torch._foreach_round", + "torch._foreach_sigmoid_", + "torch._foreach_sigmoid", + "torch._foreach_rsqrt_", + "torch._foreach_rsqrt", + "torch._foreach_sign_", + "torch._foreach_sign", + "torch._foreach_sin_", + "torch._foreach_sin", + "torch._foreach_sinh_", + "torch._foreach_sinh", + "torch._foreach_sqrt_", + "torch._foreach_sqrt", + "torch._foreach_sub_", + "torch._foreach_sub", + "torch._foreach_tan_", + "torch._foreach_tan", + "torch._foreach_tanh_", + "torch._foreach_tanh", + "torch._foreach_trunc_", + "torch._foreach_trunc", + "torch._foreach_zero_", + "torch._freeze_functional_tensor", + "torch._from_functional_tensor", + "torch._functional_assert_async", + "torch._functional_sym_constrain_range_for_size", + "torch._functional_sym_constrain_range", + "torch._functionalize_are_all_mutations_hidden_from_autograd", + "torch._functionalize_commit_update", + "torch._functionalize_enable_reapply_views", + "torch._functionalize_has_data_mutation", + "torch._functionalize_has_metadata_mutation", + "torch._functionalize_is_multi_output_view", + "torch._functionalize_mark_mutation_hidden_from_autograd", + "torch._functionalize_replace", + "torch._functionalize_sync", + "torch._functionalize_was_storage_changed", + "torch._fused_adagrad_", + "torch._fused_adam_", + "torch._fused_adamw_", + "torch._fused_dropout", + "torch._fused_moving_avg_obs_fq_helper", + "torch._fused_sdp_choice", + "torch._fw_primal_copy", + "torch._grid_sampler_2d_cpu_fallback", + "torch._grouped_mm", + "torch._histogramdd_bin_edges", + "torch._histogramdd_from_bin_cts", + "torch._histogramdd_from_bin_tensors", + "torch._index_put_impl_", + "torch._indices_copy", + "torch._int_mm", + "torch._is_all_true", + "torch._is_any_true", + "torch._is_functional_tensor", + "torch._is_zerotensor", + "torch._linalg_check_errors", + "torch._linalg_det", + "torch._linalg_eigh", + "torch._linalg_eigvals", + "torch._linalg_slogdet", + "torch._linalg_solve_ex", + "torch._linalg_svd", + "torch._log_softmax_backward_data", + "torch._log_softmax", + "torch._logcumsumexp", + "torch._lstm_mps", + "torch._lu_with_info", + "torch._make_dep_token", + "torch._make_dual_copy", + "torch._make_dual", + "torch._make_per_channel_quantized_tensor", + "torch._make_per_tensor_quantized_tensor", + "torch._masked_scale", + "torch._masked_softmax", + "torch._mirror_autograd_meta_to", + "torch._mixed_dtypes_linear", + "torch._mkldnn_reshape", + "torch._mkldnn_transpose_", + "torch._mkldnn_transpose", + "torch._mps_convolution_transpose", + "torch._mps_convolution", + "torch._native_batch_norm_legit_no_training", + "torch._native_batch_norm_legit", + "torch._native_multi_head_attention", + "torch._neg_view_copy", + "torch._neg_view", + "torch._nested_from_padded_and_nested_example", + "torch._nested_from_padded_tensor", + "torch._nested_tensor_from_mask_left_aligned", + "torch._nested_tensor_from_tensor_list", + "torch._nested_tensor_softmax_with_shape", + "torch._nested_view_from_buffer_copy", + "torch._nested_view_from_buffer", + "torch._nnpack_available", + "torch._nnpack_spatial_convolution", + "torch._pack_padded_sequence", + "torch._pad_packed_sequence", + "torch._pin_memory", + "torch._prelu_kernel", + "torch._propagate_xla_data", + "torch._remove_batch_dim", + "torch._reshape_alias_copy", + "torch._reshape_from_tensor", + "torch._resize_output_", + "torch._rowwise_prune", + "torch._sample_dirichlet", + "torch._saturate_weight_to_fp16", + "torch._scaled_dot_product_attention_math", + "torch._scaled_dot_product_efficient_attention", + "torch._scaled_dot_product_flash_attention", + "torch._scaled_dot_product_flash_attention_for_cpu", + "torch._scaled_dot_product_cudnn_attention", + "torch._scaled_mm", + "torch._scaled_mm_v2", + "torch._scaled_grouped_mm", + "torch._scaled_grouped_mm_v2", + "torch._shape_as_tensor", + "torch._sobol_engine_draw", + "torch._sobol_engine_ff_", + "torch._sobol_engine_initialize_state_", + "torch._sobol_engine_scramble_", + "torch._softmax_backward_data", + "torch._softmax", + "torch._sparse_broadcast_to_copy", + "torch._sparse_broadcast_to", + "torch._sparse_csr_prod", + "torch._sparse_csr_sum", + "torch._sparse_log_softmax_backward_data", + "torch._sparse_semi_structured_addmm", + "torch._sparse_semi_structured_linear", + "torch._sparse_semi_structured_mm", + "torch._sparse_softmax_backward_data", + "torch._sparse_sparse_matmul", + "torch._sparse_sum", + "torch._stack", + "torch._standard_gamma_grad", + "torch._standard_gamma", + "torch._test_autograd_multiple_dispatch_view_copy", + "torch._test_autograd_multiple_dispatch_view", + "torch._test_autograd_multiple_dispatch", + "torch._test_check_tensor", + "torch._test_functorch_fallback", + "torch._test_serialization_subcmul", + "torch._to_cpu", + "torch._to_functional_tensor", + "torch._to_sparse_semi_structured", + "torch._transform_bias_rescale_qkv", + "torch._transformer_encoder_layer_fwd", + "torch._trilinear", + "torch._triton_multi_head_attention", + "torch._triton_scaled_dot_attention", + "torch._unique", + "torch._unique2", + "torch._unpack_dual", + "torch._unsafe_index_put", + "torch._unsafe_index", + "torch._unsafe_masked_index_put_accumulate", + "torch._unsafe_masked_index", + "torch._use_cudnn_ctc_loss", + "torch._use_cudnn_rnn_flatten_weight", + "torch._values_copy", + "torch._weight_int4pack_mm", + "torch._weight_int4pack_mm_for_cpu", + "torch._weight_int4pack_mm_with_scales_and_zeros", + "torch._weight_int8pack_mm", + "torch._weight_norm_interface", + "torch._weight_norm", + "torch.abs_", + "torch.abs", + "torch.absolute", + "torch.acos_", + "torch.acos", + "torch.acosh_", + "torch.acosh", + "torch.adaptive_avg_pool1d", + "torch.adaptive_max_pool1d", + "torch.add", + "torch.addbmm", + "torch.addcdiv", + "torch.addcmul", + "torch.addmm", + "torch.addmv_", + "torch.addmv", + "torch.addr", + "torch.adjoint", + "torch.affine_grid_generator", + "torch.alias_copy", + "torch.all", + "torch.allclose", + "torch.alpha_dropout_", + "torch.alpha_dropout", + "torch.amax", + "torch.amin", + "torch.aminmax", + "torch.angle", + "torch.any", + "torch.arange", + "torch.arccos_", + "torch.arccos", + "torch.arccosh_", + "torch.arccosh", + "torch.arcsin_", + "torch.arcsin", + "torch.arcsinh_", + "torch.arcsinh", + "torch.arctan_", + "torch.arctan", + "torch.arctan2", + "torch.arctanh_", + "torch.arctanh", + "torch.argmax", + "torch.argmin", + "torch.argsort", + "torch.argwhere", + "torch.as_strided_", + "torch.as_strided_copy", + "torch.as_strided_scatter", + "torch.as_strided", + "torch.as_tensor", + "torch.asarray", + "torch.asin_", + "torch.asin", + "torch.asinh_", + "torch.asinh", + "torch.atan_", + "torch.atan", + "torch.atan2", + "torch.atanh_", + "torch.atanh", + "torch.avg_pool1d", + "torch.baddbmm", + "torch.bartlett_window", + "torch.batch_norm_backward_elemt", + "torch.batch_norm_backward_reduce", + "torch.batch_norm_elemt", + "torch.batch_norm_gather_stats_with_counts", + "torch.batch_norm_gather_stats", + "torch.batch_norm_stats", + "torch.batch_norm_update_stats", + "torch.batch_norm", + "torch.bernoulli", + "torch.bilinear", + "torch.binary_cross_entropy_with_logits", + "torch.bincount", + "torch.binomial", + "torch.bitwise_and", + "torch.bitwise_left_shift", + "torch.bitwise_not", + "torch.bitwise_or", + "torch.bitwise_right_shift", + "torch.bitwise_xor", + "torch.blackman_window", + "torch.bmm", + "torch.broadcast_to", + "torch.bucketize", + "torch.can_cast", + "torch.cat", + "torch.ccol_indices_copy", + "torch.ceil_", + "torch.ceil", + "torch.celu_", + "torch.celu", + "torch.channel_shuffle", + "torch.cholesky_inverse", + "torch.cholesky_solve", + "torch.choose_qparams_optimized", + "torch.chunk", + "torch.clamp_", + "torch.clamp_max_", + "torch.clamp_max", + "torch.clamp_min_", + "torch.clamp_min", + "torch.clamp", + "torch.clip_", + "torch.clip", + "torch.clone", + "torch.col_indices_copy", + "torch.column_stack", + "torch.combinations", + "torch.complex", + "torch.concat", + "torch.concatenate", + "torch.conj_physical_", + "torch.conj_physical", + "torch.conj", + "torch.constant_pad_nd", + "torch.conv_tbc", + "torch.conv_transpose1d", + "torch.conv_transpose2d", + "torch.conv_transpose3d", + "torch.conv1d", + "torch.conv2d", + "torch.conv3d", + "torch.convolution", + "torch.copysign", + "torch.corrcoef", + "torch.cos_", + "torch.cos", + "torch.cosh_", + "torch.cosh", + "torch.cosine_embedding_loss", + "torch.cosine_similarity", + "torch.count_nonzero", + "torch.cov", + "torch.cross", + "torch.crow_indices_copy", + "torch.ctc_loss", + "torch.cudnn_affine_grid_generator", + "torch.cudnn_batch_norm", + "torch.cudnn_convolution_add_relu", + "torch.cudnn_convolution_relu", + "torch.cudnn_convolution_transpose", + "torch.cudnn_convolution", + "torch.cudnn_grid_sampler", + "torch.cudnn_is_acceptable", + "torch.cummax", + "torch.cummin", + "torch.cumprod", + "torch.cumsum", + "torch.cumulative_trapezoid", + "torch.deg2rad_", + "torch.deg2rad", + "torch.dequantize", + "torch.det", + "torch.detach_", + "torch.detach_copy", + "torch.detach", + "torch.diag_embed", + "torch.diag", + "torch.diagflat", + "torch.diagonal_copy", + "torch.diagonal_scatter", + "torch.diagonal", + "torch.diff", + "torch.digamma", + "torch.dist", + "torch.div", + "torch.divide", + "torch.dot", + "torch.dropout_", + "torch.dropout", + "torch.dsmm", + "torch.dsplit", + "torch.dstack", + "torch.embedding_bag", + "torch.embedding_renorm_", + "torch.embedding", + "torch.empty_like", + "torch.empty_permuted", + "torch.empty_quantized", + "torch.empty_strided", + "torch.empty", + "torch.eq", + "torch.equal", + "torch.erf_", + "torch.erf", + "torch.erfc_", + "torch.erfc", + "torch.erfinv", + "torch.exp_", + "torch.exp", + "torch.exp2_", + "torch.exp2", + "torch.expand_copy", + "torch.expm1_", + "torch.expm1", + "torch.eye", + "torch.fake_quantize_per_channel_affine", + "torch.fake_quantize_per_tensor_affine", + "torch.fbgemm_linear_fp16_weight_fp32_activation", + "torch.fbgemm_linear_fp16_weight", + "torch.fbgemm_linear_int8_weight_fp32_activation", + "torch.fbgemm_linear_int8_weight", + "torch.fbgemm_linear_quantize_weight", + "torch.fbgemm_pack_gemm_matrix_fp16", + "torch.fbgemm_pack_quantized_matrix", + "torch.feature_alpha_dropout_", + "torch.feature_alpha_dropout", + "torch.feature_dropout_", + "torch.feature_dropout", + "torch.fill_", + "torch.fill", + "torch.fix_", + "torch.fix", + "torch.flatten", + "torch.flip", + "torch.fliplr", + "torch.flipud", + "torch.float_power", + "torch.floor_", + "torch.floor_divide", + "torch.floor", + "torch.fmax", + "torch.fmin", + "torch.fmod", + "torch.frac_", + "torch.frac", + "torch.frexp", + "torch.frobenius_norm", + "torch.from_file", + "torch.from_numpy", + "torch.frombuffer", + "torch.full_like", + "torch.full", + "torch.fused_moving_avg_obs_fake_quant", + "torch.gather", + "torch.gcd_", + "torch.gcd", + "torch.ge", + "torch.geqrf", + "torch.ger", + "torch.get_device", + "torch.get_device_module", + "torch.gradient", + "torch.greater_equal", + "torch.greater", + "torch.grid_sampler_2d", + "torch.grid_sampler_3d", + "torch.grid_sampler", + "torch.group_norm", + "torch.gru_cell", + "torch.gru", + "torch.gt", + "torch.hamming_window", + "torch.hann_window", + "torch.hardshrink", + "torch.hash_tensor", + "torch.heaviside", + "torch.hinge_embedding_loss", + "torch.histc", + "torch.histogram", + "torch.histogramdd", + "torch.hsmm", + "torch.hsplit", + "torch.hspmm", + "torch.hstack", + "torch.hypot", + "torch.i0_", + "torch.i0", + "torch.igamma", + "torch.igammac", + "torch.imag", + "torch.index_add", + "torch.index_copy", + "torch.index_fill", + "torch.index_put_", + "torch.index_put", + "torch.index_reduce", + "torch.index_select", + "torch.indices_copy", + "torch.inner", + "torch.instance_norm", + "torch.int_repr", + "torch.inverse", + "torch.is_complex", + "torch.is_conj", + "torch.is_distributed", + "torch.is_floating_point", + "torch.is_inference", + "torch.is_neg", + "torch.is_nonzero", + "torch.is_same_size", + "torch.is_signed", + "torch.is_vulkan_available", + "torch.isclose", + "torch.isfinite", + "torch.isin", + "torch.isinf", + "torch.isnan", + "torch.isneginf", + "torch.isposinf", + "torch.isreal", + "torch.istft", + "torch.kaiser_window", + "torch.kl_div", + "torch.kron", + "torch.kthvalue", + "torch.layer_norm", + "torch.lcm_", + "torch.lcm", + "torch.ldexp_", + "torch.ldexp", + "torch.le", + "torch.lerp", + "torch.less_equal", + "torch.less", + "torch.lgamma", + "torch.linspace", + "torch.log_", + "torch.log_softmax", + "torch.log", + "torch.log10_", + "torch.log10", + "torch.log1p_", + "torch.log1p", + "torch.log2_", + "torch.log2", + "torch.logaddexp", + "torch.logaddexp2", + "torch.logcumsumexp", + "torch.logdet", + "torch.logical_and", + "torch.logical_not", + "torch.logical_or", + "torch.logical_xor", + "torch.logit_", + "torch.logit", + "torch.logspace", + "torch.logsumexp", + "torch.lstm_cell", + "torch.lstm", + "torch.lt", + "torch.lu_solve", + "torch.lu_unpack", + "torch.margin_ranking_loss", + "torch.masked_fill", + "torch.masked_scatter", + "torch.masked_select", + "torch.matmul", + "torch.matrix_exp", + "torch.matrix_power", + "torch.max_pool1d_with_indices", + "torch.max_pool1d", + "torch.max_pool2d", + "torch.max_pool3d", + "torch.max", + "torch.maximum", + "torch.mean", + "torch.median", + "torch.min", + "torch.minimum", + "torch.miopen_batch_norm", + "torch.miopen_convolution_add_relu", + "torch.miopen_convolution_relu", + "torch.miopen_convolution_transpose", + "torch.miopen_convolution", + "torch.miopen_depthwise_convolution", + "torch.miopen_rnn", + "torch.mkldnn_adaptive_avg_pool2d", + "torch.mkldnn_convolution", + "torch.mkldnn_linear_backward_weights", + "torch.mkldnn_max_pool2d", + "torch.mkldnn_max_pool3d", + "torch.mkldnn_rnn_layer", + "torch.mm", + "torch.mode", + "torch.moveaxis", + "torch.movedim", + "torch.msort", + "torch.mul", + "torch.multinomial", + "torch.multiply", + "torch.mv", + "torch.mvlgamma", + "torch.nan_to_num_", + "torch.nan_to_num", + "torch.nanmean", + "torch.nanmedian", + "torch.nanquantile", + "torch.nansum", + "torch.narrow_copy", + "torch.narrow", + "torch.native_batch_norm", + "torch.native_channel_shuffle", + "torch.native_dropout", + "torch.native_group_norm", + "torch.native_layer_norm", + "torch.native_norm", + "torch.ne", + "torch.neg_", + "torch.neg", + "torch.negative_", + "torch.negative", + "torch.nextafter", + "torch.nonzero_static", + "torch.nonzero", + "torch.norm_except_dim", + "torch.normal", + "torch.not_equal", + "torch.nuclear_norm", + "torch.numel", + "torch.ones_like", + "torch.ones", + "torch.orgqr", + "torch.ormqr", + "torch.outer", + "torch.pairwise_distance", + "torch.pdist", + "torch.permute_copy", + "torch.permute", + "torch.pinverse", + "torch.pixel_shuffle", + "torch.pixel_unshuffle", + "torch.poisson_nll_loss", + "torch.poisson", + "torch.polar", + "torch.polygamma", + "torch.positive", + "torch.pow", + "torch.prelu", + "torch._print", + "torch.prod", + "torch.promote_types", + "torch.put", + "torch.q_per_channel_axis", + "torch.q_per_channel_scales", + "torch.q_per_channel_zero_points", + "torch.q_scale", + "torch.q_zero_point", + "torch.quantile", + "torch.quantize_per_channel", + "torch.quantize_per_tensor_dynamic", + "torch.quantize_per_tensor", + "torch.quantized_batch_norm", + "torch.quantized_gru_cell", + "torch.quantized_lstm_cell", + "torch.quantized_max_pool1d", + "torch.quantized_max_pool2d", + "torch.quantized_max_pool3d", + "torch.quantized_rnn_relu_cell", + "torch.quantized_rnn_tanh_cell", + "torch.rad2deg_", + "torch.rad2deg", + "torch.rand_like", + "torch.rand", + "torch.randint_like", + "torch.randint", + "torch.randn_like", + "torch.randn", + "torch.randperm", + "torch.range", + "torch.ravel", + "torch.real", + "torch.reciprocal_", + "torch.reciprocal", + "torch.relu_", + "torch.relu", + "torch.remainder", + "torch.renorm", + "torch.repeat_interleave", + "torch.reshape", + "torch.resolve_conj", + "torch.resolve_neg", + "torch.result_type", + "torch.rms_norm", + "torch.rnn_relu_cell", + "torch.rnn_relu", + "torch.rnn_tanh_cell", + "torch.rnn_tanh", + "torch.roll", + "torch.rot90", + "torch.round_", + "torch.round", + "torch.row_indices_copy", + "torch.row_stack", + "torch.rrelu_", + "torch.rrelu", + "torch.rsqrt_", + "torch.rsqrt", + "torch.rsub", + "torch.saddmm", + "torch.scalar_tensor", + "torch.scatter_add", + "torch.scatter_reduce", + "torch.scatter", + "torch.searchsorted", + "torch.segment_reduce", + "torch.select_copy", + "torch.select_scatter", + "torch.select", + "torch.selu_", + "torch.selu", + "torch.set_autocast_dtype", + "torch.sgn", + "torch.sigmoid_", + "torch.sigmoid", + "torch.sign", + "torch.signal.windows.windows.sqrt", + "torch.signbit", + "torch.sin_", + "torch.sin", + "torch.sinc_", + "torch.sinc", + "torch.sinh_", + "torch.sinh", + "torch.slice_copy", + "torch.slice_scatter", + "torch.slogdet", + "torch.smm", + "torch.softmax", + "torch.sort", + "torch.split_copy", + "torch.split_with_sizes_copy", + "torch.split_with_sizes", + "torch.spmm", + "torch.sqrt_", + "torch.sqrt", + "torch.square_", + "torch.square", + "torch.squeeze_copy", + "torch.squeeze", + "torch.sspaddmm", + "torch.stack", + "torch.std_mean", + "torch.std", + "torch.sub", + "torch.subtract", + "torch.sum", + "torch.svd", + "torch.swapaxes", + "torch.swapdims", + "torch.sym_constrain_range_for_size", + "torch.sym_constrain_range", + "torch.t_copy", + "torch.t", + "torch.take_along_dim", + "torch.take", + "torch.tan_", + "torch.tan", + "torch.tanh_", + "torch.tanh", + "torch.tensor_split", + "torch.tensor", + "torch.threshold_", + "torch.threshold", + "torch.tile", + "torch.topk", + "torch.trace", + "torch.transpose_copy", + "torch.transpose", + "torch.trapezoid", + "torch.trapz", + "torch.triangular_solve", + "torch.tril_indices", + "torch.tril", + "torch.triplet_margin_loss", + "torch.triu_indices", + "torch.triu", + "torch.true_divide", + "torch.trunc_", + "torch.trunc", + "torch.unbind_copy", + "torch.unbind", + "torch.unflatten", + "torch.unfold_copy", + "torch.unsafe_chunk", + "torch.unsafe_split_with_sizes", + "torch.unsafe_split", + "torch.unsqueeze_copy", + "torch.unsqueeze", + "torch.values_copy", + "torch.vander", + "torch.var_mean", + "torch.var", + "torch.vdot", + "torch.view_as_complex_copy", + "torch.view_as_complex", + "torch.view_as_real_copy", + "torch.view_as_real", + "torch.view_copy", + "torch.vsplit", + "torch.vstack", + "torch.where", + "torch.xlogy_", + "torch.xlogy", + "torch.zero_", + "torch.zeros", + "torch.zeros_like", + "torch._fused_sgd_", + "torch.slice_inverse", + "torch._assert_scalar", + "torch._functional_assert_scalar", + "torch.xpu._get_device_properties", + ], + TorchInGraphFunctionVariable, +) + + +if sys.version_info >= (3, 11): + torch_c_binding_in_graph_functions["math.exp2"] = TorchInGraphFunctionVariable + torch_c_binding_in_graph_functions["math.cbrt"] = TorchInGraphFunctionVariable + +if sys.version_info >= (3, 13): + torch_c_binding_in_graph_functions["math.fma"] = TorchInGraphFunctionVariable + +# In graph functions (including constant folding) that are not C bindings +# NOTE: [Cacheability of in-graph torch functions] +# Functions in this list have the property that graphs containing them are safe to cache/serialize. +# serialize given only the information in the graph. I.e, either: +# - Your function does not access or close over global state, or +# - Your function closes over global state, but this state is guarded by dynamo, either +# through constant folding or other mechanisms +# If your function needs a custom special handler (via @register on TorchInGraphFunctionVariable), +# or captures global state, please add it to manual_torch_name_rule_map instead +torch_non_c_binding_in_graph_functions = dict.fromkeys( + [ + "torch.__future__.get_overwrite_module_params_on_conversion", + "torch.__future__.set_overwrite_module_params_on_conversion", + "torch.__getattr__", + "torch._assert", + "torch._check_is_size", + "torch._compile._disable_dynamo", + "torch._functorch.apis.chunk_vmap", + "torch._functorch.batch_norm_replacement.batch_norm_without_running_stats", + "torch._functorch.batch_norm_replacement.replace_all_batch_norm_modules_", + "torch._functorch.deprecated.combine_state_for_ensemble", + "torch._functorch.deprecated.functionalize", + "torch._functorch.deprecated.get_warning", + "torch._functorch.deprecated.make_functional_with_buffers", + "torch._functorch.deprecated.make_functional", + "torch._functorch.deprecated.setup_docs", + "torch._functorch.deprecated.warn_deprecated", + "torch._functorch.eager_transforms._any_differentiable", + "torch._functorch.eager_transforms._autograd_grad", + "torch._functorch.eager_transforms._set_tensor_requires_grad", + "torch._functorch.eager_transforms._is_differentiable", + "torch._functorch.eager_transforms._maybe_unwrap_functional_tensor", + "torch._functorch.eager_transforms._maybe_wrap_functional_tensor", + "torch._functorch.eager_transforms._unwrap_all_tensors_from_functional", + "torch._functorch.eager_transforms._wrap_all_tensors_to_functional", + "torch._functorch.eager_transforms.assert_flat_tuple_of_tensors", + "torch._functorch.eager_transforms.functionalize", + "torch._functorch.eager_transforms.lazy_dynamo_disable", + "torch._functorch.eager_transforms.noop", + "torch._functorch.utils.enable_single_level_autograd_function", + "torch._functorch.utils.exposed_in", + "torch._functorch.predispatch.lazy_load_decompositions", + "torch._functorch.predispatch._vmap_increment_nesting", + "torch._functorch.predispatch._vmap_decrement_nesting", + "torch._functorch.predispatch._add_batch_dim", + "torch._functorch.predispatch._remove_batch_dim", + "torch._functorch.predispatch._unwrap_for_grad", + "torch._functorch.predispatch._make_dual", + "torch._functorch.predispatch._unpack_dual", + "torch._guards.compile_context", + "torch._guards.detect_fake_mode", + "torch._guards.tracing", + "torch._higher_order_ops.map._has_potential_branch_input_alias", + "torch._higher_order_ops.map._has_potential_branch_input_mutation", + "torch._higher_order_ops.map._stack_pytree", + "torch._higher_order_ops.map._unstack_pytree", + "torch._higher_order_ops.map.create_fw_bw_graph", + "torch._higher_order_ops.map.map_autograd", + "torch._higher_order_ops.map.map_dense", + "torch._higher_order_ops.map.map_fake_tensor_mode", + "torch._higher_order_ops.map.map_functionalize", + "torch._higher_order_ops.map.map_proxy_torch_dispatch_mode", + "torch._higher_order_ops.map.map_wrapper", + "torch._higher_order_ops.map.trace_map", + "torch._higher_order_ops.out_dtype.elementwise_dtypes", + "torch._higher_order_ops.out_dtype.is_int_mm", + "torch._higher_order_ops.out_dtype.out_dtype_dense", + "torch._higher_order_ops.out_dtype.out_dtype_fake_tensor_mode", + "torch._higher_order_ops.out_dtype.out_dtype_fallback", + "torch._higher_order_ops.out_dtype.out_dtype_func", + "torch._higher_order_ops.out_dtype.out_dtype_proxy", + "torch._higher_order_ops.out_dtype.trace_out_dtype", + "torch._higher_order_ops.utils.autograd_not_implemented_inner", + "torch._higher_order_ops.utils.autograd_not_implemented", + "torch._linalg_utils._symeig", + "torch._linalg_utils.basis", + "torch._linalg_utils.bform", + "torch._linalg_utils.eig", + "torch._linalg_utils.get_floating_dtype", + "torch._linalg_utils.is_sparse", + "torch._linalg_utils.lstsq", + "torch._linalg_utils.matmul", + "torch._linalg_utils.matrix_rank", + "torch._linalg_utils.qform", + "torch._linalg_utils.solve", + "torch._linalg_utils.symeig", + "torch._load_global_deps", + "torch._lowrank._svd_lowrank", + "torch._lowrank.get_approximate_basis", + "torch._lowrank.pca_lowrank", + "torch._lowrank.svd_lowrank", + "torch._preload_cuda_deps", + "torch._register_device_module", + "torch._utils._dummy_type", + "torch._utils._flatten_dense_tensors", + "torch._utils._unflatten_dense_tensors", + "torch._weights_only_unpickler._get_allowed_globals", + "torch._weights_only_unpickler.load", + "torch.accelerator.current_accelerator", + "torch.accelerator.current_device_index", + "torch.accelerator.current_stream", + "torch.accelerator.device_count", + "torch.accelerator.is_available", + "torch.accelerator.set_stream", + "torch.accelerator.synchronize", + "torch.amp.autocast_mode.autocast_decorator", + "torch.amp.autocast_mode.custom_bwd", + "torch.amp.autocast_mode.custom_fwd", + "torch.are_deterministic_algorithms_enabled", + "torch.atleast_1d", + "torch.atleast_2d", + "torch.atleast_3d", + "torch.autograd._calculate_shape", + "torch.autograd._is_checkpoint_valid", + "torch.autograd._profiler_enabled", + "torch.autograd._make_grads", + "torch.autograd._register_py_tensor_class_for_device", + "torch.autograd._tensor_or_tensors_to_tuple", + "torch.autograd.forward_ad._maybe_load_decompositions", + "torch.autograd.function._iter_filter", + "torch.autograd.function._iter_jit_values", + "torch.autograd.function._iter_None_tensors", + "torch.autograd.function._iter_tensors_permissive", + "torch.autograd.function._iter_tensors", + "torch.autograd.function._jit_unwrap_structured", + "torch.autograd.function._map_tensor_data", + "torch.autograd.function._nested_map", + "torch.autograd.function._unflatten", + "torch.autograd.function.once_differentiable", + "torch.autograd.function.traceable", + "torch.autograd.functional._as_tuple_nocheck", + "torch.autograd.functional._as_tuple", + "torch.autograd.functional._autograd_grad", + "torch.autograd.functional._check_requires_grad", + "torch.autograd.functional._construct_standard_basis_for", + "torch.autograd.functional._fill_in_zeros", + "torch.autograd.functional._grad_postprocess", + "torch.autograd.functional._grad_preprocess", + "torch.autograd.functional._jacfwd", + "torch.autograd.functional._tuple_postprocess", + "torch.autograd.functional._validate_v", + "torch.autograd.functional.hessian", + "torch.autograd.functional.hvp", + "torch.autograd.functional.jacobian", + "torch.autograd.functional.jvp", + "torch.autograd.functional.vhp", + "torch.autograd.functional.vjp", + "torch.autograd.graph._get_sid", + "torch.autograd.graph._get_tid", + "torch.autograd.graph.allow_mutation_on_saved_tensors", + "torch.autograd.graph.get_gradient_edge", + "torch.autograd.graph.increment_version", + "torch.autograd.graph.register_multi_grad_hook", + "torch.autograd.variable", + "torch.backends.__allow_nonbracketed_mutation", + "torch.backends.cpu.get_cpu_capability", + "torch.backends.cuda.can_use_efficient_attention", + "torch.backends.cuda.can_use_flash_attention", + "torch.backends.cuda.can_use_cudnn_attention", + "torch.backends.cuda.enable_flash_sdp", + "torch.backends.cuda.enable_math_sdp", + "torch.backends.cuda.allow_fp16_bf16_reduction_math_sdp", + "torch.backends.cuda.enable_mem_efficient_sdp", + "torch.backends.cuda.flash_sdp_enabled", + "torch.backends.cuda.is_built", + "torch.backends.cuda.is_flash_attention_available", + "torch.backends.cuda.math_sdp_enabled", + "torch.backends.cuda.fp16_bf16_reduction_math_sdp_allowed", + "torch.backends.cuda.mem_efficient_sdp_enabled", + "torch.backends.cuda.cudnn_sdp_enabled", + "torch.backends.cuda.enable_cudnn_sdp", + "torch.backends.cuda.preferred_blas_library", + "torch.backends.cuda.preferred_linalg_library", + "torch.backends.cuda.preferred_rocm_fa_library", + "torch.backends.cuda.sdp_kernel", + "torch.backends.cudnn._init", + "torch.backends.cudnn.flags", + "torch.backends.cudnn.is_acceptable", + "torch.backends.cudnn.is_available", + "torch.backends.cudnn.set_flags", + "torch.backends.cudnn.version", + "torch.backends.disable_global_flags", + "torch.backends.flags_frozen", + "torch.backends.mkl.is_available", + "torch.backends.mkldnn.flags", + "torch.backends.mkldnn.is_available", + "torch.backends.mkldnn.set_flags", + "torch.backends.mps._init", + "torch.backends.mps.is_available", + "torch.backends.mps.is_built", + "torch.backends.mps.is_macos13_or_newer", + "torch.backends.openmp.is_available", + "torch.backends.quantized._get_qengine_id", + "torch.backends.quantized._get_qengine_str", + "torch.block_diag", + "torch.broadcast_tensors", + "torch.cartesian_prod", + "torch.cdist", + "torch.chain_matmul", + "torch.compile", + "torch.compiled_with_cxx11_abi", + "torch.cpu._init_amx", + "torch.cpu.get_capabilities", + "torch.cpu.current_device", + "torch.cpu.current_stream", + "torch.cpu.device_count", + "torch.cpu.is_available", + "torch.cpu.set_device", + "torch.cpu.stream", + "torch.cpu.synchronize", + "torch.cuda._check_capability", + "torch.cuda._check_cubins", + "torch.cuda._device_count_amdsmi", + "torch.cuda._device_count_nvml", + "torch.cuda._get_amdsmi_handler", + "torch.cuda._get_amdsmi_device_index", + "torch.cuda._get_device", + "torch.cuda._get_generator", + "torch.cuda._get_nvml_device_index", + "torch.cuda._get_pynvml_handler", + "torch.cuda._get_rng_state_offset", + "torch.cuda._is_compiled", + "torch.cuda._lazy_call", + "torch.cuda._lazy_init", + "torch.cuda._memory_viz._block_extra_legacy", + "torch.cuda._memory_viz._block_extra", + "torch.cuda._memory_viz._format_size", + "torch.cuda._memory_viz._format_viz", + "torch.cuda._memory_viz._frame_filter", + "torch.cuda._memory_viz._frame_fmt", + "torch.cuda._memory_viz._frames_fmt", + "torch.cuda._memory_viz._profile_to_snapshot", + "torch.cuda._memory_viz._report_free", + "torch.cuda._memory_viz._write_blocks", + "torch.cuda._memory_viz.calc_active", + "torch.cuda._memory_viz.compare", + "torch.cuda._memory_viz.format_flamegraph", + "torch.cuda._memory_viz.memory", + "torch.cuda._memory_viz.profile_plot", + "torch.cuda._memory_viz.segment_plot", + "torch.cuda._memory_viz.segments", + "torch.cuda._memory_viz.segsum", + "torch.cuda._memory_viz.trace_plot", + "torch.cuda._memory_viz.trace", + "torch.cuda._nvml_based_avail", + "torch.cuda._parse_visible_devices", + "torch.cuda._raw_device_count_amdsmi", + "torch.cuda._raw_device_count_nvml", + "torch.cuda._raw_device_uuid_amdsmi", + "torch.cuda._raw_device_uuid_nvml", + "torch.cuda._register_triton_kernels", + "torch.cuda._set_rng_state_offset", + "torch.cuda._set_stream_by_id", + "torch.cuda._sleep", + "torch.cuda._transform_uuid_to_ordinals", + "torch.cuda._utils._get_device_index", + "torch.cuda.amp.autocast_mode._cast", + "torch.cuda.amp.autocast_mode.custom_bwd", + "torch.cuda.amp.autocast_mode.custom_fwd", + "torch.cuda.amp.common.amp_definitely_not_available", + "torch.amp.grad_scaler._refresh_per_optimizer_state", + "torch.cuda.can_device_access_peer", + "torch.cuda.check_error", + "torch.cuda.clock_rate", + "torch.cuda.cudart", + "torch.cuda.current_blas_handle", + "torch.cuda.current_solver_handle", + "torch.cuda.current_stream", + "torch.cuda.default_stream", + "torch.cuda.device_count", + "torch.cuda.device_memory_used", + "torch.cuda.get_arch_list", + "torch.cuda.get_device_capability", + "torch.cuda.get_device_name", + "torch.cuda.get_device_properties", + "torch.cuda.get_gencode_flags", + "torch.cuda.get_sync_debug_mode", + "torch.cuda.synchronize", + "torch.cuda.graphs.graph_pool_handle", + "torch.cuda.graphs.is_current_stream_capturing", + "torch.cuda.graphs.make_graphed_callables", + "torch.cuda.init", + "torch.cuda.ipc_collect", + "torch.cuda.is_available", + "torch.cuda.is_bf16_supported", + "torch.cuda.is_initialized", + "torch.cuda.jiterator._create_jit_fn", + "torch.cuda.jiterator._create_multi_output_jit_fn", + "torch.cuda.memory_usage", + "torch.cuda.memory._dump_snapshot", + "torch.cuda.memory._get_current_allocator", + "torch.cuda.memory._host_allocator", + "torch.cuda.memory._record_memory_history_impl", + "torch.cuda.memory._record_memory_history_legacy", + "torch.cuda.memory._record_memory_history", + "torch.cuda.memory._save_memory_usage", + "torch.cuda.memory._save_segment_usage", + "torch.cuda.memory._set_allocator_settings", + "torch.cuda.memory._snapshot", + "torch.cuda.memory.caching_allocator_alloc", + "torch.cuda.memory.caching_allocator_delete", + "torch.cuda.memory.caching_allocator_enable", + "torch.cuda.memory.change_current_allocator", + "torch.cuda.memory.empty_cache", + "torch.cuda.memory.get_allocator_backend", + "torch.cuda.memory.get_per_process_memory_fraction", + "torch.cuda.memory.host_memory_stats_as_nested_dict", + "torch.cuda.memory.host_memory_stats", + "torch.cuda.memory.list_gpu_processes", + "torch.cuda.memory.max_memory_allocated", + "torch.cuda.memory.max_memory_cached", + "torch.cuda.memory.max_memory_reserved", + "torch.cuda.memory.mem_get_info", + "torch.cuda.memory.memory_allocated", + "torch.cuda.memory.memory_cached", + "torch.cuda.memory.memory_reserved", + "torch.cuda.memory.memory_snapshot", + "torch.cuda.memory.memory_stats_as_nested_dict", + "torch.cuda.memory.memory_stats", + "torch.cuda.memory.memory_summary", + "torch.cuda.memory.reset_accumulated_host_memory_stats", + "torch.cuda.memory.reset_accumulated_memory_stats", + "torch.cuda.memory.reset_max_memory_allocated", + "torch.cuda.memory.reset_max_memory_cached", + "torch.cuda.memory.reset_peak_host_memory_stats", + "torch.cuda.memory.reset_peak_memory_stats", + "torch.cuda.memory.set_per_process_memory_fraction", + "torch.cuda.nccl._check_sequence_type", + "torch.cuda.nccl.all_gather", + "torch.cuda.nccl.all_reduce", + "torch.cuda.nccl.broadcast", + "torch.cuda.nccl.init_rank", + "torch.cuda.nccl.is_available", + "torch.cuda.nccl.reduce_scatter", + "torch.cuda.nccl.reduce", + "torch.cuda.nccl.unique_id", + "torch.cuda.nccl.version", + "torch.cuda.nvtx.mark", + "torch.cuda.nvtx.range_end", + "torch.cuda.nvtx.range_pop", + "torch.cuda.nvtx.range_push", + "torch.cuda.nvtx.range_start", + "torch.cuda.nvtx.range", + "torch.cuda.power_draw", + "torch.cuda.profiler.init", + "torch.cuda.profiler.profile", + "torch.cuda.profiler.start", + "torch.cuda.profiler.stop", + "torch.cuda.random.get_rng_state_all", + "torch.cuda.random.initial_seed", + "torch.cuda.random.seed_all", + "torch.cuda.random.seed", + "torch.cuda.random.set_rng_state_all", + "torch.cuda.set_stream", + "torch.cuda.set_sync_debug_mode", + "torch.cuda.stream", + "torch.cuda.temperature", + "torch.cuda.utilization", + "torch.einsum", + "torch.functional._check_list_size", + "torch.functional._consecutive_return_counts", + "torch.functional._consecutive_return_inverse_false", + "torch.functional._consecutive_return_inverse_true", + "torch.functional._consecutive_return_inverse", + "torch.functional._consecutive_return_output", + "torch.functional._lu_impl", + "torch.functional._lu_no_infos", + "torch.functional._lu_with_infos", + "torch.functional._meshgrid", + "torch.functional._return_counts", + "torch.functional._return_inverse_false", + "torch.functional._return_inverse_true", + "torch.functional._return_inverse", + "torch.functional._return_output", + "torch.functional._unique_consecutive_impl", + "torch.functional._unique_impl", + "torch.functional._unravel_index", + "torch.functional.broadcast_shapes", + "torch.functional.lu", + "torch.functional.unique", + "torch.functional.unravel_index", + "torch.futures.collect_all", + "torch.futures.wait_all", + "torch.fx.experimental.const_fold.split_const_subgraphs", + "torch.fx.experimental.proxy_tensor.make_fx", + "torch.get_deterministic_debug_mode", + "torch.get_float32_matmul_precision", + "torch.is_deterministic_algorithms_warn_only_enabled", + "torch.is_storage", + "torch.is_tensor", + "torch.is_warn_always_enabled", + "torch.masked._ops._any", + "torch.masked._ops._apply_docstring_templates", + "torch.masked._ops._canonical_dim", + "torch.masked._ops._combine_input_and_mask", + "torch.masked._ops._generate_docstring", + "torch.masked._ops._input_mask", + "torch.masked._ops._output_mask", + "torch.masked._ops._reduction_identity", + "torch.masked._ops._sparse_coo_flatten_indices", + "torch.masked._ops._sparse_coo_scatter_reduction_helper", + "torch.masked._ops._sparse_coo_where", + "torch.masked._ops._sparse_csr_segment_reduction_helper", + "torch.masked._ops._sparse_csr_where", + "torch.masked._ops._std_var", + "torch.masked._ops._where", + "torch.masked._ops.amax", + "torch.masked._ops.amin", + "torch.masked._ops.argmax", + "torch.masked._ops.argmin", + "torch.masked._ops.corresponding_real_dtype", + "torch.masked._ops.cumprod", + "torch.masked._ops.cumsum", + "torch.masked._ops.log_softmax", + "torch.masked._ops.logaddexp", + "torch.masked._ops.logsumexp", + "torch.masked._ops.mean", + "torch.masked._ops.median", + "torch.masked._ops.norm", + "torch.masked._ops.normalize", + "torch.masked._ops.prod", + "torch.masked._ops.softmax", + "torch.masked._ops.softmin", + "torch.masked._ops.std", + "torch.masked._ops.sum", + "torch.masked._ops.var", + "torch.meshgrid", + "torch.mps._get_default_mps_generator", + "torch.mps.current_allocated_memory", + "torch.mps.driver_allocated_memory", + "torch.mps.empty_cache", + "torch.mps.get_rng_state", + "torch.mps.manual_seed", + "torch.mps.profiler.profile", + "torch.mps.profiler.start", + "torch.mps.profiler.stop", + "torch.mps.seed", + "torch.mps.set_per_process_memory_fraction", + "torch.mps.set_rng_state", + "torch.mps.synchronize", + "torch.nested._internal.nested_tensor.buffer_from_jagged", + "torch.nested._internal.nested_tensor.get_tensor_symint", + "torch.nested._internal.nested_tensor.is_expandable_to", + "torch.nested._internal.nested_tensor.jagged_from_list", + "torch.nested._internal.nested_tensor.jagged_from_tensor_and_lengths", + "torch.nested._internal.nested_tensor.nested_view_from_values_offsets", + "torch.nested._internal.nested_tensor.nested_view_from_values_offsets_lengths", + "torch.nested.as_nested_tensor", + "torch.nested.narrow", + "torch.nested.nested_tensor", + "torch.nn._reduction.get_enum", + "torch.nn._reduction.legacy_get_enum", + "torch.nn._reduction.legacy_get_string", + "torch.nn.factory_kwargs", + "torch.nn.functional.adaptive_avg_pool2d", + "torch.nn.functional.adaptive_avg_pool3d", + "torch.nn.functional.adaptive_max_pool1d_with_indices", + "torch.nn.functional.adaptive_max_pool1d", + "torch.nn.functional.adaptive_max_pool2d_with_indices", + "torch.nn.functional.adaptive_max_pool2d", + "torch.nn.functional.adaptive_max_pool3d_with_indices", + "torch.nn.functional.adaptive_max_pool3d", + "torch.nn.functional.affine_grid", + "torch.nn.functional.alpha_dropout", + "torch.nn.functional.assert_int_or_pair", + "torch.nn.functional.batch_norm", + "torch.nn.functional.binary_cross_entropy_with_logits", + "torch.nn.functional.binary_cross_entropy", + "torch.nn.functional.celu", + "torch.nn.functional.cosine_embedding_loss", + "torch.nn.functional.cross_entropy", + "torch.nn.functional.ctc_loss", + "torch.nn.functional.dropout", + "torch.nn.functional.dropout1d", + "torch.nn.functional.dropout2d", + "torch.nn.functional.dropout3d", + "torch.nn.functional.elu", + "torch.nn.functional.embedding_bag", + "torch.nn.functional.embedding", + "torch.nn.functional.feature_alpha_dropout", + "torch.nn.functional.fold", + "torch.nn.functional.fractional_max_pool2d_with_indices", + "torch.nn.functional.fractional_max_pool2d", + "torch.nn.functional.fractional_max_pool3d_with_indices", + "torch.nn.functional.fractional_max_pool3d", + "torch.nn.functional.gaussian_nll_loss", + "torch.nn.functional.glu", + "torch.nn.functional.grid_sample", + "torch.nn.functional.group_norm", + "torch.nn.functional.gumbel_softmax", + "torch.nn.functional.hardsigmoid", + "torch.nn.functional.hardswish", + "torch.nn.functional.hardtanh", + "torch.nn.functional.hinge_embedding_loss", + "torch.nn.functional.huber_loss", + "torch.nn.functional.instance_norm", + "torch.nn.functional.interpolate", + "torch.nn.functional.kl_div", + "torch.nn.functional.l1_loss", + "torch.nn.functional.layer_norm", + "torch.nn.functional.leaky_relu", + "torch.nn.functional.local_response_norm", + "torch.nn.functional.log_softmax", + "torch.nn.functional.lp_pool1d", + "torch.nn.functional.lp_pool2d", + "torch.nn.functional.margin_ranking_loss", + "torch.nn.functional.max_pool1d_with_indices", + "torch.nn.functional.max_pool1d", + "torch.nn.functional.max_pool2d_with_indices", + "torch.nn.functional.max_pool2d", + "torch.nn.functional.max_pool3d_with_indices", + "torch.nn.functional.max_pool3d", + "torch.nn.functional.max_unpool1d", + "torch.nn.functional.max_unpool2d", + "torch.nn.functional.max_unpool3d", + "torch.nn.functional.mish", + "torch.nn.functional.mse_loss", + "torch.nn.functional.multi_head_attention_forward", + "torch.nn.functional.multi_margin_loss", + "torch.nn.functional.multilabel_margin_loss", + "torch.nn.functional.multilabel_soft_margin_loss", + "torch.nn.functional.nll_loss", + "torch.nn.functional.normalize", + "torch.nn.functional.poisson_nll_loss", + "torch.nn.functional.relu", + "torch.nn.functional.relu6", + "torch.nn.functional.rrelu", + "torch.nn.functional.selu", + "torch.nn.functional.sigmoid", + "torch.nn.functional.silu", + "torch.nn.functional.smooth_l1_loss", + "torch.nn.functional.soft_margin_loss", + "torch.nn.functional.softmax", + "torch.nn.functional.softmin", + "torch.nn.functional.softsign", + "torch.nn.functional.tanh", + "torch.nn.functional.tanhshrink", + "torch.nn.functional.triplet_margin_loss", + "torch.nn.functional.unfold", + "torch.nn.functional.upsample_bilinear", + "torch.nn.functional.upsample_nearest", + "torch.nn.functional.upsample", + "torch.nn.grad._pair", + "torch.nn.grad._single", + "torch.nn.grad._triple", + "torch.nn.grad.conv1d_input", + "torch.nn.grad.conv1d_weight", + "torch.nn.grad.conv2d_input", + "torch.nn.grad.conv2d_weight", + "torch.nn.grad.conv3d_input", + "torch.nn.grad.conv3d_weight", + "torch.nn.modules.activation._is_make_fx_tracing", + "torch.nn.modules.utils._list_with_default", + "torch.nn.modules.utils._ntuple", + "torch.nn.modules.utils._quadruple", + "torch.nn.modules.utils._reverse_repeat_tuple", + "torch.nn.modules.utils.consume_prefix_in_state_dict_if_present", + "torch.nn.parameter.is_lazy", + "torch.norm", + "torch.quantization.default_eval_fn", + "torch.random._seed_custom_device", + "torch.random.fork_rng", + "torch.random.initial_seed", + "torch.random.seed", + "torch.return_types.pytree_register_structseq", + "torch.set_default_dtype", + "torch.set_default_tensor_type", + "torch.set_deterministic_debug_mode", + "torch.set_float32_matmul_precision", + "torch.set_warn_always", + "torch.signal.windows.windows._add_docstr", + "torch.signal.windows.windows._window_function_checks", + "torch.signal.windows.windows.bartlett", + "torch.signal.windows.windows.blackman", + "torch.signal.windows.windows.cosine", + "torch.signal.windows.windows.exponential", + "torch.signal.windows.windows.gaussian", + "torch.signal.windows.windows.general_cosine", + "torch.signal.windows.windows.general_hamming", + "torch.signal.windows.windows.hamming", + "torch.signal.windows.windows.hann", + "torch.signal.windows.windows.kaiser", + "torch.signal.windows.windows.merge_dicts", + "torch.signal.windows.windows.nuttall", + "torch.signal.windows.windows.parse_kwargs", + "torch.sparse.semi_structured.to_sparse_semi_structured", + "torch.sparse.sum", + "torch.split", + "torch.stft", + "torch.sym_float", + "torch.sym_int", + "torch.sym_ite", + "torch.sym_max", + "torch.sym_min", + "torch.sym_not", + "torch.tensordot", + "torch.unique_consecutive", + "torch.use_deterministic_algorithms", + "torch.xpu._get_device", + "torch.xpu._get_generator", + "torch.xpu._get_rng_state_offset", + "torch.xpu._is_compiled", + "torch.xpu._lazy_call", + "torch.xpu._lazy_init", + "torch.xpu._set_rng_state_offset", + "torch.xpu._set_stream_by_id", + "torch.xpu._utils._get_device_index", + "torch.xpu.current_device", + "torch.xpu.current_stream", + "torch.xpu.device_count", + "torch.xpu.get_arch_list", + "torch.xpu.get_device_capability", + "torch.xpu.get_device_name", + "torch.xpu.get_device_properties", + "torch.xpu.get_gencode_flags", + "torch.xpu.get_stream_from_external", + "torch.xpu.init", + "torch.xpu.is_available", + "torch.xpu.is_bf16_supported", + "torch.xpu.is_initialized", + "torch.xpu.memory.empty_cache", + "torch.xpu.memory.max_memory_allocated", + "torch.xpu.memory.max_memory_reserved", + "torch.xpu.memory.mem_get_info", + "torch.xpu.memory.memory_allocated", + "torch.xpu.memory.memory_reserved", + "torch.xpu.memory.memory_stats_as_nested_dict", + "torch.xpu.memory.memory_stats", + "torch.xpu.memory.reset_accumulated_memory_stats", + "torch.xpu.memory.reset_peak_memory_stats", + "torch.xpu.random.initial_seed", + "torch.xpu.random.seed_all", + "torch.xpu.random.seed", + "torch.xpu.set_stream", + "torch.xpu.stream", + "torch.xpu.synchronize", + ], + TorchInGraphFunctionVariable, +) + + +torch_name_rule_map = [ + manual_torch_name_rule_map, + torch_c_binding_in_graph_functions, + torch_non_c_binding_in_graph_functions, +] + + +""" +Generate the torch object - Dynamo tracing rule (the wrapping variable) map. +""" + + +@functools.cache +def get_torch_obj_rule_map() -> dict[Any, type["VariableTracker"]]: + d: dict[Any, type[VariableTracker]] = {} + for m in torch_name_rule_map: + for k, v in m.items(): # type: ignore[attr-defined] + if ".py#" not in k: + obj = load_object(k) + else: + torch_dir = _module_dir(torch) + if torch_dir is None: + continue + obj = torch_dir + k[len("torch/") :] + if obj is not None: + if is_lru_cache_wrapped_function(obj): + obj = obj.__wrapped__ + if obj in d and d[obj] != v: + raise AssertionError( + f"Duplicate torch object {obj} with different rules: {v}, {d[obj]}" + ) + else: + d[obj] = v + return d + + +def _load_obj_from_str(fully_qualified_name: str) -> Any: + module, obj_name = fully_qualified_name.rsplit(".", maxsplit=1) + return getattr(importlib.import_module(module), obj_name) + + +""" +Load string represented torch objects. +""" + + +def load_object(name: str) -> Any: + try: + x = name.split("#") + if len(x) == 2: + obj = _load_obj_from_str(x[0]) + val = getattr(obj, x[1]) + else: + if len(x) != 1: + raise AssertionError(f"Invalid obj name {name}") + val = _load_obj_from_str(x[0]) + val = unwrap_if_wrapper(val) + except (AttributeError, ImportError): + val = None + return val + + +""" +Get all torch.Tensor methods which are allowed to be in graph functions. +""" + + +@functools.cache +def get_tensor_method() -> frozenset[Any]: + disallowed_tensor_methods = {"__new__", "_make_wrapper_subclass", "_make_subclass"} + s = set() + for name in dir(torch.Tensor): + method = getattr(torch.Tensor, name) + if ( + isinstance( + method, + ( + types.MethodDescriptorType, + types.WrapperDescriptorType, + types.BuiltinFunctionType, + ), + ) + and name not in disallowed_tensor_methods + ): + s.add(method) + for name, method in torch._C.TensorBase.__dict__.items(): + if ( + isinstance( + method, + ( + types.MethodDescriptorType, + types.WrapperDescriptorType, + types.BuiltinFunctionType, + ), + ) + and name not in disallowed_tensor_methods + ): + s.add(method) + + # mlazos: these are functions which we handle specially in TensorVariable + s.add(torch.Tensor.__contains__) # type: ignore[arg-type] + s.add(torch.Tensor.register_hook) # type: ignore[arg-type] + return frozenset(s) + + +""" +Return if a torch object is ATen op or torch.Tensor method. +""" + + +def is_aten_op_or_tensor_method(obj: object) -> bool: + return obj in get_tensor_method() or isinstance( + obj, + (torch._ops.OpOverloadPacket, torch._ops.OpOverload), + ) + + +class FunctionIdSet: + """ + Track a set of `id()`s of objects which are either allowed or not + allowed to go into the generated FX graph. Use to test for torch.*, + numpy.*, builtins.*, etc. + + Support user modification to permit customization of what can be + added to the graph and what will cause a graph break. + """ + + function_ids: set[int] | None = None + function_names: dict[int, str] | None = None + + def __init__( + self, lazy_initializer: Callable[[], dict[int, str] | set[int]] + ) -> None: + self.lazy_initializer = lazy_initializer + + def __call__(self) -> set[int]: + if self.function_ids is None: + value = self.lazy_initializer() + if isinstance(value, dict): + self.function_ids = set(value.keys()) + self.function_names = value + else: + if not isinstance(value, set): + raise AssertionError( + f"expected lazy_initializer to return a dict or set, got {type(value)}" + ) + self.function_ids = value + return self.function_ids + + def get_name(self, idx: int, default: str) -> str: + self() # lazy init + if self.function_names is None: + raise AssertionError( + "function_names is None; lazy_initializer returned a set, not a dict" + ) + return self.function_names.get(idx, default) + + def add(self, idx: int) -> None: + function_ids = self() # lazy init + function_ids.add(idx) + + def remove(self, idx: int) -> None: + function_ids = self() + if idx in function_ids: + function_ids.remove(idx) + + def __contains__(self, idx: int) -> bool: + return idx in self() + + +@FunctionIdSet +def _allowed_callable_ids() -> dict[int, str]: + rv: dict[int, str] = {} + return rv + + +@FunctionIdSet +def _leaf_function_ids() -> dict[int, str]: + rv: dict[int, str] = {} + return rv + + +@FunctionIdSet +def _disallowed_callable_ids() -> dict[int, str]: + rv: dict[int, str] = {} + return rv + + +@FunctionIdSet +def _nonstrict_trace_callable_ids() -> dict[int, str]: + rv: dict[int, str] = {} + return rv + + +@FunctionIdSet +def _builtin_function_ids() -> dict[int, str]: + # See also torch/_dynamo/polyfills/loader.py, which removes items in _builtin_function_ids + rv = { + id(v): f"builtins.{k}" + for k, v in builtins.__dict__.items() + if not k.startswith("_") and callable(v) + } + rv.update( + { + id(v): f"operator.{k}" + for k, v in operator.__dict__.items() + if not k.startswith("_") and callable(v) + } + ) + rv[id(builtins.__build_class__)] = "builtins.__build_class__" + return rv + + +@FunctionIdSet +def _polyfilled_function_ids() -> set[int]: + # See also @torch._dynamo.decorators.substitute_in_graph(...), which adds items in _polyfilled_function_ids + return set() + + +@FunctionIdSet +def _numpy_function_ids() -> dict[int, str]: + unsupported_funcs = { + "seed", + "ranf", + "get_bit_generator", + "RandomState", + "set_bit_generator", + "sample", + } + + def is_supported(k: str, v: Any, mod: Any) -> bool: + if not callable(v): + return False + if not getattr(v, "__module__", None): + return True + if v.__module__ == mod.__name__: + return True + if ( + v.__module__ == "numpy.random.mtrand" + and mod.__name__ == "numpy.random" + and k not in unsupported_funcs + ): + return True + return False + + rv = {} + for mod in NP_SUPPORTED_MODULES: + for k, v in mod.__dict__.items(): + if is_supported(k, v, mod): + rv[id(v)] = f"{mod.__name__}.{k}" + return rv + + +@FunctionIdSet +def _builtin_constant_ids() -> dict[int, str]: + """ + Collects constant builtins by eliminating callable items. + """ + rv = { + id(v): f"builtins.{k}" + for k, v in builtins.__dict__.items() + if not k.startswith("_") and not callable(v) + } + return rv + + +_lazy_module_init: dict[str, list[Callable[[], None]]] = defaultdict(list) + + +def add_module_init_func(name: str, init_func: Callable[[], None]) -> None: + """Register a module without eagerly importing it""" + # If the module is already imported, eagerly run init + if "." in name: + raise AssertionError(f"Expected a root module name, but got {name}") + if name in _lazy_module_init: + raise AssertionError(f"Module init function already registered for {name}") + _lazy_module_init[name].append(init_func) + + +def _maybe_init_lazy_module(obj: object) -> None: + module = getattr(obj, "__module__", None) + if module is None: + return + + base_module = module.split(".")[0] + init_funcs = _lazy_module_init.pop(base_module, None) + if init_funcs is not None: + for fn in init_funcs: + fn() + + +def is_callable_allowed(obj: object) -> bool: + _maybe_init_lazy_module(obj) + return id(obj) in _allowed_callable_ids + + +def is_nonstrict_trace_callable(obj: object) -> bool: + _maybe_init_lazy_module(obj) + return id(obj) in _nonstrict_trace_callable_ids + + +def is_leaf_function(obj: object) -> bool: + _maybe_init_lazy_module(obj) + return id(obj) in _leaf_function_ids + + +def is_callable_disallowed(obj: object) -> bool: + _maybe_init_lazy_module(obj) + return id(obj) in _disallowed_callable_ids + + +def is_forbidden(obj: object) -> bool: + _maybe_init_lazy_module(obj) + return inspect.getattr_static(obj, "_dynamo_forbidden", False) + + +def is_builtin_callable(obj: object) -> bool: + # See also torch/_dynamo/polyfills/loader.py, which removes items in _builtin_function_ids + return id(obj) in _builtin_function_ids + + +def is_builtin_constant(obj: object) -> bool: + return id(obj) in _builtin_constant_ids + + +def is_polyfilled_callable(obj: object) -> bool: + # See also @torch._dynamo.decorators.substitute_in_graph(...), which adds items in _polyfilled_function_ids + return id(obj) in _polyfilled_function_ids + + +def is_numpy(obj: object) -> bool: + if np is None: + return False + return isinstance(obj, (np.ndarray, np.generic)) or id(obj) in _numpy_function_ids + + +def is_numpy_dtype(obj: object) -> bool: + if np is None: + return False + return isinstance(obj, np.dtype) + + +def is_numpy_type_info(obj: object) -> bool: + if np is None: + return False + return isinstance(obj, (np.finfo, np.iinfo)) + + +BUILTIN_SKIPLIST = ( + abc, + copy, + importlib, + random, + re, + linecache, +) + +# Builtin modules that should be skipped at the top-level (PEP 523 frame +# evaluation) but inlined when called from code dynamo is already tracing. +# For example, copy.deepcopy should be inlined when the user calls it inside +# a compiled function, but copy module frames should be skipped when they +# appear as top-level frames (e.g. called internally by autograd). +BUILTIN_INLINE_WHEN_CALLED: set[str] = set() + +# third party libraries skiplist is defined by str, because users may not use these libraries. +# we should use lazy import & skip in the future. +THIRDPARTY_SKIPLIST = ( + "fx2trt_oss", + "hypothesis", + "networkx", + "numpy", + "onnx", + "onnxruntime", + "onnx_tf", + "pandas", + "sklearn", + "tabulate", + "tensorflow", + "tensorrt", + "torch2trt", + "tqdm", + "tree", + "tvm", + "xarray", +) + + +def _as_posix_path(path: str) -> str: + posix_path = Path(os.path.normpath(path)).as_posix() + # os.path.normpath and pathlib.Path remove trailing slash, so we need to add it back + if path.endswith((os.path.sep, "/")): + posix_path += "/" + return posix_path + + +def _strip_init_py(s: str) -> str: + suffix = "__init__.py" + s = s.removesuffix(suffix) + return _as_posix_path(s) + + +def _module_dir(m: types.ModuleType) -> str | None: + # Protect against a module not exporting __file__ - this can happen for + # frozen modules, for example. + file = getattr(m, "__file__", None) + return file and _strip_init_py(file) + + +# These are legacy workarounds, don't add new modules to this list. +# Please use the MOD_INLINELIST instead to force inline functions under particular modules. +# +# NB: The only thing that is different about MOD_INLINELIST and LEGACY_MOD_INLINELIST +# is the behavior of a function f2 in the module when called by a function f1 +# in a module in MOD_SKIPLIST (see MOD_SKIPLIST for more details) +# +# LEGACY_MOD_INLINELIST is the same thing as Dynamo's behavior on a module that +# is not in any *_INLINELIST or *_SKIPLIST. +# That being said, we prefer people to add things to MOD_INLINELIST over +# LEGACY_MOD_INLINELIST because it is less likely to break existing tests. +LEGACY_MOD_INLINELIST = { + "torch._dynamo.external_utils", + "torch._export.db.examples", + "torch._export.wrappers", + "torch._functorch.apis", + "torch._functorch.deprecated", + "torch._library.fake_class_registry", + "torch.utils._typing_utils", + "torch.nn.attention.flex_attention", + "torch.ao.quantization.stubs", + "torch.ao.quantization.pt2e.export_utils", + "torch.ao.quantization.pt2e.qat_utils", + "torch.ao.quantization.pt2e.representation.rewrite", + "torch.ao.quantization.pt2e.utils", + "torch.ao.quantization.quantizer.xnnpack_quantizer", + "torch.export.unflatten", +} + +if torch.distributed.is_available(): + LEGACY_MOD_INLINELIST |= { + "torch.distributed.tensor._api", + "torch.distributed.tensor.device_mesh", + "torch.distributed.device_mesh", + "torch.distributed.algorithms._checkpoint.checkpoint_wrapper", + "torch.distributed.tensor.parallel._data_parallel_utils", + "torch.distributed.tensor.parallel._utils", + "torch.distributed.tensor.parallel.style", + # we have to add replicate to LEGACY_MOD_INLINELIST to ensure + # the forward_hook won't be ignored. + "torch.distributed._composable.replicate", + } + +# Force inline functions under these modules, even they are in *_SKIPLIST. +# We are using python module name instead of file or directory object to avoid circular dependency. +# Please keep this sorted alphabetically. +# +# Btw, it is not "ideal" for something to be in MOD_INLINELIST. If Dynamo +# fully supports a module, then the ideal case is that it is not in +# any *_INLINELIST or *_SKIPLIST: then, the behavior of Dynamo is that +# it will always inline into functions in the module. +MOD_INLINELIST = [ + "torch._decomp", + "torch._dynamo._trace_wrapped_higher_order_op", + "torch._dynamo.compiled_autograd", + "torch._dynamo.comptime", + "torch._dynamo.polyfills", + "torch._dynamo.test_case", + "torch._export.non_strict_utils", + "torch._functorch._aot_autograd.subclass_parametrization", + "torch._functorch.autograd_function", + "torch._functorch.eager_transforms", + "torch._functorch.functional_call", + "torch._functorch.pyfunctorch", + "torch._functorch.vmap", + "torch._inductor.test_operators", + "torch._library.autograd", + "torch._library.custom_ops", + "torch._ops", + "torch._prims", + "torch._refs", + "torch._tensor", + "torch.amp.autocast_mode", + "torch.ao.nn", + "torch.ao.quantization.fx._decomposed", + "torch.autograd.function", + "torch.backends.cuda", + "torch.cuda.amp.autocast_mode", + "torch.distributions", + "torch.export._patches", + "torch.export._tree_utils", + "torch.export._unlift", + "torch.export._wrapper_utils", + "torch.fx._pytree", + "torch.fx._symbolic_trace", + "torch.fx.experimental.proxy_tensor", + "torch.fx.passes.shape_prop", + "torch.fx.traceback", + "torch.nn", + "torch.overrides", + "torch.random", + "torch.return_types", + "torch.sparse", + "torch.testing", + "torch.utils._content_store", + "torch.utils._contextlib", + "torch.utils._cxx_pytree", + "torch.utils._device", + "torch.utils._foreach_utils", + "torch.utils._ordered_set", + "torch.utils._python_dispatch", + "torch.utils._pytree", + "torch.utils.hooks", +] +if sorted(set(MOD_INLINELIST)) != MOD_INLINELIST: + raise AssertionError("MOD_INLINELIST must be sorted with no duplicates") +MOD_INLINELIST = set(MOD_INLINELIST) + + +if torch.distributed.is_available(): + MOD_INLINELIST.add("torch.distributed") + +# Modules in MOD_INLINELIST where nested graph breaks should be suppressed. +# These are large internal modules that are inlined for correctness but whose +# internal operations are not worth compiling as separate NGB subgraphs. +NGB_SUPPRESS_INLINELIST: set[str] = set() + +if torch.distributed.is_available(): + NGB_SUPPRESS_INLINELIST.add("torch.distributed") + +if not NGB_SUPPRESS_INLINELIST <= MOD_INLINELIST: + raise AssertionError( + "NGB_SUPPRESS_INLINELIST entries must also be in MOD_INLINELIST: " + f"{NGB_SUPPRESS_INLINELIST - MOD_INLINELIST}" + ) + + +# By default, all functions under these modules are skipped. +# All the other knobs +# (torch_name_rule_map, MOD_INLINELIST, LEGACY_MOD_INLINELIST) +# take precedence over this list; e.g. if a function is in +# MOD_INLINELIST and MOD_SKIPLIST, then it will be inlined. +# See "A note on skip/inline rules" for more details. +# +# The skip is NOT recursive. If a function f1 in a module in MOD_SKIPLIST +# calls out to another function f2 in some other module, then Dynamo's +# behavior (skip/inline) depends on what we've marked f2 as: +# - if f2 is a function in a module in MOD_SKIPLIST, then we skip f2 +# - if f2 is a function in a module in MOD_INLINELIST, then we skip f2 +# - if f2 is a function in a module in LEGACY_MOD_INLINELIST, then we inline f2 +# - if f2 is a function in a module not in any *_LIST, then we inline f2 +MOD_SKIPLIST = [ + "torch._VF", + "torch.__future__", + "torch.__init__", + "torch._awaits", + "torch._classes", + "torch._compile", + "torch._custom_op", + "torch._custom_ops", + "torch._decomp", + "torch._dispatch", + "torch._dynamo", + "torch._export", + "torch._functorch", + "torch._guards", + "torch._higher_order_ops.effects", + "torch._higher_order_ops.torchbind", + "torch._higher_order_ops.wrap", + "torch._inductor", + "torch._jit_internal", + "torch._lazy", + "torch._library", + "torch._linalg_utils", + "torch._lobpcg", + "torch._logging", + "torch._lowrank", + "torch._meta_registrations", + "torch._numpy", + "torch._ops", + "torch._prims", + "torch._prims_common", + "torch._python_dispatcher", + "torch._refs", + "torch._strobelight", + "torch._subclasses", + "torch._tensor", + "torch._tensor_str", + "torch._thread_safe_fork", + "torch._utils", + "torch._utils_internal", + "torch._vmap_internals", + "torch._weights_only_unpickler", + "torch.accelerator", + "torch.amp", + "torch.ao", + "torch.autograd", + "torch.backends", + "torch.compiler", + "torch.contrib", + "torch.cpu", + "torch.cuda", + "torch.distributed", + "torch.distributions", + "torch.export", + "torch.fb", + "torch.fft", + "torch.functional", + "torch.futures", + "torch.fx", + "torch.hub", + "torch.jit", + "torch.library", + "torch.linalg", + "torch.masked", + "torch.monitor", + "torch.mps", + "torch.mtia", + "torch.multiprocessing", + "torch.nested", + "torch.nn", + "torch.onnx", + "torch.overrides", + "torch.package", + "torch.profiler", + "torch.quantization", + "torch.quasirandom", + "torch.random", + "torch.serialization", + "torch.signal", + "torch.sparse", + "torch.special", + "torch.storage", + "torch.testing", + "torch.types", + "torch.utils", + "torch.xpu", +] + +if sorted(set(MOD_SKIPLIST)) != MOD_SKIPLIST: + raise AssertionError("MOD_SKIPLIST must be sorted with no duplicates") +MOD_SKIPLIST = set(MOD_SKIPLIST) + + +@functools.cache +def get_legacy_mod_inlinelist() -> set[str]: + torch_dir = _module_dir(torch) + if torch_dir is None: + return set() + inlinelist = { + _as_posix_path(torch_dir + m[len("torch.") :].replace(".", "/")) + for m in LEGACY_MOD_INLINELIST + } + return inlinelist + + +@functools.cache +def get_mod_inlinelist() -> set[str]: + torch_dir = _module_dir(torch) + if torch_dir is None: + return set() + inlinelist = { + _as_posix_path(torch_dir + m[len("torch.") :].replace(".", "/")) + for m in MOD_INLINELIST + } + return inlinelist + + +@functools.cache +def get_mod_skiplist() -> set[str]: + torch_dir = _module_dir(torch) + if torch_dir is None: + return set() + skiplist = { + _as_posix_path(torch_dir + m[len("torch.") :].replace(".", "/")) + for m in MOD_SKIPLIST + } + return skiplist + + +# skip some standard python builtin libs +SKIP_DIRS = [ + "", + _as_posix_path(_config_module.__file__), + "triton/backends", +] +SKIP_DIRS.extend(map(_as_posix_path, filter(None, map(_module_dir, BUILTIN_SKIPLIST)))) + +BUILTIN_INLINE_WHEN_CALLED.update( + filter(None, (_module_dir(copy), _as_posix_path(_config_module.__file__))) +) + +SKIP_DIRS_RE = re.compile(r"match nothing^") + +# Skip fbcode paths(including torch.package paths) containing +# one of the following strings. +FBCODE_SKIP_DIRS: set[str] = set() + +FBCODE_SKIP_DIRS_RE = re.compile(f".*({'|'.join(map(re.escape, FBCODE_SKIP_DIRS))})") + +# Remove this after fbcode is fully migrated to tracing through torchrec. +FBCODE_SKIP_TORCHREC_DIRS = { + "torchrec/distributed", + "torchrec/fb/distributed", + "caffe2/torch/fb/sparsenn/pooled_embeddings_modules.py", +} + +FBCODE_SKIP_TORCHREC_DIRS_RE = re.compile( + f".*({'|'.join(re.escape(_as_posix_path(d)) for d in FBCODE_SKIP_TORCHREC_DIRS)})" +) + +# TODO(yanboliang, anijain2305) - There are a few concerns that we should +# resolve +# 1) Audit if torchrec/distributed is even required in FBCODE_SKIPS_DIR +# 2) To inline just one file but skip others in a directory, we could use +# manual_torch_name_rule_map but this one is hard because FBCODE can add unusual +# names like torch_package. +# So, this is a stop gap solution till then. +FBCODE_INLINE_FILES_IN_SKIPPED_DIRS = { + "torchrec/distributed/types.py", +} +FBCODE_INLINE_FILES_IN_SKIPPED_DIRS_RE = re.compile( + f".*({'|'.join(re.escape(_as_posix_path(d)) for d in FBCODE_INLINE_FILES_IN_SKIPPED_DIRS)})" +) + +# torch.optim is a special case, +# we usually want to inline it, but the directory +# structure does not match the module structure +# and we want to skip the functions in optim/lr_scheduler.py +# this has precedence over all other rules in check_file +FORCE_SKIP_FILES = {f"{_module_dir(torch)}optim/lr_scheduler.py"} + + +def _recompile_re() -> None: + global SKIP_DIRS_RE + SKIP_DIRS_RE = re.compile( + rf"^[^\s<]*({'|'.join(re.escape(_as_posix_path(d)) for d in SKIP_DIRS)})" + ) + + +def add(import_name: str) -> None: + if isinstance(import_name, types.ModuleType): + return add(import_name.__name__) + if not isinstance(import_name, str): + raise AssertionError( + f"expected import_name to be a str, got {type(import_name)}" + ) + from importlib.util import find_spec + + module_spec = find_spec(import_name) + if not module_spec: + return + origin = module_spec.origin + if origin is None: + return + SKIP_DIRS.append(_strip_init_py(origin)) + _recompile_re() + + +@dataclasses.dataclass +class SkipResult: + skipped: bool + reason: str | None + + +def check_file(filename: str | None, is_inlined_call: bool = False) -> SkipResult: + """Should skip this file?""" + if filename is None: + return SkipResult( + True, "cannot determine source file (likely a C extension or builtin)" + ) + filename = _as_posix_path(filename) + if filename in FORCE_SKIP_FILES: + return SkipResult(True, f"file is force-skipped ({filename})") + + for d in get_legacy_mod_inlinelist(): + if filename.startswith(d): + return SkipResult(False, f"file matches LEGACY_MOD_INLINELIST ({d})") + if is_inlined_call and is_torch_inline_allowed(filename): + return SkipResult(False, f"file matches MOD_INLINELIST ({filename})") + if is_inlined_call and any( + filename.startswith(d) for d in BUILTIN_INLINE_WHEN_CALLED + ): + return SkipResult( + False, f"file matches BUILTIN_INLINE_WHEN_CALLED ({filename})" + ) + if ( + is_fbcode() + and FBCODE_SKIP_DIRS + and bool(FBCODE_SKIP_DIRS_RE.match(filename)) + and not bool(FBCODE_INLINE_FILES_IN_SKIPPED_DIRS_RE.match(filename)) + ): + return SkipResult(True, "file matches FBCODE_SKIP_DIRS") + + if ( + is_fbcode() + and config.skip_torchrec + and FBCODE_SKIP_TORCHREC_DIRS + and bool(FBCODE_SKIP_TORCHREC_DIRS_RE.match(filename)) + and not bool(FBCODE_INLINE_FILES_IN_SKIPPED_DIRS_RE.match(filename)) + ): + return SkipResult(True, "file matches FBCODE_SKIP_TORCHREC_DIRS") + + unittest_dir = _module_dir(unittest) + if ( + unittest_dir is not None + and filename.startswith(unittest_dir) + and not torch._dynamo.config.enable_trace_unittest + ): + return SkipResult(True, "file is in unittest directory") + + if bool(SKIP_DIRS_RE.match(filename)): + matched_dir = next((d for d in SKIP_DIRS if filename.startswith(d)), filename) + return SkipResult(True, f"file is under skip directory ({matched_dir})") + + for d in get_mod_skiplist(): + if filename.startswith(d): + return SkipResult(True, f"file matches MOD_SKIPLIST ({d})") + return SkipResult(False, "inlined by default") + + +@dataclasses.dataclass +class FunctionInfo: + py_obj: object | None + name: str | None + filename: str + code: types.CodeType | None + + +""" +This is the main entry point to determine whether an object (function) should be inlined or skipped. +Let's illustrate the logic with an example: + @torch.compile + def f1(x, y): + ...... + f2(x, y) + ...... + + def f2(x, y): + ...... + f3(x, y) + ...... + + def f3(x, y): + ...... + +There are mainly three call sites of check/check_verbose: +* The compile region entrance (like function f1), the corresponding code is located at eval_frame.py. +* When tracing the recursively called functions (like function f2 and f3). + * Dynamo decides inline/skip every time it encounters a new recursively function call, and the call site + is in InliningInstructionTranslator.check_inlineable of symbolic_convert.py. + * If f2 is skipped by Dynamo, when evaluating the frame of f3, Dynamo need the inline/skip check again + and the call site is in catch_errors_wrapper.catch_errors of convert_frame.py. +* For global variables and function arguments, Dynamo needs to decide if they are wrapped as SkipFunctionVariable in builder.py. + +`is_inlined_call` is used to indicate if the current function call is inlined (f2 is inlined call if it passes check) +or not (f3 is not inlined call if f2 is skipped). Inside of the `check_verbose` function, there are more rules +to be checked if this `is_inlined_call`. +The reason to have this flag is that if the upper level function call (e.g, f2) is skipped, +we don't want to inline the lower level function call (e.g, f3) by default. +""" + +_force_inline_flag = False + + +# pyrefly: ignore [deprecated] +@contextlib.contextmanager +def _force_inline() -> Iterator[None]: + """ + A context manager used within the dynamo codebase that forces a function + and nested function calls to be inlined during dynamo tracing. + + When active, check_verbose() will skip all inline/skip decision logic and + always return SkipResult(False, ...), meaning functions will be inlined. + + See _make_inlined() in utils.py which uses this to ensure that + a python function is fully traced to produce the needed variable trackers. + """ + global _force_inline_flag + old_val = _force_inline_flag + try: + _force_inline_flag = True + yield + finally: + _force_inline_flag = old_val + + +def check_verbose( + obj: object, is_inlined_call: bool = False, frame: Any | None = None +) -> SkipResult: + if _force_inline_flag: + return SkipResult( + False, + "don't skip because we're inside _force_inline() context", + ) + + # For eval frame callback (not inlined calls), allow tracing inbuilt + # nn.Module.forward methods when the module has hooks. Any hook can cause + # a graph break (via @torch._dynamo.disable, print, unsupported ops, etc.), + # which skips the entire _call_impl frame. By allowing forward to be traced, + # Dynamo can capture the module's operations in a new graph after the break. + if ( + not is_inlined_call + and frame is not None + and isinstance(obj, types.CodeType) + and obj.co_name == "forward" + ): + from .utils import nnmodule_has_hooks + + module = frame.f_locals.get("self") + if ( + module is not None + and isinstance(module, torch.nn.Module) + and module.__class__.__module__.startswith(("torch.nn.", "torch.ao.")) + and nnmodule_has_hooks(module, check_forward_hooks=True) + ): + return SkipResult( + False, + "inbuilt nn.Module.forward allowed - module has hooks", + ) + + if isinstance( + obj, + ( + UserFunctionVariable, + UserMethodVariable, + NestedUserFunctionVariable, + LocalGeneratorFunctionVariable, + LocalGeneratorObjectVariable, + ), + ): + try: + py_obj = obj.get_function() + except NotImplementedError: + py_obj = None + fi = FunctionInfo(py_obj, obj.get_name(), obj.get_filename(), obj.get_code()) + elif isinstance(obj, types.CodeType): + fi = FunctionInfo(None, obj.co_name, obj.co_filename, obj) + elif isinstance(obj, (types.FunctionType, types.MethodType)): + filename = getfile(obj) + if filename is None: + raise AssertionError(f"getfile returned None for function/method {obj}") + fi = FunctionInfo( + obj, + obj.__name__, + filename, + obj.__code__, # type: ignore[union-attr] # FIXME Add MethodType.__code__ to typeshed + ) + else: + filename = getfile(obj) + if filename is None: + raise AssertionError(f"getfile returned None for {type(obj)}") + fi = FunctionInfo(obj, None, filename, None) + + # typing.cast is a polyfilled no-op, but unlike C builtins it has a code + # object that PEP 523 can intercept as a standalone frame after a graph + # break. Skip it at the top level to avoid installing unnecessary guards. + if fi.code is not None and fi.code is typing.cast.__code__: + return SkipResult(True, "typing.cast is a no-op, skip at top level") + + # Consulte the central trace rules defined in torch._dynamo.trace_rules. + reasons: set[str] = set() + rule = lookup_inner(fi.py_obj, fi.name, fi.filename, is_inlined_call, reasons) + if rule is None: + raise AssertionError( + f"lookup_inner returned None for {fi.name} in {fi.filename}" + ) + if issubclass( + rule, + ( + UserFunctionVariable, + LocalGeneratorFunctionVariable, + PolyfilledFunctionVariable, + ), + ): + return SkipResult(False, reasons.pop()) + elif issubclass(rule, TorchInGraphFunctionVariable): + return SkipResult(False, reasons.pop()) + else: + if rule != SkipFunctionVariable: + raise AssertionError(f"expected SkipFunctionVariable, got {rule}") + return SkipResult(True, reasons.pop()) + + +def check(obj: object, is_inlined_call: bool = False, frame: Any | None = None) -> bool: + return check_verbose(obj, is_inlined_call, frame).skipped + + +def get_skip_reason(obj: object) -> str: + """Compute a descriptive skip reason for a callable. Only called on graph break.""" + if is_callable_disallowed(obj): + return _disallowed_callable_ids.get_name(id(obj), repr(obj)) + + filename = getfile(obj) + if filename is not None: + skip_result = check_file(filename) + if skip_result.reason is not None: + return skip_result.reason + + module = getattr(obj, "__module__", None) or "" + return ( + f"cannot determine source file for {module} (likely a C extension or builtin)" + ) + + +# skip common third party libs +for _name in THIRDPARTY_SKIPLIST: + add(_name) + +_recompile_re() + + +def is_torch_inline_allowed(filename: str) -> bool: + return any(filename.startswith(d) for d in get_mod_inlinelist()) + + +@functools.cache +def get_ngb_suppress_inlinelist() -> set[str]: + torch_dir = _module_dir(torch) + if torch_dir is None: + return set() + return { + _as_posix_path(torch_dir + m[len("torch.") :].replace(".", "/")) + for m in NGB_SUPPRESS_INLINELIST + } + + +def is_ngb_suppressed_inline(filename: str) -> bool: + return any(filename.startswith(d) for d in get_ngb_suppress_inlinelist()) + + +@functools.cache +def dynamo_dir() -> str | None: + import torch._dynamo + + return _module_dir(torch._dynamo) + + +def is_torch(filename: str) -> bool: + dynamo_path = dynamo_dir() + if dynamo_path is not None and filename.startswith(dynamo_path): + return False + torch_path = _module_dir(torch) + return torch_path is not None and filename.startswith(torch_path) + + +""" +Main entry point for looking up the trace rule (the Dynamo variable) for a given callable object. +""" + +BUILTIN_CALLABLES = { + dict: DictBuiltinVariable, + getattr: GetAttrBuiltinVariable, + hasattr: HasAttrBuiltinVariable, + iter: IterBuiltinVariable, + list: ListBuiltinVariable, + setattr: SetAttrBuiltinVariable, +} + + +def lookup_callable(obj: Callable[..., Any]) -> type[VariableTracker] | None: + if not hashable(obj): + return None + # Custom allow/disallow in graph takes precedence over the general lookup. + if is_callable_disallowed(obj): + return SkipFunctionVariable + if is_callable_allowed(obj): + return TorchInGraphFunctionVariable + if is_polyfilled_callable(obj): + return PolyfilledFunctionVariable + if obj in BUILTIN_CALLABLES: + return BUILTIN_CALLABLES[obj] + if is_builtin_callable(obj): + return BuiltinVariable + return None + + +""" +Main entry point for looking up the trace rule (the Dynamo variable) for a given function object. +E.g, the lookup result of `torch.sin` is `TorchInGraphFunctionVariable`. +""" + + +def lookup(obj: object) -> type[VariableTracker] | None: + return lookup_inner(obj) + + +# also takes config.dont_skip_tracing into account +def lookup_inner( + obj: object, + name: str | None = None, + filename: str | None = None, + is_direct_call: bool = True, + reasons: None | set[str] = None, +) -> type[VariableTracker] | None: + result = _lookup_inner( + obj, + name=name, + filename=filename, + is_direct_call=is_direct_call, + reasons=reasons, + ) + # There are still some modules we should absolutely NOT trace into - e.g. most of torch._dynamo, + # as this can result in really weird tracing behaviors. + # Note that if a torch._dynamo function is already not skipped (e.g. functions in external_utils.py), + # then this branch does not apply. + if config.dont_skip_tracing and result is SkipFunctionVariable: + if filename is None: + filename = getfile(obj) + if filename is None: + raise AssertionError( + f"getfile returned None for {type(obj)} in dont_skip_tracing path" + ) + filename = _as_posix_path(filename) + torch_dir = _module_dir(torch) + if torch_dir is not None: + dynamo_path = _as_posix_path(torch_dir) + "_dynamo" + if filename.startswith(dynamo_path) and not filename.endswith( + "test_dont_skip_tracing_functions.py" + ): + return SkipFunctionVariable + if reasons is not None: + reasons.add( + "Attempted skip but we are ignoring skips due to torch._dynamo.config.dont_skip_tracing" + ) + return UserFunctionVariable + return result + + +def _lookup_inner( + obj: object, + name: str | None = None, + filename: str | None = None, + is_direct_call: bool = True, + reasons: set[str] | None = None, +) -> type[VariableTracker] | None: + # Step 1: lookup obj's tracing rule in `torch_name_rule_map`. + # The rules defined in `torch_name_rule_map` mainly includes two parts: + # - Manually defined rules for any functions. + # - The list of torch in graph functions. + try: + can_hash = hashable(obj) + except Exception: + can_hash = False + if not can_hash: + if reasons is not None: + reasons.add("obj is not hashable") + return None + if obj is not None: + if is_aten_op_or_tensor_method(obj): + return TorchInGraphFunctionVariable + rule = get_torch_obj_rule_map().get(obj, None) + if rule is not None: + if reasons is not None: + reasons.add("get_torch_obj_rule_map") + return rule + elif name is not None and filename is not None and not is_direct_call: + if name.startswith(TORCH_DYNAMO_RESUME_IN_PREFIX): + rule = get_torch_obj_rule_map().get( + filename + "#" + TORCH_DYNAMO_RESUME_IN_PREFIX, None + ) + else: + rule = get_torch_obj_rule_map().get(filename + "#" + name, None) + if rule is not None: + if reasons is not None: + reasons.add("get_torch_obj_rule_map") + return rule + elif name == "": + if reasons is not None: + reasons.add("inlining frame from list comprehension") + return UserFunctionVariable + + # Step 2: lookup obj's tracing rule by function name. + if is_direct_call: + if name == "patched_init": + if reasons is not None: + reasons.add("func name is patched_init") + return SkipFunctionVariable + elif name == "__torch_function__" or ( + obj and getattr(obj, "__name__", None) == "__torch_function__" + ): + if reasons is not None: + reasons.add("func name is __torch_function__") + return UserFunctionVariable + + if not is_direct_call: + if name == "__getattr__": + # is_direct_call = False indicates that this is the top-level frame + # being traced (i.e., it is not inlined and not called from + # InliningInstructionTranslator). Tracing __getattr__ at the top + # level is unlikely because we inline it for + # UserDefinedObjectVariable. This scenario occurs only for + # UnspecializedNNModuleVariable, where Dynamo directly calls + # __getattr__ during trace time, generating LOAD_ATTR bytecode + # without going through the underlying __getattr__ data structures. + # When this optimized bytecode is executed, Dynamo is triggered + # again on the __getattr__ call. Therefore, we skip Dynamo tracing + # in this case. + if reasons is not None: + reasons.add( + "Tracing __getattr__ as the top level frame, unsuitable for tracing." + ) + return SkipFunctionVariable + + # Step 3: lookup obj's tracing rule by filename. + if filename is None: + filename = getfile(obj) + + skip_result = check_file(filename, is_direct_call) + if reasons is not None and skip_result.reason is not None: + reasons.add(skip_result.reason) + if skip_result.skipped: + return SkipFunctionVariable + else: + return UserFunctionVariable + + +def clear_lru_cache() -> None: + torch._dynamo.trace_rules.get_torch_obj_rule_map.cache_clear() + torch._dynamo.trace_rules.get_tensor_method.cache_clear() + torch._dynamo.trace_rules.get_legacy_mod_inlinelist.cache_clear() + torch._dynamo.trace_rules.get_mod_inlinelist.cache_clear() + torch._dynamo.trace_rules.get_ngb_suppress_inlinelist.cache_clear() + torch._dynamo.trace_rules.dynamo_dir.cache_clear() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/types.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/types.py new file mode 100644 index 0000000000000000000000000000000000000000..54171fb981ba81121f378b49fc600aef1e56bc93 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/types.py @@ -0,0 +1,149 @@ +"""This module contains the core type definitions and protocols used throughout Dynamo. + +The types defined here fall into several categories: +- Guard related types (GuardFn, GuardFail, GuardedCode): Used for tracking and managing guards that protect compiled code +- Frame and cache types (FrameState, CacheEntry): Used for managing interpreter frame state and caching +- Callback protocols (DynamoCallbackFn): Define the interface for frame evaluation callbacks +- Hook protocols (DynamoGuardHook, ProfilerStartHook, ProfilerEndHook, BytecodeHook): Define various hook points for + instrumentation and customization + +These types provide the foundational interfaces that enable Dynamo's dynamic compilation and optimization system, +ensuring type safety and clear contracts between different components of the system. +""" + +import dataclasses +import types +from collections.abc import Callable, Mapping +from typing import Any, NamedTuple, Protocol, runtime_checkable + +# CacheEntry has a `guard_manager` field for the guard, and a `code` field for the code object. +from torch._C._dynamo.eval_frame import ( + _CacheEntry as CacheEntry, + _ExtraState as ExtraState, + _FrameAction as FrameAction, + _FrameExecStrategy as FrameExecStrategy, + _PyInterpreterFrame as DynamoFrameType, +) +from torch._guards import CompileId, Guard + + +# We use a dict to store additional data per frame. +FrameState = dict[Any, Any] + + +class GuardFail(NamedTuple): + # A string repr of the piece of failed guard code we eval-ed + reason: str + # A code object where we failed a guard + orig_code: types.CodeType + + +@dataclasses.dataclass(frozen=True) +class GuardFilterEntry: + name: str + has_value: bool + value: object + guard_type: str + derived_guard_types: tuple[str, ...] + is_global: bool + orig_guard: Guard + + +class GuardFn(Protocol): + closure_vars: dict[str, object] + args: list[str] + code_parts: list[str] + verbose_code_parts: list[str] + global_scope: dict[str, object] + guard_fail_fn: Callable[[GuardFail], None] | None + cache_entry: CacheEntry | None + extra_state: ExtraState | None + + # maps locals of user function to bool + def __call__(self, f_locals: dict[str, object]) -> bool: ... + + +@dataclasses.dataclass +class GuardedCode: + code: types.CodeType + guard_manager: GuardFn + compile_id: CompileId + trace_annotation: str = "Unknown" + + +@dataclasses.dataclass +class ConvertFrameReturn: + # default return is no compiled code (i.e. `return None`): + # strategy is to skip non-recursively, for all future intercepted frames too + + # eval frame execution strategy for this frame + frame_exec_strategy: FrameExecStrategy = dataclasses.field( + default_factory=lambda: FrameExecStrategy(FrameAction.SKIP, FrameAction.DEFAULT) + ) + # also apply frame_exec strategy to future frames with same code + apply_to_code: bool = True + guarded_code: GuardedCode | None = None + skip_reason: str | None = None + + +def wrap_guarded_code(guarded_code: GuardedCode) -> ConvertFrameReturn: + return ConvertFrameReturn( + frame_exec_strategy=FrameExecStrategy(FrameAction.DEFAULT, FrameAction.DEFAULT), + guarded_code=guarded_code, + ) + + +class DynamoCallbackFn(Protocol): + def __call__( + self, + frame: DynamoFrameType, + cache_entry: CacheEntry | None, + frame_state: FrameState, + ) -> ConvertFrameReturn: ... + + +DynamoCallback = DynamoCallbackFn | None | bool + + +CompilerConfig = Mapping[str, Any] + + +@runtime_checkable +class CompilerConfigProvider(Protocol): + def get_compiler_config(self) -> CompilerConfig | None: ... + + +class DynamoGuardHook(Protocol): + def __call__( + self, + guard_manager: GuardFn, + code: types.CodeType, + f_locals: dict[str, object], + index: int, + last: bool, + ) -> None: ... + + +class DynamoGuardCompleteHook(Protocol): + def __call__( + self, + cache_hit: bool, + ) -> bool: ... + + +class ProfilerStartHook(Protocol): + def __call__( + self, + name: str, + # TODO(whc) how do I annotate a _RecordFunction here? + ) -> Any: ... + + +class ProfilerEndHook(Protocol): + def __call__(self, record: Any) -> None: ... + + +class BytecodeHook(Protocol): + def __call__( + self, code: types.CodeType, new_code: types.CodeType + ) -> types.CodeType | None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/utils.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0b02c3db4fcccb64707fa79ff23539a6ee02c9dd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/utils.py @@ -0,0 +1,6019 @@ +""" +Utility functions and classes used throughout the TorchDynamo system. + +This module contains a collection of helper utilities used by various parts of Dynamo for: +- Performance metrics collection and reporting +- Compilation timing and debugging +- Graph manipulation and tensor operations +- Runtime guards and checks +- Common data structure operations +- Testing and development tools + +This is an internal module that provides shared functionality used across the Dynamo codebase. +""" + +from __future__ import annotations + +import atexit +import collections +import contextlib +import copy +import dataclasses +import datetime +import dis +import enum +import functools +import gc +import importlib +import inspect +import itertools +import json +import linecache +import logging +import math +import operator +import os +import re +import sys +import textwrap +import threading +import time +import traceback +import types +import typing +import uuid +import warnings +import weakref +from collections import Counter, OrderedDict +from contextlib import AbstractContextManager, contextmanager +from dataclasses import is_dataclass +from functools import lru_cache +from types import CodeType, MethodWrapperType +from typing import ( + Any, + cast, + ClassVar, + Generic, + Literal, + NoReturn, + overload, + TypeAlias, + TypeGuard, + TypeVar, +) +from typing_extensions import ParamSpec, TypeIs + +import torch +import torch._functorch.config +import torch.fx.experimental.symbolic_shapes +import torch.utils._pytree as pytree +from torch import fx +from torch._C import ( + _instruction_counter, + _len_torch_function_stack, + _pop_torch_function_stack, + _push_on_torch_function_stack, +) +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.metrics_context import MetricsContext, RuntimeMetricsContext +from torch._guards import CompileId, Source, TracingContext +from torch._subclasses.meta_utils import is_sparse_compressed +from torch._utils_internal import ( + justknobs_check, + log_chromium_event_internal, + log_compilation_event, + record_chromium_event_internal, + signpost_event, +) +from torch.fx._utils import _format_graph_code, lazy_format_graph_code +from torch.monitor import _WaitCounter +from torch.nn.modules.lazy import LazyModuleMixin +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils._triton import has_triton, has_triton_package +from torch.utils.hooks import RemovableHandle + +from .graph_utils import _get_flat_args + + +if typing.TYPE_CHECKING: + from collections.abc import ( + Callable, + Container, + Generator, + ItemsView, + Iterable, + Iterator, + KeysView, + Mapping, + Sequence, + ValuesView, + ) + + from torch._dynamo.bytecode_transformation import Instruction + from torch._dynamo.replay_record import ExecutionRecord + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.base import VariableTracker + from torch._prims_common import DeviceLikeType + from torch._subclasses import FakeTensorMode + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + +try: + import torch._logging + import torch._numpy as tnp + from torch._guards import detect_fake_mode # noqa: F401 + from torch._logging import LazyString + + from . import config + + # NOTE: Make sure `NP_SUPPORTED_MODULES` and `NP_TO_TNP_MODULE` are in sync. + if np: + NP_SUPPORTED_MODULES: tuple[types.ModuleType, ...] = ( + np, + np.fft, + np.linalg, + np.random, + ) + + NP_TO_TNP_MODULE = { + np: tnp, + np.fft: tnp.fft, + np.linalg: tnp.linalg, + np.random: tnp.random, + } + else: + NP_SUPPORTED_MODULES = () + + # pyrefly: ignore [implicit-any] + NP_TO_TNP_MODULE = {} + from torch._subclasses.fake_tensor import is_fake +except ImportError: + pass + + +T = TypeVar("T") +T1 = TypeVar("T1") +T2 = TypeVar("T2") +T3 = TypeVar("T3") +T4 = TypeVar("T4") +T5 = TypeVar("T5") +T6 = TypeVar("T6") +T7 = TypeVar("T7") +T8 = TypeVar("T8") +T9 = TypeVar("T9") +T10 = TypeVar("T10") +R = TypeVar("R") +_P = ParamSpec("_P") + +unpatched_nn_module_getattr = torch.nn.Module.__getattr__ +unpatched_nn_module_call = torch.nn.Module.__call__ +unpatched_nn_module_call_impl = torch.nn.Module._call_impl + +counters: collections.defaultdict[str, Counter[str]] = collections.defaultdict( + collections.Counter +) +optimus_scuba_log: dict[str, Any] = {} +troubleshooting_url = "https://docs.pytorch.org/docs/main/user_guide/torch_compiler/compile/programming_model.recompilation.html" +nnmodule_doc_url = "https://docs.pytorch.org/docs/main/user_guide/torch_compiler/torch.compiler_nn_module.html" +nnmodule_doc_url_msg = f"See {nnmodule_doc_url} for more information and limitations." +log = logging.getLogger(__name__) + +# profiling compilation time by function +compilation_time_metrics: dict[str, list[float]] = {} + +# This supports calculate_time_spent(), which reports cumulative times +# across the process for any "phase" populated by dynamo_timed. Reset if +# reset_frame_count() is called. +cumulative_time_spent_ns: dict[str, float] = collections.defaultdict(float) + +timer_counter = itertools.count() + + +# Abstraction on top of counters. +class ReInplaceTrigger(enum.Enum): + AUTO_FUNC_V1 = 1 + AUTO_FUNC_V2 = 2 + TRITON_OPS = 3 + + +class ReinplaceCounters: + _values: collections.defaultdict[str, int] = collections.defaultdict(int) + + # Track sizes of known not re-inplaced tensors (exclude dynamic shapes). + @classmethod + def add_missed_bytes(cls, trigger: ReInplaceTrigger, bytes: int) -> None: + if bytes != 0: + cls._values[f"missed_bytes_{trigger.name}"] += bytes + + # Track number of not re-inplaced tensors. + @classmethod + def add_missed_opportunities(cls, trigger: ReInplaceTrigger, count: int) -> None: + if count != 0: + cls._values[f"missed_tensors_{trigger.name}"] += count + + @classmethod + def clear(cls) -> None: + cls._values.clear() + + @classmethod + def get_total_missed(cls) -> int: + sum = 0 + for trigger in ReInplaceTrigger: + sum += cls._values.get(f"missed_tensors_{trigger.name}", 0) + return sum + + @classmethod + def get_total_missed_bytes(cls) -> int: + sum = 0 + for trigger in ReInplaceTrigger: + sum += cls._values.get(f"missed_bytes_{trigger.name}", 0) + return sum + + @classmethod + def log(cls) -> None: + # if not empty log. + if cls._values: + signpost_event("inductor", "reinplace_counters", cls._values) + + +def tabulate( + rows: list[tuple[str, Any]] | list[list[Any]], + headers: tuple[str, ...] | list[str], +) -> str: + try: + import tabulate + + return tabulate.tabulate(rows, headers=headers) + except ImportError: + return "\n".join( + ", ".join(map(str, row)) for row in itertools.chain([headers], rows) + ) + + +curr_frame = 0 + + +# Note: Called for you by dynamo - you almost never ever want to invoke this yourself. +def increment_frame() -> None: + global curr_frame + curr_frame = curr_frame + 1 + + +# Note: Called for you by dynamo - you almost never ever want to invoke this yourself. +def reset_frame_count() -> None: + global curr_frame + cumulative_time_spent_ns.clear() + compilation_time_metrics.clear() + curr_frame = 0 + + +_recompile_user_contexts: list[Callable[[], str]] | None = None + + +def register_hook_for_recompile_user_context(hook: Callable[[], str]) -> None: + """ + Register a hook to be called when a recompile is triggered. The hook + should return a string describing user contexts that are not available + to the compiler, such as the current training epoch. This is useful for + debugging and data analysis for recompile. For data retention purposes, + the user context string is capped at 256 characters. + """ + global _recompile_user_contexts + if _recompile_user_contexts is None: + _recompile_user_contexts = [] + _recompile_user_contexts.append(hook) + + +def get_hook_for_recompile_user_context() -> list[Callable[[], str]] | None: + return _recompile_user_contexts + + +def reset_recompile_user_contexts() -> None: + """Clear any registered recompile user-context hooks (test helper).""" + global _recompile_user_contexts + _recompile_user_contexts = None + + +op_count = 0 + + +def increment_op_count(cnt: int) -> None: + global op_count + op_count += cnt + + +# Get the total time in seconds for each "phase" +# For example, {'entire_frame_compile':8.574629999999999, 'backend_compile':5.26806} +def calculate_time_spent() -> dict[str, float]: + total_by_key = {} + for phase, timing in cumulative_time_spent_ns.items(): + total_by_key[phase] = timing / 1e9 + + total_by_key["total_wall_time"] = total_by_key.get( + "entire_frame_compile", 0 + ) + total_by_key.get("entire_backward_compile", 0) + return total_by_key + + +# Print a report of time spent so far +# Ex: +# TIMING: +# entire_frame_compile:8.574629999999999 +# backend_compile:5.26806 +def print_time_report() -> None: + total_by_key = calculate_time_spent() + + out = "TIMING:" + for key, value in total_by_key.items(): + out = f"{out} {key}:{round(value, 5)}" + + print(out) + + +# Use the following singleton to capture and log CompilationMetrics. Entering the context +# manager allocates a new record to be logged when it exits. (You should not need to use +# this directly unless you introduce a new code path where compilation metrics would be +# gathered). While compiling, use the setters or timer in MetricsContext to update fields +# in the current context. For example: +# +# To set a single field once (use overwrite=True to overwrite): +# get_metrics_context().set("metric_name", value) +# +# To set multiple fields at once (use overwrite=True to overwrite): +# get_metrics_context().update({"name1": val1, "name2": val2}) +# +# To increment an integer field: +# get_metrics_context().increment("metric_name", value) +# +# To record execution time, MetricsContext works with dynamo_timed: +# def foo(...): +# # Updates the "metric_us" field. +# with dynamo_timed("metric", dynamo_compile_column_us="metric_us") +# ... +# +_metrics_context_tls = threading.local() + + +def get_metrics_context() -> MetricsContext: + if not hasattr(_metrics_context_tls, "metrics_context"): + _metrics_context_tls.metrics_context = MetricsContext( + on_exit=record_compilation_metrics + ) + return _metrics_context_tls.metrics_context + + +def get_runtime_metrics_context() -> RuntimeMetricsContext: + if not hasattr(_metrics_context_tls, "runtime_metrics_context"): + _metrics_context_tls.runtime_metrics_context = RuntimeMetricsContext( + on_exit=record_compilation_metrics + ) + return _metrics_context_tls.runtime_metrics_context + + +class CompileEventLogLevel(enum.Enum): + """ + Enum that loosely corresponds with a "log level" of a given event. + + CHROMIUM_EVENT: Logs only to tlparse. + COMPILE_EVENT: Logs to tlparse + PT2 Compile Events + COMPILATION_METRIC: Logs to tlparse, PT2 Compile Events, and dynamo_compile + """ + + CHROMIUM = 1 + PT2_COMPILE = 2 + COMPILATION_METRIC = 3 + + +class CompileEventLogger: + """ + Helper class for representing adding metadata(i.e. columns) to various compile events. + Use CompileEventLogger to add event data to: + - Chromium events + - PT2 Compile Events + - CompilationMetrics + + This should be used in conjunction with dynamo_timed() and metrics contexts, which create + timed spans and events. CompileEventLogger uses three log levels (described in CompileEventLogLevel), + where each log level logs to all sources below it in the hierarchy. + + Example usages: + - I want to log to an existing chromium event within dynamo timed: + with dynamo_timed("my_event"): + CompileEventLogger.chromium("my_event", foo=bar) + + - I want to log my event to both chromium + pt2_compile_events: + with dynamo_timed("my_event", log_pt2_compile_event=True): + CompileEventLogger.pt2_compile("my_event", foo=bar) + + - I want to add information to dynamo events and dynamo_compile + CompileEventLogger.compilation_metric(foo=bar) + """ + + @staticmethod + def log_instant_event( + event_name: str, + metadata: dict[str, Any], + time_ns: int | None = None, + log_level: CompileEventLogLevel = CompileEventLogLevel.CHROMIUM, + ) -> None: + if time_ns is None: + time_ns = time.time_ns() + chromium_log = get_chromium_event_logger() + if log_level == CompileEventLogLevel.CHROMIUM: + log_pt2_compile_event = False + elif log_level == CompileEventLogLevel.PT2_COMPILE: + log_pt2_compile_event = True + else: + raise RuntimeError( + "Cannot log instant event at COMPILATION_METRIC level. Please choose one of CHROMIUM_EVENT or COMPILE_EVENT" + ) + chromium_log.log_instant_event( + event_name, time_ns, metadata, log_pt2_compile_event + ) + + @staticmethod + def add_data( + event_name: str, + log_level: CompileEventLogLevel, + overwrite: bool = False, + **metadata: object, + ) -> None: + """ + Centralized API for adding data to various events + Log an event to a toplevel "dynamo" event or metrics context + depending on log level. + """ + chromium_log = get_chromium_event_logger() + pt2_compile_substack = chromium_log.get_pt2_compile_substack() + + if log_level == CompileEventLogLevel.CHROMIUM: + chromium_log.add_event_data(event_name, **metadata) + elif log_level == CompileEventLogLevel.PT2_COMPILE: + pt2_compile_substack = chromium_log.get_pt2_compile_substack() + if event_name not in pt2_compile_substack: + raise RuntimeError( + "Error: specified log level PT2_COMPILE, but the event %s" + " is not logged to pt2_compile_events. Make sure the event is active and you passed " + "log_pt2_compile_event=True to dynamo_timed", + event_name, + ) + chromium_log.add_event_data(event_name, **metadata) + else: + if log_level != CompileEventLogLevel.COMPILATION_METRIC: + raise AssertionError( + f"Expected log_level to be COMPILATION_METRIC, got {log_level}" + ) + top_event = chromium_log.get_outermost_event() + + if event_name != top_event: + raise RuntimeError( + "Log level is COMPILATION_METRIC, but event_name isn't the toplevel event. " + "CompilationMetrics must be logged to the toplevel event. Consider using `log_toplevel_event_data` directly." + ) + metrics_context = get_metrics_context() + if not metrics_context.in_progress(): + raise RuntimeError( + "No metrics context is in progress. Please only call this function within a metrics context." + ) + + # TODO: should we assert that the keys of metadata are in CompilationMetrics? + metrics_context.update(metadata, overwrite) + chromium_log.add_event_data(event_name, **metadata) + + @staticmethod + def add_toplevel( + log_level: CompileEventLogLevel, overwrite: bool = False, **metadata: object + ) -> None: + """ + Syntactic sugar for logging to the toplevel event + """ + top_event = get_chromium_event_logger().get_outermost_event() + if top_event is None: + raise RuntimeError( + "No toplevel event active. Please only call this function within a dynamo_timed context." + ) + CompileEventLogger.add_data(top_event, log_level, overwrite, **metadata) + + @staticmethod + def increment( + event_name: str, log_level: CompileEventLogLevel, key: str, value: int + ) -> None: + """ + Increments an existing field, or adds it + """ + chromium_log = get_chromium_event_logger() + if ( + log_level == CompileEventLogLevel.CHROMIUM + or log_level == CompileEventLogLevel.PT2_COMPILE + ): + chromium_log.increment(event_name, key, value) + else: + if log_level != CompileEventLogLevel.COMPILATION_METRIC: + raise AssertionError( + f"Expected log_level to be COMPILATION_METRIC, got {log_level}" + ) + top_event = chromium_log.get_outermost_event() + if event_name != top_event: + raise RuntimeError( + "Log level is COMPILATION_METRIC, but event_name isn't the toplevel event. " + "CompilationMetrics must be logged to the toplevel event. Consider using `increment_toplevel` directly." + ) + + metrics_context = get_metrics_context() + if not metrics_context.in_progress(): + raise RuntimeError( + "No metrics context is in progress. Please only call this function within a metrics context/dynamo_timed." + ) + + metrics_context.increment(key, value) + chromium_log.increment(event_name, key, value) + + @staticmethod + def increment_toplevel( + key: str, + value: int = 1, + log_level: CompileEventLogLevel = CompileEventLogLevel.COMPILATION_METRIC, + ) -> None: + """ + Increments a value on the toplevel metric. By default, logs to metric. + """ + chromium_log = get_chromium_event_logger() + top_event = chromium_log.get_outermost_event() + if top_event is None: + raise RuntimeError( + "No toplevel event active. Please only call this function within a metrics context/dynamo_timed." + ) + CompileEventLogger.increment(top_event, log_level, key, value) + + @staticmethod + def add_to_set( + event_name: str, log_level: CompileEventLogLevel, key: str, value: Any + ) -> None: + """ + Add metadata to a set of values with key . Creates a set if it doesn't exist. + """ + chromium_log = get_chromium_event_logger() + if ( + log_level == CompileEventLogLevel.CHROMIUM + or log_level == CompileEventLogLevel.PT2_COMPILE + ): + chromium_log.add_to_set(event_name, key, value) + else: + if log_level != CompileEventLogLevel.COMPILATION_METRIC: + raise AssertionError( + f"Expected log_level to be COMPILATION_METRIC, got {log_level}" + ) + top_event = chromium_log.get_outermost_event() + if event_name != top_event: + raise RuntimeError( + "Log level is COMPILATION_METRIC, but event_name isn't the toplevel event. " + "CompilationMetrics must be logged to the toplevel event. Consider using `add_to_set_metric` directly." + ) + + metrics_context = get_metrics_context() + if not metrics_context.in_progress(): + raise RuntimeError( + "No metrics context is in progress. Please only call this function within a metrics context/dynamo_timed." + ) + + metrics_context.add_to_set(key, value) + chromium_log.add_to_set(event_name, key, value) + + @staticmethod + def add_to_set_toplevel( + key: str, + value: Any, + log_level: CompileEventLogLevel = CompileEventLogLevel.COMPILATION_METRIC, + ) -> None: + """ + Same as add to set, just does it automatically to the toplevel event instead of having to explicitly name it. + Defaults to COMPILATION_METRIC log level. + """ + chromium_log = get_chromium_event_logger() + top_event = chromium_log.get_outermost_event() + if top_event is None: + raise RuntimeError( + "No toplevel event active. Please only call this function within a metrics context/dynamo_timed." + ) + CompileEventLogger.add_to_set(top_event, log_level, key, value) + + # Helper functions that are syntactic sugar + + @staticmethod + def chromium(event_name: str, **metadata: object) -> None: + """ + Add to in chromium. Each key/value of metadata will appear in the chromium trace. + should be the name of a timed event span passed to `dynamo_timed`. + """ + CompileEventLogger.add_data( + event_name, CompileEventLogLevel.CHROMIUM, overwrite=False, **metadata + ) + + @staticmethod + def pt2_compile(event_name: str, **metadata: object) -> None: + """ + Add to in chromium and PT2 Compile Events. + Each key/value of metadata will appear in the chromium trace. Each kwarg name becomes + a column in PT2 Compile Events, with the corresponding kwarg value. + should be the name of a timed event span passed to `dynamo_timed`, + with log_to_pt2_compile_events=True. + """ + CompileEventLogger.add_data( + event_name, CompileEventLogLevel.PT2_COMPILE, overwrite=False, **metadata + ) + + @staticmethod + def add_record_function_data(event_name: str, **metadata: object) -> None: + """ + Add record function data to the profiler event. + + This emits profiler event data so compilation events show up in stack profilers + like the PyTorch profiler. + + Args: + event_name: Name of the event to record + **metadata: Additional metadata to attach to the record function + """ + if torch.autograd.profiler._is_profiler_enabled and metadata: + metadata_str = ", ".join(f"{k}={v}" for k, v in metadata.items()) + with torch.autograd.profiler.record_function( + f"{event_name}_data: {metadata_str}" + ): + pass + + @staticmethod + def compilation_metric(overwrite: bool = False, **metadata: object) -> None: + """ + Add to the CompilationMetrics context. Also logs to PT2 Compile Events + and chromium. + Each key/value of metadata will appear in the chromium trace. Each kwarg name becomes + a column in PT2 Compile Events and Dynamo Compile, with the corresponding kwarg value. + """ + CompileEventLogger.add_toplevel( + CompileEventLogLevel.COMPILATION_METRIC, overwrite, **metadata + ) + + @staticmethod + def instant( + event_name: str, metadata: dict[str, Any], time_ns: int | None = None + ) -> None: + """ + Log an instant event to chromium logs with name at time . The `args` field in + Perfetto will point to metadata. should be a value obtained from time.time_ns(). + """ + CompileEventLogger.log_instant_event( + event_name, metadata, time_ns, CompileEventLogLevel.CHROMIUM + ) + + @staticmethod + def try_add_pt2_compile(event_name: str, **metadata: object) -> None: + """ + Adds to an existing pt2_compile event, but silently returns if the event doesn't exist + or ChromiumEventLogger is not initialized. + This function is syntactic sugar for chromium_event_logger().try_add_event_data. + """ + if not chromium_event_log_active(): + return + chromium_log = get_chromium_event_logger() + chromium_log.try_add_event_data(event_name, **metadata) + + @staticmethod + def try_(method_fn: Callable[_P, Any], *args: _P.args, **kwargs: _P.kwargs) -> None: + """ + Special function that quietly runs a given method, returning if CHROMIUM_EVENT_LOG is None or metrics context is not set + """ + if not chromium_event_log_active(): + return + metrics_context = get_metrics_context() + if not metrics_context.in_progress(): + return + method_fn(*args, **kwargs) + + +_dynamo_timed_tls = threading.local() + + +@contextmanager +def compile_time_record_function(name: str) -> Generator[Any, None, None]: + """ + A context manager for compile-time profiling that uses _RecordFunctionFast + for lower overhead than torch.profiler.record_function. + + This is intended for use during compilation (dynamo, inductor, etc.) where + we want profiling support but with minimal overhead. Moreover, we do not + want the record_function call inside torch.compile to be dispatched. + + Args: + name: The name of the record function event that will appear in profiles. + """ + if torch.autograd.profiler._is_profiler_enabled: + rf = torch._C._profiler._RecordFunctionFast(name) + rf.__enter__() + try: + yield + finally: + rf.__exit__(None, None, None) + else: + yield + + +@contextmanager +def dynamo_timed( + key: str, + # TODO(masneral): Deprecate this param. + phase_name: str | None = None, + log_pt2_compile_event: bool = False, + metadata: dict[str, object] | None = None, + dynamo_compile_column_us: str | None = None, + compile_id: CompileId | None = None, + is_backward: bool | None = None, + log_waitcounter: bool = False, + waitcounter_name_override: str | None = None, +) -> Generator[Any, None, None]: + """ + dynamo_timed is a context manager + By wrapping a function in dynamo_timed, we can get a few things: + + 1) Optionally log timings to pt2_compile_events. + 2) Optionally log timings to CompilationMetrics (dynamo_compile). + 3) Optionally log chromium events. + 4) Optionally increment a WaitCounter. + 5) Store a record in compilation_time_metrics + For example: + + def _foo(...): + with dynamo_timed("_foo"): + ... + + Would show up as an entry in our timing dict: + OrderedDict([('_foo', [0.083690, 0.23949, 3.1425e-05])]) + This is extremely useful for granular debugging. + + Although it is tempting to use dynamo_timed as a decorator, please do not. + In its decorator form it makes cProfile traces less useful as dynamo_timed + suddenly becomes a bottleneck for lots of function calls (as only one parent + pointer is recorded). + + Params: + - key: key into compile_time_metrics. If phase_name is not provided, this is + also the event name used for pt2_compile_events logs and chromium events. + - phase_name: Optional override for the event name. + - log_pt2_compile_event: Whether to log a pt2 compile event internally. + - metadata: Extra metadata to put in pt2_compile_events. + - dynamo_compile_column_us: If provided, updates the specified CompilationMetrics + field to be logged to dyname_compile column. We expect all columns to be _us; + therefore, the field name must end with "_us". + - compile_id: In the typical case, this parameter should not be needed. Use to + supply the compile_id for those cases where we want to log a compile_id where + it's not naturally available, e.g., for runtime autotuning. + - is_backward: Specify forward/backward directly when not available in a + CompileContext, e.g., during runtime autotuning. + that support it. + - log_waitcounter: If set, we'll log a waitcounter of the form "pytorch.dynamo_timed.{key}" + """ + if phase_name: + event_name = phase_name + fn_name = key + else: + event_name = key + fn_name = None + + if key not in compilation_time_metrics: + compilation_time_metrics[key] = [] + + metrics = compilation_time_metrics[key] + event_metadata = {} + if metadata: + event_metadata.update(metadata) + if fn_name: + event_metadata.update({"fn_name": fn_name}) + if is_backward is not None: + event_metadata.update({"is_backward": is_backward}) + + chromium_log: ChromiumEventLogger = get_chromium_event_logger() + start_ns = time.time_ns() + chromium_log.log_event_start( + event_name, start_ns, event_metadata, log_pt2_compile_event, compile_id + ) + + cx_mgrs: list[typing.Any] = [compile_time_record_function(f"{key} (dynamo_timed)")] + if log_waitcounter: + wc_name = waitcounter_name_override or key + cx_mgrs.append(_WaitCounter(f"pytorch.wait_counter.{wc_name}").guard()) + + is_compile_time = torch._guards.CompileContext.current_compile_id() is not None + if dynamo_compile_column_us: + # We're standardizing on microseconds for dynamo_compile timings. + if not dynamo_compile_column_us.endswith("_us"): + raise AssertionError( + f"dynamo_compile_column_us must end with '_us', got {dynamo_compile_column_us!r}" + ) + + # Track nested dynamo_timed calls that update CompilationMetrics so we can + # bump a total duration only for the outermost metric. + if not hasattr(_dynamo_timed_tls, "depth"): + _dynamo_timed_tls.depth = 0 + _dynamo_timed_tls.depth += 1 + + # The corresponding WaitCounters that we bump for all overheads + if _dynamo_timed_tls.depth == 1: + cx_mgrs.append(_WaitCounter("pytorch.wait_counter.dynamo_compile").guard()) + if not is_compile_time: + runtime_wc = "pytorch.wait_counter.compile_runtime_overheads" + cx_mgrs.append(_WaitCounter(runtime_wc).guard()) + + try: + with contextlib.ExitStack() as stack: + for cx in cx_mgrs: + stack.enter_context(cx) + yield + finally: + end_ns = time.time_ns() + time_spent_ns = end_ns - start_ns + metrics.append(time_spent_ns / 1e9) + chromium_log.log_event_end( + event_name, end_ns, {}, start_ns, log_pt2_compile_event, compile_id + ) + if dynamo_compile_column_us: + # TODO: the events that we capture in calculate_time_spent() seem a little + # arbitrary. Currently, it's only those fields that are present in + # CompilationMetrics (but note that we accumulate by the associated event + # name, not the field name in CompilationMetrics). Do we want to keep it + # this way? + cumulative_time_spent_ns[event_name] += time_spent_ns + + # Bump the total duration for every outer event. + _dynamo_timed_tls.depth -= 1 + is_outer_event = _dynamo_timed_tls.depth == 0 + + duration_us = time_spent_ns // 1000 + if is_compile_time: + metrics_context = get_metrics_context() + if metrics_context.in_progress(): + metrics_context.increment(dynamo_compile_column_us, duration_us) + if is_outer_event: + metrics_context.increment("duration_us", duration_us) + else: + runtime_context = get_runtime_metrics_context() + runtime_context.increment(dynamo_compile_column_us, duration_us) + if is_outer_event: + extra = { + "compile_id": compile_id, + "is_runtime": True, + "is_forward": not is_backward, + } + runtime_context.increment("duration_us", duration_us, extra) + + +@overload +def compile_times(repr: Literal["str"], aggregate: bool = False) -> str: ... + + +@overload +# pyrefly: ignore [inconsistent-overload] +def compile_times( + repr: Literal["csv"], aggregate: bool = False +) -> tuple[list[str], list[object]]: ... + + +def compile_times( # type: ignore[misc] + repr: str = "str", aggregate: bool = False +) -> str | None | tuple[list[str], list[str]]: + """ + Get metrics about torchdynamo frontend/backend compilation times. + + Accumulates information from functions tagged with `dynamo_timed`. + + repr='str' returns a printable string for user interaction, and 'csv' + returns headers, rows which can be logged for output + + aggregate causes values from multiple compilations (e.g. split graphs) + to be accumulated into one value. If false, expect more than one value + per metric. + """ + + def fmt_fn(values: list[float], item_fn: Callable[[float], str] = str) -> str: + if aggregate: + return item_fn(sum(values)) + return ", ".join(map(item_fn, values)) + + if repr == "str": + rows = [ + (k, fmt_fn(compilation_time_metrics[k], item_fn=lambda x: f"{x:.4f}")) + for k in compilation_time_metrics + ] + out = "TorchDynamo compilation metrics:\n" + out += tabulate(rows, headers=("Function", "Runtimes (s)")) + return out + elif repr == "csv": + values = [ + fmt_fn(v, item_fn=lambda x: f"{x:.6f}") + for v in compilation_time_metrics.values() + ] + headers = list(compilation_time_metrics.keys()) + return headers, values + return None + + +@atexit.register +def dump_compile_times() -> None: + log.info(compile_times(repr="str", aggregate=True)) + + +tensortype_to_dtype = { + torch.FloatTensor: (torch.float32, torch.float), + torch.DoubleTensor: (torch.float64, torch.double), + torch.HalfTensor: (torch.float16, torch.half), + torch.BFloat16Tensor: (torch.bfloat16,), + torch.ByteTensor: (torch.uint8,), + torch.CharTensor: (torch.int8,), + torch.LongTensor: (torch.int64, torch.long), + torch.IntTensor: (torch.int32, torch.int), + torch.ShortTensor: (torch.int16, torch.short), + torch.BoolTensor: (torch.bool,), +} + + +class DuplicateWarningChecker: + def __init__(self, maxsize: int = 4096) -> None: + self.maxsize = maxsize + self.reset() + + def reset(self) -> None: + self.set: OrderedDict[Any, Any] = OrderedDict() + + def add(self, key: str | tuple[object, object]) -> bool: + if key in self.set: + self.set.move_to_end(key, last=True) + if not config.verbose: + return False + else: + self.set[key] = None + while len(self.set) > self.maxsize: + self.set.popitem(last=False) + return True + + +graph_break_dup_warning_checker = DuplicateWarningChecker() + + +def setup_compile_debug() -> contextlib.ExitStack: + compile_debug = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1" + + if compile_debug: + return add_file_handler() + + return contextlib.ExitStack() + + +def reset_graph_break_dup_checker() -> None: + graph_break_dup_warning_checker.reset() + + +# Matches ANSI escape sequences (CSI) +ANSI_ESCAPE_PATTERN = re.compile( + r""" + \x1B # ESC + \[ # [ + [0-?]* # Parameter bytes + [ -/]* # Intermediate bytes + [@-~] # Final byte + """, + re.VERBOSE, +) + + +class StripAnsiFormatter(logging.Formatter): + """Logging formatter that strips ANSI escape codes.""" + + def format(self, record: logging.LogRecord) -> str: + msg = super().format(record) + return ANSI_ESCAPE_PATTERN.sub("", msg) + + +def add_file_handler() -> contextlib.ExitStack: + log_path = os.path.join(get_debug_dir(), "torchdynamo") + os.makedirs(log_path, exist_ok=True) + + log_file_handler = logging.FileHandler(os.path.join(log_path, "debug.log")) + log_file_handler.setFormatter(StripAnsiFormatter("%(message)s")) + logger = logging.getLogger("torch._dynamo") + logger.addHandler(log_file_handler) + + exitstack = contextlib.ExitStack() + exitstack.callback(lambda: logger.removeHandler(log_file_handler)) + return exitstack + + +def setup_log_file() -> contextlib.ExitStack: + exitstack = contextlib.ExitStack() + if config.log_file_name is not None: + log_file_handler = logging.FileHandler(config.log_file_name) + for logger in torch._logging._internal.get_loggers(): + logger.addHandler(log_file_handler) + exitstack.callback(lambda: logger.removeHandler(log_file_handler)) + return exitstack + + return exitstack + + +def gen_record_file_name(exc: Exception, code: CodeType) -> str: + return f"{get_debug_dir()}/error_recordings/\ +{code.co_name}_{type(exc).__name__}_{code.co_firstlineno}.rec" + + +def write_record_to_file(filename: str, exec_record: ExecutionRecord) -> None: + try: + if os.path.exists(filename): + log.warning( + "Unable to write execution record %s; file already exists.", filename + ) + else: + os.makedirs(os.path.dirname(filename), exist_ok=True) + with open(filename, "wb") as f: + exec_record.dump(f) + except Exception: + log.exception("Unable to write execution record %s", filename) + + +def count_calls(g: fx.Graph) -> int: + c = 0 + for n in g.nodes: + if "call" in n.op: + c += 1 + return c + + +def identity(x: T) -> T: + return x + + +def hashable(x: object) -> bool: + try: + hash(x) + return True + except TypeError: + return False + # cannot hash writable memoryview object + except ValueError: + return False + + +def nothing(*args: Any, **kwargs: Any) -> None: + pass + + +class ExactWeakKeyDictionary: + """Similar to weakref.WeakKeyDictionary, but use `is`/`id` rather than `==` to compare equality""" + + def __init__(self) -> None: + self.values: dict[int, Any] = {} + self.refs: dict[int, weakref.ReferenceType[Any]] = {} + + def __getitem__(self, key: Any) -> Any: + return self.values[id(key)] + + def get(self, key: Any, default: Any = None) -> Any: + return self.values.get(id(key), default) + + def __contains__(self, key: Any) -> bool: + return id(key) in self.values + + def __setitem__(self, key: Any, value: Any) -> None: + idx = id(key) + if idx not in self.refs: + self.refs[idx] = weakref.ref(key, lambda ref: self._remove_id(idx)) + self.values[idx] = value + + def _remove_id(self, idx: int) -> None: + if idx in self.values: + del self.values[idx] + if idx in self.refs: + del self.refs[idx] + + def clear(self) -> None: + self.refs.clear() + self.values.clear() + + +@overload +def istype(obj: object, allowed_types: type[T]) -> TypeIs[T]: ... + + +# This can be simplified once TypeVarTuple objects can be expanded into TypeIs. +@overload +def istype( + obj: object, allowed_types: tuple[type[T1], type[T2]] +) -> TypeIs[T1 | T2]: ... + + +@overload +def istype( + obj: object, allowed_types: tuple[type[T1], type[T2], type[T3]] +) -> TypeIs[T1 | T2 | T3]: ... + + +@overload +def istype( + obj: object, allowed_types: tuple[type[T1], type[T2], type[T3], type[T4]] +) -> TypeIs[T1 | T2 | T3 | T4]: ... + + +@overload +def istype( + obj: object, allowed_types: tuple[type[T1], type[T2], type[T3], type[T4], type[T5]] +) -> TypeIs[T1 | T2 | T3 | T4 | T5]: ... + + +@overload +def istype( + obj: object, + allowed_types: tuple[type[T1], type[T2], type[T3], type[T4], type[T5], type[T6]], +) -> TypeIs[T1 | T2 | T3 | T4 | T5 | T6]: ... + + +@overload +def istype( + obj: object, + allowed_types: tuple[ + type[T1], type[T2], type[T3], type[T4], type[T5], type[T6], type[T7] + ], +) -> TypeIs[T1 | T2 | T3 | T4 | T5 | T6 | T7]: ... + + +@overload +def istype( + obj: object, + allowed_types: tuple[ + type[T1], type[T2], type[T3], type[T4], type[T5], type[T6], type[T7], type[T8] + ], +) -> TypeIs[T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8]: ... + + +@overload +def istype( + obj: object, + allowed_types: tuple[ + type[T1], + type[T2], + type[T3], + type[T4], + type[T5], + type[T6], + type[T7], + type[T8], + type[T9], + ], +) -> TypeIs[T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9]: ... + + +@overload +def istype( + obj: object, + allowed_types: tuple[ + type[T1], + type[T2], + type[T3], + type[T4], + type[T5], + type[T6], + type[T7], + type[T8], + type[T9], + type[T10], + ], +) -> TypeIs[T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10]: ... + + +@overload +def istype( + obj: object, allowed_types: tuple[type, ...] | list[type] | set[type] +) -> bool: ... + + +def istype(obj: object, allowed_types: Any) -> bool: + """isinstance() without subclasses""" + if isinstance(allowed_types, (tuple, list, set)): + return type(obj) in allowed_types + return type(obj) is allowed_types + + +_builtin_final_typing_classes: tuple[Any, ...] = tuple() +if sys.version_info >= (3, 12): + # Some typing classes moved to C in 3.12, + # which no longer have the _Final mixin. + # Check for consistency e.g. here: + # https://github.com/python/cpython/blob/f2b82b3b3b1f8c7a81e84df35ee921e44517cf32/Lib/typing.py#L32 + _builtin_final_typing_classes = ( + typing.ParamSpecArgs, + typing.ParamSpecKwargs, + typing.ParamSpec, + typing.TypeVar, + typing.TypeVarTuple, + typing.TypeAliasType, + ) + + +def get_inputs_devices( + inputs: collections.abc.Sequence[object], + model: torch.fx.GraphModule, +) -> list[torch.device | None]: + all_inputs = pytree.tree_flatten(inputs)[0] + [ + node.meta["val"] for node in list(model.graph.nodes) if "val" in node.meta + ] + devices: list[torch.device | None] = list( + OrderedSet([i.device for i in all_inputs if hasattr(i, "device")]) + ) + return [ + i for i in devices if (isinstance(i, torch.device) and i.type != "meta") + ] + [None] + + +if sys.version_info >= (3, 14): + _builtin_final_typing_classes += (typing.Union,) + + +def is_typing(value: object) -> bool: + # _Final catches most of typing classes: + # - Any + # - Callable + # - Union (Python < 3.14) + # ... + # + # NB: we intentionally ignore classes that inherit from Generic, since they + # can be used as both TypingVariable as well as UserDefinedClassVariable. + if sys.version_info >= (3, 12) and isinstance(value, _builtin_final_typing_classes): + return True + return ( + isinstance(value, (types.UnionType, typing._Final)) # type: ignore[attr-defined] + or value is typing.Generic + or value is typing.Union + ) + + +def is_numpy_int_type(value: object) -> bool: + if not np: + return False + + return istype( + value, + ( + np.int8, + np.int16, + np.int32, + np.int64, + np.uint8, + np.uint16, + np.uint32, + np.uint64, + ), + ) + + +def is_numpy_float_type(value: object) -> bool: + if not np: + return False + + return istype( + value, + ( + np.float16, + np.float32, + np.float64, + ), + ) + + +_unpack_fast_types_cache: tuple[type, ...] | None = None + + +def _unpack_fast_types() -> tuple[type, ...]: + # Builtin iterables whose elements we can get directly via + # unpack_var_sequence, skipping the generic iter/getiter/iternext protocol + # (a bottleneck for large iterables). Built lazily since `variables` is a + # circular import at module load. + global _unpack_fast_types_cache + if _unpack_fast_types_cache is None: + from . import variables + + _unpack_fast_types_cache = ( + variables.ConstDictVariable, + variables.DictViewVariable, + variables.MappingProxyVariable, + variables.DequeVariable, + variables.ListVariable, + variables.ListIteratorVariable, + variables.RangeVariable, + variables.SetVariable, + variables.TensorVariable, + variables.TupleVariable, + ) + return _unpack_fast_types_cache + + +def unpack_iterable( + tx: InstructionTranslatorBase, iterable: VariableTracker +) -> list[VariableTracker]: + if isinstance(iterable, _unpack_fast_types()): + # unpack_var_sequence returns a fresh list, so hand it back directly: + # no generator, no per-element callback, single allocation. + return iterable.unpack_var_sequence(tx) + return list(lazily_unpack(tx, iterable)) + + +def unpack_and_apply_fn( + tx: InstructionTranslatorBase, + iterable: VariableTracker, + apply_fn, +) -> None: + for item in lazily_unpack(tx, iterable): + apply_fn(item) + + +def lazily_unpack( + tx: InstructionTranslatorBase, + iterable: VariableTracker, +): + from .exc import handle_observed_exception, ObservedUserStopIteration + from .variables.object_protocol import generic_getiter, pyiter_next + + if isinstance(iterable, _unpack_fast_types()): + yield from iterable.unpack_var_sequence(tx) + return + + iterator = generic_getiter(tx, iterable) # type: ignore[bad-argument-type] + while True: + try: + yield pyiter_next(tx, iterator) # type: ignore[bad-argument-type] + except ObservedUserStopIteration: + handle_observed_exception(tx) + break + + +@overload +def is_lru_cache_wrapped_function( + value: Callable[..., T], +) -> TypeGuard[functools._lru_cache_wrapper[T]]: ... + + +@overload +def is_lru_cache_wrapped_function( + value: Any, +) -> TypeGuard[functools._lru_cache_wrapper[Any]]: ... + + +def is_lru_cache_wrapped_function( + value: Any, +) -> bool: + return isinstance(value, functools._lru_cache_wrapper) and is_function( + inspect.getattr_static(value, "__wrapped__") + ) + + +_lru_cache_wrappers_allowed_to_trace_without_warning: weakref.WeakSet[ + functools._lru_cache_wrapper[Any] +] = weakref.WeakSet() + + +def allow_lru_cache_wrapper_trace_without_warning( + value: functools._lru_cache_wrapper[Any], +) -> None: + _lru_cache_wrappers_allowed_to_trace_without_warning.add(value) + + +def is_lru_cache_wrapper_trace_without_warning_allowed(value: object) -> bool: + return value in _lru_cache_wrappers_allowed_to_trace_without_warning + + +_FuncTypes: TypeAlias = ( + types.FunctionType + | types.BuiltinFunctionType + | types.MethodDescriptorType + | types.WrapperDescriptorType +) + + +def is_function_or_wrapper( + value: Any, +) -> TypeIs[_FuncTypes | torch._ops.OpOverloadPacket | torch._ops.OpOverload]: + return is_function(value) or isinstance( + value, (torch._ops.OpOverloadPacket, torch._ops.OpOverload) + ) + + +def is_function( + value: Any, +) -> TypeIs[_FuncTypes]: + return isinstance( + value, + ( + types.FunctionType, + types.BuiltinFunctionType, + types.MethodDescriptorType, + types.WrapperDescriptorType, + ), + ) + + +cmp_name_to_op_mapping = { + "__eq__": operator.eq, + "__ne__": operator.ne, + "__lt__": operator.lt, + "__le__": operator.le, + "__gt__": operator.gt, + "__ge__": operator.ge, +} + + +cmp_name_to_op_str_mapping = { + "__eq__": "==", + "__ne__": "!=", + "__lt__": "<", + "__le__": "<=", + "__gt__": ">", + "__ge__": ">=", +} + + +def is_wrapper_or_member_descriptor( + value: Any, +) -> TypeIs[ + types.GetSetDescriptorType + | types.MethodDescriptorType + | types.WrapperDescriptorType + | types.MemberDescriptorType + | types.MethodWrapperType +]: + return isinstance( + value, + ( + # set up by PyGetSetDef + types.GetSetDescriptorType, + # set by PyMethodDef, e.g. list.append + types.MethodDescriptorType, + # slots - list.__add__ + types.WrapperDescriptorType, + # set up by PyMemberDef + types.MemberDescriptorType, + # wrapper over C functions + types.MethodWrapperType, + ), + ) + + +def tracked_repr(tx: InstructionTranslatorBase, vt: VariableTracker) -> str: + from .variables.object_protocol import generic_repr + + return generic_repr(tx, vt).as_python_constant() + + +def _item_debug_repr(vt: VariableTracker) -> str: + if vt.is_python_constant(): + return repr(vt.as_python_constant()) + return vt.debug_repr() + + +def unwrap_if_wrapper(fn: Any) -> Any: + return unwrap_with_attr_name_if_wrapper(fn)[0] + + +def unwrap_with_attr_name_if_wrapper(fn: Any) -> tuple[Any, str | None]: + # TODO(anijain2305) - Investigate if we can get rid of this function + # unpack @torch._dynamo.optimize()(fn) wrapped function + if is_function(fn) and inspect.getattr_static(fn, "_torchdynamo_inline", False): + fn = inspect.getattr_static(fn, "_torchdynamo_inline", fn) + attr_name = "_torchdynamo_inline" + else: + attr_name = None + return fn, attr_name + + +def is_numpy_ndarray(value: Any) -> TypeGuard[np.ndarray]: # type: ignore[type-arg] + if not np: + return False + + return istype(value, np.ndarray) + + +def istensor(obj: Any) -> bool: + """Check of obj is a tensor""" + tensor_list: tuple[type, ...] = ( + torch.Tensor, + torch.nn.Parameter, + *config.traceable_tensor_subclasses, + ) + tensor_list = tensor_list + (torch._subclasses.FakeTensor,) + return istype(obj, tensor_list) + + +def is_lazy_module(mod: Any) -> bool: + return isinstance(mod, LazyModuleMixin) + + +@functools.lru_cache(4096) +def print_once(*args: Any) -> None: + print(*args) + + +def make_cell(val: Any = None) -> types.CellType: + """Some black magic to create a cell object that usually only exists in a closure""" + x = val + + def f() -> Any: + return x + + if f.__closure__ is None: + raise AssertionError("Expected f to have a closure, but f.__closure__ is None") + if len(f.__closure__) != 1: + raise AssertionError( + f"Expected f.__closure__ to have exactly 1 element, got {len(f.__closure__)}" + ) + return f.__closure__[0] + + +def proxy_args_kwargs(args: Any, kwargs: Any) -> tuple[tuple[Any, ...], dict[str, Any]]: + try: + proxy_args = tuple(arg.as_proxy() for arg in args) + proxy_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()} + return proxy_args, proxy_kwargs + except NotImplementedError as e: + from .exc import unimplemented + from .variables.base import typestr + + unimplemented( + gb_type="Failed to convert args/kwargs to proxy", + context=f"call_function args: {typestr(*args)} {typestr(*list(kwargs.values()))}", + explanation="Missing `as_proxy()` implementation for some arg/kwarg.", + hints=[], + from_exc=e, + ) + + +def to_int_ms(v: float | None) -> int | None: + return None if v is None else int(v * 1000) + + +# float64 timestamp has a quarter microsecond precision in 2024, so while +# this is suboptimal we shouldn't meaningfully lose precision +def to_int_us(v: float | None) -> int | None: + return None if v is None else int(v * 1_000_000) + + +# Version field added to every log. Increment to make it easier to distinguish new +# vs. old entries when you make a substantive change to how the logs are populated. +LOG_FORMAT_VERSION = 3 + + +@dataclasses.dataclass +class CompilationMetrics: + compile_id: str | None = None + frame_key: str | None = None + co_name: str | None = None + co_filename: str | None = None + co_firstlineno: int | None = None + cache_size: int | None = None + accumulated_cache_size: int | None = None + guard_count: int | None = None + shape_env_guard_count: int | None = None + graph_op_count: int | None = None + graph_node_count: int | None = None + graph_input_count: int | None = None + start_time: float | None = None + entire_frame_compile_time_s: float | None = None + backend_compile_time_s: float | None = None + inductor_compile_time_s: float | None = None + code_gen_time_s: float | None = None + fail_type: str | None = None + fail_reason: str | None = None + fail_user_frame_filename: str | None = None + fail_user_frame_lineno: int | None = None + non_compliant_ops: set[str] | None = None + compliant_custom_ops: set[str] | None = None + restart_reasons: set[str] | None = None + dynamo_time_before_restart_s: float | None = None + stack_trace: list[str] | None = None + exception_stack_trace: list[str] | None = None + graph_node_shapes: str | None = None + # Sometimes, we will finish analyzing a frame but conclude we don't want + # to install any guarded code. True means we actually decided to install + # a compiled frame + has_guarded_code: bool | None = None + remote_cache_time_saved_s: float | None = None + structured_logging_overhead_s: float | None = None + config_suppress_errors: bool | None = None + config_inline_inbuilt_nn_modules: bool | None = None + specialize_float: bool | None = None + dynamo_config: str | None = None + compiler_config: str | None = None + is_forward: bool | None = None + num_triton_bundles: int | None = None + remote_fx_graph_cache_get_time_ms: int | None = None + remote_fx_graph_cache_put_time_ms: int | None = None + start_time_us: int | None = None + duration_us: int | None = None + dynamo_cumulative_compile_time_us: int | None = None + aot_autograd_cumulative_compile_time_us: int | None = None + inductor_cumulative_compile_time_us: int | None = None + inductor_code_gen_cumulative_compile_time_us: int | None = None + triton_compile_time_us: int | None = None + runtime_cudagraphify_time_us: int | None = None + runtime_triton_autotune_time_us: int | None = None + dynamo_compile_time_before_restart_us: int | None = None + distributed_ephemeral_timeout_us: int | None = None + structured_logging_overhead_us: int | None = None + remote_fx_graph_cache_get_time_us: int | None = None + remote_fx_graph_cache_put_time_us: int | None = None + backward_cumulative_compile_time_us: int | None = None + end_time_us: int | None = None + pre_grad_pass_time_us: int | None = None + post_grad_pass_time_us: int | None = None + joint_graph_pass_time_us: int | None = None + log_format_version: int = LOG_FORMAT_VERSION + inductor_config: str | None = None + remote_cache_version: int | None = None + inductor_fx_remote_cache_hit_count: int | None = 0 + inductor_fx_remote_cache_miss_count: int | None = 0 + inductor_fx_remote_cache_backend_type: str | None = None + inductor_fx_remote_cache_hit_keys: str | None = None + inductor_fx_remote_cache_miss_keys: str | None = None + inductor_fx_local_cache_hit_count: int | None = 0 + inductor_fx_local_cache_miss_count: int | None = 0 + aotautograd_remote_cache_hit_count: int | None = 0 + aotautograd_remote_cache_miss_count: int | None = 0 + aotautograd_local_cache_hit_count: int | None = 0 + aotautograd_local_cache_miss_count: int | None = 0 + cuda_version: str | None = None + triton_version: str | None = None + feature_usage: dict[str, bool] | None = None + compile_time_autotune_time_us: int | None = None + is_runtime: bool | None = False + gc_time_us: int | None = None + tensorify_float_attempt: bool | None = None + tensorify_float_success: bool | None = None + tensorify_float_failure: set[str] | None = None + guard_latency_us: float | None = None + recompile_reason: str | None = None + num_graph_breaks: int | None = None + triton_kernel_compile_times_us: str | None = None + ir_count: int | None = None + cudagraph_skip_reason: str | None = None + python_version: str | None = None + pgo_put_remote_code_state_time_us: int | None = None + pgo_get_remote_code_state_time_us: int | None = None + # The number of elements within parameters. This is classically what people + # think of when they think of parameters in a ML model. + param_numel: int | None = None + # The number of elements counted by bytes - i.e. a float32 is 4 bytes + # per element. + param_bytes: int | None = None + # The number of parameters counted by fields. This is mostly a proxy for + # the number of distinct type of params. + param_count: int | None = None + recompile_user_contexts: set[str] | None = None + inline_inbuilt_nn_modules_candidate: bool | None = False + pytorch_version: str | None = None + inductor_provenance: set[str] | None = None + functorch_config: str | None = None + + @classmethod + def create(cls, metrics: dict[str, Any]) -> CompilationMetrics: + """ + Factory method to create a CompilationMetrics from a dict of fields. + Includes the logic to add legacy fields and any pre-processing, e.g., + we transform some fields to comma-separated strings for scuba logging. + """ + + def us_to_s(metric: int | None) -> float | None: + return metric / 1e6 if metric is not None else None + + def us_to_ms(metric: int | None) -> int | None: + return metric // 1000 if metric is not None else None + + def collection_to_str(metric: Any | None) -> str | None: + def safe_str(item: Any) -> str: + try: + return str(item) + except Exception: + return "" + + if metric is None: + return None + + if not isinstance(metric, (set, list)): + return "" + + return ",".join(safe_str(item) for item in sorted(metric)) + + def collection_to_json_str(metric: Any | None) -> str | None: + if metric is None: + return None + try: + return json.dumps(list(metric)) + except Exception: + return "" + + # TODO: The following are legacy fields, populated from the fields that replace + # them. Remove these when we decide we can really deprecate them. + legacy_metrics = { + "start_time": us_to_s(metrics.get("start_time_us")), + "entire_frame_compile_time_s": us_to_s( + metrics.get("dynamo_cumulative_compile_time_us") + ), + "backend_compile_time_s": us_to_s( + metrics.get("aot_autograd_cumulative_compile_time_us") + ), + "inductor_compile_time_s": us_to_s( + metrics.get("inductor_cumulative_compile_time_us") + ), + "code_gen_time_s": us_to_s( + metrics.get("inductor_code_gen_cumulative_compile_time_us") + ), + "remote_cache_time_saved_s": us_to_s( + metrics.get("distributed_ephemeral_timeout_us") + ), + "remote_fx_graph_cache_get_time_ms": us_to_ms( + metrics.get("remote_fx_graph_cache_get_time_us") + ), + "remote_fx_graph_cache_put_time_ms": us_to_ms( + metrics.get("remote_fx_graph_cache_put_time_us") + ), + "structured_logging_overhead_s": us_to_s( + metrics.get("structured_logging_overhead_us") + ), + } + + all_metrics = {**legacy_metrics, **metrics} + + # Processing before logging: + all_metrics["inductor_fx_remote_cache_hit_keys"] = collection_to_str( + all_metrics.get("inductor_fx_remote_cache_hit_keys") + ) + all_metrics["inductor_fx_remote_cache_miss_keys"] = collection_to_str( + all_metrics.get("inductor_fx_remote_cache_miss_keys") + ) + all_metrics["triton_kernel_compile_times_us"] = collection_to_json_str( + all_metrics.get("triton_kernel_compile_times_us") + ) + compile_id = all_metrics.get("compile_id") + all_metrics["compile_id"] = str(compile_id) if compile_id else None + + # pyrefly: ignore [bad-argument-type] + return cls(**all_metrics) + + +DEFAULT_COMPILATION_METRICS_LIMIT = 64 + + +_compilation_metrics: collections.deque[CompilationMetrics] = collections.deque( + maxlen=DEFAULT_COMPILATION_METRICS_LIMIT +) + + +def add_compilation_metrics_to_chromium(c: CompilationMetrics) -> None: + """ + These are the common fields in CompilationMetrics that existed before + metrics_context, and aren't set by MetricsContext.set(). We add the subset + of them that make sense in `dynamo`/toplevel events in PT2 Compile Events + directly. + + If you're tempted to add to this list, consider using CompileEventLogger.compilation_metric() + instead, which will automatically also add it to tlparse and PT2 Compile Events. + TODO: Get rid of this function and replace it with CompileEventLogger directly instead. + """ + event_logger = get_chromium_event_logger() + event_name = event_logger.get_outermost_event() + if not event_name: + return + event_logger.add_event_data( + event_name=event_name, + frame_key=c.frame_key, + co_name=c.co_name, + co_filename=c.co_filename, + co_firstlineno=c.co_firstlineno, + cache_size=c.cache_size, + accumulated_cache_size=c.accumulated_cache_size, + guard_count=c.guard_count, + shape_env_guard_count=c.shape_env_guard_count, + graph_op_count=c.graph_op_count, + graph_node_count=c.graph_node_count, + graph_input_count=c.graph_input_count, + fail_type=c.fail_type, + fail_reason=c.fail_reason, + fail_user_frame_filename=c.fail_user_frame_filename, + fail_user_frame_lineno=c.fail_user_frame_lineno, + # Sets aren't JSON serializable + non_compliant_ops=( + list(c.non_compliant_ops) if c.non_compliant_ops is not None else None + ), + compliant_custom_ops=( + list(c.compliant_custom_ops) if c.compliant_custom_ops is not None else None + ), + restart_reasons=( + list(c.restart_reasons) if c.restart_reasons is not None else None + ), + dynamo_time_before_restart_s=c.dynamo_time_before_restart_s, + has_guarded_code=c.has_guarded_code, + dynamo_config=c.dynamo_config, + ) + + +def _get_dynamo_config_for_logging() -> str | None: + def clean_for_json(d: dict[str, Any]) -> dict[str, Any]: + blocklist = { + "TYPE_CHECKING", + "log_file_name", + "verbose", + "repro_after", + "repro_level", + "repro_forward_only", + "repro_tolerance", + "repro_ignore_non_fp", + "same_two_models_use_fp64", + "base_dir", + "debug_dir_root", + "_save_config_ignore", + "log_compilation_metrics", + "inject_BUILD_SET_unimplemented_TESTING_ONLY", + "_autograd_backward_strict_mode_banned_ops", + "reorderable_logging_functions", + "ignore_logger_methods", + "ignore_logging_functions", + "traceable_tensor_subclasses", + "nontraceable_tensor_subclasses", + "_custom_ops_profile", + } + + return { + key: ( + sorted(value) + if isinstance(value, set) + else value.to_jsonable() + if hasattr(value, "to_jsonable") + else value + ) + for key, value in d.items() + if key not in blocklist + } + + config_dict = clean_for_json(config.get_config_copy()) + return json.dumps(config_dict, sort_keys=True) + + +def _compiler_config_for_logging() -> str | None: + def clean_for_json(d: dict[str, Any]) -> dict[str, Any]: + blocklist = { + "TYPE_CHECKING", + } + + return { + key: sorted(value) if isinstance(value, set) else value + for key, value in d.items() + if key not in blocklist + } + + if not torch.compiler.config: + return None + + try: + compiler_config_copy = torch.compiler.config.get_config_copy() # type: ignore[attr-defined] + except (TypeError, AttributeError): + return "Compiler Config cannot be pickled" + + config_dict = clean_for_json(compiler_config_copy) + return json.dumps(config_dict, sort_keys=True) + + +def _scrubbed_inductor_config_for_logging() -> str | None: + """ + Method to parse and scrub uninteresting configs from inductor config + """ + + # TypeSafeSerializer for json.dumps() + # Skips complex types as values in config dict + class TypeSafeSerializer(json.JSONEncoder): + def default(self, o: Any) -> Any: + try: + return super().default(o) + except Exception: + return "Value is not JSON serializable" + + keys_to_scrub: set[Any] = set() + inductor_conf_str = None + inductor_config_copy = None + + if torch._inductor.config: + try: + inductor_config_copy = torch._inductor.config.get_config_copy() + except (TypeError, AttributeError, RuntimeError, AssertionError): + inductor_conf_str = "Inductor Config cannot be pickled" + + if inductor_config_copy is not None: + try: + for key, val in inductor_config_copy.items(): + if not isinstance(key, str): + keys_to_scrub.add(key) + # Convert set() to list for json.dumps() + if isinstance(val, set): + inductor_config_copy[key] = list(val) + # Evict unwanted keys + for key in keys_to_scrub: + del inductor_config_copy[key] + # Stringify Inductor config + inductor_conf_str = json.dumps( + inductor_config_copy, + cls=TypeSafeSerializer, + skipkeys=True, + sort_keys=True, + ) + except Exception: + # Don't crash because of runtime logging errors + inductor_conf_str = "Inductor Config is not JSON serializable" + return inductor_conf_str + + +def _functorch_config_for_logging() -> str | None: + """Serialize functorch config (AOT autograd settings) for Scuba logging.""" + if not justknobs_check("pytorch/dynamo:log_functorch_config"): + return None + + try: + functorch_config_copy = torch._functorch.config.get_config_copy() + except (TypeError, AttributeError, RuntimeError, AssertionError): + return None + + try: + blocklist = { + "TYPE_CHECKING", + "_save_config_ignore", + } + clean = { + k: (list(v) if isinstance(v, set) else v) + for k, v in functorch_config_copy.items() + if k not in blocklist and isinstance(k, str) + } + return json.dumps(clean, sort_keys=True, default=str) + except Exception: + return "Functorch Config is not JSON serializable" + + +def record_compilation_metrics( + start_time_ns: int, + end_time_ns: int, + metrics: dict[str, Any], + exc_type: type[BaseException] | None, + exc_value: BaseException | None, +) -> None: + if torch._inductor.utils.should_use_remote_fx_graph_cache(): + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + + remote_cache_version = REMOTE_CACHE_VERSION + inductor_fx_remote_cache_backend_type = "_ManifoldCache" + except ModuleNotFoundError: + remote_cache_version = None + inductor_fx_remote_cache_backend_type = None + else: + inductor_fx_remote_cache_backend_type = None + remote_cache_version = None + + # Populate the compile_id from the metrics context if it's set. Otherwise, + # look for it in the current compile context. + compile_id = metrics.get("compile_id") + if not compile_id: + compile_id = torch._guards.CompileContext.current_compile_id() + + common_metrics = { + "compile_id": compile_id, + "start_time_us": start_time_ns // 1000, + "end_time_us": end_time_ns // 1000, + "fail_type": exc_type.__qualname__ if exc_type else None, + "fail_reason": str(exc_value) if exc_value else None, + "structured_logging_overhead_us": to_int_us( + torch._logging.get_structured_logging_overhead() + ), + "dynamo_config": _get_dynamo_config_for_logging(), + "config_suppress_errors": config.suppress_errors, + "config_inline_inbuilt_nn_modules": True, + "inductor_config": _scrubbed_inductor_config_for_logging(), + "compiler_config": _compiler_config_for_logging(), + "cuda_version": torch.version.cuda, + "triton_version": triton.__version__ if has_triton() else "", + "remote_cache_version": remote_cache_version, + "inductor_fx_remote_cache_backend_type": inductor_fx_remote_cache_backend_type, + "python_version": sys.version, + "pytorch_version": torch.__version__, + "functorch_config": _functorch_config_for_logging(), + } + + compilation_metrics = CompilationMetrics.create({**common_metrics, **metrics}) + _compilation_metrics.append(compilation_metrics) + + name = "compilation_metrics" + if compilation_metrics.is_forward is False: + name = "bwd_" + name + if compilation_metrics.is_runtime is True: + name = name + "_runtime" + + torch._logging.trace_structured( + name, + lambda: { + k: list(v) if isinstance(v, set) else v + for k, v in dataclasses.asdict(compilation_metrics).items() + }, + # NB: Because compilation metrics *includes* the logging overhead time, + # we can't both *measure* the logging overhead of compilation metrics + # without making it inconsistent with compilation metrics itself, so + # we ignore the (hopefully small) time spent logging compilation metrics + record_logging_overhead=False, + # These may be runtime logs, e.g., runtime autotunning, so we provide + # the CompileId from the compilation metrics in case it's not available + # in the current trace. + compile_id=compile_id, + ) + + # If there's a chromium event in flight, add the CompilationMetrics to it. + add_compilation_metrics_to_chromium(compilation_metrics) + + # Finally log the compilation metrics. + if config.log_compilation_metrics: + log_compilation_event(compilation_metrics) + + +def set_compilation_metrics_limit(new_size: int) -> None: + global _compilation_metrics + while len(_compilation_metrics) > new_size: + _compilation_metrics.popleft() + new_deque = collections.deque(_compilation_metrics, maxlen=new_size) + _compilation_metrics = new_deque + + +def clear_compilation_metrics() -> None: + global _compilation_metrics + _compilation_metrics.clear() + + +def get_compilation_metrics() -> list[CompilationMetrics]: + return list(_compilation_metrics) + + +class ChromiumEventLogger: + """Logs chromium events to structured logs. tlparse will concatenate these into a perfetto UI link. + + Also emits RecordFunction calls to torch.profiler when enabled. + + See https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.yr4qxyxotyw for + a specification of the Chromium Event JSON format. + """ + + def get_stack(self) -> list[str]: + """ + The main event stack, with every chromium event. + Logged to tlparse. + """ + if hasattr(self.tls, "stack"): + return self.tls.stack + else: + self.tls.stack = [] + return self.tls.stack + + def get_outermost_event(self) -> str | None: + """ + Get the outermost event name (i.e. the longest running event) + or None if the stack is empty. + """ + stack = self.get_stack() + return stack[0] if stack else None + + def get_pt2_compile_substack(self) -> list[str]: + """ + A smaller subset of the main stack that gets used to log + PT2 Compile Events internally. + """ + if hasattr(self.tls, "pt2_compile_substack"): + return self.tls.pt2_compile_substack + else: + self.tls.pt2_compile_substack = [] + return self.tls.pt2_compile_substack + + def get_event_data(self) -> dict[str, Any]: + if not hasattr(self.tls, "event_data"): + self.tls.event_data = {} + return self.tls.event_data + + def get_record_functions(self) -> dict[str, AbstractContextManager[None]]: + if not hasattr(self.tls, "record_functions"): + self.tls.record_functions = {} + return self.tls.record_functions + + def __init__(self) -> None: + self.tls = threading.local() + + from . import config + + # Generate a unique id for this logger, which we can use in scuba to filter down + # to a single python run. + if config.pt2_compile_id_prefix: + self.id_ = f"{config.pt2_compile_id_prefix}-{uuid.uuid4()}" + else: + self.id_ = str(uuid.uuid4()) + + # TODO: log to init/id tlparse after I add support for it + log.info("ChromiumEventLogger initialized with id %s", self.id_) + + def try_add_event_data(self, event_name: str, **kwargs: Any) -> None: + """ + Same as add_event_data, but will silently not log if the event isn't in the stack. + """ + if event_name not in self.get_stack(): + return + self.add_event_data(event_name, **kwargs) + + def add_event_data( + self, + event_name: str, + **kwargs: Any, + ) -> None: + """ + Adds additional metadata info to an in-progress event + This metadata is recorded in the END event + """ + if event_name not in self.get_stack(): + raise RuntimeError( + f"Event {repr(event_name)} not in {self.get_stack()}. " + "Cannot add metadata to events that aren't in progress. " + "Please make sure the event has started and hasn't ended." + ) + event_data = self.get_event_data() + if event_name not in event_data: + event_data[event_name] = {} + event_data[event_name].update(kwargs) + + def increment(self, event_name: str, key: str, value: int) -> None: + """ + Increment an integer event data field by the given amount + """ + if event_name not in self.get_stack(): + raise RuntimeError( + f"Event {repr(event_name)} not in {self.get_stack()}. " + "Cannot add metadata to events that aren't in progress. " + "Please make sure the event has started and hasn't ended." + ) + + event_data = self.get_event_data() + if event_name not in event_data: + event_data[event_name] = {} + if key not in event_data[event_name]: + event_data[event_name][key] = 0 + event_data[event_name][key] += value + + def add_to_set( + self, + event_name: str, + key: str, + value: Any, + ) -> None: + """ + Add a value to a set within a event_name's metadata if it exists + """ + if event_name not in self.get_stack(): + raise RuntimeError( + f"Event {repr(event_name)} not in {self.get_stack()}. " + "Cannot add metadata to events that aren't in progress. " + "Please make sure the event has started and hasn't ended." + ) + event_data = self.get_event_data() + if event_name not in event_data: + event_data[event_name] = {} + if key not in event_data[event_name]: + event_data[event_name][key] = set() + event_data[event_name][key].add(value) + + def log_event_start( + self, + event_name: str, + time_ns: int, + metadata: dict[str, Any], + log_pt2_compile_event: bool = False, + compile_id: CompileId | None = None, + ) -> None: + """ + Logs the start of a single event. + :param str event_name Name of event to appear in trace + :param time_ns Timestamp in nanoseconds + :param metadata: Any extra metadata associated with this event + :param log_pt2_compile_event: If True, log to pt2_compile_events + :param compile_id: Explicit compile_id (rather than using the current context) + """ + compile_id = compile_id or torch._guards.CompileContext.current_compile_id() + metadata["compile_id"] = str(compile_id) + self._log_timed_event( + event_name, + time_ns, + "B", + metadata, + ) + self.get_stack().append(event_name) + # Add metadata from start event + self.add_event_data(event_name, **metadata) + if log_pt2_compile_event: + self.get_pt2_compile_substack().append(event_name) + + # Emit profiler event so compilation events show up in stock PyTorch profiler + if torch.autograd.profiler._is_profiler_enabled: + rf = torch._C._profiler._RecordFunctionFast(event_name) + rf.__enter__() + self.get_record_functions()[event_name] = rf + + # Add metadata to the profiler event if present + if metadata: + CompileEventLogger.add_record_function_data(event_name, **metadata) + + def _reset_to_state( + self, + stack_depth: int, + pt2_compile_substack_depth: int, + event_data_keys: set[str], + record_function_keys: set[str], + ) -> None: + stack = self.get_stack() + del stack[stack_depth:] + substack = self.get_pt2_compile_substack() + del substack[pt2_compile_substack_depth:] + event_data = self.get_event_data() + for event_name in list(event_data): + if event_name not in event_data_keys: + del event_data[event_name] + # Clean up any lingering record functions (shouldn't happen in normal operation) + record_functions = self.get_record_functions() + for event_name, rf in list(record_functions.items()): + if event_name not in record_function_keys: + rf.__exit__(None, None, None) + del record_functions[event_name] + + def reset(self) -> None: + # We do this on every compile in case a compile crashes or restarts and + # we haven't cleared the stack. + self._reset_to_state(0, 0, set(), set()) + + def log_event_end( + self, + event_name: str, + time_ns: int, + metadata: dict[str, Any], + start_time_ns: int, + log_pt2_compile_event: bool, + compile_id: CompileId | None = None, + ) -> None: + """ + Logs the end of a single event. This function should only be + called after log_event_start with the same event_name. + :param event_name: Name of event to appear in trace + :param time_ns: Timestamp in nanoseconds + :param metadata: Any extra metadata associated with this event + :param start_time_ns: The start time timestamp in nanoseconds + :param log_pt_compile_event: If True, log to pt2_compile_events + :param compile_id: Explicit compile_id (rather than using the current context) + """ + compile_id = compile_id or torch._guards.CompileContext.current_compile_id() + metadata["compile_id"] = str(compile_id) + + # Grab metadata collected during event span + all_event_data = self.get_event_data() + if event_name in all_event_data: + event_metadata = all_event_data[event_name] + del all_event_data[event_name] + else: + # pyrefly: ignore [implicit-any] + event_metadata = {} + # Add the passed in metadata + event_metadata.update(metadata) + + event = self._log_timed_event( + event_name, + time_ns, + "E", + event_metadata, + ) + + def pop_stack(stack: list[str]) -> None: + while event_name != stack[-1]: + # If the event isn't the most recent one to end, pop + # off the stack until it is. + # Since event_name in self.stack, this pop is always safe + log.warning( + "ChromiumEventLogger: Detected overlapping events, fixing stack" + ) + stack.pop() + + event_stack = self.get_stack() + # These stack health checks currently never happen, + # but they're written this way to future proof any weird event + # overlaps in the future. + if event_name not in event_stack: + # Something went wrong, we never called start on this event, + # or it was skipped due to overlapping events below + log.warning("ChromiumEventLogger: Start event not in stack, ignoring") + return + + pop_stack(event_stack) + + if log_pt2_compile_event: + pt2_compile_substack = self.get_pt2_compile_substack() + pop_stack(pt2_compile_substack) + log_chromium_event_internal( + event, pt2_compile_substack, self.id_, start_time_ns + ) + # Pop actual event off of stack + pt2_compile_substack.pop() + + # Finally pop the actual event off the stack + event_stack.pop() + + # End profiler event so compilation events show up in stock PyTorch profiler + record_functions = self.get_record_functions() + if event_name in record_functions: + rf = record_functions.pop(event_name) + rf.__exit__(None, None, None) + + def _log_timed_event( + self, + event_name: str, + time_ns: int, + phase: str, + metadata: dict[str, Any] | None = None, + ) -> dict[str, Any]: + """ + Logs a timed event in chromium format. See log_event_start, log_event_end, etc. + """ + event = { + "name": event_name, + "ts": time_ns / 1000, # Chromium events are in micro seconds + "args": metadata, + "ph": phase, + # These categories are needed in all chromium traces + "cat": "dynamo_timed", + "tid": 0, + "pid": 0, # pid should be specified on all logs, we don't personally care about the actual process id + } + torch._logging.trace_structured( + "chromium_event", + payload_fn=lambda: event, + suppress_context=False, + expect_trace_id=False, # Not every chromium event will have a trace_id + ) + record_chromium_event_internal(event) + return event + + def log_instant_event( + self, + event_name: str, + time_ns: int, + metadata: dict[str, Any] | None = None, + # By default, an instant event isn't logged internally, only to structured logging. + log_pt2_compile_event: bool = False, + ) -> None: + """ + Log an instant event with no associated duration. + :param str event_name: Name of event to appear in trace + :param int time_ns Timestamp in nanoseconds + :param Optional[Dict[str, Any]] metadata: Any extra metadata associated with this event + :param str cname optional color for the arrow in the trace + """ + if metadata is None: + metadata = {} + compile_id = str(torch._guards.CompileContext.current_compile_id()) + metadata["compile_id"] = compile_id + event = { + "name": event_name, + "ts": time_ns / 1000, + "args": metadata, + "ph": "i", + # These categories are needed in all chromium traces + "cat": "dynamo_timed", + "tid": 0, + "pid": 0, + "s": "p", # We use "process" level instant events so they all appear on the same row in the trace. + } + torch._logging.trace_structured( + "chromium_event", + payload_fn=lambda: event, + suppress_context=False, + expect_trace_id=True, + ) + if log_pt2_compile_event: + # Log an instant event with the same start and end time + log_chromium_event_internal( + event, self.get_pt2_compile_substack(), self.id_, time_ns + ) + + +CHROMIUM_EVENT_LOG: ChromiumEventLogger | None = None + + +def get_chromium_event_logger() -> ChromiumEventLogger: + global CHROMIUM_EVENT_LOG + if CHROMIUM_EVENT_LOG is None: + CHROMIUM_EVENT_LOG = ChromiumEventLogger() + return CHROMIUM_EVENT_LOG + + +def chromium_event_log_active() -> bool: + global CHROMIUM_EVENT_LOG + return CHROMIUM_EVENT_LOG is not None + + +@contextmanager +def chromium_event_timed( + event_name: str, + reset_event_log_on_exit: bool = False, + log_pt2_compile_event: bool = False, +) -> Generator[Any, None, None]: + """ + Context manager that creates a chromium start and end event. Chromium event + logging is integrated with dynamo_timed, so you probably want to use that + instead. Use this context manager only if you want to avoid dynamo_timed. + """ + chromium_event_log = get_chromium_event_logger() + reset_state: tuple[int, int, set[str], set[str]] | None = None + if reset_event_log_on_exit: + reset_state = ( + len(chromium_event_log.get_stack()), + len(chromium_event_log.get_pt2_compile_substack()), + set(chromium_event_log.get_event_data()), + set(chromium_event_log.get_record_functions()), + ) + chromium_start_time = time.time_ns() + chromium_event_log.log_event_start( + event_name, + chromium_start_time, + {}, + log_pt2_compile_event, + ) + try: + yield + finally: + chromium_event_log.log_event_end( + event_name, + time.time_ns(), + {}, + chromium_start_time, + log_pt2_compile_event, + ) + if reset_state is not None: + chromium_event_log._reset_to_state(*reset_state) + + +# (id(scope), name) -> the token of whichever hook currently owns that +# binding. A value comparison isn't enough here: CompilePackage.install() can +# re-materialize a name like __builtins_dict__ with the *same* object a +# pre-reset hook already installed, so an identity-of-value check would still +# let the stale hook delete it. A token makes ownership explicit instead. +_cleanup_owners: dict[tuple[int, str], object] = {} + + +@dataclasses.dataclass +class CleanupHook: + """Remove a global variable when hook is called""" + + scope: dict[str, Any] + name: str + token: object = dataclasses.field(compare=False, repr=False) + + def __call__(self, *args: Any) -> None: + # Make sure we're not shutting down + if CleanupManager is not None: + CleanupManager.count -= 1 + # Hooks fire when the owning code object is collected, which can happen + # after something else has taken over this name -- CompilePackage.install() + # reinstalls precompiled state under names a pre-reset compile still + # owns. Only clean up while nothing has claimed the name out from under us. + key = (id(self.scope), self.name) + if _cleanup_owners.pop(key, None) is not self.token: + return + # During interpreter shutdown the scope's module __dict__ may already + # have been cleared, so the name can be gone. Use pop to avoid a + # KeyError surfacing as an "Exception ignored in weakref callback". + self.scope.pop(self.name, None) + + @staticmethod + def create(scope: dict[str, Any], name: str, val: Any) -> CleanupHook: + if name in scope: + raise AssertionError(f"Name {name!r} already exists in scope") + CleanupManager.count += 1 + scope[name] = val + token = object() + _cleanup_owners[(id(scope), name)] = token + return CleanupHook(scope, name, token) + + @staticmethod + def disown(scope: dict[str, Any], name: str) -> None: + """Invalidate whichever hook currently owns (scope, name), so that if + its code object outlives this call, firing later is a no-op instead of + deleting a binding something else has since taken over.""" + _cleanup_owners.pop((id(scope), name), None) + + +class CleanupManager(ExactWeakKeyDictionary): + count = 0 + instance: ClassVar[CleanupManager] + + def _remove_id(self, idx: int) -> None: + for hook in self.values[idx]: + hook() + super()._remove_id(idx) + + +CleanupManager.instance = CleanupManager() + + +def clone_tensor(x: torch.Tensor) -> torch.Tensor: + """Clone the tensor and its gradient""" + y = x.clone().requires_grad_(x.requires_grad) + if x.is_leaf and x.grad is not None: + y.grad = x.grad.clone() + return y + + +def _copy_dynamo_attr(src: torch.Tensor, dst: torch.Tensor, attr: str) -> None: + """Copy a single dynamo attribute from src to dst, or remove it from dst + if src doesn't have it. Uses .copy() for container types (set, dict) to + avoid shared references between src and dst, and assigns directly for + primitive types like bool (e.g., _has_dynamo_dim_marking).""" + if hasattr(src, attr): + val = getattr(src, attr) + setattr(dst, attr, val.copy() if hasattr(val, "copy") else val) + elif hasattr(dst, attr): + delattr(dst, attr) + + +def copy_dynamo_tensor_attributes(src: torch.Tensor, dst: torch.Tensor) -> None: + """ + Copy dynamo-specific tensor attributes from src to dst. + These attributes are used for dynamic shape marking and must be preserved + when cloning or casting tensors. If src doesn't have an attribute but dst does, + the attribute is removed from dst. + """ + _copy_dynamo_attr(src, dst, "_dynamo_dynamic_indices") + _copy_dynamo_attr(src, dst, "_dynamo_unbacked_indices") + _copy_dynamo_attr(src, dst, "_dynamo_hint_overrides") + _copy_dynamo_attr(src, dst, "_dynamo_shape_ids") + _copy_dynamo_attr(src, dst, "_dynamo_strict_unbacked_indices") + _copy_dynamo_attr(src, dst, "_dynamo_weak_dynamic_indices") + _copy_dynamo_attr(src, dst, "_dynamo_propagated_dynamic_indices") + _copy_dynamo_attr(src, dst, "_has_dynamo_dim_marking") + + +def clone_input(x: torch.Tensor, *, dtype: torch.dtype | None = None) -> torch.Tensor: + """copy while preserving strides""" + # TODO: this is questionable + if is_fake(x): + # this func fails on fake tensors in __torch_dispatch__ + return x + + def is_pinned_cpu_tensor(x: torch.Tensor) -> bool: + return ( + x.device.type == "cpu" + and not is_traceable_wrapper_subclass(x) + and x.is_pinned() + ) + + def torch_clone(x: torch.Tensor) -> torch.Tensor: + y = torch.clone(x) + if is_pinned_cpu_tensor(x): + y = y.pin_memory() + if x.is_leaf: + y.requires_grad_(x.requires_grad) + if x.is_leaf and x.grad is not None: + y.grad = clone_input(x.grad, dtype=dtype) + copy_dynamo_tensor_attributes(x, y) + return y + + with torch.no_grad(): + if x.device.type == "xla": + # Access data_ptr() for a xla tensor will cause crash + return torch_clone(x) + + # Handle sparse storage (no stride). + if x.layout is torch.sparse_coo: + return torch.sparse_coo_tensor( + torch_clone(x._indices()), + torch_clone(x._values()), + x.shape, + is_coalesced=x.is_coalesced(), + ) + elif is_sparse_compressed(x): + if x.layout in {torch.sparse_csr, torch.sparse_bsr}: + compressed_indices = x.crow_indices() + plain_indices = x.col_indices() + else: + compressed_indices = x.ccol_indices() + plain_indices = x.row_indices() + return torch.sparse_compressed_tensor( + torch_clone(compressed_indices), + torch_clone(plain_indices), + torch_clone(x.values()), + x.shape, + layout=x.layout, + ) + elif is_traceable_wrapper_subclass(x): + # Questionable - but this is required to not fail executorch related + # torchao tests. + return torch_clone(x) + + needed_size = sum( + (shape - 1) * stride for shape, stride in zip(x.size(), x.stride()) + ) + if x.is_quantized: + result = torch.empty_quantized((needed_size + 32,), x) + else: + result = torch.empty( + needed_size + 32, + dtype=dtype or x.dtype, + device=x.device, + pin_memory=is_pinned_cpu_tensor(x), + ) + cache_line_offset = ( + (x.data_ptr() - result.data_ptr()) % 32 + ) // x.element_size() + result.as_strided_(x.size(), x.stride(), cache_line_offset) + try: + result.copy_(x.clone()) + if x.is_leaf: + result.requires_grad_(x.requires_grad) + if x.is_leaf and x.grad is not None: + result.grad = clone_input(x.grad, dtype=dtype) + except RuntimeError: + # RuntimeError: unsupported operation: more than one element of the written-to + # tensor refers to a single memory location. Please clone() the tensor before + # performing the operation. + return torch_clone(x) + copy_dynamo_tensor_attributes(x, result) + return result + + +@overload +def clone_inputs( + example_inputs: dict[str, T | tuple[T, ...]], +) -> dict[str, list[T]]: ... + + +@overload +def clone_inputs(example_inputs: Sequence[T]) -> list[T]: ... + + +def clone_inputs(example_inputs: Any) -> Any: + res: dict[str, Any] | list[Any] + if type(example_inputs) is dict: + res = dict(example_inputs) + for key, value in res.items(): + if isinstance(value, tuple): + res[key] = clone_inputs(value) + else: + if not isinstance(value, torch.Tensor): + raise AssertionError( + f"Expected value to be a torch.Tensor, got {type(value)}" + ) + res[key] = clone_input(value) + return res + + res = list(example_inputs) + for i in range(len(res)): + if isinstance(res[i], torch.Tensor): + res[i] = clone_input(res[i]) + return res + + +def skip_frame_if_in_functorch_mode(val: torch.Tensor) -> None: + try: + val.data_ptr() # will throw for functorch tensors + except RuntimeError as e: + from .exc import unimplemented + + # This will be GradTrackingTensor/BatchedTensor/etc + functorch_subclass_name = re.sub(r"\(.*", "", repr(val)) + + unimplemented( + gb_type="skip frame due to being in functorh mode", + context="", + explanation=f"torch.compile cannot be run in context: {functorch_subclass_name}. Skipping frame.", + hints=[], + from_exc=e, + skip_frame=True, + ) + + +@contextmanager +def preserve_rng_state() -> Generator[None, None, None]: + disable_functorch = torch._C._DisableFuncTorch + disable_current_modes = torch.utils._python_dispatch._disable_current_modes + with disable_current_modes(), disable_functorch(): + rng_state = torch.clone(torch.random.get_rng_state()) + skip_frame_if_in_functorch_mode(rng_state) + if torch.cuda.is_available(): + cuda_rng_state = torch.clone(torch.cuda.get_rng_state()) + if torch.xpu.is_available(): + xpu_rng_state = torch.clone(torch.xpu.get_rng_state()) + try: + yield + finally: + with torch.utils._python_dispatch._disable_current_modes(): + torch.random.set_rng_state(rng_state) + if torch.cuda.is_available(): + torch.cuda.set_rng_state(cuda_rng_state) # type: ignore[possibly-undefined] + if torch.xpu.is_available(): + torch.xpu.set_rng_state(xpu_rng_state) # type: ignore[possibly-undefined] + + +def is_jit_model( + model0: Any, +) -> TypeIs[ + torch.jit._trace.TopLevelTracedModule + | torch.jit._script.RecursiveScriptModule + | torch.jit.ScriptFunction[Any, Any] + | torch.jit.ScriptModule +]: + return isinstance( + model0, + ( + torch.jit._trace.TopLevelTracedModule, + torch.jit._script.RecursiveScriptModule, + torch.jit.ScriptFunction, + torch.jit.ScriptModule, + ), + ) + + +def torchscript(model: Any, example_inputs: Any, verbose: bool = False) -> Any: + if is_jit_model(model): + # already done? + return model + + try: + return torch.jit.trace(model, example_inputs) + except Exception: + try: + return torch.jit.script(model) + except Exception: + if verbose: + log.exception("jit error") + else: + log.error("Both torch.jit.trace and torch.jit.script failed") + return None + + +def getfile(obj: object) -> str | None: + try: + # inspect.getfile is typed to accept only a narrow union of callable + # and module-like objects, but at runtime it accepts any object and + # raises TypeError for unsupported ones, which this function catches. + return inspect.getfile(obj) # type: ignore[arg-type] + except (TypeError, OSError): + return None + + +def is_namedtuple(obj: object) -> bool: + """Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple""" + return is_namedtuple_cls(type(obj)) + + +def is_namedtuple_cls(cls: object) -> bool: + """Test if an object is a namedtuple or a (torch.return_types|torch.autograd.forward_ad).* quasi-namedtuple""" + if not isinstance(cls, type): + return False + try: + if issubclass(cls, tuple): + module = getattr(cls, "__module__", None) + if module in ("torch.return_types", "torch.autograd.forward_ad"): + return True + if isinstance(getattr(cls, "_fields", None), tuple) and callable( + getattr(cls, "_make", None) + ): + # The subclassing style namedtuple can have an extra base `typing.Generic` + bases = tuple(t for t in cls.__bases__ if t is not Generic) + if bases == (tuple,): + # This is a namedtuple type directly created by `collections.namedtuple(...)` + return True + if bases and any( + ( + # Subclass of namedtuple + is_namedtuple_cls(t) + # For subclasses of namedtuple, the __new__ method should not be customized + and cls.__new__ is t.__new__ + ) + for t in bases + ): + return True + except TypeError: + pass + return False + + +@functools.lru_cache(1) +def namedtuple_fields(cls: type) -> tuple[str, ...]: + """Get the fields of a namedtuple or a torch.return_types.* quasi-namedtuple""" + if cls is slice: + return ("start", "stop", "step") + + if not issubclass(cls, tuple): + raise AssertionError(f"Expected cls to be a subclass of tuple, got {cls}") + if hasattr(cls, "_fields"): + # normal namedtuples + return cls._fields + + @dataclasses.dataclass + class Marker: + index: int + + # frustrating ones e.g. torch.return_types.max + if cls.__module__ != "torch.return_types": + raise AssertionError( + f"Expected cls.__module__ to be 'torch.return_types', got {cls.__module__!r}" + ) + obj = cls(map(Marker, range(cls.n_fields))) # type: ignore[attr-defined] + fields: dict[str, int] = {} + for name in dir(obj): + if name[0] != "_" and isinstance(getattr(obj, name), Marker): + fields[name] = getattr(obj, name).index + if len(fields) != cls.n_fields: # type: ignore[attr-defined] + raise AssertionError( + f"Expected {cls.n_fields} fields, got {len(fields)}" # type: ignore[attr-defined] + ) + return tuple(sorted(fields, key=fields.get)) # type: ignore[arg-type] + + +def checkpoint_params(gm: torch.fx.GraphModule) -> Callable[[], None]: + with torch.no_grad(): + rng_state = torch.clone(torch.random.get_rng_state()) + if torch.cuda.is_available(): + cuda_rng_state = torch.clone(torch.cuda.get_rng_state()) + saved_state = [ + (param, param._version, torch.clone(param)) + # pyrefly: ignore [bad-argument-type] + for param in itertools.chain(gm.parameters(), gm.buffers()) + ] + + def restore() -> None: + with torch.no_grad(): + torch.random.set_rng_state(rng_state) + if torch.cuda.is_available(): + torch.cuda.set_rng_state(cuda_rng_state) + for param, version, original_value in saved_state: + if param._version != version: + param.copy_(original_value) + + return restore + + +def timed( + model: Any, example_inputs: Iterable[Any], times: int = 1 +) -> tuple[Any, float]: + if torch.accelerator.is_available(): + synchronize = torch.accelerator.synchronize + else: + synchronize = nothing + + synchronize() + gc.collect() + torch.manual_seed(1337) + t0 = time.perf_counter() + for _ in range(times): + result = model(*example_inputs) + synchronize() + t1 = time.perf_counter() + return result, t1 - t0 # type: ignore[possibly-undefined] + + +def check_is_cuda(gm: torch.fx.GraphModule, example_inputs: Iterable[Any]) -> bool: + return all(x.is_cuda for x in itertools.chain(example_inputs, gm.parameters(True))) + + +@lru_cache(32) +def rot_n_helper(n: int) -> Callable[..., Any]: + if n <= 1: + raise AssertionError(f"Expected n > 1, got {n}") + vars = [f"v{i}" for i in range(n)] + rotated = reversed(vars[-1:] + vars[:-1]) + fn = eval(f"lambda {','.join(vars)}: ({','.join(rotated)})") + fn.__name__ = f"rot_{n}_helper" + return fn + + +common_constant_types: set[type] = { + int, + float, + complex, + bool, + str, + bytes, + type(None), + Ellipsis.__class__, + NotImplemented.__class__, + types.CodeType, + # Commonly used immutable types from torch. + torch.device, + torch.dtype, + torch.memory_format, + torch.layout, + torch.finfo, + torch.iinfo, + torch.nn.attention.SDPBackend, + torch.cuda._CudaDeviceProperties, + # Pytree key types (frozen dataclasses used in tree_map_with_path) + torch.utils._pytree.SequenceKey, + torch.utils._pytree.MappingKey, + torch.utils._pytree.GetAttrKey, +} + +if has_triton_package(): + import triton + + common_constant_types.add(triton.language.dtype) + +""" + Difference between is_safe_constant and common_constant_types. + * common_constant_types: Constants would be wrapped by VariableBuilder.wrap_literal + as ConstantVariable. + * is_safe_constant: Constants can be loaded by LOAD_CONST bytecode. +""" + + +def is_safe_constant(v: object) -> bool: + if istype(v, (tuple, frozenset)): + return all(map(is_safe_constant, v)) + return isinstance( + v, + ( + enum.Enum, + type, + torch.Size, + typing._GenericAlias, # type: ignore[attr-defined] + types.GenericAlias, + ), + ) or istype( + v, + common_constant_types | {slice}, + ) + + +@functools.cache +def common_constants() -> set[int]: + return { + # We zero-one specialize shapes, so specialize these constants + # too + 0, + 1, + } + + +def is_torch_sym(value: object) -> TypeGuard[torch.SymBool | torch.SymInt]: + return isinstance(value, (torch.SymBool, torch.SymInt)) and not isinstance( + value.node, torch.nested._internal.nested_int.NestedIntNode + ) + + +def is_int_specialization_case(value: Any, source: Any) -> bool: + from .source import is_from_defaults + + return not TracingContext.get().force_unspec_int_unbacked_size_like and ( + # Assume integers from global variables want to be specialized + not source.guard_source.is_local() + # Assume that integers that came from NN modules want to be + # specialized (as we don't expect users to be changing the + # NN modules on the fly), unless explicitly disabled + or ( + source.guard_source.is_specialized_nn_module() + and not config.allow_unspec_int_on_nn_module + ) + or ( + source.guard_source.is_unspecialized_builtin_nn_module() + and not config.allow_unspec_int_on_nn_module + ) + or ( + source.guard_source.is_unspecialized_nn_module() + and not config.allow_unspec_int_on_nn_module + ) + or is_from_defaults(source) + # TODO: Delete this condition when rollout is done. NB: this + # condition never evaluates True in open source + or ( + not justknobs_check("pytorch/dynamo:enable_unspecialize_zero_one_plain_int") + and value in common_constants() + ) + ) + + +def specialize_symnode(arg: Any) -> Any: + from .variables import ConstantVariable, LazyVariableTracker, SymNodeVariable + from .variables.lazy import ComputedLazyConstantVariable + + # Guard and specialize + if isinstance(arg, LazyVariableTracker): + if not arg.is_realized() and not isinstance(arg, ComputedLazyConstantVariable): + # Find if the arg would be realized as SymNodeVariable later on. If yes, + # realize it and specialize. Else return the arg. + + source = arg.original_source() + value = arg.original_value() + + is_symnode_vt = is_torch_sym(value) or ( + not config.specialize_int + and type(value) is int + and not is_int_specialization_case(value, source) + ) + + if not is_symnode_vt: + return arg + + # Realize to get the underlying variable (handles both realized and unrealized) + arg = arg.realize() + + if isinstance(arg, SymNodeVariable): + return ConstantVariable.create(arg.evaluate_expr()) + return arg + + +def guard_if_dyn(arg: Any) -> Any: + from .variables import VariableTracker + + arg = specialize_symnode(arg) + + if isinstance(arg, VariableTracker) and arg.is_python_constant(): + return arg.as_python_constant() + + return arg + + +def check_constant_args(args: Iterable[Any], kwargs: Mapping[Any, Any]) -> bool: + return all(x.is_python_constant() for x in itertools.chain(args, kwargs.values())) + + +def check_unspec_python_args(args: Iterable[Any], kwargs: Mapping[Any, Any]) -> bool: + from .variables import VariableTracker + from .variables.tensor import UnspecializedPythonVariable + + unspec_count = 0 + for x in itertools.chain(args, kwargs.values()): + if isinstance(x, UnspecializedPythonVariable): + unspec_count += 1 + elif not (isinstance(x, VariableTracker) and x.is_python_constant()): + return False + return unspec_count > 0 + + +def check_unspec_or_constant_args( + args: Iterable[Any], kwargs: Mapping[Any, Any] +) -> bool: + # A fused version of: + # return check_constant_args(args, kwargs) or check_unspec_python_args(args, kwargs) + from .variables.tensor import UnspecializedPythonVariable + + for x in itertools.chain(args, kwargs.values()): + if not (x.is_python_constant() or isinstance(x, UnspecializedPythonVariable)): + return False + return True + + +def check_numpy_ndarray_args(args: Iterable[Any], kwargs: Mapping[Any, Any]) -> bool: + from .variables.tensor import NumpyNdarrayVariable + + return any( + isinstance(x, NumpyNdarrayVariable) + for x in itertools.chain(args, kwargs.values()) + ) + + +dict_keys: type[KeysView[Any]] = type({}.keys()) +dict_values: type[ValuesView[Any]] = type({}.values()) +dict_items: type[ItemsView[Any, Any]] = type({}.items()) +odict_values: type[ValuesView[Any]] = type(OrderedDict().values()) +# pyrefly: ignore [bad-assignment] +tuple_iterator: type[Iterator[Any]] = type(iter(())) +# pyrefly: ignore [bad-assignment] +range_iterator: type[Iterator[Any]] = type(iter(range(0))) +tuple_iterator_len = tuple_iterator.__length_hint__ # type: ignore[attr-defined] +deque_iterator = type(iter(collections.deque())) +deque_rev_iterator = type(reversed(collections.deque())) +object_new = object.__new__ +dict_new = dict.__new__ +dict_methods = { + method + for method in itertools.chain(dict.__dict__.values(), OrderedDict.__dict__.values()) + if callable(method) +} +set_methods = {method for method in set.__dict__.values() if callable(method)} +frozenset_methods = { + method for method in frozenset.__dict__.values() if callable(method) +} +base_exception_methods = { + method for method in BaseException.__dict__.values() if callable(method) +} +exception_methods = { + method for method in Exception.__dict__.values() if callable(method) +} + + +tuple_new = tuple.__new__ +tuple_methods = {method for method in tuple.__dict__.values() if callable(method)} +list_methods = {method for method in list.__dict__.values() if callable(method)} +list_getitem = list.__getitem__ + +deque_methods = { + method for method in collections.deque.__dict__.values() if callable(method) +} + +str_methods = {method for method in str.__dict__.values() if callable(method)} + +# EnumType is the metaclass for Enum classes +enum_type_methods = { + method for method in type(enum.Enum).__dict__.values() if callable(method) +} + +K = TypeVar("K") +V = TypeVar("V") + + +def builtin_dict_keys(d: dict[K, V]) -> KeysView[K]: + # Avoids overridden keys method of the dictionary + if not isinstance(d, dict): + raise AssertionError(f"Expected d to be a dict, got {type(d)}") + return dict.keys(d) + + +def get_items_from_dict(obj: dict[K, V]) -> Iterable[tuple[K, V | Any]]: + # Get items without calling the user defined __getitem__ or keys method. + if not isinstance(obj, dict): + raise AssertionError(f"Expected obj to be a dict, got {type(obj)}") + if istype(obj, (dict, OrderedDict)): + return obj.items() + elif isinstance(obj, OrderedDict): + return [(k, OrderedDict.__getitem__(obj, k)) for k in OrderedDict.keys(obj)] + else: + return [(k, dict.__getitem__(obj, k)) for k in dict.keys(obj)] + + +def enumerate_items_with_dict_position( + obj: dict[K, V], +) -> Iterable[tuple[int, K, V | Any]]: + """Enumerate dict items yielding (dict_keys_position, key, value). + + For OrderedDicts where move_to_end/prepend has been used, the OrderedDict + iteration order can differ from dict.keys() order. We iterate in + OrderedDict order (correct execution semantics) but return each key's + dict.keys() position so that ConstDictKeySource indices stay consistent + with PyDict_Next / C++ DictGuardManager. + """ + items = get_items_from_dict(obj) + if isinstance(obj, OrderedDict): + key_to_pos = {k: i for i, k in enumerate(dict.keys(obj))} + return ((key_to_pos[k], k, v) for k, v in items) + return ((i, k, v) for i, (k, v) in enumerate(items)) + + +def nn_module_new(cls: Any) -> Any: + obj = object_new(cls) + torch.nn.Module.__init__(obj) + return obj + + +def product(it: Iterable[T]) -> int: + return functools.reduce(operator.mul, it, 1) + + +def tuple_iterator_getitem(it: Any, index: int) -> Any: + _, (obj,), start = it.__reduce__() + return obj[start + index] + + +def dataclass_fields(cls: Any) -> Any: + return torch._dynamo.disable(dataclasses.fields)(cls) + + +iter_next = next + + +def normalize_count_iter(count_iter: Iterator[Any]) -> tuple[Any, Any]: + try: + _, args = count_iter.__reduce__() + except TypeError: + # Python 3.14 no longer pickles itertools.count, so fall back to the + # repr and only recover literal arguments. Non-literal arguments still + # fall back to user-defined handling via the NotImplemented sentinel. + import ast + + count_repr = repr(count_iter) + if not count_repr.startswith("count(") or not count_repr.endswith(")"): + return (NotImplemented, NotImplemented) + try: + args = ast.literal_eval(f"({count_repr[6:-1]},)") + except (SyntaxError, ValueError): + return (NotImplemented, NotImplemented) + if not isinstance(args, tuple) or not 1 <= len(args) <= 2: + return (NotImplemented, NotImplemented) + if len(args) == 1: + return (args[0], 1) + return (args[0], args[1]) + + +def normalize_range_iter(range_iter: Any) -> tuple[int, int, int]: + _, (range_obj,), maybe_idx = range_iter.__reduce__() + # In 3.12+, `maybe_idx` could be None, and `range_obj.start` would've been + # already incremented by the current index. + # The index (maybe_idx) is the number of steps taken so far. To get the + # correct start value, one must add (maybe_idx * step) to the original + # start. See: + # https://github.com/python/cpython/blob/ea77feecbba389916af8f90b2fc77f07910a2963/Objects/rangeobject.c#L885-L899 + start = range_obj.start + (maybe_idx or 0) * range_obj.step + stop = range_obj.stop + step = range_obj.step + return (start, stop, step) + + +def to_subclass(t: Any, cls: type) -> Any: + return t.as_subclass(cls) + + +dict_getitem = dict.__getitem__ + + +@torch.fx.wrap +def dict_keys_getitem(d: dict[Any, Any], n: int) -> Any: + # Use dict.keys() to match the iteration order of PyDict_Next used by + # the C++ DictGuardManager and by ConstDictKeySource._name_template. + # pyrefly: ignore [bad-argument-type] + return next(itertools.islice(dict.keys(d), n, n + 1)) + + +def set_base_iter(s: Iterable[T]) -> Iterator[T]: + if isinstance(s, set): + return set.__iter__(s) + if isinstance(s, frozenset): + return frozenset.__iter__(s) + return iter(s) + + +def set_getitem(s: set[T], n: int) -> T: + # Set ordering might not be stable. For set/frozenset subclasses, use the + # base iterator so guard reconstruction observes the internal set contents. + try: + return next(itertools.islice(set_base_iter(s), n, n + 1)) + except StopIteration: + raise IndexError("set index out of range") from None + + +def enum_repr(value: Any, local: bool) -> str: + # enum class can override __str__ method. Use __class__ and name attribute + # to extract the class name and key name. + name = value.__class__.__name__ + val = value.name + scope = "L" if local else "G" + local_name = f'{scope}["{name}"].{val}' + return local_name + + +def set_example_value(node: torch.fx.Node, example_value: Any) -> None: + # NB: example_value is a bit of a misnomer, because this is always a fake + # tensor of some sort. Furthermore, these example values serve as the + # runtime state of Dynamo tracing, which means if metadata mutation + # occurs, the example_value gets directly updated (so you can't rely on + # this to accurately reflect what the state of the value was at the time + # the program was traced). + node.meta["example_value"] = example_value + fake_mode = TracingContext.get().fake_mode + if fake_mode is None: + raise AssertionError("fake_mode must not be None") + shape_env = fake_mode.shape_env + if ( + symbol_to_path + := torch.fx.experimental.symbolic_shapes.compute_unbacked_bindings( + shape_env, example_value + ) + ): + node.meta["unbacked_bindings"] = symbol_to_path + + +def _get_fake_tensor(vt: VariableTracker) -> Any: + fake_tensor = vt.as_proxy().node.meta.get("example_value") + if not is_fake(fake_tensor): + from . import graph_break_hints + from .exc import unimplemented + + unimplemented( + gb_type="Cannot check Tensor object identity without its fake value", + context=str(fake_tensor), + explanation="TensorVariable is missing a fake example_value.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + return fake_tensor + + +def slice_length(s: slice, seq_len: int) -> int: + start, stop, step = s.indices(seq_len) + return max(0, (stop - start + (step - (1 if step > 0 else -1))) // step) + + +def raise_args_mismatch( + tx: InstructionTranslatorBase, + name: str, + expect: str = "", + actual: str = "", +) -> NoReturn: + from torch._dynamo.exc import raise_observed_exception + + msg_str = ( + f"wrong number of arguments or keyword arguments for {name}() call.\n" + f" Expect: {expect}\n" + f" Actual: {actual}" + ) + + raise_observed_exception( + TypeError, + tx, + args=[msg_str], + ) + + +def check_positional( + tx: InstructionTranslatorBase, + funcname: str, + nargs: int, + min_args: int, + max_args: int, +) -> None: + # Mirrors CPython _PyArg_CheckPositional (Python/getargs.c): enforce + # min_args <= nargs <= max_args with CPython's exact TypeError text. Used + # for METH_FASTCALL methods, whose positional count MethodFlags (derived + # from ml_flags) cannot check. + from torch._dynamo.exc import raise_type_error + + if nargs < min_args: + rel = "" if min_args == max_args else "at least " + s = "" if min_args == 1 else "s" + raise_type_error( + tx, f"{funcname} expected {rel}{min_args} argument{s}, got {nargs}" + ) + if nargs > max_args: + rel = "" if min_args == max_args else "at most " + s = "" if max_args == 1 else "s" + raise_type_error( + tx, f"{funcname} expected {rel}{max_args} argument{s}, got {nargs}" + ) + + +def no_positional( + tx: InstructionTranslatorBase, funcname: str, args: list[VariableTracker] +) -> None: + # Mirrors CPython _PyArg_NoPositional (Python/getargs.c). + from torch._dynamo.exc import raise_type_error + + if args: + raise_type_error(tx, f"{funcname}() takes no positional arguments") + + +def no_keywords( + tx: InstructionTranslatorBase, funcname: str, kwargs: dict[str, VariableTracker] +) -> None: + # Mirrors CPython _PyArg_NoKeywords / _PyArg_NoKwnames (Python/getargs.c). + # For methods reached via tp_methods, MethodFlags already rejects kwargs; + # use this only where MethodFlags does not run (e.g. tp_init constructors). + from torch._dynamo.exc import raise_type_error + + if kwargs: + raise_type_error(tx, f"{funcname}() takes no keyword arguments") + + +def iter_contains( + items: Iterable[VariableTracker], + search: VariableTracker, + tx: InstructionTranslatorBase, +) -> VariableTracker: + from .variables import ConstantVariable + from .variables.object_protocol import generic_richcompare_bool + + items = list(items) + # CPython's list_contains/set_contains use PyObject_RichCompareBool(item, + # search, Py_EQ) with an identity shortcut. The constant fast path is only + # valid when every element is a constant too; a non-constant element earlier + # in the sequence has an __eq__ that must be honored in order (it may match, + # or raise), so fall through to the per-element richcompare loop otherwise. + if search.is_python_constant() and all(x.is_python_constant() for x in items): + search_val = search.as_python_constant() + found_const = any( + x.as_python_constant() is search_val or x.as_python_constant() == search_val + for x in items + ) + return ConstantVariable.create(found_const) + found: VariableTracker | None = None + for x in items: + check = generic_richcompare_bool(tx, x, search, "__eq__") + if check.is_constant_match(True): + return check + if check.is_constant_match(False): + continue + if found is None: + found = check + else: + from torch._dynamo.variables.builder import SourcelessBuilder + + found = SourcelessBuilder.create(tx, operator.or_).call_function( + tx, [check, found], {} + ) + if found is None: + found = ConstantVariable.create(False) + return found + + +def key_is_id( + k: Any, +) -> TypeIs[torch.Tensor | torch.nn.Module | MethodWrapperType]: + """Returns whether it indexes dictionaries using its id""" + return isinstance(k, (torch.Tensor, torch.nn.Module, MethodWrapperType)) + + +def key_to_id(value: Any) -> list[Any]: + return [id(k) if key_is_id(k) else k for k in value] + + +def const_repr(x: Any, *, local: Any) -> str: + from .trace_rules import is_builtin_callable + + if isinstance(x, (list, tuple)): + elems_repr = ",".join(const_repr(s, local=local) for s in x) + if isinstance(x, list): + return f"[{elems_repr}]" + else: + if not isinstance(x, tuple): + raise AssertionError(f"Expected x to be a tuple, got {type(x)}") + if len(x) == 1: + return f"({elems_repr},)" + else: + return f"({elems_repr})" + elif isinstance(x, enum.Enum): + # To workaround repr(Enum) returning invalid global reference before python 3.11 + # by calling enum_repr and removing quotes to render enum in guard code. + return enum_repr(x, local=local).replace("'", "") + elif is_builtin_callable(x): + return x.__name__ + elif isinstance(x, type): + + def fullname(o: Any) -> str: + klass = o.__class__ + module = klass.__module__ + if module == "builtins": + return klass.__qualname__ # avoid outputs like 'builtins.str' + return module + "." + klass.__qualname__ + + return fullname(x) + else: + return f"{x!r}" + + +def dict_keys_repr(const_keys: Any, *, local: Any) -> str: + keys_str = ",".join(const_repr(s, local=local) for s in const_keys) + return "[" + keys_str + "]" + + +GLOBAL_KEY_PREFIX = "__dict_key" + + +from torch._subclasses import UnsupportedFakeTensorException + + +def get_safe_global_name(tx: InstructionTranslatorBase, root: str, obj: Any) -> str: + # The global_mangled_class_name should be different for different + # invocations of torch.compile. Otherwise, we can run into a situation + # where multiple torch.compile invocations reuse the same global name, + # but the global's lifetime is tied to the first invocation (and + # may be deleted when the first torch.compile invocation is deleted) + # We mangle it based off of the output_graph's id. + return f"{root}_{id(obj)}_c{tx.output.compile_id}" + + +def is_in(item: T, *containers: Container[T]) -> bool: + for container in containers: + if item in container: + return True + return False + + +def get_unique_name_wrt( + prefix: str, *containers: Any, requires_suffix: bool = False +) -> str: + """ + Return a name that starts with `prefix` and is not in any of the + `containers` (e.g., map, set). + """ + if not requires_suffix and not is_in(prefix, *containers): + return prefix + + for i in itertools.count(): + candidate = f"{prefix}_{i}" + if not is_in(candidate, *containers): + return candidate + + raise AssertionError("unreachable") + + +def wrap_fake_exception(fn: Callable[[], Any]) -> Any: + try: + return fn() + except UnsupportedFakeTensorException as e: + from .exc import unimplemented + + msg = f"Encountered exception ({e.reason}) during fake tensor propagation." + log.warning(msg) + unimplemented( + gb_type="Fake tensor propagation exception", + context=str(e.reason), + explanation=msg, + hints=[], + from_exc=e, + ) + + +def deepcopy_to_fake_tensor( + obj: Any, fake_mode: torch._subclasses.fake_tensor.FakeTensorMode +) -> Any: + with torch._subclasses.fake_tensor.FakeCopyMode(fake_mode): + return wrap_fake_exception(lambda: copy.deepcopy(obj)) + + +def rmse(ref: torch.Tensor, res: torch.Tensor) -> torch.Tensor: + """ + Calculate root mean squared error + """ + return torch.sqrt(torch.mean(torch.square(ref - res))) + + +def bitwise_same(ref: Any, res: Any, equal_nan: bool = False) -> bool: + return same( + ref, + res, + tol=0.0, + equal_nan=equal_nan, + ) + + +def same( + ref: Any, + res: Any, + fp64_ref: Any = None, + cos_similarity: bool = False, + tol: float = 1e-4, + equal_nan: bool = False, + exact_dtype: bool = True, + relax_numpy_equality: bool = False, + ignore_non_fp: bool = False, + log_error: Callable[..., None] = log.error, + use_larger_multiplier_for_smaller_tensor: bool = False, + force_max_multiplier: bool = False, + use_iou_for_bool: bool = False, + iou_threshold: float = 0.99, +) -> bool: + """Check correctness to see if ref and res match""" + if fp64_ref is None: + fp64_ref = ref + if isinstance( + ref, (list, tuple, collections.deque, torch.nn.ParameterList, torch.Size) + ): + if not isinstance(res, (list, tuple, collections.deque)): + raise AssertionError(f"type mismatch {type(ref)} {type(res)}") + if len(ref) != len(res): + log_error("Length mismatch") + return False + return len(ref) == len(res) and all( + same( + ai, + bi, + fp64_refi, + cos_similarity, + tol, + equal_nan, + exact_dtype, + relax_numpy_equality, + ignore_non_fp, + log_error=log_error, + use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor, + force_max_multiplier=force_max_multiplier, + use_iou_for_bool=use_iou_for_bool, + iou_threshold=iou_threshold, + ) + for ai, bi, fp64_refi in zip(ref, res, fp64_ref) + ) + elif type(ref).__name__ == "QuestionAnsweringModelOutput": + # This skips checking accuracy for start_logits/end_logits. + # Tentatively, start_logits/end_logits appear to be very prone to + # inaccuracies and is somewhat subsumed by checking the loss. + return same( + ref.loss, + res.loss, + fp64_ref.loss, + cos_similarity, + tol, + equal_nan, + exact_dtype, + relax_numpy_equality, + ignore_non_fp, + log_error=log_error, + use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor, + force_max_multiplier=force_max_multiplier, + use_iou_for_bool=use_iou_for_bool, + iou_threshold=iou_threshold, + ) + elif isinstance(ref, dict): + if not isinstance(res, dict): + raise AssertionError(f"Expected res to be a dict, got {type(res)}") + if set(ref.keys()) != set(res.keys()): + raise AssertionError( + f"keys mismatch {set(ref.keys())} == {set(res.keys())}" + ) + for k in sorted(ref.keys()): + if not ( + same( + ref[k], + res[k], + fp64_ref[k], + cos_similarity=cos_similarity, + tol=tol, + equal_nan=equal_nan, + exact_dtype=exact_dtype, + relax_numpy_equality=relax_numpy_equality, + ignore_non_fp=ignore_non_fp, + log_error=log_error, + use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor, + force_max_multiplier=force_max_multiplier, + use_iou_for_bool=use_iou_for_bool, + iou_threshold=iou_threshold, + ) + ): + log_error("Accuracy failed for key name %s", k) + return False + return True + elif isinstance(ref, set): + if not isinstance(res, set): + raise AssertionError(f"Expected res to be a set, got {type(res)}") + if set(ref) != set(res): + raise AssertionError(f"elements mismatch {set(ref)} == {set(res)}") + return True + elif isinstance(ref, (torch.Tensor, float)): + if torch._subclasses.fake_tensor.is_fake_tensor(ref): + raise AssertionError("ref should not be a FakeTensor") + if torch._subclasses.fake_tensor.is_fake_tensor(res): + raise AssertionError("res should not be a FakeTensor") + + def to_tensor(t: Any) -> torch.Tensor: + return t if isinstance(t, torch.Tensor) else torch.tensor(t) + + ref, res, fp64_ref = (to_tensor(val) for val in (ref, res, fp64_ref)) + + if ref.is_sparse: + if not res.is_sparse: + raise AssertionError("Expected res to be sparse since ref is sparse") + ref = ref.to_dense() + res = res.to_dense() + if not isinstance(res, torch.Tensor): + raise AssertionError(f"type mismatch {type(ref)} {type(res)}") + if exact_dtype: + if ref.dtype != res.dtype: + log_error("dtype mismatch %s, %s", ref.dtype, res.dtype) + return False + if ref.dtype == torch.bool: + if ignore_non_fp: + return True + if use_iou_for_bool: + # Use IoU (Intersection over Union) metric for boolean mask comparison. + # This is useful for segmentation models where small floating-point + # differences get thresholded into boolean masks. + intersection = (ref & res).sum().float() + union = (ref | res).sum().float() + if union == 0: + # Both masks are empty + return bool(intersection == 0) + iou = (intersection / union).item() + if iou < iou_threshold: + log_error( + "IoU accuracy failed: %.4f < %.2f (intersection=%d, union=%d, ref_sum=%d, res_sum=%d, shape=%s)", + iou, + iou_threshold, + int(intersection.item()), + int(union.item()), + int(ref.sum().item()), + int(res.sum().item()), + list(ref.shape), + ) + return False + return True + # triton stores bool as int8, so add this for more accurate checking + r = torch.allclose( + ref.to(dtype=torch.uint8), + res.to(dtype=torch.uint8), + atol=tol, + rtol=tol, + equal_nan=equal_nan, + ) + if not r: + log_error("Accuracy failed: uint8 tensor did not match") + return r + + if cos_similarity: + ref = ref.flatten().to(torch.float32) + res = res.flatten().to(torch.float32) + if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=True): + # early exit that handles zero/nan better + # cosine_similarity(zeros(10), zeros(10), dim=0) is 0 + return True + score = torch.nn.functional.cosine_similarity(ref, res, dim=0, eps=1e-6) + if score < 0.99: + log.warning("Similarity score=%s", score.detach().cpu().item()) + return bool(score >= 0.99) + else: + if not exact_dtype: + ref = ref.to(res.dtype) + + # First try usual allclose + if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=equal_nan): + return True + + # Check error from fp64 version + if fp64_ref.dtype == torch.float64: + # Fix a corner case that res and fp64_ref does not contains NaN and match (with loose tolerance) + # while the ref contains NaN. In this case, RMSE should not match any ways. + # But res is 'BETTER' than ref so we count it pass. + # + # This happens for Super_SloMo when loop ordering after fusion is enabled: + # https://gist.github.com/shunting314/11f235c70f7db0d52718d26f4a701cab + loose_tol = 1e-2 * 4 + if ( + not fp64_ref.isnan().any() + and not res.isnan().any() + and ref.isnan().any() + and torch.allclose( + fp64_ref.to(dtype=res.dtype), + res, + atol=loose_tol, + rtol=loose_tol, + equal_nan=equal_nan, + ) + ): + return True + ref_error = rmse(fp64_ref, ref).item() + # ref unable to produce this with stable numerics in this precision, ignore + if math.isnan(ref_error): + log.warning( + "Found nan in reference. Consider running in higher precision." + ) + + res_error = rmse(fp64_ref, res).item() + + def get_multiplier() -> float: + # In some particular cases, we expect high difference in results. + # At the moment one of these cases is inductor freezing bfloat16 convolution const folding. + # In this case, the res_error is at least one order of magnitude higher. + if force_max_multiplier: + return 10.0 + # In the case of using AMP (Automatic Mixed Precision), certain models have + # failed the benchmark's correctness check. However, the end-to-end model's + # accuracy when comparing AMP with FP32 is within a difference of less than 0.1%. + # Thus, it's possible that the correctness check failures for these models are + # false alarms. We use multiplier of 3 instead of 2 to avoid these false alarms. + multiplier = ( + 3.0 if res.dtype in (torch.float16, torch.bfloat16) else 2.0 + ) + + if use_larger_multiplier_for_smaller_tensor and ( + fp64_ref.numel() <= 10 + ): + multiplier = 10.0 + elif use_larger_multiplier_for_smaller_tensor and ( + fp64_ref.numel() <= 500 + ): + multiplier = 8.0 + elif ( + fp64_ref.numel() < 1000 + or (ref.ndim == 4 and ref.shape[-1] == ref.shape[-2] == 1) + # large tol means a benchmark has been specified as REQUIRE_HIGHER_TOLERANCE + or tol >= 2 * 1e-2 + ): + # In the presence of noise, noise might dominate our error + # metric for smaller tensors. + # Similarly, for 1x1 kernels, there seems to be high noise with amp. + multiplier = 3.0 + return multiplier + + multiplier = get_multiplier() + + passes_test = res_error <= (multiplier * ref_error + tol / 10.0) + if ( + not passes_test + and equal_nan + and math.isnan(ref_error) + and math.isnan(res_error) + # Some unit test for the accuracy minifier relies on + # returning false in this case. + and not torch._inductor.config.cpp.inject_relu_bug_TESTING_ONLY + ): + passes_test = True + if not passes_test: + log_error( + "RMSE (res-fp64): %.5f, (ref-fp64): %.5f and shape=%s. res.dtype: %s, multiplier: %f, tol: %f" + ", use_larger_multiplier_for_smaller_tensor: %d", + res_error, + ref_error, + res.size(), + res.dtype, + multiplier, + tol, + use_larger_multiplier_for_smaller_tensor, + ) + return passes_test + + if ignore_non_fp: + return True + + log_error("Accuracy failed: allclose not within tol=%s", tol) + return False + elif isinstance(ref, (str, int, type(None), bool, torch.device)): + if ignore_non_fp: + return True + r = ref == res + if not r: + log_error("Accuracy failed (%s): %s != %s", type(ref), ref, res) + return r + elif is_numpy_int_type(ref) or is_numpy_float_type(ref): + if relax_numpy_equality and not ( + is_numpy_int_type(res) or is_numpy_float_type(res) + ): + ref = ref.item() + r = (type(ref) is type(res)) and (ref == res) + if not r: + log_error("Accuracy failed (numpy): %s != %s", ref, res) + return r + elif is_numpy_ndarray(ref): + return (type(ref) is type(res)) and same( + torch.as_tensor(ref), + torch.as_tensor(res), + fp64_ref, + cos_similarity=cos_similarity, + tol=tol, + equal_nan=equal_nan, + exact_dtype=exact_dtype, + relax_numpy_equality=relax_numpy_equality, + ignore_non_fp=ignore_non_fp, + log_error=log_error, + use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor, + force_max_multiplier=force_max_multiplier, + use_iou_for_bool=use_iou_for_bool, + iou_threshold=iou_threshold, + ) + elif type(ref).__name__ in ( + "MaskedLMOutput", + "Seq2SeqLMOutput", + "CausalLMOutputWithCrossAttentions", + "LongformerMaskedLMOutput", + "Instances", + "SquashedNormal", + "Boxes", + "Normal", + "TanhTransform", + "Foo", + "Variable", + ): + if type(ref) is not type(res): + raise AssertionError(f"type mismatch {type(ref)} {type(res)}") + return all( + same( + getattr(ref, key), + getattr(res, key), + getattr(fp64_ref, key), + cos_similarity=cos_similarity, + tol=tol, + equal_nan=equal_nan, + exact_dtype=exact_dtype, + relax_numpy_equality=relax_numpy_equality, + ignore_non_fp=ignore_non_fp, + log_error=log_error, + use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor, + force_max_multiplier=force_max_multiplier, + use_iou_for_bool=use_iou_for_bool, + iou_threshold=iou_threshold, + ) + for key in ref.__dict__ + ) + else: + raise RuntimeError(f"unsupported type: {type(ref).__name__}") + + +def format_func_info(code: CodeType) -> str: + short_filename = code.co_filename.split("/")[-1] + return f"'{code.co_name}' ({short_filename}:{code.co_firstlineno})" + + +@contextlib.contextmanager +def disable_cache_limit() -> Generator[None, None, None]: + prior = config.recompile_limit + # pyrefly: ignore [bad-assignment] + config.recompile_limit = sys.maxsize + prior_acc_limit = config.accumulated_recompile_limit + # pyrefly: ignore [bad-assignment] + config.accumulated_recompile_limit = sys.maxsize + + try: + yield + finally: + config.recompile_limit = prior + config.accumulated_recompile_limit = prior_acc_limit + + +# map from transformed code back to original user code +orig_code_map = ExactWeakKeyDictionary() + +# keep a record of code_obj -> list of guard failure reasons for logging +guard_failures: collections.defaultdict[Any, list[Any]] = collections.defaultdict(list) + +# Keep a record of graph break reasons for logging +graph_break_reasons: list[torch._dynamo.output_graph.GraphCompileReason] = [] + +# keep record of compiled code, if we are in "error if recompile" +# to track code that dynamo has compiled previously +seen_code_map = ExactWeakKeyDictionary() + + +# return same dir unless user changes config between calls +@functools.cache +def _get_debug_dir(root_dir: str) -> str: + dir_name = ( + "run_" + + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f") + # use pid to avoid conflicts among ranks + + "-pid_" + + str(os.getpid()) + ) + return os.path.join(root_dir, dir_name) + + +def get_debug_dir() -> str: + debug_root = config.debug_dir_root + return _get_debug_dir(debug_root) + + +def extract_fake_example_value(node: torch.fx.Node, required: bool = True) -> Any: + if "example_value" in node.meta and is_fake(node.meta["example_value"]): + return node.meta["example_value"] + elif required: + from torch._dynamo.exc import unimplemented + + from . import graph_break_hints + + unimplemented( + gb_type="Missing FakeTensor example value", + context=str(node), + explanation=f"`FakeTensor` example value was required for {node} but not available.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + else: + return None + + +def ensure_graph_fake(e: Any, tx: InstructionTranslatorBase) -> Any: + from torch._subclasses.fake_tensor import maybe_get_fake_mode + + if maybe_get_fake_mode(e) is not tx.fake_mode: + raise AssertionError( + f"Expected fake mode of e to be tx.fake_mode, got {maybe_get_fake_mode(e)} vs {tx.fake_mode}" + ) + return e + + +def get_fake_values_from_nodes( + tx: InstructionTranslatorBase, nodes: Any, allow_non_graph_fake: bool +) -> Any: + def visit(n: torch.fx.Node) -> Any: + if n.op == "call_function" and "example_value" not in n.meta: + # fake tensor validity is checked inside get_fake_value using + # ensure_graph_fake + return get_fake_value(n, tx, allow_non_graph_fake) + + elif n.op == "get_attr" and "example_value" not in n.meta: + if n.target not in tx.output.nn_modules: + raise AssertionError( + f"Expected n.target {n.target!r} to be in tx.output.nn_modules" + ) + gm = tx.output.nn_modules[n.target] # type: ignore[index] + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError( + f"Expected gm to be a torch.fx.GraphModule, got {type(gm)}" + ) + return gm + + out = n.meta["example_value"] + if not allow_non_graph_fake and isinstance(out, torch.Tensor): + return ensure_graph_fake(out, tx) + return out + + return torch.fx.node.map_arg(nodes, visit) + + +def get_concrete_sizes_from_symints(msg: str, fake_mode: FakeTensorMode | None) -> str: + """ + Replace symbolic size expressions (like 's0', 's94') in error messages + with their concrete runtime values for better readability. + + Example: "size (s94)" -> "size (s94: hint= 10)" if s94's value is 10. + """ + import re + + from sympy.core.numbers import Integer + + if fake_mode is None: + return msg + + pattern = r"\(s(\d+)\)" + if fake_mode.shape_env is None: + raise AssertionError("fake_mode.shape_env must not be None") + shape_env = fake_mode.shape_env + backed_var_to_val = shape_env.backed_var_to_val + + def replace_sym(match: Any) -> str: + sym_name = f"s{match.group(1)}" + val = next( + (v for k, v in backed_var_to_val.items() if k.name == sym_name), + None, + ) + if isinstance(val, (int, Integer)): + return f"({sym_name}: hint = {str(val)})" + return match.group(0) + + msg = re.sub(pattern, replace_sym, msg) + return msg + + +def _wrap_graph_break_with_torch_runtime_err(gb_fn: Callable[[], NoReturn]) -> NoReturn: + from .exc import TorchRuntimeError, Unsupported + + try: + gb_fn() + except Unsupported as e: + exc = TorchRuntimeError(str(e), getattr(e, "real_stack", None)) + raise exc.with_traceback(e.__traceback__) from None + raise AssertionError("should be unreachable") + + +def _custom_op_fake_impl_pending(tx: InstructionTranslatorBase, target: Any) -> bool: + """True if ``target`` is a custom op whose ``register_fake`` ran earlier in + this trace -- i.e. its ``_abstract_fn`` has a pending (not-yet-applied) + attribute mutation. Distinguishes an op defined+register_fake'd inside the + compiled function (recoverable via graph break) from a genuinely + unregistered op (should hard-error with actionable guidance). + + Only detects the ``CustomOpDef.register_fake`` method form (a tracked + pending ``_abstract_fn`` store on ``tx.output.side_effects``); other forms + (e.g. an op with no ``CustomOpDef``, or a definition inside a HOP body whose + mutation lives in a subtracer) fall through to the hard error, preserving + pre-existing behavior.""" + if not isinstance(target, torch._ops.OpOverload): + return False + from torch._library.custom_ops import _maybe_get_opdef + + opdef = _maybe_get_opdef(target) + if opdef is None: + return False + side_effects = tx.output.side_effects + vt = side_effects.id_to_variable.get(id(opdef)) + if vt is None: + return False + return side_effects.has_pending_mutation_of_attr(vt, "_abstract_fn") + + +def get_fake_value( + node: torch.fx.Node, + tx: InstructionTranslatorBase, + allow_non_graph_fake: bool = False, +) -> Any: + _t0 = time.time_ns() + try: + return _get_fake_value_impl(node, tx, allow_non_graph_fake) + finally: + tx.output.bytecode_tracing_timings.get_fake_value_ns += time.time_ns() - _t0 + + +def _get_fake_value_impl( + node: torch.fx.Node, + tx: InstructionTranslatorBase, + allow_non_graph_fake: bool = False, +) -> Any: + """ + Run the computation represented by `node` using fake tensors and return the result. + + allow_non_graph_fake: whether to allow the return result to be: + 1. non-fake or 2. fake that is not created by this instance of Dynamo. + If `True`, you must be prepared to deal with such return values, ideally + by further wrapping them as this graph's fakes. + """ + from torch.utils._sympy.value_ranges import ValueRangeError + + from . import graph_break_hints + from .exc import unimplemented, Unsupported, UserError, UserErrorType + + op = node.op + + # FX Node should always return the same fake value + if "example_value" in node.meta and is_fake(node.meta["example_value"]): + return node.meta["example_value"] + + args, kwargs = get_fake_values_from_nodes( + tx, (node.args, node.kwargs), allow_non_graph_fake + ) + + if ( + torch._dynamo.config.use_graph_deduplication + or torch._dynamo.config.track_nodes_for_deduplication + ): + flat_args_kwargs = get_fake_values_from_nodes( + tx, _get_flat_args(node, {}), allow_non_graph_fake + ) + id_to_initial_version = { + id(arg): arg._version for arg in flat_args_kwargs if is_fake(arg) + } + else: + # pyrefly: ignore [implicit-any] + flat_args_kwargs = [] + # pyrefly: ignore [implicit-any] + id_to_initial_version = {} + + nnmodule = None + fake_mode = tx.fake_mode + if fake_mode is None: + raise AssertionError("fake_mode must not be None") + if op == "call_method" and len(args) > 0 and isinstance(args[0], torch.nn.Module): + # If the first argument is nn.Module, should copy to fake mode. + args = (deepcopy_to_fake_tensor(args[0], fake_mode),) + tuple(args[1:]) + + if op == "call_module": + nnmodule = tx.output.nn_modules[node.target] # type: ignore[index] + + if ( + is_lazy_module(nnmodule) + and inspect.getattr_static(nnmodule, "_initialize_hook", None) is not None + ): + # In the case of a lazy module, we want to run + # the pre-hooks which initialize it. + # Afterwards, lazy module deletes its pre-hooks + # to avoid treating it as lazy on subsequent recompile. + nnmodule._infer_parameters(nnmodule, args) + + # no matter it's lazy module or not, we should copy to fake mode. + nnmodule = deepcopy_to_fake_tensor(nnmodule, fake_mode) + + if node.name in ["interpolate", "is_integer", "wrapped_gradient"] or any( + isinstance(a, complex) for a in args + ): + # We need to specialize symfloats for now. Eventually we should do a tensorify pass in dynamo. + args = tuple( + ( + float(arg) + if isinstance(arg, torch.SymFloat) and arg.node.hint is not None + else arg + ) + for arg in args + ) + + try: + from torch._dynamo.eval_frame import _use_eager_on_nested_compile + + with fake_mode, enable_python_dispatcher(), _use_eager_on_nested_compile(): + ret_val = wrap_fake_exception( + lambda: run_node(tx.output, node, args, kwargs, nnmodule) + ) + except Unsupported: + raise + except RuntimeError as e: + cause: BaseException = e + if e.__cause__ is not None: + cause = e.__cause__ + + if isinstance( + cause, torch._subclasses.fake_tensor.DataDependentOutputException + ): + # capture_scalar_outputs only works for these ops right now + # see torch/_subclasses/fake_impls.py + if cause.func in ( + torch.ops.aten.item.default, + torch.ops.aten._local_scalar_dense.default, + ): + # does this actually get triggered? + hints = [ + "Enable tracing of data-dependent output operators with " + "`torch._dynamo.config.capture_scalar_outputs = True`", + ] + else: + hints = [ + "Consider wrapping the operator into a PyTorch-understood custom operator " + "(see https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html)", + ] + unimplemented( + gb_type="Data dependent operator", + context=str(cause.func), + explanation=f"Operator `{cause.func}` has a non-Tensor output " + "whose value is dependent on the data of Tensor inputs.", + hints=hints, + from_exc=cause, + ) + elif isinstance( + cause, torch._subclasses.fake_tensor.DynamicOutputShapeException + ): + if not torch._dynamo.config.capture_dynamic_output_shape_ops: + unimplemented( + gb_type="Dynamic shape operator", + context=str(cause.func), + explanation=f"Operator `{cause.func}`'s output shape depends on input Tensor data.", + hints=[ + "Enable tracing of dynamic shape operators with " + "`torch._dynamo.config.capture_dynamic_output_shape_ops = True`", + ], + from_exc=cause, + ) + else: + unimplemented( + gb_type="Dynamic shape operator (no meta kernel)", + context=str(cause.func), + explanation=f"Operator `{cause.func}` does not have a meta kernel that supports dynamic output shapes", + hints=[ + "Please report an issue to PyTorch", + ], + from_exc=cause, + ) + elif isinstance( + cause, torch._subclasses.fake_tensor.UnsupportedOperatorException + ): + op = cause.func # type: ignore[assignment] + import_suggestion = "" + if isinstance(op, torch._ops.OpOverload): + maybe_pystub = torch._C._dispatch_pystub( + op._schema.name, op._schema.overload_name + ) + if maybe_pystub is not None: + module, ctx = maybe_pystub + import_suggestion = ( + f"It's possible that the support was implemented in " + f"module `{module}` and you may need to `import {module}`" + f"({ctx}), otherwise " + ) + unimplemented( + gb_type="Operator does not support running with fake tensors", + context=f"unsupported operator: {cause.func}", + explanation="", + hints=[ + f"{import_suggestion}see " + "https://docs.google.com/document/d/1GgvOe7C8_NVOMLOCwDaYV1mXXyHMXY7ExoewHqooxrs/edit#heading=h.64r4npvq0w0" + " for how to fix", + ], + from_exc=cause, + ) + elif isinstance( + cause, torch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode + ): + raise UserError( + UserErrorType.CONSTRAINT_VIOLATION, + str(cause), + case_name="constrain_as_size_example", + ) from cause + elif isinstance( + cause, torch._subclasses.fake_tensor.FakeTensorDeviceMismatchError + ): + _wrap_graph_break_with_torch_runtime_err( + lambda: unimplemented( + gb_type="Tensor device mismatch", + context=f"{op} {node.target}", + explanation=str(cause), + hints=["Move inputs, parameters, and buffers to the same device."], + from_exc=cause, + ) + ) + raise AssertionError("should not be reachable") from None + elif isinstance(cause, ValueRangeError): + raise UserError(UserErrorType.CONSTRAINT_VIOLATION, e.args[0]) from e + elif isinstance(cause, TypeError) and "argument" in str(cause): + unimplemented( + gb_type="TypeError when making fake tensor call", + context=f"TypeError {node.target}: {cause}", + explanation="", + hints=[*graph_break_hints.USER_ERROR], + from_exc=cause, + ) + elif "no fake impl registered" in str(cause) and _custom_op_fake_impl_pending( + tx, node.target + ): + # A custom op was defined and register_fake'd inside the compiled + # function, then called. Under nested graph breaks Dynamo traces + # into the inlined op definition, so register_fake's mutation of + # _abstract_fn is recorded as a pending side effect rather than run + # eagerly; it is not yet applied to the real op when the op is called + # here, so its fake kernel raises "no fake impl registered". (Without + # nested graph breaks the definition graph-breaks and the op is fully + # registered before the call, so this path is not hit.) Graph break: + # the definition (and register_fake) run eagerly and the op call + # itself falls back to eager -- it is not captured into the resumed + # graph. Unlike the generic RuntimeError below this is recoverable, + # so do NOT wrap it as a hard TorchRuntimeError. + # NB: gated on a pending _abstract_fn mutation so a genuinely + # unregistered op still hard-errors below with actionable guidance. + unimplemented( + gb_type="Custom op missing fake impl during tracing", + context=f"{node.target}", + explanation="A custom operator was defined and register_fake'd " + "inside the compiled function, then called before the " + "register_fake side effect was applied.", + hints=[*graph_break_hints.SUPPORTABLE], + from_exc=cause, + ) + msg = get_concrete_sizes_from_symints(str(e), fake_mode) + from .exc import ( + FakeTensorObservedException, + ObservedException, + raise_observed_exception, + ) + + if not node.users: + tx.output.graph.erase_node(node) + try: + raise_observed_exception(RuntimeError, tx, args=[msg]) + except ObservedException as e: + raise FakeTensorObservedException(msg, real_stack=e.real_stack) from None + + if not allow_non_graph_fake: + _ = pytree.tree_map_only( + torch.Tensor, + functools.partial(ensure_graph_fake, tx=tx), + ret_val, # type: ignore[unbound-name] + ) + + if ( + torch._dynamo.config.use_graph_deduplication + or torch._dynamo.config.track_nodes_for_deduplication + ): + tx.output.region_tracker.track_node_mutations( + node, + flat_args_kwargs, + id_to_initial_version, + ) + + return ret_val + + +_current_node = threading.local() + + +def get_current_node() -> torch.fx.Node | None: + return getattr(_current_node, "value", None) + + +@contextmanager +def set_current_node(node: torch.fx.Node) -> Generator[None, None, None]: + old = get_current_node() + _current_node.value = node + try: + yield + finally: + _current_node.value = old + + +def run_node( + tracer: Any, node: torch.fx.Node, args: Any, kwargs: Any, nnmodule: Any +) -> Any: + """ + Runs a given node, with the given args and kwargs. + + Behavior is dictated by a node's op. + + run_node is useful for extracting real values out of nodes. + See get_real_value for more info on common usage. + + Note: The tracer arg is only used for 'get_attr' ops + Note: The nnmodule arg is only used for 'call_module' ops + + Nodes that are not call_function, call_method, call_module, or get_attr will + raise an AssertionError. + """ + op = node.op + + with set_current_node(node): + + def make_error_message(e: Any) -> str: + return ( + f"Dynamo failed to run FX node with fake tensors: {op} {node.target}(*{args}, **{kwargs}): got " + + repr(e) + ) + + from .exc import Unsupported + + try: + if op == "call_function": + return node.target(*args, **kwargs) # type: ignore[operator] + elif op == "call_method": + if not hasattr(args[0], node.target): # type: ignore[arg-type] + from . import graph_break_hints + from .exc import unimplemented + + unimplemented( + gb_type="Missing attribute when running call_method node", + context="", + explanation=make_error_message("attribute not defined"), + hints=[*graph_break_hints.USER_ERROR], + ) + return getattr(args[0], node.target)(*args[1:], **kwargs) # type: ignore[arg-type] + elif op == "call_module": + if nnmodule is None: + raise AssertionError("nnmodule must not be None for call_module op") + return nnmodule(*args, **kwargs) + elif op == "get_attr": + return tracer.output_graph.get_submodule(node.target) + elif op == "placeholder": + if "example_value" not in node.meta: + raise AssertionError( + "Expected 'example_value' in node.meta for placeholder op" + ) + return node.meta["example_value"] + + except (NotImplementedError, UnsupportedFakeTensorException) as e: + # NB: mimic how wrap_fake_exception does it + from . import graph_break_hints + from .exc import unimplemented + + hints = [*graph_break_hints.USER_ERROR] + if isinstance(e, NotImplementedError): + hints += [ + "If the op is a custom op, did you implement a fake tensor implementation? " + "(e.g. with `@my_custom_op.register_fake`)", + "If the op is a PyTorch op, please file an issue to PyTorch.", + ] + + unimplemented( + gb_type="NotImplementedError/UnsupportedFakeTensorException when running FX node", + context="", + explanation=make_error_message(e), + hints=hints, + from_exc=e, + ) + except Unsupported: + raise + except IndexError: + # Re-raise IndexError from tensor dim validation (e.g. canonicalize_dim, + # maybe_wrap_dim) so it reaches the user as IndexError, not RuntimeError. + # This is intentionally broad: an internal Dynamo indexing bug would also + # propagate this way, but such bugs are rare and the traceback is preserved. + raise + except Exception as e: + raise RuntimeError(make_error_message(e)).with_traceback( + e.__traceback__ + ) from e + + raise AssertionError(op) + + +def get_real_value(node: torch.fx.Node, tracer: Any) -> Any: + """ + Run the actual computation represented by `node` and return the result. + This will execute any dependent nodes in the graph as well. + """ + from . import graph_break_hints + from .exc import unimplemented + + cache = tracer.real_value_cache + if node in cache: + return cache[node] + + op = node.op + args, kwargs = torch.fx.node.map_arg( # type: ignore[misc] + (node.args, node.kwargs), + lambda n: get_real_value(n, tracer), + ) + + if op == "placeholder" and "grapharg" in node.meta: + return node.meta["grapharg"].example + + if op == "call_module": + nn_module = tracer.output_graph.nn_modules[node.target] + if not is_lazy_module(nn_module): + nn_module = copy.deepcopy(nn_module) + else: + # In the case of a lazy module, we want to run + # the pre-hooks which initialize it + nn_module(*args, **kwargs) + else: + nn_module = None + + try: + real_value = run_node(tracer, node, args, kwargs, nn_module) + cache[node] = real_value + except RuntimeError as e: + exn = e # to make typing happy for the lambda + _wrap_graph_break_with_torch_runtime_err( + lambda: unimplemented( + gb_type="RuntimeError when trying to get real value from fx.Node", + context="", + explanation="", + hints=[*graph_break_hints.USER_ERROR], + from_exc=exn, + ) + ) + raise AssertionError("should not be reachable") from None + return real_value + + +def assert_no_fake_params_or_buffers(gm: torch.nn.Module) -> None: + from torch._subclasses.fake_tensor import FakeTensorConfig, is_fake + + def stack_or_hint(t: Any) -> str: + if FakeTensorConfig.debug: + import traceback + + return f"FAKE TENSOR CREATION TRACEBACK: \n {traceback.format_list(t._debug_trace)}" + else: + return "Enable TORCH_FAKE_TENSOR_DEBUG=1 to get creation stack traces on fake tensors." + + for name, buffer in gm.named_buffers(): + if is_fake(buffer): + raise AssertionError( + f"Unexpected fake buffer {name} {stack_or_hint(buffer)}" + ) + for name, param in gm.named_parameters(): + if is_fake(param): + raise AssertionError(f"Unexpected fake param {name} {stack_or_hint(param)}") + + +def fqn(obj: Any) -> str: + """ + Returns the fully qualified name of the object. + """ + return f"{obj.__module__}.{obj.__qualname__}" + + +def ifdynstaticdefault(count1: Any, count2: Any) -> Any: + if torch._dynamo.config.assume_static_by_default: + return count1 + else: + return count2 + + +def import_submodule(mod: types.ModuleType) -> None: + """ + Ensure all the files in a given submodule are imported + """ + for filename in sorted(os.listdir(os.path.dirname(cast(str, mod.__file__)))): + if filename.endswith(".py") and filename[0] != "_": + importlib.import_module(f"{mod.__name__}.{filename[:-3]}") + + +def object_has_getattribute(value: object) -> bool: + return class_has_getattribute(type(value)) + + +def object_setattr_ignore_descriptor(obj: Any, name: str, value: Any) -> None: + # Mirror the instance-dict update path in _PyObject_GenericSetAttrWithDict: + # https://github.com/python/cpython/blob/v3.13.0/Objects/object.c#L1679-L1741 + try: + d = object.__getattribute__(obj, "__dict__") + except AttributeError: + if not isinstance(obj, threading.local): + raise + # threading.local stores attributes in a per-thread C-backed dict that + # object.__getattribute__ cannot see. CPython passes that dict directly + # to _PyObject_GenericSetAttrWithDict: + # https://github.com/python/cpython/blob/v3.13.0/Modules/_threadmodule.c#L1707-L1730 + d = threading.local.__getattribute__(obj, "__dict__") + d[name] = value + + +def object_delattr_ignore_descriptor(obj: Any, name: str) -> None: + # Same path as object_setattr_ignore_descriptor with a NULL value. + # https://github.com/python/cpython/blob/v3.13.0/Objects/object.c#L1679-L1741 + try: + d = object.__getattribute__(obj, "__dict__") + except AttributeError: + if not isinstance(obj, threading.local): + raise + d = threading.local.__getattribute__(obj, "__dict__") + del d[name] + + +def class_has_getattribute(cls: type) -> bool: + try: + if isinstance( + inspect.getattr_static(cls, "__getattribute__"), + types.FunctionType, + ): + return True + except AttributeError: + pass + return False + + +def get_custom_getattr( + value: Any, ignore_nn_module_getattr: bool = False +) -> Any | None: + try: + getattr_fn = inspect.getattr_static(type(value), "__getattr__") + except AttributeError: + getattr_fn = None + if ignore_nn_module_getattr and getattr_fn is torch.nn.Module.__getattr__: + # ignore this case of getattr + getattr_fn = None + return getattr_fn + + +class TensorStaticReason(enum.Enum): + PARAMETER = 2 + NOT_TENSOR = 4 + NN_MODULE_PROPERTY = 5 + + +def tensor_static_reason_to_message(reason: TensorStaticReason) -> str: + if reason == TensorStaticReason.PARAMETER: + return "mark_dynamic on parameter, parameters are always static today." + if reason == TensorStaticReason.NOT_TENSOR: + return "mark_dynamic on a non tensor, how did this happen?" + if reason == TensorStaticReason.NN_MODULE_PROPERTY: + return "tensor is static because it is nn module associated." + raise AssertionError(f"Illegal reason {reason}") + + +def tensor_always_has_static_shape( + tensor: torch.Tensor | Any, + is_tensor: bool, + tensor_source: Source, +) -> tuple[bool, TensorStaticReason | None]: + """ + Given a tensor, source, and is_tensor flag, determine if a shape should be static. + + Args: + tensor - the real tensor to evaluate, parameters force a static shape. + is_tensor - internal dynamo check, essentially "is_tensor": target_cls is TensorVariable, + tensors not in a TensorVariable for whatever reason are forced static. + + Returns a tuple, where the first element is the bool of whether or not this tensor should have a static shape. + The second element is a TensorStaticReason, useful for passing to tensor_static_reason_to_message if needed. + """ + from .source import is_from_unspecialized_param_buffer_source + + if ( + tensor_source.guard_source.is_specialized_nn_module() + or tensor_source.guard_source.is_unspecialized_builtin_nn_module() + ) and config.force_nn_module_property_static_shapes: + return True, TensorStaticReason.NN_MODULE_PROPERTY + + if ( + type(tensor) is torch.nn.Parameter + or is_from_unspecialized_param_buffer_source(tensor_source) + ) and config.force_parameter_static_shapes: + return True, TensorStaticReason.PARAMETER + if not is_tensor: + return True, TensorStaticReason.NOT_TENSOR + return False, None + + +def lazy_format_graph_tabular(fn_name: str, gm: torch.fx.GraphModule) -> Any: + def inner() -> str: + try: + from tabulate import tabulate # TODO: Check that this is installed + except ImportError: + return ( + "Tabulate module missing, please install tabulate to log the graph in tabular format, logging code instead:\n" + + str(lazy_format_graph_code(fn_name, gm)) + ) + + node_specs = [ + [n.op, n.name, n.target, n.args, n.kwargs] for n in gm.graph.nodes + ] + graph_str = tabulate( + node_specs, headers=["opcode", "name", "target", "args", "kwargs"] + ) + return _format_graph_code(fn_name, gm.forward.__code__.co_filename, graph_str) + + return LazyString(inner) + + +def format_bytecode( + prefix: str, name: str, filename: str, line_no: int, code: Any +) -> str: + return f"{prefix} {name} {filename} line {line_no} \n{dis.Bytecode(code).dis()}\n" + + +forward_hook_names = [ + "_forward_pre_hooks", + "_forward_pre_hooks_with_kwargs", + "_forward_hooks_with_kwargs", + "_forward_hooks", +] +backward_hook_names = ["_backward_pre_hooks", "_backward_hooks"] +state_dict_hook_names = [ + "_state_dict_pre_hooks", + "_state_dict_hooks", + "_load_state_dict_pre_hooks", + "_load_state_dict_post_hooks", +] +all_hook_names = forward_hook_names + backward_hook_names + state_dict_hook_names + + +def nn_module_has_global_hooks() -> bool: + # This is limited to backward hooks for now because NNModuleVariable + # supports fwd hooks underneath. + return bool( + len(torch.nn.modules.module._global_backward_hooks) + or len(torch.nn.modules.module._global_backward_pre_hooks) + ) + + +def nn_module_get_all_hooks( + mod: torch.nn.Module, + check_forward_hooks: bool = False, + check_backward_hooks: bool = False, + check_state_dict_hooks: bool = False, +) -> list[Any]: + """ + Sometimes its useful to differentiate between types of hooks such as forward/backward/pre + hooks executed during module.__call__, and state_dict hooks which are executed separately. + """ + hook_dicts_to_check = [] + check_all_hooks = ( + not check_forward_hooks + and not check_backward_hooks + and not check_state_dict_hooks + ) + if check_forward_hooks or check_all_hooks: + hook_dicts_to_check.extend(forward_hook_names) + if check_backward_hooks or check_all_hooks: + hook_dicts_to_check.extend(backward_hook_names) + if check_state_dict_hooks: + hook_dicts_to_check.extend(state_dict_hook_names) + + all_hooks = [] + for hook_dict_name in hook_dicts_to_check: + hooks = getattr(mod, hook_dict_name, []) + for hook_name in hooks: + hook = hooks[hook_name] + + all_hooks.append(hook) + return all_hooks + + +def nnmodule_has_hooks( + mod: torch.nn.Module, + check_forward_hooks: bool = False, + check_backward_hooks: bool = False, + check_state_dict_hooks: bool = False, +) -> bool: + """ + Helper function to check if a module has any hooks attached to it. + """ + hooks = nn_module_get_all_hooks( + mod, + check_forward_hooks=check_forward_hooks, + check_backward_hooks=check_backward_hooks, + check_state_dict_hooks=check_state_dict_hooks, + ) + return bool(hooks) + + +def to_numpy_helper(value: Any) -> Any: + """Convert tensor and tnp.ndarray to numpy.ndarray.""" + if is_fake(value): + return value + if isinstance(value, tnp.ndarray): + return to_numpy_helper(value.tensor) + elif isinstance(value, torch.Tensor): + return value.numpy(force=True) + elif isinstance(value, (tuple, list)): + return type(value)(to_numpy_helper(obj) for obj in value) + else: + return value + + +def numpy_to_tensor(value: Any) -> Any: + """Convert tnp.ndarray to tensor, leave other types intact. If a list/tuple, loop through it to convert.""" + if np is None: + raise AssertionError("numpy must be available (np is None)") + if isinstance(value, np.ndarray): + return torch.as_tensor(value) + if isinstance(value, tnp.ndarray): + return value.tensor + elif isinstance(value, (tuple, list)): + return type(value)(numpy_to_tensor(obj) for obj in value) + else: + return value + + +class numpy_to_tensor_wrapper(Generic[_P, R]): + def __init__(self, f: Callable[_P, R]) -> None: + self.f = f + self.__name__ = "wrapped_" + self.f.__name__ + + def __repr__(self) -> str: + return f">" + + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> Any: + out = self.f(*args, **kwargs) + return numpy_to_tensor(out) + + +def numpy_attr_wrapper(obj: Any, name: str) -> Any: + if isinstance(obj, tnp.ndarray): + out = getattr(obj, name) + return numpy_to_tensor(out) + elif isinstance(obj, torch.Tensor): + out = getattr(tnp.ndarray(obj), name) + return numpy_to_tensor(out) + + +class numpy_method_wrapper: + """Convert obj from torch.Tensor to tnp.ndarray and call method. Then convert result back to torch.Tensor.""" + + def __init__(self, method: str) -> None: + self.method = method + self.__name__ = "wrapped_" + self.method + + def __repr__(self) -> str: + return f">" + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + obj = args[0] + if isinstance(obj, torch.Tensor): + obj = tnp.ndarray(obj) + method_callable = getattr(obj, self.method) + out = method_callable(*args[1:], **kwargs) + return numpy_to_tensor(out) + + +class numpy_operator_wrapper(Generic[_P, R]): + """Implements dunder methods for tnp.ndarray via functions from the operator library""" + + def __init__(self, op: Callable[..., Any]) -> None: + self.op = op + self.__name__ = f"wrapped_{op.__name__}" + + def __repr__(self) -> str: + return f">" + + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> Any: + if kwargs: + raise AssertionError(f"Expected no kwargs, got {kwargs}") + + # pyrefly: ignore [bad-assignment] + args = ( + tnp.ndarray(arg) if isinstance(arg, torch.Tensor) else arg for arg in args + ) + out = self.op(*args) + return numpy_to_tensor(out) + + +@functools.lru_cache(maxsize=1) +def _torch_numpy_callable_id_map() -> dict[int, tuple[Callable[..., Any], Any, str]]: + result: dict[int, tuple[Callable[..., Any], Any, str]] = {} + for np_mod, tnp_mod in NP_TO_TNP_MODULE.items(): + module = np_mod.__name__ + for name, tnp_callable in tnp_mod.__dict__.items(): + if not callable(tnp_callable): + continue + + np_callable = getattr(np_mod, name, None) + if not callable(np_callable): + continue + + result[id(tnp_callable)] = ( + tnp_callable, + np_callable, + f"{module}.{name}", + ) + return result + + +@functools.lru_cache(maxsize=1024) +def _torch_numpy_callable_cache_key_by_id( + obj_id: int, +) -> tuple[Callable[..., Any], str] | None: + tnp_callable, np_callable, cache_key = _torch_numpy_callable_id_map()[obj_id] + + module, _, name = cache_key.rpartition(".") + # Random functions depend on global RNG state, so they are not safe to + # identify only by their canonical NumPy path in an AOTAutograd cache key. + if module == "numpy.random" or module.startswith("numpy.random."): + return None + + try: + if np_callable is not getattr(importlib.import_module(module), name): + return None + except (AttributeError, ImportError): + return None + + return (tnp_callable, cache_key) + + +def _torch_numpy_callable_cache_key(obj: Callable[..., Any]) -> str | None: + obj_id = id(obj) + # Arbitrary Python callables can be short-lived, so do not cache misses by + # id; a later object may reuse the same id. + if obj_id not in _torch_numpy_callable_id_map(): + return None + + entry = _torch_numpy_callable_cache_key_by_id(obj_id) + if entry is None: + return None + + tnp_callable, cache_key = entry + if obj is not tnp_callable: + return None + + return cache_key + + +def is_safe_numpy_wrapper(obj: object) -> bool: + return numpy_wrapper_cache_key(obj) is not None + + +def numpy_wrapper_cache_key(obj: Any) -> tuple[str, str] | None: + if type(obj) is not numpy_to_tensor_wrapper: + return None + + key = _torch_numpy_callable_cache_key(obj.f) + if key is None: + return None + + return (type(obj).__qualname__, key) + + +def defake(x: Any) -> Any: + from torch._subclasses.fake_tensor import is_fake_tensor + + if not is_fake_tensor(x): + return x + size: torch._prims_common.ShapeType + stride: torch._prims_common.StrideType + if x._has_symbolic_sizes_strides: + # optimization_hint is appropriate here because defake only needs a + # plausible concrete shape to allocate a real tensor; it does not need + # to install guards. For unbacked symbols the heuristic fallback is fine. + size = [ + torch.fx.experimental.symbolic_shapes.optimization_hint(s) for s in x.size() + ] + stride = [ + torch.fx.experimental.symbolic_shapes.optimization_hint(s) + for s in x.stride() + ] + else: + size = x.size() + stride = x.stride() + y = torch.empty_strided( + size, + stride, + dtype=x.dtype, + device=x.device, + requires_grad=x.requires_grad, + ) + y.zero_() + return y + + +def _disable_side_effect_safety_checks_for_current_subtracer( + fn: Callable[_P, R], *args: _P.args, **kwargs: _P.kwargs +) -> R: + return fn(*args, **kwargs) + + +def is_utils_checkpoint(obj: object) -> bool: + # Lazy import to avoid circular dependencies + import torch.utils.checkpoint + + return obj is torch.utils.checkpoint.checkpoint + + +def is_invoke_subgraph(obj: object) -> bool: + from torch._higher_order_ops.invoke_subgraph import invoke_subgraph_placeholder + + return obj is invoke_subgraph_placeholder + + +def build_invoke_subgraph_variable(**options: Any) -> Any: + from .variables.higher_order_ops import TorchHigherOrderOperatorVariable + + return TorchHigherOrderOperatorVariable.make( + torch._higher_order_ops.invoke_subgraph, + **options, + ) + + +def build_checkpoint_variable(**options: Any) -> Any: + import torch._higher_order_ops.wrap as higher_order_ops + + from .variables.higher_order_ops import TorchHigherOrderOperatorVariable + + # TODO - This is a temporary situation where we have two versions of + # checkpointing implementation. We will converge on one and remove the other. + activation_checkpoint_op: torch._ops.HigherOrderOperator = ( + higher_order_ops.tag_activation_checkpoint + ) + if torch._functorch.config.functionalize_rng_ops: + activation_checkpoint_op = higher_order_ops.wrap_activation_checkpoint + + return TorchHigherOrderOperatorVariable.make( + activation_checkpoint_op, + **options, + ) + + +def is_compile_supported(device_type: DeviceLikeType) -> Any: + from .eval_frame import is_dynamo_supported + + type = torch.device(device_type).type + compile_supported = is_dynamo_supported() + if type == "cpu": + pass + elif type in ["cuda", "xpu", "mtia"] and compile_supported: + compile_supported = has_triton() + else: + compile_supported = False + return compile_supported + + +# The following 3.11 source code functions are adapted from +# https://github.com/python/cpython/blob/v3.11.4/Lib/traceback.py +# in order to output source code corresponding to bytecode in 3.11+. +# We need our own versions since we want to support multiline expressions. +def _fix_offset(str: str, offset: int) -> int: + """ + Convert byte offset `offset` of `str` into character offset. + Byte offset is used for 3.11+ instruction column data. + Takes things like unicode characters into consideration. + + Unchanged from CPython implementation. + """ + as_utf8 = str.encode("utf-8") + return len(as_utf8[:offset].decode("utf-8", errors="replace")) + + +@dataclasses.dataclass +class _Anchors: + # inclusive + left_end_lineno: int + left_end_offset: int + right_start_lineno: int + # exclusive + right_start_offset: int + + +def _extract_anchors_from_expr(segment: str) -> _Anchors | None: + """ + Given source code `segment` corresponding to a bytecode + instruction, determine: + - for binary ops, the location of the binary op + - for indexing, the location of the brackets. + `segment` is expected to be a valid Python expression + """ + if sys.version_info < (3, 11): + raise AssertionError(f"Python >= 3.11 required, got {sys.version_info}") + + import ast + + tree: Any | None = None + try: + # Without brackets, `segment` is parsed as a statement. + # We expect an expression, so wrap `segment` in + # brackets to handle multi-line expressions. + tree = ast.parse("(\n" + segment + "\n)") + except SyntaxError: + return None + if tree is None: + raise AssertionError("ast.parse returned None unexpectedly") + + if len(tree.body) != 1: + return None + + lines = segment.split("\n") + + # get character index given byte offset + def normalize(lineno: int, offset: int) -> int: + return _fix_offset(lines[lineno], offset) + + # Gets the next valid character index in `lines`, if + # the current location is not valid. Handles empty lines. + def next_valid_char(lineno: int, col: int) -> tuple[int, int]: + while lineno < len(lines) and col >= len(lines[lineno]): + col = 0 + lineno += 1 + if lineno >= len(lines): + raise AssertionError( + f"lineno {lineno} out of range (len(lines)={len(lines)})" + ) + if col >= len(lines[lineno]): + raise AssertionError( + f"col {col} out of range (len(lines[{lineno}])={len(lines[lineno])})" + ) + return lineno, col + + # Get the next valid character index in `lines`. + def increment(lineno: int, col: int) -> tuple[int, int]: + col += 1 + lineno, col = next_valid_char(lineno, col) + if lineno >= len(lines): + raise AssertionError( + f"lineno {lineno} out of range (len(lines)={len(lines)})" + ) + if col >= len(lines[lineno]): + raise AssertionError( + f"col {col} out of range (len(lines[{lineno}])={len(lines[lineno])})" + ) + return lineno, col + + # Get the next valid character at least on the next line + def nextline(lineno: int, col: int) -> tuple[int, int]: + col = 0 + lineno += 1 + lineno, col = next_valid_char(lineno, col) + if lineno >= len(lines): + raise AssertionError( + f"lineno {lineno} out of range (len(lines)={len(lines)})" + ) + if col >= len(lines[lineno]): + raise AssertionError( + f"col {col} out of range (len(lines[{lineno}])={len(lines[lineno])})" + ) + return lineno, col + + statement = tree.body[0] + if isinstance(statement, ast.Expr): + expr = statement.value + if isinstance(expr, ast.BinOp): + # ast gives locations for BinOp subexpressions, e.g. + # ( left_expr ) + ( right_expr ) + # left^^^^^ right^^^^^ + # -2 since end_lineno is 1-indexed and because we added an extra + # bracket to `segment` when calling ast.parse + cur_lineno = cast(int, expr.left.end_lineno) - 2 + if expr.left.end_col_offset is None: + raise AssertionError("expr.left.end_col_offset must not be None") + cur_col = normalize(cur_lineno, expr.left.end_col_offset) + cur_lineno, cur_col = next_valid_char(cur_lineno, cur_col) + + # Heuristic to find the operator character. + # The original CPython implementation did not look for ), \, or #, + # leading to incorrect anchor location, e.g. + # (x) + (y) + # ~~^~~~~~~ + while (ch := lines[cur_lineno][cur_col]).isspace() or ch in ")\\#": + if ch in "\\#": + cur_lineno, cur_col = nextline(cur_lineno, cur_col) + else: + cur_lineno, cur_col = increment(cur_lineno, cur_col) + + # binary op is 1 or 2 characters long, on the same line + right_col = cur_col + 1 + if ( + right_col < len(lines[cur_lineno]) + and not (ch := lines[cur_lineno][right_col]).isspace() + and ch not in "\\#" + ): + right_col += 1 + # right_col can be invalid since it is exclusive + + return _Anchors(cur_lineno, cur_col, cur_lineno, right_col) + elif isinstance(expr, ast.Subscript): + # ast gives locations for value and slice subexpressions, e.g. + # ( value_expr ) [ slice_expr ] + # value^^^^^ slice^^^^^ + # subscript^^^^^^^^^^^^^^^^^^^^ + # find left bracket (first '[' after value) + left_lineno = cast(int, expr.value.end_lineno) - 2 + if expr.value.end_col_offset is None: + raise AssertionError("expr.value.end_col_offset must not be None") + left_col = normalize(left_lineno, expr.value.end_col_offset) + left_lineno, left_col = next_valid_char(left_lineno, left_col) + while lines[left_lineno][left_col] != "[": + left_lineno, left_col = increment(left_lineno, left_col) + # find right bracket (final character of expression) + right_lineno = cast(int, expr.end_lineno) - 2 + if expr.end_col_offset is None: + raise AssertionError("expr.end_col_offset must not be None") + right_col = normalize(right_lineno, expr.end_col_offset) + return _Anchors(left_lineno, left_col, right_lineno, right_col) + elif isinstance(expr, ast.Call): + # ( func_expr ) (args, kwargs) + # func^^^^^ + # call^^^^^^^^^^^^^^^^^^^^^^^^ + # find left bracket (first '(' after func) + left_lineno = cast(int, expr.func.end_lineno) - 2 + if expr.func.end_col_offset is None: + raise AssertionError("expr.func.end_col_offset must not be None") + left_col = normalize(left_lineno, expr.func.end_col_offset) + left_lineno, left_col = next_valid_char(left_lineno, left_col) + while lines[left_lineno][left_col] != "(": + left_lineno, left_col = increment(left_lineno, left_col) + # find right bracket (final character of expression) + right_lineno = cast(int, expr.end_lineno) - 2 + if expr.end_col_offset is None: + raise AssertionError("expr.end_col_offset must not be None") + right_col = normalize(right_lineno, expr.end_col_offset) + return _Anchors(left_lineno, left_col, right_lineno, right_col) + + return None + + +def format_source_range( + filename: str, + lineno: int | None, + end_lineno: int | None = None, + col_offset: int | None = None, + end_col_offset: int | None = None, + *, + function_name: str = "", +) -> str: + if lineno is None: + return "" + + last_lineno = end_lineno if end_lineno is not None else lineno + source_lines = [ + linecache.getline(filename, current_lineno).rstrip() + for current_lineno in range(lineno, last_lineno + 1) + ] + if not any(source_lines): + return "" + + if ( + sys.version_info >= (3, 13) + and end_lineno is not None + and end_lineno != lineno + and col_offset is not None + and end_col_offset is not None + ): + # Keep single-line ranges on Dynamo's manual path. The stdlib traceback + # formatter is useful for multiline spans on 3.13+, but for single-line + # spans it can emit version-specific mixed `~`/`^` markers or omit the + # marker line entirely for comments. + frame_summary = traceback.FrameSummary( + filename, + lineno, + function_name, + end_lineno=end_lineno, + colno=col_offset, + end_colno=end_col_offset, + ) + result = traceback.format_list([frame_summary])[0] + result = "\n".join(result.splitlines()[1:]) + source_lines_dedent = textwrap.dedent("\n".join(source_lines)).splitlines() + if not source_lines_dedent: + return result + indent_len = len(source_lines[0]) - len(source_lines_dedent[0]) + indent = source_lines[0][:indent_len] + return textwrap.indent(textwrap.dedent(result), indent) + + first_line = source_lines[0] + if end_lineno is None or col_offset is None or end_col_offset is None: + return first_line + + start_offset = _fix_offset(first_line, col_offset) + segment = "" + markers: list[str] = [] + + if end_lineno == lineno: + end_offset = _fix_offset(first_line, end_col_offset) + segment = first_line[start_offset:end_offset] + markers.append(" " * start_offset + "~" * (end_offset - start_offset)) + else: + segment = first_line[start_offset:] + "\n" + markers.append(" " * start_offset + "~" * (len(first_line) - start_offset)) + last_line = source_lines[-1] + end_offset = _fix_offset(last_line, end_col_offset) + for line in source_lines[1:-1]: + segment += line + "\n" + num_spaces = len(line) - len(line.lstrip()) + markers.append(" " * num_spaces + "~" * (len(line) - num_spaces)) + segment += last_line[:end_offset] + num_spaces = len(last_line) - len(last_line.lstrip()) + markers.append(" " * num_spaces + "~" * (end_offset - num_spaces)) + + anchors: _Anchors | None = None + try: + anchors = _extract_anchors_from_expr(segment) + except AssertionError: + pass + + if anchors is None: + markers = [marker.replace("~", "^") for marker in markers] + else: + mutable_markers: list[list[str]] = [list(marker) for marker in markers] + + if anchors.left_end_lineno == 0: + anchors.left_end_offset += start_offset + if anchors.right_start_lineno == 0: + anchors.right_start_offset += start_offset + + for marker_lineno in range(len(markers)): + for col in range(len(mutable_markers[marker_lineno])): + if marker_lineno < anchors.left_end_lineno: + continue + if ( + marker_lineno == anchors.left_end_lineno + and col < anchors.left_end_offset + ): + continue + if ( + marker_lineno == anchors.right_start_lineno + and col >= anchors.right_start_offset + ): + continue + if marker_lineno > anchors.right_start_lineno: + continue + if mutable_markers[marker_lineno][col] == "~": + mutable_markers[marker_lineno][col] = "^" + + markers = ["".join(marker) for marker in mutable_markers] + + result = "" + for line, marker in zip(source_lines, markers): + result += line + "\n" + result += marker + "\n" + return result + + +def get_instruction_source_311(code: types.CodeType, inst: Instruction) -> str: + """ + Python 3.11+ only. Returns lines of source code (from code object `code`) + corresponding to `inst`'s location data, and underlines relevant code to `inst`. + + Example: CALL on `g`: + f(g( + ^^ + h(x))) + ^^^^^ + + We need our own implementation in < 3.13 since `format_frame_summary` in + Python's `traceback` module doesn't handle multi-line expressions + (and their anchor extraction code is not completely correct). + """ + if not hasattr(inst, "positions"): + raise AssertionError("inst must have a 'positions' attribute") + if inst.positions is None: + raise AssertionError("inst.positions must not be None") + return format_source_range( + code.co_filename, + inst.positions.lineno, + inst.positions.end_lineno, + inst.positions.col_offset, + inst.positions.end_col_offset, + function_name=code.co_name, + ) + + +# The two flavors of mark_static_address: "guarded" recompiles when the data_ptr +# changes, "unguarded" re-records cudagraphs instead. Set in decorators.py. +StaticInputType = Literal["guarded", "unguarded"] + + +def get_static_address_type(t: Any) -> StaticInputType | None: + if isinstance(t, torch.Tensor): + return getattr(t, "_dynamo_static_input_type", None) + + return None + + +def is_rng_state_getter_or_setter(value: object) -> bool: + getters = ( + # The following two functions are not identical, so don't remove anyone! + torch._C.Generator.get_state, + torch.default_generator.get_state, + torch.get_rng_state, + torch.cuda.get_rng_state, + ) + setters = ( + torch._C.Generator.set_state, + torch.default_generator.set_state, + torch.set_rng_state, + torch.cuda.set_rng_state, + ) + return value in (*setters, *getters) + + +def is_tensor_base_attr_getter(value: object) -> bool: + return ( + isinstance(value, types.MethodWrapperType) + and value.__name__ == "__get__" + and hasattr(value.__self__, "__objclass__") + and value.__self__.__objclass__ is torch._C._TensorBase # type: ignore[attr-defined] + ) + + +def is_tensor_getset_descriptor(name: str) -> bool: + try: + attr = inspect.getattr_static(torch.Tensor, name) + return type(attr) is types.GetSetDescriptorType + except AttributeError: + return False + + +def is_torch_class(cls: type) -> bool: + """Check if cls is defined in torch or a torch submodule. + + Torch-internal C-level descriptors (e.g. torch.Tensor.unsqueeze_) need + to go through VariableTracker.build / trace_rules so they get the right + VT (TorchInGraphFunctionVariable), which has guards like + inplace-view-on-input-tensor detection. This helper identifies classes + whose descriptors should take that path instead of descriptor VTs. + """ + module = getattr(cls, "__module__", None) + return module is not None and (module == "torch" or module.startswith("torch.")) + + +def is_torch_function_object(value: object) -> bool: + return hasattr(value, "__torch_function__") + + +def has_torch_function(vt: VariableTracker) -> bool: + # This emulates + # https://github.com/pytorch/pytorch/blob/8d81806211bc3c0ee6c2ef235017bacf1d775a85/torch/csrc/utils/disable_torch_function.cpp#L315-L323 + from torch._dynamo.variables import UserDefinedObjectVariable + from torch._dynamo.variables.torch_function import TensorWithTFOverrideVariable + + # Note on lazy vars: The value will either be realized or not throughout the course of execution + # if the value has a torch function, it will eventually be realized so we can realize it here + # if the value does not have a torch function, it may or may not be realized + # if it is realized it will be used and guards will be installed properly + # if it is not used, guards won't be installed, and it doesn't matter + # if the value has a torch function or not, so we should *not* realize it. + # NB: We technically know that if is_realized is False, LazyVariableTracker has the peek_value method + # but mypy does not unfortunately + if vt.is_realized() or ( + hasattr(vt, "peek_value") and hasattr(vt.peek_value(), "__torch_function__") + ): + func = None + if isinstance(vt, TensorWithTFOverrideVariable): + func = getattr(vt.class_type, "__torch_function__", None) + + elif isinstance(vt, UserDefinedObjectVariable): + func = getattr(vt.value, "__torch_function__", None) + + return func not in (None, torch._C._disabled_torch_function_impl) + + return False + + +# see note [Tensor Fakification and Symbol Caching] +def to_fake_tensor( + t: torch.Tensor, fake_mode: torch._subclasses.fake_tensor.FakeTensorMode +) -> Any: + symbolic_context = None + source = None + if tracing_context := torch._guards.TracingContext.try_get(): + if t in tracing_context.tensor_to_context: + symbolic_context = tracing_context.tensor_to_context[t] + source = symbolic_context.tensor_source + + return fake_mode.from_tensor( + t, static_shapes=False, symbolic_context=symbolic_context, source=source + ) + + +# NB: this works for both classes and instances +def is_frozen_dataclass(value: object) -> bool: + # value may be either a dataclass instance or a dataclass type; both are + # accepted by getattr_static, so the class_has_getattribute call is safe + # even though it is annotated to take a type. + return bool( + not object_has_getattribute(value) + and not class_has_getattribute(value) # type: ignore[arg-type] + and is_dataclass(value) + and hasattr(value, "__dataclass_params__") + and hasattr(value.__dataclass_params__, "frozen") + and value.__dataclass_params__.frozen + ) + + +def get_first_attr(obj: Any, *attrs: str) -> Any: + """ + Return the first available attribute or throw an exception if none is present. + """ + for attr in attrs: + if hasattr(obj, attr): + return getattr(obj, attr) + + raise AssertionError(f"{obj} does not has any of the attributes: {attrs}") + + +@contextlib.contextmanager +def maybe_enable_compiled_autograd( + should_enable: bool, fullgraph: bool = True, dynamic: bool = True +) -> Generator[Any, None, None]: + if not should_enable: + yield + else: + + def compiler_fn(gm: Any) -> Any: + def inner_compiler(gm_: Any, example_inputs_: Any) -> Any: + torch._dynamo.utils.counters["compiled_autograd"]["compiles"] += 1 + return torch._inductor.compile(gm_, example_inputs_) + + return torch.compile( + gm, backend=inner_compiler, fullgraph=fullgraph, dynamic=dynamic + ) + + with torch._dynamo.compiled_autograd._enable(compiler_fn) as ctx: + yield ctx + + +def invalid_removeable_handle() -> RemovableHandle: + # need a subclass so weakref works + class Invalid(dict): # type: ignore[type-arg] + pass + + return RemovableHandle(Invalid()) + + +# Returns a "proxy" (new object with the same class and dict) for (non-GraphModule) nn.Module's. +# Attribute changes to the original object/proxy will be reflected in the other. +# This is useful for cases where we want a keep-alive reference to a module without increasing +# its reference count. +def nn_module_proxy(mod: Any) -> Any: + if not isinstance(mod, torch.nn.Module): + return mod + if isinstance(mod, torch.fx.GraphModule): + # Dynamo-generated GM's shouldn't contain user-created GM's + return mod + proxy = mod.__class__.__new__(mod.__class__) + proxy.__dict__ = mod.__dict__ + return proxy + + +class GmWrapper(torch.nn.Module): + def __init__( + self, gm: torch.fx.GraphModule, unflatten_fn: Callable[[list[Any]], Any] + ) -> None: + super().__init__() + self.gm = gm + self.unflatten_fn = unflatten_fn + + def forward(self, *args: Any) -> Any: + # pyrefly: ignore [redefinition] + args: list[Any] = list(args) + return self.gm(*self.unflatten_fn(args)) + + +def flatten_graph_inputs( + gm: torch.fx.GraphModule, inputs: Any, compile_gm: Callable[[Any, Any], Any] +) -> Callable[..., Any]: + """ + Mutate inputs so that they are flat and wrap gm such that it + accepts those inputs. This is needed for graphs that take + bumpy inputs. + """ + inputs_idx_to_clear = [ + i + for i, node in enumerate(gm.graph.nodes) + if node.op == "placeholder" and node.meta.get("steal_arg", False) + ] + + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + # fast path, avoid pytree overhead + # compiled autograd inputs are always a list of tensors, maybe followed by symints + if inputs_idx_to_clear != [0]: + raise AssertionError( + f"Expected inputs_idx_to_clear == [0], got {inputs_idx_to_clear}" + ) + if not isinstance(inputs[0], list): + raise AssertionError( + f"Expected inputs[0] to be a list, got {type(inputs[0])}" + ) + boxed_inputs_count = len(inputs[0]) + + def flatten_fn(args: Any) -> Any: + return args[0] + list(args[1:]) + + def unflatten_fn(flat_args: Any) -> Any: + return (flat_args[:boxed_inputs_count], *flat_args[boxed_inputs_count:]) + + compiled_fn = compile_gm(GmWrapper(gm, unflatten_fn), flatten_fn(inputs)) + else: + # slow path, don't know inputs structure + flat_inputs, spec = pytree.tree_flatten(inputs) + unflatten_fn = functools.partial(pytree.tree_unflatten, treespec=spec) + compiled_fn = compile_gm(GmWrapper(gm, unflatten_fn), flat_inputs) + # note this doesn't check the spec, assuming it is the same + flatten_fn = pytree.arg_tree_leaves + + def wrapper(*args: Any) -> Any: + flat_args = flatten_fn(args) + + # flat_args is a new list, so we need to clear references from the old list + for i in inputs_idx_to_clear: + args[i].clear() + + # this call is boxed to avoid increasing refcount until we reach aot_module_simplified forward + return compiled_fn(flat_args) + + return wrapper + + +def get_locals_to_steal(maybe_gm: Any) -> list[Any]: + if not isinstance(maybe_gm, torch.fx.GraphModule) or not hasattr(maybe_gm, "meta"): + return [] + return maybe_gm.meta.get("locals_to_steal", []) + + +def set_locals_to_steal(gm: torch.fx.GraphModule, locals_to_steal: list[Any]) -> None: + gm.meta["locals_to_steal"] = locals_to_steal + + +class Lit: + def __init__(self, s: str) -> None: + self.s = s + + def __repr__(self) -> str: + return self.s + + +warn_once_cache: set[str] = set() + + +def warn_once(msg: str, stacklevel: int = 1) -> None: + # Dynamo causes all warnings.warn (in user code and in Dynamo code) to print all the time. + # https://github.com/pytorch/pytorch/issues/128427. + # warn_once is a workaround: if the msg has been warned on before, then we will not + # warn again. + # NB: it's totally ok to store a cache of all the strings: this is what warnings.warn does as well. + if msg in warn_once_cache: + return + warn_once_cache.add(msg) + warnings.warn(msg, stacklevel=stacklevel + 1) + + +def strip_color_from_string(text: str) -> str: + # This regular expression matches ANSI escape codes + ansi_escape = re.compile(r"\x1B[@-_][0-?]*[ -/]*[@-~]") + return ansi_escape.sub("", text) + + +@contextlib.contextmanager +def _disable_saved_tensors_hooks_during_tracing() -> Generator[None, None, None]: + # See NOTE: [Deferring tensor pack/unpack hooks until runtime] + try: + prior = torch._C._autograd._saved_tensors_hooks_set_tracing(True) + yield + finally: + torch._C._autograd._saved_tensors_hooks_set_tracing(prior) + + +def is_parameter_freezing() -> bool: + return torch._inductor.config.freezing and not torch.is_grad_enabled() + + +def get_torch_function_mode_stack() -> list[Any]: + return [ + get_torch_function_mode_stack_at(i) for i in range(_len_torch_function_stack()) + ] + + +def get_torch_function_mode_stack_at(ind: int) -> Any: + if ind < 0: + raise AssertionError(f"Expected ind >= 0, got {ind}") + if ind >= _len_torch_function_stack(): + raise AssertionError( + f"Expected ind < _len_torch_function_stack() ({_len_torch_function_stack()}), got {ind}" + ) + return torch._C._get_function_stack_at(ind) + + +def set_torch_function_mode_stack(stack: list[Any]) -> None: + for _ in range(_len_torch_function_stack()): + _pop_torch_function_stack() + + for mode in stack: + _push_on_torch_function_stack(mode) + + +def clear_torch_function_mode_stack() -> None: + for _ in range(_len_torch_function_stack()): + _pop_torch_function_stack() + + +def get_current_stream(device: torch.device) -> torch.Stream: + return torch.accelerator.current_stream(device) + + +# call from C dynamo in order to inspect values in pdb +def _breakpoint_for_c_dynamo(*args: Any) -> None: + breakpoint() + + +def verify_guard_fn_signature(value: Any) -> None: + fn = value.__metadata_guard__ + sig = inspect.signature(fn) + if len(sig.parameters) != 2: + from .exc import InternalTorchDynamoError + + raise InternalTorchDynamoError( + "Tensor subclass method __metadata_guard__ must take exactly two subclass metadata arguments" + ) + if fn.__self__ != value.__class__: + from .exc import InternalTorchDynamoError + + raise InternalTorchDynamoError( + "Tensor subclass method __metadata_guard__ must be a classmethod" + ) + + +def does_not_override_dict_iter_methods(user_cls: Any) -> bool: + return ( + user_cls.items in (dict.items, OrderedDict.items) + and user_cls.values in (dict.values, OrderedDict.values) + and user_cls.keys in (dict.keys, OrderedDict.keys) + and user_cls.__iter__ in (dict.__iter__, OrderedDict.__iter__) + ) + + +# Helper functions below are to prevent TorchDynamo to prevent tracing of +# __torch_function__ calls triggered on tensor properties in the pre graph +# bytecode. +@torch._disable_dynamo +def call_size(x: Any, i: int) -> int: + return x.size(i) + + +@torch._disable_dynamo +def call_stride(x: Any, i: int) -> int: + return x.stride(i) + + +@torch._disable_dynamo +def call_storage_offset(x: Any) -> int: + return x.storage_offset() + + +# Helper function to extract relevant parts of a tensor's __dict__ to store in node meta. +# To avoid ref cycles, it's important that no tensors are present here, so leave those out. +def _extract_tensor_dict(t: torch.Tensor) -> dict[str, Any]: + KEYS_TO_COPY = [ + "_dynamo_static_input_type", + "tag", + ] + + tensor_dict = { + key: copy.copy(t.__dict__[key]) for key in KEYS_TO_COPY if key in t.__dict__ + } + + return tensor_dict + + +def build_stream(args: tuple[Any], kwargs: dict[Any, Any]) -> torch.Stream: + return torch._C.Stream(*args, **kwargs) + + +def build_event(args: tuple[Any], kwargs: dict[Any, Any]) -> torch.Event: + return torch._C.Event(*args, **kwargs) + + +class FrameState(enum.Enum): + FRAME_CREATED = -3 + FRAME_SUSPENDED = -2 + FRAME_SUSPENDED_YIELD_FROM = -1 + FRAME_EXECUTING = 0 + FRAME_COMPLETED = 1 + FRAME_CLEARED = 4 + + +class PySendResult(enum.Enum): + PYGEN_RETURN = 0 + PYGEN_ERROR = -1 + PYGEN_NEXT = 1 + + +class CompileTimeInstructionCounter: + _counter: int = 0 + _id: int = -1 + _depth = 0 + + @classmethod + def start(cls) -> None: + cls._depth = cls._depth + 1 + if cls._depth == 1: + cls._id = _instruction_counter.start() + + @classmethod + def end(cls) -> None: + cls._depth = cls._depth - 1 + if cls._depth == 0: + cls._counter += _instruction_counter.end(cls._id) + cls._id = -1 + + @classmethod + def clear(cls) -> None: + cls._counter = 0 + + @classmethod + def value(cls) -> int: + return cls._counter + + @classmethod + @contextmanager + def record(cls) -> Generator[None, None, None]: + try: + if config.record_compile_time_instruction_count: + cls.start() + yield + finally: + if config.record_compile_time_instruction_count: + cls.end() + + +class CompileCounterInt(int): + def __add__(self, other: Any) -> CompileCounterInt: + return CompileCounterInt(super().__add__(other)) + + +def set_feature_use(feature: str, usage: bool) -> None: + """ + Records whether we are using a feature + Generally a feature is a JK. + """ + # Note that sometimes (tests etc...) we're not in a context which we can record into + if get_metrics_context().in_progress(): + get_metrics_context().set_key_value("feature_usage", feature, usage) + + +OptimizeDDPMode = Literal[ + "ddp_optimizer", + "python_reducer", + "python_reducer_without_compiled_forward", + "no_optimization", +] + +_ddp_optimization_mode: tuple[OptimizeDDPMode, ...] = ( + "ddp_optimizer", + "python_reducer", # experimental mode + "python_reducer_without_compiled_forward", + "no_optimization", +) + + +def get_optimize_ddp_mode() -> OptimizeDDPMode: + optimize_ddp = config.optimize_ddp + if isinstance(optimize_ddp, bool): + mode = "ddp_optimizer" if optimize_ddp else "no_optimization" + elif isinstance(optimize_ddp, str): + mode = optimize_ddp + else: + raise ValueError( + f"Invalid dynamo config optimize_ddp type {type(optimize_ddp)=}" + ) + + if mode not in _ddp_optimization_mode: + raise AssertionError(f"Invalid dynamo config optimize_ddp value {mode=}") + return cast("OptimizeDDPMode", mode) + + +@contextmanager +def maybe_disable_inference_mode() -> Generator[None, None, None]: + """ + Disables torch.inference_mode for the compilation (still on at runtime). + This simplifies the compile stack where we can assume that inference_mode + will always be off. + + Since inference_mode is equivalent to no_grad + some optimizations (version + counts etc), we turn on no_grad here. The other optimizations are not + relevant to torch.compile. + """ + is_inference_mode_on = ( + config.fake_tensor_disable_inference_mode and torch.is_inference_mode_enabled() + ) + if is_inference_mode_on: + with ( + torch.inference_mode(False), + torch.no_grad(), + ): + yield + else: + yield + + +@contextmanager +def maybe_disable_inference_mode_for_fake_prop() -> Generator[None, None, None]: + """ + Turns off tracking of inference_mode for fake tensor propagation. With this + context manager, when a real tensor is converted to fake tensor, the fake + tensor looses its inference-ness. + """ + if config.fake_tensor_disable_inference_mode: + with torch._subclasses.meta_utils.disable_inference_mode_for_fake_prop(): + yield + else: + yield + + +def is_node_meta_valid(node: torch.fx.Node | None) -> bool: + return node is None or "example_value" in node.meta or "val" in node.meta + + +# If True, enforce fullgraph=True - raise errors on graph break +_error_on_graph_break = False + + +def _get_error_on_graph_break() -> bool: + return _error_on_graph_break + + +def _set_error_on_graph_break(value: bool) -> None: + global _error_on_graph_break + _error_on_graph_break = value + + +@functools.lru_cache(1) +def _is_tensorify_enabled() -> bool: + if (env := os.getenv("TENSORIFY_PYTHON_SCALARS")) is not None: + return env not in ("0", "FALSE") + return justknobs_check("pytorch/compiler:tensorify_python_scalars") + + +@torch._disable_dynamo +def record_pregraph_bytecode_enter() -> AbstractContextManager[None]: + cm: AbstractContextManager[None] = ( + torch._C._profiler._RecordFunctionFast("Pregraph bytecode") + if torch.autograd.profiler._is_profiler_enabled + else contextlib.nullcontext() + ) + cm.__enter__() + return cm + + +@torch._disable_dynamo +def record_pregraph_bytecode_exit(cm: AbstractContextManager[None]) -> None: + cm.__exit__(None, None, None) + + +# Active `torch._dynamo.override_cudagraphs` override, set/restored at RUNTIME by +# CudagraphOverrideContextManager.__enter__/__exit__ (mirrors _error_on_graph_break +# above). This lets the override follow the dynamic call stack: a callee that +# cannot be inlined (e.g. it contains a graph break) is compiled as a separate +# frame and would otherwise not inherit the override, which lives lexically in a +# caller's `with` block / decorator. OutputGraph seeds its cudagraph_annotation +# from this value. None means no override is active; otherwise it is the +# (fwd, bwd) pair. NOTE: we intentionally do not guard on this, so the override +# is sticky per code object (first compile wins) for functions reached both +# inside and outside it. +_cudagraph_override: tuple[bool | None, bool | None] | None = None + + +def _get_cudagraph_override() -> tuple[bool | None, bool | None] | None: + return _cudagraph_override + + +def _set_cudagraph_override(value: tuple[bool | None, bool | None] | None) -> None: + global _cudagraph_override + _cudagraph_override = value + + +# Returns a set of code objects present traced in the current TracingContext, or None +# if there is no current TracingContext. +def get_traced_code() -> list[CodeType] | None: + from torch._guards import TracingContext + + return TracingContext.get_traced_code() + + +def is_pybind11_enum_member(value: object) -> bool: + """Check if value is a pybind11 enum member (with stable hash and eq). + + Pybind11 enums have __members__ on their type. Unlike Python's enum.Enum, + pybind11 injects __hash__ and __eq__ directly into the type's __dict__, + which trips raise_on_overridden_hash. But these are safe: members have + deterministic hash and equality, same as Python enums. + + Note: pybind11 doesn't always return the singleton for enum values (e.g. + a C++ function returning an enum may construct a new Python wrapper), so + we check by name membership rather than identity. + """ + t = type(value) + members = getattr(t, "__members__", None) + if members is None: + return False + name = getattr(value, "name", None) + return name is not None and name in members + + +def _make_inlined( + tx: InstructionTranslatorBase, f: Callable[..., Any] +) -> Callable[..., VariableTracker]: + if not callable(f): + raise AssertionError("Expect f to be a python callable.") + + def inline_call( + *args: VariableTracker, **kwargs: VariableTracker + ) -> VariableTracker: + from torch._dynamo.trace_rules import _force_inline + from torch._dynamo.variables.functions import UserFunctionVariable + + with _force_inline(): + return tx.inline_user_function_return( + UserFunctionVariable(f), + list(args), + dict(kwargs), + ) + + return inline_call diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb9365c44e2a74ca41c2b3cea210fae40fe769e7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__init__.py @@ -0,0 +1,305 @@ +""" +This package implements variable tracking and symbolic execution capabilities for Dynamo, +which are essential for converting Python code into FX graphs. It provides a comprehensive +set of variable types that handle different Python constructs during tracing. + +Each variable type (like BuiltinVariable, TensorVariable, NNModuleVariable, etc.) is responsible +for tracking and symbolically executing operations on specific Python objects. This enables +Dynamo to: +- Track the flow of values through Python code +- Maintain correct semantics during graph conversion +- Handle complex Python features like context managers, iterators, and custom objects +- Support both eager and symbolic execution modes + +The VariableTracker base class provides the foundation for all variable types, with each +subclass implementing specific behavior for different Python constructs. This modular design +allows Dynamo to accurately trace and optimize Python code while preserving its semantics. +""" + +from .base import VariableTracker +from .builtin import ( + BaseBuiltinVariable, + BuiltinVariable, + DictBuiltinVariable, + GetAttrBuiltinVariable, + HasAttrBuiltinVariable, + IterBuiltinVariable, + ListBuiltinVariable, + SetAttrBuiltinVariable, +) +from .constant import ConstantVariable +from .ctx_manager import ( + AcceleratorDeviceIndexVariable, + CatchWarningsCtxManagerVariable, + ContextWrappingVariable, + CUDADeviceVariable, + CudagraphOverrideVariable, + DisabledSavedTensorsHooksVariable, + DualLevelContextManager, + DynamoConfigPatchVariable, + ErrorOnGraphBreakVariable, + FSDPParamGroupUseTrainingStateVariable, + FxTracebackAnnotateVariable, + GenericContextWrappingVariable, + get_device_context_manager, + GradIncrementNestingCtxManagerVariable, + GradInplaceRequiresGradCtxManagerVariable, + GradModeVariable, + InferenceModeVariable, + JvpIncrementNestingCtxManagerVariable, + register_device_context_manager, + SDPAKernelVariable, + SetFwdGradEnabledContextManager, + TemporarilyPopInterpreterStackCtxManagerVariable, + VmapIncrementNestingCtxManagerVariable, + WithEnterFunctionVariable, + WithExitFunctionVariable, + XPUDeviceVariable, +) +from .dicts import ( + ConstDictVariable, + DictItemsVariable, + DictViewVariable, + DunderDictVariable, + MappingProxyVariable, + NNModuleHooksDictVariable, + OrderedDictVariable, +) +from .distributed import BackwardHookVariable, DistributedVariable +from .functions import ( + BaseUserFunctionVariable, + BoundBuiltinMethodVariable, + ClassMethodDescriptorVariable, + ClassMethodVariable, + CollectionsNamedTupleFunction, + CreateTMADescriptorExperimentalVariable, + CreateTMADescriptorStableVariable, + FunctionDecoratedByContextlibContextManagerVariable, + FunctoolsPartialVariable, + GetSetDescriptorVariable, + InspectSignatureVariable, + LocalGeneratorFunctionVariable, + LocalGeneratorObjectVariable, + MemberDescriptorVariable, + MethodDescriptorVariable, + MethodWrapperVariable, + NestedUserFunctionVariable, + PolyfilledFunctionVariable, + PropertyVariable, + PyTreeGetNodeTypeFunctionVariable, + PyTreeTreeIsLeafFunctionVariable, + SkipFunctionVariable, + SparseTensorCreationSkipVariable, + StaticMethodVariable, + TMADescriptorExperimentalVariable, + TMADescriptorStableVariable, + TritonSetAllocatorVariable, + TupleGetterVariable, + UserFunctionVariable, + UserMethodVariable, + WrapperDescriptorVariable, + WrapperUserFunctionVariable, + WrapperUserMethodVariable, +) +from .higher_order_ops import ( + FunctionalCallVariable, + FunctorchHigherOrderVariable, + ReparametrizeModuleCallVariable, + TorchHigherOrderOperatorVariable, +) +from .iter import ( + ChainVariable, + CountIteratorVariable, + FilterVariable, + IteratorVariable, + ItertoolsVariable, + MapVariable, + RepeatIteratorVariable, + ZipLongestVariable, + ZipVariable, +) +from .lazy import LazyConstantVariable, LazyVariableTracker +from .lists import ( + BaseListVariable, + DequeVariable, + ListIteratorVariable, + ListVariable, + RangeVariable, + SliceVariable, + TupleIteratorVariable, + TupleVariable, +) +from .memory import CUDAMemPoolContextVariable, CUDAMemPoolVariable +from .misc import ( + AttributeErrorVariable, + AutogradFunctionContextVariable, + AutogradFunctionVariable, + CallMethodVariable, + CellVariable, + ContextVarVariable, + DeletedVariable, + ExceptionVariable, + GetAttrVariable, + LambdaVariable, + NameErrorVariable, + NewGlobalVariable, + NumpyVariable, + ObjectVariable, + PythonModuleVariable, + RandomClassVariable, + RandomVariable, + StopIterationVariable, + StringFormatVariable, + SuperVariable, + TracebackVariable, + TypingVariable, + UnknownVariable, + WeakRefVariable, +) +from .nn_module import ( + FSDPManagedNNModuleVariable, + NNModuleVariable, + UnspecializedBuiltinNNModuleVariable, + UnspecializedNNModuleVariable, +) +from .optimizer import OptimizerVariable +from .sdpa import SDPAParamsVariable +from .sets import ( + DictKeySetVariable, + FrozensetVariable, + OrderedSetClassVariable, + OrderedSetVariable, + SetVariable, +) +from .streams import ( + CudaStreamVariable, + EventVariable, + StreamContextVariable, + StreamVariable, +) +from .tensor import ( + DataPtrVariable, + FakeItemVariable, + NumpyNdarrayVariable, + SymNodeVariable, + TensorVariable, + UnspecializedPythonVariable, + UntypedStorageVariable, +) +from .torch import TorchCtxManagerClassVariable, TorchInGraphFunctionVariable +from .user_defined import ( + DefaultDictVariable, + FrozenDataClassVariable, + InspectVariable, + MutableMappingVariable, + NamedTupleVariable, + RemovableHandleVariable, + StructSequenceVariable, + UserDefinedClassVariable, + UserDefinedConstantVariable, + UserDefinedDequeVariable, + UserDefinedDictVariable, + UserDefinedExceptionClassVariable, + UserDefinedExceptionObjectVariable, + UserDefinedListVariable, + UserDefinedObjectVariable, + UserDefinedSetVariable, + UserDefinedTupleVariable, + UserDefinedVariable, +) + + +__all__ = [ + "AcceleratorDeviceIndexVariable", + "AttributeErrorVariable", + "AutogradFunctionContextVariable", + "AutogradFunctionVariable", + "BackwardHookVariable", + "BaseBuiltinVariable", + "BaseListVariable", + "CallMethodVariable", + "BuiltinVariable", + "CatchWarningsCtxManagerVariable", + "CellVariable", + "ConstantVariable", + "ConstDictVariable", + "ContextVarVariable", + "ContextWrappingVariable", + "ChainVariable", + "CountIteratorVariable", + "CreateTMADescriptorExperimentalVariable", + "CreateTMADescriptorStableVariable", + "CUDADeviceVariable", + "CUDAMemPoolContextVariable", + "CUDAMemPoolVariable", + "CudagraphOverrideVariable", + "DataPtrVariable", + "DefaultDictVariable", + "DeletedVariable", + "DictBuiltinVariable", + "DictKeySetVariable", + "DynamoConfigPatchVariable", + "ErrorOnGraphBreakVariable", + "FakeItemVariable", + "get_device_context_manager", + "GetAttrBuiltinVariable", + "GetAttrVariable", + "GradModeVariable", + "HasAttrBuiltinVariable", + "InspectSignatureVariable", + "InspectVariable", + "IterBuiltinVariable", + "IteratorVariable", + "ItertoolsVariable", + "LambdaVariable", + "LazyConstantVariable", + "LazyVariableTracker", + "ListBuiltinVariable", + "ListIteratorVariable", + "ListVariable", + "MappingProxyVariable", + "NameErrorVariable", + "NamedTupleVariable", + "NestedUserFunctionVariable", + "NewGlobalVariable", + "NNModuleVariable", + "NumpyNdarrayVariable", + "NumpyVariable", + "OptimizerVariable", + "OrderedDictVariable", + "PolyfilledFunctionVariable", + "PythonModuleVariable", + "RangeVariable", + "register_device_context_manager", + "RemovableHandleVariable", + "RepeatIteratorVariable", + "SDPAParamsVariable", + "SetAttrBuiltinVariable", + "SkipFunctionVariable", + "SliceVariable", + "StopIterationVariable", + "StringFormatVariable", + "StructSequenceVariable", + "SuperVariable", + "TemporarilyPopInterpreterStackCtxManagerVariable", + "TensorVariable", + "TMADescriptorExperimentalVariable", + "TMADescriptorStableVariable", + "TorchCtxManagerClassVariable", + "TorchInGraphFunctionVariable", + "TupleVariable", + "UnknownVariable", + "UnspecializedNNModuleVariable", + "UnspecializedPythonVariable", + "UntypedStorageVariable", + "UserDefinedClassVariable", + "UserDefinedObjectVariable", + "UserDefinedTupleVariable", + "UserFunctionVariable", + "UserMethodVariable", + "VariableTracker", + "WithEnterFunctionVariable", + "WithExitFunctionVariable", + "XPUDeviceVariable", + "ZipLongestVariable", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..805e01b236bccd7bc7fd626e8a5b0a9d883233ce Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36ee2e7ecdaec92ffbd8500f76649e6c27145054 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/base.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70f9efb0286944e7520b5ae573532a35dd34664240c6074edd2d740bd6330cda +size 123472 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02a94e84ebb2d4e9ba4d0ed1ccb2ba76e1cf601f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builder.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0326ded5876d765eebda6e94bb8501e1cd036acc1f6fc71ebe8f1ee63e1de598 +size 219618 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builtin.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builtin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35a9fdd44dd3a3f31d55e60a4684d19f6ee838b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builtin.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95d11903461bf5ba134a73ad2a9f3dd45b56c537b853ef1d6709a10668b09586 +size 160274 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/constant.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/constant.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5db20e6cbb48687bf4c24e5b1c20caa83f2d81b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/constant.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/ctx_manager.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/ctx_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb8f0fd7171ca53071b60af08aa1c17a02984c52 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/ctx_manager.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/dicts.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/dicts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffc6650c9923921e73fbe53f1414f3cac2ce1447 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/dicts.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/distributed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/distributed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f08de1583765311df20a7fc1ca31a45beb3a88bb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/distributed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fe92828d206a85d0e46b541454ce534968b7894 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/functions.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8b9daa526baf5ef1d229b4c140afcdde38ce352a01ceebaa3fe5d63c3eee89b +size 223177 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/hashable.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/hashable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85259819a2a2a333a26fdc8db9591a64066612b3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/hashable.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/higher_order_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/higher_order_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd4c1e56944078c88d49d38751322ed5973fd53d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/higher_order_ops.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64c5ec296c4e69b8c6c81b0c1051d4593318fed2c8af43d213a21000fc73521f +size 215312 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/invoke_subgraph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/invoke_subgraph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14a6bc23b8061c6db81e19099986b421e8f1c804 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/invoke_subgraph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/iter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/iter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbaf548ab00576c19a61ce5fb9d1c6fd9688cc02 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/iter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lazy.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lazy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a4dc7ce932600a68e193fba2ed5ce329628b08b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lazy.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lists.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lists.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55f8154b35f50d145035ad363e44b3b340d42b0f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lists.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b745bf291763be6631163828375b980a648ae03a7a57192e5ab2d595392bf0f5 +size 110362 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/memory.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eedb2535bdee181d6ee1b5d0a041305440c2cb3e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/memory.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/misc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7fbb9025015ad4d7f5329683b92061866f92198 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/misc.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:538278a9fd7610aaf26c1566fc28bf6a94a12a96816324edc61dd08cc770b62b +size 140960 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/nn_module.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/nn_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0910ee409d1f42b1d855d0d82c812dd802f701b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/nn_module.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/object_protocol.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/object_protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4edf8c98df0551b86ff2021cc3db6916f0af9a0a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/object_protocol.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/optimizer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/optimizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddf7903d0a73365a7b3911b200b182117bec2e8b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/optimizer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/script_object.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/script_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62644a7bac28ba56fca15a09c83d62e8155593e8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/script_object.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sdpa.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sdpa.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b16b86160e19364fcc02e9cdb4c8bcd3c8a8c706 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sdpa.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sets.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f56c7792d92c31f91cb2cbba1b1d3216d9568db9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sets.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/streams.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/streams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a4ebf3b14c22b86f3834eacef78553d0307e8fc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/streams.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ad179cf18b2ecec4c122036e3d65c41585da32 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/tensor.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4cf7763405a27012040523cf3d360910fdd90866ce956a02ff9bfc6832e251e7 +size 146945 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..325bcfce37b82a80b112858e373cf3c0ee02c48e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbdaf197c9a83af9ffefccc8326de530520b6a2aaca71f09bb2f8a8965b8871c +size 196999 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..259075a6f41eccd97bdca2aaefa47df1fd8f4ea4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/user_defined.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/user_defined.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1537071f481b45926ab1b1c2b7f3abaddd052c30 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/user_defined.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d3fbc383f26fd1150552ce68b5cbe1a117dde4f09982ee3b5bdfe2e871de404 +size 221496 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/base.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/base.py new file mode 100644 index 0000000000000000000000000000000000000000..485e7966610c80dc25f2928607807872e4200173 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/base.py @@ -0,0 +1,3330 @@ +""" +Core variable tracking functionality for Dynamo. This module defines the fundamental +classes and systems used to track and manage variables during Dynamo's operation. + +The module provides: +1. VariableTracker - The base class for tracking variables during compilation +2. MutationType system - Classes for tracking and managing mutations to variables +3. Source type management - Utilities for tracking variable origins and scope +4. Variable state management - Tools for managing variable state and transformations + +These components form the foundation of Dynamo's variable handling system, +enabling accurate tracking and transformation of Python code into optimized +computations. +""" + +from __future__ import annotations + +import collections +import dataclasses +import functools +import inspect +import logging +import textwrap +from collections.abc import Callable, ItemsView, KeysView, ValuesView +from contextvars import ContextVar +from enum import Enum, IntFlag +from typing import Any, NamedTuple, NoReturn, TYPE_CHECKING, TypeAlias + +from torch._C._dynamo import ( + get_type_slots, + has_slot, + PyMappingSlots, + PyNumberSlots, + PySequenceSlots, + PyTypeSlots, +) + +from .. import graph_break_hints, variables +from ..current_scope_id import current_scope_id +from ..exc import ( + ObservedAttributeError, + raise_observed_exception, + raise_type_error, + unimplemented, + Unsupported, +) +from ..guards import GuardBuilder, install_guard +from ..source import AttrSource, Source +from ..utils import format_source_range, istype + + +_RICHCOMPARE_OPS = frozenset( + {"__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__"} +) + + +if TYPE_CHECKING: + from torch._guards import Guard + from torch.fx.proxy import Node + + from ..codegen import PyCodegen + from ..side_effects import SideEffects + from ..symbolic_convert import InstructionTranslatorBase + from .constant import ConstantVariable + from .functions import UserFunctionVariable + + +log = logging.getLogger(__name__) + + +@dataclasses.dataclass(frozen=True) +class SourceLocation: + """Source position of the bytecode instruction that generated a VariableTracker.""" + + filename: str + lineno: int + end_lineno: int | None = None + col_offset: int | None = None + end_col_offset: int | None = None + + def format(self) -> str: + result = f' File "{self.filename}", line {self.lineno}\n' + source = format_source_range( + self.filename, + self.lineno, + self.end_lineno, + self.col_offset, + self.end_col_offset, + ) + if source: + result += textwrap.indent(source.rstrip("\n"), " ") + "\n" + return result + + +# Tracks active method calls on VariableTracker instances to detect self-referential +# calls (e.g., as_python_constant on a list that contains itself). Maps +# (id(instance), id(original_method)) tuples to track which calls are in progress. +# We use id(original_method) rather than the method name string so that super() +# delegation within a class hierarchy (e.g. CustomClassObjectVariable.as_python_constant +# calling UserDefinedObjectVariable.as_python_constant) is not a false positive. +_vt_active_calls: ContextVar[set[tuple[int, int]] | None] = ContextVar( + "_vt_active_calls", default=None +) + + +class SourceType(Enum): + """ + This Enum divides VariableTracker into 2 cases, depending on the variable + it represents: + - already existed that Dynamo began tracking while introspection (Existing) + - is a new variable that is created during Dynamo introspection (New) + + In general, we have these invariants: + 1. for `VariableTracker` associated with `Existing`, its `source` field must not be None. + 2. for `VariableTracker` associated with `New`, most of the time its + `source` field is None, except for cases like side effect codegen for + `AttributeMutationNew`, during which we generate a + `LocalSource('tmp...')` for such variable, to facilitate codegen. + """ + + Existing = 0 + New = 1 + + +class MutationType: + """ + Base class for Variable.mutation_type. It encodes information about + 1. The type of mutation Dynamo allows on the variable. + 2. Whether the value represented by this variable already existed before + Dynamo tracing. + """ + + def __init__(self, typ: SourceType) -> None: + # In HigherOrderOperator tracing, we need to distinguish + # between MutationTypes inside the HigherOrderOperator and + # ones outside it. For example, it is not safe to mutate + # `a` in the following example because it was constructed + # in a different scope. + # + # def f(x): + # a = 1 + # def g(x): + # nonlocal a + # a = 2 + # return x + # return wrap(g, x) + a + # + # We use self.scope to distinguish this. + # scope == 0: The object was an existing variable + # scope == 1: The object was created while Dynamo + # was introspecting a function + # (and no HigherOrderOps were involved) + # scope >= 2: The object was created through + # Dynamo introspection of a HigherOrderOp. + # The exact number corresponds to the level + # of nested HigherOrderOps. + if typ is SourceType.Existing: + self.scope = 0 + elif typ is SourceType.New: + self.scope = current_scope_id() + else: + unimplemented( + gb_type="Unsupported SourceType", + context=f"MutationType.__init__ {self} {typ}", + explanation=f"Dynamo does not support the type `{typ}`", + hints=[ + "This branch is not supposed to be reachable.", + *graph_break_hints.DYNAMO_BUG, + ], + ) + + +class AttrMutationKind(Enum): + # Replay through STORE_ATTR/DELETE_ATTR, preserving descriptor-aware + # setattr/delattr semantics. Used for slots, getset descriptors, and other + # ordinary attribute writes that should not bypass descriptors. + GENERIC_SETATTR = 0 + # Replay a direct object.__dict__ mutation while bypassing descriptors. + INSTANCE_DICT = 1 + + +class ValueMutationNew(MutationType): + """ + This case of VariableTracker.mutation_type marker indicates + 1. Dynamo allows mutation on the value itself (rather than its attributes). + 2. The value is created by the bytecode Dynamo is tracing through. + + For instance, Dynamo could model a newly created list with this marker, + indicating that while we need to model mutations to this list, we don't have + to emit bytecode for these mutations if the list doesn't escape into the + Python world. + """ + + def __init__(self) -> None: + super().__init__(SourceType.New) + + def __hash__(self) -> int: + return id(self) + + def __eq__(self, other: object) -> bool: + return self is other + + +class ValueMutationExisting(MutationType): + """ + This case of VariableTracker.mutation_type marker indicates + 1. Dynamo allows mutation on the value itself (rather than its attributes). + 2. The value exists before Dynamo tracing started. + + For instance, Dynamo could model a pre-existing list with this marker, + indicating that if we encounter mutations to this list, we need to buffer + and re-apply those mutations after the graph runs, since the list might be + used afterwards in Python. + """ + + # A flag to indicate whether mutation happened on the associated + # `VariableTracker`. This enables SideEffects to accurately and quickly + # filter out which pre-existing values it needs to generate mutation for. + is_modified: bool + + def __init__(self, is_modified: bool = False) -> None: + super().__init__(SourceType.Existing) + self.is_modified = is_modified + + +class AttributeMutation(MutationType): + """ + This case of VariableTracker.mutation_type marker indicates that Dynamo + allows mutation on the value's attributes. + """ + + +class AttributeMutationExisting(AttributeMutation): + """ + This case of VariableTracker.mutation_type marker indicates + 1. Dynamo allows mutation on the value's attributes. + 2. The value exists before Dynamo tracing started. + + For instance, Dynamo could model a pre-existing object with this marker, + indicating that if we encounter mutations to this object, we need to buffer + then re-apply those mutations after the graph runs, since the object might + be used afterwards in Python. + """ + + def __init__(self) -> None: + super().__init__(SourceType.Existing) + + +class AttributeMutationNew(AttributeMutation): + """ + This case of VariableTracker.mutation_type marker indicates + 1. Dynamo allows mutation on the value's attributes. + 2. The value is created by the bytecode Dynamo is tracing through. + + For instance, Dynamo could model a newly created object with this marker, + indicating that while we need to model mutations to this object, we don't + have to emit bytecode for these mutations if the object doesn't escape into + the Python world. + """ + + def __init__(self, cls_source: Source | None = None) -> None: + super().__init__(SourceType.New) + self.cls_source = cls_source + + +def _is_top_level_scope(scope_id: int) -> bool: + return scope_id == 1 + + +def is_side_effect_safe(m: MutationType) -> bool: + scope_id = current_scope_id() + + # In the top-level scope (if no HigherOrderOperators are involved), + # we are allowed to modify variables created in this scope as well + # as existing variables. + if _is_top_level_scope(scope_id): + return True + # Otherwise, only allow local mutation of variables created in the current scope + return m.scope == scope_id + + +def maybe_get_python_type(obj: VariableTracker) -> type: + try: + return obj.python_type() + except NotImplementedError: + unimplemented( + gb_type="Unsupported python_type() call", + context=f"{obj} does not implement python_type()", + explanation="This VariableTracker does not implement python_type(), " + "which is required for object protocol operations.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + +class NO_SUCH_SUBOBJ: + """Sentinel indicating no concrete Python object is available.""" + + +class MethodFlags(IntFlag): + """Calling convention for a `Method` handler, mirroring CPython's + PyMethodDef ml_flags. `call_method` enforces arity from these before + invoking the handler, centralizing the raise_args_mismatch boilerplate.""" + + VARARGS = 1 # any positional args; kwargs rejected unless KEYWORDS is set + KEYWORDS = 2 # kwargs allowed (combine with VARARGS) + NOARGS = 4 # exactly zero args and zero kwargs + O = 8 # exactly one positional arg, no kwargs + + +def _check_method_arity( + vt: VariableTracker, + tx: InstructionTranslatorBase, + name: str, + flags: MethodFlags, + args: Any, + kwargs: Any, +) -> None: + # Centralized arity check for a tp_methods handler, driven by MethodFlags, + # raising the same TypeErrors CPython raises for builtin methods. Shared by + # Method and callers that run the handler directly (e.g. tensor.py). + n = len(args) + qualname = f"{vt.python_type_name()}.{name}" + if kwargs and not (flags & MethodFlags.KEYWORDS): + raise_type_error(tx, f"{qualname}() takes no keyword arguments") + if flags & (MethodFlags.NOARGS | MethodFlags.O): + if flags & MethodFlags.NOARGS and args: + raise_type_error(tx, f"{qualname}() takes no arguments ({n} given)") + if flags & MethodFlags.O and n != 1: + raise_type_error(tx, f"{qualname}() takes exactly one argument ({n} given)") + + +# CPython PyMethodDef.ml_flags bits (Include/methodobject.h); MethodFlags above +# deliberately mirrors the low four so the mapping is near-identity. +_METH_VARARGS, _METH_KEYWORDS, _METH_NOARGS, _METH_O, _METH_FASTCALL = 1, 2, 4, 8, 0x80 + + +@functools.cache +def _flags_from_ml_flags(python_type: type, name: str) -> MethodFlags: + """Arity convention for `python_type.name`, read from its CPython + PyMethodDef.ml_flags. Falls back to VARARGS|KEYWORDS when python_type has no + such attribute or it carries no ml_flags (slot wrappers, pure-Python + functions).""" + import torch + + default = MethodFlags.VARARGS | MethodFlags.KEYWORDS + fn = getattr(python_type, name, None) + ml = None if fn is None else torch._C._dynamo.eval_frame.get_method_ml_flags(fn) + if ml is None: + return default + flags = MethodFlags(0) + if ml & _METH_NOARGS: + flags |= MethodFlags.NOARGS + if ml & _METH_O: + flags |= MethodFlags.O + if ml & (_METH_VARARGS | _METH_FASTCALL): + flags |= MethodFlags.VARARGS + if ml & _METH_KEYWORDS: + flags |= MethodFlags.KEYWORDS + return flags or default + + +def _derive_method_flags(vt: VariableTracker, name: str) -> MethodFlags: + """Resolve the arity flags for method `name` from the VT's arity-reference + type (see VariableTracker.method_flags_type).""" + return _flags_from_ml_flags(vt.method_flags_type(), name) + + +@dataclasses.dataclass(slots=True) +class Method: + """Declarative entry in a VariableTracker's `tp_methods` table, analogous + to CPython's PyMethodDef. + + Handlers have signature `(self, tx, args, kwargs)` and return the result + VariableTracker, or None to decline the call (the equivalent of the old + `super().call_method` fall-through) so `call_method` continues to the + object-protocol dispatch below. The method name is the tp_methods key this + entry is stored under; its arity convention is derived + on demand from that method's ml_flags (see _derive_method_flags).""" + + handler: Callable[..., VariableTracker | None] + + def __call__( + self, + vt: VariableTracker, + tx: InstructionTranslatorBase, + name: str, + args: Any, + kwargs: Any, + ) -> VariableTracker | None: + flags = _derive_method_flags(vt, name) + _check_method_arity(vt, tx, name, flags, args, kwargs) + return self.handler(vt, tx, args, kwargs) + + +@dataclasses.dataclass(slots=True) +class GetSet: + """`tp_getset` entry, analogous to CPython's PyGetSetDef. `getter` + `(self, tx) -> VT | None` (None declines); `setter` + `(self, tx, value) -> VT | None`, None for read-only.""" + + getter: Callable[..., VariableTracker | None] + setter: Callable[..., VariableTracker | None] | None = None + + +@dataclasses.dataclass(slots=True) +class Member: + """`tp_members` entry, analogous to CPython's PyMemberDef. Same shape as + GetSet; a distinct type so members and getsets never share a class.""" + + getter: Callable[..., VariableTracker | None] + setter: Callable[..., VariableTracker | None] | None = None + + +def getset_read( + accessor: Callable[[Any], VariableTracker], +) -> Callable[..., VariableTracker]: + """Getter for a GetSet/Member whose value is an already-built VT.""" + return lambda self, tx: accessor(self) + + +def getset_build( + accessor: Callable[[Any], Any], +) -> Callable[..., VariableTracker]: + """Getter that builds a VT from the raw value returned by `accessor`.""" + return lambda self, tx: VariableTracker.build(tx, accessor(self)) + + +def unsupported_attr(name: str) -> Callable[..., VariableTracker | None]: + def graph_break( + vt: VariableTracker, tx: InstructionTranslatorBase + ) -> VariableTracker | None: + unimplemented( + gb_type="Unsupported attribute", + context=f"attr_unsupported {vt} {name}", + explanation=f"{type(vt).__name__} does not support attribute '{name}'", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + return graph_break + + +# This helps users of `as_python_constant` to catch unimplemented error with +# more information; it inherits `NotImplementedError` for backward +# compatibility reasons. +class AsPythonConstantNotImplementedError(NotImplementedError): + vt: VariableTracker + + def __init__(self, vt: VariableTracker, msg: str | None = None) -> None: + msg = f"{vt} is not a constant" if msg is None else msg + super().__init__(msg) + self.vt = vt + + +# --------------------------------------------------------------------------- +# SLOTDEFS: Dynamo's analog of CPython's static slotdefs[] table +# (Objects/typeobject.c). One global table, shared by every type, mapping a +# dunder name to the VariableTracker method that implements it (``impl``, the +# slotdefs "function" column) and a ``wrapper`` that adapts a generic call into +# the right impl invocation (the slotdefs "wrapper" column: arity + operand +# order). CPython also stores a slot offset per entry; Dynamo does not need it +# -- dispatch only cares which impl to call, and MRO lookup already tells us +# whether a name resolves. Per-VT variation is which impl method is overridden; +# the table itself never varies. Lives here alongside the ``*_impl`` methods it +# names so mapping and implementations stay together; consumers (call_method +# here, getattro in object_protocol) both read it without an import cycle. +# --------------------------------------------------------------------------- + + +def _wrap_unaryfunc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 0: + raise_type_error(tx, f"expected 0 arguments, got {len(args)}") + return func(self, tx) + + +def _wrap_binaryfunc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + other = args[0] + return func(self, tx, other) + + +def _wrap_binaryfunc_r( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # Reflected binary op (``__radd__``): same impl, operands from the right. + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + other = args[0] + return func(self, tx, other, reverse=True) + + +def _wrap_ternaryfunc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # __pow__ is binary or ternary: ``x.__pow__(y)`` or ``x.__pow__(y, z)`` (mod). + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) not in (1, 2): + raise_type_error(tx, f"expected 1 or 2 arguments, got {len(args)}") + z = args[1] if len(args) == 2 else None + return func(self, tx, args[0], z) + + +def _wrap_ternaryfunc_r( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # Reflected __rpow__: operands from the right. + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) not in (1, 2): + raise_type_error(tx, f"expected 1 or 2 arguments, got {len(args)}") + z = args[1] if len(args) == 2 else None + return func(self, tx, args[0], z, reverse=True) + + +def _wrap_sq_setitem( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + from .object_protocol import getindex + + if len(args) != 2: + raise_type_error(tx, f"expected 2 arguments, got {len(args)}") + [arg, value] = args + i = getindex(tx, self, arg) + return func(self, tx, i, value) + + +def _wrap_sq_item( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + from .object_protocol import getindex + + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + + [arg] = args + i = getindex(tx, self, arg) + return func(self, tx, i) + + +def _wrap_indexargfunc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + from .object_protocol import pynumber_as_ssize_t + + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + + [o] = args + i = pynumber_as_ssize_t(tx, o, err=OverflowError) + return func(self, tx, i) + + +def _wrap_objobjargproc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 2: + raise_type_error(tx, f"expected 2 arguments, got {len(args)}") + [key, value] = args + return func(self, tx, key, value) + + +def _wrap_delitem( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + [key] = args + return func(self, tx, key, None) + + +def _wrap_sq_delitem( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + from .object_protocol import getindex + + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + [arg] = args + i = getindex(tx, self, arg) + return func(self, tx, i, None) + + +def _wrap_objobjproc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # sq_contains via __contains__: one arg, impl returns a bool. + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + [other] = args + return func(self, tx, other) + + +def _make_richcmp( + op: str, +) -> Callable[ + [ + VariableTracker, + InstructionTranslatorBase, + Callable[..., VariableTracker], + list[VariableTracker], + dict[str, VariableTracker], + ], + VariableTracker, +]: + # tp_richcompare via __lt__/.../__ge__: one impl, op baked per dunder. + def wrapper( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + return func(self, tx, args[0], op) + + return wrapper + + +richcmp_lt = _make_richcmp("__lt__") +richcmp_le = _make_richcmp("__le__") +richcmp_eq = _make_richcmp("__eq__") +richcmp_ne = _make_richcmp("__ne__") +richcmp_gt = _make_richcmp("__gt__") +richcmp_ge = _make_richcmp("__ge__") + + +def wrap_call( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_call via __call__: variadic (kwargs handled by the call_method branch). + return func(self, tx, args, kwargs) + + +def _wrap_init( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_init via __init__: variadic, forwards kwargs (e.g. dict(a=1), + # defaultdict(list, d, c=3)). + return func(self, tx, args, kwargs) + + +def _wrap_setattr( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_setattro via __setattr__: (name, value). + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 2: + raise_type_error(tx, f"expected 2 arguments, got {len(args)}") + return func(self, tx, args[0], args[1]) + + +def _wrap_delattr( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_setattro via __delattr__: (name,). + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + return func(self, tx, args[0]) + + +def _wrap_getattro( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_getattro via __getattribute__: impl takes the attribute name as a str. + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + return func(self, tx, args[0].as_python_constant()) + + +def _wrap_descr_get( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_descr_get via __get__(obj, owner=None): owner defaults to type(obj). + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) not in (1, 2): + raise_type_error(tx, f"expected 1 or 2 arguments, got {len(args)}") + obj = args[0] + owner = args[1] if len(args) > 1 else obj.tp_getattro_impl(tx, "__class__") + return func(self, tx, obj, owner) + + +def _wrap_descr_set( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_descr_set via __set__(obj, value): 2 args. + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 2: + raise_type_error(tx, f"expected 2 arguments, got {len(args)}") + return func(self, tx, args[0], args[1]) + + +def _wrap_descr_delete( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_descr_set via __delete__(obj): value=None signals delete (CPython + # passes value==NULL to the shared tp_descr_set slot). + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + return func(self, tx, args[0], None) + + +class SlotGroup(Enum): + """A CPython slot group. The value is the group's index into + get_type_slots()'s 4-tuple.""" + + SEQUENCE = 0 + MAPPING = 1 + NUMBER = 2 + TYPE = 3 + + +@dataclasses.dataclass(frozen=True) +class Slot: + """A CPython type slot: the name of the VariableTracker method implementing + the slot function. + """ + + impl: str + + def __call__( + self, + vt: VariableTracker, + tx: InstructionTranslatorBase, + *args: Any, + **kwargs: Any, + ) -> VariableTracker: + return getattr(type(vt), self.impl)(vt, tx, *args, **kwargs) + + +class PyNumberMethods(NamedTuple): + nb_bool: Slot | None + nb_index: Slot | None + nb_int: Slot | None + nb_float: Slot | None + nb_negative: Slot | None + nb_positive: Slot | None + nb_absolute: Slot | None + nb_invert: Slot | None + nb_add: Slot | None + nb_inplace_add: Slot | None + nb_subtract: Slot | None + nb_inplace_subtract: Slot | None + nb_multiply: Slot | None + nb_inplace_multiply: Slot | None + nb_remainder: Slot | None + nb_inplace_remainder: Slot | None + nb_power: Slot | None + nb_inplace_power: Slot | None + nb_lshift: Slot | None + nb_inplace_lshift: Slot | None + nb_rshift: Slot | None + nb_inplace_rshift: Slot | None + nb_and: Slot | None + nb_inplace_and: Slot | None + nb_xor: Slot | None + nb_inplace_xor: Slot | None + nb_or: Slot | None + nb_inplace_or: Slot | None + nb_floor_divide: Slot | None + nb_inplace_floor_divide: Slot | None + nb_true_divide: Slot | None + nb_inplace_true_divide: Slot | None + nb_divmod: Slot | None + nb_matrix_multiply: Slot | None + nb_inplace_matrix_multiply: Slot | None + + +class PySequenceMethods(NamedTuple): + sq_length: Slot | None + sq_concat: Slot | None + sq_repeat: Slot | None + sq_item: Slot | None + sq_ass_item: Slot | None + sq_contains: Slot | None + sq_inplace_concat: Slot | None + sq_inplace_repeat: Slot | None + + +class PyMappingMethods(NamedTuple): + mp_length: Slot | None + mp_subscript: Slot | None + mp_ass_subscript: Slot | None + + +class PyTypeObject(NamedTuple): + tp_repr: Slot | None + tp_hash: Slot | None + tp_call: Slot | None + tp_str: Slot | None + tp_getattro: Slot | None + tp_setattro: Slot | None + tp_richcompare: Slot | None + tp_iter: Slot | None + tp_iternext: Slot | None + tp_descr_get: Slot | None + tp_descr_set: Slot | None + tp_init: Slot | None + tp_as_number: PyNumberMethods + tp_as_sequence: PySequenceMethods + tp_as_mapping: PyMappingMethods + + +# The tp_ slot fields of PyTypeObject (everything but the sub-struct pointers). +_TYPE_FIELDS = tuple(f for f in PyTypeObject._fields if not f.startswith("tp_as_")) + +# Per group: C slot bit -> struct field name, keyed via the enum's UPPERCASE name. +_BIT_FIELD: dict[SlotGroup, dict[int, str]] = { + SlotGroup.NUMBER: { + getattr(PyNumberSlots, f.upper()): f for f in PyNumberMethods._fields + }, + SlotGroup.SEQUENCE: { + getattr(PySequenceSlots, f.upper()): f for f in PySequenceMethods._fields + }, + SlotGroup.MAPPING: { + getattr(PyMappingSlots, f.upper()): f for f in PyMappingMethods._fields + }, + SlotGroup.TYPE: {getattr(PyTypeSlots, f.upper()): f for f in _TYPE_FIELDS}, +} + + +# The actual slot function (a VariableTracker method) each struct field dispatches to +_SLOT_FN: dict[SlotGroup, dict[str, str]] = { + SlotGroup.NUMBER: {f: f"{f}_impl" for f in PyNumberMethods._fields}, + SlotGroup.SEQUENCE: {f: f"{f}_impl" for f in PySequenceMethods._fields}, + SlotGroup.MAPPING: {f: f"{f}_impl" for f in PyMappingMethods._fields}, + SlotGroup.TYPE: { + **{f: f"{f}_impl" for f in _TYPE_FIELDS}, + "tp_call": "call_function", + "tp_hash": "hash_impl", + }, +} + +# _SLOT_FN must name a slot fn for exactly each struct field. +for _group, _fns in _SLOT_FN.items(): + if set(_fns) != set(_BIT_FIELD[_group].values()): + raise AssertionError(f"{_group.name}: _SLOT_FN fields != struct fields") + + +def _fill(group: SlotGroup, masks: tuple[int, int, int, int]) -> dict[str, Any]: + # {field -> Slot(slot fn) if the type fills the slot, else None} + mask = masks[group.value] + fn_map = _SLOT_FN[group] + return { + field: Slot(fn_map[field]) if has_slot(mask, bit) else None + for bit, field in _BIT_FIELD[group].items() + } + + +@functools.cache +def _tp_type(obj_type: type) -> PyTypeObject: + # obj_type's whole slot table (PyTypeObject-like). Independent of _tp_dict's + # cross-group collapse, so a type with both sq_length and mp_length shows up in + # both the sequence and mapping views (as CPython's separate sub-structs do). + masks = get_type_slots(obj_type) + return PyTypeObject( + tp_as_number=PyNumberMethods(**_fill(SlotGroup.NUMBER, masks)), + tp_as_sequence=PySequenceMethods(**_fill(SlotGroup.SEQUENCE, masks)), + tp_as_mapping=PyMappingMethods(**_fill(SlotGroup.MAPPING, masks)), + **_fill(SlotGroup.TYPE, masks), + ) + + +WrapperType: TypeAlias = Callable[ + [ + "VariableTracker", + "InstructionTranslatorBase", + Callable[..., "VariableTracker"], + list["VariableTracker"], + dict[str, "VariableTracker"], + ], + "VariableTracker", +] + + +@dataclasses.dataclass(frozen=True) +class SlotDef: + """One slotdefs entry: dunder name -> (impl method, call wrapper). + + ``impl`` is the VariableTracker method implementing the behavior; ``wrapper`` + adapts a generic ``(self, tx, args)`` call to it (arity + operand order). A + reflected op reuses the forward impl with ``_wrap_binaryfunc_r``; an in-place + op is a plain binary call into its own ``nb_inplace_*`` impl -- so no + reverse/inplace flags are needed. + + ``group`` is the CPython slot group (``SlotGroup``) the entry lives in and + ``slot`` is the bit within it; together they decide whether a real type + implements the slot. + """ + + name: str + impl: str + group: SlotGroup + slot: int + wrapper: WrapperType + + def __call__( + self, + vt: VariableTracker, + tx: InstructionTranslatorBase, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """Call the impl via the wrapper, passing self, tx, and args.""" + func = getattr(type(vt), self.impl) + return self.wrapper(vt, tx, func, args, kwargs) + + +def SQSLOT(name: str, impl: str, slot: int, wrapper: WrapperType) -> SlotDef: + return SlotDef(name, impl, SlotGroup.SEQUENCE, slot, wrapper) + + +def MPSLOT(name: str, impl: str, slot: int, wrapper: WrapperType) -> SlotDef: + return SlotDef(name, impl, SlotGroup.MAPPING, slot, wrapper) + + +def NBSLOT(name: str, impl: str, slot: int, wrapper: WrapperType) -> SlotDef: + return SlotDef(name, impl, SlotGroup.NUMBER, slot, wrapper) + + +def TPSLOT(name: str, impl: str, slot: int, wrapper: WrapperType) -> SlotDef: + return SlotDef(name, impl, SlotGroup.TYPE, slot, wrapper) + + +# The declarative slot table (mirrors CPython's static slotdefs[] array). Each +# entry: dunder name, impl method, ``group`` + ``slot`` (which slot sub-struct +# and bit -- reflected ops share the forward slot's group/slot), and wrapper +# (call shape). +_SLOTDEFS: list[SlotDef] = [ + # SlotDef("__getattribute__", ), + # SlotDef("__getattr__", ), + # SlotDef("__setattr__", ), + # SlotDef("__delattr__", ), + TPSLOT("__repr__", "tp_repr_impl", PyTypeSlots.TP_REPR, _wrap_unaryfunc), + # TPSLOT("__hash__", "tp_hash_impl", PyTypeSlots.TP_HASH, _wrap_unaryfunc), + TPSLOT("__call__", "call_function", PyTypeSlots.TP_CALL, wrap_call), + TPSLOT("__str__", "tp_str_impl", PyTypeSlots.TP_STR, _wrap_unaryfunc), + TPSLOT( + "__getattribute__", + "tp_getattro_impl", + PyTypeSlots.TP_GETATTRO, + _wrap_getattro, + ), + TPSLOT( + "__getattr__", + "tp_getattro_impl", + PyTypeSlots.TP_GETATTRO, + _wrap_getattro, + ), + # This needs one to model tp_setattro first + PyObject_GenericSetAttr / PyObject_GenericDelAttr + # TPSLOT( + # "__setattr__", + # "setattro_impl", + # PyTypeSlots.TP_SETATTRO, + # _wrap_setattr, + # ), + # TPSLOT( + # "__delattr__", + # "delattro_impl", + # PyTypeSlots.TP_SETATTRO, + # _wrap_delattr, + # ), + TPSLOT( + "__lt__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_lt, + ), + TPSLOT( + "__le__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_le, + ), + TPSLOT( + "__eq__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_eq, + ), + TPSLOT( + "__ne__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_ne, + ), + TPSLOT( + "__gt__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_gt, + ), + TPSLOT( + "__ge__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_ge, + ), + TPSLOT("__iter__", "tp_iter_impl", PyTypeSlots.TP_ITER, _wrap_unaryfunc), + TPSLOT( + "__next__", + "tp_iternext_impl", + PyTypeSlots.TP_ITERNEXT, + _wrap_unaryfunc, + ), + TPSLOT( + "__get__", + "tp_descr_get_impl", + PyTypeSlots.TP_DESCR_GET, + _wrap_descr_get, + ), + TPSLOT( + "__set__", + "tp_descr_set_impl", + PyTypeSlots.TP_DESCR_SET, + _wrap_descr_set, + ), + TPSLOT( + "__delete__", + "tp_descr_set_impl", + PyTypeSlots.TP_DESCR_SET, + _wrap_descr_delete, + ), + TPSLOT("__init__", "tp_init_impl", PyTypeSlots.TP_INIT, _wrap_init), + # SlotDef("__new__", ...), # missing + # SlotDef("__del__", ...), # missing + # SlotDef("__buffer__", ...), # missing + # SlotDef("__release_buffer__", ...), # missing + # SlotDef("__await__", ...), # missing + # SlotDef("__aiter__", ...), # missing + # SlotDef("__anext__", ...), # missing + NBSLOT( + "__add__", + "nb_add_impl", + PyNumberSlots.NB_ADD, + _wrap_binaryfunc, + ), + NBSLOT( + "__radd__", + "nb_add_impl", + PyNumberSlots.NB_ADD, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__sub__", + "nb_subtract_impl", + PyNumberSlots.NB_SUBTRACT, + _wrap_binaryfunc, + ), + NBSLOT( + "__rsub__", + "nb_subtract_impl", + PyNumberSlots.NB_SUBTRACT, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__mul__", + "nb_multiply_impl", + PyNumberSlots.NB_MULTIPLY, + _wrap_binaryfunc, + ), + NBSLOT( + "__rmul__", + "nb_multiply_impl", + PyNumberSlots.NB_MULTIPLY, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__mod__", + "nb_remainder_impl", + PyNumberSlots.NB_REMAINDER, + _wrap_binaryfunc, + ), + NBSLOT( + "__rmod__", + "nb_remainder_impl", + PyNumberSlots.NB_REMAINDER, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__divmod__", + "nb_divmod_impl", + PyNumberSlots.NB_DIVMOD, + _wrap_binaryfunc, + ), + NBSLOT( + "__rdivmod__", + "nb_divmod_impl", + PyNumberSlots.NB_DIVMOD, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__pow__", + "nb_power_impl", + PyNumberSlots.NB_POWER, + _wrap_ternaryfunc, + ), + NBSLOT( + "__rpow__", + "nb_power_impl", + PyNumberSlots.NB_POWER, + _wrap_ternaryfunc_r, + ), + NBSLOT( + "__neg__", + "nb_negative_impl", + PyNumberSlots.NB_NEGATIVE, + _wrap_unaryfunc, + ), + NBSLOT( + "__pos__", + "nb_positive_impl", + PyNumberSlots.NB_POSITIVE, + _wrap_unaryfunc, + ), + NBSLOT( + "__abs__", + "nb_absolute_impl", + PyNumberSlots.NB_ABSOLUTE, + _wrap_unaryfunc, + ), + NBSLOT( + "__bool__", + "nb_bool_impl", + PyNumberSlots.NB_BOOL, + _wrap_unaryfunc, + ), + NBSLOT( + "__invert__", + "nb_invert_impl", + PyNumberSlots.NB_INVERT, + _wrap_unaryfunc, + ), + NBSLOT( + "__lshift__", + "nb_lshift_impl", + PyNumberSlots.NB_LSHIFT, + _wrap_binaryfunc, + ), + NBSLOT( + "__rlshift__", + "nb_lshift_impl", + PyNumberSlots.NB_LSHIFT, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__rshift__", + "nb_rshift_impl", + PyNumberSlots.NB_RSHIFT, + _wrap_binaryfunc, + ), + NBSLOT( + "__rrshift__", + "nb_rshift_impl", + PyNumberSlots.NB_RSHIFT, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__and__", + "nb_and_impl", + PyNumberSlots.NB_AND, + _wrap_binaryfunc, + ), + NBSLOT( + "__rand__", + "nb_and_impl", + PyNumberSlots.NB_AND, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__xor__", + "nb_xor_impl", + PyNumberSlots.NB_XOR, + _wrap_binaryfunc, + ), + NBSLOT( + "__rxor__", + "nb_xor_impl", + PyNumberSlots.NB_XOR, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__or__", + "nb_or_impl", + PyNumberSlots.NB_OR, + _wrap_binaryfunc, + ), + NBSLOT( + "__ror__", + "nb_or_impl", + PyNumberSlots.NB_OR, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__int__", + "nb_int_impl", + PyNumberSlots.NB_INT, + _wrap_unaryfunc, + ), + NBSLOT( + "__float__", + "nb_float_impl", + PyNumberSlots.NB_FLOAT, + _wrap_unaryfunc, + ), + NBSLOT( + "__iadd__", + "nb_inplace_add_impl", + PyNumberSlots.NB_INPLACE_ADD, + _wrap_binaryfunc, + ), + NBSLOT( + "__isub__", + "nb_inplace_subtract_impl", + PyNumberSlots.NB_INPLACE_SUBTRACT, + _wrap_binaryfunc, + ), + NBSLOT( + "__imul__", + "nb_inplace_multiply_impl", + PyNumberSlots.NB_INPLACE_MULTIPLY, + _wrap_binaryfunc, + ), + NBSLOT( + "__imod__", + "nb_inplace_remainder_impl", + PyNumberSlots.NB_INPLACE_REMAINDER, + _wrap_binaryfunc, + ), + NBSLOT( + "__ipow__", + "nb_inplace_power_impl", + PyNumberSlots.NB_INPLACE_POWER, + _wrap_binaryfunc, + ), + NBSLOT( + "__ilshift__", + "nb_inplace_lshift_impl", + PyNumberSlots.NB_INPLACE_LSHIFT, + _wrap_binaryfunc, + ), + NBSLOT( + "__irshift__", + "nb_inplace_rshift_impl", + PyNumberSlots.NB_INPLACE_RSHIFT, + _wrap_binaryfunc, + ), + NBSLOT( + "__iand__", + "nb_inplace_and_impl", + PyNumberSlots.NB_INPLACE_AND, + _wrap_binaryfunc, + ), + NBSLOT( + "__ixor__", + "nb_inplace_xor_impl", + PyNumberSlots.NB_INPLACE_XOR, + _wrap_binaryfunc, + ), + NBSLOT( + "__ior__", + "nb_inplace_or_impl", + PyNumberSlots.NB_INPLACE_OR, + _wrap_binaryfunc, + ), + NBSLOT( + "__floordiv__", + "nb_floor_divide_impl", + PyNumberSlots.NB_FLOOR_DIVIDE, + _wrap_binaryfunc, + ), + NBSLOT( + "__rfloordiv__", + "nb_floor_divide_impl", + PyNumberSlots.NB_FLOOR_DIVIDE, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__truediv__", + "nb_true_divide_impl", + PyNumberSlots.NB_TRUE_DIVIDE, + _wrap_binaryfunc, + ), + NBSLOT( + "__rtruediv__", + "nb_true_divide_impl", + PyNumberSlots.NB_TRUE_DIVIDE, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__ifloordiv__", + "nb_inplace_floor_divide_impl", + PyNumberSlots.NB_INPLACE_FLOOR_DIVIDE, + _wrap_binaryfunc, + ), + NBSLOT( + "__itruediv__", + "nb_inplace_true_divide_impl", + PyNumberSlots.NB_INPLACE_TRUE_DIVIDE, + _wrap_binaryfunc, + ), + NBSLOT( + "__index__", + "nb_index_impl", + PyNumberSlots.NB_INDEX, + _wrap_unaryfunc, + ), + NBSLOT( + "__matmul__", + "nb_matrix_multiply_impl", + PyNumberSlots.NB_MATRIX_MULTIPLY, + _wrap_binaryfunc, + ), + NBSLOT( + "__rmatmul__", + "nb_matrix_multiply_impl", + PyNumberSlots.NB_MATRIX_MULTIPLY, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__imatmul__", + "nb_inplace_matrix_multiply_impl", + PyNumberSlots.NB_INPLACE_MATRIX_MULTIPLY, + _wrap_binaryfunc, + ), + # Mapping + MPSLOT( + "__len__", + "mp_length_impl", + PyMappingSlots.MP_LENGTH, + _wrap_unaryfunc, + ), + MPSLOT( + "__getitem__", + "mp_subscript_impl", + PyMappingSlots.MP_SUBSCRIPT, + _wrap_binaryfunc, + ), + MPSLOT( + "__setitem__", + "mp_ass_subscript_impl", + PyMappingSlots.MP_ASS_SUBSCRIPT, + _wrap_objobjargproc, + ), + MPSLOT( + "__delitem__", + "mp_ass_subscript_impl", + PyMappingSlots.MP_ASS_SUBSCRIPT, + _wrap_delitem, + ), + # Sequence + SQSLOT( + "__len__", + "sq_length_impl", + PySequenceSlots.SQ_LENGTH, + _wrap_unaryfunc, + ), + SQSLOT( + "__add__", + "sq_concat_impl", + PySequenceSlots.SQ_CONCAT, + _wrap_binaryfunc, + ), + SQSLOT( + "__mul__", + "sq_repeat_impl", + PySequenceSlots.SQ_REPEAT, + _wrap_indexargfunc, + ), + SQSLOT( + "__rmul__", + "sq_repeat_impl", + PySequenceSlots.SQ_REPEAT, + _wrap_indexargfunc, + ), + SQSLOT( + "__getitem__", + "sq_item_impl", + PySequenceSlots.SQ_ITEM, + _wrap_sq_item, + ), + SQSLOT( + "__setitem__", + "sq_ass_item_impl", + PySequenceSlots.SQ_ASS_ITEM, + _wrap_sq_setitem, + ), + SQSLOT( + "__delitem__", + "sq_ass_item_impl", + PySequenceSlots.SQ_ASS_ITEM, + _wrap_sq_delitem, + ), + SQSLOT( + "__contains__", + "sq_contains_impl", + PySequenceSlots.SQ_CONTAINS, + _wrap_objobjproc, + ), + SQSLOT( + "__iadd__", + "sq_inplace_concat_impl", + PySequenceSlots.SQ_INPLACE_CONCAT, + _wrap_binaryfunc, + ), + SQSLOT( + "__imul__", + "sq_inplace_repeat_impl", + PySequenceSlots.SQ_INPLACE_REPEAT, + _wrap_indexargfunc, + ), +] + + +@functools.cache +def _compute_slotdefs(obj_type: type) -> dict[str, SlotDef]: + masks = get_type_slots(obj_type) + d: dict[str, SlotDef] = {} + for sd in _SLOTDEFS: + if sd.name in d: + continue + if has_slot(masks[sd.group.value], sd.slot): + d[sd.name] = sd + return d + + +class VariableTrackerMeta(type): + all_subclasses: list[type] = [] + + def __new__( + mcs: type, name: str, bases: tuple[type, ...], attrs: dict[str, Any] + ) -> type: + # Determine which metaclass to use based on the class attributes + # Classes with _no_implicit_realize = True should NOT implicitly realize + # (they need standard isinstance behavior to avoid infinite recursion) + # Check if any base class has _no_implicit_realize set, or if it's in attrs + no_implicit_realize = attrs.get("_no_implicit_realize", False) or any( + getattr(base, "_no_implicit_realize", False) for base in bases + ) + if no_implicit_realize or name == "VariableTracker": + # Use base VariableTrackerMeta (no custom __instancecheck__) + return super().__new__(VariableTrackerMeta, name, bases, attrs) + else: + # Use ImplicitRealizingVariableTrackerMeta for all other subclasses + return super().__new__( + ImplicitRealizingVariableTrackerMeta, name, bases, attrs + ) + + def __init__( + cls: type, name: str, bases: tuple[type, ...], attrs: dict[str, Any] + ) -> None: + super().__init__(name, bases, attrs) # type: ignore[misc] + VariableTrackerMeta.all_subclasses.append(cls) + + +class ImplicitRealizingVariableTrackerMeta(VariableTrackerMeta): + def __instancecheck__(self, instance: object) -> bool: + """Make isinstance work with LazyVariableTracker""" + if instancecheck(LazyVariableTracker, instance): + return instance.lazy_isinstance(self) # pyrefly: ignore[missing-attribute] + return instancecheck(self, instance) + + +class VariableTracker(metaclass=VariableTrackerMeta): + """ + Base class for tracked locals and stack values + + VariableTracker instances are immutable and should be copied in + order to change them. + + Prefer the factory function VariableTracker.build() over VariableTracker.__init__(). + """ + + # The CPython type(s) this VT is designed to represent. + # Single type or tuple of types. None means no static CPython type mapping + # (e.g., dynamic types like UserDefinedObjectVariable, or Dynamo-internal VTs). + _cpython_type: type | tuple[type, ...] | None = None + + # Declarative named-method table (analogous to CPython's tp_methods): maps a + # method name to a Method describing its handler and calling convention. + # `call_method` consults this before the object-protocol (tp_slot) dispatch. + # Lookup walks the class MRO (see `_lookup_tp_table`), so a subclass table + # adds to (rather than replaces) the entries it inherits, with the + # most-derived class winning on name collisions. + tp_methods: dict[str, Method] = {} + # Declarative attribute tables, split to match CPython: tp_getset holds the + # PyGetSetDef attributes, tp_members the PyMemberDef ones. + tp_getset: dict[str, GetSet] = {} + tp_members: dict[str, Member] = {} + + def _lookup_tp_table(self, name: str, *table_attrs: str) -> Any: + """Resolve *name* in the given declarative tables across the class MRO. + + Mirrors CPython method/getset/member inheritance: each class contributes + its own table entries into its own tp_dict, and lookup walks the MRO with + the most-derived class winning. A subclass table therefore *adds* to + (rather than replaces) the entries it inherits. Within a class the tables + are consulted in the order given. + """ + for klass in type(self).__mro__: + d = klass.__dict__ + for attr in table_attrs: + table = d.get(attr) + if table is not None and name in table: + return table[name] + return None + + def lookup_tp_getset_member(self, name: str) -> GetSet | Member | None: + return self._lookup_tp_table(name, "tp_getset", "tp_members") + + def lookup_tp_method(self, name: str) -> Method | None: + return self._lookup_tp_table(name, "tp_methods") + + def method_flags_type(self) -> type: + """Type whose CPython ml_flags define this VT's tp_methods arities + (see _derive_method_flags). Defaults to python_type(); a VT whose + python_type() is a pure-Python stand-in without C ml_flags (e.g. + OrderedSet) overrides this to the builtin whose method arities it + mirrors, so MethodFlags still enforces arity.""" + return maybe_get_python_type(self) + + # fields to leave unmodified in apply() + _nonvar_fields = { + "value", + "guards", + "source", + "source_location", + "mutation_type", + "parents_tracker", + "user_code_variable_name", + "dict_vt", + } + + # Lazily-created view of the instance __dict__, backed by the side effects table + dict_vt: variables.DunderDictVariable | None = None + + def clone(self, **kwargs: Any) -> VariableTracker: + """Shallow copy with some (optional) changes""" + args = dict(self.__dict__) + args.update(kwargs) + return self.__class__(**args) + + @classmethod + def visit( + cls, + fn: Callable[[VariableTracker], None], + value: Any, + cache: dict[int, Any] | None = None, + side_effects: SideEffects | None = None, + ) -> None: + """ + Walk value and call fn on all the VariableTracker instances. + + When side_effects is provided, also walks attributes stored in + store_attr_mutations (e.g. dataclass fields set during tracing + that aren't in the VT's __dict__). + + Implemented with an explicit worklist rather than recursion so that + deeply chained structures (e.g. the ~N-node buffer built by + itertools.tee over a long iterable) do not overflow the Python stack. + Children are pushed in reverse so they are popped in their original + order, matching the pre-order DFS the previous recursive version + produced (callers rely on the visitation order, e.g. for graph output + ordering). + """ + if cache is None: + cache = {} + + worklist = [value] + while worklist: + cur = worklist.pop() + idx = id(cur) + if idx in cache: + continue + # save `cur` to keep it alive and ensure id() isn't reused + cache[idx] = cur + + children: list[Any] + if isinstance(cur, VariableTracker): + cur = cur.unwrap() + fn(cur) + cur = cur.unwrap() # calling fn() might have realized it + nonvars = cur._nonvar_fields + children = [ + subvalue + for key, subvalue in cur.__dict__.items() + if key not in nonvars + ] + if ( + side_effects is not None + and cur in side_effects.store_attr_mutations + ): + children.extend(side_effects.store_attr_mutations[cur].values()) + elif istype(cur, (list, tuple)): + children = list(cur) + elif istype(cur, (dict, collections.OrderedDict)): + children = list(cur.values()) + else: + continue + worklist.extend(reversed(children)) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}()" + + def debug_repr(self) -> str: + # Intended to be overridden to provide more info + try: + return repr(self.as_python_constant()) + except NotImplementedError: + return repr(self) + + def python_type(self) -> type: + """ + Abstract method to be implemented by subclasses of VariableTracker. + + This method should return the type represented by the instance of the subclass. + The purpose is to provide a standardized way to retrieve the Python type information + of the variable being tracked. + + Returns: + type: The Python type (such as int, str, list, etc.) of the variable tracked by + the subclass. If the type cannot be determined or is not relevant, + leaving it undefined or invoking super() is always sound. + + Note: + This is an abstract method and may be overridden in subclasses. + + Example: + class SetVariable(VariableTracker): + def python_type(self): + return set + + Raises: + NotImplementedError: If the method is not implemented in a subclass. + """ + try: + return type(self.as_python_constant()) + except NotImplementedError: + raise NotImplementedError(f"{self} has no type") from None + + def python_type_name(self) -> str: + """ + Return the type name for the Python type this VariableTracker represents. + + Mirrors CPython's tp_name slot (PyTypeObject.tp_name). In Python 3.10+, + type.__name__ matches CPython's tp_name exactly (e.g., "list", "NoneType"). + + Note: There are no external callers outside torch._dynamo that rely on this. + Internal uses should prefer this over hardcoded type name strings. + """ + try: + return self.python_type().__name__ + except NotImplementedError: + return "" + + def python_qualified_name(self) -> str: + """ + Equivalent to _PyType_GetFullyQualifiedName + + See https://github.com/python/cpython/blob/v3.15.0b4/Objects/typeobject.c#L1658 + """ + try: + type_ = self.python_type() + except NotImplementedError: + return "" + # Direct attribute access is safe here because type objects use the getset protocol, which will only return str + # (and not execute user code) + mod = type_.__module__ + qn = type_.__qualname__ + if mod not in ("__main__", "builtins"): + return f"{mod}.{qn}" + else: + return qn + + def as_python_constant(self) -> Any: + """For constants""" + raise AsPythonConstantNotImplementedError(self) + + def guard_as_python_constant(self) -> Any: + """Similar to as_python_constant(), but add ID_MATCH guards to try to force things to become constants""" + try: + return self.as_python_constant() + except NotImplementedError: + unimplemented( + gb_type="Not a Python constant", + context=f"guard_as_python_constant {self}", + explanation=f"Failed to convert {self} into a Python constant.", + hints=[], + ) + + def is_python_constant(self) -> bool: + try: + self.as_python_constant() + return True + except NotImplementedError: + return False + + def nb_bool_impl(self, tx: InstructionTranslatorBase) -> VariableTracker | None: + # Mirrors CPython's tp_as_number->nb_bool slot. + # https://github.com/python/cpython/blob/c09ccd9c429/Objects/object.c#L2135-L2158 + # + # Returns None when the type has no nb_bool, causing generic_is_true to + # fall through to length check, then truthy default. + return None + + def is_hashable(self) -> bool: + """Whether the underlying Python object is hashable. + + Defaults to True — in CPython, all objects are hashable unless the type + explicitly sets __hash__ = None (PyObject_HashNotImplemented). + https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L7288 + + Subclasses override to return False for unhashable types (list, dict, + set, etc.). This is a fast, side-effect-free check used by + HashableTracker and __contains__ before attempting to hash. + """ + return True + + def hash_impl(self, tx: InstructionTranslatorBase) -> tuple[int, bool]: + """Default tp_hash: object.__hash__ = PyObject_GenericHash (identity hash). + + PyObject_GenericHash: https://github.com/python/cpython/blob/e76aa128fe/Python/pyhash.c#L143-L147 + Assigned on object: https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L7288 + + Returns (hash_value, is_fake). is_fake=True means the hash depends on + a sourceless object's identity and must not escape into output bytecode. + + VT subclasses override this for types with their own C tp_hash. + UserDefinedObjectVariable.hash_impl handles the MRO walk for custom + Python __hash__, builtin-inherited C hash, and unknown C tp_hash. + """ + # object.__hash__ = Py_HashPointer(obj) — identity hash. + if self.source: + real_val = tx.output.resolve_source_value(self.source) + if type(real_val).__hash__ is not object.__hash__: + unimplemented( + gb_type="Missing hash_impl override", + context=f"hash_impl {self}", + explanation=f"{type(self).__name__} wraps " + f"{type(real_val).__name__} which has a non-default " + f"tp_hash. Add a hash_impl override to " + f"{type(self).__name__}.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + # object.__hash__ = id(obj), so the hash is identity-based. + # Return is_fake=True so the hash is only usable internally + # (dict keys, set membership) and doesn't escape into bytecode + # — avoids installing an ID_MATCH guard just for hashing. + # TODO when LazyConstants are fully landed, we can use them here instead. + return hash(real_val), True + # Sourceless: no real object to hash — fake id. + return id(self), True + + def tp_richcompare_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + op: str, + ) -> VariableTracker: + """Per-VT tp_richcompare slot. Subclasses must override. + + Analogous to CPython's tp_richcompare function pointer on PyTypeObject. + Returns ConstantVariable(NotImplemented) when the type does not handle + the comparison (signaling do_richcompare to try the other operand). + + Called from two paths: + - call_method("__eq__") calls tp_richcompare_impl directly (like CPython's + a.__eq__(b) calling tp_richcompare without do_richcompare). + - generic_richcompare calls tp_richcompare_impl as part of the 4-step + do_richcompare algorithm (subclass priority, forward, reflected, + fallback). + """ + unimplemented( + gb_type="Missing tp_richcompare_impl override", + context=f"tp_richcompare_impl {self} {op}", + explanation=f"{type(self).__name__} does not implement " + f"tp_richcompare_impl. Add a tp_richcompare_impl override to " + f"{type(self).__name__}.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + def is_constant_match(self, *values: Any) -> bool: + """ + Check if this variable is a python constant matching one of the given values. + + Examples: + var.is_constant_match(None) # True if var is constant None + var.is_constant_match(True, False) # True if var is constant True or False + var.is_constant_match(NotImplemented) # True if var is constant NotImplemented + """ + return False + + def is_constant_none(self) -> bool: + """Check if this variable is a constant None value.""" + return False + + def make_guard(self, fn: Callable[..., Any]) -> Guard: + if self.source: + return self.source.make_guard(fn) + raise NotImplementedError + + def const_getattr(self, tx: InstructionTranslatorBase, name: str) -> Any: + """getattr(self, name) returning a python constant""" + raise NotImplementedError + + def is_symnode_like(self) -> bool: + """Return True for values that can participate in SymNode operations""" + return False + + def is_tensor(self) -> bool: + """Return True for TensorVariable instances""" + return False + + def get_handler_type_for_dispatch(self) -> type[VariableTracker]: + """Return the VariableTracker type to use for builtin handler dispatch. + + This is used by BuiltinVariable to look up the appropriate handler for + a given set of arguments. Most VariableTrackers just return their own + type, but LazyConstantVariable returns ConstantVariable since it can + be treated as a constant for most builtin operations. + + Subclasses that override this should install appropriate guards to + ensure the dispatched handler remains valid. + """ + return type(self) + + def get_value_for_setattr(self) -> object | None: + """Return the wrapped Python object for generic STORE_ATTR mutation, + or None to decline. Only override for VTs with __dict__ and + standard __setattr__.""" + return None + + def lookup_instance_dict( + self, tx: InstructionTranslatorBase, name: str + ) -> VariableTracker | None: + """Look up *name* in the instance __dict__ (tp_dictoffset equivalent). + + Returns a VT if the attribute exists in the instance dict, None if + the attribute is absent or the VT has no instance dict at all. + UDOV overrides to check self.value.__dict__ + side effects. + """ + return None + + def call_getattr_fallback( + self, tx: InstructionTranslatorBase, name: str + ) -> VariableTracker | None: + """Call __getattr__ fallback (step 6 of GenericGetAttr). + + Returns a VT if the type defines __getattr__ and it succeeds, + None otherwise. The base returns None (most types have no + __getattr__). UDOV overrides to walk the MRO for __getattr__. + """ + return None + + def tp_getattro_impl( + self, tx: InstructionTranslatorBase, name: str + ) -> VariableTracker: + """Default attribute access via object_generic_getattr. + + Tries the MRO-based descriptor protocol first (PyObject_GenericGetAttr), + falls back to const_getattr for VTs without a known python_type or + when the descriptor protocol hits an unhandled type. + """ + # tp_getset/tp_members are data descriptors: resolve ahead of the + # object-protocol walk. A getter returning None declines. + getset = self.lookup_tp_getset_member(name) + if getset is not None: + result = getset.getter(self, tx) + if result is not None: + return result + + # object.__class__: one shared getset on `object` rather than per-VT. + if name == "__class__": + return VariableTracker.build(tx, self.python_type()) + + try: + py_type = self.python_type() + except NotImplementedError: + py_type = None + + if py_type is not None: + from .object_protocol import ( + _UnhandledDescriptorError, + object_generic_getattr, + ) + + try: + return object_generic_getattr(tx, self, name) + except _UnhandledDescriptorError: + pass + + value = self.const_getattr(tx, name) + if not variables.ConstantVariable.is_literal(value): + raise NotImplementedError + source = self.source and AttrSource(self.source, name) + if source and not self.is_python_constant(): + # Skip guards on const getattr objects like __code__.co_argcount + install_guard(source.make_guard(GuardBuilder.CONSTANT_MATCH)) + return variables.ConstantVariable.create(value, source=source) + + def get_dict_vt( + self, tx: InstructionTranslatorBase + ) -> variables.DunderDictVariable: + # Callers gate this on the object actually having an instance __dict__ + # (e.g. the per-VT `__dict__` attribute branches). If a VT without a + # real instance dict reaches here, DunderDictVariable's example-value + # lookup graph-breaks rather than fabricating a bogus dict. + if self.dict_vt is None: + self.dict_vt = variables.DunderDictVariable.create(tx, self) + return self.dict_vt + + def is_proxy(self) -> bool: + try: + self.as_proxy() + return True + except NotImplementedError: + return False + + def as_proxy(self) -> Any: + raise NotImplementedError(str(self)) + + def maybe_fx_node(self) -> Node | None: + try: + proxy = self.as_proxy() + import torch.fx + + if isinstance(proxy, torch.fx.Proxy): + return proxy.node + return None + except NotImplementedError: + return None + + def _contains_self_reference(self) -> bool: + """Check if this variable references itself (directly or indirectly).""" + found_self = False + + def check(vt: VariableTracker) -> None: + nonlocal found_self + if vt is self: + found_self = True + + # unwrap first iteration - otherwise we can't detect if we revisit self + for key, subvalue in self.__dict__.items(): + if key not in self._nonvar_fields: + VariableTracker.visit(check, subvalue) + + return found_self + + def reconstruct(self, codegen: PyCodegen) -> None: + raise NotImplementedError + + def reconstruct_pycode(self, codegen: PyCodegen) -> str: + raise NotImplementedError(f"reconstruct_pycode not implemented for {self}") + + def unpack_var_sequence( + self, tx: InstructionTranslatorBase + ) -> list[VariableTracker]: + raise NotImplementedError + + def _hasattr_check_side_effects( + self, tx: InstructionTranslatorBase, name: str + ) -> ConstantVariable | None: + """If *name* has a pending mutation, return the hasattr result; else None.""" + if tx.output.side_effects.has_pending_mutation_of_attr(self, name): + value = tx.output.side_effects.load_attr(self, name, deleted_ok=True) + return variables.ConstantVariable.create( + not isinstance(value, variables.DeletedVariable) + ) + return None + + def call_obj_hasattr( + self, tx: InstructionTranslatorBase, name: str + ) -> ConstantVariable: + """Dynamo's hasattr(): try tp_getattro_impl, catch AttributeError. + + Mirrors CPython's PyObject_HasAttr (via PyObject_GetOptionalAttr): + call tp_getattro, suppress AttributeError via PyErr_Clear, return + True/False. + https://github.com/python/cpython/blob/848cb25624ab44c9fef2966c777419376b65af1b/Objects/object.c#L1346 + """ + result = self._hasattr_check_side_effects(tx, name) + if result is not None: + return result + + try: + self.tp_getattro_impl(tx, name) + return variables.ConstantVariable.create(True) + except ObservedAttributeError: + tx.exn_vt_stack.clear_current_exception() + return variables.ConstantVariable.create(False) + except (NotImplementedError, Unsupported): + pass + + unimplemented( + gb_type="Unsupported hasattr call", + context=f"call_obj_hasattr {self} {name}", + explanation=f"Dynamo does not know how to trace the function `{self.debug_repr()}`", + hints=[ + f"Avoid calling `hasattr({self.__class__.__name__}, {name})` in your code.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def tp_iter_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """ + Implements PyObject_GetIter semantics (tp_iter slot). + Subclasses override this to support iteration. + """ + # PyObject_GetIter: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L2847-L2870 + # TODO: raise TypeError instead - Make sure the jit tests for ScriptDict/ScriptList works with + # this change + unimplemented( + gb_type="missing tp_iter", + context=f"tp_iter_impl not implemented for {self.python_type_name()}", + explanation=f"Dynamo does not know how to iterate over `{self.debug_repr()}`.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def tp_init_impl( + self, + tx: InstructionTranslatorBase, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """tp_init slot (__init__). VTs override to initialize instances.""" + unimplemented( + gb_type="missing tp_init", + context=f"tp_init_impl not implemented for {self.python_type_name()}", + explanation=f"Dynamo does not know how to trace __init__ on `{self.debug_repr()}`.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + def call_function( + self, + tx: InstructionTranslatorBase, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Reaching this base fallback means no subclass handled the call. If the + # object's type has no tp_call slot, it is genuinely not callable, so + # mirror CPython's PyObject_Call TypeError. Otherwise the type is + # callable in principle but unsupported by Dynamo -> graph break. + from .object_protocol import pycallable_check + + try: + obj_type = self.python_type() + except NotImplementedError: + obj_type = None + if obj_type is not None and not pycallable_check(obj_type): + raise_type_error(tx, f"'{self.python_type_name()}' object is not callable") + unimplemented( + gb_type="Unsupported function call", + context=f"call_function {self} {args} {kwargs}", + explanation=f"Dynamo does not know how to trace the function `{self.debug_repr()}`", + hints=[ + f"Avoid calling `{self.debug_repr()}` in your code.", + "Please report an issue to PyTorch.", + ], + ) + + def sq_length_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """Called when sq_length is not implemented.""" + raise_observed_exception( + TypeError, + tx, + args=[f"object of type '{self.python_type_name()}' has no len()"], + ) + + def mp_length_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """Called when mp_length is not implemented.""" + raise_observed_exception( + TypeError, + tx, + args=[f"object of type '{self.python_type_name()}' has no len()"], + ) + + def mp_subscript_impl( + self, + tx: InstructionTranslatorBase, + key: VariableTracker, + ) -> VariableTracker: + # PyObject_GetItem: https://github.com/python/cpython/blob/62a6e898e01/Objects/abstract.c#L155-L206 + # generic_getitem handles dispatch and raises TypeError for non-subscriptable + # objects. This base fallback fires for types with mp_subscript at the + # C level but no Dynamo override yet. + unimplemented( + gb_type="missing_mp_subscript", + context=f"mp_subscript_impl not defined for {type(self).__name__}", + explanation=f"Dynamo does not yet support subscripting '{self.python_type_name()}'.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def sq_item_impl( + self, + tx: InstructionTranslatorBase, + key: VariableTracker, + ) -> VariableTracker: + # PyObject_GetItem Branch 2: tp_as_sequence->sq_item + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L168-L181 + # Key has already been converted to int via nb_index_impl by generic_getitem. + unimplemented( + gb_type="unsupported __getitem__ (sq_item)", + context=f"sq_item_impl {self} {key}", + explanation=f"Dynamo does not know how to handle sq_item on {self}", + hints=[], + ) + + def sq_contains_impl( + self, tx: InstructionTranslatorBase, item: VariableTracker + ) -> VariableTracker: + """Called when sq_contains is not implemented.""" + unimplemented( + gb_type="missing sq_contains", + context=f"sq_contains_impl not implemented for {self.python_type_name()}", + explanation=f"Dynamo does not know how to check if `{item.debug_repr()}` is in `{self.debug_repr()}`.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def mp_ass_subscript_impl( + self, + tx: InstructionTranslatorBase, + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + unimplemented( + gb_type="missing_mp_ass_subscript", + context=f"mp_ass_subscript_impl not defined for {self.python_type_name()}", + explanation=f"Dynamo does not yet support item assignment on '{self.python_type_name()}'.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def sq_ass_item_impl( + self, + tx: InstructionTranslatorBase, + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + unimplemented( + gb_type="unsupported __setitem__ (sq_ass_item)", + context=f"sq_ass_item_impl {self} {key} {value}", + explanation=f"Dynamo does not know how to handle sq_ass_item on {self}", + hints=[], + ) + + def sq_concat_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """Sequence concatenation via + operator (sq_concat slot).""" + unimplemented( + gb_type="missing sq_concat", + context=f"sq_concat not defined for {type(self).__name__}", + explanation=f"Dynamo does not yet support concatenating '{self.python_type_name()}' and '{other.python_type_name()}'", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def sq_inplace_concat_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """In-place sequence concatenation via += operator (sq_inplace_concat slot).""" + unimplemented( + gb_type="missing sq_inplace_concat", + context=f"sq_inplace_concat not defined for {type(self).__name__}", + explanation=f"Dynamo does not yet support inplace concat of '{self.python_type_name()}' and '{other.python_type_name()}'", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def call_method( + self, + tx: InstructionTranslatorBase, + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Declarative named-method dispatch (tp_methods). A handler returning + # None declines the call and falls through to the object-protocol + # (tp_slot) dispatch below, mirroring the old super().call_method path. + method = self.lookup_tp_method(name) + if method is not None: + result = method(self, tx, name, args, kwargs) + if result is not None: + return result + + slotdef = self._slotdefs.get(name) + if slotdef is not None: + return slotdef(self, tx, args, kwargs) + + if name == "__hash__" and not args and not kwargs: + from .object_protocol import generic_hash + + return generic_hash(tx, self) + + if name == "__subclasscheck__" and len(args) == 1 and not kwargs: + if (self_py := self.as_python_constant()) and ( + derived_py := args[0].as_python_constant() + ): + if ( + inspect.getattr_static(self_py, "__subclasscheck__", None) + is type.__subclasscheck__ + ): + return variables.ConstantVariable.create( + issubclass(derived_py, self_py) + ) + # __reduce_ex__ is a C builtin (object.__reduce_ex__) that Dynamo + # cannot trace into. Constant-fold it for VTs backed by a real + # Python object so that copy.deepcopy can trace through. + if ( + name == "__reduce_ex__" + and len(args) == 1 + and not kwargs + and self.is_python_constant() + ): + protocol = args[0].as_python_constant() + return VariableTracker.build( + tx, self.as_python_constant().__reduce_ex__(protocol) + ) + + hints = [ + f"Avoid calling `{self.python_type_name()}.{name}` in your code.", + "Please report an issue to PyTorch.", + ] + # additional hint for method calls on improperly constructed iterators + if isinstance(self, variables.UserDefinedObjectVariable) and name in ( + "__iter__", + "__next__", + ): + if isinstance(self.value, (KeysView, ItemsView, ValuesView)): + hints.append( + "Consider moving the creation of dict view object (e.g. `dict.keys()`, `dict.items()`,) " + "to the compiled region, instead of passing it as an input to the compiled region." + ) + hints.append( + "Dynamo does not fully support tracing builtin iterators (e.g. `map`, `zip`, `enumerate`) " + "passed in from uncompiled to compiled regions (e.g. `torch.compile(fn)(enumerate(...))`). " + "This can happen unintentionally if a previous graph break happens with a builtin iterator " + "in the local scope." + ) + hints.append( + "List/dict comprehensions in Python <= 3.11 result in implicit function calls, which Dynamo " + "cannot trace as a top level frame. Possible workarounds are (1) use a loop instead of a comprehension, " + "(2) fix any graph breaks in the function above the comprehension, (3) wrap the comprehension in a " + "function, or (4) use Python 3.12+." + ) + unimplemented( + gb_type="Unsupported method call", + context=f"call_method {self} {name} {args} {kwargs}", + explanation=f"Dynamo does not know how to trace method `{name}` of class `{self.python_type_name()}`", + hints=hints, + ) + + def call_tree_map( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """Performance optimization to implement optree.tree_map faster than tracing it""" + is_leaf_var = tree_map_kwargs.get("is_leaf") + if is_leaf_var is not None and not is_leaf_var.is_constant_none(): + pred_result = is_leaf_var.call_function(tx, [self], {}) + try: + leaf_decision = pred_result.as_python_constant() + except NotImplementedError: + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + if leaf_decision: + return map_fn.call_function(tx, [self, *rest], {}) + + return self.call_tree_map_branch( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + + def call_tree_map_branch( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """Emulate optree.tree_map without is_leaf/none_is_leaf checks (handled above)""" + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + + def _tree_map_fallback( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tree_map_fn_copy = tree_map_fn.clone() + tree_map_fn_copy._maybe_call_tree_map_fastpath = lambda *args, **kwargs: None # type: ignore[missing-attribute] + log.debug( + "tree_map fastpath fallback triggered for %s (rest=%s, kwargs=%s)", + self, + rest, + tree_map_kwargs, + ) + return tree_map_fn_copy.call_function( + tx, + [map_fn, self, *rest], + tree_map_kwargs, + ) + + def call_tree_map_with_path( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + keypath: tuple[Any, ...], + ) -> VariableTracker: + """Performance optimization to implement tree_map_with_path faster than tracing it""" + is_leaf_var = tree_map_kwargs.get("is_leaf") + if is_leaf_var is not None and not is_leaf_var.is_constant_none(): + pred_result = is_leaf_var.call_function(tx, [self], {}) + try: + leaf_decision = pred_result.as_python_constant() + except NotImplementedError: + return self._tree_map_with_path_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath, + ) + if leaf_decision: + keypath_var = variables.TupleVariable( + [VariableTracker.build(tx, k) for k in keypath] + ) + return map_fn.call_function(tx, [keypath_var, self, *rest], {}) + + return self.call_tree_map_with_path_branch( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath, + ) + + def call_tree_map_with_path_branch( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + keypath: tuple[Any, ...], + ) -> VariableTracker: + """Handle tree_map_with_path for leaf nodes (default behavior)""" + keypath_var = variables.TupleVariable( + [VariableTracker.build(tx, k) for k in keypath] + ) + return map_fn.call_function(tx, [keypath_var, self, *rest], {}) + + def _tree_map_with_path_fallback( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + keypath: tuple[Any, ...], + ) -> VariableTracker: + tree_map_fn_copy = tree_map_fn.clone() + tree_map_fn_copy._maybe_call_tree_map_fastpath = lambda *args, **kwargs: None # type: ignore[missing-attribute] + log.debug( + "tree_map_with_path fastpath fallback triggered for %s (rest=%s, kwargs=%s, keypath=%s)", + self, + rest, + tree_map_kwargs, + keypath, + ) + return tree_map_fn_copy.call_function( + tx, + [map_fn, self, *rest], + tree_map_kwargs, + ) + + def set_name_hint(self, name: str) -> None: + pass + + def set_source_location(self, source_location: SourceLocation) -> None: + self.source_location = source_location + + def realize(self) -> VariableTracker: + """Used by LazyVariableTracker to build the real VariableTracker""" + return self + + def unwrap(self) -> VariableTracker: + """Used by LazyVariableTracker to return the real VariableTracker if it already exists""" + return self + + def is_realized(self) -> bool: + """Used by LazyVariableTracker to indicate an unrealized node""" + return True + + def tp_iternext_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """ + Implements tp_iternext slot semantics. + Subclasses override this to support next(). Reaching this base is a + bug — it means tp_iternext is missing for that VariableTracker subclass. + """ + unimplemented( + gb_type="Missing tp_iternext", + context=f"next({self.python_type_name()})", + explanation=( + f"Dynamo does not support next() on {self.python_type_name()}." + " Add tp_iternext_impl to this VariableTracker subclass." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def next_variable(self, tx: InstructionTranslatorBase) -> VariableTracker: + return self.tp_iternext_impl(tx) + + def is_strict_mode(self, tx: InstructionTranslatorBase) -> bool: + return bool(tx.strict_checks_fn and tx.strict_checks_fn(self)) + + def is_mutable(self) -> bool: + """Whether Dynamo allows mutation on this variable.""" + return not self.is_immutable() + + def is_immutable(self) -> bool: + """Whether Dynamo bans mutation on this variable.""" + return self.mutation_type is None + + @staticmethod + def build( + tx: InstructionTranslatorBase, + value: Any, + source: Source | None = None, + realize: bool = False, + ) -> Any: + """Create a new VariableTracker from a value and optional Source""" + if source is None: + return builder.SourcelessBuilder.create(tx, value) + elif realize: + return builder.VariableBuilder(tx, source)(value) + elif type(value) in variables.LazyConstantVariable.supported_types: + # Use LazyConstantVariable for primitives to enable deferred + # guard installation - constants that are just passed through + # won't cause recompilation when their values change. + return variables.LazyConstantVariable.create(value, source) + else: + return variables.LazyVariableTracker.create(value, source, tx=tx) + + def get_id(self, tx: InstructionTranslatorBase) -> int | None: + """Return id() of the underlying Python object, or None if unavailable. + + The base implementation uses source resolution for sourceful VTs. + Subclasses override for special cases (e.g. NNModuleVariable uses + get_submodule, ConstantVariable handles singletons). + + Returns None for sourceless VTs — callers use FakeIdVariable in + that case (see generic_id in object_protocol.py). + """ + if self.source: + return id(tx.output.resolve_source_value(self.source)) + return None + + def get_id_guard_type(self) -> Callable[..., Any] | None: + if self.source: + return GuardBuilder.ID_MATCH + return None + + def get_real_python_backed_value(self) -> object: + """Return the Python object this VT wraps, for `is` comparison. + + Returns NO_SUCH_SUBOBJ if no concrete Python object is available. + """ + + try: + return self.as_python_constant() + except NotImplementedError: + return NO_SUCH_SUBOBJ + + def nb_index_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's PyNumber_Index / nb_index slot. + + https://github.com/python/cpython/blob/c09ccd9c429/Objects/abstract.c#L1411-L1450 + + The base implementation raises TypeError, matching CPython's behavior + when tp_as_number->nb_index is NULL (_PyIndex_Check fails). + """ + raise_observed_exception( + TypeError, + tx, + args=[ + f"'{self.python_type_name()}' object cannot be interpreted as an integer" + ], + ) + + def tp_repr_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_repr slot. + + https://github.com/python/cpython/blob/v3.13.3/Objects/object.c#L745-L778 + + Called when type_implements_tp_repr returns True for this type. + Subclasses override to provide the actual repr implementation. + """ + unimplemented( + gb_type="tp_repr_impl not implemented", + context=f"{type(self).__name__} has tp_repr slot but no tp_repr_impl override", + explanation=f"The type {self.python_type_name()} has a tp_repr C slot but " + "the corresponding VariableTracker doesn't implement tp_repr_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def tp_str_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Dynamo hook for VariableTrackers with dedicated str behavior. + Subclasses override this for the per-type str result; generic_str() + handles dispatch and repr fallback. + """ + unimplemented( + gb_type="tp_str_impl not implemented", + context=f"{type(self).__name__} has no tp_str_impl override for {self.python_type_name()}", + explanation=f"Dynamo does not implement __str__ for {self.python_type_name()} " + f"in {type(self).__name__}.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_int_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_int slot. + + Called when type_implements_nb_int returns True for this type. + Subclasses override to provide the actual conversion. + """ + unimplemented( + gb_type="nb_int_impl not implemented", + context=f"{type(self).__name__} has nb_int slot but no nb_int_impl override", + explanation=f"The type {self.python_type_name()} has an nb_int C slot but " + "the corresponding VariableTracker doesn't implement nb_int_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_float_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_float slot. + + Called when type_implements_nb_float returns True for this type. + Subclasses override to provide the actual conversion. + """ + unimplemented( + gb_type="nb_float_impl not implemented", + context=f"{type(self).__name__} has nb_float slot but no nb_float_impl override", + explanation=f"The type {self.python_type_name()} has an nb_float C slot but " + "the corresponding VariableTracker doesn't implement nb_float_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def _nb_slot_not_implemented( + self, + tp_slot_name: str, + other: VariableTracker, + reverse: bool = False, + ): + unimplemented( + gb_type="tp_as_number slot not implemented", + context=f"{tp_slot_name}({self.python_type_name()}, {other.python_type_name()}, reverse={reverse})", + explanation=f"The type {self.python_type_name()} does not implement the {tp_slot_name}", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_lshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_lshift slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rlshift__`` instead of ``__lshift__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_lshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_lshift slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_rshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_rshift slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rrshift__`` instead of ``__rshift__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_rshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_rshift slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_and_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_and slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rand__`` instead of ``__and__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_and_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_and slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_xor_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_xor slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rxor__`` instead of ``__xor__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_xor_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_xor slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_floor_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_floor_divide slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rfloordiv__`` instead of ``__floordiv__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_floor_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_floor_divide slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_true_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_true_divide slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rtruediv__`` instead of ``__truediv__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_true_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_true_divide slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_remainder_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_remainder slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rmod__`` instead of ``__mod__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_remainder_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_remainder slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_divmod_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_divmod slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rdivmod__`` instead of ``__divmod__``). divmod has no + in-place form. + """ + return variables.ConstantVariable(NotImplemented) + + def nb_power_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + z: VariableTracker | None, + reverse: bool = False, + ) -> VariableTracker: + return variables.ConstantVariable(NotImplemented) + + def nb_power_z_impl( + self, + tx: InstructionTranslatorBase, + v: VariableTracker, + w: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_power slot when self is the modulus (z) operand. + + ``v`` is the base, ``w`` is the exponent, ``self`` is the modulus. + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_power_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + z: VariableTracker | None, + ) -> VariableTracker: + return variables.ConstantVariable(NotImplemented) + + def nb_multiply_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_multiply slot. Default: graph-breaks. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rmul__`` instead of ``__mul__``). The base default + graph-breaks so unmigrated VTs surface loudly; ``binary_op1`` only + invokes this on types whose CPython type advertises the slot. + """ + return self._nb_slot_not_implemented("nb_multiply_impl", other, reverse=reverse) + + def nb_inplace_multiply_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_multiply slot. Default: graph-breaks.""" + return self._nb_slot_not_implemented("nb_inplace_multiply_impl", other) + + def nb_matrix_multiply_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_matrix_multiply slot. Default: graph-breaks. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rmatmul__`` instead of ``__matmul__``). + """ + return self._nb_slot_not_implemented( + "nb_matrix_multiply_impl", other, reverse=reverse + ) + + def nb_inplace_matrix_multiply_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_matrix_multiply slot. Default: graph-breaks.""" + return self._nb_slot_not_implemented("nb_inplace_matrix_multiply_impl", other) + + def sq_repeat_impl( + self, + tx: InstructionTranslatorBase, + count: VariableTracker, + ) -> VariableTracker: + """tp_as_sequence->sq_repeat slot. + + Implements sequence repetition (e.g. ``[1, 2] * 3``). ``count`` is + an int VariableTracker already produced by ``nb_index_impl``. + """ + unimplemented( + gb_type="sq_repeat_impl not implemented", + context=f"{type(self).__name__} has sq_repeat slot but no sq_repeat_impl override", + explanation=f"The type {self.python_type_name()} has an sq_repeat C slot but " + "the corresponding VariableTracker doesn't implement sq_repeat_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def sq_inplace_repeat_impl( + self, + tx: InstructionTranslatorBase, + count: VariableTracker, + ) -> VariableTracker: + """tp_as_sequence->sq_inplace_repeat slot.""" + unimplemented( + gb_type="sq_inplace_repeat_impl not implemented", + context=f"{type(self).__name__} has sq_inplace_repeat slot but no sq_inplace_repeat_impl override", + explanation=f"The type {self.python_type_name()} has an sq_inplace_repeat C slot but " + "the corresponding VariableTracker doesn't implement sq_inplace_repeat_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_or_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_or slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__ror__`` instead of ``__or__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_or_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_or slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_negative_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_negative slot. + + Called when type_implements_nb_negative returns True for this type. + Subclasses override to provide the actual negation. + """ + unimplemented( + gb_type="nb_negative_impl not implemented", + context=f"{type(self).__name__} has nb_negative slot but no nb_negative_impl override", + explanation=f"The type {self.python_type_name()} has an nb_negative C slot but " + "the corresponding VariableTracker doesn't implement nb_negative_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_positive_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_positive slot. + + Called when type_implements_nb_positive returns True for this type. + Subclasses override to provide the actual positive. + """ + unimplemented( + gb_type="nb_positive_impl not implemented", + context=f"{type(self).__name__} has nb_positive slot but no nb_positive_impl override", + explanation=f"The type {self.python_type_name()} has an nb_positive C slot but " + "the corresponding VariableTracker doesn't implement nb_positive_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_add_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_add slot. Default: graph break. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__radd__`` instead of ``__add__``). + """ + # We need to return NotImplemented here because of sq_concat + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_add_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_add slot. Default: graph break.""" + # We need to return NotImplemented here because of sq_inplace_concat + return variables.ConstantVariable(NotImplemented) + + def nb_subtract_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_subtract slot. Default: graph break. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rsub__`` instead of ``__sub__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_subtract_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_subtract slot. Default: graph break.""" + return variables.ConstantVariable(NotImplemented) + + def nb_absolute_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_absolute slot. + + Called when type_implements_nb_absolute returns True for this type. + Subclasses override to provide the actual absolute value. + """ + unimplemented( + gb_type="nb_absolute_impl not implemented", + context=f"{type(self).__name__} has nb_absolute slot but no nb_absolute_impl override", + explanation=f"The type {self.python_type_name()} has an nb_absolute C slot but " + "the corresponding VariableTracker doesn't implement nb_absolute_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_invert_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_invert slot. + + Called when type_implements_nb_invert returns True for this type. + Subclasses override to provide the actual bitwise inversion. + """ + unimplemented( + gb_type="nb_invert_impl not implemented", + context=f"{type(self).__name__} has nb_invert slot but no nb_invert_impl override", + explanation=f"The type {self.python_type_name()} has an nb_invert C slot but " + "the corresponding VariableTracker doesn't implement nb_invert_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def __init__( + self, + *, + source: Source | None = None, + mutation_type: MutationType | None = None, + source_location: SourceLocation | None = None, + dict_vt: variables.DunderDictVariable | None = None, + ) -> None: + super().__init__() + self.source = source + self.source_location = source_location + self.mutation_type = mutation_type + # Carried so clone() round-trips the cached __dict__ view. + self.dict_vt = dict_vt + + # NOTE sometimes mutation_type is set afterwards for implementation + # convenience, we don't validate those cases at the moment. + if mutation_type is not None: + if isinstance(mutation_type, (ValueMutationNew, AttributeMutationNew)): + # If this fails, it's either + # 1. one mistakenly passed in a source + # 2. `mutation_type` is incorrect + if source is not None: + raise AssertionError( + "source must be None for ValueMutationNew/AttributeMutationNew" + ) + else: + if not isinstance( + mutation_type, (ValueMutationExisting, AttributeMutationExisting) + ): + raise AssertionError( + f"Expected ValueMutationExisting or AttributeMutationExisting, " + f"got {type(mutation_type)}" + ) + # If this fails, it's either + # 1. one forgot to pass in a source + # 2. `mutation_type` is incorrect + if source is None: + raise AssertionError( + "source must not be None for ValueMutationExisting/AttributeMutationExisting" + ) + + @property + def tp_type(self) -> PyTypeObject: + return _tp_type(maybe_get_python_type(self)) + + @property + def tp_as_number(self) -> PyNumberMethods: + return _tp_type(maybe_get_python_type(self)).tp_as_number + + @property + def tp_as_sequence(self) -> PySequenceMethods: + return _tp_type(maybe_get_python_type(self)).tp_as_sequence + + @property + def tp_as_mapping(self) -> PyMappingMethods: + return _tp_type(maybe_get_python_type(self)).tp_as_mapping + + @property + def tp_iter(self) -> Slot | None: + return _tp_type(maybe_get_python_type(self)).tp_iter + + @property + def tp_iternext(self) -> Slot | None: + return _tp_type(maybe_get_python_type(self)).tp_iternext + + @property + def tp_str(self) -> Slot | None: + return _tp_type(maybe_get_python_type(self)).tp_str + + @property + def tp_repr(self) -> Slot | None: + return _tp_type(maybe_get_python_type(self)).tp_repr + + @property + def _slotdefs(self): + return _compute_slotdefs(maybe_get_python_type(self)) + + def __init_subclass__(cls, **kwargs: Any) -> None: + """ + Wraps all subclasses' `as_python_constant` and `reconstruct` so that it cannot be + called twice in the same call chain - i.e. self-referential objects. + For `as_python_constant` - self-referential objects are NOT treated as constants. + For `reconstruct` - we will graph break. The graph break can be avoided if the VT subclass + can generate and cache itself before recursively `reconstruct`ing - see ListVariable for an example. + """ + super().__init_subclass__(**kwargs) + + def as_python_constant_failure(self) -> NoReturn: + raise AsPythonConstantNotImplementedError( + self, msg=f"{self} is self-referential" + ) + + VariableTracker._add_call_once_guard( + cls, "as_python_constant", as_python_constant_failure + ) + + def reconstruct_failure(self) -> NoReturn: + unimplemented( + gb_type="Reconstruction failure (self-referential)", + context=str(self), + explanation=f"Dynamo tried to reconstruct sourceless variable {self}, but it is self-referential. " + "Dynamo must manually implement reconstruction rules for self-referentiable sourceless variables.", + hints=[ + "If Dynamo is attempting to trace a return statement and your code is attempting to return a variable " + "that Dynamo cannot reconstruct, then remove it from the return statement.", + "Remove the self-reference in the variable. A self-referring list, for example, is `l = []; l.append(l)`.", + *graph_break_hints.CAUSED_BY_EARLIER_GRAPH_BREAK, + "Report an issue to PyTorch if you need self-referential reconstrtuction support.", + ], + ) + + VariableTracker._add_call_once_guard(cls, "reconstruct", reconstruct_failure) + + @staticmethod + def _add_call_once_guard( + cls: type[VariableTracker], + method: str, + callback: Callable[[VariableTracker], Any], + ) -> None: + original_method = getattr(cls, method) + + if original_method is getattr(VariableTracker, method) or hasattr( + original_method, "_call_once_guarded" + ): + return + + @functools.wraps(original_method) + def guarded_method(self, *args: Any, **kwargs: Any) -> VariableTracker: + active = _vt_active_calls.get() + if active is None: + active = set() + _vt_active_calls.set(active) + + key = (id(self), id(original_method)) + if key in active: + callback(self) + + active.add(key) + try: + return original_method(self, *args, **kwargs) + finally: + active.discard(key) + + guarded_method._call_once_guarded = True # pyrefly: ignore[missing-attribute] + setattr(cls, method, guarded_method) + + +def typestr(*objs: object) -> str: + if len(objs) == 1: + (obj,) = objs + if isinstance(obj, VariableTracker): + return str(obj) + else: + return type(obj).__name__ + else: + return " ".join(map(typestr, objs)) + + +instancecheck = type.__instancecheck__ + + +_CPYTHON_BASE_URL = "https://github.com/python/cpython/blob/v3.13.0/" + + +def print_cpython_to_vt_mapping() -> None: + """Print the mapping from CPython types to Dynamo VariableTracker classes. + + Reads _cpython_type from each VT subclass (own attribute only, not inherited). + """ + # Ensure all VT modules are imported so all_subclasses is complete + from . import ( # noqa: F401 + builtin, + constant, + ctx_manager, + dicts, + distributed, + functions, + higher_order_ops, + iter, + lazy, + lists, + misc, + nn_module, + streams, + tensor, + torch, + torch_function, + user_defined, + ) + + mapping: dict[type, list[type]] = {} + for vt_cls in VariableTrackerMeta.all_subclasses: + cpython_type = vt_cls.__dict__.get("_cpython_type") + if cpython_type is None: + continue + types = cpython_type if isinstance(cpython_type, tuple) else (cpython_type,) + for t in types: + mapping.setdefault(t, []).append(vt_cls) + + for py_type, vt_classes in sorted(mapping.items(), key=lambda x: x[0].__qualname__): + for vt_cls in vt_classes: + print( + f"{py_type.__module__}.{py_type.__qualname__:30s} -> {vt_cls.__name__}" + ) + + +from . import builder +from .lazy import LazyVariableTracker diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..d6514d90222035697e73538b0ea88b4dea4b7e15 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py @@ -0,0 +1,5374 @@ +""" +This module contains classes and utilities for building variable trackers in Dynamo. +Variable trackers are used to convert Python values into symbolic representations +that can be traced and transformed during graph capture. + +The key classes are: + +- VariableBuilder: Handles source-tracked objects that need guards and proper + reconstruction in the output graph. Used for inputs, module attributes, etc. + +- SourcelessBuilder: Handles ephemeral objects created during tracing that don't + need source tracking or guards. Used for temporary lists, intermediate values, etc. + +Variable trackers enable Dynamo to track the flow of values through the program, +maintain guards for dynamic properties, and reconstruct values in the output graph. +The builders in this module handle converting Python values into appropriate +VariableTracker instances based on their type and usage context. +""" + +import abc +import builtins +import collections +import contextlib +import contextvars +import copy +import dataclasses +import enum +import functools +import importlib.machinery +import inspect +import itertools +import logging +import math +import operator +import random +import re +import sys +import time +import types +import typing +import weakref +from collections.abc import Callable, MutableMapping +from types import ModuleType +from typing import Any, cast, NamedTuple, NoReturn, overload, TYPE_CHECKING, Union + +import sympy + +import torch +from torch import SymInt +from torch._custom_class_base import CustomClassBase +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.graph_bytecode_inputs import ( + CURRENT_STREAM_INDEX, + get_external_object_by_index, + register_user_object, +) +from torch._dynamo.utils import ( + get_metrics_context, + is_int_specialization_case, + is_torch_sym, + normalize_count_iter, + set_feature_use, +) +from torch._functorch._aot_autograd.utils import is_async_collective_tensor_type +from torch._guards import TracingContext +from torch._higher_order_ops.flat_apply import flat_apply +from torch._higher_order_ops.torchbind import call_torchbind +from torch._library.opaque_object import ( + is_custom_class, + is_opaque_constant_type, + is_opaque_symbolic_type, + should_hoist, +) +from torch._ops import HigherOrderOperator, OpOverload, OpOverloadPacket +from torch._subclasses.fake_tensor import ( + FakeTensor, + FakeTensorMode, + is_fake, + is_fake_tensor, + maybe_get_fake_mode, +) +from torch._subclasses.meta_utils import is_sparse_any, safe_grad +from torch._utils_internal import justknobs_check +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental._dynamism import normalize_source_name +from torch.fx.experimental.dynamic_spec import ( + DictSpec, + IntermediateSpec, + IntVar, + LeafSpec, + ObjectSpec, + SeqSpec, + ShapesSpec, + TensorSpec, +) +from torch.fx.experimental.sym_node import _DynamicScalar, DynamicInt +from torch.fx.experimental.symbolic_shapes import ( + _constrain_range_for_size, + _nested_int_aware_sort, + _symbolic_context_from_shapes_spec, + _wire_spec_slot, + _wire_tensor_spec_dims, + DimDynamic, + RelaxedUnspecConstraint, + StatefulSymbolicContext, + SubclassSymbolicContext, + SymbolicContext, + SymIntSymbolicContext, + TrackedFake, +) +from torch.fx.immutable_collections import immutable_dict, immutable_list +from torch.nn.utils._expanded_weights import ExpandedWeight +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + is_traceable_wrapper_subclass_type, +) +from torch.utils._sympy.value_ranges import ValueRanges +from torch.utils.weak import TensorWeakRef + +from .. import config, graph_break_hints, mutation_guard, replay_record, trace_rules +from ..device_interface import get_registered_device_interfaces +from ..exc import InternalTorchDynamoError, raise_observed_exception, unimplemented +from ..guards import GuardBuilder, install_guard, make_dupe_guard +from ..pgo import ( + auto_dynamic, + auto_unset, + FrameStateSizeEntry, + InferStride, + process_automatic_dynamic, +) +from ..side_effects import SideEffects +from ..source import ( + AttrProxySource, + AttrSource, + CallMethodItemSource, + ChainedSource, + ConstDictKeySource, + ConvertIntSource, + CurrentStreamSource, + DictGetItemSource, + DictSubclassGetItemSource, + DynamicScalarSource, + FloatTensorSource, + GetItemSource, + GradSource, + is_constant_source, + is_from_closure_source, + is_from_global_source, + is_from_nonlocal_source, + is_from_optimizer_source, + is_from_unspecialized_nn_module_source, + ListGetItemSource, + LocalSource, + NNModuleSource, + NonSerializableSetGetItemSource, + NumpyTensorSource, + OptimizerSource, + RandomValueSource, + SkipGuardSource, + Source, + SubclassAttrListSource, + TupleIteratorGetItemSource, + UnspecializedBuiltinNNModuleSource, + UnspecializedNNModuleSource, + UnspecializedParamBufferSource, + UnwrapCollectiveTensorSource, +) +from ..utils import ( + _extract_tensor_dict, + build_checkpoint_variable, + build_invoke_subgraph_variable, + clone_input, + common_constant_types, + dict_keys, + enumerate_items_with_dict_position, + get_fake_value, + get_locals_to_steal, + get_static_address_type, + is_frozen_dataclass, + is_function, + is_function_or_wrapper, + is_invoke_subgraph, + is_lru_cache_wrapped_function, + is_namedtuple, + is_parameter_freezing, + is_pybind11_enum_member, + is_torch_class, + is_typing, + is_utils_checkpoint, + is_wrapper_or_member_descriptor, + istype, + namedtuple_fields, + odict_values, + proxy_args_kwargs, + range_iterator, + set_base_iter, + set_example_value, + tensor_always_has_static_shape, + tuple_iterator, + tuple_iterator_getitem, + tuple_iterator_len, + unwrap_with_attr_name_if_wrapper, + wrap_fake_exception, +) +from .base import ( + AttributeMutationExisting, + AttributeMutationNew, + typestr, + ValueMutationExisting, + ValueMutationNew, + VariableTracker, + VariableTrackerMeta, +) +from .builtin import BuiltinVariable +from .constant import ConstantVariable +from .ctx_manager import ( + AutocastModeVariable, + CudagraphOverrideVariable, + DynamoConfigPatchVariable, + ErrorOnGraphBreakVariable, + NullContextVariable, + PreserveVersionContextVariable, + RecordFunctionVariable, +) +from .dicts import ConstDictVariable, MappingProxyVariable, OrderedDictVariable +from .distributed import WorldMetaClassVariable +from .functions import ( + BoundBuiltinMethodVariable, + CollectionsNamedTupleFunction, + CollectiveFunctionRewriteVariable, + CreateTMADescriptorExperimentalVariable, + CreateTMADescriptorStableVariable, + FunctoolsPartialVariable, + GetSetDescriptorVariable, + LocalGeneratorFunctionVariable, + MemberDescriptorVariable, + MethodWrapperVariable, + SysFunctionVariable, + TritonKernelVariable, + TritonSetAllocatorVariable, + UserFunctionVariable, + WrapperUserFunctionVariable, +) +from .higher_order_ops import ( + LocalMapWrappedHigherOrderVariable, + TorchHigherOrderOperatorVariable, +) +from .iter import CountIteratorVariable, ItertoolsVariable +from .lazy import LazyConstantVariable, LazyVariableTracker +from .lists import ( + BaseListVariable, + DequeVariable, + ListIteratorVariable, + ListVariable, + RangeVariable, + SizeVariable, + SliceVariable, + TupleIteratorVariable, + TupleVariable, +) +from .memory import CUDAMemPoolVariable +from .misc import ( + AutogradEngineVariable, + AutogradFunctionContextVariable, + AutogradFunctionVariable, + ComptimeVariable, + ConstantLikeVariable, + DebuggingVariable, + DelayGraphBreakVariable, + GetAttrVariable, + IgnoredFunctionVariable, + LambdaVariable, + LoggingLoggerVariable, + NumpyDTypeVariable, + NumpyVariable, + ObjectVariable, + PythonModuleVariable, + RandomClassVariable, + RandomVariable, + SavedTensorBox, + StringFormatVariable, + TypingVariable, + WeakRefVariable, +) + + +if sys.version_info >= (3, 15): + from .misc import SentinelVariable + +from .nn_module import ( + FSDPManagedNNModuleVariable, + UnspecializedBuiltinNNModuleVariable, + UnspecializedNNModuleVariable, +) +from .optimizer import OptimizerVariable +from .script_object import CustomClassObjectVariable, CustomClassVariable +from .sdpa import SDPAParamsVariable +from .sets import ( + DictKeySetVariable, + FrozensetVariable, + OrderedSetClassVariable, + OrderedSetVariable, + SetVariable, +) +from .streams import EventVariable, StreamContextVariable, StreamVariable +from .tensor import ( + NumpyNdarrayVariable, + supported_const_comparison_op_values, + SymNodeVariable, + TensorSpecializedProps, + TensorSubclassVariable, + TensorVariable, + UnspecializedPythonVariable, +) +from .torch import ( + DispatchKeySetVariable, + FuncTorchInterpreterVariable, + TorchCtxManagerClassVariable, + TorchInGraphFunctionVariable, +) +from .torch_function import ( + TensorWithTFOverrideVariable, + torch_function_mode_stack_state_mgr, + TorchFunctionModeVariable, +) +from .user_defined import ( + DefaultDictVariable, + FrozenDataClassVariable, + InspectVariable, + IntWrapperVariable, + KeyedJaggedTensorVariable, + MutableMappingVariable, + SourcelessGraphModuleVariable, + UserDefinedClassVariable, + UserDefinedConstantVariable, + UserDefinedDequeVariable, + UserDefinedDictVariable, + UserDefinedExceptionClassVariable, + UserDefinedListVariable, + UserDefinedObjectVariable, + UserDefinedSetVariable, + UserDefinedTupleVariable, +) + + +try: + import numpy as np +except ModuleNotFoundError: + np: ModuleType = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +log = logging.getLogger(__name__) +static_inputs_log = torch._logging.getArtifactLogger( + __name__, "cudagraph_static_inputs" +) +symbolic_shape_log = logging.getLogger("torch.fx.experimental.symbolic_shapes") +from typing import TypeVar + + +# Placeholder for a VariableTracker to be used in proxy +# creation so that we don't type erase +VTTypeAlias = TypeVar("VTTypeAlias") +T = TypeVar("T") + +DimList = list + + +def safe_has_grad(t: object) -> bool: + with torch._logging.hide_warnings(torch._logging._internal.safe_grad_filter): + return hasattr(t, "grad") + + +@dataclasses.dataclass(frozen=True) +class _LocalToken: + """Root token: a top-level function-argument access.""" + + name: str + is_varargs: bool = False + is_varkw: bool = False + + +@dataclasses.dataclass(frozen=True) +class _AttrToken: + """Attribute access (``obj.name``).""" + + name: str + + +@dataclasses.dataclass(frozen=True) +class _SubscriptToken: + """Subscript access (``obj[key]``). + + Emitted for ``dict`` key lookups (matched against ``DictSpec`` entries). + The key may be ``int`` or ``str`` — both are valid dict keys. + """ + + key: int | str + + +_AccessToken = _LocalToken | _AttrToken | _SubscriptToken +_AccessPath = list[_AccessToken] + + +def _format_access_path(tokens: _AccessPath) -> str: + """Format an access path as a Python source-like string for error messages. + + Examples: + [_LocalToken("xs")] -> "xs" + [_LocalToken("cfg"), _SubscriptToken("x")] -> "cfg['x']" + [_LocalToken("m"), _AttrToken("weight")] -> "m.weight" + [_SubscriptToken(0)] -> "[0]" + [_AttrToken("weight")] -> ".weight" + """ + parts: list[str] = [] + for tok in tokens: + match tok: + case _LocalToken(name=name): + parts.append(name) + case _AttrToken(name=name): + parts.append(f".{name}") + case _SubscriptToken(key=key): + parts.append(f"[{key!r}]") + case _: + raise RuntimeError( + f"_format_access_path: unexpected token {tok!r} " + f"of type {type(tok).__name__}" + ) + return "".join(parts) if parts else "" + + +def _source_to_access_path(source: Source) -> _AccessPath | None: + """Translate a dynamo ``Source`` chain into a flat ``_AccessPath``. + + Walks ``source.base`` from leaf to root, then reverses so the path + reads root-first. The returned path always starts with a single + ``_LocalToken`` (the input arg) followed by zero or more access + tokens, each of which is either an ``_AttrToken`` (attribute + access) or a ``_SubscriptToken`` (``dict[key]`` access with an + ``int`` or ``str`` key). + + Returns ``None`` for sources that we know we can't represent them + in shapes specs. + """ + path: list[_AccessToken] = [] + cur: Source = source + while not isinstance(cur, LocalSource): + if isinstance(cur, NNModuleSource): + # ``NNModuleSource`` is a guard-semantics marker, not an + # access step — transparently unwrap. + cur = cur.base + continue + # ``self.weight`` → dynamo emits + # ``DictGetItemSource(UnspecializedParamBufferSource(_, + # '_parameters'), 'weight')``. Collapse that pair into a single + # attr token. + if isinstance(cur, DictGetItemSource) and isinstance( + cur.base, UnspecializedParamBufferSource + ): + path.append(_AttrToken(cur.index)) + cur = cur.base.base + continue + # Plain ``dict[key]`` access. + if isinstance(cur, DictGetItemSource) and isinstance(cur.index, (int, str)): + path.append(_SubscriptToken(cur.index)) + cur = cur.base + continue + # Integer subscript (e.g. *args[i] or list[i]). + if isinstance(cur, GetItemSource) and type(cur.index) is int: + path.append(_SubscriptToken(cur.index)) + cur = cur.base + continue + if isinstance(cur, AttrSource): + path.append(_AttrToken(cur.member)) + cur = cur.base + continue + return None + if not cur.is_input: + return None + path.append( + _LocalToken(cur.local_name, is_varargs=cur.is_varargs, is_varkw=cur.is_varkw) + ) + path.reverse() + return path + + +def _walk_spec( + current_spec: IntermediateSpec, + full_path: _AccessPath, + start_index: int, +) -> LeafSpec: + """Walk down a spec tree starting at ``current_spec``, consuming each + token in ``full_path[start_index:]`` in order. Returns the leaf spec at + the end of the walk, or ``None`` if a key/field along the way wasn't + specified by the user. Raises on type-mismatch. + + ``full_path`` is the original access path (including any prefix already + consumed by the caller before reaching ``current_spec``); ``start_index`` + is the offset in ``full_path`` where the walk begins. + """ + + def _mismatch_error( + at_idx: int, spec: IntermediateSpec, suffix: str = "" + ) -> RuntimeError: + return RuntimeError( + f"shapes_spec walk: while processing source " + f"{_format_access_path(full_path)!r}, at " + f"{_format_access_path(full_path[:at_idx])!r} " + f"the spec is {type(spec).__name__}{suffix}" + ) + + for idx in range(start_index, len(full_path)): + token = full_path[idx] + if current_spec is None: + # Under-specified: a previous descent (DictSpec key lookup or + # ObjectSpec field lookup) returned None because the user didn't + # provide a spec for this entry. Treat as static. + return None + match current_spec: + case ObjectSpec(): + if not isinstance(token, _AttrToken): + raise _mismatch_error(idx, current_spec) + current_spec = current_spec._fields.get(token.name) + case DictSpec(): + if not isinstance(token, _SubscriptToken): + raise _mismatch_error(idx, current_spec) + current_spec = current_spec._entries.get(token.key) + case SeqSpec(): + if not isinstance(token, _SubscriptToken) or not isinstance( + token.key, int + ): + raise _mismatch_error(idx, current_spec) + + if token.key < 0: + raise RuntimeError( + "dynamo should have normalized the index to be non-negative" + ) + # Out-of-range index: unspecified -> treat as static (None), + if token.key < len(current_spec): + current_spec = current_spec._entries[token.key] + else: + current_spec = None + case _: + # leaf spec (TensorSpec / IntVar / int / None) but path still + # has tokens. + raise _mismatch_error( + idx, + current_spec, + ", but the source has further access past it", + ) + if not isinstance(current_spec, LeafSpec): + # The walk consumed all source tokens but landed on a container + # in the source. + raise _mismatch_error( + len(full_path), + current_spec, + ", but the source has no further access past it", + ) + return current_spec + + +def lookup_spec_from_dynamo_source( + source: Source, shapes_spec: ShapesSpec | None +) -> LeafSpec: + """Look up the LeafSpec at the access path derived from ``source`` in ``params``. + Returns ``None`` if the source isn't covered. + """ + if shapes_spec is None or shapes_spec._params is None: + return None + path = _source_to_access_path(source) + if not path or not isinstance(path[0], _LocalToken): + return None + params = shapes_spec._params + root = path[0] + if root.is_varargs: + # ``*args`` element access: root is the varargs local, next token must + # be an int subscript. A varargs local is always followed by a + # subscript token in ``_source_to_access_path``; anything else means + # the chain was mis-tokenized. + if not isinstance(path[1], _SubscriptToken): + raise RuntimeError( + f"Expected _SubscriptToken after *args local at path " + f"{path!r}, got {type(path[1]).__name__}" + ) + key = path[1].key + if type(key) is not int: + raise RuntimeError( + f"Unexpected non-int subscript for *args access at path " + f"{path!r}: {type(key).__name__}({key!r})" + ) + if params._varargs is None or not (0 <= key < len(params._varargs)): + return None + return _walk_spec(params._varargs[key], full_path=path, start_index=2) + if root.is_varkw: + # ``**kwargs`` element access: root is the varkw local, next token must + # be a str subscript. A varkw local is always followed by a subscript + # token in ``_source_to_access_path``; anything else means the chain + # was mis-tokenized. + if not isinstance(path[1], _SubscriptToken): + raise RuntimeError( + f"Expected _SubscriptToken after **kwargs local at path " + f"{path!r}, got {type(path[1]).__name__}" + ) + key = path[1].key + if not isinstance(key, str): + raise RuntimeError( + f"Unexpected non-str subscript for **kwargs access at path " + f"{path!r}: {type(key).__name__}({key!r})" + ) + if params._varkw is None or key not in params._varkw: + return None + + return _walk_spec(params._varkw[key], full_path=path, start_index=2) + # Regular named arg: seed at the named-arg root and descend the rest. + + current_spec: IntermediateSpec = params._named_args.get(root.name) + return _walk_spec(current_spec, full_path=path, start_index=1) + + +def bound_builtin_method_descriptor(value: Any) -> Any | None: + if not isinstance(value, types.BuiltinMethodType): + return None + + method_self = value.__self__ + # BuiltinMethodType also covers module-level C functions like len and + # torch.add. Keep those on the existing function/trace-rule path. + if method_self is None or isinstance(method_self, types.ModuleType): + return None + + # random.Random methods mutate RNG state. Existing random handling either + # records RandomValueSource calls from a RandomVariable, or graph-breaks for + # pre-bound module helpers like random.random. + if isinstance(method_self, random.Random): + return None + + owner = method_self if isinstance(method_self, type) else type(method_self) + + # Torch-internal bound methods already have dedicated Dynamo paths. Do not + # route them through the generic bound-builtin descriptor VT, which changes + # graph break boundaries for calls like Tensor.mul(...). + if is_torch_class(owner): + return None + + # BoundBuiltinMethodVariable needs the descriptor that created this bound + # method. For class-bound methods, look on the class object itself (e.g. + # dict.fromkeys); for instance-bound methods, look on type(self). + return inspect.getattr_static(owner, value.__name__, None) + + +class _missing: + pass + + +@dataclasses.dataclass +class GraphArg: + source: Source | None + # TODO: storing a SymInt here but not a FakeTensor is a pretty strange + # thing to do. Probably should have example (which stores an int) and + # fake_example + _example: Any + # When True, this indicates that this GraphArg is a Python quantity (e.g., + # a float or int) which we pass to the FX graph as a Tensor. This + # controls how we codegen calls into the Dynamo graph: we will call + # torch.as_tensor on the quantity before passing it in. + # + # Note that we typically do not pass dynamic integers as tensors, because + # they will most frequently just be used for size computation. But this + # is a policy decision that we can change our mind on; in particular, when + # an int comes from a random number generator (e.g., random.randint), we + # DO pass it as a tensor. + # + # It's also worth noting that our current tracing rules for + # pass_arg_as_tensor as subtly broken: we just pun the variable as a + # 0d scalar Tensor and pray that the semantics are the same. Which they + # often are, but not necessarily. ezyang(May 2024) plans to fix this + # soon. + pass_arg_as_tensor: bool + fake_tensor: torch._subclasses.fake_tensor.FakeTensor | None + # UnspecializedPythonVariable often masquerades as a tensor. + # We MUST NOT generate shape guard code + # that actually tries to access tensor properties on these values. + # is_tensor lets us tell if this graph arg actually is a tensor + # or not. + is_tensor: bool = True + # Sometimes, the Tensor we pass to example is freshly allocated (smh). + # Then we cannot only keep a weak reference to it. This lets you + # stash a strong reference too. + example_strong_ref: torch.Tensor | torch.SymInt | None = None + + def __setattr__(self, name: str, value: Any) -> None: + # Use object.__setattr__ to bypass Dynamo's STORE_ATTR interception. + # This is needed because when PYTORCH_TEST_WITH_DYNAMO=1, even internal + # GraphArg creation can be traced, and with replay_side_effects=False, + # normal STORE_ATTR bytecode only records mutations without applying them. + object.__setattr__(self, name, value) + + @property + def example(self) -> torch.Tensor | torch.SymInt | BackwardState | None: + if isinstance(self._example, TensorWeakRef): + r = self._example() + if r is None: + raise AssertionError("TensorWeakRef expired unexpectedly") + return r + else: + return self._example + + def __post_init__(self) -> None: + if isinstance(self._example, torch.Tensor): + self._example = TensorWeakRef(self._example) + if not is_fake(self.fake_tensor): + raise AssertionError("fake_tensor must be a FakeTensor") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.source) + + def reconstruct_pycode(self, codegen) -> str: + if self.source is None: + raise AssertionError( + "Expecting GraphArg to have source during python codegen." + ) + return self.source.reconstruct_pycode(codegen) + + def erase(self) -> None: + self._example = None + self.example_strong_ref = None + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GraphArg): + return False + if self.source is None: + return other.source is None + else: + if other.source is None: + return False + return self.source.name == other.source.name + + +class BackwardStateGraphArg(GraphArg): + def __init__(self) -> None: + super().__init__( + source=None, + _example=BackwardState(), + pass_arg_as_tensor=False, + fake_tensor=None, + is_tensor=False, + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if not codegen.tx.output.backward_state_var: + raise AssertionError("backward_state_var must be set on output") + codegen.add_push_null( + lambda: codegen.load_import_from(BackwardState.__module__, "BackwardState") + ) + codegen.call_function(0, False) + codegen.dup_top() + codegen.store(codegen.tx.output.backward_state_var) + + +# All class-based iterators in itertools +# NOTE: use id() because some objects are not hashable, it will raise error during lookup +ITERTOOLS_TYPE_IDS: frozenset[int] = frozenset( + id(member) + for name, member in vars(itertools).items() + if not name.startswith("_") and inspect.isclass(member) +) +# Will be updated later in substitute_in_graph in torch/_dynamo/polyfills/itertools.py +ITERTOOLS_POLYFILLED_TYPE_IDS: set[int] = set() + +# Capture fn pointer at import time +# This is to guard against trying to mark the iterated tensors +# as static in case user overrides fn ptr +og_module_named_buffers_fn_ptr = torch.nn.Module.named_buffers +og_module_named_parameters_fn_ptr = torch.nn.Module.named_parameters + + +def _is_dim_dynamic_from_source_dynamism( + source: Source, normalized_source_name: str, dim: int +) -> bool: + if isinstance(source, ChainedSource): + source = source.get_base() + if not isinstance(source, LocalSource) or source.dynamism is None: + return False + + source_dynamism: dict[str, tuple[bool, ...]] = dict( + typing.cast(Any, source.dynamism) + ) + dim_dynamism = source_dynamism.get(normalized_source_name) + return dim_dynamism is not None and dim < len(dim_dynamism) and dim_dynamism[dim] + + +class VariableBuilder: + """Wrap a python value in a VariableTracker() instance""" + + def __init__( + self, + tx: "InstructionTranslatorBase", + source: Source, + allow_lazy_constant: bool = True, + ) -> None: + if source is None: + raise AssertionError( + "Consider SourcelessBuilder for ephemeral objects, usually objects created locally." + ) + if TracingContext.try_get() is None: + raise AssertionError("Expected active TracingContext") + super().__init__() + self.tx = tx + self.source = source + self.name = source.name + # allow_lazy_constant controls whether LazyConstantVariable can be returned + # for int/float/bool/str. Set to False when called from LazyCache.realize() + # to prevent double-wrapping (LazyVariableTracker containing LazyConstantVariable). + self.allow_lazy_constant = allow_lazy_constant + + def __call__(self, value: object) -> VariableTracker: + _t0 = time.time_ns() + try: + return self._call_impl(value) + finally: + self.tx.output.bytecode_tracing_timings.variable_builder_call_ns += ( + time.time_ns() - _t0 + ) + + def _call_impl(self, value: object) -> VariableTracker: + self.tx.output.current_tracer.traced_sources.add(self.source) + if value in self.tx.output.side_effects: + side_effect_result = self.tx.output.side_effects[value] + dup_guard = make_dupe_guard(self.source, side_effect_result.source) + if dup_guard: + self.install_guards(dup_guard) + + if isinstance(value, torch.nn.Module) and isinstance( + side_effect_result, UnspecializedNNModuleVariable + ): + # This means that two nn module instances with different sources + # have the same id. NN modules are somewhat special objects, + # because we have to track their nn_module_stack for ease of + # use. But if we don't do anything, we will just return the + # older variable tracker with the older nn_module_stack. So, + # lets return the old variable tracker but update its + # nn_module_stack + side_effect_result.set_nn_module_stack_source(self.source) + return side_effect_result + + cached_vt = self.tx.output.variable_tracker_cache.get(self.source) + if cached_vt: + # If allow_lazy_constant=False but the cached VT is a lazy variable, + # we need to rebuild to get a non-lazy version. This happens when + # LazyConstantVariable.realize() calls VariableBuilder. + if self.allow_lazy_constant or not isinstance( + cached_vt, LazyVariableTracker + ): + return cached_vt + + vt = self._wrap(value) + + if vt.source is None: + vt.source = self.source + + def _is_deduplicable_sym_variable(value: Any, vt: VariableTracker) -> bool: + # Constants like 0, 1, 2, etc. can be unspecialized as SymNodeVariables sometimes, but we + # should NOT track them. If we use a single SymNodeVariable instance to track them + # across multiple uses, then guards created for one usage will incorrectly apply to + # all other usages of that constant, leading to unnecessary recompilations. + return ( + is_torch_sym(value) or isinstance(value, _DynamicScalar) + ) and isinstance(vt, SymNodeVariable) + + if ( + ( + self._can_lift_attrs_to_inputs(vt) + or _is_deduplicable_sym_variable(value, vt) + ) + and value not in self.tx.output.side_effects + and not is_wrapper_or_member_descriptor(value) + ): + vt = self.tx.output.side_effects.track_object_existing(value, vt) + + # Skip caching for JVP_NESTING source because + # JvpIncrementNestingCtxManagerVariable hides global JVP mutation from + # Dynamo, resulting in stale value. We attempted a fix in + # https://github.com/pytorch/pytorch/pull/174329 but it exposed other + # issues. This only affects cache hit rate, NOT correctness. + if "JVP_NESTING" not in self.source.name: + self.tx.output.variable_tracker_cache[self.source] = vt + return vt + + def _can_lift_attrs_to_inputs(self, vt: VariableTracker) -> bool: + return type(vt) in { + TensorVariable, + TensorWithTFOverrideVariable, + UserDefinedObjectVariable, + NumpyNdarrayVariable, + CustomClassObjectVariable, + } + + def get_source(self) -> Source: + return self.source + + def install_guards(self, *guards: Callable[..., Any]) -> dict[str, Any] | None: + source = self.get_source() + try: + tmp = [source.make_guard(guard) for guard in guards] + except NotImplementedError: + return None + install_guard(*tmp, skip=1) + return {} + + @classmethod + def _type_dispatch(cls) -> dict[object, Callable[..., Any]]: + return cls._type_dispatch_impl(config.trace_numpy) + + @classmethod + @functools.cache + def _type_dispatch_impl(cls, trace_numpy: bool) -> dict[object, Callable[..., Any]]: + # NB: Careful not to close over self to avoid ref cycle from lru_cache + entries = [ + ( + ( + torch.Tensor, + torch.nn.Parameter, + torch._subclasses.FakeTensor, + torch._subclasses.functional_tensor.FunctionalTensor, + ), + cls.wrap_tensor, + ), + ( + (tuple, list, odict_values, collections.deque, torch.Size), + cls.wrap_listlike, + ), + (itertools.count, cls.wrap_itertools_count), + (tuple_iterator, cls.wrap_tuple_iterator), + (range_iterator, cls.wrap_range_iterator), + ((slice, range), cls.wrap_slice_range), + (tuple(common_constant_types), cls.wrap_literal), + ((re.Pattern, re.Match), cls.wrap_regex_pattern), + (weakref.ReferenceType, cls.wrap_weakref), + (torch.utils.hooks.RemovableHandle, cls.wrap_removable_handle), + (torch.jit.ScriptFunction, cls.wrap_jit_function), + (types.MappingProxyType, cls.wrap_mapping_proxy), + ] + + if trace_numpy and np: + # pyrefly: ignore [bad-argument-type] + entries.append((np.ndarray, cls.wrap_numpy_ndarray)) + + # pyrefly: ignore [implicit-any] + result = {} + for ts, fn in entries: + for t in ts if isinstance(ts, tuple) else (ts,): + if t in result: + raise AssertionError(f"Duplicate type dispatch entry for {t}") + result[t] = fn + + return result + + def wrap_regex_pattern( + self, value: re.Pattern[Any] | re.Match[Any] + ) -> ConstantLikeVariable: + # TODO(jansel): something like a REPR_MATCH might be more robust here + self.install_guards(GuardBuilder.ID_MATCH) + return ConstantLikeVariable(value) + + def wrap_weakref(self, value: weakref.ReferenceType[Any]) -> WeakRefVariable: + self.install_guards(GuardBuilder.TYPE_MATCH) + return WeakRefVariable.build(self.tx, value, source=self.source) + + def wrap_removable_handle( + self, value: torch.utils.hooks.RemovableHandle + ) -> NoReturn: + # This means that the removable handle was created in some other frame. + # Our current infra requires the hook to be registered and removed in + # the same frame. So graph break. + # Related test - PYTORCH_TEST_WITH_DYNAMO=1 python test/test_autograd.py -k TestAutograd.test_hooks + unimplemented( + gb_type="Attempted to represent unregistered RemovableHandle", + context="", + explanation="Dynamo attempted to build a representation of a torch.utils.hooks.RemovableHandle, " + "which is not supported. This happens because the RemovableHandle was created in another frame.", + hints=[], + ) + + def wrap_jit_function(self, value: Any) -> WrapperUserFunctionVariable: + if not hasattr(value, "_torchdynamo_inline"): + unimplemented( + gb_type="wrap_jit_function: missing _torchdynamo_inline", + context=f"type: {type(value).__name__}", + explanation="Dynamo expected a JIT function with a _torchdynamo_inline attribute, " + "but the object does not have one.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + self.install_guards(GuardBuilder.TYPE_MATCH) + return WrapperUserFunctionVariable( + value, + "_torchdynamo_inline", + source=self.source, + mutation_type=AttributeMutationExisting(), + ) + + def wrap_mapping_proxy(self, value: Any) -> VariableTracker: + self.install_guards(GuardBuilder.TYPE_MATCH) + # This might be suboptimal compared to dict guards. But mappingproxy is + # not very common, so its ok to guard on all keys. + self.install_guards(GuardBuilder.MAPPING_KEYS_CHECK) + all_const = all(ConstantVariable.is_literal(k) for k in value) + + if not all_const: + unimplemented( + gb_type="non-const keys in mappingproxy", + context=f"non-const keys: {[k for k in value.keys() if not ConstantVariable.is_literal(k)]}", # noqa: SIM118 + explanation="Dynamo expects mappingproxy keys to be constants.", + hints=[ + "Ensure your mappingproxy keys are constants (e.g. int, float, strings)", + ], + ) + + def build_key_value(k: Any, v: Any) -> tuple[VariableTracker, VariableTracker]: + key = ConstantVariable.create(k) + source_key = k + + source_value = GetItemSource(self.get_source(), source_key) + res_value = LazyVariableTracker.create(v, source_value, tx=self.tx) + + return key, res_value + + items = dict(build_key_value(k, v) for k, v in value.items()) + + # Create a dict_vt to be used in the mapping proxy variable + dict_vt = ConstDictVariable(items, source=None) + result = MappingProxyVariable(dict_vt, source=self.source) + return self.tx.output.side_effects.track_mutable(value, result) + + @classmethod + @functools.cache + def _id_dispatch( + cls, + ) -> dict[int, Callable[["VariableBuilder", Any], VariableTracker]]: + from ..comptime import comptime + + entries = [ + (comptime, lambda self, value: ComptimeVariable()), + ( + dataclasses.fields, + lambda self, value: LambdaVariable( + _dataclasses_fields_lambda, + source=self.source, + **self.install_guards(GuardBuilder.CLOSURE_MATCH), + ), + ), + ] + + # pyrefly: ignore [implicit-any] + result = {} + for ts, fn in entries: + for t in ts if isinstance(ts, (tuple, list)) else (ts,): + if t in result: + raise AssertionError(f"Duplicate id dispatch entry for {t}") + result[id(t)] = fn + + return result + + def _wrap(self, value: Any) -> VariableTracker: + # import here to avoid circular dependencies + from torch.utils._triton import ( + has_triton, + has_triton_experimental_host_tma, + has_triton_tensor_descriptor_host_tma, + ) + + from ..decorators import ( + CudagraphOverrideContextManager, + DynamoConfigPatchProxy, + ErrorOnGraphBreakDecoratorContextManager, + ) + + if has_triton(): + from triton.runtime.autotuner import Autotuner + from triton.runtime.jit import JITFunction + else: + + class JITFunction: + pass + + class Autotuner: + pass + + # default implementations, in case we don't have triton (or the wrong triton version) + def create_1d_tma_descriptor() -> None: + pass + + def create_2d_tma_descriptor() -> None: + pass + + class TensorDescriptor: + @staticmethod + def from_tensor() -> None: + pass + + def set_allocator() -> None: + pass + + if has_triton_experimental_host_tma(): + from triton.tools.experimental_descriptor import ( + create_1d_tma_descriptor, + create_2d_tma_descriptor, + ) + if has_triton_tensor_descriptor_host_tma(): + from triton.tools.tensor_descriptor import TensorDescriptor + if has_triton(): + import triton as triton_mod + + if hasattr(triton_mod, "set_allocator"): + set_allocator = triton_mod.set_allocator + + # Handle exact type() match + type_dispatch = self._type_dispatch().get(type(value)) + if type_dispatch is not None: + return type_dispatch(self, value) + + # Handle exact id() match + id_dispatch = self._id_dispatch().get(id(value)) + if id_dispatch is not None: + return id_dispatch(self, value) + + # Everything else (NB: order matters!) + if ( + isinstance(value, torch.Tensor) + and type(value) + not in ( + # These torch-native subclasses have overly restrictive + # `__torch_function__` which prevents Dynamo from reading their + # tensor attributes like `is_nested` or calling methods like + # `_is_view`. + torch.nn.parameter.UninitializedBuffer, + torch.nn.parameter.UninitializedParameter, + ExpandedWeight, + ) + and type(value) not in config.nontraceable_tensor_subclasses + ): + if ( + type(value).__torch_dispatch__ is torch.Tensor.__torch_dispatch__ + or is_traceable_wrapper_subclass(value) + ): + return self.wrap_tensor(value) + + if isinstance(value, torch.profiler.record_function): + self.install_guards(GuardBuilder.ID_MATCH) + return RecordFunctionVariable(value) + if is_namedtuple(value): + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + output: list[VariableTracker] = [ + LazyVariableTracker.create( + getattr(value, name), + source=AttrSource(self.source, name), + tx=self.tx, + ) + for name in namedtuple_fields(type(value)) + ] + + tuple_vt = TupleVariable( + output, + source=self.source, + mutation_type=ValueMutationExisting(), + ) + result = UserDefinedTupleVariable.get_vt_cls(type(value))( + value, + source=self.source, + tuple_vt=tuple_vt, + ) + return self.tx.output.side_effects.track_object_existing(value, result) + elif istype(value, (dict, collections.defaultdict, collections.OrderedDict)): + self.install_guards(GuardBuilder.TYPE_MATCH) + all_const = all(ConstantVariable.is_literal(k) for k in value) + + # For all_const, we don't have to guard on anything yet. We guard on + # keys lazily by adding a dict_getitem entry for each accessed key. + # For cases where we need to guard on all keys, we lazily put guards + # during the dict call_method (check dicts.py) + if not all_const: + # Guard on the key order + # This is not ideal, i.e., there is no need to guard on the key + # order. But we guard on the key order because of the complexity + # + # 1) For non-constant objects, we can't save the key in the + # guard context because it can be memory heavy. We can add + # weakrefs but this complicates the accesses. + # + # 2) For non-constant objects, we also have to guard on the keys + # (like TENSOR_MATCH on tensor). We might also have guards on + # the attributes of the keys (like tensor.grad). To make this + # work in tree structure is complicated. + # + # So, instead we guard on the key order. While guarding on key + # order, we just save the indices and use it to access keys and + # values. Indices are cheap to save. + self.tx.output.guard_on_key_order.add(self.source) + + # We need all the keys to be hashable. We do this within the + # HashableTracker class in hashable.py + def build_key_value( + i: Any, k: Any, v: Any + ) -> tuple[VariableTracker, VariableTracker]: + base = self.get_source() + if all_const: + key = ConstantVariable.create(k) + source_key = k + else: + source_key = ConstDictKeySource(base, i) + key = LazyVariableTracker.create(k, source_key, tx=self.tx) + source_value = DictGetItemSource(base, source_key) + res_value = LazyVariableTracker.create(v, source_value, tx=self.tx) + + return key, res_value + + result = dict( + build_key_value(i, k, v) + for i, k, v in enumerate_items_with_dict_position(value) + ) + + if istype(value, collections.defaultdict): + factory_source = AttrSource(self.source, "default_factory") + dict_vt = ConstDictVariable( + result, # type: ignore[arg-type] + mutation_type=ValueMutationExisting(), + source=self.source, + ) + result = DefaultDictVariable( + value, + default_factory=VariableBuilder(self.tx, factory_source)( + value.default_factory + ), + dict_vt=dict_vt, + source=self.source, + ) + return self.tx.output.side_effects.track_object_existing(value, result) + elif istype(value, collections.OrderedDict): + result = OrderedDictVariable( + result, # type: ignore[arg-type] + source=self.source, + ) + else: + result = ConstDictVariable( + result, # type: ignore[arg-type] + source=self.source, + ) + + return self.tx.output.side_effects.track_mutable(value, result) + elif isinstance(value, torch.nn.Module): + return self.wrap_module(value) + elif ConstantVariable.is_literal(value): # non-atomic literals + return self.wrap_literal(value) + elif isinstance(value, torch.overrides.TorchFunctionMode): + var = TorchFunctionModeVariable(value, source=self.source) + self.tx.output.side_effects.track_object_existing(value, var) + return var + elif istype(value, (set, OrderedSet)): + if any(isinstance(x, torch.Tensor) for x in value): + unimplemented( + gb_type="Attempted to wrap a set with tensors", + context="Python set containing torch.Tensor elements", + explanation=( + "Dynamo cannot trace sets of tensors. To get a stable ordering, " + "Dynamo needs to convert the set into a list and the order might not be " + "stable if the set contains tensors." + ), + hints=[ + "Use a dictionary where the keys are tensors.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + set_var_cls = SetVariable + + if istype(value, OrderedSet): + # Guard on the internal dict of OrderedSet + internal_dict_source = AttrSource(self.source, "_dict") + install_guard( + internal_dict_source.make_guard(GuardBuilder.DICT_KEYS_MATCH) + ) + self.tx.output.guard_on_key_order.add(internal_dict_source) + set_var_cls = OrderedSetVariable + + # The list gives a ordering for the set items. The ordering is based + # on the Python hash and it is not related to object ordering inside + # the set object. The order being incorrect at runtime will lead to + # a recompilation. + L = list(value) if istype(value, OrderedSet) else list(set_base_iter(value)) + items = [ + LazyVariableTracker.create( + v, + source=NonSerializableSetGetItemSource(self.source, i), + tx=self.tx, + ) + for i, v in enumerate(L) + ] + result = set_var_cls(items, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif istype(value, frozenset) and all( + ( + # For DBR quantization, we could get a frozenset of torch funcs. + (type(x) is types.BuiltinMethodType and x.__module__ == "torch") + or + # Another commonly used frozenset of types. + x in torch.utils._pytree.BUILTIN_TYPES + or + # For activation checkpointing, we could get a frozenset of torch ops. + isinstance(x, (OpOverload, OpOverloadPacket)) + ) + for x in value + ): + # For the limited cases of frozenset here, we know the items won't + # change across runs, so we can safely create sourceless VTs for + # them and guard on the frozenset contents via EQUALS_MATCH. + # TODO support source for sets and remove the special logics here. + items = [SourcelessBuilder.create(self.tx, v) for v in value] + self.install_guards(GuardBuilder.EQUALS_MATCH) + return FrozensetVariable(items, source=self.source) + elif isinstance( + value, + (enum.Enum, torch.DispatchKey, torch._C._functorch.TransformType), + ) or is_pybind11_enum_member(value): + self.install_guards(GuardBuilder.ID_MATCH) + return UserDefinedObjectVariable(value, source=self.source) + elif DebuggingVariable.is_reorderable_logging_function(value): + # Put this above builtin_callable so that print() can be handled + # along with other builtin debugging functions + self.install_guards(GuardBuilder.BUILTIN_MATCH) + return DebuggingVariable(value, source=self.source) + elif callable(value) and any( + value is fn for fn in torch._dynamo.config.ignore_logging_functions + ): + # Treat ignored functions as full no-ops + self.install_guards(GuardBuilder.ID_MATCH) + return IgnoredFunctionVariable(value, source=self.source) + elif isinstance(value, logging.Logger): + self.install_guards(GuardBuilder.TYPE_MATCH) + return LoggingLoggerVariable(value, source=self.source) + elif is_utils_checkpoint(value): + return build_checkpoint_variable(source=self.source) + elif is_invoke_subgraph(value): + return build_invoke_subgraph_variable(source=self.source) + elif LocalMapWrappedHigherOrderVariable.should_wrap_in_hop(value): + return LocalMapWrappedHigherOrderVariable.build(source=self.source) + elif isinstance(value, functools.partial): + func_src = AttrSource(self.get_source(), "func") + func_obj = VariableBuilder(self.tx, func_src)(value.func) + + args = [] + args_source = AttrSource(self.get_source(), "args") + for i, arg in enumerate(value.args): + args.append( + VariableBuilder(self.tx, GetItemSource(args_source, i))(arg) + ) + + keywords = {} + keywords_source = AttrSource(self.get_source(), "keywords") + for k, v in value.keywords.items(): + if not ConstantVariable.is_literal(k): + unimplemented( + gb_type="functools.partial() with non-literal keyword", + context=f"non-literal keyword: {k}", + explanation="functools.partial() expects literal/string keywords", + hints=[*graph_break_hints.USER_ERROR], + ) + keywords[k] = VariableBuilder( + self.tx, DictGetItemSource(keywords_source, k) + )(v) + + install_guard( + self.get_source().make_guard(GuardBuilder.TYPE_MATCH), + keywords_source.make_guard(GuardBuilder.DICT_KEYS_MATCH), + args_source.make_guard(GuardBuilder.SEQUENCE_LENGTH), + ) + # Preserve cache_hash for SAC context_fn caching + original_cache_hash = getattr(value, "cache_hash", None) + return FunctoolsPartialVariable( + func_obj, args, keywords, original_cache_hash=original_cache_hash + ) + elif is_typing(value): + # typing.List, typing.Mapping, etc. + self.install_guards(GuardBuilder.ID_MATCH) + return TypingVariable( + value, + source=self.source, + ) + elif np is not None and isinstance(value, np.generic): + # numpy array scalars: convert to 0D arrays + return self.wrap_numpy_ndarray(np.asarray(value)) + elif trace_rules.is_numpy(value): + if not np: + raise AssertionError("numpy must be available for numpy tracing") + if istype(value, types.MethodType): + # Don't guard on cython functions as they don't change ids + if inspect.isfunction(value.__func__): + install_guard( + AttrSource(self.source, "__func__").make_guard( + GuardBuilder.CLOSURE_MATCH + ) + ) + elif inspect.isclass(value): + self.install_guards(GuardBuilder.CLASS_MATCH) + elif inspect.isfunction(value): + self.install_guards(GuardBuilder.CLOSURE_MATCH) + elif callable(value): + self.install_guards(GuardBuilder.ID_MATCH) + else: + self.install_guards(GuardBuilder.TYPE_MATCH) + return NumpyVariable(value, source=self.source) + elif trace_rules.is_numpy_dtype(value): + self.install_guards(GuardBuilder.ID_MATCH) + return NumpyDTypeVariable(value, source=self.source) + elif trace_rules.is_numpy_type_info(value): + if isinstance(value, np.iinfo): + self.install_guards(GuardBuilder.TYPE_MATCH) + dt_source = AttrSource(self.source, "dtype") + install_guard(dt_source.make_guard(GuardBuilder.ID_MATCH)) + else: + self.install_guards(GuardBuilder.ID_MATCH) + return ConstantLikeVariable(value, source=self.source) + # NB: These can't be put in type_dispatch, they have to run later + elif CollectiveFunctionRewriteVariable.can_rewrite(value): + self.install_guards(GuardBuilder.CLOSURE_MATCH) + return CollectiveFunctionRewriteVariable.create( + self.tx, + value, + source=self.source, + ) + elif istype(value, torch.autograd.function.FunctionMeta): + self.install_guards(GuardBuilder.CLASS_MATCH) + return AutogradFunctionVariable( + value, + source=self.source, + ) + elif isinstance(value, torch.autograd.function.FunctionCtx): + actual_saved_tensors = None + try: + # type: ignore[attr-defined] + actual_saved_tensors = value.saved_tensors + except RuntimeError: + pass + + saved_tensors = [] + guards = [self.source.make_guard(GuardBuilder.TYPE_MATCH)] + if isinstance(actual_saved_tensors, tuple): + saved_tensors_source = AttrSource(self.source, "saved_tensors") + guards.append( + saved_tensors_source.make_guard(GuardBuilder.SEQUENCE_LENGTH) + ) + for i, v in enumerate(actual_saved_tensors): + saved_tensors.append( + VariableBuilder( + self.tx, GetItemSource(saved_tensors_source, i) + )(v) + ) + install_guard(*guards) + + return self.tx.output.side_effects.track_object_existing( + value, + AutogradFunctionContextVariable( + value, + source=self.source, + saved_tensors=SavedTensorBox(saved_tensors), + ), + ) + elif ( + isinstance(value, types.MethodType) + and istype( + getattr(value, "__self__", None), torch.autograd.function.FunctionMeta + ) + and getattr(value, "__name__", "") == "apply" + and value == getattr(value.__self__, "apply", None) + ): + # handle aliased autograd function `apply` calls + install_guard( + AttrSource(self.get_source(), "__func__").make_guard( + GuardBuilder.CLOSURE_MATCH + ) + ) + return GetAttrVariable( + AutogradFunctionVariable( + value.__self__, + source=AttrSource(self.source, member="__self__"), + ), + "apply", + py_type=type(value), + ) + elif ( + isinstance(value, types.MethodType) + and value.__name__ in ("shuffle", "sample", "seed") + and isinstance(value.__self__, random.Random) + and RandomVariable.is_supported_random_obj(value.__self__) + ): + # Module-level random.shuffle/random.sample/random.seed are methods + # bound to the module-global random.Random instance. The + # scalar-returning helpers (random.random/randint/randrange/uniform) + # already have a dedicated RandomValueSource path in + # UserDefinedObjectVariable; these return sequences or mutate the RNG + # state instead, so route them through RandomVariable to model the + # RNG state rather than skipping into the random module. + random_self = value.__self__ + obj_source = self.source and AttrSource(self.source, "__self__") + obj_vt = VariableTracker.build(self.tx, random_self, obj_source) + return GetAttrVariable(obj_vt, value.__name__, py_type=type(value)) + elif ( + isinstance(value, types.BuiltinMethodType) + and isinstance(value.__self__, random.Random) + and RandomVariable.is_supported_random_obj(value.__self__) + and value in UserDefinedObjectVariable._supported_random_functions() + ): + # Module-level random.random is a C builtin method bound to the + # module-global random.Random instance (unlike randint/randrange/ + # uniform, which are Python-level methods). Route it through + # UserDefinedObjectVariable so its call_random_fn / RandomValueSource + # path models the RNG value instead of skipping into the C builtin. + self.install_guards(GuardBuilder.FUNCTION_MATCH) + return UserDefinedObjectVariable(value, source=self.source) + elif isinstance(value, torch._C._ImperativeEngine): + self.install_guards(GuardBuilder.ID_MATCH) + return AutogradEngineVariable(value, source=self.source) + elif ( + value + is torch._dynamo.external_utils.FakeCompiledAutogradEngine._exec_final_callbacks_stub + ): + self.install_guards(GuardBuilder.CLOSURE_MATCH) + return LambdaVariable( + lambda: UserFunctionVariable( + torch._dynamo.external_utils.FakeCompiledAutogradEngine.exec_final_callbacks, + ).call_function( + self.tx, + [self.tx.output.side_effects.get_ca_final_callbacks_var()], + {}, + ) + ) + elif isinstance(value, DynamoConfigPatchProxy): + return DynamoConfigPatchVariable(value.changes) + elif isinstance(value, ErrorOnGraphBreakDecoratorContextManager): + return ErrorOnGraphBreakVariable(value.error_on_graph_break) + elif isinstance(value, CudagraphOverrideContextManager): + return CudagraphOverrideVariable(value.fwd, value.bwd) + elif callable(value) and trace_rules.lookup_callable(value) is not None: + if trace_rules.is_callable_allowed(value): + self.tx.output.has_user_defined_allowed_in_graph = True + # type: ignore[attr-defined] + return trace_rules.lookup_callable(value).create_with_source( + value, source=self.source + ) + elif np and isinstance(value, np.number): + return self.wrap_unspecialized_primitive(value) + elif isinstance(value, HigherOrderOperator): + if value is torch._higher_order_ops.invoke_subgraph: + unimplemented( + gb_type="Attempted to wrap torch._higher_order_ops.invoke_subgraph", + context="", + explanation="Directly using invoke_subgraph is not supported. Use nested_compile_region", + hints=[], + ) + self.install_guards(GuardBuilder.TYPE_MATCH) + return TorchHigherOrderOperatorVariable.make(value, source=self.source) + elif isinstance(value, torch.cuda.StreamContext): + self.install_guards(GuardBuilder.ID_MATCH) + stream_source = AttrSource(self.source, "stream") + stream_var = VariableBuilder(self.tx, stream_source)(value.stream) + # type: ignore[arg-type] + return StreamContextVariable.create(self.tx, stream_var) + elif isinstance(value, torch.Stream): + self.install_guards(GuardBuilder.TYPE_MATCH) + if isinstance(self.source, CurrentStreamSource): + # Reuse the index pre-allocated in SymbolicStreamState.__init__ + index = CURRENT_STREAM_INDEX + else: + index = register_user_object(value, self.source) + stream_proxy = self.tx.output.create_proxy( + "call_function", get_external_object_by_index, (index,), {} + ) + set_example_value(stream_proxy.node, value) + var = StreamVariable( + stream_proxy, value, source=self.source, user_object_index=index + ) + return self.tx.output.side_effects.track_object_existing(value, var) + elif isinstance(value, torch.cuda.MemPool): + self.install_guards(GuardBuilder.TYPE_MATCH) + index = register_user_object(value, self.source) + mempool_proxy = self.tx.output.create_proxy( + "call_function", get_external_object_by_index, (index,), {} + ) + set_example_value(mempool_proxy.node, value) + var = CUDAMemPoolVariable( + mempool_proxy, value, source=self.source, user_object_index=index + ) + return self.tx.output.side_effects.track_object_existing(value, var) + elif isinstance(value, (torch._C._SDPAParams)): + self.install_guards(GuardBuilder.TYPE_MATCH) + return SDPAParamsVariable.create(self.tx, value, self.source) + elif isinstance(value, torch._functorch.pyfunctorch.FuncTorchInterpreter): + self.install_guards(GuardBuilder.ID_MATCH) + return FuncTorchInterpreterVariable(value) + elif isinstance(value, torch.Event): + self.install_guards(GuardBuilder.TYPE_MATCH) + index = register_user_object(value, self.source) + event_proxy = self.tx.output.create_proxy( + "call_function", + get_external_object_by_index, + (index,), + {}, + ) + set_example_value(event_proxy.node, value) + return EventVariable( + event_proxy, + value, + index, + source=self.source, + ) + elif ( + istype(value, contextlib.nullcontext) + and inspect.getattr_static(value, "enter_result", None) is None + ): + self.install_guards(GuardBuilder.TYPE_MATCH) + return NullContextVariable(source=self.source) + elif KeyedJaggedTensorVariable.is_matching_object(value): + self.install_guards(GuardBuilder.TYPE_MATCH) + result = KeyedJaggedTensorVariable(value, source=self.source) + # TODO: this doing it manually is bad + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, torch.optim.Optimizer): + self.install_guards(GuardBuilder.ID_MATCH) + self.source = OptimizerSource(self.source) + return OptimizerVariable( + value, + source=self.source, + mutation_type=AttributeMutationExisting(), + ) + elif isinstance(value, torch.DispatchKeySet): + self.install_guards(GuardBuilder.DISPATCH_KEY_SET_MATCH) + return DispatchKeySetVariable(value) + elif WorldMetaClassVariable.is_group_member_type(value): + return WorldMetaClassVariable(value, source=self.source) + elif value is OrderedSet: + self.install_guards(GuardBuilder.ID_MATCH) + return OrderedSetClassVariable() + elif ( + id(value) in ITERTOOLS_TYPE_IDS + and id(value) not in ITERTOOLS_POLYFILLED_TYPE_IDS + ): + self.install_guards(GuardBuilder.CLASS_MATCH) + return ItertoolsVariable(value, source=self.source) + elif isinstance(value, _DynamicScalar): + is_int = isinstance(value, DynamicInt) + source = DynamicScalarSource(self.source, is_int) + if id(value) in self.tx.output.root_tracer.dynamic_scalar_nodes: + # If we've already seen this dynamic scalar, reuse the existing + # SymInt/SymFloat node. + node = self.tx.output.root_tracer.dynamic_scalar_nodes[id(value)] + else: + sym = self.tx.output.shape_env.create_unspecified_symbol( + value.real, # type: ignore[attr-defined] + source=source, + dynamic_dim=DimDynamic.DYNAMIC, + ) + node = self.tx.output.shape_env.create_symintnode( + sym, + hint=value.real, # type: ignore[attr-defined] + source=source, + ) + if not isinstance(node, SymInt): + raise AssertionError(f"Expected SymInt, got {type(node)}") + + # Bind to graph input + sym_node_proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(node), + node, + source=source, + ) + sym_node_proxy.node.meta["grapharg"] = GraphArg( + source, + node, + False, + None, + is_tensor=False, + example_strong_ref=node, + ) + sym_expr = node.node.expr + if not isinstance(sym_expr, sympy.Symbol): + raise AssertionError(f"{sym_expr} is not a basic Symbol.") + self.tx.output.tracked_fakes.append(TrackedFake(node, source, None)) + return SymNodeVariable.create(self.tx, sym_node_proxy, node) + elif is_torch_sym(value): + # Note: this doesn't handle nested symints. + # For SymBool input, we reuse the infra for SymInt by simulating SymBool with a SymInt in dynamo. + + # Concretely, + # 1. We create a SymInt in dynamo's shape_env, whose source is constructed as ConvertIntSource(self.source). + # so that guards on the SymInts can be effectively applied on the original SymBool in user program. + # 2. We create a SymBool based on the SymInt in dynamo's ShapeEnv. Because the original user program + # depends on the value being a SymBool. This allows dynamo to interpret the user's program correctly. + source = ( + self.source + if isinstance(value, torch.SymInt) + else ConvertIntSource(self.source) + ) + new_symint = None + if value.node.has_hint(): + new_symint = ( + self.tx.output.shape_env.create_unspecified_symint_and_symbol( + int(value.node.hint), # type: ignore[bad-argument-type] + source, + dynamic_dim=DimDynamic.DYNAMIC, + ) + ) + else: + if isinstance(value, torch.SymBool): + # We need to create an unbacked symint to replace the unbacked symbool. + new_symint = self.tx.output.shape_env.create_unbacked_symint() + else: + shape_env = self.tx.output.shape_env + if not torch.compiler._is_non_strict_tracing(): + # TODO: Need to enable this for Dynamo after broader + # verification. See + # test_raw_unbacked_symint_input_graph_breaks_outside_non_strict. + unimplemented( + gb_type="Attempted to wrap unbacked SymInt", + context="", + explanation="Unbacked SymInt input is not supported yet.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + if value.node.shape_env is shape_env: + # SymInt already belongs to this ShapeEnv; no + # transfer needed, reuse it directly. + new_symint = value + else: + new_expr = shape_env._transfer_foreign_expr_as_unbacked( + value, source=source + ) + new_symint = shape_env.create_symintnode( + new_expr, hint=None, source=source + ) + if new_symint is None: + raise AssertionError("new_symint must not be None after wrapping") + if not isinstance(new_symint, SymInt): + raise AssertionError(f"Expected SymInt, got {type(new_symint)}") + sym_node_proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(new_symint), + new_symint, + source=source, + ) + + sym_node_proxy.node.meta["grapharg"] = GraphArg( + source, + new_symint, + False, + None, + is_tensor=False, + example_strong_ref=new_symint, + ) + sym_expr = new_symint.node.expr + if isinstance(sym_expr, sympy.Symbol): + self.tx.output.tracked_fakes.append( + TrackedFake(new_symint, source, None) + ) + + tracing_symint = ( + new_symint if isinstance(value, torch.SymInt) else new_symint == 1 + ) # cast it back to symbool for tracing + return SymNodeVariable(sym_node_proxy, tracing_symint) + + elif isinstance(value, (JITFunction, Autotuner)): + self.install_guards(GuardBuilder.ID_MATCH) + return TritonKernelVariable( + value, + None, # No kernel idx provided + None, # No grid provided + source=self.source, + ) + elif value is create_1d_tma_descriptor: + return CreateTMADescriptorExperimentalVariable(rank=1) + elif value is create_2d_tma_descriptor: + return CreateTMADescriptorExperimentalVariable(rank=2) + elif value is TensorDescriptor.from_tensor: + return CreateTMADescriptorStableVariable() + elif value is set_allocator: + return TritonSetAllocatorVariable(value) + elif isinstance(value, torch.amp.autocast_mode.autocast): + if isinstance(value, torch.amp.autocast_mode._UnmanagedAutocast): + return self.wrap_user_defined(value) + else: + self.install_guards(GuardBuilder.ID_MATCH) + return AutocastModeVariable( + target_values=[ + value.device, + value.fast_dtype, + value._enabled, + value._cache_enabled, + ], + source=self.source, + ) + elif TorchCtxManagerClassVariable.is_matching_cls(value): + if inspect.isclass(value): + self.install_guards(GuardBuilder.CLASS_MATCH) + elif inspect.isfunction(value): + self.install_guards(GuardBuilder.CLOSURE_MATCH) + return TorchCtxManagerClassVariable(value, source=self.source) + elif inspect.getattr_static(value, "__script_if_tracing_wrapper", False): + self.install_guards(GuardBuilder.TYPE_MATCH) + return WrapperUserFunctionVariable( + value, + "__original_fn", + source=self.source, + mutation_type=AttributeMutationExisting(), + ) + elif is_lru_cache_wrapped_function(value): + self.install_guards(GuardBuilder.TYPE_MATCH) + return WrapperUserFunctionVariable( + value, + "__wrapped__", + source=self.source, + mutation_type=AttributeMutationExisting(), + ) + elif value is sys.exc_info or ( + sys.version_info >= (3, 11) and value is sys.exception + ): + return SysFunctionVariable(value, source=self.source) + elif is_function_or_wrapper(value) and inspect.getattr_static( + value, "_torchdynamo_inline", False + ): + self.install_guards(GuardBuilder.TYPE_MATCH) + return WrapperUserFunctionVariable( + value, + "_torchdynamo_inline", + source=self.source, + mutation_type=AttributeMutationExisting(), + ) + elif value is collections.namedtuple: + self.install_guards(GuardBuilder.ID_MATCH) + return CollectionsNamedTupleFunction(value, source=self.source) + elif (descriptor := bound_builtin_method_descriptor(value)) is not None: + self.install_guards(GuardBuilder.ID_MATCH) + method_self = value.__self__ + obj_source = self.source and AttrSource(self.source, "__self__") + obj_vt = VariableTracker.build(self.tx, method_self, obj_source) + return BoundBuiltinMethodVariable(descriptor, obj_vt, source=self.source) + elif is_function(value) and value in (float.fromhex, float.hex): + self.install_guards(GuardBuilder.ID_MATCH) + return GetAttrVariable( + BuiltinVariable(float, source=self.source), + value.__name__, + py_type=type(value), + ) + elif is_function_or_wrapper(value): + value, attr_name = unwrap_with_attr_name_if_wrapper(value) + # For these wrappers, Dynamo points to the wrapped function, + # so source needs to be updated as well. + if attr_name is not None: + self.source = AttrSource(self.source, attr_name) + # type: ignore[attr-defined] + return trace_rules.lookup(value).create_with_source( + value, source=self.source + ) + elif value is random.Random: + self.install_guards(GuardBuilder.ID_MATCH) + return RandomClassVariable(source=self.source) + elif istype(value, random.Random) and RandomVariable.is_supported_random_obj( + value + ): + self.install_guards(GuardBuilder.TYPE_MATCH) + result = RandomVariable(value, source=self.source) + self.tx.output.side_effects.track_mutable(value, result) + return result + # Don't use istype, since some python modules are not subclasses of types.ModuleType directly. + # E.g, type(torch.ops) -> , + # type(torch.backends.cudnn) -> + elif isinstance(value, (types.ModuleType, replay_record.DummyModule)): + from torch.utils import _config_module + + if isinstance(value, _config_module.ConfigModule): + self.install_guards(GuardBuilder.MODULE_MATCH) + return UserDefinedObjectVariable(value, source=self.source) + self.install_guards(GuardBuilder.MODULE_MATCH) + result = PythonModuleVariable( + # type: ignore[arg-type] + value, + source=self.source, + ) + self.tx.output.side_effects.track_object_existing(value, result) + return result + elif ( + istype(value, types.GeneratorType) + and inspect.getgeneratorstate(value) == inspect.GEN_CREATED + ): + self.install_guards(GuardBuilder.ID_MATCH) + code = value.gi_code + frame = value.gi_frame + if frame is None: + raise AssertionError("GEN_CREATED implies a live frame") + frame_locals = frame.f_locals + closure = tuple(types.CellType(frame_locals[n]) for n in code.co_freevars) + fn = types.FunctionType(code, frame.f_globals, closure=closure) + args = [ + VariableTracker.build(self.tx, frame_locals[n]) + for n in code.co_varnames[: code.co_argcount] + ] + genfn = LocalGeneratorFunctionVariable(VariableTracker.build(self.tx, fn)) + return genfn.call_function(self.tx, args, {}) + elif isinstance(value, contextvars.ContextVar): + from .misc import ContextVarVariable + + self.install_guards(GuardBuilder.ID_MATCH) + return ContextVarVariable( + cv_obj=value, + source=self.source, + ) + elif isinstance(value, types.GetSetDescriptorType): + # GetSet descriptors are C functions attached to an attribute lookup + # using PyGetSetDef. Python, on attribute lookup, can decide to + # create a new object on the fly, and therefore the `id` of the + # descriptors is not guaranteed to be same for different attribute + # accesses. Since these are unlikely to change during the program + # execution, we can skip guarding on them. + return GetSetDescriptorVariable(value) + elif isinstance(value, types.MemberDescriptorType): + return MemberDescriptorVariable(value) + elif isinstance(value, types.MethodWrapperType): + # Method-wrappers are written in C, and they are not guaranteed to + # return the same object on attribute lookup. Therefore, we cannot + # insert a ID_MATCH guard here. method-wrappers are very + # unlikely to change, so its ok to skip the guard here. + descriptor = inspect.getattr_static(type(value.__self__), value.__name__) + if not isinstance(descriptor, types.WrapperDescriptorType): + raise AssertionError( + f"expected WrapperDescriptorType, got {type(descriptor)}" + ) + obj_source = self.source and AttrSource(self.source, "__self__") + obj_vt = VariableTracker.build(self.tx, value.__self__, obj_source) + return MethodWrapperVariable(descriptor, obj_vt) + elif issubclass(type(value), type) and issubclass(value, BaseException): + # match user defined exceptions + self.install_guards(GuardBuilder.ID_MATCH) + return UserDefinedExceptionClassVariable(value) + elif issubclass(type(value), type): + if value in ( + torch.utils.hooks.BackwardHook, + torch.nn.Parameter, + torch.nn.Buffer, + torch.backends.cuda.SDPAParams, + ): + # TODO(jansel): combine this case with the one above + # type: ignore[attr-defined] + return trace_rules.lookup(value).create_with_source( + value, source=self.source + ) + if value is torch.autograd._unsafe_preserve_version_counter: + self.install_guards(GuardBuilder.CLASS_MATCH) + return PreserveVersionContextVariable.constructor(self.tx) + if ( + # `value` must be a strict subclass of `torch.Tensor` + issubclass(value, torch.Tensor) + and value is not torch.Tensor + # `TensorSubclassVariable` is not for subclass that overrides + # `torch_dispatch`. + and value.__torch_dispatch__ is torch.Tensor.__torch_dispatch__ + # `TensorSubclassVariable` would lead to construction of + # `TensorWithTFOverrideVariable`, but we don't want that for + # traceable wrapper subclasses (we wrap those subclass instances + # into `TensorVariable`). + and not is_traceable_wrapper_subclass_type(value) + ): + return TensorSubclassVariable(value, source=self.source) + + if not is_from_closure_source(self.source): + # For closure source, the variable comes from LOAD_SUPER_ATTR, + # which calls self.__class__. This is internal Cpython + # implementation, and it is rare for the user to modify + # self.__class__ manually. + # For other cases, this is a userdefined class, so install an + # ID_MATCH even if its a global variable. + self.install_guards(GuardBuilder.CLASS_MATCH) + + if isinstance(value, type) and issubclass(value, enum.Enum): + return UserDefinedClassVariable( + value, + source=self.source, + ) + + if is_custom_class(value): + return CustomClassVariable( + value, + source=self.source, + ) + + result = UserDefinedClassVariable( + value, + source=self.source, + ) + + # Only track user-defined classes for mutation, not torch + # internals. Tracking torch classes (e.g. RemovableHandle) causes + # side effects like next_id increments to be replayed incorrectly, + # and source chains through C-level descriptors break guard + # evaluation. + mod = getattr(value, "__module__", None) or "" + if mod != "torch" and not mod.startswith(("torch.", "torch_")): + if value not in self.tx.output.side_effects: + return self.tx.output.side_effects.track_object_existing( + value, result + ) + return result + + elif type(value) is torch._C.Generator: + # Generator is registered as an opaque reference type for make_fx + # tracing, but in dynamo we handle it as a regular object so that + # trace_rules-based graph breaks (e.g. initial_seed, manual_seed) + # work gracefully — allowing dynamo to compile code before and + # after the generator call. CustomClassObjectVariable's tp_getattro_impl + # and call_method are decorated with @_raise_hard_error_if_graph_break, + # which turns any graph break into a hard error that falls back to + # eager for the entire function. Generator methods intentionally + # graph-break (they mutate/read RNG state), so they need the + # UserDefinedObjectVariable path which supports graceful graph breaks. + return self.wrap_user_defined(value) + elif CustomClassObjectVariable.is_matching_cls(type(value)): + from ..source import ( + FlattenScriptObjectSource, + ScriptObjectQualifiedNameSource, + ) + + # Unwrap FakeScriptObject to the underlying real object so the + # rest of this branch (guards, graph inputs, etc.) operates on + # the real opaque object type. + if isinstance(value, torch._library.fake_class_registry.FakeScriptObject): + value = value.real_obj + + # type: ignore[arg-type] + if torch._library.fake_class_registry.tracing_with_real(value): + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(value), + value, + source=self.source, + ) + + # setting is_unspecialized=False to not insert a as_tensor call in reconstruct by default + # setting example to be real value because these example values will be used + # as example_inputs for user compiler. + proxy.node.meta["grapharg"] = GraphArg( + self.source, + value, + False, + None, + False, + value, # type: ignore[arg-type] + ) + return CustomClassObjectVariable.create( + proxy, + value, + source=self.source, + tx=self.tx, + ) + + if is_opaque_constant_type(type(value)): + # Value-type: guard on equality (will use __eq__) + self.install_guards(GuardBuilder.CONSTANT_MATCH) + elif is_opaque_symbolic_type(type(value)): + # Symbolic-type: guard only on type, and registered guard_fn. + # Use FAKE_SCRIPT_TYPE_MATCH because at runtime the source may + # resolve to either a FakeScriptObject (during outer + # AOTAutograd tracing) or the underlying real opaque object. + self.install_guards(GuardBuilder.FAKE_SCRIPT_TYPE_MATCH) + self.install_guards(GuardBuilder.OPAQUE_OBJ_GUARD_FN_MATCH) + elif not hasattr(value, "__obj_flatten__"): + # This exists to allow a smoother transition. + # The implications are: + # The script objects won't be tracked as proxies. + # Methods on these objects won't show up in the graph. + # The original script object might be mutated. + return self.wrap_user_defined(value) + else: + # Install the guards on the fully qualified name of the script object + LazyVariableTracker.realize_all( + VariableBuilder( + self.tx, ScriptObjectQualifiedNameSource(self.source) + )( + value._type().qualified_name() # type: ignore[attr-defined] + ) + ) + # Install the guards on the content of the script object by setting the source + # to be FlattenScriptObjectSource, which calls __obj_flatten__() to get the contents. + LazyVariableTracker.realize_all( + VariableBuilder(self.tx, FlattenScriptObjectSource(self.source))( + value.__obj_flatten__() + ) + ) + + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + self.tx.output.fake_mode, value + ) + if is_opaque_constant_type(type(value)) and not should_hoist(type(value)): + fake_script_obj = value + proxy = value + + elif config.install_free_tensors and ( + is_from_global_source(self.source) + or is_from_nonlocal_source(self.source) + or is_from_unspecialized_nn_module_source(self.source) + ): + return self.tx.output.register_attr_or_module( + value, self.name, source=self.source + ) + + else: + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(value), + fake_script_obj, + source=self.source, + ) + # setting is_unspecialized=False to not insert a as_tensor call in reconstruct by default + # setting example to be real value because these example values will be used + # as example_inputs for user compiler. + proxy.node.meta["grapharg"] = GraphArg( + self.source, + value, # type: ignore[arg-type] + False, + None, + False, + fake_script_obj, # type: ignore[arg-type] + ) + + return CustomClassObjectVariable.create( + proxy, # pyrefly: ignore[bad-argument-type] + fake_script_obj, + source=self.source, + tx=self.tx, + ) + elif ( + isinstance(value, (dict, collections.OrderedDict)) + and type(value).__new__ is dict.__new__ + ): + # Construct a dict_vt that will reside inside the UserDefinedDictVariable + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + + # Guard on the key order + self.tx.output.guard_on_key_order.add(self.source) + + # We need all the keys to be hashable. We do this within the + # HashableTracker class in hashable.py + def build_key_value( + i: Any, k: Any, v: Any + ) -> tuple[VariableTracker, VariableTracker]: + base = self.get_source() + source_key = ConstDictKeySource(base, i) + key = LazyVariableTracker.create(k, source_key, tx=self.tx) + + source_value = DictSubclassGetItemSource(base, source_key) + res_value = LazyVariableTracker.create(v, source_value, tx=self.tx) + + return key, res_value + + result = dict( + build_key_value(i, k, v) + for i, k, v in enumerate_items_with_dict_position(value) + ) + + dict_vt_cls = ( + OrderedDictVariable + if isinstance(value, collections.OrderedDict) + else ConstDictVariable + ) + dict_vt = dict_vt_cls( + result, + mutation_type=ValueMutationExisting(), + source=self.source, + ) + # Force this to reconstruct on mutation to keep the reconstruction + # bytecode simple + dict_vt.should_reconstruct_all = True + + result = UserDefinedDictVariable(value, dict_vt=dict_vt, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, tuple): + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + + # NB - Be careful in not triggering user code. Guards also work on + # the underlying tuple data structure. + output = [ + LazyVariableTracker.create( + tuple.__getitem__(value, i), + source=GetItemSource(self.get_source(), i), + tx=self.tx, + ) + for i in range(tuple.__len__(value)) + ] + + tuple_vt = TupleVariable( + output, # type: ignore[arg-type] + source=self.source, + mutation_type=ValueMutationExisting(), + ) + result = UserDefinedTupleVariable( + value, tuple_vt=tuple_vt, source=self.source + ) + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, list): + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + + # NB - Be careful in not triggering user code. Guards also work on + # the underlying list data structure. + output = [ + LazyVariableTracker.create( + list.__getitem__(value, i), + source=ListGetItemSource(self.get_source(), i), + tx=self.tx, + ) + for i in range(list.__len__(value)) + ] + list_vt = ListVariable( + output, # type: ignore[arg-type] + source=self.source, + mutation_type=ValueMutationExisting(), + ) + result = UserDefinedListVariable(value, list_vt=list_vt, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, collections.deque): + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + # maxlen is baked into the DequeVariable as a constant, so guard on + # it to recompile if a same-typed deque with a different maxlen + # appears. + install_guard( + AttrSource(self.source, "maxlen").make_guard(GuardBuilder.EQUALS_MATCH) + ) + + output = [ + LazyVariableTracker.create( + collections.deque.__getitem__(value, i), + source=GetItemSource(self.get_source(), i), + tx=self.tx, + ) + for i in range(collections.deque.__len__(value)) + ] + deque_vt = DequeVariable( + output, # type: ignore[arg-type] + maxlen=ConstantVariable.create(value.maxlen), + source=self.source, + mutation_type=ValueMutationExisting(), + ) + result = UserDefinedDequeVariable( + value, deque_vt=deque_vt, source=self.source + ) + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, (set, frozenset)): + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + + L = list(set_base_iter(value)) + output = [ + LazyVariableTracker.create( + list.__getitem__(L, i), + source=NonSerializableSetGetItemSource(self.get_source(), i), + tx=self.tx, + ) + for i in range(list.__len__(L)) + ] + if isinstance(value, set): + set_vt_cls = SetVariable + else: + if not isinstance(value, frozenset): + raise AssertionError(f"Expected frozenset, got {type(value)}") + set_vt_cls = FrozensetVariable + + set_vt = set_vt_cls( + output, source=self.source, mutation_type=ValueMutationExisting() + ) + result = UserDefinedSetVariable(value, set_vt=set_vt, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif issubclass(type(value), MutableMapping): + self.install_guards(GuardBuilder.TYPE_MATCH) + result = MutableMappingVariable(value, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif is_frozen_dataclass(value): + self.install_guards(GuardBuilder.TYPE_MATCH) + result = FrozenDataClassVariable(value, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, dict_keys): + if all(ConstantVariable.is_literal(k) for k in value): + # If the dict_keys object is passed from outside the compile region, it must either be passed along with + # the corresponding dict object or treated as a set (when only the keys are passed into the compiled region). + # - If it is passed along with the dict, the dict object itself is already guarded. + # - If only the dict_keys object is passed, we add EQUALS_MATCH and SEQUENCE_LENGTH guards + # to ensure it remains unchanged across multiple runs. + items = [SourcelessBuilder.create(self.tx, v) for v in value] + install_guard( + self.get_source().make_guard(GuardBuilder.SEQUENCE_LENGTH), + self.get_source().make_guard(GuardBuilder.EQUALS_MATCH), + ) + return DictKeySetVariable(items, source=self.source) + else: + unimplemented( + gb_type="non-const keys in dict_keys", + context=f"non-const keys: {[k for k in value if not ConstantVariable.is_literal(k)]}", + explanation="Dynamo expects dict_keys keys to be constants.", + hints=[ + "Ensure your dict_keys keys are constants (e.g. int, float, strings)", + ], + ) + elif IntWrapperVariable.is_matching_object(value): + from torch.export.dynamic_shapes import _DimHintType + + if value.dynamism is None or value.dynamism.type == _DimHintType.STATIC: + return self.wrap_symint(value.val) + elif value.dynamism.type == _DimHintType.DYNAMIC: + log.debug( + "%s marked %s via IntWrapper", + self.source.name, + DimDynamic.DYNAMIC, + ) + return self.wrap_symint( + value.val, + dynamism=DimDynamic.DYNAMIC, + context=SymIntSymbolicContext( + constraint=RelaxedUnspecConstraint(warn_only=False) + ), + ) + elif value.dynamism.type == _DimHintType.AUTO: + log.debug( + "%s marked %s via IntWrapper", + self.source.name, + DimDynamic.DYNAMIC, + ) + return self.wrap_symint(value.val, dynamism=DimDynamic.DYNAMIC) + else: + raise RuntimeError(f"Undefined dynamism {value.dynamism}") + elif istype(value, object): + self.install_guards(GuardBuilder.TYPE_MATCH) + return ObjectVariable(value, source=self.source) + elif ( + sys.version_info >= (3, 15) + and type(value) is builtins.sentinel # pyrefly: ignore [missing-attribute] + ): + self.install_guards(GuardBuilder.ID_MATCH) + return SentinelVariable(value, source=self.source) + else: + return self.wrap_user_defined(value) + + def wrap_user_defined(self, value: Any) -> VariableTracker: + from .ctx_manager import GenericContextWrappingVariable + from .user_defined import _CONSTANT_BASE_TYPES, is_generic_ctx_manager_cls + + self.install_guards(GuardBuilder.TYPE_MATCH) + if InspectVariable.is_matching_object(value): + # Skip guards on inspect related variable trackers because they are + # not important for recompiles (something else will also change to + # cause recompiles) and can cause a large number of OBJECT_ALIASING + # guards. + result = InspectVariable(value, source=SkipGuardSource(self.source)) + elif ( + isinstance(value, _CONSTANT_BASE_TYPES) + and type(value) not in common_constant_types + ): + self.install_guards(GuardBuilder.CONSTANT_SUBCLASS_MATCH) + result = UserDefinedConstantVariable(value, source=self.source) + elif is_generic_ctx_manager_cls(type(value)): + # A generic context manager built inside the compiled region (via + # SideEffects.get_variable_cls) must wrap the same way when it is + # reconstructed from a source across a graph break, so a `with` on + # the reconstructed object can still be entered. + result = GenericContextWrappingVariable(value, source=self.source) + else: + result = UserDefinedObjectVariable(value, source=self.source) + if not SideEffects.cls_supports_mutation_side_effects(type(value)): + # don't allow STORE_ATTR mutation with custom __setattr__ + return result + return self.tx.output.side_effects.track_object_existing(value, result) + + def wrap_listlike( + self, value: Union[tuple[Any, ...], list[Any], odict_values, NamedTuple] + ) -> VariableTracker: + if config.specialize_int and type(value) is torch.Size: + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value) + + # One can index a tensor with a list/tuple. Therefore, we need to + # have a stricter match. + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + + # Tuples are immutable objects, so we should mark its items static. This + # avoids wrapping of tuple items as symints. This helps for nn module + # attributes like conv2d strides, dilations. + if ( + istype(value, tuple) + and all(ConstantVariable.is_literal(item) for item in value) + and self.source.guard_source.is_unspecialized_nn_module() + ): + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return TupleVariable([ConstantVariable.create(item) for item in value]) + + output = [ + LazyVariableTracker.create( + item, + source=GetItemSource(self.get_source(), i), + tx=self.tx, + ) + for i, item in enumerate(value) + ] + + maybe_gm = self.tx.output.local_scope.get("self") + if isinstance( + self.source, LocalSource + ) and self.source.local_name in get_locals_to_steal(maybe_gm): + # The input tensor list to dynamo from compiled autograd may contain activations + # which are freed as they are used in inductor. Dynamo's default behavior is to + # lift all tensors to the graph inputs, but this will cause dynamo to hold an + # extra reference to the activation tensors and increase peak memory usage. + # To allow freeing ASAP, we keep the list as graph argument to the dynamo output + # graph, and unpack it locally. + # e.g. instead of `def forward(self, L_inputs_0_, L_inputs_1_, ...):`, we have + # `def forward(self, L_inputs_):` + source = self.source + if not isinstance(value, list): + raise AssertionError(f"Expected list for steal_arg, got {type(value)}") + tensor_list_proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(value), + value, + source=source, + ) + tensor_list_proxy.node.meta["steal_arg"] = True + + list_variable = wrap_fx_proxy_cls( + target_cls=TensorVariable, + tx=self.tx, + proxy=tensor_list_proxy, + example_value=value, + subclass_type=None, + source=source, + ) + + # Apply relevant logic from `VariableTracker.build(value[i])` + # (except for the `create_graph_input` stuff). + guards = [] + # type: ignore[attr-defined] + for i, tensor_variable in enumerate(list_variable.items): + source_i = GetItemSource(base=source, index=i, index_is_slice=False) + # access unpacked tensor from this list instead of from a lifted arg + self.tx.output.input_source_to_var[source_i] = tensor_variable + tensor_variable.proxy.node.meta["tensor_dict"] = _extract_tensor_dict( + value[i] + ) + guard = functools.partial( + GuardBuilder.TENSOR_MATCH, value=TensorWeakRef(value[i]) + ) + guards.append(source_i.make_guard(guard)) + + install_guard(*guards, skip=1) + + grapharg = GraphArg( + source, + value, + pass_arg_as_tensor=False, + fake_tensor=None, + is_tensor=False, + ) + tensor_list_proxy.node.meta["grapharg"] = grapharg + + # The following is very important for maintaining the "python object + # <==> variable tracker" 1-to-1 mapping, which is mainly handled via + # `side_effects`. Note that constructing `tensor_variable` above + # already adds it to graph arg, but we never registered it with + # `side_effects`. The preemptive `realize` calls here basically + # does that registration (at the end of `self.__call__`). + # + # A slightly cleaner alternative is to register the + # `tensor_variable`s above with `side_effects` directly, and just + # return the `list_variable`, but that breaks some tensor-subclass + # related tests like `test_inputs_aliasing_bytecode_stack_restore`, + # because `tensor_variable` is constructed via + # `handle_traced_output`, which doesn't really expect/handle tensor + # subclass. + # + # Eventually, we expect to fix remove all of these by having Dynamo + # auto-boxing inputs to the compiled graph, see + # https://github.com/pytorch/pytorch/issues/153701. + for vt in output: + vt.realize() + # type: ignore[arg-type] + result = BaseListVariable.cls_for_instance(value)(output, source=self.source) + if istype(value, (list, collections.deque)): + return self.tx.output.side_effects.track_mutable(value, result) + return result + + def wrap_tuple_iterator(self, value: tuple_iterator) -> VariableTracker: + self.install_guards(GuardBuilder.TUPLE_ITERATOR_LEN) + output = [ + VariableBuilder(self.tx, TupleIteratorGetItemSource(self.get_source(), i))( + tuple_iterator_getitem(value, i) + ) + for i in range(tuple_iterator_len(value)) + ] + result = TupleIteratorVariable(output, source=self.source) + return self.tx.output.side_effects.track_mutable(value, result) + + def wrap_range_iterator(self, value: range_iterator) -> VariableTracker: + self.install_guards(GuardBuilder.RANGE_ITERATOR_MATCH) + # Get all the values from the range iterator; no need to install guards + # on items since `RANGE_ITERATOR_MATCH` guarantees the same items. + items: list[VariableTracker] = [ + ConstantVariable.create(v) for v in copy.deepcopy(value) + ] + result = ListIteratorVariable(items, source=self.source) + return self.tx.output.side_effects.track_mutable(value, result) + + def wrap_itertools_count(self, value: Any) -> VariableTracker: + current_item, step = normalize_count_iter(value) + if not ( + ConstantVariable.is_literal(current_item) + and ConstantVariable.is_literal(step) + ): + return self.wrap_user_defined(value) + + self.install_guards(GuardBuilder.COUNT_ITERATOR_MATCH) + result = CountIteratorVariable( + ConstantVariable.create(current_item), + ConstantVariable.create(step), + source=self.source, + ) + return self.tx.output.side_effects.track_mutable(value, result) + + def wrap_slice_range(self, value: slice | range) -> SliceVariable | RangeVariable: + items = [ + VariableBuilder(self.tx, AttrSource(self.get_source(), k))( + getattr(value, k) + ) + for k in ("start", "stop", "step") + ] + self.install_guards(GuardBuilder.TYPE_MATCH) + if isinstance(value, slice): + return SliceVariable(items, self.tx, source=self.source) + else: + return RangeVariable(items, source=self.source) + + def mark_static_input(self, value: torch.Tensor, guard: bool) -> None: + from ..decorators import mark_static_address + + static_inputs_log.debug( + "Marking static input %s, id: %s)", self.source.name, id(value) + ) + mark_static_address(value, guard=guard) + + # Check if we've seen this tensor before and update graph metadata if needed + # As long as this runs before AOT this is sound + if value in self.tx.output.side_effects: + var = self.tx.output.side_effects[value] + # A tensor-subclass parameter (e.g. under torch.nn.utils.parametrize) + # can be tracked as a UserDefinedObjectVariable, which has no graph + # proxy node to annotate. mark_static_address above still marks it, + # so only stamp the metadata when there is a real tensor proxy node. + if isinstance(var, TensorVariable): + var.proxy.node.meta["tensor_dict"]["_dynamo_static_input_type"] = ( + value._dynamo_static_input_type # type: ignore[attr-defined] + ) + + def wrap_module(self, value: torch.nn.Module) -> VariableTracker: + from ..eval_frame import OptimizedModule + + if len(value.__dict__) == 0: + unimplemented( + gb_type="Uninitialized nn.Module", + context=typestr(value), + explanation=f"Attempted to trace an uninitialized nn.Module of type {typestr(value)}.", + hints=[ + *graph_break_hints.USER_ERROR, + "Ensure your nn.Module instance has called `super().__init__()`.", + ], + ) + if istype(value, OptimizedModule): + # Check if the optimized module was disabled + if inspect.getattr_static(value.forward, "_torchdynamo_disable", False): + # This bytecode is mostly of kind LOAD_ATTR or LOAD_METHOD. If + # we graph break here, Dynamo does not know how to create + # continuation functions for such bytecodes. So, we delay the + # graph break to CALL_FUNCTION. + msg = inspect.getattr_static( + value.forward, "_torchdynamo_disable_msg", None + ) + return DelayGraphBreakVariable( + source=self.source, + msg=f"Optimized `nn.Module` is wrapped with `torch.compiler.disable` (reason: {msg})", + ) + + self.install_guards(GuardBuilder.TYPE_MATCH) + self.source = AttrSource(self.source, "_orig_mod") + return self.wrap_module(value._orig_mod) + + if type(value) is torch.jit._script.RecursiveScriptModule: + unimplemented( + gb_type="torch.jit.script/freeze modules unsupported", + context=str(value), + explanation="Dynamo does not support tracing into torch.jit.script or " + "torch.jit.freeze modules because they execute in the TorchScript " + "runtime, not Python. Replace the ScriptModule submodule with the " + "original eager nn.Module.", + hints=[ + *graph_break_hints.FUNDAMENTAL, + ], + ) + + if ( + isinstance(value, (torch.nn.RNN, torch.nn.GRU, torch.nn.LSTM)) + and not config.allow_rnn + ): + unimplemented( + gb_type="Attempted to wrap RNN, GRU, or LSTM", + context=str(value), + explanation="Dynamo does not support RNN, GRU, or LSTM.", + hints=[ + "Set torch._dynamo.config.allow_rnn=True to enable experimental support for RNN, GRU, and LSTM in Dynamo", + *graph_break_hints.SUPPORTABLE, + ], + ) + + if inspect.getattr_static(value, "_is_fsdp_managed_module", False): + # See note [Dynamo treats FSDP wrapped modules as UnspecializedNNModule] + # in fully_sharded_data_parallel.py for more information + + # we can't do this assert inside FSDP constructor, + # since we don't know yet whether dynamo will be used + if not inspect.getattr_static(value, "_fsdp_use_orig_params", False): + unimplemented( + gb_type="FSDP with use_orig_params=False", + context="", + explanation="Dynamo only supports FSDP with use_orig_params=True", + hints=[], + ) + + # Note on FSDP guarding + # Eager FSDP already assumes (requires, but without enforcement) + # that users don't mutate their model parameters/structure after + # FSDP wrapping, because FSDP wouldn't notice or update its + # FlatParams. + # + # Therefore, torch.compile can skip guarding on params or submodule + # structure of fsdp_managed modules, by using FSDPNNModuleSource as + # the guard source. This behavior is gated on + # config.skip_fsdp_guards. + self.install_guards(GuardBuilder.TYPE_MATCH) + result = FSDPManagedNNModuleVariable(value, source=self.get_source()) + if not SideEffects.cls_supports_mutation_side_effects(type(value)): + # don't allow STORE_ATTR mutation with custom __setattr__ + return result + return self.tx.output.side_effects.track_object_existing(value, result) + elif mutation_guard.is_dynamic_nn_module(value, self.tx.export): + # created dynamically, don't specialize on it + + # Note [Tracing a torch.compiled function] + # when make_fx tracing a compiled function, we need + if isinstance(value, torch.fx.experimental.proxy_tensor._AttrProxy): + # type: ignore[attr-defined] + value = value.get_base() + self.source = AttrProxySource(self.source) + + freezing = is_parameter_freezing() + + # Guard against the case where user may overwrite named parameters + # / named buffers + # NOTE: This is not likely to happen but worth guarding to avoid + # exception + if ( + callable(value.named_parameters) + # type: ignore[attr-defined] + and value.named_parameters.__func__ is og_module_named_parameters_fn_ptr + ): + try: # catch TypeErrors in named_parameters() from unserializable nn modules + # type: ignore[attr-defined] + for _, p in value.named_parameters(): + self.mark_static_input(p, guard=freezing) + except TypeError as e: + raise_observed_exception(type(e), self.tx, args=list(e.args)) + + if ( + callable(value.named_buffers) + # type: ignore[attr-defined] + and value.named_buffers.__func__ is og_module_named_buffers_fn_ptr + ): + try: # catch TypeErrors in named_parameters() from unserializable nn modules + # type: ignore[attr-defined] + for _, b in value.named_buffers(): + self.mark_static_input(b, guard=freezing) + except TypeError as e: + raise_observed_exception(type(e), self.tx, args=list(e.args)) + + if freezing: + # we need to add the module to tracing context + # in order to allow its params to get invalidated + # this will get cleaned up once compile ends + self.tx.output.nn_modules[self.name] = value + + if ( + value.__module__.startswith(("torch.nn.modules", "torch.ao.")) + and not value.__module__.startswith("torch.nn.modules.container") + ) or getattr(value.__class__, "_dynamo_marked_static", False): + new_source = self.source + if not self.tx.output.export or config.install_free_tensors: + new_source = UnspecializedBuiltinNNModuleSource(self.source) + result = UnspecializedBuiltinNNModuleVariable(value, source=new_source) + install_guard(new_source.make_guard(GuardBuilder.TYPE_MATCH)) + else: + new_source = self.source + if not self.tx.output.export or config.install_free_tensors: + new_source = UnspecializedNNModuleSource(self.source) + result = UnspecializedNNModuleVariable(value, source=new_source) + install_guard(new_source.make_guard(GuardBuilder.TYPE_MATCH)) + + self.tx.output.add_fqn_info_for_inlined_modules(value, self.source) + + if not SideEffects.cls_supports_mutation_side_effects(type(value)): + # don't allow STORE_ATTR mutation with custom __setattr__ + return result + return self.tx.output.side_effects.track_object_existing(value, result) + elif issubclass( + value.__class__, torch.nn.parallel.distributed.DistributedDataParallel + ): + self.install_guards(GuardBuilder.TYPE_MATCH) + return UnspecializedNNModuleVariable(value, source=self.get_source()) + else: + return self.tx.output.register_attr_or_module( + value, + self.name, + source=self.get_source(), + # Guards are added inside register_attr_or_module + ) + + def wrap_literal(self, value: object) -> VariableTracker: + # NOTE: DynamicInt (subclass of int) and SymInt inputs never reach here + # because ConstantVariable.is_literal() rejects non-exact types. + # They are handled later in __call__ and always treated as dynamic. + if type(value) is int: + # Check for user-provided spec from shapes_spec. + if config._dynamic_shapes_spec is not None: + int_spec = lookup_spec_from_dynamo_source( + self.source, config._dynamic_shapes_spec + ) + if int_spec is None: + # shapes_spec is set but this int has no spec → force static + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + elif isinstance(int_spec, int): + # Explicit static value — verify the actual matches. + if value != int_spec: + raise ValueError( + f"shapes_spec declared {self.source.name} as static " + f"with value {int_spec}, but got {value} at trace time" + ) + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + elif isinstance(int_spec, (IntVar, torch.SymInt)): + result = self.wrap_symint(value, dynamism=DimDynamic.UNBACKED) + sym_val = result.sym_num # type: ignore[attr-defined] + _wire_spec_slot(int_spec, sym_val) + return result + else: + raise ValueError( + f"shapes_spec for {self.source.name}: unexpected value " + f"{int_spec!r} (expected int, IntVar, or None)" + ) + + if is_dynamic_source(self.source.name): + log.debug( + "%s marked dynamic via dynamic-sources list", self.source.name + ) + return self.wrap_symint(value, dynamism=DimDynamic.DYNAMIC) + + if is_dynamic_value(value): + log.debug( + "%s marked dynamic via dynamic-values list (value=%s)", + self.source.name, + value, + ) + return self.wrap_symint(value, dynamism=DimDynamic.DYNAMIC) + + if is_unbacked_source(self.source.name): + log.debug( + "%s marked unbacked via unbacked-sources list", self.source.name + ) + return self.wrap_symint(value, dynamism=DimDynamic.UNBACKED) + + if not config.specialize_int: + # unspecializing int by default, but still + # specialize for the following conditions + if is_int_specialization_case(value, self.source): + recompile_hint = None + if ( + self.source.guard_source.is_unspecialized_builtin_nn_module() + or self.source.guard_source.is_unspecialized_nn_module() + ): + # This means that it is an integer from a NN module. + # Dynamo considers nn module int attributes to be static + # (a good heuristic). But a user might want to mark the + # int attribute to be a symint, so track this integer + # for recompilation later. + recompile_hint = ( + "torch.compile considers integer attributes of the nn.Module to be static. " + "If you are observing recompilation, you might want to make this integer dynamic " + "using torch._dynamo.config.allow_unspec_int_on_nn_module = True, or convert this " + "integer into a tensor." + ) + + process_automatic_dynamic( + self.tx, + self.source.name, + FrameStateSizeEntry.make_scalar(value), + is_unspecialized_nn_module=self.source.guard_source.is_unspecialized_nn_module(), + ) + self.install_guards( + functools.partial( + GuardBuilder.EQUALS_MATCH, recompile_hint=recompile_hint + ) + ) + return ConstantVariable.create(value=value, source=self.source) + + return self._wrap_lazy_constant(value, self._wrap_symint_for_lazy) + + return self._wrap_lazy_constant(value) + elif type(value) is float: + if not isinstance(value, float): + raise AssertionError(f"Expected float, got {type(value)}") + if not config.specialize_float: + return self._wrap_lazy_constant(value, self._wrap_symfloat_for_lazy) + + return self._wrap_lazy_constant(value) + elif type(value) in (bool, str): + if not isinstance(value, (bool, str)): + raise AssertionError(f"Expected bool or str, got {type(value)}") + return self._wrap_lazy_constant(value) + else: + self.install_guards(GuardBuilder.CONSTANT_MATCH) + result = ConstantVariable.create(value=value, source=self.source) + if isinstance(value, (list, set)): + return self.tx.output.side_effects.track_mutable(value, result) + return result + + def _wrap_symint_for_lazy(self, value: int) -> VariableTracker: + return self.wrap_symint(value) + + def _wrap_symfloat_for_lazy(self, value: float) -> VariableTracker: + return self.wrap_symfloat(value) + + @overload + def _wrap_lazy_constant( + self, + value: int, + wrap_fn: Callable[[int], VariableTracker], + ) -> VariableTracker: ... + + @overload + def _wrap_lazy_constant( + self, + value: float, + wrap_fn: Callable[[float], VariableTracker], + ) -> VariableTracker: ... + + @overload + def _wrap_lazy_constant( + self, + value: int | float | bool | str, + wrap_fn: None = None, + ) -> VariableTracker: ... + + def _wrap_lazy_constant( + self, + value: int | float | bool | str, + wrap_fn: Callable[[Any], VariableTracker] | None = None, + ) -> VariableTracker: + """Wrap a primitive constant, deferring guard installation if allowed.""" + if not self.allow_lazy_constant: + if wrap_fn is not None: + return wrap_fn(value) + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + return LazyConstantVariable.create(value, source=self.source) + + def assert_not_wrapped_by_this_graph(self, value: torch.Tensor) -> None: + if is_fake(value) and maybe_get_fake_mode(value) is self.tx.fake_mode: + raise InternalTorchDynamoError( + "Cannot wrap a Tensor that has already been", + "wrapped by this instance of Dynamo", + ) + + def wrap_tensor(self, value: torch.Tensor) -> VariableTracker: + source = self.get_source() + + # We cannot already be tracking the tensor, which implies + # it would have already been wrapped + if value in self.tx.output.side_effects: + raise AssertionError("Tensor is already tracked in side effects") + + is_static_input = get_static_address_type(value) is not None + + # When a shapes_spec is provided for this tensor, we must skip the + # fast paths below that would freeze the tensor as a graph constant. + # Those paths bypass _automatic_dynamic where the spec is applied. + # Without this check, specifying TensorSpec on an nn.Parameter would + # be silently ignored. + # At tensor builder callsites, shapes_spec for this source can only be TensorSpec or None. + _tensor_spec = cast( + TensorSpec | None, + lookup_spec_from_dynamo_source(source, config._dynamic_shapes_spec), + ) + _has_spec = _tensor_spec is not None + + if ( + not _has_spec + and not is_static_input + and ( + isinstance(value, torch.nn.Parameter) + # mark tensor attributes of nn modules static + or (source and source.guard_source.is_unspecialized_nn_module()) + ) + ): + self.mark_static_input(value, guard=is_parameter_freezing()) + is_static_input = True + + # Install any tensors which are "free" variables; that is: + # 1. Globals + # 2. NonLocals + # 3. tensors that are attributes of nn module + should_install_free_tensor = config.install_free_tensors and ( + is_from_global_source(source) + or is_from_nonlocal_source(source) + or is_from_unspecialized_nn_module_source(source) + ) + + make_graph_attribute = is_static_input and ( + is_parameter_freezing() or torch._dynamo.config.prepare_freezing + ) + + if not _has_spec and ( + should_install_free_tensor + or ( + (source.guard_source.is_specialized_nn_module() or make_graph_attribute) + and not source.guard_source.is_fsdp_module() + ) + ): + self.assert_not_wrapped_by_this_graph(value) + return self.tx.output.register_attr_or_module( + value, self.name, source=source + ) + + if get_static_address_type(value) == "guarded": + # If it's a guarded tensor, we can install the parameter directly + # into the Fx graph instead of lifting it as an input. Lifting + # offers no benefit, such as regional compilation, since we still + # guard on the tensor's ID. Moreover, installing it in the Fx graph + # eliminates the pre-graph bytecode required to extract the tensor + # from locals/globals, reducing overhead. This can lead to + # significant cost savings, especially for optimizers handling many + # tensors. + self.install_guards(GuardBuilder.ID_MATCH) + self.assert_not_wrapped_by_this_graph(value) + return self.tx.output.register_attr_or_module( + value, self.name, source=source + ) + + if is_constant_source(source): + self.assert_not_wrapped_by_this_graph(value) + return self.tx.output.register_attr_or_module( + value, + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + source=source, + # Guards are added inside register_attr_or_module + ) + + # NB: this just says we accessed a tensor from the same source again + # (e.g., a tensor lives in a global foo, and we LOAD_GLOBAL it twice). + # This is distinct from two distinct sources mapping to the same + # Tensor (per id())! No guard is necessary here. See below for the + # other case. + is_duplicate_tensor = source in self.tx.output.input_source_to_var + if is_duplicate_tensor: + return self.tx.output.input_source_to_var[source] + + options = {} + subclass_type = infer_subclass_type(value) + if subclass_type is not None: + self.install_guards(GuardBuilder.TYPE_MATCH) + + if get_static_address_type(value) == "guarded": + self.install_guards(GuardBuilder.ID_MATCH) + + # By this point, we should have deduplicated all tensors + self.assert_not_wrapped_by_this_graph(value) + + if ( + isinstance(value, torch.Tensor) + and value.is_nested + and not isinstance(value, torch.nested._internal.nested_tensor.NestedTensor) + ): + unimplemented( + gb_type="Attempted to wrap strided NestedTensor", + context="", + explanation="torch.compile does not support strided NestedTensor", + hints=[], + ) + + # TODO(pearu,sparse-team) - Add the corresponding SPARSE_TENSOR_MATCH guards + if ( + isinstance(value, torch.Tensor) + and is_sparse_any(value) + and (not self.tx.export or not config.capture_sparse_compute) + ): + # A hot fix for sparse tensors + torch.compile. Support for + # export + sparsity is being added but we need to create + # SPARSE_TENSOR_GUARDS for guards to work properly. + unimplemented( + gb_type="Attempted to wrap sparse Tensor", + context="", + explanation="torch.compile does not support sparse Tensors", + hints=[*graph_break_hints.SPARSE_TENSOR], + ) + + if ( + isinstance(value, torch.Tensor) + and torch._C._functorch.peek_interpreter_stack() is None + ): + try: + tangent = torch.autograd.forward_ad.unpack_dual(value).tangent + except RuntimeError: + tangent = None + if tangent is not None: + unimplemented( + gb_type="Attempted to wrap a dual tensor input", + context="", + explanation="torch.compile does not support input tensors that " + "carry a forward-mode AD tangent; compiled code would silently " + "drop the tangent.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if ( + safe_has_grad(value) + and safe_grad(value) is not None + # type: ignore[attr-defined] + and value.dtype != safe_grad(value).dtype + ): + safe_grad_val = safe_grad(value) + grad_str = str(safe_grad_val.dtype) if safe_grad_val is not None else "None" + unimplemented( + gb_type="dtype mismatch between tensor and its gradient", + context=f"tensor dtype: {value.dtype}; grad dtype: {grad_str}", + explanation="Inconsistent dtype between tensor and its gradient. " + "This can happen in FSDP and crashes meta tensor creation.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + # tx.output has multiple tracers if we're introspecting HigherOrderOperator. + # When we've discovered an untracked tensor, then we actually need + # to get Dynamo to track the tensor (which is what this function does) + # and put it as a graph input on the root tracer. Later on, + # if the input is actually used in the body of the HigherOrderOperator, + # then the relevant SubgraphTracer will lift it to being an input of + # the subgraph. + # See NOTE [HigherOrderOperator tracing design] for more details. + + example_value = wrap_to_fake_tensor_and_record( + value, tx=self.tx, is_tensor=True, source=source, tensor_spec=_tensor_spec + ) + + tensor_proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(value), + example_value, + source=source, + ) + cache_real_value_when_export(self.tx, tensor_proxy, value) + + tensor_variable = wrap_fx_proxy( + tx=self.tx, + proxy=tensor_proxy, + example_value=example_value, + subclass_type=subclass_type, + source=source, + **options, + ) + + # Track input tensors for attribute mutation, matching how + # handle_traced_output tracks intermediate tensors with AttributeMutationNew. + # This enables setattr on input tensors (e.g. tensor.custom_attr = val) + # without graph breaking. + self.tx.output.side_effects.track_object_existing(value, tensor_variable) + + if value._is_view(): + # If value is a view, add its base tensor to the tracked fakes list. + # This is so we are able to access the correct source for its symbolic + # shape values, in case we need them. + wrap_to_fake_tensor_and_record( + value._base, + tx=self.tx, + source=AttrSource(source, "_base"), + is_tensor=True, + ) + + guard_type = GuardBuilder.TENSOR_MATCH + + if isinstance(source, GradSource) and is_from_optimizer_source(source): + guard_type = GuardBuilder.NOT_NONE_MATCH + + is_dtensor = torch.distributed.is_available() and isinstance( + value, torch.distributed.tensor.DTensor + ) + + # An AsyncCollectiveTensor (ACT) flattens to a single inner tensor whose + # metadata mirrors the wrapper, and the AOTAutograd runtime wrapper + # unwraps ACT inputs before the compiled graph. So a graph traced on an + # ACT is equivalent to one traced on its resolved plain Tensor. Guard on + # the unwrapped inner tensor (via UnwrapCollectiveTensorSource) instead + # of the ACT-locked type/metadata guards, so the ACT class no longer + # forces a recompile when the runtime value alternates between an + # un-awaited ACT and an awaited Tensor. Type-introspecting code stays + # sound because observation sites reinstall the class guard on demand + # (see BuiltinVariable.call_isinstance and TensorVariable.var_getattr). + # Caveat: ACT-only member access (e.g. w.wait()) is not a class-observation + # channel and does not reinstall the guard, so such code reuses the + # ACT-traced graph for a resolved plain Tensor. It stays numerically + # correct (ACT desugars ops to the inner tensor), but a compiled region + # can succeed where eager would raise AttributeError on the plain Tensor; + # that only bites user code already broken in eager on the resolved input. + is_polymorphic_act = not is_dtensor and is_async_collective_tensor_type( + type(value) + ) + + if not is_dtensor and not is_polymorphic_act: + # We guard on the _local_tensor and the _spec, and therefore we don't + # have to guard on the outer DTensor. + self.install_guards( + functools.partial( + guard_type, + value=( + value + if isinstance(source, NumpyTensorSource) + else TensorWeakRef(value) + ), + ) + ) + + # We install TYPE_MATCH guards for traceable wrapper subclass object, + # and recursively install corresponding guard for each inner attribute. + if is_traceable_wrapper_subclass(value): + # Tensor subclass guards are very expensive because they are + # implemented in Python. Since DTensor is PyTorch-maintained class, + # we can skip a lot of these guards. + if is_dtensor: + self.install_guards(GuardBuilder.TYPE_MATCH) + + inner_attrs = value.__tensor_flatten__()[0] + if inner_attrs != ["_local_tensor", "device_mesh"]: + raise RuntimeError( + "Expecting DTensor inner attrs to be ['_local_tensor', 'device_mesh']" + ) + + flattening_ctx = value.__tensor_flatten__()[1] + if not ( + len(flattening_ctx) == 4 + and flattening_ctx[0] == value._spec.placements + and flattening_ctx[1] == value._spec.tensor_meta + and flattening_ctx[2] == value._spec.shard_order + and flattening_ctx[3] == value.requires_grad + ): + raise RuntimeError( + "Expecting DTensor flattening ctx to be (placements, tensor_meta, shard_order, requires_grad)" + ) + # Guard on the dtensor spec + install_guard( + AttrSource(self.source, "_spec").make_guard( + GuardBuilder.DTENSOR_SPEC_MATCH + ) + ) + # Move this to C++ + install_guard( + AttrSource(self.source, "requires_grad").make_guard( + GuardBuilder.EQUALS_MATCH + ) + ) + elif is_polymorphic_act: + # Guard only on the unwrapped inner tensor (inner_source below). + # Installing no type/metadata guard on the ACT wrapper is what + # lets the resolved plain Tensor reuse this cache entry. + pass + else: + self.install_guards(GuardBuilder.TENSOR_SUBCLASS_METADATA_MATCH) + self.install_guards(GuardBuilder.TYPE_MATCH) + install_guard( + SubclassAttrListSource(source).make_guard(GuardBuilder.EQUALS_MATCH) + ) + + attrs, _ = value.__tensor_flatten__() + if is_polymorphic_act and attrs != ["elem"]: + # The unwrap accessor below assumes ACT's single inner tensor. + # Unreachable today (ACT always flattens to ["elem"]); if that + # ever changes we fail hard rather than misguard -- the wrapper's + # type/metadata guards were already skipped above, so there is no + # safe fallback left at this point. + raise RuntimeError( + f"Expected AsyncCollectiveTensor to flatten to ['elem'], " + f"got {attrs}" + ) + for attr in attrs: + inner_value = getattr(value, attr) + # FakeScriptObject wraps the real opaque object during + # fake-mode tracing; unwrap before the type check. + inner_type = type(inner_value) + if isinstance( + inner_value, + torch._library.fake_class_registry.FakeScriptObject, + ): + inner_type = type(inner_value.real_obj) + if not isinstance( + inner_value, torch.Tensor + ) and not is_opaque_symbolic_type(inner_type): + raise RuntimeError( + f"{type(inner_value).__name__!r} found in tensor attrs of " + f"{type(value).__name__}.__tensor_flatten__(). " + "Only tensors and reference-type opaques are allowed " + "in tensor attrs." + ) + if is_polymorphic_act: + # ACT flattens to the single attr "elem"; guard it through + # an unwrap accessor so a plain Tensor at runtime (the + # resolved collective) matches the same guard. + inner_source = UnwrapCollectiveTensorSource(self.source) + else: + inner_source = AttrSource(self.source, attr) + LazyVariableTracker.realize_all( + VariableBuilder(self.tx, inner_source)(inner_value) + ) + + self.tx.output.input_source_to_var[source] = tensor_variable + if "tensor_dict" in tensor_proxy.node.meta: + raise AssertionError("tensor_dict already exists in tensor_proxy node meta") + tensor_proxy.node.meta["tensor_dict"] = _extract_tensor_dict(value) + + # Note: this information is conveyed via subclass_type now + # type: ignore[attr-defined] + fake_tensor_value = tensor_variable.proxy.node.meta["example_value"] + if maybe_get_fake_mode(fake_tensor_value) is not self.tx.fake_mode: + raise InternalTorchDynamoError("Wrapped Tensor must be this graph's fake") + + grapharg = GraphArg(source, value, False, fake_tensor_value) + tensor_proxy.node.meta["grapharg"] = grapharg + return tensor_variable + + def wrap_numpy_ndarray(self, value: Any) -> VariableTracker: + if np is None: + raise AssertionError("numpy must be available to wrap ndarray") + if not isinstance(value, np.ndarray): + raise AssertionError(f"Expected np.ndarray, got {type(value)}") + + source = NumpyTensorSource(self.get_source()) + + from torch._numpy import _util + + readonly = not value.flags.writeable + if readonly: + try: + value.flags.writeable = True + except ValueError: + # One can not easily make nditer elements writable, + # but warning is not the end of the world + if not isinstance(value.base, np.nditer): + raise AssertionError( + f"Expected np.nditer base, got {type(value.base)}" + ) from None + tensor_value = None + with torch_function_mode_stack_state_mgr.temp_restore_stack(): + try: + tensor_value = _util._try_convert_to_tensor(value) + if readonly: + from torch._prims_common import clone_preserve_strides + + tensor_value = clone_preserve_strides(tensor_value) + except NotImplementedError as e: + # failed to convert to tensor, graph break + unimplemented( + gb_type="failed to convert numpy.ndarray to Tensor", + context=str(value), + explanation="Exception encountered when attempting to convert numpy.ndarray to Tensor", + hints=[], + from_exc=e, + ) + if tensor_value is None: + raise AssertionError("Failed to convert numpy ndarray to tensor") + + # We do this because we want the full behavior of guarding the numpy ndarray as if it were + # a tensor. It's a little annoying to make a VT to throw out, but there's so many side effects here + # that there's not another great way to do this atm. + # This creates the right graphargs, as well as registration for guards in tensor names and shape env. + LazyVariableTracker.realize_all(VariableBuilder(self.tx, source)(tensor_value)) + example_value = wrap_to_fake_tensor_and_record( + tensor_value, + tx=self.tx, + is_tensor=False, + source=source, + ) + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(tensor_value), + example_value, + source=source, + ) + cache_real_value_when_export(self.tx, proxy, tensor_value) + options = {"source": source} + numpy_ndarray_variable = wrap_fx_proxy_cls( + target_cls=NumpyNdarrayVariable, + tx=self.tx, + proxy=proxy, + example_value=example_value, + subclass_type=None, + **options, + ) + + self.tx.output.input_source_to_var[source] = numpy_ndarray_variable + # type: ignore[attr-defined] + example_value = numpy_ndarray_variable.proxy.node.meta["example_value"] + + # pass_arg_as_tensor should be true because we are wrapping a np.ndarray as argument input, and it needs to be + # converted to a tensor. + grapharg = GraphArg( + source, + tensor_value, + pass_arg_as_tensor=True, + fake_tensor=example_value, + is_tensor=True, + example_strong_ref=tensor_value, + ) + proxy.node.meta["grapharg"] = grapharg + + # TODO - Why do we need to set the source of the np ndarray vt back to + # original source. Many tests fails. + numpy_ndarray_variable.source = self.source + + return numpy_ndarray_variable + + def wrap_symint( + self, + value: int, + dynamism: DimDynamic | None = None, + context: SymIntSymbolicContext | None = None, + ) -> VariableTracker: + if type(value) is not int: + raise AssertionError(f"Expected exact int type, got {type(value)}") + + if self.name in self.tx.output.unspec_variable_map: + return self.tx.output.unspec_variable_map[self.name] + + shape_env = self.tx.output.shape_env + frame_state_entry: FrameStateSizeEntry | None = None + if TracingContext.get().force_unspec_int_unbacked_size_like: + wrapped_value = shape_env.create_unbacked_symint() + _constrain_range_for_size(wrapped_value) + self.tx.output.tracked_fakes.append( + TrackedFake(wrapped_value, self.source, None) + ) + + # NB: We do not do float. For motivation, see + # https://docs.google.com/document/d/1INSCdYu1PxXcr43HrD82OudeEuS-qxQe1yZmLg2wy6A/edit + # but the general idea is that we generate kernels that can + # take unspecialized floats and use them in sizevar computation + elif not is_constant_source(self.get_source()): + if dynamism is None and torch._dynamo.config.specialize_int: + # If specialize_int is False, also return + # a constant (but this should have been handled + # in the caller, TBH). But if `dynamism` is set, then actually + # turn it into a symint + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + + name = self.source.name + + frame_state_entry = process_automatic_dynamic( + self.tx, + name, + FrameStateSizeEntry.make_scalar(value), + is_unspecialized_nn_module=self.source.guard_source.is_unspecialized_nn_module(), + ) + + # TODO: This should be dynamic, as we in general do not + # know if bare integers are actually going to be sizevars + # and it is inappropriate to eagerly duck size them with + # real sizevars + normalized_source_name = normalize_source_name(self.source.name) + + if dynamism is not None: + dynamic_dim = dynamism + elif ( + config.automatic_dynamic_shapes + and frame_state_entry.scalar is auto_dynamic + ): + set_feature_use("dynamo.automatic_dynamic_shapes", True) + dynamic_dim = get_automatic_dynamic_shapes_mark_as() + elif ( + _is_dim_dynamic_from_source_dynamism( + self.source, normalized_source_name, 0 + ) + ) or not config.assume_static_by_default: + symbolic_shape_log.info( + "marking %s as dynamic (from assume_static_by_default = False)", + name, + ) + dynamic_dim = DimDynamic.DYNAMIC + else: # assume_static_by_default + # TODO: dynamic_dim = DimDynamic.STATIC should work but + # for some reason it doesn't + if frame_state_entry.scalar is auto_dynamic: + set_feature_use("dynamo.automatic_dynamic_shapes", False) + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value) + + excluded_scalar = ( + frame_state_entry.excluded_scalar + if config.automatic_dynamic_exclusion_guard + and frame_state_entry is not None + else None + ) + wrapped_value = shape_env.create_unspecified_symint_and_symbol( + value, + source=self.source, + dynamic_dim=dynamic_dim, + excluded_value=excluded_scalar, + ) + if not isinstance(wrapped_value, SymInt): + raise AssertionError(f"Expected SymInt, got {type(wrapped_value)}") + + self.tx.output.tracked_fakes.append( + TrackedFake(wrapped_value, self.source, context) + ) + else: + if not is_constant_source(self.get_source()): + raise AssertionError( + f"Expected constant source, got {self.get_source()}" + ) + # TODO: Do I actually need guard for constant source? + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + + if isinstance(self.get_source(), RandomValueSource): + raise AssertionError( + "RandomValueSource is not supported for symint wrapping" + ) + install_guard(self.get_source().make_guard(GuardBuilder.TYPE_MATCH)) + + options = {"source": self.get_source()} + + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(wrapped_value), + wrapped_value, + source=self.get_source(), + ) + + sym_expr = wrapped_value.node.expr + if not isinstance(sym_expr, sympy.Symbol): + raise AssertionError(f"{sym_expr} is not a basic Symbol.") + self.tx.output.root_tracer.bound_symbols[sym_expr] = proxy + unspec_var = SymNodeVariable.create(self.tx, proxy, wrapped_value, **options) + # type: ignore[assignment] + self.tx.output.unspec_variable_map[self.name] = unspec_var + + if not is_constant_source(self.get_source()): + proxy.node.meta["grapharg"] = GraphArg( + self.get_source(), + wrapped_value, + pass_arg_as_tensor=False, + fake_tensor=None, + is_tensor=False, + example_strong_ref=wrapped_value, + ) + + return unspec_var + + def wrap_symfloat(self, value: float) -> VariableTracker: + # SymFloat wrapping is special. We first wrap it in the same way we + # do an unspecialized primitive, and then we item() it into a + # SymFloat. Removal of the item() call is left to a later FX pass, + # mostly because that pass is more easily done after we have lowered + # to ATen ops. (Dynamo doesn't do decomposition right now). + + if self.name in self.tx.output.unspec_variable_map: + return self.tx.output.unspec_variable_map[self.name] + + frame_state_entry = process_automatic_dynamic( + self.tx, + self.source.name, + # type: ignore[arg-type] + FrameStateSizeEntry.make_scalar(value), + is_unspecialized_nn_module=self.source.guard_source.is_unspecialized_nn_module(), + ) + + # NB: we specialize on nan input, because our guard modeling in + # ShapeEnv cannot deal with nan + if ( + torch._dynamo.config.specialize_float + or is_constant_source(self.get_source()) + or math.isnan(value) + or math.isinf(value) + # We don't support cudagraphs for now. Without this cudagraphs + # break because they expect all cuda inputs but our tensorified + # float will be a f64[] cpu tensor. Fixes the following test + # when specialize_float=False + # python test/inductor/test_compiled_optimizers.py CompiledOptimizerTests.test_rmsprop_weight_decay_maximize_capturable_cuda + or torch._inductor.config.triton.cudagraphs + or justknobs_check("pytorch/compiler:unspecialize_float_killswitch", False) + or ( + config.assume_static_by_default + and frame_state_entry.scalar is not auto_dynamic + ) + ): + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + + # NB: At the point we've gotten here, we don't assume static by + # default. Since we have a guard mechanism, there isn't really any + # downside to trying to be dynamic for float all the time. Unlike + # ints, this won't make codegen perf worse. Modest cost to compile + # time. + + wrapped_value = torch.tensor(value, dtype=torch.float64) + + # We don't support specializing floats for grad checking tensors + # See https://github.com/pytorch/pytorch/pull/140828 for more + # context. + if torch._C._functorch.is_gradtrackingtensor(wrapped_value): + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + + # TODO: Switch RandomValueSource over to use this, this is more + # accurate + if isinstance(self.get_source(), RandomValueSource): + raise AssertionError( + "RandomValueSource is not supported for symfloat wrapping" + ) + install_guard(self.get_source().make_guard(GuardBuilder.TYPE_MATCH)) + + # The FloatTensorSource here is just for pedantic correctness: if you + # guard against an UnspecializedPythonVariable, you need to guard + # against the tensor-ified version of the local, otherwise it's not a + # Tensor. However, we never let the UnspecializedPythonVariable escape + # here, so there should never actually be any guards against this + # source. + source = FloatTensorSource(self.get_source()) + options = {"source": source, "raw_value": value} + + # TODO: Maybe the tensor-ification should be built into the source, + # rather than by special pattern match + example_value = wrap_to_fake_tensor_and_record( + wrapped_value, tx=self.tx, is_tensor=False, source=source + ) + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(wrapped_value), + example_value, + source=source, + ) + cache_real_value_when_export(self.tx, proxy, wrapped_value) + + unspec_var = wrap_fx_proxy_cls( + UnspecializedPythonVariable, + tx=self.tx, + proxy=proxy, + example_value=example_value, + subclass_type=None, + **options, + ) + if not isinstance(unspec_var, UnspecializedPythonVariable): + raise AssertionError( + f"Expected UnspecializedPythonVariable, got {type(unspec_var)}" + ) + self.tx.output.unspec_variable_map[self.name] = unspec_var + + if self.tx.export and not isinstance(self.get_source(), LocalSource): + raise AssertionError( + f"Dynamo attempts to add additional input during export: value={wrapped_value}, source={self.get_source()}" + ) + fake_tensor_value = None + example_value = unspec_var.proxy.node.meta["example_value"] + if not is_fake(example_value): + raise AssertionError( + f"Expected fake tensor example_value, got {type(example_value)}" + ) + + fake_tensor_value = example_value + # type: ignore[attr-defined] + if fake_tensor_value.fake_mode is not self.tx.fake_mode: + raise AssertionError( + f"fake mode ({fake_tensor_value.fake_mode}) from fake tensor metadata doesn't match mode" + "({self.tx.fake_mode}) from InstructionTranslator" + ) + + # There's something a bit incoherent about pass_arg_as_tensor, + # specifically regarding sources. + # + # Specifically, suppose we have "x: float" local argument. We + # eventually end up with an UnspecializedPythonVariable denoting + # torch.as_tensor(x)... but it's source is still L['x'] (which if you + # accessed it directly is a float!) So you gotta be careful when + # setting up your guards, because it's still going to be a float at + # this point, the conversion happens only precisely at the point we're + # actually calling the FX graph. This happens to be what we want for + # shape guard generation, but it's kind of unintuitive. + proxy.node.meta["grapharg"] = GraphArg( + self.get_source(), + wrapped_value, + pass_arg_as_tensor=True, + # type: ignore[arg-type] + fake_tensor=fake_tensor_value, + is_tensor=False, + example_strong_ref=wrapped_value, + ) + + # Directly do item to bypass capture_scalar_outputs + r = wrap_fx_proxy( + self.tx, + self.tx.output.create_proxy( + "call_method", + "item", + *proxy_args_kwargs([unspec_var], {}), + ), + ) + # type: ignore[attr-defined] + self.tx.output.tracked_fakes.append(TrackedFake(r.sym_num, self.source, None)) + + get_metrics_context().set("tensorify_float_attempt", True, overwrite=True) + + return r + + def wrap_unspecialized_primitive(self, value: Any) -> VariableTracker: + if self.name in self.tx.output.unspec_variable_map: + return self.tx.output.unspec_variable_map[self.name] + + wrapped_value = torch.tensor(value) + if not isinstance(self.get_source(), RandomValueSource): + install_guard(self.get_source().make_guard(GuardBuilder.TYPE_MATCH)) + + options = {"source": self.get_source()} + options.update({"raw_value": value}) + + example_value = wrap_to_fake_tensor_and_record( + wrapped_value, tx=self.tx, is_tensor=False, source=self.get_source() + ) + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(wrapped_value), + example_value, + source=self.get_source(), + ) + cache_real_value_when_export(self.tx, proxy, wrapped_value) + + unspec_var = wrap_fx_proxy_cls( + UnspecializedPythonVariable, + tx=self.tx, + proxy=proxy, + example_value=example_value, + subclass_type=None, + **options, + ) + # type: ignore[assignment] + self.tx.output.unspec_variable_map[self.name] = unspec_var + if not is_constant_source(self.get_source()): + if self.tx.export and not isinstance(self.get_source(), LocalSource): + raise AssertionError( + f"Dynamo attempts to add additional input during export: value={wrapped_value}, source={self.get_source()}" + ) + fake_tensor_value = None + if unspec_var.is_python_constant(): + # TODO: when can this happen? + example_value = unspec_var.as_python_constant() + else: + # type: ignore[attr-defined] + example_value = unspec_var.proxy.node.meta["example_value"] + if not is_fake(example_value): + raise AssertionError( + f"Expected fake tensor example_value, got {type(example_value)}" + ) + + fake_tensor_value = example_value + # type: ignore[attr-defined] + if fake_tensor_value.fake_mode is not self.tx.fake_mode: + raise AssertionError( + f"fake mode ({fake_tensor_value.fake_mode}) from fake tensor metadata doesn't match mode" + "({self.tx.fake_mode}) from InstructionTranslator" + ) + + proxy.node.meta["grapharg"] = GraphArg( + self.get_source(), + wrapped_value, + pass_arg_as_tensor=True, + # type: ignore[arg-type] + fake_tensor=fake_tensor_value, + is_tensor=False, + example_strong_ref=wrapped_value, + ) + return unspec_var + + +def _dataclasses_fields_lambda(obj: VariableTracker) -> TupleVariable: + value = None + if isinstance(obj, UserDefinedObjectVariable): + value = obj.value + else: + unimplemented( + gb_type="dataclass fields failure", + context=f"obj: {obj}; variable type: {type(obj)}", + explanation=f"Dataclass fields handling fails for {obj}. Expected it to be a user-defined object.", + hints=[], + ) + if value is None: + raise AssertionError("dataclasses.fields requires a non-None value") + items = [] + # type: ignore[arg-type] + for field in dataclasses.fields(value): + source = None + if obj.source: + base_src = AttrSource(obj.source, "__dataclass_fields__") + source = DictGetItemSource(base_src, field.name) + items.append(UserDefinedObjectVariable(field, source=source)) + # pyrefly: ignore [bad-argument-type] + return TupleVariable(items) + + +def _clone_input(value: Any, fake_mode: FakeTensorMode | None) -> Any: + if isinstance(value, torch.Tensor): + # tensor subclasses will not be converted to FakeTensors and need to be cloned + if not ( + is_fake_tensor(value) + or ( + # Is functional tensor fakeified by this instance of Dynamo + torch._is_functional_tensor(value) + and maybe_get_fake_mode(value) is fake_mode + ) + or value.is_nested + ): + # NB: ensure strides are preserved + value = clone_input(value) + + return value + + +def wrap_fx_proxy( + tx: "InstructionTranslatorBase", + proxy: Any, + example_value: Any | None = None, + subclass_type: type | None = None, + **options: Any, +) -> VariableTracker: + kwargs = { + "tx": tx, + "proxy": proxy, + "example_value": example_value, + "subclass_type": subclass_type, + **options, + } + if subclass_type is None: + # pyrefly: ignore[bad-argument-type] + return wrap_fx_proxy_cls(target_cls=TensorVariable, **kwargs) + else: + # pyrefly: ignore[bad-argument-type] + result = wrap_fx_proxy_cls(target_cls=TensorWithTFOverrideVariable, **kwargs) + # type: ignore[attr-defined] + result.install_global(tx) + return result + + +def cache_real_value_when_export( + tx: "InstructionTranslatorBase", proxy: Any, example_value: Any +) -> None: + if tx.export: + # The legacy behavior for real value cache with subclasses was + # to perform a clone WITHOUT preserving the subclass. It's + # not entirely clear this is what you actually want though. + with torch._C.DisableTorchFunctionSubclass(): + proxy.tracer.real_value_cache[proxy.node] = _clone_input( + example_value, tx.fake_mode + ) + + +# Note: Unfortunate split due to some gross classes existing that subclass TensorVariable +# Should be compositional instead +# +# This is a horribly complicated function that does too many things, to +# explain what it does, let's first talk about the classic usage wrap_fx_proxy +# for a TensorVariable. There are two primary modes of use: +# +# 1. Wrapping a pre-existing Tensor. In this case, example_value is set +# to the pre-existing Tensor. (Note that this example_value will NOT +# be the final example_value we put into node.meta['example_value'], +# instead it is converted into a fake tensor using +# wrap_to_fake_tensor_and_record and registered as a graph input.) +# +# 2. "Wrapping" the result of some Tensor operation Dynamo traced over. In +# this case, example_value is None (and we are going to figure it out +# ourselves using FakeTensors, via get_fake_value, which will run +# the operation represented by the (singular!) FX node referenced by +# the passed in proxy.) +# +# The expectation is you end up with a Tensor output, and everything is +# straightforwardly traced into the graph. +# +# In all cases, the returned `TensorVariable` subclass will have an `example_value` +# and that `example_value` must be a `FakeTensor` produced by the currently running +# instance of Dynamo. +# +# Upon closer inspection, you may notice that there are a slurry of non-Tensor +# output cases in handle_traced_output. What gives? Well, we sometimes trace operations into the +# graph that don't involve tensors. +# +# * Some operators return tuples; we need to recursively handle their +# contents +# +# * Some operators have side effects that will affect subsequent AOTAutograd +# tracing but don't otherwise return anything. +# +# * Some operators return symbolic ints/floats/bools which can go in the +# graph and be traced (but only if they're actually symbolic! If they're +# static you don't want to put them in the graph, which means you +# shouldn't call this function.) +# +# The common theme is that you only use this function WHEN YOU ARE TRACING +# SOMETHING INTO THE GRAPH. This is sort of obvious, because you can't call +# this function without a proxy. +def wrap_fx_proxy_cls( + target_cls: type[VTTypeAlias], + tx: "InstructionTranslatorBase", + proxy: Any, + example_value: Any | None = None, + subclass_type: type | None = None, + **options: Any, +) -> VTTypeAlias: + if example_value is None: + out: VTTypeAlias = _wrap_fx_proxy( + target_cls, tx, proxy, example_value, subclass_type, **options + ) + elif isinstance(example_value, torch.Tensor): + out = _wrap_fx_preexisting_tensor( + target_cls, tx, proxy, example_value, subclass_type, **options + ) + else: + # This will skip tracing an op and recursively reinvoke wrap_fx_proxy_cls on supported + # data structures. In essence this just handles tracing some other value which may + # contain Fake Tensors or is otherwise proxyable. + # pyrefly: ignore[bad-assignment] + out = handle_traced_output( + example_value, tx, proxy, options, subclass_type, target_cls + ) + + if ( + isinstance( + out, + ( + torch._dynamo.variables.TensorVariable, + torch._dynamo.variables.SymNodeVariable, + ), + ) + and proxy.node.op != "placeholder" + ): + tx.output.current_tracer.record_proxyable_vt(out) + return out + + +# This is 1 above (wrapping a preexisting tensor) +def _wrap_fx_preexisting_tensor( + target_cls: type[VTTypeAlias], + tx: "InstructionTranslatorBase", + proxy: torch.fx.Proxy, + tensor: torch.Tensor, + subclass_type: type | None = None, + **options: Any, +) -> VTTypeAlias: + from ..symbolic_convert import InstructionTranslatorBase + + if not isinstance(tensor, torch.Tensor): + raise AssertionError( + f"_wrap_fx_preexisting_tensor expected tensor, got {type(tensor)}" + ) + + if not isinstance(tx, InstructionTranslatorBase): + raise AssertionError(f"Expected InstructionTranslatorBase, got {type(tx)}") + if "guards" in options and options["guards"] is not None: + tx.output.guards.update(options["guards"]) + + # Placeholders always carry example_value in node.meta. + # non-placeholders always have no example_value in node.meta + if proxy.node.op == "placeholder": + if "example_value" not in proxy.node.meta: + raise AssertionError( + f"placeholder {proxy} doesn't have 'example_value' in node.meta" + ) + else: + if "example_value" in proxy.node.meta: + raise AssertionError(f"{proxy.node.meta['example_value']}") + + # See NOTE: [Deferring tensor pack/unpack hooks until runtime] + with torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing(): + # Handle recursive calls here + if maybe_get_fake_mode(tensor) is tx.fake_mode: + pass + else: + cache_real_value_when_export(tx, proxy, tensor) + if tx.export: + # The legacy behavior for real value cache with subclasses was + # to perform a clone WITHOUT preserving the subclass. It's + # not entirely clear this is what you actually want though. + with torch._C.DisableTorchFunctionSubclass(): + # type: ignore[attr-defined] + proxy.tracer.real_value_cache[proxy.node] = _clone_input( + tensor, tx.fake_mode + ) + # NB: If we're ignoring subclass, then the expectation is you will + # take the returned TensorVariable and wrap it into a more + # accurate TensorVariable that is able to track subclass-ness; + # otherwise this is wrong! + kwargs = { + "is_tensor": target_cls + in (TensorVariable, TensorWithTFOverrideVariable), + } + if "source" not in options: + raise AssertionError("source must be provided in options") + if options["source"] is None: + raise AssertionError("source must not be None in options") + kwargs["source"] = options["source"] + # pyrefly: ignore [missing-argument] + tensor = wrap_to_fake_tensor_and_record(tensor, tx=tx, **kwargs) + + if tensor.device.type != "meta" and ( + maybe_get_fake_mode(tensor) is not tx.fake_mode + ): + raise InternalTorchDynamoError( + "`tensor` needs to be a `FakeTensor`" + f"wrapped by this instance of Dynamo. Found: {tensor}" + ) + + return construct_tensor_variable( + target_cls, tx, proxy, tensor, subclass_type, options + ) + + +# This is 2 in the above comment (wrapping the output of a traced op) +def _wrap_fx_proxy( + target_cls: type[VTTypeAlias], + tx: "InstructionTranslatorBase", + proxy: torch.fx.Proxy, + example_value: Any | None = None, + subclass_type: type | None = None, + **options: Any, +) -> VTTypeAlias: + from ..symbolic_convert import InstructionTranslatorBase + + if not isinstance(tx, InstructionTranslatorBase): + raise AssertionError(f"Expected InstructionTranslatorBase, got {type(tx)}") + if "guards" in options and options["guards"] is not None: + tx.output.guards.update(options["guards"]) + + if "example_value" in proxy.node.meta: + raise AssertionError(f"{proxy.node.meta['example_value']}") + + # See NOTE: [Deferring tensor pack/unpack hooks until runtime] + with torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing(): + # with preserve_rng_state(): + # only allow_non_graph_fake in this instance because we handle the non-fake + # cases properly below. + example_value = get_fake_value(proxy.node, tx, allow_non_graph_fake=True) + + # pyrefly: ignore[bad-return] + return handle_traced_output( + # type: ignore[arg-type] + example_value, + tx, + proxy, + options, + subclass_type, + target_cls, + ) + + +# This handles wrapping of the output of an op traced into the graphs +def handle_traced_output( + example_value: Any, + tx: "InstructionTranslatorBase", + proxy: torch.fx.Proxy, + options: dict[str, Any], + subclass_type: type | None, + target_cls: type[VTTypeAlias], +) -> VariableTracker: + import torch._functorch.vmap + import torch._subclasses.fake_tensor + import torch._utils + + if isinstance(example_value, torch.Tensor): + # Check if the result is a sparse tensor - + # We generally don't support sparse tensor so better to graph break here + if is_sparse_any(example_value) and ( + not tx.export or not config.capture_sparse_compute + ): + # Avoid calling str() on FakeTensors with unbacked symints as it triggers + # _tensor_str machinery which can cause GuardOnDataDependentSymNode errors + context = f"sparse tensor with layout={example_value.layout}, shape={example_value.shape}" + unimplemented( + gb_type="Attempted to wrap sparse Tensor with VariableTracker", + context=context, + explanation="torch.compile does not support sparse Tensors with VariableTracker", + hints=[*graph_break_hints.SPARSE_TENSOR], + ) + var = construct_tensor_variable( + target_cls, tx, proxy, example_value, subclass_type, options + ) + # NOTE: [Side effect tracking for newly constructed tensor] + # For newly constructed objects that have mutable attributes, we usually + # construct their VariableTracker via `track_object_new`, but since + # tensor variable construction is a bit different, we handle them + # specially here. This ensures that codegen will actually generate the + # attribute mutations on this tensor. + # + # NOTE we pass a dummy object as the `item` argument to avoid + # constructing a dummy _tensor_ object. The object isn't used for + # newly constructed VTs anyways. + if not isinstance(var, VariableTracker): + raise AssertionError(f"Expected VariableTracker, got {type(var)}") + tx.output.side_effects._track_obj( + proxy, var, mutation_type_cls=AttributeMutationNew + ) + return var + elif ( + hasattr(proxy.node.target, "__name__") + and proxy.node.target.__name__ == "set_state" + # type: ignore[attr-defined] + and isinstance(proxy.node.target.__self__, torch._C.Generator) + or proxy.node.target is torch.random.set_rng_state + ): + if type(proxy.node.target) is str: + raise AssertionError("proxy.node.target must not be a string") + # pyrefly: ignore[bad-argument-type] + return TorchInGraphFunctionVariable(proxy.node.target) + elif ( + proxy.node.target is torch._C._DisableFuncTorch + or proxy.node.target is torch.cuda._is_in_bad_fork + ): + return UserDefinedObjectVariable(example_value) + elif istype(example_value, torch.Size) and all( + isinstance(x, int) for x in example_value + ): + sizes = [ConstantVariable.create(x) for x in example_value] + return SizeVariable(sizes, **options) + elif isinstance(example_value, (tuple, list)): + set_example_value(proxy.node, example_value) + unpacked = [] + for i, val in enumerate(example_value): + if val is None: + # nn.MultiheadAttention() can return None, see issue #175 + unpacked.append( + ConstantVariable.create(None, **options), + ) + else: + proxy_i = proxy.tracer.create_proxy( + kind="call_function", + target=operator.getitem, + args=(proxy, i), + kwargs={}, + ) + + if "source" in options: + # This path should only trigger for list stealing, so it's + # safe to use `GetItemSource`. + if not isinstance(example_value, list): + raise AssertionError( + f"Expected list for source path, got {type(example_value)}" + ) + source = options["source"] + options_i = options.copy() + options_i["source"] = GetItemSource( + base=source, + index=i, + index_is_slice=False, + ) + else: + # use the same options object as parent + options_i = options + + # WARNING: this assumes the same target_cls as this tuple/list call + unpacked.append( + # pyrefly: ignore [bad-argument-type] + wrap_fx_proxy_cls( + # pyrefly: ignore[bad-argument-type] + target_cls=target_cls, + tx=tx, + proxy=proxy_i, + example_value=val, + **options_i, + ) + ) + if isinstance(example_value, torch.Size): + # NB: Keep the old proxy around. See SizeVariable for an + # explanation why + return SizeVariable(unpacked, proxy, **options) + elif istype(example_value, tuple): + return TupleVariable(unpacked, **options) + elif istype(example_value, (list, immutable_list)): + return ListVariable(unpacked, **options) + else: + if not is_namedtuple(example_value): + raise AssertionError( + f"expected namedtuple or structseq but got {type(example_value)}" + ) + tuple_vt = TupleVariable( + unpacked, + mutation_type=options.get("mutation_type", ValueMutationNew()), + ) + return UserDefinedTupleVariable.get_vt_cls(type(example_value))( + example_value, + tuple_vt=tuple_vt, + **options, # type: ignore[arg-type] + ) + elif example_value is None or proxy.node.target is torch.manual_seed: + return ConstantVariable.create(None, **options) + elif isinstance(example_value, (torch.SymInt, torch.SymFloat, torch.SymBool)): + tx.output.current_tracer.track_produced_symints(example_value, proxy) + set_example_value(proxy.node, example_value) + return SymNodeVariable.create(tx, proxy, example_value, **options) + elif ( + isinstance(example_value, torch.Stream) + and proxy.node.target is get_external_object_by_index + ) or proxy.node.target in [ + device_interface.current_stream + for _, device_interface in get_registered_device_interfaces() + ]: + set_example_value(proxy.node, example_value) + index = None + if proxy.node.target is get_external_object_by_index: + index = proxy.node.args[0] + # type: ignore[arg-type] + return StreamVariable(proxy, example_value, index, **options) + elif ( + isinstance(example_value, torch.Event) + and proxy.node.target is get_external_object_by_index + ) or proxy.node.target in [ + device_interface.current_stream + for _, device_interface in get_registered_device_interfaces() + ]: + index = None + if proxy.node.target is get_external_object_by_index: + index = proxy.node.args[0] + set_example_value(proxy.node, example_value) + # type: ignore[arg-type] + return EventVariable(proxy, example_value, index, **options) + elif ( + inspect.isclass(proxy.node.target) + and issubclass(proxy.node.target, torch.Event) + ) or proxy.node.target in [ + device_interface.Event + for _, device_interface in get_registered_device_interfaces() + ]: + set_example_value(proxy.node, example_value) + return EventVariable(proxy, example_value, None, **options) + elif proxy.node.target == "query" and proxy.node.op == "call_method": + set_example_value(proxy.node, example_value) + return ConstantVariable(example_value, **options) + elif ( + example_value is not None + and isinstance(example_value, torch.Event) + and proxy.node.target == "record_event" + and proxy.node.op == "call_method" + ): + set_example_value(proxy.node, example_value) + return EventVariable(proxy, example_value, None, **options) + elif isinstance(example_value, int) and ( + proxy.node.target + in [ + torch.sym_int, + torch.sym_max, + torch.sym_min, + getattr, + operator.getitem, + torch._utils._element_size, + torch.seed, + operator.mod, + torch._functorch.vmap._validate_and_get_batch_size, + torch._functorch.predispatch._vmap_increment_nesting, + torch._functorch.predispatch._vmap_decrement_nesting, + # some mac builds are missing torch.distributed.get_rank() + getattr(torch.distributed, "get_rank", _missing), + getattr(torch.distributed, "get_world_size", _missing), + # This always wants to be in the graph, even if the constraint + # results in a constant int + torch._constrain_as_size, + ] + or ( + # TODO: this is a little sus, because we didn't check what the self is + proxy.node.op == "call_method" and proxy.node.target == "bit_length" + ) + ): + set_example_value(proxy.node, example_value) + return ConstantVariable.create(example_value, **options) + elif isinstance(example_value, torch.backends.cuda.SDPAParams): + from .sdpa import SDPAParamsVariable + + set_example_value(proxy.node, example_value) + return SDPAParamsVariable(proxy, **options) + elif isinstance(example_value, bool) and ( + proxy.node.target + in [ + torch._C._are_functorch_transforms_active, + torch._C._functorch.is_batchedtensor, + torch.backends.cuda.is_flash_attention_available, + torch.backends.cuda.can_use_flash_attention, + torch.backends.cuda.can_use_efficient_attention, + torch._C._get_cudnn_sdp_enabled, + torch._C._get_flash_sdp_enabled, + torch._C._get_mem_efficient_sdp_enabled, + torch._C._get_math_sdp_enabled, + torch._C._get_overrideable_sdp_enabled, + torch._C._is_autocast_available, + "is_integer", + ] + + list(supported_const_comparison_op_values.keys()) + ): + set_example_value(proxy.node, example_value) + return ConstantVariable.create(example_value, **options) + elif isinstance(example_value, (int, float, bool)) and ( + proxy.node.target is call_torchbind + or proxy.node.target is flat_apply + or (proxy.node.op == "call_method" and proxy.node.target == "item") + ): + set_example_value(proxy.node, example_value) + return ConstantVariable.create(example_value, **options) + elif isinstance(example_value, float) or proxy.node.target in ["hex", "__round__"]: + set_example_value(proxy.node, example_value) + return ConstantVariable.create(example_value, **options) + elif isinstance(example_value, torch._library.fake_class_registry.FakeScriptObject): + # example_value is already a FakeScriptObject (e.g. returned by getitem + # on a container whose fake kernel returns a FakeScriptObject). No need + # to convert it — just wrap the proxy directly. + return CustomClassObjectVariable.create( + proxy, + example_value, + tx=tx, + ) + elif is_custom_class(type(example_value)): + # This is for handling opaque objects in custom ops + if is_opaque_constant_type(type(example_value)): + return CustomClassObjectVariable.create( + example_value, # pyrefly: ignore[bad-argument-type] + example_value, + tx=tx, + ) + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + tx.output.fake_mode, example_value + ) + return CustomClassObjectVariable.create( + proxy, + fake_script_obj, + tx=tx, + ) + else: + unimplemented( + gb_type="torch.* op returned non-Tensor", + context=f"example_value type: {typestr(example_value)}; op: {proxy.node.op}; target: {proxy.node.target}", + explanation="torch.* ops that return a non-Tensor cannot be traced into the Dynamo FX graph output", + hints=[], + ) + + +def infer_subclass_type(value: T) -> type[T] | None: + if type(value) in ( + torch.Tensor, + torch.nn.Parameter, + torch._subclasses.fake_tensor.FakeTensor, + torch._subclasses.functional_tensor.FunctionalTensor, + ) or is_traceable_wrapper_subclass(value): + # Ordinarily, we would fakeify a tensor so that it can get dynamic + # shapes and be computed on without triggering actual operations. + # However, how can we fakeify a tensor subclass? Ordinary + # inheritance (nor multiple inheritance) won't work. + # + # Instead, our plan is to *manually simulate* the tensor subclass + # inheriting from a fake tensor with dynamo. This means our + # data representation for a tensor subclass will be a fake tensor + # + tensor subclass type + any extra data the subclass may have + # been storing on the tensor. Because all Python accesses are + # mediated through TensorWithTFOverrideVariable, we can ensure + # that we dispatch differently, e.g., according to + # __torch_function__ + # + # To simplify things for now, the __dict__ tracking bits haven't + # been implemented yet, but they can be added into this design at + # a later point in time. + return None + else: + return type(value) + + +def get_specialized_props( + target_cls: Any, + tx: "InstructionTranslatorBase", + example_value: Any, + subclass_type: type | None, +) -> TensorSpecializedProps: + specialized_props = target_cls.specialize(example_value) + # TODO: not sure about this fake mode test + if ( + is_fake_tensor(example_value) + and maybe_get_fake_mode(example_value) is tx.fake_mode + ): + if subclass_type: + tensor_type = subclass_type + elif isinstance(example_value, torch.nn.Parameter): + tensor_type = torch.nn.Parameter + elif isinstance(example_value, torch.nn.Buffer): + tensor_type = torch.nn.Buffer + else: + tensor_type = torch.Tensor + specialized_props["class_type"] = tensor_type + + return specialized_props + + +def construct_tensor_variable( + target_cls: type[VTTypeAlias], + tx: "InstructionTranslatorBase", + proxy: torch.fx.Proxy, + example_value: Any, + subclass_type: type | None, + options: dict[str, Any], +) -> VTTypeAlias: + """ + Actually construct a tensor variable after all the pre-processing from + wrapping a pre-existing or newly created tensor value. + """ + # NB: In most (all?) cases, this does not actually do a clone. + # (WARNING: this means that if we mutate metadata on the fake + # tensor, the stored example value will update too!) + example_value = _clone_input(example_value, tx.fake_mode) + set_example_value(proxy.node, example_value) + # We bind the unbacked symints in sizes/trdies of tensor lazily. + # So that subgraphs can access the unbacked symbol's proxy in parent graph + # when lifting unbacked symbols of input tensors to subgraph inputs. + # We do it lazily because the tensor may not be used in subgraphs. + if proxy.node.op != "placeholder": + tx.output.current_tracer.track_produced_symints(example_value, proxy) + options.update(get_specialized_props(target_cls, tx, example_value, subclass_type)) + # pyrefly: ignore [bad-argument-count] + return target_cls(proxy, **options) + + +def get_automatic_dynamic_shapes_mark_as() -> DimDynamic: + if config.automatic_dynamic_shapes_mark_as == "dynamic": + return DimDynamic.DYNAMIC + elif config.automatic_dynamic_shapes_mark_as == "unbacked": + return DimDynamic.UNBACKED + else: + raise ValueError( + f"invalid automatic_dynamic_shapes_mark_as = {config.automatic_dynamic_shapes_mark_as}" + ) + + +# Each entry is (pattern, dim) where dim is None for "all dims" or an int +# for a single dim. The optional ":N" suffix on a source list entry restricts +# the match to dim N of the matched tensor. List the same source multiple +# times (e.g. "L['x']:0, L['x']:2") to target multiple specific dims. +_DYNAMIC_SOURCES: list[tuple[str, int | None]] | None = None +_DYNAMIC_SOURCES_CONFIG_HASH: int | None = None + +_DIM_SUFFIX_RE: re.Pattern[str] = re.compile(r"^(.+):(\d+)$") + + +def _parse_source_entry(entry: str) -> tuple[str, int | None]: + """Parse a source list entry into (pattern, dim). + + Entries may end with an optional ``:N`` suffix where ``N`` is a literal + non-negative integer (the dim portion is not part of the name regex). + """ + m = _DIM_SUFFIX_RE.match(entry) + if m: + return m.group(1), int(m.group(2)) + return entry, None + + +def get_dynamic_sources() -> list[tuple[str, int | None]]: + global _DYNAMIC_SOURCES, _DYNAMIC_SOURCES_CONFIG_HASH + + current_hash = hash(torch.compiler.config.dynamic_sources) + + # If we have already calculated the sources and the config hasn't changed, return cached result + if _DYNAMIC_SOURCES is not None and _DYNAMIC_SOURCES_CONFIG_HASH == current_hash: + return _DYNAMIC_SOURCES + + # Config has changed or first time, (re)calculate the sources + _DYNAMIC_SOURCES = [ + _parse_source_entry(s) + for s in torch.compiler.config.dynamic_sources.replace(" ", "").split(",") + if s + ] + _DYNAMIC_SOURCES_CONFIG_HASH = current_hash + + return _DYNAMIC_SOURCES + + +def is_dynamic_source(source_name: str, dim: int | None = None) -> bool: + """Check whether ``source_name`` is in the dynamic-sources list. + + If ``dim`` is None, returns True if any entry matches the source + name (regardless of any per-dim qualifier). This is the right semantics for + callers that ask "is this source dynamic at all?" (e.g. the static-shapes + early return, or non-tensor int sources which have no dim). + + If ``dim`` is given, returns True only when a matching entry either has no + dim qualifier ("all dims dynamic") or its dim qualifier equals ``dim``. + """ + dynamic_sources = get_dynamic_sources() + for pattern, pat_dim in dynamic_sources: + if pattern == source_name or re.match(pattern, source_name): + if dim is None or pat_dim is None or pat_dim == dim: + pretty = pattern if pat_dim is None else f"{pattern}:{pat_dim}" + log.debug( + "%s was marked dynamic due to dynamic-sources entry: %s", + source_name, + pretty, + ) + symbolic_shape_log.info( + "%s was marked dynamic due to dynamic-sources entry: %s", + source_name, + pretty, + ) + return True + return False + + +def record_automatic_dynamic( + tx: "InstructionTranslatorBase", name: str, e: torch.Tensor +) -> FrameStateSizeEntry: + # This mimics stride inference algorithm in _create_symbolic_sizes_strides_storage_offset + ex_size = e.size() + if not is_sparse_any(e): + ex_stride = e.stride() + dim = e.dim() + + stride = [None] * dim + pending = [(ex_stride[i], -i) for i in range(dim)] + pending.sort(key=_nested_int_aware_sort) + candidates = {} + for i_stride, neg_i in pending: + i = -neg_i + # pyrefly: ignore [unsupported-operation] + stride[i] = candidates.get(i_stride, i_stride) + # pyrefly: ignore [no-matching-overload] + candidates.setdefault(i_stride * ex_size[i], InferStride(i)) + else: + # pyrefly: ignore [implicit-any] + stride = [] + + return process_automatic_dynamic( + # type: ignore[arg-type]ks + tx, + name, + # type: ignore[arg-type] + FrameStateSizeEntry.make_tensor(tuple(ex_size), tuple(stride)), + ) + + +# Same per-dim suffix syntax as _DYNAMIC_SOURCES: optional ":N" restricts the +# match to dim N of the matched tensor. +_UNBACKED_SOURCES: list[tuple[str, int | None]] | None = None +_UNBACKED_SOURCES_CONFIG_HASH: int | None = None + + +def get_unbacked_sources() -> list[tuple[str, int | None]]: + global _UNBACKED_SOURCES, _UNBACKED_SOURCES_CONFIG_HASH + + current_hash = hash(torch.compiler.config.unbacked_sources) + + # If we have already calculated the sources and the config hasn't changed, return cached result + if _UNBACKED_SOURCES is not None and _UNBACKED_SOURCES_CONFIG_HASH == current_hash: + return _UNBACKED_SOURCES + + # Config has changed or first time, (re)calculate the sources + _UNBACKED_SOURCES = [ + _parse_source_entry(s) + for s in torch.compiler.config.unbacked_sources.replace(" ", "").split(",") + if s + ] + _UNBACKED_SOURCES_CONFIG_HASH = current_hash + + return _UNBACKED_SOURCES + + +def is_unbacked_source(source_name: str, dim: int | None = None) -> bool: + """Check whether ``source_name`` is in the unbacked-sources list. + + See :func:`is_dynamic_source` for the ``dim`` argument semantics. + """ + unbacked_sources = get_unbacked_sources() + for pattern, pat_dim in unbacked_sources: + if pattern == source_name or re.match(pattern, source_name): + if dim is None or pat_dim is None or pat_dim == dim: + log.debug( + "%s was marked unbacked due to unbacked-sources entry: %s", + source_name, + pattern if pat_dim is None else f"{pattern}:{pat_dim}", + ) + return True + return False + + +# Cache for the parsed `torch.compiler.config.dynamic_values` config. +_DYNAMIC_VALUES: set[int] | None = None +_DYNAMIC_VALUES_CONFIG_HASH: int | None = None + + +def get_dynamic_values() -> set[int]: + global _DYNAMIC_VALUES, _DYNAMIC_VALUES_CONFIG_HASH + + current_hash = hash(torch.compiler.config.dynamic_values) + + if _DYNAMIC_VALUES is not None and _DYNAMIC_VALUES_CONFIG_HASH == current_hash: + return _DYNAMIC_VALUES + + _DYNAMIC_VALUES = { + int(s) + for s in torch.compiler.config.dynamic_values.replace(" ", "").split(",") + if s + } + _DYNAMIC_VALUES_CONFIG_HASH = current_hash + + return _DYNAMIC_VALUES + + +def is_dynamic_value(value: int) -> bool: + """Return True if ``value`` matches an entry in the dynamic-values list.""" + dynamic_values = get_dynamic_values() + if not dynamic_values: + return False + if isinstance(value, bool): + raise TypeError( + f"is_dynamic_value got a bool ({value}); callers must pass an int" + ) + return value in dynamic_values + + +# Performs automatic dynamic dim determination. +# Returns a SymbolicContext +def _automatic_dynamic( + e: Any, + tx: "InstructionTranslatorBase", + source: Source, + static_shapes: bool, + outer_only: bool = False, + tensor_spec: TensorSpec | None = None, +) -> SymbolicContext: + # strided NT not supported + if e.is_nested and not isinstance( + e, torch.nested._internal.nested_tensor.NestedTensor + ): + unimplemented( + gb_type="Encountered strided NestedTensor in automatic dynamic dim determination", + context="", + explanation="torch.compile does not support strided NestedTensor", + hints=[], + ) + + name = source.name + prior_policy = tx.output.tracing_context.tensor_to_context.get(e, None) + shape_env_to_source_to_symbol_cache = ( + prior_policy.shape_env_to_source_to_symbol_cache if prior_policy else {} + ) + + # Get base context if the tensor is a view + view_base_context: SymbolicContext | None = None + if e._is_view(): + base_source = AttrSource(source, "_base") + view_base_context = _automatic_dynamic(e._base, tx, base_source, static_shapes) + + if is_traceable_wrapper_subclass(e) and not outer_only: + # Get symbolic context for outer tensor + outer_context = _automatic_dynamic( + e, tx, source, static_shapes, outer_only=True + ) + if not isinstance(outer_context, StatefulSymbolicContext): + raise AssertionError( + f"Expected StatefulSymbolicContext, got {type(outer_context)}" + ) + + # Get symbolic contexts for inner tensors + inner_contexts = {} # mapping from attr -> symbolic context + attrs, _ = type(e).__tensor_flatten__(e) + for attr in attrs: + match getattr(e, attr): + case torch.Tensor() as inner_value: + inner_source = AttrSource(source, attr) + inner_contexts[attr] = _automatic_dynamic( + inner_value, tx, inner_source, static_shapes + ) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + return SubclassSymbolicContext( + dynamic_sizes=outer_context.dynamic_sizes, + dynamic_strides=outer_context.dynamic_strides, + constraint_sizes=outer_context.constraint_sizes, + constraint_strides=outer_context.constraint_strides, + view_base_context=view_base_context, + tensor_source=outer_context.tensor_source, + shape_env_to_source_to_symbol_cache=outer_context.shape_env_to_source_to_symbol_cache, + inner_contexts=inner_contexts, + track_outer_size_stride=not isinstance( + e, torch.nested._internal.nested_tensor.NestedTensor + ), + ) + + # We preserve the dynamism of inputs. For example, when users call + # make_fx(torch.cond, tracing_mode="symbolic")(*args), inputs have SymInt sizes. + from torch.fx.experimental.symbolic_shapes import has_guarding_hint, is_nested_int + + if any(isinstance(s, SymInt) and not is_nested_int(s) for s in e.size()): + + def _classify_symint(s: Any) -> DimDynamic: + if not isinstance(s, SymInt): + return DimDynamic.STATIC + if not has_guarding_hint(s): + return DimDynamic.UNBACKED + return DimDynamic.DYNAMIC + + return StatefulSymbolicContext( + dynamic_sizes=[_classify_symint(s) for s in e.size()], + dynamic_strides=[DimDynamic.INFER_STRIDE] * e.dim(), + constraint_sizes=[None] * e.dim(), + constraint_strides=[None] * e.dim(), + view_base_context=view_base_context, + tensor_source=source, + shape_env_to_source_to_symbol_cache=shape_env_to_source_to_symbol_cache, + ) + + # Fast path: when the tensor must be static (and not in the dynamic-source + # whitelist), short-circuit to a fully-STATIC StatefulSymbolicContext. + # Important: this must run BEFORE record_automatic_dynamic so that PGO + # frame_state is not polluted by sizes of tensors we are forcing static + # (e.g. nn.Parameter shapes when force_parameter_static_shapes=True). + # Otherwise PGO would later "learn" those dims as dynamic and bypass the + # progressive PGO warm-up that consumers (e.g. test_pgo_dynamic_params) rely on. + if ( + config._dynamic_shapes_spec is None + and static_shapes + and not is_dynamic_source(name) + ): + return StatefulSymbolicContext( + dynamic_sizes=[DimDynamic.STATIC] * e.dim(), + dynamic_strides=[DimDynamic.INFER_STRIDE] * e.dim(), + constraint_sizes=[None] * e.dim(), + constraint_strides=[None] * e.dim(), + view_base_context=view_base_context, + tensor_source=source, + shape_env_to_source_to_symbol_cache=shape_env_to_source_to_symbol_cache, + ) + + # Prep for automatic dynamic + frame_state_entry = record_automatic_dynamic(tx, name, e) + + # TODO: index export_constraints ahead of time so we don't have to + # do a linear scan every time here + t_id = id(e) + # pyrefly: ignore [implicit-any] + dim2constraint = {} + + def update_dim2constraint( + dim: int, constraint_range: "StrictMinMaxConstraint", name: str + ) -> None: + if dim in dim2constraint: + from torch.fx.experimental.symbolic_shapes import StrictMinMaxConstraint + + old_constraint_range, old_name = dim2constraint[dim] + new_constraint_range = StrictMinMaxConstraint( + vr=constraint_range.vr & old_constraint_range.vr, + warn_only=False, + ) + # It is possible for (non-None) old_name and name to be different + # but this will only happen the corresponding Dims can be derived equal. + new_name = old_name or name + dim2constraint[dim] = new_constraint_range, new_name + else: + dim2constraint[dim] = constraint_range, name + + from torch.export.dynamic_shapes import _RelaxedConstraint + + if tx.output.export_constraints is not None: + # type: ignore[iterable] + for constraint in tx.output.export_constraints: + if isinstance(constraint, _RelaxedConstraint): + continue + if constraint.t_id == t_id: + update_dim2constraint( + constraint.dim, constraint.constraint_range, constraint.name + ) + + if config._dynamic_shapes_spec is not None: + return _symbolic_context_from_shapes_spec( + e, + source, + tensor_spec, + view_base_context, + shape_env_to_source_to_symbol_cache, + ) + + dynamic_sizes = [] + dynamic_strides = [] + constraint_sizes = [] + constraint_strides = [] + specialize_on = [] + + for i in range(e.dim()): + # NB: mark dynamic has precedence over static + marked_strict_unbacked = i in getattr(e, "_dynamo_strict_unbacked_indices", ()) + marked_unbacked = i in getattr(e, "_dynamo_unbacked_indices", ()) + marked_dynamic = i in getattr(e, "_dynamo_dynamic_indices", ()) + if marked_dynamic: + symbolic_shape_log.info("marking %s as dynamic (from mark_dynamic)", name) + marked_weak_dynamic = i in getattr( + e, "_dynamo_weak_dynamic_indices", () + ) or i in getattr(e, "_dynamo_propagated_dynamic_indices", ()) + marked_static = i in getattr(e, "_dynamo_static_indices", ()) + + specialize_on.append(getattr(e, "_specialize_on", {}).get(i, [])) + + # Reflect the user directive in the frame_state + # For dynamic, apply None always + + normalized_source_name = normalize_source_name(source.name) + + if marked_dynamic or ( + _is_dim_dynamic_from_source_dynamism(source, normalized_source_name, i) + ): + # TODO: This can be batched + # TODO: Doing this here is kind of sus, maybe better to set this + # up when we initially created the FrameStateSizeEntry to bong + # into the mutable state + log.debug("automatic dynamic %s marked dynamic", name) + mark_size = [auto_unset] * e.dim() + # pyrefly: ignore [unsupported-operation] + mark_size[i] = auto_dynamic + # pyrefly: ignore [bad-argument-type] + frame_state_entry |= FrameStateSizeEntry.make_size(size=mark_size) + + # NB: both static and dynamic have precedence over + automatic_dynamic_size = ( + config.automatic_dynamic_shapes and frame_state_entry.is_size_dynamic(i) + ) + # NB: previously, if size was dynamic, we wouldn't make its stride + # dynamic. But now, because of InferStride concept, we will properly + # not make stride dynamic even if it's wobbling + automatic_dynamic_stride = ( + config.automatic_dynamic_shapes and frame_state_entry.is_stride_dynamic(i) + ) + + if is_dynamic_source(name, i): + log.debug("%s dim %d marked dynamic via dynamic-sources list", name, i) + automatic_dynamic_size = True + + if is_dynamic_value(e.size(i)): + log.debug( + "%s dim %d marked dynamic via dynamic-values list (value=%s)", + name, + i, + e.size(i), + ) + automatic_dynamic_size = True + + if is_unbacked_source(name, i): + log.debug("%s dim %d marked unbacked via unbacked-sources list", name, i) + automatic_dynamic_size = True + + automatic_dynamic = automatic_dynamic_size or automatic_dynamic_stride + + # We will process constraints first, as they will imply that we + # have a dynamic dimension + # Precedence: export constraints > eager constraints + constraint = dim2constraint.get(i) + if constraint is None: + constraint_size = None + constraint_stride = None + if marked_dynamic and not config.allow_ignore_mark_dynamic: + # constraint_stride is deliberaly kept None because no easy way to provide value ranges for mark dynamic + constraint_stride = None + if hasattr(e, "_dynamo_dynamic_range"): + dim_range = [ + dr for dr in e._dynamo_dynamic_range if dr.dim == i + ].pop() + if dim_range.min is None and dim_range.max is None: + constraint_size = RelaxedUnspecConstraint(warn_only=False) + else: + from torch.fx.experimental.symbolic_shapes import ( + StrictMinMaxConstraint, + ) + + constraint_size = StrictMinMaxConstraint( + vr=ValueRanges(lower=dim_range.min, upper=dim_range.max), + warn_only=False, + ) + else: + constraint_size = RelaxedUnspecConstraint(warn_only=False) + elif marked_strict_unbacked: + constraint_size = RelaxedUnspecConstraint(warn_only=False) + elif not marked_static and automatic_dynamic: + set_feature_use("dynamo.automatic_dynamic_shapes", True) + if automatic_dynamic_size: + constraint_size = RelaxedUnspecConstraint(warn_only=True) + if automatic_dynamic_stride: + constraint_stride = RelaxedUnspecConstraint(warn_only=True) + else: + if not marked_static and not config.automatic_dynamic_shapes: + set_feature_use("dynamo.automatic_dynamic_shapes", False) + constraint_size = None + constraint_stride = None + else: + constraint_size, name_ = constraint + constraint_stride = None + dim_name = f"{name}.size()[{i}]" + tx.output.shape_env.source_name_to_debug_name[dim_name] = name_ + constraint_sizes.append(constraint_size) + constraint_strides.append(constraint_stride) + + if marked_unbacked or is_unbacked_source(name, i): + dynamic_size = DimDynamic.UNBACKED + elif ( + constraint_size is not None + or marked_dynamic + or marked_weak_dynamic + or is_nested_int(e.size()[i]) + ): + # NB: We could assert static_shapes is False here, but it + # seems better to allow the user to override symbolic_context in this + # case + if automatic_dynamic: + dynamic_size = get_automatic_dynamic_shapes_mark_as() + else: + dynamic_size = DimDynamic.DYNAMIC + elif static_shapes or config.assume_static_by_default or marked_static: + dynamic_size = DimDynamic.STATIC + else: + # TODO: When does this show up? + if not config.assume_static_by_default: + symbolic_shape_log.info( + "marking %s as dynamic (from assume_static_by_default = False)", + name, + ) + dynamic_size = DimDynamic.DUCK + + if constraint_stride is not None: + dynamic_stride = DimDynamic.DYNAMIC + else: + dynamic_stride = DimDynamic.INFER_STRIDE + + dynamic_sizes.append(dynamic_size) + dynamic_strides.append(dynamic_stride) + + return StatefulSymbolicContext( + dynamic_sizes=dynamic_sizes, + dynamic_strides=dynamic_strides, + constraint_sizes=constraint_sizes, + # pyrefly: ignore [bad-argument-type] + constraint_strides=constraint_strides, + specialize_on=specialize_on, + view_base_context=view_base_context, + tensor_source=source, + shape_env_to_source_to_symbol_cache=shape_env_to_source_to_symbol_cache, + shape_ids=getattr(e, "_dynamo_shape_ids", None), + unbacked_bounds=getattr(e, "_dynamo_unbacked_bounds", None), + excluded_sizes=frame_state_entry.excluded_sizes, + ) + + +# See note [Tensor Fakification and Symbol Caching] +def wrap_to_fake_tensor_and_record( + e: Any, + tx: "InstructionTranslatorBase", + *, + source: Source | None, + is_tensor: bool, + parent_context: Any | None = None, + tensor_spec: TensorSpec | None = None, +) -> Any: + _t0 = time.time_ns() + try: + return _wrap_to_fake_tensor_and_record_impl( + e, + tx, + source=source, + is_tensor=is_tensor, + parent_context=parent_context, + tensor_spec=tensor_spec, + ) + finally: + tx.output.bytecode_tracing_timings.wrap_to_fake_tensor_and_record_ns += ( + time.time_ns() - _t0 + ) + + +def _wrap_to_fake_tensor_and_record_impl( + e: Any, + tx: "InstructionTranslatorBase", + *, + source: Source | None, + is_tensor: bool, + parent_context: Any | None = None, + tensor_spec: TensorSpec | None = None, +) -> Any: + if ( + type(e) in (torch.Tensor, torch.nn.Parameter, FakeTensor) + or isinstance(e, torch.Tensor) + or is_traceable_wrapper_subclass(e) + ): + if source is None: + raise AssertionError("source must not be None for tensor wrapping") + static_shapes, _reason = tensor_always_has_static_shape( + e, + is_tensor, + tensor_source=source, + ) + + if not parent_context: + symbolic_context = _automatic_dynamic( + e, tx, source, static_shapes, tensor_spec=tensor_spec + ) + else: + # Parent contexts are passed in when we are recursively creating + # fake tensors for subclasses. A better design would be not to create a + # parent/child relationship, but to recursively call _automatic_dynamic + # as we recursively call wrap_to_fake_tensor_and_record. This runs + # into bugs around how meta_utils knows and works to create fake tensors + # with tensor subclasses. Ideally, dynamo would drive both the recursive + # wrap_to_fake_tensor_and_record and _automatic_dynamic policy creation. + if not isinstance(source, AttrSource): + raise AssertionError( + f"Expected AttrSource for parent context, got {type(source)}" + ) + inner_context_name = source.member + symbolic_context = parent_context.inner_contexts[inner_context_name] + + log.debug( + "wrap_to_fake %s %s %s %s", + source.name, + tuple(e.shape), + symbolic_context, + type(e), + ) + + # Note [enable_python_dispatcher in dynamo] + # Dynamo disables itself when it runs fake tensor prop, which means that tensor subclasses + # have no way to know (purely based off of global state) if they are currently being run under compile or not. + # we use enable_python_dispatcher mainly to tweak the DispatchKeyState so that subclass authors + # can check it to know if they are running in an eager context or not + with enable_python_dispatcher(): + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None") + fake_e = wrap_fake_exception( + lambda: tx.fake_mode.from_tensor( + e, # type: ignore[arg-type] + source=source, + symbolic_context=symbolic_context, + ) + ) + if tensor_spec is not None: + _wire_tensor_spec_dims(tensor_spec, fake_e) + if ( + source is not None + and isinstance(fake_e, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR + and (sym_val := fake_e.item_memo) is not None + ): + # Match the peephole in FakeTensorConverter.from_real_tensor that + # strips FloatTensorSource before calling create_symbol. Without + # this, the tracked fake source name won't match source_to_var and + # produce_guards_verbose will report "(unknown source)". + if isinstance(source, FloatTensorSource): + item_source = source.base + else: + item_source = CallMethodItemSource(source) + tx.output.tracked_fakes.append( + TrackedFake(sym_val, item_source, symbolic_context) + ) + + if is_traceable_wrapper_subclass(fake_e): + attrs, _ = fake_e.__tensor_flatten__() + for attr in attrs: + fake_inner = getattr(fake_e, attr) + inner = getattr(e, attr) + inner_source = AttrSource(source, attr) + wrap_to_fake_tensor_and_record( + inner, + tx, + source=inner_source, + is_tensor=isinstance(fake_inner, torch.Tensor), + parent_context=symbolic_context, + ) + + tx.output.tracing_context.tensor_to_context[e] = symbolic_context + if is_sparse_any(fake_e): + # TODO: for TensorGuards, this eventually may need more + # fields for the size/stride of any other constituents + values = fake_e._values() if fake_e.is_sparse else fake_e.values() + tx.output.input_source_to_sizes_strides[source] = { + "size": fake_e.size(), + # TODO: revise this, but for now this stride instead of () + # avoids SegFault with PYTORCH_TEST_WITH_DYNAMO=1 + "stride": (1,) * fake_e.ndim, + "values_size": values.size(), + "values_stride": values.stride(), + } + else: + tx.output.input_source_to_sizes_strides[source] = { + "size": fake_e.size(), + "stride": fake_e.stride(), + } + + if ( + is_tensor + and not (static_shapes and source.is_specialized_nn_module()) + and not is_constant_source(source) + ): + tx.output.tracked_fakes.append( + TrackedFake(fake_e, source, symbolic_context) + ) + tx.output.tracked_fakes_id_to_source[id(e)].append(source) + + return fake_e + else: + return e + + +class SourcelessBuilder: + """ + Like builder, but stateless and does not require a source. Useful for simple type->VT objects, or objects + that are being created/evaporated during inlining (ex: consider a locally made list of tensors we then iterate over + .), such a list should not show up as an artifact from inputs, nor in reconstruction, nor in the graph. However, + there may be reasons to represent it as a ListVariable internally. + + NOTE - Objects produced here are born UNGUARDED due to the nature of sources! + + NOTE - This class is very new! It will have some rough edges, but it was created to stem the bleeding of giant + if/else type->VariableTracker trees that were cropping up all over dynamo. + """ + + def __init__(self) -> None: + raise AssertionError("Use SourcelessBuilder.create()") + + @overload + @staticmethod + def create( + tx: "InstructionTranslatorBase", + value: type[set[Any]] + | type[dict[Any, Any]] + | type[tuple[Any, ...]] + | type[list[Any]], + ) -> BuiltinVariable: ... + + @overload + @staticmethod + def create(tx: "InstructionTranslatorBase", value: list[Any]) -> ListVariable: ... + + @overload + @staticmethod + def create( + tx: "InstructionTranslatorBase", value: tuple[Any, ...] + ) -> TupleVariable: ... + + @overload + @staticmethod + def create( + tx: "InstructionTranslatorBase", value: bool | int | float | str + ) -> ConstantVariable: ... + + @overload + @staticmethod + def create(tx: "InstructionTranslatorBase", value: Any) -> VariableTracker: ... + + @staticmethod + def create(tx: "InstructionTranslatorBase", value: Any) -> VariableTracker: + value_type = type(value) + # type: ignore[attr-defined] + fast_handler = SourcelessBuilder._type_handlers.get(value_type) + if fast_handler: + return fast_handler(tx, value) + + if isinstance(value, VariableTracker): + # This is always valid to call, and useful for recursive calls. + return value + elif ( + is_opaque_constant_type(type(value)) + and not isinstance(value, enum.Enum) + and not is_pybind11_enum_member(value) + ): + return CustomClassObjectVariable.create(value, value, tx=tx) + elif is_opaque_symbolic_type(type(value)): + # This is for handling opaque objects in custom ops + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + tx.output.fake_mode, value + ) + return CustomClassObjectVariable.create( + value, # pyrefly: ignore[bad-argument-type] + fake_script_obj, + tx=tx, + ) + # type: ignore[attr-defined] + elif isinstance(value, dataclasses._HAS_DEFAULT_FACTORY_CLASS): + return UserDefinedObjectVariable(value) + elif ConstantVariable.is_literal(value): + return ConstantVariable.create(value) + elif callable(value) and trace_rules.lookup_callable(value) is not None: + if trace_rules.is_callable_allowed(value): + tx.output.has_user_defined_allowed_in_graph = True + # pyrefly: ignore[not-callable, bad-argument-count] + return trace_rules.lookup_callable(value)(value) + elif callable(value) and UserDefinedClassVariable.is_supported_new_method( + value + ): + # NamedTuple._make uses an alias of tuple.__new__ + # pyrefly: ignore[not-callable, bad-argument-count, missing-attribute] + obj = trace_rules.lookup_callable(value.__self__)(value.__self__) + return GetAttrVariable(obj, "__new__", py_type=type(value)) + elif is_function_or_wrapper(value): + # pyrefly: ignore[not-callable, bad-argument-count] + return trace_rules.lookup(value)(value) + elif isinstance( + value, + (enum.Enum, torch.DispatchKey, torch._C._functorch.TransformType), + ) or is_pybind11_enum_member(value): + existing = tx.output.side_effects.id_to_variable.get(id(value)) + if existing is not None: + return existing + return tx.output.side_effects.track_mutable( + value, + UserDefinedObjectVariable(value), + AttributeMutationNew, + ) + elif isinstance(value, (type, abc.ABCMeta)): + if issubclass(type(value), type) and issubclass(value, BaseException): + return UserDefinedExceptionClassVariable(value) + return UserDefinedClassVariable(value) + elif isinstance(value, types.MethodWrapperType): + descriptor = inspect.getattr_static(type(value.__self__), value.__name__) + if not isinstance(descriptor, types.WrapperDescriptorType): + raise AssertionError( + f"expected WrapperDescriptorType, got {type(descriptor)}" + ) + return MethodWrapperVariable( + descriptor, SourcelessBuilder.create(tx, value.__self__) + ) + elif isinstance(value, types.MethodType): + if isinstance(value.__self__, (type, abc.ABCMeta)): + # value is a classmethod + if getattr(value.__self__, value.__func__.__name__) != value: + raise AssertionError( + f"Classmethod lookup mismatch: {value.__func__.__name__} on {value.__self__}" + ) + cls_obj_vt = SourcelessBuilder.create(tx, value.__self__) + try: + # pyrefly: ignore[bad-argument-type] + return cls_obj_vt.tp_getattro_impl(tx, value.__func__.__name__) + except NotImplementedError: + pass # failthrough to unimplemented branch + else: + # Instance method — look up the VT for __self__ via side effects + obj_vt = tx.output.side_effects.id_to_variable.get(id(value.__self__)) + if obj_vt is not None: + return torch._dynamo.variables.UserMethodVariable( + value.__func__, obj_vt + ) + elif isinstance(value, torch.fx.graph_module.GraphModule): + return SourcelessGraphModuleVariable(value) + elif isinstance( + value, (importlib.machinery.ModuleSpec, torch.utils._pytree.TreeSpec) + ): + return UserDefinedObjectVariable(value) + elif isinstance(value, (re.Pattern, re.Match)): + return ConstantLikeVariable(value) + elif isinstance(value, torch._dynamo.variables.lazy.LazySymNodeFormatString): + try: + return ConstantVariable.create(str(value)) + # If we cannot create due to error in str() call, we should + # try explicitly for string format variable + except ( + torch._dynamo.exc.UserError, + torch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode, + ): + return StringFormatVariable.create( + value.fmt_var.as_python_constant(), + [value.sym_node_var], + {}, + ) + elif isinstance(value, type(torch._higher_order_ops.flex_attention_backward)): + return torch._dynamo.variables.higher_order_ops.FlexAttentionBackwardHighOrderVariable( + value + ) + elif isinstance( + value, + ( + types.GenericAlias, + types.UnionType, + # `typing.Any | X` (and `typing.Union[...]`) evaluates to a + # `typing._UnionGenericAlias` on Python <= 3.10, not a + # `types.UnionType` + typing._UnionGenericAlias, # type: ignore[attr-defined] + ), + ): + return TypingVariable(value) + elif is_namedtuple(value): + output = [ + SourcelessBuilder.create(tx, getattr(value, name)) + for name in namedtuple_fields(type(value)) + ] + tuple_vt = TupleVariable(output, mutation_type=ValueMutationNew()) + return UserDefinedTupleVariable.get_vt_cls(type(value))( + value, tuple_vt=tuple_vt + ) + elif ( + isinstance(value, torch.SymInt) + and value.node.expr in tx.output.bound_symbols + ): + proxy = tx.output.bound_symbols[value.node.expr] + return SymNodeVariable.create(tx, proxy) + elif isinstance(value, slice): + items = [ + SourcelessBuilder.create(tx, getattr(value, k)) + for k in ("start", "stop", "step") + ] + return SliceVariable(items, tx) # pyrefly: ignore[bad-argument-type] + elif isinstance(value, torch.nn.parallel.distributed.DistributedDataParallel): + return UnspecializedNNModuleVariable(value) + elif istype(value, object): + return ObjectVariable(value) + elif ( + sys.version_info >= (3, 15) + and type(value) is builtins.sentinel # pyrefly: ignore [missing-attribute] + ): + return SentinelVariable(value) + unimplemented( + gb_type="Unexpected type in sourceless builder", + context=f"{value_type.__module__}.{value_type.__qualname__}", + explanation=f"SourcelessBuilder.create does not know how to wrap {value_type}", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + @staticmethod + def wrap_constant_literal(value: object) -> VariableTracker: + if not ConstantVariable.is_literal(value): + raise AssertionError(f"Expected literal value, got {type(value)}") + return ConstantVariable.create(value=value) + + @staticmethod + def make_type_handlers() -> dict[ + type, Callable[["InstructionTranslatorBase", Any], VariableTracker] + ]: + create = SourcelessBuilder.create + handlers: dict[ + type, Callable[[InstructionTranslatorBase, Any], VariableTracker] + ] = {} + for t in common_constant_types: + handlers[t] = lambda tx, value: ConstantVariable(value) + handlers[set] = lambda tx, value: SetVariable( + [create(tx, x) for x in value], mutation_type=ValueMutationNew() + ) + handlers[OrderedSet] = lambda tx, value: OrderedSetVariable( + [create(tx, x) for x in value], mutation_type=ValueMutationNew() + ) + handlers[dict] = lambda tx, value: ConstDictVariable( + {create(tx, k): create(tx, v) for k, v in value.items()}, + mutation_type=ValueMutationNew(), + ) + handlers[list] = lambda tx, value: ListVariable( + [create(tx, x) for x in value], mutation_type=ValueMutationNew() + ) + handlers[tuple] = lambda tx, value: TupleVariable( + [create(tx, x) for x in value] + ) + handlers[torch.Size] = lambda tx, value: SizeVariable( + [create(tx, x) for x in value] + ) + handlers[collections.OrderedDict] = lambda tx, value: OrderedDictVariable( + {create(tx, k): create(tx, v) for k, v in value.items()}, + mutation_type=ValueMutationNew(), + ) + # immutable_dict is a dict subclass; represent it as a plain dict VT. + handlers[immutable_dict] = handlers[dict] + handlers[immutable_list] = handlers[list] + # Sourceless MappingProxyType object can be encountered while tracing + # type.__dict__["__dict__"].__get__ + handlers[types.MappingProxyType] = lambda tx, value: MappingProxyVariable( + ConstDictVariable( + {create(tx, k): create(tx, v) for k, v in value.items()}, + mutation_type=ValueMutationNew(), + ), + ) + handlers[types.GetSetDescriptorType] = ( + lambda tx, value: GetSetDescriptorVariable(value) + ) + handlers[types.MemberDescriptorType] = ( + lambda tx, value: MemberDescriptorVariable(value) + ) + handlers[inspect.Parameter] = lambda tx, value: UserDefinedObjectVariable( + value, mutation_type=ValueMutationNew() + ) + handlers[random.Random] = lambda tx, value: RandomClassVariable() + handlers[types.ModuleType] = lambda tx, value: PythonModuleVariable(value) + + handlers[torch.DispatchKeySet] = lambda tx, value: DispatchKeySetVariable( + value, mutation_type=ValueMutationNew() + ) + handlers[torch._functorch.pyfunctorch.FuncTorchInterpreter] = ( + lambda tx, value: FuncTorchInterpreterVariable( + value, mutation_type=ValueMutationNew() + ) + ) + + handlers[torch.distributions.constraints._Real] = ( + lambda tx, value: UserDefinedObjectVariable( + value, mutation_type=ValueMutationNew() + ) + ) + handlers[torch.distributions.constraints._Interval] = ( + lambda tx, value: UserDefinedObjectVariable( + value, mutation_type=ValueMutationNew() + ) + ) + handlers[torch.distributions.constraints.Constraint] = ( + lambda tx, value: UserDefinedObjectVariable( + value, mutation_type=ValueMutationNew() + ) + ) + + def passthrough(tx: "InstructionTranslatorBase", value: T) -> T: + return value + + for cls in VariableTrackerMeta.all_subclasses: + handlers[cls] = passthrough + return handlers + + +SourcelessBuilder._type_handlers = SourcelessBuilder.make_type_handlers() + + +class SourcelessUserDefinedObjectBuilder: + """ + SourceLessBuilder does not return a UserDefinedObjectVariable, but in some + cases it might be ok to return UserDefinedObjects. In such case, use this + builder. + """ + + def __init__(self) -> None: + raise AssertionError("Use SourcelessUserDefinedObjectBuilder.create()") + + @staticmethod + def create(tx: "InstructionTranslatorBase", value: Any) -> VariableTracker: + value_type = type(value) + if issubclass(value_type, MutableMapping): + return MutableMappingVariable(value, mutation_type=ValueMutationNew()) + elif isinstance(value, torch.nn.Module): + return UnspecializedNNModuleVariable( + value, mutation_type=ValueMutationNew() + ) + else: + return UserDefinedObjectVariable(value, mutation_type=ValueMutationNew()) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builtin.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builtin.py new file mode 100644 index 0000000000000000000000000000000000000000..e81ae0d93385538feaf8327f3d2bb50e49b5397a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builtin.py @@ -0,0 +1,3860 @@ +""" +Built-in function and type variable tracking for TorchDynamo's symbolic execution. + +This module contains variable tracker classes for Python built-in functions, types, +and operations during graph compilation. It handles symbolic execution of: + +- Built-in functions (len, getattr, isinstance, etc.) +- Type constructors (int, float, str, list, dict, etc.) +- Built-in operators and methods +- Special Python constructs (super, hasattr, etc.) + +Key classes: +- BuiltinVariable: Tracks built-in functions and handles their execution +- TypeVariable: Manages type constructor calls and type checking +- SuperVariable: Handles super() calls in class hierarchies + +These variable trackers ensure that built-in Python operations are correctly +handled during symbolic execution, either by executing them directly when safe +or by creating appropriate graph nodes when needed. +""" + +import abc +import ast +import builtins +import contextlib +import functools +import inspect +import itertools +import logging +import math +import operator +import sys +import types +import typing +from collections import defaultdict, OrderedDict +from collections.abc import Callable, Iterable, Sequence +from typing import Any, NoReturn, TYPE_CHECKING + +import torch +from torch.overrides import BaseTorchFunctionMode +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .. import graph_break_hints, polyfills, variables +from ..exc import ( + handle_observed_exception, + ObservedAttributeError, + ObservedTypeError, + ObservedUserStopIteration, + raise_observed_exception, + raise_type_error, + raise_value_error, + unimplemented, + Unsupported, + UserError, + UserErrorType, +) +from ..guards import GuardBuilder, install_guard +from ..source import ( + AttrSource, + GetItemSource, + GlobalSource, + is_constant_source, + LocalSource, + Source, + TypeSource, +) +from ..utils import ( + check_constant_args, + check_numpy_ndarray_args, + check_unspec_or_constant_args, + check_unspec_python_args, + dict_methods, + extract_fake_example_value, + get_fake_value, + is_tensor_getset_descriptor, + istype, + numpy_operator_wrapper, + proxy_args_kwargs, + raise_args_mismatch, + str_methods, + tensortype_to_dtype, + unpack_iterable, +) +from .base import ( + AsPythonConstantNotImplementedError, + GetSet, + Member, + ValueMutationNew, + VariableTracker, +) +from .constant import ConstantVariable, FakeIdVariable +from .dicts import ( + ConstDictVariable, + DictItemsVariable, + DictKeysVariable, + DictViewVariable, + OrderedDictVariable, +) +from .hashable import is_hashable +from .lists import BaseListVariable, ListVariable, TupleIteratorVariable, TupleVariable +from .misc import CellVariable, NullVariable, StringFormatVariable +from .object_protocol import ( + _NO_DEFAULT, + binary_iop, + binary_op, + generic_delitem, + generic_getattr, + generic_getitem, + generic_getiter, + generic_hash, + generic_is_true, + generic_issubclass, + generic_repr, + generic_richcompare, + generic_setitem, + generic_size, + generic_str, + maybe_get_python_type, + pycallable_check, + pyiter_check, + pylong_from_base, + pynumber_absolute, + pynumber_add, + pynumber_float, + pynumber_index, + pynumber_inplace_add, + pynumber_inplace_matrix_multiply, + pynumber_inplace_multiply, + pynumber_int, + pynumber_invert, + pynumber_matrix_multiply, + pynumber_multiply, + pynumber_negative, + pynumber_positive, + pynumber_tobase, + pysequence_check, + pysequence_contains, + python_constant_richcompare_impl, + ternary_iop, + ternary_op, + type_implements_mp_length, + type_implements_sq_length, + vt_identity_compare, +) +from .sets import FrozensetVariable, SetVariable +from .tensor import ( + FakeItemVariable, + supported_comparison_ops, + SymNodeVariable, + TensorVariable, + UnspecializedPythonVariable, +) +from .user_defined import UserDefinedObjectVariable, UserDefinedVariable + + +if TYPE_CHECKING: + # Cyclic dependency... + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + +log = logging.getLogger(__name__) + + +IN_PLACE_DESUGARING_MAP = { + operator.iadd: operator.add, + operator.isub: operator.sub, + operator.imul: operator.mul, + operator.ifloordiv: operator.floordiv, + operator.itruediv: operator.truediv, + operator.imod: operator.mod, + operator.imatmul: operator.imatmul, + operator.ilshift: operator.lshift, + operator.irshift: operator.rshift, + operator.ipow: operator.pow, + operator.iand: operator.and_, + operator.ior: operator.or_, + operator.ixor: operator.xor, +} + +_BUILTIN_CONSTANT_FOLDABLE_METHODS: dict[type, frozenset[str]] = { + int: frozenset({"__new__", "from_bytes"}), + bool: frozenset({"__new__", "from_bytes"}), + float: frozenset({"fromhex", "hex"}), +} +if sys.version_info >= (3, 14): + _BUILTIN_CONSTANT_FOLDABLE_METHODS[complex] = frozenset({"from_number"}) + + +_HandlerCallback = Callable[ + ["InstructionTranslatorBase", typing.Any, typing.Any], VariableTracker | None +] +_TrackersType = type[VariableTracker] | tuple[type[VariableTracker], ...] +_OPERATOR_TO_DUNDER: dict[Callable[..., Any], str] = { + operator.eq: "__eq__", + operator.ne: "__ne__", + operator.lt: "__lt__", + operator.le: "__le__", + operator.gt: "__gt__", + operator.ge: "__ge__", +} + + +bin_ops = ( + operator.pow, + operator.mul, + operator.matmul, + operator.floordiv, + operator.truediv, + operator.mod, + operator.add, + operator.lt, + operator.gt, + operator.ge, + operator.le, + operator.ne, + operator.eq, + operator.sub, + operator.ipow, + operator.imul, + operator.imatmul, + operator.ifloordiv, + operator.itruediv, + operator.imod, + operator.iadd, + operator.isub, +) + +bin_int_ops = ( + operator.and_, + operator.or_, + operator.xor, + operator.iand, + operator.ixor, + operator.ior, +) + +un_int_ops = (operator.invert,) + +tensor_and_int_ops = ( + operator.lshift, + operator.rshift, + operator.ilshift, + operator.irshift, + operator.getitem, +) + +un_ops = ( + operator.abs, + operator.pos, + operator.neg, + operator.not_, # Note: this has a local scalar dense call + operator.length_hint, +) + +_SET_LIKE_OP_SUPPORT: tuple[type[VariableTracker], ...] = ( + DictItemsVariable, + DictKeysVariable, + SetVariable, + UserDefinedObjectVariable, +) + +BUILTIN_TO_TENSOR_FN_MAP: dict[Callable[..., Any], Callable[..., Any]] = {} + +# These functions represent the r* versions of the above ops +# Basically, if __add__(1, Tensor) is called, it is translated +# to __radd__(Tensor, 1). +# In the builtin var, we check if there is a tensor in the first args position, +# if not, we swap the args and use the r* version of the op. +BUILTIN_TO_TENSOR_RFN_MAP: dict[Callable[..., Any], Callable[..., Any]] = {} + +# Sentinel for `inspect.getattr_static` lookups that must distinguish +# "attribute absent" from "attribute is None" (e.g. `__reversed__ = None` +# opt-out). +_MISSING_SENTINEL = object() + +_COMPUTED_LAZY_CONSTANT_OPS: frozenset[Callable[..., Any]] = frozenset( + [ + operator.add, + operator.sub, + operator.mul, + ] +) + + +def _try_computed_lazy_constant( + fn: Callable[..., Any], args: list[VariableTracker] +) -> VariableTracker | None: + """Build a ComputedLazyConstantVariable for fn(*args), or None to fall back.""" + from .lazy import ComputedLazyConstantVariable, LazyConstantVariable + + fn = IN_PLACE_DESUGARING_MAP.get(fn, fn) + if fn not in _COMPUTED_LAZY_CONSTANT_OPS or len(args) != 2: + return None + any_unrealized = False + for arg in args: + if ( + isinstance(arg, (LazyConstantVariable, ComputedLazyConstantVariable)) + and not arg.is_realized() + ): + any_unrealized = True + elif not isinstance(arg, ConstantVariable): + return None + if not any_unrealized: + return None + return ComputedLazyConstantVariable.create(fn, args) + + +def populate_builtin_to_tensor_fn_map() -> None: + global BUILTIN_TO_TENSOR_FN_MAP + if len(BUILTIN_TO_TENSOR_FN_MAP) > 0: + # Only populate once; after there are elements present no need to + # repopulate + return + most_recent_func: Callable[..., Any] | None = None + + class GetMethodMode(BaseTorchFunctionMode): + """ + Mode to extract the correct methods from torch function invocations + (Used to get the correct torch.Tensor methods from builtins) + """ + + def __torch_function__( + self, + func: Callable[..., Any], + types: Any, + args: Sequence[Any] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + kwargs = kwargs or {} + nonlocal most_recent_func + most_recent_func = func + return func(*args, **kwargs) + + inp0 = torch.ones(1) + inp1 = torch.ones(1) + inp0_int = torch.ones(1, dtype=torch.int32) + inp1_int = torch.ones(1, dtype=torch.int32) + with GetMethodMode(): + setups_and_oplists: list[tuple[Callable[..., Any], Iterable[Any]]] = [ + (lambda o: o(inp0), un_ops), + (lambda o: o(inp0_int), un_int_ops), + (lambda o: o(inp0, inp1), bin_ops), + (lambda o: o(inp0_int, inp1_int), bin_int_ops), + (lambda o: o(inp0_int, 0), tensor_and_int_ops), + ] + for setup_fn, op_list in setups_and_oplists: + for op in op_list: + setup_fn(op) + if most_recent_func is None: + raise AssertionError( + f"most_recent_func is None after setup for op {op}" + ) + BUILTIN_TO_TENSOR_FN_MAP[op] = most_recent_func + + # gather the reverse functions + rsetups_and_oplists: list[tuple[Callable[..., Any], Iterable[Any]]] = [ + ( + lambda o: o(1, inp1), + bin_ops, + ), # Get r* ops, (ex. __sub__(int, Tensor) -> __rsub__(Tensor, int)) + (lambda o: o(1, inp1_int), bin_int_ops), + (lambda o: o(0, inp0_int), tensor_and_int_ops), + ] + + rskips = {operator.matmul, operator.imatmul, operator.getitem} + for setup_fn, op_list in rsetups_and_oplists: + for op in op_list: + if op in rskips: + continue + setup_fn(op) + if most_recent_func is None: + raise AssertionError( + f"most_recent_func is None after setup for reverse op {op}" + ) + if most_recent_func != BUILTIN_TO_TENSOR_FN_MAP[op]: + BUILTIN_TO_TENSOR_RFN_MAP[op] = most_recent_func + + +class BaseBuiltinVariable(VariableTracker): + """ + Common base class for all builtin variable trackers (BuiltinVariable, + DictBuiltinVariable, IterBuiltinVariable, and future specialized builtins). + + Provides shared implementations for guard installation, hasattr tracing, + and Python-level hashability/equality. + + Specialized subclasses (e.g. DictBuiltinVariable) set `_fn` as a class + attribute. BuiltinVariable stores the callable on the instance as `self.fn` + and overrides as_python_constant / reconstruct / tp_getattro_impl accordingly. + """ + + _fn: Any = None + + # Type attribute readers shared by BaseBuiltinVariable and BuiltinVariable. + # Each reader declines (returns None) when the wrapped callable is not a type, + # letting getattro_impl fall through to its dynamic getattr handling. + # CPython classification (Objects/typeobject.c): + # __bases__ -> type_getsets[] type_get_bases (getset) + # __base__ -> type_members[] {T_OBJECT, offsetof(tp_base), Py_READONLY} + # __flags__ -> type_members[] {T_ULONG, offsetof(tp_flags), Py_READONLY} + def _type_get_bases( + self: "BaseBuiltinVariable", tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + fn = self.as_python_constant() + if not isinstance(fn, type): + return None + source = self.source and AttrSource(self.source, "__bases__") + items = [ + VariableTracker.build(tx, b, source and GetItemSource(source, i)) + for i, b in enumerate(fn.__bases__) + ] + return variables.TupleVariable(items, source=source) + + def _type_get_base( + self: "BaseBuiltinVariable", tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + fn = self.as_python_constant() + if not isinstance(fn, type): + return None + source = self.source and AttrSource(self.source, "__base__") + return VariableTracker.build(tx, fn.__base__, source) + + def _type_get_flags( + self: "BaseBuiltinVariable", tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + fn = self.as_python_constant() + if not isinstance(fn, type): + return None + source = self.source and AttrSource(self.source, "__flags__") + return VariableTracker.build(tx, fn.__flags__, source) + + tp_getset = {"__bases__": GetSet(_type_get_bases, None)} + tp_members = { + "__base__": Member(_type_get_base, None), + "__flags__": Member(_type_get_flags, None), + } + + @classmethod + def create_with_source(cls, value: Any, source: Source) -> "BaseBuiltinVariable": + install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH)) + return cls(source=source) + + def as_python_constant(self) -> Any: + return self._fn + + def reconstruct(self, codegen: "PyCodegen") -> None: + name = self.as_python_constant().__name__ + if name in codegen.tx.f_globals: + raise AssertionError("shadowed global") + codegen.append_output(codegen.create_load_global(name, add=True)) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # Declarative type-attribute dispatch, mirroring the consultation at the + # top of VariableTracker.getattro_impl. Inlined here because this + # override keeps its own GetAttrVariable fallback instead of delegating + # to super(). + fn = self.as_python_constant() + source = self.source and AttrSource(self.source, name) + attr = getattr(fn, name, None) + return variables.GetAttrVariable( + self, name, py_type=type(attr) if attr is not None else None, source=source + ) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + return VariableTracker.build(tx, hasattr(self.as_python_constant(), name)) # type: ignore[return-value] + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CPython meth_hash: https://github.com/python/cpython/blob/e76aa128fe/Objects/methodobject.c#L319 + return hash(self.as_python_constant()), False + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + return python_constant_richcompare_impl(self, tx, other, op) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__str__" and len(args) == 1 and not kwargs: + arg = args[0] + if self.as_python_constant() is object: + return generic_repr(tx, arg) + if self.as_python_constant() is type: + if isinstance(arg, variables.UserDefinedClassVariable): + return VariableTracker.build(tx, type.__str__(arg.value)) + if arg.is_python_constant() and isinstance( + arg.as_python_constant(), type + ): + return VariableTracker.build( + tx, type.__str__(arg.as_python_constant()) + ) + return generic_str(tx, arg) + if name == "__repr__" and len(args) == 1 and not kwargs: + arg = args[0] + if self.as_python_constant() is object and isinstance( + arg, variables.UserDefinedObjectVariable + ): + return VariableTracker.build(tx, object.__repr__(arg.value)) + if self.as_python_constant() is type: + if isinstance(arg, variables.UserDefinedClassVariable): + return VariableTracker.build(tx, type.__repr__(arg.value)) + if arg.is_python_constant() and isinstance( + arg.as_python_constant(), type + ): + return VariableTracker.build( + tx, type.__repr__(arg.as_python_constant()) + ) + return generic_repr(tx, arg) + return super().call_method(tx, name, args, kwargs) + + +def _uses_custom_classinfo_check( + type_info: Any, + *, + use_instancecheck: bool = True, + use_subclasscheck: bool = True, +) -> bool: + if isinstance(type_info, tuple): + return any(_uses_custom_classinfo_check(item) for item in type_info) + if isinstance(type_info, types.UnionType): + return any( + _uses_custom_classinfo_check(item) for item in typing.get_args(type_info) + ) + if typing.get_origin(type_info) is typing.Union: + typing_union_uses_instancecheck = sys.version_info >= (3, 12) + return any( + _uses_custom_classinfo_check( + item, + use_instancecheck=typing_union_uses_instancecheck, + use_subclasscheck=True, + ) + for item in typing.get_args(type_info) + ) + if isinstance(type_info, type): + if type_info in tensortype_to_dtype: + return False + + type_info_meta = type(type_info) + instancecheck = getattr(type_info_meta, "__instancecheck__", None) + subclasscheck = getattr(type_info_meta, "__subclasscheck__", None) + if ( + instancecheck is type.__instancecheck__ + and subclasscheck is type.__subclasscheck__ + ): + return False + + if issubclass(type_info, torch.Tensor) and ( + type_info_meta.__module__, + type_info_meta.__qualname__, + ) in { + ("torch.nn.parameter", "_ParameterMeta"), + ("torch.nn.parameter", "_BufferMeta"), + ("torch.distributed.fsdp._flat_param", "_FlatParameterMeta"), + }: + return False + + return ( + use_instancecheck + and instancecheck is not type.__instancecheck__ + and instancecheck is not abc.ABCMeta.__instancecheck__ + ) or ( + use_subclasscheck + and subclasscheck is not type.__subclasscheck__ + and subclasscheck is not abc.ABCMeta.__subclasscheck__ + ) + return False + + +class BuiltinVariable(BaseBuiltinVariable): + """ + A VariableTracker that represents a built-in value (functions and operators). + A lot of the code here assumes it will be a function object. + + The BuiltinVariable class wraps Python built-in functions (like len, isinstance, etc.) + and operators (like +, -, *, etc.) to enable symbolic execution during tracing. This allows + Dynamo to properly handle these operations when converting Python code to FX graphs while + maintaining correct semantics and enabling optimizations. + """ + + _SENTINEL = object() + _nonvar_fields = { + "fn", + *VariableTracker._nonvar_fields, + } + + # __name__ -> type_getsets[] type_get_name (getset). Unlike the type-attribute + # readers on BaseBuiltinVariable, BuiltinVariable exposes __name__ for any + # wrapped callable (not just types), so it never declines. + def _builtin_type_get_name( + self: "BuiltinVariable", tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + source = self.source and AttrSource(self.source, "__name__") + return VariableTracker.build(tx, self.fn.__name__, source) + + tp_getset = { + "__name__": GetSet(_builtin_type_get_name, None), + } + + @classmethod + def create_with_source(cls, value: Any, source: Source) -> "BuiltinVariable": + install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH)) + return cls(value, source=source) + + @staticmethod + @functools.cache + def _constant_fold_functions() -> set[Callable[..., Any]]: + fns: set[Callable[..., Any]] = { + abs, + all, + any, + ascii, + bin, + bool, + callable, + chr, + complex, + divmod, + float, + format, + getattr, + hex, + int, + len, + max, + min, + oct, + ord, + pow, + repr, + round, + str, + str.format, + sum, + type, + operator.abs, + operator.pos, + operator.neg, + operator.not_, + operator.truth, + operator.invert, + operator.pow, + operator.mul, + operator.matmul, + operator.floordiv, + operator.truediv, + operator.mod, + operator.add, + operator.sub, + operator.getitem, + operator.length_hint, + operator.lshift, + operator.rshift, + operator.and_, + operator.or_, + operator.xor, + operator.ipow, + operator.imul, + operator.imatmul, + operator.ifloordiv, + operator.itruediv, + operator.imod, + operator.iadd, + operator.isub, + operator.ilshift, + operator.irshift, + operator.iand, + operator.ixor, + operator.ior, + operator.index, + } + from .tensor import supported_comparison_ops + + fns.update(supported_comparison_ops.values()) + fns.update(x for x in math.__dict__.values() if isinstance(x, type(math.sqrt))) + return fns + + def can_constant_fold_through(self) -> bool: + return self.fn in self._constant_fold_functions() + + @staticmethod + @functools.cache + def _fx_graph_functions() -> set[Callable[..., Any]]: + fns = { + operator.abs, + operator.pos, + operator.neg, + operator.not_, + operator.invert, + operator.pow, + operator.mul, + operator.matmul, + operator.floordiv, + operator.truediv, + operator.mod, + operator.add, + operator.lt, + operator.gt, + operator.ge, + operator.le, + operator.ne, + operator.eq, + operator.sub, + operator.length_hint, + operator.lshift, + operator.rshift, + operator.and_, + operator.or_, + operator.xor, + operator.ipow, + operator.imul, + operator.imatmul, + operator.ifloordiv, + operator.itruediv, + operator.getitem, + operator.imod, + operator.iadd, + operator.isub, + operator.ilshift, + operator.irshift, + operator.iand, + operator.ixor, + operator.ior, + } + return fns # type: ignore[return-value] + + @staticmethod + @functools.cache + def _binops() -> dict[ + Callable[..., object], tuple[list[str], Callable[..., object]] + ]: + # function -> ([forward name, reverse name, in-place name], in-place op) + fns: dict[Callable[..., object], tuple[list[str], Callable[..., object]]] = { + # NB: The follow binary operators are not supported for now, since the + # corresponding magic methods aren't defined on SymInt / SymFloat: + # operator.matmul + # divmod + # operator.and_ + # operator.or_ + } + return fns + + @staticmethod + @functools.cache + def _binop_handlers() -> dict[ + Callable[..., object], + list[ + tuple[ + tuple[ + type[VariableTracker], + _TrackersType, + ], + _HandlerCallback, + ] + ], + ]: + # Multiple dispatch mechanism defining custom binop behavior for certain type + # combinations. Handlers are attempted in order, and will be used if the type checks + # match. They are expected to have the signature: + # fn(tx, arg0: VariableTracker, arg1: VariableTracker) -> VariableTracker + from .functions import BaseUserFunctionVariable + from .nn_module import NNModuleVariable + from .tensor import supported_const_comparison_ops + from .torch import BaseTorchVariable + + # Override table contains: op_fn -> [list of handlers] + op_handlers: dict[Any, list[Any]] = {} + for ( + op, + (magic_method_names, in_place_op), + ) in BuiltinVariable._binops().items(): + op_handlers[op] = [] + op_handlers[in_place_op] = [] + + forward_name, reverse_name, inplace_name = magic_method_names + + # User-defined args (highest precedence) + def user_defined_handler( + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + *, + forward_name: str = forward_name, + reverse_name: str = reverse_name, + ) -> VariableTracker: + # Manually handle reversing logic if needed (e.g. call __radd__) + + # TODO: If we expand this to handle tensor args, we need to manually + # handle cases like this: + # + # class A(int): + # def __radd__(self, other): + # print("woof") + # torch.randn(3) + A(3) + # + # In this example, A.__radd__() is not called -> nothing is printed, because + # Tensor.__add__ only does a subtype test against int, ignoring the subclass. + # To be fully correct, we should not call A.__radd__() here, and there may be + # other cases to reason about and add exceptions for. + if isinstance(a, UserDefinedVariable): + return a.call_method(tx, forward_name, [b], {}) + else: + return b.call_method(tx, reverse_name, [a], {}) + + op_handlers[op].append( + ((UserDefinedVariable, VariableTracker), user_defined_handler) + ) + op_handlers[op].append( + ((VariableTracker, UserDefinedVariable), user_defined_handler) + ) + + def user_defined_inplace_handler( + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + *, + forward_name: str = inplace_name, + ) -> VariableTracker: + return a.call_method(tx, forward_name, [b], {}) + + op_handlers[in_place_op].append( + ((UserDefinedVariable, VariableTracker), user_defined_inplace_handler) + ) + op_handlers[in_place_op].append( + ((VariableTracker, UserDefinedVariable), user_defined_inplace_handler) + ) + + # Dynamic shape args + def dynamic_handler( + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + *, + fn: Callable[..., Any] = op, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", fn, *proxy_args_kwargs([a, b], {}) + ), + ) + + op_handlers[op].append( + ((SymNodeVariable, VariableTracker), dynamic_handler) + ) + op_handlers[op].append( + ((VariableTracker, SymNodeVariable), dynamic_handler) + ) + + # NB: Prefer out-of-place op when calling in-place op to generate valid graph + op_handlers[in_place_op].append( + ((SymNodeVariable, VariableTracker), dynamic_handler) + ) + op_handlers[in_place_op].append( + ((VariableTracker, SymNodeVariable), dynamic_handler) + ) + + # Special cases - lower precedence but still prefer these over constant folding + + def create_cmp_op_handlers( + op: Callable[..., Any], + ) -> list[tuple[tuple[_TrackersType, _TrackersType], _HandlerCallback]]: + def compare_by_value( + tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker: + try: + return VariableTracker.build(tx, op(a.value, b.value)) # type: ignore[attr-defined] + except TypeError as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + + result: list[ + tuple[ + tuple[ + _TrackersType, + _TrackersType, + ], + _HandlerCallback, + ] + ] = [((ConstantVariable, ConstantVariable), compare_by_value)] + + if op in _OPERATOR_TO_DUNDER: + # For constants, speedup the comparison instead of going + # through generic_richcompare. Removing this line causes + # major regression for pr time benchmark - add_loop_eager. + result = [ + ((ConstantVariable, ConstantVariable), compare_by_value), + ] + + op_var = BuiltinVariable(op) + # Special handling of SymNode variable + result.extend( + [ + ( + (SymNodeVariable, VariableTracker), + op_var._comparison_with_symnode, + ), + ( + (VariableTracker, SymNodeVariable), + op_var._comparison_with_symnode, + ), + ] + ) + + # COMPARE_OP (a == b) dispatches through generic_richcompare, + # which implements do_richcompare via tp_richcompare_impl slots. + # See object_protocol.py for details. + dunder = _OPERATOR_TO_DUNDER[op] + + def handler( + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + ) -> VariableTracker: + return generic_richcompare(tx, a, b, dunder) + + result.append(((VariableTracker, VariableTracker), handler)) + return result + + result = [((ConstantVariable, ConstantVariable), compare_by_value)] + + if op in supported_const_comparison_ops.values() and op.__name__.startswith( + "is_" + ): + # Tensor is None, List is not None, etc + none_result = op(object(), None) + + def never( + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + ) -> VariableTracker: + return VariableTracker.build(tx, none_result) + + obj_op_none = never + none_op_obj = never + + types_that_are_never_none = ( + TensorVariable, + SymNodeVariable, + NNModuleVariable, + BaseListVariable, + UserDefinedVariable, + BaseUserFunctionVariable, + ConstDictVariable, + BaseTorchVariable, + ) + result.extend( + [ + ( + (types_that_are_never_none, ConstantVariable), + obj_op_none, + ), + ( + (ConstantVariable, types_that_are_never_none), + none_op_obj, + ), + ] + ) + + op_var = BuiltinVariable(op) + result.extend( + [ + ( + (TensorVariable, VariableTracker), + op_var._comparison_with_tensor, + ), + ( + (VariableTracker, TensorVariable), + op_var._comparison_with_tensor, + ), + ( + (SymNodeVariable, VariableTracker), + op_var._comparison_with_symnode, + ), + ( + (VariableTracker, SymNodeVariable), + op_var._comparison_with_symnode, + ), + ] + ) + + def handle_is( + tx: "InstructionTranslatorBase", + left: VariableTracker, + right: VariableTracker, + ) -> VariableTracker | None: + result = vt_identity_compare(left, right) + if result is None: + return None + is_same = result.as_python_constant() + return VariableTracker.build( + tx, is_same if op.__name__ == "is_" else not is_same + ) + + result.append(((VariableTracker, VariableTracker), handle_is)) # type: ignore[arg-type] + + return result + + for op in supported_comparison_ops.values(): + if not callable(op): + raise AssertionError(f"comparison op {op} is not callable") + if op in op_handlers: + raise AssertionError(f"duplicate handler for op {op}") + op_handlers[op] = create_cmp_op_handlers(op) + + return op_handlers + + @staticmethod + def _find_binop_handler( + op: Callable[..., Any], a_type: type[VariableTracker], b_type: type + ) -> list[_HandlerCallback] | None: + handlers = BuiltinVariable._binop_handlers().get(op) + if handlers is None: + return None + + matches = [] + for (type1, type2), handler in handlers: + if issubclass(a_type, type1) and issubclass(b_type, type2): + matches.append(handler) + return matches + + def can_insert_in_graph(self) -> bool: + return self.fn in self._fx_graph_functions() + + # Builtins that have been promoted to their own VT classes. Creating a + # BuiltinVariable for these is a bug; use the specialized class instead. + MUST_USE_SPECIALIZED: frozenset[Any] = frozenset( + {dict, getattr, hasattr, iter, list, setattr} + ) + + def __init__(self, fn: Any, **kwargs: Any) -> None: + if fn in self.MUST_USE_SPECIALIZED: + raise AssertionError( + f"Use the specialized VT class for {fn!r}, not BuiltinVariable. " + f"E.g. DictBuiltinVariable for dict." + ) + super().__init__(**kwargs) + self.fn = fn + + def __repr__(self) -> str: + if self.fn is None: + name = "None" + else: + name = self.fn.__name__ + + return f"{self.__class__.__name__}({name})" + + def as_python_constant(self) -> Any: + return self.fn + + def get_real_python_backed_value(self) -> Any: + return self.fn + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # BuiltinVariable wraps built-in types like list, tuple, dict. + # type(self.fn).__or__(self.fn, other_val) delegates to CPython's + # _Py_union_type_or for type unions (e.g. list | tuple). + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L6028-L6030 (type_as_number.nb_or = _Py_union_type_or) + # https://github.com/python/cpython/blob/3.13/Objects/unionobject.c#L162 (_Py_union_type_or) + if not isinstance(self.fn, type): + return VariableTracker.build(tx, NotImplemented) + try: + other_val = other.as_python_constant() + except NotImplementedError: + return VariableTracker.build(tx, NotImplemented) + # pyrefly: ignore[bad-argument-count] + result = type(self.fn).__or__(self.fn, other_val) + if result is NotImplemented: + return VariableTracker.build(tx, NotImplemented) + return VariableTracker.build(tx, result) + + def as_proxy(self) -> Any: + DTYPE = { + bool: torch.bool, + int: torch.int64, + float: torch.float64, + } + if self.fn in DTYPE: + return DTYPE[self.fn] + return super().as_proxy() + + def reconstruct(self, codegen: "PyCodegen") -> None: + name = self.fn.__name__ + if self.fn.__module__ != "builtins": + raise AssertionError(f"Expected builtins module, got {self.fn.__module__}") + if name in codegen.tx.f_globals: + raise AssertionError("shadowed global") + codegen.append_output(codegen.create_load_global(name, add=True)) + + def constant_args(self, *args: VariableTracker, **kwargs: VariableTracker) -> bool: + return check_constant_args(args, kwargs) + + def tensor_args(self, *args: VariableTracker) -> bool: + any_tensor = False + for arg in args: + if isinstance(arg, variables.GetAttrVariable): + return False + any_tensor = any_tensor or arg.is_tensor() + return any_tensor + + def tensor_args_type(self, arg_types: list[type]) -> bool: + any_tensor = False + for arg_type in arg_types: + if issubclass(arg_type, variables.GetAttrVariable): + return False + any_tensor = any_tensor or issubclass(arg_type, variables.TensorVariable) + return any_tensor + + def python_and_tensor_constant_only( + self, *args: VariableTracker, **kwargs: VariableTracker + ) -> bool: + tensor_args = [] + non_tensor_args = [] + for i in itertools.chain(args, kwargs.values()): + if i.is_tensor(): + tensor_args.append(i) + else: + non_tensor_args.append(i) + return all( + is_constant_source(t.source) if t.source is not None else False + for t in tensor_args + ) and self.constant_args(*non_tensor_args) + + @staticmethod + def unwrap_unspec_args_kwargs( + args: list[VariableTracker], kwargs: dict[str, VariableTracker] + ) -> tuple[list[Any], dict[str, Any]]: + return [x.as_python_constant() for x in args], { + k: v.as_python_constant() for k, v in kwargs.items() + } + + def has_constant_handler( + self, args: list[VariableTracker], kwargs: dict[str, VariableTracker] + ) -> bool: + return self.can_constant_fold_through() and check_unspec_or_constant_args( + args, kwargs + ) + + @staticmethod + def _make_handler( + fn: Callable[..., Any], arg_types: list[type], has_kwargs: bool + ) -> Callable[ + [ + "InstructionTranslatorBase", + list[VariableTracker], + dict[str, VariableTracker], + ], + VariableTracker | None, + ]: + from .lazy import ( + ComputedLazyConstantVariable, + LazyConstantVariable, + LazyVariableTracker, + ) + + obj = BuiltinVariable(fn) + handlers: list[_HandlerCallback] = [] + + lazy_constant_types = (LazyConstantVariable, ComputedLazyConstantVariable) + lazy_types = [t for t in arg_types if issubclass(t, LazyVariableTracker)] + if lazy_types: + if not all(issubclass(t, lazy_constant_types) for t in lazy_types): + # Realize non-constant lazy args and re-dispatch. Any + # lazy constant args are kept and handled on the + # second dispatch through the branch below. + return lambda tx, args, kwargs: obj.call_function( + tx, + [ + a.realize() + if isinstance(a, LazyVariableTracker) + and not isinstance(a, lazy_constant_types) + else a + for a in args + ], + kwargs, + ) + + # Only lazy constant types. Install type guards + # and resolve the dispatch type. If the resolved type is + # ConstantVariable (the common case), delegate to a handler + # built for ConstantVariable. Otherwise (e.g. specialize_int= + # False turned the int into a SymNodeVariable), realize and + # re-dispatch so the correct handler is used. + inner_handler = BuiltinVariable._make_handler( + fn, + [ + ConstantVariable if issubclass(t, lazy_constant_types) else t + for t in arg_types + ], + has_kwargs, + ) + + def lazy_constant_handler( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + if not kwargs: + result = _try_computed_lazy_constant(fn, args) + if result is not None: + return result + for a in args: + if isinstance(a, lazy_constant_types): + if a.get_handler_type_for_dispatch() is not ConstantVariable: + return obj.call_function( + tx, + [ + v.realize() + if isinstance(v, lazy_constant_types) + else v + for v in args + ], + kwargs, + ) + return inner_handler(tx, args, kwargs) + + return lazy_constant_handler + + if inspect.isclass(fn) and ( + issubclass(fn, BaseException) + # GeneratorExit doesn't inherit from Exception + # >>> issubclass(GeneratorExit, Exception) + # False + or fn is GeneratorExit + ): + + def create_exception_class_object( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if fn is AssertionError and not all( + x.is_python_constant() and isinstance(x.as_python_constant(), str) + for x in args + ): + unimplemented( + gb_type="assert with non-string message", + context=str(args), + explanation="Dynamo only supports asserts with string messages", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if fn is StopIteration: + return variables.StopIterationVariable(fn, args, kwargs) + elif fn is AttributeError: + return variables.AttributeErrorVariable(fn, args, kwargs) + elif fn is NameError: + return variables.NameErrorVariable(fn, args, kwargs) + return variables.ExceptionVariable(fn, args, kwargs) + + return create_exception_class_object + + if obj.can_insert_in_graph() and not ( + fn is operator.getitem + and ( + len(arg_types) != 2 + or not issubclass(arg_types[0], variables.TensorVariable) + ) + ): + if obj.tensor_args_type(arg_types): + return obj._handle_insert_op_in_graph + elif has_kwargs: + # need runtime check for kwargs + handlers.append(obj._handle_insert_op_in_graph) + + # Handle binary ops (e.g. __add__ / __radd__, __iadd__, etc.) + # NB: Tensor args are handled above and not here + if len(arg_types) == 2 and not has_kwargs: + # Try to find a handler for the arg types; otherwise, fall through to constant handler + binop_handlers = BuiltinVariable._find_binop_handler(fn, *arg_types) + if not binop_handlers: + pass + elif len(binop_handlers) == 1: + (binop_handler,) = binop_handlers + handlers.append(lambda tx, args, _: binop_handler(tx, *args)) + else: + + def call_binop_handlers( + tx: "InstructionTranslatorBase", args: Any, _: Any + ) -> Any: + # pyrefly: ignore [not-iterable] + for fn in binop_handlers: + rv = fn(tx, *args) + if rv: + return rv + return None + + handlers.append(call_binop_handlers) + + self_handler = getattr(obj, f"call_{fn.__name__}", None) + if self_handler: + + def call_self_handler( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + try: + # pyrefly: ignore [not-callable] + return self_handler(tx, *args, **kwargs) + except TypeError: + # Check if binding is bad. inspect signature bind is expensive. + # So check only when handler call fails. + try: + # pyrefly: ignore [bad-argument-type] + inspect.signature(self_handler).bind(tx, *args, **kwargs) + except TypeError as e: + has_constant_handler = obj.has_constant_handler(args, kwargs) + if not has_constant_handler: + log.warning( + "incorrect arg count %s %s and no constant handler", + self_handler, + e, + ) + unimplemented( + gb_type="invalid call to builtin op handler", + context=f"invalid args to {self_handler}: {args} {kwargs}", + explanation=f"Encountered TypeError when trying to handle op {fn.__name__}", + hints=[*graph_break_hints.DIFFICULT], + ) + else: + raise + except Unsupported as exc: + has_constant_handler = obj.has_constant_handler(args, kwargs) + if not has_constant_handler: + raise + # Actually, we will handle this just fine + exc.remove_from_stats() + return None + + handlers.append(call_self_handler) + + if obj.can_constant_fold_through(): + if ( + all(issubclass(x, ConstantVariable) for x in arg_types) + and not has_kwargs + ): + + def constant_fold_handler( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + # fast path + try: + res = fn( + *[x.as_python_constant() for x in args], + ) + except Exception as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + except AsPythonConstantNotImplementedError as exc: + unimplemented( + gb_type="constant fold exception", + context=f"attempted to run function {fn} with arguments {args}", + explanation="Encountered exception when attempting to constant fold.", + hints=[*graph_break_hints.DYNAMO_BUG], + from_exc=exc, + ) + return VariableTracker.build(tx, res) + + else: + + def constant_fold_handler( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + # path with a runtime check + if check_unspec_or_constant_args(args, kwargs): + try: + res = fn( + *[x.as_python_constant() for x in args], + **{ + k: v.as_python_constant() for k, v in kwargs.items() + }, + ) + except AsPythonConstantNotImplementedError as exc: + unimplemented( + gb_type="constant fold exception", + context=f"attempted to run function {fn} with arguments {args}", + explanation="Encountered exception when attempting to constant fold.", + hints=[*graph_break_hints.DYNAMO_BUG], + from_exc=exc, + ) + except Exception as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + return VariableTracker.build(tx, res) + return None + + handlers.append(constant_fold_handler) + + def call_unimplemented(args: list[VariableTracker]) -> None: + real_arg_types = [arg.python_type_name() for arg in args] + unimplemented( + gb_type="Failed to trace builtin operator", + context=f"builtin {fn.__name__} {arg_types} {has_kwargs}", + explanation=f"Dynamo does not know how to trace builtin operator `{fn.__name__}` " + f"with argument types {real_arg_types} (has_kwargs {has_kwargs})", + hints=[ + f"Avoid calling builtin `{fn.__name__}` with argument types {real_arg_types}. " + f"Consider using an equivalent alternative function/method to `{fn.__name__}`.", + "If you are attempting to call a logging function (e.g. `print`), " + "you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.", + "Please report an issue to PyTorch.", + ], + ) + + if len(handlers) == 0: + return lambda tx, args, kwargs: call_unimplemented(args) + elif len(handlers) == 1: + (handler,) = handlers + + def builtin_dispatch( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + rv = handler(tx, args, kwargs) + if rv: + return rv + call_unimplemented(args) + return rv + + else: + + def builtin_dispatch( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + rv = None + for fn in handlers: + rv = fn(tx, args, kwargs) + if rv: + return rv + call_unimplemented(args) + return rv + + return builtin_dispatch + + @staticmethod + def _constant_eval_numeric_expr(node: ast.AST) -> bool: + allowed_nodes = ( + ast.Expression, + ast.Constant, + ast.UnaryOp, + ast.BinOp, + ast.UAdd, + ast.USub, + ast.Invert, + ast.Add, + ast.Sub, + ast.Mult, + ast.Div, + ast.FloorDiv, + ast.Mod, + ast.BitOr, + ast.BitXor, + ast.BitAnd, + ) + return all( + isinstance(child, allowed_nodes) + and ( + not isinstance(child, ast.Constant) + or isinstance(child.value, (bool, int, float, complex)) + ) + for child in ast.walk(node) + ) + + @staticmethod + def _constant_eval_result( + tx: "InstructionTranslatorBase", tree: ast.Expression, filename: str + ) -> VariableTracker | None: + if any(isinstance(child, ast.Call) for child in ast.walk(tree)): + return None + ast.fix_missing_locations(tree) + try: + result = ast.literal_eval(tree) + except ValueError: + if not BuiltinVariable._constant_eval_numeric_expr(tree): + return None + try: + result = eval( + compile(tree, filename, "eval"), + {"__builtins__": {}}, + {}, + ) + except Exception as exc: + raise_observed_exception(type(exc), tx, args=list(exc.args)) + return VariableTracker.build(tx, result) + + def call_eval( + self, + tx: "InstructionTranslatorBase", + source: VariableTracker, + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if args or kwargs: + return None + if not source.is_python_constant(): + return None + source_str = source.as_python_constant() + if not isinstance(source_str, str): + return None + + try: + tree = ast.parse(source_str.strip(), mode="eval") + except SyntaxError as exc: + raise_observed_exception(SyntaxError, tx, args=[exc.msg]) + + return self._constant_eval_result(tx, tree, "") + + def call_vars( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "vars() takes no keyword arguments") + if len(args) == 0: + return self._call_frame_locals_snapshot(tx) + if len(args) != 1: + raise_type_error(tx, f"vars expected at most 1 argument, got {len(args)}") + # vars(obj) is obj.__dict__ if __dict__ is present else TypeError + try: + return args[0].tp_getattro_impl(tx, "__dict__") + except ObservedAttributeError: + raise_observed_exception(TypeError, tx) + + def call_locals( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + if len(args) != 0: + raise_observed_exception(TypeError, tx) + return self._call_frame_locals_snapshot(tx) + + @staticmethod + def _call_frame_locals_snapshot(tx: "InstructionTranslatorBase") -> VariableTracker: + from .builder import VariableBuilder + + frame_local_names = set(tx.f_code.co_varnames) | set(tx.cell_and_freevars()) + cell_and_freevars = set(tx.cell_and_freevars()) + frame_locals = {} + # symbolic_cellvars registers all of the frame's cells. Cells are listed first so that a colliding fast local of + # the same name shadows the cell, matching CPython (except for 3.12, which is backwards): the two share a name + # but not a localsplus slot, and the fast slot wins while it holds a value (an empty one is skipped below, + # leaving the cell contents visible). + if sys.version_info[:2] == (3, 12): + its = (tx.symbolic_locals.items(), tx.symbolic_cellvars.items()) + else: + its = (tx.symbolic_cellvars.items(), tx.symbolic_locals.items()) + + for name, value in itertools.chain(*its): + if name not in frame_local_names: + continue + # Match on CellVariable, not name: a colliding fast local shares a + # cell's name but is not itself a cell. + if type.__instancecheck__(CellVariable, value): + value = tx.output.side_effects.load_cell(value) + if type.__instancecheck__(NullVariable, value) or isinstance( + value, variables.DeletedVariable + ): + continue + frame_locals[ConstantVariable.create(name)] = value + # Include locals pruned from symbolic_locals by the unused-input optimisation. + # locals()/vars() observes the entire namespace, so build VTs (installing + # guards) for any pruned entry that still has a runtime value. + for name in frame_local_names: + if name in frame_locals or name in cell_and_freevars: + continue + if name not in tx.f_locals: + continue + vt = VariableBuilder(tx, LocalSource(name))(tx.f_locals[name]) + frame_locals[ConstantVariable.create(name)] = vt + return ConstDictVariable( + frame_locals, + mutation_type=ValueMutationNew(), + ) + + def _handle_insert_op_in_graph( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + from .builder import wrap_fx_proxy, wrap_fx_proxy_cls + + if kwargs and not self.tensor_args(*args, *kwargs.values()): + return None + + # insert handling for torch function here + from .builder import SourcelessBuilder + from .torch_function import can_dispatch_torch_function, dispatch_torch_function + + global BUILTIN_TO_TENSOR_RFN_MAP, BUILTIN_TO_TENSOR_FN_MAP + if can_dispatch_torch_function(tx, args, kwargs): + # Only remap the fn to tensor methods if we aren't exporting + # export serde does not handle method descriptors today + if not tx.export: + # Ensure the builtin maps are populated before accessing them + populate_builtin_to_tensor_fn_map() + # Use sourceless builder, we built the map ourselves + if not args[0].is_tensor(): + if self.fn in BUILTIN_TO_TENSOR_RFN_MAP: + func = BUILTIN_TO_TENSOR_RFN_MAP[self.fn] + else: + func = BUILTIN_TO_TENSOR_FN_MAP[self.fn] + + tmp = args[0] + # swap args and call reverse version of func + args[0] = args[1] # type: ignore[index] + args[1] = tmp # type: ignore[index] + else: + func = BUILTIN_TO_TENSOR_FN_MAP[self.fn] + else: + func = self.fn + + fn_var = SourcelessBuilder.create(tx, func) + + return dispatch_torch_function(tx, fn_var, args, kwargs) + + fn = self.fn + try: + # Constant fold for constant tensor and python constants + if self.python_and_tensor_constant_only(*args, **kwargs): + from ..bytecode_transformation import unique_id + from .functions import invoke_and_store_as_constant + + return invoke_and_store_as_constant( + tx, fn, unique_id(fn.__name__), args, kwargs + ) + + if fn in IN_PLACE_DESUGARING_MAP and isinstance( + args[0], variables.ConstantVariable + ): + # In-place operators like += usually mustate tensor + # values, but in the edge case of immutable values they + # re-bind the variable. + # + # The easiest way to keep the graph consistent in this + # scenario is to de-sugar eagerly. + fn = IN_PLACE_DESUGARING_MAP[fn] + args = [args[0], args[1]] # type: ignore[assignment] + + if fn is operator.getitem: + if kwargs: + raise_type_error( + tx, "_operator.getitem() takes no keyword arguments" + ) + if len(args) != 2: + raise_type_error( + tx, f"getitem expected 2 arguments, got {len(args)}" + ) + if isinstance(args[1], SymNodeVariable): + # Standard indexing will force specialization due to + # __index__. Rewrite as a regular torch op which will + # trace fine + fn = torch.select + args = [ + args[0], + variables.VariableTracker.build(tx, 0), + args[1], + ] # type: ignore[assignment] + + # Interaction between ndarray and tensors: + # We prefer the tensor op whenever there are tensors involved + # NB: Use exact type check here - NumpyNdarrayVariable is a TensorVariable + # subclass but should NOT trigger the tensor path + if check_numpy_ndarray_args(args, kwargs) and not any( + type(arg) is TensorVariable for arg in args + ): + proxy = tx.output.create_proxy( + "call_function", + numpy_operator_wrapper(fn), + *proxy_args_kwargs(args, kwargs), + ) + + return wrap_fx_proxy_cls(variables.NumpyNdarrayVariable, tx, proxy) + + if ( + fn in _OPERATOR_TO_DUNDER + and len(args) == 2 + and any( + not isinstance(a, (variables.TensorVariable, SymNodeVariable)) + for a in args + ) + ): + return generic_richcompare( + tx, args[0], args[1], _OPERATOR_TO_DUNDER[fn] + ) + + proxy = tx.output.create_proxy( + "call_function", + fn, + *proxy_args_kwargs(args, kwargs), + ) + if any(isinstance(arg, FakeItemVariable) for arg in args): + return wrap_fx_proxy_cls( + FakeItemVariable, + tx, + proxy, + ) + elif check_unspec_python_args(args, kwargs): + _args, _kwargs = self.unwrap_unspec_args_kwargs(args, kwargs) + raw_value = fn(*_args, **_kwargs) + + need_unwrap = any( + x.need_unwrap + for x in itertools.chain(args, kwargs.values()) + if isinstance(x, variables.UnspecializedPythonVariable) + ) + + return wrap_fx_proxy_cls( + UnspecializedPythonVariable, + tx, + proxy, + raw_value=raw_value, + need_unwrap=need_unwrap, + ) + elif all(isinstance(x, SymNodeVariable) for x in args): + return SymNodeVariable.create(tx, proxy, None) + else: + # Work around for vision_maskrcnn due to precision difference + # specialize the dividend when float divide by tensor + if fn is operator.truediv and isinstance( + args[0], variables.UnspecializedPythonVariable + ): + args = list(args) + args[0] = args[0].as_python_constant() + return wrap_fx_proxy(tx, proxy) + + except NotImplementedError: + unimplemented( + gb_type="unimplemented builtin op on tensor arguments", + context=f"partial tensor op: {self} {args} {kwargs}", + explanation=f"Dynamo does not know how to trace builtin operator {self.fn} with tensor arguments", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + call_function_handler_cache: dict[ + tuple[object, ...], + Callable[ + [ + "InstructionTranslatorBase", + list[VariableTracker], + dict[str, VariableTracker], + ], + VariableTracker, + ], + ] = {} + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.fn is object and not args and not kwargs: + # object() -> a fresh opaque instance, wrapped as ObjectVariable to + # match how SourcelessBuilder wraps bare `object` instances. Falling + # through to the constant handler cannot build a VT from object(). + from .builder import SourcelessBuilder + + return SourcelessBuilder.create(tx, object()) + + key: tuple[object, ...] + if kwargs: + kwargs = {k: v.realize() for k, v in kwargs.items()} + key = (self.fn, *(type(x) for x in args), True) + else: + key = (self.fn, *(type(x) for x in args)) + + handler = self.call_function_handler_cache.get(key) + if not handler: + self.call_function_handler_cache[key] = handler = self._make_handler( # type: ignore[assignment] + self.fn, [type(x) for x in args], bool(kwargs) + ) + if handler is None: + raise AssertionError( + f"No handler found for {self.fn} with args {[type(x) for x in args]}" + ) + return handler(tx, args, kwargs) # type: ignore[return-value] + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.fn is object and name == "__setattr__": + if len(args) != 3: + raise AssertionError( + f"object.__setattr__ expects 3 args, got {len(args)}" + ) + if len(kwargs) != 0: + raise AssertionError( + f"object.__setattr__ expects no kwargs, got {len(kwargs)}" + ) + obj, name_var, val = args + obj = obj.realize() + if ( + isinstance(obj, UserDefinedObjectVariable) + and tx.output.side_effects.is_attribute_mutation(obj) + and name_var.is_python_constant() + ): + return obj.method_setattr_standard(tx, name_var, val) + + if name == "__new__": + # Supported __new__ methods + if self.fn is object and len(args) == 1: + if len(kwargs) != 0: + raise AssertionError( + f"object.__new__ expects no kwargs, got {len(kwargs)}" + ) + return tx.output.side_effects.track_new_user_defined_object( + self, + args[0], + args[1:], + tx=tx, + ) + + if self.fn is tuple and len(args) == 2 and not kwargs: + if isinstance(args[0], BuiltinVariable) and args[0].fn is tuple: + init_args = unpack_iterable(tx, args[1]) + return variables.TupleVariable( + init_args, mutation_type=ValueMutationNew() + ) + + return tx.output.side_effects.track_new_user_defined_object( + self, + args[0], + args[1:], + tx=tx, + ) + + if name in _BUILTIN_CONSTANT_FOLDABLE_METHODS.get(self.fn, ()): + if all(a.is_python_constant() for a in args) and all( + v.is_python_constant() for v in kwargs.values() + ): + try: + fn = getattr(self.fn, name) + res = fn( + *(a.as_python_constant() for a in args), + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + return VariableTracker.build(tx, res) + except Exception as e: + raise_observed_exception( + type(e), + tx, + args=list(e.args), + ) + + if self.fn is object and name == "__init__": + # object.__init__ is a no-op + return variables.ConstantVariable.create(None) + + if self.fn in (set, frozenset, list, tuple): + if isinstance(args[0], variables.UserDefinedObjectVariable): + if args[0]._base_vt is None: + raise AssertionError( + "UserDefinedObjectVariable._base_vt must not be None" + ) + return args[0]._base_vt.call_method(tx, name, args[1:], kwargs) + else: + return args[0].call_method(tx, name, args[1:], kwargs) + + if ( + name in ("__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__") + and len(args) == 2 + and not kwargs + and isinstance(self.fn, type) + and args[0].is_python_constant() + and args[1].is_python_constant() + ): + # Unbound rich-comparison dunder, e.g. complex.__eq__(1+1j, 2). + # Invoke only the left type's slot on the constants, mirroring + # CPython (returns NotImplemented rather than falling back to the + # reflected operation when the operands are incompatible). + lval = args[0].as_python_constant() + if isinstance(lval, self.fn): + return ConstantVariable.create( + getattr(self.fn, name)(lval, args[1].as_python_constant()) + ) + + if self.fn is str and len(args) >= 1: + resolved_fn = getattr(self.fn, name, None) + if resolved_fn in str_methods: + # Only delegate to ConstantVariable, not other types that happen to be constants + if isinstance(args[0], ConstantVariable): + return args[0].call_method(tx, name, args[1:], kwargs) + + if self.fn is float and len(args) >= 1: + # Only delegate to ConstantVariable, not other types that happen to be constants + if isinstance(args[0], ConstantVariable): + return VariableTracker.build( + tx, getattr(float, name)(args[0].as_python_constant()) + ) + + if name == "__len__" and len(args) == 1 and not kwargs: + # type.__len__(instance) → len(instance) + # e.g. list.__len__(my_list) → len(my_list) + return generic_size(tx, args[0]) + + if name == "__str__" and len(args) == 1 and not kwargs: + return super().call_method(tx, name, args, kwargs) + + if name == "__repr__" and len(args) == 1 and not kwargs: + return super().call_method(tx, name, args, kwargs) + + if name == "__iter__" and len(args) == 1 and not kwargs: + # type.__iter__(instance) → iter(instance) + # e.g., tuple.__iter__(my_tuple) → iter(my_tuple) + # For builtin types called on user-defined subclasses, use the base iterator + return generic_getiter(tx, args[0]) + + if name == "__neg__" and len(args) == 1 and not kwargs: + # type.__neg__(instance) → neg(instance) + # e.g., int.__neg__(4) → neg(4) + return pynumber_negative(tx, args[0]) + + if name == "__pos__" and len(args) == 1 and not kwargs: + # type.__pos__(instance) → pos(instance) + # e.g., int.__pos__(4) → pos(4) + return pynumber_positive(tx, args[0]) + + if name == "__abs__" and len(args) == 1 and not kwargs: + # type.__abs__(instance) → abs(instance) + # e.g., int.__abs__(-4) → abs(-4) + return pynumber_absolute(tx, args[0]) + + if name == "__invert__" and len(args) == 1 and not kwargs: + # type.__invert__(instance) → ~instance + # e.g., int.__invert__(4) → ~4 + return pynumber_invert(tx, args[0]) + + if name == "__hash__" and len(args) == 1 and not kwargs: + arg = args[0] + if ( + isinstance(arg, variables.UserDefinedConstantVariable) + and arg._base_vt is not None + ): + return generic_hash(tx, arg._base_vt) + + return super().call_method(tx, name, args, kwargs) + + def call_int( + self, + tx: "InstructionTranslatorBase", + arg: VariableTracker, + base: VariableTracker | None = None, + ) -> VariableTracker | None: + if base is None: + return pynumber_int(tx, arg) + return pylong_from_base(tx, arg, base) + + def call_float( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return pynumber_float(tx, arg) + + def call_bin( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return pynumber_tobase(tx, arg, 2) + + def call_oct( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return pynumber_tobase(tx, arg, 8) + + def call_hex( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return pynumber_tobase(tx, arg, 16) + + def call_bool( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + # Emulate PyBool_Type.tp_vectorcall which boils down to PyObject_IsTrue. + return generic_is_true(tx, arg) + + def call_hash( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + return generic_hash(tx, arg) + + def call_repr( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return generic_repr(tx, arg) + + def call_str( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return generic_str(tx, arg) + + def call___build_class__(self, tx, *args, **kwargs): + def fail(args, kwargs) -> NoReturn: + unimplemented( + gb_type="Invalid call to __build_class__", + context=f"Non-constant args to __build_class__: {args} {kwargs}", + explanation="Cannot trace class definition: the class body function is unsupported or the base class argument are not compile-time constants", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if not torch._dynamo.config.enable_trace_load_build_class: + fail(args, kwargs) + + try: + if isinstance(args[0], variables.NestedUserFunctionVariable): + fn = args[0].get_function(allow_sourced_cells=True) + else: + fn = args[0].get_function() + except NotImplementedError: + fail(args, kwargs) + + if check_constant_args(args[1:], kwargs): + r = builtins.__build_class__( + fn, # type: ignore[possibly-undefined] + *[a.as_python_constant() for a in args[1:]], + ) + return VariableTracker.build(tx, r) + else: + fail(args, kwargs) + + def _call_min_max( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + key: VariableTracker | None = None, + default: VariableTracker | None = None, + ) -> VariableTracker | None: + name = self.fn.__name__ + if len(args) == 0: + raise_type_error(tx, f"{name} expected at least 1 argument, got 0") + + # `default` is keyword-only and only valid with a single iterable arg. + positional = len(args) > 1 + if positional and default is not None: + raise_type_error( + tx, + f"Cannot specify a default for {name}() with multiple positional arguments", + ) + + if key is not None and key.is_constant_none(): + key = None + + items = list(args) if positional else unpack_iterable(tx, args[0]) + + if len(items) == 0: + if default is not None: + return default + raise_value_error(tx, f"{name}() iterable argument is empty") + + if key is None: + return self._call_min_max_seq(tx, items) + return self._call_min_max_seq_with_key(tx, items, key) + + def _call_min_max_seq( + self, tx: "InstructionTranslatorBase", items: list[VariableTracker] + ) -> VariableTracker: + if len(items) <= 0: + raise AssertionError("_call_min_max_seq requires at least one item") + if len(items) == 1: + return items[0] + + return functools.reduce(functools.partial(self._call_min_max_binary, tx), items) # type: ignore[arg-type,return-value] + + def _call_min_max_seq_with_key( + self, + tx: "InstructionTranslatorBase", + items: list[VariableTracker], + key: VariableTracker, + ) -> VariableTracker: + # Mirror CPython builtin_min_max: compare on key(item) but return the + # original element, keeping the first extremal element on ties (only + # replace on a strict comparison). Like list.sort, comparisons are done + # through Dynamo and must fold to a compile-time constant, so Tensor and + # SymInt keys graph break. + keyvals = [key.call_function(tx, [item], {}) for item in items] + best_item, best_key = items[0], keyvals[0] + for item, keyval in zip(items[1:], keyvals[1:]): + left, right = (best_key, keyval) if self.fn is max else (keyval, best_key) + cmp = BuiltinVariable(operator.lt).call_function(tx, [left, right], {}) + if not cmp.is_python_constant(): + unimplemented( + gb_type="min/max with non-constant key", + context=str(keyval), + explanation=( + f"Cannot compute {self.fn.__name__}() whose key comparison is " + f"not a compile-time constant. Key type: {keyval.python_type()}. " + f"Most notably, Tensor or SymInt keys are unsupported, but ints work." + ), + hints=[ + "Use something else as the key.", + *graph_break_hints.SUPPORTABLE, + ], + ) + if cmp.as_python_constant(): + best_item, best_key = item, keyval + return best_item + + def _call_min_max_binary( + self, + tx: "InstructionTranslatorBase", + a: VariableTracker | None, + b: VariableTracker | None, + ) -> VariableTracker | None: + if a is None or b is None: + # a or b could be none if we reduce and _call_min_max_binary failed + # to return something + return None + if self.tensor_args(a, b): + if not a.is_tensor(): + a, b = b, a + if not a.is_tensor(): + raise AssertionError( + "Expected at least one tensor argument for min/max" + ) + + # result of an item call is a scalar convert to a tensor + if isinstance(a, FakeItemVariable): + a = variables.TorchInGraphFunctionVariable(torch.tensor).call_function( + tx, [a], {} + ) + + # Dynamic input does not get resolved, rather, gets stored as call_function + if isinstance(a, SymNodeVariable) or isinstance(b, SymNodeVariable): + from .builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + type(a), + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.fn, + *proxy_args_kwargs([a, b], {}), + ), + ) + + # convert min/max to torch ops + if b.is_python_constant(): + fn: VariableTracker + if isinstance(a, variables.NumpyNdarrayVariable): + import numpy as np + + fn = variables.NumpyVariable(np.clip) + else: + fn = variables.TorchInGraphFunctionVariable(torch.clamp) + kwargs = {"min": b} if (self.fn is max) else {"max": b} + result = fn.call_function(tx, [a], kwargs) + else: + if isinstance(a, variables.NumpyNdarrayVariable): + import numpy as np + + np_fn = {max: np.maximum, min: np.minimum}[self.fn] + fn = variables.NumpyVariable(np_fn) + else: + torch_fn = {max: torch.maximum, min: torch.minimum}[self.fn] + fn = variables.TorchInGraphFunctionVariable(torch_fn) + result = fn.call_function(tx, [a, b], {}) + + # return unspec if both a, b are unspec or const + if all( + isinstance( + i, + ( + variables.UnspecializedPythonVariable, + variables.ConstantVariable, + ), + ) + for i in [a, b] + ): + if any(isinstance(val, FakeItemVariable) for val in [a, b]): + # type: ignore[arg-type] + return variables.FakeItemVariable.from_tensor_variable(result) + + if b.is_python_constant(): + raw_b = b.as_python_constant() + else: + raw_b = b.raw_value # type: ignore[attr-defined] + if self.fn is max: + raw_res = max(a.raw_value, raw_b) # type: ignore[attr-defined] + else: + raw_res = min(a.raw_value, raw_b) # type: ignore[attr-defined] + + need_unwrap = any( + x.need_unwrap + for x in [a, b] + if isinstance(x, variables.UnspecializedPythonVariable) + ) + return variables.UnspecializedPythonVariable.from_tensor_variable( + result, # type: ignore[arg-type] + raw_res, + need_unwrap, + ) + # otherwise return tensor + else: + return result + elif isinstance(a, SymNodeVariable) or isinstance(b, SymNodeVariable): + py_fn = torch.sym_max if self.fn is max else torch.sym_min + proxy = tx.output.create_proxy( + "call_function", py_fn, *proxy_args_kwargs([a, b], {}) + ) + return SymNodeVariable.create(tx, proxy, None) + elif isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable): + value = self.fn( + a.as_python_constant(), + b.as_python_constant(), + ) + return VariableTracker.build(tx, value) + return None + + call_min = _call_min_max + call_max = _call_min_max + + def call_abs( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + return pynumber_absolute(tx, arg) + + def call_pos( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + return pynumber_positive(tx, arg) + + def call_index( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + # Specialize SymNodeVariable to a constant first, matching CPython's + # PyNumber_Index which forces a concrete int. + return pynumber_index(tx, arg) + + def call_round( + self, + tx: "InstructionTranslatorBase", + arg: VariableTracker, + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + from .builder import SourcelessBuilder + + # Call arg.__round__() + round_method = SourcelessBuilder.create(tx, getattr).call_function( + tx, [arg, VariableTracker.build(tx, "__round__")], {} + ) + return round_method.call_function(tx, list(args), kwargs) + + def call_range( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "range() takes no keyword arguments") + if len(args) == 0: + raise_type_error(tx, "range expected at least 1 argument, got 0") + if len(args) > 3: + raise_type_error(tx, f"range expected at most 3 arguments, got {len(args)}") + args = tuple(pynumber_index(tx, arg) for arg in args) + return variables.RangeVariable(list(args)) + + def _dynamic_args(self, *args: VariableTracker, **kwargs: VariableTracker) -> bool: + return any(isinstance(x, SymNodeVariable) for x in args) or any( + isinstance(x, SymNodeVariable) for x in kwargs.values() + ) + + def call_slice( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + if not 1 <= len(args) < 4: + raise_type_error(tx, f"slice expected at least 1 argument, got {len(args)}") + return variables.SliceVariable(list(args), tx) + + def _dyn_proxy( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", self.fn, *proxy_args_kwargs(args, kwargs) + ), + ) + + def call_tuple( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + # ref: https://github.com/python/cpython/blob/main/Objects/abstract.c#L2004-L2078 + if kwargs: + raise_type_error( + tx, + f"{self.fn.__name__}() takes no keyword arguments", + ) + if len(args) == 0: + return TupleVariable([], mutation_type=ValueMutationNew()) + elif len(args) > 1: + raise_type_error( + tx, + f"{self.fn.__name__} expected at most 1 argument, got {len(args)}", + ) + + obj = args[0] + if isinstance(obj, TupleVariable) and obj.python_type() is tuple: + return obj + + items = unpack_iterable(tx, args[0]) + return TupleVariable(items, mutation_type=ValueMutationNew()) + + def call_callable( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + # PyCallable_Check: callable(x) is type(x)->tp_call != NULL. Dispatch on + # the arg's Python type slot rather than enumerating callable VTs. + # callable() is the only handler for this builtin, so always return a + # result (or graph break via maybe_get_python_type) -- never None, which + # would signal "try another handler" that does not exist. + return variables.ConstantVariable.create( + pycallable_check(maybe_get_python_type(arg)) + ) + + def call_cast( + self, _: Any, *args: VariableTracker, **kwargs: VariableTracker + ) -> VariableTracker | None: + if len(args) == 2: + return args[1] + + unimplemented( + gb_type="bad args to builtin cast()", + context=f"got args {args} {kwargs}", + explanation="Dynamo expects exactly 2 args to builtin cast().", + hints=["Ensure your call to cast() has exactly 2 arguments."], + ) + + def call_dir( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + if isinstance(arg, variables.UserDefinedClassVariable): + return VariableTracker.build(tx, dir(arg.value)) + if isinstance(arg, BuiltinVariable): + return VariableTracker.build(tx, dir(arg.fn)) + # Enable specialized VTs for constants to work with dir() + if arg.is_python_constant(): + return VariableTracker.build(tx, dir(arg.as_python_constant())) + return None + + def call_set( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/main/Objects/setobject.c#L2708-L2735 + # CPython set_init rejects keywords before unpacking positional args, so + # set(a=1) and set().__init__(a=1) both raise regardless of arg count. + if kwargs: + raise_type_error( + tx, + "set() takes no keyword arguments", + ) + if len(args) == 0: + return variables.SetVariable(set(), mutation_type=ValueMutationNew()) + elif len(args) > 1: + raise_type_error( + tx, + f"set expected at most 1 argument, got {len(args)}", + ) + + s = SetVariable([], mutation_type=ValueMutationNew()) + s.call_method(tx, "update", [args[0]], kwargs) + return s + + def call_frozenset( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error( + tx, + "frozenset() takes no keyword arguments", + ) + if len(args) == 0: + return variables.FrozensetVariable(set(), mutation_type=ValueMutationNew()) + elif len(args) > 1: + raise_type_error( + tx, + f"frozenset expected at most 1 argument, got {len(args)}", + ) + + if istype(args[0], variables.FrozensetVariable): + # CPython: frozenset(existing_frozenset) returns the same object. + return args[0] + + # Reuse existing HashableTracker keys from a set/frozenset/dict operand + # instead of re-hashing, mirroring CPython's set_update_internal fast + # path (do-not-rehash-dict-keys). + if isinstance(args[0], (variables.SetVariable, variables.ConstDictVariable)): + items = list(args[0].items.keys()) + else: + items = unpack_iterable(tx, args[0]) + fs = FrozensetVariable(items, mutation_type=ValueMutationNew()) + return fs + + def call_zip( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Python/bltinmodule.c#L2822-L2887 + if kwargs: + if not (len(kwargs) == 1 and "strict" in kwargs): + raise_args_mismatch( + tx, + "zip", + "1 kwargs (`strict`)", + f"{len(kwargs)} kwargs", + ) + strict = kwargs.pop("strict", ConstantVariable.create(False)) + items = [] + for arg in args: + items.append(generic_getiter(tx, arg)) + iter_args = TupleVariable(items, mutation_type=ValueMutationNew()) + return variables.ZipVariable( + iter_args, + strict=strict.as_python_constant(), + mutation_type=ValueMutationNew(), + ) + + def call_len( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "len() takes no keyword arguments") + if len(args) != 1: + raise_type_error( + tx, f"len() takes exactly one argument ({len(args)} given)" + ) + return generic_size(tx, args[0]) + + def call_length_hint( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # ref: PyObject_LengthHint (Objects/abstract.c): try __len__, then + # __length_hint__, falling back to the supplied default for either a + # missing slot or a TypeError raised by the slot. + if kwargs or not (1 <= len(args) <= 2): + raise_type_error( + tx, f"length_hint expected 1 or 2 arguments, got {len(args)}" + ) + obj = args[0] + default = args[1] if len(args) == 2 else ConstantVariable.create(0) + + obj_type = maybe_get_python_type(obj) + + if type_implements_sq_length(obj_type) or type_implements_mp_length(obj_type): + return generic_size(tx, obj) + + if getattr(obj_type, "__length_hint__", None) is None: + return default + try: + return obj.call_method(tx, "__length_hint__", [], {}) + except ObservedTypeError: + handle_observed_exception(tx) + return default + + def call_getitem( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "_operator.getitem() takes no keyword arguments") + if len(args) != 2: + raise_type_error(tx, f"getitem expected 2 arguments, got {len(args)}") + return generic_getitem(tx, args[0], args[1]) + + def call_setitem( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "_operator.setitem() takes no keyword arguments") + if len(args) != 3: + raise_type_error(tx, f"setitem expected 3 arguments, got {len(args)}") + return generic_setitem(tx, args[0], args[1], args[2]) + + def call_delitem( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "_operator.delitem() takes no keyword arguments") + if len(args) != 2: + raise_type_error(tx, f"delitem expected 2 arguments, got {len(args)}") + return generic_delitem(tx, args[0], args[1]) + + def call_isinstance( + self, + tx: "InstructionTranslatorBase", + arg: VariableTracker, + isinstance_type_var: VariableTracker, + ) -> VariableTracker: + try: + arg_type = arg.python_type() + except NotImplementedError: + unimplemented( + gb_type="builtin isinstance() cannot determine type of argument", + context=f"isinstance({arg}, {isinstance_type_var})", + explanation=f"Dynamo doesn't have a rule to determine the type of argument {arg}", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + isinstance_type = isinstance_type_var.as_python_constant() + # An AsyncCollectiveTensor (ACT) input's tensor-class guard is relaxed + # (see VariableBuilder.wrap_tensor): the cache entry does not discriminate + # ACT from the resolved plain Tensor. isinstance() observes the class and + # is constant-folded below, so reinstall the class guard -- but only when + # the result would actually differ between the ACT and the resolved + # Tensor. isinstance(w, ACT) discriminates and must recompile; + # isinstance(w, torch.Tensor) is True for both and must stay reusable. + if isinstance(arg, variables.TensorVariable) and arg.source is not None: + from torch._functorch._aot_autograd.utils import ( + is_async_collective_tensor_type, + ) + + if is_async_collective_tensor_type(arg_type): + check_types = ( + isinstance_type + if isinstance(isinstance_type, tuple) + else (isinstance_type,) + ) + # Guard if any checked type distinguishes ACT from torch.Tensor, + # or conservatively if a checked entry is not a plain class. + if any( + not isinstance(ty, type) + or issubclass(arg_type, ty) != issubclass(torch.Tensor, ty) + for ty in check_types + ): + install_guard(arg.source.make_guard(GuardBuilder.TYPE_MATCH)) + if isinstance(arg, variables.TensorVariable) and arg.dtype is not None: + if _uses_custom_classinfo_check(isinstance_type): + unimplemented( + gb_type="builtin isinstance() with custom type check on tensor", + context=f"isinstance({arg}, {isinstance_type})", + explanation="Dynamo cannot soundly trace arbitrary custom " + "__instancecheck__ or __subclasscheck__ hooks on tensor " + "values because the hook may read external mutable state.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def _tensor_isinstance( + tensor_var: VariableTracker, tensor_type: Any + ) -> bool: + def check_type(ty: Any) -> bool: + if ty not in tensortype_to_dtype: + example_val = arg.as_proxy().node.meta["example_value"] + if ( + is_traceable_wrapper_subclass(example_val) + and ty is torch.nn.parameter.Parameter + ): + # N.B: we are calling isinstance directly on the example value. + # torch.nn.Parameter has a meta-class that overrides __isinstance__, + # the isinstance check here allows us to invoke that logic. + return isinstance(example_val, ty) + else: + return issubclass(arg.python_type(), ty) + + dtypes = tensortype_to_dtype[ty] + # pyrefly: ignore [missing-attribute] + return arg.dtype in dtypes + + if type(tensor_type) is tuple: + return any(check_type(ty) for ty in tensor_type) + else: + return check_type(tensor_type) + + return VariableTracker.build(tx, _tensor_isinstance(arg, isinstance_type)) + # UserDefinedObject with C extensions can have torch.Tensor attributes, + # so break graph. + if isinstance(arg, variables.UserDefinedObjectVariable) and isinstance( + arg.value, types.MemberDescriptorType + ): + unimplemented( + gb_type="isinstance() called on user defined object with C extensions", + context=f"isinstance({arg}, {isinstance_type})", + explanation="User-defined object with C extensions can have torch.Tensor " + "attributes; intentionally graph breaking.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + # handle __instancecheck__ defined in user class + if ( + isinstance(arg, variables.UserDefinedObjectVariable) + and "__instancecheck__" in isinstance_type.__class__.__dict__ + ): + return VariableTracker.build( + tx, + isinstance_type.__class__.__instancecheck__(isinstance_type, arg.value), + ) + + if isinstance(arg, variables.UserDefinedExceptionClassVariable): + # pyrefly: ignore [unbound-name] + return VariableTracker.build(tx, isinstance(arg_type, isinstance_type)) + + isinstance_type_tuple: tuple[type, ...] + if isinstance(isinstance_type, type) or callable( + # E.g. isinstance(obj, typing.Sequence) + getattr(isinstance_type, "__instancecheck__", None) + ): + isinstance_type_tuple = (isinstance_type,) + elif isinstance(isinstance_type, types.UnionType): + isinstance_type_tuple = typing.get_args(isinstance_type) + elif isinstance(isinstance_type, tuple) and all( + isinstance(tp, type) or callable(getattr(tp, "__instancecheck__", None)) + for tp in isinstance_type + ): + isinstance_type_tuple = isinstance_type + else: + raise_observed_exception( + TypeError, + tx, + args=[ + "isinstance() arg 2 must be a type, a tuple of types, or a union" + ], + ) + + try: + # NB: `isinstance()` does not call `__subclasscheck__` but use `__instancecheck__`. + # But usually `isinstance(obj, type_info)` and `issubclass(type(obj), type_info)` gives + # the same result. + # WARNING: This might run arbitrary user code `__subclasscheck__` and we did not trace + # through it. This is a limitation of the current implementation. + # Usually `__subclasscheck__` and `__instancecheck__` can be constant fold through, it + # might not be a big issue and we trade off it for performance. + val = issubclass(arg_type, isinstance_type_tuple) + except TypeError: + val = arg_type in isinstance_type_tuple + return VariableTracker.build(tx, val) + + def call_issubclass( + self, + tx: "InstructionTranslatorBase", + left_ty: VariableTracker, + right_ty: VariableTracker, + ) -> VariableTracker: + """Checks if first arg is subclass of right arg""" + return generic_issubclass(tx, left_ty, right_ty) + + def call_super( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker: + return variables.SuperVariable(a, b) + + def call_next( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "next() takes no keyword arguments") + if len(args) == 0: + raise_type_error(tx, "next expected at least 1 argument, got 0") + if len(args) > 2: + raise_type_error(tx, f"next expected at most 2 arguments, got {len(args)}") + arg = args[0] + if not pyiter_check(maybe_get_python_type(arg)): + raise_type_error( + tx, f"'{arg.python_type_name()}' object is not an iterator" + ) + try: + return arg.next_variable(tx) + except ObservedUserStopIteration: + if len(args) == 2: + return args[1] + raise + + def call_map( + self, + tx: "InstructionTranslatorBase", + fn: VariableTracker, + *seqs: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(seqs) == 0: + raise_observed_exception( + TypeError, + tx, + args=["map() must have at least two arguments."], + ) + + strict = ConstantVariable.create(False) + if kwargs: + if sys.version_info >= (3, 14): + if not (len(kwargs) == 1 and "strict" in kwargs): + raise_args_mismatch( + tx, + "map", + "1 kwargs (`strict`)", + f"{len(kwargs)} kwargs", + ) + strict = kwargs.pop("strict", ConstantVariable.create(False)) + else: + raise_args_mismatch( + tx, + "map", + "0 kwargs", + f"{len(kwargs)} kwargs", + ) + + iterables = [generic_getiter(tx, seq) for seq in seqs] + iter_args = TupleVariable(iterables, mutation_type=ValueMutationNew()) + return variables.MapVariable( + fn, + iter_args, + strict=strict.as_python_constant(), + mutation_type=ValueMutationNew(), + ) + + def call_filter( + self, tx: "InstructionTranslatorBase", fn: VariableTracker, seq: VariableTracker + ) -> VariableTracker: + return variables.FilterVariable( + fn, + generic_getiter(tx, seq), + mutation_type=ValueMutationNew(), + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # Declarative type-attribute dispatch (__name__, __bases__, __base__, + # __flags__), mirroring the consultation at the top of + # VariableTracker.getattro_impl. Inlined because this override keeps its + # own object / GetAttrVariable handling below instead of delegating. + source = self.source and AttrSource(self.source, name) + if self.fn is object: + # for object, we can just directly read the attribute + try: + value = getattr(self.fn, name) + except AttributeError: + raise_observed_exception(AttributeError, tx) + if not callable(value): + return VariableTracker.build(tx, value, source) + attr = getattr(self.fn, name, None) + return variables.GetAttrVariable( + self, name, py_type=type(attr) if attr is not None else None, source=source + ) + + def call_delattr( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + name_var: VariableTracker, + ) -> VariableTracker: + return obj.call_method(tx, "__delattr__", [name_var], {}) + + def call_type( + self, tx: "InstructionTranslatorBase", obj: VariableTracker + ) -> VariableTracker: + try: + py_type = obj.python_type() + except NotImplementedError as error: + raise UserError( + UserErrorType.INVALID_INPUT, + str(error), + case_name="unknown_python_type", + ) from None + + source = obj.source and TypeSource(obj.source) + if ( + source is None + and isinstance(obj, variables.UserDefinedObjectVariable) + and obj.cls_source + ): + source = obj.cls_source + if py_type is torch.Tensor: + # In some cases torch isn't available in globals + name = tx.output.install_global_by_id("", torch) + source = AttrSource(GlobalSource(name), "Tensor") + + return VariableTracker.build(tx, py_type, source) + + def call_reversed( + self, tx: "InstructionTranslatorBase", obj: VariableTracker + ) -> VariableTracker: + # Mirrors CPython's builtin_reversed_impl (Python/enumobject.c) + # https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/enumobject.c#L353-L395 + # 1. Look up __reversed__ via _PyObject_LookupSpecial. If found, call it. + # 2. Else require PySequence_Check (sq_item). If absent, TypeError. + # 3. Else build a reverse sequence iterator over __len__ + __getitem__. + + obj_type = maybe_get_python_type(obj) + + # Type-level __reversed__ lookup, mirrors _PyObject_LookupSpecial. + # getattr_static skips descriptors / metaclass. CPython treats + # `__reversed__ = None` on the type as an explicit opt-out, raising + # TypeError even if the sequence protocol would otherwise work. + reversed_attr = inspect.getattr_static( + obj_type, "__reversed__", _MISSING_SENTINEL + ) + if reversed_attr is None: + raise_type_error(tx, f"'{obj_type.__name__}' object is not reversible") + if reversed_attr is not _MISSING_SENTINEL: + return obj.call_method(tx, "__reversed__", [], {}) + + if not pysequence_check(obj_type): + raise_type_error(tx, "argument to reversed() must be a sequence") + + return variables.UserFunctionVariable( + polyfills.builtins.reversed_sequence_iterator + ).call_function(tx, [obj], {}) + + def call_sorted( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if not isinstance(obj, variables.TensorVariable): + list_var = variables.ListVariable( + unpack_iterable(tx, obj), + mutation_type=ValueMutationNew(), + ) + list_var.call_method(tx, "sort", [], kwargs) + return list_var + return None + + def call_neg( + self, tx: "InstructionTranslatorBase", a: VariableTracker + ) -> VariableTracker: + return pynumber_negative(tx, a) + + def call_invert( + self, tx: "InstructionTranslatorBase", a: VariableTracker + ) -> VariableTracker: + return pynumber_invert(tx, a) + + def call_format( + self, + tx: "InstructionTranslatorBase", + _format_string: VariableTracker, + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + format_string = _format_string.as_python_constant() + format_string = str(format_string) + return StringFormatVariable.create(format_string, list(args), kwargs) + + def call_id( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + if len(args) != 1: + raise_observed_exception( + TypeError, + tx, + args=[f"id() takes exactly one argument ({len(args)} given)"], + ) + arg = args[0] + + real_id = arg.get_id(tx) + if real_id is not None: + if arg.source: + guard_type = arg.get_id_guard_type() + if guard_type is not None: + install_guard(arg.source.make_guard(guard_type)) + return VariableTracker.build(tx, real_id) + + return FakeIdVariable(id(arg)) + + def call_deepcopy( + self, tx: "InstructionTranslatorBase", x: VariableTracker + ) -> VariableTracker: + unimplemented( + gb_type="copy.deepcopy()", + context=f"copy.deepcopy({x})", + explanation="Dynamo does not support copy.deepcopy()", + hints=[ + "Avoid calling copy.deepcopy()", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def _comparison_with_tensor( + self, + tx: "InstructionTranslatorBase", + left: VariableTracker, + right: VariableTracker, + ) -> VariableTracker: + from .builder import wrap_fx_proxy_cls + from .tensor import supported_tensor_comparison_op_values + + op = self.fn + + if op in [operator.is_, operator.is_not]: + is_result = ( + left.is_tensor() + and right.is_tensor() + and id(extract_fake_example_value(left.as_proxy().node)) + == id(extract_fake_example_value(right.as_proxy().node)) + ) + if op is operator.is_: + return VariableTracker.build(tx, is_result) + else: + return VariableTracker.build(tx, not is_result) + + if op not in supported_tensor_comparison_op_values: + unimplemented( + gb_type="unsupported Tensor comparison op", + context=f"{op.__name__}({left}, {right})", + explanation=f"Dynamo does not support the comparison op {op.__name__} " + f"with Tensor arguments {left}, {right}", + hints=[*graph_break_hints.SUPPORTABLE], + ) + if ( + isinstance(left, TensorVariable) + and isinstance(right, TensorVariable) + and (left.size and right.size) is not None + and left.size != right.size + ): + try: + torch.broadcast_shapes(left.size, right.size) + except RuntimeError: + # not broadcastable, can't be compared + unimplemented( + gb_type="failed to broadcast when attempting Tensor comparison op", + context=f"{op.__name__}({left}, {right})", + explanation=f"Dynamo was unable to broad cast the arguments {left}, {right} " + f"when attempting to trace the comparison op {op.__name__}.", + hints=[*graph_break_hints.USER_ERROR], + ) + tensor_cls = left if left.is_tensor() else right + proxy = tx.output.create_proxy( + "call_function", op, (left.as_proxy(), right.as_proxy()), {} + ) + return wrap_fx_proxy_cls( + type(tensor_cls), # handle Ndarrays and Tensors + tx, + proxy, + ) + + def _comparison_with_symnode( + self, + tx: "InstructionTranslatorBase", + left: VariableTracker, + right: VariableTracker, + ) -> VariableTracker: + from .tensor import supported_tensor_comparison_op_values + + op = self.fn + + if op not in supported_tensor_comparison_op_values: + unimplemented( + gb_type="unsupported SymNode comparison op", + context=f"{op.__name__}({left}, {right})", + explanation=f"Dynamo does not support the comparison op {op.__name__} " + f"with SymNode arguments {left}, {right}", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + # SymNodes are numeric (int/float/bool). The non-SymNode operand + # must be a type that can participate in a traced numeric comparison. + # Anything else (classes, DataPtrVariable, etc.) is a different type + # entirely — the comparison result is known at compile time. + non_symnode = right if isinstance(left, SymNodeVariable) else left + if not isinstance( + non_symnode, (SymNodeVariable, ConstantVariable, TensorVariable) + ): + # pyrefly: ignore [bad-argument-type] + return VariableTracker.build(tx, op(object(), None)) + + proxy = tx.output.create_proxy( + "call_function", op, (left.as_proxy(), right.as_proxy()), {} + ) + return SymNodeVariable.create( + tx, + proxy, + sym_num=None, + ) + + def call_xor( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_xor", "^") + + def call_ixor( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_xor", "nb_xor", "^=") + + def call_mul( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_multiply(tx, a, b) + + def call_imul( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_inplace_multiply(tx, a, b) + + def call_matmul( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_matrix_multiply(tx, a, b) + + def call_imatmul( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_inplace_matrix_multiply(tx, a, b) + + def call_sub( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_subtract", "-") + + def call_isub( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_subtract", "nb_subtract", "-=") + + def call_add( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_add(tx, a, b) + + def call_iadd( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_inplace_add(tx, a, b) + + def call_and_( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_and", "&") + + def call_iand( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_and", "nb_and", "&=") + + def call_or_( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_or", "|") + + def call_ior( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_or", "nb_or", "|=") + + def call_lshift( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_lshift", "<<") + + def call_ilshift( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_lshift", "nb_lshift", "<<=") + + def call_rshift( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_rshift", ">>") + + def call_irshift( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_rshift", "nb_rshift", ">>=") + + def call_floordiv( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_floor_divide", "//") + + def call_ifloordiv( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_floor_divide", "nb_floor_divide", "//=") + + def call_truediv( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_true_divide", "/") + + def call_itruediv( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_true_divide", "nb_true_divide", "/=") + + def call_mod( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_remainder", "%") + + def call_imod( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_remainder", "nb_remainder", "%=") + + def call_divmod( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + # PyNumber_Divmod dispatches through the nb_divmod slot with no + # in-place form. https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L1056 + return binary_op(tx, a, b, "nb_divmod", "divmod()") + + def call_pow( + self, + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + c: VariableTracker | None = None, + ) -> VariableTracker | None: + return ternary_op(tx, a, b, c, "nb_power", "** or pow()") + + def call_ipow( + self, + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + c: VariableTracker | None = None, + ) -> VariableTracker | None: + return ternary_iop(tx, a, b, c, "nb_inplace_power", "nb_power", "**=") + + def call_not_( + self, tx: "InstructionTranslatorBase", a: VariableTracker + ) -> VariableTracker | None: + if isinstance(a, SymNodeVariable): + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.not_, *proxy_args_kwargs([a], {}) + ), + sym_num=None, + ) + + # Unwrap the underlying ConstDictVariable + if isinstance(a, DictViewVariable): + a = a.dv_dict + if isinstance(a, (ListVariable, ConstDictVariable, SetVariable)): + return VariableTracker.build(tx, len(a.items) == 0) + if isinstance(a, UserDefinedObjectVariable): + bool_result = self.call_bool(tx, a) + return VariableTracker.build(tx, not bool_result.value) # type: ignore[missing-attribute] + + return None + + def call_contains( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker: + return pysequence_contains(tx, a, b) + + +class DictBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `dict` builtin constructor.""" + + _fn = dict + + def __init__(self, value: type = dict, **kwargs: Any) -> None: + if value is not dict: + raise AssertionError(f"DictBuiltinVariable value must be dict, got {value}") + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "DictBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return DictBuiltinVariable.call_custom_dict(tx, dict, *args, **kwargs) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__new__": + if args: + # dict.__new__ (tp_new) ignores extra args — only the first + # arg (the type) matters. Pass init_args=[] so reconstruction + # emits base_cls.__new__(cls) without extras. + # https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L4735-L4768 + dict_vt = ConstDictVariable({}, mutation_type=ValueMutationNew()) + if isinstance(args[0], DictBuiltinVariable): + return dict_vt + return tx.output.side_effects.track_new_user_defined_object( + self, + args[0], + [], + tx=tx, + ) + + if name == "fromkeys": + return DictBuiltinVariable.call_custom_dict_fromkeys( + tx, dict, *args, **kwargs + ) + + resolved_fn = getattr(dict, name, None) + if resolved_fn is not None and resolved_fn in dict_methods: + if isinstance(args[0], variables.UserDefinedDictVariable): + if args[0]._base_vt is None: + raise AssertionError( + "UserDefinedDictVariable._base_vt must not be None for dict method dispatch" + ) + return args[0]._base_vt.call_method(tx, name, args[1:], kwargs) + elif isinstance(args[0], ConstDictVariable): + return args[0].call_method(tx, name, args[1:], kwargs) + + return super().call_method(tx, name, args, kwargs) + + @staticmethod + def call_custom_dict( + tx: "InstructionTranslatorBase", + user_cls: type, + /, + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + args_list = list(args) + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.construct_dict), + [VariableTracker.build(tx, user_cls), *args_list], + kwargs, + ) + + @staticmethod + def call_custom_dict_fromkeys( + tx: "InstructionTranslatorBase", + user_cls: type, + /, + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if user_cls not in {dict, OrderedDict, defaultdict}: + unimplemented( + gb_type="Unsupported dict type for fromkeys()", + context=f"{user_cls.__name__}.fromkeys(): {args} {kwargs}", + explanation=f"Failed to call {user_cls.__name__}.fromkeys() because " + f"{user_cls.__name__} is not any type of dict, OrderedDict, or defaultdict", + hints=[ + f"Ensure {user_cls.__name__} is a type of dict, OrderedDict, or defaultdict.", + ], + ) + if kwargs: + # Only `OrderedDict.fromkeys` accepts `value` passed by keyword + if ( + user_cls is not OrderedDict + or len(args) != 1 + or len(kwargs) != 1 + or "value" not in kwargs + ): + raise_args_mismatch( + tx, + f"{user_cls.__name__}.fromkeys", + "1 args and 1 kwargs (`value`)", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + args = (*args, kwargs.pop("value")) + if len(args) == 0: + raise_args_mismatch( + tx, + f"{user_cls.__name__}.fromkeys", + "at least 1 args", + f"{len(args)} args", + ) + if len(args) == 1: + args = (*args, ConstantVariable.create(None)) + if len(args) != 2: + raise_args_mismatch( + tx, + f"{user_cls.__name__}.fromkeys", + "2 args", + f"{len(args)} args", + ) + + arg, value = args + + def _make_result( + items: dict[VariableTracker, VariableTracker], + ) -> VariableTracker: + if user_cls is OrderedDict: + return OrderedDictVariable(items, mutation_type=ValueMutationNew()) + elif user_cls is defaultdict: + from .builder import SourcelessBuilder + from .user_defined import DefaultDictVariable + + result = tx.output.side_effects.track_new_user_defined_object( + SourcelessBuilder.create(tx, dict), + SourcelessBuilder.create(tx, defaultdict), + [], + tx=tx, + ) + if not isinstance(result, DefaultDictVariable): + raise AssertionError( + f"Expected DefaultDictVariable, got {type(result)}" + ) + result._base_vt = ConstDictVariable( + items, mutation_type=ValueMutationNew() + ) + return result + else: + return ConstDictVariable(items, mutation_type=ValueMutationNew()) + + # Reuse the operand's existing HashableTracker keys instead of + # re-wrapping (and thus re-hashing) the underlying VTs, mirroring + # CPython's do-not-rehash-dict-keys behavior when building a dict from + # an existing set/frozenset/dict. + if isinstance(arg, (variables.SetVariable, ConstDictVariable)): + # HashableTracker keys are accepted by ConstDictVariable.__init__. + return _make_result(dict.fromkeys(arg.items.keys(), value)) # type: ignore[arg-type] + if isinstance(arg, dict): + arg_list = [VariableTracker.build(tx, k) for k in arg] + return _make_result(dict.fromkeys(arg_list, value)) + elif iterator := generic_getiter(tx, arg): + keys = unpack_iterable(tx, iterator) + if all(is_hashable(v) for v in keys): + return _make_result(dict.fromkeys(keys, value)) + + unimplemented( + gb_type="failed to call dict.fromkeys()", + context=f"{user_cls.__name__}.fromkeys(): {args} {kwargs}", + explanation=f"Failed to call {user_cls.__name__}.fromkeys() because " + "arguments could not be automatically converted to a list, " + "or some dict key is not hashable.", + hints=[ + "Manually convert the argument to a list.", + "Ensure all keys are hashable.", + ], + ) + + +class IterBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `iter` builtin.""" + + _fn = iter + + def __init__(self, value: Any = iter, **kwargs: Any) -> None: + if value is not iter: + raise AssertionError(f"IterBuiltinVariable value must be iter, got {value}") + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "IterBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Python/bltinmodule.c#L1666-L1682 + + if not args: + raise_observed_exception( + TypeError, + tx, + args=["iter expected at least 1 argument, got 0"], + ) + + if len(args) == 1: + return generic_getiter(tx, args[0]) + else: + return variables.UserFunctionVariable( + polyfills.builtins.callable_iterator + ).call_function(tx, args, kwargs) + + +class GetAttrBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `getattr` builtin.""" + + _fn = getattr + + def __init__(self, value: Any = getattr, **kwargs: Any) -> None: + if value is not getattr: + raise AssertionError( + f"GetAttrBuiltinVariable value must be getattr, got {value}" + ) + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "GetAttrBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .lazy import LazyVariableTracker + + if any(isinstance(a, LazyVariableTracker) for a in args): + args = [ + a.realize() if isinstance(a, LazyVariableTracker) else a for a in args + ] + try: + return self._call_getattr(tx, args, kwargs) + except Unsupported: + # Replicate the constant-fold fallback from BuiltinVariable._make_handler: + # if all args are python constants, evaluate getattr() directly rather + # than propagating a graph break from tp_getattro_impl. + if not check_unspec_or_constant_args(args, kwargs): + raise + try: + result = getattr(*[a.as_python_constant() for a in args]) + except AttributeError: + raise_observed_exception(AttributeError, tx) + raise + except AsPythonConstantNotImplementedError: + raise + except Exception as exc: + raise_observed_exception(type(exc), tx, args=list(exc.args)) + raise + return VariableTracker.build(tx, result) + + def _call_getattr( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + obj = args[0] + name_var = args[1] + default = args[2] if len(args) > 2 else _NO_DEFAULT + + if not name_var.is_python_constant(): + unimplemented( + gb_type="getattr() with non-constant name argument", + context=f"getattr({obj}, {name_var}, {default})", + explanation="getattr() with non-constant name argument is not supported", + hints=["Ensure the name argument of getattr() is a string"], + ) + + name = name_var.as_python_constant() + return generic_getattr(tx, obj, name, default) + + +class HasAttrBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `hasattr` builtin.""" + + _fn = hasattr + + def __init__(self, value: Any = hasattr, **kwargs: Any) -> None: + if value is not hasattr: + raise AssertionError( + f"HasAttrBuiltinVariable value must be hasattr, got {value}" + ) + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "HasAttrBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: Sequence[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .lazy import LazyVariableTracker + + if any(isinstance(a, LazyVariableTracker) for a in args): + args = [ + a.realize() if isinstance(a, LazyVariableTracker) else a for a in args + ] + if len(args) != 2 or kwargs: + raise_observed_exception(TypeError, tx) + obj, attr = args + if not attr.is_python_constant(): + raise_observed_exception(TypeError, tx) + result = obj.call_obj_hasattr(tx, attr.as_python_constant()) + if result is None: + unimplemented( + gb_type="hasattr() on unsupported type", + context=f"hasattr({obj}, {attr})", + explanation=f"hasattr() is not supported on type {obj.python_type_name()}", + hints=[*graph_break_hints.SUPPORTABLE], + ) + return result + + +class SetAttrBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `setattr` builtin.""" + + _fn = setattr + + def __init__(self, value: Any = setattr, **kwargs: Any) -> None: + if value is not setattr: + raise AssertionError( + f"SetAttrBuiltinVariable value must be setattr, got {value}" + ) + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "SetAttrBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: Sequence[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .lazy import LazyVariableTracker + + if any(isinstance(a, LazyVariableTracker) for a in args): + args = [ + a.realize() if isinstance(a, LazyVariableTracker) else a for a in args + ] + if len(args) != 3 or kwargs: + raise_observed_exception(TypeError, tx) + obj, name_var, val = args + result = self._call_setattr(tx, obj, name_var, val) + if result is not None: + return result + unimplemented( + gb_type="setattr() on unsupported type", + context=f"setattr({obj}, {name_var}, {val})", + explanation=f"setattr() is not supported on type {obj.python_type_name()}", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def _call_setattr( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + name_var: VariableTracker, + val: VariableTracker, + ) -> VariableTracker | None: + if isinstance( + obj, + ( + variables.DefaultDictVariable, + variables.UserDefinedObjectVariable, + variables.NestedUserFunctionVariable, + variables.ExceptionVariable, + variables.TracebackVariable, + variables.DequeVariable, + ), + ): + return obj.call_method(tx, "__setattr__", [name_var, val], {}) + elif ( + not tx.output.side_effects.is_attribute_mutation(obj) + and obj.source is not None + and (underlying := obj.get_value_for_setattr()) is not None + and hasattr(underlying, "__dict__") + and name_var.is_python_constant() + ): + tx.output.side_effects.track_object_existing(underlying, obj) + name = name_var.as_python_constant() + tx.output.side_effects.store_attr(obj, name, val) + return val + elif ( + tx.output.side_effects.is_attribute_mutation(obj) + and name_var.is_python_constant() + ): + name = name_var.as_python_constant() + if obj.is_tensor(): + from .builder import wrap_fx_proxy + + if name == "requires_grad": + # TODO(azahed98): Make it work properly + unimplemented( + gb_type="setattr() on Tensor.requires_grad", + context=f"setattr({obj}, {name}, {val})", + explanation="setattr() on Tensor.requires_grad not supported. " + "Mutating requires_grad can introduce a new leaf from non-leaf or vice versa in " + "the middle of the graph, which AOTAutograd does not currently know how to handle.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + elif name == "data": + # [Note: set_data_on_scoped_tensor] + if obj.source is None: + unimplemented( + gb_type="Failed to mutate tensor data attribute", + context=f"setattr({obj}, {name}, {val})", + explanation="Dynamo only supports mutating `.data`" + " of tensor created outside `torch.compile` region", + hints=[ + "Don't mutate `.data` on this tensor, or move " + "the mutation out of `torch.compile` region", + ], + ) + elif obj.dtype != val.dtype: # type: ignore[attr-defined] + unimplemented( + gb_type="Failed to mutate tensor data attribute to different dtype", + context=f"setattr({obj}, {name}, {val})", + explanation="Dynamo only supports mutating `.data`" + " of tensor to a new one with the same dtype", + hints=[ + "Don't mutate `.data` on this tensor, or move " + "the mutation out of `torch.compile` region", + ], + ) + elif obj.device != val.device: # type: ignore[attr-defined] + obj_fake = get_fake_value(obj.as_proxy().node, tx) + val_fake = get_fake_value(val.as_proxy().node, tx) + if ( + obj_fake.dtype != val_fake.dtype + or obj_fake.shape != val_fake.shape + or obj_fake.stride() != val_fake.stride() + ): + unimplemented( + gb_type="Failed to mutate tensor data attribute across devices with different shape/strides", + context=f"setattr({obj}, {name}, {val})", + explanation="Dynamo only supports cross-device `.data`" + " mutation when shape and strides match", + hints=[ + "Don't mutate `.data` on this tensor, or move " + "the mutation out of `torch.compile` region", + ], + ) + + # Remove the old reference in tracked fakes - if we don't + # do this, .data value size/shape differences cause + # tracked fakes to produce incorrect guards. Sound + # because the TensorVariable from shallow_copy_data_ + # below is new and gets installed in tracked fakes. + to_remove = [ + tf for tf in tx.output.tracked_fakes if tf.source == obj.source + ] + for tf in to_remove: + tx.output.tracked_fakes.remove(tf) + + # Snapshot the placeholder before + # shallow_copy_data_ mutates it. Record the node + # and snapshot so compile_and_call_fx_graph can + # restore the correct metadata before passing the + # graph to the backend. + input_node = obj.as_proxy().node + if input_node.op == "placeholder": + ev = input_node.meta.get("example_value") + if ev is not None and hasattr(ev, "fake_mode"): + from torch._subclasses.fake_impls import fast_detach + + snapshot = fast_detach(ev.fake_mode, ev) + tx.output._shallow_copy_placeholder_snapshots.setdefault( + input_node, snapshot + ) + + with dynamo_disable_grad(tx), torch.no_grad(): + out = wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + torch.ops.aten.shallow_copy_data_, + *proxy_args_kwargs([obj, val], {}), + ), + ) + + return out + elif name in ("_grad", "grad"): + # NOTE: [Tensor "grad" and "_grad" attr] + # _grad and grad share the same setter/getter, see + # THPVariable_properties, and here we make sure setting one + # enables reading `val` from the other, by routing all + # read/write to `grad`. + name = "grad" + elif is_tensor_getset_descriptor(name): + # Attribute like `torch.Tensor.real` has special setters we + # don't yet support; it's not as simple adding an entry to + # the side effect mapping. + unimplemented( + gb_type="Failed to set tensor attribute", + context=f"setattr({obj}, {name}, {val})", + explanation="Dynamo doesn't support setting these tensor attributes", + hints=[ + f"Don't mutate attribute '{name}' on tensors, or " + "move the mutation out of `torch.compile` region", + ], + ) + + tx.output.side_effects.store_attr(obj, name, val) + return val + elif isinstance(obj, variables.NNModuleVariable): + if not tx.output.is_root_tracer(): + unimplemented( + gb_type="nn.Module mutation in HigherOrderOp", + context=f"nn.Module: {obj}", + explanation="Inplace modifying nn.Module params/buffers inside HigherOrderOps is not allowed.", + hints=[ + "Remove the mutation or move it outside of the HigherOrderOp.", + *graph_break_hints.FUNDAMENTAL, + ], + ) + if name_var.is_python_constant() and isinstance( + val, variables.TensorVariable + ): + assigning_fake_val = get_fake_value(val.as_proxy().node, tx) + + try: + getattr_var = obj.tp_getattro_impl( + tx, name_var.as_python_constant() + ) + except (AttributeError, ObservedAttributeError): + getattr_var = None + + if getattr_var is not None and getattr_var.is_tensor(): + # get_fake_val will get the same fake tensor + existing_fake_attr = get_fake_value(getattr_var.as_proxy().node, tx) + + # same tensor identity, setattr is a no-op + mod_setattr = inspect.getattr_static(obj.module_type, "__setattr__") + if ( + existing_fake_attr is assigning_fake_val + and mod_setattr is torch.nn.Module.__setattr__ + ): + return getattr_var + + obj.convert_to_unspecialized(tx) + return None + + +class ListBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `list` builtin constructor.""" + + _fn = list + + def __init__(self, value: type = list, **kwargs: Any) -> None: + if value is not list: + raise AssertionError(f"ListBuiltinVariable value must be list, got {value}") + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "ListBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/listobject.c#L1265-L1287 + if kwargs: + raise_type_error( + tx, + "list() takes no keyword arguments", + ) + if len(args) == 0: + return ListVariable([], mutation_type=ValueMutationNew()) + elif len(args) > 1: + raise_type_error( + tx, + f"list expected at most 1 argument, got {len(args)}", + ) + + obj = args[0] + if obj.source and not is_constant_source(obj.source): + if isinstance(obj, TupleIteratorVariable): + install_guard(obj.source.make_guard(GuardBuilder.TUPLE_ITERATOR_LEN)) + elif not isinstance( + obj, + (variables.IteratorVariable, variables.LocalGeneratorObjectVariable), + ): + if isinstance( + obj, + ( + ConstDictVariable, + variables.OrderedSetVariable, + variables.DictKeySetVariable, + ), + ): + tx.output.guard_on_key_order.add(obj.source) + if isinstance(obj, variables.MappingProxyVariable): + install_guard( + obj.source.make_guard(GuardBuilder.MAPPING_KEYS_CHECK) + ) + elif not isinstance(obj, variables.UnspecializedNNModuleVariable): + install_guard(obj.source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + + lst = ListVariable([], mutation_type=ValueMutationNew()) + lst.call_method(tx, "extend", [args[0]], {}) + return lst + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__new__": + if len(args) == 1 and not kwargs: + list_vt = ListVariable([], mutation_type=ValueMutationNew()) + if isinstance(args[0], ListBuiltinVariable): + return list_vt + return tx.output.side_effects.track_new_user_defined_object( + self, + args[0], + args[1:], + tx=tx, + ) + + return super().call_method(tx, name, args, kwargs) + + +# pyrefly: ignore [deprecated] +@contextlib.contextmanager +def dynamo_disable_grad(tx: "InstructionTranslatorBase") -> typing.Iterator[None]: + from . import GradModeVariable + + gmv = GradModeVariable.create(tx, False) + try: + gmv.enter(tx) + yield + finally: + gmv.exit(tx) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/constant.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/constant.py new file mode 100644 index 0000000000000000000000000000000000000000..8d555f40c7cfd9169d7b780cd1c5fa66d3d7a34c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/constant.py @@ -0,0 +1,1031 @@ +""" +Constant variable tracking in Dynamo. + +This module is fundamental to Dynamo's ability to track and propagate constant +values during compilation, ensuring proper handling of Python literals and +maintaining type safety through the compilation process. +""" + +from __future__ import annotations + +import enum +import operator +from collections.abc import Iterable +from typing import Any, Literal, overload, TYPE_CHECKING + +import torch +from torch._dynamo.source import GetItemSource + +from .. import graph_break_hints, variables +from ..exc import raise_observed_exception, raise_type_error, unimplemented +from ..utils import ( + common_constant_types, + istype, + np, + raise_args_mismatch, + unpack_iterable, +) +from .base import ValueMutationNew, VariableTracker + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from .functions import UserFunctionVariable + + +class ConstantVariable(VariableTracker): + """ + Variable tracker for Python literals and basic immutable types, with automatic + routing support for collection types (lists, tuples, sets, etc.). + + The create() method intelligently constructs appropriate variable types for + nested collections. + """ + + # PyLong_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L6585 + # PyFloat_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L1880 + # PyBool_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/boolobject.c#L171 + # PyUnicode_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/unicodeobject.c#L14931 + # PyBytes_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/bytesobject.c#L3017 + # PyComplex_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L1099 + # _PyNone_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/object.c#L2022 + _cpython_type = (int, float, str, bytes, bool, type(None), complex, type(...)) + + @overload + @staticmethod + def create(value: None) -> ConstantVariable: ... + + @overload + @staticmethod + def create(value: bool) -> ConstantVariable: ... + + @overload + @staticmethod + def create(value: Any, **kwargs: Any) -> VariableTracker: ... + + @staticmethod + def create(value: Any, **kwargs: Any) -> VariableTracker: + """ + Create a `ConstantVariable` based on the given value, and supports + automatic routing for collection types like `tuple` (in which case we'd + create `ConstantVariable` for the leaf items). + + NOTE: the caller must install the proper guards if needed; most often + the guard will be `CONSTANT_MATCH`. + """ + # Return pre-allocated sentinels for None/True/False when there are + # no extra kwargs (source, etc.) that would differentiate the instance. + if not kwargs: + match value: + case None: + return CONSTANT_VARIABLE_NONE + case True: + return CONSTANT_VARIABLE_TRUE + case False: + return CONSTANT_VARIABLE_FALSE + + source = kwargs.get("source") + + # Routing for supported collection literals. + if isinstance(value, set): + items = [ConstantVariable.create(x) for x in value] + return variables.SetVariable(items, **kwargs) # type: ignore[arg-type] + elif isinstance(value, frozenset): + items = [ConstantVariable.create(x) for x in value] + return variables.FrozensetVariable(items, **kwargs) # type: ignore[arg-type] + elif isinstance(value, slice): + slice_args = (value.start, value.stop, value.step) + slice_args_vars: list[VariableTracker] = [ + ConstantVariable.create(arg) for arg in slice_args + ] + return variables.SliceVariable(slice_args_vars, **kwargs) + elif isinstance(value, (list, tuple)): + items = [] + for i, x in enumerate(value): + item_source = GetItemSource(source, i) if source else None + items.append( + ConstantVariable.create( + x, + source=item_source, + ) + ) + return variables.BaseListVariable.cls_for(type(value))(items, **kwargs) + + return ConstantVariable(value, **kwargs) + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + if not ConstantVariable.is_base_literal(value): + raise AssertionError( + f"Cannot construct `ConstantVariable` for value of type {type(value)}.\n" + "\n" + "This failure likely due to PyTorch-internal use of `ConstantVariable` on\n" + "non-literal python values, please try using `VariableTracker.build` instead. If\n" + "you believe it's a necessary and legitimate use case (the value is immutable and\n" + "can't easily be represented with another `VariableTracker` class), please add\n" + "its type to `common_constant_types`." + ) + if np is not None and isinstance(value, np.number): + self.value = value.item() + else: + self.value = value + + def as_proxy(self) -> Any: + return self.value + + def __repr__(self) -> str: + return f"ConstantVariable({type(self.value).__name__}: {repr(self.value)})" + + def as_python_constant(self) -> Any: + return self.value + + def is_python_constant(self) -> Literal[True]: + return True + + def tp_repr_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + return ConstantVariable.create(repr(self.value)) + + def is_symnode_like(self) -> bool: + return isinstance(self.value, (int, bool)) + + def is_constant_match(self, *values: Any) -> bool: + return self.value in values + + def is_constant_none(self) -> bool: + return self.value is None + + @property + def items(self) -> list[VariableTracker]: + """ + Need this when adding a BaseListVariable and a ConstantVariable together. + Happens in detectron2. + """ + try: + return [ConstantVariable.create(x) for x in self.value] + except TypeError as e: + raise NotImplementedError from e + + def getitem_const( + self, tx: InstructionTranslatorBase, arg: VariableTracker + ) -> VariableTracker: + # bytes_subscript: https://github.com/python/cpython/blob/62a6e898e017c9878490544f6a227b8a187a949c/Objects/bytesobject.c#L1732 + # unicode_subscript: https://github.com/python/cpython/blob/62a6e898e017c9878490544f6a227b8a187a949c/Objects/unicodeobject.c#L13738 + if isinstance(self.value, (str, bytes)): + from .lists import SliceVariable + from .object_protocol import maybe_get_python_type, pyindex_check + + # _PyIndex_Check first, then slice, mirroring unicode_subscript / + # bytes_subscript. + if pyindex_check(maybe_get_python_type(arg)): + arg = arg.nb_index_impl(tx) + elif isinstance(arg, SliceVariable): + return ConstantVariable.create(self.value[arg.as_index_slice(tx)]) + else: + raise_type_error( + tx, + f"{self.python_type_name()} indices must be integers, " + f"not {arg.python_type_name()}", + ) + return ConstantVariable.create( + self.value[arg.as_python_constant()], + ) + + def sq_item_impl( + self, tx: InstructionTranslatorBase, key: VariableTracker + ) -> VariableTracker: + # unicode_getitem: https://github.com/python/cpython/blob/62a6e898e01/Objects/unicodeobject.c#L13777 + # bytes_item: https://github.com/python/cpython/blob/62a6e898e01/Objects/bytesobject.c#L319 + # CPython's sq_item takes Py_ssize_t (already int from generic_getitem's + # nb_index_impl). Unlike mp_subscript, sq_item never handles slices. + index = key.as_python_constant() + try: + return ConstantVariable.create(self.value[index]) + except IndexError as e: + raise_observed_exception(IndexError, tx, args=list(e.args)) + + @staticmethod + def is_base_literal(obj: object) -> bool: + return type(obj) in common_constant_types + + @staticmethod + def is_literal(obj: object, cache: dict[int, object] | None = None) -> bool: + if cache is None: + cache = {} + if id(obj) in cache: + # no-op if there is a cyclical reference + return True + if type(obj) in (list, tuple, set, frozenset, torch.Size): + cache[id(obj)] = obj + return all(ConstantVariable.is_literal(x, cache) for x in obj) # type: ignore[attr-defined] + return ConstantVariable.is_base_literal(obj) + + def unpack_var_sequence( + self, tx: InstructionTranslatorBase | None + ) -> list[VariableTracker]: + try: + return [ConstantVariable.create(x) for x in self.as_python_constant()] + except TypeError as e: + raise NotImplementedError from e + + def hash_impl(self, tx: InstructionTranslatorBase) -> tuple[int, bool]: + """Dynamo tracing rule for long_hash, float_hash, unicode_hash, etc.""" + return hash(self.value), False + + def tp_richcompare_impl( + self, tx: InstructionTranslatorBase, other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def tp_str_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + return ConstantVariable.create(str(self.value)) + + def len_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """Generic len for any constant value (sequence or mapping).""" + try: + return ConstantVariable.create(len(self.value)) + except TypeError as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def sq_length_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """Sequence length - delegates to len_impl for constants.""" + return self.len_impl(tx) + + def mp_length_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """Mapping length - delegates to len_impl for constants.""" + return self.len_impl(tx) + + def const_getattr( + self, tx: InstructionTranslatorBase, name: str + ) -> VariableTracker: + if not hasattr(self.value, name): + raise_observed_exception(AttributeError, tx, args=[name]) + member = getattr(self.value, name) + if callable(member): + raise NotImplementedError + return member + + def sq_contains_impl(self, tx: InstructionTranslatorBase, item: VariableTracker): + """Sequence contains for constants.""" + if item.is_python_constant(): + search = item.as_python_constant() + try: + result = search in self.value + return ConstantVariable.create(result) + except TypeError as e: + raise_observed_exception( + type(e), + tx, + args=list(e.args), + ) + return super().sq_contains_impl(tx, item) + + def tp_iter_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + from .lists import ListIteratorVariable + + if isinstance(self.value, Iterable): + try: + return ListIteratorVariable( + [ConstantVariable.create(c) for c in self.value], + mutation_type=ValueMutationNew(), + ) + except NotImplementedError: + pass + return super().tp_iter_impl(tx) + + def call_method( + self, + tx: InstructionTranslatorBase, + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .tensor import SymNodeVariable + + if name == "format" and istype(self.value, str): + return variables.BuiltinVariable(str.format).call_function( + tx, + [self, *args], + kwargs, + ) + elif name == "join" and istype(self.value, str): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + arg_unpacked = unpack_iterable(tx, args[0]) + try: + arg_const = [x.as_python_constant() for x in arg_unpacked] + return ConstantVariable.create(self.value.join(arg_const)) + except NotImplementedError: + return super().call_method(tx, name, args, kwargs) + + if any(isinstance(x, SymNodeVariable) for x in args): + # Promote to SymNodeVariable for operations involving dynamic shapes. + return variables.SymNodeVariable.create( + tx, self.as_proxy(), self.value + ).call_method(tx, name, args, kwargs) + + try: + const_args = [a.as_python_constant() for a in args] + const_kwargs = {k: v.as_python_constant() for k, v in kwargs.items()} + except NotImplementedError: + return super().call_method(tx, name, args, kwargs) + + if name == "__iter__": + return self.tp_iter_impl(tx) + + if isinstance(self.value, str) and name in str.__dict__: + method = getattr(self.value, name) + try: + result = method(*const_args, **const_kwargs) + except Exception as e: + raise_observed_exception(type(e), tx) + # str.split/rsplit/splitlines return a fresh caller-owned list; + # mark it mutable so in-place ops (.sort(), shuffle, etc.) are tracked. + if name in ("split", "rsplit", "splitlines"): + return ConstantVariable.create(result, mutation_type=ValueMutationNew()) + return ConstantVariable.create(result) + elif isinstance(self.value, (float, int)) and hasattr(self.value, name): + if not (args or kwargs): + try: + return ConstantVariable.create(getattr(self.value, name)()) + except (OverflowError, ValueError) as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + if ( + hasattr(operator, name) + and len(args) == 1 + and args[0].is_python_constant() + ): + add_target = const_args[0] + op = getattr(operator, name) + if isinstance( + add_target, (torch.SymBool, torch.SymFloat, torch.SymInt) + ): + # Addition between a non sym and sym makes a sym + proxy = tx.output.create_proxy( + "call_function", op, (self.value, add_target), {} + ) + return SymNodeVariable.create(tx, proxy, add_target) + else: + try: + return ConstantVariable.create(op(self.value, add_target)) + except Exception as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + elif isinstance(self.value, bytes) and name == "decode": + method = getattr(self.value, name) + return ConstantVariable.create(method(*const_args, **const_kwargs)) + elif type(self.value) is complex and name in complex.__dict__: + method = getattr(self.value, name) + try: + return ConstantVariable.create(method(*const_args, **const_kwargs)) + except Exception as e: + raise_observed_exception(type(e), tx) + + if name == "__round__" and len(args) == 1 and args[0].is_python_constant(): + try: + return ConstantVariable.create( + round(self.value, args[0].as_python_constant()) + ) + except Exception as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + return super().call_method(tx, name, args, kwargs) + + def call_tree_map( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.value is None: + none_is_leaf_var = tree_map_kwargs.get("none_is_leaf") + if none_is_leaf_var is not None: + try: + none_is_leaf = bool(none_is_leaf_var.as_python_constant()) + except NotImplementedError: + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + else: + tree_map_module = getattr( + getattr(tree_map_fn, "fn", None), "__module__", "" + ) + # torch.utils._pytree and torch.utils._cxx_pytree treat None as a leaf + # by default, while optree keeps it as an internal node unless + # none_is_leaf=True is provided. + none_is_leaf = not tree_map_module.startswith("optree") + if none_is_leaf: + return map_fn.call_function(tx, [self, *rest], {}) + else: + for other in rest: + if not other.is_constant_none(): + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + return self.clone() + if isinstance(self.value, (int, float, bool, complex, str, bytes, torch.dtype)): + return map_fn.call_function(tx, [self, *rest], {}) + return super().call_tree_map( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + + def reconstruct_pycode(self, codegen) -> str: + return repr(self.value) + + def get_id(self, tx: InstructionTranslatorBase) -> int | None: + # Singletons have guaranteed stable identity across the process lifetime. + if self.value is None or self.value is True or self.value is False: + return id(self.value) + # Sourceful constants resolve via source like any other sourceful VT. + # Sourceless non-singleton constants (e.g. literal 42 in compiled code) + # get FakeIdVariable — CPython interning of small ints/strings is an + # implementation detail users shouldn't rely on. + return super().get_id(tx) + + def get_real_python_backed_value(self) -> object: + return self.value + + def nb_index_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # CPython: int and bool define nb_index (returns self for int, + # int(self) for bool). All other constant types do not. + from .object_protocol import type_implements_nb_index + + if type_implements_nb_index(type(self.value)): + return ConstantVariable.create(operator.index(self.value)) + return super().nb_index_impl(tx) + + def nb_int_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # CPython: int defines nb_int (long_long, returns copy). + # bool inherits nb_int from int via slot inheritance. + # float defines nb_int (truncates toward zero via PyLong_FromDouble). + return ConstantVariable.create(int(self.value)) + + def nb_float_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # CPython: float defines nb_float (float_float, returns copy). + # int defines nb_float (long_float, converts to float). + # bool inherits nb_float from int via slot inheritance. + return ConstantVariable.create(float(self.value)) + + def _nb_binary_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + op: Any, + type_check: Any, + reverse: bool, + ) -> VariableTracker: + # Shared body for ConstantVariable's binary nb_* slots. Mirrors the + # CPython contract: if the type doesn't implement the slot, return + # NotImplemented so dispatch can try the reverse slot; otherwise run + # ``op(v, w)`` and re-raise arithmetic exceptions as observed. + if not type_check(type(self.value)): + return ConstantVariable.create(NotImplemented) + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + v, w = self_.as_python_constant(), other_.as_python_constant() + try: + result = op(v, w) + except (TypeError, ValueError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + if result is NotImplemented: + return ConstantVariable.create(NotImplemented) + return VariableTracker.build(tx, result) + + def nb_lshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: only int defines nb_lshift; bool inherits via slot inheritance. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5489 (long_lshift) + from .object_protocol import type_implements_nb_lshift + + return self._nb_binary_impl( + tx, other, operator.lshift, type_implements_nb_lshift, reverse + ) + + def nb_rshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: only int defines nb_rshift; bool inherits via slot inheritance. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5526 (long_rshift) + from .object_protocol import type_implements_nb_rshift + + return self._nb_binary_impl( + tx, other, operator.rshift, type_implements_nb_rshift, reverse + ) + + def nb_floor_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int and float define nb_floor_divide; bool inherits int's. + # complex does NOT (complex floor division raises TypeError). + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L4057 (long_floor_div) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L660 (float_floor_div) + if not isinstance(self.value, (int, float)): + return ConstantVariable.create(NotImplemented) + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + v, w = self_.as_python_constant(), other_.as_python_constant() + try: + return VariableTracker.build(tx, v // w) + except (TypeError, ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_true_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, float, and complex define nb_true_divide; bool inherits int's. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L4146 (long_true_divide) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L618 (float_div) + # https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L518 (complex_div) + if not isinstance(self.value, (int, float, complex)): + return ConstantVariable.create(NotImplemented) + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + v, w = self_.as_python_constant(), other_.as_python_constant() + try: + return VariableTracker.build(tx, v / w) + except (TypeError, ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_remainder_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int and float define nb_remainder (bool inherits int's); complex + # does NOT. str/bytes/bytearray define nb_remainder for %-formatting. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L4116 (long_mod) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L640 (float_rem) + # https://github.com/python/cpython/blob/v3.13.0/Objects/unicodeobject.c#L15170 (unicode_mod) + if not isinstance(self.value, (int, float, str, bytes, bytearray)): + return ConstantVariable.create(NotImplemented) + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + v, w = self_.as_python_constant(), other_.as_python_constant() + try: + return VariableTracker.build(tx, v % w) + except (TypeError, ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_divmod_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int and float define nb_divmod (bool inherits int's); complex + # does NOT. Returns a (quotient, remainder) tuple. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L4126 (long_divmod) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L680 (float_divmod) + if not isinstance(self.value, (int, float)): + return ConstantVariable.create(NotImplemented) + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + v, w = self_.as_python_constant(), other_.as_python_constant() + try: + return VariableTracker.build(tx, divmod(v, w)) + except (TypeError, ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_or_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, frozenset, and type all define nb_or. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5606 (long_or) + # https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L1319 (set_or) + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L6028-L6030 (type_as_number.nb_or) + # bool inherits int's nb_or via slot inheritance. + from .object_protocol import type_implements_nb_or + + return self._nb_binary_impl( + tx, other, operator.or_, type_implements_nb_or, reverse + ) + + def nb_subtract_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, float, and complex define nb_subtract; bool inherits int's. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L3819-L3824 (long_sub_method) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L598-L606 (float_sub) + # https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L494-L503 (COMPLEX_BINOP(sub, diff)) + from .object_protocol import type_implements_nb_subtract + + return self._nb_binary_impl( + tx, other, operator.sub, type_implements_nb_subtract, reverse + ) + + def nb_multiply_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # int, float, and complex all define nb_multiply (bool inherits int's slot). + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L4242-L4260 (long_mul) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L608-L616 (float_mul) + # https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L506 (complex_mul) + # str/bytes/bytearray do NOT have nb_multiply — they go through sq_repeat, + # so this method should not see them as ``self``. + from .object_protocol import type_implements_nb_multiply + + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + other_val = other.as_python_constant() + # CPython's nb_multiply (e.g. long_mul, float_mul) returns NotImplemented + # whenever the other operand isn't numeric — sequence repetition is + # then handled by PyNumber_Multiply's sq_repeat fallback. We mirror that + # here because ``operator.mul`` performs the full protocol (including + # sq_repeat) and would incorrectly short-circuit the dispatch. + if not isinstance(other_val, (int, float, complex)): + return ConstantVariable.create(NotImplemented) + return self._nb_binary_impl( + tx, other, operator.mul, type_implements_nb_multiply, reverse + ) + + def sq_repeat_impl( + self, + tx: InstructionTranslatorBase, + count: VariableTracker, + ) -> VariableTracker: + # Only str / bytes are reachable via ConstantVariable since list, tuple, + # bytearray have their own VTs. ``count`` was already validated as an + # index by pysequence_repeat -> nb_index_impl. + # https://github.com/python/cpython/blob/v3.13.0/Objects/unicodeobject.c#L12371 (unicode_repeat) + # https://github.com/python/cpython/blob/v3.13.0/Objects/bytesobject.c#L1448 (bytes_repeat) + if not isinstance(self.value, (str, bytes)): + raise AssertionError("Expected str or bytes in sq_repeat_impl") + n = count.as_python_constant() + try: + return ConstantVariable.create(self.value * n) + except (MemoryError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_and_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, frozenset, and type all define nb_and. + # https://github.com/python/cpython/blob/3.13/Objects/longobject.c#L5574 (long_and) + # https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1506-L1518 (set_and) + # bool inherits int's nb_and via slot inheritance. + from .object_protocol import type_implements_nb_and + + return self._nb_binary_impl( + tx, other, operator.and_, type_implements_nb_and, reverse + ) + + def nb_xor_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int and frozenset define nb_xor. + # https://github.com/python/cpython/blob/3.13/Objects/longobject.c#L5587 (long_xor) + # https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1984-L1990 (set_xor) + # bool inherits int's nb_xor via slot inheritance. + from .object_protocol import type_implements_nb_xor + + return self._nb_binary_impl( + tx, other, operator.xor, type_implements_nb_xor, reverse + ) + + def nb_negative_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # int: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5179-L5189 + # float: https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L839-L849 + # complex: https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L569-L575 + # bool inherits nb_negative from int via slot inheritance. + return ConstantVariable.create(-self.value) + + def nb_positive_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # int: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5619 (long_long) + # float: https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L1114 (float_float) + # complex: https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L578 (complex_pos) + # bool inherits nb_positive from int via slot inheritance. + return ConstantVariable.create(+self.value) + + def nb_add_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, float, and complex define nb_add; bool inherits int's. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L3800 (long_add) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L559 (float_add) + # https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L720 (COMPLEX_BINOP(add, sum)) + from .object_protocol import type_implements_nb_add + + return self._nb_binary_impl( + tx, other, operator.add, type_implements_nb_add, reverse + ) + + def nb_power_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + z: VariableTracker | None, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, float, and complex all define nb_power (bool inherits int's). + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c (long_pow) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c (float_pow) + # https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c (complex_pow) + + if z is not None: + z = z.as_python_constant() + + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + + self_, other_ = (other, self) if reverse else (self, other) + v, w = ( + self_.as_python_constant(), + other_.as_python_constant(), + ) + + try: + return VariableTracker.build(tx, pow(v, w, z)) + except TypeError: + return ConstantVariable.create(NotImplemented) + except (ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_power_z_impl( + self, + tx: InstructionTranslatorBase, + v: VariableTracker, + w: VariableTracker, + ) -> VariableTracker: + if not isinstance(self.value, int): + return ConstantVariable.create(NotImplemented) + if not v.is_python_constant() or not w.is_python_constant(): + return ConstantVariable.create(NotImplemented) + v_val, w_val = v.as_python_constant(), w.as_python_constant() + if not isinstance(v_val, int) or not isinstance(w_val, int): + return ConstantVariable.create(NotImplemented) + try: + return VariableTracker.build(tx, pow(v_val, w_val, self.value)) + except (TypeError, ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_absolute_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # int: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5184-L5190 + # float: https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L847-L850 + # complex: https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L588-L600 + # _Py_c_abs can set errno=ERANGE on overflow, which complex_abs + # converts to OverflowError("absolute value too large"). + # bool inherits nb_absolute from int via slot inheritance. + try: + return ConstantVariable.create(abs(self.value)) + except OverflowError as e: + raise_observed_exception(OverflowError, tx, args=list(e.args)) + + def nb_invert_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # int: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5163-L5177 + # long_invert implements ~x as -(x+1). + # bool inherits nb_invert from int via slot inheritance. + return ConstantVariable.create(~self.value) + + +CONSTANT_VARIABLE_NONE = ConstantVariable(None) +CONSTANT_VARIABLE_TRUE = ConstantVariable(True) +CONSTANT_VARIABLE_FALSE = ConstantVariable(False) + + +class FakeValueKind(enum.Enum): + ID = "id" + HASH = "hash" + + +class FakeIdVariable(VariableTracker): + """A compile-time-only id or hash value that can be used as a dict key but + cannot be reconstructed across graph breaks. + + When dynamo evaluates ``id(x)`` or ``hash(x)`` on a variable tracker that + has no corresponding runtime object, we mint a fake integer. The ``kind`` + field tracks which builtin produced the value so that same-kind comparisons + (e.g. ``id(a) != id(b)``) can be resolved at compile time while cross-kind + comparisons graph-break. + """ + + # PyLong_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L6585 + _cpython_type = int + + _nonvar_fields = { + "kind", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, value: int, *, kind: FakeValueKind = FakeValueKind.ID, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.value = value + self.kind = kind + + def as_python_constant(self) -> int: + return self.value + + def is_python_constant(self) -> bool: + return False + + def python_type(self) -> type: + return int + + def hash_impl(self, tx: InstructionTranslatorBase) -> tuple[int, bool]: + return hash(self.value), True + + def tp_repr_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + # Mirrors int.__repr__: the value is an int, so str()/repr() yield its + # decimal string. The distinct-but-compile-time-only identity carried by + # the fake id is preserved in the resulting string, matching how + # FakeIdVariable already resolves same-kind id()/hash() comparisons. + return ConstantVariable.create(repr(self.value)) + + def tp_richcompare_impl( + self, tx: InstructionTranslatorBase, other: VariableTracker, op: str + ) -> VariableTracker: + if ( + isinstance(other, FakeIdVariable) + and self.kind == other.kind + and op in ("__eq__", "__ne__") + ): + result = ( + (self.value == other.value) + if op == "__eq__" + else (self.value != other.value) + ) + return ConstantVariable.create(result) + unimplemented( + gb_type="Comparison on compile-time-only id or hash value", + context=f"FakeIdVariable({self.value}) {op} {type(other).__name__}", + explanation="Cannot compare a compile-time-only id() or hash() " + "value. The comparison will run eagerly.", + hints=[ + "Avoid comparing id() or hash() of objects created inside " + "the compiled region against other values.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # Arithmetic on a fake id/hash (e.g. ``id(self) & 0x7fffffff`` inside a + # custom __hash__) stays compile-time-only: CPython computes int op int, + # but the operand is a fake address so the result must not be baked into + # the graph. We mirror int's nb_* slots and return another fake int. + def _operand_int(self, other: VariableTracker) -> int | None: + if isinstance(other, FakeIdVariable): + return other.value + if other.is_python_constant(): + val = other.as_python_constant() + if isinstance(val, int): + return val + return None + + def _nb_binary_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + op: Any, + reverse: bool, + ) -> VariableTracker: + other_val = self._operand_int(other) + if other_val is None: + return ConstantVariable.create(NotImplemented) + lhs, rhs = (other_val, self.value) if reverse else (self.value, other_val) + try: + result = op(lhs, rhs) + except (TypeError, ValueError, OverflowError, ZeroDivisionError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + return FakeIdVariable(result) + + def nb_add_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.add, reverse) + + def nb_subtract_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.sub, reverse) + + def nb_multiply_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.mul, reverse) + + def nb_floor_divide_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.floordiv, reverse) + + def nb_remainder_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.mod, reverse) + + def nb_and_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.and_, reverse) + + def nb_or_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.or_, reverse) + + def nb_xor_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.xor, reverse) + + def nb_lshift_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.lshift, reverse) + + def nb_rshift_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.rshift, reverse) + + def nb_negative_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(-self.value) + + def nb_positive_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(+self.value) + + def nb_absolute_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(abs(self.value)) + + def nb_invert_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(~self.value) + + def nb_int_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(int(self.value), kind=self.kind) + + def nb_index_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(self.value, kind=self.kind) + + def reconstruct(self, codegen: Any) -> None: + unimplemented( + gb_type="Reconstruction of FakeIdVariable", + context=str(self.value), + explanation=( + "A fake id produced by id() on a compile-time container " + "cannot be reconstructed across a graph break." + ), + hints=[ + "Avoid using id() on containers in code that may graph-break.", + ], + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/ctx_manager.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/ctx_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..4364c03e1d08306ea367150e96682bceb604115a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/ctx_manager.py @@ -0,0 +1,1880 @@ +""" +This file contains a collection of context manager classes used by Dynamo for tracking +and managing various PyTorch runtime states during graph compilation. These context +managers handle different aspects of PyTorch's execution environment, including: + +- Autograd states (grad mode, inference mode) +- CUDA streams and events +- Profiling contexts +- Deterministic algorithms +- Forward/backward AD modes +- SDPA (Scaled Dot Product Attention) kernels +- FSDP (Fully Sharded Data Parallel) states +- AMP (Automatic Mixed Precision) autocast states + +The context managers ensure proper state transitions during graph compilation by +tracking enter/exit points and managing cleanup operations. They help maintain +consistency between eager execution and compiled graph behavior by capturing and +restoring state changes. +""" + +import contextlib +import inspect +import logging +import types +import warnings +from collections.abc import Callable, Sequence, Sized +from contextlib import AbstractContextManager, ExitStack +from typing import Any, TYPE_CHECKING + +import torch._C +from torch._dynamo import config +from torch._guards import Guard +from torch._logging import warning_once + +from .. import graph_break_hints, variables +from ..bytecode_transformation import create_call_function +from ..exc import unimplemented +from ..guards import GuardBuilder, install_guard +from ..source import AttrSource, GlobalStateSource +from ..utils import _get_error_on_graph_break, _set_error_on_graph_break +from .base import VariableTracker +from .functions import ( + NestedUserFunctionVariable, + SkipFunctionVariable, + UserFunctionVariable, + UserMethodVariable, + WrappedNestedUserFunctionVariable, + WrappedSkipFunctionVariable, + WrappedUserFunctionVariable, + WrappedUserMethodVariable, +) +from .user_defined import UserDefinedObjectVariable + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + +log = logging.getLogger(__name__) + + +class ContextWrappingVariable(VariableTracker): + _nonvar_fields = { + "cm_obj", + "target_values", + "initial_values", + "state", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, target_values: Any, initial_values: Any | None = None, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.target_values = target_values + self.initial_values = initial_values + # target_values must be None or a Sequence for reconstruct / _call_func + # etc. to work properly. + if not (target_values is None or isinstance(target_values, Sequence)): + raise TypeError( + "ContextWrappingVariable.target_values must be None or a " + f"Sequence, got {type(target_values).__name__}" + ) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if hasattr(self, "_call_func"): + self._call_func(tx, self.target_values) + self.set_cleanup_hook(tx) + return variables.ConstantVariable.create(None) + + def set_cleanup_hook( + self, tx: "InstructionTranslatorBase", fn: Callable[..., Any] | None = None + ) -> None: + if fn is None: + + def fn() -> None: + if hasattr(self, "_call_func"): + self._call_func(tx, self.initial_values) + + self.cleanup_fn: Callable[..., Any] | None = fn + tx.output.add_cleanup_hook(self.cleanup) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup_assert() + return variables.ConstantVariable.create(None) + + def reconstruct_type(self, codegen: "PyCodegen") -> None: + codegen( + AttrSource(codegen.tx.import_source(self.module_name()), self.fn_name()) + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: self.reconstruct_type(codegen)) + target_values = self.target_values + if not target_values: + target_values = () + codegen.extend_output([codegen.create_load_const(val) for val in target_values]) + codegen.extend_output(create_call_function(len(target_values), False)) + + def module_name(self) -> str: + raise NotImplementedError("module_name called on base") + + def fn_name(self) -> str: + raise NotImplementedError("fn_name called on base") + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if len(args) != 1: + raise AssertionError(f"expected exactly 1 arg, got {len(args)}") + if not isinstance( + args[0], + ( + NestedUserFunctionVariable, + SkipFunctionVariable, + UserMethodVariable, + UserFunctionVariable, + ), + ): + raise AssertionError(f"expected a function variable, got {type(args[0])}") + + if isinstance(args[0], NestedUserFunctionVariable): + return WrappedNestedUserFunctionVariable(args[0], self) + elif isinstance(args[0], SkipFunctionVariable): + return WrappedSkipFunctionVariable(args[0], self) + elif isinstance(args[0], UserMethodVariable): + return WrappedUserMethodVariable(args[0], self) + elif isinstance(args[0], UserFunctionVariable): + return WrappedUserFunctionVariable(args[0], self) + else: + raise AssertionError("Unexpected arg type") + + def supports_graph_breaks(self) -> bool: + return True + + def exit_on_graph_break(self) -> bool: + return True + + def cleanup(self) -> None: + if self.cleanup_fn is not None: + self.cleanup_fn() + self.cleanup_fn = None + + def cleanup_assert(self) -> None: + if not self.cleanup_fn: + raise AssertionError("multiple exits?") + self.cleanup() + + +class GenericContextWrappingVariable(UserDefinedObjectVariable): + # Some methods in ContextWrappingVariable assumes the arguments are + # python constants. Which might not always be the case here. + def __init__(self, cm_obj: AbstractContextManager[Any], **kwargs: Any) -> None: + if cm_obj is None: + raise AssertionError("cm_obj must not be None") + super().__init__( + value=cm_obj, + value_type=cm_obj.__class__, + **kwargs, + ) + self.cm_obj = cm_obj + + def module_name(self) -> str: + return self.cm_obj.__module__ + + def fn_name(self) -> str: + return type(self.cm_obj).__name__ + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + source = None if self.source is None else AttrSource(self.source, "__enter__") + return variables.UserMethodVariable( + self.cm_obj.__enter__.__func__, # type: ignore[attr-defined] + self, + source=source, + ).call_function(tx, [], {}) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + source = None if self.source is None else AttrSource(self.source, "__exit__") + x = variables.UserMethodVariable( + self.cm_obj.__exit__.__func__, # type: ignore[attr-defined] + self, + source=source, + ).call_function(tx, list(args), {}) + tx.active_generic_context_managers.pop() + return x + + def supports_graph_breaks(self) -> bool: + return False + + def exit_on_graph_break(self) -> bool: + return True + + +class RecordFunctionVariable(GenericContextWrappingVariable): + def __init__(self, cm_obj: torch.profiler.record_function, **kwargs: Any) -> None: + super().__init__(cm_obj, **kwargs) + args = [variables.ConstantVariable.create(cm_obj.name)] + record_kwargs = {} + if cm_obj.args: + record_kwargs["args"] = variables.ConstantVariable.create(cm_obj.args) + self.record_fn = variables.torch.ProfilerRecordFunctionContextVariable.create( + func=type(self.cm_obj), record_args=args, record_kwargs=record_kwargs + ) + + def enter(self, tx): + tx.active_generic_context_managers.append(self) + return self.record_fn.enter(tx) + + def exit(self, tx, *args): + tx.active_generic_context_managers.pop() + return self.record_fn.exit(tx, *args) + + +class RepararametrizeModuleContextVariable(GenericContextWrappingVariable): + def __init__(self, ctx_manager_vt: ContextWrappingVariable, mod: Any) -> None: + self.cm_vt = ctx_manager_vt + self.mod = mod + # We don't call super().__init__() because we're delegating most methods to cm_vt + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # Custom enter implementation with side effects. Additionally, do not + # worry about side effects for the hop, as they cancel each other out. + with torch._dynamo.variables.higher_order_ops.dynamo_allow_side_effects_in_hop( + tx + ): + self.old_parameters_var = self.mod.tp_getattro_impl( + tx, "_parameters" + ).realize() + self.old_buffer_var = self.mod.tp_getattro_impl(tx, "_buffers").realize() + tx.output.side_effects.ignore_mutations_on(self.old_parameters_var) + tx.output.side_effects.ignore_mutations_on(self.old_buffer_var) + return self.cm_vt.enter(tx) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + # Custom enter implementation with side effects. Additionally, do not + # worry about side effects for the hop, as they cancel each other out. + with torch._dynamo.variables.higher_order_ops.dynamo_allow_side_effects_in_hop( + tx + ): + x = self.cm_vt.exit(tx, *args) + tx.output.side_effects.stop_ignoring_mutations_on(self.old_buffer_var) + tx.output.side_effects.stop_ignoring_mutations_on(self.old_parameters_var) + return x + + # Forward all other method calls to self.cm_vt + def __getattr__(self, name: str) -> Any: + # This will be called for any attribute not explicitly defined in this class + return getattr(self.cm_vt, name) + + +class GradInplaceRequiresGradCtxManagerVariable(ContextWrappingVariable): + """represents torch grad requires grad""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", target_values: Any, **kwargs: Any + ) -> "GradInplaceRequiresGradCtxManagerVariable": + return GradInplaceRequiresGradCtxManagerVariable( + target_values=target_values, + initial_values=None, + **kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + [enabled] = self.target_values + self.prev_state = torch._C._functorch.get_inplace_requires_grad_allowed() + torch._C._functorch.set_inplace_requires_grad_allowed(enabled) + self.set_cleanup_hook( + tx, + lambda: torch._C._functorch.set_inplace_requires_grad_allowed( + self.prev_state + ), + ) + self.proxy = tx.output.create_node( + "call_function", + torch._C._functorch.set_inplace_requires_grad_allowed, + (enabled,), + {}, + ) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", + torch._C._functorch.set_inplace_requires_grad_allowed, + (self.prev_state,), + {}, + ) + return variables.ConstantVariable.create(None) + + +class TemporarilyPopInterpreterStackCtxManagerVariable(ContextWrappingVariable): + """represents torch._functorch.pyfunction.temporarily_pop_interpreter_stack()""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", target_values: Any, **kwargs: Any + ) -> "TemporarilyPopInterpreterStackCtxManagerVariable": + return TemporarilyPopInterpreterStackCtxManagerVariable( + target_values=target_values, + initial_values=None, + **kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self.saved = torch._C._functorch.pop_dynamic_layer_stack() + self.set_cleanup_hook( + tx, + lambda: torch._C._functorch.push_dynamic_layer_stack(self.saved), + ) + self.proxy = tx.output.create_node( + "call_function", + torch._C._functorch.pop_dynamic_layer_stack, + (), + {}, + ) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", + torch._C._functorch.push_dynamic_layer_stack, + (self.proxy,), + {}, + ) + return variables.ConstantVariable.create(None) + + +class JvpIncrementNestingCtxManagerVariable(ContextWrappingVariable): + """represents torch.func.jvp increment/decrement nesting""" + + # A guard is needed as the grad level is baked into the torch FX graph + # This is fine if jvp is only called from within the function + # being compiled. But the FX graph may be invalid in the case of a jvp + # call from eager that calls the compiled function, as the jvp levels + # may be different. + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.FUNCTORCH_STACK_MATCH) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", **kwargs: Any + ) -> "JvpIncrementNestingCtxManagerVariable": + var = JvpIncrementNestingCtxManagerVariable( + target_values=None, + initial_values=None, + **kwargs, + ) + return var + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + install_guard(self._guards_singleton) + jvp_level = torch._functorch.eager_transforms.enter_jvp_nesting() + self.set_cleanup_hook( + tx, lambda: torch._functorch.eager_transforms.exit_jvp_nesting() + ) + self.proxy = tx.output.create_node( + "call_function", + torch._functorch.predispatch._jvp_increment_nesting, + (), + {}, + ) + return variables.VariableTracker.build(tx, jvp_level) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", torch._functorch.predispatch._jvp_decrement_nesting, (), {} + ) + return variables.ConstantVariable.create(None) + + +class SetFwdGradEnabledContextManager(ContextWrappingVariable): + """represents torch.autograd.forward_ad._set_fwd_grad_enabled() to enable/disable fwd grad""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", target_values: Any, **kwargs: Any + ) -> "SetFwdGradEnabledContextManager": + return SetFwdGradEnabledContextManager( + target_values=target_values, + initial_values=None, + **kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + [mode] = self.target_values + self.prev_state = torch._C._is_fwd_grad_enabled() + torch._C._set_fwd_grad_enabled(mode) + self.set_cleanup_hook( + tx, + lambda: torch._C._set_fwd_grad_enabled(self.prev_state), + ) + self.proxy = tx.output.create_node( + "call_function", + torch._C._set_fwd_grad_enabled, + (mode,), + {}, + ) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", + torch._C._set_fwd_grad_enabled, + (self.prev_state,), + {}, + ) + return variables.ConstantVariable.create(None) + + def python_type(self) -> type: + return torch.autograd.forward_ad._set_fwd_grad_enabled + + +class DualLevelContextManager(ContextWrappingVariable): + """Represents torch.autograd.forward_ad.dual_level ctx manager""" + + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.DUAL_LEVEL) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", **kwargs: Any + ) -> "DualLevelContextManager": + return DualLevelContextManager( + target_values=None, + initial_values=None, + **kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + install_guard(self._guards_singleton) + self.new_level = torch.autograd.forward_ad.enter_dual_level() + self.set_cleanup_hook( + tx, lambda: torch.autograd.forward_ad.exit_dual_level(level=self.new_level) + ) + self.proxy = tx.output.create_node( + "call_function", + torch._functorch.predispatch._enter_dual_level, + (), + {}, + ) + return variables.VariableTracker.build(tx, self.new_level) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", + torch._functorch.predispatch._exit_dual_level, + (), + {"level": self.new_level}, + ) + return variables.ConstantVariable.create(None) + + def python_type(self) -> type: + return torch.autograd.forward_ad.dual_level + + +class GradIncrementNestingCtxManagerVariable(ContextWrappingVariable): + """represents torch.func.grad increment/decrement nesting""" + + # A guard is needed as the grad level is baked into the torch FX graph + # This is fine if grad is only called from within the function + # being compiled. But the FX graph may be invalid in the case of a grad + # call from eager that calls the compiled function, as the grad levels + # may be different. + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.FUNCTORCH_STACK_MATCH) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", **kwargs: Any + ) -> "GradIncrementNestingCtxManagerVariable": + var = GradIncrementNestingCtxManagerVariable( + target_values=None, + initial_values=None, + **kwargs, + ) + return var + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + install_guard(self._guards_singleton) + grad_level = torch._C._functorch._grad_increment_nesting() + self.set_cleanup_hook(tx, lambda: torch._C._functorch._grad_decrement_nesting()) + self.proxy = tx.output.create_node( + "call_function", + torch._C._functorch._grad_increment_nesting, + (), + {}, + ) + return variables.VariableTracker.build(tx, grad_level) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", torch._C._functorch._grad_decrement_nesting, (), {} + ) + return variables.ConstantVariable.create(None) + + +class CatchWarningsCtxManagerVariable(ContextWrappingVariable): + """Delay a call to warnings.catch_warnings""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", catch_warnings_args: dict[str, VariableTracker] + ) -> "CatchWarningsCtxManagerVariable": + return CatchWarningsCtxManagerVariable( + catch_warnings_args=catch_warnings_args, + target_values=None, + initial_values=None, + ) + + def __init__( + self, + catch_warnings_args: dict[str, VariableTracker], + target_values: Any | None = None, + initial_values: Any | None = None, + **kwargs: Any, + ) -> None: + if not isinstance(catch_warnings_args, dict): + raise AssertionError( + f"catch_warnings_args must be a dict, got {catch_warnings_args}" + ) + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + self.catch_warnings_args = catch_warnings_args + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + kwargs = { + k: v.as_python_constant() for k, v in self.catch_warnings_args.items() + } + ctx_val = warnings.catch_warnings(**kwargs) + self.set_cleanup_hook(tx, lambda: ctx_val.__exit__(None, None, None)) + return variables.VariableTracker.build(tx, ctx_val.__enter__()) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from("warnings", "catch_warnings") + ) + codegen.foreach(self.catch_warnings_args.values()) + keys = tuple(self.catch_warnings_args.keys()) + codegen.extend_output(codegen.create_call_function_kw(len(keys), keys, False)) + + def python_type(self) -> type: + return warnings.catch_warnings + + +class VmapIncrementNestingCtxManagerVariable(ContextWrappingVariable): + """represents torch VMap increment/decrement nesting""" + + # A guard is needed as the vmap level is baked into the torch FX graph + # generated. This is fine if vmap is only called from within the function + # being compiled. But the FX graph may be invalid in the case of a vmap + # call from eager that calls the compiled function, as the vmap levels + # may be different. + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.FUNCTORCH_STACK_MATCH) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + target_values: list[VariableTracker], + **kwargs: Any, + ) -> "VmapIncrementNestingCtxManagerVariable": + var = VmapIncrementNestingCtxManagerVariable( + target_values=target_values, + initial_values=None, + **kwargs, + ) + return var + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + install_guard(self._guards_singleton) + batch_size, randomness = self.target_values + if isinstance(batch_size, variables.SymNodeVariable): + batch_size_value = batch_size.sym_num + else: + batch_size_value = batch_size.as_python_constant() + randomness = randomness.as_python_constant() + vmap_level = torch._C._functorch._vmap_increment_nesting( + batch_size_value, randomness + ) + self.set_cleanup_hook(tx, lambda: torch._C._functorch._vmap_decrement_nesting()) + self.proxy = tx.output.create_proxy( + "call_function", + torch._functorch.predispatch._vmap_increment_nesting, + (batch_size.as_proxy(), randomness), + {}, + ) + return variables.VariableTracker.build(tx, vmap_level) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", + torch._functorch.predispatch._vmap_decrement_nesting, + (), + {}, + ) + return variables.ConstantVariable.create(None) + + +class GradModeVariable(ContextWrappingVariable): + """represents torch.{no_grad,enable_grad,set_grad_mode}()""" + + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.GRAD_MODE) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + target_value: Any, + initialized: bool = False, + **kwargs: Any, + ) -> "GradModeVariable": + var = GradModeVariable( + target_values=[target_value], + initial_values=[torch.is_grad_enabled()], + **kwargs, + ) + if initialized: + var._call_func(tx, var.target_values) + return var + + def __init__( + self, + target_values: Any, + initial_values: Sequence[bool] | None = None, + initialized: bool = True, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + install_guard(self._guards_singleton) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self._call_func(tx, self.target_values) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self._call_func(tx, self.initial_values) + return variables.ConstantVariable.create(None) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + self._call_func(tx, self.initial_values) # undo eager initialization + return super().call_function(tx, args, kwargs) + + def _call_func(self, tx: "InstructionTranslatorBase", values: Any) -> None: + if len(values) != 1: + raise AssertionError(f"expected 1 value, got {len(values)}") + value = values[0] + # Coalesce grad mode mutations + if torch.is_grad_enabled() != value: + tx.output.create_node( + "call_function", torch._C._set_grad_enabled, (value,), {} + ) + torch._C._set_grad_enabled(value) + + def module_name(self) -> str: + return "torch" + + def fn_name(self) -> str: + return "set_grad_enabled" + + def python_type(self) -> type: + return torch.set_grad_enabled + + +class InferenceModeVariable(ContextWrappingVariable): + @staticmethod + def create( + tx: "InstructionTranslatorBase", target_value: Any, **kwargs: Any + ) -> "InferenceModeVariable": + var = InferenceModeVariable( + [target_value], initial_values=torch.is_inference_mode_enabled(), **kwargs + ) + return var + + def __init__( + self, + target_values: Any, + initial_values: bool | None = None, + **kwargs: Any, + ) -> None: + if initial_values is None: + # This must be called here since function defaults are evaluated at import time + initial_values = torch.is_inference_mode_enabled() + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup_assert() + tx.output.create_node( + "call_function", + torch.autograd.grad_mode._exit_inference_mode, + (self.proxy,), + {}, + ) + return variables.ConstantVariable.create(None) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + disabled_inference_mode_forcibly = False + if ( + torch._dynamo.config.fake_tensor_disable_inference_mode + and self.target_values[0] + ): + # Do not set the inference mode because we keep it off during + # compilation. Set the grad_enabled to False to reflect the relevant + # part of inference_mode to torch.compile. + disabled_inference_mode_forcibly = True + prior = torch.is_grad_enabled() + torch._C._set_grad_enabled(False) + else: + ctx = torch.autograd.grad_mode._enter_inference_mode(*self.target_values) + + def cleanup_hook() -> None: + if disabled_inference_mode_forcibly: + torch._C._set_grad_enabled(prior) + else: + torch.autograd.grad_mode._exit_inference_mode(ctx) + + self.set_cleanup_hook(tx, cleanup_hook) + self.proxy = tx.output.create_node( + "call_function", + torch.autograd.grad_mode._enter_inference_mode, + (*self.target_values,), + {}, + ) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "torch" + + def fn_name(self) -> str: + return "inference_mode" + + def python_type(self) -> type: + return torch.inference_mode + + +class GenericDeviceVariable(ContextWrappingVariable): + """Abstract base for device context managers that swap the active device index.""" + + _exchange_fn: Any + _maybe_exchange_fn: Any + _get_device_index_fn: Any + + @classmethod + def create( + cls, tx: "InstructionTranslatorBase", device: Any, **kwargs: Any + ) -> "GenericDeviceVariable": + return cls( + target_values=[cls._get_device_index_fn(device, optional=True)], + initial_values=None, + **kwargs, + ) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup_assert() + tx.output.create_node( + "call_function", + self._maybe_exchange_fn, + (self.proxy,), + {}, + ) + return variables.ConstantVariable.create(False) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + prev_idx = self._exchange_fn(*self.target_values) + self.set_cleanup_hook(tx, lambda: self._maybe_exchange_fn(prev_idx)) + self.proxy = tx.output.create_node( + "call_function", + self._exchange_fn, + (*self.target_values,), + {}, + ) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + raise NotImplementedError + + def fn_name(self) -> str: + return "device" + + def python_type(self) -> type: + raise NotImplementedError + + +class CUDADeviceVariable(GenericDeviceVariable): + """represents torch.cuda.device""" + + _exchange_fn = staticmethod(torch.cuda._exchange_device) + _maybe_exchange_fn = staticmethod(torch.cuda._maybe_exchange_device) + _get_device_index_fn = staticmethod(torch.cuda._get_device_index) + + def module_name(self) -> str: + return "torch.cuda" + + def python_type(self) -> type: + return torch.cuda.device + + +class XPUDeviceVariable(GenericDeviceVariable): + """represents torch.xpu.device""" + + _exchange_fn = staticmethod(torch.xpu._exchange_device) + _maybe_exchange_fn = staticmethod(torch.xpu._maybe_exchange_device) + _get_device_index_fn = staticmethod(torch.xpu._get_device_index) + + def module_name(self) -> str: + return "torch.xpu" + + def python_type(self) -> type: + return torch.xpu.device + + +class AcceleratorDeviceIndexVariable(GenericDeviceVariable): + """represents torch.accelerator.device_index""" + + _exchange_fn = staticmethod(torch._C._accelerator_exchangeDevice) + _maybe_exchange_fn = staticmethod(torch._C._accelerator_maybeExchangeDevice) + _get_device_index_fn = staticmethod(lambda device, **kwargs: device) + + def module_name(self) -> str: + return "torch.accelerator" + + def fn_name(self) -> str: + return "device_index" + + def python_type(self) -> type: + return torch.accelerator.device_index + + +_device_context_manager_map: dict[type, type[GenericDeviceVariable]] = { + torch.cuda.device: CUDADeviceVariable, + torch.xpu.device: XPUDeviceVariable, + torch.accelerator.device_index: AcceleratorDeviceIndexVariable, +} + + +def register_device_context_manager( + device_context: type, variable_cls: type[GenericDeviceVariable] +) -> None: + """Register a Dynamo variable class for a device context manager type. + + Raises ``ValueError`` if ``device_context`` is already registered. + """ + if device_context in _device_context_manager_map: + raise ValueError( + f"Device context {device_context} already has a registered context manager" + ) + _device_context_manager_map[device_context] = variable_cls + + +def get_device_context_manager( + device_context: type, +) -> type[GenericDeviceVariable] | None: + """Return the Dynamo variable class for ``device_context``, or ``None`` if not registered.""" + return _device_context_manager_map.get(device_context) + + +class TorchFunctionDisableVariable(ContextWrappingVariable): + """represents whether torch function overrides are enabled or not""" + + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.TORCH_FUNCTION_STATE) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", **kwargs: Any + ) -> "TorchFunctionDisableVariable": + var = TorchFunctionDisableVariable( + tx, + target_values=[], + initial_values=[], + **kwargs, + ) + return var + + def __init__( + self, + tx: "InstructionTranslatorBase", + target_values: Sized, + initial_values: Sized | None = None, + only_subclass: bool = True, + **kwargs: Any, + ) -> None: + if len(target_values) != 0: + raise AssertionError(f"expected 0 target_values, got {len(target_values)}") + if initial_values is None: + raise AssertionError("initial_values must not be None") + if len(initial_values) != 0: + raise AssertionError( + f"expected 0 initial_values, got {len(initial_values)}" + ) + self.only_subclass = only_subclass + self.initial_torch_function_subclass_enabled = ( + tx.symbolic_torch_function_state.torch_function_subclass_enabled + ) + self.initial_torch_function_mode_enabled = ( + tx.symbolic_torch_function_state.torch_function_mode_enabled + ) + + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + install_guard(self._guards_singleton) + + def set_cleanup_hook( + self, + tx: "InstructionTranslatorBase", + fn: Callable[..., Any] | None = None, + ) -> None: + if fn is None: + + def fn() -> None: + tx.symbolic_torch_function_state.torch_function_subclass_enabled = ( + self.initial_torch_function_subclass_enabled + ) + if not self.only_subclass: + tx.symbolic_torch_function_state.torch_function_mode_enabled = ( + self.initial_torch_function_mode_enabled + ) + + self.cleanup_fn = fn + tx.output.add_cleanup_hook(self.cleanup) + + def _call_func(self, tx: "InstructionTranslatorBase", values: Sized) -> None: + if len(values) != 0: + raise AssertionError(f"expected 0 values, got {len(values)}") + tx.symbolic_torch_function_state.torch_function_subclass_enabled = False + if not self.only_subclass: + tx.symbolic_torch_function_state.torch_function_mode_enabled = False + + def module_name(self) -> str: + return "torch._C" + + def fn_name(self) -> str: + if self.only_subclass: + return "DisableTorchFunctionSubclass" + return "DisableTorchFunction" + + def python_type(self) -> type: + if self.only_subclass: + return torch._C.DisableTorchFunctionSubclass # pyrefly: ignore[bad-return] + return torch._C.DisableTorchFunction # pyrefly: ignore[bad-return] + + +class DisabledSavedTensorsHooksVariable(ContextWrappingVariable): + """represents torch.autograd.graph.disable_saved_tensors_hook.""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", target_value: str | None, **kwargs: Any + ) -> "DisabledSavedTensorsHooksVariable": + var = DisabledSavedTensorsHooksVariable( + target_values=[target_value], + initial_values=[ + torch._C._autograd._saved_tensors_hooks_get_disabled_error_message() + ], + **kwargs, + ) + var._call_func(tx, [target_value]) + var.set_cleanup_hook(tx) + return var + + def __init__( + self, + target_values: Sequence[str | None], + initial_values: Sequence[str | None] | None = None, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return variables.ConstantVariable.create(None) + + def _call_func( + self, tx: "InstructionTranslatorBase", values: Sequence[str | None] + ) -> None: + if len(values) != 1: + raise AssertionError(f"expected 1 value, got {len(values)}") + value = values[0] + if value is not None: + # Disable `saved_tensors_hooks` with message (`value`) + # OR + # we are exiting this context and restoring the previous message. + tx.output.create_node( + "call_function", + torch._C._autograd._saved_tensors_hooks_disable, + (value,), + {}, + ) + torch._C._autograd._saved_tensors_hooks_disable(value) + else: + # We are exiting this context and if prev_message was None, we re-enable `saved_tensors_hooks`. + tx.output.create_node( + "call_function", torch._C._autograd._saved_tensors_hooks_enable, (), {} + ) + torch._C._autograd._saved_tensors_hooks_enable() + + def module_name(self) -> str: + return "torch.autograd.graph" + + def fn_name(self) -> str: + return "disable_saved_tensors_hooks" + + def python_type(self) -> type: + return contextlib._GeneratorContextManager + + +class AutocastModeVariable(ContextWrappingVariable): + @staticmethod + def create( + func: torch.amp.autocast_mode.autocast, + args: Sequence[Any], + kwargs: dict[str, Any], + ) -> "AutocastModeVariable": + if func not in [ + torch.amp.autocast_mode.autocast, + torch.cuda.amp.autocast, + torch.cpu.amp.autocast, + ]: + raise AssertionError(f"unexpected autocast function: {func}") + # device_type : str, + # dtype : Optional[_dtype] = None, + # enabled : bool = True, + # cache_enabled : Optional[bool] = None):cache_enabled + bound_args = inspect.signature(func).bind(*args, **kwargs) + bound_args.apply_defaults() + target_values = [] + kwargs.clear() + + for key in ["device_type", "dtype", "enabled", "cache_enabled"]: + if key == "device_type" and func in [ + torch.cuda.amp.autocast, + torch.cpu.amp.autocast, + ]: + # pyrefly: ignore [unnecessary-comparison] + arg = "cuda" if func is torch.cuda.amp.autocast else "cpu" + else: + arg = bound_args.arguments[key] + if isinstance(arg, VariableTracker): + target_values.append(arg.as_python_constant()) + else: + target_values.append(arg) + + var = AutocastModeVariable(target_values, initial_values=None, **kwargs) + return var + + def __init__( + self, + target_values: Sequence[Any], + initial_values: Any | None = None, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup_assert() + tx.output.create_node( + "call_function", torch.amp._exit_autocast, (self.proxy,), {} + ) + return variables.ConstantVariable.create(None) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + ctx = torch.amp._enter_autocast(*self.target_values) + self.set_cleanup_hook(tx, lambda: torch.amp._exit_autocast(ctx)) + self.proxy = tx.output.create_node( + "call_function", torch.amp._enter_autocast, (*self.target_values,), {} + ) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "torch.amp.autocast_mode" + + def fn_name(self) -> str: + return "autocast" + + def python_type(self) -> type: + return torch.amp.autocast_mode.autocast + + +class NullContextVariable(ContextWrappingVariable): + """ + This class represents Python contextlib.nullcontext. + """ + + def __init__( + self, enter_result: VariableTracker | None = None, **kwargs: Any + ) -> None: + self.enter_result = enter_result + super().__init__(target_values=(), **kwargs) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self.enter_result is None: + return variables.ConstantVariable.create(None) + return self.enter_result + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "contextlib" + + def fn_name(self) -> str: + return "nullcontext" + + def python_type(self) -> type: + return contextlib.nullcontext + + +class ProfilerContextVariable(ContextWrappingVariable): + """ + This class represents a set of torch profiler context objects, where Dynamo + ignores all the side-effects in the __init__, __enter__ and __exit__ methods + by treating the object mostly as a `contextlib.nullcontext`, except for edge + cases like the `__enter__` method which returns the object itself rather + than `None`, per implementation of the torch objects. + """ + + def __init__(self, **kwargs: Any) -> None: + super().__init__(target_values=None, **kwargs) + + def python_type(self) -> type: + return torch.profiler.profile + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "contextlib" + + def fn_name(self) -> str: + return "nullcontext" + + def reconstruct(self, codegen: "PyCodegen") -> None: + unimplemented( + gb_type="torch.profiler object escaped from compiled region", + context=str(self), + explanation="Dynamo doesn't support compiling a region that returns a torch.profiler context manager.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + +class ProfilerRecordFunctionContextVariable(ContextWrappingVariable): + """ + This class represents torch profiler context objects. + + For record_function: emits torch.ops.profiler._record_function_enter_new + to the graph on enter, and torch.ops.profiler._record_function_exit on exit. + But if emit_profiler_ops=False, behaves like nullcontext. + + For profile: behaves like nullcontext, ignoring all side-effects. + """ + + _nonvar_fields = { + "emit_profiler_ops", + *ContextWrappingVariable._nonvar_fields, + } + + @staticmethod + def create( + func: Any, + record_args: list[VariableTracker], + record_kwargs: "dict[str, VariableTracker]", + **kwargs: Any, + ) -> "ProfilerRecordFunctionContextVariable": + target_values = None + if config.capture_profiler_record_function: + # Extract name and args for record_function + # record_function(name: str, args: Optional[str] = None) + name = ( + record_args[0].as_python_constant() + if record_args + else record_kwargs.get( + "name", variables.ConstantVariable.create("unknown") + ).as_python_constant() + ) + record_args_const = None + if len(record_args) > 1: + record_args_const = record_args[1].as_python_constant() + elif "args" in record_kwargs: + record_args_const = record_kwargs["args"].as_python_constant() + target_values = [name, record_args_const] + else: + warning_once(log, "Profiler record function %s will be ignored", func) + return ProfilerRecordFunctionContextVariable( + target_values=target_values, + initial_values=None, + **kwargs, + ) + + def __init__( + self, + target_values: Any = None, + initial_values: Any | None = None, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + + def python_type(self) -> type: + return torch.autograd.profiler.record_function + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if config.capture_profiler_record_function: + name, args = self.target_values + # Create the profiler entry node in the graph + self.proxy = tx.output.create_node( + "call_function", + torch.ops.profiler._record_function_enter_new, + (name, args), + {}, + ) + return self + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + if config.capture_profiler_record_function: + # Create the profiler exit node in the graph + tx.output.create_node( + "call_function", + torch.ops.profiler._record_function_exit._RecordFunction, + (self.proxy,), + {}, + ) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return ( + "torch.autograd.profiler" + if config.capture_profiler_record_function + else "contextlib" + ) + + def fn_name(self) -> str: + return ( + "record_function" + if config.capture_profiler_record_function + else "nullcontext" + ) + + def reconstruct_type(self, codegen: "PyCodegen") -> None: + # This will be called if we try to reconstruct the record_function type + # when there's a graph break. The _set_error_on_graph_break(True) in enter() + # will cause the graph break to raise an error before we get here. + if config.capture_profiler_record_function: + unimplemented( + gb_type="record_function escaped from compiled region", + context=str(self), + explanation="Dynamo doesn't support graph break inside record_function region.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + else: + # If capture is disabled, allow reconstruction (behaves like nullcontext) + super().reconstruct_type(codegen) + + +class PreserveVersionContextVariable(ContextWrappingVariable): + """ + Wraps torch.autograd._unsafe_preserve_version_counter + """ + + @staticmethod + def _create_lambda_from_tensors( + tx: "InstructionTranslatorBase", + tensors: VariableTracker, + ) -> "PreserveVersionContextVariable": + if tensors.is_tensor(): + versions = variables.TupleVariable( + [x.tp_getattro_impl(tx, "_version") for x in [tensors]] + ) + tensors_tuple = variables.TupleVariable([tensors]) + else: + if not isinstance(tensors, variables.TupleVariable): + raise AssertionError( + f"tensors must be a TupleVariable, got {type(tensors)}" + ) + versions = variables.TupleVariable( + [x.tp_getattro_impl(tx, "_version") for x in tensors.items] + ) + tensors_tuple = tensors + return PreserveVersionContextVariable(tensors_tuple, versions) + + @staticmethod + def constructor(tx: "InstructionTranslatorBase") -> VariableTracker: + return variables.LambdaVariable( + lambda tensors: PreserveVersionContextVariable._create_lambda_from_tensors( + tx, tensors + ) + ) + + def __init__( + self, + tensors: VariableTracker, + prev_versions: VariableTracker, + **kwargs: Any, + ) -> None: + kwargs.setdefault("target_values", None) + super().__init__(**kwargs) + self.tensors = tensors + self.prev_versions = prev_versions + # The context manager accepts Union[Tensor, Tuple[Tensor]] + if self.tensors.is_tensor(): + self.tensors = variables.TupleVariable([self.tensors]) + if self.prev_versions.is_symnode_like(): + self.prev_versions = variables.TupleVariable([self.prev_versions]) + + def python_type(self) -> type: + return torch.autograd.grad_mode._unsafe_preserve_version_counter + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + from ..tensor_version_op import _unsafe_set_version_counter + + return variables.TorchInGraphFunctionVariable( + _unsafe_set_version_counter + ).call_function(tx, [self.tensors, self.prev_versions], {}) + + def reconstruct(self, codegen: "PyCodegen") -> None: + unimplemented( + gb_type="torch.autograd._unsafe_preserve_version_counter escaped from compiled region", + context=str(self), + explanation=( + "Dynamo doesn't support compiling a region that returns " + "a torch.autograd._unsafe_preserve_version_counter context manager." + ), + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + +class FSDPParamGroupUseTrainingStateVariable(ContextWrappingVariable): + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.FSDP_TRAINING_STATE) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + param_group_var: Any, + target_value: Any, + **kwargs: Any, + ) -> "FSDPParamGroupUseTrainingStateVariable": + var = FSDPParamGroupUseTrainingStateVariable( + param_group_var=param_group_var, + target_values=[target_value], + initial_values=[param_group_var.value._training_state], + **kwargs, + ) + return var + + def __init__( + self, + param_group_var: Any, + target_values: Sequence[Any], + initial_values: Sequence[Any] | None = None, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + self.param_group_var = param_group_var + install_guard(self._guards_singleton) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self._call_func(tx, self.target_values) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self._call_func(tx, self.initial_values) # type: ignore[arg-type] + return variables.ConstantVariable.create(None) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # undo eager initialization + self._call_func(tx, self.initial_values) # type: ignore[arg-type] + return super().call_function(tx, args, kwargs) + + def _call_func( + self, tx: "InstructionTranslatorBase", values: Sequence[Any] + ) -> None: + if len(values) != 1: + raise AssertionError(f"expected 1 value, got {len(values)}") + value = values[0] + if self.param_group_var.value._training_state != value: + self.param_group_var.call_method( + tx, + "__setattr__", + ( + variables.VariableTracker.build(tx, "_training_state"), + variables.VariableTracker.build(tx, value), + ), + {}, + ) + self.param_group_var.value._training_state = value + + def module_name(self) -> str: + return "torch.distributed.fsdp._fully_shard._fsdp_param_group.FSDPParamGroup" + + def fn_name(self) -> str: + return "use_training_state" + + +class SDPAKernelVariable(ContextWrappingVariable): + """represents torch.nn.attention.sdpa_kernel""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + backends: Any, + set_priority: bool = False, + **kwargs: Any, + ) -> "SDPAKernelVariable": + if isinstance(backends, torch.nn.attention.SDPBackend): + backends = [backends] + var = SDPAKernelVariable( + target_values=backends, + initial_values=None, + set_priority=set_priority, + **kwargs, + ) + return var + + def __init__( + self, + target_values: list[torch.nn.attention.SDPBackend], + initial_values: Any = None, + set_priority: bool = False, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + self.set_priority = set_priority + + @staticmethod + def _backends_to_nodes( + tx: "InstructionTranslatorBase", + backends: list[Any], + ) -> list[Any]: + # convert to/from string in order to bake the backend into FX graph + nodes = [ + tx.output.create_node( + "call_function", + torch.nn.attention._backend_from_string, + (backend.name,), + {}, + ) + for backend in backends + ] + return nodes + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self.prev_backends = torch.nn.attention._cur_sdpa_kernel_backends( + with_priority=self.set_priority + ) + self.set_cleanup_hook( + tx, + lambda: torch.nn.attention._sdpa_kernel( + self.prev_backends, set_priority=self.set_priority + ), + ) + torch.nn.attention._sdpa_kernel( + self.target_values, set_priority=self.set_priority + ) + arg = self._backends_to_nodes(tx, self.target_values) + tx.output.create_node( + "call_function", + torch.nn.attention._sdpa_kernel, + (arg, bool(self.set_priority)), + {}, + ) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup_assert() + arg = self._backends_to_nodes(tx, self.prev_backends) + tx.output.create_node( + "call_function", + torch.nn.attention._sdpa_kernel, + (arg, bool(self.set_priority)), + {}, + ) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "torch.nn.attention" + + # use a private version of sdpa_kernel that accepts variadic arguments + # since dynamo reconstructs the contents of target_values one-by-one + def fn_name(self) -> str: + return "_sdpa_kernel_variadic" + + def python_type(self) -> type: + return contextlib._GeneratorContextManager + + +class FxTracebackAnnotateVariable(ContextWrappingVariable): + """ + fx.traceback.annotate is a context manager that allows users to annotate the + fx graph nodes with custom metadata. In the context of Dynamo, we don't have + to trace the body of the context manager. Instead we want to directly run + the body of the context manager, so the Dynamo created Fx graphs have the + right custom metadata. This variable tracker just runs __enter__ and + __exit__ method (instead of tracing). + """ + + _nonvar_fields = { + "annotation", + *ContextWrappingVariable._nonvar_fields, + } + + def __init__( + self, annotation: dict[str, Any], initial_values: Any = None, **kwargs: Any + ) -> None: + self.annotation = annotation + super().__init__(target_values=(), initial_values=initial_values, **kwargs) + + def enter( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + # Run the annotation ctx manager in eager. Also ensure that + # preserve_node_meta context manager is setup. This is important to pass + # on the metadata to the create_proxy nodes. + stack = ExitStack() + stack.enter_context(torch.fx.traceback.annotate(self.annotation)) + stack.enter_context(torch.fx.traceback.preserve_node_meta()) + self.set_cleanup_hook(tx, lambda: stack.close()) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "torch.fx.traceback" + + def fn_name(self) -> str: + return "annotate" + + def python_type(self) -> type: + return contextlib._GeneratorContextManager + + def reconstruct_type(self, codegen: "PyCodegen") -> None: + unimplemented( + gb_type="torch.fx.traceback.annotate escaped from compiled region", + context=str(self), + explanation="Dynamo doesn't support graph break on torch.fx.traceback.annotate.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + +class DynamoConfigPatchVariable(ContextWrappingVariable): + """represents torch._dynamo.patch_dynamo_config""" + + # NOTE: no need to guard on dynamo config because dynamo config should not affect soundness + # (though it may affect tracing behavior) + def __init__(self, target_values: dict[str, Any], **kwargs: Any) -> None: + target_values_tuple = tuple(target_values.items()) + super().__init__( + target_values=(target_values_tuple,), initial_values=None, **kwargs + ) + # pyrefly: ignore [implicit-any] + initial_values_dict = {} + for key, _ in target_values_tuple: + initial_values_dict[key] = torch._dynamo.config.__getattr__(key) # type: ignore[attr-defined] + self.initial_values = (tuple(initial_values_dict.items()),) + + def _call_func(self, tx: "InstructionTranslatorBase", values: Any) -> None: + if len(values) != 1: + raise AssertionError(f"expected 1 value, got {len(values)}") + value = values[0] + # manually patch dynamo config + for key, val in value: + torch._dynamo.config.__setattr__(key, val) # type: ignore[attr-defined] + # No need to keep track of global side effects because + # dynamo will properly restore this context manager for + # unsupported instructions and continuation functions. + # Dynamo config also should not affect the semantics of the compiled graph. + + def module_name(self) -> str: + return "torch._dynamo" + + def fn_name(self) -> str: + return "patch_dynamo_config" + + def python_type(self) -> type: + from torch._dynamo.decorators import DynamoConfigPatchProxy + + return DynamoConfigPatchProxy + + +class ErrorOnGraphBreakVariable(ContextWrappingVariable): + """represents torch._dynamo.error_on_graph_break""" + + def __init__(self, error_on_graph_break: bool, **kwargs: Any) -> None: + super().__init__( + target_values=(error_on_graph_break,), + initial_values=(_get_error_on_graph_break(),), + **kwargs, + ) + + def _call_func( + self, tx: "InstructionTranslatorBase", values: Sequence[bool] + ) -> None: + if len(values) != 1: + raise AssertionError(f"expected 1 value, got {len(values)}") + _set_error_on_graph_break(values[0]) + + def module_name(self) -> str: + return "torch._dynamo" + + def fn_name(self) -> str: + return "error_on_graph_break" + + def python_type(self) -> type: + from torch._dynamo.decorators import ErrorOnGraphBreakDecoratorContextManager + + return ErrorOnGraphBreakDecoratorContextManager + + +class CudagraphOverrideVariable(ContextWrappingVariable): + """represents torch._dynamo.override_cudagraphs""" + + def __init__(self, fwd: bool | None, bwd: bool | None, **kwargs: Any) -> None: + super().__init__( + target_values=(fwd, bwd), + initial_values=None, # Captured in enter() + **kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # Capture current annotation before overwriting + prev = tx.output.cudagraph_annotation + if prev is not None: + self.initial_values = (prev.fwd, prev.bwd) + else: + self.initial_values = (None,) + return super().enter(tx) + + def _call_func( + self, tx: "InstructionTranslatorBase", values: tuple[Any, ...] + ) -> None: + from torch._inductor import _CudagraphAnnotation + + if len(values) == 1 and values[0] is None: + # Restoring to no annotation + tx.output.cudagraph_annotation = None + tx.output.tracing_context.cudagraph_annotation = None + else: + if len(values) != 2: + raise AssertionError(f"expected 2 values, got {len(values)}") + fwd, bwd = values + annotation = _CudagraphAnnotation(fwd=fwd, bwd=bwd) + tx.output.cudagraph_annotation = annotation + tx.output.tracing_context.cudagraph_annotation = annotation + + def module_name(self) -> str: + return "torch._dynamo" + + def fn_name(self) -> str: + return "override_cudagraphs" + + def python_type(self) -> type: + from torch._dynamo.decorators import CudagraphOverrideContextManager + + return CudagraphOverrideContextManager + + def exit_on_graph_break(self) -> bool: + # Annotation persists until graph is compiled; each resume function + # will reconstruct the context manager and call enter() again + return False + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> "VariableTracker": + # Override to NOT call cleanup here. The cleanup will happen in + # call_cleanup_hooks() during compile_subgraph, which is AFTER + # the annotation is copied to gm.meta. + return variables.ConstantVariable.create(None) + + +class WithEnterFunctionVariable(VariableTracker): + def __init__( + self, + ctx: ContextWrappingVariable | GenericContextWrappingVariable, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.ctx = ctx + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def python_type(self) -> type: + return types.MethodType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if args: + raise AssertionError( + "WithEnterFunctionVariable.call_function expects no args" + ) + if kwargs: + raise AssertionError( + "WithEnterFunctionVariable.call_function expects no kwargs" + ) + # NOTE: we assume that the instruction immediately after the current CALL instruction + # is the first instruction of the block. + + return tx.enter_ctx(self.ctx, tx.current_instruction) + + def reconstruct(self, codegen: "PyCodegen") -> None: + try: + type_str = f"{self.ctx.module_name()}.{self.ctx.fn_name()}" + except NotImplementedError: + type_str = str(type(self.ctx)) + unimplemented( + gb_type="Attempted to reconstruct context manager's __enter__ method", + context=str(self.ctx), + explanation=f"Attempted to reconstruct context manager {type_str} while tracing `with ...:`", + hints=[ + "It is likely there is a graph break while tracing `with ctx:` " + "but outside the actual `ctx.__enter__()` method. " + "`torch.compile` does not expect this to happen.", + *graph_break_hints.DIFFICULT, + *graph_break_hints.DYNAMO_BUG, + ], + ) + + +class WithExitFunctionVariable(VariableTracker): + _nonvar_fields = { + "target", + *VariableTracker._nonvar_fields, + } + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def __init__( + self, + ctx: ContextWrappingVariable | GenericContextWrappingVariable, + target: Any, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance( + ctx, (ContextWrappingVariable, GenericContextWrappingVariable) + ): + raise AssertionError( + f"ctx must be a ContextWrappingVariable or GenericContextWrappingVariable, got {type(ctx)}" + ) + self.ctx = ctx + self.target = target + + def python_type(self) -> type: + return types.MethodType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if kwargs: + raise AssertionError( + "WithExitFunctionVariable.call_function expects no kwargs" + ) + return self.ctx.exit(tx, *args) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Note here we reconstruct the context manager rather than the + # exit function. The handler generated by BlockStackEntry + # will re-enter the context in the resume function. + self.ctx.reconstruct_type(codegen) # type: ignore[union-attr] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/dicts.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/dicts.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3d143b249dd21c99ff10be47814748307c95f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/dicts.py @@ -0,0 +1,1767 @@ +""" +Dictionary-related variable tracking classes for PyTorch Dynamo. + +This module implements variable tracking for different types of dictionary-like objects: +- Regular Python dictionaries (dict) +- Ordered dictionaries (collections.OrderedDict) +- Default dictionaries (collections.defaultdict) +- Dictionary views (keys and values) + +These classes are responsible for tracking dictionary operations during graph compilation, +maintaining proper guards for dictionary mutations and key existence checks. They handle +dictionary creation, modification, key/value access, and view operations while ensuring +correct behavior in the compiled code through appropriate guard installation. + +The implementation uses a special HashableTracker wrapper to handle +dictionary keys while preserving proper aliasing semantics. Set-related classes live +in sets.py. +""" + +import collections +import functools +import sys +import types +from collections.abc import Callable, Iterator +from typing import Any, cast, TYPE_CHECKING, Union + +from torch.utils._pytree import MappingKey + +from .. import graph_break_hints, polyfills, variables +from ..bytecode_transformation import ( + create_call_function, + create_call_method, + create_dup_top, + create_instruction, +) +from ..exc import raise_observed_exception, raise_type_error, unimplemented +from ..guards import GuardBuilder, install_guard +from ..source import ( + AttrSource, + DictGetItemSource, + is_constant_source, + is_from_local_source, +) +from ..utils import ( + _item_debug_repr, + cmp_name_to_op_mapping, + dict_items, + dict_keys, + dict_values, + istype, + raise_args_mismatch, + tracked_repr, + unpack_iterable, +) +from .base import ( + AttributeMutationExisting, + AttributeMutationNew, + AttrMutationKind, + Method, + NO_SUCH_SUBOBJ, + ValueMutationNew, + VariableTracker, +) +from .constant import ConstantVariable +from .hashable import HashableTracker, is_hashable, raise_unhashable +from .object_protocol import ( + _is_method_type, + generic_getitem, + generic_richcompare_bool, + mro_lookup, +) + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from .functions import UserFunctionVariable + + +# [Adding a new supported class within the keys of ConstDictVariable] +# - Implement hash_impl(self, tx) on the VariableTracker subclass (or rely on the +# base class default which uses get_real_python_backed_value()) +# - Implement tp_richcompare_impl() for key equality + + +def pydict_check(obj: VariableTracker) -> bool: + # This is a simplified version of the CPython's PyDict_Check function: + return issubclass(obj.python_type(), dict) + + +def _is_set_or_dictview(obj: VariableTracker) -> bool: + """PyAnySet_Check(other) || PyDictViewSet_Check(other)""" + try: + t = obj.python_type() + except NotImplementedError: + return False + return issubclass(t, (set, frozenset, dict_keys, dict_items)) + + +class ConstDictVariable(VariableTracker): + # PyDict_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L4825 + _cpython_type = dict + + CONTAINS_GUARD = GuardBuilder.DICT_CONTAINS + NOT_CONTAINS_GUARD = GuardBuilder.DICT_NOT_CONTAINS + + _nonvar_fields = { + "_checking_python_constant", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + items: dict[VariableTracker, VariableTracker], + **kwargs: Any, + ) -> None: + # .clone() pass these arguments in kwargs but they're recreated a few + # lines below + if "original_items" in kwargs: + kwargs.pop("original_items") + if "should_reconstruct_all" in kwargs: + kwargs.pop("should_reconstruct_all") + if "_checking_python_constant" in kwargs: + kwargs.pop("_checking_python_constant") + + super().__init__(**kwargs) + + Hashable = HashableTracker + + # Keys will just be HashableTrackers when cloning, in any other case they'll be VariableTrackers + if not all( + isinstance(x, (VariableTracker, Hashable)) + and isinstance(v, VariableTracker) + for x, v in items.items() + ): + raise AssertionError( + "All keys must be VariableTracker or HashableTracker " + "and all values must be VariableTracker" + ) + + def make_hashable( + key: Union[VariableTracker, "HashableTracker"], + ) -> "HashableTracker": + return key if isinstance(key, Hashable) else Hashable(key) + + items_cls = cast(type, self._cpython_type) + self.items = items_cls({make_hashable(x): v for x, v in items.items()}) + # need to reconstruct everything if the dictionary is an intermediate value + # or if a pop/delitem was executed + self.should_reconstruct_all = ( + not is_from_local_source(self.source) if self.source else True + ) + self.original_items = items.copy() + # Re-entrancy guard for is_python_constant against self-referential + # dicts (d[k] = d, directly or via an OrderedDict/defaultdict wrapper + # whose _base_vt is this instance). Both forms re-enter this same + # instance's is_python_constant, so a per-instance flag suffices. + self._checking_python_constant = False + + def as_proxy(self) -> dict[Any, Any]: + return {k.vt.as_proxy(): v.as_proxy() for k, v in self.items.items()} + + def debug_repr(self) -> str: + items: list[str] = [] + for k, v in self.items.items(): + key_str = _item_debug_repr(k.vt) + val_str = _item_debug_repr(v) + items.append(f"{key_str}: {val_str}") + return "{" + ", ".join(items) + "}" + + def is_python_constant(self) -> bool: + # Avoid the base implementation, which probes as_python_constant() and + # thus rebuilds a real dict, re-hashing the keys (wrong for keys with a + # side-effecting __hash__). Check element constness directly instead. + # Re-entrancy guard: a self-referential dict (d[k] = d, directly or via + # an OrderedDict/defaultdict wrapper delegating to this _base_vt) would + # otherwise recurse forever. A cyclic dict is not a flat python + # constant; return False so reconstruct handles the cycle. + if self._checking_python_constant: + return False + self._checking_python_constant = True + try: + return all( + k.vt.is_python_constant() and v.is_python_constant() + for k, v in self.items.items() + ) + finally: + self._checking_python_constant = False + + def as_python_constant(self) -> dict[Any, Any]: + return { + k.vt.as_python_constant(): v.as_python_constant() + for k, v in self.items.items() + } + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + items = [ + f"{tracked_repr(tx, key.vt)}: {tracked_repr(tx, value)}" + for key, value in self.items.items() + ] + return VariableTracker.build(tx, "{" + ", ".join(items) + "}") + + def keys_as_python_constant(self) -> dict[Any, VariableTracker]: + self.install_dict_keys_match_guard() + return {k.vt.as_python_constant(): v for k, v in self.items.items()} + + def python_type(self) -> type: + return cast(type, self._cpython_type) + + def __contains__(self, vt: VariableTracker) -> bool: + if not isinstance(vt, VariableTracker): + raise AssertionError(f"Expected VariableTracker, got {type(vt)}") + # Use is_hashable as a side-effect-free pre-check. We can't catch + # ObservedTypeError from HashableTracker because it modifies + # tx.exn_vt_stack as a side effect. + if not is_hashable(vt): + return False + key = HashableTracker(vt) + return key in self.items and not isinstance( + self.items[key], variables.DeletedVariable + ) + + def call_tree_map_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "UserFunctionVariable", + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + other_dicts: list[ConstDictVariable] = [] + for candidate in rest: + candidate = candidate.realize() + if not isinstance(candidate, ConstDictVariable) or len( + candidate.items + ) != len(self.items): + return self._tree_map_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + other_dicts.append(candidate) + + new_items_hashed = type(self.items)() + for key_tracker, value in self.items.items(): + sibling_leaves: list[VariableTracker] = [] + for candidate in other_dicts: + try: + sibling_leaves.append(candidate.items[key_tracker]) + except KeyError: + return self._tree_map_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + new_items_hashed[key_tracker] = value.call_tree_map( + tx, + tree_map_fn, + map_fn, + sibling_leaves, + tree_map_kwargs, + ) + + updated_original_items = { + key_tracker.vt: new_items_hashed[key_tracker] + for key_tracker in new_items_hashed + } + + return self.clone( + items=new_items_hashed, + original_items=updated_original_items, + should_reconstruct_all=True, + source=None, + mutation_type=ValueMutationNew(), + ) + + def call_tree_map_with_path_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "UserFunctionVariable", + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + keypath: tuple[Any, ...], + ) -> VariableTracker: + other_dicts: list[ConstDictVariable] = [] + for candidate in rest: + candidate = candidate.realize() + if not isinstance(candidate, ConstDictVariable) or len( + candidate.items + ) != len(self.items): + return self._tree_map_with_path_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + other_dicts.append(candidate) + + new_items_hashed = type(self.items)() + for key_tracker, value in self.items.items(): + sibling_leaves: list[VariableTracker] = [] + for candidate in other_dicts: + try: + sibling_leaves.append(candidate.items[key_tracker]) + except KeyError: + return self._tree_map_with_path_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + key_const = key_tracker.vt.as_python_constant() + child_keypath = keypath + (MappingKey(key_const),) + new_items_hashed[key_tracker] = value.call_tree_map_with_path( + tx, + tree_map_fn, + map_fn, + sibling_leaves, + tree_map_kwargs, + child_keypath, + ) + + updated_original_items = { + key_tracker.vt: new_items_hashed[key_tracker] + for key_tracker in new_items_hashed + } + + return self.clone( + items=new_items_hashed, + original_items=updated_original_items, + should_reconstruct_all=True, + source=None, + mutation_type=ValueMutationNew(), + ) + + def len(self) -> int: + return sum( + not isinstance(x, variables.DeletedVariable) for x in self.items.values() + ) + + def has_new_items(self) -> bool: + return self.should_reconstruct_all or any( + self.is_new_item(self.original_items.get(key.vt), value) + for key, value in self.items.items() + ) + + def is_new_item( + self, value: VariableTracker | None, other: VariableTracker + ) -> bool: + # compare the id of the realized values if both values are not lazy VTs + if value and value.is_realized() and other.is_realized(): + return id(value.realize()) != id(other.realize()) + return id(value) != id(other) + + def reconstruct_kvs_into_new_dict(self, codegen: "PyCodegen") -> None: + # Build a dictionary that contains the keys and values. + num_args = 0 + for key, value in self.items.items(): + # We can safely call realize() here as it won't introduce any new guards + item = self.original_items.get(key.vt) + if self.is_new_item(item, value) or self.should_reconstruct_all: + codegen(key.vt) + codegen(value) + num_args += 1 + codegen.append_output(create_instruction("BUILD_MAP", arg=num_args)) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self._contains_self_reference(): + codegen.extend_output( + [ + create_instruction("BUILD_MAP", arg=0), + create_dup_top(), + ] + ) + codegen.add_cache(self) + self.reconstruct_kvs_into_new_dict(codegen) + codegen.append_output(create_instruction("DICT_UPDATE", arg=1)) + else: + # Non-self-referential: use simple codegen + self.reconstruct_kvs_into_new_dict(codegen) + + def reconstruct_pycode(self, codegen) -> str: + if self._contains_self_reference(): + raise NotImplementedError + return f"{{{', '.join(f'{k.vt.reconstruct_pycode(codegen)}: {v.reconstruct_pycode(codegen)}' for k, v in self.items.items())}}}" + + def getitem_const_raise_exception_if_absent( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + key = HashableTracker(arg) + if key not in self.items: + raise_observed_exception(KeyError, tx, args=[arg]) + return self.items[key] + + def getitem_const( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + key = HashableTracker(arg) + if key not in self.items: + msg = f"Dictionary key {arg.value} not found during tracing" # type: ignore[attr-defined] + unimplemented( + gb_type="key not found in dict", + context=f"Key {arg.value}", # type: ignore[attr-defined] + explanation=msg, + hints=[ + "Check if the key exists in the dictionary before accessing it.", + *graph_break_hints.USER_ERROR, + ], + ) + return self.items[key] + + def maybe_getitem_const(self, arg: VariableTracker) -> VariableTracker | None: + key = HashableTracker(arg) + if key not in self.items: + return None + return self.items[key] + + def realize_key_vt(self, arg: VariableTracker) -> None: + # Realize the LazyVT on a particular index + if arg not in self: + raise AssertionError(f"Key {arg} not found in dict") + key = HashableTracker(arg) + index = tuple(self.items.keys()).index(key) + original_key_vt = tuple(self.original_items.keys())[index] + if isinstance(original_key_vt, variables.LazyVariableTracker): + original_key_vt.realize() + + def install_dict_keys_match_guard(self) -> None: + if self.source: + install_guard(self.make_guard(GuardBuilder.DICT_KEYS_MATCH)) + + def install_dict_contains_guard( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker] + ) -> None: + # Key guarding - These are the cases to consider + # 1) The dict has been mutated. In this case, we would have already + # inserted a DICT_KEYS_MATCH guard, so we can skip. + # + # 2) args[0].source is None. This happens for const keys. Here, we + # have to insert the DICT_CONTAINS guard. + # + # 3) args[0].source is not None. This can happen for non-const VTs. + # 3a) contains=True. In this case, we can access the lazyVT from + # original_items and selectively realize it. + # 3b) contains=False. There is no easy way to selectively apply this + # DICT_NOT_CONTAINS guard because our guard are represented via trees. + # Be conservative and add DICT_KEYS_MATCH guard. + + if not self.source: + return + + if tx.output.side_effects.is_modified(self): + return + + contains = args[0] in self + if args[0].source is None and args[0].is_python_constant(): + guard_fn = ( + type(self).CONTAINS_GUARD if contains else type(self).NOT_CONTAINS_GUARD + ) + install_guard( + self.make_guard( + functools.partial( + guard_fn, + key=args[0].as_python_constant(), + ) + ) + ) + elif args[0].source: + if contains: + self.realize_key_vt(args[0]) + else: + self.install_dict_keys_match_guard() + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # dict_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/dictobject.c#L3673-L3706 + # Unhashable key check happens inside HashableTracker (hash_impl → TypeError). + return self.getitem_const_raise_exception_if_absent(tx, key) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L4657-L4668 + if not is_hashable(item): + raise_type_error(tx, f"unhashable type: '{item.python_type_name()}'") + self.install_dict_contains_guard(tx, [item]) + contains = item in self + return VariableTracker.build(tx, contains) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .iter import DictIterator + + if self.source and not is_constant_source(self.source): + install_guard(self.make_guard(GuardBuilder.DICT_KEYS_MATCH)) + tx.output.guard_on_key_order.add(self.source) + return DictIterator(self.items.keys()) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from . import DictBuiltinVariable + + temp_dict_vt = DictBuiltinVariable.call_custom_dict(tx, dict, *args, **kwargs) + tx.output.side_effects.mutation(self) + self.items.update(temp_dict_vt.items) # type: ignore[attr-defined] + return ConstantVariable.create(None) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # NB - Both key and value are LazyVariableTrackers in the beginning. So, + # we have to insert guards when a dict method is accessed. For this to + # be simple, we are conservative and overguard. We skip guard only for + # get/__getitem__ because the key guard will be inserted by the + # corresponding value VT. For __contains__, we add a DICT_CONTAINS + # guard. But for all the other methods, we insert the DICT_KEYS_MATCH + # guard to be conservative. + Hashable = HashableTracker + + if name == "items": + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + self.install_dict_keys_match_guard() + if self.source: + tx.output.guard_on_key_order.add(self.source) + return DictItemsVariable(self) + elif name == "keys": + if len(args): + raise_args_mismatch(tx, name, "0 args", f"{len(args)} args") + self.install_dict_keys_match_guard() + if self.source: + tx.output.guard_on_key_order.add(self.source) + return DictKeysVariable(self) + elif name == "__reversed__": + # dict.__reversed__: reverse insertion-order key iterator. + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c (dict___reversed___impl) + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + self.install_dict_keys_match_guard() + if self.source: + tx.output.guard_on_key_order.add(self.source) + reversed_keys = [k.vt for k in reversed(list(self.items.keys()))] + return variables.ListIteratorVariable( + reversed_keys, mutation_type=ValueMutationNew() + ) + elif name == "values": + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + self.install_dict_keys_match_guard() + if self.source: + tx.output.guard_on_key_order.add(self.source) + if args or kwargs: + raise_observed_exception(TypeError, tx) + return DictValuesVariable(self) + elif name == "copy": + self.install_dict_keys_match_guard() + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return self.clone( + items=self.items.copy(), mutation_type=ValueMutationNew(), source=None + ) + elif name == "get": + if len(args) not in (1, 2): + raise_args_mismatch(tx, name, "1 or 2 args", f"{len(args)} args") + + if args[0] not in self: + self.install_dict_contains_guard(tx, args) + if len(args) == 1: + # if default is not given, return None + return ConstantVariable.create(None) + return args[1] + # Key guarding - Nothing to do. + return self.getitem_const(tx, args[0]) + elif name == "pop" and self.is_mutable(): + if len(args) not in (1, 2): + raise_args_mismatch(tx, name, "1 or 2 args", f"{len(args)} args") + + if args[0] not in self: + # missing item, return the default value. Install no DICT_CONTAINS guard. + self.install_dict_contains_guard(tx, args) + if len(args) == 1: + # if default is not given, raise KeyError + raise_observed_exception(KeyError, tx) + return args[1] + + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + return self.items.pop(Hashable(args[0])) + elif name == "popitem" and self.is_mutable(): + # dict.popitem() takes no args. OrderedDict.popitem(last=) is + # handled by OrderedDictVariable.call_method. + if len(args): + raise_args_mismatch(tx, name) + + if not self.items: + raise_observed_exception( + KeyError, + tx, + args=[ + "popitem(): dictionary is empty", + ], + ) + + k, v = self.items.popitem() + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + + return variables.TupleVariable([k.vt, v]) + elif name == "clear": + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + self.items.clear() + return ConstantVariable.create(None) + elif name == "update" and self.is_mutable(): + # Mirrors CPython PyDict_Merge: if arg has keys(), iterate keys and + # __getitem__; else treat arg as iterable of (key, value) pairs. + # kwargs are always merged on top. + # ref: https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/dictobject.c#L3571 + self.install_dict_keys_match_guard() + if len(args) > 1: + raise_args_mismatch(tx, name, "at most 1 args", f"{len(args)} args") + if args or kwargs: + tx.output.side_effects.mutation(self) + if args: + other = args[0] + if isinstance(other, ConstDictVariable): + # NB - Guard on all the keys of the other dict to ensure + # correctness. + other.install_dict_keys_match_guard() + self.items.update(other.items) + elif ( + isinstance( + other, + (variables.UserDefinedObjectVariable, MappingProxyVariable), + ) + and other.call_obj_hasattr(tx, "keys").as_python_constant() + ): + keys = other.call_method(tx, "keys", [], {}) + for key in unpack_iterable(tx, keys): + self.items[Hashable(key)] = generic_getitem(tx, other, key) + else: + for idx, item in enumerate(unpack_iterable(tx, other)): + pair = unpack_iterable(tx, item) + if len(pair) != 2: + raise_observed_exception( + ValueError, + tx, + args=[ + "dictionary update sequence element " + f"#{idx} has length {len(pair)}; 2 is required" + ], + ) + self.items[Hashable(pair[0])] = pair[1] + for k, v in kwargs.items(): + self.items[Hashable(VariableTracker.build(tx, k))] = v + return ConstantVariable.create(None) + elif name == "setdefault" and self.is_mutable(): + if len(args) not in (1, 2): + raise_args_mismatch( + tx, + name, + "1 or 2 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + self.install_dict_keys_match_guard() + if kwargs or len(args) > 2: + raise_args_mismatch( + tx, + name, + "at most 2 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + value = self.maybe_getitem_const(args[0]) + if value is not None: + return value + else: + if len(args) == 1: + x = ConstantVariable.create(None) + else: + x = args[1] + tx.output.side_effects.mutation(self) + self.items[Hashable(args[0])] = x + return x + else: + return super().call_method(tx, name, args, kwargs) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + self.install_dict_keys_match_guard() + return [x.vt for x in self.items] + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/dictobject.c#L4643-L4658 + self_, other_ = (other, self) if reverse else (self, other) + if pydict_check(self_) and pydict_check(other_): + new = self_.call_method(tx, "copy", [], {}) + new.call_method(tx, "update", [other_], {}) + return new + return ConstantVariable.create(NotImplemented) + + def nb_inplace_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/dictobject.c#L4660-L4667 + self.call_method(tx, "update", [other], {}) + return self + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c (dict_ass_sub) + if not self.is_mutable(): + return super().mp_ass_subscript_impl(tx, key, value) + + # value=None signals delete (CPython NULL sentinel). + if not is_hashable(key): + raise_unhashable(key, tx) + self.install_dict_keys_match_guard() + hkey = HashableTracker(key) + tx.output.side_effects.mutation(self) + if value is None: + if hkey not in self.items: + raise_observed_exception(KeyError, tx, args=[key.as_python_constant()]) + self.should_reconstruct_all = True + del self.items[hkey] + else: + self.items[hkey] = value + return ConstantVariable.create(None) + + def mp_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Mapping length for dict objects.""" + self.install_dict_keys_match_guard() + return VariableTracker.build(tx, len(self.items)) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + # dict not allow setting arbitrary attributes. OrderedDict and + # defaultdict allow arbitrary setattr, but not deletion of default attrs + cls = self.python_type() + if any( + cls is t for t in (dict, collections.OrderedDict, collections.defaultdict) + ): + if hasattr(cls, name): + return ConstantVariable.create(True) + if cls is dict: + return ConstantVariable.create(False) + + msg = f"hasattr on {cls} is not supported" + unimplemented( + gb_type="unsupported hasattr operation", + context=f"Class {cls}", + explanation=msg, + hints=[ + "Consider using a regular dictionary instead", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def clone(self, **kwargs: Any) -> VariableTracker: + self.install_dict_keys_match_guard() + return super().clone(**kwargs) + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, f"unhashable type: '{self.python_type_name()}'") + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # dict_richcompare: https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L4198 + # Only supports eq/ne; returns NotImplemented for ordering. + from .builder import SourcelessBuilder + from .user_defined import UserDefinedDictVariable + + if op not in ("__eq__", "__ne__"): + return ConstantVariable.create(NotImplemented) + if not isinstance(other, ConstDictVariable): + # Unwrap UserDefinedDictVariable to its base ConstDictVariable. + # This is correct because CPython's dict_equal operates on the + # internal C struct directly (ma_used, dk_entries, _Py_dict_lookup) + # -- it never calls __getitem__ or __len__ on dict subclasses. + # https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L4125-L4185 + if isinstance(other, UserDefinedDictVariable): + if other._base_vt is None: + raise AssertionError("expected _base_vt to be set") + other = other._base_vt + else: + return ConstantVariable.create(NotImplemented) + eq_result = SourcelessBuilder.create(tx, polyfills.dict___eq__).call_function( + tx, [self, other], {} + ) + if op == "__ne__": + return VariableTracker.build(tx, not eq_result.as_python_constant()) + return eq_result + + def tp_getattro_impl(self, tx: "InstructionTranslatorBase", name: str): + if name == "__class__": + return VariableTracker.build(tx, self.python_type()) + # DictGuardManager does not support getattr_manager for plain dicts, + # so AttrSource chains through a dict source break guard creation. + # Return CallMethodVariable directly for methods, bypassing the + # MRO walk in object_generic_getattr that would create that chain. + type_attr = mro_lookup(self.python_type(), name) + if type_attr is not NO_SUCH_SUBOBJ and _is_method_type(type_attr): + return variables.CallMethodVariable(self, name) + return super().tp_getattro_impl(tx, name) + + +class OrderedDictVariable(ConstDictVariable): + _cpython_type = collections.OrderedDict + + # OrderedDict-exclusive C methods, declared like CPython's odict tp_methods. + # move_to_end is odict-only; popitem honors last= (vs dict's LIFO popitem). + # OrderedDict exposes no tp_getset / tp_members. + # https://github.com/python/cpython/blob/v3.13.0/Objects/odictobject.c + + def move_to_end( + self: "OrderedDictVariable", + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + self.install_dict_keys_match_guard() + tx.output.side_effects.mutation(self) + if args[0] not in self: + raise_observed_exception(KeyError, tx) + + last = True + if len(args) == 2 and args[0].is_python_constant(): + last = args[1].as_python_constant() + if "last" in kwargs and kwargs["last"].is_python_constant(): + last = kwargs["last"].as_python_constant() + + self.items.move_to_end(HashableTracker(args[0]), last=last) + return ConstantVariable.create(None) + + def popitem( + self: "OrderedDictVariable", + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if not self.items: + raise_observed_exception( + KeyError, tx, args=["popitem(): dictionary is empty"] + ) + + last = True + if len(args) == 1 and args[0].is_python_constant(): + last = args[0].as_python_constant() + if "last" in kwargs and kwargs["last"].is_python_constant(): + last = kwargs["last"].as_python_constant() + + k, v = self.items.popitem(last=last) + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + return variables.TupleVariable([k.vt, v]) + + tp_methods = { + "move_to_end": Method(move_to_end), + "popitem": Method(popitem), + } + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Consult tp_methods before ConstDictVariable's own dispatch, whose + # bare-dict popitem() branch would otherwise shadow the OrderedDict + # popitem(last=) handler. + method = self.lookup_tp_method(name) + if method is not None: + result = method(self, tx, name, args, kwargs) + if result is not None: + return result + return super().call_method(tx, name, args, kwargs) + + def as_python_constant(self) -> "collections.OrderedDict[Any, Any]": + return collections.OrderedDict(super().as_python_constant()) + + @staticmethod + def _ordered_dict_repr(items: list[tuple[str, str]]) -> str: + if not items: + return "OrderedDict()" + if sys.version_info >= (3, 12): + return ( + "OrderedDict({" + + ", ".join(f"{key}: {value}" for key, value in items) + + "})" + ) + return ( + "OrderedDict([" + + ", ".join(f"({key}, {value})" for key, value in items) + + "])" + ) + + def debug_repr(self) -> str: + items = [(k.vt.debug_repr(), v.debug_repr()) for k, v in self.items.items()] + return self._ordered_dict_repr(items) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # Python < 3.12 uses the historical list-of-pairs form, while 3.12+ + # uses dict-style formatting. + items = [ + (tracked_repr(tx, key.vt), tracked_repr(tx, value)) + for key, value in self.items.items() + ] + return VariableTracker.build(tx, self._ordered_dict_repr(items)) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # OrderedDict.__or__/__ror__ preserve the OrderedDict type, unlike + # dict.__or__ which returns a plain dict for a subclass operand. + # ref: https://github.com/python/cpython/blob/3.13/Lib/collections/__init__.py#L327-L339 + if not issubclass(other.python_type(), dict): + return ConstantVariable.create(NotImplemented) + if reverse: + new = VariableTracker.build(tx, self.python_type()).call_function( + tx, [other], {} + ) + new.call_method(tx, "update", [self], {}) + else: + new = self.call_method(tx, "copy", [], {}) + new.call_method(tx, "update", [other], {}) + return new + + def reconstruct(self, codegen: "PyCodegen") -> None: + # emit `OrderedDict(constructed_dict)` + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(collections), + codegen.create_load_attr("OrderedDict"), + ] + ) + ) + if self._contains_self_reference(): + codegen.extend_output( + [ + *create_call_function(0, False), + create_dup_top(), + ] + ) + codegen.add_cache(self) + + codegen.append_output(create_dup_top()) + codegen.load_method("update") + self.reconstruct_kvs_into_new_dict(codegen) + codegen.extend_output( + [ + *create_call_method(1), + create_instruction("POP_TOP"), + ] + ) + else: + self.reconstruct_kvs_into_new_dict(codegen) + codegen.extend_output(create_call_function(1, False)) + + def reconstruct_pycode(self, codegen) -> str: + raise NotImplementedError + + +class MappingProxyVariable(VariableTracker): + # PyDictProxy_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/descrobject.c#L1995 + _cpython_type = types.MappingProxyType + + # proxies to the original dict_vt + def __init__(self, dv_dict: ConstDictVariable, **kwargs: Any) -> None: + super().__init__(**kwargs) + if not isinstance(dv_dict, ConstDictVariable): + raise AssertionError(f"Expected ConstDictVariable, got {type(dv_dict)}") + self.dv_dict = dv_dict + + def python_type(self) -> type: + return types.MappingProxyType + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # mappingproxy.__hash__ delegates to the underlying dict, which + # raises TypeError. Mirror that behavior. + return self.dv_dict.hash_impl(tx) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return self.dv_dict.unpack_var_sequence(tx) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # load types.MappingProxyType + if self.source: + msg = ( + f"Preexisting MappingProxyVariable (source: {self.source}) cannot be reconstructed " + "because the connection to the original dict will be lost." + ) + unimplemented( + gb_type="mapping proxy cannot be reconstructed", + context=f"Source: {self.source}", + explanation=msg, + hints=[ + "Use a mapping proxy constructed in the same `torch.compile` region.", + *graph_break_hints.SUPPORTABLE, + ], + ) + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(types), + codegen.create_load_attr("MappingProxyType"), + ] + ) + ) + codegen(self.dv_dict) + codegen.extend_output(create_call_function(1, False)) + + def _check_mutation_guard(self, tx: "InstructionTranslatorBase") -> None: + if self.source and tx.output.side_effects.has_existing_dict_mutation(): + msg = ( + "A dict has been modified while we have an existing mappingproxy object. " + "A mapping proxy object, as the name suggest, proxies a mapping " + "object (usually a dict). If the original dict object mutates, it " + "is reflected in the proxy object as well. For an existing proxy " + "object, we do not know the original dict it points to. Therefore, " + "for correctness we graph break when there is dict mutation and we " + "are trying to access a proxy object." + ) + + unimplemented( + gb_type="mapping proxy affected by dictionary mutation", + context=f"Source: {self.source}, Dict mutation detected", + explanation=msg, + hints=[ + "Avoid modifying dictionaries that might be referenced by mapping proxy objects", + "Or avoid using the mapping proxy objects after modifying its underlying dictionary", + ], + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # mappingproxy_getitem: https://github.com/python/cpython/blob/62a6e898e01/Objects/descrobject.c#L1052-L1056 + # TODO(follow-up): add tests for invalid key type, missing key + self._check_mutation_guard(tx) + return self.dv_dict.mp_subscript_impl(tx, key) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + self._check_mutation_guard(tx) + return self.dv_dict.call_method(tx, name, args, kwargs) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.dv_dict.tp_iter_impl(tx) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # https://github.com/python/cpython/blob/60403a5409ff/Objects/descrobject.c#L1087-L1095 + return self.dv_dict.sq_contains_impl(tx, item) + + def mp_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.dv_dict.mp_length_impl(tx) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # mappingproxy_richcompare delegates to the underlying mapping: + # https://github.com/python/cpython/blob/60403a5409ff/Objects/descrobject.c#L1231-L1236 + from .object_protocol import generic_richcompare + + return generic_richcompare(tx, self.dv_dict, other, op) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is types.MappingProxyType: + return VariableTracker.build(tx, name in types.MappingProxyType.__dict__) + return super().call_obj_hasattr(tx, name) + + +class NNModuleHooksDictVariable(OrderedDictVariable): + # Special class to avoid adding any guards on the nn module hook ids. + # nn.Module hook dicts are OrderedDict, so back storage/reconstruct with it. + def install_dict_keys_match_guard(self) -> None: + pass + + def install_dict_contains_guard( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker] + ) -> None: + pass + + +class DictViewVariable(VariableTracker): + """ + Models _PyDictViewObject + + This is an "abstract" class. Subclasses will override kv and the items method + """ + + kv: str | None = None + + def __init__(self, dv_dict: ConstDictVariable, **kwargs: Any) -> None: + super().__init__(**kwargs) + if self.kv not in ("keys", "values", "items"): + raise AssertionError( + f"Expected kv to be 'keys', 'values', or 'items', got {self.kv!r}" + ) + if not isinstance(dv_dict, ConstDictVariable): + raise AssertionError(f"Expected ConstDictVariable, got {type(dv_dict)}") + self.dv_dict = dv_dict + + @property + def view_items(self) -> Any: + if self.kv is None: + raise AssertionError("kv must not be None") + return getattr(self.dv_dict.items, self.kv)() + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, f"unhashable type: '{self.python_type_name()}'") + + @property + def view_items_vt(self) -> list[VariableTracker]: + # Returns an iterable of the unpacked items + # Implement in the subclasses + raise NotImplementedError + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return self.view_items_vt + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.kv is None: + raise AssertionError("kv must not be None for reconstruct") + codegen(self.dv_dict) + codegen.load_method(self.kv) + codegen.call_method(0) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.kv is None: + raise AssertionError("kv must not be None for call_obj_hasattr") + if name in self.python_type().__dict__: + return ConstantVariable.create(True) + return ConstantVariable.create(False) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # dictview_mapping getset returns a read-only mappingproxy of the + # underlying dict for dict_keys/values/items. + # https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L5032-L5040 + if name == "mapping": + return MappingProxyVariable(self.dv_dict) + return super().tp_getattro_impl(tx, name) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self.kv == "keys": + items = ", ".join(tracked_repr(tx, key.vt) for key in self.view_items) + elif self.kv == "values": + items = ", ".join(tracked_repr(tx, value) for value in self.view_items) + else: # items + items = ", ".join( + f"({tracked_repr(tx, key.vt)}, {tracked_repr(tx, value)})" + for key, value in self.view_items + ) + return VariableTracker.build(tx, f"{self.python_type_name()}([{items}])") + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__reversed__": + # dict_keys/values/items __reversed__: reverse insertion order. + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + if self.dv_dict.source and not is_constant_source(self.dv_dict.source): + tx.output.guard_on_key_order.add(self.dv_dict.source) + return variables.ListIteratorVariable( + list(reversed(self.view_items_vt)), + mutation_type=ValueMutationNew(), + ) + return super().call_method(tx, name, args, kwargs) + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Sequence length for dict view objects.""" + return VariableTracker.build(tx, len(self.view_items)) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L6142-L6155 (dictviews_or) + s = VariableTracker.build(tx, set).call_function(tx, [self], {}) + s.call_method(tx, "update", [other], {}) + return s + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L6036 (dictviews_sub) + self_, other_ = (other, self) if reverse else (self, other) + s = VariableTracker.build(tx, set).call_function(tx, [self_], {}) + s.call_method(tx, "difference_update", [other_], {}) + return s + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/dictobject.c#L6105-L6188 (_PyDictView_Intersect) + s = VariableTracker.build(tx, set).call_function(tx, [self], {}) + s.call_method(tx, "intersection_update", [other], {}) + return s + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/dictobject.c#L6305-L6325 (dictviews_xor) + s = VariableTracker.build(tx, set).call_function(tx, [self], {}) + s.call_method(tx, "symmetric_difference_update", [other], {}) + return s + + +class DictKeysVariable(DictViewVariable): + # PyDictKeys_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L6365 + _cpython_type = dict_keys + + kv = "keys" + + @property + def set_items(self) -> set[VariableTracker]: + return set(self.view_items) + + @property + def view_items_vt(self) -> list[VariableTracker]: + # Returns an iterable of the unpacked items + return [x.vt for x in self.view_items] + + def python_type(self) -> type: + return dict_keys + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .iter import DictKeysIterator + + if self.dv_dict.source and not is_constant_source(self.dv_dict.source): + tx.output.guard_on_key_order.add(self.dv_dict.source) + return DictKeysIterator(self.dv_dict.items) + + def debug_repr(self) -> str: + if not self.view_items: + return "dict_keys([])" + else: + items: list[str] = [] + for k in self.view_items: + key_str = _item_debug_repr(k.vt) + items.append(key_str) + return "dict_keys([" + ", ".join(items) + "])" + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L5998-L6005 + return self.dv_dict.sq_contains_impl(tx, item) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # dictview_richcompare: accepts set/frozenset and dict_keys/dict_items. + # https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L5952-L6010 + # Uses a polyfill with len() and ``in`` so that Dynamo traces through + # sq_length/sq_contains, matching CPython's use of PyObject_Size and + # PySequence_Contains. + from .builder import SourcelessBuilder + + if not _is_set_or_dictview(other): + return ConstantVariable.create(NotImplemented) + return SourcelessBuilder.create( + tx, polyfills.dictview_richcompare + ).call_function( + tx, + [ + SourcelessBuilder.create(tx, cmp_name_to_op_mapping[op]), + self, + other, + ], + {}, + ) + + +class DictValuesVariable(DictViewVariable): + # PyDictValues_Type: https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L6615 + _cpython_type = dict_values + + # dict_values is hashable (identity hash), unlike dict_keys/dict_items. + # + # CPython only inherits tp_hash from the base when BOTH tp_richcompare + # AND tp_hash are NULL on the type + # (https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L7665-L7679). + # dict_keys/dict_items set tp_richcompare (for set-like comparisons), + # so their tp_hash is NOT inherited — it stays NULL, and + # type_ready_set_hash sets it to PyObject_HashNotImplemented (unhashable) + # (https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L8066-L8085). + # dict_values does NOT set tp_richcompare + # (https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L6630), + # so it inherits object's tp_hash (PyObject_GenericHash) — hashable. + # + # Override DictViewVariable.hash_impl to restore the base identity hash. + kv = "values" + + # dict.values() do not implement tp_as_number + nb_or_impl = None # type: ignore[bad-override] + nb_inplace_or_impl = None # type: ignore[bad-override] + nb_subtract_impl = None # type: ignore[bad-override] + nb_inplace_subtract_impl = None # type: ignore[bad-override] + nb_and_impl = None # type: ignore[bad-override] + nb_inplace_and_impl = None # type: ignore[bad-override] + nb_xor_impl = None # type: ignore[bad-override] + nb_inplace_xor_impl = None # type: ignore[bad-override] + + def is_hashable(self) -> bool: + return True + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return super(DictViewVariable, self).hash_impl(tx) + + @property + def view_items_vt(self) -> list[VariableTracker]: + return list(self.view_items) + + def python_type(self) -> type: + return dict_values + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .iter import DictValuesIterator + + if self.dv_dict.source and not is_constant_source(self.dv_dict.source): + tx.output.guard_on_key_order.add(self.dv_dict.source) + return DictValuesIterator(self.dv_dict.items) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # dict_values has no tp_richcompare (inherits object's). + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def debug_repr(self) -> str: + if not self.view_items: + return "dict_values([])" + else: + items: list[str] = [] + for v in self.view_items: + val_str = _item_debug_repr(v) + items.append(val_str) + return "dict_values([" + ", ".join(items) + "])" + + +class DictItemsVariable(DictViewVariable): + # PyDictItems_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L6477 + _cpython_type = dict_items + + kv = "items" + + @property + def set_items(self) -> set["HashableTracker"]: + return { + HashableTracker(variables.TupleVariable([k.vt, v])) + for k, v in self.view_items + } + + @property + def view_items_vt(self) -> list[VariableTracker]: + # Returns an iterable of the unpacked items + return [variables.TupleVariable([k.vt, v]) for k, v in self.view_items] + + def python_type(self) -> type: + return dict_items + + def debug_repr(self) -> str: + if not self.view_items: + return "dict_items([])" + else: + items: list[str] = [] + for k, v in self.view_items: + key_str = _item_debug_repr(k.vt) + val_str = _item_debug_repr(v) + items.append(f"({key_str}, {val_str})") + return "dict_items([" + ", ".join(items) + "])" + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L6433-L6451 + from ..utils import iter_contains + + if not is_hashable(item): + raise_type_error(tx, f"unhashable type: '{item.python_type_name()}'") + + # Fast path: if item is a known (key, value) pair, use O(1) dict lookup. + if isinstance(item, variables.TupleVariable) and len(item.items) == 2: + key, val = item.items + key_ht = HashableTracker(key) + if key_ht not in self.dv_dict.items: + return VariableTracker.build(tx, False) + stored = self.dv_dict.items[key_ht] + # dictitems_contains: PyObject_RichCompareBool(found, value, Py_EQ) + # on the stored value, so a value whose __eq__ raises propagates. + return generic_richcompare_bool(tx, stored, val, "__eq__") + + return iter_contains(self.view_items_vt, item, tx) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # dictview_richcompare: accepts set/frozenset and dict_keys/dict_items. + # https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L5952-L6010 + # Uses a polyfill with len() and ``in`` so that Dynamo traces through + # sq_length/sq_contains, matching CPython's use of PyObject_Size and + # PySequence_Contains. + from .builder import SourcelessBuilder + + if not _is_set_or_dictview(other): + return ConstantVariable.create(NotImplemented) + return SourcelessBuilder.create( + tx, polyfills.dictview_richcompare + ).call_function( + tx, + [ + SourcelessBuilder.create(tx, cmp_name_to_op_mapping[op]), + self, + other, + ], + {}, + ) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .iter import DictItemsIterator + + if self.dv_dict.source and not is_constant_source(self.dv_dict.source): + tx.output.guard_on_key_order.add(self.dv_dict.source) + return DictItemsIterator(self.dv_dict.items) + + +kV = HashableTracker | str + + +class SideEffectsProxyDict(collections.abc.MutableMapping[kV, VariableTracker]): + """ + A proxy dict that allows us to track mutations to the dict using side + effects table as storage. + """ + + @staticmethod + def get_example_value_dict(vt: VariableTracker) -> dict[str, object]: + if istype(vt, variables.NestedUserFunctionVariable): + # NestedUserFunctionVariable is created with MAKE_FUNCTION and its + # __dict__ starts empty. Any mutation will actually be recorded in + # the side effects table. + return {} + elif isinstance(vt, variables.LocalGeneratorFunctionVariable): + return SideEffectsProxyDict.get_example_value_dict(vt.vt) + elif istype(vt, variables.ExceptionVariable): + # Synthetic exceptions created during tracing have no backing + # Python object; their __dict__ starts empty and any custom + # attribute is recorded in the side effects table. + return {} + else: + value = vt.get_real_python_backed_value() + if value is not NO_SUCH_SUBOBJ: + if isinstance(vt, variables.UserDefinedObjectVariable): + return vt._getattr_static("__dict__") # type: ignore[bad-return] + else: + return object.__getattribute__(value, "__dict__") + else: + unimplemented( + gb_type="unsupported variable type for __dict__ access", + context=f"VariableTracker type: {type(vt)}", + explanation=f"Dynamo does not know how to get __dict__ from {type(vt)}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + @staticmethod + def get_value___dict__( + tx: "InstructionTranslatorBase", vt: VariableTracker + ) -> dict[str, VariableTracker]: + # GENERIC_SETATTR on "__dict__" means the whole instance dict was + # replaced through the __dict__ getset descriptor (obj.__dict__ = ...). + # Per-key obj.__dict__[name] mutations are tracked as INSTANCE_DICT. + if isinstance( + vt, variables.UserDefinedObjectVariable + ) and tx.output.side_effects.has_pending_mutation_of_attr( + vt, "__dict__", AttrMutationKind.GENERIC_SETATTR + ): + dict_vt = tx.output.side_effects.load_attr(vt, "__dict__") + if isinstance(dict_vt, ConstDictVariable): + result = {} + for key, value in dict_vt.items.items(): + try: + key_value = key.vt.as_python_constant() + except NotImplementedError: + unimplemented( + gb_type="non-constant key in object __dict__", + context=f"key={key.vt}", + explanation="Dynamo expects object __dict__ replacement keys to be constants.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + if not isinstance(key_value, str): + unimplemented( + gb_type="non-string key in object __dict__", + context=f"key={key_value!r}", + explanation="Dynamo expects object __dict__ keys to be strings.", + hints=[*graph_break_hints.USER_ERROR], + ) + result[key_value] = value + return result + # Other replacement forms are not materialized here yet. Leave + # them on the normal example-value path until Dynamo models their + # contents explicitly. + + example_value_dict = SideEffectsProxyDict.get_example_value_dict(vt) + + return { + key: VariableTracker.build( + tx, + value, + source=vt.source + and DictGetItemSource(AttrSource(vt.source, "__dict__"), key), + ) + for key, value in example_value_dict.items() + } + + def __init__(self, item: VariableTracker, tx: "InstructionTranslatorBase") -> None: + self.item = item + self.side_effects = tx.output.side_effects + self.item_dict = self.get_value___dict__(tx, item) + + def _maybe_unwrap_key(self, key: kV) -> str: + Hasher = HashableTracker + return key.vt.as_python_constant() if istype(key, Hasher) else key + + def side_effects_table(self) -> dict[str, VariableTracker]: + return { + name: value + for name, value in self.side_effects.store_attr_mutations.get( + self.item, {} + ).items() + if self.side_effects.has_pending_mutation_of_attr( + self.item, name, AttrMutationKind.INSTANCE_DICT + ) + } + + def __getitem__(self, key: kV) -> VariableTracker: + name = self._maybe_unwrap_key(key) + if self.side_effects.has_pending_mutation_of_attr( + self.item, name, AttrMutationKind.INSTANCE_DICT + ): + return self.side_effects.load_attr(self.item, name, deleted_ok=True) + return self.item_dict[name] + + def __setitem__(self, key: kV, value: VariableTracker) -> None: + # Find a way to not hash the key using HashableTracker. CPython's + # instance __dict__ accepts arbitrary hashable keys when set via the + # mapping API (only attribute access via setattr requires str), and + # instance-dict mutations replay with object_setattr_ignore_descriptor + # (a plain __dict__ store), so a non-str constant key is fine. + name = self._maybe_unwrap_key(key) + self.side_effects.store_instance_dict_attr(self.item, name, value) + + def __delitem__(self, key: kV) -> None: + name = self._maybe_unwrap_key(key) + self.side_effects.store_instance_dict_attr( + self.item, name, variables.DeletedVariable() + ) + + def __contains__(self, key: kV) -> bool: # type: ignore[bad-override] + name = self._maybe_unwrap_key(key) + if self.side_effects.has_pending_mutation_of_attr( + self.item, name, AttrMutationKind.INSTANCE_DICT + ): + value = self.side_effects.load_attr(self.item, name, deleted_ok=True) + return not isinstance(value, variables.DeletedVariable) + return name in self.item_dict + + def __len__(self) -> int: + return sum(1 for _ in self) + + def __iter__(self) -> Iterator[HashableTracker]: + Hasher = HashableTracker + d = self.side_effects_table() + for k, v in d.items(): + if isinstance(v, variables.DeletedVariable): + continue + yield Hasher(ConstantVariable.create(k)) + + for k, v in self.item_dict.items(): + if k not in d: + yield Hasher(ConstantVariable.create(k)) + + +class DunderDictVariable(ConstDictVariable): + """represents object.__dict__""" + + @classmethod + def create( + cls, + tx: "InstructionTranslatorBase", + vt: VariableTracker, + ) -> "DunderDictVariable": + mutation = AttributeMutationExisting() if vt.source else AttributeMutationNew() + source = vt.source and AttrSource(vt.source, "__dict__") + + return cls( + vt, + tx=tx, + mutation_type=mutation, + source=source, + ) + + def __init__( + self, + vt: VariableTracker, + tx: "InstructionTranslatorBase", + **kwargs: Any, + ) -> None: + super().__init__({}, **kwargs) + self.items = SideEffectsProxyDict(vt, tx) + + def setitem(self, name: str, value: VariableTracker) -> None: + self.items[name] = value + + def delitem(self, name: str) -> None: + if not self.contains(name): + raise KeyError(name) + del self.items[name] + + def getitem(self, name: str) -> VariableTracker: + return self.items[name] + + def contains(self, name: str) -> bool: + return name in self.items + + def getitem_or_default( + self, + name: str, + default: Callable[[], VariableTracker], + ) -> VariableTracker: + if self.contains(name): + return self.getitem(name) + else: + value = default() + self.items[name] = value + return value + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "copy": + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return ConstDictVariable( + dict(self.items), mutation_type=ValueMutationNew(), source=None + ) + return super().call_method(tx, name, args, kwargs) + + # Mutations to __dict__ are tracked through side effects (SideEffectsProxyDict), + # so we don't need to install guards. Guard installation is overridden to no-op. + def install_dict_keys_match_guard(self) -> None: + pass + + def install_dict_contains_guard( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker] + ) -> None: + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/distributed.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..d0dcc3ea592f17a1a4e698fd2bfc4e4b96568cfc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/distributed.py @@ -0,0 +1,282 @@ +""" +Distributed computing variable tracking classes for PyTorch Dynamo. + +This module implements variable tracking for distributed computing components: +- Process Groups (for collective communication) +- Device Meshes (for distributed tensor sharding) +- Placement Types (for specifying distribution strategies) +- Distributed Tensors and their operations +- Backward hooks for distributed module operations + +These classes are responsible for tracking distributed operations during graph +compilation while maintaining proper guards and handling distributed-specific +behaviors. They ensure correct handling of distributed components like process +groups, device meshes, and placement strategies while preserving proper semantics +for distributed tensor operations in the compiled code. + +The implementation provides special handling for distributed package availability +checks and proper tracking of distributed state and operations across processes. +""" + +import functools +import inspect +from typing import Any, TYPE_CHECKING + +import torch +from torch.fx.experimental._backward_state import BackwardState + +from .. import compiled_autograd +from .._trace_wrapped_higher_order_op import trace_wrapped +from ..exc import unimplemented +from ..external_utils import call_module_hooks_from_backward_state +from ..guards import GuardBuilder, install_guard +from ..source import AttrSource +from .base import GetSet, Method, VariableTracker + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +class DistributedVariable(VariableTracker): + """ + The base distributed variable that encapsulates common methods + for the distributed objects (i.e. ProcessGroup, DeviceMesh, etc.). + Concrete distributed objects could inherit this class and add object + specific logic. + + i.e. It provides the check on the distributed package existence + and hold the tracking value for the corresponding distributed object. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + if not DistributedVariable.is_available(): + unimplemented( + gb_type="torch.distributed package is not available!", + context="", + explanation="The PyTorch package doesn't include torch.distributed when building from source.", + hints=[ + "Set USE_DISTRIBUTED=1 to enable it when building PyTorch from source." + ], + ) + self.value = value + + def python_type(self) -> type: + return type(self.value) + + @staticmethod + def is_available() -> bool: + # check if the distributed package is available or not + return torch.distributed.is_available() + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return hash(self.value), False + + def tp_richcompare_impl(self, tx, other, op): + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + +def is_from_local(value: object) -> bool: + if not DistributedVariable.is_available(): + return False + from torch.distributed.tensor import DTensor + + return inspect.isfunction(value) and value is DTensor.from_local + + +def is_constant_pg_functions(value: object) -> bool: + if not DistributedVariable.is_available(): + return False + + from torch.distributed.distributed_c10d import ( + _get_group_size_by_name, + _get_group_tag, + _rank_not_in_group, + _resolve_group_name_by_ranks_and_tag, + get_process_group_ranks, + ) + + constant_processgroup_functions = [ + _get_group_size_by_name, + _get_group_tag, + _rank_not_in_group, + get_process_group_ranks, + _resolve_group_name_by_ranks_and_tag, + ] + + return inspect.isfunction(value) and value in constant_processgroup_functions + + +class WorldMetaClassVariable(DistributedVariable): + """ + Tracks torch.distributed.GroupMember and torch.distributed.group, which are + instances of the metaclass _WorldMeta. + """ + + @classmethod + def is_group_member_type(cls, value: object) -> bool: + if not cls.is_available(): + return False + + from torch.distributed.distributed_c10d import _WorldMeta + + return type(value) is _WorldMeta + + def python_type(self) -> type: + return type(self.value) + + # dynamo-internal getset (not real CPython descriptors): _WorldMeta + # exposes the WORLD and NON_GROUP_MEMBER process-group sentinels. + def _world_getset(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if not self.source: + raise AssertionError( + "WorldMetaClassVariable requires a source for WORLD attribute" + ) + source = AttrSource(base=self.source, member="WORLD") + install_guard(source.make_guard(GuardBuilder.ID_MATCH)) + return VariableTracker.build(tx, self.value.WORLD, source) + + def _non_group_member_getset( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + if not self.source: + raise AssertionError( + "WorldMetaClassVariable requires a source for NON_GROUP_MEMBER attribute" + ) + source = AttrSource(base=self.source, member="NON_GROUP_MEMBER") + install_guard(source.make_guard(GuardBuilder.ID_MATCH)) + return VariableTracker.build(tx, self.value.NON_GROUP_MEMBER, source) + + tp_getset = { + "WORLD": GetSet(_world_getset, None), + "NON_GROUP_MEMBER": GetSet(_non_group_member_getset, None), + } + + +class BackwardHookVariable(VariableTracker): + """ + Handles torch.utils.hooks.BackwardHook for module-level backward + hooks. + """ + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + module: VariableTracker, + user_hooks: VariableTracker, + user_pre_hooks: VariableTracker, + ) -> "BackwardHookVariable": + if not compiled_autograd.compiled_autograd_enabled: + unimplemented( + gb_type="Module-level backwards hooks require compiled autograd.", + context="", + explanation="", + hints=[ + "Enable compiled autograd by setting torch._dynamo.config.compiled_autograd = True." + ], + ) + + def _in_graph_bw_hooks( + bw_state: BackwardState, + ) -> torch.utils.hooks.BackwardHook: + """ + Rather than installing the user hooks in the graph (which + don't survive AotAutograd), we install hooks that will call + trace_wrapped in the backward pass that CompiledAutograd + can turn into actual hook calls. + """ + return torch.utils.hooks.BackwardHook( + None, + ( + functools.partial( + trace_wrapped, + fn=call_module_hooks_from_backward_state, + bw_state=bw_state, + hooks_name=user_hooks_name, + module_name=module_name, + ), + ), + ( + functools.partial( + trace_wrapped, + fn=call_module_hooks_from_backward_state, + bw_state=bw_state, + hooks_name=user_pre_hooks_name, + module_name=module_name, + ), + ), + ) + + module_name, bw_state_proxy = tx.output.add_backward_state_hook(module, "mod") + user_pre_hooks_name, _ = tx.output.add_backward_state_hook(user_pre_hooks) + user_hooks_name, _ = tx.output.add_backward_state_hook(user_hooks) + proxy = tx.output.create_proxy( + "call_function", + _in_graph_bw_hooks, + (bw_state_proxy,), + {}, + ) + proxy.node.meta["example_value"] = torch.utils.hooks.BackwardHook(None, (), ()) + return BackwardHookVariable(proxy, module, user_hooks, user_pre_hooks) + + def __init__( + self, + proxy: torch.fx.Proxy, + module: VariableTracker, + user_hooks: VariableTracker, + user_pre_hooks: VariableTracker, + **options: Any, + ) -> None: + super().__init__(**options) + self.proxy = proxy + self.module = module + self.user_hooks = user_hooks + self.user_pre_hooks = user_pre_hooks + + def as_proxy(self) -> torch.fx.Proxy: + return self.proxy + + def python_type(self) -> type: + return torch.utils.hooks.BackwardHook + + def setup_input_hook( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._setup_hook(tx, "setup_input_hook", *args, **kwargs) + + def setup_output_hook( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._setup_hook(tx, "setup_output_hook", *args, **kwargs) + + tp_methods = { + "setup_input_hook": Method(setup_input_hook), + "setup_output_hook": Method(setup_output_hook), + } + + def _setup_hook( + self, + tx: "InstructionTranslatorBase", + hook_method_name: str, + args: VariableTracker, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_method", + hook_method_name, + (self.as_proxy(), args.as_proxy()), + {}, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/functions.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..1202d8e11bde3d75cc50096a354fe28efb4bc5bd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/functions.py @@ -0,0 +1,4899 @@ +""" +Function-related variable tracking classes for Dynamo's symbolic execution. + +This module contains classes that track different types of functions during graph +compilation, including: +- User-defined functions and methods +- Built-in functions and methods +- Wrapped functions (e.g. from decorators) +- Special function types (e.g. functools.partial) +- Triton kernels and related function types + +These classes are responsible for: +- Tracking function calls and their arguments +- Managing function closures and cell variables +- Handling function attributes and special methods +- Maintaining guards for function identity and closure contents +- Supporting function inlining and specialization +- Enabling proper symbolic execution of different function types + +The variable trackers here work together with the rest of Dynamo to enable +accurate graph capture while handling Python's various function-related behaviors. +""" + +import _collections # type: ignore[import-not-found] +import builtins +import collections +import functools +import importlib.metadata +import importlib.util +import inspect +import itertools +import logging +import os +import re +import sys +import traceback +import types +import typing +from collections.abc import Callable, Sequence +from types import CellType, FunctionType +from typing import Any, cast, Literal, Optional, TYPE_CHECKING, TypeVar +from typing_extensions import Never +from weakref import WeakKeyDictionary + +import torch +from torch._dynamo.exc import get_stack_above_dynamo +from torch._guards import Source +from torch.utils._pytree import is_namedtuple_class + +from .. import config, graph_break_hints, polyfills, variables +from ..bytecode_transformation import create_call_function, create_rot_n, is_generator +from ..exc import ( + format_frame_info, + get_dynamo_observed_exception, + InfiniteGeneratorError, + ObservedException, + ObservedGeneratorExit, + ObservedUserStopIteration, + raise_observed_exception, + raise_type_error, + raise_value_error, + StepUnsupported, + unimplemented, + Unsupported, +) +from ..guards import GuardBuilder, install_guard +from ..source import ( + AttrSource, + CellContentsSource, + ClosureSource, + ConstantSource, + DefaultsSource, + GetItemSource, + ImportSource, + SkipGuardSource, + TypeMROSource, + TypeSource, +) +from ..utils import ( + check_constant_args, + check_unspec_or_constant_args, + FrameState, + identity, + is_function, + is_lru_cache_wrapper_trace_without_warning_allowed, + is_tensor_base_attr_getter, + is_wrapper_or_member_descriptor, + istype, + make_cell, + unpack_iterable, +) +from .base import ( + AsPythonConstantNotImplementedError, + AttributeMutationNew, + GetSet, + getset_build, + getset_read, + Member, + Method, + NO_SUCH_SUBOBJ, + ValueMutationNew, + VariableTracker, +) +from .constant import ConstantVariable +from .user_defined import UserDefinedObjectVariable + + +try: + from torch.distributed.fsdp._fully_shard import _fsdp_param_group +except ModuleNotFoundError: + _fsdp_param_group = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import ( + InliningGeneratorInstructionTranslator, + InliningInstructionTranslator, + InstructionTranslatorBase, + ) + from torch._dynamo.variables.ctx_manager import ContextWrappingVariable + from torch._higher_order_ops.triton_kernel_wrap import ( + TritonGridType, + TritonKernelType, + ) + + from .lists import BaseListVariable, ListVariable + from .tensor import TensorVariable + + +_F = TypeVar("_F", bound=Callable[..., Any]) +CO_VARARGS = 0x04 +CO_VARKEYWORDS = 0x08 +_SUPPORTED_TREE_MAP_KWARGS = frozenset({"namespace", "none_is_leaf", "is_leaf"}) +_TREE_MAP_ONLY_SUPPORTED_KWARGS = frozenset({"is_leaf"}) + +PT2_ISSUE_TRACKER_URL = "https://github.com/pytorch/pytorch/issues/new?&labels=oncall%3A+pt2&projects=&template=pt2-bug-report.yml" + +# Module-level cache keyed by the function object +_spec_cache: WeakKeyDictionary[Any, Any] = WeakKeyDictionary() + + +# Raised when get_function() cannot convert a nested function to a Python function. +class ClosureConversionError(NotImplementedError): + pass + + +@functools.lru_cache +def get_pytree_SUPPORTED_NODES_source() -> AttrSource: + # Cached, so callers are responsible for installing the ID_MATCH guard on the + # embedded ImportSource("torch") themselves. + return AttrSource( + AttrSource(AttrSource(ImportSource("torch"), "utils"), "_pytree"), + "SUPPORTED_NODES", + ) + + +class FunctionSpec: + def __init__(self, func: FunctionType) -> None: + code = func.__code__ + vn = code.co_varnames + + self.posonly_count = code.co_posonlyargcount + self.arg_count = code.co_argcount + self.kwonly_count = code.co_kwonlyargcount + + self.posonly_names = vn[: self.posonly_count] + self.pos_or_kw_names = vn[self.posonly_count : self.arg_count] + self.all_pos_names = self.posonly_names + self.pos_or_kw_names + self.kwonly_names = vn[self.arg_count : self.arg_count + self.kwonly_count] + + off = self.arg_count + self.kwonly_count + self.varargs_name = vn[off] if code.co_flags & CO_VARARGS else None + off += 1 if self.varargs_name else 0 + self.varkw_name = vn[off] if code.co_flags & CO_VARKEYWORDS else None + + def update_defaults(self, func: FunctionType) -> None: + # Defaults can change from function call to function call. So re-update + # them on every call. + self.defaults = func.__defaults__ or () + self.kwdefaults = func.__kwdefaults__ or {} + + # Map positional-default names → their index in self.defaults + self.pos_default_map = dict( + zip(self.all_pos_names[-len(self.defaults) :], range(len(self.defaults))) + ) + + +def _get_spec(func: FunctionType) -> FunctionSpec: + spec = _spec_cache.get(func) + if spec is None: + spec = FunctionSpec(func) + _spec_cache[func] = spec + return spec + + +class BindArgsTypeError(TypeError): + pass + + +def bind_args_cached( + func: FunctionType, + tx: "InstructionTranslatorBase", + fn_source: Source | None, + args: Sequence[Any], + kwargs: dict[str, Any], +) -> dict[str, VariableTracker]: + spec = _get_spec(func) + + # Fast path: simple positional-only, no defaults, no varargs/varkw + # This is the common case for small utility functions called repeatedly. + if ( + len(args) == spec.arg_count + and not func.__defaults__ + and not kwargs + and not spec.varargs_name + and not spec.varkw_name + and not spec.kwonly_names + ): + return { + name: wrap_bound_arg(tx, args[i]) + for i, name in enumerate(spec.all_pos_names) + } + + # Full path with all features + spec.update_defaults(func) + ba = {} + rem_kw = dict(kwargs) + guarded_pos_defaults_len = False + + # 1) Bind all positional (pos-only + pos-or-kw) + for i, name in enumerate(spec.all_pos_names): + if i < len(args): + ba[name] = wrap_bound_arg(tx, args[i]) + elif name in rem_kw and ( + # `kwargs` can have the same key as a pos-only arg `name`. + # If this case happens, we should not consume the `name` here and + # keep it in `kwargs`: + # >>> def fn(a, /, **kwargs): return (a, kwargs) + # >>> fn(1, a=2) + # (1, {'a': 2}) + name not in spec.posonly_names + ): + ba[name] = wrap_bound_arg(tx, rem_kw.pop(name)) + elif name in spec.pos_default_map: + idx = spec.pos_default_map[name] + if fn_source and not guarded_pos_defaults_len: + # The parameter-to-default mapping depends on __defaults__ + # length; guard it without wrapping every default value. + install_guard( + AttrSource(fn_source, "__defaults__").make_guard( + GuardBuilder.SEQUENCE_LENGTH + ) + ) + guarded_pos_defaults_len = True + default_source = None + if fn_source and not ( + ConstantVariable.is_literal(spec.defaults[idx]) + and config.skip_guards_on_constant_func_defaults + ): + default_source = DefaultsSource(fn_source, idx) + ba[name] = wrap_bound_arg(tx, spec.defaults[idx], default_source) + else: + raise BindArgsTypeError(f"missing required positional argument: {name}") + + # 2) *args + extra = args[len(spec.all_pos_names) :] + if spec.varargs_name: + ba[spec.varargs_name] = wrap_bound_arg(tx, tuple(extra)) + elif extra: + raise BindArgsTypeError( + f"Too many positional arguments: got {len(args)}, expected {len(spec.all_pos_names)}" + ) + + # 3) Keyword-only + for name in spec.kwonly_names: + if name in rem_kw: + ba[name] = wrap_bound_arg(tx, rem_kw.pop(name)) + elif name in spec.kwdefaults: + kwdefault_source = None + if fn_source: + kwdefault_source = DefaultsSource(fn_source, name, is_kw=True) + ba[name] = wrap_bound_arg(tx, spec.kwdefaults[name], kwdefault_source) + else: + raise BindArgsTypeError(f"Missing required keyword-only argument: {name}") + + # 4) **kwargs + if spec.varkw_name: + ba[spec.varkw_name] = wrap_bound_arg(tx, rem_kw) + elif rem_kw: + raise BindArgsTypeError(f"Unexpected keyword arguments: {list(rem_kw)}") + + return ba + + +def wrap_bound_arg( + tx: "InstructionTranslatorBase", val: Any, source: Source | None = None +) -> VariableTracker: + # Source propagation is best effort since not every object we encounter has a source to begin with. + if isinstance(val, VariableTracker): + return val + elif not source: + return VariableTracker.build(tx, val) + else: + # Create a lazy variable to avoid guarding on __defaults__ unless really + # needed. + return variables.LazyVariableTracker.create(val, source, tx=tx) + + +def wrap_args_kwargs(tx: "InstructionTranslatorBase", result: dict[str, Any]) -> None: + for k, v in list(result.items()): + if isinstance(v, (tuple, dict)): + # args/kwargs + result[k] = wrap_bound_arg(tx, v) + + +def init_cellvars( + parent: "InstructionTranslatorBase", + result: dict[str, VariableTracker], + code: types.CodeType, +) -> None: + """ + Update `result` to add mapping from local name to new cells created + directly by `code`, or update SideEffects in `parent` if a local cell is + already in `result` (cell argument). + """ + side_effects = parent.output.side_effects + + for name in code.co_cellvars: + new_cell = side_effects.track_cell_new() + if name in result: + # This handles when a function argument is a cell (e.g., captured by + # a nested func). See `MAKE_CELL` bytecode for more info. + side_effects.store_cell(new_cell, result.pop(name)) + result[name] = new_cell + + +def _create_nested_fn( + code: types.CodeType, + f_globals: dict[str, Any], + name: str, + defaults: tuple[object, ...] | None, + closure: tuple[CellType] | None, + kwdefaults: dict[str, Any] | None, + annotations: dict[str, Any] | None, +) -> types.FunctionType: + from types import FunctionType + + func = FunctionType(code, f_globals, name, defaults, closure) + func.__kwdefaults__ = kwdefaults + + if isinstance(annotations, tuple): + from itertools import pairwise + + annotations = dict(pairwise(annotations)) + + # TypeError: __annotations__ must be set to a dict object + if not (annotations is None or isinstance(annotations, dict)): + raise AssertionError( + f"annotations must be None or a dict, got {type(annotations)}" + ) + func.__annotations__ = annotations # type: ignore[assignment] + + return func + + +fn_known_dunder_attrs = { + "__annotations__", + "__builtins__", + "__closure__", + "__code__", + "__defaults__", + "__doc__", + "__globals__", + "__kwdefaults__", + "__name__", + "__module__", +} + + +def fn_getattro_impl( + tx: "InstructionTranslatorBase", fn: object, source: Source | None, name: str +) -> VariableTracker: + source = source and AttrSource(source, name) + + if source and name == "__annotations__": + # We get a large number of silly guards from annotations from inspect + # module. Changing annotations is rare, and it impacting the extracted + # graph is even rarer. So skip guards. + source = SkipGuardSource(source) + + subobj = None + try: + subobj = inspect.getattr_static(fn, name) + except AttributeError: + # function does not have a __getattr__ or __getattribute__ method, + # so we can safely assume that this attribute is absent + raise_observed_exception(AttributeError, tx) + + # Special handling for known dunder attributes + # TODO(guilhermeleobas): this check should go through fn.__dict__ first as + # functools.partial can override it + if name in fn_known_dunder_attrs: + subobj = getattr(fn, name) + if source: + return variables.LazyVariableTracker.create(subobj, source, tx=tx) + return VariableTracker.build(tx, subobj) + + +class BaseUserFunctionVariable(VariableTracker): + # funcobject.c func_annotations: a dedicated slot, NOT a __dict__ entry. + # Materialized per-instance once accessed/assigned. + annotations: "VariableTracker | None" = None + + def tp_richcompare_impl(self, tx, other, op): + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def self_args(self) -> list[VariableTracker]: + return [] + + def get_source(self) -> Source | None: + return self.source + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/funcobject.c + return VariableTracker.build(tx, repr(self.as_python_constant())) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__setattr__": + if args[0].is_constant_match("__annotations__"): + self.annotations = args[1] + return ConstantVariable.create(None) + return self.get_dict_vt(tx).call_method( + tx, "__setitem__", list(args), kwargs + ) + elif name == "__delattr__": + if args[0].is_constant_match("__annotations__"): + self.annotations = None + return ConstantVariable.create(None) + return self.get_dict_vt(tx).call_method(tx, "__delitem__", list(args), {}) + return super().call_method(tx, name, list(args), kwargs) + + def get_filename(self) -> str: + return self.get_code().co_filename + + def get_name(self) -> str: + return self.get_code().co_name + + def get_qualname(self) -> str: + if sys.version_info >= (3, 11): + return self.get_code().co_qualname + else: + return self.get_name() + + def get_doc(self) -> str | None: + # stored in code.co_consts[0] + return self.get_code().co_consts[0] + + def get_globals(self) -> dict[str, Any]: + raise NotImplementedError + + def get_code(self) -> types.CodeType: + raise NotImplementedError + + def has_self(self) -> bool: + raise NotImplementedError + + def get_function(self) -> types.FunctionType: + raise NotImplementedError + + def get_module(self) -> str: + return self.get_globals()["__name__"] + + def _get_defaults(self, tx: "InstructionTranslatorBase") -> VariableTracker: + d = getattr(self, "defaults", None) + return d if d is not None else ConstantVariable.create(None) + + def _get_named_attr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + fn_dict = self.get_dict_vt(tx) + if fn_dict.contains(name): + return fn_dict.getitem(name) + val = getattr(self, f"get_{name[2:-2]}")() + return ConstantVariable.create( + val, source=self.source and AttrSource(self.source, name) + ) + + def _get_annotations(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # func_get_annotations lazily creates and stores an empty dict. The dict + # is a fresh value (ValueMutationNew), so it must carry no source. + if self.annotations is None: + self.annotations = variables.ConstDictVariable( + {}, mutation_type=ValueMutationNew() + ) + return self.annotations + + def _get_type_params(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.get_dict_vt(tx).getitem_or_default( + "__type_params__", + lambda: variables.TupleVariable([], mutation_type=ValueMutationNew()), + ) + + def _get_kwdefaults(self, tx: "InstructionTranslatorBase") -> VariableTracker: + d = getattr(self, "kwdefaults", None) + return d if d is not None else ConstantVariable.create(None) + + def _get_closure(self, tx: "InstructionTranslatorBase") -> VariableTracker: + c = getattr(self, "closure", None) + return c if c is not None else ConstantVariable.create(None) + + tp_getset = { + "__defaults__": GetSet(_get_defaults, None), + "__kwdefaults__": GetSet(_get_kwdefaults, None), + "__name__": GetSet(lambda s, tx: s._get_named_attr(tx, "__name__")), + "__qualname__": GetSet(lambda s, tx: s._get_named_attr(tx, "__qualname__")), + "__code__": GetSet(lambda s, tx: s._get_named_attr(tx, "__code__")), + "__dict__": GetSet(lambda s, tx: s.get_dict_vt(tx)), + "__annotations__": GetSet(_get_annotations), + "__type_params__": GetSet(_get_type_params), + } + tp_members = { + "__doc__": Member(lambda s, tx: s._get_named_attr(tx, "__doc__")), + "__module__": Member(lambda s, tx: s._get_named_attr(tx, "__module__")), + "__closure__": Member(_get_closure), + } + + def lookup_instance_dict( + self, tx: "InstructionTranslatorBase", name: str + ) -> "VariableTracker | None": + # Arbitrary attributes set on a function object live in its __dict__ + # (tp_dictoffset). Resolve them at the instance-dict step so getattr + # finds them before call_getattr_fallback (which raises). Known dunder + # slots are handled earlier via tp_getset/tp_members and never reach here. + try: + fn = self.get_function() + except NotImplementedError: + return None + fn_dict = getattr(fn, "__dict__", None) + if not fn_dict or name not in fn_dict: + return None + source = self.get_source() + source = AttrSource(source, name) if source is not None else None + if source is not None: + return variables.LazyVariableTracker.create(fn_dict[name], source, tx=tx) + return VariableTracker.build(tx, fn_dict[name]) + + def call_getattr_fallback( + self, tx: "InstructionTranslatorBase", name: str + ) -> "VariableTracker | None": + # Functions have no __getattr__; reaching the fallback means the + # attribute genuinely does not exist (CPython + # _PyObject_GenericGetAttrWithDict step 7 raises AttributeError). + raise_observed_exception(AttributeError, tx, args=[name]) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Ignore patch_track_step_called from torch/optim/lr_scheduler.py - it just patches + # the optimizer.step method and we don't need to trace it + if ( + self.get_name() == "patch_track_step_called" + and self.get_filename().endswith("torch/optim/lr_scheduler.py") + ): + return ConstantVariable.create(None) + return tx.inline_user_function_return( + self, + [*self.self_args(), *args], + kwargs, + allow_nested_graph_breaks=True, + ) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + se_result = self._hasattr_check_side_effects(tx, name) + if se_result is not None: + return se_result + + result = False + + if name in fn_known_dunder_attrs or name == "__dict__": + result = True + else: + try: + result = hasattr(self.get_function(), name) # type: ignore[attr-defined] + except NotImplementedError: + result = False + return VariableTracker.build(tx, result) + + def closure_vars( + self, tx: "InstructionTranslatorBase" + ) -> dict[str, VariableTracker]: + return {} + + # Override to set whether or not nested graph breaks should be allowed + # if we create an inlining tx for this BaseUserFunctionVariable. + # See symbolic_convert.py for where this function is called. + def should_allow_nested_graph_breaks(self) -> bool: + return True + + +class UserFunctionVariable(BaseUserFunctionVariable): + """Some unsupported user-defined global function""" + + # PyFunction_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/funcobject.c#L1046 + _cpython_type = types.FunctionType + + _nonvar_fields = { + "fn", + "is_constant", + *BaseUserFunctionVariable._nonvar_fields, + } + + _TREE_MAP_MODULES = frozenset( + { + "optree", + "optree.ops", + "torch.utils._pytree", + "torch.utils._cxx_pytree", + } + ) + + @classmethod + def create_with_source(cls, value: Any, source: Any) -> "UserFunctionVariable": + install_guard(source.make_guard(GuardBuilder.CLOSURE_MATCH)) + return cls(value, source=source) + + def get_value_for_setattr(self) -> object | None: + return self.fn + + def __init__( + self, + fn: types.FunctionType | torch.jit.ScriptFunction, # type: ignore[type-arg] + is_constant: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if getattr(fn, "_dynamo_marked_constant", False): + # This method should be treated as a constant for the purposes of compilation + self.is_constant = True + else: + self.is_constant = False + + # TODO putting this here to avoid duplication, because we could hit this + # from several paths (e.g., SuperVariable or `tp_getattro_impl`s). + if not isinstance(fn, (types.FunctionType, torch.jit.ScriptFunction)): + unimplemented( + gb_type="can't handle functions not implemented in python ", + context=f"{fn}", + explanation="Dynamo can only handle functions defined in python", + hints=[ + "Move usage of this function out of `torch.compile` region", + *graph_break_hints.INFERENCE_MODE, + ], + ) + # TODO(anijain2305) - Replace directly calling UserFunctionVariable with + # VariableBuilder, which handles the wrapping of _torchdynamo_inline. + # unpack @torch._dynamo.optimize()(fn) wrapped function + fn = inspect.getattr_static(fn, "_torchdynamo_inline", fn) + self.fn = fn + + def as_python_constant(self) -> Any: + if istype(self, UserFunctionVariable): + return self.fn + # subclasses (such as methods) usually aren't a constant + return super().as_python_constant() + + def reconstruct_pycode(self, codegen): + if self.source: + return self.source.reconstruct_pycode(codegen) + raise NotImplementedError( + "Python codegen not implemented for sourceless UserFunctionVariable" + ) + + def get_real_python_backed_value(self) -> Any: + if istype(self, UserFunctionVariable): + return self.fn + return super().get_real_python_backed_value() + + def self_args(self) -> list[VariableTracker]: + return [] + + def get_function(self) -> types.FunctionType: + return self.fn + + def get_code(self) -> types.CodeType: + return self.fn.__code__ + + def python_type(self) -> type: + return types.FunctionType + + def has_self(self) -> bool: + return getattr(self.fn, "__self__", None) is not None + + def get_globals(self) -> dict[str, Any]: + return self.fn.__globals__ + + def should_allow_nested_graph_breaks(self) -> bool: + from torch._dynamo.trace_rules import ( + BUILTIN_INLINE_WHEN_CALLED, + is_ngb_suppressed_inline, + ) + + filename = self.get_filename() + if any(filename.startswith(d) for d in BUILTIN_INLINE_WHEN_CALLED): + return False + if is_ngb_suppressed_inline(filename): + return False + return True + + def get_source(self) -> Source: + source = self.source + + if source and isinstance(self, variables.UserMethodVariable): + source = self.source_fn # type: ignore[assignment] + return source # type: ignore[return-value] + + def bind_args( + self, + parent: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> dict[str, VariableTracker]: + """ + Assume `args` and `kwargs` are VariableTracker arguments for a call to + this function, create new bindings for initial locals. + """ + if self.is_constant: + raise AssertionError( + "bind_args should not be called on a constant function" + ) + + fn: types.FunctionType = self.fn + + if not isinstance(fn, FunctionType): + raise TypeError("Only supports regular Python functions.") + root_tx = parent.output.root_tx + + source = self.get_source() + result = bind_args_cached(fn, root_tx, source, args, kwargs) # type: ignore[arg-type] + + init_cellvars(parent, result, fn.__code__) + closure = self.fn.__closure__ or () + if len(closure) != len(self.fn.__code__.co_freevars): + raise AssertionError( + f"closure length {len(closure)} does not match " + f"co_freevars length {len(self.fn.__code__.co_freevars)}" + ) + for idx, name, cell in zip( + itertools.count(), self.fn.__code__.co_freevars, closure + ): + # TODO refactor these 3 branches. + side_effects = parent.output.side_effects + if cell in side_effects: + cell_var = side_effects[cell] + + elif source: + closure_cell = GetItemSource(ClosureSource(source), idx) + closure_cell_contents = CellContentsSource( + closure_cell, "cell_contents", freevar_name=name + ) + try: + contents_var = VariableTracker.build( + parent, cell.cell_contents, closure_cell_contents + ) + except ValueError: + # Cell has not yet been assigned + contents_var = variables.DeletedVariable() + cell_var = side_effects.track_cell_existing( + closure_cell, cell, contents_var + ) + + else: + # TODO figure out why source isn't available here, and whether + # we can fix that and remove this branch. + try: + contents_var = VariableTracker.build(parent, cell.cell_contents) + except ValueError: + # Cell has not yet been assigned + contents_var = variables.DeletedVariable() + cell_var = side_effects.track_cell_existing(None, cell, contents_var) + + result[name] = cell_var + + return result + + # func.__get__ binds the function to an instance via the tp_descr_get slot + # wrapper. https://github.com/python/cpython/blob/v3.13.0/Objects/funcobject.c#L1119 + def _get_dunder_get(self, tx: "InstructionTranslatorBase") -> VariableTracker: + source = self.get_source() + source = AttrSource(source, "__get__") if source is not None else None + return VariableTracker.build(tx, self.fn.__get__, source) + + def _fn_getattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + return fn_getattro_impl(tx, self.fn, self.get_source(), name) + + # A real function object backs this VT, so resolve the function slots by + # reflecting on it (fn_getattro_impl) rather than via the synthesized + # get_*-based tables inherited from BaseUserFunctionVariable (which assume + # synthesized fields like self.defaults). These win over the base entries + # under MRO-merge resolution. __dict__ inherits the base getset (get_dict_vt). + tp_getset = { + "__get__": GetSet(_get_dunder_get, None), + "__name__": GetSet(lambda s, tx: s._fn_getattr(tx, "__name__")), + "__qualname__": GetSet(lambda s, tx: s._fn_getattr(tx, "__qualname__")), + "__code__": GetSet(lambda s, tx: s._fn_getattr(tx, "__code__")), + "__defaults__": GetSet(lambda s, tx: s._fn_getattr(tx, "__defaults__")), + "__kwdefaults__": GetSet(lambda s, tx: s._fn_getattr(tx, "__kwdefaults__")), + "__annotations__": GetSet(lambda s, tx: s._fn_getattr(tx, "__annotations__")), + "__type_params__": GetSet(lambda s, tx: s._fn_getattr(tx, "__type_params__")), + } + tp_members = { + "__doc__": Member(lambda s, tx: s._fn_getattr(tx, "__doc__")), + "__module__": Member(lambda s, tx: s._fn_getattr(tx, "__module__")), + "__closure__": Member(lambda s, tx: s._fn_getattr(tx, "__closure__")), + } + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> VariableTracker: + # Mirrors func_descr_get which calls PyMethod_New to bind + # the function to an instance. + # https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1119 + source = obj.source and AttrSource(obj.source, self.fn.__name__) + return UserMethodVariable(self.fn, obj, source_fn=self.source, source=source) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Handle patch_dynamo_config call + if self.fn is torch._dynamo.patch_dynamo_config: + try: + args_const = [arg.as_python_constant() for arg in args] + kwargs_const = { + key: val.as_python_constant() for key, val in kwargs.items() + } + changes = torch._dynamo.patch_dynamo_config( + *args_const, **kwargs_const + ).changes + return variables.DynamoConfigPatchVariable(changes) + except AsPythonConstantNotImplementedError as e: + raise RuntimeError( + "Cannot convert patch_dynamo_config args/kwargs to constants. " + "Please fix your call to patch_dynamo_config by using simpler inputs. " + f"args: {args}, kwargs: {kwargs}" + ) from e + elif self.fn is torch._dynamo.error_on_graph_break: + try: + bound = inspect.signature(self.fn).bind(*args, **kwargs) + error_on_graph_break = bound.arguments[ + "error_on_graph_break" + ].as_python_constant() + if not isinstance(error_on_graph_break, bool): + raise AssertionError( + f"error_on_graph_break must be a bool, got {type(error_on_graph_break)}" + ) + return variables.ErrorOnGraphBreakVariable(error_on_graph_break) + except Exception as e: + raise RuntimeError( + "Improper error_on_graph_break() call. Please fix your call to error_on_graph_break(). " + f"args: {args}, kwargs: {kwargs}" + ) from e + elif self.fn is torch._dynamo.override_cudagraphs: + try: + bound = inspect.signature(self.fn).bind(*args, **kwargs) + bound.apply_defaults() + fwd = bound.arguments["fwd"] + bwd = bound.arguments["bwd"] + if isinstance(fwd, VariableTracker): + fwd = fwd.as_python_constant() + if isinstance(bwd, VariableTracker): + bwd = bwd.as_python_constant() + return variables.CudagraphOverrideVariable(fwd, bwd) + except Exception as e: + raise RuntimeError( + "Improper override_cudagraphs() call. Please fix your call to override_cudagraphs(). " + f"args: {args}, kwargs: {kwargs}" + ) from e + elif self.fn is torch._dynamo.bytecode_debugger.breakpoint: + tx.output._emit_debugger_breakpoint = True + return variables.ConstantVariable.create(None) + # Handle a `nonstrict_trace(fn)` call + elif self.fn is torch._dynamo.nonstrict_trace: + bound = inspect.signature(self.fn).bind(*args, **kwargs) + fn_var = bound.args[0] + if not isinstance(fn_var, BaseUserFunctionVariable): + typ = fn_var.python_type() + msg = f"`nonstrict_trace` expects a callable, but got value of type <{typ.__name__}>" + unimplemented( + gb_type="TypeError from user code", + context=f"call_function({self.value}, {args}, {kwargs})", # type: ignore[attr-defined] + explanation=msg, + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + if not isinstance(fn_var, UserFunctionVariable): + fn_name = fn_var.get_name() + msg = f"Applying `nonstrict_trace` to function <{fn_name}>; however, `nonstrict_trace` currently requires the function to be defined outside `torch.compile` region." + unimplemented( + gb_type="Limitation of `nonstrict_trace", + context=f"{self}", + explanation=msg, + hints=[ + f"make sure definition of {fn_name} is outside ", + "`torch.compile` region", + ], + ) + + fn = fn_var.fn + return variables.TorchInGraphFunctionVariable( + fn, kind=variables.torch.AllowInGraphKind.NONSTRICT_TRACE + ) + + if self.is_constant: + return invoke_and_store_as_constant( + tx, self.fn, self.get_name(), args, kwargs + ) + + if ( + not tx.output.current_tracer.unsafe_allow_externally_visible_side_effects + and self.fn + is torch._dynamo.utils._disable_side_effect_safety_checks_for_current_subtracer + ): + with torch._dynamo.side_effects.allow_externally_visible_side_effects_in_subtracer( + tx + ): + return super().call_function(tx, args, kwargs) + + if ( + getattr(tx.output.current_tracer, "description", None) + == "torch.utils.checkpoint.checkpoint" + and not tx.output.current_tracer.allow_side_effects_in_hop + ): + try: + from torch.distributed.fsdp._fully_shard._fsdp_state import FSDPState + except Exception: + FSDPState = None # type: ignore[assignment, misc] + if FSDPState is not None and self.fn in [ + FSDPState._pre_forward, + FSDPState._post_forward, + ]: + with torch._dynamo.side_effects.allow_side_effects_in_hop(tx): + return super().call_function(tx, args, kwargs) + + tree_map_result = self._maybe_call_tree_map_fastpath(tx, args, kwargs) + if tree_map_result is not None: + return tree_map_result + + return super().call_function(tx, args, kwargs) + + def _maybe_call_tree_map_fastpath( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + rewrite = self._rewrite_tree_map_only_call(tx, args, kwargs) + if rewrite is not None: + tree_map_fn, tree_map_args, tree_map_kwargs = rewrite + else: + tree_map_fn = self + tree_map_args = args + tree_map_kwargs = kwargs + + is_tree_map = ( + isinstance(tree_map_fn, UserFunctionVariable) + and tree_map_fn._is_tree_map_function() + ) + is_tree_map_with_path = ( + isinstance(tree_map_fn, UserFunctionVariable) + and tree_map_fn._is_tree_map_with_path_function() + ) + + if not (is_tree_map or is_tree_map_with_path): + return None + if {*tree_map_kwargs} - _SUPPORTED_TREE_MAP_KWARGS: + return None + if len(tree_map_args) < 2: + return None + + map_fn = tree_map_args[0] + first_tree = tree_map_args[1] + rest = tree_map_args[2:] + + # The tree_map fast path doesn't create an InliningIT for tree_map, + # so NGB resume functions would miss the tree_map continuation. + with torch._dynamo.disable_nested_graph_breaks(): + if is_tree_map_with_path: + return first_tree.call_tree_map_with_path( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath=(), + ) + else: + return first_tree.call_tree_map( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + + def _is_tree_map_function(self) -> bool: + return ( + getattr(self.fn, "__name__", None) == "tree_map" + and getattr(self.fn, "__module__", None) in self._TREE_MAP_MODULES + ) + + def _is_tree_map_with_path_function(self) -> bool: + return ( + getattr(self.fn, "__name__", None) == "tree_map_with_path" + and getattr(self.fn, "__module__", None) in self._TREE_MAP_MODULES + ) + + def _is_tree_map_only_function(self) -> bool: + return ( + getattr(self.fn, "__name__", None) == "tree_map_only" + and getattr(self.fn, "__module__", None) in self._TREE_MAP_MODULES + ) + + def _rewrite_tree_map_only_call( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> ( + tuple[ + "UserFunctionVariable", + list[VariableTracker], + dict[str, VariableTracker], + ] + | None + ): + if not self._is_tree_map_only_function(): + return None + + if len(args) != 3: + return None + if {*kwargs} - _TREE_MAP_ONLY_SUPPORTED_KWARGS: + return None + + type_selector, map_fn, tree_arg = args + allowed_types = self._extract_tree_map_only_types(type_selector) + if allowed_types is None: + return None + + tree_map_callable = self._lookup_tree_map_function() + if tree_map_callable is None: + return None + + wrapped_map_fn = TreeMapOnlyFunctionVariable( + allowed_types, + map_fn, + source=getattr(map_fn, "source", None), + ) + tree_map_variable = VariableTracker.build(tx, tree_map_callable) + return tree_map_variable, [wrapped_map_fn, tree_arg], dict(kwargs) + + def _lookup_tree_map_function(self) -> types.FunctionType | None: + module_name = getattr(self.fn, "__module__", None) + if not module_name: + return None + module = sys.modules.get(module_name) + if module is None: + return None + tree_map = getattr(module, "tree_map", None) + if isinstance(tree_map, types.FunctionType): + return tree_map + return None + + def _extract_tree_map_only_types( + self, selector: VariableTracker + ) -> tuple[type, ...] | None: + if not selector.is_python_constant(): + return None + try: + raw_value = selector.as_python_constant() + except NotImplementedError: + return None + + flattened = self._flatten_type_spec(raw_value) + if not flattened: + return None + if not all(isinstance(typ, type) for typ in flattened): + return None + return tuple(dict.fromkeys(flattened)) + + def _flatten_type_spec(self, value: Any) -> list[type] | None: + if isinstance(value, type): + return [value] + if isinstance(value, tuple): + collected: list[type] = [] + for entry in value: + flat = self._flatten_type_spec(entry) + if flat is None: + return None + collected.extend(flat) + return collected + union_type = getattr(types, "UnionType", None) + if union_type is not None and isinstance(value, union_type): + collected = [] + for entry in typing.get_args(value): + flat = self._flatten_type_spec(entry) + if flat is None: + return None + collected.extend(flat) + return collected + return None + + +class InspectSignatureVariable(UserFunctionVariable): + """ + Variable tracker for inspect.signature with caching support. + + inspect.Signature is expensive to trace. When inspect.signature is called + repeatedly on the same function during tracing, we cache the result to avoid + retracing the signature construction each time. Although this is different + from CPython behavior, it is safe to do so because inspect.signature does + not change across different calls to the same function. + """ + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Fast path: cache results for repeated calls on the same function + if len(args) == 1 and not kwargs: + target_arg = args[0] + cache_key = None + + if isinstance(target_arg, (UserFunctionVariable, UserMethodVariable)): + cache_key = target_arg.get_function() + + if cache_key is not None: + if cache_key in tx.output.signature_cache: + return tx.output.signature_cache[cache_key] + + result = super().call_function(tx, args, kwargs) + tx.output.signature_cache[cache_key] = result + return result + + return super().call_function(tx, args, kwargs) + + +class TreeMapOnlyFunctionVariable(BaseUserFunctionVariable): + _nonvar_fields = { + "allowed_types", + *BaseUserFunctionVariable._nonvar_fields, + } + + def __init__( + self, + allowed_types: tuple[type, ...], + map_fn: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.allowed_types = allowed_types + self.map_fn = map_fn + + def python_type(self) -> type: + return FunctionType + + def _matches_allowed_type(self, node: VariableTracker) -> bool: + try: + node_type = node.python_type() + except NotImplementedError: + return False + return any(issubclass(node_type, allowed) for allowed in self.allowed_types) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if not args: + return self.map_fn.call_function(tx, args, kwargs) + leaf = args[0] + if self._matches_allowed_type(leaf): + return self.map_fn.call_function(tx, args, kwargs) + if len(args) != 1 or kwargs: + # Defer to the original map function so we fall back to normal + # tracing instead of triggering a graph break. + return self.map_fn.call_function(tx, args, kwargs) + return leaf + + +class LocalGeneratorObjectVariable(VariableTracker): + # PyGen_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/genobject.c#L814 + _cpython_type = types.GeneratorType + + def __init__( + self, + code: types.CodeType, + f_globals: dict[str, Any], + inline_tracer: "InliningGeneratorInstructionTranslator", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.code = code + self.f_globals = f_globals + self.inline_tracer = inline_tracer + self.remaining_items: list[VariableTracker] = [] + inline_tracer.output.track_generator(self) + + def get_code(self) -> types.CodeType: + return self.code + + def get_filename(self) -> str: + return self.get_code().co_filename + + def get_name(self) -> str: + return self.get_code().co_name + + def get_function(self) -> Never: + raise NotImplementedError("get_function") + + def has_self(self) -> bool: + return False + + def __name__(self) -> str: + return self.get_name() + + def __str__(self) -> str: + return f"{self.__class__.__name__}({self.get_name()})" + + __repr__ = __str__ + + def reconstruct(self, codegen: "PyCodegen") -> None: + from torch._dynamo.side_effects import disallow_side_effects_in_generator + from torch._dynamo.symbolic_convert import ( + save_and_restart_speculation_log, + temporarely_allow_writes_to_output_graph, + ) + + tx = codegen.tx + save = save_and_restart_speculation_log(tx) + disallow = disallow_side_effects_in_generator(tx) + temp = temporarely_allow_writes_to_output_graph(tx) + + with save, disallow, temp: + if not self._frame_state_finished(): + self.remaining_items = unpack_iterable(tx, self) # type: ignore[bad-argument-type] + variables.ListIteratorVariable(self.remaining_items).reconstruct(codegen) + + def get_globals(self) -> dict[str, Any]: + return self.f_globals + + def python_type(self) -> type: + return types.GeneratorType + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # Generators have no tp_richcompare: identity for ==/!=, TypeError for + # ordering. + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def pygen_yf(self) -> VariableTracker | None: + if self.inline_tracer.frame_state == FrameState.FRAME_SUSPENDED_YIELD_FROM: + if sys.version_info >= (3, 15): + ind = -2 + else: + ind = -1 + return self.inline_tracer.stack[ind] + return None + + def gen_send_ex2( + self, + tx: "InstructionTranslatorBase", + arg: VariableTracker, + exc: bool, + ) -> VariableTracker: + # https://github.com/python/cpython/blob/f31a89bb901067dd105b00cfa90523cf7ffdbbdd/Objects/genobject.c#L259 + tracer = self.inline_tracer + + if ( + tracer.frame_state == FrameState.FRAME_CREATED + and not arg.is_constant_none() + ): + raise_type_error( + tx, + "can't send non-None value to a just-started generator", + ) + + if tracer.frame_state == FrameState.FRAME_EXECUTING: + raise_value_error(tx, "generator already executing") + + if self._frame_state_finished(): + raise_observed_exception(StopIteration, tx) + + tracer.frame_state = FrameState.FRAME_EXECUTING + + try: + # Hierarchically, tx can be seen as the parent of the inline tracer + # created on call_function. Any exception needs to be propagated to tx + # for Dynamo to behave correctly + tracer.push(arg) + with self.inline_tracer.link_gi_exc_state(): + if exc: + self.throw_pending() + return tracer.inline_call_() + except ObservedUserStopIteration: + # PEP 479: pre-3.12 has no STOPITERATION_ERROR opcode, so convert a + # StopIteration that escapes the generator body to RuntimeError here + # at the frame boundary. https://github.com/python/cpython/pull/99006 + # A normal return sets FRAME_CLEARED and raises a synthetic + # StopIteration to signal exhaustion; that one must stay a + # StopIteration, so only convert when the body was still executing. + was_executing = tracer.frame_state == FrameState.FRAME_EXECUTING + tracer.frame_state = FrameState.FRAME_COMPLETED + if sys.version_info < (3, 12) and was_executing: + # Match CPython's _PyErr_FormatFromCause: set __context__ and + # __cause__ directly rather than pushing onto the exception + # stack (which must stay balanced -- genobject.c pops the + # generator's gi_exc_state before the conversion runs, so the + # caller's stack is left unchanged). do_raise sets __cause__; + # set __context__ first so set_exception_obj's implicit chaining + # leaves it untouched. + prev = tracer.exn_vt_stack.get_raised_exception() + rt = VariableTracker.build(tx, RuntimeError).call_function( + tx, + [VariableTracker.build(tx, "generator raised StopIteration")], + {}, + ) + rt.call_method( + tx, + "__setattr__", + [ConstantVariable.create("__context__"), prev], + {}, + ) + tx.do_raise(rt, prev) + raise + except ObservedException: + # An exception propagating out of the generator frame finishes it, + # mirroring CPython setting gi_frame_state = FRAME_CLEARED. + tracer.frame_state = FrameState.FRAME_CLEARED + raise + except InfiniteGeneratorError: + # test/dynamo/test_misc.py::test_iterator_limit + unimplemented( + gb_type="infinite generator detected", + context="", + explanation="Dynamo traced the YIELD_VALUE bytecode too many times. This could mean " + "that we have attempted to trace an infinite generator.", + hints=[ + f"If you are sure that your generator is not infinite, please report a bug at {PT2_ISSUE_TRACKER_URL}.", + *graph_break_hints.USER_ERROR, + ], + ) + except Unsupported as e: + torch._dynamo.eval_frame.skip_code(self.get_code()) + e.skip_frame = True + if not tx.one_graph and not tx.error_on_graph_break: + e.msg += "\n\nSkipping frame due to graph break in a generator's next() call." + raise + + def gen_send_ex( + self, + tx: "InstructionTranslatorBase", + arg: VariableTracker, + exc: bool, + ) -> VariableTracker: + # rule of thumb for gen_send_ex2: + # - PYGEN_RETURN => No exception raised + # - PYGEN_ERROR => Exception raised + # - PYGEN_NEXT => yielded - frame suspended + # gen_send_ex raises StopIteration if gen_send_ex2 returns PYGEN_RETURN + result = self.gen_send_ex2(tx, arg, exc) + if self._frame_state_suspended(): + # PYGEN_NEXT + return result + else: + # PYGEN_RETURN + if result.is_constant_none(): + raise_observed_exception(StopIteration, tx) + else: + raise_observed_exception(StopIteration, tx, args=[result]) + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/genobject.c#L832 + return self.gen_send_ex2(tx, ConstantVariable.create(None), False) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if name in self.python_type().__dict__: + return ConstantVariable.create(True) + return ConstantVariable.create(False) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/genobject.c#L831 + return self + + # no nested graph breaks in generators + def should_allow_nested_graph_breaks(self) -> Literal[False]: + return False + + def _setup_exception( + self, tx: "InstructionTranslatorBase", exc: VariableTracker + ) -> None: + # Set up the exception to be raised in the generator frame + from torch._dynamo.symbolic_convert import ExceptionTypes, ExceptionVals + + # Instantiate if an exception type was passed (builtin or user-defined). + if not isinstance(exc, (ExceptionTypes, ExceptionVals)): + raise TypeError( + f"Expected an exception type or instance, got {exc.python_type_name()}" + ) + val = tx._create_exception_instance(exc) + if not isinstance(val, ExceptionVals): + raise AssertionError(f"Expected an exception variable, got {val}") + self.inline_tracer.exn_vt_stack.set_raised_exception(val) + + def _frame_state_created(self) -> bool: + return self.inline_tracer.frame_state == FrameState.FRAME_CREATED + + def _frame_state_finished(self) -> bool: + return self.inline_tracer.frame_state in { + FrameState.FRAME_COMPLETED, + FrameState.FRAME_CLEARED, + } + + def _frame_state_suspended(self) -> bool: + return self.inline_tracer.frame_state in { + FrameState.FRAME_SUSPENDED, + FrameState.FRAME_SUSPENDED_YIELD_FROM, + } + + def gen_send( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Sends a value into the generator function. Returns the next value + # yielded by the generator, or raises StopIteration if the generator + # exits without yielding another value + return self.gen_send_ex(tx, args[0], False) + + def gen_close( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # * Raises a GeneratorExit at the point where the generator function was paused. + # * If the generator function catches the exception and returns a + # value, this value is returned from close() - Python 3.13+ + # * If the generator function is already closed, or raises GeneratorExit + # (by not catching the exception), close() returns None. + # * If the generator yields a value, a RuntimeError is raised. + # * If the generator raises any other exception, it is propagated to the caller. + # * If the generator has already exited due to an exception or normal + # exit, close() returns None and has no other effect. + + # Return None if close is called on a just-started generator + # See test GeneratorCloseCpythonTests::test_close_not_started + + tracer = self.inline_tracer + if self._frame_state_created(): + tracer.frame_state = FrameState.FRAME_COMPLETED + return ConstantVariable.create(None) + + if self._frame_state_finished(): + return ConstantVariable.create(None) + + err = False + yf = self.pygen_yf() + if yf: + with tracer.temporarily_set_frame_state(FrameState.FRAME_EXECUTING): + try: + yf.call_method(tx, "close", [], {}) + except ObservedException: + err = True + + if err is False: + self._setup_exception(tx, VariableTracker.build(tx, GeneratorExit)) + + try: + self.gen_send_ex(tx, ConstantVariable.create(None), True) + except ObservedGeneratorExit as e: + # Drop the traceback to break the exception -> traceback -> frame -> + # (raised_exception, self) reference cycle. Otherwise the generator's + # inline_tracer (and the OutputGraph it points at) survives until + # cyclic GC instead of being freed by refcount at frame exit. + e.__traceback__ = None + return ConstantVariable.create(None) + except ObservedUserStopIteration: + # generator returned a value while closing. gen_send_ex() raises + # StopIteration with the value returned + curr_exc = tracer.exn_vt_stack.get_raised_exception() + if not isinstance(curr_exc, variables.ExceptionVariable): + # make pyrefly happy + raise AssertionError( + f"Expected current exception to be an ExceptionVariable, got {curr_exc}" + ) from None + if curr_exc.args: + return curr_exc.args[0] + else: + # if it reaches here, the generator yielded a value while closing + raise_observed_exception( + RuntimeError, + tx, + args=["generator ignored GeneratorExit"], + ) + return ConstantVariable.create(None) + + def throw_pending(self) -> None: + tracer = self.inline_tracer + curr_exc = tracer.exn_vt_stack.get_raised_exception() + observed = get_dynamo_observed_exception(curr_exc.python_type())() + curr_type = VariableTracker.build(tracer, curr_exc.exc_type) + tracer.set_exception_obj(curr_type, curr_exc) + tracer.exception_handler(observed) + + def gen_throw( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # * Raises an exception at the point where the generator was paused, and + # returns the next value yielded by the generator. + # * If the generator exits without yielding, raise StopIteration + # * If the generator function does not catch the passed-in exception, + # or raises a different exception, then that exception propagates to the caller. + def throw_here(): + self._setup_exception(tx, arg) + return self.gen_send_ex(tx, ConstantVariable.create(None), True) + + from torch._dynamo.symbolic_convert import pyerr_given_exception_match + + arg = args[1] if len(args) > 1 else args[0] + yf = self.pygen_yf() + tracer = self.inline_tracer + + if yf: + # CPython has an extra flag for handling async generators + if pyerr_given_exception_match(arg, GeneratorExit): + try: + # CPython uses gen_close_iter here + with tracer.temporarily_set_frame_state(FrameState.FRAME_EXECUTING): + yf.call_method(tx, "close", [], {}) + except ObservedException: + pass + return throw_here() + + try: + with tracer.temporarily_set_frame_state(FrameState.FRAME_EXECUTING): + return yf.call_method(tx, "throw", [arg], {}) + except ObservedException: + return self.gen_send_ex(tx, ConstantVariable.create(None), True) + + return throw_here() + + tp_methods = { + "send": Method(gen_send), + "close": Method(gen_close), + "throw": Method(gen_throw), + } + + +class ContextlibContextManagerLocalGeneratorObjectVariable( + LocalGeneratorObjectVariable +): + """ + .. note:: + + This is only used when the function is annotated with @contextlib.contextmanager + + It is a special case of a generator function as we do not allow return a context manager + from a torch.compile function. + """ + + +class LocalGeneratorFunctionVariable(BaseUserFunctionVariable): + """functions that behaves like iterators + + .. note:: + + This is a wrapper around (Nested)UserFunctionVariable + """ + + def python_type(self) -> type: + return types.FunctionType + + def __init__( + self, + vt: BaseUserFunctionVariable, + *, + generator_cls: type = LocalGeneratorObjectVariable, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.vt = vt + self.generator_cls = generator_cls + + def __getattr__(self, name: str) -> Any: + if name in self.__class__.__dict__: + return getattr(self, name) + return getattr(self.vt, name) + + # These need to be explicit so the custom __getattr__ doesn't fall back to the unimplemented base class version + def get_code(self) -> types.CodeType: + return self.vt.get_code() + + def get_globals(self) -> dict[str, Any]: + return self.vt.get_globals() + + def has_self(self) -> bool: + return self.vt.has_self() + + def _build_inline_tracer( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "InliningInstructionTranslator": + from torch._dynamo.symbolic_convert import InliningInstructionTranslator + + return InliningInstructionTranslator.build_inline_tracer( + tx, + self, + args, + kwargs, + ) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if isinstance(self.vt, SkipFunctionVariable): + unimplemented( + gb_type="generator function over a skipped function", + context=str(self.vt), + explanation="Cannot trace a generator whose underlying function is skipped by Dynamo " + "(e.g. defined in a skip-listed module), since its body cannot be symbolically traced.", + hints=[*graph_break_hints.FUNDAMENTAL], + ) + if not is_generator(self.vt.get_code()): + unimplemented( + gb_type="non-generator contextlib.contextmanager", + context=str(self.vt.get_code()), + explanation="Cannot compile function decorated with `@contextlib.contextmanager` that is not a generator" + ", i.e. does not use `yield`", + hints=[ + "Use `yield` in the function body instead of `return`.", + "Remove the `@contextlib.contextmanager` decorator.", + ], + ) + + inline_tracer = self._build_inline_tracer(tx, list(args), kwargs) + code = self.vt.get_code() + f_globals = self.vt.get_globals() + + if sys.version_info >= (3, 11): + inline_tracer.inline_call_() + # calling a generator returns a generator object + return self.generator_cls( + code, + f_globals, + inline_tracer, # type: ignore[arg-type] + source=self.source, + ) + + def get_real_python_backed_value(self) -> object: + return self.vt.get_real_python_backed_value() + + +class FunctionDecoratedByContextlibContextManagerVariable( + LocalGeneratorFunctionVariable +): + """ + .. note:: + + This is only used when the function is annotated with @contextlib.contextmanager + """ + + def __init__(self, vt: BaseUserFunctionVariable, **kwargs: Any) -> None: + super().__init__( + vt, + generator_cls=ContextlibContextManagerLocalGeneratorObjectVariable, + **kwargs, + ) + + +class UserMethodVariable(UserFunctionVariable): + """Some unsupported user-defined method""" + + # PyMethod_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/classobject.c#L332 + _cpython_type = types.MethodType + + def __init__( + self, + fn: Callable[..., Any], + obj: VariableTracker, + source_fn: Source | None = None, + **kwargs: Any, + ) -> None: + super().__init__(fn=fn, **kwargs) # type: ignore[arg-type] + self.obj = obj + self.source_fn = source_fn + # Note on source and source_fn + # Be careful with `source` when delegating to UserFunctionVariable + # (base-class) methods. In this __init__, `source` is a *bound method* + # object, but the base class expects the underlying *function* object. + # One way is to simplly use `__func__` to unwrap it. + # + # For recursive dict-tag optimizations, it can be faster to fetch the + # function directly from `cls.__dict__`; that's why we pass on + # `source_fn`. Whenever it is possible to access the function from + # cls.__dict__, we pass that on to `source_fn`. Because bind_args + # operates on the unbound function, most guards should target + # `source_fn` rather than the original `source`. + if source_fn is None and kwargs.get("source") is not None: + self.source_fn = AttrSource(kwargs.get("source"), "__func__") # type: ignore[assignment, arg-type] + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.fn}, {self.obj})" + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CPython method_hash: hash(self) ^ hash(func) + # https://github.com/python/cpython/blob/e76aa128fe/Objects/classobject.c#L304 + if self.source: + real_val = tx.output.resolve_source_value(self.source) + return hash(real_val), False + # Sourceless: compute method_hash from components. + from .object_protocol import generic_hash_impl + + self_hash, self_fake = generic_hash_impl(tx, self.obj) + func_hash = hash(self.fn) + h = self_hash ^ func_hash + if h == -1: + h = -2 + return h, self_fake + + def self_args(self) -> list[VariableTracker]: + return [self.obj] + + def python_type(self) -> type[types.MethodType]: + return types.MethodType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # NOTE this is to handle methods annotated by `nonstrict_trace`. + # a `nonstrict_trace`-ed function will be wrapped by + # `VariableTracker.build` and route to `TorchInGraphFunctionVariable`, + # but in the case of method, we manually wrap it with `UserMethodVariable` + # inside `UserDefinedObjectVariable.tp_getattro_impl`. + # + # We might be able to simplify this away by canonicalizing the + # function/method wrapping code paths. + from ..trace_rules import is_leaf_function, is_nonstrict_trace_callable + + if is_nonstrict_trace_callable(self.fn): + call_args = [*self.self_args(), *args] + var = variables.TorchInGraphFunctionVariable( + self.fn, kind=variables.torch.AllowInGraphKind.NONSTRICT_TRACE + ) + return var.call_function(tx, call_args, kwargs) + + if is_leaf_function(self.fn): + call_args = [*self.self_args(), *args] + var = variables.TorchInGraphFunctionVariable( + self.fn, kind=variables.torch.AllowInGraphKind.LEAF_FUNCTION + ) + return var.call_function(tx, call_args, kwargs) + + # For nn.Module methods, redirecting to NNModuleVariable.call_method for optimized solution + # rather than simple inlining. E.g, putting `call_method` op in FX graph for `forward` method + # since we ensure `forward` of allowed modules can be traced by AOT safely. + # Note this is not only for allowed modules, as user customized modules can extend from + # allowed modules but using parent's `forward` method, which is also covered by this branch. + + # If we are tracing the higher order op, we want Dynamo to step inside + # the module call so that Dynamo can see the underlying parameters and + # buffers and raise them as inputs to the graph. The is_root_tracer + # check bypasses the if condition for non-root tracers and directly + # calls the super().call_function at the end, which is basically + # equivalent of inlining the method. + if tx.output.is_root_tracer() and isinstance( + self.obj, variables.NNModuleVariable + ): + module_attr = getattr(self.fn, "__module__", "") + # inline torch.nn.utils.parametrize + if ( + module_attr is not None + and module_attr.startswith("torch.nn.") + and module_attr != "torch.nn.utils.parametrize" + or self.is_constant + ): + return self.obj.call_method( + tx, self.fn.__name__, list(args), kwargs, constant=self.is_constant + ) + elif ( + _fsdp_param_group is not None + and self.fn is _fsdp_param_group.FSDPParamGroup.use_training_state # type: ignore[attr-defined] + ): + return variables.TorchCtxManagerClassVariable(self.fn).call_function( + tx, [self.obj, *args], kwargs + ) + if self.is_constant: + fn = getattr(self.obj.value, self.fn.__name__) # type: ignore[attr-defined] + return invoke_and_store_as_constant(tx, fn, self.get_name(), args, kwargs) + return super().call_function(tx, args, kwargs) + + def _get_func(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # We might have a better way to access the function object, this + # information is stored in self.source_fn, use that to construct the + # variable tracker. + return VariableTracker.build(tx, self.fn, self.source_fn) # type: ignore[arg-type] + + # __self__ / __func__ are read-only members on method objects. + # https://github.com/python/cpython/blob/v3.13.0/Objects/classobject.c#L20-L24 + tp_members = { + "__self__": Member(getset_read(lambda s: s.obj)), + "__func__": Member(_get_func, None), + } + + def get_real_python_backed_value(self) -> Any: + return self.fn + + +class WrappedUserMethodVariable(UserMethodVariable): + def __init__( + self, + wrapped: UserMethodVariable, + context: "ContextWrappingVariable", + **kwargs: Any, + ) -> None: + kwargs.pop("fn", None) + kwargs.pop("obj", None) + super().__init__(wrapped.fn, wrapped.obj, **kwargs) + self.wrapped = wrapped + self.context = context + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if config.nested_graph_breaks: + wrapper_fn = UserFunctionVariable(polyfills._fn_with_ctx) + return wrapper_fn.call_function( + tx, [self.context, self.wrapped] + list(args), kwargs + ) + self.context.enter(tx) + result = super().call_function(tx, args, kwargs) + self.context.exit(tx) + return result + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(self.context)) # type: ignore[arg-type] + codegen(self.wrapped) + codegen.extend_output(create_call_function(1, False)) + + +class WrappedUserFunctionVariable(UserFunctionVariable): + def __init__( + self, + wrapped: UserFunctionVariable, + context: "ContextWrappingVariable", + **kwargs: Any, + ) -> None: + kwargs.pop("fn", None) + super().__init__(wrapped.fn, **kwargs) + self.wrapped = wrapped + self.context = context + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if config.nested_graph_breaks: + wrapper_fn = UserFunctionVariable(polyfills._fn_with_ctx) + return wrapper_fn.call_function( + tx, [self.context, self.wrapped] + list(args), kwargs + ) + self.context.enter(tx) + result = super().call_function(tx, args, kwargs) + self.context.exit(tx) + return result + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(self.context)) # type: ignore[arg-type] + codegen(self.wrapped) + codegen.extend_output(create_call_function(1, False)) + + +def invoke_and_store_as_constant( + tx: "InstructionTranslatorBase", + fn: Callable[..., Any], + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + def convert(x: VariableTracker) -> Any: + if x.is_tensor(): + return cast("TensorVariable", x).get_real_value() + if isinstance(x, UserDefinedObjectVariable): + if x.source is not None: + install_guard(x.make_guard(GuardBuilder.ID_MATCH)) + return x.value + try: + return x.as_python_constant() + except AsPythonConstantNotImplementedError: + unimplemented( + gb_type="assume_constant_result argument conversion failed", + context=f"function {name}, variable type {type(x).__name__}", + explanation=f"Cannot convert argument of type {type(x).__name__} to a Python constant " + f"for function {name} marked with torch._dynamo.assume_constant_result. " + f"The variable tracker does not support constant conversion.", + hints=[ + "Remove torch._dynamo.assume_constant_result from this function", + "Ensure all arguments passed to the function can be converted to constants", + ], + ) + + args = [convert(x) for x in args] + kwargs = {k: convert(v) for k, v in kwargs.items()} + res = fn(*args, **kwargs) + return tx.output.register_attr_or_module( + res, + name, + source=ConstantSource(name), + ) + + +class NestedUserFunctionVariable(BaseUserFunctionVariable): + _nonvar_fields = { + "f_globals", + *BaseUserFunctionVariable._nonvar_fields, + } + + def __init__( + self, + fn_name: VariableTracker, + code: VariableTracker, + f_globals: dict[str, Any], + defaults: VariableTracker | None, + kwdefaults: VariableTracker | None, + closure: VariableTracker | None, + # This is present when this function is created by + # `functools.wrap(wrapped_fn)(this_fn)`. + wrapped_fn: VariableTracker | None = None, + **kwargs: Any, + ) -> None: + if kwargs.get("mutation_type") is None: + kwargs.update(mutation_type=AttributeMutationNew()) + super().__init__(**kwargs) + if not isinstance(fn_name.as_python_constant(), str): + raise AssertionError( + f"fn_name must be a str, got {type(fn_name.as_python_constant())}" + ) + if not isinstance(code.as_python_constant(), types.CodeType): + raise AssertionError( + f"code must be a CodeType, got {type(code.as_python_constant())}" + ) + if not isinstance(f_globals, dict): + raise AssertionError(f"f_globals must be a dict, got {type(f_globals)}") + self.fn_name = fn_name + self.code = code + self.f_globals = f_globals + self.defaults = defaults + self.kwdefaults = kwdefaults + self.closure = closure + self.wrapped_fn: VariableTracker | None = wrapped_fn + + def self_args(self) -> list[VariableTracker]: + return [] + + def as_python_constant(self) -> types.FunctionType: + return self.get_function() + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + try: + return super().tp_repr_impl(tx) + except ClosureConversionError as e: + unimplemented( + gb_type="repr() on nested function with non-constructible closure", + context=f"repr() on nested function {self.fn_name.as_python_constant()}: {e}", + explanation="Dynamo could not safely evaluate repr() for this " + "nested function because it could not reconstruct its closure " + "as Python constants.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def get_code(self) -> types.CodeType: + return self.code.as_python_constant() + + def python_type(self) -> type[types.FunctionType]: + return types.FunctionType + + def get_function( + self, + _converting: set[int] | None = None, + *, + allow_sourced_cells: bool = False, + ) -> types.FunctionType: + # _converting is used a way to break cycles when + # two nested_functions refer to each other. + from .base import AsPythonConstantNotImplementedError + + self_id = id(self) + if _converting is None: + _converting = set() + if self_id in _converting: + raise ClosureConversionError( + "cycle detected in mutually recursive closures" + ) + _converting.add(self_id) + try: + return self._get_function_impl(_converting, allow_sourced_cells) + except AsPythonConstantNotImplementedError as e: + raise ClosureConversionError( + "failed to convert closure cell to Python constant" + ) from e + finally: + _converting.discard(self_id) + + def is_python_constant(self) -> bool: + try: + self.as_python_constant() + return True + except (NotImplementedError, Unsupported): + return False + + def _get_function_impl( + self, _converting: set[int], allow_sourced_cells: bool + ) -> types.FunctionType: + closure_cells = None + if self.closure: + from torch._dynamo.symbolic_convert import InstructionTranslator + + tx = InstructionTranslator.current_tx() + cells = [] + + for cell_var in self.closure.items: # type: ignore[attr-defined] + # Get the cell contents from side_effects or pre_existing_contents + # load_cell will replay the side-effects + cell_contents = tx.output.side_effects.load_cell(cell_var) + + # Check for self-referential closure (function capturing itself for recursion) + # For example: + # def outer(): + # def helper(n): + # if n <= 0: + # return 0 + # return n + helper(n - 1) # helper calls itself + # return helper + if cell_contents is self: + raise ClosureConversionError("self-referential nested function") + + # If the cell contents is a NestedUserFunctionVariable, call get_function + # directly to properly propagate the _converting set for cycle detection + if isinstance(cell_contents, NestedUserFunctionVariable): + value = cell_contents.get_function( + _converting, + allow_sourced_cells=allow_sourced_cells, + ) + cells.append(make_cell(value)) + continue + + try: + value = cell_contents.as_python_constant() + cells.append(make_cell(value)) + continue + except (NotImplementedError, Unsupported): + if not allow_sourced_cells: + raise ClosureConversionError( + "failed to convert closure cell to Python constant" + ) from None + + # Non-constant closure cell (e.g. a class defined in a compiled + # region closing over a real object such as a TestCase + # instance). Only allow source-backed objects that have not + # been mutated during the trace, and pin their identity with + # an ID_MATCH guard. Materialize a real cell from the backing + # object and register it in side_effects mapping back to the + # traced VT, so that when methods of the built class are + # later inlined, bind_args reuses the original VT (preserving + # its source, guards, and identity) via load_cell. Only the + # __build_class__ path opts in; as_python_constant + # conversions must stay strict. + if not ( + isinstance(cell_contents, UserDefinedObjectVariable) + and cell_contents.source is not None + and not tx.output.side_effects.is_modified(cell_contents) + ): + raise ClosureConversionError( + "failed to convert closure cell to Python constant" + ) + value = cell_contents.guard_as_python_constant() + cell = make_cell(value) + tx.output.side_effects.track_cell_existing(None, cell, cell_contents) + cells.append(cell) + closure_cells = tuple(cells) + + func = types.FunctionType( + self.code.as_python_constant(), + self.f_globals, + self.fn_name.as_python_constant(), + argdefs=None, + closure=closure_cells, + ) + if self.defaults: + func.__defaults__ = self.defaults.as_python_constant() + if self.kwdefaults: + func.__kwdefaults__ = self.kwdefaults.as_python_constant() + if self.annotations: + annotations = self.annotations.as_python_constant() + if isinstance(annotations, tuple): + from itertools import pairwise + + annotations = dict(pairwise(annotations)) + + # TypeError: __annotations__ must be set to a dict object + if not isinstance(annotations, dict): + raise AssertionError( + f"annotations must be a dict, got {type(annotations)}" + ) + func.__annotations__ = annotations + return func + + def has_closure(self) -> bool: + return self.closure is not None + + def const_getattr(self, tx: "InstructionTranslatorBase", name: str) -> Any: + if name == "__name__": + return self.get_name() + if name == "__code__": + return self.get_code() + if name == "__defaults__": + d = getattr(self, "defaults", None) + return d.as_python_constant() if d else None + return super().const_getattr(tx, name) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if name == "__code__": + return VariableTracker.build(tx, hasattr(self, "code")) + if name == "__defaults__": + return VariableTracker.build(tx, hasattr(self, "defaults")) + vt = ConstantVariable.create(name) + if vt in self.get_dict_vt(tx): + return ConstantVariable.create(True) + return super().call_obj_hasattr(tx, name) + + def has_self(self) -> bool: + return False + + def get_globals(self) -> dict[str, Any]: + return self.f_globals + + def bind_args( + self, + parent: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> dict[str, VariableTracker]: + code = self.get_code() + func = types.FunctionType( + code, + self.f_globals, + self.fn_name.as_python_constant(), + tuple(self.defaults.items) if self.defaults else None, # type: ignore[attr-defined] + tuple(make_cell(None) for _ in range(len(self.get_code().co_freevars))), + ) + if self.kwdefaults: + func.__kwdefaults__ = self.kwdefaults.keys_as_python_constant() # type: ignore[missing-attribute] + try: + bound = inspect.signature(func).bind(*args, **kwargs) + bound.apply_defaults() + except TypeError as e: + raise BindArgsTypeError(e.args[0]) from e + result = dict(bound.arguments.items()) + wrap_args_kwargs(parent.output.root_tx, result) # type: ignore[arg-type] + init_cellvars(parent, result, code) + + for idx, name in enumerate(code.co_freevars): + if name in result: + raise AssertionError(f"free variable {name!r} already in result") + cell = self.closure.items[idx] # type: ignore[attr-defined, union-attr] + result[name] = cell + + return result + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from(__name__, "_create_nested_fn") + ) + codegen(self.code) + codegen.extend_output([codegen.create_load_const_unchecked(self.f_globals)]) + codegen(ConstantVariable.create(self.code.value.co_name)) # type: ignore[attr-defined] + + if self.defaults: + codegen(self.defaults) + else: + codegen.extend_output([codegen.create_load_const(None)]) + + if self.closure: + codegen(self.closure) + else: + codegen.extend_output([codegen.create_load_const(None)]) + + if self.kwdefaults: + codegen(self.kwdefaults) + else: + codegen.extend_output([codegen.create_load_const(None)]) + + if self.annotations is not None: + try: + annotations = self.annotations.as_python_constant() + codegen.extend_output( + [codegen.create_load_const_unchecked(annotations)] + ) + except NotImplementedError: + codegen(self.annotations) + else: + codegen.extend_output([codegen.create_load_const(None)]) + + codegen.extend_output(create_call_function(7, False)) + + if self.wrapped_fn: + codegen.add_push_null( + lambda: codegen.load_import_from("functools", "wraps") + ) + codegen(self.wrapped_fn) + codegen.extend_output(create_call_function(1, False)) + codegen.extend_output(create_rot_n(2)) + codegen.extend_output(create_call_function(1, True)) + + # codegen attributes + tx = codegen.tx + if tx.output.side_effects.has_pending_mutation(self): + for name, value in tx.output.side_effects.store_attr_mutations[ + self + ].items(): + codegen.dup_top() + codegen(value) + codegen.extend_output(create_rot_n(2)) + codegen.store_attr(name) + + +class WrappedNestedUserFunctionVariable(NestedUserFunctionVariable): + def __init__( + self, + wrapped: NestedUserFunctionVariable, + context: "ContextWrappingVariable", + **kwargs: Any, + ) -> None: + kwargs.pop("fn_name", None) + kwargs.pop("code", None) + kwargs.pop("f_globals", None) + kwargs.pop("defaults", None) + kwargs.pop("kwdefaults", None) + kwargs.pop("annotations", None) + kwargs.pop("closure", None) + kwargs.pop("wrapped_fn", None) + super().__init__( + wrapped.fn_name, + wrapped.code, + wrapped.f_globals, + wrapped.defaults, + wrapped.kwdefaults, + wrapped.closure, + wrapped.wrapped_fn, + ) + self.annotations = wrapped.annotations + self.wrapped = wrapped + self.context = context + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if config.nested_graph_breaks: + wrapper_fn = UserFunctionVariable(polyfills._fn_with_ctx) + return wrapper_fn.call_function( + tx, [self.context, self.wrapped] + list(args), kwargs + ) + self.context.enter(tx) + result = super().call_function(tx, args, kwargs) + self.context.exit(tx) + return result + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(self.context)) + codegen(self.wrapped) + codegen.extend_output(create_call_function(1, False)) + + +RE_CONSTANT_FOLD_FNS = { + re.search, + re.match, + re.fullmatch, + re.compile, + re.sub, + re.subn, + re.split, + re.findall, + re.escape, +} + + +class SkipFunctionVariable(VariableTracker): + _nonvar_fields = { + "value", + "reason", + *VariableTracker._nonvar_fields, + } + + def __init__(self, value: Any, reason: str | None = None, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + self.reason = reason + + def get_value_for_setattr(self) -> object | None: + mod = getattr(self.value, "__module__", None) or "" + if mod == "torch" or mod.startswith(("torch.", "torch_")): + return None + return self.value + + def tp_richcompare_impl(self, tx, other, op): + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def as_python_constant(self) -> Any: + return self.value + + def get_real_python_backed_value(self) -> Any: + return self.value + + @classmethod + def create_with_source(cls, value: Any, source: Source) -> "SkipFunctionVariable": + # Use closure match guard (i.e. guard on __code__ object instead of + # function id) to avoid guarding on nested functions. + if inspect.getattr_static(value, "_torchdynamo_disable", False): + # For torch._dynamo.disable function, ensure that the original + # function is guarded. Otherwise, the else branch will guard on the + # _dynamo.disable.__code__ + guard_on_source = source + guard_on_value = value + + while inspect.getattr_static( + guard_on_value, "_torchdynamo_orig_callable", False + ): + guard_on_value = guard_on_value._torchdynamo_orig_callable + guard_on_source = AttrSource( + guard_on_source, "_torchdynamo_orig_callable" + ) + + guard_on_source.make_guard(GuardBuilder.CLOSURE_MATCH) + elif inspect.isbuiltin(value): + # Bound builtin methods (e.g. obj.__reduce_ex__) are created fresh + # on every attribute access, so their id() is unstable. Skip the + # id-based BUILTIN_MATCH guard for them — the type guard on + # the owner object is sufficient. + if not hasattr(value, "__self__") or isinstance( + value.__self__, types.ModuleType + ): + install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH)) + elif not is_wrapper_or_member_descriptor(value): + # These descriptors are not guaranteed to return the same object on + # attribute lookup. They are unlikely to be changed, so we can skip + # guarding them. + install_guard(source.make_guard(GuardBuilder.CLOSURE_MATCH)) + return cls(value, source=source) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # importlib functions are frozen builtins that Dynamo cannot trace + # into. They are deterministic for a given package name, so + # constant-fold them when all args are constants. + if self.value in (importlib.util.find_spec, importlib.metadata.version) and all( + a.is_python_constant() for a in args + ): + return VariableTracker.build( + tx, self.value(*(a.as_python_constant() for a in args)) + ) + + if ( + self.value in RE_CONSTANT_FOLD_FNS + and all(a.is_python_constant() for a in args) + and all(v.is_python_constant() for v in kwargs.values()) + ): + result = self.value( + *(a.as_python_constant() for a in args), + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + return VariableTracker.build(tx, result) + + def unimplemented_direct_disable_call(api_name: str) -> Never: + # The registry linter keys off this helper name and records concrete + # entries from the call sites below. Use an alias here so the + # parameterized helper body is not recorded as a generic + # `{api_name}` entry. + _unimplemented = unimplemented + _unimplemented( + gb_type=f"Call to `{api_name}()`", + context=f"Called `{api_name}()` with args `{args}`, kwargs `{kwargs}`", + explanation=f"`{api_name}()` was called inside a compiled region. " + "This API disables compilation when used as a decorator or wrapper " + "outside the compiled region.", + hints=[ + f"Move the `{api_name}()` call outside the compiled function and apply it to the function that should run eagerly.", + "Use `torch._dynamo.graph_break()` to intentionally insert a graph break at this point.", + ], + ) + + if self.value is torch._dynamo.disable: + unimplemented_direct_disable_call("torch._dynamo.disable") + elif self.value is torch.compiler.disable: + unimplemented_direct_disable_call("torch.compiler.disable") + elif inspect.getattr_static(self.value, "_torchdynamo_disable", False): + msg = inspect.getattr_static(self.value, "_torchdynamo_disable_msg", None) + unimplemented( + gb_type="Skip calling `torch.compiler.disable()`d function", + context=str(self.value), + explanation=f"Skip calling function `{self.value}` since it was wrapped " + f"with `torch.compiler.disable` (reason: {msg})", + hints=[ + "Remove the `torch.compiler.disable` call", + ], + ) + elif self.value is torch._dynamo.graph_break: + graph_break_msg = kwargs.get("msg") + if graph_break_msg: + graph_break_msg = graph_break_msg.as_python_constant() + unimplemented( + gb_type="Call to `torch._dynamo.graph_break()`", + context=f"Called `torch._dynamo.graph_break()` with args `{args}`, kwargs `{kwargs}`", + explanation=f"User-inserted graph break. Message: {graph_break_msg}", + hints=[ + "Remove the `torch._dynamo.graph_break()` call.", + ], + ) + elif self.value is torch._dynamo.skip_frame: + skip_frame_msg = kwargs.get("msg") + if skip_frame_msg: + skip_frame_msg = skip_frame_msg.as_python_constant() + else: + skip_frame_msg = "" + unimplemented( + gb_type="Call to `torch._dynamo.skip_frame()`", + context=f"Called `torch._dynamo.skip_frame()` with args `{args}`, kwargs `{kwargs}`. " + f"Skipping frame {format_frame_info(tx.f_code)}.", + explanation=f"User-inserted skip frame. Message: {skip_frame_msg}", + hints=[ + "Remove the `torch._dynamo.skip_frame()` call.", + ], + skip_frame=True, + ) + elif self.value is torch._dynamo.step_unsupported: + try: + unimplemented( + gb_type="Call to `torch._dynamo.step_unsupported()`", + context="", + explanation="User-inserted step_unsupported.", + hints=[ + "Remove the `torch._dynamo.step_unsupported()` call.", + ], + ) + except Unsupported as e: + raise StepUnsupported(e.msg) from None + elif self.value is types.FunctionType.__get__: + # function.__get__(func, obj[, cls]) produces a bound method. + # This is called by inspect._descriptor_get when resolving + # descriptors during inspect.signature(). + # Note that function.__get__ does not use the 3rd argument. The + # reason it still has the 3rd argument is because descriptors follow + # a function signature that takes 3 arguments, and other descriptors + # (not function.__get__) can use the 3rd argument. + if len(args) in (2, 3) and not kwargs: + func_var = args[0] + obj_var = args[1] + if isinstance(func_var, UserFunctionVariable): + return UserMethodVariable( + func_var.fn, obj_var, source_fn=func_var.source + ) + unimplemented( + gb_type="unsupported function.__get__ call", + context=f"call_function {self}, args: {args}, kwargs: {kwargs}", + explanation="Dynamo only supports function.__get__(func, obj[, cls]) " + "where func is a user-defined function.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + else: + if config.dont_skip_tracing: + from .builder import SourcelessBuilder + + # re-build the function, attempting to not skip + rebuilt_fn = SourcelessBuilder.create(tx, self.value) + # if we still get SkipFunctionVariable, then we *really* should skip this function + if not isinstance(rebuilt_fn, SkipFunctionVariable): + return rebuilt_fn.call_function(tx, args, kwargs) + qualname = getattr(self.value, "__qualname__", "") + module_or = getattr(self.value, "__module__", None) + module_name = "" if module_or is None else str(module_or) + try: + path = inspect.getfile(self.value) + explanation = ( + f"Dynamo developers have intentionally marked that the function `{qualname}` " + f"in file `{path}` should not be traced." + ) + hints = [ + f"Avoid calling the function `{qualname}`.", + ] + # TODO improve trace_rules reasoning to provide better hints. + # How do we tell that a function/file should NOT be removed from skip files? + # Do a very basic check for now. + if "_dynamo" not in path: + hints += [ + f"Apply `@torch._dynamo.dont_skip_tracing` to the function `{qualname}` " + "to force tracing into the function. " + "More graph breaks may occur as a result of attempting to trace into the function.", + "Please file an issue to PyTorch.", + ] + except TypeError: + known_python_builtin_modules = {"_abc", "_warnings"} + if module_or in known_python_builtin_modules: + explanation = ( + f"Dynamo does not know how to trace the Python builtin " + f"`{module_name}.{qualname}`." + ) + hints = [ + "If you are attempting to call a logging function (e.g. `_warnings.warn`), " + "you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.", + "Please file an issue on GitHub " + "so the PyTorch team can add support for it. ", + ] + elif module_or is not None and module_or.startswith("optree"): + explanation = f"Dynamo cannot trace optree C/C++ function {module_name}.{qualname}." + hints = [ + " Consider using torch.utils._pytree - " + "https://github.com/pytorch/pytorch/blob/main/torch/utils/_pytree.py" + ] + # also warn on it because most users won't see the graph break message + torch._dynamo.utils.warn_once(explanation + "\n" + "\n".join(hints)) + else: + explanation = ( + f"Dynamo does not know how to trace the builtin `{module_name}.{qualname}.` " + f"This function is either a Python builtin (e.g. _warnings.warn) " + f"or a third-party C/C++ Python extension (perhaps created with pybind)." + ) + hints = [ + "If it is a Python builtin, please file an issue on GitHub " + "so the PyTorch team can add support for it and see the next case for a workaround.", + "If it is a third-party C/C++ Python extension, please " + "either wrap it into a PyTorch-understood custom operator " + "(see https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html " + "for more details) or, if it is traceable, use " + "`torch.compiler.allow_in_graph`.", + ] + # also warn on it because most users won't see the graph break message + torch._dynamo.utils.warn_once(explanation + "\n" + "\n".join(hints)) + if qualname == "allow_in_graph": + explanation = ( + "torch.compiler.allow_in_graph (or torch._dynamo.allow_in_graph) " + "was called inside a compiled region. Dynamically annotating functions " + "inside a compiled region is not supported." + ) + hints = [ + "Apply @torch.compiler.allow_in_graph as a decorator before compilation, " + "not inside the compiled function.", + ] + if self.reason: + reason = self.reason + else: + from ..trace_rules import get_skip_reason + + reason = get_skip_reason(self.value) + unimplemented( + gb_type="Attempted to call function marked as skipped", + context=f"module: {module_name}, qualname: {qualname}, skip reason: {reason}", + explanation=explanation, + hints=hints, + ) + + def reconstruct_pycode(self, codegen): + if self.source: + return self.source.reconstruct_pycode(codegen) + raise NotImplementedError( + "Python codegen not implemented for sourceless SkipFunctionVariable" + ) + + +class WrappedSkipFunctionVariable(SkipFunctionVariable): + def __init__( + self, + wrapped: SkipFunctionVariable, + context: "ContextWrappingVariable", + **kwargs: Any, + ) -> None: + kwargs.pop("value", None) + kwargs.pop("reason", None) + super().__init__(wrapped.value, reason=wrapped.reason, **kwargs) + self.wrapped = wrapped + self.context = context + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if config.nested_graph_breaks: + wrapper_fn = UserFunctionVariable(polyfills._fn_with_ctx) + return wrapper_fn.call_function( + tx, [self.context, self.wrapped] + list(args), kwargs + ) + self.context.enter(tx) + result = super().call_function(tx, args, kwargs) + self.context.exit(tx) + return result + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(self.context)) + codegen(self.wrapped) + codegen.extend_output(create_call_function(1, False)) + + +class WrapperUserFunctionVariable(BaseUserFunctionVariable): + """ + Used to represent a wrapper object that contains the actual callable as an + attribute. For example, torch.jit.script/trace have the original function at + their _torchdynamo_inline attribute. Similarly, functions with + __script_if_tracing_wrapper have the original attr at "__original_fn". + """ + + def python_type(self) -> type: + return types.FunctionType + + def __init__(self, wrapper_obj: Any, attr_to_trace: str, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.wrapper_obj = wrapper_obj + self.attr_to_trace = attr_to_trace + + def get_module(self) -> str: + return self.wrapper_obj.__module__ + + def get_name(self) -> str: + return self.wrapper_obj.__name__ + + def get_code(self) -> types.CodeType: + return self.get_function().__code__ + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == self.attr_to_trace: + val = getattr(self.wrapper_obj, self.attr_to_trace) + source = self.source and AttrSource(self.source, name) + return VariableTracker.build(tx, val, source) + return super().tp_getattro_impl(tx, name) + + def get_function(self): + return getattr(self.wrapper_obj, self.attr_to_trace) + + def lookup_instance_dict( + self, tx: "InstructionTranslatorBase", name: str + ) -> "VariableTracker | None": + # self.source denotes the wrapper, not the inline target reached via + # attr_to_trace. Resolve instance-dict attrs (e.g. functools.wraps' + # __wrapped__) against the wrapper so the built value matches the source; + # the base impl reflects on get_function() (the inline target), which + # would pair the inline target's value with the wrapper's source and + # yield a self-inconsistent guard (issue: swap/getfullargspec repro). + wrapper_dict = getattr(self.wrapper_obj, "__dict__", None) + if not wrapper_dict or name not in wrapper_dict: + return None + source = self.get_source() + source = AttrSource(source, name) if source is not None else None + if source is not None: + return variables.LazyVariableTracker.create( + wrapper_dict[name], source, tx=tx + ) + return VariableTracker.build(tx, wrapper_dict[name]) + + def self_args(self) -> list[VariableTracker]: + return [] + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if hasattr(self.wrapper_obj, "cache_info"): + target_fn = getattr(self.wrapper_obj, self.attr_to_trace, None) + module_name = getattr(target_fn, "__module__", "") or "" + is_allowed_lru_cache_wrapper = ( + is_lru_cache_wrapper_trace_without_warning_allowed(self.wrapper_obj) + ) + + if ( + module_name.split(".", maxsplit=1)[0] != "torch" + and not is_allowed_lru_cache_wrapper + ): + frame_summary = tx.frame_summary() + filename = os.path.basename(frame_summary.filename) + lineno = frame_summary.lineno + msg = ( + "Dynamo detected a call to a `functools.lru_cache`-wrapped " + f"function at '{filename}:{lineno}'. Dynamo ignores the " + "cache wrapper and directly traces the wrapped function. " + "Silent incorrectness is only a *potential* risk, not " + "something we have observed. " + "Enable TORCH_LOGS=+dynamo for a DEBUG stack trace.\n\n" + "This call originates from:\n" + f"{''.join(traceback.format_list([frame_summary]))}" + ) + + torch._dynamo.utils.warn_once(msg) + + dynamo_logger = torch._dynamo.utils.logging.getLogger("torch._dynamo") + if dynamo_logger.isEnabledFor(logging.DEBUG): + user_stack = torch._guards.TracingContext.extract_stack() + user_stack = get_stack_above_dynamo() + user_stack + frame_loc = (user_stack[-1].filename, user_stack[-1].lineno) + user_stack_formatted = "".join(traceback.format_list(user_stack)) + user_stack_trace = f"call to a lru_cache wrapped function at: {frame_loc[0]}:{frame_loc[1]}\n" + user_stack_trace += str(user_stack_formatted) + dynamo_logger.debug(user_stack_trace) + + all_args = self.self_args() + list(args) + # Inner torch.compile wrapper: disable nested graph breaks to + # preserve the inner compile's semantics (e.g. fullgraph=True). + # Graph breaks inside the inner function should raise Unsupported + # so they're handled by the outer frame, not as nested breaks. + # Skip this for recursive calls to the same compiled function + # (the wrapper's original callable matches the root frame's code). + is_inner_torch_compile = ( + self.attr_to_trace == "_torchdynamo_inline" + and inspect.getattr_static(self.wrapper_obj, "_is_torch_compile", False) + and getattr( + inspect.getattr_static( + self.wrapper_obj, "_torchdynamo_orig_callable", None + ), + "__code__", + None, + ) + is not tx.output.root_tx.f_code + ) + polyfill = ( + polyfills.getattr_and_trace_no_nested_graph_breaks + if is_inner_torch_compile + else polyfills.getattr_and_trace + ) + return VariableTracker.build( + tx, + polyfill, # type: ignore[arg-type] + ).call_function( + tx, + [self, VariableTracker.build(tx, self.attr_to_trace), *all_args], + kwargs, + ) + + def get_real_python_backed_value(self) -> object: + # This VT stands for the wrapper, which is also what self.source + # denotes. The inline target is reached via attr_to_trace and is a + # different object. + return self.wrapper_obj + + +class WrapperUserMethodVariable(WrapperUserFunctionVariable): + """ + Similar to WrapperUserFunctionVariable, but for methods. The only delta is + saving the vt for `self` object of the method which is then used by + WrapperUserFunctionVariable in `call_function` method. + """ + + def python_type(self) -> type: + return types.MethodType + + def __init__( + self, + wrapper_obj: Any, + attr_to_trace: str, + self_obj: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(wrapper_obj, attr_to_trace, **kwargs) + self.obj = self_obj + + def self_args(self) -> list[VariableTracker]: + return [self.obj] + + +def _traceable_collective_remaps() -> dict[Any, Any]: + # We can't rely on importing from distributed, since it's not always built + if torch.distributed.is_available(): + from torch.distributed._functional_collectives import ( + traceable_collective_remaps, + ) + + return traceable_collective_remaps + return {} + + +def _traceable_collectives_source( + tx: "InstructionTranslatorBase", fn: Callable[..., Any] +) -> AttrSource: + if not torch.distributed.is_available(): + raise AssertionError("Illegal invocation.") + if fn not in _traceable_collective_remaps().values(): + raise AssertionError(f"{fn} is not a traceable collective remap") + + inner_name = fn.__name__ + path_source = tx.import_source("torch.distributed._functional_collectives") + return AttrSource(path_source, inner_name) + + +class CollectiveFunctionRewriteVariable(UserFunctionVariable): + """ + Some of the torch.distributed.* collective APIs are possible to rewrite to 'traceable' collectives. + + This class provides both a way to check if a function is remappable, and perform the remapping. + + In the case that a function is 'remappable' but only for some combinations of call-time arguments, + we check the args at `call_function` time and fall back to graph-breaking if needed. This is no worse + than status-quo as we currently graph-break on all distributed.* collectives. + """ + + def __init__( + self, + fn: Callable[..., Any], + *, + replacement_var: UserFunctionVariable, + **kwargs: Any, + ) -> None: + super().__init__(fn, **kwargs) # type: ignore[arg-type] + if not isinstance(replacement_var, UserFunctionVariable): + raise AssertionError( + f"replacement_var must be a UserFunctionVariable, got {type(replacement_var)}" + ) + self.replacement_var = replacement_var + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + old_fn: Callable[..., Any], + source: Source, + **options: Any, + ) -> "CollectiveFunctionRewriteVariable": + new_fn, new_source = CollectiveFunctionRewriteVariable.rewrite(tx, old_fn) + return CollectiveFunctionRewriteVariable( + old_fn, + replacement_var=UserFunctionVariable(new_fn, source=new_source, **options), + source=source, + **options, + ) + + @staticmethod + def can_rewrite(variable: Any) -> bool: + return ( + inspect.isfunction(variable) and variable in _traceable_collective_remaps() + ) + + @staticmethod + def rewrite( + tx: "InstructionTranslatorBase", fn: Callable[..., Any] + ) -> tuple[Any, AttrSource]: + new_fn = _traceable_collective_remaps()[fn] + return new_fn, _traceable_collectives_source(tx, new_fn) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # call_function must check any unsupported arguments and graph-break. + # It's safe to assume args/kwargs from orig_fn map 1:1 to args/kwargs of remapped_fn, + # since that's the contract for putting a mapping in `traceable_collective_remaps` + import torch.distributed as dist + from torch.distributed._functional_collectives import REDUCE_OP_TO_STR + + # Merge args into kwargs so positional and keyword args + # can be processed the same way. + signature = inspect.signature(self.fn) + kwargs = dict(signature.bind(*args, **kwargs).arguments) + args = [] + + if "async_op" in kwargs and kwargs["async_op"].as_python_constant(): + unimplemented( + gb_type="async_op=True for distributed collectives", + context=f"{self.fn}, {args=}, {kwargs=}", + explanation=f"`torch.compile` doesn't support `async_op=True for {self.fn}", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + if self.fn == dist.batch_isend_irecv: + if not config.enable_p2p_compilation: + unimplemented( + gb_type="P2P compilation disabled for batch_isend_irecv", + context=f"{self.fn}", + explanation="P2P compilation is disabled.", + hints=[ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable.", + ], + ) + + p2p_ops = kwargs["p2p_op_list"] + if not isinstance(p2p_ops, variables.ListVariable): + raise torch._dynamo.exc.InternalTorchDynamoError( + "`P2POp` used incorrectly" + ) + + ops: list[VariableTracker] = list() + peers = list() + tags = list() + tensors = list() + group_var: VariableTracker | None = None + + for item in p2p_ops.items: + if item.python_type() is not dist.P2POp: + raise torch._dynamo.exc.InternalTorchDynamoError( + "`P2POp` used incorrectly" + ) + + op_var = item.tp_getattro_impl(tx, "op") + if op_var.is_python_constant(): + op = op_var.as_python_constant() + if op not in (dist.isend, dist.irecv): + raise torch._dynamo.exc.InternalTorchDynamoError( + f"unexpected P2POp op {op}" + ) + op_var = variables.ConstantVariable.create(op.__name__) + elif hasattr(op_var, "get_name"): + op_var = variables.ConstantVariable.create(op_var.get_name()) + else: + raise torch._dynamo.exc.InternalTorchDynamoError( + f"unexpected P2POp op variable {op_var}" + ) + + ops.append(op_var) + tensors.append(item.tp_getattro_impl(tx, "tensor")) + # batch_p2p_ops expects a group-local rank, which is what + # P2POp.group_peer provides. + peers.append(item.tp_getattro_impl(tx, "group_peer")) + tags.append(item.tp_getattro_impl(tx, "tag")) + if group_var is None: + group_var = item.tp_getattro_impl(tx, "group") + + if group_var is None: + raise AssertionError("group_var must be set from P2POp items") + new_args: list[VariableTracker] = [] + new_kwargs: dict[str, VariableTracker] = { + "op_list": variables.ListVariable(ops), + "peer_list": variables.ListVariable(peers), + "tag_list": variables.ListVariable(tags), + "tensors": variables.ListVariable(tensors), + "group_name": group_var, + } + return self.replacement_var.call_function(tx, new_args, new_kwargs) + + if self.fn in (dist.isend, dist.irecv): + if not config.enable_p2p_compilation: + unimplemented( + gb_type="P2P compilation disabled for isend/irecv", + context=f"{self.fn}", + explanation="P2P compilation is disabled.", + hints=[ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable.", + ], + ) + + return self.replacement_var.call_function(tx, args, kwargs) + + if self.fn in ( + dist.all_reduce, + dist.reduce_scatter, + dist.reduce_scatter_single, + # pyrefly: ignore [deprecated] + dist.reduce_scatter_tensor, + # pyrefly: ignore [deprecated] + dist._reduce_scatter_base, + ): + reduce_op_var = kwargs.get("op") + reduce_op = ( + reduce_op_var.value # type: ignore[attr-defined] + if reduce_op_var is not None + else signature.parameters["op"].default + ) + if reduce_op not in REDUCE_OP_TO_STR: + raise ValueError(f"Unsupported all_reduce op: {reduce_op}") + kwargs["op"] = VariableTracker.build(tx, REDUCE_OP_TO_STR[reduce_op]) + return self.replacement_var.call_function(tx, args, kwargs) + + +class CollectionsNamedTupleFunction(UserFunctionVariable): + def as_python_constant(self) -> Any: + return self.fn + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + constant_args = check_constant_args(args, kwargs) + if constant_args: + try: + value = self.fn( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + except TypeError as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + return variables.UserDefinedClassVariable( + value, + mutation_type=ValueMutationNew(), + ) + unimplemented( + gb_type="namedtuple construction", + context=f"{args=}, {kwargs=}", + explanation="`torch.compile` only support certain input types for namedtuple", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + +class FunctoolsPartialVariable(VariableTracker): + # partial_type_spec: https://github.com/python/cpython/blob/v3.13.0/Modules/_functoolsmodule.c#L538 + _cpython_type = functools.partial + + _nonvar_fields = { + "original_cache_hash", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + func: VariableTracker, + args: list[VariableTracker], + keywords: dict[str, VariableTracker], + original_cache_hash: Any = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.func = func + if not isinstance(args, list): + raise AssertionError(f"args must be a list, got {type(args)}") + self.args = args + if not isinstance(keywords, dict): + raise AssertionError(f"keywords must be a dict, got {type(keywords)}") + self.keywords = keywords + # Store cache_hash from the original partial for SAC context_fn caching + self.original_cache_hash = original_cache_hash + + def tp_richcompare_impl(self, tx, other, op): + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def python_type(self) -> type: + return functools.partial + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("functools", "partial")) + codegen(self.func) + if self.args: + codegen.foreach(self.args) + if not self.keywords: + codegen.extend_output(create_call_function(len(self.args) + 1, False)) + return + + codegen.foreach(self.keywords.values()) + keys = tuple(self.keywords.keys()) + codegen.extend_output( + codegen.create_call_function_kw(len(keys) + len(self.args) + 1, keys, False) + ) + + def get_function(self) -> Any: + return self.as_python_constant() + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + merged_args = self.args + args + merged_kwargs = {**self.keywords, **kwargs} + return self.func.call_function(tx, merged_args, merged_kwargs) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + # functools.partial uses slots, so attributes are constant + return VariableTracker.build(tx, hasattr(functools.partial(identity), name)) + + # func / args / keywords are read-only members on partial objects. + # https://github.com/python/cpython/blob/v3.13.0/Modules/_functoolsmodule.c#L295-L299 + def _get_func(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.func + + def _get_args(self, tx: "InstructionTranslatorBase") -> VariableTracker: + source = self.source and AttrSource(self.source, "args") + return variables.TupleVariable(self.args, source=source) + + def _get_keywords(self, tx: "InstructionTranslatorBase") -> VariableTracker: + source = self.source and AttrSource(self.source, "keywords") + items = {VariableTracker.build(tx, k): v for k, v in self.keywords.items()} + return variables.ConstDictVariable(items, source=source) + + tp_members = { + "func": Member(_get_func, None), + "args": Member(_get_args, None), + "keywords": Member(_get_keywords, None), + } + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + try: + return super().tp_getattro_impl(tx, name) + except NotImplementedError: + raise_observed_exception(AttributeError, tx, args=[name]) + + def as_python_constant(self) -> Any: + return functools.partial( + self.func.as_python_constant(), + *[arg.as_python_constant() for arg in self.args], + **{k: v.as_python_constant() for k, v in self.keywords.items()}, + ) + + def guard_as_python_constant(self) -> Any: + """Similar to as_python_constant(), but add ID_MATCH guards to try to force things to become constants""" + result = functools.partial( + self.func.guard_as_python_constant(), + *[v.guard_as_python_constant() for v in self.args], + **{k: v.guard_as_python_constant() for k, v in self.keywords.items()}, + ) + # Preserve cache_hash for SAC context_fn caching + if self.original_cache_hash is not None: + result.cache_hash = self.original_cache_hash # type: ignore[missing-attribute] + return result + + +class PolyfilledFunctionVariable(VariableTracker): + _nonvar_fields = { + "fn", + "wrapped_fn", + "traceable_fn", + *VariableTracker._nonvar_fields, + } + + @classmethod + @functools.cache + def _get_polyfill_handlers(cls) -> dict[Callable[..., Any], types.FunctionType]: + return {} + + @classmethod + def create_with_source( + cls, value: Any, source: Source + ) -> "PolyfilledFunctionVariable": + install_guard(source.make_guard(GuardBuilder.CLOSURE_MATCH)) + + return cls(value, source=source) + + def get_value_for_setattr(self) -> object | None: + return self.fn + + def __init__(self, fn: _F, **kwargs: Any) -> None: + super().__init__(**kwargs) + # pyrefly: ignore[invalid-type-var] + self.fn: _F = fn + + handler = self._get_polyfill_handlers().get(fn, fn) + traceable_fn = None + if not callable(handler): + raise AssertionError(f"Polyfill handler {handler} is not callable for {fn}") + for candidate_attr in ( + "__torch_dynamo_polyfill__", # registered polyfill + "__python_implementation__", # self handler from third-party libraries + ): + candidate = getattr(handler, candidate_attr, None) + if candidate: + if not callable(candidate): + raise AssertionError( + f"Polyfill candidate {candidate} is not callable" + ) + traceable_fn = candidate + break + else: + raise RuntimeError( + f"Polyfill handler {handler} does not have a traceable function" + ) + + self.wrapped_fn = handler + # pyrefly: ignore[invalid-type-var] + self.traceable_fn: _F = traceable_fn + + @property + def polyfill_fn(self) -> Callable[..., Any]: + return self.traceable_fn + + def can_constant_fold_through(self) -> bool: + return getattr( + self.wrapped_fn, "__torch_dynamo_can_constant_fold_through__", False + ) + + def get_function(self) -> Any: + return self.as_python_constant() + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.can_constant_fold_through() and check_unspec_or_constant_args( + args, kwargs + ): + result = ( + self.fn( # use the original function which is faster than the polyfill + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + ) + return VariableTracker.build(tx, result) + + # Special case for sum on tuple/list of ints + if ( + self.fn is builtins.sum + and len(args) == 1 + and not kwargs + and isinstance(args[0], (variables.ListVariable, variables.TupleVariable)) + and all( + (x.is_python_constant() and isinstance(x.as_python_constant(), int)) + or (isinstance(x, variables.SymNodeVariable) and x.python_type() is int) + for x in args[0].items + ) + ): + return variables.SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", + torch.sym_sum, + (tuple(a.as_proxy() for a in args[0].items),), + {}, + ), + sym_num=torch.sym_sum( + [ + ( + x.as_python_constant() + if x.is_python_constant() + else x.sym_num # type: ignore[attr-defined] + ) + for x in args[0].items + ] + ), + ) + + traceable_function_variable = VariableTracker.build(tx, self.traceable_fn) + return tx.inline_user_function_return( + traceable_function_variable, + list(args), + dict(kwargs), + ) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__call__": + return self.call_function(tx, args, kwargs) + + method = getattr(self.fn, name, None) + if not (method or is_function(method)): + raise_type_error(tx, f"Cannot find callable {name} in {self.fn}") + options = {} + if self.source: + options["source"] = AttrSource(self.source, name) + polyfilled_method_variable = PolyfilledFunctionVariable(method, **options) + return polyfilled_method_variable.call_function(tx, args, kwargs) + + def as_python_constant(self) -> Any: + return self.fn + + +class SysFunctionVariable(VariableTracker): + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def python_type(self) -> type: + return types.BuiltinFunctionType + + def exc_info(self, tx: "InstructionTranslatorBase") -> "variables.TupleVariable": + if len(tx.exn_vt_stack): + exn = tx.exn_vt_stack[-1] + typ = exn.exc_type # type: ignore[union-attr] + tb = exn.tp_getattro_impl(tx, "__traceback__") + items = [VariableTracker.build(tx, typ), exn, tb] + else: + items = [ + ConstantVariable.create(None), + ConstantVariable.create(None), + ConstantVariable.create(None), + ] + return variables.TupleVariable(items) # type: ignore[arg-type] + + def exception(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.exc_info(tx).items[1] + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.value is sys.exc_info: + return self.exc_info(tx) + + if self.value is not sys.exception: + raise AssertionError(f"expected sys.exception, got {self.value}") + return self.exception(tx) + + +from torch._higher_order_ops.triton_kernel_wrap import ( + create_tma_experimental_metadata, + create_tma_stable_metadata, + TMADescriptorMetadata, + TritonHOPifier, +) + + +class DynamoTritonHOPifier(TritonHOPifier): + def raise_unsupported(self, msg: str) -> Never: + unimplemented( + gb_type="triton kernel unsupported feature", + context="", + explanation=f"Encountered triton kernel unsupported feature: {msg}", + hints=[], + ) + + def is_callable(self, maybe_callable: VariableTracker) -> bool: + return isinstance( + maybe_callable, (NestedUserFunctionVariable, UserFunctionVariable) + ) + + def get_value(self, val: VariableTracker) -> Any: + return val.value # type: ignore[attr-defined] + + def check_grid(self, grid: "BaseListVariable") -> tuple[torch.fx.proxy.Proxy, ...]: + from .lists import BaseListVariable + + if isinstance(grid, BaseListVariable): + return grid.as_proxy() + else: + unimplemented( + gb_type="unsupported grid type for triton hop check_grid", + context=f"grid type = {type(grid)}", + explanation="`torch.compile` only supports list-like grid for check_grid", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + def call_grid( + self, grid: Any, meta: dict[str, Any], tx: "InstructionTranslatorBase" + ) -> Any: + meta_var = {VariableTracker.build(tx, k): v for k, v in meta.items()} + grid = grid.call_function(tx, [meta_var], {}) + return grid + + # We use this function to wrap call_prune_configs + def call_user_defined_fn( + self, + user_fn: Callable[..., Any], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + tx: Optional["InstructionTranslatorBase"], + variable: Any, + ) -> VariableTracker: + from .builder import SourcelessBuilder + + wrapped_user_function = SourcelessBuilder.create(tx, user_fn) # type: ignore[arg-type] + result = wrapped_user_function.call_function(tx, args, kwargs) + return result + + def wrap_user_defined_obj( + self, + user_obj: Any, + tx: Optional["InstructionTranslatorBase"], + variable: Any, + name: str, + ) -> VariableTracker: + from .builder import VariableBuilder + + if tx is None: + raise AssertionError("tx must not be None") + # Route through VariableBuilder.__call__ so already-tracked mutable + # objects (for example autotuner config lists) are reused instead of + # being registered for mutation twice in the same trace. + wrapped_user_obj = VariableBuilder( + tx, AttrSource(variable.kernel_source, f"{name}") + )(user_obj) + return wrapped_user_obj + + def maybe_unpack_configs( + self, configs: Any, tx: Optional["InstructionTranslatorBase"] + ) -> list[Any]: + # unpack the list of configs + if tx is None: + raise AssertionError("tx must not be None") + configs = unpack_iterable(tx, configs) + + # guard_as_python_constant inserts guards for Dynamo to check if the configs object changed. + configs = [config.guard_as_python_constant() for config in configs] + + return configs + + def maybe_unpack_heuristic_result(self, result: VariableTracker) -> Any: + if not result.is_python_constant(): + self.raise_unsupported( + "@triton.heuristics must return constant values because configs can only contain constant values." + ) + + return result.guard_as_python_constant() + + # We need to override call_getitem here so that we can add the source in the case + # where we call the triton kernel with a grid + def call_getitem( # type: ignore[override] + self, + variable: "TritonKernelVariable", + args: Sequence[Any], + ) -> "TritonKernelVariable": + # __getitem__ should only be called if we don't already have a grid + # Only grid needs to be passed + if variable.grid is not None or len(args) != 1: + self.raise_unsupported( + "Triton kernels should be called with only a single grid" + ) + return type(variable)( + kernel=variable.kernel, + kernel_idx=variable.kernel_idx, + grid=args[0], + kernel_source=variable.kernel_source, + ) + + def call_HOP( + self, + variable: "TritonKernelVariable", + grids: Any, + combined_args: dict[str, Any], + launch_kwargs: tuple[str, ...], + kernel_arg_names: set[str], + tx: "InstructionTranslatorBase", + ) -> ConstantVariable | None: + from .dicts import ConstDictVariable + + # as we can only pass tensors as non-const args in fx graph, + # here we replace TMA descriptors + # (TMADescriptorExperimentalVariable and TMADescriptorStableVariable + # instances) with the underlying tensors, while moving the + # TMA descriptor-related metadata to a separate argument, + # so that we can reconstruct the TMA descriptors downstream + tma_descriptor_metadata: TMADescriptorMetadata = {} + for k in list(combined_args.keys()): + v = combined_args[k] + if isinstance( + v, (TMADescriptorExperimentalVariable, TMADescriptorStableVariable) + ): + tma_descriptor_metadata[k] = v.to_metadata() + combined_args[k] = v.get_tensor() + + combined_args_vt = { + VariableTracker.build(tx, k): v for k, v in combined_args.items() + } + + from torch._higher_order_ops.triton_kernel_wrap import ( + kernel_side_table, + triton_kernel_wrapper_mutation, + ) + + # Combine args and kwargs and pass as a dict so that if user defined triton + # kernel uses variables as 'grid' or 'kernel', it does not conflict with + # parameters of the wrapper function + constant_args = { + k: v.as_python_constant() + for k, v in combined_args.items() + if isinstance(v, VariableTracker) and v.is_python_constant() + } + non_constant_args = { + k: v + for k, v in combined_args_vt.items() + if not (isinstance(v, VariableTracker) and v.is_python_constant()) + } + # launch_kwargs records the names passed as kwargs at the Triton launch + # site. A non-kernel launch kwarg can only be a compiler option, so it + # must be a Python constant before entering the graph. Kernel launch + # kwargs may also be compiler options, but that target-specific check + # happens in Inductor after the triton backend is determined and + # backend.parse_options() is called. + non_const_options: list[str] = [] + for k in launch_kwargs: + if k in kernel_arg_names: + continue + v = combined_args[k] + if not (isinstance(v, VariableTracker) and v.is_python_constant()): + non_const_options.append(k) + if non_const_options: + self.raise_unsupported( + "Triton backend options must be Python constants: " + f"{sorted(non_const_options)!r}." + ) + + for v in non_constant_args.values(): + v = v.realize() + if not (v.is_tensor() or v.is_symnode_like()): + self.raise_unsupported( + f"Unexpected argument type for a Triton kernel: {repr(v)}." + ) + + constant_args_idx = kernel_side_table.add_constant_args(constant_args) + meta = ConstDictVariable(non_constant_args) + tx.output.create_proxy( + "call_function", + triton_kernel_wrapper_mutation, + (), + { + "kernel_idx": variable.kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grids, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": meta.as_proxy(), + "launch_kwargs": launch_kwargs, + }, + ) + + return VariableTracker.build( + tx, + None, + ) + + +dynamo_triton_hopifier_singleton = DynamoTritonHOPifier() + + +class TritonKernelVariable(VariableTracker): + grid: "TritonGridType" + kernel: "TritonKernelType" + kernel_idx: int | None + kernel_source: Source | None + + def __init__( + self, kernel: Any, kernel_idx: int | None, grid: Any, **kwargs: Any + ) -> None: + self.kernel_source = kwargs.pop("kernel_source", kwargs.get("source")) + super().__init__(**kwargs) + dynamo_triton_hopifier_singleton.init_variable(self, kernel, kernel_idx, grid) + + def python_type(self) -> type: + return type(self.kernel) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return dynamo_triton_hopifier_singleton.call_triton_kernel( # type: ignore[return-value] + self, args, kwargs, tx + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # Triton kernel[grid] — triton-specific, not a CPython slot. + return dynamo_triton_hopifier_singleton.call_getitem(self, [key]) + + def run( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return dynamo_triton_hopifier_singleton.call_run(self, args, kwargs, tx) # type: ignore[return-value] + + def specialize_symbolic(self, arg: Any) -> Any: + from .constant import ConstantVariable + from .tensor import SymNodeVariable + + # See [Note: Specialize tl.constexpr args in user-defined triton kernels] + if isinstance(arg, SymNodeVariable): + return ConstantVariable.create(arg.evaluate_expr()) + return arg + + tp_methods = {"run": Method(run)} + + +class TMADescriptorExperimentalVariable(VariableTracker): + def __init__( + self, + data_ptr: "variables.DataPtrVariable", + dims: list[VariableTracker], + block_dims: list[VariableTracker], + element_size: VariableTracker, + **kwargs: Any, + ) -> None: + if not isinstance(data_ptr, variables.DataPtrVariable): + raise AssertionError( + f"data_ptr must be a DataPtrVariable, got {type(data_ptr)}" + ) + super().__init__(**kwargs) + self.data_ptr = data_ptr + self.dims = dims + self.block_dims = block_dims + self.element_size = element_size + + def to_metadata(self) -> Any: + return create_tma_experimental_metadata( + [dim.as_proxy() for dim in self.dims], + [dim.as_proxy() for dim in self.block_dims], + self.element_size.as_proxy(), + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + "triton.tools.experimental_descriptor", + f"create_{len(self.dims)}d_tma_descriptor", + ) + ) + self.data_ptr.reconstruct(codegen) + args = [*self.dims, *self.block_dims, self.element_size] + codegen.foreach(args) + codegen.call_function(len(args) + 1, False) + + def get_tensor(self) -> VariableTracker: + return self.data_ptr.from_tensor + + +class TMADescriptorStableVariable(VariableTracker): + def __init__( + self, + tensor: "TensorVariable", + block_shape: "ListVariable", + **kwargs: Any, + ) -> None: + if not tensor.is_tensor(): + raise AssertionError("tensor argument must be a tensor") + super().__init__(**kwargs) + self.tensor = tensor + self.block_shape = block_shape + + def to_metadata(self) -> Any: + return create_tma_stable_metadata( + self.block_shape.as_proxy(), + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + "triton.tools.tensor_descriptor", + "TensorDescriptor", + ) + ) + codegen.load_method("from_tensor") + self.tensor.reconstruct(codegen) + codegen(self.block_shape) + codegen.call_method(2) + + def get_tensor(self) -> Any: + return self.tensor + + +class CreateTMADescriptorExperimentalVariable(VariableTracker): + def __init__( + self, + rank: int, + **kwargs: Any, + ) -> None: + if rank not in (1, 2): + raise AssertionError(f"rank must be 1 or 2, got {rank}") + super().__init__(**kwargs) + self.rank = rank + + def python_type(self) -> type: + return types.FunctionType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + ptr = kwargs["ptr"] if "ptr" in kwargs else args[0] + + if not isinstance(ptr, variables.DataPtrVariable): + unimplemented( + gb_type="invalid ptr argument for create_tma_descriptor", + context=f"args = {args}, kwargs = {kwargs}", + explanation=f"Expected `ptr` argument of `create_{self.rank}d_tma_descriptor`" + "to be from a `.data_ptr()` call, represented internally by `DataPtrVariable`", + hints=[ + "`torch.compile` may fail to internally represent result of `.data_ptr()` " + "with `DataPtrVariable` due to a graph break between the `.data_ptr()` call and " + f"`create_{self.rank}d_tma_descriptor`. Please ensure there were no graph breaks " + "between these two calls.", + ], + ) + + if self.rank == 1: + if len(args) + len(kwargs) != 4: + raise_type_error( + tx, + f"TMA metadata rank=1 requires exactly 4 arguments, got {len(args) + len(kwargs)}", + ) + dims = [ + kwargs["dim"] if "dim" in kwargs else args[1], + ] + block_dims = [ + kwargs["block_dim"] if "block_dim" in kwargs else args[2], + ] + else: + if len(args) + len(kwargs) != 6: + raise_type_error( + tx, + f"TMA metadata rank=2 requires exactly 6 arguments, got {len(args) + len(kwargs)}", + ) + dims = [ + kwargs["dim1"] if "dim1" in kwargs else args[1], + kwargs["dim0"] if "dim0" in kwargs else args[2], + ] + block_dims = [ + kwargs["block_dim1"] if "block_dim1" in kwargs else args[3], + kwargs["block_dim0"] if "block_dim0" in kwargs else args[4], + ] + element_size = kwargs["element_size"] if "element_size" in kwargs else args[-1] + + # to make pyrefy happy + if not isinstance(ptr, variables.DataPtrVariable): + raise AssertionError(f"ptr must be a DataPtrVariable, got {type(ptr)}") + + return TMADescriptorExperimentalVariable( + data_ptr=ptr, + dims=dims, + block_dims=block_dims, + element_size=element_size, + ) + + +class CreateTMADescriptorStableVariable(VariableTracker): + def python_type(self) -> type: + return types.FunctionType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tensor = kwargs["tensor"] if "tensor" in kwargs else args[0] + block_shape = kwargs["block_shape"] if "block_shape" in kwargs else args[1] + + return TMADescriptorStableVariable( + tensor=tensor, # type: ignore[arg-type] + block_shape=block_shape, # type: ignore[arg-type] + ) + + +class PyTreeGetNodeTypeFunctionVariable(UserFunctionVariable): + """ + `torch.utils._pytree._get_node_type` function is very hot function. We want to special case it to reduce Dynamo tracing time. + + def _get_node_type(tree: Any) -> Any: + node_type = type(tree) + # All namedtuple types are implicitly registered as pytree nodes. + # XXX: Other parts of the codebase expect namedtuple types always return + # `namedtuple` instead of the actual namedtuple type. Even if the type + # is explicitly registered. + if is_namedtuple_class(node_type): + return collections.namedtuple + return node_type + """ + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if len(args) != 1: + raise_type_error( + tx, f"pytree_get_node_type requires exactly 1 argument, got {len(args)}" + ) + type_source = None + if args[0].source: + install_guard(args[0].source.make_guard(GuardBuilder.TYPE_MATCH)) + type_source = TypeSource(args[0].source) + python_type = args[0].python_type() + if is_namedtuple_class(python_type): + collections_source = ImportSource("collections") + install_guard(collections_source.make_guard(GuardBuilder.ID_MATCH)) + type_source = AttrSource(collections_source, "namedtuple") + return VariableTracker.build( + tx, vars(collections)["namedtuple"], type_source + ) + return VariableTracker.build(tx, python_type, source=type_source) + + +class PyTreeTreeIsLeafFunctionVariable(UserFunctionVariable): + """ + `torch.utils._pytree.tree_is_leaf` function is a hot function. We want to special case it to reduce Dynamo tracing time. + + def tree_is_leaf( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, + ) -> bool: + if is_leaf is not None and is_leaf(tree): + return True + return _get_node_type(tree) not in SUPPORTED_NODES + + When is_leaf is None (the common case), we can optimize by not tracing into the function. + When is_leaf is not None, we fall back to regular tracing since it requires executing user code. + """ + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # tree_is_leaf(tree, is_leaf=None) + if len(args) < 1 or len(args) > 2: + raise_type_error( + tx, f"tree_is_leaf requires 1 or 2 arguments, got {len(args)}" + ) + + # Check if is_leaf parameter is provided + is_leaf = kwargs.get("is_leaf", ConstantVariable.create(None)) + if len(args) == 2: + is_leaf = args[1] + + if not is_leaf.is_constant_none(): + return super().call_function(tx, args, kwargs) + + # Optimize the case where is_leaf is None + # return _get_node_type(tree) not in SUPPORTED_NODES + tree = args[0] + node_type_var = PyTreeGetNodeTypeFunctionVariable( + torch.utils._pytree._get_node_type + ).call_function(tx, [tree], {}) + + # If the SUPPORTED_NODES was seen earlier and mutated, there would be a + # source and that will give us the mutated SUPPORTED_NODES. + # get_pytree_SUPPORTED_NODES_source is cached, so install its + # ImportSource("torch") ID_MATCH guard here. + install_guard(ImportSource("torch").make_guard(GuardBuilder.ID_MATCH)) + supported_nodes_var = VariableTracker.build( + tx, + torch.utils._pytree.SUPPORTED_NODES, + source=get_pytree_SUPPORTED_NODES_source(), + ) + out = supported_nodes_var.call_method(tx, "__contains__", [node_type_var], {}) + return VariableTracker.build(tx, not out.value) + + +class SparseTensorCreationSkipVariable(SkipFunctionVariable): + """ + Skip variable for sparse tensor factory functions with clear messaging regarding lack of support. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + reason = "sparse tensor creation is not supported in torch.compile" + super().__init__(value, reason=reason, **kwargs) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .. import graph_break_hints + + fn_name = getattr(self.value, "__name__", str(self.value)) + unimplemented( + gb_type="Sparse tensor creation not supported", + context=f"function: {fn_name}", + explanation=( + f"torch.compile does not support sparse tensor creation functions like {fn_name}. " + "Sparse tensors require specialized handling that is not yet implemented in the compiler." + ), + hints=[*graph_break_hints.SPARSE_TENSOR], + ) + + +def emit_noargs_leaf_function_to_graph( + tx: "InstructionTranslatorBase", + real_impl: Callable[[], None], + name: str, +) -> None: + """Emit an invoke_leaf_function node for a side-effectful function with no + tensor inputs or outputs. + + The function is captured as a closure inside _LeafCallable objects and + registered as a static attribute on the graph module. Because + invoke_leaf_function is registered as EffectType.ORDERED, effect tokens + prevent DCE and maintain execution ordering relative to other ops. + + Use this when Dynamo needs to preserve a pure-side-effect call (like + setting global runtime state) in the compiled graph so that it replays + at the correct position at runtime. + """ + import torch.utils._pytree as pytree + from torch._higher_order_ops.invoke_leaf_function import ( + _LeafCallable, + invoke_leaf_function, + make_leaf_function_wrappers, + ) + + def fake_impl(): + return None + + captured_out_spec: list[pytree.TreeSpec | None] = [None] + wrapped_real, wrapped_fake = make_leaf_function_wrappers( + real_impl, fake_impl, captured_out_spec + ) + + real_callable = _LeafCallable(wrapped_real) + fake_callable = _LeafCallable(wrapped_fake) + input_spec = pytree.tree_flatten(((), {}))[1] + + def make_proxy(attr_name: str, val: Any) -> Any: + proxy = tx.output.register_static_attr_and_return_proxy(attr_name, val) + proxy.node.type = type(val) + return proxy + + invoke_args = ( + make_proxy(f"{name}_real_fn", real_callable), + make_proxy(f"{name}_fake_fn", fake_callable), + make_proxy(f"{name}_input_spec", input_spec), + "", # mutated_flat_indices + ) + tx.output.create_proxy("call_function", invoke_leaf_function, invoke_args, {}) + + +class TritonSetAllocatorVariable(VariableTracker): + """Trace triton.set_allocator as an invoke_leaf_function node in the + graph so that it executes at the right point at runtime, ordered by + effect tokens.""" + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def python_type(self) -> type: + return type(self.value) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if len(args) != 1: + raise AssertionError(f"expected exactly 1 arg, got {len(args)}") + if kwargs: + raise AssertionError("unexpected kwargs") + alloc_fn = args[0].as_python_constant() + + # Emit an invoke_leaf_function node so it runs at runtime. + set_allocator = self.value + + def real_impl(): + set_allocator(alloc_fn) + return None + + emit_noargs_leaf_function_to_graph(tx, real_impl, "set_alloc") + + return ConstantVariable.create(None) + + +# --------------------------------------------------------------------------- +# CPython descriptor VTs +# +# Each class mirrors a CPython descriptor type (PyWrapperDescr_Type, +# PyMethodDescr_Type, etc.) and implements tp_descr_get_impl to model +# the descriptor binding step faithfully. +# --------------------------------------------------------------------------- + + +def _check_descriptor_obj_type( + tx: "InstructionTranslatorBase", + descriptor: types.MethodDescriptorType + | types.WrapperDescriptorType + | types.MemberDescriptorType + | types.GetSetDescriptorType, + obj: "VariableTracker", +) -> None: + """Check that obj's type is compatible with descriptor.__objclass__. + + Mirrors CPython's descr_check which raises TypeError when a C descriptor + is bound to an object whose type is not a subtype of the descriptor's + __objclass__. + + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L79-L96 + """ + if obj is None: + return + try: + obj_type = obj.python_type() + except NotImplementedError: + return + if not issubclass(obj_type, descriptor.__objclass__): + raise_type_error( + tx, + f"descriptor '{descriptor.__name__}' for " + f"'{descriptor.__objclass__.__name__}' objects " + f"doesn't apply to a '{obj_type.__name__}' object", + ) + + +# descr_members: __objclass__ and __name__ are PyMemberDef on all descriptor +# types. https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L641-L645 +class WrapperDescriptorVariable(VariableTracker): + """Unbound C slot wrapper (wrapper_descriptor on a type). + + CPython types define behavior through C-level slots on PyTypeObject + (tp_richcompare, sq_length, nb_add, etc.). When these slots are + accessed from Python (e.g. list.__add__), CPython exposes them as + wrapper_descriptor objects (PyWrapperDescr_Type). A wrapper_descriptor + is an unbound descriptor living on the type -- it is not tied to any + instance. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L867 + + When a wrapper_descriptor is accessed on an instance (e.g. [1,2].__add__), + its tp_descr_get slot (wrapperdescr_get) is invoked, which calls + PyWrapper_New to produce a bound method-wrapper (_PyMethodWrapper_Type). + The tp_descr_get_impl method on this class mirrors that binding step. + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.WrapperDescriptorType, + owner: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + self.owner = owner + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return f"WrapperDescriptorVariable({cls_name}.{self.descriptor.__name__})" + + def python_type(self) -> type: + return types.WrapperDescriptorType + + def as_python_constant(self) -> types.WrapperDescriptorType: + return self.descriptor + + def get_real_python_backed_value(self) -> types.WrapperDescriptorType: + return self.descriptor + + tp_members = { + "__objclass__": Member(getset_build(lambda s: s.descriptor.__objclass__)), + "__name__": Member(getset_build(lambda s: s.descriptor.__name__)), + } + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Unbound call: list.__add__([1,2], [3,4]) -- first arg is self. + # Mirrors wrapperdescr_call which invokes the C slot directly. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L535 + if not args: + raise_type_error( + tx, + f"descriptor '{self.descriptor.__name__}' of " + f"'{self.descriptor.__objclass__.__name__}' object needs an argument", + ) + obj, *rest = args + _check_descriptor_obj_type(tx, self.descriptor, obj) + # Dispatch through the owner (UDCV for the defining class) rather + # than obj.call_method, which would do MRO resolution from type(obj) + # and find Python overrides on subclasses. Routing through the class + # mirrors CPython's wrapperdescr_call which invokes the C slot directly. + return self.owner.call_method( + tx, self.descriptor.__name__, [obj, *rest], kwargs + ) + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> "MethodWrapperVariable": + # Mirrors wrapperdescr_get which calls PyWrapper_New to produce + # a bound method-wrapper. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L203-L213 + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1489-L1505 + _check_descriptor_obj_type(tx, self.descriptor, obj) + return MethodWrapperVariable(self.descriptor, obj, source=self.source) + + +class MethodWrapperVariable(VariableTracker): + """Bound method-wrapper (wrapper_descriptor bound to an instance). + + Produced by WrapperDescriptorVariable.tp_descr_get_impl, mirroring + PyWrapper_New which stores a reference to the descriptor and the instance. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1450 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.WrapperDescriptorType, + obj: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + self.obj = obj + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return ( + f"MethodWrapperVariable({cls_name}.{self.descriptor.__name__}, {self.obj})" + ) + + def python_type(self) -> type: + return types.MethodWrapperType + + # A method-wrapper's own dunders come from the descriptor / bound obj and do + # not depend on obj's contents. Resolving them via these tables (consulted + # before the generic getset-descriptor path) avoids forcing self.obj to a + # python constant, which would break e.g. a list holding non-constant items. + tp_getset = { + "__name__": GetSet( + lambda s, tx: ConstantVariable.create(s.descriptor.__name__) + ), + "__qualname__": GetSet( + lambda s, tx: ConstantVariable.create(s.descriptor.__qualname__) + ), + } + tp_members = { + "__self__": Member(lambda s, tx: s.obj), + } + + def get_real_python_backed_value(self) -> types.MethodWrapperType: + return self.as_python_constant() + + def is_python_constant(self) -> bool: + return self.obj.is_python_constant() + + def as_python_constant(self) -> types.MethodWrapperType: + obj_value = self.obj.as_python_constant() + try: + return self.descriptor.__get__(obj_value, type(obj_value)) + except TypeError: + raise AsPythonConstantNotImplementedError(self) from None + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Only materialize the wrapper (which forces self.obj's python constant) + # for the tensor-getter special case; the generic path below dispatches + # via call_method and must not require a constant self.obj (e.g. a set / + # frozenset whose as_python_constant() re-hashes its keys). + if args and isinstance(args[0], variables.TensorVariable): + try: + method_wrapper = self.as_python_constant() + except NotImplementedError: + method_wrapper = None + if method_wrapper is not None and is_tensor_base_attr_getter( + method_wrapper + ): + if not (len(args) == 1 and len(kwargs) == 0): + raise_type_error( + tx, "tensor attribute getter takes exactly one argument" + ) + # Avoid the generic descriptor path's implicit owner lookup, which + # would read __class__ on tensor subclasses during __torch_function__. + descriptor = cast(Any, method_wrapper.__self__) + return args[0].tp_getattro_impl(tx, descriptor.__name__) + + return self.obj.call_method(tx, self.descriptor.__name__, list(args), kwargs) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.obj) + codegen.extend_output(codegen.create_load_attrs(self.descriptor.__name__)) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + try: + # CPython wrapper_hash: + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1347 + return hash(self.as_python_constant()), False + except NotImplementedError: + return super().hash_impl(tx) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + +class MethodDescriptorVariable(VariableTracker): + """Unbound C method descriptor (method_descriptor on a type). + + CPython types expose their PyMethodDef-based C methods as + method_descriptor objects (PyMethodDescr_Type) in the type's tp_dict. + For example, list.append and dict.get are method_descriptors. Like + wrapper_descriptors, these are unbound descriptors living on the type. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L716 + + When a method_descriptor is accessed on an instance (e.g. [].append), + its tp_descr_get slot (method_get) is invoked, which calls + PyCFunction_NewEx to produce a bound builtin_function_or_method + (PyCFunction_Type). The tp_descr_get_impl method mirrors that step. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L137-L159 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.MethodDescriptorType, + owner: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + self.owner = owner + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return f"MethodDescriptorVariable({cls_name}.{self.descriptor.__name__})" + + def python_type(self) -> type: + return types.MethodDescriptorType + + def as_python_constant(self) -> types.MethodDescriptorType: + return self.descriptor + + def get_real_python_backed_value(self) -> types.MethodDescriptorType: + return self.descriptor + + tp_members = { + "__objclass__": Member(getset_build(lambda s: s.descriptor.__objclass__)), + "__name__": Member(getset_build(lambda s: s.descriptor.__name__)), + } + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Mirrors methoddescr_call which invokes the C method directly. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L427 + if not args: + raise_type_error( + tx, + f"descriptor '{self.descriptor.__name__}' of " + f"'{self.descriptor.__objclass__.__name__}' object needs an argument", + ) + obj, *rest = args + name = self.descriptor.__name__ + _check_descriptor_obj_type(tx, self.descriptor, obj) + # Dispatch through the owner (UDCV for the defining class) rather + # than obj.call_method, which would do MRO resolution from type(obj) + # and find Python overrides on subclasses. + return self.owner.call_method(tx, name, [obj, *rest], kwargs) + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> "BoundBuiltinMethodVariable": + # Mirrors method_get which calls PyCFunction_NewEx to produce a + # bound builtin_function_or_method. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L137-L159 + # https://github.com/python/cpython/blob/3.13/Objects/methodobject.c#L40 + _check_descriptor_obj_type(tx, self.descriptor, obj) + return BoundBuiltinMethodVariable(self.descriptor, obj, source=self.source) + + +class BoundBuiltinMethodVariable(VariableTracker): + """Bound builtin_function_or_method (PyCFunction_Type). + + Produced by MethodDescriptorVariable.tp_descr_get_impl (binding a + method_descriptor to an instance, e.g. [].append) or created by the + builder for bound C methods (e.g. frozenset().__contains__, + tuple.__new__). The backing descriptor can be a MethodDescriptorType + or a BuiltinFunctionType (for methods stored directly in type dicts). + https://github.com/python/cpython/blob/3.13/Objects/methodobject.c#L331 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.MethodDescriptorType + | types.BuiltinFunctionType + | types.ClassMethodDescriptorType, + obj: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + self.obj = obj + + def __repr__(self) -> str: + cls_name = getattr( + getattr(self.descriptor, "__objclass__", None), "__name__", "?" + ) + return f"BoundBuiltinMethodVariable({cls_name}.{self.descriptor.__name__}, {self.obj})" + + def python_type(self) -> type: + return types.BuiltinMethodType + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # meth_hash: https://github.com/python/cpython/blob/e76aa128fe/Objects/methodobject.c#L319 + try: + return hash(self.as_python_constant()), False + except AsPythonConstantNotImplementedError: + return id(self), True + + def tp_richcompare_impl(self, tx, other, op): + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def as_python_constant(self) -> Any: + obj = self.obj.as_python_constant() + if isinstance(self.descriptor, types.ClassMethodDescriptorType): + return self.descriptor.__get__(None, obj) + if hasattr(self.descriptor, "__get__"): + return self.descriptor.__get__(obj) # type: ignore[union-attr] + return getattr(obj, self.descriptor.__name__) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.obj.call_method(tx, self.descriptor.__name__, list(args), kwargs) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.obj) + codegen.extend_output(codegen.create_load_attrs(self.descriptor.__name__)) + + +class ClassMethodDescriptorVariable(VariableTracker): + """C-level classmethod descriptor (classmethod_descriptor on a type). + + CPython exposes C classmethods defined via PyMethodDef with METH_CLASS + as classmethod_descriptor objects (PyClassMethodDescr_Type). For + example, dict.fromkeys is a classmethod_descriptor. Like + method_descriptor, these live on the type and are unbound. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L756 + + classmethod_get binds the C method to the class (ignoring obj) via + PyCMethod_New, producing a bound builtin_function_or_method. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L94-L134 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.ClassMethodDescriptorType, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return f"ClassMethodDescriptorVariable({cls_name}.{self.descriptor.__name__})" + + def python_type(self) -> type: + return types.ClassMethodDescriptorType + + def as_python_constant(self) -> types.ClassMethodDescriptorType: + return self.descriptor + + def get_real_python_backed_value(self) -> types.ClassMethodDescriptorType: + return self.descriptor + + tp_members = { + "__objclass__": Member(getset_build(lambda s: s.descriptor.__objclass__)), + "__name__": Member(getset_build(lambda s: s.descriptor.__name__)), + } + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> BoundBuiltinMethodVariable: + # classmethod_get binds the C method to the class (ignoring obj), + # producing a builtin_function_or_method via PyCMethod_New. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L94-L134 + return BoundBuiltinMethodVariable(self.descriptor, owner, source=self.source) + + +class StaticMethodVariable(VariableTracker): + """staticmethod descriptor wrapping a callable. + + CPython's staticmethod (PyStaticMethod_Type) is a non-data descriptor + whose tp_descr_get (sm_descr_get) simply returns the wrapped callable, + ignoring both obj and type. + https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1520 + https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1418-L1428 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: staticmethod, # type: ignore[type-arg] + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + func_name = getattr(self.descriptor.__func__, "__name__", "?") + return f"StaticMethodVariable({func_name})" + + def python_type(self) -> type: + return staticmethod + + def as_python_constant(self) -> staticmethod: # type: ignore[type-arg] + return self.descriptor + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker | None, + owner: VariableTracker, + ) -> VariableTracker: + # sm_descr_get returns sm->sm_callable unconditionally. + # https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1418-L1428 + func_source = AttrSource(self.source, "__func__") if self.source else None + return VariableTracker.build(tx, self.descriptor.__func__, func_source) + + +class ClassMethodVariable(VariableTracker): + """classmethod descriptor wrapping a callable. + + CPython's classmethod (PyClassMethod_Type) is a non-data descriptor + whose tp_descr_get (cm_descr_get) creates a bound method of the + wrapped callable bound to the class (via PyMethod_New). + https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1314 + https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1215-L1227 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: classmethod, # type: ignore[type-arg] + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + func_name = getattr(self.descriptor.__func__, "__name__", "?") + return f"ClassMethodVariable({func_name})" + + def python_type(self) -> type: + return classmethod + + def as_python_constant(self) -> classmethod: # type: ignore[type-arg] + return self.descriptor + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> VariableTracker: + # cm_descr_get binds the wrapped function to the class. + # https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1215-L1227 + func_source = AttrSource(self.source, "__func__") if self.source else None + bound_source = ( + AttrSource(owner.source, self.descriptor.__func__.__name__) + if owner.source + else None + ) + return UserMethodVariable( + self.descriptor.__func__, + owner, + source_fn=func_source, + source=bound_source, + ) + + +class MemberDescriptorVariable(VariableTracker): + """C struct field descriptor (member_descriptor on a type). + + CPython exposes C struct fields defined via PyMemberDef as + member_descriptor objects (PyMemberDescr_Type). These are data + descriptors used by __slots__ and C extension types to provide + direct access to struct members. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L793 + + member_get reads the field via PyMember_GetOne. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L162-L180 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.MemberDescriptorType, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return f"MemberDescriptorVariable({cls_name}.{self.descriptor.__name__})" + + def python_type(self) -> type: + return types.MemberDescriptorType + + def as_python_constant(self) -> types.MemberDescriptorType: + return self.descriptor + + tp_members = { + "__objclass__": Member(getset_build(lambda s: s.descriptor.__objclass__)), + "__name__": Member(getset_build(lambda s: s.descriptor.__name__)), + } + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> VariableTracker: + # Mirrors member_get which calls PyMember_GetOne to read the + # C struct field. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L162-L180 + _check_descriptor_obj_type(tx, self.descriptor, obj) + from .object_protocol import _UnhandledDescriptorError + + attr_name = self.descriptor.__name__ + obj_value = obj.get_real_python_backed_value() + if obj_value is NO_SUCH_SUBOBJ: + raise _UnhandledDescriptorError( + f"Cannot resolve member_descriptor '{attr_name}' " + f"on {type(obj).__name__}" + ) + try: + resolved = self.descriptor.__get__(obj_value, type(obj_value)) + except (AttributeError, TypeError): + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(obj_value).__name__}' object has no attribute '{attr_name}'" + ], + ) + result_source = obj.source and AttrSource(obj.source, attr_name) + return VariableTracker.build(tx, resolved, result_source) + + def tp_descr_set_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # Mirrors member_set (PyMember_SetOne): store into the C struct field. + # STORE_ATTR itself applies the descriptor, so replay via store_attr on + # the target (mirrors the __slots__ path in UserDefinedObjectVariable). + # value is None for __delete__. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L180-L196 + stored = variables.DeletedVariable() if value is None else value + tx.output.side_effects.store_attr(obj, self.descriptor.__name__, stored) + return variables.ConstantVariable.create(None) + + +class GetSetDescriptorVariable(VariableTracker): + """C getter/setter descriptor (getset_descriptor on a type). + + CPython exposes C getter/setter pairs defined via PyGetSetDef as + getset_descriptor objects (PyGetSetDescr_Type). These are data + descriptors used for computed attributes backed by C functions + (e.g. object.__class__, type.__dict__). + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L830 + + getset_get calls the C getter function. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L183-L197 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__(self, descriptor: types.GetSetDescriptorType, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return f"GetSetDescriptorVariable({cls_name}.{self.descriptor.__name__})" + + def get_real_python_backed_value(self) -> types.GetSetDescriptorType: + return self.descriptor + + def _getset_descriptor_get( + self, tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + if self.source is None: + return None + source = AttrSource(self.source, "__get__") + return VariableTracker.build(tx, self.descriptor.__get__, source) + + tp_getset = { + "__get__": GetSet(_getset_descriptor_get, None), + } + + tp_members = { + "__objclass__": Member(getset_build(lambda s: s.descriptor.__objclass__)), + "__name__": Member(getset_build(lambda s: s.descriptor.__name__)), + } + + def is_python_constant(self) -> bool: + return True + + def as_python_constant(self) -> types.GetSetDescriptorType: + return self.descriptor + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> VariableTracker: + # Mirrors getset_get which calls the C getter function. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L183-L197 + attr_name = self.descriptor.__name__ + # Try to eagerly call the C getter when we can obtain the + # concrete Python object (UDOV.value, or as_python_constant + # for classes/constants). Fall back to tp_getattro_impl for + # proxy-based VTs like TensorVariable. + _check_descriptor_obj_type(tx, self.descriptor, obj) + obj_value = obj.get_real_python_backed_value() + if obj_value is NO_SUCH_SUBOBJ: + from .object_protocol import _UnhandledDescriptorError + + raise _UnhandledDescriptorError( + f"Cannot resolve getset_descriptor '{attr_name}' " + f"on {type(obj).__name__}" + ) + try: + resolved = self.descriptor.__get__(obj_value, type(obj_value)) + except (AttributeError, TypeError): + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(obj_value).__name__}' object has no attribute '{attr_name}'" + ], + ) + result_source = obj.source and AttrSource(obj.source, attr_name) + if ( + obj.source + and self.descriptor.__objclass__ is type + and attr_name in ("__annotations__", "__dict__", "__mro__") + ): + # Direct descriptor calls still resolve the standard type slot even + # when a metaclass shadows the same attribute. Only attach the + # normal attribute source when runtime attribute lookup agrees. + static_desc = inspect.getattr_static(type(obj_value), attr_name, None) + if static_desc is not self.descriptor: + result_source = None + elif attr_name == "__mro__": + result_source = TypeMROSource(obj.source) + return VariableTracker.build(tx, resolved, result_source) + + +class PropertyVariable(VariableTracker): + """Python property descriptor. + + The property type is a data descriptor with tp_descr_get = + property_descr_get which calls fget(obj) to compute the value. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L2073 + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1660-L1693 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: property, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + fget_name = getattr(self.descriptor.fget, "__name__", "?") + return f"PropertyVariable({fget_name})" + + def python_type(self) -> type: + return property + + def as_python_constant(self) -> property: + return self.descriptor + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker | None, + owner: VariableTracker, + ) -> VariableTracker: + # Mirrors property_descr_get: if obj is NULL or None, return self. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1660-L1693 + if obj is None: + return self + fget_source = AttrSource(self.source, "fget") if self.source else None + fget_vt = VariableTracker.build( + tx, self.descriptor.fget, source=fget_source, realize=True + ) + return fget_vt.call_function(tx, [obj], {}) + + +class TupleGetterVariable(VariableTracker): + """_tuplegetter descriptor used by namedtuple for field access. + + _tuplegetter is a C data descriptor that stores an index and returns + self[index] on instance access. When accessed on the class (obj=None), + it returns the descriptor itself. + https://github.com/python/cpython/blob/3.13/Modules/_collectionsmodule.c#L2735 + https://github.com/python/cpython/blob/3.13/Modules/_collectionsmodule.c#L2636-L2663 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: "_collections._tuplegetter", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + _, (idx, doc) = self.descriptor.__reduce__() + return f"TupleGetterVariable(index={idx}, doc={doc!r})" + + def python_type(self) -> type: + return _collections._tuplegetter + + def as_python_constant(self) -> "_collections._tuplegetter": + return self.descriptor + + # _tuplegetter exposes __doc__ as a T_OBJECT member. + # https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L2717-L2721 + tp_members = {"__doc__": Member(getset_build(lambda s: s.descriptor.__doc__))} + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker | None, + owner: VariableTracker, + ) -> VariableTracker: + # https://github.com/python/cpython/blob/3.13/Modules/_collectionsmodule.c#L2636-L2663 + if obj is None: + return self + _, (idx, _) = self.descriptor.__reduce__() + return obj.call_method( + tx, "__getitem__", [variables.ConstantVariable.create(idx)], {} + ) + + def tp_descr_set_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # _tuplegetter fields are read-only; tuplegetter_descr_set always + # raises AttributeError for both set and delete. + # https://github.com/python/cpython/blob/3.13/Modules/_collectionsmodule.c#L2665-L2673 + msg = "can't delete attribute" if value is None else "can't set attribute" + raise_observed_exception(AttributeError, tx, args=[msg]) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/hashable.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/hashable.py new file mode 100644 index 0000000000000000000000000000000000000000..9bfe3a735b284c0777f958abe0c3e49ba4194fdf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/hashable.py @@ -0,0 +1,235 @@ +""" +Hashability utilities for PyTorch Dynamo variable tracking. + +This module provides the HashableTracker wrapper class and associated utilities +for making VariableTracker instances usable as dictionary keys and set elements +during symbolic execution. Used by both ConstDictVariable and SetVariable. +""" + +from typing import TYPE_CHECKING + +import torch + +from .. import variables +from ..exc import raise_observed_exception +from ..utils import guard_if_dyn, specialize_symnode +from .base import VariableTracker + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +def raise_unhashable( + arg: VariableTracker, tx: "InstructionTranslatorBase | None" = None +) -> None: + if tx is None: + from torch._dynamo.symbolic_convert import InstructionTranslator + + tx = InstructionTranslator.current_tx() + + try: + arg_type = arg.python_type() + except Exception: + arg_type = None + + # Safety check: if we know the real Python type and it IS hashable, + # our is_hashable() disagrees with CPython. Graph-break rather than + # raising a wrong TypeError. + if arg_type is not None and arg_type.__hash__ is not None: + from .. import graph_break_hints + from ..exc import unimplemented + + unimplemented( + gb_type="Hashability mismatch", + context=f"raise_unhashable {arg}", + explanation=f"Dynamo thinks {arg_type.__name__} is unhashable, " + f"but its __hash__ is not None. This likely indicates a missing " + f"or incorrect is_hashable() override.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + type_name = arg_type.__name__ if arg_type is not None else type(arg).__name__ + raise_observed_exception( + TypeError, + tx, + args=[ + f"unhashable type: '{type_name}'", + ], + ) + + +def is_hashable(x: VariableTracker) -> bool: + # LazyVT optimization: check hashability without realizing the VT to avoid + # accidentally inserting guards. + if ( + isinstance(x, variables.LazyVariableTracker) + and not x.is_realized() + and x.is_hashable_lazy() + ): + return True + + return x.is_hashable() + + +class RawHash: + """Wraps a pre-computed hash value to bypass int.__hash__'s modular reduction. + + When building a tuple/frozenset of per-item hashes, using bare ints would + apply long_hash (mod sys.hash_info.modulus), corrupting the values. + Wrapping in RawHash makes tuplehash/frozenset_hash see the original hash. + """ + + __slots__ = ("h",) + + def __init__(self, h: int) -> None: + self.h = h + + def __hash__(self) -> int: + return self.h + + def __eq__(self, other: object) -> bool: + return isinstance(other, RawHash) and self.h == other.h + + +class HashableTracker: + """ + Class that wraps a VariableTracker and makes it hashable. + Note that it's fine to put VTs into dictionaries and sets, but doing so + does not take into account aliasing. + """ + + _MISSING = object() + + def __init__(self, vt: VariableTracker) -> None: + # We specialize SymNodes + vt = specialize_symnode(vt) + + # Fast path for unrealized LazyVariableTrackers: check and hash without + # realizing, to avoid inserting guards. If the fast-path check fails, + # fall through to realize the VT and try the full is_hashable check. + if ( + isinstance(vt, variables.LazyVariableTracker) + and not vt.is_realized() + and vt.is_hashable_lazy() + ): + self._hash = hash(vt.original_value()) + self._hash_is_identity = False + self.vt = vt + return + + # Compute hash via the tp_hash slot (generic_hash_impl). + # For unhashable types, hash_impl raises ObservedTypeError. + from torch._dynamo.symbolic_convert import InstructionTranslator + + from .object_protocol import generic_hash_impl + + tx = InstructionTranslator.current_tx() + # is_fake marks an identity-based hash (e.g. id(fake_tensor)); such VTs + # have no python-constant value, so their key equality is identity. + self._hash, self._hash_is_identity = generic_hash_impl(tx, vt) + self.vt = vt + + @classmethod + def _maybe_constant_torch_size(cls, vt: VariableTracker) -> object: + from .lists import SizeVariable + from .tensor import TensorVariable + + if ( + isinstance(vt, variables.LazyVariableTracker) + and not vt.is_realized() + and isinstance(vt.original_value(), torch.Size) + ): + return vt.original_value() + + if not isinstance(vt, SizeVariable): + return cls._MISSING + + items = [] + for item in vt.items: + if item.is_python_constant(): + items.append(item.as_python_constant()) + continue + + if isinstance(item, TensorVariable): + proxy = getattr(item, "proxy", None) + node = getattr(proxy, "node", None) + meta = getattr(node, "meta", None) if node is not None else None + example_value = ( + meta.get("example_value") if isinstance(meta, dict) else None + ) + constant = getattr(example_value, "constant", None) + + if isinstance(constant, torch.Tensor) and constant.numel() == 1: + items.append(constant.item()) + continue + + return cls._MISSING + + return torch.Size(items) + + def __hash__(self) -> int: + return self._hash + + def __eq__(self, other: object) -> bool: + """ + Checks equality between two HashableTracker instances. + + Mirrors CPython's PyObject_RichCompareBool: routes the comparison + through generic_richcompare_bool so any user-defined __eq__ runs. + + Args: + other: Another HashableTracker instance to compare with + + Returns: + True if the underlying variable trackers are Python-equal, False otherwise + """ + if not isinstance(other, HashableTracker): + return False + if self.vt is other.vt: + return True + + self_constant = self._maybe_constant_torch_size(self.vt) + other_constant = self._maybe_constant_torch_size(other.vt) + if self_constant is not self._MISSING and other_constant is not self._MISSING: + return self_constant == other_constant + + # Tensor keys hash by identity (Tensor.__hash__ is id(self)), so CPython + # only ever compares identical tensors during a dict/set lookup; a + # tensor's elementwise __eq__ is never consulted for membership. Mirror + # that with an identity comparison instead of running __eq__, which would + # otherwise emit a stray elementwise-eq node into the FX graph and + # corrupt the surrounding trace. + from .tensor import TensorVariable + + if isinstance(self.vt, TensorVariable) or isinstance(other.vt, TensorVariable): + return ( + self._hash_is_identity + and other._hash_is_identity + and self._hash == other._hash + ) + + # All other keys: mirror PyObject_RichCompareBool and run the + # comparison through generic_richcompare_bool so any user-defined __eq__ + # runs and its result (or any exception it raises) is observed by the + # traced program. + from ..symbolic_convert import InstructionTranslator + from .object_protocol import generic_richcompare_bool + + tx = InstructionTranslator.current_tx() + + result = generic_richcompare_bool(tx, self.vt, other.vt, op="__eq__") + if result.is_python_constant(): + return bool(result.as_python_constant()) + + if result.is_symnode_like(): + return bool(guard_if_dyn(result)) + + # Comparison did not resolve to a constant (e.g. keys whose __eq__ could + # not be determined). Fall back to identity-based hash equality, which + # mirrors CPython treating such keys as equal only when identical. + return ( + self._hash_is_identity + and other._hash_is_identity + and self._hash == other._hash + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/higher_order_ops.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/higher_order_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d3548b6282a5b3703ad9c6392cec4dc33df15d61 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/higher_order_ops.py @@ -0,0 +1,6407 @@ +""" +This module contains classes and utilities for handling higher-order operators in Dynamo. +It provides functionality for tracing and transforming control flow constructs like +conditions (torch.cond), loops (torch.while_loop), maps (torch.ops.higher_order.map), +and other higher-order operations. + +The module includes specialized VariableTracker classes for different types of +higher-order operations, along with utilities for: +- Speculating and capturing subgraphs +- Managing control flow +- Handling autograd function applications +- Supporting function transformations +- Processing activation checkpoints + +These classes work together to enable Dynamo to correctly trace and compile code +containing complex control flow patterns and higher-order functions while preserving +their semantic behavior. +""" + +import contextlib +import copy +import functools +import inspect +import itertools +import logging +import traceback +import types +import warnings +from collections import Counter +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import Any, cast, get_args, Literal, Optional, TYPE_CHECKING, Union + +import torch._C +import torch.fx +import torch.nn +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.utils import get_fake_value +from torch._dynamo.variables.constant import ConstantVariable +from torch._dynamo.variables.ctx_manager import RepararametrizeModuleContextVariable +from torch._dynamo.variables.functions import UserFunctionVariable +from torch._dynamo.variables.nn_module import UnspecializedNNModuleVariable +from torch._dynamo.variables.script_object import CustomClassObjectVariable +from torch._dynamo.variables.tensor import SymNodeVariable, TensorVariable +from torch._guards import Source +from torch._higher_order_ops.flex_gemm import FLEX_GEMM_OP_ALIASES +from torch._higher_order_ops.invoke_subgraph import NestedCompileRegionOptions +from torch._ops import HigherOrderOperator +from torch.fx.graph_module import GraphModule +from torch.fx.passes.shape_prop import _extract_tensor_metadata +from torch.fx.proxy import Proxy +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet + +from .. import graph_break_hints, variables +from ..exc import ( + FakeTensorObservedException, + ObservedException, + UncapturedHigherOrderOpError, + unimplemented, + Unsupported, +) +from ..source import AttrSource, DictGetItemSource +from ..utils import proxy_args_kwargs, set_example_value, unpack_iterable +from .base import VariableTracker +from .dicts import ConstDictVariable +from .lazy import LazyVariableTracker +from .lists import ListVariable, TupleVariable +from .sets import SetVariable + + +if TYPE_CHECKING: + from torch._dynamo.output_graph import SubgraphTracer + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode + from . import AutogradFunctionContextVariable + +from collections.abc import Generator, Iterable +from typing import ParamSpec, TypeVar + + +P = ParamSpec("P") +R = TypeVar("R") +HOP_VT_Alias = TypeVar("HOP_VT_Alias", bound="TorchHigherOrderOperatorVariable") + +log = logging.getLogger(__name__) +hc_log = torch._logging.getArtifactLogger(__name__, "hierarchical_compile") + +# How speculate_subgraph constructs subgraph placeholders from sub_args. See +# NOTE [argument `set_subgraph_inputs`] below for the meaning of each value. This +# is the single source of truth for the runtime asserts that validate the value. +SetSubgraphInputs = Literal[ + "automatic", "automatic_with_forced_inputs", "flatten_manual", "manual" +] + + +@dataclass +class OutputSpec: + """ + Contains the treespec of the output of the speculated subgraph, and the + information to mask out the constant values from the output during + flattening and inserting them back during unflattening. Cleaning up + constants from the graph makes the graph simpler for AOTDispatcher and + Inductor. + """ + + treespec: pytree.TreeSpec + # list of True/False to identify the locations of const values in the + # subgraph output. True means that value at that index is a constant. + masks_to_filter_const_values: list[bool] | None = None + # The actual constant values that were present in the subgraph output. Note + # that this is the same length as the mask, we just look at the indices + # where mask is True. + const_values: list[Any] | None = None + # Number of intermediate nodes that are also made subgraph outputs. + num_intermediate_nodes_as_outputs: int = 0 + + def __post_init__(self) -> None: + if ( + self.masks_to_filter_const_values is not None + and self.const_values is not None + ): + if len(self.masks_to_filter_const_values) != len(self.const_values): + raise AssertionError( + "masks_to_filter_const_values and const_values must have the same length" + ) + + +@dataclass(frozen=True) +class SubgraphTracingInfo: + """Properties observed during subgraph tracing. + + Expandable container for metadata collected while tracing a HOP subgraph. + Future additions may include aliasing info, mutation info, etc. + """ + + # User code stack at the point where the first externally-visible side + # effect was detected. None means no side effect was observed. + side_effect_stack: traceback.StackSummary | None = None + # All sources accessed via VariableBuilder during the subgraph trace. + traced_sources: OrderedSet[Any] = field(default_factory=OrderedSet) + + +# This function is a syntax sugar for creating a dummy new subtracer so that +# newly added nodes are added to a separate subgraph in this subtracer instead of affecting +# the main graph. This is useful for creating sample inputs for tracing the subgraph. +# For example, in FlexAttentionHigherOrderVariable, we want to create several scalars +# to trace the score_mod function but we don't want the operators that creates the scalar to +# show up in the graph, we could this function to discard the graph changes. +# Example usage: +# with discard_graph_changes(): +# sample_input= create_sample_inputs() +# speculate_subgraph(tx, f, sample_inputs, {}) +@contextlib.contextmanager +def discard_graph_changes( + tx: "InstructionTranslatorBase", +) -> Generator[None, None, None]: + ctx = tx.output.subtracer("subgraph_wrapper", None) + try: + ctx.__enter__() + yield + finally: + ctx.__exit__(None, None, None) + + +def check_meta_consistency_vt( + vars1: list[VariableTracker], + vars2: list[VariableTracker], + lhs_name: str, + rhs_name: str, + include_contiguity: bool = True, +) -> None: + from torch._higher_order_ops.utils import check_meta_consistency + + def _unwrap_var(var: VariableTracker) -> Any: + if var.is_tensor(): + # pyrefly: ignore[missing-attribute] + return var.proxy.node.meta["example_value"] + elif isinstance(var, SymNodeVariable): + return var.sym_num + elif var.is_python_constant(): + return var.as_python_constant() + else: + unimplemented( + gb_type="cannot unwrap variable for check_meta_consistency", + context=str(var), + explanation=f"Expected {var} to be TensorVariable, SymNodeVariable, or ConstantVariable", + hints=[], + ) + + unwrapped1 = [_unwrap_var(var) for var in vars1] + unwrapped2 = [_unwrap_var(var) for var in vars2] + + return check_meta_consistency( + unwrapped1, + unwrapped2, + lhs_name, + rhs_name, + include_contiguity=include_contiguity, + ) + + +@contextlib.contextmanager +def dynamo_enable_grad( + tx: "InstructionTranslatorBase", enable: bool = True +) -> Generator[None, None, None]: + from . import GradModeVariable + + org_value = torch.is_grad_enabled() + try: + GradModeVariable.create(tx, enable, initialized=True) + yield + finally: + GradModeVariable.create(tx, org_value, initialized=True) + + +@contextlib.contextmanager +def dynamo_allow_side_effects_in_hop( + tx: "InstructionTranslatorBase", +) -> Generator[None, None, None]: + orig_val = tx.output.current_tracer.allow_side_effects_in_hop + try: + tx.output.current_tracer.allow_side_effects_in_hop = True + yield + finally: + tx.output.current_tracer.allow_side_effects_in_hop = orig_val + + +def find_mismatched_vars( + var: Any, types: type | tuple[type, ...], allow_none: bool = False +) -> set[VariableTracker]: + """ + Recursively finds variables whose type is not an instance of the specified types. + Args: + var: The variable to check. + types: A tuple of allowed types. + allow_none (bool): Whether to allow None values. Defaults to False. + Returns: + A set of variables whose type is not an instance of the specified types. + """ + mismatched_vars = set() + if isinstance(var, (list, tuple)): + for item in var: + mismatched_vars.update(find_mismatched_vars(item, types, allow_none)) + elif isinstance(var, (TupleVariable, ListVariable)): + for item in var.items: + mismatched_vars.update(find_mismatched_vars(item, types, allow_none)) + elif isinstance(var, ConstDictVariable): + for value in var.items.values(): + mismatched_vars.update(find_mismatched_vars(value, types, allow_none)) + elif isinstance(var, SetVariable): + for key in var.items: + mismatched_vars.update(find_mismatched_vars(key.vt, types, allow_none)) + else: + if not isinstance(var, types) and not (allow_none and var.is_constant_none()): + mismatched_vars.add(var) + return mismatched_vars + + +def only_consist_of( + var: Any, types: tuple[type, ...], allow_none: bool = False +) -> bool: + mismatch_vars = find_mismatched_vars(var, types, allow_none=allow_none) + return len(mismatch_vars) == 0 + + +# A more read-able syntax sugar for creating a UserFunctionVariable for f +# and run call_function on it. Make it return a function to preserve the calling +# convention of the original f. +from torch._dynamo.utils import _make_inlined + + +def add_call_function( + tx: "InstructionTranslatorBase", + fn: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any], + flat_example_value: Any, + config: NestedCompileRegionOptions | None = None, +) -> VariableTracker: + from .builder import wrap_fx_proxy + + proxy = tx.output.create_proxy( + "call_function", + fn, + args=args, + kwargs=kwargs, + ) + + # Set backend metadata if provided + if config is not None: + if "custom" not in proxy.node.meta: + # pyrefly: ignore [implicit-any] + proxy.node.meta["custom"] = {} + proxy.node.meta["custom"]["nested_region_config"] = config + if proxy.node.target != torch._higher_order_ops.invoke_subgraph: + raise AssertionError( + "Expected proxy node target to be torch._higher_order_ops.invoke_subgraph" + ) + + # Store the invocation as a call + flat_variable = wrap_fx_proxy( + tx=tx, + proxy=proxy, + example_value=flat_example_value, + ) + return flat_variable + + +def overwrite_tensor_vt_requires_grad( + graph_output_vts: Iterable[VariableTracker], flat_variable: VariableTracker +) -> None: + # All outputs of autograd.Function have requires_grad=True. We turn off + # grad_mode in autograd.Function, so our outputs naively have + # requires_grad=False. So we hackily force them back on here. A better + # solution would be to write python code that Dynamo could trace but we + # decided that it wasn't worth it. + # pyrefly: ignore[missing-attribute] + for orig_vt, subgraph_vt in zip(graph_output_vts, flat_variable.items): + if isinstance(orig_vt, variables.TensorVariable): + if not isinstance(subgraph_vt, variables.TensorVariable): + raise AssertionError("Expected subgraph_vt to be a TensorVariable") + orig_vt.requires_grad = subgraph_vt.requires_grad + if orig_vt.requires_grad: + orig_vt.has_grad_fn = True + + +def overwrite_tensor_vt_proxy( + graph_output_vts: Iterable[VariableTracker], flat_variable: VariableTracker +) -> None: + # wrap_fx_proxy creates fresh variable trackers. However, the main program + # after the speculate subgraph can still use the original tensor vts that + # are still pointing to the nodes present in the subgraph. So, we reproxify + # the original tensor vts with the subgraph outputs. This way, whenever the + # outer graph uses an original vt, it uses the subgraph output. + # + # This is critical for maintaining the separation between: + # - `body_r`: The output VT structure that Dynamo continues tracing (may + # contain non-proxyable objects, nested structures, etc.) + # - `graph_output_vts`: Only the tensor/symint VTs that were actual graph + # outputs from speculate_subgraph + # + # By overwriting the proxies of VTs in `body_r` with the proxies from the + # HOP call, we ensure the outer graph correctly references the HOP outputs + # while still allowing `body_r` to contain arbitrary Python objects. + # pyrefly: ignore[missing-attribute] + for orig_vt, subgraph_vt in zip(graph_output_vts, flat_variable.items): + if isinstance( + orig_vt, + ( + variables.SymNodeVariable, + variables.TensorVariable, + CustomClassObjectVariable, + ), + ): + if not ( + subgraph_vt.is_tensor() + or isinstance(subgraph_vt, (SymNodeVariable, CustomClassObjectVariable)) + ): + raise AssertionError( + "Expected subgraph_vt to be a tensor, SymNodeVariable, or CustomClassObjectVariable" + ) + orig_vt.proxy = subgraph_vt.proxy + + +def _call_function_with_auto_output_flattening( + tx: "InstructionTranslatorBase", + fn: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any], + flat_example_value: Any, + body_r: VariableTracker | None, + graph_output_vts: VariableTracker | tuple[VariableTracker, ...], + config: NestedCompileRegionOptions | None = None, +) -> VariableTracker | None: + """ + Create HOP call node and reproxify output VTs for HOPs with auto output semantics. + + This function is used by HOPs with auto output semantics (see speculate_subgraph_with_auto_output_flattening) + to create the actual HOP call in the FX graph and properly handle the output variable trackers. + + The key operation is "reproxifying" - updating the proxies of the original tensor VTs + (from body_r) to point to the HOP call outputs, ensuring the outer graph correctly + references the HOP outputs while allowing body_r to contain arbitrary Python objects. + + Args: + tx: The instruction translator + fn: The HOP function to call + args: Arguments for the HOP call (typically includes the subgraph node) + kwargs: Keyword arguments for the HOP call + flat_example_value: Example value for the HOP output + body_r: The output VT structure that Dynamo continues tracing with (may be None) + graph_output_vts: Tensor/symint VTs that were actual graph outputs + + Returns: + The body_r VT (unchanged), which Dynamo will continue tracing with + """ + + flat_variable = add_call_function(tx, fn, args, kwargs, flat_example_value, config) + if body_r is not None: + # pyrefly: ignore[bad-argument-type] + overwrite_tensor_vt_proxy(graph_output_vts, flat_variable) + return body_r + + +def _call_function_and_unflatten_output( + tx: "InstructionTranslatorBase", + fn: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any], + flat_example_value: Any, + ret_spec: OutputSpec, + body_r: VariableTracker | None, +) -> VariableTracker: + from .builder import SourcelessBuilder, wrap_fx_proxy + + # Store the invocation as a call + flat_variable = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + fn, + args=args, + kwargs=kwargs, + ), + example_value=flat_example_value, + ) + + # wrap_fx_proxy creates fresh variable trackers. However, the main program + # after the speculate subgraph can still use the original tensor vts that + # are still pointing to the nodes present in the subgraph. So, we reproxify + # the original tensor vts with the subgraph outputs. This way, whenever the + # outer graph uses an original vt, it uses the subgraph output. + if body_r is not None: + # mypy: ignore[attr-defined] + for orig_vt, subgraph_vt in zip(body_r.items, flat_variable.items): + if orig_vt.is_tensor() or isinstance(orig_vt, SymNodeVariable): + if not ( + subgraph_vt.is_tensor() or isinstance(subgraph_vt, SymNodeVariable) + ): + raise AssertionError( + "Expected subgraph_vt to be a tensor or SymNodeVariable" + ) + orig_vt.proxy = subgraph_vt.proxy + + if ret_spec.num_intermediate_nodes_as_outputs: + # The treespec was computed w/o any extra intermediate outputs. At this + # point, it is safe to just get rid of the extra outputs + flat_variable = SourcelessBuilder.create( + tx, + flat_variable.items[ # mypy: ignore[attr-defined] + : -ret_spec.num_intermediate_nodes_as_outputs + ], + ) + + if ret_spec.masks_to_filter_const_values: + from torch._dynamo.external_utils import insert_const_values_with_mask + + # During flattening, we removed the constant values. To ensure Dynamo + # can trace correctly, insert back the constant values in the output. + flat_variable = _make_inlined(tx, insert_const_values_with_mask)( + flat_variable, ret_spec.masks_to_filter_const_values, ret_spec.const_values + ) + + # Transform variable back into a list (previously made into a tuple by + # speculate_subgraph function) so as to respect the pytree API typing. + flat_list_variable = SourcelessBuilder.create(tx, list).call_function( + tx, [flat_variable], {} + ) + return ( + _make_inlined(tx, pytree.tree_unflatten)(flat_list_variable, ret_spec.treespec) + if ret_spec.treespec + else flat_variable + ) + + +def _assert_tensors_nonaliasing(inputs: Any, outputs: Any) -> None: + input_tensor_ids = { + id(t) for t in pytree.tree_leaves(inputs) if isinstance(t, torch.Tensor) + } + output_tensor_ids = { + id(t) for t in pytree.tree_leaves(outputs) if isinstance(t, torch.Tensor) + } + if not input_tensor_ids.isdisjoint(output_tensor_ids): + raise AssertionError("inputs to function body cannot alias outputs") + + +def get_tensor_storages(tensor: torch.Tensor) -> set[StorageWeakRef]: + """ + Get storage references from a tensor. + + Handles regular tensors. Raises NotImplementedError for sparse tensors + and traceable wrapper subclasses. + + Args: + tensor: The tensor to extract storages from + + Returns: + Set of StorageWeakRef objects for the tensor's storage(s) + """ + from torch.multiprocessing.reductions import StorageWeakRef + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + storages: set[StorageWeakRef] = set() + + if not isinstance(tensor, torch.Tensor): + return storages + + if tensor.is_sparse or tensor.is_sparse_csr: + raise NotImplementedError("get_tensor_storages does not support sparse tensors") + + if is_traceable_wrapper_subclass(tensor): + raise NotImplementedError( + "get_tensor_storages does not support traceable wrapper subclasses" + ) + else: + storages.add(StorageWeakRef(tensor._typed_storage())) + + return storages + + +def subgraph_mutated_input_storages( + subgraph: torch.fx.Graph, mutated_input_indices: Iterable[int] +) -> set[StorageWeakRef]: + """Map subgraph placeholder indices flagged as mutated to their tensor storages. + + Used by HigherOrderVariable subclasses to translate + ``_dynamo_mutated_input_indices`` into a parent-side storage set, + which is then matched against the parent's full input list to recover + the parent-side mutated index list passed as a HOP kwarg. + """ + placeholders = [node for node in subgraph.nodes if node.op == "placeholder"] + storages: set[StorageWeakRef] = set() + for idx in mutated_input_indices: + if idx >= len(placeholders): + raise AssertionError( + f"mutated input index {idx} out of range for {len(placeholders)} placeholders" + ) + placeholder = placeholders[idx] + example_value = placeholder.meta.get( + "example_value", placeholder.meta.get("val", None) + ) + if not isinstance(example_value, torch.Tensor): + raise AssertionError("The mutated input must be a tensor") + storages |= get_tensor_storages(example_value) + return storages + + +def parent_mutated_input_indices( + parent_inputs: Sequence["VariableTracker | Proxy"], + mutated_input_storages: set[StorageWeakRef], +) -> list[int]: + """Walk a HOP's full parent-side input list and return the indices whose + tensor storage matches one of the storages mutated inside any of the + subgraphs. + + If no subgraph mutation was detected, returns the empty list without + inspecting any storages. Some inputs (e.g. BatchedTensor under vmap) + deliberately refuse storage access; we must not trip on those when + there's nothing to match against. + """ + if not mutated_input_storages: + return [] + mutated: list[int] = [] + for idx, inp in enumerate(parent_inputs): + example_value = None + if isinstance(inp, VariableTracker): + if inp.is_tensor(): + example_value = inp.as_proxy().node.meta.get("example_value", None) + else: + if not isinstance(inp, Proxy): + raise AssertionError("Expected inp to be a Proxy") + example_value = inp.node.meta.get("example_value", inp.node.meta.get("val")) + + if isinstance(example_value, torch.Tensor): + for storage in get_tensor_storages(example_value): + if storage in mutated_input_storages: + mutated.append(idx) + break + return mutated + + +class StorageAliasingTracker: + """ + Tracks storage references to detect aliasing between tensors. + + This class encapsulates the logic for collecting storages from tensors + and checking for aliasing conflicts. Used to filter intermediate outputs + that would create input-output or output-output aliasing. + """ + + def __init__(self) -> None: + self.excluded_storages: set[StorageWeakRef] = set() + + def _collect_storages_from_tensor(self, example_value: torch.Tensor) -> None: + self.excluded_storages.update(get_tensor_storages(example_value)) + + def collect_from_inputs(self, tx: "InstructionTranslatorBase") -> None: + """Collect storages from graph input placeholders.""" + from torch._higher_order_ops.utils import _collect_fake_inputs + + for node in tx.output.graph.nodes: + if node.op == "placeholder": + example_value = _collect_fake_inputs([node])[0] + if isinstance(example_value, torch.Tensor): + self._collect_storages_from_tensor(example_value) + else: + break + + def collect_from_outputs(self, graph_output_vts: list[VariableTracker]) -> None: + """Collect storages from existing graph outputs.""" + from torch._higher_order_ops.utils import _collect_fake_inputs + + for vt in graph_output_vts: + proxy = vt.as_proxy() + example_value = _collect_fake_inputs([proxy.node])[0] + if isinstance(example_value, torch.Tensor): + self._collect_storages_from_tensor(example_value) + + def check_and_track(self, proxy_node: Proxy) -> bool: + """ + Check if a tensor can be added as a subgraph output without causing aliasing issues. + + Given a proxy node, extracts its example tensor value and checks if its storage + aliases with any previously tracked storages (from inputs or other outputs). + If there's no aliasing conflict, the tensor's storage is added to the tracked set. + + Args: + proxy_node: An FX proxy node whose example_value is the tensor to check. + + Returns: + True if the tensor doesn't alias with tracked storages (safe to add as output), + False if it aliases (should be filtered out). + """ + from torch._higher_order_ops.utils import _collect_fake_inputs + from torch.multiprocessing.reductions import StorageWeakRef + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + example_value = _collect_fake_inputs([proxy_node])[0] + + # Non-tensor outputs (e.g., symints) don't have aliasing concerns + if not isinstance(example_value, torch.Tensor): + return True + + # Check if any storage aliases with existing inputs/outputs + tensor_storages = get_tensor_storages(example_value) + if tensor_storages & self.excluded_storages: + return False + + # Track this tensor's storage (for wrapper subclasses, inner storages were already checked) + if not is_traceable_wrapper_subclass(example_value): + if not (example_value.is_sparse or example_value.is_sparse_csr): + self.excluded_storages.add( + StorageWeakRef(example_value._typed_storage()) + ) + + return True + + +def taint_filtered_vt(vt: VariableTracker) -> None: + """Mark a VT as filtered due to aliasing so it raises a clear error if used.""" + original_as_proxy = vt.as_proxy + + def tainted_as_proxy() -> Any: + proxy = original_as_proxy() + raise RuntimeError( + f"An intermediate tensor '{proxy.node.name}' created inside a " + f"higher-order op subgraph aliases an input or output, so it was " + f"not included in the subgraph outputs. However, it is being used " + f"in the outer graph (e.g., via a side effect like list.append). " + f"To fix this, clone the tensor before capturing it " + f"(e.g., use tensor.clone() instead of tensor)." + ) + + vt.as_proxy = tainted_as_proxy # type: ignore[method-assign] + + +def collect_intermediate_outputs( + tx: "InstructionTranslatorBase", + subtracer: "SubgraphTracer", + graph_output_vts: list[VariableTracker], + filter_aliased_intermediates: bool = False, +) -> list[VariableTracker]: + extra_outputs = [] + existing_out_proxies = {vt.as_proxy() for vt in graph_output_vts} + + # Build the aliasing tracker if we're filtering + tracker = None + if filter_aliased_intermediates: + tracker = StorageAliasingTracker() + tracker.collect_from_inputs(tx) + tracker.collect_from_outputs(graph_output_vts) + + for out in subtracer.tracked_proxyable_vt: + proxy = out.as_proxy() + + # Skip if already in output + if proxy in existing_out_proxies: + continue + + # TODO floats are not supported in HOP input/output + if isinstance(out, SymNodeVariable) and out.python_type() is float: + continue + + if not filter_aliased_intermediates: + extra_outputs.append(out) + else: + # Filter out intermediates that alias with inputs or outputs. + # This is needed for HOPs like invoke_subgraph that don't support aliasing. + if tracker is None: + raise AssertionError( + "tracker must not be None for intermediate filtering" + ) + if tracker.check_and_track(proxy.node): + extra_outputs.append(out) + else: + taint_filtered_vt(out) + + return extra_outputs + + +def _check_all_tensorvariable(args: list[VariableTracker]) -> None: + if not all(type(a.realize()) is TensorVariable for a in args): + unimplemented( + gb_type="HOP: non torch.Tensor leaf", + context=f"args types: {[type(a.realize()) for a in args]}", + explanation="Expected all leaves to be of torch.Tensor type.", + hints=[], + ) + + +def _check_supported_callable_arg( + tx: "InstructionTranslatorBase", func_var: VariableTracker, arg_name: str +) -> None: + from .builder import SourcelessBuilder + + is_callable = ( + SourcelessBuilder.create(tx, callable) + .call_function(tx, [func_var], {}) + .as_python_constant() + ) + if not is_callable: + unimplemented( + gb_type="HOP: non-callable variable", + context=f"arg name: {arg_name}, func_var type: {str(func_var)}", + explanation=f"{arg_name} should be a callable but is of type {str(func_var)}.", + hints=[], + ) + + +def _call_while_loop( + self: Union[ + "WhileLoopHigherOrderVariable", "WhileLoopStackOutputHigherOrderVariable" + ], + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + stack_output: bool, + hop_name: str, +) -> VariableTracker: + from torch._higher_order_ops.while_loop import _create_unbacked_symint + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + cond_fn, body_fn, operands, additional_inputs = args + + # Input checks + for i, k in enumerate(["cond_fn", "body_fn", "operands"]): + if v := kwargs.pop(k, None): + if i != len(args): + raise AssertionError( + "did not provide the right number of non-keyword args" + ) + args.append(v) + + if kwargs or len(args) != 4: + unimplemented( + gb_type="torch.while_loop: improper args/kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"torch.while_loop expects 4 positional arguments (got {len(args)}) " + f"and no keyword arguments (got {len(kwargs)}) " + "Usage: while_loop(cond_fn, body_fn, operands)", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # cond_fn and body_fn input check + _check_supported_callable_arg(tx, cond_fn, "cond_fn") + _check_supported_callable_arg(tx, body_fn, "body_fn") + + # operands input check + operands_seq = unpack_iterable(tx, operands) + + # additional_inputs input check + if not isinstance(additional_inputs, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.while_loop: improper additional_inputs", + context=str(additional_inputs), + explanation=f"Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + additional_inputs_seq = unpack_iterable(tx, additional_inputs) + + with discard_graph_changes(tx): + # Note: this must be run under discard graph changes. + def unspecialize_carried_inputs( + tx: "InstructionTranslatorBase", carry: VariableTracker + ) -> VariableTracker: + # See NOTE [unspecialize int carry with unbacked symints] + if ( + carry.is_python_constant() + and isinstance(carry.as_python_constant(), int) + ) or isinstance(carry, SymNodeVariable): + example_value = _create_unbacked_symint( + tx.output.fake_mode, ignore_fresh_unbacked_symbols=True + ) + proxy = tx.output.current_tracer.create_graph_input( + "unbacked_symint", type(example_value), example_value + ) + return SymNodeVariable.create(tx, proxy, example_value) + else: + # See NOTE [unspecialize constant tensor carry] + if not carry.is_tensor(): + raise AssertionError("Expected carry to be a tensor") + cloned_carry = carry.clone() + # type: ignore[attr-defined] + cloned_carry.proxy.node.meta["example_value"].constant = None + return cloned_carry + + # clone inputs across subgraphs, to avoid unbacked memoization in fake prop + cond_operands_seq = [ + unspecialize_carried_inputs( + tx, + ( + carry.call_method(tx, "clone", args=[], kwargs={}) + if carry.is_tensor() + else carry + ), + ) + for carry in operands_seq + ] + body_operands_seq = [ + unspecialize_carried_inputs( + tx, + ( + carry.call_method(tx, "clone", args=[], kwargs={}) + if carry.is_tensor() + else carry + ), + ) + for carry in operands_seq + ] + + # create cond subgrpahs + ( + (cond_r, _cond_treespec), + cond_graph, + cond_lifted_freevars, + ) = speculate_subgraph( + tx, + cond_fn, + cond_operands_seq + additional_inputs_seq, + {}, + hop_name, + source_target=self.value, + # NOTE [why we cannot use "automatic" for while_loop]: + # The reason is that we want to enforce + # the ordering of inputs and outputs to be consistent and the ordering + # of cond_fn and body_fn to the consistent. + # e.g. suppose we use "automatic" and we have: + # + # def body_fn(ph1, ph2): + # new_a, new_b = ph2.cos(), ph1.sin() + # return new_a, new_b + # + # a, b = torch.randn(3), torch.randn(3) + # new_a, new_b = body_fn(a, b) + # + # Using automatic, the ordering of arguments will be the order that they're + # used. In this example, the capture graph looks like: + # + # def captured_body(ph1, ph2): + # new_a, new_b = ph1.cos(), ph2.add_(1) + # return new_a, new_b + # + # This is fine when we change the calling convention of captured_body to be + # new_a, new_b = captured_body(b, a). + # But for while_loop, the next iteration's input is previous iteration output + # we'll end up feeding captured_body(new_a, new_b) instead. + # So it's best we always enforce the ordering of carried_inputs the same as outputs + # with "flatten_manual". + set_subgraph_inputs="flatten_manual", + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + remove_consts_from_outputs=False, + ) + cond_nn_modules = dict(tx.output.nn_modules) + validate_subgraph_output_types(cond_r) + if cond_r.is_tensor(): + cond_r_meta = _extract_tensor_metadata( + # type: ignore[attr-defined] + cond_r.proxy.node.meta["example_value"], + include_contiguity=False, + ) + if cond_r_meta.dtype != torch.bool or cond_r_meta.shape != torch.Size([]): + unimplemented( + gb_type="torch.while_loop: unsupported cond_fn return type", + context=str(cond_r), + explanation=f"Expected cond_fn to return a scalar tensor or a bool but got {cond_r_meta.shape}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + elif cond_r.is_python_constant(): + # short-circuiting while_loop when cond_fn returns a constant such as 0, 1 True or False + pred = cond_r.as_python_constant() + if pred: + unimplemented( + gb_type="torch.while_loop: infinite loop detected", + context=str(cond_r), + explanation=f"Infinite loop detected because while_loop's cond_fn always returns the same value {pred}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + else: + return operands + + # create body subgraph + ( + (body_r, body_treespec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + body_fn, + body_operands_seq + additional_inputs_seq, + {}, + hop_name, + source_target=self.value, + set_subgraph_inputs="flatten_manual", + should_flatten_outputs=True, + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + remove_consts_from_outputs=False, + ) + validate_subgraph_output_types(body_r) + cond_mutated_inputs = set(getattr(cond_graph, "_dynamo_mutated_input_indices", ())) + body_mutated_inputs = set(getattr(body_graph, "_dynamo_mutated_input_indices", ())) + + mutated_input_storages = subgraph_mutated_input_storages( + cond_graph, cond_mutated_inputs + ) | subgraph_mutated_input_storages(body_graph, body_mutated_inputs) + + # We set include contiguity=False because we have vmap x HOP tests, where if + # include_contiguity=True will call t.is_contiguous inside of vmap and get an error + # "querying is_contiguous inside of vmap for memory_format other than + # torch.contiguous_format is not yet implemented". This is okay because stride + # is still checked. + check_meta_consistency_vt( + unpack_iterable(tx, body_r), + operands_seq, + "body_fn_output", + "carried_inputs", + include_contiguity=False, + ) + + shared, (cond_unique, body_unique) = _merge_graph_inputs( + [cond_graph, body_graph], + [cond_lifted_freevars, body_lifted_freevars], + ["cond_fn", "body_fn"], + ) + + additional_lifted_inputs = shared + cond_unique + body_unique + all_while_loop_inputs: list[VariableTracker | Proxy] = ( + list(operands_seq) + + list(additional_inputs_seq) + + list(additional_lifted_inputs) + ) + mutated_inputs = parent_mutated_input_indices( + all_while_loop_inputs, mutated_input_storages + ) + + mutated_arg_indices = ",".join(str(i) for i in mutated_inputs) + + body_nn_modules = dict(tx.output.nn_modules) + + cond_gm = torch.fx.GraphModule(cond_nn_modules, cond_graph) + body_gm = torch.fx.GraphModule(body_nn_modules, body_graph) + cond_name = tx.output.install_subgraph("cond_fn", cond_gm) + body_name = tx.output.install_subgraph("body_fn", body_gm) + + cond_node = make_attr(tx, cond_name) + body_node = make_attr(tx, body_name) + + operands_proxy = tuple(operand.as_proxy() for operand in operands_seq) + additional_inputs_proxy = tuple( + [inp.as_proxy() for inp in additional_inputs_seq] + additional_lifted_inputs + ) + p_args = ( + cond_node, + body_node, + operands_proxy, + additional_inputs_proxy, + ) + hop_kwargs = ( + {"mutated_arg_indices": mutated_arg_indices} + if not stack_output and mutated_arg_indices + else {} + ) + return _call_function_and_unflatten_output( + tx, + self.value, + p_args, + hop_kwargs, + None, + body_treespec, + body_r, + ) + + +def are_same_graph_modules( + fn_name: str, a_mod: GraphModule, b_mod: GraphModule, fake_mode: "FakeTensorMode" +) -> bool: + from torch._subclasses._fake_tensor_utils import _CacheKeyState + from torch._subclasses.fake_tensor import extract_tensor_metadata + + # Maps the equivalent nodes from a to b + # pyrefly: ignore [implicit-any] + node_map = {} + + def check_all_args(a_nodes: Iterable[Any], b_nodes: Iterable[Any]) -> bool: + for arg_a, arg_b in zip(a_nodes, b_nodes): + if isinstance(arg_a, torch.fx.Node): + if node_map[arg_a] != arg_b: + return False + elif isinstance(arg_a, slice): + if not isinstance(arg_b, slice): + return False + if not check_all_args( + (arg_a.start, arg_a.stop, arg_a.step), + (arg_b.start, arg_b.stop, arg_b.step), + ): + return False + elif arg_a != arg_b: + # This is a catch-all for everything else. `slice` was a + # surprise but can there be other data structures that can + # contain fx.Nodes in them? + return False + return True + + for a_node, b_node in zip(a_mod.graph.nodes, b_mod.graph.nodes): + if a_node.op != b_node.op: + return False + + if a_node.op == "placeholder": + a_value = a_node.meta["example_value"] + b_value = b_node.meta["example_value"] + + if isinstance(a_value, torch.Tensor): + if not isinstance(b_value, torch.Tensor): + return False + # Extract fake tensor metadata for a and b and then compare + # pyrefly: ignore [implicit-any] + a_result = [] + state = _CacheKeyState(fake_mode.shape_env) + a_metadata = extract_tensor_metadata(a_value) + a_metadata._flatten_into(a_result, fake_mode, state) + + b_result = [] + state = _CacheKeyState(fake_mode.shape_env) + b_metadata = extract_tensor_metadata(b_value) + b_metadata._flatten_into(b_result, fake_mode, state) + if a_result != b_result: + return False + elif isinstance(a_value, torch.SymInt): + if not isinstance(b_value, torch.SymInt): + return False + if a_value is not b_value: + return False + elif a_node.op == "call_function": + if a_node.target is not b_node.target: + return False + a_flat, _ = pytree.tree_flatten((a_node.args, a_node.kwargs)) + b_flat, _ = pytree.tree_flatten((b_node.args, b_node.kwargs)) + if not check_all_args(a_flat, b_flat): + hc_log.debug( + "%s: Graph comparison failed at node (call_function): %s", + fn_name, + a_node, + ) + return False + elif a_node.op == "call_method": + if a_node.target != b_node.target: + return False + a_flat, _ = pytree.tree_flatten((a_node.args, a_node.kwargs)) + b_flat, _ = pytree.tree_flatten((b_node.args, b_node.kwargs)) + if not check_all_args(a_flat, b_flat): + hc_log.debug( + "%s: Graph comparison failed at node (call_method) : %s", + fn_name, + a_node, + ) + return False + elif a_node.op == "output": + a_flat, _ = pytree.tree_flatten((a_node.args, a_node.kwargs)) + b_flat, _ = pytree.tree_flatten((b_node.args, b_node.kwargs)) + if not check_all_args(a_flat, b_flat): + hc_log.debug("%s: Graph comparison failed at the output node", fn_name) + return False + elif a_node.op == "get_attr": + a_attr = getattr(a_mod, a_node.target) + b_attr = getattr(b_mod, b_node.target) + if isinstance(a_attr, torch.fx.GraphModule): + if not isinstance(b_attr, torch.fx.GraphModule): + return False + # This is an example of a HOP inside a HOP + if not are_same_graph_modules(fn_name, a_attr, b_attr, fake_mode): + return False + else: + # TODO - write an example with tensor as a graph attribute in + # the Fx graph + raise NotImplementedError(f"get_attr with {type(a_attr)}") + else: + # TODO - call_module is not supported because Dynamo Fx graph does + # not install a call_module + raise NotImplementedError(f"Graph equivalence check saw a {a_node.op}") + + # Two nodes are equal - add them to them map + node_map[a_node] = b_node + + return True + + +def validate_args_and_maybe_create_graph_inputs( + sub_args: list[VariableTracker], + tracer: "SubgraphTracer", + tx: "InstructionTranslatorBase", + set_subgraph_inputs: SetSubgraphInputs, + description: str, + sub_args_names: Sequence[str] | None = None, +) -> list[Any]: + from . import AutogradFunctionContextVariable + from .builder import SourcelessBuilder, wrap_fx_proxy_cls + + if tracer.parent is None: + raise AssertionError("tracer.parent must not be None") + + if set_subgraph_inputs == "flatten_manual": + flat_args, tree_spec = unpack_iterable( + tx, + _make_inlined(tx, pytree.tree_flatten)( + SourcelessBuilder.create(tx, sub_args) + ), + ) + + flat_inputs = validate_args_and_maybe_create_graph_inputs( + unpack_iterable(tx, flat_args), + tracer, + tx, + set_subgraph_inputs="manual", + description=description, + ) + + return unpack_iterable( + tx, + _make_inlined(tx, pytree.tree_unflatten)( + SourcelessBuilder.create(tx, list(flat_inputs)), tree_spec + ), + ) + else: + if sub_args_names is not None: + # Can be greater if user passes some args as kwargs + if len(sub_args_names) < len(sub_args): + raise AssertionError( + "sub_args_names must have at least as many entries as sub_args" + ) + args = [] + for idx, a in enumerate(sub_args): + if not isinstance(a, VariableTracker): + raise AssertionError("Expected each sub_arg to be a VariableTracker") + new_arg = None + if set_subgraph_inputs == "automatic": + args.append(a) + continue + elif set_subgraph_inputs == "automatic_with_forced_inputs": + if isinstance(a, LazyVariableTracker): + a = a.realize() + if isinstance(a, variables.TensorVariable): + node = a.maybe_fx_node() + if node is None: + raise AssertionError( + "Expected TensorVariable to have an fx node" + ) + example_value = node.meta["example_value"] + arg_name = ( + a.as_proxy().node.name + if sub_args_names is None + else sub_args_names[idx] + ) + new_proxy = tracer.create_graph_input( + arg_name, a.python_type(), example_value + ) + example_value = node.meta.get("example_value", None) + a = wrap_fx_proxy_cls( + target_cls=type(a), + tx=tx, + proxy=new_proxy, + example_value=example_value, + ) + args.append(a) + continue + + if a.is_python_constant(): + # This arg is not used in the body of the higher order op. + # Currently, this new input is added to make the calls + # happy, which expect a fixed number of arguments. In + # future, we can clean this up. + arg_name = ( + "const_unused" + if sub_args_names is None + else f"const_unused_{sub_args_names[idx]}" + ) + tracer.create_graph_input( + arg_name, a.python_type(), a.as_python_constant() + ) + new_arg = a + # Weird special case, we probably want to delete it or fold it + # into the next case (of `a` being placeable into a graph) + elif isinstance(a, AutogradFunctionContextVariable): + example_value = a.as_proxy().node.meta["example_value"] + arg_name = ( + a.as_proxy().node.name + if sub_args_names is None + else sub_args_names[idx] + ) + tracer.create_graph_input(arg_name, a.python_type(), example_value) + new_arg = a + # If `a` can be put into a graph + elif a.maybe_fx_node() is not None: + node = a.maybe_fx_node() + if node is None: + raise AssertionError( + "Expected a non-None fx node after maybe_fx_node() check" + ) + example_value = node.meta.get("example_value", None) + arg_name = node.name if sub_args_names is None else sub_args_names[idx] + new_proxy = tracer.create_graph_input( + arg_name, a.python_type(), example_value + ) + new_arg = wrap_fx_proxy_cls( + target_cls=type(a), + tx=tx, + proxy=new_proxy, + example_value=example_value, + ) + # If `a` cannot be put into a graph + else: + # HOPs work much better if they use speculate_subgraph(set_subgraph_inputs="automatic"). + unimplemented( + gb_type="HOP body taking non-Tensor as input", + context=str(sub_args), + explanation=f"{description} with body that accepts non-Tensors as input. " + f"Got type {a.python_type()} at index {idx}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + args.append(new_arg) + return args + + +# N-branch generalization of former _merge_graph_inputs. Used by torch.cond (2 branches) +# and torch.switch (N branches): both must produce subgraphs with a unified +# placeholder signature so the higher order op can pass a single operand list. +# +# Returns (shared, unique_per_branch): +# * shared: proxies present in every branch's lifted freevars. For plain +# proxies, "present" means by identity. For get_attr proxies, "present" +# means by node target (branches in separate tracing contexts can produce +# distinct proxies for the same nn module attr); the proxy from the first +# branch is chosen as the canonical representative. +# * unique_per_branch[i]: proxies lifted by branch i, not shared, and not +# already assigned to an earlier branch's unique block. With N > 2 a +# freevar can be lifted by some but not all branches; the first such branch +# claims it, and later branches that also lift it reuse the same placeholder. +# For N == 2 any non-shared freevar is lifted by exactly one branch -> no-op. +# Each block is sorted by node name for determinism. +# +# Side effect: each graph is rewritten in-place so its placeholders follow the +# 1 + N block layout: shared block (no suffix), then one block per branch +# (suffixed with "_") holding that branch's unique freevars. A +# branch graph wires its inner uses to whichever block holds the placeholder +# for the freevar it lifted (its own block, or the earlier branch that +# claimed it); the remaining blocks become unused placeholders for signature +# alignment. +def _merge_graph_inputs( + graphs: list[torch.fx.Graph], + lifted_freevars: list[dict[Proxy, Proxy]], + names: list[str], +) -> tuple[list[Proxy], list[list[Proxy]]]: + n = len(graphs) + if n != len(lifted_freevars) or n != len(names): + raise AssertionError( + "Expected graphs, lifted_freevars and names to have the same length" + ) + if n == 0: + raise AssertionError("Expected at least one graph") + + # Step 1: pick a canonical proxy for every distinct outer freevar across + # branches, deduplicating get_attrs that share a target. A canonical proxy + # is shared iff every branch contributed to it. + get_attr_canonical: dict[Any, Proxy] = {} + per_branch_outer_to_canonical: list[dict[Proxy, Proxy]] = [] + canonical_branch_count: Counter[Proxy] = Counter() + for branch_lifted in lifted_freevars: + outer_to_canonical: dict[Proxy, Proxy] = {} + for outer in branch_lifted: + canonical = outer + if outer.node.op == "get_attr": + target = outer.node.target + canonical = get_attr_canonical.setdefault(target, outer) + outer_to_canonical[outer] = canonical + per_branch_outer_to_canonical.append(outer_to_canonical) + canonical_branch_count.update(set(outer_to_canonical.values())) + + shared_canonical = {c for c, count in canonical_branch_count.items() if count == n} + + # Step 2: derive the shared block and the per-branch unique blocks. Plain + # proxies are the same object across branches, so a single canonical entry + # covers all of them; for shared get_attrs the canonical is the branch-0 + # proxy. A non-shared canonical lifted by multiple branches is assigned + # to the first branch that lifted it. + def _sort_by_name(vars: Iterable[Proxy]) -> list[Proxy]: + return sorted(vars, key=lambda var: var.node.name) + + shared = _sort_by_name(shared_canonical) + claimed_canonical: set[Proxy] = set(shared_canonical) + unique_per_branch: list[list[Proxy]] = [] + for outer_to_canonical in per_branch_outer_to_canonical: + branch_unique = [] + for outer, canonical in outer_to_canonical.items(): + if canonical in claimed_canonical: + continue + branch_unique.append(outer) + claimed_canonical.add(canonical) + unique_per_branch.append(_sort_by_name(branch_unique)) + + # For N branches the merged signature has 1 + N blocks: shared (no suffix) + # then one suffixed block per branch. Within each block proxies are + # ordered by node name for determinism. + def fixup_branch_inps( + graph: torch.fx.Graph, + branch_lifted: dict[Proxy, Proxy], + outer_to_canonical: dict[Proxy, Proxy], + ) -> None: + # Reverse-map canonical -> this branch's outer proxy so we can find the + # old placeholder to replace when emitting the shared block. + canonical_to_branch_outer = {c: o for o, c in outer_to_canonical.items()} + + def _insert_or_replace_phs(new_args: Sequence[Proxy], name_suffix: str) -> None: + for arg in new_args: + new_ph = graph.placeholder(arg.node.name + name_suffix) + new_ph.meta = arg.node.meta + # If this branch lifted `arg` (directly or via a shared + # get_attr target), wire the new placeholder to the existing + # uses and erase the old placeholder. + local_outer = canonical_to_branch_outer.get(arg, arg) + if local_outer in branch_lifted: + old_ph = branch_lifted[local_outer].node + old_ph.replace_all_uses_with(new_ph) + # replace_all_uses_with doesn't clean users. Clean it manually so that we could erase it. + old_ph.users = {} + graph.erase_node(old_ph) + + first_not_ph_node = next( + node for node in graph.nodes if node.op != "placeholder" + ) + with graph.inserting_before(first_not_ph_node): + _insert_or_replace_phs(shared, "") + for other_name, other_unique in zip(names, unique_per_branch): + _insert_or_replace_phs(other_unique, "_" + other_name) + + for graph, branch_lifted, outer_to_canonical in zip( + graphs, lifted_freevars, per_branch_outer_to_canonical + ): + fixup_branch_inps(graph, branch_lifted, outer_to_canonical) + + return shared, unique_per_branch + + +# NOTE: [HigherOrderOperator subgraph input ordering] +# The input ordering of the higher order ops is determined by the order of +# the creation of the placeholder. +# Manually created inputs are created in validate_args_and_maybe_create_graph_inputs before +# speculating subgraph. +# During subgraph speculation, we may lift closured tensors and free symbols as inputs, +# their ordering is determined by the time they are lifted: earlier lifted ones precede later +# lifted ones. +# +# Suppose the placeholders are +# O1, O2, X1, O3, O4, X2, X3, O5 where Xs are lifted phs +# The following code re-order the placeholders to +# O1, O2, O3, O4, O5, X1, X2, X3 +def move_lifted_freevars_phs_to_end( + graph: torch.fx.Graph, lifted_freevars: dict[Proxy, Proxy] +) -> None: + lifted_ph_set = {child_p.node for child_p in lifted_freevars.values()} + + prev_phs = [n for n in graph.nodes if n.op == "placeholder"] + + # No need to reorder when graph doesn't have args or doesn't + # have lifted freevars or all inputs are lifted freevars. + if ( + len(prev_phs) == 0 + or len(lifted_ph_set) == 0 + or len(prev_phs) == len(lifted_ph_set) + ): + return + + # Step 1: find first X1 + for x1 in prev_phs: + if x1 in lifted_ph_set: + break + + if x1 is None: + raise AssertionError("x1 must not be None") + if x1.op != "placeholder": + raise AssertionError("x1.op must be 'placeholder'") + # Step 2: starting from the X1, skip Xs and prepend Os before X1. + cand_x = x1.next + while cand_x is not None and cand_x.op == "placeholder": + if cand_x in lifted_ph_set: + cand_x = cand_x.next + else: + nxt = cand_x.next + cand_x._remove_from_list() + x1.prepend(cand_x) + cand_x = nxt + + # Step 3: assert that all placeholders are in the correct order as . + # in lifted_freevars + after_phs = [node for node in graph.nodes if node.op == "placeholder"][ + -len(lifted_freevars) : + ] + if len(after_phs) != len(lifted_freevars): + raise AssertionError( + "Number of trailing placeholders must match number of lifted_freevars" + ) + for child_proxy, ph in zip(lifted_freevars.values(), after_phs): + if child_proxy.node is not ph: + raise AssertionError( + "The order of placeholders is different from the order of lifted_freevars" + ) + + graph.lint() + + +def check_aliasing_and_input_mutation( + subtracer: "SubgraphTracer", + graph: torch.fx.Graph, + supports_input_mutation: bool, + supports_aliasing: bool, + source_target: Optional["HigherOrderOperator"], +) -> None: + name = source_target.name if source_target else "" + if not supports_input_mutation: + mutation_info = subtracer.has_input_mutation() + if mutation_info.has_mutation: + context = f"{mutation_info.msg} in\n {graph}" + unimplemented( + gb_type="Encountered input mutation during higher order op tracing", + context=context, + explanation=f"Higher order ops do not support input mutation. Found in {name}", + hints=[ + "Consider using the debug context to change user code to avoid mutation.", + "Please open an issue.", + ], + ) + + if not supports_aliasing: + aliasing_info = subtracer.has_aliasing() + if aliasing_info.has_aliasing: + context = f"{aliasing_info.msg} in\n {graph}" + unimplemented( + gb_type="Encountered aliasing during higher order op tracing", + context=context, + explanation=f"Higher order ops do not support aliasing. Found in {name}", + hints=[ + "Replace `return input` with `return input.clone()` to avoid aliasing.", + "Consider using the debug context to change user code to avoid aliasing.", + "Please open an issue.", + ], + ) + + +def trace_hop_function( + f: VariableTracker, + tx: "InstructionTranslatorBase", + subtracer: "SubgraphTracer", + enable_grad: bool | None, + restore_side_effects: bool, + args: list[VariableTracker], + sub_kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # For autograd.Function and other legacy HOPs, we do NOT couple + # restore_side_effects with allow_side_effects_in_hop. + # This preserves the old behavior where: + # - restore_side_effects=False means ctx mutations persist + # - But non-ctx side effects still cause graph breaks (under_activation_checkpoint was False) + enable_side_effects_with_extra_outputs = False + + autograd_ctx = ( + dynamo_enable_grad(tx, enable_grad) + if enable_grad is not None + else contextlib.nullcontext() + ) + side_effects_ctx = ( + dynamo_allow_side_effects_in_hop(tx) + if enable_side_effects_with_extra_outputs + else contextlib.nullcontext() + ) + + # For handling side effects, we can make an argument that we don't + # have to do anything here. The side effects infra does a good job + # of graph breaking if we mutate any nonlocal or global variable + # while subtracing. As a result if tracing succeeds, side effects + # data structure will only contain read-only data structures that + # are put there for tracking purposes. + # But on the other hand, there is an argument that if we ever write + # a new side effect in Dynamo which does not go through the side + # effect infra, we can end up in bad state. + # Therefore we restore the side effects after tracing. The catch is + # that we have to special handle tensor variables. If we have seen a + # nonlocal variable tensor during subtracing, we want to keep a + # track of that tensor, so that later subtracing or the root tracer + # itself does not create a new proxy for the already observed tensor + # variable. + prev_side_effects = None + if restore_side_effects: + prev_side_effects = tx.output.side_effects.clone() + + # When restoring side effects, defer outer-scope mutation checks so + # context managers that flip-flop a flag don't fail immediately. After + # tracing, we validate that all deferred mutations were nullified. + deferred_ctx = ( + tx.output.side_effects.defer_side_effect_checks() + if restore_side_effects + else contextlib.nullcontext() + ) + + with autograd_ctx, side_effects_ctx, deferred_ctx: + output = f.call_function(tx, args, sub_kwargs) + + if restore_side_effects: + new_side_effects = tx.output.side_effects.clone() + if prev_side_effects is None: + raise AssertionError( + "prev_side_effects must not be None when restoring side effects" + ) + prev_side_effects.track_runahead_tensor_and_symvar_side_effects( + new_side_effects + ) + tx.output.side_effects = prev_side_effects + return output + + +def trace_hop_function_with_auto_output_flattening( + f: VariableTracker, + tx: "InstructionTranslatorBase", + subtracer: "SubgraphTracer", + enable_grad: bool | None, + allow_side_effects: bool, + args: list[VariableTracker], + sub_kwargs: dict[str, VariableTracker], +) -> VariableTracker: + autograd_ctx = ( + dynamo_enable_grad(tx, enable_grad) + if enable_grad is not None + else contextlib.nullcontext() + ) + side_effects_ctx = ( + dynamo_allow_side_effects_in_hop(tx) + if allow_side_effects + else contextlib.nullcontext() + ) + + deferred_ctx = ( + tx.output.side_effects.defer_side_effect_checks() + if not allow_side_effects + else contextlib.nullcontext() + ) + + with autograd_ctx, side_effects_ctx, deferred_ctx: + output = f.call_function(tx, args, sub_kwargs) + + return output + + +def get_hop_args( + tx: "InstructionTranslatorBase", + f: VariableTracker, + subtracer: "SubgraphTracer", + sub_args: list[VariableTracker], + sub_kwargs: dict[str, VariableTracker], + set_subgraph_inputs: SetSubgraphInputs, + description: str, +) -> list[VariableTracker]: + sub_args_names = maybe_positional_arg_names(f) + # User mismatch in the number of args. Will eventually lead to an error. + if sub_args_names is not None and len(sub_args_names) < len(sub_args): + sub_args_names = None + args = validate_args_and_maybe_create_graph_inputs( + sub_args, + subtracer, + tx, + set_subgraph_inputs, + description, + sub_args_names, + ) + + validate_args_and_maybe_create_graph_inputs( + sub_kwargs.values(), # type: ignore[arg-type] + subtracer, + tx, + set_subgraph_inputs="automatic", + description=description, + ) + return args + + +# TODO - The eventual goal is to replace +# speculate_subgraph_with_auto_output_flattening with speculate_subgraph or +# merge them two into one. We are following a staged approach because of +# existing implementation complexity for control flow ops. +def speculate_subgraph_with_auto_output_flattening( + tx: "InstructionTranslatorBase", + f: VariableTracker, + sub_args: list[VariableTracker], + sub_kwargs: dict[str, VariableTracker] | None, + description: str, + *, + # source_target is the .value of HigherOrderOpVariable and is the + # target of the proxy that we created for the higherOrderOperator. + source_target: HigherOrderOperator | None = None, + enable_grad: bool | None = None, + # automatic: relies on Dynamo to find the used tensors and lift them as + # inputs. + # + # automatic_with_forced_inputs: relies on the function arg names to create + # a new proxy. Also, it will always INSERT a tensor placeholder as input, + # even though it might not be used in the graph and they will also be in the + # same order as the original function (as opposed to automatic which will + # not insert the unused placeholder and can insert other placeholders in the + # order they are see while tracing). This is useful for autograd.Function + # backward where we do need to account for all the inputs of the backwards + # to be lifted as inputs for making the fwd-bwd graph consistent. + set_subgraph_inputs: SetSubgraphInputs = "automatic", + # If True, exposes intermediates to subgraph outputs to allow later tensor ops to + # access intermediates from the subgraph, this is useful for mutation + allow_side_effects: bool = False, + # Controls whether to filter aliased intermediates when collecting extra outputs. + # This is only relevant when allow_side_effects=True. + # - True: Filter out intermediates that alias with inputs or outputs (strict, for invoke_subgraph) + # - False: Allow aliased intermediates (for checkpoint/autograd.Function which get desugared/inlined) + # + # Example where filtering is needed: + # + # @invoke_subgraph + # def gn(x): + # view = x.view(2, 4) # intermediate that aliases input x + # y = torch.sin(view) + # return torch.cos(view) + # + # def fn(x): + # res = gn(x) + # return res + 4 + # + # In this case, if we don't filter `view`, we would later error because some HOPs + # have strict aliasing checks on inputs/outputs. + # + # This does however introduce a subtle issue when we do something like: + # + # captured = [] + # + # @invoke_subgraph + # def gn(x): + # view = x.view(2, 4) # intermediate that aliases input x + # y = torch.sin(view) + # captured.append(view) + # return torch.cos(view) + # + # def fn(x): + # res = gn(x) + # return res + captured[0] + # + # In this case, we will not replay the side effect on `captured` in the graph, + # which fails with a not-so-nice error. We will address this in a follow-up PR + # because this case is rare. This is not a regression because side effects were + # never supported for invoke_subgraph anyway. + filter_aliased_intermediates: bool = False, + # TODO - supports input_mutation and aliasing should be False by default for strictness + supports_input_mutation: bool = True, + supports_aliasing: bool = True, + # Pass in an originating tracer - this is needed for preserving context + # across fwd-bwd for autograd.Function + tracer: Optional["SubgraphTracer"] = None, +) -> tuple[ + VariableTracker, # output: The VT that Dynamo continues tracing with + torch.fx.Graph, # graph: The FX graph representing the subgraph computation + dict[ + torch.fx.Proxy, torch.fx.Proxy + ], # lifted_freevars: Free variables lifted as inputs + VariableTracker + | tuple[ + VariableTracker, ... + ], # graph_output_vts: Tensor/symint VTs that are actual FX graph outputs + SubgraphTracingInfo, # tracing_info: Properties observed during subgraph tracing +]: + """ + Speculate subgraph for Higher-Order Operators (HOPs) with automatic output flattening. + + ## Automatic output flattening + + For many HOPs, the representation exists only as a container for the + subgraph. In later compiler stages or at runtime, the HOP is desugared and + simply executes the subgraph directly, as if it were inlined. For such hops, + we follow automatic output flattening. + For example: + - invoke_subgraph + - activation checkpointing (torch.utils.checkpoint.checkpoint) + - autograd.Function + - nested_compile_region + + This is in contrast to control flow HOPs which do not follow this desugaring: + - torch.cond (conditional execution based on predicate) + - torch.while_loop (iterative execution) + - torch.map (parallel execution over batch dimension) + + For control flow HOPs, the HOP behavior is fundamentally different from just + running the body function once. + + ## Key Advantage: Disentangling VTs from Graph Outputs + + Desugaring simplify HOP processing by allowing us to disentangle the output + variable trackers (VTs) from the HOP subgraph outputs. This mirrors typical + Dynamo processing where: + - VTs "run ahead" representing the program state for continued tracing + - The graph is a side data structure tracking computation seen so far + + This separation is crucial for HOPs with non-proxyable outputs (e.g., custom + user-defined objects containing tensors). The function may return complex Python + objects for Dynamo to continue tracing, but only the tensor/symint VTs need to + be registered as actual FX graph outputs. + + Example: + class Foo: + def __init__(self, a, b): + self.a = a # tensor + self.b = b # tensor + + def gn(x): + return Foo(torch.sin(x), torch.cos(x)) + + result = some_hop(gn, x) # Returns Foo instance + out = result.a + result.b # Dynamo can continue tracing + + Here, `output` VT is a UserDefinedObjectVariable wrapping Foo, but + `graph_output_vts` contains only the tensor VTs (a and b) that should be + actual FX graph outputs. This allows Dynamo to continue tracing with the + Foo object while the graph only needs to output the constituent tensors. + + ## Return Values + + Unlike `speculate_subgraph`, this function returns: + - output: The VT that Dynamo continues tracing with (may be complex Python objects) + - graph: The FX graph representing the subgraph computation + - lifted_freevars: Free variables lifted as inputs to the subgraph + - graph_output_vts: Only the tensor/symint VTs that are actual FX graph outputs + + The key difference is `graph_output_vts` instead of `treespec`, which gives more + flexibility for handling non-proxyable outputs. + """ + if sub_kwargs is None: + sub_kwargs = {} + + if set_subgraph_inputs not in get_args(SetSubgraphInputs): + raise AssertionError( + "Please use one of the supported set_subgraph_inputs options." + ) + + # See NOTE [Temporary argument `set_subgraph_inputs`] + if sub_kwargs and set_subgraph_inputs != "automatic": + unimplemented( + gb_type="invalid set_subgraph_inputs and sub_kwargs settings", + context=f"set_subgraph_inputs: {set_subgraph_inputs}, sub_kwargs: {sub_kwargs}", + explanation="`sub_kwargs` cannot be used when `set_subgraph_inputs` is not set to 'automatic'.", + hints=[ + "Use `set_subgraph_inputs='automatic'` when passing `sub_kwargs`.", + *graph_break_hints.USER_ERROR, + ], + ) + + try: + with tx.output.subtracer(source_target, tracer, description) as subtracer: + args = get_hop_args( + tx, + f, + subtracer, + list(sub_args), + sub_kwargs, + set_subgraph_inputs, + description, + ) + + # Special case - if users uses + # `traced_with_externally_visible_side_effects`, we still need to + # return the intermediates as outputs. However, this API gets + # triggered during the hop tracing, and we don't know at this point + # of time, if the API will take into effect. To handle this, we have + # a flag traced_with_externally_visible_side_effects (default=False) + # that is set to True anytime + # `traced_with_externally_visible_side_effects` is set. We reset it + # with the old value after the hop is traced out. + old_value = ( + tx.output.current_tracer.traced_with_externally_visible_side_effects + ) + + output = trace_hop_function_with_auto_output_flattening( + f, + tx, + subtracer, + enable_grad, + allow_side_effects, + args, + sub_kwargs, + ) + + # NOTE: [Separation of graph outputs and output VTs] + # In Dynamo (outside of speculate_subgraph), VTs and the graph are + # separate concepts: + # - VTs (VariableTrackers) can "run ahead" and continue Dynamo tracing + # - The graph is just a side data structure tracking computation seen so far + # + # This separation is crucial for HOPs with non-proxyable outputs (e.g., + # custom user-defined objects containing tensors). The function may return + # complex Python objects for Dynamo to continue tracing, but only the + # tensor/symint VTs need to be registered as actual graph outputs. + # + # Example: + # class Foo: + # def __init__(self, a, b): + # self.a = a # tensor + # self.b = b # tensor + # + # def gn(x): + # return Foo(torch.sin(x), torch.cos(x)) + # + # Here, `output` VT is a UserDefinedObjectVariable wrapping Foo, but + # `graph_output_vts` contains only the tensor VTs (a and b) that should + # be actual FX graph outputs. + # Collect only tensor and symint VTs that should be graph outputs. + # We walk the output structure and extract proxyable VTs. + graph_output_vts: list[VariableTracker] = [] + + def visit(vt: VariableTracker) -> None: + if vt.is_tensor() or isinstance( + vt, (SymNodeVariable, CustomClassObjectVariable) + ): + graph_output_vts.append(vt) + + VariableTracker.visit(visit, output, side_effects=tx.output.side_effects) + + # NOTE - [Return subgraph intermediates as subgraph outputs] + # This helps HOPs which allow side effects. Consider the + # following example + # + # def gn(x, z): + # o = torch.matmul(x, x) @ x + # out = x.sin() + # z.append(out) + # return torch.cos(torch.sin(o)) + + # def fn(x): + # z = [] + # out1 = torch.utils.checkpoint.checkpoint( + # gn, + # x, + # z, + # use_reentrant=False, + # ) + # return out1, z[0] + # + # In this example, list `z` is in outer scope and gets appended + # in the subgraph with `out`. But `out` is not an output of the + # subgraph. This can cause issue because later on when the outer + # graph returns `z[0]` it needs to have access to the graph node + # `out`. To solve this problem, we just return all intermediates + # from the subgraph. + + # TODO - Today this is supported only for AC. AC HOP gets + # desugared in AOTDispatcher so even though subgraph has extra + # unused outputs in Dynamo, its ok even if we don't DCE them in + # Dynamo. As AOTDispatcher desugars/inlines the subgraph, the + # subgraph boundary disappears. And even for AC, today this only + # works when the skip_fwd_side_effects_in_bwd_under_checkpoint + # flag is True, i.e., only when we allow side-effects. But, we + # want this to be supported for other Hops as well, specifically + # nested_compile_region and autograd.Function. Today, its safe + # because we error out on seeing a side-effect. + + traced_externally = ( + tx.output.current_tracer.traced_with_externally_visible_side_effects + ) + has_side_effects = ( + subtracer.side_effect_stack is not None or traced_externally + ) + if (allow_side_effects or traced_externally) and has_side_effects: + extra_outputs = collect_intermediate_outputs( + tx, subtracer, graph_output_vts, filter_aliased_intermediates + ) + graph_output_vts = graph_output_vts + extra_outputs + + tx.output.current_tracer.traced_with_externally_visible_side_effects = ( + old_value + ) + + validate_subgraph_output_types(graph_output_vts) + + # The output proxies might not belong to this SubgraphTracer + # (if they are free variables that were never lifted) + # so lift them here. + # output_proxies = output.as_proxy() + if isinstance(graph_output_vts, list): + output_proxies = [a.as_proxy() for a in graph_output_vts] # type: ignore[attr-defined] + output_proxies = pytree.tree_map( + subtracer.maybe_lift_tracked_freevar_to_input, output_proxies + ) + output_proxies = tuple(output_proxies) + else: + output_proxies = output.as_proxy() + output_proxies = pytree.tree_map( + subtracer.maybe_lift_tracked_freevar_to_input, output_proxies + ) + + tx.output.create_node( + "output", + "output", + (subtracer.create_arg((output_proxies,))), + {}, + ) + graph = tx.output.graph + graph.lint() + lifted_freevars = subtracer.lifted_freevars + + if len(lifted_freevars) > 0: + move_lifted_freevars_phs_to_end(graph, lifted_freevars) + + check_aliasing_and_input_mutation( + subtracer, + graph, + supports_input_mutation, + supports_aliasing, + source_target, + ) + # Return both the output VT and the graph output VTs separately: + # - `output`: The VT that Dynamo continues tracing with (may be + # complex Python objects, tuples, dicts, etc.) + # - `graph`: The FX graph representing the subgraph computation + # - `lifted_freevars`: Free variables lifted as inputs to the subgraph + # - `graph_output_vts`: Only the tensor/symint VTs that are actual + # FX graph outputs (basically the vts associated with graph outputs) + # - `tracing_info`: Properties observed during subgraph tracing + tracing_info = SubgraphTracingInfo( + side_effect_stack=subtracer.side_effect_stack, + traced_sources=subtracer.traced_sources, + ) + + return ( + output, + graph, + lifted_freevars, + tuple(graph_output_vts), + tracing_info, + ) + except Unsupported as ex: + f_name = f"{type(f).__name__}" + if isinstance(f, UserFunctionVariable): + f_name = f.get_name() + msg = ( + f"speculate_subgraph: while introspecting {description}, we were unable " + f"to trace function `{f_name}` into a single graph. This means " + f"that Dynamo was unable to prove safety for this API and will " + f"fall back to eager-mode PyTorch, which could lead to a slowdown." + ) + log.info(msg) + log.info(ex) + raise ex + + +# See NOTE [HigherOrderOperator tracing design] for details of the design +def speculate_subgraph( + tx: "InstructionTranslatorBase", + f: VariableTracker, + sub_args: list[VariableTracker], + sub_kwargs: dict[str, VariableTracker] | None, + description: str, + *, + # source_target is the .value of HigherOrderOpVariable and is the + # target of the proxy that we created for the higherOrderOperator. + source_target: HigherOrderOperator | None = None, + always_restore: bool = False, + enable_grad: bool | None = None, + # NOTE [argument `set_subgraph_inputs`] + # set_subgraph_inputs controls what how to construct subgraphs' placeholders from sub_args. + # 1. if your HOP supports arbitrary inputs, use set_subgraph_inputs="automatic" (most recommended). + # 2. if your HOP supports only Tensor and symnode inputs, use set_subgraph_inputs="flatten_manual" (recommended). + # If sub_args contain Pytree structure (e.g. dict/list/tuple/set), the sub_args will be flattened first. + # Then the flattened args are manually set as subgraph's placeholders. + # 3. if your HOP must preserve inputs that are not tensor or symnode as placeholders e.g. AutogradFunctionContextVariable + # use set_subgraph_inputs="manual" (not recommended). We do not recommend it in general because it has the + # restriction that user need to manually control how to create placeholders and VariableTrackers for the args. + set_subgraph_inputs: SetSubgraphInputs = "automatic", + restore_side_effects: bool = True, + should_flatten_outputs: bool = False, + # if should_flatten_outputs is True, `remove_consts_from_outputs` remove the + # const outputs from the subgraph output. + remove_consts_from_outputs: bool = True, + # TODO - supports input_mutation and aliasing should be False by default for strictness + supports_input_mutation: bool = True, + supports_aliasing: bool = True, + # Pass in an originating tracer - this is needed for preserving context + # across fwd-bwd for autograd.Function + tracer: Optional["SubgraphTracer"] = None, +) -> tuple[tuple[VariableTracker, OutputSpec], torch.fx.Graph, dict[Proxy, Proxy]]: + if sub_kwargs is None: + sub_kwargs = {} + + from .builder import SourcelessBuilder + + if set_subgraph_inputs not in get_args(SetSubgraphInputs): + raise AssertionError( + "Please use one of the supported set_subgraph_inputs options." + ) + + # See NOTE [Temporary argument `set_subgraph_inputs`] + if sub_kwargs and set_subgraph_inputs != "automatic": + unimplemented( + gb_type="invalid set_subgraph_inputs and sub_kwargs settings", + context=f"set_subgraph_inputs: {set_subgraph_inputs}, sub_kwargs: {sub_kwargs}", + explanation="`sub_kwargs` cannot be used when `set_subgraph_inputs` is not set to 'automatic'.", + hints=[ + "Use `set_subgraph_inputs='automatic'` when passing `sub_kwargs`.", + *graph_break_hints.USER_ERROR, + ], + ) + + try: + # ensure guards on args get installed in parent subgraph + f, sub_args, sub_kwargs = LazyVariableTracker.realize_all( + (f, sub_args, sub_kwargs), + ) + + with tx.output.subtracer(source_target, tracer, description) as subtracer: + args = get_hop_args( + tx, f, subtracer, sub_args, sub_kwargs, set_subgraph_inputs, description + ) + + output = trace_hop_function( + f, + tx, + subtracer, + enable_grad, + restore_side_effects, + args, + sub_kwargs, + ) + + treespec = None + masks_to_filter_const_values = None + const_values = None + if should_flatten_outputs: + from torch._dynamo.external_utils import filter_out_const_values + + # Flatten the speculated subgraph output. + output, treespec = unpack_iterable( + tx, _make_inlined(tx, pytree.tree_flatten)(output) + ) + + # Actually, transform the list (returned by flatten) into a tuple + # for dynamo consistency. + output = SourcelessBuilder.create(tx, tuple).call_function( + tx, [output], {} + ) + + if remove_consts_from_outputs: + # Filter out the constants and save them into a spec. Filtering + # out constants makes the graph simpler for the backends. We + # need to ensure that after unflattening the constants are + # inserted back at the right positions for the Dynamo tracing to + # continue. This is done by filter_const_spec + output_proxies = output.as_proxy() + masks_to_filter_const_values = pytree.tree_map( + lambda x: not isinstance(x, torch.fx.Proxy), output_proxies + ) + const_values = pytree.tree_map( + lambda x: None if isinstance(x, torch.fx.Proxy) else x, + output_proxies, + ) + output = _make_inlined(tx, filter_out_const_values)( + output, masks_to_filter_const_values + ) + + # TODO - clean up num_intermediate_nodes_as_outputs - we do not need + # after AC moved to auto_output_flattening + num_intermediate_nodes_as_outputs = 0 + # Register output to graph + # Modeled off of compile_and_call_fx_graph + # TODO: support pytree output + # We check always_restore because we don't use the output or side effects of always_restore code, + # like bwd. + if always_restore: + # Nothing left to do here + return ( + ( + output, + OutputSpec( + treespec, # type: ignore[arg-type] + masks_to_filter_const_values, + const_values, + num_intermediate_nodes_as_outputs, + ), + ), + tx.output.graph, + subtracer.lifted_freevars, + ) + else: + validate_subgraph_output_types(output) + + # The output proxies might not belong to this SubgraphTracer + # (if they are free variables that were never lifted) + # so lift them here. + output_proxies = output.as_proxy() + output_proxies = pytree.tree_map( + subtracer.maybe_lift_tracked_freevar_to_input, output_proxies + ) + + tx.output.create_node( + "output", + "output", + (subtracer.create_arg((output_proxies,))), + {}, + ) + graph = tx.output.graph + graph.lint() + lifted_freevars = subtracer.lifted_freevars + + if len(lifted_freevars) > 0: + move_lifted_freevars_phs_to_end(graph, lifted_freevars) + check_aliasing_and_input_mutation( + subtracer, + graph, + supports_input_mutation, + supports_aliasing, + source_target, + ) + mutation_info = subtracer.has_input_mutation() + graph._dynamo_mutated_input_indices = ( # pyrefly: ignore[missing-attribute] + mutation_info.mutated_input_indices + ) + + return ( + ( + output, + OutputSpec( + treespec, # type: ignore[arg-type] + masks_to_filter_const_values, + const_values, + num_intermediate_nodes_as_outputs, + ), + ), + graph, + lifted_freevars, + ) + + except Unsupported as ex: + f_name = f"{type(f).__name__}" + if isinstance(f, UserFunctionVariable): + f_name = f.get_name() + msg = ( + f"speculate_subgraph: while introspecting {description}, we were unable " + f"to trace function `{f_name}` into a single graph. This means " + f"that Dynamo was unable to prove safety for this API and will " + f"fall back to eager-mode PyTorch, which could lead to a slowdown." + ) + log.info(msg) + log.info(ex) + raise ex + + +def make_attr(tx: "InstructionTranslatorBase", name: str) -> Proxy: + node = tx.output.create_proxy( + "get_attr", + name, + (), + {}, + ) + return node + + +def add_hop_context(cls: type[HOP_VT_Alias]) -> type[HOP_VT_Alias]: + """ + Class decorator that adds HOP context to exceptions raised in call_function. + + Requires the class to have _HOP_NAME and _ALLOW_FALLBACK_TO_EAGER set. + """ + + if hasattr(cls.call_method, "_hop_wrapped"): + return cls + + if cls._HOP_NAME is None: + raise TypeError(f"{cls.__name__} must define _HOP_NAME class attribute.") + if cls._ALLOW_FALLBACK_TO_EAGER is None: + raise TypeError( + f"{cls.__name__} must define _ALLOW_FALLBACK_TO_EAGER class attribute." + ) + + original_call_function = cls.call_function + + @functools.wraps(original_call_function) + def wrapped_call_function(self, *args: Any, **kwargs: Any) -> VariableTracker: + try: + return original_call_function(self, *args, **kwargs) + except UncapturedHigherOrderOpError as e: + if not hasattr(e, "_hop_name"): + e._hop_name = self._HOP_NAME # pyrefly: ignore[missing-attribute] + raise + except (Unsupported, ObservedException) as e: + if isinstance(e, FakeTensorObservedException): + raise + # Only tag if not already tagged (reports deepest HOP only) + if hasattr(e, "_hop_name"): + raise + + if self._ALLOW_FALLBACK_TO_EAGER: + # Tag the exception with HOP name for later formatting in exc.py + # NOTE: because nested graph breaks are NOT supported on HOPs, we will + # NEVER log a HOP graph break before running this + e._hop_name = self._HOP_NAME # pyrefly: ignore[missing-attribute] + raise + else: + real_stack = getattr(e, "real_stack", None) + full_msg = ( + "This higher order operator doesn't work unless it is " + "captured completely with torch.compile. Got graph break/error:" + f"\n\n{str(e)}" + ) + exc = UncapturedHigherOrderOpError(full_msg, real_stack) + exc._hop_name = self._HOP_NAME # pyrefly: ignore[missing-attribute] + raise exc.with_traceback(e.__traceback__) from None + + wrapped_call_function._hop_wrapped = True # pyrefly: ignore[missing-attribute] + cls.call_function = wrapped_call_function + return cls + + +class TorchHigherOrderOperatorVariable(VariableTracker): + # Subclasses should set _HOP_NAME to enable automatic HOP context in error messages + _HOP_NAME: str | None = None + # Set to False for HOPs that hard error on graph break (e.g., cond, map, scan); otherwise + # HOPs will fall back to eager. + _ALLOW_FALLBACK_TO_EAGER: bool = True + + def __init_subclass__(cls, **kwargs: Any) -> None: + super().__init_subclass__(**kwargs) + add_hop_context(cls) + + def __init__( + self, value: HigherOrderOperator, source: Source | None = None, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.value = value + self.source = source + + @staticmethod + def make( + value: HigherOrderOperator, source: Source | None = None, **kwargs: Any + ) -> "TorchHigherOrderOperatorVariable": + variable_class = _hop_name_to_variable_class.get(value.__name__) + if variable_class is not None: + return variable_class(value, source, **kwargs) + + from torch._higher_order_ops import BaseHOP + + if isinstance(value, BaseHOP): + return BaseHOPVariable(value, source, **kwargs) + unimplemented( + gb_type="unsupported HigherOrderOperator", + context=str(value), + explanation=f"Unable to create higher order operator variable for {value.__name__}.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .torch_function import can_dispatch_torch_function, dispatch_torch_function + + if can_dispatch_torch_function(tx, args, kwargs): + return dispatch_torch_function(tx, self, args, kwargs) + + return self._call_function(tx, args, kwargs) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + unimplemented( + gb_type="unsupported HigherOrderOperator function call", + context=str(self.value), + explanation=f"Unable to trace calling higher order operator variable for {self.value.__name__}.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + def as_python_constant(self) -> HigherOrderOperator: + return self.value + + +class CustomFunctionHigherOrderOperatorVariable(TorchHigherOrderOperatorVariable): + """ + Wraps torch._functorch.autograd_function.custom_function_call + """ + + _HOP_NAME = "torch.ops.higher_order.custom_function_call" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.source is None: + raise AssertionError("source must not be None") + return torch._dynamo.variables.UserMethodVariable( + self.value.__call__.__func__, + torch._dynamo.variables.UserDefinedObjectVariable( + self.value, source=self.source + ), + source=AttrSource(self.source, "__call__"), + ).call_function(tx, args, kwargs) + + +class CondHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.cond" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from . import ListVariable + + self.supports_input_mutation = not torch.is_grad_enabled() + self.supports_aliasing = not torch.is_grad_enabled() + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + for i, k in enumerate(["pred", "true_fn", "false_fn", "operands"]): + if v := kwargs.pop(k, None): + if i != len(args): + raise AssertionError( + "did not provide the right number of non-keyword args" + ) + args.append(v) + + # TODO(voz): Support fake tensor dispatch for recursive + # ops - see torch/dispatch/_dispatcher.py + if len(args) != 4 or kwargs: + unimplemented( + gb_type="torch.cond: improper args/kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"torch.cond expects 4 positional arguments (got {len(args)}) " + f"and no keyword arguments (got {len(kwargs)}) " + "Usage: cond(pred, cond_fn, body_fn, operands)", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # Specialize into one of the branches since pred is constant + pred, true_fn, false_fn, operands = args + if type(args[0]) is ConstantVariable: + warnings.warn( + "Pred is a Python constant. When used with torch.cond, it specializes on one of the branches." + " If you want torch.cond to preserve two branches, please make the predicate a boolean tensor or a SymBool.", + UserWarning, + ) + if pred.as_python_constant(): + return true_fn.call_function(tx, unpack_iterable(tx, operands), {}) + else: + return false_fn.call_function(tx, unpack_iterable(tx, operands), {}) + + # predicate + if type(pred.realize()) not in ( + ConstantVariable, + TensorVariable, + SymNodeVariable, + ): + unimplemented( + gb_type="torch.cond: improper predicate", + context=str(pred), + explanation="Expected `pred` to be a bool or a boolean tensor with a single item " + f"but got {str(type(pred))} with original python type {str(pred.python_type())}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # operands + if not isinstance(operands, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.cond: improper operands", + context=str(operands), + explanation="Expected `operands` to be a list/tuple " + f"but got {operands.python_type()}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + operands_seq = unpack_iterable(tx, operands) + if not only_consist_of( + operands, (TensorVariable, ConstantVariable, SymNodeVariable) + ): + unimplemented( + gb_type="torch.cond: improper operands contents", + context=str(operands), + explanation="Expected `operands` to be a list/tuple of pytrees that only consists of tensor leaves.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # branches + _check_supported_callable_arg(tx, true_fn, "true_fn") + _check_supported_callable_arg(tx, false_fn, "false_fn") + + # Our strategy for tracing the true/false branches of cond + # are to checkpoint our graphstate, run the true branch, + # roll it back to the checkpoint, and run the false + # branch, and then merge the graphstates. Well, perhaps + # "merge" is too strong a word: we mostly assert that + # the resulting graphstates have to be the same. + # + # We only permit guards to diverge (we union the guards from + # both branches). In particular, this means that side + # effects are NOT permitted inside true/false branches; this + # would be difficult to implement, because of the path + # explosion problem. + + def speculate_branch( + branch: bool, + ) -> tuple[VariableTracker, OutputSpec, torch.fx.Graph, dict[Proxy, Proxy]]: + # NB: 0 is predicate + ix = 1 if branch else 2 + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + # TODO: Support kwargs + ( + (ret_val, ret_spec), + ret_graph, + ret_lifted_freevars, + ) = speculate_subgraph( + tx, + args[ix], + operands_seq, + {}, + self._HOP_NAME, + source_target=self.value, + should_flatten_outputs=True, + # TODO - removing consts from control flow ops need more work + remove_consts_from_outputs=False, + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + # need to ensure we increase epoch so we don't memoize unbacked bindings + # across different subgraphs which can interfere with runtime assertion + # generation. + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None") + tx.fake_mode.epoch += 1 + + if not only_consist_of(ret_val, (TensorVariable, ConstantVariable)): + unimplemented( + gb_type="torch.cond: unsupported branch return type", + context=str(ret_val), + explanation="Expected branches to return a possibly nested pytree of tensors or constant ints.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + for ret in unpack_iterable(tx, ret_val): + if ret.is_python_constant() and not isinstance( + ret.as_python_constant(), int + ): + unimplemented( + gb_type="torch.cond: unsupported branch return type (constant non-int)", + context=str(ret_val), + explanation="Constants returned from branches must be ints.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + return ret_val, ret_spec, ret_graph, ret_lifted_freevars + + (true_r, true_spec, true_graph, true_lifted_freevars) = speculate_branch(True) + true_nn_modules = dict(tx.output.nn_modules) + + ( + false_r, + false_spec, + false_graph, + false_lifted_freevars, + ) = speculate_branch(False) + false_nn_modules = dict(tx.output.nn_modules) + + same_spec = _make_inlined(tx, pytree.TreeSpec.__eq__)( + true_spec.treespec, false_spec.treespec + ).as_python_constant() + # 3.14: NotImplemented cannot be converted to bool + if same_spec is not NotImplemented and not same_spec: + unimplemented( + gb_type="torch.cond: differing branch outputs", + context=f"true_spec: {true_spec.treespec}, false_spec: {false_spec.treespec}, same_spec: {same_spec}", + explanation="Expected branches to return the same pytree structure.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + shared, (unique_true, unique_false) = _merge_graph_inputs( + [true_graph, false_graph], + [true_lifted_freevars, false_lifted_freevars], + ["true_branch", "false_branch"], + ) + + true_name = tx.output.install_subgraph( + "cond_true", + torch.fx.GraphModule(true_nn_modules, true_graph), + ) + false_name = tx.output.install_subgraph( + "cond_false", + torch.fx.GraphModule(false_nn_modules, false_graph), + ) + + true_node = make_attr(tx, true_name) + false_node = make_attr(tx, false_name) + + p_args = ( + pred.as_proxy(), + true_node, + false_node, + tuple(shared + unique_true + unique_false), + ) + + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.cond, + p_args, + {}, + None, + true_spec, + true_r, + ) + + +class SwitchHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.switch" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: Sequence[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from torch._higher_order_ops.switch import _get_branch + + from . import ListVariable + + self.supports_input_mutation = not torch.is_grad_enabled() + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + for i, k in enumerate(["index", "branches", "operands"]): + if v := kwargs.pop(k, None): + if i != len(args): + raise AssertionError( + "did not provide the right number of non-keyword args" + ) + args.append(v) + + if len(args) != 3 or kwargs: + unimplemented( + gb_type="torch.switch: improper args/kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"torch.switch expects 3 positional arguments (got {len(args)}) " + f"and no keyword arguments (got {len(kwargs)}) " + "Usage: switch(index, branches, operands)", + hints=[*graph_break_hints.USER_ERROR], + ) + + index, branches, operands = args + if type(index) is ConstantVariable: + # Specialize into one of the branches since index is constant. + warnings.warn( + "Index is a Python constant. When used with torch.switch, it specializes on one of the branches." + " If you want torch.switch to preserve the branches, please make the index a tensor or SymInt.", + UserWarning, + ) + idx = index.as_python_constant() + branch_fns = branches.unpack_var_sequence(tx) + return _get_branch(branch_fns, idx).call_function( + tx, operands.unpack_var_sequence(tx), {} + ) + + # index + if type(index.realize()) not in ( + ConstantVariable, + TensorVariable, + SymNodeVariable, + ): + unimplemented( + gb_type="torch.switch: improper index", + context=str(index), + explanation="Expected index to be an int or a tensor with a single item " + f"but got {str(type(index))} with original python type {str(index.python_type())}.", + hints=[*graph_break_hints.USER_ERROR], + ) + + # operands + if not isinstance(operands, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.switch: improper operands", + context=str(operands), + explanation=f"Expected operands to be a list/tuple " + f"but got {operands.python_type()}.", + hints=[*graph_break_hints.USER_ERROR], + ) + + operands_seq = operands.unpack_var_sequence(tx) + if not only_consist_of( + operands, (TensorVariable, ConstantVariable, SymNodeVariable) + ): + unimplemented( + gb_type="torch.switch: improper operands contents", + context=str(operands), + explanation="Expected `operands` to be a list/tuple of pytrees that only consists of tensor leaves.", + hints=[*graph_break_hints.USER_ERROR], + ) + + # branches + if not isinstance(branches, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.switch: improper branches", + context=str(branches), + explanation="Expected branches to be a list/tuple of callables.", + hints=[*graph_break_hints.USER_ERROR], + ) + + branch_fns = branches.unpack_var_sequence(tx) + if len(branch_fns) == 0: + unimplemented( + gb_type="torch.switch: empty branches", + context=str(branches), + explanation="Expected at least one branch.", + hints=[*graph_break_hints.USER_ERROR], + ) + + for i, branch_fn in enumerate(branch_fns): + _check_supported_callable_arg(tx, branch_fn, f"branch{i}") + + # Our strategy for tracing the branches of switch mirrors cond: each + # branch is speculated in isolation and the resulting graphs are + # merged, asserting the output specs agree. Side effects are not + # permitted inside branches because of the path-explosion problem. + def speculate_branch( + func, + ) -> tuple[VariableTracker, OutputSpec, torch.fx.Graph, dict[Proxy, Proxy]]: + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (ret_val, ret_spec), + ret_graph, + ret_lifted_freevars, + ) = speculate_subgraph( + tx, + func, + operands_seq, + {}, + self._HOP_NAME, + source_target=self.value, + should_flatten_outputs=True, + remove_consts_from_outputs=False, + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + # need to ensure we increase epoch so we don't memoize unbacked bindings + # across different subgraphs which can interfere with runtime assertion + # generation. + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None") + tx.fake_mode.epoch += 1 + + if not only_consist_of( + ret_val, (TensorVariable, ConstantVariable), allow_none=True + ): + unimplemented( + gb_type="torch.switch: unsupported branch return type", + context=str(ret_val), + explanation="Expected branches to return a possibly nested pytree of tensor or constant int/None leaves.", + hints=[*graph_break_hints.USER_ERROR], + ) + for ret in ret_val.unpack_var_sequence(tx): + if ret.is_python_constant(): + const = ret.as_python_constant() + # Python floats in branch outputs are blocked upstream by + # validate_subgraph_output_types (shared HOP gate); we + # mirror the whitelist here to keep the error specific to + # torch.switch. bool is implicitly accepted via the int check. + if not (isinstance(const, int) or const is None): + unimplemented( + gb_type="torch.switch: unsupported branch return type (constant)", + context=str(ret_val), + explanation="Constants returned from branches must be int or None.", + hints=[*graph_break_hints.USER_ERROR], + ) + return ret_val, ret_spec, ret_graph, ret_lifted_freevars + + branch_states: list[Any] = [] + branch_nn_modules: list[Any] = [] + for f in branch_fns: + branch_states.append(speculate_branch(f)) + branch_nn_modules.append(dict(tx.output.nn_modules)) + branch_rets, branch_specs, branch_graphs, branch_lifted_freevars = zip( + *branch_states + ) + + for i, (spec_a, spec_b) in enumerate(itertools.pairwise(branch_specs)): + same_spec = _make_inlined(tx, pytree.TreeSpec.__eq__)( + spec_a.treespec, spec_b.treespec + ).as_python_constant() + # 3.14: NotImplemented cannot be converted to bool + if same_spec is not NotImplemented and not same_spec: + unimplemented( + gb_type="torch.switch: differing branch outputs", + context=f"branch{i}: {spec_a.treespec}, branch{i + 1}: {spec_b.treespec}, same_spec: {same_spec}", + explanation="Expected branches to return the same pytree structure.", + hints=[*graph_break_hints.USER_ERROR], + ) + + # Merge lifted freevars across all branches so they all share the same + # placeholder signature. Branches may capture different free variables + # (e.g. different nn module attrs), so we union them and add missing + # placeholders to any branch graph that lacks them. + branch_names_for_merge = [f"branch{i}" for i in range(len(branch_fns))] + shared, unique_per_branch = _merge_graph_inputs( + list(branch_graphs), + list(branch_lifted_freevars), + branch_names_for_merge, + ) + all_lifted = shared + [u for branch in unique_per_branch for u in branch] + + branch_names = [ + tx.output.install_subgraph( + f"switch_branch{i}", + GraphModule(branch_nn_modules[i], graph), + ) + for i, graph in enumerate(branch_graphs) + ] + + branch_nodes = [make_attr(tx, name) for name in branch_names] + + p_args = ( + index.as_proxy(), + branch_nodes, + tuple(all_lifted), + ) + + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.switch, + p_args, + {}, + None, + branch_specs[0], + branch_rets[0], + ) + + +class CallTorchbindHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.call_torchbind" + + def __init__( + self, + hop: HigherOrderOperator, + source: Source | None, + script_obj_var: Any, + method_name: str, + ) -> None: + super().__init__(hop, source) + self.script_obj_var = script_obj_var + self.method_name = method_name + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + args_proxy = [arg.as_proxy() for arg in args] + kwargs_proxy = {k: v.as_proxy() for k, v in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=tuple( + [self.script_obj_var.as_proxy(), self.method_name] + args_proxy + ), + kwargs=kwargs_proxy, + ), + ) + + +def validate_subgraph_output_types( + output: VariableTracker | list[VariableTracker], +) -> None: + """Verify that the output of the subgraph is a tensor, + int, bool, SymBool, or SymInt. + """ + from . import TensorVariable + + if non_tensor_output := find_mismatched_vars( + output, TensorVariable, allow_none=True + ): + for out in non_tensor_output: + if ( + (isinstance(out, SymNodeVariable) and out.python_type() in (int, bool)) + or ( + out.is_python_constant() + and isinstance(out.as_python_constant(), (int, bool)) + ) + or isinstance(out, CustomClassObjectVariable) + ): + continue + unimplemented( + gb_type="HOP body output unsupported", + context=f"non-tensor outputs: {non_tensor_output}", + explanation="HigherOrderOperator body's output must consist of tensors or ints/bools only " + f"but got {out.python_type()}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + +class WhileLoopHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.while_loop" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + self.supports_input_mutation = not torch.is_grad_enabled() + return _call_while_loop( + self, tx, args, kwargs, stack_output=False, hop_name=self._HOP_NAME + ) + + +class WhileLoopStackOutputHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.while_loop" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + return _call_while_loop( + self, tx, args, kwargs, stack_output=True, hop_name=self._HOP_NAME + ) + + +class AssociativeScanHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.associative_scan" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from torch._higher_order_ops.utils import first_slice_copy + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + def arg_extractor( + combine_fn: VariableTracker, + xs: VariableTracker, + additional_inputs: VariableTracker, + ) -> tuple[VariableTracker, VariableTracker, VariableTracker]: + return combine_fn, xs, additional_inputs + + combine_fn, xs, additional_inputs = arg_extractor(*args, **kwargs) + + if args[0].python_type() is functools.partial: + # This is the standard case when the user calls the frontend + # and the frontend invokes dynamo + if len(args) != 2: + unimplemented( + gb_type="torch.associative_scan: improper args", + context=f"args: {args}", + explanation=f"torch.associative_scan expects 2 positional arguments (got {len(args)}) " + "Usage: associative_scan(combine_fn, xs)", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + xs_treespec = args[0].keywords["spec"] + + # combine_fn input check + # We need to get the pure combine_fn from the functools.partial + _check_supported_callable_arg( + tx, + combine_fn.keywords["combine_fn"], # type: ignore[attr-defined] + "combine_fn", + ) + else: + # This case is hit during re-tracing, for example in export tests + # In this case, the combine_fn is a callable and not a functools.partial + xs_treespec = _make_inlined(tx, pytree.tree_structure)(xs) + + _check_supported_callable_arg(tx, combine_fn, "combine_fn") + + # xs input check + if not isinstance(xs, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.associative_scan: improper xs", + context=str(xs), + explanation=f"Expected xs to be a list/tuple but got {xs.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + xs_vars = unpack_iterable(tx, xs) + _check_all_tensorvariable(xs_vars) + + # additional_inputs input check + if not isinstance(additional_inputs, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.associative_scan: improper additional_inputs", + context=str(additional_inputs), + explanation=f"Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + additional_inputs_vars = unpack_iterable(tx, additional_inputs) + _check_all_tensorvariable(additional_inputs_vars) + + # Trace the subgraph + # The sub_args is a slice of original input, e.g. if input.size is (3, 4), and scan dim=0 + # the sub_args shape will be (4, ). + with discard_graph_changes(tx): + sub_args = [ + _make_inlined(tx, first_slice_copy)(leaf) + for leaf in itertools.chain(xs_vars, xs_vars) + ] + sub_args_additional_inputs = [ + t.call_method(tx, "clone", args=[], kwargs={}) + for t in additional_inputs_vars + ] + + sub_args = sub_args + sub_args_additional_inputs + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (combine_result, _combine_spec), + combine_graph, + combine_lifted_freevars, + ) = speculate_subgraph( + tx, + combine_fn, + sub_args, + sub_kwargs={}, + description=self._HOP_NAME, + source_target=self.value, + set_subgraph_inputs="flatten_manual", + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + # Ensure that the output of scan is a flattened list of elements, + # because downstream operations assume that the output of HOPs + # is flattened + output_node = combine_graph.find_nodes(op="output")[0] + output_node.args = (pytree.tree_leaves(output_node.args),) + combine_graph.lint() + + # Collect the results from the combine_fn + results, _combine_treespec = unpack_iterable( + tx, _make_inlined(tx, pytree.tree_flatten)(combine_result) + ) + + # Check whether the combine_fn returns one child tree for the output. + if _combine_treespec.as_python_constant().num_leaves < 1: + unimplemented( + gb_type="torch.associative_scan: combine_fn improper number of leaves", + context=str(_combine_treespec.as_python_constant()), + explanation="combine_fn needs to produce one pytree for the output " + f"but combine_fn produces the pytree {_combine_treespec.as_python_constant()}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # Check whether the outs produced by combine_fn has the same treespec as xs + # We need to have this check this way, because in case init is a TreeSpec and carry + # but carry is only a LeafSpec, these two cannot be compared correctly. + if ( + xs_treespec.as_python_constant().is_leaf() + != _combine_treespec.as_python_constant().is_leaf() + ) or not _make_inlined(tx, pytree.TreeSpec.__eq__)( + xs_treespec, _combine_treespec + ).as_python_constant(): + unimplemented( + gb_type="torch.associative_scan: mismatched input/output tree structure", + context=f"xs: {xs_treespec.as_python_constant()}, output: {_combine_treespec.as_python_constant()}", + explanation="The tree structure of the xs and the outs of the combine_fn are expected to be identical, but got " + f"xs: {xs_treespec.as_python_constant()} vs output: {_combine_treespec.as_python_constant()}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # We set include contiguity=False because we have vmap x HOP tests, where if + # include_contiguity=True will call t.is_contiguous inside of vmap and get an error + # "querying is_contiguous inside of vmap for memory_format other than + # torch.contiguous_format is not yet implemented". This is okay because stride + # is still checked. + check_meta_consistency_vt( + [_make_inlined(tx, first_slice_copy)(t) for t in xs_vars], + results.items, # type: ignore[attr-defined] + "initial_xs", + "combine_fn_output", + include_contiguity=False, + ) + + combine_gm = torch.fx.GraphModule(dict(tx.output.nn_modules), combine_graph) + combine_freevars_proxy = tuple(combine_lifted_freevars.keys()) + + # Compute the proxies for the input check + proxy_vars_inputcheck = ( + tuple(sarg.as_proxy() for sarg in sub_args) + combine_freevars_proxy + ) + + from torch._higher_order_ops.utils import _maybe_fake_tracing + from torch._inductor.utils import is_pointwise_use + + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None") + with tx.fake_mode: + sub_args_fake = [ + ( + leaf.node.meta["example_value"].clone() + if hasattr(leaf.node.meta["example_value"], "clone") + else leaf.node.meta["example_value"] + ) + for leaf in pytree.tree_leaves(proxy_vars_inputcheck) + ] + pre_dispatch = False + + fx = _maybe_fake_tracing( + combine_gm, sub_args_fake, pre_dispatch=pre_dispatch + ) + + for node in fx.graph.nodes: + # Check that the combine_fn is pointwise, if combine_mode='pointwise' + if not all( + is_pointwise_use(use) or use.op == "output" for use in node.users + ): + raise RuntimeError( + "For combine_mode='pointwise', the combine_fn needs to be pointwise" + ) + + combine_fn_name = tx.output.install_subgraph( + "associative_scan_combine_fn", combine_gm + ) + + # Compute the proxies + xs_proxy = xs.as_proxy() + combine_freevars_proxy = tuple(combine_lifted_freevars.keys()) + additional_inputs_proxy = additional_inputs.as_proxy() + combine_freevars_proxy + + p_args = ( + make_attr(tx, combine_fn_name), + xs_proxy, + additional_inputs_proxy, + ) + + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.associative_scan, + p_args, + {}, + None, + OutputSpec(xs_treespec), # type: ignore[arg-type] + None, + ) + + +class ScanHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.scan" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from torch._higher_order_ops.scan import _extract_carry_and_out + from torch._higher_order_ops.utils import first_slice_copy + + self.supports_input_mutation = not torch.is_grad_enabled() + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + # combine_fn input check + def _check_combine_fn_is_normalized(combine_fn_var: VariableTracker) -> bool: + if not isinstance( + combine_fn_var, + ( + variables.nn_module.NNModuleVariable, + variables.nn_module.UnspecializedNNModuleVariable, + variables.FunctoolsPartialVariable, + ), + ): + unimplemented( + gb_type="torch.scan: improper combine_fn", + context=str(combine_fn_var), + explanation="Expected combine_fn to be wrapped as functools.partial in scan user-facing api " + f"or a graph module if we're re-exporting but got {combine_fn_var.python_type()}.", + hints=[ + *graph_break_hints.DIFFICULT, + ], + ) + return isinstance( + combine_fn_var, + ( + variables.nn_module.NNModuleVariable, + variables.nn_module.UnspecializedNNModuleVariable, + ), + ) + + def arg_extractor( + combine_fn: VariableTracker, + init: VariableTracker, + xs: VariableTracker, + additional_inputs: VariableTracker, + ) -> tuple[VariableTracker, VariableTracker, VariableTracker, VariableTracker]: + return combine_fn, init, xs, additional_inputs + + combine_fn, init, xs, additional_inputs = arg_extractor(*args, **kwargs) + init_vars = unpack_iterable(tx, init) + xs_vars = unpack_iterable(tx, xs) + additional_inputs_vars = unpack_iterable(tx, additional_inputs) + + # combine_fn input check + combine_fn_is_normalized = _check_combine_fn_is_normalized(combine_fn) + if combine_fn_is_normalized: + combine_gm = combine_fn.value # type: ignore[attr-defined] + if not isinstance(combine_gm, torch.fx.GraphModule): + raise AssertionError( + f"Expected combine_gm to be a GraphModule, got {combine_fn}, {combine_gm}" + ) + else: + # combine_fn input check + # We need to get the pure combine_fn from the functools.partial + _check_supported_callable_arg( + tx, + combine_fn.keywords["combine_fn"], # type: ignore[attr-defined] + "combine_fn", + ) + # xs input check + if not isinstance(xs, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.scan: improper xs", + context=str(xs), + explanation=f"Expected xs to be a list/tuple but got {xs.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + # init input check + if not isinstance(init, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.scan: improper init", + context=str(init), + explanation=f"Expected init to be a list/tuple with at least one element but got {init.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + if len(init_vars) == 0: + unimplemented( + gb_type="torch.scan: no init leaves", + context="", + explanation="Expected init leaves.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + # additional_inputs input check + if not isinstance(additional_inputs, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.scan: improper additional_inputs", + context=str(additional_inputs), + explanation=f"Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + _check_all_tensorvariable(init_vars) + _check_all_tensorvariable(xs_vars) + _check_all_tensorvariable(additional_inputs_vars) + + with discard_graph_changes(tx): + sub_args_init = [ + ini.call_method(tx, "clone", args=[], kwargs={}) for ini in init_vars + ] + # The sub_args_inp is a slice of original input, e.g. if input.size is (3, 4), and scan dim=0 + # the sub_args_inp shape will be (4, ). + sub_args_inp = [_make_inlined(tx, first_slice_copy)(inp) for inp in xs_vars] + sub_args_additional_inputs = [ + t.call_method(tx, "clone", args=[], kwargs={}) + for t in additional_inputs_vars + ] + + sub_args = sub_args_init + sub_args_inp + sub_args_additional_inputs + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (combine_result, _combine_spec), + combine_graph, + combine_lifted_freevars, + ) = speculate_subgraph( + tx, + combine_fn, + sub_args, + sub_kwargs={}, + description=self._HOP_NAME, + source_target=self.value, + set_subgraph_inputs="flatten_manual", + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + combine_mutated_inputs = set( + getattr(combine_graph, "_dynamo_mutated_input_indices", ()) + ) + + # Ensure that the output of scan is a flattened list of elements, + # because downstream operations assume that the output of HOPs + # is flattened + output_node = combine_graph.find_nodes(op="output")[0] + output_node.args = (pytree.tree_leaves(output_node.args),) + combine_graph.lint() + combine_freevars_proxy = list(combine_lifted_freevars.keys()) + combine_result_vars = unpack_iterable(tx, combine_result) + + if combine_fn_is_normalized: + carry_vars, out_vars = _extract_carry_and_out( + combine_result_vars, len(init_vars) + ) + else: + if len(combine_result_vars) != 2: + unimplemented( + gb_type="torch.scan: improper combine_fn number of returns", + context=str(combine_result_vars), + explanation=f"Expect combine_fn to return a tuple (next_carry, y) but got {combine_result_vars}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + carry_tree, out_vars = combine_result_vars + carry_vars, _ = unpack_iterable( + tx, _make_inlined(tx, pytree.tree_flatten)(carry_tree) + ) + carry_vars = unpack_iterable(tx, carry_vars) + out_vars = unpack_iterable( + tx, _make_inlined(tx, pytree.tree_leaves)(out_vars) + ) + + # additional output checking + _combine_spec = OutputSpec( + _make_inlined(tx, pytree.tree_structure)(combine_result) # type: ignore[arg-type] + ) + + check_meta_consistency_vt( + init_vars, + carry_vars, + "init", + "carry", + ) + + # Check meta data of carries and inits. If we pass this stage, we are sure that the init and carries + # have the same tree structure. + # We set include contiguity=False because we have vmap x HOP tests, where if + # include_contiguity=True will call t.is_contiguous inside of vmap and get an error + # "querying is_contiguous inside of vmap for memory_format other than + # torch.contiguous_format is not yet implemented". This is okay because stride + # is still checked. + check_meta_consistency_vt( + init_vars, + carry_vars, + "init", + "carry", + include_contiguity=False, + ) + + xs_proxy = xs.as_proxy() + init_proxy = init.as_proxy() + additional_inputs_proxy = list(additional_inputs.as_proxy()) + list( + combine_freevars_proxy + ) + + # Mutation handling: scan allows in-place writes only to + # additional_inputs (lifted, loop-invariant tensors). Mutations of + # init / xs are unsafe (see ScanOp.gen_schema for the contract) so + # we graph-break here with a precise message. The remaining indices + # are mapped through the parent-side input list to produce a + # comma-joined ``mutated_arg_indices`` kwarg for the HOP call, + # mirroring while_loop. + n_init = len(init_vars) + n_xs = len(xs_vars) + + disallowed = sorted(i for i in combine_mutated_inputs if i < n_init + n_xs) + if disallowed: + init_part = [i for i in disallowed if i < n_init] + xs_part = [i - n_init for i in disallowed if n_init <= i] + unimplemented( + gb_type="torch.scan: combine_fn mutates init or xs", + context=f"init={init_part}, xs={xs_part}", + explanation=( + "scan only supports in-place mutation of additional_inputs " + "(loop-invariant tensors). init is the *initial* carry only -- " + "from step 1 on the driver feeds combine_fn's returned carry, " + "so an in-place write to init would only affect step 0. " + "xs[t] is a fresh, storage-disjoint slice each step, so a " + "mutation cannot be observed by step t+1. Update the carry " + "via the combine_fn return value; for in-place lifted buffers " + "use additional_inputs." + ), + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # additional_inputs (subgraph indices [n_init+n_xs, ...)) plus any + # lifted freevars (indices >= n_init+n_xs+n_additional). Both are + # carried as additional_inputs at the HOP-call layer. + all_scan_inputs: list[VariableTracker | Proxy] = ( + list(init_vars) + + list(xs_vars) + + list(additional_inputs_vars) + + list(combine_freevars_proxy) + ) + # Build a parent-storage set from the subgraph placeholders that were + # detected as mutated, then re-map through ``all_scan_inputs`` so we + # cover both regular additional_inputs and lifted freevars. + mutated_input_storages = subgraph_mutated_input_storages( + combine_graph, + {i for i in combine_mutated_inputs if i >= n_init + n_xs}, + ) + mutated_inputs = parent_mutated_input_indices( + all_scan_inputs, mutated_input_storages + ) + mutated_arg_indices = ",".join(str(i) for i in mutated_inputs) + + combine_gm = torch.fx.GraphModule(dict(tx.output.nn_modules), combine_graph) + combine_fn_name = tx.output.install_subgraph("scan_combine_fn", combine_gm) + + p_args = ( + make_attr(tx, combine_fn_name), + init_proxy, + xs_proxy, + additional_inputs_proxy, + ) + hop_kwargs = ( + {"mutated_arg_indices": mutated_arg_indices} if mutated_arg_indices else {} + ) + + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.scan, + p_args, + hop_kwargs, + None, + _combine_spec, + None, + ) + + +class MapHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.map_impl" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + self.supports_input_mutation = not torch.is_grad_enabled() + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + if len(kwargs) > 0: + unimplemented( + gb_type="torch.map: kwargs not supported", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"torch.map expects no keyword arguments (got {len(kwargs)})", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + _check_supported_callable_arg(tx, args[0], "map_fn") + + # args = f, flat_xs, flat_args + if not isinstance(args[1], (ListVariable, TupleVariable)): + raise AssertionError( + f"Expected args[1] to be a ListVariable or TupleVariable, got {args[1]}" + ) + if not isinstance(args[2], (ListVariable, TupleVariable)): + raise AssertionError( + f"Expected args[2] to be a ListVariable or TupleVariable, got {args[2]}" + ) + unpacked_xs = unpack_iterable(tx, args[1]) + unpacked_args = unpack_iterable(tx, args[2]) + + sample_shape = get_fake_value(unpacked_xs[0].as_proxy().node, tx).size() + + if len(sample_shape) < 1 or sample_shape[0] == 0: + unimplemented( + gb_type="torch.map: improper inputs", + context=str(sample_shape), + explanation="torch.map doesn't support scalar or non-zero sized tensors during tracing.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # To get the example output from map() we will need to provide at least one sample to + # the loop body. In our case we will always use xs[0], and our map() won't support zero + # sized tensor during tracing. + with discard_graph_changes(tx): + sliced_xs = [ + xs.call_method( + tx, + "select", + args=[VariableTracker.build(tx, 0), VariableTracker.build(tx, 0)], + kwargs={}, + ) + for xs in unpacked_xs + ] + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + + # TODO: Support kwargs + ( + (body_r, body_spec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + args[0], + [ + *sliced_xs, + *unpacked_args, + ], + {}, + self._HOP_NAME, + source_target=self.value, + set_subgraph_inputs="flatten_manual", + should_flatten_outputs=True, + # TODO - removing consts from control flow ops need more work + remove_consts_from_outputs=False, + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + body_mutated_inputs = set( + getattr(body_graph, "_dynamo_mutated_input_indices", ()) + ) + + # Check all outputs of map are tensors. + # For map, outputting None is OK, thus ignore None values in the check + body_r_vars = unpack_iterable(tx, body_r) + none_mask = [x.is_constant_none() for x in body_r_vars] + _check_all_tensorvariable( + [br for bm, br in zip(none_mask, body_r_vars) if not bm] + ) + + # Mutation handling: map allows in-place writes only to xs + # (each iteration sees a storage-disjoint slice). Mutations of + # pos_args or captured freevars are unsafe (see MapImpl.gen_schema + # for the contract). Placeholder order is [xs, pos_args, freevars]. + n_xs = len(unpacked_xs) + n_pos = len(unpacked_args) + + pos_args_mutated = sorted( + i - n_xs for i in body_mutated_inputs if n_xs <= i < n_xs + n_pos + ) + if pos_args_mutated: + unimplemented( + gb_type="torch.map: f mutates pos_args", + context=f"pos_args={pos_args_mutated}", + explanation=( + "map only supports in-place mutation of xs (each " + "iteration sees a storage-disjoint slice). pos_args " + "are loop-invariant: every iteration sees the same " + "tensor, so a mutation makes iterations depend on each " + "other, breaking map's independence contract and " + "introducing a data race under any parallel lowering. " + "Use scan or while_loop if sequential buffer updates " + "are required." + ), + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + freevars_mutated = sorted( + i - n_xs - n_pos for i in body_mutated_inputs if i >= n_xs + n_pos + ) + if freevars_mutated: + unimplemented( + gb_type="torch.map: f mutates a captured tensor", + context=f"freevars={freevars_mutated}", + explanation=( + "map only supports in-place mutation of xs. A tensor " + "captured from the enclosing scope (lifted parameter) is loop-invariant: " + "every iteration sees the same tensor, so a mutation " + "makes iterations depend on each other, breaking map's " + "independence contract and introducing a data race " + "under any parallel lowering. Pass the buffer through " + "xs, or use scan / while_loop if sequential buffer " + "updates are required." + ), + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # No storage round-trip needed: aliasing graph-breaks upstream, so the + # mutated subgraph placeholder indices are already the parent xs indices. + mutated_arg_indices = ",".join(str(i) for i in sorted(body_mutated_inputs)) + + body_nn_modules = dict(tx.output.nn_modules) + + body_name = tx.output.install_subgraph( + "map_body", + torch.fx.GraphModule(body_nn_modules, body_graph), + ) + + body_node = make_attr(tx, body_name) + + p_args = ( + body_node, + [xs.as_proxy() for xs in unpacked_xs], + [arg.as_proxy() for arg in unpacked_args] + + list(body_lifted_freevars.keys()), + ) + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.map_impl, + p_args, + {"mutated_arg_indices": mutated_arg_indices} if mutated_arg_indices else {}, + None, + body_spec, + body_r, + ) + + +class PrintHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.print" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + args_proxy = [arg.as_proxy() for arg in args] + kwargs_proxy = {k: v.as_proxy() for k, v in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=tuple(args_proxy), + kwargs=kwargs_proxy, + ), + ) + + +class ExecutorchCallDelegateHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.executorch_call_delegate" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + # This is operator for delegation within Executorch which calls a + # specific function in the given lowered module with the given + # operators. The actual operator is defined in the Executorch codebase. + # This is a bad hierarchical violation since + # executorch_call_delegate sits at a higher level than dynamo, but + # there's no real solution to this issue yet. + if len(kwargs) > 0: + unimplemented( + gb_type="executorch_call_delegate: kwargs not supported", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"executorch_call_delegate expects no keyword arguments (got {len(kwargs)})", + hints=[], + ) + lowered_module, lowered_node = None, None + if isinstance(args[0], variables.NNModuleVariable): + lowered_module = tx.output.get_submodule(args[0].module_key) + lowered_node = make_attr(tx, args[0].module_key) + elif isinstance(args[0], variables.UnspecializedNNModuleVariable): + # This nn module is special sa delegated by executorch. Just + # install it as a attr in the graph. + lowered_module = args[0].value + lowered_node = tx.output.register_static_attr_and_return_proxy( + "delegate", lowered_module + ) + else: + unimplemented( + gb_type="executorch_call_delegate: first arg not supported", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"executorch_call_delegate expects the first argument to be a nn.Module (got {args[0]})", + hints=[], + ) + + p_args = tuple(arg.as_proxy() for arg in args[1:]) + real_sub_args = pytree.tree_map_only( + torch.fx.Proxy, lambda a: get_fake_value(a.node, tx), p_args + ) + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None") + with tx.fake_mode: + example_value = lowered_module.original_module.module()(*real_sub_args) # type: ignore[attr-defined] + + # NOTE [Guaranteeing the 1-1 correspondence of FakeTensors and real tensors]: + # executorch modules promise not to alias inputs and outputs. + # Thus, output FakeTensors will correctly not alias input FakeTensors. + _assert_tensors_nonaliasing(real_sub_args, example_value) + + p_args = (lowered_node,) + p_args + + # Store the invocation as a call + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=tuple(p_args), + kwargs={}, + ), + example_value=example_value, + ) + + +class FunctorchHigherOrderVariable(UserFunctionVariable): + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return super().call_function(tx, args, kwargs) + + def should_allow_nested_graph_breaks(self) -> bool: + return False + + +class FunctionalCallVariable(FunctorchHigherOrderVariable): + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return super().call_function(tx, args, kwargs) + + +class ReparametrizeModuleCallVariable(FunctorchHigherOrderVariable): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + ctx_manager_vt = super().call_function(tx, args, kwargs) + return RepararametrizeModuleContextVariable(ctx_manager_vt, args[0]) # type: ignore[arg-type] + + +class WrapHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.wrap" + supports_input_mutation = True + supports_aliasing = True + allow_side_effects = False + + def install_subgraph_in_output_graph( + self, + tx: "InstructionTranslatorBase", + fn_vt: VariableTracker, + fn_args_vt: list[VariableTracker], + kwargs: dict[str, VariableTracker], + body_gmod: GraphModule, + attr_name: str = "wrap_body", + ) -> str: + return tx.output.install_subgraph( + f"{attr_name}", + body_gmod, + ) + + def create_wrapped_node( + self, + tx: "InstructionTranslatorBase", + fn_vt: VariableTracker, + fn_args_vt: list[VariableTracker], + kwargs: dict[str, VariableTracker], + description: str, + *, + subgraph_name: str = "wrap_body", + set_subgraph_inputs: Literal[ + "automatic", "automatic_with_forced_inputs" + ] = "automatic", + ) -> tuple[ + tuple[Proxy, ...], + dict[str, VariableTracker], + Any, + VariableTracker, + GraphModule, + str, + VariableTracker | tuple[VariableTracker, ...], + SubgraphTracingInfo, + ]: + # See NOTE [HigherOrderOperator tracing design] for more details + ( + body_r, + body_graph, + body_lifted_freevars, + body_graph_output_vts, + tracing_info, + ) = speculate_subgraph_with_auto_output_flattening( + tx, + fn_vt, + fn_args_vt, + kwargs, + description, + source_target=self.value, + set_subgraph_inputs=set_subgraph_inputs, + allow_side_effects=self.allow_side_effects, + filter_aliased_intermediates=getattr( + self, "filter_aliased_intermediates", False + ), + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + body_gmod = torch.fx.GraphModule(tx.output.nn_modules, body_graph) + body_name = self.install_subgraph_in_output_graph( + tx, + fn_vt, + fn_args_vt, + kwargs, + body_gmod, + attr_name=subgraph_name, + ) + body_node = make_attr(tx, body_name) + + if set_subgraph_inputs == "automatic_with_forced_inputs": + # Forced mode creates placeholders eagerly (in user arg order) and + # rewraps the tensor VTs with child-tracer proxies, so these args + # never go through the freevar lift path. Build the outer p_args + # from fn_args_vt directly, then append any closure captures that + # were auto-lifted during body tracing. + forced_args = tuple(a.as_proxy() for a in fn_args_vt if a.is_tensor()) + lifted_args = forced_args + tuple(body_lifted_freevars) + else: + # With "automatic", all args flow through the freevar lift path. + lifted_args = tuple(body_lifted_freevars) + + proxy_args = (body_node,) + lifted_args + + example_value = pytree.tree_map_only( + torch.fx.Node, + lambda a: a.meta["example_value"], + body_graph.find_nodes(op="output")[0].args[0], + ) + + return ( + proxy_args, + {}, + example_value, + body_r, + body_gmod, + body_name, + body_graph_output_vts, + tracing_info, + ) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # This flattens the kwargs into lifted args + ( + p_args, + p_kwargs, + _example_value, + body_r, + _, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node(tx, args[0], args[1:], kwargs, "wrap") + + if len(p_kwargs) > 0: + unimplemented( + gb_type="WrapHigherOrderVariable: kwargs unexpected", + context=f"args: {args}, kwargs: {kwargs}", + explanation="kwargs should have been flattened into lifted args.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + return _call_function_with_auto_output_flattening( # type: ignore[return-value] + tx, + self.value, + tuple(p_args), + p_kwargs, + _example_value, + body_r, + body_graph_output_vts, + ) + + +class WrapWithSetGradEnabledHigherOrderVariable(TorchHigherOrderOperatorVariable): + """ + This hop is not exposed to users but is inserted into the graph + after export as a post-processing step. + """ + + _HOP_NAME = "torch.ops.higher_order.wrap_with_set_grad_enabled" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + if kwargs: + unimplemented( + gb_type="wrap_with_set_grad_enabled: unexpected kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"wrap_with_set_grad_enabled expects no keyword arguments (got {len(kwargs)}).", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + grad_enabled, fn_var, *rest_args = args + + if not grad_enabled.is_python_constant(): + unimplemented( + gb_type="wrap_with_set_grad_enabled: non-constant grad_enabled", + context=str(grad_enabled), + explanation="wrap_with_set_grad_enabled expects grad_enabled argument to be a constant.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + _check_supported_callable_arg(tx, fn_var, "enable_grad_fn") + + with torch.set_grad_enabled(grad_enabled.as_python_constant()): + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (body_r, treespec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + fn_var, + [*rest_args], + {}, + self._HOP_NAME, + source_target=self.value, + set_subgraph_inputs="manual", + should_flatten_outputs=True, + ) + + if len(body_lifted_freevars) > 0: + unimplemented( + gb_type="wrap_with_set_grad_enabled: unexpected freevars", + context=str(body_lifted_freevars), + explanation="wrap_with_set_grad_enabled expects no freevars.", + hints=[], + ) + + body_gmod = torch.fx.GraphModule(tx.output.nn_modules, body_graph) + body_name = tx.output.install_subgraph( + "wrap_body", + body_gmod, + ) + + body_node = make_attr(tx, body_name) + + proxy_args = tuple( + [ + grad_enabled.as_python_constant(), + body_node, + ] + + [operand.as_proxy() for operand in rest_args] + ) + example_value = pytree.tree_map_only( + torch.fx.Proxy, + lambda a: a.node.meta["example_value"], + body_r.as_proxy(), + ) + return _call_function_and_unflatten_output( + tx, self.value, proxy_args, {}, example_value, treespec, body_r + ) + + +class WrapWithAutocastHigherOrderVariable(TorchHigherOrderOperatorVariable): + """ + This hop is not exposed to users but is inserted into the graph + after export as a post-processing step. + """ + + _HOP_NAME = "torch.ops.higher_order.wrap_with_autocast" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + if kwargs: + unimplemented( + gb_type="wrap_with_autocast: unexpected kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"wrap_with_autocast expects no keyword arguments (got {len(kwargs)}).", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + device_type, dtype, enabled, cache_enabled, fn_var, *rest_args = args + + for arg in [device_type, dtype, enabled, cache_enabled]: + if not arg.is_python_constant(): + unimplemented( + gb_type="wrap_with_autocast: expected constant arg", + context=str(args), + explanation="wrap_with_autocast expects device_type, dtype, enabled, " + "and cache_enabled arguments to be constants.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + _check_supported_callable_arg(tx, fn_var, "autocast") + + python_constants = [ + arg.as_python_constant() + for arg in [device_type, dtype, enabled, cache_enabled] + ] + + with torch.autocast(*python_constants): + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (body_r, treespec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + fn_var, + [*rest_args], + {}, + self._HOP_NAME, + source_target=self.value, + set_subgraph_inputs="manual", + should_flatten_outputs=True, + ) + + if len(body_lifted_freevars) > 0: + unimplemented( + gb_type="wrap_with_autocast: unexpected freevars", + context=str(body_lifted_freevars), + explanation="wrap_with_autocast expects no freevars.", + hints=[], + ) + + body_gmod = torch.fx.GraphModule(tx.output.nn_modules, body_graph) + body_name = tx.output.install_subgraph( + "wrap_body", + body_gmod, + ) + + body_node = make_attr(tx, body_name) + + proxy_args = tuple( + [ + *python_constants, + body_node, + ] + + [operand.as_proxy() for operand in rest_args] + ) + example_value = pytree.tree_map_only( + torch.fx.Proxy, + lambda a: a.node.meta["example_value"], + body_r.as_proxy(), + ) + + return _call_function_and_unflatten_output( + tx, self.value, proxy_args, {}, example_value, treespec, body_r + ) + + +class FlexGemmHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.ops.higher_order.flex_gemm" + _ALLOW_FALLBACK_TO_EAGER = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: Sequence[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if kwargs: + unimplemented( + gb_type="flex_gemm: unexpected kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation="flex_gemm internal HOP expects positional args only.", + hints=[*graph_break_hints.USER_ERROR], + ) + + if ( + len(args) != 5 + or not isinstance(args[2], (ListVariable, TupleVariable)) + or not isinstance(args[3], ConstDictVariable) + or not isinstance(args[4], ConstDictVariable) + ): + unimplemented( + gb_type="flex_gemm: improper args/kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=( + "flex_gemm expects 5 positional arguments: " + "gemm_op, body_fn, args, kwargs, kernel_options. args is " + "expected to be list/tuple and kwargs/kernel_options are " + "expected to be dicts." + ), + hints=[*graph_break_hints.USER_ERROR], + ) + + _check_supported_callable_arg(tx, args[1], "body_fn") + operands = args[2].unpack_var_sequence(tx) + fn_kwargs = args[3].as_python_constant() + kernel_options = args[4].as_python_constant() + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + p_args, + _, + example_value, + body_r, + _, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, + args[1], + operands, + {}, + self._HOP_NAME, + subgraph_name="flex_gemm_body", + ) + + body_node = p_args[0] + gemm_op = args[0].as_python_constant() + p_args = ( + FLEX_GEMM_OP_ALIASES.get(gemm_op, gemm_op), + body_node, + tuple(p_args[1:]), + fn_kwargs, + kernel_options, + ) + + return cast( + VariableTracker, + _call_function_with_auto_output_flattening( + tx, + self.value, + p_args, + {}, + example_value, + body_r, + body_graph_output_vts, + ), + ) + + +class HintsWrapperHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.ops.higher_order.hints_wrapper" + _ALLOW_FALLBACK_TO_EAGER = False + + def install_subgraph_in_output_graph( + self, + tx: "InstructionTranslatorBase", + fn_vt: VariableTracker, + fn_args_vt: list[VariableTracker], + kwargs: dict[str, VariableTracker], + body_gmod: GraphModule, + attr_name: str = "wrap_body", + ) -> str: + return tx.output.install_subgraph( + "hints_wrapper_body", + body_gmod, + ) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + _check_supported_callable_arg(tx, args[0], "body_fn") + + # inputs + if ( + len(args) != 3 + or not isinstance(args[1], (ListVariable, TupleVariable)) + or not isinstance(args[2], ConstDictVariable) + or len(kwargs) != 1 + or "hints" not in kwargs + ): + unimplemented( + gb_type="hints_wrapper: improper args/kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"hints_wrapper expects 3 positional arguments (got {len(args)}) " + f"and 1 keyword argument (got {len(kwargs)}). " + "Usage: hints_wrapper(body_fn, args, kwargs, hints=...). " + "args is expected to be list/tuple and kwargs is expected to be a dict.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + operands = unpack_iterable(tx, args[1]) + fn_kwargs = args[2].as_python_constant() + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + # Use create_wrapped_node from WrapHigherOrderVariable + ( + p_args, + _, + example_value, + body_r, + body_gmod, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, + args[0], # function + operands, + fn_kwargs, + self._HOP_NAME, + ) + + # hints_wrapper expects (body_node, args, kwargs) as positional args + # So we need to restructure p_args from (body_node, *lifted_args) + # to (body_node, lifted_args_tuple, {}) + body_node = p_args[0] + lifted_args = p_args[1:] + # pyrefly: ignore [implicit-any] + p_args = (body_node, tuple(lifted_args), {}) + + # add hints into p_kwargs + p_kwargs = {} + p_kwargs["hints"] = kwargs["hints"].as_python_constant() + + return _call_function_with_auto_output_flattening( # type: ignore[return-type] + tx, + self.value, + p_args, + p_kwargs, + example_value, + body_r, + body_graph_output_vts, + ) + + +class OutDtypeHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.out_dtype" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if len(kwargs) > 0: + unimplemented( + gb_type="out_dtype: unexpected kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"out_dtype expects no keyword arguments (got {len(kwargs)}).", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + p_args = tuple(arg.as_proxy() for arg in args) + op = p_args[0] + output_dtype = p_args[1] + fake_sub_args = pytree.tree_map_only( + torch.fx.Proxy, lambda a: a.node.meta["example_value"], p_args[2:] + ) + # This is a simplified implementation of this operator just for tracing. + # Actual implementation may also first promote the arguments + example_value = op(*fake_sub_args).to(dtype=output_dtype) + + # Store the invocation as a call + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=tuple(p_args), + kwargs={}, + ), + example_value=example_value, + ) + + +class StrictModeHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.strict_mode" + _ALLOW_FALLBACK_TO_EAGER = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + unpacked_sequence = unpack_iterable(tx, args[1]) + # TODO (tmanlaibaatar) support pytree here + for arg in unpacked_sequence: + if isinstance( + arg, (ListVariable, TupleVariable, ConstDictVariable, SetVariable) + ): + unimplemented( + gb_type="strict_mode: improper args", + context=f"args: {args}, kwargs: {kwargs}", + explanation="strict_mode higher order op expects flat inputs (list/tuple/dict/set)", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + if kwargs: + unimplemented( + gb_type="strict_mode: unexpected kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"strict_mode higher order op expects no keyword arguments (got {len(kwargs)}).", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (ret_val, ret_spec), + ret_graph, + ret_lifted_freevars, + ) = speculate_subgraph( + tx, + args[0], + unpacked_sequence, + {}, + self._HOP_NAME, + source_target=self.value, + should_flatten_outputs=True, + ) + + strict_mode_nn_modules = dict(tx.output.nn_modules) + + strict_mode_name = tx.output.install_subgraph( + "strict_mode_body", + torch.fx.GraphModule(strict_mode_nn_modules, ret_graph), + ) + + strict_mode_node = make_attr(tx, strict_mode_name) + p_args = ( + strict_mode_node, + tuple(ret_lifted_freevars.keys()), + ) + + flat_example_value = pytree.tree_map_only( + torch.fx.Proxy, + lambda a: a.node.meta["example_value"], + ret_val.as_proxy(), + ) + + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.strict_mode, + p_args, + {}, + flat_example_value, + ret_spec, + ret_val, + ) + + +class CheckpointHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.utils.checkpoint.checkpoint" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.allow_side_effects = ( + torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint + ) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from torch._higher_order_ops.wrap import TagActivationCheckpoint + from torch.utils.checkpoint import noop_context_fn + + context_fn = None + if "context_fn" in kwargs and kwargs["context_fn"] is not noop_context_fn: + ctx = kwargs.pop("context_fn") + if isinstance(ctx, torch._dynamo.variables.UserFunctionVariable): + context_fn = ctx.fn + elif isinstance( + ctx, torch._dynamo.variables.functions.FunctoolsPartialVariable + ): + context_fn = ctx.guard_as_python_constant() + else: + raise NotImplementedError( + f"checkpoint not implemented for {type(ctx)} context_fn" + ) + + checkpoint_kwargs, gmod_kwargs = TagActivationCheckpoint.divide_kwargs(kwargs) + + # Here we use checkpoint_kwargs (and not gmod kwargs). gmod_kwargs are + # already flattened above and managed inside the fx graph. + ( + p_args, + _, + example_value, + _body_r, + checkpointed_gmod, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, + args[0], + args[1:], + gmod_kwargs, + "torch.utils.checkpoint.checkpoint", + ) + if context_fn is not None: + checkpointed_gmod.meta["_checkpoint_context_fn"] = context_fn + + _, checkpoint_kwargs = proxy_args_kwargs([], checkpoint_kwargs) + + return _call_function_with_auto_output_flattening( # type: ignore[return-value] + tx, + self.value, + p_args, + checkpoint_kwargs, + example_value, + _body_r, + body_graph_output_vts, + ) + + +class DynamoBypassingWrapperHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.ops.higher_order.dynamo_bypassing_wrapper" + + def __init__(self, hop: HigherOrderOperator, source: Source | None) -> None: + super().__init__(hop, source) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + func_var = args[0] + + if isinstance(func_var, torch._dynamo.variables.UserFunctionVariable): + func = func_var.fn + elif isinstance( + func_var, torch._dynamo.variables.functions.FunctoolsPartialVariable + ): + func = func_var.as_python_constant() + else: + raise RuntimeError( + f"DynamoBypassingWrapperHigherOrderVariable: Unsupported function {type(func_var)}" + ) + ( + p_args, + _, + example_value, + _body_r, + gmod, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, + args[1], + args[2:], + kwargs, + str(func), + ) + + # Alternatively, we could've stored only the function's fqn and + # reconstructed, but that requires the function to be a global. + gmod_meta_key = "_dynamo_bypassing_wrapper_fn" + gmod.meta[gmod_meta_key] = func + + return _call_function_with_auto_output_flattening( # type: ignore[return-value] + tx, + self.value, + (gmod_meta_key,) + tuple(p_args), + {}, + example_value, + _body_r, + body_graph_output_vts, + ) + + +class ExportTracepointHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order._export_tracepoint" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + p_args = tuple(arg.as_proxy() for arg in args) + p_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=p_args, + kwargs=p_kwargs, + ), + example_value=None, + ) + + +class RunWithRNGStateHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.run_with_rng_state" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + p_args = tuple(arg.as_proxy() for arg in args) + p_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=p_args, + kwargs=p_kwargs, + ), + example_value=None, + ) + + +class InlineAsmElementwiseHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "inline_asm_elementwise" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + p_args = tuple(arg.as_proxy() for arg in args) + p_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=p_args, + kwargs=p_kwargs, + ), + example_value=None, + ) + + +class AutoFunctionalizeHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.auto_functionalized" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + p_args = tuple(arg.as_proxy() for arg in args) + p_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=p_args, + kwargs=p_kwargs, + ), + example_value=None, + ) + + +class FlexAttentionBackwardHighOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.flex_attention_backward" + + @staticmethod + def _uses_pretraced_graphs( + fw_graph: VariableTracker, joint_graph: VariableTracker + ) -> bool: + return not joint_graph.is_constant_none() or isinstance( + fw_graph, UnspecializedNNModuleVariable + ) + + def proxy_submod( + self, tx: "InstructionTranslatorBase", arg: UnspecializedNNModuleVariable + ) -> Proxy: + if not arg.source: # type: ignore[attr-defined] + raise AssertionError("arg.source must be set") + if not isinstance(arg.source.base, DictGetItemSource): # type: ignore[attr-defined] + raise AssertionError("arg.source.base must be a DictGetItemSource") + submod_name = tx.output.install_subgraph(arg.source.base.index, arg.value) # type: ignore[arg-type] + p_submod = make_attr(tx, submod_name) + set_example_value(p_submod.node, arg.value) + return p_submod + + def to_proxy(self, tx: "InstructionTranslatorBase", arg: VariableTracker) -> Any: + if isinstance(arg, UnspecializedNNModuleVariable): + return self.proxy_submod(tx, arg) + elif isinstance(arg, (ListVariable, TupleVariable)): + return arg.python_type()( + self.to_proxy(tx, nested_arg) for nested_arg in arg.items + ) + else: + return arg.as_proxy() + + def create_wrapped_node( + self, + tx: "InstructionTranslatorBase", + query: VariableTracker, + fn: VariableTracker, + fn_name: str, + other_buffers: list[VariableTracker], + ) -> tuple[Proxy, tuple[Proxy, ...], torch.fx.GraphModule]: + from .._trace_wrapped_higher_order_op import TransformGetItemToIndex + + def create_scalar() -> VariableTracker: + return query.call_method( + tx, + "new_empty", + [VariableTracker.build(tx, [])], + {"dtype": VariableTracker.build(tx, torch.int32)}, + ) + + with discard_graph_changes(tx): + bhmn = [create_scalar() for _ in range(4)] + if fn_name == "score_mod": + scores_require_grad: bool = query.requires_grad # type: ignore[attr-defined] + score = query.call_method( + tx, + "new_empty", + [VariableTracker.build(tx, [])], + {"requires_grad": VariableTracker.build(tx, scores_require_grad)}, + ) + new_args = [score, *bhmn, *other_buffers] + else: + if fn_name != "mask_fn": + raise AssertionError("Illegal function name: " + fn_name) + new_args = [*bhmn, *other_buffers] + + with TransformGetItemToIndex(): + ( + (_body_output, _body_spec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + fn, + new_args, + {}, + description=f"{self._HOP_NAME}: {fn_name}", + source_target=self.value, + set_subgraph_inputs="flatten_manual", + ) + + gm = torch.fx.GraphModule(tx.output.nn_modules, body_graph) + body_name = tx.output.install_subgraph(fn_name, gm) + return make_attr(tx, body_name), tuple(body_lifted_freevars), gm + + @staticmethod + def _buffer_example_value(buffer: VariableTracker) -> Any: + proxy = buffer.as_proxy() + if isinstance(proxy, Proxy): + return proxy.node.meta["example_value"] + return proxy + + def _derive_joint_graph( + self, + tx: "InstructionTranslatorBase", + query: VariableTracker, + fw_graph_gm: torch.fx.GraphModule, + score_mod_other_buffers: TupleVariable, + fw_graph_lifted_args: tuple[Proxy, ...], + ) -> Proxy: + from torch._higher_order_ops.flex_attention import create_fw_bw_graph + + query_example = query.as_proxy().node.meta["example_value"] + example_vals = ( + query_example.new_zeros((), requires_grad=True), + query_example.new_zeros((), dtype=torch.int), + query_example.new_zeros((), dtype=torch.int), + query_example.new_zeros((), dtype=torch.int), + query_example.new_zeros((), dtype=torch.int), + ) + all_buffer_examples = tuple( + self._buffer_example_value(buf) for buf in score_mod_other_buffers.items + ) + tuple(buf.node.meta["example_value"] for buf in fw_graph_lifted_args) + + _, joint_gm = create_fw_bw_graph(fw_graph_gm, example_vals, all_buffer_examples) + joint_gm = cast(GraphModule, joint_gm) + + submod_name = tx.output.install_subgraph("joint_graph", joint_gm) + p_submod = make_attr(tx, submod_name) + set_example_value(p_submod.node, joint_gm) + return p_submod + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if len(args) != 14: + return self._call_function_fallback(tx, args, kwargs) + + ( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + fw_graph, + joint_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) = args + + if ( + not isinstance(block_mask, TupleVariable) + or not isinstance(score_mod_other_buffers, TupleVariable) + or not isinstance(mask_mod_other_buffers, TupleVariable) + or len(block_mask.items) < 1 + ): + return self._call_function_fallback(tx, args, kwargs) + + if self._uses_pretraced_graphs(fw_graph, joint_graph): + return self._call_function_fallback(tx, args, kwargs) + + fw_graph_node, fw_graph_lifted_args, fw_graph_gm = self.create_wrapped_node( + tx, query, fw_graph, "score_mod", score_mod_other_buffers.items + ) + + joint_graph_node = self._derive_joint_graph( + tx, + query, + fw_graph_gm, + score_mod_other_buffers, + fw_graph_lifted_args, + ) + + mask_fn = block_mask.items[-1] + if mask_fn.is_python_constant() and mask_fn.as_python_constant() is None: + mask_fn = VariableTracker.build( + tx, + torch.nn.attention.flex_attention.noop_mask, + source=mask_fn.source, + ) + mask_fn_node, mask_fn_lifted_args, _ = self.create_wrapped_node( + tx, query, mask_fn, "mask_fn", mask_mod_other_buffers.items + ) + + proxied_args = [ + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + TupleVariable(block_mask.items[:-1], source=block_mask.source), + scale, + kernel_options, + ] + inp_args, _ = proxy_args_kwargs(proxied_args, {}) + proxied_score_mod_other_buffers = tuple( + self.to_proxy(tx, arg) for arg in score_mod_other_buffers.items + ) + proxied_mask_mod_other_buffers = tuple( + self.to_proxy(tx, arg) for arg in mask_mod_other_buffers.items + ) + + ( + inp_q, + inp_k, + inp_v, + inp_out, + inp_lse, + inp_grad_out, + inp_grad_lse, + inp_block_mask, + inp_scale, + inp_kernel_options, + ) = inp_args + + block_mask_proxy = tuple(inp_block_mask + (mask_fn_node,)) + + with torch.fx.experimental.proxy_tensor.set_original_aten_op(self.value): + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=( + inp_q, + inp_k, + inp_v, + inp_out, + inp_lse, + inp_grad_out, + inp_grad_lse, + fw_graph_node, + joint_graph_node, + block_mask_proxy, + inp_scale, + inp_kernel_options, + proxied_score_mod_other_buffers + fw_graph_lifted_args, + proxied_mask_mod_other_buffers + mask_fn_lifted_args, + ), + kwargs={}, + ), + example_value=None, + ) + + def _call_function_fallback( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + p_args, p_kwargs = None, None + try: + p_args = tuple(self.to_proxy(tx, arg) for arg in args) + p_kwargs = {key: self.to_proxy(tx, arg) for key, arg in kwargs.items()} + except (NotImplementedError, Unsupported) as err: + unimplemented( + gb_type="failed to handle argument for FlexAttentionBackward HOP", + context=f"args: {args}, kwargs: {kwargs}", + explanation="Missing Dynamo support for FlexAttentionBackward HOP argument.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + from_exc=err, + ) + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=p_args, + kwargs=p_kwargs, + ), + example_value=None, + ) + + +class TraceWrappedHigherOrderOperatorVariable(TorchHigherOrderOperatorVariable): + """ + Handles torch._dynamo._trace_wrapped_higher_order_op.inner_trace + by unwrapping the higher order op and inlining through it. This op + is created by dynamo to survive through AotAutograd, then unwrapped + here in the call to dynamo from compiled autograd. + """ + + _HOP_NAME = "torch._dynamo._trace_wrapped_higher_order_op.inner_trace" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + kwargs = dict(kwargs) + fn = kwargs.pop("fn") + return fn.call_function(tx, args, kwargs) + + +class FlexAttentionHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.flex_attention" + + @staticmethod + def normalize_to_args( + args: list[VariableTracker], kwargs: dict[str, VariableTracker] + ) -> list[VariableTracker]: + # input signature is (query, key, value, score_mod, block_mask, *other_buffers), + # block_mask is a tuple, and we don't want to flatten it. + # only flatten kwargs into lists + flat_kwargs = pytree.tree_flatten(kwargs)[0] + + # Combine the flattened lists + all_args = args + flat_kwargs + return all_args + + def create_wrapped_node( + self, + tx: "InstructionTranslatorBase", + query: VariableTracker, + fn: VariableTracker, + fn_name: str, + ) -> tuple[Proxy, tuple[Proxy, ...]]: + from .._trace_wrapped_higher_order_op import TransformGetItemToIndex + + def create_scalar() -> VariableTracker: + return query.call_method( + tx, + "new_empty", + [ + VariableTracker.build(tx, []), + ], + { + "dtype": VariableTracker.build(tx, torch.int32), + }, + ) + + with discard_graph_changes(tx): + bhmn = [create_scalar() for _ in range(4)] + if fn_name == "score_mod": + scores_require_grad: bool = query.requires_grad # type: ignore[attr-defined] + score = query.call_method( + tx, + "new_empty", + [ + VariableTracker.build(tx, []), + ], + {"requires_grad": VariableTracker.build(tx, scores_require_grad)}, + ) + new_args = [score, *bhmn] + else: + if fn_name != "mask_fn": + raise AssertionError("Illegal function name: " + fn_name) + new_args = [*bhmn] + + with TransformGetItemToIndex(): + ( + (_body_output, _body_spec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + fn, + new_args, + {}, # expect only args no kwargs for now + description=f"{self._HOP_NAME}: {fn_name}", + source_target=self.value, + set_subgraph_inputs="flatten_manual", + ) + + body_name = tx.output.install_subgraph( + fn_name, + torch.fx.GraphModule(tx.output.nn_modules, body_graph), + ) + + body_node = make_attr(tx, body_name) + + # It is possible that the score-mod function captures some free variables that are not + # passed in as arguments. In this case, we need to lift them, which is handled by speculate_subgraph. + # We then need to create proxies for this + the inputs. + + lifted_args = tuple(arg for arg in body_lifted_freevars) + + proxy_args = (body_node, lifted_args) + + return proxy_args + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + ( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + ) = self.normalize_to_args(list(args), kwargs) + + score_mod_node, score_mod_lifted_args = self.create_wrapped_node( + tx, query, score_mod, "score_mod" + ) + mask_fn = block_mask.items[-1] # type: ignore[attr-defined] + if mask_fn.is_python_constant() and mask_fn.as_python_constant() is None: + mask_fn = VariableTracker.build( + tx, + torch.nn.attention.flex_attention.noop_mask, + source=mask_fn.source, + ) + mask_fn_node, mask_fn_lifted_args = self.create_wrapped_node( + tx, query, mask_fn, "mask_fn" + ) + + proxied_args = [ + query, + key, + value, + TupleVariable(block_mask.items[:-1], source=block_mask.source), # type: ignore[attr-defined] + scale, + kernel_options, + ] + + # Store the invocation as a call + # Norm_kwargs contains the score_function and we don't want to proxy this because + # Proxying user defined functions is not supported. + inp_args, _ = proxy_args_kwargs(proxied_args, {}) + + # Compose the ordered HOO args: + # - inp_args: [query, key, value, block_mask, scale, kernel_options] + # - subgraph node: [score_mod, mask_fn_node] + # - lifted args from tracing subgraph: [score_mod_other_buffers, mask_fn_other_buffers] + _, _, _, inp_arg_block_mask, inp_arg_scale, inp_arg_kernel_options = inp_args + block_mask = tuple(inp_arg_block_mask + (mask_fn_node,)) + with torch.fx.experimental.proxy_tensor.set_original_aten_op(self.value): + proxy = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=inp_args[:3] + + ( + score_mod_node, + block_mask, + inp_arg_scale, + inp_arg_kernel_options, + score_mod_lifted_args, + mask_fn_lifted_args, + ), + kwargs={}, + ), + example_value=None, + ) + return proxy + + +@add_hop_context +class AutogradFunctionApplyVariable(VariableTracker): + _HOP_NAME: str = "autograd.Function" + _ALLOW_FALLBACK_TO_EAGER = True + + def __init__( + self, fwd_fn: Any, bwd_fn: Any, parent_source: Source | None, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.fwd_fn = fwd_fn + self.bwd_fn = bwd_fn + self.parent_source = parent_source + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def python_type(self) -> type: + return types.BuiltinMethodType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """ + At the highest level, the goal of tracing an autograd.Function is to + essentially emit a new autograd.Function object. To do this, Dynamo + traces fwd and bwd graph and then inserts a AutogradFunctionApply HOP in + the graph that call the traced fwd and bwd graph in the `forward` and + `backward` methods respectively. AOTDispatcher desugars this HOP and + just inlines the hop fwd and bwd into the main graph during its tracing. + + However, the traced forward and backward graphs cannot be directly + placed in the new autograd.Function because autograd.Function has some + requirements. + + a) # fwd graph inputs = # bwd graph outputs + b) # fwd graph outputs = # bwd graph inputs + c) Since the graphs do not have ctx variable, we have to manually return + the saved_tensors from the forward and have additional inputs in the + backward, and wire the connections. + + Unfortunately, reworking the initial traced fwd and bwd graphs to + satisfy the above 3 conditions leads to a very tedious codebase. + + Lets look at an example + + class Foo: + def __init__(self): + self.a = 4 + + class MySin(torch.autograd.Function): + @staticmethod + def forward(ctx, x, foo): + ctx.save_for_backward(x) + return x.sin() + foo.a + + @staticmethod + def backward(ctx, grad): + x, = ctx.saved_tensors + return grad * x.cos() + + We want the resulting graphs to look like: + + # Note that Dynamo lifts the foo_a directly as an input. + def fwd(ctx, x, foo_a): + # (output, saved tensors / attrs) + return (x.sin() + foo_a, (x)) + + # Note that backward graph has None as the second output to match the + # fwd requirements (even though the original backward function has just + # output) + def bwd(ctx, grad, x): + return grad * x.cos(), None + + + To accomplish this, we're going to: + 1. Construct a ctx object + 2. Speculate subgraph forward + 3. Speculate subgraph backward + 4. rewired_bwd_graph_inputs - Use the traced fwd graph as the anchor point, and rewire the backward graph outputs + 5. handle_saved_tensors_wiring - Handle the saved tensors, as mentioned in (c) + """ + + fwd_tracer = torch._dynamo.output_graph.SubgraphTracer( + tx.output, + parent=tx.output.current_tracer, + source_target=self._HOP_NAME, + ) + + ctx = self.prepare_ctx_vt(tx, args, kwargs) + + fwd_fn, fwd_out, fwd_graph, fwd_freevars, fwd_graph_output_vts = ( + self.trace_forward_graph(tx, ctx, fwd_tracer, args, kwargs) + ) + + bwd_args, bwd_out, bwd_graph, bwd_freevars, bwd_graph_output_vts = ( + self.trace_backward_graph(tx, ctx, fwd_tracer, fwd_out, fwd_fn) + ) + + self.rewire_bwd_graph_outputs( + fwd_freevars, bwd_out, bwd_graph, bwd_freevars, args + ) + + fwd_graph, bwd_graph = self.handle_saved_tensors_wiring( + fwd_out, + fwd_graph, + fwd_freevars, + fwd_graph_output_vts, # type: ignore[arg-type] + bwd_graph, + bwd_freevars, + ) + + # If users call ctx.mark_non_differentiable, we should capture these output tensors who + # are marked as non-differentiable and pass them to ApplyTemplate + # at torch._functorch.autograd_function.AutogradFunctionApply for reconstruction. + non_differentiable_idx = [] + if ctx.non_differentiable is not None: + non_differentiable_set = set(ctx.non_differentiable) + if not isinstance(fwd_out, variables.BaseListVariable): + raise AssertionError("Expected fwd_out to be a BaseListVariable") + for i, x in enumerate(fwd_out.items): + if x.is_tensor() and x.as_proxy() in non_differentiable_set: + non_differentiable_idx.append(i) + + dirty_idx: list[int] = [] + if ctx.dirty_tensors is not None: + dirty_tensor_set: set[Proxy] = { + x.as_proxy() for x in ctx.dirty_tensors if x.is_tensor() + } + matched_dirty_tensor_set: set[Proxy] = set() + if fwd_out.is_tensor(): + fwd_out_proxy = fwd_out.as_proxy() + if fwd_out_proxy in dirty_tensor_set: + dirty_idx.append(0) + matched_dirty_tensor_set.add(fwd_out_proxy) + else: + if not isinstance(fwd_out, variables.BaseListVariable): + raise AssertionError("Expected fwd_out to be a BaseListVariable") + for i, x in enumerate(fwd_out.items): + if x.is_tensor(): + x_proxy = x.as_proxy() + if x_proxy in dirty_tensor_set: + dirty_idx.append(i) + matched_dirty_tensor_set.add(x_proxy) + if dirty_tensor_set - matched_dirty_tensor_set: + unimplemented( + gb_type="autograd.Function.apply: mark_dirty input not returned", + context="", + explanation="Dynamo only supports ctx.mark_dirty when each " + "dirty input is also returned from forward.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # See Note [Activations with no version counter checks in eager] + # Compute which tensors in bwd_freevars came from ctx.save_for_backward. + # This allows AOT autograd to distinguish between tensors saved via + # save_for_backward vs those stashed directly on ctx (e.g., ctx.x = x). + saved_for_backward_idx = [] + if ctx.saved_tensors is not None and len(ctx.saved_tensors.tensors) > 0: + # Build a set of proxies that were passed to save_for_backward + saved_tensor_proxies = OrderedSet() + for tensor_vt in ctx.saved_tensors.tensors: + if tensor_vt.is_tensor(): + saved_tensor_proxies.add(tensor_vt.as_proxy()) + + # bwd_freevars is a dict of outer-graph proxy -> inner-graph proxy + # for all tensors passed from fwd to bwd. Find which indices + # correspond to save_for_backward tensors. + for i, fwd_proxy in enumerate(bwd_freevars.keys()): + if fwd_proxy in saved_tensor_proxies: + saved_for_backward_idx.append(i) + + # Store fwd_body + fwd_nn_modules = tx.output.tracing_context.module_context.copy_graphstate() + fwd_name = tx.output.install_subgraph( + "fwd_body", + torch.fx.GraphModule(fwd_nn_modules.nn_modules, fwd_graph), + ) + fwd_node = make_attr(tx, fwd_name) + + # Store bwd_body + bwd_nn_modules = tx.output.tracing_context.module_context.copy_graphstate() + bwd_name = tx.output.install_subgraph( + "bwd_body", + torch.fx.GraphModule(bwd_nn_modules.nn_modules, bwd_graph), + ) + bwd_node = make_attr(tx, bwd_name) + + p_args = ( + fwd_node, + bwd_node, + *list(fwd_freevars.keys()), + ) + kwargs_for_fn = { + "non_differentiable_idx": non_differentiable_idx, + "saved_for_backward_idx": saved_for_backward_idx, + } + # Preserve the existing HOP call shape for the common no-mark_dirty case. + if dirty_idx: + kwargs_for_fn["dirty_idx"] = dirty_idx + + # Store the invocation as a call + from torch._functorch.autograd_function import autograd_function_apply + + # We use speculate_subgraph to get the fwd graph, but it's always under no grad mode like what eager mode does. + # The fwd outputs (tensor's example_value) need to be inferred from fake tensor prop to get the correct attributes + # (e.g, tensor.requires_grad), which would be used by downstream Dynamo tracing. + # Since there can be other ops like Triton kernels, which depends on python dispatcher, we have to enable it. + # TODO - revisit if we need the python dispatcher + with enable_python_dispatcher(): + with tx.output.fake_mode: + fwd_freevars_args = [_get_fake_value(arg) for arg in fwd_freevars] + + example_value = autograd_function_apply( + tx.output.nn_modules[fwd_node.node.name], + tx.output.nn_modules[bwd_node.node.name], + *fwd_freevars_args, + **kwargs_for_fn, + ) + + flat_variable = add_call_function( + tx, autograd_function_apply, p_args, kwargs_for_fn, example_value + ) + # type: ignore[arg-type] + overwrite_tensor_vt_proxy(fwd_graph_output_vts, flat_variable) + # type: ignore[arg-type] + overwrite_tensor_vt_requires_grad(fwd_graph_output_vts, flat_variable) + return fwd_out + + def prepare_ctx_vt( + self, tx: "InstructionTranslatorBase", args: Any, kwargs: Any + ) -> "AutogradFunctionContextVariable": + from . import AutogradFunctionContextVariable + + ctx = AutogradFunctionContextVariable.create(tx, args, kwargs) + with discard_graph_changes(tx): + # A little hacky, but we need a dummy ctx proxy for speculate_subgraph. + # We should clean this up at some point. + proxy = tx.output.create_proxy( + "call_function", torch.autograd.function.FunctionCtx, (), {} + ) + # type: ignore[attr-defined] + set_example_value(proxy.node, ctx.value) + # type: ignore[attr-defined] + ctx.proxy = proxy + # pyrefly: ignore[bad-return] + return ctx + + def trace_forward_graph( + self, + tx: "InstructionTranslatorBase", + ctx: "AutogradFunctionContextVariable", + fwd_tracer: "SubgraphTracer", + args: Any, + kwargs: Any, + ) -> tuple[ + VariableTracker, + VariableTracker, + torch.fx.Graph, + dict[Proxy, Proxy], + VariableTracker | tuple[VariableTracker, ...], + ]: + """ + Traces the forward method of the autograd.Function object. + """ + from torch._functorch.autograd_function import DynamoAutogradFunctionTraceHelper + + fwd_fn, fwd_args = self.prepare_fn_vt(tx, ctx, "forward", args) + + # autograd.Function forward does a few things like running in no_grad + # mode and also applying view_as for input tensors that are returned as + # outputs. Therefore, we wrap the original forward in a helper that have + # those extra bits for Dynamo to trace. + fwd_fn = _make_inlined(tx, DynamoAutogradFunctionTraceHelper.fwd_trace_helper)( + fwd_fn + ) + + # Speculate subgraph on the fwd + fwd_out, fwd_graph, fwd_freevars, fwd_graph_output_vts, _ = ( + speculate_subgraph_with_auto_output_flattening( + tx, + fwd_fn, + fwd_args, + kwargs, + self._HOP_NAME, + enable_grad=None, + set_subgraph_inputs="automatic", + allow_side_effects=True, + filter_aliased_intermediates=True, + tracer=fwd_tracer, + ) + ) + + # There could be unused inputs in the forward, and Dynamo might not + # capture them. We must lift them as inputs, because even though they + # are not used in forward, we still need to account for their gradients + # in the backward. + for arg in args: + if arg.is_tensor(): + fwd_tracer.maybe_lift_tracked_freevar_to_input(arg.as_proxy()) + + if ctx in tx.output.side_effects.store_attr_mutations: + if ( + "_materialize_non_diff_grads" + in tx.output.side_effects.store_attr_mutations[ctx] + ): + unimplemented( + gb_type="autograd.Function.apply: _materialize_non_diff_grads mutation", + context="", + explanation="Mutations to autograd.Function.ctx._materialize_non_diff_grads are not supported.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + return fwd_fn, fwd_out, fwd_graph, fwd_freevars, fwd_graph_output_vts + + def trace_backward_graph( + self, + tx: "InstructionTranslatorBase", + ctx: "AutogradFunctionContextVariable", + fwd_tracer: "SubgraphTracer", + fwd_out: VariableTracker, + fwd_fn: VariableTracker, + ) -> tuple[ + list[VariableTracker], + VariableTracker, + torch.fx.Graph, + dict[Proxy, Proxy], + VariableTracker | tuple[VariableTracker, ...], + ]: + """ + Traces the backward method of the autograd.Function object. + """ + from . import UserMethodVariable + + # Note that for the forward, we do not restore side effects, because we + # want the later tracing to see the side-effects. But for backward, we + # are just trying to capture the graph, and therefore we must restore + # the side effects. + prev_side_effects = tx.output.side_effects + + # Speculate subgraph on the backward. We make the bwd tracer a child of + # the fwd tracer, because backward may rely on tensors/attrs created in + # the fwd tracer. + bwd_tracer = torch._dynamo.output_graph.SubgraphTracer( + tx.output, + parent=fwd_tracer, + source_target=self._HOP_NAME, + ) + + bwd_args = [] + if fwd_out.is_tensor(): + bwd_args.append(fwd_out) + else: + if not isinstance(fwd_out, variables.BaseListVariable): + raise AssertionError("Expected fwd_out to be a BaseListVariable") + for i in fwd_out.items: + if i.is_tensor(): + bwd_args.append(i) + else: + bwd_args.append(ConstantVariable.create(None)) + + bwd_fn, bwd_args = self.prepare_fn_vt(tx, ctx, "backward", bwd_args) + + def is_strict_for(v: VariableTracker) -> bool: + if v.is_tensor(): + # we can be more lax for stuff from forward + return v.proxy.tracer is not fwd_tracer # type: ignore[attr-defined] + return True + + # automatic_with_forced_inputs relies on the function arg names to + # create a new proxy. Also, it will always INSERT a tensor placeholder + # as input, even though it might not be used in the graph. This allows + # us to make a mapping for the backward graph. + with ( + tx.output.subtracer(fwd_fn, fwd_tracer), # type: ignore[arg-type] + tx.strict_translation_mode(is_strict_for), + ): + try: + bwd_out, bwd_graph, bwd_freevars, bwd_graph_output_vts, _ = ( + speculate_subgraph_with_auto_output_flattening( + tx, + bwd_fn, + bwd_args, + {}, + self._HOP_NAME, + # TODO - revisit if we need enable_grad + enable_grad=False, + set_subgraph_inputs="automatic_with_forced_inputs", + allow_side_effects=False, + tracer=bwd_tracer, + ) + ) + except torch._dynamo.exc.UnknownPropertiesDuringBackwardTrace as e: + # TODO - Do not support this path because of eager + # divergence forced by contiguous calls. Instead suggested + # nonstrict_trace. + from unittest import mock + + bwd_tracer = torch._dynamo.output_graph.SubgraphTracer( + tx.output, + parent=fwd_tracer, + source_target=self._HOP_NAME, + ) + from .._trace_wrapped_higher_order_op import ( + autograd_function_backward_rewritten, + ) + from .builder import SourcelessBuilder + + if isinstance(self.bwd_fn, types.FunctionType): + bwd_fn = SourcelessBuilder.create( + tx, autograd_function_backward_rewritten(self.bwd_fn) + ) + elif isinstance(self.bwd_fn, types.MethodType): + bwd_fn = UserMethodVariable( + autograd_function_backward_rewritten(self.bwd_fn.__func__), + VariableTracker.build(tx, self.bwd_fn.__class__), + ) + else: + unimplemented( + gb_type="autograd.Function.apply: non-function or method backward (2)", + context=str(self.bwd_fn), + explanation="Expected backward function to be a function or method.", + hints=[], + from_exc=e, + ) + + with mock.patch( + "torch._dynamo.config._autograd_backward_strict_mode_conditional_banned_ops", + [], + ): + bwd_out, bwd_graph, bwd_freevars, bwd_graph_output_vts, _ = ( + speculate_subgraph_with_auto_output_flattening( + tx, + bwd_fn, + bwd_args, + {}, + self._HOP_NAME, + enable_grad=False, + set_subgraph_inputs="automatic_with_forced_inputs", + allow_side_effects=False, + tracer=bwd_tracer, + ) + ) + + # Restore the side effects + tx.output.side_effects = prev_side_effects + + return bwd_args, bwd_out, bwd_graph, bwd_freevars, bwd_graph_output_vts + + def rewire_bwd_graph_outputs( + self, + fwd_freevars: dict[Proxy, Proxy], + bwd_out: VariableTracker, + bwd_graph: torch.fx.Graph, + bwd_freevars: dict[Proxy, Proxy], + orig_fwd_args: list[VariableTracker], + ) -> None: + # --------------------------------------------------------------------- + # Forward–Backward Input/Output Alignment + # + # autograd.Function requires that the outputs of backward() correspond + # exactly to the inputs of forward(). Normally this alignment is the + # user’s responsibility. However, when Dynamo synthesizes a new + # autograd.Function for a traced region, Dynamo must perform this + # alignment automatically. + # + # To do this, Dynamo uses the *original* forward call site as the anchor + # that defines how forward inputs map to backward outputs. + # + # --------------------------------------------------------------------- + # Terminology + # + # fwd_freevars / bwd_freevars: + # Maps from *outer-graph proxies* to *inner-graph placeholder + # proxies*. Keys are always outer-graph proxies (these may be actual + # user inputs or intermediate values lifted into the subgraph). + # + # orig_fwd_args: + # VariableTrackers for the forward() inputs. Since these correspond + # to user-exposed arguments, each tracker points to an *outer-graph* + # proxy. + # + # bwd_outs: + # VariableTrackers for the backward() outputs. These usually point to + # *inner-graph* proxies, except for cases where a forward input is + # passed directly through to a backward output—in which case the + # tracker may still refer to an outer-graph proxy. + # + # --------------------------------------------------------------------- + # Goal + # + # To ensure forward–backward consistency, we must rewire the backward + # graph outputs so that they line up with the forward graph inputs. + # + # We build a mapping from outer-graph proxy → inner-graph proxy using + # orig_fwd_args and bwd_outs, then iterate over the fwd_graph inputs to + # determine which backward outputs must be generated (or padded with + # None) to satisfy autograd’s calling convention. + # + # --------------------------------------------------------------------- + # Example + # + # Suppose the forward receives a user-defined object: + # + # @dataclass + # class Weird: + # x: int + # b: torch.Tensor + # c: torch.Tensor + # + # class Foo(torch.autograd.Function): + # @staticmethod + # def forward(ctx, x: torch.Tensor, weird: Weird, z: torch.Tensor): + # ctx.save_for_backward(weird.b, weird.c) + # return weird.b * weird.c * x.clone() + # + # @staticmethod + # def backward(ctx, grad): + # b, c = ctx.saved_tensors + # return grad * b * c, None, grad * 2 + # + # Dynamo lifts the tensor fields of the user-defined object for the trace: + # + # fwd_graph(): + # %l_weird_b : FakeTensor = placeholder[target=l_weird_b] + # %l_weird_c : FakeTensor = placeholder[target=l_weird_c] + # %l_x_ : FakeTensor = placeholder[target=l_x_] + # %l_z_ : FakeTensor = placeholder[target=l_z_] + # ... + # return (outs,) + # + # The initial backward graph: + # + # bwd_graph(): + # %grad : Tensor = placeholder[target=grad] + # %l_weird_b : FakeTensor = placeholder[target=l_weird_b] + # %l_weird_c : FakeTensor = placeholder[target=l_weird_c] + # ... + # return (mul_1, mul_2) + # + # The forward graph has 4 inputs, but the backward graph produces only 2 + # outputs, and their ordering does not match the forward argument order. + # + # So Dynamo rewires the backward graph outputs to align with the forward + # inputs: + # + # bwd_graph(): + # ... + # return (None, None, mul_1, mul_2) + # + # This ensures the synthesized autograd.Function conforms to PyTorch’s + # forward/backward contract. + # --------------------------------------------------------------------- + + def get_bwd_node(vt: VariableTracker) -> torch.fx.Node: + # Backward tensor vt here can be - (1) an intermediate, or (2) input + # to the backward graph. If it is an input to the backward graph, we have to lookup bwd_freevars to get the inner proxy. + return bwd_freevars.get(vt.proxy, vt.proxy).node # type: ignore[attr-defined] + + tensor_args_seen: list[Any] = [] + for arg in orig_fwd_args: + if arg.is_tensor(): + fake_tensor = _get_fake_value(arg) + if any(fake_tensor is seen for seen in tensor_args_seen): + unimplemented( + gb_type="autograd.Function.apply: duplicate tensor input", + context="", + explanation="Dynamo does not support tracing autograd.Function.apply " + "when the same tensor is passed to multiple forward inputs.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + tensor_args_seen.append(fake_tensor) + + # Find the mapping between orig_fwd_args and bwd_out + # pyrefly: ignore [implicit-any] + outer_fwd_proxy_to_bwd_node = {} + if isinstance(bwd_out, variables.BaseListVariable): + bwd_outs = bwd_out.items + for idx, fwd_arg in enumerate(orig_fwd_args): + # We care about tensor args. For non-tensor args, the bwd output returns None. + if fwd_arg.is_tensor(): + bwd_out_at_idx = bwd_outs[idx] + if bwd_out_at_idx.is_tensor(): + # type: ignore[attr-defined] + outer_fwd_proxy_to_bwd_node[fwd_arg.proxy] = get_bwd_node( + bwd_out_at_idx + ) + else: + # backward can return None at the output + if not isinstance(bwd_out_at_idx, variables.ConstantVariable): + raise AssertionError( + "Expected backward output to be a ConstantVariable" + ) + if bwd_out_at_idx.value is not None: + raise AssertionError( + "Expected backward output ConstantVariable to have value None" + ) + # type: ignore[attr-defined] + outer_fwd_proxy_to_bwd_node[fwd_arg.proxy] = None + + elif bwd_out.is_tensor(): + # type: ignore[attr-defined] + outer_fwd_proxy_to_bwd_node[orig_fwd_args[0].proxy] = get_bwd_node(bwd_out) + + # Ideally, we should have walked through the fwd placeholders. But we + # can instead walk through the fwd_freevars, which is a insertion sorted + # dictionary and therefore represents the outer_proxies for the + # placeholder in the same order as that as placeholders. + rewired_bwd_outputs = [ + outer_fwd_proxy_to_bwd_node.get(fwd_proxy) for fwd_proxy in fwd_freevars + ] + + for node in bwd_graph.find_nodes(op="output"): + bwd_graph.erase_node(node) + break + bwd_graph.output(tuple(rewired_bwd_outputs)) + bwd_graph.lint() + + def handle_saved_tensors_wiring( + self, + fwd_out: VariableTracker, + fwd_graph: torch.fx.Graph, + fwd_freevars: dict[Proxy, Proxy], + fwd_graph_body_outputs: list[VariableTracker], + bwd_graph: torch.fx.Graph, + bwd_freevars: dict[Proxy, Proxy], + ) -> tuple[torch.fx.Graph, torch.fx.Graph]: + # --------------------------------------------------------------------- + # Rewiring Forward Outputs to Backward Inputs (and Handling Saved Tensors) + # + # In `rewire_bwd_graph_outputs`, we aligned the *forward inputs* with the + # *backward outputs*. This method performs the complementary task: + # aligning the *forward outputs* with the *backward inputs*, while also + # incorporating all tensors saved via ctx.save_for_backward. + # + # There are two main issues we must resolve: + # + # (1) Forward outputs may contain non-tensor values. + # This means the number of tensors visible in fwd_out may not match + # the number of tensors produced by the traced forward graph. As a + # result, the backward graph’s placeholders may not line up with the + # actual tensor outputs. + # + # (2) The backward graph may require intermediate tensors saved during + # the forward pass (via save_for_backward), but those intermediates + # might not currently be included among the forward graph’s outputs. + # + # Together, these issues mean that the bwd_graph input signature may be + # inconsistent with what fwd_graph outputs, and we need to rewrite both. + # + # Lets look at an example to understand the transformation + # + # class Add(torch.autograd.Function): + # @staticmethod + # def forward(ctx, x, y): + # a = torch.sin(x) + # b = torch.cos(y) + # ctx.save_for_backward(a) + # return Foo(a, b), x * y + + # @staticmethod + # def backward(ctx, grad_a, grad_b): + # (a,) = ctx.saved_tensors + # return grad_b * 2, a * grad_b * 3 + + # Before + # fwd_graph(): + # %l_x_ : torch._subclasses.fake_tensor.FakeTensor [num_users=2] = placeholder[target=l_x_] + # %l_y_ : torch._subclasses.fake_tensor.FakeTensor [num_users=2] = placeholder[target=l_y_] + # .... + # return (a, b, out) + # + # bwd_graph(): + # %grad_b : torch.Tensor [num_users=2] = placeholder[target=grad_b] + # %a : torch._subclasses.fake_tensor.FakeTensor [num_users=1] = placeholder[target=a] + # .... + # return (mul, mul_2) + # + # The problems here: + # (1) fwd_graph has 3 tensor outputs (a, b, out), but bwd_graph has + # only 1 gradient input - grad_b. We need 3. + # + # (2) bwd_graph uses `a` (a saved tensor) as an input, but fwd_graph + # does not currently return `a`. To make `a` available to the + # backward graph, the forward graph must expose it as part of its + # output signature. + # + # After this transformation + # fwd_graph(): + # %l_x_ : torch._subclasses.fake_tensor.FakeTensor [num_users=2] = placeholder[target=l_x_] + # %l_y_ : torch._subclasses.fake_tensor.FakeTensor [num_users=2] = placeholder[target=l_y_] + # ..... + # return ((a, b, out), (a,)) + # bwd_graph(): + # %unused_0 : [num_users=0] = placeholder[target=unused_0] + # %unused_1 : [num_users=0] = placeholder[target=unused_1] + # %grad_b : [num_users=2] = placeholder[target=grad_b] + # %a : [num_users=1] = placeholder[target=a] + # ..... + # return (mul, mul_2) + # + # Key changes: + # + # 1) The forward graph now returns: + # (existing_outputs), (saved_tensors) + # This exposes saved intermediates (`a`) as part of the fwd output + # structure, making them available to backward. + # + # 2) The backward graph input signature is rewritten to: + # (*grads_for_existing_outputs, *saved_tensors) + # This ensures the counts and ordering match the new fwd_graph + # output structure. Placeholders corresponding to tensors whose + # gradients are unused (e.g., `a`, `b`) appear as `%unused_*`. + # + # This alignment ensures that the synthesized autograd.Function follows + # PyTorch’s forward/backward calling convention and that all required + # saved tensors are available to the backward graph. + # --------------------------------------------------------------------- + + # To address Problem (1), we must determine which backward-graph inputs + # correspond to the forward-graph outputs. + # + # We use two facts: + # • `fwd_out` preserves the original forward output order. + # • Backward-graph inputs are also ordered according to the backward() + # method signature, thanks to automatic_with_forced_inputs. + # + # For any forward output that is *not* a tensor, there is no + # corresponding tensor placeholder in the backward graph. During tracing, + # we intentionally inserted a `None` VariableTracker for these positions, + # so the backward graph contains no placeholder for them. + bwd_input_nodes = list(bwd_graph.find_nodes(op="placeholder")) + # pyrefly: ignore [implicit-any] + fwd_vt_to_bwd_node = {} + bwd_idx = 0 + if isinstance(fwd_out, variables.BaseListVariable): + for fwd_vt in fwd_out.items: + if fwd_vt.is_tensor(): + fwd_vt_to_bwd_node[fwd_vt] = bwd_input_nodes[bwd_idx] + bwd_idx += 1 + else: + if fwd_out.is_tensor(): + fwd_vt_to_bwd_node[fwd_out] = bwd_input_nodes[bwd_idx] + bwd_idx += 1 + + rewired_bwd_graph_inputs = [] + for fwd_graph_vt in fwd_graph_body_outputs: + # for tensor vts that were part of a user-defined object (like in + # the above example), we just set None for now. Later, we will use + # these None to insert a unused placeholder. + # type: ignore[arg-type] + rewired_bwd_graph_inputs.append(fwd_vt_to_bwd_node.get(fwd_graph_vt)) + + # To address Problem (2), we must incorporate any tensors that were saved + # (or otherwise smuggled) from the forward pass into the backward graph. + # + # Fortunately, these are easy to identify: they appear in `bwd_freevars`. + # `bwd_freevars` maps outer-graph lifted proxies to inner-graph placeholder + # proxies. Because the backward graph is traced using proxies originating + # from `fwd_out`, any value lifted into the backward graph represents a + # saved/smuggled tensor. + # + # Once we identify these saved tensors, we must also locate their + # corresponding forward-graph proxies so that the forward graph can return + # these tensors as part of its output signature. + extra_fwd_output_nodes = [] + for fwd_proxy, bwd_inner_proxy in bwd_freevars.items(): + # For backward, its easy, just get the node from bwd_inner_proxy + rewired_bwd_graph_inputs.append(bwd_inner_proxy.node) + + # For the fwd_proxy, it could be a proxy from the outer graph, or it + # could be an intermediate. + # First ensure that's its inner fwd proxy + inner_fwd_proxy = fwd_freevars.get(fwd_proxy, fwd_proxy) + extra_fwd_output_nodes.append(inner_fwd_proxy.node) + + # Mechanical steps from here on. We have the extra_fwd_outputs and rewired_bwd_inputs. Lets make the changes. + # Lets change the fwd graph outputs. + # pyrefly: ignore [implicit-any] + fwd_output_nodes = [] + for node in fwd_graph.find_nodes(op="output"): + fwd_output_nodes = node.args[0] + fwd_graph.erase_node(node) + break + + # The signature is now ((*existing_outputs), (*extra_outputs)). Please + # take a look at AutogradFunctionApply where we take the saved_tensors + # out in the forward method to save for backward. + new_fwd_graph_outputs = (fwd_output_nodes, tuple(extra_fwd_output_nodes)) + fwd_graph.output(new_fwd_graph_outputs) + fwd_graph.lint() + + # Now lets change the bwd graph. + new_graph = torch.fx.Graph() + env = {} + + count = itertools.count() + + for node in rewired_bwd_graph_inputs: + if node is None: + new_node = new_graph.placeholder(f"unused_{next(count)}") + else: + new_node = new_graph.placeholder(node.name) + new_node.meta = copy.copy(node.meta) + env[node] = new_node + + for node in bwd_graph.nodes: + if node.op == "placeholder": + if node not in env: + raise AssertionError("Placeholder node not found in env") + else: + env[node] = new_graph.node_copy(node, lambda x: env[x]) + env[node].meta = copy.copy(node.meta) + + new_graph.lint() + return fwd_graph, new_graph + + def prepare_fn_vt( + self, + tx: "InstructionTranslatorBase", + ctx: "AutogradFunctionContextVariable", + method_name: str, + args: list[VariableTracker], + ) -> tuple[VariableTracker, list[VariableTracker]]: + from . import UserMethodVariable + + source = None + if self.parent_source: + source = AttrSource(self.parent_source, member=method_name) + + if method_name == "forward": + fn = self.fwd_fn + else: + fn = self.bwd_fn + + fn_vt, fn_args = None, None + if isinstance(fn, types.FunctionType): + fn_vt = VariableTracker.build(tx, fn, source=source) + fn_args = [ctx, *args] + elif isinstance(fn, types.MethodType): + cls_vt = VariableTracker.build(tx, fn.__class__) + fn_vt = UserMethodVariable( + fn.__func__, + cls_vt, + source=source, + ) + fn_args = [cls_vt, ctx, *args] + else: + unimplemented( + gb_type="autograd.Function.apply: non-function or method forward", + context=str(fn), + explanation=f"Expected {method_name} to be a function or method.", + hints=[], + ) + if fn_vt is None: + raise AssertionError("fn_vt must not be None") + if fn_args is None: + raise AssertionError("fn_args must not be None") + return fn_vt, fn_args + + +def _get_fake_value(x: Union[VariableTracker, Proxy, "FakeTensor"]) -> "FakeTensor": + if isinstance(x, variables.VariableTracker): + return x.as_proxy().node.meta["example_value"] + elif isinstance(x, torch.fx.Proxy): + return x.node.meta["example_value"] + else: + return x + + +def maybe_positional_arg_names(func: VariableTracker) -> list[str] | None: + result = [] + if not hasattr(func, "get_function"): + return None + try: + fn = func.get_function() + except (Unsupported, NotImplementedError): + return None + try: + sig = inspect.signature(fn) + except ValueError: + return None + for name, param in sig.parameters.items(): + if param.kind is inspect.Parameter.VAR_POSITIONAL: + return None + if ( + param.kind is inspect.Parameter.POSITIONAL_ONLY + or param.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD + ): + if name == "self": + # FX graphs can't have a placeholder named self + result.append("self_") + else: + result.append(name) + return result + + +class BaseHOPVariable(WrapHigherOrderVariable): + # Generic fallback for BaseHOP instances not explicitly mapped + # The actual HOP name comes from self.value._name at runtime + _HOP_NAME = "base HOP (name not yet determined)" + supports_input_mutation = False + supports_aliasing = False + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._HOP_NAME = self.value._name + + def python_type(self) -> type: + return type(self.value) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + ( + p_args, + p_kwargs, + example_value, + body_r, + _, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, args[0], args[1:], {}, self.value._name, subgraph_name="subgraph" + ) + if len(p_kwargs) != 0: + raise AssertionError("Expected p_kwargs to be empty") + + p_kwargs = {key: value.as_proxy() for key, value in kwargs.items()} + return _call_function_with_auto_output_flattening( # type: ignore[return-value] + tx, + self.value, + p_args, + p_kwargs, + example_value, + body_r, + body_graph_output_vts, + ) + + +class LocalMapWrappedHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.ops.higher_order.local_map_hop" + supports_input_mutation = False + supports_aliasing = False + + # Subclasses aren't supported by speculate_subgraph yet + # So this HOP is only usable with plain tensors + _enabled = False + + @classmethod + @contextlib.contextmanager + def enable(cls) -> Generator[None, None, None]: + """Context manager to temporarily enable local map wrapping. + Will be removed when speculate_subgraph supports subclass inputs: + https://github.com/pytorch/pytorch/issues/161456. + + Usage: + with LocalMapWrappedHigherOrderVariable.enable_wrapping(): + # Code where should_wrap_in_hop will return True + pass + """ + old_value = cls._enabled + cls._enabled = True + try: + yield + finally: + cls._enabled = old_value + + @classmethod + def should_wrap_in_hop(cls, value: Any) -> bool: + if not torch.distributed.is_available(): + return False + + from torch.distributed.tensor.experimental._func_map import _local_map_wrapped + + # check is important to avoid subclass dispatch + if type(value) is not type(_local_map_wrapped): + return False + + return value is _local_map_wrapped and cls._enabled + + @staticmethod + # pyrefly: ignore[bad-override] + def build(**options: Any) -> "TorchHigherOrderOperatorVariable": + return TorchHigherOrderOperatorVariable.make( + torch._higher_order_ops.local_map_hop, + **options, + ) + + def python_type(self) -> type: + return type(self.value) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """ + Goal of this function is to rewrite local_map usage as a HOP: + local_map(func, ...) -> local_map_hop(gm, ...) + """ + + ( + user_func, + out_placements, + in_placements, + in_grad_placements, + device_mesh, + redistribute_inputs, + enable_spmd_types, + *user_args, + ) = args + + # None placements are used to pass non-Tensors into the local_map function. + # Containers passed this way can not hold tensors. Thus, Dynamo would have inlined + # into them, and we handle None placements by assuming they will be desugared away. + # This will need to be adjusted for dynamic shapes support. + def check_none_last(placements: Sequence[Any | None]) -> int: + seen_none = 0 + for p in placements: + if p is None: + seen_none += 1 + else: + if seen_none != 0: + raise AssertionError( + "Tracing local_map is only currently supported with None placements last." + ) + return seen_none + + inputs_none_placements = check_none_last(in_placements.value) # type: ignore[attr-defined] + output_none_placements = check_none_last(out_placements.value) # type: ignore[attr-defined] + + local_map_kwargs = { + "out_placements": out_placements.value, # type: ignore[attr-defined] + "in_placements": in_placements.value, # type: ignore[attr-defined] + "redistribute_inputs": redistribute_inputs.value, # type: ignore[attr-defined] + "in_grad_placements": in_grad_placements.value, # type: ignore[attr-defined] + "device_mesh": device_mesh.value, # type: ignore[attr-defined] + } + if local_map_kwargs["device_mesh"] is None: + raise AssertionError( + "Not yet implemented, please manually provide a device_mesh to local_map." + ) + mesh = local_map_kwargs["device_mesh"] + + # For Autoparallel, the initial trace is done with global shapes, then we decide model weights sharding, + # and reuse the graph. Since the sharding decision is after the initial trace, we can't trace with local shapes. + # For local_map however, since we specify all placements, we can trace with local shapes. + + # Step 1: Validate the annotated function matches the input_placements (i.e. that it can run in eager) + template = ( + "Expecting {expected} {inputs_or_outputs} to local_map function based on placements" + ", but found {actual}. Please ensure the count matches for eager. " + ) + if len(in_placements.value) != len(user_args): # type: ignore[attr-defined] + raise AssertionError( + template.format( + expected=len(in_placements.value), # type: ignore[attr-defined] + inputs_or_outputs="inputs", + actual=len(user_args), + ) + ) + + from torch._higher_order_ops.local_map import ( + redistribute_fw_inputs, + redistribute_fw_outputs, + ) + + # Step 2: Convert inputs to local shapes + priors = {} + for placements, vt in zip(in_placements.value, user_args): # type: ignore[attr-defined] + if isinstance(vt, variables.lazy.LazyVariableTracker): + vt = variables.lazy.LazyVariableTracker.realize_all(vt) + + if not vt.is_tensor(): + if placements is not None: + raise AssertionError( + "Expected placements to be None for non-tensor input" + ) + continue + + global_tensor = vt.as_proxy().node.meta["example_value"] + # NOTE: We don't support local_map region relying on exact grad_fn information + # This is okay since accessing grad_fn is a graph break. + local_tensor = redistribute_fw_inputs( + (global_tensor,), + (placements,), + mesh, + ) + local_tensor = local_tensor[0] + + priors[vt] = global_tensor + vt.as_proxy().node.meta["example_value"] = local_tensor + # pyrefly: ignore [missing-attribute] + vt.synchronize_attributes(tx) + + # Step 3: Trace local_map subgraph with local tensors + # + # Use "automatic_with_forced_inputs" so subgraph placeholders are + # created eagerly in the user's call-site arg order. Under "automatic", + # Dynamo lifts freevars in first-use order, which diverges between + # static and dynamic shapes (e.g. `x.shape[-1]` early in the body lifts + # `x` first under dynamic shapes but constant-folds under static). The + # forced mode keeps `in_placements` aligned with user args regardless. + ( + p_args, + p_kwargs, + example_value, + body_r, + body_gmod, + body_name, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, + user_func, + user_args, + kwargs, + self.value._name, + subgraph_name="subgraph", + set_subgraph_inputs="automatic_with_forced_inputs", + ) + + # Step 4: Validate traced graph signature still matches placement information + expected_num_inputs = len(in_placements.value) - inputs_none_placements # type: ignore[attr-defined] + actual_num_inputs = len(body_gmod.graph.find_nodes(op="placeholder")) + expected_num_outputs = len(out_placements.value) - output_none_placements # type: ignore[attr-defined] + if len(body_gmod.graph.find_nodes(op="output")) != 1: + raise AssertionError("Expected exactly one output node in body graph") + actual_num_outputs = len(body_gmod.graph.find_nodes(op="output")[0].args[0]) + + template = ( + "Expecting {expected} {inputs_or_outputs} to local_map function based on placements" + ", but found {actual}. If the count matches for eager, " + "Dynamo may have flattened {inputs_or_outputs} to the function or found additional " + "tensors used via closures. " + "Please adjust the input placements to match what the traced graph sees: \n{gm_str}." + ) + + def make_error_msg(*args: Any) -> str: + expected_num, actual_num, inputs_or_outputs = args + gm_str = body_gmod.print_readable(print_output=False) + return template.format( + expected=expected_num, + inputs_or_outputs=inputs_or_outputs, + actual=actual_num, + gm_str=gm_str, + ) + + if expected_num_inputs != actual_num_inputs: + raise AssertionError( + make_error_msg(expected_num_inputs, actual_num_inputs, "inputs") + ) + if expected_num_outputs != actual_num_outputs: + raise AssertionError( + make_error_msg(expected_num_outputs, actual_num_outputs, "outputs") + ) + + if inputs_none_placements > 0: + expected_input_nodes = [ + arg.as_proxy().node for arg in user_args[:-inputs_none_placements] + ] + else: + expected_input_nodes = [arg.as_proxy().node for arg in user_args] + actual_input_nodes = [proxy.node for proxy in p_args] + if actual_input_nodes[0].op != "get_attr": + raise AssertionError("Expected first actual input node op to be 'get_attr'") + if "subgraph" not in actual_input_nodes[0].target: # type: ignore[attr-defined] + raise AssertionError( + "Expected 'subgraph' in first actual input node target" + ) + if expected_input_nodes != actual_input_nodes[1:]: + raise AssertionError( + "local_map: unexpected argument ordering. Outer HOP args did " + "not match user call-site order " + f"(expected={expected_input_nodes}, actual={actual_input_nodes[1:]}). " + "automatic_with_forced_inputs should have preserved order; " + "please file an issue at https://github.com/pytorch/pytorch/issues." + ) + if len(p_kwargs) != 0: + raise AssertionError("Expected p_kwargs to be empty") + + # Step 5: Install local_map subgraph + p_kwargs = {key: value.as_proxy() for key, value in kwargs.items()} + out = _call_function_with_auto_output_flattening( + tx, + self.value, + p_args, + p_kwargs, + example_value, + body_r, + body_graph_output_vts, + ) + + # Step 6: Restore inputs and outputs to global shapes + for vt, global_tensor in priors.items(): + vt.as_proxy().node.meta["example_value"] = global_tensor + # pyrefly: ignore [missing-attribute] + vt.synchronize_attributes(tx) + + outs = out.items if isinstance(out, TupleVariable) else [out] + if len(outs) != len(out_placements.value): # type: ignore[attr-defined] + raise AssertionError( + "Number of outputs must match number of out_placements" + ) + for placements, vt in zip(out_placements.value, outs): # type: ignore[attr-defined] + if not vt.is_tensor(): # type: ignore[attr-defined] + if placements is not None: + raise AssertionError( + "Expected placements to be None for non-tensor output" + ) + continue + + local_tensor = vt.as_proxy().node.meta["example_value"] # type: ignore[attr-defined] + + # NOTE: We don't support code after the local_map region relying on exact grad_fn information + # This is okay since accessing grad_fn is a graph break. + global_tensor = redistribute_fw_outputs( + (local_tensor,), + (placements,), + mesh, + num_activations=0, # this is not the joint + ) + global_tensor = global_tensor[0] + + vt.as_proxy().node.meta["example_value"] = global_tensor # type: ignore[attr-defined] + vt.synchronize_attributes(tx) # type: ignore[attr-defined] + + # TODO: Figure out how to handle output order diverging from eager + + # Treat as const, so we don't have to deal with Placement types in fx IR + # Guarded with EQUALS_MATCH on local_map call's arguments + body_gmod.meta["local_map_kwargs"] = { + "out_placements": out_placements.value[:expected_num_outputs], # type: ignore[attr-defined] + "in_placements": in_placements.value[:expected_num_inputs], # type: ignore[attr-defined] + "redistribute_inputs": redistribute_inputs.value, # type: ignore[attr-defined] + "in_grad_placements": in_grad_placements.value, # type: ignore[attr-defined] + "device_mesh": device_mesh.value, # type: ignore[attr-defined] + } + if out is None: + raise AssertionError("out must not be None") + return out + + +from .invoke_subgraph import InvokeSubgraphHigherOrderVariable + + +# Map operator names to their corresponding variable for fast TorchHigherOrderOperatorVariable.make() +_hop_name_to_variable_class = { + "cond": CondHigherOrderVariable, + "switch": SwitchHigherOrderVariable, + "while_loop": WhileLoopHigherOrderVariable, + "while_loop_stack_output": WhileLoopStackOutputHigherOrderVariable, + "map_impl": MapHigherOrderVariable, + "executorch_call_delegate": ExecutorchCallDelegateHigherOrderVariable, + "out_dtype": OutDtypeHigherOrderVariable, + "wrap": WrapHigherOrderVariable, + "hints_wrapper": HintsWrapperHigherOrderVariable, + "flex_gemm": FlexGemmHigherOrderVariable, + "flex_attention": FlexAttentionHigherOrderVariable, + "flex_attention_backward": FlexAttentionBackwardHighOrderVariable, + "wrap_activation_checkpoint": CheckpointHigherOrderVariable, + "tag_activation_checkpoint": CheckpointHigherOrderVariable, + "_export_tracepoint": ExportTracepointHigherOrderVariable, + "trace_wrapped": TraceWrappedHigherOrderOperatorVariable, + "strict_mode": StrictModeHigherOrderVariable, + "run_with_rng_state": RunWithRNGStateHigherOrderVariable, + "associative_scan": AssociativeScanHigherOrderVariable, + "scan": ScanHigherOrderVariable, + "call_torchbind": CallTorchbindHigherOrderVariable, + "print": PrintHigherOrderVariable, + "wrap_with_set_grad_enabled": WrapWithSetGradEnabledHigherOrderVariable, + "wrap_with_autocast": WrapWithAutocastHigherOrderVariable, + "dynamo_bypassing_wrapper": DynamoBypassingWrapperHigherOrderVariable, + "auto_functionalized": AutoFunctionalizeHigherOrderVariable, + "auto_functionalized_v2": AutoFunctionalizeHigherOrderVariable, + "inline_asm_elementwise": InlineAsmElementwiseHigherOrderVariable, + "invoke_subgraph": InvokeSubgraphHigherOrderVariable, + "custom_function_call": CustomFunctionHigherOrderOperatorVariable, + "local_map_hop": LocalMapWrappedHigherOrderVariable, +} diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/invoke_subgraph.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/invoke_subgraph.py new file mode 100644 index 0000000000000000000000000000000000000000..4ace18194412831cecefd5e5ce21c355109296b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/invoke_subgraph.py @@ -0,0 +1,1492 @@ +""" +This module contains the InvokeSubgraphHigherOrderVariable class and its +supporting helpers for subgraph reuse (auto-cache) in Dynamo's invoke_subgraph +higher-order operator. +""" + +import collections +import enum +import logging +import traceback +import types +from dataclasses import dataclass +from typing import Any, cast, NamedTuple, TYPE_CHECKING, TypeGuard + +import torch +import torch._higher_order_ops +from torch._dynamo import graph_break_hints +from torch._dynamo.exc import unimplemented +from torch._dynamo.guards import ( + extract_tensor_metadata, + GUARD_VALUE_DISPATCH, + GuardCheckSpec, + SKIP_GUARD, + UnsupportedGuardCheckSpec, +) +from torch._dynamo.source import SyntheticLocalSource +from torch._dynamo.utils import _make_inlined, unpack_iterable +from torch._dynamo.variables.base import VariableTracker +from torch._dynamo.variables.constant import ConstantVariable +from torch._dynamo.variables.functions import UserFunctionVariable +from torch._dynamo.variables.higher_order_ops import WrapHigherOrderVariable +from torch._dynamo.variables.lists import ListVariable, TupleVariable +from torch._dynamo.variables.nn_module import UnspecializedNNModuleVariable +from torch._dynamo.variables.tensor import SymNodeVariable, TensorVariable +from torch._dynamo.variables.user_defined import UserDefinedObjectVariable +from torch._guards import ( + Guard, + InvokeSubgraphReuseCondition, + InvokeSubgraphReuseEntry, + Source, +) +from torch._higher_order_ops.invoke_subgraph import NestedCompileRegionOptions +from torch.fx.graph_module import GraphModule +from torch.fx.proxy import Proxy +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.higher_order_ops import SubgraphTracingInfo + +log = logging.getLogger(__name__) +hc_log = torch._logging.getArtifactLogger(__name__, "hierarchical_compile") + +# Note: [invoke_subgraph subgraph reuse] +# +# When mark_compile_region wraps a function called N times (e.g. 80 identical +# transformer layers), Dynamo traces the subgraph once and stamps out cached +# copies for subsequent calls. It does safety checks to ensure that a subgraph +# is reusable, if not (e.g. side-effect), it will fallback to tracing the +# next invocation. +# +# HIGH-LEVEL FLOW +# =============== +# User code: model.layers[0](x), model.layers[1](x), ..., model.layers[79](x) +# | | | +# v v v +# +--------------+ +--------------+ +--------------+ +# | First Call | | Second Call | ... | 80th Call | +# +------+-------+ +------+-------+ +------+-------+ +# | | | +# v v v +# +--------------+ +--------------+ +--------------+ +# | Full subgraph| | Cache lookup | | Cache lookup | +# | trace | | (is_reusable) | | (is_reusable) | +# +------+-------+ +------+-------+ +------+-------+ +# | | | +# v v v +# +--------------+ +--------------+ +--------------+ +# | save_reuse_ | | stamp_out_ | | stamp_out_ | +# | entry() | | subgraph() | | subgraph() | +# +--------------+ +--------------+ +--------------+ +# +# WHAT GETS CACHED +# ================ +# After the first trace, save_reuse_entry stores an InvokeSubgraphReuseEntry +# (in _guards.py) containing: +# - body_name/body_gmod: the traced subgraph +# - arg_sources: sources of the original call's arguments +# - subgraph_input_mapping: how each lifted arg maps back to user inputs or captures +# - output_metadata: shape/stride/dtype/device of outputs +# +# Paired with an InvokeSubgraphReuseCondition containing: +# - input_checks: (tag, tensor_metadata) per input +# - guards: (source, handler, expected, guard) tuples +# - treespec: pytree structure of the args +# - traced_sources: sources accessed during the trace +# +# CACHE LOOKUP (is_reusable) +# ========================== +# On subsequent calls: +# 1. Input structure match -- same treespec, tags, tensor metadata. +# 2. Source replacement -- clone each guard's source with a replacement map +# (old: L['self'].layers[0].weight -> new: L['self'].layers[1].weight), +# then evaluate against the new source's runtime value. +# 3. Mutation check -- reject if the subgraph mutated any captured var. +# +# A shared resolve_cache memoizes intermediate source resolution (e.g. +# L['self'].layers is evaluated once and reused across all guards). +# +# STAMP OUT (stamp_out_subgraph) +# ============================== +# On cache hit, reconstruct the argument list using the freevar mapping +# (list[LiftedArgOrigin]): +# +# LiftedUserArg(index) +# User arg (activation / explicit input). +# Looked up from new call's flat proxies. +# +# LiftedCapturedSource(source) +# Sourceful captured var (weight, param, etc). +# Source is cloned with replacement map, resolved via +# VariableBuilder. Deduplicates via input_source_to_var. +# +# LiftedSyntheticObject(ctor_fn, ctor_args, ctor_arg_sources) +# Synthetic object (opaque type with SyntheticLocalSource). +# Reconstructed via synthetic_graph_input with cached constructor info. +# +# SAFETY +# ====== +# In normal Dynamo compilation, safety is enforced at runtime: guards are +# installed during tracing and re-evaluated on every subsequent call against +# real Python objects. Subgraph reuse operates differently — we are in the +# middle of tracing, there are no real Python objects, only VariableTrackers. +# We must answer: what could cause the second invocation of a nested compile +# region to produce a different trace than the first? +# +# VariableTrackers fall into two categories: +# +# 1. Intermediates — values produced during tracing with no originating source +# (e.g. the result of a prior FX op). These can reach a nested compile region +# only via (a) the region's explicit function arguments, or (b) closure +# capture. We do not support nested-function regions that close over tensors, +# so only (a) applies. For explicit arguments, the set of types we support is +# small and well-defined: TensorVariable, SymNodeVariable, and +# ConstantVariable (enum members included). Each has a cheap structural +# comparison (tensor metadata, symnode identity, constant value equality). +# We also snapshot the pytree treespec of the argument list and verify it +# matches on lookup, ensuring the flattened structure is identical. +# A sourceless object -- an nn.Module built during tracing, say -- has +# neither a structural comparison nor guards, so it is not eligible at all. +# +# 2. Sourceful variables — values with a known originating source (e.g. a +# module attribute or a local variable visible in the outer frame). For these +# we collect the guard delta from the first trace, parameterize the guard +# sources by replacing the original arg sources with the new arg sources, and +# re-evaluate the guards by resolving each source against the live f_locals / +# f_globals. The one extra hazard here is mutation: if the outer trace +# mutates a sourceful object between the first and second invocations, the +# cached guards would evaluate against stale values. We therefore also check +# that none of the sources read by the cached subgraph have been mutated in +# the outer SideEffects tracker before accepting a reuse. +# +# - max_reuse_entries (default 8, configurable via nested_compile_region arg) +# caps cache entries per function. Exceeding it raises RuntimeError. +# - Guard failures logged with guard type + user stack trace. +# Enable: TORCH_LOGS='+hierarchical_compile' +# --------------------------------------------------------------------------- +# Auto-cache helpers for invoke_subgraph +# --------------------------------------------------------------------------- + + +class InputTag(enum.Enum): + TENSOR = "tensor" + SYMNODE = "symnode" + CONSTANT = "constant" + OBJECT = "object" + + +class InputFingerprint(NamedTuple): + # (InputTag, VariableTracker) pairs for each leaf input. + flat_vts: list[tuple[InputTag, VariableTracker]] + # 1-1 mapping to flat_vts: source for each leaf, or None if the VT has no source. + arg_sources: list[Source | None] + # True if any leaf VT had an unsupported type for reuse. + has_unknown: bool = False + # TreeSpec from pytree.tree_flatten of the (args, kwargs) structure. + treespec: pytree.TreeSpec | None = None + + +def is_constant_like( + vt: Any, +) -> TypeGuard[ConstantVariable | UserDefinedObjectVariable]: + """Whether a leaf VT is compared by value, via ``vt.value``. + + Enum members are UserDefinedObjectVariable (not ConstantVariable) in + Dynamo, but they are immutable singletons, so value comparison is as + sound as it is for ConstantVariable. + """ + if isinstance(vt, ConstantVariable): + return True + return isinstance(vt, UserDefinedObjectVariable) and isinstance(vt.value, enum.Enum) + + +def classify_vt(vt: Any) -> InputTag | None: + """Return the tag for a leaf VT, or None if unsupported.""" + if isinstance(vt, TensorVariable): + return InputTag.TENSOR + elif isinstance(vt, SymNodeVariable): + return InputTag.SYMNODE + elif is_constant_like(vt): + return InputTag.CONSTANT + elif isinstance(vt, UserDefinedObjectVariable) and vt.source is not None: + # Covers nn.Modules too -- UnspecializedNNModuleVariable is a + # UserDefinedObjectVariable subclass. No metadata is recorded; reuse + # safety comes entirely from re-evaluating the guards installed on this + # object's source and on the sources derived from it. A sourceless + # object has no guards to re-evaluate, so it stays unsupported. + return InputTag.OBJECT + return None + + +def build_input_fingerprint( + tx: "InstructionTranslatorBase", + fn_args_vt: Any, + kwargs: dict[str, Any], +) -> InputFingerprint: + """Build an InputFingerprint by flattening (args, kwargs) via pytree. + + Flattens the argument structure into leaf VTs, classifying each leaf as + tensor/symnode/constant/module. Also records the TreeSpec so that + cache lookups can verify structural equivalence. + + Fast path: when kwargs is empty and all args are already leaf VTs + (tensor/symnode/constant/module), skip the pytree flatten entirely. + """ + # Fast path: flat args, no kwargs — skip pytree machinery. + if not kwargs: + all_leaf = True + for vt in fn_args_vt: + if classify_vt(vt) is None: + all_leaf = False + break + if all_leaf: + return build_fingerprint_fast(fn_args_vt) + + return build_fingerprint_with_pytree(tx, fn_args_vt, kwargs) + + +def build_fingerprint_fast(fn_args_vt: Any) -> InputFingerprint: + """Build fingerprint for the common case of flat leaf args, no kwargs.""" + flat_vts: list[tuple[InputTag, VariableTracker]] = [] + arg_sources: list[Source | None] = [] + for vt in fn_args_vt: + tag = classify_vt(vt) + if tag is None: + raise AssertionError( + f"classify_vt returned None for {type(vt).__name__} in fast path" + ) + flat_vts.append((tag, vt)) + # Always append (even None) to keep positional alignment with flat_vts + # so that source_replacement zip pairing is correct across calls. + arg_sources.append(getattr(vt, "source", None)) + return InputFingerprint(flat_vts, arg_sources) + + +def build_fingerprint_with_pytree( + tx: "InstructionTranslatorBase", + fn_args_vt: Any, + kwargs: dict[str, Any], +) -> InputFingerprint: + """Build fingerprint via pytree flatten for nested/kwargs cases. + + Recurses over the pytree structure natively (untraced), inlining/tracing + only each container node's own ``flatten_fn`` rather than the full + recursive tree_flatten dispatch around it. This is safe because node-type + classification only depends on ``type()``, never on tensor values. + + Note: skipping the traced registry dispatch also means we no longer + install guards on the pytree registry itself, for the plain-function + flatten_fn case (the non-FunctionType fallback below still traces the + full tree_flatten and so still installs them). That's fine either way: + this fingerprint is built fresh from the live registry on every + reuse-lookup (register_pytree_node isn't traceable, so the registry + can't change mid-trace), and reuse is separately gated on treespec/tag + equality. So a registry change between compiles can only make a cached + subgraph ineligible for reuse (has_unknown / treespec mismatch), never + silently wrong. + """ + from torch._dynamo.variables.builder import SourcelessBuilder + + flat_vts: list[tuple[InputTag, VariableTracker]] = [] + arg_sources: list[Source | None] = [] + has_unknown = False + + def add_leaf(vt: VariableTracker) -> None: + nonlocal has_unknown + tag = classify_vt(vt) + if tag is None: + has_unknown = True + else: + flat_vts.append((tag, vt)) + # Always append (even None) to keep positional alignment with flat_vts. + arg_sources.append(getattr(vt, "source", None)) + + def flatten(node_vt: VariableTracker) -> pytree.TreeSpec: + nonlocal has_unknown + try: + node_type = node_vt.python_type() + except NotImplementedError: + has_unknown = True + return pytree.treespec_leaf() + # Keep in sync with pytree._get_node_type. + if pytree.is_namedtuple_class(node_type): + node_type = collections.namedtuple + + if node_type not in pytree.SUPPORTED_NODES: + add_leaf(node_vt) + return pytree.treespec_leaf() + + flatten_fn = pytree.SUPPORTED_NODES[node_type].flatten_fn + if not isinstance(flatten_fn, types.FunctionType): + # _make_inlined only supports plain Python functions (it always + # wraps its argument in a UserFunctionVariable). A flatten_fn + # registered as e.g. a functools.partial, bound method, or + # callable object can't go through it directly. Fall back to + # tracing the full recursive tree_flatten for this subtree, which + # dispatches calls generically and so handles any callable. + leaves_vt, treespec_vt = unpack_iterable( + tx, _make_inlined(tx, pytree.tree_flatten)(node_vt) + ) + for leaf_vt in unpack_iterable(tx, leaves_vt): + add_leaf(leaf_vt) + return treespec_vt.as_python_constant() + + children_vt, context_vt = unpack_iterable( + tx, _make_inlined(tx, flatten_fn)(node_vt) + ) + context = context_vt.as_python_constant() + child_specs = [flatten(child) for child in unpack_iterable(tx, children_vt)] + return pytree.TreeSpec(node_type, context, child_specs) + + container_vt = SourcelessBuilder.create(tx, (list(fn_args_vt), kwargs)) + treespec = flatten(container_vt) + + return InputFingerprint(flat_vts, arg_sources, has_unknown, treespec) + + +def sym_num_key(sym_num: Any) -> Any: + """Key for matching a symbolic input against a cached one. + + Compares the symbolic expression rather than the SymInt object. Each tensor + holds its own SymInt objects, so two arguments carrying the same symbol + (e.g. the atom count threaded through successive layers) are distinct + objects. Equal expressions mean the same value, which is what reuse needs; + distinct symbols still have distinct expressions. + + ``expr`` rather than ``_expr`` on purpose: it has the ShapeEnv's + replacements applied, so a symbol that was specialized keys on the value it + was specialized to. + """ + return sym_num.node.expr + + +def get_flat_proxies(fingerprint: InputFingerprint) -> list[Proxy]: + """Collect deduplicated proxies from tensor/symnode leaves.""" + seen: set[torch.fx.Node] = set() + flat_proxies: list[Proxy] = [] + for tag, vt in fingerprint.flat_vts: + if tag in (InputTag.TENSOR, InputTag.SYMNODE): + proxy = vt.as_proxy() + if proxy.node not in seen: + seen.add(proxy.node) + flat_proxies.append(proxy) + return flat_proxies + + +@dataclass +class LiftedUserArg: + """Lifted arg that came from a user argument (intermediate activation or explicit input).""" + + index: int + + +@dataclass +class LiftedCapturedSource: + """Lifted arg that is a captured variable (e.g. a weight or parameter) with a Source.""" + + source: Any # Source + + +@dataclass +class LiftedSyntheticObject: + """Lifted arg that is a TorchScriptObject with a SyntheticLocalSource.""" + + ctor_fn: Any # Callable + ctor_args: tuple[Any, ...] + ctor_arg_sources: tuple[Any, ...] | None + + +@dataclass +class LiftedBoundSymbol: + """Lifted arg that is a SymInt already bound as a graph input. + + SymInt graph inputs are created during tensor wrapping (not through + VariableBuilder.wrap_symint), so they aren't registered in + unspec_variable_map or variable_tracker_cache. Using LiftedCapturedSource + for these would resolve the source to a concrete Python int via + source.get_value() instead of reusing the existing symbolic proxy. + """ + + expr: Any # sympy.Expr + + +LiftedArgOrigin = ( + LiftedUserArg | LiftedCapturedSource | LiftedSyntheticObject | LiftedBoundSymbol +) + + +def get_fn_code(fn_var: Any) -> types.CodeType | None: + if isinstance(fn_var, UserFunctionVariable): + return fn_var.get_function().__code__ + elif isinstance(fn_var, UnspecializedNNModuleVariable): + return ( + fn_var.value.forward.__func__.__code__ # pyrefly: ignore[missing-attribute] + ) + return None + + +def has_mutated_vars( + tx: "InstructionTranslatorBase", + traced_sources: OrderedSet[Source], +) -> bool: + """Check if any source accessed by the subgraph has been mutated. + + SideEffects.mutated_sources records the exact AttrSource for every + store_attr call. A simple set intersection with traced_sources tells + us whether any source the subgraph read was later written to. + """ + overlap = tx.output.side_effects.mutated_sources & traced_sources + if overlap: + hc_log.debug( + "subgraph_reuse: mutated sources detected -- %s", + overlap, + ) + return True + return False + + +def is_reuse_eligible( + tx: "InstructionTranslatorBase", + body_r: Any, + fingerprint: InputFingerprint, + tracing_info: "SubgraphTracingInfo", + traced_sources: OrderedSet[Source] | None = None, + has_reuse_hash_fn: bool = False, +) -> bool: + """Best-effort check for whether a traced subgraph result can be reused. + + It is possible that a subgraph is morally reusable but does not fall + into the limited support that Dynamo has today. Current limitations: + - The subgraph must not have side effects. + - No sourceful variable accessed by the subgraph may have been + mutated, because guards are snapshotted on source values at trace + time — if the underlying object changed since then, the cached + guards would silently evaluate against stale values. + - Output must be a single tensor, or a tuple/list of plain tensors. + - All flattened inputs must be one of: tensor, symnode, constant + (including enum members), or a sourceful user-defined object + (nn.Modules included) — for sourceless or other input types we + rely on the treespec and tags for structural matching, so only + types with well-defined comparison semantics are supported. + + When ``has_reuse_hash_fn`` is True, side-effect and mutation checks are + skipped because the hash key replaces guards — there are no guards to + go stale from mutations. + """ + if not has_reuse_hash_fn: + if tracing_info.side_effect_stack is not None: + stack_msg = "\n" + "".join( + traceback.format_list(tracing_info.side_effect_stack) + ) + hc_log.debug( + "subgraph_reuse: not eligible -- subgraph has side effects%s", + stack_msg, + ) + return False + + if traced_sources and has_mutated_vars(tx, traced_sources): + return False + + if isinstance(body_r, TensorVariable): + pass + elif isinstance(body_r, (TupleVariable, ListVariable)): + non_tensor = [ + type(item).__name__ + for item in body_r.items + if not isinstance(item, TensorVariable) + ] + if non_tensor: + hc_log.debug( + "subgraph_reuse: not eligible -- output contains non-tensor types: %s", + non_tensor, + ) + return False + else: + hc_log.debug( + "subgraph_reuse: not eligible -- output type %s is not tensor or tuple/list", + type(body_r).__name__, + ) + return False + + if fingerprint.has_unknown: + hc_log.debug( + "subgraph_reuse: not eligible -- unsupported input VT types", + ) + return False + + return True + + +def build_reuse_condition( + tx: "InstructionTranslatorBase", + fingerprint: InputFingerprint, + traced_sources: OrderedSet[Source], +) -> InvokeSubgraphReuseCondition | None: + """Build an InvokeSubgraphReuseCondition from a traced subgraph. + + A reuse condition is a mix of two kinds of checks: + + 1. **Input tag checks** (from flat_vts): For each flattened leaf VT, + we record its tag (InputTag.TENSOR/SYMNODE/CONSTANT/OBJECT) and + metadata (e.g. tensor shape/stride/dtype/device/requires_grad). + At lookup time, the treespec ensures structural equivalence, and + then we compare tags and metadata leaf-by-leaf. + + 2. **Guard checks** (from traced_sources): During the subgraph trace, + every source accessed via VariableBuilder is recorded. We look up + all guards installed on those sources (and on the arg_sources) to + build the set of guards that must be re-evaluated on cache hit. + This is more robust than guard diffing because it catches guards + that were already installed before the subgraph trace began. + + Raise if any guard type is unsupported, as a feedback for compiler + developers to support that guard type. + """ + from torch._guards import InvokeSubgraphReuseCondition + + input_checks: list[tuple[InputTag, object]] = [] + for tag, vt in fingerprint.flat_vts: + if tag == InputTag.TENSOR: + if not isinstance(vt, TensorVariable): + raise AssertionError( + f"expected TensorVariable for TENSOR tag, got {type(vt).__name__}" + ) + example = vt.proxy.node.meta.get("example_value", None) + if example is None: + hc_log.debug( + "subgraph_reuse: cannot build condition -- tensor input has no example_value" + ) + return None + input_checks.append((InputTag.TENSOR, extract_tensor_metadata(example))) + elif tag == InputTag.SYMNODE: + if not isinstance(vt, SymNodeVariable): + raise AssertionError( + f"expected SymNodeVariable for SYMNODE tag, got {type(vt).__name__}" + ) + input_checks.append((InputTag.SYMNODE, sym_num_key(vt.sym_num))) + elif tag == InputTag.CONSTANT: + if not is_constant_like(vt): + raise AssertionError( + f"expected constant-like VT for CONSTANT tag, got {type(vt).__name__}" + ) + # Type is part of the key: `Mode.ADD == 1` and `True == 1` compare + # equal, but an isinstance() check inside the region traces + # differently for each, so value equality alone is not enough. + input_checks.append((InputTag.CONSTANT, (type(vt.value), vt.value))) + elif tag == InputTag.OBJECT: + input_checks.append((InputTag.OBJECT, None)) + else: + raise AssertionError( + f"Unexpected input tag '{tag}' for {type(vt).__name__} -- " + f"is_reuse_eligible should have rejected this" + ) + + # Collect all guards for sources accessed during the subgraph trace + # and for the flattened arg sources. + all_sources = set(traced_sources) + all_sources.update(s for s in fingerprint.arg_sources if s is not None) + all_relevant_guards: set[Guard] = set() + for source in all_sources: + all_relevant_guards.update(tx.output.guards.get_guards_for_source(source)) + + guard_tuples: list[tuple[Source, GuardCheckSpec, object, Guard]] = [] + for guard in all_relevant_guards: + source = guard.originating_source + type_str = guard.create_fn_name() + handler = GUARD_VALUE_DISPATCH.get(type_str) + + if handler is SKIP_GUARD: + continue + + if handler is None or isinstance(handler, UnsupportedGuardCheckSpec): + raise RuntimeError( + f"subgraph_reuse: unsupported guard type '{type_str}' on source '{source.name}'" + ) + + try: + value = tx.output.resolve_source_value(source) + except Exception: + raise RuntimeError( + f"subgraph_reuse: failed to resolve source '{source.name}' for {type_str} guard" + ) from None + + # TODO(anijain2305): vLLM workaround -- skip CONSTANT_MATCH on + # strings. Re-evaluate once vLLM migrates off this pattern. + # if type_str == "CONSTANT_MATCH" and isinstance(value, str): + # continue + + handler = cast(GuardCheckSpec, handler) + expected = handler.get_metadata_fn(guard, value) + guard_tuples.append((source, handler, expected, guard)) + + hc_log.debug("Number of guards %s", len(guard_tuples)) + + return InvokeSubgraphReuseCondition( + input_checks=input_checks, + guards=guard_tuples, + treespec=fingerprint.treespec, + traced_sources=traced_sources, + ) + + +def build_source_replacement( + old_arg_sources: list[Source | None], + new_arg_sources: list[Source | None], +) -> dict[Source, Source]: + """Map old arg sources to new arg sources for remapping captured variable sources.""" + return { + old: new + for old, new in zip(old_arg_sources, new_arg_sources) + if old is not None and new is not None and old != new + } + + +def is_reusable( + tx: "InstructionTranslatorBase", + condition: "InvokeSubgraphReuseCondition", + fingerprint: InputFingerprint, + cached_entry: InvokeSubgraphReuseEntry, +) -> bool: + """Check if a cached subgraph can be reused for the current call. + + Three-phase check: + (1) Verify that intermediates (tensor metadata, symnode types, constant + values) match the cached input_checks — these are lightweight + structural comparisons that don't require source resolution. + (2) Check for mutations on the remapped traced_sources — if any source + the subgraph read has been mutated since the original trace, the + cached guards would evaluate against stale values. + (3) Build a source replacement mapping (old sources → new sources) and + re-evaluate the snapshotted guards under the new sources. + """ + # Structural check: treespec must match first. + if condition.treespec is not None and fingerprint.treespec != condition.treespec: + hc_log.debug( + "subgraph_reuse: reuse failed -- treespec mismatch", + ) + return False + + # Input count, tags, and metadata must match. + # Tensor metadata (shape, stride, dtype, device, requires_grad) is checked + # here because TENSOR_MATCH guards for subgraph inputs typically already + # exist in the outer graph before tracing and thus won't appear in the + # guard delta. + if len(condition.input_checks) != len(fingerprint.flat_vts): + hc_log.debug( + "subgraph_reuse: reuse failed -- input count mismatch: cached %d vs current %d", + len(condition.input_checks), + len(fingerprint.flat_vts), + ) + return False + + for i, ((cached_tag, cached_val), (cur_tag, cur_vt)) in enumerate( + zip(condition.input_checks, fingerprint.flat_vts) + ): + if cached_tag != cur_tag: + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d tag mismatch: cached '%s' vs current '%s'", + i, + cached_tag, + cur_tag, + ) + return False + if cached_tag == InputTag.TENSOR: + if not isinstance(cur_vt, TensorVariable): + raise AssertionError( + f"expected TensorVariable for TENSOR tag, got {type(cur_vt).__name__}" + ) + example = cur_vt.proxy.node.meta.get("example_value", None) + if example is None: + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d tensor has no example_value", + i, + ) + return False + cur_meta = extract_tensor_metadata(example) + if cur_meta != cached_val: + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d tensor metadata mismatch", + i, + ) + return False + elif cached_tag == InputTag.SYMNODE: + if not isinstance(cur_vt, SymNodeVariable): + raise AssertionError( + f"expected SymNodeVariable for SYMNODE tag, got {type(cur_vt).__name__}" + ) + if sym_num_key(cur_vt.sym_num) != cached_val: + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d symnode mismatch: cached '%s' vs current '%s'", + i, + cached_val, + cur_vt.sym_num, + ) + return False + elif cached_tag == InputTag.CONSTANT: + if not is_constant_like(cur_vt): + raise AssertionError( + f"expected constant-like VT for CONSTANT tag, got {type(cur_vt).__name__}" + ) + cached_type, cached_value = cast(tuple[type, Any], cached_val) + if type(cur_vt.value) is not cached_type: + # Not deferred to the source check below: a value guard cannot + # catch a type change that alters the trace (isinstance, etc). + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d constant type " + "mismatch: cached '%s' vs current '%s'", + i, + cached_type, + type(cur_vt.value), + ) + return False + if cur_vt.value != cached_value: + # If both the cached and current arg have sources, source + # replacement in stamp_out will resolve the correct value. + cached_src = ( + cached_entry.arg_sources[i] + if i < len(cached_entry.arg_sources) + else None + ) + new_src = ( + fingerprint.arg_sources[i] + if i < len(fingerprint.arg_sources) + else None + ) + if cached_src is None or new_src is None: + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d constant mismatch " + "with no source to replace: cached '%s' vs current '%s'", + i, + cached_val, + cur_vt.value, + ) + return False + + source_replacement = build_source_replacement( + cached_entry.arg_sources, fingerprint.arg_sources + ) + + # Parameterized source - this function gives you new sources parameterized + # on the arg_sources. For example, if the input to the nested compile region + # is a nn Module layer with source `layers[0]`, then old source + # `layers[0].weight` gets remapped to `layers[1].weight`. This + # parameterization is central in getting the new sources and then running + # guards on them. + def replacement_fn(s: Source) -> Source: + return source_replacement.get(s, s) + + # Check for mutations on remapped traced_sources. + if source_replacement: + remapped = OrderedSet(s.clone(replacement_fn) for s in condition.traced_sources) + else: + remapped = condition.traced_sources + if has_mutated_vars(tx, remapped): + return False + + # If no sources changed, all guards were already checked during the + # original trace and will trivially pass again. + if not source_replacement: + return True + + # Shared resolution context so source.get_value memoizes intermediate + # results (e.g. common base sources) across all guards in this check. + resolve_globals: dict[str, Any] = { + "G": tx.output.root_tx.f_globals, + "L": tx.output.root_tx.f_locals, + } + resolve_locals: dict[str, Any] = {} + resolve_cache: dict[Source, Any] = {} + + for source, handler, expected, guard in condition.guards: + new_source = source.clone(replacement_fn) + # Source unchanged after replacement — guard already passed during + # the original trace, skip re-evaluation. + if new_source == source: + continue + + try: + value = new_source.get_value(resolve_globals, resolve_locals, resolve_cache) + except Exception: + hc_log.debug( + "subgraph_reuse: reuse failed -- cannot resolve source\n" + " guard type: %s\n" + " guard source: %s\n" + " guard source name: %s\n" + " user stack:\n%s", + guard.create_fn_name(), + new_source, + new_source.name, + "".join(guard.user_stack.format()) + if guard.user_stack + else "", + ) + return False + + if not handler.eval_fn(value, expected): + hc_log.debug( + "subgraph_reuse: reuse failed --\n" + " guard type: %s\n" + " guard source: %s\n" + " guard source name: %s\n" + " expected: %s\n" + " got: %s\n" + " user stack:\n%s", + guard.create_fn_name(), + new_source, + new_source.name, + expected, + value, + "".join(guard.user_stack.format()) + if guard.user_stack + else "", + ) + return False + + return True + + +def has_reuse_entries( + tx: "InstructionTranslatorBase", + fn_var: Any, +) -> bool: + """Cheap check: does the cache have any entries for this function?""" + from torch._guards import InvokeSubgraphCache + + invoke_subgraph_cache = tx.output.tracing_context.hop_dispatch_set_cache.get_cache( + torch._higher_order_ops.invoke_subgraph + ) + if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache): + return False + fn_code = get_fn_code(fn_var) + return fn_code is not None and fn_code in invoke_subgraph_cache.subgraph_reuse_cache + + +def find_reuse_match( + tx: "InstructionTranslatorBase", + fn_var: Any, + fingerprint: InputFingerprint, +) -> InvokeSubgraphReuseEntry | None: + from torch._guards import InvokeSubgraphCache + + invoke_subgraph_cache = tx.output.tracing_context.hop_dispatch_set_cache.get_cache( + torch._higher_order_ops.invoke_subgraph + ) + if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache): + return None + fn_code = get_fn_code(fn_var) + if fn_code is None: + return None + + # this evaluator function is called one by one for all the invoke subgraph + # reuse entries - the one that evaluates to True is stamped out in the + # graph. + def evaluator( + cond: "InvokeSubgraphReuseCondition", entry: InvokeSubgraphReuseEntry + ) -> bool: + return is_reusable(tx, cond, fingerprint, entry) + + return invoke_subgraph_cache.find_reuse_entry(fn_code, evaluator) + + +def save_reuse_entry( + tx: "InstructionTranslatorBase", + fn_var: Any, + fingerprint: InputFingerprint, + body_name: str, + body_gmod: torch.fx.GraphModule, + config: NestedCompileRegionOptions | None, + p_args: tuple[Any, ...], + body_r: VariableTracker, + example_value: Any, + max_reuse_entries: int = 8, + condition: "InvokeSubgraphReuseCondition | None" = None, + hash_key: int | None = None, +) -> None: + """Save a traced subgraph into the reuse cache for future cache hits. + + Builds an InvokeSubgraphReuseEntry with the freevar mapping (how each + lifted arg maps back to user inputs or captured variables), output + metadata, and arg sources. On a future cache hit, stamp_out_subgraph + uses this entry to emit a new invoke_subgraph call without re-tracing. + + Exactly one of ``condition`` or ``hash_key`` must be provided. + ``condition`` stores the entry in the guard-based cache (linear scan); + ``hash_key`` stores it in the hash-key cache (O(1) lookup). + """ + from torch._guards import InvokeSubgraphCache + + if not ((condition is None) != (hash_key is None)): + raise AssertionError("Exactly one of condition or hash_key must be provided") + + invoke_subgraph_cache = tx.output.tracing_context.hop_dispatch_set_cache.get_cache( + torch._higher_order_ops.invoke_subgraph + ) + if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache): + return + + fn_code = get_fn_code(fn_var) + if fn_code is None: + return + + subgraph_input_mapping = build_subgraph_input_mapping( + tx, p_args, fingerprint.flat_vts + ) + single_tensor_output = isinstance(body_r, TensorVariable) + + # Count user-visible outputs from body_r. The graph may have additional + # outputs from side-effect intermediates that stamp_out_subgraph must + # not include when reconstructing the user-visible return value. + user_output_vts: list[VariableTracker] = [] + VariableTracker.visit( + lambda vt: user_output_vts.append(vt) + if vt.is_tensor() or isinstance(vt, SymNodeVariable) + else None, + body_r, + ) + num_user_outputs = len(user_output_vts) + + # Cache output tensor metadata so we can construct fresh FakeTensors on + # cache hit without re-running the subgraph. This is safe because + # invoke_subgraph does not support aliasing between inputs and outputs + # (speculate_subgraph will fail if that happens). + # example_value may contain SymInts (e.g. shape values for backward); + # only record metadata for actual tensors. + output_metadata = [ + (t.shape, t.stride(), t.dtype, t.device, t.requires_grad) + for t in example_value + if isinstance(t, torch.Tensor) + ] + + entry = InvokeSubgraphReuseEntry( + body_name=body_name, + body_gmod=body_gmod, + config=config, + subgraph_input_mapping=subgraph_input_mapping, + single_tensor_output=single_tensor_output, + output_metadata=output_metadata, + # Record arg sources so that on cache hit we can build a + # source replacement mapping (old sources → new sources) to + # rewrite captured variable sources for the current invocation. + arg_sources=fingerprint.arg_sources, + num_user_outputs=num_user_outputs, + ) + if condition is not None: + invoke_subgraph_cache.add_reuse_entry( + fn_code, condition, entry, max_reuse_entries + ) + else: + if hash_key is None: + raise AssertionError("hash_key must not be None when condition is None") + invoke_subgraph_cache.add_reuse_entry_by_key( + fn_code, hash_key, entry, max_reuse_entries + ) + + +def trace_reuse_hash_fn( + tx: "InstructionTranslatorBase", + reuse_hash_fn: Any, + fn_args_vt: "list[VariableTracker]", + kwargs: dict[str, VariableTracker], +) -> int: + """Trace the user's reuse_hash_fn to get a constant integer hash key. + + Guards installed during the hash function tracing are skipped — the hash + key itself is the reuse condition, not the guards. + """ + from torch._dynamo.exc import Unsupported + + with tx.output.tracing_context.guards_context.skip_guard_install(): + try: + result = _make_inlined(tx, reuse_hash_fn)(*fn_args_vt, **kwargs) + except Unsupported as e: + raise RuntimeError( + f"reuse_hash_fn must be fully traceable without graph breaks. Got: {e}" + ) from e + + if not isinstance(result, ConstantVariable) or not isinstance(result.value, int): + raise RuntimeError( + f"reuse_hash_fn must return a constant integer, got {result}" + ) + + return result.value + + +def find_reuse_entry_by_key( + tx: "InstructionTranslatorBase", + fn_var: Any, + hash_key: int, +) -> InvokeSubgraphReuseEntry | None: + from torch._guards import InvokeSubgraphCache + + invoke_subgraph_cache = tx.output.tracing_context.hop_dispatch_set_cache.get_cache( + torch._higher_order_ops.invoke_subgraph + ) + if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache): + return None + fn_code = get_fn_code(fn_var) + if fn_code is None: + return None + return invoke_subgraph_cache.find_reuse_entry_by_key(fn_code, hash_key) + + +def stamp_out_subgraph( + tx: "InstructionTranslatorBase", + fingerprint: InputFingerprint, + cached: InvokeSubgraphReuseEntry, +) -> VariableTracker: + """Emit a new invoke_subgraph call by stamping out a cached subgraph. + + Sources in the cached entry are parameterized: they refer to the original + call's sources and must be rewritten to the current call's sources via + source replacement before we can look up or create the corresponding + graph placeholders. + """ + from torch._dynamo.variables.builder import VariableBuilder + from torch._dynamo.variables.higher_order_ops import add_call_function, make_attr + + flat_proxies = get_flat_proxies(fingerprint) + new_arg_sources = fingerprint.arg_sources + + source_replacement = build_source_replacement(cached.arg_sources, new_arg_sources) + + new_lifted_args = [] + # Shared resolution context so get_value memoizes intermediate results + # (e.g. L['self'].layers) across all freevars in this stamp-out. + resolve_globals: dict[str, Any] = { + "G": tx.output.root_tx.f_globals, + "L": tx.output.root_tx.f_locals, + } + resolve_locals: dict[str, Any] = {} + resolve_cache: dict[Source, Any] = {} + + # Find the args for the about-to-be-inserted invoke_subgraph call. + for subgraph_input in cached.subgraph_input_mapping: + if isinstance(subgraph_input, LiftedUserArg): + new_lifted_args.append(flat_proxies[subgraph_input.index]) + elif isinstance(subgraph_input, LiftedBoundSymbol): + from torch._dynamo.output_graph import LazyProxy + + proxy = tx.output.current_tracer.bound_symbols[subgraph_input.expr] + if isinstance(proxy, LazyProxy): + proxy = proxy() + tx.output.current_tracer.bound_symbols[subgraph_input.expr] = proxy + new_lifted_args.append(proxy) + elif isinstance(subgraph_input, LiftedSyntheticObject): + ctor_args = subgraph_input.ctor_args + ctor_arg_sources = subgraph_input.ctor_arg_sources + if ctor_arg_sources and source_replacement: + new_ctor_args = [] + new_ctor_arg_sources = [] + for val, arg_src in zip(ctor_args, ctor_arg_sources): + if arg_src is not None: + new_src = arg_src.clone(lambda s: source_replacement.get(s, s)) + val = new_src.get_value( + resolve_globals, resolve_locals, resolve_cache + ) + arg_src = new_src + new_ctor_args.append(val) + new_ctor_arg_sources.append(arg_src) + ctor_args = tuple(new_ctor_args) + ctor_arg_sources = tuple(new_ctor_arg_sources) + vt = tx.output.synthetic_graph_input( + subgraph_input.ctor_fn, ctor_args, ctor_arg_sources + ) + new_lifted_args.append(vt.as_proxy()) + elif isinstance(subgraph_input, LiftedCapturedSource): + new_source = subgraph_input.source + if source_replacement: + new_source = new_source.clone(lambda s: source_replacement.get(s, s)) + # VariableBuilder deduplicates via input_source_to_var, + # so this reuses existing graph placeholders automatically. + value = new_source.get_value(resolve_globals, resolve_locals, resolve_cache) + vt = VariableBuilder(tx, new_source)(value) + new_lifted_args.append(vt.as_proxy()) + + # Generate fake tensor outputs + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None for stamp_out_subgraph") + with tx.fake_mode: + example_value = tuple( + torch.empty_strided( + shape, + stride, + dtype=dtype, + device=device, + requires_grad=req_grad, + ) + for shape, stride, dtype, device, req_grad in cached.output_metadata + ) + + # Install the invoke_subgraph call + body_node = make_attr(tx, cached.body_name) + p_args = (body_node, cached.body_name, *new_lifted_args) + flat_variable = add_call_function( + tx, + torch._higher_order_ops.invoke_subgraph, + tuple(p_args), + {}, + example_value, + cached.config, + ) + + # Return only the user-visible outputs. The graph may have extra + # intermediate outputs from side effects (allow_side_effects=True) + # that should not be part of the user-facing return value. + if cached.single_tensor_output: + items = flat_variable.items # pyrefly: ignore[missing-attribute] + if not isinstance(items[0], TensorVariable): + raise AssertionError( + f"Expected tensor output but got {type(items[0]).__name__}" + ) + return items[0] + + items = flat_variable.items # pyrefly: ignore[missing-attribute] + n = cached.num_user_outputs + if n > 0 and n < len(items): + from .builder import SourcelessBuilder + + return SourcelessBuilder.create(tx, tuple(items[:n])) + return flat_variable + + +def build_subgraph_input_mapping( + tx: "InstructionTranslatorBase", + p_args: tuple[Any, ...], + flat_vts: list[tuple[InputTag, VariableTracker]], +) -> list[LiftedArgOrigin]: + """Build a mapping that records the origin of each lifted arg for a subgraph. + + On a cache hit, we stamp out a new invoke_subgraph call and need to + reconstruct its argument list in the correct order. Each lifted arg + (p_args[2:], skipping body_node and body_name) comes from one of: + + - LiftedUserArg: a user argument (intermediate activation or explicit input) + - LiftedCapturedSource: a captured variable (e.g. a weight or parameter) + - LiftedSyntheticObject: a TorchScriptObject with a SyntheticLocalSource + - LiftedBoundSymbol: a SymInt already bound as a graph input + """ + proxy_node_to_idx: dict[torch.fx.Node, int] = {} + idx = 0 + for tag, vt in flat_vts: + if tag in (InputTag.TENSOR, InputTag.SYMNODE): + node = vt.as_proxy().node + if node not in proxy_node_to_idx: + proxy_node_to_idx[node] = idx + idx += 1 + + subgraph_input_mapping: list[LiftedArgOrigin] = [] + for outer_proxy in p_args[2:]: + matched_idx = proxy_node_to_idx.get(outer_proxy.node, -1) + if matched_idx >= 0: + subgraph_input_mapping.append(LiftedUserArg(matched_idx)) + else: + grapharg = outer_proxy.node.meta.get("grapharg", None) + source = grapharg.source if grapharg is not None else None + # SymInt freevars must reuse the existing symbolic proxy rather + # than resolving via source.get_value() (which returns the + # concrete int). They appear as either: + # - placeholder nodes with grapharg.example being a SymInt + # - call_function nodes (e.g. sym_size_int) with no grapharg + # In both cases, store the sympy expression and look it up in + # bound_symbols during stamp-out. + example = ( + grapharg.example + if grapharg is not None + else outer_proxy.node.meta.get("example_value", None) + ) + if isinstance(example, torch.SymInt): + # _expr rather than expr: expr applies the ShapeEnv's + # replacements, so a symbol the region lifted before it was + # specialized comes back as a constant, which bound_symbols has + # no entry for. + subgraph_input_mapping.append(LiftedBoundSymbol(example.node._expr)) + continue + if source is None: + raise AssertionError( + f"Freevar has no source: node.op={outer_proxy.node.op} " + f"node.name={outer_proxy.node.name} -- this likely means a " + f"function argument was not included in the proxy matching" + ) + if isinstance(source, SyntheticLocalSource): + ctor_info = tx.output.synthetic_source_ctor_info.get(source) + if ctor_info is not None: + ctor_fn, ctor_args, ctor_arg_sources = ctor_info + subgraph_input_mapping.append( + LiftedSyntheticObject(ctor_fn, ctor_args, ctor_arg_sources) + ) + continue + subgraph_input_mapping.append(LiftedCapturedSource(source)) + return subgraph_input_mapping + + +class InvokeSubgraphHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.ops.higher_order.invoke_subgraph" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = True + supports_aliasing = False + allow_side_effects = True + # invoke_subgraph is NOT desugared in AOTAutograd, so the HOP input/output + # shouldn't alias. For checkpoint HOP, we inline it so we don't need + # alias analysis as functionalization would just work on the flat graph. + filter_aliased_intermediates = True + + # pyrefly: ignore[bad-override] + def install_subgraph_in_output_graph( + self, + tx: "InstructionTranslatorBase", + fn_vt: VariableTracker, + fn_args_vt: "list[VariableTracker]", + kwargs: dict[str, VariableTracker], + body_gmod: GraphModule, + attr_name: str, + ) -> str: + # Check if the subgraph from speculate_subgraph (body_gmod) and the fake + # inputs have already been seen before. If yes, the subgraph is already + # installed in the output graph and we can just access the subgraph + # using the saved attr name. + + if not isinstance(fn_vt, (UnspecializedNNModuleVariable, UserFunctionVariable)): + unimplemented( + gb_type="Encountered non user function variable during invoke_subgraph HOP tracing", + context=str(fn_vt), + explanation="invoke_subgraph does not support non user function variable", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + invoke_subgraph_cache = ( + tx.output.tracing_context.hop_dispatch_set_cache.get_cache( + torch._higher_order_ops.invoke_subgraph + ) + ) + + if isinstance(fn_vt, UserFunctionVariable): + fn_code = fn_vt.get_function().__code__ + fn_name = fn_vt.get_function().__name__ + else: + if not isinstance(fn_vt, UnspecializedNNModuleVariable): + raise AssertionError( + f"expected UnspecializedNNModuleVariable, got {type(fn_vt).__name__}" + ) + fn_code = fn_vt.value.forward.__func__.__code__ # type: ignore[attr-defined] + fn_name = fn_vt.value.forward.__name__ # type: ignore[attr-defined] + # pyrefly: ignore [implicit-any] + previously_installed_submodules = [] + if invoke_subgraph_cache: + previously_installed_submodules = ( + invoke_subgraph_cache.get_dynamo_installed_submodules(fn_code) + ) + current_mod = body_gmod + # NB - reverse is more likely to cause a hit sooner because first + # graph can have requires_grad=False for a few inputs + for submodule_name in reversed(previously_installed_submodules): + if submodule_name not in tx.output.nn_modules: + raise AssertionError( + f"submodule '{submodule_name}' not found in nn_modules" + ) + previous_mod = tx.output.nn_modules[submodule_name] + if not tx.fake_mode: + raise AssertionError( + "tx.fake_mode must be set for subgraph comparison" + ) + from torch._dynamo.variables.higher_order_ops import ( + are_same_graph_modules, + ) + + if are_same_graph_modules( + fn_name, previous_mod, current_mod, tx.fake_mode + ): + return submodule_name + + body_name = super().install_subgraph_in_output_graph( + tx, fn_vt, fn_args_vt, kwargs, body_gmod, "subgraph" + ) + hc_log.debug( + "%s: Installing subgraph with identifier '%s', bringing total count for '%s' function to %s", + fn_name, + body_name, + fn_name, + len(previously_installed_submodules) + 1, + ) + if invoke_subgraph_cache: + invoke_subgraph_cache.add_dynamo_installed_submodule(fn_code, body_name) + + return body_name + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: "list[VariableTracker]", + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from torch._dynamo.utils import dynamo_timed + from torch._dynamo.variables.higher_order_ops import ( + _call_function_with_auto_output_flattening, + ) + + fn_var = args[0] + fn_args_vt = args[1:] + + config = None + max_reuse_entries = 8 + reuse_hash_fn = None + if hasattr(fn_var, "get_function"): + try: + fn = fn_var.get_function() + config = getattr(fn, "__marked_compile_region_config__", None) + max_reuse_entries = getattr( + fn, "__marked_compile_region_max_reuse_entries__", 8 + ) + reuse_hash_fn = getattr( + fn, "__marked_compile_region_reuse_hash_fn__", None + ) + except Exception: + log.warning( + "Failed to extract nested_compile_region() config from InvokeSubgraphHigherOrderVariable. ", + exc_info=True, + ) + raise + + # TODO (anijain2305) - Collect issues why this does not work for export, + # and enable if request arises. + reuse = not tx.output.export + + # User-provided reuse_hash_fn path: hash key determines cache lookup. + if reuse and reuse_hash_fn is not None: + with dynamo_timed("invoke_subgraph_reuse_hash_fn"): + hash_key = trace_reuse_hash_fn(tx, reuse_hash_fn, fn_args_vt, kwargs) + + cached = find_reuse_entry_by_key(tx, fn_var, hash_key) + if cached is not None: + hc_log.debug( + "subgraph_reuse: hash key %d hit for '%s', reusing subgraph '%s'", + hash_key, + fn_var, + cached.body_name, + ) + fingerprint = build_input_fingerprint(tx, fn_args_vt, kwargs) + with dynamo_timed("invoke_subgraph_reuse_stamp_out"): + return stamp_out_subgraph(tx, fingerprint, cached) + + # Automatic reuse lookup (guard-based): check fn_code first (cheap) to + # avoid the expensive pytree flatten in build_input_fingerprint on + # the first call when there's nothing in the cache yet. + elif reuse and has_reuse_entries(tx, fn_var): + with dynamo_timed("invoke_subgraph_reuse_lookup"): + fingerprint = build_input_fingerprint(tx, fn_args_vt, kwargs) + match = find_reuse_match( + tx, + fn_var, + fingerprint, + ) + if match is not None: + hc_log.debug( + "subgraph_reuse: cache hit for '%s', reusing subgraph '%s'", + fn_var, + match.body_name, + ) + with dynamo_timed("invoke_subgraph_reuse_stamp_out"): + return stamp_out_subgraph(tx, fingerprint, match) + + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must not be None") + with dynamo_timed("invoke_subgraph_trace"): + ( + p_args, + p_kwargs, + example_value, + body_r, + body_gmod, + body_name, + body_graph_output_vts, + tracing_info, + ) = self.create_wrapped_node(tx, fn_var, fn_args_vt, kwargs, self._HOP_NAME) + + if len(p_kwargs) > 0: + unimplemented( + gb_type="invoke_subgraph: kwargs unexpected", + context=f"args: {args}, kwargs: {kwargs}", + explanation="kwargs should have been flattened into lifted args.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + # Store config in the body graph module meta + if isinstance(config, NestedCompileRegionOptions): + body_gmod.meta["nested_region_config"] = config + + p_args = ( + p_args[0], + body_name, + *p_args[1:], + ) + + # Subgraph reuse: save entry for future cache hits + if reuse: + fingerprint = build_input_fingerprint(tx, fn_args_vt, kwargs) + if reuse_hash_fn is not None: + traced_sources = tracing_info.traced_sources + if not is_reuse_eligible( + tx, + body_r, + fingerprint, + tracing_info, + traced_sources, + has_reuse_hash_fn=True, + ): + raise RuntimeError( + "reuse_hash_fn was provided but the subgraph is not " + "eligible for reuse. Check the logs with " + "TORCH_LOGS='+hierarchical_compile' for details." + ) + save_reuse_entry( + tx, + fn_var, + fingerprint, + body_name, + body_gmod, + config, + p_args, + body_r, + example_value, + max_reuse_entries, + hash_key=hash_key, # type: ignore[possibly-undefined] + ) + else: + traced_sources = tracing_info.traced_sources + if is_reuse_eligible( + tx, body_r, fingerprint, tracing_info, traced_sources + ): + condition = build_reuse_condition( + tx, + fingerprint, + traced_sources, + ) + if condition is not None: + save_reuse_entry( + tx, + fn_var, + fingerprint, + body_name, + body_gmod, + config, + p_args, + body_r, + example_value, + max_reuse_entries, + condition=condition, + ) + + return _call_function_with_auto_output_flattening( # type: ignore[return-value] + tx, + torch._higher_order_ops.invoke_subgraph, + tuple(p_args), + p_kwargs, + example_value, + body_r, + body_graph_output_vts, + config=config, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/iter.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/iter.py new file mode 100644 index 0000000000000000000000000000000000000000..a485cac42807b254b1a10649174e36a25d8eb0f1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/iter.py @@ -0,0 +1,969 @@ +""" +This module provides iterator-related variable tracking functionality for Dynamo. +It implements variable classes for handling Python iterators and itertools functions +during symbolic execution and tracing. + +The module includes: +- Base iterator variable classes for tracking iterator state +- Implementations of built-in iterators (zip, map, filter) +- Support for itertools functions (product, groupby, count, etc.) +- Mutation tracking and reconstruction capabilities for iterator operations + +These classes integrate with Dynamo's variable tracking system to enable proper +handling of iterator operations during code transformation and optimization. +""" + +import inspect +import itertools +import operator +import sys +from typing import Any, TYPE_CHECKING + +from .. import graph_break_hints, polyfills, variables +from ..bytecode_transformation import ( + create_call_function, + create_call_function_ex, + create_instruction, +) +from ..exc import ( + handle_observed_exception, + ObservedUserStopIteration, + raise_observed_exception, + raise_type_error, + raise_value_error, + unimplemented, +) +from ..utils import raise_args_mismatch, tracked_repr, unpack_iterable +from .base import GetSet, Method, ValueMutationNew, VariableTracker +from .constant import ConstantVariable +from .hashable import HashableTracker +from .object_protocol import generic_getiter, pyiter_next + + +# chain.from_iterable is a method descriptor that creates a new object on each +# attribute access (a is b → False). Capture once at import time for stable +# identity comparisons in ItertoolsVariable.call_function. +_CHAIN_FROM_ITERABLE = itertools.chain.from_iterable + +# repeat(object, times=-1); itertools.repeat has no introspectable signature, so +# declare one to bind args/kwargs. `times` defaults to None to mark the unbounded +# form (CPython's cnt == -1). +_REPEAT_SIGNATURE = inspect.Signature( + [ + inspect.Parameter("object", inspect.Parameter.POSITIONAL_OR_KEYWORD), + inspect.Parameter( + "times", inspect.Parameter.POSITIONAL_OR_KEYWORD, default=None + ), + ] +) + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +MAX_ITERATOR_LIMIT = 100 * 1024 # 100k + + +def is_iterator_exhausted( + tx: "InstructionTranslatorBase", iterator: VariableTracker +) -> bool: + try: + pyiter_next(tx, iterator) + return False + except ObservedUserStopIteration: + handle_observed_exception(tx) + return True + + +class ItertoolsVariable(VariableTracker): + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def __repr__(self) -> str: + return f"ItertoolsVariable({self.value})" + + def as_python_constant(self) -> Any: + return self.value + + def get_real_python_backed_value(self) -> Any: + return self.value + + def _get_from_iterable( + self, tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + # Only itertools.chain has from_iterable; declining (None) falls + # through to the generic protocol for other itertools callables. + if self.value is itertools.chain: + return ItertoolsVariable(_CHAIN_FROM_ITERABLE) + return None + + tp_getset = { + "from_iterable": GetSet(_get_from_iterable), + } + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list["VariableTracker"], + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + # See also: module `torch._dynamo.polyfills.itertools` + + if self.value is itertools.chain and not kwargs: + # Wrap args in a ListIteratorVariable so sub-iterables are pulled lazily. + # generic_getiter on each sub-iterable is deferred to tp_iternext_impl, + # matching CPython's behavior (iter() on each arg is lazy, not at construction). + source = variables.ListIteratorVariable( + list(args), mutation_type=ValueMutationNew() + ) + return ChainVariable(source, mutation_type=ValueMutationNew()) + elif self.value is _CHAIN_FROM_ITERABLE and not kwargs and len(args) == 1: + # Convert outer iterable to iterator; each sub-iterable converted lazily. + source = generic_getiter(tx, args[0]) + return ChainVariable(source, mutation_type=ValueMutationNew()) + elif self.value is itertools.zip_longest: + fillvalue_vt = kwargs.pop("fillvalue", ConstantVariable.create(None)) + if kwargs: + unimplemented( + gb_type="Unsupported kwargs for itertools.zip_longest", + context=f"call_function {self} {args} {kwargs}", + explanation=f"Expected kwargs: 'fillvalue', but got " + f"{','.join(set(kwargs.keys()) - {'fillvalue'})}", + hints=[*graph_break_hints.USER_ERROR], + ) + iterables = [generic_getiter(tx, arg) for arg in args] + return ZipLongestVariable( + iterables, + fillvalue=fillvalue_vt, + mutation_type=ValueMutationNew(), + ) + elif self.value is itertools.product: + if any(kw != "repeat" for kw in kwargs): + unimplemented( + gb_type="Unsupported kwargs for itertools.product", + context=f"call_function {self} {args} {kwargs}", + explanation=f"Expected kwargs: 'repeat', but got " + f"{','.join(set(kwargs.keys()) - {'repeat'})}", + hints=[*graph_break_hints.USER_ERROR], + ) + + if "repeat" in kwargs: + r = kwargs["repeat"].as_python_constant() + else: + r = 1 + seqs = [unpack_iterable(tx, arg) for arg in args] + items = [ + variables.TupleVariable(list(item)) + for item in itertools.product(*seqs, repeat=r) + ] + return variables.ListIteratorVariable( + items, # type: ignore[arg-type] + mutation_type=ValueMutationNew(), + ) + elif self.value is itertools.groupby: + if any(kw != "key" for kw in kwargs): + unimplemented( + gb_type="Unsupported kwargs for itertools.groupby", + context=f"call_function {self} {args} {kwargs}", + explanation=f"Expected kwargs: 'key', but got " + f"{','.join(set(kwargs.keys()) - {'key'})}", + hints=[*graph_break_hints.USER_ERROR], + ) + + def retrieve_const_key(key: VariableTracker) -> Any: + from ..utils import specialize_symnode + + # Unwrap LazyVariableTracker to get the underlying variable + key = specialize_symnode(key) + if isinstance(key, variables.SymNodeVariable): + return key.evaluate_expr() + elif key.is_python_constant(): + return key.as_python_constant() + else: + unimplemented( + gb_type="Unsupported key type for itertools.groupby", + context=f"call_function {self} {args} {kwargs}", + explanation="Dynamo does not know how to trace " + f"itertools.groupby with key type: {str(type(key))}. " + "We only support grouping keys that are constants (int, float, str, etc.)", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if len(args) != 1: + unimplemented( + gb_type="Unsupported arguments for itertools.groupby", + context=f"call_function {self} {args} {kwargs}", + explanation="Dynamo does not know how to trace " + f"itertools.groupby with args: {args} and kwargs: {kwargs}. " + "itertools.groupby expects an iterable to group and an " + "optional key function to determine groupings.", + hints=[ + "Make sure the arguments to itertools.groupby are correct.", + *graph_break_hints.SUPPORTABLE, + ], + ) + seq = unpack_iterable(tx, args[0]) + + if "key" in kwargs: + + def keyfunc(x: VariableTracker) -> Any: + return retrieve_const_key( + kwargs.get("key").call_function(tx, [x], {}) # type: ignore[union-attr] + ) + + else: + + def keyfunc(x: VariableTracker) -> Any: + return retrieve_const_key(x) + + result = [] + try: + for k, v in itertools.groupby(seq, key=keyfunc): + result.append( + variables.TupleVariable( + [ + ( + variables.ConstantVariable.create(k) + if variables.ConstantVariable.is_literal(k) + else k + ), + variables.ListIteratorVariable( + list(v), mutation_type=ValueMutationNew() + ), + ], + mutation_type=ValueMutationNew(), + ) + ) + except Exception as e: + unimplemented( + gb_type="Unexpected failure during itertools.groupby() iteration", + context=f"call_function {self} {args} {kwargs}", + explanation="Unexpected failure in invoking function during groupby", + hints=[*graph_break_hints.SUPPORTABLE], + from_exc=e, + ) + return variables.ListIteratorVariable( + result, # type: ignore[arg-type] + mutation_type=ValueMutationNew(), + ) + elif self.value is itertools.repeat: + # ref: repeat_new in itertoolsmodule.c. A user-supplied negative + # `times` is clamped to 0; an absent `times` means unbounded. + try: + bound = _REPEAT_SIGNATURE.bind(*args, **kwargs) + except TypeError: + raise_args_mismatch(tx, "repeat") + item = bound.arguments["object"] + times = bound.arguments.get("times") + if times is None: + return RepeatIteratorVariable(item, mutation_type=ValueMutationNew()) + if not times.is_python_constant(): + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.repeat), + [item, times], + {}, + ) + times_val = times.as_python_constant() + if not isinstance(times_val, int): + raise_type_error( + tx, + f"'{times.python_type_name()}' object cannot be interpreted " + "as an integer", + ) + return RepeatIteratorVariable( + item, times=max(times_val, 0), mutation_type=ValueMutationNew() + ) + elif self.value is itertools.count: + # count(start=0, step=1): let Python's own argument binding validate + # the call. Anything it rejects (extra args, duplicate/unknown + # kwargs) falls through to a graph break so eager raises the + # CPython TypeError. + def count_sig(start: Any = 0, step: Any = 1) -> tuple[Any, Any]: + return start, step + + try: + item, step = count_sig(*args, **kwargs) + except TypeError: + return super().call_function(tx, args, kwargs) + return variables.CountIteratorVariable( + item, step, mutation_type=ValueMutationNew() + ) + else: + return super().call_function(tx, args, kwargs) + + +class IteratorVariable(VariableTracker): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + unimplemented( + gb_type="Unimplemented next() call", + context=f"next({self})", + explanation="This abstract method must be implemented", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> "ConstantVariable": + if name == "__iter__" or name == "__next__": + return variables.ConstantVariable.create(True) + return super().call_obj_hasattr(tx, name) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + """Iterators are their own iterator.""" + return self + + +class ChainVariable(IteratorVariable): + """ + Represents itertools.chain(*iterables) — yields one item per tp_iternext_impl call. + + Uses a source_iterator that yields raw sub-iterables (not yet converted to + iterators). Conversion happens lazily in tp_iternext_impl so that non-iterable + args raise TypeError at iteration time, matching CPython's behavior. + """ + + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c#L225-L310 + _cpython_type = itertools.chain + + def __init__( + self, + source_iterator: "VariableTracker", + current: "VariableTracker | None" = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + # source_iterator yields raw sub-iterables; converted lazily per tp_iternext_impl + self.source_iterator = source_iterator + # current sub-iterator (None = not started or just exhausted a sub-iterable) + self.current = current + + def python_type(self) -> type: + return itertools.chain + + def _get_from_iterable(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + return ItertoolsVariable(_CHAIN_FROM_ITERABLE) + + tp_getset = { + "from_iterable": GetSet(_get_from_iterable), + } + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + if not self.is_mutable(): + raise AssertionError("ChainVariable must be mutable for next()") + while True: + if self.current is None: + # Pull next sub-iterable from source (source is always an iterator) + try: + next_raw = pyiter_next(tx, self.source_iterator) + except ObservedUserStopIteration: + handle_observed_exception(tx) + raise_observed_exception(StopIteration, tx) + # Convert sub-iterable to iterator lazily — may raise TypeError + it = generic_getiter(tx, next_raw) + tx.output.side_effects.mutation(self) + self.current = it + try: + return pyiter_next(tx, self.current) + except ObservedUserStopIteration: + handle_observed_exception(tx) + tx.output.side_effects.mutation(self) + self.current = None + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Reconstruct as itertools.chain(current, itertools.chain.from_iterable(source)) + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(itertools), + codegen.create_load_attr("chain"), + ] + ) + ) + if self.current is not None: + codegen(self.current) + # chain.from_iterable(source_iterator) for remaining sub-iterables + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(itertools), + codegen.create_load_attr("chain"), + codegen.create_load_attr("from_iterable"), + ] + ) + ) + codegen(self.source_iterator) + codegen.extend_output(create_call_function(1, False)) + n_args = (1 if self.current is not None else 0) + 1 + codegen.extend_output(create_call_function(n_args, False)) + + +class RepeatIteratorVariable(IteratorVariable): + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c + # repeat carries a `cnt` count: -1 means unbounded; CPython's repeat_new + # clamps a user-supplied negative `times` to 0. We model that with `times` + # (None == unbounded) and a `remaining` counter consumed by next(). + _nonvar_fields = { + "times", + "remaining", + *IteratorVariable._nonvar_fields, + } + + def __init__( + self, + item: VariableTracker, + times: int | None = None, + remaining: int | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.item = item + self.times = times + self.remaining = times if remaining is None else remaining + + def python_type(self) -> type: + return itertools.repeat + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c repeat_next + if self.remaining is None: + return self.item + if not self.is_mutable(): + raise AssertionError("bounded RepeatIteratorVariable must be mutable") + if self.remaining == 0: + raise_observed_exception(StopIteration, tx) + tx.output.side_effects.mutation(self) + self.remaining -= 1 + return self.item + + def repeat_length_hint( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # ref: repeat_len in itertoolsmodule.c (exposed as __length_hint__); + # raises TypeError for the unbounded form ("len() of unsized object"). + # Not a C-level slot, so it lives in tp_methods rather than call_method. + if self.times is None: + raise_type_error(tx, "len() of unsized object") + return ConstantVariable.create(self.remaining) + + tp_methods = { + "__length_hint__": Method(repeat_length_hint), + } + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + item_repr = tracked_repr(tx, self.item) + if self.times is None: + return ConstantVariable.create(f"repeat({item_repr})") + return ConstantVariable.create(f"repeat({item_repr}, {self.remaining})") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(itertools), + codegen.create_load_attr("repeat"), + ] + ) + ) + codegen(self.item) + if self.times is None: + codegen.extend_output(create_call_function(1, False)) + else: + codegen(ConstantVariable.create(self.remaining)) + codegen.extend_output(create_call_function(2, False)) + + +class CountIteratorVariable(IteratorVariable): + # advance_count tracks how many next() calls were made during tracing, + # used by side_effects.py to replay them on the real iterator post-execution. + _nonvar_fields = { + "advance_count", + *IteratorVariable._nonvar_fields, + } + + def python_type(self) -> type: + return itertools.count + + def __init__( + self, + item: int | VariableTracker = 0, + step: int | VariableTracker = 1, + advance_count: int = 0, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(item, VariableTracker): + item = ConstantVariable.create(item) + if not isinstance(step, VariableTracker): + step = ConstantVariable.create(step) + self.item = item + self.step = step + self.advance_count = advance_count + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c#L4189-L4216 + if not self.is_mutable(): + raise AssertionError("CountIteratorVariable must be mutable for next()") + old_item = self.item + tx.output.side_effects.mutation(self) + self.item = self.item.call_method(tx, "__add__", [self.step], {}) + self.advance_count += 1 + return old_item + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c#L4218-L4243 + if not (self.item.is_python_constant() and self.step.is_python_constant()): + return super().tp_repr_impl(tx) + cnt = self.item.as_python_constant() + step = self.step.as_python_constant() + # Suppress step in the repr when it is an integer equal to 1. + if isinstance(step, int) and step == 1: + result = f"count({cnt!r})" + else: + result = f"count({cnt!r}, {step!r})" + return ConstantVariable.create(result) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(itertools), + codegen.create_load_attr("count"), + ] + ) + ) + codegen(self.item) + codegen(self.step) + codegen.extend_output(create_call_function(2, False)) + + +class ZipVariable(IteratorVariable): + """ + Represents zip(*iterables) + """ + + # PyZip_Type: https://github.com/python/cpython/blob/v3.13.0/Python/bltinmodule.c#L3011 + _cpython_type = zip + + _nonvar_fields = { + "strict", + *IteratorVariable._nonvar_fields, + } + + def __init__( + self, + iterable: VariableTracker, + strict: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(iterable, variables.TupleVariable): + raise AssertionError(f"Expected a tuple of iterables, got {type(iterable)}") + # can be list[Variable] or VariableTracker (with next_variable implemented) + self.iterable = iterable + self.strict = strict + + def python_type(self) -> type[zip]: # type: ignore[type-arg] + return zip + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Python/bltinmodule.c#L2906-L2994 + if not self.is_mutable(): + raise AssertionError("ZipVariable must be mutable for next()") + tuplesize = len(self.iterable.items) + + if tuplesize == 0: + raise_observed_exception(StopIteration, tx) + + items = [] + for i in range(tuplesize): + it = self.iterable.items[i] + try: + items.append(pyiter_next(tx, it)) + except ObservedUserStopIteration: + if not self.strict: + raise + + if i > 0: + raise_value_error( + tx, f"zip() argument {i} shorter than previous arguments" + ) + + # In strict mode, if any iterable is exhausted, all must be exhausted + for j in range(i + 1, tuplesize): + it_j = self.iterable.items[j] + if is_iterator_exhausted(tx, it_j): + continue + break + else: + # all iterables exhausted, raise StopIteration + raise + + handle_observed_exception(tx) # StopIteration + raise_value_error( + tx, f"zip() argument {i} is longer than previous arguments" + ) + + return variables.TupleVariable(items) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from("builtins", "zip"), call_function_ex=True + ) + codegen(self.iterable) + codegen.extend_output( + [ + codegen.create_load_const("strict"), + codegen.create_load_const(self.strict), + create_instruction("BUILD_MAP", arg=1), + *create_call_function_ex(True, False), + ] + ) + + +class ZipLongestVariable(IteratorVariable): + """ + Represents itertools.zip_longest(*iterables, fillvalue=None) + """ + + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c#L2822-L2887 + _cpython_type = itertools.zip_longest + + _nonvar_fields = { + "exhausted", + *IteratorVariable._nonvar_fields, + } + + def __init__( + self, + iterables: "list[VariableTracker]", + fillvalue: "VariableTracker", + exhausted: "list[bool] | None" = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.iterables = iterables + self.fillvalue = fillvalue + self.exhausted = ( + exhausted if exhausted is not None else [False] * len(iterables) + ) + + def python_type(self) -> type: + return itertools.zip_longest + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c#L2737-L2808 + if not self.is_mutable(): + raise AssertionError("ZipLongestVariable must be mutable for next()") + if all(self.exhausted): + raise_observed_exception(StopIteration, tx) + values = [] + # CPython: when the last active iterator exhausts, return without yielding. + any_active = False + for i, it in enumerate(self.iterables): + if self.exhausted[i]: + values.append(self.fillvalue) + else: + try: + values.append(pyiter_next(tx, it)) + any_active = True + except ObservedUserStopIteration: + handle_observed_exception(tx) + tx.output.side_effects.mutation(self) + self.exhausted[i] = True + values.append(self.fillvalue) + if not any_active: + raise_observed_exception(StopIteration, tx) + return variables.TupleVariable(values) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(itertools), + codegen.create_load_attr("zip_longest"), + ] + ), + call_function_ex=True, + ) + for i, it in enumerate(self.iterables): + if not self.exhausted[i]: + codegen(it) + else: + codegen.add_push_null( + lambda: codegen.append_output( + codegen.create_load_python_module(iter) # type: ignore[arg-type] + ) + ) + codegen.extend_output( + [ + create_instruction("BUILD_TUPLE", arg=0), + *create_call_function(1, False), + ] + ) + codegen.extend_output( + [create_instruction("BUILD_TUPLE", arg=len(self.iterables))] + ) + codegen.extend_output([codegen.create_load_const("fillvalue")]) + codegen(self.fillvalue) + codegen.extend_output( + [ + create_instruction("BUILD_MAP", arg=1), + *create_call_function_ex(True, False), + ] + ) + + +class MapVariable(IteratorVariable): + """ + Represents map(fn, *iterables) + """ + + # PyMap_Type: https://github.com/python/cpython/blob/v3.13.0/Python/bltinmodule.c#L1484 + _cpython_type = map + + _nonvar_fields = { + "strict", + *IteratorVariable._nonvar_fields, + } + + def __init__( + self, + fn: VariableTracker, + iterables: VariableTracker, + strict: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.fn = fn + if not isinstance(iterables, variables.TupleVariable): + raise AssertionError( + f"Expected a tuple of iterables, got {type(iterables)}" + ) + self.iterable = iterables + self.strict = strict + + def python_type(self) -> type: + return map + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Python/bltinmodule.c#L1409-L1450 + if not self.is_mutable(): + raise AssertionError("MapVariable must be mutable for next()") + + tuplesize = len(self.iterable.items) + + items = [] + for i in range(tuplesize): + it = self.iterable.items[i] + try: + items.append(pyiter_next(tx, it)) + except ObservedUserStopIteration: + if not self.strict: + raise + + handle_observed_exception(tx) # StopIteration + + if i: + raise_value_error( + tx, + f"map() argument {i + 1} shorter than argument {i}", + ) + + # In strict mode, if any iterable is exhausted, all must be exhausted. + for j in range(1, tuplesize): + it_j = self.iterable.items[j] + if not is_iterator_exhausted(tx, it_j): + raise_value_error( + tx, f"map() argument {j + 1} is longer than argument {j}" + ) + + raise_observed_exception(StopIteration, tx) + + # type: ignore[attr-defined] + return self.fn.call_function(tx, items, {}) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from("builtins", "map"), call_function_ex=True + ) + codegen(variables.TupleVariable([self.fn, *self.iterable.items])) + if self.strict: + if sys.version_info < (3, 14): + raise AssertionError( + "Unexpected bug: map(strict=True) requires Python 3.14+" + ) + codegen.extend_output( + [ + codegen.create_load_const("strict"), + codegen.create_load_const(self.strict), + create_instruction("BUILD_MAP", arg=1), + *create_call_function_ex(True, False), + ] + ) + else: + codegen.extend_output(create_call_function_ex(False, False)) + + +class FilterVariable(IteratorVariable): + """ + Represents filter(fn, iterable) + """ + + # PyFilter_Type: https://github.com/python/cpython/blob/v3.13.0/Python/bltinmodule.c#L630 + _cpython_type = filter + + def __init__( + self, + fn: VariableTracker, + iterable: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.fn = fn + self.iterable = iterable + + def python_type(self) -> type: + return filter + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Python/bltinmodule.c#L573-L606 + # A do-while loop to find elements that make fn return true + while True: + item = pyiter_next(tx, self.iterable) + if self.fn.is_constant_none(): + res = item + else: + res = self.fn.call_function(tx, [item], {}) + pred_res = variables.UserFunctionVariable( + polyfills.predicate # type: ignore[arg-type] + ).call_function(tx, [res], {}) + if pred_res.as_python_constant(): + return item + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("builtins", "filter")) + codegen(self.fn) + codegen(self.iterable) + codegen.extend_output(create_call_function(2, False)) + + +class DictViewIterator(IteratorVariable): + """Base class for dict view iterators (keys, values, or items).""" + + _nonvar_fields = { + "view_type", + *IteratorVariable._nonvar_fields, + } + + view_type: str = "keys" + + def __init__( + self, + items: dict[HashableTracker, VariableTracker], + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if self.view_type == "keys": + self._iter = iter(items) + elif self.view_type == "values": + self._iter = iter(items.values()) # type: ignore[bad-assignment] + else: + if self.view_type != "items": + raise AssertionError( + f"Expected view_type 'items', got {self.view_type!r}" + ) + self._iter = iter(items.items()) # type: ignore[bad-assignment] + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # dictiter_iternextitem: https://github.com/python/cpython/blob/v3.13.3/Objects/dictobject.c#L5538-L5578 + # dictiter_iternextkey: https://github.com/python/cpython/blob/v3.13.3/Objects/dictobject.c#L5125-L5144 + # dictiter_iternextvalue: https://github.com/python/cpython/blob/v3.13.3/Objects/dictobject.c#L5248-L5267 + try: + item = next(self._iter) + + if self.view_type == "keys": + return item.vt + elif self.view_type == "values": + return item # type: ignore[bad-return] + else: # items + k, v = item # type: ignore[not-iterable] + return VariableTracker.build(tx, (k.vt, v)) + except (RuntimeError, StopIteration) as e: + raise_observed_exception( + type(e), + tx, + args=[VariableTracker.build(tx, a) for a in e.args], + ) + + def dict_view_iter_length_hint( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # dictiter_len/setiter_len: __length_hint__ returns the number of + # not-yet-consumed elements. self._iter is a live Python iterator over + # the captured items, so its own length hint already reflects any + # next() calls made during tracing. + # Not a C-level slot, so it lives in tp_methods rather than call_method. + return ConstantVariable.create(operator.length_hint(self._iter)) + + tp_methods = { + "__length_hint__": Method(dict_view_iter_length_hint), + } + + def python_type(self) -> type: + if self.view_type == "keys": + return type(iter({})) + elif self.view_type == "values": + return type(iter({}.values())) + else: # items + return type(iter({}.items())) + + +class DictIterator(DictViewIterator): + _cpython_type = type(iter({})) + view_type = "keys" + + +class DictKeysIterator(DictViewIterator): + _cpython_type = type(iter({}.keys())) + view_type = "keys" + + +class DictValuesIterator(DictViewIterator): + _cpython_type = type(iter({}.values())) + view_type = "values" + + +class DictItemsIterator(DictViewIterator): + _cpython_type = type(iter({}.items())) + view_type = "items" + + +class SetIterator(DictViewIterator): + _cpython_type = type(iter(set())) + view_type = "keys" diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lazy.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lazy.py new file mode 100644 index 0000000000000000000000000000000000000000..a07fe7e2e1c6f1cc1f5510ad8f49205d95969235 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lazy.py @@ -0,0 +1,719 @@ +from __future__ import annotations + +import collections +import functools +import inspect +from typing import Any, TYPE_CHECKING + +from .. import config +from ..utils import is_function_or_wrapper +from .base import SourceLocation, VariableTracker, VariableTrackerMeta + + +if TYPE_CHECKING: + from collections.abc import Callable + from typing_extensions import Self + + from ..symbolic_convert import InstructionTranslatorBase + from .tensor import SymNodeVariable + + +class LazyCache: + """Container to cache the real VariableTracker""" + + def __init__(self, value: Any, source: Any) -> None: + if not isinstance(value, LazySymNodeFormatString): + if not source: + raise AssertionError( + "source is required for non-LazySymNodeFormatString values" + ) + self.value = value + self.source = source + self.name_hint: str | None = None + self.source_location: SourceLocation | None = None + self.vt: VariableTracker | None = None + + def realize(self) -> None: + if self.vt is not None: + raise AssertionError("LazyCache.realize() called but vt is already set") + from ..symbolic_convert import InstructionTranslator + from . import builder + + tx = InstructionTranslator.current_tx() + + if isinstance(self.value, LazySymNodeFormatString): + self.vt = builder.SourcelessBuilder.create(tx, self.value) + else: + # Pass allow_lazy_constant=False to prevent VariableBuilder from + # returning LazyConstantVariable, which would cause infinite recursion + # when LazyVariableTracker.realize() returns LazyConstantVariable. + self.vt = builder.VariableBuilder( + tx, self.source, allow_lazy_constant=False + )(self.value) + + if self.name_hint is not None: + self.vt.set_name_hint(self.name_hint) + + if self.source_location is not None and self.vt.source_location is None: + self.vt.set_source_location(self.source_location) + + del self.value + del self.source + del self.name_hint + del self.source_location + + +class ComputedLazyCache: + """Like LazyCache, but for sourceless constants computed from lazy operands.""" + + def __init__( + self, + value: Any, + lazy_vars: list[LazyConstantVariable], + args: list[VariableTracker], + op: Callable[..., Any], + num_nodes: int, + ) -> None: + self.value = value + self.lazy_vars = lazy_vars + self.args = args + self.op = op + self.num_nodes = num_nodes + self.name_hint: str | None = None + self.source_location: SourceLocation | None = None + self.vt: VariableTracker | None = None + + def realize(self) -> None: + if self.vt is not None: + raise AssertionError( + "ComputedLazyCache.realize() called but vt is already set" + ) + from ..symbolic_convert import InstructionTranslator + from .constant import ConstantVariable + from .tensor import SymNodeVariable + + any_symbolic = False + for lazy_var in self.lazy_vars: + if isinstance(lazy_var.realize(), SymNodeVariable): + any_symbolic = True + + if any_symbolic: + # The precomputed constant is stale; recompute symbolically + from .builtin import BuiltinVariable + + tx = InstructionTranslator.current_tx() + realized_args = [arg.realize() for arg in self.args] + self.vt = BuiltinVariable(self.op).call_function(tx, realized_args, {}) + else: + self.vt = ConstantVariable.create(self.value) + + if self.name_hint is not None: + self.vt.set_name_hint(self.name_hint) + if self.source_location is not None and self.vt.source_location is None: + self.vt.set_source_location(self.source_location) + + +class LazyVariableTracker(VariableTracker, metaclass=VariableTrackerMeta): + """ + A structure that defers the creation of the actual VariableTracker + for a given underlying value until it is accessed. + + The `realize` function invokes VariableTracker.build() to produce the real object. + Once a LazyVariableTracker has been realized, internal bookkeeping will + prevent double realization. + + This object should be utilized for processing containers, or objects that + reference other objects where we may not want to take on creating all the + VariableTrackers right away. + """ + + # Flag to prevent implicit realization in isinstance checks (inherited by subclasses) + _no_implicit_realize = True + _nonvar_fields = {"_cache", *VariableTracker._nonvar_fields} + + @staticmethod + def create( + value: Any, + source: Any, + *, + tx: InstructionTranslatorBase | None = None, + **options: Any, + ) -> VariableTracker: + if type(value) in LazyConstantVariable.supported_types: + return LazyConstantVariable.create(value, source, **options) + + # Cache based on source when no extra options are passed + if tx is not None and source is not None and not options: + cache = tx.output.variable_tracker_cache + cached = cache.get(source) + if cached is not None: + return cached + vt = LazyVariableTracker(LazyCache(value, source), source=source) + cache[source] = vt + return vt + + return LazyVariableTracker(LazyCache(value, source), source=source, **options) + + def __init__(self, _cache: LazyCache | ComputedLazyCache, **kwargs: Any) -> None: + if not isinstance(_cache, (LazyCache, ComputedLazyCache)): + raise AssertionError( + f"_cache must be a LazyCache or ComputedLazyCache instance, got {type(_cache).__name__}" + ) + super().__init__(**kwargs) + self._cache = _cache + + def realize(self) -> VariableTracker: + """Force construction of the real VariableTracker""" + if self._cache.vt is None: + self._cache.realize() + if self._cache.vt is None: + raise AssertionError("LazyCache.realize() did not set vt") + return self._cache.vt + + def lazy_isinstance(self, cls: type) -> bool: + """Check isinstance after realizing, used by ImplicitRealizingVariableTrackerMeta""" + return type.__instancecheck__(cls, self.realize()) + + def unwrap(self) -> VariableTracker | Self: + """Return the real VariableTracker if it already exists""" + if self.is_realized(): + if self._cache.vt is None: + raise AssertionError("is_realized() returned True but vt is None") + return self._cache.vt + return self + + def is_realized(self) -> bool: + return self._cache.vt is not None + + def clone(self, **kwargs: Any) -> VariableTracker: + if kwargs.get("_cache", self._cache) is not self._cache: + raise AssertionError( + "cannot clone LazyVariableTracker with a different _cache" + ) + if kwargs.get("source", self.source) is not self.source: + self.realize() + return VariableTracker.clone(self.unwrap(), **kwargs) + + def peek_type(self) -> type[Any]: + if self.is_realized(): + raise AssertionError( + "peek_type() called on an already realized LazyVariableTracker" + ) + return type(self._cache.value) + + def peek_value(self) -> Any: + if self.is_realized(): + raise AssertionError( + "peek_value() called on an already realized LazyVariableTracker" + ) + return self._cache.value + + def set_name_hint(self, name: str) -> None: + if self.is_realized(): + self._cache.vt.set_name_hint(name) # type: ignore[union-attr] + else: + self._cache.name_hint = name + + def set_source_location(self, source_location: SourceLocation) -> None: + self.source_location = source_location + if self.is_realized(): + self._cache.vt.set_source_location(source_location) # type: ignore[union-attr] + else: + self._cache.source_location = source_location + + def __str__(self) -> str: + variable_info = "LazyVariableTracker(" + if self.is_realized(): + variable_info += f"realized: {repr(self.unwrap())})" + else: + variable_info += f"unrealized: {self.peek_type()})" + + return variable_info + + def __getattr__(self, item: str) -> Any: + return getattr(self.realize(), item) + + def get_handler_type_for_dispatch(self) -> type: + """Return the VariableTracker type to use for builtin handler dispatch. + + For regular LazyVariableTracker (not LazyConstantVariable), we return + LazyVariableTracker itself so that _make_handler knows it needs to realize + the arguments before calling the handler. LazyConstantVariable overrides + this to return ConstantVariable since it can stay lazy. + """ + return LazyVariableTracker + + # most methods are auto-generated below, these are the ones we want to exclude + visit = VariableTracker.visit # type: ignore[assignment] + __repr__ = __str__ + + @classmethod + def realize_all( + cls, + value: Any, + cache: dict[int, tuple[Any, Any]] | None = None, + *, + allow_lazy_constant: bool = False, + ) -> Any: + """ + Walk an object and realize all LazyVariableTrackers inside it. + """ + if cache is None: + cache = {} + + idx = id(value) + if idx in cache: + return cache[idx][0] + + value_cls = type(value) + if issubclass(value_cls, LazyVariableTracker): + # Allow LazyConstantVariable and ComputedLazyConstantVariable to + # stay lazy when returning from a frame + keep_lazy = allow_lazy_constant and isinstance( + value, (LazyConstantVariable, ComputedLazyConstantVariable) + ) + if keep_lazy: + if isinstance(value, ComputedLazyConstantVariable): + if value.is_realized(): + result = cls.realize_all( + value.realize(), cache, allow_lazy_constant=True + ) + else: + # Output bytecode recomputes the value; operands only need TYPE_MATCH + for lazy_var in value._cache.lazy_vars: + lazy_var._ensure_type_guard() + result = value + else: + result = value + else: + result = cls.realize_all( + value.realize(), cache, allow_lazy_constant=allow_lazy_constant + ) + elif issubclass(value_cls, VariableTracker): + # update value in-place + result = value + # update cache now to prevent infinite recursion + cache[idx] = (result, value) + value_dict = value.__dict__ + nonvars = value._nonvar_fields + for key in value_dict: + if key not in nonvars: + value_dict[key] = cls.realize_all( + value_dict[key], cache, allow_lazy_constant=allow_lazy_constant + ) + elif value_cls is list: + result = [ + cls.realize_all(v, cache, allow_lazy_constant=allow_lazy_constant) + for v in value + ] + elif value_cls is tuple: + result = tuple( + cls.realize_all(v, cache, allow_lazy_constant=allow_lazy_constant) + for v in value + ) + elif value_cls in (dict, collections.OrderedDict): + result = { + k: cls.realize_all(v, cache, allow_lazy_constant=allow_lazy_constant) + for k, v in list(value.items()) + } + else: + result = value + + # save `value` to keep it alive and ensure id() isn't reused + cache[idx] = (result, value) + return result + + def is_hashable_lazy(self) -> bool: + # Checks that the underlying value is hashable without realizing the VT. + # This is used by the is_hashable() function in hashable.py as a fast + # path for unrealized LazyVTs. + def _helper(value: Any) -> bool: + # TODO: Add support for more types + return ( + inspect.isbuiltin(value) + or issubclass(type(value), type) + or is_function_or_wrapper(value) + ) + + if self.is_realized(): + raise AssertionError( + "is_hashable() called on an already realized LazyVariableTracker" + ) + value = self._cache.value + if isinstance(value, tuple): + return all(_helper(v) for v in value) + return _helper(value) + + def original_value(self) -> Any: + # Returns the value without realizing the VT. + if self.is_realized(): + raise AssertionError( + "original_value() called on an already realized LazyVariableTracker" + ) + return self._cache.value + + def original_source(self) -> Any: + # Returns the source without realizing the VT. + if self.is_realized(): + raise AssertionError( + "original_source() called on an already realized LazyVariableTracker" + ) + # pyrefly: ignore[missing-attribute] + return self._cache.source + + +class LazyConstantVariable(LazyVariableTracker): + """ + A lazy variable tracker for constants (int, float, bool, str) that defers + guarding until the value is actually used in a way that requires it. + + This allows constants that are just passed through (e.g., returned without + being used in control flow or math) to avoid unnecessary recompilation when + their values change. + + Guards are installed lazily: + - TYPE_MATCH guard is installed when type-based methods (python_type, is_tensor, + lazy_isinstance) are called + - CONSTANT_MATCH guard is installed on full realization (e.g., used in control + flow or math), which subsumes any TYPE_MATCH guard + """ + + supported_types = (int, float, bool, str) + _nonvar_fields = { + "_type_guard_installed", + "_type_guard_ref", + "_handler_type", + *LazyVariableTracker._nonvar_fields, + } + + @staticmethod + def create( + value: Any, + source: Any, + **options: Any, + ) -> VariableTracker: + from ..source import is_constant_source + from .constant import ConstantVariable + + if type(value) not in LazyConstantVariable.supported_types: + raise AssertionError( + f"unsupported type {type(value).__name__} for LazyConstantVariable" + ) + if source is None: + raise AssertionError("source must not be None for LazyConstantVariable") + + # If the source doesn't support guards (e.g., ConstantSource), fall back + # to creating a regular ConstantVariable directly + if is_constant_source(source): + return ConstantVariable.create(value, source=source, **options) + + return LazyConstantVariable(LazyCache(value, source), source=source, **options) + + def __init__(self, _cache: LazyCache, **kwargs: Any) -> None: + super().__init__(_cache, **kwargs) + self._type_guard_installed = False + self._type_guard_ref: Any = None + self._handler_type: type | None = None + + def _ensure_type_guard(self) -> None: + """Install TYPE_MATCH guard if not already installed and not realized.""" + if self._type_guard_installed or self.is_realized(): + return + + from ..guards import GuardBuilder, install_guard + + if self.source is None: + raise AssertionError("source must not be None when installing type guard") + guard = self.source.make_guard(GuardBuilder.TYPE_MATCH) + install_guard(guard) + self._type_guard_installed = True + self._type_guard_ref = guard + + def realize(self) -> VariableTracker: + """Force construction of the real VariableTracker.""" + if self.is_realized(): + return super().realize() + + from torch._guards import TracingContext + + from ..guards import GuardBuilder, install_guard + from .constant import ConstantVariable + + if self.source is None: + raise AssertionError( + "source must not be None when realizing LazyConstantVariable" + ) + + result = super().realize() + + # Only remove TYPE_MATCH if we're installing CONSTANT_MATCH + # (which subsumes it). For SymNodeVariable, keep TYPE_MATCH. + if isinstance(result, ConstantVariable): + if self._type_guard_ref is not None: + tracing_context = TracingContext.get() + tracing_context.guards_context.dynamo_guards.inner.discard( + self._type_guard_ref + ) + self._type_guard_ref = None + install_guard(self.source.make_guard(GuardBuilder.CONSTANT_MATCH)) + + return result + + def python_type(self) -> type: + """Return the Python type without triggering realization.""" + if self.is_realized(): + return super().python_type() + self._ensure_type_guard() + return self.peek_type() + + def is_tensor(self) -> bool: + """Primitive constants are never tensors.""" + self._ensure_type_guard() + return False + + def is_constant_none(self) -> bool: + self._ensure_type_guard() + return False + + def _maybe_realize_for_type(self) -> type | None: + """Check if we need to realize to determine the VariableTracker type. + + Returns None if we can determine the type without realization (and installs + TYPE_MATCH guard). Returns the realized type if realization was needed. + + With specialize_int=False or specialize_float=False, ints/floats may become + either ConstantVariable or SymNodeVariable, so we must realize to know. + For bool/str, we always know it will be ConstantVariable. + """ + if self.is_realized(): + return type(self.realize()) + + value_type = self.peek_type() + + # When specialize_int/specialize_float is False, ints/floats may become + # SymNodeVariable. Must realize to determine the actual type. + if not config.specialize_int and value_type is int: + return type(self.realize()) + if not config.specialize_float and value_type is float: + return type(self.realize()) + + # For bool/str, or when specializing ints/floats, we know it will be + # ConstantVariable. Install TYPE_MATCH guard and return None. + self._ensure_type_guard() + return None + + def get_handler_type_for_dispatch(self) -> type: + """Return the VariableTracker type to use for builtin handler dispatch. + + This allows builtins like isinstance() and type() to find the correct + handler without triggering full realization of the lazy constant. + """ + if self._handler_type is not None: + return self._handler_type + + from .constant import ConstantVariable + + realized_type = self._maybe_realize_for_type() + self._handler_type = ( + realized_type if realized_type is not None else ConstantVariable + ) + return self._handler_type + + def lazy_isinstance(self, cls: type) -> bool: + """Check isinstance without triggering realization when possible. + + LazyConstantVariable only wraps primitive types (int, float, bool, str) + which always realize to ConstantVariable, so we can answer isinstance + checks by checking if the target class is ConstantVariable or a parent. + + However, when specialize_int=False or specialize_float=False, integers + and floats may realize to SymNodeVariable instead of ConstantVariable, + so we must fall back to full realization for those cases. + """ + from .constant import ConstantVariable + from .tensor import SymNodeVariable + + # If already realized, delegate to the parent which does the regular check + if self.is_realized(): + return super().lazy_isinstance(cls) + + # LazyConstantVariable can only realize to ConstantVariable or SymNodeVariable. + # If cls is not a parent of either, we can answer False without realization. + if not issubclass(ConstantVariable, cls) and not issubclass( + SymNodeVariable, cls + ): + self._ensure_type_guard() + return False + + realized_type = self._maybe_realize_for_type() + if realized_type is not None: + return issubclass(realized_type, cls) + return issubclass(ConstantVariable, cls) + + +class ComputedLazyConstantVariable(LazyVariableTracker): + """ + Result of a supported op over lazy constant operands. The value is computed + eagerly at trace time but guards are deferred: if never realized, output + bytecode recomputes it from the operands (TYPE_MATCH only); realization + realizes the operands, installing their CONSTANT_MATCH guards. + """ + + _cache: ComputedLazyCache # pyrefly: ignore[bad-override] + + @staticmethod + def create( # pyrefly: ignore[bad-param-name-override, bad-override] + op: Callable[..., Any], + args: list[VariableTracker], + ) -> VariableTracker | None: + """Compute op(*args) eagerly; returns None to fall back to realization.""" + from .constant import ConstantVariable + + max_nodes = config.computed_lazy_constant_max_nodes + if max_nodes <= 0: + return None + + lazy_vars: list[LazyConstantVariable] = [] + num_nodes = 1 + + def get_value(arg: VariableTracker) -> Any: + nonlocal num_nodes + if isinstance(arg, ComputedLazyConstantVariable) and not arg.is_realized(): + lazy_vars.extend(arg._cache.lazy_vars) + num_nodes += arg._cache.num_nodes + return arg._cache.value + if isinstance(arg, LazyConstantVariable) and not arg.is_realized(): + lazy_vars.append(arg) + return arg.peek_value() + return arg.as_python_constant() + + values = [get_value(arg) for arg in args] + # realize/reconstruct recurse through args; unbounded chains overflow the stack + if num_nodes > max_nodes: + return None + try: + value = op(*values) + except Exception: + return None + if not ConstantVariable.is_base_literal(value): + return None + if not lazy_vars: + return ConstantVariable.create(value) + return ComputedLazyConstantVariable( + ComputedLazyCache(value, lazy_vars, list(args), op, num_nodes) + ) + + def __init__(self, _cache: ComputedLazyCache, **kwargs: Any) -> None: + if not isinstance(_cache, ComputedLazyCache): + raise AssertionError( + f"_cache must be a ComputedLazyCache instance, got {type(_cache).__name__}" + ) + super().__init__(_cache, **kwargs) + + def _ensure_operand_type_guards(self) -> None: + # Type queries on the result depend on the operand types + for lazy_var in self._cache.lazy_vars: + lazy_var._ensure_type_guard() + + def python_type(self) -> type: + if self.is_realized(): + return super().python_type() + self._ensure_operand_type_guards() + return type(self._cache.value) + + def is_tensor(self) -> bool: + if self.is_realized(): + return super().is_tensor() + self._ensure_operand_type_guards() + return False + + def _might_realize_symbolic(self) -> bool: + # Mirrors LazyConstantVariable._maybe_realize_for_type + from .tensor import SymNodeVariable + + for lazy_var in self._cache.lazy_vars: + if lazy_var.is_realized(): + if type.__instancecheck__(SymNodeVariable, lazy_var.realize()): + return True + else: + value_type = lazy_var.peek_type() + if value_type is int and not config.specialize_int: + return True + if value_type is float and not config.specialize_float: + return True + return False + + def get_handler_type_for_dispatch(self) -> type: + from .constant import ConstantVariable + + if not self.is_realized() and not self._might_realize_symbolic(): + self._ensure_operand_type_guards() + return ConstantVariable + return type(self.realize()) + + def lazy_isinstance(self, cls: type) -> bool: + from .constant import ConstantVariable + from .tensor import SymNodeVariable + + if self.is_realized(): + return type.__instancecheck__(cls, self.realize()) + if not issubclass(ConstantVariable, cls) and not issubclass( + SymNodeVariable, cls + ): + self._ensure_operand_type_guards() + return False + if self._might_realize_symbolic(): + return type.__instancecheck__(cls, self.realize()) + self._ensure_operand_type_guards() + return issubclass(ConstantVariable, cls) + + def reconstruct(self, codegen: Any) -> None: + from ..bytecode_transformation import create_call_function + + cache = self._cache + codegen.add_push_null( + lambda: codegen.load_import_from("operator", cache.op.__name__) + ) + for arg in cache.args: + codegen(arg) + codegen.extend_output(create_call_function(len(cache.args), False)) + + +class LazySymNodeFormatString: + def __init__( + self, sym_node_variable: SymNodeVariable, fmt_spec_var: VariableTracker + ) -> None: + from .constant import ConstantVariable + + self.sym_node_var = sym_node_variable + self.fmt_var = ConstantVariable.create( + "{:" + fmt_spec_var.as_python_constant() + "}" + ) + + def __repr__(self) -> str: + return str.format( + self.fmt_var.as_python_constant(), + str(self.sym_node_var.evaluate_expr()), + ) + + +def _create_realize_and_forward( + name: str, +) -> Callable[[LazyVariableTracker, Any, Any], Any]: + @functools.wraps(getattr(VariableTracker, name)) + def realize_and_forward( + self: LazyVariableTracker, *args: Any, **kwargs: Any + ) -> Any: + return getattr(self.realize(), name)(*args, **kwargs) + + return realize_and_forward + + +def _populate() -> None: + for name, value in VariableTracker.__dict__.items(): + if name not in LazyVariableTracker.__dict__: + if callable(value): + setattr(LazyVariableTracker, name, _create_realize_and_forward(name)) + + +_populate() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lists.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lists.py new file mode 100644 index 0000000000000000000000000000000000000000..d4a2493f53e72988d6ed7d9ed45ff447a5d99940 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lists.py @@ -0,0 +1,2529 @@ +""" +Variable tracking implementations for list-like data structures in Dynamo. + +This module provides specialized variable tracking for various collection types: +- Lists and list subclasses (including torch.nn.ModuleList, ParameterList) +- Tuples and named tuples +- Ranges and slices +- Collections.deque +- torch.Size with special proxy handling + +The implementations support both mutable and immutable collections, iteration, +and common sequence operations. Each collection type has a dedicated Variable +class that handles its unique behaviors while integrating with Dynamo's +variable tracking system. +""" + +import collections +import operator +import sys +from typing import Any, Optional, TYPE_CHECKING + +import torch +import torch.fx +from torch.utils._pytree import SequenceKey + +from .. import graph_break_hints, polyfills, variables +from ..bytecode_transformation import ( + create_build_tuple, + create_call_function, + create_call_method, + create_dup_top, + create_instruction, +) +from ..exc import ( + ObservedException, + raise_observed_exception, + raise_type_error, + unimplemented, + Unsupported, +) +from ..source import AttrSource +from ..utils import ( + check_positional, + cmp_name_to_op_mapping, + get_fake_value, + guard_if_dyn, + iter_contains, + odict_values, + raise_args_mismatch, + range_iterator, + set_example_value, + tracked_repr, + unpack_and_apply_fn, + unpack_iterable, +) +from .base import ( + AsPythonConstantNotImplementedError, + GetSet, + Method, + ValueMutationNew, + VariableTracker, +) +from .constant import ConstantVariable +from .functions import UserFunctionVariable +from .iter import IteratorVariable +from .object_protocol import ( + generic_richcompare_bool, + maybe_get_python_type, + pyindex_check, + pylong_as_ssize_t, + pynumber_as_ssize_t, + pynumber_index, + type_implements_nb_index, + vt_is_iterable, +) + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +def pytuple_checkexact(obj: VariableTracker) -> bool: + return obj.python_type() is tuple + + +def pytuple_check(obj: VariableTracker) -> bool: + return issubclass(obj.python_type(), tuple) + + +def pylist_check(obj: VariableTracker) -> bool: + return issubclass(obj.python_type(), list) + + +def pylist_checkexact(obj: VariableTracker) -> bool: + return obj.python_type() is list + + +def pyslice_check(obj: VariableTracker) -> bool: + return issubclass(obj.python_type(), slice) + + +def _cpython_has_simple_slice_bug() -> bool: + # CPython gh-120384 fixed an array-out-of-bounds crash by moving the + # PySequence_Fast check ahead of the step==1 branch in + # list_ass_subscript, which as a side effect unified the non-iterable + # error message for simple and extended slices. Before this landed, + # simple slices (step is None or 1) raised "can only assign an + # iterable" instead of "must assign iterable to extended slice". + # Verified empirically against real CPython builds: the fix shipped in + # 3.10.20, 3.11.15, and 3.12.5 (3.12.0 is the first 3.12 release, so + # 3.12.0-3.12.4 predate it); 3.13+ never had the bug. + v = sys.version_info + if v[:2] == (3, 10): + return v < (3, 10, 20) + if v[:2] == (3, 11): + return v < (3, 11, 15) + if v[:2] == (3, 12): + return v < (3, 12, 5) + return False + + +class BaseListVariable(VariableTracker): + @staticmethod + def cls_for_instance(obj: Any) -> type["BaseListVariable"]: + return BaseListVariable.cls_for(type(obj)) + + @staticmethod + def cls_for(obj: Any) -> type: + return { + iter: ListIteratorVariable, + list: ListVariable, + slice: SliceVariable, + torch.Size: SizeVariable, + tuple: TupleVariable, + odict_values: ListVariable, + torch.nn.ParameterList: ListVariable, + torch.nn.ModuleList: ListVariable, + collections.deque: DequeVariable, + }[obj] + + def __init__( + self, + items: list[VariableTracker], + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(items, list): + raise AssertionError(f"items must be a list, got {type(items).__name__}") + if not all(isinstance(x, VariableTracker) for x in items): + raise AssertionError("all items must be VariableTracker instances") + self.items: list[VariableTracker] = items + + def _as_proxy(self) -> list[Any]: + return [x.as_proxy() for x in self.items] + + def modified( + self, items: list[VariableTracker], **kwargs: Any + ) -> "BaseListVariable": + return type(self)(items, **kwargs) + + @property + def value(self) -> Any: + return self.as_python_constant() + + def debug_repr_helper(self, prefix: str, suffix: str) -> str: + return prefix + ", ".join(i.debug_repr() for i in self.items) + suffix + + def as_python_constant(self) -> Any: + return self.python_type()([x.as_python_constant() for x in self.items]) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + return VariableTracker.build(tx, self.debug_repr()) + + def as_proxy(self) -> Any: + if self.python_type() is SizeVariable: + raise AssertionError( + "SizeVariable should not use BaseListVariable.as_proxy" + ) + return self.python_type()(self._as_proxy()) + + def getitem_const( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + if pyindex_check(maybe_get_python_type(arg)): + index = pynumber_as_ssize_t(tx, arg).as_python_constant() + try: + return self.items[index] + except IndexError: + raise_observed_exception( + IndexError, tx, args=["list index out of range"] + ) + elif pyslice_check(arg): + if not isinstance(arg, SliceVariable): + raise AssertionError("Expected arg to be a SliceVariable") + index = arg.as_index_slice(tx) + if index.step == 0: + raise_observed_exception( + ValueError, tx, args=["slice step cannot be zero"] + ) + # Set source to None because slicing a list gives a new local + return self.clone( + items=self.items[index], + source=None, + mutation_type=ValueMutationNew() if self.mutation_type else None, + ) + else: + raise_type_error( + tx, + f"{self.python_type_name()} indices must be integers or slices, " + f"not {arg.python_type_name()}", + ) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return list(self.items) + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Sequence length for lists, tuples, and range objects.""" + return VariableTracker.build(tx, len(self.items)) + + mp_length_impl = sq_length_impl + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L635-L652 + + # TODO(dynamo-team): Replace iter_contains by a proper impl. once we + # implement PyObject_RichCompare + return iter_contains(self.items, item, tx) + + def call_tree_map_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if not isinstance(self, (ListVariable, TupleVariable)): + return self._tree_map_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + + other_lists: list[BaseListVariable] = [] + for candidate in rest: + if ( + not isinstance(candidate, BaseListVariable) + or len(candidate.items) != len(self.items) + or self.python_type() != candidate.python_type() + ): + return self._tree_map_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + other_lists.append(candidate) + + new_items: list[VariableTracker] = [] + for idx, item in enumerate(self.items): + sibling_leaves = [candidate.items[idx] for candidate in other_lists] + new_items.append( + item.call_tree_map( + tx, + tree_map_fn, + map_fn, + sibling_leaves, + tree_map_kwargs, + ) + ) + + return self.clone( + items=new_items, + source=None, + mutation_type=ValueMutationNew(), + ) + + def call_tree_map_with_path_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + keypath: tuple[Any, ...], + ) -> VariableTracker: + if not isinstance(self, (ListVariable, TupleVariable)): + return self._tree_map_with_path_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + + other_lists: list[BaseListVariable] = [] + for candidate in rest: + if ( + not isinstance(candidate, BaseListVariable) + or len(candidate.items) != len(self.items) + or self.python_type() != candidate.python_type() + ): + return self._tree_map_with_path_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + other_lists.append(candidate) + + new_items: list[VariableTracker] = [] + for idx, item in enumerate(self.items): + sibling_leaves = [candidate.items[idx] for candidate in other_lists] + child_keypath = keypath + (SequenceKey(idx),) + new_items.append( + item.call_tree_map_with_path( + tx, + tree_map_fn, + map_fn, + sibling_leaves, + tree_map_kwargs, + child_keypath, + ) + ) + + return self.clone( + items=new_items, + source=None, + mutation_type=ValueMutationNew(), + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # list_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/listobject.c#L3689-L3710 + return self.getitem_const(tx, key) + + def sq_item_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # list_item: https://github.com/python/cpython/blob/62a6e898e01/Objects/listobject.c#L335-L351 + # tuple_item: https://github.com/python/cpython/blob/62a6e898e01/Objects/tupleobject.c#L421-L430 + # CPython's sq_item takes Py_ssize_t (already int from generic_getitem's + # nb_index_impl). Unlike mp_subscript, sq_item never handles slices. + index = key.as_python_constant() + try: + return self.items[index] + except IndexError: + raise_observed_exception( + IndexError, + tx, + args=[f"{self.python_type_name()} index out of range"], + ) + + def sq_repeat_impl( + self, + tx: "InstructionTranslatorBase", + count: VariableTracker, + ) -> VariableTracker: + n = count.as_python_constant() + if pytuple_checkexact(self) and (n == 1 or not self.items): + return self + try: + new_items = self.items * n + except (MemoryError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + # self.items is a list, so we can't go through VariableTracker.build (which would wrap in a list variable) + kwargs: dict[str, Any] = {} + if issubclass(self.python_type(), list): + kwargs["mutation_type"] = ValueMutationNew() + return type(self)(new_items, **kwargs) + + def _seq_richcompare( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + accepted_type: type, + ) -> VariableTracker: + """Shared list_richcompare / tuplerichcompare core. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/listobject.c#L3352 + https://github.com/python/cpython/blob/e76aa128fe/Objects/tupleobject.c#L821 + CPython operates on the internal C array directly, so we compare + VT items without going through a polyfill. + """ + from .object_protocol import generic_richcompare + from .tensor import SymNodeVariable + + try: + other_type = other.python_type() + except NotImplementedError: + return ConstantVariable.create(NotImplemented) + if not issubclass(other_type, accepted_type): + return ConstantVariable.create(NotImplemented) + + left = self.items + # CPython uses ob_item (the C array) directly, bypassing __iter__. + # For user-defined subclasses (UserDefinedListVariable etc.), + # the items live on the _base_vt. + other_vt = getattr(other, "_base_vt", None) or other + right = other_vt.items # pyrefly: ignore[missing-attribute] + + cmp_op = cmp_name_to_op_mapping[op] + + if cmp_op is operator.eq and len(left) != len(right): + return ConstantVariable.create(False) + if cmp_op is operator.ne and len(left) != len(right): + return ConstantVariable.create(True) + + sym_eq_acc = None + for a, b in zip(left, right): + # CPython uses PyObject_RichCompareBool per element, which has + # an identity shortcut before the full do_richcompare dispatch. + eq_result = generic_richcompare_bool(tx, a, b, "__eq__") + if eq_result.is_python_constant(): + if not eq_result.as_python_constant(): + if cmp_op in (operator.eq, operator.ne): + return ConstantVariable.create(cmp_op is operator.ne) + return generic_richcompare(tx, a, b, op) + elif eq_result.is_symnode_like(): + if cmp_op not in (operator.eq, operator.ne): + # Ordering requires branching on element equality, which + # can't be expressed as a single symbolic expression. + # Specialize: install a guard on the equality result and + # proceed with the concrete value. + eq_bool = guard_if_dyn(eq_result) + if not eq_bool: + return generic_richcompare(tx, a, b, op) + continue + if sym_eq_acc is None: + sym_eq_acc = eq_result + else: + proxy = tx.output.create_proxy( + "call_function", + operator.and_, + (sym_eq_acc.as_proxy(), eq_result.as_proxy()), + {}, + ) + sym_eq_acc = SymNodeVariable.create(tx, proxy, sym_num=None) + else: + unimplemented( + gb_type="list_richcompare_nonconst", + context=f"element comparison produced {type(eq_result).__name__}", + explanation="Cannot determine list/tuple comparison at compile time when element comparison produces a non-constant result.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if sym_eq_acc is not None: + if cmp_op is operator.ne: + proxy = tx.output.create_proxy( + "call_function", + operator.not_, + (sym_eq_acc.as_proxy(),), + {}, + ) + return SymNodeVariable.create(tx, proxy, sym_num=None) + return sym_eq_acc + + return ConstantVariable.create(cmp_op(len(left), len(right))) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "index": + if not len(args): + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + try: + # Speedup trace times for constant data structures + items = [item.as_python_constant() for item in self.items] + const_args = [arg.as_python_constant() for arg in args] + const_kwargs = {k: v.as_python_constant() for k, v in kwargs.items()} + try: + return VariableTracker.build( + tx, items.index(*const_args, **const_kwargs) + ) + except ValueError: + raise_observed_exception( + ValueError, + tx, + args=["tuple.index()"], + ) + except AsPythonConstantNotImplementedError: + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.index), + [self] + list(args), + kwargs, + ) + elif name == "count": + if len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return VariableTracker.build(tx, operator.countOf).call_function( + tx, + [self, args[0]], + kwargs, + ) + elif name == "__reversed__": + # list/tuple/namedtuple __reversed__: reverse iterator over items. + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return ListIteratorVariable( + list(reversed(self.items)), + mutation_type=ValueMutationNew(), + ) + return super().call_method(tx, name, args, kwargs) + + +class RangeVariable(BaseListVariable): + # PyRange_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/rangeobject.c#L767 + _cpython_type = range + + def __init__(self, items: list[VariableTracker], **kwargs: Any) -> None: + items_to_map = items + start = variables.ConstantVariable.create(0) + stop = None + step = variables.ConstantVariable.create(1) + + if len(items_to_map) == 1: + (stop,) = items_to_map + elif len(items_to_map) == 2: + start, stop = items_to_map + elif len(items_to_map) == 3: + start, stop, step = items_to_map + else: + raise AssertionError + + def maybe_as_int(x: VariableTracker) -> VariableTracker: + return ( + ConstantVariable.create(int(x.as_python_constant())) + if x.is_python_constant() + else x + ) + + # cast each argument to an integer + start = maybe_as_int(start) + step = maybe_as_int(step) + stop = maybe_as_int(stop) + + if stop is None: + raise AssertionError("stop must not be None after parsing range arguments") + super().__init__([start, stop, step], **kwargs) + + def debug_repr(self) -> str: + repr = f"range({self.start()}, {self.stop()}" + if self.step() != 1: + repr += f", {self.step()}" + repr += ")" + return repr + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: range_repr in https://github.com/python/cpython/blob/6280bb547840b609feedb78887c6491af75548e8/Objects/rangeobject.c#L673-L691 + return VariableTracker.build(tx, self.debug_repr()) + + def python_type(self) -> type: + return range + + # range math needs concrete bounds; with assume_static_by_default=False a + # range object's start/stop/step are wrapped as symbolic ints, so specialize + # them (installing a guard) rather than assuming a plain constant. + def start(self) -> int: + return guard_if_dyn(self.items[0]) + + def stop(self) -> int: + return guard_if_dyn(self.items[1]) + + def step(self) -> int: + return guard_if_dyn(self.items[2]) + + def range_length(self) -> int: + lo = self.start() + hi = self.stop() + step = self.step() + + if step == 0: + raise AssertionError("step must not be zero") + if step > 0 and lo < hi: + return 1 + (hi - 1 - lo) // step + elif step < 0 and lo > hi: + return 1 + (lo - 1 - hi) // (0 - step) + else: + return 0 + + def _get_slice_indices(self, length: int, slice: slice) -> list[int]: + step_is_negative = 0 + + if slice.step is None: + step = 1 + step_is_negative = False + else: + step = slice.step + step_is_negative = slice.step < 0 + + # Find lower and upper bounds for start and stop. + if step_is_negative: + lower = -1 + upper = length + lower + else: + lower = 0 + upper = length + + # Compute start + if slice.start is None: + start = upper if step_is_negative else lower + else: + start = slice.start + + if start < 0: + start += length + if start < lower: + start = lower + else: + if start > upper: + start = upper + + # Compute stop. + if slice.stop is None: + stop = lower if step_is_negative else upper + + else: + stop = slice.stop + + if stop < 0: + stop += length + if stop < lower: + stop = lower + else: + if stop > upper: + stop = upper + + return [start, stop, step] + + def apply_index( + self, tx: "InstructionTranslatorBase", index: int + ) -> VariableTracker: + length = self.range_length() + if index < 0: + index = length + index + + if index < 0 or index >= length: + raise_observed_exception( + IndexError, + tx, + args=["range object index out of range"], + ) + + return VariableTracker.build(tx, self.start() + (index * self.step())) + + def apply_slice(self, slice: slice) -> "RangeVariable": + (slice_start, slice_stop, slice_step) = self._get_slice_indices( + self.range_length(), slice + ) + + def compute_item(index: int) -> int: + return self.start() + (index * self.step()) + + sub_step = self.step() * slice_step + sub_start = compute_item(slice_start) + sub_stop = compute_item(slice_stop) + + result = RangeVariable( + [ + variables.ConstantVariable.create(x) + for x in [sub_start, sub_stop, sub_step] + ], + mutation_type=ValueMutationNew() if self.mutation_type else None, + ) + return result + + def as_python_constant(self) -> range: + return range(*[x.as_python_constant() for x in self.items]) + + def getitem_const( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + # range_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/rangeobject.c#L729-L748 + arg_type = maybe_get_python_type(arg) + if pyindex_check(arg_type): + i = pynumber_index(tx, arg) + return self.apply_index(tx, i.as_python_constant()) + elif pyslice_check(arg): + if not isinstance(arg, SliceVariable): + raise AssertionError("Expected arg to be a SliceVariable") + return self.apply_slice(arg.as_index_slice(tx)) + raise_type_error( + tx, + f"range indices must be integers or slices, not {arg.python_type_name()}", + ) + + def as_proxy(self) -> range: + return self.python_type()(*self._as_proxy()) + + def unpack_var_sequence( + self, tx: Optional["InstructionTranslatorBase"] = None + ) -> list[VariableTracker]: + rng = range(self.start(), self.stop(), self.step()) + return [variables.ConstantVariable.create(x) for x in rng] + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Sequence length for range objects.""" + length = self.range_length() + if length > sys.maxsize: + raise_observed_exception(OverflowError, tx) + return VariableTracker.build(tx, length) + + def mp_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.sq_length_impl(tx) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if "range" in codegen.tx.f_globals: + raise AssertionError("'range' must not be shadowed in f_globals") + codegen.add_push_null( + lambda: codegen.append_output(codegen.create_load_python_module(range)) # type: ignore[arg-type] + ) + codegen.foreach(self.items) + codegen.extend_output(create_call_function(3, False)) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is range: + return VariableTracker.build(tx, name in range.__dict__) + return super().call_obj_hasattr(tx, name) + + def range_equals(self, other: "RangeVariable") -> bool: + # ref: https://github.com/python/cpython/blob/62a6e898e017c9878490544f6a227b8a187a949c/Objects/rangeobject.c#L514-L553 (range_equals) + r0, r1 = self, other + if r0 is r1: + return True + if r0.range_length() != r1.range_length(): + return False + if r0.range_length() == 0: + return True + if r0.start() != r1.start(): + return False + if r0.range_length() == 1: + return True + return r0.step() == r1.step() + + def range_count(self, x: VariableTracker) -> int: + # Based on CPython + # https://github.com/guilhermeleobas/cpython/blob/baefaa6cba1d69efd2f930cdc56bca682c54b139/Objects/rangeobject.c#L442-L486 + x = x.as_python_constant() + if type(x) not in (bool, int, float): + return 0 + + start, stop, step = self.start(), self.stop(), self.step() + + if step == 0: + return 0 + + in_range = (start <= x < stop) if step > 0 else (stop < x <= start) + + if in_range: + re = ((x - start) % step) == 0 + return int(re) + return 0 + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # range_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/rangeobject.c#L729-L748 + return self.getitem_const(tx, key) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # range_contains: https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/rangeobject.c#L482-L490 + if maybe_get_python_type(item) in (int, bool): + return VariableTracker.build(tx, bool(self.range_count(item))) + return iter_contains(self.unpack_var_sequence(tx), item, tx) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/rangeobject.c#L896-L927 + if not all(var.is_python_constant() for var in self.items): + # Can't represent a `range_iterator` without well defined bounds + return variables.misc.DelayGraphBreakVariable( + msg="Cannot create range_iterator: bounds (start, stop, step) must be fully defined as concrete constants.", + ) + return RangeIteratorVariable( + self.start(), self.stop(), self.step(), self.range_length() + ) + + def sq_item_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # range_item: https://github.com/python/cpython/blob/62a6e898e01/Objects/rangeobject.c#L405-L416 + # CPython's sq_item takes Py_ssize_t (already int from generic_getitem's + # nb_index_impl). Unlike mp_subscript (range_subscript), no slices. + index = key.as_python_constant() + return self.apply_index(tx, index) + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """range_richcompare: eq/ne via range_equals, NotImplemented for ordering. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/rangeobject.c#L472 + """ + from .builder import SourcelessBuilder + + if op not in ("__eq__", "__ne__"): + return ConstantVariable.create(NotImplemented) + try: + if other.python_type() is not range: + return ConstantVariable.create(NotImplemented) + except NotImplementedError: + return ConstantVariable.create(NotImplemented) + + if isinstance(other, RangeVariable): + cmp = self.range_equals(other) + else: + cmp = False + + if op == "__eq__": + return SourcelessBuilder.create(tx, cmp) + else: + return SourcelessBuilder.create(tx, not cmp) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import SourcelessBuilder + + if name == "count": + return SourcelessBuilder.create(tx, self.range_count(*args)) + elif name == "__reversed__": + # range.__reversed__: range_iterator with reversed bounds. + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/rangeobject.c (range_reverse) + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + length = self.range_length() + start = self.start() + step = self.step() + new_start = start + (length - 1) * step + new_step = -step + return RangeIteratorVariable(new_start, 0, new_step, length) + elif name == "index": + x = args[0].as_python_constant() + start, stop, step = self.start(), self.stop(), self.step() + in_range = (start <= x < stop) if step > 0 else (stop < x <= start) + if in_range and ((x - start) % step) == 0: + return VariableTracker.build(tx, (x - start) // step) + raise_observed_exception( + ValueError, + tx, + args=[f"{x} is not in range"], + ) + return super().call_method(tx, name, args, kwargs) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + fields = ["start", "stop", "step"] + if name in fields: + return self.items[fields.index(name)] + + return super().tp_getattro_impl(tx, name) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CPython range_hash: https://github.com/python/cpython/blob/e76aa128fe/Objects/rangeobject.c#L572 + return hash(self.as_python_constant()), False + + +class CommonListMethodsVariable(BaseListVariable): + """ + Implement methods common to List and other List-like things + """ + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .tensor import SymNodeVariable + + if name == "append" and self.is_mutable(): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + (arg,) = args + tx.output.side_effects.mutation(self) + self.items.append(arg) + return ConstantVariable.create(None) + elif name == "extend" and self.is_mutable(): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + # CPython has a series of checks to optimize list.extend for different data types + # ref: https://github.com/python/cpython/blob/0fd4fd4496c557b68477a99c1c231a5870c91daf/Objects/listobject.c#L1389-L1444 + from .dicts import ConstDictVariable + from .sets import SetVariable + from .user_defined import UserDefinedObjectVariable + + sz = len(self.items) + if isinstance(args[0], (ListVariable, TupleVariable)): + self.items.extend(args[0].items) + elif isinstance(args[0], UserDefinedObjectVariable): + self.items.extend(unpack_iterable(tx, args[0])) + elif isinstance(args[0], (ConstDictVariable, SetVariable)): + items = [item.vt for item in args[0].items] + self.items.extend(items) + elif isinstance(args[0], ConstantVariable): + items = unpack_iterable(tx, args[0]) + self.items.extend(items) + else: + unpack_and_apply_fn( + tx, args[0], lambda item: self.call_method(tx, "append", [item], {}) + ) + + if len(self.items) > sz: + tx.output.side_effects.mutation(self) + return ConstantVariable.create(None) + elif name == "insert" and self.is_mutable(): + if kwargs or len(args) != 2: + raise_args_mismatch( + tx, + name, + "2 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + idx, value = args + if isinstance(idx, SymNodeVariable): + const_idx = idx.evaluate_expr() + else: + const_idx = idx.as_python_constant() + tx.output.side_effects.mutation(self) + # type: ignore[arg-type] + self.items.insert(const_idx, value) + return ConstantVariable.create(None) + elif name == "pop" and self.is_mutable(): + if kwargs or len(args) > 1: + raise_args_mismatch( + tx, + name, + "at most 1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + if len(self.items) == 0: + raise_observed_exception(IndexError, tx, args=["pop from empty list"]) + + if len(args): + idx = args[0].as_python_constant() + if idx >= len(self.items): + raise_observed_exception( + IndexError, tx, args=["pop index out of range"] + ) + tx.output.side_effects.mutation(self) + return self.items.pop(*[a.as_python_constant() for a in args]) + elif name == "clear" and self.is_mutable(): + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + tx.output.side_effects.mutation(self) + self.items.clear() + return ConstantVariable.create(None) + elif name == "copy": + # List copy() doesn't have args and kwargs + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + items_lst: list[VariableTracker] = list(self.items) + return self.modified(items_lst, mutation_type=ValueMutationNew()) + elif name == "reverse" and self.is_mutable(): + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + self.items.reverse() + tx.output.side_effects.mutation(self) + return ConstantVariable.create(None) + elif name == "remove" and self.is_mutable(): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + idx = self.call_method(tx, "index", args, kwargs) + self.call_method(tx, "pop", [idx], {}) + return ConstantVariable.create(None) + else: + return super().call_method(tx, name, args, kwargs) + + +class ListVariable(CommonListMethodsVariable): + # PyList_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L3776 + _cpython_type = list + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + return self._seq_richcompare(tx, other, op, list) + + def python_type(self) -> type: + return list + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(length={len(self.items)})" + + def debug_repr(self) -> str: + return self.debug_repr_helper("[", "]") + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + items = ", ".join(tracked_repr(tx, item) for item in self.items) + return VariableTracker.build(tx, f"[{items}]") + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self._contains_self_reference(): + # Self-referential list: create empty, cache, then extend + codegen.extend_output( + [ + create_instruction("BUILD_LIST", arg=0), + create_dup_top(), + ] + ) + codegen.add_cache(self) + + codegen.foreach(self.items) + codegen.extend_output( + [ + create_instruction("BUILD_LIST", arg=len(self.items)), + create_instruction("LIST_EXTEND", arg=1), + ] + ) + else: + # Non-self-referential: use simple codegen + codegen.foreach(self.items) + codegen.append_output(create_instruction("BUILD_LIST", arg=len(self.items))) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Include/internal/pycore_list.h#L55-L59 + return ListIteratorVariable(self.items, mutation_type=ValueMutationNew()) + + def sq_inplace_repeat_impl( + self, + tx: "InstructionTranslatorBase", + count: VariableTracker, + ) -> VariableTracker: + # list_inplace_repeat: https://github.com/python/cpython/blob/v3.13.13/Objects/listobject.c#L1071 + if not self.is_mutable(): + raise AssertionError( + f"sq_inplace_repeat_impl reached an immutable {type(self).__name__}; " + "every construction site should set mutation_type." + ) + n = count.as_python_constant() + try: + new_items = self.items * n + except (MemoryError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + tx.output.side_effects.mutation(self) + self.items[:] = new_items + return self + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "sort" and self.is_mutable(): + if len(args) != 0: + raise_args_mismatch(tx, name, "0 args", f"{len(args)} args") + key_fn_var = kwargs.pop("key", ConstantVariable.create(None)) + reverse = kwargs.pop( + "reverse", ConstantVariable.create(False) + ).as_python_constant() + if len(kwargs) != 0: + raise_args_mismatch(tx, name, "0 kwargs", f"{len(kwargs)} kwargs") + + tx.output.side_effects.mutation(self) + # CPython's list.sort detaches the list while sorting: reads + # during the sort observe an empty list, items added during the + # sort are discarded, and the mutation raises ValueError after + # the sorted result is installed. + saved = list(self.items) + self.items.clear() + + class _TracedKey: + # Compares through Dynamo so user-defined __lt__ (e.g. from + # functools.cmp_to_key) is traced like CPython's timsort, + # which only ever uses "<". + def __init__(self, key: VariableTracker) -> None: + self.key = key + + def __lt__(self, other: "_TracedKey") -> bool: + result = variables.BuiltinVariable(operator.lt).call_function( + tx, [self.key, other.key], {} + ) + if not result.is_python_constant(): + unimplemented( + gb_type="sort with non-constant keys", + context=str(self.key), + explanation=( + f"Cannot perform sort whose key comparison is not " + f"a compile-time constant. " + f"Key type: {self.key.python_type()}. " + f"Most notably, we cannot sort with Tensor or SymInt " + f"keys, but we can sort ints." + ), + hints=[ + "Use something else as the key.", + *graph_break_hints.SUPPORTABLE, + ], + ) + return bool(result.as_python_constant()) + + try: + if key_fn_var.is_constant_none(): + keys = saved + else: + keys = [key_fn_var.call_function(tx, [x], {}) for x in saved] + + if all(k.is_python_constant() for k in keys): + order = sorted( + range(len(saved)), + key=lambda i: keys[i].as_python_constant(), + reverse=reverse, + ) + else: + order = sorted( + range(len(saved)), + key=lambda i: _TracedKey(keys[i]), + reverse=reverse, + ) + new_items = [saved[i] for i in order] + except Exception as e: + self.items[:] = saved + if isinstance(e, (ObservedException, Unsupported)): + raise + raise_observed_exception(type(e), tx, args=list(e.args)) + modified_during_sort = bool(self.items) + self.items[:] = new_items + if modified_during_sort: + raise_observed_exception( + ValueError, tx, args=["list modified during sort"] + ) + return ConstantVariable.create(None) + return super().call_method(tx, name, args, kwargs) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # list___init___impl: clear the list, then extend with the optional + # iterable arg. + # https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L2966-L2986 + if kwargs or len(args) > 1: + raise_args_mismatch( + tx, + "__init__", + "at most 1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + tx.output.side_effects.mutation(self) + self.items.clear() + if len(args) == 1: + self.call_method(tx, "extend", args, {}) + return ConstantVariable.create(None) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == "__class__": + source = AttrSource(self.source, name) if self.source else None + class_type = self.python_type() + if class_type is list: + return VariableTracker.build(tx, class_type, source=source) + else: + return VariableTracker.build(tx, class_type, source) + return super().tp_getattro_impl(tx, name) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is not list: + return super().call_obj_hasattr(tx, name) + return VariableTracker.build(tx, hasattr([], name)) + + def sq_ass_item_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L865-L890 (list_ass_item) + if not self.is_mutable(): + return super().sq_ass_item_impl(tx, key, value) + # value=None signals delete (CPython NULL sentinel). + idx = key.nb_index_impl(tx).as_python_constant() + if not (0 <= idx < len(self.items)): + raise_observed_exception( + IndexError, tx, args=["list assignment index out of range"] + ) + try: + if value is None: + self.items.__delitem__(idx) + else: + self.items[idx] = value + except (IndexError, TypeError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + tx.output.side_effects.mutation(self) + return ConstantVariable.create(None) + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L3119-L3150 (list_ass_subscript) + if not self.is_mutable(): + return super().mp_ass_subscript_impl(tx, key, value) + # value=None signals delete (CPython NULL sentinel). + if pyindex_check(key.python_type()): + i = key.nb_index_impl(tx).as_python_constant() + if i < 0: + i += len(self.items) + return self.sq_ass_item_impl(tx, ConstantVariable(i), value) + elif pyslice_check(key): + # CPython runs PySlice_Unpack first, which raises ValueError on + # step==0 before the iterable check. + key_as_const = key.as_python_constant() + if key_as_const.step == 0: + raise_observed_exception( + ValueError, tx, args=["slice step cannot be zero"] + ) + if value is None: + # delete slice + try: + self.items.__delitem__(key_as_const) + except ValueError as exc: + raise_observed_exception( + ValueError, + tx, + args=list(exc.args), + ) + tx.output.side_effects.mutation(self) + else: + # assign slice + # CPython list_ass_subscript runs PySequence_Fast on value + # before the step==1 branch, so this message applies to all + # slice forms. + if not vt_is_iterable(value): + msg = "must assign iterable to extended slice" + step = key_as_const.step + if step in (None, 1) and _cpython_has_simple_slice_bug(): + msg = "can only assign an iterable" + raise_type_error(tx, msg) + + value_unpack = unpack_iterable(tx, value) + try: + self.items[key_as_const] = value_unpack + except ValueError as exc: + raise_observed_exception( + ValueError, + tx, + args=list(exc.args), + ) + tx.output.side_effects.mutation(self) + else: + raise_type_error( + tx, + f"list indices must be integers or slices, not {key.python_type_name()}", + ) + return ConstantVariable.create(None) + + def sq_concat_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # Implements PySequence_Concat for sequences + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L725-L773 (list_concat) + if not pylist_check(other): + raise_type_error( + tx, + f"can only concatenate list (not '{other.python_type_name()}') to list", + ) + + items = self.items + unpack_iterable(tx, other) + return ListVariable(items, mutation_type=ValueMutationNew()) + + def sq_inplace_concat_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # Implements PySequence_InPlaceConcat for sequences + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L1464-L1472 + self.call_method(tx, "extend", [other], {}) + return self + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, f"unhashable type: '{self.python_type_name()}'") + + +_deque_state_mutating_methods = frozenset( + { + "append", + "appendleft", + "extend", + "extendleft", + "pop", + "popleft", + "insert", + "remove", + "clear", + } +) + + +# TODO(dynamo-team): Split deque from CommonListMethodsVariable / ListVariable +class DequeVariable(CommonListMethodsVariable): + # deque_spec: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L1866 + # tp_hash = PyObject_HashNotImplemented (unhashable) + _cpython_type = collections.deque + + _nonvar_fields = { + "state", + *CommonListMethodsVariable._nonvar_fields, + } + + # deque exposes a single read-only getset descriptor, maxlen. + tp_getset = { + "maxlen": GetSet(lambda self, tx: self.maxlen, None), + } + + def _rotate( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + # deque_rotate: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L927 + # rotate(n=1, /) shifts n steps to the right (left if n < 0). n is + # resolved through nb_index. A deque of length <= 1 is a no-op. A + # non-mutable deque declines (returns None) so dispatch falls through + # to the object protocol, matching the old is_mutable() guard. + if not self.is_mutable(): + return None + # deque.rotate is METH_FASTCALL, so the flags derived from ml_flags + # reject kwargs but cannot bound the positional count; deque_rotate + # does that itself with _PyArg_CheckPositional. + check_positional(tx, "rotate", len(args), 0, 1) + n_vt = args[0] if args else ConstantVariable.create(1) + n = n_vt.nb_index_impl(tx).as_python_constant() + length = len(self.items) + if length > 1: + tx.output.side_effects.mutation(self) + k = n % length + if k != 0: + self.items[:] = self.items[-k:] + self.items[:-k] + self.state += 1 + return ConstantVariable.create(None) + + tp_methods = {"rotate": Method(_rotate)} + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + return self._seq_richcompare(tx, other, op, collections.deque) + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, f"unhashable type: '{self.python_type_name()}'") + + @staticmethod + def validate_maxlen( + tx: "InstructionTranslatorBase", maxlen: VariableTracker + ) -> None: + # deque_init: maxlenobj != Py_None is run through PyLong_AsSsize_t + # https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L1729-L1736 + if isinstance(maxlen, ConstantVariable) and maxlen.value is None: + return + if pylong_as_ssize_t(tx, maxlen) < 0: + raise_observed_exception( + ValueError, tx, args=["maxlen must be non-negative"] + ) + + def __init__( + self, + items: list[VariableTracker], + maxlen: VariableTracker | None = None, + **kwargs: Any, + ) -> None: + if maxlen is None: + maxlen = ConstantVariable.create(None) + if not maxlen.is_python_constant(): + raise AssertionError( + f"maxlen must be a constant, got: {maxlen.debug_repr()}" + ) + self.maxlen = maxlen + items = list(items) + if self.maxlen.as_python_constant() is not None: + items = items[-maxlen.as_python_constant() :] + super().__init__(items, **kwargs) + # Mirrors CPython deque->state: bumped on every structural mutation so + # deque iterators can detect mutation during iteration. + self.state = 0 + + def python_type(self) -> type: + return collections.deque + + def sq_item_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # deque_item: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L1888 + # CPython's sq_item takes Py_ssize_t (already int from generic_getitem's + # nb_index_impl). deque has no mp_subscript, so this is the real path. + index = key.as_python_constant() + try: + return self.items[index] + except IndexError: + raise_observed_exception(IndexError, tx, args=["deque index out of range"]) + + def sq_ass_item_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c (deque_ass_item) + if not self.is_mutable(): + return super().sq_ass_item_impl(tx, key, value) + # value=None signals delete (CPython NULL sentinel). + idx = key.nb_index_impl(tx).as_python_constant() + length = len(self.items) + if idx < 0: + idx += length + if not (0 <= idx < length): + raise_observed_exception(IndexError, tx, args=["deque index out of range"]) + tx.output.side_effects.mutation(self) + if value is None: + # deque_ass_item_lock_held bumps deque->state only on the delete + # path (deque_del_item); the set path (Py_SETREF) does not bump. + self.state += 1 + self.items.__delitem__(idx) + else: + self.items[idx] = value + return ConstantVariable.create(None) + + def sq_concat_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # Implements PySequence_Concat for deque + # ref: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L691-L699 + + if not issubclass(other.python_type(), collections.deque): + raise_type_error( + tx, + f"can only concatenate deque (not '{other.python_type_name()}') to deque", + ) + + return DequeVariable( + self.items + unpack_iterable(tx, other), + maxlen=self.maxlen, + mutation_type=ValueMutationNew(), + ) + + def sq_inplace_concat_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # Implements PySequence_InPlaceConcat for deque + # ref: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L572-L584 + self.call_method(tx, "extend", [other], {}) + return self + + def sq_inplace_repeat_impl( + self, + tx: "InstructionTranslatorBase", + count: VariableTracker, + ) -> VariableTracker: + # deque_inplace_repeat: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L811 + if not self.is_mutable(): + raise AssertionError( + f"sq_inplace_repeat_impl reached an immutable {type(self).__name__}; " + "every construction site should set mutation_type." + ) + n = count.as_python_constant() + try: + new_items = self.items * n + except (MemoryError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + # A bounded deque drops from the left, keeping the last maxlen items + # (maxlen == 0 yields an empty deque). + maxlen = self.maxlen.as_python_constant() + if maxlen is not None: + new_items = new_items[-maxlen:] if maxlen else new_items[:0] + tx.output.side_effects.mutation(self) + self.items[:] = new_items + return self + + def debug_repr(self) -> str: + if self.maxlen.as_python_constant() is None: + return self.debug_repr_helper("deque([", "])") + return self.debug_repr_helper( + "deque([", "], maxlen=" + self.maxlen.debug_repr() + ")" + ) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + items = ", ".join(tracked_repr(tx, item) for item in self.items) + if self.maxlen.as_python_constant() is None: + return VariableTracker.build(tx, f"{self.python_type_name()}([{items}])") + return VariableTracker.build( + tx, + f"{self.python_type_name()}([{items}], maxlen={tracked_repr(tx, self.maxlen)})", + ) + + def as_python_constant(self) -> collections.deque[Any]: + return self.python_type()( + [x.as_python_constant() for x in self.items], + maxlen=self.maxlen.as_python_constant(), + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # To deal with self-referential sets + codegen.add_push_null( + lambda: codegen.append_output( + codegen.create_load_python_module(collections.deque) # type: ignore[arg-type] + ) + ) + codegen.append_output(create_instruction("BUILD_LIST", arg=0)) + codegen(self.maxlen) + codegen.extend_output( + [ + *codegen.create_call_function_kw(2, ("maxlen",), False), + create_dup_top(), + ] + ) + codegen.add_cache(self) + + codegen.append_output(create_dup_top()) + codegen.load_method("extend") + + codegen.foreach(self.items) + codegen.extend_output( + [ + create_instruction("BUILD_LIST", arg=len(self.items)), + *create_call_method(1), + create_instruction("POP_TOP"), + ] + ) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # __init__ resets maxlen, so it must bypass the trailing maxlen clamp + # below (which uses the pre-call maxlen captured here). + if name == "__init__": + return self.tp_init_impl(tx, args, kwargs) + + if name == "__setattr__": + # deque has no __dict__, so every attribute write raises. A name + # backed by a getset descriptor (maxlen) is read-only; anything else + # is simply absent. + attr_name = args[0].as_python_constant() + if self.lookup_tp_getset_member(attr_name) is not None: + msg = ( + f"attribute '{attr_name}' of 'collections.deque' objects " + "is not writable" + ) + else: + msg = ( + f"'collections.deque' object has no attribute '{attr_name}' " + "and no __dict__ for setting new attributes" + ) + raise_observed_exception(AttributeError, tx, args=[msg]) + + if name == "__reversed__": + # deque.__reversed__ returns a _deque_reverse_iterator that snapshots + # the current state and detects mutation during iteration. + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return DequeReverseIteratorVariable( + list(reversed(self.items)), + self, + self.state, + mutation_type=ValueMutationNew(), + ) + + maxlen = self.maxlen.as_python_constant() + if maxlen is not None: + slice_within_maxlen = slice(-maxlen, None) + else: + slice_within_maxlen = None + + if name in ("copy", "__copy__"): + # deque_copy preserves maxlen: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L890 + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return DequeVariable( + list(self.items), + maxlen=self.maxlen, + mutation_type=ValueMutationNew(), + ) + + pre_len = len(self.items) + + if name == "extendleft" and self.is_mutable() and len(args) > 0: + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + # NOTE this is inefficient, but the alternative is to represent self.items + # as a deque, which is a more intrusive change. + unpack_and_apply_fn( + tx, args[0], lambda item: self.call_method(tx, "appendleft", [item], {}) + ) + slice_within_maxlen = slice(None, maxlen) + result = ConstantVariable.create(None) + elif name == "popleft" and self.is_mutable(): + if kwargs or len(args) > 0: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + tx.output.side_effects.mutation(self) + result, *self.items[:] = self.items + elif name == "appendleft" and len(args) > 0 and self.is_mutable(): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + tx.output.side_effects.mutation(self) + self.items[:] = [args[0], *self.items] + slice_within_maxlen = slice(None, maxlen) + result = ConstantVariable.create(None) + elif name == "insert" and len(args) > 0 and self.is_mutable(): + if kwargs or len(args) != 2: + raise_args_mismatch( + tx, + name, + "2 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + if maxlen is not None and len(self.items) == maxlen: + raise_observed_exception( + IndexError, tx, args=["deque already at its maximum size"] + ) + result = super().call_method(tx, name, args, kwargs) + else: + result = super().call_method(tx, name, args, kwargs) + + # Capture growth before the maxlen clamp: extend/extendleft appended an + # item iff the length grew here (the clamp may shrink it back). + extend_appended = len(self.items) > pre_len + if ( + slice_within_maxlen is not None + and maxlen is not None + and len(self.items) > maxlen + ): + self.items[:] = self.items[slice_within_maxlen] + if name in _deque_state_mutating_methods and self.is_mutable(): + # extend/extendleft with an empty iterable append nothing -> no bump. + if name not in ("extend", "extendleft") or extend_appended: + self.state += 1 + return result + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is collections.deque: + return VariableTracker.build(tx, name in collections.deque.__dict__) + return super().call_obj_hasattr(tx, name) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # deque_init: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L1810 + # Re-init resets maxlen (to None unless given), clears the deque, + # then extends with the iterable. + if not self.is_mutable(): + return super().tp_init_impl(tx, args, kwargs) + iterable = args[0] if len(args) >= 1 else kwargs.pop("iterable", None) + new_maxlen = ( + args[1] + if len(args) >= 2 + else kwargs.pop("maxlen", ConstantVariable.create(None)) + ) + if len(args) > 2 or kwargs: + raise_args_mismatch(tx, "__init__") + self.validate_maxlen(tx, new_maxlen) + tx.output.side_effects.mutation(self) + self.state += 1 + self.maxlen = new_maxlen + self.items.clear() + if iterable is not None: + self.call_method(tx, "extend", [iterable], {}) + return ConstantVariable.create(None) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Modules/_collectionsmodule.c#L1886-L1904 + return DequeIteratorVariable( + list(self.items), + self, + self.state, + mutation_type=ValueMutationNew(), + ) + + +class TupleVariable(BaseListVariable): + # PyTuple_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/tupleobject.c#L846 + _cpython_type = tuple + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + return self._seq_richcompare(tx, other, op, tuple) + + def python_type(self) -> type[tuple]: # type: ignore[type-arg] + return tuple + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(length={len(self.items)})" + + def debug_repr(self) -> str: + if len(self.items) == 1: + return self.debug_repr_helper("(", ",)") + return self.debug_repr_helper("(", ")") + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + items = ", ".join(tracked_repr(tx, item) for item in self.items) + if len(self.items) == 1: + items += "," + return VariableTracker.build(tx, f"({items})") + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/tupleobject.c#L1101-L1117 + return TupleIteratorVariable(self.items, mutation_type=ValueMutationNew()) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.foreach(self.items) + codegen.append_output(create_build_tuple(len(self.items))) + + def reconstruct_pycode(self, codegen): + if len(self.items) == 0: + return "()" + else: + return f"({', '.join([item.reconstruct_pycode(codegen) for item in self.items])},)" + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == "__class__": + source = AttrSource(self.source, name) if self.source else None + class_type = self.python_type() + return VariableTracker.build(tx, class_type, source=source) + return super().tp_getattro_impl(tx, name) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is not tuple: + return super().call_obj_hasattr(tx, name) + return VariableTracker.build(tx, hasattr((), name)) + + def sq_concat_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ): + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/tupleobject.c#L441-L486 (tuple_concat) + if len(self.items) == 0 and pytuple_checkexact(other): + return other + + if not pytuple_check(other): + raise_type_error( + tx, + f"can only concatenate tuple (not '{other.python_type_name()}') to tuple", + ) + + return TupleVariable( + self.items + unpack_iterable(tx, other), mutation_type=ValueMutationNew() + ) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CPython tuplehash: https://github.com/python/cpython/blob/e76aa128fe/Objects/tupleobject.c#L321 + # Collect per-item hashes and feed them through tuplehash. We wrap + # each hash in RawHash to bypass int.__hash__'s modular reduction, + # so tuplehash sees the original hash values — matching CPython exactly. + from .hashable import RawHash + from .object_protocol import generic_hash_impl + + is_fake = False + raw_hashes = [] + for item in self.items: + h, fake = generic_hash_impl(tx, item) + is_fake = is_fake or fake + raw_hashes.append(RawHash(h)) + return hash(tuple(raw_hashes)), is_fake + + +class SizeVariable(TupleVariable): + """torch.Size(...)""" + + _cpython_type = torch.Size + + _nonvar_fields = { + "proxy", + *TupleVariable._nonvar_fields, + } + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # torch.Size items may be TensorVariables wrapping scalar tensors with + # known constant values (node.meta["example_value"].constant). Extract + # the actual int values so the hash matches eager torch.Size hashing. + from .tensor import TensorVariable + + int_items: list[int] = [] + for item in self.items: + if item.is_python_constant(): + int_items.append(item.as_python_constant()) + continue + if isinstance(item, TensorVariable): + proxy = getattr(item, "proxy", None) + node = getattr(proxy, "node", None) + meta = getattr(node, "meta", None) if node is not None else None + example_value = ( + meta.get("example_value") if isinstance(meta, dict) else None + ) + constant = getattr(example_value, "constant", None) + if isinstance(constant, torch.Tensor) and constant.numel() == 1: + int_items.append(int(constant.item())) + continue + # Can't extract a concrete int — fall back to TupleVariable + return super().hash_impl(tx) + return hash(torch.Size(int_items)), False + + def __init__( + self, + items: list[VariableTracker], + proxy: torch.fx.Proxy | None = None, + **kwargs: Any, + ) -> None: + self.proxy = proxy + super().__init__(items, **kwargs) + + def debug_repr(self) -> str: + return self.debug_repr_helper("torch.Size([", "])") + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + items = ", ".join(tracked_repr(tx, item) for item in self.items) + return VariableTracker.build(tx, f"torch.Size([{items}])") + + def python_type(self) -> type: + return torch.Size + + def as_proxy(self) -> Any: + if self.proxy is not None: + return self.proxy + + # torch.Size needs special handling. Normally, we pun a list-like + # container to directly contain Proxy/Node objects from FX, and FX + # knows to look inside containers (via map_aggregate). But torch.Size + # is weird; although it subclasses from tuple, it doesn't allow + # members which aren't int-like (rejecting Proxy and Node). This + # means we can't use the normal representation trick + # torch.Size([proxy0, proxy1]). I looked into seeing if I could + # relax torch.Size in PyTorch proper, but if torch.Size constructor + # sees a type that it doesn't recognize, it will try to call + # __index__() on it, so there is no BC way to actually change this + # behavior (though it occurs to me that I could have just added a + # YOLO no checking alternate constructor.) + # + # To work around this problem, I represent a torch.Size proxy as + # a straight up proxy, that would have been constructed by taking + # the constituent proxies as arguments. This trick can be generally + # used for any construct that we need a proxy for but we can't + # directly represent as an aggregate; I don't see very many examples + # of this in torchdynamo though! + + # Look for a proxy. If there are none, do the legacy behavior + tracer = None + proxies = self._as_proxy() + for proxy in proxies: + if isinstance(proxy, torch.fx.Proxy): + tracer = proxy.tracer + break + + if tracer is None: + return torch.Size(proxies) + + proxy = tracer.create_proxy("call_function", torch.Size, (proxies,), {}) + set_example_value( + proxy.node, + torch.Size( + [ + p.node.meta["example_value"] if not isinstance(p, int) else p + for p in proxies + ] + ), + ) + return proxy + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("torch", "Size")) + codegen.foreach(self.items) + build_torch_size = [ + create_build_tuple(len(self.items)), + ] + create_call_function(1, False) + codegen.extend_output(build_torch_size) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return list(self.items) + + def numel(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .builder import SourcelessBuilder + from .tensor import SymNodeVariable + + const_result = 1 + # pyrefly: ignore [implicit-any] + sym_sizes = [] + + for v in self.items: + if v.is_python_constant(): + const_result *= v.as_python_constant() + else: + if not isinstance(v, SymNodeVariable): + raise AssertionError( + f"expected SymNodeVariable, got {type(v).__name__}" + ) + # Delay proxy calls until we know it will be necessary + sym_sizes.append(v) + + result = VariableTracker.build(tx, const_result) + if sym_sizes and const_result == 1: + # Skip multiplying by 1 + result, *sym_sizes = sym_sizes + + if not sym_sizes or const_result == 0: + return result + + mul = SourcelessBuilder.create(tx, operator.mul) + for v in sym_sizes: + result = mul.call_function(tx, [result, v], {}) + return result + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # tuple_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/tupleobject.c#L877-L930 + try: + key_type = key.python_type() + except NotImplementedError: + key_type = None + if key_type not in (int, bool, slice): + if key_type is not None and not type_implements_nb_index(key_type): + raise_observed_exception( + TypeError, + tx, + args=[ + f"tuple indices must be integers or slices, not {key.python_type_name()}" + ], + ) + key = key.nb_index_impl(tx) + return self.get_item_dyn(tx, key) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "numel": + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return self.numel(tx) + + return super().call_method(tx, name, args, kwargs) + + def get_item_dyn( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + from .tensor import SymNodeVariable, TensorVariable + + if isinstance(arg, SymNodeVariable): + index = arg.sym_num + elif isinstance(arg, TensorVariable): + value = get_fake_value(arg.as_proxy().node, tx) + if value.constant is None or value.constant.numel() != 1: + unimplemented( + gb_type="Indexing torch.Size with non-scalar tensor", + context=f"get_item_dyn {self} {arg}", + explanation=( + "Attempted to index torch.Size with a tensor that is not a scalar constant." + ), + hints=[*graph_break_hints.USER_ERROR], + ) + index = value.constant.item() + else: + index = arg.as_python_constant() + + if isinstance(index, slice): + return SizeVariable(self.items[index]) + else: + if not isinstance(index, (int, torch.SymInt)): + raise AssertionError( + f"index must be int or SymInt, got {type(index).__name__}" + ) + return self.items[index] + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + return VariableTracker.build(tx, hasattr(torch.Size, name)) + + def sq_concat_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + """ + Implements torch.Size concatenation via sq_concat protocol. + torch.Size accepts concatenation with any tuple-like object. + Ref: torch/csrc/Size.cpp::THPSize_concat + """ + if not pytuple_check(other): + raise_type_error( + tx, + f"can only concatenate tuple (not '{other.python_type_name()}') to torch.Size", + ) + # Size nb_add uses sq_concat. We do the opposite here because of the reverse keyword + return self.nb_add_impl(tx, other) + + def nb_add_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # NOTE: The python interpreter tries, in order: + # 1. right.nb_add(left, right) (only if right is a subclass of left) + # 2. left.nb_add(left, right) + # 3. right.nb_add(left, right) + # 4. left.sq_concat(right) + # Hence, to support tuple + size -> size, we need to implement nb_add + if not pytuple_check(other): + return ConstantVariable(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + a, b = unpack_iterable(tx, self_), unpack_iterable(tx, other_) + return SizeVariable(list(a) + list(b), mutation_type=ValueMutationNew()) + + +class SliceVariable(VariableTracker): + # PySlice_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/sliceobject.c#L689 + _cpython_type = slice + + def __init__( + self, + items: list[VariableTracker], + tx: Optional["InstructionTranslatorBase"] = None, + **kwargs: Any, + ) -> None: + items_to_map = items + start, stop, step = [variables.ConstantVariable.create(None)] * 3 + + if len(items_to_map) == 1: + (stop,) = items_to_map + elif len(items_to_map) == 2: + start, stop = items_to_map + elif len(items_to_map) == 3: + start, stop, step = items_to_map + else: + raise AssertionError + + # Convert TensorVariable to SymIntVariable by calling .item() + # This decomposes a[:t] to u=t.item(); a[:u] at the dynamo level + if start.is_tensor(): + if tx is None: + raise AssertionError( + "tx is required when slice indices are TensorVariables" + ) + start = start.call_method(tx, "item", [], {}) + if stop.is_tensor(): + if tx is None: + raise AssertionError( + "tx is required when slice indices are TensorVariables" + ) + stop = stop.call_method(tx, "item", [], {}) + if step.is_tensor(): + if tx is None: + raise AssertionError( + "tx is required when slice indices are TensorVariables" + ) + step = step.call_method(tx, "item", [], {}) + + self.items = (start, stop, step) + + super().__init__(**kwargs) + + def debug_repr(self) -> str: + return "slice(" + ", ".join(i.debug_repr() for i in self.items) + ")" + + def as_proxy(self) -> slice: + return slice(*[x.as_proxy() for x in self.items]) + + def python_type(self) -> type: + return slice + + def as_python_constant(self) -> slice: + return slice(*[guard_if_dyn(x) for x in self.items]) + + def as_index_slice(self, tx: "InstructionTranslatorBase") -> slice: + # PySlice_Unpack -> evaluate_slice_index: each non-None member is + # coerced through __index__ (nb_index), so user objects with an + # __index__ method are valid slice bounds. + # https://github.com/python/cpython/blob/62a6e898e01/Objects/sliceobject.c#L196-L242 + members = [] + for member in self.items: + if isinstance(member, ConstantVariable) and member.value is None: + members.append(None) + continue + if not pyindex_check(maybe_get_python_type(member)): + raise_type_error( + tx, + "slice indices must be integers or None or have an __index__ method", + ) + members.append(pynumber_index(tx, member).as_python_constant()) + return slice(*members) + + def is_hashable(self) -> bool: + # Slices became hashable in Python 3.12 (CPython slicehash). + return sys.version_info >= (3, 12) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + if sys.version_info < (3, 12): + raise_type_error(tx, "unhashable type: 'slice'") + # CPython slicehash: https://github.com/python/cpython/blob/e76aa128fe/Objects/sliceobject.c#L667 + s = self.as_python_constant() + try: + h = hash(s) + except TypeError as e: + raise_observed_exception(TypeError, tx, args=[str(e)]) + return h, False + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """slice_richcompare: delegates all 6 ops to (start, stop, step) tuple comparison. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/sliceobject.c#L667-L686 + """ + from .object_protocol import generic_richcompare + + if not isinstance(other, SliceVariable): + return ConstantVariable.create(NotImplemented) + self_tuple = TupleVariable(list(self.items)) + other_tuple = TupleVariable(list(other.items)) + return generic_richcompare(tx, self_tuple, other_tuple, op) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.foreach(self.items) + codegen.append_output(create_instruction("BUILD_SLICE", arg=len(self.items))) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name in cmp_name_to_op_mapping or name in ("__hash__", "indices"): + return variables.GetAttrVariable( + self, name, py_type=type(getattr(slice, name)) + ) + fields = ["start", "stop", "step"] + if name not in fields: + unimplemented( + gb_type="Unsupported attribute for slice() object", + context=f"tp_getattro_impl {self} {name}", + explanation=f"Expected attribute to be one of {','.join(fields)} " + f"but got {name}", + hints=[*graph_break_hints.USER_ERROR], + ) + return self.items[fields.index(name)] + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "indices": + if len(args) != 1 or kwargs: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + length_var = args[0].nb_index_impl(tx) + length = length_var.as_python_constant() + items: list[int | None] = [] + for item in self.items: + if item.is_constant_none(): + items.append(None) + else: + idx_var = item.nb_index_impl(tx) + items.append(idx_var.as_python_constant()) + + try: + result = slice(*items).indices(length) + except (ValueError, TypeError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + return VariableTracker.build(tx, result) + + return super().call_method(tx, name, args, kwargs) + + +class ListIteratorVariable(IteratorVariable): + # PyListIter_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L3842 + _cpython_type = type(iter([])) + + _nonvar_fields = { + "index", + *IteratorVariable._nonvar_fields, + } + + def __init__( + self, items: list[VariableTracker], index: int = 0, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + if not isinstance(items, list): + raise AssertionError(f"items must be a list, got {type(items).__name__}") + # Removing this check as it slows things down too much + # https://github.com/pytorch/pytorch/pull/87533#issuecomment-1287574492 + + # assert all(isinstance(x, VariableTracker) for x in items) + self.items = items + self.index = index + self.is_exhausted = False + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(length={len(self.items)}, index={repr(self.index)})" + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/6280bb547840b609feedb78887c6491af75548e8/Objects/listobject.c#L4110-L4133 + if not self.is_mutable(): + raise AssertionError("ListIteratorVariable must be mutable to iterate") + old_index = self.index + if old_index >= len(self.items) or self.is_exhausted: + self.is_exhausted = True + raise_observed_exception(StopIteration, tx) + + tx.output.side_effects.mutation(self) + self.index += 1 + return self.items[old_index] + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + return VariableTracker.build(tx, hasattr(iter([]), name)) + + def python_type(self) -> type: + return type(iter([])) + + def as_python_constant(self) -> Any: + if self.index > 0: + raise NotImplementedError + return iter([x.as_python_constant() for x in self.items]) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + if self.is_exhausted: + return [] + self.is_exhausted = True + return list(self.items[self.index :]) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # starting in 3.15 GET_ITER creates virtual iterators (see https://github.com/python/cpython/issues/145668), so use builtin iter instead + codegen.add_push_null( + lambda: codegen.append_output(codegen.create_load_python_module(iter)) # type: ignore[arg-type] + ) + if not self.is_exhausted: + remaining_items = self.items[self.index :] + else: + # pyrefly: ignore [implicit-any] + remaining_items = [] + codegen.foreach(remaining_items) + codegen.append_output(create_build_tuple(len(remaining_items))) + codegen.extend_output(create_call_function(1, False)) + + +class TupleIteratorVariable(ListIteratorVariable): + # PyTupleIter_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/tupleobject.c#L1067 + _cpython_type = type(iter(())) + + +class DequeIteratorVariable(ListIteratorVariable): + _cpython_type = type(iter(collections.deque())) + + _nonvar_fields = { + "saved_state", + *ListIteratorVariable._nonvar_fields, + } + + def __init__( + self, + items: list[VariableTracker], + source_deque: "DequeVariable", + saved_state: int, + index: int = 0, + **kwargs: Any, + ) -> None: + super().__init__(items, index=index, **kwargs) + self.source_deque = source_deque + self.saved_state = saved_state + + def _check_mutation(self, tx: "InstructionTranslatorBase") -> None: + if self.source_deque.state != self.saved_state: + raise_observed_exception( + RuntimeError, tx, args=["deque mutated during iteration"] + ) + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self._check_mutation(tx) + return super().tp_iternext_impl(tx) + + def python_type(self) -> type: + return type(iter(collections.deque())) + + +class DequeReverseIteratorVariable(DequeIteratorVariable): + _cpython_type = type(reversed(collections.deque())) + + def python_type(self) -> type: + return type(reversed(collections.deque())) + + +class RangeIteratorVariable(IteratorVariable): + # PyRangeIter_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/rangeobject.c#L896 + _cpython_type = type(iter(range(0))) + + def __init__( + self, start: int, stop: int, step: int, len_: int, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.start = start + self.stop = stop + self.step = step + self.len = len_ + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Range iterators are their own iterator.""" + return self + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is range_iterator: + ri = iter(range(0)) + return VariableTracker.build(tx, hasattr(ri, name)) + return super().call_obj_hasattr(tx, name) + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/rangeobject.c#L1072-L1091 + if self.len <= 0: + raise_observed_exception(StopIteration, tx) + + self.len -= 1 + current = self.start + self.start += self.step + return VariableTracker.build(tx, current) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__setstate__": + # rangeiter_setstate clamps the arg against the current remaining + # length, then advances: r->start += arg*step; r->len -= arg. + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/rangeobject.c#L1093-L1107 + if len(args) != 1 or kwargs: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + arg = args[0].as_python_constant() + index = min(max(arg, 0), self.len) + self.start += index * self.step + self.len -= index + return ConstantVariable.create(None) + elif name == "__length_hint__": + # rangeiter_len: remaining items. + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/rangeobject.c#L1109-L1115 + return ConstantVariable.create(self.len) + return super().call_method(tx, name, args, kwargs) + + def python_type(self) -> type: + return range_iterator + + def reconstruct(self, codegen: "PyCodegen") -> None: + # starting in 3.15 GET_ITER creates virtual iterators (see https://github.com/python/cpython/issues/145668), so use builtin iter instead + codegen.add_push_null( + lambda: codegen.append_output(codegen.create_load_python_module(iter)) # type: ignore[arg-type] + ) + codegen.add_push_null( + lambda: codegen.append_output(codegen.create_load_python_module(range)) # type: ignore[arg-type] + ) + codegen.append_output(codegen.create_load_const(self.start)) + codegen.append_output(codegen.create_load_const(self.stop)) + codegen.append_output(codegen.create_load_const(self.step)) + codegen.extend_output(create_call_function(3, False)) + codegen.extend_output(create_call_function(1, False)) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/memory.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..0edeaca58b6695951026f580215b991922cfd816 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/memory.py @@ -0,0 +1,214 @@ +from contextlib import ExitStack +from typing import Any, TYPE_CHECKING + +import torch +from torch.fx import has_side_effect, Proxy + +from ..bytecode_transformation import create_call_function +from ..exc import raise_type_error, unimplemented +from ..graph_bytecode_inputs import get_external_object_by_index +from ..guards import GuardBuilder, install_guard +from ..source import AttrSource, CallFunctionNoArgsSource, ImportSource +from .base import Member, VariableTracker +from .constant import ConstantVariable +from .ctx_manager import ContextWrappingVariable + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from ..codegen import PyCodegen + +from torch._library.custom_ops import custom_op + + +def _get_mempool_by_index(index: int) -> torch.cuda.MemPool: + mempool = get_external_object_by_index(index) + if not isinstance(mempool, torch.cuda.MemPool): + raise RuntimeError( + f"use_mem_pool expected a torch.cuda.MemPool object at index {index}" + ) + return mempool + + +def _current_cuda_device_source() -> CallFunctionNoArgsSource: + return CallFunctionNoArgsSource( + AttrSource(AttrSource(ImportSource("torch"), "cuda"), "current_device") + ) + + +# These marker ops are intentional even though Inductor also annotates enclosed +# FX nodes. The annotations tell Inductor which scheduler nodes allocate in a +# user pool, while begin/end keep the pool lifetime visible as ordered FX +# side-effects for non-Inductor backends. +@custom_op("mempool::begin", mutates_args=()) +def begin_mempool(device_index: int, mempool_index: int) -> None: + mempool = _get_mempool_by_index(mempool_index) + torch.cuda.memory._cuda_beginAllocateCurrentThreadToPool(device_index, mempool.id) + + +@begin_mempool.register_fake +def _(device_index: int, mempool_index: int) -> None: + pass + + +has_side_effect(torch.ops.mempool.begin.default) + + +@custom_op("mempool::end", mutates_args=()) +def end_mempool(device_index: int, mempool_index: int) -> None: + mempool = _get_mempool_by_index(mempool_index) + torch.cuda.memory._cuda_endAllocateToPool(device_index, mempool.id) + torch.cuda.memory._cuda_releasePool(device_index, mempool.id) + + +@end_mempool.register_fake +def _(device_index: int, mempool_index: int) -> None: + pass + + +has_side_effect(torch.ops.mempool.end.default) + + +class CUDAMemPoolVariable(VariableTracker): + """Represents a torch.cuda.MemPool object.""" + + def __init__( + self, + proxy: Proxy, + value: torch.cuda.MemPool, + user_object_index: int, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.proxy = proxy + self.value = value + self.user_object_index = user_object_index + + def python_type(self) -> type: + return torch.cuda.MemPool + + def get_real_python_backed_value(self) -> object: + return self.value + + def _id(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self.source: + install_guard(self.source.make_guard(GuardBuilder.ID_MATCH)) + return ConstantVariable.create(self.value.id) + + tp_members = { + "id": Member(_id), + } + + def as_proxy(self) -> Proxy: + return self.proxy + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.source: + return super().reconstruct(codegen) + + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, + "get_external_object_by_index", + ) + ) + codegen.append_output(codegen.create_load_const(self.user_object_index)) + codegen.extend_output(create_call_function(1, False)) + + +class CUDAMemPoolContextVariable(ContextWrappingVariable): + """Represents the torch.cuda.use_mem_pool context manager.""" + + def __init__( + self, + mempool: CUDAMemPoolVariable, + device_index: int, + **kwargs: Any, + ) -> None: + self.mempool = mempool + self.device_index = device_index + super().__init__(target_values=(), initial_values=None, **kwargs) + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + mempool: VariableTracker, + device: VariableTracker | None = None, + **kwargs: Any, + ) -> "CUDAMemPoolContextVariable": + if not isinstance(mempool, CUDAMemPoolVariable): + raise_type_error( + tx, + "torch.cuda.use_mem_pool() expected a torch.cuda.MemPool argument", + ) + + if device is None or ( + isinstance(device, ConstantVariable) and device.value is None + ): + install_guard( + _current_cuda_device_source().make_guard(GuardBuilder.EQUALS_MATCH) + ) + device_index = torch.cuda.current_device() + elif device.is_python_constant(): + device_index = torch.cuda._utils._get_device_index( + device.as_python_constant() + ) + else: + unimplemented( + gb_type="torch.cuda.use_mem_pool with non-constant device", + context=f"device={device}", + explanation="Dynamo requires the device argument to torch.cuda.use_mem_pool to be a Python constant.", + hints=[], + ) + + return CUDAMemPoolContextVariable(mempool, device_index, **kwargs) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + stack = ExitStack() + stack.enter_context( + torch.fx.traceback.annotate( + { + "mempool": self.mempool.user_object_index, + "mempool_device": self.device_index, + } + ) + ) + stack.enter_context(torch.fx.traceback.preserve_node_meta()) + self.set_cleanup_hook(tx, lambda: stack.close()) + tx.output.create_proxy( + "call_function", + torch.ops.mempool.begin, + (self.device_index, self.mempool.user_object_index), + {}, + ) + return ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + tx.output.create_proxy( + "call_function", + torch.ops.mempool.end, + (self.device_index, self.mempool.user_object_index), + {}, + ) + self.cleanup_assert() + return ConstantVariable.create(None) + + def module_name(self) -> str: + return "torch.cuda" + + def fn_name(self) -> str: + return "use_mem_pool" + + def reconstruct_type(self, codegen: "PyCodegen") -> None: + # Supporting graph breaks safely requires reconstructing the eager + # torch.cuda.use_mem_pool context on the resume path while keeping the + # compiled begin/end marker ops balanced around each compiled segment. + unimplemented( + gb_type="torch.cuda.use_mem_pool graph break", + context=str(self), + explanation="Dynamo doesn't support graph breaks inside torch.cuda.use_mem_pool.", + hints=[], + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/misc.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..59746cba4e47584d601f478939866987358fcfbe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/misc.py @@ -0,0 +1,3023 @@ +""" +This module contains miscellaneous variable tracker implementations for various Python types +and features used in Dynamo's symbolic execution. These classes help track and propagate +information about different kinds of variables during graph capture. + +Key classes include: +- SuperVariable: Handles super() calls and method resolution +- ExceptionVariable: Tracks exception objects +- RandomVariable: Manages random number generators +- GetAttrVariable: Tracks attribute access +- MethodWrapperVariable: Handles method wrappers +- PythonModuleVariable: Tracks Python modules +- NumpyVariable: Handles numpy functions and types +- StringFormatVariable: Manages string formatting +- DebuggingVariable: Handles print and logging +""" + +import builtins +import contextvars +import dataclasses +import enum +import functools +import inspect +import itertools +import logging +import random +import re +import sys +import traceback +import types +import weakref +from collections.abc import Callable, Sequence +from random import Random +from types import BuiltinFunctionType +from typing import Any, TYPE_CHECKING, TypeGuard, Union + +import torch._C +import torch._numpy as tnp +import torch.utils._pytree as pytree +from torch._dynamo.variables.base import MutationType +from torch._dynamo.variables.lists import TupleVariable +from torch._guards import Source + +from .. import config, graph_break_hints, trace_rules, variables +from ..bytecode_transformation import ( + create_call_function, + create_call_function_ex, + create_instruction, +) +from ..create_parameter_op import do_not_convert_to_tracable_parameter +from ..exc import ( + raise_observed_exception, + raise_type_error, + raise_value_error, + unimplemented, +) +from ..guards import GuardBuilder, install_guard +from ..mutation_guard import unpatched_nn_module_init +from ..source import ( + AttrSource, + GenericAttrSource, + GetItemSource, + TypeMROSource, + TypeSource, + WeakRefCallSource, +) +from ..utils import ( + check_positional, + check_unspec_or_constant_args, + identity, + istype, + no_keywords, + proxy_args_kwargs, + raise_args_mismatch, + unpack_iterable, +) +from .base import ( + AsPythonConstantNotImplementedError, + getset_build, + getset_read, + Member, + Method, + NO_SUCH_SUBOBJ, + VariableTracker, +) +from .constant import ConstantVariable +from .functions import NestedUserFunctionVariable, UserFunctionVariable +from .object_protocol import generic_str +from .user_defined import call_random_fn, is_standard_setattr, UserDefinedObjectVariable + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +class SuperVariable(VariableTracker): + # PySuper_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L11511 + _cpython_type = super + + _nonvar_fields = { + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + typevar: VariableTracker, + objvar: VariableTracker | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + # typevar is the first argument to super(). In the case where no argument + # is provided to super(), it is the __class__ object where + # the super() function is being called + self.typevar = typevar + # objvar here must be an instance or subtype of typevar. + # In the case where super() is called without arguments, it is the first argument + # to the current function where super() is called from (self for regular method, + # cls for a classmethod) + self.objvar = objvar + + def python_type(self) -> type: + return builtins.super + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(variables.BuiltinVariable(super))) + codegen(self.typevar) + if self.objvar is not None: + codegen(self.objvar) + codegen.extend_output(create_call_function(2, False)) + else: + codegen.extend_output(create_call_function(1, False)) + + def _resolved_getattr_and_source( + self, tx: "InstructionTranslatorBase", name: str + ) -> tuple[Any, AttrSource | None]: + if not self.objvar: + unimplemented( + gb_type="1-arg super not implemented", + context="", + explanation=f"Dynamo failed to trace attribute `{name}` accessed " + f"via `super()` (for type `{self.typevar}` and object `{self.objvar}`) " + "because one-argument of super() is not supported.", + hints=[ + "Use two-argument super(type, object_or_type).", + ], + ) + if self.objvar is None: + raise AssertionError("super() requires objvar to be set") + search_type = self.typevar.as_python_constant() + + # The rest of this function does two things: + # - Walk the mro to find where the attribute comes from to be + # able to provide accurate source + # - Call the getattr to get the object + + # Find the class object, where the function lives. + # When objvar is "self", use type(self), when objvar is "cls", use it as-is + type_to_use = self.objvar.python_type() + type_to_use_source: Source | None = ( + TypeSource(self.objvar.source) if self.objvar.source else None + ) + if issubclass(type_to_use, type): + type_to_use = self.objvar.value # type: ignore[attr-defined] + type_to_use_source = self.objvar.source + + source = None + search_mro = type_to_use.__mro__ + + try: + start_index = search_mro.index(search_type) + 1 + except ValueError: + # Corner case where the typevar is not in the mro of the objvar + # https://github.com/python/cpython/blob/3.11/Objects/typeobject.c#L8843-L8844 + return getattr(super(search_type, type_to_use), name), None + # Implemented based on https://github.com/python/cpython/blob/3.11/Objects/typeobject.c#L8812 + # super has its getattro implementation. The key point is that instead of calling getattr, it checks the + # attribute in the class __dict__ + for index in range(start_index, len(search_mro)): + # Don't call getattr, just check the __dict__ of the class + if resolved_getattr := search_mro[index].__dict__.get(name, NO_SUCH_SUBOBJ): + if resolved_getattr is not NO_SUCH_SUBOBJ: + # Equivalent of something like type(L['self']).__mro__[1].attr_name + if type_to_use_source: + source = AttrSource( + GetItemSource(TypeMROSource(type_to_use_source), index), + name, + ) + return resolved_getattr, source + + unimplemented( + gb_type="Unable to resolve super getattr", + context="", + explanation=f"Dynamo failed to trace attribute `{name}` accessed " + f"via `super()` (for type `{self.typevar}` and object `{self.objvar}`) " + "because the resolved attribute type is not supported.", + hints=[ + "Ensure the attribute exists in the parent class.", + "Check the arguments passed to `super()`.", + ], + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # Check if getattr is a constant. If not, delay the actual work by + # wrapping the result in GetAttrVariable. Mostly super is called with a + # method, so most of the work is delayed to call_function. + # + # We could have just implemented a const_getattr. However, super is + # special when it comes to finding sources. Compared to other VTs, super + # requires the attr name to walk the mro and find the actual source (and + # not just AttrSource). + value, source = self._resolved_getattr_and_source(tx, name) + if not variables.ConstantVariable.is_literal(value): + return GetAttrVariable(self, name, py_type=type(value)) + if source: + install_guard(source.make_guard(GuardBuilder.CONSTANT_MATCH)) + return variables.ConstantVariable.create(value, source=source) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + inner_fn, source = self._resolved_getattr_and_source(tx, name) + if self.objvar is None: + raise AssertionError("super() requires objvar to be set for method calls") + # This essentially simulates CPython's `super_getattro`: + # https://github.com/python/cpython/blob/a1c52d1265c65bcf0d9edf87e143843ad54f9b8f/Objects/typeobject.c#L11138-L11168 + # where `inner_fn` is the VT for `res = _super_lookup_descr(...)`. + # + # However, `res`'s type needs to be checked for `tp_descr_get`, and + # applied if it has one. We currently don't have polyfills for all the + # relevant `tp_descr_get`, so we explicitly handle the cases we care + # about here (e.g., note the staticmethod, classmethod cases). + if inner_fn is object.__init__: + return LambdaVariable(identity) + elif inner_fn is torch.nn.Module.__init__: + objvar = self.objvar + from ..side_effects import AttributeMutationNew + + if ( + isinstance(objvar, variables.UserDefinedObjectVariable) + and isinstance(objvar.mutation_type, AttributeMutationNew) + and not (args or kwargs) + ): + with do_not_convert_to_tracable_parameter(): + fn_vt = VariableTracker.build( + tx, unpatched_nn_module_init, source=source + ) + return fn_vt.call_function(tx, [self.objvar] + args, kwargs) + else: + unimplemented( + gb_type="Unsupported super().__init__() call", + context=f"call_method {self} {name} {args} {kwargs}", + explanation="Dynamo encountered a super().__init__() call " + f"on {objvar} that resolved to a `torch.nn.Module.__init__()` " + "call that we cannot trace.", + hints=[*graph_break_hints.DIFFICULT], + ) + elif ( + self.objvar.source + and hasattr(inner_fn, "__name__") + and inner_fn.__name__ == "__new__" + and variables.UserDefinedClassVariable.is_supported_new_method(inner_fn) + ): + user_cls = inner_fn.__self__ + if hasattr(user_cls, "__module__") and user_cls.__module__ == "builtins": + user_cls_vt: VariableTracker = VariableTracker.build(tx, user_cls) + else: + if source is None: + raise AssertionError( + "source must not be None for user-defined class" + ) + user_cls_source = source.member + user_cls_vt = variables.UserDefinedClassVariable( + user_cls, source=user_cls_source + ) + return user_cls_vt.call_method(tx, "__new__", args, kwargs) + elif isinstance(inner_fn, staticmethod) and isinstance( + inner_fn.__func__, types.FunctionType + ): + fn_vt = VariableTracker.build( + tx, inner_fn.__func__, source=source, realize=True + ) + return fn_vt.call_function(tx, args, kwargs) + elif isinstance(inner_fn, classmethod) and isinstance( + inner_fn.__func__, types.FunctionType + ): + if isinstance(self.objvar, variables.UserDefinedClassVariable): + # super().classmethod is called from a classmethod itself. So, + # super was converted to super(__class__, cls) in bytecode and + # therefore we have to propagate the cls. + cls_variable = self.objvar + else: + # current function is an instance method, therefore super was + # converted to super(__class__, self). We have to find + # type(self) to bind the cls to the parent classmethod. + # Note that it can't be the self.typevar because __class__ is + # the class where the method is defined, which could be + # different from type(self) with polymorphism. + cls_source = None + if self.objvar.source: + cls_source = TypeSource(self.objvar.source) + cls_variable = VariableTracker.build( + tx, + self.objvar.value_type, # type: ignore[attr-defined] + cls_source, + ) + if source is None: + raise AssertionError( + "source must not be None for classmethod resolution" + ) + fn_vt = VariableTracker.build( + tx, + inner_fn.__func__, + source=AttrSource(source, "__func__"), + realize=True, + ) + return fn_vt.call_function(tx, [cls_variable, *args], kwargs) + elif isinstance(inner_fn, types.FunctionType): + fn_vt = VariableTracker.build(tx, inner_fn, source=source, realize=True) + return fn_vt.call_function(tx, [self.objvar] + args, kwargs) + elif isinstance(inner_fn, types.MethodType): + return variables.UserMethodVariable( + inner_fn.__func__, self.objvar, source=source + ).call_function(tx, args, kwargs) + elif is_standard_setattr(inner_fn) and isinstance( + self.objvar, UserDefinedObjectVariable + ): + # type: ignore[arg-type] + return self.objvar.method_setattr_standard(tx, *args, **kwargs) + elif inner_fn is object.__delattr__: + attr = args[0] + try: + attr = attr.as_python_constant() + except NotImplementedError as exc: + unimplemented( + gb_type="Non-constant attribute given to `super().__delattr__()`", + context=f"call_method {self} {name}", + explanation="Dynamo requires the attribute name passed to " + "`super().__delattr__(...)` to be a constant (string).", + hints=[ + "Ensure the attribute name is a string literal or a constant variable." + ], + from_exc=exc, + ) + if not tx.output.side_effects.is_attribute_mutation(self.objvar): + unimplemented( + gb_type="Attempted super().__delattr__() on an object without mutation tracking", + context=f"call_method {self} {name}", + explanation="Dynamo needs to track mutations on an object " + "before `super().__delattr__` can be used on it. But the " + f"object ({self.objvar}) doesn't have attribute mutation " + "tracking enabled.", + hints=[ + "Ensure the object is tracked by Dynamo's side effect system.", + *graph_break_hints.DYNAMO_BUG, + ], + ) + if not isinstance(attr, str): + raise AssertionError(f"attr must be a str, got {type(attr)}") + tx.output.side_effects.store_attr( + self.objvar, attr, variables.DeletedVariable() + ) + return variables.ConstantVariable.create(None) + elif ( + isinstance(self.objvar, variables.UserDefinedObjectVariable) + and self.objvar._base_vt is not None + and self.objvar._base_methods is not None + and inner_fn in self.objvar._base_methods + ): + return self.objvar._base_vt.call_method(tx, name, args, kwargs) + elif inner_fn is object.__getattribute__: + attr_name = args[0].value # type: ignore[attr-defined] + # object.__getattribute__ IS PyObject_GenericGetAttr. Delegate + # to the shared implementation so that __dict__, __class__, + # polyfilled C descriptors, etc. are all handled consistently. + if isinstance(self.objvar, UserDefinedObjectVariable): + return self.objvar.generic_getattr(tx, attr_name) + + attr_value = None + try: + attr_value = object.__getattribute__( + self.objvar.value, # pyrefly: ignore[missing-attribute] + attr_name, + ) + except AttributeError: + raise_observed_exception(AttributeError, tx) + + attr_source = None + if self.objvar.source is not None: + attr_source = GenericAttrSource(self.objvar.source, attr_name) + return VariableTracker.build(tx, attr_value, attr_source) + elif inner_fn is torch._C._disabled_torch_function_impl: + # See `THPModule_disable_torch_function` for the C impl. + # The signature of _disabled_torch_function_impl is similar to + # `__torch_function__`, just without the first `cls` argument: + # * (func, types, args, kwargs) + func = args[0] + # pyrefly: ignore [implicit-any] + tf_kwargs = {} + tf_args = args[2].items # type: ignore[attr-defined] + # type: ignore[attr-defined] + for hash_key_vt, value_vt in args[3].items.items(): + key_str = hash_key_vt.vt.as_python_constant() + tf_kwargs[key_str] = value_vt + + tx_old = tx.symbolic_torch_function_state.torch_function_subclass_enabled + tx.symbolic_torch_function_state.torch_function_subclass_enabled = False + try: + return func.call_function(tx, tf_args, tf_kwargs) + finally: + tx.symbolic_torch_function_state.torch_function_subclass_enabled = ( + tx_old + ) + elif ( + isinstance(inner_fn, types.MethodDescriptorType) + and inner_fn in trace_rules.get_tensor_method() + ): + # FunctionType but implementation is in C, we support some of these, + # e.g., tensor ops like `torch.Tensor.to`. + fn_var = VariableTracker.build(tx, inner_fn, source, realize=True) + return fn_var.call_function(tx, [self.objvar] + args, kwargs) + elif isinstance(inner_fn, types.BuiltinFunctionType): + fn_vt = VariableTracker.build(tx, inner_fn, source=source, realize=True) + return fn_vt.call_function(tx, args, kwargs) + + unimplemented( + gb_type="Attempted to call a super() attribute that is " + "not a function or method", + context=f"call_method {self} {name}", + explanation="Dynamo does not know how to trace the call " + f"`super().{name}()` because `super().{name}` is not a " + "function or method attribute.", + hints=[ + "Ensure the attribute accessed via `super()` is a standard method or function.", + ], + ) + + +class FrameSummaryVariable(VariableTracker): + def __init__(self, frame_summary: traceback.FrameSummary, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.frame_summary = frame_summary + + def python_type(self) -> type: + return traceback.FrameSummary + + # traceback.FrameSummary is pure-Python with __slots__ (Lib/traceback.py); + # each slot is exposed as a read-only member_descriptor. + tp_members = { + "lineno": Member(getset_build(lambda s: s.frame_summary.lineno)), + "filename": Member(getset_build(lambda s: s.frame_summary.filename)), + "name": Member(getset_build(lambda s: s.frame_summary.name)), + "line": Member(getset_build(lambda s: s.frame_summary.line)), + } + + +class TracebackVariable(VariableTracker): + def __init__( + self, + frame_summary: FrameSummaryVariable, + tb_next: Union["TracebackVariable", ConstantVariable], + **kwargs: Any, + ) -> None: + # The traceback holds four attributes: + # - tb_frame + # - tb_lineno + # - tb_lasti + # - tb_next + + super().__init__(**kwargs) + self.frame_summary = frame_summary + # the next traceback in the chain + if tb_next is None: + raise AssertionError("tb_next must not be None") + self.tb_next = tb_next + + @classmethod + def from_frame_summary( + cls, + frame_summary: traceback.FrameSummary, + tb_next: Union["TracebackVariable", ConstantVariable], + ) -> "TracebackVariable": + return cls(FrameSummaryVariable(frame_summary), tb_next=tb_next) + + @staticmethod + def is_valid_traceback(obj: VariableTracker) -> bool: + return istype(obj, TracebackVariable) or obj.is_constant_none() + + def extract_tb(self) -> list[traceback.FrameSummary | FrameSummaryVariable]: + if istype(self.tb_next, ConstantVariable): + return [self.frame_summary] + return [self.frame_summary] + self.tb_next.extract_tb() + + def has_reference_cycle(self, tb: VariableTracker) -> bool: + # checks if `tb` is in the chain of tb_next starting from `self` + curr_tb: TracebackVariable | ConstantVariable = self + while istype(curr_tb, TracebackVariable): + if curr_tb is tb: + return True + curr_tb = curr_tb.tb_next + return False + + def python_type(self) -> type[types.TracebackType]: + return types.TracebackType + + def call_setattr( + self, + tx: "InstructionTranslatorBase", + name_var: VariableTracker, + val: VariableTracker, + ) -> VariableTracker: + name = name_var.as_python_constant() + if name == "tb_next": + if not self.is_valid_traceback(val): + raise_observed_exception(TypeError, tx) + if not isinstance(val, (TracebackVariable, ConstantVariable)): + raise AssertionError( + f"tb_next val must be TracebackVariable or ConstantVariable, got {type(val)}" + ) + if self.has_reference_cycle(val) or ( + istype(val, TracebackVariable) and val.has_reference_cycle(self) + ): + raise_observed_exception(ValueError, tx) + self.tb_next = val + return variables.ConstantVariable.create(None) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == "tb_next": + return self.tb_next + elif name == "tb_lineno": + return self.frame_summary.tp_getattro_impl(tx, "lineno") + elif name == "frame_summary": + return self.frame_summary + elif name == "tb_lasti": + unimplemented( + gb_type="traceback.tb_lasti not supported", + context=f"{self} accessing 'tb_lasti'", + explanation="Dynamo does not support accessing the tb_lasti attribute of traceback objects.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + return super().tp_getattro_impl(tx, name) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__setattr__": + return self.call_setattr(tx, *args) + return super().call_method(tx, name, args, kwargs) + + +class ExceptionVariable(VariableTracker): + # _PyExc_BaseException: https://github.com/python/cpython/blob/v3.13.0/Objects/exceptions.c + _cpython_type = BaseException + + # The ExceptionVariable corresponds to the BaseException class in Python + def __init__( + self, + exc_type: Any, + args: list[VariableTracker], + init_kwargs: dict[str, VariableTracker] | None = None, + source: Source | None = None, + mutation_type: MutationType | None = None, + ) -> None: + super().__init__(source=source, mutation_type=mutation_type) + self.exc_type = exc_type + self.args = args + if init_kwargs: + unimplemented( + gb_type="Keyword args passed to exception constructor", + context=f"{self} with kwargs {init_kwargs}", + explanation="Dynamo does not know how to handle keyword args passed to an exception constructor", + hints=[*graph_break_hints.SUPPORTABLE], + ) + # When raising a new exception while another exception is already being + # handled, the new exception's __context__ attribute is automatically + # set to the handled exception. + self.__context__: VariableTracker = ConstantVariable.create(None) + # Set when user raised an exception from another: + # raise ... from ... + self.__cause__: VariableTracker = ConstantVariable.create(None) + # Boolean flag that controls whether the __context__ attribute is set + self.__suppress_context__: VariableTracker = ConstantVariable.create(False) + # Contains the call stack where the exception was raised. + self.__traceback__: VariableTracker = ConstantVariable.create(None) + # The user stack at the time this exception was first raised. + # Used to preserve the original exception location when re-raising. + self.python_stack: traceback.StackSummary | None = None + + def set_context(self, context: VariableTracker) -> None: + self.__context__ = context + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from("builtins", self.exc_type.__name__) + ) + codegen.foreach(self.args) + codegen.call_function(len(self.args), False) + + def codegen_attr(name: str) -> None: + attr = getattr(self, name) + if istype(attr, ConstantVariable): + if attr.value not in (True, False, None): + raise AssertionError( + f"attr.value must be True, False, or None, got {attr}" + ) + else: + codegen.dup_top() + codegen(attr) + codegen.extend_output(codegen.rot_n(2)) + codegen.store_attr(name) + + codegen_attr("__context__") + codegen_attr("__cause__") + codegen_attr("__suppress_context__") + + def python_type(self) -> type: + return self.exc_type + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__setattr__": + name = args[0].as_python_constant() + val = args[1] + if name == "__context__": + # Constant can be either an Exceptior or None + if not ( + val.is_constant_none() + or isinstance( + val, + ( + variables.ExceptionVariable, + variables.UserDefinedExceptionClassVariable, + variables.UserDefinedExceptionObjectVariable, + ), + ) + ): + raise_type_error( + tx, + "exception context must be None or derive from BaseException", + ) + self.set_context(val) + elif name == "__cause__": + if val.is_constant_none() or isinstance( + val, + ( + variables.BuiltinVariable, + variables.ExceptionVariable, + variables.UserDefinedExceptionClassVariable, + variables.UserDefinedExceptionObjectVariable, + ), + ): + self.__cause__ = val + self.__suppress_context__ = variables.ConstantVariable.create(True) + else: + raise_type_error( + tx, "exception cause must be None or derive from BaseException" + ) + elif name == "__suppress_context__": + if val.is_constant_match(True, False): + self.__suppress_context__ = val + else: + raise_type_error( + tx, "exception cause must be None or derive from BaseException" + ) + elif name == "__traceback__": + if not TracebackVariable.is_valid_traceback(val): + raise_type_error(tx, "__traceback__ must be a traceback or None") + self.__traceback__ = val + elif name == "args": + # CPython coerces any iterable to a tuple (PySequence_Tuple). + self.args = unpack_iterable(tx, val) + else: + # Arbitrary user attribute -> store in the instance __dict__ + # via the side effects table. + se = tx.output.side_effects + if not se.is_attribute_mutation(self): + se.track_attribute_mutation_new(self) + se.store_instance_dict_attr(self, name, val) + return variables.ConstantVariable.create(None) + elif name == "__setstate__": + if len(args) != 1: + raise_type_error( + tx, f"__setstate__() takes exactly one argument ({len(args)} given)" + ) + [state] = args + # BaseException.__setstate__(None) is a documented no-op. + if state.is_constant_none(): + return variables.ConstantVariable.create(None) + if not isinstance(state, variables.ConstDictVariable): + raise_type_error(tx, "state is not a dictionary") + for key, value in state.keys_as_python_constant().items(): + self.call_method( + tx, "__setattr__", [ConstantVariable.create(key), value], {} + ) + return variables.ConstantVariable.create(None) + elif name == "with_traceback": + if len(args) != 1: + raise_type_error( + tx, + f"with_traceback() takes exactly one argument ({len(args)} given)", + ) + [tb] = args + if not TracebackVariable.is_valid_traceback(tb): + raise_type_error(tx, "__traceback__ must be a traceback or None") + self.__traceback__ = tb + return self + else: + return super().call_method(tx, name, args, kwargs) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == "__class__": + return VariableTracker.build(tx, self.exc_type) + elif name == "__context__": + return self.__context__ + elif name == "__cause__": + return self.__cause__ + elif name == "__suppress_context__": + return self.__suppress_context__ + elif name == "__traceback__": + return self.__traceback__ + elif name == "args": + return VariableTracker.build( + tx, + tuple(self.args), + source=self.source and AttrSource(self.source, "args"), + ) + try: + # Custom attributes are stored in the side effects instance dict and + # resolved by generic_getattr before reaching here, so a fall-through + # to the generic lookup that finds nothing means the attribute is + # genuinely absent -- match CPython's BaseException tp_getattro + # (PyObject_GenericGetAttr) and raise AttributeError. + return super().tp_getattro_impl(tx, name) + except NotImplementedError: + raise_observed_exception( + AttributeError, + tx, + args=[f"'{self.exc_type.__name__}' object has no attribute '{name}'"], + ) + + def tp_str_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/exceptions.c#L118-L129 + if len(self.args) == 0: + return VariableTracker.build(tx, "") + elif len(self.args) == 1: + return generic_str(tx, self.args[0]) + else: + from . import TupleVariable + + tuple_var = TupleVariable(list(self.args)) + return generic_str(tx, tuple_var) + + def __str__(self) -> str: + return f"{self.__class__.__name__}({self.exc_type})" + + __repr__ = __str__ + + @staticmethod + def _debug_format_arg(arg: VariableTracker) -> str: + try: + return repr(arg.as_python_constant()) + except Exception: + return arg.debug_repr() + + def debug_repr(self) -> str: + args = ", ".join(self._debug_format_arg(arg) for arg in self.args) + return f"{self.python_type_name()}({args})" + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: BaseException_repr in https://github.com/python/cpython/blob/3.13/Objects/exceptions.c#L135-L142 + return VariableTracker.build(tx, self.debug_repr()) + + +class StopIterationVariable(ExceptionVariable): + def __init__( + self, + exc_type: Any, + args: list[VariableTracker], + init_kwargs: dict[str, VariableTracker] | None = None, + source: Source | None = None, + mutation_type: MutationType | None = None, + ) -> None: + self.value = args[0] if args else variables.ConstantVariable.create(None) + super().__init__(exc_type, args, init_kwargs, source, mutation_type) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == "value": + return self.value + return super().tp_getattro_impl(tx, name) + + +class _KwargAttrExceptionVariable(ExceptionVariable): + # Base for exceptions whose constructor accepts keyword-only attributes that + # default to None (e.g. NameError's `name`, AttributeError's `name`/`obj`). + # Subclasses list the attribute names in `_kwarg_attrs`; they are popped from + # init_kwargs, exposed via getattr, and restored on reconstruct. + _kwarg_attrs: tuple[str, ...] = () + + def __init__( + self, + exc_type: Any, + args: list[VariableTracker], + init_kwargs: dict[str, VariableTracker] | None = None, + source: Source | None = None, + mutation_type: MutationType | None = None, + ) -> None: + init_kwargs = dict(init_kwargs) if init_kwargs else {} + none = variables.ConstantVariable.create(None) + self._attrs = {name: init_kwargs.pop(name, none) for name in self._kwarg_attrs} + super().__init__(exc_type, args, init_kwargs, source, mutation_type) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name in self._attrs: + return self._attrs[name] + return super().tp_getattro_impl(tx, name) + + def reconstruct(self, codegen: "PyCodegen") -> None: + super().reconstruct(codegen) + for name, val in self._attrs.items(): + if not (istype(val, ConstantVariable) and val.value is None): + codegen.dup_top() + codegen(val) + codegen.extend_output(codegen.rot_n(2)) + codegen.store_attr(name) + + +class AttributeErrorVariable(_KwargAttrExceptionVariable): + # https://docs.python.org/3/library/exceptions.html#AttributeError + _kwarg_attrs = ("name", "obj") + tp_members = { + "name": Member(getset_read(lambda s: s._attrs["name"])), + "obj": Member(getset_read(lambda s: s._attrs["obj"])), + } + + +class NameErrorVariable(_KwargAttrExceptionVariable): + # https://docs.python.org/3/library/exceptions.html#NameError + _kwarg_attrs = ("name",) + tp_members = {"name": Member(getset_read(lambda s: s._attrs["name"]))} + + +class UnknownVariable(VariableTracker): + """ + It could be anything! + """ + + +class DelayGraphBreakVariable(UnknownVariable): + """ + Used to insert a dummy variable in the stack to do the graph break at CALL_FUNCTION. + """ + + def __init__( + self, + msg: str | None = None, + hints: list[str] | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.msg = msg + self.hints = hints or [] + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + name = "" if self.source is None else self.source.name + unimplemented( + gb_type="Unsupported function call (delayed)", + context=f"source: {self.source}", + explanation="Dynamo determined that a graph break should occur " + f"when calling `{name}`. Reason: {self.msg}", + hints=self.hints, + ) + + +class ComptimeVariable(VariableTracker): + """ + This variable is special, it lets you execute arbitrary code at + Dynamo compile time + """ + + def reconstruct(self, codegen: "PyCodegen") -> None: + raise NotImplementedError("comptime is special form") + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + from ..comptime import comptime + + if self.source is None: + raise AssertionError("ComptimeVariable requires a source") + # To support the comptime.print_graph convenience accessors + return VariableTracker.build( + tx, getattr(comptime, name), source=AttrSource(self.source, name) + ) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from ..comptime import ComptimeContext + + # TODO: support an expression form as well + # Second argument is runtime lambda, ignored + if kwargs or len(args) > 2: + raise_args_mismatch( + tx, + "comptime()", + "at most 2 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + fn = args[0] + if isinstance(fn, UserFunctionVariable): + fn.get_function()(ComptimeContext(tx)) + elif isinstance(fn, NestedUserFunctionVariable): + # We have to manually bind the freevars ourselves + code = fn.get_code() + if fn.closure: + raise_type_error( + tx, + f"comptime function must not have free variables, but these variables were free: {code.co_freevars}", + ) + func = types.FunctionType( + code, + fn.f_globals, + fn.fn_name.as_python_constant(), + # type: ignore[attr-defined] + tuple(fn.defaults.items) if fn.defaults else None, + # We could automatically promote free variables into + # ComptimeVar but this is confusing if you access + # a free variable that we actually DO have the runtime + # value for + # tuple(make_cell(ComptimeVar(i)) for i in fn.closure.items) + (), + ) + func(ComptimeContext(tx)) + else: + raise RuntimeError(f"unsupported argument to comptime: {type(fn)}") + + return variables.ConstantVariable.create(None) + + +class CellVariable(VariableTracker): + # PyCell_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/cellobject.c#L151 + _cpython_type = types.CellType + + # If the cell existed before Dynamo tracing started, this will be the + # VariableTracker that represents the cell content. + # + # Note that all mutation to the cell (i.e., its content) will be buffered in + # SideEffects, rather than being reflected here. One can think of + # `CellVariable` as a special case for `UserDefinedObjectVariable`. + pre_existing_contents: VariableTracker | None + + # This is set when this cell can be referenced via `LOAD/STORE_DEREF` in the + # root frame via this name (e.g., the name is in `co_cellvars/co_freevars`). + local_name: str | None = None + + def __init__( + self, pre_existing_contents: VariableTracker | None = None, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.pre_existing_contents = pre_existing_contents + + def python_type(self) -> type: + return types.CellType + + +class NewGlobalVariable(VariableTracker): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + +def produce_trampoline_autograd_apply(fn_cls: Any) -> Callable[..., Any]: + def trampoline_autograd_apply(*args: Any, **kwargs: Any) -> Any: + return fn_cls.apply(*args, **kwargs) + + # type: ignore[attr-defined] + trampoline_autograd_apply._origin = produce_trampoline_autograd_apply + return trampoline_autograd_apply + + +class AutogradFunctionVariable(VariableTracker): + """represents a torch.autograd.Function subclass""" + + _nonvar_fields = { + "fn_cls", + *VariableTracker._nonvar_fields, + } + + def __init__(self, fn_cls: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.fn_cls = fn_cls + + def python_type(self) -> type: + return type + + def _resolve_kwargs( + self, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> list[VariableTracker] | None: + """Resolve kwargs to positional args using forward().__code__. + + Uses co_varnames/co_argcount directly to match the C++ + resolve_kwargs_to_positional in python_function.cpp. + Keyword-only args are not resolved; callers should graph break. + """ + from torch.autograd.function import _is_setup_context_defined + + fn = self.fn_cls.forward + code = fn.__code__ + has_ctx = not _is_setup_context_defined(self.fn_cls.setup_context) + param_offset = 1 if has_ctx else 0 + param_names = list(code.co_varnames[param_offset : code.co_argcount]) + + for name in kwargs: + if name not in param_names: + return None + if param_names.index(name) < len(args): + raise TypeError(f"forward() got multiple values for argument '{name}'") + + max_idx = max( + (param_names.index(name) for name in kwargs), + default=len(args) - 1, + ) + + result: list[VariableTracker] = list(args) + for i in range(len(args), max_idx + 1): + name = param_names[i] + if name in kwargs: + result.append(kwargs[name]) + else: + raise TypeError( + f"forward() missing required argument: '{name}' (position {i})" + ) + return result + + def call_apply( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if kwargs: + resolved = self._resolve_kwargs(args, kwargs) + if resolved is None: + unimplemented( + gb_type="autograd_function_kwonly_args", + context=f"forward() has keyword-only args: {set(kwargs) - set(self.fn_cls.forward.__code__.co_varnames)}", + explanation="autograd.Function.apply does not support keyword-only arguments in forward().", + hints=[*graph_break_hints.SUPPORTABLE], + ) + args = resolved + kwargs = {} + + requires_grad = False + + def visit(vt: VariableTracker) -> None: + nonlocal requires_grad + if vt.is_tensor(): + # type: ignore[attr-defined] + if vt.requires_grad is not False: + requires_grad = True + if isinstance(vt, variables.NNModuleVariable): + if vt.is_training(tx): + requires_grad = True + + VariableTracker.visit(visit, (args, kwargs)) + + if requires_grad and torch.is_grad_enabled(): + source = self.source + + from torch._functorch.autograd_function import ( + autograd_function_forward_rewritten, + ) + from torch.autograd.function import _is_setup_context_defined + + forward_fn = self.fn_cls.forward + + is_setup_ctx_defined = _is_setup_context_defined(self.fn_cls.setup_context) + if is_setup_ctx_defined: + # If setup_context is defined, we generate a new forward function which includes + # the original forward and setup_context function, and trace the new forward function. + forward_fn = autograd_function_forward_rewritten( + self.fn_cls.forward, self.fn_cls.setup_context + ) + # The forward points to a new function now, so we can't use the + # old source. Later on, we guard specifically on + # is_setup_ctx_defined + source = None + + vjp_fn = self.fn_cls.vjp # type: ignore[attr-defined] + if vjp_fn is not torch.autograd.Function.vjp: + unimplemented( + gb_type="Unsupported custom vjp", + context=f"call_apply {self} {args} {kwargs}", + explanation="Dynamo does not support tracing " + "`torch.autograd.Function` subclasses that define " + "a custom `vjp` method.", + hints=[ + "Remove the custom `vjp` method if possible.", + "Use standard `backward` instead if applicable.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + jvp_fn = self.fn_cls.jvp # type: ignore[attr-defined] + if jvp_fn is not torch.autograd.Function.jvp: + unimplemented( + gb_type="Unsupported custom jvp", + context=f"call_apply {self} {args} {kwargs}", + explanation="Dynamo does not support tracing " + "`torch.autograd.Function` subclasses that define " + "a custom `jvp` method.", + hints=[ + "Remove the custom `jvp` method if possible.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + from .higher_order_ops import AutogradFunctionApplyVariable + + if source is None and not is_setup_ctx_defined: + source = AttrSource( + tx.import_source(self.fn_cls.__module__), self.fn_cls.__name__ + ) + apply_source = source and AttrSource(source, member="apply") + val = AutogradFunctionApplyVariable( + forward_fn, + self.fn_cls.backward, + source, + source=apply_source, + ).call_function(tx, args, kwargs) + if self.source and is_setup_ctx_defined: + fwd_src = AttrSource(self.source, "forward") + install_guard(fwd_src.make_guard(GuardBuilder.CLOSURE_MATCH)) + setup_ctx_src = AttrSource(self.source, "setup_context") + install_guard(setup_ctx_src.make_guard(GuardBuilder.CLOSURE_MATCH)) + + return val + + if self.source: + source = AttrSource(self.source, "forward") + else: + source = None + + fn = self.fn_cls.forward + ctx = AutogradFunctionContextVariable.create(tx, args, kwargs) + args = [ctx, *args] + if isinstance(fn, types.FunctionType): + sig = inspect.signature(fn) + if len(args) - 1 == len(sig.parameters): + args = args[1:] # Don't use context + fn_vt = VariableTracker.build(tx, fn, source=source, realize=True) + return fn_vt.call_function(tx, args, kwargs) + elif isinstance(fn, types.MethodType): + return variables.UserMethodVariable( + fn.__func__, + variables.UserDefinedClassVariable(self.fn_cls), + source=source, + ).call_function(tx, args, kwargs) + else: + unimplemented( + gb_type="Non-function or method in subclass of torch.autograd.Function", + context=f"call_apply {self} {args} {kwargs}", + explanation="Dynamo requires the `forward` attribute of a " + "`torch.autograd.Function` subclass to be a standard Python " + f"function or method. Found type `{type(fn).__name__}` instead.", + hints=[ + "Ensure the `forward` method is defined as a regular " + "function or instance method." + ], + ) + + def call_backward( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fn = self.fn_cls.backward + if ( + type(args[0].value) # type: ignore[attr-defined] + is not torch._dynamo.external_utils.FakeBackwardCFunction + ): + raise AssertionError( + f"Expected FakeBackwardCFunction, got {type(args[0].value)}" + ) + if not isinstance(fn, types.FunctionType): + raise AssertionError(f"Expected FunctionType, got {type(fn)}") + if self.source is None: + raise AssertionError("AutogradFunctionVariable requires a source") + fn_source = AttrSource(self.source, "backward") + fn_vt = VariableTracker.build(tx, fn, source=fn_source, realize=True) + return fn_vt.call_function(tx, args, kwargs) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "AutogradFunctionVariable": + return AutogradFunctionVariable(self.fn_cls) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if name == "apply": + if trace_rules.is_callable_allowed(self.fn_cls): + trampoline_autograd_apply = produce_trampoline_autograd_apply( + self.fn_cls + ) + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + trampoline_autograd_apply, + *proxy_args_kwargs(args, kwargs), + ), + ) + else: + return self.call_apply(tx, args, kwargs) + + elif name == "backward": + return self.call_backward(tx, args, kwargs) + else: + source = AttrSource(self.source, name) if self.source is not None else None + try: + obj = inspect.getattr_static(self.fn_cls, name) + except AttributeError: + obj = None + + if isinstance(obj, staticmethod): + func = obj.__get__(self.fn_cls) + traced = trace_rules.lookup(func) + if traced is None: + raise AssertionError(f"trace_rules.lookup returned None for {func}") + if source is not None: + return ( + # type: ignore[attr-defined] + traced.create_with_source(func, source=source).call_function( + tx, args, kwargs + ) + ) + else: + # type: ignore[misc] + return traced(func).call_function(tx, args, kwargs) + elif isinstance(obj, classmethod): + return variables.UserMethodVariable( + obj.__func__, self, source=source + ).call_function(tx, args, kwargs) + else: + unimplemented( + gb_type="Unsupported autograd.Function method", + context=f"call_method {self} {name}", + explanation="Dynamo does not support calling the method " + f"`{name}` directly on the `torch.autograd.Function` " + "instance. Supported methods include `apply`, `backward`, " + "static methods, and class methods.", + hints=[ + "Ensure the method is decorated with `@staticmethod` " + "or `@classmethod` if it's meant to be called on the class.", + ], + ) + + +@dataclasses.dataclass +class SavedTensorBox: + tensors: list[VariableTracker] = dataclasses.field(default_factory=list) + + +class AutogradFunctionContextVariable(UserDefinedObjectVariable): + """ + Tracks an autograd.Function() context using mutation tracking in side_effects.py + """ + + _nonvar_fields = { + "proxy", + "inference", + "saved_tensors", + *UserDefinedObjectVariable._nonvar_fields, + } + + def __init__( + self, + value: Any, + value_type: type | None = None, + inference: bool = False, + saved_tensors: Any | None = None, + non_differentiable: Any | None = None, + dirty_tensors: list[VariableTracker] | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value=value, value_type=value_type, **kwargs) + self.inference = inference + self.saved_tensors = saved_tensors + self.non_differentiable = non_differentiable + self.dirty_tensors = dirty_tensors + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + args: list[VariableTracker] | None = None, + kwargs: dict[str, VariableTracker] | None = None, + ) -> VariableTracker: + out = tx.output.side_effects.track_object_new( + None, + torch.autograd.function.FunctionCtx, + functools.partial( + AutogradFunctionContextVariable, + inference=True, + saved_tensors=SavedTensorBox(), + ), + {}, + ) + if args and not kwargs: + # The real apply() populates ctx.needs_input_grad; mirror it as a + # regular attribute store so reads and user writes both flow + # through the generic side_effects machinery. + # pyrefly: ignore [missing-attribute] + needs_input_grad = tuple(x.is_tensor() and x.requires_grad for x in args) + tx.output.side_effects.store_instance_dict_attr( + out, "needs_input_grad", ConstantVariable.create(needs_input_grad) + ) + return out + + def as_proxy(self) -> Any: + # type: ignore[attr-defined] + if self.proxy is None: + unimplemented( + gb_type="proxy not set", + context=f"as_proxy {self}", + explanation="Dynamo requires the autograd.Function context " + "to be initialized with a proxy.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + # type: ignore[attr-defined] + return self.proxy + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__setattr__": + return super().call_method(tx, name, args, kwargs) + elif name == "mark_non_differentiable": + if kwargs: + raise_args_mismatch(tx, name, "0 kwargs", f"{len(kwargs)} kwargs") + self.non_differentiable = proxy_args_kwargs(args, {})[0] + return variables.ConstantVariable.create(None) + elif name == "mark_dirty": + if kwargs: + raise_args_mismatch(tx, name, "0 kwargs", f"{len(kwargs)} kwargs") + if getattr(self, "proxy", None) is None: + unimplemented( + gb_type="Unsupported autograd.Function context `mark_dirty`", + context=f"call_method {self} {name}", + explanation="Dynamo only supports tracing ctx.mark_dirty " + "inside autograd.Function.apply.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + self.dirty_tensors = args + return variables.ConstantVariable.create(None) + + if name != "save_for_backward": + unimplemented( + gb_type="Unsupported autograd.Function context method", + context=f"call_method {self} {name}", + explanation="Dynamo does not support calling the method " + f"`{name}` on `autograd.Function` context objects. Supported " + "methods are `__setattr__`, `save_for_backward`, " + "`mark_dirty` and `mark_non_differentiable`.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + if self.saved_tensors is None: + unimplemented( + gb_type="Unsupported autograd.Function context `save_for_backward`", + context=f"call_method {self} {name}", + explanation="Dynamo requires the `saved_tensors` attribute " + "to be initialized on the `autograd.Function` context object.", + hints=[ + "Ensure that the `saved_tensors` attribute is properly " + "initialized before calling `save_for_backward`. " + "`save_for_backward` only supported on a newly constructed `torch.autograd.function.FunctionCtx`.", + ], + ) + if self.saved_tensors is None: + raise AssertionError( + "saved_tensors must be initialized before save_for_backward" + ) + if not self.inference: + if kwargs or not self.source: + raise_type_error( + tx, "save_for_backward() requires a source and no keyword arguments" + ) + tx.output.side_effects.track_save_for_backward(self, args) + + # In eager mode, multiple calls to .save_for_backward() will overwrite previous calls. + if len(self.saved_tensors.tensors) > 0: + # pyrefly: ignore [implicit-any] + self.saved_tensors.tensors = [] + for arg in args: + self.saved_tensors.tensors.append(arg) + return variables.ConstantVariable.create(None) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name in ["save_for_backward", "mark_dirty", "mark_non_differentiable"]: + return LambdaVariable( + lambda *args, **kwargs: self.call_method(tx, name, list(args), kwargs) + ) + if name == "dirty_tensors": + if self.dirty_tensors is None: + return variables.ConstantVariable.create(None) + return variables.TupleVariable(list(self.dirty_tensors)) + if name == "saved_tensors" and self.saved_tensors is not None: + return variables.TupleVariable(list(self.saved_tensors.tensors)) + + return super().tp_getattro_impl(tx, name) + + +class AutogradEngineVariable(UserDefinedObjectVariable): + """ + Represents a torch._C._ImperativeEngine instance. + """ + + def __init__( + self, + value: torch._C._ImperativeEngine, + value_type: type[torch._C._ImperativeEngine] | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value=value, value_type=value_type, **kwargs) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "queue_callback": + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + if not (tx.one_graph or tx.error_on_graph_break): + raise AssertionError( + "queue_callback() is only supported when Compiled Autograd is enabled with fullgraph=True" + ) + # queue_callback is a method-wrapper, no need to insert a guard. + fn_vt = VariableTracker.build( + tx, + torch._dynamo.external_utils.FakeCompiledAutogradEngine.queue_callback, + ) + return fn_vt.call_function( + tx, + (tx.output.side_effects.get_ca_final_callbacks_var(), *args), + kwargs, + ) + else: + unimplemented( + gb_type="Unsupported torch._C._ImperativeEngine.queue_callback()", + context=f"call_method {self} {name}", + explanation="queue_callback() is only supported when " + "Compiled Autograd is enabled with fullgraph=True.", + hints=[], + ) + else: + unimplemented( + gb_type="Unsupported torch._C._ImperativeEngine method", + context=f"call_method {self} {name}", + explanation="Dynamo only supports the `queue_callback` method " + f"on a torch._C._ImperativeEngine instance, but found: `{name}`.", + hints=[], + ) + + +class LambdaVariable(VariableTracker): + # TODO: change to Ts = TypeVarTuple("Ts") for py 3.11+ + def __init__(self, fn: Callable[..., VariableTracker], **kwargs: Any) -> None: + super().__init__(**kwargs) + self.fn = fn + + def python_type(self) -> type: + return types.FunctionType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.fn(*args, **kwargs) + + +class GetAttrVariable(VariableTracker): + _nonvar_fields = { + "name", + "py_type", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + obj: VariableTracker, + name: str, + py_type: type | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(obj, VariableTracker): + raise AssertionError(f"obj must be a VariableTracker, got {type(obj)}") + if not isinstance(name, str): + raise AssertionError(f"name must be a str, got {type(name)}") + self.obj = obj + self.name = name + self.py_type = py_type # In some cases we know the type (ex. tensor methods) + + def python_type(self) -> type: + if self.py_type is not None: + return self.py_type + else: + return super().python_type() + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.obj}, {self.name})" + + @staticmethod + def create_getattr_proxy(base_proxy: torch.fx.Proxy, attr: str) -> Any: + return getattr(base_proxy, attr) + + def as_proxy(self) -> Any: + return GetAttrVariable.create_getattr_proxy(self.obj.as_proxy(), self.name) + + def as_python_constant(self) -> Any: + constant = self.obj.as_python_constant() + try: + return getattr(constant, self.name) + except AttributeError: + raise NotImplementedError(f"{self} is not a constant") from None + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # GetAttrVariable can wrap various types (bound methods, descriptors, + # etc.) with different C tp_hash. Resolve to the actual value and hash. + try: + val = self.as_python_constant() + except (AsPythonConstantNotImplementedError, NotImplementedError): + from ..exc import unimplemented + + unimplemented( + gb_type="Non-constant GetAttrVariable hash", + context=f"hash_impl {self}", + explanation=f"Cannot hash {self} because Dynamo doesn't know how to represent " + "the type of the getattr() result, which is not a constant.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + return hash(val), False + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> "ConstantVariable": + if ( + isinstance(self.obj, AutogradFunctionVariable) + and self.name == "apply" + and getattr(self.obj.fn_cls, "generate_vmap_rule", False) + ): + return variables.ConstantVariable.create( + hasattr(self.obj.fn_cls.apply, name) + ) + return super().call_obj_hasattr(tx, name) + + def const_getattr(self, tx: "InstructionTranslatorBase", name: str) -> Any: + if not isinstance(self.obj, variables.NNModuleVariable): + raise NotImplementedError + step1 = tx.output.get_submodule(self.obj.module_key) + if self.name not in step1.__dict__: + raise NotImplementedError + step2 = inspect.getattr_static(step1, self.name) + if name not in step2.__dict__: + raise NotImplementedError + return inspect.getattr_static(step2, name) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.obj) + codegen.extend_output(codegen.create_load_attrs(self.name)) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import generic_richcompare + + try: + resolved = self.obj.tp_getattro_impl(tx, self.name) + except NotImplementedError: + resolved = None + if resolved is None or isinstance(resolved, GetAttrVariable): + if self.obj.is_python_constant(): + val = getattr(self.obj.as_python_constant(), self.name) + resolved = VariableTracker.build(tx, val) + else: + unimplemented( + gb_type="Unresolved GetAttrVariable comparison", + context=f"tp_richcompare_impl {self} {op}", + explanation=f"Cannot compare {self} because the attribute " + f"could not be resolved to a concrete value.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + return generic_richcompare(tx, resolved, other, op) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.obj.call_method(tx, self.name, args, kwargs) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + if self.name == "__dict__" and hasattr(self.obj, "get_dict_vt"): + return self.obj.get_dict_vt(tx).mp_subscript_impl(tx, key) + return super().mp_subscript_impl(tx, key) + + +class CallMethodVariable(VariableTracker): + """A method bound to a VT instance. + + Returned by object_generic_getattr when the MRO walk finds a method + on a VT that has custom call_method logic. + """ + + _nonvar_fields = { + "method_name", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + obj: VariableTracker, + method_name: str, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.obj = obj + self.method_name = method_name + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.obj}, {self.method_name})" + + def python_type(self) -> type: + try: + return type(self.as_python_constant()) + except (AsPythonConstantNotImplementedError, AttributeError): + return types.MethodType + + def as_python_constant(self) -> Any: + return getattr(self.obj.as_python_constant(), self.method_name) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + try: + return hash(self.as_python_constant()), False + except AsPythonConstantNotImplementedError: + return id(self), True + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.obj.call_method(tx, self.method_name, args, kwargs) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.obj) + codegen.extend_output(codegen.create_load_attrs(self.method_name)) + + +class PythonModuleVariable(VariableTracker): + # PyModule_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/moduleobject.c#L1203 + _cpython_type = types.ModuleType + + _nonvar_fields = { + "value", + "is_torch", + *VariableTracker._nonvar_fields, + } + + def __init__(self, value: types.ModuleType, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + self.is_torch = self.value is torch or self.value.__name__.startswith("torch.") + + def python_type(self) -> type[types.ModuleType]: + return types.ModuleType + + def as_python_constant(self) -> types.ModuleType: + return self.value + + def get_real_python_backed_value(self) -> types.ModuleType: + return self.value + + def __repr__(self) -> str: + return f"PythonModuleVariable({self.value})" + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if tx.output.side_effects.has_pending_mutation_of_attr(self, name): + return tx.output.side_effects.load_attr(self, name) + + attr_value = None + if self.is_torch or name not in self.value.__dict__: + try: + attr_value = getattr(self.value, name) + except AttributeError: + raise_observed_exception(AttributeError, tx) + else: + attr_value = self.value.__dict__[name] + + source = self.source and AttrSource(self.source, name) + return VariableTracker.build(tx, attr_value, source) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + +class TypingVariable(VariableTracker): + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # e.g., List[int] → typing.List[int] + if not key.is_python_constant(): + unimplemented( + gb_type="non-constant typing subscript", + context=f"TypingVariable[{key}]", + explanation=f"Cannot subscript typing construct {self.value} with a non-constant key.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + new_typing = self.value[key.as_python_constant()] + return TypingVariable(new_typing) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + if op in ("__eq__", "__ne__"): + if istype(other, TypingVariable): + result = self.value == other.value + if op == "__ne__": + result = not result + return ConstantVariable.create(result) + return ConstantVariable.create(NotImplemented) + return ConstantVariable.create(NotImplemented) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + unimplemented( + gb_type="unsupported method call on `typing` variable", + context=f"typing variable: {self.value}, method name: {name}, args: {args}, kwargs: {kwargs}", + explanation=f"`torch.compile` does not support method call `{name}` on `typing` variable f{self.value}.", + hints=[ + f"Avoid calling the {name} method on {self.value}.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # GenericAlias types (e.g. Callable[[int], bool]) support __or__ for + # type unions (e.g. Callable[[int], bool] | None). + if not other.is_python_constant(): + return VariableTracker.build(tx, NotImplemented) + other_val = other.as_python_constant() + # pyrefly: ignore[bad-argument-count] + result = type(self.value).__or__(self.value, other_val) + if result is NotImplemented: + return VariableTracker.build(tx, NotImplemented) + return VariableTracker.build(tx, result) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + from .builder import SourcelessBuilder, VariableBuilder + + if tx.output.side_effects.has_pending_mutation_of_attr(self, name): + return tx.output.side_effects.load_attr(self, name) + + value = getattr(self.value, name) + if self.source: + attr_source = AttrSource(self.source, name) + return VariableBuilder(tx, attr_source)(value) + else: + return SourcelessBuilder.create(tx, value) + + def as_python_constant(self) -> Any: + return self.value + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return hash(self.value), False + + def get_real_python_backed_value(self) -> Any: + return self.value + + def reconstruct(self, codegen: "PyCodegen") -> None: + if not isinstance(self.value, types.GenericAlias): + return super().reconstruct(codegen) + # We're just trying to load the type here. Reconstructing the type from + # scratch is tricky - for a type like `typing.List[int]` we'd need to + # deconstruct the origin and args. The origin for `List[int]` is `list` + # and the args is `(int,)`. When we recombine those we get the parts + # back and need to emit code for: + # + # `typing.List[int]` + # + # But it's # worse than that - what if `typing` isn't in the globals (or + # was loaded like `import typing as _typing ; _typing.List[int]`?) so we + # really need to do something like: + # + # `sys.modules["typing"].List[int]` + # + # Argh - but what if they rewrote the global `int`? So we have to do: + # + # `sys.modules["typing"].List[sys.modules["builtins"].int]` + # + # But where do we get `sys`? What if they never imported it or have + # something ELSE called `sys`? + # + # Let's skip all that noise and just emit it as a simple const. + # + codegen.append_output(codegen.create_load_const(self.value)) + + +@functools.lru_cache(maxsize=1) +def get_np_to_tnp_map() -> dict[types.BuiltinFunctionType, types.FunctionType]: + """ + This generates a mapping from numpy modules to their torch._numpy + modules equivalents. + """ + from ..utils import NP_TO_TNP_MODULE + + np_fn_to_tnp_fn = {} + + for np_mod, tnp_mod in NP_TO_TNP_MODULE.items(): + for fn_name, tnp_fn in tnp_mod.__dict__.items(): + if callable(tnp_fn): + # some internal details do leak from tnp + # which are not part of numpy API. + if np_fn := getattr(np_mod, fn_name, None): + np_fn_to_tnp_fn[np_fn] = tnp_fn + + return np_fn_to_tnp_fn + + +@functools.lru_cache(maxsize=1) +def get_tnp_to_np_map() -> dict[types.FunctionType, types.BuiltinFunctionType]: + """ + This is just the reverse mapping of get_np_to_tnp_map() - mapping from + torch._numpy modules to numpy equivalents. + """ + m = get_np_to_tnp_map() + return {v: k for k, v in m.items()} + + +class NumpyVariable(VariableTracker): + """ + Wrapper around `numpy.*`. Currently, is able to trace a small subset of numpy functions as well as numpy dtypes. + """ + + constant_fold_functions = (tnp.issubdtype,) + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def get_real_python_backed_value(self) -> Any: + return self.value + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + # NumpyVariable wraps singleton numpy module attrs (dtypes, ufuncs, + # constants); compare by the backed value for eq/ne, else NotImplemented. + if op not in ("__eq__", "__ne__") or not hasattr(other, "value"): + return ConstantVariable.create(NotImplemented) + result = ( + self.value == other.value if op == "__eq__" else self.value != other.value + ) + return ConstantVariable.create(result) + + @classmethod + def can_constant_fold_through(cls, fn: types.FunctionType) -> bool: + mod = fn.__module__.split(".") + if len(mod) < 2: + raise AssertionError( + f"Expected module path with at least 2 parts, got {mod}" + ) + if mod[:2] != ["torch", "_numpy"]: + raise AssertionError( + f"Expected torch._numpy module, got {'.'.join(mod[:2])}" + ) + return fn in cls.constant_fold_functions + + @classmethod + def get_constant_collection_for_func(cls, fn: types.FunctionType) -> Any: + mod = fn.__module__.split(".") + if len(mod) < 2: + raise AssertionError( + f"Expected module path with at least 2 parts, got {mod}" + ) + if mod[:2] != ["torch", "_numpy"]: + raise AssertionError( + f"Expected torch._numpy module, got {'.'.join(mod[:2])}" + ) + return np_constant_collections_map.get(fn) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if not config.trace_numpy: + unimplemented( + gb_type="attempted to trace numpy function with config.trace_numpy=False", + context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs}", + explanation=f"Attempted to trace numpy function {self.value} " + "while `torch._dynamo.config.trace_numpy` was set to False.", + hints=[ + "Set `torch._dynamo.config.trace_numpy` to True to trace numpy functions.", + ], + ) + + from ..utils import numpy_to_tensor_wrapper + from .tensor import NumpyNdarrayVariable + + func = get_np_to_tnp_map().get(self.value) + if func is None: + unimplemented( + gb_type="attempted to trace numpy function unsupported by PyTorch", + context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + explanation=f"Can't find numpy numpy function {self.value} in torch._numpy.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + # We are dealing with a function that produces a const collection type (np.dtype, np.iinfo/np.finfo) + if func is None: + raise AssertionError( + f"Could not find torch._numpy equivalent for {self.value}" + ) + if ( + collection_variable_typ := self.get_constant_collection_for_func(func) + ) is not None: + try: + return collection_variable_typ( + self.value( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + ) + except AsPythonConstantNotImplementedError: + unimplemented( + gb_type="numpy function that produces a const collection type encountered non-const arguments", + context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + explanation=f"numpy function {self.value} that produces a const collection type " + "(e.g. np.dtype, np.iinfo/np.finfo) " + "received arguments that are not constant.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + else: + if ( + func.__module__ == "torch._numpy.random" + and config.use_numpy_random_stream + ): + unimplemented( + gb_type="attempted to trace torch._numpy.random function with config.use_numpy_random_stream=True", + context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + explanation=f"Attempted to trace {self.value} when `torch._dynamo.config.use_numpy_random_stream` " + "is set to True.", + hints=[ + "Set `torch._dynamo.config.use_numpy_random_stream` to False.", + f"Avoid calling {self.value}.", + ], + ) + + args, kwargs = NumpyNdarrayVariable.patch_args(func.__name__, args, kwargs) + + if self.can_constant_fold_through(func) and ( + check_unspec_or_constant_args(args, kwargs) + ): + # constant fold + return VariableTracker.build( + tx, + self.as_python_constant()( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ), + ) + + # TODO Add all the functions that go from constants to constants to can_constant_fold_through + proxy = tx.output.create_proxy( + "call_function", + numpy_to_tensor_wrapper(func), + *proxy_args_kwargs(args, kwargs), + ) + return NumpyNdarrayVariable.create(tx, proxy) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + unimplemented( + gb_type="attempted to trace numpy.* function as a method", + context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs}", + explanation="Tracing numpy.* functions as methods is not supported.", + hints=[ + *graph_break_hints.DIFFICULT, + ], + ) + + def as_python_constant(self) -> BuiltinFunctionType: + return self.value + + def as_proxy(self) -> Any: + if config.trace_numpy: + # Can replace with EnumType once we drop 3.10 support + if isinstance(self.value, enum.EnumMeta): + # This is mostly for np._CopyMode + return self.value + if isinstance(self.value, type): + # This handles numpy dtype attributes such as np.float32 + # We return a string as we don't want to serialize non-PyTorch objects in the output FX graph + # In torch/_numpy we normalize strings to their dtypes when the input is a dtype, as NumPy does + return self.value.__name__ + + return super().as_proxy() + + +# Used to keep track of NULLs pushed on the stack for Python 3.11 function calls +class NullVariable(VariableTracker): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "NullVariable" + + def reconstruct(self, codegen: "PyCodegen") -> None: + if sys.version_info < (3, 11): + unimplemented( + gb_type="cannot reconstruct NullVariable in Python < 3.11", + context="", + explanation="Attempted to generate PUSH_NULL instruction in Python < 3.11; " + "where this instruction does not exist.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + codegen.append_output(create_instruction("PUSH_NULL")) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + return "None" + + +class DeletedVariable(VariableTracker): + """Marker used to implement delattr()""" + + +class StringFormatVariable(VariableTracker): + """ + Represents a call to str.format(), we delay calling format until after the graph. + """ + + _nonvar_fields = {"format_string", *VariableTracker._nonvar_fields} + + def python_type(self) -> type: + return str + + @classmethod + def create( + cls, + format_string: str, + sym_args: list[VariableTracker], + sym_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if all( + x.is_python_constant() + for x in itertools.chain(sym_args, sym_kwargs.values()) + ): + return variables.ConstantVariable.create( + format_string.format( + *[v.as_python_constant() for v in sym_args], + **{k: v.as_python_constant() for k, v in sym_kwargs.items()}, + ) + ) + return cls(format_string, list(sym_args), dict(sym_kwargs)) + + def __init__( + self, + format_string: str, + sym_args: list[VariableTracker], + sym_kwargs: dict[str, VariableTracker], + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(format_string, str): + raise AssertionError( + f"format_string must be a str, got {type(format_string)}" + ) + self.format_string = format_string + self.sym_args = sym_args + self.sym_kwargs = sym_kwargs + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.format_string!r}, {self.sym_args!r}, {self.sym_kwargs!r})" + + @staticmethod + def _debug_format_arg(arg: VariableTracker) -> object: + try: + return arg.as_python_constant() + except Exception: + return arg.debug_repr() + + def debug_repr(self) -> str: + try: + rendered = self.format_string.format( + *[self._debug_format_arg(arg) for arg in self.sym_args], + **{ + key: self._debug_format_arg(value) + for key, value in self.sym_kwargs.items() + }, + ) + except Exception: + return repr(self) + return repr(rendered) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_const(self.format_string), + codegen.create_load_attr("format"), + ] + ), + call_function_ex=True, + ) + codegen(variables.TupleVariable(list(self.sym_args))) + kwargs = { + variables.ConstantVariable.create(k): v for k, v in self.sym_kwargs.items() + } + codegen(variables.ConstDictVariable(kwargs)) + codegen.extend_output(create_call_function_ex(True, False)) + + +class ObjectVariable(VariableTracker): + # PyBaseObject_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L7243 + _cpython_type = object + + # placeholder for unknown / opaque values + def __init__(self, value: object, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def get_real_python_backed_value(self) -> object: + return self.value + + def python_type(self) -> type[object]: + return object + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + +if sys.version_info >= (3, 15): + + class SentinelVariable(VariableTracker): + # Use builtins.sentinel to avoid ruff errors + _cpython_type = builtins.sentinel + + def __init__(self, value: builtins.sentinel, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def get_real_python_backed_value(self) -> builtins.sentinel: + return self.value + + def python_type(self) -> type[builtins.sentinel]: + return self._cpython_type + + +class DebuggingVariable(VariableTracker): + """ + Represents a call to a debugging function like print(), or something + registered to config.reorderable_logging_functions. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def python_type(self) -> type: + return type(self.value) + + @staticmethod + def is_reorderable_logging_function( + obj: Any, + ) -> TypeGuard[types.FunctionType | types.BuiltinFunctionType]: + return ( + callable(obj) + and isinstance(obj, (types.FunctionType, types.BuiltinFunctionType)) + and obj in torch._dynamo.config.reorderable_logging_functions + ) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if tx.export: + # For export cases, we can just make debugging functions no-ops + return ConstantVariable.create(None) + + if not self.can_reorder_logs(self.value, args, kwargs): + unimplemented( + gb_type="attempted to reorder a debugging function that can't actually be reordered", + context=f"fn: {self.value}, args: {args}, kwargs: {kwargs}", + explanation="`torch.compile` can only reorder functions that are called " + "without keyword arguments and whose arguments are Tensors, constants, " + "or string formatters.", + hints=[ + f"Avoid calling the logging function {self.value} with args that are not supported.", + ], + ) + + tx.debug_locals.append((self, list(args))) + return ConstantVariable.create(None) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.source is None: + raise AssertionError( + "DebugLocalVariable requires a source for reconstruction" + ) + return self.source.reconstruct(codegen) + + @staticmethod + def can_reorder_logs(fn: Any, args: Sequence[Any], kwargs: dict[str, Any]) -> bool: + """ + Run some additional checks for what sort of function calls can we + actually reorder. + """ + + # kwargs are dropped by the replay codegen, so refuse rather than lose them + if kwargs: + return False + + allowed_input_types = ( + variables.TensorVariable, + variables.ConstantVariable, + StringFormatVariable, + ) + + flat_args = pytree.tree_leaves(args) + for arg in flat_args: + if not isinstance(arg, allowed_input_types): + return False + + return True + + +class IgnoredFunctionVariable(VariableTracker): + """ + Represents a call to an arbitrary function that should be ignored. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def python_type(self) -> type: + return type(self.value) + + def get_real_python_backed_value(self) -> Any: + return self.value + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return variables.ConstantVariable.create(None) + + +class LoggingLoggerVariable(VariableTracker): + """ + Represents a call to any logging.Logger methods. + """ + + def __init__(self, value: logging.Logger, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def python_type(self) -> type: + return type(self.value) + + def get_real_python_backed_value(self) -> logging.Logger: + return self.value + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if tx.export: + # For export cases, we can just make logging functions no-ops. + return variables.ConstantVariable.create(None) + + method = getattr(self.value, name, None) + function = getattr(method, "__func__", None) + + # Unified ignore set + ignore_set = torch._dynamo.config.ignore_logging_functions + + if method in ignore_set or function in ignore_set: + return variables.ConstantVariable.create(None) + + reorderable = torch._dynamo.config.reorderable_logging_functions + if self.source and (method in reorderable or function in reorderable): + fn_var = DebuggingVariable(method, source=AttrSource(self.source, name)) + return fn_var.call_function(tx, args, kwargs) + + logger_cls = type(self.value) + logger_cls_name = f"{logger_cls.__module__}.{logger_cls.__qualname__}" + unimplemented( + gb_type="logging.Logger method not supported for non-export cases", + context=f"method: {self.value}.{name}, args: {args}, kwargs: {kwargs}", + explanation="For non-export cases, logging.Logger methods are only supported if the logger " + "has a source and the method is registered as reorderable.", + hints=[ + "If you do not need this logging side effect, add the exact method being called to `torch._dynamo.config.ignore_logging_functions`. Dynamo will skip the call and return `None`.", + f"For example, for `logger.{name}(...)`, use `torch._dynamo.config.ignore_logging_functions.add(logger.{name})`. If `{name}` is defined on the logger class, add the class method `{logger_cls_name}.{name}` to ignore this method for all instances of that class.", + f"Dynamo does not trace into logging.Logger method bodies, so only the method you call directly (`{name}`) is checked against the ignore set. Ignoring a method that `{name}` calls internally has no effect.", + f"If you need the log side effect to run, then you can try one of (1) create the logger outside the compiled region and add the method to `torch._dynamo.config.reorderable_logging_functions` (e.g. `torch._dynamo.config.reorderable_logging_functions.add(logger.{name})`) so that it runs after the compiled region, as long as it is called without kwargs and its arguments are tensors, constants, or string formatters, (2) `torch._higher_order_ops.print(...)`, (3) wrap the logging call in a custom op (marked as mutable), or (4) preserve the logging contents and move the logging call outside the compiled region.", + ], + ) + + +class ConstantLikeVariable(VariableTracker): + """self.value is a compile-time constant, but not a literal""" + + try: + from numpy import ( + dtype as np_dtype, + floating as np_floating, + generic as np_generic, + ) + except ImportError: + # type: ignore[misc, assignment] + np_floating = type("invalid_type", (), {}) + # type: ignore[misc, assignment] + np_dtype = type("invalid_type", (), {}) + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + @property + def _error_prefix(self) -> str: + """Dynamically compute the prefix from the value's type""" + t = type(self.value) + + # For builtins (int, str, etc.), just return the name + if t.__module__ == "builtins": + return t.__qualname__ + + return f"{t.__module__}.{t.__qualname__}" + + def as_python_constant(self) -> Any: + return self.value + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return hash(self.value), False + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # pyrefly: ignore [implicit-any] + cargs, ckwargs = [], {} + try: + # we only support constant propagation for methods + cargs = [x.as_python_constant() for x in args] + ckwargs = {k: v.as_python_constant() for k, v in kwargs.items()} + except NotImplementedError: + unimplemented( + gb_type="constant-like method call with non-constant args", + context=f"{self._error_prefix}.{name}(*{args}, **{kwargs})", + explanation=f"Attempted to call {self._error_prefix}.{name} with non-constant args.", + hints=[ + "Ensure that the args to the method call are constant (int, str, etc.).", + ], + ) + + result = getattr(self.value, name)(*cargs, **ckwargs) + + if variables.ConstantVariable.is_literal(result): + return VariableTracker.build(tx, result) + if isinstance(result, re.Match): + return ConstantLikeVariable(result) + + unimplemented( + gb_type="constant-like method call with unsupported return type", + context=f"{self._error_prefix}.{name}(*{args}, **{kwargs}) returned {result}", + explanation=f"Attempted to call {self._error_prefix}.{name}, got unsupported return value {result}.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + result = getattr(self.value, name) + if isinstance(result, self.np_floating): + result = float(result) + if isinstance(result, self.np_dtype): + return NumpyDTypeVariable(result) + if isinstance(result, type) and issubclass(result, self.np_generic): + # things like x.dtype.type + return NumpyVariable(result) + if variables.ConstantVariable.is_literal(result): + return VariableTracker.build(tx, result) + return GetAttrVariable(self, name, py_type=type(result)) + + +class NumpyDTypeVariable(ConstantLikeVariable): + def as_proxy(self) -> str: + """Similar to how numpy dtype descriptors (e.g. np.float32 ) are handled by NumpyVariable: + + np.dtype() objects are serialized as strings, torch._numpy wrappers will normalize to the torch dtype. + This also handles unsupported things nicely (i.e. structured arrays and object arrays). + """ + return self.value.type.__name__ + + +np_constant_collections_map = { + tnp.finfo: ConstantLikeVariable, + tnp.iinfo: ConstantLikeVariable, + tnp.dtype: NumpyDTypeVariable, +} + + +class ContextVarVariable(VariableTracker): + """Wraps a contextvars.ContextVar for Dynamo tracing. + + .get() is resolved at trace time with a guard that re-checks at cache time. + .set() and .reset() graph-break in Phase 1. + """ + + _nonvar_fields = { + "cv_obj", + *VariableTracker._nonvar_fields, + } + + def __init__(self, cv_obj: contextvars.ContextVar[Any], **kwargs: Any) -> None: + super().__init__(**kwargs) + self.cv_obj = cv_obj + + def python_type(self) -> type: + return contextvars.ContextVar + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: "list[VariableTracker]", + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + if name == "get": + return self._handle_get(tx, args, kwargs) + elif name in ("set", "reset"): + unimplemented( + gb_type="ContextVar mutation not supported", + context=f"ContextVar('{self.cv_obj.name}').{name}()", + explanation=( + f"ContextVar.{name}() is not yet supported inside " + f"torch.compile. Move the .{name}() call outside the " + f"compiled region." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + return super().call_method(tx, name, args, kwargs) + + def _handle_get( + self, + tx: "InstructionTranslatorBase", + args: "list[VariableTracker]", + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + from ..source import ContextVarGetSource + from ..utils import is_safe_constant + from .base import NO_SUCH_SUBOBJ + + if kwargs: + raise_observed_exception( + TypeError, tx, args=["ContextVar.get() takes no keyword arguments"] + ) + if len(args) > 1: + raise_observed_exception( + TypeError, + tx, + args=[f"get expected at most 1 argument, got {len(args)}"], + ) + + default_var = args[0] if args else None + has_default = default_var is not None + default_value = None + + if has_default: + default_value = default_var.get_real_python_backed_value() + if default_value is NO_SUCH_SUBOBJ or not is_safe_constant(default_value): + unimplemented( + gb_type="ContextVar.get() with non-constant default", + context=f"ContextVar('{self.cv_obj.name}').get(...)", + explanation=( + "ContextVar.get() default argument must be a " + "compile-time constant inside torch.compile." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + + value = self._get_value(tx, has_default, default_value) + + if not self.source: + raise AssertionError("ContextVarVariable requires a source for .get()") + value_source = ContextVarGetSource( + base=self.source, + has_default=has_default, + default_value=default_value, + ) + return VariableTracker.build(tx, value, source=value_source) + + def _get_value( + self, + tx: "InstructionTranslatorBase", + has_default: bool, + default_value: Any, + ) -> Any: + if has_default: + return self.cv_obj.get(default_value) + try: + return self.cv_obj.get() + except LookupError: + raise_observed_exception(LookupError, tx, args=[f"{self.cv_obj!r}"]) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> "VariableTracker": + if name == "name": + return ConstantVariable.create(self.cv_obj.name) + return super().tp_getattro_impl(tx, name) + + +class RandomClassVariable(VariableTracker): + """random.Random""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + def python_type(self) -> type: + return type + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "RandomVariable": + if len(args) > 1 or kwargs: + unimplemented( + gb_type="random.Random() with improper arguments", + context=f"args: {args}, kwargs: {kwargs}", + explanation="random.Random() with > 1 arg or with kwargs is not supported.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + seed = variables.ConstantVariable.create(None) if len(args) == 0 else args[0] + return RandomVariable( + seed=seed, mutation_type=variables.base.ValueMutationNew() + ) + + +class RandomVariable(VariableTracker): + """random.Random() + + Implemented by wrapping a VariableTracker around a random.Random object. + The supported methods for the random.Random object cannot be overridden. + Assumes that random objects behave the same given a set seed or state. + """ + + _cpython_type = random.Random + + _nonvar_fields = { + "random", + *VariableTracker._nonvar_fields, + } + + _supported_fn_names = { + "random", + "randint", + "randrange", + "uniform", + } + + def __init__( + self, + rand: random.Random | None = None, + seed: VariableTracker | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if rand is not None: + if not self.is_supported_random_obj(rand): + raise AssertionError( + "Unsupported random.Random object with overridden methods" + ) + self.random = random.Random() + self.random.setstate(rand.getstate()) + else: + seed = seed.as_python_constant() if seed is not None else None + self.random = random.Random(seed) + + def python_type(self) -> type[random.Random]: + return random.Random + + def as_python_constant(self) -> random.Random: + return self.random + + @staticmethod + def is_supported_random_obj(val: Random) -> bool: + if type(val) is not random.Random: + return False + for name in itertools.chain( + RandomVariable._supported_fn_names, ("seed", "getstate", "setstate") + ): + if not hasattr(val, name): + return False + meth = getattr(val, name) + if inspect.isbuiltin(meth): + # e.g. random.Random.random + if meth != getattr(random.Random, name).__get__(val): + return False + else: + if getattr(meth, "__func__", None) is not getattr(random.Random, name): + return False + return True + + @staticmethod + def check_state(state: tuple[int, tuple[int, ...], float | None]) -> None: + if type(state) is not tuple: + raise AssertionError(f"state must be a tuple, got {type(state)}") + if type(state[0]) is not int: + raise AssertionError(f"state[0] must be an int, got {type(state[0])}") + if type(state[1]) is not tuple: + raise AssertionError(f"state[1] must be a tuple, got {type(state[1])}") + if not all(type(x) is int for x in state[1]): + raise AssertionError("all elements of state[1] must be int") + if state[2] is not None and type(state[2]) is not float: + raise AssertionError( + f"state[2] must be None or float, got {type(state[2])}" + ) + + @staticmethod + def wrap_state(state: tuple[int, tuple[int, ...], float | None]) -> TupleVariable: + RandomVariable.check_state(state) + return variables.TupleVariable( + [ + variables.ConstantVariable.create(state[0]), + variables.TupleVariable( + [variables.ConstantVariable.create(x) for x in state[1]] + ), + variables.ConstantVariable.create(state[2]), + ] + ) + + @staticmethod + def unwrap_state( + state: VariableTracker, + ) -> tuple[int, tuple[int, ...], float | None]: + state_obj = state.as_python_constant() + RandomVariable.check_state(state_obj) + return state_obj + + def seed( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.side_effects.mutation(self) + self.random.seed( + *[x.as_python_constant() for x in args], + **{key: val.as_python_constant() for key, val in kwargs.items()}, + ) + return variables.ConstantVariable.create(None) + + def getstate( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.wrap_state(self.random.getstate()) + + def setstate( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.side_effects.mutation(self) + self.random.setstate(self.unwrap_state(args[0])) + return variables.ConstantVariable.create(None) + + def shuffle( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + name = "shuffle" + check_positional(tx, name, len(args), 1, 1) + no_keywords(tx, name, kwargs) + seq = args[0].realize() + tx.output.side_effects.mutation(self) + # shuffle's permutation depends only on the sequence length and the + # RNG state, not on the elements, so shuffle a list of indices to + # both advance the symbolic RNG and obtain the permutation to apply. + if not hasattr(seq, "items"): + raise AssertionError("shuffle only supports ListVariable and TupleVariable") + perm = list(range(len(seq.items))) + self.random.shuffle(perm) + tx.output.side_effects.mutation(seq) + seq.items[:] = [seq.items[i] for i in perm] + return variables.ConstantVariable.create(None) + + def sample( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + name = "sample" + check_positional(tx, name, len(args), 2, 2) + no_keywords(tx, name, kwargs) + elems = unpack_iterable(tx, args[0]) + k = args[1].as_python_constant() + if not isinstance(k, int) or k < 0 or k > len(elems): + raise_value_error( + tx, + "Sample larger than population or is negative", + ) + tx.output.side_effects.mutation(self) + # Like shuffle, sample's selected positions depend only on the + # population length and RNG state, so sample over an index range to + # advance the symbolic RNG and pick the population elements to keep. + indices = self.random.sample(range(len(elems)), k) + return variables.ListVariable( + [elems[i] for i in indices], + mutation_type=variables.base.ValueMutationNew(), + ) + + def _call_random(self, tx, name, args, kwargs): + tx.output.side_effects.mutation(self) + state = self.random.getstate() + + def call_random_meth(*args: Any, **kwargs: Any) -> Any: + r = random.Random() + r.setstate(state) + return getattr(r, name)(*args, **kwargs) + + # self.random state not actually updated by call_random_meth, so update here + # by calling the method + getattr(self.random, name)( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + + return call_random_fn(tx, call_random_meth, args, kwargs) + + def _random( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._call_random(tx, "random", args, kwargs) + + def _randint( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._call_random(tx, "randint", args, kwargs) + + def _randrange( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._call_random(tx, "randrange", args, kwargs) + + def _uniform( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._call_random(tx, "uniform", args, kwargs) + + tp_methods = { + "seed": Method(seed), + "getstate": Method(getstate), + "setstate": Method(setstate), + "shuffle": Method(shuffle), + "sample": Method(sample), + "random": Method(_random), + "randint": Method(_randint), + "randrange": Method(_randrange), + "uniform": Method(_uniform), + } + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(random), + codegen.create_load_attr("Random"), + ] + ) + ) + codegen.call_function(0, False) + # NOTE using add_push_null may result in NULL being duplicated + # so defer the push_null to call_function + codegen.dup_top() + codegen.load_attr("setstate") + codegen(self.wrap_state(self.random.getstate())) + codegen.call_function(1, True) + codegen.pop_top() + + +class WeakRefVariable(VariableTracker): + def python_type(self) -> type: + return weakref.ref + + @staticmethod + # pyrefly: ignore [bad-override, bad-param-name-override] + def build( + tx: "InstructionTranslatorBase", + weakref_value: weakref.ReferenceType[Any], + source: Source | None, + **options: Any, + ) -> "WeakRefVariable": + if source is None: + raise AssertionError("WeakRefVariable.build requires a source") + callback = weakref_value.__callback__ + callback_source = source and AttrSource(source, "__callback__") + callback_vt = VariableTracker.build(tx, callback, callback_source) + referent = weakref_value() + source = source and WeakRefCallSource(source) + referent_vt = VariableTracker.build(tx, referent, source) + options["source"] = source + return WeakRefVariable(referent_vt, callback_vt, **options) + + def __init__( + self, referent_vt: VariableTracker, callback_vt: VariableTracker, **options: Any + ) -> None: + super().__init__(**options) + self.referent_vt = referent_vt + self.callback_vt = callback_vt + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.referent_vt + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("weakref", "ref")) + codegen(self.referent_vt) + codegen(self.callback_vt) + codegen.extend_output(create_call_function(2, False)) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CPython weakref_hash: hash(referent) + # https://github.com/python/cpython/blob/e76aa128fe/Objects/weakrefobject.c#L186 + from .object_protocol import generic_hash_impl + + return generic_hash_impl(tx, self.referent_vt) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import generic_richcompare + + # Weak references only support equality, not ordering. Two weak references + # are equal if the underlying objects are equal. If the underlying object has + # gone away, they are equal if they are identical. + if op not in ("__eq__", "__ne__") or not isinstance(other, WeakRefVariable): + return ConstantVariable.create(NotImplemented) + return generic_richcompare(tx, self.referent_vt, other.referent_vt, op) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/nn_module.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/nn_module.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0dfd62bcfa4a051eeecaff443f4402e302b237 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/nn_module.py @@ -0,0 +1,1649 @@ +""" +This module implements variable tracking for PyTorch nn.Module instances during Dynamo tracing. + +It provides specialized handling for different types of nn.Module instances through several key classes: + +- NNModuleVariable: Handles instance-specific module tracing, specializing on module id() and placing + parameters directly on the torch.fx.GraphModule. This creates one graph per module instance. + +- UnspecializedNNModuleVariable: Provides class-level module tracing, treating nn.Modules like other + user-defined objects and passing parameters as inputs to the FX graph. This creates one graph per + module class. + +- UnspecializedBuiltinNNModuleVariable: Specifically handles built-in PyTorch modules (e.g. nn.Linear) + with appropriate optimizations. + +- FSDPManagedNNModuleVariable: Special handling for FSDP-wrapped modules with modified guarding behavior + and parameter handling. + +The module integrates with Dynamo's broader tracing functionality to handle module method calls, +parameter access, hooks, and other nn.Module behaviors while maintaining proper scoping and guarding +of module state. +""" + +import collections +import functools +import inspect +import itertools +import re +import types +from collections.abc import Iterable +from contextlib import contextmanager, nullcontext +from typing import Any, TYPE_CHECKING + +import torch.nn +from torch._guards import Source + +from .. import graph_break_hints, trace_rules, variables +from ..exc import ( + handle_observed_exception, + ObservedAttributeError, + raise_observed_exception, + raise_type_error, + unimplemented, + UnspecializeRestartAnalysis, + Unsupported, +) +from ..guards import GuardBuilder, install_guard, make_dupe_guard +from ..mutation_guard import GenerationTracker +from ..source import ( + AttrSource, + ConstDictKeySource, + DictGetItemSource, + FSDPNNModuleSource, + GetItemSource, + NNModuleSource, + UnspecializedNNModuleSource, +) +from ..utils import ( + enumerate_items_with_dict_position, + get_custom_getattr, + get_fake_value, + is_lazy_module, + is_namedtuple, + is_safe_constant, + istensor, + istype, + nnmodule_has_hooks, + object_has_getattribute, + proxy_args_kwargs, + raise_args_mismatch, + set_example_value, + unpatched_nn_module_call, + unpatched_nn_module_call_impl, +) +from .base import Method, typestr, ValueMutationNew, VariableTracker +from .functions import invoke_and_store_as_constant +from .lazy import LazyVariableTracker +from .user_defined import UserDefinedObjectVariable + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from .constant import ConstantVariable + + +def initialize_lazy_module( + tx: "InstructionTranslatorBase", + mod: torch.nn.Module, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> None: + """ + Fairly coupled helper used by NNModuleVariable and UnspecializedNNModuleVariable. + + Used to cause lazy module to be initialized (and delete its init hook) before tracing. Especially + useful now that 'allowed' modules graph-break on hooks, calling this first ensures there is no hook + by the time we trace __call__ and thus no graph-break for lazy allowed modules. + """ + if inspect.getattr_static(mod, "_initialize_hook", None) is not None: + + def convert_to_fake(x: Any) -> Any: + if is_namedtuple(x): + return type(x)(*(convert_to_fake(elem) for elem in x)) + elif isinstance(x, dict): + return {k: convert_to_fake(v) for k, v in x.items()} # type: ignore[misc] + elif isinstance(x, (list, tuple, set)): + return type(x)(convert_to_fake(elem) for elem in x) + elif isinstance(x, torch.fx.Proxy): + fake = get_fake_value(x.node, tx) + if isinstance(fake, torch.Tensor) and any( + isinstance(s, torch.SymInt) for s in fake.shape + ): + # _infer_parameters runs real ops on the module, so + # symbolic shapes must be concretized to their hints. + shape = [ + s.node.hint if isinstance(s, torch.SymInt) else s + for s in fake.shape + ] + if not all(isinstance(s, int) for s in shape): + raise AssertionError( + f"expected all shape entries to be int, got {shape}" + ) + return torch.empty( # pyrefly: ignore[no-matching-overload] + shape, dtype=fake.dtype, device=fake.device + ) + return fake + else: + return x + + proxy_args, proxy_kwargs = proxy_args_kwargs(args, kwargs) + fake_args = [convert_to_fake(arg) for arg in proxy_args] + fake_kwargs = {k: convert_to_fake(v) for k, v in proxy_kwargs.items()} + try: + mod._infer_parameters(mod, fake_args, fake_kwargs) # type: ignore[operator] + except AttributeError: + # Re-raise with the original error message from the AttributeError + raise_observed_exception( + AttributeError, + tx, + args=["AttributeError during lazy module initialization"], + ) + + +@contextmanager +def record_nn_module_stack( + module_key: str, + source: Source, + tx: "InstructionTranslatorBase", + mod: torch.nn.Module, +) -> Any: + fully_qualified_name = source.name + # Remove redundant namings + fully_qualified_name = re.sub( + r"\._(?:modules|parameters|buffers)\[(['\"])([^'\"\]]+)\1\]", + r".\2", + fully_qualified_name, + ) + num_calls = tx.num_calls.get(fully_qualified_name, 0) + module_key = f"{module_key}@{num_calls}" if num_calls > 0 else module_key + try: + tx.nn_module_stack[module_key] = (fully_qualified_name, mod.__class__) + tx.num_calls[fully_qualified_name] = num_calls + 1 + yield + finally: + del tx.nn_module_stack[module_key] + + +def guard_to_detect_forward_monkeypatching( + source: Source | None, mod: torch.nn.Module +) -> None: + # Users sometimes patch the forward method of a nn module instance to + # perform optimizations like quantization. Though this is not a good + # software practice, but python allows this and Dynamo needs to detect + # this patching. + # + # One way to do this is to add an ID_MATCH guard on every function + # getting inlined (https://github.com/pytorch/pytorch/pull/124975). But + # this increased guard overhead by around 20%. + # + # To keep the guard overhead down, we just guard on the `forward` being + # not present in the mod __dict__. The common case of patching forward + # method adds `forward` in the instance __dict__, whereas the unpatched + # `forward` sits in the type(mod).__dict__ + if source: + if "forward" in mod.__dict__ and callable(mod.__dict__["forward"]): + # Monkeypatched forward method, guard on call-relevant structure. + fwd = mod.__dict__["forward"] + forward_source = AttrSource(source, "forward") + if type(fwd) is types.MethodType: + forward_source = AttrSource(forward_source, "__func__") + install_guard(forward_source.make_guard(GuardBuilder.CLOSURE_MATCH)) + elif isinstance(fwd, functools.partial): + guard_to_detect_forward_partial_monkeypatching( + source, mod, forward_source, fwd + ) + else: + install_guard(forward_source.make_guard(GuardBuilder.CLOSURE_MATCH)) + else: + # Common case - check that the forward key is absent in mod __dict__ + install_guard( + source.make_guard( + functools.partial( + GuardBuilder.NOT_PRESENT_IN_GENERIC_DICT, attr="forward" + ) + ) + ) + + +def guard_to_detect_forward_partial_monkeypatching( + module_source: Source, + mod: torch.nn.Module, + partial_source: Source, + partial_obj: functools.partial[Any], +) -> None: + install_guard(partial_source.make_guard(GuardBuilder.TYPE_MATCH)) + + func_source = AttrSource(partial_source, "func") + if isinstance(partial_obj.func, functools.partial): + guard_to_detect_forward_partial_monkeypatching( + module_source, mod, func_source, partial_obj.func + ) + else: + install_guard(func_source.make_guard(GuardBuilder.CLOSURE_MATCH)) + + args_source = AttrSource(partial_source, "args") + install_guard(args_source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + for i, arg in enumerate(partial_obj.args): + guard_to_detect_forward_partial_value( + module_source, mod, GetItemSource(args_source, i), arg + ) + + keywords_source = AttrSource(partial_source, "keywords") + if partial_obj.keywords is None: + install_guard(keywords_source.make_guard(GuardBuilder.NONE_MATCH)) + return + + install_guard(keywords_source.make_guard(GuardBuilder.DICT_KEYS_MATCH)) + for key, value in partial_obj.keywords.items(): + guard_to_detect_forward_partial_value( + module_source, mod, DictGetItemSource(keywords_source, key), value + ) + + +def guard_to_detect_forward_partial_value( + module_source: Source, + mod: torch.nn.Module, + value_source: Source, + value: Any, +) -> None: + if value is mod: + dupe_guard = make_dupe_guard(value_source, module_source) + install_guard(value_source.make_guard(dupe_guard or GuardBuilder.ID_MATCH)) + elif isinstance(value, functools.partial): + guard_to_detect_forward_partial_monkeypatching( + module_source, mod, value_source, value + ) + elif type(value) is types.FunctionType: + install_guard(value_source.make_guard(GuardBuilder.CLOSURE_MATCH)) + elif is_safe_constant(value): + install_guard(value_source.make_guard(GuardBuilder.CONSTANT_MATCH)) + else: + install_guard(value_source.make_guard(GuardBuilder.ID_MATCH)) + + +class NNModuleVariable(VariableTracker): + _nonvar_fields = { + "module_type", + "module_key", + "value", + "nn_module_stack_source", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, module_type: type, module_key: str, value: torch.nn.Module, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.module_type = module_type + self.module_key = module_key + self.value = value + # pyrefly: ignore[bad-override] + # NOTE: Don't remove this; better than adding suppressions + # everywhere else with asserts + self.source: Source = self.source + self.nn_module_stack_source = self.source + + def get_nn_module_stack_source(self) -> Source: + res = self.nn_module_stack_source or self.source + if not res: + raise AssertionError("nn_module_stack_source must not be None") + return res + + def set_nn_module_stack_source(self, source: Source) -> None: + self.nn_module_stack_source = source + + def python_type(self) -> type: + return self.module_type + + def get_id(self, tx: "InstructionTranslatorBase") -> int | None: + return id(tx.output.get_submodule(self.module_key)) + + def get_real_python_backed_value(self) -> object: + return self.value + + def nb_bool_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """nb_bool for nn.Module. + + nn.Module itself has no __bool__ or __len__, so bare modules are always + truthy. Subclasses like ModuleList/ModuleDict define __len__, so + bool(module) calls PyObject_IsTrue which falls through nb_bool (NULL) + to sq_length/mp_length. We evaluate on the real module to capture this. + """ + from .constant import ConstantVariable + + mod = tx.output.get_submodule(self.module_key) + return ConstantVariable.create(bool(mod)) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + mod = tx.output.get_submodule(self.module_key) + return VariableTracker.build(tx, repr(mod)) + + def _wrap_submodule( + self, + tx: "InstructionTranslatorBase", + source: Source, + submod: torch.nn.Module, + *key_extra: Any, + **options: Any, + ) -> None: + return + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + # implement list/iter/tuple/etc calls + base = tx.output.get_submodule(self.module_key) + result: list[VariableTracker] = [] + if isinstance(base, torch.nn.ModuleDict): + for name, submod in base.items(): + name_var = VariableTracker.build(tx, name) + tx.output.register_attr_or_module( + submod, + self.module_key, + name, + source=NNModuleSource(GetItemSource(self.source, name)), # type: ignore[arg-type] + ) + result.append(name_var) + return result + + if not isinstance( + base, (torch.nn.ModuleList, torch.nn.ParameterList, torch.nn.Sequential) + ): + raise AssertionError( + f"Expected ModuleList, ParameterList, or Sequential, got {typestr(base)}" + ) + for idx, submod in enumerate(base): + result.append( + tx.output.register_attr_or_module( + submod, + self.module_key, + idx, + source=NNModuleSource(GetItemSource(self.source, idx)), + ) + ) + return result + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> "ConstantVariable": + mod = tx.output.get_submodule(self.module_key) + result = hasattr(mod, name) + install_guard( + self.source.make_guard(functools.partial(GuardBuilder.HASATTR, attr=name)) + ) + return VariableTracker.build(tx, result) + + def is_training(self, tx: "InstructionTranslatorBase") -> bool: + mod = tx.output.get_submodule(self.module_key) + return getattr(mod, "training", False) + + def convert_to_unspecialized(self, tx: "InstructionTranslatorBase") -> None: + """Restart analysis treating this module as an UnspecializedNNModuleVariable""" + mod = tx.output.get_submodule(self.module_key) + GenerationTracker.tag(mod) + + # Mark the class dynamic unless its module initialization + if tx.f_code.co_name != "__init__": + GenerationTracker.mark_class_dynamic(type(mod)) + raise UnspecializeRestartAnalysis + + def _custom_getattr_fallback( + self, + base: torch.nn.Module, + tx: "InstructionTranslatorBase", + name: str, + obj_source: Source, + ) -> VariableTracker | None: + """Check for a __getattr__ and handle it specially if it is implemented""" + if object_has_getattribute(base): + getattribute_fn = inspect.getattr_static(type(base), "__getattribute__") + new_source = ( + AttrSource(obj_source, "__getattribute__") if obj_source else None + ) + try: + return variables.UserMethodVariable( + getattribute_fn, + self, + source=new_source, + ).call_function(tx, [variables.ConstantVariable.create(name)], {}) + except ObservedAttributeError: + handle_observed_exception(tx) + except Unsupported: + unimplemented( + gb_type="Custom __getattribute__ in nn.Module attribute access", + context=f"tp_getattro_impl {self} {name}", + explanation="Dynamo could not trace through the custom " + "`__getattribute__` method on this `nn.Module`.", + hints=[ + "Simplify your `__getattribute__` implementation, " + "or replace it with a targeted `@property`.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + getattr_fn = get_custom_getattr(base, ignore_nn_module_getattr=True) + if getattr_fn is None: + return None + + if not isinstance(getattr_fn, types.FunctionType): + unimplemented( + gb_type="torch.nn.Module with a non-function custom __getattr__", + context=f"tp_getattro_impl {self} {name}", + explanation=( + "Dynamo detected a nn.Module object with a custom " + "`__getattr__` method, but this method is not a standard " + "Python function (e.g., it might be implemented in C/C++). " + "Dynamo cannot currently trace into such non-standard " + "`__getattr__` methods." + ), + hints=[ + "Avoid using objects with non-standard __getattr__ methods " + "within the compiled region. If possible, implement " + "__getattr__ as a standard Python function.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + options = {"source": AttrSource(obj_source, "__getattr__")} + + return variables.UserMethodVariable(getattr_fn, self, **options).call_function( + tx, [VariableTracker.build(tx, name)], {} + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + source = self.source and AttrSource(self.source, name) + + base = tx.output.get_submodule(self.module_key) + # NB: We look up attributes in __dict__ directly, bypassing any custom + # __getattribute__. Custom __getattribute__ is only traced through as a + # fallback (via _custom_getattr_fallback) for attributes not found here. + base_dict = object.__getattribute__(base, "__dict__") + object_member = True + all_class_attribute_names = set() + for x in inspect.getmro(base.__class__): + all_class_attribute_names.update(x.__dict__.keys()) + + if not self.source: + unimplemented( + gb_type="getattr with no source", + context=f"tp_getattro_impl {self} {name}", + explanation="Dynamo does not know how to access an attribute " + "on an `nn.Module` instance that lacks a source. This is " + "usually an internal error in Dynamo.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + if name == "__dict__": + return self.get_dict_vt(tx) + + subobj = None + if name in base_dict: + subobj = base_dict[name] + elif ( + "_modules" in base_dict + and name in base_dict["_modules"] + and name not in all_class_attribute_names + ): + subobj = base_dict["_modules"][name] + elif "_parameters" in base_dict and name in base_dict["_parameters"]: + subobj = base_dict["_parameters"][name] + elif "_buffers" in base_dict and name in base_dict["_buffers"]: + subobj = base_dict["_buffers"][name] + else: + try: + subobj = inspect.getattr_static(base, name) + object_member = False + except AttributeError: + # see if we can fallback to __getattr__, which is not checked by getattr_static + result = self._custom_getattr_fallback( + base=base, tx=tx, name=name, obj_source=self.source + ) + if result is not None: + return result + # if we can't find a __getattr__, we can't parse this, raise attribute error + raise_observed_exception( + AttributeError, + tx, + args=[f"'{type(base).__name__}' object has no attribute '{name}'"], + ) + + if name == "forward": + guard_to_detect_forward_monkeypatching(self.source, base) + + if name == "__class__" and not object_member: + return VariableTracker.build(tx, base.__class__, source=source) + + if object_member: + out = VariableTracker.build(tx, subobj, NNModuleSource(source)) # type: ignore[arg-type] + + if isinstance(out, (NNModuleVariable, UnspecializedNNModuleVariable)): + # nn_module_stack source is BC surface area. Ensure that + # mod._modules["linear"] is reflected as mod.linear for + # nn_module_stack. + out.set_nn_module_stack_source( + AttrSource(self.get_nn_module_stack_source(), name) + ) + return out + + else: + if istype(subobj, property): + if self.source: + # Read the class attribute to reach the property + source = AttrSource(AttrSource(self.source, "__class__"), name) + # Get the getter function + source = AttrSource(source, "fget") + return variables.UserFunctionVariable( + subobj.fget, # pyrefly: ignore[bad-argument-type] + source=source, + ).call_function(tx, [(self)], {}) + elif istype(subobj, classmethod): + return variables.UserMethodVariable( + subobj.__func__, + variables.UserDefinedObjectVariable(type(base)), + source=source, + ) + elif istype(subobj, staticmethod): + return variables.UserFunctionVariable( + subobj.__get__(base), + source=source, + ) + elif istype(subobj, types.FunctionType): + return variables.UserMethodVariable(subobj, self, source=source) + elif is_safe_constant(subobj) or istensor(subobj): + # Support possibly common cases of class members + return VariableTracker.build(tx, subobj, NNModuleSource(source)) # type: ignore[arg-type] + else: + unimplemented( + gb_type="Unsupported nn.Module attribute type", + context=f"nn.Module subclass: {typestr(base)}, name: {name}, attribute type: {typestr(subobj)}", + explanation=f"Dynamo does not support tracing nn.Module attributes of type `{typestr(subobj)}`", + hints=[ + f"Refactor your code so that `{name}` (type `{typestr(subobj)}`) is not an attribute of `{typestr(base)}`", + "Currently supported attribute types are methods, classmethods, staticmethods, " + "properties, constants, and tensors.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + return super().tp_getattro_impl(tx, name) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + mod = tx.output.get_submodule(self.module_key) + + with record_nn_module_stack( + self.module_key, self.get_nn_module_stack_source(), tx, mod + ): + is_lazy = is_lazy_module(mod) + if ( + isinstance(mod, torch.nn.Sequential) + and mod.__class__.forward is torch.nn.Sequential.forward + ): + if nnmodule_has_hooks(mod): + # We do not want to unroll sequential if it has hooks, since evaporating it + # will cause hooks to not fire! + # This terminates and restart the tracing process + self.convert_to_unspecialized(tx) + + # Unroll sequential + if is_lazy: + raise AssertionError( + "Expected lazy sequential isn't a valid combination?" + ) + if kwargs: + raise_args_mismatch( + tx, + "torch.nn.Module.Sequential", + "0 kwargs", + f"{len(kwargs)} kwargs", + ) + (arg,) = args + # TODO: Use named_children when it supports remove_duplicate=False. + for child_name, submod in mod._modules.items(): + tx.call_function( + tx.output.register_attr_or_module( + submod, + self.module_key, + child_name, + source=NNModuleSource(AttrSource(self.source, child_name)), # type: ignore[arg-type] + ), + [arg], + {}, + ) + arg = tx.pop() + return arg + + if is_lazy: + # The module type will change after it is called + if mod.cls_to_become is not None: + self.module_type = mod.cls_to_become # type: ignore[assignment] + + # The pre-hook runs to initialize the module shapes, then deletes itself. After this, + # the module is more or less not lazy and can be treated as a normal module regardless of + # is_allowed or other variations. + initialize_lazy_module(tx, mod, args, kwargs) + + # If we are tracing the higher order op, we want Dynamo to step + # inside the module call so that Dynamo can see the underlying + # parameters and buffers and raise them as inputs to the graph. + # + # NB: torch.nn.utils.parametrize changes the class type of a + # parametrized module such that its __module__ points to + # "torch.nn.utils.parametrize". + if ( + tx.output.is_root_tracer() + and mod.__module__.startswith(("torch.nn.", "torch.ao.")) + and mod.__module__ != "torch.nn.utils.parametrize" + ): + if nnmodule_has_hooks( + mod, check_forward_hooks=True, check_backward_hooks=True + ): + # End of fn, this bubbles up and restarts tracing. + self.convert_to_unspecialized(tx) + + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_module", + self.module_key, + *proxy_args_kwargs(args, kwargs), + ), + ) + else: + if isinstance(mod, torch.fx.GraphModule): + # TODO: do we want to support __call__ for GM's? + # If so at least some changes are needed, we don't allow inlining + # the call_wrapped currently, and maybe other issues too + fn = mod.forward + fn_source = AttrSource(self.source, "forward") + else: + fn = mod._call_impl + fn_source = AttrSource(self.source, "_call_impl") + if istype(fn, types.MethodType): + fn = fn.__func__ + fn_source = AttrSource(fn_source, "__func__") + args = [self] + list(args) + else: + if not istype(fn, types.FunctionType): + raise AssertionError(f"Expected FunctionType, got {type(fn)}") + return tx.inline_user_function_return( + variables.UserFunctionVariable(fn, source=fn_source), + args, + kwargs, + allow_nested_graph_breaks=True, + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: "VariableTracker", + ) -> "VariableTracker": + # nn.Module containers (ModuleList/Dict/Sequential/ParameterDict/ParameterList) + # These are Python-level __getitem__, not CPython C slots. + from .lists import SliceVariable + from .tensor import SymNodeVariable + + module = tx.output.get_submodule(self.module_key) + + builtin_supported = ( + torch.nn.ModuleDict.__getitem__, + torch.nn.ModuleList.__getitem__, + torch.nn.ParameterDict.__getitem__, + torch.nn.ParameterList.__getitem__, + torch.nn.Sequential.__getitem__, + ) + # pyrefly: ignore[missing-attribute] + if type(module).__getitem__ not in builtin_supported: + if not ( + key.is_python_constant() + and isinstance(key.as_python_constant(), (str, int)) + ): + unimplemented( + gb_type="Invalid or non-const argument in nn.Module __getitem__", + context=f"mp_subscript_impl: {self} {key}", + explanation="Dynamo does not support calling " + f"method `__getitem__` of ``nn.Module`` {module} with a non-constant or non-(str, int) key.", + hints=["Use constant arguments of type str or int for __getitem__"], + ) + fn = module.__getitem__.__func__ # pyrefly: ignore[missing-attribute] + + if not isinstance(fn, types.FunctionType): + raise AssertionError(f"Expected FunctionType, got {type(fn)}") + + src = AttrSource(AttrSource(self.source, "__getitem__"), "__func__") # type: ignore[arg-type] + return tx.inline_user_function_return( + variables.UserFunctionVariable(fn, source=src), + [self, key], + {}, + allow_nested_graph_breaks=True, + ) + + if isinstance(key, SliceVariable): + # TODO(anijain2305,export-team) - Remove this if condition when inlining of inbuilt nn modules is + # enabled for export. + if tx.output.export: + result = [] + keys = list(range(len(module)))[key.as_python_constant()] # type: ignore[arg-type] + for idx, submod in enumerate(module[key.as_python_constant()]): # type: ignore[arg-type] + k = keys[idx] + src = NNModuleSource(GetItemSource(self.source, k)) + result.append( + tx.output.register_attr_or_module( + submod, + k, + source=src, + ) + ) + + new_module = module[key.as_python_constant()] # type: ignore[index] + new_module_variable = tx.output.register_attr_or_module( + new_module, + f"{self}.__getitem__(slice)", + source=NNModuleSource( + GetItemSource(self.source, key.as_python_constant()) + ), + ) + return new_module_variable + else: + # slice on nn module results in a creation of new module instance, so we need to make it sourceless. + # Convert to unspecialized so that UnspecializedNNModule variable can take care of it. + self.convert_to_unspecialized(tx) + + key_value = 0 + if isinstance(key, SymNodeVariable): + key_value = key.evaluate_expr(tx.output) + elif key.is_python_constant(): + key_value = key.as_python_constant() + else: + unimplemented( + gb_type="Unsupported key type for nn.Module.__getitem__", + context=f"mp_subscript_impl: {self} {key}", + explanation="Dynamo does not support getitem on " + "`nn.Module` with non-constant key.", + hints=[], + ) + + submod = module[key_value] # type: ignore[index] + return tx.output.register_attr_or_module( + submod, + self.module_key, + key_value, + source=NNModuleSource(GetItemSource(self.source, key_value)), + ) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from . import ListIteratorVariable + + return ListIteratorVariable( + self.unpack_var_sequence(tx), mutation_type=ValueMutationNew() + ) + + @staticmethod + def _gen_source(source: Source, name: str) -> Source: + name_split = name.split(".") + if name_split[0] == "": + return source + while len(name_split) > 0: + x = name_split.pop(0) + source = AttrSource(source, x) + return source + + def _generic_call_method_helper( + self, tx: "InstructionTranslatorBase", name: str, args: Any, kwargs: Any + ) -> VariableTracker: + # Put a `call_method` node in the FX graph, with the nn.Module as the + # first arg. + module = tx.output.get_submodule(self.module_key) + mod_proxy = tx.output.create_proxy("get_attr", self.module_key, (), {}) + set_example_value(mod_proxy.node, module) + proxy_args, proxy_kwargs = proxy_args_kwargs(args, kwargs) + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_method", name, args=(mod_proxy, *proxy_args), kwargs=proxy_kwargs + ), + ) + + def _assert_all_args_kwargs_const( + self, tx: "InstructionTranslatorBase", name: str, args: Any, kwargs: Any + ) -> None: + if not all( + x.is_python_constant() for x in itertools.chain(args, kwargs.values()) + ): + module = tx.output.get_submodule(self.module_key) + unimplemented( + gb_type="non-const argument in nn.Module method", + context=f"call_method: {self} {name} {args} {kwargs}", + explanation="Dynamo does not support calling " + f"method `{name}` of ``nn.Module`` {module} with non-constant arguments.", + hints=[], + ) + + def _get_kwargs( + self, + tx: "InstructionTranslatorBase", + name: str, + args: Any, + kwargs: Any, + *names: str, + ) -> dict[str, Any]: + self._assert_all_args_kwargs_const(tx, name, args, kwargs) + module = tx.output.get_submodule(self.module_key) + fn = getattr(module, name) + bound_args = inspect.signature(fn).bind( + *([x.as_python_constant() for x in args]), + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + bound_args.apply_defaults() + bound_args = bound_args.arguments + return {k: bound_args[k] for k in names} + + def _wrap_values( + self, tx: "InstructionTranslatorBase", items: Iterable[tuple[Any, Any]] + ) -> "variables.ListIteratorVariable": + result: list[VariableTracker] = [] + for name, submod in items: + result.append( + tx.output.register_attr_or_module( + submod, + self.module_key, + name, + source=NNModuleSource(self._gen_source(self.source, name)), + ) + ) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def _named_embed( + self, tx: "InstructionTranslatorBase", name: str, obj: Any + ) -> "variables.TupleVariable": + return variables.TupleVariable( + [ + VariableTracker.build(tx, name), + tx.output.register_attr_or_module( + obj, + self.module_key, + name, + source=NNModuleSource(self._gen_source(self.source, name)), + ), + ] + ) + + def _call_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Example: `self.layer.__call__(x)`. Dynamo inlines `__call__`, + # including hooks. + return self.call_function(tx, args, kwargs) + + def forward( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Example: `self.layer.forward(x)`. Dynamo puts a `call_method` node in + # the FX graph and does not trigger hooks. + module = tx.output.get_submodule(self.module_key) + with record_nn_module_stack( + self.module_key, self.get_nn_module_stack_source(), tx, module + ): + return self._generic_call_method_helper(tx, "forward", args, kwargs) + + def _get_item_by_idx( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + if not args[1].is_python_constant(): + raise_type_error( + tx, + f"``nn.Module`` {module}'s call method _get_item_by_idx requires a constant index argument", + ) + if not isinstance(args[0], variables.TupleVariable): + raise_type_error( + tx, + f"``nn.Module`` {module}'s call method _get_item_by_idx requires a tuple as first argument", + ) + mod_var = args[0].items[args[1].as_python_constant()] + if isinstance(mod_var, UnspecializedNNModuleVariable): + return mod_var + key = mod_var.module_key + submod = tx.output.get_submodule(key) + return tx.output.register_attr_or_module( + submod, key, key, source=NNModuleSource(GetItemSource(self.source, key)) + ) + + def named_children( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_modules")) + if args or kwargs: + raise_args_mismatch( + tx, + "named_children", + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + result: list[VariableTracker] = [] + for n, submod in module.named_children(): + result.append(self._named_embed(tx, n, submod)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def named_parameters( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_parameters")) + kw = self._get_kwargs(tx, "named_parameters", args, kwargs, "prefix", "recurse") + result: list[VariableTracker] = [] + for n, param in module.named_parameters(**kw): + result.append(self._named_embed(tx, n, param)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def named_buffers( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_buffers")) + kw = self._get_kwargs( + tx, "named_buffers", args, kwargs, "prefix", "recurse", "remove_duplicate" + ) + result: list[VariableTracker] = [] + for n, buffer in module.named_buffers(**kw): + result.append(self._named_embed(tx, n, buffer)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def named_modules( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_modules")) + kw = self._get_kwargs( + tx, "named_modules", args, kwargs, "memo", "prefix", "remove_duplicate" + ) + result: list[VariableTracker] = [] + for n, submod in module.named_modules(**kw): + result.append(self._named_embed(tx, n, submod)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def children( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_modules")) + if args or kwargs: + raise_args_mismatch( + tx, + "children", + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return self._wrap_values(tx, module.named_children()) + + def modules( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_modules")) + return self._wrap_values(tx, module.named_modules()) + + def parameters( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_parameters")) + kw = self._get_kwargs(tx, "parameters", args, kwargs, "recurse") + return self._wrap_values(tx, module.named_parameters(**kw)) + + def buffers( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_buffers")) + kw = self._get_kwargs(tx, "buffers", args, kwargs, "recurse") + return self._wrap_values(tx, module.named_buffers(**kw)) + + def keys( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + if args or kwargs: + raise_args_mismatch( + tx, + "keys", + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + result: list[VariableTracker] = [] + # pyrefly: ignore[not-iterable] + for tmp in module: + result.append(VariableTracker.build(tx, tmp)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def values( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + if args or kwargs: + raise_args_mismatch( + tx, + "values", + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return self._wrap_values(tx, module.items()) # type: ignore[operator] + + def items( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + if args or kwargs: + raise_args_mismatch( + tx, + "items", + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + result: list[VariableTracker] = [] + for n, submod in module.items(): # type: ignore[operator] + result.append(self._named_embed(tx, n, submod)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + tp_methods = { + "_call_impl": Method(_call_impl), + "_wrapped_call_impl": Method(_call_impl), + "forward": Method(forward), + "_get_item_by_idx": Method(_get_item_by_idx), + "named_children": Method(named_children), + "named_parameters": Method(named_parameters), + "named_buffers": Method(named_buffers), + "named_modules": Method(named_modules), + "children": Method(children), + "modules": Method(modules), + "parameters": Method(parameters), + "buffers": Method(buffers), + "keys": Method(keys), + "values": Method(values), + "items": Method(items), + } + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + constant: bool = False, + ) -> VariableTracker: + from .constant import ConstantVariable + + module = tx.output.get_submodule(self.module_key) + + if name == "_check_input_dim" and trace_rules.is_torch_inline_allowed( + inspect.getfile(module.__class__._check_input_dim) # type: ignore[union-attr] + ): + return ConstantVariable.create(True) + + if constant: + fn = getattr(module, name) + const_name = f"{module.__class__.__name__}_{name}_result" + return invoke_and_store_as_constant(tx, fn, const_name, args, kwargs) + + if name == "__iter__": + return self.tp_iter_impl(tx) + elif ( + name == "__contains__" + and isinstance(module, (torch.nn.ModuleDict, torch.nn.ParameterDict)) + and args + and args[0].is_python_constant() + ): + return VariableTracker.build( + tx, args[0].as_python_constant() in module._modules + ) + elif ( + name == "_get_abs_string_index" + or ( + isinstance(module, torch.nn.modules.conv._ConvNd) + and name == "_conv_forward" + ) + or ( + isinstance(module, torch.nn.modules.conv._ConvTransposeNd) + and name == "_output_padding" + ) + ): + # Inline the function + fn = getattr(module, name).__func__ + fn_source = AttrSource(AttrSource(self.source, name), "__func__") # type: ignore[arg-type] + return tx.inline_user_function_return( + variables.UserFunctionVariable(fn, source=fn_source), + [self] + list(args), + kwargs, + ) + # A loose heuristic, but seems to be generally good before we drop into + # the manual handling of inputs. Skip tp_methods names so they reach the + # declarative dispatch in the base call_method. + elif ( + name not in self.tp_methods + and name in module.__class__.__dict__ + and callable(module.__class__.__dict__[name]) + and all(x.is_tensor() for x in itertools.chain(args, kwargs.values())) + ): + return self._generic_call_method_helper(tx, name, args, kwargs) + else: + return super().call_method(tx, name, list(args), kwargs) + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + """Sequence length for container modules (e.g., nn.Sequential).""" + module = tx.output.get_submodule(self.module_key) + return VariableTracker.build(tx, len(module)) # type: ignore[arg-type] + + +class UnspecializedNNModuleVariable(UserDefinedObjectVariable): + _nonvar_fields = { + "value_type", + "is_state_mutated", + "nn_module_stack_source", + *UserDefinedObjectVariable._nonvar_fields, + } + + """ + The above class will specialize on the id() of a module and place + parameters on the torch.fx.GraphModule. Giving one graph per + module instance. This version treats nn.Modules() like other user + defined objects and will pass parameters into the FX graph as inputs. + Giving one graph per module class. + """ + + def __init__(self, value: torch.nn.Module, **kwargs: Any) -> None: + if "value_type" in kwargs: + lazy_value_to_become = getattr(kwargs["value_type"], "cls_to_become", None) + if type(value) is lazy_value_to_become: + # We may have cloned a variabletracker for a LazyModule earlier (e.g. tracking side-effects) + # and then later we called and mutated the LazyModule into a MaterializedModule. + # We do not do the mutation upon first seeing a LazyModule since we preserve eager semantics to only + # mutate upon first call, but this requires we update multiple copies of the VariableTracker post-mutation. + kwargs["value_type"] = type(value) + + super().__init__(value=value, **kwargs) + self.is_state_mutated = False + # nn_module_stack_source is used to ensure BC for nn_module_stack. + # Downstream users prefer mod.linear instead of mod._modules['linear'] + # as the module stack. When Dynamo inlines the __getattr__ method, we + # cannot use self.source for nn_module_stack because it will be similar + # to mod._modules['linear']. In these cases, we set the + # nn_module_stack_source appropriately to resemble mod.linear. + self.nn_module_stack_source = self.source + + def _wrap_source(self, attr_source: Source) -> Source: + # the vt is already wrapped with UnspecializedNNModuleSource + return attr_source + + def get_nn_module_stack_source(self) -> Source: + res = self.nn_module_stack_source or self.source + if not res: + raise AssertionError("nn_module_stack_source must not be None") + return res + + def set_nn_module_stack_source(self, source: Source) -> None: + self.nn_module_stack_source = source + + @staticmethod + @functools.cache + def _nn_module_method_ids() -> set[int]: + # Allow __setattr__ to fall through to base class handler + supported = { + torch.nn.Module.__setattr__, + torch.nn.Module.__init__, + torch.nn.Module.__delattr__, + } + return { + id(x.__code__) + for x in torch.nn.Module.__dict__.values() + if hasattr(x, "__code__") and x not in supported + } + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + try: + fn = inspect.getattr_static(self.value_type, "__iter__") + except AttributeError as e: + raise NotImplementedError from e + + if fn in ( + torch.nn.ModuleList.__iter__, + torch.nn.ParameterList.__iter__, + torch.nn.Sequential.__iter__, + ): + # The program can mutate the nn module object but the saved `value` + # will not reflect the mutations. So, trace through the `__iter__` + # function to reflect any tracked mutations. + return tx.inline_user_function_return( + VariableTracker.build(tx, fn), + [ + self, + ], + {}, + ).unpack_var_sequence(tx) + + return super().unpack_var_sequence(tx) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + mod = self.value + # see comment on lazy module handling in NNModuleVariable.call_function for context + if is_lazy_module(mod): # type: ignore[arg-type] + if mod.cls_to_become is not None: # type: ignore[attr-defined] + self.value_type = mod.cls_to_become # type: ignore[attr-defined,assignment] + initialize_lazy_module(tx, mod, args, kwargs) # type: ignore[arg-type] + + if not isinstance(mod, torch.fx.GraphModule): + name = "__call__" + fn = getattr(self.value_type, name) + else: + name = "_call_impl" + fn = getattr(self.value_type, name) + + # Check if we can short circuit nn.Module._call_impl to the forward + # method. NB - This is done to reduce the compile time of Dynamo. + if ( + istype(mod.__call__, types.MethodType) # type: ignore[operator] + and istype(mod._call_impl, types.MethodType) # type: ignore[attr-defined] + and mod.__call__.__func__ is unpatched_nn_module_call # type: ignore[operator] + and mod._call_impl.__func__ is unpatched_nn_module_call_impl # type: ignore[attr-defined] + # Consult pending STORE_ATTR side effects too. During tracing the + # patched forward may not be visible in mod.__dict__ yet. + and not self.has_key_in_generic_dict(tx, "forward") + ): + forward_method = inspect.getattr_static(mod, "forward") + if isinstance(forward_method, types.FunctionType): + globals_vt = tx.nn_modules_globals_vt + + def _hooks_dict_len(obj: VariableTracker, attr: str) -> int: + vt = obj.tp_getattro_impl(tx, attr) + vt = vt.realize() if hasattr(vt, "realize") else vt + return vt.len() # type: ignore[union-attr] + + has_hooks = any( + _hooks_dict_len(self, attr) + for attr in ( + "_backward_hooks", + "_backward_pre_hooks", + "_forward_hooks", + "_forward_hooks_with_kwargs", + "_forward_pre_hooks", + "_forward_pre_hooks_with_kwargs", + ) + ) or any( + _hooks_dict_len(globals_vt, attr) + for attr in ( + "_global_backward_pre_hooks", + "_global_backward_hooks", + "_global_forward_hooks", + "_global_forward_pre_hooks", + ) + ) + + if not has_hooks: + name = "forward" + fn = self.value_type.forward # type: ignore[attr-defined] + + if self.source: + source = self.get_source_by_walking_mro(tx, name) + else: + source = None + + guard_to_detect_forward_monkeypatching(self.source, mod) # type: ignore[arg-type] + + ctx = ( + record_nn_module_stack( + str(id(mod)), + self.get_nn_module_stack_source(), + tx, + mod, # type: ignore[arg-type] + ) + if self.source + else nullcontext() + ) + with ctx: + if not isinstance(fn, (types.FunctionType, torch.jit.ScriptFunction)): + fn_vt = VariableTracker.build(tx, fn, source=source, realize=True) + return fn_vt.call_function(tx, [self] + list(args), kwargs) + else: + # Ideally we would have just used VariableTracker.build(tx, fn, + # source=source) but that introduces guard on the + # `forward.__code__` object. Given that we already guard on the + # forward not present in generic dict, we don't need this guard. + return variables.UserFunctionVariable(fn, source=source).call_function( + tx, [self] + list(args), kwargs + ) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name in ["_call_impl", "_wrapped_call_impl"]: + fn = getattr(self.value_type, name) + if self.source: + source = self.get_source_by_walking_mro(tx, name) + else: + source = None + + fn_vt = VariableTracker.build(tx, fn, source=source, realize=True) + return fn_vt.call_function(tx, [self] + list(args), kwargs) + + if not self.has_key_in_generic_dict(tx, name): + try: + method = inspect.getattr_static(type(self.value), name) + except AttributeError: + method = None + + if isinstance(method, staticmethod): + source = AttrSource( + self.get_source_by_walking_mro(tx, name), "__func__" + ) + fn_vt = VariableTracker.build( + tx, method.__func__, source=source, realize=True + ) + return fn_vt.call_function(tx, args, kwargs) + + if ( + hasattr(method, "__code__") + and id(method.__code__) in self._nn_module_method_ids() + ): + unimplemented( + gb_type="UnspecializedNNModuleVariable missing method", + context=f"call_method: {self} {name} {args} {kwargs}", + explanation=f"Dynamo does not support tracing method {name} of nn.Module {self.value}", + hints=[ + "Dynamo does not really define unspecialized nn.Module very well.", + *graph_break_hints.DIFFICULT, + ], + ) + + # "_parameters" in self.value.__dict__ checks that module is initialized + if name == "__setattr__" and "_parameters" in self.value.__dict__: + # Record if mutations happens on parameters/buffers/modules. The + # mutations on these are not tracked by base class + # UserDefinedObject vt. This will be used later to graph break + # on seeing a parameters() and family calls. + # TODO(anijain2305) - This might not be needed if we let Dynamo + # inline both getattr and setattr. In that case, it should see + # the lowest level dicts - _parameters and family and + # automatically track mutations on those. Investigate if that + # can be done. + attr_name = args[0].as_python_constant() + value = args[1] + + # This is reverse engineered by looking at nn module __setattr__ + # logic. + if ( + value.is_tensor() and value.python_type() is torch.nn.Parameter + ) or attr_name in self.value.__dict__["_parameters"]: + # Handle parameters + self.is_state_mutated = True + elif attr_name in self.value.__dict__["_buffers"]: + # Handle buffers + self.is_state_mutated = True + elif ( + isinstance( + value, + ( + variables.NNModuleVariable, + variables.UnspecializedNNModuleVariable, + ), + ) + or attr_name in self.value.__dict__["_modules"] + ): + # Handle submodules + self.is_state_mutated = True + + if ( + method is torch.nn.Module.__setattr__ + and isinstance(args[1], variables.DeletedVariable) + ) or method is torch.nn.Module.__delattr__: + # Trace through __delattr__ to track mutations on the module + # members like `_modules``. + fn_vt = VariableTracker.build(tx, torch.nn.Module.__delattr__) + return fn_vt.call_function(tx, [self, args[0]], kwargs) + + return super().call_method(tx, name, list(args), kwargs) + + def getattr_helper( + self, tx: "InstructionTranslatorBase", field: str, name_vt: VariableTracker + ) -> VariableTracker | None: + dict_vt = self.tp_getattro_impl(tx, field) + if isinstance(dict_vt, variables.UserDefinedDictVariable): + dict_vt = dict_vt._base_vt + if isinstance(dict_vt, variables.ConstDictVariable): + return dict_vt.maybe_getitem_const(name_vt) + return None + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if ( + tx.output.side_effects.is_attribute_mutation(self) + and name + in ( + "named_parameters", + "parameters", + "named_buffers", + "buffers", + "named_modules", + "modules", + ) + and self.is_state_mutated + and tx.output.side_effects.has_pending_mutation(self) + ): + unimplemented( + gb_type="getattr() on nn.Module with pending mutation", + context=f"getattr({self}, {name})", + explanation="Intentionally graph breaking on getattr() on a nn.Module " + "with a pending mutation", + hints=[], + ) + + # Allow skipping of empty hook dict guards on inbuilt nn modules + if name in ( + "_backward_hooks", + "_backward_pre_hooks", + "_forward_hooks_with_kwargs", + "_forward_hooks", + "_forward_pre_hooks_with_kwargs", + "_forward_pre_hooks", + ): + # For empty hooks, make an EMPTY_NN_MODULE_HOOKS_DICT. This allows us to control the installation of empty + # hooks guard via skip_nnmodule_hook_guards + if not tx.output.side_effects.has_pending_mutation_of_attr(self, name): + hooks_dict = getattr(self.value, name) + if isinstance(hooks_dict, dict) and len(hooks_dict) == 0: + hooks_source = ( + AttrSource(self.source, name) if self.source else None + ) + if hooks_source: + install_guard( + hooks_source.make_guard( + GuardBuilder.EMPTY_NN_MODULE_HOOKS_DICT + ) + ) + hooks_vt_cls = ( + variables.OrderedDictVariable + if isinstance(hooks_dict, collections.OrderedDict) + else variables.ConstDictVariable + ) + return hooks_vt_cls({}, source=hooks_source) + + # For non-empty hook dicts, one way is to just fallback to VariableTracker.build() and create a ConstDictVariable. + # However, ConstDictVariable guards on keys. This can cause recompiles when the same hook is installed for + # different nn module instances, because the key keeps changing (look more into RemovableHandle to understand why + # key changes - also related https://github.com/pytorch/pytorch/issues/125836). Here, we carefully craft a + # NNModuleHooksDictVariable (a subclass of ConstDictVariable) to avoid any guard on the keys. + if ( + self.source + and name + in ( + "_forward_pre_hooks_with_kwargs", + "_forward_pre_hooks", + "_forward_hooks_with_kwargs", + "_forward_hooks", + ) + and not tx.output.side_effects.has_pending_mutation_of_attr(self, name) + ): + hooks_dict = getattr(self.value, name) + hooks_dict_source = AttrSource(self.source, name) + install_guard(hooks_dict_source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + tx.output.guard_on_key_order.add(hooks_dict_source) + + def build_key_value( + i: int, k: Any, v: Any + ) -> tuple[VariableTracker, VariableTracker]: + # Make key sourceless to avoid any guard on it + key = VariableTracker.build(tx, k) + + # Instead of using dict[key] to access the value, use a dict[dict.keys()[index]] to access the + # value. This removes the reliance on the actual key value. + source_key = ConstDictKeySource(hooks_dict_source, i) + source_value = DictGetItemSource(hooks_dict_source, source_key) + value = LazyVariableTracker.create(v, source_value, tx=tx) + return key, value + + result = dict( + build_key_value(i, k, v) + for i, k, v in enumerate_items_with_dict_position(hooks_dict) + ) + + return variables.NNModuleHooksDictVariable(result, source=hooks_dict_source) + return super().tp_getattro_impl(tx, name) + + def manually_trace_nn_module_getattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + """ + Dynamo tracing of nn.Module __getattr__ can be expensive if the model + has deep submodule hierarchy. Since the __getattr__ is stable, we can + directly look into the underlying datastructures. This saves a lot of + compilation time. + """ + from .builder import SourcelessBuilder + + name_vt = SourcelessBuilder.create(tx, name) + out = self.getattr_helper(tx, "_parameters", name_vt) + if out is None: + out = self.getattr_helper(tx, "_modules", name_vt) + if out is None: + out = self.getattr_helper(tx, "_buffers", name_vt) + if out is None: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object has no attribute '{name}'" + ], + ) + if out is None: + raise AssertionError( + f"manually_trace_nn_module_getattr failed to find attribute '{name}'" + ) + return out + + +class UnspecializedBuiltinNNModuleVariable(UnspecializedNNModuleVariable): + """ + Differentiates between builtin nn modules (e.g. torch.nn.Linear) and user defined nn modules. + """ + + def _wrap_source(self, attr_source: Source) -> Source: + # vt is already wrapped with the UnspecializedBuiltinNNModuleSource + return attr_source + + +class FSDPManagedNNModuleVariable(UnspecializedNNModuleVariable): + """ + Tracing behavior: trace into submodules and treat them as Unspecialized, do not + register parameters to the top-level, treat them as function inputs. + + Guards behavior: if 'skip_fsdp_guards', many guards that would be installed + by a vanilla UnspecializedNNModuleVariable are simply dropped, on the basis + that a user wrapping their model in FSDP(model) is already opting into a + requirement to not modify internal model state, which would already break FSDP without + compilation. + """ + + def __init__(self, value: torch.nn.Module, **kwargs: Any) -> None: + source = kwargs.get("source") + if source is None: + raise AssertionError( + "FSDPManagedNNModule depends on having an accurate source to control guarding." + ) + + super().__init__(value=value, **kwargs) + self.source = source + + def _wrap_source(self, attr_source: Any) -> Any: + if not isinstance( + attr_source, (FSDPNNModuleSource, UnspecializedNNModuleSource) + ): + if torch._dynamo.config.skip_fsdp_guards: + return FSDPNNModuleSource(attr_source) + else: + return UnspecializedNNModuleSource(attr_source) + return attr_source diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/object_protocol.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/object_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..e9cde39513351a6959a614bf1ebee5a85b70324a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/object_protocol.py @@ -0,0 +1,2311 @@ +""" +Dynamo implementations of CPython's PyObject_* default slot algorithms. + +Analogous to CPython's Objects/object.c, this module holds the general +dispatch machinery that is independent of any specific type. +Per-type hook implementations (nb_bool_impl, tp_richcompare_impl, tp_getattro_impl, +etc.) live in their respective VT files. +""" + +import abc +import collections +import enum +import sys +import types +import typing +from functools import lru_cache, partial +from typing import NoReturn, TYPE_CHECKING + +import torch +from torch._C._dynamo import ( + get_type_slots, + has_slot, + PyMappingSlots, + PyNumberSlots, + PySequenceSlots, + PyTypeSlots, +) + +from .. import graph_break_hints, polyfills, variables +from ..exc import ( + handle_observed_exception, + ObservedTypeError, + raise_observed_exception, + raise_type_error, + UnhandledDescriptorError, + unimplemented, +) +from ..source import AttrSource, Source +from ..utils import istype +from .base import ( + AsPythonConstantNotImplementedError, + AttrMutationKind, + maybe_get_python_type, + NO_SUCH_SUBOBJ, + VariableTracker, +) +from .constant import ConstantVariable + + +if TYPE_CHECKING: + from ..symbolic_convert import InstructionTranslatorBase + + +def vt_identity_compare( + left: VariableTracker, + right: VariableTracker, +) -> "VariableTracker | None": + """Try to determine Python identity (left is right) at trace time. + + Returns ConstantVariable(True/False) if determinable, else None. + Mirrors the logic in BuiltinVariable's handle_is handler. + """ + if left is right: + return ConstantVariable.create(True) + + left_val = left.get_real_python_backed_value() + right_val = right.get_real_python_backed_value() + left_known = left_val is not NO_SUCH_SUBOBJ + right_known = right_val is not NO_SUCH_SUBOBJ + + if left_known and right_known: + return ( + ConstantVariable.create(True) + if left_val is right_val + else ConstantVariable.create(False) + ) + + # One side has a concrete backing object, the other doesn't — they can't + # be the same object. + if left_known != right_known: + return ConstantVariable.create(False) + + # Objects created during tracing: VT identity = Python identity. + from .dicts import ConstDictVariable + from .lists import ListVariable + from .misc import TracebackVariable + from .sets import SetVariable + + if isinstance( + left, (ConstDictVariable, ListVariable, SetVariable, TracebackVariable) + ): + return ConstantVariable.create(False) + + # Different Python types can never be the same object. + try: + if left.python_type() is not right.python_type(): + return ConstantVariable.create(False) + except NotImplementedError: + pass + + # Different exception types are never identical. + if ( + istype(left, variables.ExceptionVariable) + and istype(right, variables.ExceptionVariable) + and left.exc_type is not right.exc_type # type: ignore[attr-defined] + ): + return ConstantVariable.create(False) + + return None + + +def binop_type_error( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + op_symbol: str, +) -> NoReturn: + raise_type_error( + tx, + f"unsupported operand type(s) for {op_symbol}: '{v.python_type_name()}' and '{w.python_type_name()}'", + ) + + +@lru_cache(maxsize=256) +def _get_cached_slots(obj_type: type) -> tuple[int, int, int, int]: + """Get all type slots for a type (cached).""" + return get_type_slots(obj_type) + + +def type_implements_sq_slot(obj_type: type, slot: int) -> bool: + """Check whether obj_type implements the given sq slot.""" + seq_slots, _, _, _ = _get_cached_slots(obj_type) + return has_slot(seq_slots, slot) + + +def type_implements_mp_slot(obj_type: type, slot: int) -> bool: + """Check whether obj_type implements the given mp slot.""" + _, map_slots, _, _ = _get_cached_slots(obj_type) + return has_slot(map_slots, slot) + + +# PySequenceSlots +type_implements_sq_item = partial(type_implements_sq_slot, slot=PySequenceSlots.SQ_ITEM) +type_implements_sq_length = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_LENGTH +) +type_implements_sq_concat = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_CONCAT +) +type_implements_sq_inplace_concat = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_INPLACE_CONCAT +) +type_implements_sq_contains = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_CONTAINS +) +type_implements_sq_ass_item = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_ASS_ITEM +) +type_implements_sq_repeat = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_REPEAT +) + +type_implements_sq_inplace_repeat = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_INPLACE_REPEAT +) + +# PyMappingSlots +type_implements_mp_length = partial( + type_implements_mp_slot, slot=PyMappingSlots.MP_LENGTH +) +type_implements_mp_subscript = partial( + type_implements_mp_slot, slot=PyMappingSlots.MP_SUBSCRIPT +) +type_implements_mp_ass_subscript = partial( + type_implements_mp_slot, slot=PyMappingSlots.MP_ASS_SUBSCRIPT +) +type_implements_mp_length = partial( + type_implements_mp_slot, slot=PyMappingSlots.MP_LENGTH +) + + +def type_implements_nb_slot(obj_type: type, slot: int) -> bool: + """Check whether obj_type implements the nb slot.""" + _, _, number_slots, _ = _get_cached_slots(obj_type) + return has_slot(number_slots, slot) + + +type_implements_nb_add = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_ADD) +type_implements_nb_subtract = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_SUBTRACT +) +type_implements_nb_multiply = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_MULTIPLY +) +type_implements_nb_remainder = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_REMAINDER +) +type_implements_nb_power = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_POWER) +type_implements_nb_negative = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_NEGATIVE +) +type_implements_nb_positive = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_POSITIVE +) +type_implements_nb_absolute = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_ABSOLUTE +) +type_implements_nb_bool = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_BOOL) +type_implements_nb_invert = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INVERT +) +type_implements_nb_lshift = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_LSHIFT +) +type_implements_nb_rshift = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_RSHIFT +) +type_implements_nb_and = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_AND) +type_implements_nb_xor = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_XOR) +type_implements_nb_or = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_OR) +type_implements_nb_int = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_INT) +type_implements_nb_float = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_FLOAT) +type_implements_nb_inplace_add = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_ADD +) +type_implements_nb_inplace_subtract = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_SUBTRACT +) +type_implements_nb_inplace_multiply = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_MULTIPLY +) +type_implements_nb_inplace_remainder = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_REMAINDER +) +type_implements_nb_inplace_power = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_POWER +) +type_implements_nb_inplace_lshift = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_LSHIFT +) +type_implements_nb_inplace_rshift = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_RSHIFT +) +type_implements_nb_inplace_and = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_AND +) +type_implements_nb_inplace_xor = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_XOR +) +type_implements_nb_inplace_or = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_OR +) +type_implements_nb_floor_divide = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_FLOOR_DIVIDE +) +type_implements_nb_true_divide = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_TRUE_DIVIDE +) +type_implements_nb_inplace_floor_divide = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_FLOOR_DIVIDE +) +type_implements_nb_inplace_true_divide = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_TRUE_DIVIDE +) +type_implements_nb_index = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_INDEX) +type_implements_nb_matrix_multiply = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_MATRIX_MULTIPLY +) +type_implements_nb_inplace_matrix_multiply = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_MATRIX_MULTIPLY +) + + +def type_implements_tp_iter(obj_type: type) -> bool: + _, _, _, type_slot = _get_cached_slots(obj_type) + return has_slot(type_slot, PyTypeSlots.TP_ITER) + + +def type_implements_tp_iternext(obj_type: type) -> bool: + _, _, _, type_slot = _get_cached_slots(obj_type) + return has_slot(type_slot, PyTypeSlots.TP_ITERNEXT) + + +def type_implements_tp_repr(obj_type: type) -> bool: + """Check whether obj_type implements the tp_repr slot.""" + _, _, _, type_slot = _get_cached_slots(obj_type) + return has_slot(type_slot, PyTypeSlots.TP_REPR) + + +def type_implements_tp_str(obj_type: type) -> bool: + """Check whether obj_type implements the tp_str slot.""" + _, _, _, type_slot = _get_cached_slots(obj_type) + return has_slot(type_slot, PyTypeSlots.TP_STR) + + +def type_implements_tp_call(obj_type: type) -> bool: + """Check whether obj_type implements the tp_call slot.""" + _, _, _, type_slot = _get_cached_slots(obj_type) + return has_slot(type_slot, PyTypeSlots.TP_CALL) + + +def pyiter_check(obj_type: type) -> bool: + # ref: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L2891-L2897 + # CPython checks if tp_iternext != _PyObject_NextNotImplemented + # Dynamo only sets the bit if __next__ is actually defined + return type_implements_tp_iternext(obj_type) + + +def pysequence_check(obj_type: type) -> bool: + """Implements PySequence_Check semantics for VariableTracker objects.""" + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1714-L1721 + if issubclass(obj_type, dict): + return False + return type_implements_sq_item(obj_type) + + +def pyindex_check(obj_type: type) -> bool: + """Implements _PyIndex_Check semantics for VariableTracker objects.""" + # ref: https://github.com/python/cpython/blob/3.13/Include/internal/pycore_abstract.h#L11-L17 + return type_implements_nb_index(obj_type) + + +def pycallable_check(obj_type: type) -> bool: + """Implements PyCallable_Check: type(x)->tp_call != NULL. + + obj_type is the object's Python type (Py_TYPE(x)); a non-NULL tp_call + slot on it means instances are callable. + + ref: https://github.com/python/cpython/blob/v3.13.0/Objects/call.c#L52-L57 + """ + return type_implements_tp_call(obj_type) + + +def pyiter_send( + tx: "InstructionTranslatorBase", iter_: VariableTracker, arg: VariableTracker +) -> VariableTracker: + """Implements PyIter_Send semantics for VariableTracker objects. + + ref: https://github.com/python/cpython/blob/51b511d7299f91a458e40d1ea997bd7e6cd3deef/Objects/abstract.c#L2930-L2953 + """ + + tp_iternext = iter_.tp_iternext + if arg.is_constant_none() and tp_iternext is not None: + return iter_.tp_iternext_impl(tx) + else: + return iter_.call_method(tx, "send", [arg], {}) + + +def pymapping_size( + tx: "InstructionTranslatorBase", obj: "VariableTracker" +) -> "VariableTracker": + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/abstract.c#L2308-L2330 + if obj.tp_as_mapping.mp_length: + return obj.mp_length_impl(tx) + + if obj.tp_as_sequence.sq_length is not None: + raise_type_error(tx, f"{obj.python_type_name()} is not a mapping") + + raise_type_error(tx, f"object of type {obj.python_type_name()} has no len()") + + +def generic_size( + tx: "InstructionTranslatorBase", obj: "VariableTracker" +) -> "VariableTracker": + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/abstract.c#L53-L69 + """ + Implements PyObject_Size/PyObject_Length semantics for VariableTracker objects. + Dispatches to sq_length (sequences) or mp_length (mappings) depending on the VT type. + """ + + if obj.tp_as_sequence.sq_length: + return obj.sq_length_impl(tx) + return pymapping_size(tx, obj) + + +def generic_is_true( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyObject_IsTrue. + + https://github.com/python/cpython/blob/c09ccd9c429/Objects/object.c#L2135-L2158 + + Resolution order: constants → nb_bool → mp_length/sq_length → truthy. + """ + from .constant import ConstantVariable + + if obj.is_python_constant(): + try: + return ConstantVariable.create(bool(obj.as_python_constant())) + except Exception as e: + raise_observed_exception(type(e), tx, args=[str(e)]) + + if obj.tp_as_number.nb_bool: + result = obj.nb_bool_impl(tx) + if result is not None: + return result + + try: + length = generic_size(tx, obj) + from .tensor import SymNodeVariable + + if isinstance(length, SymNodeVariable): + return SymNodeVariable.create(tx, length.as_proxy() > 0) + length_val = length.as_python_constant() + if length_val < 0: + raise_observed_exception( + ValueError, tx, args=["__len__() should return >= 0"] + ) + return ConstantVariable.create(length_val > 0) + except ObservedTypeError: + handle_observed_exception(tx) + + return ConstantVariable.create(True) + + +_repr_running: set[int] = set() + + +def generic_repr( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyObject_Repr with Py_ReprEnter/Py_ReprLeave cycle detection. + + https://github.com/python/cpython/blob/v3.13.3/Objects/object.c#L745-L778 + + Resolution order: tp_repr -> TypeError if the result is not str. + """ + obj_type = maybe_get_python_type(obj) + + tp_repr = obj.tp_repr + if tp_repr is not None: + obj_id = id(obj) + if obj_id in _repr_running: + sentinel = {list: "[...]", dict: "{...}", collections.deque: "[...]"} + return ConstantVariable.create(sentinel.get(obj_type, "...")) + _repr_running.add(obj_id) + try: + result = obj.tp_repr_impl(tx) + finally: + _repr_running.discard(obj_id) + result_type = maybe_get_python_type(result) + if not issubclass(result_type, str): + if sys.version_info >= (3, 15): + err_str = f"{obj.python_qualified_name()}.__repr__() must return a str, not int" + else: + err_str = f"__repr__ returned non-string (type {result_type.__name__})" + raise_type_error(tx, err_str) + return result + + raise_type_error(tx, f"object of type '{obj.python_type_name()}' has no repr") + + +def generic_str( + tx: "InstructionTranslatorBase", obj: "VariableTracker" +) -> "VariableTracker": + """Mirrors PyObject_Str semantics in Dynamo. + + https://github.com/python/cpython/blob/v3.13.3/Objects/object.c#L781-L829 + + Resolution order: str identity check -> tp_str (tp_str_impl) -> tp_repr fallback. + """ + from ..exc import TorchDynamoException + + if maybe_get_python_type(obj) is str: + return obj + + try: + if obj.tp_str and type(obj).tp_str_impl is not VariableTracker.tp_str_impl: + result = obj.tp_str_impl(tx) + else: + result = generic_repr(tx, obj) + except TorchDynamoException: + raise + except Exception as exc: + raise_observed_exception(type(exc), tx, args=list(exc.args)) + + result_type = maybe_get_python_type(result) + if not issubclass(result_type, str): + if sys.version_info >= (3, 15): + err_str = f"{obj.python_qualified_name()}.__str__() must return a str, not {result.python_qualified_name()}" + else: + err_str = f"__str__ returned non-string (type {result_type.__name__})" + raise_type_error(tx, err_str) + return result + + +def generic_getitem( + tx: "InstructionTranslatorBase", + obj: VariableTracker, + key: VariableTracker, +) -> VariableTracker: + """CPython's PyObject_GetItem — dispatch to the type's mp_subscript/sq_item. + + PyObject_GetItem: https://github.com/python/cpython/blob/62a6e898e01/Objects/abstract.c#L155-L206 + + CPython checks three branches in order: + 1. tp_as_mapping->mp_subscript (L161-166) + 2. tp_as_sequence->sq_item (L168-181) — only if key passes _PyIndex_Check + 3. PyType_Check(o) (L183-203) — type[int] → GenericAlias/__class_getitem__ + + Branch 1 is the common path (list, tuple, dict, range all have mp_subscript). + Branch 2 fires for types with only sq_item (e.g. deque). + Branch 3 delegates to mp_subscript_impl for type objects (__class_getitem__). + """ + obj_type = maybe_get_python_type(obj) + # Branch 1: mp_subscript + if obj.tp_as_mapping.mp_subscript: + return obj.mp_subscript_impl(tx, key) + # Branch 2: sq_item (only if mp_subscript is absent) + # CPython: abstract.c L168-181 — _PyIndex_Check(key) → PyNumber_AsSsize_t + # → PySequence_GetItem (wraps negative, calls sq_item) + if obj.tp_as_sequence.sq_item is not None: + key_type = maybe_get_python_type(key) + if pyindex_check(key_type): + key = pynumber_as_ssize_t(tx, key, IndexError) + return pysequence_getitem(tx, obj, key) + raise_type_error( + tx, + f"{obj_type.__name__} indices must be integers, not {key_type.__name__}", + ) + # Branch 3: PyType_Check → __class_getitem__ (abstract.c L183-203) + # In 3.10+ type.__getitem__ sets mp_subscript so this is normally caught + # by Branch 1, but we check explicitly for safety. + if issubclass(obj_type, type): + return obj.mp_subscript_impl(tx, key) + # CPython: abstract.c L205 + raise_type_error(tx, f"'{obj_type.__name__}' object is not subscriptable") + + +def pysequence_getitem( + tx: "InstructionTranslatorBase", + obj: VariableTracker, + index: VariableTracker, +) -> VariableTracker: + """CPython's PySequence_GetItem — always sq_item, never mp_subscript. + + ref: https://github.com/python/cpython/blob/v3.13.3/Objects/abstract.c#L1874-L1902 + + Called by PyObject_GetItem branch 2, reversed() fallback, and the old + iteration protocol. Wraps negative indices via sq_length before + dispatching to sq_item. + """ + sq_item = obj.tp_as_sequence.sq_item + if sq_item is not None: + # Negative index wrapping (abstract.c L2175-2183) + if isinstance(index, ConstantVariable): + index_val = index.as_python_constant() + if isinstance(index_val, int) and index_val < 0: + if obj.tp_as_sequence.sq_length is not None: + length = obj.sq_length_impl(tx) + index = ConstantVariable.create( + index_val + length.as_python_constant() + ) + return obj.sq_item_impl(tx, index) + + if obj.tp_as_mapping.mp_subscript is not None: + raise_type_error(tx, f"'{obj.python_type_name()}' is not a sequence") + + raise_type_error(tx, f"'{obj.python_type_name()}' object does not support indexing") + + +def pysequence_setitem( + tx: "InstructionTranslatorBase", + s: VariableTracker, + i: VariableTracker, + o: VariableTracker, +) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L1926-L1957 (PySequence_SetItem) + sq_ass_item = s.tp_as_sequence.sq_ass_item + if sq_ass_item is not None: + # Negative index wrapping (abstract.c L1944-1952) + if isinstance(i, ConstantVariable): + index_val = i.as_python_constant() + if isinstance(index_val, int) and index_val < 0: + if s.tp_as_sequence.sq_length is not None: + length = s.sq_length_impl(tx) + i = ConstantVariable.create(index_val + length.as_python_constant()) + return s.sq_ass_item_impl(tx, i, o) + + if s.tp_as_mapping.mp_ass_subscript is not None: + raise_type_error(tx, f"'{s.python_type_name()}' is not a sequence") + + raise_type_error( + tx, f"'{s.python_type_name()}' object does not support item assignment" + ) + + +def generic_setitem( + tx: "InstructionTranslatorBase", + o: VariableTracker, + key: VariableTracker, + value: VariableTracker, +) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L222-L254 + mp_ass_subscript = o.tp_as_mapping.mp_ass_subscript + if mp_ass_subscript is not None: + return o.mp_ass_subscript_impl(tx, key, value) + + if o.tp_as_sequence.sq_ass_item is not None: + key_type = maybe_get_python_type(key) + if pyindex_check(key_type): + key_value = pynumber_as_ssize_t(tx, key, err=IndexError) + return pysequence_setitem(tx, o, key_value, value) + raise_type_error( + tx, f"sequence index must be integer, not '{key.python_type_name()}'" + ) + raise_type_error( + tx, f"'{o.python_type_name()}' object does not support item assignment" + ) + + +def pysequence_delitem( + tx: "InstructionTranslatorBase", + s: VariableTracker, + i: VariableTracker, +) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L1959-L1990 + + sq_ass_item = s.tp_as_sequence.sq_ass_item + if sq_ass_item is not None: + if isinstance(i, ConstantVariable): + idx = i.as_python_constant() + if idx < 0: + if s.tp_as_sequence.sq_length is not None: + length = s.sq_length_impl(tx) + i = pynumber_add(tx, i, length) + return s.sq_ass_item_impl(tx, i, None) + + if s.tp_as_mapping.mp_ass_subscript is not None: + raise_type_error(tx, f"'{s.python_type_name()}' is not a sequence") + + raise_type_error( + tx, f"'{s.python_type_name()}' object does not support item deletion" + ) + + +def generic_delitem( + tx: "InstructionTranslatorBase", + o: VariableTracker, + key: VariableTracker, +) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L256-L288 + + mp_ass_subscript = o.tp_as_mapping.mp_ass_subscript + if mp_ass_subscript is not None: + return o.mp_ass_subscript_impl(tx, key, None) + + key_type = maybe_get_python_type(key) + if pyindex_check(key_type): + key_value = key.nb_index_impl(tx) + return pysequence_delitem(tx, o, key_value) + elif o.tp_as_sequence.sq_ass_item is not None: + raise_type_error( + tx, f"sequence index must be integer, not {key.python_type_name()}" + ) + + raise_type_error(tx, f"'{o.python_type_name()}' does not support item deletion") + + +def pynumber_int( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Long (int(x) dispatch). + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1520-L1632 + + Resolution: nb_int → nb_index → str/bytes/bytearray parsing → TypeError. + """ + from .constant import ConstantVariable + + # Fast path for int (sub)class instances — mirrors PyLong_Check at the + # top of PyNumber_Long (abstract.c:1531). Avoids infinite recursion for + # int subclasses like IntEnum whose __int__ calls int() again. + if obj.is_python_constant() and isinstance(obj.as_python_constant(), int): + return ConstantVariable.create(int(obj.as_python_constant())) + + if obj.tp_as_number.nb_int is not None: + res = obj.nb_int_impl(tx) + if res.python_type() is not int: + raise_type_error( + tx, + f"__int__ returned non-int (type {res.python_type_name()})", + ) + return res + + if obj.tp_as_number.nb_index is not None: + return obj.nb_index_impl(tx) + + # String/bytes/bytearray parsing fallback. + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1598-L1612 + if obj.is_python_constant() and isinstance( + obj.as_python_constant(), (str, bytes, bytearray) + ): + try: + return ConstantVariable.create(int(obj.as_python_constant())) + except ValueError as e: + raise_observed_exception(ValueError, tx, args=[str(e)]) + + raise_type_error( + tx, + f"int() argument must be a string, a bytes-like object " + f"or a real number, not '{obj.python_type_name()}'", + ) + + +def pylong_from_base( + tx: "InstructionTranslatorBase", x: VariableTracker, obase: VariableTracker +) -> VariableTracker | None: + """Mirrors the explicit-base path of long_new_impl (int(x, base)). + + https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5879-L5922 + + The base is resolved via PyNumber_AsSsize_t, which consults __index__, so + any __index__-able object is accepted. Returns None (graph break) when the + inputs cannot be resolved to Python constants. + """ + # base = PyNumber_AsSsize_t(obase, NULL) -> nb_index. + if obase.is_python_constant() and issubclass(obase.python_type(), int): + base_vt = obase + elif obase.tp_as_number.nb_index is not None: + base_vt = obase.nb_index_impl(tx) + else: + raise_type_error( + tx, + f"'{obase.python_type_name()}' object cannot be interpreted as an integer", + ) + if not (base_vt.is_python_constant() and issubclass(base_vt.python_type(), int)): + return None + base = base_vt.as_python_constant() + if (base != 0 and base < 2) or base > 36: + raise_observed_exception( + ValueError, tx, args=["int() base must be >= 2 and <= 36, or 0"] + ) + if not x.is_python_constant(): + return None + xval = x.as_python_constant() + if not isinstance(xval, (str, bytes, bytearray)): + raise_type_error(tx, "int() can't convert non-string with explicit base") + try: + return ConstantVariable.create(int(xval, base)) + except ValueError as e: + raise_observed_exception(ValueError, tx, args=list(e.args)) + + +def pynumber_float( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Float (float(x) dispatch). + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1635-L1692 + + Resolution: nb_float → nb_index → str parsing → TypeError. + """ + from .constant import ConstantVariable + + # Fast path: if the value is already a float constant, return it directly. + # Mirrors PyFloat_CheckExact fast path at the top of PyNumber_Float + # (abstract.c:1641-1643). + if obj.is_python_constant() and isinstance(obj.as_python_constant(), float): + return ConstantVariable.create(float(obj.as_python_constant())) + + if obj.tp_as_number.nb_float is not None: + res = obj.nb_float_impl(tx) + if res.python_type() is not float: + raise_type_error( + tx, + f"__float__ returned non-float (type {res.python_type_name()})", + ) + return res + + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1674-L1685 + if obj.tp_as_number.nb_index is not None: + return obj.nb_index_impl(tx) + + # PyFloat_FromString fallback — handles str and bytes. + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1691 + if issubclass(obj.python_type(), (str, bytes)): + try: + return ConstantVariable.create(float(obj.as_python_constant())) + except ValueError as e: + raise_observed_exception(ValueError, tx, args=[str(e)]) + + raise_type_error( + tx, + f"float() argument must be a string or a real number, " + f"not '{obj.python_type_name()}'", + ) + + +def getindex( + tx: "InstructionTranslatorBase", + obj: VariableTracker, + arg: VariableTracker, +) -> VariableTracker: + """Mirrors typeobject.c::getindex: calls PyNumber_AsSsize_t then tp_as_sequence.sq_length""" + obj_type = maybe_get_python_type(obj) + + i = pynumber_as_ssize_t(tx, arg, err=OverflowError) + if i.as_python_constant() < 0: + if type_implements_sq_length(obj_type): + length = obj.sq_length_impl(tx) + i = pynumber_add(tx, i, length) + return i + + +def pylong_as_ssize_t(tx: "InstructionTranslatorBase", obj: VariableTracker) -> int: + """Mirrors PyLong_AsSsize_t: requires an int (or subclass). + values outside the Py_ssize_t range raise OverflowError. + + https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/longobject.c#L576 + """ + # Starting on Python 3.16, this will explicitly require an integer instance + # https://docs.python.org/3/deprecations/index.html#pending-removal-in-python-3-16 + if not issubclass(obj.python_type(), int): + raise_type_error(tx, "an integer is required") + val = obj.as_python_constant() + if not -sys.maxsize - 1 <= val <= sys.maxsize: + raise_observed_exception( + OverflowError, + tx, + args=["Python int too large to convert to C ssize_t"], + ) + return val + + +def pynumber_as_ssize_t( + tx: "InstructionTranslatorBase", + item: VariableTracker, + err: type[Exception] | None = IndexError, +) -> VariableTracker: + """Mirrors PyNumber_AsSsize_t: _PyNumber_Index(item) then PyLong_AsSsize_t. + + On overflow (value outside the Py_ssize_t range) CPython remaps the + OverflowError to `err`, or clips to the Py_ssize_t bounds when err is None. + + https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/abstract.c#L1469 + """ + from .tensor import SymNodeVariable + + value = pynumber_index(tx, item) + + # PyLong_AsSsize_t: a symbolic int must be specialized to a concrete + # ssize_t (with guard) to be usable as a C index. + if isinstance(value, SymNodeVariable): + val = value.evaluate_expr(tx.output) + else: + val = value.as_python_constant() + + if not isinstance(val, int): + raise AssertionError("pynumber_index did not return an int-like value") + + if -sys.maxsize - 1 <= val <= sys.maxsize: + return ConstantVariable.create(int(val)) + if err is None: + r = sys.maxsize if val > 0 else -sys.maxsize - 1 + return ConstantVariable.create(r) + raise_observed_exception( + err, + tx, + args=[f"cannot fit '{item.python_type_name()}' into an index-sized integer"], + ) + + +def pynumber_index( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> "VariableTracker": + """Mirrors PyNumber_Index (index(x) dispatch).""" + + if obj.tp_as_number.nb_index is None: + raise_type_error( + tx, + f"'{obj.python_type_name()}' object cannot be interpreted as an integer", + ) + + result = obj.nb_index_impl(tx) + + if not issubclass(result.python_type(), int): + raise_type_error( + tx, + f"__index__ returned non-int (type {result.python_type_name()})", + ) + + return result + + +def pynumber_tobase( + tx: "InstructionTranslatorBase", obj: VariableTracker, base: int +) -> VariableTracker | None: + """Mirrors PyNumber_ToBase (bin/oct/hex dispatch). + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1653-L1666 + + Resolves __index__ (raising TypeError if absent), then formats the + resulting int in the requested base. Returns None (graph break) when the + index result is not a Python constant. + """ + index = pynumber_index(tx, obj) + format_fn = {2: bin, 8: oct, 16: hex}[base] + return ConstantVariable.create(format_fn(index.as_python_constant())) + + +def pyiter_next( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> "VariableTracker": + """ + Implements PyIter_Next / tp_iternext semantics for VariableTracker objects. + + Calls obj.tp_iternext_impl(tx) if the object is an iterator, otherwise raises + TypeError. StopIteration propagation is left to the caller (mirrors + CPython's iternext contract where NULL return signals exhaustion). + """ + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L2865 + + tp_iternext = obj.tp_iternext + if tp_iternext is None: + raise_type_error(tx, f"expected an iterator, got '{obj.python_type_name()}'") + + return obj.tp_iternext_impl(tx) + + +def pynumber_negative( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Negative. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1375-L1392 + + Algorithm: + 1. If type has nb_negative slot, call obj.nb_negative_impl(tx) + 2. Otherwise, raise TypeError + """ + + nb_negative = obj.tp_as_number.nb_negative + if nb_negative is not None: + return obj.nb_negative_impl(tx) + + raise_type_error( + tx, + f"bad operand type for unary -: '{obj.python_type_name()}'", + ) + + +def pynumber_positive( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Positive. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1375-L1393 + + Algorithm: + 1. If type has nb_positive slot, call obj.nb_positive_impl(tx) + 2. Otherwise, raise TypeError + """ + + nb_positive = obj.tp_as_number.nb_positive + if nb_positive is not None: + return obj.nb_positive_impl(tx) + + raise_type_error( + tx, + f"bad operand type for unary +: '{obj.python_type_name()}'", + ) + + +def pynumber_absolute( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Absolute. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1375-L1395 + + Algorithm: + 1. If type has nb_absolute slot, call obj.nb_absolute_impl(tx) + 2. Otherwise, raise TypeError + """ + + nb_absolute = obj.tp_as_number.nb_absolute + if nb_absolute is not None: + return obj.nb_absolute_impl(tx) + + raise_type_error( + tx, + f"bad operand type for abs(): '{obj.python_type_name()}'", + ) + + +def vt_is_iterable(obj: VariableTracker) -> bool: + """Check if the object supports iteration (i.e. has tp_iter or sequence protocol).""" + T = maybe_get_python_type(obj) + return obj.tp_iter is not None or pysequence_check(T) + + +def pynumber_invert( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Invert. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1375-L1394 + + Algorithm: + 1. If type has nb_invert slot, call obj.nb_invert_impl(tx) + 2. Otherwise, raise TypeError + """ + + nb_invert = obj.tp_as_number.nb_invert + if nb_invert is not None: + return obj.nb_invert_impl(tx) + + raise_type_error( + tx, + f"bad operand type for unary ~: '{obj.python_type_name()}'", + ) + + +def generic_getiter( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> "VariableTracker": + """ + Implements PyObject_GetIter semantics for VariableTracker objects. + Routes to obj.tp_iter_impl(tx), the tp_iter slot on the object's type. + """ + + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L2847-L2870 + # The algorithm for PyObject_GetIter works as follows: Steps: + # 1. If the object has tp_iter slot, call it and return the result. The + # return object must be an iterator (it must have a tp_iternext slot) + # 2. If the object implements the sequence protocol - implements __getitem__ + # then create a sequence iterator for the object and return it + # 3. Otherwise, raise a TypeError + + T = maybe_get_python_type(obj) + tp_iter = obj.tp_iter + if tp_iter is not None: + res = obj.tp_iter_impl(tx) + res_T = maybe_get_python_type(res) + if not pyiter_check(res_T): + if sys.version_info >= (3, 15): + err_str = f"{obj.python_qualified_name()}.__iter__() must return an iterator, not {res.python_qualified_name()}" + else: + err_str = ( + f"iter() returned non-iterator of type '{res.python_type_name()}'" + ) + raise_type_error(tx, err_str) + return res + elif pysequence_check(T): + from .functions import UserFunctionVariable + + return UserFunctionVariable(polyfills.builtins.sequence_iterator).call_function( + tx, [obj], {} + ) + else: + raise_type_error(tx, f"'{obj.python_type_name()}' object is not iterable") + + +# --------------------------------------------------------------------------- +# Binary-op dispatch (CPython's abstract.c: binary_op1 / binary_op) +# https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L927 (binary_op1) +# --------------------------------------------------------------------------- + +NB_SLOT_MAPPING = { + "nb_lshift": PyNumberSlots.NB_LSHIFT, + "nb_inplace_lshift": PyNumberSlots.NB_INPLACE_LSHIFT, + "nb_inplace_rshift": PyNumberSlots.NB_INPLACE_RSHIFT, + "nb_rshift": PyNumberSlots.NB_RSHIFT, + "nb_or": PyNumberSlots.NB_OR, + "nb_inplace_or": PyNumberSlots.NB_INPLACE_OR, + "nb_subtract": PyNumberSlots.NB_SUBTRACT, + "nb_inplace_subtract": PyNumberSlots.NB_INPLACE_SUBTRACT, + "nb_add": PyNumberSlots.NB_ADD, + "nb_inplace_add": PyNumberSlots.NB_INPLACE_ADD, + "nb_multiply": PyNumberSlots.NB_MULTIPLY, + "nb_inplace_multiply": PyNumberSlots.NB_INPLACE_MULTIPLY, + "nb_matrix_multiply": PyNumberSlots.NB_MATRIX_MULTIPLY, + "nb_inplace_matrix_multiply": PyNumberSlots.NB_INPLACE_MATRIX_MULTIPLY, + "nb_and": PyNumberSlots.NB_AND, + "nb_inplace_and": PyNumberSlots.NB_INPLACE_AND, + "nb_xor": PyNumberSlots.NB_XOR, + "nb_inplace_xor": PyNumberSlots.NB_INPLACE_XOR, + "nb_floor_divide": PyNumberSlots.NB_FLOOR_DIVIDE, + "nb_inplace_floor_divide": PyNumberSlots.NB_INPLACE_FLOOR_DIVIDE, + "nb_true_divide": PyNumberSlots.NB_TRUE_DIVIDE, + "nb_inplace_true_divide": PyNumberSlots.NB_INPLACE_TRUE_DIVIDE, + "nb_remainder": PyNumberSlots.NB_REMAINDER, + "nb_inplace_remainder": PyNumberSlots.NB_INPLACE_REMAINDER, + "nb_divmod": PyNumberSlots.NB_DIVMOD, + "nb_power": PyNumberSlots.NB_POWER, + "nb_inplace_power": PyNumberSlots.NB_INPLACE_POWER, +} + + +def is_nb_not_implemented(result: VariableTracker) -> bool: + return result.is_constant_match(NotImplemented) + + +def is_python_subtype(w: VariableTracker, v: VariableTracker) -> bool: + """Check if w's underlying Python type is a proper subtype of v's.""" + try: + return issubclass(w.python_type(), v.python_type()) + except NotImplementedError: + return False + + +# Calling scheme used for binary operations: +# +# Order operations are tried until either a valid result or error: +# w.op(v,w)[*], v.op(v,w), w.op(v,w) +# +# [*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of +# Py_TYPE(v) + + +def binary_op1( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + op_slot: str, +) -> VariableTracker: + """CPython's binary_op1: try v's slot, then w's slot with subclass priority. + + Each VT that participates provides a ``_impl(self, tx, other, + reverse)`` method. ``reverse=False`` means "self is left operand" (forward, + e.g. ``__or__``), ``reverse=True`` means "self is right operand" (reverse, + e.g. ``__ror__``). For built-in types the flag is ignored because their + slots check both operands symmetrically. + + CPython splits the check into two steps: ``Py_TYPE(v)->tp_as_number != + NULL`` (does the type have a number-protocol struct), then read the + slot pointer (which may itself be NULL). We collapse both into a + single :func:`type_implements_nb_slot` query — its bit is set only + when the specific slot is non-NULL, which already implies + ``tp_as_number`` is non-NULL. Treating a missing slot as "no impl" + is what keeps the base ``VariableTracker.nb_*_impl`` graph-break + out of the path for types that genuinely lack the slot in C. + + https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L926-L977 + """ + impl_attr = f"{op_slot}_impl" + nb_slot_bit = NB_SLOT_MAPPING[op_slot] + + v_type = maybe_get_python_type(v) + w_type = maybe_get_python_type(w) + + v_slot = ( + getattr(type(v), impl_attr, None) + if type_implements_nb_slot(v_type, nb_slot_bit) + else None + ) + w_slot = ( + getattr(type(w), impl_attr, None) + if type_implements_nb_slot(w_type, nb_slot_bit) + else None + ) + + # CPython skips slotw if Py_TYPE(w) == Py_TYPE(v) (one C type, one slot + # function). In Dynamo two VT subclasses can share a Python type — e.g. + # ConstantVariable(3) and SymNodeVariable both report ``int`` — yet have + # different ``nb_*_impl`` methods. Comparing the slots themselves + # captures both "literally the same function" (CPython's check) and + # "different VT subclasses sharing a python_type", so we drop the type + # equality check. + if v_slot is w_slot: + w_slot = None + + if v_slot is not None: + # Subclass priority: if w's Python type is a proper subtype of v's + # Python type and overrides the slot, try w first (CPython abstract.c:952-960). + if w_slot is not None and is_python_subtype(w, v): + # CPython ALWAYS calls the slot with (v, w), even for reverse slots. + # Since w_slot is a method call, we use reverse=True to indicate w + # is the right operand, matching CPython's semantics. + result = w_slot(w, tx, v, True) + if not is_nb_not_implemented(result): + return result + w_slot = None + result = v_slot(v, tx, w, False) + if not is_nb_not_implemented(result): + return result + if w_slot is not None: + result = w_slot(w, tx, v, True) + if not is_nb_not_implemented(result): + return result + return ConstantVariable.create(NotImplemented) + + +def binary_op( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + op_slot: str, + op_symbol: str, +) -> VariableTracker: + """CPython's binary_op: binary_op1 + TypeError fallback. + https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L997-L1020 + """ + + result = binary_op1(tx, v, w, op_slot) + if is_nb_not_implemented(result): + binop_type_error(tx, v, w, op_symbol) + return result + + +def ternary_op( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + z: VariableTracker | None, + op_slot: str, + op_name: str, +) -> VariableTracker: + impl_attr = f"{op_slot}_impl" + nb_slot_bit = NB_SLOT_MAPPING[op_slot] + + v_type = maybe_get_python_type(v) + w_type = maybe_get_python_type(w) + + v_slot = ( + getattr(type(v), impl_attr, None) + if type_implements_nb_slot(v_type, nb_slot_bit) + else None + ) + + w_slot = ( + getattr(type(w), impl_attr, None) + if type_implements_nb_slot(w_type, nb_slot_bit) + else None + ) + + if v_slot is w_slot: + w_slot = None + + if v_slot: + if w_slot and is_python_subtype(w, v): + result = w_slot(w, tx, v, z, True) + if not is_nb_not_implemented(result): + return result + w_slot = None + result = v_slot(v, tx, w, z, False) + if not is_nb_not_implemented(result): + return result + if w_slot: + result = w_slot(w, tx, v, z, True) + if not is_nb_not_implemented(result): + return result + + if z: + z_type = maybe_get_python_type(z) + if type_implements_nb_slot(z_type, nb_slot_bit): + z_impl_attr = f"{op_slot}_z_impl" + z_slot = getattr(type(z), z_impl_attr, None) + if z_slot in (v_slot, w_slot): + z_slot = None + if z_slot: + result = z_slot(z, tx, v, w) + if not is_nb_not_implemented(result): + return result + + if z is None: + binop_type_error(tx, v, w, op_name) + else: + raise_type_error( + tx, + f"unsupported operand type(s) for {op_name}: " + f"'{v.python_type_name()}', '{w.python_type_name()}', '{z.python_type_name()}'", + ) + + +def ternary_iop( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + z: VariableTracker | None, + iop_slot: str, + op_slot: str, + op_name: str, +) -> VariableTracker: + v_type = maybe_get_python_type(v) + if type_implements_nb_slot(v_type, NB_SLOT_MAPPING[iop_slot]): + impl_attr = f"{iop_slot}_impl" + slot = getattr(type(v), impl_attr) + result = slot(v, tx, w, z) + if not is_nb_not_implemented(result): + return result + + return ternary_op(tx, v, w, z, op_slot, op_name) + + +# Binary in-place operators +# +# The in-place operators are defined to fall back to the 'normal', non +# in-place operations, if the in-place methods are not in place. +# +# - If the left hand object has the appropriate struct members, and they are +# filled, call the appropriate function and return the result. No coercion +# is done on the arguments; the left-hand object is the one the operation +# is performed on, and it's up to the function to deal with the right-hand +# object. +# +# - Otherwise, in-place modification is not supported. Handle it exactly as a +# non in-place operation of the same kind. + + +def binary_iop1( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + iop_slot: str, + op_slot: str, +) -> VariableTracker: + v_type = maybe_get_python_type(v) + + if type_implements_nb_slot(v_type, NB_SLOT_MAPPING[iop_slot]): + impl_attr = f"{iop_slot}_impl" + slot = getattr(type(v), impl_attr) + result = slot(v, tx, w) + if not is_nb_not_implemented(result): + return result + + return binary_op1(tx, v, w, op_slot) + + +def binary_iop( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + iop_slot: str, + op_slot: str, + op_symbol: str, +) -> VariableTracker: + """CPython's binary_iop: try inplace slot, fallback to binary_op1. + + Combines binary_iop1 + TypeError fallback from binary_iop. + https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L1229-L1270 (binary_iop1, binary_iop) + """ + result = binary_iop1(tx, v, w, iop_slot, op_slot) + if is_nb_not_implemented(result): + binop_type_error(tx, v, w, op_symbol) + return result + + +# add / inplace add needs special handling +def pynumber_add( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Implements addition via nb_add / nb_inplace_add with binary_op dispatch.""" + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1138-L1155 + result = binary_op1(tx, v, w, "nb_add") + if not is_nb_not_implemented(result): + return result + + sq_concat = v.tp_as_sequence.sq_concat + if sq_concat is not None: + return v.sq_concat_impl(tx, w) + binop_type_error(tx, v, w, "+") + + +def pynumber_inplace_add( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Implements in-place addition via nb_inplace_add with binary_iop dispatch.""" + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1307-L1328 + result = binary_iop1(tx, v, w, "nb_inplace_add", "nb_add") + if is_nb_not_implemented(result): + sq_inplace_concat = v.tp_as_sequence.sq_inplace_concat + sq_concat = v.tp_as_sequence.sq_concat + if sq_inplace_concat is not None: + return v.sq_inplace_concat_impl(tx, w) + elif sq_concat is not None: + return v.sq_concat_impl(tx, w) + else: + binop_type_error(tx, v, w, "+=") + return result + + +# --------------------------------------------------------------------------- +# Multiplication: PyNumber_Multiply / PyNumber_InPlaceMultiply +# +# Multiplication is special because numeric types implement nb_multiply but +# sequence types (list, tuple, str, bytes, bytearray) implement only sq_repeat. +# CPython's PyNumber_Multiply tries nb_multiply first (via binary_op1) and on +# NotImplemented falls back to sq_repeat on either operand. +# +# https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1156-L1193 +# --------------------------------------------------------------------------- + + +def pysequence_repeat( + tx: "InstructionTranslatorBase", + seq: VariableTracker, + n: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's sequence_repeat helper. + + Validates that ``n`` is index-like, converts it to an int, and dispatches + to ``seq.sq_repeat_impl(tx, count)``. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1156-L1174 + """ + n_type = maybe_get_python_type(n) + if not pyindex_check(n_type): + raise_type_error( + tx, + f"can't multiply sequence by non-int of type '{n.python_type_name()}'", + ) + count = n.nb_index_impl(tx) + validate_sequence_repeat_count(tx, count) + return seq.sq_repeat_impl(tx, count) + + +def pysequence_inplace_repeat( + tx: "InstructionTranslatorBase", + seq: VariableTracker, + n: VariableTracker, +) -> VariableTracker: + """pysequence_repeat using sq_inplace_repeat. + + The validation step is identical to ``pysequence_repeat``; only the + target slot differs. + """ + n_type = maybe_get_python_type(n) + if not pyindex_check(n_type): + raise_type_error( + tx, + f"can't multiply sequence by non-int of type '{n.python_type_name()}'", + ) + count = n.nb_index_impl(tx) + validate_sequence_repeat_count(tx, count) + return seq.sq_inplace_repeat_impl(tx, count) + + +def validate_sequence_repeat_count( + tx: "InstructionTranslatorBase", + count: VariableTracker, +) -> None: + n = count.as_python_constant() + if n < -sys.maxsize - 1 or n > sys.maxsize: + raise_observed_exception( + OverflowError, + tx, + args=["cannot fit 'int' into an index-sized integer"], + ) + + +def pynumber_multiply( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's PyNumber_Multiply. + + Try nb_multiply via binary_op1; on NotImplemented fall back to sq_repeat + on either operand. TypeError if no path works. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1176-L1193 + """ + result = binary_op1(tx, v, w, "nb_multiply") + if not is_nb_not_implemented(result): + return result + + if v.tp_as_sequence.sq_repeat is not None: + return pysequence_repeat(tx, v, w) + if w.tp_as_sequence.sq_repeat is not None: + return pysequence_repeat(tx, w, v) + + raise_type_error( + tx, + f"unsupported operand type(s) for *: " + f"'{v.python_type_name()}' and '{w.python_type_name()}'", + ) + + +def pynumber_inplace_multiply( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's PyNumber_InPlaceMultiply. + + Try nb_inplace_multiply / nb_multiply via binary_iop1; on NotImplemented + fall back to sq_inplace_repeat (preferred), then sq_repeat. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1330-L1357 + """ + result = binary_iop1(tx, v, w, "nb_inplace_multiply", "nb_multiply") + if not is_nb_not_implemented(result): + return result + + if v.tp_as_sequence.sq_inplace_repeat is not None: + return pysequence_inplace_repeat(tx, v, w) + if v.tp_as_sequence.sq_repeat is not None: + return pysequence_repeat(tx, v, w) + # Cannot mutate w in-place — abstract.c L1348-1352 explicitly avoids + # sq_inplace_repeat on the right-hand operand. + if w.tp_as_sequence.sq_repeat is not None: + return pysequence_repeat(tx, w, v) + + raise_type_error( + tx, + f"unsupported operand type(s) for *=: " + f"'{v.python_type_name()}' and '{w.python_type_name()}'", + ) + + +def pynumber_matrix_multiply( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's PyNumber_MatrixMultiply.""" + return binary_op(tx, v, w, "nb_matrix_multiply", "@") + + +def pynumber_inplace_matrix_multiply( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's PyNumber_InPlaceMatrixMultiply.""" + return binary_iop( + tx, + v, + w, + "nb_inplace_matrix_multiply", + "nb_matrix_multiply", + "@=", + ) + + +# --------------------------------------------------------------------------- +# Type-object slot wrappers for ``__mul__`` / ``__rmul__`` / ``__imul__`` +# +# These mirror the *type object*'s installation of ``__mul__`` etc. as a +# method, not the operator dispatch. In CPython the user-visible +# ``int.__mul__`` and ``list.__mul__`` are different functions, each +# generated at type-construction time from ``Objects/typeobject.c``'s +# ``slotdefs[]`` table: +# +# slotdefs[]: +# BINSLOT(__mul__, nb_multiply, slot_nb_multiply, "*") [L10323] +# SQSLOT (__mul__, sq_repeat, NULL, wrap_indexargfunc) [L10419] +# RBINSLOT(__rmul__, nb_multiply, slot_nb_multiply, "*") [L10325] +# SQSLOT (__rmul__, sq_repeat, NULL, wrap_indexargfunc) [L10421] +# IBSLOT (__imul__, nb_inplace_multiply, ...) [L10364] +# SQSLOT (__imul__, sq_inplace_repeat, NULL, ...) [L10434] +# +# https://github.com/python/cpython/blob/v3.13.13/Objects/typeobject.c#L10244 (slotdefs[]) +# https://github.com/python/cpython/blob/v3.13.13/Objects/typeobject.c#L10412-L10416 (rationale comment) +# +# ``add_operators`` walks ``slotdefs[]`` and inserts a method into the +# type's ``__dict__`` for whichever slot the type fills. As the comment +# at L10412 notes, types fill at most one of ``nb_multiply`` / +# ``sq_repeat`` per op; nb_* takes priority because its slotdef appears +# first. ``slot_wrapper_mul``/``slot_wrapper_imul`` reproduce that +# selection so that ``call_method`` routing for direct dunder calls +# (``[1, 2].__mul__(3)``) reaches the correct slot. +# +# Distinct from ``pynumber_multiply`` / ``pynumber_inplace_multiply``, which +# mirror the operator-level algorithm in ``Objects/abstract.c`` +# (``PyNumber_Multiply``) — cross-operand subclass priority and the +# ``sq_repeat`` fallback when ``nb_multiply`` returns ``NotImplemented``. +# --------------------------------------------------------------------------- + + +def slot_wrapper_mul( + tx: "InstructionTranslatorBase", + self: VariableTracker, + other: VariableTracker, + reverse: bool = False, +) -> VariableTracker: + """``self.__mul__(other)`` / ``self.__rmul__(other)`` slot wrapper.""" + nb_multiply = self.tp_as_number.nb_multiply + if nb_multiply is not None: + return self.nb_multiply_impl(tx, other, reverse=reverse) + if self.tp_as_sequence.sq_repeat is not None: + # SQSLOT for __mul__ and __rmul__ both use ``wrap_indexargfunc`` — + # the wrapper ignores the reverse flag because sq_repeat takes + # ``(seq, count)`` regardless of which side ``self`` is on. + return pysequence_repeat(tx, self, other) + raise_type_error( + tx, + f"unsupported operand type(s) for *: " + f"'{self.python_type_name()}' and '{other.python_type_name()}'", + ) + + +def slot_wrapper_imul( + tx: "InstructionTranslatorBase", + self: VariableTracker, + other: VariableTracker, +) -> VariableTracker: + """``self.__imul__(other)`` slot wrapper. + + When neither ``nb_inplace_multiply`` nor ``sq_inplace_repeat`` is + installed, the slotdef machinery doesn't generate ``__imul__`` at all + — but the operator-level fallback in ``slot_nb_inplace_multiply`` + (typeobject.c) does try the non-inplace slot. We mirror that here so + method lookups don't graph-break on (e.g.) tuple, even though tuple + has no ``__imul__`` attribute in standard CPython. + """ + nb_inplace_multiply = self.tp_as_number.nb_inplace_multiply + if nb_inplace_multiply is not None: + return self.nb_inplace_multiply_impl(tx, other) + if self.tp_as_sequence.sq_inplace_repeat is not None: + return pysequence_inplace_repeat(tx, self, other) + return slot_wrapper_mul(tx, self, other) + + +# --------------------------------------------------------------------------- +# Type-object slot wrappers for ``__add__`` / ``__radd__`` / ``__iadd__`` + +# BINSLOT (__add__, nb_add, slot_nb_add, "+") [typeobject.c L10915] +# RBINSLOT(__radd__, nb_add, slot_nb_add, "+") [L10917] +# SQSLOT (__add__, sq_concat, NULL, wrap_binaryfunc) [L11017] +# IBSLOT (__iadd__, nb_inplace_add, ...) [L10960] +# SQSLOT (__iadd__, sq_inplace_concat, NULL, ...) [L11031] +# +# Distinct from ``pynumber_add`` / ``pynumber_inplace_add``, which mirror the +# operator-level ``PyNumber_Add`` (cross-operand priority, sq_concat fallback). +# --------------------------------------------------------------------------- + + +def slot_wrapper_add( + tx: "InstructionTranslatorBase", + self: VariableTracker, + other: VariableTracker, + reverse: bool = False, +) -> VariableTracker: + """``self.__add__(other)`` / ``self.__radd__(other)`` slot wrapper.""" + nb_add = self.tp_as_number.nb_add + if nb_add is not None: + return self.nb_add_impl(tx, other, reverse=reverse) + # No SQSLOT(__radd__): sq_concat backs only the forward __add__. + sq_concat = self.tp_as_sequence.sq_concat + if not reverse and sq_concat is not None: + return self.sq_concat_impl(tx, other) + raise_type_error( + tx, + f"unsupported operand type(s) for +: " + f"'{self.python_type_name()}' and '{other.python_type_name()}'", + ) + + +def slot_wrapper_iadd( + tx: "InstructionTranslatorBase", + self: VariableTracker, + other: VariableTracker, +) -> VariableTracker: + """``self.__iadd__(other)`` slot wrapper. + + Mirrors ``slot_wrapper_imul``: when neither ``nb_inplace_add`` nor + ``sq_inplace_concat`` is installed, fall back to the non-inplace slot. + """ + nb_inplace_add = self.tp_as_number.nb_inplace_add + if nb_inplace_add is not None: + return self.nb_inplace_add_impl(tx, other) + sq_inplace_concat = self.tp_as_sequence.sq_inplace_concat + if sq_inplace_concat is not None: + return self.sq_inplace_concat_impl(tx, other) + return slot_wrapper_add(tx, self, other) + + +# --------------------------------------------------------------------------- +# tp_richcompare -- comparison dispatch +# +# CPython comparison architecture (Objects/object.c, Objects/typeobject.c): +# +# a == b (COMPARE_OP bytecode) +# -> PyObject_RichCompare(a, b, Py_EQ) +# -> do_richcompare(a, b, Py_EQ) # the 4-step algorithm +# -> type(a)->tp_richcompare(a, b, Py_EQ) # per-type slot +# +# a.__eq__(b) (attribute access) +# -> type(a)->tp_getattro(a, "__eq__") # descriptor protocol +# -> returns wrapper bound to tp_richcompare +# -> calling wrapper invokes tp_richcompare(a, b, Py_EQ) directly +# +# do_richcompare algorithm (Objects/object.c#L901-L955): +# 1. Subclass priority: if type(b) is a proper subclass of type(a), +# try type(b)->tp_richcompare(b, a, swapped_op) first +# 2. Forward: type(a)->tp_richcompare(a, b, op) +# 3. Reflected: type(b)->tp_richcompare(b, a, swapped_op) +# 4. Fallback: identity for eq/ne, TypeError for ordering +# +# Dynamo implementation: +# +# tp_richcompare_impl(self, tx, other, op) -- per-VT slot, analogous to +# tp_richcompare. Returns ConstantVariable(NotImplemented) when the +# type does not handle the comparison. +# +# generic_richcompare(tx, lhs, rhs, op) -- analogous to do_richcompare. +# Implements the 4-step algorithm directly using tp_richcompare_impl +# slots. If a user comparison method graph-breaks, the Unsupported +# exception propagates to COMPARE_OP (which has +# @break_graph_if_unsupported) and runs the comparison eagerly. +# UDOV.tp_richcompare_impl disables nested graph breaks on the resolved +# funcvar so the InliningInstructionTranslator does not try to split +# the inlined user method mid-function. +# +# Two entry points converge on tp_richcompare_impl: +# +# COMPARE_OP (a == b): +# -> BuiltinVariable dispatch -> generic_richcompare +# -> tp_richcompare_impl (4-step: subclass priority, forward, reflected, fallback) +# +# call_method("__eq__") (a.__eq__(b) in user code): +# -> base.py call_method -> tp_richcompare_impl directly +# +# The call_method path calls tp_richcompare_impl directly (not +# generic_richcompare) to match CPython semantics: a.__eq__(b) invokes +# the type's tp_richcompare slot without do_richcompare's reflected- +# operand protocol, and may return NotImplemented. +# --------------------------------------------------------------------------- + + +is_richcompare_not_implemented = is_nb_not_implemented + + +def object_richcompare( + self: VariableTracker, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, +) -> VariableTracker: + """object's tp_richcompare. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L6263-L6305 + - __eq__: identity check, else NotImplemented + - __ne__: delegates to tp_richcompare(self, other, Py_EQ) and inverts + - ordering + """ + if op == "__eq__": + identity = vt_identity_compare(self, other) + if identity is not None and identity.as_python_constant(): + return ConstantVariable.create(True) + return ConstantVariable.create(NotImplemented) + elif op == "__ne__": + # https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L6279-L6298 + # Safe to call as_python_constant(): only identity-based types use + # object_richcompare, so eq_result is always True or NotImplemented. + eq_result = self.tp_richcompare_impl(tx, other, "__eq__") + if is_richcompare_not_implemented(eq_result): + return eq_result + return ConstantVariable.create(not eq_result.as_python_constant()) + else: + return ConstantVariable.create(NotImplemented) + + +def python_constant_richcompare_impl( + self: VariableTracker, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, +) -> VariableTracker: + """Constant-fold comparison for types with as_python_constant().""" + if not self.is_python_constant() or not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_val = self.as_python_constant() + other_val = other.as_python_constant() + try: + result = getattr(type(self_val), op)(self_val, other_val) + except TypeError as e: + raise_observed_exception(TypeError, tx, args=list(e.args)) + return ConstantVariable.create(result) + + +# _Py_SwappedOp: https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L987 +_REFLECTED_OP: dict[str, str] = { + "__lt__": "__gt__", + "__gt__": "__lt__", + "__le__": "__ge__", + "__ge__": "__le__", + "__eq__": "__eq__", + "__ne__": "__ne__", +} + +_OP_STR: dict[str, str] = { + "__lt__": "<", + "__le__": "<=", + "__eq__": "==", + "__ne__": "!=", + "__gt__": ">", + "__ge__": ">=", +} + + +def generic_richcompare( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + op: str, +) -> VariableTracker: + """Dynamo's do_richcompare. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L994-L1039 + + Implements the 4-step algorithm directly using tp_richcompare_impl slots. + Graph breaks inside user comparison methods propagate to COMPARE_OP + (which runs eagerly) because UDOV.tp_richcompare_impl disables nested + graph breaks on the resolved funcvar. + """ + reflected = _REFLECTED_OP[op] + + try: + v_type = v.python_type() + except NotImplementedError: + v_type = None + try: + w_type = w.python_type() + except NotImplementedError: + w_type = None + + checked_reverse = False + + # Step 1: subclass priority + if ( + v_type is not None + and w_type is not None + and v_type is not w_type + and issubclass(w_type, v_type) + ): + checked_reverse = True + result = w.tp_richcompare_impl(tx, v, reflected) + if not is_richcompare_not_implemented(result): + return result + + # Step 2: forward + result = v.tp_richcompare_impl(tx, w, op) + if not is_richcompare_not_implemented(result): + return result + + # Step 3: reflected (if not already tried) + if not checked_reverse: + result = w.tp_richcompare_impl(tx, v, reflected) + if not is_richcompare_not_implemented(result): + return result + + # Step 4: fallback + if op in ("__eq__", "__ne__"): + identity = vt_identity_compare(v, w) + if identity is not None: + if op == "__ne__": + return ConstantVariable.create(not identity.as_python_constant()) + return identity + unimplemented( + gb_type="richcompare identity fallback undetermined", + context=f"generic_richcompare({v}, {w}, {op})", + explanation="Cannot determine object identity for comparison fallback.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + else: + raise_type_error( + tx, + f"'{_OP_STR[op]}' not supported between instances of " + f"'{v.python_type_name()}' and '{w.python_type_name()}'", + ) + + +def generic_richcompare_bool( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + op: str, +) -> VariableTracker: + """Dynamo's PyObject_RichCompareBool for eq/ne. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L1046-L1080 + + Like generic_richcompare, but with an identity shortcut first: if v + and w are the same Python object, eq is True and ne is False. This + matters for NaN (nan is nan -> True, but nan == nan -> False). Used by + container comparisons (list_richcompare, tuplerichcompare) which call + PyObject_RichCompareBool per element in CPython. + """ + if op not in ("__eq__", "__ne__"): + raise AssertionError(f"generic_richcompare_bool only supports eq/ne, got {op}") + identity = vt_identity_compare(v, w) + if identity is not None and identity.as_python_constant(): + return ConstantVariable.create(op == "__eq__") + return generic_richcompare(tx, v, w, op) + + +def generic_hash_impl( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> tuple[int, bool]: + """Internal API: compute hash as (value, is_fake). + + Dispatches to the VT's hash_impl. Called by generic_hash (which wraps + the result in a VT), container hash_impls (which propagate is_fake), + and HashableTracker (which just needs the int). + """ + return obj.hash_impl(tx) + + +def generic_hash( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """User-facing API: mirrors PyObject_Hash, returns a VariableTracker. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L1101-L1115 + + Wraps the result in ConstantVariable or FakeIdVariable depending on + whether the hash depends on a sourceless object's identity. + """ + from .constant import ConstantVariable, FakeIdVariable, FakeValueKind + + h, is_fake = generic_hash_impl(tx, obj) + if is_fake: + return FakeIdVariable(h, kind=FakeValueKind.HASH) + return ConstantVariable.create(h) + + +def pysequence_contains( + tx: "InstructionTranslatorBase", obj: "VariableTracker", item: "VariableTracker" +) -> "VariableTracker": + """ + Implements PySequence_Contains semantics for VariableTracker objects. + + If the object has sq_contains (i.e., __contains__), calls obj.sq_contains_impl(tx, item). + Otherwise falls back to iterating over obj and comparing each element. + """ + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L2272-L2283 + sq_contains = obj.tp_as_sequence.sq_contains + if sq_contains is not None: + return obj.sq_contains_impl(tx, item) + else: + # iter fallback handles both __iter__ and __getitem__ sequence protocol cases + it = generic_getiter(tx, obj) + return VariableTracker.build( + tx, polyfills.impl_CONTAINS_OP_fallback + ).call_function(tx, [item, it], {}) + + +# Metaclasses whose __subclasscheck__ Dynamo can't trace but whose +# behavior we're willing to observe at trace time via Python's issubclass. +# Each entry trades fidelity to the metaclass's side effects (e.g. ABC's +# subclass cache mutation) for coverage of the common case. +_CONSTANT_FOLD_SUBCLASSCHECK_METACLASSES: tuple[type, ...] = ( + abc.ABCMeta, + torch._C._TensorMeta, # actually just type.__subclasscheck__, but easier to list it here + enum.EnumMeta, +) + + +def generic_issubclass( + tx: "InstructionTranslatorBase", + derived: VariableTracker, + cls: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's PyObject_IsSubclass / object_issubclass. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L2766-L2823 + + This only attempts to replicate object_issubclass, otherwise we delegate to cpython + """ + derived_py = derived.get_real_python_backed_value() + cls_py = cls.get_real_python_backed_value() + if derived_py is NO_SUCH_SUBOBJ or cls_py is NO_SUCH_SUBOBJ: + unimplemented( + gb_type="issubclass() with unsupported arguments", + context=f"issubclass({derived}, {cls})", + explanation="Arguments to issubclass() must be backed by python values.", + hints=[ + "Make sure your arguments are types.", + *graph_break_hints.USER_ERROR, + *graph_break_hints.SUPPORTABLE, + ], + ) + cls_type = maybe_get_python_type(cls) + + # Step 1: PyType_CheckExact fast path — abstract.c L2772 + if cls_type is type: + try: + return ConstantVariable.create( + issubclass( + derived_py, # pyrefly: ignore [bad-argument-type] + cls_py, # pyrefly: ignore [invalid-argument] + ) + ) + except TypeError as e: + raise_observed_exception(TypeError, tx, args=list(e.args)) + + # Step 2: PEP 604 Union (e.g. ``int | str``) — abstract.c L2779-2781. + union_types = {types.UnionType} + if sys.version_info < (3, 14): + union_types.add( + typing._UnionGenericAlias # pyrefly: ignore [missing-attribute] + ) + if cls_type in union_types: + # TODO can trace this once TypingVariable is removed + args = typing.get_args(cls_py) + cls = VariableTracker.build(tx, args) + + # Step 3: tuple of classes — abstract.c L2783-2799. Check for + # TupleVariable instead of tuple to make the type checker happy. + from .lists import TupleVariable + + if isinstance(cls, TupleVariable): + for item in cls.items: + r = generic_issubclass(tx, derived, item) + if isinstance(r, ConstantVariable) and r.value: + return ConstantVariable.create(True) + return ConstantVariable.create(False) + + # Allowlist short-circuit for Step 4: constant-fold via Python's + # issubclass for metaclasses whose ``__subclasscheck__`` Dynamo can't + # trace (see _CONSTANT_FOLD_SUBCLASSCHECK_METACLASSES). Note that ABCMeta + # is problematic in particular since it caches registered subclasses. + # Ideally this should be traced or guarded + if isinstance(cls_py, type) and issubclass( + type(cls_py), _CONSTANT_FOLD_SUBCLASSCHECK_METACLASSES + ): + try: + return ConstantVariable.create( + issubclass( + derived_py, # pyrefly: ignore [bad-argument-type] + cls_py, + ) + ) + except TypeError as e: + raise_observed_exception(TypeError, tx, args=list(e.args)) + + # TypeError gate, mirroring abstract.c L2822 ``recursive_issubclass``: + # CPython reaches that fallback when ``_PyObject_LookupSpecial`` for + # ``__subclasscheck__`` returns NULL, and its first action is + # ``check_class(cls, ...)`` which raises this TypeError. We check + # eagerly because Dynamo's ``call_method`` below would graph-break + # rather than cleanly signal "no such method". + if not isinstance(cls_py, type): + raise_type_error( + tx, + "issubclass() arg 2 must be a class, a tuple of classes, or a union", + ) + + # Step 4: general case — call ``__subclasscheck__`` on cls's metaclass + # (abstract.c L2801-2815). Runs user code on a custom metaclass. + result = cls.call_method(tx, "__subclasscheck__", [derived], {}) + + # Coerce to bool (PyObject_IsTrue, abstract.c L2812). + return generic_is_true(tx, result) + + +# ── tp_getattro ────────────────────────────────────────────────────── +# +# Dynamo's PyObject_GetAttr / PyObject_GenericGetAttr. +# +# CPython references: +# PyObject_GetAttr: Objects/object.c#L1259-L1283 +# PyObject_GenericGetAttr: Objects/object.c#L1611-L1683 +# _PyType_LookupRef: Objects/typeobject.c#L5208-L5262 +# +# PyObject_GetAttr(obj, name): +# tp = Py_TYPE(obj) +# if tp->tp_getattro: +# return tp->tp_getattro(obj, name) +# ... +# raise AttributeError +# +# Dispatch path: +# LOAD_ATTR / getattr() -> GetAttrBuiltinVariable -> generic_getattr +# -> obj.tp_getattro_impl(tx, name) +# +# The base VariableTracker.tp_getattro_impl tries object_generic_getattr() +# first (MRO walk + descriptor protocol), falling back to const_getattr +# on _UnhandledDescriptorError. Callers of object_generic_getattr +# directly must handle _UnhandledDescriptorError at every step (2, 4, +# and 7), not just for unrecognized descriptor types. +# +# VTs with custom tp_getattro (TensorVariable, NNModuleVariable, +# UserDefinedClassVariable, SuperVariable) override tp_getattro_impl. + +_NO_DEFAULT = object() + + +_UnhandledDescriptorError = UnhandledDescriptorError + + +def mro_lookup(py_type: type, name: str) -> object: + """Walk py_type.__mro__ to find *name* in the class hierarchy. + + Mirrors CPython's _PyType_LookupRef (Objects/typeobject.c). + Searches only the class chain (py_type.__mro__), NOT the metaclass + chain. Returns the raw descriptor/value from the class __dict__, + or NO_SUCH_SUBOBJ if not found. + """ + for base in py_type.__mro__: + if name in base.__dict__: + return base.__dict__[name] + return NO_SUCH_SUBOBJ + + +def _resolve_descriptor_get( + tx: "InstructionTranslatorBase", + type_attr: object, + obj: VariableTracker, + class_vt: VariableTracker, + source: "Source | None", +) -> "VariableTracker | None": + """Invoke tp_descr_get on a type attribute if it's a descriptor. + + Handles all descriptor types that have dedicated VTs with + tp_descr_get_impl. Returns None if type_attr is not a recognized + descriptor type (plain class variable). + """ + import types as _types + + if isinstance(type_attr, property): + prop_vt = variables.PropertyVariable(type_attr, source=source) + return prop_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.MemberDescriptorType): + md_vt = variables.MemberDescriptorVariable(type_attr, source=source) + return md_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.GetSetDescriptorType): + gs_vt = variables.GetSetDescriptorVariable(type_attr, source=source) + return gs_vt.tp_descr_get_impl(tx, obj, class_vt) + _tuplegetter = collections._tuplegetter # pyrefly: ignore[missing-attribute] + if isinstance(type_attr, _tuplegetter): + tg_vt = variables.TupleGetterVariable(type_attr, source=source) + return tg_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, staticmethod): + sm_vt = variables.StaticMethodVariable(type_attr, source=source) + return sm_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, classmethod): + cm_vt = variables.ClassMethodVariable(type_attr, source=source) + return cm_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.ClassMethodDescriptorType): + cmd_vt = variables.ClassMethodDescriptorVariable(type_attr, source=source) + return cmd_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.WrapperDescriptorType): + wd_vt = variables.WrapperDescriptorVariable( + type_attr, owner=class_vt, source=source + ) + return wd_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.MethodDescriptorType): + md_vt = variables.MethodDescriptorVariable( + type_attr, owner=class_vt, source=source + ) + return md_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.FunctionType): + return variables.UserMethodVariable(type_attr, obj, source=source) + + return None + + +# BuiltinFunctionType is intentionally excluded: _resolve_descriptor_get +# does not handle it, so it falls through to _UnhandledDescriptorError +# and generic_getattr's GetAttrVariable fallback. +_METHOD_TYPES = ( + types.FunctionType, + types.MethodDescriptorType, + types.WrapperDescriptorType, +) + + +def _is_method_type(type_attr: object) -> bool: + return isinstance(type_attr, _METHOD_TYPES) + + +def _has_custom_call_method(obj: VariableTracker) -> bool: + for cls in type(obj).__mro__: + if cls is VariableTracker: + return False + if "call_method" in cls.__dict__: + return True + return False + + +def object_generic_getattr( + tx: "InstructionTranslatorBase", + obj: VariableTracker, + name: str, +) -> VariableTracker: + """Dynamo's PyObject_GenericGetAttr. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L1611-L1683 + + Implements the standard attribute lookup algorithm using the VT's + python_type() for MRO walking, and hooks on the VT for instance dict + and __getattr__ fallback. + + Steps: + 1. MRO walk on python_type() for type_attr + 2. Data descriptor -> invoke tp_descr_get + 3. Instance dict -> obj.lookup_instance_dict(tx, name) + 4. Non-data descriptor -> invoke tp_descr_get + 5. Plain class variable -> wrap in VT + 6. __getattr__ fallback -> obj.call_getattr_fallback(tx, name) + 7. AttributeError + """ + from .user_defined import is_data_descriptor + + py_type = obj.python_type() + source = obj.source and AttrSource(obj.source, name) + + # Step 1: MRO walk. + type_attr = mro_lookup(py_type, name) + + # Step 2: Data descriptor takes priority over instance dict. + if type_attr is not NO_SUCH_SUBOBJ and is_data_descriptor(type_attr): + class_vt = VariableTracker.build(tx, py_type) + result = _resolve_descriptor_get(tx, type_attr, obj, class_vt, source) + if result is not None: + return result + raise _UnhandledDescriptorError( + f"object_generic_getattr: unhandled data descriptor " + f"{type(type_attr)} for {name}" + ) + + # Step 3: Instance dict (tp_dictoffset). + instance_result = obj.lookup_instance_dict(tx, name) + if instance_result is not None: + return instance_result + + # Step 4: Non-data descriptor with __get__. + if type_attr is not NO_SUCH_SUBOBJ and hasattr(type(type_attr), "__get__"): + # If the VT dispatches this method through call_method (a hand-written + # override or a tp_methods entry), return a CallMethodVariable that + # dispatches through call_method instead of inlining the resolved + # method directly. This preserves custom tracing logic (side effects, + # graph nodes, suppression) that MRO-based resolution via + # UserMethodVariable would bypass. + if _is_method_type(type_attr) and ( + obj._lookup_tp_table(name, "tp_methods") is not None + or _has_custom_call_method(obj) + ): + return variables.CallMethodVariable(obj, name, source=source) + + class_vt = VariableTracker.build(tx, py_type) + result = _resolve_descriptor_get(tx, type_attr, obj, class_vt, source) + if result is not None: + return result + raise _UnhandledDescriptorError( + f"object_generic_getattr: unhandled non-data descriptor " + f"{type(type_attr)} for {name}" + ) + + # Step 5: Plain class variable (no __get__). + if type_attr is not NO_SUCH_SUBOBJ: + return VariableTracker.build(tx, type_attr, source) + + # Step 6: __getattr__ fallback. + getattr_result = obj.call_getattr_fallback(tx, name) + if getattr_result is not None: + return getattr_result + + # Step 7: Attribute not found -- signal to caller to fall back. + raise _UnhandledDescriptorError( + f"object_generic_getattr: '{py_type.__name__}' has no attribute '{name}'" + ) + + +def generic_getattr( + tx: "InstructionTranslatorBase", + obj: VariableTracker, + name: str, + default: "VariableTracker | object" = _NO_DEFAULT, +) -> VariableTracker: + """Dynamo's PyObject_GetAttr: attribute access dispatch. + + Checks side effects for pending attribute mutations, then dispatches + to obj.tp_getattro_impl(tx, name). On NotImplementedError, falls back + to GetAttrVariable (deferred resolution). + """ + from .user_defined import is_data_descriptor + + # NOTE [Tensor "grad" and "_grad" attr] + if obj.is_tensor() and name == "_grad": + name = "grad" + + # Side effects: check for pending attribute mutations. + if tx.output.side_effects.has_pending_mutation_of_attr(obj, name): + if not isinstance(obj, variables.UserDefinedObjectVariable): + return tx.output.side_effects.load_attr(obj, name) + if tx.output.side_effects.has_pending_mutation_of_attr( + obj, name, AttrMutationKind.INSTANCE_DICT + ): + value = tx.output.side_effects.load_attr(obj, name, deleted_ok=True) + type_attr = obj.lookup_class_mro_attr(name) + if not isinstance(value, variables.DeletedVariable) and ( + type_attr is NO_SUCH_SUBOBJ or not is_data_descriptor(type_attr) + ): + return value + + # Handle default for getattr(obj, name, default). + if default is not _NO_DEFAULT: + hasattr_var = obj.call_obj_hasattr(tx, name) + if not hasattr_var.is_constant_match(True, False): + raise AssertionError( + f"hasattr_var must be a constant True or False, got {hasattr_var}" + ) + if not hasattr_var.as_python_constant(): + return default # type: ignore[return-value] + + # tp_getset/tp_members are data descriptors: resolve ahead of the VT's + # tp_getattro so a tp_getattro_impl override need not repeat the consult. + getset = obj.lookup_tp_getset_member(name) + if getset is not None: + result = getset.getter(obj, tx) + if result is not None: + return result + + # Core dispatch: call the VT's tp_getattro_impl (tp_getattro). + source = obj.source and AttrSource(obj.source, name) + try: + return obj.tp_getattro_impl(tx, name) + except AsPythonConstantNotImplementedError: + raise + except NotImplementedError: + return variables.GetAttrVariable(obj, name, source=source) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/optimizer.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..eb88bab39d81358c40752acd7ad7a469f31e8fd2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/optimizer.py @@ -0,0 +1,434 @@ +""" +This module implements variable tracking for PyTorch optimizers during Dynamo tracing. + +The OptimizerVariable class provides specialized handling for optimizer instances by: +- Optimizing the tracing of expensive optimizer initialization +- Managing optimizer state and parameter group tracking +- Handling tensor sources and guards for optimizer state tensors +- Supporting CUDA graph execution through static tensor address management +- Providing special handling for parameter gradients and optimizer state tensors + +Key features include: +- Efficient initialization tracing via _init_group optimization +- Automatic marking of optimizer state tensors as static for CUDA graphs +- Proper source tracking for parameter groups, gradients, and state tensors +- Guard installation for optimizer state structure +- Support for both CPU and GPU tensor handling +- Cleanup of static tensor references via finalizers + +The module integrates with Dynamo's broader tracing system while providing +optimizer-specific optimizations and safety guarantees. +""" + +import logging +import weakref +from collections.abc import Iterable +from typing import Any, TYPE_CHECKING + +import torch +from torch._dynamo.variables.tensor import TensorVariable +from torch._guards import Source +from torch._logging import getArtifactLogger +from torch.utils._pytree import tree_map_only + +from ..guards import GuardBuilder, install_guard +from ..source import ( + AttrSource, + ConstDictKeySource, + DictGetItemSource, + GetItemSource, + GlobalWeakRefSource, + GradSource, +) +from ..utils import GLOBAL_KEY_PREFIX, unpack_iterable +from .base import GetSet, VariableTracker +from .constant import ConstantVariable +from .dicts import ConstDictVariable +from .hashable import HashableTracker +from .lists import ListVariable +from .misc import GetAttrVariable +from .user_defined import UserDefinedObjectVariable + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +class ArgMappingException(Exception): + pass + + +class GuardInstallException(Exception): + pass + + +perf_hint_log = getArtifactLogger(__name__, "perf_hints") + + +def _is_static_for_cudagraphs(x: torch.Tensor) -> bool: + from torch._inductor.cudagraph_trees import get_manager + + if x.is_cuda: + manager = get_manager(x.device.index, False) + is_static_address = torch._dynamo.utils.get_static_address_type(x) is not None + if manager: + if manager.current_node is None: + raise AssertionError("CUDA graph manager has no current node") + return ( + is_static_address + or manager.current_node._is_cuda_graph_recorded_tensor(x) + ) + else: + return is_static_address + else: + # Don't print a warning for non-cuda tensors + return True + + +class OptimizerVariable(UserDefinedObjectVariable): + _nonvar_fields = { + "grad_to_source", + "tensor_to_source", + "static_tensor_names", + *UserDefinedObjectVariable._nonvar_fields, + } + + def __init__( + self, + value: torch.optim.Optimizer, + grad_to_source: dict[Any, GradSource] | None = None, + static_tensor_names: set[str] | None = None, + tensor_to_source: dict[torch.Tensor, Source] | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value, **kwargs) + # pyrefly: ignore [bad-override] + self.value: torch.optim.Optimizer = value + self.grad_to_source = grad_to_source or {} + self.tensor_to_source = tensor_to_source or {} + self.static_tensor_names = static_tensor_names or set() + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "VariableTracker": + """This is an optimization to avoid tracing the very slow initialization of the optimizer""" + if name == "_init_group": + if not hasattr(self.value, "_init_group"): + # Fallback: if the optimizer does not have _init_group, trace normally + return super().call_method(tx, name, args, kwargs) + try: + self.graph_break_if_pending_mutation(tx) + self.move_step_if_cpu() + py_args, py_kwargs = self.get_python_args(*args, **kwargs) + ret_val = self.value._init_group(*py_args, **py_kwargs) + self.map_sources_and_install_guards(tx) + self.update_list_args(tx, args, kwargs, py_args, py_kwargs) + # stash a weak_ptr to optimizer to invalidate code + # if the optimizer object dies + mangled_name = f"__optimizer_{id(self.value)}" + tx.store_global_weakref_by_id(mangled_name, self.value) + self.create_finalizer(tx) + + # This is currently safe only because the only actual `ret_val`s returned + # by the `_init_group` of existing optimizers are properties that are invariant + # to the input tensors (e.g. dtype, layout). Changing these would trigger a + # recompilation and hence never result in the wrong specialization of `ret_val`. + return ConstantVariable.create(ret_val) + except (ArgMappingException, GuardInstallException) as _: + # trace normally if we can't map args or install guards correctly + pass + + return super().call_method(tx, name, args, kwargs) + + # _init_group resolves to a GetAttrVariable so the call is intercepted in + # call_method (in the typical case, a UserMethodVariable would inline it). + def _get_init_group(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if not self.source: + raise AssertionError("OptimizerVariable requires a source for _init_group") + name = "_init_group" + py_type = type(getattr(self.value, name)) + return GetAttrVariable( + self, name, py_type=py_type, source=AttrSource(self.source, name) + ) + + # param_groups only runs setup side effects (static addresses, capturable + # guards) and declines, falling through to the generic protocol. + def _get_param_groups(self, tx: "InstructionTranslatorBase") -> None: + from ..decorators import mark_static_address + + for group in self.value.param_groups: + for p in group["params"]: + mark_static_address(p, guard=True) + + self._set_capturable(tx) + return None + + tp_getset = { + "_init_group": GetSet(_get_init_group), + "param_groups": GetSet(_get_param_groups), + } + + def graph_break_if_pending_mutation(self, tx: "InstructionTranslatorBase") -> None: + # If there are pending mutations on a parameter (due to using closure) + # then we need to graph break to allow the python version of the parameter + # to update, so that running _init_group will initialize the states with + # the correct values + for g in self.value.param_groups: + for p in g["params"]: + side_effects = tx.output.side_effects + variable = side_effects.id_to_variable.get(id(p), None) + if variable and side_effects.has_pending_mutation(variable): + from ..exc import unimplemented + + unimplemented( + gb_type="optimizer: pending mutation on parameter", + context=f"variable: {variable}, parameter: {p}", + explanation="Pending mutations on a parameter (e.g. due to using closure) require a graph break.", + hints=[], + ) + + def _set_capturable(self, tx: "InstructionTranslatorBase") -> None: + from . import LazyVariableTracker + + # We only set capturable if params are on cuda + # and the state is not initialized + def safe_to_set_capturable(group: dict[str, Any]) -> bool: + all_uninitialized = True + all_gpu = True + + for p in group.get("params", []): + all_gpu &= p.is_cuda or p.is_xpu + all_uninitialized &= p not in self.value.state + + return "capturable" in group and all_uninitialized and all_gpu + + # track indices to not set so we don't need to + # in the variable tracker realize the whole state + # we handle guarding the state specially + for group in self.value.param_groups: + if safe_to_set_capturable(group): + group["capturable"] = True + + source = self.source and AttrSource(self.source, "param_groups") + param_groups_vt = LazyVariableTracker.realize_all( + VariableTracker.build(tx, self.value.param_groups, source) + ) + for param_group_vt in param_groups_vt.items: + key = HashableTracker(ConstantVariable.create("capturable")) + param_group_vt.items[key] = ConstantVariable.create(True) + + def get_python_args( + self, *args: Any, **kwargs: Any + ) -> tuple[list[Any], dict[str, Any]]: + """Get python values equivalent to the variable tracker args""" + + def map_arg(arg: Any) -> Any: + if isinstance(arg, VariableTracker) and arg.is_python_constant(): + return arg.as_python_constant() + elif isinstance(arg, ListVariable) and not arg.items: + # pyrefly: ignore [implicit-any] + return [] + elif ( + isinstance(arg, ConstDictVariable) + and isinstance(arg.source, GetItemSource) + and isinstance(arg.source.base, AttrSource) + and arg.source.base.member == "param_groups" + ): + return self.value.param_groups[arg.source.index] + + raise ArgMappingException + + new_args = [map_arg(arg) for arg in args] + new_kwargs = {k: map_arg(v) for k, v in kwargs.items()} + + return new_args, new_kwargs + + # If users load an old state dictionary, + # it's possible that step could be on the cpu + # if this is the case, move it to the GPU + # corresponding to the parameter + # in most cases this is a no-op because the state is empty + def move_step_if_cpu(self) -> None: + for p, state in self.value.state.items(): + if "step" in state and state["step"].is_cpu: + state["step"] = state["step"].to(p.device) + + def map_sources_and_install_guards(self, tx: "InstructionTranslatorBase") -> None: + from ..decorators import mark_static_address + from .lazy import LazyVariableTracker + + self.grad_to_source = {} + self.tensor_to_source = {} + + def mark_static(x: Any) -> None: + mark_static_address(x, guard=True) + + tree_map_only(torch.Tensor, mark_static, self.value.state) + + # Recursively realize the variable trackers for optim.state and + # optim.param_groups, which recursively install the necessary guards. + params_groups_source = self.source and AttrSource(self.source, "param_groups") + param_groups_vt = LazyVariableTracker.realize_all( + VariableTracker.build(tx, self.value.param_groups, params_groups_source) + ) + + state_source = self.source and AttrSource(self.source, "state") + state_vt = VariableTracker.build(tx, self.value.state, state_source) + + # We need to realize the top level state dict to populate + # the guard locals + state_vt.realize() + if state_source is None: + raise AssertionError("state_source must not be None") + tx.output.guard_on_key_order.add(state_source) + + # Populate self.grad_to_source and self.tensor_to_source so that we can + # manually update_list_args + for group, group_vt in zip(self.value.param_groups, param_groups_vt.items): + # we assume here that all params within a param group + # are initialized similarly + if len(group["params"]) > 0: + for param in group["params"]: + if param.grad is not None: + key_index = None + for i, k in enumerate(self.value.state.keys()): + if k is param: + key_index = i + break + if key_index: + LazyVariableTracker.realize_all( + VariableTracker.build( + tx, + self.value.state[param], + DictGetItemSource( + state_source, + ConstDictKeySource(state_source, key_index), + ), + ) + ) + break + + params_vt = group_vt.getitem_const(tx, ConstantVariable.create("params")) + all_static = True + non_static_grads = [] + for p, p_vt in zip(group["params"], unpack_iterable(tx, params_vt)): + param_source = p_vt.source + if param_source is None: + raise AssertionError(f"param {p} does not have a source") + self.tensor_to_source[p] = param_source + grad_source = GradSource( + param_source, + "grad", + ) + + if p.grad is not None: + self.grad_to_source[p.grad] = grad_source + if not _is_static_for_cudagraphs(p.grad): + all_static = False + non_static_grads.append(grad_source) + else: + install_guard(grad_source.make_guard(GuardBuilder.CONSTANT_MATCH)) + + # Note: to avoid spam logs only warn if perf hint artifact is enabled + # (NB: artifacts are only enabled at the debug or warning level) + if not all_static and perf_hint_log.isEnabledFor(logging.DEBUG): + non_static_grad_names = [src.name for src in non_static_grads] + perf_hint_log.warning( + ( + "Grad tensors %s will be copied during cudagraphs execution." + "If using cudagraphs and the grad tensor addresses will be the same across runs," + " use torch._dynamo.decorators.mark_static_address to elide this copy.", + ), + non_static_grad_names, + ) + + # We have to again iterate over the state dict to collect the + # tensor_to_source dict. This is used for the finalizer. + for idx, value in enumerate(self.value.state.values()): + p_state_source = DictGetItemSource( + state_source, ConstDictKeySource(state_source, idx) + ) + tx.output.guard_on_key_order.add(p_state_source) + for inner_idx, v in enumerate(value.values()): + if ( + isinstance(v, torch.Tensor) + and v not in self.grad_to_source + and v not in self.tensor_to_source + ): + self.tensor_to_source[v] = DictGetItemSource( + p_state_source, ConstDictKeySource(p_state_source, inner_idx) + ) + + def wrap_tensor( + self, tx: "InstructionTranslatorBase", tensor_value: torch.Tensor + ) -> TensorVariable: + """Wrap state tensor in a TensorVariable""" + from ..decorators import mark_static_address + + # If we have a source for a tensor already use it, + # if we have not seen a tensor before, stash and use a + # global weak ref source, since it must be an optimizer tensor + # that we have missed + + if tensor_value in self.tensor_to_source: + # mark these tensors as static for cudagraphs + mark_static_address(tensor_value, guard=True) + source = self.tensor_to_source[tensor_value] + self.static_tensor_names.add(tx.output.module_key_name(source.name)) + elif tensor_value in self.grad_to_source: + source = self.grad_to_source[tensor_value] + else: + # mark these tensors as static for cudagraphs + mark_static_address(tensor_value, guard=True) + + global_name = tx.store_global_weakref_by_id(GLOBAL_KEY_PREFIX, tensor_value) + source = GlobalWeakRefSource(global_name) + self.static_tensor_names.add(tx.output.module_key_name(source.name)) + + return VariableTracker.build(tx, tensor_value, source) + + def update_list_args( + self, + tx: "InstructionTranslatorBase", + args: Iterable[VariableTracker], + kwargs: Any, + py_args: Iterable[Any], + py_kwargs: Any, + ) -> None: + """Update the args and kwargs to the traced optimizer call""" + for arg, py_arg in zip(args, py_args): + if isinstance(arg, ListVariable): + if not isinstance(py_arg, list): + raise AssertionError( + "py_arg should be a list in optimizer variable" + ) + for i, val in enumerate(py_arg): + tx.output.side_effects.mutation(arg) + if isinstance(val, torch.Tensor): + arg.items.append(self.wrap_tensor(tx, val)) + else: + source = arg.source and GetItemSource(arg.source, i) + arg.items.append(VariableTracker.build(tx, val, source)) + + def create_finalizer(self, tx: "InstructionTranslatorBase") -> None: + names_to_delete = self.static_tensor_names + value = self.value + tc = tx.output.tracing_context + + def init_finalizer(gm: torch.fx.GraphModule) -> None: + def clear_static_tensor_refs() -> None: + for name in names_to_delete: + gm._buffers.pop(name, None) + gm._parameters.pop(name, None) + if tc.params_flat: + tc.params_flat.clear() + if tc.params_flat_unwrap_subclasses: + tc.params_flat_unwrap_subclasses.clear() + + weakref.finalize(value, clear_static_tensor_refs) + + tx.output.add_graph_finalizer(init_finalizer) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/script_object.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/script_object.py new file mode 100644 index 0000000000000000000000000000000000000000..2630864cdae3b8b2565a20bf8a0561fdbdde0740 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/script_object.py @@ -0,0 +1,587 @@ +""" +This module implements variable tracking for TorchScript objects during Dynamo tracing. + +The CustomClassObjectVariable class provides specialized handling for TorchScript +objects with strong safety guarantees by: +- Enforcing method-call-only access to prevent unsafe attribute manipulation +- Converting graph breaks into hard errors via _raise_hard_error_if_graph_break +- Proper proxy and source tracking for TorchScript method calls +- Integration with higher-order operators for method call handling + +Key safety features: +- Strict validation that only method calls are allowed (no direct attribute access) +- Immediate error reporting for potentially unsafe operations +- Proper source tracking for debugging and guard installation +- Safe handling of TorchScript object method calls through torchbind + +The module ensures that TorchScript objects are handled safely during tracing +by limiting operations to known-safe patterns and failing fast for unsafe usage. +""" + +import enum +import functools +import inspect +import types +from collections.abc import Callable, Iterable +from typing import Any, TYPE_CHECKING, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch.utils._pytree as pytree +from torch._guards import Source +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import ( + get_member_type, + is_custom_class, + is_opaque_constant_type, + is_opaque_symbolic_type, + MemberType, + should_hoist, +) +from torch.fx.proxy import Proxy + +from .. import graph_break_hints +from ..eval_frame import skip_code +from ..exc import ( + raise_observed_exception, + unimplemented, + UnsafeScriptObjectError, + Unsupported, +) +from ..source import AttrSource +from ..utils import proxy_args_kwargs +from .base import VariableTracker +from .constant import ConstantVariable +from .dicts import ConstDictVariable +from .lists import TupleVariable +from .misc import LambdaVariable +from .user_defined import UserDefinedObjectVariable, UserDefinedVariable + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + +_P = ParamSpec("_P") +_T = TypeVar("_T") + + +def _raise_hard_error_if_graph_break( + reason: str, +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + def deco(fn: Callable[_P, _T]) -> Callable[_P, _T]: + @functools.wraps(fn) + def graph_break_as_hard_error(*args: _P.args, **kwargs: _P.kwargs) -> _T: + try: + return fn(*args, **kwargs) + except Unsupported as e: + raise UnsafeScriptObjectError(e.msg) from e + + return graph_break_as_hard_error + + return deco + + +class CustomClassVariable(UserDefinedVariable): + """ + A variable that represents an opaque object class (not instance). + Since UserDefinedClassVariable has some special handling for side effects, + we have a separate class here which will directly return the object when + __init__ is called. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + if isinstance(value, type) and issubclass(value, enum.Enum): + raise AssertionError( + f"Enum class {value} should use UserDefinedClassVariable, " + "not CustomClassVariable" + ) + super().__init__(**kwargs) + self.value = value + + def as_python_constant(self) -> Any: + return self.value + + def is_python_constant(self) -> bool: + # prevents constant folding of attribute accesses on + # opaque classes. this ensures tp_getattro_impl is called, + # allowing for proper validation and error handling + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CustomClassVariable wraps the CLASS, not an instance. + # Classes are always hashable in CPython (type.__hash__ = object.__hash__). + return hash(self.value), False + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: "VariableTracker", + reverse: bool = False, + ) -> "VariableTracker": + try: + other_val = other.as_python_constant() + except NotImplementedError: + return VariableTracker.build(tx, NotImplemented) + # pyrefly: ignore[bad-argument-count] + result = type(self.value).__or__(self.value, other_val) + if result is NotImplemented: + return VariableTracker.build(tx, NotImplemented) + return VariableTracker.build(tx, result) + + def as_proxy(self) -> Any: + return self.value + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.value})" + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + obj = None + try: + obj = inspect.getattr_static(self.value, name) + except AttributeError: + unimplemented( + gb_type="Attribute not found on opaque class", + context=f"class={self.value}, attr={name}", + explanation=f"The attribute '{name}' does not exist on opaque class {self.value}.", + hints=[ + f"Ensure '{name}' is a valid attribute of {type(self.value)}.", + ], + ) + + if isinstance(obj, staticmethod): + obj = obj.__get__(self.value) + elif isinstance(obj, property): + obj = obj.__get__(None, self.value) # pyrefly: ignore[no-matching-overload] + elif hasattr(obj, "__get__"): + if not isinstance(type(obj).__dict__.get("__get__"), types.FunctionType): + # C-level descriptors are safe to resolve dynamically. + obj = getattr(self.value, name) + else: + type_name = type(obj).__name__ + unimplemented( + gb_type="Unsupported descriptor on opaque class", + context=f"class={self.value}, attr={name}, descriptor={type_name}", + explanation=f"The attribute '{name}' is a descriptor of type '{type_name}' which is not supported.", + hints=[ + "Only staticmethod, property, and pybind11_static_property are supported.", + "Consider accessing this attribute outside of the compiled region.", + ], + ) + + if ConstantVariable.is_literal(obj): + return VariableTracker.build(tx, obj) + + source = AttrSource(self.source, name) if self.source else None + return VariableTracker.build(tx, obj, source) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # disallow creating reference-type opaque objects in the middle of the + # program + if is_opaque_symbolic_type(self.value): + # Skip __init__ to prevent dynamo from tracing it during resume. + # C extension types (e.g. torch._C.Generator) have wrapper_descriptor + # __init__ without __code__, so guard the skip_code call. + if hasattr(self.value.__init__, "__code__"): + skip_code(self.value.__init__.__code__) + + unimplemented( + gb_type="An opaque object was created in the middle of the program.", + context=f"Opaque object type: {self.value}.", + explanation=( + "Opaque objects cannot be created inside the torch.compile region. " + "They must be created before entering the compiled function." + ), + hints=[ + "Please create the opaque object before calling torch.compile " + "and pass it in as an argument or as a global variable." + ], + ) + + var_args = TupleVariable(list(args)) + var_kwargs = ConstDictVariable( + {VariableTracker.build(tx, k): v for k, v in kwargs.items()} + ) + if should_hoist(self.value): + with tx.output.tracing_context.guards_context.skip_guard_install(): + constant_args = var_args.as_python_constant() + constant_kwargs = var_kwargs.as_python_constant() + else: + constant_args = var_args.as_python_constant() + constant_kwargs = var_kwargs.as_python_constant() + opaque_obj = self.value( # pyrefly: ignore[not-callable] + *constant_args, **constant_kwargs + ) + + # Capture sources from the VT args so subgraph reuse can apply + # source replacement to resolve new ctor arg values on stamp-out. + ctor_arg_sources = tuple(getattr(a, "source", None) for a in args) + + if is_opaque_constant_type(type(opaque_obj)): + fake_script_obj = opaque_obj + else: + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + tx.output.fake_mode, opaque_obj + ) + + return CustomClassObjectVariable.create( + opaque_obj, + fake_script_obj, + (constant_args, constant_kwargs), + ctor_arg_sources=ctor_arg_sources, + tx=tx, + ) + + +class CustomClassObjectVariable(UserDefinedObjectVariable): + _fake_script_object_cache: dict[int, "CustomClassObjectVariable"] = {} + + @classmethod + def is_matching_cls(cls, user_cls: type) -> bool: + return ( + issubclass(user_cls, torch.ScriptObject) + or is_custom_class(user_cls) + or issubclass(user_cls, FakeScriptObject) + ) + + @staticmethod + def create( + proxy: Proxy, + value: Any, + ctor_args_kwargs: Any = None, + ctor_arg_sources: tuple[Source | None, ...] | None = None, + *, + tx: "InstructionTranslatorBase | None" = None, + **options: Any, + ) -> "CustomClassObjectVariable": + if isinstance(value, enum.Enum): + raise AssertionError( + f"Enum {type(value)} should use UserDefinedObjectVariable, not CustomClassObjectVariable" + ) + out = CustomClassObjectVariable( + proxy, value, ctor_args_kwargs, ctor_arg_sources=ctor_arg_sources, **options + ) + if isinstance(proxy, torch.fx.Proxy) and proxy.node.op != "placeholder": + if tx is None: + raise AssertionError( + "tx must be provided to CustomClassObjectVariable.create " + "when proxy is a real Proxy" + ) + tx.output.current_tracer.record_proxyable_vt(out) + return out + + def __init__( + self, + proxy: Proxy, + value: Any, + ctor_args_kwargs: Any = None, + source: Source | None = None, + ctor_arg_sources: tuple[Source | None, ...] | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value, **kwargs) + self.proxy = proxy + if isinstance(self.proxy, torch.fx.Proxy): + self.proxy.node.meta["example_value"] = value + self.source = source + # If the OpaqueObject is sourceless, then this is + # the constant (args, kwargs) that Dynamo used to construct it. + self.ctor_args_kwargs = ctor_args_kwargs + # Sources of the constructor args, used by subgraph reuse to + # resolve new values via source replacement on stamp-out. + self.ctor_arg_sources = ctor_arg_sources + + def as_proxy(self) -> Proxy: + if not isinstance(self.proxy, torch.fx.Proxy): + # If we have a hoisted value type, then lazily lift it to be a graph + # input when as_proxy() is called. + if not is_opaque_constant_type(type(self.proxy)): + raise AssertionError( + f"Expected opaque constant type, got {type(self.proxy)}" + ) + if should_hoist(type(self.proxy)): + from torch._dynamo.symbolic_convert import InstructionTranslator + + tx = InstructionTranslator.current_tx() + # if any kwargs (synthetic_graph_input doesn't support them yet) + # not a graph break because hard error more explicit here + # (and opaque objects are really just used for compile) + if self.ctor_args_kwargs[1]: + raise RuntimeError( + "NYI: hoisted opaque objects that accept kwargs, please pass as args" + ) + hoisted_vt = tx.output.synthetic_graph_input( + type(self.proxy), + self.ctor_args_kwargs[0], + ctor_arg_sources=self.ctor_arg_sources, + ) + self.proxy = hoisted_vt.as_proxy() + + return self.proxy + + def __str__(self) -> str: + value = ( + self.value.real_obj + if isinstance(self.value, FakeScriptObject) + else self.value + ) + return f"{self.__class__.__name__}({value})" + + __repr__ = __str__ + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: "VariableTracker", + op: str, + ) -> "VariableTracker": + from .constant import ConstantVariable + from .object_protocol import object_richcompare + + # Try value-based comparison first. CustomClassObjectVariable wraps + # pybind11 objects (e.g. Placement subclasses) whose C++ operator== + # does value comparison. Falling through to object_richcompare would + # use identity, returning wrong results (e.g. Shard(0) == Shard(0) + # would be False instead of True). + try: + self_val = self.as_python_constant() + except NotImplementedError: + return object_richcompare(self, tx, other, op) + try: + other_val = other.as_python_constant() + except NotImplementedError: + return ConstantVariable.create(NotImplemented) + try: + result = getattr(type(self_val), op)(self_val, other_val) + return ConstantVariable.create(result) + except Exception: + return ConstantVariable.create(NotImplemented) + + @_raise_hard_error_if_graph_break( + "Dynamo cannot safely trace script object due to graph break." + ) + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + from torch._higher_order_ops.torchbind import call_torchbind + + from .higher_order_ops import TorchHigherOrderOperatorVariable + + real_obj = self.as_python_constant() + real_obj_type = type(real_obj) + if is_custom_class(real_obj_type): + member_type = get_member_type(real_obj_type, name) + + if member_type == MemberType.USE_REAL: + value = getattr(real_obj, name) + if inspect.ismethod(value) or isinstance( + value, types.MethodWrapperType + ): + return LambdaVariable( + lambda *args, **kwargs: self.call_method(tx, name, args, kwargs) + ) + else: + return super().tp_getattro_impl(tx, name) + + elif member_type == MemberType.INLINED: + value = getattr(real_obj, name) + if ( + inspect.ismethod(value) + or isinstance(value, types.MethodWrapperType) + ) and self.source is None: + # When we don't have a source, fall back to call_method + # which creates a proxy node. + return LambdaVariable( + lambda *args, **kwargs: self.call_method(tx, name, args, kwargs) + ) + return super().tp_getattro_impl(tx, name) + + elif is_opaque_constant_type(real_obj_type): + return super().tp_getattro_impl(tx, name) + + elif name in ("__bool__", "__len__") and not hasattr(real_obj, name): + # Special case: __bool__ and __len__ are used for truthiness checks. + # If they're not registered and the real object doesn't have them, + # raise ObservedAttributeError so the caller can fall back to + # treating the object as truthy (Python default behavior + raise_observed_exception(AttributeError, tx) + + else: + unimplemented( + gb_type="Attempted to access unregistered member on an OpaqueObject", + context=f"value={real_obj}, attr={name}", + explanation=f"Member '{name}' is not registered for this opaque object type.", + hints=[ + f"Register '{name}' with a MemberType in register_custom_class(members=...).", + ], + ) + + method = getattr(self.value, name, None) + if method is None: + unimplemented( + gb_type="FakeScriptObject missing method implementation", + context=f"value={self.value}, method={name}", + explanation=f"TorchScript object {self.value} doesn't define the method {name}.", + hints=[ + f"Ensure the method {name} is implemented in {self.value}.", + *graph_break_hints.USER_ERROR, + ], + ) + + if not callable(method): + unimplemented( + gb_type="Attempted to access non-callable attribute of TorchScript object", + context=f"value={self.value}, method={name}", + explanation="Attribute accesses of TorchScript objects to non-callable attributes are not supported.", + hints=[ + "Use method calls instead of attribute access.", + ], + ) + + if self.source is None: + raise AssertionError( + "CustomClassObjectVariable requires a source for tp_getattro_impl" + ) + return TorchHigherOrderOperatorVariable.make( + call_torchbind, + source=AttrSource(self.source, name), + script_obj_var=self, + method_name=name, + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: "VariableTracker", + ) -> "VariableTracker": + # Call call_method directly on this class to avoid the __getitem__ → + # mp_subscript_impl loop in VariableTracker.call_method. + return CustomClassObjectVariable.call_method(self, tx, "__getitem__", [key], {}) + + # We only support method calls on script objects. Interpreting the bytecodes + # should go through tp_getattro_impl then call_function instead of call_method. + + # However, it's possible for call_method to be used directly e.g. for __setattr__. + @_raise_hard_error_if_graph_break( + "Dynamo cannot safely trace script object due to graph break." + ) + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: Iterable[Any], + kwargs: dict[str, Any], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + real_obj = self.as_python_constant() + real_obj_type = type(real_obj) + if is_custom_class(real_obj_type): + member_type = get_member_type(real_obj_type, name) + + if member_type == MemberType.USE_REAL: + if ( + inspect.getattr_static(real_obj_type, "__getattr__", None) + is not None + ): + unimplemented( + gb_type="Opaque object with custom __getattr__ not supported", + context=f"{real_obj_type.__name__} with custom __getattr__", + explanation="Dynamo does not support opaque objects types with custom __getattr__ methods", + hints=[], + ) + + args_const = [x.as_python_constant() for x in args] + kwargs_const = {k: v.as_python_constant() for k, v in kwargs.items()} + + method = getattr(real_obj, name) + + if name == "__setattr__": + method(*args_const, **kwargs_const) + return real_obj # pyrefly: ignore[bad-return] + + constant_val = method(*args_const, **kwargs_const) + + if any( + is_opaque_symbolic_type(type(r)) + for r in pytree.tree_leaves(constant_val) + ): + unimplemented( + gb_type="Opaque object member with method-type USE_REAL returned a reference-type opaque object.", + context=f"Opaque object type: {real_obj_type}. Method name: '{name}'", + explanation=( + "To properly guard reference-type opaque objects, " + "we must lift them as inputs to the graph. In order " + "to do this, they must all have a source, meaning they " + "come from a global value or are an attribute of an input." + ), + hints=[ + f"Register member '{name}' with MemberType.INLINED in " + f"register_custom_class({real_obj_type}, members=...).", + ], + ) + + return VariableTracker.build(tx, constant_val) + + elif member_type == MemberType.INLINED or is_opaque_constant_type( + real_obj_type + ): + proxy_args, proxy_kwargs = proxy_args_kwargs(args, kwargs) + + proxy = tx.output.create_proxy( + "call_method", + name, + args=(self.proxy, *proxy_args), + kwargs=proxy_kwargs, + ) + + return wrap_fx_proxy(tx=tx, proxy=proxy) + + else: + unimplemented( + gb_type="Attempted to access unregistered member on an OpaqueObject", + context=f"value={real_obj}, attr={name}", + explanation=f"Member '{name}' is not registered for this opaque object type.", + hints=[ + f"Register '{name}' with a MemberType in register_custom_class(members=...).", + ], + ) + + unimplemented( + gb_type="Weird method call on TorchScript object", + context=f"value={self.value}, method={name}", + explanation=( + f"This particular method call ({name}) is not supported (e.g. calling `__setattr__`). " + "Most method calls to TorchScript objects should be supported." + ), + hints=[ + "Avoid calling this method.", + ], + ) + + def as_python_constant(self) -> Any: + if isinstance(self.value, FakeScriptObject): + return self.value.real_obj + elif is_opaque_constant_type(type(self.value)): + return self.value + elif isinstance(self.value, torch.ScriptObject): + return self.value + return super().as_python_constant() + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + real_obj = self.as_python_constant() + try: + return hash(real_obj), False + except TypeError: + raise_type_error(tx, f"unhashable type: '{type(real_obj).__name__}'") + + def get_real_value(self) -> Any: + return self.as_python_constant() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sdpa.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sdpa.py new file mode 100644 index 0000000000000000000000000000000000000000..ef515365e5b360ef5628d915bac4f4a67fc900d3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sdpa.py @@ -0,0 +1,103 @@ +from inspect import getattr_static +from typing import Any, TYPE_CHECKING, TypeGuard + +from torch._guards import Source +from torch.backends.cuda import SDPAParams +from torch.fx.proxy import Proxy + +from ..bytecode_transformation import create_call_function +from ..exc import unimplemented +from ..source import AttrSource +from .base import VariableTracker + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + +PARAM_NAMES = [ + "query", + "key", + "value", + "attn_mask", + "dropout", + "is_causal", + "enable_gqa", +] + + +class SDPAParamsVariable(VariableTracker): + """Represents the c++ params struct for scaled dot product attention. + This is a read-only container.""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", value: Any, source: Source + ) -> VariableTracker: + from .torch import TorchInGraphFunctionVariable + + params = [ + VariableTracker.build(tx, getattr(value, p), AttrSource(source, p)) + for p in PARAM_NAMES + ] + return TorchInGraphFunctionVariable(SDPAParams).call_function(tx, params, {}) + + def __init__( + self, proxy: Proxy, param_vars: list[VariableTracker], **kwargs: Any + ) -> None: + self.proxy = proxy + self.param_vars = param_vars + super().__init__(**kwargs) + + def python_type(self) -> type: + return SDPAParams + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.source is not None: + raise AssertionError( + "SDPAParamsVariable should not have a source during reconstruct" + ) + if self.param_vars is None: + raise AssertionError("SDPAParamsVariable.param_vars must not be None") + codegen.add_push_null( + lambda: codegen.load_import_from("torch._C", "_SDPAParams") + ) + codegen.foreach(self.param_vars) + codegen.extend_output(create_call_function(len(self.param_vars), False)) + + def as_proxy(self) -> Proxy: + return self.proxy + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + import torch._C + + from .builder import wrap_fx_proxy + from .misc import GetAttrVariable + + try: + getattr_static(torch._C._SDPAParams, name) + except AttributeError: + import torch._dynamo.graph_break_hints as graph_break_hints + + unimplemented( + gb_type="unsupported torch._C._SDPAParams attribute", + context=f"name: {name}", + explanation=f"Unable to fetch attribute {name} from torch._C._SDPAParams.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + proxy = GetAttrVariable.create_getattr_proxy(self.as_proxy(), name) + if self.source is not None: + return wrap_fx_proxy( + tx=tx, proxy=proxy, source=AttrSource(self.source, name) + ) + else: + return wrap_fx_proxy(tx=tx, proxy=proxy) + + @staticmethod + def is_sdpa_params(value: Any) -> TypeGuard["SDPAParams"]: + return value is SDPAParams diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sets.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sets.py new file mode 100644 index 0000000000000000000000000000000000000000..e432240fe58eb7dbe8ba7bd6280a31bf80663307 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sets.py @@ -0,0 +1,1072 @@ +""" +Set-related variable tracking classes for PyTorch Dynamo. + +This module implements variable tracking for different types of set-like objects: +- Regular Python sets (set) +- Frozen sets (frozenset) +- Ordered sets (torch.utils._ordered_set.OrderedSet) +- Dictionary key sets (dict_keys views used as sets) + +These classes are responsible for tracking set operations during graph compilation, +maintaining proper guards for set mutations and element existence checks. + +The implementation uses a special HashableTracker wrapper to handle set elements +while preserving proper aliasing semantics. Sets are modeled internally as +dictionaries with None values. +""" + +import functools +import operator +from collections.abc import Iterable, Iterator +from typing import Any, TYPE_CHECKING + +from torch.utils._ordered_set import OrderedSet + +from .. import variables +from ..bytecode_transformation import create_call_function, create_instruction +from ..exc import raise_observed_exception, raise_type_error +from ..guards import GuardBuilder, install_guard +from ..source import is_constant_source, is_from_local_source +from ..utils import ( + _item_debug_repr, + cmp_name_to_op_mapping, + istype, + lazily_unpack, + raise_args_mismatch, + set_methods, + tracked_repr, + unpack_iterable, +) +from .base import Member, Method, ValueMutationNew, VariableTracker +from .constant import ConstantVariable +from .hashable import HashableTracker, is_hashable + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +# [Adding a new supported class within the keys of SetVariable] +# see steps outlined for ConstDictVariable + + +def pyanyset_check(obj: VariableTracker) -> bool: + return issubclass(obj.python_type(), (set, frozenset)) + + +def pyset_check(obj: VariableTracker) -> bool: + # ref: https://github.com/python/cpython/blob/v3.13.0/Include/setobject.h#L36-L38 + return issubclass(obj.python_type(), set) + + +def set_copy(obj: VariableTracker) -> VariableTracker: + """Mirrors CPython's internal `set_copy` (Objects/setobject.c). + + Always allocates a fresh set/frozenset with a shallow-copied items dict. + Distinct from the user-visible `.copy()` method, which preserves identity + for exact frozenset (`frozenset_copy`). Use this for binary-op scratch + storage so mutations don't bleed into the input. + """ + base = obj._base_vt if isinstance(obj, variables.UserDefinedSetVariable) else obj + if base is None: + raise AssertionError("_base_vt must not be None") + return base.clone( + items=base.items.copy(), # type: ignore[missing-attribute] + mutation_type=ValueMutationNew(), + source=None, + ) + + +class SetVariable(VariableTracker): + """Represents a Python set during symbolic execution.""" + + # PySet_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L2436 + _cpython_type = set + + CONTAINS_GUARD = GuardBuilder.SET_CONTAINS + NOT_CONTAINS_GUARD = GuardBuilder.SET_NOT_CONTAINS + + def __init__( + self, + items: Iterable[VariableTracker | HashableTracker], + **kwargs: Any, + ) -> None: + # .clone() passes these arguments in kwargs but they're recreated below + if "original_items" in kwargs: + kwargs.pop("original_items") + if "should_reconstruct_all" in kwargs: + kwargs.pop("should_reconstruct_all") + + super().__init__(**kwargs) + + # Items can be either VariableTrackers or HashableTrackers (from set ops). + # For VariableTrackers, realize them to ensure aliasing guards are installed + # when the same object appears multiple times. + hashable_items = [] + for item in items: + if isinstance(item, HashableTracker): + # Already a HashableTracker from a set operation + hashable_items.append(item) + else: + # VariableTracker - realize to install guards, then wrap + # pyrefly: ignore [bad-argument-type] + hashable_items.append(HashableTracker(item.realize())) + # Internal representation as dict allows for simple integration with + # OrderedSet, notably polyfills. Using set moves complexity to OrderedSet + self.items = dict.fromkeys(hashable_items, SetVariable._default_value()) + self.should_reconstruct_all = ( + not is_from_local_source(self.source) if self.source else True + ) + self.original_items = dict.fromkeys( + hashable_items, SetVariable._default_value() + ) + + def debug_repr(self) -> str: + if not self.items: + return "set()" + else: + items: list[str] = [] + for v in self.items: + vt = v.vt if isinstance(v, HashableTracker) else v + val_str = _item_debug_repr(vt) + items.append(val_str) + return "{" + ", ".join(items) + "}" + + @property + def set_items(self) -> set["HashableTracker"]: + return set(self.items.keys()) + + @staticmethod + def _default_value() -> VariableTracker: + # Variable to fill in the keys of the dictionary + return ConstantVariable.create(None) + + def as_proxy(self) -> Any: + return {k.vt.as_proxy() for k in self.set_items} + + def python_type(self) -> type: + return set + + def is_python_constant(self) -> bool: + # Avoid the base implementation, which probes as_python_constant() and + # thus rebuilds a real set, re-hashing the elements (wrong for elements + # with a side-effecting __hash__). Check element constness directly. + return all(k.vt.is_python_constant() for k in self.set_items) + + def as_python_constant(self) -> Any: + return {k.vt.as_python_constant() for k in self.set_items} + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L763-L822 + if not self.items: + return VariableTracker.build(tx, f"{self.python_type_name()}()") + items = ", ".join(tracked_repr(tx, item.vt) for item in self.set_items) + return VariableTracker.build(tx, "{" + items + "}") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.foreach([x.vt for x in self.set_items]) + codegen.append_output(create_instruction("BUILD_SET", arg=len(self.set_items))) + + def __contains__(self, vt: VariableTracker) -> bool: + if not isinstance(vt, VariableTracker): + raise AssertionError(f"Expected VariableTracker, got {type(vt)}") + # Use is_hashable as a side-effect-free pre-check. We can't catch + # ObservedTypeError from HashableTracker because it modifies + # tx.exn_vt_stack as a side effect. + if not is_hashable(vt): + return False + key = HashableTracker(vt) + return key in self.items + + def has_new_items(self) -> bool: + return self.should_reconstruct_all or any( + # pyrefly: ignore [bad-argument-type] + self.is_new_item(self.original_items.get(key.vt), value) + for key, value in self.items.items() + ) + + def is_new_item( + self, value: VariableTracker | None, other: VariableTracker + ) -> bool: + if value and value.is_realized() and other.is_realized(): + return id(value.realize()) != id(other.realize()) + return id(value) != id(other) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return [x.vt for x in self.items] + + def clone(self, **kwargs: Any) -> VariableTracker: + from torch._dynamo.variables.base import AttributeMutationNew, ValueMutationNew + + if isinstance( + kwargs.get("mutation_type"), (ValueMutationNew, AttributeMutationNew) + ): + kwargs["source"] = None + return super().clone(**kwargs) + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, f"unhashable type: '{self.python_type_name()}'") + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + return VariableTracker.build(tx, hasattr(self.python_type(), name)) + + def install_set_contains_guard( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker] + ) -> None: + if not self.source: + return + + if tx.output.side_effects.is_modified(self): + return + + contains = args[0] in self + if args[0].source is None and args[0].is_python_constant(): + guard_fn = ( + type(self).CONTAINS_GUARD if contains else type(self).NOT_CONTAINS_GUARD + ) + install_guard( + self.make_guard( + functools.partial( + guard_fn, + key=args[0].as_python_constant(), + ) + ) + ) + + def _fast_set_method( + self, + tx: "InstructionTranslatorBase", + fn: Any, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + try: + res = fn( + *[x.as_python_constant() for x in [self, *args]], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + except Exception as exc: + raise_observed_exception(type(exc), tx, args=list(exc.args)) + return VariableTracker.build(tx, res) + + def _iter_operand_keys( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> "Iterator[HashableTracker]": + # Lazily yield HashableTracker keys for a set-operation operand, one + # element at a time so callers that short-circuit (isdisjoint) observe + # the same generator side effects as CPython. A set or dict operand's + # keys are reused directly (no re-hashing), mirroring CPython's + # set_update_internal fast path for set/frozenset/dict operands. + # HashableTracker raises ObservedTypeError for an unhashable element, + # matching CPython's hash-at-insert behavior. + from .dicts import ConstDictVariable + + if isinstance(other, (SetVariable, ConstDictVariable)): + yield from other.items.keys() + return + + yield from (HashableTracker(item) for item in lazily_unpack(tx, other)) + + def _operand_keys( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> list[HashableTracker]: + # Eager variant: unpack_iterable takes the fast unpack_var_sequence + # path for builtin iterables instead of the per-element iterator + # protocol. + from .dicts import ConstDictVariable + + if isinstance(other, (SetVariable, ConstDictVariable)): + return list(other.items.keys()) + return [HashableTracker(x) for x in unpack_iterable(tx, other)] + + def _new_set(self, items: "Iterable[HashableTracker]") -> "SetVariable": + # Build a fresh set of the same concrete type (set / frozenset / + # OrderedSet). list() preserves insertion order, which matters for + # OrderedSet. + return type(self)(list(items), mutation_type=ValueMutationNew()) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L2131-L2149 + if not is_hashable(item): + # Mirror CPython's set_contains: if hashing fails with TypeError due to + # an unhashable set, coerce the key to frozenset and retry. + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L2151-L2159 + if not pyset_check(item): + raise_type_error(tx, f"unhashable type: '{item.python_type_name()}'") + # CPython NOTE: + # Note that 'key' could be a set() or frozenset() object. Unlike most + # container types, set allows membership testing with a set key, even + # though it is not hashable. + item = FrozensetVariable(item.items) # type: ignore[missing-attribute] + self.install_set_contains_guard(tx, [item]) + contains = item in self + return VariableTracker.build(tx, contains) + + def _try_fast_set_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "VariableTracker | None": + from ..utils import check_constant_args + from .dicts import ConstDictVariable + + # Constant, exact-builtin fast path: materialize and call the real + # method. Set/dict operands take the slow VT path below so their keys + # are not re-hashed (CPython's do-not-rehash-dict-keys fast path); + # OrderedSet is excluded because as_python_constant() loses insertion + # order (it routes through the unordered set_items). + if ( + not any(isinstance(a, (SetVariable, ConstDictVariable)) for a in args) + and check_constant_args(args, kwargs) + and self.python_type() in (set, frozenset) + ): + py_type = self.python_type() + return self._fast_set_method(tx, getattr(py_type, name), args, kwargs) + return None + + def add( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Convert add to __setitem__ with None value + tx.output.side_effects.mutation(self) + self.items[HashableTracker(args[0])] = SetVariable._default_value() + return ConstantVariable.create(None) + + def pop( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Choose an item at random and pop it + try: + result: VariableTracker = self.set_items.pop().vt # type: ignore[assignment] + except KeyError as e: + raise_observed_exception(KeyError, tx, args=list(e.args)) + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + self.items.pop(HashableTracker(result)) + return result + + def isdisjoint( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fast = self._try_fast_set_method(tx, "isdisjoint", args, kwargs) + if fast is not None: + return fast + for key in self._iter_operand_keys(tx, args[0]): + if key in self.items: + return ConstantVariable.create(False) + return ConstantVariable.create(True) + + def intersection( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fast = self._try_fast_set_method(tx, "intersection", args, kwargs) + if fast is not None: + return fast + out_items = dict(self.items) + for other in args: + other_keys = set(self._operand_keys(tx, other)) + out_items = {k: v for k, v in out_items.items() if k in other_keys} + return self._new_set(out_items) + + def intersection_update( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + kept = dict(self.items) + for other in args: + other_keys = set(self._operand_keys(tx, other)) + kept = {k: v for k, v in kept.items() if k in other_keys} + tx.output.side_effects.mutation(self) + self.should_reconstruct_all = True + self.items.clear() + self.items.update(kept) + return ConstantVariable.create(None) + + def union( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fast = self._try_fast_set_method(tx, "union", args, kwargs) + if fast is not None: + return fast + out_items = dict(self.items) + for other in args: + for key in self._operand_keys(tx, other): + out_items.setdefault(key, SetVariable._default_value()) + return self._new_set(out_items) + + def difference( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fast = self._try_fast_set_method(tx, "difference", args, kwargs) + if fast is not None: + return fast + out_items = dict(self.items) + for other in args: + for key in self._operand_keys(tx, other): + out_items.pop(key, None) + return self._new_set(out_items) + + def difference_update( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.side_effects.mutation(self) + self.should_reconstruct_all = True + for other in args: + for key in self._operand_keys(tx, other): + self.items.pop(key, None) + return ConstantVariable.create(None) + + def symmetric_difference( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fast = self._try_fast_set_method(tx, "symmetric_difference", args, kwargs) + if fast is not None: + return fast + other = dict.fromkeys( + self._operand_keys(tx, args[0]), SetVariable._default_value() + ) + out_items = {k: v for k, v in self.items.items() if k not in other} + out_items.update({k: v for k, v in other.items() if k not in self.items}) + return self._new_set(out_items) + + def symmetric_difference_update( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + other = dict.fromkeys( + self._operand_keys(tx, args[0]), SetVariable._default_value() + ) + new_items = {k: v for k, v in self.items.items() if k not in other} + new_items.update({k: v for k, v in other.items() if k not in self.items}) + tx.output.side_effects.mutation(self) + self.should_reconstruct_all = True + self.items.clear() + self.items.update(new_items) + return ConstantVariable.create(None) + + def update( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + if not self.is_mutable(): + return None + tx.output.side_effects.mutation(self) + for other in args: + for key in self._operand_keys(tx, other): + self.items.setdefault(key, SetVariable._default_value()) + return ConstantVariable.create(None) + + def remove( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if not self.sq_contains_impl(tx, args[0]).as_python_constant(): + raise_observed_exception(KeyError, tx, args=[args[0]]) + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + # sq_contains validated/normalized args[0]; a set key was coerced to + # a frozenset, so pop that same normalized key. + key = args[0] if is_hashable(args[0]) else FrozensetVariable(args[0].items) # type: ignore[missing-attribute] + self.items.pop(HashableTracker(key)) + return ConstantVariable.create(None) + + def discard( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.sq_contains_impl(tx, args[0]).as_python_constant(): + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + # sq_contains validated/normalized args[0]; a set key was coerced + # to a frozenset, so pop that same normalized key. + key = ( + args[0] if is_hashable(args[0]) else FrozensetVariable(args[0].items) # type: ignore[missing-attribute] + ) + self.items.pop(HashableTracker(key)) + return ConstantVariable.create(None) + + def _ordering_test(self, tx, args, op): + from .builder import SourcelessBuilder + + other = args[0].realize() + if not istype(other, SetVariable): + other = SourcelessBuilder.create(tx, set).call_function(tx, [other], {}) + return SourcelessBuilder.create(tx, op).call_function(tx, [self, other], {}) + + def issubset( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._ordering_test(tx, args, operator.le) + + def issuperset( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._ordering_test(tx, args, operator.ge) + + def copy( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return set_copy(self) + + def clear( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + self.items.clear() + return ConstantVariable.create(None) + + tp_methods = { + "add": Method(add), + "pop": Method(pop), + "isdisjoint": Method(isdisjoint), + "intersection": Method(intersection), + "intersection_update": Method(intersection_update), + "union": Method(union), + "difference": Method(difference), + "difference_update": Method(difference_update), + "symmetric_difference": Method(symmetric_difference), + "symmetric_difference_update": Method(symmetric_difference_update), + "update": Method(update), + "remove": Method(remove), + "discard": Method(discard), + "issubset": Method(issubset), + "issuperset": Method(issuperset), + "copy": Method(copy), + "clear": Method(clear), + } + + def getitem_const( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + raise RuntimeError("Illegal to getitem on a set") + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import SourcelessBuilder + + temp_set_vt = SourcelessBuilder.create(tx, set).call_set(tx, *args, **kwargs) + tx.output.side_effects.mutation(self) + self.items.clear() + self.items.update(temp_set_vt.items) # type: ignore[attr-defined] + return ConstantVariable.create(None) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .iter import SetIterator + + if self.source and not is_constant_source(self.source): + tx.output.guard_on_key_order.add(self.source) + return SetIterator(self.items) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1318-L1338 + self_, other_ = (other, self) if reverse else (self, other) + + if not pyanyset_check(self_) or not pyanyset_check(other_): + return ConstantVariable.create(NotImplemented) + + result = set_copy(self_) + if self_ is other_: + return result + result.items.update(other_.items) # type: ignore[missing-attribute] + return result + + def nb_inplace_or_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1340-L1350 + if not pyanyset_check(other): + return ConstantVariable.create(NotImplemented) + + tx.output.side_effects.mutation(self) + self.items.update(other.items) # type: ignore[missing-attribute] + return self + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L1801-L1812 + self_, other_ = (other, self) if reverse else (self, other) + + if not pyanyset_check(self_) or not pyanyset_check(other_): + return ConstantVariable.create(NotImplemented) + + result = set_copy(self_) + for k in list(other_.items.keys()): # type: ignore[missing-attribute] + result.items.pop(k, None) # type: ignore[missing-attribute] + return result + + def nb_inplace_subtract_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L1814-L1828 + if not pyanyset_check(other): + return ConstantVariable.create(NotImplemented) + + tx.output.side_effects.mutation(self) + for k in list(other.items.keys()): # type: ignore[missing-attribute] + self.items.pop(k, None) + return self + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1506-L1518 (set_and) + self_, other_ = (other, self) if reverse else (self, other) + + if not pyanyset_check(self_) or not pyanyset_check(other_): + return ConstantVariable.create(NotImplemented) + + return self_.call_method(tx, "intersection", [other_], {}) + + def nb_inplace_and_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1520-L1536 (set_iand) + if not pyanyset_check(other): + return ConstantVariable.create(NotImplemented) + + self.call_method(tx, "intersection_update", [other], {}) + return self + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1984-L1990 (set_xor) + self_, other_ = (other, self) if reverse else (self, other) + + if not pyanyset_check(self_) or not pyanyset_check(other_): + return ConstantVariable.create(NotImplemented) + + return self_.call_method(tx, "symmetric_difference", [other_], {}) + + def nb_inplace_xor_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1992-L2004 (set_ixor) + if not pyanyset_check(other): + return ConstantVariable.create(NotImplemented) + + self.call_method(tx, "symmetric_difference_update", [other], {}) + return self + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return VariableTracker.build(tx, len(self.set_items)) + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """set_richcompare: subset/superset comparisons for all 6 ops. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/setobject.c#L2097 + CPython uses PyAnySet_Check: only accepts set/frozenset (not dict views). + """ + if not isinstance(other, SetVariable): + try: + other_type = other.python_type() + except NotImplementedError: + return ConstantVariable.create(NotImplemented) + if not issubclass(other_type, (set, frozenset)): + return ConstantVariable.create(NotImplemented) + + # Accessing set_items directly is correct: CPython's set_richcompare + # operates on the internal C struct (PySet_GET_SIZE, set_next, + # set_contains_entry) -- it never calls __len__ or __contains__. + # https://github.com/python/cpython/blob/e76aa128fe/Objects/setobject.c#L2093-L2130 + self_items = self.set_items + other_items = other.set_items # type: ignore[attr-defined] + if op == "__eq__": + # len check + issubset: same length and subset implies equality. + if len(self_items) != len(other_items): + return ConstantVariable.create(False) + return VariableTracker.build(tx, self_items <= other_items) + elif op == "__ne__": + if len(self_items) != len(other_items): + return ConstantVariable.create(True) + return VariableTracker.build(tx, not (self_items <= other_items)) + else: + return VariableTracker.build( + tx, + cmp_name_to_op_mapping[op](self_items, other_items), + ) + + +class OrderedSetClassVariable(VariableTracker): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + def as_python_constant(self) -> type[OrderedSet[Any]]: + return OrderedSet + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__new__": + if len(args) != 2 or kwargs: + raise_args_mismatch( + tx, + name, + "OrderedSet.__new__ only accepts one arg" + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + return variables.OrderedSetVariable([], mutation_type=ValueMutationNew()) + + resolved_fn = getattr(set, name) + if resolved_fn in set_methods and isinstance(args[0], variables.SetVariable): + return args[0].call_method(tx, name, args[1:], kwargs) + + return super().call_method(tx, name, args, kwargs) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "OrderedSetVariable": + if len(args) > 1 or kwargs: + raise_args_mismatch( + tx, + "OrderedSet", + "OrderedSet only accepts one arg" + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + if len(args) == 0: + # pyrefly: ignore [implicit-any] + items = [] + else: + items = unpack_iterable(tx, args[0]) + return variables.OrderedSetVariable(items, mutation_type=ValueMutationNew()) + + +class OrderedSetVariable(SetVariable): + _cpython_type = OrderedSet + + def method_flags_type(self) -> type: + # OrderedSet is pure-Python (no C ml_flags); its named methods mirror + # set's arities, so derive MethodFlags from set to enforce them. + return set + + def _get_internal_dict(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # OrderedSet is backed by a dict (self._dict). Expose it so inlined + # OrderedSet methods (e.g. __contains__ -> `elem in self._dict`) trace + # natively instead of graph-breaking on an unmodeled attribute. + from .dicts import ConstDictVariable + + return ConstDictVariable(self.items, mutation_type=ValueMutationNew()) # type: ignore[bad-argument-type] + + tp_members = {"_dict": Member(_get_internal_dict, None)} + + def debug_repr(self) -> str: + if not self.items: + return "OrderedSet([])" + else: + items: list[str] = [] + for k in self.items: + key_str = _item_debug_repr(k.vt) + items.append(key_str) + return "OrderedSet([" + ", ".join(items) + "])" + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + items = ", ".join(tracked_repr(tx, item.vt) for item in self.set_items) + return VariableTracker.build(tx, f"{self.python_type_name()}([{items}])") + + def as_python_constant(self) -> OrderedSet[Any]: + return OrderedSet([k.vt.as_python_constant() for k in self.set_items]) + + def python_type(self) -> type[OrderedSet[Any]]: + return OrderedSet + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from("torch.utils._ordered_set", "OrderedSet") + ) + codegen.foreach([x.vt for x in self.set_items]) + codegen.append_output(create_instruction("BUILD_LIST", arg=len(self.set_items))) + codegen.extend_output(create_call_function(1, False)) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # OrderedSet does not inherit from Python set, so SetVariable.nb_or_impl + # won't work due to the PyAnySet_Check + return super().call_method(tx, "union", [other], {}) + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # OrderedSet does not inherit from Python set, so SetVariable.nb_and_impl + # won't work due to the PyAnySet_Check + return super().call_method(tx, "intersection", [other], {}) + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # OrderedSet does not inherit from Python set, so SetVariable.nb_xor_impl + # won't work due to the PyAnySet_Check + return super().call_method(tx, "symmetric_difference", [other], {}) + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + self_, other_ = (other, self) if reverse else (self, other) + return self_.call_method(tx, "difference", [other_], {}) + + def nb_inplace_subtract_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + tx.output.side_effects.mutation(self) + self.call_method(tx, "difference_update", [other], {}) + return self + + +class FrozensetVariable(SetVariable): + # PyFrozenSet_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L2526 + _cpython_type = frozenset + + nb_inplace_subtract_impl = None # type: ignore[bad-override] + + def debug_repr(self) -> str: + if not self.items: + return "frozenset()" + else: + items: list[str] = [] + for k in self.items: + key_str = _item_debug_repr(k.vt) + items.append(key_str) + return "frozenset({" + ", ".join(items) + "})" + + @property + def set_items(self) -> set["HashableTracker"]: + return set(self.items.keys()) + + def python_type(self) -> type: + return frozenset + + def as_python_constant(self) -> Any: + return frozenset({k.vt.as_python_constant() for k in self.set_items}) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L763-L822 + if not self.items: + return VariableTracker.build(tx, f"{self.python_type_name()}()") + items = ", ".join(tracked_repr(tx, item.vt) for item in self.set_items) + return VariableTracker.build(tx, f"{self.python_type_name()}({{{items}}})") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_global("frozenset"), + ] + ) + ) + codegen.foreach([x.vt for x in self.set_items]) + codegen.extend_output( + [ + create_instruction("BUILD_LIST", arg=len(self.set_items)), + *create_call_function(1, False), + ] + ) + + def copy( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if type(self) is FrozensetVariable: + return self + return SetVariable.copy(self, tx, args, kwargs) + + def difference( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + r = SetVariable.difference(self, tx, args, kwargs) + return FrozensetVariable(r.items) # type: ignore[attr-defined] + + def intersection( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + r = SetVariable.intersection(self, tx, args, kwargs) + return FrozensetVariable(r.items) # type: ignore[attr-defined] + + def symmetric_difference( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + r = SetVariable.symmetric_difference(self, tx, args, kwargs) + return FrozensetVariable(r.items) # type: ignore[attr-defined] + + tp_methods = { + "copy": Method(copy), + "difference": Method(difference), + "intersection": Method(intersection), + "symmetric_difference": Method(symmetric_difference), + } + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # frozenset is immutable. Calling __init__ again shouldn't have any effect. + return ConstantVariable.create(None) + + def is_hashable(self) -> bool: + return True + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # Overrides SetVariable.hash_impl (which raises TypeError for mutable sets). + # CPython frozenset_hash: https://github.com/python/cpython/blob/e76aa128fe/Objects/setobject.c#L769 + from .hashable import RawHash + from .object_protocol import generic_hash_impl + + if self.is_python_constant(): + return hash(self.as_python_constant()), False + is_fake = False + raw_hashes = [] + for item in self.set_items: + h, fake = generic_hash_impl(tx, item.vt) + is_fake = is_fake or fake + raw_hashes.append(RawHash(h)) + return hash(frozenset(raw_hashes)), is_fake + + +class DictKeySetVariable(SetVariable): + def debug_repr(self) -> str: + if not self.items: + return "dict_keys([])" + else: + items: list[str] = [] + for k in self.items: + key_str = _item_debug_repr(k.vt) + items.append(key_str) + return "dict_keys([" + ", ".join(items) + "])" + + def install_set_contains_guard( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker] + ) -> None: + # Already EQUALS_MATCH guarded + pass + + @property + def set_items(self) -> Any: + return self.items + + def python_type(self) -> type: + from ..utils import dict_keys + + return dict_keys + + def as_python_constant(self) -> Any: + return dict.fromkeys( + {k.vt.as_python_constant() for k in self.set_items}, None + ).keys() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/streams.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..f445d050e2f370c39ae98c7d7fb7bc34d5223288 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/streams.py @@ -0,0 +1,842 @@ +import collections +from collections.abc import Callable +from typing import Any, Optional + +import torch +from torch._dynamo.variables.dicts import ConstDictVariable +from torch._dynamo.variables.lists import TupleVariable +from torch.fx import has_side_effect, Proxy + +from .. import graph_break_hints +from ..bytecode_transformation import create_call_function +from ..exc import TYPE_CHECKING, unimplemented +from ..graph_bytecode_inputs import ( + CURRENT_STREAM_INDEX, + get_external_object_by_index, + register_graph_created_object, + register_user_object, + reset_user_object_tracking, +) +from ..source import CurrentStreamSource +from .base import GetSet, Method, VariableTracker +from .constant import ConstantVariable +from .ctx_manager import FxTracebackAnnotateVariable +from .lazy import LazyVariableTracker + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from ..codegen import PyCodegen + +from torch._library.custom_ops import custom_op + + +Tensor = torch.Tensor + + +def new_event(*args: Any, **kwargs: Any) -> int: + event = torch.Event(*args, **kwargs) + return register_graph_created_object( + event, + EventVariable.make_construct_in_graph_event_fn( + TupleVariable([]), ConstDictVariable({}) + ), + ) + + +def new_stream(*args: tuple[Any], **kwargs: Any) -> int: + stream = torch.Stream(*args, **kwargs) # type: ignore[no-matching-overload,call-overload] + return register_graph_created_object( + stream, + StreamVariable.make_construct_in_graph_stream_fn( + TupleVariable([]), ConstDictVariable({}) + ), + ) + + +def _codegen_current_stream(device: torch.device, cg: "PyCodegen") -> None: + cg.add_push_null( + lambda: cg.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, # type: ignore[implicit-imports] + "stash_graph_created_object", + ) + ) + cg(CurrentStreamSource(device)) + cg.extend_output(create_call_function(1, False)) + + +def get_current_stream(device: torch.device) -> int: + stream = torch.accelerator.current_stream(device) + return register_graph_created_object( + stream, lambda _, cg: _codegen_current_stream(device, cg) + ) + + +def _get_stream_by_index(index: int) -> torch.Stream: + stream = get_external_object_by_index(index) + if not isinstance(stream, torch.Stream): + raise AssertionError( + f"Fork/join stream expected a stream object at index {index}" + ) + return stream + + +def _get_event_by_index(index: int) -> torch.Event: + event = get_external_object_by_index(index) + if not isinstance(event, torch.Event): + raise AssertionError( + f"Record/wait event expected an event object at index {index}" + ) + return event + + +@custom_op("streams::fork", mutates_args=()) +def fork_stream( + from_index: int, # kept to make stream transitions clearer + to_index: int, +) -> None: + torch.accelerator.set_stream(_get_stream_by_index(to_index)) + + +@fork_stream.register_fake +def _( + from_index: int, # kept to make stream transitions clearer + to_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.fork.default) + + +@custom_op("streams::join", mutates_args=()) +def join_stream(from_index: int, to_index: int) -> None: + torch.accelerator.set_stream(_get_stream_by_index(to_index)) + + +@join_stream.register_fake +def _( + from_index: int, + to_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.join.default) + + +@custom_op("streams::record_event", mutates_args=()) +def record_event(event_index: int, stream_index: int) -> None: + event = _get_event_by_index(event_index) + stream = _get_stream_by_index(stream_index) + event.record(stream) + + +@record_event.register_fake +def _( + event_index: int, + stream_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.record_event.default) + + +@custom_op("streams::wait_event", mutates_args=()) +def wait_event(event_index: int, stream_index: int) -> None: + event = _get_event_by_index(event_index) + stream = _get_stream_by_index(stream_index) + event.wait(stream) + + +@wait_event.register_fake +def _( + event_index: int, + stream_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.wait_event.default) + + +@custom_op("streams::synchronize_event", mutates_args=()) +def synchronize_event(event_index: int) -> None: + event = _get_event_by_index(event_index) + event.synchronize() + + +@synchronize_event.register_fake +def _(event_index: int) -> None: + pass + + +has_side_effect(torch.ops.streams.synchronize_event.default) + + +@custom_op("streams::synchronize_device", mutates_args=()) +def synchronize_device(device_type: str, device_index: int) -> None: + torch.accelerator.synchronize(torch.device(device_type, device_index)) + + +@synchronize_device.register_fake +def _(device_type: str, device_index: int) -> None: + pass + + +has_side_effect(torch.ops.streams.synchronize_device.default) + + +@custom_op("streams::synchronize_stream", mutates_args=()) +def synchronize_stream(stream_index: int) -> None: + stream = _get_stream_by_index(stream_index) + stream.synchronize() + + +@synchronize_stream.register_fake +def _(stream_index: int) -> None: + pass + + +has_side_effect(torch.ops.streams.synchronize_stream.default) + + +@custom_op("streams::wait_stream", mutates_args=()) +def wait_stream(waiting_stream_index: int, waited_on_stream_index: int) -> None: + waiting = _get_stream_by_index(waiting_stream_index) + waited_on = _get_stream_by_index(waited_on_stream_index) + waiting.wait_stream(waited_on) + + +@wait_stream.register_fake +def _( + event_index: int, + stream_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.wait_stream.default) + + +@custom_op("streams::sync_dealloc", mutates_args=()) +def sync_dealloc( + wait_event_index: int, src_stream_index: int, to_dealloc: torch.Tensor +) -> None: + """An op which waits on an event and moves the last usage of to_dealloc + after the wait, so that after the sync occurs, the deallocation or + subsequent reuse of the tensor's memory will be guaranteed to happen + after a side stream is finished using it. + See https://docs.pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html#torch.Tensor.record_stream + for more details""" + torch.ops.streams.wait_event.default(wait_event_index, src_stream_index) + + +@sync_dealloc.register_fake +def _( + wait_event_index: int, + src_stream_index: int, + to_dealloc: torch.Tensor, +) -> None: + pass + + +has_side_effect(torch.ops.streams.sync_dealloc.default) + + +@custom_op("streams::record_stream", mutates_args=()) +def record_stream(tensor: torch.Tensor, stream_index: int) -> None: + tensor.record_stream(_get_stream_by_index(stream_index)) + + +@record_stream.register_fake +def _( + tensor: torch.Tensor, + stream_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.record_stream.default) + + +class SymbolicStreamState: + """Track the currently entered stream if any""" + + def __init__(self) -> None: + from ..source import CurrentStreamSource + + cur_stack: list[StreamVariable] = [] + if torch.accelerator.is_available(): + # Reset the registry so the current stream is guaranteed index 0. + reset_user_object_tracking() + stream = torch.accelerator.current_stream() + source = CurrentStreamSource(stream.device) + # Register the current stream so it gets index 0 (registry is + # fresh at tracing start). The inductor wrapper updates this + # entry at runtime so cudagraph capture uses the capture stream + # instead of this stale trace-time stream. + index = register_user_object(stream, source) + if index != CURRENT_STREAM_INDEX: + raise AssertionError( + f"Current stream must be registered at index {CURRENT_STREAM_INDEX}, " + f"got {index}" + ) + stream_var = LazyVariableTracker.create(stream, source=source) + # Set user_object_index as an instance attribute so accessing it + # does NOT trigger LazyVariableTracker realization. + stream_var.user_object_index = index # type: ignore[union-attr] + cur_stack = [stream_var] # type: ignore[list-item] + + self.cur_stream_stack: collections.deque[StreamVariable] = collections.deque( + cur_stack + ) + + def enter_stream(self, stream: "StreamVariable") -> None: + self.cur_stream_stack.append(stream) + + def exit_stream(self) -> None: + self.cur_stream_stack.pop() + + def cur_stream(self, device: torch.device | None = None) -> "StreamVariable": + if device is not None: + for stream in reversed(self.cur_stream_stack): + if stream.device == device: + return stream + + return self.cur_stream_stack[-1] + + def in_stream_context(self) -> bool: + return len(self.cur_stream_stack) > 0 + + def cur_stream_id(self) -> int: + """Get a Python object id for the current stream without realizing lazy variables.""" + stream = self.cur_stream_stack[-1] + if isinstance(stream, LazyVariableTracker) and not stream.is_realized(): + return id(stream.peek_value()) + return id(stream.value) + + +class StreamContextVariable(FxTracebackAnnotateVariable): + """This represents torch.cuda.StreamContext""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + stream_to_enter: "StreamVariable", + **kwargs: dict[str, Any], + ) -> "StreamContextVariable": + return StreamContextVariable( + stream_to_enter, + **kwargs, + ) + + def __init__(self, stream: Optional["StreamVariable"], **kwargs: Any) -> None: + self.stream = stream + super().__init__( + annotation={"stream": self.get_stream().user_object_index}, + initial_values=None, + **kwargs, + ) + + def enter( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + # to stream, from stream is the order of the arguments + # we are entering the target, and leaving the initial stream + tx.symbolic_stream_state.enter_stream(self.get_stream()) + return super().enter(tx) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + # to stream, from stream is the order of the arguments + # we are leaving the target, and entering the initial stream + tx.symbolic_stream_state.exit_stream() + return super().exit(tx, *args) + + def python_type(self) -> type: + return torch.cuda.StreamContext + + def supports_graph_breaks(self) -> bool: + return True + + def get_stream(self) -> "StreamVariable": + if not self.stream: + raise AssertionError("Stream context should have a separate stream") + return self.stream + + +class StreamVariable(StreamContextVariable): + """Represents the device-agnostic torch.Stream class""" + + _cpython_type: type = torch.Stream # pyrefly: ignore [bad-override] + # Subclasses set this to the device-specific handle attribute name + # (e.g. "cuda_stream", "sycl_queue"). None means no special handling. + _device_handle_attr: str | None = None + + def __init__( + self, + proxy: Proxy, + value: torch.Stream, + user_object_index: int | None = None, + **kwargs: Any, + ) -> None: + # Index into the user object table + # used to pass arbitrary objects to the graph + if proxy is not None and "example_value" in proxy.node.meta: + if proxy.node.meta["example_value"] != value: + raise AssertionError( + f"proxy example_value {proxy.node.meta['example_value']} != {value}" + ) + + self.proxy = proxy + self.value = value + self.device = value.device + + self.user_object_index = user_object_index + super().__init__(None, **kwargs) + + def python_type(self) -> type: + return self._cpython_type + + def _stream_device_handle_get( + self: "StreamVariable", tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + from ..guards import GuardBuilder, install_guard + + name = self._device_handle_attr + if name is None: + raise AssertionError( + "StreamVariable subclass must define _device_handle_attr" + ) + if self.source: + install_guard(self.source.make_guard(GuardBuilder.EQUALS_MATCH)) + if hasattr(self.value, name): + return ConstantVariable.create(getattr(self.value, name)) + if hasattr(self.value, "native_handle"): + return ConstantVariable.create(self.value.native_handle) + return None + + def get_real_python_backed_value(self) -> object: + return self.value + + def wait_event( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + event_arg = args[0] + if not isinstance(event_arg, EventVariable): + raise AssertionError(f"Expected EventVariable, got {type(event_arg)}") + tx.output.create_proxy( + "call_function", + torch.ops.streams.wait_event, + (event_arg.user_object_index, self.user_object_index), + {}, + ) + return ConstantVariable.create(None) + + def wait_stream( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + other_stream = args[0] + if not isinstance(other_stream, StreamVariable): + raise AssertionError(f"Expected StreamVariable, got {type(other_stream)}") + tx.output.create_proxy( + "call_function", + torch.ops.streams.wait_stream, + (self.user_object_index, other_stream.user_object_index), + {}, + ) + return ConstantVariable.create(None) + + def synchronize( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.create_proxy( + "call_function", + torch.ops.streams.synchronize_stream, + (self.user_object_index,), + {}, + ) + return ConstantVariable.create(None) + + def query( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from ..utils import proxy_args_kwargs + from .builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + target_cls=ConstantVariable, + tx=tx, + proxy=tx.output.create_proxy( + "call_method", "query", *proxy_args_kwargs([self] + args, kwargs) + ), + ) + + def record_event( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + tx.output.check_event_record_after_input_mutation(id(self.value)) + if args and isinstance(args[0], EventVariable): + event_var = args[0] + event = event_var.value + event_index = event_var.user_object_index + else: + event = self.value.record_event() + event_index = register_graph_created_object( + event, + EventVariable.make_construct_in_graph_event_fn( + TupleVariable([]), ConstDictVariable({}) + ), + ) + tx.output.create_proxy( + "call_function", + torch.ops.streams.record_event, + (event_index, self.user_object_index), + {}, + ) + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + get_external_object_by_index, + (event_index,), + {}, + ), + ) + + tp_methods = { + "wait_event": Method(wait_event), + "wait_stream": Method(wait_stream), + "synchronize": Method(synchronize), + "query": Method(query), + "record_event": Method(record_event), + } + + def tp_richcompare_impl(self, tx, other, op): + from ..guards import GuardBuilder, install_guard + from ..utils import cmp_name_to_op_mapping + from .constant import ConstantVariable + + if not isinstance(other, StreamVariable): + # Stream's tp_richcompare (THPStream_richcompare) compares + # stream_id/device and never returns NotImplemented. + return ConstantVariable.create(op == "__ne__") + if self.source: + install_guard(self.source.make_guard(GuardBuilder.EQUALS_MATCH)) + if other.source: + install_guard(other.source.make_guard(GuardBuilder.EQUALS_MATCH)) + op_fn = cmp_name_to_op_mapping[op] + return VariableTracker.build( + tx, + op_fn(self.value, other.value), # pyrefly: ignore[bad-argument-type] + ) + + def as_proxy(self) -> Proxy: + return self.proxy + + def module_name(self) -> str: + return "torch._C" + + def fn_name(self) -> str: + return "Stream" + + def reconstruct(self, codegen: "PyCodegen") -> None: + # If we got here, this stream is fully subsumed by the graph - this means it is + # not an input or global + if self.source: + raise AssertionError("Stream should not have a source during reconstruct") + if self.user_object_index is not None: + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, + "get_external_object_by_index", + ) + ) + codegen.append_output(codegen.create_load_const(self.user_object_index)) + codegen.extend_output(create_call_function(1, False)) + else: + # This will support the legacy behavior + prefix = f"_stream_{self.device}" + name = codegen.tx.output.install_global_by_id(prefix, self.value) + codegen.append_output(codegen.create_load_global(name, add=True)) + + def get_stream(self) -> "StreamVariable": + return self + + @staticmethod + def make_construct_in_graph_stream_fn( + args: TupleVariable, kwargs: ConstDictVariable + ) -> Callable[[int, "PyCodegen"], None]: + def fn(index: int, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, # type: ignore[implicit-imports] + "stash_graph_created_object", + ) + ) + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.utils.__name__, "build_stream" + ) + ) + codegen(args) + codegen(kwargs) + codegen.extend_output(create_call_function(2, False)) + codegen.extend_output(create_call_function(1, False)) + + return fn + + +class CudaStreamVariable(StreamVariable): + """Represents torch.cuda.Stream, preserving device-specific type and attributes.""" + + _cpython_type = torch.cuda.Stream + _device_handle_attr = "cuda_stream" + + tp_getset = { + "cuda_stream": GetSet(StreamVariable._stream_device_handle_get, None), + } + + +class XpuStreamVariable(StreamVariable): + """Represents torch.xpu.Stream, preserving device-specific type and attributes.""" + + _cpython_type = torch.xpu.Stream + _device_handle_attr = "sycl_queue" + + tp_getset = { + "sycl_queue": GetSet(StreamVariable._stream_device_handle_get, None), + } + + +_stream_fn_to_variable_cls: dict[object, type[StreamVariable]] = { + torch.cuda.current_stream: CudaStreamVariable, + torch.xpu.current_stream: XpuStreamVariable, +} + + +def _get_stream_variable_cls(stream_fn: object) -> type[StreamVariable] | None: + return _stream_fn_to_variable_cls.get(stream_fn) + + +class EventVariable(VariableTracker): + def __init__( + self, + proxy: Proxy, + value: torch.Event, + user_object_index: int | None, + **kwargs: Any, + ) -> None: + if proxy is not None and "example_value" in proxy.node.meta: + if proxy.node.meta["example_value"] != value: + raise AssertionError( + f"proxy example_value {proxy.node.meta['example_value']} != {value}" + ) + super().__init__(**kwargs) + self.proxy = proxy + self.value = value + self.user_object_index = user_object_index + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def python_type(self) -> type: + return type(self.value) + + def get_real_python_backed_value(self) -> object: + return self.value + + def wait( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + _, stream_index = EventVariable._get_stream_arg(tx, args, kwargs) + tx.output.create_proxy( + "call_function", + torch.ops.streams.wait_event, + ( + self.user_object_index, + stream_index, + ), + {}, + ) + return ConstantVariable.create(None) + + def record( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + stream_arg, stream_index = EventVariable._get_stream_arg(tx, args, kwargs) + tx.output.check_event_record_after_input_mutation(id(stream_arg.value)) + tx.output.create_proxy( + "call_function", + torch.ops.streams.record_event, + ( + self.user_object_index, + stream_index, + ), + {}, + ) + return ConstantVariable.create(None) + + def synchronize( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.create_proxy( + "call_function", + torch.ops.streams.synchronize_event, + (self.user_object_index,), + {}, + ) + return ConstantVariable.create(None) + + def query( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from ..utils import proxy_args_kwargs + from .builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + target_cls=ConstantVariable, + tx=tx, + proxy=tx.output.create_proxy( + "call_method", "query", *proxy_args_kwargs([self] + args, kwargs) + ), + ) + + tp_methods = { + "wait": Method(wait), + "record": Method(record), + "synchronize": Method(synchronize), + "query": Method(query), + } + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Event supports only the tp_methods above; every other name (including + # dunders) graph-breaks with an event-specific message rather than the + # generic "Unsupported method call". + if name in self.tp_methods: + return super().call_method(tx, name, args, kwargs) + method_name = ( + f"{type(self.value).__module__}.{type(self.value).__qualname__}.{name}" + ) + unimplemented( + gb_type="Unsupported event method", + context=str(name), + explanation=f"Dynamo doesn't support tracing the {method_name} method. " + f"We currently support wait, record, synchronize, and query.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + def as_proxy(self) -> Proxy: + return self.proxy + + @staticmethod + def _get_stream_arg( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> tuple["StreamVariable", int]: + """Returns (stream_variable, stream_index_for_op). + + The ambient current stream is registered at index 0 in the external + object registry. The inductor wrapper updates index 0 at runtime so + that cudagraph capture sees the capture stream, not the stale + trace-time default stream. + """ + stream_arg = None + if args: + stream_arg = args[0] + elif kwargs: + stream_arg = kwargs.get("stream") + + if not stream_arg: + stream_var = tx.symbolic_stream_state.cur_stream() + return stream_var, stream_var.user_object_index # type: ignore[return-value] + + return stream_arg, stream_arg.user_object_index # type: ignore[return-value] + + @staticmethod + def make_construct_in_graph_event_fn( + args: TupleVariable, kwargs: ConstDictVariable + ) -> Callable[[int, "PyCodegen"], None]: + def fn(index: int, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, # type: ignore[implicit-imports] + "stash_graph_created_object", + ) + ) + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.utils.__name__, "build_event" + ) + ) + codegen(args) + codegen(kwargs) + codegen.extend_output(create_call_function(2, False)) + codegen.extend_output(create_call_function(1, False)) + + return fn + + def reconstruct(self, codegen: "PyCodegen") -> None: + # If we got here, this event is fully subsumed by the graph - this means it is + # not an input or global + if self.source: + raise AssertionError("Event should not have a source during reconstruct") + if self.user_object_index is not None: + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, + "get_external_object_by_index", + ) + ) + codegen.append_output(codegen.create_load_const(self.user_object_index)) + codegen.extend_output(create_call_function(1, False)) + else: + prefix = "_event" + name = codegen.tx.output.install_global_by_id(prefix, self.value) + codegen.append_output(codegen.create_load_global(name, add=True)) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/tensor.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..c2bc10f2ef6a4489c137f86dd442f5eced999471 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/tensor.py @@ -0,0 +1,3667 @@ +""" +This module contains variable tracker classes for handling tensors and tensor-related operations in Dynamo. + +The main class is TensorVariable which represents torch.Tensor inputs and intermediate values in the FX graph. +It handles tensor operations, method calls, and maintains metadata about tensor properties like dtype, device, etc. + +Other key classes include: +- SymNodeVariable: Represents symbolic scalars (int/float/bool) used for size computation and unspecialized values +- NumpyNdarrayVariable: Handles numpy array interop through torch._numpy +- UnspecializedPythonVariable: Represents unspecialized Python numeric values as 1-element tensors +- TensorSubclassVariable: Handles tensor subclasses with __torch_function__ overrides +- UntypedStorageVariable: Represents tensor storage objects +- DataPtrVariable: Handles tensor data pointer operations + +These classes work together to track tensor operations and properties during Dynamo's tracing process. +""" + +import functools +import logging +import operator +import textwrap +import traceback +import types +from collections.abc import Iterable, Sequence +from contextlib import nullcontext +from itertools import chain +from types import NoneType +from typing import Any, NoReturn, Optional, TYPE_CHECKING +from typing_extensions import NotRequired, TypedDict + +import sympy + +import torch._numpy as tnp +import torch.fx +import torch.random +from torch import sym_float, sym_int +from torch._custom_class_base import CustomClassBase +from torch._dynamo import compiled_autograd +from torch._library.opaque_object import is_opaque_symbolic_type +from torch._subclasses.meta_utils import is_sparse_any +from torch.fx.experimental.symbolic_shapes import ( + guard_scalar, + GuardOnDataDependentSymNode, + has_free_symbols, + is_symbolic, + SymTypes, +) +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .. import config, graph_break_hints, variables +from .._trace_wrapped_higher_order_op import trace_wrapped +from ..exc import ( + ObservedAttributeError, + raise_observed_exception, + raise_type_error, + raise_value_error, + TorchRuntimeError, + unimplemented, + UnknownPropertiesDuringBackwardTrace, + UserError, + UserErrorType, +) +from ..external_utils import call_hook_from_backward_state +from ..guards import GuardBuilder, install_guard +from ..source import AttrSource, TypeSource +from ..utils import ( + cmp_name_to_op_mapping, + fqn, + get_custom_getattr, + get_fake_value, + get_real_value, + guard_if_dyn, + object_has_getattribute, + product, + proxy_args_kwargs, + set_example_value, + tensortype_to_dtype, +) +from .base import ( + _check_method_arity, + _derive_method_flags, + AttributeMutationNew, + GetSet, + Method, + ValueMutationNew, + VariableTracker, +) +from .constant import ConstantVariable +from .lists import ListIteratorVariable, SizeVariable +from .script_object import CustomClassObjectVariable +from .user_defined import UserDefinedClassVariable + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.output_graph import OutputGraph + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from .functions import UserFunctionVariable + from .torch_function import TensorWithTFOverrideVariable + + +log = logging.getLogger(__name__) + +# Ops that allow tensor tensor +supported_tensor_comparison_ops = { + ">": operator.gt, + "<": operator.lt, + ">=": operator.ge, + "<=": operator.le, + "==": operator.eq, + "!=": operator.ne, + "is": operator.is_, + "is not": operator.is_not, +} +# Ops that allow tensor None +supported_const_comparison_ops = { + "is": operator.is_, + "is not": operator.is_not, + "==": operator.eq, + "!=": operator.ne, +} +supported_comparison_ops = { + **supported_tensor_comparison_ops, + **supported_const_comparison_ops, +} +supported_tensor_comparison_op_values = dict.fromkeys( + supported_tensor_comparison_ops.values() +) +supported_const_comparison_op_values = dict.fromkeys( + supported_const_comparison_ops.values() +) + + +def is_bound_tensor_method(value: object) -> bool: + return bool( + callable(value) + and not torch._dynamo.utils.object_has_getattribute(value) + and hasattr(value, "__self__") + and isinstance(value.__self__, torch.Tensor) + and getattr(value.__self__, value.__name__, None) + ) + + +# instead of using inspect.getattr_static, we directly lookup the appropriate +# dicts. It is necessary to keep the torch._C.TensorBase first in the or +# operation, because the second arg takes priority in or operation when there +# are common keys. +all_tensor_attrs = torch._C.TensorBase.__dict__ | torch.Tensor.__dict__ + +# Tensor attributes that are plain views of the tensor. Each maps to the aten op +# that the C++ getter dispatches to, see native_functions.yaml. +_VIEW_ATTR_TO_ATEN_OP = { + "T": torch.ops.aten.numpy_T, + "mT": torch.ops.aten.mT, + "H": torch.ops.aten.matrix_H, + "mH": torch.ops.aten.mH, +} + + +def _is_sym_arith_operand(vt: VariableTracker) -> bool: + """True if vt can be the other operand of a SymNode arithmetic op + (add/sub). Accepts SymNode-like values plus float ConstantVariable — + arithmetic with float promotes to SymFloat, unlike bitwise ops.""" + if vt.is_symnode_like(): + return True + + # mirror sym_node.py::binary_magic_impl + return isinstance(vt, ConstantVariable) and isinstance(vt.value, (float, int, bool)) + + +def _tensor_debug_repr(value: torch.Tensor, type_name: str = "Tensor") -> str: + if torch._C._functorch.is_batchedtensor(value): + level = torch._C._functorch.maybe_get_level(value) + bdim = torch._C._functorch.maybe_get_bdim(value) + unwrapped = torch._C._functorch.get_unwrapped(value) + return ( + "BatchedTensor(" + f"lvl={level}, bdim={bdim}, value={_tensor_debug_repr(unwrapped)}" + ")" + ) + if torch._C._functorch.is_gradtrackingtensor(value): + level = torch._C._functorch.maybe_get_level(value) + unwrapped = torch._C._functorch.get_unwrapped(value) + return f"GradTrackingTensor(lvl={level}, value={_tensor_debug_repr(unwrapped)})" + if torch._C._functorch.is_functionaltensor(value): + level = torch._C._functorch.maybe_get_level(value) + unwrapped = torch._C._functorch.get_unwrapped(value) + return f"FunctionalTensor(lvl={level}, value={_tensor_debug_repr(unwrapped)})" + return f"{type_name}(shape={tuple(value.shape)}, dtype={value.dtype})" + + +class TensorSpecializedProps(TypedDict): + """Static tensor metadata produced by TensorVariable.specialize; the keys + map 1:1 to the corresponding TensorVariable.__init__ kwargs. The size, + stride and contiguity keys are only populated for fully static shapes.""" + + dtype: torch.dtype + device: torch.device + layout: torch.layout + ndim: int + requires_grad: bool + is_nested: bool + is_quantized: bool + is_sparse: bool + class_type: type + has_grad_fn: bool + _size: NotRequired[tuple[Any, ...]] + stride: NotRequired[tuple[Any, ...]] + is_contiguous: NotRequired[tuple[torch.memory_format, ...] | None] + + +class TensorVariable(VariableTracker): + """A torch.Tensor input or an intermediate value in the FX graph""" + + _nonvar_fields = { + "proxy", + "dtype", + "device", + "layout", + "ndim", + "size", + "stride", + "requires_grad", + "is_quantized", + "is_contiguous", + "is_nested", + "is_sparse", + "class_type", + "specialized_value", + "_is_name_set", + *VariableTracker._nonvar_fields, + } + + def reconstruct_pycode(self, codegen) -> str: + if id(self.proxy) in codegen.graph_outputs: + return f"__graph_out[{codegen.graph_outputs[id(self.proxy)].index}]" + elif self.source: + return self.source.reconstruct_pycode(codegen) + else: + raise RuntimeError(f"Python codegen for {self} failed with unknown source.") + + def get_real_value(self) -> torch.Tensor: + """ + Get the actual value represented by this variable if computation is run + using the user-provided inputs. + NOTE: this runs actual tensor computation and may be + slow and memory-intensive. + """ + return get_real_value(self.proxy.node, self.proxy.tracer) + + def __init__( + self, + proxy: torch.fx.Proxy, + *, + dtype: torch.dtype, + device: torch.device, + layout: torch.layout, + ndim: int, + requires_grad: bool, + is_nested: bool, + is_quantized: bool, + is_sparse: bool, + class_type: type, + has_grad_fn: bool, + _size: tuple[Any, ...] | None = None, + stride: tuple[Any, ...] | None = None, + is_contiguous: tuple[torch.memory_format, ...] | None = None, + _is_name_set: bool | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.proxy = proxy + self.dtype = dtype + self.device = device + self.layout = layout + self.ndim = ndim + self._size = _size # this is accessed as a property for validation + self.stride = stride + self.requires_grad = requires_grad + self.is_quantized = is_quantized + self.is_contiguous = is_contiguous + self.is_nested = is_nested + self.is_sparse = is_sparse + self.class_type = class_type + self.has_grad_fn = has_grad_fn + if _is_name_set is None: + # no need to rename inputs + _is_name_set = self.proxy.node.op == "placeholder" + self._is_name_set: bool = _is_name_set + + def synchronize_attributes( + self, tx: "InstructionTranslatorBase", target_cls: type | None = None + ) -> None: + from .builder import get_specialized_props, infer_subclass_type + + if target_cls is None: + target_cls = type(self) + + example_value = self.proxy.node.meta.get("example_value") + specialized_props = get_specialized_props( + target_cls, tx, example_value, infer_subclass_type(example_value) + ) + # These fields match the conditionally specialized metadata in + # get_specialized_props(). If fake execution changes them to symbolic + # values, they are omitted and the old cache must be invalidated. + for k in ("_size", "stride", "is_contiguous"): + if k not in specialized_props: + setattr(self, k, None) + for k, v in specialized_props.items(): + setattr(self, k, v) + + def _get_fake_version(self) -> int | None: + """Get the current version of self's fake tensor, or None if unavailable.""" + self_fake = self.proxy.node.meta.get("example_value") + return self_fake._version if self_fake is not None else None + + def _sync_if_inplace_mutation( + self, + tx: "InstructionTranslatorBase", + version_before: int | None, + ) -> None: + """ + Sync attributes if self was mutated by an inplace operation. + + See Note [Inplace ops and VariableTracker metadata] + """ + version_after = self._get_fake_version() + if ( + version_before is not None + and version_after is not None + and version_after > version_before + ): + self.synchronize_attributes(tx) + tx.output.check_input_mutation_on_current_stream(tx) + + def debug_repr(self) -> str: + return _tensor_debug_repr( + self.proxy.node.meta["example_value"], self.python_type_name() + ) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + unimplemented( + gb_type="repr() on tensor", + context=f"repr() on {self.python_type_name()}", + explanation="Tensor repr requires actual runtime values which are " + "not available during tracing.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def as_proxy(self) -> torch.fx.Proxy: + return self.proxy + + def python_type(self) -> type: + return self.class_type + + def is_tensor(self) -> bool: + return True + + def nb_bool_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # THPVariable_bool calls at::Tensor::is_nonzero(), i.e. .item() != 0. + from .constant import ConstantVariable + + item = self.call_method(tx, "item", [], {}) + if isinstance(item, SymNodeVariable) and isinstance( + item.sym_num, torch.SymBool + ): + return item + if isinstance(item, ConstantVariable): + return VariableTracker.build(tx, bool(item.value)) + return SymNodeVariable.create(tx, item.as_proxy() != 0) + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """Tensor tp_richcompare: element-wise comparison producing an FX proxy.""" + from .builder import wrap_fx_proxy_cls + + if not isinstance(other, (SymNodeVariable, ConstantVariable, TensorVariable)): + return ConstantVariable.create(NotImplemented) + op_fn = cmp_name_to_op_mapping[op] + proxy = tx.output.create_proxy( + "call_function", op_fn, (self.as_proxy(), other.as_proxy()), {} + ) + return wrap_fx_proxy_cls(type(self), tx, proxy) + + @staticmethod + def specialize(value: torch.Tensor) -> TensorSpecializedProps: + try: + has_grad_fn = value.grad_fn is not None + except Exception: + # Workaround for issues with create_parameter_op in Dynamo. Reading + # grad_fn should never cause an issue. + has_grad_fn = False + + props: TensorSpecializedProps = { + "dtype": value.dtype, + "device": value.device, + "layout": value.layout, + "ndim": int(value.ndim), + "requires_grad": value.requires_grad, + "is_nested": value.is_nested, + "is_quantized": value.is_quantized, + "is_sparse": value.is_sparse, + "class_type": type(value), + "has_grad_fn": has_grad_fn, + } + + if is_sparse_any(value) and not has_free_symbols(value): + props["_size"] = tuple( + int(s) if is_symbolic(s) else s for s in value.size() + ) + elif not has_free_symbols(value): + # this is a fully static shape, and the keys on props here inform specialization. + # We have to cast to int here, because these might get accessed as ConstantVariable, which has + # a strict no-symint policy. If we got here due to not having free symbols, this is a known constant + # already. We could remove the discrepancy here, by having ConstantVariable be more permissive for + # constant backed SymInts, but that assert being strict has led to some good signal in hunting bugs, and + # I'd like to keep it around for now. + props["_size"] = tuple( + # the non is_symbolic case applies to the jagged layout + # NestedTensor case as singleton ints are not symbolic + int(s) if is_symbolic(s) else s + for s in value.size() + ) + props["stride"] = tuple(value.stride()) + if torch._C._functorch.is_batchedtensor(value): + # Batched tensors does not support contiguity patterns, so + # we refrain from computing the `is_contiguous` property + props["is_contiguous"] = None + else: + props["is_contiguous"] = tuple( + x + for x in torch._prims_common._memory_formats + if value.is_contiguous(memory_format=x) + ) + return props + + def dynamic_getattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + fake_val = self.proxy.node.meta["example_value"] + # For getattrs on tensors without sources, + # we can do better than the default (creating a GetAttrVariable) + # if: + # (1) the tensor is a traceable tensor subclass + # (2) We are getattr'ing an inner tensor from that subclass + if not self.source and is_traceable_wrapper_subclass(fake_val): + attrs, _ctx = fake_val.__tensor_flatten__() + proxy = getattr(self.as_proxy(), name) + example_value = getattr(fake_val, name) + if name in attrs: + # attrs returned from tensor_flatten are always tensors or opaques + if not isinstance(example_value, (torch.Tensor, CustomClassBase)): + raise AssertionError( + f"Expected Tensor or CustomClassBase, got {type(example_value)}" + ) + from .builder import wrap_fx_proxy + + return wrap_fx_proxy(tx=tx, proxy=proxy, example_value=example_value) + elif is_opaque_symbolic_type(type(example_value)): + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + tx.output.fake_mode, example_value + ) + return CustomClassObjectVariable.create(proxy, fake_script_obj, tx=tx) + elif isinstance( + example_value, + torch._library.fake_class_registry.FakeScriptObject, + ): + return CustomClassObjectVariable.create(proxy, example_value, tx=tx) + # any other attributes on the subclass (that are not methods) + # are assumed to be constant metadata. + elif not callable(example_value): + return VariableTracker.build(tx, example_value) + + if not (self.source and self.source.subguards_allowed()): + raise NotImplementedError + + # For local source, we associate the real value. We use this real value + # for implementing getattr fallthrough on the variable tracker base class. + + # Note - this scope construction is mirrored in guards + # A subsequent PR will introduce a util. + scope = {"L": tx.output.local_scope, "G": tx.output.global_scope} + try: + # We raise in case we get a typerror bug w/ SuperSource. + # SuperSource has bugs in it atm, and can produce code like + # eval("super(L['mod'].model.model.encoder.embed_positions.forward__class__, + # L['mod'].model.model.encoder.embed_positions)", scope) + # Which is incorrect, and violates the invariant that all sources should be eval()-able against the scope. + _input_associated_real_value = eval(self.source.name, scope) + except Exception as exc: + raise NotImplementedError from exc + + if _input_associated_real_value is None: + raise NotImplementedError + + if object_has_getattribute(_input_associated_real_value): + raise NotImplementedError + + if get_custom_getattr(_input_associated_real_value): + raise NotImplementedError + + try: + real_value = getattr(_input_associated_real_value, name) + except AttributeError: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(_input_associated_real_value).__name__}' object has no attribute '{name}'" + ], + ) + + attr_source = AttrSource(self.source, name) + + # Typically we'd want to use variable builder here + # but unfortunately id(real_value.__self__) is not id() + if is_bound_tensor_method(real_value): + # No need to install the guard because its a bound tensor method + from .misc import GetAttrVariable + + return GetAttrVariable( + self, name, source=attr_source, py_type=type(real_value) + ) + + install_guard( + self.source.make_guard(functools.partial(GuardBuilder.HASATTR, attr=name)) + ) + return VariableTracker.build(tx, real_value, attr_source) + + def _view_attr(self, tx: "InstructionTranslatorBase", name: str) -> VariableTracker: + """Trace a view attribute as a call to the aten op behind the C++ getter. + + Going through the op keeps the node on the current tracer. Reading the + attribute off the base proxy instead puts the node in whichever graph + owns the base, so inside a higher order op it lands in the parent graph + and then has to be lifted back in as a subgraph input. + """ + from .torch import TorchInGraphFunctionVariable + + return TorchInGraphFunctionVariable(_VIEW_ATTR_TO_ATEN_OP[name]).call_function( + tx, [self], {} + ) + + def method_attr_T(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self._view_attr(tx, "T") + + def method_attr_mT(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self._view_attr(tx, "mT") + + def method_attr_H(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self._view_attr(tx, "H") + + def method_attr_mH(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self._view_attr(tx, "mH") + + def method_attr_ndim(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self.ndim is not None: + return VariableTracker.build(tx, self.ndim) + else: + return self.call_method(tx, "dim", [], {}) + + def method_attr_dtype( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker | None: + if self.dtype is not None: + return VariableTracker.build(tx, self.dtype) + return None + + def method_attr_device( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker | None: + if self.device is not None: + return VariableTracker.build(tx, self.device) + return None + + def method_attr_layout( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker | None: + if self.layout is not None: + return VariableTracker.build(tx, self.layout) + return None + + def method_attr_is_cuda( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.device is not None: + return VariableTracker.build(tx, self.device.type == "cuda") + return None + + def method_attr_shape(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self.valid_size(): + sizes: list[VariableTracker] = [ + VariableTracker.build(tx, x) for x in self.size + ] + return SizeVariable(sizes) + else: + return self.call_method(tx, "size", [], {}) + + def method_attr_requires_grad( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.requires_grad is not None: + return VariableTracker.build(tx, self.requires_grad) + return None + + def method_attr_is_quantized( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.is_quantized is not None: + return VariableTracker.build(tx, self.is_quantized) + return None + + def method_attr_is_sparse( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.is_sparse is not None: + return VariableTracker.build(tx, self.is_sparse) + return None + + def method_attr_is_nested( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.is_nested is not None: + return VariableTracker.build(tx, self.is_nested) + return None + + def method_attr_retain_grad(self, tx: "InstructionTranslatorBase") -> NoReturn: + unimplemented( + gb_type="Tensor.retain_grad() with AOTDispatcher", + context=f"tp_getattro_impl {self} retain_grad", + explanation="`Tensor.retain_grad()` does not work with AOTDispatcher.", + hints=[], + ) + + def method_attr_grad( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker | None: + if tx.output.side_effects.has_pending_mutation_of_attr(self, "grad"): + return tx.output.side_effects.load_attr(self, "grad") + if ( + isinstance(self.mutation_type, AttributeMutationNew) + and not self.has_grad_fn + ): + return ConstantVariable.create(None) + # None tells tp_getattro_impl to use default .grad handling + return None + + def method_attr_data(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return variables.TorchInGraphFunctionVariable( + torch._C._autograd._get_data_attr # type: ignore[attr-defined] + ).call_function(tx, [self], {}) + + def method_attr_grad_fn( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.has_grad_fn: + unimplemented( + gb_type="Tensor with grad_fn()", + context=f"tp_getattro_impl {self} grad_fn", + explanation="Dynamo does not support tracing tensors with a grad_fn directly.", + hints=[], + ) + else: + return variables.ConstantVariable.create(None) + + def method_attr__version(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from ..tensor_version_op import _tensor_version + + return variables.TorchInGraphFunctionVariable(_tensor_version).call_function( + tx, [self], {} + ) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + from . import GetAttrVariable + + # TODO - This is not a good solution but solves an accuracy issue. + # Today, tp_getattro_impl returns GetAttrVariable for both non-existent + # attributes and existing attributes. This is a bug and requires more + # deep dive. + if name in all_tensor_attrs: + return ConstantVariable.create(True) + + try: + var = VariableTracker.build(tx, getattr).call_function( + tx, [self, VariableTracker.build(tx, name)], {} + ) + # in the event that TensorVariable returns NotImplemented + # GetAttrBuiltinVariable.call_function returns GetAttrVariable + ret_val = not isinstance(var, GetAttrVariable) + except (AttributeError, ObservedAttributeError): + ret_val = False + + if self.source: + install_guard( + self.source.make_guard( + functools.partial(GuardBuilder.HASATTR, attr=name) + ) + ) + + return VariableTracker.build(tx, ret_val) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + fake_val = self.as_proxy().node.meta["example_value"] + if ( + isinstance(fake_val, torch.Tensor) + and is_sparse_any(fake_val) + and (not tx.export or not config.capture_sparse_compute) + ): + unimplemented( + gb_type="Attempted to wrap sparse Tensor", + context="", + explanation="torch.compile does not support sparse Tensors", + hints=[*graph_break_hints.SPARSE_TENSOR], + ) + + if self.is_strict_mode(tx): + if name in self._strict_mode_banned_ops(): + unimplemented( + gb_type="Strict mode banned op", + context=f"tp_getattro_impl {self} {name}", + explanation=f"Getattr invocation '{name}' in strict mode is not supported.", + hints=[ + f"Remove `{name}` from the list of banned ops by " + "setting `torch._dynamo.config._autograd_backward_strict_mode_banned_ops`.", + ], + ) + elif name in self._strict_mode_conditional_banned_ops(): + raise UnknownPropertiesDuringBackwardTrace( + f"Unknown property {name} during speculating backward, dynamo will insert contiguous call ahead and speculate it again" + ) + + if name == "__class__": + # Carry provenance on the class, mirroring BuiltinVariable.call_type. + # A sourced class self-guards when observed downstream (e.g. + # `w.__class__ is SomeType`), which keeps type observation sound even + # when the input's own class guard is relaxed (see + # VariableBuilder.wrap_tensor and ACT input polymorphism). + source = self.source and TypeSource(self.source) + return VariableTracker.build(tx, self.python_type(), source) + + handler = getattr(self, f"method_attr_{name}", None) + result = handler(tx) if handler is not None else None + + # Add a guard for type matching, these guards are checked before tensor guards + # In some cases, a . guard can be evaluated first, and break if + # is later changed to another type + if ( + result is not None + and self.source + and self.source.subguards_allowed() + # A view attribute is the output of an op we just traced, like any + # other view. An AttrSource would instead make Dynamo drop it from + # the graph outputs and rebuild it in bytecode from the base. + and name not in _VIEW_ATTR_TO_ATEN_OP + and not ( + name not in ("grad", "requires_grad") and result.is_python_constant() + ) + ): + install_guard(self.make_guard(GuardBuilder.TYPE_MATCH)) + result.source = AttrSource(self.source, name) + + # It's hard to get inplace view (metadata mutation) on graph input work properly across + # dynamo/aot/inductor, just fall back. + if self.source is not None and hasattr(torch.ops.aten, name): + fn = getattr(torch.ops.aten, name) + if ( + hasattr(fn, "overloads") + and hasattr(fn, fn.overloads()[0]) + and torch.Tag.inplace_view in getattr(fn, fn.overloads()[0]).tags + ): + # Delay the graph break to the actual call of unsqueeze_/resize_/resize_as_ etc. + return variables.misc.DelayGraphBreakVariable( + source=AttrSource(self.source, name), + msg="Getting an inplace view on a graph input is not supported", + hints=[ + "Avoid mutating a graph input's tensor metadata with in-place view ops. " + "If the mutation is only needed inside the compiled region, replace the in-place call " + "with an out-of-place view, for example `x = x.transpose(1, 2)` instead of " + "`x.transpose_(1, 2)`.", + "If you need to mutate the input tensor's metadata, move the in-place view call outside " + "`torch.compile`.", + ], + ) + + # For attributes (not methods) that were not caught in the special handling above, + # (e.g. tensor.real), we handle these generically, assuming that the output type is + # a tensor. + if result is None and name != "grad": + + def try_generic_attr_handling() -> VariableTracker | None: + from .builder import wrap_fx_proxy + + static_attr = all_tensor_attrs.get(name, None) + if static_attr is None: + return None + + # Make sure this is an attribute, not a method. + # type(torch.Tensor.H) should be "getset_descriptor" + # This is a because of CPython implementation, see THPVariableType: + # these attributes are implemented under tp_getset, which appear + # as `getset_descriptor`s, (compared to, say, methods which appear + # as `method_descriptor`s) + if type(static_attr) is not types.GetSetDescriptorType: + return None + + # Create the node on the current tracer, not on the tracer that + # owns the base proxy. Otherwise, inside a higher order op, the + # node lands in the parent graph and has to be lifted back in as + # a subgraph input. + proxy = tx.output.current_tracer.create_proxy( + "call_function", getattr, (self.as_proxy(), name), {} + ) + if self.source is not None: + return wrap_fx_proxy( + tx=tx, proxy=proxy, source=AttrSource(self.source, name) + ) + else: + return wrap_fx_proxy(tx=tx, proxy=proxy) + + result = try_generic_attr_handling() + + if result is None: + result = self.dynamic_getattr(tx, name) + + if result is None: + raise NotImplementedError + return result + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase", idxes: Sequence[int] | None = None + ) -> list[VariableTracker]: + from .builder import wrap_fx_proxy_cls + from .torch_function import TensorWithTFOverrideVariable + + if self.valid_size(): + size_len = len(self.size) + else: + size_var = self.call_method(tx, "size", [], {}) + if not isinstance(size_var, SizeVariable): + raise AssertionError(f"Expected SizeVariable, got {type(size_var)}") + size_len = len(size_var.items) + # Ensure we don't unpack a scalar tensor. + if size_len == 0: + raise AssertionError("Can't unpack scalar tensors.") + + if self.valid_size(): + length = self.size[0] + else: + dyn_length = self.call_method( + tx, "size", [VariableTracker.build(tx, 0)], {} + ) + # SymNodeVariable for symbolic sizes, ConstantVariable for constants OR values produced through + # symbolic_shapes, but that end up as int/sympy.Integer + if not ( + isinstance(dyn_length, SymNodeVariable) + or dyn_length.is_python_constant() + ): + raise AssertionError( + f"Expected SymNodeVariable or python constant, got {type(dyn_length)}" + ) + if isinstance(dyn_length, SymNodeVariable): + length = dyn_length.evaluate_expr(tx.output) + else: + length = dyn_length.as_python_constant() + + if idxes is None: + idxes = range(length) # type: ignore[arg-type] + else: + if len(idxes) != length: + raise AssertionError( + f"Can't unpack a tensor of {length} rows into a tuple of {len(idxes)} elements." + ) + + # preserve tensor subclass type when unpacking + if isinstance(self, TensorWithTFOverrideVariable): + base_vars = [ + wrap_fx_proxy_cls( + target_cls=TensorVariable, tx=tx, proxy=self.as_proxy()[i] + ) + for i in idxes + ] + return [ + TensorWithTFOverrideVariable.from_tensor_var( + tx, v, self.class_type, self.source + ) + for v in base_vars + ] + + return [ + wrap_fx_proxy_cls(target_cls=type(self), tx=tx, proxy=self.as_proxy()[i]) + for i in idxes + ] + + def call_tree_map( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "UserFunctionVariable", + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return map_fn.call_function(tx, [self, *rest], {}) + + def valid_size(self) -> bool: + return self._size is not None + + @property + def size(self) -> tuple[Any, ...]: + if self._size is None: + raise AssertionError("accessing None size in TensorVariable") + return self._size + + def _strict_mode_banned_ops(self) -> list[str]: + return torch._dynamo.config._autograd_backward_strict_mode_banned_ops + + def _strict_mode_conditional_banned_ops(self) -> list[str]: + return ( + torch._dynamo.config._autograd_backward_strict_mode_conditional_banned_ops + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # Tensor.__getitem__ is a custom C slot, not CPython's mp_subscript. + from .builder import SourcelessBuilder, VariableBuilder + from .torch_function import can_dispatch_torch_function, dispatch_torch_function + + if self.is_strict_mode(tx) and "__getitem__" in self._strict_mode_banned_ops(): + unimplemented( + gb_type="Illegal __getitem__ invocation in strict mode", + context=f"mp_subscript_impl {self} {key}", + explanation="Dynamo currently does not support __getitem__ " + "invocation in strict mode.", + hints=[], + ) + + empty_kwargs: dict[str, VariableTracker] = {} + static_attr = all_tensor_attrs.get("__getitem__", None) + if static_attr is not None and can_dispatch_torch_function( + tx, (self, key), empty_kwargs + ): + if self.source: + func_var = VariableBuilder( + tx, + AttrSource(AttrSource(self.source, "__class__"), "__getitem__"), + )(static_attr) + else: + func_var = SourcelessBuilder.create(tx, torch.Tensor.__getitem__) + return dispatch_torch_function(tx, func_var, (self, key), empty_kwargs) + + return self.method___getitem__(tx, key) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: "dict[str, VariableTracker]", + ) -> VariableTracker: + from .builder import SourcelessBuilder, VariableBuilder + from .torch_function import can_dispatch_torch_function, dispatch_torch_function + + if self.is_strict_mode(tx) and name in self._strict_mode_banned_ops(): + unimplemented( + gb_type="Illegal method invocation in strict mode", + context=f"call_method {self} {name} {args} {kwargs}", + explanation="Dynamo currently does not support this method " + f"({name}) invocation in strict mode.", + hints=[], + ) + + if name == "__deepcopy__": + unimplemented( + gb_type="Attempted to copy.deepcopy a tensor", + context=f"copy.deepcopy({self})", + explanation="Dynamo does not support copy.deepcopy() on tensors.", + hints=[ + "Avoid calling copy.deepcopy() on tensors inside compiled regions.", + ], + ) + + # Only override builtin tensor methods + # The user can manually add override handling + # with a decorator for other methods (e.g. a dispatch subclass with other methods) + static_attr = all_tensor_attrs.get(name, None) + is_base_tensor_method = static_attr is not None + + if ( + can_dispatch_torch_function(tx, tuple([self] + list(args)), kwargs) + and is_base_tensor_method + ): + if self.source: + func_var = VariableBuilder( + tx, AttrSource(AttrSource(self.source, "__class__"), name) + )(static_attr) + else: + func_var = SourcelessBuilder.create(tx, getattr(torch.Tensor, name)) + + return dispatch_torch_function( + tx, func_var, tuple([self] + list(args)), kwargs + ) + + # Declarative named-method dispatch (tp_methods). Mirrors CPython's + # tp_methods table: arity (derived from CPython's ml_flags) is checked + # centrally via _check_method_arity, then the handler runs with its + # native Python signature. A handler returning None declines and falls + # through to the generic proxy path below, matching the old per-handler + # fall-through. + method = self.tp_methods.get(name) + if method is not None: + flags = _derive_method_flags(self, name) + _check_method_arity(self, tx, name, flags, args, kwargs) + # Realize any LazyVariableTracker in kwargs before calling handler. + realized_kwargs = {k: v.realize() for k, v in kwargs.items()} + try: + result = method.handler(self, tx, *args, **realized_kwargs) + except TypeError as e: + unimplemented( + gb_type="Unhandled args for method", + context=f"call_method {self} {name} {args} {kwargs}", + explanation="Dynamo encountered an error while calling " + f"the method `{name}`.", + hints=[], + from_exc=e, + ) + if result is not None: + return result + + # Guard against unknown methods reaching the generic proxy path. + # For traceable wrapper subclasses (DTensor, NestedTensor), class_type + # is torch.Tensor, so check the example_value's actual type instead. + example_value = self.proxy.node.meta.get("example_value") + check_type = ( + type(example_value) if example_value is not None else self.class_type + ) + if not hasattr(check_type, name): + unimplemented( + gb_type="Unhandled tensor method", + context=f"call_method {self} {name} {args} {kwargs}", + explanation=f"Tensor method `{name}` is not defined on " + f"{check_type.__name__} and does not have an explicit " + "handler in TensorVariable.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + from .builder import wrap_fx_proxy + + try: + proxy = tx.output.create_proxy( + "call_method", + name, + *proxy_args_kwargs([self, *args], kwargs), + ) + except NotImplementedError as e: + unimplemented( + gb_type="Unsupported argument type in tensor method call", + context=f"call_method {self} {name} {args} {kwargs}", + explanation=f"Dynamo could not create a proxy for an argument in the call " + f"to Tensor.{name}(). This usually means an unsupported type was passed " + f"as an argument to a tensor method.", + hints=[*graph_break_hints.SUPPORTABLE], + from_exc=e, + ) + + # [Note: Inplace ops and VariableTracker metadata] + # For inplace operations, we need to propagate tensor metadata from the + # arguments to self. For example: + # x.add_(y) where y.requires_grad=True => x.requires_grad becomes True + # We detect inplace ops by checking if self's fake tensor version changes + # after wrap_fx_proxy (which runs get_fake_value internally). + # Some inplace ops mutate metadata even without tensor arguments, e.g. + # as_strided_ mutates size/stride from integer/list arguments. + + # See ops_consuming_unbacked_scalars in torch.py for the full allowlist + # and reasoning. + from .torch import methods_consuming_unbacked_scalars + + ctx = ( + tx.fake_mode.shape_env.ignore_fresh_unbacked_symbols + if tx.fake_mode + and tx.fake_mode.shape_env + and name in methods_consuming_unbacked_scalars + and any( + isinstance(v, TensorVariable) and v.ndim == 0 + for v in chain(args, kwargs.values()) + ) + else nullcontext + ) + + version_before = self._get_fake_version() + with ctx(): + result = wrap_fx_proxy(tx, proxy) + self._sync_if_inplace_mutation(tx, version_before) + + return result + + def method_size( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker | None: + return self._method_size_stride("size", *args, **kwargs) + + def method_stride( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker | None: + return self._method_size_stride("stride", *args, **kwargs) + + def _method_size_stride( + self, name: str, dim: Any | None = None + ) -> VariableTracker | None: + dim = guard_if_dyn(dim) + + def make_const_size_variable(x: Sequence[Any], **options: Any) -> SizeVariable: + return SizeVariable( + [ConstantVariable.create(y, **options) for y in x], **options + ) + + RetVariable = ( + make_const_size_variable if name == "size" else ConstantVariable.create + ) + + # Technically, this should not be necessary, but I'm including it + # for enhanced BC, in case example_value is sometimes not set + # (it really should always be set though!) + if name != "size": + r = getattr(self, name) + elif name == "size" and self.valid_size(): + r = self.size + else: + r = None + + if r is not None: + if dim is None: + return RetVariable(r) + else: + return ConstantVariable.create(r[dim]) + + # It might still be constant! Consult the fake tensor and see + if (fake := self.proxy.node.meta.get("example_value")) is not None: + if dim is None: + fake_r = getattr(fake, name)() + if not has_free_symbols(fake_r): + # int conversion for safety, in case a SymInt refined + # to constant + return RetVariable(tuple(int(r) for r in fake_r)) + else: + fake_r = getattr(fake, name)(dim) + if not has_free_symbols(fake_r): + return ConstantVariable.create(int(fake_r)) + return None + + def method_numel(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + if self.valid_size(): + return VariableTracker.build(tx, product(self.size)) + + # It might still be constant! Consult the fake tensor and see + if (fake := self.proxy.node.meta.get("example_value")) is not None: + fake_r = fake.numel() + if not has_free_symbols(fake_r): + return VariableTracker.build(tx, int(fake_r)) + return None + + method_nelement = method_numel + + def method_dim(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + if self.ndim is not None: + return VariableTracker.build(tx, self.ndim) + return None + + method_ndimension = method_dim + + def method_is_floating_point( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.dtype is not None: + return VariableTracker.build(tx, self.dtype.is_floating_point) + return None + + def method_is_inference( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if config.fake_tensor_disable_inference_mode: + unimplemented( + gb_type="Encountered tensor.is_inference() during tracing", + context="", + explanation="tensor.is_inference() is not supported", + hints=[ + *graph_break_hints.FUNDAMENTAL, + *graph_break_hints.INFERENCE_MODE, + ], + ) + if (fake := self.proxy.node.meta.get("example_value")) is not None: + return VariableTracker.build(tx, fake.is_inference()) + return None + + def method_is_complex( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.dtype is not None: + return VariableTracker.build(tx, self.dtype.is_complex) + return None + + def method_is_contiguous( + self, + tx: "InstructionTranslatorBase", + memory_format: VariableTracker | None = None, + ) -> ConstantVariable | None: + memory_format_const = ( + memory_format.as_python_constant() + if memory_format is not None + else torch.contiguous_format + ) + if self.is_contiguous is not None: + # pyrefly: ignore[not-iterable] + return VariableTracker.build(tx, memory_format_const in self.is_contiguous) + elif (fake := self.proxy.node.meta.get("example_value")) is not None: + return VariableTracker.build( + tx, fake.is_contiguous(memory_format=memory_format_const) + ) + return None + + def method_type( + self, + tx: "InstructionTranslatorBase", + dtype: Any | None = None, + non_blocking: bool = False, + **kwargs: Any, + ) -> VariableTracker | None: + if ( + dtype is None + and self.dtype is not None + and isinstance(self.device, torch.device) + ): + tensortype = next( + k for k, v in tensortype_to_dtype.items() if self.dtype in v + ) + if self.device.type == "cpu": + return VariableTracker.build(tx, f"torch.{tensortype.__name__}") + else: + return VariableTracker.build( + tx, f"torch.{self.device.type}.{tensortype.__name__}" + ) + elif ( + dtype is not None + and fqn(type(dtype.as_python_constant())) == "torch.tensortype" + ): + # torch.FloatTensor, etc. are all of type "torch.tensortype". + # torch.fx's tracer fails on these types, because it doesn't support arguments of torch.tensortype type. + # So, we pass it in as a string (which is also supported, see above implementation for .type() with 0 args) + tensor_type = dtype.as_python_constant() + tensor_type_const = VariableTracker.build(tx, fqn(tensor_type)) + + from .builder import wrap_fx_proxy + + if non_blocking: + kwargs = {"non_blocking": non_blocking, **kwargs} + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_method", + "type", + *proxy_args_kwargs([self, tensor_type_const], kwargs), + ), + ) + return None + + def method_as_subclass( + self, tx: "InstructionTranslatorBase", cls: VariableTracker + ) -> "TensorWithTFOverrideVariable": + if isinstance(cls, TensorSubclassVariable) and cls.source: + from .torch_function import TensorWithTFOverrideVariable + + py_cls = cls.as_python_constant() + var = TensorWithTFOverrideVariable.from_tensor_var( + tx, self, py_cls, cls.source + ) + # See NOTE [Side effect tracking for newly constructed tensor] + tx.output.side_effects._track_obj( + object(), var, mutation_type_cls=AttributeMutationNew + ) + return var + unimplemented( + gb_type="Argument of `as_subclass` must be a non-dispatcher-style tensor subclass", + context=f"{self}.as_subclass({cls})", + explanation="Currently not supported", + hints=[ + "Avoid this call or move it outside `torch.compile` region", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def method_get_device( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker | None: + if isinstance(self.device, torch.device): + index = self.device.index if self.device.type != "cpu" else -1 + return VariableTracker.build(tx, index) + return None + + def method_element_size(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return VariableTracker.build(tx, self.dtype.itemsize) + + def method_numpy( + self, tx: "InstructionTranslatorBase", *, force: VariableTracker | bool = False + ) -> "NumpyNdarrayVariable": + if not config.trace_numpy: + unimplemented( + gb_type="Tensor.numpy() with trace_numpy=False", + context=f"call_method {self} numpy", + explanation="`Tensor.numpy()` was called, but the `trace_numpy` " + "configuration was manually disabled.", + hints=[ + "Set `torch._dynamo.config.trace_numpy = True` to allow " + "Dynamo to trace through NumPy.", + ], + ) + if not np: + unimplemented( + gb_type="Tensor.numpy() without NumPy installed", + context=f"call_method {self} numpy", + explanation="`Tensor.numpy()` was called, but the NumPy library " + "is not available in the current environment.", + hints=[ + "Ensure NumPy is installed in your Python environment.", + ], + ) + if self.layout != torch.strided: + raise TypeError( + f"can't convert {self.layout} layout tensor to numpy. Use Tensor.to_dense() first" + ) + + # We don't check that the tensor is on CPU when force is False, as this + # allows us to execute NumPy code on CUDA. Same for requires_grad=True + if force and force.as_python_constant(): # type: ignore[attr-defined] + # If the user set force=True we try to preserve the semantics (no gradients, move to CPU...) + t = self.call_method(tx, "detach", [], {}) + proxy = tx.output.create_proxy("call_method", "cpu", (t.as_proxy(),), {}) + else: + # Hacky way to create a view of self that will be marked as NumpyNdarrayVariable + proxy = tx.output.create_proxy( + "call_method", "view_as", *proxy_args_kwargs([self, self], {}) + ) + return NumpyNdarrayVariable.create(tx, proxy) + + def method_tolist(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .builder import wrap_fx_proxy + + def tolist(tensor: torch.Tensor, sub_proxy: torch.fx.Proxy) -> Any | list[Any]: + def wrap(i: Any, sub_proxy: torch.fx.Proxy) -> VariableTracker: + return wrap_fx_proxy( + tx, + sub_proxy.item(), + ) + + if tensor.dtype not in [ + torch.int8, + torch.int16, + torch.int32, + torch.int64, + ]: + unimplemented( + gb_type="Tensor.tolist() with non-integer tensor", + context=f"call_method {self} to_list", + explanation="Dynamo currently does not support tracing " + "`tolist()` on non-integer tensors.", + hints=[ + "Ensure the input tensor to `tolist()` is an integer " + "type (e.g., int8, int16, int32, int64)." + ], + ) + + if tensor.dim() == 0: + return wrap(tensor, sub_proxy) + + if tensor.dim() == 1: + return [wrap(val, sub_proxy[i]) for i, val in enumerate(tensor)] + + return [ + tolist(sub_tensor, sub_proxy=sub_proxy[i]) + for i, sub_tensor in enumerate(tensor) + ] + + tensor = self.as_proxy().node.meta["example_value"] + out = tolist(tensor, self.as_proxy()) + return VariableTracker.build(tx, out) + + def _collect_backward_inputs( + self, vars_iter: Iterable[VariableTracker], error_on_non_leaf: bool = False + ) -> list[VariableTracker] | None: + """ + Collect unique leaf tensors from vars_iter for backward. + + Only collects leaf tensors (no grad_fn). Non-leaf tensors are skipped + (or error if error_on_non_leaf=True) because when auto-detecting inputs, + we must not stop gradients at non-leafs - they are intermediates, and the + real leaf tensors (parameters) are further up the autograd graph. + + Deduplicates by proxy.node. + Returns list of unique leaf tensor variables. + """ + from ..source import SyntheticLocalSource + + result = [] + seen_nodes: set[torch.fx.Node] = set() + for var in vars_iter: + if isinstance(var, TensorVariable) and var.requires_grad: + # Non-leaf tensors (has_grad_fn=True) must be skipped because: + # 1. Semantically: they're intermediates, not the leaves we want gradients for + # 2. Implementation: the backward rewrite can't handle .grad on non-leafs + # (Dynamo creates GetAttrVariable instead of TensorVariable) + # + # In-graph created tensors without proper source also can't be handled + # when user explicitly passes them as inputs, because + # subguards_allowed() returns False for SyntheticLocalSource. + # However, in auto-detect mode (error_on_non_leaf=False), source-less + # leaves are valid backward targets — they gained requires_grad via + # requires_grad_() and accumulate_grad_ writes to .grad directly. + if var.has_grad_fn: + if error_on_non_leaf: + unimplemented( + gb_type="backward() with non-leaf tensor", + context=f"backward(inputs=[...]) with non-leaf tensor: {var}", + explanation="backward(inputs=[...]) with non-leaf tensors is not yet supported.", + hints=[ + "Only pass leaf tensors (parameters, graph inputs) to backward(inputs=...)", + ], + ) + elif error_on_non_leaf and ( + not var.source or isinstance(var.source, SyntheticLocalSource) + ): + unimplemented( + gb_type="backward() with in-graph created tensor", + context=f"backward(inputs=[...]) with in-graph created tensor: {var}", + explanation="backward(inputs=[...]) with tensors created inside the " + "compiled function is not yet supported.", + hints=[ + "Only pass tensors that are inputs to the compiled function or captured from outside", + ], + ) + else: + node = var.proxy.node + if node not in seen_nodes: + seen_nodes.add(node) + result.append(var) + # pyrefly: ignore [bad-return] + return result + + def method_backward( + self, + tx: "InstructionTranslatorBase", + gradient: VariableTracker | None = None, + retain_graph: VariableTracker | None = None, + create_graph: VariableTracker | None = None, + inputs: VariableTracker | None = None, + ) -> VariableTracker | None: + """ + Trace tensor.backward() by rewriting as autograd.grad() + accumulate_grad. + + Implementation: + 1. Collect leaf tensors to compute gradients for + 2. Call autograd.grad(loss, inputs) to compute gradients + 3. For each leaf tensor, call accumulate_grad to update .grad + + Non-leaf tensor handling: + - Auto-detect (inputs=None): Non-leaf tensors are silently skipped. + This matches eager where only leaves get .grad. + - User-provided (inputs=[...]): Errors if any non-leaf tensor is found. + While eager backward(inputs=[non_leaf]) works, Dynamo cannot trace it + because the backward rewrite accesses .grad, and Dynamo creates + a generic GetAttrVariable for .grad on non-leaf tensors (instead of a + TensorVariable), which cannot be used in tensor operations. + + TODO: Support non-leaf tensors by fixing .grad access on non-leaf in Dynamo. + """ + if not config.trace_autograd_ops: + unimplemented( + gb_type="Unsupported Tensor.backward() call", + context=f"call_method {self} backward {gradient} {retain_graph} {create_graph} {inputs}", + explanation="Dynamo currently does not support tracing `Tensor.backward()` when trace_autograd_ops is off.", + hints=["Set torch._dynamo.trace_autograd_ops=True"], + ) + + if not self.requires_grad and not self.has_grad_fn: + raise TorchRuntimeError( + "tensor does not require grad and does not have a grad_fn" + ) + + # Step 1: Collect leaf tensors to compute gradients for + # + # Note: We rely on the autograd.grad handler to validate that the generated + # autograd.grad call is legal (i.e., doesn't traverse external grad_fns). + # If the loss depends on leaves we don't know about, the autograd.grad + # handler will catch it via the external_grad_fns check. + auto_detect = inputs is None + if auto_detect: + # Sources can be either user inputs (params are included here) + # or parameters that are created in forward. + all_vars = chain( + tx.output.leaf_var_creation_order, + tx.output.input_source_to_var.values(), + ) + input_vars = self._collect_backward_inputs(all_vars) + if not input_vars: + # No leaf tensors found - nothing to accumulate gradients into. + # This matches eager behavior where backward() is a no-op if there + # are no leaves requiring grad. + return ConstantVariable.create(None) + else: + if isinstance(inputs, variables.BaseListVariable): + provided_vars = inputs.items + elif isinstance(inputs, variables.ConstDictVariable): + provided_vars = list(inputs.items.values()) + else: + provided_vars = [inputs] + input_vars = self._collect_backward_inputs( + provided_vars, error_on_non_leaf=True + ) + if not input_vars: + # User explicitly provided inputs but none were valid leaf tensors. + # This would cause "grad requires non-empty inputs" error at runtime. + unimplemented( + gb_type="backward() with empty inputs", + context="backward(inputs=[...]) resulted in no valid leaf tensors", + explanation="backward(inputs=[...]) requires at least one valid leaf tensor.", + hints=[ + "Ensure at least one tensor in inputs is a leaf (requires_grad=True, no grad_fn)", + ], + ) + + # Build autograd.grad call + grad_kwargs = {"allow_unused": VariableTracker.build(tx, auto_detect)} + if retain_graph is not None: + grad_kwargs["retain_graph"] = retain_graph + if create_graph is not None: + grad_kwargs["create_graph"] = create_graph + + inputs_var = VariableTracker.build(tx, input_vars) + grad_args = [self, inputs_var] + if gradient is not None: + grad_args.append(gradient) + + autograd_grad_fn = VariableTracker.build(tx, torch.autograd.grad) + grads_var = autograd_grad_fn.call_function(tx, grad_args, grad_kwargs) + + # Accumulate gradients for unique leaf tensors under no_grad context + # to replicate eager autograd engine. + from .ctx_manager import GradModeVariable + + grad_mode_var = GradModeVariable.create(tx, False, initialized=True) + grad_mode_var.enter(tx) + + accumulate_grad_fn = VariableTracker.build( + tx, torch.ops.inductor.accumulate_grad_.default + ) + if input_vars is None: + raise AssertionError("input_vars must not be None") + for idx, input_var in enumerate(input_vars): + grad_i = grads_var.call_method( + tx, "__getitem__", [VariableTracker.build(tx, idx)], {} + ) + accumulate_grad_fn.call_function(tx, [input_var, grad_i], {}) + + grad_mode_var.exit(tx) + + return ConstantVariable.create(None) + + def method_data_ptr( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> "DataPtrVariable": + return DataPtrVariable(self) + + def method_const_data_ptr( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> "DataPtrVariable": + return DataPtrVariable(self, method_name="const_data_ptr") + + def method_record_stream( + self, + tx: "InstructionTranslatorBase", + stream: VariableTracker, + ) -> VariableTracker: + from .streams import StreamVariable + + if not isinstance(stream, StreamVariable): + raise RuntimeError( + f"record_stream() expects a Stream argument, got {stream.python_type().__name__}" + ) + tx.output.create_proxy( + "call_function", + torch.ops.streams.record_stream, + (self.as_proxy(), stream.user_object_index), + {}, + ) + return ConstantVariable.create(None) + + def method_item( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> None: + # We enable capture_scalar_outputs when full_graph=True by default. + if not tx.one_graph and not config.capture_scalar_outputs: + self._warn_capture_scalar_outputs() + unimplemented( + gb_type="Unsupported Tensor.item() call with capture_scalar_outputs=False", + context=f"call_method {self} item {args} {kwargs}", + explanation="Dynamo does not support tracing `Tensor.item()` " + "with config.capture_scalar_outputs=False.", + hints=[ + "Set `torch._dynamo.config.capture_scalar_outputs = True` " + "or `export TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS=1` " + "to include these operations in the captured graph.", + ], + ) + return None + + def nb_index_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: only integer tensors of a single element can be converted + # to an index. Mirrors THPVariable_index_scalar in + # https://github.com/pytorch/pytorch/blob/7cfd054075b/tools/autograd/templates/python_variable_methods.cpp#L372-L385 + if self.dtype is not None and ( + not self.dtype.is_floating_point and not self.dtype.is_complex + ): + item = self.call_method(tx, "item", [], {}) + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + sym_int, + (item.as_proxy(),), + {}, + ), + ) + raise_observed_exception( + TypeError, + tx, + args=[ + "only integer tensors of a single element can be converted to an index" + ], + ) + + def nb_int_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: THPVariable_integral_scalar handles both integer and float + # tensors (floats are truncated to int). Complex tensors raise + # RuntimeError at runtime. + if self.dtype is not None and self.dtype.is_complex: + raise_observed_exception( + RuntimeError, + tx, + args=["value cannot be converted to type int64_t without overflow"], + ) + # For known non-complex dtypes and unknown dtype (None), emit the + # proxy and let it fail at runtime if the dtype is unsupported. + item = self.call_method(tx, "item", [], {}) + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + sym_int, + (item.as_proxy(),), + {}, + ), + ) + + def method___int__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_int_impl(tx) + + def nb_float_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: THPVariable_float_scalar dispatches to double. + # Complex tensors raise RuntimeError at runtime. + if self.dtype is not None and self.dtype.is_complex: + raise_observed_exception( + RuntimeError, + tx, + args=["value cannot be converted to type double without overflow"], + ) + item = self.call_method(tx, "item", [], {}) + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + sym_float, + (item.as_proxy(),), + {}, + ), + ) + + def method___float__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_float_impl(tx) + + def nb_negative_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + operator.neg, + (self.as_proxy(),), + {}, + ), + ) + + def method___neg__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_negative_impl(tx) + + def nb_positive_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + operator.pos, + (self.as_proxy(),), + {}, + ), + ) + + def method___pos__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_positive_impl(tx) + + def nb_absolute_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + operator.abs, + (self.as_proxy(),), + {}, + ), + ) + + def method___abs__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_absolute_impl(tx) + + def nb_invert_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + operator.invert, + (self.as_proxy(),), + {}, + ), + ) + + def method___invert__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_invert_impl(tx) + + def method___getitem__( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if isinstance(args[0], SymNodeVariable): + # Standard indexing will force specialization due to + # __index__. Rewrite as a regular torch op which will + # trace fine + fn, args = ( # type: ignore[assignment] + torch.select, + [ + VariableTracker.build(tx, 0), + args[0], + ], + ) + else: + fn = operator.getitem + + proxy = tx.output.create_proxy( + "call_function", + fn, + *proxy_args_kwargs([self] + list(args), kwargs), + ) + + return wrap_fx_proxy(tx, proxy) + + @staticmethod + @functools.cache + def _warn_capture_scalar_outputs() -> None: + user_stack = torch._guards.TracingContext.extract_stack() + user_stack_formatted = "".join(traceback.format_list(user_stack)) + log.warning( + textwrap.dedent( + """\ + Graph break from `Tensor.item()`, consider setting: + torch._dynamo.config.capture_scalar_outputs = True + or: + env TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS=1 + to include these operations in the captured graph. + + Graph break: from user code at: + %s + """ + ), + user_stack_formatted, + ) + + def method___len__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.sq_length_impl(tx) + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Sequence length for tensors (size along first dimension).""" + return self.call_method(tx, "size", [VariableTracker.build(tx, 0)], {}) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return ListIteratorVariable( + self.unpack_var_sequence(tx), mutation_type=ValueMutationNew() + ) + + def method___iter__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.tp_iter_impl(tx) + + def method_addcmul_( + self, + tx: "InstructionTranslatorBase", + tensor1: Any, + tensor2: Any, + *, + value: Any | None = None, + ) -> Any | None: + if value is not None and config.enable_dynamo_decompositions: + from torch._inductor import inductor_prims + + mul_var = variables.TorchInGraphFunctionVariable(torch.mul) + fma_var = variables.TorchInGraphFunctionVariable(inductor_prims.fma) + product = mul_var.call_function(tx, [tensor1, tensor2], {}) + result = fma_var.call_function(tx, [product, value, self], {}) + return self.call_method(tx, "copy_", [result], {}) + return None + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + if value is None: + raise_type_error(tx, "Tensor does not support deleting items") + return self.method___setitem__(tx, key, value) + + def method___setitem__( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker, + ) -> VariableTracker: + proxy = tx.output.create_proxy( + "call_function", + operator.setitem, + *proxy_args_kwargs([self, key, value], {}), + ) + + # See Note [Inplace ops and VariableTracker metadata] + # __setitem__ is always an inplace operation. We need to run fake execution + # and propagate metadata if self was mutated. + # The context managers handle saved tensor hooks and unbacked symbols. + version_before = self._get_fake_version() + + with ( + torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing(), + tx.fake_mode.shape_env.ignore_fresh_unbacked_symbols() + if tx.fake_mode and tx.fake_mode.shape_env + else nullcontext(), + ): + get_fake_value(proxy.node, tx, allow_non_graph_fake=False) + + self._sync_if_inplace_mutation(tx, version_before) + + if config.use_graph_deduplication or config.track_nodes_for_deduplication: + tx.output.region_tracker.add_node_mutation(proxy.node, 0) + + return ConstantVariable.create(None) + + def method_resize_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> NoReturn: + unimplemented( + gb_type="Unsupported Tensor.resize_() call", + context=f"call_method {self} resize_ {args} {kwargs}", + explanation="Dynamo currently does not support tracing `Tensor.resize_()`.", + hints=[], + ) + + def method_resize_as_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> NoReturn: + unimplemented( + gb_type="Unsupported Tensor.resize_as_() call", + context=f"call_method {self} resize_as_ {args} {kwargs}", + explanation="Dynamo currently does not support tracing `Tensor.resize_as_()`.", + hints=[], + ) + + def method_sparse_resize_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> NoReturn: + unimplemented( + gb_type="Unsupported Tensor.sparse_resize_() call", + context=f"call_method {self} sparse_resize_ {args} {kwargs}", + explanation="Dynamo currently does not support tracing `Tensor.sparse_resize_()`.", + hints=[], + ) + + def method_sparse_resize_and_clear_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> NoReturn: + unimplemented( + gb_type="Unsupported Tensor.sparse_resize_and_clear_() call", + context=f"call_method {self} sparse_resize_and_clear_ {args} {kwargs}", + explanation="Dynamo currently does not support tracing `Tensor.sparse_resize_and_clear_()`.", + hints=[], + ) + + def method_set_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> None: + if len(args) > 1: + # torch.Tensor.set_() has several overloads. + # aten::set_.source_Tensor(Tensor) gets special handling + # in AOTAutograd and functionalization, because it is the most common + # overload and is used by FSDP. + # graph-breaking on aten::set_source_Tensor_storage_offset for now, + # unless we find that we need to make it work. + unimplemented( + gb_type="Unsupported Tensor.set_() call", + context=f"call_method {self} set_ {args} {kwargs}", + explanation="Dynamo currently does not support tracing `Tensor.set_()` " + "overloads that include more than one argument.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + return None + + def method_add_( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + *, + alpha: VariableTracker | None = None, + ) -> VariableTracker | None: + # Tensor alpha: ATen would call .item() and fma internally. + # Use fma directly to avoid the item() graph break. + if ( + alpha is not None + and isinstance(alpha, TensorVariable) + and config.enable_dynamo_decompositions + ): + from torch._inductor import inductor_prims + + fma_var = variables.TorchInGraphFunctionVariable(inductor_prims.fma) + result = fma_var.call_function(tx, [other, alpha, self], {}) + return self.call_method(tx, "copy_", [result], {}) + return None + + def method_addcdiv_( + self, + tx: "InstructionTranslatorBase", + tensor1: "TensorVariable", + tensor2: "TensorVariable", + *, + value: VariableTracker | None = None, + ) -> VariableTracker | None: + if value is not None and config.enable_dynamo_decompositions: + result = variables.TorchInGraphFunctionVariable(torch.div).call_function( + tx, [tensor1, tensor2], {} + ) + from torch._inductor import inductor_prims + + fma_var = variables.TorchInGraphFunctionVariable(inductor_prims.fma) + fma_result = fma_var.call_function(tx, [result, value, self], {}) + return self.call_method(tx, "copy_", [fma_result], {}) + return None + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # Rewrite __contains__ here so that downstream passes can trace through + # without dealing with unbacked symbool. Roughly the code we translate is: + # def __contains__(self, x): + # return (x == self).any().item() + result = variables.TorchInGraphFunctionVariable(torch.eq).call_function( + tx, [self, item], {} + ) + result = variables.TorchInGraphFunctionVariable(torch.any).call_function( + tx, [result], {} + ) + return result.call_method(tx, "item", [], {}) + + def method___contains__( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + return self.sq_contains_impl(tx, arg) + + def method_register_hook( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return self._method_register_hook(tx, "register_hook", *args, **kwargs) + + def method_register_post_accumulate_grad_hook( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return self._method_register_hook( + tx, "register_post_accumulate_grad_hook", *args, **kwargs + ) + + def _method_register_hook( + self, tx: "InstructionTranslatorBase", name: str, hook: VariableTracker + ) -> VariableTracker: + # Note - do not arbitrarily add hooks here - make sure they match the same contract + # see [On tensor.register_hook] + + if not self.source: + # For intermediate tensors (those without a source), we have two approaches: + # 1. When compiled autograd is enabled: use BackwardState to defer hook execution + # 2. When compiled autograd is NOT enabled: use a custom autograd function + if compiled_autograd.compiled_autograd_enabled: + # Use the BackwardState approach for compiled autograd + hook_name, bw_state_proxy = tx.output.add_backward_state_hook(hook) + + def _register_hook_trampoline( + tensor: torch.Tensor, bw_state: compiled_autograd.BackwardState + ) -> None: + register_hook = getattr(tensor, name) + register_hook( + functools.partial( + trace_wrapped, + fn=call_hook_from_backward_state, + bw_state=bw_state, + hook_name=hook_name, + ) + ) + # TODO(jansel): returning None here is wrong, it should be + # RemovableHandle, but we need some extra work to support + # this properly. + return None + + from .builder import wrap_fx_proxy + + self_proxy = self.as_proxy() + self_proxy.node.meta["has_backward_hook"] = True + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + _register_hook_trampoline, + (self_proxy, bw_state_proxy), + {}, + ), + ) + # Register the hook via a trampoline in the graph where the + # tensor's proxy lives. During AOTAutograd's make_fx, the + # trampoline calls tensor.register_hook(hook_fn). The hook + # fires on the accumulated gradient during backward + # tracing, matching eager semantics. When inside a subgraph + # (e.g. checkpoint), the node is created in the parent + # graph so the hook is not confined to the HOP scope. + from .higher_order_ops import speculate_subgraph + + tensor_proxy = self.as_proxy() + target_tracer = tensor_proxy.tracer + + # Trace the hook body with strict mode so stride-dependent + # operations (e.g. is_contiguous()) graph break instead of + # silently specializing on the FakeTensor's strides. + try: + with tx.strict_translation_mode(lambda v: v.is_tensor()): + (body_r, _), hook_graph, hook_freevars = speculate_subgraph( + tx, + hook, + [self], + {}, + "register_hook", + source_target=None, + enable_grad=None, + set_subgraph_inputs="automatic_with_forced_inputs", + restore_side_effects=True, + ) + except torch._dynamo.exc.UnknownPropertiesDuringBackwardTrace: + unimplemented( + gb_type="register_hook with stride-dependent code", + context="Hook accesses grad metadata (e.g. is_contiguous)", + explanation="register_hook callbacks that branch on " + "gradient metadata are not supported because grad " + "properties are unknown at trace time.", + hints=[], + ) + + hook_nn_modules = tx.output.tracing_context.module_context.copy_graphstate() + hook_name = tx.output.install_subgraph( + "hook_body", + torch.fx.GraphModule(hook_nn_modules.nn_modules, hook_graph), + ) + hook_node = target_tracer.create_proxy("get_attr", hook_name, (), {}) + + from torch._higher_order_ops.register_hook import register_hook_op + + p_args = (tensor_proxy, hook_node, *list(hook_freevars.keys())) + hooked_proxy = target_tracer.create_proxy( + "call_function", + register_hook_op, + tuple(p_args), + {}, + ) + hooked_proxy.node.meta["example_value"] = tensor_proxy.node.meta[ + "example_value" + ] + self.proxy = hooked_proxy + self.synchronize_attributes(tx) + return variables.RemovableHandleVariable( + mutation_type=variables.base.ValueMutationNew(), + ) + + handle_variable = variables.RemovableHandleVariable( + mutation_type=variables.base.ValueMutationNew(), + ) + tx.output.side_effects.register_hook(self, hook, handle_variable, name) + return handle_variable + + def method_requires_grad_( + self, + tx: "InstructionTranslatorBase", + requires_grad: bool | VariableTracker = True, + ) -> VariableTracker: + if requires_grad is not True: + requires_grad = requires_grad.as_python_constant() # type: ignore[attr-defined] + + node = self.as_proxy().node + example_value = node.meta["example_value"] + if example_value.requires_grad != requires_grad: + # For graph inputs (tensors with source), requires_grad_() is a + # metadata mutation that we can't trace — graph break as before. + if self.source: + unimplemented( + gb_type="Unsupported Tensor.requires_grad_() call", + context=f"call_method {self} requires_grad_", + explanation="Dynamo does not support changes to a Tensor's " + "`requires_grad` through calling `requires_grad_()`.", + hints=[], + ) + # On a previous attempt, we traced through requires_grad_() but + # discovered at compile time that the tainted intermediate leaked + # as a graph output. Graph break here to preserve partial + # acceleration for code before requires_grad_(). + if tx.speculation_log.graph_break_on_requires_grad_: + unimplemented( + gb_type="requires_grad_() intermediate leaked as output", + context=f"call_method {self} requires_grad_", + explanation="An intermediate tensor with requires_grad_() called " + "on it (or a tensor derived from it) is returned from the " + "compiled region. Graph breaking here to preserve partial " + "acceleration.", + hints=[ + "Call .detach() before returning if you only need values.", + "Consume the gradient inside the compiled function " + "(call backward() and use .grad), " + "or move requires_grad_() outside torch.compile.", + ], + ) + # AOTAutograd re-traces the FX graph under functorch transforms + # (functionalization). Functorch's checkSupportsInplaceRequiresGrad() + # rejects requires_grad_() when the dynamic layer stack is non-empty. + # We wrap the call with set_inplace_requires_grad_allowed(True) to + # bypass this check, matching GradInplaceRequiresGradCtxManagerVariable + # in ctx_manager.py (which handles the explicit context manager case). + # + # Lines below do two things in parallel: + # 1. Mutate trace-time state so example_value.requires_grad_() works + # 2. Emit FX nodes so the same toggle happens during AOTAutograd re-trace + prev_state = torch._C._functorch.get_inplace_requires_grad_allowed() + torch._C._functorch.set_inplace_requires_grad_allowed(True) + try: + tx.output.create_node( + "call_function", + torch._C._functorch.set_inplace_requires_grad_allowed, + (True,), + {}, + ) + tx.output.create_proxy( + "call_method", + "requires_grad_", + (self.as_proxy(),), + {}, + ) + tx.output.create_node( + "call_function", + torch._C._functorch.set_inplace_requires_grad_allowed, + (prev_state,), + {}, + ) + finally: + torch._C._functorch.set_inplace_requires_grad_allowed(prev_state) + example_value.requires_grad_(requires_grad) + self.requires_grad = requires_grad + if requires_grad: + tx.output.leaf_var_creation_order.append(self) + # For source-less intermediates, initialize .grad = None in + # side effects so the backward rewrite can read/write + # .grad naturally. Graph inputs don't need this — they handle + # .grad through their source. + if not self.source and tx.output.side_effects.is_attribute_mutation( + self + ): + tx.output.side_effects.store_attr( + self, "grad", variables.ConstantVariable.create(None) + ) + return self + + def method_detach_(self, tx: "InstructionTranslatorBase") -> "TensorVariable": + from .builder import wrap_fx_proxy + + proxy = tx.output.create_proxy( + "call_method", + "detach_", + (self.as_proxy(),), + {}, + ) + # Run the fake op so the proxy metadata reflects the detached tensor state. + wrap_fx_proxy(tx, proxy) + self.synchronize_attributes(tx) + return self + + def method_share_memory_(self, tx: "InstructionTranslatorBase") -> NoReturn: + unimplemented( + gb_type="Unsupported Tensor.share_memory_() call", + context=f"call_method {self} share_memory_", + explanation="Dynamo does not support Tensor.share_memory_() which modifies tensor storage for IPC", + hints=[ + "Move share_memory_() call outside the compiled region. ", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def method_new( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + # Convert x.new(torch.Size) into x.new_empty(torch.Size), + # as Tensor.new acts differently with a Size input versus a tuple input. + if (len(args) == 1 and isinstance(args[0], SizeVariable)) or ( + len(args) >= 1 + and all( + a.is_python_constant() and isinstance(a.as_python_constant(), int) + for a in args + ) + ): + return self.call_method(tx, "new_empty", list(args), kwargs) + return None + + def method_new_tensor( + self: "TensorVariable", + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if len(args) != 1: + return None + data_arg = args[0] + layout = kwargs.get("layout") + if layout is not None: + if not layout.is_python_constant(): + return None + if layout.as_python_constant() != torch.strided: + return None + fwd_kwargs = dict(kwargs) + fwd_kwargs.pop("layout", None) + fwd_kwargs.setdefault("dtype", self.tp_getattro_impl(tx, "dtype")) + fwd_kwargs.setdefault("device", self.tp_getattro_impl(tx, "device")) + return variables.TorchInGraphFunctionVariable(torch.tensor).call_function( + tx, + [data_arg], + fwd_kwargs, + ) + + def method_untyped_storage( + self, tx: "InstructionTranslatorBase" + ) -> "UntypedStorageVariable": + return UntypedStorageVariable( + self, self.as_proxy().node.meta["example_value"].untyped_storage() + ) + + def method_wait( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if args or kwargs: + raise torch._dynamo.exc.InternalTorchDynamoError( + "`wait` and `wait_tensor` do not take any arguments" + ) + from torch.distributed._functional_collectives import wait_tensor + + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", wait_tensor, (self.as_proxy(),), {} + ), + ) + + def method_random_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> NoReturn: + # For historical reasons, these ops decompose down to syntactically + # invalid aten ops because they contain the python keyword `from`, see + # discussions in #151432 for more details. + # We graph break for now since this use case is uncommon. + unimplemented( + gb_type="Tensor.random_ op", + context=f"Tensor.random_({args=}, {kwargs=})", + explanation="This is currently not supported.", + hints=[ + "Use the out-of-place version of this op", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def method_uniform_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if "from" in kwargs: + unimplemented( + gb_type="Tensor.uniform_ op called with `from` keyword", + context=f"Tensor.uniform_({args=}, {kwargs=})", + explanation="This is currently not supported.", + hints=[ + "Avoid using the `from` keyword.", + *graph_break_hints.SUPPORTABLE, + ], + ) + return None + + # Named-method dispatch table (see call_method). Each entry mirrors a + # CPython PyMethodDef: the handler keeps its native Python signature and + # `flags` (ml_flags) drive centralized arity checking. Tensor methods + # without an entry fall through to the generic FX-proxy path in call_method. + tp_methods = { + "size": Method(method_size), + "stride": Method(method_stride), + "numel": Method(method_numel), + "nelement": Method(method_nelement), + "dim": Method(method_dim), + "ndimension": Method(method_ndimension), + "is_floating_point": Method(method_is_floating_point), + "is_inference": Method(method_is_inference), + "is_complex": Method(method_is_complex), + "is_contiguous": Method(method_is_contiguous), + "type": Method(method_type), + "as_subclass": Method(method_as_subclass), + "get_device": Method(method_get_device), + "element_size": Method(method_element_size), + "numpy": Method(method_numpy), + "tolist": Method(method_tolist), + "backward": Method(method_backward), + "data_ptr": Method(method_data_ptr), + "const_data_ptr": Method(method_const_data_ptr), + "record_stream": Method(method_record_stream), + "item": Method(method_item), + "__int__": Method(method___int__), + "__float__": Method(method___float__), + "__neg__": Method(method___neg__), + "__pos__": Method(method___pos__), + "__abs__": Method(method___abs__), + "__invert__": Method(method___invert__), + "__getitem__": Method(method___getitem__), + "__len__": Method(method___len__), + "__iter__": Method(method___iter__), + "__setitem__": Method(method___setitem__), + "__contains__": Method(method___contains__), + "addcmul_": Method(method_addcmul_), + "addcdiv_": Method(method_addcdiv_), + "add_": Method(method_add_), + "resize_": Method(method_resize_), + "resize_as_": Method(method_resize_as_), + "sparse_resize_": Method(method_sparse_resize_), + "sparse_resize_and_clear_": Method(method_sparse_resize_and_clear_), + "set_": Method(method_set_), + "register_hook": Method(method_register_hook), + "register_post_accumulate_grad_hook": Method( + method_register_post_accumulate_grad_hook + ), + "requires_grad_": Method(method_requires_grad_), + "detach_": Method(method_detach_), + "share_memory_": Method(method_share_memory_), + "new": Method(method_new), + "new_tensor": Method(method_new_tensor), + "untyped_storage": Method(method_untyped_storage), + "wait": Method(method_wait), + "random_": Method(method_random_), + "uniform_": Method(method_uniform_), + } + + def set_name_hint(self, name: str) -> None: + if not self._is_name_set: + self.proxy.node._rename(name) + self._is_name_set = True + return None + + def nb_add_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1139 (PyNumber_Add) + from .builder import wrap_fx_proxy + + if not (isinstance(other, TensorVariable) or _is_sym_arith_operand(other)): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + proxy = tx.output.create_proxy( + "call_function", operator.add, *proxy_args_kwargs(args, {}) + ) + # Tensor dominates: any of Tensor+Tensor, Tensor+SymNode, Tensor+scalar + # produces a Tensor. + return wrap_fx_proxy(tx=tx, proxy=proxy) + + def nb_lshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.lshift, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_rshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.rshift, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.or_, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.and_, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.xor, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__mul__(x)`` calls — the + # ``operator.mul`` path goes through ``_handle_insert_op_in_graph`` + # in ``BuiltinVariable``. Build the same FX proxy. + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.mul, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_matrix_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__matmul__(x)`` calls. + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.matmul, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_floor_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__floordiv__(x)`` calls — the + # ``operator.floordiv`` path goes through ``_handle_insert_op_in_graph`` + # in ``BuiltinVariable``. Build the same FX proxy. + if not (isinstance(other, TensorVariable) or _is_sym_arith_operand(other)): + return VariableTracker.build(tx, NotImplemented) + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.floordiv, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_true_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__truediv__(x)`` calls — the + # ``operator.truediv`` path goes through ``_handle_insert_op_in_graph`` + # in ``BuiltinVariable``. Build the same FX proxy. + if not (isinstance(other, TensorVariable) or _is_sym_arith_operand(other)): + return VariableTracker.build(tx, NotImplemented) + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.truediv, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_remainder_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__mod__(x)`` calls — the + # ``operator.mod`` path goes through ``_handle_insert_op_in_graph`` + # in ``BuiltinVariable``. Build the same FX proxy. + if not (isinstance(other, TensorVariable) or _is_sym_arith_operand(other)): + return VariableTracker.build(tx, NotImplemented) + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.mod, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # Tensor.__hash__ is `return id(self)`, so hash == id. + # Always use the FakeTensor identity so aliased tensors + # (e.g. y = x.add_(1)) hash consistently. + fake = self.as_proxy().node.meta["example_value"] + return id(fake), True + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1135 (PyNumber_Subtract) + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.sub, *proxy_args_kwargs(args, {}) + ), + sym_num=None, + ) + + def nb_power_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + z: VariableTracker | None, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__pow__(x)`` calls — the + # ``operator.pow`` path goes through ``_handle_insert_op_in_graph`` + # in ``BuiltinVariable``. Build the same FX proxy. + if not (isinstance(other, TensorVariable) or _is_sym_arith_operand(other)) or z: + return VariableTracker.build(tx, NotImplemented) + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.pow, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + +class SymNodeVariable(VariableTracker): + """ + Represents a symbolic scalar, either int, float or bool. This is most commonly used to + handle symbolic size computation, e.g., tensor.size(0), but it is also used to + handle logic like float_tensor.item() or unspecialized float inputs. + """ + + _nonvar_fields = { + "proxy", + "sym_num", + *VariableTracker._nonvar_fields, + } + + def debug_repr(self) -> str: + return repr(self.sym_num) + + @classmethod + def create( + cls, + tx: "InstructionTranslatorBase", + proxy: Any, + sym_num: Any | None = None, + **options: Any, + ) -> "VariableTracker": + if sym_num is None: + sym_num = get_fake_value(proxy.node, tx) + if "example_value" in proxy.node.meta: + if proxy.node.meta["example_value"] != sym_num: + raise AssertionError( + f"proxy example_value {proxy.node.meta['example_value']} != {sym_num}" + ) + set_example_value(proxy.node, sym_num) + + if isinstance(sym_num, (sympy.Integer, int, bool)): + sym_num = int(sym_num) if isinstance(sym_num, sympy.Integer) else sym_num + return VariableTracker.build(tx, sym_num) + + out = SymNodeVariable(proxy, sym_num, **options) + if proxy.node.op != "placeholder": + tx.output.current_tracer.record_proxyable_vt(out) + return out + + def __init__(self, proxy: Any, sym_num: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.proxy = proxy + # TODO: Should we allow non SymTypes here? Today it is allowed + self.sym_num = sym_num + self._tensor_var: TensorVariable | None = None + + def python_type(self) -> type: + if isinstance(self.sym_num, SymTypes): + return self.sym_num.node.pytype + else: + return type(self.sym_num) + + def is_symnode_like(self) -> bool: + return True + + def as_proxy(self) -> Any: + return self.proxy + + def nb_bool_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # long_bool / float_bool: non-zero check. SymBool is already boolean. + # https://github.com/python/cpython/blob/c09ccd9c429/Objects/longobject.c#L5200 + # https://github.com/python/cpython/blob/c09ccd9c429/Objects/floatobject.c#L853 + if isinstance(self.sym_num, torch.SymBool): + return self + if not isinstance(self.sym_num, (torch.SymInt, torch.SymFloat)): + raise AssertionError( + f"Expected SymInt or SymFloat, got {type(self.sym_num)}" + ) + return SymNodeVariable.create(tx, self.as_proxy() != 0) + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """SymNode tp_richcompare: symbolic numeric comparison.""" + if not isinstance(other, (SymNodeVariable, ConstantVariable, TensorVariable)): + if op in ("__eq__", "__ne__"): + op_fn = cmp_name_to_op_mapping[op] + return VariableTracker.build(tx, op_fn(object(), None)) + return ConstantVariable.create(NotImplemented) + op_fn = cmp_name_to_op_mapping[op] + proxy = tx.output.create_proxy( + "call_function", op_fn, (self.as_proxy(), other.as_proxy()), {} + ) + return SymNodeVariable.create(tx, proxy, sym_num=None) + + def as_tensor(self, tx: "InstructionTranslatorBase", dtype: Any) -> TensorVariable: + if self._tensor_var is None: + self._tensor_var = VariableTracker.build( + tx, torch.scalar_tensor + ).call_function(tx, [self], {"dtype": VariableTracker.build(tx, dtype)}) + return self._tensor_var + + def evaluate_expr( + self, output_graph: Optional["OutputGraph"] = None + ) -> bool | int | float: + try: + return guard_scalar(self.sym_num) + except GuardOnDataDependentSymNode as e: + if torch.fx.experimental._config.no_data_dependent_graph_break: + raise + + raise UserError( # noqa: B904 + UserErrorType.ANTI_PATTERN, + f"Consider annotating your code using torch._check*(). {str(e)}", + case_name="constrain_as_size_example", + ) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_method", + name, + *proxy_args_kwargs([self, *args], kwargs), + ), + ) + + def nb_index_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # SymInt / SymBool define __index__ as `self.node.int_()`, which + # specializes the symbolic value to a concrete int (with guard). + # SymFloat has no __index__. + # ref: torch/__init__.py SymInt.__index__ / SymBool.__index__ + + pytype = self.python_type() + if pytype in (int, bool): + return variables.ConstantVariable.create(self.evaluate_expr()) + return super().nb_index_impl(tx) + + def nb_int_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # SymInt.__int__: https://github.com/pytorch/pytorch/blob/ee336ca5440939b8ad65e916d47421f849e56178/torch/__init__.py#L462 + # SymFloat.__int__: https://github.com/pytorch/pytorch/blob/ee336ca5440939b8ad65e916d47421f849e56178/torch/__init__.py#L682 + # SymBool.__int__: https://github.com/pytorch/pytorch/blob/ee336ca5440939b8ad65e916d47421f849e56178/torch/__init__.py#L784 + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + sym_int, + (self.as_proxy(),), + {}, + ), + ) + + def method___int__( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + return self.nb_int_impl(tx) + + def nb_add_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1139 (PyNumber_Add) + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.add, *proxy_args_kwargs(args, {}) + ), + sym_num=None, + ) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.or_, *proxy_args_kwargs([self, other], {}) + ), + sym_num=None, + ) + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.and_, *proxy_args_kwargs([self, other], {}) + ), + sym_num=None, + ) + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.xor, *proxy_args_kwargs([self, other], {}) + ), + sym_num=None, + ) + + def nb_lshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.lshift, *proxy_args_kwargs(args, {}) + ), + sym_num=None, + ) + + def nb_rshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.rshift, *proxy_args_kwargs(args, {}) + ), + sym_num=None, + ) + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1135 (PyNumber_Subtract) + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.sub, *proxy_args_kwargs(args, {}) + ), + sym_num=None, + ) + + def nb_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # sequence * sym_node must go through sq_repeat and not nb_multiply + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.mul, *proxy_args_kwargs([lhs, rhs], {}) + ), + sym_num=None, + ) + + def nb_floor_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.floordiv, *proxy_args_kwargs([lhs, rhs], {}) + ), + sym_num=None, + ) + + def nb_true_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.truediv, *proxy_args_kwargs([lhs, rhs], {}) + ), + sym_num=None, + ) + + def nb_remainder_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.mod, *proxy_args_kwargs([lhs, rhs], {}) + ), + sym_num=None, + ) + + def nb_float_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # SymFloat.__float__: https://github.com/pytorch/pytorch/blob/ee336ca5440939b8ad65e916d47421f849e56178/torch/__init__.py#L679 + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + sym_float, + (self.as_proxy(),), + {}, + ), + ) + + def method___float__( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + return self.nb_float_impl(tx) + + def nb_negative_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + return SymNodeVariable.create( + tx, + operator.neg(self.as_proxy()), + sym_num=None, + ) + + def method___neg__( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + return self.nb_negative_impl(tx) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return hash(self.evaluate_expr()), False + + def nb_positive_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + return SymNodeVariable.create( + tx, + operator.pos(self.as_proxy()), + sym_num=None, + ) + + def method___pos__( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + return self.nb_positive_impl(tx) + + def nb_absolute_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + return SymNodeVariable.create( + tx, + operator.abs(self.as_proxy()), + sym_num=None, + ) + + def nb_power_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + z: VariableTracker | None, + reverse: bool = False, + ) -> VariableTracker: + if z is not None: + return VariableTracker.build(tx, NotImplemented) + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.pow, *proxy_args_kwargs([lhs, rhs], {}) + ), + sym_num=None, + ) + + def method___abs__( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + return self.nb_absolute_impl(tx) + + def is_python_hashable(self) -> bool: + return True + + def get_python_hash(self) -> int: + # Essentially convert the SymNode to a constant variable whenever its + # searched for a dict key. + return hash(self.evaluate_expr()) + + +class NumpyNdarrayVariable(TensorVariable): + """ + Represents a np.ndarray, but backed by torch Tensor via torch._numpy.ndarray. + Use this for Tensor.numpy() call. + """ + + @staticmethod + def create( + tx: "InstructionTranslatorBase", proxy: torch.fx.Proxy, **options: Any + ) -> "NumpyNdarrayVariable": + from .builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + target_cls=NumpyNdarrayVariable, + tx=tx, + proxy=proxy, + **options, + ) + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, "unhashable type: 'numpy.ndarray'") + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """ndarray tp_richcompare: element-wise comparison via numpy_operator_wrapper.""" + from ..utils import numpy_operator_wrapper + + if not isinstance(other, (SymNodeVariable, ConstantVariable, TensorVariable)): + return ConstantVariable.create(NotImplemented) + op_fn = cmp_name_to_op_mapping[op] + proxy = tx.output.create_proxy( + "call_function", + numpy_operator_wrapper(op_fn), + (self.as_proxy(), other.as_proxy()), + {}, + ) + return NumpyNdarrayVariable.create(tx, proxy) + + # NB: ndim/itemsize are ALWAYS specialized constants (numpy exposes them via + # PyGetSetDef on ndarray), unlike size/shape which may carry free symbols. + def _get_ndim(self, tx: "InstructionTranslatorBase") -> VariableTracker: + example_value = self.as_proxy().node.meta["example_value"] + return VariableTracker.build(tx, tnp.ndarray(example_value).ndim) + + def _get_itemsize(self, tx: "InstructionTranslatorBase") -> VariableTracker: + example_value = self.as_proxy().node.meta["example_value"] + return VariableTracker.build(tx, tnp.ndarray(example_value).itemsize) + + def _get_numpy_attr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + from ..utils import numpy_attr_wrapper + + proxy = tx.output.create_proxy( + "call_function", numpy_attr_wrapper, (self.as_proxy(), name), {} + ) + return NumpyNdarrayVariable.create(tx, proxy) + + tp_getset = { + "ndim": GetSet(_get_ndim, None), + "itemsize": GetSet(_get_itemsize, None), + "T": GetSet(lambda s, tx: s._get_numpy_attr(tx, "T")), + "real": GetSet(lambda s, tx: s._get_numpy_attr(tx, "real")), + "imag": GetSet(lambda s, tx: s._get_numpy_attr(tx, "imag")), + "flat": GetSet(lambda s, tx: s._get_numpy_attr(tx, "flat")), + } + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # NB: This INTENTIONALLY does not call super(), because there is + # no intrinsic reason ndarray properties are related to Tensor + # properties. The inheritance here is for implementation sharing. + # tp_getset (ndim/itemsize/T/real/imag/flat) is resolved by + # generic_getattr before this method is reached, so it is not + # consulted here. + from ..utils import numpy_attr_wrapper + from .builder import wrap_fx_proxy + + example_value = self.as_proxy().node.meta["example_value"] + example_ndarray = tnp.ndarray(example_value) + + def insert_into_graph() -> VariableTracker: + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", numpy_attr_wrapper, (self.as_proxy(), name), {} + ), + ) + + # These are awkward to implement. The standard playbook for torch._numpy + # interop is to trace a call into the torch._numpy wrapper which works for + # Tensor operations. However, we don't want to do this for calls + # that don't return Tensors, because in those cases we may not want + # to trace the attribute access into the graph at all (it is sort + # of harmless to do so, because AOTAutograd will eliminate them, + # but it's best not to trace them in to begin with.) But in any + # case, tracing these into the graph is like trying to fit a square + # peg into a round hole; best not to do it. So instead we + # painstakingly implement these by hand + # + # NB: only ALWAYS specialized attributes can go here; notably, + # size/shape not allowed! + if name in ("shape", "stride"): + if not has_free_symbols(r := getattr(example_ndarray, name)): + return VariableTracker.build(tx, tuple(int(r) for r in r)) + return insert_into_graph() + elif name == "size": + if not has_free_symbols(r := example_ndarray.size): + return VariableTracker.build(tx, int(r)) + return insert_into_graph() + elif name in ["base", "flags", "dtype"]: + unimplemented( + gb_type="Unsupported ndarray attribute access", + context=f"tp_getattro_impl {self} {name}", + explanation=f"Dynamo currently does not support tracing `ndarray.{name}`.", + hints=[], + ) + elif name == "__version__": + unimplemented( + gb_type="Unsupported ndarray.__version__ access", + context=f"tp_getattro_impl {self} {name}", + explanation=f"Dynamo currently does not support tracing `ndarray.{name}`.", + hints=[], + ) + raise NotImplementedError + + @staticmethod + def patch_args( + name: str, args: list[VariableTracker], kwargs: dict[str, VariableTracker] + ) -> tuple[list[VariableTracker], dict[str, VariableTracker]]: + if name == "clip": + kwargs_rename = {"a_min": "min", "a_max": "max"} + kwargs = {kwargs_rename.get(k, k): v for k, v in kwargs.items()} + return args, kwargs + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from ..exc import unimplemented + from ..utils import numpy_method_wrapper + + args, kwargs = self.patch_args(name, args, kwargs) + + if name == "astype": + from .builtin import BuiltinVariable + + dtype_arg = None + if "dtype" in kwargs: + dtype_arg = kwargs["dtype"] + elif len(args) > 0: + dtype_arg = args[0] + is_object_str = dtype_arg is not None and dtype_arg.is_constant_match("O") + is_object_type = ( + isinstance(dtype_arg, BuiltinVariable) and dtype_arg.fn is object + ) + if is_object_str or is_object_type: + unimplemented( + gb_type="ndarray.astype(object)", + context=f"call_method {self} {name} {args} {kwargs}", + explanation=( + "`ndarray.astype('O')` or `ndarray.astype(object)` is not supported " + "by torch.compile, as there is no equivalent to object type in torch.Tensor. " + "This will be executed eagerly." + ), + hints=[*graph_break_hints.FUNDAMENTAL], + ) + if name in ["__len__", "size", "tolist", "__iter__"]: + # delegate back to TensorVariable + return super().call_method(tx, name, args, kwargs) + if name in ("tostring", "tobytes", "__delattr__"): + unimplemented( + gb_type="Unsupported ndarray method call", + context=f"call_method {self} {name} {args} {kwargs}", + explanation=f"`ndarray.{name}()` is not modelled in `torch._numpy`.", + hints=[], + ) + proxy = tx.output.create_proxy( + "call_function", + numpy_method_wrapper(name), + *proxy_args_kwargs([self] + list(args), kwargs), + ) + return NumpyNdarrayVariable.create(tx, proxy) + + def python_type(self) -> type: + if np is not None: + return np.ndarray + else: + return NoneType + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + if value is None: + raise_value_error(tx, "cannot delete array elements") + return self.call_method(tx, "__setitem__", [key, value], {}) + + +class UnspecializedPythonVariable(TensorVariable): + """ + This is a 1-element tensor represents unspecialized python float/int. + """ + + _nonvar_fields = { + "raw_value", + "need_unwrap", + *TensorVariable._nonvar_fields, + } + + def __init__( + self, + proxy: torch.fx.Proxy, + *, + raw_value: float | int | None = None, + need_unwrap: bool = True, + **kwargs: Any, + ) -> None: + super().__init__(proxy, **kwargs) + self.raw_value = raw_value + self.need_unwrap = need_unwrap + + @classmethod + def from_tensor_variable( + cls, + tensor_variable: TensorVariable, + raw_value: float | int | None, + need_unwrap: bool = True, + ) -> "UnspecializedPythonVariable": + # Convert a `TensorVariable` instance into an `UnspecializedPythonVariable` instance. + return UnspecializedPythonVariable( + **dict(tensor_variable.__dict__), + raw_value=raw_value, + need_unwrap=need_unwrap, + ) + + +class FakeItemVariable(TensorVariable): + """An unspecialized python variable which prevents access to the underlying raw value. + This is needed if item is called on a FakeTensor.""" + + _nonvar_fields = { + "need_unwrap", + *TensorVariable._nonvar_fields, + } + + def __init__(self, proxy: torch.fx.Proxy, **kwargs: Any) -> None: + need_unwrap = kwargs.pop("need_unwrap", False) + super().__init__(proxy, **kwargs) + self.need_unwrap = need_unwrap + + @classmethod + def from_tensor_variable( + cls, tensor_variable: TensorVariable + ) -> "FakeItemVariable": + return FakeItemVariable(**dict(tensor_variable.__dict__)) + + +class TensorSubclassVariable(UserDefinedClassVariable): + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Handle `Subclass(existing_tensor, ...)` calls. + from .torch_function import TensorWithTFOverrideVariable + + new_func = self.value.__new__ + if new_func is torch.Tensor.__new__: + var = None + if len(args) == 1 and args[0].is_tensor() and len(kwargs) == 0: + data = args[0] + # Simulate `torch.Tensor.__new__` as shallow-copying the input + # tensor data with a new type. TODO polyfill? + var = TensorWithTFOverrideVariable.from_tensor_var( + tx, data, self.value, self.source + ) + else: + unimplemented( + gb_type="Calling subclass default constructor with more than tensor argument", + context=f"{self.value}(args={args}, kwargs={kwargs})", + explanation="Currently not supported", + hints=[ + "Avoid this constructor call or move it outside " + "`torch.compile` region", + *graph_break_hints.SUPPORTABLE, + ], + ) + else: + # Let Dynamo trace through custom `__new__` + var = VariableTracker.build(tx, new_func).call_function( + tx, [self] + list(args), kwargs + ) + if var is None: + raise AssertionError("__new__ must return a non-None variable") + # Let Dynamo trace through custom `__init__` + init_func = self.value.__init__ + # TODO builder should be able to handle `torch.Tensor.__init__`, + # which is `object.__init__`, so that we can remove this check. + if init_func is not torch.Tensor.__init__: + VariableTracker.build(tx, init_func).call_function(tx, [var], kwargs) + + # See NOTE [Side effect tracking for newly constructed tensor] + tx.output.side_effects._track_obj( + object(), var, mutation_type_cls=AttributeMutationNew + ) + return var + + def as_python_constant(self) -> type: + return self.value + + +class UntypedStorageVariable(VariableTracker): + _nonvar_fields = { + "example_value", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + from_tensor: TensorVariable, + example_value: torch.UntypedStorage, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.from_tensor = from_tensor + # Example_value will always have device="meta" + self.example_value = example_value + + def python_type(self) -> type: + return torch.UntypedStorage + + def method_size( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + result = self.example_value.size() + if not has_free_symbols(result): + # avoid creating a node in the graph + return VariableTracker.build(tx, int(result)) + from ..external_utils import untyped_storage_size + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + untyped_storage_size, + (self.from_tensor.as_proxy(),), + {}, + ), + ) + + def method_resize_( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.create_proxy( + "call_function", + torch.ops.inductor.resize_storage_bytes_, + (self.from_tensor.as_proxy(), args[0].as_proxy()), + {}, + ) + return self + + tp_methods = { + "size": Method(method_size), + "resize_": Method(method_resize_), + } + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.from_tensor) + codegen.load_method("untyped_storage") + codegen.call_method(0) + + +class DataPtrVariable(VariableTracker): + _DATA_PTR_PRESERVING_TARGETS = { + ("call_method", "detach"), + ("call_function", torch.ops.aten.detach.default), + } + + def __init__( + self, + from_tensor: TensorVariable, + method_name: str = "data_ptr", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.from_tensor = from_tensor + self.method_name = method_name + self.tensor_version = from_tensor._get_fake_version() + + def python_type(self) -> type: + return int + + @classmethod + def _strip_data_ptr_preserving_aliases(cls, node: torch.fx.Node) -> torch.fx.Node: + while ( + isinstance(node, torch.fx.Node) + and (node.op, node.target) in cls._DATA_PTR_PRESERVING_TARGETS + and len(node.args) == 1 + and isinstance(node.args[0], torch.fx.Node) + ): + node = node.args[0] + return node + + def _is_same_data_ptr(self, other: "VariableTracker") -> bool: + if not isinstance(other, DataPtrVariable): + return False + + if self.tensor_version is None or self.tensor_version != other.tensor_version: + return False + + self_root = self._strip_data_ptr_preserving_aliases( + self.from_tensor.as_proxy().node + ) + other_root = self._strip_data_ptr_preserving_aliases( + other.from_tensor.as_proxy().node + ) + return self_root is other_root + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """DataPtr tp_richcompare: identity-based eq/ne.""" + if op not in ("__eq__", "__ne__"): + return ConstantVariable.create(NotImplemented) + same_data_ptr = self._is_same_data_ptr(other) + if same_data_ptr: + return ConstantVariable.create(op == "__eq__") + unimplemented( + gb_type="Data pointer comparison", + context=f"tp_richcompare_impl {self} {op} {other}", + explanation="Dynamo can only trace data pointer comparisons " + "when it can prove both operands have the same data pointer.", + hints=[], + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.from_tensor) + codegen.load_method(self.method_name) + codegen.call_method(0) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch.py new file mode 100644 index 0000000000000000000000000000000000000000..0953412d95c815720acd05ca2c70f2e415fdff61 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch.py @@ -0,0 +1,4368 @@ +""" +This module implements variable tracking for torch functions and operations during Dynamo tracing. + +It provides classes to handle different types of torch operations: + +TorchInGraphFunctionVariable: Handles torch.* functions that should be captured in the FX graph. +Provides special handling for constant folding, tensor methods, and torch function overrides. +Manages complex cases like out= variants and parameter construction. + +TorchCtxManagerClassVariable: Handles torch context managers like torch.no_grad(), autocast, etc. +Provides implementations for entering/exiting these contexts during tracing. + +DispatchKeySetVariable: Represents torch.DispatchKeySet for managing dispatch keys and +device-specific operations during tracing. + +The module includes special handling for: +- Constant folding of pure functions +- Tensor method calls +- torch.nn.Parameter construction +- __torch_function__ overrides +- Context manager state tracking +- Device and dtype management + +This is a core part of Dynamo's tracing system, translating torch operations into +traceable graph nodes while preserving correct semantics and handling edge cases. +""" + +import enum +import functools +import inspect +import logging +import math +import re +from collections.abc import Callable, Iterable +from contextlib import nullcontext +from typing import Any, cast, NoReturn, TYPE_CHECKING, TypeVar, Union +from typing_extensions import TypeIs + +import torch._C +import torch._refs +import torch.fx +import torch.nn +import torch.utils._pytree as _pytree +from torch._C import DispatchKeySet +from torch._dynamo.variables.constant import ConstantVariable +from torch._dynamo.variables.streams import StreamVariable +from torch._dynamo.variables.torch_function import TorchFunctionModeVariable +from torch._guards import Guard, Source, TracingContext +from torch._logging import warning_once +from torch._subclasses.fake_tensor import is_fake_tensor +from torch.autograd.graph import GradientEdge +from torch.utils._python_dispatch import is_traceable_wrapper_subclass_type + +from .. import config, graph_break_hints, polyfills, variables +from ..codegen import PyCodegen +from ..create_parameter_op import ( + can_convert_to_tracable_parameter, + new_parameter_placeholder, + tracable_create_parameter, +) +from ..device_interface import get_registered_device_interfaces +from ..exc import ( + raise_observed_exception, + raise_type_error, + unimplemented, + UserError, + UserErrorType, +) +from ..guards import ( + _COW_TENSOR_UNSUPPORTED, + _try_is_cow_tensor, + GuardBuilder, + install_guard, +) +from ..source import ( + AttrSource, + CallFunctionNoArgsSource, + GlobalStateSource, + ImportSource, + SyntheticLocalSource, +) +from ..utils import ( + _is_tensorify_enabled, + check_unspec_or_constant_args, + guard_if_dyn, + has_torch_function, + hashable, + is_wrapper_or_member_descriptor, + product, + proxy_args_kwargs, + unpack_iterable, + unwrap_if_wrapper, +) +from .base import typestr, VariableTracker +from .ctx_manager import ( + AutocastModeVariable, + ProfilerContextVariable, + ProfilerRecordFunctionContextVariable, + TorchFunctionDisableVariable, +) +from .distributed import DistributedVariable +from .functions import ( + bind_args_cached, + ClosureConversionError, + NestedUserFunctionVariable, + UserFunctionVariable, +) +from .lists import ListVariable, TupleVariable +from .object_protocol import vt_is_iterable +from .script_object import CustomClassObjectVariable +from .torch_function import ( + can_dispatch_torch_function, + dispatch_torch_function, + TensorWithTFOverrideVariable, + TorchFunctionModeStackVariable, +) +from .user_defined import UserDefinedTupleVariable + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + +try: + from torch.distributed.fsdp._fully_shard import _fsdp_param_group +except ModuleNotFoundError: + _fsdp_param_group = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from torch._custom_class_base import CustomClassBase + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch.utils._pytree import TreeSpec + + +V = TypeVar("V") +T = TypeVar("T") + +log = logging.getLogger(__name__) + + +def _is_supported_out_tensor_layout( + fake_out: torch.Tensor, *, false_if_dde: bool +) -> bool: + # Functionalization can preserve standard dense memory formats, but not + # arbitrary non-contiguous view strides. + return ( + torch._prims_common.is_contiguous(fake_out, false_if_dde=false_if_dde) + or torch._prims_common.is_contiguous_for_memory_format( + fake_out, + memory_format=torch.channels_last, + false_if_dde=false_if_dde, + ) + or torch._prims_common.is_contiguous_for_memory_format( + fake_out, + memory_format=torch.channels_last_3d, + false_if_dde=false_if_dde, + ) + ) + + +supported_ctx_manager_classes = dict.fromkeys( + [ + torch.profiler.profiler.profile, + torch.autograd.forward_ad._set_fwd_grad_enabled, + torch.autograd.forward_ad.dual_level, + torch.autograd.profiler.profile, + torch.autograd.profiler.record_function, + torch._C.DisableTorchFunctionSubclass, + torch._C.DisableTorchFunction, + torch._functorch.vmap.vmap_increment_nesting, + torch._functorch.eager_transforms.grad_increment_nesting, + torch._functorch.eager_transforms.jvp_increment_nesting, + torch._functorch.eager_transforms.enable_inplace_requires_grad, + torch.amp.autocast_mode.autocast, + torch.autograd.grad_mode.enable_grad, + torch.autograd.grad_mode.inference_mode, + torch.autograd.grad_mode.no_grad, + torch.autograd.grad_mode.set_grad_enabled, + torch.autograd.graph.disable_saved_tensors_hooks, + torch.cpu.amp.autocast_mode.autocast, + torch.cuda.amp.autocast_mode.autocast, + torch.cuda.use_mem_pool, + torch.cuda.use_mem_pool.__wrapped__, # type: ignore[attr-defined] + torch.fx.traceback.annotate, + torch.fx.traceback.annotate.__wrapped__, # type: ignore[attr-defined] + # We'll let Dynamo inline into the contextlib part of these context + # manager instances, all the way till it invokes the wrapped function + # itself (at which point we wrap it back to special context manager + # VTs). + # + # This allows us to support calling functions decorated with these + # context managers, without much extra effort or code dup. + torch.nn.attention.sdpa_kernel.__wrapped__, # type: ignore[attr-defined] + ] +) + + +REWRITE_OPS_TO_TENSOR_SIZE_METHOD = dict.fromkeys( + [ + torch._shape_as_tensor, + ] +) + +constant_fold_functions_need_guards = [ + torch._C._functorch.get_dynamic_layer_stack_depth, + torch.accelerator.current_device_index, + torch.accelerator.current_accelerator, + torch.cuda.current_device, + torch.cuda.is_initialized, + torch.xpu.current_device, + torch.xpu.is_initialized, + torch.__future__.get_overwrite_module_params_on_conversion, +] + +constant_fold_functions = [ + torch._assert, + torch._utils._get_device_index, + torch._C._get_cublas_allow_tf32, + torch._C._is_any_autocast_enabled, + torch.accelerator.is_available, + torch.backends.mps.is_available.__wrapped__, # type: ignore[attr-defined] + torch.backends.mps.is_built, + torch.cuda.get_device_properties, + torch.cuda.is_available, + torch.distributed.is_available, + torch.get_autocast_dtype, + torch.get_autocast_gpu_dtype, + torch.get_default_dtype, + torch.is_autocast_cache_enabled, + torch.is_autocast_cpu_enabled, + torch.is_autocast_enabled, + torch.is_complex, + torch.is_floating_point, + torch.nn.functional._Reduction.get_enum, # type: ignore[attr-defined] + torch.promote_types, + torch._C._get_privateuse1_backend_name, + torch.autograd._is_checkpoint_valid, + torch.mps.is_available, + torch.mtia.is_available, + torch.xpu.get_device_properties, + torch.xpu.is_available, +] + constant_fold_functions_need_guards +if torch.distributed.is_available(): + constant_fold_functions.extend( + [ + torch.distributed.is_initialized, + torch.distributed.get_rank, + torch.distributed.get_world_size, + ] + ) +# Convert to dict for O(1) access times +constant_fold_functions_need_guards = dict.fromkeys(constant_fold_functions_need_guards) +constant_fold_functions = dict.fromkeys(constant_fold_functions) + +# Ops that consume scalar values from 0-d tensors (via .item()) for computation +# only, not for output shapes. When capture_scalar_outputs is enabled, these ops +# create unbacked symbols that don't affect the outputs, causing +# PendingUnbackedSymbolNotFound errors. +# +# We use an explicit allowlist rather than generically suppressing for any 0-d +# tensor argument because an op could legitimately create unbacked symbols for +# data-dependent output shapes. Suppressing those would silently drop binding +# information. +ops_consuming_unbacked_scalars: frozenset[Callable[..., Any]] = frozenset( + { + # ops with Scalar alpha/beta/value arguments + torch.add, + torch.sub, + torch.addmm, + torch.addmv, + torch.addr, + torch.addbmm, + torch.baddbmm, + torch.addcmul, + torch.addcdiv, + # foreach ops with scalar/alpha arguments + torch._foreach_add, + torch._foreach_add_, + torch._foreach_sub, + torch._foreach_sub_, + torch._foreach_mul, + torch._foreach_mul_, + torch._foreach_div, + torch._foreach_div_, + torch._foreach_clamp_max, + torch._foreach_clamp_max_, + torch._foreach_clamp_min, + torch._foreach_clamp_min_, + torch._foreach_maximum, + torch._foreach_maximum_, + torch._foreach_minimum, + torch._foreach_minimum_, + torch._foreach_pow, + torch._foreach_pow_, + torch._foreach_lerp, + torch._foreach_lerp_, + torch._foreach_addcmul, + torch._foreach_addcmul_, + torch._foreach_addcdiv, + torch._foreach_addcdiv_, + } +) + +# Derived set of method names for TensorVariable.call_method. Includes inplace +# variants (e.g., "add_") since those are only callable as tensor methods. +# This is a set of strings (not function objects) because the call_method path +# only has the method name, whereas call_function has the actual function object. +methods_consuming_unbacked_scalars: frozenset[str] = frozenset( + name + for fn in ops_consuming_unbacked_scalars + for name in (fn.__name__, fn.__name__ + "_") + if hasattr(torch.Tensor, name) +) + + +@functools.cache +def tracing_state_functions() -> dict[Callable[[], Any], bool | None]: + # Defined as a function to avoid circular import like torch.onnx + return { + torch.jit.is_scripting: False, + torch.jit.is_tracing: False, + torch._C._get_tracing_state: None, + torch.fx._symbolic_trace.is_fx_tracing: False, + torch.fx._symbolic_trace.is_fx_symbolic_tracing: False, + torch.onnx.is_in_onnx_export: False, + # pyrefly: ignore [deprecated] + torch._dynamo.external_utils.is_compiling: True, + # pyrefly: ignore [deprecated] + torch._utils.is_compiling: True, + torch.compiler.is_compiling: True, + torch.compiler.is_dynamo_compiling: True, + torch.compiler.is_exporting: True, + torch._dynamo.eval_frame._is_in_optimized_module: True, + # Look into https://github.com/pytorch/pytorch/pull/164721 why this is + # turned to True for Dynamo. + torch.nn.modules.activation._is_make_fx_tracing: True, + } + + +bin_ops = dict.fromkeys(["add", "sub", "mul", "div", "sqrt"]) + +dispatch_key_set_functions = { + torch._C._dispatch_keys, + torch._C._dispatch_tls_local_include_set, + torch._C._dispatch_tls_local_exclude_set, +} + + +def _check_for_gradient_edge(var: VariableTracker, arg_name: str) -> None: + """Check if var contains a GradientEdge from outside the compiled region. + + Used by handle_autograd_grad to reject external GradientEdge objects that + cannot be traced through. + """ + from .dicts import ConstDictVariable + from .lists import BaseListVariable + + if isinstance(var, UserDefinedTupleVariable) and type(var.value) is GradientEdge: + # Try to get source info for context + source_info = var.source.name if var.source else None + context = f"GradientEdge in {arg_name}" + if source_info: + context += f": {source_info}" + + unimplemented( + gb_type="autograd.grad with external GradientEdge", + context=context, + explanation=( + "torch.autograd.grad() cannot be used with GradientEdge inputs " + "passed from outside the compiled region. The GradientEdge contains " + "a reference to an autograd node that was created before torch.compile " + "started tracing, so Dynamo cannot trace through its computation." + ), + hints=[ + "Move the autograd.grad() call outside the torch.compile region.", + "Or use tensor inputs directly instead of GradientEdge objects.", + *graph_break_hints.SUPPORTABLE, + ], + ) + elif isinstance(var, BaseListVariable): + for i, item in enumerate(var.items): + _check_for_gradient_edge(item, f"{arg_name}[{i}]") + elif isinstance(var, ConstDictVariable): + for hash_key, item in var.items.items(): + if not hash_key.vt.is_python_constant(): + unimplemented( + gb_type="autograd.grad with non-constant dict key", + context=f"non-constant key in {arg_name}", + explanation="autograd.grad/backward dict inputs must have constant keys.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + key_repr = hash_key.vt.as_python_constant() + _check_for_gradient_edge(item, f"{arg_name}[{key_repr!r}]") + + +def _collect_all_grad_fns(tensor: torch.Tensor) -> set[torch.autograd.graph.Node]: + from torch._subclasses.fake_tensor import get_plain_tensors + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + grad_fns: set[torch.autograd.graph.Node] = set() + + plain_tensors: list[torch.SymInt | torch.Tensor | int | CustomClassBase] = [] + # Get all plain tensors (handles nested subclasses) + if is_traceable_wrapper_subclass(tensor): + get_plain_tensors(tensor, out=plain_tensors) + else: + plain_tensors.append(tensor) + + for t in plain_tensors: + if not isinstance(t, torch.Tensor): + continue + + if t.grad_fn is not None: + grad_fns.add(t.grad_fn) + + # For views, also include the base tensor's grad_fn + if t._base is not None and t._base.grad_fn is not None: + grad_fns.add(t._base.grad_fn) + + return grad_fns + + +def _collect_tensors_with_sources( + var: VariableTracker, +) -> list[tuple[torch.Tensor, str | None]]: + """Extract (fake_tensor, source_name) pairs from a VariableTracker. + + Used by handle_autograd_grad to collect tensors from the outputs and inputs + arguments for grad_fn reachability analysis. + """ + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + from .dicts import ConstDictVariable + from .lazy import LazyVariableTracker + from .lists import BaseListVariable + from .tensor import TensorVariable + + results: list[tuple[torch.Tensor, str | None]] = [] + if isinstance(var, TensorVariable): + fake_tensor = var.as_proxy().node.meta.get("example_value") + if not isinstance(fake_tensor, torch.Tensor): + raise AssertionError( + f"Expected fake_tensor to be a torch.Tensor, got {type(fake_tensor)}" + ) + if is_fake_tensor(fake_tensor): + pass + elif is_traceable_wrapper_subclass(fake_tensor): + # For tensor subclasses (e.g. DTensor), verify the inner tensors + # are FakeTensors but keep the original subclass for grad_fn + # reachability analysis. + plain: list[object] = [] + torch._subclasses.fake_tensor.get_plain_tensors( + fake_tensor, # pyrefly: ignore[bad-argument-type] + out=plain, # pyrefly: ignore[bad-argument-type] + ) + if not all(is_fake_tensor(t) for t in plain if isinstance(t, torch.Tensor)): + raise AssertionError( + f"Expected all plain tensors to be FakeTensors, got {[type(t) for t in plain]}" + ) + else: + raise AssertionError( + f"Expected FakeTensor or subclass, got {type(fake_tensor)}" + ) + source_name = var.source.name if var.source else None + results.append((fake_tensor, source_name)) + elif isinstance(var, LazyVariableTracker): + # Realize the lazy var to get the actual TensorVariable + results.extend(_collect_tensors_with_sources(var.realize())) + elif isinstance(var, BaseListVariable): + for item in var.items: + results.extend(_collect_tensors_with_sources(item)) + elif isinstance(var, ConstDictVariable): + for item in var.items.values(): + results.extend(_collect_tensors_with_sources(item)) + else: + unimplemented( + gb_type="autograd.grad with unsupported argument type", + context=f"got {type(var).__name__}", + explanation=( + f"torch.autograd.grad() received an argument of type {type(var).__name__} " + "which is not supported. Expected tensor or sequence of tensors." + ), + hints=[ + "Ensure outputs and inputs arguments are tensors or sequences of tensors.", + ], + ) + return results + + +def _collect_placeholder_nodes(var: "VariableTracker") -> list[torch.fx.Node]: + """Recursively collect FX placeholder nodes from a VariableTracker. + + The returned placeholder nodes carry grapharg.example (real tensor) and + example_value (FakeTensor) metadata — comparing these reveals lost + autograd linkage (e.g., grad_fn dropped during tracing). + See NOTE [Detecting lost autograd linkage in closure-captured tensors]. + """ + from .lazy import LazyVariableTracker + from .lists import BaseListVariable + from .tensor import TensorVariable + + result: list[torch.fx.Node] = [] + if isinstance(var, TensorVariable): + node = var.as_proxy().node + if node.op == "placeholder": + result.append(node) + elif isinstance(var, LazyVariableTracker): + result.extend(_collect_placeholder_nodes(var.realize())) + elif isinstance(var, BaseListVariable): + for item in var.items: + result.extend(_collect_placeholder_nodes(item)) + else: + unimplemented( + gb_type="_autograd_grad with unsupported argument type", + context=f"got {type(var).__name__}", + explanation=( + f"_autograd_grad() received an argument of type {type(var).__name__} " + "which is not supported. Expected tensor or sequence of tensors." + ), + hints=[ + "Ensure outputs and inputs arguments are tensors or sequences of tensors.", + ], + ) + return result + + +@functools.cache +def get_overridable_functions() -> set[Callable[..., Any]]: + from itertools import chain + + from torch.overrides import get_overridable_functions as get_overridable_functions_ + from torch.utils._device import _device_constructors + + funcs = set(chain.from_iterable(get_overridable_functions_().values())) + funcs.update(_device_constructors()) + more: set[Callable[..., Any]] = { + torch.ones_like, + torch.zeros_like, + torch.empty_like, + torch.full_like, + } + funcs.update(more) + return funcs + + +class BaseTorchVariable(VariableTracker): + """common base for all torch.* functions, classes, modules and other things""" + + @classmethod + def create_with_source(cls, value: Any, source: Source) -> "BaseTorchVariable": + if inspect.isclass(value): + install_guard(source.make_guard(GuardBuilder.CLASS_MATCH)) + elif inspect.ismodule(value): + install_guard(source.make_guard(GuardBuilder.MODULE_MATCH)) + elif inspect.isfunction(value): + install_guard(source.make_guard(GuardBuilder.CLOSURE_MATCH)) + elif inspect.isbuiltin(value) or isinstance( + value, (torch._ops.OpOverload, torch._ops.OpOverloadPacket) + ): + install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH)) + elif is_wrapper_or_member_descriptor(value) or isinstance( + value, torch._dynamo.compiled_autograd.Op + ): + # Don't need to guard on wrappers + pass + else: + install_guard(source.make_guard(GuardBuilder.FUNCTION_MATCH)) + return cls(value, source=source) + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def reconstruct(self, codegen: "PyCodegen") -> None: + try: + name = f"{self.value.__module__}.{self.value.__name__}" + except Exception: + name = f"torch_obj_{id(self.value)}" + unique_var_name = "__" + re.sub(r"[^a-zA-Z0-9_]+", "_", name) + codegen.extend_output( + codegen.setup_globally_cached(unique_var_name, self.value) + ) + + def as_proxy(self) -> Any: + return self.value + + def as_python_constant(self) -> Any: + return self.value + + def get_real_python_backed_value(self) -> Any: + return self.value + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + return self._nb_binop_impl(tx, other, "__or__", "__ror__", reverse) + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + return self._nb_binop_impl(tx, other, "__sub__", "__rsub__", reverse) + + def _nb_binop_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + forward: str, + reverse_dunder: str, + reverse: bool, + ) -> VariableTracker: + dunder = reverse_dunder if reverse else forward + method = getattr(type(self.value), dunder, None) + if method is None: + return VariableTracker.build(tx, NotImplemented) + try: + other_val = other.as_python_constant() + except NotImplementedError: + return VariableTracker.build(tx, NotImplemented) + result = method(self.value, other_val) + if result is NotImplemented: + return VariableTracker.build(tx, NotImplemented) + return VariableTracker.build(tx, result) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return hash(self.value), False + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + result = hasattr(self.value, name) + return VariableTracker.build(tx, result) + + def can_constant_fold_through(self) -> bool: + if self.value in constant_fold_functions: + return True + + if ( + self.value is torch.autograd._profiler_enabled + and config.constant_fold_autograd_profiler_enabled + ): + # The relevant flag is enabled only for export. One might wonder + # why? + # + # Actually we would like to not graph break even in the case of + # Dynamo. But there is a weird-unsolved bug with Kineto + Dynamo + # when there are distributed jobs that lead to NCCL timeouts. This + # bug is a rare edege case, but we have not been able to root cause + # it yet. See https://www.internalfb.com/sevmanager/view/560336 for + # more details. + # + # So is this safe for export? Yes, for export, we do not anticipate + # JIT tracing in distributed job training, and the weird edge-case + # interaction with Kineto is not a valid usecase. So, this is ok. + return True + + return getattr(self.value, "__module__", None) == "math" + + +class TorchCtxManagerClassVariable(BaseTorchVariable): + """Points to a context manager class in torch.* that dynamo has implementations""" + + def __repr__(self) -> str: + return f"TorchCtxManagerClassVariable({self.value})" + + @staticmethod + def is_matching_cls(value: Any) -> bool: + # Unwrap if it's a functools.lru_cache wrapper + value = unwrap_if_wrapper(value) + # We can't do isinstance(value, type) check because some ctx managers + # are implemented as a function decorated by contextlib.contextmanager, + # E.g., torch._functorch.vmap.vmap_increment_nesting. + return ( + # Context manager type or function with @contextmanager is callable + callable(value) + and ( + hashable(value) # accesses value.__hash__() + and value in supported_ctx_manager_classes + ) + ) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + from . import ( + CUDAMemPoolContextVariable, + DisabledSavedTensorsHooksVariable, + DualLevelContextManager, + FSDPParamGroupUseTrainingStateVariable, + FxTracebackAnnotateVariable, + GradIncrementNestingCtxManagerVariable, + GradInplaceRequiresGradCtxManagerVariable, + GradModeVariable, + InferenceModeVariable, + JvpIncrementNestingCtxManagerVariable, + SDPAKernelVariable, + SetFwdGradEnabledContextManager, + StreamVariable, + VmapIncrementNestingCtxManagerVariable, + ) + + if self.value is torch.no_grad: + if len(args) == 1 and isinstance( + args[0], variables.functions.BaseUserFunctionVariable + ): + ctx = GradModeVariable.create(tx, False) + return ctx.call_function(tx, args, kwargs) + else: + return GradModeVariable.create(tx, False) + elif self.value in ( + torch.cuda.use_mem_pool, + torch.cuda.use_mem_pool.__wrapped__, # type: ignore[attr-defined] + ): + unexpected_kwargs = [k for k in kwargs if k not in ("pool", "device")] + if unexpected_kwargs: + raise_type_error( + tx, + "use_mem_pool() got an unexpected keyword argument " + f"'{unexpected_kwargs[0]}'", + ) + if args and "pool" in kwargs: + raise_type_error( + tx, "use_mem_pool() got multiple values for argument 'pool'" + ) + if len(args) > 1 and "device" in kwargs: + raise_type_error( + tx, "use_mem_pool() got multiple values for argument 'device'" + ) + if len(args) > 2: + raise_type_error( + tx, + "use_mem_pool() takes from 1 to 2 positional arguments " + f"but {len(args)} were given", + ) + if not args and "pool" not in kwargs: + raise_type_error( + tx, + "use_mem_pool() missing 1 required positional argument: 'pool'", + ) + mempool = args[0] if args else kwargs["pool"] + device = args[1] if len(args) > 1 else kwargs.get("device") + return CUDAMemPoolContextVariable.create(tx, mempool, device) + elif self.value is torch.enable_grad: + if len(args) == 1 and isinstance( + args[0], variables.functions.BaseUserFunctionVariable + ): + ctx = GradModeVariable.create(tx, True) + return ctx.call_function(tx, args, kwargs) + return GradModeVariable.create(tx, True) + elif self.value is torch.set_grad_enabled and len(args) == 1: + return GradModeVariable.create( + tx, args[0].as_python_constant(), initialized=True + ) + elif self.value is torch.inference_mode: + if len(args) > 1: + raise AssertionError( + f"torch.inference_mode expects at most 1 arg, got {len(args)}" + ) + if len(kwargs) != 0: + raise AssertionError( + f"torch.inference_mode expects no kwargs, got {len(kwargs)}" + ) + inf_mode = args[0].as_python_constant() if len(args) == 1 else True + return InferenceModeVariable.create(tx, inf_mode) + elif self.value in ( + torch.fx.traceback.annotate, + torch.fx.traceback.annotate.__wrapped__, # type: ignore[attr-defined] + ): + if len(args) > 1: + raise AssertionError( + f"torch.fx.traceback.annotate expects at most 1 arg, got {len(args)}" + ) + if len(kwargs) != 0: + raise AssertionError( + f"torch.fx.traceback.annotate expects no kwargs, got {len(kwargs)}" + ) + return FxTracebackAnnotateVariable( + args[0].as_python_constant(), source=self.source + ) + elif inspect.isclass(self.value) and issubclass(self.value, torch.Stream): + from torch._dynamo.variables.builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + StreamVariable, + tx, + tx.output.create_proxy( + "call_function", + self.value, + (), + {}, + ), + ) + elif self.value in ( + torch.amp.autocast_mode.autocast, + torch.cuda.amp.autocast, + torch.cpu.amp.autocast, + ): + # pyrefly: ignore [bad-argument-type] + return AutocastModeVariable.create(self.value, args, kwargs) + elif self.value in ( + torch.profiler.record_function, + torch.autograd.profiler.record_function, + ): + return ProfilerRecordFunctionContextVariable.create( + func=self.value, record_args=args, record_kwargs=kwargs + ) + elif self.value in ( + torch.profiler.profile, + torch.autograd.profiler.profile, + ): + warning_once(log, "Profiler function %s will be ignored", self.value) + return ProfilerContextVariable() + elif ( + self.value is torch._C.DisableTorchFunctionSubclass + or self.value is torch._C.DisableTorchFunction + ): + if args or kwargs: + raise AssertionError( + "DisableTorchFunctionSubclass/DisableTorchFunction expects no args or kwargs" + ) + return TorchFunctionDisableVariable.create( + tx, only_subclass=self.value is torch._C.DisableTorchFunctionSubclass + ) + elif self.value is torch._functorch.vmap.vmap_increment_nesting: + if len(args) != 2: + raise AssertionError( + f"vmap_increment_nesting expects 2 args, got {len(args)}" + ) + return VmapIncrementNestingCtxManagerVariable.create( + tx, + args, + ) + elif self.value is torch._functorch.eager_transforms.jvp_increment_nesting: + if len(args) != 0: + raise AssertionError( + f"jvp_increment_nesting expects 0 args, got {len(args)}" + ) + return JvpIncrementNestingCtxManagerVariable.create(tx) + elif self.value is torch.autograd.forward_ad._set_fwd_grad_enabled: + if len(args) != 1: + raise AssertionError( + f"_set_fwd_grad_enabled expects 1 arg, got {len(args)}" + ) + return SetFwdGradEnabledContextManager.create( + tx, + [guard_if_dyn(x) for x in args], + ) + elif self.value is torch.autograd.forward_ad.dual_level: + if len(args) != 0: + raise AssertionError(f"dual_level expects 0 args, got {len(args)}") + return DualLevelContextManager.create(tx) + elif self.value is torch._functorch.eager_transforms.grad_increment_nesting: + if len(args) != 0: + raise AssertionError( + f"grad_increment_nesting expects 0 args, got {len(args)}" + ) + return GradIncrementNestingCtxManagerVariable.create(tx) + elif ( + self.value is torch._functorch.eager_transforms.enable_inplace_requires_grad + ): + if len(args) != 1: + raise AssertionError( + f"enable_inplace_requires_grad expects 1 arg, got {len(args)}" + ) + return GradInplaceRequiresGradCtxManagerVariable.create( + tx, + [guard_if_dyn(x) for x in args], + ) + elif self.value is torch.autograd.graph.disable_saved_tensors_hooks: + if len(args) != 1: + raise AssertionError( + f"disable_saved_tensors_hooks expects 1 arg, got {len(args)}" + ) + return DisabledSavedTensorsHooksVariable.create( + tx, args[0].as_python_constant() + ) + elif ( + _fsdp_param_group is not None + and self.value is _fsdp_param_group.FSDPParamGroup.use_training_state + ): + if len(args) != 2: + raise AssertionError( + f"FSDPParamGroup.use_training_state expects 2 args, got {len(args)}" + ) + return FSDPParamGroupUseTrainingStateVariable.create( + tx, args[0], args[1].as_python_constant() + ) + elif self.value is torch.nn.attention.sdpa_kernel.__wrapped__: # type: ignore[attr-defined] + name_to_arg_map = bind_args_cached( + self.value, + tx, + self.source, + args, + kwargs, + ) + backends = name_to_arg_map["backends"].as_python_constant() + set_priority = name_to_arg_map["set_priority"].as_python_constant() + return SDPAKernelVariable.create(tx, backends, set_priority) + + return super().call_function(tx, args, kwargs) + + +class AllowInGraphKind(enum.Enum): + DEFAULT = "default" + NONSTRICT_TRACE = "nonstrict_trace" + LEAF_FUNCTION = "leaf_function" + + +class TorchInGraphFunctionVariable(BaseTorchVariable): + """Points to a torch function/method that should be put in FX graph""" + + def __init__( + self, + value: Callable[..., Any], + kind: AllowInGraphKind | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value, **kwargs) + from ..trace_rules import is_leaf_function, is_nonstrict_trace_callable + + if kind is None: + if is_leaf_function(value): + kind = AllowInGraphKind.LEAF_FUNCTION + elif is_nonstrict_trace_callable(value): + kind = AllowInGraphKind.NONSTRICT_TRACE + else: + kind = AllowInGraphKind.DEFAULT + + self.kind = kind + + def __repr__(self) -> str: + return f"TorchInGraphFunctionVariable({self.value}, kind={self.kind})" + + def get_function(self) -> Callable[..., Any]: + return self.value + + @staticmethod + @functools.cache + def _get_handlers() -> dict[Callable[..., Any], Callable[..., Any]]: + """Build a dict from function -> method to handle it so that we are O(1) + in terms of the number of function with special handling.""" + # pyrefly: ignore [implicit-any] + handlers = {} + + def register( + *fns: Callable[..., Any], + ) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + def _register(handler: Callable[..., Any]) -> Callable[..., Any]: + for fn in fns: + if fn in handlers: + raise AssertionError(f"Handler already registered for {fn}") + handlers[fn] = handler + return handler + + if not callable(fns[0]): + raise AssertionError( + f"Expected first argument to be callable, got {type(fns[0])}" + ) + return _register + + from torch.backends.cuda import SDPAParams + + from . import ( + ConstantVariable, + GradModeVariable, + InferenceModeVariable, + StreamContextVariable, + SymNodeVariable, + TensorVariable, + UserDefinedObjectVariable, + ) + from .builder import wrap_fx_proxy, wrap_fx_proxy_cls + + @register(*tracing_state_functions()) + def handle_tracing_state_functions( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if args: + raise AssertionError( + f"Tracing state functions expect no args, got {len(args)}" + ) + if kwargs: + raise AssertionError( + f"Tracing state functions expect no kwargs, got {len(kwargs)}" + ) + # See: https://github.com/pytorch/pytorch/issues/110765 + if self.value in ( + # pyrefly: ignore [deprecated] + torch._utils.is_compiling, + # pyrefly: ignore [deprecated] + torch._dynamo.external_utils.is_compiling, + torch.compiler.is_compiling, + torch.compiler.is_dynamo_compiling, + torch.compiler.is_exporting, + torch._dynamo.eval_frame._is_in_optimized_module, + ): + tx.mark_inconsistent_side_effects() + # Read dynamically: the cached dict always has True, but + # is_exporting() should only be True during torch.export. + if self.value is torch.compiler.is_exporting: + return VariableTracker.build(tx, torch.compiler._is_exporting_flag) + return VariableTracker.build(tx, tracing_state_functions()[self.value]) + + @register(*dispatch_key_set_functions) + def handle_dispatch_key_set_functions( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise AssertionError( + f"Dispatch key set functions expect no kwargs, got {len(kwargs)}" + ) + if self.value is torch._C._dispatch_keys: + if len(args) != 1: + raise AssertionError( + f"_dispatch_keys expects 1 arg, got {len(args)}" + ) + if not args[0].is_tensor(): + raise AssertionError( + "Expected first argument to _dispatch_keys to be a tensor" + ) + # pyrefly: ignore[missing-attribute] + example_value = args[0].proxy.node.meta["example_value"] + dks = self.value(example_value) + # Remove Python and PythonTLSSnapshot from the dispatch key set, + # as they originate from FakeTensor propagation. + # This should only be done if the example_value is a FakeTensor. + # However, if tensor subclasses are present, + # it is reasonable for Python to remain in the dispatch key set. + if torch._subclasses.fake_tensor.is_fake_tensor(example_value): + dks = ( + dks + - torch._C.DispatchKeySet(torch._C.DispatchKey.Python) + - torch._C.DispatchKeySet( + torch._C.DispatchKey.PythonTLSSnapshot + ) + ) + return DispatchKeySetVariable.create(dks) + else: + if args: + raise AssertionError( + f"Dispatch key set function expects no args, got {len(args)}" + ) + return DispatchKeySetVariable.create(self.value()) + + @register(torch.overrides.get_default_nowrap_functions.__wrapped__) + def handle_get_default_nowrap_functions( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # [Note: __torch_function__] we return empty here because we restrict + # the set of functions that we trace __torch_function__ on to + # functions outside of the actual set. Implementing this properly will require implementing + # some variable types to track and compare tensor getset descriptors + return VariableTracker.build( + tx, torch.overrides.get_default_nowrap_functions() + ) + + @register(torch.ops.inductor.accumulate_grad_.default) + def handle_accumulate_grad_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(args) == 2 and not kwargs: + variable, new_grad = args + if isinstance(variable, variables.LazyVariableTracker): + variable = variable.realize() + if not variable.is_tensor(): + raise AssertionError( + "Expected first argument to accumulate_grad_ to be a tensor" + ) + variable_grad = variable.tp_getattro_impl(tx, "grad") + updated_grad = tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.accumulate_grad), + [variable, variable_grad, new_grad], + kwargs, + ) + updated_grad = updated_grad.clone(source=None, mutation_type=None) + tx.output.side_effects.store_attr(variable, "grad", updated_grad) + return ConstantVariable.create(None) + if len(args) == 3 and not kwargs: + variable, variable_grad, new_grad = args + if isinstance(variable, variables.LazyVariableTracker): + variable = variable.realize() + if not variable.is_tensor(): + raise AssertionError( + "Expected first argument to accumulate_grad_ to be a tensor" + ) + updated_grad = tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.accumulate_grad_no_alias), + [variable, variable_grad, new_grad], + kwargs, + ) + tx.output.side_effects.store_attr( + variable, + "grad", + updated_grad.clone(source=None, mutation_type=None), + ) + return updated_grad + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.accumulate_grad_no_alias), + list(args), + kwargs, + ) + + @register(math.radians) + def handle_radians( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if not check_unspec_or_constant_args(args, kwargs): + # Use polyfill to convert math.radians(x) into math.pi * x / 180.0 + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.radians), + list(args), + kwargs, + ) + + if hasattr(math, "fma"): # Python 3.13+ + + @register(math.fma) + def handle_fma( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if len(args) != 3 or kwargs: + return None + + if all(arg.is_tensor() for arg in args): + x, y, z = args + addcmul_fn = TorchInGraphFunctionVariable(torch.addcmul) + return addcmul_fn.call_function(tx, [z, x, y], {}) + + # Use math.fma if constants + return None + + @register(torch.is_inference_mode_enabled) + def handle_is_inference_mode_enabled( + self, tx: "InstructionTranslatorBase" + ) -> NoReturn: + unimplemented( + gb_type="Encountered torch.is_inference_mode_enabled during tracing", + context="", + explanation="torch.is_inference_mode_enabled() is not supported", + hints=[ + *graph_break_hints.FUNDAMENTAL, + *graph_break_hints.INFERENCE_MODE, + ], + ) + + @register(torch.is_tensor, torch.overrides.is_tensor_like) + def handle_is_tensor( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + if arg.is_tensor() or ( + self.value is torch.overrides.is_tensor_like + and isinstance(arg, UserDefinedObjectVariable) + and hasattr(arg.value, "__torch_function__") + ): + return ConstantVariable.create(True) + else: + return ConstantVariable.create(False) + + @register( + torch.is_floating_point, + torch.is_complex, + ) + def handle_is_floating_point( + self, tx: "InstructionTranslatorBase", input: Any + ) -> VariableTracker | None: + input_arg = input + if input_arg.is_tensor() and input_arg.dtype is not None: + if self.value is torch.is_floating_point: + return VariableTracker.build(tx, input_arg.dtype.is_floating_point) + elif self.value is torch.is_complex: + return VariableTracker.build(tx, input_arg.dtype.is_complex) + else: + raise AssertionError(f"calling {self.value}") + return None + + @register(torch.numel) + def handle_numel( + self, tx: "InstructionTranslatorBase", input: Any + ) -> VariableTracker | None: + if input.is_tensor() and input.valid_size(): + return VariableTracker.build(tx, product(input.size)) + elif input.is_tensor(): + # Workaround dynamic shapes issue + return input.call_method(tx, "numel", [], {}) + return None + + @register(torch.compile) + def handle_torch_compile( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(args) == 1: + # torch.compile is a no-op in dynamo + return args[0] + + unimplemented( + gb_type="torch.compile call with > 1 args", + context=f"args={args}, kwargs={kwargs}", + explanation="Attempted to call `torch.compile` with > 1 args. Dynamo does not support this.", + hints=[ + "Remove the torch.compile call or its additional args.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + @register(torch.library.wrap_triton, torch._library.capture_triton) + def handle_wrap_triton( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(args) == 1: + # wrap_triton / capture_triton is a no-op in dynamo + return args[0] + + unimplemented( + gb_type="torch.library.wrap_triton call with > 1 args", + context=f"args={args}, kwargs={kwargs}", + explanation="Attempted to call `wrap_triton`/`capture_triton`" + " with > 1 args. Dynamo does not support this.", + hints=[ + "Remove the wrap_triton/capture_triton call or its additional args.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + @register(*REWRITE_OPS_TO_TENSOR_SIZE_METHOD) + def handle_tensor_size_rewrites( + self, tx: "InstructionTranslatorBase", input: VariableTracker + ) -> VariableTracker: + if not input.is_tensor(): + raise AssertionError( + "Expected input to tensor size rewrite to be a tensor" + ) + return input.call_method(tx, "size", [], {}) + + @register( + torch.nn.modules.utils._single, + torch.nn.modules.utils._pair, + torch.nn.modules.utils._triple, + torch.nn.modules.utils._quadruple, + torch.nn.modules.utils._ntuple, + ) + def handle_ntuple( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return self._call_ntuple(tx, args, kwargs) + + @register(torch.is_grad_enabled) + def handle_is_grad_enabled( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable: + install_guard(GradModeVariable._guards_singleton) + return VariableTracker.build(tx, torch.is_grad_enabled()) + + @register(torch.autograd.grad_mode._enter_inference_mode) + def handle_enter_inference_mode( + self, tx: "InstructionTranslatorBase", mode: VariableTracker + ) -> InferenceModeVariable: + ctx = InferenceModeVariable.create(tx, mode.as_python_constant()) + ctx.enter(tx) + return ctx + + @register(torch.autograd.grad_mode._exit_inference_mode) + def handle_exit_inference_mode( + self, tx: "InstructionTranslatorBase", mode: InferenceModeVariable + ) -> VariableTracker: + return mode.exit(tx) + + @register(torch.use_deterministic_algorithms) + def handle_use_deterministic_algorithms( + self, + tx: "InstructionTranslatorBase", + mode: Any, + warn_only: VariableTracker | bool = False, + ) -> VariableTracker: + value = mode.as_python_constant() + warn_only_value = ( + warn_only.as_python_constant() + if isinstance(warn_only, VariableTracker) + else warn_only + ) + tx.output.create_node( + "call_function", + torch._C._set_deterministic_algorithms, + (value,), + {"warn_only": warn_only_value}, + ) + torch._C._set_deterministic_algorithms(value, warn_only=warn_only_value) + return ConstantVariable.create(None) + + @register(torch.autocast_increment_nesting) + def handle_autocast_increment_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch.autocast_increment_nesting, (), {} + ) + prev = torch.autocast_increment_nesting() + tx.output.add_cleanup_hook(lambda: torch.autocast_decrement_nesting()) + return VariableTracker.build(tx, prev) + + @register(torch.autocast_decrement_nesting) + def handle_autocast_decrement_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch.autocast_decrement_nesting, (), {} + ) + prev = torch.autocast_decrement_nesting() + tx.output.add_cleanup_hook(lambda: torch.autocast_increment_nesting()) + return VariableTracker.build(tx, prev) + + @register(torch.set_autocast_enabled) + def handle_set_autocast_enabled( + self, + tx: "InstructionTranslatorBase", + device_type: VariableTracker, + enabled: VariableTracker, + ) -> VariableTracker: + tx.output.create_node( + "call_function", + torch.set_autocast_enabled, + (device_type.as_proxy(), enabled.as_proxy()), + ) + dev_py_const = device_type.as_python_constant() + prev = torch.is_autocast_enabled(dev_py_const) + torch.set_autocast_enabled(dev_py_const, enabled.as_python_constant()) + tx.output.add_cleanup_hook( + lambda: torch.set_autocast_enabled(dev_py_const, prev) + ) + return ConstantVariable.create(None) + + @register(torch.set_autocast_dtype) + def handle_set_autocast_dtype( + self, + tx: "InstructionTranslatorBase", + device_type: VariableTracker, + dtype: VariableTracker, + ) -> VariableTracker: + tx.output.create_node( + "call_function", + torch.set_autocast_dtype, + (device_type.as_proxy(), dtype.as_proxy()), + ) + dev_py_const = device_type.as_python_constant() + prev = torch.get_autocast_dtype(dev_py_const) + torch.set_autocast_dtype(dev_py_const, dtype.as_python_constant()) + tx.output.add_cleanup_hook( + lambda: torch.set_autocast_dtype(dev_py_const, prev) + ) + return ConstantVariable.create(None) + + @register(torch.set_autocast_cache_enabled) + def handle_set_autocast_cache_enabled( + self, tx: "InstructionTranslatorBase", enabled: VariableTracker + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch.set_autocast_cache_enabled, (enabled.as_proxy(),) + ) + prev = torch.is_autocast_cache_enabled() + torch.set_autocast_cache_enabled(enabled.as_python_constant()) + tx.output.add_cleanup_hook(lambda: torch.set_autocast_cache_enabled(prev)) + return ConstantVariable.create(None) + + @register(torch._functorch.predispatch._jvp_increment_nesting) + def handle_jvp_increment_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch._functorch.predispatch._jvp_increment_nesting + ) + level = torch._functorch.predispatch._jvp_increment_nesting() + tx.output.add_cleanup_hook( + torch._functorch.predispatch._jvp_decrement_nesting + ) + return VariableTracker.build(tx, level) + + @register(torch._functorch.predispatch._jvp_decrement_nesting) + def handle_jvp_decrement_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch._functorch.predispatch._jvp_decrement_nesting + ) + level = torch._functorch.predispatch._jvp_decrement_nesting() + tx.output.add_cleanup_hook( + torch._functorch.predispatch._jvp_increment_nesting + ) + return VariableTracker.build(tx, level) + + @register(torch._functorch.predispatch._enter_dual_level) + def handle_enter_dual_level( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch._functorch.predispatch._enter_dual_level + ) + level = torch._functorch.predispatch._enter_dual_level() + tx.output.add_cleanup_hook( + lambda: torch._functorch.predispatch._exit_dual_level(level=level) + ) + return VariableTracker.build(tx, level) + + @register(torch._functorch.predispatch._exit_dual_level) + def handle_exit_dual_level( + self, tx: "InstructionTranslatorBase", level: VariableTracker + ) -> VariableTracker: + level_const = level.as_python_constant() + tx.output.create_node( + "call_function", + torch._functorch.predispatch._exit_dual_level, + (), + { + "level": level_const, + }, + ) + torch._functorch.predispatch._exit_dual_level(level=level_const) + + def cleanup(): + new_level = torch._functorch.predispatch._enter_dual_level() + if new_level != level_const: + raise AssertionError("Invalid _exit_dual_level") + + tx.output.add_cleanup_hook(cleanup) + return ConstantVariable.create(None) + + @register(torch._C._functorch._grad_increment_nesting) + def handle_grad_increment_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch._C._functorch._grad_increment_nesting + ) + level = torch._C._functorch._grad_increment_nesting() + tx.output.add_cleanup_hook(torch._C._functorch._grad_decrement_nesting) + return VariableTracker.build(tx, level) + + @register(torch._C._functorch._grad_decrement_nesting) + def handle_grad_decrement_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch._C._functorch._grad_decrement_nesting + ) + level = torch._C._functorch._grad_decrement_nesting() + tx.output.add_cleanup_hook(torch._C._functorch._grad_increment_nesting) + return VariableTracker.build(tx, level) + + @register(torch._C._functorch.set_inplace_requires_grad_allowed) + def handle_set_inplace_requires_grad_allowed( + self, tx: "InstructionTranslatorBase", allowed: VariableTracker + ) -> VariableTracker: + tx.output.create_node( + "call_function", + torch._C._functorch.set_inplace_requires_grad_allowed, + (allowed.as_proxy(),), + ) + prev = torch._C._functorch.get_inplace_requires_grad_allowed() + torch._C._functorch.set_inplace_requires_grad_allowed( + allowed.as_python_constant() + ) + tx.output.add_cleanup_hook( + lambda: torch._C._functorch.set_inplace_requires_grad_allowed(prev) + ) + return ConstantVariable.create(None) + + @register(torch.are_deterministic_algorithms_enabled) + def handle_are_deterministic_algorithms_enabled( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable: + guard = Guard( + GlobalStateSource(), + GuardBuilder.DETERMINISTIC_ALGORITHMS, # type: ignore[arg-type] + ) + install_guard(guard) + return VariableTracker.build( + tx, torch.are_deterministic_algorithms_enabled() + ) + + @register(torch._C._is_torch_function_enabled) + def handle_is_torch_function_enabled( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable: + install_guard(TorchFunctionDisableVariable._guards_singleton) + # see comment on SymbolicTorchFunctionState class as to why + # this is not a bug + return VariableTracker.build( + tx, tx.symbolic_torch_function_state.torch_function_subclass_enabled + ) + + @register(torch._C._is_cow_tensor) # pyrefly: ignore[missing-attribute] + def handle_is_cow_tensor( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> ConstantVariable: + if not arg.is_tensor(): + raise AssertionError( + f"_is_cow_tensor expects a tensor, got {arg.python_type_name()}" + ) + + def has_prior_cow_state_changing_op() -> bool: + if not isinstance(arg, TensorVariable): + return False + graph = arg.as_proxy().node.graph + return any( + (node.op == "call_method" and node.target == "_lazy_clone") + or (node.op == "call_function" and node.target is torch._lazy_clone) + for node in graph.nodes + ) + + if arg.source is None: + unimplemented( + gb_type="source-less COW tensor check", + context="torch._C._is_cow_tensor on source-less tensor", + explanation=( + "Dynamo cannot safely guard COW state for an intermediate " + "tensor without a source." + ), + hints=[ + "Avoid checking COW state on intermediate tensors inside " + "torch.compile regions.", + ], + ) + if tx.output.current_tracer.is_export or torch.compiler._is_exporting_flag: + unimplemented( + gb_type="COW tensor check during export", + context="torch._C._is_cow_tensor during export", + explanation=( + "Dynamo cannot safely export COW-state-dependent " + "control flow because COW state is not represented in " + "the exported graph." + ), + hints=[ + "Avoid checking COW state inside torch.export regions.", + ], + ) + fake_version = arg._get_fake_version() # pyrefly: ignore[missing-attribute] + if fake_version is not None and fake_version > 0: + unimplemented( + gb_type="COW tensor check after mutation", + context="torch._C._is_cow_tensor after tensor mutation", + explanation=( + "Dynamo cannot safely fold a COW state check after " + "the tensor's state may have changed inside the " + "compiled frame." + ), + hints=[ + "Move the COW state check before tensor mutations or " + "outside the torch.compile region.", + ], + ) + if has_prior_cow_state_changing_op(): + unimplemented( + gb_type="COW tensor check after COW-state-changing op", + context="torch._C._is_cow_tensor after _lazy_clone", + explanation=( + "Dynamo cannot safely fold a COW state check after " + "an op in the current graph may have changed that " + "tensor's COW state." + ), + hints=[ + "Move the COW state check before _lazy_clone or outside " + "the torch.compile region.", + ], + ) + real_value = arg.get_real_value() # pyrefly: ignore[missing-attribute] + if is_fake_tensor(real_value): + unimplemented( + gb_type="COW tensor check on FakeTensor", + context="torch._C._is_cow_tensor on FakeTensor", + explanation=( + "Dynamo cannot safely evaluate COW state from a " + "FakeTensor because COW state is not represented in " + "FakeTensor metadata." + ), + hints=[ + "Avoid checking COW state on FakeTensors inside " + "torch.compile regions.", + ], + ) + cow_state = _try_is_cow_tensor(real_value) + if cow_state is _COW_TENSOR_UNSUPPORTED: + unimplemented( + gb_type="COW tensor check on Python tensor subclass", + context="torch._C._is_cow_tensor on Python tensor subclass", + explanation=( + "Dynamo cannot safely evaluate COW state for Python " + "tensor subclasses because their storage semantics are " + "controlled by __torch_dispatch__." + ), + hints=[ + "Avoid checking COW state on tensor subclasses inside " + "torch.compile regions.", + ], + ) + install_guard(arg.source.make_guard(GuardBuilder.COW_TENSOR_MATCH)) + return VariableTracker.build(tx, cast(bool, cow_state)) + + @register(torch._C._is_torch_function_all_disabled) + def handle_is_torch_function_all_disabled( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable: + install_guard(TorchFunctionDisableVariable._guards_singleton) + return VariableTracker.build( + tx, not tx.symbolic_torch_function_state.torch_function_mode_enabled + ) + + @register(torch._C._is_torch_function_mode_enabled) + def handle_is_torch_function_mode_enabled( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable: + install_guard(TorchFunctionDisableVariable._guards_singleton) + # _is_torch_function_mode_enabled returns True only if: + # 1. Torch function modes are not disabled (DisableTorchFunction not entered) + # 2. There are actually modes on the stack + return VariableTracker.build( + tx, + tx.symbolic_torch_function_state.torch_function_mode_enabled + and tx.symbolic_torch_function_state.in_torch_function_mode(), + ) + + @register( + torch.overrides.has_torch_function, + torch.overrides.has_torch_function_variadic, + torch.overrides.has_torch_function_unary, + ) + def handle_has_torch_function( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> ConstantVariable: + tf_state = tx.symbolic_torch_function_state + if tf_state.skip_next: + tf_state.skip_next = False + return VariableTracker.build(tx, False) + elems = ( + unpack_iterable(tx, args[0]) + if len(args) == 1 and isinstance(args[0], TupleVariable) + else args + ) + return VariableTracker.build(tx, any(has_torch_function(x) for x in elems)) + + @register(torch._C._skip_one_hop_torch_function) + def handle_skip_one_hop_torch_function( + self, + tx: "InstructionTranslatorBase", + func: VariableTracker, + types: VariableTracker, + args: VariableTracker, + kwargs: VariableTracker, + ) -> VariableTracker: + tf_state = tx.symbolic_torch_function_state + if tf_state.skip_next: + from torch._dynamo.exc import raise_observed_exception + + raise_observed_exception( + RuntimeError, + tx, + args=[ + "you cannot skip two levels of __torch_function__, " + "you need to run one level of __torch_function__ " + "before being able to skip again." + ], + ) + tf_state.skip_next = True + tx.skip_one_hop_torch_function_depth += 1 + try: + return func.call_function( + tx, + unpack_iterable(tx, args), + kwargs.keys_as_python_constant(), # type: ignore[attr-defined] + ) + finally: + tx.skip_one_hop_torch_function_depth -= 1 + tf_state.skip_next = False + + @register( + *dict.fromkeys( # remove duplicates + device_interface.stream + for _, device_interface in get_registered_device_interfaces() + ) + ) + def handle_device_interface_stream( + self, tx: "InstructionTranslatorBase", stream: "StreamVariable" + ) -> StreamContextVariable: + return StreamContextVariable.create(tx, stream) + + @register(torch.from_numpy) + def handle_from_numpy( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> TensorVariable: + if not config.trace_numpy: + unimplemented( + gb_type="call `torch.from_numpy` with `torch._dynamo.config.trace_numpy=False`", + context=f"trace_numpy={config.trace_numpy}", + explanation=( + "Attempted to call `torch.from_numpy` with config " + "`torch._dynamo.config.trace_numpy` set to `False`." + ), + hints=[ + "Change `torch._dynamo.config.trace_numpy` to `True`.", + ], + ) + if not np: + unimplemented( + gb_type="`torch.from_numpy` with NumPy unavailable", + context="", + explanation="Attempted to call `torch.numpy` but NumPy could not be imported.", + hints=[ + "Check NumPy version and installation in your environment.", + *graph_break_hints.USER_ERROR, + ], + ) + return wrap_fx_proxy_cls( + target_cls=TensorVariable, + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + torch.as_tensor, + *proxy_args_kwargs(args, {}), + ), + example_value=None, + ) + + @register(torch.jit.annotate) + def handle_jit_annotate( + self, tx: "InstructionTranslatorBase", the_type: Any, the_value: V + ) -> V: + return the_value + + @register(torch.backends.cudnn.is_acceptable) + def handle_cudnn_is_acceptable( + self, tx: "InstructionTranslatorBase", tensor: Any, *extra: Any + ) -> ConstantVariable: + # is_acceptable(tensor) returns true if + # (a) tensor dtype/device are supported by cudnn + # (b) cudnn is available + # (c) some initialization has completed + # technically, it depends on some global state from (c) (torch.backends.cudnn.__cudnn_version) + if extra: + raise AssertionError("Expect 1 input to cudnn.is_acceptable") + if not tensor.is_tensor(): + raise AssertionError( + "Expect input to cudnn.is_acceptable to be a tensor" + ) + tensor_inp = torch.tensor(0, dtype=tensor.dtype, device=tensor.device) + return VariableTracker.build( + tx, torch.backends.cudnn.is_acceptable(tensor_inp) + ) + + @register(torch.utils.hooks.BackwardHook) + def handle_backward_hook( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return variables.BackwardHookVariable.create(tx, *args, **kwargs) + + @register(torch.nn.Parameter) + def handle_parameter( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return self.call_nn_parameter(tx, *args, **kwargs) + + @register(torch.ops.aten.sym_size, torch.ops.aten.sym_size.int) + def handle_sym_size( + self_: Any, tx: "InstructionTranslatorBase", self, dim: Any | None = None + ) -> VariableTracker | None: + # we see this when retracing already traced code + if dim is not None: + return self.call_method(tx, "size", [dim], {}) + return None + + @register(torch.ops.aten.sym_stride, torch.ops.aten.sym_stride.int) + def handle_sym_stride( + self_: Any, tx: "InstructionTranslatorBase", self, dim: Any | None = None + ) -> VariableTracker | None: + if dim is not None: + return self.call_method(tx, "stride", [dim], {}) + return None + + @register(torch.addcdiv) + def handle_addcdiv( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if len(args) == 3 and "value" in kwargs and len(kwargs) == 1: + # decompose addcdiv into constituent ops, prevents a graph break due to converting + # value to a scalar + result = TorchInGraphFunctionVariable(torch.div).call_function( + tx, [*args[1:]], {} + ) + result = TorchInGraphFunctionVariable(torch.mul).call_function( + tx, [result, kwargs["value"]], {} + ) + return TorchInGraphFunctionVariable(torch.add).call_function( + tx, [args[0], result], {} + ) + return None + + @register(torch.full) + def handle_full( + self, + tx: "InstructionTranslatorBase", + size: VariableTracker, + fill_value: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if fill_value.is_tensor() and not issubclass( + fill_value.python_type(), torch.nn.Parameter + ): + # Decompose: create empty tensor and fill it + # This avoids the scalar extraction at compile time + empty_result = TorchInGraphFunctionVariable(torch.empty).call_function( + tx, [size], kwargs + ) + # Call fill_ method on the empty tensor + return empty_result.call_method(tx, "fill_", [fill_value], {}) + return None + + @register(torch.tensor_split) + def handle_tensor_split( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + indices_or_sections = ( + args[1] if len(args) >= 2 else kwargs.get("indices_or_sections") + ) + if not isinstance(indices_or_sections, TensorVariable): + return None + + example_value = indices_or_sections.as_proxy().node.meta.get( + "example_value" + ) + if ( + example_value is None + or example_value.dim() != 0 + or example_value.device.type != "cpu" + or example_value.dtype != torch.int64 + or (item_memo := example_value.item_memo) is None + ): + return None + + sections = torch.fx.experimental.symbolic_shapes.guard_scalar(item_memo) + if not isinstance(sections, int): + return None + + # tensor_split's scalar-tensor overload needs a concrete output + # arity. Guard the memoized value here so downstream AOT tracing + # does not re-read the 0-D tensor as a fresh unbacked scalar. + sections_vt = ConstantVariable.create(sections) + if len(args) >= 2: + args = (args[0], sections_vt, *args[2:]) + else: + kwargs["indices_or_sections"] = sections_vt + return TorchInGraphFunctionVariable(torch.tensor_split).call_function( + tx, list(args), kwargs + ) + + @register(torch._foreach_lerp_) + def handle_inplace_foreach_lerp_scalar( + _: Any, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + # Decompose via addcmul_ only when the weight is a tensor, so + # tensor weights (e.g. 0-dim tensor from tensor betas in Adam) stay + # in tensor arguments instead of hitting float() in the native + # lerp_scalar lowering. Python scalar weights can use the native + # foreach op directly, avoiding extra full-size weight tensors. + if ( + config.enable_dynamo_decompositions + and len(args) == 3 + and args[2].is_tensor() + and not kwargs + ): + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.foreach_lerp_inplace), + list(args), + kwargs, + ) + return None + + @register(torch._foreach_pow) + def handle_foreach_pow_scalar( + _: Any, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if not config.enable_dynamo_decompositions: + return None + + # In eager it's more performant to call item() from within the C op implementation + # in compile, it's more performant to not graph break. + if len(args) == 2 and args[0].is_tensor() and not kwargs: + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.foreach_pow_scalar), + list(args), + kwargs, + ) + return None + + @register(torch._C._group_tensors_by_device_and_dtype) + def handle_group_tensors_by_device_and_dtype( + _: Any, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.group_tensors_by_device_and_dtype), + list(args), + kwargs, + ) + + @register(torch._assert) + def handle_assert( + self, + tx: "InstructionTranslatorBase", + condition: VariableTracker, + message: VariableTracker, + ) -> VariableTracker | None: + if (condition.is_python_constant() and condition.as_python_constant()) or ( + isinstance(condition, variables.SymNodeVariable) + and condition.evaluate_expr() + ): + return ConstantVariable.create(None) + return None + + @register(SDPAParams) + def handle_sdpa_params( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return wrap_fx_proxy( + tx, + proxy=tx.output.create_proxy( + "call_function", + torch._C._SDPAParams, + *proxy_args_kwargs(args, kwargs), + ), + param_vars=args, + ) + + if DistributedVariable.is_available(): + from torch.distributed.distributed_c10d import ( + _get_group_size_by_name, + _get_group_tag, + _rank_not_in_group, + _resolve_group_name_by_ranks_and_tag, + get_process_group_ranks, + get_rank, + get_world_size, + ) + + @register( + _get_group_size_by_name, + _get_group_tag, + _rank_not_in_group, + get_process_group_ranks, + _resolve_group_name_by_ranks_and_tag, + get_rank, + get_world_size, + ) + def handle_constant_processgroup_functions( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # We desugar it at trace-time into ranks by directly calling util + # bake the result into the trace + if len(args) == 0 and len(kwargs) == 0: + # get_rank() or get_world_size() with no args (uses default group) + pass + elif len(args) == 1 and len(kwargs) == 0: + # group or group name + if not ( + args[0].is_python_constant() + or ( + isinstance(args[0], CustomClassObjectVariable) + and args[ # pyrefly: ignore[missing-attribute] + 0 + ].value.script_class_name # pyrefly: ignore[missing-attribute] + == "torch.distributed.distributed_c10d.ProcessGroup" + ) + ): + raise AssertionError( + f"Expected group arg to be a python constant or ProcessGroup, got {args[0]}" + ) + elif len(args) == 2 and len(kwargs) == 0: + # ranks + tag + if not isinstance(args[0], ListVariable): + raise AssertionError( + f"Expected first arg to be a ListVariable (ranks), got {type(args[0])}" + ) + if not args[1].is_python_constant(): + raise AssertionError( + "Expected second arg (tag) to be a python constant" + ) + elif len(args) == 0 and len(kwargs) > 0: + # All keyword arguments (e.g., get_world_size(group=...)) + pass + else: + raise AssertionError( + f"Invalid group value ({args}, {kwargs}) for constant pg " + f"function {self.value}" + ) + + def get_arg_value(arg: VariableTracker) -> Any: + # CustomClassObjectVariable for ProcessGroup doesn't support + # as_python_constant(), so extract real_obj directly + if isinstance(arg, CustomClassObjectVariable): + return arg.value.real_obj # pyrefly: ignore[missing-attribute] + return arg.as_python_constant() + + args_as_value = [get_arg_value(arg) for arg in args] + kwargs_as_value = {k: get_arg_value(v) for k, v in kwargs.items()} + invocation_result = self.value(*args_as_value, **kwargs_as_value) + + # Note - while we *could* cook up sources around invocations, like a FunctionSource + # the space of invoking functions in the middle of the guard chain is very iffy. As such, + # guard propagation via options is the best we can do. + return VariableTracker.build(tx, invocation_result) + + @register(torch.nested.nested_tensor) + def handle_nested_tensor( + self, + tx: "InstructionTranslatorBase", + tensor_list: VariableTracker | None = None, + *args: VariableTracker, + layout: Any | None = None, + **kwargs: VariableTracker, + ) -> None: + from .lists import BaseListVariable + + if layout and layout.is_constant_match(torch.strided): + unimplemented( + gb_type="Attempted to use strided NestedTensor", + context=f"layout={layout}", + explanation="Dynamo does not support this.", + hints=[ + "Change layout=torch.jagged.", + *graph_break_hints.SUPPORTABLE, + ], + ) + if not isinstance(tensor_list, BaseListVariable): + unimplemented( + gb_type="Attempted to use `nested_tensor` with non-list input", + context=f"tensor_list={tensor_list}", + explanation="Dynamo does not support this.", + hints=[ + "Change `nested_tensor` with list input.", + *graph_break_hints.USER_ERROR, + ], + ) + return None + + @register(torch.nn.functional.one_hot) + def handle_one_hot( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> None: + if len(args) + len(kwargs) == 1 or ( + len(args) == 2 and args[1].is_constant_match(-1) + ): + unimplemented( + gb_type="Attempted to use `torch.nn.functional.one_hot` with data-dependent output shape", + context=f"args={args}, kwargs={kwargs}", + explanation="Dynamo does not support this.", + hints=[ + "Explicitly set the `num_classes` param of the function call " + "`torch.nn.functional.one_hot` to something other than -1.", + ], + ) + return None + + @register(torch.fx.experimental.symbolic_shapes.guarding_hint_or_throw) + def handle_guarding_hint_or_throw( + self, + tx: "InstructionTranslatorBase", + expr: VariableTracker, + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.guarding_hint_or_throw( + expr.sym_num + ), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.optimization_hint) + def handle_optimization_hint( + self, + tx: "InstructionTranslatorBase", + expr: VariableTracker, + fallback: VariableTracker | None = None, + ) -> VariableTracker | None: + fallback_int = fallback.as_python_constant() if fallback else None + if isinstance(expr, SymNodeVariable): + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.optimization_hint( + expr.sym_num, fallback_int + ), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.guard_size_oblivious) # type: ignore[deprecated] + def handle_guard_size_oblivious( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + # TODO: this probably should be folded somewhere else but I'm not sure where + # TODO: some of the other symbolic_shapes special tools can also get this treatment too + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.guard_size_oblivious( # type: ignore[deprecated] + expr.sym_num + ), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.guard_or_true) + def handle_guard_or_true( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + # TODO: this probably should be folded somewhere else but I'm not sure where + # TODO: some of the other symbolic_shapes special tools can also get this treatment too + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.guard_or_true(expr.sym_num), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.guard_or_false) + def handle_guard_or_false( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + # TODO: this probably should be folded somewhere else but I'm not sure where + # TODO: some of the other symbolic_shapes special tools can also get this treatment too + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.guard_or_false(expr.sym_num), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.statically_known_false) + def handle_statically_known_false( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.statically_known_false( + expr.sym_num + ), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.has_free_unbacked_symbols) + def handle_has_free_unbacked_symbols( + self, tx: "InstructionTranslatorBase", x: VariableTracker + ) -> VariableTracker | None: + from .tensor import TensorVariable + + if isinstance(x, TensorVariable): + example_value = x.as_proxy().node.meta.get("example_value") + if example_value is not None: + return variables.ConstantVariable.create( + torch.fx.experimental.symbolic_shapes.has_free_unbacked_symbols( + example_value + ) + ) + return None + + @register(torch.fx.experimental.symbolic_shapes.guard_scalar) + def guard_scalar( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker: + if isinstance(expr, SymNodeVariable): + val = expr.sym_num + elif expr.is_python_constant(): + val = expr.as_python_constant() + else: + unimplemented( + gb_type="torch.fx.experimental.symbolic_shapes.guard_scalar branch not supported", + context=f"expr: {expr}", + explanation="Expected `expr` to be a symbolic variable or constant.", + hints=[], + ) + return VariableTracker.build( + tx, + # pyrefly: ignore [bad-argument-type, unbound-name] + torch.fx.experimental.symbolic_shapes.guard_scalar(val), + ) + + @register(torch.fx.experimental.symbolic_shapes.statically_known_true) + def handle_statically_known_true( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.statically_known_true( + expr.sym_num + ), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.sym_and) + def handle_sym_and( + self, tx: "InstructionTranslatorBase", *terms: VariableTracker + ) -> VariableTracker | None: + if all(isinstance(x, SymNodeVariable) for x in terms): + return SymNodeVariable.create( + tx, + torch.fx.experimental.symbolic_shapes.sym_and( + *(x.as_proxy() for x in terms) + ), + sym_num=None, + ) + return None + + @register(torch.fx.experimental.symbolic_shapes.sym_or) + def handle_sym_or( + self, tx: "InstructionTranslatorBase", *terms: VariableTracker + ) -> VariableTracker | None: + if all(isinstance(x, SymNodeVariable) for x in terms): + return SymNodeVariable.create( + tx, + torch.fx.experimental.symbolic_shapes.sym_or( + *(x.as_proxy() for x in terms) + ), + sym_num=None, + ) + return None + + @register(torch.fx.experimental.symbolic_shapes.has_static_value) + def handle_has_static_value( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + val = expr.sym_num + elif expr.is_python_constant(): + val = expr.as_python_constant() + else: + return None + + return VariableTracker.build( + tx, torch.fx.experimental.symbolic_shapes.has_static_value(val) + ) + + @register(torch._C._autograd._unsafe_set_version_counter) + def handle_unsafe_set_version_counter( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + from ..tensor_version_op import _unsafe_set_version_counter + + return TorchInGraphFunctionVariable( + _unsafe_set_version_counter + ).call_function(tx, [*args], kwargs) + + @register(torch._C._functorch.peek_interpreter_stack) + def handle_functorch_peek_interpreter_stack( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> UserDefinedObjectVariable: + # Wrap C++ interpreter (torch._C._functorch.CInterpreter) as UserDefinedObjectVariable, + # but Python interpreter (torch._functorch.pyfunctorch.FuncTorchInterpreter) as FuncTorchInterpreterVariable. + return UserDefinedObjectVariable( + torch._C._functorch.peek_interpreter_stack() + ) + + @register(torch._functorch.pyfunctorch.coerce_cinterpreter) + def handle_functorch_pyfunctorch_coerce_cinterpreter( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> FuncTorchInterpreterVariable: + # pyrefly: ignore[missing-attribute] + cinterpreter = args[0].value + return FuncTorchInterpreterVariable( + torch._functorch.pyfunctorch.coerce_cinterpreter(cinterpreter) + ) + + @register(torch.tensor) + def handle_torch_tensor( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + def check_any_unspec(x: VariableTracker) -> bool: + # NB: This includes UnspecializedPythonVariable + if x.is_tensor() or isinstance(x, SymNodeVariable): + return True + elif isinstance(x, (ListVariable, TupleVariable)): + return any(check_any_unspec(y) for y in x.items) + # TODO: there maybe other recursive structures you need to + # check + else: + return False + + data_arg = None + if args: + data_arg = args[0] + elif "data" in kwargs: + data_arg = kwargs["data"] + + # NB: OK to pass torch.tensor(tensor), this will trace fine + if ( + data_arg is not None + and not data_arg.is_tensor() + and check_any_unspec(data_arg) + ): + # This is slower and less canonical, so only use it if we + # have to + return TorchInGraphFunctionVariable(torch._refs.tensor).call_function( + tx, [*args], kwargs + ) + else: + return None + + @register(torch._C._pop_torch_function_stack) + def handle_pop_torch_function( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> TorchFunctionModeVariable: + if args: + raise AssertionError( + f"_pop_torch_function_stack expects no args, got {len(args)}" + ) + if kwargs: + raise AssertionError( + f"_pop_torch_function_stack expects no kwargs, got {len(kwargs)}" + ) + if not tx.symbolic_torch_function_state.mode_stack: + unimplemented( + gb_type="Attempted to pop from empty torch function mode stack", + context="", + explanation="Called `torch._C._pop_torch_function_stack` when torch function mode stack is empty.", + hints=[ + "Do not pop from empty torch function mode stack.", + *graph_break_hints.USER_ERROR, + ], + ) + TorchFunctionModeStackVariable.register_mutation(tx) + return tx.symbolic_torch_function_state.pop_torch_function_mode() + + @register(torch._C._push_on_torch_function_stack) + def handle_push_torch_function( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(args) != 1 or kwargs: + raise_type_error( + tx, + f"push_torch_function takes exactly one argument ({len(args)} given)", + ) + TorchFunctionModeStackVariable.register_mutation(tx) + # type: ignore[arg-type] + tx.symbolic_torch_function_state.push_torch_function_mode(args[0]) + return ConstantVariable.create(None) + + @register(torch._C._len_torch_function_stack) + def handle_len_torch_function( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if args or kwargs: + raise_type_error(tx, "len_torch_function_stack takes no arguments") + return VariableTracker.build( + tx, len(tx.symbolic_torch_function_state.mode_stack) + ) + + @register(torch._C._get_function_stack_at) + def handle_get_stack_at( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> TorchFunctionModeVariable: + if len(args) != 1 or kwargs: + raise_type_error( + tx, + f"get_function_stack_at takes exactly one argument ({len(args)} given)", + ) + ind = args[0].as_python_constant() + if ind < 0: + raise AssertionError( + f"Expected non-negative index for get_function_stack_at, got {ind}" + ) + if ind >= len(tx.symbolic_torch_function_state.mode_stack): + raise AssertionError( + f"Index {ind} out of range for torch function mode stack " + f"of length {len(tx.symbolic_torch_function_state.mode_stack)}" + ) + return tx.symbolic_torch_function_state.mode_stack[ind] + + @register(torch.utils._python_dispatch._get_current_dispatch_mode_stack) + def handle_get_current_dispatch_mode_stack( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if args or kwargs: + raise_type_error( + tx, + "_get_current_dispatch_mode_stack() takes no arguments", + ) + # During tracing, Dynamo runs with dispatch modes removed, so + # the stack is always empty. Return [] as a constant instead + # of graph-breaking. + return VariableTracker.build(tx, []) + + @register(torch.get_device_module.__wrapped__) + def handle_get_device_module( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(args) + len(kwargs) > 1 or (kwargs and "device" not in kwargs): + unimplemented( + gb_type="improper torch.get_device_module arguments", + context=f"args={args}, kwargs={kwargs}", + explanation="torch.get_device_module accepts 1 optional argument `device`", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + try: + if kwargs: + device = kwargs["device"].as_python_constant() + elif args: + device = args[0].as_python_constant() + else: + device = None + module = torch.get_device_module(device) + except Exception as e: + unimplemented( + gb_type="bad device argument to torch.get_device_module", + context=f"args={args}, kwargs={kwargs}", + explanation="Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + hints=[*graph_break_hints.USER_ERROR], + from_exc=e, + ) + + # need to guard only on no-arg get_device_module + if device is None: + source = CallFunctionNoArgsSource(self.source) + install_guard(source.make_guard(GuardBuilder.ID_MATCH)) + # assumes `module` is in the form `torch.xyz` + torch_source = ImportSource("torch") + install_guard(torch_source.make_guard(GuardBuilder.ID_MATCH)) + new_source = AttrSource( + torch_source, + module.__name__.rsplit(".", maxsplit=1)[-1], + ) + return VariableTracker.build(tx, module, new_source) + + @register( + torch.accelerator.current_stream, + torch.cuda.current_stream, + torch.xpu.current_stream, + ) + def handle_current_stream( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> StreamVariable: + from .streams import _get_stream_variable_cls + + if len(args) + len(kwargs) > 1 or (kwargs and "device" not in kwargs): + unimplemented( + gb_type="unsupported arguments to torch.accelerator.current_stream", + context=f"args={args}, kwargs={kwargs}", + explanation="torch.accelerator.current_stream accepts one optional argument `device`", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + try: + if kwargs: + device = torch.device(kwargs["device"].as_python_constant()) + elif args: + device = torch.device(args[0].as_python_constant()) + else: + device = None + + stream_var = tx.symbolic_stream_state.cur_stream(device) + stream_variable_cls = _get_stream_variable_cls(self.value) + if stream_variable_cls is not None and not isinstance( + stream_var, stream_variable_cls + ): + stream_var = stream_variable_cls( + stream_var.proxy, + stream_var.value, + stream_var.user_object_index, + source=stream_var.source, + ) + return stream_var + except Exception as e: + unimplemented( + gb_type="bad device argument to torch.accelerator.current_stream", + context=f"args={args}, kwargs={kwargs}", + explanation="Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + hints=[*graph_break_hints.USER_ERROR], + from_exc=e, + ) + + _synchronize_fn_to_device_type = { + torch.cuda.synchronize: "cuda", + torch.xpu.synchronize: "xpu", + torch.mps.synchronize: "mps", + torch.cpu.synchronize: "cpu", + } + + @register( + torch.accelerator.synchronize, + torch.cuda.synchronize, + torch.xpu.synchronize, + torch.mps.synchronize, + torch.cpu.synchronize, + ) + def handle_synchronize( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + device = None + if kwargs and "device" in kwargs: + device = torch.device(kwargs["device"].as_python_constant()) + elif args: + device = torch.device(args[0].as_python_constant()) + + if device is None: + device_type = _synchronize_fn_to_device_type.get(self.value) + if device_type is None: + # torch.accelerator.synchronize with no args + accelerator = torch.accelerator.current_accelerator() + if accelerator is None: + raise AssertionError( + "No accelerator available for torch.accelerator.synchronize" + ) + device_type = accelerator.type + device = torch.device(device_type) + + # CPU synchronize is a no-op, skip emitting the op + if device.type == "cpu": + return ConstantVariable.create(None) + + tx.output.create_proxy( + "call_function", + torch.ops.streams.synchronize_device, + (device.type, device.index or 0), + {}, + ) + return ConstantVariable.create(None) + + @register(torch.set_default_device) + def handle_set_default_device( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # Today this is inserted in the graph, once TF mode + # handling is complete, we can trace the device context + # like any other TF mode and remove this special handling + # Insert the TF mode representing the device context at + # the bottom of the stack to match the eager semantics + # Running the graph will ensure that the DeviceContext mode is + # at the correct position in the stack + TorchFunctionModeStackVariable.register_mutation(tx) + if args[0].is_constant_none(): + TorchFunctionModeStackVariable.clear_default_device(tx) + else: + TorchFunctionModeStackVariable.register_device_context_insertion(tx) + + return ConstantVariable.create(None) + + from torch._prims_common import elementwise_dtypes + + @register(elementwise_dtypes) + def handle_elementwise_dtypes( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + from .builder import SourcelessBuilder + + type_promotion_kind = kwargs["type_promotion_kind"].as_python_constant() + real_args = [] + for arg in args: + if isinstance(arg, TensorVariable): + real_args.append(arg.as_proxy().node.meta["example_value"]) + elif arg.is_python_constant(): + real_args.append(arg.as_python_constant()) + else: + unimplemented( + gb_type="elementwise_dtypes unsupported arg type", + context=str(arg), + explanation=( + "elementwise_dtypes requires tensor or constant arguments, " + f"got {type(arg).__name__}" + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + result = elementwise_dtypes( + *real_args, type_promotion_kind=type_promotion_kind + ) + return SourcelessBuilder.create(tx, result) + + def check_impl( + self, + tx: "InstructionTranslatorBase", + predicate_vt: VariableTracker | None, + message_vt: VariableTracker | None, + error_type: type[Exception] = RuntimeError, + ) -> VariableTracker: + if predicate_vt is None: + raise_type_error( + tx, + f"{self.value.__name__}() missing 1 required positional argument: 'cond'", + ) + + if predicate_vt.is_tensor(): + raise_type_error( + tx, + "cond must be a bool, but got a Tensor. " + "For tensor conditions, use torch._check_tensor_all() " + "to assert that all elements are true.", + ) + + message_eager = None + message_graph_arg = None + # Realize a possible LazyVariableTracker so the exact-type checks + # below see the underlying VariableTracker rather than the wrapper. + if message_vt is not None: + message_vt = message_vt.realize() + match message_vt: + case None: + pass + case NestedUserFunctionVariable() | UserFunctionVariable() if type( + message_vt + ) in (NestedUserFunctionVariable, UserFunctionVariable): + # These report is_python_constant() True (as_python_constant + # returns the underlying fn), so this arm must precede the + # constant arm below. Restrict to exact types: other + # function-VT subclasses (e.g. bound methods, whose + # get_function drops the receiver) cannot be faithfully + # reconstructed as a zero-arg message callable, so they fall + # through to the graph-break arm. + try: + message_eager = message_vt.get_function() + except ClosureConversionError: + unimplemented( + gb_type="Can't convert torch._check*() message closure", + context=str(message_vt), + explanation=( + "The message argument of torch._check*() must be a function " + "whose closure variables are Python constants." + ), + hints=[ + "Remove closure variables that reference non-constant values, e.g. " + "remove references to tensor `x` in `lambda: f'{x} failed check'`", + *graph_break_hints.SUPPORTABLE, + ], + ) + + message_graph_arg = tx.output.register_static_attr_and_return_proxy( + "_check_message", message_eager + ) + case _ if message_vt.is_python_constant(): + # Mirror eager torch._check, which accepts any constant and + # stringifies it; None means "use the default message". + message_eager = message_vt.as_python_constant() + if message_eager is not None: + message_graph_arg = str(message_eager) + case _: + unimplemented( + gb_type="Can't extract message from torch._check*()", + context=str(message_vt), + explanation=( + "The message argument of torch._check*() must be a string, None, " + "or a function." + ), + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + if predicate_vt.is_python_constant(): + if predicate_vt.as_python_constant(): + return ConstantVariable.create(None) + msg = ( + str(message_eager() if callable(message_eager) else message_eager) + if message_eager is not None + else ("Expected cond to be True, but got False.") + ) + raise_observed_exception(error_type, tx, args=[msg]) + + predicate_proxy = predicate_vt.as_proxy() + + proxy_args: tuple[Any, ...] + if message_graph_arg is None: + proxy_args = (predicate_proxy,) + else: + proxy_args = (predicate_proxy, message_graph_arg) + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + torch._check, + proxy_args, + {}, + ), + ) + + @register(torch._check) + def handle_check( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + predicate_vt = args[0] if args else kwargs.get("cond") + rest_args = args[1:] if args else () + message_vt = rest_args[0] if rest_args else kwargs.get("message") + return check_impl(self, tx, predicate_vt, message_vt) + + @register( + torch._check_with, + torch._check_index, + torch._check_value, + torch._check_type, + torch._check_not_implemented, + ) + def handle_check_with( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if self.value is torch._check_with: + error_type_vt = args[0] if args else kwargs.get("error_type") + rest_args = args[1:] if args else () + else: + error_type_vt = None + rest_args = args + + _CHECK_ERROR_TYPES: dict[object, type[Exception]] = { + torch._check_index: IndexError, + torch._check_value: ValueError, + torch._check_type: TypeError, + torch._check_not_implemented: NotImplementedError, + } + + error_type = ( + error_type_vt.as_python_constant() + if error_type_vt is not None + else _CHECK_ERROR_TYPES.get(self.value, RuntimeError) + ) + + predicate_vt = rest_args[0] if rest_args else kwargs.get("cond") + rest_args = rest_args[1:] if rest_args else () + message_vt = rest_args[0] if rest_args else kwargs.get("message") + return check_impl(self, tx, predicate_vt, message_vt, error_type) + + @register( + torch._check_tensor_all_with, + torch._check_tensor_all, + ) + def handle_check_tensor_all( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if self.value is torch._check_tensor_all_with: + error_type_vt = args[0] if args else kwargs.get("error_type") + rest_args = args[1:] if args else () + error_type = ( + error_type_vt.as_python_constant() + if error_type_vt is not None + else RuntimeError + ) + else: + rest_args = args + error_type = RuntimeError + + cond_vt = rest_args[0] if rest_args else kwargs.get("cond") + rest_args = rest_args[1:] if rest_args else () + message_vt = rest_args[0] if rest_args else kwargs.get("message") + + if cond_vt is None: + return check_impl(self, tx, None, message_vt, error_type) + + scalar_vt = cond_vt.call_method(tx, "_is_all_true", [], {}).call_method( + tx, "item", [], {} + ) + + return check_impl(self, tx, scalar_vt, message_vt, error_type) + + def exchange_device_helper( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + fn: Callable[[int], int | None], + ) -> VariableTracker: + if len(args) != 1 or kwargs: + raise_type_error( + tx, + f"{fn.__name__} takes exactly one argument ({len(args)} given)", + ) + torch_source = ImportSource("torch") + install_guard(torch_source.make_guard(GuardBuilder.ID_MATCH)) + current_device_source = CallFunctionNoArgsSource( + AttrSource(AttrSource(torch_source, "cuda"), "current_device") + ) + install_guard(current_device_source.make_guard(GuardBuilder.EQUALS_MATCH)) + arg = args[0].as_python_constant() + prev = fn(arg) + tx.output.create_node( + "call_function", + fn, + (arg,), + {}, + ) + tx.output.add_cleanup_hook(lambda: torch.cuda.set_device(prev)) + return VariableTracker.build(tx, prev) + + @register(torch.cuda._exchange_device) + def handle_exchange_device( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return exchange_device_helper( + tx, list(args), kwargs, torch.cuda._exchange_device + ) + + @register(torch.cuda._maybe_exchange_device) + def handle_maybe_exchange_device( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return exchange_device_helper( + tx, list(args), kwargs, torch.cuda._maybe_exchange_device + ) + + @register(torch._dynamo.decorators.override_optimization_hint) + def handle_override_optimization_hint( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + from .constant import ConstantVariable + from .tensor import SymNodeVariable + + x_vt = args[0] + val_vt = args[1] + val = val_vt.as_python_constant() + + if x_vt.is_python_constant(): + torch._dynamo.decorators.override_optimization_hint( + x_vt.as_python_constant(), val + ) + return ConstantVariable.create(None) + + if isinstance(x_vt, SymNodeVariable): + torch._dynamo.decorators.override_optimization_hint(x_vt.sym_num, val) + return ConstantVariable.create(None) + + raise UserError( + UserErrorType.INVALID_INPUT, + "override_optimization_hint expects a SymInt or int argument, " + f"got {type(x_vt).__name__}", + ) + + @register(torch.autograd.grad) + def handle_autograd_grad( + self, tx: "InstructionTranslatorBase", *args, **kwargs + ): + """ + Handle torch.autograd.grad() calls within compiled regions. + + NOTE [Tracing autograd.grad in dynamo] + + We validate two things: + + 1. External grad_fns cannot be consumed: The grad_fn on external inputs + could change at runtime, so we would need to guard on it if we wanted + to trace through it. For now, we reject this case. + We compute "consumed" grad_fns (reachable from outputs, excluding + autograd.grad inputs parameter) and verify no graph input's grad_fn is in this set. + + 2. Returned tensors cannot have consumed grad_fns: If autograd.grad + consumes a grad_fn and we return a tensor connected to it, the user + would get "backward through graph a second time" error. We track + consumed grad_fns and check at output time. If violated, we retry + with a graph break at autograd.grad. + + Safe vs Unsafe Cases: + + Case 1 - Safe (external tensor is autograd.grad input): + x = torch.randn(4, requires_grad=True) + external = x * 2 # has external grad_fn + + @torch.compile + def fn(external_input): + loss = external_input.sum() + return torch.autograd.grad(loss, external_input) + + Safe because autograd.grad stops at external_input, never consuming + its external grad_fn. + + Case 2 - Unsafe (external grad_fn in path): + @torch.compile + def fn(external_input): + loss = mod(external_input).sum() + return torch.autograd.grad(loss, mod.weight) + + Unsafe because autograd.grad must traverse through external_input's + grad_fn to reach mod.weight. The external grad_fn could change at + runtime, so we would need to guard on it (like AOTAutograd does). + For now, we reject this case. + + Case 3 - Unsafe (returning tensor with consumed grad_fn): + @torch.compile + def fn(x): + y = x * 2 + grad = torch.autograd.grad(y.sum(), x) + return y, grad # y's grad_fn was consumed! + + Unsafe because y's grad_fn was consumed by autograd.grad. Trying to + backward through y later would error. + """ + from .. import compiled_autograd, config + from .builder import wrap_fx_proxy + from .constant import ConstantVariable + from .dicts import ConstDictVariable + from .lists import BaseListVariable + from .tensor import TensorVariable + + if not config.trace_autograd_ops: + unimplemented( + gb_type="using `torch.autograd.grad` with `torch._dynamo.config.trace_autograd_ops=False`", + context=f"trace_autograd_ops={config.trace_autograd_ops}", + explanation=( + "Attempted to call `torch.autograd.grad` with config " + "`torch._dynamo.config.trace_autograd_ops` set to `False`." + ), + hints=[ + "Change `torch._dynamo.config.trace_autograd_ops` to `True`.", + ], + ) + + # Graph break if we detected on a previous attempt that autograd.grad + # consumed grad_fns of returned tensors. This gives better compile + # coverage than failing the entire compile. + if tx.speculation_log.graph_break_on_autograd_grad: + leaked = tx.speculation_log.autograd_grad_leaked_tensors + leaked_str = ", ".join(leaked) if leaked else "unknown" + unimplemented( + gb_type="autograd.grad consumed returned tensor's grad_fn", + context=f"Leaked output tensors: {leaked_str}", + explanation=( + "torch.autograd.grad() consumes grad_fns that are needed by tensors " + "returned from this compiled function. This would cause 'backward " + "through graph a second time' errors.\n" + f" The following returned tensors have consumed grad_fns: {leaked_str}" + ), + hints=[ + f"Detach the problematic tensor(s) before returning: e.g. `{leaked[0]}.detach()`" + if leaked + else "Call .detach() on the tensor before returning.", + "If you need to backward through the returned tensor, use retain_graph=True in autograd.grad().", + ], + ) + + # Graph break if compiled_autograd is enabled. + # Compiled autograd has limitations (e.g., view_fn in CopySlices) + # that would cause errors during fake tensor execution. + if compiled_autograd.compiled_autograd_enabled: + unimplemented( + gb_type="autograd.grad with compiled autograd", + context="compiled_autograd is currently enabled", + explanation=( + "torch.autograd.grad() inside torch.compile is not supported when " + "compiled autograd is enabled. These two features have conflicting " + "requirements for how the autograd graph is traced." + ), + hints=[ + "Disable compiled autograd by removing the compiled_autograd context manager.", + "Or move the autograd.grad() call outside the torch.compile region.", + "Or restructure your code so autograd.grad() and compiled_autograd don't overlap.", + ], + ) + + # Check for external GradientEdge objects in outputs and inputs args + # if there is it will be a graph break + if len(args) >= 1: + _check_for_gradient_edge(args[0], "outputs") + if len(args) >= 2: + _check_for_gradient_edge(args[1], "inputs") + + # Collect external grad_fn objects from graph inputs, along with their sources. + # We need to collect ALL grad_fns associated with each input tensor: + # - Direct grad_fn, base tensor's grad_fn (for views) + # - Inner tensors (for subclasses) + external_grad_fns: set[torch.autograd.graph.Node] = set() + # Map grad_fn -> source name for better error messages + grad_fn_to_source: dict[torch.autograd.graph.Node, str] = {} + for var in tx.output.input_source_to_var.values(): + if isinstance(var, TensorVariable): + fake_tensor = var.as_proxy().node.meta.get("example_value") + if not isinstance(fake_tensor, torch.Tensor): + raise AssertionError( + f"Expected fake_tensor to be a torch.Tensor, got {type(fake_tensor)}" + ) + tensor_grad_fns = _collect_all_grad_fns(fake_tensor) + external_grad_fns.update(tensor_grad_fns) + # Track source name for error messages + if var.source is not None: + for gf in tensor_grad_fns: + grad_fn_to_source[gf] = var.source.name + + # Collect tensors from outputs and inputs args + from ..output_graph import collect_reachable_grad_fns + + outputs_with_sources = ( + _collect_tensors_with_sources(args[0]) if len(args) >= 1 else [] + ) + inputs_with_sources = ( + _collect_tensors_with_sources(args[1]) if len(args) >= 2 else [] + ) + + # Collect grad_fns from the autograd.grad inputs tensors to use as stop points. + # For non-leaf tensors: we stop at their grad_fn + # For leaf tensors (requires_grad=True, grad_fn=None): we don't add anything here, + # but this is fine because their AccumulateGrad is created during fake tensor + # tracing and is not in external_grad_fns, so it won't trigger a false positive. + inputs_grad_fns: set[torch.autograd.graph.Node] = set() + for tensor, _ in inputs_with_sources: + if isinstance(tensor, torch.Tensor) and tensor.grad_fn is not None: + inputs_grad_fns.add(tensor.grad_fn) + + # Collect all consumed grad_fns that are reachable from outputs, stopping at inputs. + # + # Note: Do not try to "optimize" by only checking inputs in the `inputs` arg. + # Without guarding on the autograd graph, we can't distinguish: + # Case 1: x, y are independent leaves -> OK, y's path not consumed + # Case 2: y = x * 2 (y.grad_fn external) -> BAD, we hit external grad_fn + # Since the same compiled code could be called with either, we must check + # ALL graph inputs for external grad_fns. + consumed_grad_fns = collect_reachable_grad_fns( + outputs_with_sources, stop_at=inputs_grad_fns + ) + + # Check if any graph input's grad_fn is in the consumed set. + # If so, autograd.grad would need to traverse through external autograd nodes, + # which we cannot trace. (If a graph input is also an autograd.grad input, + # its grad_fn is already excluded from consumed_grad_fns via stop_at.) + external_in_consumed = consumed_grad_fns & external_grad_fns + + if external_in_consumed: + sources = [ + grad_fn_to_source[gf] + for gf in external_in_consumed + if gf in grad_fn_to_source + ] + context = f"inputs with external grad_fn: {sources}" if sources else "" + unimplemented( + gb_type="autograd.grad with external grad_fn", + context=context, + explanation=( + "torch.autograd.grad() cannot trace through the autograd graph because " + "it's output depends on a tensor that was created outside " + "the compiled region and has a grad_fn attached. The autograd graph " + "extends beyond the compiled region boundary, which Dynamo cannot trace." + ), + hints=[ + "If you don't need gradients to flow back to the original tensor outside " + "the compiled region, detach the input: `tensor.detach().requires_grad_(True)`.", + "Otherwise, move the autograd.grad() call outside the compiled region.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # Track consumed grad_fns for later validation + # (to detect returning tensors whose grad_fn was consumed by autograd.grad) + # Skip if retain_graph=True or create_graph=True since the graph is not + # consumed in those cases and can be traversed again. + retain_graph = kwargs.get("retain_graph") + create_graph = kwargs.get("create_graph") + graph_preserved = ( + isinstance(retain_graph, ConstantVariable) + and retain_graph.value is True + ) or ( + isinstance(create_graph, ConstantVariable) + and create_graph.value is True + ) + if not graph_preserved: + # Filter out AccumulateGrad nodes - they're never actually "consumed" + # by autograd. They just accumulate gradients into leaf.grad and can + # be traversed multiple times without issues. + non_leaf_consumed = { + gf + for gf in consumed_grad_fns + if type(gf).__name__ != "AccumulateGrad" + } + + # Check for double-consumption: if any grad_fn was already consumed + # by a previous autograd.grad, that's an error. + already_consumed = tx.output.autograd_grad_consumed_grad_fns + double_consumed = non_leaf_consumed & already_consumed + if double_consumed: + unimplemented( + gb_type="autograd.grad with already consumed grad_fn", + context=f"double consumed grad_fns: {len(double_consumed)}", + explanation=( + "torch.autograd.grad() is trying to consume grad_fns that were " + "already consumed by a previous autograd.grad() call. This would " + "cause 'backward through graph a second time' errors at runtime." + ), + hints=[ + "Use retain_graph=True in the first autograd.grad() call if you " + "need to compute gradients through the same graph multiple times.", + ], + ) + tx.output.autograd_grad_consumed_grad_fns.update(non_leaf_consumed) + + # Convert dict inputs to tuple for the FX graph. The engine + # always operates on flat tuples; we reconstruct the dict after. + inputs_var = args[1] if len(args) >= 2 else kwargs.get("inputs") + if isinstance(inputs_var, ConstDictVariable): + inputs_as_tuple = TupleVariable(list(inputs_var.items.values())) + if len(args) >= 2: + args = (args[0], inputs_as_tuple, *args[2:]) + else: + kwargs = {**kwargs, "inputs": inputs_as_tuple} + + with ( + torch.fx.traceback.preserve_node_meta(), + torch.fx.traceback._set_autograd_backward(), + ): + proxy = tx.output.create_proxy( + "call_function", + torch.autograd.grad, + *proxy_args_kwargs(args, kwargs), + ) + result = wrap_fx_proxy(tx=tx, proxy=proxy) + + if isinstance(inputs_var, ConstDictVariable): + if not isinstance(result, BaseListVariable): + raise AssertionError( + f"Expected BaseListVariable from autograd.grad with dict inputs, " + f"got {type(result)}" + ) + items: dict[VariableTracker, VariableTracker] = dict( + zip( + inputs_var.items.keys(), + result.items, + strict=True, + ) + ) + return ConstDictVariable(items) + return result + + @register(torch._functorch.eager_transforms._autograd_grad) + def handle_functorch_autograd_grad( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + """Graph-break when closure-captured tensors lose their grad_fn. + + NOTE [Detecting lost autograd linkage in closure-captured tensors] + + Functorch transforms (vjp, grad, jacrev) return closures that capture + tensors with grad_fn. When such a closure is compiled separately, those + tensors become graph placeholders whose FakeTensors lose grad_fn, + causing _autograd_grad to silently return zeros. + + _collect_placeholder_nodes gathers placeholder nodes from the + outputs/inputs args. For each, we compare grapharg.example (the real + tensor, retains grad_fn) against example_value (FakeTensor, grad_fn + is None). A mismatch means autograd linkage was lost, so we + graph-break. + + This is a pre-check only: kwargs (retain_graph, create_graph, + grad_outputs) don't affect linkage detection and are handled by + the default proxy path when this returns None. + """ + outputs_var = args[0] if len(args) >= 1 else None + inputs_var = args[1] if len(args) >= 2 else None + + if outputs_var is None or inputs_var is None: + return None + + output_placeholder_nodes = _collect_placeholder_nodes(outputs_var) + input_placeholder_nodes = _collect_placeholder_nodes(inputs_var) + + if output_placeholder_nodes and input_placeholder_nodes: + for node in output_placeholder_nodes: + fake = node.meta.get("example_value") + grapharg = node.meta.get("grapharg") + if ( + grapharg is not None + and isinstance(fake, torch.Tensor) + and fake.grad_fn is None + ): + real = grapharg.example + if isinstance(real, torch.Tensor) and real.grad_fn is not None: + unimplemented( + gb_type="_autograd_grad with lost grad_fn linkage", + context="outputs lost autograd linkage during tracing", + explanation=( + "_autograd_grad() received tensors whose grad_fn " + "was lost during tracing - this silently produces " + "zero gradients." + ), + hints=[ + "Compile the full transform instead of the returned " + "closure: torch.compile(lambda x: torch.func.vjp(f, x))", + *graph_break_hints.SUPPORTABLE, + ], + ) + return None + + return handlers + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> "VariableTracker": + source = self.source and AttrSource(self.source, name) + try: + member = getattr(self.value, name) + except AttributeError: + raise_observed_exception(AttributeError, tx) + raise + + if isinstance( + member, (torch._ops.OpOverloadPacket, torch._ops.OpOverload) + ) and torch._dynamo.trace_rules.is_aten_op_or_tensor_method(member): + return TorchInGraphFunctionVariable(member, source=source) + return variables.GetAttrVariable(self, name, source=source) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + from . import SymNodeVariable + from .builder import wrap_fx_proxy + + if self.kind == AllowInGraphKind.NONSTRICT_TRACE: + return self._call_nonstrict_traceable_function(tx, args, kwargs) + + if self.kind == AllowInGraphKind.LEAF_FUNCTION: + return self._call_leaf_function(tx, args, kwargs) + + if self.torch_function_override_enabled(tx, args, kwargs): + return dispatch_torch_function(tx, self, args, kwargs) + + if self.can_constant_fold_through() and check_unspec_or_constant_args( + args, kwargs + ): + # constant fold functions need to be guarded. + if self.value in constant_fold_functions_need_guards: + if self.source is None: + raise AssertionError( + "Expected source to be set for constant fold function needing guards" + ) + source = CallFunctionNoArgsSource(self.source) + install_guard(source.make_guard(GuardBuilder.EQUALS_MATCH)) + # constant fold + try: + return VariableTracker.build( + tx, + self.as_python_constant()( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ), + ) + except (OverflowError, TypeError, ValueError) as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + + if self.is_tensor_method(): + name = self.value.__name__ + # Guard against inplace view op on input tensor (not supported) + if args and args[0].is_tensor(): + tensor_var = args[0] + # Check if input tensor and inplace_view op specifically + if tensor_var.source is not None and hasattr(torch.ops.aten, name): + fn = getattr(torch.ops.aten, name) + if ( + hasattr(fn, "overloads") + and hasattr(fn, fn.overloads()[0]) + and torch.Tag.inplace_view + in getattr(fn, fn.overloads()[0]).tags + ): + unimplemented( + gb_type="Inplace op on input tensor", + context="", + explanation=f"Attempted to trace an inplace view op on input tensor {typestr(self.value)}.", + hints=[ + *graph_break_hints.SUPPORTABLE, + "Ensure you do not modify input tensor in place.", + ], + ) + return self.call_tensor_method(tx, list(args), kwargs) + + special_handler = self._get_handlers().get(self.value) + if special_handler: + result = special_handler(self, tx, *args, **kwargs) + if result: + return result + + any_symints_or_symfloats = any(isinstance(x, SymNodeVariable) for x in args) + + all_ints_or_floats = all( + isinstance(x, SymNodeVariable) or x.is_python_constant() for x in args + ) + # Intentional abstraction violation: when tensorify is enabled, + # skip this graph break. Scalar-only bin_ops on SymInt/SymFloat + # args are valid symbolic arithmetic that Dynamo can trace. + # The tensorify pass (in AOTAutograd) will convert SymFloat + # scalar ops to tensor ops downstream; SymInt ops flow through + # as symbolic expressions. + if ( + getattr(self.value, "__module__", "") == "torch" + and self.value.__name__ in bin_ops + and any_symints_or_symfloats + and all_ints_or_floats + and not _is_tensorify_enabled() + ): + msg = f"""\ +Calling {str(self.value)} on only torch.SymInt arguments is not yet supported. +To support this behavior, we need to allow const-propping tensors that store symint data. +For now, dynamo will explicitly graph break when it encounters user code with this behavior. +""" + log.warning(msg) + unimplemented( + gb_type="Attempted to call torch in-graph function on only torch.SymInt arguments", + context=f"fn={self.value}, args={args}, kwargs={kwargs}", + explanation=( + f"Attempted to call {str(self.value)} (that should be put in the FX graph) on only torch.SymInt arguments. " + "Dynamo does not support this." + ), + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + # TODO(voz): Replace w/ dynamic shape rewrite table. + # Ideally, we would be able to do this at ctor time, but alas we need a combination + # of value + args to determine this. + fn_ = self.value + if any_symints_or_symfloats: + torch_sym_op = f"_sym_{self.value.__name__}" + if getattr(self.value, "__module__", None) == "math" and hasattr( + torch, torch_sym_op + ): + fn_ = getattr(torch, torch_sym_op) + + # TODO for each of the following check on `out=` or `requires_grad=` + # variant torch ops, the original function could come from a user + # defined `@allow_in_graph` function as well, which doesn't have the + # same semantics as the torch ops. + + # Calling fake tensor propagation can mutate the out= tensor in + # tx.output.tracked_fakes. tracked_fakes are used to apply + # symbolic_shape guards. Mutating them destroys the information + # prior to tracing, which is essential for creating right + # guards. So save the shape now, and check later if it has + # changed. If it has, graph break. + saved_out_shapes = None + out_kwarg_vt = None + if "out" in kwargs: + out_kwarg_vt = kwargs["out"] + + # e.g., out=(t1, t2, ...) + if isinstance(out_kwarg_vt, (TupleVariable, ListVariable)): + saved_out_shapes = [] + for vt in out_kwarg_vt.items: + if vt.is_tensor(): + shape = vt.as_proxy().node.meta["example_value"].shape + else: + shape = None + saved_out_shapes.append(shape) + + # e.g., out=output_tensor + if out_kwarg_vt.is_tensor(): + saved_out_shapes = ( + out_kwarg_vt.as_proxy().node.meta["example_value"].shape + ) + + ctx = nullcontext + if fn_ in ops_consuming_unbacked_scalars: + if tx.fake_mode and tx.fake_mode.shape_env: + ctx = tx.fake_mode.shape_env.ignore_fresh_unbacked_symbols + + with ctx(): + tensor_variable = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + fn_, + *proxy_args_kwargs(args, kwargs), + ), + ) + + # Handle e.g., `torch.ones(10, requires_grad=True)` + if ( + tensor_variable.is_tensor() + and "requires_grad" in kwargs + and kwargs["requires_grad"].as_python_constant() + ): + unimplemented( + gb_type="Attempted to use tensor creation function with requires_grad=True", + context=f"fn={self.value}, args={args}, kwargs={kwargs}", + explanation="Dynamo does not support this.", + hints=[ + "Create the tensor outside the compiled region.", + "Do not set `requires_grad=True`.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # Handle e.g., `torch.add(a, b, out=result)` + if saved_out_shapes is not None: + # out variants of torch operators like torch.sort and torch.sigmoid + # mutate the tensors in the out field. + # + # However, it's non-trivial to update all references of the old + # `TensorVariable` to the new one returned (`result_var`), so we + # take the conservative approach to graph break on size changes, and + # assume other cases can fall through soundly. + # + # Note that although these tensor variables would hold different + # proxies, the in-place mutation semantics is preserved in the FX + # graph, so we won't have correctness issues. + if isinstance(saved_out_shapes, list): + for out_tensor_vt, saved_out_shape in zip( + out_kwarg_vt.items, # type: ignore[union-attr] + saved_out_shapes, + ): + if saved_out_shape is None: + # This should be extremely rare, but it's kept for now + # until we invest in enforcing the `out=` kwarg for only + # torch methods. + continue + + if not out_tensor_vt.is_tensor(): + raise AssertionError( + "Expected out= list element to be a tensor" + ) + fake_out = out_tensor_vt.proxy.node.meta["example_value"] + if saved_out_shape != fake_out.shape: + # It's hard to get out variants with resizing on graph inputs work + # properly across dynamo/aot/inductor, just fall back. + unimplemented( + gb_type="Shape mismatch with out= list of tensor variants", + context=f"fn={self.value}, args={args}, kwargs={kwargs}", + explanation=( + f"Shape mismatch when calling {self.value} with `out=`. " + f"Provided `out=` shape: {saved_out_shape}. Actual shape: {fake_out.shape}." + ), + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + if not _is_supported_out_tensor_layout( + fake_out, false_if_dde=False + ): + # It's difficult to handle strides correctly in functionalization + # when calling an out= op with a non-contiguous out argument + unimplemented( + gb_type="Attempted to call op with non-contiguous `out=` list of tensors", + context=f"self.value={self.value}, args={args}, kwargs={kwargs}", + explanation="Dynamo does not support this.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + else: + if out_kwarg_vt is None: + raise AssertionError("Expected out= kwarg to be set") + if not out_kwarg_vt.is_tensor(): + raise AssertionError("Expected out= kwarg to be a tensor") + if "example_value" not in out_kwarg_vt.as_proxy().node.meta: + raise AssertionError( + "Expected out= kwarg proxy node to have example_value metadata" + ) + fake_out = out_kwarg_vt.as_proxy().node.meta["example_value"] + if saved_out_shapes != fake_out.shape: + # It's hard to get out variants with resizing on graph inputs work + # properly across dynamo/aot/inductor, just fall back. + unimplemented( + gb_type="Shape mismatch with out= tensor variant", + context=f"fn={self.value}, args={args}, kwargs={kwargs}", + explanation=( + f"Shape mismatch when calling {self.value} with `out=`. " + f"Provided `out=` shape: {saved_out_shapes}. Actual shape: {fake_out.shape}." + ), + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + if not _is_supported_out_tensor_layout(fake_out, false_if_dde=True): + # It's difficult to handle strides correctly in functionalization + # when calling an out= op with a non-contiguous out argument + unimplemented( + gb_type="Attempted to call op with non-contiguous `out=` tensor", + context=f"self.value={self.value}, args={args}, kwargs={kwargs}", + explanation="Dynamo does not support this.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + return tensor_variable + + def _call_nonstrict_traceable_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: "dict[str, VariableTracker]", + ) -> VariableTracker: + from torch._dynamo.utils import _make_inlined + from torch._higher_order_ops.flat_apply import ( + flat_apply, + is_graphable_type, + is_valid_output, + to_graphable, + ) + from torch._higher_order_ops.invoke_leaf_function import _LeafCallable + from torch._subclasses.fake_tensor import fake_tensor_tls + from torch.utils._pytree import tree_flatten + + from .base import AsPythonConstantNotImplementedError + from .builder import SourcelessBuilder, wrap_fx_proxy + + # 1. Convert `args, kwargs` into pytree-flattened proxy forms. + # + # Rather than reconstructing `args, kwargs` into python objects and + # then tree_flatten them, we just let Dynamo symbolically interpret + # `tree_flatten((args, kwargs))`. This saves us from having to + # worry about the reconstruction logic, side effects, and guards. + args_with_states, kwargs_with_states = self._extract_nn_module_states( + tx, args, kwargs + ) + flat_args_vts, input_spec_vt = unpack_iterable( + tx, + _make_inlined(tx, tree_flatten)( + VariableTracker.build(tx, (args_with_states, kwargs_with_states)) + ), + ) + if not isinstance(flat_args_vts, ListVariable): + raise AssertionError( + f"Expected flat_args_vts to be a ListVariable, got {type(flat_args_vts)}" + ) + + # Handle the case when the input contains a non-graphable type. + for flat_arg_vt in flat_args_vts.items: + arg_type = flat_arg_vt.python_type() + if not is_graphable_type(arg_type): + type_name = flat_arg_vt.python_type().__qualname__ + unimplemented( + gb_type="Invalid input type for nonstrict_trace-ed function", + context=f"Encountered input of type <{type_name}>.", + explanation=( + "For `nonstrict_trace`-ed functions, only basic types (e.g., torch.Tensor, int, float) " + "or pytree containers of those are allowed as inputs. The provided argument contains " + "an unsupported type." + ), + hints=[ + "Use one of the following to register the type with pytree:\n" + "* `torch.utils._pytree.register_constant`\n" + "* `torch.utils._pytree.register_dataclass`\n" + "* `torch.utils._pytree.register_pytree_node`", + ], + ) + + # Since we checked with `is_graphable` above, `as_proxy` on the + # flat_arg VT should always work. + proxified_flat_args = [ + flat_arg_vt.as_proxy() for flat_arg_vt in flat_args_vts.items + ] + + # The downstream `flat_apply` call requires the input spec; however, + # the spec not a graphable type, so we still have to reconstruct it + # into a python object, and store it as a constant attribute on the + # fx graph. + try: + input_spec = input_spec_vt.as_python_constant() + except AsPythonConstantNotImplementedError as e: + typ = e.vt.python_type() + type_name = typ.__qualname__ + import torch.utils._pytree as pytree + + if pytree.is_constant_class(typ): + unimplemented( + gb_type="Input marked with `pytree.register_constant` constructed in the `torch.compile` region", + context=f"Input={input_spec_vt}, offending type <{type_name}>.", + explanation=( + "Calling a `nonstrict_trace`-ed function with an input that contains an object " + f"of type <{type_name}>, which was marked with `pytree.register_constant`. However, the object " + "was constructed _inside_ the `torch.compile` region. This is not supported." + ), + hints=[ + "Construct the object _outside_ the `torch.compile` region, or submit an issue to GitHub.", + *graph_break_hints.SUPPORTABLE, + ], + from_exc=e, + ) + else: + unimplemented( + gb_type="Invalid use of pytree_flatten with nonstrict_trace-ed function", + context=f"Input={input_spec_vt}, offending type <{type_name}>.", + explanation=( + "Calling a `nonstrict_trace`-ed function where one of the inputs has been registered " + f"with a `pytree_flatten` that places an object of type <{type_name}> into the context." + ), + hints=[ + "Modifying the `pytree_flatten` to avoid placing the object into the context.", + f"Apply one of the following to <{type_name}>:\n" + "* `torch.utils._pytree.register_constant`\n" + "* `torch.utils._pytree.register_dataclass`\n" + "* `torch.utils._pytree.register_pytree_node`", + *graph_break_hints.SUPPORTABLE, + ], + from_exc=e, + ) + + fn = self.value + + def patched_fn( + *args: VariableTracker, **kwargs: VariableTracker + ) -> VariableTracker: + # This enables reads to global/captured tensors, and we'll just + # treat them as constants in the graph. Note that after + # AOTDispatcher, this logic would disappear. + old_val = fake_tensor_tls.allow_non_fake_inputs_override + fake_tensor_tls.allow_non_fake_inputs_override = True + try: + res = fn(*args, **kwargs) + finally: # reset even when `fn` raises + fake_tensor_tls.allow_non_fake_inputs_override = old_val + return res + + f_callable = _LeafCallable(patched_fn) + + f_callable_proxy = tx.output.register_static_attr_and_return_proxy( + f"{fn.__name__}_callable", f_callable + ) + input_spec_proxy = tx.output.register_static_attr_and_return_proxy( + fn.__name__ + "_input_spec", + # pyrefly: ignore [unbound-name] + input_spec, + ) + f_callable_proxy.node.type = type(f_callable) + # pyrefly: ignore [unbound-name] + input_spec_proxy.node.type = type(input_spec) + all_args = (f_callable_proxy, input_spec_proxy, *proxified_flat_args) + + # 2. Create a proxy call to `flat_apply`, then fake-tensor propagate + # the call and wrap output into a VariableTracker. + + # What's going on here? The output of the nonstrict-traced function must + # be something we can put into the graph. This means it has to be Tuple, + # int, str, etc or lists/tuples of those (or lists of lists of those, + # etc). So by default we don't handle PyTree-able outputs. + + # To handle PyTree-able outputs we flatten the output to a flattened + # list of graph types and then trace the unflattening into the graph. + captured_spec: TreeSpec | None = None + + def flat_apply_capture(*args: Any) -> list[object]: + nonlocal captured_spec + out = flat_apply(*args, checked_output=False) + # Output is handled similar to flat_apply input but reverse by + # tree_flattening the output and trace the unflattening. Note that + # wrapped functions must return the same pytree structure every time + # they're called. + flat_out, spec = to_graphable(out) + if captured_spec is None: + captured_spec = spec + else: + if captured_spec != spec: + raise AssertionError( + "Error: nonstrict-traced functions must return the same " + f"output shape every time. got {spec!r} vs but expected {captured_spec!r}" + ) + if not is_valid_output(flat_out): + raise AssertionError( + "Nonstrict-traced function returned invalid output" + ) + return flat_out + + proxy = tx.output.create_proxy( + "call_function", flat_apply_capture, all_args, {} + ) + + # Instead of calling tree_unflatten at runtime, symbolically trace it + # just like we did for tree_flatten on inputs. This lets Dynamo + # capture the unflatten into the FX graph as well. + + # Build VTs representing (flat_output_list, out_spec) + try: + proxy_list_vt = wrap_fx_proxy(tx, proxy) + except ( + # From `handle_traced_output`. + torch._dynamo.exc.Unsupported, + # From `flat_apply` assert on output type. + torch._dynamo.exc.TorchRuntimeError, + # From fake tensor eval in _get_fake_value_impl. + torch._dynamo.exc.FakeTensorObservedException, + ): + unimplemented( + gb_type="Unsupported output type for nonstrict_trace-ed function", + context=f"Function: {fn.__name__}", + explanation=( + "For `nonstrict_trace`-ed functions, only basic types (e.g., torch.Tensor, int, list)" + " are allowed as output. The result of this call contains an unsupported type." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + # pyrefly error: why doesn't it recognize unimplemented() as NoReturn? + raise AssertionError("unreachable") # noqa: B904 + + if captured_spec is None: + raise AssertionError("captured_spec was not set during nonstrict trace") + out_spec_vt = VariableTracker.build(tx, captured_spec) + + # Reuse the same pattern used above for tree_flatten: call the python + # function through Dynamo so it symbolically interprets it. + out_vt = SourcelessBuilder.create(tx, _pytree.tree_unflatten).call_function( + tx, [proxy_list_vt, out_spec_vt], {} + ) + + return out_vt + + def _extract_nn_module_states( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> tuple[VariableTracker, VariableTracker]: + """ + Extract nn.Module states from arguments for leaf function invocation. + + Replaces nn.Module arguments with LeafModuleState objects containing + the module's index (for later retrieval), parameters, and buffers. + """ + import torch.utils._pytree as pytree + from torch._dynamo.graph_bytecode_inputs import register_user_object + from torch._dynamo.utils import _make_inlined + from torch._higher_order_ops.invoke_leaf_function import ( + convert_modules_to_states, + ) + + from .nn_module import NNModuleVariable, UnspecializedNNModuleVariable + + def is_module_variable( + var: VariableTracker, + ) -> TypeIs[Union["NNModuleVariable", "UnspecializedNNModuleVariable"]]: + return isinstance(var, (NNModuleVariable, UnspecializedNNModuleVariable)) + + flat_args_var, tree_spec_var = unpack_iterable( + tx, + _make_inlined(tx, pytree.tree_flatten)( + VariableTracker.build(tx, (args, kwargs)) + ), + ) + + module_to_index: dict[int, int] = {} + for arg in unpack_iterable(tx, flat_args_var): + if is_module_variable(arg): + if arg.source is None: + unimplemented( + gb_type="leaf_function: nn.Module argument without source", + context=f"module type: {type(arg.value).__name__}", + explanation=( + "leaf_function received an nn.Module argument that cannot be " + "traced back to its origin. This typically happens when the " + "module is created dynamically inside the compiled region." + ), + hints=[ + "Ensure the nn.Module is created outside the compiled function " + "and passed as an argument.", + "If the module is a class attribute, access it via self.module_name.", + ], + ) + if arg.source is None: # make linter happy + raise AssertionError("Expected arg.source to be set") + module_to_index[id(arg.value)] = register_user_object( + arg.value, arg.source + ) + + if not module_to_index: + args_var = VariableTracker.build(tx, tuple(args)) + kwargs_var = VariableTracker.build(tx, kwargs) + return args_var, kwargs_var + + module_to_index_var = VariableTracker.build(tx, module_to_index) + + result_var = _make_inlined(tx, convert_modules_to_states)( + VariableTracker.build(tx, (args, kwargs)), module_to_index_var + ) + return unpack_iterable(tx, result_var) # pyrefly: ignore [bad-return] + + def _call_leaf_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + import torch.utils._pytree as pytree + from torch._dynamo.utils import _make_inlined + from torch._higher_order_ops.invoke_leaf_function import ( + _LeafCallable, + invoke_leaf_function, + make_leaf_function_wrappers, + ) + + from .builder import wrap_fx_proxy + + decorated_fn = self.value + real_impl = decorated_fn._torchdynamo_leaf_real_fn + fake_impl = decorated_fn._torchdynamo_leaf_fake_fn + mutates_args = decorated_fn._torchdynamo_leaf_mutates_args + + if fake_impl is None: + raise ValueError( + f"leaf_function '{getattr(decorated_fn, '__name__', decorated_fn)}' " + "requires a fake implementation. Please provide one using the @.register_fake " + "decorator. See the leaf_function docstring for details." + ) + + args_with_states, kwargs_with_states = self._extract_nn_module_states( + tx, args, kwargs + ) + + flat_args_var, input_spec_var = unpack_iterable( + tx, + _make_inlined(tx, pytree.tree_flatten)( + VariableTracker.build(tx, (args_with_states, kwargs_with_states)) + ), + ) + flat_arg_proxies = [ + arg.as_proxy() for arg in unpack_iterable(tx, flat_args_var) + ] + input_spec = input_spec_var.as_python_constant() + + mutated_flat_indices = "" + if mutates_args: + from torch._higher_order_ops.invoke_leaf_function import ( + _resolve_mutated_flat_indices, + ) + + try: + mutated_flat_indices = _resolve_mutated_flat_indices( + real_impl, mutates_args, len(flat_arg_proxies), input_spec + ) + except ValueError as e: + raise UserError(UserErrorType.INVALID_INPUT, str(e)) from e + + # Single-element mutable list so the wrappers can write back the output + # TreeSpec. Read captured_out_spec[0] after the wrappers have been called. + captured_out_spec: list[pytree.TreeSpec | None] = [None] + wrapped_real_impl, wrapped_fake_impl = make_leaf_function_wrappers( + real_impl, fake_impl, captured_out_spec + ) + + real_impl_callable = _LeafCallable(wrapped_real_impl) + fake_impl_callable = _LeafCallable(wrapped_fake_impl) + hook_fn = getattr(decorated_fn, "_torchdynamo_leaf_hook_fn", None) + if hook_fn is not None: + hook_fake_fn = getattr(decorated_fn, "_torchdynamo_leaf_hook_fake_fn", None) + real_impl_callable._leaf_hook_real_fn = hook_fn # type: ignore[attr-defined] + real_impl_callable._leaf_hook_fake_fn = hook_fake_fn # type: ignore[attr-defined] + + def make_callable_proxy(name: str, spec: Any) -> Any: + proxy = tx.output.register_static_attr_and_return_proxy(name, spec) + proxy.node.type = type(spec) + return proxy + + real_impl_proxy = make_callable_proxy("real_fn", real_impl_callable) + fake_impl_proxy = make_callable_proxy("fake_fn", fake_impl_callable) + input_spec_proxy = make_callable_proxy("input_spec", input_spec) + + invoke_args = ( + real_impl_proxy, + fake_impl_proxy, + input_spec_proxy, + mutated_flat_indices, + *flat_arg_proxies, + ) + result_proxy = tx.output.create_proxy( + "call_function", invoke_leaf_function, invoke_args, {} + ) + + flat_output_vt = wrap_fx_proxy(tx, result_proxy) + + if captured_out_spec[0] is None: + raise AssertionError( + "Output spec was not captured during fake tensor propagation. " + "This should not happen - please report a bug." + ) + out_spec_vt = VariableTracker.build(tx, captured_out_spec[0]) + return _make_inlined(tx, _pytree.tree_unflatten)(flat_output_vt, out_spec_vt) + + def _call_ntuple( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """inline behavior of torch.nn.modules.utils._ntuple""" + if self.value is torch.nn.modules.utils._ntuple: + count = args[0].as_python_constant() + else: + count = self.value.__closure__[0].cell_contents + if not isinstance(count, int): + raise AssertionError( + f"Expected count to be an int in _ntuple, got {type(count)}" + ) + if kwargs: + raise AssertionError(f"_ntuple expects no kwargs, got {len(kwargs)}") + + def handle_ntuple(value: VariableTracker) -> VariableTracker: + if vt_is_iterable(value): + return variables.TupleVariable(unpack_iterable(tx, value)) + elif value.is_python_constant(): + # constant prop through it + return VariableTracker.build( + tx, + torch.nn.modules.utils._ntuple(count)(value.as_python_constant()), + ) + else: + unimplemented( + gb_type="Attempted to use `torch.nn.modules.utils._ntuple` with unsupported argument type", + context=f"value={value}", + explanation="Dynamo does not support this.", + hints=[ + "Change use of _ntuple with argument as constant or tensor.", + ], + ) + + if self.value is torch.nn.modules.utils._ntuple: + return variables.LambdaVariable(handle_ntuple) + else: + return handle_ntuple(args[0]) + + @classmethod + def call_nn_parameter( + cls, + tx: "InstructionTranslatorBase", + data: Any | None = None, + requires_grad: bool = True, + ) -> VariableTracker: + """A call to torch.nn.Parameter() gets lifted to before the graph""" + if tx.export: + unimplemented( + gb_type="Attempted to use `torch.nn.Parameter()` with export", + context="", + explanation="Dynamo does not support this.", + hints=[ + "Do not use `torch.nn.Parameter()` with export.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + if isinstance(requires_grad, variables.VariableTracker): + try: + requires_grad = requires_grad.as_python_constant() + except NotImplementedError: + unimplemented( + gb_type="non-constant `requires_grad` argument to `torch.nn.Parameter`", + context=f"requires_grad={requires_grad}", + explanation="Dynamo does not support this.", + hints=[ + "Change `requires_grad` to be a bool.", + *graph_break_hints.USER_ERROR, + ], + ) + + if data is None or not data.is_tensor(): + unimplemented( + gb_type="`torch.nn.Parameter()` with unsupported data type", + context=f"data={data}", + explanation="Called `torch.nn.Parameter()` with non-Tensor argument.", + hints=[ + "Ensure the argument to `torch.nn.Parameter()` is a `torch.Tensor`.", + *graph_break_hints.USER_ERROR, + ], + ) + + # this results in cleaner graphs, but only works for inputs + if data.source: + return cls._nn_param_via_prefix_insert(tx, data, requires_grad) + + if config.graph_break_on_nn_param_ctor: + # Need user to manually move since we cannot + unimplemented( + gb_type="Attempted to use `torch.nn.Parameter()` constructor with Dynamo", + context="", + explanation="Dynamo does not support this", + hints=[ + "Try to construct `torch.nn.Parameter()` outside the compiled region.", + "If this is not possible, turn `graph_break_on_nn_param_ctor` off", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # TODO[@lucaskabela]: Remove the behavior below since it is deprecated + if isinstance( + data, + TensorWithTFOverrideVariable, + ) or is_traceable_wrapper_subclass_type(data.class_type): + unimplemented( + gb_type="Attempted to use torch.nn.Parameter constructor with tensor subclass", + context=str(data), + explanation="Dynamo does not support this.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + if not can_convert_to_tracable_parameter(): + unimplemented( + gb_type="`torch.nn.Parameter`: cannot convert to traceable tracable", + context="", + explanation="convert_tracable_parameter is set to False.", + hints=[ + "Check usage of context manager: do_not_convert_to_tracable_parameter", + *graph_break_hints.DIFFICULT, + ], + ) + + try: + shape = tuple(data.tp_getattro_impl(tx, "shape").as_python_constant()) + dtype = data.tp_getattro_impl(tx, "dtype").as_python_constant() + device = data.tp_getattro_impl(tx, "device").as_python_constant() + except NotImplementedError as e: + unimplemented( + gb_type="`torch.nn.Parameter` with non-constant Tensor attributes", + context=f"data={data}", + explanation="Dynamo does not support this.", + hints=[ + "Ensure the Tensor argument's shape, dtype, and device are correct.", + *graph_break_hints.USER_ERROR, + ], + from_exc=e, + ) + + placeholder = tx.output.synthetic_graph_input( + new_parameter_placeholder, + (shape, dtype, device, requires_grad), + ) + if data.requires_grad: + data = data.call_method(tx, "detach", [], {}) + + from .builder import wrap_fx_proxy + + result = wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + tracable_create_parameter, + (data.as_proxy(), placeholder.as_proxy()), + {}, + ), + # In reconstruct() we should use the original parameter. The one + # returned by the graph will be an alias. + source=placeholder.source, + ) + if not result.is_tensor(): + raise AssertionError( + "Expected result of traceable_create_parameter to be a tensor" + ) + result.class_type = torch.nn.Parameter # type: ignore[union-attr] + + # TODO(jansel/bdhirsh) - There is some issue with + # tracable_create_parameter. It does not seem to use the right + # grad_enabled. Since this is parameter, we can just override the + # has_grad_fn field to False to workaround the issue. + result.has_grad_fn = False # type: ignore[union-attr] + + # Register this parameter as a leaf tensor for backward() auto-detection. + # When backward() is called without inputs, we need to find all leaf tensors, + # including those created in-graph like nn.Parameter. + tx.output.leaf_var_creation_order.append(result) + + # TODO(jansel): if the new param falls out of scope, currently it won't get freed until + # the end of the graph. We should fix this. + return result + + @staticmethod + def _nn_param_via_prefix_insert( + tx: "InstructionTranslatorBase", data: Any, requires_grad: bool + ) -> VariableTracker: + # Alternate version if we have a .source + varname = tx.output.new_var() + + # construct the nn.Parameter before the graph save it to varname + if tx.output.root_tx is None: + raise AssertionError("Expected tx.output.root_tx to be set") + cg = PyCodegen(tx.output.root_tx) + cg.add_push_null(lambda: cg.load_import_from("torch.nn", "Parameter")) + cg(data.source) + cg(VariableTracker.build(tx, requires_grad)) + cg.call_function(2, False) + cg.store(varname) + tx.output.pregraph_bytecode.extend(cg.get_instructions()) + + data_node = data.as_proxy().node + if data_node.op not in ("placeholder", "get_attr"): + unimplemented( + gb_type="Unexpected type of data placeholder op for parameter construction", + context=f"data_node.op={data_node.op}", + explanation="Data node op should be placeholder or get_attr.", + hints=[ + *graph_break_hints.DIFFICULT, + ], + ) + + # add the newly constructed nn.Parameter as a graph input + source = SyntheticLocalSource(varname) + example_value = torch.nn.Parameter( + tx.output.example_value_from_input_node(data.as_proxy().node), + requires_grad=requires_grad, + ) + result = VariableTracker.build(tx, example_value, source) + # Realize the VT because we will delete the guards on it in the next line. + result = result.realize() + # No need to guard on this since we already guarded on `data`. + # These guards would fail since varname doesn't exist until after the function starts + TracingContext.get().guards_context.dynamo_guards.remove_guards_with_source( + source + ) + return result + + def call_tensor_method( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return args[0].call_method(tx, self.get_function().__name__, args[1:], kwargs) + + def is_tensor_method(self) -> bool: + from ..trace_rules import get_tensor_method + + return ( + inspect.ismethoddescriptor(self.get_function()) + and hasattr(self.get_function(), "__objclass__") + # pyrefly: ignore[missing-attribute] + and self.get_function().__objclass__ == torch._C.TensorBase + ) or self.get_function() in get_tensor_method() + + def torch_function_override_enabled( + self, + tx: "InstructionTranslatorBase", + args: Iterable[Any], + kwargs: dict[str, Any], + ) -> bool: + return ( + self.get_function() in get_overridable_functions() + or isinstance( + self.get_function(), + (torch._ops.OpOverload, torch._ops.OpOverloadPacket), + ) + ) and can_dispatch_torch_function(tx, args, kwargs) + + +class DispatchKeySetVariable(BaseTorchVariable): + """represents torch.DispatchKeySet""" + + @staticmethod + def create(value: DispatchKeySet, **kwargs: Any) -> "DispatchKeySetVariable": + return DispatchKeySetVariable(value, **kwargs) + + @classmethod + def create_with_source( + cls, value: DispatchKeySet, source: Source + ) -> "DispatchKeySetVariable": + install_guard(source.make_guard(GuardBuilder.DISPATCH_KEY_SET_MATCH)) + return cls(value, source=source) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def is_constant_fold_method(self, name: str) -> bool: + return name == "has" + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "VariableTracker": + if self.is_constant_fold_method(name) and check_unspec_or_constant_args( + args, kwargs + ): + method = getattr(self.value, name) + return VariableTracker.build( + tx, + method( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ), + ) + elif name == "highestPriorityTypeId": + return VariableTracker.build(tx, self.value.highestPriorityTypeId()) + return super().call_method(tx, name, args, kwargs) + + +class FuncTorchInterpreterVariable(BaseTorchVariable): + """represents torch._functorch.pyfunctorch.FuncTorchInterpreter""" + + @classmethod + def create_with_source( + cls, value: Any, source: Source + ) -> "FuncTorchInterpreterVariable": + install_guard(source.make_guard(GuardBuilder.ID_MATCH)) + return cls(value, source=source) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "VariableTracker": + if name == "key": + return VariableTracker.build(tx, self.value.key()) + elif name == "process": + return tx.inline_user_function_return( + VariableTracker.build(tx, self.value.process.__func__), + [self] + args, + kwargs, + ) + elif name in ["level", "batch_size", "randomness"]: + return VariableTracker.build(tx, getattr(self.value, name)()) + elif name == "lower": + if args: + raise AssertionError(f"lower() expects no args, got {len(args)}") + if kwargs: + raise AssertionError(f"lower() expects no kwargs, got {len(kwargs)}") + return variables.TemporarilyPopInterpreterStackCtxManagerVariable.create( + tx, None + ) + return super().call_method(tx, name, args, kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch_function.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch_function.py new file mode 100644 index 0000000000000000000000000000000000000000..310866ff0725a8a5f196b18d700c43b218c9a557 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch_function.py @@ -0,0 +1,789 @@ +"""TorchDynamo support for __torch_function__ tensor subclasses. + +This module implements support for tensor subclasses with __torch_function__ overrides. +A tensor subclass instance is represented as a TensorWithTFOverrideVariable, which handles +dispatching __torch_function__ on attribute accesses, method calls, and torch API calls. + +Unsupported features: +- Triggering __torch_function__ on tensor subclass non-tensor custom attributes +- Graph breaking on mutating guardable tensor properties within a __torch_function__ context + (can cause excessive recompiles in certain cases) +- Matching exact eager behavior of ignoring __torch_function__ objects in non-tensor + argument positions of Torch API calls + +Supported features: +- Static method implementations of __torch_function__ on custom objects (triggers on torch + API calls with the object as any argument) +- Triggering __torch_function__ on torch API calls with tensor subclass arguments +- __torch_function__ calls on base tensor attribute access and method calls for tensor + subclass instances +- Matches dispatch ordering behavior of eager __torch_function__ with subclass/object + arguments in any position + +See https://docs.google.com/document/d/1WBxBSvW3NXhRp9ncmtokJloMLCtF4AYNhJaffvHe8Kw/edit#heading=h.vacn73lozd9w +for more information on the design. +""" + +import collections +import contextlib +import inspect +import operator +from collections.abc import Generator, Iterable +from types import TracebackType +from typing import Any, TYPE_CHECKING + +import torch._C +import torch.utils._pytree as pytree +from torch._guards import Source +from torch.overrides import ( + _get_overloaded_args, + get_default_nowrap_functions, + TorchFunctionMode, +) +from torch.utils._device import DeviceContext + +from .. import graph_break_hints +from ..exc import unimplemented +from ..guards import GuardBuilder, install_guard +from ..polyfills import NoEnterTorchFunctionMode +from ..source import AttrSource, GlobalSource, TorchFunctionModeStackSource, TypeSource +from ..utils import ( + class_has_getattribute, + clear_torch_function_mode_stack, + get_safe_global_name, + has_torch_function, + is_tensor_base_attr_getter, + set_torch_function_mode_stack, +) +from .base import VariableTracker +from .constant import ConstantVariable +from .ctx_manager import GenericContextWrappingVariable +from .functions import UserMethodVariable +from .lazy import LazyVariableTracker +from .lists import TupleVariable +from .tensor import TensorSubclassVariable, TensorVariable +from .user_defined import UserDefinedObjectVariable + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +bin_ops = [ + operator.pow, + operator.mul, + operator.matmul, + operator.floordiv, + operator.truediv, + operator.mod, + operator.add, + operator.lt, + operator.gt, + operator.ge, + operator.le, + operator.ne, + operator.eq, + operator.sub, + operator.ipow, + operator.imul, + operator.imatmul, + operator.ifloordiv, + operator.itruediv, + operator.imod, + operator.iadd, + operator.isub, +] + +bin_int_ops = [ + operator.and_, + operator.or_, + operator.xor, + operator.iand, + operator.ixor, + operator.ior, +] + +un_int_ops = [operator.invert] + +tensor_and_int_ops = [ + operator.lshift, + operator.rshift, + operator.ilshift, + operator.irshift, + operator.getitem, +] + +un_ops = [ + operator.abs, + operator.pos, + operator.neg, + operator.not_, # Note: this has a local scalar dense call + operator.length_hint, +] + + +banned_attrs = [ + fn.__self__.__name__ # type: ignore[attr-defined] + for fn in get_default_nowrap_functions() + if is_tensor_base_attr_getter(fn) +] + + +class TorchFunctionModeVariable(GenericContextWrappingVariable): + @staticmethod + def is_supported_torch_function_mode(ty: type[TorchFunctionMode]) -> bool: + # Supported in this sense means we can support graph breaks under the + # context. + # We are able to trace custom modes but if there are graph breaks under them + # and they have a custom __enter__/__exit__ we don't handle this for the + # same reason we don't handle generic context managers: there may be side effects + # that are now affected by executing the function across two frames instead of one + # Today we support the enter/exit of the default TorchFunctionMode as well as + # DeviceContext (which is used for set_default_device) + return issubclass(ty, (NoEnterTorchFunctionMode, DeviceContext)) or ( + not class_has_getattribute(ty) + and inspect.getattr_static(ty, "__enter__") is TorchFunctionMode.__enter__ + and inspect.getattr_static(ty, "__exit__") is TorchFunctionMode.__exit__ + ) + + def __init__( + self, + value: TorchFunctionMode | None, + source: Source | None = None, + **kwargs: Any, + ) -> None: + if value is not None: + super().__init__(value, **kwargs) + self.value = value + # needed for BC with calling enter from CM code + self.cm_obj = value # type: ignore[assignment] + self.source = source # type: ignore[assignment] + + def reconstruct(self, codegen: "PyCodegen") -> None: + # This shouldn't be called unless we have a source + if not self.source: + raise AssertionError( + "TorchFunctionModeVariable requires a source for reconstruct" + ) + self.source.reconstruct(codegen) + + def module_name(self) -> str: + return self.value.__module__ + + def fn_name(self) -> str: + return type(self.value).__name__ + + def python_type(self) -> type: + return type(self.value) + + def call_torch_function( + self, + tx: "InstructionTranslatorBase", + fn: VariableTracker, + types: TupleVariable, + args: Iterable[Any], + kwargs: dict[str, Any], + ) -> VariableTracker: + return call_torch_function( + tx, + get_torch_function_fn(tx, self), # type: ignore[arg-type] + fn, + types, + args, + kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .torch import TorchInGraphFunctionVariable + + if isinstance(self.value, NoEnterTorchFunctionMode): + return ConstantVariable.create(None) + + TorchInGraphFunctionVariable( + torch._C._push_on_torch_function_stack + ).call_function(tx, [self], {}) + return ConstantVariable.create(None) + + def exit(self, tx: "InstructionTranslatorBase", *args: Any) -> VariableTracker: + from .torch import TorchInGraphFunctionVariable + + TorchInGraphFunctionVariable(torch._C._pop_torch_function_stack).call_function( + tx, [], {} + ) + return ConstantVariable.create(None) + + def reconstruct_type(self, codegen: "PyCodegen") -> None: + ty = NoEnterTorchFunctionMode + codegen( + AttrSource( + codegen.tx.import_source(ty.__module__), + ty.__name__, + ) + ) + + def supports_graph_breaks(self) -> bool: + return True + + def exit_on_graph_break(self) -> bool: + return False + + +# Used to clear/restore the python torch function mode stack and temporarily restore it as needed +class TorchFunctionModeStackStateManager: + def __init__(self) -> None: + self.stack: list[Any] = [] + + def __enter__(self) -> None: + self.stack = torch.overrides._get_current_function_mode_stack() + clear_torch_function_mode_stack() + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + set_torch_function_mode_stack(self.stack) + self.stack = [] + + @contextlib.contextmanager + def temp_restore_stack(self) -> Generator[None, None, None]: + prev = torch.overrides._get_current_function_mode_stack() + set_torch_function_mode_stack(self.stack) + try: + yield + finally: + set_torch_function_mode_stack(prev) + + +torch_function_mode_stack_state_mgr = TorchFunctionModeStackStateManager() + + +class SymbolicTorchFunctionState: + def __init__(self, py_stack: Iterable[Any], skip_next: bool) -> None: + # This is annoyingly complicated because of how the torch function subclass + mode C API was designed + # There are two exposed C knobs here as contexts: torch._C.DisableTorchFunction and torch._C.DisableTorchFunctionSubclass + # These are their definitions: + # 1) torch._C._is_torch_function_enabled indicates that neither of the above knobs have been entered + # (if either are entered, this will be False) + # 2) torch._C._is_torch_function_mode_enabled indicates that either the torch mode stack is empty OR + # torch._C.DisableTorchFunction has been entered + # To disambiguate these and keep myself sane I added a C API to check whether all torch function + # concepts (modes and subclasses) are enabled. + # This only returns true iff we have not entered torch._C.DisableTorchFunction and allows us to separate + # the stack length from the enablement state of torch function modes. + # This is important because now if a mode is pushed while dynamo is tracing, we know whether + # or not torch function modes are enabled and whether we should trace it. + self.torch_function_subclass_enabled = torch._C._is_torch_function_enabled() + + # Mirrors PythonTorchFunctionTLS::skip_next in C++. + # Set by _skip_one_hop_torch_function, consumed by has_torch_function. + # The real TLS flag is consumed by save_global_state in + # OutputGraph.__init__ (which runs before this) and passed in here. + # On tracing failure, restore_graphstate restores the real TLS. + self.skip_next = skip_next + + # This differs from the C API of the same name + # this will only be false iff we have entered torch._C.DisableTorchFunction + # and does not take into account the mode stack length, while the C API bundles these + # two concepts + self.torch_function_mode_enabled = ( + not torch._C._is_torch_function_all_disabled() + ) + + self.cur_mode = None + + TorchFunctionModeStackVariable.reset() + + self.mode_stack: collections.deque[TorchFunctionModeVariable] = ( + collections.deque() + ) + + for i, val in enumerate(py_stack): + self.mode_stack.append( + LazyVariableTracker.create(val, source=TorchFunctionModeStackSource(i)) # type: ignore[arg-type] + ) + + def in_torch_function_mode(self) -> bool: + return len(self.mode_stack) > 0 + + def pop_torch_function_mode(self) -> TorchFunctionModeVariable: + return self.mode_stack.pop() + + def push_torch_function_mode(self, mode_var: TorchFunctionModeVariable) -> None: + self.mode_stack.append(mode_var) + + def call_torch_function_mode( + self, + tx: "InstructionTranslatorBase", + fn: VariableTracker, + types: TupleVariable, + args: Iterable[Any], + kwargs: dict[str, Any], + ) -> Any: + with self._pop_mode_for_inlining() as cur_mode: + return cur_mode.call_torch_function(tx, fn, types, args, kwargs) + + @contextlib.contextmanager + def _pop_mode_for_inlining( + self, + ) -> Generator[TorchFunctionModeVariable, None, None]: + old_mode = self.cur_mode + self.cur_mode = self.pop_torch_function_mode() # type: ignore[assignment] + try: + yield self.cur_mode # type: ignore[misc] + finally: + mode = self.cur_mode + self.cur_mode = old_mode + self.push_torch_function_mode(mode) # type: ignore[arg-type] + + +class TorchFunctionModeStackVariable(VariableTracker): + """Fake VT to use as a dummy object, indicating the presence of torch function mode stack mutation""" + + # singleton value representing the global torch function mode stack + # singleton (it exists in C++) + stack_value_singleton = object() + + # offset is used to track if we have inserted/removed a + # device context which is always placed at the bottom of the stack + # if a device context is inserted, the graph will run this mutation + # so when we want to reconstruct any other modes on the stack + # their indices should be shifted right by 1 (+1) + # Conversely, if there was a device context on the stack, and the graph + # mutates the stack to remove that context (set default device to None) + # each of the indices of other modes should be shifted left by 1 (-1) + offset = 0 + + def __init__( + self, + source: Source, + symbolic_stack: collections.deque[TorchFunctionModeVariable], + ) -> None: + self.source = source + self.symbolic_stack = symbolic_stack + + @classmethod + def reset(cls) -> None: + cls.offset = 0 + + @classmethod + def register_mutation(cls, tx: "InstructionTranslatorBase") -> None: + if cls.stack_value_singleton not in tx.output.side_effects: + var = cls( + source=Source(), + symbolic_stack=tx.symbolic_torch_function_state.mode_stack, + ) + tx.output.side_effects.track_mutable(cls.stack_value_singleton, var) + tx.output.side_effects.mutation(var) + + @classmethod + def register_device_context_insertion(cls, tx: "InstructionTranslatorBase") -> None: + stack = tx.symbolic_torch_function_state.mode_stack + if stack and cls.is_device_context(stack[0]): + return + else: + cls.offset += 1 + stack.insert( + 0, + TorchFunctionModeVariable( + None, source=TorchFunctionModeStackSource(-cls.offset) + ), + ) + + @classmethod + def clear_default_device(cls, tx: "InstructionTranslatorBase") -> None: + stack = tx.symbolic_torch_function_state.mode_stack + if stack and cls.is_device_context(stack[0]): + stack.popleft() + cls.offset -= 1 + + @staticmethod + def is_device_context(var: TorchFunctionModeVariable) -> bool: + return isinstance(var.value, DeviceContext) or var.value is None + + @classmethod + def get_mode_index(cls, ind: int) -> int: + return ind + cls.offset + + +def _get_all_args( + args: Iterable[Any], kwargs: dict[str, Any] +) -> Iterable[VariableTracker]: + return _flatten_vts(pytree.arg_tree_leaves(*args, **kwargs)) + + +def _flatten_vts(vts: Iterable[VariableTracker]) -> list[VariableTracker]: + from collections import deque + + from .dicts import ConstDictVariable + from .lists import ListVariable + + vts = deque(vts) + output = [] + + while vts: + vt = vts.popleft() + + if not vt.is_realized() and vt.peek_type() in (dict, list, tuple): # type: ignore[attr-defined] + vt.realize() + + if vt.is_realized(): + if isinstance(vt, ListVariable): + vts.extend(vt.items) + continue + elif isinstance(vt, ConstDictVariable): + vts.extend(vt.items.values()) + continue + + output.append(vt) + + return output + + +def _get_subclass_type(var: VariableTracker) -> type: + if not isinstance(var, (TensorWithTFOverrideVariable, UserDefinedObjectVariable)): + raise AssertionError(f"Unexpected type {type(var)}") + return var.python_type() + + +def _get_subclass_type_var( + tx: "InstructionTranslatorBase", var: VariableTracker +) -> VariableTracker: + if isinstance(var, TensorWithTFOverrideVariable): + return var.class_type_var(tx) + elif isinstance(var, UserDefinedObjectVariable): + source = var.source and TypeSource(var.source) + return VariableTracker.build(tx, var.python_type(), source) + else: + raise AssertionError(f"Unexpected type {type(var)}") + + +def _is_attr_overridden( + tx: "InstructionTranslatorBase", var: VariableTracker, name: str +) -> bool: + if not isinstance(var, (TensorWithTFOverrideVariable, UserDefinedObjectVariable)): + return False + import torch + + overridden = False + try: + attr_val = inspect.getattr_static(var.python_type(), name) + overridden |= attr_val != getattr(torch.Tensor, name) + except AttributeError: + pass + + return overridden + + +def call_torch_function( + tx: "InstructionTranslatorBase", + torch_function_var: VariableTracker, + fn: VariableTracker, + types: TupleVariable, + args: Iterable[Any], + kwargs: dict[str, Any], + *, + is_subclass_dispatch: bool = False, +) -> Any: + # This emulates calling __torch_function__, which has a signature + # def __torch_function__(cls, func, types, args=(), kwargs=None): + # + # Also notice the `cls` is not explicitly passed in the reference + # implementations: + # 1. https://github.com/pytorch/pytorch/blob/8d81806211bc3c0ee6c2ef235017bacf1d775a85/torch/csrc/utils/python_arg_parser.cpp#L368-L374 + # 2. https://github.com/pytorch/pytorch/blob/8d81806211bc3c0ee6c2ef235017bacf1d775a85/torch/overrides.py#L1741-L1743 + tf_args = [ + fn, + types, + VariableTracker.build(tx, tuple(args)), + VariableTracker.build(tx, kwargs), + ] + # Mirror the C++ THPModule_disable_torch_function behavior: disable + # __torch_function__ subclass dispatch during the call to prevent + # re-entrant dispatch on operations inside __torch_function__. + # Only do this for subclass dispatch, not mode dispatch. Modes need + # subclass dispatch to remain enabled because the mode's + # __torch_function__ may re-dispatch to the subclass. + tf_state = tx.symbolic_torch_function_state + old_subclass_enabled = tf_state.torch_function_subclass_enabled + if is_subclass_dispatch and old_subclass_enabled: + tf_state.torch_function_subclass_enabled = False + try: + return torch_function_var.call_function(tx, tf_args, {}) + finally: + tf_state.torch_function_subclass_enabled = old_subclass_enabled + + +def get_torch_function_fn( + tx: "InstructionTranslatorBase", vt: VariableTracker +) -> VariableTracker: + # The underlying function could be a classmethod, staticmethod, regular + # function or a function with C-implementation. It doesn't matter as long as + # they satisfy the calling convention in `call_torch_function`. + + args = [vt, VariableTracker.build(tx, "__torch_function__")] + func_vt = VariableTracker.build(tx, getattr).call_function(tx, args, {}) + return func_vt + + +def can_dispatch_torch_function( + tx: "InstructionTranslatorBase", args: Iterable[Any], kwargs: dict[str, Any] +) -> bool: + has_overridden_args = any( + has_torch_function(arg) for arg in _get_all_args(args, kwargs) + ) + tf_state = tx.symbolic_torch_function_state + return (has_overridden_args and tf_state.torch_function_subclass_enabled) or ( + tf_state.torch_function_mode_enabled and tf_state.in_torch_function_mode() + ) + + +def dispatch_torch_function( + tx: "InstructionTranslatorBase", + fn: VariableTracker, + args: Iterable[Any], + kwargs: dict[str, Any], +) -> Any: + """Gathers all args that are TensorWithTFOverrideVariable and dispatches based on the ordering in _get_overloaded_args""" + + all_args = _get_all_args(args, kwargs) + overloaded_args = _get_overloaded_args( + [arg for arg in all_args if has_torch_function(arg)], + _get_subclass_type, + ) + + types = TupleVariable([_get_subclass_type_var(tx, arg) for arg in overloaded_args]) + + if tx.symbolic_torch_function_state.in_torch_function_mode(): + res = tx.symbolic_torch_function_state.call_torch_function_mode( + tx, fn, types, args, kwargs + ) + if not res.is_constant_match(NotImplemented): + return res + + for arg in overloaded_args: + res = arg.call_torch_function( + tx, + fn, + types, + args, + kwargs, + ) + + if not res.is_constant_match(NotImplemented): + tx.output.torch_function_subclass_inlined = True + return res + + unimplemented( + gb_type="All __torch_function__ overrides returned NotImplemented due to TypeError from user code", + context=f"{fn=}, {args=}, {kwargs=}", + explanation=f"All __torch_function__ overrides for function {fn} returned NotImplemented", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + +class TensorWithTFOverrideVariable(TensorVariable): + """ + Represents a tensor subclass instance with a __torch_function__ override. + """ + + @classmethod + def from_tensor_var( + cls, + tx: "InstructionTranslatorBase", + tensor_var: VariableTracker, + class_type: type, + cls_source: Source | None, + ) -> "TensorWithTFOverrideVariable": + # [Note: __torch_function__] coerce `tensor_var` into a + # TensorWithTFOverrideVariable. In eager, this is just a type change. + import torch + + tensor_var = tensor_var.realize() + # This simulates shallow-copying the tensor object. + kwargs = dict(tensor_var.__dict__) + input_tensor_type = kwargs.pop("class_type") + if not ( + input_tensor_type in (torch.Tensor, torch.nn.Parameter) + or issubclass(input_tensor_type, torch.Tensor) + ): + raise AssertionError( + f"invalid class type {input_tensor_type} in TensorWithTFOverrideVariable.from_tensor_var" + ) + var = cls(class_type=class_type, **kwargs) + var.install_global(tx) + return var + + def install_global(self, tx: "InstructionTranslatorBase") -> None: + # stash the subclass type to rewrap an output tensor if needed + # this is needed because the actual type needs to be available + # each time the compiled artifact is run and outputs a wrapped tensor. + if self.global_mangled_class_name(tx) not in tx.output.global_scope: + # Safe because global_mangled_class_name figures it out + tx.output.install_global_unsafe( + self.global_mangled_class_name(tx), self.class_type + ) + + def python_type(self) -> type: + return self.class_type + + def class_type_var(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return TensorSubclassVariable( + self.class_type, source=GlobalSource(self.global_mangled_class_name(tx)) + ) + + def global_mangled_class_name(self, tx: "InstructionTranslatorBase") -> str: + return get_safe_global_name( + tx, f"__subclass_{self.class_type.__name__}", self.class_type + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # [Note: __torch_function__] We currently only support attributes that are defined on + # base tensors, custom attribute accesses will graph break. + import torch + + # I think only `_base` is breaking because we aren't modelling view + # relationship perfectly in some scenarios. + if name in banned_attrs: + unimplemented( + gb_type="Unsupported tensor subclass attribute access", + context=f"{name}", + explanation="`torch.compile` currently can't trace this", + hints=[ + f"Avoid accessing {name} of tensor subclass in torch.compile region", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # Handle non-overridden attributes inherited from `torch.Tensor`. + attr_is_overridden = _is_attr_overridden(tx, self, name) + if ( + hasattr(torch.Tensor, name) + and not attr_is_overridden + and not inspect.ismethoddescriptor(getattr(torch.Tensor, name)) + ): + args = [self] + kwargs: dict[Any, Any] = {} + if can_dispatch_torch_function(tx, args, kwargs): + get_fn = VariableTracker.build(tx, getattr(torch.Tensor, name).__get__) + + return self.call_torch_function( + tx, + get_fn, + TupleVariable([self.class_type_var(tx)]), + args, + kwargs, + ) + else: + # `TensorVariable.tp_getattro_impl` doesn't handle user-defined + # function/attribute well, so we explicitly handle them here. + # + # TODO move this logic into `TensorVariable`, or try to merge it + # with similar logic in `UserDefinedObjectVariable`. + try: + attr = inspect.getattr_static(self.class_type, name) + except AttributeError: + pass + else: + import types + + cls_source = GlobalSource(self.global_mangled_class_name(tx)) + attr_source = AttrSource(cls_source, name) + if isinstance(attr, types.FunctionType): + install_guard(attr_source.make_guard(GuardBuilder.CLOSURE_MATCH)) + return UserMethodVariable(attr, self) + + elif isinstance(attr, property): + getter_source = AttrSource(attr_source, "fget") + getter = attr.fget + getter_var = VariableTracker.build( + tx, getter, source=getter_source, realize=True + ) + return getter_var.call_function(tx, [self], {}) + + elif isinstance(attr, classmethod): + return UserMethodVariable( + attr.__func__, self.class_type_var(tx), source=attr_source + ) + + elif attr_is_overridden: + unimplemented( + gb_type="Unsupported tensor subclass overridden attribute access", + context=f"{name}", + explanation="`torch.compile` only support tracing certain types of overridden tensor subclass attributes", + hints=[ + f"Avoid accessing {name} of tensor subclass in torch.compile region", + f"Renaming attribute `{name}` of type {self.class_type}", + *graph_break_hints.SUPPORTABLE, + ], + ) + + return super().tp_getattro_impl(tx, name) + + def call_torch_function( + self, + tx: "InstructionTranslatorBase", + fn: VariableTracker, + types: TupleVariable, + args: Iterable[Any], + kwargs: dict[str, Any], + ) -> Any: + # NOTE this assumes `__torch_function__` isn't modified during tracing. + if not hasattr(self, "torch_function_fn"): + self.torch_function_fn = get_torch_function_fn(tx, self) + + return call_torch_function( + tx, + self.torch_function_fn, + fn, + types, + args, + kwargs, + is_subclass_dispatch=True, + ) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + # This code block implements inlining the __torch_function__ override + # of `call_method`. + tf_args = [self] + list(args) + if can_dispatch_torch_function(tx, tf_args, kwargs): + import torch + + if _is_attr_overridden(tx, self, name): + unimplemented( + gb_type="Tensor subclass overridden method call", + context=f"{name}", + explanation="`torch.compile` currently can't trace this", + hints=[ + f"Avoid calling {name} of tensor subclass in torch.compile region", + f"Renaming method `{name}` of type {self.class_type}", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # [Note: __torch_function__] Currently we only support methods that are defined on tensor + # we will graph break in other cases this will need a bigger overhaul of extracting methods/comparing them for equality + # We've established with the above check that the method is not overridden, so we guard that the method is the same + # as the impl defined on tensor and retrieve it + if self.source: + source = AttrSource(AttrSource(self.source, "__class__"), name) + value = inspect.getattr_static(self.python_type(), name) + else: + source = None + value = getattr(torch.Tensor, name) + func_var = VariableTracker.build(tx, value, source) + return dispatch_torch_function(tx, func_var, tf_args, kwargs) + else: + return super().call_method(tx, name, args, kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/user_defined.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/user_defined.py new file mode 100644 index 0000000000000000000000000000000000000000..dece28d92214ea56eef31ab4538d40cbcc589bd5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/user_defined.py @@ -0,0 +1,5488 @@ +""" +This module contains variable classes for handling user-defined objects in Dynamo's tracing system. + +The key classes are: +- UserDefinedVariable: Base class for representing custom Python objects +- UserDefinedClassVariable: Handles Python class objects/types +- UserDefinedObjectVariable: Fallback class for instance objects, with support for method calls, + attribute access, and other Python object behaviors. +- Specialized subclasses for common patterns: + - UserDefinedDictVariable: For dict subclasses + - UserDefinedSetVariable: For set subclasses + - UserDefinedTupleVariable: For tuple subclasses + - UserDefinedExceptionObjectVariable: For exception subclasses + - FrozenDataClassVariable: Special handling of frozen dataclasses + - MutableMappingVariable: For collections.abc.MutableMapping subclasses + +Dynamo specializes to VariableTracker subclasses like FrozenDataClassVariable if available; if no +subclass qualifies, it falls back to UserDefinedObjectVariable. + +These classes help Dynamo track and handle arbitrary Python objects during tracing, +maintaining proper semantics while enabling optimizations where possible. +""" + +import _collections # type: ignore[import-not-found] +import builtins +import collections +import contextlib +import dataclasses +import enum +import functools +import inspect +import random +import sys +import threading +import traceback +import types +import warnings +import weakref +from collections.abc import Callable, Iterable, Sequence +from typing import Any, cast, NoReturn, TYPE_CHECKING, Union +from typing_extensions import is_typeddict + +import torch._dynamo.config +import torch.nn +from torch._C._dynamo import PyNumberSlots +from torch._guards import Source, TracingContext +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import is_traceable_wrapper_subclass_type +from torch.utils._pytree import GetAttrKey, is_structseq_class + +from .. import config, graph_break_hints, polyfills, variables +from ..bytecode_transformation import create_call_function +from ..create_parameter_op import do_not_convert_to_tracable_parameter +from ..exc import ( + handle_observed_exception, + ObservedAttributeError, + ObservedKeyError, + raise_observed_exception, + raise_type_error, + unimplemented, +) +from ..graph_bytecode_inputs import get_external_object_by_index +from ..guards import GuardBuilder, install_guard +from ..source import ( + AttrSource, + CallFunctionNoArgsSource, + DictGetItemSource, + GetItemSource, + RandomValueSource, + TypeDictSource, + TypeMROSource, + TypeSource, + UnspecializedParamBufferSource, +) +from ..utils import ( + base_exception_methods, + check_constant_args, + cmp_name_to_op_mapping, + deque_iterator, + deque_methods, + deque_rev_iterator, + dict_methods, + exception_methods, + frozenset_methods, + get_custom_getattr, + has_torch_function, + is_lru_cache_wrapped_function, + is_namedtuple_cls, + is_pybind11_enum_member, + is_torch_class, + istype, + list_methods, + namedtuple_fields, + object_has_getattribute, + proxy_args_kwargs, + raise_args_mismatch, + set_methods, + tensortype_to_dtype, + tracked_repr, + tuple_methods, + unpack_iterable, + unpatched_nn_module_getattr, +) +from .base import ( + AsPythonConstantNotImplementedError, + AttrMutationKind, + GetSet, + getset_read, + Member, + Method, + MutationType, + NO_SUCH_SUBOBJ, + ValueMutationNew, + VariableTracker, +) +from .dicts import ConstDictVariable, OrderedDictVariable, pydict_check +from .hashable import HashableTracker +from .object_protocol import ( + _resolve_descriptor_get, + generic_is_true, + generic_repr, + is_nb_not_implemented, + mro_lookup, + pynumber_as_ssize_t, + pynumber_index, + type_implements_nb_slot, +) +from .sets import SetVariable + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + +try: + from torch.utils._cxx_pytree import PyTreeSpec +except ImportError: + PyTreeSpec = type(None) # type: ignore[misc, assignment] + + +_SAFE_C_SLOTS: OrderedSet[object] | None = None + + +def _safe_c_slots() -> OrderedSet[object]: + """C slot wrappers known to be safe to call at trace time. + + Covers tp_hash and tp_richcompare slots for C extension types. + Used by UDOV's hash_impl and tp_richcompare_impl MRO walks. + """ + global _SAFE_C_SLOTS + if _SAFE_C_SLOTS is None: + import datetime + import decimal + import re + + _SAFE_C_SLOTS = OrderedSet() + for tp in ( + datetime.datetime, + datetime.date, + datetime.time, + datetime.timedelta, + datetime.timezone, + decimal.Decimal, + re.Pattern, + ): + _SAFE_C_SLOTS.add(tp.__hash__) + for dunder in ("__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__"): + if hasattr(tp, dunder): + _SAFE_C_SLOTS.add(getattr(tp, dunder)) + return _SAFE_C_SLOTS + + +def _safe_c_tp_hash_funcs() -> OrderedSet[object]: + """Backward compat: returns the unified set (hash funcs are a subset).""" + return _safe_c_slots() + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.side_effects import SideEffects + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.constant import ConstantVariable + + from .lists import ListVariable, TupleVariable + + +def is_standard_setattr(val: object) -> bool: + return val in (object.__setattr__, BaseException.__setattr__) + + +def is_standard_delattr(val: object) -> bool: + return val in (object.__delattr__, BaseException.__delattr__) + + +def is_forbidden_context_manager(ctx: object) -> bool: + f_ctxs: list[Any] = [] + + # pytest >= 8.4 moved RaisesContext into _pytest.raises and renamed it to RaisesExc, + # also adding RaisesGroup for ExceptionGroup matching. Keep both old and new names + # in independent try blocks so that one missing symbol doesn't drop the others. + try: + from _pytest.raises import RaisesExc, RaisesGroup # type: ignore[attr-defined] + + f_ctxs.append(RaisesExc) + f_ctxs.append(RaisesGroup) + except ImportError: + pass + + try: + from _pytest.python_api import RaisesContext # type: ignore[attr-defined] + + f_ctxs.append(RaisesContext) + except ImportError: + pass + + try: + from _pytest.recwarn import WarningsChecker # type: ignore[attr-defined] + + f_ctxs.append(WarningsChecker) + except ImportError: + pass + + if m := sys.modules.get("torch.testing._internal.jit_utils"): + f_ctxs.append(m._AssertRaisesRegexWithHighlightContext) + + return ctx in f_ctxs + + +def is_generic_ctx_manager_cls(cls: type) -> bool: + # A class is wrapped/entered as a GenericContextWrappingVariable only when + # its __enter__/__exit__ are plain Python-function methods: GCWV.enter/exit + # take `.__func__`, which only a regular bound method has. getattr_static + # (not getattr) inspects the raw descriptor, so staticmethod/classmethod + # descriptors and C-level slots (threading.Lock, file objects) are rejected + # -- those fall back to UserDefinedObjectVariable and cleanly graph-break on + # `with` instead of raising. Used at both wrap sites (VariableBuilder for + # sourced objects and SideEffects.get_variable_cls for in-trace ones) so a + # ctx manager wraps identically however it is encountered. + return ( + inspect.isfunction(inspect.getattr_static(cls, "__enter__", None)) + and inspect.isfunction(inspect.getattr_static(cls, "__exit__", None)) + and not is_forbidden_context_manager(cls) + ) + + +def is_cython_function(obj: object) -> bool: + return ( + callable(obj) + and hasattr(type(obj), "__name__") + and type(obj).__name__ == "cython_function_or_method" + ) + + +def is_pydantic_dataclass_cls(value: object) -> bool: + return ( + inspect.isclass(value) + and dataclasses.is_dataclass(value) + and "__is_pydantic_dataclass__" in getattr(value, "__dict__", {}) + ) + + +# Types whose instances are data descriptors (have __get__ + (__set__ or __delete__)). +# CPython invokes data descriptors found on the type MRO *before* checking +# the instance __dict__. This set is used by is_data_descriptor for a fast +# O(1) check before falling back to the generic hasattr probe. +KNOWN_DATA_DESCRIPTOR_TYPES: frozenset[type] = frozenset( + { + property, + _collections._tuplegetter, + types.MemberDescriptorType, + types.GetSetDescriptorType, + } +) + + +def is_data_descriptor(obj: object) -> bool: + """Return True if *obj* is a data descriptor (has __get__ and (__set__ or __delete__)).""" + tp = type(obj) + if tp in KNOWN_DATA_DESCRIPTOR_TYPES: + return True + return hasattr(tp, "__get__") and ( + hasattr(tp, "__set__") or hasattr(tp, "__delete__") + ) + + +def is_hashable(obj: object) -> bool: + try: + hash(obj) + return True + except TypeError: + return False + + +class UserDefinedVariable(VariableTracker): + value: object + + def _maybe_get_baseclass_method(self, name: str) -> Any: + """Get method from the base class if not overridden in value's __dict__.""" + if name not in getattr(self.value, "__dict__", {}): + try: + return inspect.getattr_static(type(self.value), name) + except AttributeError: + pass + return None + + +class UserDefinedClassVariable(UserDefinedVariable): + # pyrefly: ignore[bad-override] + value: type[object] + + def __init__(self, value: type[object], **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + # Used when we materialize class.__dict__ to a MappingProxyObject. In + # this case, we don't want to allow mutation in the class because there + # is no way to reflect it in the created MappingProxyVariable. + self.ban_mutation = False + + def get_value_for_setattr(self) -> object | None: + mod = getattr(self.value, "__module__", None) or "" + if mod == "torch" or mod.startswith(("torch.", "torch_")): + return None + return self.value + + def get_id_guard_type(self) -> Callable[..., Any] | None: + if self.source: + return GuardBuilder.CLASS_MATCH + return None + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + if self.source: + try: + install_guard(self.source.make_guard(GuardBuilder.CLASS_MATCH)) + return hash(self.value), False + except NotImplementedError: + pass + return hash(self.value), True + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .constant import ConstantVariable + + if not hasattr(other, "value"): + return ConstantVariable.create(NotImplemented) + if op in ("__eq__", "__ne__"): + try: + result = ( + (self.value == other.value) + if op == "__eq__" + else (self.value != other.value) + ) + return ConstantVariable.create(result) + except Exception: + return ConstantVariable.create(NotImplemented) + return ConstantVariable.create(NotImplemented) + + def as_python_constant(self) -> type[object]: + return self.value + + def as_proxy(self) -> object: + return self.value + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.value})" + + @staticmethod + @functools.cache + def _constant_fold_classes() -> set[type[object]]: + return { + torch.device, + torch.finfo, + torch.iinfo, + torch.Size, + } + + @staticmethod + @functools.cache + def _in_graph_classes() -> set[type[object]]: + _in_graph_class_list = { + torch.Tensor, + torch.cuda.FloatTensor, # type: ignore[attr-defined] + torch.cuda.DoubleTensor, # type: ignore[attr-defined] + torch.cuda.HalfTensor, # type: ignore[attr-defined] + torch.cuda.BFloat16Tensor, # type: ignore[attr-defined] + torch.cuda.ByteTensor, # type: ignore[attr-defined] + torch.cuda.CharTensor, # type: ignore[attr-defined] + torch.cuda.IntTensor, # type: ignore[attr-defined] + torch.cuda.ShortTensor, # type: ignore[attr-defined] + torch.cuda.LongTensor, # type: ignore[attr-defined] + torch.Stream, + torch.Event, + torch.cuda.Stream, + torch.cuda.Event, + torch.xpu.Stream, + torch.xpu.Event, + } + if hasattr(torch, "hpu"): + _in_graph_class_list.update( + { + torch.hpu.Stream, + torch.hpu.Event, + } + ) + + return set(tensortype_to_dtype.keys()) | _in_graph_class_list + + @staticmethod + @functools.cache + def supported_c_new_functions() -> set[Any]: + exceptions: set[Any] = { + getattr(builtins, name).__new__ + for name in dir(builtins) + if isinstance(getattr(builtins, name), type) + and issubclass(getattr(builtins, name), BaseException) + } + c_new_fns: set[Any] = { + object.__new__, + dict.__new__, + set.__new__, + frozenset.__new__, + tuple.__new__, + list.__new__, + int.__new__, + float.__new__, + str.__new__, + collections.deque.__new__, + } + return c_new_fns.union(exceptions) + + @staticmethod + def is_supported_new_method(value: object) -> bool: + if not is_hashable(value): + return False + if value in UserDefinedClassVariable.supported_c_new_functions(): + return True + # Structseq types each define their own C tp_new. + owner = getattr(value, "__self__", None) + return isinstance(owner, type) and is_structseq_class(owner) + + def can_constant_fold_through(self) -> bool: + if self.value in self._constant_fold_classes(): + return True + # Enum class calls (e.g., Color(1)) are value lookups that return + # existing singleton members, so they can always be constant-folded. + return isinstance(self.value, type) and issubclass(self.value, enum.Enum) + + def lookup_cls_mro_attr(self, name: str) -> object: + """Walk cls.__mro__ only (not the metaclass chain) to find *name*.""" + return mro_lookup(self.value, name) + + def get_source_by_walking_mro( + self, tx: "InstructionTranslatorBase", name: str + ) -> DictGetItemSource: + source = self.source + if source is None: + raise RuntimeError("get_source_by_walking_mro requires source") + + for idx, klass in enumerate(self.value.__mro__): + if name in klass.__dict__: + descriptor = klass.__dict__[name] + + for absent_idx in range(1, idx): + absent_klass = self.value.__mro__[absent_idx] + cache_key = (id(absent_klass), name) + if cache_key in tx.output.guarded_mro_absent_keys: + continue + tx.output.guarded_mro_absent_keys.add(cache_key) + mro_source = TypeMROSource(source) + klass_source: Source = GetItemSource(mro_source, absent_idx) + dict_source = TypeDictSource(klass_source) + install_guard( + dict_source.make_guard( + functools.partial(GuardBuilder.DICT_NOT_CONTAINS, key=name) + ) + ) + + cache_key = (id(descriptor), name) + cache = tx.output.mro_source_cache + if cache_key in cache: + return cache[cache_key] + + if idx != 0: + mro_source = TypeMROSource(source) + klass_source = GetItemSource(mro_source, idx) + else: + klass_source = source + dict_source = TypeDictSource(klass_source) + out_source = DictGetItemSource(dict_source, name) + cache[cache_key] = out_source + return out_source + + raise RuntimeError(f"Attribute {name} not found in MRO of {self.value}") + + def lookup_metaclass_attr(self, name: str) -> object: + """Walk type(cls).__mro__ (the metaclass chain) to find *name*.""" + return mro_lookup(type(self.value), name) + + def nb_bool_impl( + self, + tx: "InstructionTranslatorBase", + ) -> "VariableTracker": + from .constant import ConstantVariable + + # bool() on a class consults the metaclass __bool__. + # If the metaclass is the default `type`, all classes are truthy. + metaclass = type(self.value) + if hasattr(metaclass, "__bool__") and metaclass is not type: + return self.call_method(tx, "__bool__", [], {}) + return ConstantVariable.create(True) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L2379-L2408 + metaclass = type(self.value) + if metaclass is type or metaclass.__repr__ is type.__repr__: + return VariableTracker.build(tx, repr(self.value)) + + type_attr = self.lookup_metaclass_attr("__repr__") + if type_attr is None: + raise_type_error(tx, "'NoneType' object is not callable") + return self.call_method(tx, "__repr__", [], {}) + + def tp_str_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + metaclass = type(self.value) + if metaclass is type or metaclass.__str__ is type.__str__: + return generic_repr(tx, self) + + type_attr = self.lookup_metaclass_attr("__str__") + if type_attr is None: + raise_type_error(tx, "'NoneType' object is not callable") + return self.call_method(tx, "__str__", [], {}) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython's type.__or__ implements _Py_union_type_or (type unions). + try: + other_val = other.as_python_constant() + except NotImplementedError: + return VariableTracker.build(tx, NotImplemented) + # pyrefly: ignore[bad-argument-count] + result = type(self.value).__or__(self.value, other_val) + if result is NotImplemented: + return VariableTracker.build(tx, NotImplemented) + return VariableTracker.build(tx, result) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + source = AttrSource(self.source, name) if self.source is not None else None + + # --- Dynamo-specific pre-checks --- + + # Custom metaclasses that override __getattribute__ replace the entire + # lookup algorithm; bail out for those. Standard metaclasses (ABCMeta, + # EnumType, etc.) that don't override __getattribute__ use + # type.__getattribute__ which is the algorithm we implement below. + metacls = type(self.value) + if metacls is not type and "__getattribute__" in metacls.__dict__: + unimplemented( + gb_type="Custom metaclass with __getattribute__", + context=f"type({self.value}) = {metacls}", + explanation="Dynamo does not trace attribute access on classes whose " + "metaclass overrides __getattribute__", + hints=graph_break_hints.SUPPORTABLE, + ) + + # ---- CPython type_getattro algorithm ---- + # https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L5417-L5505 + # 1. meta_attr = lookup name in type(cls).__mro__ (metaclass chain) + # 2. if meta_attr is a DATA descriptor → invoke + # 3. cls_attr = lookup name in cls.__mro__ (class chain) + # 4. if cls_attr has __get__ → invoke cls_attr.__get__(None, cls) + # 5. if cls_attr exists (plain) → return as-is + # 6. if meta_attr is a non-data descriptor or plain → return + # 7. raise AttributeError + + # Step 1-2: Metaclass data descriptors. + # For type(cls) is type, these are C-level getset/member descriptors + # for __dict__, __mro__, __name__, __qualname__, __doc__, etc. + meta_attr = self.lookup_metaclass_attr(name) + if meta_attr is not NO_SUCH_SUBOBJ and is_data_descriptor(meta_attr): + return self.resolve_meta_data_descriptor(tx, name, meta_attr, source) + + # Check for pending mutations from setattr on the class during tracing. + if tx.output.side_effects.has_pending_mutation_of_attr(self, name): + return tx.output.side_effects.load_attr(self, name) + + # Step 3-5: Class MRO lookup. + cls_attr = self.lookup_cls_mro_attr(name) + if cls_attr is not NO_SUCH_SUBOBJ: + if hasattr(type(cls_attr), "__get__"): + # Step 4: Descriptor — invoke __get__(None, cls). + return self.resolve_cls_descriptor(tx, name, cls_attr, source) + # Step 5: Plain attribute. + return self.resolve_cls_plain_attr(tx, name, cls_attr, source) + + # Step 6: Metaclass non-data descriptor or plain attr. + # For C-level descriptors with proper VTs, invoke tp_descr_get to + # produce a bound method. For everything else, defer to GetAttrVariable + # which routes call_function through call_method at runtime. + if meta_attr is not NO_SUCH_SUBOBJ: + metacls_source = TypeSource(self.source) if self.source else None + metacls_vt = VariableTracker.build(tx, type(self.value), metacls_source) + result = _resolve_descriptor_get(tx, meta_attr, self, metacls_vt, source) + if result is not None: + return result + return variables.GetAttrVariable(self, name, type(meta_attr), source=source) + + # __getattr__ on metaclass (not part of type_getattro proper — + # CPython handles this via slot_tp_getattr_hook). + metacls = type(self.value) + if metacls is not type: + meta_getattr = self.lookup_metaclass_attr("__getattr__") + if meta_getattr is not NO_SUCH_SUBOBJ and isinstance( + meta_getattr, types.FunctionType + ): + return variables.UserMethodVariable(meta_getattr, self).call_function( + tx, [variables.ConstantVariable.create(name)], {} + ) + + # Step 7: AttributeError. + raise_observed_exception( + AttributeError, + tx, + args=[f"type object '{self.value.__name__}' has no attribute '{name}'"], + ) + + def resolve_meta_data_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + meta_attr: object, + source: Source | None, + ) -> VariableTracker: + """Handle data descriptors from the metaclass MRO (type.__dict__ slots).""" + if name == "__dict__": + return VariableTracker.build( + tx, + self.value.__dict__, + source=self.source and AttrSource(self.source, "__dict__"), + ) + if name == "__mro__": + if meta_attr is type.__dict__["__mro__"]: + attr_source = self.source and TypeMROSource(self.source) + else: + attr_source = source + return VariableTracker.build(tx, self.value.__mro__, attr_source) + if name == "__bases__": + bases = self.value.__bases__ + items = [ + VariableTracker.build(tx, b, source and GetItemSource(source, i)) + for i, b in enumerate(bases) + ] + return variables.TupleVariable(items, source=source) + if name == "__base__": + return VariableTracker.build(tx, self.value.__base__, source) + # __name__, __qualname__, __doc__, __module__, + # __abstractmethods__, etc. — all C-level getset descriptors on type. + resolved = type.__getattribute__(self.value, name) + if source: + return VariableTracker.build(tx, resolved, source) + from . import ConstantVariable + + if ConstantVariable.is_literal(resolved): + return VariableTracker.build(tx, resolved) + return variables.GetAttrVariable(self, name, type(resolved), source=source) + + def _descriptor_defining_class_vt( + self, + tx: "InstructionTranslatorBase", + descriptor: types.WrapperDescriptorType | types.MethodDescriptorType, + ) -> VariableTracker: + """VT for the class that actually implements an unbound C descriptor. + + Consider the following example: + + # Metaclass defines __neg__, so `-SomeClass` would call Meta.__neg__(cls). + class Meta(type): + def __neg__(cls): + return 999 + + + class Base(metaclass=Meta): + # Alias int's unary __neg__ slot wrapper into this class's dict under a + # different name. __objclass__ == int, __name__ == '__neg__', but looked + # up on Base, whose metaclass separately defines __neg__. + sneaky = int.__neg__ + + This helper function determines the correct owner of the descriptor based on the `__objclass__` attribute. + + class Foo(int): + ... + + assert Foo.__neg__ == int.__neg__ + assert Foo.__neg__.__objclass__ is int + """ + objclass = descriptor.__objclass__ + if objclass is self.value: + return self + return VariableTracker.build(tx, objclass) + + def resolve_cls_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + cls_attr: object, + source: Source | None, + ) -> VariableTracker: + """Handle descriptors found in cls.__mro__.""" + if isinstance(cls_attr, staticmethod): + # Source points to the descriptor in the class __dict__ via MRO + # walk, not via AttrSource(cls, name) which would trigger the + # descriptor protocol and skip past the staticmethod wrapper. + descriptor_source = ( + self.get_source_by_walking_mro(tx, name) + if self.source is not None + else None + ) + sm_vt = variables.StaticMethodVariable(cls_attr, source=descriptor_source) + return sm_vt.tp_descr_get_impl(tx, self, self) + + if isinstance(cls_attr, classmethod): + if isinstance(cls_attr.__func__, property): + fget_vt = VariableTracker.build(tx, cls_attr.__func__.fget) + return fget_vt.call_function(tx, [self], {}) + # Source points to the descriptor in the class __dict__ via MRO + # walk, not via AttrSource(cls, name) which would trigger the + # descriptor protocol and skip past the classmethod wrapper. + descriptor_source = ( + self.get_source_by_walking_mro(tx, name) + if self.source is not None + else None + ) + cm_vt = variables.ClassMethodVariable(cls_attr, source=descriptor_source) + return cm_vt.tp_descr_get_impl(tx, self, self) + + if isinstance(cls_attr, types.ClassMethodDescriptorType): + cmd_vt = variables.ClassMethodDescriptorVariable(cls_attr, source=source) + return cmd_vt.tp_descr_get_impl(tx, self, self) + + # property_descr_get with obj=NULL returns self. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1662-L1663 + if isinstance(cls_attr, property): + descriptor_source = ( + self.get_source_by_walking_mro(tx, name) + if self.source is not None + else None + ) + return variables.PropertyVariable(cls_attr, source=descriptor_source) + + # member_get with obj=NULL returns self. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L162-L164 + if isinstance(cls_attr, types.MemberDescriptorType): + descriptor_source = ( + self.get_source_by_walking_mro(tx, name) + if self.source is not None + else None + ) + return variables.MemberDescriptorVariable( + cls_attr, source=descriptor_source + ) + + if isinstance(cls_attr, _collections._tuplegetter): + descriptor_source = ( + self.get_source_by_walking_mro(tx, name) + if self.source is not None + else None + ) + tg_vt = variables.TupleGetterVariable(cls_attr, source=descriptor_source) + return tg_vt.tp_descr_get_impl(tx, None, self) + + # TODO(tp_descr_get) - Comparison dunders must be checked before + # WrapperDescriptor/MethodDescriptor to avoid VT type mismatches in + # identity checks. Revisit once we implement tp_richcompare slot. + if name in cmp_name_to_op_mapping and not isinstance( + cls_attr, types.FunctionType + ): + return variables.GetAttrVariable( + self, name, py_type=type(cls_attr), source=source + ) + + # wrapperdescr_get/method_get with obj=NULL returns the + # descriptor itself. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L206-L207 + if ( + isinstance(cls_attr, types.WrapperDescriptorType) + and not is_torch_class(self.value) + and name not in ("__get__", "__set__", "__delete__") + ): + return variables.WrapperDescriptorVariable( + cls_attr, + owner=self._descriptor_defining_class_vt(tx, cls_attr), + source=source, + ) + + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L140-L141 + if ( + isinstance(cls_attr, types.MethodDescriptorType) + and not is_torch_class(self.value) + and name not in ("__get__", "__set__", "__delete__") + ): + return variables.MethodDescriptorVariable( + cls_attr, + owner=self._descriptor_defining_class_vt(tx, cls_attr), + source=source, + ) + + # User-defined descriptor with Python __get__. + # For torch-internal classes or attributes in the class's own __dict__, + # defer descriptor invocation to runtime via VariableTracker.build to + # avoid compile-time side effects (e.g. deprecation warnings from + # _ClassPropertyDescriptor on torch.FloatStorage.dtype). + get_fn = inspect.getattr_static(type(cls_attr), "__get__", None) + if isinstance(get_fn, types.FunctionType): + if source and ( + name in getattr(self.value, "__dict__", {}) + or self.value.__module__.startswith("torch.") + or self.value.__module__ == "torch" + ): + return VariableTracker.build(tx, cls_attr, source) + return self.invoke_cls_descriptor_get(tx, name, cls_attr, source) + + # TODO(tp_descr_get) - C-level descriptors not matched above (e.g. + # instancemethod, or wrapper/method descriptors on torch classes that + # need trace_rules). OrderedDict's C-level methods are handled at + # runtime. + if inspect.ismethoddescriptor(cls_attr): + if ( + source + and self.value is not collections.OrderedDict + and ( + name in getattr(self.value, "__dict__", {}) + or self.value.__module__.startswith("torch.") + or self.value.__module__ == "torch" + ) + ): + return VariableTracker.build(tx, cls_attr, source) + return variables.GetAttrVariable(self, name, type(cls_attr), source=source) + + # Everything else: FunctionType, etc. + return VariableTracker.build(tx, cls_attr, source) + + def resolve_cls_plain_attr( + self, + tx: "InstructionTranslatorBase", + name: str, + cls_attr: object, + source: Source | None, + ) -> VariableTracker: + """Handle non-descriptor attributes from cls.__mro__.""" + if name == "__new__" and UserDefinedClassVariable.is_supported_new_method( + cls_attr + ): + return variables.GetAttrVariable(self, name, source=source) + if self.value is collections.OrderedDict: + return variables.GetAttrVariable(self, name, py_type=type(cls_attr)) + return VariableTracker.build(tx, cls_attr, source) + + def invoke_cls_descriptor_get( + self, + tx: "InstructionTranslatorBase", + name: str, + descriptor: object, + source: Source | None, + ) -> VariableTracker: + """Trace a class-MRO descriptor's __get__(None, cls) call.""" + from .constant import ConstantVariable + + descriptor_source = None + descriptor_get_source = None + if self.source: + descriptor_source = AttrSource(self.source, name) + descriptor_get_source = AttrSource(TypeSource(descriptor_source), "__get__") + descriptor_var = VariableTracker.build(tx, descriptor, descriptor_source) + else: + descriptor_var = UserDefinedObjectVariable(descriptor) + + none_var = ConstantVariable.create(None) + return variables.UserMethodVariable( + descriptor.__get__.__func__, # type: ignore[union-attr] + descriptor_var, + source=descriptor_get_source, + ).call_function(tx, [none_var, self], {}) + + def len_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__len__") + if m: + source = self.source and AttrSource(self.source, "__len__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + raise_type_error(tx, f"object of type {self.python_type_name()} has no length") + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.len_impl(tx) + + def mp_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.len_impl(tx) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + m = self._maybe_get_baseclass_method("__contains__") + if m: + return self.call_method(tx, "__contains__", [item], {}) + return super().sq_contains_impl(tx, item) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__iter__") + if m: + source = self.source and AttrSource(self.source, "__iter__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + return super().tp_iter_impl(tx) + + def nb_negative_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__neg__") + if m: + source = self.source and AttrSource(self.source, "__neg__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + raise_type_error( + tx, f"bad operand type for unary -: '{self.python_type_name()}'" + ) + + def nb_positive_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__pos__") + if m: + source = self.source and AttrSource(self.source, "__pos__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + raise_type_error( + tx, f"bad operand type for unary +: '{self.python_type_name()}'" + ) + + def nb_absolute_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__abs__") + if m: + source = self.source and AttrSource(self.source, "__abs__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + raise_type_error( + tx, + f"bad operand type for abs(): '{self.python_type_name()}'", + ) + + def nb_invert_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__invert__") + if m: + source = self.source and AttrSource(self.source, "__invert__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + raise_type_error( + tx, + f"bad operand type for unary ~: '{self.python_type_name()}'", + ) + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # Class-level __setitem__ / __delitem__: looked up on the metaclass. + # `cls[k] = v` invokes type(cls).__setitem__(cls, k, v); `del cls[k]` + # invokes __delitem__. value=None signals delete (CPython NULL). + is_delete = value is None + attr = "__delitem__" if is_delete else "__setitem__" + m = self._maybe_get_baseclass_method(attr) + if isinstance(m, types.FunctionType): + source = self.source and AttrSource(self.source, attr) + args = [key] if is_delete else [key, value] + variables.UserMethodVariable(m, self, source_fn=source).call_function( + tx, args, {} + ) + return variables.ConstantVariable.create(None) + return super().mp_ass_subscript_impl(tx, key, value) + + sq_ass_item_impl = mp_ass_subscript_impl + + def _call_cross_entropy_loss( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """ + functional: input, target, weight=None, size_average=None, ignore_index=- 100, reduce=None, reduction='mean', + label_smoothing=0.0 + + non functional ctor: weight=None, size_average=None, ignore_index=- 100, reduce=None, reduction='mean', + label_smoothing=0.0 + + non functional loss call: input, target, optional_output + """ + from . import ConstantVariable + + def normalize_args( + weight: VariableTracker = ConstantVariable.create(None), + size_average: VariableTracker = ConstantVariable.create(None), + ignore_index: VariableTracker = ConstantVariable.create(-100), + reduce: VariableTracker = ConstantVariable.create(None), + reduction: VariableTracker = ConstantVariable.create("mean"), + label_smoothing: VariableTracker = ConstantVariable.create(0.0), + ) -> tuple[VariableTracker, ...]: + return ( + weight, + size_average, + ignore_index, + reduce, + reduction, + label_smoothing, + ) + + ( + weight, + size_average, + ignore_index, + reduce_arg, + reduction, + label_smoothing, + ) = normalize_args(*args, **kwargs) + + def fake_cross_entropy_loss( + input: VariableTracker, target: VariableTracker + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + torch.nn.functional.cross_entropy, + *proxy_args_kwargs( + [ + input, + target, + weight, + size_average, + ignore_index, + reduce_arg, + reduction, + label_smoothing, + ], + {}, + ), + ), + ) + + return variables.LambdaVariable(fake_cross_entropy_loss) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import SourcelessBuilder + + if ( + name == "__subclasses__" + and len(args) == 0 + and not kwargs + and "__subclasses__" not in self.value.__dict__ + ): + source = self.source + if self.source: + source = AttrSource(self.source, "__subclasses__") + source = CallFunctionNoArgsSource(source) + return VariableTracker.build(tx, self.value.__subclasses__(), source) + elif ( + self.value in {collections.OrderedDict, collections.defaultdict} + and name == "fromkeys" + ): + return variables.DictBuiltinVariable.call_custom_dict_fromkeys( + tx, self.value, *args, **kwargs + ) + elif self.value is collections.OrderedDict and name == "move_to_end": + return args[0].call_method(tx, name, [*args[1:]], kwargs) + elif ( + self.value in {collections.defaultdict, collections.deque} + and name == "__copy__" + and len(args) == 1 + and not kwargs + ): + # copy.copy(x) resolves type(x).__copy__ and calls it with the + # instance as the sole argument; dispatch to the instance so the + # contents (and defaultdict default_factory / deque maxlen) are + # preserved. + return args[0].call_method(tx, name, [], kwargs) + elif name == "__len__" and len(args) == 1 and not kwargs: + from .object_protocol import generic_size + + return generic_size(tx, args[0]) + elif issubclass(self.value, dict) and name != "__new__": + # __new__ is handled below + return SourcelessBuilder.create(tx, dict).call_method( + tx, name, args, kwargs + ) + elif issubclass(self.value, (set, frozenset)) and name != "__new__": + # __new__ is handled below + return SourcelessBuilder.create(tx, set).call_method(tx, name, args, kwargs) + elif ( + len(args) == 1 + and isinstance(args[0], variables.GenericContextWrappingVariable) + and name == "__enter__" + ): + return args[0].enter(tx) + elif name == "__new__" and UserDefinedClassVariable.is_supported_new_method( + self.value.__new__ + ): + if self.value is collections.OrderedDict: + # Exact OrderedDict: represent as a bare OrderedDictVariable, + # mirroring dict.__new__(dict) -> ConstDictVariable. + return OrderedDictVariable({}, mutation_type=ValueMutationNew()) + # Some C-level tp_new functions (dict.__new__, set.__new__) ignore + # extra args — only the type arg matters. Pass init_args=[] for + # those so reconstruction emits base_cls.__new__(cls) without + # unreconstructable args (e.g. generators). Other tp_new functions + # (tuple.__new__, BaseException.__new__) use the extra args. + new_fn = self.value.__new__ + if new_fn in (dict.__new__, set.__new__, collections.deque.__new__): + init_args: list[VariableTracker] = [] + else: + init_args = list(args[1:]) + return tx.output.side_effects.track_new_user_defined_object( + self, + args[0], + init_args, + tx=tx, + ) + elif name == "__setattr__" and self.ban_mutation: + unimplemented( + gb_type="Class attribute mutation when the __dict__ was already materialized", + context=str(self.value), + explanation="Dynamo does not support tracing mutations on a class when its __dict__ is materialized", + hints=graph_break_hints.SUPPORTABLE, + ) + + # Dispatch dunder methods defined on the metaclass (e.g., EnumType.__contains__). + # In Python, `x in Color` calls `type(Color).__contains__(Color, x)`. + metaclass = type(self.value) + if metaclass is not type: + # Look up the method on the metaclass MRO, not the class MRO + for klass in metaclass.__mro__: + if name in klass.__dict__: + method = klass.__dict__[name] + if isinstance(method, types.FunctionType): + source = self.source and AttrSource(self.source, name) + return variables.UserMethodVariable( + method, self, source=source + ).call_function(tx, args, kwargs) + break + + return super().call_method(tx, name, args, kwargs) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list["VariableTracker"]: + if isinstance(self.value, type) and issubclass(self.value, enum.Enum): + return [VariableTracker.build(tx, item) for item in self.value] + raise NotImplementedError + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from ..side_effects import SideEffects + from .builder import SourcelessBuilder, wrap_fx_proxy + from .ctx_manager import ( + GenericContextWrappingVariable, + get_device_context_manager, + ) + + constant_args = check_constant_args(args, kwargs) + + if torch.distributed.is_available() and self.value is torch.distributed.P2POp: + if not config.enable_p2p_compilation: + unimplemented( + gb_type="P2P compilation disabled for P2POp construction", + context="torch.distributed.P2POp", + explanation="P2P compilation is disabled.", + hints=[ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable.", + ], + ) + var = tx.output.side_effects.track_new_user_defined_object( + SourcelessBuilder.create(tx, object), + self, + [], + tx=tx, + ) + var.call_method(tx, "__init__", list(args), kwargs) # type: ignore[arg-type] + return var + + if self.can_constant_fold_through() and constant_args: + # constant fold + return VariableTracker.build( + tx, + self.as_python_constant()( # type: ignore[operator] + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ), + ) + elif self.value is torch.nn.CrossEntropyLoss: + return self._call_cross_entropy_loss(tx, args, kwargs) + elif self.value is contextlib.nullcontext: + # import here to avoid circular dependency + from .ctx_manager import NullContextVariable + + return NullContextVariable(*args, **kwargs) + elif self.value is collections.defaultdict: + # defaultdict construction — use track_new_user_defined_object + # which creates DefaultDictVariable. __init__ handler extracts + # default_factory and populates items. + from .builder import SourcelessBuilder + + result = tx.output.side_effects.track_new_user_defined_object( + SourcelessBuilder.create(tx, dict), + self, + [], + tx=tx, + ) + result.call_method(tx, "__init__", list(args), kwargs) + return result + elif is_typeddict(self.value): + if self.value.__optional_keys__: # type: ignore[attr-defined] + unimplemented( + gb_type="TypedDict with optional keys", + context=str(self.value), + explanation="Dynamo does not support tracing TypedDict with optional keys", + hints=[ + "Avoid using TypedDict with optional keys", + *graph_break_hints.SUPPORTABLE, + ], + ) + return variables.DictBuiltinVariable.call_custom_dict( + tx, dict, *args, **kwargs + ) + elif self.value is collections.deque: + maxlen = variables.ConstantVariable.create(None) + + def deque_signature( + iterable: Iterable[Any] | None = None, maxlen: int | None = None + ) -> Any: + pass + + bound_args = None + try: + bound_args = inspect.signature(deque_signature).bind(*args, **kwargs) + except TypeError as e: + unimplemented( + gb_type="collections.deque() with bad arguments", + context=f"args={args}, kwargs={kwargs}", + explanation="Detected call to collections.deque() with bad arguments.", + hints=[ + "Fix the call to collections.deque().", + *graph_break_hints.USER_ERROR, + ], + from_exc=e, + ) + if bound_args is None: + raise AssertionError("bound_args is None after signature binding") + if "iterable" in bound_args.arguments: + items = unpack_iterable(tx, bound_args.arguments["iterable"]) + else: + # pyrefly: ignore [implicit-any] + items = [] + + if "maxlen" in bound_args.arguments: + maxlen = bound_args.arguments["maxlen"] + + variables.lists.DequeVariable.validate_maxlen(tx, maxlen) + return variables.lists.DequeVariable( + items, maxlen=maxlen, mutation_type=ValueMutationNew() + ) + elif self.value in ( + deque_iterator, + deque_rev_iterator, + ): + # _deque_iterator(deque[, index]) / _deque_reverse_iterator(deque[, index]) + # ref: dequeiter_new in Modules/_collectionsmodule.c + name = self.value.__name__ + + def deque_iterator_sig(deque: Any, index: Any = 0, /) -> tuple[Any, Any]: + return deque, index + + try: + deque_arg, index = deque_iterator_sig(*args, **kwargs) + except TypeError: + raise_args_mismatch(tx, name) + if not isinstance(deque_arg, variables.lists.DequeVariable): + raise_type_error( + tx, + f"{name}() argument 1 must be collections.deque, " + f"not {deque_arg.python_type_name()}", + ) + if not isinstance(index, int): + index = index.as_python_constant() + if self.value is deque_rev_iterator: + cls = variables.lists.DequeReverseIteratorVariable + snapshot = list(reversed(deque_arg.items)) + else: + cls = variables.lists.DequeIteratorVariable + snapshot = list(deque_arg.items) + return cls( + snapshot, + deque_arg, + deque_arg.state, + index=index, + mutation_type=ValueMutationNew(), + ) + elif ( + # https://github.com/python/cpython/blob/33efd7178e269cbd04233856261fd0aabbf35447/Lib/contextlib.py#L475-L477 + self.value is types.MethodType + and len(args) == 2 + and isinstance(args[0], variables.UserFunctionVariable) + and isinstance(args[1], GenericContextWrappingVariable) + and args[0].get_name() in ("__enter__", "__exit__") + ): + cm_obj = args[1].cm_obj + fn = getattr(cm_obj, args[0].get_name()).__func__ + return variables.UserMethodVariable(fn, args[1], source=self.source) + elif self.value is weakref.ref: + if len(args) > 1: + callback = args[1] + else: + callback = variables.ConstantVariable.create(None) + return variables.WeakRefVariable(args[0], callback) + elif self.value is functools.partial: + if not args: + unimplemented( + gb_type="missing args to functools.partial", + context="", + explanation="functools.partial requires at least one argument", + hints=[ + "Fix the functools.partial call.", + *graph_break_hints.USER_ERROR, + ], + ) + # The first arg, a callable (the ctor below will assert on types) + fn = args[0] + rest_args = args[1:] + # guards for the produced FunctoolsPartialVariable are installed in FunctoolsPartialVariable ctor from the + # args and keywords + return variables.functions.FunctoolsPartialVariable( + fn, args=rest_args, keywords=kwargs + ) + elif self.value is warnings.catch_warnings and not args: + return variables.CatchWarningsCtxManagerVariable.create(tx, kwargs) + elif ( + not kwargs + and len(args) == 1 + and (variable_cls := get_device_context_manager(self.value)) is not None + ): + if not args[0].is_python_constant(): + raise_type_error( + tx, + f"{self.value.__module__}.{self.value.__qualname__} requires a constant argument", + ) + return variable_cls.create(tx, args[0].as_python_constant()) + elif ( + issubclass(type(self.value), type) + and hasattr( + self.value, "__enter__" + ) # TODO(voz): These can invoke user code! + and hasattr( + self.value, "__exit__" + ) # TODO(voz): These can invoke user code! + and self.is_standard_new() + and SideEffects.cls_supports_mutation_side_effects(self.value) + and self.source + and not is_forbidden_context_manager(self.value) + ): + from . import TorchCtxManagerClassVariable + from .functions import ( + BaseUserFunctionVariable, + FunctionDecoratedByContextlibContextManagerVariable, + ) + + # graph break on any contextlib.* that it is not contextlib.contextmanager + # Some of the APIs below are not supported because they rely on features + # that Dynamo doesn't play well today (i.e. contextlib.suppress) + if self.value in ( + contextlib._AsyncGeneratorContextManager, + contextlib.closing, + contextlib.redirect_stdout, + contextlib.redirect_stderr, + contextlib.AsyncExitStack, + ): + # We are not changing the behavior of Dynamo as these function were + # already ignored on trace_rules.py before #136033 landed + unimplemented( + gb_type="unsupported contextlib.* API", + context=f"{self.value}", + explanation=f"{self.value} not supported. This may be due to its use of " + "context-specific operations that are not supported in " + "Dynamo yet (i.e. Exception handling)", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + arg_new = args + if self.value is contextlib._GeneratorContextManager and isinstance( + args[0], (BaseUserFunctionVariable, TorchCtxManagerClassVariable) + ): + if not torch._dynamo.config.enable_trace_contextlib: + unimplemented( + gb_type="attempted to trace contextlib.contextmanager", + context=f"args={args}", + explanation="Tracing contextlib.contextmanager is disabled.", + hints=[ + "Set torch._dynamo.config.enable_trace_contextlib = True", + ], + ) + + # Special treatments for certain context managers created via + # contextlib, because + # 1. we (pytorch) own their impls + # 2. it's tedious to trace through them, so we effectively + # "allow in graph" them without sacrificing soundness. + # + # We would typically reach here via either + # 1. the instance construction in `with ctx_manager(...):`: + # https://github.com/python/cpython/blob/3.12/Lib/contextlib.py#L301 + # 2. calling a function decorated with a context manager: + # https://github.com/python/cpython/blob/3.12/Lib/contextlib.py#L122 + # + # So we basically trace through the surface part of the + # contextlib code, and then special case the shared remaining + # logic (the actual context manager instance construction and + # usage later on). + if isinstance(args[0], TorchCtxManagerClassVariable): + fn_var = args[0] + args_list = args[1].items # type: ignore[union-attr,attr-defined] + kwargs_dict = args[2].keys_as_python_constant() # type: ignore[union-attr,attr-defined] + return fn_var.call_function(tx, args_list, kwargs_dict) + + # Wrap UserFunctionVariable in FunctionDecoratedByContextlibContextManagerVariable + # if the function is annotated with @contextlib.contextmanager + # This shouldn't be necessary once generator functions are fully + # supported in dynamo + # pyrefly: ignore[unsupported-operation] + arg_new = [ + FunctionDecoratedByContextlibContextManagerVariable( + args[0], source=args[0].source + ) + ] + args[1:] + + return tx.inline_user_function_return( + VariableTracker.build( + tx, polyfills.instantiate_user_defined_class_object + ), + [self, *arg_new], + kwargs, + ) + elif is_namedtuple_cls(self.value): + if is_structseq_class(self.value): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + "torch.return_types", + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + # Structseq tp_new is a C function, so we can't trace into + # it like namedtuples. Use track_new_user_defined_object + # directly with self as both base_cls_vt and cls_vt. + return tx.output.side_effects.track_new_user_defined_object( + self, + self, + list(args), + tx=tx, + ) + else: + # Namedtuple __new__ is a Python function that calls + # tuple.__new__(cls, (field_values,)). Let Dynamo trace + # into it so default values and kwargs are handled by + # the generated __new__ itself. + return tx.inline_user_function_return( + VariableTracker.build( + tx, polyfills.instantiate_user_defined_class_object + ), + [self, *args], + kwargs, + ) + elif self.value is torch.Size: + # This simulates `THPSize_pynew`, the C impl for `Size.__new__`. + from .lists import SizeVariable + + tup = SourcelessBuilder.create(tx, tuple).call_function(tx, args, kwargs) + return SizeVariable(tup.items) # type: ignore[missing-attribute] + elif is_pydantic_dataclass_cls(self.value): + # Pydantic populates dataclass fields through an external validator, + # so tracing through the constructor misses the instance mutations. + unimplemented( + gb_type="Pydantic dataclass constructor", + context=f"{self.value}", + explanation="Dynamo graph breaks on pydantic dataclass constructors " + "because validation mutates the instance outside traced bytecode.", + hints=graph_break_hints.SUPPORTABLE, + ) + elif ( + self.value in self._in_graph_classes() + or is_traceable_wrapper_subclass_type(self.value) + ): + # torch.LongTensor cannot accept a list of FakeTensors. + # So we stack the list of FakeTensors instead. + from .lists import ListVariable + + if ( + np + and self.value in tensortype_to_dtype + and len(args) == 1 + and isinstance(args[0], ListVariable) + and len(args[0].items) > 1 + and all(x.is_tensor() for x in args[0].items) + ): + # Stack FakeTensor + stacked = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + torch.stack, + *proxy_args_kwargs(args, kwargs), + ), + ) + args = [stacked] + + if issubclass(self.value, torch.Stream): + from .lists import TupleVariable + + var_kwargs = ConstDictVariable( + {VariableTracker.build(tx, k): v for k, v in kwargs.items()} + ) + var_args = TupleVariable(list(args)) + stream = self.value( + *(var_args.as_python_constant()), + **(var_kwargs.as_python_constant()), + ) + from ..graph_bytecode_inputs import register_graph_created_object + from .streams import StreamVariable + + ind = register_graph_created_object( + stream, + StreamVariable.make_construct_in_graph_stream_fn( + var_args, var_kwargs + ), + ) + tensor_variable = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", get_external_object_by_index, (ind,), {} + ), + ) + elif issubclass(self.value, torch.Event): + from .lists import TupleVariable + + # Register newly created event for reconstruction + var_kwargs = ConstDictVariable( + {VariableTracker.build(tx, k): v for k, v in kwargs.items()} + ) + var_args = TupleVariable(list(args)) + event = self.value( + *(var_args.as_python_constant()), + **(var_kwargs.as_python_constant()), + ) + from ..graph_bytecode_inputs import register_graph_created_object + from .streams import EventVariable + + ind = register_graph_created_object( + event, + EventVariable.make_construct_in_graph_event_fn( + var_args, var_kwargs + ), + ) + tensor_variable = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", get_external_object_by_index, (ind,), {} + ), + ) + else: + tensor_variable = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + *proxy_args_kwargs(args, kwargs), + ), + ) + + return tensor_variable + elif self.value is random.Random: + if len(args) == 1 and args[0].is_python_constant(): + seed = args[0].as_python_constant() + else: + seed = None + random_object = random.Random(seed) + return RandomVariable(random_object) + elif self.value is types.MappingProxyType and len(args) == 1: + # types.MappingProxyType is a read-only proxy of the dict. If the + # original dict changes, the changes are reflected in proxy as well. + dict_arg = args[0] + if isinstance(dict_arg, variables.UserDefinedDictVariable): + dict_arg = dict_arg._base_vt + if isinstance(dict_arg, ConstDictVariable): + return variables.MappingProxyVariable(dict_arg) + elif SideEffects.cls_supports_mutation_side_effects(self.value) and ( + self.source or torch._dynamo.config.enable_trace_load_build_class + ): + if self.value.__new__ is object.__new__: + # Graph-break before inlining the class-instantiation polyfill + # for extension types where object.__new__ cannot allocate an + # example object. SideEffects keeps a matching backstop for + # direct construction paths. This allocates one temporary + # instance for classes that pass the check. + try: + object.__new__(self.value) + except TypeError as exc: + unimplemented( + gb_type="Unsupported object.__new__ user-defined class construction", + context=f"class={self.value}, error={exc}", + explanation=( + "Dynamo could not construct an example object for " + "side-effect replay using object.__new__." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + with do_not_convert_to_tracable_parameter(): + result = tx.inline_user_function_return( + VariableTracker.build( + tx, polyfills.instantiate_user_defined_class_object + ), + [self, *args], + kwargs, + ) + return result + + return super().call_function(tx, args, kwargs) + + def is_standard_new(self) -> bool: + """Check for __new__ being overridden""" + new_fn = inspect.getattr_static(self.value, "__new__", None) + if isinstance(new_fn, staticmethod): + new_fn = new_fn.__func__ + return new_fn is object.__new__ + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> "ConstantVariable": + se_result = self._hasattr_check_side_effects(tx, name) + if se_result is not None: + return se_result + if self.source: + install_guard( + self.source.make_guard( + functools.partial(GuardBuilder.HASATTR, attr=name) + ) + ) + return VariableTracker.build(tx, hasattr(self.value, name)) + + def const_getattr(self, tx: "InstructionTranslatorBase", name: str) -> Any: + if name == "__name__": + return self.value.__name__ + return super().const_getattr(tx, name) + + def reconstruct_pycode(self, codegen) -> str: + if self.source: + return self.source.reconstruct_pycode(codegen) + raise NotImplementedError( + "Python codegen not implemented yet for sourceless UserDefinedClassVariable." + ) + + def get_real_python_backed_value(self) -> object: + return self.value + + +class UserDefinedExceptionClassVariable(UserDefinedClassVariable): + @property + def fn(self) -> type[object]: + return self.value + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import SourcelessBuilder + + if self.source is None: + # NB: If source is added via side effects, create the exception + # object through side_effects as well. See FrozenDataClass creation + var = tx.output.side_effects.track_new_user_defined_object( + SourcelessBuilder.create(tx, BaseException), + self, + list(args), + tx=tx, + ) + var.call_method(tx, "__init__", list(args), dict(kwargs)) + return var + return super().call_function(tx, args, kwargs) + + +class RemovableHandleClass: + # Dummy class to pass to python_type of + # RemovableHandleVariable + # Useful for isinstance check on hooks + pass + + +def call_random_fn( + tx: "InstructionTranslatorBase", + fn: Callable[..., Any], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + from .builder import VariableBuilder + + args = [x.as_python_constant() for x in args] + kwargs = {k: v.as_python_constant() for k, v in kwargs.items()} + random_call_index = len(tx.output.random_calls) + # NB: it is probably not important for the example_value to be exactly correct, + # we just need the right type + example_value = fn(*args, **kwargs) + source = RandomValueSource(random_call_index) + tx.output.random_calls.append((fn, args, kwargs)) # type: ignore[arg-type] + # TODO: arguably, this should route to wrap_symint/wrap_symfloat + # (currently hypothetical), but I'm not going to poke my hand in + # this nest for now + return VariableBuilder(tx, source).wrap_unspecialized_primitive(example_value) + + +class UserDefinedObjectVariable(UserDefinedVariable): + """ + Mostly objects of defined type. Catch-all for something where we only know the type. + """ + + # VT representing the base built-in type's data for subclassed built-in types + # (e.g., ConstDictVariable for dict subclasses, ListVariable for list subclasses). + # None for plain user-defined objects that don't subclass a built-in container. + _base_vt: VariableTracker | None = None + + # Set of base class methods that can be delegated to _base_vt. + # Used to check whether a method is overridden before delegating. + _base_methods: set[Any] | None = None + + _nonvar_fields = { + "value", + "value_type", + *UserDefinedVariable._nonvar_fields, + } + + def __init__( + self, + value: object, + *, + value_type: type | None = None, + cls_source: TypeSource | None = None, + base_cls_vt: VariableTracker | None = None, + init_args: list[VariableTracker] | None = None, + **kwargs: Any, + ) -> None: + kwargs.pop("tx", None) + super().__init__(**kwargs) + self.value = value + self.value_type = value_type or type(value) + if type(value) is not self.value_type: + raise AssertionError(f"Expected type {self.value_type}, got {type(value)}") + # This is used with __new__, when the new object is sourceless but the user class can be sourceful. + self.cls_source = cls_source + if cls_source is None and self.source is not None: + self.cls_source = TypeSource(self.source) + + # These attributes are used to reconstruct the user defined object. The + # pseudo code looks like this. Builtin C __new__ do not support kwargs, + # so init_args is sufficient. + # obj = base_cls.__new__(user_cls, *args) + self.base_cls_vt = base_cls_vt + self.init_args = init_args + + # Cache inspect.getattr_static outputs for the same name. This is fine + # because if there is a mutation for the name, we use side-effects infra + # to early return the mutated value. + self._looked_up_attrs: dict[str, object] = {} + + # This is to avoid getattr_static calls to look up the subobj from the self.value.__class__ + self._subobj_from_class: dict[str, object] = {} + + import torch.utils._pytree as pytree + + self.is_pytree_constant_class = pytree.is_constant_class(self.value_type) + if pytree.is_constant_class(self.value_type) and self.source: + install_guard(self.source.make_guard(GuardBuilder.EQUALS_MATCH)) + + self._object_has_getattribute = object_has_getattribute(self.value) + + def __str__(self) -> str: + inner = self.value_type.__name__ + if inner in [ + "builtin_function_or_method", + "getset_descriptor", + "method_descriptor", + "method", + ]: + inner = str(getattr(self.value, "__name__", None)) + return f"{self.__class__.__name__}({inner})" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.value_type.__name__})" + + def is_base_vt_modified(self, side_effects: "SideEffects") -> bool: + if self._base_vt is not None: + return side_effects.is_modified(self._base_vt) + return False + + def reconstruct_pycode(self, codegen): + if self.source: + return self.source.reconstruct_pycode(codegen) + raise NotImplementedError( + "Python codegen not implemented yet for sourceless UserDefinedObjectVariable" + ) + + def python_type(self) -> type: + return self.value_type # type: ignore[return-value] + + def get_real_python_backed_value(self) -> object: + return self.value + + def as_python_constant(self) -> object: + from ..utils import is_pybind11_enum_member + + if isinstance( + self.value, + (enum.Enum, torch.DispatchKey, torch._C._functorch.TransformType), + ) or is_pybind11_enum_member(self.value): + return self.value + + from torch.utils._triton import has_triton_package + + if has_triton_package(): + import triton.language as tl + + if isinstance(self.value, tl.constexpr): + return self.value.value + + if self.is_pytree_constant_class and self.source: + # NOTE pytree constants created in the torch.compile region will + # NOT be guarded (even though they have a source set) + return self.value + # TODO else try reconstructing the object by, e.g., leveraging side + # effects and `as_python_constant`. + + # Special case for _MaskModWrapper during legacy export: Dynamo creates + # objects via __new__ without calling __init__, so self.value.fn is unset. + # Reconstruct from the tracked side-effect attribute instead. + from torch.nn.attention.flex_attention import _MaskModWrapper + + if isinstance(self.value, _MaskModWrapper): + from torch._dynamo.symbolic_convert import InstructionTranslator + + tx = InstructionTranslator.current_tx() + if tx is not None and tx.export: + fn_vt = tx.output.side_effects.load_attr(self, "fn", deleted_ok=True) + if fn_vt is not None: + # Let as_python_constant() raise the proper exception + # (e.g., ClosureConversionError for non-constant closures) + fn = fn_vt.as_python_constant() + return _MaskModWrapper(fn) + + return super().as_python_constant() + + def as_proxy(self) -> object: + if isinstance(self.value, enum.Enum): + if isinstance(self.value, int): + return int(self.value) + return self.value + return super().as_proxy() + + def guard_as_python_constant(self) -> object: + if self.source: + install_guard(self.source.make_guard(GuardBuilder.ID_MATCH)) + return self.value + return super().guard_as_python_constant() + + def nb_bool_impl( + self, + tx: "InstructionTranslatorBase", + ) -> "VariableTracker | None": + # Mirrors slot_nb_bool: + # https://github.com/python/cpython/blob/c09ccd9c429/Objects/typeobject.c#L9408-L9458 + res = self._maybe_call_special(tx, "__bool__", []) + type_attr = self.lookup_class_mro_attr("__bool__") + using_len = False + + if type_attr is None: + raise_type_error( + tx, + f"'{self.python_type_name()}' cannot be interpreted as a boolean", + ) + elif res is None: + res = self._maybe_call_special(tx, "__len__", []) + using_len = True + + if res is None: + raise AssertionError("'res' should not be None") + + if using_len: + return generic_is_true(tx, res) + elif res.python_type() is bool: # pybool_check + return res + else: + if sys.version_info >= (3, 15): + err_str = f"{self.python_qualified_name()}.__bool__() must return a bool, not {res.python_qualified_name()}" + else: + err_str = ( + f"__bool__ should return bool, returned {res.python_type_name()}" + ) + + raise_type_error(tx, err_str) + + def tp_repr_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # ref: slot_tp_repr in https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10687-L10698 + if type(self.value).__repr__ is object.__repr__: + return VariableTracker.build(tx, repr(self.value)) + # A C-implemented __repr__ (e.g. `__repr__ = str.upper`) has no Python + # body to trace and graph breaks in _maybe_call_special. + res = self._maybe_call_special(tx, "__repr__", []) + if res is not None: + return res + unimplemented( + gb_type="untraceable user-defined __repr__", + context=f"Could not trace __repr__ override for {type(self.value).__name__}", + explanation="Dynamo could not safely trace this user-defined __repr__ override.", + hints=[*graph_break_hints.SUPPORTABLE], + skip_frame=True, + ) + + def tp_str_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/typeobject.c#L9475 + if type(self.value).__str__ is object.__str__: + return generic_repr(tx, self) + return self.SLOT0(tx, "__str__") + + def nb_index_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: PyNumber_Index checks tp_as_number->nb_index. + return self.SLOT0(tx, "__index__") + + def nb_int_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_int calls __int__(), PyNumber_Long validates the return type. + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1538-L1550 + return self.SLOT0(tx, "__int__") + + def nb_float_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_float calls __float__(), PyNumber_Float validates the return type. + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1647-L1658 + return self.SLOT0(tx, "__float__") + + def nb_negative_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_negative calls __neg__() via vectorcall_method. + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L9361 + return self.SLOT0(tx, "__neg__") + + def nb_positive_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_positive calls __pos__() via vectorcall_method. + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L9361 + return self.SLOT0(tx, "__pos__") + + def nb_absolute_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_absolute calls __abs__() via vectorcall_method. + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L9406 + return self.SLOT0(tx, "__abs__") + + def nb_invert_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_invert calls __invert__() via vectorcall_method. + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L9426 + return self.SLOT0(tx, "__invert__") + + def torch_function_check(self) -> None: + if not has_torch_function(self): + raise AssertionError( + f"calling torch function on object without __torch_function__ {self}" + ) + + def get_torch_fn(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self.torch_function_check() + from .torch_function import get_torch_function_fn + + return get_torch_function_fn(tx, self) + + def call_torch_function( + self, + tx: "InstructionTranslatorBase", + fn: VariableTracker, + types: "TupleVariable", + args: Sequence[Any], + kwargs: dict[str, Any], + ) -> VariableTracker: + self.torch_function_check() + + from .torch_function import call_torch_function + + return call_torch_function( + tx, + self.get_torch_fn(tx), + fn, + types, + args, + kwargs, + ) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9337 + type_attr = self.lookup_class_mro_attr("__contains__") + if type_attr is NO_SUCH_SUBOBJ: + raise_type_error( + tx, + f"'{self.python_type_name()}' object is not iterable", + ) + if type_attr is None: + raise_type_error(tx, f"{self.python_type_name()} is not a container") + + res = self._maybe_call_special(tx, "__contains__", [item]) + if res is None: + # PySequenceIterSearch + PySeqIterSearch = VariableTracker.build( + tx, polyfills.impl_CONTAINS_OP_fallback + ) + res = PySeqIterSearch.call_function(tx, [self, item], {}) + return generic_is_true(tx, res) + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # https://github.com/python/cpython/blob/1ad0eef8ce8ec3db548be89c40fa427494e82814/Objects/typeobject.c#L10517 + return self._vectorcall_method(tx, "__next__", [], {}) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # https://github.com/python/cpython/blob/1ad0eef8ce8ec3db548be89c40fa427494e82814/Objects/typeobject.c#L10496 + type_attr = self.lookup_class_mro_attr("__iter__") + if type_attr is None: + raise_type_error( + tx, + f"'{self.python_type_name()}' object is not iterable", + ) + + res = self._maybe_call_special(tx, "__iter__", []) + has_dunder_getitem = type_attr and type_attr is not NO_SUCH_SUBOBJ + + if res: + return res + + if not has_dunder_getitem: + raise_type_error( + tx, + f"'{self.python_type_name()}' object is not iterable", + ) + + SeqIter = VariableTracker.build(tx, polyfills.builtins.sequence_iterator) + return SeqIter.call_function(tx, [self], {}) + + @staticmethod + @functools.cache + def _supported_random_functions() -> set[Any]: + fns = { + random.random, + random.randint, + random.randrange, + random.uniform, + } + return fns + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9370 + return self.SLOT1(tx, "__getitem__", key) + + def sq_repeat_impl( + self, + tx: "InstructionTranslatorBase", + count: VariableTracker, + ) -> VariableTracker: + method = self._maybe_get_baseclass_method("__mul__") + if ( + self._base_vt is not None + and self._base_methods is not None + and method in self._base_methods + ): + return self._base_vt.sq_repeat_impl(tx, count) + return super().sq_repeat_impl(tx, count) + + def sq_inplace_repeat_impl( + self, + tx: "InstructionTranslatorBase", + count: VariableTracker, + ) -> VariableTracker: + method = self._maybe_get_baseclass_method("__imul__") + if ( + self._base_vt is not None + and self._base_methods is not None + and method in self._base_methods + ): + self._base_vt.sq_inplace_repeat_impl(tx, count) + return self + return super().sq_inplace_repeat_impl(tx, count) + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9373 + if value is None: + return self._vectorcall_method(tx, "__delitem__", [key], {}) + else: + return self._vectorcall_method(tx, "__setitem__", [key, value], {}) + + sq_ass_item_impl = mp_ass_subscript_impl + + def _maybe_lookup_method( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker | None: + type_attr = self.lookup_class_mro_attr(name) + if type_attr is NO_SUCH_SUBOBJ: + # The method doesn't exist + return None + if type_attr is None: + # Method exists but it is set to None + return variables.ConstantVariable.create(None) + source = self.get_source_by_walking_mro(tx, name) if self.source else None + + # C slot wrapper / C method as a dunder: no Python body to trace. + # pybind11 exposes methods as CPython instancemethods wrapping a builtin + # function (e.g. ScriptDict.__repr__); those are equally untraceable, + # detected by a __func__ that is not a Python function. + is_c_special_method = isinstance( + type_attr, (types.WrapperDescriptorType, types.MethodDescriptorType) + ) or ( + torch._C._dynamo.utils.is_instancemethod(type_attr) # type: ignore[attr-defined] + and not isinstance(getattr(type_attr, "__func__", None), types.FunctionType) + ) + if is_c_special_method: + if not ( + self._base_vt is not None + and self._base_methods is not None + and type_attr in self._base_methods + ): + unimplemented( + gb_type="C-implemented special method without VariableTracker model", + context=f"name={name}, type={self.python_type_name()}, attr={type_attr}", + explanation=( + f"'{self.python_type_name()}' implements '{name}' in C " + f"and Dynamo has no model for it." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + if isinstance(type_attr, types.WrapperDescriptorType): + # WrapperDescriptor.tp_descr_get -> MethodWrapper + return variables.MethodWrapperVariable( + type_attr, self._base_vt, source=source + ) + elif isinstance(type_attr, types.MethodDescriptorType): + # MethodDescriptor.tp_descr_get -> BuiltinMethod + return variables.BoundBuiltinMethodVariable( + type_attr, self._base_vt, source=source + ) + + if is_cython_function(type_attr): + raise AssertionError( + f"Cannot trace Cython function {name} on user-defined type {self.python_type_name()}" + ) + elif ( + torch._C._dynamo.utils.is_instancemethod(type_attr) # type: ignore[attr-defined] + or is_data_descriptor(type_attr) + ): + return self.resolve_data_descriptor(tx, name, type_attr, source) + else: + return self.resolve_type_attr(tx, name, type_attr, source) + + def _lookup_method( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + m = self._maybe_lookup_method(tx, name) + if m is None: + raise_type_error( + tx, f"'{self.python_type_name()}' object has no attribute '{name}'" + ) + return m + + def _vectorcall_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Mirror's CPython variant of vectorcall_method. + # NOTE: Dynamo does not IMPLEMENT the vectorcall protocol, but we keep + # the name for consistency with CPython's typeobject.c + m = self._lookup_method(tx, name) + return m.call_function(tx, args, kwargs) + + def _maybe_call_special( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + ) -> VariableTracker | None: + # Mirror's CPython variants of maybe_call_special_no_args and maybe_call_special_one_arg + m = self._maybe_lookup_method(tx, name) + if m is None: + return None + return m.call_function(tx, args, {}) + + def _vectorcall_maybe( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + ) -> VariableTracker: + # Mirrors CPython's vectorcall_maybe: lookup `name` on the type's MRO + # (NOT the instance), bind via the descriptor protocol, and call. + # Returns NotImplemented if the attribute is missing. + # + # Crucially, this must NOT route through `call_method`, since + # `call_method` re-dispatches dunders like __add__ back through + # nb__impl -> SLOT1BIN, causing infinite recursion when the + # type's ____ is a C-implemented slot wrapper that has no + # Python override. + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L2968-L2989 + + m = self._maybe_lookup_method(tx, name) + if m is None: + return variables.ConstantVariable.create(NotImplemented) + return m.call_function(tx, args, {}) + + def SLOT0( + self, + tx: "InstructionTranslatorBase", + dunder: str, + ) -> VariableTracker: + # Mirrors CPython's SLOT0 macro (Objects/typeobject.c). + return self._vectorcall_method(tx, dunder, [], {}) + + def SLOT1( + self, + tx: "InstructionTranslatorBase", + dunder: str, + other: VariableTracker, + ) -> VariableTracker: + # Mirrors CPython's SLOT1 macro (Objects/typeobject.c). + return self._vectorcall_method(tx, dunder, [other], {}) + + def SLOT1BIN( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + dunder: str, + rdunder: str, + nb_slot: int, # NB_OR, NB_AND, etc + reverse: bool, + ) -> VariableTracker: + # Implement SLOT1BIN semantics from CPython + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9202-L9246 + # + # Direct translation of CPython's SLOT1BINFULL macro (Objects/typeobject.c). + # The logic is a bit convoluted, but the main idea remains the same. + # While implementing this I had some questions that might be worth + # answering here: + # + # Q1) What does SLOT1BIN do? + # + # It bridges a C nb_slot to the corresponding Python-level dunder + # methods, handling dispatch order (subclass priority, reflected calls) + # correctly. + # + # Q2) Why does this macro exist? + # + # For built-in types, CPython dispatches binary operations through + # C-level tp_as_number slots (e.g., nb_or). User-defined types don't + # have a native C slot implementation, so CPython installs a wrapper + # function (e.g., slot_nb_or) that maps the C slot interface to the + # Python-level dunder methods (e.g., __or__ / __ror__). SLOT1BINFULL is + # the body of that wrapper. + # + # Q3) Does SLOT1BIN implement the same logic as binary_op1? + # + # Not quite. binary_op1 (Objects/abstract.c) reads C slot pointers and + # dispatches based on pointer identity. SLOT1BINFULL runs *inside* a + # slot call and handles Python-level dispatch (MRO lookup, subclass + # priority, NotImplemented fallthrough). They are complementary layers. + # + # Q4) What types can self and other be? + # + # SLOT1BINFULL is installed as the C slot for Python-defined types, so + # at least one operand always has the slot wrapper (e.g., slot_nb_or). + # The do_other / TESTFUNC checks determine if the *other* operand also + # has a Python-defined slot: + # + # int do_other = !Py_IS_TYPE(self, Py_TYPE(other)) && + # Py_TYPE(other)->tp_as_number != NULL && + # Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; + # if (Py_TYPE(self)->tp_as_number != NULL && + # Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { ... } + # + # TESTFUNC == slot_nb_or (for the | operator), so this is basically + # asking "does this operand's type have a Python-defined dunder?" Native + # C types (e.g., int) fail the check and are skipped. + # + # Q5) Can this cause infinite recursion? + # + # Not if the dunder methods are called directly (MRO lookup + direct + # call), which is what CPython's vectorcall_maybe does. This is + # equivalent to calling a.__or__(b) directly, NOT a | b, which would + # re-enter the C slot layer and loop. + + def py_is_type(w_type: type, v_type: type) -> bool: + return w_type is v_type + + def py_is_subtype(w_type: type, v_type: type) -> bool: + return issubclass(w_type, v_type) + + self_, other_ = (other, self) if reverse else (self, other) + + s_type = self_.python_type() + o_type = other_.python_type() + + # Check if other is a different type and has the number slots + do_other = ( + not py_is_type(s_type, o_type) + and type_implements_nb_slot(o_type, nb_slot) + and isinstance(other_, UserDefinedObjectVariable) + ) + + if isinstance(self_, UserDefinedObjectVariable) and type_implements_nb_slot( + s_type, nb_slot + ): + if do_other and py_is_subtype(o_type, s_type): + # TODO: missing method_is_overloaded + method_is_overloaded = self_._maybe_get_baseclass_method( + rdunder + ) != other_._maybe_get_baseclass_method(rdunder) + if method_is_overloaded: + r = other_._vectorcall_maybe(tx, rdunder, [self_]) + if not is_nb_not_implemented(r): + return r + do_other = False + + r = self_._vectorcall_maybe(tx, dunder, [other_]) + if not is_nb_not_implemented(r) or py_is_type(o_type, s_type): + return r + + if do_other: + if not isinstance(other_, UserDefinedObjectVariable): + raise AssertionError( + f"Expected UserDefinedObjectVariable, got {type(other_)}" + ) + if other_._maybe_get_baseclass_method(rdunder): + r = other_._vectorcall_maybe(tx, rdunder, [self_]) + if not is_nb_not_implemented(r): + return r + + return variables.ConstantVariable.create(NotImplemented) + + def nb_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + return self.SLOT1BIN( + tx, + other, + "__mul__", + "__rmul__", + nb_slot=PyNumberSlots.NB_MULTIPLY, + reverse=reverse, + ) + + def nb_matrix_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + return self.SLOT1BIN( + tx, + other, + "__matmul__", + "__rmatmul__", + nb_slot=PyNumberSlots.NB_MATRIX_MULTIPLY, + reverse=reverse, + ) + + def nb_inplace_matrix_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__imatmul__", other) + + def nb_lshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10337-L10340 + return self.SLOT1BIN( + tx, + other, + "__lshift__", + "__rlshift__", + nb_slot=PyNumberSlots.NB_LSHIFT, + reverse=reverse, + ) + + def nb_inplace_lshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__ilshift__", other) + + def nb_rshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10341-L10344 + return self.SLOT1BIN( + tx, + other, + "__rshift__", + "__rrshift__", + nb_slot=PyNumberSlots.NB_RSHIFT, + reverse=reverse, + ) + + def nb_inplace_rshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__irshift__", other) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10354-L10355 + return self.SLOT1BIN( + tx, + other, + "__or__", + "__ror__", + nb_slot=PyNumberSlots.NB_OR, + reverse=reverse, + ) + + def nb_inplace_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9494 + return self.SLOT1(tx, "__ior__", other) + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9472 (slot_nb_and) + return self.SLOT1BIN( + tx, + other, + "__and__", + "__rand__", + nb_slot=PyNumberSlots.NB_AND, + reverse=reverse, + ) + + def nb_inplace_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__iand__", other) + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9473 (slot_nb_xor) + return self.SLOT1BIN( + tx, + other, + "__xor__", + "__rxor__", + nb_slot=PyNumberSlots.NB_XOR, + reverse=reverse, + ) + + def nb_inplace_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__ixor__", other) + + def nb_add_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10315-L10318 + return self.SLOT1BIN( + tx, + other, + "__add__", + "__radd__", + nb_slot=PyNumberSlots.NB_ADD, + reverse=reverse, + ) + + def nb_inplace_add_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9494 + return self.SLOT1(tx, "__iadd__", other) + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10319-L10322 + return self.SLOT1BIN( + tx, + other, + "__sub__", + "__rsub__", + nb_slot=PyNumberSlots.NB_SUBTRACT, + reverse=reverse, + ) + + def nb_inplace_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10362-L10363 + return self.SLOT1(tx, "__isub__", other) + + def nb_inplace_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__imul__", other) + + def nb_floor_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10323-L10326 + return self.SLOT1BIN( + tx, + other, + "__floordiv__", + "__rfloordiv__", + nb_slot=PyNumberSlots.NB_FLOOR_DIVIDE, + reverse=reverse, + ) + + def nb_inplace_floor_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__ifloordiv__", other) + + def nb_true_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10327-L10330 + return self.SLOT1BIN( + tx, + other, + "__truediv__", + "__rtruediv__", + nb_slot=PyNumberSlots.NB_TRUE_DIVIDE, + reverse=reverse, + ) + + def nb_inplace_true_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__itruediv__", other) + + def nb_remainder_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10331-L10334 + return self.SLOT1BIN( + tx, + other, + "__mod__", + "__rmod__", + nb_slot=PyNumberSlots.NB_REMAINDER, + reverse=reverse, + ) + + def nb_inplace_remainder_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__imod__", other) + + def nb_divmod_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10335-L10336 + return self.SLOT1BIN( + tx, + other, + "__divmod__", + "__rdivmod__", + nb_slot=PyNumberSlots.NB_DIVMOD, + reverse=reverse, + ) + + def nb_power_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + z: VariableTracker | None, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10319-L10322 + if z is not None: + # Ternary pow(x, y, mod): __rpow__ is never called for 3-arg pow. + base, exp = (other, self) if reverse else (self, other) + return base.call_method(tx, "__pow__", [exp, z], {}) + return self.SLOT1BIN( + tx, + other, + "__pow__", + "__rpow__", + nb_slot=PyNumberSlots.NB_POWER, + reverse=reverse, + ) + + def nb_inplace_power_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + z: VariableTracker | None, + ) -> VariableTracker: + return self.SLOT1(tx, "__ipow__", other) + + def nb_power_z_impl( + self, + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + ) -> VariableTracker: + # CPython: type(z)->nb_power(v, w, z) for a Python class calls v.__pow__(w, z). + return v.call_method(tx, "__pow__", [w, self], {}) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .. import trace_rules + from . import UserMethodVariable + from .constant import ConstantVariable + + method = self._maybe_get_baseclass_method(name) + if method is not None: + if method is object.__init__: + return ConstantVariable.create(None) + + if is_standard_setattr(method) or isinstance(self.value, threading.local): + return self.method_setattr_standard(tx, *args, **kwargs) + + if is_standard_delattr(method): + return self.method_setattr_standard( + tx, args[0], variables.DeletedVariable() + ) + + if isinstance(self.value, types.GeneratorType): + unimplemented( + gb_type="call_method on generator", + context=f"object={self.value}, method={name}, args={args}, kwargs={kwargs}", + explanation="Detected a method call to a user-defined generator object. " + "This is not fully supported.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + # torch.Generator methods like manual_seed(), get_state(), etc. + # are stateful RNG operations that cannot be soundly traced. + if ( + isinstance(self.value, torch._C.Generator) + and name in trace_rules._GENERATOR_METHODS_THAT_GRAPH_BREAK + ): + unimplemented( + gb_type="torch.Generator method", + context=f"torch.Generator.{name}", + explanation=f"torch.Generator.{name}() is a stateful RNG " + "operation that cannot be soundly traced in the FX graph.", + hints=[*graph_break_hints.FUNDAMENTAL], + ) + + tp_method = self.lookup_tp_method(name) + if tp_method is not None: + result = tp_method(self, tx, name, args, kwargs) + if result is not None: + return result + + # Delegate to _base_vt for non-overridden base-class methods. + # Skip comparison ops: they go through tp_richcompare_impl on the + # UserDefined*Variable subclass, which handles _base_vt + # unwrapping and avoids tracing tensor elements via list_cmp. + if ( + self._base_vt is not None + and self._base_methods is not None + and method in self._base_methods + and name not in self._slotdefs + ): + return self._base_vt.call_method(tx, name, args, kwargs) + + # check for methods implemented in C++ + if isinstance(method, types.FunctionType): + source = self.source + source_fn = None + if source: + source_fn = self.get_source_by_walking_mro(tx, name) + # TODO(jansel): add a guard to check for monkey patching? + from ..mutation_guard import unpatched_nn_module_init + + if method is torch.nn.Module.__init__: + method = unpatched_nn_module_init + return UserMethodVariable( + method, self, source_fn=source_fn, source=source + ).call_function(tx, args, kwargs) # type: ignore[arg-type] + + if method is list.__len__ and self.source and not (args or kwargs): + install_guard(self.source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + return VariableTracker.build(tx, len(self.value)) # type: ignore[arg-type] + + if trace_rules.is_polyfilled_callable(method): # type: ignore[arg-type] + from .functions import PolyfilledFunctionVariable + + polyfill_handlers = PolyfilledFunctionVariable._get_polyfill_handlers() + wrapped: Any = polyfill_handlers.get(method) # type: ignore[arg-type] + if wrapped is not None: + traceable_fn = wrapped.__torch_dynamo_polyfill__ + return variables.UserMethodVariable( + traceable_fn, self + ).call_function(tx, args, kwargs) + + if name == "__call__": + unimplemented( + gb_type="call to a callable object with no traceable __call__", + context=f"object={self.value}", + explanation="Dynamo could not trace a Python `__call__` method on " + "this object.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + return super().call_method(tx, name, args, kwargs) + + def sq_item_impl( + self, tx: "InstructionTranslatorBase", key: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9294 + return self._vectorcall_method(tx, "__getitem__", [key], {}) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + res = self._vectorcall_method(tx, "__init__", args, kwargs) + if not res.is_constant_none(): + raise_type_error( + tx, f"__init__() should return None, got {res.python_type_name()}" + ) + return res + + def sq_concat_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L10373-L10374 + method = self._maybe_get_baseclass_method("__add__") + if ( + self._base_vt is not None + and self._base_methods is not None + and method in self._base_methods + ): + return self._base_vt.sq_concat_impl(tx, other) + return super().sq_concat_impl(tx, other) + + def sq_inplace_concat_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L10387-L10389 + method = self._maybe_get_baseclass_method("__iadd__") + if ( + self._base_vt is not None + and self._base_methods is not None + and method in self._base_methods + ): + self._base_vt.sq_inplace_concat_impl(tx, other) + return self + return super().sq_inplace_concat_impl(tx, other) + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9266 + res = self._vectorcall_method(tx, "__len__", [], {}) + + # A symbolic length must stay symbolic: coercing it via __index__ / + # PyNumber_AsSsize_t would specialize the shape to a constant and + # defeat dynamic shapes. The runtime non-negativity check is skipped. + if isinstance(res, variables.SymNodeVariable): + return res + + res = pynumber_index(tx, res) + if res.as_python_constant() < 0: + raise_observed_exception( + ValueError, + tx, + args=["__len__() should return >= 0"], + ) + + return pynumber_as_ssize_t(tx, res, OverflowError) + + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9368 + mp_length_impl = sq_length_impl + + def method_setattr_standard( + self, + tx: "InstructionTranslatorBase", + name: VariableTracker, + value: VariableTracker, + ) -> VariableTracker: + name_str = "" + try: + name_str = name.as_python_constant() + except NotImplementedError: + unimplemented( + gb_type="non-const setattr name on user-defined object", + context=f"object={self}, name={name}, value={value}", + explanation="Detected a call to `setattr` of a user-defined object with a non-constant name.", + hints=["Ensure that the name is a string."], + ) + if not tx.output.side_effects.is_attribute_mutation(self): + raise AssertionError( + "Attempted setattr on a user-defined object that does not have " + "an AttributeMutation mutation_type" + ) + + if ( + torch.distributed.is_available() + and type(self.value) is torch.distributed.P2POp + and ( + tx.output.side_effects.has_pending_mutation_of_attr(self, name_str) + or name_str in self.value.__dict__ + ) + ): + unimplemented( + gb_type="P2POp mutation", + context=f"object={self}, name={name}, value={value}", + explanation="Dynamo does not support mutating torch.distributed.P2POp instances.", + hints=[ + "Construct a new torch.distributed.P2POp instead of mutating an existing one inside torch.compile.", + ], + ) + + if name_str == "__class__": + unimplemented( + gb_type="__class__ assignment on user-defined object", + context=f"object={self}, value={value}", + explanation="Dynamo does not support reassigning __class__ on user-defined objects.", + hints=[ + "Move the __class__ assignment outside of the torch.compile region.", + ], + ) + + def raise_cannot_set_attr() -> NoReturn: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object has no attribute '{name_str}'" + ], + ) + + def raise_readonly_attr() -> NoReturn: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object attribute '{name_str}' is read-only" + ], + ) + + def raise_property_error(action: str) -> NoReturn: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"property '{name_str}' of " + f"'{type(self.value).__name__}' object has no {action}" + ], + ) + + descriptor = self.lookup_class_mro_attr(name_str) + if descriptor is not NO_SUCH_SUBOBJ and ( + hasattr(type(descriptor), "__set__") + or hasattr(type(descriptor), "__delete__") + ): + desc_source = None + if self.cls_source: + desc_source = self.get_source_by_walking_mro(tx, name_str) + + if isinstance(descriptor, property): + if isinstance(value, variables.DeletedVariable): + if descriptor.fdel is None: + raise_property_error("deleter") + fdel_source = ( + AttrSource(desc_source, "fdel") if desc_source else None + ) + fdel_var = VariableTracker.build( + tx, descriptor.fdel, source=fdel_source + ) + return fdel_var.call_function(tx, [self], {}) + if descriptor.fset is None: + raise_property_error("setter") + fset_source = AttrSource(desc_source, "fset") if desc_source else None + fset_var = VariableTracker.build( + tx, descriptor.fset, source=fset_source + ) + return fset_var.call_function(tx, [self, value], {}) + + if isinstance(descriptor, types.MemberDescriptorType): + tx.output.side_effects.store_attr(self, name_str, value) + return variables.ConstantVariable.create(None) + + if isinstance(descriptor, types.GetSetDescriptorType): + if name_str == "__dict__": + self.dict_vt = None + # C get/set descriptors are applied by STORE_ATTR itself, so + # replay must stay descriptor-aware rather than using the + # descriptor-bypassing instance-dict or slot paths. + tx.output.side_effects.store_attr(self, name_str, value) + return variables.ConstantVariable.create(None) + + setter = inspect.getattr_static(type(descriptor), "__set__", None) + deleter = inspect.getattr_static(type(descriptor), "__delete__", None) + # collections._tuplegetter (namedtuple field accessor) is a C-level + # data descriptor whose __set__/__delete__ unconditionally raise + # AttributeError. Short-circuit so we don't need to model it. + _tuplegetter = getattr(collections, "_tuplegetter", None) + if _tuplegetter is not None and type(descriptor) is _tuplegetter: + raise_readonly_attr() + desc_var = VariableTracker.build(tx, descriptor, desc_source) + if isinstance(value, variables.DeletedVariable): + if isinstance(deleter, types.FunctionType): + del_source = ( + AttrSource(TypeSource(desc_source), "__delete__") + if desc_source + else None + ) + del_var = VariableTracker.build( + tx, deleter, del_source, realize=True + ) + return del_var.call_function(tx, [desc_var, self], {}) + if deleter is not None: + unimplemented( + gb_type="C-level descriptor delete on user-defined object", + context=f"object={self}, name={name_str}, descriptor={descriptor}", + explanation=( + "Dynamo does not yet model this C-level descriptor deleter " + "for user-defined objects." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + raise_readonly_attr() + if isinstance(setter, types.FunctionType): + set_source = ( + AttrSource(TypeSource(desc_source), "__set__") + if desc_source + else None + ) + set_var = VariableTracker.build(tx, setter, set_source, realize=True) + return set_var.call_function(tx, [desc_var, self, value], {}) + + unimplemented( + gb_type="C-level descriptor setattr on user-defined object", + context=f"object={self}, name={name_str}, descriptor={descriptor}", + explanation=( + "Dynamo does not yet model this C-level descriptor setter " + "for user-defined objects." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if hasattr(self.value, "__dict__"): + dict_vt = self.get_dict_vt(tx) + if isinstance(value, variables.DeletedVariable): + if not dict_vt.contains(name_str): + raise_cannot_set_attr() + dict_vt.delitem(name_str) + else: + dict_vt.setitem(name_str, value) + return variables.ConstantVariable.create(None) + + raise_cannot_set_attr() + + def needs_slow_setattr(self) -> bool: + return not is_standard_setattr( + inspect.getattr_static(self.value, "__setattr__", None) + ) and not isinstance(self.value, threading.local) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return unpack_iterable(tx, self) + + def is_supported_random(self) -> bool: + try: + return self.value in self._supported_random_functions() + except (TypeError, AttributeError): + # TypeError: unhashable type + # AttributeError: backing object may not be fully initialized + return False + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if ( + self.is_supported_random() + and all(k.is_python_constant() for k in args) + and all(v.is_python_constant() for v in kwargs.values()) + ): + return call_random_fn(tx, self.value, args, kwargs) # type: ignore[arg-type] + elif istype(self.value, types.MethodType): + func = self.value.__func__ + obj = self.value.__self__ + if ( + func is torch.utils._contextlib._DecoratorContextManager.clone + and variables.TorchCtxManagerClassVariable.is_matching_cls( + obj.__class__ + ) + and not (args or kwargs) + ): + return variables.TorchCtxManagerClassVariable( + obj.__class__ + ).call_function(tx, args, kwargs) + + if ( + func is torch.autograd.grad_mode.inference_mode.clone + and obj.__class__ is torch.autograd.grad_mode.inference_mode + ): + # simulate the inference_mode.clone implementation + var = VariableTracker.build(tx, obj.mode) # type: ignore[attr-defined] + return variables.TorchCtxManagerClassVariable( + obj.__class__ + ).call_function(tx, [var], kwargs) + + if self.source is None: + unimplemented( + gb_type="attempted to call sourceless user-defined object as a method", + context=f"object={self.value}, function={func}, args={args}, kwargs={kwargs}", + explanation="Dynamo does not support this.", + hints=[ + f"Ensure the user-defined object {self.value} is constructed outside the compiled region.", + ], + ) + if self.source is None: + raise AssertionError("source must not be None for bound method call") + func_src = AttrSource(self.source, "__func__") + func_var = VariableTracker.build(tx, func, func_src, realize=True) + obj_src = AttrSource(self.source, "__self__") + obj_var = VariableTracker.build(tx, obj, obj_src) + return func_var.call_function(tx, [obj_var] + args, kwargs) # type: ignore[arg-type] + elif callable(self.value): + if self.source: + if self.cls_source is None: + raise AssertionError( + "cls_source must not be None for callable with source" + ) + source_attr = AttrSource(self.cls_source, "__call__") + install_guard(source_attr.make_guard(GuardBuilder.CLOSURE_MATCH)) + return self.call_method(tx, "__call__", args, kwargs) # type: ignore[arg-type] + + return super().call_function(tx, args, kwargs) + + def _check_for_getattr(self) -> object: + return get_custom_getattr(self.value) + + def _is_c_defined_property(self, subobj: object) -> bool: + if not isinstance(subobj, property): + return False + + # pybind def_readwrite is implemented via PyCFunction. At the python level, it is visible as a property whose + # fget is an instancemethod wrapper - https://docs.python.org/3/c-api/method.html#c.PyInstanceMethod_Check + + # If we have a PyCFunction, we make an assumption that there is no side effect. + return isinstance( + subobj.fget, types.BuiltinFunctionType + ) or torch._C._dynamo.utils.is_instancemethod(subobj.fget) # type: ignore[attr-defined] + + def _getattr_static(self, name: str) -> object: + if name in self._looked_up_attrs: + return self._looked_up_attrs[name] + + subobj = inspect.getattr_static(self.value, name, NO_SUCH_SUBOBJ) + + # In some cases, we have to do dynamic lookup because getattr_static is not enough. For example, threading.local + # has side-effect free __getattribute__ and the attribute is not visible without a dynamic lookup. + # NOTE we assume the following descriptors are side-effect-free as far + # as Dynamo tracing is concerned. + # + # C-level descriptors (getset_descriptor for __dict__, member_descriptor + # for __slots__) are always safe to resolve — their __get__ is + # implemented in C and doesn't run user code, so __getattribute__ + # overrides are irrelevant. The NO_SUCH_SUBOBJ and + # _is_c_defined_property cases DO require the absence of a custom + # __getattribute__ because they fall back to + # type(self.value).__getattribute__ which could be user-overridden. + if inspect.ismemberdescriptor(subobj) or inspect.isgetsetdescriptor(subobj): + subobj = type(self.value).__getattribute__(self.value, name) + elif not self._object_has_getattribute and ( + subobj is NO_SUCH_SUBOBJ # e.g., threading.local + or self._is_c_defined_property(subobj) + ): + # Call __getattribute__, we have already checked that this is not overridden and side-effect free. We don't + # want to call getattr because it can be user-overridden. + subobj = type(self.value).__getattribute__(self.value, name) + elif self._object_has_getattribute and subobj is NO_SUCH_SUBOBJ: + # If the object has an overridden getattribute method, Dynamo has + # already tried tracing it, and encountered an AttributeError. We + # call getattr_static only when the __getattribute__ tracing fails + # (check tp_getattro_impl impl). So, it is safe here to raise the + # AttributeError. + raise AttributeError + + self._looked_up_attrs[name] = subobj + return subobj + + def lookup_class_mro_attr(self, name: str) -> object: + """Walk type(obj).__mro__ to find *name* in the class hierarchy. + + Cached wrapper around mro_lookup() for UDOV. Only searches the + class chain (type(obj).__mro__), NOT the metaclass chain. + """ + if name in self._subobj_from_class: + return self._subobj_from_class[name] + + result = mro_lookup(type(self.value), name) + self._subobj_from_class[name] = result + return result + + def has_key_in_generic_dict( + self, tx: "InstructionTranslatorBase", key: str + ) -> bool: + if tx.output.side_effects.has_pending_mutation_of_attr( + self, key, AttrMutationKind.INSTANCE_DICT + ): + mutated_attr = tx.output.side_effects.load_attr(self, key, deleted_ok=True) + return not isinstance(mutated_attr, variables.DeletedVariable) + + # TODO(guilhermeleobas): This can trigger a side effect + return key in self.value.__dict__ + + def get_source_by_walking_mro( + self, tx: "InstructionTranslatorBase", name: str + ) -> DictGetItemSource: + if self.cls_source is None: + raise AssertionError("cls_source must not be None for MRO walk") + + for idx, klass in enumerate(type(self.value).__mro__): + if name in klass.__dict__: + descriptor = klass.__dict__[name] + + # Guard that intermediate MRO classes don't shadow this + # attribute, deduplicating by (id(klass), name) across + # subclasses that share the same intermediate MRO class. + # Safe because TYPE_MATCH guards fix the MRO, so the same + # id(klass) always refers to the same class object. + for absent_idx in range(1, idx): + absent_klass = type(self.value).__mro__[absent_idx] + cache_key = (id(absent_klass), name) + if cache_key in tx.output.guarded_mro_absent_keys: + continue + tx.output.guarded_mro_absent_keys.add(cache_key) + mro_source = TypeMROSource(self.cls_source) + klass_source: Source = GetItemSource(mro_source, absent_idx) + dict_source = TypeDictSource(klass_source) + install_guard( + dict_source.make_guard( + functools.partial(GuardBuilder.DICT_NOT_CONTAINS, key=name) + ) + ) + + # Guard that the instance __dict__ does not shadow the + # class attribute. Skipped for data descriptors (those + # with __set__, e.g. property) because Python gives data + # descriptors priority over instance __dict__ in attribute + # lookup — the instance dict can only be populated by + # directly writing to obj.__dict__, not via setattr. + if ( + self.source + and hasattr(self.value, "__dict__") + and name not in self.value.__dict__ + and not hasattr(descriptor, "__set__") + ): + install_guard( + self.source.make_guard( + functools.partial( + GuardBuilder.NOT_PRESENT_IN_GENERIC_DICT, attr=name + ) + ) + ) + + # Reuse the source if we've already resolved the same + # descriptor object for the same attribute name (e.g. same + # property reached via different subclasses) to avoid + # redundant ID_MATCH guards. We include name in the key + # because distinct attributes can point to the same object + # (e.g. a = b = some_obj, or interned small integers). + cache_key = (id(descriptor), name) + cache = tx.output.mro_source_cache + if cache_key in cache: + return cache[cache_key] + + if idx != 0: + mro_source = TypeMROSource(self.cls_source) + klass_source = GetItemSource(mro_source, idx) + else: + klass_source = self.cls_source + dict_source = TypeDictSource(klass_source) + out_source = DictGetItemSource(dict_source, name) + cache[cache_key] = out_source + return out_source + + unimplemented( + gb_type="could not find name in object's mro", + context=f"name={name}, object type={type(self.value)}, mro={type(self.value).__mro__}", + explanation=f"Could not find name `{name}` in mro {type(self.value).__mro__}", + hints=[ + f"Ensure the name `{name}` is defined somewhere in {self.value}'s type hierarchy.", + *graph_break_hints.USER_ERROR, + ], + ) + + def generic_getattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + """Dynamo implementation of CPython's PyObject_GenericGetAttr. + + This mirrors object.__getattribute__ and is called from: + - tp_getattro_impl (for objects without a custom __getattribute__) + - SuperVariable.call_method (when super().__getattribute__() resolves + to object.__getattribute__) + + The algorithm: MRO walk → data descriptor → instance __dict__ → + non-data descriptor / plain class attr → dynamic fallback → + __getattr__ → AttributeError. + """ + source: Source | None = AttrSource(self.source, name) if self.source else None + + if name == "__dict__": + if not hasattr(self.value, "__dict__"): + raise_observed_exception(AttributeError, tx) + return self.get_dict_vt(tx) + + # TODO(anijain2305) - Investigate if we need specialization for more + # dunder attrs. inspect.getattr_static does not return correct value for + # them. + if name == "__class__": + cls_source: Source | None = source + if source is None: + cls_source = self.cls_source + else: + cls_source = source + return VariableTracker.build(tx, type(self.value), cls_source) + + from ..mutation_guard import unpatched_nn_module_init + + # ---- CPython attribute lookup algorithm ---- + # Mirror object.__getattribute__ (PyObject_GenericGetAttr): + # 1. type_attr = lookup name in type(obj).__mro__ + # 2. if type_attr is a DATA descriptor → invoke it + # 3. if name in obj.__dict__ → return as-is (no descriptor invocation) + # 4. if type_attr is a non-data descriptor → invoke it + # 5. if type_attr is a plain class variable → return it + # 6. __getattr__ fallback + # 7. raise AttributeError + # + # Between steps 5 and 6, we also handle objects with custom storage + # that aren't visible via the MRO walk or instance __dict__ (step 5b). + # + # Step 1: Single MRO walk on the type (cached). + type_attr = self.lookup_class_mro_attr(name) + + # Dynamo patches nn.Module.__init__ at import time to inject tracing + # hooks. Undo that here so the unpatched original is traced instead. + if type_attr is torch.nn.Module.__init__: + type_attr = unpatched_nn_module_init + + # Step 2: Data descriptors on the type take priority over instance dict. + if type_attr is not NO_SUCH_SUBOBJ and is_data_descriptor(type_attr): + return self.resolve_data_descriptor(tx, name, type_attr, source) + + # Step 3: Instance __dict__ — return as-is, no descriptor invocation. + result = self.lookup_instance_dict(tx, name) + if result is not None: + return result + + # Step 4-5: Non-data descriptor or plain class attribute. + if type_attr is not NO_SUCH_SUBOBJ: + return self.resolve_type_attr(tx, name, type_attr, source) + + # Step 5b: Dynamic fallback for attributes that exist on the live + # object but aren't visible to the static MRO walk or instance + # __dict__ check above. This covers objects with custom storage + # backends (e.g. threading.local uses a per-thread dict not + # accessible via obj.__dict__) and C extensions that store data + # outside the normal Python object layout. + # + # This is NOT the same as the C-level data descriptor fallback in + # resolve_data_descriptor (step 2): that handles descriptors found + # on the type MRO (like member_descriptor for __slots__), while this + # handles attributes that aren't on the type MRO at all. + # + # Only safe when the class doesn't override __getattribute__, + # otherwise we'd run arbitrary user code. + # Skip if side effects have mutations that supersede the live object. + has_instance_mutations = tx.output.side_effects.has_pending_mutation_of_attr( + self, + name, + (AttrMutationKind.INSTANCE_DICT, AttrMutationKind.GENERIC_SETATTR), + ) or tx.output.side_effects.has_pending_mutation_of_attr( + self, "__dict__", AttrMutationKind.GENERIC_SETATTR + ) + if not self._object_has_getattribute and not has_instance_mutations: + try: + resolved = type(self.value).__getattribute__(self.value, name) + source = self.maybe_wrap_nn_module_source_for_instance(tx, name, source) + return VariableTracker.build(tx, resolved, source) + except AttributeError: + pass + + # Step 6: __getattr__ fallback. + result = self.call_getattr_fallback(tx, name) + if result is not None: + return result + + # Step 7: AttributeError. + raise_observed_exception( + AttributeError, + tx, + args=[f"'{type(self.value).__name__}' object has no attribute '{name}'"], + kwargs={"name": variables.ConstantVariable.create(name), "obj": self}, + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if self._object_has_getattribute: + getattribute_fn = inspect.getattr_static( + type(self.value), "__getattribute__" + ) + new_source: AttrSource | None = ( + AttrSource(self.source, "__getattribute__") if self.source else None + ) + + try: + return variables.UserMethodVariable( + getattribute_fn, + self, + source=new_source, + ).call_function(tx, [VariableTracker.build(tx, name)], {}) + except ObservedAttributeError: + # Pass through to __getattr__ if __getattribute__ fails + handle_observed_exception(tx) + + return self.generic_getattr(tx, name) + + def resolve_data_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + type_attr: object, + source: Source | None, + ) -> VariableTracker: + """Handle data descriptors found on the type MRO (property, _tuplegetter, etc.).""" + # TODO - Check what is this _is_c_defined_property and if this handling should be moved inside the PropertyVariable. + if isinstance(type_attr, property) and not self._is_c_defined_property( + type_attr + ): + # Source points to the descriptor in the class __dict__ via MRO + # walk, not via AttrSource(cls, name) which would trigger the + # descriptor protocol and skip past the property wrapper. + if self.source: + source = self.get_source_by_walking_mro(tx, name) + prop_vt = variables.PropertyVariable(type_attr, source=source) + return prop_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + if isinstance(type_attr, types.MemberDescriptorType): + if tx.output.side_effects.has_pending_mutation_of_attr( + self, name, AttrMutationKind.GENERIC_SETATTR + ): + result = tx.output.side_effects.load_attr(self, name, deleted_ok=True) + if isinstance(result, variables.DeletedVariable): + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object has no attribute '{name}'" + ], + ) + return result + md_vt = variables.MemberDescriptorVariable(type_attr, source=source) + return md_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + + if isinstance(type_attr, types.GetSetDescriptorType): + if tx.output.side_effects.has_pending_mutation_of_attr( + self, name, AttrMutationKind.GENERIC_SETATTR + ): + result = tx.output.side_effects.load_attr(self, name, deleted_ok=True) + if isinstance(result, variables.DeletedVariable): + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object has no attribute '{name}'" + ], + ) + return result + gs_vt = variables.GetSetDescriptorVariable(type_attr, source=source) + return gs_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + + if isinstance(type_attr, _collections._tuplegetter): + tg_vt = variables.TupleGetterVariable(type_attr, source=source) + return tg_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + + get_fn = inspect.getattr_static(type(type_attr), "__get__", None) + if isinstance(get_fn, types.FunctionType): + # User-defined data descriptor with a Python __get__. + return self.invoke_descriptor_get(tx, name, type_attr, source) + + # TODO - Check when are these called - and if we need to create new VTs. + # Remaining C-level data descriptors (Cython attrs, etc.) + # -- resolve via __getattribute__. + try: + resolved = type(self.value).__getattribute__(self.value, name) + except AttributeError: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object has no attribute '{name}'" + ], + ) + return VariableTracker.build(tx, resolved, source) + + def resolve_type_attr( + self, + tx: "InstructionTranslatorBase", + name: str, + type_attr: object, + source: Source | None, + ) -> VariableTracker: + """Handle non-data descriptors and plain class attributes from the type MRO.""" + from ..mutation_guard import unpatched_nn_module_init + + if ( + type_attr is unpatched_nn_module_init + or type_attr is torch.nn.Module.__init__ + ): + type_attr = unpatched_nn_module_init + + can_use_mro_source = self.cls_source is not None and self.source is not None + + if isinstance(type_attr, staticmethod): + # Source points to the descriptor in the class __dict__ via MRO + # walk, not via AttrSource(cls, name) which would trigger the + # descriptor protocol and skip past the staticmethod wrapper. + if can_use_mro_source: + source = self.get_source_by_walking_mro(tx, name) + sm_vt = variables.StaticMethodVariable(type_attr, source=source) + return sm_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + elif isinstance(type_attr, classmethod): + # Source points to the descriptor in the class __dict__ via MRO + # walk, not via AttrSource(cls, name) which would trigger the + # descriptor protocol and skip past the classmethod wrapper. + if can_use_mro_source: + source = self.get_source_by_walking_mro(tx, name) + cm_vt = variables.ClassMethodVariable(type_attr, source=source) + return cm_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + elif isinstance(type_attr, types.ClassMethodDescriptorType): + cmd_vt = variables.ClassMethodDescriptorVariable(type_attr, source=source) + return cmd_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + elif isinstance(type_attr, types.WrapperDescriptorType): + class_vt = self.tp_getattro_impl(tx, "__class__") + wd_vt = variables.WrapperDescriptorVariable( + type_attr, owner=class_vt, source=source + ) + return wd_vt.tp_descr_get_impl(tx, self, class_vt) + elif isinstance(type_attr, types.MethodDescriptorType): + class_vt = self.tp_getattro_impl(tx, "__class__") + md_vt = variables.MethodDescriptorVariable( + type_attr, owner=class_vt, source=source + ) + return md_vt.tp_descr_get_impl(tx, self, class_vt) + elif is_lru_cache_wrapped_function(type_attr): + return variables.WrapperUserMethodVariable( + type_attr, "__wrapped__", self, source=source + ) + elif isinstance(type_attr, types.FunctionType): + while hasattr(type_attr, "_torchdynamo_inline"): + type_attr = type_attr._torchdynamo_inline # type: ignore[union-attr] + source = AttrSource(source, "_torchdynamo_inline") if source else None + # Function on the type MRO + not in instance dict → bound method. + var_source = None + if can_use_mro_source: + var_source = self.get_source_by_walking_mro(tx, name) + return variables.UserMethodVariable( + type_attr, self, source_fn=var_source, source=source + ) + # Check for a Python-level __get__ (non-data descriptor with traceable __get__). + get_fn = inspect.getattr_static(type(type_attr), "__get__", None) + if isinstance(get_fn, types.FunctionType): + return self.invoke_descriptor_get(tx, name, type_attr, source) + + # TODO(tp_descr_get) - Investigate if we need a separate descriptor + # VT for instancemethod and cython functions. + if ( + torch._C._dynamo.utils.is_instancemethod(type_attr) # type: ignore[attr-defined] + or is_cython_function(type_attr) + ): + return variables.GetAttrVariable(self, name, type(type_attr), source=source) + + # Plain class variable (or MethodType, C-level non-data descriptor + # without __get__, etc.). + if can_use_mro_source: + source = self.get_source_by_walking_mro(tx, name) + elif not source and self.cls_source is not None: + source = AttrSource(self.cls_source, name) + return VariableTracker.build(tx, type_attr, source) + + def invoke_descriptor_get( + self, + tx: "InstructionTranslatorBase", + name: str, + descriptor: object, + source: Source | None, + ) -> VariableTracker: + """Trace a descriptor's __get__(instance, owner) call.""" + descriptor_source = None + descriptor_get_source = None + if self.cls_source: + descriptor_source = self.get_source_by_walking_mro(tx, name) + descriptor_get_source = AttrSource(TypeSource(descriptor_source), "__get__") + descriptor_var = VariableTracker.build(tx, descriptor, descriptor_source) + else: + descriptor_var = UserDefinedObjectVariable(descriptor) + + owner_var = UserDefinedClassVariable(type(self.value)) + return variables.UserMethodVariable( + descriptor.__get__.__func__, # type: ignore[union-attr] + descriptor_var, + source=descriptor_get_source, + ).call_function(tx, [self, owner_var], {}) + + def lookup_instance_dict( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker | None: + source: Source | None = AttrSource(self.source, name) if self.source else None + + if tx.output.side_effects.has_pending_mutation_of_attr( + self, + name, + (AttrMutationKind.INSTANCE_DICT, AttrMutationKind.GENERIC_SETATTR), + ): + result = tx.output.side_effects.load_attr(self, name, deleted_ok=True) + if not isinstance(result, variables.DeletedVariable): + return result + return None + + if tx.output.side_effects.has_pending_mutation_of_attr( + self, "__dict__", AttrMutationKind.GENERIC_SETATTR + ): + dict_vt = self.get_dict_vt(tx) + if dict_vt.contains(name): + return dict_vt.getitem(name) + return None + + if hasattr(self.value, "__dict__") and name in self.value.__dict__: + subobj = self.value.__dict__[name] + source = self.maybe_wrap_nn_module_source_for_instance(tx, name, source) + return VariableTracker.build(tx, subobj, source) + + return None + + def call_getattr_fallback( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker | None: + getattr_fn = self._check_for_getattr() + if isinstance(getattr_fn, types.FunctionType): + if ( + getattr_fn is unpatched_nn_module_getattr + and isinstance(self, variables.UnspecializedNNModuleVariable) + and istype(self.value._parameters, dict) # type: ignore[attr-defined] + and istype(self.value._buffers, dict) # type: ignore[attr-defined] + and istype(self.value._modules, dict) # type: ignore[attr-defined] + ): + out = self.manually_trace_nn_module_getattr(tx, name) + else: + new_source = None + if self.source: + new_source = AttrSource(self.source, "__getattr__") + out = variables.UserMethodVariable( + getattr_fn, self, source=new_source + ).call_function(tx, [variables.ConstantVariable.create(name)], {}) + + if self.source and getattr_fn is torch.nn.Module.__getattr__: + if isinstance( + out, + ( + variables.UnspecializedNNModuleVariable, + variables.NNModuleVariable, + ), + ): + out.set_nn_module_stack_source( # type: ignore[attr-defined] + AttrSource(self.get_nn_module_stack_source(), name) # type: ignore[attr-defined] + ) + return out + + elif getattr_fn is not None: + unimplemented( + gb_type="User-defined object with non-function __getattr__", + context=f"object={self.value}, name={name}, getattr_fn={getattr_fn}", + explanation=f"Found a non-function __getattr__ {getattr_fn} from a user-defined object {self.value} " + f" when attempting to getattr `{name}`", + hints=[ + "Ensure the object's __getattr__ is a function type.", + ], + ) + + return None + + def maybe_wrap_nn_module_source_for_instance( + self, + tx: "InstructionTranslatorBase", + name: str, + source: Source | None, + ) -> Source | None: + """Wrap source for nn.Module instance dict attribute access if needed.""" + if ( + source + and isinstance(self, variables.UnspecializedNNModuleVariable) + and (not tx.output.export or torch._dynamo.config.install_free_tensors) + ): + if name in ("_buffers", "_parameters"): + if self.source is None: + raise AssertionError( + "source must not be None for _buffers/_parameters access" + ) + source = UnspecializedParamBufferSource(self.source, name) + source = self._wrap_source(source) + return source + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> "ConstantVariable": + if self.source: + install_guard( + self.source.make_guard( + functools.partial(GuardBuilder.HASATTR, attr=name) + ) + ) + + if not self._object_has_getattribute: + type_attr = self.lookup_class_mro_attr(name) + if ( + (type_attr is NO_SUCH_SUBOBJ or not is_data_descriptor(type_attr)) + and hasattr(self.value, "__dict__") + and not tx.output.side_effects.has_pending_mutation_of_attr( + self, + name, + (AttrMutationKind.INSTANCE_DICT, AttrMutationKind.GENERIC_SETATTR), + ) + and not tx.output.side_effects.has_pending_mutation_of_attr( + self, "__dict__", AttrMutationKind.GENERIC_SETATTR + ) + and self.has_key_in_generic_dict(tx, name) + ): + return variables.ConstantVariable.create(True) + + try: + var_vt = self.tp_getattro_impl(tx, name) + return VariableTracker.build( + tx, not isinstance(var_vt, variables.DeletedVariable) + ) + except ObservedAttributeError: + handle_observed_exception(tx) + return variables.ConstantVariable.create(False) + + def is_hashable(self) -> bool: + # Mirrors the __hash__ is None check in hash_impl's MRO walk. + # Returns "Is this hashable in CPython?", not "can Dynamo trace the hash?". + # Unknown C hashes are hashable but graph-break in hash_impl. + return type(self.value).__hash__ is not None + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # Mirrors CPython's slot_tp_hash which looks up __hash__ via the MRO: + # https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L9521-L9565 + # __hash__ = None → PyObject_HashNotImplemented: + # https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L8066-L8085 + + obj_type = type(self.value) + + # Walk the MRO to find the class that defines __hash__. + for cls in obj_type.__mro__: + if "__hash__" not in cls.__dict__: + continue + type_hash = cls.__dict__["__hash__"] + if type_hash is None: + raise_type_error(tx, f"unhashable type: '{obj_type.__name__}'") + if cls is object: + # object.__hash__ — identity hash, handled below + break + if isinstance(type_hash, types.FunctionType): + # Python __hash__: trace into it via resolve_type_attr. + method_var = self.resolve_type_attr( + tx, "__hash__", type_hash, source=None + ) + result = method_var.call_function(tx, [], {}) + from .constant import FakeIdVariable + + if isinstance(result, FakeIdVariable): + return result.as_python_constant(), True + if isinstance(result, variables.SymNodeVariable): + return int(result.evaluate_expr()), False + # CPython's slot_tp_hash validates PyLong_Check(res): + # https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L9543-L9548 + try: + result_type = result.python_type() + except NotImplementedError: + result_type = None + if result_type is not None and not issubclass(result_type, int): + raise_observed_exception( + TypeError, + tx, + args=[ + f"__hash__ method should return an integer, " + f"not '{result_type.__name__}'" + ], + ) + if not result.is_python_constant(): + unimplemented( + gb_type="Non-constant __hash__ return", + context=f"hash_impl {self}", + explanation=f"__hash__ returned a non-constant " + f"{type(result).__name__}.", + hints=[ + "Ensure that your custom __hash__ function returns an integer.", + *graph_break_hints.USER_ERROR, + ], + ) + return result.as_python_constant(), False + try: + in_allowlist = type_hash in _safe_c_tp_hash_funcs() + except TypeError: + in_allowlist = False + if ( + cls.__module__ == "builtins" + or in_allowlist + or is_pybind11_enum_member(self.value) + ): + # C hash we know is safe to call at trace time. + break + unimplemented( + gb_type="Untraceable C tp_hash", + context=f"hash_impl {self}", + explanation=f"{cls.__name__} defines a C __hash__ that " + f"Dynamo cannot trace into.", + hints=[ + f"Use torch._dynamo.allow_c_slot({cls.__name__}) to " + f"register it as safe if its slots are pure and " + f"deterministic.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + if self._base_vt is not None: + return self._base_vt.hash_impl(tx) + # hash(self.value) calls the real tp_hash — handles both + # object.__hash__ (identity) and builtin-inherited C hashes + # (e.g. IntEnum inheriting int.__hash__). + return hash(self.value), False + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + """MRO walk for tp_richcompare, analogous to slot_tp_richcompare. + + https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9421-L9468 + """ + from .constant import ConstantVariable + from .object_protocol import object_richcompare + + obj_type = type(self.value) + + for cls in obj_type.__mro__: + if op not in cls.__dict__: + continue + + if cls is object: + break + + method = cls.__dict__[op] + + if isinstance(method, types.FunctionType): + resolved = self.resolve_type_attr(tx, op, method, source=None) + if resolved is not None: + # Disable nested graph breaks so that if the user's + # comparison method graph-breaks, it propagates to + # COMPARE_OP (which runs eagerly) instead of splitting + # mid-method. Once PR #179844 lands (which defaults + # allow_nested_graph_breaks=False on + # inline_user_function_return), this override becomes + # unnecessary. + from unittest.mock import patch + + with patch.object( + resolved, "should_allow_nested_graph_breaks", lambda: False + ): + return resolved.call_function(tx, [other], {}) + break + + # C comparison method. If _base_vt exists, it already implements + # this type's C-level comparison (e.g. ConstDictVariable for dict, + # SetVariable for set). Delegate to it instead of constant-folding + # or graph-breaking. + if self._base_vt is not None: + break + + in_allowlist = False + try: + in_allowlist = method in _safe_c_slots() + except TypeError: + pass + if ( + cls.__module__ == "builtins" + or in_allowlist + or is_pybind11_enum_member(self.value) + ): + other_val = other.get_real_python_backed_value() + if other_val is not NO_SUCH_SUBOBJ: + try: + result = method(self.value, other_val) + return ConstantVariable.create(result) + except Exception: + pass + return ConstantVariable.create(NotImplemented) + unimplemented( + gb_type="Untraceable C tp_richcompare", + context=f"tp_richcompare_impl {self} {op}", + explanation=f"{cls.__name__} defines a C comparison method " + f"that Dynamo cannot trace into.", + hints=[ + f"Use torch._dynamo.allow_c_slot({cls.__name__}) to " + f"register it as safe if its comparison methods are pure " + f"and deterministic.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + if self._base_vt is not None: + return self._base_vt.tp_richcompare_impl(tx, other, op) + + return object_richcompare(self, tx, other, op) + + def call_tree_map_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "variables.functions.UserFunctionVariable", + map_fn: "VariableTracker", + rest: "list[VariableTracker]", + tree_map_kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + """Emulate tree_map behavior for user-defined objects. + + In pytree, a type is a leaf if it is NOT in SUPPORTED_NODES. + User-defined objects (that are not registered with register_pytree_node) + are always treated as leaves. This works for both torch.utils._pytree + and optree implementations. + """ + # Determine which tree_map implementation is being used + tree_map_module = getattr(getattr(tree_map_fn, "fn", None), "__module__", "") + is_optree = tree_map_module.startswith("optree") + + if is_optree: + # Check optree's registry - need to handle namespaces + # In optree, types can be registered globally (type in registry) + # or with a namespace ((namespace, type) in registry) + try: + import optree + from optree.registry import _NODETYPE_REGISTRY + + # Check if registered globally + # Namedtuples and structseqs are implicitly pytree nodes + is_registered = ( + self.value_type in _NODETYPE_REGISTRY + or optree.is_namedtuple_class(self.value_type) + or optree.is_structseq_class(self.value_type) + ) + + # Also check if registered with a namespace that's being used + if not is_registered: + namespace_var = tree_map_kwargs.get("namespace") + if namespace_var is not None: + try: + namespace = namespace_var.as_python_constant() + # Check for namespaced registration + is_registered = ( + namespace, + self.value_type, + ) in _NODETYPE_REGISTRY + except NotImplementedError: + # Can't determine namespace at compile time, fall back + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + except ImportError: + # Can't import optree registry, fall back to tracing + import logging + + log = logging.getLogger(__name__) + log.warning( + "Failed to import optree.registry._NODETYPE_REGISTRY, " + "falling back to tracing for tree_map" + ) + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + else: + # Check pytorch's pytree registry + import torch.utils._pytree as pytree + + # Namedtuples and structseqs are implicitly pytree nodes + is_registered = ( + self.value_type in pytree.SUPPORTED_NODES + or pytree.is_namedtuple_class(self.value_type) + or pytree.is_structseq_class(self.value_type) + ) + + # If not registered, it's a leaf and we should apply the map_fn directly + if not is_registered: + return map_fn.call_function(tx, [self, *rest], {}) + + # The type is registered in pytree - we need to fall back to tracing + # the actual tree_map implementation since we don't have the flattening + # logic implemented here + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + + def call_tree_map_with_path_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "variables.functions.UserFunctionVariable", + map_fn: "VariableTracker", + rest: "list[VariableTracker]", + tree_map_kwargs: "dict[str, VariableTracker]", + keypath: "tuple[Any, ...]", + ) -> "VariableTracker": + """Emulate tree_map_with_path behavior for user-defined objects. + + Same logic as call_tree_map_branch but passes keypath to the map function. + """ + tree_map_module = tree_map_fn.get_module() + is_optree = tree_map_module.startswith("optree") + + if is_optree: + try: + import optree + from optree.registry import _NODETYPE_REGISTRY + + is_registered = ( + self.value_type in _NODETYPE_REGISTRY + or optree.is_namedtuple_class(self.value_type) + or optree.is_structseq_class(self.value_type) + ) + + if not is_registered: + namespace_var = tree_map_kwargs.get("namespace") + if namespace_var is not None: + try: + namespace = namespace_var.as_python_constant() + is_registered = ( + namespace, + self.value_type, + ) in _NODETYPE_REGISTRY + except NotImplementedError: + return self._tree_map_with_path_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath, + ) + except ImportError: + return self._tree_map_with_path_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath, + ) + else: + import torch.utils._pytree as pytree + + is_registered = ( + self.value_type in pytree.SUPPORTED_NODES + or pytree.is_namedtuple_class(self.value_type) + or pytree.is_structseq_class(self.value_type) + ) + + if not is_registered: + keypath_var = variables.TupleVariable( + [VariableTracker.build(tx, k) for k in keypath] + ) + return map_fn.call_function(tx, [keypath_var, self, *rest], {}) + + return self._tree_map_with_path_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath, + ) + + +class FrozenDataClassVariable(UserDefinedObjectVariable): + """Frozen dataclass variable for as_proxy/as_python_constant/hashability. + + Construction is handled by the generic polyfill path (tracing through + the auto-generated __init__). Field values are retrieved dynamically + via tp_getattro_impl using InstructionTranslator.current_tx(). + """ + + def _get_field_vt(self, field_name: str) -> VariableTracker: + from torch._dynamo.symbolic_convert import InstructionTranslator + + tx = InstructionTranslator.current_tx() + return self.tp_getattro_impl(tx, field_name) + + def as_python_constant(self) -> object: + from dataclasses import fields + + import torch.utils._pytree as pytree + + if not istype( + self.value, (pytree.TreeSpec, pytree.LeafSpec, pytree.ConstantNode) + ): + raise NotImplementedError( + "currently can't reconstruct arbitrary frozen dataclass instances" + ) + + if istype(self.value, pytree.LeafSpec): + return pytree.treespec_leaf() + + args: list[object] = [] + kwargs: dict[str, object] = {} + for field in fields(self.value): # type: ignore[arg-type] + if field.init: + data = self._get_field_vt(field.name).as_python_constant() + if getattr(field, "kw_only", False): + kwargs[field.name] = data + else: + args.append(data) + + return self.python_type()(*args, **kwargs) + + def as_proxy(self) -> object: + from dataclasses import fields + + args: list[object] = [] + kwargs: dict[str, object] = {} + for field in fields(self.value): # type: ignore[arg-type] + proxy = self._get_field_vt(field.name).as_proxy() + if hasattr(field, "kw_only") and field.kw_only: + kwargs[field.name] = proxy + else: + args.append(proxy) + + return self.python_type()(*args, **kwargs) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.source is not None: + codegen(self.source) + return + codegen.append_output( + codegen.create_load_const_unchecked(self.as_python_constant()) + ) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.value_type.__name__})" + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # The fast path below replicates CPython's *generated* frozen dataclass + # __hash__ (hash(tuple(field_values))). A frozen dataclass may instead + # define a custom __hash__ (e.g. the PyTreeSpec polyfill); dataclasses + # synthesizes the generated one via exec (co_filename ""), so a + # __hash__ from a real source file is custom -- defer to the general + # MRO-walking hash_impl, which traces it. + type_hash = type(self.value).__hash__ + if ( + isinstance(type_hash, types.FunctionType) + and type_hash.__code__.co_filename != "" + ): + return super().hash_impl(tx) + + # CPython's frozen dataclass __hash__ is generated by _hash_add: + # https://github.com/python/cpython/blob/e76aa128fe/Lib/dataclasses.py#L886-L892 + # It computes hash(tuple(field_values)), i.e. tuplehash applied to + # field values. Use RawHash to bypass int.__hash__'s modular reduction. + from dataclasses import fields as dc_fields + + from .hashable import RawHash + from .object_protocol import generic_hash_impl + + is_fake = False + raw_hashes = [] + for f in dc_fields(self.value): # type: ignore[arg-type] + h, fake = generic_hash_impl(tx, self._get_field_vt(f.name)) + is_fake = is_fake or fake + raw_hashes.append(RawHash(h)) + return hash(tuple(raw_hashes)), is_fake + + +class SourcelessGraphModuleVariable(UserDefinedObjectVariable): + def __init__( + self, + value: object, + **kwargs: Any, + ) -> None: + super().__init__(value, **kwargs) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fn_variable = VariableTracker.build(tx, self.value.forward.__func__) # type: ignore[attr-defined] + args = [self] + args + return tx.inline_user_function_return( + fn_variable, + args, + kwargs, + ) + + +class UserDefinedExceptionObjectVariable(UserDefinedObjectVariable): + def __init__(self, value: object, **kwargs: Any) -> None: + super().__init__(value, **kwargs) + init_args = kwargs.get("init_args", []) + self._base_vt = variables.ExceptionVariable(self.value_type, init_args) + self._base_methods = ( + base_exception_methods + if isinstance(value, BaseException) + else exception_methods + ) + + @property + def fn(self) -> Callable[..., object]: + return self.value_type + + @property + def exc_vt(self) -> "variables.ExceptionVariable": + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for exception repr") + return cast(variables.ExceptionVariable, self._base_vt) + + def _with_traceback( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker], kwargs + ) -> "VariableTracker": + return self._base_vt.call_method(tx, "with_traceback", args, kwargs) # type: ignore[missing-attribute] + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # __setattr__ is the tp_setattro slot, not dispatched through tp_methods, + # so handle it here (mirroring ExceptionVariable.call_method) to route + # writes of __cause__/__context__/__suppress_context__/__traceback__ to + # the wrapped base exception VT. Without this, `raise X from Y` never + # records X.__cause__ (issue: contextlib exception-chaining repro). + if ( + name == "__setattr__" + and len(args) == 2 + and args[0].is_constant_match( + "__cause__", "__context__", "__suppress_context__", "__traceback__" + ) + ): + return self._base_vt.call_method(tx, "__setattr__", args, kwargs) # type: ignore[missing-attribute] + return super().call_method(tx, name, args, kwargs) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Inherited C exception __init__ (BaseException.__init__, a method + # descriptor) is a no-op here; args are captured via __new__. Mirrors + # call_method's __init__ handling. + method = self._maybe_get_baseclass_method("__init__") + if method and inspect.ismethoddescriptor(method) and len(kwargs) == 0: + return variables.ConstantVariable.create(None) + return super().tp_init_impl(tx, args, kwargs) + + tp_methods = { + "with_traceback": Method(_with_traceback), + } + + # BaseException args/__cause__/__context__/__suppress_context__/__traceback__ + # are members/getsets; delegate each to the wrapped base exception VT. + tp_members = { + "args": Member(lambda s, tx: s._base_vt.tp_getattro_impl(tx, "args")), + "__cause__": Member(lambda s, tx: s._base_vt.tp_getattro_impl(tx, "__cause__")), + "__context__": Member( + lambda s, tx: s._base_vt.tp_getattro_impl(tx, "__context__") + ), + "__suppress_context__": Member( + lambda s, tx: s._base_vt.tp_getattro_impl(tx, "__suppress_context__") + ), + "__traceback__": Member( + lambda s, tx: s._base_vt.tp_getattro_impl(tx, "__traceback__") + ), + } + + @property + def __context__(self) -> "ConstantVariable": + return self._base_vt.__context__ # type: ignore[missing-attribute] + + @property + def args(self) -> list[VariableTracker]: + return self._base_vt.args # type: ignore[missing-attribute] + + def set_context(self, context: "variables.ExceptionVariable") -> None: + return self._base_vt.set_context(context) # type: ignore[missing-attribute] + + @property + def exc_type(self) -> type[BaseException]: + return self._base_vt.exc_type # type: ignore[missing-attribute] + + @property + def python_stack(self) -> traceback.StackSummary | None: + return self._base_vt.python_stack # type: ignore[missing-attribute] + + def debug_repr(self) -> str: + return self.exc_vt.debug_repr() + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # ref: BaseException_repr in https://github.com/python/cpython/blob/3.13/Objects/exceptions.c#L135-L142 + if type(self.value).__repr__ is not BaseException.__repr__: + return super().tp_repr_impl(tx) + return self.exc_vt.tp_repr_impl(tx) + + def tp_str_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # ref: BaseException_str in https://github.com/python/cpython/blob/3.13/Objects/exceptions.c#L118-L129 + if type(self.value).__str__ is not BaseException.__str__: + return super().tp_str_impl(tx) + return self.exc_vt.tp_str_impl(tx) + + @python_stack.setter + def python_stack(self, value: traceback.StackSummary) -> None: + self._base_vt.python_stack = value # type: ignore[missing-attribute] + + +class InspectVariable(UserDefinedObjectVariable): + """Handles inspect.Signature and inspect.Parameter objects. + + Short-circuits property accesses to avoid tracing property getters, + redirecting them to the underlying private attributes directly. + """ + + _PROPERTY_REDIRECTS: dict[type, dict[str, str]] = { + inspect.Signature: {"parameters": "_parameters"}, + inspect.Parameter: {"kind": "_kind", "name": "_name"}, + } + + @staticmethod + def is_matching_object(obj: object) -> bool: + return type(obj) in InspectVariable._PROPERTY_REDIRECTS + + @staticmethod + def is_matching_class(obj: object) -> bool: + return obj in InspectVariable._PROPERTY_REDIRECTS + + def _redirect( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker | None: + redirects = self._PROPERTY_REDIRECTS.get(type(self.value), {}) + if name in redirects: + return super().tp_getattro_impl(tx, redirects[name]) + return None + + def _parameters(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + return self._redirect(tx, "parameters") + + def _kind(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + return self._redirect(tx, "kind") + + def _name(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + return self._redirect(tx, "name") + + # inspect.Signature.parameters and inspect.Parameter.name/.kind are Python + # `property` objects (getset-like). Redirect to the private backing slots to + # avoid tracing the property getters. The redirect is per-type, so a getter + # declines (returns None) when the attribute doesn't apply to self.value. + tp_getset = { + "parameters": GetSet(_parameters, None), + "kind": GetSet(_kind, None), + "name": GetSet(_name, None), + } + + +class KeyedJaggedTensorVariable(UserDefinedObjectVariable): + @staticmethod + def is_matching_object(obj: object) -> bool: + mod = sys.modules.get("torchrec.sparse.jagged_tensor") + return mod is not None and type(obj) is mod.KeyedJaggedTensor + + def __init__(self, value: object, **kwargs: Any) -> None: + from torchrec.sparse.jagged_tensor import ( # type: ignore[import-not-found] + KeyedJaggedTensor, + ) + + if type(value) is not KeyedJaggedTensor: + raise AssertionError(f"Expected KeyedJaggedTensor, got {type(value)}") + super().__init__(value, **kwargs) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if ( + torch._dynamo.config.force_unspec_int_unbacked_size_like_on_torchrec_kjt + and self.source is not None + and name in ("_length_per_key", "_offset_per_key") + ): + with TracingContext.patch(force_unspec_int_unbacked_size_like=True): + return super().tp_getattro_impl(tx, name) + return super().tp_getattro_impl(tx, name) + + +_CONSTANT_BASE_TYPES = (int, float, str) + +_constant_base_methods: dict[type, set[Any]] = { + t: {m for m in t.__dict__.values() if callable(m)} for t in _CONSTANT_BASE_TYPES +} + + +class UserDefinedConstantVariable(UserDefinedObjectVariable): + """ + Represents user-defined objects that subclass immutable constant types + (int, float, str). + + Uses a ConstantVariable as _base_vt for the underlying constant value. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + from .constant import ConstantVariable + + super().__init__(value, **kwargs) + for base in type(value).__mro__: + if base in _CONSTANT_BASE_TYPES: + self._base_vt = ConstantVariable.create(base(value)) + self._base_methods = _constant_base_methods[base] + break + if self._base_vt is None: + raise AssertionError(f"No constant base type found in MRO of {type(value)}") + + def as_python_constant(self) -> Any: + return self.value + + def as_proxy(self) -> object: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in as_proxy") + return self._base_vt.as_proxy() + + +class IntWrapperVariable(UserDefinedObjectVariable): + # Dummy class to check if the object is an IntWrapper, and turn it into a + # symint + @staticmethod + def is_matching_object(obj: object) -> bool: + mod = sys.modules.get("torch.export.dynamic_shapes") + return mod is not None and type(obj) is mod._IntWrapper + + +class RemovableHandleVariable(VariableTracker): + REMOVED = -1 + + def __init__( + self, + mutation_type: MutationType | None = None, + # index of the registration in the side_effects owned register_hook/handle list, used during removal. + idx: int | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.mutation_type = mutation_type + self.idx = idx + + def remove( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.idx != self.REMOVED: + if self.idx is None: + raise AssertionError("idx must not be None for hook removal") + tx.output.side_effects.remove_hook(self.idx) + self.idx = self.REMOVED + return variables.ConstantVariable.create(None) + + tp_methods = {"remove": Method(remove)} + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.idx == self.REMOVED: + # Hook has already been removed, return a dummy handle + codegen.add_push_null( + lambda: codegen.load_import_from( + "torch._dynamo.utils", "invalid_removeable_handle" + ) + ) + codegen.extend_output(create_call_function(0, False)) + return + # unreachable due to codegen.add_cache() when the hook is installed + super().reconstruct(codegen) + + def python_type(self) -> type[object]: + return RemovableHandleClass + + +class UserDefinedDictVariable(UserDefinedObjectVariable): + """ + Represents user defined objects that are subclasses of dict/OrderedDict. + + Internally, it uses a ConstDictVariable to represent the dict part of the + variable tracker. For everything else, it falls back to + UserDefinedObjectVariable. + """ + + def __init__( + self, + value: object, + dict_vt: ConstDictVariable | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value, **kwargs) + if dict_vt is None: + if self.source is not None: + raise AssertionError( + "dict_vt must be constructed by builder.py when source is present" + ) + # OrderedDict subclasses need an OrderedDict-backed store so + # move_to_end / popitem(last=) delegate correctly. + base_cls = ( + OrderedDictVariable + if isinstance(value, collections.OrderedDict) + else ConstDictVariable + ) + self._base_vt = base_cls( + {}, + mutation_type=ValueMutationNew(), + ) + else: + self._base_vt = dict_vt + self._base_methods = dict_methods + if self._base_vt is None: + raise AssertionError("_base_vt must not be None after initialization") + + def len(self) -> int: + # Used by nn_module.py to short-circuit the nn.Module forward method + # when no hooks are registered. Calling .len() directly avoids the + # overhead of full call_method("__len__") dispatch during tracing. + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in len") + return self._base_vt.len() # type: ignore[union-attr] + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # Dict implements __len__ via mp_length (mapping protocol), not + # sq_length (sequence protocol). Redirect so generic_size works. + return self.mp_length_impl(tx) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # dict_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/dictobject.c#L3673-L3706 + # TODO(follow-up): add test for unhashable/invalid key type, Counter missing key + method = self._maybe_get_baseclass_method("__getitem__") + if method in self._base_methods: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in mp_subscript_impl") + try: + return self._base_vt.mp_subscript_impl(tx, key) + except ObservedKeyError: + if issubclass( + self.python_type(), dict + ) and self._maybe_get_baseclass_method("__missing__"): + return self.call_method(tx, "__missing__", [key], {}) + else: + raise + return super().mp_subscript_impl(tx, key) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Inherited dict/OrderedDict __init__ populates the underlying storage + # (CPython dict_init == dict.update); route to _base_vt so content is + # not lost. defaultdict.__init__'s first arg is the default_factory and + # has its own path. Mirrors call_method's __init__ handling. + if self._maybe_get_baseclass_method("__init__") in ( + dict.__init__, + collections.OrderedDict.__init__, + ): + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in tp_init_impl") + self._base_vt.call_method(tx, "update", args, kwargs) + return variables.ConstantVariable.create(None) + return super().tp_init_impl(tx, args, kwargs) + + def debug_repr(self) -> str: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for dict repr") + base_vt = cast(ConstDictVariable, self._base_vt) + if type(self.value).__repr__ is collections.Counter.__repr__: + items = list(base_vt.items.items()) + try: + items = sorted( + items, + key=lambda item: item[1].as_python_constant(), + reverse=True, + ) + except (NotImplementedError, TypeError): + pass + if not items: + return f"{type(self.value).__name__}()" + contents = ", ".join( + f"{key.vt.debug_repr()}: {value.debug_repr()}" for key, value in items + ) + return f"{type(self.value).__name__}({{{contents}}})" + return base_vt.debug_repr() + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # https://github.com/python/cpython/blob/3.13/Lib/collections/__init__.py#L748-L757 + method = self._maybe_get_baseclass_method("__repr__") + if type(self.value).__repr__ is collections.Counter.__repr__: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for Counter repr") + base_vt = cast(ConstDictVariable, self._base_vt) + items = list(base_vt.items.items()) + try: + items = sorted( + items, + key=lambda item: item[1].as_python_constant(), + reverse=True, + ) + except (NotImplementedError, TypeError): + pass + if not items: + return VariableTracker.build(tx, f"{type(self.value).__name__}()") + contents = ", ".join( + f"{tracked_repr(tx, key.vt)}: {tracked_repr(tx, value)}" + for key, value in items + ) + return VariableTracker.build( + tx, f"{type(self.value).__name__}({{{contents}}})" + ) + if method in self._base_methods: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for dict repr") + return self._base_vt.tp_repr_impl(tx) + return super().tp_repr_impl(tx) + + +# TODO: move to dicts.py alongside ConstDictVariable. +# Currently blocked by circular imports (dicts.py ↔ user_defined.py). +class DefaultDictVariable(UserDefinedDictVariable): + """ + Represents collections.defaultdict instances. + + CPython's defaultdict is implemented in C: + https://github.com/python/cpython/blob/v3.13.3/Modules/_collectionsmodule.c#L2177-L2180 + + default_factory is a field on the C struct (defdictobject.default_factory), + not a Python instance attribute, so we model it as a field on the VT. + + Dict storage is delegated to _base_vt (a ConstDictVariable) via + UserDefinedDictVariable. + """ + + _cpython_type = collections.defaultdict + + def __init__( + self, + value: object, + default_factory: VariableTracker | None = None, + dict_vt: ConstDictVariable | None = None, + **kwargs: Any, + ) -> None: + if dict_vt is None: + from .dicts import ConstDictVariable + + dict_vt = ConstDictVariable( + {}, + mutation_type=ValueMutationNew(), + ) + super().__init__(value, dict_vt=dict_vt, **kwargs) + if default_factory is None: + from .constant import ConstantVariable + + default_factory = ConstantVariable.create(None) + self.default_factory = default_factory + + @staticmethod + def is_supported_factory(arg: VariableTracker) -> bool: + """Check if arg is a valid default_factory (callable or None). + + CPython's defaultdict.__init__ checks ``callable(factory)`` and + raises TypeError if not. We mirror this by checking the + underlying Python value when possible. + """ + val = arg.get_real_python_backed_value() + if val is not NO_SUCH_SUBOBJ: + return val is None or callable(val) + # Callables (functions, builtins, classes) are supported + return isinstance( + arg, + ( + variables.BaseBuiltinVariable, + variables.functions.BaseUserFunctionVariable, + variables.functions.PolyfilledFunctionVariable, + variables.UserDefinedClassVariable, + ), + ) + + def is_python_constant(self) -> bool: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for defaultdict const") + if not self.default_factory.is_python_constant(): + return False + return self._base_vt.is_python_constant() + + def as_python_constant(self) -> Any: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for defaultdict const") + if not self.default_factory.is_python_constant(): + raise AsPythonConstantNotImplementedError( + self, + "defaultdict default_factory is not a Python constant", + ) + factory = self.default_factory.as_python_constant() + return collections.defaultdict(factory, self._base_vt.as_python_constant()) + + def debug_repr(self) -> str: + if self.default_factory is None: + raise AssertionError("default_factory must not be None in debug_repr") + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in debug_repr") + return ( + f"defaultdict({self.default_factory.debug_repr()}, " + f"{self._base_vt.debug_repr()})" + ) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # https://github.com/python/cpython/blob/3.13/Modules/_collectionsmodule.c#L2373-L2405 + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for defaultdict repr") + return VariableTracker.build( + tx, + f"{self.python_type_name()}({tracked_repr(tx, self.default_factory)}, " + f"{tracked_repr(tx, self._base_vt)})", + ) + + # ref: defdict_members[] in CPython Modules/_collectionsmodule.c + # {"default_factory", T_OBJECT, offsetof(defdictobject, default_factory)} + tp_members = { + "default_factory": Member(getset_read(lambda s: s.default_factory)), + } + + def _missing_impl( + self, + tx: "InstructionTranslatorBase", + key: "VariableTracker", + ) -> "VariableTracker": + """defaultdict.__missing__: auto-vivification via default_factory. + + https://github.com/python/cpython/blob/v3.13.3/Modules/_collectionsmodule.c#L2233-L2254 + """ + from .constant import ConstantVariable + + if ( + istype(self.default_factory, ConstantVariable) + and self.default_factory.value is None + ): + raise_observed_exception(KeyError, tx, args=[key]) + default_var = self.default_factory.call_function(tx, [], {}) + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in _missing_impl") + self._base_vt.call_method(tx, "__setitem__", [key, default_var], {}) + return default_var + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: "VariableTracker", + ) -> "VariableTracker": + """defaultdict.__getitem__: dict lookup with __missing__ fallback.""" + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in mp_subscript_impl") + if key in self._base_vt: # type: ignore[operator] + return self._base_vt.getitem_const(tx, key) # type: ignore[union-attr] + return self._missing_impl(tx, key) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L2356-L2395 + # The C impl uses a naming convention of left/right for the two operands + # and swap self/other depending on some conditions. For simplicity, we + # will suffix the var names with "_" + + # new_defdict(self, left) calls type(self)(self.default_factory, left), + # then PyDict_Update(new, right). left/right are the original operands. + left, right = (other, self) if reverse else (self, other) + ret = issubclass(left.python_type(), collections.defaultdict) + self_, other_ = (left, right) if ret else (right, left) + if not isinstance(self_, DefaultDictVariable): + raise AssertionError(f"Expected DefaultDictVariable, got {type(self_)}") + + if not pydict_check(other_): + return variables.ConstantVariable.create(NotImplemented) + + if isinstance(left, ConstDictVariable): + items = left.items + else: + if not isinstance(left, UserDefinedDictVariable): + raise AssertionError( + f"Expected UserDefinedDictVariable, got {type(left)}: {left}" + ) + items = left._base_vt.items # type: ignore[missing-attribute] + + new = tx.output.side_effects.track_new_user_defined_object( + VariableTracker.build(tx, dict), + VariableTracker.build(tx, collections.defaultdict), + [], + tx=tx, + ) + new.default_factory = self.default_factory # type: ignore[missing-attribute] + new._base_vt = ConstDictVariable(items.copy(), mutation_type=ValueMutationNew()) # type: ignore[missing-attribute] + default_factory = new.default_factory # type: ignore[missing-attribute] + tx.output.side_effects.store_attr(new, "default_factory", default_factory) + new.call_method(tx, "update", [right], {}) + return new + + def nb_inplace_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + self.call_method(tx, "update", [other], {}) + return self + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # defaultdict.__init__(self, default_factory=None, *args, **kwargs) + # https://github.com/python/cpython/blob/v3.13.3/Modules/_collectionsmodule.c#L2072 + # Extract default_factory, delegate rest to dict.__init__ + if len(args) >= 1: + if self.is_supported_factory(args[0]): + self.default_factory = args[0] + tx.output.side_effects.store_attr( + self, + "default_factory", + self.default_factory, + ) + args = list(args[1:]) + else: + # CPython raises TypeError for non-callable first arg + raise_observed_exception( + TypeError, + tx, + args=["first argument must be callable or None"], + ) + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in __init__") + return self._base_vt.call_method(tx, "__init__", args, kwargs) + + def _getitem( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker], kwargs + ) -> "VariableTracker": + if len(args) != 1: + raise_args_mismatch(tx, "__getitem__", "1 args", f"{len(args)} args") + return self.mp_subscript_impl(tx, args[0]) + + def _missing( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker], kwargs + ) -> "VariableTracker": + if len(args) != 1: + raise_args_mismatch(tx, "__missing__", "1 args", f"{len(args)} args") + return self._missing_impl(tx, args[0]) + + def _copy( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker], kwargs + ) -> "VariableTracker": + # defaultdict.copy() / copy.copy(dd) both create a new defaultdict + # https://github.com/python/cpython/blob/6280bb547840b609feedb78887c6491af75548e8/Modules/_collectionsmodule.c#L2290-L2293 + from .builder import SourcelessBuilder + + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in copy") + new_dd = tx.output.side_effects.track_new_user_defined_object( + SourcelessBuilder.create(tx, dict), + SourcelessBuilder.create(tx, collections.defaultdict), + [], + tx=tx, + ) + if not isinstance(new_dd, DefaultDictVariable): + raise AssertionError(f"Expected DefaultDictVariable, got {type(new_dd)}") + new_dd.default_factory = self.default_factory + new_dd._base_vt = self._base_vt.clone( + mutation_type=ValueMutationNew(), + source=None, + ) + tx.output.side_effects.store_attr( + new_dd, "default_factory", new_dd.default_factory + ) + return new_dd + + # __ior__ and __setattr__ are C-level slots (nb_inplace_or, tp_setattro), + # so they are handled in call_method rather than declared in tp_methods. + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .constant import ConstantVariable + + if name == "__setattr__": + if len(args) != 2: + raise_args_mismatch(tx, name, "2 args", f"{len(args)} args") + if ( + istype(args[0], ConstantVariable) and args[0].value == "default_factory" + ) and self.is_supported_factory(args[1]): + self.default_factory = args[1] + tx.output.side_effects.store_attr( + self, "default_factory", self.default_factory + ) + return ConstantVariable.create(None) + return super().call_method(tx, name, args, kwargs) + + tp_methods = { + "__getitem__": Method(_getitem), + "__missing__": Method(_missing), + "copy": Method(_copy), + "__copy__": Method(_copy), + } + + +class UserDefinedSetVariable(UserDefinedObjectVariable): + """ + Represents user defined objects that are subclasses of set. + + Internally, it uses a SetVariable to represent the set part of the + variable tracker. For everything else, it falls back to + UserDefinedObjectVariable. + """ + + def __init__( + self, value: object, set_vt: SetVariable | None = None, **kwargs: Any + ) -> None: + from .builder import SourcelessBuilder + + tx = kwargs.pop("tx", None) + super().__init__(value, **kwargs) + + python_type = set if isinstance(value, set) else frozenset + self._base_methods = set_methods if python_type is set else frozenset_methods + + if set_vt is None: + if self.source is not None: + raise AssertionError( + "set_vt must be constructed by builder.py when source is present" + ) + if python_type is set: + # set is initialized later + self._base_vt = variables.SetVariable( + set(), + mutation_type=ValueMutationNew(), + ) + else: + init_args = kwargs.get("init_args", {}) + self._base_vt = SourcelessBuilder.create(tx, python_type).call_function( # type: ignore[assignment] + tx, init_args, {} + ) + else: + self._base_vt = set_vt + if self._base_vt is None: + raise AssertionError("_base_vt must not be None after initialization") + + def as_python_constant(self) -> object: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in as_python_constant") + return self._base_vt.as_python_constant() + + @property + def set_items(self) -> set[Any]: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in set_items") + return self._base_vt.set_items # pyrefly: ignore[missing-attribute] + + @property + def items(self) -> dict[HashableTracker, VariableTracker]: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in items") + return self._base_vt.items # pyrefly: ignore[missing-attribute] + + +class UserDefinedListVariable(UserDefinedObjectVariable): + """ + Represents user defined objects that are subclasses of lists. + + Internally, it uses a ListVariable to represent the list part of the + variable tracker. For everything else, it falls back to + UserDefinedObjectVariable. + """ + + def __init__( + self, value: object, list_vt: Union["ListVariable", None] = None, **kwargs: Any + ) -> None: + from .lists import ListVariable + + super().__init__(value, **kwargs) + if list_vt is None: + if self.source is not None: + raise AssertionError( + "list_vt must be constructed by builder.py when source is present" + ) + self._base_vt = ListVariable([], mutation_type=ValueMutationNew()) + else: + self._base_vt = list_vt + self._base_methods = list_methods + if self._base_vt is None: + raise AssertionError("_base_vt must not be None after initialization") + + +class UserDefinedDequeVariable(UserDefinedObjectVariable): + """ + Represents user defined objects that are subclasses of collections.deque. + + Internally, it uses a DequeVariable to represent the deque part of the + variable tracker. For everything else, it falls back to + UserDefinedObjectVariable. + """ + + def __init__( + self, + value: object, + deque_vt: Union["variables.lists.DequeVariable", None] = None, + **kwargs: Any, + ) -> None: + from .lists import DequeVariable + + super().__init__(value, **kwargs) + if deque_vt is None: + if self.source is not None: + raise AssertionError( + "deque_vt must be constructed by builder.py when source is present" + ) + self._base_vt = DequeVariable([], mutation_type=ValueMutationNew()) + else: + self._base_vt = deque_vt + self._base_methods = deque_methods + if self._base_vt is None: + raise AssertionError("_base_vt must not be None after initialization") + + def _maxlen(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + # maxlen is a read-only getset on deque, not a method, so it is not + # covered by the _base_methods call_method delegation; route it to the + # DequeVariable which tracks maxlen on the base deque. + if self._base_vt is not None: + return self._base_vt.tp_getattro_impl(tx, "maxlen") + return None + + # ref: deque_getset[] in CPython Modules/_collectionsmodule.c; maxlen is a + # read-only getset (deque_get_maxlen, no setter). + tp_getset = { + "maxlen": GetSet(_maxlen, None), + } + + +class UserDefinedTupleVariable(UserDefinedObjectVariable): + """ + Represents user defined objects that are subclasses of tuple. + + Internally, it uses a TupleVariable to represent the tuple part of the + variable tracker. For everything else, it falls back to + UserDefinedObjectVariable. + + NamedTupleVariable and StructSequenceVariable are subclasses that handle + namedtuples and structseqs (torch.return_types.*) respectively. + """ + + _nonvar_fields = { + "tuple_cls", + *UserDefinedObjectVariable._nonvar_fields, + } + + @staticmethod + def get_vt_cls(cls: type) -> type["UserDefinedTupleVariable"]: + if is_structseq_class(cls): + return StructSequenceVariable + return NamedTupleVariable + + def __init__(self, value, tuple_vt=None, init_args=None, **kwargs): # type: ignore[all] + from .lists import TupleVariable + + tx = kwargs.pop("tx", None) + super().__init__(value, init_args=init_args, **kwargs) + if tuple_vt is None: + if self.source is not None: + raise AssertionError( + "tuple_vt must be constructed by builder.py when source is present" + ) + # Emulate `tuple.__new__`: `tuple.__new__(cls)` with no iterable + # arg builds an empty tuple, `tuple.__new__(cls, iterable)` builds + # a tuple from the iterable. + # https://github.com/python/cpython/blob/3.11/Objects/tupleobject.c#L697-L710 + # + # TODO this duplicates the logic in `BuiltinVariable(tuple)` + elems = unpack_iterable(tx, init_args[0]) if init_args else [] + self._base_vt = TupleVariable(elems, mutation_type=ValueMutationNew()) + else: + self._base_vt = tuple_vt + self.tuple_cls = type(value) + self._base_methods = tuple_methods + if self._base_vt is None: + raise AssertionError("_base_vt must not be None after initialization") + + @property + def items(self) -> list[VariableTracker]: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in items") + return self._base_vt.items # type: ignore[return-value] + + def resolve_data_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + type_attr: object, + source: Source | None, + ) -> VariableTracker: + if isinstance(type_attr, _collections._tuplegetter): + # namedtuple fields are _tuplegetter descriptors implemented in C. + # Emulate _tuplegetter.__get__ via tracked tuple items because + # self.value may be a freshly-created empty tuple from + # SideEffects.get_example_value (tuple.__new__(cls) with no args) + # or otherwise underpopulated. Subclasses (NamedTupleVariable, + # StructSequenceVariable) may further override for their specific + # descriptor types. + _, (idx, _) = type_attr.__reduce__() + return self.items[idx] + return super().resolve_data_descriptor(tx, name, type_attr, source) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Sourceless namedtuples/structseqs (e.g. tensor subclass metadata from + # SourcelessBuilder) aren't in id_to_variable so codegen_save_tempvars + # never processes them. When they appear in return values, codegen falls + # through to call_reconstruct. This is the same pattern as other + # sourceless containers (ConstDictVariable, TupleVariable, etc.). + # UserDefinedDictVariable doesn't need this because it's never created + # sourceless — it only comes from VariableBuilder which always has a + # source. + if self.source is not None: + raise AssertionError( + "reconstruct should only be called on sourceless tuples" + ) + create_fn = self.get_construct_fn() + codegen.add_push_null( + lambda: codegen.append_output( + codegen.create_load_const_unchecked(create_fn) + ) + ) + codegen(self._base_vt) + codegen.extend_output(create_call_function(1, False)) + + def get_construct_fn(self) -> Callable[..., Any]: + raise NotImplementedError + + def _validate_rest_for_tree_map( + self, rest: "list[VariableTracker]" + ) -> list["UserDefinedTupleVariable"] | None: + """Validate that rest args are compatible for tree_map fast-path.""" + others: list[UserDefinedTupleVariable] = [] + n = len(self.items) + for candidate in rest: + if ( + not isinstance(candidate, UserDefinedTupleVariable) + or len(candidate.items) != n + or candidate.tuple_cls is not self.tuple_cls + ): + return None + others.append(candidate) + return others + + def _make_tree_map_result( + self, new_items: list[VariableTracker] + ) -> "UserDefinedTupleVariable": + from .lists import TupleVariable + + tuple_vt = TupleVariable(new_items, mutation_type=ValueMutationNew()) + return type(self)( + self.value, + tuple_vt=tuple_vt, + mutation_type=ValueMutationNew(), + ) + + def _is_pytree_node(self) -> bool: + from torch.utils._pytree import is_namedtuple_class + + return is_namedtuple_class(self.tuple_cls) or is_structseq_class(self.tuple_cls) + + def call_tree_map_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "variables.functions.UserFunctionVariable", + map_fn: "VariableTracker", + rest: "list[VariableTracker]", + tree_map_kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + if not self._is_pytree_node(): + return super().call_tree_map_branch( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + others = self._validate_rest_for_tree_map(rest) + if others is None: + return self._tree_map_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + + new_items: list[VariableTracker] = [] + for idx, item in enumerate(self.items): + sibling_leaves = [o.items[idx] for o in others] + new_items.append( + item.call_tree_map( + tx, tree_map_fn, map_fn, sibling_leaves, tree_map_kwargs + ) + ) + + return self._make_tree_map_result(new_items) + + def call_tree_map_with_path_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "variables.functions.UserFunctionVariable", + map_fn: "VariableTracker", + rest: "list[VariableTracker]", + tree_map_kwargs: "dict[str, VariableTracker]", + keypath: "tuple[Any, ...]", + ) -> "VariableTracker": + if not self._is_pytree_node(): + return super().call_tree_map_with_path_branch( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + others = self._validate_rest_for_tree_map(rest) + if others is None: + return self._tree_map_with_path_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + + fields = namedtuple_fields(self.tuple_cls) + new_items: list[VariableTracker] = [] + for idx, item in enumerate(self.items): + sibling_leaves = [o.items[idx] for o in others] + child_keypath = keypath + (GetAttrKey(fields[idx]),) + new_items.append( + item.call_tree_map_with_path( + tx, + tree_map_fn, + map_fn, + sibling_leaves, + tree_map_kwargs, + child_keypath, + ) + ) + + return self._make_tree_map_result(new_items) + + +class NamedTupleVariable(UserDefinedTupleVariable): + """Represents Python namedtuples (created via collections.namedtuple). + + Namedtuples use _tuplegetter descriptors for field access and + Type(*args) / Type._make(iterable) for construction. + """ + + def resolve_data_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + type_attr: object, + source: Source | None, + ) -> VariableTracker: + if isinstance(type_attr, _collections._tuplegetter): + # namedtuple fields are _tuplegetter descriptors implemented in C. + # We emulate _tuplegetter.__get__ by indexing into the tracked + # tuple items, because self.value may not hold actual runtime values. + _, (idx, _) = type_attr.__reduce__() + return self.items[idx] # type: ignore[union-attr] + return super().resolve_data_descriptor(tx, name, type_attr, source) + + def get_construct_fn(self) -> Callable[..., Any]: + return self.tuple_cls._make # type: ignore[attr-defined] + + def as_python_constant(self) -> Any: + items = [x.as_python_constant() for x in self.items] + return self.tuple_cls(*items) # type: ignore[arg-type] + + def as_proxy(self) -> Any: + items = [x.as_proxy() for x in self.items] + return self.tuple_cls(*items) # type: ignore[arg-type] + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + fields = namedtuple_fields(self.tuple_cls) + items = ", ".join( + f"{name}={tracked_repr(tx, item)}" for name, item in zip(fields, self.items) + ) + return VariableTracker.build(tx, f"{self.tuple_cls.__name__}({items})") + + +class StructSequenceVariable(UserDefinedTupleVariable): + """Represents C-implemented PyStructSequence types (torch.return_types.*). + + Structseqs use Type(iterable) calling convention and reject tuple.__new__. + """ + + def resolve_data_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + type_attr: object, + source: Source | None, + ) -> VariableTracker: + if isinstance(type_attr, types.MemberDescriptorType): + # Structseq fields are member_descriptor objects. We emulate + # field access by looking up the field name in _fields and + # indexing into the tracked tuple items. + fields = namedtuple_fields(self.tuple_cls) + if name in fields: + return self.items[fields.index(name)] + return super().resolve_data_descriptor(tx, name, type_attr, source) + + def get_construct_fn(self) -> Callable[..., Any]: + return self.tuple_cls + + def as_python_constant(self) -> Any: + items = [x.as_python_constant() for x in self.items] + return self.tuple_cls(items) + + def as_proxy(self) -> Any: + items = [x.as_proxy() for x in self.items] + return self.tuple_cls(items) + + def debug_repr(self) -> str: + fields = namedtuple_fields(self.tuple_cls) + items = ", ".join( + f"{name}={item.debug_repr()}" for name, item in zip(fields, self.items) + ) + return f"{self.tuple_cls.__module__}.{self.tuple_cls.__qualname__}({items})" + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + fields = namedtuple_fields(self.tuple_cls) + items = ", ".join( + f"{name}={tracked_repr(tx, item)}" for name, item in zip(fields, self.items) + ) + return VariableTracker.build( + tx, + f"{self.tuple_cls.__module__}.{self.tuple_cls.__qualname__}({items})", + ) + + +class MutableMappingVariable(UserDefinedObjectVariable): + def __init__(self, value: object, **kwargs: Any) -> None: + super().__init__(value, **kwargs) + + def method_setattr_standard( + self, + tx: "InstructionTranslatorBase", + name: VariableTracker, + value: VariableTracker, + ) -> VariableTracker: + """Override to handle property setters on MutableMapping subclasses. + + This is needed because property.__set__ is a slot wrapper (C function), + but property.fset is a Python function we can trace. + + Without this, property setters on newly created MutableMapping objects fail + when accessing nested objects (which haven't been initialized yet on the + example value). By tracing the fset, we capture the setter logic in the graph + instead of running it on uninitialized example objects. + + TODO(compiler): This fix is scoped to MutableMapping only because tracing + property setters on ALL UserDefinedObjectVariable can cause failures when + the fset calls untraceable C++ functions (e.g., pybind functions). Ideally, + this should be extended to all user-defined classes with a graceful fallback + when tracing the fset hits an untraceable function. + See: https://github.com/pytorch/pytorch/issues/172000 + """ + if isinstance(name, variables.ConstantVariable) and isinstance(name.value, str): + name_str = name.value + descriptor = inspect.getattr_static(type(self.value), name_str, None) + if isinstance(descriptor, property) and descriptor.fset is not None: + fset_source = None + if self.cls_source: + desc_source = self.get_source_by_walking_mro(tx, name_str) + fset_source = AttrSource(desc_source, "fset") + fset_vt = VariableTracker.build(tx, descriptor.fset, fset_source) + return fset_vt.call_function(tx, [self, value], {}) + + return super().method_setattr_standard(tx, name, value) + + def _get(self, tx: "InstructionTranslatorBase") -> "VariableTracker | None": + # `.get` backed by the stdlib Mapping/dict implementation resolves to a + # traceable polyfill; anything else declines to the generic getattro. + if type(self.value).get in ( # type: ignore[attr-defined] + collections.abc.Mapping.get, + dict.get, + ): + return variables.UserMethodVariable(polyfills.mapping_get, self) + return None + + tp_getset = {"get": GetSet(_get, None)} + + def mp_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self._maybe_get_baseclass_method("__len__") in dict_methods: + return VariableTracker.build(tx, len(self.value)) # type: ignore[bad-argument-type] + return super().mp_length_impl(tx) + + +class RandomVariable(UserDefinedObjectVariable): + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_environment.py b/.venv/lib/python3.12/site-packages/torch/_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..67e5784dfc1a5104f92b4d2144189976fcce43e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_environment.py @@ -0,0 +1,9 @@ +from typing import Literal + + +def is_fbcode() -> Literal[False]: + return False + + +def is_prod() -> Literal[False]: + return False diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a46a50c04b3ffe6aac78ca2978cdde293f2a17b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/__init__.py @@ -0,0 +1,189 @@ +# mypy: allow-untyped-defs +import copy +import dataclasses +import functools +import io +import json +import logging +import os +import re +import sys +import types +import warnings +import weakref +import zipfile +from collections import OrderedDict +from contextlib import contextmanager +from functools import lru_cache + +from typing import Any, Optional, TYPE_CHECKING, Union +from collections.abc import Callable +from unittest.mock import patch + +import torch +import torch.fx +import torch.utils._pytree as pytree + +from torch._dispatch.python import enable_python_dispatcher +from torch._guards import compile_context +from torch._utils_internal import log_export_usage +from torch.export._tree_utils import reorder_kwargs +from torch.export.graph_signature import ( + ArgumentSpec, + ConstantArgument, + ExportGraphSignature, + InputKind, + InputSpec, + OutputKind, + OutputSpec, + SymIntArgument, + SymBoolArgument, + SymFloatArgument, + TensorArgument, +) +from torch.fx import traceback as fx_traceback +from torch.fx._compatibility import compatibility +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo + +from .wrappers import _wrap_submodules +from .utils import _materialize_cpp_cia_ops +from . import config + +if TYPE_CHECKING: + from torch._C._aoti import AOTIModelContainerRunner + +log = logging.getLogger(__name__) + +@dataclasses.dataclass +class ExportDynamoConfig: + """ + Manage Export-specific configurations of Dynamo. + """ + allow_rnn: bool = True + + +# We only want to print this once to avoid flooding logs in workflows where aot_compile_warning +# is called multiple times. +@lru_cache +def aot_compile_warning(): + + log.warning("+============================+") + log.warning("| !!! WARNING !!! |") + log.warning("+============================+") + log.warning( + "torch._export.aot_compile()/torch._export.aot_load() is being deprecated, please switch to " + "directly calling torch._inductor.aoti_compile_and_package(torch.export.export())/" + "torch._inductor.aoti_load_package() instead.") + + +def aot_compile( + f: Callable, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + dynamic_shapes: dict[str, Any] | None = None, + options: dict[str, Any] | None = None, + remove_runtime_assertions: bool = False, + disable_constraint_solver: bool = False, + same_signature: bool = True, +) -> list[Any] | str: + """ + Note: this function is not stable yet + + Traces either an nn.Module's forward function or just a callable with PyTorch + operations inside, generates executable cpp code from the program, and returns + the path to the generated shared library + + Args: + f: the `nn.Module` or callable to trace. + + args: example positional inputs. + + kwargs: optional example keyword inputs. + + dynamic_shapes: Should either be: + 1) a dict from argument names of ``f`` to their dynamic shape specifications, + 2) a tuple that specifies dynamic shape specifications for each input in original order. + If you are specifying dynamism on keyword args, you will need to pass them in the order that + is defined in the original function signature. + + The dynamic shape of a tensor argument can be specified as either + (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is + not required to include static dimension indices in this dict, but when they are, + they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None, + where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions + are denoted by None. Arguments that are dicts or tuples / lists of tensors are + recursively specified by using mappings or sequences of contained specifications. + + options: A dictionary of options to control inductor + + disable_constraint_solver: Whether the dim constraint solver must be disabled. + + Returns: + Path to the generated shared library + """ + from torch.export._trace import _export_to_torch_ir + from torch._inductor.decomposition import select_decomp_table + from torch._inductor import config as inductor_config + + aot_compile_warning() + + if inductor_config.is_predispatch: + gm = torch.export._trace._export(f, args, kwargs, dynamic_shapes, pre_dispatch=True).module() + else: + # We want to export to Torch IR here to utilize the pre_grad passes in + # inductor, which run on Torch IR. + with torch._export.config.patch(use_new_tracer_experimental=True): + gm = _export_to_torch_ir( + f, + args, + kwargs, + dynamic_shapes, + disable_constraint_solver=disable_constraint_solver, + same_signature=same_signature, + # Disabling this flag, because instead we can rely on the mapping + # dynamo_flat_name_to_original_fqn which is coming from Dynamo. + restore_fqn=False, + ) + + with torch.no_grad(): + so_path = torch._inductor.aot_compile(gm, args, kwargs, options=options) # type: ignore[arg-type] + + if not isinstance(so_path, (str, list)): + raise AssertionError(f"expected str or list, got {type(so_path)}") + return so_path + +def aot_load(so_path: str, device: str) -> Callable: + """ + Loads a shared library generated by aot_compile and returns a callable + + Args: + so_path: Path to the shared library + + Returns: + A callable + """ + aot_compile_warning() + + if device == "cpu": + runner: AOTIModelContainerRunner = torch._C._aoti.AOTIModelContainerRunnerCpu(so_path, 1) + elif device == "cuda" or device.startswith("cuda:"): + runner = torch._C._aoti.AOTIModelContainerRunnerCuda(so_path, 1, device) + elif device == "xpu" or device.startswith("xpu:"): + runner = torch._C._aoti.AOTIModelContainerRunnerXpu(so_path, 1, device) + elif device == "mps" or device.startswith("mps:"): + runner = torch._C._aoti.AOTIModelContainerRunnerMps(so_path, 1) + else: + raise RuntimeError("Unsupported device " + device) + + def optimized(*args, **kwargs): + call_spec = runner.get_call_spec() + in_spec = pytree.treespec_loads(call_spec[0]) + out_spec = pytree.treespec_loads(call_spec[1]) + flat_inputs = pytree.tree_flatten((args, reorder_kwargs(kwargs, in_spec)))[0] + flat_inputs = [x for x in flat_inputs if isinstance(x, torch.Tensor)] + flat_outputs = runner.run(flat_inputs) + return pytree.tree_unflatten(flat_outputs, out_spec) + + return optimized diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7232eaba3319e444f77b314d1ac98ed8331c175 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4bd9899a7c5831109362361bab07cdb2ddb5887 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/converter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/converter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34c1a765519f05741d135ec7a2111e85d42e7421 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/converter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/error.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..331575310a2b86af7a4363cd4b1ede298ea175fc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/error.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/non_strict_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/non_strict_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a00f5d6bddcb886f6de25042519b6bb8d2cb13b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/non_strict_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/pass_base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/pass_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8483d42d9ec7046fca6888a725b050310a737f8e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/pass_base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/tools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/tools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1073dcdebe07e139bb26c3a26761a79c6f19c7f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/tools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8776b9ab833e3b9b860497af5439ecea303666fb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/verifier.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/verifier.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8eb09d374a7d3b3081b9571c425acf5b6618da44 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/verifier.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/wrappers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba769f63259b295e0f05da7b3c64f804cac91fbb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/wrappers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/config.py b/.venv/lib/python3.12/site-packages/torch/_export/config.py new file mode 100644 index 0000000000000000000000000000000000000000..4f800487b2ab67ad88384d42bfb93f35f5e7b417 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/config.py @@ -0,0 +1,45 @@ +""" +Configuration module for torch.export.export. + +This module contains various configuration flags and settings that control torch.export's +behavior, including: +- Runtime behavior flags +- Debugging and development options +""" + +import sys +from typing import Any, TYPE_CHECKING + +from torch._environment import is_fbcode +from torch.utils._config_module import install_config_module + + +# this flag controls whether we use new functional tracer. It +# should be True in the long term. +use_new_tracer_experimental = True + +# this flag is used to control whether we want to instrument +# fake tensor creation to track potential leaks. It is off +# by default, but user can turn it on to debug leaks. +detect_non_strict_fake_tensor_leaks = False + +# error on potentially pre-dispatch/non-strict tracing limitation +# this type of error usually happens when we encounter an op +# that we don't know how to proxy, resulting in untracked fake tensors +error_on_lifted_constant_tensors = True + +# enable auto_functionalized_v2 in export +# We turn this off in fbcode due to downstream users not +# being ready to handle auto_functionalized_v2. +enable_auto_functionalized_v2_for_export = not is_fbcode() + +use_legacy_dynamo_graph_capture = True + + +if TYPE_CHECKING: + from torch.utils._config_typing import * # noqa: F403 + + def _make_closure_patcher(**changes: Any) -> Any: ... + + +install_config_module(sys.modules[__name__]) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/converter.py b/.venv/lib/python3.12/site-packages/torch/_export/converter.py new file mode 100644 index 0000000000000000000000000000000000000000..1cba606d093f715d6a6be9d683784461bfe1763c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/converter.py @@ -0,0 +1,1622 @@ +# mypy: allow-untyped-defs +import builtins +import logging +import operator +import typing +import warnings +from collections.abc import Callable, Sequence +from contextlib import contextmanager +from typing import Any + +import torch +import torch.export._trace +from torch import _C +from torch._export.passes.replace_quantized_ops_with_standard_ops_pass import ( + replace_quantized_ops_with_standard_ops, +) +from torch.export.dynamic_shapes import _tree_map_with_path, Dim +from torch.export.exported_program import ExportedProgram +from torch.export.graph_signature import ( + ConstantArgument, + CustomObjArgument, + InputKind, + InputSpec, + OutputKind, + OutputSpec, + TensorArgument, +) +from torch.fx import subgraph_rewriter + + +log = logging.getLogger(__name__) + + +def _get_param_count_list(method_graph, args_params): + param_count_list = [] + for input_, arg_params_ in zip(method_graph.inputs(), args_params): + if "PackedParams" in str(input_.type()): + in_vars, _ = torch.jit._flatten(arg_params_) + param_count_list.append(len(in_vars)) + else: + param_count_list.append(arg_params_ is not None) + + return param_count_list + + +def _trace_and_get_graph_from_model(model, args): + # A basic sanity check: make sure the state_dict keys are the same + # before and after running the model. Fail fast! + orig_state_dict_keys = torch.jit._unique_state_dict(model).keys() + + # Disable Autocast cache because it replaces kernel's weight and bias + # by (undesired) constants. + # No perf impact for when there are reused weights since https://github.com/pytorch/pytorch/pull/85665 + prev_autocast_cache_enabled = torch.is_autocast_cache_enabled() + torch.set_autocast_cache_enabled(False) + trace_graph, torch_out, _inputs_states = torch.jit._get_trace_graph( + model, + args, + strict=False, + _force_outplace=False, + _return_inputs_states=True, + ) + torch.set_autocast_cache_enabled(prev_autocast_cache_enabled) + + if orig_state_dict_keys != torch.jit._unique_state_dict(model).keys(): + raise RuntimeError( + "state_dict changed after running the tracer; " + "something weird is happening in your model!" + ) + + return trace_graph, torch_out + + +def _create_jit_graph( + model: torch.nn.Module | torch.jit.ScriptFunction, args: Sequence[Any] +) -> tuple[torch.Graph, list["_C.IValue"], Any, torch.ScriptModule | None]: + if isinstance(model, (torch.jit.ScriptFunction, torch.jit.ScriptModule)): + flattened_args = tuple(torch.jit._flatten(tuple(args))[0]) + torch_out = None + + if isinstance(model, torch.jit.ScriptModule): + try: + graph = model.forward.graph # type: ignore[attr-defined] + except AttributeError as e: + raise RuntimeError("'forward' method must be a script method") from e + _C._jit_pass_onnx_function_substitution(graph) + freezed_module = _C._freeze_module( + typing.cast(_C.ScriptModule, model._c), preserveParameters=True + ) + module, params = _C._jit_onnx_list_model_parameters(freezed_module) + method_graph = module._get_method("forward").graph + args_params = tuple(args) + tuple(params) + param_count_list = _get_param_count_list(method_graph, args_params) + in_vars, _ = torch.jit._flatten(args_params) + graph = _C._propagate_and_assign_input_shapes( + method_graph, tuple(in_vars), param_count_list, False, False + ) + return graph, params, torch_out, module + + # torch.jit.ScriptFunction + params = [] + graph = model.graph + _C._jit_pass_onnx_function_substitution(graph) + param_count_list = _get_param_count_list(graph, args) + graph = _C._propagate_and_assign_input_shapes( + graph, flattened_args, param_count_list, False, False + ) + return graph, params, torch_out, None + + graph, torch_out = _trace_and_get_graph_from_model(model, args) + _C._jit_pass_onnx_lint(graph) + state_dict = torch.jit._unique_state_dict(model) + params = list(state_dict.values()) + graph_inputs = list(graph.inputs()) + user_input_num = len(graph_inputs) - len(state_dict) + param_names = list(state_dict.keys()) + for i, inp in enumerate(graph_inputs): + if i >= user_input_num: + inp.setDebugName(param_names[i - user_input_num]) + _C._jit_pass_onnx_function_substitution(graph) + return graph, params, torch_out, None + + +def list_add(a, b): + return a + b + + +def list_append(container, element): + return container + [element] + + +def execute_subgraph_from_prim_loop( + subgraph, iter_idx, len_loop_local_arguments, *args, **kwargs +): + """ + subgraph: GraphModule from sub-block. + iter_idx: The index of interaction. + len_loop_local_arguments: The number of loop local arguments in args. + """ + + # Loop local variables. TS graph create those as inputs because their values + # are updated inside the loop. + loop_local_args = args[:len_loop_local_arguments] + # Global variables that are not passed in as inputs to the loop sub-blocks + # but are directly used. Most of time, their values are not updated, but + # the only exception is when there are some operations that perform inplace + # updates. + global_args = args[len_loop_local_arguments:] + return subgraph(*global_args, iter_idx, *loop_local_args, **kwargs) + + +def inplace_optimize_sym_size_div(gm: torch.fx.GraphModule): + def pattern(im, dim, scale): + sym_size_int = torch.ops.aten.sym_size.int(im, dim) + scalar_tensor = torch.ops.aten.scalar_tensor(sym_size_int) + div_scalar_mode = torch.ops.aten.div.Scalar_mode( + scalar_tensor, scale, rounding_mode="trunc" + ) + int_tensor = torch.ops.aten.Int.Tensor(div_scalar_mode) + return int_tensor + + def replacement(im, dim, scale): + sym_size_int = torch.ops.aten.sym_size.int(im, dim) + return sym_size_int // scale + + subgraph_rewriter.replace_pattern(gm, pattern, replacement) + + +def is_valid_for_codegen(name): + if len(name) == 0: + raise RuntimeError("Empty argument name for codegen") + if name[0].isdigit(): + return False + return True + + +def normalize_name(name: str, prefix: str = "rename") -> str: + name = name.replace(".", "_") + if is_valid_for_codegen(name): + return name + return f"{prefix}_{name}" + + +def ir_name_to_func_name(name: str) -> str: + """prim::If -> convert_prim_If""" + name_list = name.split("::") + return "convert_" + "_".join(name_list) + + +def get_node_as_placeholder_or_get_attr(fx_graph, name, is_top_level_graph): + if is_top_level_graph: + return fx_graph.get_attr(name) + return fx_graph.placeholder(name) + + +_TORCH_DTYPE_TO_ENUM = { + torch.uint8: 0, + torch.int8: 1, + torch.int16: 2, + torch.int32: 3, + torch.int64: 4, + torch.float16: 5, + torch.float32: 6, + torch.float64: 7, + torch.complex32: 8, + torch.complex64: 9, + torch.complex128: 10, + torch.bool: 11, + torch.qint8: 12, + torch.quint8: 13, + torch.bfloat16: 15, +} + +_TORCH_ENUM_TO_DTYPE = {value: key for key, value in _TORCH_DTYPE_TO_ENUM.items()} + + +def get_dtype_as_int(tensor): + """ + prim::dtype has the signature "Tensor a) -> int", where it gets the dtype of + the tensor and returns the integer corresponding to this dtype based on the + enum in ScalarType.h + """ + dtype = tensor.dtype + if dtype not in _TORCH_DTYPE_TO_ENUM: + raise RuntimeError(f"Unsupported dtype {dtype}") + return _TORCH_DTYPE_TO_ENUM[dtype] + + +# Those operators will be automatically populated to an instance method +# of TS2FXGraphConverter with name convert__(). +# Please check __init__ for method population implementations. +kind_to_standard_operators: dict[str, Callable[..., Any]] = { + "prim::max": builtins.max, + "prim::min": builtins.min, + "prim::TupleIndex": operator.getitem, + "aten::__is__": operator.is_, + "aten::__isnot__": operator.is_not, + "aten::__not__": operator.not_, + "aten::__contains__": operator.contains, + "prim::dtype": get_dtype_as_int, + "aten::len": len, + # Mapping from specialized op to its symbolic counterpart. + # They currently do not have any other overrides. + "aten::numel": torch.ops.aten.sym_numel, + "aten::size": torch.ops.aten.sym_size, + "aten::storage_offset": torch.ops.aten.sym_storage_offset, + "aten::stride": torch.ops.aten.sym_stride, +} + + +def get_ir_value_parent_name_and_attr_name(node): + irv_parent_name, irv_name = node.input().debugName(), node.output().debugName() + attr_name = node.s("name") + return irv_name, irv_parent_name, attr_name + + +def construct_fqn(ir, ref_map, name_map): + name_list = [] + while ir in ref_map: + name_list.append(name_map[ir]) + ir = ref_map[ir] + return ".".join(reversed(name_list)) + + +def get_block_to_lifted_attrs( + graph: torch._C.Graph, +) -> tuple[dict[torch._C.Block, set[str]], dict[str, str]]: + """ + Perform two passes to get a mapping of blocks to a set of FQNs of its lifted attributes. + When a graph has control flow, the graph will be divided into multiple blocks. We want to convert + each block to a graph which will be passed into torch.cond. A restriction for torch.cond is that model + parameters/buffers are expected to be lifted as inputs to the subgraphs. Before converting the model, + we will run this pass which will: + 1. Figure out which params/buffers are used within blocks through tracing the GetAttr calls. + 2. Process the graph bottom up to find the lifted attributes of each block by taking the union + of the attributes used in the current block, and the lifted attributes of all its child blocks. + + Returns: + A mapping of blocks to a set of FQNs of its lifted attributes, and a + mapping of node names to the FQNs of its lifted attributes. + """ + + # A map from a block to its expected to be lifted arguments. + blocks_to_lifted_attrs: dict[torch._C.Block, set[str]] = {} + + # Reference map stores the input (i.e., src) and output (i.e., dest) IR of a + # GetAttr node. By traversing this reference map, we can figure out the + # full IR aliasing pass and figure out the FQN of an attribute. + # E.g., %2 = GetAttr(linear)[%1] --> node_to_parent_map["%2"] = "%1" + node_to_parent_map: dict[str, str] = {} + + # Used for reconstructing the FQN of an attribute based on the reference map. + # In nutshell, for each GetAttr call, GetAttr(input IR, attribute name) -> output IR + # This name map stores which attribute name is called for a src IR --> dest IR action. + # E.g., %2 = GetAttr(linear)[%1] --> node_to_attr_name["%2"] = "linear" + node_to_attr_name: dict[str, str] = {} + + def _dfs_get_attr_dependency(entry): + """ + First DFS path to construct reference map and name map. + """ + for node in entry.nodes(): + if node.kind() == "prim::GetAttr": + ( + irv_name, + irv_parent_name, + attr_name, + ) = get_ir_value_parent_name_and_attr_name(node) + node_to_parent_map[irv_name] = irv_parent_name + node_to_attr_name[irv_name] = attr_name + for block in node.blocks(): + _dfs_get_attr_dependency(block) + + def _map_blocks_to_lifted_attrs(entry): + """ + Walk the graph in a bottom-up fashion to build the expected to be + lifted arguments for each block. + """ + arguments: set[str] = set() + for node in entry.nodes(): + for block in node.blocks(): + # Recursively build. + arguments = arguments.union(_map_blocks_to_lifted_attrs(block)) + if node.kind() == "prim::GetAttr": + irv_name = node.output().debugName() + # Skip for intermediate GetAttr, which will anyway not result a FQN. + # E.g., node_to_parent_name: {"%3": "%2", "%2": "%1"} + # node_to_attr_name: {"%3": "weight", "%2": "linear", "%1": "self"} + # There is only one FQN %3-->%2-->%1: self.linear.weight + # %2-->%1 is not a FQN: self.linear + if irv_name not in set(node_to_parent_map.values()): + arguments.add( + construct_fqn(irv_name, node_to_parent_map, node_to_attr_name) + ) + if not isinstance(entry, torch._C.Graph): # Skip the top level. + blocks_to_lifted_attrs[entry] = arguments + return arguments + + _dfs_get_attr_dependency(graph) + _map_blocks_to_lifted_attrs(graph) + + return blocks_to_lifted_attrs, node_to_attr_name + + +def get_attribute_fqn_from_ts_node( + name_to_attribute_fqn: dict[str, str], node: torch._C.Node +) -> str: + def get_attr(name: str): + if name in name_to_attribute_fqn: + return name_to_attribute_fqn[name] + else: + raise ValueError(f"Attribute {name} not found") + + if node.kind() == "prim::SetAttr": + input_name = next(node.inputs()).debugName() + elif node.kind() == "prim::GetAttr": + input_name = node.input().debugName() + else: + raise RuntimeError( + f"Unexpected node kind when getting attribute fqn. node: {node} " + ) + + attr_name = node.s("name") + root_attr_name = get_attr(input_name) + attr_fqn = f"{root_attr_name}.{attr_name}" if root_attr_name else attr_name + + return attr_fqn + + +def get_op_overload(node: torch._C.Node): + schema_str = node.schema() + if schema_str == "(no schema)": + raise AssertionError(f"got empty schema for {node}") + schema: torch._C.FunctionSchema = torch._C.parse_schema(schema_str) + ns, op_name = str(schema.name).split("::") + override = schema.overload_name + + try: + op_overload_mod = getattr(torch.ops, ns) + op_overload_packet = getattr(op_overload_mod, op_name) + if override: + op_overload = getattr(op_overload_packet, override) + else: + op_overload = op_overload_packet.default + except Exception as e: + raise RuntimeError( + f"Unable to find operator {node.kind()} with schema {node.schema()}" + ) from e + + return op_overload + + +class TS2FXGraphConverter: + def __init__( + self, + ts_graph: torch._C.Graph | torch._C.Block, + name_to_param: dict[str, torch.Tensor], + name_to_buffer: dict[str, torch.Tensor], + blocks_to_lifted_attrs: dict[torch._C.Block, set[str]], + name_to_non_tensor_attribute: dict[str, Any], + name_to_constant: dict[str, Any], + name_to_attribute_fqn: dict[str, str], + ): + self.ts_graph = ts_graph + # Mapping of parameter FQN to actual parameter value + self.name_to_param = name_to_param + # Mapping of buffer FQN to actual buffer value + self.name_to_buffer = name_to_buffer + + self.fx_graph: torch.fx.Graph = torch.fx.Graph() + self.input_specs: list[InputSpec] = [] + self.output_specs: list[OutputSpec] = [] + + # Mapping of TS node name to converted FX node + self.name_to_node: dict[ + str, torch.fx.Node | list[torch.fx.Node] | dict[Any, torch.fx.Node] + ] = {} + # Mapping of TS node name to constant value (int, str, TorchBind obj, + # tensor constants ...) + self.name_to_constant: dict[str, Any] = name_to_constant + + # Mapping from torchscript node output name to attribute fully qualified name + self.name_to_attribute_fqn: dict[str, str] = name_to_attribute_fqn + + # Mapping from fully qualified name to real values or a fx graph node + # During convert, this represents the current value of a non-tensor attribute + # One use case is: + # def forward(self, x): + # c1 = self.count + # self.count += 1 + # c2 = self.count + # return x + c1 + c2 + self.name_to_non_tensor_attribute_node: dict[str, Any] = {} + + # Mapping from fully qualified name to initial real values inputs + # We separate it from self.name_to_non_tensor_attribute_node since + # we need initial real value input when we construct fx.GraphModule + self.name_to_non_tensor_attribute: dict[str, Any] = name_to_non_tensor_attribute + + self.subgraphs: dict[str, torch.fx.GraphModule] = {} + + # Mapping of block to list of attributes that need to be lifted for each + # block + self.blocks_to_lifted_attrs = blocks_to_lifted_attrs + + # Populate methods for the standard operators. + for k in kind_to_standard_operators: + handler_func_name = ir_name_to_func_name(k) + # Create an indirect function call: + # convert__ --> lambda node: _convert_standard_operator(node) + setattr( + self, + handler_func_name, + lambda node: self._convert_standard_operators(node), + ) + + # This stores a list of return results that do not appear in the original TS + # graph's outputs. The reason we maintain this is because some operations in the sub-block + # might have inplace updates to the variable defined in the parent fx graph. After + # the execution of that sub-block, the variable defined in the parent fx graph also + # needs to be updated. + self.name_update_from_subblock_to_parent: set[str] = set() + + def _is_get_attr_node(self, fqn): + return ( + fqn in self.name_to_buffer + or fqn in self.name_to_param + or ( + fqn in self.name_to_constant + and isinstance(self.name_to_constant[fqn], torch.ScriptObject) + ) + ) + + def _convert_block_to_subgraph(self, node: torch._C.Node, arguments: list[str]): + subgraph_nodes, subgraph_converters = [], [] + for block in node.blocks(): + subgraph_converter = TS2FXGraphConverter( + block, + self.name_to_param, + self.name_to_buffer, + self.blocks_to_lifted_attrs, + {}, + self.name_to_constant, + self.name_to_attribute_fqn, + ) + + for block_arg in arguments: + normalized_block_arg_name = normalize_name(block_arg) + placeholder_node = subgraph_converter.fx_graph.placeholder( + normalized_block_arg_name + ) + subgraph_converter.name_to_node[block_arg] = placeholder_node + + subgraph = subgraph_converter.convert() + subgraph_name = self.add_subgraph(subgraph) + subgraph_nodes.append(self.fx_graph.get_attr(subgraph_name)) + subgraph_converters.append(subgraph_converter) + return subgraph_nodes, subgraph_converters + + def _identify_inputs_as_arguments(self, entry): + """ + Identify inputs from the innermost sub-block. This is needed + for nested sub-blocks when the input is hidden in the nested sub-block. + E.g., example IR of input is hidden in the nested sub-block. + Graph[x.1] + %1 = ... + Block[] + Block[x.1] + %2 = x.1 ... + """ + arguments: set[str] = set() + for block in entry.blocks(): + for block_node in block.nodes(): + for block_node_in in block_node.inputs(): + if ( + block_node_in.debugName() in self.name_to_node + and block_node_in.debugName() not in self.name_to_attribute_fqn + ): + arguments.add(block_node_in.debugName()) + arguments = arguments.union( + self._identify_inputs_as_arguments(block_node) + ) + return arguments + + def is_top_level_graph(self): + return isinstance(self.ts_graph, torch._C.Graph) + + def add_subgraph(self, subgraph) -> str: + name = f"subgraph_{len(self.subgraphs)}" + self.subgraphs[name] = subgraph + return name + + def get_args_kwargs(self, node: torch._C.Node, schema): + args = [] + kwargs = {} + for input, schema_arg in zip(node.inputs(), schema.arguments): + if schema_arg.kwarg_only: + kwargs[schema_arg.name] = self.get_fx_value_by_ir_value(input) + else: + args.append(self.get_fx_value_by_ir_value(input)) + + return tuple(args), kwargs + + def get_fx_value_by_ir_value(self, value: torch._C.Value): + value_name = value.debugName() + + if value_name in self.name_to_node: + input_node = self.name_to_node[value_name] + return input_node + elif value_name in self.name_to_constant: + if isinstance(self.name_to_constant[value_name], torch.ScriptObject): + return self.fx_graph.get_attr(value_name) + return self.name_to_constant[value_name] + elif value_name in self.name_to_attribute_fqn: + return self.get_fx_value_by_fqn(self.name_to_attribute_fqn[value_name]) + else: + raise ValueError(f"Input {value_name} not found") + + def get_fx_value_by_fqn(self, name): + if name in self.name_to_node: + fx_node = self.name_to_node[name] + elif name in self.name_to_constant: + fx_node = self.name_to_constant[name] + elif name in self.name_to_non_tensor_attribute_node: + fx_node = self.name_to_non_tensor_attribute_node[name] + elif name in self.name_to_non_tensor_attribute: + fx_node = self.name_to_non_tensor_attribute[name] + else: + raise ValueError(f"Attribute {name} not found") + return fx_node + + def convert(self) -> torch.fx.GraphModule: + self.convert_graph_inputs() + + for node in self.ts_graph.nodes(): + self.convert_node(node) + + self.convert_graph_outputs() + + # Pass parameter and buffer to the root for lookup. + gm = torch.fx.GraphModule( + { + **self.subgraphs, + **self.name_to_param, + **self.name_to_buffer, + **self.name_to_non_tensor_attribute, + **self.name_to_constant, + }, + self.fx_graph, + ) + + inplace_optimize_sym_size_div(gm) + + gm.graph.lint() + + return gm + + def convert_graph_inputs(self): + for graph_input in self.ts_graph.inputs(): + name = graph_input.debugName() + + if name in self.name_to_param: + normalized_name = normalize_name(name) + self.input_specs.append( + InputSpec( + InputKind.PARAMETER, + arg=TensorArgument(name=normalized_name), + target=name, + ) + ) + fx_node = get_node_as_placeholder_or_get_attr( + self.fx_graph, name, self.is_top_level_graph() + ) + elif name in self.name_to_buffer: + normalized_name = normalize_name(name) + self.input_specs.append( + InputSpec( + InputKind.BUFFER, + arg=TensorArgument(name=normalized_name), + target=name, + persistent=True, + ) + ) + fx_node = get_node_as_placeholder_or_get_attr( + self.fx_graph, name, self.is_top_level_graph() + ) + elif name in self.name_to_constant: + if not isinstance(self.name_to_constant[name], torch.ScriptObject): + raise AssertionError( + f"Input conversion only handles ScriptObject, got {type(self.name_to_constant[name])}" + ) + normalized_name = normalize_name(name) + self.input_specs.append( + InputSpec( + InputKind.CUSTOM_OBJ, + arg=CustomObjArgument( + name=normalized_name, class_fqn=normalized_name + ), + target=name, + persistent=False, + ) + ) + fx_node = get_node_as_placeholder_or_get_attr( + self.fx_graph, name, self.is_top_level_graph() + ) + elif isinstance(graph_input.type(), torch.ClassType): + # Directly skip inputs that are ScriptObject but not used in the graph. + continue + else: + normalized_name = normalize_name(name, prefix="input") + self.input_specs.append( + InputSpec( + InputKind.USER_INPUT, + arg=TensorArgument(name=normalized_name), + target=name, + ) + ) + fx_node = self.fx_graph.placeholder(normalized_name) + + self.name_to_node[name] = fx_node + + def convert_aten_Float(self, node: torch._C.Node): + def to_float_tensor(t): + return t.to(dtype=torch.float).item() + + inp_list = [self.get_fx_value_by_ir_value(inp) for inp in node.inputs()] + fx_node = self.fx_graph.call_function( + to_float_tensor, + tuple(inp_list), + ) + self.name_to_node[node.output().debugName()] = fx_node + + def convert_aten_tensor(self, node: torch._C.Node): + """aten::tensor creates a constant tensor ad-hoc --> GetAttr""" + args, kwargs = self.get_args_kwargs(node, torch.ops.aten.tensor.default._schema) + + for k in kwargs: + if k == "requires_grad": + kwargs[k] = bool(kwargs[k]) # 0 -> False, 1 -> True + + to_tensor = ( + torch.tensor + if all(isinstance(a, int) for a in args) + else torch._refs.tensor + ) + + def target(*args, **kwargs): + if "dtype" in kwargs and kwargs["dtype"] is not None: + kwargs["dtype"] = _TORCH_ENUM_TO_DTYPE[kwargs["dtype"]] + return to_tensor(*args, **kwargs) + + # def to_dynamic_tensor(*args, **kwargs): + # if "dtype" in kwargs and kwargs["dtype"] is not None: + # kwargs["dtype"] = _TORCH_ENUM_TO_DTYPE[kwargs["dtype"]] + # return torch._refs.tensor(*args, **kwargs) + + output_name = node.output().debugName() + fx_node = self.fx_graph.call_function(target, args, kwargs) + self.name_to_node[output_name] = fx_node + + def convert_aten_append(self, node: torch._C.Node): + # special handle python list append: "aten::append.t(t[](a!) self, t(c -> *) el) -> t[](a!)" + + # inplace append to the list!! This is kinda crazy, as we are inplace mutating the list + # This makes the converter "non-functional", and the result depends on the order of the nodes being converted + # In a sense, the converter now becomes a stateful interpreter + warnings.warn( + "Converting aten::append.t, which is an inplace mutation of the list. " + "This makes the converter non-functional: the result depends on the order of the append nodes being converted!", + stacklevel=2, + ) + + args = tuple(self.get_fx_value_by_ir_value(inp) for inp in node.inputs()) + fx_node = self.fx_graph.call_function(list_append, args) + self.name_to_node[node.output().debugName()] = fx_node + + # inplace mutate arg[0], which is the python list + self.name_to_node[node.inputsAt(0).debugName()] = fx_node + + # Variables that need to be updated to parent module. + if not self.is_top_level_graph() and args[0].op == "placeholder": + self.name_update_from_subblock_to_parent.add(node.inputsAt(0).debugName()) + + def convert_prim_Constant(self, node: torch._C.Node): + name = node.output().debugName() + + value: Any = None + if node.hasAttribute("value"): + constant_kind = node.kindOf("value") + if constant_kind == "i": + value = node.i("value") + elif constant_kind == "f": + value = node.f("value") + elif constant_kind == "s": + value = node.s("value") + elif constant_kind == "t": + alias_name = ( + f"lifted_tensor_{name}" # Follow naming convention from EP tracing. + ) + fx_node = self.fx_graph.get_attr(alias_name) + self.name_to_node[name] = fx_node + name, value = alias_name, node.t("value") + elif constant_kind == "ival": + value = node.ival("value") + else: + raise ValueError(f"Unsupported constant type: {node.kindOf('value')}") + else: + value = None + + self.name_to_constant[name] = value + + def convert_prim_CallMethod(self, node: torch._C.Node): + inp_list = [self.get_fx_value_by_ir_value(inp) for inp in node.inputs()] + fx_node = self.fx_graph.call_method( + node.s("name"), + tuple(inp_list), + ) + self.name_to_node[node.output().debugName()] = fx_node + + def convert_prim_device(self, node: torch._C.Node): + input_type = node.input().type() + if input_type.isSubtypeOf(torch._C.TensorType.get()): + device = input_type.device() # type: ignore[attr-defined] + output_name = node.output().debugName() + self.name_to_constant[output_name] = device + else: + raise ValueError(f"Unsupported JitType ({input_type}) when get device") + + def convert_prim_GetAttr(self, node: torch._C.Node): + # Build fully qualified name + attr_fqn = get_attribute_fqn_from_ts_node(self.name_to_attribute_fqn, node) + output_name = node.output().debugName() + self.name_to_attribute_fqn[output_name] = attr_fqn + + if self.is_top_level_graph(): + if self._is_get_attr_node(attr_fqn): + # We insert a get_attr node due to two reasons. + # First, ts graph does not lift tensor constants as input nodes. So + # tensor constants may be ignored by in convert_graph_inputs(). + # Second, attr_fqn may have been written to via SetAttr. Two + # GetAttr may give different values. + self.name_to_node[output_name] = self.fx_graph.get_attr(attr_fqn) + else: + if attr_fqn not in self.name_to_non_tensor_attribute_node: + self.name_to_non_tensor_attribute_node[attr_fqn] = ( + self.name_to_non_tensor_attribute[attr_fqn] + ) + self.name_to_node[output_name] = self.name_to_non_tensor_attribute_node[ + attr_fqn + ] + else: + # Special support for if blocks which do not allow SetAttr TorchScript + # node and get_attr FX Graph Node. + if self._is_get_attr_node(attr_fqn): + self.name_to_node[output_name] = self.name_to_node[attr_fqn] + + def convert_prim_SetAttr(self, node: torch._C.Node): + attr_fqn = get_attribute_fqn_from_ts_node(self.name_to_attribute_fqn, node) + attr_value = tuple(node.inputs())[1] + ts_graph_tensor_input = self.get_fx_value_by_ir_value(attr_value) + if self._is_get_attr_node(attr_fqn): + fx_attr_node = self.fx_graph.get_attr(attr_fqn) + self.fx_graph.call_function( + torch.Tensor.copy_, (fx_attr_node, ts_graph_tensor_input) + ) + else: + self.name_to_non_tensor_attribute_node[attr_fqn] = ts_graph_tensor_input + + def convert_call_function_op(self, node: torch._C.Node): + target = get_op_overload(node) + + args, kwargs = self.get_args_kwargs(node, target._schema) + + fx_node = self.fx_graph.call_function(target, args, kwargs) + + # TODO: convert sourceRange() into stack_trace + # fx_node.meta["stack_trace"] = node.sourceRange() + + if node.outputsSize() == 1: + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + else: + for i, outp in enumerate(node.outputs()): + output_name = outp.debugName() + next_fx_node = self.fx_graph.call_function( + operator.getitem, (fx_node, i) + ) + self.name_to_node[output_name] = next_fx_node + + def convert_prim_TupleConstruct(self, node: torch._C.Node): + self._convert_prim_iterator(node) + + def convert_prim_ListConstruct(self, node: torch._C.Node): + self._convert_prim_iterator(node) + + def _convert_prim_iterator(self, node: torch._C.Node): + output_list = [self.get_fx_value_by_ir_value(inp) for inp in node.inputs()] + + output_name = node.output().debugName() + self.name_to_node[output_name] = output_list + + def convert_prim_DictConstruct(self, node: torch._C.Node): + output_dict = {} + k, v = None, None + for i, inp in enumerate(node.inputs()): + # We assume key value are stored in pair in the DictConstruct. + # The first element is the key and the following is the value. + if i % 2 == 0: + k = self.get_fx_value_by_ir_value(inp) + else: + v = self.get_fx_value_by_ir_value(inp) + if k is None or v is None: + raise AssertionError("DictConstruct has an empty key value pair.") + output_dict[k] = v + k, v = None, None + + if k is not None or v is not None: + raise AssertionError( + "DictConstruct has an odd number of elements (violating our assumption)." + ) + + output_name = node.output().debugName() + self.name_to_node[output_name] = output_dict + + def convert_prim_ListUnpack(self, node: torch._C.Node): + self._convert_prim_unpack_iterator(node) + + def convert_prim_TupleUnpack(self, node: torch._C.Node): + self._convert_prim_unpack_iterator(node) + + def _convert_prim_unpack_iterator(self, node: torch._C.Node): + # Single input and multiple outputs for unpacking. + for i, outp in enumerate(node.outputs()): + outp_name = outp.debugName() + inp = self.get_fx_value_by_ir_value(node.input()) + fx_node = self.fx_graph.call_function(operator.getitem, (inp, i)) + self.name_to_node[outp_name] = fx_node + + def convert_aten_Int(self, node: torch._C.Node): + # converts aten::Int as aten._to_copy + aten::_local_scalar_dense + target = torch.ops.aten._to_copy.default + args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs()) + to_copy_node = self.fx_graph.call_function(target, args, {"dtype": torch.int32}) + + fx_node = self.fx_graph.call_function( + torch.ops.aten._local_scalar_dense.default, (to_copy_node,) + ) + + # TODO: convert sourceRange() into stack_trace + # fx_node.meta["stack_trace"] = node.sourceRange() + + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_prim_NumToTensor(self, node: torch._C.Node): + # Converts prim::NumToTensor as aten.scalar_tensor. + # prim::NumToTensor IRs are currently triggered by: + # .size() https://github.com/pytorch/pytorch/blob/main/torch/csrc/jit/frontend/tracer.cpp#L950 + # .numel() https://github.com/pytorch/pytorch/blob/main/torch/csrc/jit/frontend/tracer.cpp#L971 + # For both of those APIs, torch.jit.trace implicitly sets the output tensor type + # to be LongTensor. + target = torch.ops.aten.scalar_tensor + args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs()) + + fx_node = self.fx_graph.call_function(target, args, {"dtype": torch.long}) + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_prim_CreateObject(self, node: torch._C.Node): + output_name = node.output().debugName() + self.name_to_attribute_fqn[output_name] = "" + + def convert_aten__convolution(self, node: torch._C.Node): + # converts aten::_convolution as aten.convolution, since aten::_convolution + # doesn't have a meta function + target = torch.ops.aten.convolution.default + args, kwargs = self.get_args_kwargs(node, target._schema) + + fx_node = self.fx_graph.call_function(target, args, kwargs) + + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_aten_div(self, node: torch._C.Node): + target = get_op_overload(node) + schema = target._schema + + args, kwargs = self.get_args_kwargs(node, schema) + + # converts aten::div.Tensor_mode(x, tensor_constant) + # as aten.div.Scalar_mode(x, tensor_constant.item()) + if schema.overload_name == "Tensor_mode": + arg1_name = args[1].name + if arg1_name in self.name_to_constant and isinstance( + self.name_to_constant[arg1_name], torch.Tensor + ): + tensor_constant = self.name_to_constant[arg1_name] + if tensor_constant.numel() == 1: + updated_args = list(args) + updated_args[1] = self.name_to_constant[arg1_name].item() + + fx_node = self.fx_graph.call_function( + torch.ops.aten.div.Scalar_mode, + tuple(updated_args), + kwargs, + ) + + # TODO: convert sourceRange() into stack_trace + # fx_node.meta["stack_trace"] = node.sourceRange() + + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + return + + self.convert_call_function_op(node) + + def convert_aten___getitem__(self, node: torch._C.Node): + input_container, index = tuple( + self.get_fx_value_by_ir_value(input) for input in node.inputs() + ) + fx_node = self.fx_graph.call_function( + operator.getitem, (input_container, index) + ) + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_aten_to(self, node: torch._C.Node): + target = get_op_overload(node) + args, _kwargs = self.get_args_kwargs(node, target._schema) + + # special handle aten.to.dtype and aten.to.prim_dtype followed by inplace_mutation_op + # coz aten.to + inplace_mutation_op pattern would trigger + # "cannot mutate tensors with frozen storage" functionalization error. + # To work around the issue, we override the copy to be True, so that the output + # is for sure not an alias of input + if target is torch.ops.aten.to.dtype or target is torch.ops.aten.to.prim_dtype: + user_nodes = [use.user for use in node.output().uses()] + user_targets = [ + get_op_overload(user_node) + for user_node in user_nodes + if user_node.schema() != "(no schema)" + ] + has_mutable_target = any( + target._schema.is_mutable for target in user_targets + ) + + if has_mutable_target: + if len(args) < 4: + raise AssertionError(f"expected at least 4 args, got {len(args)}") + new_args = list(args) + new_args[3] = True # copy, override to True + fx_node = self.fx_graph.call_function( + torch.ops.aten.to.dtype, tuple(new_args) + ) + # temp hack to work around the issue https://github.com/pytorch/pytorch/issues/131679 + # When this issue is fixed, the clone node would be no longer needed + clone_node = self.fx_graph.call_function( + torch.ops.aten.clone.default, (fx_node,) + ) + output_name = node.output().debugName() + self.name_to_node[output_name] = clone_node + return + + self.convert_call_function_op(node) + + def convert_aten_add(self, node: torch._C.Node): + if node.schema() == "(no schema)": + if isinstance(node.inputsAt(0).type(), torch.ListType) and isinstance( + node.inputsAt(1).type(), torch.ListType + ): + target = torch.ops.aten.add.t + else: + raise RuntimeError(f"unable to determined the target for {node}") + else: + target = get_op_overload(node) + + if target is torch.ops.aten.add.t: + # special handle python list/tuple add: "aten::add.t(t[] a, t[] b) -> t[]" for + # RuntimeError: aten::add() Expected a value of type 'List[t]' for argument 'a' but instead found type 'immutable_list'. + args, _kwargs = self.get_args_kwargs(node, target._schema) + output_name = node.output().debugName() + self.name_to_node[output_name] = self.fx_graph.call_function(list_add, args) + else: + self.convert_call_function_op(node) + + def _check_prim_loop_support(self, node): + inputs = list(node.inputs()) + + # TODO: (1/N) stage. + if inputs[0].debugName() not in self.name_to_constant: + raise RuntimeError( + "prim::Loop currently cannot run with dynamic value of number of iterations." + ) + + # Make sure the condition is not updated in the subblock. + subblock = next(node.blocks()) + condition_output_name = next(subblock.outputs()).debugName() + for node in subblock.nodes(): + if ( + node.outputsSize() == 1 + and node.output().debugName() == condition_output_name + ): + raise RuntimeError( + "prim::Loop currently cannot run with dynamic value of condition." + ) + if node.outputsSize() >= 2: + for outp in node.outputs(): + if outp.debugName() == condition_output_name: + raise RuntimeError( + "prim::Loop currently cannot run with dynamic value of condition." + ) + + def convert_prim_Loop(self, node: torch._C.Node): + inputs = list(node.inputs()) + self._check_prim_loop_support(node) + + num_iterations = self.get_fx_value_by_ir_value(inputs[0]) + + # Find inputs. + loop_local_arguments = [inp.debugName() for inp in inputs[2:]] + + global_arguments = self._identify_inputs_as_arguments(node) + + # Lift parameters as inputs. + for block in node.blocks(): + global_arguments = global_arguments.union( + self.blocks_to_lifted_attrs[block] + ) + + global_arguments = list(global_arguments) + + subgraph_nodes, subgraph_converters = self._convert_block_to_subgraph( + node, global_arguments + ) + + if len(subgraph_nodes) != 1: + raise AssertionError(f"expected 1 subgraph node, got {len(subgraph_nodes)}") + subgraph_converter = subgraph_converters[0] + if not self.is_top_level_graph(): + self.name_update_from_subblock_to_parent = ( + self.name_update_from_subblock_to_parent.union( + subgraph_converter.name_update_from_subblock_to_parent + ) + ) + + fx_block_args = [ + self.get_fx_value_by_fqn(name) + for name in loop_local_arguments + global_arguments + ] + for iter_idx in range(num_iterations): + loop_node = self.fx_graph.call_function( + execute_subgraph_from_prim_loop, + # Check execute_node function for the expected arguments order. + ( + subgraph_nodes[0], + iter_idx, + len(loop_local_arguments), + *fx_block_args, + ), + {}, + ) + + # Update the value of loop local variables. + if node.outputsSize() >= 1: + for i, outp in enumerate(node.outputs()): + output_name = outp.debugName() + self.name_to_node[output_name] = self.fx_graph.call_function( + operator.getitem, + ( + loop_node, + i + 1, + ), # + 1 because the 0th element is the condition. + ) + fx_block_args[i] = self.name_to_node[output_name] + + # Update the value of global variables, whose values are modified inplace. + + for i, name in enumerate( + subgraph_converter.name_update_from_subblock_to_parent + ): + self.name_to_node[name] = self.fx_graph.call_function( + operator.getitem, + ( + loop_node, + i + node.outputsSize() + 1, + ), # + 1 because the 0th element is the condition. + ) + global_argument_index = global_arguments.index(name) + fx_block_args[i + node.outputsSize() + global_argument_index] = ( + self.name_to_node[name] + ) + + def _check_set_attr_in_if_block(self, if_node: torch._C.Node): + for block in if_node.blocks(): + for node in block.nodes(): + if node.kind() == "prim::SetAttr": + raise RuntimeError( + "During converting prim::If to torch.cond, found prim::SetAttr op" + " which is not supported yet. Please file an issue if you come " + "across this error." + ) + + def convert_prim_If(self, node: torch._C.Node): + self._check_set_attr_in_if_block(node) + + inputs = list(node.inputs()) + if len(inputs) != 1: + raise AssertionError(f"expected 1 input for prim::If, got {len(inputs)}") + predicate = self.get_fx_value_by_ir_value(inputs[0]) + + # Find inputs. + arguments = self._identify_inputs_as_arguments(node) + + # Lift parameters as inputs. + for block in node.blocks(): + arguments = arguments.union(self.blocks_to_lifted_attrs[block]) + + arguments = list(arguments) + subgraph_nodes, _ = self._convert_block_to_subgraph(node, arguments) + + if len(subgraph_nodes) != 2: + raise AssertionError( + f"expected 2 subgraph nodes, got {len(subgraph_nodes)}" + ) + + fx_block_args = [self.get_fx_value_by_fqn(name) for name in arguments] + + args = ( + predicate, + subgraph_nodes[0], + subgraph_nodes[1], + tuple(fx_block_args), + ) + + cond_node = self.fx_graph.call_function(torch.cond, args, {}) + + # prim::If can also have zero output. + if node.outputsSize() == 1: + output_name = node.output().debugName() + self.name_to_node[output_name] = cond_node + elif node.outputsSize() > 1: + for i, output in enumerate(node.outputs()): + output_name = output.debugName() + getitem = self.fx_graph.call_function(operator.getitem, (cond_node, i)) + self.name_to_node[output_name] = getitem + + def convert_aten_Bool(self, node: torch._C.Node): + self._convert_as_noop(node) + + def convert_prim_Enter(self, node: torch._C.Node): + # export generally treats prim::Enter as noop + # The only context manager export supports is aten::enable_grad. + # Unfortunately, TorchScript does not support aten::enable_grad yet. + # TODO: support aten::enable_grad in both TorchScript and Converter. + return + + def convert_prim_Exit(self, node: torch._C.Node): + # export treats prim::Exit as noop + return + + def _convert_as_noop(self, node: torch._C.Node): + # Converts the node as a no-op by mapping its output node as arg[0] + + target = get_op_overload(node) + schema = target._schema + + args, _kwargs = self.get_args_kwargs(node, schema) + + output_name = node.output().debugName() + self.name_to_node[output_name] = args[0] + + def convert_profiler__record_function_exit(self, node: torch._C.Node): + # _record_function_exit has side effect so we keep it in fx.graph + # currently, _record_function_enter_new and _record_function_exit are + # discarded during `retrace_as_exported_program`. + target = torch.ops.profiler._record_function_exit + args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs()) + self.fx_graph.call_function(target, args) + + def convert_prim_tolist(self, node: torch._C.Node): + # prim::tolist cannot be supported by `_convert_standard_operators` + # since it requires call_method instead of call_function. + target = "tolist" + args = (self.get_fx_value_by_ir_value(next(node.inputs())),) + fx_node = self.fx_graph.call_method(target, args) + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_prim_Uninitialized(self, node: torch._C.Node): + # `prim::Uninitialized` is inserted by the compiler when it can prove + # the value will never be used. It can be introduced by exceptions, + # breaks, continues, and returns. + # So we add a dummy constant to the graph. + output_name = node.output().debugName() + self.name_to_constant[output_name] = torch.Tensor() + + def _convert_standard_operators(self, node: torch._C.Node): + target = kind_to_standard_operators[node.kind()] + args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs()) + fx_node = self.fx_graph.call_function(target, args) + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_node(self, node: torch._C.Node): + node_kind = node.kind() + + # Get handler based on namespace and operator name. + # Provide a default node handler as well in case we don't find + # matching converter for that. + handler_func_name = ir_name_to_func_name(node_kind) + handler_func = getattr(self, handler_func_name, self.convert_call_function_op) + + # str calls print function implemented in CPP. To avoid repeating + # the entire logic here, we simply keep first line from node string (getting rid + # of sub-blocks IR prints). + node_str = "".join(str(node).split("\n")[:1]) + log.debug("[%s] converts [%s]", handler_func.__name__, node_str) + try: + handler_func(node) + except Exception as e: + raise RuntimeError(f"TS2EPConverter failed for node {node_kind}") from e + + def convert_graph_outputs(self): + args = [] + outp_name_list = [outp.debugName() for outp in self.ts_graph.outputs()] + list( + self.name_update_from_subblock_to_parent + ) + for output_name in outp_name_list: + if output_name in self.name_to_node: + fx_node = self.name_to_node[output_name] + # TODO: Revisit this later after HigherOrderOp design changes. + # Currently, we cannot directly return input as output. + if ( + not self.is_top_level_graph() + and isinstance(fx_node, torch.fx.Node) + and fx_node.op == "placeholder" + ): + fx_node = self.fx_graph.call_function(torch.clone, (fx_node,)) + args.append(fx_node) + self.output_specs.append( + OutputSpec( + OutputKind.USER_OUTPUT, + arg=TensorArgument(name=output_name), + target=output_name, + ) + ) + elif output_name in self.name_to_constant: + args.append(self.name_to_constant[output_name]) + self.output_specs.append( + OutputSpec( + OutputKind.USER_OUTPUT, + arg=ConstantArgument( + name=output_name, value=self.name_to_constant[output_name] + ), + target=output_name, + ) + ) + else: + raise ValueError(f"Output {output_name} not found") + + if len(args) == 0: + # Sub-block of prim::If can have zero output. + self.fx_graph.output([]) + elif len(args) == 1: + self.fx_graph.output( + args[0] + ) # Get rid of an extra list wrapped around final output. + elif len(args) > 1: + self.fx_graph.output( + args + ) # For prim::Loop and prim::If with multiple outputs. + else: + # Sub-block of prim::Loop can have multiple outputs. + self.fx_graph.output(args) + + +class ExplainTS2FXGraphConverter(TS2FXGraphConverter): + """ + Run TS2FXGraphConverter in an explain mode. It collects all failed operators conversions + and provide that information to users. In order to collect all failed conversions, it + also mocks some internal attributes (e.g., name_to_node). + """ + + class _DictMock(dict): + def __init__(self, dict_data, mock_value): + super().__init__(dict_data) + self.mock_value = mock_value + + def __getitem__(self, key): + # If the original dictionary has the key, return its value. + # Otherwise, return the mock value. + if not super().__contains__(key): + return self.mock_value + return super().__getitem__(key) + + def __contains__(self, key): + return True + + def __init__( + self, + ts_graph: torch._C.Graph | torch._C.Block, + name_to_param: dict[str, torch.Tensor], + name_to_buffer: dict[str, torch.Tensor], + blocks_to_lifted_attrs: dict[torch._C.Block, set[str]], + name_to_non_tensor_attribute: dict[str, Any], + name_to_constant: dict[str, Any], + name_to_attribute_fqn: dict[str, str], + ): + super().__init__( + ts_graph, + name_to_param, + name_to_buffer, + blocks_to_lifted_attrs, + name_to_non_tensor_attribute, + name_to_constant, + name_to_attribute_fqn, + ) + + # Data to keep track of unsupported nodes. + self.unsupported_node_list: list[torch._C.Node] = [] + + # Add mock to needed attributes. + self.name_to_node = ExplainTS2FXGraphConverter._DictMock( + self.name_to_node, + # Dummy node. + torch.fx.Node( + None, # type: ignore[arg-type] + "mock", + "call_function", + lambda: None, + (), + {}, + ), + ) + + def explain(self): + self.convert_graph_inputs() + for node in self.ts_graph.nodes(): + self.convert_node(node) + self.convert_graph_outputs() + + def convert_node(self, node): + try: + super().convert_node(node) + except Exception: + self.unsupported_node_list.append(node) + + +@contextmanager +def disable_logging(log): + disabled = log.disabled + log.disabled = True + try: + yield + finally: + log.disabled = disabled + + +class TS2EPConverter: + # TorchScript model to ExportedProgram converter + def __init__( + self, + ts_model: torch.jit.ScriptModule | torch.jit.ScriptFunction, + sample_args: tuple[Any, ...], + sample_kwargs: dict[str, Any] | None = None, + ): + self.ts_model = ts_model + self.ts_graph, self.params, _, _ = _create_jit_graph(ts_model, sample_args) + + self.sample_args = sample_args + self.sample_kwargs = sample_kwargs + + self.name_to_param: dict[str, torch.Tensor] = {} + self.name_to_buffer: dict[str, torch.Tensor] = {} + param_list = ( + list(self.ts_model.parameters()) + if not isinstance(self.ts_model, torch._C.ScriptFunction) + else [] + ) + if not isinstance(self.ts_model, torch._C.ScriptFunction): + for k, tensor in self.ts_model.state_dict().items(): # type: ignore[union-attr] + # Check if tensor belongs to any parameter. + if any( + (tensor == param).all() + for param in param_list + if tensor.shape == param.shape + ): + self.name_to_param[k] = tensor + else: + self.name_to_buffer[k] = tensor + + self.name_to_non_tensor_attributes: dict[str, Any] = {} + self.name_to_constant: dict[str, Any] = {} + + self.lift_get_attr() + + def convert(self) -> ExportedProgram: + log.info( + """ +TS2EPConverter logging starts from here. + +INFO: (TORCH_LOGS="export" ) + * Log TorchScript IR. + +DEBUG: (TORCH_LOGS="+export" ), additionally + * Log conversion IR by IR in a format of [] converts []. + """ + ) + log.info("TorchScript graph\n\n%s\n", self.ts_graph) + + blocks_to_lifted_attrs, name_to_attribute_fqn = get_block_to_lifted_attrs( + self.ts_graph + ) + + graph_converter = TS2FXGraphConverter( + self.ts_graph, + self.name_to_param, + self.name_to_buffer, + blocks_to_lifted_attrs, + self.name_to_non_tensor_attributes, + self.name_to_constant, + name_to_attribute_fqn, + ) + gm = graph_converter.convert() + + # Post-processing step to deal with quantized operators. + replace_quantized_ops_with_standard_ops(gm) + log.info("GraphModule: %s", gm.print_readable(print_output=False)) + + ep = self.retrace_as_exported_program( + gm, + graph_converter.name_to_constant, + ) + log.info("%s", ep) + + # Post-processing step to ensure ExportedProgram has the same state_dict as + # the original TorchScript model. Throw warnings for additionally populated + # state_dict entries. + if not isinstance(self.ts_model, torch._C.ScriptFunction): + for k, tensor in self.ts_model.state_dict().items(): # type: ignore[union-attr] + if k not in ep.state_dict: + warnings.warn( + f"Manually populate {k} into state_dict ExportedProgram, but it is never used by the ExportedProgram.", + stacklevel=2, + ) + ep.state_dict[k] = tensor + + return ep + + @disable_logging(log) + def explain(self, print_output=True): + blocks_to_lifted_attrs, name_to_attribute_fqn = get_block_to_lifted_attrs( + self.ts_graph + ) + + graph_converter = ExplainTS2FXGraphConverter( + self.ts_graph, + self.name_to_param, + self.name_to_buffer, + blocks_to_lifted_attrs, + self.name_to_non_tensor_attributes, + self.name_to_constant, + name_to_attribute_fqn, + ) + graph_converter.explain() + if len(graph_converter.unsupported_node_list) > 0: + explain_str = "Unsupported nodes are found in the following list:" + for i, n in enumerate(graph_converter.unsupported_node_list): + node_str = "".join(str(n).split("\n")[:1]) + explain_str += f"\n\n {i}. {n.kind()} [{node_str}]" + else: + explain_str = "Success!" + if print_output: + print(explain_str) + return explain_str + + def retrace_as_exported_program( + self, + gm: torch.fx.GraphModule, + name_to_constant: dict[str, Any], + ): + dynamic_shapes = _tree_map_with_path( + lambda path, x: ( + [Dim.AUTO] * x.dim() if isinstance(x, torch.Tensor) else None + ), + self.sample_args, + ) + + # TODO: adjust input orders to match GraphSignature convention + ep = torch.export._trace._export( + gm, + self.sample_args, + dynamic_shapes=dynamic_shapes, + strict=False, + pre_dispatch=True, + ) + + # Post-processing to make sure the ExportedProgram states are correct. + # Because during conversion, we set tensor constants as GetAttr, + # retracing cannot recognize them as tensor constants but instead + # treat them as buffers. We need to set them again here. + ep._constants.update( + { + k: v + for k, v in name_to_constant.items() + if isinstance(v, (torch.Tensor, torch.ScriptObject)) + } + ) + for k in name_to_constant: + ep.state_dict.pop(k, None) + + for spec in ep.graph_signature.input_specs: + # Mark as constant tensors for erroneously traced buffers. + if spec.kind == InputKind.BUFFER and spec.target in name_to_constant: + if not isinstance(name_to_constant[spec.target], torch.Tensor): + raise AssertionError( + f"{type(name_to_constant[spec.target])} has been erroneously marked as buffer" + ) + spec.kind = InputKind.CONSTANT_TENSOR + spec.persistent = None + ep.verifier().check(ep) + + return ep + + def lift_get_attr(self): + # This function lifts multiple data types. + + # 1. Tensor constants attributes (e.g., self.data = torch.tensor([2,3])) + # to buffers. Currently, when there are tensor constants, export + # would error and ask users to register tensor constants as buffers. + # Since it is hard to manually do so for TorchScript models + # (e.g., source code is missing), this function automatically + # lifts tensor constants to be buffers. + + # 2. ScriptObbject to constant. It will then be converted to getattr in + # in the fx graph. + # + # This function should happen in TS2EPConverter instead of + # TS2FXGraphConverter since it gets attributes from self.ts_model + # which is not accessible in TS2FXGraphConverter. It is similar to where + # we collect self.name_to_param and self.name_to_buffer. + name_to_attribute_fqn: dict[str, str] = {} + + def get_attr(fqn: str): + name = fqn.split(".") + v = self.ts_model + for n in name: + v = getattr(v, n) + return v + + def get_fqn(node: torch._C.Node): + attr_name = node.s("name") + input_name = node.input().debugName() + root_attr_name = name_to_attribute_fqn[input_name] + attr_fqn = f"{root_attr_name}.{attr_name}" if root_attr_name else attr_name + return attr_fqn + + def _dfs_get_attr(block): + for node in block.nodes(): + if node.kind() == "prim::CreateObject": + output_name = node.output().debugName() + name_to_attribute_fqn[output_name] = "" + + if node.kind() == "prim::GetAttr": + attr_fqn = get_fqn(node) + value = get_attr(attr_fqn) + output_name = node.output().debugName() + name_to_attribute_fqn[output_name] = attr_fqn + if isinstance(value, torch.Tensor): + if attr_fqn not in self.name_to_buffer: + # Lift tensor constants to be a buffer + self.name_to_buffer[attr_fqn] = value + elif isinstance(value, torch.ScriptObject): + if attr_fqn not in self.name_to_constant: + self.name_to_constant[attr_fqn] = value + else: + self.name_to_non_tensor_attributes[attr_fqn] = value + + for subblock in node.blocks(): + _dfs_get_attr(subblock) + + _dfs_get_attr(self.ts_graph) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/db/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f3f86783f6df5ad23665eab3adc8fe2c9f18d34 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/case.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/case.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f5f00281eac327b547f758294be3ed2ba9d200b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/case.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/gen_example.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/gen_example.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edf515e1b1524b0763d6741b22a8a575b4a0e155 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/gen_example.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/logging.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/logging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea225412fa0566e46d2aad4bda0ab6f376fd9248 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/logging.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/case.py b/.venv/lib/python3.12/site-packages/torch/_export/db/case.py new file mode 100644 index 0000000000000000000000000000000000000000..476fe9793a55ca6cf91277da97a8c7c5c02223f1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/case.py @@ -0,0 +1,177 @@ +# mypy: allow-untyped-defs +import inspect +import re +import string +from dataclasses import dataclass, field +from enum import Enum +from typing import Any +from types import ModuleType + +import torch + +_TAGS: dict[str, dict[str, Any]] = { + "torch": { + "cond": {}, + "dynamic-shape": {}, + "escape-hatch": {}, + "map": {}, + "dynamic-value": {}, + "operator": {}, + "mutation": {}, + }, + "python": { + "assert": {}, + "builtin": {}, + "closure": {}, + "context-manager": {}, + "control-flow": {}, + "data-structure": {}, + "standard-library": {}, + "object-model": {}, + }, +} + + +class SupportLevel(Enum): + """ + Indicates at what stage the feature + used in the example is handled in export. + """ + + SUPPORTED = 1 + NOT_SUPPORTED_YET = 0 + + +ArgsType = tuple[Any, ...] + + +def check_inputs_type(args, kwargs): + if not isinstance(args, tuple): + raise ValueError( + f"Expecting args type to be a tuple, got: {type(args)}" + ) + if not isinstance(kwargs, dict): + raise ValueError( + f"Expecting kwargs type to be a dict, got: {type(kwargs)}" + ) + for key in kwargs: + if not isinstance(key, str): + raise ValueError( + f"Expecting kwargs keys to be a string, got: {type(key)}" + ) + +def _validate_tag(tag: str): + parts = tag.split(".") + t = _TAGS + for part in parts: + if not set(part) <= set(string.ascii_lowercase + "-"): + raise AssertionError(f"Tag contains invalid characters: {part}") + if part in t: + t = t[part] + else: + raise ValueError(f"Tag {tag} is not found in registered tags.") + + +@dataclass(frozen=True) +class ExportCase: + example_args: ArgsType + description: str # A description of the use case. + model: torch.nn.Module + name: str + example_kwargs: dict[str, Any] = field(default_factory=dict) + extra_args: ArgsType | None = None # For testing graph generalization. + # Tags associated with the use case. (e.g dynamic-shape, escape-hatch) + tags: set[str] = field(default_factory=set) + support_level: SupportLevel = SupportLevel.SUPPORTED + dynamic_shapes: dict[str, Any] | None = None + + def __post_init__(self): + check_inputs_type(self.example_args, self.example_kwargs) + if self.extra_args is not None: + check_inputs_type(self.extra_args, {}) + + for tag in self.tags: + _validate_tag(tag) + + if not isinstance(self.description, str) or len(self.description) == 0: + raise ValueError(f'Invalid description: "{self.description}"') + + +_EXAMPLE_CASES: dict[str, ExportCase] = {} +_MODULES: set[ModuleType] = set() +_EXAMPLE_CONFLICT_CASES: dict[str, list[ExportCase]] = {} +_EXAMPLE_REWRITE_CASES: dict[str, list[ExportCase]] = {} + + +def register_db_case(case: ExportCase) -> None: + """ + Registers a user provided ExportCase into example bank. + """ + if case.name in _EXAMPLE_CASES: + if case.name not in _EXAMPLE_CONFLICT_CASES: + _EXAMPLE_CONFLICT_CASES[case.name] = [_EXAMPLE_CASES[case.name]] + _EXAMPLE_CONFLICT_CASES[case.name].append(case) + return + + _EXAMPLE_CASES[case.name] = case + + +def to_snake_case(name): + name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) + return re.sub("([a-z0-9])([A-Z])", r"\1_\2", name).lower() + + +def _make_export_case(m, name, configs): + if not isinstance(m, torch.nn.Module): + raise TypeError("Export case class should be a torch.nn.Module.") + + if "description" not in configs: + # Fallback to docstring if description is missing. + if m.__doc__ is None: + raise AssertionError( + f"Could not find description or docstring for export case: {m}" + ) + configs = {**configs, "description": m.__doc__} + # pyrefly: ignore [bad-argument-type] + return ExportCase(**{**configs, "model": m, "name": name}) + + +def export_case(**kwargs): + """ + Decorator for registering a user provided case into example bank. + """ + + def wrapper(m): + configs = kwargs + module = inspect.getmodule(m) + if module in _MODULES: + raise RuntimeError("export_case should only be used once per example file.") + + if module is None: + raise AssertionError("module must not be None") + _MODULES.add(module) + module_name = module.__name__.split(".")[-1] + case = _make_export_case(m, module_name, configs) + register_db_case(case) + return case + + return wrapper + + +def export_rewrite_case(**kwargs): + def wrapper(m): + configs = kwargs + + parent = configs.pop("parent") + if not isinstance(parent, ExportCase): + raise AssertionError(f"expected ExportCase, got {type(parent)}") + key = parent.name + if key not in _EXAMPLE_REWRITE_CASES: + _EXAMPLE_REWRITE_CASES[key] = [] + + configs["example_args"] = parent.example_args + case = _make_export_case(m, to_snake_case(m.__name__), configs) + _EXAMPLE_REWRITE_CASES[key].append(case) + return case + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..834dbce32f10bfb339fd2182a2455b43914441c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__init__.py @@ -0,0 +1,61 @@ +# mypy: allow-untyped-defs +import dataclasses +import glob +import inspect +from os.path import basename, dirname, isfile, join + +import torch +from torch._export.db.case import ( + _EXAMPLE_CASES, + _EXAMPLE_CONFLICT_CASES, + _EXAMPLE_REWRITE_CASES, + SupportLevel, + export_case, + ExportCase, +) + + +def _collect_examples(): + case_names = glob.glob(join(dirname(__file__), "*.py")) + case_names = [ + basename(f)[:-3] for f in case_names if isfile(f) and not f.endswith("__init__.py") + ] + + case_fields = {f.name for f in dataclasses.fields(ExportCase)} + for case_name in case_names: + case = __import__(case_name, globals(), locals(), [], 1) + variables = [name for name in dir(case) if name in case_fields] + export_case(**{v: getattr(case, v) for v in variables})(case.model) + +_collect_examples() + +def all_examples(): + return _EXAMPLE_CASES + + +if len(_EXAMPLE_CONFLICT_CASES) > 0: + + def get_name(case): + model = case.model + if isinstance(model, torch.nn.Module): + model = type(model) + return model.__name__ + + msg = "Error on conflict export case name.\n" + for case_name, cases in _EXAMPLE_CONFLICT_CASES.items(): + msg += f"Case name {case_name} is associated with multiple cases:\n " + msg += f"[{','.join(map(get_name, cases))}]\n" + + raise RuntimeError(msg) + + +def filter_examples_by_support_level(support_level: SupportLevel): + return { + key: val + for key, val in all_examples().items() + if val.support_level == support_level + } + + +def get_rewrite_cases(case): + return _EXAMPLE_REWRITE_CASES.get(case.name, []) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46cb4cd7f3249e44331f0f3dbd67ae2e8a9d7b1a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/assume_constant_result.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/assume_constant_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff5cf018ab885925cbba6274a12d268e0706b037 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/assume_constant_result.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/autograd_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/autograd_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4246922e767e992cd50423e050081818645106e3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/autograd_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/class_method.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/class_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..852515d19969847c998477fa2e860178c82a2060 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/class_method.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_class_method.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_class_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f1b013c91358b1b6037eabdd9b5369004a75fd8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_class_method.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nested_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nested_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1068490e888c002a08b39e7807f025720a3c214 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nested_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nonlocal_variables.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nonlocal_variables.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4e65f0aed3a5dec4eaffa7cf08a70a0d8409b8c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nonlocal_variables.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_closed_over_variable.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_closed_over_variable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d35fadcec4dd40508cd7e60ab4dca8fa33d20496 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_closed_over_variable.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_operands.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_operands.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1220fa29573be247cc003477e03693b9a0a4395 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_operands.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_predicate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_predicate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8d7be07e6888ba2c159fe5be7865681bfe96047 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_predicate.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_size_example.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_size_example.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c59e609a066bbdfeea6ed9a790795c54572b1ab3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_size_example.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_value_example.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_value_example.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b7462aad83acfda21ee48caf15cbc41a2be7fdc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_value_example.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/decorator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/decorator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f185552fb8c13f32b621e4b701e626d9026868f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/decorator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dictionary.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dictionary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f958d46f2a5fe93d3d12f8b4915273761b5bff43 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dictionary.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_assert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_assert.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..162c7bff02cd89662c9a18778d6d424f6167a3e2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_assert.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_constructor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_constructor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cec7cc7f5633233b9697142b4a7d43a85f48af25 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_constructor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_if_guard.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_if_guard.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10e871bcea7f053132ff02cc5e3bbd6751f43061 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_if_guard.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_map.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_map.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08702b2c486eea377bd6bdfbefe8af4c22c1b881 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_map.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_round.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_round.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b29f375207cc044ea2873c7150092ad3eb462f4f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_round.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_slicing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_slicing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..166878dce89061b9e0376ae1d9865c98c05446b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_slicing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_view.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_view.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09400082b59ce3eb9266025d0371daddceb90e52 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_view.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/fn_with_kwargs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/fn_with_kwargs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6bb2385550ec0717e352d8dd87524b5ca3d80da Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/fn_with_kwargs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_contains.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_contains.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d9779979def8587a5cb9bc4ef824367d8ab0fb8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_contains.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_unpack.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_unpack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7fd05bca4d6aeb2dfe2d684a2a7561210320b73 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_unpack.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/model_attr_mutation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/model_attr_mutation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b34e35d572ccb6cce6ca288d38219b72009681f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/model_attr_mutation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/nested_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/nested_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2286b1ea65ac5a5757fad2cbcf133d71b912432f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/nested_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/null_context_manager.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/null_context_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e539314149a92dad2d0f9e88d1116676994ca023 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/null_context_manager.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/optional_input.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/optional_input.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6b6f100ba36d857f4d75daf536f25164d646d8d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/optional_input.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/pytree_flatten.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/pytree_flatten.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..320a96c0e3b816ddb5ac49ca4c3768a54825fa78 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/pytree_flatten.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/scalar_output.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/scalar_output.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2ead47343b7bcc6352918077240c9afe8acc49f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/scalar_output.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/specialized_attribute.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/specialized_attribute.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eed7840364121d6454d3c388135c772bedd55ee7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/specialized_attribute.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_for_loop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_for_loop.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35739d45fcf1362d29dbcf40ecfc4664eabfe51d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_for_loop.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_if.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_if.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce25b9f99fc7737ddfe618240e8bbac061df4b6c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_if.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/tensor_setattr.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/tensor_setattr.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3142719fac0137122f16d8d92e71f5fa7aeac048 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/tensor_setattr.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/type_reflection_method.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/type_reflection_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b995e6d5ccb007524f206ea92391c1cf86c9b02d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/type_reflection_method.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/unsupported_operator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/unsupported_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e9b104fae57dc34b2dd659c9ca151a68e659100 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/unsupported_operator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/user_input_mutation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/user_input_mutation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cabbc012f13537ce1a2760a27bb0e34d7d376e2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/user_input_mutation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/assume_constant_result.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/assume_constant_result.py new file mode 100644 index 0000000000000000000000000000000000000000..ccd66f6c6f937004db4798a68719ce60fedc79c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/assume_constant_result.py @@ -0,0 +1,20 @@ +# mypy: allow-untyped-defs +import torch +import torch._dynamo as torchdynamo + + +class AssumeConstantResult(torch.nn.Module): + """ + Applying `assume_constant_result` decorator to burn make non-traceable code as constant. + """ + + @torchdynamo.assume_constant_result + def get_item(self, y): + return y.int().item() + + def forward(self, x, y): + return x[: self.get_item(y)] + +example_args = (torch.randn(3, 2), torch.tensor(4)) +tags = {"torch.escape-hatch"} +model = AssumeConstantResult() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/autograd_function.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/autograd_function.py new file mode 100644 index 0000000000000000000000000000000000000000..efd645d13a7d5a13dc69d9ab3593772520b726c0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/autograd_function.py @@ -0,0 +1,25 @@ +# mypy: allow-untyped-defs +import torch + +class MyAutogradFunction(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx, x): + return x.clone() + + @staticmethod + # pyrefly: ignore [bad-override] + def backward(ctx, grad_output): + return grad_output + 1 + +class AutogradFunction(torch.nn.Module): + """ + TorchDynamo does not keep track of backward() on autograd functions. We recommend to + use `allow_in_graph` to mitigate this problem. + """ + + def forward(self, x): + return MyAutogradFunction.apply(x) + +example_args = (torch.randn(3, 2),) +model = AutogradFunction() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/class_method.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/class_method.py new file mode 100644 index 0000000000000000000000000000000000000000..f701f54d4f4ea1cb5816292cd60bb4df3d03c5e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/class_method.py @@ -0,0 +1,22 @@ +# mypy: allow-untyped-defs +import torch + +class ClassMethod(torch.nn.Module): + """ + Class methods are inlined during tracing. + """ + + @classmethod + def method(cls, x): + return x + 1 + + def __init__(self) -> None: + super().__init__() + self.linear = torch.nn.Linear(4, 2) + + def forward(self, x): + x = self.linear(x) + return self.method(x) * self.__class__.method(x) * type(self).method(x) + +example_args = (torch.randn(3, 4),) +model = ClassMethod() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_class_method.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_class_method.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf9b8de296e4f4b61cf0f2666c02fda25ae60f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_class_method.py @@ -0,0 +1,44 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import cond + +class MySubModule(torch.nn.Module): + def foo(self, x): + return x.cos() + + def forward(self, x): + return self.foo(x) + +class CondBranchClassMethod(torch.nn.Module): + """ + The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules: + - both branches must take the same args, which must also match the branch args passed to cond. + - both branches must return a single tensor + - returned tensor must have the same tensor metadata, e.g. shape and dtype + - branch function can be free function, nested function, lambda, class methods + - branch function can not have closure variables + - no inplace mutations on inputs or global variables + + + This example demonstrates using class method in cond(). + + NOTE: If the `pred` is tested on a dim with batch size < 2, it will be specialized. + """ + + def __init__(self) -> None: + super().__init__() + self.subm = MySubModule() + + def bar(self, x): + return x.sin() + + def forward(self, x): + return cond(x.shape[0] <= 2, self.subm.forward, self.bar, [x]) + +example_args = (torch.randn(3),) +tags = { + "torch.cond", + "torch.dynamic-shape", +} +model = CondBranchClassMethod() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nested_function.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nested_function.py new file mode 100644 index 0000000000000000000000000000000000000000..ab52d8c8cde45d0855d6807df3081c72f9ab97da --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nested_function.py @@ -0,0 +1,41 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import cond + +class CondBranchNestedFunction(torch.nn.Module): + """ + The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules: + - both branches must take the same args, which must also match the branch args passed to cond. + - both branches must return a single tensor + - returned tensor must have the same tensor metadata, e.g. shape and dtype + - branch function can be free function, nested function, lambda, class methods + - branch function can not have closure variables + - no inplace mutations on inputs or global variables + + This example demonstrates using nested function in cond(). + + NOTE: If the `pred` is tested on a dim with batch size < 2, it will be specialized. + """ + + def forward(self, x): + def true_fn(x): + def inner_true_fn(y): + return x + y + + return inner_true_fn(x) + + def false_fn(x): + def inner_false_fn(y): + return x - y + + return inner_false_fn(x) + + return cond(x.shape[0] < 10, true_fn, false_fn, [x]) + +example_args = (torch.randn(3),) +tags = { + "torch.cond", + "torch.dynamic-shape", +} +model = CondBranchNestedFunction() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py new file mode 100644 index 0000000000000000000000000000000000000000..73df8add4703186bd3a0219b9e4eb845f35e0811 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py @@ -0,0 +1,59 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import cond + +class CondBranchNonlocalVariables(torch.nn.Module): + """ + The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules: + - both branches must take the same args, which must also match the branch args passed to cond. + - both branches must return a single tensor + - returned tensor must have the same tensor metadata, e.g. shape and dtype + - branch function can be free function, nested function, lambda, class methods + - branch function can not have closure variables + - no inplace mutations on inputs or global variables + + This example demonstrates how to rewrite code to avoid capturing closure variables in branch functions. + + The code below will not work because capturing closure variables is not supported. + ``` + my_tensor_var = x + 100 + my_primitive_var = 3.14 + + def true_fn(y): + nonlocal my_tensor_var, my_primitive_var + return y + my_tensor_var + my_primitive_var + + def false_fn(y): + nonlocal my_tensor_var, my_primitive_var + return y - my_tensor_var - my_primitive_var + + return cond(x.shape[0] > 5, true_fn, false_fn, [x]) + ``` + + NOTE: If the `pred` is tested on a dim with batch size < 2, it will be specialized. + """ + + def forward(self, x): + my_tensor_var = x + 100 + my_primitive_var = 3.14 + + def true_fn(x, y, z): + return x + y + z + + def false_fn(x, y, z): + return x - y - z + + return cond( + x.shape[0] > 5, + true_fn, + false_fn, + [x, my_tensor_var, torch.tensor(my_primitive_var)], + ) + +example_args = (torch.randn(6),) +tags = { + "torch.cond", + "torch.dynamic-shape", +} +model = CondBranchNonlocalVariables() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_closed_over_variable.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_closed_over_variable.py new file mode 100644 index 0000000000000000000000000000000000000000..183180ab4fc825385170fea2bec6af184374a67e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_closed_over_variable.py @@ -0,0 +1,22 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import cond + +class CondClosedOverVariable(torch.nn.Module): + """ + torch.cond() supports branches closed over arbitrary variables. + """ + + def forward(self, pred, x): + def true_fn(val): + return x * 2 + + def false_fn(val): + return x - 2 + + return cond(pred, true_fn, false_fn, [x + 1]) + +example_args = (torch.tensor(True), torch.randn(3, 2)) +tags = {"torch.cond", "python.closure"} +model = CondClosedOverVariable() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_operands.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_operands.py new file mode 100644 index 0000000000000000000000000000000000000000..d94e59c121788b6bba6dd52931e0048c04467ad2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_operands.py @@ -0,0 +1,35 @@ +# mypy: allow-untyped-defs +import torch + +from torch.export import Dim + +x = torch.randn(3, 2) +y = torch.randn(2) +dim0_x = Dim("dim0_x") + +class CondOperands(torch.nn.Module): + """ + The operands passed to cond() must be: + - a list of tensors + - match arguments of `true_fn` and `false_fn` + + NOTE: If the `pred` is tested on a dim with batch size < 2, it will be specialized. + """ + + def forward(self, x, y): + def true_fn(x, y): + return x + y + + def false_fn(x, y): + return x - y + + return torch.cond(x.shape[0] > 2, true_fn, false_fn, [x, y]) + +example_args = (x, y) +tags = { + "torch.cond", + "torch.dynamic-shape", +} +extra_inputs = (torch.randn(2, 2), torch.randn(2)) +dynamic_shapes = {"x": {0: dim0_x}, "y": None} +model = CondOperands() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_predicate.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_predicate.py new file mode 100644 index 0000000000000000000000000000000000000000..20ce1d6c8340b5462f5b1d13d0900706437d97d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_predicate.py @@ -0,0 +1,25 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import cond + +class CondPredicate(torch.nn.Module): + """ + The conditional statement (aka predicate) passed to cond() must be one of the following: + - torch.Tensor with a single element + - boolean expression + + NOTE: If the `pred` is tested on a dim with batch size < 2, it will be specialized. + """ + + def forward(self, x): + pred = x.dim() > 2 and x.shape[2] > 10 + + return cond(pred, lambda x: x.cos(), lambda y: y.sin(), [x]) + +example_args = (torch.randn(6, 4, 3),) +tags = { + "torch.cond", + "torch.dynamic-shape", +} +model = CondPredicate() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_size_example.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_size_example.py new file mode 100644 index 0000000000000000000000000000000000000000..934746aaf6739de7a37077d8ec3c2776586a5657 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_size_example.py @@ -0,0 +1,23 @@ +# mypy: allow-untyped-defs +import torch + + +class ConstrainAsSizeExample(torch.nn.Module): + """ + If the value is not known at tracing time, you can provide hint so that we + can trace further. Please look at torch._check APIs. + """ + + def forward(self, x): + a = x.item() + torch._check(a >= 0) + torch._check(a <= 5) + return torch.zeros((a, 5)) + + +example_args = (torch.tensor(4),) +tags = { + "torch.dynamic-value", + "torch.escape-hatch", +} +model = ConstrainAsSizeExample() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_value_example.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_value_example.py new file mode 100644 index 0000000000000000000000000000000000000000..22f791a3e80474257c27d927bad56cf4c2fbce78 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_value_example.py @@ -0,0 +1,26 @@ +# mypy: allow-untyped-defs +import torch + + +class ConstrainAsValueExample(torch.nn.Module): + """ + If the value is not known at tracing time, you can provide hint so that we + can trace further. Please look at torch._check API. + """ + + def forward(self, x, y): + a = x.item() + torch._check(a >= 0) + torch._check(a <= 5) + + if a < 6: + return y.sin() + return y.cos() + + +example_args = (torch.tensor(4), torch.randn(5, 5)) +tags = { + "torch.dynamic-value", + "torch.escape-hatch", +} +model = ConstrainAsValueExample() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/decorator.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..7d24cc681a6b62adf40bfd9a2e5283afb3515131 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/decorator.py @@ -0,0 +1,23 @@ +# mypy: allow-untyped-defs +import functools + +import torch + +def test_decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + 1 + + return wrapper + +class Decorator(torch.nn.Module): + """ + Decorators calls are inlined into the exported function during tracing. + """ + + @test_decorator + def forward(self, x, y): + return x + y + +example_args = (torch.randn(3, 2), torch.randn(3, 2)) +model = Decorator() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dictionary.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dictionary.py new file mode 100644 index 0000000000000000000000000000000000000000..49e688bc0ac1f09567e3b877aaca29a1d02b4121 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dictionary.py @@ -0,0 +1,17 @@ +# mypy: allow-untyped-defs +import torch + +class Dictionary(torch.nn.Module): + """ + Dictionary structures are inlined and flattened along tracing. + """ + + def forward(self, x, y): + elements = {} + elements["x2"] = x * x + y = y * elements["x2"] + return {"y": y} + +example_args = (torch.randn(3, 2), torch.tensor(4)) +tags = {"python.data-structure"} +model = Dictionary() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_assert.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_assert.py new file mode 100644 index 0000000000000000000000000000000000000000..abf40db97dd459b24dad35a14d1576ae6d1c93a1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_assert.py @@ -0,0 +1,18 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeAssert(torch.nn.Module): + """ + A basic usage of python assertion. + """ + + def forward(self, x): + # assertion with error message + assert x.shape[0] > 2, f"{x.shape[0]} is greater than 2" # noqa: S101 + # assertion without error message + assert x.shape[0] > 1 # noqa: S101 + return x + +example_args = (torch.randn(3, 2),) +tags = {"python.assert"} +model = DynamicShapeAssert() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..157e460274ad58ba71c886b35364ddc0cd4d886a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py @@ -0,0 +1,15 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeConstructor(torch.nn.Module): + """ + Tensor constructors should be captured with dynamic shape inputs rather + than being baked in with static shape. + """ + + def forward(self, x): + return torch.zeros(x.shape[0] * 2) + +example_args = (torch.randn(3, 2),) +tags = {"torch.dynamic-shape"} +model = DynamicShapeConstructor() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_if_guard.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_if_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..90e336868ce4e784f2799d86c5887cec91e887e6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_if_guard.py @@ -0,0 +1,19 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeIfGuard(torch.nn.Module): + """ + `if` statement with backed dynamic shape predicate will be specialized into + one particular branch and generate a guard. However, export will fail if the + dimension is marked as dynamic shape from higher level API. + """ + + def forward(self, x): + if x.shape[0] == 3: + return x.cos() + + return x.sin() + +example_args = (torch.randn(3, 2, 2),) +tags = {"torch.dynamic-shape", "python.control-flow"} +model = DynamicShapeIfGuard() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_map.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_map.py new file mode 100644 index 0000000000000000000000000000000000000000..f8066aed556b9ee588b9744d17ba16c35d8fed6c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_map.py @@ -0,0 +1,19 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import map + +class DynamicShapeMap(torch.nn.Module): + """ + functorch map() maps a function over the first tensor dimension. + """ + + def forward(self, xs, y): + def body(x, y): + return x + y + + return map(body, xs, y) + +example_args = (torch.randn(3, 2), torch.randn(2)) +tags = {"torch.dynamic-shape", "torch.map"} +model = DynamicShapeMap() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_round.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_round.py new file mode 100644 index 0000000000000000000000000000000000000000..decbf036553cb76544a19e531e5aee98d792ae0b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_round.py @@ -0,0 +1,21 @@ +# mypy: allow-untyped-defs +import torch + +from torch._export.db.case import SupportLevel +from torch.export import Dim + +class DynamicShapeRound(torch.nn.Module): + """ + Calling round on dynamic shapes is not supported. + """ + + def forward(self, x): + return x[: round(x.shape[0] / 2)] + +x = torch.randn(3, 2) +dim0_x = Dim("dim0_x") +example_args = (x,) +tags = {"torch.dynamic-shape", "python.builtin"} +support_level = SupportLevel.NOT_SUPPORTED_YET +dynamic_shapes = {"x": {0: dim0_x}} +model = DynamicShapeRound() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_slicing.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_slicing.py new file mode 100644 index 0000000000000000000000000000000000000000..360fe15f6f98d9d735366bfa53371d79e0b00209 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_slicing.py @@ -0,0 +1,15 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeSlicing(torch.nn.Module): + """ + Slices with dynamic shape arguments should be captured into the graph + rather than being baked in. + """ + + def forward(self, x): + return x[: x.shape[0] - 2, x.shape[1] - 1 :: 2] + +example_args = (torch.randn(3, 2),) +tags = {"torch.dynamic-shape"} +model = DynamicShapeSlicing() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_view.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_view.py new file mode 100644 index 0000000000000000000000000000000000000000..c45d4aeebb0282a0f56c58a587b4bfe1655f50e3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_view.py @@ -0,0 +1,17 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeView(torch.nn.Module): + """ + Dynamic shapes should be propagated to view arguments instead of being + baked into the exported graph. + """ + + def forward(self, x): + new_x_shape = x.size()[:-1] + (2, 5) + x = x.view(*new_x_shape) + return x.permute(0, 2, 1) + +example_args = (torch.randn(10, 10),) +tags = {"torch.dynamic-shape"} +model = DynamicShapeView() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/fn_with_kwargs.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/fn_with_kwargs.py new file mode 100644 index 0000000000000000000000000000000000000000..46b2637b398c21bf9399d0a3fa2a964354beea3e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/fn_with_kwargs.py @@ -0,0 +1,30 @@ +# mypy: allow-untyped-defs +import torch + +class FnWithKwargs(torch.nn.Module): + """ + Keyword arguments are not supported at the moment. + """ + + def forward(self, pos0, tuple0, *myargs, mykw0, **mykwargs): + out = pos0 + for arg in tuple0: + out = out * arg + for arg in myargs: + out = out * arg + out = out * mykw0 + out = out * mykwargs["input0"] * mykwargs["input1"] + return out + +example_args = ( + torch.randn(4), + (torch.randn(4), torch.randn(4)), + *[torch.randn(4), torch.randn(4)] +) +example_kwargs = { + "mykw0": torch.randn(4), + "input0": torch.randn(4), + "input1": torch.randn(4), +} +tags = {"python.data-structure"} +model = FnWithKwargs() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_contains.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_contains.py new file mode 100644 index 0000000000000000000000000000000000000000..150070945cfa7f2ef7aca1f8c3dfece0f07cbecd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_contains.py @@ -0,0 +1,17 @@ +# mypy: allow-untyped-defs +import torch + +class ListContains(torch.nn.Module): + """ + List containment relation can be checked on a dynamic shape or constants. + """ + + def forward(self, x): + assert x.size(-1) in [6, 2] # noqa: S101 + assert x.size(0) not in [4, 5, 6] # noqa: S101 + assert "monkey" not in ["cow", "pig"] # noqa: S101 + return x + x + +example_args = (torch.randn(3, 2),) +tags = {"torch.dynamic-shape", "python.data-structure", "python.assert"} +model = ListContains() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_unpack.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_unpack.py new file mode 100644 index 0000000000000000000000000000000000000000..98533cfab5498934a61fbe693bb2497d5dbc9738 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_unpack.py @@ -0,0 +1,21 @@ +# mypy: allow-untyped-defs + +import torch + +class ListUnpack(torch.nn.Module): + """ + Lists are treated as static construct, therefore unpacking should be + erased after tracing. + """ + + def forward(self, args: list[torch.Tensor]): + """ + Lists are treated as static construct, therefore unpacking should be + erased after tracing. + """ + x, *y = args + return x + y[0] + +example_args = ([torch.randn(3, 2), torch.tensor(4), torch.tensor(5)],) +tags = {"python.control-flow", "python.data-structure"} +model = ListUnpack() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/model_attr_mutation.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/model_attr_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..122b0ddfc3429fb31415a146e8e1dcfddb2fe031 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/model_attr_mutation.py @@ -0,0 +1,24 @@ +# mypy: allow-untyped-defs +import torch + + +class ModelAttrMutation(torch.nn.Module): + """ + Attribute mutation raises a warning. Covered in the test_export.py test_detect_leak_strict test. + """ + + def __init__(self) -> None: + super().__init__() + self.attr_list = [torch.randn(3, 2), torch.randn(3, 2)] + + def recreate_list(self): + return [torch.zeros(3, 2), torch.zeros(3, 2)] + + def forward(self, x): + self.attr_list = self.recreate_list() + return x.sum() + self.attr_list[0].sum() + + +example_args = (torch.randn(3, 2),) +tags = {"python.object-model"} +model = ModelAttrMutation() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/nested_function.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/nested_function.py new file mode 100644 index 0000000000000000000000000000000000000000..e4076ac14dada40b4d78812666a9ec6b5e67045b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/nested_function.py @@ -0,0 +1,23 @@ +# mypy: allow-untyped-defs +import torch + +class NestedFunction(torch.nn.Module): + """ + Nested functions are traced through. Side effects on global captures + are not supported though. + """ + + def forward(self, a, b): + x = a + b + z = a - b + + def closure(y): + nonlocal x + x += 1 + return x * y + z + + return closure(x) + +example_args = (torch.randn(3, 2), torch.randn(2)) +tags = {"python.closure"} +model = NestedFunction() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/null_context_manager.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/null_context_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..80d09f68097edbe676077be183711dabe5cbc664 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/null_context_manager.py @@ -0,0 +1,21 @@ +# mypy: allow-untyped-defs +import contextlib + +import torch + +class NullContextManager(torch.nn.Module): + """ + Null context manager in Python will be traced out. + """ + + def forward(self, x): + """ + Null context manager in Python will be traced out. + """ + ctx = contextlib.nullcontext() + with ctx: + return x.sin() + x.cos() + +example_args = (torch.randn(3, 2),) +tags = {"python.context-manager"} +model = NullContextManager() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/optional_input.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/optional_input.py new file mode 100644 index 0000000000000000000000000000000000000000..41e66a7c977a83bf59116864c7f443387277f06e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/optional_input.py @@ -0,0 +1,20 @@ +# mypy: allow-untyped-defs +import torch +from torch._export.db.case import SupportLevel + + +class OptionalInput(torch.nn.Module): + """ + Tracing through optional input is not supported yet + """ + + def forward(self, x, y=torch.randn(2, 3)): + if y is not None: + return x + y + return x + + +example_args = (torch.randn(2, 3),) +tags = {"python.object-model"} +support_level = SupportLevel.SUPPORTED +model = OptionalInput() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/pytree_flatten.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/pytree_flatten.py new file mode 100644 index 0000000000000000000000000000000000000000..804e73c5a6d58ad5b5be179bf67a5d5bc38c2e2b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/pytree_flatten.py @@ -0,0 +1,16 @@ +# mypy: allow-untyped-defs +import torch + +from torch.utils import _pytree as pytree + +class PytreeFlatten(torch.nn.Module): + """ + Pytree from PyTorch can be captured by TorchDynamo. + """ + + def forward(self, x): + y, _spec = pytree.tree_flatten(x) + return y[0] + 1 + +example_args = ({1: torch.randn(3, 2), 2: torch.randn(3, 2)},), +model = PytreeFlatten() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/scalar_output.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/scalar_output.py new file mode 100644 index 0000000000000000000000000000000000000000..86d3b4645330c47c3625736b695d635f4ab58c70 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/scalar_output.py @@ -0,0 +1,23 @@ +# mypy: allow-untyped-defs +import torch + +from torch.export import Dim + +x = torch.randn(3, 2) +dim1_x = Dim("dim1_x") + +class ScalarOutput(torch.nn.Module): + """ + Returning scalar values from the graph is supported, in addition to Tensor + outputs. Symbolic shapes are captured and rank is specialized. + """ + def __init__(self) -> None: + super().__init__() + + def forward(self, x): + return x.shape[1] + 1 + +example_args = (x,) +tags = {"torch.dynamic-shape"} +dynamic_shapes = {"x": {1: dim1_x}} +model = ScalarOutput() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/specialized_attribute.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/specialized_attribute.py new file mode 100644 index 0000000000000000000000000000000000000000..f17092f9afc681b91a982a8a2479ac1dde4f455d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/specialized_attribute.py @@ -0,0 +1,26 @@ +# mypy: allow-untyped-defs +from enum import Enum + +import torch + +class Animal(Enum): + COW = "moo" + +class SpecializedAttribute(torch.nn.Module): + """ + Model attributes are specialized. + """ + + def __init__(self) -> None: + super().__init__() + self.a = "moo" + self.b = 4 + + def forward(self, x): + if self.a == Animal.COW.value: + return x * x + self.b + else: + raise ValueError("bad") + +example_args = (torch.randn(3, 2),) +model = SpecializedAttribute() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_for_loop.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_for_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..aa62b86d16d9b6a1c539976a891f58bd732ae30d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_for_loop.py @@ -0,0 +1,16 @@ +# mypy: allow-untyped-defs +import torch + +class StaticForLoop(torch.nn.Module): + """ + A for loop with constant number of iterations should be unrolled in the exported graph. + """ + + def forward(self, x): + # constant + ret = [i + x for i in range(10)] + return ret + +example_args = (torch.randn(3, 2),) +tags = {"python.control-flow"} +model = StaticForLoop() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_if.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_if.py new file mode 100644 index 0000000000000000000000000000000000000000..f169380159a45489142ce5ae3523b2e4504c6721 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_if.py @@ -0,0 +1,18 @@ +# mypy: allow-untyped-defs +import torch + +class StaticIf(torch.nn.Module): + """ + `if` statement with static predicate value should be traced through with the + taken branch. + """ + + def forward(self, x): + if len(x.shape) == 3: + return x + torch.ones(1, 1, 1) + + return x + +example_args = (torch.randn(3, 2, 2),) +tags = {"python.control-flow"} +model = StaticIf() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/tensor_setattr.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/tensor_setattr.py new file mode 100644 index 0000000000000000000000000000000000000000..8fbc263e7ff2240a3cf8618c56f152e744aa40e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/tensor_setattr.py @@ -0,0 +1,15 @@ +# mypy: allow-untyped-defs +import torch + + +class TensorSetattr(torch.nn.Module): + """ + setattr() call onto tensors is not supported. + """ + def forward(self, x, attr): + setattr(x, attr, torch.randn(3, 2)) + return x + 4 + +example_args = (torch.randn(3, 2), "attr") +tags = {"python.builtin"} +model = TensorSetattr() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/type_reflection_method.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/type_reflection_method.py new file mode 100644 index 0000000000000000000000000000000000000000..99ad42a153c512d65aaae1bcac2377ee1e124f25 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/type_reflection_method.py @@ -0,0 +1,22 @@ +# mypy: allow-untyped-defs +import torch + +class A: + @classmethod + def func(cls, x): + return 1 + x + +class TypeReflectionMethod(torch.nn.Module): + """ + type() calls on custom objects followed by attribute accesses are not allowed + due to its overly dynamic nature. + """ + + def forward(self, x): + a = A() + return type(a).func(x) + + +example_args = (torch.randn(3, 4),) +tags = {"python.builtin"} +model = TypeReflectionMethod() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/unsupported_operator.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/unsupported_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5475c5f15fe35c9ba2be57f295f568602b82c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/unsupported_operator.py @@ -0,0 +1,18 @@ +# mypy: allow-untyped-defs +import torch +from torch._export.db.case import SupportLevel + + +class TorchSymMin(torch.nn.Module): + """ + torch.sym_min operator is supported in export. + """ + + def forward(self, x): + return x.sum() + torch.sym_min(x.size(0), 100) + + +example_args = (torch.randn(3, 2),) +tags = {"torch.operator"} +support_level = SupportLevel.SUPPORTED +model = TorchSymMin() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/user_input_mutation.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/user_input_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..3156b3a1bf2ec6f6361395de3dacb098ecf20c3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/user_input_mutation.py @@ -0,0 +1,17 @@ +# mypy: allow-untyped-defs +import torch + + +class UserInputMutation(torch.nn.Module): + """ + Directly mutate user input in forward + """ + + def forward(self, x): + x.mul_(2) + return x.cos() + + +example_args = (torch.randn(3, 2),) +tags = {"torch.mutation"} +model = UserInputMutation() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/gen_example.py b/.venv/lib/python3.12/site-packages/torch/_export/db/gen_example.py new file mode 100644 index 0000000000000000000000000000000000000000..5c422f457bc3c7c1d7bc5d17dd4e93b8558a5de4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/gen_example.py @@ -0,0 +1,23 @@ +import os +import sys + +import torch._export.db.examples as examples + +TEMPLATE = '''import torch + +def {case_name}(x): + """ + """ + + return +''' + +if __name__ == "__main__": + if len(sys.argv) != 2: + raise AssertionError(f"expected 2 arguments, got {len(sys.argv)}") + root_dir = examples.__name__.replace(".", "/") + if not os.path.exists(root_dir): + raise AssertionError(f"root_dir does not exist: {root_dir}") + with open(os.path.join(root_dir, sys.argv[1] + ".py"), "w") as f: + print("Writing to", f.name, "...") + f.write(TEMPLATE.format(case_name=sys.argv[1])) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/logging.py b/.venv/lib/python3.12/site-packages/torch/_export/db/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..1416b1e99c2d163bcceced1ef827a5292bed0565 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/logging.py @@ -0,0 +1,46 @@ + +def exportdb_error_message(case_name: str) -> str: + from .examples import all_examples + from torch._utils_internal import log_export_usage + + ALL_EXAMPLES = all_examples() + # Detect whether case_name is really registered in exportdb. + if case_name in ALL_EXAMPLES: + url_case_name = case_name.replace("_", "-") + return f"See {case_name} in exportdb for unsupported case. \ + https://pytorch.org/docs/main/generated/exportdb/index.html#{url_case_name}" + else: + log_export_usage( + event="export.error.casenotregistered", + message=case_name, + ) + return f"{case_name} is unsupported." + + +def get_class_if_classified_error(e: Exception) -> str | None: + """ + Returns a string case name if the export error e is classified. + Returns None otherwise. + """ + + from torch._dynamo.exc import TorchRuntimeError, Unsupported, UserError + + ALWAYS_CLASSIFIED = "always_classified" + DEFAULT_CLASS_SIGIL = "case_name" + + # add error types that should be classified, along with any attribute name + # whose presence acts like a sigil to further distinguish which errors of + # that type should be classified. If the attribute name is None, then the + # error type is always classified. + _ALLOW_LIST = { + Unsupported: DEFAULT_CLASS_SIGIL, + UserError: DEFAULT_CLASS_SIGIL, + TorchRuntimeError: None, + } + if type(e) in _ALLOW_LIST: + # pyrefly: ignore [bad-index, index-error] + attr_name = _ALLOW_LIST[type(e)] + if attr_name is None: + return ALWAYS_CLASSIFIED + return getattr(e, attr_name, None) + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_export/error.py b/.venv/lib/python3.12/site-packages/torch/_export/error.py new file mode 100644 index 0000000000000000000000000000000000000000..03b7f52fb9de435b9e58fa4a0bb141cc191e84c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/error.py @@ -0,0 +1,56 @@ +from enum import Enum + + +class ExportErrorType(Enum): + # User providing invalid inputs to either tracer, or other public facing APIs + INVALID_INPUT_TYPE = 1 + + # User returning values from their models that we don't support. + INVALID_OUTPUT_TYPE = 2 + + # Generated IR does not conform to Export IR Specification. + VIOLATION_OF_SPEC = 3 + + # User's code contains types and functionalities we don't support. + NOT_SUPPORTED = 4 + + # User's code didn't provide necessary details for us to successfully trace and export. + # For example, we use a lot of decorators and ask users to annotate their model. + MISSING_PROPERTY = 5 + + # User is using an API without proper initialization step. + UNINITIALIZED = 6 + + +def internal_assert(pred: bool, assert_msg: str) -> None: + """ + This is exir's custom assert method. It internally just throws InternalError. + Note that the sole purpose is to throw our own error while maintaining similar syntax + as python assert. + """ + + if not pred: + raise InternalError(assert_msg) + + +class InternalError(Exception): + """ + Raised when an internal invariance is violated in EXIR stack. + Should hint users to report a bug to dev and expose the original + error message. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class ExportError(Exception): + """ + This type of exception is raised for errors that are directly caused by the user + code. In general, user errors happen during model authoring, tracing, using our public + facing APIs, and writing graph passes. + """ + + def __init__(self, error_code: ExportErrorType, message: str) -> None: + prefix = f"[{error_code}]: " + super().__init__(prefix + message) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/non_strict_utils.py b/.venv/lib/python3.12/site-packages/torch/_export/non_strict_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7e444cd87f82ce1c13456a7f6635427ff6943c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/non_strict_utils.py @@ -0,0 +1,1384 @@ +import builtins +import contextlib +import functools +import inspect +import logging +import math +import sys +from collections import defaultdict +from collections.abc import Callable, Generator, Sequence +from contextlib import contextmanager +from typing import Any, cast, TYPE_CHECKING, TypeGuard, TypeVar + +import torch +import torch.utils._pytree as pytree +from torch._custom_class_base import CustomClassBase +from torch._dynamo.source import ( + AttrSource, + GetItemSource, + LocalSource, + TensorProperty, + TensorPropertySource, +) +from torch._dynamo.variables.builder import TrackedFake +from torch._export.passes.lift_constants_pass import ConstantAttrMap +from torch._export.utils import _fakify_params_buffers +from torch._guards import Source +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class_obj +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.export import Constraint +from torch.export.dynamic_shapes import ( + _check_dynamic_shapes, + _combine_args, + _DimHint, + _DimHintType, + _IntWrapper, + _process_dynamic_shapes, + _RelaxedConstraint, + _tree_map_with_path, +) +from torch.export.graph_signature import CustomObjArgument +from torch.fx.experimental import _config as config +from torch.fx.experimental.symbolic_shapes import ( + _find_user_code_frame, + _suggest_fixes_for_data_dependent_error_non_strict, + ConstraintViolationError, + DimDynamic, + EqualityConstraint, + GuardOnDataDependentSymNode, + RelaxedUnspecConstraint, + ShapeEnv, + StatelessSymbolicContext, + SymIntSymbolicContext, + ValueRanges, +) +from torch.utils._pytree import ( + GetAttrKey, + KeyPath, + MappingKey, + SequenceKey, + tree_map_with_path, +) +from torch.utils._sympy.numbers import int_oo + + +if TYPE_CHECKING: + from sympy import Expr, Symbol + + from torch.fx.experimental.dynamic_spec import ParamsSpec, ShapesSpec + from torch.fx.experimental.symbolic_shapes import SymbolicContext + + +log = logging.getLogger(__name__) + + +_ModuleT = TypeVar("_ModuleT", bound=torch.nn.Module) + + +_DATA_PTR_ACCESS_ERROR = "Cannot access data pointer of Tensor" +_RAW_TRITON_KERNEL_NON_STRICT_EXPORT_ERROR = ( + "Raw Triton kernel calls are not supported by non-strict torch.export. " + "Wrap the kernel in a torch.library.triton_op and call it through " + "torch.library.wrap_triton (or torch._library.capture_triton) so export " + "records a stable custom operator instead of tracing into Triton's runtime." +) + + +def _is_raw_triton_kernel_data_ptr_error( + func: Callable[..., object], exc: RuntimeError +) -> bool: + if getattr(func, "__name__", None) != "data_ptr": + return False + if _DATA_PTR_ACCESS_ERROR not in str(exc): + return False + + for frame in inspect.stack(context=0): + filename = frame.filename.replace("\\", "/") + if "/triton/runtime/" in filename: + return True + return False + + +class _KeyPath: + """ + Wraps `KeyPath` to aid `isinstance` checks. + """ + + def __init__(self, kp: KeyPath) -> None: + self.kp = kp + + +class _KeyPathTrie: + """ + Builds a trie of `KeyPath` prefixes mapping to `Source` leaves. + """ + + def __init__(self) -> None: + self.root: dict[Any, Any] = {} + + def add(self, kp: KeyPath, src: Source) -> None: + if len(kp) == 0: + raise AssertionError("KeyPath must not be empty") + *path, leaf = kp + node = self.root + for k in path: + if k not in node: + node[k] = {} + node = node[k] + node[leaf] = src + + def get(self, kp: KeyPath) -> tuple[Source, KeyPath]: + node = self.root + # pyrefly: ignore [bad-assignment] + while not isinstance(node, Source): + if len(kp) == 0: + raise AssertionError("KeyPath exhausted before reaching Source") + k, *kp = kp # type: ignore[assignment] + node = node[k] + # pyrefly: ignore [bad-return] + return node, kp + + +def make_sourced_prefixes( + nn_module: torch.nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any] +) -> _KeyPathTrie: + kp_args, kp_kwargs = tree_map_with_path( + lambda kp, _: _KeyPath(kp), + (tuple(None for _ in args), {k: None for k in kwargs}), # noqa: C420 + ) + kp_combined_args = _combine_args(nn_module, kp_args, kp_kwargs) + + sourced_prefixes = _KeyPathTrie() + for name, struct in kp_combined_args.items(): + src = LocalSource(name) + + if isinstance(struct, _KeyPath): + sourced_prefixes.add(struct.kp, src) + elif isinstance(struct, tuple): + for i, prefix in enumerate(struct): + if not isinstance(prefix, _KeyPath): + raise AssertionError(f"expected _KeyPath, got {type(prefix)}") + sourced_prefixes.add(prefix.kp, GetItemSource(src, i)) + elif isinstance(struct, dict): + for k, prefix in struct.items(): + if not isinstance(prefix, _KeyPath): + raise AssertionError(f"expected _KeyPath, got {type(prefix)}") + sourced_prefixes.add(prefix.kp, GetItemSource(src, k)) + + return sourced_prefixes + + +def key_path_to_source( + kp: KeyPath, sourced_prefixes: _KeyPathTrie | None = None +) -> Source: + """ + Given a key path, return the source for the key path. + """ + if sourced_prefixes is None: + source: Source = LocalSource("args") + else: + source, kp = sourced_prefixes.get(kp) + + for k in kp: + if isinstance(k, SequenceKey): + source = GetItemSource(source, k.idx) + elif isinstance(k, MappingKey): + source = GetItemSource(source, k.key) + elif isinstance(k, GetAttrKey): + source = AttrSource(source, k.name) + else: + raise ValueError(f"Unknown KeyEntry {k}") + + return source + + +def _is_constant_argument(t: object) -> bool: + return t is None or isinstance(t, (float, bool, str)) + + +def fakify( + mode: FakeTensorMode, + kp: KeyPath, + t: Any, + t_constraints: dict[int, dict[int, Constraint]], + sources: dict[tuple[int, int], list[Source]], + sourced_prefixes: _KeyPathTrie | None = None, +) -> Any: + source = key_path_to_source(kp, sourced_prefixes=sourced_prefixes) + if ( + _is_constant_argument(t) + or isinstance(t, (torch.ScriptObject, torch.nn.Module)) + or is_custom_class_obj(t) + ): + return t + + if isinstance(t, _IntWrapper): + if t.dynamism is not None and t.dynamism.type in ( # type: ignore[union-attr] + _DimHintType.DYNAMIC, + _DimHintType.AUTO, + ): + symint = mode.shape_env.create_unspecified_symint_and_symbol( # type: ignore[union-attr] + t.val, source, DimDynamic.DYNAMIC + ) + context = ( + SymIntSymbolicContext( + constraint=RelaxedUnspecConstraint(warn_only=False) + ) + if t.dynamism.type == _DimHintType.DYNAMIC # type: ignore[union-attr] + else None + ) + mode.shape_env.tracked_fakes.append( # type: ignore[union-attr] + TrackedFake(symint, source, context) + ) + return symint + else: + return t.val + + if not isinstance(t, torch.Tensor): + raise ValueError( + f"Unsupported input type {type(t)}. " + "Export only supports pytree containers of basic types (Tensor, int, float, ...) as input. " + "To register a custom dataclass, use torch.export.register_dataclass. " + "To register a custom container type, use torch.utils._pytree.register_pytree_node. " + "To register a constant input, use torch.utils._pytree.register_constant" + ) + + # Create symbolic context (handles subclass recursion internally) + symbolic_context = _create_symbolic_context_for_tensor( + t, source, t_constraints, sources, mode + ) + + fake = mode.from_tensor(t, source=source, symbolic_context=symbolic_context) + mode.shape_env.tracked_fakes.append(TrackedFake(fake, source, symbolic_context)) # type: ignore[union-attr] + return fake + + +def _create_symbolic_context_for_tensor( + t: torch.Tensor, + source: Source, + t_constraints: dict[int, dict[int, Constraint]], + sources: dict[tuple[int, int], list[Source]], + mode: FakeTensorMode, +) -> "SymbolicContext": + """Helper function to create symbolic context for a tensor.""" + from torch._dynamo.source import AttrSource + from torch.fx.experimental.symbolic_shapes import ( + DimDynamic, + RelaxedUnspecConstraint, + SubclassSymbolicContext, + ) + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + # Common dynamic dimension logic for both regular tensors and subclasses + n_dims = len(t.shape) + dynamic_sizes = [] + constraint_sizes = [None] * n_dims + + for i in range(n_dims): + if i in getattr(t, "_dynamo_weak_dynamic_indices", {}): + dynamic_sizes.append(DimDynamic.DYNAMIC) + elif i in getattr(t, "_dynamo_dynamic_indices", {}): + # bit annoying, but we need to replicate process in _dynamo/variables/builder.py + # where a RelaxedUnspecConstraint is created for Dim.DYNAMIC, so constraint violations + # are raised when specializing. + dynamic_sizes.append(DimDynamic.DYNAMIC) + constraint_sizes[i] = RelaxedUnspecConstraint(warn_only=False) # type: ignore[call-overload] + else: + dynamic_sizes.append(DimDynamic.STATIC) + + # Handle nested subclasses + if is_traceable_wrapper_subclass(t): + # Get inner contexts recursively + inner_contexts: dict[str, SymbolicContext] = {} + # pyrefly: ignore[missing-attribute] # TODO traceable wrapper subclasses define __tensor_flatten__ + attrs, _ = type(t).__tensor_flatten__(t) + + # Propagate outer tensor constraints to inner tensors if not already present + for attr in attrs: + match getattr(t, attr): + case torch.Tensor() as inner_value: + inner_source = AttrSource(source, attr) + inner_contexts[attr] = _create_symbolic_context_for_tensor( + inner_value, inner_source, t_constraints, sources, mode + ) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + symbolic_context = SubclassSymbolicContext( + dynamic_sizes=dynamic_sizes, + constraint_sizes=constraint_sizes, # type: ignore[arg-type] + view_base_context=None, + tensor_source=source, + shape_env_to_source_to_symbol_cache={}, + inner_contexts=inner_contexts, + ) + else: + symbolic_context: StatelessSymbolicContext = ( # type: ignore[no-redef] + StatelessSymbolicContext( + dynamic_sizes=dynamic_sizes, + constraint_sizes=constraint_sizes, # type: ignore[arg-type] + ) + ) + + # Apply constraints (common logic) + t_id = id(t) + if mode.shape_env is None: + raise AssertionError("mode.shape_env must not be None") + if t_id in t_constraints: + for i, constraint in t_constraints[t_id].items(): + src = TensorPropertySource(base=source, prop=TensorProperty.SIZE, idx=i) + sources[(t_id, i)].append(src) + if isinstance(constraint, _RelaxedConstraint): + continue + symbolic_context.constraint_sizes[i] = constraint.constraint_range + mode.shape_env.source_name_to_debug_name[src.name] = constraint.name # type: ignore[assignment] + + return symbolic_context + + +def _is_unbacked_symint(symbol: object) -> bool: + if not isinstance(symbol, torch.SymInt): + return False + + if symbol.node.shape_env is None: + raise AssertionError("shape_env should not be None") + return symbol.node.shape_env.is_unbacked_symint(symbol.node.expr) + + +def _tensor_min_max( + *args: Any, + real_callable: Callable[..., object], + tensor_callable: Callable[..., object], + **kwargs: Any, +) -> Any: + """ + This logic is replicated from dynamo/variables/builtin.py + """ + if len(args) == 2 and not kwargs: + arg1, arg2 = args + + # Case 1: Both are tensors + if isinstance(arg1, torch.Tensor) and isinstance(arg2, torch.Tensor): + return tensor_callable(arg1, arg2) + + # Case 2: One tensor, one scalar + elif isinstance(arg1, torch.Tensor) or isinstance(arg2, torch.Tensor): + if not isinstance(arg1, torch.Tensor): + arg1, arg2 = arg2, arg1 + + if isinstance(arg2, (int, float)): + kwarg = {"min" if tensor_callable is torch.maximum else "max": arg2} + return torch.clamp(arg1, **kwarg) # type: ignore[call-overload] + else: + return real_callable(arg1, arg2) + + # Case 3: SymInts + elif isinstance(arg1, torch.SymInt) or isinstance(arg2, torch.SymInt): + return ( + torch.sym_max(arg1, arg2) + if tensor_callable is torch.maximum + else torch.sym_min(arg1, arg2) + ) + + # Fallback + else: + return real_callable(arg1, arg2) + + # Single iterable argument handling + if len(args) == 1 and not kwargs: + iterable = args[0] + + if isinstance(iterable, torch.Tensor): + return tensor_callable(iterable) + try: + iterator = iter(iterable) + except TypeError: + pass + else: + items = list(iterator) + if not items: + raise ValueError(f"{real_callable.__name__}() arg is an empty sequence") + + return functools.reduce( + lambda a, b: _tensor_min_max( + a, b, real_callable=real_callable, tensor_callable=tensor_callable + ), + items, + ) + + # Fallback to original callable + return real_callable(*args, **kwargs) + + +@contextmanager +def _override_builtin_ops() -> Generator[None, None, None]: + original_max = builtins.max + original_min = builtins.min + original_pow = math.pow + + # pyrefly: ignore [bad-assignment] + builtins.max = functools.partial( + _tensor_min_max, real_callable=original_max, tensor_callable=torch.maximum + ) + + # pyrefly: ignore [bad-assignment] + builtins.min = functools.partial( + _tensor_min_max, real_callable=original_min, tensor_callable=torch.minimum + ) + + math.pow = lambda x, y: x**y # type: ignore[operator] + + try: + yield + finally: + builtins.max = original_max + builtins.min = original_min + math.pow = original_pow + + +def _make_fake_inputs_with_spec( + fake_mode: FakeTensorMode, + nn_module: Any, + args: Any, + kwargs: Any, + sourced_prefixes: Any, + dynamic_shapes: Any, + original_signature: inspect.Signature, +) -> tuple[FakeTensorMode, Any, Any, EqualityConstraint, inspect.Signature, Any]: + from torch.fx.experimental._spec_binding import _bind_spec_to_args + from torch.fx.experimental.dynamic_spec import ( + _coerce_to_shapes_spec, + IntVar, + ShapesSpec, + ) + from torch.fx.experimental.symbolic_shapes import ( + _finalize_spec_wiring, + _symbolic_context_from_shapes_spec, + _wire_spec_assumptions, + _wire_spec_slot, + _wire_tensor_spec_dims, + ) + + user_spec = cast(ShapesSpec, _coerce_to_shapes_spec(dynamic_shapes)) + shape_env = fake_mode.shape_env + if shape_env is None: + raise AssertionError("fake_mode.shape_env must not be None") + + def _fakify_one_leaf(x: Any, source: Source, leaf_spec: Any) -> Any: + """Fakify a single flat input leaf against its (already-bound) spec.""" + if isinstance(x, torch.Tensor): + if leaf_spec is None: + return fake_mode.from_tensor(x, static_shapes=True, source=source) + ctx = _symbolic_context_from_shapes_spec(x, source, leaf_spec, None, {}) + fake_x = fake_mode.from_tensor( + x, static_shapes=False, source=source, symbolic_context=ctx + ) + _wire_tensor_spec_dims(leaf_spec, fake_x) + return fake_x + # NB: don't match on bools. + if type(x) is int: + if isinstance(leaf_spec, int): + # Static int spec: verify the runtime value matches. + if x != leaf_spec: + raise ValueError( + f"shapes_spec declared {source.name} as static with " + f"value {leaf_spec}, but got {x} at trace time" + ) + return x + if isinstance(leaf_spec, (IntVar, torch.SymInt)): + sym_node = shape_env.create_unbacked_symint(source=source) + _wire_spec_slot(leaf_spec, sym_node) + return sym_node + return x + + # Wire assumptions BEFORE processing inputs so derived / assumption + # checks can drain as inputs bind. + if user_spec._assumptions: + _wire_spec_assumptions(shape_env, user_spec) + + leaf_specs, flat_args, in_spec = _bind_spec_to_args( + nn_module, args, kwargs, user_spec + ) + leaf_sources = [ + key_path_to_source(kp, sourced_prefixes=sourced_prefixes) + for kp, _ in pytree.tree_flatten_with_path((args, kwargs))[0] + ] + + with shape_env.ignore_fresh_unbacked_symbols(): + fake_leaves = [ + _fakify_one_leaf(x, leaf_sources[i], leaf_specs[i]) + for i, x in enumerate(flat_args) + ] + + # Verify every spec assumption / derived check that survived input + # processing has been emitted. + _finalize_spec_wiring(shape_env) + + fake_args, fake_kwargs = pytree.tree_unflatten(fake_leaves, in_spec) + equalities_inputs = EqualityConstraint( + source_pairs=[], + derived_equalities=[], + phantom_symbols=[], + relaxed_sources=set(), + warn_only=False, + ) + return ( + fake_mode, + fake_args, + fake_kwargs, + equalities_inputs, + original_signature, + dynamic_shapes, + ) + + +def make_fake_inputs( + nn_module: torch.nn.Module, + args: tuple[Any, ...], + kwargs: dict[str, Any], + dynamic_shapes: "dict[str, Any] | tuple[Any, ...] | list[Any] | ShapesSpec | ParamsSpec | None", + prefer_deferred_runtime_asserts_over_guards: bool = False, +) -> tuple[ + FakeTensorMode, + tuple[Any, ...], + dict[str, Any], + EqualityConstraint, + inspect.Signature, + dict[str, Any] | tuple[Any, ...] | list[Any] | None, +]: + """ + Given an nn module, example inputs, and constraints, return a new fake mode, + fake inputs created in that mode whose dynamic shape dimensions are constrained + by the given ranges, and sources for pairs of dynamic shape dimensions that are + constrained to be equal. + """ + # TODO(avik): refactor Dynamo to avoid duplication of the following code + # between non-strict and strict. + # Specifically, here (non-strict) we do the following pre-tracing steps: + # - Fakify inputs. + # - Process input shape equalities. + # In strict, these steps are spread across multiple files: + # - output_graph.py fakifies inputs. + # - [post-tracing] guards.py processes input shape equalities. + import torch._functorch.config as _config + from torch.fx.experimental.dynamic_spec import ParamsSpec, ShapesSpec + + # ShapesSpec/ParamsSpec drive dynamism via unbacked symbols (handled by the + # spec fakify branch below); skip the legacy constraint machinery for it. + is_shapes_spec = isinstance(dynamic_shapes, (ShapesSpec, ParamsSpec)) + + constraints: list[Constraint] = [] + t_constraints: dict[int, dict[int, Constraint]] = defaultdict(dict) + if not is_shapes_spec: + # Map ints to a wrapper structure to help us mark it as dynamic, if it is + # dynamic. We will unwrap ints in fakify later. + args, kwargs = pytree.tree_map_only( + int, lambda a: _IntWrapper(a), (args, kwargs) + ) + + combined_args = _combine_args(nn_module, args, kwargs) + _check_dynamic_shapes(combined_args, dynamic_shapes) + constraints = _process_dynamic_shapes(combined_args, dynamic_shapes) + for constraint in constraints: + t_constraints[constraint.t_id][constraint.dim] = constraint + + context = torch._guards.TracingContext.try_get() + if context is not None: + # This occurs when we are exporting within dynamo. There already exists + # a toplevel TracingContext with a fake mode, so we do not want to + # create another fake mode. + fake_mode = context.fake_mode + if fake_mode is None: + raise AssertionError("context.fake_mode must not be None") + else: + if isinstance(nn_module.forward, functools.partial): + # functools handles nesting by itself, no need to recurse + code = nn_module.forward.func.__code__ + elif ( + sys.version_info >= (3, 14) + and (fwd := getattr(nn_module.forward, "__func__", None)) + and isinstance(fwd, functools.partial) + ): + # functools.partial is now a method descriptor: + # https://docs.python.org/3/whatsnew/3.14.html#changes-in-the-python-api + code = fwd.func.__code__ + else: + code = nn_module.forward.__code__ + co_fields = { + "co_name": code.co_name, + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + } + with _config.patch(fake_tensor_allow_unsafe_data_ptr_access=False): + fake_mode = FakeTensorMode( + shape_env=ShapeEnv( + tracked_fakes=[], + co_fields=co_fields, + prefer_deferred_runtime_asserts_over_guards=prefer_deferred_runtime_asserts_over_guards, + trace_asserts=True, + ), + allow_non_fake_inputs=True, + export=True, + ) + if fake_mode.shape_env is None or fake_mode.shape_env.tracked_fakes is None: + raise ValueError( + "Detected fake_mode does not have a shape_env with tracked fakes. " + "If you constructed the module under a FakeTensorMode, " + "please initialize it like: FakeTensorMode(shape_env=ShapeEnv(tracked_fakes=[]))" + ) + + with fake_mode: + original_signature = inspect.signature(nn_module.forward) + sources: dict[tuple[int, int], list[Source]] = defaultdict(list) + sourced_prefixes = make_sourced_prefixes(nn_module, args, kwargs) + if is_shapes_spec: + return _make_fake_inputs_with_spec( + fake_mode, + nn_module, + args, + kwargs, + sourced_prefixes, + dynamic_shapes, + original_signature, + ) + fake_args, fake_kwargs = tree_map_with_path( + lambda kp, val: fakify( + fake_mode, + kp, + val, + t_constraints, + sources, + sourced_prefixes=sourced_prefixes, + ), + (args, kwargs), + ) + + names: dict[str, tuple[int, int]] = {} + source_pairs: list[tuple[Source, Source]] = [] + derived_equalities: list[ + tuple[Source, Source | Symbol, Callable[..., object]] + ] = [] + phantom_symbols: dict[str, Symbol] = {} + relaxed_sources: set[Source] = set() + for constraint in constraints: + torch.export.dynamic_shapes._process_equalities( + constraint, + lambda t_id, dim: sources[(t_id, dim)], + fake_mode.shape_env, + names, + source_pairs, + derived_equalities, + phantom_symbols, + relaxed_sources, + ) + + equalities_inputs = EqualityConstraint( + source_pairs=source_pairs, + derived_equalities=derived_equalities, + phantom_symbols=list(phantom_symbols.values()), + relaxed_sources=relaxed_sources, + warn_only=False, + ) + return ( + fake_mode, + fake_args, + fake_kwargs, + equalities_inputs, + original_signature, + dynamic_shapes, + ) + + +def _flatten_dynamic_shapes( + combined_args: dict[str, Any], + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any], +) -> list[Any]: + flat_shapes: list[Any] = [] + + def _tree_map_helper(path: KeyPath, t: Any, shape: Any) -> None: + nonlocal flat_shapes + flat_shapes.append(shape) + + _tree_map_with_path(_tree_map_helper, combined_args, dynamic_shapes) + return flat_shapes + + +def _clean_dynamic_markers(tensor: torch.Tensor) -> None: + for attr in ( + "_dynamo_weak_dynamic_indices", + "_dynamo_dynamic_indices", + "_dynamo_dynamic_range", + "_dynamo_static_indices", + "_dynamo_unbacked_indices", + "_dynamo_propagated_dynamic_indices", + "_has_dynamo_dim_marking", + ): + if hasattr(tensor, attr): + delattr(tensor, attr) + + +def produce_guards_and_solve_constraints( + fake_mode: FakeTensorMode, + gm: torch.fx.GraphModule, + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None, + equalities_inputs: EqualityConstraint, + original_signature: inspect.Signature, +) -> None: + """ + Given a fake mode, sources pairs corresponding to equal dynamic shape dimensions, + and a graph module, produce guards on the fake mode's shape env (raising constraint + violations if any), solve (to suggest simplifications or fixes). + Dynamo already performs this, so this is for non-strict mode. + + Additional inputs: + equalities_inputs: the equality constraints to use for guards + original_signature: the signature of the forward method + """ + shape_env = fake_mode.shape_env + if shape_env is None: + raise AssertionError("fake_mode.shape_env must not be None") + if shape_env.tracked_fakes is None: + raise AssertionError("shape_env.tracked_fakes must not be None") + + placeholders = [tf.fake for tf in shape_env.tracked_fakes] + sources = [tf.source for tf in shape_env.tracked_fakes] + input_contexts = [tf.symbolic_context for tf in shape_env.tracked_fakes] + constraint_violation_error = None + try: + shape_env.produce_guards( + placeholders, + sources, + input_contexts=input_contexts, + equalities_inputs=equalities_inputs, + ignore_static=False, + ) + except ConstraintViolationError as e: + constraint_violation_error = e + + shape_env.frozen = True + dim_constraints = shape_env.dim_constraints + if dim_constraints is None: + # Expected when shape_env.produce_guards throws an early constraint violation error. + # There is nothing to solve for in this case. + # TODO(avik): Maybe record the constraint violation error instead and replay later? + if not constraint_violation_error: + raise AssertionError( + "expected constraint_violation_error when dim_constraints is None" + ) + raise constraint_violation_error + dim_constraints.solve() + forced_specializations = dim_constraints.forced_specializations() + + msg = dim_constraints.prettify_results( + original_signature, + dynamic_shapes, # type: ignore[arg-type] + constraint_violation_error, + forced_specializations, # type: ignore[arg-type] + ) + + if constraint_violation_error: + if constraint_violation_error.args: + constraint_violation_error.args = ( + constraint_violation_error.args[0] + msg, + ) + else: + constraint_violation_error.args = (msg,) + elif forced_specializations: + constraint_violation_error = ConstraintViolationError(msg) + if constraint_violation_error: + raise constraint_violation_error + + +def is_int(x: object) -> TypeGuard[int | torch.SymInt]: + return isinstance(x, int) or (isinstance(x, torch.SymInt) and x.node.expr.is_number) + + +def _constrain_user_specified_dimhint_range( + symint: torch.SymInt, + hint: int, + dim: _DimHint, + range_constraints: dict["Expr", "ValueRanges[Expr]"], + shape_env: ShapeEnv, + keypath: KeyPath, + i: int | None = None, +) -> str | None: + trace_vr = ( + range_constraints[symint.node.expr] + if not is_int(symint) + else ValueRanges(int(symint), int(symint)) + ) + + # warn on 0/1 specialization for Dim.AUTO; not an actual error + if dim.type == _DimHintType.AUTO and trace_vr.is_singleton() and hint in (0, 1): + pathstr = f"inputs{pytree.keystr(keypath)}" + if i is not None: + pathstr += f".shape[{i}]" + msg = ( + f"dimension {pathstr} 0/1 specialized; Dim.AUTO was specified along " + + f"with a sample input with hint = {hint}." + ) + log.warning(msg) + + try: + user_vr = ValueRanges( + lower=0 if dim.min is None else dim.min, + upper=int_oo if dim.max is None else dim.max, + ) + if is_int(symint): + out_vr = trace_vr & user_vr + else: + range_constraints[symint.node.expr] &= user_vr + shape_env.var_to_range[symint.node._expr] &= user_vr + out_vr = range_constraints[symint.node.expr] + + # check for Dim.DYNAMIC specializations; special case error message on 0/1 + if dim.type == _DimHintType.DYNAMIC and out_vr.is_singleton(): + path = f"inputs{pytree.keystr(keypath)}" + if i is not None: + path += f".shape[{i}]" + if ( + trace_vr.is_singleton() + and hint in (0, 1) + and not torch.fx.experimental._config.backed_size_oblivious + ): + msg = ( + f"- Received user-specified dim hint Dim.DYNAMIC(min={dim.min}, max={dim.max}), " + f"but export 0/1 specialized due to hint of {hint} for dimension {path}." + ) + else: + msg = ( + f"- Received user-specified dim hint Dim.DYNAMIC(min={dim.min}, max={dim.max}), " + f"but tracing inferred a static shape of {out_vr.lower} for dimension {path}." + ) + return msg + + except torch.utils._sympy.value_ranges.ValueRangeError: + path = f"inputs{pytree.keystr(keypath)}" + if i is not None: + path += f".shape[{i}]" + msg = ( + f"- Received user-specified min/max range of [{dim.min}, {dim.max}], " + f"conflicting with the inferred min/max range of [{trace_vr.lower}, {trace_vr.upper}], " + f"for {path}." + ) + return msg + + return None + + +def make_constraints( + fake_mode: FakeTensorMode, + gm: torch.fx.GraphModule, + combined_args: dict[str, Any], + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None, + num_lifted_inputs: int, +) -> dict["Expr", "ValueRanges[Expr]"]: + """ + Given a fake mode's shape env and user-specified dynamic shapes, + return the resulting range constraints and equality constraints. + + Additional args: + num_lifted_inputs: the number of non-user-input placeholder nodes in the graph + (used only to enumerate the user-input nodes) + """ + + shape_env = fake_mode.shape_env + if shape_env is None: + raise AssertionError("fake_mode.shape_env must not be None") + inline_constraints = gm.meta.get("inline_constraints", []) + range_constraints = defaultdict(lambda: ValueRanges(0, int_oo)) | inline_constraints + if not dynamic_shapes: + return dict(range_constraints) + + # clean up dynamic markers from tensors + flat_paths, flat_args = zip(*pytree.tree_flatten_with_path(combined_args)[0]) + for arg in flat_args: + if isinstance(arg, torch.Tensor): + _clean_dynamic_markers(arg) + + # get individual dynamic shapes spec for each input + if not isinstance(dynamic_shapes, dict): + if not isinstance(dynamic_shapes, (tuple, list)): + raise AssertionError( + f"expected dict, tuple, or list for dynamic_shapes, got {type(dynamic_shapes)}" + ) + combined_args = type(dynamic_shapes)(combined_args.values()) # type: ignore[assignment, misc] + flat_dynamic_shapes = _flatten_dynamic_shapes(combined_args, dynamic_shapes) + + # check number of shapes vs. number of inputs + num_placeholders = [node.op == "placeholder" for node in gm.graph.nodes].count(True) + if len(flat_dynamic_shapes) != num_placeholders - num_lifted_inputs: + raise AssertionError( + f"expected {num_placeholders - num_lifted_inputs} shapes, got {len(flat_dynamic_shapes)}" + ) + + free_symbols = set() + range_violations: list[str] = [] + for input_index, node in enumerate(gm.graph.nodes): + meta_val = node.meta.get("val") + + if ( + input_index < num_lifted_inputs + or node.op != "placeholder" + or meta_val is None + ): + continue + + elif _is_constant_argument(meta_val) or isinstance(meta_val, CustomObjArgument): + continue + + shape_spec = flat_dynamic_shapes[input_index - num_lifted_inputs] + keypath = flat_paths[input_index - num_lifted_inputs] + flat_arg = flat_args[input_index - num_lifted_inputs] + + if isinstance(meta_val, int) or ( + isinstance(meta_val, torch.SymInt) and meta_val.node.expr.is_number + ): + pass + + elif isinstance(meta_val, torch.SymInt): + if shape_spec is not None and isinstance(shape_spec, _DimHint): + hint = flat_arg + range_constraints[meta_val.node.expr] &= shape_env.bound_sympy( + meta_val.node._expr + ) + violation = _constrain_user_specified_dimhint_range( + meta_val, + hint, + shape_spec, + range_constraints, + shape_env, + keypath, + None, + ) + if violation: + range_violations.append(violation) + else: + raise RuntimeError("nyi") + free_symbols.update(meta_val.node.expr.free_symbols) + + elif isinstance(meta_val, torch.Tensor): + for i, d in enumerate(node.meta["val"].shape): + dim = None + if isinstance(shape_spec, (list, tuple)): + dim = shape_spec[i] + elif isinstance(shape_spec, dict): + dim = shape_spec.get(i) + if not is_int(d): + # Compute the range constraint for the symbolic expression corresponding + # to this shape dimension and store it. + if dim is None or isinstance(dim, _DimHint): + range_constraints[d.node.expr] &= shape_env.bound_sympy( + d.node.expr + ) + else: + range_constraints[d.node.expr] &= ValueRanges( + lower=dim.min, upper=dim.max + ) + + free_symbols.update(d.node.expr.free_symbols) + + # check user-specified min/max range for DimHints; + # we might want to do this even if model tracing inferred a static dimension. + if isinstance(dim, _DimHint): + hint = flat_arg.shape[i] + violation = _constrain_user_specified_dimhint_range( + d, hint, dim, range_constraints, shape_env, keypath, i + ) + if violation: + range_violations.append(violation) + else: + raise RuntimeError(f"Unfamiliar meta val: {meta_val}") + + if range_violations: + prefix = "Found the following conflicts between user-specified ranges and inferred ranges from model tracing:\n" + raise ValueError(prefix + "\n".join(range_violations)) + + for symbol in free_symbols: + if symbol not in range_constraints: + # Placeholders can have symbolic shapes that are derived expressions. + # The above code will record direct range constraints for them + # so that we can do runtime assertions. In addition, for serde checks + # we want to record range constraints for their root symbols. + range_constraints[symbol] = shape_env.var_to_range[symbol] + + return dict(range_constraints) + + +def _gather_constant_attrs(m: torch.nn.Module) -> ConstantAttrMap: + """Search the module hierarchy, gathering up all tensor and ScriptObject constants. + + Returns a dictionary mapping hash(value) to the name of the constant. We + have to abuse `hash` here unfortunately, see: [ScriptObject hash]. + """ + constants = ConstantAttrMap() + buffers_parameters = set(m.buffers()) + buffers_parameters.update(m.parameters()) + + def inner( + m: torch.nn.Module, prefix_atoms: list[str], constants: ConstantAttrMap + ) -> None: + for k, v in m.__dict__.items(): + if isinstance( + v, + ( + torch.Tensor, + torch.ScriptObject, + FakeScriptObject, + ), + ): + if v in buffers_parameters: + # filter out buffers and parameters, leaving only constants + continue + + fqn = ".".join(prefix_atoms + [k]) + constants.add(v, fqn) + for k, v in m.named_children(): + inner(v, prefix_atoms + [k], constants) + + inner(m, [], constants) + return constants + + +def _get_graph_inputs_of_type_nn_module( + args: tuple[tuple[Any], dict[Any, Any]] | None, +) -> set[type[torch.nn.Module]]: + if args is None: + return set() + module_types = set() + for arg in pytree.tree_leaves(args): + if isinstance(arg, torch.nn.Module): + module_types.add(type(arg)) + return module_types + + +def _enter_enable_graph_inputs_of_type_nn_module( + module_types: set[type[torch.nn.Module]], +) -> None: + for t in module_types: + torch._export.utils.register_module_as_pytree_input_node(t) + + +def _exit_enable_graph_inputs_of_type_nn_module( + module_types: set[type[torch.nn.Module]], +) -> None: + for t in module_types: + torch._export.utils.deregister_module_as_pytree_input_node(t) + + +@contextlib.contextmanager +def _enable_graph_inputs_of_type_nn_module( + args: tuple[tuple[Any], dict[Any, Any]] | None, +) -> Generator[None, None, None]: + if args is None: + yield + return + + module_types = _get_graph_inputs_of_type_nn_module(args) + _enter_enable_graph_inputs_of_type_nn_module(module_types) + try: + yield + finally: + _exit_enable_graph_inputs_of_type_nn_module(module_types) + + +@contextlib.contextmanager +def _fakify_module_inputs( + args: tuple[Any], + kwargs: dict[Any, Any], + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode, +) -> Generator[None, None, None]: + # This context manager is used to fakify module inputs. + # Inputs: + # args, kwargs: the args and kwargs containing module inputs that haven't been fakified. + # fake_mode: the fake mode to be used for fakifying script objects. It's the same mode that fakify input tensors. + + ctxs = [_enable_graph_inputs_of_type_nn_module((args, kwargs))] + for arg in pytree.tree_leaves((args, kwargs)): + if isinstance(arg, torch.nn.Module): + fake_params_buffers = _fakify_params_buffers(fake_mode, arg) + ctxs.append( + torch.nn.utils.stateless._reparametrize_module( + arg, + fake_params_buffers, + tie_weights=True, + strict=True, + stack_weights=True, + ) + ) + with contextlib.ExitStack() as stack: + for ctx in ctxs: + stack.enter_context(ctx) + yield + + +@contextlib.contextmanager +def _fakify_script_objects( + mod: _ModuleT, + args: Sequence[Any], + kwargs: dict[Any, Any], + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode | None, +) -> Generator[tuple[_ModuleT, Any, Any, ConstantAttrMap, dict[Any, Any]], None, None]: + # This context manager is used to fakify script objects into FakeScriptObject. + # Inputs: + # mod: the module to be exported, it (and its recursive submodules)'s script object attrs haven't been fakified. + # args, kwargs: the args and kwargs inputs for mod, script object inputs haven't been fakified. + # fake_mode: the fake mode to be used for fakifying script objects. It's the same mode that fakify input tensors. + # + # Returns: + # mod: the patched module, its (and its recursive submodules) script object attrs have been fakified. + # fake_args, fake_kwargs: new fakified args and kwargs. + # Script object inputs have been fakified. Don't touch the tensors. + # fake_constant_attrs: a new map from FakeScriptObject to the fqn of the original script object. + # fake_to_real: a mapping between FakeScriptObject and the original script object in order to un-do the patching. + + constant_attrs: ConstantAttrMap = _gather_constant_attrs(mod) + if any(isinstance(obj, FakeScriptObject) for obj in constant_attrs.values()): + raise AssertionError("Mod shouldn't contain any FakeScriptObject.") + if pytree.tree_any(lambda obj: isinstance(obj, FakeScriptObject), (args, kwargs)): + raise AssertionError("args and kwargs shouldn't contain any FakeScriptObject.") + + patched_attr: dict[str, Any] = {} + fake_constant_attrs = ConstantAttrMap() + fake_to_real: dict[Any, Any] = {} + + def _maybe_fakify_obj(obj: object) -> FakeScriptObject | torch.ScriptObject: + fake_obj = torch._library.fake_class_registry.maybe_to_fake_obj(fake_mode, obj) + fake_to_real[fake_obj] = obj + return fake_obj + + def _leaf_mod_and_attr( + mod: torch.nn.Module, attr_fqn: str + ) -> tuple[torch.nn.Module, str]: + *prefix_attr, last_attr = attr_fqn.split(".") + cur_mod = mod + for attr in prefix_attr: + cur_mod = getattr(cur_mod, attr) + return cur_mod, last_attr + + try: + for obj, fqns in constant_attrs.items(): + if torch._library.fake_class_registry._is_script_object( + obj + ) or is_custom_class_obj(obj): + fake_script_obj = _maybe_fakify_obj(obj) + for fqn in fqns: + cur_mod, attr = _leaf_mod_and_attr(mod, fqn) + if obj is not getattr(cur_mod, attr): + raise AssertionError( + f"obj mismatch at {fqn}: expected {obj}, got {getattr(cur_mod, attr)}" + ) + setattr(cur_mod, attr, fake_script_obj) + fake_constant_attrs.add(fake_script_obj, fqn) + patched_attr[fqn] = obj + else: + for fqn in fqns: + fake_constant_attrs.add(obj, fqn) + + fake_args, fake_kwargs = pytree.tree_map_only( + torch.ScriptObject, _maybe_fakify_obj, (args, kwargs) + ) + yield (mod, fake_args, fake_kwargs, fake_constant_attrs, fake_to_real) + finally: + for fqn, orig_obj in patched_attr.items(): + cur_mod, attr = _leaf_mod_and_attr(mod, fqn) + setattr(cur_mod, attr, orig_obj) + + +class _NonStrictTorchFunctionHandler(torch.overrides.TorchFunctionMode): + """ + 1. Handles data-dependent errors raised by torch function calls in non-strict. + + Any data-dependent error is due to some condition on unbacked symints + that cannot be resolved. A mechanical way of fixing the error is to use + a torch._check() call to assert either that condition or its negation. + The handler suggests these options as code and points to the location + of the torch function call that raised the error as part of the error + message shown to the user, who can then simply select and copy-paste + a suggested fix at that location. + + NOTE: Not all data-dependent errors are raised by torch function calls. + In particular, conditions on unbacked symints can appear outside such + calls, and as such are not handled here. + + 2. Overrides torch functions that are known to cause problems in non-strict. + + Certain Python features, such as indexing/slicing, cannot be intercepted + in non-strict. Likewise, certain legacy ops, such as distributed collectives, + may need to be mapped to other ops. When there is special handling in Dynamo + for such things, tracing can fail in non-strict (while succeeding in strict). + Fortunately, redirecting to other torch functions can often fix such issues. + + 3. Handles line-of-code logging for each torch function call in non-strict. + + Usage: TORCHEXPORT_EXTENDED_DEBUG_CURRENT_LOC=1 TORCH_LOGS="+export" ... + """ + + def _override( + self, func: Callable[..., object], args: Sequence[Any], kwargs: dict[str, Any] + ) -> tuple[Callable[..., object], Sequence[Any], dict[str, Any]]: + if torch.distributed.is_available(): + from torch.distributed._functional_collectives import ( + _remap_traceable_collective, + ) + + # Redirect legacy collectives to functional collectives, following + # Dynamo. See torch/distributed/_functional_collectives.py for details. + remapped = _remap_traceable_collective(func, args, kwargs) + if remapped is not None: + return remapped + if func is torch.tensor: + # Redirect to Python implementation of torch.tensor for data with symints. + # NOTE(avik): We don't unconditionally redirect to this implementation + # because it has some known incompletenesses, e.g., it doesn't support + # empty data. See https://github.com/pytorch/pytorch/issues/143216 + if any( + isinstance(a, (torch.SymInt, torch.SymFloat, torch.SymBool)) + for a in pytree.tree_flatten(args[0])[0] + ): + return torch._refs.tensor, args, kwargs + if func.__name__ == "__getitem__" and isinstance(args[0], torch.Tensor): + + def is_scalar_tensor_index(item: object) -> TypeGuard[torch.Tensor]: + if not isinstance(item, torch.Tensor) or item.ndim != 0: + return False + # vmap BatchedTensor scalar indices must remain tensor indices; + # calling item() on them is unsupported. + if torch._C._functorch.is_batchedtensor(item): + return False + + from torch._prims_common import is_integer_dtype + + return is_integer_dtype(item.dtype) + + def maybe_tensor_index_item(item: object) -> Any: + if is_scalar_tensor_index(item): + return item.item() + return item + + def rewrite( + dim: int, item: Any + ) -> tuple[int, tuple[Callable[..., object], list[Any]]] | None: + # Redirect to torch.select for indexing. + if item is None: + return dim + 1, (torch.unsqueeze, [dim]) + if isinstance(item, (int, torch.SymInt)): + return dim, (torch.select, [dim, item]) + if is_scalar_tensor_index(item): + return dim, ( + lambda t, dim, item: torch.select( + t, dim, maybe_tensor_index_item(item) + ), + [dim, item], + ) + # Redirect to torch.ops.aten.slice for slicing. + if isinstance(item, slice): + step = 1 if item.step is None else item.step + if ( + item.start is None + and item.stop is None + and isinstance(step, int) + and step == 1 + ): + # no-op + return dim + 1, (lambda t: t, []) + return dim + 1, ( + lambda t, dim, start, stop, step: torch.ops.aten.slice( + t, + dim, + maybe_tensor_index_item(start), + maybe_tensor_index_item(stop), + maybe_tensor_index_item(step), + ), + [dim, item.start, item.stop, step], + ) + # Otherwise do nothing. + + items = list(args[1]) if isinstance(args[1], tuple) else [args[1]] + + has_symint = False + index_ellipsis = None + t = args[0] + n_none_slices = t.ndim + 1 + for i, item in enumerate(items): + if ( + isinstance(item, torch.SymInt) + or ( + isinstance(item, slice) + and any( + isinstance(s, torch.SymInt) or is_scalar_tensor_index(s) + for s in (item.start, item.stop, item.step) + ) + ) + or is_scalar_tensor_index(item) + ): + has_symint = True + if item is Ellipsis: + index_ellipsis = i + if item is not None: + n_none_slices -= 1 + + # only rewrite when there are symints + if has_symint: + if index_ellipsis is not None: + none_slices = [slice(None)] * n_none_slices + items[index_ellipsis : index_ellipsis + 1] = none_slices + + dim = 0 + # Sequence rewrites. + sequence: list[tuple[Callable[..., object], list[Any]]] = [] + for item in items: + if (r := rewrite(dim, item)) is None: + return func, args, kwargs + dim, call_spec = r + sequence.append(call_spec) + + def run() -> Any: + # Run sequence. + # pyrefly: ignore [bad-index, index-error] + t = args[0] + for _method, _args in sequence: + t = _method(t, *_args) + return t + + return run, [], {} + + return func, args, kwargs + + def __torch_function__( + self, + func: Callable[..., object], + types: Sequence[type], + args: Sequence[Any] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + kwargs = kwargs or {} + if torch.compiler.is_dynamo_compiling(): + return func(*args, **kwargs) + + if log.isEnabledFor(logging.DEBUG) and config.extended_debug_current_loc: + frame = _find_user_code_frame() + if frame is not None: + log.debug( + "%s called at %s:%s in %s", + func.__qualname__, + frame.f_code.co_filename, + frame.f_lineno, + frame.f_code.co_name, + ) + + func, args, kwargs = self._override(func, args, kwargs) + try: + return func(*args, **kwargs) + except GuardOnDataDependentSymNode as e: + _suggest_fixes_for_data_dependent_error_non_strict(e) + raise + except RuntimeError as e: + if _is_raw_triton_kernel_data_ptr_error(func, e): + raise RuntimeError(_RAW_TRITON_KERNEL_NON_STRICT_EXPORT_ERROR) from e + raise diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_base.py b/.venv/lib/python3.12/site-packages/torch/_export/pass_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a9e5826f057aa2d068da8bf24f82185d538a9b51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/pass_base.py @@ -0,0 +1,505 @@ +# mypy: allow-untyped-defs +import operator +import traceback +from collections.abc import Callable +from contextlib import nullcontext +from typing import Any + +import torch +from torch import fx +from torch._dispatch.python import enable_python_dispatcher +from torch._export.pass_infra.node_metadata import NodeMetadata +from torch._export.pass_infra.proxy_value import ProxyValue +from torch._higher_order_ops.map import _unstack_pytree +from torch._subclasses import FakeTensor, UnsupportedFakeTensorException +from torch._subclasses.fake_tensor import ( + FakeTensorMode, + is_fake_tensor, + maybe_get_fake_constant, + maybe_get_fake_mode, +) +from torch.fx import traceback as fx_traceback +from torch.fx.experimental.proxy_tensor import PythonKeyTracer +from torch.fx.experimental.symbolic_shapes import ( + compute_unbacked_bindings, + PropagateUnbackedSymInts, +) +from torch.fx.graph import CodeGen +from torch.fx.passes.infra.pass_base import PassBase, PassResult +from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata +from torch.utils import _pytree as pytree + + +__all__ = ["_ExportPassBaseDeprecatedDoNotUse"] + + +Argument = Any +Value = Any +Fn = Callable[..., Any] +PassType = Callable[[torch.fx.GraphModule], PassResult | None] + + +_TORCH_SYM_OPS: set[Callable] = { + torch.sym_int, + torch.sym_float, + torch.sym_ite, + torch.sym_max, + torch.sym_min, + torch.sym_not, + torch.sym_sqrt, +} + + +class ExportPassBaseError(RuntimeError): + pass + + +class _ExportPassBaseDeprecatedDoNotUse(PassBase): + """ + Interpreter-based pass class to help users maintain the IR spec while writing + transformations. + """ + + @staticmethod + def _create_dummy_node_metadata(): + return NodeMetadata({"stack_trace": "".join(traceback.format_stack(limit=1))}) + + class ExportTracer(PythonKeyTracer): + def __init__( + self, callback: "_ExportPassBaseDeprecatedDoNotUse", codegen: CodeGen + ) -> None: + super().__init__() + self.callback = callback + self.root = torch.nn.Module() + self.graph = torch.fx.Graph() + self.graph.set_codegen(codegen) + self.tensor_attrs: dict[str, torch.Tensor] = {} # type: ignore[assignment] + self.fake_tensor_mode: FakeTensorMode | None = None + self.submodules: dict[torch.nn.Module, str] = {} + + def trace(self) -> None: # type: ignore[override] + raise ExportPassBaseError("ExportTracer doesn't support trace().") + + def create_arg(self, a: Argument) -> torch.fx.Node: + if isinstance(a, torch.nn.Module): + if a not in self.submodules: + name_submodule = f"submodule_{len(self.submodules)}" + self.root.add_module(name_submodule, a) + self.submodules[a] = name_submodule + elif is_fake_tensor(a): + if maybe_get_fake_constant(a) is None: + raise ExportPassBaseError(f"Cannot add {a} to graph.") + a = maybe_get_fake_constant(a) + node = super().create_arg(a) + if ( + isinstance(a, torch.Tensor) + and isinstance(node, torch.fx.Node) + and node.op == "get_attr" + ): + self.set_metadata(node, a) + self.callback.on_attr(ProxyValue(a, node)) + return node + + def set_metadata( + self, + node: torch.fx.Node, + value: Argument, + ) -> None: + # propagate the fake tensor or sym nodes + def make_val( + x: Argument, + ) -> ( + FakeTensor + | torch.SymInt + | torch.SymFloat + | torch.SymBool + | int + | float + | bool + | str + | None + ): + if isinstance(x, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return x + elif isinstance(x, torch.Tensor): + if x.is_quantized: + # TODO (tmanlaibaatar) properly support Quantized FakeTensor + x = torch.dequantize(x) + + try: + if self.fake_tensor_mode is None: + raise AssertionError("fake_tensor_mode must not be None") + # TODO we should allocate static shapes + # for param/buffer values + if isinstance(x, torch.nn.Parameter): + fake_tensor = self.fake_tensor_mode.from_tensor( + x, static_shapes=True + ) + else: + fake_tensor = self.fake_tensor_mode.from_tensor(x) + except UnsupportedFakeTensorException: + # TODO: This is just a workaround to get over the + # x.as_subclass error + print( + "Fakeifying a Tensor subclass is not supported \ + right now. Instead a TensorMetadata is used." + ) + fake_tensor = None + return fake_tensor + elif isinstance( + x, + ( + torch.SymInt, + torch.SymFloat, + torch.SymBool, + int, + float, + bool, + str, + ), + ): + return x + else: + return None + + node.meta["val"] = pytree.tree_map(make_val, value) + + # Set the tensor_metadata for values that do not have a corresponding FakeTensor + def make_tensor_meta(x: Argument) -> TensorMetadata | None: + if not is_fake_tensor(x) and isinstance(x, torch.Tensor): + if x.is_quantized: + # TODO (tmanlaibaatar) properly support Quantized FakeTensor + x = torch.dequantize(x) + + try: + if self.fake_tensor_mode is None: + raise AssertionError("fake_tensor_mode must not be None") + _ = self.fake_tensor_mode.from_tensor(x) + tensor_meta = None + except UnsupportedFakeTensorException: + # TODO: This is just a workaround to get over the + # x.as_subclass error + tensor_meta = _extract_tensor_metadata(x) + return tensor_meta + else: + return None + + node.meta["tensor_meta"] = pytree.tree_map(make_tensor_meta, value) + + class ExportInterpreter(fx.Interpreter): + def __init__( + self, callback: "_ExportPassBaseDeprecatedDoNotUse", gm: fx.GraphModule + ) -> None: + super().__init__(gm) + self.callback = callback + self.node: torch.fx.Node = next(iter(gm.graph.nodes)) + + # pyrefly: ignore [bad-override] + def placeholder( + self, + target: str, # type: ignore[override] + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> ProxyValue: + arg = super().placeholder(target, args, kwargs) + return self.callback.placeholder(target, arg, NodeMetadata(self.node.meta)) + + def output( + self, + target: torch.fx.node.Target, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> ProxyValue: + return self.callback.output(args[0], NodeMetadata(self.node.meta)).data # type: ignore[return-value] + + def call_function( + self, + target: torch.fx.node.Target, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> ProxyValue: + meta = NodeMetadata(self.node.meta) + + if target is operator.getitem: + value, key = args + return self.callback.call_getitem(value, key, meta) + elif getattr(target, "__module__", None) in { + "_operator", + "builtins", + "math", + }: + if not callable(target): + raise AssertionError(f"expected callable target, got {target}") + return self.callback.call_sym(target, args, meta) + elif target in _TORCH_SYM_OPS: + if not callable(target): + raise AssertionError(f"expected callable target, got {target}") + return self.callback.call_sym(target, args, meta) + elif isinstance( + target, (torch._ops.OpOverload, torch._ops.OpOverloadPacket) + ): + return self.callback.call_operator( + target, + args, + kwargs, + meta, + ) + elif target is torch.ops.higher_order.cond: + pred, true_fn, false_fn, inputs = args + return self.callback.call_cond(pred, true_fn, false_fn, inputs, meta) + elif target is torch.ops.higher_order.map_impl: + f, mapped_args, operands = args # type: ignore[assignment] + return self.callback.call_map(f, mapped_args, operands, meta) + # For other unregistered HigherOrderOps, just interpret them blindly + elif isinstance(target, torch._ops.HigherOrderOperator): + return self.callback._fx( + "call_function", + target, + args, + kwargs, + meta, + ) + else: + raise ExportPassBaseError(f"Unsupported target type: {target}") + + def get_attr( # type: ignore[override] + self, + target: str, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> Argument: + return super().get_attr(target, args, kwargs) + + def call_module( + self, + target: torch.fx.node.Target, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> None: + raise ExportPassBaseError("call_module is not supported.") + + def call_method( # type: ignore[override] + self, + target: str, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> None: + raise ExportPassBaseError("call_method is not supported.") + + def run_node(self, n: torch.fx.Node) -> Argument: + self.node = n + self.callback.node_debug_str = n.format_node() + return super().run_node(n) + + def __init__(self) -> None: + self.interpreter = PropagateUnbackedSymInts( + torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph()) + ) + self.tracer = self.ExportTracer(self, CodeGen()) + self.fake_tensor_mode: FakeTensorMode | None = None + self._initialized = True + self.node_debug_str: str | None = None + + def _fx( + self, + kind: str, + target: torch.fx.node.Target, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + meta: NodeMetadata, + ) -> ProxyValue: + args_data, kwargs_data = pytree.tree_map_only( + ProxyValue, lambda x: x.data, (args, kwargs) + ) + res_data = getattr(self.interpreter, kind)(target, args_data, kwargs_data) + args_proxy, kwargs_proxy = pytree.tree_map_only( + ProxyValue, lambda x: x.proxy, (args, kwargs) + ) + + name = None + if isinstance(target, torch._ops.OpOverload): + name = self.tracer.graph._target_to_str(target.overloadpacket.__name__) + + res_proxy = self.tracer.create_proxy( + kind, target, args_proxy, kwargs_proxy, name=name + ) + res_proxy.node.meta.update(meta.data) + if self.fake_tensor_mode and (shape_env := self.fake_tensor_mode.shape_env): + if symbol_to_path := compute_unbacked_bindings(shape_env, res_data): + res_proxy.node.meta["unbacked_bindings"] = symbol_to_path + self.tracer.set_metadata(res_proxy.node, res_data) + return ProxyValue(res_data, res_proxy) + + def inputs(self, graph_module: torch.fx.GraphModule) -> list[Argument]: + # TODO(angelayi): Update this with what we decide to do for metadata in + # the exported graph module + if (args := graph_module.meta.get("args", None)) is not None: + return list(args) + + def extract_input(node: torch.fx.Node) -> FakeTensor | None: + if "val" in node.meta: + fake = node.meta["val"] + if hasattr(fake, "constant") and fake.constant is not None: + return fake.constant + return fake + elif tensor_meta := node.meta.get("tensor_meta"): + if self.fake_tensor_mode is None: + raise AssertionError("fake_tensor_mode must not be None") + return FakeTensor( + self.fake_tensor_mode, + torch.empty( + tensor_meta.shape, + dtype=tensor_meta.dtype, + device="meta", + requires_grad=tensor_meta.requires_grad, + memory_format=tensor_meta.memory_format, + ), + torch.device("cpu"), + ) + elif len(node.users) == 0: + return None + raise ExportPassBaseError( + f"Cannot construct an input for graph module: {graph_module}.", + ) + + return [ + extract_input(node) + for node in graph_module.graph.nodes + if node.op == "placeholder" + ] + + def on_attr(self, attr: ProxyValue) -> None: + pass + + def placeholder(self, name: str, arg: Argument, meta: NodeMetadata) -> ProxyValue: + arg_proxy = self.tracer.create_proxy("placeholder", name, (), {}) + arg_proxy.node.meta = meta.data + self.tracer.set_metadata(arg_proxy.node, arg) + return ProxyValue(arg, arg_proxy) + + def call_operator( + self, + op, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + meta: NodeMetadata, + ) -> ProxyValue: + return self._fx("call_function", op, args, kwargs, meta) + + def call_sym( + self, + target: Fn, + args: tuple[Argument, ...], + meta: NodeMetadata, + ) -> ProxyValue: + return self._fx("call_function", target, args, {}, meta) + + def call_cond( + self, + pred: ProxyValue, + true_fn: torch.fx.GraphModule, + false_fn: torch.fx.GraphModule, + inputs: list[Argument], + meta: NodeMetadata, + ) -> ProxyValue: + true_branch = self.call_submodule(true_fn, tuple(inputs)) + false_branch = self.call_submodule(false_fn, tuple(inputs)) + if true_branch is None: + raise AssertionError("true_branch must not be None") + if false_branch is None: + raise AssertionError("false_branch must not be None") + return self._fx( + "call_function", + torch.ops.higher_order.cond, + (pred, true_branch.graph_module, false_branch.graph_module, list(inputs)), + {}, + meta, + ) + + def call_map( + self, + f: torch.fx.GraphModule, + mapped_args: list[ProxyValue], + operands: list[ProxyValue], + meta: NodeMetadata, + ) -> ProxyValue: + xs = _unstack_pytree([arg.data for arg in mapped_args])[0] + f_branch = self.call_submodule(f, tuple(xs + [arg.data for arg in operands])) + if f_branch is None: + raise AssertionError("f_branch must not be None") + return self._fx( + "call_function", + torch.ops.higher_order.map_impl, + (f_branch.graph_module, mapped_args, operands), + {}, + meta, + ) + + def call_getitem( + self, value: ProxyValue, key: int, meta: NodeMetadata + ) -> ProxyValue: + return self._fx("call_function", operator.getitem, (value, key), {}, meta) + + def output(self, results: list[Argument], meta: NodeMetadata) -> ProxyValue: + return self._fx("output", "output", (results,), {}, meta) + + def call_submodule( + self, graph_module: fx.GraphModule, inputs: tuple[Argument, ...] + ) -> PassResult: + prev_tracer, self.tracer = ( + self.tracer, + self.ExportTracer(self, graph_module.graph._codegen), + ) + self.tracer.fake_tensor_mode = prev_tracer.fake_tensor_mode + interpreter = self.ExportInterpreter(self, graph_module) + # pyrefly: ignore [bad-assignment] + prev_interpreter, self.interpreter = ( + self.interpreter, + torch.fx.Interpreter( # type: ignore[assignment] + torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph()) + ), + ) + inputs_data = pytree.tree_map_only(ProxyValue, lambda x: x.data, inputs) + with fx_traceback.preserve_node_meta(): + interpreter.run(*inputs_data) + + new_graph_module = torch.fx.GraphModule(self.tracer.root, self.tracer.graph) + + self.tracer = prev_tracer + self.interpreter = prev_interpreter + return PassResult( + new_graph_module, + True, + ) + + def call(self, graph_module: fx.GraphModule) -> PassResult: + if not getattr(self, "_initialized", False): + raise ExportPassBaseError( + "ExportPass is not initialized with __init__().", + ) + + inputs = self.inputs(graph_module) + + fake_tensor_mode = None + for i in inputs: + if is_fake_tensor(i): + if ( + fake_tensor_mode is not None + and fake_tensor_mode is not maybe_get_fake_mode(i) + ): + raise AssertionError("Multiple fake tensor mode detected.") + fake_tensor_mode = maybe_get_fake_mode(i) + if fake_tensor_mode is None: + self.tracer.fake_tensor_mode = FakeTensorMode(allow_non_fake_inputs=True) + fake_tensor_mode = nullcontext() # type: ignore[assignment] + dispatcher_mode = nullcontext() # type: ignore[assignment] + else: + fake_tensor_mode.allow_non_fake_inputs = True + self.tracer.fake_tensor_mode = fake_tensor_mode + dispatcher_mode = enable_python_dispatcher() # type: ignore[assignment] + self.fake_tensor_mode = self.tracer.fake_tensor_mode + + with fake_tensor_mode, dispatcher_mode: # type: ignore[assignment, union-attr] + result = self.call_submodule(graph_module, tuple(inputs)) + + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b60dd6d7a34f3a90f44710b2a347edec8e95a75e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/node_metadata.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/node_metadata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..187c19c182be9a3f4145c4026bd563d8a4179999 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/node_metadata.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/proxy_value.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/proxy_value.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8d6f59a73d51d7d609f28fd9b902c6240e12934 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/proxy_value.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/node_metadata.py b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/node_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..9874dc1520fdbd6f4adc061dd7bccee031710797 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/node_metadata.py @@ -0,0 +1,32 @@ +from typing import Any + + +NodeMetadataValue = Any + + +PROTECTED_KEYS: set[str] = { + "val", + "stack_trace", + "nn_module_stack", + "debug_handle", + "tensor_meta", +} + + +class NodeMetadata: + def __init__(self, data: dict[str, Any]) -> None: + self.data: dict[str, Any] = data.copy() + + def __getitem__(self, key: str) -> NodeMetadataValue: + return self.data[key] + + def __setitem__(self, key: str, value: NodeMetadataValue) -> NodeMetadataValue: + if key in PROTECTED_KEYS: + raise RuntimeError(f"Could not override node key: {key}") + self.data[key] = value + + def __contains__(self, key: str) -> bool: + return key in self.data + + def copy(self) -> "NodeMetadata": + return NodeMetadata(self.data.copy()) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/proxy_value.py b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/proxy_value.py new file mode 100644 index 0000000000000000000000000000000000000000..d4a3e1cc4a63c8e26cda39346507a3b9f96b1efa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/proxy_value.py @@ -0,0 +1,49 @@ +# pyre-strict +from collections.abc import Iterable, Iterator +from typing import Generic, TypeVar + +import torch + + +_T = TypeVar("_T") + + +class ProxyValue(Generic[_T]): + # pyre-ignore + def __init__(self, data: Iterable[_T], proxy: torch.fx.Proxy | torch.fx.Node): + # pyre-ignore + self.data = data + self.proxy_or_node = proxy + + @property + def node(self) -> torch.fx.Node: + if isinstance(self.proxy_or_node, torch.fx.Node): + return self.proxy_or_node + if not isinstance(self.proxy_or_node, torch.fx.Proxy): + raise AssertionError( + f"expected Node or Proxy, got {type(self.proxy_or_node)}" + ) + return self.proxy_or_node.node + + @property + def proxy(self) -> torch.fx.Proxy: + if not isinstance(self.proxy_or_node, torch.fx.Proxy): + raise RuntimeError( + f"ProxyValue doesn't have attached Proxy object. Node: {self.proxy_or_node.format_node()}" + ) + return self.proxy_or_node + + def to_tensor(self) -> torch.Tensor: + if not isinstance(self.data, torch.Tensor): + raise AssertionError(f"expected Tensor, got {type(self.data)}") + return self.data + + def is_tensor(self) -> bool: + return isinstance(self.data, torch.Tensor) + + # pyre-ignore + def __iter__(self) -> Iterator[_T]: + yield from self.data + + def __bool__(self) -> bool: + return bool(self.data) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa9ce2ac03c23600c86ff02e38a2a4bfeefef9e2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/__init__.py @@ -0,0 +1 @@ +from .replace_view_ops_with_view_copy_ops_pass import ReplaceViewOpsWithViewCopyOpsPass diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb4246797bf0e624279f00dec20256d2066836ba Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/_node_metadata_hook.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/_node_metadata_hook.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba4c56b84a27188fd804a40db51e7151e5c2428a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/_node_metadata_hook.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/add_runtime_assertions_for_constraints_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/add_runtime_assertions_for_constraints_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a87757d3385eb22f394d28bb61378775eaff462 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/add_runtime_assertions_for_constraints_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/collect_tracepoints_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/collect_tracepoints_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dcb43d3a7e67110781bddb29ed2a29069bd84bd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/collect_tracepoints_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/constant_folding.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/constant_folding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0be07b3294e3c3b03c4195106104e6d974ce3215 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/constant_folding.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/functionalize_side_effectful_ops_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/functionalize_side_effectful_ops_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d2b0162e11ef89ebdd48bfb0083845e60186285 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/functionalize_side_effectful_ops_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/insert_custom_op_guards.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/insert_custom_op_guards.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac1fb18274dfed616634c9833d7541efbbdf170c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/insert_custom_op_guards.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/lift_constants_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/lift_constants_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa0afff5026319b90512b97583589f6d92b30bd2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/lift_constants_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/remove_runtime_assertions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/remove_runtime_assertions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16a5dd8be9f703a2d3cd2d7099730bf73fadcbd6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/remove_runtime_assertions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_autocast_with_hop_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_autocast_with_hop_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3732e2ef2ac915bd4e1baefd7f9ba667e3a69644 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_autocast_with_hop_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_quantized_ops_with_standard_ops_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_quantized_ops_with_standard_ops_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecccf05a3277d32b8985f06ea271b64e1b3838a2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_quantized_ops_with_standard_ops_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_set_grad_with_hop_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_set_grad_with_hop_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1b0dcb2b7643fcb66dda0b292202e8d387b1cd5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_set_grad_with_hop_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_view_ops_with_view_copy_ops_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_view_ops_with_view_copy_ops_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbe0dd169688df448d733982165dfa35af826289 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_view_ops_with_view_copy_ops_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_with_hop_pass_util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_with_hop_pass_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4adeae9a3f301b54f86c8d48dd105e59cd22d5ac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_with_hop_pass_util.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/_node_metadata_hook.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/_node_metadata_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..414bc04d1bad980fde10dd7e9dd3148445240da7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/_node_metadata_hook.py @@ -0,0 +1,112 @@ +# mypy: allow-untyped-defs +import contextlib +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._dispatch.python import enable_python_dispatcher +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.fx.graph_module import GraphModule + + +_EMPTY_NN_MODULE_STACK_KEY = "_empty_nn_module_stack_from_metadata_hook" + + +def _node_metadata_hook( + node: torch.fx.Node, + metadata: dict[str, Any] | None = None, + fake_mode: FakeTensorMode | None = None, +) -> None: + """ + Hook for adding the appropriate metadata to nodes that are created during a + pass using graph.create_node. An example of how to use it: + + ``` + with _set_node_metadata_hook(gm, + functools.partial(_node_metadata_hook, metadata={"stack_trace": "file"}) + ): + pass(gm) + ``` + + This hook should not work for all generic cases -- specifically it assumes + that nodes being added are only call_function nodes, and copies over the + first argument node's nn_module_stack. + """ + # pyrefly: ignore [bad-assignment] + fake_mode = fake_mode or contextlib.nullcontext() + + if node.op != "call_function" or not callable(node.target): + raise AssertionError(f"node: {node}, target: {node.target}") + + if ( + isinstance(node.target, torch._ops.OpOverload) + and len(node.target._schema.returns) == 0 + ): + node.meta["val"] = None + else: + fake_args, fake_kwargs = pytree.tree_map_only( + torch.fx.Node, lambda arg: arg.meta["val"], (node.args, node.kwargs) + ) + # pyrefly: ignore [bad-context-manager] + with fake_mode, enable_python_dispatcher(): + fake_res = node.target(*fake_args, **fake_kwargs) + node.meta["val"] = fake_res + + if metadata is not None: + for k, v in metadata.items(): + node.meta[k] = v + + # Copy over metadata from argument nodes + arg_meta = [ + arg.meta + for arg in pytree.tree_flatten((node.args, node.kwargs))[0] + if isinstance(arg, torch.fx.Node) + ] + if len(arg_meta) == 0: + return + arg_meta = arg_meta[0] + + node.meta["nn_module_stack"] = node.meta.get( + "nn_module_stack", + arg_meta.get( + "nn_module_stack", + { + _EMPTY_NN_MODULE_STACK_KEY: ( + _EMPTY_NN_MODULE_STACK_KEY, + _EMPTY_NN_MODULE_STACK_KEY, + ) + }, + ), + ) + + node.meta["torch_fn"] = node.meta.get( + "torch_fn", + ( + f"{node.target.__name__}_0", + f"{node.target.__class__.__name__}.{node.target.__name__}", + ), + ) + + node.meta["custom"] = node.meta.get("custom", arg_meta.get("custom", {})) + + +@contextlib.contextmanager +def _set_node_metadata_hook(gm: torch.fx.GraphModule, f): + """ + Takes a callable which will be called after we create a new node. The + callable takes the newly created node as input and returns None. + """ + if not callable(f): + raise AssertionError("node_metadata_hook must be a callable.") + + # Add the hook to all submodules + for m in gm.modules(): + if isinstance(m, GraphModule): + m._register_create_node_hook(f) + try: + yield + finally: + # Restore hook for all submodules + for m in gm.modules(): + if isinstance(m, GraphModule): + m._unregister_create_node_hook(f) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..2a49de497f81c0106708a3246ec3846a49002fdf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py @@ -0,0 +1,253 @@ +# mypy: allow-untyped-defs +import math +import operator +import traceback +from functools import partial +from typing import NamedTuple, TYPE_CHECKING + +import sympy + +import torch +import torch.fx +from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols +from torch.fx.passes.infra.pass_base import PassBase, PassResult +from torch.utils._sympy.numbers import int_oo +from torch.utils._sympy.value_ranges import ValueRanges + + +if TYPE_CHECKING: + from collections.abc import Callable + + +__all__ = ["InputDim"] + + +class InputDim(NamedTuple): + input_name: str + dim: int + + +def _convert_to_int(val): + # Convert simple sympy Integers into concrete int + if val in (sympy.oo, int_oo): + return math.inf + if val in (-sympy.oo, -int_oo): + return -math.inf + if isinstance(val, sympy.Integer): + return int(val) + raise RuntimeError("Export constraints cannot be non-integer expressions") + + +def _convert_range_to_int(range: ValueRanges): + if not isinstance(range, ValueRanges): + raise AssertionError(f"expected ValueRanges, got {type(range)}") + min_val = _convert_to_int(range.lower) + max_val = _convert_to_int(range.upper) + return min_val, max_val + + +class _AddRuntimeAssertionsForInlineConstraintsPass(PassBase): + def __init__( + self, + range_constraints: dict[sympy.Symbol, ValueRanges], + ): + super().__init__() + self.range_constraints: dict[sympy.Symbol, ValueRanges] = range_constraints + self._asserts_generated_unbacked_symbols: set[sympy.Symbol] = set() + self.counter = 0 + + def _assert_range_constraint(self, node, lower, upper, assert_msg): + last_node = node + if lower > -math.inf: + last_node = self._insert_assert_async( + last_node, operator.ge, node, lower, assert_msg + ) + + if upper < math.inf: + last_node = self._insert_assert_async( + last_node, operator.le, node, upper, assert_msg + ) + + def _insert_assert_async(self, last_node, op, lower, upper, assert_msg): + """ + Inserts assert_async call_function nodes in the graph. This function is + called **during** the interpreter-based pass. + """ + self.counter += 1 + graph = last_node.graph + with graph.inserting_after(last_node): + cmp = graph.call_function(op, (lower, upper), {}) + with graph.inserting_after(cmp): + cmp_tensor = graph.call_function( + torch.ops.aten.scalar_tensor.default, (cmp,), {} + ) + with graph.inserting_after(cmp_tensor): + assert_async = graph.call_function( + torch.ops.aten._assert_async.msg, + (cmp_tensor, assert_msg), + {}, + ) + return assert_async + + def call(self, graph_module) -> PassResult: + self.existing_inline_assertions = _get_existing_inline_assertions( + graph_module, self.range_constraints + ) + + for module in graph_module.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + if node.op != "call_function": + continue + if "val" not in node.meta: + continue + + val = node.meta["val"] + # In general, we may have to deal the case such as: ret[1].shape[0]. + # We need first find out what symbols require assertion, then we need to follow the path + # from ret to the symbol, construct the proxies along the way and construct the messages + # piece-wise at the same time. + # + # We use post-order traversal to collect all the proxies callbacks needed, construct + # the error message callbacks, and at the top-level traversal tree we execute all the callbacks. + # We need the callbacks because, in order to call the function to create a proxy for shape[0], we + # need the proxy for shape, which further requires the proxy for ret[1], etc. + + def add_assertions(val): + call_backs: list[Callable] = [] + messages: list[str] = [] + if isinstance(val, (torch.SymInt, torch.SymFloat, torch.SymBool)): + symbol = val.node.expr + if symbol in self.existing_inline_assertions: + return call_backs, messages + if isinstance(symbol, sympy.Symbol) and free_unbacked_symbols( + symbol + ): + if symbol in self._asserts_generated_unbacked_symbols: + return call_backs, messages + # We only care about unbacked symints for these inline + # constraints, which are prefixed with 'u' + constraint = self.range_constraints[symbol] + min_val, max_val = _convert_range_to_int(constraint) + assert_msg = f" is outside of inline constraint [{min_val}, {max_val}]." + call_backs.append( + partial( + self._assert_range_constraint, + lower=min_val, + upper=max_val, + ) + ) + messages.append(assert_msg) + self._asserts_generated_unbacked_symbols.add(symbol) + + elif isinstance(val, torch.Tensor): + for i, sym in enumerate(val.shape): + cbs, msgs = add_assertions(sym) + for cb, msg in zip(cbs, msgs): + + def sym_size_cb(node, assert_msg, dim): + with node.graph.inserting_after(node): + dim_node = module.graph.create_size_node( # type: ignore[union-attr] + node, dim + ) + cb(node=dim_node, assert_msg=assert_msg) + + call_backs.append(partial(sym_size_cb, dim=i)) + messages.append(f".shape[{i}]" + msg) + return call_backs, messages + + callbacks, messages = add_assertions(val) + for cb, msg in zip(callbacks, messages): + cb(node=node, assert_msg=f"{node}" + msg) + + module.recompile() + + # Sometimes this pass would return a wrong graph where we have mismatched + # node names in signature. Before we fix it, let's just skip it. + if ( + self.counter == 0 + and type(self) is _AddRuntimeAssertionsForInlineConstraintsPass + ): + return PassResult(graph_module, False) + + # Populate the stack trace with dummy vals to respect IR + for node in graph_module.graph.nodes: + if not node.meta.get("stack_trace", None) and node.op not in [ + "placeholder", + "output", + ]: + node.meta["stack_trace"] = "".join(traceback.format_stack(limit=1)) + return PassResult(graph_module, True) + + +def _get_existing_inline_assertions( + graph_module: torch.fx.GraphModule, + range_constraints: dict[sympy.Symbol, ValueRanges], +) -> dict[sympy.Symbol, ValueRanges]: + existing_inline_assertions: dict[sympy.Symbol, ValueRanges] = {} + + for module in graph_module.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + + # Find all the existing inline assertions. They will look something like: + # %_local_scalar_dense = call_function[target=torch.ops.aten._local_scalar_dense.default](args = (%arg1_1,), kwargs = {}) + # %ge = call_function[target=operator.ge](args = (%_local_scalar_dense, 0), kwargs = {}) + # %_assert_scalar = call_function[target=torch.ops.aten._assert_scalar.default](args = (%scalar_tensor, "..."), kwargs = {}) + for node in module.graph.nodes: + if node.target != torch.ops.aten._assert_scalar.default: + continue + + compare_arg = node.args[0] + if not ( + isinstance(compare_arg, torch.fx.Node) + and compare_arg.op == "call_function" + and compare_arg.target in (operator.le, operator.ge) + and len(compare_arg.args) == 2 + ): + continue + + compare_op = compare_arg.target + lhs, rhs = compare_arg.args + + def maybe_get_symint(x): + if ( + isinstance(x, torch.fx.Node) + and "val" in x.meta + and isinstance(x.meta["val"], torch.SymInt) + ): + return x.meta["val"].node.expr + return x + + lhs = maybe_get_symint(lhs) + rhs = maybe_get_symint(rhs) + + if compare_op is operator.ge: + lhs, rhs = rhs, lhs + + if isinstance(lhs, sympy.Symbol) and isinstance(rhs, int): + symint = lhs + scalar = rhs + elif isinstance(rhs, sympy.Symbol) and isinstance(lhs, int): + symint = rhs + scalar = lhs + else: + continue + + if symint not in range_constraints: + raise RuntimeError( + f"Unable to find symint {symint} in {range_constraints}" + ) + + previous_range = existing_inline_assertions.get( + symint, ValueRanges(-math.inf, math.inf) + ) + + if symint is lhs: + bounds = ValueRanges(-math.inf, scalar) + else: + bounds = ValueRanges(scalar, math.inf) + existing_inline_assertions[symint] = previous_range & bounds + + return existing_inline_assertions diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/collect_tracepoints_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/collect_tracepoints_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..ed43e3319ce79f80a9754231ad16d0751023851a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/collect_tracepoints_pass.py @@ -0,0 +1,158 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import operator +from typing import TYPE_CHECKING + +import torch +from torch.export.exported_program import ConstantArgument, TensorArgument +from torch.fx.passes.infra.pass_base import PassBase, PassResult + + +if TYPE_CHECKING: + from torch.export.exported_program import ModuleCallSignature + from torch.export.graph_signature import ExportGraphSignature + + +__all__ = ["CollectTracepointsPass"] + + +class CollectTracepointsPass(PassBase): + """ + Performs constant folding and constant propagation. + """ + + def __init__( + self, specs: dict[str, ModuleCallSignature], sig: ExportGraphSignature + ) -> None: + super().__init__() + self.specs = specs + self.sig = sig + + def call(self, gm: torch.fx.GraphModule) -> PassResult | None: + def get_arg_spec(arg) -> TensorArgument | ConstantArgument: + if isinstance(arg, torch.fx.Node): + if isinstance(arg.meta.get("val"), torch.Tensor): + return TensorArgument(name=arg.name) + else: + raise AssertionError( + "Symint input is not implemented yet for submodule call signature." + ) + else: + return ConstantArgument(name="", value=arg) + + for module in gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + nn_module_stack = None + for node in module.graph.nodes: + if node.op != "call_function": + continue + if node.target is torch.ops.higher_order._export_tracepoint: + kind = node.kwargs["kind"] + if kind == "module_call_outputs": + nn_module_stack = node.meta["nn_module_stack"] + elif kind == "module_call_inputs": + nn_module_stack = None + else: + raise AssertionError(f"Unknown tracepoint kind: {kind}") + elif node.meta["nn_module_stack"] == nn_module_stack: + node.meta["nn_module_stack"].popitem() + else: + nn_module_stack = None + nn_module_stack = None + for node in reversed(module.graph.nodes): + if node.op != "call_function": + continue + if node.target is torch.ops.higher_order._export_tracepoint: + kind = node.kwargs["kind"] + if kind == "module_call_inputs": + nn_module_stack = node.meta["nn_module_stack"] + elif kind == "module_call_outputs": + nn_module_stack = None + else: + raise AssertionError(f"Unknown tracepoint kind: {kind}") + elif node.meta["nn_module_stack"] == nn_module_stack: + node.meta["nn_module_stack"].popitem() + else: + nn_module_stack = None + + def copy_sig(sig) -> ModuleCallSignature: + from torch.export.exported_program import ModuleCallSignature + + return ModuleCallSignature( + inputs=[], + outputs=[], + in_spec=sig.in_spec, + out_spec=sig.out_spec, + forward_arg_names=None, + ) + + for module in gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + if node.op != "call_function": + continue + if node.target is torch.ops.higher_order._export_tracepoint: + # There's some subtlety worth noting. Here fqn corresponds to + # the call name, whereas path corresponds to the module name. + # They are not necessarily the same! When a submodule is shared + # through different aliases, there are as many _export_tracepoint + # markers as there are aliases, since the shared submodule is + # wrapped once for each alias. + path = node.kwargs["path"] + fqn, _ = next(reversed(node.meta["nn_module_stack"].values())) + + module_key = next(reversed(node.meta["nn_module_stack"])) + if "@" in module_key: + suffix = module_key.split("@")[-1] + path = f"{path}@{suffix}" + + call_fqn = f"{fqn}@{suffix}" + if call_fqn not in self.specs: + self.specs[call_fqn] = copy_sig(self.specs[fqn]) + fqn = call_fqn + + kind = node.kwargs["kind"] + for i, arg in enumerate(node.args): + # We only update the signature of the alias used to call + # the submodule. Otherwise the signatures of all aliases + # would get conflated; the inputs/outputs of every call + # would be recorded in every other call as well. + if fqn == path: + if kind == "module_call_inputs": + self.specs[path].inputs.append(get_arg_spec(arg)) + elif kind == "module_call_outputs": + self.specs[path].outputs.append(get_arg_spec(arg)) + else: + raise AssertionError(f"Unknown tracepoint kind: {kind}") + if isinstance(arg, torch.fx.Node): + for user in node.users: + if user.op != "call_function": + raise AssertionError( + f"expected call_function, got {user.op}" + ) + if user.target is not operator.getitem: + raise AssertionError( + f"expected getitem target, got {user.target}" + ) + if not isinstance(user.args[1], int): + raise AssertionError( + f"expected int arg, got {type(user.args[1])}" + ) + if user.args[1] == i: + user.replace_all_uses_with(arg) + self.sig.replace_all_uses(user.name, arg.name) + break + users = list(node.users) + for user in users: + if len(user.users) != 0: + raise AssertionError( + f"expected no users, got {len(user.users)}" + ) + gm.graph.erase_node(user) + gm.graph.erase_node(node) + return PassResult(gm, True) + + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/constant_folding.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/constant_folding.py new file mode 100644 index 0000000000000000000000000000000000000000..3e6fc281b85b9e967416fb2c2cff489ce02cc3bd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/constant_folding.py @@ -0,0 +1,304 @@ +# mypy: allow-untyped-defs +import collections +from collections import defaultdict +from collections.abc import Callable +from typing import Any + +import torch +import torch.utils._pytree as pytree + + +aten = torch.ops.aten + +# We would like to split modules into two subgraphs for runtime weight updates to work correctly. +# The use case and more information could be found at: +# https://docs.google.com/document/d/1inZC-8KarJ6gKB7G9egmYLx1V_dKX_apxon0w4zPC0Q/edit?usp=sharing +META_TAG = "MODULE_TYPE" +MODULE_TAG = "_MAIN_MODULE" +CONST_MODULE_TAG = "_CONST_MODULE" + + +def replace_node_with_constant(gm, node, constant, name=None): + g = gm.graph + + if name: + qualname = name + else: + if not hasattr(gm, "_frozen_param_count"): + gm._frozen_param_count = 0 + i = gm._frozen_param_count + + while True: + qualname = f"_frozen_param{i}" + if not hasattr(gm, qualname): + break + i += 1 + + gm._frozen_param_count = i + 1 + + with g.inserting_before(node): + new_input_node = g.create_node("get_attr", qualname, (), {}) + node.replace_all_uses_with(new_input_node) + new_input_node.meta.update(node.meta) + g.erase_node(node) + + # needed to suppress `does not reference an nn.Module, nn.Parameter, or buffer` warning + gm.register_buffer(qualname, constant) + setattr(gm, qualname, constant) + + +class ConstantFolder(torch.fx.Interpreter): + def __init__( + self, + gm: torch.fx.GraphModule, + skip_constructors: bool = False, + ): + super().__init__(gm) + self.node_replacements: dict[torch.fx.Node, Any] = {} + self.replaced_uses: dict[torch.fx.Node, int] = collections.Counter() + self.unknown_value = object() + self.skip_constructors: bool = skip_constructors + + # overwrite this to deallocate env values if their only remaining use + # is the output + self.user_to_last_uses = self.node_to_last_non_output_use() + + def is_impure(self, node: torch.fx.Node) -> bool: + if ( + node.target is torch.ops.prims.convert_element_type.default + and node.args[0].op == "get_attr" # type: ignore[union-attr] + and node.args[0].meta["val"].dtype == torch.int8 # type: ignore[union-attr] + and node.args[1] == torch.bfloat16 + ): + # For int8_weight -> dq -> bf16_weight + return True + if node.target in [ + torch.ops.quantized_decomposed.dequantize_per_channel.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.tensor, + torch.ops.pt2e_quant.dequantize_affine, + ]: + # For the pattern fp32_weight -> q -> dq + # We only folding fp32_weight -> q + # int8_weight and leave dq in graph to be fused + return True + return False + + def node_to_last_non_output_use(self): + last_non_output_use = collections.defaultdict(list) + seen_uses = set() + output_node = next(iter(reversed(self.module.graph.nodes))) # type: ignore[arg-type, union-attr] + + for node in reversed(self.module.graph.nodes): # type: ignore[arg-type, union-attr] + if node.target == "output": + continue + + def add_use(inp): + if inp in seen_uses: + return + + seen_uses.add(inp) + last_non_output_use[node].append(inp) + + # In-place is fine since we don't mutate + pytree.tree_map_only_(torch.fx.Node, add_use, (node.args, node.kwargs)) + + # if this node is only used in output, we want to gc it right away + if len(node.users) == 1 and output_node in node.users: + last_non_output_use[node].append(node) + + return last_non_output_use + + def run_node(self, node): + if node.target == "output": + # because we remove nodes from env on last non output use, + # re-define them now or we'll get error in interpreter + def set_env(arg): + self.env[arg] = self.unknown_value + + # In-place is fine since we don't mutate + pytree.tree_map_only_(torch.fx.Node, set_env, node.args) + return super().run_node(node) + + args, kwargs = self.fetch_args_kwargs_from_env(node) + flattened_inputs = pytree.arg_tree_leaves(*args, **kwargs) + + # We need to do this weird thing because in cases where flattened_inputs + # contains a ScriptObject, equality checking results in a type error if + # the types are different. + if any( + type(self.unknown_value) is type(input_) and self.unknown_value == input_ + for input_ in flattened_inputs + ): + return self.unknown_value + + # TODO - fix errors with this + if ( + node.op == "call_function" + and node.target is aten._efficientzerotensor.default + ): + return self.unknown_value + + # TODO - constant folding triton kernel returns the inputs -- fix this + if ( + node.op == "call_function" + and node.name == "triton_kernel_wrapper_functional_proxy" + ): + return self.unknown_value + + # skip constructors, since inductor generates optimal code for them already + # and turning into tensor would result in an additional global memory read + # TODO - more complicated strategy + if ( + self.skip_constructors + and node.op != "get_attr" + and not any(isinstance(e, torch.Tensor) for e in flattened_inputs) + ): + return self.unknown_value + + # All mutations should either be removed or on inputs which we did not make constant + if ( + isinstance(node.target, torch._ops.OpOverload) + and torch.Tag.nondeterministic_seeded in node.target.tags + ): + return self.unknown_value + + out = super().run_node(node) + + if node.op != "get_attr" and isinstance(out, torch.Tensor): + if out.device.type == "meta": + return out + + if not self.insertable_tensor_check(out): + return out + + if self.is_impure(node): + return self.unknown_value + + self.add_node_replacement(node, out) + + flattened_node_inps = pytree.arg_tree_leaves(*node.args, **node.kwargs) + + for n in flattened_node_inps: + if not isinstance(n, torch.fx.Node): + continue + + self.replaced_uses[n] += 1 + + for to_delete in self.user_to_last_uses.get(node, []): + if self.replaced_uses[to_delete] == len(to_delete.users): + self.node_replacements.pop(to_delete, None) + + return out + + def insertable_tensor_check(self, tensor: torch.Tensor) -> bool: + return True + + def add_node_replacement(self, node: torch.fx.Node, tensor: torch.Tensor) -> None: + self.node_replacements[node] = tensor + + def run(self): # type: ignore[override] + env = {} + for n in self.module.graph.find_nodes(op="placeholder"): # type: ignore[operator, union-attr] + env[n] = self.unknown_value + return super().run(initial_env=env) + + +def constant_fold( + gm: torch.fx.GraphModule, + constraint_fn: Callable[[torch.fx.Node], bool] | None = None, +): + with torch.utils._python_dispatch._disable_current_modes(): + cf = ConstantFolder(gm, skip_constructors=True) + cf.run() + + for node, constant in cf.node_replacements.items(): + if constraint_fn is not None and not constraint_fn(node): + continue + replace_node_with_constant(gm, node, constant) + + erased_params = [] + # Get all attr users by looking up the graph instead from node.users, because in this case + # _tensor_constant0 and _tensor_constant0_1 are actually referring to the same tensor. + + # opcode name target args kwargs + # ------------- ------------------- ---------------- --------------------------- -------- + # placeholder arg0_1 arg0 () {} + # get_attr _tensor_constant0 state () {} + # call_function add aten.add.Tensor (arg0_1, _tensor_constant0) {} + # get_attr _tensor_constant0_1 state () {} + # call_function add_ aten.add_.Tensor (_tensor_constant0_1, 1) {} + # output output output ([add],) {} + + get_attr_node_users = defaultdict(list) + for node in gm.graph.nodes: + if node.op == "get_attr": + get_attr_node_users[node.target].extend(node.users.keys()) + for node in gm.graph.find_nodes(op="get_attr"): + if node.op == "get_attr" and len(get_attr_node_users[node.target]) == 0: + if hasattr(gm, node.target): + delattr(gm, node.target) + erased_params.append(node) + for node in erased_params: + gm.graph.erase_node(node) + + gm.graph.eliminate_dead_code() + gm.graph.lint() + gm.recompile() + + +def constant_graph_tag(gm: torch.fx.GraphModule) -> None: + with torch.utils._python_dispatch._disable_current_modes(): + cf = ConstantFolder(gm, skip_constructors=True) + cf.run() + + for node in gm.graph.nodes: + if ( + node.op == "get_attr" + or node in cf.node_replacements + or node in cf.replaced_uses + ): + node.meta[META_TAG] = CONST_MODULE_TAG + else: + node.meta[META_TAG] = MODULE_TAG + + +def run_and_get_constant_graph(gm: torch.fx.GraphModule) -> torch.fx.GraphModule: + """ + Construct a GraphModule which corresponds to the part which could be + constant folded in provided gm. + """ + + constant_graph_tag(gm) + # We rewrite the tags, if it's a constant being directly consumed, without + # any folding opportunity, we keep it in main gm. + for node in gm.graph.find_nodes(op="get_attr"): + used_to_fold = False + for u in node.users: + if u.meta[META_TAG] == CONST_MODULE_TAG: + used_to_fold = True + break + if not used_to_fold: + node.meta[META_TAG] = MODULE_TAG + + new_graph = torch.fx.Graph() + + node_remapping: dict[torch.fx.Node, torch.fx.Node] = {} + output_nodes = [] + for node in gm.graph.nodes: + if node.meta[META_TAG] == MODULE_TAG: + continue + + new_node = new_graph.node_copy(node, lambda x: node_remapping[x]) + node_remapping[node] = new_node + + for user in node.users: + if user.meta[META_TAG] == MODULE_TAG: + output_nodes.append(new_node) + break + + new_graph.output(tuple(output_nodes)) + new_graph.lint() + new_gm = torch.fx.GraphModule(gm, new_graph) + + return new_gm diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..c612aaf34888793b0953779c67e656d98eb6316f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py @@ -0,0 +1,100 @@ +import copy + +import torch +from torch._export.pass_base import ( + _ExportPassBaseDeprecatedDoNotUse, + Argument, + PassResult, +) +from torch._export.pass_infra.node_metadata import NodeMetadata +from torch._export.pass_infra.proxy_value import ProxyValue +from torch._ops import OpOverload + + +aten = torch.ops.aten + +_NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS: dict[OpOverload, OpOverload] = { + aten.sym_constrain_range.default: aten._functional_sym_constrain_range.default, + aten._assert_async.msg: aten._functional_assert_async.msg, +} + + +class _FunctionalizeSideEffectfulOpsPass(_ExportPassBaseDeprecatedDoNotUse): + """ + Functionalize ops with side effect in graph module by replacing the op with + functional version of it. A new dependency token (`dep_token`) will be + created and propagated through functional ops to output. + For example: + ``` + def f(x): + sym_constrain_range(x.shape[0], min=1, max=3) + return x.add(3) + ``` + Will be transformed to: + ``` + def f(x): + dep_token0 = _make_dep_token() + dep_token1 = _functional_sym_constrain_range( + x.shape[0], min=1, max=3, dep_token=dep_token0 + ) + + return x.add(3), dep_token1 + ``` + """ + + def __init__(self) -> None: + super().__init__() + self._dep_token: ProxyValue | None = None + self._next_dep_token_index: int | None = None + + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: + # Early return if no non-functional assertions. + if not any( + n.target in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS + for n in graph_module.graph.nodes + ): + return PassResult(graph_module=graph_module, modified=False) + + gm = copy.deepcopy(graph_module) + self._dep_token = None + self._next_dep_token_index = None + return super().call(gm) + + def call_operator( + self, + op: OpOverload, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + meta: NodeMetadata, + ) -> ProxyValue: + if op not in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS: + return super().call_operator(op, args, kwargs, meta) + + if self._dep_token is None: + self._dep_token = super().call_operator( + aten._make_dep_token, + args=(), + kwargs={}, + meta=self._create_dummy_node_metadata(), + ) + self._dep_token.node.name = "dep_token0" + self._next_dep_token_index = 1 + + self._dep_token = super().call_operator( + _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS[op], + args=args, + kwargs={**kwargs, "dep_token": self._dep_token}, + meta=meta, + ) + if self._next_dep_token_index is None: + raise AssertionError("_next_dep_token_index must not be None") + self._dep_token.node.name = f"dep_token{self._next_dep_token_index}" + self._next_dep_token_index += 1 + + return self._dep_token + + def output(self, results: list[Argument], meta: NodeMetadata) -> ProxyValue: + if self._dep_token is None: + raise AssertionError("_dep_token must not be None") + + return super().output(results=(*results, self._dep_token), meta=meta) # type: ignore[arg-type] diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/insert_custom_op_guards.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/insert_custom_op_guards.py new file mode 100644 index 0000000000000000000000000000000000000000..8bbca86cf58908ffe31f976f3fa3fce152ade694 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/insert_custom_op_guards.py @@ -0,0 +1,84 @@ +import functools +from collections import defaultdict + +import torch +from torch._export.passes._node_metadata_hook import ( + _node_metadata_hook, + _set_node_metadata_hook, +) +from torch._library.fake_profile import OpProfile, TensorMetadata + + +def insert_custom_op_guards(gm: torch.fx.GraphModule, ops_to_guard: set[str]) -> None: + """ + This is used by draft_export to insert guards in front of calls to custom + operators which have a generated fake kernel. + """ + for node in gm.graph.nodes: + if node.op == "call_function" and str(node.target) in ops_to_guard: + with ( + _set_node_metadata_hook( + gm, + functools.partial( + _node_metadata_hook, + metadata={"stack_trace": node.meta.get("stack_trace")}, + ), + ), + gm.graph.inserting_before(node), + ): + for arg in (*node.args, *node.kwargs.values()): + if isinstance(arg, torch.fx.Node) and isinstance( + arg.meta.get("val"), torch.Tensor + ): + val = arg.meta["val"] + gm.graph.call_function( + torch.ops.aten._assert_tensor_metadata.default, + args=(arg,), + kwargs={ + "dtype": val.dtype, + "device": val.device, + "layout": val.layout, + }, + ) + + gm.recompile() + + +def get_op_profiles( + gm: torch.fx.GraphModule, ops_to_guard: set[str] +) -> dict[str, set[OpProfile]]: + """ + This is used by draft_export to get a list of custom operator profiles so + that we can generate fake kernels. + """ + + def _get_op_profile(node: torch.fx.Node) -> OpProfile: + args_profile = tuple( + TensorMetadata.maybe_from_tensor(arg.meta.get("val")) + if isinstance(arg, torch.fx.Node) + else None + for arg in (*node.args, *node.kwargs.values()) + ) + + out_profile = None + meta = node.meta.get("val") + if meta is None: + raise AssertionError("node.meta['val'] must not be None") + if isinstance(meta, torch.Tensor): + out_profile = TensorMetadata.maybe_from_tensor(meta) + elif isinstance(meta, (list, tuple)): + out_profile = tuple(TensorMetadata.maybe_from_tensor(m) for m in meta) # type: ignore[assignment] + if out_profile is None: + raise AssertionError( + f"out_profile must not be None for meta type {type(meta)}" + ) + + return OpProfile(args_profile, out_profile) # type: ignore[arg-type] + + op_profiles: dict[str, set[OpProfile]] = defaultdict(set) + + for node in gm.graph.nodes: + if node.op == "call_function" and str(node.target) in ops_to_guard: + op_profiles[str(node.target)].add(_get_op_profile(node)) + + return op_profiles diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/lift_constants_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/lift_constants_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..e57a5569233e27d8efa117a41a1b9e96f4daf793 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/lift_constants_pass.py @@ -0,0 +1,449 @@ +# mypy: allow-untyped-defs +import collections +import logging +from typing import Any + +import torch +from torch._export.verifier import SpecViolationError +from torch._guards import detect_fake_mode +from torch._library.fake_class_registry import FakeScriptObject, maybe_to_fake_obj +from torch._library.opaque_object import ( + get_opaque_type_name, + is_custom_class, + is_opaque_symbolic_type, +) +from torch._subclasses.fake_tensor import unset_fake_temporarily +from torch.export.exported_program import ( + ArgumentSpec, + CustomObjArgument, + ExportGraphSignature, + InputKind, + InputSpec, + TensorArgument, +) +from torch.fx._symbolic_trace import _ConstantAttributeType +from torch.fx.graph_module import _get_attr + + +log = logging.getLogger(__name__) + + +class ConstantAttrMap(collections.abc.MutableMapping): + """A mapping class that understands how to use module constants (tensors, + ScriptObjects, FakeScriptObjects, opaque objects) as keys. We store tensors, + FakeScriptObjects, and opaque objects normally, but ScriptObjects are stored + by hash, because different torch.ScriptObjects can point to the same + underlying value (but we guarantee that they will `hash()` to the same value + if that's the case). + """ + + def __init__(self) -> None: + # Underlying dict that we use to implement this mapping. + self._constant_attrs: dict[ + int | torch.Tensor | FakeScriptObject | torch.utils._pytree.TreeSpec, + list[Any], + ] = {} + # Map from the hash(ScriptObject) to the ScriptObject itself. Used for + # APIs like `__iter__` that should look like they're returning the + # original ScriptObjects. + self._script_object_map: dict[int, torch.ScriptObject] = {} + + def __getitem__(self, key: _ConstantAttributeType) -> Any: + real_key = hash(key) if isinstance(key, torch.ScriptObject) else key + if not isinstance( + real_key, (int, torch.Tensor, FakeScriptObject) + ) and not is_custom_class(type(real_key)): + raise AssertionError( + f"expected int, Tensor, FakeScriptObject, or opaque type key, got {type(real_key)}" + ) + return self._constant_attrs[real_key] + + def __setitem__(self, key: _ConstantAttributeType, value): + # we shouldn't actually call this, should go to add() instead to handle aliasing + raise NotImplementedError( + """Directly setting values for ConstantAttrMap is not supported, please use add(key, value) instead. +The same key can be mapped to multiple values, for handling constant aliasing.""" + ) + + def add(self, key: _ConstantAttributeType, value: Any) -> None: + if isinstance(key, torch.ScriptObject): + if hash(key) not in self._constant_attrs: + self._constant_attrs[hash(key)] = [] + self._constant_attrs[hash(key)].append(value) + self._script_object_map[hash(key)] = key + elif isinstance(key, (torch.Tensor, FakeScriptObject)) or is_custom_class( + type(key) + ): + if key not in self._constant_attrs: + self._constant_attrs[key] = [] + self._constant_attrs[key].append(value) + else: + raise TypeError( + f"Expected key to be a tensor or ScriptObject, got {type(key)}" + ) + + def __delitem__(self, key: _ConstantAttributeType): + real_key = hash(key) if isinstance(key, torch.ScriptObject) else key + + del self._constant_attrs[real_key] + + def __iter__(self): + for key in self._constant_attrs: + if isinstance(key, int): + yield self._script_object_map[key] + else: + yield key + + def __len__(self): + return len(self._constant_attrs) + + def __contains__(self, key: object) -> bool: + real_key = hash(key) if isinstance(key, torch.ScriptObject) else key + return real_key in self._constant_attrs + + +def get_constant_fqn(node: torch.fx.Node, constant_name: str) -> str: + # The FQN of the constant tensor in the state dict should + # correspond to the module where the constant tensor was + # originally used. + if len(node.meta["nn_module_stack"]) == 0: + return constant_name + parent_fqn = list(node.meta["nn_module_stack"].values())[-1][0] + if len(parent_fqn) > 0: + return f"{parent_fqn}.{constant_name}" + else: + return constant_name + + +def _get_first_fqn( + const_attrs: ConstantAttrMap, + key: _ConstantAttributeType, +) -> Any: + fqns = const_attrs.get(key) + return fqns[0] if fqns else None + + +def _unused_constant(node: torch.fx.Node) -> list[torch.fx.Node] | None: + """ + If there is a tensor constant created while tracing, here is how the graph + looks like: + + %_tensor_constant0 : [num_users=1] = get_attr[target=_tensor_constant0] + %lift_fresh_copy : [num_users=1] = call_function[target=torch.ops.aten.lift_fresh_copy.default](args = (%_tensor_constant0,)) + %detach_ : [num_users=?] = call_function[target=torch.ops.aten.detach_.default](args = (%lift_fresh_copy,)) + + To check to see if the tensor constant is being used, we want to traverse to + the detach node to see if it's actually being used. + + This function returns None if this constant is being used, otherwise it returns the + lift_fresh and detach node to be removed later. + """ + if len(node.users) > 1: + return None + + lift_fresh_node = next(iter(node.users.keys())) + if not ( + lift_fresh_node.op == "call_function" + and lift_fresh_node.target + in ( + torch.ops.aten.lift_fresh.default, + torch.ops.aten.lift_fresh_copy.default, + ) + ): + return None + + if len(lift_fresh_node.users) > 1: + return None + + # Case 1: lift node is not used anywhere + if len(lift_fresh_node.users) == 0: + return [lift_fresh_node, node] + + detach_node = next(iter(lift_fresh_node.users.keys())) + if not ( + detach_node.op == "call_function" + and detach_node.target + in ( + torch.ops.aten.detach_.default, + torch.ops.aten.detach.default, + ) + ): + return None + + if len(detach_node.users) > 0: + return None + else: + # Case 2: Lift node's child is not used anywhere + return [detach_node, lift_fresh_node, node] + + +def lift_constants_pass( + gm: torch.fx.GraphModule, + graph_signature: ExportGraphSignature, + constant_attrs: ConstantAttrMap, +) -> dict[str, _ConstantAttributeType]: + """ + Takes a graph module, graph signature, and modifies them inplace to lift any + constants (tensors or custom classes) as inputs to the graph. Returns a + dictionary of names to constants. + + Arguments: + gm (torch.fx.GraphModule): The graph module containing the graph and constants to lift. + graph_signature (ExportGraphSignature): This graph signature will be + mutated to add additional CONSTANT_TENSOR and CUSTOM_OBJ inputs. + constant_attrs (ConstantAttr): A mapping from a constant value to its + fully-qualified path in `gm`. This is used to maintain consistent + location of constants between the original module and the exported + version. + + Returns: + A dictionary of fqn => constant value. + """ + all_constants: dict[str, _ConstantAttributeType] = {} + + input_specs = graph_signature.input_specs + num_custom_obj = sum( + input_spec.kind == InputKind.CUSTOM_OBJ for input_spec in input_specs + ) + num_tensor_constants = sum( + input_spec.kind == InputKind.CONSTANT_TENSOR for input_spec in input_specs + ) + + fake_mode = detect_fake_mode( + tuple(node.meta["val"] for node in gm.graph.nodes if node.op == "placeholder") + ) + + first_user_input_loc, first_user_input = 0, next(iter(gm.graph.nodes)) + used_target_names = set() + + input_nodes = [node for node in gm.graph.nodes if node.op == "placeholder"] + if len(input_nodes) != len(input_specs): + raise AssertionError( + f"input nodes count {len(input_nodes)} != input specs count {len(input_specs)}" + ) + for i, (node, input_spec) in enumerate(zip(input_nodes, input_specs)): + used_target_names.add(input_spec.target) + if input_spec.kind == InputKind.USER_INPUT: + first_user_input = node + first_user_input_loc = i + break + + lifted_objs = ConstantAttrMap() + renamed_targets = {} + for node in list(gm.graph.nodes): + if node.op == "get_attr": + if nodes_to_remove := _unused_constant(node): + # Remove the node if it's not being used + for node_rm in nodes_to_remove: + gm.graph.erase_node(node_rm) + continue + + constant_val = _get_attr(gm, node.target) + # These are not hashable and not gonna be lifted + # so we can skip them earlier + if isinstance(constant_val, torch.fx.GraphModule): + continue + if "LoweredBackendModule" in type(constant_val).__name__: + continue + if "AOTInductorRunnerWrapper" in type(constant_val).__name__: + continue + if isinstance(constant_val, torch.utils._pytree.TreeSpec): + continue + + if constant_val in lifted_objs: + # We already lifted this constant elsewhere. Just rewrite uses + # of this get_attr to point to the already-existing placeholder + # node. + const_placeholder_node = _get_first_fqn(lifted_objs, constant_val) + node.replace_all_uses_with(const_placeholder_node) + gm.graph.erase_node(node) + renamed_targets[node.name] = const_placeholder_node.name + continue + + # For ScriptObject, Tensor and FakeScriptObject constants: + # First check if the constant was an attribute on some module by + # consulting `constant_attrs` map. If it is, use the fqn that keeps + # its location consistent with the eager module. + # + # If it's not in the `constant_attrs` map, that means it's an inline + # constant (e.g. x + torch.tensor(0)), and thus did not have a + # specific location in the eager module. In that case, just generate + # some name and attach it to the module in which it was used. + if isinstance( + constant_val, (torch.ScriptObject, FakeScriptObject) + ) or is_opaque_symbolic_type(type(constant_val)): + constant_kind = InputKind.CUSTOM_OBJ + constant_fqn = _get_first_fqn(constant_attrs, constant_val) + if constant_fqn is not None: + constant_name = constant_fqn.replace(".", "_") + else: + constant_name = f"lifted_custom_{num_custom_obj}" + constant_fqn = get_constant_fqn(node, constant_name) + while constant_fqn in used_target_names: + num_custom_obj += 1 + constant_name = f"lifted_custom_{num_custom_obj}" + constant_fqn = get_constant_fqn(node, constant_name) + num_custom_obj += 1 + elif isinstance(constant_val, torch.Tensor): + # Remove the parameterness of constant_val + if isinstance(constant_val, torch.nn.Parameter): + log.debug( + "%s created when tracing %s is a parameter. But " + "it's not registered with register_parameter(). export will treat it as a constant tensor", + str(node.target), + str(node.meta.get("stack_trace", "")), + ) + # We get the real data out of the parameter by disabling the surrounding fake mode. + with unset_fake_temporarily(): + constant_val = constant_val.data + constant_kind = InputKind.CONSTANT_TENSOR + constant_fqn = _get_first_fqn(constant_attrs, constant_val) + if constant_fqn is not None: + constant_name = constant_fqn.replace(".", "_") + else: + constant_name = f"lifted_tensor_{num_tensor_constants}" + constant_fqn = get_constant_fqn(node, constant_name) + while constant_fqn in used_target_names: + num_tensor_constants += 1 + constant_name = f"lifted_tensor_{num_tensor_constants}" + constant_fqn = get_constant_fqn(node, constant_name) + num_tensor_constants += 1 + else: + raise SpecViolationError( + f"getattr node {node} referencing unsupported type {type(constant_val)}" + ) + + with gm.graph.inserting_before(first_user_input): + # Insert the constant node before the first user input + const_placeholder_node = gm.graph.placeholder(constant_name) + # match target name with its node name in case there is name collision + # and suffix is added to node name in fx + const_placeholder_node.target = const_placeholder_node.name + + for k, v in node.meta.items(): + const_placeholder_node.meta[k] = v + + # Once the FQN has been used, remove nn_module_stack, stack_trace + const_placeholder_node.meta.pop("nn_module_stack") + const_placeholder_node.meta.pop("stack_trace", None) + + input_spec_arg: ArgumentSpec + if isinstance(constant_val, torch.Tensor): + if fake_mode is not None: + const_placeholder_node.meta["val"] = fake_mode.from_tensor( + constant_val, static_shapes=True + ) + const_placeholder_node.meta["val"].constant = constant_val + else: + const_placeholder_node.meta["val"] = constant_val + input_spec_arg = TensorArgument(name=const_placeholder_node.name) + elif isinstance(constant_val, torch._C.ScriptObject): + class_fqn = constant_val._type().qualified_name() # type: ignore[attr-defined] + const_placeholder_node.meta["val"] = CustomObjArgument( + constant_fqn, class_fqn + ) + input_spec_arg = CustomObjArgument( + name=const_placeholder_node.name, class_fqn=class_fqn + ) + elif isinstance(constant_val, FakeScriptObject): + class_fqn = constant_val.script_class_name + const_placeholder_node.meta["val"] = CustomObjArgument( + constant_fqn, class_fqn, constant_val + ) + input_spec_arg = CustomObjArgument( + name=const_placeholder_node.name, + class_fqn=class_fqn, + fake_val=constant_val, + ) + elif is_custom_class(type(constant_val)): + class_fqn = get_opaque_type_name(type(constant_val)) + fake_val = ( + maybe_to_fake_obj(fake_mode, constant_val) + if fake_mode + else None + ) + const_placeholder_node.meta["val"] = CustomObjArgument( + constant_fqn, + class_fqn, + fake_val, # pyrefly: ignore[bad-argument-type] + ) + input_spec_arg = CustomObjArgument( + name=const_placeholder_node.name, + class_fqn=class_fqn, + fake_val=fake_val, # pyrefly: ignore[bad-argument-type] + ) + else: + raise SpecViolationError( + f"tried to lift unsupported type {type(constant_val)} from node {node.format_node()}" + ) + + lifted_objs.add(constant_val, const_placeholder_node) + node.replace_all_uses_with(const_placeholder_node) + gm.graph.erase_node(node) + + renamed_targets[node.name] = const_placeholder_node.name + + # Add the constant as a buffer to the graph signature + graph_signature.input_specs.insert( + first_user_input_loc, + InputSpec( + kind=constant_kind, + arg=input_spec_arg, + target=constant_fqn, + ), + ) + if constant_val in constant_attrs: + for fqn in constant_attrs[constant_val]: + all_constants[fqn] = constant_val + else: + all_constants[constant_fqn] = constant_val + first_user_input_loc += 1 + + for spec in graph_signature.output_specs: + if spec.arg.name in renamed_targets: + spec.arg.name = renamed_targets[spec.arg.name] + + return all_constants + + +def rewrite_script_object_meta( + gm: torch.fx.GraphModule, +) -> dict[str, _ConstantAttributeType]: + """When tracing, we produce a graph with FakeScriptObject in the + meta["val"]. + + For now, we rewrite meta["val"] to be a placeholder CustomObjArgument + """ + constants: dict[ + str, + _ConstantAttributeType, + ] = {} + for node in gm.graph.nodes: + if "val" not in node.meta: + continue + + old_meta = node.meta["val"] + + if isinstance(old_meta, torch.ScriptObject): + class_fqn = old_meta._type().qualified_name() # type: ignore[attr-defined] + new_meta = CustomObjArgument(node.name, class_fqn) + constants[node.name] = old_meta + node.meta["val"] = new_meta + + elif isinstance(old_meta, FakeScriptObject): + class_fqn = old_meta.script_class_name # type: ignore[attr-defined] + new_meta = CustomObjArgument(node.name, class_fqn, old_meta) + constants[node.name] = old_meta + node.meta["val"] = new_meta + + return constants + + +def _materialize_and_lift_constants( + gm: torch.fx.GraphModule, + export_graph_signature: ExportGraphSignature, + constant_attrs: ConstantAttrMap, +) -> dict[str, _ConstantAttributeType]: + constants = rewrite_script_object_meta(gm) + constants.update(lift_constants_pass(gm, export_graph_signature, constant_attrs)) + return constants diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/remove_runtime_assertions.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/remove_runtime_assertions.py new file mode 100644 index 0000000000000000000000000000000000000000..ceed7cd23aa0e953b99586052629668cc53c4bdd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/remove_runtime_assertions.py @@ -0,0 +1,36 @@ +import torch +from torch.fx.passes.infra.pass_base import PassBase, PassResult + + +class _RemoveRuntimeAssertionsPass(PassBase): + """ + Remove runtime assertions inserted by the + _AddRuntimeAssertionsForInlineConstraintsPass. + """ + + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: + modified = False + for module in graph_module.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + if node.target in [ + torch.ops.aten._assert_async.msg, + torch.ops.aten._assert_scalar.default, + torch.ops.aten.sym_constrain_range_for_size.default, + torch.ops.aten.sym_constrain_range.default, + torch.ops.aten._assert_tensor_metadata.default, + ]: + assert_async_node = node + if len(assert_async_node.users) > 0: + continue + module.graph.erase_node(assert_async_node) + # the upstream scalar_tensor <- {le, ge} <- sym_size + # linear chain of nodes of nodes is removed by the + # downstream dead code elimination + modified = True + + # We don't necessarily want to run DCE here because it could affect + # nodes that are in the module_call_graph attribute of the exported + # program. We will leave it to the pass caller to call DCE. + return PassResult(graph_module, modified) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..a603565f502f83eff2bdaed145a850987a7eceda --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py @@ -0,0 +1,212 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from torch._higher_order_ops.wrap import wrap_with_autocast + +from ..utils import node_inline_, nodes_filter, nodes_first, sequential_split +from .replace_with_hop_pass_util import ( + _replace_with_hop_helper, + _replace_with_hop_pass_helper, + _sequential_split_and_maybe_inline_subgraphs_helper, +) + + +if TYPE_CHECKING: + from torch.export.graph_signature import ExportGraphSignature + + +def _is_autocast_node(node: torch.fx.Node) -> torch.fx.Node | bool: + return ( + node + and node.op == "call_function" + and node.target + in [ + torch.amp.autocast_mode._enter_autocast, + torch.amp.autocast_mode._exit_autocast, + ] + ) + + +def _is_enter_autocast_node(node: torch.fx.Node) -> torch.fx.Node | bool: + return ( + node + and node.op == "call_function" + and node.target is torch.amp.autocast_mode._enter_autocast + ) + + +def _is_exit_autocast_node(node: torch.fx.Node) -> torch.fx.Node | bool: + return ( + node + and node.op == "call_function" + and node.target is torch.amp.autocast_mode._exit_autocast + ) + + +def _is_autocast_sub_mod(node: torch.fx.Node) -> bool: + """ + Check if the first non-placeholder node is `torch.amp.autocast_mode._enter_autocast`. + """ + if node.op == "call_module": + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + subgm = getattr(node.graph.owning_module, node.target) + first_non_ph = nodes_first( + subgm.graph.nodes, lambda node: node.op != "placeholder" + ) + if ( + first_non_ph + and first_non_ph.op == "call_function" + and first_non_ph.target is torch.amp.autocast_mode._enter_autocast + ): + # TODO: check if current auto-cast type is the same as the args of + # _enter_autocast. If so, return False, i.e. do not create a submodule. + return True + return False + + +def _check_valid_autocast_block( + enter_autocast_node: torch.fx.Node, exit_autocast_node: torch.fx.Node +) -> None: + if not _is_enter_autocast_node(enter_autocast_node): + raise AssertionError( + f"expected enter_autocast node, got {enter_autocast_node.target}" + ) + if not _is_exit_autocast_node(exit_autocast_node): + raise AssertionError( + f"expected exit_autocast node, got {exit_autocast_node.target}" + ) + if exit_autocast_node.args[0] != enter_autocast_node: + raise AssertionError( + "exit_autocast_node.args[0] must match enter_autocast_node" + ) + + +def _replace_with_hop(node: torch.fx.Node) -> None: + if node.op != "call_module": + raise AssertionError(f"expected call_module op, got {node.op}") + graph: torch.fx.Graph = node.graph + if graph.owning_module is None: + raise AssertionError("graph.owning_module must not be None") + gm: torch.fx.GraphModule = graph.owning_module + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + sub_gm = getattr(gm, node.target) + sub_graph = sub_gm.graph + autocast_nodes = nodes_filter(sub_graph.nodes, _is_autocast_node) + if len(autocast_nodes) > 0: + if len(autocast_nodes) <= 1: + raise AssertionError( + f"need at least an enter node and an exit node, got {len(autocast_nodes)}" + ) + enter_autocast_node = autocast_nodes[0] + exit_autocast_node = autocast_nodes[-1] + _check_valid_autocast_block(enter_autocast_node, exit_autocast_node) + + _replace_with_hop_helper(node, enter_autocast_node, wrap_with_autocast) + sub_graph.erase_node(exit_autocast_node) + sub_graph.erase_node(enter_autocast_node) + + +def _split_autocast(gm: torch.fx.GraphModule) -> torch.fx.GraphModule: + """ + split_autocast creates a new graph module that splits the input graph module into multiple submodules + based on the `_enter_autocast` and `_exit_autocast` nodes. It doesn't mutate the input graph module. + + Nodes between the **outer-most** `_enter_autocast` and `_exit_autocast(_enter_autocast)` are split + into a submodule. Nested autocast regions are not split. + `_enter_autocast` and `_exit_autocast(_enter_autocast)` nodes are in the submodule as well. + + Below is an example of splitting. A, B, C, D, E are blocks of non-autocast nodes in the original graph + module. Nodes marked with the same number are grouped into the same submodule. + A # 0 + enter_autocast # 1 + B # 1 + exit_autocast # 1 + C # 2 + enter_autocast # 3 + D # 3 + exit_autocast # 3 + E # 4 + """ + enter_autocast_node_stack: list[torch.fx.Node] = [] + first_node_after_outer_most_exit: bool = False + + def node_call_back(node: torch.fx.Node) -> bool: + nonlocal enter_autocast_node_stack, first_node_after_outer_most_exit + increment_id = False + if first_node_after_outer_most_exit or ( + len(enter_autocast_node_stack) == 0 and _is_enter_autocast_node(node) + ): + if len(enter_autocast_node_stack) != 0: + raise AssertionError( + f"expected empty stack, got {len(enter_autocast_node_stack)} items" + ) + first_node_after_outer_most_exit = False + increment_id = True + if _is_enter_autocast_node(node): + enter_autocast_node_stack.append(node) + elif _is_exit_autocast_node(node): + if len(enter_autocast_node_stack) == 0: + raise AssertionError("enter_autocast_node_stack must not be empty") + last_enter_autocast_node = enter_autocast_node_stack.pop() + if node.args[0] != last_enter_autocast_node: + raise AssertionError("exit node args[0] must match last enter node") + if len(enter_autocast_node_stack) == 0: + # next node should be in the next submodule since + # autocast block ends + first_node_after_outer_most_exit = True + return increment_id + + return sequential_split(gm, node_call_back) + + +def _sequential_split_and_maybe_inline_subgraphs( + gm: torch.fx.GraphModule, graph_signature: ExportGraphSignature | None +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Helper function for replace_autocast_with_hop_pass(). + Split the graph module into multiple subgraphs based on the autocast nodes. + For each subgraph, decides whether to construct a HOO subgraph, or inline the calls + back into the parent graph module. + Nodes between `_enter_autocast` and `_exit_autocast(_enter_autocast)` are considered + as a subgraph. + """ + need_replacing = any(_is_autocast_node(node) for node in gm.graph.nodes) + if not need_replacing: + return gm, graph_signature + + # split_autocast returns a new graph module that could have different output + # args names. We need to fix the graph signature in `_sequential_split_and_maybe_inline_subgraphs_helper`. + new_gm = _split_autocast(gm) + + def _maybe_inline_or_replace_with_hop(node: torch.fx.Node) -> None: + if _is_autocast_sub_mod(node): + _replace_with_hop(node) + else: + if node.op != "call_module": + raise AssertionError(f"expected call_module op, got {node.op}") + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + node_inline_(node) + + return _sequential_split_and_maybe_inline_subgraphs_helper( + new_gm, graph_signature, _maybe_inline_or_replace_with_hop + ) + + +def replace_autocast_with_hop_pass( + gm: torch.fx.GraphModule, graph_signature: ExportGraphSignature | None +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and + then recursively call itself on each of the submodules. + """ + return _replace_with_hop_pass_helper( + gm, + graph_signature, + _sequential_split_and_maybe_inline_subgraphs, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..8016708026b2ef71b04062b3aec2151ec6ee7fba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.py @@ -0,0 +1,700 @@ +# mypy: allow-untyped-defs +import logging +import operator + +import torch +import torch.export._trace +from torch._ops import OpOverload +from torch.ao.quantization.fx._decomposed import ( + dequantize_per_channel, + dequantize_per_tensor, + quantize_per_tensor, +) +from torch.ao.quantization.utils import calculate_qmin_qmax +from torch.fx.graph_module import _assign_attr + + +log = logging.getLogger(__name__) + +# Those values will need to be carried over multiple operators. +_INPUT_Q_DTYPE: torch.dtype | torch.fx.Node | None = None +_SCALE: float | torch.fx.Node | None = None +_ZERO_POINT: float | torch.fx.Node | None = None + + +def int_to_valid_dtype(val: int) -> torch.dtype: + from torch._export.converter import _TORCH_ENUM_TO_DTYPE # No circular import. + + if isinstance(val, torch.dtype): + return val + dtype = _TORCH_ENUM_TO_DTYPE[val] + if dtype == torch.quint8: + return torch.uint8 + elif dtype == torch.qint8: + return torch.int8 + return dtype + + +def fx_enum_to_dtype(gm: torch.fx.GraphModule, val: int) -> torch.fx.Node: + return gm.graph.call_function(int_to_valid_dtype, (val,)) + + +def insert_quantized_node( + gm: torch.fx.GraphModule, + val_node: torch.fx.Node, + scale_node: float | torch.fx.Node, + zero_point_node: float | torch.fx.Node, + qmin_node: float | int | torch.fx.Node, + qmax_node: float | int | torch.fx.Node, + dtype_node: torch.dtype | torch.fx.Node, + qscheme: torch.qscheme | None, +) -> torch.fx.Node: + return gm.graph.call_function( + quantize_per_tensor, + ( + val_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + dtype_node, + ), + ) + + +def get_dequantized( + val: torch.Tensor, + scale: float | torch.Tensor, + zero_point: float | torch.Tensor, + qmin: float | int, + qmax: float | int, + dtype: torch.dtype, + axis: int | None, + qscheme: torch.qscheme | None, +) -> torch.Tensor: + if qscheme is torch.per_tensor_affine: + return dequantize_per_tensor( + val, + scale, # type: ignore[arg-type] + zero_point, # type: ignore[arg-type] + qmin, # type: ignore[arg-type] + qmax, # type: ignore[arg-type] + dtype, + ) + elif qscheme is torch.per_channel_affine: + return dequantize_per_channel( + val, + scale, # type: ignore[arg-type] + zero_point, # type: ignore[arg-type] + axis, # type: ignore[arg-type] + qmin, # type: ignore[arg-type] + qmax, # type: ignore[arg-type] + dtype, + ) + else: + raise RuntimeError(f"Unsupported dequantization scheme: {qscheme}") + + +def insert_dequantized_node( + gm: torch.fx.GraphModule, + val_node: torch.fx.Node, + scale_node: float | torch.fx.Node, + zero_point_node: float | torch.fx.Node, + qmin_node: float | int | torch.fx.Node, + qmax_node: float | int | torch.fx.Node, + dtype_node: torch.dtype | torch.fx.Node, + axis_node: int | torch.fx.Node | None, + qscheme: torch.qscheme | None, +) -> torch.fx.Node: + if qscheme is torch.per_tensor_affine: + return gm.graph.call_function( + dequantize_per_tensor, + ( + val_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + dtype_node, + ), + ) + elif qscheme is torch.per_channel_affine: + return gm.graph.call_function( + dequantize_per_channel, + ( + val_node, + scale_node, + zero_point_node, + axis_node, + qmin_node, + qmax_node, + dtype_node, + ), + ) + else: + raise RuntimeError(f"Unsupported dequantization scheme: {qscheme}") + + +def get_qmin_qmax(dtype: torch.dtype) -> tuple[int | float, int | float]: + return calculate_qmin_qmax(None, None, False, dtype, False) # type: ignore[arg-type] + + +def insert_qmin_qmax_node( + gm: torch.fx.GraphModule, dtype_node: torch.dtype | torch.fx.Node +) -> tuple[torch.fx.Node, torch.fx.Node]: + q_min_max_node = gm.graph.call_function( + calculate_qmin_qmax, (None, None, False, dtype_node, False) + ) + qmin_node = gm.graph.call_function(operator.getitem, (q_min_max_node, 0)) + qmax_node = gm.graph.call_function(operator.getitem, (q_min_max_node, 1)) + return qmin_node, qmax_node + + +def get_script_object( + gm: torch.nn.Module, node: torch.fx.Node +) -> torch._C.ScriptObject: + if not isinstance(node, torch.fx.Node): + raise AssertionError(f"expected fx.Node, got {type(node).__name__}") + if node.op != "get_attr": + raise AssertionError(f"expected get_attr op, got {node.op}") + attr_name = node.target + if not isinstance(attr_name, str): + raise AssertionError(f"expected str target, got {type(attr_name).__name__}") + + mod = gm + for attr in attr_name.split("."): + mod = getattr(mod, attr) + if not isinstance(mod, torch._C.ScriptObject): + raise AssertionError(f"expected ScriptObject, got {type(mod).__name__}") + return mod + + +def insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject( + gm: torch.fx.GraphModule, + param_node: torch.fx.Node, +) -> tuple[torch.fx.Node, torch.fx.Node | None]: + """Directly inline tensor from a get_attr fx node.""" + mod = get_script_object(gm, param_node) + w_qtensor, b_qtensor = mod.unpack() # type: ignore[attr-defined] + w_attr_name, b_attr_name = ( + f"dequantized_{param_node.target}_w", + f"dequantized_{param_node.target}_b", + ) + return insert_weight_and_bias_get_attr_node( + gm, w_qtensor, b_qtensor, w_attr_name, b_attr_name + ) + + +def insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor( + gm: torch.fx.GraphModule, + get_attr_to_weight_node: torch.fx.Node, + get_attr_to_bias_node: torch.fx.Node | None, +) -> tuple[torch.fx.Node, torch.fx.Node | None]: + if not isinstance(get_attr_to_weight_node.target, str): + raise AssertionError( + f"expected str target, got {type(get_attr_to_weight_node.target).__name__}" + ) + w_qtensor = getattr(gm, get_attr_to_weight_node.target) + w_attr_name = f"dequantized_{get_attr_to_weight_node.target}_w" + + if get_attr_to_bias_node is not None: + if not isinstance(get_attr_to_bias_node.target, str): + raise AssertionError( + f"expected str target, got {type(get_attr_to_bias_node.target).__name__}" + ) + b_qtensor = getattr(gm, get_attr_to_bias_node.target) + b_attr_name = f"dequantized_{get_attr_to_bias_node.target}_b" + else: + b_qtensor, b_attr_name = None, "" + + return insert_weight_and_bias_get_attr_node( + gm, w_qtensor, b_qtensor, w_attr_name, b_attr_name + ) + + +def insert_weight_and_bias_get_attr_node( + gm: torch.fx.GraphModule, + w_qtensor: torch.Tensor, + b_qtensor: torch.Tensor | None, + w_attr_name: str, + b_attr_name: str, +) -> tuple[torch.fx.Node, torch.fx.Node | None]: + w_tensor = get_tensor_from_qtensor(w_qtensor) + _assign_attr(w_tensor, gm, w_attr_name) + w_tensor_attr = gm.graph.get_attr(w_attr_name) + + if b_qtensor is not None: + b_tensor = get_tensor_from_qtensor(b_qtensor, dequant=False) + _assign_attr(b_tensor, gm, b_attr_name) + b_tensor_attr = gm.graph.get_attr(b_attr_name) + else: + b_tensor_attr = None + + return w_tensor_attr, b_tensor_attr + + +def get_tensor_from_qtensor( + qtensor: torch.Tensor, dequant: bool = True +) -> torch.Tensor: + # Manual conversion because qint8 is not used anymore. + if qtensor.dtype in [torch.qint8, torch.quint8]: + tensor = qtensor.int_repr() + else: + tensor = qtensor + + # Weights need dequantization with scaling and zero_point adjustment, but + # bias does not need that. + if dequant: + qscheme = qtensor.qscheme() + if qscheme == torch.per_channel_affine: + scale, zero_point, axis = ( + qtensor.q_per_channel_scales(), + qtensor.q_per_channel_zero_points(), + qtensor.q_per_channel_axis(), + ) + else: + scale, zero_point, axis = ( + qtensor.q_scale(), # type: ignore[assignment] + qtensor.q_zero_point(), # type: ignore[assignment] + None, + ) + dtype = tensor.dtype + qmin, qmax = get_qmin_qmax(dtype) + return get_dequantized( + tensor, scale, zero_point, qmin, qmax, dtype, axis, qscheme + ) + return tensor + + +def insert_fused_activation_node( + gm: torch.fx.GraphModule, opname: str, fx_node: torch.fx.Node +) -> torch.fx.Node: + if opname in ["conv1d_relu", "conv2d_relu", "linear_relu", "add_relu", "mul_relu"]: + fx_node = gm.graph.call_function(torch.ops.aten.relu, (fx_node,)) + return fx_node + + +def _conv1d_op_with_squeeze( + inp: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None, + stride: list[int], + padding: list[int], + dilation: list[int], + groups: int, +) -> torch.Tensor: + # In quantized version, conv1d is emulated using conv2d with squeeze and unsqueeze + # operations before and after the conv2d operation to match the dimension of weights. + # Reference: https://github.com/pytorch/pytorch/blob/eca0cb0fbe84bb0a34fa94afe261bceecd52c436/aten/src/ATen/native/quantized/cpu/qconv.cpp#L1827 + s_inp = torch.ops.aten.unsqueeze(inp, 2) + conv1d_res = torch.ops.aten.conv2d( + s_inp, + weight, + bias, + stride, + padding, + dilation, + groups, + ) + uns_conv1d_res = torch.ops.aten.squeeze(conv1d_res, 2) + return uns_conv1d_res + + +def _transform_conv_with_packedparam(gm: torch.fx.GraphModule, node: torch.fx.Node): + """Conv specific transformation function.""" + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(node.target).__name__}") + opname = node.target._opname + scale_node, zero_point_node = node.args[2], node.args[3] + + op_f = ( + torch.ops.aten.conv2d + if opname in ["conv2d", "conv2d_relu"] + else _conv1d_op_with_squeeze + ) + + inp_node, param_node = node.args[0], node.args[1] + if not isinstance(inp_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for inp, got {type(inp_node)}") + if not isinstance(param_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for param, got {type(param_node)}") + + if param_node.op == "call_function": + # Using Conv2dPrepackParam from conv_prepack. + # We directly skip the packing call and inline weights and bias. + w_node, b_node = param_node.args[0], param_node.args[1] + if not isinstance(w_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for w, got {type(w_node)}") + if b_node is not None and not isinstance(b_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for b, got {type(b_node)}") + ( + param_0, + param_1, + ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor( + gm, w_node, b_node + ) + op_res_node = gm.graph.call_function( + op_f, (inp_node, param_0, param_1, *param_node.args[2:]) + ) + else: + # Using ConvPrepackedParam. + param = get_script_object(gm, param_node) + ( + param_0, + param_1, + ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject( + gm, param_node + ) # type: ignore[assignment] + op_res_node = gm.graph.call_function( + op_f, + ( + inp_node, + param_0, + param_1, + param.stride(), # type: ignore[attr-defined] + param.padding(), # type: ignore[attr-defined] + param.dilation(), # type: ignore[attr-defined] + param.groups(), # type: ignore[attr-defined] + ), + ) + return op_res_node, scale_node, zero_point_node + + +def _transform_linear_with_packedparam(gm: torch.fx.GraphModule, node: torch.fx.Node): + """Linear specific transformation function.""" + scale_node, zero_point_node = node.args[2], node.args[3] + + inp_node, param_node = node.args[0], node.args[1] + if not isinstance(inp_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for inp, got {type(inp_node)}") + if not isinstance(param_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for param, got {type(param_node)}") + + if param_node.op == "call_function": + # Using LinearPrepackParam from linear_prepack. + # We directly skip the packing call and inline weights and bias. + w_node, b_node = param_node.args[0], param_node.args[1] + if not isinstance(w_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for w, got {type(w_node)}") + if b_node is not None and not isinstance(b_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for b, got {type(b_node)}") + ( + param_0, + param_1, + ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor( + gm, w_node, b_node + ) + op_res_node = gm.graph.call_function( + torch.ops.aten.linear, (inp_node, param_0, param_1, *param_node.args[2:]) + ) + else: + # Using LinearPackedParams. + ( + param_0, + param_1, + ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject( + gm, param_node + ) # type: ignore[assignment] + op_res_node = gm.graph.call_function( + torch.ops.aten.linear, (inp_node, param_0, param_1) + ) + return op_res_node, scale_node, zero_point_node + + +def _transform_op_where_last_two_arguments_are_scale_and_zero_point( + gm: torch.fx.GraphModule, node: torch.fx.Node +): + """ + This transformation function can be used for function where the last two + parameters are scale and zero point. Additionally, the function's parameters + do not need any unpacking. + """ + to_standard_op = { + "mul": torch.ops.aten.mul, + "mul_relu": torch.ops.aten.mul, + "add": torch.ops.aten.add, + "add_relu": torch.ops.aten.add, + "softmax": torch.ops.aten.softmax, + "cat": torch.ops.aten.cat, + "hardswish": torch.ops.aten.hardswish, + } + + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(node.target).__name__}") + opname, args = node.target._opname, node.args + scale_node, zero_point_node = args[-2], args[-1] + op_res_node = gm.graph.call_function(to_standard_op[opname], tuple(args[:-2])) + return op_res_node, scale_node, zero_point_node + + +def _transform_scalar_arithmetic(gm: torch.fx.GraphModule, node: torch.fx.Node): + """Transform scalar overload for basic arithmetic.""" + to_standard_op = { + "mul": torch.ops.aten.mul.Scalar, + "add": torch.ops.aten.add.Scalar, + } + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(node.target).__name__}") + opname, args = node.target._opname, node.args + op_res_node = gm.graph.call_function(to_standard_op[opname], args) + return op_res_node, _SCALE, _ZERO_POINT + + +def _transform_prepacked_op(gm: torch.fx.GraphModule, node: torch.fx.Node): + """ + Transformation for functions under prepacked namespace, where they share + the same handling logic that [...]OpContext contains all parameters. + """ + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(node.target).__name__}") + opname, args = node.target._opname, node.args + op_f = None + if opname == "conv2d_clamp_run": + op_f = torch.ops.aten.conv2d + elif opname == "linear_clamp_run": + op_f = torch.ops.aten.linear + else: + raise RuntimeError(f"Invalid operator {opname}") + + if not isinstance(args[1], torch.fx.Node): + raise AssertionError(f"expected fx.Node for args[1], got {type(args[1])}") + so = get_script_object(gm, args[1]) + + func_args = [] + func_args += [args[0]] + func_args += so.unpack()[:2] # type: ignore[attr-defined] + if opname == "conv2d_clamp_run": + func_args += torch.ops.prepacked.unpack_prepacked_sizes_conv2d(so)[2:] + + op_res_node = gm.graph.call_function(op_f, tuple(func_args)) + return op_res_node + + +def _transform_batch_norm(gm: torch.fx.GraphModule, node: torch.fx.Node): + args = node.args + scale_node, zero_point_node = args[-2], args[-1] + op_res_node = gm.graph.call_function( + torch.ops.aten.native_batch_norm, (*args[:-3], False, 0.1, args[-3]) + ) + op_res_node = gm.graph.call_function(operator.getitem, (op_res_node, 0)) + return op_res_node, scale_node, zero_point_node + + +def fx_transform_quantized_op_to_standard_op( + gm: torch.fx.GraphModule, node: torch.fx.Node +) -> torch.fx.Node: + global _SCALE, _ZERO_POINT, _INPUT_Q_DTYPE + + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(node.target).__name__}") + opname, overload = node.target._opname, node.target._overloadname + + key = f"{opname}.{overload}" + opname_to_transform_f = { + "conv1d.new": _transform_conv_with_packedparam, + "conv1d_relu.new": _transform_conv_with_packedparam, + "conv1d.default": _transform_conv_with_packedparam, + "conv1d_relu.default": _transform_conv_with_packedparam, + "conv2d.new": _transform_conv_with_packedparam, + "conv2d_relu.new": _transform_conv_with_packedparam, + "conv2d.default": _transform_conv_with_packedparam, + "conv2d_relu.default": _transform_conv_with_packedparam, + "linear.default": _transform_linear_with_packedparam, + "linear_relu.default": _transform_linear_with_packedparam, + "add.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "add_relu.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "mul.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "mul_relu.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "softmax.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "cat.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "hardswish.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "batch_norm2d.default": _transform_batch_norm, + "mul.Scalar": _transform_scalar_arithmetic, + "add.Scalar": _transform_scalar_arithmetic, + } + + if f"{key}" not in opname_to_transform_f: + raise RuntimeError(f"Unsupported quantized op during transformation: {key}") + + op_res_node, scale_node, zero_point_node = opname_to_transform_f[f"{key}"](gm, node) + + # Add fused activation layer. + op_res_node = insert_fused_activation_node(gm, opname, op_res_node) + _SCALE, _ZERO_POINT = scale_node, zero_point_node + + if _INPUT_Q_DTYPE is None: + raise AssertionError("_INPUT_Q_DTYPE should not be None") + qmin_node, qmax_node = insert_qmin_qmax_node(gm, _INPUT_Q_DTYPE) + q_fx_node = insert_quantized_node( + gm, + op_res_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + _INPUT_Q_DTYPE, + torch.per_tensor_affine, + ) + dq_fx_node = insert_dequantized_node( + gm, + q_fx_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + _INPUT_Q_DTYPE, + None, + torch.per_tensor_affine, + ) + return dq_fx_node + + +def replace_quantized_ops_with_standard_ops(gm: torch.fx.GraphModule): + """ + Replace legacy quantized ops (aten.quantize_per_tensor, quantized.conv) with + PT2 ops (quantize_decomposed.quantize_per_tensor, aten.conv). + + Before: x || -> aten.q || -> quantized.conv2d || -> quantized.linear || -> aten.dq || -> y + + After: x || -> qd.q -> qd.dq || -> aten.conv2d -> qd.q -> qd.dq || aten.linear -> qd.q -> qd.dq || -> y + + (qd == quantized_decomposed library, q = quantize, dq = dequantize) + ^ + | + getattr(w), getattr(b) from Conv2dParamPrepack + + During each iteration, the transformation spits out the transformed operator, its quantized output, + and its dequantized value together. We did this because dequantization need to use the + scale and zero point parameters from the quantization to recover the approximate original value. After each + iteration, the new dequantization node will be used as the input to the next node (e.g., dq2 -> linear). + + For operators like conv2d and linear, their weights and bias are packed in a quantized format in the ScriptObject. + During the transformation, we unpack those objects, get their dequantized tensor, populate those + as attributes to the module, and use getattr to access them. + + One exception in the transformation is conv_prepack and linear_prepack. Those calls pack + weight and bias constant tensors into ScriptObject, which are then used by subsequent conv2d or linear calls. + During transformation, we directly skip transforming conv_prepack or linear_prepack. We check whether ScriptObject to the + quantized::conv2d or linear is from conv_prepack or linear_prepack. If it is, we then inline those parameters + to the operator by converting them to a getattr fx.node. + + For prepacked::conv2d_clamp_run and prepacked::linear_clamp_run, we directly convert them to aten.conv2d and aten.linear + without the need of doing de/quantization. + + Three global variables defined are _INPUT_Q_DTYPE, _SCALE, _ZERO_POINT. _INPUT_Q_DTYPE determines the de/quantization + data type, which is the same across the entire program, but it only shows up in the very first quantization + call. _SCALE and _ZERO_POINT are used only when operators do not have those specified. E.g., mul.Scalar. + """ + + global _INPUT_Q_DTYPE + + quantized = False + + last_quantized_node = None + # pyrefly: ignore [bad-assignment] + for node in gm.graph.nodes: + if isinstance(node.target, OpOverload): + with gm.graph.inserting_before(node): + namespace, opname = node.target.namespace, node.target._opname + if namespace == "quantized" and opname not in [ + "conv_prepack", + "linear_prepack", + ]: + quantized = True + fx_node = fx_transform_quantized_op_to_standard_op(gm, node) + node.replace_all_uses_with(fx_node) + last_quantized_node = fx_node + elif namespace == "prepacked": + quantized = True + fx_node = _transform_prepacked_op(gm, node) + node.replace_all_uses_with(fx_node) + last_quantized_node = fx_node + elif namespace == "aten" and opname == "quantize_per_tensor": + inp_node, scale_node, zero_point_node, dtype_node = node.args + dtype_node = fx_enum_to_dtype(gm, dtype_node) + _INPUT_Q_DTYPE = dtype_node + qmin_node, qmax_node = insert_qmin_qmax_node(gm, dtype_node) + q_fx_node = insert_quantized_node( + gm, + inp_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + dtype_node, + torch.per_tensor_affine, + ) + dq_fx_node = insert_dequantized_node( + gm, + q_fx_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + dtype_node, + None, + torch.per_tensor_affine, + ) + node.replace_all_uses_with(dq_fx_node) + last_quantized_node = dq_fx_node + elif namespace == "aten" and opname == "dequantize": + if last_quantized_node is None: + raise AssertionError("last_quantized_node should not be None") + node.replace_all_uses_with(last_quantized_node) + else: + last_quantized_node = node + + # Post-processing again to remove legacy ScriptObjects and quantized tensors + # stored as attributes or in the buffer. This is used to clean up the GraphModule + # to not trigger tracing errors like missing __obj_flatten__ functions. + def _clean_attr(mod: torch.nn.Module): + for submod in mod.modules(): + attr_names_to_clean = set() + for k, v in submod.__dict__.items(): + if isinstance(v, torch.ScriptObject): + attr_names_to_clean.add(k) + if k == "_buffers": + buffer_name_to_clean = set() + + for b_name, b_value in v.items(): + if isinstance(b_value, torch.Tensor) and b_value.dtype in [ + torch.qint8, + torch.quint8, + ]: + buffer_name_to_clean.add(b_name) + for b_name in buffer_name_to_clean: + v.pop(b_name, None) + for attr_name in attr_names_to_clean: + delattr(submod, attr_name) + + if quantized: + """ + TODO: SetAttr + quantized ops will result incorrect program. This flag is used to temporarily + bypass test cases. + + The deadcode elimination pass is needed to remove legacy quantized ops. Otherwise, retracing + will throw errors. However, the current way of SetAttr does inplace update to attributes, so + this pass regard them as dead code and remove them. Below is an example of GraphModule before + and after the dead code elimination pass. + + class GraphModule(torch.nn.Module): + def forward(self, x_1): + # No stacktrace found for following nodes + data = self.data; data = None + data_1 = self.data + add_tensor = torch.ops.aten.add.Tensor(data_1, x_1, alpha = 1); data_1 = None + data_2 = self.data + copy_ = torch_Tensor_copy_(data_2, add_tensor); data_2 = add_tensor = copy_ = None + data_3 = self.data + add_tensor_1 = torch.ops.aten.add.Tensor(x_1, data_3, alpha = 1); x_1 = data_3 = None + return add_tensor_1 + + class GraphModule(torch.nn.Module): + def forward(self, x_1): + # No stacktrace found for following nodes + data_3 = self.data + add_tensor_1 = torch.ops.aten.add.Tensor(x_1, data_3, alpha = 1); x_1 = data_3 = None + return add_tensor_1 + """ + gm.graph.eliminate_dead_code() + _clean_attr(gm) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..100c88397828f42b340174f02f9cc2327338be0f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py @@ -0,0 +1,131 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from torch._higher_order_ops.wrap import wrap_with_set_grad_enabled + +from ..utils import node_inline_, nodes_filter, nodes_first, nodes_map, sequential_split +from .replace_with_hop_pass_util import ( + _replace_with_hop_helper, + _replace_with_hop_pass_helper, + _sequential_split_and_maybe_inline_subgraphs_helper, +) + + +if TYPE_CHECKING: + from torch.export.graph_signature import ExportGraphSignature + + +def _is_set_grad_enabled_node(node: torch.fx.Node) -> torch.fx.Node | bool: + return ( + node + and node.op == "call_function" + and node.target is torch._C._set_grad_enabled + ) + + +def _is_set_grad_enabled_sub_mod( + node: torch.fx.Node, omit_if_same_with_ambient: bool = False +) -> bool | torch.Tensor: + if node.op == "call_module": + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + subgm = getattr(node.graph.owning_module, node.target) + first_non_ph = nodes_first( + subgm.graph.nodes, lambda node: node.op != "placeholder" + ) + if ( + first_non_ph + and first_non_ph.op == "call_function" + and first_non_ph.target is torch._C._set_grad_enabled + ): + return ( + first_non_ph.args[0] != torch.is_grad_enabled() # type: ignore[bad-return] + if omit_if_same_with_ambient + else True + ) + return False + + +def _replace_with_hop(node: torch.fx.Node) -> None: + if node.op != "call_module": + raise AssertionError(f"expected call_module op, got {node.op}") + graph: torch.fx.Graph = node.graph + if graph.owning_module is None: + raise AssertionError("graph.owning_module must not be None") + gm: torch.fx.GraphModule = graph.owning_module + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + sub_gm = getattr(gm, node.target) + sub_graph = sub_gm.graph + set_grad_nodes = nodes_filter(sub_graph.nodes, _is_set_grad_enabled_node) + if len(set_grad_nodes) > 0: + if len(set_grad_nodes) != 1: + raise AssertionError( + f"expected exactly 1 set_grad node, got {len(set_grad_nodes)}" + ) + set_grad_node = set_grad_nodes[0] + _replace_with_hop_helper(node, set_grad_node, wrap_with_set_grad_enabled) + sub_graph.erase_node(set_grad_node) + + +def _remove_set_grad_and_inline(node: torch.fx.Node) -> None: + if node.op != "call_module": + raise AssertionError(f"expected call_module op, got {node.op}") + graph: torch.fx.Graph = node.graph + if graph.owning_module is None: + raise AssertionError("graph.owning_module must not be None") + gm: torch.fx.GraphModule = graph.owning_module + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + sub_gm = getattr(gm, node.target) + sub_graph = sub_gm.graph + nodes_map( + sub_graph.nodes, + lambda n: sub_graph.erase_node(n) if _is_set_grad_enabled_node(n) else n, + ) + node_inline_(node) + + +def _sequential_split_and_maybe_inline_subgraphs( + gm: torch.fx.GraphModule, graph_signature: ExportGraphSignature | None +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Helper function for replace_set_grad_with_hop_pass(). + Split the graph module into multiple subgraphs based on the set_grad_enabled nodes. + For each subgraph, decides whether to construct a HOO subgraph, or inline the calls + back into the parent graph module. + """ + need_replacing = any(_is_set_grad_enabled_node(node) for node in gm.graph.nodes) + if not need_replacing: + return gm, graph_signature + + # sequential_split returns a new graph module that could have different output + # args names. We need to fix the graph signature. + new_gm = sequential_split(gm, _is_set_grad_enabled_node) + + def _maybe_inline_or_replace_with_hop(node: torch.fx.Node): + if _is_set_grad_enabled_sub_mod(node, omit_if_same_with_ambient=True): + _replace_with_hop(node) + else: + _remove_set_grad_and_inline(node) + + return _sequential_split_and_maybe_inline_subgraphs_helper( + new_gm, graph_signature, _maybe_inline_or_replace_with_hop + ) + + +def replace_set_grad_with_hop_pass( + gm: torch.fx.GraphModule, graph_signature: ExportGraphSignature | None +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and + then recursively call itself on each of the submodules. + """ + return _replace_with_hop_pass_helper( + gm, + graph_signature, + _sequential_split_and_maybe_inline_subgraphs, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..98d93e16559b77e9fc812096a010261cdaf05fde --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py @@ -0,0 +1,64 @@ +# mypy: allow-untyped-defs + +import torch +from torch._export.error import InternalError +from torch._export.pass_base import _ExportPassBaseDeprecatedDoNotUse +from torch._ops import HigherOrderOperator, OpOverload + + +__all__ = ["ReplaceViewOpsWithViewCopyOpsPass"] + + +_NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS: dict[OpOverload, OpOverload] = { + torch.ops.aten._unsafe_view.default: torch.ops.aten.view_copy.default, +} + + +def is_view_op(schema: torch._C.FunctionSchema) -> bool: + if len(schema.arguments) == 0: + return False + alias_info = schema.arguments[0].alias_info + return (alias_info is not None) and (not alias_info.is_write) + + +def get_view_copy_of_view_op(schema: torch._C.FunctionSchema) -> OpOverload | None: + if is_view_op(schema) and schema.name.startswith("aten::"): + view_op_name = schema.name.split("::")[1] + view_op_overload = ( + schema.overload_name if schema.overload_name != "" else "default" + ) + view_copy_op_name = view_op_name + "_copy" + if not hasattr(torch.ops.aten, view_copy_op_name): + raise InternalError(f"{schema.name} is missing a view_copy variant") + + view_copy_op_overload_packet = getattr(torch.ops.aten, view_copy_op_name) + + if not hasattr(view_copy_op_overload_packet, view_op_overload): + raise InternalError(f"{schema.name} is missing a view_copy variant") + + return getattr(view_copy_op_overload_packet, view_op_overload) + + return None + + +class ReplaceViewOpsWithViewCopyOpsPass(_ExportPassBaseDeprecatedDoNotUse): + """ + Our backend expects pure functional operators. For efficiency + purposes, we keep view ops around while functionalizing the exported + program. This pass replaces view ops with view copy ops for backends that + need AOT memory planning. + """ + + def call_operator(self, op, args, kwargs, meta): + if op in _NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS: + return super().call_operator( + (_NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS[op]), args, kwargs, meta + ) + + if isinstance(op, HigherOrderOperator): + return super().call_operator(op, args, kwargs, meta) + + if view_copy_op := get_view_copy_of_view_op(op._schema): + return super().call_operator(view_copy_op, args, kwargs, meta) + + return super().call_operator(op, args, kwargs, meta) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_with_hop_pass_util.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_with_hop_pass_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b095d2c6e07609fd603477011b29de1a326769d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_with_hop_pass_util.py @@ -0,0 +1,202 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import contextlib +import copy +import operator +from typing import TYPE_CHECKING + +import torch + +from ..utils import node_replace_, nodes_map + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torch._ops import HigherOrderOperator + from torch.export.graph_signature import ExportGraphSignature + + +def _replace_with_hop_helper( + node: torch.fx.Node, + enter_block_node: torch.fx.Node, + wrap_hoo: HigherOrderOperator, +) -> None: + graph: torch.fx.Graph = node.graph + if graph.owning_module is None: + raise AssertionError("graph.owning_module must not be None") + gm: torch.fx.GraphModule = graph.owning_module + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + sub_gm = getattr(gm, node.target) + + def set_hoo_node_meta(call_func_node): + call_func_node.meta["nn_module_stack"] = copy.copy( + enter_block_node.meta.get("nn_module_stack", {}) + ) + call_func_node.meta["torch_fn"] = ( + f"{wrap_hoo.__name__}", + # pyrefly: ignore [missing-attribute] + f"{wrap_hoo.__class__.__name__}.{wrap_hoo.__name__}", + ) + if isinstance(output_args, (tuple, list)): + call_func_node.meta["val"] = tuple(arg.meta["val"] for arg in output_args) + elif isinstance(output_args, torch.fx.Node): + call_func_node.meta["val"] = (output_args.meta["val"],) + + with graph.inserting_before(node): + get_attr_node = graph.get_attr(node.target) + get_attr_node.meta["nn_module_stack"] = copy.copy( + enter_block_node.meta.get("nn_module_stack", {}) + ) + output_node = next(iter(reversed(sub_gm.graph.nodes)), None) + # Split_module pass intentionally doesn't add output node + # if the graph doesn't return anything. + # TODO (tmanlaibaatar) Figure out if this is right behaviour + # for split_module + if isinstance(output_node, torch.fx.Node) and output_node.op != "output": + output_node = None + if output_node is not None: + if len(output_node.args) != 1: + raise AssertionError( + f"expected 1 output arg, got {len(output_node.args)}" + ) + output_args = output_node.args[0] + enter_block_node_args = enter_block_node.args + if isinstance(output_args, (tuple, list)): + call_func_node = graph.call_function( + wrap_hoo, + (*enter_block_node_args, get_attr_node, *node.args), + {}, + ) + # Create the metadata + set_hoo_node_meta(call_func_node) + node_replace_(node, call_func_node) + + # Rename the name of getitem nodes to the actual name of its contents + # for passing verifier and better readability, also propagate metadata + for get_item_node in call_func_node.users: + idx: int = get_item_node.args[1] # type: ignore[assignment] + output_node = output_args[idx] + get_item_node._rename(output_node.name) + get_item_node.meta = output_node.meta + + elif isinstance(output_args, torch.fx.Node): + call_func_node = graph.create_node( + "call_function", + wrap_hoo, + (*enter_block_node_args, get_attr_node, *node.args), + {}, + output_args.name, + ) + # Modify the subgraph to output a singleton list. + output_node.args = ((output_args,),) + # Add in an extra `getitem(wrap_hoo, 0)` node to the toplevel graph. + get_item_node = graph.create_node( + "call_function", + operator.getitem, + (call_func_node, 0), + {}, + ) + # Create the metadata + get_item_node.meta = output_args.meta + set_hoo_node_meta(call_func_node) + node_replace_(node, get_item_node) + else: + raise NotImplementedError( + f"replace_with_hop_pass doesn't support output type {type(output_args)}" + ) + else: + # TODO (shangdiy): remove this line, since the export graph can be non-functional + node.graph.erase_node(node) + + +def _sequential_split_and_maybe_inline_subgraphs_helper( + new_gm: torch.fx.GraphModule, + graph_signature: ExportGraphSignature | None, + maybe_inline_or_replace_with_hop: Callable[[torch.fx.Node], None], +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Helper function for replacing graph nodes with higher order nodes. + For each subgraph in `new_gm`, decides whether to construct a HOO subgraph, or inline the calls + back into the parent graph module, depending on `maybe_inline_or_replace_with_hop`. + """ + # new_gm is a new graph module that could have different output args names. + # We need to fix the graph signature. + replace_ctx = contextlib.nullcontext() + new_signature = None + if graph_signature is not None: + # Cannot deep copy a real ScriptObject, which is referenced + # in the FakeScriptObject. Copy should be good enough to guard + # against accidental mutation to original graph_signature. + new_signature = copy.copy(graph_signature) + new_gm_out_node = next(reversed(new_gm.graph.find_nodes(op="output"))) + if new_gm_out_node.op != "output" or len(new_gm_out_node.args[0]) != len( + new_signature.output_specs + ): + raise AssertionError( + f"output node mismatch: {new_gm_out_node.op}, " + f"{len(new_gm_out_node.args[0])} vs {len(new_signature.output_specs)}" + ) + for arg_node, out_spec in zip( + new_gm_out_node.args[0], new_signature.output_specs + ): + if arg_node is None: + if out_spec.arg.value is not None: # type: ignore[union-attr] + raise AssertionError( + f"expected None out_spec.arg.value, got {out_spec.arg.value}" # type: ignore[union-attr] + ) + elif ( + isinstance(arg_node, torch.fx.Node) + and out_spec.arg.name != arg_node.name + ): + out_spec.arg.name = arg_node.name + + replace_ctx = new_gm._set_replace_hook(new_signature.get_replace_hook()) # type: ignore[assignment] + + with replace_ctx: + nodes_map( + list(new_gm.graph.nodes), + lambda node: ( + maybe_inline_or_replace_with_hop(node) + if node.op == "call_module" + else node + ), + ) + new_gm.recompile() + new_gm.graph.lint() + return new_gm, new_signature + + +def _replace_with_hop_pass_helper( + gm: torch.fx.GraphModule, + graph_signature: ExportGraphSignature | None, + sequential_split_and_maybe_inline_subgraphs: Callable[ + [torch.fx.GraphModule, ExportGraphSignature | None], + tuple[torch.fx.GraphModule, ExportGraphSignature | None], + ], +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and + then recursively call itself on each of the submodules. + """ + new_gm, new_signature = sequential_split_and_maybe_inline_subgraphs( + gm, graph_signature + ) + # recursively call + for node in new_gm.graph.nodes: + if node.op == "get_attr": + subgm = getattr(new_gm, node.target) + if not isinstance(subgm, torch.fx.GraphModule): + continue + new_subgm, _ = _replace_with_hop_pass_helper( + subgm, + None, + sequential_split_and_maybe_inline_subgraphs, + ) + setattr(new_gm, node.target, new_subgm) + + new_gm.recompile() + new_gm.graph.lint() + return new_gm, new_signature diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af8ea412709f7bb16052cb25795597469ad61c60 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/dynamic_shapes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/dynamic_shapes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..148984c99057c6e68ef1a48bb34e8ff64bd574f8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/dynamic_shapes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf91411fb64da2b309bc413ce875142e3e51fe2f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema_check.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema_check.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c19289f9fa80ca96440085acab5d2cce2ce8946 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema_check.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaa4ab8f58b380161bc85736a5e8b4dbdd319c7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:945bc7008c47b8da653b3aeefba9cb943119de745389967fa268a8d0b0a606e6 +size 225350 diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/union.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/union.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adfd8141a0d889ebb7a697d19c3f469e818bdb9d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/union.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/dynamic_shapes.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/dynamic_shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..32fe6014b04447ebe8f51ce8e855a737fbddd5d6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/dynamic_shapes.py @@ -0,0 +1,327 @@ +import dataclasses +from typing import Any + +import torch +from torch._dynamo.exc import UserError, UserErrorType +from torch.export.dynamic_shapes import ( + _check_dynamic_shapes, + _DerivedDim, + _DimHint, + _tree_map_with_path, + Dim, +) +from torch.utils._pytree import tree_map + +from .serialize import _dataclass_to_dict + + +@dataclasses.dataclass +class RootDim: + """ + This represents a Dim object. + """ + + min: int + max: int | None + derived: list[str] + + +@dataclasses.dataclass +class DynamicShapesSpec: + """ + This stores a dynamic_shapes spec for de/serialization. + """ + + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None + dims: dict[str, RootDim] + + +def _postprocess_serialized_shapes( + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None, + dims: dict[str, dict[str, int | list[str] | None]], + to_dict: bool | None = False, +) -> DynamicShapesSpec | dict[str, Any]: + """ + Sorts dims and dumps to dictionary format. + """ + from torch.utils._sympy.numbers import int_oo + + # pyrefly: ignore [bad-assignment] + dims = { + k: RootDim( + min=v["min"], # type: ignore[arg-type] + max=None if v["max"] is int_oo else v["max"], # type: ignore[arg-type] + derived=sorted(v["derived"]), # type: ignore[arg-type] + ) + for k, v in sorted(dims.items()) + } + # pyrefly: ignore [bad-argument-type] + spec = DynamicShapesSpec(dynamic_shapes=dynamic_shapes, dims=dims) + if to_dict: + return _dataclass_to_dict(spec) + else: + return spec + + +def _dump_dynamic_shapes( + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None, + args: tuple[Any], + kwargs: dict[str, Any] | None = None, + to_dict: bool | None = False, +) -> DynamicShapesSpec | dict[str, Any]: + """ + Utility function for dynamic shapes serialization, serializing a dynamic_shapes spec. + Returns a DynamicShapesSpec dataclass containing 2 fields, "dynamic_shapes" and "dims". + Uses args & kwargs to distinguish between tensor-level and dim-level specs (only for Nones). + + dynamic_shapes: A pytree structure mirroring the dynamic_shapes input to export(): + - Each tensor input is represented with a list of values, non-tensor inputs with None. + - dynamic dimensions (i.e. symbols) in tensors and Dim enums are represented with strings. + - static dimensions are represented with ints. + + dims: A dictionary mapping each symbol name to the min/max range and derived dim names. + + For example: + ``` + dx = Dim("dx", min=4, max=16) + dy = dx + 1 + + inputs = ( + [ + torch.randn(4, 4), + torch.randn(5, 4), + ], + torch.randn(4), + torch.randn(4, 4), + "hello", + ) + dynamic_shapes = { + "a": [ + (dx, 4), + (dy, 4), + ], + "b": (Dim.STATIC,), + "c": None, + "d": None, + } + out = _dump_dynamic_shapes(dynamic_shapes, inputs, to_dict=True) + ``` + would generate the following output: + ``` + { + "dynamic_shapes": ( + [ + ["dx", 4], + ["dx + 1", 4], + ], + ["_DimHint.STATIC"], + ["_DimHint.STATIC", "_DimHint.STATIC"], + None, + ), + "dims": { + "dx": { + "min": 4, + "max": 16, + "derived": ["dx + 1"], + }, + }, + } + ``` + """ + dims: dict[str, dict[str, Any]] = {} + + def _standardize_shapes(path, tensor, shape): # type: ignore[no-untyped-def] + """ + Helps standardize the dynamic_shapes tree structure we serialize, + returning lists for each tensor shape, handling tensor-level Nones. + """ + if not isinstance(tensor, torch.Tensor): + return None + if shape is None: + return [Dim.STATIC] * len(tensor.shape) + + out = [] + if isinstance(shape, dict): + for i, s in enumerate(tensor.shape): + out.append(s if shape.get(i) is None else shape.get(i)) + else: + if not isinstance(shape, (tuple, list)): + raise AssertionError(f"expected tuple or list, got {type(shape)}") + for i, s in enumerate(tensor.shape): + out.append(s if shape[i] is None else shape[i]) + return out + + def _track_dim_from_dims( + val: None | int | _DimHint | Dim, + ) -> None | int | str: + """ + Tracks dims, ranges, derived dims from the standardized dynamic_shapes spec. + """ + if val is None or isinstance(val, int): # non-tensor input or static + return val + if isinstance(val, _DimHint): # store enum as string + return val.__class__.__name__ + "." + val.type.name + + if not isinstance(val, Dim): + raise AssertionError(f"expected Dim, got {type(val)}") + + # track root dim + root = val.root if isinstance(val, _DerivedDim) else val # type: ignore[attr-defined] + if root.__name__ not in dims: + dims[root.__name__] = { + "min": root.min, # type: ignore[attr-defined,union-attr] + "max": root.max, # type: ignore[attr-defined,union-attr] + "derived": set(), + } + + # track derived dims + if isinstance(val, _DerivedDim): + dims[root.__name__]["derived"].add(val.__name__) + + return val.__name__ + + if dynamic_shapes is None: + return {"dynamic_shapes": None, "dims": {}} + + # convert to tuple of specs, for each arg/kwarg + kwargs = kwargs or {} + if isinstance(dynamic_shapes, dict): + dynamic_shapes = dynamic_shapes.values() # type: ignore[assignment] + # pyrefly: ignore [bad-assignment, bad-argument-type] + dynamic_shapes = tuple(dynamic_shapes) + combined_args = tuple(args) + tuple(kwargs.values()) + + # run same check when we're processing shapes for export - is this too lazy? + _check_dynamic_shapes(dict(enumerate(combined_args)), dynamic_shapes) # type: ignore[arg-type] + + tree_shapes = _tree_map_with_path( + _standardize_shapes, combined_args, dynamic_shapes, tree_name="inputs" + ) + serialized_shapes = tree_map(_track_dim_from_dims, tree_shapes) + return _postprocess_serialized_shapes(serialized_shapes, dims, to_dict=to_dict) + + +def _load_dynamic_shapes( + spec: DynamicShapesSpec | dict[str, Any], + from_dict: bool | None = False, +) -> dict[str, Any] | tuple[Any] | list[Any] | None: + """ + Utility function for dynamic shapes serialization. + Deserializes a DynamicShapesSpec or corresponding dictionary into a dynamic_shapes input to export(). + """ + import sympy + + from torch.fx.experimental.symbolic_shapes import _is_supported_equivalence + + if from_dict: + if not isinstance(spec, dict): + raise UserError( + UserErrorType.INVALID_INPUT, + f"With from_dict=True, expected `spec` to be a dict, got {type(spec)}", + ) + if sorted(spec.keys()) != ["dims", "dynamic_shapes"]: + raise UserError( + UserErrorType.INVALID_INPUT, + "With from_dict=True, expected `spec` to have keys `dims` and `dynamic_shapes`, " + f"instead found {spec.keys()}", + ) + dims = {} + for k, v in spec["dims"].items(): + if not isinstance(k, str): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected `spec['dims']` keys to be strings for symbols, got key {type(k)}", + ) + if sorted(v.keys()) != ["derived", "max", "min"]: + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected `spec['dims']` values to have keys `derived`, `max`, and `min`, " + f"instead found {v.keys()}", + ) + if not isinstance(v["min"], int): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected dims in `spec['dims']` to map `min` to an int, got {k}: {v['min']}", + ) + if not isinstance(v["max"], int) or v["max"] is None: + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected dims in `spec['dims']` to map `max` to an int or None, got {k}: {v['max']}", + ) + if not isinstance(v["derived"], list) or any( + not isinstance(d, str) for d in v["derived"] + ): + raise UserError( + UserErrorType.INVALID_INPUT, + "Expected dims in `spec['dims']` to map `derived` to a list of derived expressions, " + f"got {k}: {v['derived']}", + ) + dims[k] = RootDim(**v) + dynamic_shapes = spec["dynamic_shapes"] + else: + if not isinstance(spec, DynamicShapesSpec): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected `spec` to be a DynamicShapesSpec, got {type(spec)}", + ) + dims = spec.dims + dynamic_shapes = spec.dynamic_shapes + + if dynamic_shapes is None: + return None + + dim_cache = {} + for name, info in dims.items(): + symbol = sympy.sympify(name) + if not isinstance(symbol, sympy.Symbol): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected `spec['dims']` keys to be symbols, got {name}", + ) + dim_cache[name] = Dim(name, min=info.min, max=info.max) # cache root dim + for _expr in info.derived: + expr = sympy.sympify(_expr) + if len(expr.free_symbols) != 1 or symbol not in expr.free_symbols: + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected derived expressions in to have {name} as the only free symbol, got {expr}", + ) + if not _is_supported_equivalence(expr): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected derived expressions to be linear expressions, got {expr}", + ) + modulus, remainder = sympy.polys.polytools.div(expr, symbol) + ddim = dim_cache[name] + if modulus != 1: + ddim = int(modulus) * ddim # type: ignore[assignment, operator] + if remainder != 0: + ddim = ddim + int(remainder) # type: ignore[assignment, operator] + dim_cache[_expr] = ddim # cache derived dims + + def deserialize_shape( + val: None | int | str, + ) -> None | int | Dim | _DimHint: + if val is None or isinstance(val, int): + return val + elif val == "_DimHint.AUTO": + return _DimHint.AUTO() + elif val == "_DimHint.DYNAMIC": + return _DimHint.DYNAMIC() + elif val == "_DimHint.STATIC": + return _DimHint.STATIC() + if not isinstance(val, str): + raise UserError( + UserErrorType.INVALID_INPUT, + "Expected leaves in `spec['dynamic_shapes']` to be ints, None, Dim.AUTO/STATIC, symbols, " + f" or derived expressions, got {val}", + ) + if val not in dim_cache: + raise UserError( + UserErrorType.INVALID_INPUT, + "Expected dims in `spec['dynamic_shapes']` to be tracked in `spec['dims']`, " + f"got {val} which is not in {dims.keys()}", + ) + return dim_cache[val] # type: ignore[return-value] + + return tree_map(deserialize_shape, dynamic_shapes) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/export_schema.thrift b/.venv/lib/python3.12/site-packages/torch/_export/serde/export_schema.thrift new file mode 100644 index 0000000000000000000000000000000000000000..5268efc883809b1b70c229e311ff90a5de7f50b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/export_schema.thrift @@ -0,0 +1,383 @@ +// @generated by update_schema.py +// checksum<> + +namespace py3 torch._export +namespace cpp2 torch._export.schema + +enum ArgumentKind { + UNKNOWN = 0, + POSITIONAL = 1, + KEYWORD = 2, +} + + +enum Layout { + Unknown = 0, + SparseCoo = 1, + SparseCsr = 2, + SparseCsc = 3, + SparseBsr = 4, + SparseBsc = 5, + _mkldnn = 6, + Strided = 7, +} + + +enum MemoryFormat { + Unknown = 0, + ContiguousFormat = 1, + ChannelsLast = 2, + ChannelsLast3d = 3, + PreserveFormat = 4, +} + + +enum ScalarType { + UNKNOWN = 0, + BYTE = 1, + CHAR = 2, + SHORT = 3, + INT = 4, + LONG = 5, + HALF = 6, + FLOAT = 7, + DOUBLE = 8, + COMPLEXHALF = 9, + COMPLEXFLOAT = 10, + COMPLEXDOUBLE = 11, + BOOL = 12, + BFLOAT16 = 13, + UINT16 = 28, + FLOAT8E4M3FN = 29, + FLOAT8E5M2 = 30, + FLOAT8E4M3FNUZ = 31, + FLOAT8E5M2FNUZ = 32, + FLOAT8E8M0FNU = 33, + UINT32 = 34, + UINT64 = 35, +} + + +struct Device { + 10: string type; + 20: optional i64 index; +} + +union SymExprHint { + 10: i64 as_int; + 20: bool as_bool; + 30: double as_float; +} + +struct SymExpr { + 10: string expr_str; + 20: optional SymExprHint hint; +} + +union SymInt { + 10: SymExpr as_expr; + 20: i64 as_int; +} + +union SymFloat { + 10: SymExpr as_expr; + 20: double as_float; +} + +union SymBool { + 10: SymExpr as_expr; + 20: bool as_bool; +} + +struct TensorMeta { + 10: ScalarType dtype; + 20: list sizes; + 30: bool requires_grad; + 40: Device device; + 50: list strides; + 60: SymInt storage_offset; + 70: Layout layout; +} + +union SymIntArgument { + 10: string as_name; + 20: i64 as_int; +} + +union SymFloatArgument { + 10: string as_name; + 20: double as_float; +} + +union SymBoolArgument { + 10: string as_name; + 20: bool as_bool; +} + +struct TensorArgument { + 10: string name; +} + +struct TokenArgument { + 10: string name; +} + +union OptionalTensorArgument { + 20: TensorArgument as_tensor; + 10: bool as_none; +} + +struct GraphArgument { + 10: string name; + 20: Graph graph; +} + +struct CustomObjArgument { + 10: string name; + 20: string class_fqn; +} + +struct ComplexValue { + 10: double real; + 20: double imag; +} + +union Argument { + 10: bool as_none; + 20: TensorArgument as_tensor; + 30: list as_tensors; + 50: i64 as_int; + 70: list as_ints; + 80: double as_float; + 90: list as_floats; + 100: string as_string; + 101: list as_strings; + 110: SymIntArgument as_sym_int; + 120: list as_sym_ints; + 130: ScalarType as_scalar_type; + 140: MemoryFormat as_memory_format; + 150: Layout as_layout; + 160: Device as_device; + 170: bool as_bool; + 180: list as_bools; + 182: SymBoolArgument as_sym_bool; + 184: list as_sym_bools; + 200: GraphArgument as_graph; + 190: list as_optional_tensors; + 210: CustomObjArgument as_custom_obj; + 220: string as_operator; + 230: SymFloatArgument as_sym_float; + 240: list as_sym_floats; + 250: OptionalTensorArgument as_optional_tensor; + 260: ComplexValue as_complex; + 270: list> as_nested_tensors; + 280: list> as_int_lists; + 290: map as_string_to_argument; + 300: list> as_float_lists; +} + +struct NamedArgument { + 10: string name; + 20: Argument arg; + 30: optional ArgumentKind kind; +} + +struct Node { + 10: string target; + 20: list inputs; + 30: list outputs; + 40: map metadata; + 50: optional bool is_hop_single_tensor_return; + 60: optional string name; +} + +struct Graph { + 10: list inputs; + 20: list outputs; + 30: list nodes; + 40: map tensor_values; + 50: map sym_int_values; + 60: map sym_bool_values; + 70: bool is_single_tensor_return; + 80: map custom_obj_values; + 90: map sym_float_values; +} + +struct UserInputSpec { + 10: Argument arg; +} + +union ConstantValue { + 10: bool as_none; + 20: i64 as_int; + 30: double as_float; + 40: string as_string; + 50: bool as_bool; +} + +struct InputToConstantInputSpec { + 10: string name; + 20: ConstantValue value; +} + +struct InputToParameterSpec { + 10: TensorArgument arg; + 20: string parameter_name; +} + +struct InputToBufferSpec { + 10: TensorArgument arg; + 20: string buffer_name; + 30: bool persistent; +} + +struct InputToTensorConstantSpec { + 10: TensorArgument arg; + 20: string tensor_constant_name; +} + +struct InputToCustomObjSpec { + 10: CustomObjArgument arg; + 20: string custom_obj_name; +} + +struct InputTokenSpec { + 10: TokenArgument arg; +} + +union InputSpec { + 10: UserInputSpec user_input; + 20: InputToParameterSpec parameter; + 30: InputToBufferSpec buffer; + 40: InputToTensorConstantSpec tensor_constant; + 50: InputToCustomObjSpec custom_obj; + 70: InputTokenSpec token; + 60: InputToConstantInputSpec constant_input; +} + +struct UserOutputSpec { + 10: Argument arg; +} + +struct LossOutputSpec { + 10: TensorArgument arg; +} + +struct BufferMutationSpec { + 10: TensorArgument arg; + 20: string buffer_name; +} + +struct ParameterMutationSpec { + 10: TensorArgument arg; + 20: string parameter_name; +} + +struct GradientToParameterSpec { + 10: TensorArgument arg; + 20: string parameter_name; +} + +struct GradientToUserInputSpec { + 10: TensorArgument arg; + 20: string user_input_name; +} + +struct UserInputMutationSpec { + 10: TensorArgument arg; + 20: string user_input_name; +} + +struct OutputTokenSpec { + 10: TokenArgument arg; +} + +union OutputSpec { + 10: UserOutputSpec user_output; + 20: LossOutputSpec loss_output; + 30: BufferMutationSpec buffer_mutation; + 40: GradientToParameterSpec gradient_to_parameter; + 50: GradientToUserInputSpec gradient_to_user_input; + 60: UserInputMutationSpec user_input_mutation; + 70: OutputTokenSpec token; + 80: ParameterMutationSpec parameter_mutation; +} + +struct GraphSignature { + 10: list input_specs; + 20: list output_specs; +} + +struct RangeConstraint { + 10: optional i64 min_val; + 20: optional i64 max_val; +} + +struct ModuleCallSignature { + 10: list inputs; + 20: list outputs; + 30: string in_spec; + 40: string out_spec; + 50: optional list forward_arg_names; +} + +struct ModuleCallEntry { + 10: string fqn; + 30: optional ModuleCallSignature signature; +} + +struct NamedTupleDef { + 10: list field_names; +} + +struct GraphModule { + 10: Graph graph; + 50: GraphSignature signature; + 60: list module_call_graph; + 40: map metadata; + 70: map treespec_namedtuple_fields; +} + +struct SchemaVersion { + 10: i64 major; + 20: i64 minor; +} + +struct ExportedProgram { + 10: GraphModule graph_module; + 20: map opset_version; + 30: map range_constraints; + 60: SchemaVersion schema_version; + 70: list verifiers; + 80: string torch_version; + 90: list guards_code; +} + +struct PayloadMeta { + 10: string path_name; + 20: bool is_param; + 30: bool use_pickle; + 40: optional TensorMeta tensor_meta; +} + +struct PayloadConfig { + 10: map config; +} + +struct AOTInductorModelPickleData { + 1: string library_basename; + 2: list input_names; + 3: list output_names; + 4: optional i64 floating_point_input_dtype; + 5: optional i64 floating_point_output_dtype; + 6: optional bool aot_inductor_model_is_cpu; +} + +struct ExternKernelNode { + 10: string name; + 20: Node node; +} + +struct ExternKernelNodes { + 10: list nodes; +} diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..1715a72511bb2d6140ca2ae3b7972e1d0f6a6ad0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.py @@ -0,0 +1,574 @@ +# NOTE: This is a placeholder for iterating on export serialization schema design. +# Anything is subject to change and no guarantee is provided at this point. + +from dataclasses import dataclass, field +from enum import IntEnum +from typing import Annotated + +from torch._export.serde.union import _Union, _union_dataclass + + +# NOTE: Please update this value if any modifications are made to the schema +SCHEMA_VERSION = (8, 20) +TREESPEC_VERSION = 1 + + +# NOTE: If you updated the schema, please run `scripts/export/update_schema.py` +# to update the auto generated files. +# +# There are also mappings from serialized enum values to c10 enum member names. +# These are used by scripts/export/update_schema.py to generate C++ conversion +# functions for oss_proxy_executor.cpp. +# When adding new enum values, update both the enum AND the mapping. +class ScalarType(IntEnum): + UNKNOWN = 0 + BYTE = 1 + CHAR = 2 + SHORT = 3 + INT = 4 + LONG = 5 + HALF = 6 + FLOAT = 7 + DOUBLE = 8 + COMPLEXHALF = 9 + COMPLEXFLOAT = 10 + COMPLEXDOUBLE = 11 + BOOL = 12 + BFLOAT16 = 13 + UINT16 = 28 + FLOAT8E4M3FN = 29 + FLOAT8E5M2 = 30 + FLOAT8E4M3FNUZ = 31 + FLOAT8E5M2FNUZ = 32 + FLOAT8E8M0FNU = 33 + UINT32 = 34 + UINT64 = 35 + + +class Layout(IntEnum): + Unknown = 0 + SparseCoo = 1 + SparseCsr = 2 + SparseCsc = 3 + SparseBsr = 4 + SparseBsc = 5 + _mkldnn = 6 + Strided = 7 + + +class MemoryFormat(IntEnum): + Unknown = 0 + ContiguousFormat = 1 + ChannelsLast = 2 + ChannelsLast3d = 3 + PreserveFormat = 4 + + +SCALAR_TYPE_TO_C10: dict[int, str] = { + ScalarType.BYTE: "Byte", + ScalarType.CHAR: "Char", + ScalarType.SHORT: "Short", + ScalarType.INT: "Int", + ScalarType.LONG: "Long", + ScalarType.HALF: "Half", + ScalarType.FLOAT: "Float", + ScalarType.DOUBLE: "Double", + ScalarType.COMPLEXHALF: "ComplexHalf", + ScalarType.COMPLEXFLOAT: "ComplexFloat", + ScalarType.COMPLEXDOUBLE: "ComplexDouble", + ScalarType.BOOL: "Bool", + ScalarType.BFLOAT16: "BFloat16", + ScalarType.UINT16: "UInt16", + ScalarType.FLOAT8E4M3FN: "Float8_e4m3fn", + ScalarType.FLOAT8E5M2: "Float8_e5m2", + ScalarType.FLOAT8E4M3FNUZ: "Float8_e4m3fnuz", + ScalarType.FLOAT8E5M2FNUZ: "Float8_e5m2fnuz", + ScalarType.FLOAT8E8M0FNU: "Float8_e8m0fnu", + ScalarType.UINT32: "UInt32", + ScalarType.UINT64: "UInt64", +} + +LAYOUT_TO_C10: dict[int, str] = { + Layout.SparseCoo: "Sparse", + Layout.SparseCsr: "SparseCsr", + Layout.SparseCsc: "SparseCsc", + Layout.SparseBsr: "SparseBsr", + Layout.SparseBsc: "SparseBsc", + Layout._mkldnn: "Mkldnn", + Layout.Strided: "Strided", +} + +MEMORY_FORMAT_TO_C10: dict[int, str] = { + MemoryFormat.ContiguousFormat: "Contiguous", + MemoryFormat.ChannelsLast: "ChannelsLast", + MemoryFormat.ChannelsLast3d: "ChannelsLast3d", + MemoryFormat.PreserveFormat: "Preserve", +} + + +@dataclass +class Device: + type: Annotated[str, 10] + index: Annotated[int | None, 20] = None + + +@_union_dataclass +class SymExprHint(_Union): + as_int: Annotated[int, 10] + as_bool: Annotated[bool, 20] + as_float: Annotated[float, 30] + + +# This is for storing the symbolic expressions behind symints/symfloats/symbools +# For example, we can get something like +# SymExpr(expr_str="s0 + s1", hint=SymExprHint(as_int=4) +# if we also have the hint that s0 and s1 are both 2. +@dataclass +class SymExpr: + expr_str: Annotated[str, 10] + hint: Annotated[SymExprHint | None, 20] = None + + +@_union_dataclass +class SymInt(_Union): + as_expr: Annotated[SymExpr, 10] + as_int: Annotated[int, 20] + + +@_union_dataclass +class SymFloat(_Union): + as_expr: Annotated[SymExpr, 10] + as_float: Annotated[float, 20] + + +@_union_dataclass +class SymBool(_Union): + as_expr: Annotated[SymExpr, 10] + as_bool: Annotated[bool, 20] + + +@dataclass +class TensorMeta: + dtype: Annotated[ScalarType, 10] + sizes: Annotated[list[SymInt], 20] + requires_grad: Annotated[bool, 30] + device: Annotated[Device, 40] + strides: Annotated[list[SymInt], 50] + storage_offset: Annotated[SymInt, 60] + layout: Annotated[Layout, 70] + + +# In most cases we will use the "as_name" field to store arguments which are +# SymInts. +# The "as_int" field is used in the case where we have a list containing a mix +# of SymInt and ints (ex. [1, s0, ...]). We will serialize this type of list to +# be List[SymIntArgument] and map the SymInts to the "as_name" field, and ints +# to the "as_int" field. +@_union_dataclass +class SymIntArgument(_Union): + as_name: Annotated[str, 10] + as_int: Annotated[int, 20] + + +# In most cases we will use the "as_name" field to store arguments which are +# SymFloats. +# The "as_float" field is used in the case where we have a list containing a mix +# of SymFloat and float (ex. [1.0, s0, ...]). We will serialize this type of list to +# be List[SymFloatArgument] and map the SymFloats to the "as_name" field, and ints +# to the "as_float" field. +@_union_dataclass +class SymFloatArgument(_Union): + as_name: Annotated[str, 10] + as_float: Annotated[float, 20] + + +# In most cases we will use the "as_name" field to store arguments which are +# SymBools. +# The "as_bool" field is used in the case where we have a list containing a mix +# of SymBool and bools (ex. [True, i0, ...]). We will serialize this type of list to +# be List[SymBoolArgument] and map the SymBools to the "as_name" field, and bools +# to the "as_bool" field. +@_union_dataclass +class SymBoolArgument(_Union): + as_name: Annotated[str, 10] + as_bool: Annotated[bool, 20] + + +@dataclass +class TensorArgument: + name: Annotated[str, 10] + + +@dataclass +class TokenArgument: + name: Annotated[str, 10] + + +# This is use for storing the contents of a list which contain optional tensors +# (Tensor?[], ex. [Tensor, None, ...]), where the list will be serialized to the +# type List[OptionalTensorArgument], with tensor values serialized to the +# "as_tensor" field, and None values serialized to the "as_none" field. +@_union_dataclass +class OptionalTensorArgument(_Union): + as_tensor: Annotated[TensorArgument, 20] + as_none: Annotated[bool, 10] + + +@dataclass +class GraphArgument: + name: Annotated[str, 10] + graph: Annotated["Graph", 20] + + +@dataclass +class CustomObjArgument: + name: Annotated[str, 10] + class_fqn: Annotated[str, 20] + + +@dataclass +class ComplexValue: + real: Annotated[float, 10] + imag: Annotated[float, 20] + + +# This is actually a union type +@_union_dataclass +class Argument(_Union): + as_none: Annotated[bool, 10] + as_tensor: Annotated[TensorArgument, 20] + as_tensors: Annotated[list[TensorArgument], 30] + as_int: Annotated[int, 50] + as_ints: Annotated[list[int], 70] + as_float: Annotated[float, 80] + as_floats: Annotated[list[float], 90] + as_string: Annotated[str, 100] + as_strings: Annotated[list[str], 101] + as_sym_int: Annotated[SymIntArgument, 110] + as_sym_ints: Annotated[list[SymIntArgument], 120] + as_scalar_type: Annotated[ScalarType, 130] + as_memory_format: Annotated[MemoryFormat, 140] + as_layout: Annotated[Layout, 150] + as_device: Annotated[Device, 160] + as_bool: Annotated[bool, 170] + as_bools: Annotated[list[bool], 180] + as_sym_bool: Annotated[SymBoolArgument, 182] + as_sym_bools: Annotated[list[SymBoolArgument], 184] + as_graph: Annotated[GraphArgument, 200] + as_optional_tensors: Annotated[list[OptionalTensorArgument], 190] + as_custom_obj: Annotated[CustomObjArgument, 210] + as_operator: Annotated[str, 220] + as_sym_float: Annotated[SymFloatArgument, 230] + as_sym_floats: Annotated[list[SymFloatArgument], 240] + as_optional_tensor: Annotated[OptionalTensorArgument, 250] + as_complex: Annotated[ComplexValue, 260] + as_nested_tensors: Annotated[list[list[TensorArgument]], 270] + as_int_lists: Annotated[list[list[int]], 280] + as_string_to_argument: Annotated[dict[str, "Argument"], 290] + as_float_lists: Annotated[list[list[float]], 300] + + +class ArgumentKind(IntEnum): + UNKNOWN = 0 + POSITIONAL = 1 + KEYWORD = 2 + + +@dataclass +class NamedArgument: + # Argument name from the operator schema + name: Annotated[str, 10] + arg: Annotated[Argument, 20] + kind: Annotated[ArgumentKind | None, 30] = None + + +@dataclass +class Node: + target: Annotated[str, 10] + inputs: Annotated[list[NamedArgument], 20] + outputs: Annotated[list[Argument], 30] + metadata: Annotated[dict[str, str], 40] + is_hop_single_tensor_return: Annotated[bool | None, 50] = None + # For BC, default is None so older serialized models without 'name' can be loaded. + name: Annotated[str | None, 60] = None + + +@dataclass +class Graph: + inputs: Annotated[list[Argument], 10] + outputs: Annotated[list[Argument], 20] + nodes: Annotated[list[Node], 30] + tensor_values: Annotated[dict[str, TensorMeta], 40] + sym_int_values: Annotated[dict[str, SymInt], 50] + sym_bool_values: Annotated[dict[str, SymBool], 60] + # This is for deserializing the submodule graphs from higher order ops + # (ex. cond, map) where single tensor returns will just return a single + # tensor, rather than following export schema and returning a singleton + # list. + is_single_tensor_return: Annotated[bool, 70] = False + custom_obj_values: Annotated[dict[str, CustomObjArgument], 80] = field( + default_factory=dict + ) + sym_float_values: Annotated[dict[str, SymFloat], 90] = field(default_factory=dict) + + +@dataclass +class UserInputSpec: + # Actually, only tensors and SymInts are allowed here + arg: Annotated[Argument, 10] + + +@_union_dataclass +class ConstantValue(_Union): + as_none: Annotated[bool, 10] + as_int: Annotated[int, 20] + as_float: Annotated[float, 30] + as_string: Annotated[str, 40] + as_bool: Annotated[bool, 50] + + +@dataclass +class InputToConstantInputSpec: + name: Annotated[str, 10] + value: Annotated[ConstantValue, 20] + + +@dataclass +class InputToParameterSpec: + arg: Annotated[TensorArgument, 10] + parameter_name: Annotated[str, 20] + + +@dataclass +class InputToBufferSpec: + arg: Annotated[TensorArgument, 10] + buffer_name: Annotated[str, 20] + persistent: Annotated[bool, 30] + + +@dataclass +class InputToTensorConstantSpec: + arg: Annotated[TensorArgument, 10] + tensor_constant_name: Annotated[str, 20] + + +@dataclass +class InputToCustomObjSpec: + arg: Annotated[CustomObjArgument, 10] + custom_obj_name: Annotated[str, 20] + + +@dataclass +class InputTokenSpec: + arg: Annotated[TokenArgument, 10] + + +@_union_dataclass +class InputSpec(_Union): + user_input: Annotated[UserInputSpec, 10] + parameter: Annotated[InputToParameterSpec, 20] + buffer: Annotated[InputToBufferSpec, 30] + tensor_constant: Annotated[InputToTensorConstantSpec, 40] + custom_obj: Annotated[InputToCustomObjSpec, 50] + token: Annotated[InputTokenSpec, 70] + constant_input: Annotated[InputToConstantInputSpec, 60] + + +@dataclass +class UserOutputSpec: + arg: Annotated[Argument, 10] + + +@dataclass +class LossOutputSpec: + arg: Annotated[TensorArgument, 10] + + +@dataclass +class BufferMutationSpec: + arg: Annotated[TensorArgument, 10] + buffer_name: Annotated[str, 20] + + +@dataclass +class ParameterMutationSpec: + arg: Annotated[TensorArgument, 10] + parameter_name: Annotated[str, 20] + + +@dataclass +class GradientToParameterSpec: + arg: Annotated[TensorArgument, 10] + parameter_name: Annotated[str, 20] + + +@dataclass +class GradientToUserInputSpec: + arg: Annotated[TensorArgument, 10] + user_input_name: Annotated[str, 20] + + +@dataclass +class UserInputMutationSpec: + arg: Annotated[TensorArgument, 10] + user_input_name: Annotated[str, 20] + + +@dataclass +class OutputTokenSpec: + arg: Annotated[TokenArgument, 10] + + +@_union_dataclass +class OutputSpec(_Union): + user_output: Annotated[UserOutputSpec, 10] + loss_output: Annotated[LossOutputSpec, 20] + buffer_mutation: Annotated[BufferMutationSpec, 30] + gradient_to_parameter: Annotated[GradientToParameterSpec, 40] + gradient_to_user_input: Annotated[GradientToUserInputSpec, 50] + user_input_mutation: Annotated[UserInputMutationSpec, 60] + token: Annotated[OutputTokenSpec, 70] + parameter_mutation: Annotated[ParameterMutationSpec, 80] + + +@dataclass +class GraphSignature: + input_specs: Annotated[list[InputSpec], 10] + output_specs: Annotated[list[OutputSpec], 20] + + +@dataclass +class RangeConstraint: + min_val: Annotated[int | None, 10] + max_val: Annotated[int | None, 20] + + +@dataclass +class ModuleCallSignature: + inputs: Annotated[list[Argument], 10] + outputs: Annotated[list[Argument], 20] + + # These are serialized by calling pytree.treespec_loads + # And deserialized by calling pytree.treespec_dumps + in_spec: Annotated[str, 30] + out_spec: Annotated[str, 40] + + # This field is used to prettify the graph placeholders + # after we Ser/Der and retrace + forward_arg_names: Annotated[list[str] | None, 50] = None + + +@dataclass +class ModuleCallEntry: + fqn: Annotated[str, 10] + signature: Annotated[ModuleCallSignature | None, 30] = None + + +@dataclass +class NamedTupleDef: + field_names: Annotated[list[str], 10] + + +@dataclass +class GraphModule: + graph: Annotated[Graph, 10] + signature: Annotated[GraphSignature, 50] + # This is used for unflattening, by tracking the calling structure of all of + # the modules in order to unflatten the modules back to the eager calling + # conventions. + module_call_graph: Annotated[list[ModuleCallEntry], 60] + metadata: Annotated[dict[str, str], 40] = field(default_factory=dict) + # Mapping of namedtuple types to namedtuple field names, used for BC + treespec_namedtuple_fields: Annotated[dict[str, NamedTupleDef], 70] = field( + default_factory=dict + ) + + +# Invariant: Every time a change is made to the schema, one of the versions +# should be updated. +@dataclass +class SchemaVersion: + major: Annotated[ + int, 10 + ] # Major version number is bumped every time a breaking change is made. + minor: Annotated[ + int, 20 + ] # Minor version number is bumped when a compatible change is made. + + +@dataclass +class ExportedProgram: + graph_module: Annotated[GraphModule, 10] + # Key is the opset namespace (ex. aten), and value is the version number + opset_version: Annotated[dict[str, int], 20] + range_constraints: Annotated[dict[str, RangeConstraint], 30] + schema_version: Annotated[SchemaVersion, 60] + verifiers: Annotated[list[str], 70] = field(default_factory=list) + torch_version: Annotated[str, 80] = "<=2.4" + guards_code: Annotated[list[str], 90] = field(default_factory=list) + + +######################################################################### +# Container types for inference tasks, not being used directly for export. +######################################################################### + + +# The metadata for payload saved in PT2 archive. +# payload includes params, buffers, tensor constants, and custom objects. +@dataclass +class PayloadMeta: + # the path of the payload in the archive file, e.g. "weight_0" + path_name: Annotated[str, 10] + is_param: Annotated[bool, 20] + # whether the payload is serialized using pickle. + # Only custom objects and tensor subclasses that are not fake tensors + # are serialized using pickle. + use_pickle: Annotated[bool, 30] + # Custom Objects don't have tensor_meta and will be serialized using pickle + tensor_meta: Annotated[TensorMeta | None, 40] + + +# The mapping from payload FQN to its metadata. +@dataclass +class PayloadConfig: + config: Annotated[dict[str, PayloadMeta], 10] + + +# +# The structure is used to serialize instances of AOTInductorModel to pass +# them from the publishing pipeline to the predictor. +# +# All new fields should be marked as optional. +# +@dataclass +class AOTInductorModelPickleData: + # Base name of an associated .so AOTInductor library. Typically looks like: + # "abc.so". + library_basename: Annotated[str, 1] + + # AOTInductor engine input names. + input_names: Annotated[list[str], 2] + + # AOTInductor engine output names. + output_names: Annotated[list[str], 3] + + # These fields tell whether floating point inputs/outputs should be converted to + # a certain type. If None, the dtypes that the AOTInductor engine inferred from the sample + # inputs are used. + floating_point_input_dtype: Annotated[int | None, 4] = None + floating_point_output_dtype: Annotated[int | None, 5] = None + + # Whether AOTInductor runtime is for CPU. + aot_inductor_model_is_cpu: Annotated[bool | None, 6] = None + + +@dataclass +class ExternKernelNode: + # name is not the unique identifier of the node + name: Annotated[str, 10] + node: Annotated[Node, 20] + + +@dataclass +class ExternKernelNodes: + nodes: Annotated[list[ExternKernelNode], 10] diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.yaml b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b9c4d3051a8779f77627b3e187c57e31fbf58be --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.yaml @@ -0,0 +1,569 @@ +# @generated by update_schema.py +# checksum<> +AOTInductorModelPickleData: + kind: struct + fields: + library_basename: + type: str + input_names: + type: List[str] + output_names: + type: List[str] + floating_point_input_dtype: + type: Optional[int] + default: None + floating_point_output_dtype: + type: Optional[int] + default: None + aot_inductor_model_is_cpu: + type: Optional[bool] + default: None +Argument: + kind: union + fields: + as_none: + type: bool + as_tensor: + type: TensorArgument + as_tensors: + type: List[TensorArgument] + as_int: + type: int + as_ints: + type: List[int] + as_float: + type: float + as_floats: + type: List[float] + as_string: + type: str + as_strings: + type: List[str] + as_sym_int: + type: SymIntArgument + as_sym_ints: + type: List[SymIntArgument] + as_scalar_type: + type: ScalarType + as_memory_format: + type: MemoryFormat + as_layout: + type: Layout + as_device: + type: Device + as_bool: + type: bool + as_bools: + type: List[bool] + as_sym_bool: + type: SymBoolArgument + as_sym_bools: + type: List[SymBoolArgument] + as_graph: + type: GraphArgument + as_optional_tensors: + type: List[OptionalTensorArgument] + as_custom_obj: + type: CustomObjArgument + as_operator: + type: str + as_sym_float: + type: SymFloatArgument + as_sym_floats: + type: List[SymFloatArgument] + as_optional_tensor: + type: OptionalTensorArgument + as_complex: + type: ComplexValue + as_nested_tensors: + type: List[List[TensorArgument]] + as_int_lists: + type: List[List[int]] + as_string_to_argument: + type: Dict[str, Argument] + as_float_lists: + type: List[List[float]] +ArgumentKind: + kind: enum + fields: + UNKNOWN: 0 + POSITIONAL: 1 + KEYWORD: 2 +BufferMutationSpec: + kind: struct + fields: + arg: + type: TensorArgument + buffer_name: + type: str +ComplexValue: + kind: struct + fields: + real: + type: float + imag: + type: float +ConstantValue: + kind: union + fields: + as_none: + type: bool + as_int: + type: int + as_float: + type: float + as_string: + type: str + as_bool: + type: bool +CustomObjArgument: + kind: struct + fields: + name: + type: str + class_fqn: + type: str +Device: + kind: struct + fields: + type: + type: str + index: + type: Optional[int] + default: None +ExportedProgram: + kind: struct + fields: + graph_module: + type: GraphModule + opset_version: + type: Dict[str, int] + range_constraints: + type: Dict[str, RangeConstraint] + schema_version: + type: SchemaVersion + verifiers: + type: List[str] + default: '[]' + torch_version: + type: str + default: <=2.4 + guards_code: + type: List[str] + default: '[]' +ExternKernelNode: + kind: struct + fields: + name: + type: str + node: + type: Node +ExternKernelNodes: + kind: struct + fields: + nodes: + type: List[ExternKernelNode] +GradientToParameterSpec: + kind: struct + fields: + arg: + type: TensorArgument + parameter_name: + type: str +GradientToUserInputSpec: + kind: struct + fields: + arg: + type: TensorArgument + user_input_name: + type: str +Graph: + kind: struct + fields: + inputs: + type: List[Argument] + outputs: + type: List[Argument] + nodes: + type: List[Node] + tensor_values: + type: Dict[str, TensorMeta] + sym_int_values: + type: Dict[str, SymInt] + sym_bool_values: + type: Dict[str, SymBool] + is_single_tensor_return: + type: bool + default: 'False' + custom_obj_values: + type: Dict[str, CustomObjArgument] + default: '{}' + sym_float_values: + type: Dict[str, SymFloat] + default: '{}' +GraphArgument: + kind: struct + fields: + name: + type: str + graph: + type: Graph +GraphModule: + kind: struct + fields: + graph: + type: Graph + signature: + type: GraphSignature + module_call_graph: + type: List[ModuleCallEntry] + metadata: + type: Dict[str, str] + default: '{}' + treespec_namedtuple_fields: + type: Dict[str, NamedTupleDef] + default: '{}' +GraphSignature: + kind: struct + fields: + input_specs: + type: List[InputSpec] + output_specs: + type: List[OutputSpec] +InputSpec: + kind: union + fields: + user_input: + type: UserInputSpec + parameter: + type: InputToParameterSpec + buffer: + type: InputToBufferSpec + tensor_constant: + type: InputToTensorConstantSpec + custom_obj: + type: InputToCustomObjSpec + token: + type: InputTokenSpec + constant_input: + type: InputToConstantInputSpec +InputToBufferSpec: + kind: struct + fields: + arg: + type: TensorArgument + buffer_name: + type: str + persistent: + type: bool +InputToConstantInputSpec: + kind: struct + fields: + name: + type: str + value: + type: ConstantValue +InputToCustomObjSpec: + kind: struct + fields: + arg: + type: CustomObjArgument + custom_obj_name: + type: str +InputToParameterSpec: + kind: struct + fields: + arg: + type: TensorArgument + parameter_name: + type: str +InputToTensorConstantSpec: + kind: struct + fields: + arg: + type: TensorArgument + tensor_constant_name: + type: str +InputTokenSpec: + kind: struct + fields: + arg: + type: TokenArgument +Layout: + kind: enum + fields: + Unknown: 0 + SparseCoo: 1 + SparseCsr: 2 + SparseCsc: 3 + SparseBsr: 4 + SparseBsc: 5 + _mkldnn: 6 + Strided: 7 +LossOutputSpec: + kind: struct + fields: + arg: + type: TensorArgument +MemoryFormat: + kind: enum + fields: + Unknown: 0 + ContiguousFormat: 1 + ChannelsLast: 2 + ChannelsLast3d: 3 + PreserveFormat: 4 +ModuleCallEntry: + kind: struct + fields: + fqn: + type: str + signature: + type: Optional[ModuleCallSignature] + default: None +ModuleCallSignature: + kind: struct + fields: + inputs: + type: List[Argument] + outputs: + type: List[Argument] + in_spec: + type: str + out_spec: + type: str + forward_arg_names: + type: Optional[List[str]] + default: None +NamedArgument: + kind: struct + fields: + name: + type: str + arg: + type: Argument + kind: + type: Optional[ArgumentKind] + default: None +NamedTupleDef: + kind: struct + fields: + field_names: + type: List[str] +Node: + kind: struct + fields: + target: + type: str + inputs: + type: List[NamedArgument] + outputs: + type: List[Argument] + metadata: + type: Dict[str, str] + is_hop_single_tensor_return: + type: Optional[bool] + default: None + name: + type: Optional[str] + default: None +OptionalTensorArgument: + kind: union + fields: + as_tensor: + type: TensorArgument + as_none: + type: bool +OutputSpec: + kind: union + fields: + user_output: + type: UserOutputSpec + loss_output: + type: LossOutputSpec + buffer_mutation: + type: BufferMutationSpec + gradient_to_parameter: + type: GradientToParameterSpec + gradient_to_user_input: + type: GradientToUserInputSpec + user_input_mutation: + type: UserInputMutationSpec + token: + type: OutputTokenSpec + parameter_mutation: + type: ParameterMutationSpec +OutputTokenSpec: + kind: struct + fields: + arg: + type: TokenArgument +ParameterMutationSpec: + kind: struct + fields: + arg: + type: TensorArgument + parameter_name: + type: str +PayloadConfig: + kind: struct + fields: + config: + type: Dict[str, PayloadMeta] +PayloadMeta: + kind: struct + fields: + path_name: + type: str + is_param: + type: bool + use_pickle: + type: bool + tensor_meta: + type: Optional[TensorMeta] +RangeConstraint: + kind: struct + fields: + min_val: + type: Optional[int] + max_val: + type: Optional[int] +ScalarType: + kind: enum + fields: + UNKNOWN: 0 + BYTE: 1 + CHAR: 2 + SHORT: 3 + INT: 4 + LONG: 5 + HALF: 6 + FLOAT: 7 + DOUBLE: 8 + COMPLEXHALF: 9 + COMPLEXFLOAT: 10 + COMPLEXDOUBLE: 11 + BOOL: 12 + BFLOAT16: 13 + UINT16: 28 + FLOAT8E4M3FN: 29 + FLOAT8E5M2: 30 + FLOAT8E4M3FNUZ: 31 + FLOAT8E5M2FNUZ: 32 + FLOAT8E8M0FNU: 33 + UINT32: 34 + UINT64: 35 +SchemaVersion: + kind: struct + fields: + major: + type: int + minor: + type: int +SymBool: + kind: union + fields: + as_expr: + type: SymExpr + as_bool: + type: bool +SymBoolArgument: + kind: union + fields: + as_name: + type: str + as_bool: + type: bool +SymExpr: + kind: struct + fields: + expr_str: + type: str + hint: + type: Optional[SymExprHint] + default: None +SymExprHint: + kind: union + fields: + as_int: + type: int + as_bool: + type: bool + as_float: + type: float +SymFloat: + kind: union + fields: + as_expr: + type: SymExpr + as_float: + type: float +SymFloatArgument: + kind: union + fields: + as_name: + type: str + as_float: + type: float +SymInt: + kind: union + fields: + as_expr: + type: SymExpr + as_int: + type: int +SymIntArgument: + kind: union + fields: + as_name: + type: str + as_int: + type: int +TensorArgument: + kind: struct + fields: + name: + type: str +TensorMeta: + kind: struct + fields: + dtype: + type: ScalarType + sizes: + type: List[SymInt] + requires_grad: + type: bool + device: + type: Device + strides: + type: List[SymInt] + storage_offset: + type: SymInt + layout: + type: Layout +TokenArgument: + kind: struct + fields: + name: + type: str +UserInputMutationSpec: + kind: struct + fields: + arg: + type: TensorArgument + user_input_name: + type: str +UserInputSpec: + kind: struct + fields: + arg: + type: Argument +UserOutputSpec: + kind: struct + fields: + arg: + type: Argument +SCHEMA_VERSION: +- 8 +- 20 +TREESPEC_VERSION: 1 diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/schema_check.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema_check.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9d94b876f1873549c1a7699ed9e59a3ddd2573 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema_check.py @@ -0,0 +1,927 @@ +import dataclasses +import hashlib +import inspect +import re +import types +import typing +from enum import IntEnum +from typing import Annotated, Any, ForwardRef, Union + +from torch._export.serde import schema +from torch._export.serde.union import _Union + + +class SchemaUpdateError(Exception): + pass + + +def _check(x: object, msg: str) -> None: + if not x: + raise SchemaUpdateError(msg) + + +_CPP_TYPE_MAP = { + str: "std::string", + int: "int64_t", + float: "F64", + bool: "bool", +} + +_THRIFT_TYPE_MAP = { + str: "string", + int: "i64", + float: "double", + bool: "bool", +} + + +def _staged_schema() -> tuple[dict[str, Any], str, str]: + yaml_ret: dict[str, Any] = {} + defs: dict[str, Any] = {} + cpp_enum_defs: dict[str, str] = {} + cpp_class_defs: dict[str, str] = {} + cpp_type_decls: list[str] = [] + cpp_json_defs: list[str] = [] + thrift_enum_defs: list[str] = [] + thrift_type_defs: dict[str, str] = {} + + def _handle_aggregate( + ty: type[Any], + ) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: + def dump_type(t: Any, level: int) -> tuple[str, str, str]: + if getattr(t, "__name__", None) in cpp_enum_defs: + return t.__name__, "int64_t", t.__name__ + elif t in _CPP_TYPE_MAP: + return (t.__name__, _CPP_TYPE_MAP[t], _THRIFT_TYPE_MAP[t]) + elif isinstance(t, str): + if t not in defs: + raise AssertionError(f"type {t} not in defs") + if t in cpp_enum_defs: + raise AssertionError(f"type {t} unexpectedly in cpp_enum_defs") + if "[" in t: + raise AssertionError(f"type {t} contains '[' which is not allowed") + return t, f"ForwardRef<{t}>", t + elif isinstance(t, ForwardRef): + return ( + t.__forward_arg__, + f"ForwardRef<{t.__forward_arg__}>", + t.__forward_arg__, + ) + elif o := typing.get_origin(t): + # Lemme know if there's a better way to do this. + if o is list: + yaml_head, cpp_head, thrift_head, thrift_tail = ( + "List", + "std::vector", + "list<", + ">", + ) + elif o is dict: + yaml_head, cpp_head, thrift_head, thrift_tail = ( + "Dict", + "std::unordered_map", + "map<", + ">", + ) + elif o is Union or o is types.UnionType: + if level != 0: + raise AssertionError( + f"Optional is only supported at the top level, got level={level}" + ) + args = typing.get_args(t) + if len(args) != 2 or args[1] is not type(None): + raise AssertionError( + f"expected Optional type with 2 args ending in None, got {args}" + ) + yaml_type, cpp_type, thrift_type = dump_type(args[0], level + 1) + return ( + f"Optional[{yaml_type}]", + f"std::optional<{cpp_type}>", + f"optional {thrift_type}", + ) + elif o is Annotated: + return dump_type(t.__origin__, level) + else: + raise AssertionError(f"Type {t} is not supported in export schema.") + yaml_arg_types, cpp_arg_types, thrift_arg_types = zip( + *[dump_type(x, level + 1) for x in typing.get_args(t)] + ) + return ( + (f"{yaml_head}[{', '.join(yaml_arg_types)}]"), + (f"{cpp_head}<{', '.join(cpp_arg_types)}>"), + f"{thrift_head}{', '.join(thrift_arg_types)}{thrift_tail}", + ) + elif isinstance(t, type): + return (t.__name__, t.__name__, t.__name__) + else: + raise AssertionError(f"Type {t} is not supported in export schema.") + + def dump_cpp_value(v: object) -> str: + if v is None: + return "std::nullopt" + elif v is True: + return "true" + elif v is False: + return "false" + elif v == {}: + return "{}" + elif v == []: + return "{}" + elif v == (): + return "{}" + elif isinstance(v, str): + return f'"{v}"' + else: + raise AssertionError( + f"Default value {v} is not supported yet in export schema." + ) + + def dump_field( + f: dataclasses.Field[Any], + ) -> tuple[dict[str, Any], str, str | None, str, int]: + t, cpp_type, thrift_type = dump_type(f.type, 0) + ret = {"type": t} + cpp_default: str | None = None + if typing.get_origin(f.type) is not Annotated: + raise AssertionError( + f"Field {f.name} must be annotated with an integer id." + ) + # pyrefly: ignore[missing-attribute] # TODO f.type is an Annotated alias at runtime, not str + thrift_id = f.type.__metadata__[0] + if type(thrift_id) is not int: + raise AssertionError( + f"Field {f.name} must be annotated with an integer id, got {type(thrift_id)}" + ) + + value = dataclasses.MISSING + if f.default is not dataclasses.MISSING: + value = f.default + elif f.default_factory is not dataclasses.MISSING: + value = f.default_factory() + + if value is not dataclasses.MISSING: + default = str(value) + ret["default"] = default + cpp_default = dump_cpp_value(value) + + if t.startswith("Optional[") and value is not None: + raise AssertionError( + f"Optional field {ty.__name__}.{f.name} must have default value to be None." + ) + + # Skip emitting "= {}" for non-primitive types whose + # default-construction already yields the same empty value + # (containers, strings, classes). Emitting it would trigger + # readability-redundant-member-init. Keep it for primitives + # (int64_t, bool, F64) which require explicit value-init. + if cpp_default == "{}" and cpp_type not in ("int64_t", "bool", "F64"): + cpp_default = None + elif cpp_type in ("int64_t", "bool", "F64"): + # Value-initialize primitive/enum members (enums map to int64_t) + # to satisfy cppcoreguidelines-pro-type-member-init. Non-primitive + # types (std::string, containers, classes) default-construct + # themselves; emitting "= {}" for those would trigger + # readability-redundant-member-init. + cpp_default = "{}" + + return ret, cpp_type, cpp_default, thrift_type, thrift_id + + yaml_ret = {} + cpp_ret = {} + thrift_ret = {} + thrift_ids = set() + for f in dataclasses.fields(ty): + yaml_res, cpp_type, cpp_default, thrift_type, thrift_id = dump_field(f) + yaml_ret[f.name] = yaml_res + cpp_ret[f.name] = {"cpp_type": cpp_type, "cpp_default": cpp_default} + thrift_ret[f.name] = {"thrift_type": thrift_type, "thrift_id": thrift_id} + if thrift_id in thrift_ids: + raise AssertionError( + f"Duplicate thrift id {thrift_id} for field {f.name} in {ty.__name__}." + ) + thrift_ids.add(thrift_id) + return yaml_ret, cpp_ret, thrift_ret + + def _handle_int_enum(name: str, ty: type[IntEnum]) -> None: + yaml_ret[name] = {"kind": "enum", "fields": {x.name: x.value for x in ty}} + cpp_enum_defs[name] = f""" +enum class {name} {{ +{chr(10).join([f" {x.name} = {x.value}," for x in ty])} +}}; + +inline std::string_view printEnum(const {name}& e) {{ + switch (e) {{ +{chr(10).join([f" case {name}::{x.name}: return {chr(34)}{x.name}{chr(34)};" for x in ty])} + default: + throw std::runtime_error("Unknown enum value"); + }} +}} + +inline void parseEnum(std::string_view s, {name}& t) {{ +{chr(10).join([f" if (s == {chr(34)}{x.name}{chr(34)}) {{ t = {name}::{x.name}; return; }}" for x in ty])} + throw std::runtime_error("Unknown enum value: " + std::string{{s}}); +}} +""" + thrift_enum_defs.append( + f""" +enum {name} {{ +{chr(10).join([f" {x.name} = {x.value}," for x in ty])} +}} +""" + ) + + def _handle_struct(name: str, ty: type[Any]) -> None: + fields, cpp_fields, thrift_fields = _handle_aggregate(ty) + yaml_ret[name] = {"kind": "struct", "fields": fields} + field_decls = "\n".join( + f" {f['cpp_type']} {name}{' = ' + f['cpp_default'] if f['cpp_default'] is not None else ''};" + for name, f in cpp_fields.items() + ) + + def accessor(name: str, ty: str) -> str: + type_name = fields[name]["type"] + if type_name in cpp_enum_defs: + return f""" + {type_name} get_{name}() const {{ + return static_cast<{type_name}>({name}); + }} + + void set_{name}({type_name} def) {{ + {name} = static_cast(def); + }} +""" + return f""" + const {ty}& get_{name}() const {{ + return {name}; + }} + + template + void set_{name}(U&& def) {{ + {name} = std::forward(def); + }} +""" + + to_json_decl = f"void to_json(nlohmann::json& nlohmann_json_j, const {name}& nlohmann_json_t)" + to_json_def = f"""{{ +{chr(10).join([f' nlohmann_json_j["{name}"] = nlohmann_json_t.{name};' for name in cpp_fields])} +}} +""" + from_json_decl = f"void from_json(const nlohmann::json& nlohmann_json_j, {name}& nlohmann_json_t)" + + from_json_def = f"""{{ + {name} nlohmann_json_default_obj; +{ + chr(10).join( + [ + f' nlohmann_json_t.{name} = nlohmann_json_j.value("{name}", nlohmann_json_default_obj.{name});' + for name in cpp_fields + ] + ) + } +}} +""" + cpp_class_defs[name] = f""" +class {name} {{ + private: +{field_decls} + + public: +{"".join([accessor(name, f["cpp_type"]) for name, f in cpp_fields.items()])} + friend {to_json_decl}; + friend {from_json_decl}; +}}; +""" + cpp_json_defs.append(f"inline {to_json_decl} {to_json_def}") + cpp_json_defs.append(f"inline {from_json_decl} {from_json_def}") + cpp_type_decls.append(f"class {name};") + + thrift_type_defs[name] = f""" +struct {name} {{ +{chr(10).join(f" {f['thrift_id']}: {f['thrift_type']} {n};" for n, f in thrift_fields.items())} +}}""" + + def _handle_union(name: str, ty: type[Any]) -> None: + fields, cpp_fields, thrift_fields = _handle_aggregate(ty) + yaml_ret[name] = {"kind": "union", "fields": fields} + + def accessor(name: str, ty: str, idx: int) -> str: + return f""" + const {ty}& get_{name}() const {{ + return std::get<{idx + 1}>(variant_); + }} + + template + void set_{name}(U&& def) {{ + variant_.emplace<{idx + 1}>(std::forward(def)); + tag_ = Tag::{name.upper()}; + }} +""" + + to_json_branches = "".join( + [ + f""" + if (nlohmann_json_t.tag_ == Tag::{name.upper()}) {{ + nlohmann_json_j["{name}"] = nlohmann_json_t.get_{name}(); + return; + }}""" + for idx, (name, f) in enumerate(cpp_fields.items()) + ] + ) + from_json_branches = "".join( + [ + f""" + if (nlohmann_json_j.contains("{name}")) {{ + nlohmann_json_t.variant_.emplace<{idx + 1}>(nlohmann_json_j.at("{name}").template get<{f["cpp_type"]}>()); + nlohmann_json_t.tag_ = Tag::{name.upper()}; + return; + }}""" + for idx, (name, f) in enumerate(cpp_fields.items()) + ] + ) + + cpp_class_defs[name] = f""" +class {name} {{ + struct Void {{}}; + + public: + enum class Tag {{ + {", ".join([name.upper() for name in cpp_fields])} + }}; + + private: + std::variant variant_; + Tag tag_{{}}; + + public: + Tag tag() const {{ + return tag_; + }} +{"".join([accessor(name, f["cpp_type"], idx) for idx, (name, f) in enumerate(cpp_fields.items())])} + friend void to_json(nlohmann::json& nlohmann_json_j, const {name}& nlohmann_json_t) {{ +{to_json_branches} + }} + + friend void from_json(const nlohmann::json& nlohmann_json_j, {name}& nlohmann_json_t) {{ +{from_json_branches} + }} +}}; + +inline std::string_view printEnum(const {name}::Tag& e) {{ + switch (e) {{ +{chr(10).join([f" case {name}::Tag::{x.upper()}: return {chr(34)}{x.upper()}{chr(34)};" for x in cpp_fields])} + default: + throw std::runtime_error("Unknown enum value"); + }} +}} + +inline void parseEnum(std::string_view s, {name}::Tag& t) {{ +{chr(10).join([f" if (s == {chr(34)}{x.upper()}{chr(34)}) {{ t = {name}::Tag::{x.upper()}; return; }}" for x in cpp_fields])} + throw std::runtime_error("Unknown enum value: " + std::string{{s}}); +}} + +""" + cpp_type_decls.append(f"class {name};") + + thrift_type_defs[name] = f""" +union {name} {{ +{chr(10).join(f" {f['thrift_id']}: {f['thrift_type']} {n};" for n, f in thrift_fields.items())} +}}""" + + for name in dir(schema): + if name.startswith("_"): + continue + + value = getattr(schema, name) + + if hasattr(value, "__module__") and value.__module__ != schema.__name__: + continue + + defs[name] = value + + class_ordering = {} + for name, value in defs.items(): + if isinstance(value, type): + if issubclass(value, IntEnum): + _handle_int_enum(name, value) + elif dataclasses.is_dataclass(value): + class_ordering[name] = inspect.findsource(value)[1] + if issubclass(value, _Union): + _handle_union(name, value) + else: + _handle_struct(name, value) + else: + raise AssertionError(f"Unknown schema type {name}: {value}") + elif isinstance(value, (int, tuple)): + if name not in ("SCHEMA_VERSION", "TREESPEC_VERSION"): + raise AssertionError( + f"expected SCHEMA_VERSION or TREESPEC_VERSION, got {name}" + ) + elif isinstance(value, dict): + # Skip mapping dictionaries used for codegen + pass + else: + raise AssertionError(f"Unknown variable {name}: {value}") + + yaml_ret["SCHEMA_VERSION"] = list(defs["SCHEMA_VERSION"]) + if not all(x > 0 for x in yaml_ret["SCHEMA_VERSION"]): + raise AssertionError( + f"all SCHEMA_VERSION values must be > 0, got {yaml_ret['SCHEMA_VERSION']}" + ) + yaml_ret["TREESPEC_VERSION"] = defs["TREESPEC_VERSION"] + if yaml_ret["TREESPEC_VERSION"] <= 0: + raise AssertionError( + f"TREESPEC_VERSION must be > 0, got {yaml_ret['TREESPEC_VERSION']}" + ) + + cpp_header = f""" +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann {{ +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END }} +#endif + +// https://github.com/nlohmann/json/pull/2117 +NLOHMANN_JSON_NAMESPACE_BEGIN +template +struct adl_serializer> {{ + static void to_json(json& j, const std::optional& opt) {{ + if (opt == std::nullopt) {{ + j = nullptr; + }} else {{ + j = *opt; // this will call adl_serializer::to_json which will + // find the free function to_json in T's namespace! + }} + }} + + static void from_json(const json& j, std::optional& opt) {{ + if (j.is_null()) {{ + opt = std::nullopt; + }} else {{ + opt = j.template get(); // same as above, but with + // adl_serializer::from_json + }} + }} +}}; +NLOHMANN_JSON_NAMESPACE_END + +namespace torch::_export {{ + +template +class ForwardRef {{ + static_assert(!std::is_reference_v, "ForwardRef cannot be a reference type"); + + public: + ForwardRef(): ptr_(std::make_unique()) {{}} + ForwardRef(ForwardRef&&) noexcept; + ForwardRef(const ForwardRef& other): ptr_(std::make_unique(*other.ptr_)) {{}} + ForwardRef& operator=(ForwardRef&&) noexcept; + ForwardRef& operator=(const ForwardRef& other) {{ + ptr_ = std::make_unique(*other.ptr_); + return *this; + }} + ~ForwardRef(); + const T& operator*() const {{ + return *ptr_; + }} + + const T* operator->() const {{ + return ptr_.get(); + }} + + void emplace(T&& t) {{ + ptr_ = std::make_unique(std::move(t)); + }} + + private: + std::unique_ptr ptr_; +}}; + +template +void to_json(nlohmann::json& j, const ForwardRef& p) {{ + j = *p; +}} + +template +void from_json(const nlohmann::json& j, ForwardRef& p) {{ + p.emplace(j.template get()); +}} + +class F64 {{ + public: + double get() const {{ + return value_; + }} + + void set(double value) {{ + value_ = value; + }} + + private: + double value_{{}}; +}}; + +inline void to_json(nlohmann::json& j, const F64& f) {{ + if (std::isinf(f.get())) {{ + j = "Infinity"; + }} else if (std::isinf(-f.get())) {{ + j = "-Infinity"; + }} else if (std::isnan(f.get())) {{ + j = "NaN"; + }} else {{ + j = f.get(); + }} +}} + +inline void from_json(const nlohmann::json& j, F64& f) {{ + if (j == "Infinity") {{ + f.set(std::numeric_limits::infinity()); + }} else if (j == "-Infinity") {{ + f.set(-std::numeric_limits::infinity()); + }} else if (j == "NaN") {{ + f.set(std::numeric_limits::quiet_NaN()); + }} else {{ + f.set(j.get()); + }} +}} + +{chr(10).join(cpp_type_decls)} +{"".join(cpp_enum_defs.values())} +{"".join(dict(sorted(cpp_class_defs.items(), key=lambda x: class_ordering[x[0]])).values())} +{chr(10).join(cpp_json_defs)} + +template ForwardRef::ForwardRef(ForwardRef&&) noexcept = default; +template ForwardRef& ForwardRef::operator=(ForwardRef&&) noexcept = default; +template ForwardRef::~ForwardRef() = default; +}} // namespace torch::_export +""" + thrift_schema = f""" +namespace py3 torch._export +namespace cpp2 torch._export.schema +{chr(10).join(thrift_enum_defs)} +{chr(10).join(dict(sorted(thrift_type_defs.items(), key=lambda x: class_ordering[x[0]])).values())} +""" + return yaml_ret, cpp_header, thrift_schema + + +def _diff_schema( + dst: dict[str, Any], src: dict[str, Any] +) -> tuple[dict[str, Any], dict[str, Any]]: + additions = {key: src[key] for key in src.keys() - dst.keys()} + subtractions = {key: dst[key] for key in dst.keys() - src.keys()} + + common_keys = src.keys() & dst.keys() + + versions = {"SCHEMA_VERSION", "TREESPEC_VERSION"} + common_keys -= versions + + for key in common_keys: + src_kind = src[key]["kind"] + src_fields = src[key]["fields"] + dst_kind = dst[key]["kind"] + dst_fields = dst[key]["fields"] + _check( + src_kind == dst_kind, + f"Type {key} changed kind from {dst_kind} to {src_kind}", + ) + if not isinstance(src_fields, dict) or not isinstance(dst_fields, dict): + raise AssertionError( + f"expected dict fields, got src={type(src_fields)}, dst={type(dst_fields)}" + ) + added_fields = { + key: src_fields[key] for key in src_fields.keys() - dst_fields.keys() + } + subtracted_fields = { + key: dst_fields[key] for key in dst_fields.keys() - src_fields.keys() + } + common_fields = src_fields.keys() & dst_fields.keys() + + for field in common_fields: + src_field = src_fields[field] + dst_field = dst_fields[field] + if src_kind == "struct": + _check( + src_field["type"] == dst_field["type"], + f"Type of the field {key}.{field} changed from {dst_field['type']} to {src_field['type']}", + ) + if "default" in src_field and "default" not in dst_field: + added_fields[field] = {} + added_fields[field]["default"] = src_field["default"] + if "default" not in src_field and "default" in dst_field: + subtracted_fields[field] = {} + subtracted_fields[field]["default"] = dst_field["default"] + elif src_kind == "enum": + _check( + src_field == dst_field, + f"Value of the enum field {key}.{field} changed from {dst_field} to {src_field}", + ) + elif src_kind == "union": + _check( + src_field["type"] == dst_field["type"], + f"Type of the field {key}.{field} changed from {dst_field['type']} to {src_field['type']}", + ) + else: + raise AssertionError(f"Unknown kind {src_kind}: {key}") + if len(added_fields) > 0: + if key in additions: + raise AssertionError(f"key {key} already in additions") + additions[key] = {} + additions[key]["fields"] = added_fields + if len(subtracted_fields) > 0: + if key in subtractions: + raise AssertionError(f"key {key} already in subtractions") + subtractions[key] = {} + subtractions[key]["fields"] = subtracted_fields + + return additions, subtractions + + +def _hash_content(s: str) -> str: + return hashlib.sha256(s.strip().encode("utf-8")).hexdigest() + + +def _generate_enum_converters() -> str: + """Generate C++ converter functions from serialized enum values to c10 enums.""" + + def validate_mapping( + enum_class: type[IntEnum], + mapping: dict[int, str], + enum_name: str, + skip_values: set[int], + ) -> None: + """Validate that all enum values have corresponding c10 mappings.""" + for member in enum_class: + if member.value in skip_values: + continue + if member.value not in mapping: + raise SchemaUpdateError( + f"{enum_name}.{member.name} (value={member.value}) is missing " + f"from {enum_name.upper()}_TO_C10 mapping in schema.py. " + f"Please add the mapping to the c10 enum name." + ) + + # Validate that all enum values have mappings (except UNKNOWN values) + validate_mapping( + schema.ScalarType, + schema.SCALAR_TYPE_TO_C10, + "ScalarType", + {schema.ScalarType.UNKNOWN}, + ) + validate_mapping( + schema.Layout, + schema.LAYOUT_TO_C10, + "Layout", + {schema.Layout.Unknown}, + ) + validate_mapping( + schema.MemoryFormat, + schema.MEMORY_FORMAT_TO_C10, + "MemoryFormat", + {schema.MemoryFormat.Unknown}, + ) + + def generate_converter( + name: str, + c10_type: str, + mapping: dict[int, str], + max_value: int, + ) -> str: + lines: list[str] = [] + for i in range(max_value + 1): + if i in mapping: + lines.append( + f" static_cast(c10::{c10_type}::{mapping[i]}), // {i}" + ) + else: + lines.append(f" kInvalid, // {i}") + + return f""" +inline c10::{c10_type} convertSerialized{name}(int serialized_value) {{ + constexpr int kInvalid = -1; + constexpr int k{name}Map[] = {{ +{chr(10).join(lines)} + }}; + constexpr int kMapSize = sizeof(k{name}Map) / sizeof(k{name}Map[0]); + + TORCH_CHECK( + serialized_value >= 0 && serialized_value < kMapSize, + "Serialized {name} value out of range: ", + serialized_value); + int result = k{name}Map[serialized_value]; + TORCH_CHECK( + result != kInvalid, + "Invalid serialized {name} value: ", + serialized_value); + return static_cast(result); +}} +""" + + scalar_type_converter = generate_converter( + "ScalarType", + "ScalarType", + schema.SCALAR_TYPE_TO_C10, + max(schema.SCALAR_TYPE_TO_C10.keys()), + ) + layout_converter = generate_converter( + "Layout", + "Layout", + schema.LAYOUT_TO_C10, + max(schema.LAYOUT_TO_C10.keys()), + ) + memory_format_converter = generate_converter( + "MemoryFormat", + "MemoryFormat", + schema.MEMORY_FORMAT_TO_C10, + max(schema.MEMORY_FORMAT_TO_C10.keys()), + ) + + return f""" +#pragma once + +#include +#include +#include +#include + +// Converter functions from serialized enum values (torch._export.serde.schema) +// to c10 enums. The serialized format has different enum values than c10. + +namespace torch::aot_inductor {{ +{scalar_type_converter} +{layout_converter} +{memory_format_converter} +}} // namespace torch::aot_inductor +""" + + +@dataclasses.dataclass +class _Commit: + result: dict[str, Any] + checksum_next: str + yaml_path: str + additions: dict[str, Any] + subtractions: dict[str, Any] + base: dict[str, Any] + checksum_head: str | None + cpp_header: str + cpp_header_path: str + enum_converter_header: str + enum_converter_header_path: str + thrift_checksum_head: str | None + thrift_checksum_real: str | None + thrift_checksum_next: str + thrift_schema: str + thrift_schema_path: str + + +def update_schema() -> _Commit: + import importlib.resources + + dst: dict[str, Any] + # pyrefly: ignore [bad-argument-type] + if importlib.resources.is_resource(__package__, "schema.yaml"): + # pyrefly: ignore [bad-argument-type] + content = importlib.resources.read_text(__package__, "schema.yaml") + match = re.search("checksum<<([A-Fa-f0-9]{64})>>", content) + _check(match is not None, "checksum not found in schema.yaml") + if match is None: + raise AssertionError("checksum not found in schema.yaml") + checksum_head = match.group(1) + + thrift_content = importlib.resources.read_text( + # pyrefly: ignore [bad-argument-type] + __package__, + "export_schema.thrift", + ) + match = re.search("checksum<<([A-Fa-f0-9]{64})>>", thrift_content) + _check(match is not None, "checksum not found in export_schema.thrift") + if match is None: + raise AssertionError("checksum not found in export_schema.thrift") + thrift_checksum_head = match.group(1) + thrift_content = thrift_content.splitlines() + if not thrift_content[0].startswith("// @" + "generated"): + raise AssertionError( + f"expected first line to start with '// @generated', got {thrift_content[0]!r}" + ) + if not thrift_content[1].startswith("// checksum<<"): + raise AssertionError( + f"expected second line to start with '// checksum<<', got {thrift_content[1]!r}" + ) + thrift_checksum_real = _hash_content("\n".join(thrift_content[2:])) + + from yaml import load, Loader + + dst = load(content, Loader=Loader) + if not isinstance(dst, dict): + raise AssertionError(f"expected dict from yaml, got {type(dst)}") + else: + checksum_head = None + thrift_checksum_head = None + thrift_checksum_real = None + dst = {"SCHEMA_VERSION": None, "TREESPEC_VERSION": None} + + src, cpp_header, thrift_schema = _staged_schema() + enum_converter_header = _generate_enum_converters() + additions, subtractions = _diff_schema(dst, src) + # pyrefly: ignore [missing-attribute] + yaml_path = __package__.replace(".", "/") + "/schema.yaml" + # pyrefly: ignore [missing-attribute] + thrift_schema_path = __package__.replace(".", "/") + "/export_schema.thrift" + torch_prefix = "torch/" + if not yaml_path.startswith(torch_prefix): + raise AssertionError( + f"yaml_path must start with {torch_prefix}, got {yaml_path}" + ) + if not thrift_schema_path.startswith(torch_prefix): + raise AssertionError( + f"thrift_schema_path must start with {torch_prefix}, got {thrift_schema_path}" + ) + + return _Commit( + result=src, + checksum_next=_hash_content(repr(src)), + yaml_path=yaml_path, + additions=additions, + subtractions=subtractions, + base=dst, + checksum_head=checksum_head, + cpp_header=cpp_header, + cpp_header_path=torch_prefix + "csrc/utils/generated_serialization_types.h", + enum_converter_header=enum_converter_header, + enum_converter_header_path=torch_prefix + + "csrc/inductor/aoti_torch/generated_enum_converters.h", + thrift_checksum_head=thrift_checksum_head, + thrift_checksum_real=thrift_checksum_real, + thrift_checksum_next=_hash_content(thrift_schema), + thrift_schema=thrift_schema, + thrift_schema_path=thrift_schema_path, + ) + + +def check(commit: _Commit, force_unsafe: bool = False) -> tuple[list[int] | None, str]: + next_version: list[int] | None = None + reason = "" + # Step 1: Detect major schema updates. + if len(commit.additions) > 0: + for k, v in commit.additions.items(): + if k not in commit.base: + continue + kind = commit.result[k]["kind"] + fields = v["fields"] + for f, d in fields.items(): + if kind == "struct" and "default" not in d: + reason += ( + f"Field {k}.{f} is added to schema.py without a default value as an incompatible change " + + "which requires major version bump.\n" + ) + next_version = [commit.base["SCHEMA_VERSION"][0] + 1, 1] + + if len(commit.subtractions) > 0: + for k, v in commit.subtractions.items(): + if k not in commit.result: + continue + for f in v["fields"]: + reason = f"Field {k}.{f} is removed from schema.py as an incompatible change which requires major version bump.\n" + next_version = [commit.base["SCHEMA_VERSION"][0] + 1, 1] + + if force_unsafe: + reason += "--force-unsafe is used." + next_version = commit.result["SCHEMA_VERSION"] + else: + # Step 2: Detect minor schema updates. + if next_version is None and len(commit.additions) > 0: + for k, v in commit.additions.items(): + for f in v["fields"]: + reason += ( + f"Field {k}.{f} is added to schema.py as a compatible change " + + "which still requires minor version bump.\n" + ) + next_version = [ + commit.base["SCHEMA_VERSION"][0], + commit.base["SCHEMA_VERSION"][1] + 1, + ] + if next_version is None and len(commit.subtractions) > 0: + for k, v in commit.subtractions.items(): + for f in v["fields"]: + reason += ( + f"Field {k}.{f} is removed from schema.py as a compatible change " + + "which still requires minor version bump.\n" + ) + next_version = [ + commit.base["SCHEMA_VERSION"][0], + commit.base["SCHEMA_VERSION"][1] + 1, + ] + + return next_version, reason diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/serialize.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/serialize.py new file mode 100644 index 0000000000000000000000000000000000000000..4b9e761513cc372e2d722f961e5f8bd319f52e7a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/serialize.py @@ -0,0 +1,4431 @@ +# mypy: allow-untyped-defs +import base64 +import copy +import copyreg +import dataclasses +import heapq +import inspect +import io +import json +import keyword +import logging +import math +import operator +import re +import traceback +import types +import typing +from collections import namedtuple, OrderedDict +from collections.abc import Callable, Iterable, Iterator, Sequence +from contextlib import contextmanager +from dataclasses import dataclass, field +from enum import Enum +from typing import Annotated, Any, cast, final, Optional + +import sympy + +import torch +import torch.export.exported_program as ep +from torch._export.non_strict_utils import _enable_graph_inputs_of_type_nn_module +from torch._export.verifier import load_verifier +from torch._library.opaque_object import get_opaque_type_name, is_custom_class_obj +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode +from torch.fx._symbolic_trace import _ConstantAttributeType +from torch.fx.experimental import symbolic_shapes +from torch.fx.traceback import NodeSource +from torch.utils import _pytree as pytree +from torch.utils._pytree import treespec_dumps, treespec_loads +from torch.utils._sympy.numbers import int_oo +from torch.utils._sympy.symbol import prefix_str, SymT +from torch.utils._sympy.value_ranges import ValueRanges +from torch.utils._traceback import CapturedTraceback +from torch.utils._triton import has_triton + +from ..utils import remove_proxy_from_state_dict +from . import schema +from .schema import ( # type: ignore[attr-defined] + Argument, + ArgumentKind, + BufferMutationSpec, + ComplexValue, + ConstantValue, + CustomObjArgument, + Device, + ExportedProgram, + GradientToParameterSpec, + GradientToUserInputSpec, + Graph, + GraphArgument, + GraphModule, + GraphSignature, + InputSpec, + InputToBufferSpec, + InputToConstantInputSpec, + InputToCustomObjSpec, + InputTokenSpec, + InputToParameterSpec, + InputToTensorConstantSpec, + Layout, + LossOutputSpec, + MemoryFormat, + ModuleCallEntry, + ModuleCallSignature, + NamedArgument, + NamedTupleDef, + Node, + OptionalTensorArgument, + OutputSpec, + OutputTokenSpec, + ParameterMutationSpec, + RangeConstraint, + ScalarType, + SCHEMA_VERSION, + SchemaVersion, + SymBool, + SymBoolArgument, + SymExpr, + SymExprHint, + SymFloat, + SymFloatArgument, + SymInt, + SymIntArgument, + TensorArgument, + TensorMeta, + TokenArgument, + TREESPEC_VERSION, + UserInputMutationSpec, + UserInputSpec, + UserOutputSpec, +) +from .union import _Union + + +__all__ = [ + "serialize", + "GraphModuleSerializer", + "ExportedProgramSerializer", + "GraphModuleDeserializer", + "ExportedProgramDeserializer", +] + +log = logging.getLogger(__name__) + + +class SerializeError(RuntimeError): + pass + + +def _reverse_map(d: dict[Any, Enum]): + return {v.value: k for k, v in d.items()} + + +MetaType = ( + FakeTensor + | int + | torch.SymInt + | float + | torch.SymFloat + | bool + | torch.SymBool + | ep.CustomObjArgument +) + +DEFAULT_PICKLE_PROTOCOL = 2 + +ST_DELIMITER = ";" + +_TORCH_TO_SERIALIZE_DTYPE = { + torch.uint8: ScalarType.BYTE, + torch.int8: ScalarType.CHAR, + torch.uint16: ScalarType.UINT16, + torch.int16: ScalarType.SHORT, + torch.int32: ScalarType.INT, + torch.int64: ScalarType.LONG, + torch.float16: ScalarType.HALF, + torch.float32: ScalarType.FLOAT, + torch.float64: ScalarType.DOUBLE, + torch.complex32: ScalarType.COMPLEXHALF, + torch.complex64: ScalarType.COMPLEXFLOAT, + torch.complex128: ScalarType.COMPLEXDOUBLE, + torch.bool: ScalarType.BOOL, + torch.bfloat16: ScalarType.BFLOAT16, + torch.float8_e4m3fn: ScalarType.FLOAT8E4M3FN, + torch.float8_e5m2: ScalarType.FLOAT8E5M2, + torch.float8_e4m3fnuz: ScalarType.FLOAT8E4M3FNUZ, + torch.float8_e5m2fnuz: ScalarType.FLOAT8E5M2FNUZ, + torch.float8_e8m0fnu: ScalarType.FLOAT8E8M0FNU, + torch.uint32: ScalarType.UINT32, + torch.uint64: ScalarType.UINT64, +} + + +_SERIALIZE_TO_TORCH_DTYPE = _reverse_map(_TORCH_TO_SERIALIZE_DTYPE) # type: ignore[arg-type] + + +_TORCH_TO_SERIALIZE_LAYOUT = { + torch.sparse_coo: Layout.SparseCoo, + torch.sparse_csr: Layout.SparseCsr, + torch.sparse_csc: Layout.SparseCsc, + torch.sparse_bsr: Layout.SparseBsr, + torch.sparse_bsc: Layout.SparseBsc, + torch._mkldnn: Layout._mkldnn, # type: ignore[attr-defined] + torch.strided: Layout.Strided, +} + + +_SERIALIZE_TO_TORCH_LAYOUT = _reverse_map(_TORCH_TO_SERIALIZE_LAYOUT) # type: ignore[arg-type] + + +_TORCH_TO_SERIALIZE_MEMORY_FORMAT = { + torch.contiguous_format: MemoryFormat.ContiguousFormat, + torch.channels_last: MemoryFormat.ChannelsLast, + torch.channels_last_3d: MemoryFormat.ChannelsLast3d, + torch.preserve_format: MemoryFormat.PreserveFormat, +} + + +_SERIALIZE_TO_TORCH_MEMORY_FORMAT = _reverse_map(_TORCH_TO_SERIALIZE_MEMORY_FORMAT) # type: ignore[arg-type] + +_SYM_OPS = { + operator.eq, + operator.ne, + operator.le, + operator.ge, + operator.lt, + operator.gt, + operator.neg, + operator.pos, + math.trunc, + torch.sym_not, + operator.mul, + operator.add, + operator.sub, + operator.floordiv, + operator.mod, + operator.pow, + torch.sym_int, + torch.sym_float, + torch.sym_ite, + torch.sym_max, + torch.sym_min, + torch.sym_sqrt, + operator.truediv, + operator.and_, + operator.or_, + operator.lshift, + operator.rshift, +} + + +if any(isinstance(op, torch._ops.OpOverload) for op in _SYM_OPS): + raise AssertionError("_SYM_OPS should not contain OpOverload instances") + + +@dataclass +class SerializedArtifact: + exported_program: bytes + state_dict: bytes + constants: bytes + example_inputs: bytes + + +@dataclass +class _SerializedProgram: + exported_program: ExportedProgram + state_dict: bytes + constants: bytes + example_inputs: bytes + + +class LazyMap(dict): + """ + Dictionary class for deferred instantiation of node metadata values. + Purpose is to avoid creation of symbolic-shape tensors before relevant shape guards are parsed. + """ + + def __init__(self): + self.map = {} + self.evaluated = set() + + def __setitem__(self, k, v): + self.map[k] = v + + def __getitem__(self, k): + out = self.map[k] + if k in self.evaluated: + return out + self.evaluated.add(k) + self.map[k] = out() + return self.map[k] + + def __repr__(self): + return self.map.__repr__() + + +def deserialize_device(d: Device) -> torch.device: + if d.index is None: + return torch.device(type=d.type) # type: ignore[call-overload] + return torch.device(type=d.type, index=d.index) + + +def deserialize_size(sizes: Sequence[SymInt]) -> tuple[int, ...]: + for sym_int_size in sizes: + if sym_int_size.type != "as_int": + raise AssertionError(f"Only as_int is supported, got {sym_int_size.type}") + return tuple(sym_int_size.as_int for sym_int_size in sizes) + + +def deserialize_stride(strides: Sequence[SymInt]) -> tuple[int, ...]: + for sym_int_stride in strides: + if sym_int_stride.type != "as_int": + raise AssertionError(f"Only as_int is supported, got {sym_int_stride.type}") + return tuple(sym_int_stride.as_int for sym_int_stride in strides) + + +def deserialize_scalar_type(st: ScalarType) -> torch.dtype: + return _SERIALIZE_TO_TORCH_DTYPE[st] + + +def deserialize_storage_offset(offset: SymInt) -> int: + if offset.type != "as_int": + raise AssertionError(f"Only as_int is supported, got {offset.type}") + return offset.as_int + + +def _print_sympy(s: torch.SymInt | torch.SymBool | torch.SymFloat | sympy.Expr): + if isinstance(s, (torch.SymInt, torch.SymBool, torch.SymFloat)): + s = s.node.expr + return sympy.printing.repr.srepr(s) + + +def serialize_sym_int(s: int | torch.SymInt) -> SymInt: + if isinstance(s, (torch.SymInt, sympy.Symbol, int)): + if symbolic_shapes.is_concrete_int(s): + return SymInt.create(as_int=int(s)) + else: + if not isinstance(s, (torch.SymInt, sympy.Symbol)): + raise AssertionError( + f"expected SymInt or Symbol, got {type(s).__name__}" + ) + if s.node.hint is None: + return SymInt.create(as_expr=SymExpr(_print_sympy(s))) + else: + return SymInt.create( + as_expr=SymExpr( + _print_sympy(s), + hint=SymExprHint.create(as_int=s.node.hint), + ) + ) + else: + raise SerializeError( + f"SymInt should be either symbol or int, got `{s}` of type `{type(s)}`" + ) + + +def serialize_sym_float(s: float | torch.SymFloat) -> SymFloat: + if isinstance(s, (torch.SymFloat, sympy.Symbol, float)): + if symbolic_shapes.is_concrete_float(s): + return SymFloat.create(as_float=float(s)) + else: + if not isinstance(s, (torch.SymFloat, sympy.Symbol)): + raise AssertionError( + f"expected SymFloat or Symbol, got {type(s).__name__}" + ) + if s.node.hint is None: + return SymFloat.create(as_expr=SymExpr(_print_sympy(s))) + else: + return SymFloat.create( + as_expr=SymExpr( + _print_sympy(s), + hint=SymExprHint.create(as_float=s.node.hint), + ) + ) + else: + raise SerializeError( + f"SymFloat should be either symbol or float, got `{s}` of type `{type(s)}`" + ) + + +def serialize_sym_bool(s: bool | torch.SymBool) -> SymBool: + if isinstance(s, (torch.SymBool, bool)): + if symbolic_shapes.is_concrete_bool(s): + return SymBool.create(as_bool=bool(s)) + else: + return SymBool.create(as_expr=SymExpr(expr_str=_print_sympy(s))) + else: + raise SerializeError( + f"SymBool should be either symbol or bool, got `{s}` of type `{type(s)}`" + ) + + +def serialize_tensor_meta(t: torch.Tensor) -> TensorMeta: + """ + Extract a TensorMeta describing `t`. + """ + return TensorMeta( + dtype=_TORCH_TO_SERIALIZE_DTYPE[t.dtype], + sizes=[serialize_sym_int(s) for s in t.shape], + requires_grad=t.requires_grad, + device=Device(type=t.device.type, index=t.device.index), + strides=[serialize_sym_int(s) for s in t.stride()], + storage_offset=serialize_sym_int(t.storage_offset()), + layout=_TORCH_TO_SERIALIZE_LAYOUT[t.layout], + ) + + +_CURRENT_DESERIALIZER: Optional["GraphModuleDeserializer"] = None + + +def _reduce_fake_tensor(fake_tensor: FakeTensor): + is_parameter = isinstance(fake_tensor, torch.nn.Parameter) + tensor_meta = serialize_tensor_meta(fake_tensor) + tensor_meta_bytes = json.dumps( + _dataclass_to_dict(tensor_meta), cls=EnumEncoder + ).encode("utf-8") + return _reconstruct_fake_tensor, (tensor_meta_bytes, is_parameter) + + +def _reconstruct_fake_tensor( + serialized_tensor_meta: bytes, is_parameter: bool +) -> FakeTensor: + # Deserialize the bytes into a TensorMeta + json_tensor_meta = json.loads(serialized_tensor_meta.decode("utf-8")) + tensor_meta = _dict_to_dataclass(TensorMeta, json_tensor_meta) + # Find the current fake mode + if _CURRENT_DESERIALIZER is None: + raise AssertionError("Need access to current deserializer state") + fake_tensor = _CURRENT_DESERIALIZER.deserialize_tensor_meta(tensor_meta) + if is_parameter: + fake_tensor = torch.nn.Parameter(fake_tensor) # type: ignore[assignment] + # pyrefly: ignore [bad-return] + return fake_tensor + + +def serialize_torch_artifact( + artifact: Any | None, pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL +) -> bytes: + if artifact is None: + return b"" + + if FakeTensor in copyreg.dispatch_table: + raise AssertionError("Refusing to stomp on existing FakeTensor reducer") + try: + copyreg.pickle(FakeTensor, _reduce_fake_tensor) + buffer = io.BytesIO() + # This is a workaround for backend's tensor deserialization problem: + # unpickleTensor() always create a tensor on the device where it was originally saved + # This behavior is bad for multi-gpu training, as we wish to directly load the tensor + # on the designated device. + # For now, we simply move the tensor to cpu before saving. + # TODO: this should be fixed by deserialization instead. + torch.save(artifact, buffer, pickle_protocol=pickle_protocol) + return buffer.getvalue() + finally: + del copyreg.dispatch_table[FakeTensor] + + +def deserialize_torch_artifact( + serialized: dict[str, Any] | tuple[Any, ...] | bytes, +): + if isinstance(serialized, (dict, tuple)): + return serialized + if len(serialized) == 0: + return {} + buffer = io.BytesIO(serialized) + buffer.seek(0) + # weights_only=False as we want to load custom objects here (e.g. ScriptObject) + try: + artifact = torch.load(buffer, weights_only=True) + except Exception as e: + buffer.seek(0) + artifact = torch.load(buffer, weights_only=False) + log.warning( + "Fallback to weights_only=False succeeded. " + "Loaded object of type %s after initial failure: %s", + type(artifact), + exc_info=e, + ) + if not isinstance(artifact, (tuple, dict)): + raise AssertionError(f"expected tuple or dict, got {type(artifact).__name__}") + return artifact + + +def _sympy_int_to_int(val: sympy.Expr, adjust: str) -> int | None: + # Convert simple sympy Integers into concrete int + if val in (sympy.oo, int_oo): + return None + if val in (-sympy.oo, -int_oo): + return None + if isinstance(val, sympy.Integer): + return int(val) + + # TODO: Remove this adjustment when Ed gets rid of fractional ranges + log.warning( + "Export constraints cannot be non-integer expressions. Found " + "type %s, and value %s. We will attempt to %s " + "this value.", + type(val), + val, + adjust, + ) + + if adjust == "floor": + return math.floor(val) + elif adjust == "ceil": + return math.ceil(val) + else: + raise RuntimeError(f"Got invalid adjustment {adjust}") + + +def _int_to_sympy_int(val: int | None, default) -> sympy.Expr: + # Convert concrete int into simple sympy Integers + if val is None: + return default + if val in [-int_oo, int_oo]: + return val + if val == math.inf: + return int_oo + if val == -math.inf: + return -int_oo + return sympy.Integer(val) + + +def _symbol_index(sym: sympy.Symbol, sym_type: SymT): + return int(str(sym)[len(prefix_str[sym_type]) :]) + + +def serialize_range_constraints( + range_constraints: dict[sympy.Symbol, ValueRanges], +) -> dict[str, RangeConstraint]: + return { + str(k): RangeConstraint( + _sympy_int_to_int(v.lower, "ceil"), # type: ignore[arg-type] + _sympy_int_to_int(v.upper, "floor"), # type: ignore[arg-type] + ) + for k, v in range_constraints.items() + } + + +def _get_schema_from_target(target): + if isinstance(target, torch._ops.OpOverload): + return target._schema + elif type(target) in _serialization_registry: + return _serialization_registry[type(target)].op_schema(target) + raise RuntimeError(f"Cannot find schema for {type(target)}") + + +@dataclass +class GraphState: + inputs: list[Argument] = field(default_factory=list) + outputs: list[Argument] = field(default_factory=list) + nodes: list[Node] = field(default_factory=list) + tensor_values: dict[str, TensorMeta] = field(default_factory=dict) + sym_int_values: dict[str, SymInt] = field(default_factory=dict) + sym_bool_values: dict[str, SymBool] = field(default_factory=dict) + sym_float_values: dict[str, SymFloat] = field(default_factory=dict) + is_single_tensor_return: bool = False + custom_obj_values: dict[str, CustomObjArgument] = field(default_factory=dict) + + +class Final(type): + def __new__(metacls, name, bases, classdict): + for b in bases: + if isinstance(b, Final): + raise TypeError(f"type '{b.__name__}' is not an acceptable base type") + return type.__new__(metacls, name, bases, dict(classdict)) + + +def is_metadata_matched(config, entry_metadata): + metadata_attrs = ["num_cpu_threads", "num_warps", "num_stages", "num_ctas"] + for attr in metadata_attrs: + if hasattr(config, attr) and hasattr(entry_metadata, attr): + if getattr(config, attr) != getattr(entry_metadata, attr): + return False + return True + + +def get_triton_kernel_and_cache_entry(node: torch.fx.Node): + if ( + node.target + is not torch._higher_order_ops.triton_kernel_wrap.triton_kernel_wrapper_functional + ): + raise AssertionError( + f"expected triton_kernel_wrapper_functional, got {node.target}" + ) + + if not has_triton(): + raise AssertionError("triton required to serialize triton kernels") + from triton.runtime.autotuner import Autotuner + from triton.runtime.jit import JITFunction + + if not isinstance(node.kwargs["kernel_idx"], int): + raise AssertionError( + f"expected kernel_idx to be int, got {type(node.kwargs['kernel_idx'])}" + ) + kernel = torch._higher_order_ops.triton_kernel_wrap.kernel_side_table.get_kernel( + node.kwargs["kernel_idx"] + ) + + # For Autotuner, we need to look at the underlying JITFunction's cache + # since the Autotuner itself doesn't have a cache + is_autotuner = isinstance(kernel, Autotuner) + # pyrefly: ignore [missing-attribute] + actual_kernel = kernel.fn if is_autotuner else kernel + + if hasattr(actual_kernel, "device_caches"): + caches = actual_kernel.device_caches + if len(caches.keys()) != 1: + raise AssertionError( + f"expected exactly 1 device cache, got {len(caches.keys())}" + ) + cache = next(iter(caches.values()))[0] + elif hasattr(actual_kernel, "cache"): + # old path, still used for cpu triton builds + caches = actual_kernel.cache + if len(caches.keys()) != 1: + raise AssertionError( + f"expected exactly 1 cache key, got {len(caches.keys())}" + ) + cache = next(iter(caches.values())) + else: + raise AssertionError( + # pyrefly: ignore [missing-attribute] + f"kernel caches not found for kernel {actual_kernel.__name__}" + ) + + if len(cache.keys()) == 1: + return actual_kernel, next(iter(cache.values())) + + has_constexprs = ( + isinstance(actual_kernel, JITFunction) + and hasattr(actual_kernel, "constexprs") + and len(actual_kernel.constexprs) > 0 + ) + + if has_constexprs: + constexpr_vals = {} + # pyrefly: ignore [missing-attribute] + for constexpr_idx in actual_kernel.constexprs: + # pyrefly: ignore [missing-attribute] + if constexpr_idx < len(actual_kernel.arg_names): + # pyrefly: ignore [missing-attribute] + param_name = actual_kernel.arg_names[constexpr_idx] + kwargs_dict = node.kwargs.get("kwargs", {}) + if isinstance(kwargs_dict, dict): + if param_name in kwargs_dict: + constexpr_vals[param_name] = kwargs_dict[param_name] + + expected_values = [ + # pyrefly: ignore [missing-attribute] + constexpr_vals[actual_kernel.arg_names[idx]] + # pyrefly: ignore [missing-attribute] + for idx in actual_kernel.constexprs + # pyrefly: ignore [missing-attribute] + if actual_kernel.arg_names[idx] in constexpr_vals + ] + + # Normalize expected values for comparison with parsed constexpr values. + # The kernel signature key stores constexprs as strings (e.g., "True", "1.5", "42"), + # which we parse back to Python types. To ensure proper comparison, we normalize + # the expected values: booleans, ints, and floats are kept as-is since they can + # be compared directly with parsed values. Other types (like dtype or string + # constants) are converted to strings to match the parsed format. + normalized_expected = [] + for val in expected_values: + if isinstance(val, (bool, int, float)): + normalized_expected.append(val) + else: + # pyrefly: ignore [bad-argument-type] + normalized_expected.append(str(val)) + + matching_entries = [] + for sig_key, cache_entry in cache.items(): + constexpr_matches = re.findall(r"\('constexpr',\s*([^)]+)\)", sig_key) + if constexpr_matches: + # Parse constexpr string values back to Python types for comparison. + # Booleans are stored as "True"/"False" strings, numbers as their string + # representation. Values that can't be parsed as numbers are kept as strings + # (e.g., dtype names like "torch.float32"). + constexpr_values = [] + for match in constexpr_matches: + if match in ("True", "False"): + constexpr_values.append(match == "True") + else: + try: + constexpr_values.append(float(match)) + except ValueError: + try: + constexpr_values.append(int(match)) + except ValueError: + constexpr_values.append(match) + + if constexpr_values == normalized_expected: + matching_entries.append((sig_key, cache_entry)) + else: + matching_entries = list(cache.items()) + + if len(matching_entries) == 0: + raise AssertionError( + # pyrefly: ignore [missing-attribute] + f"couldn't find a kernel cache entry with metadata matching the autotuner configs for kernel {actual_kernel.__name__}. " + f"Available cache keys: {list(cache.keys())}" + ) + + if len(matching_entries) == 1: + return actual_kernel, matching_entries[0][1] + + if is_autotuner: + for _sig_key, cache_entry in matching_entries: + entry_metadata = cache_entry.metadata + # pyrefly: ignore [missing-attribute] + for config in kernel.configs: + if is_metadata_matched(config, entry_metadata): + return actual_kernel, cache_entry + + raise AssertionError( + # pyrefly: ignore [missing-attribute] + f"Multiple cache entries found for autotuned kernel {actual_kernel.__name__} " + f"{'with same constexpr values' if has_constexprs else 'with no constexpr'} " + f"and couldn't disambiguate using configs. " + ) + + raise AssertionError( + # pyrefly: ignore [missing-attribute] + f"Multiple cache entries found for non-autotuned kernel {actual_kernel.__name__} " + f"{'with same constexpr values' if has_constexprs else 'with no constexpr'}. " + f"This should not happen. Available cache keys: {[key for key, _ in matching_entries]}" + ) + + +@final +class GraphModuleSerializer(metaclass=Final): + def __init__( + self, + graph_signature: ep.ExportGraphSignature, + module_call_graph: list[ep.ModuleCallEntry], + ): + self.graph_state = GraphState() + self.graph_signature = graph_signature + self.module_call_graph = module_call_graph + self.custom_objs: dict[str, Any] = {} + self.duplicate_getitem_nodes: dict[str, str] = {} + self.treespec_namedtuple_fields: dict[str, NamedTupleDef] = {} + + @contextmanager + def save_graph_state(self): + saved = self.graph_state + self.graph_state = GraphState() + try: + yield + finally: + self.graph_state = saved + + def handle_placeholder(self, node: torch.fx.Node): + if node.op != "placeholder": + raise AssertionError(f"expected placeholder op, got {node.op}") + val = node.meta["val"] + log.debug("[handle_placeholder] %s: %s", node.name, val) + if isinstance(val, torch.Tensor): + graph_input = Argument.create( + as_tensor=self.serialize_tensor_output(node.name, val) + ) + elif isinstance(val, torch.SymInt): + graph_input = Argument.create( + as_sym_int=self.serialize_sym_int_output(node.name, val) + ) + elif isinstance(val, torch.SymFloat): + raise AssertionError("SymFloat graph input is not implemented yet.") + elif isinstance(val, (int, bool, str, float, type(None))): + graph_input = self.serialize_input(val) + elif isinstance(val, ep.CustomObjArgument): + class_fqn = val.class_fqn + graph_input = Argument.create( + as_custom_obj=CustomObjArgument(name=node.name, class_fqn=class_fqn) + ) + self.graph_state.custom_obj_values[node.name] = ( + self.serialize_script_obj_meta(val) + ) + else: + raise AssertionError(f"Unimplemented graph input type: {node.meta['val']}") + self.graph_state.inputs.append(graph_input) + + def handle_output(self, node: torch.fx.Node): + if node.op != "output": + raise AssertionError(f"expected output op, got {node.op}") + if len(node.args) != 1: + raise AssertionError( + f"FX.Node's args should have one arg, got {len(node.args)}" + ) + node_args = node.args[0] + log.debug("[handle_output] %s: %s", node.name, node_args) + if isinstance(node_args, torch.fx.Node): + # For singleton tensor returns + self.graph_state.is_single_tensor_return = True + self.graph_state.outputs = [self.serialize_input(node_args)] + else: + if not isinstance(node_args, (tuple, list)): + raise AssertionError(f"expected tuple or list, got {type(node_args)}") + self.graph_state.outputs = [self.serialize_input(arg) for arg in node_args] + + def serialize_operator(self, target) -> str: + if isinstance(target, str): + return target + elif target.__module__.startswith("torch._ops"): + # TODO(zhxchen17) Maybe provide a function name helper in FX. + # From torch.fx.node._get_qualified_name + module = target.__module__.replace("torch._ops", "torch.ops") + return f"{module}.{target.__name__}" + else: # TODO(zhxchen17) Don't catch all here. + return f"{target.__module__}.{target.__name__}" + + def handle_call_function(self, node: torch.fx.Node): + if node.op != "call_function": + raise AssertionError(f"expected call_function op, got {node.op}") + meta_val = node.meta.get("val") + log.debug( + "[handle_call_function] %s: %s(%s, {%s}) -> %s", + node.name, + node.target, + node.args, + node.kwargs, + meta_val, + ) + + # getitem has been handled in the producer node, skip it here + if node.target is operator.getitem: + return + + if node.target in _SYM_OPS or ( + meta_val is not None + and isinstance(meta_val, (torch.SymInt, torch.SymBool, torch.SymFloat)) + ): + if len(node.kwargs) != 0: + raise AssertionError( + f"expected no kwargs for sym op, got {len(node.kwargs)}" + ) + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=self.serialize_sym_op_inputs(node.target, node.args), + outputs=[self.serialize_output(node.name, meta_val)], + metadata=self.serialize_metadata(node), + ) + elif isinstance(node.target, torch._ops.OpOverload): + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=self.serialize_inputs(node.target, node.args, node.kwargs), + outputs=self.serialize_outputs(node), + # TODO: create a new tensor_values here, meta might have faketensor info + metadata=self.serialize_metadata(node), + ) + elif isinstance(node.target, torch._ops.HigherOrderOperator): + + def _is_hop_single_tensor_return(node) -> bool: + if not isinstance(node.target, torch._ops.HigherOrderOperator): + raise AssertionError( + f"expected HigherOrderOperator, got {type(node.target).__name__}" + ) + # HOP schema is not always available, so we look at node.meta["val"] + meta_val = node.meta.get("val", None) + return meta_val is not None and isinstance(meta_val, torch.Tensor) + + # Special handle serialization for aoti_call_delegate + if node.target is torch._higher_order_ops.aoti_call_delegate: + serializable_args = list(node.args) + + # AOTI lowered module is not serializable, serialize the aoti_path instead + lowered_module_name: str = node.args[0].name # type: ignore[assignment, no-untyped-def, union-attr] + if not hasattr(node.graph.owning_module, lowered_module_name): + raise AssertionError( + f"owning_module does not have attribute {lowered_module_name}" + ) + lowered_module = getattr(node.graph.owning_module, lowered_module_name) # type: ignore[no-untyped-def] + serializable_args[0] = lowered_module.aoti_path + + # AOTI compiled graph module in node.args[0] is stateful, and will fail the verifier check + # Skip serializing original_gm as a workaround + serializable_args[1] = None + + serializable_weight_nodes = [] + if serializable_args[2] is not None and isinstance( + serializable_args[2], Iterable + ): + for weight_node in serializable_args[2]: + # skip passing custom obj into the weight arg as an hack + # The schema of weight input is a list of Tensors. + # Downstream runtime is not actively consuming the weighs arg for anything meaningful. + if isinstance(weight_node, torch.fx.Node) and isinstance( + weight_node.meta.get("val", None), ep.CustomObjArgument + ): + continue + serializable_weight_nodes.append(weight_node) + serializable_args[2] = serializable_weight_nodes + + def serialize_tensor_list_output(node): + meta_val = node.meta.get("val", None) + tensor_args = [] + for idx, meta in enumerate(meta_val): + name = self._output_node_name_at_index(node, idx) + tensor_args.append(self.serialize_tensor_output(name, meta)) + return [Argument.create(as_tensors=tensor_args)] + + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=self.serialize_hoo_inputs(serializable_args, node.kwargs), + outputs=serialize_tensor_list_output(node), + metadata=self.serialize_metadata(node), + is_hop_single_tensor_return=False, + ) + elif ( + node.target + is torch._higher_order_ops.triton_kernel_wrap.triton_kernel_wrapper_functional + ): + kernel, kernel_cache_entry = get_triton_kernel_and_cache_entry(node) + kernel_cache_metadata = kernel_cache_entry.metadata + + meta_val = node.meta["val"] + if not isinstance(meta_val, dict): + raise AssertionError( + f"expected meta_val to be dict, got {type(meta_val).__name__}" + ) + + output_keys = meta_val.keys() + output_indices = [] + + constexpr_keys = {p.name for p in kernel.params if p.is_constexpr} + found_constexpr = False + inputs_new = [] + i = 0 + + if not isinstance(node.kwargs["kwargs"], dict): + raise AssertionError( + f"expected kwargs['kwargs'] to be dict, got {type(node.kwargs['kwargs'])}" + ) + for k, v in node.kwargs["kwargs"].items(): + # don't serialize constexpr since they will + # be embedded into the binary and don't + # need to be passed around as attributes + if k in constexpr_keys: + found_constexpr = True + continue + + if found_constexpr: + raise AssertionError( + "non-constexpr args found after constexpr arg(s)" + ) + + if k in output_keys: + output_indices.append(i) + inputs_new.append( + NamedArgument( + name=k, + arg=self.serialize_input(v), + kind=ArgumentKind.POSITIONAL, + ) + ) + i += 1 + + if not isinstance(node.kwargs["grid"], list): + raise AssertionError( + f"expected grid to be list, got {type(node.kwargs['grid'])}" + ) + + kernel_name_with_hash = ( + f"{kernel.fn.__name__}_{kernel_cache_metadata.hash}" + ) + kwargs_new = { + "name": kernel_name_with_hash, + "grid": node.kwargs["grid"][0], + "output_indices": output_indices, + "num_warps": kernel_cache_metadata.num_warps, + } + if hasattr(kernel_cache_metadata, "num_cpu_threads"): + kwargs_new["num_cpu_threads"] = ( + kernel_cache_metadata.num_cpu_threads + ) + + if hasattr(kernel_cache_metadata, "shared"): + if isinstance(kernel_cache_metadata.shared, bool): + kwargs_new["shared_memory_bytes"] = int( + kernel_cache_metadata.shared + ) + else: + kwargs_new["shared_memory_bytes"] = kernel_cache_metadata.shared + + # MTIA-specific parameters for triton kernel compilation + if hasattr(kernel_cache_metadata, "tile_width"): + kwargs_new["tile_width"] = kernel_cache_metadata.tile_width + if hasattr(kernel_cache_metadata, "tile_height"): + kwargs_new["tile_height"] = kernel_cache_metadata.tile_height + if hasattr(kernel_cache_metadata, "base_pe"): + kwargs_new["base_pe"] = kernel_cache_metadata.base_pe + + # Kernel parameter metadata for MTIA fatbin compilation + kwargs_new["kernel_param_names"] = [ + p.name for p in kernel.params if not p.is_constexpr + ] + # Use inferred signature types from the compiled kernel's ASTSource + # when available. The signature is populated at runtime with actual + # types like "i32", "*fp32" based on the values passed to the kernel + # (see specialize_impl in jit.py). Fall back to static annotations + # for architectures that don't rely on precise type information. + compiled_signature = getattr( + getattr(kernel_cache_entry, "src", None), "signature", None + ) + if compiled_signature is not None: + kwargs_new["kernel_param_types"] = [ + str(compiled_signature.get(p.name, p.annotation)) + for p in kernel.params + if not p.is_constexpr + ] + else: + # Default behavior: use static annotations (may be empty) + kwargs_new["kernel_param_types"] = [ + str(p.annotation) for p in kernel.params if not p.is_constexpr + ] + + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=inputs_new + + [ + NamedArgument( + name=name, + arg=self.serialize_input(a), + kind=ArgumentKind.KEYWORD, + ) + for name, a in kwargs_new.items() + ], + outputs=self.serialize_hoo_outputs(node), + metadata=self.serialize_metadata(node), + is_hop_single_tensor_return=_is_hop_single_tensor_return(node), + ) + else: + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=self.serialize_hoo_inputs(node.args, node.kwargs), + outputs=self.serialize_hoo_outputs(node), + metadata=self.serialize_metadata(node), + is_hop_single_tensor_return=_is_hop_single_tensor_return(node), + ) + elif type(node.target) in _serialization_registry: + # Sanity check for unhandled serialization. + if type(node.target) not in _serialization_registry: + raise AssertionError( + f"{type(node.target)} is not supported in export serialization." + ) + + handler = _serialization_registry[type(node.target)] + namespace = handler.namespace() + op_name = handler.to_op_name(node.target) + if not isinstance(namespace, str) or not isinstance(op_name, str): + raise AssertionError( + f"expected namespace and op_name to be str, got {type(namespace).__name__} and {type(op_name).__name__}" + ) + if ":" in namespace or ":" in op_name: + raise AssertionError( + f"namespace and op_name should not contain ':', got {namespace!r} and {op_name!r}" + ) + ex_node = Node( + name=node.name, + target=f"#{namespace}:{op_name}", + inputs=self.serialize_inputs(node.target, node.args, node.kwargs), + outputs=self.serialize_outputs(node), + metadata=self.serialize_metadata(node), + ) + elif callable(node.target): + # Handle predispatch wrapper functions (vmap, JVP, etc.) that appear + # as plain Python function call_function nodes in pre_dispatch graphs. + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=self.serialize_hoo_inputs(node.args, node.kwargs), + outputs=self.serialize_hoo_outputs(node), + metadata=self.serialize_metadata(node), + ) + else: + raise SerializeError(f"Serializing {node.target} is not supported") + + self.graph_state.nodes.append(ex_node) + + def handle_get_attr(self, node): + log.debug("[handle_get_attr] %s", node.name) + + def _output_node_at_index(self, node, index) -> torch.fx.Node | None: + user_node = None + for user in node.users: + if user.target is not operator.getitem: + raise AssertionError(f"{user} is not a getitem node") + if index == user.args[1]: + if user_node is None: + user_node = user + else: + # We want to deduplicate getitem nodes that are trying to + # index to the same index + self.duplicate_getitem_nodes[user.name] = user_node.name + return user_node + + def _output_node_name_at_index(self, node, index) -> str: + user_node = self._output_node_at_index(node, index) + if user_node is None: + return f"{node.name}_unused_{index}" + else: + return user_node.name + + def serialize_metadata(self, node: torch.fx.Node) -> dict[str, str]: + ret = {} + + if stack_trace := node.meta.get("stack_trace"): + ret["stack_trace"] = stack_trace + + if nn_module_stack := node.meta.get("nn_module_stack"): + + def export_nn_module_stack(val): + if not isinstance(val, tuple) or len(val) != 2: + val_len = len(val) if isinstance(val, tuple) else "N/A" + raise AssertionError( + f"expected tuple of length 2, got {type(val).__name__} of length {val_len}" + ) + path, ty = val + + if not isinstance(path, str): + raise AssertionError( + f"expected path to be str, got {type(path).__name__}" + ) + if not isinstance(ty, str): + raise AssertionError( + f"expected ty to be str, got {type(ty).__name__}" + ) + + return path + "," + ty + + # Serialize to "key,orig_path,type_str" + nn_module_list = [ + f"{k},{export_nn_module_stack(v)}" for k, v in nn_module_stack.items() + ] + ret["nn_module_stack"] = ST_DELIMITER.join(nn_module_list) + + if source_fn_st := node.meta.get("source_fn_stack"): + source_fn_list = [ + f"{source_fn[0]},{self.serialize_operator(source_fn[1])}" + for source_fn in source_fn_st + ] + ret["source_fn_stack"] = ST_DELIMITER.join(source_fn_list) + + if torch_fn := node.meta.get("torch_fn"): + ret["torch_fn"] = ST_DELIMITER.join(list(torch_fn)) + + if custom := node.meta.get("custom"): + try: + ret["custom"] = json.dumps(custom) + except Exception as e: + raise SerializeError( + f"Failed to serialize custom metadata for node {node.name} with error {e}" + ) from e + + if "from_node" in node.meta: + from_node = node.meta["from_node"] + # Serialize from_node as JSON since it's a complex nested structure + ret["from_node"] = json.dumps(self._serialize_from_node(from_node)) + + return ret + + def _serialize_from_node( + self, from_node: list[NodeSource] | None + ) -> list[dict[str, Any]] | None: + """ + Serialize from_node metadata from a list of NodeSource objects to a list of dictionaries. + """ + if from_node is None: + return None + + return [ + node_source.to_dict() + for node_source in from_node + if isinstance(node_source, NodeSource) + ] + + def serialize_script_obj_meta( + self, script_obj_meta: ep.CustomObjArgument + ) -> CustomObjArgument: + log.debug("[serialize_script_obj_meta] %s", script_obj_meta) + return CustomObjArgument( + name=script_obj_meta.name, + class_fqn=script_obj_meta.class_fqn, + ) + + def serialize_sym_op_inputs(self, op, args) -> list[NamedArgument]: + if isinstance(op, torch._ops.OpOverload): + args_names = [arg.name for arg in op._schema.arguments] + else: + if op not in _SYM_OPS: + raise AssertionError(f"op {op} is not in _SYM_OPS") + args_names = list(inspect.signature(op).parameters.keys()) + serialized_args = [] + for args_name, arg in zip(args_names, args): + serialized_args.append( + NamedArgument( + name=args_name, + arg=self.serialize_input(arg), + kind=ArgumentKind.POSITIONAL, + ) + ) + return serialized_args + + def serialize_inputs( + self, + target: Any, # torch._ops.OpOverload and other custom operator types. + args, + kwargs=None, + ) -> list[NamedArgument]: + schema = None + serialized_args = [] + + if isinstance(target, torch._higher_order_ops.torchbind.CallTorchBind): + obj = args[0] + method = args[1] + schema = target.schema(obj, method) + else: + if not isinstance( + target, (torch._ops.OpOverload, *_registered_extension_types()) + ): + raise AssertionError( + f"expected OpOverload or registered extension type, got {type(target).__name__}" + ) + schema = _get_schema_from_target(target) + if schema is None: + raise AssertionError("schema should not be None") + kwargs = kwargs or {} + + for i, schema_arg in enumerate(schema.arguments): + if schema_arg.name in kwargs: + serialized_args.append( + NamedArgument( + name=schema_arg.name, + arg=self.serialize_input( + kwargs[schema_arg.name], schema_arg.type + ), + kind=ArgumentKind.KEYWORD, + ) + ) + elif not schema_arg.kwarg_only and i < len(args): + serialized_args.append( + NamedArgument( + name=schema_arg.name, + arg=self.serialize_input(args[i], schema_arg.type), + kind=ArgumentKind.POSITIONAL, + ) + ) + else: + # We intentionally don't serialize the missing arguments + # with default values + pass + + return serialized_args + + def serialize_hoo_inputs(self, args, kwargs) -> list[NamedArgument]: + """ + For serializing HOO inputs since HOOs do not have a schema. + """ + inputs = [ + NamedArgument( + name="", arg=self.serialize_input(a), kind=ArgumentKind.POSITIONAL + ) + for a in args + ] + inputs.extend( + [ + NamedArgument( + name=name, + arg=self.serialize_input(a), + kind=ArgumentKind.KEYWORD, + ) + for name, a in kwargs.items() + ] + ) + return inputs + + def is_inductor_sym_int_arg(self, arg) -> bool: + # This is a special branch for handling SymInt args in inductor's + # ExternalFallbackNode. + # For regular FX graph, SymInt arg should be a fx.Node and should be + # verified with is_sym_int_arg() + return type(arg) is int or isinstance(arg, torch.SymInt) + + def is_sym_int_arg(self, arg) -> bool: + return type(arg) is int or ( + isinstance(arg, torch.fx.Node) + and arg.name in self.graph_state.sym_int_values + ) + + def is_sym_float_arg(self, arg) -> bool: + return isinstance(arg, float) or ( + isinstance(arg, torch.fx.Node) + and arg.name in self.graph_state.sym_float_values + ) + + def is_sym_bool_arg(self, arg) -> bool: + return isinstance(arg, bool) or ( + isinstance(arg, torch.fx.Node) + and arg.name in self.graph_state.sym_bool_values + ) + + # should be torch._C.JitType but that annotation is busted + def serialize_input(self, arg, arg_type: Any | None = None) -> Argument: + import torch._inductor.ir as inductor_ir + + inductor_tensor_buffers = ( + inductor_ir.Buffer, + inductor_ir.ReinterpretView, + ) + + if isinstance(arg, torch.fx.Node): + if arg.op == "get_attr": + if not isinstance(arg.target, str): + raise AssertionError( + f"expected arg.target to be str, got {type(arg.target).__name__}" + ) + attr = getattr(arg.graph.owning_module, arg.target) + + if isinstance(attr, torch.Tensor): + raise SerializeError( + "getattr nodes containing tensors should not appear in the graph" + ) + elif isinstance(attr, torch.fx.GraphModule): + with self.save_graph_state(): + graph = self.serialize_graph(attr) + return Argument.create( + as_graph=GraphArgument(name=arg.target, graph=graph) + ) + elif type(attr).__name__ == "LoweredBackendModule": + # Special handling for executorch_call_delegate HOP + # Its first argument is a LoweredBackendModule, for which we + # serialize name and backend id of the lowered module + module_name = getattr(attr, "module_name", None) + backend_id = getattr(attr, "backend_id", None) + if module_name is None: + raise AssertionError("module_name should not be None") + if backend_id is None: + raise AssertionError("backend_id should not be None") + return Argument.create(as_string=f"{module_name}-{backend_id}") + else: + raise SerializeError( + f"Unsupported getattr attribute {arg.target} with type: {type(attr)}" + ) + elif self.is_sym_int_arg(arg): + return Argument.create( + as_sym_int=SymIntArgument.create(as_name=arg.name) + ) + elif self.is_sym_float_arg(arg): + return Argument.create( + as_sym_float=SymFloatArgument.create(as_name=arg.name) + ) + elif self.is_sym_bool_arg(arg): + return Argument.create( + as_sym_bool=SymBoolArgument.create(as_name=arg.name) + ) + elif isinstance(arg.meta["val"], ep.CustomObjArgument): + return Argument.create( + as_custom_obj=CustomObjArgument( + name=arg.name, class_fqn=arg.meta["val"].class_fqn + ) + ) + elif arg.name in self.duplicate_getitem_nodes: + dedup_name = self.duplicate_getitem_nodes[arg.name] + return Argument.create(as_tensor=TensorArgument(name=dedup_name)) + else: + return Argument.create(as_tensor=TensorArgument(name=arg.name)) + elif isinstance(arg, inductor_tensor_buffers): + # Other branches are for arguments in fx node. + # This is a special branch for handling buffers (representing tensor arguments) + # for inductor's ExternalFallbackNode + # export_extern_kernel_node() is using this function to serialize arguments + arg_name = arg.get_name() + if arg_name is None: + raise AssertionError("Buffer must have valid name") + return Argument.create(as_tensor=TensorArgument(name=arg_name)) + elif isinstance(arg, inductor_ir.TorchBindObject): + # This is a special branch for handling TorchBindObject + # for inductor's ExternalFallbackNode + # export_extern_kernel_node() is using this function to serialize arguments + arg_name = arg.get_name() + if arg_name is None: + raise AssertionError("Buffer must have valid name") + arg_val = arg.get_real_obj() + class_fqn = arg_val._type().qualified_name() + self.custom_objs[arg_name] = arg_val + return Argument.create(as_custom_obj=CustomObjArgument(arg_name, class_fqn)) + elif isinstance(arg, torch.SymInt): + # This is a special branch for handling SymInt args in inductor's + # ExternalFallbackNode. + # For regular FX graph, SymInt arg should be a fx.Node with + # self.is_sym_int_arg(arg) being true + return Argument.create(as_sym_int=SymIntArgument.create(as_name=str(arg))) + elif isinstance(arg, torch.SymFloat): + # This is a special branch for handling SymFloat args in inductor's + # ExternalFallbackNode. + # For regular FX graph, SymInt arg should be a fx.Node with + # self.is_sym_float_arg(arg) being true + return Argument.create( + as_sym_float=SymFloatArgument.create(as_name=str(arg)) + ) + elif type(arg) is bool: + return Argument.create(as_bool=arg) + elif type(arg) is str: + return Argument.create(as_string=arg) + elif type(arg) is int: + return Argument.create(as_int=arg) + elif type(arg) is float: + return Argument.create(as_float=arg) + elif type(arg) is complex: + return Argument.create( + as_complex=ComplexValue(real=arg.real, imag=arg.imag) + ) + elif arg is None: + return Argument.create(as_none=True) + elif isinstance(arg, dict): + serialized_dict = {} + for key, value in arg.items(): + if not isinstance(key, str): + raise SerializeError(f"Dict keys must be strings, got {type(key)}") + serialized_dict[key] = self.serialize_input(value) + return Argument.create(as_string_to_argument=serialized_dict) + elif isinstance(arg, (list, tuple)): + if len(arg) == 0: + if arg_type is not None: + if isinstance(arg_type, torch.OptionalType): + arg_type = arg_type.getElementType() # type: ignore[assignment] + if not isinstance(arg_type, torch.ListType): + raise AssertionError( + f"expected ListType, got {type(arg_type).__name__}" + ) + elem_type = arg_type.getElementType() + if isinstance(elem_type, torch.OptionalType): + elem_type = elem_type.getElementType() + + if isinstance(elem_type, torch.BoolType): + return Argument.create(as_bools=[]) + elif isinstance(elem_type, torch.IntType): + return Argument.create(as_ints=[]) + elif isinstance(elem_type, torch.FloatType): + return Argument.create(as_floats=[]) + elif isinstance(elem_type, torch.StringType): + return Argument.create(as_strings=[]) + elif isinstance(elem_type, torch.TensorType): + return Argument.create(as_tensors=[]) + elif isinstance(elem_type, torch.ListType): + inner_elem_type = elem_type.getElementType() + if isinstance(inner_elem_type, torch.IntType): + return Argument.create(as_int_lists=[]) + elif isinstance(inner_elem_type, torch.FloatType): + return Argument.create(as_float_lists=[]) + else: + raise SerializeError( + f"Empty list with nested type {elem_type} nyi." + ) + else: + # I believe empty symint lists default to ints, but + # please file an issue if this is not the case + raise SerializeError(f"Empty list with type {elem_type} nyi.") + else: + # We could serialize this by default to a tensor list. This + # is needed in the HOO case + log.warning( + "Unsure how to serialize the given empty list, " + "as we don't know what is the type of this argument. " + "Serializing it as a tensor list by default." + ) + return Argument.create(as_tensors=[]) + + if all(type(a) is bool for a in arg): + return Argument.create(as_bools=list(arg)) + elif all(type(a) is int for a in arg): + return Argument.create(as_ints=list(arg)) + elif all(type(a) is float for a in arg): + return Argument.create(as_floats=list(arg)) + elif all(type(a) is str for a in arg): + return Argument.create(as_strings=list(arg)) + elif all(self.is_inductor_sym_int_arg(a) for a in arg): + # This is a special branch for handling SymInt args in inductor's + # ExternalFallbackNode. + # For regular FX graph, SymInt arg should be a fx.Node + values = [] + for a in arg: + if isinstance(a, torch.SymInt): + values.append(SymIntArgument.create(as_name=str(a))) + elif type(a) is int: + values.append(SymIntArgument.create(as_int=a)) + return Argument.create(as_sym_ints=values) + elif all(isinstance(a, torch.SymFloat) for a in arg): + return Argument.create( + as_sym_floats=[SymFloatArgument.create(as_name=str(a)) for a in arg] + ) + elif all(self.is_sym_int_arg(a) for a in arg): + # list of sym_ints + values = [] + for a in arg: + if isinstance(a, torch.fx.Node): + values.append(SymIntArgument.create(as_name=a.name)) + elif type(a) is int: + values.append(SymIntArgument.create(as_int=a)) + return Argument.create(as_sym_ints=values) + elif all(self.is_sym_float_arg(a) for a in arg): + # list of sym_float + values = [] + for a in arg: + if isinstance(a, torch.fx.Node): + values.append(SymFloatArgument.create(as_name=a.name)) + elif isinstance(a, float): + values.append(SymFloatArgument.create(as_float=a)) + return Argument.create(as_sym_floats=values) + elif all(self.is_sym_bool_arg(a) for a in arg): + # list of sym_bools + values = [] + for a in arg: + if isinstance(a, torch.fx.Node): + values.append(SymBoolArgument.create(as_name=a.name)) + elif isinstance(a, bool): + values.append(SymBoolArgument.create(as_bool=a)) + return Argument.create(as_sym_bools=values) + elif all(isinstance(a, torch.fx.Node) for a in arg): + # list of tensors + arguments = [] + for a in arg: + if a.op == "get_attr": + raise SerializeError( + "getattr nodes containing tensors should not appear in the graph" + ) + arguments.append(TensorArgument(name=a.name)) + return Argument.create(as_tensors=arguments) + elif all(isinstance(a, (list, tuple)) for a in arg) and all( + all(isinstance(t, torch.fx.Node) for t in inner) for inner in arg + ): + # nested list of tensors (List[List[Tensor]]) + nested_arguments = [] + for inner_list in arg: + inner_arguments = [] + for node in inner_list: + if node.op == "get_attr": + raise SerializeError( + "getattr nodes containing tensors should not appear in the graph" + ) + inner_arguments.append(TensorArgument(name=node.name)) + nested_arguments.append(inner_arguments) + return Argument.create(as_nested_tensors=nested_arguments) + elif all(isinstance(a, (torch.fx.Node, type(None))) for a in arg): + # list of optional tensors + def serialize_optional_tensor_args(a): + if a is None: + return OptionalTensorArgument.create(as_none=True) + elif isinstance(a, torch.fx.Node): + return OptionalTensorArgument.create( + as_tensor=TensorArgument(name=a.name) + ) + else: + raise SerializeError(f"Unsupported list/tuple argument: {a}") + + return Argument.create( + as_optional_tensors=list(map(serialize_optional_tensor_args, arg)) + ) + elif all(isinstance(a, inductor_tensor_buffers) for a in arg): + # list of inductor buffers + return Argument.create( + as_tensors=[TensorArgument(name=a.get_name()) for a in arg], + ) + elif all( + isinstance(a, (*inductor_tensor_buffers, type(None))) for a in arg + ): + # list of inductor buffers as optional tensors + def serialize_optional_tensor_args(a): + if a is None: + return OptionalTensorArgument.create(as_none=True) + elif isinstance(a, inductor_tensor_buffers): + return OptionalTensorArgument.create( + as_tensor=TensorArgument(name=a.get_name()) + ) + else: + raise SerializeError(f"Unsupported list/tuple argument: {a}") + + return Argument.create( + as_optional_tensors=list(map(serialize_optional_tensor_args, arg)) + ) + elif all( + isinstance(a, (list, tuple)) and all(type(x) is int for x in a) + for a in arg + ): + # list of int lists (List[List[int]]) + return Argument.create(as_int_lists=[list(t) for t in arg]) + elif all( + isinstance(a, (list, tuple)) and all(isinstance(x, float) for x in a) + for a in arg + ): + # list of float lists (List[List[float]]) + return Argument.create(as_float_lists=[list(t) for t in arg]) + else: + raise SerializeError( + f"Unsupported list/tuple argument type: {[type(a) for a in arg]}" + ) + elif isinstance(arg, torch.dtype): + return Argument.create(as_scalar_type=_TORCH_TO_SERIALIZE_DTYPE[arg]) + elif isinstance(arg, torch.device): + return Argument.create(as_device=Device(type=arg.type, index=arg.index)) + elif isinstance(arg, torch.memory_format): + return Argument.create( + as_memory_format=_TORCH_TO_SERIALIZE_MEMORY_FORMAT[arg] + ) + elif isinstance(arg, torch.layout): + return Argument.create(as_layout=_TORCH_TO_SERIALIZE_LAYOUT[arg]) + elif isinstance(arg, torch._C.ScriptObject): + if not ( + arg._has_method("__getstate__") # type: ignore[attr-defined] + and arg._has_method("__setstate__") # type: ignore[attr-defined] + ): + raise SerializeError( + f"Unable to serialize custom class {arg}. Please define " + "serialization methods via def_pickle()." + ) + # Custom objects through torchind are serializable with pickle, + # through implementing the .def_pickle function. This should result + # in the object containing a __getstate__ and __setstate__ + # serialize/deserialize function. + custom_obj_name = f"_custom_obj_{len(self.custom_objs)}" + self.custom_objs[custom_obj_name] = arg + class_fqn = arg._type().qualified_name() # type: ignore[attr-defined] + return Argument.create( + as_custom_obj=CustomObjArgument(custom_obj_name, class_fqn) + ) + elif is_custom_class_obj(arg): + custom_obj_name = f"_custom_obj_{len(self.custom_objs)}" + self.custom_objs[custom_obj_name] = arg + class_fqn = get_opaque_type_name(type(arg)) + return Argument.create( + as_custom_obj=CustomObjArgument(custom_obj_name, class_fqn) + ) + elif isinstance(arg, (torch._ops.OpOverload, torch._ops.HigherOrderOperator)): + return Argument.create(as_operator=self.serialize_operator(arg)) + else: + raise SerializeError( + f"Unsupported argument type: {type(arg)} with schema arg_type {arg_type}" + ) + + def serialize_tensor_output(self, name, meta_val) -> TensorArgument: + if name in self.graph_state.tensor_values: + raise AssertionError(f"name {name!r} already in tensor_values") + self.graph_state.tensor_values[name] = serialize_tensor_meta(meta_val) + return TensorArgument(name=name) + + def serialize_sym_int_output(self, name, meta_val) -> SymIntArgument: + if name in self.graph_state.sym_int_values: + raise AssertionError(f"name {name!r} already in sym_int_values") + self.graph_state.sym_int_values[name] = serialize_sym_int(meta_val) + return SymIntArgument.create(as_name=name) + + def serialize_sym_float_output(self, name, meta_val) -> SymFloatArgument: + if name in self.graph_state.sym_float_values: + raise AssertionError(f"name {name!r} already in sym_float_values") + self.graph_state.sym_float_values[name] = serialize_sym_float(meta_val) + return SymFloatArgument.create(as_name=name) + + def serialize_sym_bool_output(self, name, meta_val) -> SymBoolArgument: + if name in self.graph_state.sym_bool_values: + raise AssertionError(f"name {name!r} already in sym_bool_values") + self.graph_state.sym_bool_values[name] = serialize_sym_bool(meta_val) + return SymBoolArgument.create(as_name=name) + + def serialize_input_spec(self, spec: ep.InputSpec) -> InputSpec: + log.debug("[serialize_input_spec] %s", spec) + if spec.kind == ep.InputKind.USER_INPUT: + if isinstance(spec.arg, ep.ConstantArgument): + if type(spec.arg.value) is int: + constant_spec = ConstantValue.create(as_int=spec.arg.value) + elif type(spec.arg.value) is bool: + constant_spec = ConstantValue.create(as_bool=spec.arg.value) + elif type(spec.arg.value) is str: + constant_spec = ConstantValue.create(as_string=spec.arg.value) + elif type(spec.arg.value) is float: + constant_spec = ConstantValue.create(as_float=spec.arg.value) + elif spec.arg.value is None: + constant_spec = ConstantValue.create(as_none=True) + else: + raise SerializeError( + f"Unhandled constant input {spec.arg.value} to serialize" + ) + return InputSpec.create( + constant_input=InputToConstantInputSpec( + name=spec.arg.name, value=constant_spec + ) + ) + else: + return InputSpec.create( + user_input=UserInputSpec(arg=self.serialize_argument_spec(spec.arg)) + ) + elif spec.kind == ep.InputKind.PARAMETER: + if spec.target is None: + raise AssertionError("spec.target should not be None for PARAMETER") + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return InputSpec.create( + parameter=InputToParameterSpec( + arg=TensorArgument(name=spec.arg.name), + parameter_name=spec.target, + ) + ) + elif spec.kind == ep.InputKind.BUFFER: + if spec.target is None: + raise AssertionError("spec.target should not be None for BUFFER") + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + if spec.persistent is None: + raise AssertionError("spec.persistent should not be None for BUFFER") + return InputSpec.create( + buffer=InputToBufferSpec( + arg=TensorArgument(name=spec.arg.name), + buffer_name=spec.target, + persistent=spec.persistent, + ) + ) + elif spec.kind == ep.InputKind.CONSTANT_TENSOR: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for CONSTANT_TENSOR" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return InputSpec.create( + tensor_constant=InputToTensorConstantSpec( + arg=TensorArgument(name=spec.arg.name), + tensor_constant_name=spec.target, + ) + ) + elif spec.kind == ep.InputKind.CUSTOM_OBJ: + if spec.target is None: + raise AssertionError("spec.target should not be None for CUSTOM_OBJ") + if not isinstance(spec.arg, ep.CustomObjArgument): + raise AssertionError( + f"expected CustomObjArgument, got {type(spec.arg).__name__}" + ) + return InputSpec.create( + custom_obj=InputToCustomObjSpec( + arg=CustomObjArgument( + name=spec.arg.name, class_fqn=spec.arg.class_fqn + ), + custom_obj_name=spec.target, + ) + ) + elif spec.kind == ep.InputKind.TOKEN: + if not isinstance(spec.arg, ep.TokenArgument): + raise AssertionError( + f"expected TokenArgument, got {type(spec.arg).__name__}" + ) + return InputSpec.create( + token=InputTokenSpec( + arg=TokenArgument(name=spec.arg.name), + ) + ) + else: + raise AssertionError(f"Unknown argument kind: {spec}") + + def serialize_output_spec(self, spec: ep.OutputSpec) -> OutputSpec: + log.debug("[serialize_output_spec] %s", spec) + if spec.kind == ep.OutputKind.USER_OUTPUT: + return OutputSpec.create( + user_output=UserOutputSpec(arg=self.serialize_argument_spec(spec.arg)) + ) + elif spec.kind == ep.OutputKind.LOSS_OUTPUT: + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + loss_output=LossOutputSpec(arg=TensorArgument(name=spec.arg.name)) + ) + elif spec.kind == ep.OutputKind.BUFFER_MUTATION: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for BUFFER_MUTATION" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + buffer_mutation=BufferMutationSpec( + arg=TensorArgument(name=spec.arg.name), + buffer_name=spec.target, + ) + ) + elif spec.kind == ep.OutputKind.PARAMETER_MUTATION: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for PARAMETER_MUTATION" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + parameter_mutation=ParameterMutationSpec( + arg=TensorArgument(name=spec.arg.name), + parameter_name=spec.target, + ) + ) + elif spec.kind == ep.OutputKind.GRADIENT_TO_PARAMETER: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for GRADIENT_TO_PARAMETER" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + gradient_to_parameter=GradientToParameterSpec( + arg=TensorArgument(name=spec.arg.name), + parameter_name=spec.target, + ) + ) + elif spec.kind == ep.OutputKind.GRADIENT_TO_USER_INPUT: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for GRADIENT_TO_USER_INPUT" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + gradient_to_user_input=GradientToUserInputSpec( + arg=TensorArgument(name=spec.arg.name), + user_input_name=spec.target, + ) + ) + elif spec.kind == ep.OutputKind.USER_INPUT_MUTATION: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for USER_INPUT_MUTATION" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + user_input_mutation=UserInputMutationSpec( + arg=TensorArgument(name=spec.arg.name), + user_input_name=spec.target, + ) + ) + elif spec.kind == ep.OutputKind.TOKEN: + if not isinstance(spec.arg, ep.TokenArgument): + raise AssertionError( + f"expected TokenArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + token=OutputTokenSpec( + arg=TokenArgument(name=spec.arg.name), + ) + ) + else: + raise AssertionError(f"Unknown argument kind: {spec}") + + def serialize_signature(self, sig: ep.ExportGraphSignature) -> GraphSignature: + log.debug("\n[serialize_signature]") + return GraphSignature( + input_specs=[self.serialize_input_spec(s) for s in sig.input_specs], + output_specs=[self.serialize_output_spec(s) for s in sig.output_specs], + ) + + def serialize_argument_spec(self, x: ep.ArgumentSpec) -> Argument: + if isinstance(x, ep.TensorArgument): + return Argument.create(as_tensor=TensorArgument(name=x.name)) + elif isinstance(x, ep.SymIntArgument): + return Argument.create(as_sym_int=SymIntArgument.create(as_name=x.name)) + elif isinstance(x, ep.SymFloatArgument): + return Argument.create(as_sym_float=SymFloatArgument.create(as_name=x.name)) + elif isinstance(x, ep.ConstantArgument): + return self.serialize_input(x.value) + elif isinstance(x, ep.CustomObjArgument): + return Argument.create( + as_custom_obj=CustomObjArgument(name=x.name, class_fqn=x.class_fqn) + ) + else: + raise AssertionError("TODO") + + def serialize_treespec(self, treespec: pytree.TreeSpec) -> str: + # We want to additionally save all the field names of the namedtuples in + # case users want to check that the treespec types are equivalent + def store_namedtuple_fields(ts: pytree.TreeSpec) -> None: + if ts.type is None: + return + if ts.type is namedtuple or pytree.is_namedtuple_class(ts.type): + serialized_type_name = pytree.SUPPORTED_SERIALIZED_TYPES[ + ts.context + ].serialized_type_name + if serialized_type_name in self.treespec_namedtuple_fields: + field_names = self.treespec_namedtuple_fields[ + serialized_type_name + ].field_names + if field_names != ts.context._fields: + raise SerializeError( + f"The given TreeSpec's namedtuple type {ts.context} " + f"was found to have field names {ts.context._fields} " + f"but somehow previously was found to have field names {field_names}." + ) + else: + self.treespec_namedtuple_fields[serialized_type_name] = ( + NamedTupleDef(field_names=ts.context._fields) + ) + + for child in ts.children(): + store_namedtuple_fields(child) + + serialized_treespec = treespec_dumps(treespec, TREESPEC_VERSION) + store_namedtuple_fields(treespec) + return serialized_treespec + + def serialize_module_call_signature( + self, module_call_signature: ep.ModuleCallSignature + ) -> ModuleCallSignature: + log.debug("[serialize_module_call_signature] %s", module_call_signature) + return ModuleCallSignature( + inputs=[ + self.serialize_argument_spec(x) for x in module_call_signature.inputs + ], + outputs=[ + self.serialize_argument_spec(x) for x in module_call_signature.outputs + ], + in_spec=self.serialize_treespec(module_call_signature.in_spec), + out_spec=self.serialize_treespec(module_call_signature.out_spec), + forward_arg_names=( + names if (names := module_call_signature.forward_arg_names) else None + ), + ) + + def serialize_module_call_graph( + self, module_call_graph: list[ep.ModuleCallEntry] + ) -> list[ModuleCallEntry]: + log.debug("\n[serialize_module_call_graph]") + return [ + ModuleCallEntry( + fqn=entry.fqn, + signature=( + self.serialize_module_call_signature(entry.signature) + if entry.signature + else None + ), + ) + for entry in module_call_graph + ] + + def serialize_outputs(self, node: torch.fx.Node) -> list[Argument]: + """For a given node, return the dataclass representing its output values. + + [NOTE: Multiple outputs] We handle aggregates differently than FX. For + FX, it looks like: + + x = call_function("multiple_return", ...) + element0 = call_function(getitem, x, 0) + foo = call_function("use_output", element0) + + We do not want the intermediate `getitem` call, so our serialized thing looks like: + + element0, element1, element2 = call_function("multiple_return", ...) + foo = call_function("use_output", element0) + + We want names to be consistent across these two schemes, so that we can + mostly reuse the names coming from FX. This function computes a mapping from + the FX representation to our representation, preserving the names. + """ + + def _is_single_tensor_list_return(target: Any) -> bool: + schema = _get_schema_from_target(target) + returns = schema.returns + + if len(returns) != 1: + return False + return_type = returns[0].real_type + return isinstance(return_type, torch.ListType) and isinstance( + return_type.getElementType(), torch.TensorType + ) + + if not ( + node.op == "call_function" + and isinstance( + node.target, (torch._ops.OpOverload, *_registered_extension_types()) + ) + ): + raise AssertionError( + f"expected call_function with OpOverload or registered extension type, " + f"got {node.op} with {type(node.target).__name__}" + ) + + schema = _get_schema_from_target(node.target) + returns = schema.returns + + if len(returns) == 0: + return [] + + meta_val = node.meta["val"] + + # Check single value return + if _is_single_tensor_list_return(node.target): + # e.g "-> Tensor[]" + tensor_args = [] + for idx, meta in enumerate(meta_val): + name = self._output_node_name_at_index(node, idx) + tensor_args.append(self.serialize_tensor_output(name, meta)) + return [Argument.create(as_tensors=tensor_args)] + elif len(returns) == 1: + return [self.serialize_output(node.name, meta_val)] + + # There are a two possibilities at this point: + # - This operator returns a tuple of Tensors, e.g. "-> (Tensor, Tensor)" + # - This operator returns a tuple of mixed of Tensor and Tensors, e.g. "-> (Tensor, Tensor[])" + # + # Either way, start by gathering a list of TensorArguments with the correct names. + # For consistent naming with FX, consult the downstream `getitem` node and + # make sure our outputs have the same name. + + output_arguments = [] + for idx, (meta, return_schema) in enumerate(zip(meta_val, returns)): + if meta is None: + if not isinstance( + return_schema.real_type, (torch.OptionalType, torch.TensorType) + ): + raise AssertionError( + f"expected OptionalType or TensorType, got {type(return_schema.real_type).__name__}" + ) + # When the return type is annotated as Tensor type, the op can also return an + # undefined Tensor which will be implicitly converted to None in Python. + output_arguments.append(Argument.create(as_none=True)) + elif isinstance(meta, torch.Tensor): + if not isinstance( + return_schema.real_type, (torch.OptionalType, torch.TensorType) + ): + raise AssertionError( + f"expected OptionalType or TensorType, got {type(return_schema.real_type).__name__}" + ) + name = self._output_node_name_at_index(node, idx) + output_arguments.append(self.serialize_output(name, meta)) + elif isinstance(meta, list): + # for List[Tensor] return type + if not ( + isinstance(return_schema.real_type, torch.ListType) + and isinstance( + return_schema.real_type.getElementType(), torch.TensorType + ) + ): + raise AssertionError( + f"expected ListType with TensorType element, got {type(return_schema.real_type).__name__}" + ) + user_node = self._output_node_at_index(node, idx) + args = [] + for i, m in enumerate(meta): + if m is None: + continue + if user_node is None: + name = f"{node.name}_unused_{idx}_{i}" + else: + name = self._output_node_name_at_index(user_node, i) + args.append(self.serialize_tensor_output(name, m)) + output_arguments.append(Argument.create(as_tensors=args)) + elif isinstance(meta, (int, SymInt, float, SymFloat)): + user_node_name = self._output_node_name_at_index(node, idx) + output_arguments.append(self.serialize_output(user_node_name, meta)) + else: + raise ValueError( + f"Unhandled output type {type(meta)} from node {node.format_node()}" + ) + + return output_arguments + + def serialize_hoo_outputs(self, node: torch.fx.Node) -> list[Argument]: + """ + For serializing HOO outputs since HOOs do not have a schema. + """ + meta_val = node.meta["val"] + + if isinstance(meta_val, tuple): + outputs = [] + for i, element_meta_val in enumerate(meta_val): + user_node = self._output_node_at_index(node, i) + if isinstance(element_meta_val, list): + # e.g "-> Tensor[]" + tensors = [] + for j, m in enumerate(element_meta_val): + if not isinstance(m, torch.Tensor): + raise SerializeError( + f"Serialize list output with type {type(m)} nyi" + ) + + if user_node is None: + name = f"{node.name}_unused_{i}_{j}" + else: + name = self._output_node_name_at_index(user_node, j) + tensors.append(self.serialize_tensor_output(name, m)) + outputs.append(Argument.create(as_tensors=tensors)) + + else: + name = ( + user_node.name + if user_node is not None + else f"{node.name}_unused_{i}" + ) + + outputs.append(self.serialize_output(name, element_meta_val)) + + return outputs + elif isinstance(meta_val, dict): + tensor_args = [] + # use the dict key as the idx + for idx, meta in meta_val.items(): + if not isinstance(meta, torch.Tensor): + raise SerializeError( + f"Serialize list output with type {type(meta)} nyi" + ) + name = self._output_node_name_at_index(node, idx) + tensor_args.append(self.serialize_tensor_output(name, meta)) + return [Argument.create(as_tensors=tensor_args)] + else: + return [self.serialize_output(node.name, meta_val)] + + def serialize_output(self, name: str, meta_val: Any) -> Argument: + # Check single value return + if meta_val is None: + return Argument.create(as_none=True) + if isinstance(meta_val, torch.Tensor): + # e.g "-> Tensor" + return Argument.create( + as_tensor=self.serialize_tensor_output(name, meta_val) + ) + elif isinstance(meta_val, (bool, torch.SymBool)): + # e.g "-> SymBool" + return Argument.create( + as_sym_bool=self.serialize_sym_bool_output(name, meta_val) + ) + elif isinstance(meta_val, (int, torch.SymInt)): + # e.g "-> SymInt" + if isinstance(meta_val, bool): + raise AssertionError( + "meta_val should not be bool when returning SymInt" + ) + return Argument.create( + as_sym_int=self.serialize_sym_int_output(name, meta_val) + ) + elif isinstance(meta_val, (float, torch.SymFloat)): + # e.g "-> SymFloat" + return Argument.create( + as_sym_float=self.serialize_sym_float_output(name, meta_val) + ) + + # list outputs should've been handled earlier + raise SerializeError(f"Unable to serialize output {meta_val}") + + def _handle_getitem_users(self, node: torch.fx.Node) -> list[TensorArgument]: + meta_val = node.meta["val"] + + idx_to_name = {} + for user in node.users: + if user.target is not operator.getitem: + raise AssertionError(f"User node {user} of {node} is incorrect") + # pyrefly: ignore [unsupported-operation] + idx_to_name[user.args[1]] = user.name + + for idx, _ in enumerate(meta_val): + # FX does not emit a getitem node for any outputs that are unused. + # However, we need a name for them so that the number of outputs will + # correctly match the schema. Just assign a dummy name. + if idx not in idx_to_name: + # pyrefly: ignore [unsupported-operation] + idx_to_name[idx] = f"{node.name}_unused_{idx}" + + arg_list = [] + for i, element_meta_val in enumerate(meta_val): + arg_list.append( + # pyrefly: ignore [bad-index] + self.serialize_tensor_output(idx_to_name[i], element_meta_val) + ) + + return arg_list + + def serialize_graph(self, graph_module: torch.fx.GraphModule) -> Graph: + if not isinstance(graph_module, torch.fx.GraphModule): + raise AssertionError( + f"expected GraphModule, got {type(graph_module).__name__}" + ) + log.debug( + "[serialize_graph]\n\n%s", graph_module.print_readable(print_output=False) + ) + + for node in graph_module.graph.nodes: + try: + getattr(self, f"handle_{node.op}")(node) + except Exception as e: + raise SerializeError( + f"Failed serializing node {node} in graph: {node.format_node()}\n Original exception {traceback.format_exc()}" + ) from e + + return Graph( + inputs=self.graph_state.inputs, + nodes=self.graph_state.nodes, + tensor_values=self.graph_state.tensor_values, + sym_int_values=self.graph_state.sym_int_values, + sym_float_values=self.graph_state.sym_float_values, + sym_bool_values=self.graph_state.sym_bool_values, + custom_obj_values=self.graph_state.custom_obj_values, + outputs=self.graph_state.outputs, + is_single_tensor_return=self.graph_state.is_single_tensor_return, + ) + + def serialize_graph_module_metadata(self, meta: dict[str, Any]): + ret = {} + if custom := meta.get("custom"): + log.debug("\n[serialize_graph_module_metadata] %s", custom) + try: + ret["custom"] = json.dumps(custom) + except Exception as e: + raise SerializeError( + f"Failed to serialize custom metadata for graph with error {e}" + ) from e + + return ret + + def serialize(self, graph_module: torch.fx.GraphModule) -> GraphModule: + log.debug("\n[serialize]") + graph = self.serialize_graph(graph_module) + + return GraphModule( + graph=graph, + signature=self.serialize_signature(self.graph_signature), + module_call_graph=self.serialize_module_call_graph(self.module_call_graph), + metadata=self.serialize_graph_module_metadata(graph_module.meta), + treespec_namedtuple_fields=self.treespec_namedtuple_fields, + ) + + +@final +class ExportedProgramSerializer(metaclass=Final): + def __init__( + self, + opset_version: dict[str, int] | None = None, + pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL, + ): + self.opset_version: dict[str, int] = {} + if opset_version: + self.opset_version.update(opset_version) + if "aten" not in self.opset_version: + self.opset_version["aten"] = torch._C._get_max_operator_version() + + self.pickle_protocol = pickle_protocol + + def serialize( + self, + exported_program: ep.ExportedProgram, + *, + serialize_state_dict: bool = True, + serialize_constants: bool = True, + serialize_example_inputs: bool = True, + ) -> _SerializedProgram: + """ + Args: + exported_program: Exported Program to serialize + """ + exported_program.validate() + + gm_serializer = GraphModuleSerializer( + exported_program.graph_signature, exported_program.module_call_graph + ) + serialized_graph_module = gm_serializer.serialize(exported_program.graph_module) + serialized_range_constraints = serialize_range_constraints( + exported_program.range_constraints + ) + + # TODO: Directly serialize exported_program.constants once + # CustomClassHolders get stored in the ExportedProgram rather than in + # the graph + constants: dict[str, Any] = gm_serializer.custom_objs.copy() + for n, t in exported_program.constants.items(): + if n in constants: + raise AssertionError(f"constant name {n!r} already exists in constants") + constants[n] = t + + serialized_ep = ExportedProgram( + graph_module=serialized_graph_module, + opset_version=self.opset_version, + range_constraints=serialized_range_constraints, + schema_version=SchemaVersion( + major=SCHEMA_VERSION[0], + minor=SCHEMA_VERSION[1], + ), + verifiers=[v.dialect for v in exported_program.verifiers], + torch_version=torch.__version__, + guards_code=exported_program._guards_code, + ) + + # Test canonical form is well defined. + canonicalize(serialized_ep, set(constants.keys())) + + # Proxy cannot be dumped, so we remove them. + new_state_dict = remove_proxy_from_state_dict( + exported_program.state_dict, in_place=False + ) + serialized_state_dict = b"" + if serialize_state_dict: + serialized_state_dict = serialize_torch_artifact( + new_state_dict, self.pickle_protocol + ) + + serialized_constants = b"" + if serialize_constants: + serialized_constants = serialize_torch_artifact( + constants, self.pickle_protocol + ) + + serialized_example_inputs = b"" + if serialize_example_inputs: + serialized_example_inputs = serialize_torch_artifact( + exported_program.example_inputs, self.pickle_protocol + ) + + return _SerializedProgram( + serialized_ep, + serialized_state_dict, + serialized_constants, + serialized_example_inputs, + ) + + +@final +class GraphModuleDeserializer(metaclass=Final): + @dataclasses.dataclass + class Result: + graph_module: torch.fx.GraphModule + signature: ep.ExportGraphSignature + module_call_graph: list[ep.ModuleCallEntry] + names_to_symbols: dict[str, sympy.Symbol] + state_dict: dict[str, torch.Tensor | torch.nn.Parameter] + constants: dict[str, _ConstantAttributeType] + example_inputs: tuple[tuple[torch.Tensor, ...], dict[str, Any]] | None + + def __init__(self) -> None: + self.serialized_name_to_node: dict[str, torch.fx.Node] = {} + self.serialized_name_to_meta: LazyMap = LazyMap() # str -> MetaType + self.graph = torch.fx.Graph() + self.module = torch.nn.Module() + + @contextmanager + def save_graph_module(self) -> Iterator[None]: + saved = ( + self.graph, + self.module, + self.serialized_name_to_node, + self.serialized_name_to_meta, + self.unbacked_symbols, + ) + self.graph = torch.fx.Graph() + self.module = torch.nn.Module() + self.serialized_name_to_node = {} + self.serialized_name_to_meta = LazyMap() + self.unbacked_symbols: set[sympy.Symbol] = set() + try: + yield + finally: + ( + self.graph, + self.module, + self.serialized_name_to_node, + self.serialized_name_to_meta, + self.unbacked_symbols, + ) = saved + + def deserialize_extension_operator(self, serialized_target: str): + namespace, op_name = serialized_target.split(":") + namespace = namespace[1:] # starting with # + handler = _deserialization_registry[namespace] + return handler.from_op_name(op_name) + + def deserialize_operator(self, serialized_target: str): + if serialized_target.startswith( + "_operator" + ): # TODO(zhxchen17) Follow up on this. + module = operator + serialized_target_names = serialized_target.split(".")[1:] + elif serialized_target.startswith("torch"): + module = torch # type: ignore[misc] + serialized_target_names = serialized_target.split(".")[1:] + elif serialized_target.startswith("math"): + module = math # type: ignore[misc] + serialized_target_names = serialized_target.split(".")[1:] + elif serialized_target.startswith("#"): + return self.deserialize_extension_operator(serialized_target) + else: # TODO(zhxchen17) Don't catch all here. + return serialized_target + + target = module + for name in serialized_target_names: + if not hasattr(target, name): + return serialized_target + else: + target = getattr(target, name) + return target + + def _parse_sym_expr( + self, expr_str: str, hint: int | bool | float | None = None + ) -> sympy.Expr: + """ + Parses and does bottom-up processing of sympy.Expr nodes, + populating ShapeEnv & caching symbols as needed. + """ + + def _process_sym_expr( + sym: sympy.Expr, hint: int | bool | float | None = None + ) -> sympy.Expr: + if sym.is_Integer or sym.is_Float or sym.is_Boolean: # base case + return sym + else: # recursive case + # important to use str(expr) and not _print_sympy(), + # str(expr) is key for self.symbol_name_to_range + expr_str = str(sym) + for arg in sym.args: + self._parse_sym_expr(arg) + # symbol caching + if expr_str in self.symbol_name_to_symbol: + sym = self.symbol_name_to_symbol[expr_str] + else: + self.symbol_name_to_symbol[expr_str] = sym + if isinstance(sym, sympy.Symbol) and symbolic_shapes.symbol_is_type( + sym, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT) + ): + self.unbacked_symbols.add(sym) + # hints + if hint is not None and sym not in self.shape_env.backed_var_to_val: + self.shape_env.add_backed_var_to_val(sym, hint) # type: ignore[arg-type] + # ValueRanges + if vr := self.symbol_name_to_range.get(expr_str): + self.shape_env.constrain_symbol_range( + sym, + compiler_min=vr.lower, # type: ignore[arg-type] + compiler_max=vr.upper, # type: ignore[arg-type] + ) + # ShapeEnv meta + if isinstance(sym, sympy.Symbol): + self.shape_env.var_to_stack[sym] = CapturedTraceback.extract(skip=1) + return sym + + expr = sympy.sympify( + expr_str, + locals={**self.sympy_functions, **self.symbol_name_to_symbol}, + ) + return _process_sym_expr(expr, hint) + + def deserialize_sym_int(self, s: SymInt) -> int | torch.SymInt: + val = s.value + if s.type == "as_expr": + if val.hint is None: + hint = None + else: + if val.hint.type != "as_int": + raise AssertionError( + f"expected hint type 'as_int', got {val.hint.type!r}" + ) + hint = val.hint.value + + sym = self._parse_sym_expr(val.expr_str, hint) + return self.shape_env.create_symintnode(sym, hint=hint) + elif s.type == "as_int": + if type(val) is not int: + raise AssertionError(f"expected int, got {type(val).__name__}") + return val + else: + raise SerializeError( + f"SymInt has invalid field type {s.type} with value {s.value}" + ) + + def deserialize_sym_float(self, s: SymFloat) -> float | torch.SymFloat: + val = s.value + if s.type == "as_expr": + hint = val.hint.as_float if val.hint else None + sym = self._parse_sym_expr(val.expr_str, hint) + return self.shape_env.create_symfloatnode(sym, hint=hint) + elif s.type == "as_float": + if not isinstance(val, float): + raise AssertionError(f"expected float, got {type(val).__name__}") + return val + else: + raise SerializeError( + f"SymFloat has invalid field type {s.type} with value {s.value}" + ) + + def deserialize_sym_bool(self, s: SymBool) -> bool | torch.SymBool: + val = s.value + if s.type == "as_expr": + expr = self._parse_sym_expr(val.expr_str) + return self.shape_env.create_symboolnode(expr) + elif s.type == "as_bool": + if not isinstance(val, bool): + raise AssertionError(f"expected bool, got {type(val).__name__}") + return val + else: + raise SerializeError( + f"SymBool has invalid field type {s.type} with value {s.value}" + ) + + def deserialize_tensor_meta( + self, + tensor_meta: TensorMeta, + ) -> FakeTensor: + with self.fake_tensor_mode: + return cast( + FakeTensor, + torch.empty_strided( + tuple(self.deserialize_sym_int(val) for val in tensor_meta.sizes), # type: ignore[misc] + tuple(self.deserialize_sym_int(val) for val in tensor_meta.strides), # type: ignore[misc] + device=deserialize_device(tensor_meta.device), + dtype=_SERIALIZE_TO_TORCH_DTYPE[tensor_meta.dtype], + requires_grad=tensor_meta.requires_grad, + ), + ) + + def deserialize_script_obj_meta( + self, script_obj_meta: CustomObjArgument + ) -> ep.CustomObjArgument: + return ep.CustomObjArgument( + name=script_obj_meta.name, + class_fqn=script_obj_meta.class_fqn, + ) + + def deserialize_graph_output(self, output) -> torch.fx.Node | int | None: + if output.type == "as_tensor": + return self.serialized_name_to_node[output.as_tensor.name] + elif output.type == "as_sym_int": + return self.serialized_name_to_node[output.as_sym_int.as_name] + elif output.type == "as_sym_bool": + return self.serialized_name_to_node[output.as_sym_bool.as_name] + elif output.type == "as_sym_float": + return self.serialized_name_to_node[output.as_sym_float.as_name] + elif output.type == "as_int": + return output.as_int + elif output.type == "as_float": + return output.as_float + elif output.type == "as_bool": + return output.as_bool + elif output.type == "as_none": + return None + else: + raise SerializeError(f"Unable to deserialize output node {output}") + + def deserialize_graph(self, serialized_graph: Graph) -> torch.fx.Graph: + log.debug("\n[deserialize_graph]") + + # Handle the tensor metas. + for name, tensor_value in serialized_graph.tensor_values.items(): + log.debug("[deserialize_tensor_meta] %s (input): %s", name, tensor_value) + self.serialized_name_to_meta[name] = ( + lambda v=tensor_value: self.deserialize_tensor_meta(v) + ) + + for name, sym_int_value in serialized_graph.sym_int_values.items(): + log.debug("[deserialize_sym_int] %s (input): %s", name, sym_int_value) + self.serialized_name_to_meta[name] = ( + lambda v=sym_int_value: self.deserialize_sym_int(v) + ) + + for name, sym_float_value in serialized_graph.sym_float_values.items(): + log.debug("[deserialize_sym_float] %s (input): %s", name, sym_float_value) + self.serialized_name_to_meta[name] = ( + lambda v=sym_float_value: self.deserialize_sym_float(v) + ) + + for name, sym_bool_value in serialized_graph.sym_bool_values.items(): + log.debug("[deserialize_sym_bool] %s (input): %s", name, sym_bool_value) + self.serialized_name_to_meta[name] = ( + lambda v=sym_bool_value: self.deserialize_sym_bool(v) + ) + + for name, script_obj_meta in serialized_graph.custom_obj_values.items(): + log.debug("[deserialize_script_obj_meta] %s", script_obj_meta) + self.serialized_name_to_meta[name] = ( + lambda v=script_obj_meta: self.deserialize_script_obj_meta(v) + ) + + log.debug("\n[deserialize graph nodes]") + # Inputs: convert to placeholder nodes in FX. + for i, input_ in enumerate(serialized_graph.inputs): + log.debug("[deserialize input] %s", input_) + if input_.type in ("as_tensor", "as_custom_obj"): + node_name = input_.value.name + placeholder_node = self.graph.placeholder(node_name) + # FX might declare a name illegal (e.g. some nn.Modules use "input" as forward() arguments) + # we will overwrite it + placeholder_node.name = node_name + self.sync_fx_node(node_name, placeholder_node) + elif input_.type == "as_sym_int": + if input_.value.type == "as_name": + node_name = input_.value.as_name + placeholder_node = self.graph.placeholder(node_name) + # FX might declare a name illegal (e.g. some nn.Modules use "input" as forward() arguments) + # we will overwrite it + placeholder_node.name = node_name + self.sync_fx_node(node_name, placeholder_node) + else: + raise SerializeError( + f"Deserializing a constant symint {input_.value} as an input" + ) + elif input_.type in ( + "as_int", + "as_float", + "as_bool", + "as_none", + "as_string", + ): + node_name = self.signature.input_specs[i].arg.name or f"arg{i}" + placeholder_node = self.graph.placeholder(node_name) + placeholder_node.meta["val"] = self.deserialize_input(input_) + else: + raise SerializeError(f"Invalid input type {input_}") + + # Nodes: convert to call_function nodes. + for serialized_node in serialized_graph.nodes: + try: + target = self.deserialize_operator(serialized_node.target) + self.deserialize_node(serialized_node, target) + + except Exception as e: + raise SerializeError( + f"Failed deserializing node {serialized_node}\n Original exception {traceback.format_exc()}" + ) from e + + # Outputs: convert to a single `output` node. + outputs = [] + for output in serialized_graph.outputs: + log.debug("[deserialize output] %s", output) + outputs.append(self.deserialize_graph_output(output)) + + if serialized_graph.is_single_tensor_return: + if len(outputs) != 1: + raise AssertionError( + f"expected single output for single_tensor_return, got {len(outputs)}" + ) + outputs = outputs[0] # type: ignore[assignment] + else: + outputs = tuple(outputs) # type: ignore[assignment] + + output_node = self.graph.output(outputs) + + if serialized_graph.is_single_tensor_return: + first_arg = output_node.args[0] + if not isinstance(first_arg, torch.fx.Node): + raise AssertionError( + f"Expected Node for single tensor return, got {type(first_arg)}" + ) + output_node.meta["val"] = first_arg.meta["val"] + else: + first_arg = output_node.args[0] + if not isinstance(first_arg, (tuple, list)): + raise AssertionError( + f"Expected tuple/list for multi tensor return, got {type(first_arg)}" + ) + output_node.meta["val"] = tuple( + arg.meta["val"] if isinstance(arg, torch.fx.Node) else arg + for arg in first_arg + ) + + # recompute unbacked bindings + for node in self.graph.nodes: + if (val := node.meta.get("val")) is not None and ( + unbacked_bindings := symbolic_shapes._free_unbacked_symbols_with_path( + val, + (), + shape_env=self.shape_env, + pending=self.unbacked_symbols, + simplify=True, + ) + ): + node.meta["unbacked_bindings"] = unbacked_bindings + + if len(self.unbacked_symbols) != 0: + raise AssertionError( + f"expected no unbacked symbols, got {len(self.unbacked_symbols)}: {self.unbacked_symbols}" + ) + return self.graph + + def deserialize_node(self, serialized_node: Node, target: Callable) -> None: + def _is_single_tensor_return(target) -> bool: + schema = _get_schema_from_target(target) + returns = schema.returns + return len(returns) == 1 and isinstance( + returns[0].real_type, torch.TensorType + ) + + if ( + target in _SYM_OPS + or target + == torch.ops.aten.item.default # this can produce either SymInt or SymBool + ): + # BC: use serialized_node.name if available, otherwise fallback to original logic + name = ( + serialized_node.name + if serialized_node.name + else serialized_node.outputs[0].value.as_name + ) + args = self.deserialize_sym_op_inputs(serialized_node.inputs) + + fx_node = self.graph.create_node("call_function", target, args, {}, name) + self.deserialize_sym_op_outputs(serialized_node, fx_node) + elif ( + target + is torch._higher_order_ops.triton_kernel_wrap.triton_kernel_wrapper_functional + ): + raise SerializeError( + "deserialize nyi for torch._higher_order_ops.triton_kernel_wrap.triton_kernel_wrapper_functional" + ) + elif isinstance(target, torch._ops.HigherOrderOperator): + args, kwargs = self.deserialize_hoo_inputs(serialized_node.inputs) + metadata = self.deserialize_metadata(serialized_node.metadata) + for x in (*args, *kwargs.values()): + if isinstance(x, torch.fx.Node) and x.op == "get_attr": + # this means that we have deserialized a graph argument, but + # unfortunately the schema for it does not include metadata; + # so we reuse the metadata of the HOP call for such arguments + x.meta.update(metadata) + # If a serialized HOP node has a length=1 outputs of type `as_tensor``. + # There could be two cases: + # (1) The HOP node returns a single tensor + # (2) The HOP node returns a tuple containing a single tensor + # We distinguish (1) and (2) by the `is_single_tensor_return` + # field in the schema of Node + # For BC, getattr() will return True if `is_single_tensor_return` doesn't + # exist. This is because prior to adding `is_single_tensor_return`, + # only (1) could happen as we handle (2) with type `as_tensors` + # BC: use serialized_node.name if available, otherwise fallback to original logic + if serialized_node.name: + name = serialized_node.name + else: + name = ( + serialized_node.outputs[0].as_tensor.name + if len(serialized_node.outputs) == 1 + and hasattr(serialized_node.outputs[0], "as_tensor") + and getattr(serialized_node, "is_hop_single_tensor_return", True) + else None + ) + fx_node = self.graph.create_node( + "call_function", target, args, kwargs, name + ) + self.deserialize_outputs(serialized_node, fx_node) + fx_node.meta.update(metadata) + + elif isinstance( + target, (torch._ops.OpOverload, *_registered_extension_types()) + ): + # For convenience: if this node returns a single tensor, name the + # newly-created node after it. This ensures that these tensor values + # have names that are consistent with serialized. + # BC: use serialized_node.name if available, otherwise fallback to original logic + if serialized_node.name: + name = serialized_node.name + else: + name = ( + serialized_node.outputs[0].as_tensor.name + if _is_single_tensor_return(target) + else None # FX will generate a name for us. + ) + + args, kwargs = self.deserialize_inputs(target, serialized_node) + fx_node = self.graph.create_node( + "call_function", target, args, kwargs, name + ) + self.deserialize_outputs(serialized_node, fx_node) + elif callable(target): + # Handle predispatch wrapper functions (vmap, JVP, etc.) + args, kwargs = self.deserialize_hoo_inputs(serialized_node.inputs) + name = serialized_node.name if serialized_node.name else None + fx_node = self.graph.create_node( + "call_function", target, args, kwargs, name + ) + self.deserialize_outputs(serialized_node, fx_node) + else: + _additional_msg = ( + ( + f"We failed to resolve {target} to an operator. " + + "If it's a custom op/custom triton op, this is usually because the custom op is not registered" + + " when deserializing. Please import the custom op to register it before deserializing." + + " Otherwise, please file an issue on github." + ) + if isinstance(target, str) + else "" + ) + raise SerializeError( + _additional_msg + + f" Unsupported target type for node {serialized_node}: {type(target)}." + ) + + fx_node.meta.update(self.deserialize_metadata(serialized_node.metadata)) + log.debug( + "[deserialize_node] %s: %s(%s, {%s}) -> %s", + fx_node.name, + fx_node.target, + fx_node.args, + fx_node.kwargs, + fx_node.meta.get("val"), + ) + + # handle ShapeEnv asserts + if target is torch.ops.aten._assert_scalar.default: + if not isinstance((arg := fx_node.args[0]), bool): + expr = arg.meta["val"] # type: ignore[union-attr] + if isinstance(expr, torch.SymBool): + self.shape_env.guard_or_defer_runtime_assert( + expr.node.expr, "", fx_node + ) + elif target is torch.ops.aten.sym_constrain_range_for_size.default: + sym = fx_node.args[0].meta["val"] # type: ignore[union-attr] + if isinstance(sym, torch.SymInt): + self.shape_env._constrain_range_for_size(sym.node.expr) + + # handle nn_module_stack; serialization throws away empty dicts + if ( + fx_node.op not in ["placeholder", "output"] + and "nn_module_stack" not in fx_node.meta + ): + fx_node.meta["nn_module_stack"] = {} + + def deserialize_input_spec(self, i: InputSpec) -> ep.InputSpec: + log.debug("[deserialize_input_spec] %s", i) + if i.type == "user_input": + return ep.InputSpec( + kind=ep.InputKind.USER_INPUT, + arg=self.deserialize_argument_spec(i.user_input.arg), + target=None, + ) + elif i.type == "parameter": + return ep.InputSpec( + kind=ep.InputKind.PARAMETER, + arg=ep.TensorArgument(name=i.parameter.arg.name), + target=i.parameter.parameter_name, + ) + elif i.type == "buffer": + return ep.InputSpec( + kind=ep.InputKind.BUFFER, + arg=ep.TensorArgument(name=i.buffer.arg.name), + target=i.buffer.buffer_name, + persistent=i.buffer.persistent, + ) + elif i.type == "tensor_constant": + return ep.InputSpec( + kind=ep.InputKind.CONSTANT_TENSOR, + arg=ep.TensorArgument(name=i.tensor_constant.arg.name), + target=i.tensor_constant.tensor_constant_name, + ) + elif i.type == "custom_obj": + return ep.InputSpec( + kind=ep.InputKind.CUSTOM_OBJ, + arg=ep.CustomObjArgument( + name=i.custom_obj.arg.name, class_fqn=i.custom_obj.arg.class_fqn + ), + target=i.custom_obj.custom_obj_name, + ) + elif i.type == "token": + return ep.InputSpec( + kind=ep.InputKind.TOKEN, + arg=ep.TokenArgument(name=i.token.arg.name), + target=None, + ) + elif i.type == "constant_input": + return ep.InputSpec( + kind=ep.InputKind.USER_INPUT, + arg=ep.ConstantArgument( + name=i.constant_input.name, + value=self.deserialize_constant_input(i.constant_input.value), + ), + target=None, + ) + else: + raise AssertionError(f"Unknown input spec {i}") + + def deserialize_output_spec(self, o: OutputSpec) -> ep.OutputSpec: + log.debug("[deserialize_output_spec] %s", o) + if o.type == "user_output": + return ep.OutputSpec( + kind=ep.OutputKind.USER_OUTPUT, + arg=self.deserialize_argument_spec(o.user_output.arg), + target=None, + ) + elif o.type == "loss_output": + return ep.OutputSpec( + kind=ep.OutputKind.LOSS_OUTPUT, + arg=ep.TensorArgument(name=o.loss_output.arg.name), + target=None, + ) + elif o.type == "buffer_mutation": + return ep.OutputSpec( + kind=ep.OutputKind.BUFFER_MUTATION, + arg=ep.TensorArgument(name=o.buffer_mutation.arg.name), + target=o.buffer_mutation.buffer_name, + ) + elif o.type == "parameter_mutation": + return ep.OutputSpec( + kind=ep.OutputKind.PARAMETER_MUTATION, + arg=ep.TensorArgument(name=o.parameter_mutation.arg.name), + target=o.parameter_mutation.parameter_name, + ) + elif o.type == "gradient_to_parameter": + return ep.OutputSpec( + kind=ep.OutputKind.GRADIENT_TO_PARAMETER, + arg=ep.TensorArgument(name=o.gradient_to_parameter.arg.name), + target=o.gradient_to_parameter.parameter_name, + ) + elif o.type == "gradient_to_user_input": + return ep.OutputSpec( + kind=ep.OutputKind.GRADIENT_TO_USER_INPUT, + arg=ep.TensorArgument(name=o.gradient_to_user_input.arg.name), + target=o.gradient_to_user_input.user_input_name, + ) + elif o.type == "user_input_mutation": + return ep.OutputSpec( + kind=ep.OutputKind.USER_INPUT_MUTATION, + arg=ep.TensorArgument(name=o.user_input_mutation.arg.name), + target=o.user_input_mutation.user_input_name, + ) + elif o.type == "token": + return ep.OutputSpec( + kind=ep.OutputKind.TOKEN, + arg=ep.TokenArgument(name=o.token.arg.name), + target=None, + ) + else: + raise AssertionError(f"Unknown output spec {o}") + + def deserialize_signature(self, sig: GraphSignature) -> ep.ExportGraphSignature: + log.debug("\n[deserialize_signature]") + return ep.ExportGraphSignature( + input_specs=[self.deserialize_input_spec(i) for i in sig.input_specs], + output_specs=[self.deserialize_output_spec(o) for o in sig.output_specs], + ) + + def deserialize( + self, + serialized_graph_module: GraphModule, + serialized_state_dict: dict[str, torch.Tensor] | bytes, + constants: dict[str, Any] | bytes, + example_inputs: tuple[tuple[torch.Tensor, ...], dict[str, Any]] + | bytes + | None = None, + symbol_name_to_range: dict[str, symbolic_shapes.ValueRanges] | None = None, + ) -> Result: + global _CURRENT_DESERIALIZER + if _CURRENT_DESERIALIZER is not None: + raise AssertionError("_CURRENT_DESERIALIZER is already set") + _CURRENT_DESERIALIZER = self + try: + log.debug("\n[deserialize]") + self.shape_env = symbolic_shapes.ShapeEnv(assume_static_by_default=True) + self.fake_tensor_mode = FakeTensorMode( + allow_fallback_kernels=False, + allow_non_fake_inputs=True, + shape_env=self.shape_env, + ) + self.sympy_functions = { + # all torch.utils._sympy.functions should go here + # TODO(avik): find a better way to keep this collection in sync; + # e.g.., `exec('from torch.utils._sympy.functions import *', ...)` + # would work as long as the public API of that module is complete + "FloorDiv": torch.utils._sympy.functions.FloorDiv, + "ModularIndexing": torch.utils._sympy.functions.ModularIndexing, + "Where": torch.utils._sympy.functions.Where, + "PythonMod": torch.utils._sympy.functions.PythonMod, + "Mod": torch.utils._sympy.functions.Mod, + "CleanDiv": torch.utils._sympy.functions.CleanDiv, + "CeilToInt": torch.utils._sympy.functions.CeilToInt, + "FloorToInt": torch.utils._sympy.functions.FloorToInt, + "CeilDiv": torch.utils._sympy.functions.CeilDiv, + "LShift": torch.utils._sympy.functions.LShift, + "RShift": torch.utils._sympy.functions.RShift, + "PowByNatural": torch.utils._sympy.functions.PowByNatural, + "FloatPow": torch.utils._sympy.functions.FloatPow, + "FloatTrueDiv": torch.utils._sympy.functions.FloatTrueDiv, + "IntTrueDiv": torch.utils._sympy.functions.IntTrueDiv, + "IsNonOverlappingAndDenseIndicator": torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator, + "TruncToFloat": torch.utils._sympy.functions.TruncToFloat, + "TruncToInt": torch.utils._sympy.functions.TruncToInt, + "RoundToInt": torch.utils._sympy.functions.RoundToInt, + "RoundDecimal": torch.utils._sympy.functions.RoundDecimal, + "ToFloat": torch.utils._sympy.functions.ToFloat, + "Identity": torch.utils._sympy.functions.Identity, + } + self.symbol_name_to_symbol: dict[str, sympy.Symbol] = {} + self.constants = deserialize_torch_artifact(constants) + self.signature = self.deserialize_signature( + serialized_graph_module.signature + ) + + # deserialization does analysis with checks on 0/1, so we create fake range constraints and + # restore the original range constraints afterwards + self.symbol_name_to_range = {} + # we also need to bump unbacked sym[float,int] counters in the + # shape env to accommodate unbacked symbols in the exported program + self.unbacked_symbols = set() + count_unbacked_symfloat, count_unbacked_symint = -1, -1 + unbacked_symfloat_prefix, unbacked_symint_prefix = ( + prefix_str[t] for t in [SymT.UNBACKED_FLOAT, SymT.UNBACKED_INT] + ) + if symbol_name_to_range: + for k, vr in symbol_name_to_range.items(): + lower = vr.lower + self.symbol_name_to_range[k] = symbolic_shapes.ValueRanges( + _int_to_sympy_int(lower, -int_oo), vr.upper + ) + if k.startswith(unbacked_symfloat_prefix): + i = int(k[len(unbacked_symfloat_prefix) :]) + count_unbacked_symfloat = max(count_unbacked_symfloat, i) + elif k.startswith(unbacked_symint_prefix): + i = int(k[len(unbacked_symint_prefix) :]) + count_unbacked_symint = max(count_unbacked_symint, i) + + # TODO(pianpwk): if we can clean up unused symbols in range_constraints, + # then this logic can just be handled with self.unbacked_symbols alone + for _ in range(count_unbacked_symfloat + 1): + self.shape_env.unbacked_symfloat_counter += 1 + for _ in range(count_unbacked_symint + 1): + self.shape_env.unbacked_symint_counter += 1 + + if example_inputs is not None and len(example_inputs) > 0: + self.example_inputs = deserialize_torch_artifact(example_inputs) + else: + self.example_inputs = None + self.deserialize_graph(serialized_graph_module.graph) + + with _enable_graph_inputs_of_type_nn_module(self.example_inputs): + module_call_graph = self.deserialize_module_call_graph( + serialized_graph_module.module_call_graph + ) + graph_module = ep._create_graph_module_for_export(self.module, self.graph) + meta = {} + if custom := serialized_graph_module.metadata.get("custom"): + meta["custom"] = json.loads(custom) + if hasattr(serialized_graph_module, "treespec_namedtuple_fields"): + meta["treespec_namedtuple_fields"] = {} + for ( + type_, + fields, + ) in serialized_graph_module.treespec_namedtuple_fields.items(): + meta["treespec_namedtuple_fields"][type_] = fields.field_names + graph_module.meta = meta + return GraphModuleDeserializer.Result( + graph_module=graph_module, + signature=self.signature, + module_call_graph=module_call_graph, + names_to_symbols=self.symbol_name_to_symbol, + state_dict=deserialize_torch_artifact(serialized_state_dict), + constants=self.constants, + example_inputs=self.example_inputs, + ) + finally: + _CURRENT_DESERIALIZER = None + + def sync_fx_node(self, name: str, fx_node: torch.fx.Node): + if name in self.serialized_name_to_node: + raise SerializeError(f"Node {name} has already been deserialized before.") + # overwrite name + fx_node.name = name + self.serialized_name_to_node[name] = fx_node + if "val" in fx_node.meta: + raise AssertionError(f"fx_node {name} already has 'val' in meta") + fx_node.meta["val"] = self.serialized_name_to_meta[name] + + def deserialize_sym_op_inputs(self, inputs): + return tuple(self.deserialize_input(input.arg) for input in inputs) + + def deserialize_inputs(self, target, serialized_node: Node): + schema_args = _get_schema_from_target(target).arguments + argument_kinds = {input.name: input.kind for input in serialized_node.inputs} + actual_args = { + input.name: self.deserialize_input(input.arg) + for input in serialized_node.inputs + } + args = [] + kwargs: OrderedDict[str, Any] = OrderedDict() + for schema_arg in schema_args: + if schema_arg.name in actual_args: + arg = actual_args[schema_arg.name] + kind = argument_kinds[schema_arg.name] + if kind == ArgumentKind.POSITIONAL: + args.append(arg) + continue + elif kind == ArgumentKind.KEYWORD and not keyword.iskeyword( + schema_arg.name + ): + kwargs[schema_arg.name] = arg + continue + + # If there's no ArgumentKind found, fallback to the old cases. + is_positional = ( + not schema_arg.has_default_value() and not schema_arg.kwarg_only + ) + if is_positional: + args.append(actual_args[schema_arg.name]) + elif keyword.iskeyword(schema_arg.name): + if schema_arg.kwarg_only: + raise AssertionError( + f"schema_arg {schema_arg.name} should not be kwarg_only" + ) + if len(kwargs) > 0: + kwargs = OrderedDict() + args.extend(list(kwargs.values())) + args.append(actual_args[schema_arg.name]) + else: + if schema_arg.name in actual_args: + kwargs[schema_arg.name] = actual_args[schema_arg.name] + return tuple(args), kwargs + + def deserialize_hoo_inputs(self, inputs: list[NamedArgument]): + """ + For deserializing HOO inputs since HOOs do not have a schema. + """ + args = [] + kwargs = {} + for input_ in inputs: + if input_.kind == ArgumentKind.POSITIONAL or input_.name == "": + args.append(self.deserialize_input(input_.arg)) + else: + kwargs[input_.name] = self.deserialize_input(input_.arg) + return (tuple(args), kwargs) + + def deserialize_input(self, inp: Argument) -> Any: + value = inp.value + typ_ = inp.type + if typ_ == "as_none": + # None should converted as None, but is encoded as bool in serialized + # Convert serialized object to torch equivalent + return None + elif typ_ == "as_tensor": + return self.serialized_name_to_node[inp.as_tensor.name] + elif typ_ == "as_scalar_type": + return _SERIALIZE_TO_TORCH_DTYPE[inp.as_scalar_type] + elif typ_ == "as_memory_format": + return _SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format] + elif typ_ == "as_layout": + return _SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout] + elif typ_ == "as_graph": + if not isinstance(value, GraphArgument): + raise AssertionError( + f"expected GraphArgument, got {type(value).__name__}" + ) + with self.save_graph_module(): + self.deserialize_graph(value.graph) + submodule = ep._create_graph_module_for_export(self.module, self.graph) + self.module.register_module(value.name, submodule) + return self.graph.create_node( + "get_attr", + value.name, + name=value.name, + ) + elif typ_ == "as_device": + return deserialize_device(inp.as_device) + elif typ_ == "as_int": + return inp.as_int + elif typ_ == "as_float": + return inp.as_float + elif typ_ == "as_bool": + return inp.as_bool + elif typ_ == "as_string": + return inp.as_string + elif typ_ == "as_complex": + return complex(inp.as_complex.real, inp.as_complex.imag) + elif typ_ == "as_sym_int": + return self.deserialize_sym_argument(inp.as_sym_int) + elif typ_ == "as_sym_float": + return self.deserialize_sym_argument(inp.as_sym_float) + elif typ_ == "as_sym_bool": + return self.deserialize_sym_argument(inp.as_sym_bool) + elif isinstance(value, dict): + if typ_ == "as_string_to_argument": + # Deserialize dict[str, Argument] recursively + return {k: self.deserialize_input(v) for k, v in value.items()} + else: + raise SerializeError(f"Unknown dict type: {typ_}") + elif isinstance(value, list): + if len(value) == 0: + return [] + elif typ_ == "as_tensors": + result = [self.serialized_name_to_node[arg.name] for arg in value] + return result + elif typ_ in ("as_ints", "as_floats", "as_bools", "as_strings"): + # convert from serialized.python.types.List to python list + return list(value) + elif typ_ == "as_int_lists": + # Convert list of lists back to list of tuples for Triton grids + return [tuple(dims) for dims in value] + elif typ_ == "as_float_lists": + return [list(floats) for floats in value] + elif typ_ == "as_nested_tensors": + # nested list of tensors (List[List[Tensor]]) + return [ + [self.serialized_name_to_node[arg.name] for arg in inner_list] + for inner_list in value + ] + elif typ_ in ("as_sym_ints", "as_sym_bools", "as_sym_floats"): + return [self.deserialize_sym_argument(arg) for arg in value] + elif typ_ == "as_optional_tensors": + + def deserialize_optional_tensor_args(a): + if a.type == "as_none": + return None + elif a.type == "as_tensor": + return self.serialized_name_to_node[a.value.name] + else: + raise SerializeError(f"Unhandled argument {inp}") + + return list(map(deserialize_optional_tensor_args, value)) + else: + raise SerializeError(f"Unhandled argument {inp}") + elif typ_ == "as_custom_obj": + if inp.as_custom_obj.name in self.serialized_name_to_node: + # Custom object has been lifted as an input + return self.serialized_name_to_node[inp.as_custom_obj.name] + return self.constants[inp.as_custom_obj.name] + elif typ_ == "as_operator": + return self.deserialize_operator(inp.as_operator) + else: + raise SerializeError(f"Unhandled argument {inp}") + + def deserialize_constant_input(self, inp: ConstantValue) -> Any: + if inp.type == "as_int": + return int(inp.as_int) + elif inp.type == "as_float": + return float(inp.as_float) + elif inp.type == "as_string": + return str(inp.as_string) + elif inp.type == "as_bool": + return bool(inp.as_bool) + elif inp.type == "as_none": + return None + else: + raise SerializeError(f"Unhandled constant argument {inp} to deserialize") + + def deserialize_sym_argument(self, sym_arg): + if isinstance(sym_arg, SymIntArgument): + if sym_arg.type == "as_int": + return sym_arg.as_int + elif sym_arg.type == "as_name": + return self.serialized_name_to_node[sym_arg.as_name] + elif isinstance(sym_arg, SymFloatArgument): + if sym_arg.type == "as_float": + return sym_arg.as_float + elif sym_arg.type == "as_name": + return self.serialized_name_to_node[sym_arg.as_name] + elif isinstance(sym_arg, SymBoolArgument): + if sym_arg.type == "as_bool": + return sym_arg.as_bool + elif sym_arg.type == "as_name": + return self.serialized_name_to_node[sym_arg.as_name] + raise SerializeError(f"Unknown symbolic argument type: {sym_arg}") + + def deserialize_sym_op_outputs(self, serialized_node: Node, fx_node: torch.fx.Node): + self.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node) + + def deserialize_outputs(self, serialized_node: Node, fx_node: torch.fx.Node): + # Check single value return + if len(serialized_node.outputs) == 0: + return + + if ( + len(serialized_node.outputs) == 1 + and "torch.ops.higher_order" in serialized_node.target + and not getattr(serialized_node, "is_hop_single_tensor_return", True) + and serialized_node.outputs[0].type != "as_none" + ): + + def _deserialize_hop_with_single_return(serialized_node, fx_node): + meta_val: list[Any] = [] + arg = None + if serialized_node.outputs[0].type == "as_tensor": + arg = serialized_node.outputs[0].as_tensor + elif isinstance( + serialized_node.outputs[0].value, + (SymIntArgument, SymBoolArgument, SymFloatArgument), + ): + arg = serialized_node.outputs[0].value + deserialized_metadata = self.deserialize_metadata( + serialized_node.metadata + ) + if arg is None: + raise AssertionError("arg should not be None") + # pyrefly: ignore [bad-argument-type] + self.generate_getitem(meta_val, fx_node, arg, 0, deserialized_metadata) + fx_node.meta["val"] = tuple(meta_val) + self.serialized_name_to_node[fx_node.name] = fx_node + return + + return _deserialize_hop_with_single_return(serialized_node, fx_node) + + if ( + len(serialized_node.outputs) == 1 + and serialized_node.outputs[0].type == "as_tensor" + ): + self.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node) + return + elif len(serialized_node.outputs) == 1 and isinstance( + serialized_node.outputs[0].value, + (SymIntArgument, SymBoolArgument, SymFloatArgument), + ): + self.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node) + return + elif ( + len(serialized_node.outputs) == 1 + and serialized_node.outputs[0].type == "as_none" + ): + # manually rename the node to a unused name to avoid naming conflicts + fx_node.meta["val"] = None + fx_node._rename(f"{self.graph._target_to_str(fx_node.target)}_unused") + return + + self.deserialize_multiple_outputs(serialized_node, fx_node) + + def generate_getitem( + self, + meta_val, + fx_node: torch.fx.Node, + arg: TensorArgument | SymIntArgument | SymFloatArgument, + idx: int, + deserialized_metadata: dict[str, Any], + ): + if isinstance(arg, TensorArgument): + name = arg.name + elif isinstance(arg, SymIntArgument): + name = arg.as_name + elif isinstance(arg, SymFloatArgument): + name = arg.as_name + else: + raise AssertionError( + f"generate_getitem got unknown argument type {type(arg)}" + ) + individual_output = self.graph.create_node( + "call_function", + operator.getitem, + (fx_node, idx), + name=name, + ) + self.sync_fx_node(name, individual_output) + meta_val.append(self.serialized_name_to_meta[name]) + # The derived `getitem` nodes should have the same stacktrace as the + # original `fx_node` + individual_output.meta.update(deserialized_metadata) + + def generate_getitems( + self, + meta_val, + fx_node: torch.fx.Node, + args, + deserialized_metadata: dict[str, Any], + ): + for idx, arg in enumerate(args): + if isinstance(arg, (TensorArgument, SymIntArgument, SymFloatArgument)): + self.generate_getitem( + meta_val, fx_node, arg, idx, deserialized_metadata + ) + continue + + if not isinstance(arg, Argument): + raise AssertionError(f"expected Argument, got {type(arg).__name__}") + if arg.type in ("as_tensor", "as_sym_int", "as_sym_float"): + self.generate_getitem( + meta_val, fx_node, arg.value, idx, deserialized_metadata + ) + elif arg.type in ( + "as_tensors", + "as_sym_ints", + "as_sym_floats", + "as_ints", + "as_floats", + "as_strings", + "as_bools", + "as_sym_bools", + ): + list_output = self.graph.create_node( + "call_function", + operator.getitem, + (fx_node, idx), + ) + meta_val.append([]) + self.generate_getitems( + meta_val[-1], list_output, arg.value, deserialized_metadata + ) + list_output.meta.update(deserialized_metadata) + list_output.meta["val"] = meta_val[-1] + elif arg.type == "as_none": + individual_output = self.graph.create_node( + "call_function", + operator.getitem, + (fx_node, idx), + name="as_none", + ) + meta_val.append(None) + individual_output.meta["val"] = None + individual_output.meta.update(deserialized_metadata) + else: + raise NotImplementedError(f"Unimplemented node output type: {arg}") + + def deserialize_multiple_outputs( + self, serialized_node: Node, fx_node: torch.fx.Node + ) -> None: + deserialized_metadata = self.deserialize_metadata(serialized_node.metadata) + + # Convert multiple return types to FX format. + # In FX, each node only returns one value. So in order to represent + # multiple return values, we have to emit a `getitem` node for each + # return value. + # This performs the inverse mapping of the `serialize_outputs` call in + # serialization, see [NOTE: Multiple outputs] + meta_val: list[Any] = [] + if len(serialized_node.outputs) == 1: + if not isinstance(serialized_node.outputs[0].value, list): + raise AssertionError( + f"expected list, got {type(serialized_node.outputs[0].value).__name__}" + ) + if not isinstance(serialized_node.outputs[0].value[0], TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(serialized_node.outputs[0].value[0]).__name__}" + ) + self.generate_getitems( + meta_val, + fx_node, + serialized_node.outputs[0].as_tensors, + deserialized_metadata, + ) + else: + self.generate_getitems( + meta_val, fx_node, serialized_node.outputs, deserialized_metadata + ) + + # also update the metaval for `fx_node` to be a list(meta) + fx_node.meta["val"] = tuple(meta_val) + self.serialized_name_to_node[fx_node.name] = fx_node + + def deserialize_metadata(self, metadata: dict[str, str]) -> dict[str, Any]: + ret: dict[str, Any] = {} + if stack_trace := metadata.get("stack_trace"): + ret["stack_trace"] = stack_trace + + def deserialize_meta_func(serialized_target: str): + module = None + if serialized_target.startswith("torch.nn"): + module = torch.nn + serialized_target_names = serialized_target.split(".")[2:] + elif serialized_target.startswith("torch"): + module = torch + serialized_target_names = serialized_target.split(".")[1:] + else: + return self.deserialize_operator(serialized_target) + + target = module + for name in serialized_target_names: + if not hasattr(target, name): + return serialized_target + else: + target = getattr(target, name) + return target + + if nn_module_stack_str := metadata.get("nn_module_stack"): + # Originally serialized to "key,orig_path,type_str" + def import_nn_module_stack(key, path, ty): + return key, (path, ty) + + # Helper function to split string by commas, accounting for nested parentheses/brackets + def metadata_split(metadata): + out = [] + start, n = 0, 0 + a, b = "[(", ")]" + for end, c in enumerate(metadata): + if c in a: + n += 1 + elif c in b: + n -= 1 + elif c == "," and n == 0: + out.append(metadata[start:end]) + start = end + 1 + out.append(metadata[start:]) + if len(out) != 3: + raise AssertionError( + f"expected metadata_split to return 3 parts, got {len(out)}" + ) + return out + + nn_module_stack = dict( + import_nn_module_stack(*metadata_split(item)) + for item in nn_module_stack_str.split(ST_DELIMITER) + ) + ret["nn_module_stack"] = nn_module_stack + + if source_fn_st_str := metadata.get("source_fn_stack"): + # Originally serializes to "fx_node_name,op_str" + source_fn_st = [] + for source_fn_str in source_fn_st_str.split(ST_DELIMITER): + name, target_str = source_fn_str.split(",") + source_fn_st.append((name, deserialize_meta_func(target_str))) + ret["source_fn_stack"] = source_fn_st + + if torch_fn_str := metadata.get("torch_fn"): + ret["torch_fn"] = tuple(torch_fn_str.split(ST_DELIMITER)) + + if custom_str := metadata.get("custom"): + ret["custom"] = json.loads(custom_str) + + if from_node_str := metadata.get("from_node"): + ret["from_node"] = self._deserialize_from_node(json.loads(from_node_str)) + + return ret + + def _deserialize_from_node( + self, from_node_data: list[dict[str, Any]] | None + ) -> list[NodeSource] | None: + """ + Deserialize from_node metadata from JSON data. + """ + if from_node_data is None: + return None + + if not isinstance(from_node_data, list): + raise AssertionError(f"expected list, got {type(from_node_data).__name__}") + + return [ + node_source + for fn_dict in from_node_data + if (node_source := NodeSource._from_dict(fn_dict)) is not None + ] + + def deserialize_argument_spec(self, x: Argument) -> ep.ArgumentSpec: + log.debug("[deserialize_argument_spec] %s", x) + if x.type == "as_tensor": + return ep.TensorArgument(name=x.as_tensor.name) + elif x.type == "as_sym_int": + return ep.SymIntArgument(name=x.as_sym_int.as_name) + elif x.type == "as_sym_float": + return ep.SymFloatArgument(name=x.as_sym_float.as_name) + elif x.type == "as_custom_obj": + return ep.ConstantArgument( + name=x.as_custom_obj.name, value=self.deserialize_input(x) + ) + else: + return ep.ConstantArgument(name="", value=self.deserialize_input(x)) + + def deserialize_module_call_signature( + self, module_call_signature: ModuleCallSignature + ) -> ep.ModuleCallSignature: + return ep.ModuleCallSignature( + inputs=[ + self.deserialize_argument_spec(x) for x in module_call_signature.inputs + ], + outputs=[ + self.deserialize_argument_spec(x) for x in module_call_signature.outputs + ], + in_spec=treespec_loads(module_call_signature.in_spec), + out_spec=treespec_loads(module_call_signature.out_spec), + forward_arg_names=( + names if (names := module_call_signature.forward_arg_names) else None + ), + ) + + def deserialize_module_call_graph( + self, module_call_graph: list[ModuleCallEntry] + ) -> list[ep.ModuleCallEntry]: + log.debug("\n[deserialize_module_call_graph]") + return [ + ep.ModuleCallEntry( + fqn=entry.fqn, + signature=( + self.deserialize_module_call_signature(entry.signature) + if entry.signature + else None + ), + ) + for entry in module_call_graph + ] + + +@final +class ExportedProgramDeserializer(metaclass=Final): + def __init__(self, expected_opset_version: dict[str, int] | None = None): + self.expected_opset_version: dict[str, int] = {} + if expected_opset_version: + self.expected_opset_version.update(expected_opset_version) + if "aten" not in self.expected_opset_version: + self.expected_opset_version["aten"] = torch._C._get_max_operator_version() + + def deserialize_range_constraints( + self, + symbol_name_to_range: dict[str, symbolic_shapes.ValueRanges], + symbol_name_to_symbol: dict[str, sympy.Symbol], + ) -> dict[sympy.Symbol, ValueRanges]: + log.debug("\n[deserialize_range_constraints]") + range_constraints = {} + for k, v in symbol_name_to_range.items(): + if symbol := symbol_name_to_symbol.get(k): + log.debug("[deserialize_range_constraints] %s -> %s", k, v) + range_constraints[symbol] = v # type: ignore[arg-type] + else: + log.warning( + "Symbol %s did not appear in the graph that was deserialized", k + ) + return range_constraints + + def deserialize( + self, + exported_program: ExportedProgram, + state_dict: dict[str, torch.Tensor] | bytes, + constants: dict[str, torch.Tensor] | bytes, + example_inputs: tuple[tuple[torch.Tensor, ...], dict[str, Any]] + | bytes + | None = None, + *, + _unsafe_skip_version_check=False, + ) -> ep.ExportedProgram: + if not isinstance(exported_program, ExportedProgram): + raise AssertionError( + f"expected ExportedProgram, got {type(exported_program).__name__}" + ) + version = exported_program.schema_version + + # TODO(zhxchen17) blocked on thrift schema refactor + if version.major != SCHEMA_VERSION[0] and not ( + version.major == 0 and version.minor == 0 + ): + if not _unsafe_skip_version_check: + raise SerializeError( + f"Serialized schema version {exported_program.schema_version} " + f"does not match our current schema version {SCHEMA_VERSION}." + ) + + symbol_name_to_range = { + k: symbolic_shapes.ValueRanges( + _int_to_sympy_int(v.min_val, -int_oo), + _int_to_sympy_int(v.max_val, int_oo), + ) + for k, v in exported_program.range_constraints.items() + } + res = GraphModuleDeserializer().deserialize( + exported_program.graph_module, + state_dict, + constants, + example_inputs, + symbol_name_to_range, + ) + range_constraints = self.deserialize_range_constraints( + symbol_name_to_range, + res.names_to_symbols, + ) + + result = ep.ExportedProgram( + root=res.graph_module, + graph=res.graph_module.graph, + graph_signature=res.signature, + state_dict=res.state_dict, # type: ignore[arg-type] + range_constraints=range_constraints, + module_call_graph=res.module_call_graph, + example_inputs=res.example_inputs, + constants=res.constants, + verifiers=[load_verifier(v) for v in exported_program.verifiers], + ) + result._guards_code = exported_program.guards_code + log.debug("\n[deserialize]: %s", result) + return result + + +class EnumEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, Enum): + return obj.value + if isinstance(obj, bytes): + return base64.b64encode(obj).decode("utf-8") + return super().default(obj) + + +def _dataclass_to_dict(obj): + if isinstance(obj, _Union): + return {obj.type: _dataclass_to_dict(obj.value)} + elif dataclasses.is_dataclass(obj): + return { + f.name: _dataclass_to_dict(getattr(obj, f.name)) + for f in dataclasses.fields(obj) + } + elif isinstance(obj, list): + return [_dataclass_to_dict(x) for x in obj] + elif isinstance(obj, tuple): + return tuple(_dataclass_to_dict(x) for x in obj) + elif isinstance(obj, dict): + return {k: _dataclass_to_dict(v) for k, v in obj.items()} + elif isinstance(obj, float): + if obj == math.inf: + return "Infinity" + elif obj == -math.inf: + return "-Infinity" + elif math.isnan(obj): + return "NaN" + else: + return obj + else: + return obj + + +def _to_json_bytes(obj: Any) -> bytes: + return json.dumps(_dataclass_to_dict(obj), cls=EnumEncoder, allow_nan=False).encode( + "utf-8" + ) + + +def serialize( + exported_program: ep.ExportedProgram, + opset_version: dict[str, int] | None = None, + pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL, + *, + serialize_state_dict: bool = True, + serialize_constants: bool = True, + serialize_example_inputs: bool = True, +) -> SerializedArtifact: + with _enable_graph_inputs_of_type_nn_module(exported_program.example_inputs): + serialized_program = ExportedProgramSerializer( + opset_version, pickle_protocol + ).serialize( + exported_program, + serialize_state_dict=serialize_state_dict, + serialize_constants=serialize_constants, + serialize_example_inputs=serialize_example_inputs, + ) + if not isinstance(serialized_program.exported_program, ExportedProgram): + raise AssertionError( + f"expected ExportedProgram, got {type(serialized_program.exported_program).__name__}" + ) + + json_bytes = _to_json_bytes(serialized_program.exported_program) + artifact = SerializedArtifact( + json_bytes, + serialized_program.state_dict, + serialized_program.constants, + serialized_program.example_inputs, + ) + return artifact + + +def _resolve_schema_cls(cls): + if isinstance(cls, str): + resolved = getattr(schema, cls, None) + if resolved is not None: + return resolved + if isinstance(cls, typing.ForwardRef): + return _resolve_schema_cls(cls.__forward_arg__) + return cls + + +def _dict_to_dataclass(cls, data): + cls = _resolve_schema_cls(cls) + if isinstance(cls, str): + raise AssertionError(f"Unresolved class type: '{cls}'.") + if typing.get_origin(cls) is Annotated: + return _dict_to_dataclass(cls.__origin__, data) + if typing.get_origin(cls) in (typing.Union, types.UnionType) and type( + None + ) in typing.get_args(cls): + if data is None: + return None + ty_args = typing.get_args(cls) + if len(ty_args) != 2: + raise AssertionError(f"expected 2 type args, got {len(ty_args)}") + return _dict_to_dataclass(ty_args[0], data) + elif isinstance(cls, type) and issubclass(cls, _Union): + if not isinstance(data, dict): + raise AssertionError(f"expected dict, got {type(data).__name__}") + if len(data) != 1: + raise AssertionError(f"expected dict with 1 key, got {len(data)}") + _type = next(iter(data.keys())) + _value = next(iter(data.values())) + if not isinstance(_type, str): + raise AssertionError(f"expected str key, got {type(_type).__name__}") + type_hints = typing.get_type_hints(cls, globalns=vars(schema)) + field_type = type_hints[_type] + # pyrefly: ignore [missing-attribute] + return cls.create(**{_type: _dict_to_dataclass(field_type, _value)}) + elif dataclasses.is_dataclass(cls): + fields = {} + type_hints = typing.get_type_hints(cls, globalns=vars(schema)) + # For forward compatibility consideration, we ignore all the keys + # that are not showing up in the dataclass definition. + for f in dataclasses.fields(cls): + name = f.name + if name not in data: + continue + new_field_obj = _dict_to_dataclass(type_hints[name], data[name]) + fields[name] = new_field_obj + return cls(**fields) # type: ignore[operator] + elif isinstance(data, list): + if len(data) == 0: + return data + d_type = typing.get_args(cls)[0] + return [_dict_to_dataclass(d_type, d) for d in data] + elif isinstance(data, dict): + v_type = typing.get_args(cls)[1] + return {k: _dict_to_dataclass(v_type, v) for k, v in data.items()} + elif cls is float: + return float(data) + return data + + +def _bytes_to_dataclass(cls: Any, artifact_bytes: bytes) -> Any: + artifact_str = artifact_bytes.decode("utf-8") + artifact_dict = json.loads(artifact_str) + artifact_dataclass = _dict_to_dataclass(cls, artifact_dict) + return artifact_dataclass + + +def deserialize( + artifact: SerializedArtifact, + expected_opset_version: dict[str, int] | None = None, + *, + _unsafe_skip_version_check=False, +) -> ep.ExportedProgram: + if not isinstance(artifact.exported_program, bytes): + raise AssertionError( + f"expected bytes, got {type(artifact.exported_program).__name__}" + ) + serialized_exported_program = _bytes_to_dataclass( + ExportedProgram, artifact.exported_program + ) + return ExportedProgramDeserializer(expected_opset_version).deserialize( + serialized_exported_program, + artifact.state_dict, + artifact.constants, + artifact.example_inputs, + _unsafe_skip_version_check=_unsafe_skip_version_check, + ) + + +def _canonicalize_graph( + sorted_inputs, sorted_outputs, graph, constants +) -> tuple[Graph, dict[str, str]]: + def _get_argument(a: Argument): + if a.type == "as_none": + return None + elif a.type == "as_tensor": + return a.as_tensor + elif a.type == "as_tensors": + return a.as_tensors + elif a.type == "as_int": + return None + elif a.type == "as_ints": + return None + elif a.type == "as_float": + return None + elif a.type == "as_floats": + return None + elif a.type == "as_string": + return None + elif a.type == "as_strings": + return None + elif a.type == "as_complex": + return None + elif a.type == "as_sym_int": + return a.as_sym_int + elif a.type == "as_sym_ints": + return a.as_sym_ints + elif a.type == "as_sym_float": + return a.as_sym_float + elif a.type == "as_sym_floats": + return a.as_sym_floats + elif a.type == "as_scalar_type": + return None + elif a.type == "as_memory_format": + return None + elif a.type == "as_layout": + return None + elif a.type == "as_device": + return None + elif a.type == "as_bool": + return None + elif a.type == "as_bools": + return None + elif a.type == "as_sym_bool": + return a.as_sym_bool + elif a.type == "as_sym_bools": + return a.as_sym_bools + elif a.type == "as_graph": + return None + elif a.type == "as_optional_tensors": + return a.as_optional_tensors + elif a.type == "as_custom_obj": + return a.as_custom_obj + elif a.type == "as_operator": + return None + elif a.type == "as_int_lists": + return None + elif a.type == "as_float_lists": + return None + elif a.type == "as_string_to_argument": + return None + elif a.type == "as_nested_tensors": + return a.as_nested_tensors + else: + raise AssertionError(f"Unknown input type to the ExportedProgram: {a}") + + # Stage 1: Reorder named items. + def for_args(f, a): + if not isinstance(a, Argument): + raise AssertionError(f"expected Argument, got {type(a).__name__}") + pytree.tree_map(f, _get_argument(a)) + + def sort_nodes(nodes): + @dataclass + class Edges: + outs: list[int] + ins: int + + graph_inputs: set[str] = set() + def_table: dict[str, int] = {} + edges: dict[int, Edges] = {} + candidates: list[tuple[str, list[tuple[str, list[int]]], int]] = [] + rank: dict[str, int] = {} + ret: list[Node] = [] + + def get_name(a) -> str | None: + if a is None: + return None + if isinstance(a, TensorArgument): + return a.name + elif isinstance(a, (SymIntArgument, SymBoolArgument, SymFloatArgument)): + if a.type == "as_name": + return a.as_name + elif a.type in ("as_int", "as_bool", "as_float"): + return None + else: + raise AssertionError(f"Unknown argument type: {a}") + elif isinstance(a, OptionalTensorArgument): + if a.type == "as_tensor": + return a.as_tensor.name + elif a.type == "as_none": + return None + else: + raise AssertionError(f"Unknown optional tensor type: {a}") + elif isinstance(a, CustomObjArgument): + return a.name + else: + raise AssertionError(f"Unknown argument type: {a}") + + for i in sorted_inputs: + + def add_input(a): + if s := get_name(a): + graph_inputs.add(s) + + for_args(add_input, i) + + for idx, node in enumerate(nodes): + + def add_def(a): + if s := get_name(a): + if s in def_table: + raise AssertionError(f"symbol {s!r} already in def_table") + def_table[s] = idx + + for o in node.outputs: + for_args(add_def, o) + + edges[idx] = Edges([], 0) + + for idx, user in enumerate(nodes): + + def add_edge(a): + if s := get_name(a): + if s in constants: + return + if s not in def_table: + if s not in graph_inputs: + raise AssertionError( + f"symbol {s!r} not in def_table or graph_inputs" + ) + return + src = def_table[s] + edges[src].outs.append(idx) + edges[idx].ins += 1 + + for i in user.inputs: + for_args(add_edge, i.arg) + + def add_rank(a): + if s := get_name(a): + if s in rank: + raise AssertionError(f"symbol {s!r} already in rank") + rank[s] = len(rank) + + def get_rank(a): + s = get_name(a) + if s and s not in constants: + return rank[s] + else: + return -1 + + for i in sorted_inputs: + for_args(add_rank, i) + + def add_candidate(idx: int): + def get_ranks(i): + ranks = [] + for_args(lambda x: ranks.append(get_rank(x)), i) + return ranks + + node = nodes[idx] + args_rank = [(a.name, get_ranks(a.arg)) for a in node.inputs] + heapq.heappush(candidates, (node.target, args_rank, idx)) + + for idx, e in edges.items(): + if e.ins == 0: + add_candidate(idx) + + while len(candidates) > 0: + _, _, idx = heapq.heappop(candidates) + node = nodes[idx] + for o in node.outputs: + for_args(add_rank, o) + ret.append(node) + if idx not in edges: + raise AssertionError(f"idx {idx} not in edges") + for user in edges[idx].outs: + e = edges[user] + if e.ins <= 0: + raise AssertionError(f"e.ins should be > 0, got {e.ins}") + e.ins -= 1 + if e.ins == 0: + add_candidate(user) + edges[idx].outs.clear() + + return ret + + sorted_nodes = sort_nodes(graph.nodes) + if len(sorted_nodes) != len(graph.nodes): + raise AssertionError( + f"expected {len(graph.nodes)} sorted nodes, got {len(sorted_nodes)}" + ) + + # Stage 2: Rename nodes. + name_table: dict[str, str] = {} + + def rename_def(a): + def _rename(arg_name, values): + new_name = f"_{len(name_table)}" + if arg_name in name_table: + raise AssertionError(f"arg_name {arg_name!r} already in name_table") + name_table[arg_name] = new_name + if arg_name not in values: + raise AssertionError(f"arg_name {arg_name!r} not in values") + values[new_name] = values.pop(arg_name) + return new_name + + if a is None: + return + if isinstance(a, TensorArgument): + a.name = _rename(a.name, graph.tensor_values) + elif isinstance(a, SymIntArgument): + if a.type == "as_name": + a.as_name = _rename(a.as_name, graph.sym_int_values) + elif isinstance(a, SymFloatArgument): + if a.type == "as_name": + a.as_name = _rename(a.as_name, graph.sym_float_values) + elif isinstance(a, SymBoolArgument): + if a.type == "as_name": + a.as_name = _rename(a.as_name, graph.sym_bool_values) + elif isinstance(a, CustomObjArgument): + a.name = _rename(a.name, graph.custom_obj_values) + else: + raise AssertionError(f"Unknown argument type: {a}") + + def replace_use(a): + if a is None: + return + if isinstance(a, TensorArgument): + a.name = name_table.get(a.name, a.name) + elif isinstance(a, (SymIntArgument, SymFloatArgument)): + if a.type == "as_name": + a.as_name = name_table.get(a.as_name, a.as_name) + elif isinstance(a, SymBoolArgument): + if a.type == "as_name": + a.as_name = name_table.get(a.as_name, a.as_name) + elif isinstance(a, OptionalTensorArgument): + if a.type == "as_tensor": + a.as_tensor.name = name_table.get(a.as_tensor.name, a.as_tensor.name) + elif isinstance(a, CustomObjArgument): + a.name = name_table.get(a.name, a.name) + else: + raise AssertionError(f"Unknown argument type: {a}") + + for i in sorted_inputs: + for_args(rename_def, i) + + for n in sorted_nodes: + for o in n.outputs: + for_args(rename_def, o) + + for n in sorted_nodes: + for i in n.inputs: + for_args(replace_use, i.arg) + + for o in sorted_outputs: + for_args(replace_use, o) + + # Stage 3: Remove unstable fields. + for n in sorted_nodes: + n.metadata.clear() + + # Stage 4: Aggregate values. + # pyrefly: ignore [no-matching-overload] + sorted_tensor_values = dict( + sorted(graph.tensor_values.items(), key=operator.itemgetter(0)) + ) + # pyrefly: ignore [no-matching-overload] + sorted_sym_int_values = dict( + sorted(graph.sym_int_values.items(), key=operator.itemgetter(0)) + ) + # pyrefly: ignore [no-matching-overload] + sorted_sym_float_values = dict( + sorted(graph.sym_float_values.items(), key=operator.itemgetter(0)) + ) + # pyrefly: ignore [no-matching-overload] + sorted_sym_bool_values = dict( + sorted(graph.sym_bool_values.items(), key=operator.itemgetter(0)) + ) + # pyrefly: ignore [no-matching-overload] + sorted_custom_obj_values = dict( + sorted(graph.custom_obj_values.items(), key=operator.itemgetter(0)) + ) + + # Stage 5: Recurse in subgraphs. + counter = 0 + for node in sorted_nodes: + for i in node.inputs: + a = i.arg + if a.type == "as_graph": + a.as_graph.graph, _ = _canonicalize_graph( + a.as_graph.graph.inputs, + a.as_graph.graph.outputs, + a.as_graph.graph, + constants, + ) + a.as_graph.name = f"_g{counter}" + counter += 1 + + graph = Graph( + inputs=sorted_inputs, + outputs=sorted_outputs, + nodes=sorted_nodes, + tensor_values=sorted_tensor_values, + sym_int_values=sorted_sym_int_values, + sym_float_values=sorted_sym_float_values, + sym_bool_values=sorted_sym_bool_values, + is_single_tensor_return=graph.is_single_tensor_return, + custom_obj_values=sorted_custom_obj_values, + ) + return graph, name_table + + +def canonicalize( + ep: ExportedProgram, constants: set[str] | None = None +) -> ExportedProgram: + """ + Normalize a serialized ExportedProgram, so that different eager program which + shares the same semantics can get a single representation on disk. + + This function canonicalizes an ExportedProgram by: + + 1. Sorting nodes in topological order. + 2. Rename nodes to have unique names. + 3. Remove unstable fields. + 4. Aggregate the above program fields. + 5. Recurse in subgraphs. + + Args: + ep (ExportedProgram): The ExportedProgram to canonicalize. + constants (Optional[set[str]]): Set of constants names + + Returns: + ExportedProgram: The canonicalized exported program. + """ + ep = copy.deepcopy(ep) + # pyrefly: ignore [annotation-mismatch, redefinition] + constants: set[str] = constants or set() + + opset_version = dict(sorted(ep.opset_version.items(), key=operator.itemgetter(0))) + range_constraints = dict( + sorted(ep.range_constraints.items(), key=operator.itemgetter(0)) + ) + guards_code = sorted(ep.guards_code) + module_call_graph = sorted(ep.graph_module.module_call_graph, key=lambda x: x.fqn) + signature = ep.graph_module.signature + graph = ep.graph_module.graph + + if len(graph.inputs) != len(signature.input_specs): + raise AssertionError( + f"graph.inputs length {len(graph.inputs)} != signature.input_specs length {len(signature.input_specs)}" + ) + if len(graph.outputs) != len(signature.output_specs): + raise AssertionError( + f"graph.outputs length {len(graph.outputs)} != signature.output_specs length {len(signature.output_specs)}" + ) + + def rank_input(inp) -> tuple[int, str | None, int]: + idx, (_arg, spec) = inp + if not isinstance(spec, InputSpec): + raise AssertionError(f"expected InputSpec, got {type(spec).__name__}") + if spec.type == "user_input": + return 5, None, idx + elif spec.type == "parameter": + return 1, spec.parameter.parameter_name, idx + elif spec.type == "buffer": + return 2, spec.buffer.buffer_name, idx + elif spec.type == "tensor_constant": + return 3, spec.tensor_constant.tensor_constant_name, idx + elif spec.type == "custom_obj": + return 4, spec.custom_obj.custom_obj_name, idx + elif spec.type == "token": + return 0, None, idx + elif spec.type == "constant_input": + return 6, spec.constant_input.name, idx + else: + raise AssertionError(f"Unknown input type: {spec}") + + def rank_output(out) -> tuple[int, str | None, int]: + idx, (_arg, spec) = out + if not isinstance(spec, OutputSpec): + raise AssertionError(f"expected OutputSpec, got {type(spec).__name__}") + if spec.type == "user_output": + return 4, None, idx + elif spec.type == "loss_output": + return 4, None, idx + elif spec.type == "parameter_mutation": + return 1, spec.parameter_mutation.parameter_name, idx + elif spec.type == "buffer_mutation": + return 2, spec.buffer_mutation.buffer_name, idx + elif spec.type == "gradient_to_parameter": + return 5, spec.gradient_to_parameter.parameter_name, idx + elif spec.type == "gradient_to_user_input": + return 6, None, idx + elif spec.type == "user_input_mutation": + return 3, None, idx + elif spec.type == "token": + return 0, None, idx + else: + raise AssertionError(f"Unknown output type: {spec}") + + sorted_ins = sorted( + enumerate(zip(graph.inputs, signature.input_specs)), key=rank_input + ) + + if len(sorted_ins) > 0: + sorted_inputs, input_specs = zip(*(i for idx, i in sorted_ins)) # type: ignore[assignment] + else: + sorted_inputs = () + input_specs = () + + sorted_outs = sorted( + enumerate(zip(graph.outputs, signature.output_specs)), key=rank_output + ) + sorted_outputs, output_specs = zip(*(i for idx, i in sorted_outs)) # type: ignore[assignment] + + sorted_graph, replace_table = _canonicalize_graph( + sorted_inputs, sorted_outputs, graph, constants + ) + + def replace_input(spec): + if not isinstance(spec, InputSpec): + raise AssertionError(f"expected InputSpec, got {type(spec).__name__}") + if spec.type == "user_input": + arg = spec.user_input.arg + if arg.type == "as_tensor": + t = arg.as_tensor + t.name = replace_table[t.name] + elif arg.type == "as_sym_int": + s = arg.as_sym_int + if s.type == "as_name": + s.as_name = replace_table[s.as_name] + elif s.type == "as_int": + pass + else: + raise AssertionError(f"Unknown sym_int type: {s}") + elif arg.type == "as_sym_float": + f = arg.as_sym_float + if f.type == "as_name": + f.as_name = replace_table[f.as_name] + elif f.type == "as_float": + pass + else: + raise AssertionError(f"Unknown sym_float type: {f}") + elif arg.type in ( + "as_none", + "as_bool", + "as_int", + "as_float", + "as_string", + "as_custom_obj", + ): + return + else: + raise AssertionError(f"Unknown input type: {arg}") + elif spec.type == "parameter": + t = spec.parameter.arg + t.name = replace_table[t.name] + elif spec.type == "buffer": + t = spec.buffer.arg + t.name = replace_table[t.name] + elif spec.type == "tensor_constant": + t = spec.tensor_constant.arg + t.name = replace_table[t.name] + elif spec.type == "custom_obj": + t_custom_obj = spec.custom_obj.arg + t_custom_obj.name = replace_table[t_custom_obj.name] + return + elif spec.type == "token": + tok = spec.token.arg + tok.name = replace_table[tok.name] + elif spec.type == "constant_input": + return + else: + raise AssertionError(f"Unknown input type: {spec}") + + def replace_output(out): + if not isinstance(spec, OutputSpec): + raise AssertionError(f"expected OutputSpec, got {type(spec).__name__}") + if spec.type == "user_output": + arg = spec.user_output.arg + if arg.type == "as_tensor": + t = arg.as_tensor + t.name = replace_table[t.name] + elif arg.type == "as_sym_int": + s = arg.as_sym_int + if s.type == "as_name": + s.as_name = replace_table[s.as_name] + elif s.type == "as_int": + pass + else: + raise AssertionError(f"Unknown sym_int type: {s}") + elif arg.type == "as_sym_float": + f = arg.as_sym_float + if f.type == "as_name": + f.as_name = replace_table[f.as_name] + elif f.type == "as_float": + pass + else: + raise AssertionError(f"Unknown sym_float type: {f}") + elif arg.type in ("as_none", "as_bool", "as_int", "as_float", "as_string"): + return + else: + raise AssertionError(f"Unknown input type: {arg}") + elif spec.type == "loss_output": + t = spec.loss_output.arg + t.name = replace_table[t.name] + elif spec.type == "buffer_mutation": + t = spec.buffer_mutation.arg + t.name = replace_table[t.name] + elif spec.type == "parameter_mutation": + t = spec.parameter_mutation.arg + t.name = replace_table[t.name] + elif spec.type == "gradient_to_parameter": + t = spec.gradient_to_parameter.arg + t.name = replace_table[t.name] + elif spec.type == "gradient_to_user_input": + g = spec.gradient_to_user_input + g.arg.name = replace_table[g.arg.name] + g.user_input_name = replace_table[g.user_input_name] + elif spec.type == "user_input_mutation": + u = spec.user_input_mutation + u.arg.name = replace_table[u.arg.name] + u.user_input_name = replace_table[u.user_input_name] + elif spec.type == "token": + tok = spec.token.arg + tok.name = replace_table[tok.name] + else: + raise AssertionError(f"Unknown output type: {spec}") + + for spec in input_specs: + replace_input(spec) + + for spec in output_specs: + replace_output(spec) + + return ExportedProgram( + graph_module=GraphModule( + graph=sorted_graph, + signature=GraphSignature( + input_specs=list(input_specs), + output_specs=list(output_specs), + ), + module_call_graph=module_call_graph, + ), + opset_version=opset_version, + range_constraints=range_constraints, + schema_version=ep.schema_version, + verifiers=ep.verifiers, + torch_version=ep.torch_version, + guards_code=guards_code, + ) + + +class ExtensionHandler: + """ + Base class for handling extension operators. + """ + + @classmethod + def namespace(cls) -> str: + raise NotImplementedError(f"{cls.__class__} namespace() must be implemented") + + @classmethod + def to_op_name(cls, op) -> str: + raise NotImplementedError(f"{cls.__class__} op_name() must be implemented") + + @classmethod + def from_op_name(cls, name: str): + raise NotImplementedError(f"{cls.__class__} op_name() must be implemented") + + @classmethod + def op_schema(cls, op) -> torch.FunctionSchema: + raise NotImplementedError(f"{cls.__class__} op_schema() must be implemented") + + +def register_extension( + op_type: type[Any], + extension_handler: type[ExtensionHandler], +): + """Register custom de/serialization method for a node with non-standard type.""" + if not issubclass(extension_handler, ExtensionHandler): + raise AssertionError(f"Expected ExtensionHandler, got {extension_handler}.") + if op_type in _serialization_registry: + raise AssertionError(f"{op_type} is already registered.") + if not isinstance(op_type, type): + raise AssertionError(f"op_type must be a type, got {type(op_type).__name__}") + if op_type.__module__.startswith("torch") or op_type.__module__.startswith( + "builtins" + ): + raise AssertionError( + f"op_type module {op_type.__module__} should not start with 'torch' or 'builtins'" + ) + if extension_handler.namespace() in _deserialization_registry: + raise AssertionError( + f"namespace {extension_handler.namespace()!r} is already registered" + ) + _serialization_registry[op_type] = extension_handler + _deserialization_registry[extension_handler.namespace()] = extension_handler + + +def _registered_extension_types(): + return tuple(_serialization_registry.keys()) + + +# Registry to store all custom serialization implementations. +# The registry maps an operation to its serialization function (a callable), in their own +# namespace to avoid conflicts. +# Serialization: Op type --> custom handler. +# De-serialization: Namespace --> custom handler. +_serialization_registry: dict[type[Any], type[ExtensionHandler]] = {} +_deserialization_registry: dict[str, type[ExtensionHandler]] = {} diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/union.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/union.py new file mode 100644 index 0000000000000000000000000000000000000000..6610c4d74ee9f63ddc8e5d21f64e37bc2ba543ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/union.py @@ -0,0 +1,104 @@ +import functools +from collections.abc import Hashable +from dataclasses import dataclass, fields +from typing import Any, TypeVar +from typing_extensions import dataclass_transform + + +T = TypeVar("T", bound="_Union") + + +class _UnionTag(str): + __slots__ = ("_cls",) + _cls: Hashable + + @staticmethod + def create(t: str, cls: type["_Union"]) -> "_UnionTag": + tag = _UnionTag(t) + if hasattr(tag, "_cls"): + raise AssertionError("tag already has _cls attribute") + tag._cls = cls + return tag + + def __eq__(self, cmp: object) -> bool: + if not isinstance(cmp, str): + raise AssertionError(f"expected str, got {type(cmp)}") + other = str(cmp) + if other not in _get_field_names(self._cls): + raise AssertionError( + f"{other} is not a valid tag for {self._cls}. Available tags: {_get_field_names(self._cls)}" + ) + return str(self) == other + + def __hash__(self) -> int: + return hash(str(self)) + + +@functools.cache +def _get_field_names(cls: type["_Union"]) -> set[str]: + # pyrefly: ignore[bad-argument-type] # TODO _Union subclasses are dataclasses at runtime via _union_dataclass + return {f.name for f in fields(cls)} + + +# If you turn a schema class that inherits from union into a dataclass, please use +# this decorator to configure it. It's safe, faster and allows code sharing. +# +# For example, _union_dataclass customizes the __eq__ method to only check the type +# and value property instead of default implementation of dataclass which goes +# through every field in the dataclass. +@dataclass_transform(eq_default=False) +def _union_dataclass(cls: type[T]) -> type[T]: + if not issubclass(cls, _Union): + raise AssertionError(f"{cls} must inherit from {_Union}.") + return dataclass(repr=False, eq=False)(cls) + + +class _Union: + _type: _UnionTag + + @classmethod + def create(cls: type[T], **kwargs: object) -> T: + if len(kwargs) != 1: + raise AssertionError(f"expected exactly 1 kwarg, got {len(kwargs)}") + obj = cls(**{**{f.name: None for f in fields(cls)}, **kwargs}) # type: ignore[arg-type] + obj._type = _UnionTag.create(next(iter(kwargs.keys())), cls) + return obj + + def __post_init__(self) -> None: + if any( + f.name in ("type", "_type", "create", "value") + for f in fields(self) # type: ignore[arg-type, misc] + ): + raise AssertionError( + "field names 'type', '_type', 'create', 'value' are reserved" + ) + + @property + def type(self) -> str: + try: + return self._type + except AttributeError as e: + raise RuntimeError( + f"Please use {type(self).__name__}.create to instantiate the union type." + ) from e + + @property + def value(self) -> Any: + return getattr(self, self.type) + + def __getattribute__(self, name: str) -> Any: + attr = super().__getattribute__(name) + if attr is None and name in _get_field_names(type(self)) and name != self.type: + raise AttributeError(f"Field {name} is not set.") + return attr + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _Union): + return False + return self.type == other.type and self.value == other.value + + def __str__(self) -> str: + return self.__repr__() + + def __repr__(self) -> str: + return f"{type(self).__name__}({self.type}={getattr(self, self.type)})" diff --git a/.venv/lib/python3.12/site-packages/torch/_export/tools.py b/.venv/lib/python3.12/site-packages/torch/_export/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..94f5168930b1c0d4177830d72563305961672e71 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/tools.py @@ -0,0 +1,148 @@ +# mypy: allow-untyped-defs +import logging +import warnings +from collections.abc import Iterable +from typing import Any + +import torch +import torch.export +import torch.export._trace +from torch._utils_internal import log_export_usage + + +log = logging.getLogger(__name__) + +__all__ = ["report_exportability"] + + +def _generate_inputs_for_submodules( + model: torch.nn.Module, + target_submodules: Iterable[str], + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, +) -> dict[str, tuple[Any, Any]]: + """ + Generate inputs for targeting submodules in the given model. Note that if two submodules refer to the same obj, this + function doesn't work. + + Args: + model: root model. + inputs: inputs to the root model. + target_submodules: submodules that we want to generate inputs for. + + Returns: + A dict that maps from submodule name to its inputs. + """ + kwargs = kwargs or {} + + handles = [] + results = {} + submodule_to_names = {mod: name for name, mod in model.named_modules()} + + def pre_forward(module, module_args, module_kwargs): + results[submodule_to_names[module]] = (module_args, module_kwargs) + + try: + for name, mod in model.named_modules(): + if name in target_submodules: + handles.append( + mod.register_forward_pre_hook(pre_forward, with_kwargs=True) + ) + model(*args, **kwargs) + except Exception as e: + warnings.warn( + f"Failed to generate submodule inputs because of the following error:\n{e}", + stacklevel=2, + ) + finally: + for h in handles: + h.remove() + return results + + +def report_exportability( + mod: torch.nn.Module, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + strict: bool = True, + pre_dispatch: bool = False, +) -> dict[str, Exception | None]: + """ + Report exportability issues for a module in one-shot. + + Args: + mod: root module. + args: args to the root module. + kwargs: kwargs to the root module. + Returns: + A dict that maps from submodule name to the exception that was raised when trying to export it. + `None` means the module is exportable without issue. + Sample output: + { + '': UnsupportedOperatorException(func=), + 'submod_1': UnsupportedOperatorException(func=), + 'submod_2': None + } + """ + + log_export_usage(event="export.report_exportability") + + kwargs = kwargs or {} + + all_submod_names = [name for name, _ in mod.named_modules() if name != ""] + submod_inputs = _generate_inputs_for_submodules(mod, all_submod_names, args, kwargs) + + tried_module_types = set() + report: dict[str, Exception | None] = {} + + def try_export(module, module_name, args, kwargs): + nonlocal submod_inputs, report, strict, pre_dispatch, tried_module_types + + if type(module) in tried_module_types: + return + tried_module_types.add(type(module)) + + if args is not None or kwargs is not None: + try: + torch.export._trace._export( + module, + args, + kwargs, + strict=strict, + pre_dispatch=pre_dispatch, + ) + report[module_name] = None + log.info("Successfully exported `%s`", module_name) + return + except Exception as e: + short_msg = repr(e).split("\n")[0] + log.warning( + "Failed exporting `%s` with exception: %s", module_name, short_msg + ) + report[module_name] = e + + for name, submod in module.named_children(): + sub_module_name = name if module_name == "" else f"{module_name}.{name}" + + submod_args, submod_kwargs = submod_inputs.get( + sub_module_name, (None, None) + ) + + try_export(submod, sub_module_name, submod_args, submod_kwargs) + + return + + try_export(mod, "", args, kwargs) + + unique_issues = set() + for exception in report.values(): + if exception is not None: + key = repr(exception).split("\\n")[0] + unique_issues.add(key) + + log.warning("Found %d export issues:", len(unique_issues)) + for issue in unique_issues: + log.warning(issue) + + return report diff --git a/.venv/lib/python3.12/site-packages/torch/_export/utils.py b/.venv/lib/python3.12/site-packages/torch/_export/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3f51d0efb3b2dd4cf8c8376f180fd1463a95165d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/utils.py @@ -0,0 +1,1693 @@ +import ast +import copy +import dataclasses +import functools +import inspect +import json +import math +import operator +import re +from collections import defaultdict +from collections.abc import Callable, Collection, Generator, Iterable, Sequence +from contextlib import contextmanager +from inspect import ismethod, Parameter +from typing import Any, TYPE_CHECKING + +import torch +from torch._guards import detect_fake_mode +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode, is_fake_tensor +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx._utils import first_call_function_nn_module_stack +from torch.fx.experimental.proxy_tensor import PreDispatchTorchFunctionMode +from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts + + +if TYPE_CHECKING: + import sympy + + from torch._export.passes.lift_constants_pass import ConstantAttrMap + from torch._functorch._aot_autograd.schemas import GraphSignature + from torch._ops import OperatorBase + from torch.export import ExportedProgram + from torch.export.graph_signature import ExportGraphSignature + from torch.fx.experimental.symbolic_shapes import ShapeEnv + from torch.utils._pytree import TreeSpec + +from torch.export.graph_signature import CustomObjArgument, InputKind, OutputKind +from torch.fx._pytree import ( + _deregister_pytree_flatten_spec, + register_pytree_flatten_spec, +) +from torch.utils._pytree import ( + _deregister_pytree_node, + _register_pytree_node, + Context, + FlattenFn, + FromDumpableContextFn, + GetAttrKey, + KeyPath, + keystr, + MappingKey, + SequenceKey, + ToDumpableContextFn, + tree_flatten_with_path, + UnflattenFn, +) + + +placeholder_prefixes = { + InputKind.USER_INPUT: "", + InputKind.PARAMETER: "p_", + InputKind.BUFFER: "b_", + InputKind.CONSTANT_TENSOR: "c_", + InputKind.CUSTOM_OBJ: "obj_", + InputKind.TOKEN: "token", +} + +_DISABLE_ATEN_TO_ASSERTION_PASS = False + + +def _collect_and_set_constant_attrs( + graph_signature: "ExportGraphSignature", + constants: dict[str, Any], + mod: torch.nn.Module, +) -> "ConstantAttrMap": + # the exported module will store constants & non-persistent buffers such that + # retracing treats them as persistent buffers, so we inform the constants lifting pass + # and overwrite the new graph signature using the previous program. This is intended to only be used + # in run_decompositions where we still have access to original EP. + from torch._export.passes.lift_constants_pass import ConstantAttrMap + + constant_attrs = ConstantAttrMap() + non_persistent_buffers = { + spec.target + for spec in graph_signature.input_specs + if spec.kind == InputKind.BUFFER and not spec.persistent + } + for name, value in constants.items(): + if name in non_persistent_buffers: + continue + # recursive getattr + _mod = mod + *atoms, attr = name.split(".") + for atom in atoms: + _mod = getattr(_mod, atom) + # remove as buffer, reassign as constant/non-persistent buffer + _mod._buffers.pop(attr, None) + setattr(_mod, attr, value) + constant_attrs.add(value, name) + return constant_attrs + + +def _register_constants_as_buffers( + mod: torch.fx.GraphModule, + state_dict: dict[str, Any], + non_persistent_buffers: Collection[str], +) -> set[str]: + # TODO some annoying circular dependency issue + from torch.export.unflatten import _assign_attr, _AttrKind + + temp_registered_constants = set() + + for node in mod.graph.nodes: + if node.op == "get_attr": + target = torch.fx.graph_module._get_attr(mod, node.target) + if isinstance(target, torch.Tensor): + # Make sure we also check if the original buffer is + # non persistent as well. + if (node.target not in state_dict) and ( + node.target not in non_persistent_buffers + ): + torch.fx.graph_module._del_attr(mod, node.target) + _assign_attr(target, mod, node.target, _AttrKind.BUFFER, False) + temp_registered_constants.add(node.target) + + mod.recompile() + + return temp_registered_constants + + +def _override_graph_signature_for_temp_registered_constants( + sig: "ExportGraphSignature", temp_registered_constants: set[str] +) -> "ExportGraphSignature": + for spec in sig.input_specs: + if spec.target in temp_registered_constants: + spec.kind = InputKind.CONSTANT_TENSOR + spec.persistent = None + + for spec in sig.output_specs: + if ( + spec.kind == OutputKind.BUFFER_MUTATION + and spec.target in temp_registered_constants + ): + raise RuntimeError( + f"Constant {spec.target} is mutated in the forward method. Pls register it as buffer" + ) + + return sig + + +def _overwrite_signature_for_non_persistent_buffers( + old_sig: "ExportGraphSignature", new_sig: "ExportGraphSignature" +) -> "ExportGraphSignature": + # overwrite signature for non-persistent buffers + non_persistent_buffers = { + spec.target + for spec in old_sig.input_specs + if spec.kind == InputKind.BUFFER and not spec.persistent + } + + for spec in new_sig.input_specs: + if spec.kind == InputKind.BUFFER and spec.target in non_persistent_buffers: + spec.persistent = False + return new_sig + + +def _collect_param_buffer_metadata(mod: torch.fx.GraphModule) -> dict[str, Any]: + """ + Param/buffer metadata needs to be saved before lowering to aten IR + because aten IR lifts them, as a result, automatic preservation doesn't work. + This is intended to be called on the strict mode tracing right before lowering to + aten IR OR run_decomposition pass. + """ + params_buffers_to_node_meta = {} + + def _getattr(model: torch.fx.GraphModule, attr_name: str) -> Any: + *prefix, field = attr_name.split(".") + t = model + for item in prefix: + t = getattr(t, item, None) # type: ignore[assignment] + if t is None: + raise AssertionError(f"attribute {item!r} not found in path") + + return getattr(t, field) + + for node in mod.graph.nodes: + target = node.target + meta = node.meta + if node.op == "call_module": + submodule = _getattr(mod, target) + if isinstance(submodule, torch.nn.Module): + for name, _ in submodule.named_parameters( + recurse=True, remove_duplicate=False + ): + params_buffers_to_node_meta[target + "." + name] = meta + + for name, _ in submodule.named_buffers( + recurse=True, remove_duplicate=False + ): + params_buffers_to_node_meta[target + "." + name] = meta + + if node.op == "get_attr": + submodule = _getattr(mod, target) + if not isinstance(submodule, torch.fx.GraphModule): + params_buffers_to_node_meta[target] = meta + + # If the call_function uses param as input, we also need to update params' meta + # with this call_function node's meta. + # This is basically the same flow as torch.fx.traceback.preserve_meta() + if node.op == "call_function" and not isinstance( + node.target, torch._ops.HigherOrderOperator + ): + for arg in node._input_nodes: + if arg.op == "get_attr": + for entry in torch.fx.proxy._COPY_META_FIELDS: + # the custom field should not be copied + if entry == "custom": + continue + if entry in meta: + params_buffers_to_node_meta[arg.target][entry] = meta[entry] + + return params_buffers_to_node_meta + + +def _maybe_find_pre_dispatch_tf_mode_for_export() -> ( + PreDispatchTorchFunctionMode | None +): + if not torch.compiler.is_exporting(): + return None + + if not torch._C._is_torch_function_mode_enabled(): + return None + + torch_function_mode_stack = torch.overrides._get_current_function_mode_stack() + + pre_dispatch_tf_modes = [ + mode + for mode in torch_function_mode_stack + if isinstance(mode, PreDispatchTorchFunctionMode) + ] + + if len(pre_dispatch_tf_modes) > 1: + raise AssertionError( + f"Expected only one PreDispatchTorchFunctionMode, found {len(pre_dispatch_tf_modes)}" + ) + + if len(pre_dispatch_tf_modes) == 0: + return None + + mode = pre_dispatch_tf_modes[0] + return mode + + +def _populate_param_buffer_metadata_to_new_gm( + params_buffers_to_node_meta: dict[str, Any], + gm: torch.fx.GraphModule, + new_sig: "ExportGraphSignature", +) -> None: + """ + Given that we collected param'buffer metadata before, we put them back in + newly traced graph module + """ + # Don't copy over nn_module_stack, stack_trace metadata for params/buffers nodes + for metadata in params_buffers_to_node_meta.values(): + metadata.pop("nn_module_stack", None) + metadata.pop("stack_trace", None) + + inputs_to_parameters = new_sig.inputs_to_parameters + inputs_to_buffers = new_sig.inputs_to_buffers + for node in gm.graph.nodes: + if node.op == "placeholder": + if node.target in inputs_to_parameters: + param_name = inputs_to_parameters[node.target] + if param_name in params_buffers_to_node_meta: + for k, v in params_buffers_to_node_meta[param_name].items(): + node.meta[k] = v + if node.target in inputs_to_buffers: + buffer_name = inputs_to_buffers[node.target] + if buffer_name in params_buffers_to_node_meta: + for k, v in params_buffers_to_node_meta[buffer_name].items(): + node.meta[k] = v + + +def _get_shape_env_from_gm(gm: torch.fx.GraphModule) -> "ShapeEnv | None": + vals = [ + node.meta["val"] + for node in gm.graph.nodes + if node.meta.get("val", None) is not None + ] + + fake_mode = _detect_fake_mode_from_gm(gm) + if fake_mode is not None: + return fake_mode.shape_env + for v in vals: + if isinstance(v, torch.SymInt): + return v.node.shape_env + + +def _rename_without_collisions( + name_map: dict[str, str], + find_available: dict[str, int], + used_names: set[str], + orig_name: str, + name: str, + is_placeholder: bool = False, +) -> str: + """ + Renames nodes to avoid name collisions, with suffixing. + name_map: map from original name to new name + find_available: map prefix to available suffix + used_names: cache of used names + orig_name: mapping key + name: candidate name (potentially suffixed, e.g. mul_2) + is_placeholder: if the node is a placeholder, avoid detecting suffix + """ + match = re.match(r"(.*)_(\d+)", name) + key = name + + if match and not is_placeholder: + prefix, n = match.group(1), match.group(2) + key = prefix + + new_name = name + if new_name in used_names: + new_name = f"{key}_{find_available[key] + 1}" + + match = re.match(r"(.*)_(\d+)", new_name) + if match: + prefix, n = match.group(1), match.group(2) + if int(n) > find_available[prefix]: + find_available[prefix] = int(n) + + name_map[orig_name] = new_name + used_names.add(new_name) + + return name_map[orig_name] + + +def get_keystr(key_path: KeyPath) -> str: + """For a given index into the flat_args, return a human readable string + describing how to access it, e.g. "*args["foo"][0].bar" + """ + # Prefix the keypath with "*args" or "**kwargs" to make it clearer where + # the arguments come from. Ultimately we ought to serialize the + # original arg names for the best error message here. + args_kwargs_key_path = key_path[0] + if not isinstance(args_kwargs_key_path, SequenceKey): + raise AssertionError( + f"expected SequenceKey, got {type(args_kwargs_key_path).__name__}" + ) + if args_kwargs_key_path.idx == 0: + return f"*args{keystr(key_path[1:])}" + else: + kwarg_key = key_path[1] + if not isinstance(kwarg_key, (GetAttrKey, MappingKey)): + raise AssertionError( + f"expected GetAttrKey or MappingKey, got {type(kwarg_key).__name__}" + ) + name = str(kwarg_key)[1:-1] # get rid of the enclosed [] + return f"{name}{keystr(key_path[2:])}" + + +def _check_symint( + symint: int | torch.SymInt, + arg: int, + range_constraints: dict["sympy.Expr", Any], + unification_map: dict["sympy.Symbol", Any], + keypath: KeyPath, + i: int | None = None, +) -> None: + from torch.export.dynamic_shapes import _IntWrapper + + if ( + isinstance(arg, torch.SymInt) + and not arg.node.expr.is_number + or isinstance(arg, _IntWrapper) + ): + # This can happen when, say, arg is a fake tensor. + # We do not run checks on symbolic shapes of fake inputs as + # such checks can affect the shape env. + return + + import sympy + + from torch._export.passes.add_runtime_assertions_for_constraints_pass import ( + _convert_range_to_int, + ) + from torch.utils._sympy.solve import try_solve + + if isinstance(symint, torch.SymInt) and len(symint.node.expr.free_symbols) == 1: + symbol = next(iter(symint.node.expr.free_symbols)) + if symbol in unification_map: + existing_dim = symint.node.expr.subs(unification_map) + if arg != existing_dim: + path = get_keystr(keypath) + if i is not None: + path += f".shape[{i}]" + raise RuntimeError( + f"Expected input at {path} to be equal to {existing_dim}, but got {arg}", + ) + else: + if isinstance(symint.node.expr, sympy.Symbol): + # Short cut for try_solve below. Also useful in cases where + # sympy.Eq(symint.node.expr, arg) would evaluate to False + # purely because symbol is constrained to be size-like, + # e.g., when symint.node.expr = symbol and arg = 0. + unification_map[symbol] = int(arg) + else: + solution = try_solve(sympy.Eq(symint.node.expr, arg), symbol) + if solution is None: + path = get_keystr(keypath) + if i is not None: + path += f".shape[{i}]" + raise RuntimeError( + f"Expected input {path} = {arg} to be " + f"of the form {symint.node.expr}, where {symbol} is an integer" + ) + else: + unification_map[symbol] = int(solution[1]) + + if symint.node.expr in range_constraints: + min_val, max_val = _convert_range_to_int( + range_constraints[symint.node.expr] + ) + # NOTE: we allow dimensions to be 0/1 at runtime + if min_val > 2: + if arg < min_val: + path = get_keystr(keypath) + if i is not None: + path += f".shape[{i}]" + raise RuntimeError( + f"Expected input at {path} to be >= {min_val}, but got {arg}", + ) + if max_val < math.inf: + if arg > max_val: + path = get_keystr(keypath) + if i is not None: + path += f".shape[{i}]" + raise RuntimeError( + f"Expected input at {path} to be <= {max_val}, but got {arg}", + ) + elif isinstance(symint, torch.SymInt) and not symint.node.expr.is_number: + # this means we deferred a guard from export analysis to runtime, let this pass + # we'll add a runtime assert checking equality to this replacement expression + pass + elif arg != int(symint): + path = get_keystr(keypath) + if i is not None: + path += f".shape[{i}]" + raise RuntimeError( + f"Expected input at {path} to be equal to {symint}, but got {arg}. " + "If you meant for this dimension to be dynamic, please re-export and specify dynamic_shapes " + "(e.g. with Dim.DYNAMIC)" + ) + + +def _check_input_constraints_for_graph( + input_placeholders: list[torch.fx.Node], + flat_args_with_path: Sequence[tuple[tuple[Any, ...], Any]], + range_constraints: dict["sympy.Expr", Any], +) -> None: + if len(flat_args_with_path) != len(input_placeholders): + raise RuntimeError( + "Unexpected number of inputs " + f"(expected {len(input_placeholders)}, got {len(flat_args_with_path)})" + ) + # NOTE: export already guarantees that the same symbol is used in metadata + # for all InputDims related by equality constraints, so we can just unify + # symbols with given input dimension values to check equality constraints. + unification_map: dict[sympy.Symbol, Any] = {} + for (key_path, arg), node in zip(flat_args_with_path, input_placeholders): + node_val = node.meta.get("val") + if is_fake_tensor(node_val): + if not isinstance(arg, torch.Tensor): + raise RuntimeError( + f"Expected input at {get_keystr(key_path)} to be a tensor, but got {type(arg)}", + ) + + if len(node_val.shape) != len(arg.shape): + raise RuntimeError( + f"Unexpected number of dimensions in input at {get_keystr(key_path)}.shape " + f"(expected {node_val.shape}, got {arg.shape})" + ) + + for j, (arg_dim, node_dim) in enumerate(zip(arg.shape, node_val.shape)): + _check_symint( + node_dim, arg_dim, range_constraints, unification_map, key_path, j + ) + + elif isinstance(node_val, (int, float, str)): + if type(arg) is not type(node_val): + raise RuntimeError( + f"Expected input at {get_keystr(key_path)} to be equal to {node_val}, but got {arg}", + ) + # NaN != NaN in Python, so use math.isnan for NaN-to-NaN comparison + if isinstance(node_val, float) and math.isnan(node_val): + if not isinstance(arg, float) or not math.isnan(arg): + raise RuntimeError( + f"Expected input at {get_keystr(key_path)} to be nan, but got {arg}", + ) + elif arg != node_val: + raise RuntimeError( + f"Expected input at {get_keystr(key_path)} to be equal to {node_val}, but got {arg}", + ) + elif isinstance(node_val, torch.SymInt): + _check_symint( + node_val, + arg, + range_constraints, + unification_map, + key_path, + None, + ) + + +def register_dataclass_as_pytree_node( + cls: type[Any], + flatten_fn: FlattenFn | None = None, + unflatten_fn: UnflattenFn | None = None, + *, + serialized_type_name: str | None = None, + to_dumpable_context: ToDumpableContextFn | None = None, + from_dumpable_context: FromDumpableContextFn | None = None, + return_none_fields: bool = False, +) -> None: + if not dataclasses.is_dataclass(cls): + raise AssertionError( + f"Only dataclasses can be registered with this function: {cls}" + ) + + @torch._dynamo.dont_skip_tracing + def default_flatten_fn(obj: Any) -> tuple[list[Any], Context]: + flattened = [] + flat_names = [] + none_names = [] + for f in dataclasses.fields(obj): + name, val = f.name, getattr(obj, f.name) + if val is not None or return_none_fields: + flattened.append(val) + flat_names.append(name) + else: + none_names.append(name) + return flattened, [flat_names, none_names] + + @torch._dynamo.dont_skip_tracing + def default_unflatten_fn(values: Iterable[Any], context: Context) -> Any: + flat_names, none_names = context + return cls(**dict(zip(flat_names, values)), **dict.fromkeys(none_names)) + + @torch._dynamo.dont_skip_tracing + def default_flatten_fn_with_keys(obj: Any) -> tuple[list[Any], Context]: + flattened, (flat_names, _none_names) = flatten_fn(obj) # type: ignore[misc] + return [(MappingKey(k), v) for k, v in zip(flat_names, flattened)], flat_names + + flatten_fn = flatten_fn if flatten_fn is not None else default_flatten_fn + unflatten_fn = unflatten_fn if unflatten_fn is not None else default_unflatten_fn + + if (to_dumpable_context is None) ^ (from_dumpable_context is None): + raise ValueError( + f"Both to_dumpable_context and from_dumpable_context for {cls} must " + "be None or registered." + ) + + _register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + flatten_with_keys_fn=default_flatten_fn_with_keys, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + + +def is_param(program: "ExportedProgram", node: torch.fx.Node) -> bool: + """ + Checks if the given node is a parameter within the exported program + """ + + return node.name in program.graph_signature.inputs_to_parameters + + +def get_param( + program: "ExportedProgram", + node: torch.fx.Node, +) -> torch.nn.Parameter | None: + """ + Returns the parameter associated with the given node in the exported program. + Returns None if the node is not a parameter within the exported program + """ + + if is_param(program, node): + parameter_name = program.graph_signature.inputs_to_parameters[node.name] + return program.state_dict[parameter_name] + + return None + + +def is_buffer(program: "ExportedProgram", node: torch.fx.Node) -> bool: + """ + Checks if the given node is a buffer within the exported program + """ + + return node.name in program.graph_signature.inputs_to_buffers + + +def get_buffer( + program: "ExportedProgram", + node: torch.fx.Node, +) -> torch.Tensor | None: + """ + Returns the buffer associated with the given node in the exported program. + Returns None if the node is not a buffer within the exported program + """ + + if is_buffer(program, node): + buffer_name = program.graph_signature.inputs_to_buffers[node.name] + if buffer_name in program.graph_signature.non_persistent_buffers: + return program.constants[buffer_name] + else: + return program.state_dict[buffer_name] + + return None + + +def is_lifted_tensor_constant( + program: "ExportedProgram", + node: torch.fx.Node, +) -> bool: + """ + Checks if the given node is a lifted tensor constant within the exported program + """ + + return node.name in program.graph_signature.inputs_to_lifted_tensor_constants + + +def get_lifted_tensor_constant( + program: "ExportedProgram", + node: torch.fx.Node, +) -> torch.Tensor | None: + """ + Returns the lifted tensor constant associated with the given node in the exported program. + Returns None if the node is not a lifted tensor constant within the exported program + """ + + if is_lifted_tensor_constant(program, node): + lifted_tensor_name = program.graph_signature.inputs_to_lifted_tensor_constants[ + node.name + ] + return program.constants[lifted_tensor_name] + + return None + + +def sequential_split( + gm: torch.fx.GraphModule, + node_call_back: Callable[[torch.fx.Node], torch.fx.Node | bool], +) -> torch.fx.GraphModule: + """ + sequential_split creates a new graph module that splits the input graph module into multiple submodules + based on the node_call_back. It doesn't mutate the input graph module. The node_call_back should return + True if the node is a delimiter. Delimiter will be the first node in the next submodule. + """ + from torch.fx.passes.split_module import split_module + + split_map = {} + split_id = 0 + for node in gm.graph.nodes: + if node_call_back(node): + split_id += 1 + split_map[node] = split_id + + new_gm = split_module( + gm, + gm, + lambda node: split_map[node], + keep_original_order=True, + keep_original_node_name=True, + ) + # Keep the codegen from original graph module to preserve e.g. pytree info. + new_gm.graph._codegen = gm.graph._codegen + new_gm.recompile() + return new_gm + + +def nodes_filter( + nodes: list[torch.fx.Node], node_call_back: Callable[[torch.fx.Node], object] +) -> list[torch.fx.Node]: + """Returns the nodes that match the node_call_back as a list.""" + return [node for node in nodes if node_call_back(node)] + + +@contextmanager +def _disable_aten_to_metadata_assertions() -> Generator[None, None, None]: + global _DISABLE_ATEN_TO_ASSERTION_PASS + orig_val = _DISABLE_ATEN_TO_ASSERTION_PASS + _DISABLE_ATEN_TO_ASSERTION_PASS = True + try: + yield + finally: + _DISABLE_ATEN_TO_ASSERTION_PASS = orig_val + + +def _insert_aten_to_metadata_assert_pass(gm: torch.fx.GraphModule) -> None: + from torch._export.passes._node_metadata_hook import ( + _node_metadata_hook, + _set_node_metadata_hook, + ) + + if _DISABLE_ATEN_TO_ASSERTION_PASS: + return + + aten_to_variants = [ + torch.ops.aten.to.device, + torch.ops.aten.to.dtype, + torch.ops.aten.to.dtype_layout, + ] + for node in gm.graph.nodes: + if node.target in aten_to_variants: + if ( + node.prev.target is torch.ops.aten._assert_tensor_metadata.default + and node.args[0] == node.prev.args[0] + ): + # skip if already guarded + continue + + if (tensor_val := node.args[0].meta.get("val")) is not None: + with ( + gm.graph.inserting_before(node), + _set_node_metadata_hook( + gm, + functools.partial( + _node_metadata_hook, + metadata={ + "stack_trace": node.meta.get("stack_trace"), + "nn_module_stack": node.meta.get("nn_module_stack"), + }, + ), + ), + ): + gm.graph.call_function( + torch.ops.aten._assert_tensor_metadata.default, + args=(node.args[0],), + kwargs={ + "dtype": tensor_val.dtype, + "device": tensor_val.device, + "layout": tensor_val.layout, + }, + ) + + +def apply_runtime_assertion_pass( + gm: torch.fx.GraphModule, graph_signature: "GraphSignature" +) -> tuple[torch.fx.GraphModule, "GraphSignature"]: + from torch._export.passes._node_metadata_hook import ( + _node_metadata_hook, + _set_node_metadata_hook, + ) + from torch._functorch._aot_autograd.input_output_analysis import _graph_output_names + + if not torch._dynamo.config.do_not_emit_runtime_asserts: + stack_trace = ( + 'File "torch/fx/passes/runtime_assert.py", line 24, ' + "in insert_deferred_runtime_asserts" + ) + with _set_node_metadata_hook( + gm, + functools.partial( + _node_metadata_hook, metadata={"stack_trace": stack_trace} + ), + ): + shape_env = _get_shape_env_from_gm(gm) + if shape_env: + insert_deferred_runtime_asserts( + gm, + shape_env, + f"exported program: {first_call_function_nn_module_stack(gm.graph)}", + export=True, + ) + + # insert runtime assertions for aten.to nodes + _insert_aten_to_metadata_assert_pass(gm) + + # update output specs + gm.recompile() + graph_signature.user_outputs = _graph_output_names(gm) + return gm, graph_signature + + +def nodes_first( + nodes: list[torch.fx.Node], + node_call_back: Callable[[torch.fx.Node], object] | None = None, +) -> torch.fx.Node | None: + """ + Returns the first node that matches the node_call_back. If no node matches, returns None. + When node_call_back is None, returns the first node in the node list. + """ + ret = nodes_filter(nodes, node_call_back if node_call_back else lambda node: True) + if len(ret) > 0: + return ret[0] + return None + + +def nodes_count( + nodes: list[torch.fx.Node], node_call_back: Callable[[torch.fx.Node], object] +) -> int: + """Returns the number of nodes that match the node_call_back.""" + return len(nodes_filter(nodes, node_call_back)) + + +def nodes_map( + nodes: list[torch.fx.Node], node_call_back: Callable[[torch.fx.Node], object] +) -> list[torch.fx.Node]: + """ + Sequentially visit the nodes list and invoke node_call_back on each element. + Returns the nodes list after the node_call_back is invoked on each element. + """ + for node in nodes: + node_call_back(node) + return nodes + + +def node_replace_(old_node: torch.fx.Node, new_node: torch.fx.Node) -> None: + """ + Replace all uses of old_node with new_node. + """ + old_node.replace_all_uses_with(new_node) + old_node.users.clear() + old_node.graph.erase_node(old_node) + + +def _update_gm_meta_if_possible(gm: torch.fx.GraphModule, mod: torch.nn.Module) -> None: + if ( + isinstance(mod, torch.fx.GraphModule) + and hasattr(mod, "meta") + and "custom" in mod.meta + ): + gm.meta.update({"custom": mod.meta["custom"]}) + + +def node_inline_(call_mod_node: torch.fx.Node) -> torch.fx.GraphModule | None: + """ + Inline the submodule of the given node into the parent module. + Note: we only support the case where submodule takes tensors inputs. + """ + if call_mod_node.op != "call_module": + raise AssertionError(f"expected call_module op, got {call_mod_node.op}") + gm = call_mod_node.graph.owning_module + if gm is None: + raise AssertionError("owning_module should not be None") + + if not isinstance(call_mod_node.target, str): + raise AssertionError( + f"expected target to be str, got {type(call_mod_node.target).__name__}" + ) + sub_gm = getattr(gm, call_mod_node.target) + + phs = (node for node in sub_gm.graph.nodes if node.op == "placeholder") + body = ( + node for node in sub_gm.graph.nodes if node.op not in ("placeholder", "output") + ) + output = [node for node in sub_gm.graph.nodes if node.op == "output"] + + for ph, arg in zip(phs, call_mod_node.args): + if not isinstance(arg, torch.fx.Node): + raise AssertionError(f"expected fx.Node, got {type(arg)}") + node_replace_(ph, arg) + + with gm.graph.inserting_before(call_mod_node): + for node in body: + new_node = gm.graph.node_copy(node) + if node.op == "get_attr": + if not isinstance(new_node.target, str): + raise AssertionError( + f"Expected str target for get_attr, got {type(new_node.target)}" + ) + if not isinstance(node.target, str): + raise AssertionError( + f"Expected str target for get_attr, got {type(node.target)}" + ) + new_target_name = new_node.target + if hasattr(gm, new_target_name): + # Loop through and find the "submod_{i}" that have no name collision + i = 1 + new_target_name = f"submod_{i}" + while hasattr(gm, new_target_name): + i += 1 + new_target_name = f"submod_{i}" + new_node.target = new_target_name + setattr(gm, new_node.target, getattr(sub_gm, node.target)) + node_replace_(node, new_node) + + if len(output) > 0: + if len(output) != 1 or len(output[0].args) != 1: + raise AssertionError( + f"expected exactly 1 output with 1 arg, got {len(output)} outputs" + ) + new_output = output[0].args[0] + + if isinstance(new_output, torch.fx.Node): + # Clear the users of the output node and set + # the users to be the users of original call_module node. + new_output.users.clear() + node_replace_(call_mod_node, new_output) + elif isinstance(new_output, (list, tuple)): + # Pop subgraph output node from users. + for node in new_output: + node.users.pop(output[0]) + + # Inline the get_item calls for the output node. + get_item_users = nodes_filter( + list(call_mod_node.users.keys()), + lambda node: node.op == "call_function" + and node.target is operator.getitem, + ) + # get_item_node.args[1] is the idx referring to new_output[idx] + nodes_map( + get_item_users, + lambda get_item_node: node_replace_( + get_item_node, + # pyrefly: ignore[bad-index] # TODO getitem idx is an int FX arg + new_output[get_item_node.args[1]], + ), + ) + call_mod_node.graph.erase_node(call_mod_node) + else: + raise NotImplementedError( + f"Unsupported output type {type(new_output)}. Expect it to be a Node or a list/tuple of Nodes." + ) + else: + call_mod_node.graph.erase_node(call_mod_node) + + gm.delete_all_unused_submodules() + gm.recompile() + return gm + + +def _get_torch_jit_trace_forward_signature(mod: torch.nn.Module) -> inspect.Signature: + """ + Get source code and parse argument names using AST. The function returns + a signature of the forward() function. + + # TODO: Directly provide inspect.signature compatible TS-d module. + """ + ast_mod = ast.parse(mod.code) # type: ignore[call-overload] + ast_func_def: ast.FunctionDef = ast_mod.body[0] + + # FIXME(jiashenc): TorchScript should only allow positional or keywords arguments. + arg_type_map = {"args": Parameter.POSITIONAL_OR_KEYWORD} + + # Traverse all argument types in AST tree and create associated parameters. + param_list = [] + for arg_type, param_type in arg_type_map.items(): + arg_name_list = [a.arg for a in getattr(ast_func_def.args, arg_type)] + for arg_name in arg_name_list: + if arg_name == "self": + continue # Skip self argument. + param_list.append(inspect.Parameter(arg_name, param_type)) + + return inspect.Signature(parameters=param_list) + + +def _bind_signature_to_inputs( + mod: torch.nn.Module, fake_args: tuple[Any, ...], fake_kwargs: dict[str, Any] +) -> dict[str, Any]: + if isinstance(mod, (torch.jit.ScriptModule, torch.jit.TracedModule)): + sig = _get_torch_jit_trace_forward_signature(mod) + + # Sanity check for placeholder names coming from TorchScript. + if len(sig.parameters) != len(fake_args) + len(fake_kwargs): + raise AssertionError( + "Arguments other than POSITIONAL_OR_KEYWORD kinds in forward() " + "are not supported in _get_torch_jit_trace_forward_signature" + ) + else: + sig = inspect.signature(mod.forward) + + # Rather than binding both fake_args and fake_kwargs to sig names, we + # (partially) bind only fake_args, while reusing fake_kwarg names. This + # ensures that fake_kwargs do not get reordered, which is important to + # match flattened user inputs. + return {**sig.bind_partial(*fake_args).arguments, **fake_kwargs} + + +def _build_cache( + name: str, find_available: dict[str, int], used_names: set[str] +) -> None: + used_names.add(name) + match = re.match(r"(.*)_(\d+)", name) + if match: + prefix, n = match.group(1), match.group(2) + if int(n) > find_available[prefix]: + find_available[prefix] = int(n) + + +def _name_hoo_subgraph_placeholders(gm: torch.fx.GraphModule) -> None: + """ + Propagate placeholder names from the top-level graph into HigherOrderOp subgraphs, + and handle collisions with non-placeholders by count suffixing. + Different HOO subgraph types have different input schemas, so we first enumerate them + and gather the top-level named placeholder nodes. + """ + + # gather all HOO subgraphs and their top-level named placeholder nodes + subgraph_ph_tuples: list[tuple[torch.fx.GraphModule, list[torch.fx.Node]]] = [] + for node in gm.graph.nodes: + if node.op == "call_function" and isinstance( + node.target, torch._ops.HigherOrderOperator + ): + # HOO subgraphs have varying input schemas, so we enumerate them there + if node.target._name == "cond": + _, true_graph, false_graph, cond_args = node._args + subgraph_ph_tuples.append((getattr(gm, true_graph.target), cond_args)) + subgraph_ph_tuples.append((getattr(gm, false_graph.target), cond_args)) + elif node.target._name == "wrap_with_set_grad_enabled": + subgraph, phs = node._args[1], node._args[2:] + subgraph_ph_tuples.append((getattr(gm, subgraph.target), phs)) + elif node.target._name == "map_impl": + body_graph, array, args = node._args + subgraph_ph_tuples.append( + (getattr(gm, body_graph.target), array + args) + ) + + # propagate names + for subgraph, hoo_phs in subgraph_ph_tuples: + name_map: dict[str, str] = {} + find_available: dict[str, int] = defaultdict(int) + used_names: set[str] = set() + for i, node in enumerate(subgraph.graph.nodes): + if i < len(hoo_phs): # placeholder, retain name + name_map[node.name] = hoo_phs[i].name + node.name = node.target = hoo_phs[i].name + _build_cache(node.name, find_available, used_names) + else: # non-placeholder, check for collisions + node.name = _rename_without_collisions( + name_map, find_available, used_names, node.name, node.name + ) + + # recurse and recompile + _name_hoo_subgraph_placeholders(subgraph) + subgraph.recompile() + + +def _assign_new_node_names( + gm: torch.fx.GraphModule, + name_map: dict[str, str], + custom_meta: dict[str, Any], +) -> None: + """ + Assign new names to all nodes, in the graph module, from name map. + """ + for node in gm.graph.nodes: + if node.op == "placeholder": + if node.name not in name_map: + raise AssertionError(f"placeholder node {node.name!r} not in name_map") + node.name = node.target = name_map[node.name] + if node.name in custom_meta: + if node.meta.get("custom") is None: + empty_custom: dict[str, Any] = {} + node.meta["custom"] = empty_custom + else: + # Assert if any existing key has different value + for k, v in node.meta["custom"].items(): + if ( + k in custom_meta[node.name] + and v != custom_meta[node.name][k] + ): + raise AssertionError( + f"Mismatch in custom metadata for key {k}. Value in " + f"node.meta is {v} and value in custom_meta is {custom_meta[node.name][k]}." + ) + node.meta["custom"].update(custom_meta[node.name]) + # if the constant obj is an input, we also need to update meta["val"] + # because this is created before the placeholder naming pass + if isinstance(node.meta["val"], CustomObjArgument): + node.meta["val"].name = node.name + elif node.name in name_map: + node.name = name_map[node.name] + + +def placeholder_naming_pass( + gm: torch.fx.GraphModule, + export_graph_signature: "ExportGraphSignature", + mod: torch.nn.Module, + fake_args: tuple[Any, ...], + fake_kwargs: dict[str, Any], + fake_params_buffers: dict[str, torch.Tensor | torch.nn.Parameter], + constants: dict[str, Any], +) -> None: + """ + This pass is run at the end of _export_non_strict() to assign better placeholder node names: + - User inputs: + These follow the signature of mod.forward(), e.g. forward(x, y) produces nodes x, y. + For nested inputs from dictionaries, lists, tuples, or dataclasses, + the names are a concatenation of the path to the tensor. + e.g. x = { + 'a': torch.randn(), + 'b': [torch.randn(), torch.randn()] + } + produces nodes x_a, x_b_0, x_b_1. + - Parameters/buffers/constants/custom objects: + These follow the FQN of the object, prefixed by "p", "b", "c", "obj" respectively. + e.g. self.bar.l0.weight produces "p_bar_l0_weight". + - Effect tokens: + These are named token, token_1, ... + """ + + custom_meta: dict[str, Any] = {} + if isinstance(mod, torch.fx.GraphModule): + for node in mod.graph.nodes: + if "custom" in node.meta: + custom_meta[node.name] = node.meta["custom"] + + def _strip_name(x: str) -> str: + if x.startswith("L__self___"): + x = x[len("L__self___") :] + elif x.startswith("self_"): + x = x[len("self_") :] + x = re.sub(r"[^a-zA-Z0-9]", "_", x) + return x + + def _extract_pytree_key(x: object) -> str: + if isinstance(x, MappingKey): + x = re.sub(r"[^a-zA-Z0-9]", "_", str(x.key)) + return x + elif isinstance(x, SequenceKey): + return str(x.idx) + elif isinstance(x, GetAttrKey): + return x.name + else: + raise RuntimeError(f"Pytree key of type {type(x)} not handled for {x}") + + name_map: dict[str, str] = {} + find_available: dict[str, int] = defaultdict(int) + used_names: set[str] = set() + + # map user input names with mod.forward() signature + combined_args = _bind_signature_to_inputs(mod, fake_args, fake_kwargs) + + flat_args_with_path, _ = tree_flatten_with_path(combined_args) + user_input_names = [ + spec.arg.name + for spec in export_graph_signature.input_specs + if spec.kind == InputKind.USER_INPUT + ] + + # use pytree path to name nested user inputs + for (arg_path, _arg), user_input_name in zip(flat_args_with_path, user_input_names): + if user_input_name: + _rename_without_collisions( + name_map, + find_available, + used_names, + user_input_name, + placeholder_prefixes[InputKind.USER_INPUT] + + "_".join(_extract_pytree_key(x).lower() for x in arg_path), + is_placeholder=True, + ) + + # use graph signature input specs to map param/buffer/constant names + # name effect tokens as token, token_1, ... (these aren't visible to user) + for spec in export_graph_signature.input_specs: + if spec.kind == InputKind.USER_INPUT: + continue + if spec.kind == InputKind.TOKEN: + base_name = "" + else: + # pyrefly: ignore[bad-argument-type] # TODO non-token specs always have a str target + base_name = _strip_name(spec.target).lower() + base_name = re.sub(r"[^a-zA-Z0-9]", "_", base_name) + + _rename_without_collisions( + name_map, + find_available, + used_names, + spec.arg.name, + placeholder_prefixes[spec.kind] + base_name, + is_placeholder=True, + ) + if base_name in custom_meta: + # the keys in custom_meta are node names from `mod`, + # which is the base_name here. + # we need the re-mapped name for lookup later + custom_meta[name_map[spec.arg.name]] = custom_meta[base_name] + del custom_meta[base_name] + + # handle naming collisions with call_function/get_attr inputs. + # here, we want to prioritize user input names over call_function names + # e.g. not have forward(self, mul): lead to a placeholder node called mul_13, + # so we increment the suffix of call_function nodes as needed + for node in gm.graph.nodes: + if node.op == "placeholder": + continue + _rename_without_collisions( + name_map, find_available, used_names, node.name, node.name + ) + + # assign new node names + _assign_new_node_names(gm, name_map, custom_meta) + + # propagate names to higher order op subgraphs + _name_hoo_subgraph_placeholders(gm) + + # re-generate graph module code + gm.recompile() + + # modify graph signature (input specs, output specs, user input mutations) + for spec in export_graph_signature.input_specs: + if spec.arg.name not in name_map: + raise AssertionError(f"input spec arg {spec.arg.name!r} not in name_map") + spec.arg.name = name_map[spec.arg.name] + if ( # handle targets for custom objects + spec.kind == InputKind.CUSTOM_OBJ and spec.target in name_map + ): + # pyrefly: ignore [bad-index, index-error] + spec.target = name_map[spec.target][4:] # strip obj_ prefix + + for spec in export_graph_signature.output_specs: + if spec.arg.name in name_map: + spec.arg.name = name_map[spec.arg.name] + if spec.kind == OutputKind.USER_INPUT_MUTATION and spec.target in name_map: + # pyrefly: ignore [bad-index, index-error] + spec.target = name_map[spec.target] + + # rename keys in constants dict for custom objects + for name in list(constants.keys()): + constant = constants[name] + if name in name_map and not isinstance( + constant, torch.Tensor + ): # rename custom objects with generic names + new_name = name_map[name] + if ( + new_name != name + and re.match(r"arg(\d+)_1", name) + and new_name != placeholder_prefixes[InputKind.CUSTOM_OBJ] + name + ): + constants[new_name] = constant + del constants[name] + + +def remove_proxy_from_state_dict( + state_dict: dict[str, Any], in_place: bool +) -> dict[str, Any]: + """ + If `in_place` is false, return a new copy of `state_dict` with "proxy" removed from `v.__dict__`. + `v` is the values in the dictionary. + If `in_place` is true, modify `state_dict` in place. + """ + if in_place: + for k, v in state_dict.items(): + if hasattr(v, "proxy"): + delattr(state_dict[k], "proxy") + return state_dict + else: + new_state_dict = {} + for k, v in state_dict.items(): + if hasattr(v, "proxy"): + new_state_dict[k] = v.detach().clone() + else: + new_state_dict[k] = v + return new_state_dict + + +def _detect_fake_mode_from_gm( + gm: torch.fx.GraphModule, +) -> torch._subclasses.fake_tensor.FakeTensorMode | None: + """ + For a given graph module, we look at the "val" of placeholder nodes to find the fake inputs. + Additionally, if gm doesn't have placeholders, we further look at the "example_value" or "val" of other nodes. + If no fake mode is found, we return None for fake_mode. + """ + + fake_inps: list[torch.Tensor] = [] + fake_vals: list[torch.Tensor] = [] + for node in gm.graph.nodes: + if node.op == "placeholder" and "val" in node.meta: + fake_val = node.meta["val"] + if fake_val is not None and isinstance(fake_val, torch.Tensor): + fake_inps.append(fake_val) + elif len(fake_inps) == 0 and ( + "example_value" in node.meta or "val" in node.meta + ): + fake_val = None + if "example_value" in node.meta: + fake_val = node.meta["example_value"] + elif "val" in node.meta: + fake_val = node.meta["val"] + if fake_val is not None and isinstance(fake_val, torch.Tensor): + fake_vals.append(fake_val) + + return detect_fake_mode(fake_inps + fake_vals) + + +@contextmanager +def _disable_load_state_dict_hooks( + mod: torch.nn.Module, +) -> Generator[None, None, None]: + state_dict_hooks: dict[int, Callable[..., object]] = dict(mod._state_dict_hooks) + state_dict_pre_hooks: dict[int, Callable[..., object]] = dict( + mod._state_dict_pre_hooks + ) + mod._state_dict_hooks.clear() + mod._state_dict_pre_hooks.clear() + try: + yield + finally: + mod._state_dict_hooks = state_dict_hooks + mod._state_dict_pre_hooks = state_dict_pre_hooks + + +def _is_cia_op(op: "OperatorBase") -> bool: + return ( + torch._C._dispatch_has_kernel_for_dispatch_key( + op.name(), torch._C.DispatchKey.CompositeImplicitAutograd + ) + or torch._C.DispatchKey.CompositeImplicitAutograd in op.py_kernels + ) + + +def _is_preservable_cia_op(op: "OperatorBase") -> bool: + return _check_valid_to_preserve(op) and _is_cia_op(op) + + +def _is_aten_op(op: "OperatorBase") -> bool: + return op.name().split("::")[0] == "aten" + + +def _is_custom_op(op: "OperatorBase") -> bool: + return not _is_aten_op(op) + + +# We can't cache this because custom op registry API in python can still +# add entries to the C++ dispatcher. +def _materialize_cpp_cia_ops() -> None: + """ + Utility function to query C++ dispatcher to get the all + possible CIA ops and populate them into torch.ops namespace + """ + cia_ops = torch._C._dispatch_get_registrations_for_dispatch_key( + "CompositeImplicitAutograd" + ) + + # Materialize all CIA ops + for op in cia_ops: + namespace, op_name = tuple(op.split("::")) + split_list = op_name.split(".") + # Sometime overload could be missing + if len(split_list) not in (1, 2): + raise AssertionError(f"expected 1 or 2 parts, got {len(split_list)}") + op_name = split_list[0] + op_overload_name = "default" + if len(split_list) == 2: + op_overload_name = split_list[1] + + _ = getattr(getattr(getattr(torch.ops, namespace), op_name), op_overload_name) + + +def _special_op_to_preserve_cia(*args: Any, **kwargs: Any) -> Any: + """ + This is a special marker that tells our infra that we shouldn't decompose this op. + """ + return NotImplemented + + +# Our strategy for deciding if we can preserve a op is following: +# 1. The op should be known statically that it is functional +# 2. If it is maybe aliasing, we decompose because we must know if an op +# is mutating or aliasing. +def _check_valid_to_preserve(op_overload: "OperatorBase") -> bool: + from torch._decomp import _should_decompose_because_unsafe_op + + if _should_decompose_because_unsafe_op(op_overload): + return False + if op_overload in FunctionalTensor.metadata_fns: + return False + + if not hasattr(op_overload, "_schema"): + return False + + alias_info = len( + [i for i in op_overload._schema.arguments if i.alias_info is not None] + ) + + is_mutating_or_aliasing = alias_info != 0 or op_overload._schema.is_mutable + + if is_mutating_or_aliasing: + return False + + if not torch._C._dispatch_has_kernel(op_overload.name()): + return False + + return True + + +@functools.lru_cache(maxsize=1) +def _collect_all_valid_cia_ops_for_aten_namespace() -> set["OperatorBase"]: + return _collect_all_valid_cia_ops_for_namespace(torch.ops.aten) + + +def _collect_all_valid_cia_ops_for_namespace( + op_namespace: torch._ops._OpNamespace, +) -> set["OperatorBase"]: + # Step 1: Materialize all ops from C++ dispatcher + _materialize_cpp_cia_ops() + + # Step 2: Query all ops from python dispatcher + cia_ops = set() + for op in op_namespace: + op_packet = getattr(op_namespace, op) + for op_overload in op_packet.op_overloads(): + if _is_preservable_cia_op(op_overload): + cia_ops.add(op_overload) + return cia_ops + + +def _collect_all_valid_cia_ops() -> set["OperatorBase"]: + """ + This is an util function that gets the all CIA functional ops. + + The algorithm is in 2 steps: + 1. We first query C++ dispatcher to get the list of CIA ops + and then we call getattr on torch.ops.aten to lazily populate + them. + + 2. Sometimes, handful of ops have CIA registered in python dispatcher + but not on the C++ side, these can't be caught at the first step. + So we walk again to get the final list. + + Note that the output of this function should never be modified + """ + cia_ops = set() + for op_namespace_name in torch.ops._dir: + # The reason we split here is because aten ops are safe to cache. + if op_namespace_name != "aten": + if not hasattr(torch.ops, op_namespace_name): + raise AssertionError( + f"torch.ops does not have attribute {op_namespace_name!r}" + ) + op_namespace = getattr(torch.ops, op_namespace_name) + if isinstance(op_namespace, torch._ops._OpNamespace): + cia_ops |= _collect_all_valid_cia_ops_for_namespace(op_namespace) + else: + cia_ops |= _collect_all_valid_cia_ops_for_aten_namespace() + return cia_ops + + +def _get_decomp_for_cia(op: "OperatorBase") -> Callable[..., object]: + # [NOTE] Separating out func.decompose + # Ideally we should be able to just register func.decompose but + # we can't as this decomp is gonna be registered to the py_impl. + # As a result it will infinitely recurse. So we first check if the op + # has py_impl entry for CIA and if it is we use that first. If not, + # we register C++ query to py_impl. + dk = torch._C.DispatchKey.CompositeImplicitAutograd + if dk in op.py_kernels and not isinstance(op.py_kernels[dk], torch._C.DispatchKey): + return op.py_kernels[dk] + + def _special_op_to_decompose_cia(*args: Any, **kwargs: Any) -> Any: + kernel = kwargs["kernel"] + del kwargs["kernel"] + # Can't call kernel.decompose due to infinite recursion as + # we register this kernel to py_impl directly + dk = torch._C.DispatchKey.CompositeImplicitAutograd + if torch._C._dispatch_has_kernel_for_dispatch_key( + kernel.name(), torch._C.DispatchKey.CompositeImplicitAutograd + ): + return kernel._op_dk(dk, *args, **kwargs) + else: + raise AssertionError( + f"Expected {kernel} to have CompositeImplicitAutograd kernel" + ) + + return functools.partial(_special_op_to_decompose_cia, kernel=op) + + +@contextmanager +def _compiling_state_context() -> Generator[None, None, None]: + old_compiling_flag = torch.compiler._is_compiling_flag + old_exporting_flag = torch.compiler._is_exporting_flag + try: + torch.compiler._is_compiling_flag = True + torch.compiler._is_exporting_flag = True + yield + finally: + torch.compiler._is_compiling_flag = old_compiling_flag + torch.compiler._is_exporting_flag = old_exporting_flag + + +def _fakify_params_buffers( + fake_mode: FakeTensorMode, + mod: torch.nn.Module, +) -> dict[str, torch.Tensor | torch.nn.Parameter]: + params_buffers = { + **dict(mod.named_parameters(remove_duplicate=False)), + **dict(mod.named_buffers(remove_duplicate=False)), + } + + faked_params_buffers = {} + memo: dict[int, FakeTensor] = {} + for key, value in params_buffers.items(): + if id(value) in memo: + fake_tensor = memo[id(value)] + else: + fake_tensor = fake_mode.from_tensor(value, static_shapes=True) + memo[id(value)] = fake_tensor + faked_params_buffers[key] = fake_tensor + return faked_params_buffers # type: ignore[return-value] + + +def register_module_as_pytree_input_node(cls: type[torch.nn.Module]) -> None: + """ + Registers a module as a valid input type for :func:`torch.export.export`. + + Args: + mod: the module instance + serialized_type_name: The serialized name for the module. This is + required if you want to serialize the pytree TreeSpec containing this + module. + + Example:: + + import torch + + + class Module(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(3, 3) + + def forward(self, x): + return self.linear(x) + + + torch._export.utils.register_module_as_pytree_node(InputDataClass) + + + class Mod(torch.nn.Module): + def forward(self, x, m): + return m(x) + x + + + ep = torch.export.export(Mod(), (torch.randn(3), Module())) + print(ep) + + """ + if not issubclass(cls, torch.nn.Module): + raise AssertionError(f"expected nn.Module subclass, got {cls}") + + import weakref + + class PrototypeModule(weakref.ref[torch.nn.Module]): + def __init__(self, m: torch.nn.Module, *args: Any, **kwargs: Any) -> None: + super().__init__(m, *args, **kwargs) # type: ignore[call-arg] + if not isinstance(m, torch.nn.Module): + raise AssertionError(f"expected nn.Module, got {type(m).__name__}") + if hasattr(self, "_proto_cls"): + raise AssertionError("_proto_cls should not be set") + self._proto_cls = cls + + def __eq__(self, other: object) -> bool: + return self._proto_cls == other._proto_cls # type: ignore[attr-defined] + + def __deepcopy__(self, memo: dict[Any, Any]) -> "PrototypeModule": + # pyrefly: ignore[bad-argument-type] # TODO referent is alive during deepcopy + return PrototypeModule(self()) + + def default_flatten_fn(obj: Any) -> tuple[list[Any], Context]: + named_parameters = dict(obj.named_parameters()) + named_buffers = dict(obj.named_buffers()) + params_buffers = {**named_parameters, **named_buffers} + return list(params_buffers.values()), [ + list(params_buffers.keys()), + PrototypeModule(obj), + ] + + def default_unflatten_fn(values: Iterable[Any], context: Context) -> Any: + flat_names, ref = context + if ref is None or ref() is None: + raise RuntimeError("Module has been garbage collected") + obj = ref() + if flatten_fn is None: + raise AssertionError("flatten_fn should not be None") + flattened, _ = flatten_fn(obj) + + # NOTE: This helper function will replicate an nn.Module in the exactly same + # structure to be used together with _reparameterize_module. This will + # create a clone of the module with the new parameters and buffers without + # affecting the original module. + def copy_module(mod: torch.nn.Module) -> torch.nn.Module: + ret = copy.copy(mod) + ret.__dict__ = {copy.copy(k): copy.copy(v) for k, v in mod.__dict__.items()} + for name, child in ret.named_children(): + setattr(ret, name, copy_module(child)) + return ret + + if any(v is not o for v, o in zip(values, flattened)): + with torch.nn.utils.stateless._reparametrize_module( + obj, dict(zip(flat_names, values)), tie_weights=True, strict=True + ): + ret = copy_module(obj) + else: + ret = obj + return ret + + def default_flatten_fn_with_keys(obj: Any) -> tuple[list[Any], Context]: + flattened, [flat_names, *args] = flatten_fn(obj) # type: ignore[misc] + return [(MappingKey(k), v) for k, v in zip(flat_names, flattened)], [ + flat_names, + *args, + ] + + flatten_fn = default_flatten_fn + unflatten_fn = default_unflatten_fn + + serialized_type_name = cls.__module__ + "." + cls.__qualname__ + + def to_dumpable_context(context: Context) -> str: + keys, *_ = context + return json.dumps([keys, *([None] * len(_))]) + + def from_dumpable_context(dumpable: str) -> Any: + s = json.loads(dumpable) + s[1] = PrototypeModule(torch.nn.Module()) + return s + + _register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + flatten_with_keys_fn=default_flatten_fn_with_keys, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + + def default_flatten_fn_spec(obj: Any, spec: "TreeSpec") -> list[Any]: + flats, context = flatten_fn(obj) + if context != spec.context: + raise AssertionError(f"context mismatch: {context} != {spec.context}") + return flats + + register_pytree_flatten_spec( + cls, + default_flatten_fn_spec, + ) + + +def deregister_module_as_pytree_input_node(cls: type[torch.nn.Module]) -> None: + _deregister_pytree_node(cls) + _deregister_pytree_flatten_spec(cls) + + +def _sync_state(src: torch.nn.Module, dst: torch.nn.Module) -> None: + if not isinstance(src, torch.nn.Module): + raise AssertionError(f"Expected {src} to be a nn.Module") + if not isinstance(dst, torch.nn.Module): + raise AssertionError(f"Expected {dst} to be a nn.Module") + # Share state (params, buffers) between modules. + # This ensures that state mutations are visible across them. + # Since tensor constants are not mutable, copying (without sharing) is OK. + # Also, primitive constants are specialized, so copying (without sharing) is OK. + dst._parameters = src._parameters + dst._buffers = src._buffers + + +def sync_state(*wrapped_method_modules: torch.nn.Module) -> None: + """ + Sync state between exported modules corresponding to wrapped methods. + This might be necessary after serializing/deserializing due to copying. + """ + if wrapped_method_modules: + m, *other_ms = wrapped_method_modules + for other_m in other_ms: + _sync_state(m, other_m) + + +class _WrappedMethod(torch.nn.Module): + def __init__(self, method: Callable[..., object]) -> None: + super().__init__() + # share state of method's self module + _sync_state(method.__self__, self) # type: ignore[attr-defined] + # redirect forward to method + self.forward = method + + +def wrap_method(method: Callable[..., object]) -> _WrappedMethod: + """ + Wrap a method as a module so that it can be exported. + The wrapped module's forward points to the method, and + the method's original module state is shared. + """ + if not ismethod(method): + raise AssertionError(f"Expected {method} to be a method") + return _WrappedMethod(method) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/verifier.py b/.venv/lib/python3.12/site-packages/torch/_export/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..00a9c9e106f1bedf5acd89b63c84d939c4ad3932 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/verifier.py @@ -0,0 +1,584 @@ +# mypy: allow-untyped-defs +import inspect +import math +import operator +from collections.abc import Iterable +from typing import Any, final, TYPE_CHECKING + +import torch +from torch._library.opaque_object import is_custom_class +from torch._ops import HigherOrderOperator, OpOverload +from torch._subclasses.fake_tensor import FakeTensor +from torch.export.graph_signature import ( + CustomObjArgument, + InputKind, + SymBoolArgument, + SymFloatArgument, + SymIntArgument, + TensorArgument, + TokenArgument, +) +from torch.fx import GraphModule + + +if TYPE_CHECKING: + from torch.export.exported_program import ExportedProgram + + +class SpecViolationError(Exception): + pass + + +def is_functional(op: OpOverload) -> bool: + return not op._schema.is_mutable + + +def _check_has_fake_tensor(node: torch.fx.Node) -> None: + # TODO(angelayi): remove this in favor of _check_val + return _check_val(node) + + +def _check_val(node: torch.fx.Node) -> None: + from torch.fx.experimental.symbolic_shapes import SymBool, SymFloat, SymInt + + def _check_correct_val(val): + if val is None: + return True + elif isinstance(val, (int, bool, str, float)): + return True + elif isinstance( + val, (torch.memory_format, torch.dtype, torch.device, torch.layout) + ): + return True + elif isinstance( + val, (FakeTensor, torch.Tensor) + ): # TODO(zhxchen17) Remove Tensor. + return True + elif isinstance(val, (SymInt, SymFloat, SymBool)): + return True + elif isinstance(val, CustomObjArgument): + return True + elif isinstance(val, Iterable): + return all(_check_correct_val(x) for x in val) + elif is_custom_class(type(val)): + return True + return False + + def _no_returns(op): + if not isinstance(op, OpOverload): + return False + return len(op._schema.returns) == 0 + + if "val" not in node.meta: + if node.op == "call_function" and _no_returns(node.target): + return + raise SpecViolationError(f"Node.meta {node.name} is missing val field.") + + val = node.meta["val"] + if not _check_correct_val(val): + raise SpecViolationError(f"Node.meta {node.name} has invalid val field {val}") + + +def _check_torch_fn(node: torch.fx.Node) -> None: + torch_fn = node.meta.get("torch_fn") + if torch_fn is None: + raise SpecViolationError( + f"Unable to find torch_fn metadata for node {node.name}" + ) + if ( + not isinstance(torch_fn, tuple) + and isinstance(torch_fn[0], str) + and isinstance(torch_fn[1], str) + ): + raise SpecViolationError( + f"Node.meta {node.name} has invalid torch_fn field {torch_fn}" + ) + + +class _VerifierMeta(type): + _registry: dict[str, type["Verifier"]] = {} + + def __new__(metacls, name, bases, attrs): + if bases: + if "check" in attrs or "_check_graph_module" in attrs: + raise SyntaxError("Overriding method check is not allowed.") + if "dialect" not in attrs or attrs["dialect"] == "ATEN": + raise AssertionError( + f"subclass must define dialect != 'ATEN', got {attrs.get('dialect')}" + ) + else: + if "check" not in attrs: + raise AssertionError("base class must define 'check' method") + if "_check_graph_module" not in attrs: + raise AssertionError( + "base class must define '_check_graph_module' method" + ) + if attrs["dialect"] != "ATEN": + raise AssertionError( + f"base class dialect must be 'ATEN', got {attrs['dialect']}" + ) + + if not isinstance(attrs["dialect"], str): + raise AssertionError(f"dialect must be str, got {type(attrs['dialect'])}") + ret = type.__new__(metacls, name, bases, attrs) + metacls._registry[attrs["dialect"]] = ret # type: ignore[assignment] + return ret + + +def getattr_recursive(obj: Any, target: str) -> Any: + target_atoms = target.split(".") + attr_itr = obj + for i, atom in enumerate(target_atoms): + if not hasattr(attr_itr, atom): + raise RuntimeError( + f"Node referenced nonexistent target {'.'.join(target_atoms[:i])}" + ) + attr_itr = getattr(attr_itr, atom) + return attr_itr + + +class Verifier(metaclass=_VerifierMeta): + dialect = "ATEN" + + def allowed_builtin_ops(self) -> list: + return [ + operator.getitem, + operator.add, + operator.mul, + operator.sub, + operator.truediv, + operator.ge, + operator.le, + operator.gt, + operator.lt, + operator.eq, + operator.ne, + operator.floordiv, + operator.mod, + operator.and_, + operator.or_, + operator.not_, + operator.pow, + operator.neg, + operator.abs, + operator.lshift, + operator.rshift, + math.ceil, + math.floor, + math.trunc, + round, + ] + + def allowed_op_types(self) -> tuple[type[Any], ...]: + return (OpOverload, HigherOrderOperator) + + def allowed_getattr_types(self) -> tuple[type[Any], ...]: + return (torch.fx.GraphModule, torch.utils._pytree.TreeSpec) + + def allowed_getattr_types_for_subgm(self) -> tuple[type[Any], ...]: + # subgm in HOP's argument could have getattr(weight) nodes, thus stateful + return ( + torch.fx.GraphModule, + torch.nn.parameter.Parameter, + torch.Tensor, # for buffer and constant tensor + torch.utils._pytree.TreeSpec, + ) + + def check_valid_op(self, op): + pass + + def check_additional(self, gm: GraphModule) -> None: + """ + Additional checks that are specific to some dialects. + """ + + @final + def check(self, ep: "ExportedProgram") -> None: + self._check_graph_module(ep.graph_module) + _verify_exported_program_module_call_graph(ep) + _verify_exported_program_signature(ep) + + @final + def _check_graph_module(self, gm: torch.fx.GraphModule) -> None: + def _allowed_getattr_types(is_toplevel_gm) -> tuple[type[Any], ...]: + if is_toplevel_gm: + ret = self.allowed_getattr_types() + else: + ret = self.allowed_getattr_types_for_subgm() + if any(t is object for t in ret): + raise AssertionError("allowed_getattr_types must not contain 'object'") + return ret + + def _check_valid_op(op) -> None: + def _allowed_builtin_ops() -> list: + ret = self.allowed_builtin_ops() + if not all(inspect.isbuiltin(op) for op in ret): + raise AssertionError("allowed_builtin_ops must all be builtins") + return ret + + def _allowed_op_types() -> tuple[type[Any], ...]: + ret = self.allowed_op_types() + if any(t is object for t in ret): + raise AssertionError("allowed_op_types must not contain 'object'") + return ret + + # TODO Remove this allowlist. + _allowed_torch_functions = ( + torch.autograd.grad_mode.set_grad_enabled, + torch.sym_int, + torch.sym_float, + torch.sym_ite, + torch.sym_max, + torch.sym_min, + torch.sym_not, + torch.sym_sqrt, + torch.sym_sum, + torch.export.custom_ops._call_custom_autograd_function_in_pre_dispatch, + # TODO (tmanlaibaatar) + # Predispatch export is able to contain autograd ops. + # These will be modeled as HOO later + torch._C._set_grad_enabled, + torch.amp.autocast_mode._enter_autocast, + torch.amp.autocast_mode._exit_autocast, + torch.fx.experimental.symbolic_shapes.cast_symbool_to_symint_guardless, + torch._functorch.predispatch._add_batch_dim, + torch._functorch.predispatch._remove_batch_dim, + torch._functorch.predispatch._vmap_increment_nesting, + torch._functorch.predispatch._vmap_decrement_nesting, + torch._functorch.predispatch.lazy_load_decompositions, + torch._functorch.predispatch._make_dual, + torch._functorch.predispatch._unpack_dual, + torch._functorch.predispatch._jvp_increment_nesting, + torch._functorch.predispatch._jvp_decrement_nesting, + torch._functorch.predispatch._unwrap_for_grad, + torch._functorch.predispatch._enter_dual_level, + torch._functorch.predispatch._exit_dual_level, + ) + + if not isinstance(op, _allowed_op_types()): + if ( + op not in _allowed_builtin_ops() + and op not in _allowed_torch_functions + ): + raise SpecViolationError( + f"Operator '{op}' is not an allowed operator type: {_allowed_op_types()}\n" + f"Valid builtin ops: {_allowed_builtin_ops()}" + f"Valid torch functions: {_allowed_torch_functions}" + ) + + if isinstance(op, OpOverload): + # All ops functional + # TODO (tmanlaibaatar) more proper way is needed here + if self.dialect != "TRAINING" and not is_functional(op): + raise SpecViolationError(f"operator '{op}' is not functional") + self.check_valid_op(op) + + for mod in gm.modules(): + is_toplevel_gm = mod is gm + + if not isinstance(mod, torch.fx.GraphModule): + continue + + mod.graph.lint() + for node in mod.graph.nodes: + # TODO(T140410192): should have fake tensor for all dialects + if node.op in {"call_module", "call_method"}: + raise SpecViolationError( + f"call_module is not valid: got a class '{node.target}' ", + ) + + elif node.op == "call_function": + _check_val(node) + + _check_valid_op(node.target) + + elif node.op == "get_attr": + if not isinstance(node.target, str): + raise SpecViolationError( + f"Expected get_attr target to be string, but got {type(node.target)}" + ) + + attr = getattr_recursive(mod, node.target) + if isinstance(attr, torch.nn.Module): + + def _is_type(name, ty): + return isinstance(getattr(attr, name, None), ty) + + if type(attr).__name__ == "LoweredBackendModule": + if ( + _is_type("backend_id", str) + and hasattr(attr, "original_module") + and hasattr(attr, "module_name") + and getattr(attr, "backend_id", None) == "aoti" + ): + continue + if ( + _is_type("backend_id", str) + and _is_type("processed_bytes", bytes) + and _is_type("compile_specs", list) + and hasattr(attr, "original_module") + ): + continue + else: + backend_id = getattr(attr, "backend_id", None) + processed_bytes = getattr(attr, "processed_bytes", None) + compile_specs = getattr(attr, "compile_specs", None) + raise SpecViolationError( + f"Invalid get_attr type {type(attr)}. \n" + f"LoweredBackendModule fields: " + f"backend_id(str) : {type(backend_id)}, " + f"processed_bytes(bytes) : {type(processed_bytes)}, " + f"compile_specs(list) : {type(compile_specs)}" + ) + elif type(attr).__name__ == "AOTInductorEPModule": + continue + + elif type(attr).__name__ == "AOTInductorRunnerWrapper": + continue + + if not isinstance(attr, _allowed_getattr_types(is_toplevel_gm)): + raise SpecViolationError( + f"Invalid get_attr type {type(attr)} on target {node.target}. \n" + f"Valid get_attr types: {_allowed_getattr_types(is_toplevel_gm)}" + ) + + elif node.op == "placeholder": + _check_val(node) + # TODO(zhxchen17) + # elif node.op == "output": + # _check_flattened_outputs() + + self.check_additional(gm) + + +class TrainingIRVerifier(Verifier): + dialect = "TRAINING" + + +def _verify_exported_program_module_call_graph(exported_program) -> None: + module_call_graph = exported_program.module_call_graph + nodes = {node.name for node in exported_program.graph.nodes} + for entry in module_call_graph: + if entry.signature is not None: + for arg in entry.signature.inputs: + if arg.name and arg.name not in nodes: + raise SpecViolationError( + f"Input {arg.name} does not exist in the graph." + ) + for arg in entry.signature.outputs: + if arg.name and arg.name not in nodes: + raise SpecViolationError( + f"Output {arg.name} does not exist in the graph." + ) + + +def _verify_exported_program_signature(exported_program) -> None: + # Check ExportedProgram signature matches + gs = exported_program.graph_signature + + # Lazily computed on first use; avoids calling graph_module.state_dict() + # unless at least one buffer is missing from the top-level state_dict. + _gm_state_dict: dict | None = None + + # Check every node in the signature exists in the graph + input_node_names = [ + node.name for node in exported_program.graph.nodes if node.op == "placeholder" + ] + + if len(input_node_names) != len(gs.input_specs): + input_spec_names = [ + spec.arg.name for spec in gs.input_specs if hasattr(spec.arg, "name") + ] + missing_in_specs = set(input_node_names) - set(input_spec_names) + missing_in_graph = set(input_spec_names) - set(input_node_names) + raise SpecViolationError( + f"Number of graph inputs ({len(input_node_names)}) " + f"does not match number of inputs in the graph signature ({len(gs.input_specs)})\n" + f"Placeholders missing input_specs: {missing_in_specs}\n" + f"Input_specs missing placeholders: {missing_in_graph}" + ) + + for input_spec, node in zip(gs.input_specs, input_node_names): + if isinstance( + input_spec.arg, + (TensorArgument, SymIntArgument, SymFloatArgument, SymBoolArgument), + ): + if input_spec.arg.name != node: + raise SpecViolationError( + f"Input spec name {input_spec.arg.name} does not match node name {node}" + ) + + if input_spec.kind == InputKind.USER_INPUT: + continue + + elif input_spec.kind == InputKind.PARAMETER: + if not isinstance(input_spec.arg, TensorArgument): + raise SpecViolationError( + f"Parameter {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead." + ) + if input_spec.target is None: + raise SpecViolationError( + f"InputSpec for {input_spec.name} has no target." + ) + + param = input_spec.target + if param not in exported_program.state_dict: + raise SpecViolationError(f"Parameter {param} is not in the state dict.") + + if not isinstance(exported_program.state_dict[param], torch.nn.Parameter): + raise SpecViolationError( + f"State dict entry for parameter {param} is not an instance of torch.nn.Parameter." + ) + + elif input_spec.kind == InputKind.BUFFER: + if not isinstance(input_spec.arg, TensorArgument): + raise SpecViolationError( + f"Buffer {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead." + ) + if input_spec.target is None: + raise SpecViolationError( + f"InputSpec for {input_spec.name} has no target." + ) + + buffer = input_spec.target + if input_spec.persistent is None: + raise SpecViolationError( + f"Buffer {buffer} is missing a persistence flag" + ) + + if ( + input_spec.persistent is True + and buffer not in exported_program.state_dict + ): + # Allow buffers that live in constants or in a subgraph + # submodule (e.g. lifted tensor constants from + # invoke_subgraph tracing stored under repeated_subgraph0). + # Use a lazy copy of the graph module state to avoid the + # cost of state_dict() when no fallback is needed. + if buffer not in exported_program.constants: + if _gm_state_dict is None: + _gm_state_dict = exported_program.graph_module.state_dict() + if buffer not in _gm_state_dict: + raise SpecViolationError( + f"Buffer {buffer} is not in the state dict." + ) + + if input_spec.persistent is False and buffer in exported_program.state_dict: + raise SpecViolationError( + f"Non-persistent buffer {buffer} is in the state dict, it should not be." + ) + elif input_spec.kind == InputKind.CONSTANT_TENSOR: + if not isinstance(input_spec.arg, TensorArgument): + raise SpecViolationError( + f"Constant tensor {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead." + ) + if input_spec.target is None: + raise SpecViolationError( + f"InputSpec for {input_spec.name} has no target." + ) + + tensor_const = input_spec.target + if tensor_const not in exported_program.constants: + raise SpecViolationError( + f"Constant tensor {tensor_const} is not in the constants dictionary." + ) + elif input_spec.kind == InputKind.CUSTOM_OBJ: + if not isinstance(input_spec.arg, CustomObjArgument): + raise SpecViolationError( + f"Custom object {input_spec.name} is not a custom object argument. Found {input_spec.arg} instead." + ) + if input_spec.target is None: + raise SpecViolationError( + f"InputSpec for {input_spec.name} has no target." + ) + + custom_obj = input_spec.target + if custom_obj not in exported_program.constants: + raise SpecViolationError( + f"Custom object {custom_obj} is not in the constants dictionary." + ) + elif input_spec.kind == InputKind.TOKEN: + if not isinstance(input_spec.arg, TokenArgument): + raise SpecViolationError( + f"Constant tensor {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead." + ) + else: + raise SpecViolationError(f"Unknown InputKind {input_spec.kind}.") + + # Check outputs + output_node = list(exported_program.graph.nodes)[-1] + if output_node.op != "output": + raise AssertionError(f"last node must be output, got {output_node.op}") + output_nodes = [ + arg.name if isinstance(arg, torch.fx.Node) else arg + for arg in output_node.args[0] + ] + + if len(output_nodes) != len(gs.output_specs): + output_spec_names = [ + spec.arg.name if hasattr(spec.arg, "name") else str(spec.arg) + for spec in gs.output_specs + ] + missing_out_specs = set(output_nodes) - set(output_spec_names) + missing_out_graph = set(output_spec_names) - set(output_nodes) + raise SpecViolationError( + f"Number of output nodes {len(output_nodes)} is different " + f"Than the number of outputs specified by the graph signature: {len(gs.output_specs)}\n" + f"Nodes missing output_specs: {missing_out_specs}\n" + f"Output_specs missing nodes: {missing_out_graph}" + ) + + num_tokens = len(gs.output_tokens) + buffers_to_mutate = gs.buffers_to_mutate + parameters_to_mutate = gs.parameters_to_mutate + user_inputs_to_mutate = gs.user_inputs_to_mutate + end = ( + len(buffers_to_mutate) + + len(parameters_to_mutate) + + len(user_inputs_to_mutate) + + num_tokens + ) + mutate_nodes: list[str] = output_nodes[num_tokens:end] + user_output_nodes = output_nodes[end : end + len(gs.user_outputs)] + + for mutation_node in mutate_nodes: + if mutation_node in buffers_to_mutate: + if buffers_to_mutate[mutation_node] not in gs.buffers: + raise SpecViolationError( + f"Buffer output {mutation_node} does not point to a buffer that exists. \n" + f"Dict of buffers that are mutated, in order: {buffers_to_mutate} \n" + f"Buffer nodes available: {gs.buffers} \n" + ) + elif mutation_node in parameters_to_mutate: + if parameters_to_mutate[mutation_node] not in gs.parameters: + raise SpecViolationError( + f"Parameter output {mutation_node} does not point to a parameter that exists. \n" + f"Dict of parameters that are mutated, in order: {parameters_to_mutate} \n" + f"Parameter nodes available: {gs.parameters} \n" + ) + elif mutation_node in user_inputs_to_mutate: + if user_inputs_to_mutate[mutation_node] not in gs.user_inputs: + raise SpecViolationError( + f"User input output {mutation_node} does not point to a user input that exists. \n" + f"Dict of user inputs that are mutated, in order: {user_inputs_to_mutate} \n" + f"User input nodes available: {gs.user_inputs} \n" + ) + else: + raise SpecViolationError( + f"Mutation node {mutation_node} is neither a buffer nor a user input. " + f"Buffers to mutate: {buffers_to_mutate}, User inputs to mutate: {user_inputs_to_mutate}" + ) + + for user_output_node, user_output_name in zip(user_output_nodes, gs.user_outputs): + if user_output_node != user_output_name: + raise SpecViolationError( + f"User output {user_output_node} is not in the correct " + "order or is not found in the " + f"exported program's user_output list: {gs.user_outputs}. " + ) + + +def load_verifier(dialect: str) -> type[Verifier]: + if dialect == "ATEN" or dialect == "": + return _VerifierMeta._registry.get(dialect, Verifier) + return _VerifierMeta._registry[dialect] diff --git a/.venv/lib/python3.12/site-packages/torch/_export/wrappers.py b/.venv/lib/python3.12/site-packages/torch/_export/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..28418576aac4f773e2b217a2ec86108a83222668 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/wrappers.py @@ -0,0 +1,399 @@ +import inspect +from collections.abc import Callable, Generator, Iterable +from contextlib import contextmanager +from functools import wraps +from typing import Any, TYPE_CHECKING, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch._custom_ops +from torch._C import DispatchKey +from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export +from torch._higher_order_ops.flat_apply import ( + _ConstantFunction, + flat_apply, + to_graphable, +) +from torch._higher_order_ops.strict_mode import strict_mode +from torch._higher_order_ops.utils import autograd_not_implemented, register_fake +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ( + PreDispatchTorchFunctionMode, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.utils import _pytree as pytree +from torch.utils._python_dispatch import is_traceable_wrapper_subclass_type + + +if TYPE_CHECKING: + from torch._subclasses.functional_tensor import BaseFunctionalizeAPI + from torch.fx.experimental.proxy_tensor import _ProxyTracer + from torch.fx.proxy import Proxy + from torch.utils.hooks import RemovableHandle + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +class ExportTracepoint(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("_export_tracepoint") + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + # pyrefly: ignore [missing-attribute] + return super().__call__(*args, **kwargs) + + +_export_tracepoint = ExportTracepoint() + + +@_export_tracepoint.py_impl(ProxyTorchDispatchMode) +def export_tracepoint_dispatch_mode( + mode: ProxyTorchDispatchMode, *args: Any, **kwargs: Any +) -> Any: + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + p_args, p_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, (args, kwargs)) + proxy = mode.tracer.create_proxy( + "call_function", _export_tracepoint, p_args, p_kwargs + ) + return track_tensor_tree(args, proxy, constant=None, tracer=mode.tracer) + + +@register_fake(_export_tracepoint, skip_cache=True) +def export_tracepoint_fake_tensor_mode(*args: Any, **kwargs: Any) -> tuple[Any, ...]: + return args + + +@_export_tracepoint.py_functionalize_impl +def export_tracepoint_functional( + ctx: "BaseFunctionalizeAPI", *args: Any, **kwargs: Any +) -> tuple[Any, ...]: + unwrapped_args = ctx.unwrap_tensors(args) + # pyrefly: ignore[bad-argument-type] # TODO unwrap_tensors accepts pytrees at runtime + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + + with ctx.redispatch_to_next(): + _export_tracepoint(*unwrapped_args, **unwrapped_kwargs) + return args + + +_export_tracepoint.py_impl(DispatchKey.Autograd)( + autograd_not_implemented(_export_tracepoint, deferred_error=True) +) + + +@_export_tracepoint.py_impl(DispatchKey.CPU) +def export_tracepoint_cpu(*args: Any, **kwargs: Any) -> tuple[Any, ...]: + return args + + +def _wrap_submodule( + mod: torch.nn.Module, + path: str, + module_call_specs: dict[str, dict[str, pytree.TreeSpec]], +) -> tuple["RemovableHandle", "RemovableHandle"]: + if not isinstance(mod, torch.nn.Module): + raise AssertionError(f"expected torch.nn.Module, got {type(mod)}") + if path == "": + raise AssertionError("path must not be empty") + submodule = torch.fx.graph_module._get_attr(mod, path) + + def update_module_call_signatures( + path: str, in_spec: pytree.TreeSpec, out_spec: pytree.TreeSpec + ) -> None: + if path in module_call_specs: + if module_call_specs[path]["in_spec"] != in_spec: + raise AssertionError( + f"in_spec mismatch for {path}: {module_call_specs[path]['in_spec']} != {in_spec}" + ) + if module_call_specs[path]["out_spec"] != out_spec: + raise AssertionError( + f"out_spec mismatch for {path}: {module_call_specs[path]['out_spec']} != {out_spec}" + ) + module_call_specs[path] = {"in_spec": in_spec, "out_spec": out_spec} + + def check_flattened(flat_args: list[Any]) -> None: + for a in flat_args: + if not (isinstance(a, (torch.Tensor, str, int, float, bool)) or a is None): + raise AssertionError( + f"Only Tensors or scalars are supported as pytree flattened inputs, got: {a}" + ) + + def pre_hook( + module: torch.nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> tuple[tuple[Any, ...], dict[str, Any]]: + flat_args, in_spec = pytree.tree_flatten((args, kwargs)) + check_flattened(flat_args) + flat_args = _export_tracepoint(*flat_args, kind="module_call_inputs", path=path) + args, kwargs = pytree.tree_unflatten(flat_args, in_spec) + return args, kwargs + + def post_hook( + module: torch.nn.Module, + args: tuple[Any, ...], + kwargs: dict[str, Any], + res: Any, + ) -> Any: + _, in_spec = pytree.tree_flatten((args, kwargs)) + flat_res, out_spec = pytree.tree_flatten(res) + check_flattened(flat_res) + flat_res = _export_tracepoint(*flat_res, kind="module_call_outputs", path=path) + update_module_call_signatures(path, in_spec, out_spec) + return pytree.tree_unflatten(flat_res, out_spec) + + pre_handle = submodule.register_forward_pre_hook(pre_hook, with_kwargs=True) + post_handle = submodule.register_forward_hook(post_hook, with_kwargs=True) + return pre_handle, post_handle + + +@contextmanager +def _wrap_submodules( + f: torch.nn.Module | Callable[..., object], + preserve_signature: Iterable[str], + module_call_signatures: dict[str, dict[str, pytree.TreeSpec]], +) -> Generator[None, None, None]: + handles: list[RemovableHandle] = [] + + try: + for path in preserve_signature: + # pyrefly: ignore[bad-argument-type] # TODO f is an nn.Module at runtime (asserted in _wrap_submodule) + handles.extend(_wrap_submodule(f, path, module_call_signatures)) + yield + finally: + for handle in handles: + handle.remove() + + +def _mark_strict_experimental(cls: type[_R]) -> type[_R]: + def call(self: Any, *args: Any) -> Any: + return strict_mode(self, args) + + cls.__call__ = call # type: ignore[attr-defined] + return cls + + +def _register_func_spec_proxy_in_tracer( + tracer: "_ProxyTracer", name: str, spec: pytree.TreeSpec +) -> "Proxy": + """ + This is a wrapper utility method on top of tracer to cache the + already registered subclass spec attribute. This is useful because + Subclass.__init__ will be same for each subclass. By default, fx will + create multiple attributes/proxies for given attribute. + """ + fx_name = name + "0" + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + if hasattr(tracer.root, fx_name): + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + if getattr(tracer.root, fx_name) != spec: + raise AssertionError(f"spec mismatch for {fx_name}") + return tracer.create_proxy("get_attr", fx_name, (), {}) + + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + qualname = tracer.get_fresh_qualname(name) + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + setattr(tracer.root, qualname, spec) + return tracer.create_proxy("get_attr", qualname, (), {}) + + +def _emit_flat_apply_call( + *, + tracer: "_ProxyTracer", + spec_name: str, + const_target_for_apply: Callable[..., object], + graphable_args: pytree.PyTree, + track_value: object, + call_spec_cache_key: str, +) -> None: + # Flatten to graphable form and record the spec on the FX root + flat_args, in_spec = to_graphable(graphable_args) + qualname = tracer.get_fresh_qualname(spec_name) # type: ignore[union-attr] + setattr(tracer.root, qualname, in_spec) # type: ignore[union-attr] + spec_proxy = tracer.create_proxy("get_attr", qualname, (), {}) + + # Reuse/cached ConstantFunction spec on the root + _, func_spec = pytree.tree_flatten(_ConstantFunction(const_target_for_apply)) + func_spec_proxy = _register_func_spec_proxy_in_tracer( + tracer, f"{call_spec_cache_key}_const_func_spec", func_spec + ) + + # Map runtime args -> proxies (always via tracer.unwrap_proxy now) + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + flat_proxy_args = pytree.tree_map(tracer.unwrap_proxy, flat_args) + + # Emit flat_apply and track result structure + out_proxy = tracer.create_proxy( + "call_function", flat_apply, (func_spec_proxy, spec_proxy, *flat_proxy_args), {} + ) + track_tensor_tree(track_value, out_proxy, constant=None, tracer=tracer) + + +def _is_init(fn: object) -> bool: + return callable(fn) and fn.__name__ == "__init__" + + +def mark_subclass_constructor_exportable_experimental( + constructor_subclass: Callable[_P, None], +) -> Callable[_P, None]: + """ + Experimental decorator that makes subclass to be traceable in export + with pre-dispatch IR. To make your subclass traceable in export, you need to: + 1. Implement __init__ method for your subclass (Look at DTensor implementation) + 2. Decorate your __init__ method with _mark_constructor_exportable_experimental + 3. Put torch._dynamo_disable decorator to prevent dynamo from peeking into its' impl + + Example: + + class FooTensor(torch.Tensor): + @staticmethod + def __new__(cls, elem, *, requires_grad=False): + # ... + return torch.Tensor._make_subclass(cls, elem, requires_grad=requires_grad) + + @torch._dynamo_disable + @mark_subclass_constructor_exportable_experimental + def __init__(self, elem, ...): + # ... + """ + if not _is_init(constructor_subclass): + raise RuntimeError( + f"torch._export.wrappers.mark_constructor_exportable_experimental can only be applied on subclass tensor.__init__" + f"But, you are adding it on {constructor_subclass.__name__} which is not supported. " + f"If __init__ doesn't exist on your subclass, please add it. Look at DTensor.__init__ implementation for example" + ) + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> None: + constructor_subclass(*args, **kwargs) + + if not torch.compiler.is_exporting(): + return + + if not is_traceable_wrapper_subclass_type(type(args[0])): + if not constructor_subclass.__qualname__.endswith("__init__"): + raise AssertionError( + f"expected __qualname__ to end with '__init__', got {constructor_subclass.__qualname__}" + ) + obj_name = constructor_subclass.__qualname__[: -len("__init__")] + raise RuntimeError( + f"Can't intercept {obj_name} in export because this object is not a traceable " + f"tensor subclass. Please look at DTensor.__init__ implementation as an example of proper usage of this API." + ) + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + if mode is None: + return + + if not isinstance(mode, PreDispatchTorchFunctionMode): + raise AssertionError( + f"expected PreDispatchTorchFunctionMode, got {type(mode)}" + ) + + tracer = mode.tracer + subclass = args[0] + graphable = (tuple(args[1:]), kwargs) + + spec_name = "_".join(constructor_subclass.__qualname__.lower().split(".")) + call_spec_cache_key = type(subclass).__name__.lower() + + _emit_flat_apply_call( + tracer=tracer, + spec_name=spec_name, + const_target_for_apply=type(subclass), + graphable_args=graphable, + track_value=subclass, # track the constructed subclass instance + call_spec_cache_key=call_spec_cache_key, + ) + return + + return wrapper + + +def allow_in_pre_dispatch_graph(func: Callable[_P, _R]) -> Callable[_P, _R]: + """ + Experimental decorator that adds user function to export pre-dispatch graph. Note that + we only support custom autograd function/subclass constructors today. To use this function: + 1. For subclasses: + 1. refer to instructions in mark_subclass_constructor_exportable_experimental + 2. Define apply method on your custom autograd function and apply this decorator. + + Example: + + class MyCoolCustomAutogradFunc(autograd.Function): + @classmethod + @torch._export.wrappers.allow_in_pre_dispatch_graph + def apply(cls, *args, **kwargs): + return super(MyCoolCustomAutogradFunc, cls).apply(*args, **kwargs) + + """ + if _is_init(func): + # pyrefly: ignore[bad-return, bad-argument-type] # TODO _is_init(func) implies func returns None + return mark_subclass_constructor_exportable_experimental(func) + + if not (_is_init(func) or func.__name__ == "apply"): + raise RuntimeError( + f"torch._export.wrappers.allow_in_pre_dispatch_graph can only be applied on subclass tensor.__init_ " + f"or custom_autograd_function.apply. " + f"But, you are adding it on {func.__name__} which is not supported. " + f"If __init__ doesn't exist on your subclass, please add it. Look at DTensor.__init__ implementation for example. " + f"If you are adding it on custom autograd function, please add it on apply method. " + f"If anything else, file an issue on github and we may consider extending our support. " + ) + + @wraps(func) + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + if not torch.compiler.is_exporting(): + return func(*args, **kwargs) + + if not inspect.isclass(args[0]): + return func(*args, **kwargs) + + if not issubclass(args[0], torch.autograd.Function): + return func(*args, **kwargs) + + from torch._ops import _get_dispatch_mode_pre_dispatch + + mode = _get_dispatch_mode_pre_dispatch(torch._C._TorchDispatchModeKey.PROXY) + if mode is None: + return func(*args, **kwargs) + + # Sometimes custom autograd functions can call into HOPs that don't have proxy impl + # at PreDispatch level, so we just dispatch it below to get the concrete result. + include_to_set = torch._C._dispatch_tls_local_include_set().remove( + torch._C.DispatchKey.PreDispatch + ) + exclude_to_set = ( + torch._C._dispatch_tls_local_exclude_set() + | torch._C.DispatchKeySet(torch._C.DispatchKey.PreDispatch) + ) + + with torch._C._ForceDispatchKeyGuard(include_to_set, exclude_to_set): + out = func(*args, **kwargs) + + if not mode.pre_dispatch: + raise AssertionError("Should only do this in predispatch") + tracer = mode.tracer + + function_cls_name = f"{args[0].__module__}.{args[0].__qualname__}" + graphable = ((function_cls_name, *args[1:]), kwargs) + + from torch.export.custom_ops import ( + _call_custom_autograd_function_in_pre_dispatch, + ) + + spec_name = "_".join(function_cls_name.split(".")) + call_spec_cache_key = type( + _call_custom_autograd_function_in_pre_dispatch + ).__name__.lower() + _emit_flat_apply_call( + tracer=tracer, + spec_name=spec_name, + const_target_for_apply=_call_custom_autograd_function_in_pre_dispatch, + graphable_args=graphable, + track_value=out, + call_spec_cache_key=call_spec_cache_key, + ) + return out + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__init__.py b/.venv/lib/python3.12/site-packages/torch/_functorch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02a4cad3ca14e06883a283ee4bada5379fed9073 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/aot_autograd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/aot_autograd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ff5379b74d85cd6af551b335dee33b471aad55 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/aot_autograd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/apis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/apis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d090e2802d2b80706c42bdd3b0951058c479dde3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/apis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/autograd_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/autograd_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ff8d16447c3cbccbd20d869d29018bdee800541 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/autograd_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/batch_norm_replacement.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/batch_norm_replacement.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2f632e5d77aa860b8a64b82cf3ee427e2f09581 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/batch_norm_replacement.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/benchmark_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/benchmark_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5b1fa896050fff57d3c61dcb1b653264dd5a390 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/benchmark_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compile_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compile_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bed43310a3113bfb306319f818318a0a48f0a23a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compile_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compilers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compilers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f313ae9305540a76b83d30c3f226810e00aa217 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compilers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a9c5d656ba16d50cf7efd4b9c5dd9ec14ed1d39 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/deprecated.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/deprecated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e769ad6ae0d76e100c4c34bcf94f73d781a28060 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/deprecated.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/eager_transforms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/eager_transforms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..570dde28e4eca2eff6b4b871f9e620b7e2eac7ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/eager_transforms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/einops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/einops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fca6ffe067c69ddb260b90f490ac5a04cce6641 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/einops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/functional_call.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/functional_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52d54b8b508b29c82eff261cd1d03cf7b7879aea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/functional_call.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/fx_minifier.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/fx_minifier.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b304be2f77fc9e2ffa114292db6f1e2e4ebbe40 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/fx_minifier.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/make_functional.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/make_functional.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..828b21cfca98757e1ff49596f5b4968059995c0a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/make_functional.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bebcc2277722f026b65690bd046e90d3be0a53ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:166a63fbe903d78c104caa25e82acf6539fe2e558519895016e7a48f75ec0c78 +size 191712 diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/predispatch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/predispatch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e7406737ef91366d1b6d2bf375a4b87831eb2c3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/predispatch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pyfunctorch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pyfunctorch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffcfcd15bec9f5590ef2c516ac5d665e1e5da13a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pyfunctorch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/python_key.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/python_key.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b0ae16ca2a417ec09a1ae0d30db47408cb5bed3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/python_key.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pytree_hacks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pytree_hacks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8303fcf25ef78cccbfc039018aac48ba1445d3c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pytree_hacks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/top_operators_github_usage.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/top_operators_github_usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd3dec5343c6c3797e8c7159a7a4f0bda4aca5e0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/top_operators_github_usage.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19f163bc0e9d3d08a9e8cc5b97389091e8439a82 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/vmap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/vmap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8eb79f6eaadd1a424e2d54e20a37791a86c0200 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/vmap.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__init__.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb3afecc4499723a1adc32bb7f72450f9005d253 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/ac_logging_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/ac_logging_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f35db80b7745e4b4450eafc0754306c4ccf5a80 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/ac_logging_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/graph_info_provider.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/graph_info_provider.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..293617cc3062705eccf275d5b7a39bc04c3e3738 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/graph_info_provider.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de994026758f73022598104e4edab130092c1c16 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack_evaluator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack_evaluator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bd4de8594e1054959ff888747f8663fb843436e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack_evaluator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/remat_using_tags_for_fwd_loss_bwd_graph_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/remat_using_tags_for_fwd_loss_bwd_graph_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c876336779006ec47f68bf692cf1b615a4beec2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/remat_using_tags_for_fwd_loss_bwd_graph_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/ac_logging_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/ac_logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f456804d8bf66ceec62081439fd1da47c21df3e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/ac_logging_utils.py @@ -0,0 +1,228 @@ +import json +import logging +from typing import Any + +from torch._logging import trace_structured +from torch.fx import Graph, Node + + +log: logging.Logger = logging.getLogger(__name__) + + +def create_joint_graph_node_information( + joint_graph: Graph, + recomputable_node_info: dict[str, int], +) -> dict[str, Any]: + joint_graph_node_information: dict[str, Any] = {} + + for i, joint_graph_node in enumerate(joint_graph.nodes): + is_recomputable_candidate: bool = ( + joint_graph_node.name in recomputable_node_info + ) + tensor_meta = joint_graph_node.meta.get("tensor_meta") + # pyrefly: ignore [implicit-any] + shape = getattr(tensor_meta, "shape", []) if tensor_meta else [] + + node_info: dict[str, Any] = { + "index": i, + "name": joint_graph_node.name, + "is_recomputable_candidate": is_recomputable_candidate, + "target": str(joint_graph_node.target), + "shape": str(shape), + "input_arguments": [inp.name for inp in joint_graph_node.all_input_nodes], + "stack_trace": joint_graph_node.meta.get("stack_trace", ""), + } + + if is_recomputable_candidate: + idx: int = recomputable_node_info[joint_graph_node.name] + node_info["recomputable_candidate_info"] = { + "recomputable_node_idx": idx, + } + + joint_graph_node_information[joint_graph_node.name] = node_info + + return joint_graph_node_information + + +def create_joint_graph_edges(joint_graph: Graph) -> list[tuple[str, str]]: + joint_graph_edges: list[tuple[str, str]] = [ + (inp.name, node.name) + for node in joint_graph.nodes + for inp in node.all_input_nodes + ] + return joint_graph_edges + + +def create_activation_checkpointing_logging_structure_payload( + joint_graph: Graph, + joint_graph_node_information: dict[str, Any], + joint_graph_edges: list[tuple[str, str]], + all_recomputable_banned_nodes: list[Node], + expected_runtime: float, + saved_node_idxs: list[int], + recomputable_node_idxs: list[int], + memories_banned_nodes: list[int], + normalized_memories_banned_nodes: list[float], + runtimes_banned_nodes: list[float], + min_cut_saved_values: list[Node], + memory_budget: float, + min_act_size: float, + max_act_size: float, + saved_values_act_size: float, + more_aggressive_saved_values_mem_ratio: float, + aggressive_recomputation_saved_values_mem_ratio: float, +) -> dict[str, Any]: + """ + Creates a structured payload for logging activation checkpointing information. + + Args: + joint_graph: The computational graph representing operations. + joint_graph_node_information: Dictionary containing information about nodes in the joint graph. + joint_graph_edges: List of edges in the joint graph represented as tuples of node names. + all_recomputable_banned_nodes: List of nodes that are banned from recomputation. + expected_runtime: Expected runtime of the computation. + saved_node_idxs: Indices of nodes that are saved (not recomputed). + recomputable_node_idxs: Indices of nodes that can be recomputed. + memories_banned_nodes: Memory usage values (in absolute units) for banned nodes. + normalized_memories_banned_nodes: Normalized memory usage values for banned nodes, + used as input to the knapsack algorithm. + runtimes_banned_nodes: Runtime values for banned nodes, used as input to the + knapsack algorithm. + min_cut_saved_values: List of nodes saved by the min-cut algorithm. + memory_budget: The memory budget ratio (0 to 1) used for activation checkpointing. + min_act_size: Minimum activation size in GB (size when saving only inputs). + max_act_size: Maximum activation size in GB (size when saving all runtime-optimized values). + saved_values_act_size: Estimated activation size in GB for the saved values. + more_aggressive_saved_values_mem_ratio: Memory ratio for more aggressive recomputation strategy. + aggressive_recomputation_saved_values_mem_ratio: Memory ratio for fully aggressive recomputation strategy. + + Returns: + A dictionary containing structured logging information for activation checkpointing. + """ + activation_checkpointing_logging_structure_payload: dict[str, Any] = { + "Joint Graph Size": len(joint_graph.nodes), + "Joint Graph Edges": { + "Total": len(joint_graph_edges), + "Edges": joint_graph_edges, + }, + "Joint Graph Node Information": joint_graph_node_information, + "Recomputable Banned Nodes Order": [ + node.name for node in all_recomputable_banned_nodes + ], + "Expected Runtime": expected_runtime, + "Knapsack Saved Nodes": saved_node_idxs, + "Knapsack Recomputed Nodes": recomputable_node_idxs, + "Absolute Memories": memories_banned_nodes, + "Knapsack Input Memories": normalized_memories_banned_nodes, + "Knapsack Input Runtimes": runtimes_banned_nodes, + "Min Cut Solution Saved Values": [node.name for node in min_cut_saved_values], + "Memory Budget": memory_budget, + "Min Activation Size (GB)": min_act_size, + "Max Activation Size (GB)": max_act_size, + "Saved Values Activation Size (GB)": saved_values_act_size, + "More Aggressive Saved Values Mem Ratio": more_aggressive_saved_values_mem_ratio, + "Aggressive Recomputation Saved Values Mem Ratio": aggressive_recomputation_saved_values_mem_ratio, + } + return activation_checkpointing_logging_structure_payload + + +def create_structured_trace_for_min_cut_info( + joint_graph: Graph, + all_recomputable_banned_nodes: list[Node], + saved_node_idxs: list[int], + recomputable_node_idxs: list[int], + expected_runtime: float, + memories_banned_nodes: list[int], + normalized_memories_banned_nodes: list[float], + runtimes_banned_nodes: list[float], + min_cut_saved_values: list[Node], + memory_budget: float, + min_act_size: float, + max_act_size: float, + saved_values_act_size: float, + more_aggressive_saved_values_mem_ratio: float, + aggressive_recomputation_saved_values_mem_ratio: float, +) -> None: + """ + Creates a structured trace for minimum cut information in the graph. + + Args: + joint_graph: The computational graph representation. + all_recomputable_banned_nodes: List of nodes that can be recomputed. + saved_node_idxs: Indices of nodes that are saved in memory. + recomputable_node_idxs: Indices of nodes that are recomputed. + expected_runtime: Expected runtime for the computation. + memories_banned_nodes: Memory requirements for each banned node in bytes. + normalized_memories_banned_nodes: Normalized memory requirements for each banned node + (typically scaled between 0 and 1 for relative comparison). + runtimes_banned_nodes: Runtime costs associated with each banned node. + min_cut_saved_values: Nodes that are saved as part of the minimum cut solution. + memory_budget: The memory budget ratio (0 to 1) used for activation checkpointing. + min_act_size: Minimum activation size in GB (size when saving only inputs). + max_act_size: Maximum activation size in GB (size when saving all runtime-optimized values). + saved_values_act_size: Estimated activation size in GB for the saved values. + more_aggressive_saved_values_mem_ratio: Memory ratio for more aggressive recomputation strategy. + aggressive_recomputation_saved_values_mem_ratio: Memory ratio for fully aggressive recomputation strategy. + """ + # Create a dictionary to store recomputable node information + recomputable_node_info: dict[str, int] = { + node.name: idx for idx, node in enumerate(all_recomputable_banned_nodes) + } + + # Create joint graph node information + joint_graph_node_information = create_joint_graph_node_information( + joint_graph, recomputable_node_info + ) + + # Update node information with recomputable candidate details + for node_name, node_info in joint_graph_node_information.items(): + if node_info["is_recomputable_candidate"]: + idx = recomputable_node_info[node_name] + node_info["recomputable_candidate_info"]["memory"] = memories_banned_nodes[ + idx + ] + node_info["recomputable_candidate_info"]["runtime"] = runtimes_banned_nodes[ + idx + ] + node_info["recomputable_candidate_info"]["is_saved"] = ( + idx in saved_node_idxs + ) + node_info["recomputable_candidate_info"]["is_recomputed"] = ( + idx in recomputable_node_idxs + ) + + # Create joint graph edges + joint_graph_edges = create_joint_graph_edges(joint_graph) + + # Create activation checkpointing logging structure payload + activation_checkpointing_logging_structure_payload = create_activation_checkpointing_logging_structure_payload( + joint_graph=joint_graph, + joint_graph_node_information=joint_graph_node_information, + joint_graph_edges=joint_graph_edges, + all_recomputable_banned_nodes=all_recomputable_banned_nodes, + expected_runtime=expected_runtime, + saved_node_idxs=saved_node_idxs, + recomputable_node_idxs=recomputable_node_idxs, + memories_banned_nodes=memories_banned_nodes, + normalized_memories_banned_nodes=normalized_memories_banned_nodes, + runtimes_banned_nodes=runtimes_banned_nodes, + min_cut_saved_values=min_cut_saved_values, + memory_budget=memory_budget, + min_act_size=min_act_size, + max_act_size=max_act_size, + saved_values_act_size=saved_values_act_size, + more_aggressive_saved_values_mem_ratio=more_aggressive_saved_values_mem_ratio, + aggressive_recomputation_saved_values_mem_ratio=aggressive_recomputation_saved_values_mem_ratio, + ) + + # Create structured trace + payload_str = json.dumps(activation_checkpointing_logging_structure_payload) + + # Store on graph for AOTAutograd cache replay + joint_graph._min_cut_info_str = payload_str # type: ignore[attr-defined] + + trace_structured( + "artifact", + metadata_fn=lambda: {"name": "min_cut_information", "encoding": "json"}, + payload_fn=lambda: payload_str, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/graph_info_provider.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/graph_info_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..0294e32f292e5f9fe00eb6a1227c7c948757171b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/graph_info_provider.py @@ -0,0 +1,319 @@ +from typing import Any + +import networkx as nx + +from torch.fx import Graph, Node + + +class GraphInfoProvider: + """ + This class provides information about the graph, such as the nodes, edges, and their runtime and memory requirements. + It also provides methods to create graphs from the information provided. + """ + + __RECOMPUTABLE_NODE_ONLY_GRAPH = "recomputable_node_only_graph" + __RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT = ( + "recomputable_node_only_graph_with_larger_graph_context" + ) + __FULL_NX_JOINT_GRAPH = "full_nx_joint_graph" + __SIMPLIFIED_FX_JOINT_GRAPH = "fx_joint_graph" + + def __init__( + self, + graph_nodes_in_order: list[str], + graph_edges: list[tuple[str, str]], + all_recomputable_banned_nodes: list[str], + all_node_runtimes: dict[str, float] | None = None, + all_node_memories: dict[str, float] | None = None, + recorded_knapsack_input_memories: list[float] | None = None, + recorded_knapsack_input_runtimes: list[float] | None = None, + joint_graph: Graph | None = None, + ) -> None: + self.graph_nodes_in_order = graph_nodes_in_order + self.graph_edges = graph_edges + self.all_node_runtimes: dict[str, float] = dict() + if all_node_runtimes is None: + if recorded_knapsack_input_runtimes is None: + raise ValueError( + "Either all_node_runtimes or recorded_knapsack_input_runtimes must be provided." + ) + self.all_node_runtimes = { + node: recorded_knapsack_input_runtimes[i] + for i, node in enumerate(all_recomputable_banned_nodes) + } + else: + self.all_node_runtimes.update(all_node_runtimes) + self.all_node_memories: dict[str, float] = dict() + if all_node_memories is None: + if recorded_knapsack_input_memories is None: + raise ValueError( + "Either all_node_memories or recorded_knapsack_input_memories must be provided." + ) + self.all_node_memories = { + node: recorded_knapsack_input_memories[i] + for i, node in enumerate(all_recomputable_banned_nodes) + } + else: + self.all_node_memories.update(all_node_memories) + self.all_recomputable_banned_nodes = all_recomputable_banned_nodes + self.all_recomputable_banned_nodes_set = set(all_recomputable_banned_nodes) + self.recorded_knapsack_input_memories = recorded_knapsack_input_memories + self.recorded_knapsack_input_runtimes = recorded_knapsack_input_runtimes + self._lazily_initialized_graphs: dict[str, Any] = { + self.__RECOMPUTABLE_NODE_ONLY_GRAPH: None, + self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT: None, + self.__FULL_NX_JOINT_GRAPH: None, + self.__SIMPLIFIED_FX_JOINT_GRAPH: None, + } + + @classmethod + def inialize_from_graph( + cls, + joint_graph: Graph, + all_recomputable_banned_nodes: list[Node], + recorded_knapsack_input_memories: list[float], + recorded_knapsack_input_runtimes: list[float], + ) -> "GraphInfoProvider": + """ + Enables initialization from a joint graph. + """ + graph_nodes_in_order = [node.name for node in joint_graph.nodes] + graph_edges = [ + (node.name, user.name) for node in joint_graph.nodes for user in node.users + ] + all_recomputable_banned_node_names = [ + node.name for node in all_recomputable_banned_nodes + ] + return cls( + graph_nodes_in_order=graph_nodes_in_order, + graph_edges=graph_edges, + all_recomputable_banned_nodes=all_recomputable_banned_node_names, + recorded_knapsack_input_memories=recorded_knapsack_input_memories, + recorded_knapsack_input_runtimes=recorded_knapsack_input_runtimes, + joint_graph=joint_graph, + ) + + @property + def recomputable_node_only_graph(self) -> nx.DiGraph: + if self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH] is None: + self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH] = ( + self._create_recomputable_node_only_graph() + ) + return self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH] + + @property + def recomputable_node_only_graph_with_larger_graph_context(self) -> nx.DiGraph: + if ( + self._lazily_initialized_graphs[ + self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT + ] + is None + ): + self._lazily_initialized_graphs[ + self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT + ] = self._create_recomputable_node_only_graph_with_larger_graph_context() + return self._lazily_initialized_graphs[ + self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT + ] + + @property + def full_joint_nx_graph(self) -> nx.DiGraph: + if self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH] is None: + self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH] = ( + self._create_full_joint_graph() + ) + return self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH] + + @property + def simplified_fx_joint_graph(self) -> Graph: + if self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH] is None: + self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH] = ( + self._recreate_psuedo_joint_graph() + ) + return self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH] + + def get_non_ac_peak_memory(self) -> float: + return sum( + self.all_node_memories[node_name] + for node_name in self.all_recomputable_banned_nodes_set + ) + + def get_theoretical_max_runtime(self) -> float: + return sum( + self.all_node_runtimes[node_name] + for node_name in self.all_recomputable_banned_nodes_set + ) + + def get_knapsack_memory_input(self) -> list[float]: + return ( + self.recorded_knapsack_input_memories + if self.recorded_knapsack_input_memories + else [ + self.all_node_memories[node_name] + for node_name in self.all_recomputable_banned_nodes + ] + ) + + def get_knapsack_runtime_input(self) -> list[float]: + return ( + self.recorded_knapsack_input_runtimes + if self.recorded_knapsack_input_runtimes + else [ + self.all_node_runtimes[node_name] + for node_name in self.all_recomputable_banned_nodes + ] + ) + + def _create_recomputable_node_only_graph(self) -> nx.DiGraph: + graph = nx.DiGraph() + for recomputable_node in self.all_recomputable_banned_nodes: + graph.add_node(recomputable_node) + + for a, b in self.graph_edges: + if ( + a in self.all_recomputable_banned_nodes_set + and b in self.all_recomputable_banned_nodes_set + ): + graph.add_edge(a, b) + return graph + + def _create_recomputable_node_only_graph_with_larger_graph_context( + self, + ) -> nx.DiGraph: + # Create a dictionary to store the reachable nodes for each node + all_recomputable_banned_nodes_set = set(self.all_recomputable_banned_nodes) + + reachable_nodes = {} + for node in all_recomputable_banned_nodes_set: + # Use BFS to find all reachable nodes + predecessors = dict(nx.bfs_predecessors(self.full_joint_nx_graph, node)) + reachable_recomputable_nodes = set(predecessors.keys()).intersection( + all_recomputable_banned_nodes_set + ) + reachable_nodes[node] = reachable_recomputable_nodes + # Create the candidate graph + candidate_graph = nx.DiGraph() + candidate_graph.add_nodes_from(all_recomputable_banned_nodes_set) + for node1 in all_recomputable_banned_nodes_set: + for node2 in reachable_nodes[node1]: + # Check if there is an overlapping path + overlapping_path = False + for intermediate_node in reachable_nodes[node1]: + if ( + intermediate_node != node2 + and node2 in reachable_nodes[intermediate_node] + ): + overlapping_path = True + break + if not overlapping_path: + candidate_graph.add_edge(node1, node2) + return candidate_graph + + def _create_full_joint_graph(self) -> nx.DiGraph: + graph = nx.DiGraph() + for node in self.graph_nodes_in_order: + if node == "output": + continue + graph.add_node(node) + + for a, b in self.graph_edges: + if a == "output" or b == "output": + continue + graph.add_edge(a, b) + return graph + + def _recreate_psuedo_joint_graph(self) -> Graph: + # Create a dictionary to store the dependencies of each node + node_dependencies: dict[str, list[str]] = { + node: [] for node in self.graph_nodes_in_order + } + for a, b in self.graph_edges: + if a not in node_dependencies or b not in node_dependencies: + raise ValueError(f"Edge ({a}, {b}) references a non-existent node.") + node_dependencies[b].append(a) + + joint_graph = Graph() + # Create nodes in the graph + nodes: dict[str, Node] = {} + for node_name in self.graph_nodes_in_order: + input_nodes = [nodes[dep] for dep in node_dependencies[node_name]] + if input_nodes: + node = joint_graph.call_function(lambda *x: x, tuple(input_nodes)) + node.name = node_name + else: + node = joint_graph.placeholder(node_name) + nodes[node_name] = node + return joint_graph + + def _visualize_recomputable_candidate_graph_with_larger_context( + self, + layout_k: float = 0.5, + layout_iterations: int = 30, + ) -> None: + """ + Visualize the recomputable candidate graph with larger context. + """ + from matplotlib import cm, colors as mcolors, pyplot as plt + + pos = nx.spring_layout( + self.recomputable_node_only_graph_with_larger_graph_context, + k=layout_k, + iterations=layout_iterations, + ) + # pos = nx.spectral_layout(graph_with_indirect_edges) + plt.figure(figsize=(20, 15)) + + # Create a dictionary for node labels using the index + labels = { + node: self.recomputable_node_only_graph_with_larger_graph_context.nodes[ + node + ].get("index", node) + for node in self.recomputable_node_only_graph_with_larger_graph_context.nodes + } + + # Extract memory values and normalize them + norm = mcolors.Normalize( + vmin=min(self.get_knapsack_memory_input()), + vmax=max(self.get_knapsack_memory_input()), + ) + cmap = cm.viridis # type: ignore[attr-defined] + + # Assign colors based on memory + node_colors = [ + cmap( + norm( + float( + self.recomputable_node_only_graph_with_larger_graph_context.nodes[ + node + ]["memory"] + ) + ) + ) + for node in self.recomputable_node_only_graph_with_larger_graph_context.nodes + ] + + # Draw the graph with parsed nodes only + nx.draw_networkx_nodes( + self.recomputable_node_only_graph_with_larger_graph_context, + pos, + node_color=node_colors, + node_size=300, + label="Parsed Nodes", + ) + nx.draw_networkx_edges( + self.recomputable_node_only_graph_with_larger_graph_context, + pos, + arrows=True, + arrowsize=10, + ) + nx.draw_networkx_labels( + self.recomputable_node_only_graph_with_larger_graph_context, + pos, + labels=labels, + font_size=8, + font_weight="bold", + ) + + plt.title("Memory Colour Coded Dependency Graph for Recomputable Nodes") + plt.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), label="Memory") + plt.show() diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f0a124c64c1ec7ec6651aa79ff62ebec557949 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack.py @@ -0,0 +1,267 @@ +import torch + + +def greedy_knapsack( + memory: list[float], runtimes: list[float], max_memory: float +) -> tuple[float, list[int], list[int]]: + n = len(runtimes) + items = list(range(n)) + + # Sort items based on the ratio of runtime to memory in descending order + items = sorted(items, key=lambda i: runtimes[i] / memory[i], reverse=True) + + total_memory = 0.0 + total_runtime = 0.0 + items_to_save = [] + items_to_allow_recomputing = [] + + for i in items: + if total_memory + memory[i] <= max_memory: + total_memory += memory[i] + total_runtime += runtimes[i] + items_to_save.append(i) + else: + items_to_allow_recomputing.append(i) + return total_runtime, items_to_save, items_to_allow_recomputing + + +def ilp_knapsack( + memory: list[float], runtimes: list[float], max_memory: float +) -> tuple[float, list[int], list[int]]: + import numpy as np + + try: + from scipy.optimize import Bounds, LinearConstraint, milp + except ImportError: + raise RuntimeError( + "To use the ILP for memory budget checkpointing you need to install scipy" + ) from None + + np_memory = np.array(memory) + np_runtimes = np.array(runtimes) + c = -np_runtimes # type: ignore[operator] + + memory_constraint = LinearConstraint(A=np_memory, ub=np.array(max_memory)) + constraints = [memory_constraint] + + integrality = np.ones_like(c) + res = milp( + c=c, constraints=constraints, integrality=integrality, bounds=Bounds(0, 1) + ) + if not res.success: + raise RuntimeError("Somehow scipy solving failed") + + items_to_save = [] + items_to_allow_recomputing = [] + for idx, i in enumerate(res.x): + if i == 1: + items_to_save.append(idx) + else: + items_to_allow_recomputing.append(idx) + return -res.fun, items_to_save, items_to_allow_recomputing + + +def dp_knapsack( + memory: list[float], runtime: list[float], max_memory: float +) -> tuple[float, list[int], list[int]]: + # Scaling factor to convert floating point weights to integers + S = 10000 + + # Quantize the memory weights + quantized_memory = torch.tensor( + [round(m * S) for m in memory], dtype=torch.long, device="cpu" + ) + runtimes = torch.tensor(runtime, dtype=torch.float32, device="cpu") + + # Quantized pseudopolynomial DP for 0-1 Knapsack + quantized_max_memory = round(max_memory * S) + + n = len(memory) + + # Initialize the DP table + # TODO(chilli): I think if needed, this memory can be optimized with sliding + # window trick + Hirschberg trick: + # https://codeforces.com/blog/entry/47247?#comment-316200 + dp = torch.zeros( + (n + 1, quantized_max_memory + 1), dtype=torch.float32, device="cpu" + ) + + for i in range(1, n + 1): + current_memory = quantized_memory[i - 1] + current_runtime = runtimes[i - 1] + + # Copy the previous row + dp[i, :] = dp[i - 1, :] + + # Update dp[i, j] for all j >= current_memory + if current_memory == 0: + dp[i, :] = dp[i - 1, :] + current_runtime + else: + dp[i, current_memory:] = torch.maximum( + dp[i - 1, current_memory:], + dp[i - 1, :-current_memory] + current_runtime, + ) + + # Backtrack to find the items included in the knapsack + saved_items = [] + recomputable_items = [] + j: int = quantized_max_memory + for i in range(n, 0, -1): + if dp[i][j] != dp[i - 1][j]: + saved_items.append(i - 1) # Include this item (indexing from 0) + j -= int(quantized_memory[i - 1].item()) + else: + recomputable_items.append(i - 1) + + saved_items.reverse() # To get items in the order they were added + + # The maximum runtime that can be achieved within the max_memory constraint + max_runtime = dp[n][quantized_max_memory].item() + + return max_runtime, saved_items, recomputable_items + + +def dp_knapsack_sliding_hirschberg( + memory: list[float], runtime: list[float], max_memory: float +) -> tuple[float, list[int], list[int]]: + # Scaling factor to convert floating point weights to integers + S = 10000 + + # q_ prefix stands for quantized + q_memory = [int(round(m * S)) for m in memory] + runtimes = [float(v) for v in runtime] + + q_max_memory = int(round(max_memory * S)) + + q_memory_length = len(q_memory) + if q_memory_length == 0: + return 0.0, [], [] + + item_indices = list(range(q_memory_length)) + dp_profile_size = q_max_memory + 1 + + # Current DP profile (row) + dp_profile = torch.zeros(dp_profile_size, dtype=torch.float32, device="cpu") + # Store a candidate for next dp_profile - current dp row + item + candidate_profile = torch.empty(dp_profile_size, dtype=torch.float32, device="cpu") + left_profile = torch.empty(dp_profile_size, dtype=torch.float32, device="cpu") + right_profile = torch.empty(dp_profile_size, dtype=torch.float32, device="cpu") + + saved_items: list[int] = [] + recomputable_items: list[int] = [] + + # Explicit stack to optimize memory and avoid recursion + # Stack stores segments as (start index, end index, capacity for segment) + stack: list[tuple[int, int, int]] = [(0, q_memory_length, q_max_memory)] + + # LIFO + while stack: + start, end, capacity = stack.pop() + length = end - start + if length == 0: + continue + + # Leaf + if length == 1: + index = item_indices[start] + memory_item = q_memory[index] + runtime_item = runtimes[index] + if memory_item <= capacity and runtime_item > 0.0: + saved_items.append(index) + else: + recomputable_items.append(index) + continue + + # Split the segment into two halves + middle = start + (length // 2) + left_start, left_end = middle, end + right_start, right_end = start, middle + + # Assign items to both halves + left_items = item_indices[left_start:left_end] + right_items = item_indices[right_start:right_end] + + # Working only on items allowed by segment's capacity + capacity = capacity + 1 + dp_view = dp_profile[:capacity] + candidate_view = candidate_profile[:capacity] + left_dp_local = left_profile[:capacity] + right_dp_local = right_profile[:capacity] + + # Left part + dp_view.zero_() + for index in left_items: + memory_item = q_memory[index] + runtime_item = runtimes[index] + + if memory_item == 0: + # Weight is 0, so add it to all capacities; a "free lunch", essentially + dp_view.add_(runtime_item) + continue + + # If item is too heavy, we skip it + if memory_item >= capacity: + continue + + # Add the current item so we can then pick the highest value + dp_view_candidate = candidate_view[: capacity - memory_item] + torch.add(dp_view[:-memory_item], runtime_item, out=dp_view_candidate) + # Take the highest - either previous (without current) or with current + torch.maximum( + dp_view[memory_item:], dp_view_candidate, out=dp_view[memory_item:] + ) + + # Store the left profile + left_dp_local.copy_(dp_view) + + # Right part + dp_view.zero_() + for index in right_items: + memory_item = q_memory[index] + runtime_item = runtimes[index] + + if memory_item == 0: + dp_view.add_(runtime_item) + continue + + if memory_item >= capacity: + continue + + dp_view_candidate = candidate_view[: capacity - memory_item] + torch.add(dp_view[:-memory_item], runtime_item, out=dp_view_candidate) + torch.maximum( + dp_view[memory_item:], dp_view_candidate, out=dp_view[memory_item:] + ) + + # Store the reversed right profile + right_dp_local.copy_(dp_view.flip(-1)) + + # In-place compute item-wise sum of left and right to pick the split point where the sum is highest + left_dp_local.add_(right_dp_local) + + # Pick the index of highest value of a pair, which we then use as a split point + best_split = int(torch.argmax(left_dp_local).item()) + + left_capacity = best_split + right_capacity = capacity - best_split + + # Clamp (might be removed if we're 100% sure that there is no edge case that will mess up the indices math) + if left_capacity < 0: + left_capacity = 0 + if right_capacity < 0: + right_capacity = 0 + if left_capacity > q_max_memory: + left_capacity = q_max_memory + if right_capacity > q_max_memory: + right_capacity = q_max_memory + + # Push right then left, so left is processed next + stack.append((right_start, right_end, right_capacity)) + stack.append((left_start, left_end, left_capacity)) + + saved_items = sorted(saved_items) + recomputable_items = sorted(recomputable_items) + + max_runtime = sum(runtime[i] for i in saved_items) + recomputable_items.reverse() + return max_runtime, saved_items, recomputable_items diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack_evaluator.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..75e35571a1d5b14da2fab08e2c5d5fc92e8da112 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack_evaluator.py @@ -0,0 +1,282 @@ +import operator +from collections import deque +from collections.abc import Callable + +import networkx as nx + +from torch._functorch._activation_checkpointing.graph_info_provider import ( + GraphInfoProvider, +) + + +class KnapsackEvaluator: + """ + This class evaluates the theoretical runtime and peak memory usage of a given checkpointing strategy. + It takes in a graph and a list of nodes that are saved and recomputed, and then simulates the + backward pass to calculate the peak memory usage. + """ + + def __init__( + self, + graph_info_provider: GraphInfoProvider, + ) -> None: + self._graph_info_provider = graph_info_provider + + def _get_backward_memory_from_topologically_sorted_graph( + self, + node_graph: nx.DiGraph, + node_memories: dict[str, float], + saved_nodes_set: set[str], + peak_memory_after_forward_pass: float, + ) -> list[tuple[float, str]]: + """ + Simulates the backward pass and keeps track of the peak memory usage. + + High Level Steps: + 1. Set Initial Peak/Current Memory + Allows you to set the peak memory after the forward pass, but typically this is + the sum of the estimated memory of the saved nodes. + 2. Perform a reverse topological sort of the node_graph. + If full graph is defined then will sort the full graph and only process the subset + of nodes in the node_graph. + 3. Iterate through the sorted graph nodes. + If the node is saved then just drop its memory from current memory. + If the node is not saved then add its memory to current memory and then traverse its + predecessors to simulate recomputation chain. Will check if new peak memory after all + predecessors are processed. + + Args: + node_graph (nx.DiGraph): A directed graph representing the recomputable forward nodes. + saved_nodes_set (Set[str]): A set of node names that are saved. + peak_memory_after_forward_pass (float): The peak memory usage after the forward pass. + """ + current_memory = [ + (peak_memory_after_forward_pass, "Initial Peak/Current Memory") + ] + already_computed = set() + sorted_nodes = list(reversed(list(nx.topological_sort(node_graph)))) + dependencies_computed = set() + + for node in sorted_nodes: + if node in saved_nodes_set or node in already_computed: + current_memory.append( + ( + current_memory[-1][0] - node_memories[node], + f"Dropping Node(already saved): {node}", + ) + ) + continue + + already_computed.add(node) + current_memory.append( + ( + current_memory[-1][0] + node_memories[node], + f"Recomputing Node: {node}", + ) + ) + # Create a queue of dependencies required for recomputation + predecessor_queue = deque( + [ + dependency + # pyrefly: ignore [bad-unpacking] + for dependency, v in node_graph.in_edges(node) + if dependency not in already_computed + ] + ) + while predecessor_queue: + dep = predecessor_queue.popleft() + already_computed.add(dep) + dependencies_computed.add(dep) + current_memory.append( + ( + current_memory[-1][0] + node_memories[dep], + f"Recomputing Predecessor of {node}: {dep}", + ) + ) + # Add predecessors of the predecessor to the queue if they haven't been recomputed yet + # pyrefly: ignore [bad-unpacking] + for dependency_of_dependency, _ in node_graph.in_edges(dep): + if ( + dependency_of_dependency in already_computed + or dependency_of_dependency in saved_nodes_set + or dependency_of_dependency in predecessor_queue + ): + continue + predecessor_queue.append(dependency_of_dependency) + dependencies_computed.clear() + current_memory.append( + (current_memory[-1][0] - node_memories[node], f"Dropping Node: {node}") + ) + return current_memory + + def _validate_all_indexes_accounted_for_in_provided_output( + self, saved_nodes_idxs: list[int], recomputable_node_idxs: list[int] + ) -> None: + """ + Validate that all indexes are accounted for in the provided output. + This function checks that the union of saved nodes and recomputable nodes + covers all candidate nodes without any overlaps. + """ + recomputable_node_idxs_set = set(recomputable_node_idxs) + saved_nodes_idxs_set = set(saved_nodes_idxs) + all_candidate_nodes_idxs = set( + range(len(self._graph_info_provider.all_recomputable_banned_nodes)) + ) + # Check that there are no overlaps between saved nodes and recomputable nodes + if len(recomputable_node_idxs_set.intersection(saved_nodes_idxs_set)) != 0: + raise AssertionError( + f"Saved nodes and recomputable nodes cannot have any overlaps, " + f"but found overlap: {recomputable_node_idxs_set.intersection(saved_nodes_idxs_set)}" + ) + # Check that all candidate nodes are accounted for + if ( + recomputable_node_idxs_set.union(saved_nodes_idxs_set) + != all_candidate_nodes_idxs + ): + raise AssertionError( + f"All candidate nodes must be accounted for in the provided output, " + f"got union={recomputable_node_idxs_set.union(saved_nodes_idxs_set)}, " + f"expected={all_candidate_nodes_idxs}" + ) + + def evaluate_knapsack_output( + self, + saved_nodes_idxs: list[int], + recomputable_node_idxs: list[int], + account_for_backward_pass: bool = False, + ) -> dict[str, float]: + """ + Evaluate the theoretical runtime and peak memory usage of a given checkpointing strategy. + Args: + - saved_nodes_idxs (List[int]): The indices of nodes that are saved. + - recomputable_node_idxs (List[int]): The indices of nodes that need to be recomputed. + """ + self._validate_all_indexes_accounted_for_in_provided_output( + saved_nodes_idxs, recomputable_node_idxs + ) + recomputation_runtime = sum( + self._graph_info_provider.all_node_runtimes[ + self._graph_info_provider.all_recomputable_banned_nodes[node] + ] + for node in recomputable_node_idxs + ) + if account_for_backward_pass: + memory_list = self._get_backward_memory_from_topologically_sorted_graph( + node_graph=self._graph_info_provider.recomputable_node_only_graph_with_larger_graph_context, + saved_nodes_set={ + self._graph_info_provider.all_recomputable_banned_nodes[i] + for i in saved_nodes_idxs + }, + node_memories=self._graph_info_provider.all_node_memories, + peak_memory_after_forward_pass=sum( + self._graph_info_provider.all_node_memories[ + self._graph_info_provider.all_recomputable_banned_nodes[i] + ] + for i in saved_nodes_idxs + ), + ) + peak_memory = max(memory_list, key=operator.itemgetter(0))[0] + else: + peak_memory = sum( + self._graph_info_provider.all_node_memories[ + self._graph_info_provider.all_recomputable_banned_nodes[node] + ] + for node in saved_nodes_idxs + ) + return { + "peak_memory": peak_memory, + "recomputation_runtime": recomputation_runtime, + "non_ac_peak_memory": self._graph_info_provider.get_non_ac_peak_memory(), + "theoretical_max_runtime": self._graph_info_provider.get_theoretical_max_runtime(), + "percentage_of_theoretical_peak_memory": peak_memory + / self._graph_info_provider.get_non_ac_peak_memory(), + "percentage_of_theoretical_peak_runtime": recomputation_runtime + / self._graph_info_provider.get_theoretical_max_runtime(), + } + + def evaluate_distribution_of_results_for_knapsack_algo( + self, + knapsack_algo: Callable[ + [list[float], list[float], float], tuple[float, list[int], list[int]] + ], + memory_budget_values: list[float], + ) -> list[dict[str, float]]: + """ + Evaluates the distribution of results for a given knapsack algorithm. + Args: + knapsack_algo (Callable): The knapsack algorithm to use for evaluation. + memory_budget_values (List[float]): A list of memory budgets to evaluate. + """ + results = [] + for memory_budget in memory_budget_values: + _, saved_nodes, recomputed_nodes = knapsack_algo( + self._graph_info_provider.get_knapsack_memory_input(), + self._graph_info_provider.get_knapsack_runtime_input(), + memory_budget, + ) + result = self.evaluate_knapsack_output( + saved_nodes_idxs=saved_nodes, + recomputable_node_idxs=recomputed_nodes, + ) + result["memory_budget"] = memory_budget + results.append(result) + return results + + def get_knee_point_memory_budget( + self, + knapsack_algo: Callable[ + [list[float], list[float], float], tuple[float, list[int], list[int]] + ], + max_mem_budget: float = 0.1, + min_mem_budget: float = 0.001, + iterations: int = 100, + ) -> float: + """ + Finds the memory budget at the knee point in the Pareto frontier. + + The knee point is defined as the point where the trade-off between + runtime and memory usage is optimal. + + Args: + knapsack_algo (callable): Knapsack algorithm to use for evaluation. + max_mem_budget (float, optional): Maximum memory budget. Defaults to 0.1. + min_mem_budget (float, optional): Minimum memory budget. Defaults to 0.001. + iterations (int, optional): Number of memory budgets to evaluate. Defaults to 100. + + Returns: + float: Memory budget at the knee point. + """ + results = self.evaluate_distribution_of_results_for_knapsack_algo( + knapsack_algo=knapsack_algo, + memory_budget_values=[ + min_mem_budget + + i * (max_mem_budget - min_mem_budget) / (iterations - 1) + for i in range(iterations) + ], + ) + runtime_values = [ + result["percentage_of_theoretical_peak_runtime"] for result in results + ] + memory_values = [ + result["percentage_of_theoretical_peak_memory"] for result in results + ] + runtime_range = max(runtime_values) - min(runtime_values) + memory_range = max(memory_values) - min(memory_values) + if runtime_range == 0 or memory_range == 0: + return max_mem_budget + + # Normalize values + runtime_min = min(runtime_values) + memory_min = min(memory_values) + runtime_norm = [ + (value - runtime_min) / runtime_range for value in runtime_values + ] + memory_norm = [(value - memory_min) / memory_range for value in memory_values] + # Calculate Euclidean distance + distances = [ + (runtime_norm[i] ** 2 + memory_norm[i] ** 2) ** 0.5 + for i in range(len(runtime_norm)) + ] + # Find the knee point(shortest distance from the origin) + knee_index = distances.index(min(distances)) + return results[knee_index]["memory_budget"] diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/remat_using_tags_for_fwd_loss_bwd_graph_pass.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/remat_using_tags_for_fwd_loss_bwd_graph_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..a8826183675a8d169746aca181da469ecb1bb61b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/remat_using_tags_for_fwd_loss_bwd_graph_pass.py @@ -0,0 +1,246 @@ +"""AC rematerialize pass: Duplicates recompute nodes for backward, then DCE removes unused forward versions.""" + +import itertools +import logging +from typing import Any, overload + +import torch +import torch.fx as fx +from torch._functorch.compile_utils import raise_getitems +from torch._functorch.partitioners import ( + cleanup_recompute_tags, + force_save_bw_mutation_src, + has_recomputable_ops, + has_recomputable_rng_ops, + is_not_collective, + must_recompute, +) + + +log = logging.getLogger(__name__) +_EMPTY_CUSTOM_META: dict[str, object] = {} + + +def is_impure_node_for_dce(node: fx.Node) -> bool: + # Check for special collectives that should be treated as pure + if not is_not_collective(node): + # It's a collective (wait_tensor, all_gather_into_tensor, etc.) + # Treat as pure - can be eliminated if unused + return False + + # For everything else, fall back to the DEFAULT logic + # This is what eliminate_dead_code() calls when is_impure_node=None + impure_random = True + if torch._guards.TracingContext.try_get(): + impure_random = torch._inductor.config.fallback_random + return node.is_impure(impure_random) + + +def _is_backward_node(node: fx.Node, use_phase: bool = False) -> bool: + """Check if node is in backward region. + + If use_phase is True, only checks custom["phase"] == "backward" + (user annotation). Otherwise falls back to node.meta["autograd_backward"], + which Dynamo adds when tracing torch.autograd.grad. + """ + custom = node.meta.get("custom", _EMPTY_CUSTOM_META) + if use_phase: + return custom.get("phase") == "backward" + return node.meta.get("autograd_backward", False) + + +def _has_user_phase_annotation(gm: fx.GraphModule) -> bool: + """Check if any node has the user-level phase: backward annotation.""" + return any( + node.meta.get("custom", _EMPTY_CUSTOM_META).get("phase") == "backward" + for node in gm.graph.nodes + ) + + +def _collect_backward_regions( + gm: fx.GraphModule, use_phase: bool +) -> list[tuple[int, int, bool]]: + """Returns (bwd_start, bwd_end, needs_remat) for each backward region. + + Regions are maximal contiguous runs of backward nodes, as [start, end) + indices into the graph node list. + """ + regions: list[tuple[int, int, bool]] = [] + bwd_start: int | None = None + needs_remat = False + + for idx, node in enumerate(gm.graph.nodes): + if _is_backward_node(node, use_phase=use_phase): + if bwd_start is None: + bwd_start = idx + needs_remat = False + if not needs_remat and any( + must_recompute(inp) for inp in node.all_input_nodes + ): + needs_remat = True + elif bwd_start is not None: + regions.append((bwd_start, idx, needs_remat)) + bwd_start = None + + if bwd_start is not None: + regions.append((bwd_start, idx + 1, needs_remat)) + + return regions + + +def remat_using_tags_for_fwd_loss_bwd_graph(gm: fx.GraphModule) -> fx.GraphModule: + """ + Duplicate recompute nodes for backward use. DCE removes unused forward versions. + + Backward regions are identified by custom["phase"] == "backward" (user + annotation) or node.meta["autograd_backward"] == True (set automatically when + Dynamo traces torch.autograd.grad). When the user provides phase + annotations, only those annotated regions are used. + + The graph may contain multiple disjoint backward regions (e.g. chunked + loss). Regions that do not depend on recomputable forward nodes are + skipped. Only one region may require remat; if multiple do, we error + and ask the user to annotate which region to rematerialize. + """ + if not has_recomputable_ops(gm): + return gm + + if has_recomputable_rng_ops(gm): + raise RuntimeError( + "Activation checkpoint rematerialization in `forward-loss-backward` graph does not support RNG ops " + "in recompute regions. Please move RNG operations outside " + "of recompute regions, or use joint graph mode (where partitioner handles RNG)." + ) + + # Use partitioner pass to normalize AC node tags. + gm = cleanup_recompute_tags(gm, is_default_partition=True) + + force_save_bw_mutation_src(gm) + + # must_recompute (used inside _collect_backward_regions) requires + # cleanup_recompute_tags to have run first. + use_phase = _has_user_phase_annotation(gm) + regions = _collect_backward_regions(gm, use_phase) + if not regions: + return gm + + # User-annotated phase regions: multiple annotations is always an error. + if use_phase and len(regions) > 1: + raise RuntimeError( + f"Detected {len(regions)} disjoint backward regions annotated with " + 'phase: "backward" but remat only supports a single backward region. ' + "Please ensure only one contiguous region is annotated." + ) + + remat_regions = [(s, e) for s, e, needs in regions if needs] + + if len(remat_regions) > 1: + raise RuntimeError( + f"Detected {len(remat_regions)} disjoint backward regions that require recomputation, " + "but remat only supports one such region in a forward-loss-backward graph." + ) + + if not remat_regions: + return gm + + bwd_start, bwd_end = remat_regions[0] + + order = {node: idx for idx, node in enumerate(gm.graph.nodes)} + new_graph = fx.Graph() + env: dict[fx.Node, fx.Node] = {} + recomputed_nodes: dict[fx.Node, fx.Node] = {} + + # Insert forward nodes + for node in itertools.islice(gm.graph.nodes, 0, bwd_start): + env[node] = new_graph.node_copy(node, lambda x: env[x]) + + def _ensure_in_env(node: fx.Node) -> fx.Node: + """Eagerly copy a backward node and its dependencies into the new graph. + + The CPU offloading pass must run before remat. Offloaded forward nodes + carry ``cpu_offload_reload_node`` metadata pointing to their backward + reload chain (ao.reload -> ao.wait_tensor). Recomputed nodes need the + reloaded tensor, but the reload chain may not have been copied into + ``env`` yet (e.g. layer-boundary nodes whose reload is in a later + backward region). This helper copies the chain on demand. + """ + if node in env: + return env[node] + for dep in node.all_input_nodes: + _ensure_in_env(dep) + env[node] = new_graph.node_copy(node, lambda x: env[x]) + return env[node] + + @overload + def remat_input(x: fx.Node) -> fx.Node: ... + @overload + def remat_input(x: Any) -> Any: ... + + def remat_input(x: object) -> object: + if not isinstance(x, fx.Node): + return x + if x in recomputed_nodes: + return recomputed_nodes[x] + reload_node = x.meta.get("cpu_offload_reload_node") + if reload_node is not None: + return _ensure_in_env(reload_node) + return env[x] + + def gather_recompute_deps(node: fx.Node) -> set[fx.Node]: + deps: set[fx.Node] = set() + + def _gather(n: fx.Node) -> None: + if n in deps or n in recomputed_nodes or not must_recompute(n): + return + deps.add(n) + for inp in n.all_input_nodes: + _gather(inp) + + # Can't call _gather(node) directly: node itself may not be must_recompute + # (e.g. backward nodes), so _gather would return early without visiting inputs. + for inp in node.all_input_nodes: + _gather(inp) + return deps + + # Insert backward nodes + for node in itertools.islice(gm.graph.nodes, bwd_start, bwd_end): + # Gather all deps that need to be recomputed for this node + deps = gather_recompute_deps(node) + + # Insert deps in forward order (guaranteed disjoint from already-inserted) + # This is not as inefficient as it looks, because we only add fresh dependencies + # when they are not yet processed as recomputed nodes. + new_deps = sorted(deps, key=lambda n: order[n]) + if new_deps: + log.debug( + "To compute backward node %s, recomputing [%s]", + node.name, + ", ".join(dep.name for dep in new_deps), + ) + for dep in new_deps: + dup = new_graph.node_copy(dep, remat_input) + dup.name = dep.name + "_recomputed" + dup.meta["autograd_backward"] = True + recomputed_nodes[dep] = dup + + # Skip nodes already copied by _ensure_in_env (offload reload chains) + # to avoid duplicating H2D transfers. + if node not in env: + env[node] = new_graph.node_copy(node, remat_input) + + for node in itertools.islice(gm.graph.nodes, bwd_end, None): + if node not in env: + env[node] = new_graph.node_copy(node, lambda x: env[x]) + + new_gm = torch.fx.GraphModule(gm, new_graph) + + # DCE with custom is_impure_node (like default_partition) + # Treats certain collectives as pure while delegating to default impurity logic + new_gm.graph.eliminate_dead_code(is_impure_node=is_impure_node_for_dce) + + # raise_getitems pass for better memory (like default_partition) + new_gm = raise_getitems(new_gm) + + new_gm.recompile() + + return new_gm diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__init__.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80ad878f7a054c3c9b66d9155413b3be3ee1ae4a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/activation_offloading.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/activation_offloading.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..630773a1a9b1b85a87e6579a59c67336f755246c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/activation_offloading.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/offload_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/offload_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78276c0e463695bdb9314138d1a692c89df21f87 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/offload_ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/activation_offloading.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/activation_offloading.py new file mode 100644 index 0000000000000000000000000000000000000000..943ec2cf75cac70857bc959e6533c43d381b127f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/activation_offloading.py @@ -0,0 +1,828 @@ +"""Activation offloading for memory optimization during compilation. + +This module provides functionality to offload activations to CPU during the forward +pass and reload them during the backward pass, reducing GPU memory usage. It can be +applied to graphs produced by both AOT Autograd partitioners and make_fx-based tracing. +""" + +import logging +import operator +from dataclasses import dataclass + +import torch +import torch.fx as fx +from torch._functorch._activation_offloading.offload_ops import ( # noqa: F401 -- registers ao::offload, ao::reload, ao::wait_tensor ops + offload, + reload, + wait_tensor, +) +from torch._inductor.fx_passes.overlap_scheduling import benchmark_node, is_compute_node +from torch._subclasses.fake_tensor import extract_tensor_metadata +from torch.utils._ordered_set import OrderedSet + +from .. import config +from ..partitioners import _size_of, get_default_op_list, OpTypes + + +log: logging.Logger = logging.getLogger(__name__) + + +# Node name prefixes for offload/reload operations +# NOTE: right now we are using these prefixes as identifiers for offload/reload +CPU_OFFLOAD_PREFIX = "cpu_offload_" +GPU_RELOAD_PREFIX = "gpu_reload_" + + +def _find_all_effective_users(node: fx.Node, op_types: OpTypes) -> OrderedSet[fx.Node]: + """Find all effective users of a node, where view ops extend the lifetime + of the original node. If a user is a view op, recursively find users of + the view.""" + effective_users: OrderedSet[fx.Node] = OrderedSet() + for user in node.users: + if user.op == "output": + continue + effective_users.add(user) + if op_types.is_view(user): + effective_users.update(_find_all_effective_users(user, op_types)) + return effective_users + + +@dataclass +class ReloadNodeInfo: + """ + Information about backward reload related nodes for each reload operation. + + Pattern: ao.reload → ao.wait_tensor + + - Reload group (ao.reload): Performs the actual asynchronous data transfer. + Can be moved earlier in the graph to overlap with computation. + - Wait node (ao.wait_tensor): Synchronization point that blocks until the data + transfer completes. Must remain at the point where the data is first needed. + """ + + reload_group_nodes: list[fx.Node] + wait_event_node: fx.Node + transfer_size_bytes: int + transfer_time_ms: float + + +@dataclass +class ReloadQueueEntry: + """ + Entry in the reload queue for prefetch scheduling. + + Attributes: + pattern: The reload pattern information + remaining_time_ms: Remaining overlap time needed in milliseconds + """ + + pattern: ReloadNodeInfo + remaining_time_ms: float + + +def offload_activation_fw(graph: fx.Graph) -> None: + """ + Insert CPU offload operations in the forward pass graph. + + Offload operations are placed after the last effective use of each tensor marked + for offloading. This ensures the tensor is no longer needed on the GPU before + transferring it to CPU memory. + + NOTE: An alternative approach would offload tensors immediately after generation + to maximize compute-communication overlap. However, this requires additional + synchronization to ensure tensor deletion (which occurs on the default stream) + waits for the asynchronous offload operation to complete. This would necessitate + more complex tracking to separate operation scheduling from memory cleanup. + + Args: + graph: The forward graph to modify + """ + + op_types: OpTypes = get_default_op_list() + + output_node: fx.Node = graph.find_nodes(op="output")[0] + # pyrefly: ignore [bad-assignment] + fwd_outputs: tuple[fx.Node, ...] = output_node.args[ + 0 + ] # pyrefly: ignore [bad-assignment] + node_to_offload: dict[fx.Node, fx.Node] = dict() + node_to_index: dict[fx.Node, int] = { + node: idx for idx, node in enumerate(graph.nodes) + } + + for node in fwd_outputs: + if node.meta.get("saved_for_offloading", False) is False: + continue + + # Find insertion point, which is the last use + if all_effective_users := _find_all_effective_users(node, op_types): + last_user = max(all_effective_users, key=lambda n: node_to_index[n]) + else: + last_user: fx.Node = node + + # Insert the CPU offload operation after the last user + with graph.inserting_after(last_user): + cpu_node: fx.Node = graph.call_function( + torch.ops.prims.device_put.default, + args=(node, torch.device("cpu")), + kwargs={"non_blocking": True}, + name=CPU_OFFLOAD_PREFIX + str(node.name), + ) + cpu_node.meta["val"] = node.meta["val"].to(torch.device("cpu")) + cpu_node.meta["tensor_meta"] = extract_tensor_metadata(cpu_node.meta["val"]) + + node_to_offload[node] = cpu_node + + # Update the return node args + output_node.update_arg( + 0, tuple(node_to_offload.get(node, node) for node in fwd_outputs) + ) + + +def reload_activation_bw(graph: fx.Graph) -> None: + """ + Insert GPU reload operations in the backward pass graph. + + Reload operations are placed before the first use of each offloaded tensor, + transferring it from CPU back to GPU memory before it's needed for computation. + + Args: + graph: The backward graph to modify + """ + + node_to_index: dict[fx.Node, int] = { + node: idx for idx, node in enumerate(graph.nodes) + } + output_node: fx.Node = graph.find_nodes(op="output")[0] + + for node in graph.find_nodes(op="placeholder"): + if node.meta.get("saved_for_offloading", False) is False: + continue + + # Find insertion point, which is the first use or output node if no users + # The later should not happen, but inserting before output node is safe + insert_point: fx.Node = ( + min(node.users.keys(), key=lambda n: node_to_index[n]) + if node.users + else output_node + ) + + # Insert the GPU reload operation before the first user + original_device: torch.Device = node.meta["original_device"] + with graph.inserting_before(insert_point): + gpu_node: fx.Node = graph.call_function( + torch.ops.prims.device_put.default, + args=(node, original_device), + kwargs={"non_blocking": True}, + name=str(node.name).replace(CPU_OFFLOAD_PREFIX, GPU_RELOAD_PREFIX), + ) + gpu_node.meta["val"] = node.meta["val"].to(original_device) + gpu_node.meta["tensor_meta"] = extract_tensor_metadata(gpu_node.meta["val"]) + + # Replace all uses of the CPU tensor with the GPU tensor + for user in list(node.users.keys()): + if user != gpu_node: + user.replace_input_with(node, gpu_node) + + +def offload_activation_fw_async(graph: fx.Graph) -> None: + """Insert async CPU offload operations in the forward pass graph. + + Uses ao.offload + ao.wait_tensor ops which encapsulate stream management + internally, producing a clean 2-node IR per offloaded tensor. + """ + + op_types: OpTypes = get_default_op_list() + + output_node: fx.Node = graph.find_nodes(op="output")[0] + # pyrefly: ignore [bad-assignment] + fwd_outputs: tuple[fx.Node, ...] = output_node.args[ + 0 + ] # pyrefly: ignore [bad-assignment] + node_to_offload: dict[fx.Node, fx.Node] = dict() + node_to_index: dict[fx.Node, int] = { + node: idx for idx, node in enumerate(graph.nodes) + } + + if not any(n.meta.get("saved_for_offloading", False) for n in fwd_outputs): + return + + for node in fwd_outputs: + if node.meta.get("saved_for_offloading", False) is False: + continue + + if all_effective_users := _find_all_effective_users(node, op_types): + last_user = max(all_effective_users, key=lambda n: node_to_index[n]) + else: + last_user: fx.Node = node + + with graph.inserting_after(last_user): + offload_node: fx.Node = graph.call_function( + torch.ops.ao.offload.default, + args=(node,), + name=f"async_{CPU_OFFLOAD_PREFIX}{node.name}", + ) + offload_node.meta["val"] = node.meta["val"].to(torch.device("cpu")) + offload_node.meta["tensor_meta"] = extract_tensor_metadata( + offload_node.meta["val"] + ) + # The keepalive=node arg extends the GPU tensor's lifetime in the + # graph so the allocator doesn't reclaim it before the async D2H + # copy completes. + with graph.inserting_after(offload_node): + wait_node: fx.Node = graph.call_function( + torch.ops.ao.wait_tensor.default, + args=(offload_node, node), + name=CPU_OFFLOAD_PREFIX + str(node.name), + ) + wait_node.meta["val"] = offload_node.meta["val"] + wait_node.meta["tensor_meta"] = offload_node.meta["tensor_meta"] + + node_to_offload[node] = wait_node + + output_node.update_arg( + 0, tuple(node_to_offload.get(node, node) for node in fwd_outputs) + ) + + +def reload_activation_bw_async(graph: fx.Graph) -> None: + """Insert async GPU reload operations in the backward pass graph. + + Uses ao.reload + ao.wait_tensor ops which encapsulate stream management internally, + producing a clean 2-node IR per reloaded tensor. + """ + + node_to_index: dict[fx.Node, int] = { + node: idx for idx, node in enumerate(graph.nodes) + } + + nodes_to_reload = [ + n + for n in graph.find_nodes(op="placeholder") + if n.meta.get("saved_for_offloading", False) + ] + if not nodes_to_reload: + return + + for node in nodes_to_reload: + if not node.users: + raise RuntimeError( + f"Offloaded tensor {node.name} has no users in the backward graph" + ) + insert_point: fx.Node = min(node.users.keys(), key=lambda n: node_to_index[n]) + + original_device: torch.device = node.meta["original_device"] + original_size: tuple[int, ...] = node.meta["original_size"] + original_stride: tuple[int, ...] = node.meta["original_stride"] + with graph.inserting_before(insert_point): + reload_node: fx.Node = graph.call_function( + torch.ops.ao.reload.default, + args=( + node, + original_device, + list(original_size), + list(original_stride), + ), + name=f"async_{str(node.name).replace(CPU_OFFLOAD_PREFIX, GPU_RELOAD_PREFIX)}", + ) + reload_node.meta["val"] = torch.empty_strided( + original_size, + original_stride, + dtype=node.meta["val"].dtype, + device=original_device, + ) + reload_node.meta["tensor_meta"] = extract_tensor_metadata( + reload_node.meta["val"] + ) + wait_node: fx.Node = graph.call_function( + torch.ops.ao.wait_tensor.default, + args=(reload_node, node), + name=str(node.name).replace(CPU_OFFLOAD_PREFIX, GPU_RELOAD_PREFIX), + ) + wait_node.meta["val"] = reload_node.meta["val"] + wait_node.meta["tensor_meta"] = reload_node.meta["tensor_meta"] + + for user in list(node.users.keys()): + if user != reload_node and user != wait_node: + user.replace_input_with(node, wait_node) + + +def can_offload( + node: fx.Node, + fwd_outputs: OrderedSet[fx.Node], + model_outputs: OrderedSet[fx.Node], + static_lifetime_input_nodes: OrderedSet[fx.Node], +) -> bool: + """ + Determine if a node can be offloaded to CPU. + + Args: + node: The node to check + fwd_outputs: Forward module outputs, including model outputs and activations + model_outputs: Model outputs + + NOTE: Additional context for the logic behind these offloading checks: + + * fwd_outputs: Only saved intermediate tensors should be offloaded. + + * model_outputs / static_lifetime_input_nodes: Tensors that may be accessed outside + the compiled region (e.g., model outputs, static inputs) cannot be offloaded as + they must remain accessible beyond the scope of the compiled graph. + + * views / getitems: Offloading such nodes can lead to segmentation faults. + + * contiguous: Offloading non-contiguous tensors causes CPU-side stride changes + during both forward and backward passes when using the Inductor backend. While + these stride changes cancel each other out, they introduce significant compute + overhead. This is due to the contiguity check in ir.py (see link below). + TODO: This restriction could potentially be bypassed in the future. + Reference: https://github.com/pytorch/pytorch/blob/44ac69388a4a5eb463dbd2a13f00d1e3b924566c/torch/_inductor/ir.py#L3214 + + Additional criteria to consider for offloading optimization: + + * Tensor size: Small tensors may not fully utilize available bandwidth, reducing the + efficiency gains from offloading. + + * Position in forward/backward graph: Activations generated near the end of the forward + pass are typically consumed near the beginning of the backward pass. Offloading such + tensors may be counterproductive since they are quickly reloaded, not having sufficient + time to overlap the transfer with computation. + """ + + log.debug(f"Checking node {node.name} for offloading...") # noqa: G004 + + op_types: OpTypes = get_default_op_list() + + if node not in fwd_outputs: + log.debug("\tSkipped! Can only offload nodes in fwd_module_outputs.") + return False + if node in model_outputs: + log.debug("\tSkipped! Cannot offload model outputs.") + return False + if node in static_lifetime_input_nodes: + log.debug("\tSkipped! Cannot offload static input nodes.") + return False + if op_types.is_view(node): + log.debug("\tSkipped! Cannot offload views.") + return False + if node.target == operator.getitem: + log.debug("\tSkipped! Cannot offload getitems.") + return False + if hasattr(node, "meta") and "val" in node.meta: + if ( + isinstance(val := node.meta["val"], torch.Tensor) + and not val.is_contiguous() + ): + log.debug("\tSkipped! Cannot offload non-contiguous tensors.") + return False + + log.debug("\tGood!") + return True + + +def choose_offload_sets( + fwd_module: fx.GraphModule, + num_fwd_outputs: int, + static_lifetime_input_nodes: OrderedSet[fx.Node], +) -> bool: + """ + Decide which nodes will be offloaded based on the marked nodes and feasibility. + Marks nodes with "saved_for_offloading" if they should and can be offloaded. + + Args: + fwd_module: Forward graph module + bwd_module: Backward graph module + num_fwd_outputs: Number of forward outputs + + Returns: + bool: Whether activation offloading should be performed + """ + + fwd_outputs: OrderedSet[fx.Node] = OrderedSet( + fwd_module.graph.find_nodes(op="output")[0].args[0] + ) + model_outputs: OrderedSet[fx.Node] = OrderedSet( + fwd_module.graph.find_nodes(op="output")[0].args[0][:num_fwd_outputs] + ) + + should_perform_offloading = False + for node in fwd_module.graph.nodes: + if node.meta.get("should_offload", False) and can_offload( + node, fwd_outputs, model_outputs, static_lifetime_input_nodes + ): + node.meta["saved_for_offloading"] = True + should_perform_offloading = True + + return should_perform_offloading + + +def offload_chosen_sets( + fwd_module: fx.GraphModule, + bwd_module: fx.GraphModule, +) -> None: + """ + Add offload and reload nodes to the forward and backward graphs. + This function adds device_put operations without any stream handling. + + Args: + fwd_module: Forward module graph + bwd_module: Backward module graph + """ + + # Add offload nodes in forward graph + offload_activation_fw(fwd_module.graph) + + # Update backward graph inputs to be offloaded tensors + bwd_inputs: dict[str, fx.Node] = { + node.name: node for node in bwd_module.graph.find_nodes(op="placeholder") + } + for fwd_node in fwd_module.graph.find_nodes(op="output")[0].args[0]: + if CPU_OFFLOAD_PREFIX not in fwd_node.name: + continue + + bwd_node: fx.Node = bwd_inputs[fwd_node.name.replace(CPU_OFFLOAD_PREFIX, "")] + with bwd_module.graph.inserting_after(bwd_node): + bwd_offload_node: fx.Node = bwd_module.graph.placeholder(name=fwd_node.name) + + bwd_offload_node.meta.update(fwd_node.meta) + bwd_offload_node.meta["saved_for_offloading"] = True + bwd_offload_node.meta["original_device"] = bwd_node.meta["val"].device + bwd_offload_node.meta["original_size"] = tuple(bwd_node.meta["val"].size()) + bwd_offload_node.meta["original_stride"] = tuple(bwd_node.meta["val"].stride()) + bwd_node.replace_all_uses_with(bwd_offload_node) + bwd_module.graph.erase_node(bwd_node) + + # Add reload nodes in backward graph + reload_activation_bw(bwd_module.graph) + + +def offload_chosen_sets_async( + fwd_module: fx.GraphModule, + bwd_module: fx.GraphModule, +) -> None: + """ + Add async offload and reload nodes using ao ops. + + Uses ao.offload/ao.reload + ao.wait_tensor which encapsulate stream management, + instead of device_put + explicit stream operations. Can be applied to + partitioned forward/backward graphs or to a joint graph produced by make_fx. + """ + + offload_activation_fw_async(fwd_module.graph) + + # Replace backward graph placeholders with their offloaded (CPU) counterparts. + # For each offloaded forward output, find the matching backward input and swap + # it with a new placeholder carrying the CPU tensor's metadata, then mark it + # for reloading. + bwd_inputs: dict[str, fx.Node] = { + node.name: node for node in bwd_module.graph.find_nodes(op="placeholder") + } + for fwd_node in fwd_module.graph.find_nodes(op="output")[0].args[0]: + if CPU_OFFLOAD_PREFIX not in fwd_node.name: + continue + + bwd_node: fx.Node = bwd_inputs[fwd_node.name.replace(CPU_OFFLOAD_PREFIX, "")] + with bwd_module.graph.inserting_after(bwd_node): + bwd_offload_node: fx.Node = bwd_module.graph.placeholder(name=fwd_node.name) + + bwd_offload_node.meta.update(fwd_node.meta) + bwd_offload_node.meta["saved_for_offloading"] = True + bwd_offload_node.meta["original_device"] = bwd_node.meta["val"].device + bwd_offload_node.meta["original_size"] = tuple(bwd_node.meta["val"].size()) + bwd_offload_node.meta["original_stride"] = tuple(bwd_node.meta["val"].stride()) + bwd_node.replace_all_uses_with(bwd_offload_node) + bwd_module.graph.erase_node(bwd_node) + + reload_activation_bw_async(bwd_module.graph) + + +def activation_offload_sink_wait_async(fwd_module: fx.GraphModule) -> None: + """Sink ao.wait_tensor operations for offload completion to the end of the graph. + + This allows computation to overlap with offload operations. + + NOTE: Sinking waits to the end delays GPU memory release of the source + tensor (kept alive via the wait's keepalive arg) until the end of the + compiled graph. For per-layer compile this is fine (one layer's worth of + memory), but for full-model compile this means offloaded GPU tensors are + not freed until the entire forward pass completes. + """ + graph: fx.Graph = fwd_module.graph + output_node: fx.Node = graph.find_nodes(op="output")[0] + + wait_nodes_to_sink: list[fx.Node] = [ + node + for node in graph.nodes + if node.op == "call_function" + and node.target == torch.ops.ao.wait_tensor.default + and isinstance(node.args[0], fx.Node) + and node.args[0].op == "call_function" + and node.args[0].target == torch.ops.ao.offload.default + ] + + # prepend moves the node from its current position (no manual removal needed) + for wait_node in wait_nodes_to_sink: + output_node.prepend(wait_node) + + +def activation_reload_prefetch_async(bwd_module: fx.GraphModule) -> None: + """ + Prefetch backward reload operations by moving ao.reload nodes earlier + in the graph to overlap data transfer with computation, while keeping + ao.wait_tensor at its original position. + """ + graph: fx.Graph = bwd_module.graph + nodes_list: list[fx.Node] = list(graph.nodes) + + # Identify reload + wait pairs + reload_patterns: dict[fx.Node, ReloadNodeInfo] = {} + for node in graph.nodes: + if not ( + node.op == "call_function" and node.target == torch.ops.ao.reload.default + ): + continue + wait_node = next( + (u for u in node.users if u.target == torch.ops.ao.wait_tensor.default), + None, + ) + if wait_node is None: + continue + transfer_size_bytes: int = _calculate_transfer_size(node) + transfer_time_ms: float = _estimate_transfer_time_in_ms(transfer_size_bytes) + reload_patterns[node] = ReloadNodeInfo( + reload_group_nodes=[node], + wait_event_node=wait_node, + transfer_size_bytes=transfer_size_bytes, + transfer_time_ms=transfer_time_ms, + ) + + reorder_for_prefetch(nodes_list, reload_patterns) + + +def _calculate_transfer_size(device_put_node: fx.Node) -> int: + """Calculate the size in bytes of data being transferred.""" + + # ao.offload(tensor) -> tensor at args[0] + # ao.reload(tensor, device) -> tensor at args[0] + if device_put_node.target in ( + torch.ops.ao.offload.default, + torch.ops.ao.reload.default, + ): + return _size_of(device_put_node.args[0]) # pyrefly: ignore [bad-argument-type] + raise ValueError(f"Unexpected transfer op: {device_put_node.target}") + + +def _estimate_transfer_time_in_ms(transfer_size_bytes: int) -> float: + """Estimate transfer time in milliseconds based on size and bandwidth. + + Uses config.activation_offload_cpu_gpu_bw (GB/s) which should be set by + the user to match their hardware. + """ + return ( + transfer_size_bytes / (1024**3) * 1_000 / config.activation_offload_cpu_gpu_bw + ) + + +def identify_reload_patterns( + graph: fx.Graph, nodes_list: list[fx.Node], node_to_idx: dict[fx.Node, int] +) -> dict[fx.Node, ReloadNodeInfo]: + """ + Identify backward reload patterns in the graph. + + Pattern: fork → wait_stream → device_put → record_event → join → wait_event + + This uses position-based matching since these nodes are inserted together in + add_backward_reload_stream_ops() in a specific order. Since stream operations + do not have data dependencies between them, they are unsuitable for subgroup + pattern matching type of checks. + + Returns a dict mapping device_put node to ReloadNodeInfo containing: + - reload_group_nodes: fork → wait_stream → device_put → record_event → join + - wait_event_node: the wait_event node + - transfer_size_bytes: size of data being transferred + - transfer_time_ms: estimated transfer time in milliseconds + """ + patterns: dict[fx.Node, ReloadNodeInfo] = {} + + # Find all GPU reload device_put nodes whose inputs are placeholder nodes + reload_nodes: list[fx.Node] = [ + node + for node in graph.find_nodes( + op="call_function", target=torch.ops.prims.device_put.default + ) + if GPU_RELOAD_PREFIX in node.name + and ( + node.args + and isinstance(node.args[0], fx.Node) + and node.args[0].op == "placeholder" + ) + ] + + # Extract patterns for each reload device_put node + for reload_node in reload_nodes: + reload_node_idx: int = node_to_idx[reload_node] + + fork_node: fx.Node = nodes_list[reload_node_idx - 2] + wait_stream_node: fx.Node = nodes_list[reload_node_idx - 1] + record_event_node: fx.Node = nodes_list[reload_node_idx + 1] + join_node: fx.Node = nodes_list[reload_node_idx + 2] + wait_event_node: fx.Node = nodes_list[reload_node_idx + 3] + + # Validate the nodes are what we expect + # Removed in follow-up commit + _validate_pattern_nodes( # noqa: F821 # pyrefly: ignore [unknown-name] + fork_node, + wait_stream_node, + record_event_node, + join_node, + wait_event_node, + ) + + # Calculate transfer size and time + transfer_size_bytes: int = _calculate_transfer_size(reload_node) + transfer_time_ms: float = _estimate_transfer_time_in_ms(transfer_size_bytes) + + patterns[reload_node] = ReloadNodeInfo( + reload_group_nodes=[ + fork_node, + wait_stream_node, + reload_node, + record_event_node, + join_node, + ], + wait_event_node=wait_event_node, + transfer_size_bytes=transfer_size_bytes, + transfer_time_ms=transfer_time_ms, + ) + + return patterns + + +def reorder_for_prefetch( + nodes_list: list[fx.Node], + reload_patterns: dict[fx.Node, ReloadNodeInfo], +) -> None: + """ + Reorder nodes to prefetch reload operations by directly manipulating the graph. + + This follows the algorithm as follows: + - Go through nodes in reverse order + - When encountering a reload pattern, add it to a queue with its transfer time + - When encountering a compute node, use its runtime to satisfy overlap requirements + - Place reload patterns when their overlap requirement is satisfied + - When encountering placeholder nodes, flush queue as reloads cannot move before inputs + """ + + # Build a set of all nodes in reload groups for quick lookup + reload_group_nodes_set: set[fx.Node] = set() + for pattern in reload_patterns.values(): + reload_group_nodes_set.update(pattern.reload_group_nodes) + + # Queue to hold reload group nodes waiting to be placed (FIFO) + reload_queue: list[ReloadQueueEntry] = [] + + # Loop through nodes in reverse + for node in reversed(nodes_list): + if node.op == "output": + continue + elif node.op == "placeholder": + # Flush queue - place all remaining reloads after the last placeholder + while reload_queue: + entry: ReloadQueueEntry = reload_queue.pop(0) + for reload_group_node in reversed(entry.pattern.reload_group_nodes): + node.append(reload_group_node) + break + elif node in reload_patterns: + pattern: ReloadNodeInfo = reload_patterns[node] + reload_queue.append( + ReloadQueueEntry( + pattern=pattern, remaining_time_ms=pattern.transfer_time_ms + ) + ) + elif node in reload_group_nodes_set: + continue + else: + if not reload_queue: + continue + compute_runtime_ms: float = ( + benchmark_node(node) if is_compute_node(node) else 0 + ) + reload_queue[0].remaining_time_ms -= compute_runtime_ms + + # Pop and place reload if its remaining time is satisfied (<= 0) + if reload_queue[0].remaining_time_ms <= 0: + entry: ReloadQueueEntry = reload_queue.pop(0) + for reload_group_node in entry.pattern.reload_group_nodes: + node.prepend(reload_group_node) + + +def activation_offload_sink_wait(fwd_module: fx.GraphModule) -> None: + """ + Sink wait_event operations for offload completion to the end of the graph. + + This function identifies wait_event nodes for offload completion and moves them + to the end of the graph, allowing computation to overlap with offload operations. + + Args: + fwd_module: Forward module graph + """ + graph: fx.Graph = fwd_module.graph + nodes_list: list[fx.Node] = list(graph.nodes) + node_to_idx: dict[fx.Node, int] = {node: idx for idx, node in enumerate(nodes_list)} + + # Find all CPU offload device_put nodes + offload_nodes: list[fx.Node] = [ + node + for node in graph.find_nodes( + op="call_function", target=torch.ops.prims.device_put.default + ) + if CPU_OFFLOAD_PREFIX in node.name + ] + + # Collect all wait_event nodes that need to be moved + wait_nodes_to_sink: list[fx.Node] = [] + for offload_node in offload_nodes: + offload_idx: int = node_to_idx[offload_node] + wait_event_node: fx.Node = nodes_list[offload_idx + 3] + + # Validate it's actually a wait_event node + if not ( + wait_event_node.op == "call_function" + and wait_event_node.target == torch.ops.streams.wait_event.default + ): + raise ValueError( + f"Expected wait_event node three positions after {offload_node.name}" + ) + + wait_nodes_to_sink.append(wait_event_node) + + # Find the output node, and move all wait_event nodes to just before the output node + output_node: fx.Node = graph.find_nodes(op="output")[0] + for wait_node in wait_nodes_to_sink: + output_node.prepend(wait_node) + + +def activation_reload_prefetch(bwd_module: fx.GraphModule) -> None: + """ + Prefetch backward reload operations by moving them earlier in the graph + to overlap communication with computation. + + This function identifies backward reload patterns (fork → wait_stream → device_put → + record_event → join) and moves them earlier in the execution order to overlap + the data transfer with computation, while keeping the wait_event at its original + position. + + Args: + bwd_module: Backward module graph + """ + graph: fx.Graph = bwd_module.graph + nodes_list: list[fx.Node] = list(graph.nodes) + node_to_idx: dict[fx.Node, int] = {node: idx for idx, node in enumerate(nodes_list)} + + # Step 1: Identify reload patterns + reload_patterns: dict[fx.Node, ReloadNodeInfo] = identify_reload_patterns( + graph, nodes_list, node_to_idx + ) + + # Step 2: Reorder nodes by directly manipulating the graph + reorder_for_prefetch(nodes_list, reload_patterns) + + +def enable_activation_offloading( + fwd_module: fx.GraphModule, + bwd_module: fx.GraphModule, + num_fwd_outputs: int, + static_lifetime_input_nodes: OrderedSet[fx.Node], +) -> None: + """ + Main entry point for activation offloading. + + Args: + fwd_module: Forward module graph + bwd_module: Backward module graph + num_fwd_outputs: Number of forward outputs + """ + + # Step 1: Decide which nodes to offload and mark them + should_perform_offloading: bool = choose_offload_sets( + fwd_module, + num_fwd_outputs, + static_lifetime_input_nodes, + ) + if not should_perform_offloading: + return + + # Step 2: Add offload and reload nodes to the graphs + if config.activation_offload_separate_stream: + # Use async ao ops (2 nodes each: offload/reload + wait_tensor) + offload_chosen_sets_async(fwd_module, bwd_module) + if config.activation_offload_sink_wait: + activation_offload_sink_wait_async(fwd_module) + if config.activation_reload_prefetch: + activation_reload_prefetch_async(bwd_module) + else: + # Use synchronous device_put (1 node each) + offload_chosen_sets(fwd_module, bwd_module) + + fwd_module.graph.lint() + bwd_module.graph.lint() diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/offload_ops.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/offload_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..88b663b59aadb8b3433aebaf4aedb0a65f9e5f06 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/offload_ops.py @@ -0,0 +1,296 @@ +"""Custom ops for async activation offloading between GPU and CPU. + +These ops encapsulate stream management internally, producing a clean 2-node +IR pattern (offload/reload + wait_tensor) similar to c10d functional collectives. + +A single dedicated transfer stream handles all D2H/H2D copies. +Completion events are keyed by output tensor data_ptr() and stored in a +module-level registry, so ``ao.wait_tensor`` takes only the tensor itself +(plus optional ``keepalive`` and ``last_use_of_storage`` args). + +Offload pattern: + cpu_tensor = ao.offload(gpu_tensor) + cpu_tensor = ao.wait_tensor(cpu_tensor, keepalive=gpu_tensor) + keepalive frees the GPU tensor's storage after the D2H copy completes. + +Reload pattern: + gpu_tensor = ao.reload(cpu_tensor, device) + gpu_tensor = ao.wait_tensor(gpu_tensor, keepalive=cpu_tensor) + keepalive frees the CPU tensor's storage after the H2D copy completes. + +The optional ``last_use_of_storage`` arg creates a dependency on a tensor whose +storage must outlive the async transfer but is not otherwise connected by a +data-flow edge in the graph. +""" + +import torch +from torch._library.custom_ops import custom_op +from torch.fx import has_side_effect + + +# --- Global transfer stream (one per device, lazily created) --- +_transfer_streams: dict[torch.device, torch.Stream] = {} + + +def _get_or_create_transfer_stream(device: torch.device) -> torch.Stream: + if device not in _transfer_streams: + _transfer_streams[device] = torch.Stream(device=device) + return _transfer_streams[device] + + +# --- Pinned memory pool (avoids per-offload cudaHostAlloc overhead) --- +# Keyed by (numel, dtype) to prevent cross-dtype reuse. +# Not keyed by device: pinned CPU memory is host-side and accessible from +# any GPU. Cross-device reuse is safe because wait_tensor synchronizes the +# transfer (via wait_event) before _pool_free returns the buffer — the +# buffer is never in-flight when reused. +_pinned_pool: dict[tuple[int, torch.dtype], list[torch.Tensor]] = {} +_pool_enabled: bool = False +_pool_managed_ptrs: set[int] = set() + + +def _maybe_pool_alloc(numel: int, dtype: torch.dtype) -> torch.Tensor: + """Get a pinned CPU buffer from the pool (if enabled), or allocate fresh.""" + if _pool_enabled: + key = (numel, dtype) + bucket = _pinned_pool.get(key) + if bucket: + buf = bucket.pop() + _pool_managed_ptrs.add(buf.data_ptr()) + return buf + buf = torch.empty(numel, dtype=dtype, device="cpu", pin_memory=True) + _pool_managed_ptrs.add(buf.data_ptr()) + return buf + return torch.empty(numel, dtype=dtype, device="cpu", pin_memory=True) + + +def _pool_free(buf: torch.Tensor) -> None: + """Return a pinned buffer to the pool, or free its storage if pool disabled.""" + ptr = buf.data_ptr() + if ptr in _pool_managed_ptrs: + key = (buf.nelement(), buf.dtype) + _pinned_pool.setdefault(key, []).append(buf) + else: + storage = buf.untyped_storage() + if storage.size() > 0: + storage.resize_(0) + + +def _pool_clear() -> None: + """Free all cached pinned buffers.""" + _pinned_pool.clear() + _pool_managed_ptrs.clear() + + +import contextlib + + +@contextlib.contextmanager +def pinned_memory_pool(enabled: bool = True): + """Context manager that controls pinned memory pooling for offload ops. + + Without this context manager, ``ao.offload`` allocates a fresh pinned + buffer every call and ``ao.wait_tensor`` does not cache freed buffers. + Inside the context with ``enabled=True``, buffers are reused across + calls, avoiding the ~3 ms per-tensor ``cudaHostAlloc`` overhead:: + + with pinned_memory_pool(): + for step in range(num_steps): + train_step() # ao.offload/reload reuse pooled buffers + # pinned buffers freed here + + Nestable: inner contexts save and restore the outer state. + Pass ``enabled=False`` to temporarily disable pooling. + """ + global _pool_enabled + saved = _pool_enabled + _pool_enabled = enabled + try: + yield + finally: + if not saved: + _pool_clear() + _pool_enabled = saved + + +# --- Wait registry: maps data_ptr() -> (completion_event, device) --- +# Created by ao.offload / ao.reload, consumed (popped) by ao.wait_tensor. +# Not thread-safe — graph execution is single-threaded Python. +_wait_registry: dict[int, tuple[torch.Event, torch.device]] = {} + + +def _register_wait(tensor: torch.Tensor, device: torch.device) -> torch.Event: + """Create an event for an async transfer and register it for wait_tensor.""" + event = torch.Event() + _wait_registry[tensor.data_ptr()] = (event, device) + return event + + +def _pop_wait(tensor: torch.Tensor) -> tuple[torch.Event, torch.device]: + key = tensor.data_ptr() + try: + return _wait_registry.pop(key) + except KeyError: + raise RuntimeError( + f"ao.wait_tensor: no pending transfer for tensor with data_ptr={key}. " + "Every ao.wait_tensor must be paired with a preceding ao.offload or ao.reload." + ) from None + + +def _clear_wait_registry() -> None: + _wait_registry.clear() + + +@custom_op("ao::offload", mutates_args=()) +def offload(tensor: torch.Tensor) -> torch.Tensor: + """Async offload a GPU tensor to CPU on the dedicated transfer stream. + + Callers MUST pair this with an ``ao.wait_tensor`` that passes the source GPU + tensor as ``keepalive`` to extend its lifetime past the async D2H copy. + Do NOT use ``record_stream`` — it causes memory fragmentation and + unbounded memory growth. + + Uses pinned-memory allocation + copy_ so the transfer is compatible + with CUDA graph capture. + """ + device = tensor.device + transfer_stream = _get_or_create_transfer_stream(device) + current_stream = torch.accelerator.current_stream(device) + + transfer_stream.wait_stream(current_stream) + + torch.accelerator.set_stream(transfer_stream) + result = _maybe_pool_alloc(tensor.nelement(), tensor.dtype).view(tensor.shape) + completion_event = _register_wait(result, device) + result.copy_(tensor, non_blocking=True) + transfer_stream.record_event(completion_event) + torch.accelerator.set_stream(current_stream) + + return result + + +@offload.register_fake +def _(tensor: torch.Tensor) -> torch.Tensor: + return torch.empty(tensor.shape, dtype=tensor.dtype, device="cpu") + + +@custom_op("ao::reload", mutates_args=()) +def reload( + tensor: torch.Tensor, + device: torch.device, + original_size: list[int] | None = None, + original_stride: list[int] | None = None, +) -> torch.Tensor: + """Async reload a CPU tensor to GPU on the dedicated transfer stream. + + The GPU tensor is allocated on the compute stream to avoid cross-stream + allocator ownership issues. The H2D copy runs on the transfer stream. + The completion event is keyed by the output tensor's data_ptr. + + ``original_size`` and ``original_stride`` restore the GPU tensor's + original layout (which may be non-contiguous, e.g. from transpose). + When None, the tensor's own size/stride are used. + """ + size = original_size if original_size is not None else list(tensor.shape) + stride = original_stride if original_stride is not None else list(tensor.stride()) + transfer_stream = _get_or_create_transfer_stream(device) + current_stream = torch.accelerator.current_stream(device) + + result = torch.empty_strided(size, stride, dtype=tensor.dtype, device=device) + completion_event = _register_wait(result, device) + + transfer_stream.wait_stream(current_stream) + + torch.accelerator.set_stream(transfer_stream) + result.copy_(tensor, non_blocking=True) + transfer_stream.record_event(completion_event) + torch.accelerator.set_stream(current_stream) + + return result + + +@reload.register_fake +def _( + tensor: torch.Tensor, + device: torch.device, + original_size: list[int] | None = None, + original_stride: list[int] | None = None, +) -> torch.Tensor: + size = original_size if original_size is not None else list(tensor.shape) + stride = original_stride if original_stride is not None else list(tensor.stride()) + return torch.empty_strided(size, stride, dtype=tensor.dtype, device=device) + + +# ao::wait_tensor is defined via torch.library with an aliasing schema so the +# output can alias the input (custom_op forbids this). +# +# Uses CompositeExplicitAutograd (single impl for all devices) because the +# offload case has mixed-device args: ``tensor`` is CPU (the offload result) +# while ``keepalive`` is CUDA (the source GPU tensor). A single impl avoids +# relying on device-priority dispatch ordering. +# +# Synchronization details (completion event, device) are looked up from +# ``_wait_registry`` keyed on ``tensor.data_ptr()``. +# +# ``keepalive`` is the source tensor of the async transfer. It creates a +# graph dependency that extends the source tensor's lifetime until the +# compute stream has waited on the transfer completion event. After the +# wait, the op frees the source tensor's storage via ``resize_(0)`` since +# it is no longer needed: +# - Offload (D2H): keepalive is the GPU tensor; freed after the D2H copy. +# - Reload (H2D): keepalive is the CPU tensor; freed after the H2D copy. +# +# ``last_use_of_storage`` is an optional tensor whose storage is shared with +# other live tensors (views/aliases). Passing it here tells the scheduler +# that this wait_tensor call is the last consumer of that storage, creating +# a data dependency edge that prevents the storage from being freed or +# reused before the async transfer completes. This is needed when the +# storage is not otherwise kept alive by a direct data-flow edge in the +# graph -- without it, a compiler pass could schedule a storage-freeing op +# before the transfer finishes. +_lib = torch.library.Library("ao", "DEF") +_lib.define( + "wait_tensor(Tensor(a) tensor, Tensor? keepalive=None, Tensor? last_use_of_storage=None) -> Tensor(a)" +) + + +@torch.library.impl("ao::wait_tensor", "CompositeExplicitAutograd") +def _ao_wait_tensor( + tensor: torch.Tensor, + keepalive: torch.Tensor | None = None, + last_use_of_storage: torch.Tensor | None = None, +) -> torch.Tensor: + completion_event, device = _pop_wait(tensor) + current_stream = torch.accelerator.current_stream(device) + + current_stream.wait_event(completion_event) + if keepalive is not None: + if keepalive.is_pinned(): + # Return CPU pinned buffer to pool for reuse + _pool_free(keepalive.view(-1)) + else: + storage = keepalive.untyped_storage() + if storage.size() > 0: + storage.resize_(0) + return tensor + + +@torch.library.register_fake("ao::wait_tensor") +def _ao_wait_tensor_fake( + tensor: torch.Tensor, + keepalive: torch.Tensor | None = None, + last_use_of_storage: torch.Tensor | None = None, +) -> torch.Tensor: + return tensor + + +has_side_effect(torch.ops.ao.wait_tensor.default) + + +def wait_tensor( + tensor: torch.Tensor, + keepalive: torch.Tensor | None = None, + last_use_of_storage: torch.Tensor | None = None, +) -> torch.Tensor: + """Callable wrapper so ``wait_tensor`` can be imported by name for op registration.""" + return torch.ops.ao.wait_tensor.default(tensor, keepalive, last_use_of_storage) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__init__.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..618e33bb59fa701fe124eae0cd2d498ad3f7ce89 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/aot_autograd_result.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/aot_autograd_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..496248921fbfc60c9f363277d4a1f964d9d9a672 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/aot_autograd_result.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/autograd_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/autograd_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d5be85ca58dea2212ab37e89eb9a0f9361f978b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/autograd_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e1381a5514e8383ae3c183f82c4ffc2e45e7ca7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/collect_metadata_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/collect_metadata_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..583ac728f1da15197b18c9960c3dd90a9f7e7744 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/collect_metadata_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/complex_decomposition.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/complex_decomposition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c78d58fe686d89324961efafd520e36193f01ba Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/complex_decomposition.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/descriptors.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/descriptors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c78c3e2520bf4c5b57fadd225e6c40d60d41b4c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/descriptors.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/frontend_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/frontend_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fc9a399e2612bbaa16abc0e9e80ae3120950333 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/frontend_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/functional_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/functional_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56f3db9a739743228298aec87ba6813be1649ee2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/functional_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/fx_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/fx_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..374ecee0a1305388eb06ecf37c47c4049f0661f6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/fx_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..243500d21fffa15830a29365e30fd42ca6eb0ff2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture_wrappers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture_wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3bb923dc47c8b89db08057c6da8a42006468bcf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture_wrappers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cef8cd8fd7d39fe270c61bbf19e3b26f99a11055 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/indexed_dict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/indexed_dict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3d32130dc0b0c065820b8d66167fcaab86df3e0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/indexed_dict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/input_output_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/input_output_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be33fa2be50b092d4cc315a18ded2971d362e9df Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/input_output_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/logging_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/logging_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a37a34f6a2bb1a0ea261b73574247279fb72fdc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/logging_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce6b7e0de5cb7d7bdc8c5b37c39086e25675381c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77e31e07a704815bcd165b9bdcb11cb5c2a4ba4c528f64ff091fc342a28649c6 +size 156248 diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/schemas.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/schemas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a080a59dd19946b746e9eebcc42913f55b406be Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/schemas.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/source_emit.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/source_emit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5a1e7234d2c753e97d52c4e07ede235fa2e3679 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/source_emit.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/standalone_runtime.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/standalone_runtime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d91f76b5dcb7c461e968b5f38d96389e2969ef8c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/standalone_runtime.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/streams.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/streams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41783d24802700eb21ed6f657de8d651d8a1e8b9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/streams.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43aea8bf9c692aaf15af8cc70aaeff844dcf4ecb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_parametrization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_parametrization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9bf987de106dcb9dfb237364dd2fae033ad9022 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_parametrization.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2f727aab9b99c70a7fb461864a998cfb871b817 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/to_standalone_python.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/to_standalone_python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..222854567a21cc402cb6ad87ee44e07260e2c49c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/to_standalone_python.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd00971e473b55c95a778d3c8859f0f118b39137 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/aot_autograd_result.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/aot_autograd_result.py new file mode 100644 index 0000000000000000000000000000000000000000..eeff74fc596fef55dcaf2a28d769a67dcc0212a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/aot_autograd_result.py @@ -0,0 +1,756 @@ +""" +This module provides result classes for AOT Autograd compilation. + +Similar to how torch._inductor.output_code provides OutputCode classes for inductor +compilation results, this module provides AOTAutogradResult classes that represent +the compiled artifacts produced by AOT Autograd. + +These results are: +- Serializable: can be saved/loaded from disk without recompilation +- Addressable: can be stored in caches with keys for later retrieval +- Reusable: can be used for both caching and ahead-of-time compilation (precompile) + +The main result types are: +- GenericAOTAutogradResult: Abstract base for all AOT Autograd results +- AOTAutogradResult: Regular result that references FxGraphCache entries +- BundledAOTAutogradResult: Result that bundles the entire compiled code directly +""" + +from __future__ import annotations + +import json +import logging +from abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from copy import copy +from dataclasses import dataclass +from typing import Any, cast, Generic, TYPE_CHECKING, TypeVar + +import torch +from torch._dynamo.precompile_context import BackendCacheArtifact +from torch._inductor.codecache import FxGraphCache +from torch._inductor.output_code import ( + CompiledFxGraph, + CompiledFxGraphConstants, + OutputCode, +) +from torch._inductor.utils import should_use_remote_fx_graph_cache +from torch._logging import getArtifactLogger + +from .runtime_wrappers import ( + AOTDispatchAutograd, + AOTDispatchAutogradCompileSpec, + AOTDispatchSubclassWrapper, + CachedAutogradLazyBackwardCompileInfo, + CompilerWrapper, + FunctionalizedRngRuntimeWrapper, + post_compile, + RuntimeWrapper, + SerializableCompiledFunction, + SubclassMeta, +) +from .schemas import AOTAutogradCacheInfo, AOTConfig # noqa: F401 +from .utils import simple_wraps + + +if TYPE_CHECKING: + from torch._inductor.compile_fx import _CompileFxKwargs + + from .schemas import CacheableAOTConfig, ViewAndMutationMeta + +log = logging.getLogger(__name__) +aot_graphs_log = getArtifactLogger(__name__, "aot_graphs") + + +TOut = TypeVar("TOut", bound=OutputCode) + + +class InductorOutput(ABC, Generic[TOut]): + """ + Class representing a single inductor output + """ + + @abstractmethod + def pre_save(self) -> None: ... + + @abstractmethod + def load(self, example_inputs: Sequence[Any]) -> TOut: ... + + @abstractmethod + def post_compile(self, result: TOut, fx_config: _CompileFxKwargs) -> TOut: ... + + +TOutputCode = TypeVar("TOutputCode", bound=OutputCode) + + +@dataclass +class BundledOutputCodeLoadable(InductorOutput[TOutputCode], Generic[TOutputCode]): + """ + A generic wrapper for OutputCode objects that are bundled directly in the cache + (rather than looked up via FxGraphCache). + + This works for any OutputCode subclass (CompiledFxGraph, RegionalOutputCode, etc.) + """ + + result: TOutputCode + + def pre_save(self) -> None: + disk_result = copy(self.result) + disk_result.prepare_for_serialization() + self.result = disk_result + return + + def load(self, example_inputs: Sequence[Any]) -> TOutputCode: + self.example_inputs = example_inputs + return self.result + + def post_compile( + self, result: TOutputCode, fx_config: _CompileFxKwargs + ) -> TOutputCode: + constants = CompiledFxGraphConstants() + + # Special handling for CompiledFxGraph - needs FxGraphCache.cache_hit_post_compile + if isinstance(result, CompiledFxGraph): + graph, cache_info = FxGraphCache.cache_hit_post_compile( + result, {}, constants + ) + if graph is None: + raise RuntimeError("Failed to reload cache entry from disk") + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_graph_bundled_cache_hit", # always a hit + "encoding": "json", + }, + payload_fn=lambda: json.dumps(cache_info), + ) + result = graph # type: ignore[assignment] + result.compile_region_name = ( # pyrefly: ignore[missing-attribute] + fx_config.get("compile_region_name") + ) + + # Run normal post compile + result.post_compile(self.example_inputs, constants, fx_config) + + # Let the CUDAGraph policy do outer-level wrapping (e.g. wrapping + # an entire RegionalOutputCode as a single CUDA graph instead of + # per-inner-region). + import torch._inductor.config as _inductor_config + + policy = _inductor_config.cudagraph_policy + if policy is not None: + result = policy.wrap_output(result) + + return result + + +# Backwards compatibility alias +CompiledFxGraphLoadable: type[BundledOutputCodeLoadable[CompiledFxGraph]] = ( + BundledOutputCodeLoadable[CompiledFxGraph] +) + + +@dataclass +class FxGraphCacheLoadable(InductorOutput[CompiledFxGraph]): + fx_graph_cache_info: tuple[str, list[str]] + fx_graph_guard_expr: str | None + + def pre_save(self) -> None: + return + + def _is_backward(self) -> bool: + return False + + def load(self, example_inputs: Sequence[Any]) -> CompiledFxGraph: + from .autograd_cache import FXGraphCacheMiss + + # [Note: AOTAutogradCache and FXGraphCache Guard interactions] + # As mentioned, AOTAutograd takes in the symint inputs from dynamo's list of arguments. + # FXGraphCache serializes guards that are needed in the shape_env based on these symint inputs to the graph. + # The invariant that AOTAutograd uses here is that the sources for symints given to it by dynamo are exactly + # the same as the ones it passes to inductor, for both the forward and backward passes. + # (This does not mean that the tensor values passed in are the same: only that their symints are). + # That is, AOTAutograd and Inductor never create new guards based on symints with different sources + # than those passed to it by inductor. + # We pass the post compile function, which sets various fx_config boxed values, + # so we can call it only after we're sure both forward and backward have + # Clear CompiledTritonKernels before loading from FXGraphCache + torch._inductor.async_compile.CompiledTritonKernels.cache_clear() + remote_cache = None + constants = CompiledFxGraphConstants() + if should_use_remote_fx_graph_cache(): + remote_cache = FxGraphCache.get_remote_cache() + (cache_key, debug_lines) = self.fx_graph_cache_info + + def check_exact_guard_match(guard_expr: str, _hints: Any) -> bool: + """ + AOTAutogradCache tracks its own guards, so we just need to treat these guard expressions as a second + cache key of sorts: we just check for equality, i.e. the FXGraphCache entry with + the exact same guards as we originally saved into the cache. + """ + return guard_expr == self.fx_graph_guard_expr + + result, cache_info = FxGraphCache.load_with_key( + cache_key, + debug_lines, + example_inputs, + local=True, + remote_cache=remote_cache, + is_backward=self._is_backward(), + constants=constants, + evaluate_guards=check_exact_guard_match, + ) + if result is None: + log.info("FXGraphCache cache miss for key %s", self.fx_graph_cache_info) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_graph_cache_miss", # always a hit + "encoding": "json", + }, + payload_fn=lambda: json.dumps(cache_info), + ) + + raise FXGraphCacheMiss + + # No need to log chromium event because AOTAutograd will log that immediately for us + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_graph_cache_hit", # always a hit + "encoding": "json", + }, + payload_fn=lambda: json.dumps(cache_info), + ) + self.example_inputs = example_inputs + self.constants = constants + return result + + def post_compile( + self, result: CompiledFxGraph, fx_config: _CompileFxKwargs + ) -> CompiledFxGraph: + """ + Called after FXGraphCacheLoadable.load, mutates fx_config + """ + result.compile_region_name = fx_config.get( # pyrefly: ignore[bad-assignment] + "compile_region_name" + ) + result.post_compile(self.example_inputs, self.constants, fx_config) + + import torch._inductor.config as _inductor_config + + policy = _inductor_config.cudagraph_policy + if policy is not None: + result = policy.wrap_output(result) + + return result + + +@dataclass +class CompiledForward(FxGraphCacheLoadable): + """ + Cacheable entry for a forward function + """ + + def _is_backward(self) -> bool: + return False + + +@dataclass +class GenericCompiledBackward(InductorOutput[TOut]): + # Used by AOTDispatchAutograd.post_compile + backward_state_indices: list[int] + num_symints_saved_for_bw_: int + + def post_compile(self, result: TOut, fx_config: _CompileFxKwargs) -> TOut: + # The concrete post_compile comes from the loadable mixin in each subclass MRO. + compiled_bw = super().post_compile( # pyrefly: ignore[missing-attribute] + result, fx_config + ) + # See note [Wrapping bw_compiler in disable] + # This is done by _wrapped_bw_compiler in torch/_dynamo/backends/common.py + # But since on cache hit we do not call the bw_compiler, we need to reapply the disable + return torch._dynamo.disable( # type: ignore[return-value] + compiled_bw, reason="do not trace generated backwards pass" + ) + + +@dataclass +class CompiledBackward(GenericCompiledBackward[CompiledFxGraph], FxGraphCacheLoadable): + """ + Cacheable entry for a backward function + """ + + def _is_backward(self) -> bool: + return True + + +# Generic bundled forward/backward classes that work with any OutputCode type +@dataclass +class BundledCompiledForward( + BundledOutputCodeLoadable[TOutputCode], Generic[TOutputCode] +): + """ + Generic forward function for bundled compilation. + Works with any OutputCode type (CompiledFxGraph, RegionalOutputCode, etc.) + """ + + +@dataclass +class BundledCompiledBackward( + GenericCompiledBackward[TOutputCode], + BundledOutputCodeLoadable[TOutputCode], + Generic[TOutputCode], +): + """ + Generic backward function for bundled compilation. + Works with any OutputCode type (CompiledFxGraph, RegionalOutputCode, etc.) + """ + + +@dataclass +class SerializedGraphModule: + fn: Callable[[dict[Any, Any], str], torch.nn.Module] + args: tuple[Any, ...] + + def __init__(self, gm: torch.fx.GraphModule) -> None: + self.fn, self.args = gm.__reduce__() + + def deserialize(self) -> torch.fx.GraphModule: + gm = self.fn(*self.args) + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"expected fx.GraphModule, got {type(gm)}") + return gm + + +def serialize_graph_module(gm: torch.fx.GraphModule) -> SerializedGraphModule: + # NOTE: mutates the graph module + gm.meta = {} + for node in gm.graph.nodes: + # pyrefly: ignore [implicit-any] + node.meta = {} + return SerializedGraphModule(gm) + + +TForward = TypeVar("TForward", bound="InductorOutput[Any]") +TBackward = TypeVar("TBackward", bound="GenericCompiledBackward[Any]") + + +@dataclass +class GenericAOTAutogradResult(Generic[TForward, TBackward]): + """A single result from AOT Autograd compilation, genericized by Forward and Backward types. + + A TForward is always an InductorOutput of some sort, which represents the + forward graph of the compile. + A TBackward is an InductorOutput + metadata about the backward, useful for specific + backward-only wrappers. This type is encapsulated by GenericCompiledBackward. + + Each AOTAutogradResult is essentially parameterized by 1. the method of loading + from the cache (either Bundled or UnBundled), and 2. The type of the output. For now, + the only type of output we support is Python Wrapper output, i.e. OutputCode.CompiledFxGraph, + but the same technique works for C++ wrapper code; we'd just add an extra InductorOutput type. + """ + + # Forward and Backward info + compiled_fw: TForward + compiled_bw: TBackward | None + + # Code of the joint graph using print_readable() + # Used for logging purposes + aot_joint_graph_str: str | None + aot_forward_graph_str: str | None + aot_backward_graph_str: str | None + min_cut_info_str: str | None + + # Runtime_metadata saved right before compilation + runtime_metadata: ViewAndMutationMeta + + # Wrappers that run after each aot_dispatch_* function + dispatch_wrappers: list[CompilerWrapper] + + # Used by AOTSubclassWrapper + maybe_subclass_meta: SubclassMeta | None + num_fw_outs_saved_for_bw: int | None + + # Used by RuntimeWrapper + indices_of_inps_to_detach: list[int] + + # Time taken to trace/compile the forward + # forward_time_taken includes AOTAutograd tracing time + inductor compilation time + # backward_time_taken is essentially just the time inductor took to compile + forward_time_taken_ns: int + backward_time_taken_ns: int + + # Used by standalone_compile + sanitized_aot_config: CacheableAOTConfig + + guards_expr: str | None + + # Used by Compiled Autograd + serialized_bw_module: SerializedGraphModule | None + + def pre_save(self) -> None: + """ + Perform any preparations to make the result ready for serialization. + """ + self.compiled_fw.pre_save() + if self.compiled_bw is not None: + self.compiled_bw.pre_save() + + def _log_cached_graphs(self, aot_config: AOTConfig | CacheableAOTConfig) -> None: + if not aot_config.enable_log: + return + + if self.aot_joint_graph_str is not None: + torch._logging.trace_structured( + "aot_joint_graph", payload_fn=lambda: self.aot_joint_graph_str + ) + aot_graphs_log.info( + "Joint graph (from cache)\n\n%s", self.aot_joint_graph_str + ) + + if self.aot_forward_graph_str is not None: + from torchgen.utils import dataclass_repr + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(self.runtime_metadata), + ) + if self.maybe_subclass_meta is not None: + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_subclass_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(self.maybe_subclass_meta), + ) + + # It's called an inference graph if not running with autograd + has_backward = self.aot_backward_graph_str is not None + torch._logging.trace_structured( + "aot_forward_graph" if has_backward else "aot_inference_graph", + payload_fn=lambda: self.aot_forward_graph_str, + ) + aot_graphs_log.info( + "Forward graph (from cache)\n\n%s", + self.aot_forward_graph_str, + ) + + if self.aot_backward_graph_str is not None: + torch._logging.trace_structured( + "aot_backward_graph", payload_fn=lambda: self.aot_backward_graph_str + ) + aot_graphs_log.info( + "Backward graph (from cache)\n\n%s", + self.aot_backward_graph_str, + ) + + if self.min_cut_info_str is not None: + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "min_cut_information", + "encoding": "json", + }, + payload_fn=lambda: self.min_cut_info_str, + ) + + def _load_and_post_compile( + self, + args: list[torch.Tensor], + fx_config: _CompileFxKwargs, + ) -> tuple[Callable[..., Any], Callable[..., Any] | None, bool]: + from torch._dynamo.utils import CompileEventLogger + + compiled_fw_func = self.compiled_fw.load(args) + if self.compiled_bw is not None: + compiled_bw_func = self.compiled_bw.load(args) + needs_autograd = True + CompileEventLogger.try_add_pt2_compile( + "backend_compile", dispatch_mode="autograd" + ) + # Now that we've loaded forward and backward, call post compile on both + # This avoids setting things like BoxedBools in fx_config until + # after both forward and backward cache hit + fw_fx_config: _CompileFxKwargs = { + **fx_config, + "is_backward": False, + } + bw_fx_config: _CompileFxKwargs = { + **fx_config, + "is_backward": True, + } + compiled_fw_func = self.compiled_fw.post_compile( + compiled_fw_func, fw_fx_config + ) + compiled_bw_func = self.compiled_bw.post_compile( + compiled_bw_func, bw_fx_config + ) + return compiled_fw_func, compiled_bw_func, needs_autograd + + inference_fx_config: _CompileFxKwargs = { + **fx_config, + "is_backward": False, + } + + needs_autograd = False + CompileEventLogger.try_add_pt2_compile( + "backend_compile", dispatch_mode="inference" + ) + compiled_fw_func = self.compiled_fw.post_compile( + compiled_fw_func, inference_fx_config + ) + return compiled_fw_func, None, needs_autograd + + def _apply_runtime_wrappers( + self, + compiled_fw_func: Callable[..., Any], + compiled_bw_func: Callable[..., Any] | None, + needs_autograd: bool, + aot_config: AOTConfig, + ) -> Callable[..., Any]: + from torch._dynamo.utils import CompileEventLogger + + compiled_fw_func = AOTDispatchSubclassWrapper( + trace_joint=needs_autograd, + fw_only=None, + maybe_subclass_meta=self.maybe_subclass_meta, + num_fw_outs_saved_for_bw=self.num_fw_outs_saved_for_bw, + ).post_compile( + compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata + ) + + req_subclass_dispatch = self.maybe_subclass_meta is not None + CompileEventLogger.try_add_pt2_compile( + "backend_compile", requires_subclass_dispatch=req_subclass_dispatch + ) + + # In autograd case, functionalizedRngWrapper should not modify outs + return_new_outs = not needs_autograd + compiled_fw_func = FunctionalizedRngRuntimeWrapper( + return_new_outs=return_new_outs + ).post_compile( + compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata + ) + # pyrefly: ignore [missing-attribute] + compiled_fw_func._boxed_call = True + disable_amp = torch._C._is_any_autocast_enabled() + + if needs_autograd: + if self.compiled_bw is None: + raise AssertionError("compiled_bw must not be None when needs_autograd") + + cached_lazy_backward = None + if self.serialized_bw_module is not None: + cached_lazy_backward = CachedAutogradLazyBackwardCompileInfo( + self.serialized_bw_module.deserialize + ) + # This function is run on both cache miss and cache hit, either here + # or in aot_dispatch_autograd. On a cache hit, + # 1. the bw is already compiled + # 2. we don't need to save to the cache again + # so those corresponding arguments are set to None. + compile_spec = AOTDispatchAutogradCompileSpec( + compiled_fw_func=compiled_fw_func, + compiled_bw_func=compiled_bw_func, + maybe_subclass_meta=self.maybe_subclass_meta, + num_symints_saved_for_bw=self.compiled_bw.num_symints_saved_for_bw_, + backward_state_indices=self.compiled_bw.backward_state_indices, + disable_amp=disable_amp, + indices_of_inps_to_detach=self.indices_of_inps_to_detach, + lazy_backward_info=cached_lazy_backward, + bw_compiler=None, + aot_config=aot_config, + fw_metadata=self.runtime_metadata, + try_save_cache_entry=None, + ) + compiled_function = AOTDispatchAutograd.post_compile(compile_spec) + + else: + compiled_function = RuntimeWrapper( + indices_of_inps_to_detach=self.indices_of_inps_to_detach, + trace_joint=False, + disable_amp=disable_amp, + ).post_compile( + compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata + ) + + # Add serialization function back onto object + compiled_function, _ = post_compile( + self.dispatch_wrappers, + compiled_function, + aot_config, + runtime_metadata=self.runtime_metadata, + ) + return compiled_function + + def _check_guards(self, args: list[torch.Tensor]) -> None: + if self.guards_expr: + from .autograd_cache import AOTAutogradCache + + symints = AOTAutogradCache._filter_backed_symints(args) + check = bool(AOTAutogradCache.evaluate_guards(self.guards_expr, symints)) + if check is not True: + raise AssertionError(f"guards check failed: {check}") + + # Turn result into the original callable + def wrap_post_compile( + self, + args: list[torch.Tensor], + aot_config: AOTConfig | CacheableAOTConfig, + fx_config: _CompileFxKwargs, + ) -> Callable[..., Any]: + """ + This function takes a result and carefully reconstructs the original callable + that AOTAutograd returned the first time it was run. It does this by running the various + post compile steps that AOTAutograd runs on its compiled artifact after running the fw/bw compilers. + + In the inference path, this consists of the Subclass, FunctionalzedRngRuntime, and RuntimeWrappers. + In the autograd path, this consists of AOTAutogradDispatch.post_compile. + + The steps here should match exactly the steps that are run in aot_dispatch_base and aot_dispatch_autograd. + + Notably absent from the cached path are: + - DebugAssertWrapper + - FakifiedOutWrapper + + Which we'll handle separately later on, if necessary. + """ + from torch._dynamo.utils import dynamo_timed + + self._log_cached_graphs(aot_config) + # Cache hits only retain the cacheable subset of AOTConfig. Narrow once + # here so the existing post-compile wrapper stack can keep its compile-time + # AOTConfig annotations. + runtime_aot_config = cast(AOTConfig, aot_config) + with dynamo_timed("AOTAutogradCache.inductor_load"): + compiled_fw_func, compiled_bw_func, needs_autograd = ( + self._load_and_post_compile(args, fx_config) + ) + + compiled_function = self._apply_runtime_wrappers( + compiled_fw_func, + compiled_bw_func, + needs_autograd, + runtime_aot_config, + ) + # Now that we're pretty sure it's a successful load, add guards + # to the existing shape environment from the cache. + self._check_guards(args) + return compiled_function + + +class AOTAutogradResult(GenericAOTAutogradResult[CompiledForward, CompiledBackward]): + """ + Regular AOTAutogradResult: saves the forward/backward FxGraphCache keys + and looks them up in FxGraphCache on load + """ + + +class BundledAOTAutogradResult( + GenericAOTAutogradResult[ + BundledCompiledForward[TOutputCode], BundledCompiledBackward[TOutputCode] + ], + Generic[TOutputCode], +): + """ + Generic AOTAutogradResult where we bundle the entire OutputCode directly + (rather than looking it up via FxGraphCache). + + This works with any OutputCode type: + - CompiledFxGraph: Traditional inductor compilation + - RegionalOutputCode: Regional inductor compilation with GraphPickler serialization + - Any future OutputCode subclasses + + Type parameter: + TOutputCode: The OutputCode subclass (e.g., CompiledFxGraph, RegionalOutputCode) + + Usage with CompiledFxGraph: + entry = BundledAOTAutogradResult[CompiledFxGraph]( + compiled_fw=BundledCompiledForward(result=CompiledFxGraph(...)), + compiled_bw=BundledCompiledBackward( + result=CompiledFxGraph(...), + backward_state_indices=[...], + num_symints_saved_for_bw_=..., + ), + ... + ) + + Usage with RegionalOutputCode: + entry = BundledAOTAutogradResult[RegionalOutputCode]( + compiled_fw=BundledCompiledForward(result=RegionalOutputCode(gm)), + compiled_bw=BundledCompiledBackward( + result=RegionalOutputCode(gm), + backward_state_indices=[...], + num_symints_saved_for_bw_=..., + ), + ... + ) + """ + + +def deserialize_bundled_cache_entry( + entry: BundledAOTAutogradResult[Any], +) -> Callable[..., Any]: + from copy import deepcopy + + from torch._inductor.cudagraph_utils import BoxedDeviceIndex + from torch._inductor.utils import BoxedBool + + # In the precompile use case, guards are already serialized + # by dynamo, so we don't need to add them to the environment + entry.guards_expr = None + # TODO: this isn't exactly right, because cudagraphs needs to be a shared config + # which is set by compile_fx. But in precompile, we never actually call compile_fx + # so we don't have a place to track cudagraphs here. + cudagraphs = BoxedBool(torch._inductor.config.triton.cudagraphs) + boxed_forward_device_index = BoxedDeviceIndex(None) + # We need to make a clean copy of the cache entry + # in case it needs to be serialized again + serializable_copy = deepcopy(entry) + + from torch._subclasses import FakeTensorMode + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + context = torch._guards.TracingContext.try_get() + if context is None: + # Create a clean environment when running fx graph post compile + # if one is not available + context = torch._guards.TracingContext(FakeTensorMode(shape_env=ShapeEnv())) + with torch._guards.tracing(context): + compiled_fn = entry.wrap_post_compile( + [], + entry.sanitized_aot_config, + { + "cudagraphs": cudagraphs, + "boxed_forward_device_index": boxed_forward_device_index, + }, + ) + # Ensure the deserialized cache entry is still serializable + + compiled_fn = SerializableCompiledFunction(compiled_fn, lambda: serializable_copy) + + # TODO: this ignores flat_params, which can exist + # if inline_builtin_nn_modules=False + @simple_wraps(compiled_fn) + def forward(*runtime_args: Any) -> Any: + return compiled_fn(list(runtime_args)) + + if not hasattr(compiled_fn, "serialize"): + raise AssertionError("compiled_fn must have serialize attribute") + forward.serialize = compiled_fn.serialize # type: ignore[attr-defined] + + return forward + + +@dataclass +# pyrefly: ignore [implicit-any] +class BundledAOTAutogradCacheArtifact(BackendCacheArtifact[Callable]): + # pyrefly: ignore [implicit-any] + def after_deserialization(self) -> Callable: + return deserialize_bundled_cache_entry(self.content) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/autograd_cache.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/autograd_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..652fa39cb453c0fe828b539669a4041b630717f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/autograd_cache.py @@ -0,0 +1,1584 @@ +""" +Utils for caching the outputs of AOTAutograd +""" + +from __future__ import annotations + +import base64 +import contextlib +import dataclasses +import functools +import hashlib +import json +import logging +import os +import pickle +import random +import shutil +import time +import traceback +from copy import copy +from typing import Any, TYPE_CHECKING +from typing_extensions import override + +import torch +from torch._dynamo.precompile_context import PrecompileContext +from torch._dynamo.trace_rules import torch_non_c_binding_in_graph_functions +from torch._dynamo.utils import ( + chromium_event_log_active, + CompileEventLogger, + counters, + is_safe_numpy_wrapper, + numpy_wrapper_cache_key, + warn_once, +) +from torch._functorch import config +from torch._inductor.codecache import ( + _ident, + add_ephemeral_timeout_increase_for_distributed, + AOTAUTOGRAD_CACHE_PREFIX, + BypassFxGraphCache, + create_cache, + extract_tensor_metadata_for_cache_key, + FxGraphCache, + FxGraphCachePickler, + FxGraphHashDetails, + GuardedCache, + sha256_hash, + write_atomic, +) +from torch._inductor.custom_graph_pass import ( + CustomKnapsackSolver, + CustomRuntimeEstimator, +) +from torch._inductor.output_code import OutputCode +from torch._inductor.remote_cache import cache_stats +from torch._inductor.runtime.runtime_utils import cache_dir +from torch._inductor.utils import BoxedBool, should_use_remote_fx_graph_cache +from torch._library.fake_class_registry import FakeScriptObject +from torch._logging import LazyString +from torch._utils_internal import log_cache_bypass +from torch.compiler._cache import ( + CacheArtifact, + CacheArtifactFactory, + CacheArtifactRecorder, +) +from torch.fx.experimental.symbolic_shapes import guarding_hint_or_throw +from torch.fx.node import Node +from torch.fx.traceback import _get_memory_budget_annotation +from torch.utils._triton import has_triton_package + +from .aot_autograd_result import ( + AOTAutogradResult, + BundledAOTAutogradCacheArtifact, + BundledAOTAutogradResult, + BundledCompiledBackward, + BundledCompiledForward, + CompiledBackward, + CompiledForward, + GenericAOTAutogradResult, + SerializedGraphModule, +) +from .runtime_wrappers import ( + CompilerWrapper, + SerializableCompiledFunction, + SubclassMeta, +) +from .schemas import ( + ActInputPaths, + AOTAutogradCacheInfo, + AOTConfig, + CacheableAOTConfig, + ViewAndMutationMeta, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Sequence + + from torch._inductor.compile_fx import _CompileFxKwargs, CompilerConfigExtra + from torch._inductor.remote_cache import JsonDataTy, RemoteCache + + +log = logging.getLogger(__name__) + + +class BypassAOTAutogradCache(Exception): + pass + + +# Used to signify when FXGraphCache missed when AOTAutogradCache uses it +class FXGraphCacheMiss(BypassAOTAutogradCache): + pass + + +def should_use_remote_autograd_cache() -> bool: + if torch.compiler.config.force_disable_caches: + return False + if config.enable_remote_autograd_cache is not None: + return config.enable_remote_autograd_cache + if not config.is_fbcode(): + return False + + if torch._utils_internal.is_fb_unit_test(): + return False + + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + except ModuleNotFoundError: + return False + + jk_name = "pytorch/remote_cache:aot_autograd_cache_version" + + return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int(jk_name) + + +def should_use_local_autograd_cache() -> bool: + if torch.compiler.config.force_disable_caches: + return False + return config.enable_autograd_cache + + +def should_bundle_autograd_cache() -> bool: + return config.bundled_autograd_cache or torch._dynamo.config.caching_precompile + + +def check_node_safe(node: Node) -> None: + """ + Checks that the node only uses supported operators. We are starting with very + conservative cacheability constraints, and incrementally adding more support as we expand. + + [Note: AOTAutograd Cacheability checks] + - Our cache key is computed from the FX graph produced by Dynamo and the input example values + - A node is "safe" if the same cache key results in a compiled artifact that has the same behavior + (i.e, the set of inputs that go into our cache key is sufficient to distinguish its behavior) + + To accomplish this safety check, we consider the following functions to be safe: + - Public functions under modules torch, torch.functional, and torch.nn.functional: these are + allowed in the graph by dynamo, so we can assume they are safe to cache. + - method calls on base tensor types + - Any call_module that dynamo deemed safe to allow AOTAutograd to trace + - Non callable nodes, such as placeholder, output, get_attr + + The test suite test_aot_autograd_cache.py::AOTAutogradCachePicklerTests tries its best to fully cover/specify this behavior. + """ + SAFE_TORCH_MODULES = ("torch.functional", "torch.nn.functional") + SAFE_TORCH_FUNCTIONS = ( + "torch.Size", + "torch.Tensor", + "torch.sym_int", + "torch._sym_sqrt", + "torch.sym_float", + "torch.sym_sum", + "torch.autograd.grad", + "torch.distributed.tensor._api.from_local", + # An autocast context manager *inside* a compiled region is traced into + # these calls. What they do is fully determined by their arguments + # (device type, dtype, enabled, cache_enabled), which are constants in + # the graph and therefore part of the cache key, so a graph compiled + # under one autocast setting can never be reused for another. + "torch.amp.autocast_mode._enter_autocast", + "torch.amp.autocast_mode._exit_autocast", + ) + SAFE_NON_TORCH_FUNCTIONS = ( + "einops.einops.rearrange", + "einops.einops.repeat", + ) + + def is_public_torch_api(target: Callable[..., Any]) -> bool: + # Don't blindly allow private functions in the torch namespace + is_private = target.__name__.startswith("_") + + return ( + getattr(target, "__module__", None) in SAFE_TORCH_MODULES and not is_private + ) + + def is_safe_torch_function(target: Callable[..., Any]) -> bool: + """Allowlisted torch functions""" + function_name = f"{target.__module__}.{target.__name__}" + # Allow torch.autograd.function.FunctionCtx if custom autograd functions are allowed + if function_name == "torch.autograd.function.FunctionCtx": + return ( + torch._functorch.config.autograd_cache_allow_custom_autograd_functions + ) + + # Functions in torch_non_c_binding_in_graph_functions + # are guaranteed to be cache safe. + # See NOTE: [Cacheability of in-graph torch functions] + return ( + function_name in torch_non_c_binding_in_graph_functions + or function_name in SAFE_TORCH_FUNCTIONS + or function_name in torch._inductor.config.unsafe_marked_cacheable_functions + ) + + def is_cacheable_function(target: Callable[..., Any]) -> bool: + if isinstance(target, (torch._ops.OpOverload, torch._ops.OpOverloadPacket)): + return True + if is_safe_numpy_wrapper(target): + return True + if is_public_torch_api(target): + return True + # Technically, FXGraphCache._check_for_hop already checks this, + # but better to error earlier anyway + if isinstance(target, torch._ops.HigherOrderOperator): + return target.cacheable() + is_builtin_fun_or_type = type(target).__name__ == "builtin_function_or_method" + if is_builtin_fun_or_type: + return True + if is_safe_torch_function(target): + return True + function_name = f"{target.__module__}.{target.__name__}" + if function_name in SAFE_NON_TORCH_FUNCTIONS: + return True + return False + + def is_tensor(target: Node) -> bool: + # Tensors always have example values in meta field + return "example_value" in target.meta + + # I'd love to use a match statement here, but it wasn't introduced until py3.10 + if node.op == "call_function": + if node.meta and node.meta.get("is_wrapped", False): + # This is fx.wrap function + # By default we BypassAOTAutogradCache for unknown functions, + # But if user explicitly specified cache hash - allow to cache it. + if node.meta.get("user_cache_hash", None): + return + if isinstance(node.target, str): + raise AssertionError( + f"expected node.target to not be a string, got {node.target}" + ) + if not is_cacheable_function(node.target): + module = getattr(node.target, "__module__", None) + name = getattr(node.target, "__name__", None) + raise BypassAOTAutogradCache( + f"Unsupported call_function target {node.target}. \n Function module: {module}, \nFunction name: {name}" + ) + elif node.op == "call_method": + method_name = node.target + method_target = node.args[0] + # Only support method calls on base tensors + if not isinstance(method_target, Node): + raise AssertionError( + f"expected method_target to be Node, got {type(method_target)}" + ) + if not is_tensor(method_target): + module = getattr(method_target, "__module__", None) + name = getattr(method_target, "__name__", None) + raise BypassAOTAutogradCache( + f"Unsupported call_method target {method_target}. \nMethod module: {module}, \nMethod name: {name}" + ) + if ( + type(method_name) is not str + and type(method_name).__name__ != "method_descriptor" + ): + raise BypassAOTAutogradCache( + f"Unsupported call_method method {node.target}: {method_name}" + ) + # Cache safe + elif node.op in ("placeholder", "get_attr", "call_module", "output"): + # Assumption today for call_module being a safe op: + # (1) today the only call_module ops that can show up in a graph come from "built-in-nn-modules" + # that dynamo assumes are safe to trace. If dynamo assumes they are safely to blindly trace, then + # they should be safe to cache as well. + # (2) in the steady-state (some time in H2?) we shouldn't see these anymore, once inline builtin nn modules by default + # (3) We do not allow user made nn modules in the graph today, only function calls. + pass + else: + raise BypassAOTAutogradCache(f"Unsupported node op {node.op}") + + +def check_cacheable(gm: torch.fx.GraphModule) -> None: + """ + Checks that the graph module only uses supported operators + """ + nodes = gm.graph.nodes + if torch._inductor.config.freezing: + raise BypassAOTAutogradCache("Cannot cache a graph with freezing enabled") + + if not ( + torch._inductor.config.fx_graph_cache or should_use_remote_fx_graph_cache() + ): + raise BypassAOTAutogradCache("FX graph cache is not enabled") + + tracing_context = torch._guards.TracingContext.try_get() + if tracing_context and tracing_context.fakify_first_call: + raise BypassAOTAutogradCache( + "Won't cache a graph with fakify_first_call enabled" + ) + for node in nodes: + check_node_safe(node) + + # Saved tensors hooks are globally set subgraphs, + # that are not used explicitly in the main graph. + # They are inlined in aot_autograd graphs. + # Subgraphs are only used for caching logic. + if hasattr(gm, "saved_tensors_hooks_pack_0"): + check_cacheable(gm.saved_tensors_hooks_pack_0) # type: ignore[arg-type] + # We have guarantee of unpack subgraph existence if pack subgraph exists + check_cacheable(gm.saved_tensors_hooks_unpack_0) # type: ignore[arg-type] + + +def _get_context_fn_cache_hash(context_fn: Callable[..., Any]) -> str | None: + """ + Extract a cache hash from a context_fn used for selective activation checkpointing (SAC). + + The context_fn determines which ops are saved vs recomputed in the SAC region. + Since context_fn can be an arbitrary Python function, we cannot reliably pickle + it for cache key generation (pickle only captures the function name, not the code). + + Users must provide a stable hash by setting a `cache_hash` attribute on the context_fn. + For functools.partial objects, set the cache_hash on the partial object itself, not on + the underlying function. + + Returns: + The cache hash if found + None: If no hash is provided (caller should bypass caching) + """ + if hasattr(context_fn, "cache_hash"): + return context_fn.cache_hash + + return None + + +def _iter_graph_modules( + gm: torch.fx.GraphModule, +) -> Generator[torch.fx.GraphModule, None, None]: + for module in gm.modules(): + if isinstance(module, torch.fx.GraphModule): + yield module + + +def _collect_context_fn_hashes(gm: torch.fx.GraphModule) -> list[str]: + """ + Collect cache hashes from all context_fn used in SAC HOPs within the graph module. + + Returns a list of hashes. Raises BypassAOTAutogradCache if any context_fn + lacks a cache_hash attribute. + """ + hashes = [] + for module in _iter_graph_modules(gm): + context_fn = module.meta.get("_checkpoint_context_fn") + if context_fn is not None: + cache_hash = _get_context_fn_cache_hash(context_fn) + if cache_hash is None: + raise BypassAOTAutogradCache( + "SAC context_fn does not have a cache_hash attribute. " + "To enable caching with selective activation checkpointing, " + "add a 'cache_hash' attribute to your context_fn. This can be " + "a string or any hashable value that uniquely identifies the checkpointing " + "behavior (e.g., based on source code hash and closed-over globals). " + "For functools.partial objects, set cache_hash on the partial itself." + ) + hashes.append(cache_hash) + return hashes + + +def _collect_wrapped_user_cache_hashes(gm: torch.fx.GraphModule) -> list[str]: + wrapped_user_cache_hashes = [] + for node in gm.graph.nodes: + if node.meta and node.meta.get("is_wrapped", False): + wrapped_user_cache_hashes.append(node.meta["user_cache_hash"]) + return wrapped_user_cache_hashes + + +def _collect_saved_tensors_hooks_fx_wrap_cache_hashes( + gm: torch.fx.GraphModule, +) -> tuple[list[str], list[str]]: + if not hasattr(gm, "saved_tensors_hooks_pack_0"): + return ([], []) + + return ( + _collect_wrapped_user_cache_hashes( + # pyrefly: ignore[bad-argument-type] + gm.saved_tensors_hooks_pack_0 + ), + _collect_wrapped_user_cache_hashes( + # pyrefly: ignore[bad-argument-type] + gm.saved_tensors_hooks_unpack_0 + ), + ) + + +def _get_custom_estimator_solver_uuids( + autograd_config: Any, +) -> tuple[object | None, object | None]: + """ + Extract uuid values from custom runtime estimator and solver configs if they have uuid() methods. + + Returns a tuple of (runtime_estimator_uuid, solver_uuid). + + Returns None for each component if: + - The config field value is None + - The config field value is a string (built-in option like "flops", "greedy") + + Raises BypassAOTAutogradCache if: + - The config field value is a raw callable without uuid() method (caching not supported) + - The CustomRuntimeEstimator/CustomKnapsackSolver's uuid() method returns None + (caching explicitly disabled by implementation) + """ + + runtime_estimator = getattr( + autograd_config, "activation_memory_budget_runtime_estimator", None + ) + solver = getattr(autograd_config, "activation_memory_budget_solver", None) + + runtime_estimator_uuid = None + solver_uuid = None + + if isinstance(runtime_estimator, CustomRuntimeEstimator): + runtime_estimator_uuid = runtime_estimator.uuid() + if runtime_estimator_uuid is None: + raise BypassAOTAutogradCache( + "CustomRuntimeEstimator.uuid() returned None, bypassing cache" + ) + elif callable(runtime_estimator) and not isinstance(runtime_estimator, str): + raise BypassAOTAutogradCache( + "activation_memory_budget_runtime_estimator is a raw callable without uuid() method, " + "bypassing cache. Use CustomRuntimeEstimator for cache support." + ) + + if isinstance(solver, CustomKnapsackSolver): + solver_uuid = solver.uuid() + if solver_uuid is None: + raise BypassAOTAutogradCache( + "CustomKnapsackSolver.uuid() returned None, bypassing cache" + ) + elif callable(solver) and not isinstance(solver, str): + raise BypassAOTAutogradCache( + "activation_memory_budget_solver is a raw callable without uuid() method, " + "bypassing cache. Use CustomKnapsackSolver for cache support." + ) + + return runtime_estimator_uuid, solver_uuid + + +class AOTAutogradCacheDetails(FxGraphHashDetails): + """ + Object to capture all the details for a dynamo graph module relevant to computing + a safe and stable cache key for AOTAutograd. + """ + + def _iter_triton_kernels_from_node(self, node: Node) -> Generator[Any, None, None]: + if isinstance(node.target, torch._ops.OpOverloadPacket): + for attr in node.target._dir: + custom_op = getattr(node.target, attr, None) + if custom_op is not None: + yield from torch._library.triton.get_triton_kernels_for_op( + custom_op._name + ) + return + if isinstance(node.target, torch._ops.OpOverload): + yield from torch._library.triton.get_triton_kernels_for_op( + node.target._name + ) + + def get_triton_source_codes_from_gm( + self, + gm: torch.fx.GraphModule, + ) -> list[str]: + if not has_triton_package(): + raise AssertionError("Triton is not available") + + triton_kernels = [] + for module in _iter_graph_modules(gm): + for node in module.graph.nodes: + triton_kernels.extend(self._iter_triton_kernels_from_node(node)) + + triton_kernel_source_codes = [] + from torch._inductor.codegen.wrapper import ( + user_defined_triton_kernel_transitive_closure_source_code, + ) + + for kernel in triton_kernels: + from triton.runtime.autotuner import Autotuner + + if isinstance(kernel, Autotuner): + # Grab the Inner JITFunction + kernel = kernel.fn + source_codes = user_defined_triton_kernel_transitive_closure_source_code( + kernel + ) + triton_kernel_source_codes.append(source_codes) + + return triton_kernel_source_codes + + def __init__( + self, + gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + aot_config: AOTConfig, + fx_config: _CompileFxKwargs, + act_input_paths: ActInputPaths = (), + ) -> None: + # FxGraphHashDetails contains all the keys related to inductor. Also + # includes some system info. + self.aot_config = aot_config + self.act_input_paths = tuple(act_input_paths) + self._record_runtime_state(gm) + self.saved_tensors_hooks_fx_wrap_cache_hashes = ( + _collect_saved_tensors_hooks_fx_wrap_cache_hashes(gm) + ) + self.sac_context_fn_hashes = _collect_context_fn_hashes(gm) + + # region_activation_memory_budget is graph-wide (the partitioner enforces + # a single value across the graph) and propagates to every node, so the + # cache key only needs the value off the first node. node.meta is stripped + # by GraphModule.__reduce__, so without recording it here a budget change + # would not invalidate the cache. + first_node = next(iter(gm.graph.nodes), None) + self.region_activation_memory_budget: float | None = ( + _get_memory_budget_annotation(first_node) + if first_node is not None + else None + ) + + # Note: We use the live config module, not self.autograd_config (the + # saved config), because activation_memory_budget_runtime_estimator and + # activation_memory_budget_solver are excluded from save_config (in + # _save_config_ignore) since they're not serializable. We must access the + # config module directly to get the patched runtime values. + self.custom_estimator_solver_uuids = _get_custom_estimator_solver_uuids(config) + self._init_fx_graph_hash_details(gm, example_inputs, fx_config) + + def _record_runtime_state(self, gm: torch.fx.GraphModule) -> None: + self.grad_enabled = torch.is_grad_enabled() + # Include per-device autocast dtype in cache key to avoid reusing + # a graph compiled for one autocast dtype (e.g. bfloat16) when + # running under a different autocast dtype (e.g. float16). + self.autocast_state: dict[str, torch.dtype] = {} + for device_type in torch._C._autocast_supported_devices(): + if torch.is_autocast_enabled(device_type): + self.autocast_state[device_type] = torch.get_autocast_dtype(device_type) + self.deterministic_algorithms = torch.are_deterministic_algorithms_enabled() + self.autograd_config = config.save_config() + if has_triton_package(): + self.triton_kernel_source_codes = self.get_triton_source_codes_from_gm(gm) + + def _init_fx_graph_hash_details( + self, + gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + fx_config: _CompileFxKwargs, + ) -> None: + try: + # FXGraphCache has constraints on what can be pickled in its inductor + # config. Check that the gm is cacheable by inductor first, + # and if it raises an exception, also bypass on our end. + FxGraphCache._check_can_cache(gm, example_inputs, fx_config) + super().__init__(gm, example_inputs, fx_config, []) + except BypassFxGraphCache as e: + # Sometimes inductor configs are unpickleable and can fail + raise BypassAOTAutogradCache(str(e)) from e + + +class AOTAutogradCachePickler(FxGraphCachePickler): + def __init__( + self, + gm: torch.fx.GraphModule, + symint_name_map: dict[str, str] | None = None, + graph_symint_names: set[str] | None = None, + ) -> None: + super().__init__(gm) + self._symint_name_map: dict[str, str] = symint_name_map or {} + self._graph_symint_names: set[str] = graph_symint_names or set() + # pyrefly: ignore[missing-attribute] + self.dispatch_table.update( + { + AOTConfig: functools.partial(self._reduce_aot_config), + torch.Tensor: functools.partial(self._reduce_tensor), + FakeScriptObject: functools.partial(self._reduce_fake_script_object), + } + ) + + def _reduce_symint( + self, s: torch.SymInt + ) -> tuple[Callable[..., Any], tuple[Any, ...]]: + name = str(s) + normalized = self._symint_name_map.get(name) + if normalized is not None: + if name in self._graph_symint_names: + return (_ident, (normalized,)) + # Non-graph SymInt with non-deterministic name (from MetaConverter). + # Include the hint to distinguish different specializations. + hint = s.node.hint + if hint is not None: + return (_ident, (normalized, hint)) + return (_ident, (name,)) + + # pyrefly: ignore [bad-override] + def reducer_override(self, obj: Any) -> Any: + """ + Override to handle tensor subclasses (like DTensor) that aren't caught + by the dispatch_table's exact type matching. + + The dispatch_table only matches exact types, so subclasses like DTensor + fall through to the default __reduce_ex__ which includes non-deterministic + storage addresses. This method catches those cases using isinstance checks. + """ + if isinstance(obj, torch.fx.GraphModule): + return self._reduce_graph_module_for_cache_key(obj) + if (numpy_key := numpy_wrapper_cache_key(obj)) is not None: + return (_ident, (numpy_key,)) + # Handle tensor subclasses that aren't exactly torch.Tensor + # dispatch_table already handles torch.Tensor exactly + if isinstance(obj, torch.Tensor) and type(obj) is not torch.Tensor: + return self._reduce_tensor_subclass(obj) + # Fall back to parent class reducer which handles unpicklable types + return super().reducer_override(obj) + + @staticmethod + def _format_global_for_cache_key(name: str, obj: Any) -> str: + if (numpy_key := numpy_wrapper_cache_key(obj)) is not None: + return f"# cache_key_numpy_wrapper {name}: {numpy_key!r}" + + from torch.fx.graph_module import _format_import_statement + from torch.package import sys_importer + + return _format_import_statement(name, obj, sys_importer) + + def _reduce_graph_module_for_cache_key( + self, gm: torch.fx.GraphModule + ) -> tuple[Callable[..., Any], tuple[Any, ...]]: + recompile = getattr(gm, "_real_recompile", gm.recompile) + python_code = recompile() + # FxGraphCache strips user-defined Triton side-table indices from + # Inductor wrapper code. This reducer handles arbitrary AOT GraphModule + # code, so keep the generated code exact and let AOTAutogradCacheDetails + # carry Triton source/constant-arg metadata separately. + dict_without_graph = gm.__dict__.copy() + dict_without_graph.pop("_graph", None) + + import_block = "\n".join( + sorted( + self._format_global_for_cache_key(name, obj) + for name, obj in python_code.globals.items() + ) + ) + return (_ident, ((dict_without_graph, import_block),)) + + # [NOTE] Tensor subclass stable hashing for AOT autograd cache + # Python's hash() varies with PYTHONHASHSEED, making cache keys unstable + # across processes. We use blake2b for cross-process determinism. + # + # EXTENSION POINT: Traceable wrapper subclasses can override cache key + # generation by implementing _stable_hash_for_caching(self) -> str. + # This method should return a deterministic string that uniquely identifies + # the tensor's metadata for caching purposes. See DTensor for an example. + # + # We can't define a default method on subclasses because there is no abstract + # base subclass, and we don't want to pollute torch.Tensor. Instead, we provide + # a default implementation here that uses __tensor_flatten__ to recursively + # hash inner tensors and metadata. + + def _hash_bytes_for_cache(self, data: bytes) -> str: + return hashlib.blake2b(data, digest_size=16).hexdigest() + + def _hash_pickled_value_for_cache(self, value: Any) -> str: + return self._hash_bytes_for_cache(pickle.dumps(value)) + + def _stable_hash_for_cache_value(self, obj: Any) -> str: + """Get a stable hash for an object used inside tensor subclass metadata.""" + from torch._custom_class_base import CustomClassBase + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + if hasattr(obj, "_stable_hash_for_caching"): + return obj._stable_hash_for_caching() + if isinstance(obj, torch.Tensor) and is_traceable_wrapper_subclass(obj): + return self._default_stable_hash_for_caching(obj) + if isinstance(obj, CustomClassBase): + # Opaque objects are runtime pass-throughs; only the type matters + # for cache key purposes, not the instance identity or value. + return self._hash_bytes_for_cache(type(obj).__qualname__.encode()) + if isinstance(obj, torch.Tensor): + return self._hash_pickled_value_for_cache( + extract_tensor_metadata_for_cache_key(obj) + ) + return self._hash_pickled_value_for_cache(obj) + + def _reduce_tensor_subclass( + self, tensor: torch.Tensor + ) -> tuple[Callable[..., Any], tuple[Any]]: + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + if hasattr(tensor, "_stable_hash_for_caching"): + return (_ident, (tensor._stable_hash_for_caching(),)) + if is_traceable_wrapper_subclass(tensor): + warn_once( + f"{type(tensor).__name__} does not implement _stable_hash_for_caching. " + "For PT2-compatible tensor subclasses, it is recommended to implement " + "_stable_hash_for_caching(self) -> str for stable AOT autograd caching." + ) + return (_ident, (self._default_stable_hash_for_caching(tensor),)) + return self._reduce_tensor(tensor) + + def _collect_inner_tensor_hashes( + self, tensor: torch.Tensor, inner_tensor_names: Sequence[str] + ) -> dict[str, str]: + inner_hashes = {} + for name in inner_tensor_names: + inner_hashes[name] = self._stable_hash_for_cache_value( + getattr(tensor, name) + ) + return inner_hashes + + def _stabilize_tensor_subclass_metadata(self, obj: Any) -> Any: + from torch._custom_class_base import CustomClassBase + + if isinstance(obj, CustomClassBase): + return type(obj).__qualname__ + if isinstance(obj, tuple): + return tuple(self._stabilize_tensor_subclass_metadata(x) for x in obj) + if isinstance(obj, list): + return [self._stabilize_tensor_subclass_metadata(x) for x in obj] + if isinstance(obj, dict): + return { + k: self._stabilize_tensor_subclass_metadata(v) for k, v in obj.items() + } + return obj + + def _default_stable_hash_for_caching(self, tensor: torch.Tensor) -> str: + """ + Default stable hash implementation for traceable wrapper subclasses. + """ + inner_tensor_names, subclass_metadata = tensor.__tensor_flatten__() # type: ignore[attr-defined] + cache_payload = ( + tensor.shape, + tensor.requires_grad, + self._stabilize_tensor_subclass_metadata(subclass_metadata), + self._collect_inner_tensor_hashes(tensor, inner_tensor_names), + ) + return self._hash_pickled_value_for_cache(cache_payload) + + def _reduce_aot_config( + self, aot_config: AOTConfig + ) -> tuple[Callable[..., Any], tuple[Any, ...]]: + """ + Reduce the config to a stable key for caching. + """ + cacheable = aot_config.to_cacheable() + return ( + # Cache entries persist the full CacheableAOTConfig, but cache keys + # intentionally ignore the debug-only aot_id so equivalent graphs can hit. + _ident, + ( + cacheable.num_params_buffers, + cacheable.keep_inference_input_mutations, + cacheable.is_export, + cacheable.no_tangents, + cacheable.dynamic_shapes, + cacheable.aot_autograd_arg_pos_to_source, + cacheable.static_input_indices, + cacheable.enable_log, + cacheable.pre_dispatch, + cacheable.precompile_backend_id, + ), + ) + + def _reduce_tensor(self, t: torch.Tensor) -> tuple[Callable[..., Any], tuple[Any]]: + """ + Reduce the tensor to a stable key for caching. + """ + metadata = extract_tensor_metadata_for_cache_key(t) + return (_ident, (metadata,)) + + +@contextlib.contextmanager +def normalize_placeholder_names( + gm: torch.fx.GraphModule, +) -> Generator[None, None, None]: + """ + Context manager that normalizes the placeholder names in the graph module. + This is used while generating a cache key for AOTAutogradCache, so that two graphs + that are isomorphic when normalizing names can hit the same cache entry. + This is safe because nothing underneath AOTAutograd uses the node names on the + original dynamo graph: AOTAutograd re-traces with its own nodes, and guards are + in terms of original sources rather than placeholder names. + """ + # Standalone inductor: we're bypassing AOTAutogradCache anyway, so return the graph + # as-is + if not config.autograd_cache_normalize_inputs or not hasattr(gm, "graph"): + yield + return + + # Track all the old state of placeholders + old_placeholder_names = [] + old_symint_names = [] + old_used_names = copy(gm.graph._graph_namespace._used_names) + i = 0 + j = 0 + for n in gm.graph.find_nodes(op="placeholder", sort=True): + if n.type == torch.SymInt: + new_name = f"s_{j}" + old_symint_names.append((n.name, n.target)) + n.target = new_name + n._rename(new_name) + j += 1 + else: + # _rename renames the node in the body of the function, + # but it doesn't change the raw name from node.target + # So we also set the raw_name of node.target to a new placeholder name + new_placeholder_name = f"p_{i}" + old_placeholder_names.append((n.name, n.target)) + n.target = new_placeholder_name + n._rename(new_placeholder_name) + i += 1 + gm.recompile() + try: + yield + finally: + # Used_names contains all our old placeholder names, + # so we clear it temporarily when we put them back + gm.graph._graph_namespace._used_names = set() + # Restore the placeholder names + i = 0 + j = 0 + for n in gm.graph.find_nodes(op="placeholder", sort=True): + if n.type == torch.SymInt: + (name, target) = old_symint_names[j] + n.target = target + n._rename(name) + j += 1 + else: + (name, target) = old_placeholder_names[i] + n.target = target + n._rename(name) + i += 1 + if i != len(old_placeholder_names): + raise AssertionError( + f"i={i} != len(old_placeholder_names)={len(old_placeholder_names)}" + ) + if j != len(old_symint_names): + raise AssertionError( + f"j={j} != len(old_symint_names)={len(old_symint_names)}" + ) + # Now restore the old namespace's used names + gm.graph._graph_namespace._used_names = old_used_names + gm.recompile() + + +def create_fx_config( + compiler_config_extra: CompilerConfigExtra | None = None, + compile_region_name: str | None = None, +) -> _CompileFxKwargs: + if compiler_config_extra is None: + cudagraphs = BoxedBool(torch._inductor.config.triton.cudagraphs) + boxed_forward_device_index = None + else: + cudagraphs = compiler_config_extra.cudagraphs + boxed_forward_device_index = compiler_config_extra.forward_device + return { + "cudagraphs": cudagraphs, + "boxed_forward_device_index": boxed_forward_device_index, + "compile_region_name": compile_region_name, # pyrefly: ignore[bad-typed-dict-key] + } + + +def _check_triton_cache_version() -> None: + if not has_triton_package(): + return + + # Due to https://github.com/triton-lang/triton/issues/3729, if triton is < + # 3.2.0, AOTAutogradCache may cause us to attempt to load a cache entry + # without initializing the CUDA context on the autograd thread. + # + # Without caching, we naturally do this initialization when tracing through + # the graph with the autograd engine. + import triton + + if triton.__version__ < "3.2.0": + raise BypassAOTAutogradCache("AOTAutogradCache requires triton 3.2.0") + + +def _get_debug_lines_for_cache_key( + pickler: AOTAutogradCachePickler, + details: AOTAutogradCacheDetails, + key: str, +) -> list[str]: + # debug_lines re-hashes every attribute individually and is expensive. Only + # compute when debug logging is enabled. + if not log.isEnabledFor(logging.DEBUG): + return [] + + debug_lines = pickler.debug_lines(details) + log.debug( + "Autograd graph cache hash details for key %s:\n%s", + key, + LazyString(lambda: "\n".join(debug_lines)), + ) + return debug_lines + + +def autograd_cache_key( + mod: torch.fx.GraphModule | torch._dynamo.utils.GmWrapper, + example_inputs: Sequence[Any], + config: AOTConfig, + compiler_config_extra: CompilerConfigExtra | None = None, + act_input_paths: ActInputPaths = (), + # TODO: add args and parameters +) -> tuple[str, list[str]]: + """ + Generate a unique hash of the FX graph for caching. + """ + + gm = mod.gm if isinstance(mod, torch._dynamo.utils.GmWrapper) else mod + try: + # Capture graph SymInt placeholder names before normalization so the + # pickler can distinguish graph-native SymInts (deterministic names) + # from MetaConverter-generated SymInts (non-deterministic names). + graph_symint_names: set[str] = set() + symint_name_map: dict[str, str] = {} + if torch._functorch.config.autograd_cache_normalize_inputs: + for n in gm.graph.find_nodes(op="placeholder", sort=True): + if n.type == torch.SymInt: + graph_symint_names.add(n.target) + j = 0 + for inp in example_inputs: + if isinstance(inp, torch.SymInt): + symint_name_map[str(inp)] = f"s_{j}" + j += 1 + with sanitize_gm_for_cache(gm): + check_cacheable(gm) + _check_triton_cache_version() + details = AOTAutogradCacheDetails( + gm, + example_inputs, + config, + create_fx_config(compiler_config_extra), + act_input_paths, + ) + pickler = AOTAutogradCachePickler(gm, symint_name_map, graph_symint_names) + # The prefix distinguishes among the other kinds of objects we cache + key = AOTAUTOGRAD_CACHE_PREFIX + pickler.get_hash(details) + debug_lines = _get_debug_lines_for_cache_key(pickler, details, key) + return key, debug_lines + except Exception: + # If enable_aot_compile is set, we're in AOT precompile mode where we always + # want to use fallback nonce keys. Unlike caching, it's fine if we can't generate + # a proper key because we are guaranteed in an AOT precompile world users are in + # complete control of distributing and loading artifacts. + if torch._functorch.config.bypass_autograd_cache_key: + log.info( + "Failed to generate AOTAutograd cache key; falling back to nonce due to enable_aot_compile", + exc_info=True, + ) + return str(random.random()), [] + else: + raise + + +@contextlib.contextmanager +def sanitize_gm_for_cache( + gm: torch.fx.GraphModule, +) -> Generator[None, None, None]: + """ + Clears a few fields in a dynamo supplied Graph Module that are not stable between graph inputs, but don't + affect inductor or aotdispatch correctness. + + These fields **can** be used by code calling into aotdispatch (namely, dynamo), so we can't null them out completely. + + To ensure that these fields are not accessed by inductor or aotdispatch, we clear them during AOTAutogradCache.load, + and then put them back before returning. This way, we generate a cache key based off of a canonical graph + without these fields, and also guarantee they aren't used to affect the cache's output. + """ + # Mapping from each field to a default value + IGNORED_FIELDS: dict[str, Any] = { + # pyrefly: ignore [implicit-any] + "meta": {}, # metadata used by export + "compile_subgraph_reason": None, # Used by dynamo only for logging, no change in inductor/autograd behavior + "_param_name_to_source": None, # Encapsulated by aot_config.aot_autograd_arg_pos_to_source + "_backend_id": None, + } + saved_fields = {} + for field, default_value in IGNORED_FIELDS.items(): + saved_fields[field] = getattr(gm, field, None) + # Clear the field + setattr(gm, field, default_value) + try: + with normalize_placeholder_names(gm): + yield + finally: + for field, value in saved_fields.items(): + setattr(gm, field, value) + + +@CacheArtifactFactory.register +class AOTAutogradCacheArtifact(CacheArtifact): + @override + def populate_cache(self) -> None: + AOTAutogradCache._write_to_local_cache(self.key, self.content) + + @override + @staticmethod + def type() -> str: + return "aot_autograd" + + +class AOTAutogradCache(GuardedCache[GenericAOTAutogradResult[Any, Any]]): + """ + Caches the results of running AOTAutograd. This class mostly handles the save and load logic, whereas + AOTAutogradResult handles the wrapping/unwrapping logic. + + Cache Inputs (AOTAutogradCacheDetails) + - AOTAutogradCache takes in the following inputs, which are analogous to inputs given + to AOTAutograd by dynamo: + - A fx graph module generated by dynamo + - A list of args, which consists of: + - Symint inputs to the graph, generated by dynamo + - The **real tensor** inputs, which inductor uses for cudagraphs + - Notably, the real tensor inputs don't have symints in their metadata. + AOTAutograd then retraces those real tensor arguments into FakeTensors later during execution. + - A set of global configurations that affect AOTAutograd or Inductor behavior. + + It then generates a cache key given these values. Notably, this means AOTAutogradCache currently + specializes on the sizes and strides of the real tensor inputs when dynamic shapes are turned on. + In a later PR, we'll likely generate the cache key based on the FakeTensors AOTAutograd generates + based on the real tensor inputs, which can contain symints. + + # Cache Outputs (AOTAutogradResult) + - AOTAutogradCache caches the following values: + - The compiled forward and backward functions from inductor, via keys to the FXGraphCache + - Metadata to reconstruct the AOTModule from the compiled inductor artifacts + - See AOTAutogradResult for more info + + [Note: Caching guards generated by AOTAutograd and Inductor] + AOTAutograd and inductor both can introduce new guards to the shape environment. FXGraphCache saves guards with each + compiled graph inductor generates. On a cache hit, AOTAutograd reloads the compiled forward and backward functions + from FXGraphCache, giving it new symint arguments from the input args. + FXGraphCache uses those symints and its saved guards to repopulate the ShapeEnv with guards. + **No new guards are generated into the shape env after inductor finishes compiling**, so the guards + saved by inductor are sufficient for correctness for both AOTAutograd and Inductor's caches. + """ + + @staticmethod + def clear() -> None: + """Clear the cache""" + shutil.rmtree(AOTAutogradCache._get_tmp_dir(), ignore_errors=True) + + @staticmethod + def try_load( + mod: torch.fx.GraphModule | torch._dynamo.utils.GmWrapper, + args: list[Any], + aot_config: AOTConfig, + compiler_config_extra: CompilerConfigExtra | None, + local: bool, + remote: bool, + act_input_paths: ActInputPaths = (), + compile_region_name: str | None = None, + ) -> tuple[Callable[..., Any] | None, AOTConfig]: + """ + Load a result from the cache, and reconstruct a runtime wrapper around + the object. On a cache miss, return an updated config carrying the + cache metadata needed to save the eventual compile result. + """ + compiled_fn = None + cache_info: dict[str, Any] = {} + cache_key = None + debug_lines: list[str] = [] + cache_event_time = time.time_ns() + cache_state = None + try: + cache_key, debug_lines = autograd_cache_key( + mod, args, aot_config, compiler_config_extra, act_input_paths + ) + result: tuple[GenericAOTAutogradResult[Any, Any], bytes] | None = ( + AOTAutogradCache._lookup( + cache_key, local, remote, args, cache_info, aot_config + ) + ) + if result is not None: + (entry, pickled_content) = result + fx_config = create_fx_config(compiler_config_extra, compile_region_name) + compiled_fn = entry.wrap_post_compile(args, aot_config, fx_config) + # Make the compiled_fn serializable, where the serialize function just + # makes a copy of the original entry before post compile via the pickled content + compiled_fn = SerializableCompiledFunction( + compiled_fn, lambda: pickle.loads(pickled_content) + ) + log.info("AOTAutograd cache hit for key %s", cache_key) + + counters["aot_autograd"]["autograd_cache_hit"] += 1 + cache_state = "hit" + cache_event_time = time.time_ns() + forward_time_saved = entry.forward_time_taken_ns // 1e6 + backward_time_saved = entry.backward_time_taken_ns // 1e6 + cache_info.update( + { + "forward_time_saved_ms": forward_time_saved, + "backward_time_saved_ms": backward_time_saved, + "time_saved_ms": forward_time_saved + backward_time_saved, + } + ) + time_saved_ns = ( + entry.forward_time_taken_ns + entry.backward_time_taken_ns + ) + # TODO: should we use the same field for remote cache time saved for both + # FXGraphCache and AOTAutogradCache? + # get_metrics_context().increment(...) + if ( + ephemeral_increase + := add_ephemeral_timeout_increase_for_distributed(time_saved_ns) + ) != 0: + cache_info["ephemeral_timeout_increase"] = ephemeral_increase + + if compiled_fn is None: + log.info("AOTAutograd cache miss for key %s", cache_key) + counters["aot_autograd"]["autograd_cache_miss"] += 1 + cache_state = "miss" + cache_event_time = time.time_ns() + # Count missing the FXGraphCache as a miss not a bypass + except FXGraphCacheMiss as e: + counters["aot_autograd"]["autograd_cache_miss"] += 1 + cache_state = "miss" + if config.strict_autograd_cache or torch._dynamo.config.strict_precompile: + raise e + # Most often this is BypassAOTAutogradCache, but + # if there's ever different reason we can't cache, + # we still never want to hard throw an exception, since + # we can always fallback to a cache bypass. + # As an example, if the user calls autograd via + # standalone inductor, we will sometimes get a GraphModule + # that doesn't actually have a `.graph` on it. Instead + # of checking every single case, we safely catch the exception + # in those cases. + except Exception as e: + cache_key = None + counters["aot_autograd"]["autograd_cache_bypass"] += 1 + log.info("Bypassing autograd cache due to: %s", e) + cache_state = "bypass" + cache_event_time = time.time_ns() + cache_info["cache_bypass_reason"] = str(e) + cache_info["cache_bypass_exception_type"] = type(e).__name__ + cache_info["cache_bypass_traceback"] = traceback.format_exc().split("\n") + # TODO: this gets logged implicitly by cache_bypass_reason, + # and here we explicitly log it into tlparse. + # We may want to log this as an extra column in Scuba, though. + cache_info["cache_bypass_hard_exception"] = not isinstance( + e, BypassAOTAutogradCache + ) + if remote: + log_cache_bypass("bypass_aot_autograd", str(e)) + if config.strict_autograd_cache or torch._dynamo.config.strict_precompile: + raise e + if compiled_fn is None: + # Set the cache key so we can save a cache result later + symints = AOTAutogradCache._filter_backed_symints(args) + if cache_key is not None: + aot_config = dataclasses.replace( + aot_config, + cache_info=AOTAutogradCacheInfo( + cache_key, + time.time_ns(), + forward_symints=symints, + ), + ) + + cache_info.update( + { + "key": cache_key, + "cache_state": cache_state, + "components": debug_lines, + } + ) + if chromium_event_log_active(): + CompileEventLogger.instant( + f"autograd_cache_{cache_state}", + metadata=cache_info, + time_ns=cache_event_time, + ) + CompileEventLogger.try_add_pt2_compile( + "backend_compile", + cache_state=cache_state, + cache_event_time=cache_event_time, + key=cache_info.get("key"), + components=cache_info.get("components"), + cache_bypass_reason=cache_info.get("cache_bypass_reason"), + remote_cache_enabled=remote, + local_cache_enabled=local, + ) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": f"aotautograd_cache_{cache_state}", + "encoding": "json", + }, + payload_fn=lambda: json.dumps(cache_info), + ) + + return compiled_fn, aot_config + + @classmethod + def generate_guards_expression( + cls: type[AOTAutogradCache], cache_info: AOTAutogradCacheInfo + ) -> str | None: + shape_env = cls._get_shape_env() + + if shape_env is None: + return None + + symints = cache_info.forward_symints + guards = shape_env.get_pruned_guards(symints) + return shape_env.produce_guards_expression(placeholders=symints, guards=guards) + + @classmethod + def _get_tmp_dir(cls: type[AOTAutogradCache]) -> str: + """ + Get the toplevel temporary directory for storing compiled graphs. + """ + return os.path.join(cache_dir(), "aotautograd") + + @classmethod + def _get_tmp_dir_for_key(cls: type[AOTAutogradCache], _key: str) -> str: + """ + Get the toplevel temporary directory for storing compiled graphs. + """ + return os.path.join(cls._get_tmp_dir(), _key) + + @classmethod + def _record_result( + cls: type[AOTAutogradCache], + key: str, + local_hit: bool, + local_miss: bool, + remote_hit: bool, + remote_miss: bool, + ) -> None: + """ + Called by GuardedCache to record hit/miss statistics. + """ + if local_hit: + cache_stats.hit("LocalAOTAutogradCache") + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "aotautograd_local_cache_hit_count", + ) + if remote_hit: + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "aotautograd_remote_cache_hit_count", + ) + if local_miss: + cache_stats.miss("LocalAOTAutogradCache") + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "aotautograd_local_cache_miss_count", + ) + if remote_miss: + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "aotautograd_remote_cache_miss_count", + ) + + @staticmethod + def evaluate_guards(guard_expr: str, hints: list[int] | list[torch.SymInt]) -> bool: + if torch._inductor.config.unsafe_skip_cache_dynamic_shape_guards: + return True + shape_env = AOTAutogradCache._get_shape_env() + if shape_env is None: + raise AssertionError("shape_env must not be None") + result = shape_env.evaluate_guards_expression(guard_expr, hints) + return result + + @staticmethod + def _lookup( + key: str, + local: bool, + remote: bool, + args: list[Any], + cache_info: dict[str, Any], + aot_config: AOTConfig | None, + ) -> tuple[GenericAOTAutogradResult[Any, Any], bytes] | None: + """Given a key generated by AOTAutogradCachePickler, look up its location in the cache.""" + remote_cache: RemoteCache[JsonDataTy] | None = None + if remote: + remote_cache = AOTAutogradCache.get_remote_cache() + + symints = AOTAutogradCache._filter_backed_symints(args) + hints = [guarding_hint_or_throw(s) for s in symints] + entry = None + pickled_content = None + try: + ( + entry, + pickled_content, + guard_info, + ) = AOTAutogradCache.find_guarded_entry( + key, local, remote_cache, AOTAutogradCache.evaluate_guards, hints + ) + + if entry is None and guard_info["cache_status_detailed"] == "guard_miss": + counters["aot_autograd"]["autograd_cache_guard_miss"] += 1 + cache_info.update(guard_info) + CacheArtifactRecorder( + AOTAutogradCacheArtifact.type(), key + ).record_if_present(pickled_content) + if pickled_content is not None: + if ( + should_bundle_autograd_cache() + and aot_config is not None + and aot_config.precompile_backend_id is not None + ): + # NB: We don't want to use the cached aot_config.precompile_backend_id + # 1. because we set it to None on save 2. even if we didn't, this new run + # that cache hit has a *new* backend id associated with it. + PrecompileContext.record_artifact( + BundledAOTAutogradCacheArtifact( + aot_config.precompile_backend_id, entry + ), + ) + except Exception as e: + log.info("AOTAutograd cache unable to load compiled graph: %s", e) + if config.strict_autograd_cache: + raise e + if entry is not None: + if pickled_content is None: + raise AssertionError( + "pickled_content must not be None when entry is not None" + ) + return (entry, pickled_content) + else: + return None + + @staticmethod + def _write_to_local_cache(key: str, content: bytes) -> None: + """Write an entry to the local cache.""" + subdir = AOTAutogradCache._get_tmp_dir_for_key(key) + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + + # Use a hash of the serialized entry to get a unique file + # name. The specific name doesn't matter since a lookup involves + # iterating over all entries in the parent subdir. + path = os.path.join(subdir, sha256_hash(content)) + log.info("Writing AOTAutograd cache entry to %s", path) + write_atomic(path, content) + + @staticmethod + def _find_unpicklable_field( + entry: GenericAOTAutogradResult[Any, Any], + ) -> str | None: + """Find which field of entry is causing pickle to fail.""" + # pyrefly: ignore [implicit-any] + fields = [] + if hasattr(entry, "__dataclass_fields__"): + fields = list(entry.__dataclass_fields__.keys()) + elif hasattr(entry, "__dict__"): + fields = list(entry.__dict__.keys()) + + for name in fields: + try: + pickle.dumps(getattr(entry, name)) + except Exception: + return name + return None + + @staticmethod + def _pickle_entry( + entry: GenericAOTAutogradResult[Any, Any], remote: bool + ) -> bytes | None: + """Pickle entry, returning None on failure.""" + try: + with torch.utils._python_dispatch._disable_current_modes(): + return pickle.dumps(entry) + except (pickle.PicklingError, TypeError, AttributeError) as e: + bad_field = AOTAutogradCache._find_unpicklable_field(entry) + error_str = str(e) + log.warning("AOTAutograd cache unable to serialize compiled graph: %s", e) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aotautograd_cache_pickle_failure", + "encoding": "json", + }, + payload_fn=lambda: json.dumps({"error": error_str, "field": bad_field}), + ) + if remote: + log_cache_bypass( + "bypass_aot_autograd", "Unable to serialize: " + str(e) + ) + if config.strict_autograd_cache: + raise + return None + + @staticmethod + def _handle_save_error(e: Exception, remote: bool, is_bypass: bool) -> None: + """Handle exceptions during save, re-raising if strict mode is enabled.""" + if is_bypass: + counters["aot_autograd"]["autograd_cache_bypass"] += 1 + log.info("Bypassing autograd cache due to: %s", e) + bypass_reason = str(e) + else: + log.warning("AOTAutograd cache unable to serialize compiled graph: %s", e) + bypass_reason = "Unable to serialize: " + str(e) + if remote: + log_cache_bypass("bypass_aot_autograd", bypass_reason) + if config.strict_autograd_cache: + raise e + + @staticmethod + def save(key: str, entry: GenericAOTAutogradResult[Any, Any], remote: bool) -> None: + """Save a single entry into the cache.""" + content: bytes | None = None + try: + entry.pre_save() + content = AOTAutogradCache._pickle_entry(entry, remote) + if content is None: + return None + CacheArtifactRecorder(AOTAutogradCacheArtifact.type(), key).record(content) + if ( + should_bundle_autograd_cache() + and entry.sanitized_aot_config.precompile_backend_id is not None + ): + precompile_key = entry.sanitized_aot_config.precompile_backend_id + artifact = BundledAOTAutogradCacheArtifact(precompile_key, entry) + entry.sanitized_aot_config.precompile_backend_id = None + PrecompileContext.record_artifact(artifact) + AOTAutogradCache._write_to_local_cache(key, content) + counters["aot_autograd"]["autograd_cache_saved"] += 1 + cache_stats.put("LocalAOTAutogradCache") + except BypassAOTAutogradCache as e: + AOTAutogradCache._handle_save_error(e, remote, is_bypass=True) + return None + except Exception as e: + AOTAutogradCache._handle_save_error(e, remote, is_bypass=False) + return None + + if remote: + remote_cache = AOTAutogradCache.get_remote_cache() + if remote_cache is not None: + time_taken_ms = int( + (entry.forward_time_taken_ns + entry.backward_time_taken_ns) // 1e6 + ) + cache_data: JsonDataTy = { + "data": base64.b64encode(content).decode("ascii"), + "time_taken_ms": time_taken_ms, + } + remote_cache.put(key, cache_data) + + @staticmethod + @functools.cache + def get_remote_cache() -> RemoteCache[JsonDataTy] | None: + """ + Attempts to load the remote cache, returns None on error. + """ + cache_id = "autograd-experimental" + return create_cache( + cache_id, + config.is_fbcode(), + "FbRemoteAOTAutogradCache", + "RemoteAOTAutogradCache", + ) + + @staticmethod + def make_entry( + compiled_fw_func: OutputCode, + compiled_bw_func: OutputCode | None, + aot_joint_graph_str: str | None, + aot_forward_graph_str: str | None, + aot_backward_graph_str: str | None, + runtime_metadata: ViewAndMutationMeta, + dispatch_wrappers: list[CompilerWrapper], + maybe_subclass_meta: SubclassMeta | None, + num_fw_outs_saved_for_bw: int | None, + indices_of_inps_to_detach: list[int], + forward_time_taken_ns: int, + backward_time_taken_ns: int, + sanitized_aot_config: CacheableAOTConfig, + guards_expr: str | None, + backward_state_indices: list[int] | None, + num_symints_saved_for_bw: int | None, + serialized_bw_module: SerializedGraphModule | None, + min_cut_info_str: str | None, + ) -> GenericAOTAutogradResult[Any, Any]: + if should_bundle_autograd_cache(): + # Helper function to unwrap all the wrappers we added during aotdispatch + # They get reapplied on cache load + def unwrap_output_code(obj: object) -> OutputCode: + while hasattr(obj, "__wrapped__"): + obj = obj.__wrapped__ + if not isinstance(obj, OutputCode): + raise AssertionError(f"expected OutputCode, got {type(obj)}") + return obj + + compiled_fw_graph = unwrap_output_code(compiled_fw_func) + bundled_compiled_forward = BundledCompiledForward(compiled_fw_graph) + bundled_compiled_backward = None + if compiled_bw_func is not None: + if backward_state_indices is None: + raise AssertionError("backward_state_indices must not be None") + if num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + compiled_bw_graph = unwrap_output_code(compiled_bw_func) + bundled_compiled_backward = BundledCompiledBackward( + compiled_bw_graph, backward_state_indices, num_symints_saved_for_bw + ) + + return BundledAOTAutogradResult( + compiled_fw=bundled_compiled_forward, + compiled_bw=bundled_compiled_backward, + aot_joint_graph_str=aot_joint_graph_str, + aot_forward_graph_str=aot_forward_graph_str, + aot_backward_graph_str=aot_backward_graph_str, + min_cut_info_str=min_cut_info_str, + runtime_metadata=runtime_metadata, + dispatch_wrappers=dispatch_wrappers, + maybe_subclass_meta=maybe_subclass_meta, + num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw, + indices_of_inps_to_detach=indices_of_inps_to_detach, + forward_time_taken_ns=forward_time_taken_ns, + backward_time_taken_ns=backward_time_taken_ns, + sanitized_aot_config=sanitized_aot_config, + guards_expr=guards_expr, + serialized_bw_module=serialized_bw_module, + ) + + else: + fw_key = getattr(compiled_fw_func, "_fx_graph_cache_key", None) + fw_debug_lines = getattr( + compiled_fw_func, "_fx_graph_cache_debug_lines", [] + ) + + if fw_key is None: + raise AssertionError("fw_key must not be None") + compiled_forward = CompiledForward( + fx_graph_cache_info=(fw_key, fw_debug_lines), + fx_graph_guard_expr=getattr(compiled_fw_func, "guards_expr", None), + ) + compiled_backward = None + if compiled_bw_func is not None: + bw_key = getattr(compiled_bw_func, "_fx_graph_cache_key", None) + bw_debug_lines = getattr( + compiled_bw_func, "_fx_graph_cache_debug_lines", [] + ) + if bw_key is None: + raise AssertionError("bw_key must not be None") + if backward_state_indices is None: + raise AssertionError("backward_state_indices must not be None") + if num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + compiled_backward = CompiledBackward( + fx_graph_cache_info=(bw_key, bw_debug_lines), + fx_graph_guard_expr=getattr(compiled_bw_func, "guards_expr", None), + backward_state_indices=backward_state_indices, + num_symints_saved_for_bw_=num_symints_saved_for_bw, + ) + + return AOTAutogradResult( + compiled_fw=compiled_forward, + compiled_bw=compiled_backward, + aot_joint_graph_str=aot_joint_graph_str, + aot_forward_graph_str=aot_forward_graph_str, + aot_backward_graph_str=aot_backward_graph_str, + min_cut_info_str=min_cut_info_str, + runtime_metadata=runtime_metadata, + dispatch_wrappers=dispatch_wrappers, + maybe_subclass_meta=maybe_subclass_meta, + num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw, + indices_of_inps_to_detach=indices_of_inps_to_detach, + forward_time_taken_ns=forward_time_taken_ns, + backward_time_taken_ns=backward_time_taken_ns, + sanitized_aot_config=sanitized_aot_config, + guards_expr=guards_expr, + serialized_bw_module=serialized_bw_module, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/codegen.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..d35f98523c50c23487a06cfe47cbbfcbcaf21a63 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/codegen.py @@ -0,0 +1,240 @@ +""" +Generic codegen for AOTAutograd runtime wrappers. + +PySourceBuilder accumulates indented Python source together with the globals the +generated code closes over and a fresh-name counter; _compile_and_exec_source is +the single chokepoint that turns generated source into a live function (logging it +as a structured-trace artifact for tlparse and giving it a stable traceback +filename). Every runtime-wrapper codegen routes through it -- the subclass wrappers +in subclass_codegen.py and the orchestration / alias / mutation epilogues in +runtime_wrappers.py -- so it knows nothing about any particular wrapper kind. This +module also hosts the optional thread-local capture sink that records each codegen'd +wrapper's source, which AOT-to-Python lowering (to_standalone_python.py) uses to +compose the wrappers into one standalone module. Kept as a leaf module (stdlib + +torch only) so it is safe to import anywhere. +""" + +import contextlib +import functools +import logging +import threading +from collections.abc import Callable, Iterator + +import torch +from torch.utils._indented_buffer import IndentedBuffer + + +log = logging.getLogger(__name__) + + +class PySourceBuilder(IndentedBuffer): + """Builds indented Python source for compile/exec, along with the globals + the generated code closes over and a monotonic fresh-name counter. + + Inherits the indentation primitive (``writeline``/``indent()``) from + IndentedBuffer: body lines are written WITHOUT leading whitespace and + indentation is managed by the ``indent()`` context manager so call sites + read as plain code. This subclass adds the exec layer (globals binding, + fresh-name generation, and ``build()`` via _compile_and_exec_source). Pass + ``fn_name``/``artifact_name`` to emit a ``def`` header and enable + ``build()``. + """ + + def __init__( + self, + fn_name: str | None = None, + *, + args: str = "args", + artifact_name: str | None = None, + ) -> None: + super().__init__() + self.globals: dict[str, object] = {} + self._name_counter: int = 0 + self._fn_name = fn_name + self._artifact_name = artifact_name + if fn_name is not None: + self.writeline(f"def {fn_name}({args}):") + + def emit(self, line: str, indent: int = 1) -> None: + """Append one line at an explicit absolute indent level. + + Convenient for recursive generators that thread an indent depth instead + of nesting indent() context managers. + """ + saved, self._indent = self._indent, indent + try: + self.writeline(line) + finally: + self._indent = saved + + def fresh_name(self, prefix: str) -> str: + name = f"{prefix}_{self._name_counter}" + self._name_counter += 1 + return name + + def add_global(self, name: str, value: object) -> str: + """Bind a live object into the exec globals under ``name``, by reference.""" + self.globals[name] = value + return name + + def bind(self, **values: object) -> None: + """Bind live objects into the exec globals by keyword, by reference.""" + self.globals.update(values) + + def bind_value(self, prefix: str, value: object) -> str: + """Bind a value under a fresh unique name and return that name.""" + return self.add_global(self.fresh_name(prefix), value) + + def getvalue(self) -> str: + # Join without a trailing newline (unlike IndentedBuffer.getvalue). + if not all(isinstance(li, str) for li in self._lines): + raise AssertionError(f"expected all lines to be str, got {self._lines}") + return "\n".join(self._lines) # type: ignore[arg-type] + + def build( + self, *, wrapped_fn: Callable[..., object] | None = None + ) -> Callable[..., object]: + if self._fn_name is None or self._artifact_name is None: + raise AssertionError("build() requires fn_name and artifact_name") + return _compile_and_exec_source( + self.getvalue(), + self.globals, + self._fn_name, + self._artifact_name, + wrapped_fn=wrapped_fn, + ) + + +# Optional sink for the source of every runtime-wrapper function codegen'd via +# ``_compile_and_exec_source``. When a sink is installed (see +# ``capture_generated_sources``), each codegen'd wrapper appends a +# ``GeneratedSource`` to it; this lets AOT-to-Python lowering compose the wrappers +# into one standalone module. Thread-local (NOT a process global) so a concurrent +# compile on another thread cannot splice its wrappers into this capture -- and, +# conversely, so an unrelated concurrent compile on another thread is never mistaken for +# offloaded capture work and aborted (``_compile_and_exec_source`` runs on EVERY +# AOTAutograd compile, not just this one). Absent (zero overhead, no behavior change) +# during ordinary compilation. Mirrors the threading.local used by +# _saved_tensor_hook_context in graph_compile.py. +_capture_tls = threading.local() + + +def _current_capture_sink() -> "list[GeneratedSource] | None": + return getattr(_capture_tls, "sink", None) + + +class GeneratedSource: + """One codegen'd runtime-wrapper function: its source, the exec'd function + object, and the globals it closes over (which include the inner ``compiled_fn`` + it chains to, plus any baked metadata). The function object lets a composer wire + cross-wrapper references by identity. Recorded by ``_compile_and_exec_source`` + when capture is active. + + ``globals_dict`` is a PRE-EXEC snapshot of the declared closure globals: it does + NOT contain the interpreter ``__builtins__`` that exec() would otherwise inject, + so the standalone composer can reconstruct every entry as source without having + to special-case ``__builtins__``.""" + + def __init__( + self, + artifact_name: str, + fn_name: str, + source: str, + globals_dict: dict[str, object], + fn: object, + origin_id: int | None = None, + ) -> None: + self.artifact_name = artifact_name + self.fn_name = fn_name + self.source = source + self.globals_dict = globals_dict + self.fn = fn + # Identity of the TracingContext this wrapper was codegen'd under. The capture + # sink is duration-scoped over one inductor compile, so a re-entrant on-thread + # lowering that codegen's into THIS sink during that window would append its + # wrappers too; the composer filters by this id, which separates such a foreign + # lowering when it ran under a DISTINCT TracingContext. A same-context re-entrant + # lowering shares this id and is caught instead by the composer's + # orchestration-count guard. + self.origin_id = origin_id + + +@contextlib.contextmanager +def capture_generated_sources(into: "list[GeneratedSource]") -> "Iterator[None]": + """Within this context, record every codegen'd runtime-wrapper function's source + into ``into`` (in codegen order). A no-op when not entered. + + THREADING: the sink is thread-local, so every wrapper captured into ``into`` must be + codegen'd ON THIS THREAD. There is deliberately NO cross-thread tripwire here: a + process-global owner check would abort an unrelated concurrent compile on another + thread, since ``_compile_and_exec_source`` runs on every AOTAutograd compile and is not + serialized against this capture. If a future change offloads wrapper codegen to a + worker thread, those wrappers are simply not captured; a forward that loses its + orchestration wrapper this way is rejected by the composer (it requires exactly one), + so the common case fails loudly rather than emitting an empty module. + """ + prev = _current_capture_sink() + _capture_tls.sink = into + try: + yield + finally: + _capture_tls.sink = prev + + +def _compile_and_exec_source( + source: str, + globals_dict: dict[str, object], + fn_name: str, + artifact_name: str, + wrapped_fn: Callable[..., object] | None = None, +) -> Callable[..., object]: + """Compile generated source, exec it, and return the named function. + + If wrapped_fn is provided, applies functools.update_wrapper so that + __wrapped__ and __dict__ (e.g. _fx_graph_cache_key) propagate to the + generated function. + """ + if log.isEnabledFor(logging.DEBUG): + log.debug("Generated %s:\n%s", artifact_name, source) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": artifact_name, + "encoding": "string", + }, + payload_fn=lambda: source, + ) + + # Use a path under torch/_functorch/ so the code object is recognized by + # dynamo's MOD_SKIPLIST. The eval frame hook stays active during the entire + # torch.compile(fn)(*args) call (to handle graph breaks and resume functions), + # so codegen'd functions called during backward get intercepted even though + # no tracing is active. A real path makes them skip automatically. + code = compile(source, f"{__file__}:codegen({artifact_name})", "exec") + local_dict: dict[str, object] = {} + # exec() mutates ``globals_dict`` in place, injecting ``__builtins__`` (and any + # name the source binds at module scope). When capturing, snapshot the declared + # closed-over names BEFORE that happens so the captured GeneratedSource holds only + # the intended closure globals -- not the post-exec dict with the interpreter's + # ``__builtins__`` -- which is what the standalone composer reconstructs as source. + sink = _current_capture_sink() + captured_globals = dict(globals_dict) if sink is not None else globals_dict + exec(code, globals_dict, local_dict) + fn = local_dict[fn_name] + if wrapped_fn is not None: + functools.update_wrapper(fn, wrapped_fn) # type: ignore[arg-type] + + if sink is not None: + # Tag with the current TracingContext identity so the composer can drop any + # wrapper a re-entrant lowering appended during the capture window (see the + # origin_id note on GeneratedSource). + ctx = torch._guards.TracingContext.try_get() + origin_id = id(ctx) if ctx is not None else None + sink.append( + GeneratedSource( + artifact_name, fn_name, source, captured_globals, fn, origin_id + ) + ) + + return fn # type: ignore[return-value] diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/collect_metadata_analysis.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/collect_metadata_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..d7c298170cec45ace0e5597a87763fa90e396430 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/collect_metadata_analysis.py @@ -0,0 +1,880 @@ +from __future__ import annotations + + +""" +This module is one of the analysis modules - it takes as input a function or graph +and some preexisting properties, and returns some data that is useful for deciding +how to further proceed with compilation or construct runtime wrappers. + +In particular, the analysis here constructs view and mutation metadata from running +a functionalized version of the graph under compilation. +""" + +import collections +import contextlib +import logging +from typing import Any, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch import Tensor +from torch._guards import detect_fake_mode +from torch._library.opaque_object import is_custom_class +from torch._logging import getArtifactLogger +from torch._subclasses.functional_tensor import FunctionalTensor, FunctionalTensorMode +from torch._subclasses.meta_utils import safe_is_leaf +from torch.fx.experimental.proxy_tensor import disable_autocast_cache +from torch.fx.experimental.symbolic_shapes import is_concrete_int +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + transform_subclass, +) + +from .descriptors import ( + AOTInput, + AOTOutput, + InputMutationAOTOutput, + IntermediateBaseAOTOutput, + PlainAOTOutput, + TangentAOTInput, +) +from .functional_utils import ( + are_all_mutations_hidden_from_autograd, + are_all_mutations_under_no_grad_or_inference_mode, + from_fun, + has_data_mutation, + has_metadata_mutation, + MetadataKey, + to_fun, + ViewMetaSequence, + was_inductor_storage_resized, + was_shallow_copy_data, +) +from .schemas import ( + InputAliasInfo, + MemoryFormatMeta, + MutationType, + OutputAliasInfo, + OutputType, + ViewAndMutationMeta, +) +from .subclass_utils import create_subclass_meta +from .utils import _get_autocast_states, KNOWN_TYPES, simple_wraps, strict_zip + + +if TYPE_CHECKING: + from collections.abc import Callable + +zip = strict_zip + +log = logging.getLogger(__name__) +static_input_logger = getArtifactLogger("torch._dynamo", "cudagraph_static_inputs") + + +# Note [Tangents memory format] +# We assume tangents memory format to be similar to corresponding output's memory_format. +# The idea is that we are technically making a guess about the strides of our tangents, +# while we trace out the joint. +# If runtime specified tangents will not have the same memory format as predicted traced tangents, +# we coerce them at runtime to traced tangents memory format. + + +# Coercing and collecting traced tangents memory format in one recursive traversal +def coerce_tangent_and_suggest_memory_format( + x: Tensor, +) -> tuple[Any, MemoryFormatMeta | list[Any] | None, bool]: + updated = False + if not isinstance(x, Tensor): + return x, None, updated + + out = x.detach() + + is_subclass = is_traceable_wrapper_subclass(out) + + memory_format = MemoryFormatMeta.from_tensor(out) + + # pyrefly: ignore [missing-attribute] + if memory_format.memory_format is not None: + was = out + # pyrefly: ignore [bad-argument-type] + out = out.contiguous(memory_format=memory_format.memory_format) + updated = was is not out + + # For subclass we keep memory format of outer strides at the beginning of the list + out_memory_format = [memory_format] if is_subclass else memory_format + + # Note [Tangents memory format, Part 2] + # In the same way that "what strides do we assigns to our tangents" is a question + # that we can not answer (and therefore have to guess) as we trace the backward ahead-of-time, + # The same applies to any tensor subclass metadata, when we have tangents that are subclasses. + # To handle this situation, we have two new methods that a tensor subclass can implement: + # (1) __coerce_tangent_metadata__(self) + # Given a subclass with "non-standard" metadata, turn it into a new subclass with "normal" metadata. + # The main example here is a DTensor with the "_Partial" placement. + # If we have a forward output with a _Partial placement, and corresponding tangent + # with a Replicate/Shard placement, we have no way to convert the tangent "back" to a _Partial placement. + # This method lets us avoid the problem entirely by allowing subclasses to ensure that we can never + # have a tangent with "problematic" metadata, that we cannot convert to. + # (1) __coerce_same_metadata_as_tangent__(self, metadata) + # Given a subclass, and a target differing metadata, + # convert self to have the same metadata as the target. + # With DTensor being the main example, we can use this to convert a DTensor with a Replicate() + # placement into one with a Shard() placement, in the case that we "guessed wrong", + # and traced tangents with a Shard() placement at compile time. + # + if is_subclass and hasattr(out, "__coerce_tangent_metadata__"): + out = out.__coerce_tangent_metadata__() # type: ignore[attr-defined] + + if is_subclass: + # pyrefly: ignore [missing-attribute] + attrs = out.__tensor_flatten__()[0] + + for attr in attrs: + elem = getattr(out, attr) + ( + new_elem, + new_elem_memory_format, + elem_updated, + ) = coerce_tangent_and_suggest_memory_format(elem) + # pyrefly: ignore [missing-attribute] + out_memory_format.append(new_elem_memory_format) + if elem_updated: + setattr(out, attr, new_elem) + + return out, out_memory_format, updated + + +# This is a version of functionalization that is specifically designed +# for the AOTAutograd use case. +# +# Unlike functorch's variant, this doesn't use the functorch level system, +# instead it directly uses PyTorch's conventional dispatcher to hit the +# functionalization key. In particular, this means that FunctionalTensorWrapper +# can have autograd data stored directly on it. +# +# In typical AOTAutograd usage, the dispatch key order will look like: +# +# Autograd - Functionalization ~~~~> Proxy Mode - Fake Tensor +# outer tensor inner tensor +# +# Returns: +# - ViewAndMutationMeta, telling us metadata about the inputs and outputs, and +# The list of outputs from the forward, but **only** the outputs that we need +# to pass in as tangents into the backward. +# Specifically, aliased outputs from the forward get regenerated, and don't participate +# in the compiled backward function. +def run_functionalized_fw_and_collect_metadata( + f: Callable[..., Any], + *, + flat_args_descs: list[AOTInput], + keep_input_mutations: bool, + # Note: this is guaranteed to be set when running under dynamo + static_input_indices: list[int] | None = None, + pre_dispatch: bool = False, +) -> Callable[..., ViewAndMutationMeta]: + memo: dict[Tensor, Tensor] = {} + + # TODO: see if we can rewrite this to be more accurate using + # overload + def _to_fun(t: object) -> object: + if isinstance(t, Tensor): + if t in memo: + return memo[t] + r = to_fun(t) + memo[t] = r + return r + else: + return t + + @simple_wraps(f) + def inner(*flat_args: Any) -> ViewAndMutationMeta: + # This function is meant to be run with the forward, which expects a flat list of tensor/symint/other args. + if not all( + isinstance(a, tuple(KNOWN_TYPES)) or is_custom_class(type(a)) + for a in flat_args + ): + raise AssertionError("all flat_args must be KNOWN_TYPES or opaque types") + + input_info: list[InputAliasInfo] = [] + output_info: list[OutputAliasInfo] = [] + + prior_grad_enabled = torch.is_grad_enabled() + prior_autocast_states = _get_autocast_states() + + # See Note [Disabling Functionalize TLS Above Python Functionalization] + disable_above = torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + + # It doesn't matter if we run this under predispatch or not because it is + # only for figuring out metadata + mode = FunctionalTensorMode( + _allow_token_discovery=True, + _keep_input_mutations=keep_input_mutations, + ) + suppress_pending = contextlib.nullcontext() + fake_mode = detect_fake_mode() + if fake_mode and (shape_env := fake_mode.shape_env): + suppress_pending = shape_env.ignore_fresh_unbacked_symbols() + with disable_above, mode, suppress_pending, disable_autocast_cache(): + # precondition: The passed in function already handles unflattening inputs + flattening outputs + flat_f_args = pytree.tree_map(_to_fun, flat_args) + flat_f_args_descs = flat_args_descs + flat_f_outs = f(*flat_f_args) + + # Assert that f does NOT have an AOTOutputs in it, easy mistake to + # make! You need to drop the second output before calling this + # function + if pytree.tree_any(lambda x: isinstance(x, AOTOutput), flat_f_outs): + raise AssertionError( + f"{f} returned AOTOutput when it shouldn't. Did you remember to wrap the " + "function with without_output_descs before passing it here?" + ) + + # NB: this is just to setup the input descriptors, we will + # recreate these descriptors (with the same convention!) when we + # actually do the trace + flat_f_outs_descs = [PlainAOTOutput(i) for i in range(len(flat_f_outs))] + + # We didn't do any tracing, so we don't need to process the + # unbacked symbols, they will just disappear into the ether. + # Also, prevent memoization from applying. + if fake_mode: + fake_mode.epoch += 1 + fake_mode.reset_nt_tensor_id_counter() + + if prior_autocast_states != _get_autocast_states(): + raise RuntimeError( + "AOTAutograd does not support tracing graphs that mutate the autocast state. " + "Dynamo will only insert autocast context managers (e.g. with torch.autocast(..)) into the graph, " + "which will unwind all of their mutations to autocast state before the graph exits. " + "If you encounter this error while using torch.compile, please file a bug." + ) + + # Inspect the state of the input tensor functional wrapper to detect input mutation info + # If inp[i] has a metadata-only mutation, then maybe_inputs_with_mutated_metadata[i] contains the updated version + for arg, f_arg in zip(flat_args, flat_f_args): + mutates_data = has_data_mutation(f_arg) + mutates_metadata = has_metadata_mutation( + f_arg, arg, check_only_storage_mutation=False + ) + mutates_storage_metadata = has_metadata_mutation( + f_arg, arg, check_only_storage_mutation=True + ) + mutations_hidden_from_autograd = are_all_mutations_hidden_from_autograd( + f_arg + ) + mutations_under_no_grad_or_inference_mode = ( + mutates_data + and are_all_mutations_under_no_grad_or_inference_mode(f_arg) + ) + mutation_inductor_storage_resize = was_inductor_storage_resized(f_arg) + + if mutates_storage_metadata: + mutates_data = False + + requires_grad = isinstance(f_arg, torch.Tensor) and f_arg.requires_grad + + input_info.append( + InputAliasInfo( + is_leaf=isinstance(arg, Tensor) and safe_is_leaf(arg), + mutates_data=mutates_data, + mutates_metadata=mutates_metadata, + mutations_hidden_from_autograd=mutations_hidden_from_autograd, + mutates_storage_metadata=mutates_storage_metadata, + mutation_is_shallow_copy_data=was_shallow_copy_data(f_arg), + mutations_under_no_grad_or_inference_mode=mutations_under_no_grad_or_inference_mode, + mutation_inductor_storage_resize=mutation_inductor_storage_resize, + requires_grad=requires_grad, + keep_input_mutations=keep_input_mutations, + ) + ) + + # If a function involves creating a tensor, and returning a view of it, such that its _base is the intermediate, + # We need to make sure our graph returns the _base as a graph output, and we manually recreate the view + # to return to the user. Why? The backend compiler is free to (incorrectly) not set requires_grad + # on the base tensor, but we are obligated to properly set requires-gradness on the real output. + + inp_storage_refs = { + StorageWeakRef(inpt.untyped_storage()): idx + for idx, inpt in enumerate(flat_f_args) + if isinstance(inpt, Tensor) + } + + # We need inp tensor id's to be able to tell if an outputs **are** inputs. + inp_tensor_ids = {id(inpt) for inpt in flat_f_args if isinstance(inpt, Tensor)} + # We need output tensor id's to tell if any output._base` attributes **are** other outputs. + # (This is also a dict because we need to know that output's index, so we can regenerate + # the alias from it). + out_tensor_ids = {id(o): i for i, o in enumerate(flat_f_outs)} + + # Keep track of which outputs alias other outputs + out_tensor_alias_counts: collections.defaultdict[StorageWeakRef | None, int] = ( + collections.defaultdict(int) + ) + # This tells us, for a given group of outputs that alias each other, + # whether they e.g. all came from an unbind call + num_aliased_tensors_that_are_multi_output_views: collections.defaultdict[ + StorageWeakRef | None, int + ] = collections.defaultdict(int) + + out_storage_to_metadata_key_to_tensors: collections.defaultdict[ + StorageWeakRef | None, + collections.defaultdict[MetadataKey, set[torch.Tensor]], + ] = collections.defaultdict(lambda: collections.defaultdict(set)) + + curr_storage = None + for o in flat_f_outs: + if isinstance(o, torch.Tensor): + curr_storage = StorageWeakRef(o.untyped_storage()) + out_tensor_alias_counts[curr_storage] += 1 + # Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call] + # This is an optimization on top of the "alias of intermediates" logic, + # which you can read more about under Note [AOT Autograd: outputs aliasing inputs or intermediates!] + # + # Before describing the optimization: this is important for AOTAutograd to have good + # perf around, multi-output views. HOWEVER: + # - There is a more generic change to AOTAutograd that we'd like to make, that subsumes this case, + # around using pre-dispatch tracing to partition out a graph so we can faithfully replay all + # views without having to regenerate them at runtime. + # - It's loosely described in this doc (more details will be added soon): + # https://docs.google.com/document/d/1DlfFq8TKbuAn2zyJxLfoW-X1qkkm5PLdHFtySo03QAk/edit + # - Once that change lands, we should just rip out this "optimization", since: + # (1) It will be fully unnecessary + # (2) Although it is only a few lines of code, it is a bit difficult to reason about + # its correctness with the autograd engine in all cases. + # + # + # What is this optimization? Consider the below case: + # def f(x): + # intermediate = x.mul(2) + # # x and intermediate here require grad + # o1, o2, ... o10 = intermediate.unbind(-1) + # return intermediate, o1, o2, ... o10 + # Now, the "intermediate base" handling in AOTAutograd implies that we must do the following: + # (1) return "intermediate as an extra output of the compiled graph + # (2) regenerate each aliased output off of "intermediate", **outside** of the autograd.Function. + # The reason AOTAutograd ordinarily does this is for safety: the autograd engine needs to know + # that o1 through o10 are all aliased, and if we blindly return o1 through o10 from the autograd.Function, + # this information will be hidden. + # In particular, mutating one alias might require autograd to update autograd metadata on the other aliases + # (like their grad_fn, for example, when the autograd engine needs to do view-replay). + # + # However, intermediate_base logic can be bad for backward performance (we sometimes generate + # as_strided calls during the intermediate base logic, which can have a slow backward formula). + # Is it possible to find a set of conditions where it is **safe** to hide the output aliasing from autograd? + # + # For a set of outputs of the graph that alias each other, o_1...o_k, consider: + # (1) They came from the same multi-output view op, e.g. o_1, ..., o_k = intermediate.unbind(0) + # (2) If there are any other aliases of o_1 through o_k (in the example above, intermediate), + # **at most** 1 can escape from the graph (e.g. there is not some other graph input/output + # o_other, that aliases these outputs) + # (3) o_1...o_k all require_grad, they all share the same ._base, and their ._base requires grad. + # This condition is important because it's what causes slowness in the intermediate_base + # codepath of aot_autograd. Ordinarily, o_1...o_k would all get a grad_fn, and + # aot_autograd's view-replay might give each output an AsStridedBackward as its grad_fn. + # "K" AsStridedBackward calls will be *much* slower than a single UnbindBackward. + # In this setup, is it possible to mutate one of the outputs o_i in a way that would affect the autograd meta + # of the other aliases? + # + # Claim: No! Consider a few example (which I'm pretty sure cover all cases of mutation w.r.t. autograd): + # (a) What happens if we mutate any of o_1 through o_k directly? + # Autograd raises an error: + # "RuntimeError: Output 0 of UnbindBackward0 is a view and is being modified inplace. This view is + # the output of a function that returns multiple views. Such functions do not allow the output + # views to be modified inplace. You should replace the inplace operation by an out-of-place one." + # (b) What if we take a view of o_k and mutate it, o_k.view(o_k.shape).mul_(2)? + # Autograd raises the same error- the "multi-output-view"ness of an alias propagates to future views. + # (c) What if we mutate o_k under no_grad? + # Autograd raises the same error + # (d) What if we detach and mutate, e.g. o_k.detach().mul_(2)? + # Autograd allows this, *but* autograd updates all alias's grad_fn's to be error functions when accessed. + # Autograd raises the same error + # (e) What if we try to mutate another alias of o_1...o_k, that was **not** created from a multi-output view? + # We promised that there is at most **one** such alias, e.g. intermediate in the example above. + # You can mutate intermediate, but in eager mode this will change the grad_fn of o_1...o_k + # to be error fn's. + # Since intermediate was the *only* non-multi-output-alias, there are no other aliases + # of `intermediate` around that were produced by the compiled fn and have a valid grad_fn. + # + # Coming back to this optimization: + # Given that it is not possible for mutating one of these aliases to affect the autograd metadata of another alias + # without causing an error in eager mode, we will simple hide the aliasing from autograd during torch.compile + # if all of the above conditions are met. + # This has the slight downside that it's possible to write some "bad" code that autograd will raise an error on + # in eager but fail to during torch.compile, but it has the benefit that this code has much better performance. + # NOTE: if and when we eventually update AOTAutograd to do the "view graph slicing" defined here: + # https://docs.google.com/document/d/1DlfFq8TKbuAn2zyJxLfoW-X1qkkm5PLdHFtySo03QAk/edit, + # then this optimization will probably matter less and might be ok to remove. + is_cur_tensor_multi_out_view = isinstance( + o, FunctionalTensor + ) and torch._functionalize_is_multi_output_view( # type: ignore[attr-defined] + o.elem + ) + if is_cur_tensor_multi_out_view: + num_aliased_tensors_that_are_multi_output_views[curr_storage] += 1 + if o.requires_grad: + out_storage_to_metadata_key_to_tensors[curr_storage][ + MetadataKey.make(o) + ].add(o) + + # maps the id of an intermediate base to its index in the output of the compiled forward + intermediate_base_tensor_id_to_output_idx: dict[int, int] = {} + intermediate_bases: list[torch.Tensor] = [] + intermediate_bases_descs: list[AOTInput] = [] + # Why Do We Care If Storage Changed? + # It's important to understand the implications of storage changes in complex scenarios. Take this example: + # + # def f(x): + # x_storage = x.untyped_storage() + # non_leaf_tensor = torch.ones(4, requires_grad=True).clone() + # + # # Using no_grad() and _unsafe_preserve_version_counter to simulate the .data = operation + # with torch.no_grad(), torch.autograd._unsafe_preserve_version_counter(x): + # x.set_(non_leaf_tensor.untyped_storage()) + # + # out = x.view(-1) + # + # # Restoring x to its original storage, again simulating .data = operation + # with torch.no_grad(), torch.autograd._unsafe_preserve_version_counter(x): + # x.set_(x_storage) + # + # return out + # + # In this scenario, 'x' and 'out' have different shapes and are stored at different memory addresses, aka no aliasing. + # However, due to how set_() and more specifically, set is functionalized, is defined to preserve eager semantics, + # the autograd engine mistakenly assumes that 'x' and 'out' are aliased, treating 'x' as 'out._base'. + # This misinterpretation leads to an 'alias_of_input' flag, causing an unnecessary as_strided() call to be generated, + # which could lead to issues later in the code. + for o, desc in zip(flat_f_outs, flat_f_outs_descs): + functional_tensor_storage_changed = isinstance( + o, FunctionalTensor + ) and torch._functionalize_was_storage_changed( # type: ignore[attr-defined] + o.elem + ) + curr_storage = ( + None + if not isinstance(o, torch.Tensor) + else StorageWeakRef(o.untyped_storage()) + ) + outs_with_identical_metadata_that_require_grad: list[torch.Tensor] = ( + [] + if not isinstance(o, Tensor) + else [ + curr + for curr in out_storage_to_metadata_key_to_tensors[curr_storage][ + MetadataKey.make(o) + ] + if o is not curr + ] + ) + + # See Note [Accessing .grad_fn on FunctionalTensor] + # In-place operations on views will trigger a lazy rebase of the autograd graph; + # this runs during access to the .grad_fn. The rebase logic will invoke view ops + # on FunctionalTensors, so we must enable a FunctionalTensorMode here to ensure + # these op calls succeed. + grad_fn = None + if isinstance(o, Tensor): + with FunctionalTensorMode(): + grad_fn = o.grad_fn + + is_result_of_custom_autograd_fn = False + # Need to check for both custom cpp (CppFunction) and python (BackwardCFunction) + # autograd fns + if type(grad_fn).__name__ == "CppFunction": + is_result_of_custom_autograd_fn = True + if isinstance(grad_fn, torch.autograd.function.BackwardCFunction): + is_result_of_custom_autograd_fn = True + + if not isinstance(o, Tensor): + output_type = OutputType.non_alias + base_idx = None + elif ( + curr_storage in inp_storage_refs + and grad_fn is not None + and is_result_of_custom_autograd_fn + ): + output_type = OutputType.custom_function_view + base_idx = None + elif ( + curr_storage in inp_storage_refs + and not functional_tensor_storage_changed + ): + # pyrefly: ignore [bad-index, index-error] + base_idx = inp_storage_refs[curr_storage] + is_input_tensor = id(o) in inp_tensor_ids + num_aliased_outs = out_tensor_alias_counts[curr_storage] + num_multi_output_view_outs = ( + num_aliased_tensors_that_are_multi_output_views[curr_storage] + ) + num_aliased_outs_that_are_not_multi_output_views = ( + num_aliased_outs - num_multi_output_view_outs + ) + if ( + grad_fn is not None + and num_aliased_outs_that_are_not_multi_output_views == 0 + ): + # See Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call] + # In particular, given: + # def f(x): + # return list(x.unbind(0)) + # The main reason we ordinarily try to regenerate these output aliases outside of the + # compiled autograd.Function is because if any of the outputs are later mutated, + # autograd needs to perform view-replay to regenerate them. + # However, autograd does not allow users to mutate multi-output views + # in any way that can change the autograd metadata of other aliases. + # So we hide this aliasing from autograd here. + log.debug( + "Encountered AOTAutograd case: differentiable outputs that \ +alias each other from a multi-output view call" + ) + output_type = OutputType.non_alias + elif is_input_tensor: + output_type = OutputType.is_input + else: + output_type = OutputType.alias_of_input + elif functional_tensor_storage_changed and id(o) in inp_tensor_ids: + # When there is a set_() on an input, we cannot rely on checking storages + # to detect if we are returning an input (since the inputs storage is different) + if curr_storage is None: + raise AssertionError("curr_storage must not be None") + base_idx = inp_storage_refs[curr_storage] + output_type = OutputType.is_input + + # We only need to handle the intermediate base case when both + # the intermediate base and the output require gradients. + # See Note [AOT Autograd: outputs aliasing inputs or intermediates!] + elif o._base is not None and o.requires_grad and o._base.requires_grad: + num_aliased_outs = out_tensor_alias_counts[curr_storage] + num_multi_output_view_outs = ( + num_aliased_tensors_that_are_multi_output_views[curr_storage] + ) + num_aliased_outs_that_are_not_multi_output_views = ( + num_aliased_outs - num_multi_output_view_outs + ) + # Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call] + if ( + out_tensor_alias_counts[curr_storage] == 1 + or num_aliased_outs_that_are_not_multi_output_views <= 1 + ): + # Note [Intermediate Bases Optimization] + # Normally if we have an output that aliases an intermediate, + # we need to add the extra "intermediate base" logic further down + # to prevent autograd from yelling at us if the user later tries to + # mutate that output. + # However, the common case here is if we have an output that aliases an intermediate, + # but doesn't alias any other outputs. + # In that case, autograd shouldn't have to worry about the aliasing at all + # (if that output is mutated, there are no other live aliases for autograd to worry about). + # The "intermediate bases" can hurt inductor perf by forcing more variables to become outputs. + # So as an optimization, we won't do intermediate base handling in this case. + # Instead, we'll hide the aliasing from autograd using aten._unsafe_view(). + if ( + out_tensor_alias_counts[curr_storage] != 1 + and num_aliased_outs_that_are_not_multi_output_views <= 1 + ): + log.debug( + "Encountered AOTAutograd case: differentiable outputs that alias each other \ +from a multi-output view call" + ) + output_type = OutputType.unsafe_view_alias + base_idx = None + else: + # First, check if o's ._base is an existing output + maybe_existing_out_idx = out_tensor_ids.get(id(o._base)) + if maybe_existing_out_idx is not None: + # Special case where the output is an alias of a graph intermediate, but that intermediate + # is itself also a user output. + output_type = ( + OutputType.alias_of_intermediate_base_is_user_output + ) + base_idx = maybe_existing_out_idx + else: + # Next, check if o's ._base is an intermediate base that we already returned + maybe_existing_base_output_idx = ( + intermediate_base_tensor_id_to_output_idx.get(id(o._base)) + ) + if maybe_existing_base_output_idx is not None: + output_type = OutputType.alias_of_intermediate + base_idx = maybe_existing_base_output_idx + else: + # Otherwise, take o._base and explicitly return it as an output in the compiled graph + new_out_idx = len(intermediate_bases) + base_idx = new_out_idx + # Indicate to the logic later on (when we trace the joint) + # that this particular output should get it's ._base appended to the forward graph outputs + output_type = ( + OutputType.alias_of_intermediate_save_as_output + ) + intermediate_base_tensor_id_to_output_idx[id(o._base)] = ( + new_out_idx + ) + intermediate_bases.append(o._base) + # NB: The desc we picked here is guaranteed to be + # synchronized with the one in + # graph_capture_wrappers.py because we + # SPECIFICALLY notated this output as + # alias_of_intermediate_save_as_output + intermediate_bases_descs.append( + TangentAOTInput(IntermediateBaseAOTOutput(desc)) + ) + elif ( + # See https://github.com/pytorch/pytorch/issues/100348 for this case. + # This protects against the specific case where a user fn returns (output, output.detach()) + out_tensor_alias_counts[curr_storage] > 1 + and len(outs_with_identical_metadata_that_require_grad) > 0 + and not o.requires_grad + ): + # In theory we could use any of these tensors to regenerate the aliased outputs from, + # since they all alias each other and have identical metadata + out_alias = outs_with_identical_metadata_that_require_grad[0] + existing_out_idx = out_tensor_ids[id(out_alias)] + output_type = OutputType.alias_of_intermediate_base_is_user_output + base_idx = existing_out_idx + else: + output_type = OutputType.non_alias + base_idx = None + + if isinstance(o, torch.Tensor): + dynamic_dims = { + i for i, s in enumerate(o.shape) if not is_concrete_int(s) + } + else: + dynamic_dims = None + + # Save the current FunctionalTensor output. + # + # This will be used at runtime for reconstructing output views from + # their respective base tensors. + # + # The FunctionalTensor will be saved if one of the 2 conditions below + # is true: + view_meta_sequence = None + if ( + # 1. If the output_type is either of: + # (i) alias_of_intermediate; + # (ii) alias_of_intermediate_save_as_output; or + # (iii) alias_of_intermediate_base_is_user_output. + # + # No need to worry about in-place view operations here, since + # this functionalization step eliminates mutations. + # + # i.e. we have access to the actual base tensor, before the + # in-place operation was applied. + output_type + in ( + OutputType.alias_of_intermediate, + OutputType.alias_of_intermediate_save_as_output, + OutputType.alias_of_intermediate_base_is_user_output, + ) + ) or ( + # 2. If the output_type is alias_of_input, and no in-place view + # operation was run on the input (base tensor). + # + # In this case, we need to check for metadata mutation because + # the runtime explicitly reconstructs the inputs, before actually + # reconstructing the outputs. Due to in-place view operations, the + # fully reconstructed input may not be this output base tensor + # anymore. + output_type == OutputType.alias_of_input + and base_idx is not None + and not input_info[base_idx].mutates_metadata + ): + if isinstance(o, FunctionalTensor): + view_meta_sequence = ViewMetaSequence(o) + + requires_grad = isinstance(o, torch.Tensor) and o.requires_grad + out_info = OutputAliasInfo( + output_type=output_type, + raw_type=type(o), + base_idx=base_idx, + dynamic_dims=dynamic_dims, + requires_grad=requires_grad, + # A view created under no_grad() inherits requires_grad from + # its base but has no grad_fn and does not participate in + # differentiation. + requires_grad_for_backward=requires_grad + and (o._base is None or grad_fn is not None), + view_meta_sequence=view_meta_sequence, + ) + output_info.append(out_info) + + # See Note [AOT Autograd: Views to avoid tangents aliasing inputs] + def view_avoid_dupes_with_primals(t: object) -> object: + if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t): + return transform_subclass( + t, lambda _, inner_t: view_avoid_dupes_with_primals(inner_t) + ) + if isinstance(t, Tensor): + return t.view(t.shape) + return t + + # This analysis function returns *only* the outputs that are meant to be tangents to the backwards. + # Anything that aliases (inputs returned in the fw due to metadata mutations, or outputs that alias inputs/intermediates) + # are *regenerated* later, and not used directly in the autograd graph + def _plain_fake_tensor_like_subclass(x: Any) -> torch.Tensor: + # pyrefly: ignore [bad-context-manager] + with detect_fake_mode(): + return torch.empty( + x.shape, dtype=x.dtype, device=x.device, layout=x.layout + ) + + def _is_subclass_mutated_input_tangent_always_subclass(inp: object) -> bool: + return ( + isinstance(inp, torch.nested._internal.nested_tensor.NestedTensor) + or torch._functorch.config.disable_guess_zero_tangent_for_mutated_input_subclass + ) + + f_input_tangents_pairs = [ + # Note: [AOTAutograd Tangent Subclassness for mutated inputs] + # Generally when creating tangents to trace with, we assume that tangents will have + # the same subclass-ness as their forward outs + # however: for tangents that correspond to input mutations, in practice it is more likely + # that these tangents will be plain tensors of zeros at runtime, so we tweak our guess + # to assume that these tangents should always be plaint tensors. + # Example: + # def f(x): + # x.mul_(2) + # return x + 1 + # out = f(x) + # out.sum().backward() + # In the above code, we will have a tangent "x_updated_tangent", + # which will be a plain tensor of zeros, *unless* x is used in some compute after executing f + # + # However, there are exceptions to this logic. If a view is created from mutated input and is used in backward, + # The tangent for this subclass input will be a subclass tensor. + # Example: + # def f(a, b): + # a.mul_(2) + # b.mul_(3) + # return b.view(b.shape), a + b + # a_out, b_out = f(..., Subclass) + # (a * b).sum().backward() + # + # We can not deduce it easily now, so introducing a debug config to be able to turn off this for specific cases. + # NJT guarantees to have its tangent as NJT, because it has dedicated integration in Autograd + # See torch/csrc/autograd/python_function.cpp, use_zeros_like. + ( + ( + _plain_fake_tensor_like_subclass(inp) + if is_traceable_wrapper_subclass(inp) + and not _is_subclass_mutated_input_tangent_always_subclass(inp) + else inp + ), + TangentAOTInput(InputMutationAOTOutput(inp_desc)), + ) + for inp, inp_desc, info in zip(flat_f_args, flat_f_args_descs, input_info) + if info.mutation_type == MutationType.MUTATED_OUT_GRAPH + and info.mutates_data + and info.requires_grad + ] + f_input_tangents, f_input_tangents_descs = ( + [x[0] for x in f_input_tangents_pairs], + [x[1] for x in f_input_tangents_pairs], + ) + + f_output_tangents_pairs = [ + (o, TangentAOTInput(desc)) + for o, info, desc in zip(flat_f_outs, output_info, flat_f_outs_descs) + if info.output_type + in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + and issubclass(info.raw_type, torch.Tensor) + and info.requires_grad_for_backward + ] + f_output_tangents, f_output_tangents_descs = ( + [x[0] for x in f_output_tangents_pairs], + [x[1] for x in f_output_tangents_pairs], + ) + + # intermediate bases are also included in the backward graph + f_tangents = f_input_tangents + f_output_tangents + intermediate_bases + f_tangents_descs = ( + f_input_tangents_descs + f_output_tangents_descs + intermediate_bases_descs + ) + + # TODO: I'm pretty sure you don't need a tree_map here + traced_tangents = pytree.tree_map(from_fun, f_tangents) + traced_tangents = pytree.tree_map( + view_avoid_dupes_with_primals, traced_tangents + ) + traced_tangents = [ + coerce_tangent_and_suggest_memory_format(tt)[0] + for i, tt in enumerate(traced_tangents) + ] + # NB: update this if the maps above ever change structure. + # Also, it might be helpful to add coercion information to the tangent desc! + traced_tangents_descs = f_tangents_descs + + nonlocal static_input_indices + static_input_indices = static_input_indices or [] + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + passed_indices = set(static_input_indices) + static_input_indices = [ + i + for i, arg in enumerate(flat_args) + if (isinstance(arg, torch.nn.Parameter) or i in passed_indices) + ] + + static_input_logger.debug( + "static input indices metadata analysis: %s", static_input_indices + ) + + f_mutated_inputs = [ + inp + for inp, info in zip(flat_f_args, input_info) + if info.mutation_type == MutationType.MUTATED_OUT_GRAPH + ] + # Build the full list of forward graph outputs so the subclass wrapping + # code knows exactly which graph outputs to wrap back into subclasses. + # Including intermediate_bases unconditionally is safe: they are only + # populated when outputs require grad (line ~539), so they are naturally + # empty during pure inference. In the "downgrade from training to + # inference" path, num_intermediate_bases > 0 is already gated behind + # `assert not req_subclass_dispatch` (aot_autograd.py), so the subclass + # wrapping code that consumes subclass_fw_graph_out_meta never sees them. + f_fw_graph_outs = [*f_mutated_inputs, *flat_f_outs, *intermediate_bases] + fw_graph_outs = pytree.tree_map(from_fun, f_fw_graph_outs) + + grad_enabled_mutation = None + if torch.is_grad_enabled() != prior_grad_enabled: + grad_enabled_mutation = torch.is_grad_enabled() + torch.set_grad_enabled( + prior_grad_enabled + ) # Restore the prior state after tracing it + log.debug( + ( + "grad_mode mutation encountered in graph. " + "Will emit mutation epilogue, to set grad_mode=%s" + ), + grad_enabled_mutation, + ) + + subclass_inp_meta = create_subclass_meta(flat_args) + subclass_fw_graph_out_meta = create_subclass_meta(fw_graph_outs) + subclass_tangent_meta = create_subclass_meta( + traced_tangents, count_symints=False, with_memory_format=True + ) + + metadata = ViewAndMutationMeta( + input_info=input_info, + output_info=output_info, + num_intermediate_bases=len(intermediate_bases), + keep_input_mutations=keep_input_mutations, + traced_tangents=traced_tangents, + traced_tangents_descs=traced_tangents_descs, + subclass_inp_meta=subclass_inp_meta, + subclass_fw_graph_out_meta=subclass_fw_graph_out_meta, + subclass_tangent_meta=subclass_tangent_meta, + grad_enabled_mutation=grad_enabled_mutation, + static_input_indices=static_input_indices, + tokens=mode._tokens, + ) + return metadata + + return inner diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/complex_decomposition.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/complex_decomposition.py new file mode 100644 index 0000000000000000000000000000000000000000..583e0addb15aac48ab5790861ef097f3523d982d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/complex_decomposition.py @@ -0,0 +1,147 @@ +""" +Graph pass to decompose complex-valued operations into real-valued operations. + +This pass runs AFTER functionalization, so the graph is purely functional (no +mutations, no aliasing). It retraces the graph with ComplexTensor dispatch active, +which decomposes each complex op into real-valued sub-ops. The graph signature +(input/output count and dtypes) is preserved: complex inputs get unpacked via +aten.real/aten.imag at the top, and complex outputs get repacked via aten.complex +at the bottom. +""" + +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +import torch +import torch.fx as fx +import torch.fx.traceback as fx_traceback +import torch.utils._pytree as pytree +from torch import Tensor +from torch._subclasses.complex_tensor import ComplexTensor, WrapComplexMode +from torch.fx.experimental.proxy_tensor import make_fx + + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping + + from torch._ops import OpOverload + + +def _can_wrap(value: Any) -> bool: + return ( + isinstance(value, Tensor) + and value.dtype.is_complex + and not isinstance(value, ComplexTensor) + ) + + +def _maybe_wrap(value: Any) -> Any: + if _can_wrap(value): + return ComplexTensor(torch.real(value), torch.imag(value)) + return value + + +def _maybe_unwrap(value: Any) -> Any: + if isinstance(value, ComplexTensor): + return value.as_interleaved() + return value + + +def _has_complex(gm: fx.GraphModule, flat_args: list[Any]) -> bool: + for arg in flat_args: + if _can_wrap(arg): + return True + for node in gm.graph.nodes: + if node.op == "call_function": + val = node.meta.get("val") + if _can_wrap(val): + return True + return False + + +def _aliased_input_indices(op: torch._ops.OpOverload) -> list[int]: + schema = op._schema + ret_aliases = set() + idxs = [] + + for ret in schema.returns: + ret_alias = ret.alias_info + if ret_alias is None: + continue + ret_aliases.update(ret_alias.before_set) + + if len(ret_aliases) == 0: + return idxs + + for i, arg in enumerate(schema.arguments): + if arg.alias_info is None: + continue + if not arg.alias_info.before_set.isdisjoint(ret_aliases): + idxs.append(i) + + return idxs + + +def _collect_storage_aliases(node: fx.Node) -> set[fx.Node]: + seen: set[fx.Node] = set() + stack: list[fx.Node] = [node] + while stack: + n = stack.pop() + if n in seen: + continue + seen.add(n) + if not isinstance(n.target, torch._ops.OpOverload): + continue + idxs = _aliased_input_indices(n.target) + for idx in idxs: + src = n.args[idx] + if isinstance(src, fx.Node): + stack.append(src) + return seen + + +def _assert_no_incorrect_aliasing_mutation(gm: fx.GraphModule) -> None: + """ + In this function, we check that the compiled graph respects aliasing semantics. + + There are three cases in which this check fires: + 1. A complex tensor is mutated in place via an incorrect alias. + The ops that produce incorrect aliases are listed in `INCORRECT_ALIASING_OPS`. + 2. A complex input is mutated in place. This is not allowed because complex inputs + decompose to real and imaginary parts, which are made contiguous for performance. + Therefore, any complex input passed in does not alias the original tensor. + 3. A complex input aliases an output. This is not allowed as the input and output + tensors can't alias each other because of 2. + + In all three cases, we raise an error if possible incorrectness is detected. + """ + for n in gm.graph.nodes: + if ( + isinstance(n.target, torch._ops.OpOverload) + and n.target.overloadpacket == torch.ops.aten.copy_ + and n.args[0].meta["val"].dtype.is_complex + ): + raise RuntimeError( + "Mutating a complex tensor in place is not allowed in a `torch.compile` region." + ) + + +def decompose_complex_in_graph( + gm: fx.GraphModule, + flat_args: list[Any], + decompositions: Mapping[OpOverload, Callable[..., Any]] | None = None, +) -> fx.GraphModule: + if not _has_complex(gm, flat_args): + return gm + + _assert_no_incorrect_aliasing_mutation(gm) + + def wrapper(*args: Any) -> Any: + wrapped = tuple(_maybe_wrap(a) for a in args) + with WrapComplexMode(): + result = fx.Interpreter(gm).run(*wrapped) + return pytree.tree_map(_maybe_unwrap, result) + + with fx_traceback.preserve_node_meta(): + return make_fx(wrapper, decomposition_table=decompositions)(*flat_args) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/descriptors.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/descriptors.py new file mode 100644 index 0000000000000000000000000000000000000000..d1c47f64dacf1b8f4a96551637e9b9bebf3606e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/descriptors.py @@ -0,0 +1,782 @@ +""" +AOTAutograd descriptors are a path-like data structure (similar to pytree +paths and sources) that describe the semantic meaning of an input/output to FX +graphs. Although you may know the input/output meaning at the top level of +the original function you traced, because we have many graph capture wrappers +that change the calling convention, it can be difficult to tell how these +correspond to the actual FX graph you get back, to say nothing about the extra +arguments/outputs for tangents, gradients, etc. Descriptors describe the meaning +of arguments. + +Examples +-------- + +Before we talk about the precise semantics, it's helpful to look at some +examples to get some intuition for the meaning of descriptors. Here are some +input descriptors you might find on the joint FX graph: + +* PlainAOTInput(idx=0) - the first input from the original callable, as is + +* ParamAOTInput(target="mod.weight") - the parameter with FQN mod.weight + +* TangentAOTInput(output=PlainAOTOutput(idx=1)) - the input tangent + corresponding to the gradients for the second output in the forward graph + +* ViewBaseAOTInput(base_of=PlainAOTInput(idx=0)) - it turned out the first + input was actually a (differentiable) view of a tensor which aliased with + another input tensor. We replaced this input with a single input for the + base of all of these inputs, replacing the original inputs (one of which is + mentioned in base_of). We would generate a GradAOTOutput for *this* input + (and not the original PlainAOTInputs!) If you have a joint graph where a + view base like this is undesirable, you can eliminate this by cloning + the views outside of the compiled region (assuming you aren't mutating this + tensor). + +* SubclassGetAttrAOTInput(base=AOTInput(idx=0), attr="inner") - this tensor + corresponds to the "inner" tensor from the tensor subclass that is at the + first index. In general, joint graphs from AOTAutograd never take tensor + subclasses as inputs; they are always unpacked into their constituent plain + tensor pieces; use the descriptors to identify the parts of the tensor that + are related. Note that this can be nested (if you have nested tensor + subclasses!) + +Here are some output descriptors you might find on the Joint FX graph: + +* PlainAOTOutput(idx=0) - the first output from the original forward function, + as is + +* GradAOTOutput(grad_of=PlainAOTInput(idx=1)) - the computed gradient for the + second input to the graph, an output of the backward graph + +* InputMutationAOTOutput(mutated_input=PlainAOTInput(idx=0)) - when the first + input is mutated, the new value to be copied into the first input of the + graph. Sometimes, these outputs can be elided and the ``copy_`` is done directly + in the graph (controlled by keep_input_mutations), but if the input + mutation must be differentiated through we always generate an output like this + +* IntermediateBaseAOTOutput(base_of=PlainAOTOutput(idx=0)) - if we return + multiple outputs which alias each other, we instead replace them with a single + output tensor representing the base of all the aliases. This output indicates + it is the base for /one/ of those original outputs. If this is undesirable in + the joint graph, clone all outputs before returning from the graph. + +* SubclassGetAttrAOTOutput(base=PlainAOTOutput(idx=0), idx="inner") - this + tensor corresponds to the inner tensor of the first original output which + is a tensor subclass. This and other subclass components of that output will + get repacked into a tensor subclass. + +High level semantics +-------------------- + +OK, let's formally define a descriptor. Intuitively, suppose we have:: + + def wrapped_graph(*args): + ret = graph(*in_transform(args)) + return out_transform(ret) + +Then the descriptor for input[i] to graph describes a function fin_i such that:: + + fin_i(args) == in_transform(args)[i] + +and the descriptor for output[j] from graph describes a function fout_j such that:: + + fout_j(out_transform(ret)) == ret[j] + +AKA input descriptors tell you how to get from outer inputs to inner inputs, +while output descriptors tell you how to get from outer outputs to inner +outputs (inverse data flow!) + +We haven't said anything about what these transformations actually do. There +are three major transformations AOTAutograd does (performed in this order): + +* View/mutation handling +* Autograd +* Subclasses + +So intuitively, descriptors are built like this: + +1. **PlainAOTInput, PlainAOTOutput.** + + We start off descriptors describing the exact inputs/outputs of the + original flattened user function. This user function is assumed to already + be flattened; you would chain on pytree KeyPaths to further describe where + in the pytree each input/output lived if you needed to deal with + unflattened functions: this can be done from userland on top of + descriptors, so the main descriptors mechanism doesn't handle it. + +2. **SyntheticBaseAOTInput, ViewBaseAOTInput, MetadataMutationAOTOutput, + InputMutationAOTOutput, IntermediateBaseAOTOutput** + + We deal with mutations and aliasing by removing duplicate PlainAOTInputs + and introduce some new artificial inputs/outputs. These inputs do not + have a straightforward correspondence to the original user inputs, but if + you are implementing a pass that doesn't care about the exact semantics of + inputs, you should handle all of these uniformly in the same way as regular + inputs. + +3. **TangentAOTInput, GradAOTOutput** + + We deal with autograd by introducing a tangent input for every + differentiable AOTOutput (including the new ones introduced above), and a + gradient output for every differentiable AOTInput (also including new ones + introduced above.) The arguments to these AOTInput/AOTOutput can ONLY be + the ones we already have above (from steps 1-2). As AOTAutograd does not + currently support double backwards, you never have tangents of grads or + vice versa (but in the future we could!) + +4. **SubclassGetAttrAOTInput, SubclassGetAttrAOTOutput, et al.** + + We deal with subclasses by introducing flattened inputs/outputs (including + potentially symbolic sizes/strides) for every AOTInput/AOTOutput that was a + subclass. As above, the arguments to these AOTInput/AOTOutput can ONLY be + the ones we have above (from steps 1-3). Recursive subclasses are + supported, so these descriptors can nest with each other (so descriptors + from step 4 are fair game as well.) + +5. **ForwardTokenAOTInput, ForwardTokenAOTOutput, BackwardTokenAOTInput, BackwardTokenAOTOutput.** + + Some extra token inputs/outputs get added, these are synthetic and are just here to + prevent DCE/reordering. + +The important thing about the pipeline is that descriptors can ONLY be +created from top-to-bottom. So for example, you can have:: + + SubclassGetAttrAOTInput(TangentAOTInput(PlainAOTOutput(...))) # OK + +As you can see that PlainAOTOutput -> TangentAOTInput -> +SubclassGetAttrAOTInput is consistent with the pipeline ordering), but you can +NEVER have:: + + TangentAOTInput(SubclassGetAttrAOTOutput(PlainAOTOutput(...)) # BAD + +This is inconsistent; we always do autograd BEFORE we process subclasses! + +Similarly, for example, this is illegal:: + + GradAOTOutput(SubclassGetAttrAOTInput(PlainAOTInput(...))) # BAD + +It is illegal because subclasses are handled *after* create joint during +wrapper construction. Instead, you would have:: + + SubclassGetAttrAOTOutput(GradAOTOutput(PlainAOTInput(...))) # OK + +This intuitively captures the fact that we always to autograd directly on the +subclass, rather than after desugaring the subclass into its inner tensors. + +Descriptor index +---------------- + +Here is a list of all AOTInput/AOTOutput, organized by how likely you need to +handle them: + +* AOTInput + + * Important: + + * PlainAOTInput (the primals!) + * ParamAOTInput + * TangentAOTInput + * SubclassGetAttrAOTInput et al. (if you use subclasses) + + * View related (can be eliminated by cloning inputs to graph; if you don't + eliminate them, make sure to handle pairing them with GradAOTOutput): + + * ViewBaseAOTInput + * SyntheticBaseAOTInput + + * Non-tensor, mostly just ignore them: + + * DummyAOTInput + * PhiloxForwardSeedAOTInput + * PhiloxForwardBaseOffsetAOTInput + * PhiloxBackwardSeedAOTInput + * PhiloxBackwardBaseOffsetAOTInput + * ForwardTokenAOTInput + * BackwardTokenAOTInput + +* AOTOutput + + * Important: + + * PlainAOTOutput + * GradAOTOutput + * SubclassGetAttrAOTOutput et al. (if you use subclasses) + + * More obscure (if not eliminated, make sure you handle pairing them with + TangentAOTInput): + + * InputMutationAOTOutput (can be eliminated if mutations are non-differentiable) + * IntermediateBaseAOTOutput (can be eliminated by cloning outputs of graph) + * MetadataMutationAOTOutput (uhh, just don't mutate metadata?) + + * Non-tensor, mostly just ignore them: + + * PhiloxUpdatedForwardOffsetAOTOutput + * PhiloxUpdatedBackwardOffsetAOTOutput + * ForwardTokenAOTOutput + * BackwardTokenAOTOutput + * DummyAOTOutput + +For convenience, we also have DifferentiableAOTInput and +DifferentiableAOTOutput to help you classify which inputs/outputs can be +wrapped by GradAOTOutput/TangentAOTInput (respectively), which are essentially +all tensor AOTInput/AOTOutput excluding the subclass descriptors. + +Implementation details +---------------------- + +The stylized view above is good for understanding how to interpret +descriptors, but the way that descriptors are generated in code is a bit more +complicated. Specifically, AOTAutograd is structured as a series of wrappers +on the original user function, which are composed together to form the final +function to trace. As a result of this, AOTAutograd ends up first building +the full AOTInputs for a function to be traced (as it builds the wrappers and +modifies the flat arguments to be compatible with the new input signature of +the wrapper), and then in reverse builds up the AOTOutput as it is tracing. + +There is one major exception to this general idea of "build AOTInput first", +and then "build AOTOutput second": when we create TangentAOTInput, we need to +reference AOTOutputs (which output we are the tangents of) which we generally +haven't created yet. There's two ways we deal with this: + +- After the precompile steps (dedup and synthetic base handling), we do an + initial pass to collect forward metadata that produces the initial set of + PlainAOTOutputs which we use to create the tangent inputs. + +- We also sometimes just violate causality and predict that an AOTOutput will + be created in a particular way at some later point in time when we build an + AOTInput. + +As of July 2025, here is an exhaustive description of how inputs/outputs +traverse the wrappers from AOTAutograd, and what descriptors can be introduced +at these phases. + +:: + + Build wrappers (FLOWS DOWN) Run trace (FLOWS UP) + ------------------------------------------------------------------------------------------------- + Begin PlainAOTInput (n/a) + ParamAOTInput + + Precompile dedupe (remove dupes) (nothing) + + Precompile synthetic base SyntheticBaseAOTInput MetadataMutationAOTOutput + ViewBaseAOTInput + + Forward metadata trace PlainAOTOutput (n/a) + MetadataMutationAOTOutput + + Prepare for autograd (nothing) InputMutationAOTOutput + IntermediateBaseAOTOutput + + Create joint TangentAOTInput GradAOTOutput + w/ InputMutationAOTOutput + w/ IntermediateBaseAOTOutput + + Precompile subclass SubclassGetAttrAOTInput et al. SubclassGetAttrAOTOutput et al. + + Effect tokens ForwardTokenAOTInput ForwardTokenAOTOutput + BackwardTokenAOTInput BackwardTokenAOTOutput + + End (n/a) PlainAOTOutput + +It can be helpful to separately write down the input flow and the output flow +for ease of understanding the data flow: + +* Input desc propagation (happens as we build wrappers) + + * [IN] Begin with original calling convention (PlainAOTInput, ParamAOTInput) + * [IN] Precompile dedupe: (removes duplicate AOTInputs) + * [IN] Precompile synthetic base: SyntheticBaseAOTInput, ViewBaseAOTInput + * Forward metadata trace (mini output desc propagation) + + * [OUT] Original output convention: PlainAOTOutput + * [OUT] Precompile synthetic base: MetadataMutationAOTOutput + + * [IN] Prepare for autograd: (nothing) + * [IN] Create joint: TangentAOTInput (potentially w/ + IntermediateBaseAOTOutput, InputMutationAOTOutput) + * [IN] Precompile subclass: SubclassGetAttrAOTInput et al. + * [IN] Effect tokens: ForwardTokenAOTInput, BackwardTokenAOTInput + (Note: BackwardTokenAOTInput is technically generated not by a wrapper but + actually done by token_discovery which implicitly adds extra arguments + to the FX trace on-the-fly.) + +* Trigger a trace with the modified inputs on the wrapper +* Output desc propagation (happens as we unwind from the user function call in trace) + + * [OUT] Begin with original calling convention: PlainAOTOutput + * [OUT] Effect tokens: ForwardTokenAOTOutput, BackwardTokenAOTOutput + * [OUT] Precompile subclass: SubclassGetAttrAOTOutput et al. + * [OUT] Create joint: GradAOTOutput + * [OUT] Prepare for autograd: InputMutationAOTOutput, IntermediateBaseAOTOutput + * [OUT] Precompile synthetic base: MetadataMutationAOTOutput + * [OUT] Precompile dedupe: (nothing) +""" + +import dataclasses + + +# TODO: the is_* predicates are a little suspicious because (1) they're not +# used by anything and (2) they always report False even when a parameter got +# swizzled into a view base or deduped with a non-parameter. It is pretty +# difficult to exercise these cases but it's not clear if you will write code +# that works correctly in those cases. + + +@dataclasses.dataclass(frozen=True) +class AOTInput: + """Describes where an input from an AOTAutograd produced FX graph comes from""" + + def expr(self) -> str: + raise NotImplementedError("Subclasses must implement expr()") + + def is_param(self) -> bool: + """True if this input is a parameter or derived from a parameter (e.g., subclass attr)""" + return False + + def is_buffer(self) -> bool: + """True if this input is a buffer or derived from a buffer (e.g., subclass attr)""" + return False + + def is_tangent(self) -> bool: + """True if this input is a tangent or derived from a tangent (e.g., subclass attr)""" + return False + + +# Note: Currently, our typing discipline for differentiable versus not is not +# very good, so feel free to rely on runtime tests instead. + + +@dataclasses.dataclass(frozen=True) +class DifferentiableAOTInput(AOTInput): + """A subclass that classifies AOTInput that can be wrapped by GradAOTOutput""" + + +@dataclasses.dataclass(frozen=True) +class AOTOutput: + """Describes where an output from an AOTAutograd produced FX graph will + eventually be bundled into the final output""" + + def expr(self) -> str: + raise NotImplementedError("Subclasses must implement expr()") + + def is_grad(self) -> bool: + """True if this output is a grad or derived from a grad (e.g., subclass attr)""" + return False + + +@dataclasses.dataclass(frozen=True) +class DifferentiableAOTOutput(AOTOutput): + """A subclass that classifies AOTOutput that can be wrapped by TangentAOTInput""" + + +# ------------ + +# AOTInput + +# ------------ + + +@dataclasses.dataclass(frozen=True) +class ParamAOTInput(DifferentiableAOTInput): + """The input is a parameter, whose FQN is target""" + + target: str + + def expr(self) -> str: + return f"self.get_parameter({self.target!r})" + + def is_param(self) -> bool: + return True + + def is_buffer(self) -> bool: + return False + + +@dataclasses.dataclass(frozen=True) +class BufferAOTInput(DifferentiableAOTInput): + """The input is a buffer, whose FQN is target""" + + target: str + + def expr(self) -> str: + return f"self.get_buffer({self.target!r})" + + def is_param(self) -> bool: + return False + + def is_buffer(self) -> bool: + return True + + +@dataclasses.dataclass(frozen=True) +class DummyAOTInput(AOTInput): + """In some circumstances, we want to call into a function that expects AOTInput, but + we don't actually care about that logic (most typically, because some code is being used + for both compile-time and run-time; AOTInput processing is not needed in this situation. + Pass a dummy in this situation; but it is better to just have a version of the function + that doesn't have this at all.""" + + idx: int + + def expr(self) -> str: + return f"__dummy{self.idx}" + + +@dataclasses.dataclass(frozen=True) +class PlainAOTInput(DifferentiableAOTInput): + """The input is a plain input, corresponding to a particular positional index. + + Note that AOTInput is always relative to a function with a *flat* calling convention, + e.g., as accepted by `aot_module_simplified`. There are some AOTAutograd APIs that + flatten pytrees, and we don't record PyTree key paths from the flattening (but we + could and should!) + """ + + idx: int + + def expr(self) -> str: + return f"args[{self.idx}]" + + +@dataclasses.dataclass(frozen=True) +class SubclassGetAttrAOTInput(AOTInput): + """Subclass inputs get unpacked into their constituent pieces before going into an FX + graph. This tells you which particular attribute of the subclass this particular + input corresponds to (of the 'base' originally subclass argument.) + """ + + base: AOTInput + attr: str + + def expr(self) -> str: + return f"{self.base.expr()}.{self.attr}" + + def is_param(self) -> bool: + return self.base.is_param() + + def is_buffer(self) -> bool: + return self.base.is_buffer() + + def is_tangent(self) -> bool: + return self.base.is_tangent() + + +@dataclasses.dataclass(frozen=True) +class SubclassSizeAOTInput(AOTInput): + """Which subclass this particular outer size SymInt input (at dim idx) came from.""" + + base: AOTInput + idx: int + + def expr(self) -> str: + return f"{self.base.expr()}.size({self.idx})" + + +@dataclasses.dataclass(frozen=True) +class SubclassStrideAOTInput(AOTInput): + """Which subclass this particular outer stride SymInt input (at dim idx) came from.""" + + base: AOTInput + idx: int + + def expr(self) -> str: + return f"{self.base.expr()}.stride({self.idx})" + + +@dataclasses.dataclass(frozen=True) +class ViewBaseAOTInput(DifferentiableAOTInput): + """ + When multiple differentiable inputs are views of the same input, AOTAutograd will replace all of these + views with a single input representing the base. If this is undesirable, you can clone the views + example inputs before passing them into AOTAutograd. + + TODO: In principle we could report ALL of the inputs who this is a base of. + """ + + base_of: AOTInput + + def expr(self) -> str: + return f"{self.base_of.expr()}._base" + + +@dataclasses.dataclass(frozen=True) +class SyntheticBaseAOTInput(DifferentiableAOTInput): + """This is similar to ViewBaseAOTInput, but this happens when none of the views were differentiable, so + we weren't able to get our hands on the true original view and constructed a synthetic one instead + for the sake of autograd. + """ + + base_of: AOTInput + + def expr(self) -> str: + return f"__make_synthetic_base({self.base_of.expr()})" + + +@dataclasses.dataclass(frozen=True) +class PhiloxForwardSeedAOTInput(AOTInput): + """The seed for functionalized Philox RNG calls, specifically for forward graph.""" + + def expr(self) -> str: + return "__philox_forward_seed" + + +@dataclasses.dataclass(frozen=True) +class PhiloxForwardBaseOffsetAOTInput(AOTInput): + """The offset for functionalized Philox RNG calls, specifically for forward graph.""" + + def expr(self) -> str: + return "__philox_forward_base_offset" + + +@dataclasses.dataclass(frozen=True) +class PhiloxBackwardSeedAOTInput(AOTInput): + """The seed for functionalized Philox RNG calls, specifically for backward graph.""" + + def expr(self) -> str: + return "__philox_backward_seed" + + +@dataclasses.dataclass(frozen=True) +class PhiloxBackwardBaseOffsetAOTInput(AOTInput): + """The offset for functionalized Philox RNG calls, specifically for backward graph.""" + + def expr(self) -> str: + return "__philox_backward_base_offset" + + +@dataclasses.dataclass(frozen=True) +class ForwardTokenAOTInput(AOTInput): + """The world token which is threaded through side-effectful operations""" + + idx: int + + def expr(self) -> str: + return f"__forward_token{self.idx}" + + +@dataclasses.dataclass(frozen=True) +class BackwardTokenAOTInput(AOTInput): + """The world token which is threaded through side-effectful operations, for backwards""" + + idx: int + + def expr(self) -> str: + return f"__backward_token{self.idx}" + + +# Technically the "output" here is redundant, tangents always correspond to +# outputs +# NB: this is marked differentiable as it /would/ be differentiable if we +# support double backwards, but we never generate this today because we +# don't support double backwards. +@dataclasses.dataclass(frozen=True) +class TangentAOTInput(DifferentiableAOTInput): + """An input to the joint graph representing the tangent of an output.""" + + output: DifferentiableAOTOutput + + def __post_init__(self) -> None: + if not isinstance(self.output, DifferentiableAOTOutput): + raise AssertionError( + f"expected output to be DifferentiableAOTOutput, got {type(self.output)}" + ) + + def expr(self) -> str: + return f"__output_tangent({self.output.expr()})" + + def is_tangent(self) -> bool: + return True + + +# ------------ + +# AOTOutput + +# ------------ + + +@dataclasses.dataclass(frozen=True) +class PlainAOTOutput(DifferentiableAOTOutput): + """A plain tensor output at position idx of the output tuple""" + + idx: int + + def expr(self) -> str: + return f"output[{self.idx}]" + + +@dataclasses.dataclass(frozen=True) +class InputMutationAOTOutput(DifferentiableAOTOutput): + """The mutated value of an input tensor, returned so we can appropriately propagate autograd.""" + + mutated_input: AOTInput + + def expr(self) -> str: + return f"__input_mutation({self.mutated_input.expr()})" + + +@dataclasses.dataclass(frozen=True) +class IntermediateBaseAOTOutput(DifferentiableAOTOutput): + """An intermediate base of multiple outputs which alias each other. We only report ONE of + the outputs that contributed to this base""" + + base_of: "AOTOutput" + + def expr(self) -> str: + return f"__intermediate_base({self.base_of.expr()})" + + +# TODO: it's a little dodgy this is differentiable lol, but we do generate +# these BEFORE autograd is handled +@dataclasses.dataclass(frozen=True) +class MetadataMutationAOTOutput(DifferentiableAOTOutput): + idx: int + + def expr(self) -> str: + return f"__aliased_arg_with_metadata_mutation{self.idx}" + + +# NB: this is marked differentiable as it /would/ be differentiable if we +# support double backwards, but we never generate this today because we +# don't support double backwards. +@dataclasses.dataclass(frozen=True) +class GradAOTOutput(DifferentiableAOTOutput): + """An output representing the computed gradient for a differentiable input, in the joint graph""" + + grad_of: DifferentiableAOTInput + + def __post_init__(self) -> None: + if not isinstance(self.grad_of, DifferentiableAOTInput): + raise AssertionError( + f"expected grad_of to be DifferentiableAOTInput, got {type(self.grad_of)}" + ) + + def expr(self) -> str: + return f"__grad({self.grad_of.expr()})" + + def is_grad(self) -> bool: + return True + + +@dataclasses.dataclass(frozen=True) +class PhiloxUpdatedForwardOffsetAOTOutput(AOTOutput): + """The final offset from the functionalized RNG calls, forward only""" + + def expr(self) -> str: + return "__philox_updated_forward_offset" + + +@dataclasses.dataclass(frozen=True) +class PhiloxUpdatedBackwardOffsetAOTOutput(AOTOutput): + """The final offset from the functionalized RNG calls, backward only""" + + def expr(self) -> str: + return "__philox_updated_backward_offset" + + +@dataclasses.dataclass(frozen=True) +class ForwardTokenAOTOutput(AOTOutput): + """The world token output for side-effectful calls, returned so we cannot DCE it, forward only""" + + idx: int + + def expr(self) -> str: + return f"__forward_token{self.idx}" + + +@dataclasses.dataclass(frozen=True) +class BackwardTokenAOTOutput(AOTOutput): + """The world token output for side-effectful calls, returned so we cannot DCE it, backward only""" + + idx: int + + def expr(self) -> str: + return f"__backward_token{self.idx}" + + +# These are seemingly symmetric with their AOTInput counterparts. The way to +# think about it is that a subclass could be an input or an output, and they +# get exploded into plain tensors on the way in and out. So we need +# descriptors for both. +@dataclasses.dataclass(frozen=True) +class SubclassGetAttrAOTOutput(AOTOutput): + """This output will be bundled into a subclass at this location""" + + base: AOTOutput + attr: str + + def expr(self) -> str: + return f"{self.base.expr()}.{self.attr}" + + def is_grad(self) -> bool: + return self.base.is_grad() + + +@dataclasses.dataclass(frozen=True) +class SubclassSizeAOTOutput(AOTOutput): + """This output size will be bundled into a subclass at this location""" + + base: AOTOutput + idx: int + + def expr(self) -> str: + return f"{self.base.expr()}.size({self.idx})" + + +@dataclasses.dataclass(frozen=True) +class SubclassStrideAOTOutput(AOTOutput): + """This output stride will be bundled into a subclass at this location""" + + base: AOTOutput + idx: int + + def expr(self) -> str: + return f"{self.base.expr()}.stride({self.idx})" + + +@dataclasses.dataclass(frozen=True) +class DummyAOTOutput(AOTOutput): + """For cases when you don't actually care about descriptor propagation, do not use under normal + circumstances.""" + + idx: int + + def expr(self) -> str: + return f"__dummy{self.idx}" + + +@dataclasses.dataclass(frozen=True) +class SavedForBackwardsAOTOutput(AOTOutput): + idx: int + + def expr(self) -> str: + return f"__saved_for_backwards_{self.idx}" + + +# Note [Activations with no version counter checks in eager] +# In eager, when a tensor is saved for backward, the autograd engine +# generally performs version counter checks when grabbing the activation +# at backward time. +# One exception is in a custom autograd.Function: if the user stashes a tensor +# for use in the backward using `ctx.foo = foo`, rather than +# `ctx.save_for_backward(foo)`, then the autograd engine will not know +# to perform any checks. +# In torch.compile, we handle autograd by tracing through it ahead of time, +# and wrapping the fw + bw graphs into a custom autograd.Function. +# In order to provide parity with eager around VC checks, though, we need +# to know which activations had gotten this "no VC checks" treatment in eager, +# so we can plumb this info into the AOTAutograd runtime, +# and avoid calling ctx.save_for_backward on these tensors. +# +# This dataclass tells us that a given AOTOutput corresponds to: +# - An activation output from the forward graph +# - that should *not* have its version counter checked at runtime in the backward. +# This is done by stashing this activation on the ctx object directly +@dataclasses.dataclass(frozen=True) +class SavedForBackwardsNoVcCheckAOTOutput(AOTOutput): + idx: int + + def expr(self) -> str: + return f"__saved_for_backwards_no_vc_check_{self.idx}" diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/frontend_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/frontend_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8aef1c8f7740c1f4b054d50561a9ff16a1581094 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/frontend_utils.py @@ -0,0 +1,478 @@ +from __future__ import annotations + +import warnings +from contextlib import contextmanager +from typing import Any, cast, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch._custom_class_base import CustomClassBase +from torch._guards import detect_fake_mode +from torch._library.opaque_object import is_custom_class +from torch._subclasses import FakeTensor, FakeTensorMode +from torch._subclasses.fake_tensor import is_fake_tensor, maybe_get_fake_mode +from torch.fx.experimental.proxy_tensor import _pytree_subclasses_that_lose_info +from torch.fx.experimental.symbolic_shapes import ShapeEnv +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .. import config +from .descriptors import BufferAOTInput, DifferentiableAOTInput, ParamAOTInput +from .schemas import ActInputPath, AOTConfig, FakifiedFlatArgs +from .utils import get_loaded_async_collective_tensor_type + + +if TYPE_CHECKING: + from collections.abc import Generator, KeysView + + from torch.distributed._functional_collectives import AsyncCollectiveTensor + + +static_inputs_log = torch._logging.getArtifactLogger( + __name__, "cudagraph_static_inputs" +) + + +def process_inputs( + flat_args: list[Any], + aot_config: AOTConfig, + fake_mode: FakeTensorMode, + shape_env: ShapeEnv | None, + ignore_shape_env: bool = False, +) -> tuple[FakifiedFlatArgs, list[ActInputPath]]: + """Convert real tensor inputs into fake tensors for AOT autograd tracing. + + Called at compile time (not runtime) to produce the fake inputs that AOT + autograd traces through. Each real tensor is converted to a FakeTensor + via ``fake_mode.from_tensor``, preserving shape, dtype, device, and + symbolic shape information from the ShapeEnv. Non-tensor inputs (ints, + SymInts, ScriptObjects) are converted or passed through as appropriate. + + Tensor subclass inputs (DTensor, etc.) are fakified recursively by walking + their ``__tensor_flatten__`` attrs. AsyncCollectiveTensors are resolved via + ``trigger_wait()`` before fakification so they don't appear in the traced + metadata (see below). + + Called from ``aot_function``, ``aot_module_simplified``, and + ``aot_export_module`` — anywhere AOT autograd needs fake inputs before + graph capture. + + Returns: + A tuple of (fakified_args, act_input_paths) where act_input_paths records + which input paths held AsyncCollectiveTensors. The paths are stored on + ViewAndMutationMeta so the runtime wrapper can re-wait those positions. + """ + # Resolve AsyncCollectiveTensors before tracing. ACTs are transient + # eager-mode wrappers for async collective overlap; if they leak into the + # traced graph as input types, AOT autograd records them in + # SubclassCreationMeta for output tangent metadata. At runtime, autograd + # produces plain tensor tangents, causing a type mismatch. Unwrapping + # here prevents ACT from appearing in the traced metadata. + AsyncCollectiveTensor = get_loaded_async_collective_tensor_type() + act_input_paths: list[ActInputPath] = [] + if AsyncCollectiveTensor is not None: + tracing_context = torch._guards.TracingContext.try_get() + for i, a in enumerate(flat_args): + resolved_arg = _resolve_input_async_collectives( + a, i, (), act_input_paths, AsyncCollectiveTensor + ) + # Rebuilt wrapper inputs must keep Dynamo's symbolic context so + # fakeification does not allocate source-less shape symbols. + if resolved_arg is not a and isinstance(resolved_arg, torch.Tensor): + if tracing_context is not None: + if a in tracing_context.tensor_to_context: + tracing_context.tensor_to_context[resolved_arg] = ( + tracing_context.tensor_to_context[a] + ) + flat_args[i] = resolved_arg + + with fake_mode: + + def convert(idx: int, x: Any) -> Any: + nonlocal ignore_shape_env + if shape_env is not None and not ignore_shape_env: + from torch._dynamo.source import ConstantSource + + if isinstance(x, int): + # We always specialize on scalar values in export. + if aot_config.is_export: + return x + source = ConstantSource(f"sym_{idx}") + return shape_env.create_symintnode( + shape_env.create_symbol(x, source, positive=x >= 0), + hint=x, + source=source, + ) + if isinstance(x, torch.ScriptObject) or is_custom_class(type(x)): + return torch._library.fake_class_registry.maybe_to_fake_obj( + fake_mode, x + ) + if not isinstance(x, torch.Tensor): + return x + if is_fake_tensor(x): + # In the case of cross compilation we will have example inputs + # with a different fake mode than our tracing fake mode. + # In these cases we want to clone the fake tensor into our + # inner fake mode. + if maybe_get_fake_mode(x) is not fake_mode: + return fake_mode.from_tensor(x) + return x + if is_traceable_wrapper_subclass(x): + attrs, _ = x.__tensor_flatten__() + # See if all inner tensors are FakeTensors from this mode + all_this_fake = True + for a in attrs: + match getattr(x, a): + case FakeTensor() as v: + if v.fake_mode is not fake_mode: + # FakeTensor subclass from a different mode. + # Fall through to refakify. + all_this_fake = False + break + case torch.Tensor(): + all_this_fake = False + break + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + if all_this_fake: + return x + + # see note [Tensor Fakification and Symbol Caching] + symbolic_context = None + source = None + trace = True + if tracing_context := torch._guards.TracingContext.try_get(): + if x in tracing_context.tensor_to_context: + symbolic_context = tracing_context.tensor_to_context[x] + source = symbolic_context.tensor_source + # We already fakeified this tensor in Dynamo, don't + # dump the trace for it again + trace = False + if ( + idx < aot_config.num_params_buffers + and config.static_weight_shapes + and not symbolic_context + ): + # TODO: Ensure that this codepath is never exercised from + # Dynamo + return fake_mode.from_tensor(x, static_shapes=True) + + result = fake_mode.from_tensor( + x, + static_shapes=ignore_shape_env, + symbolic_context=symbolic_context, + source=source, + trace=trace, + ) + return result + + return FakifiedFlatArgs( + [convert(idx, x) for idx, x in enumerate(flat_args)] + ), act_input_paths + + +def _resolve_input_async_collectives( + x: object, + idx: int, + attr_path: tuple[str, ...], + act_input_paths: list[ActInputPath], + AsyncCollectiveTensor: type[AsyncCollectiveTensor], +) -> object: + """Wait on ACT inputs, recording each top-level or wrapper-subclass path.""" + if isinstance(x, AsyncCollectiveTensor): + act_input_paths.append((idx, attr_path)) + return x.trigger_wait() + + if not is_traceable_wrapper_subclass(x): + return x + + attrs, meta = x.__tensor_flatten__() + inner_tensors: dict[str, Any] | None = None + for attr in attrs: + inner = getattr(x, attr) + match inner: + case CustomClassBase(): + continue + case torch.Tensor(): + resolved_inner = _resolve_input_async_collectives( + inner, + idx, + (*attr_path, attr), + act_input_paths, + AsyncCollectiveTensor, + ) + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(inner)}" + ) + + if resolved_inner is not inner: + if inner_tensors is None: + inner_tensors = {a: getattr(x, a) for a in attrs} + inner_tensors[attr] = resolved_inner + + if inner_tensors is None: + return x + + return type(x).__tensor_unflatten__( # type: ignore[attr-defined] + inner_tensors, meta, x.size(), x.stride() + ) + + +def construct_fake_mode( + flat_args: list[Any], aot_config: AOTConfig +) -> tuple[FakeTensorMode, ShapeEnv | None]: + fake_mode = detect_fake_mode(flat_args) + if fake_mode is None: + shape_env = ShapeEnv() if aot_config.dynamic_shapes else None + fake_mode = FakeTensorMode(shape_env=shape_env) + else: + shape_env = fake_mode.shape_env + return (fake_mode, shape_env) + + +def _try_get_metadata_from_dynamo( + mod: torch.nn.Module, + param_keys: KeysView[str], + full_args_num: int, + full_args_descs: list[DifferentiableAOTInput], +) -> tuple[list[torch._guards.Source | None] | None, list[int]]: + """ + Metadata is forwarded from Dynamo to AOTDispatch via special fields on GraphModule. + We first verify that `mod` does come from Dynamo, then we handle cases where + metadata might be missing. + + Returns: + aot_autograd_arg_pos_to_source: used to dedup params and their guards + static_input_indices: used to identify static inputs for cudagraphs + """ + # Note [Assumption on Dynamo Metadata] + # This function assumes a graph module from dynamo provides `dynamo_compiled_id`, + # _param_name_to_source, and every placeholder node has `_dynamo_source` attributes. + # When gm is modified (e.g., DDPOptimizer via split_module), metadata needs to + # be propagated in order to be recognized as a dynamo graph + + if not (isinstance(mod, torch.fx.GraphModule) and "dynamo_compile_id" in mod.meta): + # graph was not captured by dynamo + return None, [] + + if not hasattr(mod, "_param_name_to_source"): + # is from export + static_input_indices = [ + i + for i, node in enumerate(full_args_descs) + if isinstance(node, (ParamAOTInput, BufferAOTInput)) + ] + return None, static_input_indices + + # We now know this came from dynamo, and (1) we care about guards, + # so setting up aot_autograd_arg_pos_to_source for downstream dedup guards + # can now be done safely. (2) Dynamo logic protects the 1:1 sizing below. + # Additionally, we mark static indices for cudagraphs. + param_name_to_source = cast( + dict[str, torch._guards.Source], mod._param_name_to_source + ) + seen_sources = set() + + aot_autograd_arg_pos_to_source: list[torch._guards.Source | None] = [] + static_input_indices = [] + # Collect the new inputs lifted by aotdispatch + for i, name in enumerate(param_keys): + if name not in param_name_to_source: + raise AssertionError(f"{name} not found in param_name_to_source") + source = param_name_to_source[name] + if source in seen_sources: + raise AssertionError(f"source {source} already in seen_sources") + if source is None: + raise AssertionError(f"source must not be None for {name}") + seen_sources.add(source) + aot_autograd_arg_pos_to_source.append(source) + + static_input_indices.append(i) + + # Collect the dynamo graph inputs + # TODO(mlazos): Revisit if this is still needed. With Dynamo install ID + # matched tensors back into the Fx graph, this might not be necessary. + for pos, node in enumerate(mod.graph.find_nodes(op="placeholder")): + if not hasattr(node, "_dynamo_source"): + raise AssertionError(f"node {node} must have _dynamo_source attribute") + source = node._dynamo_source + # `source`` specifies the source from user code. ddp optimizer may have + # intermediate values becoming submodule placeholders which does not + # have a source + if source is not None and source in seen_sources: + raise AssertionError(f"source {source} already in seen_sources") + seen_sources.add(source) + aot_autograd_arg_pos_to_source.append(source) + source_name = source.name if source else str(source) + + # input[i] in dynamo is now: + # input[i + len(extra_params)] in AOT, + # where extra_params are the params/buffers that dynamo baked into the + # OutputGraph + actual_pos = pos + len(param_keys) + + if "tensor_dict" in node.meta and node.meta["tensor_dict"].get( + "_dynamo_static_input_type", None + ): + static_inputs_log.debug( + "Adding static input pos %s for source %s", actual_pos, source_name + ) + static_input_indices.append(actual_pos) + else: + static_inputs_log.debug( + "Non-static input pos %s for source %s", actual_pos, source_name + ) + + if full_args_num != len(aot_autograd_arg_pos_to_source): + raise AssertionError( + f"full_args_num={full_args_num} != len(aot_autograd_arg_pos_to_source)={len(aot_autograd_arg_pos_to_source)}" + ) + return aot_autograd_arg_pos_to_source, static_input_indices + + +@contextmanager +def _detect_attribute_assignment(mod: torch.nn.Module) -> Generator[None, None, None]: + # Do not allow assignment of tensor attributes during export unless + # the attribute is registered as a buffer. + + NN_MODULE_STD_ATTRS = [ + "_backward_hooks", + "_backward_pre_hooks", + "_buffers", + "_forward_hooks", + "_forward_hooks_always_called", + "_forward_hooks_with_kwargs", + "_forward_pre_hooks", + "_forward_pre_hooks_with_kwargs", + "_is_full_backward_hook", + "_load_state_dict_post_hooks", + "_load_state_dict_pre_hooks", + "_modules", + "_non_persistent_buffers_set", + "_parameters", + "_state_dict_hooks", + "_state_dict_pre_hooks", + "training", + ] + NN_MODULE_LAZY_STD_ATTRS = [ + "_initialize_hook", + "_load_hook", + ] + STD_ATTRS = { + *NN_MODULE_STD_ATTRS, + *NN_MODULE_LAZY_STD_ATTRS, + } + + def _get_attributes(mod: torch.nn.Module) -> dict[str, Any]: + # return any attributes of a module that are not standard attributes + return {k: v for k, v in mod.__dict__.items() if k not in STD_ATTRS} + + def _get_all_module_attributes(mod: torch.nn.Module) -> dict[str, dict[str, Any]]: + # return attributes from all modules and submodules + result = {} + for name, submodule in mod.named_modules(): + result[name] = _get_attributes(submodule) + return result + + def _restore_all_module_attributes( + mod: torch.nn.Module, snapshot: dict[str, dict[str, Any]] + ) -> None: + # restore attributes to all modules and submodules + for name, submodule in mod.named_modules(): + if name in snapshot: + submodule.__dict__.update(snapshot[name]) + + # save state of attributes before enter + snapshot = pytree.tree_map( + lambda x: x, + _get_all_module_attributes(mod), + is_leaf=lambda x: type(x) in _pytree_subclasses_that_lose_info, + ) + try: + yield + finally: + # after exit, compare state of attributes with snapshot + # to detect which tensor attributes were assigned + + def _collect_assigned_tensor_attributes( + snapshot: dict[str, dict[str, Any]], new_attrs: dict[str, dict[str, Any]] + ) -> list[str]: + assigned_tensor_attributes = [] + + def _compare_values(path: str, old_val: Any, new_val: Any) -> None: + """Recursively compare values, handling containers.""" + # Same object, no change + if old_val is new_val: + return + + if old_val is None or new_val is None: + if isinstance(new_val, torch.Tensor): + assigned_tensor_attributes.append(path) + return + + # Check if it's a tensor that was reassigned + if isinstance(new_val, torch.Tensor): + assigned_tensor_attributes.append(path) + return + + # Handle dict containers + if isinstance(old_val, dict) and isinstance(new_val, dict): + all_keys = set(old_val.keys()) | set(new_val.keys()) + for key in all_keys: + old_item = old_val.get(key) + new_item = new_val.get(key) + _compare_values(f"{path}[{key!r}]", old_item, new_item) + return + + # Handle list/tuple containers + if isinstance(old_val, (list, tuple)) and isinstance( + new_val, (list, tuple) + ): + # Different lengths = mutation happened + max_len = max(len(old_val), len(new_val)) + for i in range(max_len): + old_item = old_val[i] if i < len(old_val) else None + new_item = new_val[i] if i < len(new_val) else None + _compare_values(f"{path}[{i}]", old_item, new_item) + return + + # For other types, just check if they're different objects + # (we don't care about non-tensor mutations) + + for module_name in snapshot.keys() | new_attrs.keys(): + old_module_attrs = snapshot.get(module_name, {}) + new_module_attrs = new_attrs.get(module_name, {}) + + for attr_name in old_module_attrs.keys() | new_module_attrs.keys(): + module_prefix = f"self.{module_name}." if module_name else "self." + full_path = f"{module_prefix}{attr_name}" + + old_val = old_module_attrs.get(attr_name) + new_val = new_module_attrs.get(attr_name) + _compare_values(full_path, old_val, new_val) + + return assigned_tensor_attributes + + new_attrs = _get_all_module_attributes(mod) + assigned_tensor_attributes = _collect_assigned_tensor_attributes( + snapshot, new_attrs + ) + # restore state of all attributes (including, e.g., of primitive types) + _restore_all_module_attributes(mod, snapshot) + + if assigned_tensor_attributes: + if len(assigned_tensor_attributes) > 1: + noun, verb = "attributes", "were" + else: + noun, verb = "attribute", "was" + warnings.warn( + f"The tensor {noun} {', '.join(assigned_tensor_attributes)} {verb} assigned during export. " + "Such attributes must be registered as buffers using the `register_buffer` API " + "(https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_buffer).", + stacklevel=2, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/functional_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/functional_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cd26a80fb560660332887169ee1feb841f08bd7c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/functional_utils.py @@ -0,0 +1,700 @@ +""" +This file contains utilities related to functionalization in AOTAutograd: +1. converting to/from functional tensors +2. detecting Tensor mutations - both metadata and Tensor value +3. regenerating/replaying views from their base +4. checking if a graph is functional i.e. whether it contains any mutation ops +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, TypeGuard + +import torch +from torch import Tensor +from torch._C import _functionalization +from torch._custom_class_base import CustomClassBase +from torch._logging import getArtifactLogger +from torch._subclasses.fake_tensor import is_fake_tensor +from torch._subclasses.functional_tensor import FunctionalTensor +from torch._subclasses.meta_utils import is_sparse_any +from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq, SymIntEqByExpr +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + transform_subclass, +) + + +aot_joint_log = getArtifactLogger(__name__, "aot_joint_graph") + + +def to_fun(t: object) -> Any: + if isinstance(t, Tensor): + if is_traceable_wrapper_subclass(t): + # See Note [Functionalization always runs last] + # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper + # goes at the bottom. + # recurse here, so we can support nested wrapper subclasses + out = transform_subclass(t, lambda _, inner_t: to_fun(inner_t)) + torch._mirror_autograd_meta_to(t, out) # type: ignore[attr-defined] + return out + else: + return FunctionalTensor.to_functional(t) + else: + return t + + +def sync_functional_tensor(t: torch.Tensor) -> None: + if is_traceable_wrapper_subclass(t): + attrs, _ctx = t.__tensor_flatten__() # type: ignore[attr-defined] + for attr in attrs: + match getattr(t, attr): + case Tensor() as inner: + sync_functional_tensor(inner) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + else: + torch._sync(t) + + +# When subclasses are involved, t here will usually look something like: +# SubclassA(SubclassB(FunctionalTensor(_to_fun_tensor(FakeTensor)))) +def from_fun(t: object) -> object: + if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t): + # See Note [Functionalization always runs last] + # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper + # goes at the bottom. + # recurse here, so we can support nested wrapper subclasses + out = transform_subclass(t, lambda _, inner_t: from_fun(inner_t)) + torch._mirror_autograd_meta_to(t, out) # type: ignore[attr-defined] + return out + + if not isinstance(t, FunctionalTensor): + # quick sanity assert + if isinstance(t, torch.Tensor): + if torch._is_functional_tensor(t): # type: ignore[attr-defined] + raise AssertionError("expected non-functional tensor") + return t + sync_functional_tensor(t) + return torch._from_functional_tensor(t.elem) + + +def is_fun(t: object) -> TypeGuard[FunctionalTensor | Tensor]: + if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t): + # See Note [Functionalization always runs last] + # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper + # goes at the bottom. + # recurse here, so we can support nested wrapper subclasses + t_attrs, _ = t.__tensor_flatten__() # type: ignore[attr-defined] + got_fun: bool | None = None + for attr in t_attrs: + match getattr(t, attr): + case Tensor() as v: + fun = is_fun(v) + if got_fun is None: + got_fun = fun + elif got_fun != fun: + raise AssertionError( + "mixed functional/non-functional inner tensors" + ) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return got_fun or False + + return isinstance(t, FunctionalTensor) + + +# t here is either +# (1) A FunctionalTensor(_to_functional_tensor(FakeTensor)) +# (2) A traceable tensor subclass that holds a FunctionalTensor +# (3) Not a tensor +def has_data_mutation(t: object) -> bool: + if is_traceable_wrapper_subclass(t): + attrs, _ = t.__tensor_flatten__() + # A tensor subclass was updated if any of its inner elements were updated + for attr in attrs: + match getattr(t, attr): + case Tensor() as v: + if has_data_mutation(v): + return True + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return False + else: + if isinstance(t, torch.Tensor): + if not isinstance(t, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(t)}") + return torch._functionalize_has_data_mutation(t.elem) # type: ignore[attr-defined] + return False + + +def are_all_mutations_hidden_from_autograd(t: object) -> bool: + if is_traceable_wrapper_subclass(t): + attrs, _ = t.__tensor_flatten__() + # If all inner elements are mutations hidden from autograd, then it is a mutation hidden from autograd. + for attr in attrs: + match getattr(t, attr): + case Tensor() as v: + if not are_all_mutations_hidden_from_autograd(v): + return False + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return True + elif isinstance(t, torch.Tensor): + if not isinstance(t, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(t)}") + return torch._functionalize_are_all_mutations_hidden_from_autograd(t.elem) + else: + return False + + +def are_all_mutations_under_no_grad_or_inference_mode(t: torch.Tensor) -> bool: + if is_traceable_wrapper_subclass(t): + attrs, _ = t.__tensor_flatten__() + for attr in attrs: + match getattr(t, attr): + case Tensor() as v: + if not are_all_mutations_under_no_grad_or_inference_mode(v): + return False + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return True + else: + if not isinstance(t, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(t)}") + return torch._functionalize_are_all_mutations_under_no_grad_or_inference_mode( + t.elem + ) + + +def was_inductor_storage_resized(t: object) -> bool: + if is_traceable_wrapper_subclass(t): + attrs, _ = t.__tensor_flatten__() + for attr in attrs: + match getattr(t, attr): + case Tensor() as v: + if was_inductor_storage_resized(v): + raise RuntimeError( + f"storage resizing is not supported on tensor subclass: {type(t)}" + ) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return False + elif not isinstance(t, torch.Tensor): + return False + else: + if not isinstance(t, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(t)}") + return torch._functionalize_was_inductor_storage_resized(t.elem) + + +def was_shallow_copy_data(t: object) -> bool: + if is_traceable_wrapper_subclass(t): + return False + if not isinstance(t, torch.Tensor): + return False + if not isinstance(t, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(t)}") + return torch._functionalize_was_shallow_copy_data(t.elem) # type: ignore[attr-defined] + + +# f_arg here is either +# (1) A FunctionalTensor(_to_functional_tensor(FakeTensor)) +# (2) A traceable tensor subclass that holds a FunctionalTensor +# (3) Not a tensor +# Assumption: arg promises to be the "original" tensor wrapped by f_arg +# Note: "storage mutations" coming from set_() are a type of metadata mutation. So: +# - check_only_storage_mutation=True: only return true if there was a storage mutation +# - check_only_storage_mutation=False: return true if there was any metadata mutation (including a storage mutation) +def has_metadata_mutation( + f_arg: object, arg: object, *, check_only_storage_mutation: bool +) -> bool: + if is_traceable_wrapper_subclass(f_arg): + attrs, _ = f_arg.__tensor_flatten__() + # A tensor subclass was updated if any of its inner elements were updated + for attr in attrs: + match getattr(f_arg, attr): + case Tensor(): + f_inner_t = getattr(f_arg, attr) + inner_t = getattr(arg, attr) + if has_metadata_mutation( + f_inner_t, + inner_t, + check_only_storage_mutation=check_only_storage_mutation, + ): + return True + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return False + else: + if not isinstance(f_arg, torch.Tensor): + if isinstance(arg, torch.Tensor): + raise AssertionError( + f"f_arg is not a Tensor but arg is: {type(f_arg)} vs {type(arg)}" + ) + return False + if not isinstance(f_arg, FunctionalTensor): + raise AssertionError( + f"expected FunctionalTensor for f_arg, got {type(f_arg)}" + ) + if not is_fake_tensor(arg): + raise AssertionError(f"expected FakeTensor for arg, got {type(arg)}") + + arg_after = torch._from_functional_tensor(f_arg.elem) + # This is true if the current tensor experienced at least one set_() call + maybe_storage_changed = torch._functionalize_was_storage_changed(f_arg.elem) # type: ignore[attr-defined] + # However, multiple set_() calls can cancel out. So we also check whether the + # storage of the tensor has changed. + # Note: if an input experienced two set_() calls that cancel out, **and** + # it experiences a data mutation, we pessimistically think that the set_() + # call is necessary here. We could in theory fix this, but this will + # hopefully never happen in user code, and is not needed for fsdp. + if is_sparse_any(arg): + # TODO:add sparse tensors support to functionalization + same_storages = False + else: + same_storages = StorageWeakRef(arg.untyped_storage()) == StorageWeakRef( + arg_after.untyped_storage() + ) + has_storage_metadata_mutation = maybe_storage_changed and not same_storages + if check_only_storage_mutation: + return has_storage_metadata_mutation + + # storage metadata mutation is a type of metadata mutation, so return true if we saw one + if has_storage_metadata_mutation: + return True + + maybe_metadata_mutated = torch._functionalize_has_metadata_mutation(f_arg.elem) # type: ignore[attr-defined] + # This is true if the current tensor experienced at least one metadata mutation. + # So if false, we know there was no metadata mutation + if not maybe_metadata_mutated: + return False + + # However, multi metadata mutations can cancel out. + # So we also check if the concrete sizes/strides on the tensor have changed. + same_sizes = arg.shape == arg_after.shape + same_strides = arg.stride() == arg_after.stride() + same_offsets = arg.storage_offset() == arg_after.storage_offset() + has_metadata_mutation_ = maybe_metadata_mutated and not ( + same_sizes and same_strides and same_offsets + ) + # We consider a tensor to have been metadata mutated if its storage was mutated through a set_() call. + return has_metadata_mutation_ + + +def gen_alias_from_base( + aliased_base_tensor: Tensor, + target_meta_tensor: Tensor, + target_requires_grad: bool, + target_view_meta_sequence: ViewMetaSequence | None = None, + *, + replay_views: bool, +) -> Tensor: + # Patch the correct requires_grad field of the output tensor, depending on whether: + # (i) the reconstructed output (out) was came from a tensor that requires grad or not; + # and (ii) the concrete returned output does require grad or not. + def patch_requires_grad(out: Tensor) -> Tensor: + if aliased_base_tensor.requires_grad and not target_requires_grad: + out = out.detach() + elif not aliased_base_tensor.requires_grad and target_requires_grad: + out.requires_grad_(True) + return out + + # If provided, use the target functional tensor for replaying the views. + # + # In summary, we use the fact that FunctionalTensorWrapper saves the view + # functions applied to itself (collected during functionalization) so as + # to replay them (view functions) on the aliased_base_tensor. + if ( + replay_views + and target_view_meta_sequence is not None + and not any(vm.has_symbolic_inputs for vm in target_view_meta_sequence.sequence) + ): + out = _functionalization.apply_view_meta_sequence( + aliased_base_tensor, target_view_meta_sequence.sequence + ) + # If re-applying the ViewMeta sequence succeeded, there should be no more + # problems going forward. We just check we got to the target shape and + # patch requires_grad flag. + if out.shape != target_meta_tensor.shape: + raise AssertionError( + "incorrect out shape after application of ViewMeta sequence: " + f"{tuple(out.shape)} (actual) vs {tuple(target_meta_tensor.shape)} (expected)" + ) + return patch_requires_grad(out) + + # Try to do view-replay if possible. + # fall back to .as_strided() if we can't. + if target_meta_tensor._base is not None: + # The base that we want to replay our view off of might have a different shape than the view's original base. + b = target_meta_tensor._base + abt = aliased_base_tensor + # Don't unnecessarily call as_strided if nothing changed; as_strided's + # backward is poorly implemented and slow + if abt is not b and ( + abt.size() != b.size() + or abt.stride() != b.stride() + or abt.storage_offset() != b.storage_offset() + ): + reshaped_base_tensor = aliased_base_tensor.as_strided( + b.size(), b.stride(), b.storage_offset() + ) + else: + reshaped_base_tensor = aliased_base_tensor + out = target_meta_tensor._view_func(reshaped_base_tensor) # type: ignore[attr-defined] + # This shape mismatch can happen due to a bug in inplace/view handling in autograd. + # Try putting a breakpoint here and running + # `test/functorch/test_aotdispatch TestAOTAutograd.test_output_all_alias_types` + # Also, https://github.com/pytorch/pytorch/issues/49825 + # + # As a stopgap, we'll fall back to as_strided. + if out is not None and out.shape == target_meta_tensor.shape: + return patch_requires_grad(out) + + size = target_meta_tensor.size() + stride = target_meta_tensor.stride() + storage_offset = target_meta_tensor.storage_offset() + # If the target lives on a different storage than the aliased base + # (e.g. because inductor's copy_misaligned_inputs cloned the input to + # obtain an aligned buffer), ``target.storage_offset()`` is expressed in + # the cloned storage and would pick the wrong slice when applied via + # ``as_strided()`` on the original aliased base tensor. Translate the + # offset: the traced FakeTensor's storage_offset equals the trace-time + # RELATIVE offset from the input, so add back the runtime input's + # ``storage_offset`` to keep the alias anchored to the correct slice. + # Compare storages via ``_cdata`` (raw c10::Storage handle) rather than + # ``.data_ptr()`` so this is safe on fake/meta storages that would raise + # from ``.data_ptr()`` during AOT tracing. + if ( + aliased_base_tensor.untyped_storage()._cdata + != target_meta_tensor.untyped_storage()._cdata + ): + storage_offset = aliased_base_tensor.storage_offset() + storage_offset + if aliased_base_tensor.is_complex() and not target_meta_tensor.is_complex(): + aliased_out = torch.view_as_real(aliased_base_tensor).as_strided( + size, stride, storage_offset + ) + elif not aliased_base_tensor.is_complex() and target_meta_tensor.is_complex(): + aliased_out = torch.view_as_complex(aliased_base_tensor).as_strided( + size, stride, storage_offset + ) + else: + aliased_out = aliased_base_tensor.as_strided(size, stride, storage_offset) + # For outputs aliasing inputs, we need to check if the requires-gradness has changed. + aliased_out = patch_requires_grad(aliased_out) + # For outputs aliasing inputs, we need to check if the dtype has changed. + # as_strided() is the "most generic" view, but it does not cover cross-dtype views + if aliased_out.dtype != target_meta_tensor.dtype: + aliased_out = aliased_out.view(target_meta_tensor.dtype) + return aliased_out + + +def has_same_metadata(t1: Tensor, t2: Tensor) -> bool: + return ( + guard_or_false(sym_eq(t1.size(), t2.size())) + and guard_or_false(t1.layout == t2.layout) + and ( + is_sparse_any(t1) + or ( + guard_or_false(sym_eq(t1.stride(), t2.stride())) + and guard_or_false(t1.storage_offset() == t2.storage_offset()) + ) + ) + and t1.is_conj() == t2.is_conj() + and t1.is_neg() == t2.is_neg() + ) + + +@dataclass(frozen=True) +class MetadataKey: + """ + This should be equal whenever has_same_metadata would return True + """ + + size: tuple[SymIntEqByExpr, ...] + layout: torch.layout + is_sparse: bool + # these are empty when is_sparse + stride: tuple[SymIntEqByExpr, ...] | None + storage_offset: SymIntEqByExpr | None + is_conj: bool + is_neg: bool + + @staticmethod + def make(t: Tensor) -> MetadataKey: + is_sparse = is_sparse_any(t) + return MetadataKey( + size=tuple(SymIntEqByExpr(s) for s in t.size()), + layout=t.layout, + is_sparse=is_sparse, + stride=None if is_sparse else tuple(SymIntEqByExpr(s) for s in t.stride()), + storage_offset=None if is_sparse else SymIntEqByExpr(t.storage_offset()), + is_conj=t.is_conj(), + is_neg=t.is_neg(), + ) + + +# ViewMeta sequence wrapper for equality comparisons. +# +# Even though we can compare each ViewMeta instance, we compare the resulting +# tensor metadata, instead. That's because the creation of synthetic bases + the +# re-generation of input views might end-up creating a different sequence of +# ViewMeta that is semantically equivalent. i.e. gets to a tensor with the same +# metadata. +# +# Therefore, we store what the end result should look like as serializable +# metadata. +# +# When logging, this class should look like: +# +# ViewMetaSequence(view, select_int, slice_Tensor) +# +# i.e. a parenthesized list of view operations within that ViewMeta sequence. +class ViewMetaSequence: + def __init__(self, tensor: FunctionalTensor) -> None: + if not torch._is_functional_tensor(tensor.elem): + raise AssertionError("expected tensor.elem to be a functional tensor") + self.sequence = _functionalization.get_view_meta_sequence(tensor.elem) + self.metadata = MetadataKey.make(tensor) + + def __repr__(self) -> str: + suffix = len("_ViewMeta") + types = ", ".join(type(vm).__name__[:-suffix] for vm in self.sequence) + return f"ViewMetaSequence({types})" + + def __eq__(self, other: object) -> bool: + # If other is None, then it probably means that we weren't able to recreate + # the ViewMeta sequence. One example is when we update the view metadata by + # calling: create_synthetic_base_metadata. + if other is None: + return True + + # Comparison against any other type is not implemented. + if not isinstance(other, ViewMetaSequence): + return NotImplemented + + return self.metadata == other.metadata + + @classmethod + def _from_parts( + cls, sequence: list[_functionalization.ViewMeta], metadata: MetadataKey + ) -> ViewMetaSequence: + # Rebuild a ViewMetaSequence directly from its parts, bypassing the + # FunctionalTensor-based __init__. This lets the recipe be reconstructed from + # plain values rather than from a live FunctionalTensor or an embedded pickle. + # Sole caller: torch._functorch._aot_autograd.source_emit, when baking a + # ViewMetaSequence into standalone source; keep the attributes set here in sync + # with __init__ (sequence, metadata) or the reconstructed object diverges. + self = cls.__new__(cls) + self.sequence = sequence + self.metadata = metadata + return self + + +# new_arg and arg here are either: +# (1) both a FakeTensor +# (2) both a traceable tensor subclass that holds a FakeTensor +# Pre-condition: the two args are the "old" and "new" inputs from running functionalization. +# When we run functionalization and wrap our inputs into FunctionalTensors, +# we can detect whether or not an input was mutated by checking to see if the inner tensor has changed +# +# Normally it would be enough just to check if arg is new_arg, which is normally enough for functionalization +# to confirm that inputs were not mutated when running the user's model with functionalization on. +# But when we have subclass inputs, we can't rely on that: +# `from_fun(to_fun(x)) is x` will return False, because the call to `from_fun` constructs +# a brand new subclass instance: we are calling __tensor_unflatten__, and going +# from Subclass(FakeTensor) to Subclass(FunctionalTensor(FakeTensor)) +def was_tensor_updated(arg: torch.Tensor, new_arg: torch.Tensor) -> bool: + if is_traceable_wrapper_subclass(arg): + if not is_traceable_wrapper_subclass(new_arg): + raise AssertionError( + f"expected new_arg to be traceable wrapper subclass, got {type(new_arg)}" + ) + attrs, _ = arg.__tensor_flatten__() + new_attrs, _ = new_arg.__tensor_flatten__() + if attrs != new_attrs: + raise AssertionError(f"attrs mismatch: {attrs} != {new_attrs}") + # A tensor subclass was updated if any of its inner elements were updated + for attr in attrs: + match getattr(arg, attr): + case Tensor() as v: + if was_tensor_updated(v, getattr(new_arg, attr)): + return True + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return False + else: + return arg is not new_arg + + +# new_arg and arg here are either: +# (1) both a FakeTensor +# (2) both a traceable tensor subclass that holds a FakeTensor +# Pre-condition: the two args are the "old" and "new" inputs from running functionalization. +# When we run functionalization and wrap our inputs into FunctionalTensors, +# we can detect whether or not an input was mutated by checking to see if the inner tensor has changed, +# but shares storage with the old input +def was_tensor_metadata_updated(arg: Any, new_arg: Any) -> bool: + if is_traceable_wrapper_subclass(arg): + if not is_traceable_wrapper_subclass(new_arg): + raise AssertionError( + f"expected new_arg to be traceable wrapper subclass, got {type(new_arg)}" + ) + attrs, _ = arg.__tensor_flatten__() + new_attrs, _ = new_arg.__tensor_flatten__() + if attrs != new_attrs: + raise AssertionError(f"attrs mismatch: {attrs} != {new_attrs}") + # A tensor subclass was updated if any of its inner elements were updated + for attr in attrs: + match getattr(arg, attr): + case Tensor() as v: + if was_tensor_metadata_updated(v, getattr(new_arg, attr)): + return True + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return False + else: + return arg is not new_arg and StorageWeakRef( + arg.untyped_storage() + ) == StorageWeakRef(new_arg.untyped_storage()) + + +# Returns the number of detected copy_ +def _is_functional_graph(fx_g: torch.fx.Graph) -> tuple[str | None, int]: + allowed_mutation_ops = [ + torch.ops.aten.copy_.default, + torch.ops.aten.set_.source_Tensor, + torch.ops.aten.shallow_copy_data_.default, + ] + if hasattr(torch.ops.fsdp, "copy_"): + allowed_mutation_ops.append(torch.ops.fsdp.copy_.default) + + placeholders = set() + mutation_count = 0 + # NB: It would also be nice to verify that the mutations all happen at the + # end, but we also do some administrative views after mutations so this + # isn't actually true. (TODO: Could this cause problems for Inductor?) + error = None + for n in fx_g.nodes: + if n.op == "placeholder": + placeholders.add(n) + if isinstance(n.target, torch._ops.OpOverload): + if n.target in allowed_mutation_ops: + # Can only copy_/set_ into an input + # this is mostly a hack to avoid failing XLA tests. + # See https://github.com/pytorch/pytorch/pull/122434#issuecomment-2101012113 + if "set_buffer_donor_" not in str(n.args[0]): + if n.args[0] not in placeholders: + error = f"n={str(n)}, n.args[0]={str(n.args[0])}, placeholders={str(placeholders)}, graph={str(fx_g)}" + mutation_count += 1 + else: + if n.target._schema.is_mutable: + error = f"aot_autograd expected to have an entirely functional graph, but found {n.format_node()}" + return error, mutation_count + + +def assert_functional_graph(fx_g: torch.fx.Graph) -> int: + error, mutation_count = _is_functional_graph(fx_g) + if error is not None: + raise AssertionError(error) + return mutation_count + + +def propagate_input_mutation_stacktraces(fx_g: torch.fx.Graph) -> None: + placeholders = set() + for n in fx_g.nodes: + if n.op == "placeholder": + placeholders.add(n) + if isinstance(n.target, torch._ops.OpOverload): + if n.target is torch.ops.aten.copy_.default: + # Can only copy_ into an input, and can only do so once + if "set_buffer_donor_" not in str(n.args[0]): + if n.args[0] not in placeholders: + raise AssertionError( + f"n={str(n)}, n.args[0]={str(n.args[0])}, placeholders={str(placeholders)}, graph={str(fx_g)}" + ) + placeholders.remove(n.args[0]) + copy_from_node = n.args[1] + # Pre-condition: every node has a "stack_trace" field in its meta, + # but copy_() nodes do not (since we manually added them during functionalization). + # Instead, we manually propagate here. + if "stack_trace" in copy_from_node.meta: + n.meta["stack_trace"] = copy_from_node.meta["stack_trace"] + + +def _check_if_mutation_can_be_in_graph( + keep_input_mutations: bool, + mutates_data: bool, + mutates_metadata: bool, + mutations_hidden_from_autograd: bool, + mutations_under_no_grad_or_inference_mode: bool, + mutates_storage_metadata: bool, + mutation_inductor_storage_resize: bool, + requires_grad: bool, +) -> bool: + if keep_input_mutations: + in_graph = ( + mutates_data or mutates_storage_metadata or mutation_inductor_storage_resize + ) and ( + (not mutates_metadata and not requires_grad) + or mutations_hidden_from_autograd + or mutations_under_no_grad_or_inference_mode + ) + else: + in_graph = False + # See Note [set_() Input Mutations in AOTAutograd] + # If there was a `set_()`, we require that all mutations were under no_grad, + # so we can (safely) emit the set_() in the graph at runtime + # resize_() gets the same treatment + if mutation_inductor_storage_resize or mutates_storage_metadata: + op_name = "resize_" if mutation_inductor_storage_resize else "set_" + if not in_graph: + raise AssertionError(f"""\ +Encountered a {op_name} on a graph input, but the input has other mutations that we cannot +keep in the graph. This is not supported today. Current state: + keep_input_mutations={keep_input_mutations} + mutates_data={mutates_data} + mutates_metadata={mutates_metadata} + mutations_hidden_from_autograd={mutations_hidden_from_autograd} + mutations_under_no_grad_or_inference_mode={mutations_under_no_grad_or_inference_mode} + mutation_inductor_storage_resize={mutation_inductor_storage_resize} + requires_grad={requires_grad}""") + return in_graph diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/fx_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/fx_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9446b9c4943b6f6f2336419085a20b7738d4a8ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/fx_utils.py @@ -0,0 +1,324 @@ +""" +This module contains utility functions for working with joint FX graphs with descriptors +that are produced by AOTAutograd. They will NOT work on generic FX graphs. See also +:func:`torch._functorch.aot_autograd.aot_export_joint_with_descriptors`. We also +recommend reading :mod:torch._functorch._aot_autograd.descriptors`. +""" + +from typing import NoReturn + +import torch.fx as fx + +from .descriptors import ( + AOTInput, + AOTOutput, + BufferAOTInput, + DifferentiableAOTInput, + DifferentiableAOTOutput, + GradAOTOutput, + ParamAOTInput, + PlainAOTInput, + PlainAOTOutput, + SubclassGetAttrAOTInput, + SubclassGetAttrAOTOutput, + TangentAOTInput, +) + + +def _raise_autograd_subclass_not_implemented( + n: fx.Node, desc: AOTInput | AOTOutput +) -> NoReturn: + raise RuntimeError( + "Subclasses are currently not supported by this function, but a desugared subclass input " + f"was found at {n} ({desc}). The problem is " + "that there may not necessarily be a 1-1 correspondence between primals/tangents/outputs/grads " + "when subclasses are involved: for example, the primal might be a plain tensor " + "but the tangent a tensor subclass that desugared into multiple plain tensors. " + "It is not clear what exactly you would like this function to do in this case " + "(Collect all nodes for the subclass together? Match up the inner nodes if " + "subclasses match exactly?) If you have a concrete use case, please file an " + "issue so we can understand it and design an API that works for your case." + ) + + +def get_all_input_and_grad_nodes( + g: fx.Graph, +) -> dict[DifferentiableAOTInput, tuple[fx.Node, fx.Node | None]]: + """ + Given a joint graph with descriptors (meta['desc'] on placeholders and + output), returns the node for every input and its corresponding grad + output node if it exists. These tuples are in a dict that is indexed by + the AOTInput descriptor that describes the input. + + NB: *all* forward tensor inputs are returned, including non-differentiable + inputs (which simply have a None grad), so it is safe to use this function + to perform operations on all inputs. (Non-tensor inputs like symbolic + integers, tokens or RNG state are NOT traversed by this function.) + + Args: + g: The FX joint graph with descriptors + + Returns: + A dictionary mapping each DifferentiableAOTInput descriptor to a tuple + containing: + - The input node itself + - The grad (output) node if it exists, None otherwise + + Raises: + RuntimeError: If the joint graph has subclass tensor inputs/outputs; this + is not supported by API as there is not necessarily a 1-1 correspondence + between inputs and grads when subclasses are involved. + """ + input_index: dict[DifferentiableAOTInput, tuple[fx.Node, fx.Node | None]] = {} + for n in g.nodes: + if n.op == "placeholder": + desc = n.meta["desc"] + # Skip inputs that cannot possibly be differentiable + if not isinstance(desc, DifferentiableAOTInput): + continue + if isinstance(desc, SubclassGetAttrAOTInput): + _raise_autograd_subclass_not_implemented(n, desc) + + input_index[desc] = (n, None) + elif n.op == "output": + if "desc" not in n.meta: + raise AssertionError(f"'desc' not in n.meta for {n}: {n.meta}") + desc = n.meta["desc"] + for sub_n, sub_desc in zip(n.args[0], desc): + if isinstance(sub_desc, SubclassGetAttrAOTOutput): + _raise_autograd_subclass_not_implemented(sub_n, sub_desc) + if isinstance(sub_desc, GradAOTOutput): + inp, grad = input_index[sub_desc.grad_of] + if grad is not None: + raise AssertionError( + f"grad already set for {sub_n}, {sub_desc}, {input_index}" + ) + input_index[sub_desc.grad_of] = (inp, sub_n) + return input_index + + +def get_all_output_and_tangent_nodes( + g: fx.Graph, +) -> dict[DifferentiableAOTOutput, tuple[fx.Node, fx.Node | None]]: + """Get all output nodes and their corresponding tangent nodes from a joint graph. + + Similar to get_all_input_and_grad_nodes, but returns output nodes paired with + their tangent nodes (if they exist). This function traverses the graph to find + all differentiable outputs and matches them with their corresponding tangent + inputs used in forward-mode autodiff. + + NB: *all* forward tensor outputs are returned, including non-differentiable outputs, + so you can use this function to perform operations on all outputs. + + Args: + g: The FX joint graph with descriptors + + Returns: + A dictionary mapping each DifferentiableAOTOutput descriptor to a tuple + containing: + - The output node itself + - The tangent (input) node if it exists, None otherwise + + Raises: + RuntimeError: If the joint graph has subclass tensor inputs/outputs; this + is not supported by API as there is not necessarily a 1-1 correspondence + between outputs and tangents when subclasses are involved. + """ + output_index: dict[DifferentiableAOTOutput, tuple[fx.Node, fx.Node | None]] = {} + for n in g.nodes: + if n.op == "output": + desc = n.meta["desc"] + for sub_n, sub_d in zip(n.args[0], desc): + # Skip outputs that cannot possibly be differentiable + if not isinstance(sub_d, DifferentiableAOTOutput): + continue + if isinstance(sub_d, SubclassGetAttrAOTOutput): + _raise_autograd_subclass_not_implemented(sub_n, sub_d) + + output_index[sub_d] = (sub_n, None) + for n in g.nodes: + if n.op == "placeholder": + desc = n.meta["desc"] + if isinstance(desc, SubclassGetAttrAOTInput): + _raise_autograd_subclass_not_implemented(n, desc) + if isinstance(desc, TangentAOTInput): + out, tangent = output_index[desc.output] + if tangent is not None: + raise AssertionError( + f"tangent already set for {n}, {desc}, {output_index}" + ) + output_index[desc.output] = (out, n) + return output_index + + +def get_param_and_grad_nodes( + graph: fx.Graph, +) -> dict[ParamAOTInput, tuple[fx.Node, fx.Node | None]]: + """Get parameter nodes and their corresponding gradient nodes from a joint graph. + + Args: + graph: The FX joint graph with descriptors + + Returns: + A dictionary mapping each ParamAOTInput descriptor to a tuple containing: + - The parameter input node + - The gradient (output) node if it exists, None otherwise + """ + return { + desc: (n, g) + for desc, (n, g) in get_all_input_and_grad_nodes(graph).items() + if isinstance(desc, ParamAOTInput) + } + + +def get_plain_input_and_grad_nodes( + graph: fx.Graph, +) -> dict[PlainAOTInput, tuple[fx.Node, fx.Node | None]]: + """Get plain input nodes and their corresponding gradient nodes from a joint graph. + + Args: + graph: The FX joint graph with descriptors + + Returns: + A dictionary mapping each PlainAOTInput descriptor to a tuple containing: + - The plain input node + - The gradient (output) node if it exists, None otherwise + """ + return { + desc: (n, g) + for desc, (n, g) in get_all_input_and_grad_nodes(graph).items() + if isinstance(desc, PlainAOTInput) + } + + +def get_plain_output_and_tangent_nodes( + graph: fx.Graph, +) -> dict[PlainAOTOutput, tuple[fx.Node, fx.Node | None]]: + """Get plain output nodes and their corresponding tangent nodes from a joint graph. + + Args: + graph: The FX joint graph with descriptors + + Returns: + A dictionary mapping each PlainAOTOutput descriptor to a tuple containing: + - The plain output node + - The tangent (input) node if it exists, None otherwise + """ + return { + desc: (n, g) + for desc, (n, g) in get_all_output_and_tangent_nodes(graph).items() + if isinstance(desc, PlainAOTOutput) + } + + +def _raise_fqn_subclass_not_implemented( + n: fx.Node, desc: AOTInput | AOTOutput +) -> NoReturn: + raise RuntimeError( + "Subclasses are currently not supported by this function, but a desugared subclass input " + f"was found at {n} ({desc}). The problem is " + "that there may not necessarily be a 1-1 correspondence between a FQN and a plain tensor " + "when subclasses are involved: for example, a parameter that is a subclass " + "would desugar into multiple plain tensors, which we can't uniquely assign the " + "FQN to. It's not clear what you want the API to do in this case: do you want to " + "instead return a struct of nodes showing how to assemble the subclass? But you " + "don't (directly) have the metadata for the subclass? If you have a concrete use " + "case, please file an issue so we can understand it and design an API that works for your case." + ) + + +def get_named_param_nodes(graph: fx.Graph) -> dict[str, fx.Node]: + """Get parameter nodes mapped by their fully qualified names. + + This function traverses the graph to find all parameter input nodes and + returns them in a dictionary where keys are the parameter names (FQNs) + and values are the corresponding FX nodes. + + Args: + graph: The FX joint graph with descriptors + + Returns: + A dictionary mapping parameter names (str) to their corresponding FX nodes. + + Raises: + RuntimeError: If subclass tensors are encountered (not yet supported), as + with subclasses a FQN does not necessarily map to a single plain tensor. + """ + r = {} + for n in graph.nodes: + if n.op == "placeholder": + desc = n.meta["desc"] + if isinstance(desc, SubclassGetAttrAOTInput): + _raise_fqn_subclass_not_implemented(n, desc) + elif isinstance(desc, ParamAOTInput): + r[desc.target] = n + return r + + +def get_named_buffer_nodes(graph: fx.Graph) -> dict[str, fx.Node]: + """Get buffer nodes mapped by their fully qualified names. + + This function traverses the graph to find all buffer input nodes and + returns them in a dictionary where keys are the buffer names (FQNs) + and values are the corresponding FX nodes. + + Args: + graph: The FX joint graph with descriptors + + Returns: + A dictionary mapping buffer names (str) to their corresponding FX nodes. + + Raises: + RuntimeError: If subclass tensors are encountered (not yet supported), as + with subclasses a FQN does not necessarily map to a single plain tensor. + """ + r = {} + for n in graph.nodes: + if n.op == "placeholder": + desc = n.meta["desc"] + if isinstance(desc, SubclassGetAttrAOTInput): + _raise_fqn_subclass_not_implemented(n, desc) + elif isinstance(desc, BufferAOTInput): + r[desc.target] = n + return r + + +def get_param_nodes(graph: fx.Graph) -> list[fx.Node]: + """Get all parameter nodes from a graph as a list. + + You can rely on this providing the correct order of parameters you need + to feed into the joint graph (at the very beginning of the argument list, + before buffers). + + Args: + graph: The FX joint graph with descriptors + + Returns: + A list of FX nodes representing all parameters in the graph. + + Raises: + RuntimeError: If subclass tensors are encountered (not yet supported), as + it is not clear if you wanted each individual constituent piece of the + subclasses, or have them grouped up in some way. + """ + return list(get_named_param_nodes(graph).values()) + + +def get_buffer_nodes(graph: fx.Graph) -> list[fx.Node]: + """Get all buffer nodes from a graph as a list. + + You can rely on this providing the correct order of buffers you need + to feed into the joint graph (after parameters). + + Args: + graph: The FX joint graph with descriptors + + Returns: + A list of FX nodes representing all buffers in the graph. + + Raises: + RuntimeError: If subclass tensors are encountered (not yet supported), as + it is not clear if you wanted each individual constituent piece of the + subclasses, or have them grouped up in some way. + """ + return list(get_named_buffer_nodes(graph).values()) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture.py new file mode 100644 index 0000000000000000000000000000000000000000..a511ce7d91d0edfff9a0d467a35b91e10f51313a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture.py @@ -0,0 +1,590 @@ +""" +This module dispatches the graphs to either the forward-only or joint compilation +pathways, taking into account the AOTConfig and the collected ViewAndMutationMetadata. +""" + +import contextlib +import dataclasses +from collections.abc import Callable +from typing import Any + +import torch +import torch.utils._pytree as pytree +import torch.utils.dlpack +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.utils import detect_fake_mode, lazy_format_graph_code +from torch._logging import getArtifactLogger, trace_structured +from torch._subclasses.functional_tensor import FunctionalTensorMode +from torch.fx.experimental.proxy_tensor import make_fx +from torchgen.utils import dataclass_repr + +from .. import config +from .descriptors import AOTInput, BackwardTokenAOTInput +from .functional_utils import ( + assert_functional_graph, + propagate_input_mutation_stacktraces, +) +from .graph_capture_wrappers import ( + aot_dispatch_subclass, + create_functionalized_fn, + create_joint, + fn_input_mutations_to_outputs, + fn_prepped_for_autograd, + handle_effect_tokens_fn, +) +from .schemas import AOTConfig, FxValue, SubclassMeta, TraceFn, ViewAndMutationMeta +from .streams import ( + assign_backward_streams, + assign_epilogue_copy_streams, + insert_backward_syncs, + populate_fw_metadata_with_stream_indices, + sync_deallocations, + wrap_all_sync_nodes_with_control_deps, +) +from .utils import ( + call_and_expect_output_descs, + copy_fwd_metadata_to_bw_nodes, + fn_wrappers, + register_buffer_assignment_hook, + root_module_when_exporting_non_strict, + simple_wraps, + unlift_tokens, +) + + +aot_graphs_log = getArtifactLogger(__name__, "aot_graphs") + + +def _extract_tangent_source_stack_traces( + fx_g: torch.fx.GraphModule, + fw_metadata: ViewAndMutationMeta, +) -> None: + from .descriptors import PlainAOTOutput, TangentAOTInput + + if not fw_metadata.traced_tangents_descs: + return + + output_node = list(fx_g.graph.nodes)[-1] + all_outputs = output_node.args[0] + + stack_traces: list[str | None] = [] + got_one = False + + for desc in fw_metadata.traced_tangents_descs: + stack_trace = None + + if isinstance(desc, TangentAOTInput): + output_desc = desc.output + if isinstance(output_desc, PlainAOTOutput) and output_desc.idx < len( + all_outputs + ): + output_arg = all_outputs[output_desc.idx] + if isinstance(output_arg, torch.fx.Node): + stack_trace = output_arg.meta.get("stack_trace", None) + got_one = True + + stack_traces.append(stack_trace) + + if got_one: + fw_metadata.tangent_source_stack_traces = stack_traces + + +def _create_graph( + f: Callable[..., Any], + args: list[torch.Tensor], + args_descs: list[AOTInput] + | None = None, # keep compat with old clients; maybe we should split into two impls + *, + aot_config: AOTConfig, +) -> torch.fx.GraphModule: + # FunctionalTensorMode must be enabled here. + # See Note [Accessing .grad_fn on FunctionalTensor] + out_descs = None + + if args_descs is None: + inner_f = f + else: + + @simple_wraps(f) + def inner_f(*args: Any) -> Any: + nonlocal out_descs + if out_descs is not None: + raise AssertionError("out_descs must be None") + out, out_descs = call_and_expect_output_descs(f, args) + return out + + if aot_config.disable_functionalization: + ctx = contextlib.nullcontext() + else: + ctx = FunctionalTensorMode( # type: ignore[assignment] + pre_dispatch=aot_config.pre_dispatch, + export=aot_config.is_export, + # Allow token discovery for joint fn tracing as tokens can be used in backward. + _allow_token_discovery=True, + _keep_input_mutations=aot_config.keep_inference_input_mutations, + ) + + with ( + enable_python_dispatcher(), + ctx, + torch._dynamo.eval_frame._use_eager_on_nested_compile(), + ): + fx_g = make_fx( + inner_f, + decomposition_table=aot_config.decompositions, + record_module_stack=True, + pre_dispatch=aot_config.pre_dispatch, + _disable_torch_fn_metadata_mode=aot_config._disable_torch_fn_metadata_mode, + )(*args) + + if args_descs is not None: + flat_args_descs, _ = pytree.tree_flatten(args_descs) + flat_out_descs, _ = pytree.tree_flatten(out_descs) + + # Unfortunately, flat_args_descs is not guaranteed to match the + # number of actual arguments that show up on the FX graph. + # Specifically, allow_token_discovery=True means that we will + # silently add extra token arguments to the backwards graph. + # + # Although there are a few ways to detect what these tokens are, + # we are going to settle for something dodgy but simple to + # implement: match tangents_token placeholders specifically, + # as these are the only placeholders that are created by token + # discovery (NB: there is NO other code that treats this name + # as load bearing, so this is a bit naughty!) + # + # I originally wanted to detect tokens in exactly the same way + # that they are detected at normal runtime, but to be honest + # the normal runtime detection is pretty strange: it seems the + # backward tokens are not reliably at the end of the argument list + # but *precede* the RNG arguments (I don't understand why this is + # the case). And in unlift_tokens, token arguments are detected + # by seeing if they feed into an effects call! Dastardly. Why + # didn't we just introduce a new type. + + i = 0 + j = 0 + for n in fx_g.graph.nodes: + if n.op == "placeholder": + if n.name.startswith("tangents_token"): + n.meta["desc"] = BackwardTokenAOTInput(j) + j += 1 + else: + if i >= len(flat_args_descs): + raise AssertionError( + f"i={i} >= len(flat_args_descs)={len(flat_args_descs)}: " + f"fn_wrappers={fn_wrappers(inner_f)}, " + f"placeholders={[n for n in fx_g.graph.nodes if n.op == 'placeholder']}" + ) + n.meta["desc"] = flat_args_descs[i] + i += 1 + elif n.op == "output": + n.meta["desc"] = flat_out_descs + + return fx_g + + +# TODO: Refactor the following code so detach() persists item_memo +def _detach_and_copy_item_memo(t: torch.Tensor) -> torch.Tensor: + detached_t = t.detach() + if hasattr(t, "item_memo"): + # pyrefly: ignore[missing-attribute] + detached_t.item_memo = t.item_memo + return detached_t + + +@dataclasses.dataclass +class _GraphCaptureTracingResult: + fn_to_trace: Callable[..., Any] + flat_args: Any + flat_args_descs: Any + maybe_subclass_meta: SubclassMeta | None + + +def _detach_traced_inputs(flat_args: Any) -> Any: + if detect_fake_mode(): + detach_tensor = _detach_and_copy_item_memo + else: + + def detach_tensor(t: torch.Tensor) -> torch.Tensor: + return t.detach() + + return pytree.tree_map_only(torch.Tensor, detach_tensor, flat_args) + + +def _prepare_graph_capture_tracing( + fn_to_trace: Callable[..., Any], + flat_args: Any, + flat_args_descs: Any, + flat_fn: TraceFn, + *, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + trace_joint: bool, + joint_fn_handle: Any | None = None, +) -> _GraphCaptureTracingResult: + if aot_config.disable_functionalization: + updated_flat_args, updated_flat_args_descs = flat_args, flat_args_descs + else: + fn_to_trace, updated_flat_args, updated_flat_args_descs = ( + create_functionalized_fn( + fn_to_trace, + flat_args, + flat_args_descs, + meta=fw_metadata, + aot_config=aot_config, + trace_joint=trace_joint, + joint_fn_handle=joint_fn_handle, + ) + ) + + subclass_tracing_info = aot_dispatch_subclass( + fn_to_trace, + updated_flat_args, + updated_flat_args_descs, + is_joint_structure=trace_joint, + meta=fw_metadata, + fw_only=flat_fn, + ) + fn_to_trace = subclass_tracing_info.plain_tensor_trace_fn + updated_flat_args = subclass_tracing_info.plain_tensor_args + updated_flat_args_descs = subclass_tracing_info.plain_tensor_args_descs + + if not aot_config.disable_functionalization: + fn_to_trace, updated_flat_args, updated_flat_args_descs = ( + handle_effect_tokens_fn( + fn_to_trace, + updated_flat_args, + updated_flat_args_descs, + meta=fw_metadata, + trace_joint=trace_joint, + ) + ) + return _GraphCaptureTracingResult( + fn_to_trace=fn_to_trace, + flat_args=updated_flat_args, + flat_args_descs=updated_flat_args_descs, + maybe_subclass_meta=subclass_tracing_info.maybe_subclass_meta, + ) + + +def _create_graph_and_save_traced_inputs( + fn_to_trace: Callable[..., Any], + flat_args: Any, + flat_args_descs: Any, + *, + aot_config: AOTConfig, +) -> tuple[torch.fx.GraphModule, Any]: + saved_flat_args = _detach_traced_inputs(flat_args) + return ( + _create_graph(fn_to_trace, flat_args, flat_args_descs, aot_config=aot_config), + saved_flat_args, + ) + + +def aot_dispatch_base_graph( + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, +) -> tuple[torch.fx.GraphModule, list[FxValue], list[AOTInput], SubclassMeta | None]: + # aot_dispatch_base requires functionalization, but doesn't need to handle as many cases as the autograd case. + # The cases that aot_dispatch_base doesn't need to handle include: + # - outputs that are aliases of graph intermediates + # - outputs that are aliases of graph inputs + # While cases that it does need to handle include: + # - input mutations (including when inputs are aliases of each other) + # - input metadata mutations + fn_to_trace = fn_input_mutations_to_outputs( + flat_fn, + flat_args_descs, + fw_metadata, + keep_data_input_mutations=aot_config.keep_inference_input_mutations, + ) + # TODO: replace with AOTDispatchSubclassWrapper once we refactor + # fn_input_mutations_to_outputs and create_functionalized_fn + # into CompilerWrappers. + tracing_state = _prepare_graph_capture_tracing( + fn_to_trace, + flat_args, + flat_args_descs, + flat_fn, + fw_metadata=fw_metadata, + aot_config=aot_config, + trace_joint=False, + ) + fn_to_trace = tracing_state.fn_to_trace + updated_flat_args_subclasses_desugared = tracing_state.flat_args + updated_flat_args_subclasses_desugared_descs = tracing_state.flat_args_descs + maybe_subclass_meta = tracing_state.maybe_subclass_meta + + aot_graphs_log.debug( + "aot_config id: %s, fw_metadata=%s,subclass_metadata=%s", + aot_config.aot_id, + fw_metadata, + maybe_subclass_meta, + ) + + # We track buffer assignments when exporting in non-strict mode. + # (In contrast, strict mode errors on any attribute assignment.) + mod_when_exporting_non_strict = root_module_when_exporting_non_strict(flat_fn) + assigned_buffers: dict[str, str] = {} + hook = None + if aot_config.is_export and mod_when_exporting_non_strict is not None: + # For any buffer that is assigned, we want to associate it to the final proxy node + # that it is assigned to. This node can then be added as a buffer mutation output. + hook = register_buffer_assignment_hook( + mod_when_exporting_non_strict, assigned_buffers + ) + + try: + ( + fw_module, + saved_updated_flat_args_subclasses_desugared, + ) = _create_graph_and_save_traced_inputs( + fn_to_trace, + updated_flat_args_subclasses_desugared, + updated_flat_args_subclasses_desugared_descs, + aot_config=aot_config, + ) + finally: + if hook is not None: + hook.remove() + hook = None + saved_updated_flat_args_subclasses_desugared_descs = ( + updated_flat_args_subclasses_desugared_descs + ) + + if aot_config.is_export and mod_when_exporting_non_strict is not None: + # We update metadata to consider any assigned buffers as buffer mutations. + i = len(dict(mod_when_exporting_non_strict.named_parameters())) + for name, _ in mod_when_exporting_non_strict.named_buffers(): + if name in assigned_buffers and not fw_metadata.input_info[i].mutates_data: + fw_metadata.input_info[i] = dataclasses.replace( + fw_metadata.input_info[i], mutates_data=True + ) + fw_metadata.num_mutated_inp_runtime_indices += 1 + i += 1 + + # We add nodes corresponding to buffer assignments as output nodes in the graph. + add_nodes = [] + output_node = list(fw_module.graph.nodes)[-1] + for name in assigned_buffers.values(): + for node in fw_module.graph.nodes: + if node.name == name: + add_nodes.append(node) + node.users[output_node] = None + output_node.args = ((*add_nodes, *output_node.args[0]),) + + # As long as we opted to remove input mutations, then + # there should be *NO* mutating ops in the graph at this point. + if not aot_config.disable_functionalization: + copy_count = assert_functional_graph(fw_module.graph) + assign_epilogue_copy_streams(fw_module) + # Wrap sync nodes with control_deps to prevent reordering + wrap_all_sync_nodes_with_control_deps(fw_module) + # Populate fw_metadata with stream indices from the compiled graph + populate_fw_metadata_with_stream_indices(fw_module, fw_metadata) + fw_module.graph.eliminate_dead_code() + fw_module.recompile() + copy_count2 = assert_functional_graph(fw_module.graph) + propagate_input_mutation_stacktraces(fw_module.graph) + if copy_count != copy_count2: + raise AssertionError( + f"copy_count={copy_count} != copy_count2={copy_count2}" + ) + else: + fw_module.graph.eliminate_dead_code() + + # See Note [Side-Effectful Tokens in AOTAutograd] + num_tokens = len(fw_metadata.tokens) + if num_tokens != 0 and config.unlift_effect_tokens: + unlift_tokens(fw_module, fw_metadata, aot_config) + saved_updated_flat_args_subclasses_desugared = ( + saved_updated_flat_args_subclasses_desugared[num_tokens:] + ) + saved_updated_flat_args_subclasses_desugared_descs = ( + saved_updated_flat_args_subclasses_desugared_descs[num_tokens:] + ) + + if aot_config.enable_log: + aot_graphs_log.info( + "%s", + lazy_format_graph_code( + "Forward graph", + fw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + # For more expanded output set this to True (but can't default + # to this because it affects tests): + expanded_def=False, + ), + ) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(fw_metadata), + ) + if maybe_subclass_meta is not None: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_subclass_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(maybe_subclass_meta), + ) + + trace_structured( + "aot_inference_graph", + payload_fn=lambda: fw_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ), + ) + + # TODO: should factor this into a separate function for export that always only returns just the graph. + if aot_config.is_export and maybe_subclass_meta is not None: + raise AssertionError( + "aot_export_module does not support tensor subclass inputs for now." + ) + return ( + fw_module, + saved_updated_flat_args_subclasses_desugared, + saved_updated_flat_args_subclasses_desugared_descs, + maybe_subclass_meta, + ) + + +# Has the precondition that there +# are no duplicate arguments in flat_args (e.g., the same Tensor +# object never shows up twice. However, two tensor inputs MAY alias +# the same storage, so long as they have separate TensorImpls.) +def aot_dispatch_autograd_graph( + flat_fn: TraceFn, + flat_args: list[Any], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, +) -> tuple[ + torch.fx.GraphModule, + tuple[list[Any], list[Any]], + tuple[list[AOTInput], list[AOTInput]], + SubclassMeta | None, +]: + # NB: flat_fn here is the original user function (as far as + # aot_module_simplified is concerned) + + # traced_tangents corresponds to the set of outputs in the traced forward that should get grad_outputs in the traced backward. + # It includes outputs of the original forward, *and* any updated inputs due to input mutations. + # However, it does *not* include any outputs that are aliases of inputs or intermediates, or any metadata-only input mutations. + joint_inputs = (flat_args, fw_metadata.traced_tangents) + joint_inputs_descs = (flat_args_descs, fw_metadata.traced_tangents_descs) + + fn_prepared_for_autograd = fn_prepped_for_autograd( + flat_fn, + flat_args_descs, + fw_metadata, + aot_config, + ) + joint_fn_to_trace = create_joint( + fn_prepared_for_autograd, flat_args_descs, aot_config=aot_config + ) + # pyrefly: ignore[missing-attribute] + joint_fn_handle = joint_fn_to_trace.handle + # TODO: replace with AOTDispatchSubclassWrapper once we refactor + # fn_input_mutations_to_outputs and create_functionalized_fn + # into CompilerWrappers. + tracing_state = _prepare_graph_capture_tracing( + joint_fn_to_trace, + joint_inputs, + joint_inputs_descs, + flat_fn, + fw_metadata=fw_metadata, + aot_config=aot_config, + trace_joint=True, + joint_fn_handle=joint_fn_handle, + ) + joint_fn_to_trace = tracing_state.fn_to_trace + updated_joint_inputs = tracing_state.flat_args + updated_joint_inputs_descs = tracing_state.flat_args_descs + maybe_subclass_meta = tracing_state.maybe_subclass_meta + + # When we call _create_graph, this may mutate the metadata of joint + # inputs. But callers are expecting to get the original joint inputs. So + # we make aliases of all the inputs to make sure we have a copy that + # doesn't get modified. + # + # This destroys requires_grad/grad_fn information. However, backends + # beneath AOTAutograd are indifferent to this information, so it doesn't + # matter. + fx_g, saved_updated_joint_inputs = _create_graph_and_save_traced_inputs( + joint_fn_to_trace, + updated_joint_inputs, + updated_joint_inputs_descs, + aot_config=aot_config, + ) + + # Redundant with the check above, but worth having in case tracing introduced + # a fake tensor. Unlikely. + # See Note: [Fake Modules and AOTAutograd] + torch._dynamo.utils.assert_no_fake_params_or_buffers(fx_g) + + # Have to copy before eliminate_dead_code otherwise the + # fw node match might be erased + copy_fwd_metadata_to_bw_nodes(fx_g) + + # After copying metadata, assign streams to gradient accumulation nodes + assign_backward_streams(fx_g) + + assign_epilogue_copy_streams(fx_g) + + # Insert syncs for newly assigned backward streams + insert_backward_syncs(fx_g) + + # Sync deallocations for tensors where the stream w/ their last usage + # is distinct from their allocation stream + sync_deallocations(fx_g) + + # Wrap sync nodes with control_deps to prevent reordering + # (must be after sync_deallocations which inserts additional sync nodes) + wrap_all_sync_nodes_with_control_deps(fx_g) + + # Populate fw_metadata with stream indices from the compiled graph + # NB: This needs to be done after the above stream assignments + populate_fw_metadata_with_stream_indices(fx_g, fw_metadata) + + # this helps users identify which forward output to call .detach() on. + _extract_tangent_source_stack_traces(fx_g, fw_metadata) + + fx_g.graph.eliminate_dead_code() + if not aot_config.disable_functionalization: + # There should be *NO* mutating ops in the graph at this point. + assert_functional_graph(fx_g.graph) + + fx_g.recompile() + + # TODO: in AOTAutograd, we create metadata like _indices_of_inps_to_detach to detect + # when we need to manually detach() some inputs in the forward. + # Higher order ops might eventually need to do the same. + if aot_config.is_export and maybe_subclass_meta is not None: + raise AssertionError( + "aot_export_module does not support tensor subclass inputs for now." + ) + return ( + fx_g, + saved_updated_joint_inputs, + updated_joint_inputs_descs, + maybe_subclass_meta, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture_wrappers.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..5b3ee4992d30dfcf96339b88554f97e24814522c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture_wrappers.py @@ -0,0 +1,1557 @@ +""" +This module is responsible for transforming functions to be traced into a form +that is easier for the downstream infra (e.g. Autograd, FX, AOTAutograd analysis) +to handle. + +It does so by: +1. functionalization (including RNG functionalzation) +2. creating a joint graph when required +3. transforming mutations into extra outputs +4. dispatching subclasses +""" + +import typing +import warnings +from collections.abc import Callable, Generator +from contextlib import AbstractContextManager, contextmanager, ExitStack, nullcontext +from dataclasses import dataclass +from typing import Any, TypeVar +from unittest.mock import patch + +import torch +import torch.fx.traceback as fx_traceback +import torch.utils._pytree as pytree +from torch import Tensor +from torch._custom_class_base import CustomClassBase +from torch._decomp.decompositions_for_rng import PhiloxStateTracker +from torch._guards import detect_fake_mode +from torch._prims_common import CUDARngStateHelper +from torch.fx.experimental.proxy_tensor import ( + _proxy_tensor_disable_update_tensor_tracker, + get_proxy_mode, + maybe_disable_thunkify, + maybe_enable_thunkify, +) +from torch.fx.experimental.symbolic_shapes import ( + guard_or_true, + PropagateUnbackedSymInts, + sym_eq, +) +from torch.nn.utils import stateless +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils._pytree import TreeSpec + +from .. import config +from .collect_metadata_analysis import run_functionalized_fw_and_collect_metadata +from .descriptors import ( + AOTInput, + AOTOutput, + BackwardTokenAOTOutput, + ForwardTokenAOTInput, + ForwardTokenAOTOutput, + GradAOTOutput, + InputMutationAOTOutput, + IntermediateBaseAOTOutput, + PhiloxBackwardBaseOffsetAOTInput, + PhiloxBackwardSeedAOTInput, + PhiloxForwardBaseOffsetAOTInput, + PhiloxForwardSeedAOTInput, + PhiloxUpdatedBackwardOffsetAOTOutput, + PhiloxUpdatedForwardOffsetAOTOutput, +) +from .functional_utils import ( + _check_if_mutation_can_be_in_graph, + are_all_mutations_hidden_from_autograd, + are_all_mutations_under_no_grad_or_inference_mode, + from_fun, + has_data_mutation, + has_metadata_mutation, + is_fun, + sync_functional_tensor, + to_fun, + was_inductor_storage_resized, +) +from .logging_utils import setup_stacktrace_preservation_hooks +from .schemas import ( + AOTConfig, + FxValue, + InputAliasInfo, + JointTraceFn, + MutationType, + OutputType, + PreppedForAutogradTraceFn, + SubclassMeta, + SubclassTracingInfo, + TraceFn, + ViewAndMutationMeta, +) +from .subclass_utils import ( + create_subclass_meta, + remap_unwrapped_subclass_arg_indices, + requires_subclass_dispatch, + unwrap_tensor_subclasses, + wrap_tensor_subclasses_maybe_joint, +) +from .utils import ( + _is_tangent, + call_and_expect_output_descs, + maybe_to_fresh_input, + simple_wraps, + without_output_descs, +) + + +# This function returns a new function that returns mutated inputs as outputs. +# if keep_data_input_mutations is set, then we assume that data-only mutations +# will be left in the graph, and we only return metadata-mutated inputs as outputs. +def fn_input_mutations_to_outputs( + fn: Callable[..., Any], + args_descs: list[AOTInput], + meta: ViewAndMutationMeta, + keep_data_input_mutations: bool, +) -> Any: + @simple_wraps(fn) + def inner_fn(*args: FxValue) -> tuple[tuple[Any, ...], tuple[Any, ...]]: + outs, outs_descs = call_and_expect_output_descs(fn, args) + if len(meta.output_info) != len(outs): + raise AssertionError( + f"output_info length ({len(meta.output_info)}) != outs length ({len(outs)})" + ) + # The compiled fw will return mutated input tensors, *including* metadata-only mutation. + # However, if keep_data_input_mutations is set, the compiled fw only needs to return metadata-mutated inputs. + # (because data-only input mutations are handled directly in the compiled graph) + mutated_input_pairs = [ + (x, InputMutationAOTOutput(src)) + for (i, (x, src)) in enumerate(zip(args, args_descs)) + if i in meta.mutated_inp_runtime_indices + ] + if mutated_input_pairs: + mutated_inputs_to_return, mutated_inputs_to_return_descs = zip( + *mutated_input_pairs + ) + else: + mutated_inputs_to_return, mutated_inputs_to_return_descs = (), () + return ( + (*mutated_inputs_to_return, *outs), + (*mutated_inputs_to_return_descs, *outs_descs), + ) + + return inner_fn + + +@contextmanager +def disable_autocast() -> Generator[None, None, None]: + with ExitStack() as stack: + autocast_enabled_devices = torch._C._autocast_supported_devices() + for device_type in autocast_enabled_devices: + if hasattr(torch, device_type): + stack.enter_context(torch.amp.autocast(device_type, enabled=False)) + yield + + +# This function takes in a fn with external aliasing and mutation, +# and returns a new fn with no external aliasing and mutation, +# as needed for autograd. +# The main transformations are: +# - Return mutated inputs as extra outputs +# - Clone mutated inputs that require gradients, +# because autograd will require us to pass the pre-mutated inputs into autograd.grad +# - Return intermediate bases of outputs as additional outputs, +# needed to appease autograd.Function +# The new function returns: +# (1) The updated outputs +# (2) A boolean mask of len(new_fn_outputs), +# that can be used to tell autograd.grad which outputs should get tangents +# if we trace the backward. +def fn_prepped_for_autograd( + fn: TraceFn, + args_descs: list[AOTInput], + meta: ViewAndMutationMeta, + aot_config: AOTConfig, +) -> PreppedForAutogradTraceFn: + @simple_wraps(fn) + def inner_fn( + *args: FxValue, + ) -> tuple[tuple[list[FxValue], list[bool]], list[AOTOutput]]: + args_maybe_cloned = [ + maybe_to_fresh_input(i, t, meta) for i, t in enumerate(args) + ] + + outs, outs_descs = call_and_expect_output_descs(fn, args_maybe_cloned) # type: ignore[arg-type] + if not isinstance(outs, (tuple, list)): + raise AssertionError(f"expected outs to be tuple or list, got {type(outs)}") + outs = list(outs) + if len(meta.output_info) != len(outs): + raise AssertionError( + f"output_info length ({len(meta.output_info)}) != outs length ({len(outs)})" + ) + + mutated_input_pairs = [ + (x, InputMutationAOTOutput(src)) + for (i, (x, src)) in enumerate(zip(args_maybe_cloned, args_descs)) + if i in meta.mutated_inp_runtime_indices + ] + if mutated_input_pairs: + mutated_inputs_to_return, mutated_inputs_to_return_descs = zip( + *mutated_input_pairs + ) + else: + mutated_inputs_to_return, mutated_inputs_to_return_descs = (), () + + intermediate_bases = [] + intermediate_bases_descs = [] + for o, info, o_desc in zip(outs, meta.output_info, outs_descs): + if info.output_type == OutputType.alias_of_intermediate_save_as_output: + if not isinstance(o, torch.Tensor): + raise AssertionError( + f"Expected tensor for intermediate base, got {type(o)}" + ) + intermediate_bases.append(o._base) + intermediate_bases_descs.append(IntermediateBaseAOTOutput(o_desc)) + + if meta.num_intermediate_bases != len(intermediate_bases): + raise AssertionError( + f"num_intermediate_bases ({meta.num_intermediate_bases}) != len(intermediate_bases) ({len(intermediate_bases)})" + ) + + # the compiled forward should return (mutated_inputs, user_outs, intermediate_bases) + fw_outs_to_return = *mutated_inputs_to_return, *outs, *intermediate_bases + fw_outs_to_return_descs = ( + *mutated_inputs_to_return_descs, + *outs_descs, + *intermediate_bases_descs, + ) + + # Also return a boolean mask specifying which outputs to this function will be used as tangents + mutated_inputs_grad_mask = [ + meta.input_info[meta.mutated_inp_runtime_indices[i]].mutates_data + and meta.input_info[meta.mutated_inp_runtime_indices[i]].requires_grad + for (i, x) in enumerate(mutated_inputs_to_return) + ] + + # Pass any (non-aliased) outputs in as tangents, since they'll be returned as outputs in the fw + # For outputs that are aliases of intermediates, we will have returned the output's _base as an output in the graph instead, + # which we *should* send to grad() + output_grad_mask = [ + meta.output_info[i].output_type + in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + # Also, only tensor outputs should participate in the backward + # (in particular, Symint outputs in the forward graph shouldn't get tangents) + and issubclass(meta.output_info[i].raw_type, Tensor) + and meta.output_info[i].requires_grad_for_backward + for (i, x) in enumerate(outs) + ] + + intermediate_base_grad_mask = [True for _ in range(len(intermediate_bases))] + + out_grad_mask = ( + mutated_inputs_grad_mask + output_grad_mask + intermediate_base_grad_mask + ) + if len(out_grad_mask) != len(fw_outs_to_return): + raise AssertionError( + f"out_grad_mask length ({len(out_grad_mask)}) != fw_outs_to_return length ({len(fw_outs_to_return)})" + ) + + # Take care to grab and sync the updated inputs from primals_after_cloning (the inputs we actually mutate!) + # and not primals (the preserved inputs, pre-mutation, that we pass to grad()) + # This is annoying: our joint function needs to be aware of functionalization + # (syncing mutated inputs before calling autograd.grad()) + # In theory, we could make the autograd engine do this automatically, although that probably isn't any cleaner. + if not aot_config.disable_functionalization: + for arg in args_maybe_cloned: + if not isinstance(arg, Tensor): + continue + sync_functional_tensor(arg) + + # pyrefly: ignore[bad-return] + return (fw_outs_to_return, out_grad_mask), ( + fw_outs_to_return_descs, + out_grad_mask, + ) + + return inner_fn + + +@dataclass +class JointFnHandle: + post_forward: Callable[..., Any] | None = None + + +# Given a fn, computes the joint. +# NOTE: fn is expects the following behavior: +# (1) fn() needs to return a tuple of (outs, mask), +# where `mask` tells us which outputs are meant to have tangents. +# we don't know this info automatically, because we don't actually want to blindly +# compute tangents for every output that requires grad. +# Specifically, outputs that alias inputs won't participate in the backward and get tangents. +# (2) fn() cannot mutate any inputs that require gradient. +# otherwise, when we compute autograd.grad(), we will not take those input mutations into account +# (the way this is handled is that we ensure any inputs that normally get mutated are cloned first) +def create_joint( + fn: Callable[..., Any], + primals_descs: list[AOTInput] | None = None, + *, + aot_config: AOTConfig, +) -> Callable[..., Any]: + joint_fn_handle = JointFnHandle() + + # post_forward + # NB: this type is inaccurate when primals_descs is None + @simple_wraps(fn) + def inner_fn( + primals: list[FxValue], tangents: list[FxValue] + ) -> tuple[ + tuple[list[FxValue], list[Tensor | None]], + tuple[list[AOTOutput], list[AOTOutput | None]], + ]: + outs_descs = None + if primals_descs is None: + outs, tangent_mask = fn(*primals) + if pytree.tree_any(lambda x: isinstance(x, AOTOutput), tangent_mask): + raise AssertionError( + "tangent_mask should not contain AOTOutput instances" + ) + else: + (outs, tangent_mask), (outs_descs, _) = call_and_expect_output_descs( + fn, + primals, # type: ignore[arg-type] + ) + mode = get_proxy_mode() + if mode is None: + raise AssertionError("Expected non-None proxy mode") + for node in mode.tracer.graph.nodes: + if _is_tangent(node): + node.meta["partitioner_tag"] = "is_backward" + else: + node.meta["partitioner_tag"] = "is_forward" + + # TODO: I think this hook can also be eliminated now + if joint_fn_handle and joint_fn_handle.post_forward: + joint_fn_handle.post_forward(primals) + + if len(tangent_mask) != len(outs): + raise AssertionError( + f"tangent_mask length ({len(tangent_mask)}) != outs length ({len(outs)})" + ) + outs_to_grad = [ + o for needs_tangent, o in zip(tangent_mask, outs) if needs_tangent + ] + if len(outs_to_grad) != len(tangents): + raise AssertionError( + f"outs_to_grad length ({len(outs_to_grad)}) != tangents length ({len(tangents)})" + ) + + # Get the inputs that need gradients + grad_primals: list[torch.Tensor] = [] + inputs_needs_grads = [] + # Note that we're not using primals here, + # being carefully not to pass any mutated inputs into autograd.grad() + for p in primals: + if isinstance(p, Tensor) and p.requires_grad: + inputs_needs_grads.append(True) + if not isinstance(p, torch.Tensor): # Help mypy understand the type + raise AssertionError(f"expected Tensor, got {type(p)}") + grad_primals.append(p) + else: + inputs_needs_grads.append(False) + + # Get the outputs that need gradients + needed_outs: list[Tensor] = [] + needed_tangents: list[Tensor] = [] + for out, tangent in zip(outs_to_grad, tangents): + if isinstance(out, Tensor) and out.requires_grad: + # A bit sketchy, but fixes e.g. test_aot_autograd_exhaustive_matmul_cpu_float32 + # The issue is that we are sensitive to decomps that don't accurately maintain + # their output's _base.shape compared to eager mode, and this helps mitigate a bit. + # The guard_or_true also sketchy; if unbacked + # symints are involved, we're just going to assume that the + # decomps setup the base shape correctly + + # Return out if the result of out.shape==tangent.shape is unknown or known to be true. + # otherwise if its a known false return out.view(tangent.shape). + # tangent should also be a tensor since it corresponds to a tensor output + if not isinstance(tangent, torch.Tensor): + raise AssertionError( + f"Expected tensor tangent, got {type(tangent)}" + ) + needed_outs.append( + out + if guard_or_true(sym_eq(out.shape, tangent.shape)) + else out.view(tangent.shape) + ) + needed_tangents.append(tangent) + + setup_stacktrace_preservation_hooks( + [out.grad_fn for out in needed_outs if out.grad_fn is not None] + ) + + if config.functionalize_rng_ops: + PhiloxStateTracker.mark_beginning_of_backward() + backward_out: tuple[Tensor, ...] = () + # Call the backwards pass + if grad_primals: + functional_tensor_mode = torch.utils._python_dispatch._detect_infra_mode( + torch._C._TorchDispatchModeKey.FUNCTIONAL + ) + if functional_tensor_mode is not None: + # Side-Effect Tokens: + # We want to have independent chains of tokens for forward and backward. + # functional_tensor_mode._tokens is used by both. + # We memoize the result tokens of forward in functional_tensor_mode._tokens_forward_output, + # to return them as joint graph outputs. + # We clean functional_tensor_mode._tokens before backward, to prevent reuse of forward tokens in backward. + # Joint graph tracing allows tokens discovery, + # So all the tokens in backward will be created and added as a graph inputs during tracing. + functional_tensor_mode._tokens_forward_output = ( + functional_tensor_mode._tokens + ) + functional_tensor_mode._tokens = {} # pyrefly: ignore[implicit-any] + + with ( + set_partitioner_tag_is_backward(), + fx_traceback.preserve_node_meta(), + ExitStack() as stack, + ): + backward_pass_autocast = torch._functorch.config.backward_pass_autocast + if backward_pass_autocast == "same_as_forward": + # Use the ambient autocast mode(s) + pass + elif backward_pass_autocast == "off": + stack.enter_context(disable_autocast()) + else: + # Disable autocast, then enable anything in `backward_pass_autocast`. + stack.enter_context(disable_autocast()) + if not isinstance(backward_pass_autocast, list): + raise AssertionError( + f"expected backward_pass_autocast to be a list, got {type(backward_pass_autocast)}" + ) + for kwargs in backward_pass_autocast: + if not isinstance(kwargs, dict): + raise AssertionError( + f"expected kwargs to be a dict, got {type(kwargs)}" + ) + stack.enter_context(torch.amp.autocast(**kwargs)) + + # for full graph export, we always export a joint graph where we assume no tangents are needed. + if aot_config.no_tangents: + if not ( + len(needed_tangents) == 1 and needed_tangents[0].numel() == 1 + ): + raise AssertionError( + f"expected single scalar tangent for no_tangents mode, got {len(needed_tangents)} tangents" + ) + backward_out = torch.autograd.grad( + needed_outs, + grad_primals, + allow_unused=True, + ) + else: + backward_out = torch.autograd.grad( + needed_outs, + grad_primals, + grad_outputs=needed_tangents, + allow_unused=True, + ) + backward_out_iter = iter(backward_out) + final_outs = ( + outs, + [next(backward_out_iter) if i else None for i in inputs_needs_grads], + ) + if primals_descs is None: + return final_outs # type: ignore[return-value] + if outs_descs is None: + raise AssertionError("outs_descs must not be None") + # pyrefly: ignore[bad-return] + return final_outs, ( + outs_descs, + [ + # TODO: ideally we do know this is DifferentiableAOTInput + # but this is quite an involved refactor + GradAOTOutput(desc) if i else None # type: ignore[arg-type] + for i, desc in zip(inputs_needs_grads, primals_descs) + ], + ) + + @simple_wraps(inner_fn) + def inner_fn_with_anomaly( + primals: list[FxValue], tangents: list[FxValue] + ) -> tuple[ + tuple[list[FxValue], list[Tensor | None]], + tuple[list[AOTOutput], list[AOTOutput | None]], + ]: + with fx_traceback.preserve_node_meta(), warnings.catch_warnings(): + warnings.filterwarnings("ignore", "Anomaly Detection has been enabled.") + with torch.autograd.detect_anomaly(check_nan=False): + return inner_fn(primals, tangents) + + def joint_helper( + primals: list[FxValue], tangents: list[FxValue] + ) -> tuple[ + tuple[list[FxValue], list[Tensor | None]], + tuple[list[AOTOutput], list[AOTOutput | None]], + ]: + return inner_fn_with_anomaly(primals, tangents) + + joint_helper.handle = joint_fn_handle # type: ignore[attr-defined] + + # pyrefly: ignore[bad-return] + return joint_helper + + +def create_functionalized_rng_ops_wrapper( + func: Callable[..., Any], + args: Any, + args_descs: list[AOTInput], + trace_joint: bool = True, +) -> Any: + # Functionalization of rng ops changes the calling convention of the joint graph. + # It goes from (primals, tangents) to (seed, offset, primals, tangents) + # At runtime, we pass on the current seed and offset. This is hidden from + # the user. + fake_mode_det = detect_fake_mode() + fake_mode: AbstractContextManager[Any] = nullcontext() + if fake_mode_det is not None: + fake_mode = fake_mode_det + + def override_get_rng_state( + device: int | str | torch.device = "cuda", + ) -> Tensor: + out = PhiloxStateTracker.get_state_as_tensor() + return out + + def override_set_rng_state( + x: Tensor, device: int | str | torch.device = "cuda" + ) -> None: + PhiloxStateTracker.set_state_from_tensor(x) + + def append_rng_offsets(outs: Any, outs_descs: Any) -> Any: + if trace_joint: + # outs signature before: Tuple(fwd_outputs), Tuple(bwd_outputs) + # outs signature after: Tuple(fwd_outputs, new_fwd_rng_offset), Tuple(bwd_offset, new_bwd_rng_offset) + return ( + ( + (*outs[0], PhiloxStateTracker.get_updated_fwd_offset()), + (*outs[1], PhiloxStateTracker.get_updated_bwd_offset()), + ), + ( + (*outs_descs[0], PhiloxUpdatedForwardOffsetAOTOutput()), + (*outs_descs[1], PhiloxUpdatedBackwardOffsetAOTOutput()), + ), + ) + else: + # outs signature before: Tuple(fwd_outputs) + # outs signature after: Tuple(fwd_outputs, new_fwd_rng_offset) + return ( + (*outs, PhiloxStateTracker.get_updated_fwd_offset()), + (*outs_descs, PhiloxUpdatedForwardOffsetAOTOutput()), + ) + + def traced_joint( + primals: list[FxValue], + tangents: list[FxValue], + fwd_seed: Tensor, + fwd_base_offset: Tensor, + bwd_seed: Tensor, + bwd_base_offset: Tensor, + ) -> tuple[ + tuple[tuple[FxValue, ...], tuple[FxValue, ...]], + tuple[tuple[AOTOutput, ...], tuple[AOTOutput, ...]], + ]: + with ( + patch("torch.cuda.get_rng_state", override_get_rng_state), + patch("torch.cuda.set_rng_state", override_set_rng_state), + ): + return append_rng_offsets(*func(primals, tangents)) + + def traced_forward(*primals_fwd_seed_fwd_base_offset: Any) -> Any: + # The signature is (*primals, seed, offset) + with ( + patch("torch.cuda.get_rng_state", override_get_rng_state), + patch("torch.cuda.set_rng_state", override_set_rng_state), + ): + return append_rng_offsets(*func(*primals_fwd_seed_fwd_base_offset[:-2])) + + if trace_joint: + # Get the current seed and offset to setup tracing. + fwd_seed, fwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple( + fake_mode + ) + bwd_seed, bwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple( + fake_mode + ) + PhiloxStateTracker.record_state(fwd_seed, fwd_base_offset, "forward") + PhiloxStateTracker.record_state(bwd_seed, bwd_base_offset, "backward") + return ( + traced_joint, + ( + *args, + fwd_seed, + fwd_base_offset, + bwd_seed, + bwd_base_offset, + ), + ( + *args_descs, + PhiloxForwardSeedAOTInput(), + PhiloxForwardBaseOffsetAOTInput(), + PhiloxBackwardSeedAOTInput(), + PhiloxBackwardBaseOffsetAOTInput(), + ), + ) + else: + # Get the current seed and offset to setup tracing. + fwd_seed, fwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple( + fake_mode + ) + PhiloxStateTracker.record_state(fwd_seed, fwd_base_offset, "forward") + return ( + traced_forward, + (*args, fwd_seed, fwd_base_offset), + ( + *args_descs, + PhiloxForwardSeedAOTInput(), + PhiloxForwardBaseOffsetAOTInput(), + ), + ) + + +@contextmanager +def set_partitioner_tag(tag: str) -> Generator[None, None, None]: + meta_key = "partitioner_tag" + if not fx_traceback.has_preserved_node_meta(): + raise AssertionError("expected preserved node meta") + + original_val = fx_traceback.current_meta.get(meta_key, None) + fx_traceback.current_meta[meta_key] = tag + try: + yield + finally: + fx_traceback.current_meta[meta_key] = original_val + + +def set_partitioner_tag_is_backward() -> AbstractContextManager[None]: + return set_partitioner_tag("is_backward") + + +def set_partitioner_tag_must_be_in_backward() -> AbstractContextManager[None]: + return set_partitioner_tag("must_be_in_backward") + + +def set_partitioner_tag_must_be_in_forward() -> AbstractContextManager[None]: + return set_partitioner_tag("must_be_in_forward") + + +@dataclass +class MutationCounters: + mc_data: int + mc_storage: int + mc_inductor_storage_resized: int + + +T = TypeVar("T") + + +def sc_visit( + t: torch.Tensor, + fn: Callable[[Tensor], T], + reduce_fn: Callable[[T, T], T], + accum_init: T, +) -> T: + if not is_traceable_wrapper_subclass(t): + return fn(t) + + accum = accum_init + + def visit(e: Any) -> None: + if not is_traceable_wrapper_subclass(e): + nonlocal accum + accum = reduce_fn(accum, fn(e)) + return + + for a in e.__tensor_flatten__()[0]: + match getattr(e, a): + case torch.Tensor() as inner: + visit(inner) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + visit(t) + return accum + + +def _get_mutation_counter(t: torch.Tensor) -> int: + return sc_visit( + t, + lambda t: torch._functionalize_mutation_counter(t.elem), # type: ignore[attr-defined] + lambda l, r: max(l, r), + -1, + ) + + +def _get_storage_changed_counter(t: torch.Tensor) -> int: + return sc_visit( + t, + lambda t: torch._functionalize_storage_changed_counter(t.elem), # type: ignore[attr-defined] + lambda l, r: max(l, r), + -1, + ) + + +def _get_inductor_storage_resized_counter(t: torch.Tensor) -> int: + return sc_visit( + t, + lambda t: torch._functionalize_inductor_storage_resized_counter(t.elem), # type: ignore[attr-defined] + lambda l, r: max(l, r), + -1, + ) + + +def _get_mutation_counters(t: torch.Tensor) -> MutationCounters: + return MutationCounters( + _get_mutation_counter(t), + _get_storage_changed_counter(t), + _get_inductor_storage_resized_counter(t), + ) + + +def apply_in_graph_mutations( + input_info: InputAliasInfo, + inpt_old: Tensor, + inpt_new: Tensor, + f_inpt: Tensor, + input_idx: int, + mcs: MutationCounters | None = None, + applied_mcs: MutationCounters | None = None, +) -> None: + if input_info.mutation_type != MutationType.MUTATED_IN_GRAPH: + raise AssertionError( + f"expected mutation_type MUTATED_IN_GRAPH, got {input_info.mutation_type}" + ) + # See Note [set_() Input Mutations in AOTAutograd] + # all mutations on the input must be under no_grad, so it is safe to put in the graph + # Here, we're saying that if an input experienced a set call, inp.set_(other), + # then we can effectively not have to worry about whether its data was mutated. + # There are 3 cases: + # (1) We mutate inp *after* the set_() call. other is a graph intermediate. + # In this case, we're not really mutating the input storage of "inp"; + # we're mutating the storage of an intermediate value (other), + # and slamming that storage into the input tensor. So no data mutation is necessary. + # (2) We mutate inp *after* the set_() call. other is a graph *input*. + # In this case, the data mutation will be properly handled in the runtime + # epilogue during the processing of "other" + # (3) We mutate inp *before* the set_() call. + # This case is *not* currently handled. + if input_info.mutates_storage_metadata: + if mcs is None or mcs.mc_storage > applied_mcs.mc_storage: # type: ignore[union-attr] + with torch.no_grad(): + if input_info.mutation_is_shallow_copy_data: + torch.ops.aten.shallow_copy_data_(inpt_old, inpt_new) + else: + # pyrefly: ignore [bad-argument-type, no-matching-overload] + inpt_old.set_(inpt_new) + + # Note [Ordering of resize_() and set_()] + # Importantly: the common usage in FSDP is that we have a dummy parameter + # that sees a set_() and **Then** a resize_(). + # We must put those mutations into the graph in the same order, + # Since running them in the opposite order will have different behavior. + # We fully ban resize_() followed by set_() for now, although in principal + # we could support this + if input_info.mutation_inductor_storage_resize: + if ( + mcs is None + or mcs.mc_inductor_storage_resized > applied_mcs.mc_inductor_storage_resized # type: ignore[union-attr] + ): + # resizing is not supported on subclasses (we error earlier if this happens) + from torch._subclasses.functional_tensor import FunctionalTensor + + if not isinstance(f_inpt, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(f_inpt)}") + old_storage_size = torch._functionalize_get_storage_size( # type: ignore[attr-defined] + f_inpt.elem, before=True + ) + new_storage_size = torch._functionalize_get_storage_size( # type: ignore[attr-defined] + f_inpt.elem, before=False + ) + if old_storage_size != new_storage_size: + if not (old_storage_size == 0 or new_storage_size == 0): + raise AssertionError(f"""\ + Encosize during tracing on input {input_idx}. Old nbytes={old_storage_size}, new nbytes={new_storage_size} + We oresizing on graph inputs as long as the input either starts or ends with a storage size of 0 + (thee for FSDP)""") + torch.ops.inductor.resize_storage_bytes_(inpt_old, new_storage_size) + if new_storage_size == 0: + # Even if we marked the input as having a data mutation (thus needing a copy_()), + # We should **ignore** it if our input has no storage + # (this can happen if, e.g. we temporarily resize our input, copy data into it, + # and resize it back down to zero) + return + + # Optimization: if the copy_() is a no-op then don't include it in the graph. + # In theory inductor could optimize this away, however in fsdp, we end up with + # param.copy_(param), where param is a zero-storage-size tensor, + # and running this op in eager mode (using the aot_eager backend) will result in a segfault. + # So we may as well optimize it away here. + if inpt_old is inpt_new: + # (This check needs to be done after putting resize_() in the graph, + # since a resize_(0) doesn't actually change the FunctionalTensor's inner tensor) + return + # We found an input that had a (data-only) mutation. + # Since keep_input_mutations is set, we need to faithfully apply a copy_() + # so the compiler will see the input mutation in the graph. + + if not input_info.mutates_data: + return + + if mcs is not None and mcs.mc_data <= applied_mcs.mc_data: # type: ignore[union-attr] + return + + if input_info.mutations_hidden_from_autograd: + # Hidden from autograd = run under no_grad, **and** don't bump VC + # (although if the tensor was created in inference mode, it has no VC) + if inpt_old.is_inference(): + maybe_preserve_vc = nullcontext() + else: + maybe_preserve_vc = torch.autograd._unsafe_preserve_version_counter( + inpt_old # type: ignore[assignment] + ) + with torch.no_grad(), maybe_preserve_vc: + inpt_old.copy_(inpt_new) + elif input_info.mutations_under_no_grad_or_inference_mode: + # Under no_grad = run under no_grad (we still bump the VC though) + # (inference_mode will also bump the VC, as long as the tensor in question + # was created outside of inference_mode) + + with torch.no_grad(): + inpt_old.copy_(inpt_new) + else: + inpt_old.copy_(inpt_new) + + +# This creates the final function that we want to trace using make_fx(), +# in both aot_dispatch_autograd and aot_dispatch_base. +# Preconditions: +# - fn corresponds to the user's fw function +# - fn arguments have been flattened, duplicate arguments have been handled +# - In the returned function, the "primals" arguments *includes* synthetic bases. +# This function does the work of functionalizing the input function, +# and performing copy_() calls at the end of the function if `keep_input_mutations` is set. +# The function returned has signature that is either: +# (1) "traced_fn(primals: List[Any])" if trace_joint is False +# (2) "traced_fn(primals: List[Any], tangents: List[Any])" if trace_joint is True +# Returns a new (functionalized) function, and updated arguments to call it with. +def create_functionalized_fn( + fn: Callable[..., Any], + args: Any, + args_descs: Any, + *, + meta: ViewAndMutationMeta, + aot_config: AOTConfig, + trace_joint: bool, + joint_fn_handle: JointFnHandle | None = None, +) -> Any: + primals_after_forward = None + f_args_after_forward = None + f_args_mutation_counters_after_forward: list[MutationCounters] | None = None + inputs_mutated_in_graph = [ + info.mutation_type == MutationType.MUTATED_IN_GRAPH for info in meta.input_info + ] + has_input_mutated_in_graph = any(inputs_mutated_in_graph) + + @simple_wraps(fn) + def _functionalized_f_helper( + *args: list[FxValue], + ) -> tuple[tuple[list[FxValue], list[Tensor]], list[AOTOutput | None]]: + with maybe_enable_thunkify(): + # See Note [Disabling Functionalize TLS Above Python Functionalization] + disable_above = torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + + with disable_above: + # The functionalization code here can potentially trigger traces + # into the graph, but we'd prefer to NOT do this, because if we + # trace them now, we will end up with FX nodes that don't have + # module stack annotations, which makes unflattener unhappy. + # Wrap inputs into functional wrappers + f_args = pytree.tree_map(to_fun, args) + + if trace_joint and has_input_mutated_in_graph and joint_fn_handle: + # TODO(ivankobzarev): Support fw and bw mutations for subclasses + def _post_forward(primals: Any) -> None: + nonlocal primals_after_forward + primals_after_forward = pytree.tree_map(from_fun, primals) + nonlocal f_args_after_forward + f_args_after_forward = f_args[0] + nonlocal f_args_mutation_counters_after_forward + f_args_mutation_counters_after_forward = [ + MutationCounters(-1, -1, -1) + if not inputs_mutated_in_graph[i] + else _get_mutation_counters(f_arg) + for i, f_arg in enumerate(f_args_after_forward) + ] + + joint_fn_handle.post_forward = _post_forward + + # Run the joint + f_outs, f_outs_descs = call_and_expect_output_descs(fn, f_args) + + if trace_joint: + # We support a limited amount of mutation of graph inputs during the backward pass. + # (This is used e.g. by Float8, which needs to update buffers during the backward pass) + # Here, we perform extra checks for primals that were mutated in the **backward** + # We're doing the checks here instead of doing them with the rest of the input mutation handling because: + # - We need to detect inputs that were mutated in the backward **separately** from mutations that happened + # during the forward, because the handling is different: some input mutations from the forward + # can be only handled in a fw-only runtime epilogue, and in theory if we wanted to handle those same + # types of mutations in the backward we would need a bw-only runtime epilogue. + # - We could in theory have our analysis pass differentiate mutations in the fw from mutations in + # the bw by running our analysis first on the fw-only graph, and then on the joint graph. This would + # require an extra round of tracing though, so it's more efficient to do in-line here. + if not ( + isinstance(args, tuple) + and len(args) == 2 + and isinstance(args[0], (list, tuple)) + ): + raise AssertionError( + f"expected args to be tuple of (list/tuple, ...), got {type(args)}" + ) + # Only look at mutations that happened to forward inputs (e.g. fw buffers that were saved for bw) + primals_before = args[0] + primals_after = pytree.tree_map(from_fun, f_args[0]) + for idx, (f_inpt, before, after, inpt_info) in enumerate( + zip(f_args[0], primals_before, primals_after, meta.input_info) + ): + # Store information about mutations in joint(for backward analysis) + joint_mutates_data = has_data_mutation(f_inpt) + + joint_mutates_metadata = has_metadata_mutation( + f_inpt, before, check_only_storage_mutation=False + ) + + # Ban metadata mutations on fw inputs during the bw + if not inpt_info.mutates_metadata: + if joint_mutates_metadata: + raise AssertionError( + "Found a graph input that had its metadata mutated in the backward. This is not supported" + ) + + # Ban storage resizing on fw inputs during the bw + if not inpt_info.mutation_inductor_storage_resize: + if was_inductor_storage_resized(f_inpt): + raise AssertionError( + "Found a graph input that had storage resizing in the backward. This is not supported" + ) + + # Allow data mutations on fw inputs during the bw, but only if they do not require grad + # So we can guarantee that we can keep the mutations in the graph + if ( + joint_mutates_data + and not inpt_info.mutates_data + and not inpt_info.mutates_storage_metadata + ): + # Not banning here mutations on inpt_info.requires_grad - + # we'll check at runtime and fail only when backward is under torch.is_grad_enabled (create_graph) + # Add node meta for copy_ for partitioner that this node should be in backward graph. + with ( + torch.fx.traceback.preserve_node_meta(), + set_partitioner_tag_must_be_in_backward(), + ): + # before and after should be tensors if we're calling copy_ on them + if not ( + isinstance(before, torch.Tensor) + and isinstance(after, torch.Tensor) + ): + raise AssertionError( + f"expected both before and after to be Tensors, got {type(before)} and {type(after)}" + ) + # no_grad prevents the FakeTensor's requires_grad from + # triggering check_inplace during tracing. The + # requires_grad case is checked at runtime instead + with torch.no_grad(): + before.copy_(after) + meta.indices_of_inputs_that_requires_grad_with_mutations_in_bw.append( + idx + ) + # Now that we covered mutations to *forward* inputs during the backward, + # we also need to cover mutations to *backward-only* inputs during the backward (e.g. mutation to a grad_out). + # Today, we will just error in all cases of this happening unless someone needs us to support it. + tangents_before = args[1] + tangents_after = pytree.tree_map(from_fun, f_args[1]) + for f_inpt, before, after in zip( + f_args[1], tangents_before, tangents_after + ): + if has_metadata_mutation( + f_inpt, before, check_only_storage_mutation=False + ): + raise AssertionError( + "Found an input to the backward that had metadata mutated " + "during the backward pass. This is not supported" + ) + if has_data_mutation(f_inpt): + can_be_in_graph = _check_if_mutation_can_be_in_graph( + keep_input_mutations=True, + mutates_data=True, + mutates_metadata=False, + mutations_hidden_from_autograd=are_all_mutations_hidden_from_autograd( + f_inpt + ), + mutations_under_no_grad_or_inference_mode=are_all_mutations_under_no_grad_or_inference_mode( + f_inpt + ), + mutates_storage_metadata=False, + mutation_inductor_storage_resize=was_inductor_storage_resized( + f_inpt + ), + requires_grad=f_inpt.requires_grad, + ) + if not can_be_in_graph: + raise AssertionError( + "a backward input that had data mutated in an autograd-aware way. This is not supported" + ) + # Perform the input mutation + with torch.fx.traceback.preserve_node_meta(): + # before and after should be tensors if we're calling copy_ on them + if not ( + isinstance(before, torch.Tensor) + and isinstance(after, torch.Tensor) + ): + raise AssertionError( + f"expected both before and after to be Tensors, got {type(before)} and {type(after)}" + ) + before.copy_(after) + + if aot_config.keep_inference_input_mutations: + # Note: This is a bit annoying. There's a layering issue here, where: + # (1) functionalization needs to operate on **synthetic base** inputs, before unpacking them into the "real" inputs. + # (2) For keep_input_mutations, we support tracing a call to copy_() directly on mutated inputs. + # However, we **only** want to support this for inputs that have data-only (and no metadata) mutations, + # because inductor (and backends in generally) would prefer not to see these (e.g. as_strided_(), resize_()). + # This makes it pretty difficult for this logic to operate on synthetic bases. + # (3) In addition, there are cases where it's significantly cheaper to perform the copy on the individual + # (unpacked) input aliases, instead of the synthetic base. + # Example case where (3) could be important: + # + # def f(x, y): + # x.mul_(2) + # y.mul_(3) + # return x, y + # a = torch.ones(1'000'000) + # x, y = out(a[0:9], a[1:10]) + # + # It would be much better to add copy_() calls into the graph for the two tiny slices, instead of materializing + # a giant "updated synthetic base" and copying into a's entire storage. + # + # For now, we are pessimistically not performing the optimization from (3); + # we will materialize an "updated" synthetic base, and copy it back to the synthetic input base. + # This allows us to factor aot autograd much more nicely, since only one area of the code needs to worry + # about synthetic bases. + + # Apply in graph forward mutations only in joint case. + # Note: Mutations of primals in forward AND backward. + # If we have mutations of the same input in forward and in backward, + # we can not fuse them into one copy_ node. As in this case partitioner will put it + # either in forward or in backward. This will lead to incorrect state + # after forward and before backward. + # We have to emit two copy_ nodes, marking with additional meta each node, + # if it must be in forward or backward. + # We memorize mutation counter of the inputs after forward. + # Based on this after joint graph we check if backward also mutated input or not. + # We emit copy_ only in the end of joint tracing, to provide invariant for joint + # graph passes, that our graph is functional, except only some number of copy_ nodes + # in the end. + mcs_applied: list[MutationCounters] = [MutationCounters(0, 0, 0)] * len( + meta.input_info + ) + if f_args_mutation_counters_after_forward is not None: + primals_before = args[0] + for idx, (f_inpt, before, after, inpt_info) in enumerate( + # pyrefly: ignore [no-matching-overload] + zip( + f_args_after_forward, # type: ignore[arg-type] + primals_before, # type: ignore[arg-type] + primals_after_forward, # type: ignore[arg-type] + meta.input_info, + ) + ): + if inpt_info.mutation_type != MutationType.MUTATED_IN_GRAPH: + continue + + mcs_after_forward = f_args_mutation_counters_after_forward[idx] + with ( + torch.fx.traceback.preserve_node_meta(), + set_partitioner_tag_must_be_in_forward(), + _proxy_tensor_disable_update_tensor_tracker(), + ): + apply_in_graph_mutations( + inpt_info, + # pyrefly: ignore [bad-argument-type] + before, + after, + f_inpt, + idx, + mcs_after_forward, + mcs_applied[idx], + ) + mcs_applied[idx] = mcs_after_forward + + for idx, (inpt_old, f_inpt) in enumerate( + zip(args, f_args) if not trace_joint else zip(args[0], f_args[0]) # type: ignore[arg-type] + ): + if not isinstance(f_inpt, torch.Tensor): + continue + if not is_fun(f_inpt): + raise AssertionError( + f"expected functional tensor, got {type(f_inpt)}" + ) + inpt_new = from_fun(f_inpt) + if ( + meta.input_info[idx].mutation_type + != MutationType.MUTATED_IN_GRAPH + ): + continue + mcs: MutationCounters | None = None + if f_args_mutation_counters_after_forward is not None: + # This could happen for subclasses tracing + # Subclasses support for mutations in fw and bw is TBD. + mcs = _get_mutation_counters(f_inpt) + if mcs == mcs_applied[idx]: + # No mutation in backward; mutation was already applied. + continue + + with ( + torch.fx.traceback.preserve_node_meta(), + set_partitioner_tag_must_be_in_backward(), + ): + apply_in_graph_mutations( + meta.input_info[idx], + # pyrefly: ignore[bad-argument-type] + inpt_old, + # pyrefly: ignore[bad-argument-type] + inpt_new, + f_inpt, + idx, + mcs, + mcs_applied[idx], + ) + + # When an output tensor is a functionalized mutated input, and we + # were able to move the mutation in to the graph then we can return + # the mutated input directly. This prevents duplicating the + # tensors contents. + flat_outs, outs_spec = pytree.tree_flatten(f_outs) + flat_outs = [from_fun(o) for o in flat_outs] + num_outs = len(meta.output_info) + + for i in range(num_outs): + info = meta.output_info[i] + if info.output_type != OutputType.is_input: + continue + + if info.base_idx is None: + raise AssertionError("info.base_idx must not be None") + if ( + meta.input_info[info.base_idx].mutation_type + == MutationType.MUTATED_IN_GRAPH + ): + fw_args = args[0] if trace_joint else args + flat_outs[i] = fw_args[info.base_idx] + return pytree.tree_unflatten(flat_outs, outs_spec), f_outs_descs + + return pytree.tree_map(from_fun, f_outs), f_outs_descs + + # Kinda annoying, but needed to make sure that the fx graph we trace out has "primals" + # and "tangents" as its input names (which are special-cased by the partitioner) + # TODO (tmanlaibaatar) revisit this if we ever need to turn on non-strict joint graph export + def joint_helper(primals: list[FxValue], tangents: list[FxValue]) -> Any: + return _functionalized_f_helper(primals, tangents) + + helper = joint_helper if trace_joint else _functionalized_f_helper + if config.functionalize_rng_ops: + # Setup the wrapper for functionalization of rng ops + helper, args, args_descs = create_functionalized_rng_ops_wrapper( + helper, args, args_descs, trace_joint + ) + + return helper, args, args_descs + + +def handle_effect_tokens_fn( + fn: Callable[..., Any], + args: Any, + args_descs: list[AOTInput], + *, + meta: ViewAndMutationMeta, + trace_joint: bool, +) -> Any: + num_tokens = len(meta.tokens) + + @simple_wraps(fn) + def inner_fn(*args: Any) -> Any: + # See Note [Disabling Functionalize TLS Above Python Functionalization] + disable_above = torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + + with disable_above: + # See Note [Side-Effectful Tokens in AOTAutograd] + if trace_joint: + if not (isinstance(args, tuple) and isinstance(args[0], (list, tuple))): + raise AssertionError( + f"expected args to be tuple with first element as list/tuple, got {type(args)}" + ) + tokens = args[0][:num_tokens] + if not all(token.numel() == 0 for token in tokens): + raise AssertionError("all tokens must have numel() == 0") + args = (args[0][num_tokens:], *args[1:]) + else: + tokens = args[:num_tokens] + if not all(token.numel() == 0 for token in tokens): + raise AssertionError("all tokens must have numel() == 0") + args = args[num_tokens:] + + # Populate the current FunctionalTensorMode with the tokens per + # operator. See Note [FunctionalTensorMode is Stateful] + functional_tensor_mode = torch.utils._python_dispatch._detect_infra_mode( + torch._C._TorchDispatchModeKey.FUNCTIONAL + ) + if functional_tensor_mode is None: + raise AssertionError("functional_tensor_mode must not be None") + f_tokens = pytree.tree_map(to_fun, tokens) + for i, k in enumerate(meta.tokens.keys()): + functional_tensor_mode._tokens[k] = f_tokens[i] + + # Run the joint + outs, outs_descs = call_and_expect_output_descs(fn, args) + + # Return both the tokens and the outputs + # See Note [Side-Effectful Tokens in AOTAutograd] + if trace_joint: + if len(outs) != 2: + raise AssertionError( + f"expected len(outs) == 2 for joint trace, got {len(outs)}" + ) + if len(functional_tensor_mode._tokens_forward_output) != num_tokens: + raise AssertionError( + f"expected {num_tokens} forward output tokens, got {len(functional_tensor_mode._tokens_forward_output)}" + ) + fwd_out_tokens = functional_tensor_mode._tokens_forward_output.values() + + bwd_out_tokens = functional_tensor_mode._tokens.values() + + f_fwd_out_tokens = [from_fun(t) for t in fwd_out_tokens] + f_bwd_out_tokens = [from_fun(t) for t in bwd_out_tokens] + f_fwd_out_tokens_descs = [ + ForwardTokenAOTOutput(i) for i in range(len(fwd_out_tokens)) + ] + f_bwd_out_tokens_descs = [ + BackwardTokenAOTOutput(i) for i in range(len(bwd_out_tokens)) + ] + + meta.num_backward_tokens = len(bwd_out_tokens) + return ( + ((*f_fwd_out_tokens, *outs[0]), (*outs[1], *f_bwd_out_tokens)), + ( + (*f_fwd_out_tokens_descs, *outs_descs[0]), + (*outs_descs[1], *f_bwd_out_tokens_descs), + ), + ) + + out_tokens = [from_fun(t) for t in functional_tensor_mode._tokens.values()] + # TODO: can probably do a little more resolution here + out_tokens_descs = [ + ForwardTokenAOTOutput(i) + for i in range(len(functional_tensor_mode._tokens.values())) + ] + return ((*out_tokens, *outs), (*out_tokens_descs, *outs_descs)) + + # Additionally pass in tokens as inputs + # See Note [Side-Effectful Tokens in AOTAutograd] + additional_fwd_token_inputs = [torch.tensor([])] * num_tokens + additional_fwd_token_inputs_descs = [ + ForwardTokenAOTInput(i) for i in range(num_tokens) + ] + + if trace_joint: + args = ([*additional_fwd_token_inputs, *args[0]], *args[1:]) + args_descs = ( # type: ignore[assignment] + [*additional_fwd_token_inputs_descs, *args_descs[0]], # type: ignore[misc] + *args_descs[1:], + ) + else: + args = [*additional_fwd_token_inputs, *args] + args_descs = [*additional_fwd_token_inputs_descs, *args_descs] + + if num_tokens > 0: + meta.static_input_indices = [ + idx + num_tokens for idx in meta.static_input_indices + ] + return inner_fn, args, args_descs + + +# Given a function operating on Subclass -> Subclass, returns a function that operates on Tensor -> Tensor +# Also returns: +# - the new set of arguments to pass into this function (now that tensor subclasses have been eliminated) +# - the updated ViewAndMutationMeta for this dense -> dense function. +# The other important arguments are: +# - flat_fn_maybe_joint: when is_joint_structure=True, this is the joint fw-bw function. +# when is_joint_structure=False, this is just the forward function. +# - fw_only: this is *always* the forward-only function. +# Why do we need this? We need to collect updated ViewAndMutationMeta on our new dense -> dense functions. +# In particular, we need this to tell the partitioner how many dense forward outputs there are. +def aot_dispatch_subclass( + flat_fn_maybe_joint: JointTraceFn | TraceFn, + args: list[FxValue] | tuple[list[FxValue], list[FxValue]], + args_descs: list[AOTInput] | tuple[list[AOTInput], list[AOTInput]], + *, + is_joint_structure: bool, + meta: ViewAndMutationMeta, + fw_only: Callable[..., Any], +) -> SubclassTracingInfo: + # Skip logic if we don't need to trace through any subclasses + req_subclass_dispatch = requires_subclass_dispatch(args, meta) # type: ignore[arg-type] + if not req_subclass_dispatch: + return SubclassTracingInfo( + plain_tensor_trace_fn=flat_fn_maybe_joint, + plain_tensor_args=args, + plain_tensor_args_descs=args_descs, + maybe_subclass_meta=None, + ) + + # TODO: add subclass guards (later PR). + + # What's going on here? We need to compute subclass metadata about the outputs of the joint (grad_inputs). + # Annoying: we don't know the grad input metas until we're in the middle of tracing the joint, + # so we set it later, while we're tracing the joint (see inner_fn() below). + # Another option would be to run our run_functionalized_fw_and_collect_metadata() function + # directly on the joint, but this would hurt compile time (adding yet another pass through the joint). + subclass_meta = SubclassMeta() + + # NB: doesn't take descs, this is going from the NEW flat_args to the + # subclasses, we don't need to do bookkeeping here + def inner_fn(fn: Callable[..., Any], args: Any, *, use_trace_joint: bool) -> Any: + # Step 1: wrap tensor inputs into subclasses if necessary + all_args = wrap_tensor_subclasses_maybe_joint( + args, is_joint_structure=use_trace_joint, meta=meta + ) + + # Step 2: call the inner function, with our (maybe subclass) inputs + wrapped_outs, wrapped_outs_descs = call_and_expect_output_descs(fn, all_args) # type: ignore[arg-type] + + if use_trace_joint: + # See Note: [Computing Subclass Metadata about grad_inputs] + # We also stash subclass info on our grad_inputs, if we're tracing the joint. + nonlocal subclass_meta + if not (isinstance(wrapped_outs, tuple) and len(wrapped_outs) == 2): + raise AssertionError( + f"expected wrapped_outs to be tuple of length 2, got {type(wrapped_outs)}, {wrapped_outs_descs}" + ) + # Don't need fw outs since we already have subclass metadata on them + grad_inputs = wrapped_outs[1] + subclass_meta.grad_input_metas = create_subclass_meta(grad_inputs) + + # Add extra symints as outputs to the forward/backward graphs + # ignore nested ints here + forward_outs, forward_outs_descs = unwrap_tensor_subclasses( + wrapped_outs[0], + wrapped_outs_descs[0], + append_symints=True, + ) + # ignore nested ints here + backward_outs, backward_outs_descs = unwrap_tensor_subclasses( + wrapped_outs[1], + wrapped_outs_descs[1], + append_symints=True, + ) + return ( + (forward_outs, backward_outs), + (forward_outs_descs, backward_outs_descs), + ) + + # Step 3: Unwrap any subclass outputs back into dense tensors + return unwrap_tensor_subclasses( + wrapped_outs, wrapped_outs_descs, append_symints=True + ) + + def joint_fn( + primals: list[FxValue], tangents: list[FxValue] + ) -> tuple[ + tuple[list[FxValue], list[FxValue]], tuple[list[AOTOutput], list[AOTOutput]] + ]: + with maybe_enable_thunkify(): + return inner_fn( + flat_fn_maybe_joint, (primals, tangents), use_trace_joint=True + ) + + def fw_fn(*primals: FxValue) -> tuple[list[FxValue], list[AOTOutput]]: + with maybe_enable_thunkify(): + return inner_fn(flat_fn_maybe_joint, primals, use_trace_joint=False) + + def metadata_fn(*primals: FxValue) -> tuple[list[FxValue], list[AOTOutput]]: + @simple_wraps(fw_only) + def inner_fw_only(*args: Any) -> Any: + return call_and_expect_output_descs(fw_only, args) + + return inner_fn(inner_fw_only, primals, use_trace_joint=False) + + if is_joint_structure: + primals_wrapped: list[FxValue] = typing.cast(list[FxValue], args[0]) + primals_wrapped_descs: list[AOTInput] = typing.cast( + list[AOTInput], args_descs[0] + ) + tangents_wrapped: list[FxValue] = typing.cast(list[FxValue], args[1]) + tangents_wrapped_descs: list[AOTInput] = typing.cast( + list[AOTInput], args_descs[1] + ) + + # Add extra symints (size/strides) as input to the forward graph + primals_unwrapped_pair = unwrap_tensor_subclasses( + primals_wrapped, + primals_wrapped_descs, + append_symints=True, + ) + # We pass append_symints=False here because the partitioner will + # capture and add any extra argument. + tangents_unwrapped_pair = unwrap_tensor_subclasses( + tangents_wrapped, + tangents_wrapped_descs, + append_symints=False, + ) + + args_unwrapped = (primals_unwrapped_pair[0], tangents_unwrapped_pair[0]) + args_descs_unwrapped = (primals_unwrapped_pair[1], tangents_unwrapped_pair[1]) + remapped_static_indices = remap_unwrapped_subclass_arg_indices( + primals_wrapped, + meta.static_input_indices, # type: ignore[arg-type] + ) + + primals_unwrapped = args_unwrapped[0] # type: ignore[assignment] + primals_unwrapped_descs = args_descs_unwrapped[0] # type: ignore[assignment] + fn_to_trace = joint_fn # type: ignore[assignment] + else: + primals_wrapped: list[FxValue] = typing.cast(list[FxValue], args) + primals_wrapped_descs: list[AOTInput] = typing.cast(list[AOTInput], args_descs) + + args_unwrapped, args_descs_unwrapped = unwrap_tensor_subclasses( # type: ignore[assignment] + primals_wrapped, + primals_wrapped_descs, + append_symints=True, + ) + remapped_static_indices = remap_unwrapped_subclass_arg_indices( + primals_wrapped, + meta.static_input_indices, # type: ignore[arg-type] + ) + + primals_unwrapped = args_unwrapped # type: ignore[assignment] + primals_unwrapped_descs = args_descs_unwrapped # type: ignore[assignment] + fn_to_trace = fw_fn # type: ignore[assignment] + + # Note: [Partitioner handling for Subclasses, Part 1] + # The way the partitioner works is that: + # (1) we pass is a single graph containing the joint fw/bw, + # where the # of graph outputs corresponds to # fw_outputs + # grad_inputs + # (2) The partitioner accepts an arguments, num_fwd_outputs, + # and assumes that the first "num_fwd_outputs" graph outputs correspond + # to outputs of the forward graph. + # How do tensor subclasses enter the picture? + # the num_fwd_outputs in the final graph is actually non-trivial to compute, + # because it can be influenced by input mutations and intermediate bases. + # So we compute it by inspecting the current ViewAndMutationMeta object. + # However, the original ViewAndMutationMeta that we computed was created + # on the subclass -> subclass graph, + # which can have a different number of outputs than the dense -> dense graph. + # That's why we created a fresh metadata object on the dense -> dense function here, + # and plumb it back up to the partitioner. + # See Note: [Partitioner handling for Subclasses, Part 2] for more info. + with torch._dynamo.eval_frame._use_eager_on_nested_compile(): + meta_updated = run_functionalized_fw_and_collect_metadata( + without_output_descs(metadata_fn), + # pyrefly: ignore [bad-argument-type] + flat_args_descs=primals_unwrapped_descs, + static_input_indices=remapped_static_indices, + keep_input_mutations=meta.keep_input_mutations, + # pyrefly: ignore [not-iterable] + )(*primals_unwrapped) + + subclass_meta.fw_metadata = meta_updated + + return SubclassTracingInfo( + plain_tensor_trace_fn=fn_to_trace, + plain_tensor_args=args_unwrapped, + plain_tensor_args_descs=args_descs_unwrapped, + maybe_subclass_meta=subclass_meta, + ) + + +def create_functional_call( + mod: Any, + params_spec: Any, + params_len: int, + store_orig_mod: bool = False, + strict_out_tuple: bool = True, +) -> Callable[..., Any]: + # Redundant with dynamo, but worth having in case this gets invoked elsewhere. + + @simple_wraps(mod) + def functional_call(*args: Any, **kwargs: Any) -> Any: + flat_params = args[:params_len] + if isinstance(params_spec, TreeSpec): + params = pytree.tree_unflatten(flat_params, params_spec) + else: + if not isinstance(params_spec, list): + raise AssertionError( + f"expected params_spec to be a list, got {type(params_spec)}" + ) + params = dict(zip(params_spec, flat_params)) + with ( + stateless._reparametrize_module(mod, params), + maybe_disable_thunkify(), + ): + if isinstance(mod, torch.fx.GraphModule): + if kwargs: + # Handle **kwargs. FX only natively supports positional + # arguments (through placeholders). + arg_list = list(args[params_len:]) + arg_list.extend(list(kwargs.values())) + args = tuple(arg_list) + else: + args = args[params_len:] + + with fx_traceback.preserve_node_meta(), warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", "Anomaly Detection has been enabled." + ) + with torch.autograd.detect_anomaly(check_nan=False): + fake_mode = detect_fake_mode() + if fake_mode is None: + raise AssertionError("fake_mode must not be None") + fake_mode.epoch += 1 + out = PropagateUnbackedSymInts(mod).run(*args) + else: + out = mod(*args[params_len:], **kwargs) + + if strict_out_tuple and not isinstance(out, (tuple, list)): + raise RuntimeError( + "Graph output must be a (). This is so that we can avoid " + "pytree processing of the outputs. Please change the module to " + "have tuple outputs or use aot_module instead." + ) + return out + + # Note [Preserving the nn module stack metadata during export non-strict mode] + # This path is currently only used by the non-strict export flow, + # where we cannot rely on dynamo to preserve nn stack metadata in our captured graph. + # Instead, we stash the original user nn module here, and rely on `make_fx` to grab + # this stashed module and use it to track nn module stack metadata + if store_orig_mod and not hasattr(functional_call, "_orig_mod"): + functional_call._orig_mod = mod # type: ignore[attr-defined] + + return functional_call diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_compile.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..d27c3d2889bcc1599e12d1f935a96fe86fb07605 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_compile.py @@ -0,0 +1,2881 @@ +""" +Functions in this module do most of the "work" of AOTAutograd. +An aot_dispatch_* function: +- Takes in the input flat_fn, flat_args, and some metadata +- Runs a set of pre compile wrappers (e.g. argument deduping) +- Runs the actual compiler +- Wraps the returned callable in a set of post compile wrappers +- Returns the wrapped callable and metadata. +""" + +import copy +import dataclasses +import functools +import itertools +import logging +import operator +import threading +import time +import traceback +from collections import defaultdict +from collections.abc import Callable, Generator +from contextlib import contextmanager, nullcontext +from typing import Any + +import torch +import torch.utils._pytree as pytree +import torch.utils.dlpack +from torch import Tensor +from torch._custom_class_base import CustomClassBase +from torch._dynamo.utils import ( + CompileEventLogger, + detect_fake_mode, + dynamo_timed, + lazy_format_graph_code, +) +from torch._guards import CompileContext, TracingContext +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class_obj +from torch._logging import getArtifactLogger, trace_structured +from torch._subclasses import FakeTensor +from torch._subclasses.fake_tensor import is_fake_tensor +from torch._subclasses.meta_utils import is_sparse_any +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import is_sym_node +from torch.fx.experimental.symbolic_shapes import fx_placeholder_vals, guard_or_true +from torch.fx.graph_module import GraphModule +from torch.fx.passes._tensorify_python_scalars import tensorify_python_scalars +from torch.multiprocessing.reductions import StorageWeakRef +from torch.types import py_sym_types +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torchgen.utils import dataclass_repr + +from .. import config +from .aot_autograd_result import GenericAOTAutogradResult, serialize_graph_module +from .autograd_cache import ( + AOTAutogradCache, + should_bundle_autograd_cache, + should_use_remote_autograd_cache, +) +from .descriptors import AOTOutput, PlainAOTOutput +from .graph_capture import aot_dispatch_autograd_graph, aot_dispatch_base_graph +from .logging_utils import track_graph_compiling +from .runtime_wrappers import ( + AOTDedupeWrapper, + AOTDispatchAutograd, + AOTDispatchAutogradCompileSpec, + AOTDispatchSubclassWrapper, + AOTSyntheticBaseWrapper, + AutogradLazyBackwardCompileInfo, + CompilerWrapper, + DebugAssertWrapper, + EffectTokensWrapper, + FakifiedOutWrapper, + FunctionalizedRngRuntimeWrapper, + make_runtime_safe, + post_compile, + pre_compile, + RuntimeWrapper, + SerializableCompiledFunction, +) +from .schemas import ( + AOTConfig, + AOTGraphCapture, + AOTState, + FlatFn, + FxValue, + MutationType, + SubclassMeta, + ViewAndMutationMeta, +) +from .subclass_utils import compute_inner_mutated_inp_indices_from_subclass_meta +from .utils import ( + contain_metadata_mutation_ops, + get_default_generator, + make_boxed_func, + simple_wraps, + strict_zip, + unlift_tokens, +) + + +def is_opaque_node(node: Any) -> bool: + """Check if a node contains an opaque or non-tensor value (e.g., ProcessGroup).""" + from torch._library.fake_class_registry import FakeScriptObject + + if not isinstance(node, torch.fx.Node): + return False + if "val" not in getattr(node, "meta", {}): + return False + val = node.meta["val"] + if is_custom_class_obj(val): + return True + if isinstance(val, (torch.ScriptObject, FakeScriptObject)): + return True + return False + + +_thread_local = threading.local() + + +def _should_save_cache(*compiled_fns: Callable[..., Any]) -> bool: + if should_bundle_autograd_cache(): + return True + return all( + getattr(fn, "_fx_graph_cache_key", None) is not None for fn in compiled_fns + ) + + +@contextmanager +def maybe_skip_decompose(aot_config: AOTConfig) -> Generator[AOTConfig, None, None]: + if config.selective_decompose: + yield dataclasses.replace(aot_config, decompositions={}) + else: + yield aot_config + + +# Saved tensor hooks context +# Compiled saved tensor hooks are convenient way to inline some logic in the graphs +# for saved nodes from forward to backward. (E.g. activations quantization) +# In base implementation user does not have any additional information about saved value +# in the hook, except FakeTensor shape, dtype, device etc. +# _get_saved_tensor_hook_context gives additional graph information about that saved value, +# that can be used to make a decisions which pack/unpack to apply for particular saved value. +# This allows user to reuse saved tensors hooks api to apply selective pack/unpack in +# graph aware way. +# Alternative to this will be making user to write a custom pass that mucks with forward outputs, +# backward input metadata, which requires significantly more effort. +# +# As for now in context we expose forward graph, backward graph and current saved node, +# which contains node.meta with additional information about that fx.Node. +# Warning: This API may change without backward compatibility. +@contextmanager +def _saved_tensor_hook_context(state: dict[str, Any]) -> Generator[None, None, None]: + previous_state = getattr(_thread_local, "state", None) + try: + _thread_local.state = state + yield + finally: + # Clean up: restore previous state or remove attribute + if previous_state is not None: + _thread_local.state = previous_state + else: + if hasattr(_thread_local, "state"): + delattr(_thread_local, "state") + + +def _get_saved_tensor_hook_context() -> dict[str, Any] | None: + return getattr(_thread_local, "state", None) + + +zip = strict_zip + +log = logging.getLogger(__name__) +aot_joint_log = getArtifactLogger(__name__, "aot_joint_graph") +aot_graphs_log = getArtifactLogger(__name__, "aot_graphs") + +aten = torch.ops.aten + +# Returns a Callable and a ViewAndMutationMeta. +# Currently, only export needs the ViewAndMutationMeta after this function. +# TODO: Refactor this +DispatchReturn = tuple[Callable[..., Any], ViewAndMutationMeta] + + +def _create_wrappers_for_dispatch(needs_autograd: bool) -> list[CompilerWrapper]: + """ + Wrappers that run on every dispatch function + """ + return [AOTDedupeWrapper(), AOTSyntheticBaseWrapper(trace_joint=needs_autograd)] + + +def aot_stage1_graph_capture( + aot_state: AOTState, + orig_flat_fn: FlatFn, +) -> AOTGraphCapture: + # NB: flat_fn at this point coincides with the initial info from forward + # metadata collection returning a list[Tensor]. We are now going to + # augment the output to return a tuple[list[Tensor], list[AOTOutput]] and + # then preserve this convention through the rest of the passes. + + # TODO: We could test for consistency with fw_metadata, but this is not a + # big deal + @simple_wraps(orig_flat_fn) + def orig_flat_fn2(*args: FxValue) -> tuple[list[FxValue], list[AOTOutput]]: + out = orig_flat_fn(*args) + out_descs: list[AOTOutput] = type(out)( # type: ignore[assignment] + PlainAOTOutput(i) # type: ignore[misc] + for i in range(len(out)) # type: ignore[misc] + ) + return out, out_descs + + aot_config = aot_state.aot_config + + wrappers = _create_wrappers_for_dispatch(aot_state.needs_autograd) + flat_fn, aot_state.flat_args, aot_state.flat_args_descs, aot_state.fw_metadata = ( + pre_compile( + wrappers, + orig_flat_fn2, + aot_state.flat_args, + aot_state.flat_args_descs, + aot_config, + fw_metadata=aot_state.fw_metadata, + ) + ) + if aot_config.disable_functionalization: + # Effect tokens are introduced by FunctionalTensorMode. The + # disable_functionalization path intentionally traces without the + # effect-token wrapper, so metadata-discovered tokens must not affect + # graph signatures or forward/backward output partitioning. + aot_state.fw_metadata.tokens = {} + aot_state.fw_metadata.num_backward_tokens = 0 + + # NB: This is currently only used for backwards, where fwd/bwd + # deterministic TLS can be different + aot_state.fw_metadata.deterministic = torch.are_deterministic_algorithms_enabled() + updated_flat_args: list[Any] | tuple[list[Any], list[Any]] + + with maybe_skip_decompose(aot_config) as graph_capture_aot_config: + # if config.selective_decompose, skip decomposition and apply selective_decompose + # after we get the joint graph. See [Note: Selective Decomposition] for details. + if aot_state.needs_autograd and not aot_config.pre_dispatch: + # FYI: this being moved to trigger in export is new, seems fine! + with dynamo_timed("aot_trace_joint_graph", log_pt2_compile_event=True): + ( + graph, + updated_flat_args, + updated_flat_args_descs, + maybe_subclass_meta, + ) = aot_dispatch_autograd_graph( + flat_fn, + aot_state.flat_args, + aot_state.flat_args_descs, + graph_capture_aot_config, + fw_metadata=aot_state.fw_metadata, + ) + else: + graph, updated_flat_args, updated_flat_args_descs, maybe_subclass_meta = ( + aot_dispatch_base_graph( + flat_fn, + aot_state.flat_args, + aot_state.flat_args_descs, + graph_capture_aot_config, + fw_metadata=aot_state.fw_metadata, + ) + ) + if config.selective_decompose: + from torch.fx.experimental.proxy_tensor import selective_decompose + from torch.fx.passes.regional_inductor import _needs_inductor_compile + + graph = selective_decompose( + graph, + *updated_flat_args, + decomposition=aot_config.decompositions, + should_decompose=_needs_inductor_compile, + trace_joint_graph=aot_state.needs_autograd and not aot_config.pre_dispatch, + ) + + return AOTGraphCapture( + wrappers=wrappers, + graph_module=graph, + updated_flat_args=updated_flat_args, + updated_flat_args_descs=updated_flat_args_descs, + maybe_subclass_meta=maybe_subclass_meta, + ) + + +def aot_stage2_export( + aot_state: AOTState, aot_graph_capture: AOTGraphCapture +) -> DispatchReturn: + graph = aot_graph_capture.graph_module + aot_config = aot_state.aot_config + wrappers = aot_graph_capture.wrappers + + CompileEventLogger.try_add_pt2_compile("backend_compile", dispatch_mode="export") + + # NB: the wrappers that run in pre_compile for export are + # either a no-op, because they're not needed, or will raise a runtime error, + # since they don't support export. + # We still run these wrappers to make sure that they're not needed pre compile, + # but we technically don't need to run them post compile at all here. + compiled_fn, aot_state.fw_metadata = post_compile( + wrappers, + graph, # pyrefly: ignore [bad-argument-type] + aot_config, + runtime_metadata=aot_state.fw_metadata, + ) + + # Therefore, since no wrapperes run, we don't get back a callable - we get back the raw fx graph + # (either a joint or an inference-only graph) + if not isinstance(compiled_fn, torch.fx.GraphModule): + raise AssertionError( + f"expected compiled_fn to be GraphModule, got {type(compiled_fn)}" + ) + return compiled_fn, aot_state.fw_metadata + + +def _get_inner_meta( + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, +) -> ViewAndMutationMeta: + """ + Util to get view and mutation metadata. + """ + return ( + fw_metadata if maybe_subclass_meta is None else maybe_subclass_meta.fw_metadata + ) + + +def _apply_tensorify_python_scalars(module: torch.fx.GraphModule) -> None: + """ + Util to apply tensorify_python_scalars. + """ + # TODO(anijain2305) - Add tensorify_python_scalars to the HOP graph passes. + fake_mode = detect_fake_mode() + if fake_mode is not None and fake_mode.shape_env is not None: + tensorify_python_scalars(module, fake_mode.shape_env, fake_mode) + + +def aot_stage2_compile( + aot_state: AOTState, + aot_graph_capture: AOTGraphCapture, + # pyrefly: ignore [implicit-any] + partition_fn: Callable, + # pyrefly: ignore [implicit-any] + fw_compiler: Callable, + # pyrefly: ignore [implicit-any] + bw_compiler: Callable | None = None, + # pyrefly: ignore [implicit-any] + inference_compiler: Callable | None = None, +) -> DispatchReturn: + if bw_compiler is None: + bw_compiler = fw_compiler + if inference_compiler is None: + inference_compiler = fw_compiler + + if aot_state.needs_autograd and not aot_state.aot_config.pre_dispatch: + return aot_stage2_autograd( + aot_state, + aot_graph_capture, + partition_fn, + fw_compiler, + bw_compiler, + ) + else: + return aot_stage2_inference( + aot_state, + aot_graph_capture, + partition_fn, + inference_compiler, + ) + + +def _log_inference_graph( + fw_module: torch.fx.GraphModule, + aot_config: AOTConfig, +) -> str | None: + """ + Log the inference graph to the structured logger. + Return a str representation of the graph. + """ + if aot_config.enable_log: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "torch._functorch.config", + "encoding": "string", + }, + payload_fn=lambda: torch._functorch.config.get_serializable_config_copy(), + ) + + # Save the forward_graph_str right after aot_dispatch_base_graph, + # to save in the cache + aot_forward_graph_str = None + if aot_config.cache_info is not None: + aot_forward_graph_str = fw_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + fast_sympy_print=True, + expanded_def=True, + ) + + return aot_forward_graph_str + + +def _aot_stage2b_inference_compile( + fw_module: torch.fx.GraphModule, + updated_flat_args: list[Any], + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + inference_compiler: Callable, + # pyrefly: ignore [implicit-any] +) -> Callable: + return _aot_stage2b_compile_forward_or_inference( + fw_module, + updated_flat_args, # type: ignore[arg-type] + maybe_subclass_meta, + fw_metadata, + aot_config, + inference_compiler, + is_inference=True, + )[1] + + +def aot_stage2_inference( + aot_state: AOTState, + aot_graph_capture: AOTGraphCapture, + # pyrefly: ignore [implicit-any] + partition_fn: Callable, + # pyrefly: ignore [implicit-any] + inference_compiler: Callable, +) -> DispatchReturn: + """ + Handles functions that don't need autograd. Runs wrappers and compiles with + the stage-2 inference compiler. + """ + + aot_config = aot_state.aot_config + fw_metadata = aot_state.fw_metadata + fw_module = aot_graph_capture.graph_module + wrappers = aot_graph_capture.wrappers + updated_flat_args = aot_graph_capture.updated_flat_args + maybe_subclass_meta = aot_graph_capture.maybe_subclass_meta + + CompileEventLogger.try_add_pt2_compile("backend_compile", dispatch_mode="inference") + aot_forward_graph_str = _log_inference_graph(fw_module, aot_config) + + if not isinstance(fw_module, GraphModule): + raise AssertionError( + f"expected fw_module to be GraphModule, got {type(fw_module)}" + ) + _apply_tensorify_python_scalars(fw_module) + + # When trace_autograd_ops=True, the inference graph may contain fw/bw + # invoke_subgraph pairs from traced torch.autograd.grad/backward calls. + # Partition them before the remat pass so that remat duplicates the + # already-partitioned fw subgraphs (which produce saved tensors for bw). + fw_module = run_joint_graph_passes_on_hops( + fw_module, None, aot_config, default_partition_fn=partition_fn + ) + + # Apply AC rematerialization after HOP partitioning. This must happen + # after partitioning so remat duplicates the partitioned fw subgraphs + # (not the original unpartitioned ones). + if torch._functorch.config.remat_using_tags_for_fwd_loss_bwd_graph: + from torch._functorch._activation_checkpointing.remat_using_tags_for_fwd_loss_bwd_graph_pass import ( + remat_using_tags_for_fwd_loss_bwd_graph, + ) + + fw_module = remat_using_tags_for_fwd_loss_bwd_graph(fw_module) + + if _has_invoke_subgraph_node(fw_module): + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_inference_graph_after_hop_passes", + "encoding": "string", + }, + payload_fn=lambda: fw_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ), + ) + + compiled_fw = _aot_stage2b_inference_compile( + fw_module, + updated_flat_args, # type: ignore[arg-type] + maybe_subclass_meta, + fw_metadata, + aot_config, + inference_compiler, + ) + + entry = _cache_inference_info( + aot_config, + fw_metadata, + maybe_subclass_meta, + compiled_fw, + aot_forward_graph_str, + wrappers, + ) + + return _aot_stage2c_make_inference_function( + aot_config, + fw_metadata, + compiled_fw, + wrappers, + entry, + ) + + +def _cache_inference_info( + aot_config: AOTConfig, + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: SubclassMeta | None, + compiled_fw: Callable[..., Any], + aot_forward_graph_str: str | None, + wrappers: list[CompilerWrapper], +) -> GenericAOTAutogradResult[Any, Any] | None: + make_runtime_safe(fw_metadata, maybe_subclass_meta) + + cache_info = aot_config.cache_info + + entry: GenericAOTAutogradResult[Any, Any] | None = None + if cache_info is not None and _should_save_cache(compiled_fw): + time_taken_ns = time.time_ns() - cache_info.start_time_ns + guards_expr = AOTAutogradCache.generate_guards_expression(cache_info) + entry = AOTAutogradCache.make_entry( + compiled_fw_func=compiled_fw, # type: ignore[arg-type] + compiled_bw_func=None, + aot_joint_graph_str=None, + aot_forward_graph_str=aot_forward_graph_str, + aot_backward_graph_str=None, + runtime_metadata=fw_metadata, + dispatch_wrappers=wrappers, + maybe_subclass_meta=maybe_subclass_meta, + num_fw_outs_saved_for_bw=None, + indices_of_inps_to_detach=[], + forward_time_taken_ns=time_taken_ns, + backward_time_taken_ns=0, + sanitized_aot_config=aot_config.to_cacheable(), + guards_expr=guards_expr, + backward_state_indices=None, + num_symints_saved_for_bw=None, + serialized_bw_module=None, + min_cut_info_str=None, + ) + AOTAutogradCache.save( + cache_info.cache_key, + entry, + remote=should_use_remote_autograd_cache(), + ) + + return entry + + +def _aot_stage2c_make_inference_function( + aot_config: AOTConfig, + fw_metadata: ViewAndMutationMeta, + compiled_fw: Callable[..., Any], + wrappers: list[CompilerWrapper], + entry: GenericAOTAutogradResult[Any, Any] | None, +) -> DispatchReturn: + if entry is not None: + compiled_fw = SerializableCompiledFunction(compiled_fw, lambda: entry) + + disable_amp = torch._C._is_any_autocast_enabled() + compiled_fn = RuntimeWrapper( + indices_of_inps_to_detach=[], + trace_joint=False, + disable_amp=disable_amp, + ).post_compile( + compiled_fw, + aot_config, + runtime_metadata=fw_metadata, + ) + + compiled_fn = post_compile( + wrappers, compiled_fn, aot_config, runtime_metadata=fw_metadata + ) + return compiled_fn + + +def collect_fw_donated_buffer_idxs( + fw_ins: list[FakeTensor | None], + user_fw_outs: list[FakeTensor | None], + bw_outs: list[FakeTensor | None], + saved_tensors: list[FakeTensor | None], +) -> list[int]: + """ + Checks if the saved tensors are donated buffers, which means a saved tensor is not + an alias of any tensors in fw_ins, user_fw_outs, and bw_outs. + """ + + storage_refs = set() + + for t in itertools.chain(fw_ins, user_fw_outs, bw_outs): + # Only access storage if a tensor has storage (not sparse) + if t is not None and is_fake_tensor(t) and not is_sparse_any(t): + storage_refs.add(StorageWeakRef(t.untyped_storage())) + + num_saved_tensor = len(saved_tensors) + donated_buffer_idxs = [] + for i in range(num_saved_tensor): + t = saved_tensors[i] + if ( + t is not None + and is_fake_tensor(t) + and not is_sparse_any(t) + and StorageWeakRef(t.untyped_storage()) not in storage_refs + ): + donated_buffer_idxs.append(i) + + return donated_buffer_idxs + + +def collect_bw_donated_buffer_idxs( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + fw_metadata: ViewAndMutationMeta, +) -> list[int]: + """ + Collects backward donated buffer indexes from fw_module and bw_module. + """ + + # [Note: Metadata mutation in proxy tracing] + # node.meta["val"] is a snapshot of the tensor value when tracing a graph, + # instead of the final state after the graph has run. node.meta["val"] is + # not updated even if later there is a metadata mutation op. + # See: https://github.com/pytorch/pytorch/pull/141308#issuecomment-2495798947 + # + # Currently, metadata mutation op happens only for sacrificial parameter + # specifically the `set_` op. This motivates banning metadata mutation from + # proxy tracing. + # + # Since node.meta["val"] is used to detect donated buffer, we return an empty + # list if there exists metadata mutation op. + if contain_metadata_mutation_ops(fw_module) or contain_metadata_mutation_ops( + bw_module + ): + return [] + + fw_ins = fw_module.graph.find_nodes(op="placeholder") + bw_outs = next(reversed(bw_module.graph.find_nodes(op="output"))).args[0] + fw_outs = next(reversed(fw_module.graph.find_nodes(op="output"))).args[0] + + fw_ins = [ + n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None + for n in fw_ins + ] + fw_outs = [ + n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None + for n in fw_outs + ] + bw_outs = [ + n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None + for n in bw_outs + ] + + user_fw_outs = fw_outs[: fw_metadata.num_forward] + saved_tensors = fw_outs[fw_metadata.tensors_saved_for_backwards_slice] + + fw_donated_buffer = collect_fw_donated_buffer_idxs( + fw_ins, + user_fw_outs, + bw_outs, + saved_tensors, + ) + + if fw_metadata.num_symints_saved_for_bw is None: + raise AssertionError("fw_metadata.num_symints_saved_for_bw must not be None") + return [fw_metadata.num_symints_saved_for_bw + i for i in fw_donated_buffer] + + +@dataclasses.dataclass +class InvokeSubgraphHopGraphs: + """ + A data structure to hold all the information needed to partition the + `joint_hop_gm` and joint graph and the restitch the `new_fw_hop_gm` and + `new_bw_hop_gm` into the bigger `joint_gm`. + """ + + # To avoid re-partitioning subgraphs + partitioning_done: bool = False + old_num_fw_outputs: int | None = None + old_num_fw_inputs: int | None = None + + new_fw_hop_gm: torch.fx.GraphModule | None = None + new_bw_hop_gm: torch.fx.GraphModule | None = None + new_num_sym_nodes: int | None = None + new_num_saved_nodes: int | None = None + + +def prepare_for_partitioner( + mod: torch.fx.GraphModule, num_primals: int, num_fw_outputs: int +) -> torch.fx.GraphModule: + # min-cut partitioner requires the placeholders to have primals and + # tangents string in the node.name. The signature of the joint graph is + # (*primals, *tangents) + + # We also have to update the output signature which is right now + # (*grads, *fw_outs) and we have to change to (*fw_outs, *grads) for the + # partitioner to work. + new_graph = torch.fx.Graph() + env = {} + + primals_counter = itertools.count(0) + tangents_counter = itertools.count(0) + + for idx, node in enumerate(mod.graph.nodes): + if node.op == "placeholder": + if idx < num_primals: + env[node] = new_graph.placeholder(f"primals_{next(primals_counter)}") + else: + env[node] = new_graph.placeholder(f"tangents_{next(tangents_counter)}") + env[node].meta = copy.copy(node.meta) + elif node.op == "output": + # Reverse the (*grads, *fw_outs) to (*fw_outs, *grads) + # The reason for having the reversed signature in the first + # place is to simplify step 3. + old_outputs = node.args[0] + new_outputs = ( + *old_outputs[-num_fw_outputs:], + *old_outputs[:-num_fw_outputs], + ) + new_outputs = [env[n] if n else None for n in new_outputs] + new_graph.output(tuple(new_outputs)) + else: + env[node] = new_graph.node_copy(node, lambda n: env[n]) + env[node].meta = copy.copy(node.meta) + + new_graph.lint() + + out = torch.fx.GraphModule(mod, new_graph) + return out + + +def _get_partition_fn( + fw_hop_node: torch.fx.Node, + aot_config: AOTConfig, + default_partition_fn: Callable[ + ..., tuple[torch.fx.GraphModule, torch.fx.GraphModule] + ] + | None, +) -> tuple[bool, Callable[..., tuple[torch.fx.GraphModule, torch.fx.GraphModule]]]: + """ + Return either `default_partition_fn` or a HOP specific partition function. + + If a HOP specific partition function is returned, used_hop_custom_partition is True. + + See Note [InvokeSubgraphHOP Partitioner] + """ + used_hop_custom_partition = False + + # Check for HOP-specific partition function first. This is needed because + # run_joint_graph_passes_on_hops can be called without an outer stage-2 + # partition function (e.g., in aot_stage1_graph_capture before the remat + # pass). + if ( + fw_hop_node.target == torch._higher_order_ops.invoke_subgraph + and "custom" in fw_hop_node.meta + and "nested_region_config" in fw_hop_node.meta["custom"] + ): + hop_partition_fn = fw_hop_node.meta["custom"][ + "nested_region_config" + ].partitioner + if hop_partition_fn is not None: + if callable(hop_partition_fn): + raw_partitioner = hop_partition_fn + elif not isinstance(hop_partition_fn, str): + raise AssertionError( + f"expected hop_partition_fn to be str, got {type(hop_partition_fn)}" + ) + else: + match hop_partition_fn: + case "default_partition": + raw_partitioner = ( + torch._functorch.partitioners.default_partition + ) + case "min_cut_rematerialization_partition": + raw_partitioner = torch._functorch.partitioners.min_cut_rematerialization_partition + case _: + raise ValueError( + f"Unknown HOP partitioner config: {hop_partition_fn}" + ) + + # Route through Inductor's `partition_fn` so joint-graph passes + # (e.g. scatter_upon_const_tensor) run on the HOP subgraph before + # the user-selected raw partitioner. + from torch._inductor.compile_fx import ( + partition_fn as _inductor_partition_fn, + ) + + return True, functools.partial( + _inductor_partition_fn, partitioner_fn_override=raw_partitioner + ) + + # Fall back to the parent partitioner from aot_config. When the outer + # compile is Inductor this is already `compile_fx.partition_fn` so + # joint-graph passes run there too. + if default_partition_fn is None: + raise AssertionError("default_partition_fn must not be None") + return used_hop_custom_partition, default_partition_fn + + +def _has_invoke_subgraph_node(gm: torch.fx.GraphModule): + from torch._higher_order_ops import invoke_subgraph + + for node in gm.graph.nodes: + if node.op == "call_function" and node.target is invoke_subgraph: + return True + return False + + +def run_joint_graph_passes_on_hops( + joint_gm: torch.fx.GraphModule, + joint_inputs: Any, + aot_config: AOTConfig, + *, + default_partition_fn: Callable[ + ..., tuple[torch.fx.GraphModule, torch.fx.GraphModule] + ] + | None = None, +) -> torch.fx.GraphModule: + """ + This pass runs the joint graph passes on the HOP graph. In torch.compile, we + typically have many passes which work on the joint graph and then end with a + partitioner. + + + The partitioner part is quite mechanical to handle. HOP have their own + forward and backward graph. The process can be broken into following steps + + 1) Get a `joint_hop_gm` from the `fw_hop_gm` and `bw_hop_gm` + 2) Run joint graph passes on the `joint_hop_gm` to get `new_fw_hop_gm` and `new_bw_hop_gm` + 3) Stitch the `new_fw_hop_gm` and `new_bw_hop_gm` back into the `joint_gm`. + + The terminology used in the code is + `joint_graph/joint_gm` : Refers to the main graph. This may contain many HOPs which have their own `hop_graph` + `fw_hop_graph/fw_hop_gm` : Refers to the forward graph associated with a HOP. + `bw_hop_graph/bw_hop_gm` : Refers to the backward graph associated with a HOP. + `joint_hop_graph/joint_hop_gm` : Refers to the subgraph associated with the HOP like invoke_subgraph. + `new_fw_hop_graph/new_fw_hop_gm` : Refers to the forward graph after partitioning is applied to `joint_hop_gm`. + `new_bw_hop_graph/new_bw_hop_gm` : Refers to the backward graph after partitioning is applied to `joint_hop_gm`. + + NB: This pass works for invoke_subgraph today because we took extra care in + the Autograd.Dispatch key of invoke_subgraph to vastly simplify Step 1. + + NB: This pass only matches **top-level** invoke_subgraph HOP nodes in + `joint_gm`. It does not recurse into subgraph modules, so when one + `nested_compile_region` is invoked from inside another, the inner + invoke_subgraph HOPs live inside the outer's subgraph module and are not + paired here. Top-level HOPs are still paired correctly via `call_id`; + recursive partitioning of nested regions is left to downstream passes. + """ + from torch._higher_order_ops import invoke_subgraph + from torch._higher_order_ops.invoke_subgraph import ( + get_backward_nested_region_config, + ) + + def num_outputs(mod: torch.fx.GraphModule) -> int: + return len(mod.graph.find_nodes(op="output")[0].args[0]) + + def num_inputs(mod: torch.fx.GraphModule) -> int: + return len(mod.graph.find_nodes(op="placeholder")) + + new_hop_graphs: dict[str, InvokeSubgraphHopGraphs] = defaultdict( + lambda: InvokeSubgraphHopGraphs() + ) + + # Step 1 - Get a `joint_hop_gm` from the `fw_hop_gm` and `bw_hop_gm` This is + # easy to do for `invoke_subgraph` HOP. During the Autograd dispatch key + # tracing, we have put the joint_hop_graph in the backward hop graph itself. + # So to recover the joint_hop_gm, we just have to look at the backward + # HOP graphs. + # So we will merge step 1 and step 2 in this next section + + # Save the fw and bwd hop nodes. We will later in-place modify the graph + # using these nodes. + # pyrefly: ignore [implicit-any] + fw_hop_nodes = [] + # pyrefly: ignore [implicit-any] + bw_hop_nodes = [] + for node in joint_gm.graph.nodes: + if ( + node.op == "call_function" + and node.target is invoke_subgraph + and isinstance(node.args[1], str) + ): + if node.args[1].startswith("fw"): + fw_hop_nodes.append(node) + elif node.args[1].startswith("bw"): + bw_hop_nodes.append(node) + + if not bw_hop_nodes: + return joint_gm + + # The fw and bw HOP counts are not necessarily equal. A fw HOP can have no + # corresponding bw HOP when autograd never runs backward through that call + # — e.g. the user does `x_d = x.detach().requires_grad_()` between two + # regions, or some outputs are not used in the loss. Likewise, multiple fw + # calls in the same compile region can share a single bw if autograd dedups + # or DCEs intermediate bws. + # + # Pair fw and bw HOPs by `call_id` — a per-call counter stamped by + # InvokeSubgraphAutogradOp's fw/bw on each FX node. This is unambiguous + # regardless of how autograd dispatched the backward (single outer + # `.backward()`, per-iter `.backward()` in a loop, interleaved regions). + fws_by_call_id: dict[int, torch.fx.Node] = {} + for fw in fw_hop_nodes: + cid = fw.meta.get("custom", {}).get("call_id") + if cid is None: + continue + if cid in fws_by_call_id: + raise AssertionError( + f"duplicate call_id={cid} on fw HOPs " + f"{fws_by_call_id[cid].name!r} and {fw.name!r}" + ) + fws_by_call_id[cid] = fw + + bw_to_fw_hop_node: dict[torch.fx.Node, torch.fx.Node] = {} + paired_fws: set[torch.fx.Node] = set() + for bw in bw_hop_nodes: + cid = bw.meta.get("custom", {}).get("call_id") + if cid is None: + raise AssertionError( + f"bw HOP {bw.args[1]!r} has no call_id in meta['custom']" + ) + fw = fws_by_call_id.get(cid) + if fw is None: + raise AssertionError( + f"could not find matching fw HOP for bw {bw.args[1]!r} " + f"with call_id={cid} (fw call_ids: {sorted(fws_by_call_id)})" + ) + bw_to_fw_hop_node[bw] = fw + paired_fws.add(fw) + + # Extra fws share a compile region with a paired bw but have no bw of + # their own (autograd may dedup or DCE the bw). They still must be + # rewritten to call the new partitioned fw subgraph, otherwise the output + # signatures diverge from the rewritten paired fws. Key by the bw + # identifier so the key matches `new_hop_graphs`. + fw_args_to_bw_identifier: dict[str, str] = {} + for bw, fw in bw_to_fw_hop_node.items(): + fw_arg = fw.args[1] + bw_arg = bw.args[1] + if not (isinstance(fw_arg, str) and isinstance(bw_arg, str)): + raise AssertionError( + f"expected fw/bw invoke_subgraph HOP args[1] to be str identifiers, " + f"got fw={type(fw_arg)}, bw={type(bw_arg)}" + ) + fw_args_to_bw_identifier.setdefault(fw_arg, bw_arg.removeprefix("bw")) + extra_fws_by_id: dict[str, list[torch.fx.Node]] = defaultdict(list) + for fw in fw_hop_nodes: + if fw in paired_fws: + continue + bw_ident_key = fw_args_to_bw_identifier.get(fw.args[1]) + if bw_ident_key is None: + continue + extra_fws_by_id[bw_ident_key].append(fw) + + for node in bw_hop_nodes: + identifier = node.args[1].removeprefix("bw") + + # If partitioning already done for this identifier, skip. This saves + # redundant joint graph passes for same subgraphs. + if new_hop_graphs[identifier].partitioning_done: + continue + + # Collect some information from the forward hop graph + fw_hop_node = bw_to_fw_hop_node[node] + fw_subgraph_attr = fw_hop_node.args[0] + if not isinstance(fw_subgraph_attr, torch.fx.Node): + raise AssertionError( + f"expected fw invoke_subgraph HOP args[0] to be torch.fx.Node, " + f"got {type(fw_subgraph_attr)}" + ) + fw_subgraph_attr_target = fw_subgraph_attr.target + if not isinstance(fw_subgraph_attr_target, str): + raise AssertionError( + f"expected fw invoke_subgraph HOP args[0].target to be str, " + f"got {type(fw_subgraph_attr_target)}" + ) + fw_hop_gm = getattr(joint_gm, fw_subgraph_attr_target) + if not isinstance(fw_hop_gm, torch.fx.GraphModule): + raise AssertionError( + f"expected fw_hop_gm to be GraphModule, got {type(fw_hop_gm)}" + ) + num_fw_inputs = num_inputs(fw_hop_gm) + num_fw_outputs = num_outputs(fw_hop_gm) + new_hop_graphs[identifier].old_num_fw_inputs = num_fw_inputs + new_hop_graphs[identifier].old_num_fw_outputs = num_fw_outputs + + # Step 1) - Get the `joint_hop_gm`. As mentioned earlier, the + # backward graph is the joint graph. + joint_hop_gm = getattr(joint_gm, node.args[0].target) + if not isinstance(joint_hop_gm, torch.fx.GraphModule): + raise AssertionError( + f"expected joint_hop_gm to be GraphModule, got {type(joint_hop_gm)}" + ) + + # Prepare the graph for the partitioner + joint_hop_gm = prepare_for_partitioner( + joint_hop_gm, num_fw_inputs, num_fw_outputs + ) + + # TODO: invoke_subgraph should track which of its inputs static indices + # so it can propagate them to the partitioner (and use in cudagraphs) + static_lifetime_input_indices: list[int] = [] + + used_hop_custom_partition, partition_fn = _get_partition_fn( + fw_hop_node, aot_config, default_partition_fn + ) + + # Step 2) and 3) - Run joint graph passes and partitioner + try: + new_fw_hop_gm, new_bw_hop_gm = partition_fn( + joint_hop_gm, + [], + num_fwd_outputs=num_fw_outputs, + static_lifetime_input_indices=static_lifetime_input_indices, + ) + except Exception as e: + if used_hop_custom_partition: + raise RuntimeError( + f"Error in custom partition function for invoke_subgraph node {fw_hop_node.name}: {e}" + ) from e + else: + raise + + # Save the new forward and backward graph modules + new_hop_graphs[identifier].new_fw_hop_gm = new_fw_hop_gm + new_hop_graphs[identifier].new_bw_hop_gm = new_bw_hop_gm + + # Save the number of symints and saved tensors + new_fw_out_nodes = new_fw_hop_gm.graph.find_nodes(op="output")[0].args[0] + extra_outputs = new_fw_out_nodes[num_fw_outputs:] + symint_outputs = [n for n in extra_outputs if is_sym_node(n)] + + new_hop_graphs[identifier].new_num_sym_nodes = len(symint_outputs) + new_hop_graphs[identifier].new_num_saved_nodes = len(extra_outputs) - len( + symint_outputs + ) + + new_hop_graphs[identifier].partitioning_done = True + + # Step 3) Restitch the new fw and bw graphs back into the main graph. + # + # This is a very mechanical process. There are a quite a few pieces that we + # need to connect together to make it work. Lets try to understand the + # problem statement first. + # + # For the forward graph, the signature of the old_fw_hop_gm is + # inputs - (*primals) + # outputs - (*fw_outs) + # Now the signature of the new_fw_hop_gm is + # inputs - (*primals) -- This is same + # outputs - (*fw_outs, *saved_tensors) - This is different + # At a high level, this is an easy transformation, in the new graph we just + # have to replace the old_fw_hop_gm with the new_fw_hop_gm. Everything else + # falls into place, because the input signature (i.e. args) is same. And + # even though output signature is different, fw_outs are still at the same + # indexes as before. So the forward of the `joint_gm` works nicely. + # + # Now, lets look at the backward hop graph. Old signature + # inputs - (*primals, *tangents) + # outputs - (*grad_outs, *fw_outs) + # New signature + # inputs - (*saved_tensors, *tangents) -- Different + # outputs - (*grad_outs) -- Different + # Here both input and output signature change. The output signature handling + # is quite easy because the grads_out are sitting at the right place, so we + # don't have to do anything. + # + # For the input signature, we have to collect the saved tensors from the + # corresponding forward graph output. We collect all saved_tensors when we + # see the forward graph, and save it into a map and then later use it during + # the backward. + + # The stack of fw_nodes for invoke_subgraph HOP. There is an implicit + # assumption about the graph structure, i.e., if we have hop1, hop2, hop3, + # ... in the forward part of the joint graph, we will have .., hop3, hop2, + # hop1 order for the backward. This structure allows us to just use a stack + # to collect all the information that we need to pass from the forward hop + # node to the corresponding backward node. + + already_added_new_hop_mods = set() + + def add_new_hop_gm(new_subgraph_mod: torch.fx.GraphModule, name: str) -> str: + new_subgraph_attr_name = f"partitioned_{name}" + if new_subgraph_attr_name in already_added_new_hop_mods: + return new_subgraph_attr_name + + joint_gm.register_module(new_subgraph_attr_name, new_subgraph_mod) + already_added_new_hop_mods.add(new_subgraph_attr_name) + return new_subgraph_attr_name + + def propagate_meta_info( + new_hop_gm: torch.fx.GraphModule, + new_call_function_node: torch.fx.Node, + old_call_function_node: torch.fx.Node, + ) -> None: + # Copy all the fields from the old call_function node. And then override + # the `val` meta field with the outputs of new_hop_gm. + new_call_function_node.meta = copy.copy(old_call_function_node.meta) + + output = new_hop_gm.graph.find_nodes(op="output")[0] + out_example_vals = [n.meta["val"] if n else None for n in output.args[0]] + new_call_function_node.meta["val"] = tuple(out_example_vals) + + for bw_node in reversed(bw_hop_nodes): + identifier = bw_node.args[1].removeprefix("bw") + + # Make changes to the corresponding fw and bw node pair simultaneously. + # The removes the need of any bookkeeping. + + # Fw node changes + # Insert the new_fw_hop_gm. This is straightforward. Get the + # new_fw_hop_gm, insert the hop_gm as a get_attr fw_node, and then + # add a call_function fw_node. Additionally, also use getitem + # call_functions to collect the saved_tensor nodes + + fw_node = bw_to_fw_hop_node[bw_node] + new_fw_hop_gm = new_hop_graphs[identifier].new_fw_hop_gm + if new_fw_hop_gm is None: + raise AssertionError( + f"new_fw_hop_gm for identifier {identifier} must not be None" + ) + + old_num_fw_outputs = new_hop_graphs[identifier].old_num_fw_outputs + new_num_sym_nodes = new_hop_graphs[identifier].new_num_sym_nodes + new_num_saved_nodes = new_hop_graphs[identifier].new_num_saved_nodes + if old_num_fw_outputs is None: + raise AssertionError( + f"old_num_fw_outputs for identifier {identifier} must not be None" + ) + if new_num_sym_nodes is None: + raise AssertionError( + f"new_num_sym_nodes for identifier {identifier} must not be None" + ) + if new_num_saved_nodes is None: + raise AssertionError( + f"new_num_saved_nodes for identifier {identifier} must not be None" + ) + total_outputs = old_num_fw_outputs + new_num_saved_nodes + new_num_sym_nodes + + extra_fw_outputs = [] + + # Insert the new_fw_hop_gm into the joint_gm + fw_subgraph_attr = fw_node.args[0] + if not isinstance(fw_subgraph_attr, torch.fx.Node): + raise AssertionError( + f"expected fw invoke_subgraph HOP args[0] to be torch.fx.Node, " + f"got {type(fw_subgraph_attr)}" + ) + with joint_gm.graph.inserting_after(fw_node): + new_fw_mod_attr_name = add_new_hop_gm(new_fw_hop_gm, f"fw{identifier}") + new_fw_mod_attr = joint_gm.graph.get_attr(new_fw_mod_attr_name) + new_fw_mod_attr.meta = copy.copy(fw_subgraph_attr.meta) + + # new_hop_fw_gm output signature is (*fw_outs, *saved_tensors) + with joint_gm.graph.inserting_after(new_fw_mod_attr): + new_fw_node = joint_gm.graph.call_function( + the_function=invoke_subgraph, + args=( + new_fw_mod_attr, + new_fw_mod_attr_name, + *fw_node.args[2:], + ), + ) + propagate_meta_info(new_fw_hop_gm, new_fw_node, fw_node) + + # old_num_fw_outputs = (*fw_outs) + # new_num_fw_outputs = (*fw_outs, *saved_tensors, *sym_nodes) + with joint_gm.graph.inserting_after(new_fw_node): + for fw_out_idx in range(old_num_fw_outputs, total_outputs): + saved_tensor_node = joint_gm.graph.call_function( + the_function=operator.getitem, args=(new_fw_node, fw_out_idx) + ) + saved_tensor_node.meta = copy.copy(new_fw_node.meta) + saved_tensor_node.meta["val"] = new_fw_node.meta["val"][fw_out_idx] + extra_fw_outputs.append(saved_tensor_node) + + fw_node.replace_all_uses_with(new_fw_node) + joint_gm.graph.erase_node(fw_node) + + # Bw node changes + # Prepare the operands for the bwd graph + # Old bw graph signature : (*primals, *tangents) + # New signature will be : (*sym_nodes, *saved_tensors, *tangents) + # We have already collected the saved_tensors in the forward hop processing. + + # extra_fw_outputs are in the order (*saved_nodes, *sym_nodes). + # Partitioner has this quirk where the backward wants sym_nodes + # first. So extract the sym and saved nodes. + + new_bw_hop_gm = new_hop_graphs[identifier].new_bw_hop_gm + if new_bw_hop_gm is None: + raise AssertionError( + f"new_bw_hop_gm for identifier {identifier} must not be None" + ) + + saved_tensor_nodes = extra_fw_outputs[:new_num_saved_nodes] + sym_nodes = extra_fw_outputs[new_num_saved_nodes:] + + num_primals = new_hop_graphs[identifier].old_num_fw_inputs + if num_primals is None: + raise AssertionError( + f"num_primals for identifier {identifier} must not be None" + ) + tangents = list(bw_node.args[2 + num_primals :]) + operands = sym_nodes + saved_tensor_nodes + tangents + + # Insert the new_bw_hop_gm into the joint_gm + with joint_gm.graph.inserting_after(bw_node): + new_bw_mod_attr_name = add_new_hop_gm(new_bw_hop_gm, bw_node.args[1]) + new_bw_mod_attr = joint_gm.graph.get_attr(new_bw_mod_attr_name) + new_bw_mod_attr.meta = copy.copy(bw_node.args[0].meta) + + with joint_gm.graph.inserting_after(new_bw_mod_attr): + new_bw_node = joint_gm.graph.call_function( + the_function=invoke_subgraph, + args=( + new_bw_mod_attr, + new_bw_mod_attr_name, + *operands, + ), + ) + propagate_meta_info(new_bw_hop_gm, new_bw_node, bw_node) + # Since the partitioner is run after the graph passes, we have lost + # the eager information and cannot faithfully extract the eager + # inputs for the new partitioned backward graph. For the forward + # graph, it was fine because the input signature remains same. + new_bw_node.meta.pop("eager_input_vals", None) + + # When the region sets backward-specific inductor config, compile the + # partitioned backward under it; the forward keeps its own config. + fw_region_config = fw_node.meta.get("custom", {}).get( + "nested_region_config" + ) + # get_backward_nested_region_config returns fw_config unchanged when + # the region has no distinct backward config, so identity tells us + # whether to stamp. + bw_region_config = get_backward_nested_region_config(fw_region_config) + if bw_region_config is not fw_region_config: + # Re-stamp on the fresh backward node's meta["custom"] (the source + # of truth: unlike a GraphModule's meta it survives FX transforms). + # Lowering picks it up via the subgraph-module mirror (_propagate_*) + # or the ir.py node fallback. + new_bw_node.meta["custom"] = { + **new_bw_node.meta.get("custom", {}), + "nested_region_config": bw_region_config, + } + + bw_node.replace_all_uses_with(new_bw_node) + joint_gm.graph.erase_node(bw_node) + + # Rewrite extra (unpaired) fws to call the new partitioned fw subgraph. + # Their additional saved-tensor outputs become dead and are pruned by + # eliminate_dead_code. + for identifier, extras in extra_fws_by_id.items(): + if not new_hop_graphs[identifier].partitioning_done: + continue + new_fw_hop_gm = new_hop_graphs[identifier].new_fw_hop_gm + if new_fw_hop_gm is None: + continue + for fw_node in extras: + fw_subgraph_attr = fw_node.args[0] + if not isinstance(fw_subgraph_attr, torch.fx.Node): + raise AssertionError( + f"expected fw invoke_subgraph HOP args[0] to be torch.fx.Node, " + f"got {type(fw_subgraph_attr)}" + ) + with joint_gm.graph.inserting_after(fw_node): + new_attr_name = add_new_hop_gm(new_fw_hop_gm, f"fw{identifier}") + new_attr = joint_gm.graph.get_attr(new_attr_name) + new_attr.meta = copy.copy(fw_subgraph_attr.meta) + with joint_gm.graph.inserting_after(new_attr): + new_fw_node = joint_gm.graph.call_function( + the_function=invoke_subgraph, + args=(new_attr, new_attr_name, *fw_node.args[2:]), + ) + propagate_meta_info(new_fw_hop_gm, new_fw_node, fw_node) + fw_node.replace_all_uses_with(new_fw_node) + joint_gm.graph.erase_node(fw_node) + + joint_gm.graph.eliminate_dead_code() + joint_gm.graph.lint() + joint_gm.recompile() + return joint_gm + + +def maybe_log_graph( + gm: torch.fx.GraphModule, + graph_name: str, + aot_config: AOTConfig, + structured_log_prefix_fn: Callable[[], str], + out_structured_logs: list[str] | None = None, +) -> None: + if not aot_config.enable_log: + return + aot_graphs_log.debug( + "%s", + lazy_format_graph_code( + f"{graph_name}", + gm, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + + def gm_str_fn() -> str: + return gm.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ) + + if out_structured_logs is not None: + out_structured_logs.append(f"{structured_log_prefix_fn()}:{gm_str_fn()}") + else: + trace_structured( + f"{structured_log_prefix_fn()}", + payload_fn=lambda: gm_str_fn(), + ) + + +def create_wrap_fn( + fn: Callable[..., Any], args: tuple[Any, ...] +) -> tuple[Callable[..., Any], tuple[Any, ...]]: + from torch.fx.experimental.proxy_tensor import maybe_enable_thunkify + + from .functional_utils import from_fun, has_data_mutation, to_fun + + def assert_no_mutation(t: Any) -> None: + if has_data_mutation(t): + raise AssertionError( + "Saved tensors hooks with inputs mutations are not allowed" + ) + + @simple_wraps(fn) + def _wrapper(*args: Any) -> Any: + with maybe_enable_thunkify(): + disable_above = torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + + with disable_above: + f_args = pytree.tree_map(to_fun, args) + f_outs = fn(*f_args) + pytree.tree_map(assert_no_mutation, f_args) + return pytree.tree_map(from_fun, f_outs) + + return _wrapper, args + + +def prepare_hook_gm( + aot_config: AOTConfig, fn: Callable[..., Any], args: tuple[Any, ...] +) -> torch.fx.GraphModule: + from torch._functorch._aot_autograd.graph_capture import _create_graph + + fn, args = create_wrap_fn(fn, args) + gm = _create_graph(fn, args, aot_config=aot_config) # type: ignore[arg-type] + return gm + + +# Inline Autograd saved_tensors_hooks into epilogue of forward graph +# and prologue of backward graph. +# This changes forward graph outputs and inputs. +# Pack hook can return tensors, sym scalars, constants. +# All tensors to save for backward will be grouped together at front. +# Sym scalars grouped on another end. Constants are inlined in the graph. +def maybe_inline_graph_saved_tensors_hooks( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + num_inner_fwd_outputs: int, + inner_meta: ViewAndMutationMeta, + aot_config: AOTConfig, + static_input_indices: list[int], +) -> None: + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + return + + get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks + are_inline_hooks = ( + torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable + ) + + hooks = get_hooks() + if not are_inline_hooks(hooks): + return + + pack_hook_gm, unpack_hook_gm = hooks + + structured_logs: list[str] = [] + maybe_log_graph( + fw_module, + "Forward graph pre saved_tensors_hooks inlining", + aot_config, + lambda: "aot_forward_graph_pre_saved_tensors_hooks", + structured_logs, + ) + maybe_log_graph( + bw_module, + "Backward graph pre saved_tensors_hooks inlining", + aot_config, + lambda: "aot_backward_graph_pre_saved_tensors_hooks", + structured_logs, + ) + fw_g = fw_module.graph + bw_g = bw_module.graph + + fw_g_names = {node.name for node in fw_g.nodes} + bw_g_names = {node.name for node in bw_g.nodes} + + def _gen_unused_name(candidate: str) -> str: + c = candidate + i = 0 + while c in fw_g_names or c in bw_g_names: + c = f"{candidate}_{i}" + i = i + 1 + return c + + bw_g_inputs = bw_g.find_nodes(op="placeholder") + + fw_out_n = fw_g.output_node() + fw_outs = fw_out_n.args[0] # type: ignore[var-annotated] + fw_outs_inner_set = set(fw_outs[:num_inner_fwd_outputs]) # type: ignore[index] + fw_outs_saved_for_bw = fw_outs[num_inner_fwd_outputs:] # type: ignore[index] + fw_outs_packed_tensors = [] # type: ignore[var-annotated] + fw_outs_packed_syms = [] # type: ignore[var-annotated] + + # The main use case for saved_tensors_hooks is activation quantization, + # for memory usage optimization. + # Desired behavior is to quantize saved activations to free the original saved tensor. + # Saved nodes may include forward inputs, outputs, parameters. + # They may be held by something else and will not be deallocated after quantization. + # Donated buffers are intermediates in the graph invisible for the user, + # this guarantees that they can be deallocated. + # Using this as a default behavior to select saved nodes to apply hooks. + # There is also a config to apply hooks for all saved nodes without any filtering. + # The plan is to propagate meta about the source of the saved node to the user hook function. + mode = torch._functorch.config.saved_tensors_hooks_filtering_mode + allow_set = None + exclude_set = None + + if mode == "donated": + # collect_bw_donated_buffer_idxs requires inner_meta to have num_symints_saved_for_bw + inner_meta.num_symints_saved_for_bw = len( + [n for n in fw_outs_saved_for_bw if is_sym_node(n)] # type: ignore[arg-type] + ) + # Count tensors with no version counter check (used in tensors_saved_for_backwards_slice) + inner_meta.num_tensors_saved_with_no_vc_check = len( + [ + n + # pyrefly: ignore [not-iterable] + for n in fw_outs_saved_for_bw + if isinstance(n, torch.fx.Node) + and n.meta.get("saved_tensor_with_no_vc_check", False) + ] + ) + bw_donated_idxs = collect_bw_donated_buffer_idxs( + fw_module, + bw_module, + inner_meta, + ) + fw_donated_idxs = [ + i - inner_meta.num_symints_saved_for_bw for i in bw_donated_idxs + ] + allow_set = {fw_outs_saved_for_bw[i].name for i in fw_donated_idxs} # type: ignore[union-attr] + elif mode == "no_static": + fw_g_inputs = fw_g.find_nodes(op="placeholder") + exclude_set = {fw_g_inputs[i].name for i in static_input_indices} + + if (allow_set is not None) and (not allow_set): + # This means we have empty whitelist, + # No donated (intermediate) saved. + # Do not do anything in this case + return + + if aot_config.enable_log: + structured_logs.append(f"fw_outs_saved_for_bw:{fw_outs_saved_for_bw}") + structured_logs.append(f"mode:{mode}") + structured_logs.append(f"allow_set:{allow_set}") + structured_logs.append(f"exclude_set:{exclude_set}") + + # pyrefly: ignore [not-iterable] + for saved in fw_outs_saved_for_bw: + if ((allow_set is not None) and (saved.name not in allow_set)) or ( # type: ignore[union-attr] + (exclude_set is not None) and (saved.name in exclude_set) # type: ignore[union-attr] + ): + if isinstance(saved.meta["val"], torch.Tensor): # type: ignore[union-attr] + fw_outs_packed_tensors.append(saved) + continue + + val = saved.meta["val"] # type: ignore[union-attr] + if not isinstance(val, torch.Tensor): + continue + + def _get_extra_info() -> dict[str, Any]: + return {"_fw_graph": fw_g, "_bw_graph": bw_g, "_node": saved} + + with _saved_tensor_hook_context(_get_extra_info()): + pack_out_val = pack_hook_gm(val) + + requires_sc_handling = any( + is_traceable_wrapper_subclass(x) for x in pytree.tree_leaves(pack_out_val) + ) + if requires_sc_handling: + raise NotImplementedError( + "Tensor subclasses in GraphModule saved tensors hooks are not supported" + "You can workaround it by manually returning subclass's inner tensors" + " in the pack hook, and reconstructing the subclass in the unpack hook" + ) + + with _saved_tensor_hook_context(_get_extra_info()): + pack_gm = prepare_hook_gm(aot_config, pack_hook_gm, (val,)) + pack_g = pack_gm.graph + maybe_log_graph( + pack_gm, + f"saved_tensors_pack_hook {saved.name}", # type: ignore[union-attr] + aot_config, + lambda: f"aot_saved_tensors_hooks_pack {saved.name}", # type: ignore[union-attr] + structured_logs, + ) + pack_out_val = pack_gm(val) + + # Install pack hook graph as eiplogue of fw_module. + # Saved tensor output becomes input of pack hook graph. + # Replace saved tensor output with pack hook graph output. + # Outputs symbolic scalars, tensors are accumulated separately. + # Then in forward outputs and backward inputs installed in order + # sym_scalars, packed_saved_tensors. + # Keeping all tensors together allows to preserve + # the same identification at runtime, + # updating only number of saved sym_scalars and tensors. + pack_g_inputs = pack_g.find_nodes(op="placeholder") + if len(pack_g_inputs) != 1: + raise AssertionError( + f"expected exactly 1 pack_g_input, got {len(pack_g_inputs)}" + ) + env = {pack_g_inputs[0]: saved} + fw_pack_out_args = None + with fw_g.inserting_before(fw_out_n): + for node in pack_g.nodes: + if node.op == "placeholder": + continue + new_n = fw_g.node_copy(node, lambda n: env[n]) + fw_g_names.add(new_n.name) + env[node] = new_n + # Output node is temporarily copied to have remapped arguments. + # Removed in the end. + if node.op == "output": + fw_pack_out_args = new_n.args[0] + fw_g.erase_node(new_n) + + env.clear() + if not fw_pack_out_args: + raise AssertionError("fw_pack_out_args must not be empty") + fw_outs_bw_ins_node_names = [] + for out_idx, _n in enumerate(pytree.tree_leaves(fw_pack_out_args)): + if not isinstance(_n, torch.fx.Node): + fw_outs_bw_ins_node_names.append("") + continue + + # This happens when hook is noop and it is either user input or user output. + # Do not do anything with this node. + if _n.op == "placeholder" or _n in fw_outs_inner_set: + # This means the hook returned input primals unchanged + # Do not rename in this case. + n = _n + new_node_name = _n.name + fw_outs_bw_ins_node_names.append(new_node_name) + else: + # We can not specify desired name in node_copy. + # Copying node manually to set specific name, + # to have matching fw_outs, bw_inputs names. + new_node_name = _gen_unused_name(f"{saved.name}_hook_{out_idx}") # type: ignore[union-attr] + with fw_g.inserting_before(_n): + n = fw_g.create_node( + _n.op, + _n.target, + _n.args, + _n.kwargs, + name=new_node_name, + ) + if n.name != new_node_name: + raise AssertionError( + f"expected n.name == {new_node_name}, got {n.name}" + ) + fw_outs_bw_ins_node_names.append(new_node_name) + n.meta = copy.copy(_n.meta) + _n.replace_all_uses_with(n) + fw_g.erase_node(_n) + if isinstance(n.meta["val"], torch.Tensor): + fw_outs_packed_tensors.append(n) + elif is_sym_node(n): + fw_outs_packed_syms.append(n) + + # Install unpack hook graph as a prologue of backward graph + # Saved tensors inputs are replaced with packed tensors and packed sym scalars. + # The saved tensors inputs usages in the graph are replaced with unpack hook graph outputs. + with _saved_tensor_hook_context(_get_extra_info()): + unpack_gm = prepare_hook_gm(aot_config, unpack_hook_gm, (pack_out_val,)) + unpack_g = unpack_gm.graph + maybe_log_graph( + unpack_gm, + f"saved_tensors_unpack_hook {saved.name}", # type: ignore[union-attr] + aot_config, + lambda: f"aot_saved_tensors_hooks_unpack {saved.name}", # type: ignore[union-attr] + structured_logs, + ) + + def find_saved_in_bw_inputs( + bw_inputs: list[torch.fx.Node], + ) -> torch.fx.Node | None: + for n in bw_inputs: + if n.name == saved.name: # type: ignore[union-attr] + return n + + bw_g_input = find_saved_in_bw_inputs(bw_g_inputs) + if not bw_g_input: + raise AssertionError( + f"could not find saved tensor {saved.name} in bw_g_inputs" # type: ignore[union-attr] + ) + original_bw_g_input_users = list(bw_g_input.users.keys()) + bw_g_input_used_directly = False + + # Replace backward graph saved tensor input with copy of pack graph outputs + # All non-Tensor, non-symscalars outputs are constanted. + + unpack_g_inputs = unpack_g.find_nodes(op="placeholder") + env = {} + for out_idx, (unp_in_n, out_n, val) in enumerate( + zip( + unpack_g_inputs, + pytree.tree_leaves(fw_pack_out_args), + pytree.tree_leaves(pack_out_val), + ) + ): + is_sym = isinstance(val, py_sym_types) + if isinstance(val, torch.Tensor) or is_sym: + # We want forward_outputs names to match backward_inputs, + # Potentially backward may already have "{saved.name}_hook_{idx}", + # In this case fx.Graph will add suffix. + new_node_name = fw_outs_bw_ins_node_names[out_idx] + if bw_g_input.name == new_node_name: + env[unp_in_n] = bw_g_input + bw_g_input_used_directly = True + else: + # Backward calling convention: ctx_symints,ctx_saved_tensors + # Inserting packed sym scalars before first saved tensor input. + # Inserting packed tensors before last saved tensor input. + # Saved tensor inputs between them will be removed. + with ( + bw_g.inserting_before(bw_g_inputs[0]) + if is_sym + else bw_g.inserting_before(bw_g_input) + ): + new_n = bw_g.placeholder(new_node_name) + if new_n.name != new_node_name: + raise AssertionError( + f"expected new_n.name == {new_node_name}, got {new_n.name}" + ) + new_n.meta = copy.copy(out_n.meta) + env[unp_in_n] = new_n + else: + # Inline values of non-Tensor, non-SymScalars + env[unp_in_n] = val + + # Inserting unpack hook after placeholders. + bw_unpack_out_n = None + with bw_g.inserting_before(bw_g_inputs[-1].next): + for node in unpack_g.nodes: + if node.op == "placeholder": + continue + new_n = bw_g.node_copy(node, lambda n: env[n]) + bw_g_names.add(new_n.name) + env[node] = new_n + # Temporary insert output, to have remapped by node_copy args. + # Removed in the end. + if node.op == "output": + bw_unpack_out_n = new_n + + if not bw_unpack_out_n: + raise AssertionError("bw_unpack_out_n must not be None") + _leaves = pytree.tree_leaves(bw_unpack_out_n.args) + if len(_leaves) != 1: + raise AssertionError(f"expected exactly 1 leaf, got {len(_leaves)}") + unpack_saved_tensor_n = _leaves[0] + + if not bw_g_input_used_directly: + bw_g_input.replace_all_uses_with(unpack_saved_tensor_n) + bw_g.erase_node(bw_g_input) + else: + # Keep usages of bw_g_input in inserted unpacked hook graph. + # Replace other usages of bw_g_input with unpack_saved_tensor_n. + for use_node in original_bw_g_input_users: + use_node._replace_input_with(bw_g_input, unpack_saved_tensor_n) + bw_g.erase_node(bw_unpack_out_n) + + # Changing forward graph outputs, + # Inserting packed_tensors and packed_syms on the place of saved tensors. + # Packed sym_scalars are together with saved symints + symint_outs_saved_for_bw = [n for n in fw_outs_saved_for_bw if is_sym_node(n)] # type: ignore[arg-type] + fw_new_outs = pytree.tree_leaves( + ( + fw_outs[:num_inner_fwd_outputs], # type: ignore[index] + fw_outs_packed_tensors, + fw_outs_packed_syms, + symint_outs_saved_for_bw, + ) + ) + fw_out_n.args = (tuple(fw_new_outs),) + + # Assert that saved tensors and symints in forward outputs are aligned with backward inputs + _fw_n = num_inner_fwd_outputs + _fw_num_t = len(fw_outs_packed_tensors) + _fw_num_s = len(fw_outs_packed_syms) + len(symint_outs_saved_for_bw) + fw_outs_saved_tensors = fw_new_outs[_fw_n : _fw_n + _fw_num_t] + fw_outs_saved_syms = fw_new_outs[_fw_n + _fw_num_t :] + bw_new_ins = list(bw_g.find_nodes(op="placeholder")) + bw_ins_saved_syms = bw_new_ins[:_fw_num_s] + bw_ins_saved_tensors = bw_new_ins[_fw_num_s : _fw_num_s + _fw_num_t] + + fw_t_names = [n.name for n in fw_outs_saved_tensors] + bw_t_names = [n.name for n in bw_ins_saved_tensors] + fw_s_names = [n.name for n in fw_outs_saved_syms] + bw_s_names = [n.name for n in bw_ins_saved_syms] + + def _log_structured_logs() -> None: + if not aot_config.enable_log: + return + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_saved_tensors_hooks_graphs", + "encoding": "string", + }, + payload_fn=lambda: "\n".join(structured_logs), + ) + + if aot_config.enable_log: + structured_logs.append( + f"fw_outs[:num_inner_fwd_outputs]:{fw_outs[:num_inner_fwd_outputs]}" # type: ignore[index] + ) + structured_logs.append(f"fw_outs_packed_tensors:{fw_outs_packed_tensors}") + structured_logs.append(f"fw_t_names:{fw_t_names}") + structured_logs.append(f"bw_t_names:{bw_t_names}") + structured_logs.append(f"fw_s_names:{fw_s_names}") + structured_logs.append(f"bw_s_names:{bw_s_names}") + structured_logs.append(f"\nfw_g_pre_assert:{fw_g}") + structured_logs.append(f"\nbw_g_pre_assert:{bw_g}") + maybe_log_graph( + fw_module, + "Forward graph after transform pre-assert", + aot_config, + lambda: "aot_forward_graph_pre_assert_saved_tensors_hooks", + structured_logs, + ) + maybe_log_graph( + bw_module, + "Backward graph after transform pre-assert", + aot_config, + lambda: "aot_backward_graph_pre_assert_saved_tensors_hooks", + structured_logs, + ) + _log_structured_logs() + + if fw_t_names != bw_t_names: + raise AssertionError( + f"expected fw_t_names == bw_t_names, got {fw_t_names} != {bw_t_names}" + ) + if fw_s_names != bw_s_names: + raise AssertionError( + f"expected fw_s_names == bw_s_names, got {fw_s_names} != {bw_s_names}" + ) + + fw_g.lint() + bw_g.lint() + fw_module.recompile() + bw_module.recompile() + + +def _log_joint_graph( + fx_g: torch.fx.GraphModule, + aot_config: AOTConfig, +) -> str | None: + """ + Log the joint graph to the structured logger. + Return a str representation of the graph. + """ + joint_graph_str = None + if aot_config.enable_log: + aot_joint_log.info( + "%s", + lazy_format_graph_code( + "Joint graph", + fx_g, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + joint_graph_str = fx_g.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ) + trace_structured( + "aot_joint_graph", + payload_fn=lambda: joint_graph_str, + ) + return joint_graph_str + + +def _log_fw_bw_graphs( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, +) -> tuple[str | None, str | None]: + """ + Log the fw and bw graphs to the structured logger. + Return str representations of the graphs. + """ + fw_module_str = None + bw_module_str = None + if aot_config.enable_log: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "torch._functorch.config", + "encoding": "string", + }, + payload_fn=lambda: torch._functorch.config.get_serializable_config_copy(), + ) + aot_graphs_log.info( + "aot_config id: %s, fw_metadata=%s, inner_meta=%s", + aot_config.aot_id, + fw_metadata, + _get_inner_meta(maybe_subclass_meta, fw_metadata), + ) + + aot_graphs_log.info( + "%s", + lazy_format_graph_code( + "Forward graph", + fw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + aot_graphs_log.info( + "%s", + lazy_format_graph_code( + "Backward graph", + bw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + fw_module_str = fw_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ) + bw_module_str = bw_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(fw_metadata), + ) + if maybe_subclass_meta is not None: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_subclass_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(maybe_subclass_meta), + ) + + trace_structured( + "aot_forward_graph", + payload_fn=lambda: fw_module_str, + ) + trace_structured( + "aot_backward_graph", + payload_fn=lambda: bw_module_str, + ) + return fw_module_str, bw_module_str + + +def _partition_joint_graph_into_fw_bw( + fx_g: torch.fx.GraphModule, + joint_inputs: list[Any] | tuple[list[Any], list[Any]], + inner_meta: ViewAndMutationMeta, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + partition_fn: Callable, +) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule, int]: + # See Note: [Partitioner handling for Subclasses, Part 1] + # See Note: [Recomputing subclass mutation handling] + mutated_inp_runtime_indices = compute_inner_mutated_inp_indices_from_subclass_meta( + fw_metadata, inner_meta + ) + num_tokens = len(fw_metadata.tokens) + num_inner_fwd_outputs = ( + len(mutated_inp_runtime_indices) + + inner_meta.num_outputs + + inner_meta.num_intermediate_bases + + inner_meta.num_outputs_rng_offset + + num_tokens # See Note [Side-Effectful Tokens in AOTAutograd] + ) + + fx_g = run_joint_graph_passes_on_hops( + fx_g, joint_inputs, aot_config, default_partition_fn=partition_fn + ) + + # apply joint_gm callback here + if callable(torch._functorch.config.joint_custom_pass): + # pyrefly: ignore [bad-assignment] + fx_g = torch._functorch.config.joint_custom_pass(fx_g, joint_inputs) + + fw_module, bw_module = partition_fn( + fx_g, + joint_inputs, + num_fwd_outputs=num_inner_fwd_outputs, + static_lifetime_input_indices=fw_metadata.static_input_indices, + ) + + rng_states = [ + n + for n in fw_module.graph.find_nodes(op="placeholder") + if "fwd_rng_state" in n.name + ] + fw_metadata.num_graphsafe_rng_states = len(rng_states) + if rng_states: + rng_device = rng_states[0].meta["val"].device + fw_metadata.graphsafe_rng_state_index = rng_device.index + fw_metadata.graphsafe_rng_device = rng_device + + return fw_module, bw_module, num_inner_fwd_outputs + + +def _joint_inputs_for_forward( + joint_inputs: list[Any] | tuple[list[Any], list[Any]], +) -> list[Any]: + return joint_inputs[0] if isinstance(joint_inputs, tuple) else joint_inputs + + +def _maybe_unlift_partitioned_effect_tokens( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + joint_inputs: list[Any] | tuple[list[Any], list[Any]], + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + num_inner_fwd_outputs: int, +) -> tuple[int, list[Any] | tuple[list[Any], list[Any]]]: + num_tokens = len(fw_metadata.tokens) + + # See Note [Side-Effectful Tokens in AOTAutograd] + if config.unlift_effect_tokens and ( + num_tokens > 0 or fw_metadata.num_backward_tokens > 0 + ): + unlift_tokens(fw_module, fw_metadata, aot_config, bw_module) + num_inner_fwd_outputs -= num_tokens + if isinstance(joint_inputs, tuple): + joint_inputs = ( + _joint_inputs_for_forward(joint_inputs)[num_tokens:], + joint_inputs[1], + ) + else: + joint_inputs = joint_inputs[num_tokens:] + + return num_inner_fwd_outputs, joint_inputs + + +def _categorize_saved_tensors_for_backward( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + inner_meta: ViewAndMutationMeta, + fw_metadata: ViewAndMutationMeta, + num_inner_fwd_outputs: int, +) -> tuple[int, int]: + fw_outs = next(iter(fw_module.graph.find_nodes(op="output"))).args[0] + # we only need to bookkeep the symints that are saved for bw, not any symints + # the user forward might have returned in its own output + fw_outs_saved_for_bw = fw_outs[num_inner_fwd_outputs:] + num_fw_outs_saved_for_bw = len(fw_outs_saved_for_bw) + + num_symints_saved_for_bw = 0 + num_opaque_objects_saved_for_bw = 0 + saved_tensor_is_graph_input: list[bool] = [] + for idx, node in enumerate(fw_outs_saved_for_bw): + if is_sym_node(node): + num_symints_saved_for_bw += 1 + elif is_opaque_node(node): + num_opaque_objects_saved_for_bw += 1 + elif isinstance(node, torch.fx.Node) and "val" in getattr(node, "meta", {}): + if is_fake_tensor(node.meta["val"]): + # If the saved_tensor is a view, a graph intermediate, + # and returned from the autograd.Function output, we need to + # detach() it to prevent a reference cycle. Record + # if the saved_tensor is a graph input here to help. + saved_tensor_is_graph_input.append(node.op == "placeholder") + # record dynamic tensor activations + dynamic_dims: set[int] = { + dim + for dim, size in enumerate(node.meta["val"].shape) + if not isinstance(size, int) + } + if dynamic_dims: + fw_metadata.dynamic_saved_tensors_idxs[idx] = dynamic_dims + elif isinstance(node.meta["val"], (FakeScriptObject, CustomClassBase)): + num_opaque_objects_saved_for_bw += 1 + else: + saved_tensor_is_graph_input.append(False) + + fw_metadata.num_symints_saved_for_bw = num_symints_saved_for_bw + fw_metadata.num_opaque_objects_saved_for_bw = num_opaque_objects_saved_for_bw + num_tensors_saved_for_bw = ( + num_fw_outs_saved_for_bw + - num_symints_saved_for_bw + - num_opaque_objects_saved_for_bw + ) + if len(saved_tensor_is_graph_input) != num_tensors_saved_for_bw: + raise AssertionError( + "expected one saved_tensor_is_graph_input entry per saved tensor, " + f"got {len(saved_tensor_is_graph_input)} != {num_tensors_saved_for_bw}" + ) + fw_metadata.saved_tensor_is_graph_input = saved_tensor_is_graph_input + inner_meta.num_symints_saved_for_bw = num_symints_saved_for_bw + inner_meta.num_opaque_objects_saved_for_bw = num_opaque_objects_saved_for_bw + inner_meta.saved_tensor_is_graph_input = saved_tensor_is_graph_input + + # See Note [Activations with no version counter checks in eager] + # Count tensors saved with no version counter check. + # These are tensors that were stashed on ctx (e.g., ctx.x = x) rather than + # via save_for_backward in an autograd.Function. + # The partitioner sorts these to be at the end of saved_values. + num_tensors_saved_with_no_vc_check = sum( + 1 + for node in fw_outs_saved_for_bw + if isinstance(node, torch.fx.Node) + and node.meta.get("saved_tensor_with_no_vc_check", False) + ) + fw_metadata.num_tensors_saved_with_no_vc_check = num_tensors_saved_with_no_vc_check + inner_meta.num_tensors_saved_with_no_vc_check = num_tensors_saved_with_no_vc_check + + if torch._functorch.config.donated_buffer: + fw_metadata.bw_donated_idxs = collect_bw_donated_buffer_idxs( + fw_module, + bw_module, + inner_meta, + ) + inner_meta.bw_donated_idxs = fw_metadata.bw_donated_idxs + + return num_fw_outs_saved_for_bw, num_symints_saved_for_bw + + +# Note [Detaching inputs that never need gradients] +# See https://github.com/pytorch/pytorch/issues/97745 +# Suppose we have a function like this that we want to compile: +# +# def f(x, y): +# return torch.mul(x, y.detach()) +# +# What gradients should we compute for x and y? +# By default, AOTAutograd will compute a gradient for **every** input that requires gradients, +# and so we'll compute: +# x_grad_input = y +# y_grad_input = None +# Does this preserve the semantics of eager mode? +# Unfortunately, no. +# Doing the above will cause autograd to **continue** to backprop the autograd tape +# that was generated from constructing y. +# +# This is **different** from what would have happened in eager mode. +# In eager mode, if we backprop through the output of this function, autograd will only traverse +# the bit of the autograd tape corresponding to "x". +# In particular, if a user had previously backpropped through y's autograd tape, +# And then they try to backprop through the output of the above function, +# then we'll hit the dreaded "Trying to backward through the graph a second time" error. +# +# You might think: If autograd sees that a gradient is None, shouldn't it stop early, +# instead of continuing the backprop through the ancestors of that node in the graph? +# +# Autograd has two passes: +# (1) a first pass that traverses the autograd graph and figures out which nodes need to be executed +# (2) a second pass that actually goes ahead and executes each node when it becomes ready, +# propagating gradients +# By the time we're executing a node and we see that it produces a None, the set of nodes to execute +# is already locked-in. +# +# The fix: instead, we can recognize statically that the graph we're compiling will never contribute +# gradients to y, and prevent autograd from trying to traverse y's autograd tape at all. +# We can do this by manually detach'ing y before sending it through the `CompiledFunction`. +# +# Note that this solution is not bulletproof. +# It's possible to construct a case where eager may or may not have tried to autograd through y, +# depending on the actual grad_outputs that were passed in during the backward. +# There is no easy fix for this: the simplest fix would be to run with `retain_graph=True`, +# allowing autograd to reuse the graph. +# +# An example of this case is: +# def f(x): +# return x.detach() * 2, x * 3 +# If we were to only backprop through outs[0], in eager, we would stop +# If we backward only on the first output, we shouldn't send a grad through x. +# But the custom autograd function doesn't know that: it will materialize zero grads for x * 3 +# and we will end up with a zero grad at x. +# If we later backprop through the second output, this will also require backprop'ing through x. +# Meaning we'll need to use `retain_graph=True` to be able to backprop through x the second time. +def _compute_indices_of_inps_to_detach( + bw_module: torch.fx.GraphModule, + maybe_subclass_meta: SubclassMeta | None, + inner_meta: ViewAndMutationMeta, + fw_metadata: ViewAndMutationMeta, +) -> list[int]: + # TODO: we should apply the below "detach inputs if their gradients are statically known to be None" + # optimization even if we have subclass inputs/outputs (we do not handle this today). + # Computing which our our inputs get None gradients is a bit more complicated, + # if any of our inputs are subclasses. Why? + # (a) we need to make sure that we call .detach() on the input subclasses, since autograd sees subclasses. + # (b) The grad_outputs that we AOT computed in our backward graph are the desugared tensor tensors, + # so we need to figure out which subclass fw inputs they map to. + if maybe_subclass_meta is not None: + return [] + + indices_of_inps_to_detach: list[int] = [] + + # reversed() since we expect output at end of graph + bw_output = next(reversed(bw_module.graph.find_nodes(op="output"))) + bw_outs = bw_output.args[0] + + num_backward_tokens = inner_meta.num_backward_tokens + expected_bw_outs = ( + len(fw_metadata.input_info) + + inner_meta.num_outputs_rng_offset + + num_backward_tokens + ) + if len(bw_outs) != expected_bw_outs: + raise AssertionError( + f"expected len(bw_outs) == {expected_bw_outs}, got {len(bw_outs)}" + ) + + bw_outs_no_rng_no_tokens = bw_outs + if (inner_meta.num_outputs_rng_offset + num_backward_tokens) > 0: + bw_outs_no_rng_no_tokens = bw_outs[ + : -(inner_meta.num_outputs_rng_offset + num_backward_tokens) + ] + if len(bw_outs_no_rng_no_tokens) != len(fw_metadata.input_info): + raise AssertionError( + f"expected len(bw_outs_no_rng_no_tokens) == {len(fw_metadata.input_info)}, " + f"got {len(bw_outs_no_rng_no_tokens)}" + ) + + for i, bw_out in enumerate(bw_outs_no_rng_no_tokens): + # If our input experiences a metadata mutation inside the graph (e.g. set_()), + # we *must* not detach, otherwise it will be the detach'd input that gets the metadata mutation + metadata_mutation_in_graph = ( + fw_metadata.input_info[i].mutation_type == MutationType.MUTATED_IN_GRAPH + and fw_metadata.input_info[i].mutates_storage_metadata + ) + is_non_leaf = ( + fw_metadata.input_info[i].requires_grad + and not fw_metadata.input_info[i].is_leaf + ) + if bw_out is None and not metadata_mutation_in_graph and is_non_leaf: + indices_of_inps_to_detach.append(i) + + return indices_of_inps_to_detach + + +def _aot_stage2a_partition( + fx_g: torch.fx.GraphModule, + joint_inputs: list[Any] | tuple[list[Any], list[Any]], + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + partition_fn: Callable, +) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule, int, int, list[int], list[Any]]: + """ + Partition the joint graph into a forward graph and a backward graph. Returns: + - the forward and backward graphs + - the number of forward outputs and the number of symints saved for backward + - indices of inputs to detach + - adjusted inputs to forward + """ + disable_amp = torch._C._is_any_autocast_enabled() + inner_meta = _get_inner_meta(maybe_subclass_meta, fw_metadata) + + with torch.no_grad(): + context = torch._C._DisableAutocast if disable_amp else nullcontext + with context(), track_graph_compiling(aot_config, "joint"): + fw_module, bw_module, num_inner_fwd_outputs = ( + _partition_joint_graph_into_fw_bw( + fx_g, + joint_inputs, + inner_meta, + fw_metadata, + aot_config, + partition_fn, + ) + ) + num_inner_fwd_outputs, joint_inputs = ( + _maybe_unlift_partitioned_effect_tokens( + fw_module, + bw_module, + joint_inputs, + fw_metadata, + aot_config, + num_inner_fwd_outputs, + ) + ) + + maybe_inline_graph_saved_tensors_hooks( + fw_module, + bw_module, + num_inner_fwd_outputs, + inner_meta, + aot_config, + fw_metadata.static_input_indices, + ) + num_fw_outs_saved_for_bw, num_symints_saved_for_bw = ( + _categorize_saved_tensors_for_backward( + fw_module, + bw_module, + inner_meta, + fw_metadata, + num_inner_fwd_outputs, + ) + ) + + _indices_of_inps_to_detach = _compute_indices_of_inps_to_detach( + bw_module, + maybe_subclass_meta, + inner_meta, + fw_metadata, + ) + + return ( + fw_module, + bw_module, + num_fw_outs_saved_for_bw, + num_symints_saved_for_bw, + _indices_of_inps_to_detach, + _joint_inputs_for_forward(joint_inputs), + ) + + +def _aot_stage2b_fw_compile( + fw_module: torch.fx.GraphModule, + adjusted_flat_args: list[Any], + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + num_fw_outs_saved_for_bw: int, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + fw_compiler: Callable, + # pyrefly: ignore [implicit-any] +) -> tuple[list[tuple[int, ...] | None] | None, Callable]: + return _aot_stage2b_compile_forward_or_inference( + fw_module, + adjusted_flat_args, + maybe_subclass_meta, + fw_metadata, + aot_config, + fw_compiler, + is_inference=False, + num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw, + ) + + +def _aot_stage2b_bw_compile( + bw_module: torch.fx.GraphModule, + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + fwd_output_strides: list[tuple[int, ...] | None] | None, + num_symints_saved_for_bw: int, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + bw_compiler: Callable, + # pyrefly: ignore [implicit-any] +) -> tuple[AutogradLazyBackwardCompileInfo, Callable | None]: + """ + Compile the backward graph. Returns: + - the placeholder list for the backward graph + - the compiled backward function + """ + with torch.no_grad(): + # NB: It's important to compile backwards ahead of time, as this may + # add extra guards which we need to apply to the Dynamo cache at + # forwards + with track_graph_compiling(aot_config, "backward"), torch._C._DisableAutocast(): + placeholder_list = fx_placeholder_vals(bw_module) + + forward_saved_for_backwards_strides = None + if fwd_output_strides is not None: + inner_meta = _get_inner_meta(maybe_subclass_meta, fw_metadata) + forward_saved_for_backwards_strides = fwd_output_strides[ + inner_meta.tensors_saved_for_backwards_slice + ] + + # saved activations can have different stride to eager if + # the compiler does layout optimization. We should restride the + # tensor passed in for compiling the backward graph using the + # saved tensor's stride. + for i in range(len(placeholder_list)): + ph_arg = placeholder_list[i] + if not isinstance(ph_arg, torch.Tensor): + continue + + if forward_saved_for_backwards_strides is None: + continue + + real_stride = None + # Per all_args calling convention + j = i - num_symints_saved_for_bw + if 0 <= j < len(forward_saved_for_backwards_strides): + real_stride = forward_saved_for_backwards_strides[j] + if real_stride is None: + continue + + # Comparing ph_arg.stride() with real_stride directly may + # cause dynamic dimensions in ph_arg being specialized to static + # value. Using suppress_guards and guard_or_true to avoid that. + + stride_different = False + fake_mode = detect_fake_mode() + suppress_ctx = ( + fake_mode.shape_env.suppress_guards() + if fake_mode is not None and fake_mode.shape_env is not None + else nullcontext() + ) + + # Inductor can choose different strides for activations than + # what backward graph has. if we can't statically tell that + # strides are the same, we assume they are not. + with suppress_ctx: + for k in range(len(ph_arg.stride())): + # real_stride can't be symbolic. + + if guard_or_true(ph_arg.stride()[k] != int(real_stride[k])): + stride_different = True + break + + if stride_different: + # Note that here we use the stride of the real tensor to + # restride a FakeTensor. This does not cause trouble + # for dynamic shape since this code path only get + # executed if layout optimization is enabled. And we + # disable layout optimization for dynamic shape right + # now. + # + # A solution that decide stride order based on real + # tensor's stride and then apply that stride order to + # the FakeTensor does not work smoothly since some + # tensor's layout is not 'dense'. E.g. mixnet_l has a + # tensor with size [8, 64, 112, 112] and strides + # (2408448, 1, 21504, 192). The solution mentioned will + # decide a stride of (802816, 1, 7168, 64) for this + # tensor which is wrong. + + ph_size = ph_arg.size() + + placeholder_list[i] = ph_arg.as_strided(ph_size, real_stride) + compiled_bw_func = None + if ( + num_symints_saved_for_bw > 0 + or aot_config.force_non_lazy_backward_lowering + ): + try: + # See Note: [Backward graph lazy lowering] + with torch._subclasses.fake_tensor.unset_fake_temporarily(): + # If bw_module contains lifted constants, they will be real tensors stored as + # GraphModule. Deepcopying tensors under fake mode is not supported and will + # raise when attempting to set storage. + bw_module_copy = copy.deepcopy(bw_module) + compiled_bw_func = bw_compiler(bw_module_copy, placeholder_list) + del bw_module_copy + except Exception as e: + if aot_config.force_non_lazy_backward_lowering: + raise + exc = e + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "eager_compile_backwards_failure", + "encoding": "string", + }, + payload_fn=lambda: "\n".join( + traceback.format_exception( + type(exc), exc, exc.__traceback__ + ) + ), + ) + log.warning( + "failed to eagerly compile backwards for dynamic, suppressing in case backwards not needed", + exc_info=True, + ) + # Compiled autograd will run the bw_module in the backward pass, + # so recompilation need happen anyway if the backward pass is ever + # called. + # + # The reason we do the GraphModule recompilation here is because + # the lazy recompilation will cause issue in the backward pass + # with compiled autograd. + # + # Do the _LazyGraphModule.force_recompile here rather than when + # bw_module is first generated by the partitioner because the bw_module.recompile + # may be called in some code path later and cause the _LazyGraphModule.forward + # becomes the lazy version again. One example is when dynamic shape is enabled + # upfront, the bw_compiler will be called above which can cause extra + # graph module recompilation on bw_module. + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + from torch.fx._lazy_graph_module import _LazyGraphModule + + _LazyGraphModule.force_recompile(bw_module) + + saved_context = TracingContext.try_get() + saved_compile_context = CompileContext.try_get() + + lazy_backward_info = AutogradLazyBackwardCompileInfo( + # pyrefly: ignore [bad-argument-type] + bw_module, + placeholder_list, + saved_context, + saved_compile_context, + ) + + return lazy_backward_info, compiled_bw_func + + +def aot_stage2_autograd( + aot_state: AOTState, + aot_graph_capture: AOTGraphCapture, + # pyrefly: ignore [implicit-any] + partition_fn: Callable, + # pyrefly: ignore [implicit-any] + fw_compiler: Callable, + # pyrefly: ignore [implicit-any] + bw_compiler: Callable, +) -> DispatchReturn: + """ + Autograd logic. Generates a joint graph, partitions it, manipulates the input with various wrappers, + and returns a wrapped torch.autograd.Function with a forward and backward. + """ + + fx_g = aot_graph_capture.graph_module + maybe_subclass_meta = aot_graph_capture.maybe_subclass_meta + fw_metadata = aot_state.fw_metadata + aot_config = aot_state.aot_config + + CompileEventLogger.try_add_pt2_compile("backend_compile", dispatch_mode="autograd") + joint_graph_str = _log_joint_graph(fx_g, aot_config) + + _apply_tensorify_python_scalars(fx_g) + + ( + fw_module, + bw_module, + num_fw_outs_saved_for_bw, + num_symints_saved_for_bw, + _indices_of_inps_to_detach, + adjusted_flat_args, + ) = _aot_stage2a_partition( + fx_g, + aot_graph_capture.updated_flat_args, + maybe_subclass_meta, + fw_metadata, + aot_config, + partition_fn, + ) + + min_cut_info_str = getattr(fx_g.graph, "_min_cut_info_str", None) + + fw_module_str, bw_module_str = _log_fw_bw_graphs( + fw_module, bw_module, maybe_subclass_meta, fw_metadata, aot_config + ) + + fwd_output_strides, compiled_fw_func = _aot_stage2b_fw_compile( + fw_module, + adjusted_flat_args, + maybe_subclass_meta, + fw_metadata, + num_fw_outs_saved_for_bw, + aot_config, + fw_compiler, + ) + + lazy_backward_info, compiled_bw_func = _aot_stage2b_bw_compile( + bw_module, + maybe_subclass_meta, + fw_metadata, + fwd_output_strides, + num_symints_saved_for_bw, + aot_config, + bw_compiler, + ) + + try_save_cache_entry, entry = _cache_autograd_info( + aot_config, + aot_state.flat_args, + compiled_fw_func, + compiled_bw_func, + fw_module_str, + bw_module_str, + joint_graph_str, + aot_graph_capture.wrappers, + maybe_subclass_meta, + fw_metadata, + num_fw_outs_saved_for_bw, + _indices_of_inps_to_detach, + num_symints_saved_for_bw, + bw_module, + min_cut_info_str, + ) + + return _aot_stage2c_make_autograd_function( + aot_config, + aot_state.flat_args, + fw_metadata, + maybe_subclass_meta, + aot_graph_capture.wrappers, + compiled_fw_func, + compiled_bw_func, + bw_compiler, + lazy_backward_info, + try_save_cache_entry, # type: ignore[arg-type] + entry, # type: ignore[arg-type] + _indices_of_inps_to_detach, + num_symints_saved_for_bw, + ) + + +def _aot_stage2c_make_autograd_function( + aot_config: AOTConfig, + flat_args: list[Any], + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: SubclassMeta | None, + wrappers: list[CompilerWrapper], + compiled_fw_func: Callable[..., Any], + compiled_bw_func: Callable[..., Any] | None, + # pyrefly: ignore [implicit-any] + bw_compiler: Callable, + lazy_backward_info: AutogradLazyBackwardCompileInfo | None, + try_save_cache_entry: Callable[..., Any], + entry: GenericAOTAutogradResult[Any, Any] | None, + _indices_of_inps_to_detach: list[int], + num_symints_saved_for_bw: int, +) -> DispatchReturn: + backward_state_indices = [ + idx for idx, x in enumerate(flat_args) if isinstance(x, BackwardState) + ] + if len(backward_state_indices) > 1: + raise AssertionError( + f"expected at most 1 backward_state_index, got {len(backward_state_indices)}" + ) + + disable_amp = torch._C._is_any_autocast_enabled() + compile_spec = AOTDispatchAutogradCompileSpec( + compiled_fw_func=compiled_fw_func, + compiled_bw_func=compiled_bw_func, + maybe_subclass_meta=maybe_subclass_meta, + num_symints_saved_for_bw=num_symints_saved_for_bw, + backward_state_indices=backward_state_indices, + disable_amp=disable_amp, + indices_of_inps_to_detach=_indices_of_inps_to_detach, + lazy_backward_info=lazy_backward_info, + bw_compiler=bw_compiler, + aot_config=aot_config, + fw_metadata=fw_metadata, + try_save_cache_entry=try_save_cache_entry, + ) + compiled_fn = AOTDispatchAutograd.post_compile(compile_spec) + + if entry is not None: + compiled_fn = SerializableCompiledFunction(compiled_fn, lambda: entry) + + if config.debug_assert: + flat_requires_grad: list[bool | None] = [ + a.requires_grad if isinstance(a, Tensor) else None for a in flat_args + ] + compiled_fn = DebugAssertWrapper( + flat_requires_grad=flat_requires_grad + ).post_compile(compiled_fn, aot_config, runtime_metadata=fw_metadata) + + compiled_fn = post_compile( + wrappers, + compiled_fn, + aot_config, + runtime_metadata=fw_metadata, + ) + return compiled_fn + + +def _cache_autograd_info( + aot_config: AOTConfig, + flat_args: list[Any], + compiled_fw_func: Callable[..., Any], + compiled_bw_func: Callable[..., Any] | None, + fw_module_str: str | None, + bw_module_str: str | None, + joint_graph_str: str | None, + wrappers: list[CompilerWrapper], + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + num_fw_outs_saved_for_bw: int, + _indices_of_inps_to_detach: list[int], + num_symints_saved_for_bw: int, + bw_module: torch.fx.GraphModule | None, + min_cut_info_str: str | None, +) -> tuple[ + GenericAOTAutogradResult[Any, Any] | None, + Callable[..., Any], +]: + backward_state_indices = [ + idx for idx, x in enumerate(flat_args) if isinstance(x, BackwardState) + ] + if len(backward_state_indices) > 1: + raise AssertionError( + f"expected at most 1 backward_state_index, got {len(backward_state_indices)}" + ) + + make_runtime_safe(fw_metadata, maybe_subclass_meta) + + try_save_cache_entry: Callable[..., Any] | None = None + entry: GenericAOTAutogradResult[Any, Any] | None = None + + if aot_config.cache_info is not None: + forward_time_taken_ns = time.time_ns() - aot_config.cache_info.start_time_ns + + # NB: aot_config here is technically not needed as an argument: we could just + # close over aot_config.cache_info, since aot_config never changes. + # But closing over random variables is confusing IMO, so I'm leaving it. + def try_save_cache_entry( + compiled_bw_func: Callable[..., Any], + bw_module: torch.fx.GraphModule, + _fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + ) -> GenericAOTAutogradResult[Any, Any] | None: + cache_info = aot_config.cache_info + + if cache_info is not None and _should_save_cache( + compiled_fw_func, compiled_bw_func + ): + if forward_time_taken_ns is None: + raise AssertionError("forward_time_taken_ns must not be None") + # TODO: technically, AOTAutograd does a *little* bit of post processing work + # in the backward that isn't measured here. But it's small enough that it's not worth + # the complexity of threading a bunch of times through the code, so we + # use the compiled_bw_func's inductor compile time instead. + # It's possible this changes in the future, in which case we should + # update backward_time_taken_ns to be more inclusive + backward_time_taken_ns = getattr(compiled_bw_func, "_time_taken_ns", 0) + + aot_forward_graph_str: str | None = fw_module_str + aot_backward_graph_str: str | None = bw_module_str + aot_joint_graph_str: str | None = joint_graph_str + guards_expr = AOTAutogradCache.generate_guards_expression(cache_info) + + entry = AOTAutogradCache.make_entry( + compiled_fw_func, # type: ignore[arg-type] + compiled_bw_func, # type: ignore[arg-type] + aot_joint_graph_str, + aot_forward_graph_str, + aot_backward_graph_str, + _fw_metadata, + wrappers, + maybe_subclass_meta, + num_fw_outs_saved_for_bw, + _indices_of_inps_to_detach, + forward_time_taken_ns, + backward_time_taken_ns, + sanitized_aot_config=aot_config.to_cacheable(), + guards_expr=guards_expr, + backward_state_indices=backward_state_indices, + num_symints_saved_for_bw=num_symints_saved_for_bw, + serialized_bw_module=serialize_graph_module(bw_module), + min_cut_info_str=min_cut_info_str, + ) + AOTAutogradCache.save( + cache_info.cache_key, + entry, + remote=should_use_remote_autograd_cache(), + ) + return entry + return None + + if compiled_bw_func is not None: + # If we already compiled the backward, we save its cache entry now + if bw_module is None: + raise AssertionError( + "bw_module must not be None when compiled_bw_func is not None" + ) + entry = try_save_cache_entry( + compiled_bw_func, + bw_module, + fw_metadata, + aot_config, # type: ignore[arg-type] + ) + try_save_cache_entry = None + + return try_save_cache_entry, entry # type: ignore[return-value] + + +def _aot_stage2b_compile_forward_or_inference( + fw_module: torch.fx.GraphModule, + adjusted_flat_args: list[Any], + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + compiler: Callable, + *, + is_inference: bool, + num_fw_outs_saved_for_bw: int | None = None, + # pyrefly: ignore [implicit-any] +) -> tuple[list[tuple[int, ...] | None] | None, Callable]: + """ + Compile the forward or inference graph. Returns: + - the output strides of the forward graph + - the compiled forward/inference function + + Args: + fw_module: The forward graph module to compile + adjusted_flat_args: Flattened arguments after adjustments + maybe_subclass_meta: Metadata for tensor subclasses + fw_metadata: View and mutation metadata + aot_config: AOT configuration + is_inference: If True, compile for inference; if False, compile for forward (autograd) + num_fw_outs_saved_for_bw: Number of forward outputs saved for backward (required if not is_inference) + + Before compiling, we run pre_compile for the following wrappers: + - FakifiedOutWrapper + - FunctionalizedRngRuntimeWrapper + After compiling, we run post_compile for the following wrappers: + - EffectTokensWrapper + - AOTDispatchSubclassWrapper + - FunctionalizedRngRuntimeWrapper + - FakifiedOutWrapper + """ + + # Validation + if not is_inference and num_fw_outs_saved_for_bw is None: + raise ValueError( + "num_fw_outs_saved_for_bw must be provided when is_inference=False" + ) + + # Determine grad context, autocast context, and tracking mode. + if is_inference: + grad_ctx: Any = nullcontext + autocast_ctx: Any = ( + torch._C._DisableAutocast + if torch._C._is_any_autocast_enabled() + else nullcontext + ) + tracking_mode: str = "inference" + else: + grad_ctx = torch.no_grad + autocast_ctx = torch._C._DisableAutocast + tracking_mode = "forward" + + with grad_ctx(), autocast_ctx(), track_graph_compiling(aot_config, tracking_mode): + # Setup wrappers + fakified_out_wrapper = FakifiedOutWrapper() + fakified_out_wrapper.pre_compile( + fw_module, adjusted_flat_args, aot_config, fw_metadata=fw_metadata + ) + + # Initialize RNG wrapper based on mode + functionalized_rng_wrapper = FunctionalizedRngRuntimeWrapper( + return_new_outs=is_inference + ) + + # Add RNG states for forward mode only + if not is_inference and fw_metadata.num_graphsafe_rng_states > 0: + index = fw_metadata.graphsafe_rng_state_index + if index is None: + raise AssertionError( + "fw_metadata.graphsafe_rng_state_index must not be None when num_graphsafe_rng_states > 0" + ) + device = fw_metadata.graphsafe_rng_device + if device is None: + raise AssertionError( + "fw_metadata.graphsafe_rng_device must not be None when num_graphsafe_rng_states > 0" + ) + rng_states = [ + get_default_generator(device).clone_state() + for _ in range(fw_metadata.num_graphsafe_rng_states) + ] + adjusted_flat_args.extend(rng_states) # type: ignore[arg-type] + + functionalized_rng_wrapper.pre_compile( + fw_module, adjusted_flat_args, aot_config, fw_metadata=fw_metadata + ) + + # Set tracing context + if tracing_context := torch._guards.TracingContext.try_get(): + tracing_context.fw_metadata = _get_inner_meta( + maybe_subclass_meta, fw_metadata + ) + + if config.enable_complex_wrapper: + from .complex_decomposition import decompose_complex_in_graph + + fw_module = decompose_complex_in_graph( + fw_module, adjusted_flat_args, aot_config.decompositions + ) + + with TracingContext.report_output_strides() as fwd_output_strides: + # pyrefly: ignore[not-callable] + compiled_fw_func = compiler(fw_module, adjusted_flat_args) + + # Make boxed if needed + if not getattr(compiled_fw_func, "_boxed_call", False): + compiled_fw_func = make_boxed_func(compiled_fw_func) + + # Set forward output strides if needed + if fakified_out_wrapper.needs_post_compile: + fakified_out_wrapper.set_fwd_output_strides(fwd_output_strides) # type: ignore[arg-type] + + # Apply post-compile wrappers + compiled_fw_func = EffectTokensWrapper().post_compile( + compiled_fw_func, + aot_config, + runtime_metadata=fw_metadata, + ) + + compiled_fw_func = AOTDispatchSubclassWrapper( + fw_only=None, + trace_joint=False, + maybe_subclass_meta=maybe_subclass_meta, + num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw, + ).post_compile( + compiled_fw_func, + aot_config, + runtime_metadata=fw_metadata, + ) + + compiled_fw_func = functionalized_rng_wrapper.post_compile( + compiled_fw_func, aot_config, runtime_metadata=fw_metadata + ) + + compiled_fw_func = fakified_out_wrapper.post_compile( + compiled_fw_func, + aot_config, + runtime_metadata=fw_metadata, + ) + + return fwd_output_strides, compiled_fw_func diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/indexed_dict.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/indexed_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..748818ff4b16ccf6651a9bdfe7b8064e67ff922e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/indexed_dict.py @@ -0,0 +1,54 @@ +from collections.abc import Iterator, MutableMapping +from typing import Generic, TypeVar + + +K = TypeVar("K") +V = TypeVar("V") + + +# Used for fast next key access (using the fact that the dict is ordered) +# Note: doesn't support deletion but we don't need it! +class IndexedDict(MutableMapping[K, V], Generic[K, V]): + """A dict that maintains insertion order with O(1) index access.""" + + __slots__ = ("_dict", "_keys", "_key_to_index") + + def __init__(self) -> None: + self._dict: dict[K, V] = {} + self._keys: list[K] = [] # typing: ignore[bad-override] + self._key_to_index: dict[K, int] = {} + + def __setitem__(self, key: K, value: V) -> None: + if key not in self._dict: + self._key_to_index[key] = len(self._keys) + self._keys.append(key) + self._dict[key] = value + + def __getitem__(self, key: K) -> V: + return self._dict[key] + + def __delitem__(self, key: K) -> None: + raise NotImplementedError("Deletion not supported for IndexedDict") + + def __len__(self) -> int: + return len(self._dict) + + def __iter__(self) -> Iterator[K]: + return iter(self._keys) + + def __contains__(self, key: object) -> bool: + return key in self._dict + + def next_key(self, key: K) -> K | None: + """Get the next key in insertion order. O(1).""" + idx = self._key_to_index.get(key) + if idx is not None and idx + 1 < len(self._keys): + return self._keys[idx + 1] + return None + + def prev_key(self, key: K) -> K | None: + """Get the previous key in insertion order. O(1).""" + idx = self._key_to_index.get(key) + if idx is not None and idx > 0: + return self._keys[idx - 1] + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/input_output_analysis.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/input_output_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb2c49d1fc9871741c524316d04a1e6a76f4aeb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/input_output_analysis.py @@ -0,0 +1,508 @@ +""" +This module is one of the analysis modules - it takes as input a function or graph +and some preexisting properties, and returns some data that is useful for deciding +how to further proceed with compilation or construct runtime wrappers. + +In particular, the following analyses are provided: +1. Refine the view and mutation metadata collected previously - removing duplicate + inputs or mapping views to their bases. +2. We also analyze the function signature for export graphs. +""" + +import contextlib +import itertools +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch import Tensor +from torch._C._dynamo.guards import compute_overlapping_tensors +from torch._functorch._aot_autograd.schemas import PlainTensorMeta +from torch._guards import StorageOverlap +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx.experimental.symbolic_shapes import is_concrete_int + +from .collect_metadata_analysis import coerce_tangent_and_suggest_memory_format +from .descriptors import AOTInput, InputMutationAOTOutput, TangentAOTInput +from .schemas import ( + AOTConfig, + BackwardSignature, + GraphSignature, + InputAliasInfo, + MemoryFormatMeta, + OutputAliasInfo, + OutputType, + ViewAndMutationMeta, +) +from .utils import strict_zip + + +zip = strict_zip + + +def remove_dupe_metadata( + m: ViewAndMutationMeta, + keep_arg_mask: list[bool], + add_dupe_map: list[int], +) -> ViewAndMutationMeta: + if len(m.input_info) != len(keep_arg_mask): + raise AssertionError( + f"len(m.input_info)={len(m.input_info)} != len(keep_arg_mask)={len(keep_arg_mask)}" + ) + # Easy invariant: the first argument should never be a dupe (it will be kept) + if len(keep_arg_mask) == 0 or not keep_arg_mask[0]: + raise AssertionError( + "keep_arg_mask must be non-empty and keep_arg_mask[0] must be True" + ) + + # Filter dupe'd mutated inputs out of traced_tangents + num_data_mutations = len([x for x in m.input_info if x.mutates_data]) + other_traced_tangents = m.traced_tangents[num_data_mutations:] + inp_traced_tangents = m.traced_tangents[:num_data_mutations] + other_traced_tangents_descs = m.traced_tangents_descs[num_data_mutations:] + inp_traced_tangents_descs = m.traced_tangents_descs[:num_data_mutations] + filtered_inp_traced_tangents = [ + # See Note [Tangents memory format] + x + for i, x in enumerate(inp_traced_tangents) + if keep_arg_mask[m.mutated_inp_runtime_indices[i]] + ] + filtered_inp_traced_tangents_descs = [ + x_desc + for i, x_desc in enumerate(inp_traced_tangents_descs) + if keep_arg_mask[m.mutated_inp_runtime_indices[i]] + ] + traced_tangents = filtered_inp_traced_tangents + other_traced_tangents + traced_tangents_descs = ( + filtered_inp_traced_tangents_descs + other_traced_tangents_descs + ) + + if m.subclass_tangent_meta is None: + raise AssertionError("m.subclass_tangent_meta must not be None") + subclass_tangent_meta = [ + PlainTensorMeta( + 0, memory_format=MemoryFormatMeta(memory_format=torch.contiguous_format) + ) + ] * len(filtered_inp_traced_tangents) + m.subclass_tangent_meta[num_data_mutations:] + + return ViewAndMutationMeta( + input_info=[x for i, x in enumerate(m.input_info) if keep_arg_mask[i]], + # For outputs that are views of inputs, we store the index of the input that the output + # was generated from. Need to update that index to account for removed dupes. + output_info=[ + OutputAliasInfo( + output_type=o.output_type, + raw_type=o.raw_type, + dynamic_dims=o.dynamic_dims, + base_idx=None if o.base_idx is None else add_dupe_map[o.base_idx], + requires_grad=o.requires_grad, + requires_grad_for_backward=o.requires_grad_for_backward, + view_meta_sequence=o.view_meta_sequence, + ) + for o in m.output_info + ], + num_intermediate_bases=m.num_intermediate_bases, + keep_input_mutations=m.keep_input_mutations, + traced_tangents=traced_tangents, + traced_tangents_descs=traced_tangents_descs, + # We are guaranteed not to get here, since dupes are not supported today with subclass inputs. + subclass_inp_meta=[], + subclass_fw_graph_out_meta=[], + subclass_tangent_meta=subclass_tangent_meta, + ) + + +# Given our ViewAndMutation metadata, this fn constructs a new set of metadata, +# after adding synthetic base arguments to the function. +# Most of the work in this fn is slogging through all of the metadata corresponding to inputs, +# and updating it with our synthetic base calling convention. +# +# When config.debug_assert is set, we automatically regenerate the metadata +# and compare it to this output for sanity. +# +# In addition to the updated metadata, also return the list of input indices +# that will need to be updated in the synthetic base epilogue +def create_synthetic_base_metadata( + m: ViewAndMutationMeta, + # Maps each outer argument idx to its inner idx (or, if this outer arg is generated from a + # synthetic base, you get a tuple of (i, TensorMeta), telling you the base tensor idx, and view metadata) + synthetic_base_info: list[int | tuple[int, torch.Tensor]], + outer_args: list[Any], + inner_args: list[Any], + inner_args_desc: list[AOTInput], +) -> tuple[ViewAndMutationMeta, list[int]]: + # maps inner arg indices to outer arg indices + synthetic_base_to_indices: dict[int, list[int]] = {} + for inner_idx in range(len(inner_args)): + outer_aliased_indices_of_current_base_arg = [ + outer_idx + for outer_idx, inner_idx_or_tuple in enumerate(synthetic_base_info) + if (isinstance(inner_idx_or_tuple, int) and inner_idx_or_tuple == inner_idx) + or ( + isinstance(inner_idx_or_tuple, tuple) + and inner_idx_or_tuple[0] == inner_idx + ) + ] + synthetic_base_to_indices[inner_idx] = outer_aliased_indices_of_current_base_arg + + # given the requires_grad info on mutated inputs, + # generate the requires_grad info on those same mutated inputs, but after constructing synthetic bases. + # pyrefly: ignore [implicit-any] + input_infos = [] + for outer_indices in synthetic_base_to_indices.values(): + # leaf-ness should be all-or-nothing for aliased tensor. + # (aka if "a" and "b" are views, then a.is_leaf == b.is_leaf) + any_leaf = any(m.input_info[x].is_leaf for x in outer_indices) + all_leaf = all(m.input_info[x].is_leaf for x in outer_indices) + if any_leaf != all_leaf: + raise AssertionError( + f"any_leaf={any_leaf} != all_leaf={all_leaf} for outer_indices={outer_indices}" + ) + + mutates_data = ( + True + if len(outer_indices) > 1 + else m.input_info[outer_indices[0]].mutates_data + ) + mutates_metadata = ( + False + if len(outer_indices) > 1 + else m.input_info[outer_indices[0]].mutates_metadata + ) + requires_grad = any(m.input_info[x].requires_grad for x in outer_indices) + mutations_under_no_grad_or_inference_mode = all( + m.input_info[x].mutations_under_no_grad_or_inference_mode + for x in outer_indices + ) + + mutation_inductor_storage_resize = all( + m.input_info[x].mutation_inductor_storage_resize for x in outer_indices + ) + + inpt_info = InputAliasInfo( + # If len(outer_indices) > 1, then this input is a synthetic base. + # The invariant is that to the rest of aot autograd, synthetic bases only show up if + # one of their aliases gets a data mutation. And if any of their aliases get metadata + # mutations, they will be hidden from the rest of aot autograd. + mutates_data=mutates_data, + mutates_metadata=mutates_metadata, + mutations_hidden_from_autograd=all( + m.input_info[x].mutations_hidden_from_autograd for x in outer_indices + ), + mutates_storage_metadata=( + False + if len(outer_indices) > 1 + else m.input_info[outer_indices[0]].mutates_storage_metadata + ), + mutation_is_shallow_copy_data=( + False + if len(outer_indices) > 1 + else m.input_info[outer_indices[0]].mutation_is_shallow_copy_data + ), + mutations_under_no_grad_or_inference_mode=mutations_under_no_grad_or_inference_mode, + mutation_inductor_storage_resize=mutation_inductor_storage_resize, + is_leaf=any_leaf, + requires_grad=requires_grad, + keep_input_mutations=m.keep_input_mutations, + ) + input_infos.append(inpt_info) + + # Find any inputs that fulfill the following criteria: + # (1) They are part of a synthetic base (because they alias another input, + # and at least one input experiences a data mutation) + # (2) They experience a metadata mutation + outer_aliased_arg_idx_with_metadata_mutations = [ + outer_idx + for outer_idx, inpt_info in enumerate(m.input_info) + if inpt_info.mutates_metadata + and not isinstance(synthetic_base_info[outer_idx], int) + ] + + # grab the original requires grad info on the outputs, except the ones from the mutated inputs + input_metadata_output_info = [ + OutputAliasInfo( + output_type=OutputType.alias_of_input, + raw_type=FunctionalTensor, + dynamic_dims={ + i + for i, s in enumerate(outer_args[outer_idx].shape) + if not is_concrete_int(s) + }, + base_idx=synthetic_base_info[outer_idx][0], # type: ignore[index] + requires_grad=(requires_grad := outer_args[outer_idx].requires_grad), + requires_grad_for_backward=requires_grad, + ) + for outer_idx in outer_aliased_arg_idx_with_metadata_mutations + ] + existing_output_infos = [] + for o in m.output_info: + synthetic_base_info_for_output = ( + None if o.base_idx is None else synthetic_base_info[o.base_idx] + ) + new_base_idx = ( + None + if o.base_idx is None + else ( + synthetic_base_info_for_output + if isinstance(synthetic_base_info_for_output, int) + else synthetic_base_info_for_output[0] # type: ignore[index] + ) + ) + # If the original input was merged into a synthetic base, then an + # output that was literally that input is now a view of the base. + input_merged = o.base_idx is not None and isinstance( + synthetic_base_info[o.base_idx], tuple + ) + new_output_type = ( + OutputType.alias_of_input + if o.output_type == OutputType.is_input and input_merged + else o.output_type + ) + existing_output_infos.append( + OutputAliasInfo( + output_type=new_output_type, + raw_type=o.raw_type, + dynamic_dims=o.dynamic_dims, + # Map the input idx pre-synthetic-bases to the new idx post-synthetic-bases + base_idx=new_base_idx, # type: ignore[arg-type] + requires_grad=o.requires_grad, + requires_grad_for_backward=o.requires_grad_for_backward, + view_meta_sequence=o.view_meta_sequence, + ) + ) + + inner_mutated_tangents_and_memory_formats = [ + # See Note [Tangents memory format] + ( + coerce_tangent_and_suggest_memory_format(x), + TangentAOTInput(InputMutationAOTOutput(x_desc)), + ) + for inner_idx, (x, x_desc) in enumerate(zip(inner_args, inner_args_desc)) + if input_infos[inner_idx].mutates_data and input_infos[inner_idx].requires_grad + ] + inner_mutated_tangents = [ + x[0][0] for x in inner_mutated_tangents_and_memory_formats + ] + inner_mutated_tangents_descs = [ + x[1] for x in inner_mutated_tangents_and_memory_formats + ] + inner_mutated_tangents_memory_formats = [ + x[0][1] for x in inner_mutated_tangents_and_memory_formats + ] + + output_info = existing_output_infos + input_metadata_output_info + # Regenerate traced tangents to include mutated inputs including synthetic bases + traced_tangents = ( + inner_mutated_tangents + m.traced_tangents[len(inner_mutated_tangents) :] + ) + traced_tangents_descs = ( + inner_mutated_tangents_descs + + m.traced_tangents_descs[len(inner_mutated_tangents) :] + ) + if m.subclass_tangent_meta is None: + raise AssertionError("m.subclass_tangent_meta must not be None") + subclass_tangent_meta = [ + # pyrefly: ignore[bad-argument-type] + PlainTensorMeta(0, memory_format=x) + for x in inner_mutated_tangents_memory_formats + ] + m.subclass_tangent_meta[len(inner_mutated_tangents) :] + + return ( + ViewAndMutationMeta( + input_info=input_infos, + output_info=output_info, + num_intermediate_bases=m.num_intermediate_bases, + keep_input_mutations=m.keep_input_mutations, + traced_tangents=traced_tangents, + traced_tangents_descs=traced_tangents_descs, + # We are guaranteed not to get here, since synthetic_base codepaths are not supported today with subclass inputs. + subclass_inp_meta=[], + subclass_fw_graph_out_meta=[], + subclass_tangent_meta=subclass_tangent_meta, + ), + outer_aliased_arg_idx_with_metadata_mutations, + ) + + +def compute_overlapping_inputs( + aot_config: AOTConfig, fwd_inputs: list[Any], aliased_input_indices: list[int] +) -> set[int]: + num_aliases = len(aliased_input_indices) + + shape_env = None + maybe_suppress_guards = contextlib.nullcontext + tracing_context = torch._guards.TracingContext.try_get() + + if tracing_context is not None: + if tracing_context.fake_mode is None: + raise AssertionError("tracing_context.fake_mode must not be None") + shape_env = tracing_context.fake_mode.shape_env + + # Check whether we can actually get the dynamo sources from within AOTAutograd. + if aot_config.aot_autograd_arg_pos_to_source and shape_env is not None: + maybe_suppress_guards = shape_env.suppress_guards # type: ignore[assignment] + + # Check whether there are any symbolic values being used. + # We do this for 2 reasons: + # 1. StorageOverlap guard is only issued whenever dynamic shapes is turned on + # 2. Triggers the fast-path for computing storage overlapping + symbolic = any( + isinstance(x, torch.SymInt) + for i in aliased_input_indices + for x in [ + *fwd_inputs[i].shape, + *fwd_inputs[i].stride(), + fwd_inputs[i].storage_offset(), + ] + ) + + if torch._inductor.config.is_fbcode(): + if symbolic and num_aliases > 400: + from torch._subclasses.fake_tensor import ( + UnsupportedMutationAliasingException, + ) + from torch._utils_internal import justknobs_check + + msg = f"Encountered {num_aliases} dynamic, aliased/mutated inputs, consider setting dynamic=False" + + if justknobs_check( + "pytorch/compiler:aliased_inputs_with_mutation_and_dyn_shapes_killswitch", + False, + ): + raise UnsupportedMutationAliasingException(msg) + + with maybe_suppress_guards(): + aliased_fwd_inputs = [fwd_inputs[i] for i in aliased_input_indices] + actual_aliased_indices = { + aliased_input_indices[i] + for i in compute_overlapping_tensors(aliased_fwd_inputs, symbolic=symbolic) + } + + # Add the StorageOverlap AOTAutograd guard only if we are actually keeping track of + # dynamo sources inside AOTAutograd. + if ( + tracing_context is not None + # Make sure dynamic shapes is currently being used. + and symbolic + # We check that we have more than 1 aliased tensor, which should be true at + # this point, anyway. + and num_aliases > 1 + and aot_config.aot_autograd_arg_pos_to_source + ): + no_overlap_indices = list(set(aliased_input_indices) - actual_aliased_indices) + + overlapping_sources = [ + aot_config.aot_autograd_arg_pos_to_source[i] for i in actual_aliased_indices + ] + non_overlapping_sources = [ + aot_config.aot_autograd_arg_pos_to_source[i] for i in no_overlap_indices + ] + + tracing_context.guards_context.aotautograd_guards.append( + StorageOverlap(overlapping_sources, non_overlapping_sources) + ) + + return actual_aliased_indices + + +def _graph_input_names(gm: torch.fx.GraphModule) -> list[str]: + return [node.name for node in gm.graph.find_nodes(op="placeholder")] + + +def _graph_output_names(gm: torch.fx.GraphModule) -> list[Any]: + output_node = next(iter(reversed(gm.graph.nodes))) + if output_node.op != "output" or len(output_node.args) != 1: + raise AssertionError( + f"expected output node with 1 arg, got op={output_node.op}, args={len(output_node.args)}" + ) + return_args = output_node.args[0] + return [getattr(return_arg, "name", None) for return_arg in return_args] + + +def create_graph_signature( + fx_g: torch.fx.GraphModule, + fw_metadata: ViewAndMutationMeta, + in_spec: pytree.TreeSpec, + out_spec: pytree.TreeSpec, + *, + user_args_flat: list[Tensor], + params_and_buffers_flat: list[Tensor], + param_names: list[str], + buffer_names: list[str], + trace_joint: bool, + num_user_fw_outs: int | None, + loss_index: int | None, +) -> GraphSignature: + # Retrieve graph input names + graph_input_names = _graph_input_names(fx_g) + # Retrieve graph output names + graph_output_names = _graph_output_names(fx_g) + + num_params_buffers = len(param_names) + len(buffer_names) + num_tokens = len(fw_metadata.tokens) + # We have enough restrictions on the graph (no de-duping, synthetic bases, etc), + # Such that # graph inps = # user inps + # params + # buffers + num_user_args = len(graph_input_names) - num_params_buffers - num_tokens + + if trace_joint: + if num_user_fw_outs is None: + raise AssertionError( + "num_user_fw_outs must not be None when trace_joint=True" + ) + num_fw_outs = num_user_fw_outs + fw_metadata.num_mutated_inp_runtime_indices + backward_output_names = graph_output_names[num_fw_outs:] + + grad_index = itertools.count(0) + gradients_to_parameters = { + backward_output_names[next(grad_index)]: param_names[i] + for i, param in enumerate(params_and_buffers_flat) + if param.requires_grad + } + + gradients_to_user_inputs = { + backward_output_names[next(grad_index)]: graph_input_names[ + i + len(params_and_buffers_flat) + ] + for i, user_input in enumerate(user_args_flat) + if user_input.requires_grad + } + + if len(gradients_to_parameters) + len(gradients_to_user_inputs) != len( + backward_output_names + ): + raise AssertionError( + f"len(gradients_to_parameters)={len(gradients_to_parameters)} + " + f"len(gradients_to_user_inputs)={len(gradients_to_user_inputs)} != " + f"len(backward_output_names)={len(backward_output_names)}" + ) + + # Check that we have fully accounted for all graph outputs + if loss_index is None: + raise AssertionError("loss_index must not be None") + backward_signature = BackwardSignature( + gradients_to_parameters, + gradients_to_user_inputs, + graph_output_names[loss_index], + ) + else: + backward_signature = None + num_user_fw_outs = ( + len(graph_output_names) + - fw_metadata.num_mutated_inp_runtime_indices + - num_tokens + ) + + return GraphSignature.from_tracing_metadata( + in_spec=in_spec, + out_spec=out_spec, + graph_input_names=graph_input_names, + graph_output_names=graph_output_names, + view_mutation_metadata=fw_metadata, + named_parameters=param_names, + named_buffers=buffer_names, + num_user_inputs=num_user_args, + num_user_outputs=num_user_fw_outs, + trace_joint=trace_joint, + loss_index=loss_index, + backward_signature=backward_signature, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/logging_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a5dda6c67dfa7804170374e7c737b3bc3ec5eb2e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/logging_utils.py @@ -0,0 +1,166 @@ +""" +Contains utils for logging in AOTAutograd, including managing the names of the graphs under +compilation, capturing user-friendly tracebacks, and debug messages. +""" + +import collections +from collections.abc import Callable, Generator, Iterator +from contextlib import contextmanager +from typing import Any + +import torch +import torch.fx.traceback as fx_traceback + +from .schemas import AOTConfig + + +# This is a list since looking forward, we can have this arbitrarily nested. +graph_being_compiled: list[str] = [] +# TODO: It would be nice to reset the numbering every time aot_id goes +# up, but this is annoying to do right now (because we don't know if +# an aot_id will come back from the dead), so right now this also happens +# to be a globally unique number too (at the cost of wobbling if you change +# how the graphs compile) +nth_graph: int = 0 +model_name: str = "model" + + +def set_model_name(name: str) -> None: + global model_name + model_name = name + + +def get_aot_compilation_context() -> tuple[list[str], str, int]: + return list(graph_being_compiled), model_name, nth_graph + + +def get_aot_graph_name() -> str: + """ + Returns the name of the graph being compiled. + """ + global model_name, graph_being_compiled, nth_graph + return f"{model_name}__{'_'.join(graph_being_compiled)}_{nth_graph}" + + +get_graph_being_compiled = get_aot_graph_name + + +@contextmanager +def track_graph_compiling( + aot_config: AOTConfig, graph_name: str +) -> Generator[None, None, None]: + global graph_being_compiled + # TODO: Don't shove the aot_id in here; set it in the context + graph_being_compiled = [f"{aot_config.aot_id}_{graph_name}"] + old_name = None + if tracing_context := torch._guards.TracingContext.try_get(): + old_name = tracing_context.aot_graph_name + tracing_context.aot_graph_name = graph_being_compiled + has_tracing_context = True + else: + has_tracing_context = False + try: + yield + finally: + global nth_graph + nth_graph += 1 + graph_being_compiled = [] + if has_tracing_context: + if tracing_context := torch._guards.TracingContext.try_get(): + tracing_context.aot_graph_name = old_name + + +# Set up hooks so that during backward the fx's stack_trace is properly set +callback_set = False + + +def setup_stacktrace_preservation_hooks(roots: list[torch.autograd.graph.Node]) -> None: + def iter_graph( + roots: list[torch.autograd.graph.Node], + ) -> Iterator[torch.autograd.graph.Node]: + if not roots: + return + seen = set() + q = collections.deque() + for node in roots: + if node is not None and node not in seen: + seen.add(node) + q.append(node) + + while q: + node = q.popleft() + for fn, _idx in node.next_functions: + if fn in seen or fn is None: + continue + seen.add(fn) + q.append(fn) + + yield node + + def get_callback(saved_stack_: list[str]) -> Callable[[], None]: + def callback() -> None: + global callback_set + fx_traceback.set_stack_trace(saved_stack_) + callback_set = False + + return callback + + def get_prehook(stack_: list[str], seq_nr: int) -> Callable[[Any], None]: + def prehook(grad_output: Any) -> None: + global callback_set + + if not callback_set: + torch.autograd.variable.Variable._execution_engine.queue_callback( # type: ignore[attr-defined] + get_callback(fx_traceback.format_stack()) + ) + callback_set = True + + fx_traceback.set_stack_trace(stack_) + fx_traceback.set_grad_fn_seq_nr(seq_nr) + fx_traceback._mark_autograd_backward() + + return prehook + + def get_posthook( + special_stack_: list[str], seq_nr: int + ) -> Callable[[Any, Any], None]: + def posthook(grad_input: Any, grad_output: Any) -> None: + fx_traceback.set_stack_trace(special_stack_) + fx_traceback.reset_grad_fn_seq_nr() + fx_traceback._reset_autograd_backward() + + return posthook + + for node in iter_graph(roots): + # pyrefly: ignore[missing-attribute] + forward_node_stack = node.metadata.get("traceback_", []) + node.register_prehook(get_prehook(forward_node_stack, node._sequence_nr())) + + special_stack = forward_node_stack.copy() + special_stack.append(fx_traceback.GRADIENT_ACC_SPECIAL_STACK) + node.register_hook(get_posthook(special_stack, node._sequence_nr())) + + +def setup_stacktrace_preservation_hooks_from_tensors(outputs: Any) -> None: + roots = [ + t.grad_fn + for t in (outputs if isinstance(outputs, (list, tuple)) else (outputs,)) + if isinstance(t, torch.Tensor) and t.grad_fn is not None + ] + if roots: + setup_stacktrace_preservation_hooks(roots) + + +def describe_input(i: int, aot_config: AOTConfig) -> str: + if i < aot_config.num_params_buffers: + return f"parameter/buffer {i}" + else: + return f"input {i - aot_config.num_params_buffers}" + + +def format_guard_bug_msg(aot_config: AOTConfig, expected: str) -> str: + return ( + f"At compilation time, graph {aot_config.aot_id} was compiled under the " + f"assumption that {expected}, but at runtime this was not the case. " + "This indicates a guard bug in AOTAutograd or Dynamo, please file a bug to PyTorch." + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..2fcc5a964c3f1dbadd302c0429101abe5e76246d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py @@ -0,0 +1,3915 @@ +""" +This module defines runtime wrappers, which, based on previous analysis attempts to: +1. process the inputs and outputs +2. apply mutations +3. handle functionalized randomness +4. deduplicate inputs and consolidate views into their bases (see input_output_analysis) +""" + +import collections +import contextlib +import copy +import functools +import itertools +import pprint +import typing +import warnings +import weakref +from collections.abc import Callable, Generator, Sequence +from contextlib import AbstractContextManager, nullcontext +from dataclasses import dataclass, field +from functools import wraps +from typing import Any + +import torch +import torch.fx as fx +from torch import Tensor +from torch._custom_class_base import CustomClassBase +from torch._dynamo import config as dynamo_config +from torch._dynamo.callback import callback_handler, CallbackTrigger +from torch._dynamo.graph_bytecode_inputs import index_to_external_object_weakref +from torch._dynamo.utils import CompileEventLogger, dynamo_timed, get_metrics_context +from torch._guards import ( + compile_context, + CompileContext, + detect_fake_mode, + DuplicateInputs, + tracing, + TracingContext, +) +from torch._library.opaque_object import is_custom_class +from torch._library.utils import is_builtin +from torch._logging import getArtifactLogger +from torch._ops import OpOverload +from torch._prims_common import CUDARngStateHelper +from torch._subclasses.fake_tensor import is_fake_tensor +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import HANDLED_TYPES +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + TorchDispatchMode, +) +from torch.utils._pytree import tree_flatten + +from .. import config +from .collect_metadata_analysis import run_functionalized_fw_and_collect_metadata +from .descriptors import ( + AOTInput, + AOTOutput, + DummyAOTInput, + MetadataMutationAOTOutput, + SyntheticBaseAOTInput, + ViewBaseAOTInput, +) +from .functional_utils import gen_alias_from_base +from .graph_capture_wrappers import aot_dispatch_subclass +from .input_output_analysis import ( + compute_overlapping_inputs, + create_synthetic_base_metadata, + remove_dupe_metadata, +) +from .logging_utils import describe_input, format_guard_bug_msg, track_graph_compiling +from .schemas import ( + AOTConfig, + CompilerWrapper, + FxValue, + InductorWrapper, + InputAliasInfo, + MemoryFormatMeta, + MutationType, + OpaqueMeta, + OutputAliasInfo, + OutputType, + PlainTensorMeta, + SubclassCreationMeta, + SubclassMeta, + TensorAlias, + TraceFn, + ViewAndMutationMeta, +) +from .subclass_utils import ( + requires_subclass_dispatch, + runtime_unwrap_tensor_subclasses, + wrap_tensor_subclasses, +) +from .utils import ( + call_and_expect_output_descs, + call_func_at_runtime_with_args, + make_boxed_func, + partial_flatten_asdict, + simple_wraps, + strict_zip, + without_output_descs, +) + + +if typing.TYPE_CHECKING: + from .codegen import PySourceBuilder + + +def _snapshot_external_objects(ctx: Any) -> None: + """Snapshot the external object registry onto ctx for backward restore.""" + ctx._external_objects = { + k: ref() + for k, ref in index_to_external_object_weakref.items() + if ref() is not None + } + + +def _unwrap_tensor_subclasses_no_symints( + args: list[Any], +) -> list[Any]: + return runtime_unwrap_tensor_subclasses(args, append_symints=False) # type: ignore[arg-type] + + +zip = strict_zip + +aot_graphs_log = getArtifactLogger(__name__, "aot_graphs") + + +def _unwrap_no_symints(args: list[Any]) -> list[Any]: + return runtime_unwrap_tensor_subclasses(args, append_symints=False) + + +def _describe_arg_for_logging(arg: object) -> str: + from torch._library import opaque_object + + try: + is_dtensor = isinstance(arg, torch.distributed.tensor.DTensor) + except AttributeError: + is_dtensor = False + + if is_dtensor: + arg = typing.cast(torch.distributed.tensor.DTensor, arg) + mesh = arg.device_mesh + return ( + f"DTensor(shape={arg.shape}, dtype={arg.dtype}, " + f"device={arg.device}, mesh_shape={mesh.shape}, " + f"placements={arg.placements})" + ) + elif isinstance(arg, torch.Tensor): + return f"Tensor(shape={arg.shape}, dtype={arg.dtype}, device={arg.device})" + elif opaque_object.is_custom_class(type(arg)): + return f"Opaque: {type(arg).__name__}" + else: + return f"{type(arg).__name__}: {arg}" + + +def _log_input_metadata(runtime_metadata: ViewAndMutationMeta) -> None: + aot_graphs_log.debug( + "Expected input metadata (count=%s):", len(runtime_metadata.subclass_inp_meta) + ) + for i, meta in enumerate(runtime_metadata.subclass_inp_meta): + aot_graphs_log.debug(" [%s] %s", i, meta) + + +def _log_args_list(args: Sequence[object], label: str) -> None: + aot_graphs_log.debug("%s (count=%s):", label, len(args)) + for i, arg in enumerate(args): + aot_graphs_log.debug(" [%s] %s", i, _describe_arg_for_logging(arg)) + + +def _log_args_maybe_list(arg: object, label: str) -> None: + if isinstance(arg, (list, tuple)): + _log_args_list(arg, label) + else: + aot_graphs_log.debug("%s: %s", label, _describe_arg_for_logging(arg)) + + +# The wrapper created by this function handles all of the runtime aliasing and mutation "epilogue" logic +# that needs to run after the compiled function. +# +# This function accepts a trace_joint flag, indicating whether or not we're generating the runtime +# epilogue for a forward-only inference graph, or for an autograd.Function.apply function. +# This is because there are some minor differences in how we treat these cases at runtime: +# - resize_() is currently handled in the inference case, but not fully handled in the autograd case. +# - the autograd cases inserts TensorAlias wrapper objects for outputs that alias inputs +@dataclass +class RuntimeWrapper(CompilerWrapper): + indices_of_inps_to_detach: list[int] + trace_joint: bool + disable_amp: bool + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + return _create_runtime_wrapper( + compiled_fn, + runtime_metadata=runtime_metadata, + indices_of_inps_to_detach=self.indices_of_inps_to_detach, + trace_joint=self.trace_joint, + keep_input_mutations=aot_config.keep_inference_input_mutations, + disable_amp=self.disable_amp, + ) + + +class NoopAliasHandler: + def __init__( + self, + info: OutputAliasInfo, + runtime_metadata: ViewAndMutationMeta, + trace_joint: bool, + ) -> None: + pass + + def __call__( + self, orig_inputs: dict[int, Tensor], fw_outs: list[Any], out: Any + ) -> Any: + return out + + +def _unwrap_tensoralias(x: TensorAlias) -> torch.Tensor: + if not isinstance(x, TensorAlias): + raise AssertionError(f"expected TensorAlias, got {type(x)}") + return x.alias + + +def _identity(x: Any) -> Any: + return x + + +class AliasOfInputHandler: + def __init__( + self, + info: OutputAliasInfo, + runtime_metadata: ViewAndMutationMeta, + trace_joint: bool, + ) -> None: + if info.base_idx is None: + raise AssertionError("expected info.base_idx to be set") + self.base_idx = info.base_idx + self.unwrap_out = _unwrap_tensoralias if trace_joint else _identity + self.requires_grad = info.requires_grad + self.view_meta_sequence = info.view_meta_sequence + self.replay_views = config.view_replay_for_aliased_outputs + + def __call__( + self, orig_inputs: dict[int, Tensor], fw_outs: list[Any], out: Any + ) -> torch.Tensor: + aliased_base_tensor = orig_inputs[self.base_idx] + return gen_alias_from_base( + aliased_base_tensor, + self.unwrap_out(out), + self.requires_grad, + self.view_meta_sequence, + replay_views=self.replay_views, + ) + + +class IsInputHandler: + def __init__( + self, + info: OutputAliasInfo, + runtime_metadata: ViewAndMutationMeta, + trace_joint: bool, + ) -> None: + if info.base_idx is None: + raise AssertionError("expected info.base_idx to be set") + self.base_idx = info.base_idx + + def __call__( + self, orig_inputs: dict[int, Tensor], fw_outs: list[Any], out: Any + ) -> torch.Tensor: + aliased_base_tensor = orig_inputs[self.base_idx] + return aliased_base_tensor + + +class AliasOfIntermediateHandler: + def __init__( + self, + info: OutputAliasInfo, + runtime_metadata: ViewAndMutationMeta, + trace_joint: bool, + ) -> None: + if info.base_idx is None: + raise AssertionError("expected info.base_idx to be set") + self._unwrap_aliased_base_tensor = _identity + if info.output_type in ( + OutputType.alias_of_intermediate, + OutputType.alias_of_intermediate_save_as_output, + ): + num_user_outputs = len(runtime_metadata.output_info) + self.base_idx = info.base_idx + num_user_outputs + else: + self.base_idx = info.base_idx + if self.base_idx in runtime_metadata.aliased_out_indices: + self._unwrap_aliased_base_tensor = _unwrap_tensoralias + + self.unwrap_out = _unwrap_tensoralias if trace_joint else _identity + self.requires_grad = info.requires_grad + self.view_meta_sequence = info.view_meta_sequence + self.replay_views = config.view_replay_for_aliased_outputs + + def __call__( + self, orig_inputs: dict[int, Tensor], fw_outs: list[Any], out: Any + ) -> torch.Tensor: + aliased_base_tensor = fw_outs[self.base_idx] + return gen_alias_from_base( + self._unwrap_aliased_base_tensor(aliased_base_tensor), + self.unwrap_out(out), + self.requires_grad, + self.view_meta_sequence, + replay_views=self.replay_views, + ) + + +_HANDLER_MAP: dict[ + OutputType, + type[ + NoopAliasHandler + | AliasOfInputHandler + | IsInputHandler + | AliasOfIntermediateHandler + ], +] = { + OutputType.non_alias: NoopAliasHandler, + OutputType.unsafe_view_alias: NoopAliasHandler, + OutputType.custom_function_view: NoopAliasHandler, + OutputType.alias_of_input: AliasOfInputHandler, + OutputType.is_input: IsInputHandler, + OutputType.alias_of_intermediate: AliasOfIntermediateHandler, + OutputType.alias_of_intermediate_save_as_output: AliasOfIntermediateHandler, + OutputType.alias_of_intermediate_base_is_user_output: AliasOfIntermediateHandler, +} + + +def make_output_handler( + info: OutputAliasInfo, runtime_metadata: ViewAndMutationMeta, trace_joint: bool +) -> ( + NoopAliasHandler | AliasOfInputHandler | IsInputHandler | AliasOfIntermediateHandler +): + handler_type = _HANDLER_MAP[info.output_type] + return handler_type(info, runtime_metadata, trace_joint) + + +# _dynamo_propagated_dynamic_indices: A guardless attribute for cross-graph-break +# dynamism propagation. When AOTAutograd traces a graph and discovers that output +# dimensions are symbolic (dynamic), it stamps this attribute on the output tensors +# at runtime. This tells Dynamo to treat those dims as weakly dynamic when the tensor +# appears as input to a subsequent graph (e.g., after a graph break), avoiding +# unnecessary specialization and recompilation. +# +# Unlike _dynamo_weak_dynamic_indices (which is user-facing, set via maybe_mark_dynamic(), +# and guarded on), this attribute is compiler-internal and NOT guarded on. This avoids +# the problem where the compiler mutating an input tensor's attributes (through an +# input-aliased output) would cause a spurious guard failure and recompilation. +# +# Note: this is best-effort. Eager code does not propagate +# _dynamo_propagated_dynamic_indices, so there is no guarantee that the next graph +# will have proper dynamism information. It only helps when the output of one compiled +# graph feeds directly into the next. +def mark_dynamo_propagated_dynamic_indices(t: torch.Tensor, dims: set[int]) -> None: + if hasattr(t, "_dynamo_propagated_dynamic_indices"): + # pyrefly: ignore [missing-attribute] + t._dynamo_propagated_dynamic_indices |= dims + else: + t._dynamo_propagated_dynamic_indices = dims.copy() # type: ignore[attr-defined] + + +def _should_disable_saved_tensors_hooks() -> bool: + # Compiled autograd is not supported yet, to be added in future. + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + return False + + get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks + are_inline_hooks = ( + torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable + ) + + hooks = get_hooks() + if are_inline_hooks(hooks): + return True + + return False + + +def _schema_allows_aliasing(func: Any) -> bool: + schema = func._schema + # View ops have non-write aliases declared in arguments + if schema._is_view_op(): + return True + # Handles cases like mkldnn::_convolution_pointwise_.binary + # where the schema is Tensor(a!) other -> Tensor(a!) Y + for ret in schema.returns: + if ret.alias_info is not None: + return True + return False + + +def _check_custom_op_aliasing( + name: str, args: tuple[Any, ...], kwargs: dict[str, Any], result: Any +) -> None: + """ + Check if custom op outputs alias inputs or other outputs. + If config.error_on_custom_op_aliasing is True, raises RuntimeError. + Otherwise, emits a warning. + """ + try: + torch._library.utils._c_check_aliasing_constraint( + name, + args, + kwargs, + result, + ) + except RuntimeError as e: + if config.error_on_custom_op_aliasing: + raise + else: + msg = f"{e} This is deprecated and will become an error in a future version of PyTorch." + warnings.warn(msg, UserWarning, stacklevel=3) + + +@functools.lru_cache(None) +def _is_fsdp_all_gather_copy_in(func: Any) -> bool: + """ + Check if func is torch.ops.fsdp.all_gather_copy_in.default by comparing + namespace and name strings. This avoids accessing torch.ops.fsdp directly, + which would fail on platforms where FSDP ops aren't registered (e.g., macOS + builds with USE_DISTRIBUTED=0). + """ + return ( + hasattr(func, "namespace") + and func.namespace == "fsdp" + and hasattr(func, "__name__") + and func.__name__ == "all_gather_copy_in.default" + ) + + +class _AnalyzeCustomOpInputOutputMode(TorchDispatchMode): + """ + Checks if inp/out of custom ops alias each other. + If config.error_on_custom_op_aliasing is True, violations raise errors. + Otherwise, violations emit warnings. + """ + + def __init__(self) -> None: + super().__init__() + self.supports_higher_order_operators = True + + def __torch_dispatch__( + self, + func: OpOverload, + types: Any, + args: tuple[Any, ...] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + if not kwargs: + kwargs = {} + + flat_tensor_args = filter( + lambda x: isinstance(x, torch.Tensor), tree_flatten((args, kwargs))[0] + ) + + # Defer this to subclass torchdispatch modes (probably shouldn't have fake tensor here tho) + # For Parameters, we need to check the underlying tensor type, not the Parameter itself + for tensor in flat_tensor_args: + underlying_tensor = tensor + if isinstance(tensor, torch.nn.Parameter): + underlying_tensor = tensor.data + if type(underlying_tensor) not in HANDLED_TYPES: + return NotImplemented + + res = func(*args, **kwargs) + # Only check aliasing for custom ops (non-aten/prim/prims/_c10d_functional/c10d) + # that claim to be functional + # Skip ops whose schema declares aliasing is allowed + if ( + not isinstance(func, torch._ops.HigherOrderOperator) + and not is_builtin(func) + # TODO (https://github.com/pytorch/pytorch/issues/170986) + and func.namespace not in ("_c10d_functional", "c10d", "onednn") + # This op is quite important but has wrong schema, so lets skip for now + and not _is_fsdp_all_gather_copy_in(func) + and not _schema_allows_aliasing(func) + ): + _check_custom_op_aliasing( + func.name(), + args, + kwargs, + res, + ) + return res + + @classmethod + def ignore_compile_internals(cls) -> bool: + return True + + +class _FirstInvocationContext: + """ + Context manager that tracks first invocation and conditionally enables _AnalyzeCustomOpInputOutputMode. + This is useful when we have a custom op where we want to analyze its input + and output during cold start. + """ + + def __init__(self) -> None: + self._is_first = True + + def __call__(self) -> AbstractContextManager[Any]: + """ + Returns a context manager: _AnalyzeCustomOpInputOutputMode on first invocation, nullcontext thereafter. + Automatically updates state after first use. + """ + # NB: Don't run the analyzer when you're forcing compile during FX + # tracing, as the analyzer doesn't play nicely when it's being + # make_fx'ed through + if ( + self._is_first + and config.check_custom_op_aliasing + and not torch._dynamo.config.force_compile_during_fx_trace + ): + self._is_first = False + return _AnalyzeCustomOpInputOutputMode() + return nullcontext() + + +# Note [RuntimeWrapper codegen specification methods] +# The run() method on _RuntimeCompiledFnInvoker and the capture_orig_inputs(), +# increment_mutation_versions(), and finalize() methods on _RuntimeForwardEpilogue +# are the readable reference implementations for the codegen'd _runtime_wrapper +# generated in _create_runtime_wrapper(). They are not called on the hot path; +# the codegen inlines their logic with all branches resolved at compile time. +# +# WARNING: Any semantic change to the runtime wrapper must be reflected in both +# the reference methods here and the codegen in _create_runtime_wrapper(). +@dataclass +class _RuntimeCompiledFnInvoker: + compiled_fn: Callable[..., Any] + indices_of_inps_to_detach: list[int] + trace_joint: bool + disable_amp: bool + first_invocation_ctx: _FirstInvocationContext = field( + default_factory=_FirstInvocationContext + ) + + def __post_init__(self) -> None: + if not getattr(self.compiled_fn, "_boxed_call", False): + self.compiled_fn = make_boxed_func(self.compiled_fn) + + # WARNING: this is a reference implementation; the hot path uses codegen'd + # code from _create_runtime_wrapper(). Keep both in sync. + # See Note [RuntimeWrapper codegen specification methods] + def run(self, args: list[Any], *, on_before_call: Callable[[], None]) -> list[Any]: + with self.first_invocation_ctx(): + if self.trace_joint: + args_ = list(args) + # See Note [Detaching inputs that never need gradients] + for idx in self.indices_of_inps_to_detach: + if isinstance(args_[idx], torch.Tensor): + args_[idx] = args_[idx].detach() + + # It's possible to have trace_joint inside user specified with no_grad() region, + # if there is a nested with enable_grad(), that forces some outputs to require gradients. + # Therefore, we unconditionally turn on enable_grad() for compiled_fn execution. + prev_view_replay_enabled = torch._C._is_view_replay_enabled() + try: + if not prev_view_replay_enabled: + torch._C._set_view_replay_enabled(True) + with torch.enable_grad(): + on_before_call() + return call_func_at_runtime_with_args( + self.compiled_fn, + args_, + disable_amp=self.disable_amp, + steal_args=True, + ) + finally: + if torch._C._is_view_replay_enabled() != prev_view_replay_enabled: + torch._C._set_view_replay_enabled(prev_view_replay_enabled) + + # When we have an inference graph, we run with grad disabled. + # It's possible to get an inference graph with inputs that require grad, + # in which case we want to make sure autograd is disabled + # (since e.g., inductor will generate aten.addmm.out calls which autograd will complain on) + # NOTE: We use _set_grad_enabled directly to reduce runtime overhead + grad_enabled = torch.is_grad_enabled() + try: + if grad_enabled: + torch._C._set_grad_enabled(False) + on_before_call() + return call_func_at_runtime_with_args( + self.compiled_fn, + args, + disable_amp=self.disable_amp, + steal_args=True, + ) + finally: + if grad_enabled: + torch._C._set_grad_enabled(True) + + +@dataclass +class _RuntimeForwardEpilogue: + runtime_metadata: ViewAndMutationMeta + trace_joint: bool + keep_input_mutations: bool + epilogue_args_idx: tuple[int, ...] = field(init=False) + output_handlers: tuple[ + NoopAliasHandler + | AliasOfInputHandler + | IsInputHandler + | AliasOfIntermediateHandler, + ..., + ] = field(init=False) + + def __post_init__(self) -> None: + epilogue_args_idx = list(self.runtime_metadata.mutated_inp_runtime_indices) + for info in self.runtime_metadata.output_info: + if ( + info.output_type == OutputType.alias_of_input + or info.output_type == OutputType.is_input + ): + if not isinstance(info.base_idx, int): + raise AssertionError( + f"expected info.base_idx to be int, got {type(info.base_idx)}" + ) + epilogue_args_idx.append(info.base_idx) + self.epilogue_args_idx = tuple(epilogue_args_idx) + + if config.unlift_effect_tokens: + if len(self.runtime_metadata.tokens) != 0: + raise AssertionError( + "expected no tokens when unlift_effect_tokens is True, " + f"got {len(self.runtime_metadata.tokens)}" + ) + + if self.runtime_metadata.num_outputs_aliased > 0: + self.output_handlers = tuple( + make_output_handler(info, self.runtime_metadata, self.trace_joint) + for info in self.runtime_metadata.output_info + ) + else: + self.output_handlers = () + + # WARNING: this is a reference implementation; the hot path uses codegen'd + # code from _create_runtime_wrapper(). Keep both in sync. + # See Note [RuntimeWrapper codegen specification methods] + def capture_orig_inputs(self, args: list[Any]) -> dict[int, Tensor]: + return {i: typing.cast(Tensor, args[i]) for i in self.epilogue_args_idx} + + # WARNING: this is a reference implementation; the hot path uses codegen'd + # code from _create_runtime_wrapper(). Keep both in sync. + # See Note [RuntimeWrapper codegen specification methods] + def increment_mutation_versions(self, args: list[Any]) -> None: + if self.keep_input_mutations: + mutated_args = ( + args[i] + for i in self.runtime_metadata.mutated_graph_handled_indices_seen_by_autograd + ) + torch.autograd.graph.increment_version(mutated_args) + + # WARNING: this is a reference implementation; the hot path uses codegen'd + # code from _create_runtime_wrapper(). Keep both in sync. + # See Note [RuntimeWrapper codegen specification methods] + def finalize(self, orig_inputs: dict[int, Tensor], all_outs: list[Any]) -> Any: + self._validate_compiled_output_arity(all_outs) + updated_inputs, fw_outs = self._split_mutated_inputs(all_outs) + if updated_inputs is not None: + self._apply_input_mutations(orig_inputs, updated_inputs) + + ret_outs = self._replay_output_aliases(orig_inputs, fw_outs) + if self.runtime_metadata.dynamic_outputs: + for t, o in zip(ret_outs, self.runtime_metadata.output_info): + if o.dynamic_dims is None: + continue + mark_dynamo_propagated_dynamic_indices(t, o.dynamic_dims) + if self.runtime_metadata.grad_enabled_mutation is not None: + torch._C._set_grad_enabled(self.runtime_metadata.grad_enabled_mutation) + return ret_outs + + def _validate_compiled_output_arity(self, all_outs: list[Any]) -> None: + expected_outs = ( + self.runtime_metadata.num_mutated_inp_runtime_indices + + self.runtime_metadata.num_outputs + + self.runtime_metadata.num_intermediate_bases + ) + if len(all_outs) != expected_outs: + raise AssertionError( + f"expected {expected_outs} outputs, got {len(all_outs)}" + ) + + def _split_mutated_inputs( + self, all_outs: list[Any] + ) -> tuple[list[Any] | None, list[Any]]: + num_mutated_runtime_inps = self.runtime_metadata.num_mutated_inp_runtime_indices + if num_mutated_runtime_inps == 0: + return None, all_outs + return ( + all_outs[:num_mutated_runtime_inps], + all_outs[num_mutated_runtime_inps:], + ) + + def _apply_input_mutations( + self, orig_inputs: dict[int, Tensor], updated_inputs: list[Any] + ) -> None: + for i, inpt_idx in enumerate(self.runtime_metadata.mutated_inp_runtime_indices): + meta = self.runtime_metadata.input_info[inpt_idx] + if not meta.mutates_data and not meta.mutates_metadata: + continue + original_inpt = orig_inputs[inpt_idx] + updated_inpt = updated_inputs[i] + if meta.mutates_storage_metadata: + # See Note [set_() Input Mutations in AOTAutograd] + # mutates_storage_metadata means our input saw a x.set_(y) call. + # What if x **also** saw a data and/or a metadata mutation? + # (1) If the [meta]data mutation occurred after the set_(), + # then there is no need to copy_() the data. + # When we perform x.set_(x_updated), we are guaranteed that + # x_updated already has the final version of the data/metadata + # (2) If a data mutation occurred before the set_(). + # This case seems very difficult to support. + # TODO: discuss on the PR and decide if we want to tr to + # either support it, or detect and ban it. + if self.trace_joint: + if not isinstance(updated_inpt, TensorAlias): + raise AssertionError( + f"expected TensorAlias for updated_inpt, got {type(updated_inpt)}" + ) + updated_inpt = updated_inpt.alias + with torch.no_grad(): + if meta.mutation_is_shallow_copy_data: + torch.ops.aten.shallow_copy_data_(original_inpt, updated_inpt) + else: + original_inpt.set_(updated_inpt) + continue + if meta.mutates_metadata and not meta.mutates_data: + if self.trace_joint: + if not isinstance(updated_inpt, TensorAlias): + raise AssertionError( + f"expected TensorAlias for updated_inpt, got {type(updated_inpt)}" + ) + updated_inpt = updated_inpt.alias + # We need to grab the size/stride/storage_offset from the compiled forward, + # and use that to mutate the metadata of the input + original_inpt.as_strided_( + updated_inpt.size(), + updated_inpt.stride(), + updated_inpt.storage_offset(), + ) + else: + if meta.mutates_data and meta.mutates_metadata: + original_inpt.as_strided_( + updated_inpt.size(), + updated_inpt.stride(), + updated_inpt.storage_offset(), + ) + else: + if not meta.mutates_data: + raise AssertionError("expected meta.mutates_data to be True") + if meta.is_leaf and original_inpt.requires_grad: + # We can hit this situation in this case: + # def f(x): + # x.detach().mul_(2) + # return x + 1 + # AOTAutograd will see a mutation in the above case, and try to + # apply a copy_() here, in the epilogue. + # But if x required gradients, and is a leaf, then autograd + # will yell at us for trying to mutate it. + # However, it's only possible to end up in this scenario (like the above) + # if all of the mutations to the leaf input were non-autograd-tracking mutations + # (aka mutations under no_grad(), or on detached views). + # In that case, we fully want to hide the mutation from autograd, so detaching is ok. + original_inpt.detach().copy_(updated_inpt) + else: + # Check if we have stream index information for this mutated input + if ( + self.runtime_metadata.mutated_inp_stream_indices is not None + and i < len(self.runtime_metadata.mutated_inp_stream_indices) + and self.runtime_metadata.mutated_inp_stream_indices[i] + is not None + ): + raise RuntimeError( + "Mutations on inputs with user-specified streams are not yet supported. " + "See: https://github.com/pytorch/pytorch/issues/172522" + ) + original_inpt.copy_(updated_inpt) + + def _replay_output_aliases( + self, orig_inputs: dict[int, Tensor], fw_outs: list[Any] + ) -> Any: + if self.runtime_metadata.num_outputs_aliased == 0: + return fw_outs + + # The compiled forward also returned intermediate bases. We don't want to return them to the user. + expect_num_outputs = ( + len(self.output_handlers) + self.runtime_metadata.num_intermediate_bases + ) + if len(fw_outs) != expect_num_outputs: + raise AssertionError( + f"expected {expect_num_outputs} fw_outs, got {len(fw_outs)}" + ) + return [ + handler(orig_inputs, fw_outs, out) + for out, handler in zip(fw_outs, self.output_handlers) + ] + + +def _codegen_capture_orig_inputs( + buf: "PySourceBuilder", + epilogue_args_idx: tuple[int, ...], +) -> None: + if epilogue_args_idx: + idx_str = ", ".join(f"{i}: args[{i}]" for i in epilogue_args_idx) + buf.emit(f"orig_inputs = {{{idx_str}}}", indent=1) + else: + buf.emit("orig_inputs = {}", indent=1) + + +def _codegen_increment_mutation_versions( + buf: "PySourceBuilder", + keep_input_mutations: bool, + runtime_metadata: ViewAndMutationMeta, +) -> None: + if ( + keep_input_mutations + and runtime_metadata.mutated_graph_handled_indices_seen_by_autograd + ): + buf.add_global("_increment_version_", torch.autograd.graph.increment_version) + mut_idx = tuple(runtime_metadata.mutated_graph_handled_indices_seen_by_autograd) + gen_expr = ", ".join(f"args[{i}]" for i in mut_idx) + buf.emit(f"_increment_version_(({gen_expr},))", indent=1) + + +def _codegen_normalize_as_list( + buf: "PySourceBuilder", var_name: str, *, indent_level: int +) -> None: + buf.emit(f"if isinstance({var_name}, tuple):", indent=indent_level) + buf.emit(f"{var_name} = list({var_name})", indent=indent_level + 1) + buf.emit(f"elif not isinstance({var_name}, list):", indent=indent_level) + buf.emit(f"{var_name} = [{var_name}]", indent=indent_level + 1) + + +def _codegen_compiled_fn_invocation( + buf: "PySourceBuilder", + trace_joint: bool, + indices_of_inps_to_detach: list[int], + disable_amp: bool, +) -> None: + buf.emit("with _first_ctx_():", indent=1) + # trace_joint is known at codegen time. Only the joint/training path needs + # forced view replay; inference wrappers should not touch this TLS state. + if trace_joint: + buf.emit("args_ = list(args)", indent=2) + for idx in indices_of_inps_to_detach: + buf.emit( + f"if isinstance(args_[{idx}], torch.Tensor): " + f"args_[{idx}] = args_[{idx}].detach()", + indent=2, + ) + buf.emit( + "prev_view_replay_enabled = torch._C._is_view_replay_enabled()", indent=2 + ) + buf.emit("try:", indent=2) + buf.emit("if not prev_view_replay_enabled:", indent=3) + buf.emit("torch._C._set_view_replay_enabled(True)", indent=4) + buf.emit("with torch.enable_grad():", indent=3) + buf.emit("_on_before_call_()", indent=4) + if disable_amp: + buf.add_global("_DisableAutocast_", torch._C._DisableAutocast) + buf.emit("with _DisableAutocast_():", indent=4) + buf.emit("all_outs = _compiled_fn_(args_)", indent=5) + _codegen_normalize_as_list(buf, "all_outs", indent_level=5) + else: + buf.emit("all_outs = _compiled_fn_(args_)", indent=4) + _codegen_normalize_as_list(buf, "all_outs", indent_level=4) + buf.emit("finally:", indent=2) + buf.emit( + "if torch._C._is_view_replay_enabled() != prev_view_replay_enabled:", + indent=3, + ) + buf.emit( + "torch._C._set_view_replay_enabled(prev_view_replay_enabled)", indent=4 + ) + else: + buf.emit("grad_enabled = torch.is_grad_enabled()", indent=2) + buf.emit("try:", indent=2) + buf.emit("if grad_enabled: torch._C._set_grad_enabled(False)", indent=3) + buf.emit("_on_before_call_()", indent=3) + if disable_amp: + buf.add_global("_DisableAutocast_", torch._C._DisableAutocast) + buf.emit("with _DisableAutocast_():", indent=3) + buf.emit("all_outs = _compiled_fn_(args)", indent=4) + _codegen_normalize_as_list(buf, "all_outs", indent_level=4) + else: + buf.emit("all_outs = _compiled_fn_(args)", indent=3) + _codegen_normalize_as_list(buf, "all_outs", indent_level=3) + buf.emit("finally:", indent=2) + buf.emit("if grad_enabled: torch._C._set_grad_enabled(True)", indent=3) + buf.emit("del args", indent=1) + + +# signatures mirror the _RuntimeForwardEpilogue reference methods +# (_apply_input_mutations / _replay_output_aliases). The codegen'd _alias_fn +# always builds and returns a list, so list[Any] is tighter than the reference's +# -> Any (the early `return fw_outs` path does not exist in the codegen'd fn). +_EpilogueApplyMutationsFn = Callable[[dict[int, Tensor], list[Any]], None] +_EpilogueReplayAliasesFn = Callable[[dict[int, Tensor], list[Any]], list[Any]] + + +def _codegen_epilogue( + buf: "PySourceBuilder", + runtime_metadata: ViewAndMutationMeta, + apply_mutations_fn: _EpilogueApplyMutationsFn | None, + replay_aliases_fn: _EpilogueReplayAliasesFn | None, + num_mutated_runtime_inps: int, + expected_outs: int, +) -> None: + buf.emit(f"if len(all_outs) != {expected_outs}:", indent=1) + buf.emit( + f'raise AssertionError(f"expected {expected_outs} outputs, ' + f'got {{len(all_outs)}}")', + indent=2, + ) + + if num_mutated_runtime_inps > 0: + buf.emit(f"updated_inputs = all_outs[:{num_mutated_runtime_inps}]", indent=1) + buf.emit(f"fw_outs = all_outs[{num_mutated_runtime_inps}:]", indent=1) + buf.emit("_apply_mutations_(orig_inputs, updated_inputs)", indent=1) + buf.add_global("_apply_mutations_", apply_mutations_fn) + else: + buf.emit("fw_outs = all_outs", indent=1) + + if runtime_metadata.num_outputs_aliased > 0: + buf.add_global("_replay_aliases_", replay_aliases_fn) + buf.emit("ret_outs = _replay_aliases_(orig_inputs, fw_outs)", indent=1) + else: + buf.emit("ret_outs = fw_outs", indent=1) + + if runtime_metadata.dynamic_outputs: + buf.add_global("_mark_dynamic_", mark_dynamo_propagated_dynamic_indices) + for i, o in enumerate(runtime_metadata.output_info): + if o.dynamic_dims is not None: + dims_name = f"_dyn_dims_{i}" + buf.add_global(dims_name, o.dynamic_dims) + buf.emit(f"_mark_dynamic_(ret_outs[{i}], {dims_name})", indent=1) + + if runtime_metadata.grad_enabled_mutation is not None: + buf.emit( + f"torch._C._set_grad_enabled({runtime_metadata.grad_enabled_mutation!r})", + indent=1, + ) + + buf.emit("return ret_outs", indent=1) + + +def _create_runtime_wrapper( + compiled_fn: Callable[..., Any], + *, + runtime_metadata: ViewAndMutationMeta, + indices_of_inps_to_detach: list[int], + trace_joint: bool, + keep_input_mutations: bool, + disable_amp: bool, +) -> Callable[..., Any]: + compiled_invoker = _RuntimeCompiledFnInvoker( + compiled_fn=compiled_fn, + indices_of_inps_to_detach=indices_of_inps_to_detach, + trace_joint=trace_joint, + disable_amp=disable_amp, + ) + runtime_epilogue = _RuntimeForwardEpilogue( + runtime_metadata=runtime_metadata, + trace_joint=trace_joint, + keep_input_mutations=keep_input_mutations, + ) + + # The orchestration closes over these two codegen'd epilogue functions directly + # (bound into rw_globals as _apply_mutations_ / _replay_aliases_ in _codegen_epilogue). + # Each stays None when its epilogue step is absent for this graph. + codegen_apply_mutations: _EpilogueApplyMutationsFn | None = None + codegen_alias_fn: _EpilogueReplayAliasesFn | None = None + + # Codegen output alias regeneration: emit straight-line code per output + # with all handler branches resolved at compile time. + if runtime_metadata.num_outputs_aliased > 0: + output_handlers = runtime_epilogue.output_handlers + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_alias_fn", + args="orig_inputs, fw_outs", + artifact_name="output_alias_wrapper", + ) + buf.bind( + gen_alias_from_base=gen_alias_from_base, + _unwrap_tensoralias=_unwrap_tensoralias, + ) + with buf.indent(): + buf.writeline("ret_outs = []") + for i, handler in enumerate(output_handlers): + if isinstance(handler, NoopAliasHandler): + buf.writeline(f"ret_outs.append(fw_outs[{i}])") + elif isinstance(handler, IsInputHandler): + buf.writeline(f"ret_outs.append(orig_inputs[{handler.base_idx}])") + elif isinstance(handler, AliasOfInputHandler): + vms_name = buf.bind_value("_vms", handler.view_meta_sequence) + out_expr = ( + f"_unwrap_tensoralias(fw_outs[{i}])" + if trace_joint + else f"fw_outs[{i}]" + ) + buf.writeline( + f"ret_outs.append(gen_alias_from_base(" + f"orig_inputs[{handler.base_idx}], {out_expr}, " + f"{handler.requires_grad!r}, {vms_name}, " + f"replay_views={handler.replay_views!r}))" + ) + elif isinstance(handler, AliasOfIntermediateHandler): + vms_name = buf.bind_value("_vms", handler.view_meta_sequence) + out_expr = ( + f"_unwrap_tensoralias(fw_outs[{i}])" + if trace_joint + else f"fw_outs[{i}]" + ) + base_unwrap = ( + handler._unwrap_aliased_base_tensor is _unwrap_tensoralias + ) + base_expr = ( + f"_unwrap_tensoralias(fw_outs[{handler.base_idx}])" + if base_unwrap + else f"fw_outs[{handler.base_idx}]" + ) + buf.writeline( + f"ret_outs.append(gen_alias_from_base(" + f"{base_expr}, {out_expr}, " + f"{handler.requires_grad!r}, {vms_name}, " + f"replay_views={handler.replay_views!r}))" + ) + else: + raise AssertionError( + f"unhandled output handler type: {type(handler).__name__}" + ) + buf.writeline("return ret_outs") + + codegen_alias_fn = typing.cast(_EpilogueReplayAliasesFn, buf.build()) + + def record_runtime_wrapper_prologue_enter() -> AbstractContextManager[None] | None: + if ( + torch.autograd.profiler._is_profiler_enabled + and dynamo_config.record_runtime_overhead + ): + cm = torch._C._profiler._RecordFunctionFast( + "AOTDispatcher Runtime Wrapper Prologue" + ) + cm.__enter__() + return cm + return None + + def record_runtime_wrapper_prologue_exit( + cm: AbstractContextManager[None] | None, + ) -> None: + if cm is not None: + cm.__exit__(None, None, None) + + # Codegen mutation epilogue: emit straight-line code per mutated input + # with all branches resolved at compile time. + if runtime_metadata.num_mutated_inp_runtime_indices > 0: + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_apply_mutations", + args="orig_inputs, updated_inputs", + artifact_name="mutation_epilogue", + ) + buf.bind(torch=torch, _unwrap_tensoralias=_unwrap_tensoralias) + wrote_body = False + with buf.indent(): + for i, inpt_idx in enumerate(runtime_metadata.mutated_inp_runtime_indices): + meta = runtime_metadata.input_info[inpt_idx] + if not meta.mutates_data and not meta.mutates_metadata: + continue + wrote_body = True + oi = f"orig_inputs[{inpt_idx}]" + ui = f"updated_inputs[{i}]" + if meta.mutates_storage_metadata: + u = buf.fresh_name("_u") + if trace_joint: + buf.writeline(f"{u} = _unwrap_tensoralias({ui})") + else: + buf.writeline(f"{u} = {ui}") + buf.writeline(f"with torch.no_grad(): {oi}.set_({u})") + elif meta.mutates_metadata and not meta.mutates_data: + u = buf.fresh_name("_u") + if trace_joint: + buf.writeline(f"{u} = _unwrap_tensoralias({ui})") + else: + buf.writeline(f"{u} = {ui}") + buf.writeline( + f"{oi}.as_strided_({u}.size(), {u}.stride(), {u}.storage_offset())" + ) + else: + if meta.mutates_data and meta.mutates_metadata: + buf.writeline( + f"{oi}.as_strided_({ui}.size(), {ui}.stride(), {ui}.storage_offset())" + ) + else: + if not meta.mutates_data: + raise AssertionError( + f"expected mutates_data for input {inpt_idx}" + ) + if meta.is_leaf: + buf.writeline( + f"if {oi}.requires_grad: {oi}.detach().copy_({ui})" + ) + buf.writeline(f"else: {oi}.copy_({ui})") + else: + has_stream = ( + runtime_metadata.mutated_inp_stream_indices is not None + and i < len(runtime_metadata.mutated_inp_stream_indices) + and runtime_metadata.mutated_inp_stream_indices[i] + is not None + ) + if has_stream: + msg_name = buf.bind_value( + "_stream_err", + "Mutations on inputs with user-specified streams are not yet supported. " + "See: https://github.com/pytorch/pytorch/issues/172522", + ) + buf.writeline(f"raise RuntimeError({msg_name})") + else: + buf.writeline(f"{oi}.copy_({ui})") + if not wrote_body: + buf.writeline("pass") + + codegen_apply_mutations = typing.cast(_EpilogueApplyMutationsFn, buf.build()) + + from .codegen import PySourceBuilder + + epilogue_args_idx = runtime_epilogue.epilogue_args_idx + num_mutated_runtime_inps = runtime_metadata.num_mutated_inp_runtime_indices + expected_outs = ( + num_mutated_runtime_inps + + runtime_metadata.num_outputs + + runtime_metadata.num_intermediate_bases + ) + + buf = PySourceBuilder( + "_runtime_wrapper", + args="_compiled_fn_, _first_ctx_, _on_before_call_, args", + artifact_name="runtime_wrapper_orchestration", + ) + buf.bind(torch=torch) + + _codegen_capture_orig_inputs(buf, epilogue_args_idx) + _codegen_increment_mutation_versions(buf, keep_input_mutations, runtime_metadata) + _codegen_compiled_fn_invocation( + buf, trace_joint, indices_of_inps_to_detach, disable_amp + ) + _codegen_epilogue( + buf, + runtime_metadata, + codegen_apply_mutations, + codegen_alias_fn, + num_mutated_runtime_inps, + expected_outs, + ) + + _codegen_runtime_wrapper = buf.build() + + _inner_compiled_fn = compiled_invoker.compiled_fn + _first_invocation_ctx = compiled_invoker.first_invocation_ctx + + @simple_wraps(_inner_compiled_fn) + def runtime_wrapper(args: list[Any]) -> Any: + cm = record_runtime_wrapper_prologue_enter() + prologue_exited = False + + def exit_prologue() -> None: + nonlocal prologue_exited + if not prologue_exited: + record_runtime_wrapper_prologue_exit(cm) + prologue_exited = True + + try: + result = _codegen_runtime_wrapper( + _inner_compiled_fn, + _first_invocation_ctx, + exit_prologue, + args, + ) + finally: + exit_prologue() + del args + return result + + if not (trace_joint and _should_disable_saved_tensors_hooks()): + return runtime_wrapper + + @simple_wraps(runtime_wrapper) + def _runtime_wrapper(*args: Any, **kwargs: Any) -> Any: + with _disable_saved_tensors_hooks(): + return runtime_wrapper(*args, **kwargs) + + return _runtime_wrapper + + +# WARNING: this does NOT operate on TraceFn +@dataclass +class FunctionalizedRngRuntimeWrapper(InductorWrapper): + # TODO: I would love to get rid of this argument, but it's + # Wrapped pretty tightly around our aot_dispatch_autograd logic. + # Specifically, tensors_saved_for_backwards_slice's value is both used for calculating indices + # for setting placeholder strides(which is done before runtime, before this wrapper runs) + # and for saving tensors for backward (which is done during runtime, after this wrapper runs) + # So in aot_dispatch_autograd, this wrapper can't edit the set of outs without making one + # of those two indices incorrect. + return_new_outs: bool = True + + def pre_compile( + self, + fw_module: torch.fx.GraphModule, + flat_args: list[Any], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> None: + if config.functionalize_rng_ops: + # Update example inputs for the fw_compiler + fake_mode = detect_fake_mode() + if fake_mode is None: + raise AssertionError( + "fake_mode must not be None when functionalize_rng_ops is True" + ) + seed, offset = CUDARngStateHelper.get_torch_state_as_tuple(fake_mode) + flat_args.extend([seed, offset]) + # We are not clearing flat_args here because + # 1) There is a check in the debug compiler at the end + # 2) It does not matter as these are fake tensors + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + if not runtime_metadata.is_rng_op_functionalized: + return compiled_fn + + if runtime_metadata.num_outputs_rng_offset != 1: + raise AssertionError( + f"expected num_outputs_rng_offset == 1, got {runtime_metadata.num_outputs_rng_offset}" + ) + + from .codegen import PySourceBuilder + + offset_index = runtime_metadata.num_forward_returns + buf = PySourceBuilder( + "_functionalized_rng_wrapper", + args="runtime_args", + artifact_name="functionalized_rng_wrapper", + ) + buf.bind( + _compiled_fn_=compiled_fn, + _get_rng_state_=CUDARngStateHelper.get_torch_state_as_tuple, + _set_offset_=CUDARngStateHelper.set_new_offset, + ) + with buf.indent(): + buf.writeline("seed, offset = _get_rng_state_()") + buf.writeline("runtime_args.extend([seed, offset])") + buf.writeline("outs = _compiled_fn_(runtime_args)") + buf.writeline(f"_set_offset_(outs[{offset_index}])") + if self.return_new_outs: + buf.writeline( + f"return outs[:{offset_index}] + outs[{offset_index + 1}:]" + ) + else: + buf.writeline("return outs") + + inner_fn = buf.build(wrapped_fn=compiled_fn) + inner_fn._boxed_call = True # type: ignore[attr-defined] + return inner_fn + + # Calling convention: If we are running functionalized RNG, then outs consists + # of (user_outs, rng_offset) + def _functionalized_rng_runtime_epilogue( + self, + metadata: ViewAndMutationMeta, + outs: Any, + offset_index: int, + ) -> Any: + if metadata.is_rng_op_functionalized: + if metadata.num_outputs_rng_offset != 1: + raise AssertionError( + f"expected num_outputs_rng_offset == 1, got {metadata.num_outputs_rng_offset}" + ) + new_rng_offset = outs[offset_index] + CUDARngStateHelper.set_new_offset(new_rng_offset) + if self.return_new_outs: + user_outs = outs[:offset_index] + outs[offset_index + 1 :] + return user_outs + else: + return outs + + return outs + + +# WARNING: this does NOT operate on TraceFn +@dataclass +class FakifiedOutWrapper(InductorWrapper): + out_metas: list[torch.Tensor] = field(default_factory=list) + # TracingContext.fwd_output_strides + # Generated from actually doing compile + # NB: an entry is None if it's not a Tensor + fwd_output_strides: list[list[int] | None] | None = None + needs_post_compile: bool = True + + def pre_compile( + self, + fw_module: fx.GraphModule, # Must be fw_module from aot_dispatch_*_graph + flat_args: list[Any], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> None: + tracing_context = torch._guards.TracingContext.try_get() + if tracing_context and tracing_context.fakify_first_call: + self.out_metas = [ + n.meta["val"] for n in (list(fw_module.graph.nodes)[-1].args[0]) + ] + else: + self.needs_post_compile = False + + def _compute_output_meta_with_inductor_strides(self) -> list[torch.Tensor]: + out = self.out_metas + fwd_output_strides = self.fwd_output_strides + if not fwd_output_strides: + return out + + from torch.fx.experimental.symbolic_shapes import statically_known_true + + for i in range(len(out)): + if not isinstance(out[i], Tensor): + continue + strides = fwd_output_strides[i] + # fwd_output_strides is best effort by Inductor. When an output + # Tensor has unbacked SymInts, Inductor may sometimes be unable + # to compute what the output stride would be. If Inductor doesn't + # have any clear direction on the layout, we don't have to run + # as_strided. To repro without this, run: + # + # python test/distributed/test_dynamo_distributed.py + # TestFakeDistributedSingleProc.test_unbacked_symbol_splitting_no_binding + if strides is None: + continue + if all( + statically_known_true(s1 == s2) + for s1, s2 in zip(out[i].stride(), strides) + ): + continue + out[i] = out[i].as_strided(out[i].shape, strides) + return out + + # To be called post compile + def set_fwd_output_strides( + self, fwd_output_strides: list[list[int] | None] + ) -> None: + self.fwd_output_strides = fwd_output_strides + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + if self.needs_post_compile: + if self.fwd_output_strides is None: + raise AssertionError( + "fwd_output_strides must not be None when needs_post_compile is True" + ) + fakified_out = self._compute_output_meta_with_inductor_strides() + + @wraps(compiled_fn) + def wrapper(runtime_args: list[Any]) -> Any: + nonlocal fakified_out + if fakified_out is not None: + out = fakified_out + fakified_out = None + return out + return compiled_fn(runtime_args) + + return wrapper + # If we don't need to fakify, we can just return the original compiled function + return compiled_fn + + +# This wrapper handles the AOTDispatch runtime logic for tensor subclasses. +# At runtime, we have a compiled function that knows how to operate on the domain of DenseTensor -> DenseTensor, +# But the user might have passed us some tensor subclass inputs (or expect some subclass tensor outputs). +# This function handles the wrapping and unwrapping of tensor subclasses at runtime. +@dataclass +class AOTDispatchSubclassWrapper(CompilerWrapper): + trace_joint: bool + fw_only: Callable[..., Any] | None # Not cached, only used in pre_compile + maybe_subclass_meta: SubclassMeta | None + num_fw_outs_saved_for_bw: int | None + + def pre_compile( + self, + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[TraceFn, list[FxValue], list[AOTInput], ViewAndMutationMeta]: + (new_flat_fn, new_flat_args, new_flat_args_descs, subclass_meta) = ( + aot_dispatch_subclass( + flat_fn, + flat_args, + flat_args_descs, + is_joint_structure=self.trace_joint, + meta=fw_metadata, + fw_only=self.fw_only, # type: ignore[arg-type] + ) + ) + self.maybe_subclass_meta = subclass_meta + return new_flat_fn, new_flat_args, new_flat_args_descs, fw_metadata + + @staticmethod + def _get_frozen_inp_indices() -> frozenset[int]: + # fw_compiler_freezing (compile_fx.py) bakes frozen params into the + # graph and sets their TracingContext.params_flat entries to None + # before post_compile runs. We pass these indices to codegen so it + # can emit straight-line code instead of a runtime None check. + tc = TracingContext.try_get() + if tc is None or tc.params_flat is None: + return frozenset() + return frozenset(i for i, p in enumerate(tc.params_flat) if p is None) + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + if self.maybe_subclass_meta is None and not runtime_metadata.act_input_paths: + return compiled_fn + + from .subclass_codegen import codegen_subclass_wrapper + + inner_fn = codegen_subclass_wrapper( + compiled_fn=compiled_fn, + inp_metas=runtime_metadata.subclass_inp_meta, + out_metas=runtime_metadata.subclass_fw_graph_out_meta, + num_fw_outs_saved_for_bw=self.num_fw_outs_saved_for_bw, + frozen_inp_indices=self._get_frozen_inp_indices(), + act_input_paths=runtime_metadata.act_input_paths, + ) + inner_fn._boxed_call = True # type: ignore[attr-defined] + return inner_fn + + +@dataclass +class EffectTokensWrapper(CompilerWrapper): + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + num_tokens = len(runtime_metadata.tokens) + if num_tokens == 0: + return compiled_fn + + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_effect_tokens_wrapper", + args="args", + artifact_name="effect_tokens_wrapper", + ) + buf.bind(_compiled_fn_=compiled_fn) + with buf.indent(): + buf.writeline(f"new_args = [{', '.join(['None'] * num_tokens)}, *args]") + buf.writeline("args.clear()") + buf.writeline("outs = _compiled_fn_(new_args)") + buf.writeline("if outs is None:") + with buf.indent(): + buf.writeline("return None") + buf.writeline(f"return outs[{num_tokens}:]") + + inner_fn = buf.build(wrapped_fn=compiled_fn) + inner_fn._boxed_call = True # type: ignore[attr-defined] + return inner_fn + + +# MOTIVATION: +# +# When tracing functions for future execution, one must be careful not to pass +# in the same input tensor multiple times (e.g., f(x, x), as this can result +# in graphs that are ONLY valid if you later pass a new tensor in exactly the +# same way (e.g., f(y, y)). (NB: we really mean duplicate; two distinct +# tensors that alias each other is a different situation that is covered by +# aot_dispatch_deduplicated_autograd). Here are two examples: +# +# (1) Suppose you have a function: +# +# def f(x, y): +# return x + y +# +# If you make_fx(f)(x, x), you will trace out: +# +# def f(x, y): +# return y + y +# +# Oops! +# +# (2) For most tensors x and y, you can compute f's gradient with respect to +# these to inputs by saying torch.autograd.grad(f(x, y), (x, y)). However, +# if x is y, you will trace out a program that gets incorrect gradients: +# +# >>> x = torch.randn(1, requires_grad=True) +# >>> torch.autograd.grad(x + x, (x, x)) +# (tensor([2.]), tensor([2.])) +# +# In other words, the gradient is double-counted. Deduplicating the arguments +# gives you an appropriate gradient: +# +# >>> y = torch.randn(1, requires_grad=True) +# >>> torch.autograd.grad(x + y, (x, y)) +# (tensor([1.]), tensor([1.])) +# +# HOW TO DEDUPLICATE: +# +# There are a few strategies, in order of preference: +# +# 1. For every duplicate argument to the function, detach it into +# a separate leaf tensor, so that it is no longer duplicated. +# +# PRO: The resulting compiled graph works for any configuration +# of duplicated arguments. +# +# CON: It does not (naively) work if you mutate the metadata of inputs: +# +# def f(x, y): +# x.transpose_(0, 1) +# y.transpose_(0, 2) +# +# x = torch.randn(2, 3, 4) +# f(x, x) +# +# The ordering of the transposes inside f dictates whether or not +# you get [4, 2, 3] or [3, 4, 2]. This means that you cannot precompute +# what metadata mutations should get applied to each input; you need to +# assume they aren't duplicates (what we do today) or preserve +# the original metadata mutations exactly in order, so that they work +# for any duplicate configuration. +# +# CON: It does not (naively) work if you mutate the data of inputs. +# In particular, leaf tensors that require grad cannot be mutated, +# this makes it impossible to differentiate with respect to the original +# base. +# +# 2. For every duplicate argument to the function, remove it, so it is +# no longer part of the "true" signature: +# +# PRO: Implemented naively, it still works for metadata/data mutation. +# +# CON: The resulting compiled graph is duplicate-specialized: it only +# works if future calls duplicate arguments in exactly the same way. +# Horribly, Dynamo doesn't guard on this at the moment. But even if +# it did, you could still end up recompiling a bunch of each duplicate. +# +# Our strategy is to do (1) if we can, and do (2) otherwise, erroring if +# Dynamo's guards are not enough. In practice, this seems to cover +# everything. +# +@dataclass +class AOTDedupeWrapper(CompilerWrapper): + keep_arg_mask: list[bool] = field(default_factory=list) + add_dupe_map: list[int] = field(default_factory=list) + old_input_metadata: list[InputAliasInfo] = field(default_factory=list) + needs_post_compile: bool = True + + # NB: Hot path, avoid set lookups here + # TODO: Can avoid the zip here too, probably + def remove_dupe_args(self, args: list[Any]) -> list[Any]: + return [t for t, keep in zip(args, self.keep_arg_mask) if keep] + + def add_dupe_args(self, args: list[Any]) -> list[Any]: + return [args[i] for i in self.add_dupe_map] + + def pre_compile( + self, + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[TraceFn, list[FxValue], list[AOTInput], ViewAndMutationMeta]: + # Use information about whether or not flat_fn mutates its arguments + # or not to handle dupe args + + # Strategy 1: For any input that is not mutated, we can leafify it if we + # need to remove a duplicate. + leaf_flat_args: list[FxValue] = [] + leaf_flat_args_descs: list[AOTInput] = [] + args_set = set() + ok = True + + for i, (a, a_desc) in enumerate(zip(flat_args, flat_args_descs)): + if not isinstance(a, torch.Tensor): + leaf_flat_args.append(a) + leaf_flat_args_descs.append(a_desc) + elif a not in args_set: + args_set.add(a) + leaf_flat_args.append(a) + leaf_flat_args_descs.append(a_desc) + elif ( + not fw_metadata.input_info[i].mutates_data + and not fw_metadata.input_info[i].mutates_metadata + ): + leaf_flat_args.append(a.detach().requires_grad_(a.requires_grad)) + leaf_flat_args_descs.append(a_desc) + else: + ok = False + break + + if ok: + self.needs_post_compile = False + return flat_fn, leaf_flat_args, leaf_flat_args_descs, fw_metadata + + if requires_subclass_dispatch(leaf_flat_args, fw_metadata): # type: ignore[arg-type] + raise RuntimeError( + """\ + Encountered duplicate inputs that are mutated in the graph, but at least one input/output + to the graph is a tensor subclass. This is not supported today. You can try to + remove the aliasing yourself as a workaround, or otherwise file an issue on github.""" + ) + + # export path: ban duplicate inputs for now, add later if requested. + if aot_config.is_export: + raise RuntimeError( + f"""\ + Encountered duplicated inputs that are mutated in the graph you are trying to export. + This functionality is currently not supported. If needed, please file a github issue. + + fw_metadata={str(fw_metadata)} + """ + ) + + # Strategy 2: Duplicate specialization + # + # When we have duplicate arguments in a function call, we need to handle them specially. + # For example, if we have a function call f(a, b, a, c), we need to: + # + # 1. Remove duplicates to get a deduplicated list [a, b, c] + # 2. Compile our function to work with this deduplicated list + # 3. At runtime, convert incoming arguments with duplicates to the deduplicated form + # 4. Pass the deduplicated arguments to our compiled function + # + # To do this, we need two helper functions: + # + # - remove_dupe_args: Converts [a, b, a, c] -> [a, b, c] + # - add_dupe_args: Converts [a, b, c] -> [a, b, a, c] + # + # For our example [a, b, a, c], we track: + # + # - seen_args = {a: 0, b: 1, c: 2} (maps each unique arg to its first position) + # - add_dupe_map = [0, 1, 0, 2] (tells us how to reconstruct the original list) + # - keep_arg_mask = [True, True, False, True] (tells us which args to keep when deduplicating) + + seen_args: dict[Tensor, int] = {} + # Implicitly map duped arg position (list index) to de-duped arg position + keep_arg_mask: list[bool] = [] + add_dupe_map: list[int] = [] + duped_arg_len = len(flat_args) + + j = 0 # index into deduped_flat_args + for t in flat_args: + if isinstance(t, torch.Tensor): + if t in seen_args: + keep_arg_mask.append(False) + add_dupe_map.append(seen_args[t]) + continue + seen_args[t] = j + + keep_arg_mask.append(True) + add_dupe_map.append(j) + j += 1 + if len(add_dupe_map) != duped_arg_len: + raise AssertionError( + f"Expects add_dupe_map to have length {duped_arg_len} but got {len(add_dupe_map)}" + ) + + self.keep_arg_mask = keep_arg_mask + self.add_dupe_map = add_dupe_map + + deduped_flat_args = self.remove_dupe_args(flat_args) + # TODO: instead of arbitrarily removing args, it might be useful to + # have a record that these were duped, perhaps as a mutable attribute + # on the kept arg? Do this if someone needs it + deduped_flat_args_descs = self.remove_dupe_args(flat_args_descs) + + # Update our input metadata to remove duped input metadata. + updated_fw_metadata = remove_dupe_metadata( + fw_metadata, keep_arg_mask, add_dupe_map + ) + + if ( + tracing_context := TracingContext.try_get() + and aot_config.aot_autograd_arg_pos_to_source + ): + # TODO(voz): This structure is 1:1, we could consider an alternate structure like + # kept_pos:[dupe_arg_pos], however, add_dupe_map is 1:1 so we would need a new structure there, + # which feels like needless complexity for a tiny bit of efficiency at this point. + for dupe_arg_pos, (kept_pos, keep_arg) in enumerate( + zip(add_dupe_map, keep_arg_mask) + ): + if not keep_arg: + dupe_arg_source = aot_config.aot_autograd_arg_pos_to_source[ + dupe_arg_pos + ] + kept_arg_source = aot_config.aot_autograd_arg_pos_to_source[ + kept_pos + ] + tracing_context.guards_context.aotautograd_guards.append( # type: ignore[attr-defined] + DuplicateInputs(kept_arg_source, dupe_arg_source) + ) + + @simple_wraps(flat_fn) + def wrapped_flat_fn( + *args: FxValue, + ) -> tuple[list[FxValue], list[AOTOutput]]: + outs, out_descs = call_and_expect_output_descs( + flat_fn, + self.add_dupe_args(args), # type: ignore[arg-type] + ) + return outs, out_descs + + if config.debug_assert: + ref_fw_metadata = run_functionalized_fw_and_collect_metadata( + without_output_descs(wrapped_flat_fn), + flat_args_descs=deduped_flat_args_descs, + static_input_indices=aot_config.static_input_indices, + keep_input_mutations=fw_metadata.keep_input_mutations, + )(*deduped_flat_args) + if ref_fw_metadata != updated_fw_metadata: + raise AssertionError( + f"ref_metadata={str(ref_fw_metadata)}, actual_metadata={str(updated_fw_metadata)}" + ) + + return ( + wrapped_flat_fn, + deduped_flat_args, + deduped_flat_args_descs, + updated_fw_metadata, + ) + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + if not self.needs_post_compile: + return compiled_fn + + keep_indices = [i for i, keep in enumerate(self.keep_arg_mask) if keep] + idx_list = ", ".join(f"args[{i}]" for i in keep_indices) + from .codegen import PySourceBuilder + + buf = PySourceBuilder("inner_fn", args="args", artifact_name="dedup_wrapper") + buf.bind(compiled_fn=compiled_fn) + with buf.indent(): + buf.writeline(f"deduped_args = [{idx_list}]") + buf.writeline("args.clear()") + buf.writeline("return compiled_fn(deduped_args)") + + wrapped_compiled_fn: Callable[..., Any] = buf.build( # type: ignore[assignment] + wrapped_fn=compiled_fn + ) + + wrapped_compiled_fn._boxed_call = True # type: ignore[attr-defined] + + # This can be uncommented when we properly guard for duplicates, + # but right now we must not do it. + # if not config.debug_assert: + # return wrapped_compiled_fn + + @wraps(wrapped_compiled_fn) + def debugged_compiled_fn(args: list[Any]) -> Any: + # Test that the computed remove/add arg functions are an inverse + new_args = self.add_dupe_args(self.remove_dupe_args(args)) + seen: dict[Any, None] = {} + for i, (x, y) in enumerate(zip(new_args, args)): + seen[y] = None + if x is not y: + raise AssertionError( + format_guard_bug_msg( + aot_config, + f"{describe_input(i, aot_config)} would be a duplicate of " + f"{describe_input(self.add_dupe_map[i], aot_config)}", + ) + ) + # This is only an error if there is metadata mutation on both of + # the duped arguments; in this case, we need to know what order + # the metadata mutation applies in. You'll get the correct result + # otherwise, because a graph that assumes distinct inputs works if + # you dupe the inputs (the gradient contributions from each input + # will get summed up appropriately.) + # + # TODO: work out how to setup this assert correctly + """ + assert len(seen) == unique_args, format_guard_bug_msg(aot_config, + f"there would be {unique_args} distinct arguments" + ) + """ + return wrapped_compiled_fn(args) + + debugged_compiled_fn._boxed_call = True # type: ignore[attr-defined] + + return debugged_compiled_fn + + +# This layer handles the situation where you have two inputs that alias each other, +# and one of the inputs is mutated. +# We need to take special care to ensure that the mutation is applied to the other aliases in the graph. +# +# pre-condition: AOTDedupWrapper has already run. +# (This function will in theory work if there are duplicate args. +# However, the synthetic base code path is a bit sub-optimal, and running with dupe'd inputs +# would cause us to hit that path more frequently). +@dataclass +class AOTSyntheticBaseWrapper(CompilerWrapper): + # Currently, the only reason we need to plumb this bool is because + # the synthetic base code prohibits more cases in the autograd case than the inference case. + trace_joint: bool # TODO: refactor trace_joint + needs_post_compile: bool = True + aliased_arg_idx_with_metadata_mutations: list[int] = field(default_factory=list) + base_groups: dict[int, list[int]] = field( + default_factory=lambda: collections.defaultdict(list) + ) + other_arg_indices: list[int] = field(default_factory=list) + + def pre_compile( + self, + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[Callable[..., Any], list[FxValue], list[AOTInput], ViewAndMutationMeta]: + is_inference = not self.trace_joint + ( + flat_args_with_synthetic_bases, + flat_args_descs_with_synthetic_bases, + synthetic_base_info, + ) = merge_view_inputs( + aot_config, + flat_args, + flat_args_descs, + fw_metadata.input_info, + is_inference=is_inference, + ) + + # Happy path: we don't need synthetic bases + if synthetic_base_info is None: + self.needs_post_compile = False + return flat_fn, flat_args, flat_args_descs, fw_metadata + + # export path: ban synthetic bases for now, add later if requested. + if requires_subclass_dispatch(flat_args, fw_metadata): # type: ignore[arg-type] + raise RuntimeError( + """\ + Encountered aliased inputs that are mutated in the graph, but at least one input/output + to the graph is a tensor subclass. This is not supported today. You can try to + remove the aliasing yourself as a workaround, or otherwise file an issue on github.""" + ) + + if aot_config.is_export: + raise RuntimeError( + f"""\ + Encountered aliased inputs that are mutated in the graph you are trying to export. + This functionality is currently not supported. If needed, please file a github issue. + + synthetic_base_info={str(synthetic_base_info)} + + fw_metadata={str(fw_metadata)} + """ + ) + + if len(fw_metadata.input_info) != len(synthetic_base_info): + raise AssertionError( + f"expected len(fw_metadata.input_info) == len(synthetic_base_info), " + f"got {len(fw_metadata.input_info)} != {len(synthetic_base_info)}" + ) + + # Update our forward metadata to take synthetic bases into account + ( + fw_metadata_updated, + aliased_arg_idx_with_metadata_mutations, + ) = create_synthetic_base_metadata( + fw_metadata, + synthetic_base_info, + flat_args, + flat_args_with_synthetic_bases, + flat_args_descs_with_synthetic_bases, + ) + # Pre-compute base_groups and other_arg_map from + # synthetic_base_info so the post_compile codegen can emit a + # wrapper without calling merge_view_inputs at runtime. + # + # other_arg_entries collects (new_idx, orig_idx) pairs so we can + # sort by new_idx -- the position in the post-merge calling + # convention (bases ++ others). merge_view_inputs puts + # non-tensor args before non-aliased tensor args, so iterating + # by orig_idx alone would produce a wrong order when non-tensors + # are interleaved with tensors. + other_arg_entries: list[tuple[int, int]] = [] + for orig_idx, entry in enumerate(synthetic_base_info): + if isinstance(entry, int): + other_arg_entries.append((entry, orig_idx)) + else: + base_idx, _ = entry + self.base_groups[base_idx].append(orig_idx) + other_arg_entries.sort() + self.other_arg_indices = [orig_idx for _, orig_idx in other_arg_entries] + + self.aliased_arg_idx_with_metadata_mutations = ( + aliased_arg_idx_with_metadata_mutations + ) + replay_views = config.view_replay_for_aliased_outputs + + def _unpack_synthetic_bases(primals: tuple[Any, ...]) -> list[Any]: + f_args_inner = [] + # pyrefly: ignore [not-iterable] + for inner_idx_or_tuple in synthetic_base_info: + if isinstance(inner_idx_or_tuple, int): + f_args_inner.append(primals[inner_idx_or_tuple]) + else: + inner_base_idx, view_tensor = inner_idx_or_tuple + base = primals[inner_base_idx] + view_arg = gen_alias_from_base( + base, + view_tensor, + view_tensor.requires_grad, + replay_views=replay_views, + ) + f_args_inner.append(view_arg) + return f_args_inner + + @simple_wraps(flat_fn) + def wrapped_flat_fn(*args: Any) -> Any: + unpacked_args = _unpack_synthetic_bases(args) + # This is a bit subtle. The goal of this entire function (aot_dispatch_synthetic_bases) + # is to relieve the downstream logic from having to reason about mutations on inputs that alias + # each other, by replacing aliased inputs with a synthetic base. + # One area where this breaks down a bit however is if one of those aliased inputs + # experienced a metadata mutation. + # We are now obligated to reapply the metadata mutation directly to the user's input; + # it isn't enough to apply mutations back to the synthetic base in the downstream logic. + # + # The way we handle this is by pretending that those aliased inputs that experience metadata mutations + # are additional outputs in the user's forward function. + # The downstream logic will just treat these as "user outputs that alias inputs". + # However, we will manually grab them at runtime here, use them to reapply the metadata mutation + # to the user inputs, and not return them to the user. + aliased_args_with_metadata_mutations = [ + x + for i, x in enumerate(unpacked_args) + if i in self.aliased_arg_idx_with_metadata_mutations + ] + out, out_descs = call_and_expect_output_descs(flat_fn, unpacked_args) # type: ignore[arg-type] + if len(aliased_args_with_metadata_mutations) > 0: + # TODO: record more detailed desc information here + return (*out, *aliased_args_with_metadata_mutations), ( + *out_descs, + *( + [ + MetadataMutationAOTOutput(i) + for i in range( + len(self.aliased_arg_idx_with_metadata_mutations) + ) + ] + ), + ) + else: + return out, out_descs + + if config.debug_assert: + ref_fw_metadata = run_functionalized_fw_and_collect_metadata( + without_output_descs(wrapped_flat_fn), + flat_args_descs=flat_args_descs_with_synthetic_bases, + static_input_indices=aot_config.static_input_indices, + keep_input_mutations=fw_metadata.keep_input_mutations, + )(*flat_args_with_synthetic_bases) + if ref_fw_metadata != fw_metadata_updated: + raise AssertionError( + f"ref_metadata={pprint.pformat(partial_flatten_asdict(ref_fw_metadata))}, " + f"\nactual_metadata={pprint.pformat(partial_flatten_asdict(fw_metadata_updated))}" + ) + return ( + wrapped_flat_fn, + flat_args_with_synthetic_bases, + flat_args_descs_with_synthetic_bases, + fw_metadata_updated, + ) + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + if not self.needs_post_compile: + return compiled_fn + + from .codegen import PySourceBuilder + + base_groups = self.base_groups + other_indices = self.other_arg_indices + + num_bases = len(base_groups) + aliased_meta_mut_indices = self.aliased_arg_idx_with_metadata_mutations + num_meta_mut = len(aliased_meta_mut_indices) + + buf = PySourceBuilder( + "_synthetic_base_wrapper", + args="args", + artifact_name="synthetic_base_wrapper", + ) + buf.bind(torch=torch, _compiled_fn_=compiled_fn) + + with buf.indent(): + buf.writeline(f"_bases = [None] * {num_bases}") + for base_idx in sorted(base_groups): + group = base_groups[base_idx] + first_orig = group[0] + if len(group) == 1: + indices_check = f"args[{first_orig}]._base is not None" + base_expr = f"args[{first_orig}]._base" + else: + indices_str = ", ".join(str(i) for i in group) + indices_check = ( + f"any(args[_i]._base is not None for _i in [{indices_str}])" + ) + base_expr = f"next(args[_i]._base for _i in [{indices_str}] if args[_i]._base is not None)" + buf.writeline(f"if {indices_check}:") + with buf.indent(): + buf.writeline(f"_bases[{base_idx}] = {base_expr}") + buf.writeline("else:") + with buf.indent(): + buf.writeline( + f"_b = torch.empty((0,), dtype=args[{first_orig}].dtype, device=args[{first_orig}].device)" + ) + buf.writeline(f"_b.set_(args[{first_orig}].untyped_storage())") + buf.writeline(f"_bases[{base_idx}] = _b") + + other_items = ", ".join(f"args[{orig}]" for orig in other_indices) + buf.writeline(f"_new_args = _bases + [{other_items}]") + + if num_meta_mut > 0: + meta_items = ", ".join(f"args[{i}]" for i in aliased_meta_mut_indices) + buf.writeline(f"_meta_mut = [{meta_items}]") + + buf.writeline("args.clear()") + buf.writeline("_outs = _compiled_fn_(_new_args)") + + if num_meta_mut > 0: + # Handles metadata mutations on inputs that were merged into + # synthetic bases (create_synthetic_base_metadata hides these + # from the normal tracking by forcing mutates_metadata=False + # on the base). Metadata mutations on non-aliased inputs are + # handled separately by _apply_input_mutations in the runtime + # epilogue. + buf.writeline(f"_mut_inps = _outs[-{num_meta_mut}:]") + buf.writeline(f"_user_outs = _outs[:-{num_meta_mut}]") + buf.writeline("for _inp, _mi in zip(_meta_mut, _mut_inps):") + with buf.indent(): + buf.writeline( + "_inp.as_strided_(_mi.size(), _mi.stride(), _mi.storage_offset())" + ) + buf.writeline("return _user_outs") + else: + buf.writeline("return _outs") + + inner_fn = buf.build(wrapped_fn=compiled_fn) + inner_fn._boxed_call = True # type: ignore[attr-defined] + return inner_fn + + +# Note [Handling mutations on an input that aliases other inputs] +# The easiest example to show-case this edge case is here: +# +# def f(a, b): +# a.mul_(2) +# out = a + b +# return out +# b = torch.ones(...) +# a = b.view(-1) +# f(a, b) +# +# In this situation, if a and b happened to be aliased, we need to trace something different! +# Suppose we had b = a.view(-1) +# (In this case, that means that `a._base is b`) +# +# We need to ensure that the aliasing relationship between a and b is preserved. +# We do that detecting the specific situation above (mutate an input that aliases another input), +# and when we do that, we create a synthetic base argument. Then inside of the traced forward, +# we regenerate a and b off of that base. +# The complete example of the transformed function looks like this: +# +# // The traced forward takes in a synthetic base, and regenerates the aliased inputs as views +# // We could consider getting view-replay support here to minimize as_strided_scatter ops in the graph +# def traced_forward(base): +# a = base.as_strided(...) +# b = base.as_strided(...) +# a_updated = a.mul(2) +# base_updated = torch.as_strided_scatter(base, a_updated, ...) +# b_updated = base_updated.as_strided(...) +# out = a_updated + b_updated +# return a_updated, out +# +# def compiled_fn(a, b): +# // we detect that a is the "differentiable base" here +# base = a +# // In other situations, we might do either: +# // (1) a and b are both views off of some larger differentiable base +# // assert a._base is b._base and a._base is not None +# // base = a._base +# // (2) a and b both don't require gradients. Create a base from the storage +# // assert a._base is None and b._base is None +# // base = torch.Tensor(a.storage()) +# a_updated, out = traced_forward(base) +# a.copy_(a_updated) +# return out +# +# This function: +# (1) Merges input views into a synthetic base argument, when any of those input views are mutated +# (2) Returns metadata telling the autograd.Function how to modify their arguments properly, +# to respect the new calling convention. +# +# The calling convention is as follows. +# Any inputs that were originally views of one another get yanked, and replaced with a synthetic base. +# The argument list ordering goes [base1, ..., baseN], [arg1, ..., argN], +# Where the ordering of the bases is determined from the ordering of the original view args. +# baseA will come before baseB if the earliest original argument coming from baseA +# showed up earlier in the argument list than the earliest original argument coming from baseB. +# +# Example, given some tensors a, b, c, d +# call site: +# f(a, c.view(-1), b.view(-1), b, c, d) +# Modified argument list: +# c_base comes first because the first c view came earlier in arg list than the first b view +# a and d still show up in the modified arg list, but b and c don't- they're regenerated from their bases +# b_base = torch.Tensor(b.storage()) +# c_base = torch.Tensor(c.storage()) +# f(c_base, b_base, a, d) +def merge_view_inputs( + aot_config: AOTConfig, + fwd_inputs: list[Any], + # This is None when called at runtime from post_compile closure + fwd_inputs_descs: list[AOTInput] | None, + mutated_input_info: list[InputAliasInfo], + *, + # The autograd case currently has more restrictions than the inference case. + is_inference: bool, +) -> tuple[list[Any], list[AOTInput], list[int | tuple[int, torch.Tensor]] | None]: + if fwd_inputs_descs is None: + fwd_inputs_descs = [DummyAOTInput(i) for i in range(len(fwd_inputs))] + + def _are_differentiable_views(view1: torch.Tensor, view2: torch.Tensor) -> bool: + if view1 is view2: + return True + if view1._base is None and view2._base is None: + return False + if view1._base is view2._base or view1._base is view2 or view1 is view2._base: + return True + return False + + def _same_dtype_views(view1: torch.Tensor, view2: torch.Tensor) -> bool: + if view1.dtype != view2.dtype: + return False + if view1._base is not None and view1.dtype != view1._base.dtype: + return False + if view2._base is not None and view2.dtype != view2._base.dtype: + return False + return True + + def _format_input(idx: int) -> str: + if ( + aot_config.aot_autograd_arg_pos_to_source is not None + and idx < len(aot_config.aot_autograd_arg_pos_to_source) + and aot_config.aot_autograd_arg_pos_to_source[idx] is not None + ): + source = aot_config.aot_autograd_arg_pos_to_source[idx] + name = getattr(source, "local_name", source.name) + else: + name = fwd_inputs_descs[idx].expr() + return f"input {idx} ({name})" + + if len(fwd_inputs) != len(mutated_input_info): + raise AssertionError( + f"expected len(fwd_inputs) == len(mutated_input_info), " + f"got {len(fwd_inputs)} != {len(mutated_input_info)}" + ) + if not [info for info in mutated_input_info if info.mutates_data]: + # Return early when there are no mutations. + return fwd_inputs, fwd_inputs_descs, None + + storage_ref_to_idx: dict[StorageWeakRef, list[int]] = collections.defaultdict(list) + # pyrefly: ignore [implicit-any] + base_args = [] + # pyrefly: ignore [implicit-any] + other_args = [] + base_args_descs = [] + other_args_descs = [] + for i, (inpt, source) in enumerate(zip(fwd_inputs, fwd_inputs_descs)): + if isinstance(inpt, Tensor): + storage_ref = StorageWeakRef(inpt.untyped_storage()) + storage_ref_to_idx[storage_ref].append(i) + else: + other_args.append(inpt) + other_args_descs.append(source) + # Note [Synthetic Base Info Metadata] + # This list contains metadata that tells you what the i'th argument in the inner calling convention should be. + # It's either: + # - another int (corresponding to the index in the argument list of the element from the outer calling convention) + # - idx, view_tensor, where we can generate the new output with view_tensor._view_func(old_args[idx]) + # idx corresponds to which synthetic base from the outer calling context to view + inner_calling_convention_meta: dict[int, int | tuple[int, torch.Tensor]] = {} + for aliased_input_indices in storage_ref_to_idx.values(): + if len(aliased_input_indices) <= 1 or not any( + # We only care about mutations that affect all aliases, + # so metadata mutations on an input doesn't require us to do synthetic base handling. + mutated_input_info[inpt_idx].mutates_data + for inpt_idx in aliased_input_indices + ): + other_args.extend( + fwd_inputs[curr_idx] for curr_idx in aliased_input_indices + ) + other_args_descs.extend( + fwd_inputs_descs[curr_idx] for curr_idx in aliased_input_indices + ) + continue + + # Here, we attempt to do a more complicated check to detect false aliasing + # (e.g. if all the tensors have the same storage, but don't actually overlap) + # In theory, we could have a large group of tensors that all share storages, where only *some* of them + # have overlapping memory. + # I don't bother with that case for now: here, we only bail out earlier if we detect that **every** pair + # of tensors in the current group that shares a storage is non-overlapping. + aliased_input_indices_no_false_sharing = compute_overlapping_inputs( + aot_config, fwd_inputs, aliased_input_indices + ) + if len(aliased_input_indices_no_false_sharing) <= 1: + other_args.extend( + fwd_inputs[curr_idx] for curr_idx in aliased_input_indices + ) + other_args_descs.extend( + fwd_inputs_descs[curr_idx] for curr_idx in aliased_input_indices + ) + continue + + # We detected an input that was mutated, AND aliases with another input. + # we need to replace this set of aliased inputs with a single synthetic base. + # For now, I'm banning a bunch of cases. We expect dynamo to properly detect these cases + # and error out. We can fix them later. + # These checks are transitive, so we don't need to check every pair. + for idx1, idx2 in zip( + aliased_input_indices, aliased_input_indices[1:], strict=False + ): + view1 = fwd_inputs[idx1] + view2 = fwd_inputs[idx2] + # The "inputs that are aliased but have different differentiable bases" case + # is more complicated and hopefully pretty rare. Not currently handled. + if not is_inference: + if not _are_differentiable_views(view1, view2): + raise AssertionError( + f"aot_autograd() does not yet handle non-differentiable view input mutations. " + f"{_format_input(idx1)} and {_format_input(idx2)} share storage but are " + f"not differentiable views of each other." + ) + # Regenerating views when reinterpreting complex / real tensors seems non-trivial, + # not handling for now + if not _same_dtype_views(view1, view2): + raise AssertionError( + "aot_autograd() does not yet handle input mutations on views with different dtypes." + ) + non_none_bases = [ + (i, fwd_inputs[i]._base) + for i in aliased_input_indices + if fwd_inputs[i]._base is not None + ] + aliases_with_none_bases = [ + fwd_inputs[i] for i in aliased_input_indices if fwd_inputs[i]._base is None + ] + synthetic_base_desc: AOTInput + if len(non_none_bases) == 0: + # Case where none of the aliases have a ._base + # we generate a synthetic base without gradients, and generate views off of it + # We hit this case when we have input tensors to the graph that share a storage, + # but do not have a ._base field. + # Wondering when we hit this case? + # The _base field simply says that autograd knows about the aliasing relationship, + # but sometimes we create tensors which are aliased out of the same storage but guaranteed + # to be disjoint. In these cases, we will skip setting up the _base relationship + # for performance reasons (because the fact that the tensors share the same storage + # is unobservable unless you (1) do naughty things with resize_/as_strided + # or (2) look at the storage--as we are doing here.) + # One particular example of this is optimizer steps on the LSTM module: + # LSTM parameters are packed into a contiguous storage for efficiency reasons when + # calling cuDNN kernels, so when these parameters get passed to the optimizer we will + # find they share the same storage, but do not have _base set since they are all disjoint. + # + # NOTE: There is one case where this is unsafe: + # torch.Tensor(storage) will ALWAYS create a 1D tensor, which is not necessarily + # the same shape as the "actual" base that the tensor came from. + # For the most part this is fine, because we always use as_strided() + # to generate the original aliased inputs again. + # If we were to use view-replay though, this could cause the aliased views + # to have incorrect sizes. + example_idx = aliased_input_indices[0] + example_alias = fwd_inputs[example_idx] + # Note that this function is reused at both trace time and runtime. + # At trace time, we're under a FakeMode so synthetic_base becomes a FakeTensor. + synthetic_base = torch.empty( + (0,), dtype=example_alias.dtype, device=example_alias.device + ) + # We don't actually have a convenient way of going from storage -> tensor, + # So using set_() here (we suffer some minor overhead, but this case is rare). + synthetic_base.set_(example_alias.untyped_storage()) + synthetic_base_desc = SyntheticBaseAOTInput(fwd_inputs_descs[example_idx]) + else: + # Case where all of the aliases require gradients, and have the same _base. + i, synthetic_base = non_none_bases[0] + synthetic_base_desc = ViewBaseAOTInput(fwd_inputs_descs[i]) + for j, other_base in non_none_bases[1:]: + if other_base is not synthetic_base: + raise AssertionError( + f"aot_autograd() does not yet handle non-differentiable view input mutations. " + f"Aliased inputs share storage but have different autograd ._base tensors: " + f"{_format_input(i)} and {_format_input(j)} have ._base fields that point to different tensors." + ) + for alias in aliases_with_none_bases: + if alias is not synthetic_base: + none_base_indices = [ + _format_input(k) + for k in aliased_input_indices + if fwd_inputs[k]._base is None + ] + has_base_indices = [ + _format_input(k) + for k in aliased_input_indices + if fwd_inputs[k]._base is not None + ] + raise AssertionError( + f"aot_autograd() does not yet handle non-differentiable view input mutations. " + f"Aliased inputs share storage but have mixed autograd ._base states: " + f"{has_base_indices} have ._base set, while " + f"{none_base_indices} have ._base=None (and are not the synthetic base)." + ) + base_args.append(synthetic_base) + base_args_descs.append(synthetic_base_desc) + for curr_view_idx in aliased_input_indices: + curr_view = fwd_inputs[curr_view_idx] + base_idx = len(base_args) - 1 + # We store just enough info here so that we can regenerate the view later. + # Regeneration: curr_view._view_func(args[base_idx]) + inner_calling_convention_meta[curr_view_idx] = (base_idx, curr_view) + if len(base_args) == 0: + if len(other_args) != len(fwd_inputs): + raise AssertionError( + f"expected len(other_args) == len(fwd_inputs), " + f"got {len(other_args)} != {len(fwd_inputs)}" + ) + # If no synthetic bases are necessary, just return the original inputs. + return fwd_inputs, fwd_inputs_descs, None + else: + from torch.fx.experimental.symbolic_shapes import SymIntEqByExpr + + def make_hashable(arg: Any) -> Any: + if isinstance(arg, torch.SymInt): + # Since only nested SymInt objects can be hashed, we wrap them with + # SymIntEqByExpr, which is a hashable wrapper of SymInts. + return SymIntEqByExpr(arg) + return arg + + # Otherwise, return: + # (1) The new args according to the updated calling convention: (synthetic_bases, other_args) + # (2) Metadata telling functionalization how to generate the inner argument list given the outer calling convention. + # We post-process it into a list, where meta[i] tells you info about the i'th argument in the inner calling convention. + args_to_functionalization = base_args + other_args + args_to_functionalization_descs = base_args_descs + other_args_descs + + # Map each argument into its old index. + # There may be some repeated arguments, so we collect their indices in a list. + arg_to_old_idx_map = collections.defaultdict(list) + for i, arg in enumerate(fwd_inputs): + arg_to_old_idx_map[make_hashable(arg)].append(i) + # Reverse the list of each argument, so that we can easily pop them one-after-the-other in order. + for hashable_arg in arg_to_old_idx_map: + arg_to_old_idx_map[hashable_arg] = list( + reversed(arg_to_old_idx_map[hashable_arg]) + ) + + for i, other_arg in enumerate(other_args): + new_idx = len(base_args) + i + old_idx = arg_to_old_idx_map[make_hashable(other_arg)].pop() + inner_calling_convention_meta[old_idx] = new_idx + + # post process into a list + post_processed_calling_convention_meta: list[int | tuple[int, torch.Tensor]] = [ + -1 for _ in range(len(inner_calling_convention_meta)) + ] + for k, v in inner_calling_convention_meta.items(): + post_processed_calling_convention_meta[k] = v + # Quick assert: every argument in the inner calling convention should be accounted for. + for x in post_processed_calling_convention_meta: + if x == -1: + raise AssertionError( + "every argument in the inner calling convention should be accounted for" + ) + # pyrefly: ignore [bad-return] + return ( + args_to_functionalization, + args_to_functionalization_descs, + post_processed_calling_convention_meta, + ) + + +# Note: [Backward graph lazy lowering] +# After AOTDispatch traces the backward for graphs requiring autograd, we will lower the graph lazily, +# unless we suspect that inductor might specialize and insert additional guards. When we do lazy +# lowering, we stash the AOT backward graph (bw_module) in this class. +# +# Lowering passes are performed on a deepcopy of this bw_module due to compatibility +# with compiled autograd. See: https://github.com/pytorch/pytorch/pull/149229#discussion_r2002122645. +@dataclass +class AutogradLazyBackwardCompileInfo: + bw_module: Callable[..., Any] + placeholder_list: list[Any] + saved_context: TracingContext | None + saved_compile_context: CompileContext | None + + +# On an AOT Autograd cache hit, we already have a lowered backward, so there is usually +# no need to keep information around for a new lazy compilation. Except for compiled autograd, +# which wants to retrace this backward into a larger graph, and it needs the graph module to do so. +@dataclass +class CachedAutogradLazyBackwardCompileInfo: + bw_module_fn: Callable[..., Any] + + +def initialize_rng_states( + num_rng: int, + graphsafe_idx: int, + fwd_rng_states: list[torch.Generator], + bwd_rng_states: list[torch.Generator], + *, + device: torch.device, +) -> None: + """ + Initialize the graphsafe rng states. + + Initialization of rng states should have a few properties: + - the initialization for each rng state should be independent + - the initialization should be deterministic + - the initialization should be based off current rng state, so that independent graphs do not + have equal rng behavior + + We defer initialization of rng states until runtime because compilation is wrapped + with preserve_rng_states. Seed initialization should advance the rng states so consecutive compilations + do not give equal randomness. + """ + from .utils import get_default_generator + + with torch.utils._python_dispatch._disable_current_modes(): + seeds = torch.randint(0, torch.iinfo(torch.int64).max, (num_rng,), device="cpu") + generator = get_default_generator(device) + fwd_rng_states.extend( + [generator.clone_state().manual_seed(int(seeds[i])) for i in range(num_rng)] + ) + bwd_rng_states.extend( + [generator.clone_state().manual_seed(int(seeds[i])) for i in range(num_rng)] + ) + + +def coerce_to_expected_memory_format( + x: torch.Tensor, memory_format: MemoryFormatMeta +) -> torch.Tensor: + if memory_format.memory_format is not None: + # Coerce to torch.memory_format + if not x.is_contiguous(memory_format=memory_format.memory_format): + x = x.contiguous(memory_format=memory_format.memory_format) + return x + + expected_size = memory_format.size + if expected_size is None: + raise AssertionError("memory_format.size must not be None") + expected_stride = memory_format.stride + if expected_stride is None: + raise AssertionError("memory_format.stride must not be None") + # Expected size and stride are static ints + # ok to use == to compare runtime tensor strides and shapes + + if x.shape == expected_size and x.stride() == expected_stride: + # Runtime tangent size and stride are the same as expected, no need to coerce + return x + + # Empty_strided creates a raw Tensor. + # We are guaranteed that only raw Tensors has expected size and stride. + # Subclasses have only expected memory_format. + restrided = torch.empty_strided( + size=expected_size, + stride=expected_stride, + dtype=x.dtype, + device=x.device, + layout=x.layout, + requires_grad=x.requires_grad, + ) + restrided.copy_(x) + return restrided + + +@contextlib.contextmanager +def _disable_saved_tensors_hooks() -> Generator[None, None, None]: + error_message = ( + "Saved tensors hooks were specialized as GraphModules." + "In this case aot_autograd inlines them in forward and backward graph " + "and disables them during runtime of aot_autograd compiled region." + "If you see this error, that means that there is some unexpected push or pop manipulation " + "during aot_autograd compiled region runtime." + "Compilation with different hooks must result in recompilation." + ) + fail_if_non_empty = False + maybe_prev_message = None + try: + maybe_prev_message = ( + torch._C._autograd._saved_tensors_hooks_get_disabled_error_message() + ) + torch._C._autograd._saved_tensors_hooks_disable( + error_message, fail_if_non_empty + ) + yield + finally: + if maybe_prev_message is None: + torch._C._autograd._saved_tensors_hooks_enable() + else: + torch._C._autograd._saved_tensors_hooks_disable( + maybe_prev_message, fail_if_non_empty + ) + + +@dataclass +class SerializableCompiledFunction: + """ + Represents a result of AOTDispatch after calling the inner compiler + that can be serialized + """ + + compiled_fn: Callable[..., Any] + serialize_fn: Callable[[], Any] + + def __init__( + self, compiled_fn: Callable[..., Any], serialize_fn: Callable[[], Any] + ) -> None: + self.compiled_fn = compiled_fn + self.serialize_fn = serialize_fn + # Equivalent to functools.wraps + functools.update_wrapper( + self, + compiled_fn, + assigned=("__doc__", "__annotations__", "__type_params__"), + ) + + def serialize(self) -> Any: + return self.serialize_fn() + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self.compiled_fn(*args, **kwargs) + + +@dataclass +class AOTDispatchAutogradCompileSpec: + compiled_fw_func: Callable[..., Any] + compiled_bw_func: Callable[..., Any] | None + maybe_subclass_meta: SubclassMeta | None + num_symints_saved_for_bw: int + backward_state_indices: list[int] + disable_amp: bool + indices_of_inps_to_detach: list[int] + lazy_backward_info: ( + AutogradLazyBackwardCompileInfo | CachedAutogradLazyBackwardCompileInfo | None + ) + bw_compiler: Callable[..., Any] | None + aot_config: AOTConfig + fw_metadata: ViewAndMutationMeta + try_save_cache_entry: Callable[..., Any] | None + + +@dataclass +class _AutogradSavedState: + metadata: ViewAndMutationMeta + + def save_from_forward(self, ctx: Any, fw_outs: Sequence[Any]) -> None: + tensors_saved_with_vc_check = fw_outs[ + self.metadata.tensors_saved_for_backwards_with_vc_check_slice + ] + tensors_saved_no_vc_check = fw_outs[ + self.metadata.tensors_saved_for_backwards_no_vc_check_slice + ] + if not all(isinstance(x, torch.Tensor) for x in tensors_saved_with_vc_check): + raise AssertionError( + "expected all tensors_saved_with_vc_check to be Tensors, " + f"got types: {[type(x) for x in tensors_saved_with_vc_check]}" + ) + if not all(isinstance(x, torch.Tensor) for x in tensors_saved_no_vc_check): + raise AssertionError( + "expected all tensors_saved_no_vc_check to be Tensors, " + f"got types: {[type(x) for x in tensors_saved_no_vc_check]}" + ) + + # See Note [Detaching saved tensors in AOTAutograd] + num_vc_check = len(tensors_saved_with_vc_check) + is_graph_input = self.metadata.saved_tensor_is_graph_input + tensors_to_save = [ + x if is_graph_input[i] or not x._is_view() else x.detach() + for i, x in enumerate(tensors_saved_with_vc_check) + ] + tensors_no_vc_check = [ + x if is_graph_input[num_vc_check + i] or not x._is_view() else x.detach() + for i, x in enumerate(tensors_saved_no_vc_check) + ] + + # dynamic_saved_tensors_idxs has indices relative to all saved tensors + # (vc_check + no_vc_check combined). Mark dynamics on the detached tensors. + for idx, dims in self.metadata.dynamic_saved_tensors_idxs.items(): + if idx < num_vc_check: + mark_dynamo_propagated_dynamic_indices(tensors_to_save[idx], dims) + else: + mark_dynamo_propagated_dynamic_indices( + tensors_no_vc_check[idx - num_vc_check], dims + ) + + ctx.save_for_backward(*tensors_to_save) + ctx._tensors_no_vc_check = tensors_no_vc_check + + symint_outs = fw_outs[self.metadata.symints_saved_for_backwards_slice] + if not all( + isinstance(x, (int, float, torch.SymInt, torch.SymFloat)) + for x in symint_outs + ): + raise AssertionError( + "expected all symint_outs to be int/float/SymInt/SymFloat, " + f"got types: {[type(x) for x in symint_outs]}" + ) + ctx.symints = symint_outs + + opaque_object_outs = fw_outs[ + self.metadata.opaque_objects_saved_for_backwards_slice + ] + if not all( + is_custom_class(type(obj)) or isinstance(obj, CustomClassBase) + for obj in opaque_object_outs + ): + raise AssertionError( + "expected all opaque_object_outs to be opaque types, " + f"got types: {[type(obj) for obj in opaque_object_outs]}" + ) + ctx.opaque_objects = opaque_object_outs + + +@dataclass +class _AutogradForwardEpilogue: + metadata: ViewAndMutationMeta + + def finalize(self, ctx: Any, fw_outs: Sequence[Any]) -> tuple[Any, ...]: + num_outputs = self.metadata.num_outputs + num_outputs_aliased = self.metadata.num_outputs_aliased + num_mutated_runtime_inps = self.metadata.num_mutated_inp_runtime_indices + num_forward_returns = self.metadata.num_forward_returns + + raw_returns = list(fw_outs[:num_forward_returns]) + + # Wrap all autograd.Function.forward() outputs that are aliases + # so that autograd.Function doesn't treat them as tensors + if num_mutated_runtime_inps > 0: + for i, idx in enumerate(self.metadata.mutated_inp_runtime_indices): + # We could make this faster by only looping over inputs with metadata-only mutations + # (instead of looping over inputs with either data or metadata mutations), but there shouldn't be many. + info = self.metadata.input_info[idx] + if info.mutates_metadata and not info.mutates_data: + raw_returns[i] = TensorAlias(raw_returns[i]) + + if config.debug_assert: + user_mutated_inputs_raw = raw_returns[0:num_mutated_runtime_inps] + mut_inp_infos = [ + x + for x in self.metadata.input_info + if x.mutates_data or x.mutates_metadata + ] + if len(user_mutated_inputs_raw) != len(mut_inp_infos): + raise AssertionError( + "expected len(user_mutated_inputs_raw) == len(mut_inp_infos), " + f"got {len(user_mutated_inputs_raw)} != {len(mut_inp_infos)}" + ) + + if self.metadata.num_unsafe_view_outputs > 0: + for idx in self.metadata.unsafe_view_out_indices: + raw_return_idx = num_mutated_runtime_inps + idx + o = raw_returns[raw_return_idx] + raw_returns[raw_return_idx] = torch.ops.aten._unsafe_view(o, o.shape) + + if num_outputs_aliased > 0: + for idx in self.metadata.aliased_out_indices: + raw_return_idx = num_mutated_runtime_inps + idx + raw_returns[raw_return_idx] = TensorAlias(raw_returns[raw_return_idx]) + + if config.debug_assert: + intermediates_raw = raw_returns[ + num_mutated_runtime_inps + num_outputs : + ] + if any(isinstance(x, TensorAlias) for x in intermediates_raw): + raise AssertionError("expected no TensorAlias in intermediates_raw") + + # invariant: intermediate bases always require gradients, so we don't have to + # consider marking them as non-differentiable. + raw_returns_not_including_intermediate_bases = raw_returns[ + : num_mutated_runtime_inps + num_outputs + ] + raw_returns_meta = [ + x + for x in self.metadata.input_info + if x.mutation_type == MutationType.MUTATED_OUT_GRAPH + ] + self.metadata.output_info + + fw_outs_not_requiring_grad = [ + x + for (i, x) in enumerate(raw_returns_not_including_intermediate_bases) + if isinstance(x, torch.Tensor) and not raw_returns_meta[i].requires_grad + ] + ctx.mark_non_differentiable(*fw_outs_not_requiring_grad) + ctx._materialize_non_diff_grads = False + _snapshot_external_objects(ctx) + + return tuple(raw_returns) + + +@dataclass +class _AutogradRngStateTracker: + num_rng: int + graphsafe_idx: int | None + device: torch.device | None = None + fwd_rng_states: list[torch.Generator] = field(default_factory=list) + bwd_rng_states: list[torch.Generator] = field(default_factory=list) + curr_fwd_iter: Any = field(default_factory=lambda: itertools.count(0)) + backward_state_position: int = 0 + pending_forwards: set[int] = field(default_factory=set) + saved_backward_tensor_states: dict[int, list[torch.Tensor]] = field( + default_factory=dict + ) + + def add_forward_args(self, ctx: Any, args: tuple[Any, ...]) -> tuple[Any, ...]: + if self.num_rng == 0: + return args + + if len(self.fwd_rng_states) == 0: + if self.graphsafe_idx is None: + raise AssertionError("graphsafe_idx must not be None when num_rng > 0") + if self.device is None: + raise AssertionError("device must not be None when num_rng > 0") + initialize_rng_states( + self.num_rng, + self.graphsafe_idx, + self.fwd_rng_states, + self.bwd_rng_states, + device=self.device, + ) + + curr_iter = next(self.curr_fwd_iter) + ctx._curr_iter = curr_iter + + # if this state is not contained in the backward, + # we need to save it for when its backward pass happens + if curr_iter != self.backward_state_position: + self.saved_backward_tensor_states[curr_iter] = [ + rng_state.get_state() for rng_state in self.fwd_rng_states + ] + + self.pending_forwards.add(curr_iter) + return (*args, *self.fwd_rng_states) + + def add_backward_args(self, ctx: Any, all_args: list[Any]) -> None: + if self.num_rng == 0: + return + + curr_backward_iter = ctx._curr_iter + retain_graph = torch._C._autograd._get_current_graph_task_keep_graph() + + # Save current state if we have a pending forward that needs this state + # or this state may be needed again because of retain graph + if ( + self.backward_state_position in self.pending_forwards + and self.backward_state_position not in self.saved_backward_tensor_states + and (self.backward_state_position != curr_backward_iter or retain_graph) + ): + self.saved_backward_tensor_states[self.backward_state_position] = [ + rng_state.get_state() for rng_state in self.bwd_rng_states + ] + + # Restore saved states if needed + if curr_backward_iter in self.saved_backward_tensor_states: + if self.backward_state_position != curr_backward_iter: + for bwd_state, saved_state in zip( + self.bwd_rng_states, + self.saved_backward_tensor_states[curr_backward_iter], + ): + bwd_state.set_state(saved_state) + if not retain_graph: + del self.saved_backward_tensor_states[curr_backward_iter] + else: + if self.backward_state_position != curr_backward_iter: + raise AssertionError( + "expected backward_state_position == curr_backward_iter, " + f"got {self.backward_state_position} != {curr_backward_iter}" + ) + + self.backward_state_position = curr_backward_iter + 1 + if not retain_graph: + self.pending_forwards.remove(curr_backward_iter) + all_args.extend(self.bwd_rng_states) + + +@dataclass +class _AutogradBackwardCompiler: + compiled_bw: Callable[..., Any] | None + lazy_backward_info: ( + AutogradLazyBackwardCompileInfo | CachedAutogradLazyBackwardCompileInfo | None + ) + disable_amp: bool + bw_compiler: Callable[..., Any] | None + aot_config: AOTConfig + fw_metadata: ViewAndMutationMeta + try_save_cache_entry: Callable[..., Any] | None + + def get_or_compile(self, *, saved_tensors_use_once: bool) -> Callable[..., Any]: + if self.compiled_bw is not None: + return self.compiled_bw + + if self.lazy_backward_info is None: + raise AssertionError("lazy_backward_info must not be None") + if not isinstance(self.lazy_backward_info, AutogradLazyBackwardCompileInfo): + raise AssertionError( + "expected AutogradLazyBackwardCompileInfo, " + f"got {type(self.lazy_backward_info)}" + ) + + self._prepare_lazy_backward_context(saved_tensors_use_once) + + bw_module = self.lazy_backward_info.bw_module + placeholder_list = self.lazy_backward_info.placeholder_list + saved_context = self.lazy_backward_info.saved_context + saved_compile_context = self.lazy_backward_info.saved_compile_context + + context = torch._C._DisableAutocast if self.disable_amp else nullcontext + metrics_context = get_metrics_context() + with ( + tracing(saved_context), + compile_context(saved_compile_context), + context(), + track_graph_compiling(self.aot_config, "backward"), + metrics_context, + dynamo_timed( + "backward._backward_impl", + phase_name="entire_backward_compile", + log_pt2_compile_event=True, + dynamo_compile_column_us="backward_cumulative_compile_time_us", + log_waitcounter=True, + waitcounter_name_override="entire_backward_compile", + ), + callback_handler.install_callbacks( + CallbackTrigger.LAZY_BACKWARD, + str(CompileContext.current_compile_id()), + ), + ): + CompileEventLogger.compilation_metric(is_forward=False) + # See Note: [Backward graph lazy lowering] + if self.bw_compiler is None: + raise AssertionError("bw_compiler must not be None") + self.compiled_bw = self.bw_compiler( + copy.deepcopy(bw_module), placeholder_list + ) + # Maybe save cache entry + if self.try_save_cache_entry is not None: + self.try_save_cache_entry( + self.compiled_bw, + bw_module, + self.fw_metadata, + self.aot_config, + ) + + return self.compiled_bw + + def _prepare_lazy_backward_context(self, saved_tensors_use_once: bool) -> None: + if self.lazy_backward_info is None: + raise AssertionError("lazy_backward_info must not be None") + if not isinstance(self.lazy_backward_info, AutogradLazyBackwardCompileInfo): + raise AssertionError( + "expected AutogradLazyBackwardCompileInfo, " + f"got {type(self.lazy_backward_info)}" + ) + + if ( + hasattr(self.lazy_backward_info, "saved_context") + and self.lazy_backward_info.saved_context is not None + ): + if not isinstance(self.lazy_backward_info.saved_context, TracingContext): + raise AssertionError( + f"expected TracingContext, got {type(self.lazy_backward_info.saved_context)}" + ) + ddp_ctx = self.lazy_backward_info.saved_context.ddp_optimizer_ctx + if ddp_ctx is not None: + if ddp_ctx.curr_bucket < 0: + raise AssertionError( + "expected same # of fw and bw compiles, " + f"but found bucket {ddp_ctx.curr_bucket}" + ) + curr_fw_meta = ddp_ctx.metadata_per_bucket[ddp_ctx.curr_bucket] + # Note [DDPOptimizer and fw_metadata] + # When using the DDPOptimizer, we have a single dynamo graph (and TracingContext), + # but multiple AOTDispatcher graph. + # + # One consequence is that there will be **multiple** fw_metadata objects, one per AOT graph, + # which we stash the fw_metadata on the TracingContext. + # + # Normally what happens is that as we compile AOT graphs 1...N, we clobber the fw_metadata + # for graph i-1 when we start running AOT for graph i. + # Ordinarily this is fine, because inductor no longer needs the metadata from graph i-1. + # + # However, this is a problem for lazy compilation of the backward. During backward compilation, + # we compile the backward lazily at backward runtime, meaning that we will first compile + # backward graph N, N-1, ..., 1. + # We need to ensure that at the time inductor compiles bw graph N-1, it can access + # the corresponding fw_metadata for graph N-1. + # + # We do this by stashing a DDPOptimizerContext, which tracks: + # - the metadata of all N graphs + # - the graph we are currently compiling in our DDPOptimizer region. + ddp_ctx.curr_bucket -= 1 + self.lazy_backward_info.saved_context.fw_metadata = curr_fw_meta + + if not saved_tensors_use_once: + self.fw_metadata.bw_donated_idxs = [] + # Update bw_donated_idxs if using lazy_backward_info from `aot_dispatch_autograd` + if ( + hasattr(self.lazy_backward_info, "saved_context") + and hasattr(self.lazy_backward_info.saved_context, "fw_metadata") + and hasattr( + self.lazy_backward_info.saved_context.fw_metadata, # type: ignore[union-attr] + "bw_donated_idxs", + ) + ): + self.lazy_backward_info.saved_context.fw_metadata.bw_donated_idxs = ( # type: ignore[union-attr] + # pyrefly: ignore [implicit-any] + [] + ) + + +def _codegen_backward_prologue( + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: SubclassMeta | None, + codegen_unwrap_fn: Callable[..., Any] | None, +) -> Callable[..., Any]: + from .codegen import PySourceBuilder + + num_mutated_runtime_inps = fw_metadata.num_mutated_inp_runtime_indices + num_outputs = fw_metadata.num_outputs + num_intermediate_bases = fw_metadata.num_intermediate_bases + expected_grad_outs = num_outputs + num_mutated_runtime_inps + num_intermediate_bases + deterministic = fw_metadata.deterministic + num_backward_tokens = fw_metadata.num_backward_tokens + is_rng_op_functionalized = fw_metadata.is_rng_op_functionalized + has_subclass = maybe_subclass_meta is not None + has_mutations_in_bw = bool( + fw_metadata.indices_of_inputs_that_requires_grad_with_mutations_in_bw + ) + input_info = fw_metadata.input_info + + inp_surviving: list[int] = [] + for i, info_idx in enumerate(fw_metadata.mutated_inp_runtime_indices): + if input_info[info_idx].mutates_data and input_info[info_idx].requires_grad: + inp_surviving.append(i) + + out_surviving: list[int] = [] + for i, info in enumerate(fw_metadata.output_info): + if ( + info.output_type + in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + and issubclass(info.raw_type, torch.Tensor) + and info.requires_grad_for_backward + ): + out_surviving.append(num_mutated_runtime_inps + i) + + intermediate_start = num_mutated_runtime_inps + num_outputs + all_surviving = ( + inp_surviving + + out_surviving + + list(range(intermediate_start, expected_grad_outs)) + ) + num_flat_bw_args_with_grads = len(all_surviving) + + buf = PySourceBuilder( + "_backward_prologue", + args="ctx_saved_tensors, ctx_symints, ctx_opaque_objects, flat_args", + artifact_name="backward_prologue", + ) + buf.bind(torch=torch) + + with buf.indent(): + buf.writeline("stack = torch._C._functorch.peek_interpreter_stack()") + buf.writeline( + "torch._check(stack is None, lambda: (" + "\"It looks like you're trying to call a compiled backward " + 'function within vmap/grad/vjp, "' + " \"which isn't supported. Try wrapping vmap inside " + 'torch.compile, or skip compiling the "' + ' "backward function."),)' + ) + + if deterministic is not None and not deterministic: + buf.writeline("_gd = torch.are_deterministic_algorithms_enabled()") + buf.writeline( + "torch._check(not _gd, lambda: (" + "'This compiled backward function is being run with '" + " 'torch.use_deterministic_algorithms(True), '" + " 'but it was previously generated during the forward function" + " while '" + " 'torch.use_deterministic_algorithms(False) was set.'))" + ) + + buf.writeline(f"if len(flat_args) != {expected_grad_outs}:") + with buf.indent(): + buf.writeline( + f"raise AssertionError(" + f"f'expected {expected_grad_outs} grad_outs, " + f"got {{len(flat_args)}}')" + ) + + if all_surviving: + items = ", ".join(f"flat_args[{i}]" for i in all_surviving) + buf.writeline(f"_bw_grads = [{items}]") + else: + buf.writeline("_bw_grads = []") + + buf.writeline("if isinstance(flat_args, list):") + with buf.indent(): + buf.writeline("flat_args.clear()") + + buf.writeline("_n_saved = len(ctx_saved_tensors)") + + parts = [ + "*ctx_symints", + "*ctx_saved_tensors", + "*ctx_opaque_objects", + "*_bw_grads", + ] + if num_backward_tokens > 0: + parts.append(f"*([None] * {num_backward_tokens})") + if is_rng_op_functionalized: + buf.bind(_get_rng_state_=CUDARngStateHelper.get_torch_state_as_tuple) + parts.append("*_get_rng_state_()") + buf.writeline(f"all_args = [{', '.join(parts)}]") + buf.writeline("del ctx_saved_tensors") + + buf.writeline("_ts = len(ctx_symints) + _n_saved + len(ctx_opaque_objects)") + buf.writeline(f"_te = _ts + {num_flat_bw_args_with_grads}") + + buf.bind( + _process_tangent_=AOTDispatchAutograd.process_runtime_tangent, + _tangent_metas_=fw_metadata.subclass_tangent_meta, + _tangent_descs_=fw_metadata.traced_tangents_descs, + _compile_id_=fw_metadata.compile_id_str, + _stack_traces_=fw_metadata.tangent_source_stack_traces or (), + ) + + if has_subclass: + buf.bind(_chain_=itertools.chain.from_iterable) + + buf.writeline("_tangents = all_args[_ts:_te]") + buf.writeline( + f"if len(_tangents) != {len(fw_metadata.subclass_tangent_meta)}:" + ) + with buf.indent(): + buf.writeline( + "raise RuntimeError(" + "'The grad inputs should be same number as forward output tangents')" + ) + buf.writeline( + "_fpt = list(_chain_(" + "_process_tangent_(t, m, idx, desc, _compile_id_, " + "_stack_traces_[idx] if _stack_traces_ else None)[1] " + "for idx, (t, m, desc) in enumerate(" + "zip(_tangents, _tangent_metas_, _tangent_descs_))))" + ) + + if codegen_unwrap_fn is not None: + buf.bind(_unwrap_=codegen_unwrap_fn) + else: + buf.bind(_unwrap_=_unwrap_no_symints) + buf.writeline( + "all_args = _unwrap_(all_args[:_ts]) + _fpt + _unwrap_(all_args[_te:])" + ) + elif num_flat_bw_args_with_grads > 0: + buf.writeline(f"for j in range({num_flat_bw_args_with_grads}):") + with buf.indent(): + buf.writeline("_i = _ts + j") + buf.writeline( + "all_args[_i] = _process_tangent_(all_args[_i], " + "_tangent_metas_[j], j, _tangent_descs_[j], _compile_id_, " + "_stack_traces_[j] if _stack_traces_ else None)[0]" + ) + + if has_mutations_in_bw: + buf.writeline("if torch.is_grad_enabled():") + with buf.indent(): + buf.writeline( + "raise RuntimeError(" + "'aot_autograd does not support input mutations with " + "requires_grad in backward for create_graph=True')" + ) + + buf.writeline("return all_args") + + return buf.build() + + +def _codegen_backward_epilogue( + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: SubclassMeta | None, + codegen_wrap_fn: Callable[..., Any] | None, +) -> Callable[..., Any]: + from .codegen import PySourceBuilder + + num_bw_tokens = fw_metadata.num_backward_tokens + is_rng = fw_metadata.is_rng_op_functionalized + has_subclass = maybe_subclass_meta is not None + + if has_subclass: + args = "out, make_subclass_override=None" + else: + args = "out" + buf = PySourceBuilder( + "_backward_epilogue", args=args, artifact_name="backward_epilogue" + ) + + with buf.indent(): + if num_bw_tokens > 0: + buf.writeline(f"out = out[:-{num_bw_tokens}]") + + if is_rng: + if fw_metadata.num_outputs_rng_offset != 1: + raise AssertionError( + f"expected num_outputs_rng_offset == 1, got {fw_metadata.num_outputs_rng_offset}" + ) + buf.bind(_set_offset_=CUDARngStateHelper.set_new_offset) + buf.writeline("_oi = len(out) - 1") + buf.writeline("_set_offset_(out[_oi])") + buf.writeline("out = out[:_oi] + out[_oi + 1:]") + + buf.writeline("out = tuple(out)") + + if has_subclass: + buf.bind(_wrap_subclasses_=wrap_tensor_subclasses) + if ( + maybe_subclass_meta.grad_input_metas is None + ): # pyrefly: ignore [missing-attribute] + raise AssertionError("grad_input_metas must not be None") + buf.bind( + _grad_input_metas_=maybe_subclass_meta.grad_input_metas + ) # pyrefly: ignore [missing-attribute] + if codegen_wrap_fn is not None: + buf.bind(_wrap_=codegen_wrap_fn) + buf.writeline("if make_subclass_override is None:") + with buf.indent(): + buf.writeline("return _wrap_(out)") + buf.writeline( + "return _wrap_subclasses_(out, " + "subclass_metas=_grad_input_metas_, " + "included_subclass_symints=True, is_runtime=True, " + "make_subclass_override=make_subclass_override)" + ) + else: + buf.writeline("return out") + + return buf.build() + + +def _codegen_compiled_forward( + fw_metadata: ViewAndMutationMeta, + backward_state_indices: list[int], + disable_amp: bool, + num_rng: int, +) -> Callable[..., Any]: + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_compiled_forward", + args="ctx, args, _rng_add_, _save_, _finalize_, _compiled_fw_", + artifact_name="compiled_function_forward", + ) + buf.bind(torch=torch, BackwardState=BackwardState) + + with buf.indent(): + if backward_state_indices: + idx = backward_state_indices[0] + buf.writeline(f"_bw_state = args[{idx}]") + buf.writeline("if not isinstance(_bw_state, BackwardState):") + with buf.indent(): + buf.writeline( + "raise AssertionError(" + "f'expected BackwardState, got {type(_bw_state)}')" + ) + buf.writeline("ctx._compiled_autograd_backward_state = _bw_state") + + if num_rng > 0: + buf.writeline("args = _rng_add_(ctx, args)") + + if disable_amp: + buf.bind(_DisableAutocast_=torch._C._DisableAutocast) + buf.writeline("with _DisableAutocast_():") + with buf.indent(): + buf.writeline("fw_outs = _compiled_fw_(list(args))") + _codegen_normalize_as_list(buf, "fw_outs", indent_level=2) + else: + buf.writeline("fw_outs = _compiled_fw_(list(args))") + _codegen_normalize_as_list(buf, "fw_outs", indent_level=1) + + buf.writeline("_save_(ctx, fw_outs)") + buf.writeline("return _finalize_(ctx, fw_outs)") + + return buf.build() + + +def _codegen_compiled_backward( + num_rng: int, + num_tensors_no_vc_check: int | None, + inputs_require_grad: bool, +) -> Callable[..., Any]: + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_compiled_backward", + args="_flat_args_, _ctx_, _prologue_," + " _rng_add_, _impl_, _epilogue_, _double_bw_", + artifact_name="compiled_function_backward", + ) + buf.bind(torch=torch, functools=functools) + + with buf.indent(): + buf.writeline( + "if len(_flat_args_) != 1 or not isinstance(_flat_args_[0], list):" + ) + with buf.indent(): + buf.writeline( + "raise AssertionError(" + "'Compiled backward expects grads as a single mutable list '" + " f'argument, but got {len(_flat_args_)} args. '" + " 'Grads must be passed as [grad0, grad1, ...] to allow '" + " 'freeing individual grads mid-backward.')" + ) + buf.writeline("grad_args = _flat_args_[0]") + buf.writeline("del _flat_args_") + + if num_tensors_no_vc_check is not None and num_tensors_no_vc_check > 0: + buf.writeline( + "_saved = (*_ctx_.saved_tensors, *_ctx_._tensors_no_vc_check)" + ) + else: + buf.writeline("_saved = _ctx_.saved_tensors") + + buf.writeline( + "all_args = _prologue_(_saved, _ctx_.symints," + " _ctx_.opaque_objects, grad_args)" + ) + buf.writeline("del _saved") + + if num_rng > 0: + buf.writeline("_rng_add_(_ctx_, all_args)") + + buf.writeline("def impl_fn(double_ctx=None):") + with buf.indent(): + buf.writeline("out = _impl_(_ctx_, all_args)") + buf.writeline("return _epilogue_(out)") + + buf.writeline( + "if (torch._C._is_key_in_tls('context')" + " and (_cc := torch._C._get_obj_in_tls('context')) is not None):" + ) + with buf.indent(): + buf.writeline("impl_fn = functools.partial(_cc.copy().run, impl_fn)") + + if inputs_require_grad: + buf.writeline("if torch.is_grad_enabled():") + else: + buf.writeline( + "_ng = torch.is_grad_enabled() and any(" + "t.requires_grad for t in all_args if isinstance(t, torch.Tensor))" + ) + buf.writeline("if _ng:") + with buf.indent(): + buf.writeline("return _double_bw_(_ctx_, impl_fn, all_args)") + buf.writeline("return impl_fn()") + + return buf.build() + + +@dataclass +class _AOTDispatchAutogradFunctionFactory: + spec: AOTDispatchAutogradCompileSpec + + def build(self) -> type[torch.autograd.Function]: + compile_id = CompileContext.current_compile_id() + compile_id_str = str(compile_id) if compile_id is not None else None + self.spec.fw_metadata.compile_id_str = compile_id_str + + saved_state = _AutogradSavedState(self.spec.fw_metadata) + forward_epilogue = _AutogradForwardEpilogue(self.spec.fw_metadata) + rng_state = _AutogradRngStateTracker( + num_rng=self.spec.fw_metadata.num_graphsafe_rng_states, + graphsafe_idx=self.spec.fw_metadata.graphsafe_rng_state_index, + device=self.spec.fw_metadata.graphsafe_rng_device, + ) + backward_compiler = _AutogradBackwardCompiler( + compiled_bw=self.spec.compiled_bw_func, + lazy_backward_info=self.spec.lazy_backward_info, + disable_amp=self.spec.disable_amp, + bw_compiler=self.spec.bw_compiler, + aot_config=self.spec.aot_config, + fw_metadata=self.spec.fw_metadata, + try_save_cache_entry=self.spec.try_save_cache_entry, + ) + + compiled_fw_func = self.spec.compiled_fw_func + compiled_bw_func = self.spec.compiled_bw_func + maybe_subclass_meta = self.spec.maybe_subclass_meta + num_symints_saved_for_bw_ = self.spec.num_symints_saved_for_bw + backward_state_indices = self.spec.backward_state_indices + disable_amp = self.spec.disable_amp + lazy_backward_info = self.spec.lazy_backward_info + aot_config = self.spec.aot_config + fw_metadata = self.spec.fw_metadata + + _codegen_bw_unwrap_fn = None + _codegen_bw_wrap_fn = None + if maybe_subclass_meta is not None: + from .subclass_codegen import codegen_backward_subclass_fns + + _codegen_bw_unwrap_fn, _codegen_bw_wrap_fn = codegen_backward_subclass_fns( + grad_input_metas=maybe_subclass_meta.grad_input_metas, + ) + + _codegen_bw_prologue = _codegen_backward_prologue( + fw_metadata, + maybe_subclass_meta, + _codegen_bw_unwrap_fn, + ) + + _codegen_bw_epilogue = _codegen_backward_epilogue( + fw_metadata, + maybe_subclass_meta, + _codegen_bw_wrap_fn, + ) + + _codegen_fwd = _codegen_compiled_forward( + fw_metadata, + backward_state_indices, + disable_amp, + rng_state.num_rng, + ) + + _codegen_bwd = _codegen_compiled_backward( + rng_state.num_rng, + fw_metadata.num_tensors_saved_with_no_vc_check, + any(inp.requires_grad for inp in fw_metadata.input_info), + ) + + # Codegen for CompiledFunction.forward: emit straight-line TensorAlias + # wrapping, _unsafe_view, and non-differentiable output collection with + # all indices resolved at compile time. + num_mutated_runtime_inps = fw_metadata.num_mutated_inp_runtime_indices + num_outputs = fw_metadata.num_outputs + num_outputs_aliased = fw_metadata.num_outputs_aliased + + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_transform_raw_returns", + args="raw_returns", + artifact_name="compiled_fn_wrapper", + ) + buf.bind(TensorAlias=TensorAlias, torch=torch, Tensor=Tensor) + + with buf.indent(): + for i, idx in enumerate(fw_metadata.mutated_inp_runtime_indices): + info = fw_metadata.input_info[idx] + if info.mutates_metadata and not info.mutates_data: + buf.writeline(f"raw_returns[{i}] = TensorAlias(raw_returns[{i}])") + + if fw_metadata.num_unsafe_view_outputs > 0: + for idx in fw_metadata.unsafe_view_out_indices: + ri = num_mutated_runtime_inps + idx + buf.writeline(f"_o = raw_returns[{ri}]") + buf.writeline( + f"raw_returns[{ri}] = torch.ops.aten._unsafe_view(_o, _o.shape)" + ) + + if num_outputs_aliased > 0: + for idx in fw_metadata.aliased_out_indices: + ri = num_mutated_runtime_inps + idx + buf.writeline(f"raw_returns[{ri}] = TensorAlias(raw_returns[{ri}])") + + # Non-differentiable output collection: build a list of specific indices + # at compile time rather than iterating at runtime. + _non_diff_indices: list[int] = [] + _returns_meta = [ + x + for x in fw_metadata.input_info + if x.mutation_type == MutationType.MUTATED_OUT_GRAPH + ] + list(fw_metadata.output_info) + for i, meta in enumerate(_returns_meta): + if ( + i < num_mutated_runtime_inps + num_outputs + and not meta.requires_grad + ): + _non_diff_indices.append(i) + if _non_diff_indices: + checks = " + ".join( + f"([raw_returns[{i}]] if isinstance(raw_returns[{i}], Tensor) else [])" + for i in _non_diff_indices + ) + buf.writeline(f"non_diff = {checks}") + else: + buf.writeline("non_diff = []") + buf.writeline("return non_diff") + + _codegen_transform_raw_returns: Callable[..., list[Any]] = buf.build() # type: ignore[assignment] + + # Monkey-patch forward_epilogue.finalize to use codegen'd transform + def _codegen_finalize(ctx: Any, fw_outs: Any) -> tuple[Any, ...]: + num_forward_returns = fw_metadata.num_forward_returns + raw_returns = list(fw_outs[:num_forward_returns]) + fw_outs_not_requiring_grad = _codegen_transform_raw_returns(raw_returns) + if config.debug_assert: + if num_mutated_runtime_inps > 0: + user_mutated_inputs_raw = raw_returns[0:num_mutated_runtime_inps] + mut_inp_infos = [ + x + for x in fw_metadata.input_info + if x.mutates_data or x.mutates_metadata + ] + if len(user_mutated_inputs_raw) != len(mut_inp_infos): + raise AssertionError( + f"expected len(user_mutated_inputs_raw) == len(mut_inp_infos), " + f"got {len(user_mutated_inputs_raw)} != {len(mut_inp_infos)}" + ) + if num_outputs_aliased > 0: + intermediates_raw = raw_returns[ + num_mutated_runtime_inps + num_outputs : + ] + if any(isinstance(x, TensorAlias) for x in intermediates_raw): + raise AssertionError( + "expected no TensorAlias in intermediates_raw" + ) + ctx.mark_non_differentiable(*fw_outs_not_requiring_grad) + ctx._materialize_non_diff_grads = False + _snapshot_external_objects(ctx) + + return tuple(raw_returns) + + forward_epilogue.finalize = _codegen_finalize # type: ignore[method-assign] + + class CompiledFunction(torch.autograd.Function): + compiled_fw = compiled_fw_func + compiled_bw = compiled_bw_func + metadata: ViewAndMutationMeta = fw_metadata # type: ignore[assignment] + maybe_subclass_metadata: SubclassMeta | None = maybe_subclass_meta + num_symints_saved_for_bw = num_symints_saved_for_bw_ + _aot_id = aot_config.aot_id + _lazy_backward_info = lazy_backward_info + _bw_prologue_fn = _codegen_bw_prologue + _bw_epilogue_fn = _codegen_bw_epilogue + _fwd_fn = _codegen_fwd + _bwd_fn = _codegen_bwd + boxed_grads_call = True + + @staticmethod + def _compiled_autograd_key(ctx: Any) -> tuple[Any, ...]: + return (ctx._autograd_function_id, *ctx.symints) + + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx: Any, *deduped_flat_tensor_args: Any) -> Any: + return CompiledFunction._fwd_fn( + ctx, + deduped_flat_tensor_args, + rng_state.add_forward_args, + saved_state.save_from_forward, + forward_epilogue.finalize, + CompiledFunction.compiled_fw, + ) + + @staticmethod + def backward(ctx: Any, *flat_args: Any) -> tuple[Any, ...]: + return CompiledFunction._bwd_fn( + flat_args, + ctx, + CompiledFunction._bw_prologue_fn, + rng_state.add_backward_args, + CompiledFunction._backward_impl, + CompiledFunction._bw_epilogue_fn, + CompiledFunction._double_backward, + ) + + @staticmethod + def _double_backward( + ctx: Any, impl_fn: Callable[..., Any], all_args: list[Any] + ) -> Any: + # Ensure that the graph is connected, and error if double backward is performed. + # See comment for why once_differentiable is not sufficient: + # https://github.com/pytorch/pytorch/pull/92348/files#r1072962107 + class CompiledFunctionBackward(torch.autograd.Function): + # CompiledFunctionBackward is not yet supported in dynamo skipfiles + _aot_id = aot_config.aot_id + + @staticmethod + # pyrefly: ignore [bad-override] + def forward(double_ctx: Any, *unused_args: Any) -> Any: + return impl_fn(double_ctx) + + @staticmethod + def backward(ctx: Any, *args: Any) -> None: + raise RuntimeError( + "torch.compile with aot_autograd does not currently support double backward" + ) + + CompiledFunctionBackward._compiled_autograd_key = ( # type: ignore[method-assign] + CompiledFunction._compiled_autograd_key + ) + + # Saved tensors are detached (forward runs under no-grad), so no + # real arg requires grad. Prepend a dummy requires_grad=True + # input so CompiledFunctionBackward.apply attaches a grad_fn and + # gradient outputs report requires_grad=True for create_graph=True. + if not any( + t.requires_grad for t in all_args if isinstance(t, torch.Tensor) + ): + all_args = [torch.empty(0, requires_grad=True)] + all_args + return CompiledFunctionBackward.apply(*all_args) + + @staticmethod + def _backward_impl(ctx: Any, all_args: list[Any]) -> Any: + # compiled autograd reimplements this function at proxy_call_aot_backward + if backward_state_indices: + raise AssertionError("BackwardState requires CompiledAutograd") + ctx.maybe_clear_saved_tensors() + + saved_tensors_use_once = ( + not torch._C._autograd._get_current_graph_task_keep_graph() + ) + compiled_bw = backward_compiler.get_or_compile( + saved_tensors_use_once=saved_tensors_use_once + ) + CompiledFunction.compiled_bw = compiled_bw + + if ( + torch._functorch.config.donated_buffer + and not saved_tensors_use_once + and fw_metadata.bw_donated_idxs != [] + ): + torch._check( + False, + lambda: ( + "This backward function was compiled with non-empty donated " + "buffers which requires create_graph=False and retain_graph=False. " + "Please keep backward(create_graph=False, retain_graph=False) " + "across all backward() function calls, or set " + "torch._functorch.config.donated_buffer=False to disable " + "donated buffer." + ), + ) + + for idx, obj in getattr(ctx, "_external_objects", {}).items(): + index_to_external_object_weakref[idx] = weakref.ref(obj) + + return call_func_at_runtime_with_args( + compiled_bw, + all_args, + steal_args=True, + disable_amp=disable_amp, + ) + + return CompiledFunction + + +# This is wrapped in a class just for namespacing purposes +# No need to make it into an actual CompilerWrapper because it doesn't fit the abstract as cleanly +class AOTDispatchAutograd: + @staticmethod + def _raise_tangent_metadata_error( + expected_type: type | None, + expected_meta: Any, + runtime_type: type, + runtime_meta: Any, + orig_x: torch.Tensor, + tangent_idx: int | None, + tangent_desc: Any | None, + compile_id_str: str | None, + tangent_stack_trace: str | None, + ) -> RuntimeError: + expected_subclass_got_plain_tensor = ( + expected_type is not None + and expected_type is not torch.Tensor + and runtime_type is torch.Tensor + ) + if expected_subclass_got_plain_tensor: + tangent_msg = "" + if tangent_idx is not None: + tangent_msg = f" (tangent index: {tangent_idx})" + + output_hint = "" + if tangent_desc is not None: + from .descriptors import PlainAOTOutput, TangentAOTInput + + if isinstance(tangent_desc, TangentAOTInput) and isinstance( + tangent_desc.output, PlainAOTOutput + ): + idx = tangent_desc.output.idx + output_hint = f"\n\nThe problematic output is: forward output at index {idx} (0-indexed)" + else: + output_hint = ( + f"\n\nThe problematic output is: {tangent_desc.expr()}" + ) + + graph_hint = "" + if compile_id_str is not None: + graph_hint = ( + f"\n\nThis error occurred in compiled graph [{compile_id_str}]." + ) + + stack_trace_hint = "" + if tangent_stack_trace is not None: + stack_trace_hint = ( + f"\n\nThe forward output was created here:\n{tangent_stack_trace}" + ) + + return RuntimeError( + f""" +During the backward, we encountered a tensor subclass where we guessed its +metadata incorrectly. +Expected a {expected_type.__name__} tangent but got a plain Tensor{tangent_msg}. +This happens when a compiled function returns multiple outputs that +require gradients, but .backward() is only called on some of them. +To fix: call .detach() on forward outputs you don't need gradients for.{output_hint}{graph_hint}{stack_trace_hint} + +This error is also more likely to occur if your compiled model is suffering +from a large number of graph breaks. For more advice on finding and fixing +graph breaks, see: +https://docs.pytorch.org/docs/stable/user_guide/torch_compiler/compile/programming_model.graph_breaks_index.html + +For more info about this error, see: +https://github.com/pytorch/pytorch/issues/172556""" + ) + else: + return RuntimeError( + f""" +During the backward, we encountered a tensor subclass where we guessed its +metadata incorrectly. +Expected: {expected_meta} (type {expected_type}), +got: {runtime_meta} (type {runtime_type}), shape: {orig_x.shape}. +Your tensor subclass must implement __coerce_same_metadata_as_tangent__.""" + ) + + @staticmethod + def process_runtime_tangent( + x: Any, + meta: PlainTensorMeta | SubclassCreationMeta, + tangent_idx: int | None = None, + tangent_desc: Any | None = None, + compile_id_str: str | None = None, + tangent_stack_trace: str | None = None, + ) -> tuple[Any, list[Any]]: + if not isinstance(x, torch.Tensor): + return x, [x] + + if is_fake_tensor(x): + if not meta.memory_format: + raise AssertionError( + "meta.memory_format must not be None for FakeTensor" + ) + x = coerce_to_expected_memory_format(x, meta.memory_format) + return x, [x] + + expected_type: type | None = torch.Tensor + expected_meta = None + if isinstance(meta, SubclassCreationMeta): + expected_type = meta.original_subclass_type + expected_meta = meta.meta + + runtime_type = type(x) + # When we're inside compiled autograd's AOTDispatcher step, + # regular Tensors look like FunctionalTensors. + # Tensor subclasses still look like Tensor subclasses though. + if isinstance(x, torch._subclasses.functional_tensor.FunctionalTensor): + runtime_type = torch.Tensor + + runtime_meta = None + runtime_subclass_keys: Sequence[str] = [] + + if is_traceable_wrapper_subclass(x): + runtime_subclass_keys, runtime_meta = x.__tensor_flatten__() + + def maybe_coerce(x: torch.Tensor) -> torch.Tensor | None: + same_type: bool = expected_type == runtime_type + same_meta: bool = expected_meta == runtime_meta + + if same_type and same_meta: + return x + + if not hasattr(x, "__coerce_same_metadata_as_tangent__"): + return None + + if same_type: + # Backward Compatibility, as some Subclass impls can have original 1-arg function. + return x.__coerce_same_metadata_as_tangent__(expected_meta) + + return x.__coerce_same_metadata_as_tangent__(expected_meta, expected_type) + + # Coerce to expected type and metadata + orig_x = x + x = maybe_coerce(x) + if x is None: + raise AOTDispatchAutograd._raise_tangent_metadata_error( + expected_type, + expected_meta, + runtime_type, + runtime_meta, + orig_x, + tangent_idx, + tangent_desc, + compile_id_str, + tangent_stack_trace, + ) + + # Coerce to expected memory format + if not meta.memory_format: + raise AssertionError("meta.memory_format must not be None") + x = coerce_to_expected_memory_format(x, meta.memory_format) + + if not is_traceable_wrapper_subclass(x): + return x, [x] + + if not isinstance(meta, SubclassCreationMeta): + raise AssertionError(f"expected SubclassCreationMeta, got {type(meta)}") + if orig_x is not x: + runtime_subclass_keys = x.__tensor_flatten__()[0] + + if len(meta.attrs) != len(runtime_subclass_keys): + raise AssertionError( + f"expected len(meta.attrs) == len(runtime_subclass_keys), " + f"got {len(meta.attrs)} != {len(runtime_subclass_keys)}" + ) + leaves = [] + for attr, attr_meta in meta.attrs.items(): + if isinstance(attr_meta, OpaqueMeta): + # Opaques aren't differentiable but occupy a flat arg slot. + leaves.append(getattr(x, attr)) + continue + elem = getattr(x, attr) + new_elem, elem_leaves = AOTDispatchAutograd.process_runtime_tangent( + elem, attr_meta + ) + if new_elem is not elem: + setattr(x, attr, new_elem) + leaves.extend(elem_leaves) + + return x, leaves + + @staticmethod + def post_compile(spec: AOTDispatchAutogradCompileSpec) -> Callable[..., Any]: + compiled_function_cls = _AOTDispatchAutogradFunctionFactory(spec).build() + return RuntimeWrapper( + indices_of_inps_to_detach=spec.indices_of_inps_to_detach, + trace_joint=True, + disable_amp=spec.disable_amp, + ).post_compile( + compiled_function_cls.apply, + spec.aot_config, + runtime_metadata=spec.fw_metadata, + ) + + +@dataclass +class DebugAssertWrapper(CompilerWrapper): + flat_requires_grad: list[bool | None] = field(default_factory=list) + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "inner_fn", args="args", artifact_name="debug_assert_wrapper" + ) + buf.bind(compiled_fn=compiled_fn) + with buf.indent(): + for i, can_require_grad in enumerate(self.flat_requires_grad): + if can_require_grad is None: + buf.writeline( + f"if isinstance(args[{i}], Tensor):" + f" raise AssertionError(" + f"'expected non-Tensor for arg {i}, got Tensor')" + ) + elif not can_require_grad: + msg_name = buf.bind_value( + "_msg", + format_guard_bug_msg( + aot_config, + f"{describe_input(i, aot_config)} would not require grad", + ), + ) + buf.writeline( + f"if args[{i}].requires_grad: raise AssertionError({msg_name})" + ) + buf.writeline("return compiled_fn(args)") + + buf.bind(Tensor=Tensor) + + return buf.build(wrapped_fn=compiled_fn) + + +def pre_compile( + wrappers: list[CompilerWrapper], + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, +) -> tuple[TraceFn, list[FxValue], list[AOTInput], ViewAndMutationMeta]: + """ + Runs a sequence of wrappers on the given function and arguments. + Mutates wrappers in place. + """ + for wrapper in wrappers: + flat_fn, flat_args, flat_args_descs, fw_metadata = wrapper.pre_compile( + flat_fn, flat_args, flat_args_descs, aot_config, fw_metadata=fw_metadata + ) + return flat_fn, flat_args, flat_args_descs, fw_metadata + + +def post_compile( + wrappers: list[CompilerWrapper], + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, +) -> tuple[Callable[..., Any], ViewAndMutationMeta]: + """ + Runs a sequence of wrappers on the given function. Should be called after pre_compile() + """ + for wrapper in reversed(wrappers): + compiled_fn = wrapper.post_compile( + compiled_fn, aot_config, runtime_metadata=runtime_metadata + ) + return compiled_fn, runtime_metadata + + +def make_runtime_safe( + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: SubclassMeta | None, +) -> None: + """ + Calls make_runtime_safe on all ViewAndMutationMetas. + Modifies both arguments. Allows ViewAndMutationMetas to + be safely cached in AOTAutogradCache. + """ + fw_metadata.make_runtime_safe() + if maybe_subclass_meta is not None: + maybe_subclass_meta.fw_metadata.make_runtime_safe() + if maybe_subclass_meta.grad_input_metas: + for meta in maybe_subclass_meta.grad_input_metas: + if isinstance(meta, SubclassCreationMeta): + meta.make_runtime_safe() diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/schemas.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..c3b7013b4a21754cca829498a2a21a61fa70065b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/schemas.py @@ -0,0 +1,1567 @@ +""" +The various dataclasses, Enums, namedtuples etc used in AOTAutograd. This includes +input/output types, metadata, config, function signatures etc. +""" + +from __future__ import annotations + +import collections +import functools +from collections.abc import Sequence +from dataclasses import dataclass, field, replace +from enum import Enum +from typing import Any, NewType, Protocol, TYPE_CHECKING, TypeAlias, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch.utils._pytree as pytree +from torch import SymInt, Tensor +from torch._custom_class_base import CustomClassBase +from torch._subclasses.fake_tensor import is_fake, is_fake_tensor +from torch.fx.experimental._backward_state import BackwardState +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .. import config +from .functional_utils import _check_if_mutation_can_be_in_graph, ViewMetaSequence +from .utils import strict_zip + + +if TYPE_CHECKING: + import contextlib + from collections.abc import Callable, Iterable + + from torch._guards import Source + from torch._inductor.output_code import OutputCode + from torch._inductor.utils import InputType + from torch._ops import OpOverload + from torch._subclasses import FakeTensorMode + from torch.types import IntLikeType + + from .descriptors import AOTInput, AOTOutput + from .graph_capture_wrappers import JointFnHandle + +_P = ParamSpec("_P") +_R = TypeVar("_R") +zip = strict_zip + +ActInputPath: TypeAlias = tuple[int, tuple[str, ...]] +ActInputPaths: TypeAlias = Sequence[ActInputPath] + + +OutputType = Enum( + "OutputType", + ( + # output is not an alias + "non_alias", + # output aliases an input + "alias_of_input", + # output **is** an input tensor + "is_input", + # output has a ._base tensor, which is a graph intermediate. + # We need to return its ._base as a graph output, + # so its requires_grad info is populated correctly. + # Instructs the runtime code to regenerate the current output + # from a base tensor, graph_intermediates[base_idx] + "alias_of_intermediate_save_as_output", + # Same as above; but we don't need to explicitly add its ._base + # as a graph output, because it already **is** a graph output. + "alias_of_intermediate", + # Same as above; but the output's ._base is **already** a user output. + # Instructs the runtime code to regenerate the current output from + # a base tensor, user_outputs[base_idx] + "alias_of_intermediate_base_is_user_output", + # See Note [Intermediate Bases Optimization] + "unsafe_view_alias", + # output is an alias, but has a custom autograd.Function backward. + # In this case, we don't want to do view-replay, since we won't be able to replay the custom function. + # Instead, we'll treat this output "normally", and trace its backward into the graph. + "custom_function_view", + ), +) + + +# This class stores info about every user output. +@dataclass(frozen=True) +class OutputAliasInfo: + # Tells us if this output is: + # (1) a regular (non-aliased) output + # (2) an alias of a forward input + # (3) **is** a forward input (special case of "alias_of_input") + # (4) an alias of an intermediate (aka an alias of an output of the inner traced forward) + # (5) an alias of an intermediate, that explicitly requires returning the intermediate + # as a graph output + # (6) an alias of an intermediate, where that intermediate is also a user output + output_type: OutputType + # The raw type of the output (torch.Tensor, SymInt, etc) + raw_type: type + # If (1) above, then + # - base_idx is None + # If (2) or (3) above, then + # - Tells us that the base of this alias is user_fwd_input[base_idx] + # (This is an index into the inputs *before* we make synthetic bases) + # If (4) or (5) above, then + # - Tells us that the base of this alias is output_graph_intermediates[base_idx] + # here, this refers to the index of the *direct* traced + # If (6) above, then: + # - Tells us that the base of this alias is output_user_fwds[base_idx] + # here, this refers to the index of the *direct* traced + base_idx: int | None + # If it is a Tensor, what the dynamic dims are (otherwise is None) + dynamic_dims: set[int] | None + # Whether the output tensor has requires_grad=True. Use for + # preserving output properties (mark_non_differentiable, alias reconstruction). + requires_grad: bool + # Whether this output participates in backward as + # a tangent. Normally the same as requires_grad, but False for views created + # under no_grad() that inherit requires_grad from their base without having a + # grad_fn. Use when constructing tangent lists for torch.autograd.grad(). + requires_grad_for_backward: bool + # Sequence of ViewMeta objects. + # + # Provides us the means to re-run view functions on other tensors. + # + # We need to wrap the actual list of ViewMeta with this class so that + # we compare the ViewMeta elements appropriately, i.e. their type and + # the elements returned by the `as_tuple()` call. + view_meta_sequence: ViewMetaSequence | None = None + + +class MutationType(Enum): + NOT_MUTATED = 1 + MUTATED_IN_GRAPH = 2 + MUTATED_OUT_GRAPH = 3 + + +# This class tells us info about user inputs. +@dataclass(frozen=True) +class InputAliasInfo: + is_leaf: bool + mutates_data: bool + mutates_metadata: bool + mutations_hidden_from_autograd: bool + mutations_under_no_grad_or_inference_mode: bool + mutation_inductor_storage_resize: bool + mutates_storage_metadata: bool + mutation_is_shallow_copy_data: bool + requires_grad: bool + keep_input_mutations: bool + + def __post_init__(self) -> None: + if self.mutates_storage_metadata: + # For convenience, we guarantee that this is always true. + # In practice, If we call .set_(), then at runtime there is no need + # to additionally fix up the tensor metadata, since our runtime + # call to inp.set_(updated_inp) will already have the right metadata + if not self.mutates_metadata: + raise AssertionError( + "mutates_storage_metadata requires mutates_metadata to be True" + ) + + @functools.cached_property + def mutation_type(self) -> MutationType: + if ( + (not self.mutates_data) + and (not self.mutates_metadata) + and not (self.mutation_inductor_storage_resize) + ): + return MutationType.NOT_MUTATED + + if _check_if_mutation_can_be_in_graph( + self.keep_input_mutations, + self.mutates_data, + self.mutates_metadata, + self.mutations_hidden_from_autograd, + self.mutations_under_no_grad_or_inference_mode, + self.mutates_storage_metadata, + self.mutation_inductor_storage_resize, + self.requires_grad, + ): + return MutationType.MUTATED_IN_GRAPH + + return MutationType.MUTATED_OUT_GRAPH + + +@dataclass +class MemoryFormatMeta: + # For static shapes we assume tangents have the same strideness as outputs + size: Sequence[int] | None = None + stride: Sequence[int] | None = None + + # For dynamic shapes we assume the same memory format: contiguous, channels_last etc. + memory_format: torch.memory_format | None = None + + @staticmethod + def from_tensor( + t: torch.Tensor, force_use_memory_format: bool = False + ) -> MemoryFormatMeta | None: + # We only memorize expected memory format for + # 1. Traceable wrapper subclasses + # We can not create restrided subclass tensor, as torch.empty_strided works only with dense tensors. + # 2. Dynamic shape tensors + # Support for symbolic shapes is not implemented yet. + # 3. force_use_memory_format=True (e.g., local_map where shapes change) + use_memory_format: bool = ( + force_use_memory_format + or not torch._functorch.config.guess_tangent_strides_as_outputs + or is_traceable_wrapper_subclass(t) + ) + if not use_memory_format: + use_memory_format = t._has_symbolic_sizes_strides + + if ( + not use_memory_format + and t.layout == torch.strided + and torch._debug_has_internal_overlap(t) == 1 + ): + # An internally overlapping output, e.g. from expand(), cannot + # represent arbitrary incoming gradients with its own strides. + use_memory_format = True + + if use_memory_format: + return MemoryFormatMeta( + # pyrefly: ignore [unbound-name] + memory_format=torch._prims_common.suggest_memory_format(t), + ) + + return MemoryFormatMeta( + size=t.size(), + stride=t.stride(), + ) + + +@dataclass +class PlainTensorMeta: + unwrapped_idx: int + memory_format: MemoryFormatMeta | None = None + size_symbol_placeholders: tuple[bool, ...] = () + stride_symbol_placeholders: tuple[bool, ...] = () + + @property + def arg_count(self) -> int: + return ( + 1 + + sum(self.size_symbol_placeholders) + + sum(self.stride_symbol_placeholders) + ) + + +@dataclass +class OpaqueMeta: + pass + + +@dataclass +class SubclassCreationMeta: + """ + Used for AOTDispatch. + This dataclass gives us the information we need to reconstruct a tensor subclass + from our flat inputs. + Why is this important? The graph that we'd like to trace out contains flat tensor inputs, + But the user's original model may have subclass inputs and outputs. + So we need to wrap/unwrap subclasses as necessary to translate between the user's + view (subclass inps/outs), and the backend compiler's view (graph with no subclass args). + + Complications arise mostly from the fact that a subclass can hold more than one inner tensor; + So for a given subclass input/output, we need to carefully track which indices map + to the subclass tensor in the corresponding "dense-tensor-only" graph. + """ + + # In the inner graph that only takes in dense tensor inputs, + # this maps to the first index of "tensors that should go in this subclass wrapper" + flat_tensor_start_idx: int + # arg_count is inclusive of the arg_counts of any + # inner tensor subclasses: If I have a TwoTensor and + # both of its inner elements are TwoTensors, then the + # arg_count of the outer-most subclass will be 4 + arg_count: int + # Mark where or not symints were included. This flag is only used in one assertion + # in "wrap_tensor_subclasses" + included_subclass_symints: bool + # meta and attrs are produced by the subclass's __tensor_flatten__. + # We need to keep them around along with outer_size / outer_stride to plumb them + # into __tensor_unflatten__ + attrs: dict[str, SubclassCreationMeta | PlainTensorMeta | OpaqueMeta] + outer_size: Iterable[IntLikeType | None] + outer_stride: Iterable[IntLikeType | None] + meta: Any + # Stores the original subclass itself. + # This is needed because we need the autograd metadata on the original subclass + # (this is guaranteed to be a wrapper subclass that holds a fake tensor, + # so holding onto this at runtime shouldn't leak memory) + # This field is nulled out after calling make_runtime_safe() + original_subclass: torch.Tensor | None + + # Used at runtime to determine the subclass type, so we don't need to save the original subclass + original_subclass_type: type | None = None + memory_format: MemoryFormatMeta | None = None + outer_size_from_attr: str | None = None + outer_stride_from_attr: str | None = None + + def compute_outer_size_and_stride( + self, + all_args: Sequence[torch.Tensor | IntLikeType | CustomClassBase], + *, + curr_start_idx: int, + ) -> tuple[ + Iterable[IntLikeType | None], + Iterable[IntLikeType | None], + ]: + from .subclass_utils import compute_symint_placeholders + + def compute( + outer: Iterable[IntLikeType | None], start_idx: int + ) -> tuple[Any, int | Any]: + placeholders = compute_symint_placeholders(outer) + has_symbolic = any(placeholders) + + if has_symbolic: + end = start_idx + sum(placeholders) + it_args = iter(all_args[start_idx:end]) + it_placeholders = iter(placeholders) + return pytree.tree_map_only( + lambda _: next(it_placeholders), lambda _: next(it_args), outer + ), end + else: + return outer, start_idx + + outer_size, next_idx = compute(self.outer_size, curr_start_idx) + outer_stride, _ = compute(self.outer_stride, next_idx) + return outer_size, outer_stride + + def creation_fn( + self, + all_args: Sequence[torch.Tensor | IntLikeType | CustomClassBase], + *, + is_runtime: bool, + ) -> torch.Tensor: + inner_tensors: dict[str, torch.Tensor | CustomClassBase] = {} + + curr_start_idx = self.flat_tensor_start_idx + for attr, creation_meta in self.attrs.items(): + if isinstance(creation_meta, OpaqueMeta): + opaque = all_args[curr_start_idx] + if not isinstance(opaque, CustomClassBase): + raise AssertionError( + f"CustomClassBase expected, got {type(opaque)}" + ) + inner_tensors[attr] = opaque + curr_start_idx += 1 + continue + if isinstance(creation_meta, PlainTensorMeta): + subclass = all_args[curr_start_idx] + if not isinstance(subclass, Tensor): + raise AssertionError("Tensor expected") + curr_start_idx += creation_meta.arg_count + else: + subclass = creation_meta.creation_fn( + all_args, + is_runtime=is_runtime, + ) + curr_start_idx += creation_meta.arg_count + inner_tensors[attr] = subclass + + if is_runtime: + if self.original_subclass_type is None: + raise AssertionError( + "original_subclass_type must not be None at runtime" + ) + original_subclass_type = self.original_subclass_type + else: + original_subclass_type = type(self.original_subclass) + + if is_runtime: + outer_size, outer_stride = self.compute_outer_size_and_stride( + all_args, + curr_start_idx=curr_start_idx, + ) + if self.outer_size_from_attr is not None: + size_attr = inner_tensors[self.outer_size_from_attr] + if not isinstance(size_attr, Tensor): + raise AssertionError("Tensor expected") + outer_size = size_attr.size() + if self.outer_stride_from_attr is not None: + stride_attr = inner_tensors[self.outer_stride_from_attr] + if not isinstance(stride_attr, Tensor): + raise AssertionError("Tensor expected") + outer_stride = stride_attr.stride() + else: + outer_size, outer_stride = self.outer_size, self.outer_stride + + rebuilt = original_subclass_type.__tensor_unflatten__( # type: ignore[attr-defined] + inner_tensors, self.meta, outer_size, outer_stride + ) + + if not is_runtime: + # After wrapping up the inner dense tensors into a subclass, we need to make sure that our new wrapper + # has correct autograd metadata, since we'll be tracing through the autograd engine with the subclass. + # We don't trace through the autograd engine at runtime though, so no need + # to compute this extra metadata then! + torch._mirror_autograd_meta_to(self.original_subclass, rebuilt) # type: ignore[attr-defined] + + return rebuilt + + def make_runtime_safe(self) -> None: + def _make_size_runtime_safe(x: None | int | torch.SymInt) -> int | None: + dummy = -1 + if isinstance(x, torch.SymInt): + # Replace nested ints by a dummy value (-1) as NJT ignores + # the outer_size/outer_stride at runtime. + return dummy if x.node.is_nested_int() else None + return x + + if self.original_subclass is None: + raise AssertionError( + "original_subclass must not be None before calling make_runtime_safe" + ) + self.original_subclass_type = type(self.original_subclass) + self.original_subclass = None + + # Note: NJT outer_size in AOTDispatcher + # `_make_size_runtime_safe` replaces any nested int with a dummy value (-1) + # to prevent serializing a SymInt at runtime. Internally, nested tensor __tensor_unflatten__ + # is designed to safely ignore this dummy value. + # For more details, see: https://github.com/pytorch/pytorch/blob/5141ade8e30c64e873e14dcc8de233da45d15025/torch/nested/_internal/nested_tensor.py#L266-L299 + self.outer_size = tuple(map(_make_size_runtime_safe, self.outer_size)) + self.outer_stride = tuple(map(_make_size_runtime_safe, self.outer_stride)) + + # Recurse on nested subclass info + for creation_meta in self.attrs.values(): + if isinstance(creation_meta, SubclassCreationMeta): + creation_meta.make_runtime_safe() + + def __post_init__(self) -> None: + # sanity assert to make sure we don't leak memory + if not is_fake(self.original_subclass): + raise AssertionError( + f"original_subclass must be a fake tensor to avoid memory leaks, got {type(self.original_subclass)}" + ) + + +# This class encapsulates all aliasing + mutation info we need about the forward graph +# See a more detailed overview of the edge case handling at +# https://docs.google.com/document/d/19UoIh_SVrMy_b2Sx5ZaeOJttm6P0Qmyss2rdBuyfoic/edit +# NOTE: This class is saved in AOTAutogradCache, If you are adding elements, make sure +# they are covered by warm cache tests. +@dataclass(eq=False) +class ViewAndMutationMeta: + # length = # user inputs + # This gives us info about every input, and what sort of mutation happened to it (if any) + input_info: list[InputAliasInfo] + + # length = # user outputs + # This gives us info about every output (mostly around whether it aliases other tensors) + output_info: list[OutputAliasInfo] + + # length = the number of intermediate bases appended as outputs to the end of the forward graph. + # Note: this is not necessarily the same thing as: + # len([x for x in output_info if x.output_type == OutputType.alias_of_intermediate]) + # Because outputs might share a ._base, or an output's ._base might itself be + # another user output (in both cases, we won't redundantly append bases to the end of the graph) + num_intermediate_bases: int + + # For inference only: instructs us to keep data-only input mutations directly in the graph + keep_input_mutations: bool + + # length = (# inputs w data mutations) + (# user outputs that are non_aliasing tensors) + # + (# intermediate bases) + # These are the FakeTensor (or potential SymInt) outputs that we traced from our + # metadata pass of the user's forward function. + # Their only use today is to pass them as a best-guess for tangents when tracing the joint. + # Stashing them as part of our "metadata" makes it simpler if we want to run our analysis + # pass once, and reuse the output throughout AOTAutograd + traced_tangents: list[Any] + + # TODO doc + traced_tangents_descs: list[AOTInput] + + # Each of these is a list telling us about subclasses for the inputs/outputs/grad_outs + # They are used throughout AOTDispatch to tell us how to generate a list of subclass tensors, + # Given a (potentially larger) list of plain torch tensors. + + # Taking subclass_inp_meta as an example: + # subclass_inp_meta[i] = j (an int) tells us: + # "The i'th user input is not a subclass, and corresponds to inputs[j] of the plain-tensor graph." + # subclass_inp_meta[i] = SubclassCreationMeta(flat_tensor_start_idx=3, arg_count=2) + # "The i'th user input is subclass holding two inner tensors, which are + # inputs[3] and inputs[4] of the plain-tensor graph". + + # length = # user inputs + subclass_inp_meta: list[PlainTensorMeta | SubclassCreationMeta] + # So, the full set of outputs to the forward graph looks something like: + # (*mutated_inps, *user_outs, *intermediate_bases, *saved_for_bw_tensors) + # where the first 3 of those 4 can be subclasses + # (but not saved_for_bw tensors, since these are internal to the compiler + # and not user visible, so there's no point in wrapping/unwrapping them at runtime). + # This list contains subclass information on all of the fw graph outputs + # except for saved_for_bw_tensors. + subclass_fw_graph_out_meta: list[PlainTensorMeta | SubclassCreationMeta] + # length = # backward graph inputs + subclass_tangent_meta: list[PlainTensorMeta | SubclassCreationMeta] + + # length = (# inputs w data mutations) + (# user outputs that are non_aliasing tensors) + # + (# intermediate bases) + # At runtime, we don't keep the traced_tangents around since they're not serializable. + # Instead, we keep any necessary subclass metadata necessary about each traced_tangent. + # This list is generated after calling make_runtime_safe(). + traced_tangent_metas: list[Any] | None = None + + num_symints_saved_for_bw: int | None = None + + # See Note [Activations with no version counter checks in eager] + # Number of tensors saved for backward that were stashed on ctx (e.g., ctx.x = x) + # rather than via save_for_backward in an autograd.Function. + # These tensors are placed at the end of the saved tensors and should skip + # version counter checks at runtime. + num_tensors_saved_with_no_vc_check: int | None = None + + # Number of opaque objects saved for backward + num_opaque_objects_saved_for_bw: int | None = None + + # Whether each saved tensor is also a graph input. + saved_tensor_is_graph_input: list[bool] = field(default_factory=list) + # The grad_enabled mutation that will be emitted in the runtime_wrapper epilogue + # NOTE: AOTAutograd will assume that the ambient `is_grad_enabled` is the grad mode + # that is intended to be in effect prior to running the graph, in keeping with + # equivalence to eager mode. It is the responsibility of upstream graph acquisition + # to reset the grad mode to its pre-graph value prior to calling aot_autograd. + grad_enabled_mutation: bool | None = None + + # Keeps track of whether `torch.use_deterministic_algorithms` was turned on + # when the forward was run. If deterministic mode was turned off during the + # forward, but is turned on during the backward call, then an error is + # raised + deterministic: bool | None = None + + # Keeps track of which input indices store parameters (which we will treat as static) + static_input_indices: list[int] = field(default_factory=list) + + # Input paths that held AsyncCollectiveTensors at compile time. A path is + # (input_index, attr_path), where an empty attr_path means the top-level + # input. Used to emit direct trigger_wait() calls at runtime instead of + # scanning every arg on every graph invocation. + act_input_paths: list[ActInputPath] = field(default_factory=list) + + # Map of effect type (ex. _EffectType.ORDERED) to token. If there are + # side-effectful operators, FunctionalTensorMode will populate this + # dictionary telling us how many tokens we will need during tracing. + tokens: dict[Any, torch.Tensor] = field(default_factory=dict) + + # Only filled in if/when we trace the joint function + # If an input requires grad and is mutated in the backward, it is only safe to keep the mutation + # in the graph if gradients are disabled while the backward runs + # (grad mode is disabled by default when users run the backward, but can be turned on with create_graph=True) + # At runtime during the backward, we use this list of indices to error properly if we find out + # that it was not safe to include a backward mutation in the graph. + indices_of_inputs_that_requires_grad_with_mutations_in_bw: list[int] = field( + default_factory=list + ) + + # Indexes of saved tensors which are donated buffer. + # Donated buffer means the tensor is not alias of any forward user input, forward user output, + # and backward output. + bw_donated_idxs: list[int] | None = None + + # Number of tokens used in backward, appended at the end of backward outputs. + # Filled after tracing joint function. + num_backward_tokens: int = 0 + + # Number of rng states that will get thread into the forward and backward for + # cudagraph compatible run_and_save_rng + num_graphsafe_rng_states: int = 0 + + graphsafe_rng_state_index: int | None = None + + # Device for graphsafe RNG states (supports CUDA, TPU, etc.) + graphsafe_rng_device: torch.device | None = None + + # Stream indices for mutated inputs in the epilogue + # Maps from index in mutated_inp_runtime_indices to the stream index that last touched + # the storage of the tensor that will be copied back into the original input + # None means use the current/default stream + # This is populated during graph compilation when stream assignments are made + mutated_inp_stream_indices: list[int | None] | None = None + + # compile ID string (e.g., "1/0") for error messages + compile_id_str: str | None = None + + # help users identify where to add .detach() in their code + tangent_source_stack_traces: list[str | None] | None = None + + def __post_init__(self) -> None: + # pre-compute the indices of the inputs that are mutated. + # When keep_input_mutations is set, we don't need to worry about our epilogue + # handling data-only mutations, because we keep them directly in the graph. + mutated_inp_runtime_indices = [ + i + for i, m in enumerate(self.input_info) + if (m.mutation_type == MutationType.MUTATED_OUT_GRAPH) + ] + + mutated_graph_handled_indices = [ + i + for i, m in enumerate(self.input_info) + if m.mutation_type == MutationType.MUTATED_IN_GRAPH + ] + self.mutated_graph_handled_indices = mutated_graph_handled_indices + self.num_mutated_graph_handled_indices = len(self.mutated_graph_handled_indices) + + mutated_graph_handled_indices_seen_by_autograd = [ + i + for i in mutated_graph_handled_indices + if not self.input_info[i].mutations_hidden_from_autograd + ] + + self.mutated_graph_handled_indices_seen_by_autograd = ( + mutated_graph_handled_indices_seen_by_autograd + ) + self.num_mutated_graph_handled_indices_seen_by_autograd = len( + self.mutated_graph_handled_indices_seen_by_autograd + ) + + aliased_out_indices = [ + i + for i, m in enumerate(self.output_info) + if m.output_type + not in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + ] + unsafe_view_out_indices = [ + i + for i, m in enumerate(self.output_info) + if m.output_type is OutputType.unsafe_view_alias + ] + + # This is pre-computed in post_init for perf. + # It contains the index of every element + # of input_info that corresponds to a mutation (data or metadata or both) + self.mutated_inp_runtime_indices = mutated_inp_runtime_indices + self.num_mutated_inp_runtime_indices = len(self.mutated_inp_runtime_indices) + + # This is pre-computed for perf. + # It contains the index of every element + # of output_info that corresponds to an alias (either of an input or intermediate) + self.aliased_out_indices = aliased_out_indices + self.unsafe_view_out_indices = unsafe_view_out_indices + self.num_outputs = len(self.output_info) + self.num_outputs_non_aliased = len( + [ + x + for x in self.output_info + if x.output_type + in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + ] + ) + self.num_outputs_aliased_to_inputs = len( + [ + x + for x in self.output_info + if x.output_type + in [ + OutputType.alias_of_input, + OutputType.is_input, + ] + ] + ) + self.num_unsafe_view_outputs = len(self.unsafe_view_out_indices) + self.num_outputs_aliased_to_intermediates = len( + [ + x + for x in self.output_info + if x.output_type + in [ + OutputType.alias_of_intermediate, + OutputType.alias_of_intermediate_save_as_output, + OutputType.alias_of_intermediate_base_is_user_output, + ] + ] + ) + self.num_outputs_aliased = ( + self.num_outputs_aliased_to_inputs + + self.num_outputs_aliased_to_intermediates + ) + + # Record dynamic outputs of the Dynamo traced forward graph + # Mark them as dynamic at the end of the runtime wrapper + self.dynamic_outputs = any(o.dynamic_dims for o in self.output_info) + + # Record the indices of dynamic outputs in the partitioned forward graph + # Mark them as dynamic in the runtime wrapper + # activation index -> dynamic dims indices + self.dynamic_saved_tensors_idxs: dict[int, set[int]] = {} + + # See Note: [AOTAutograd Backward Guards] + # This is pre-computed for fast asserts on the types of our grad_outputs in the backward. + # Eventually, we should kill this and replace with real backward guards. + # (we want to precompute the "runtime" types, so replace FakeTensor with torch.Tensor) + self.output_types = [ + torch.Tensor if is_fake_tensor(x) else type(x) for x in self.traced_tangents + ] + + self.is_rng_op_functionalized = config.functionalize_rng_ops + # All of the above metadata is collected by tracing the fw function. + # However, extra outputs for rng offsets behave differently. Both fwd + # and bwd graphs have their own outputs for the total consumed offsets. + # Unlike mutated inputs, we don't have to worry about sending the right + # set of tensors between fwd and bwd. Fwd and bwd offsets are + # independent and simpler to handle. Therefore, we track them + # separately. + self.num_outputs_rng_offset = 1 if self.is_rng_op_functionalized else 0 + + # Our forward() returns both (tokens, mutated_inputs, outputs, output_intermediate_bases, saved_tensors, saved_symints) + # Tokens will be split out before mutations/view handling and we do not count them here. + self.num_forward_returns = ( + self.num_mutated_inp_runtime_indices + + self.num_outputs + + self.num_intermediate_bases + ) + # In case of functionalization of rng ops, the fw_module returns one + # additional output for rng offset. This rng offset is used right + # away to advance the rng state, and is not passed on to the raw + # outputs. However, we need to know the exact boundary to identify + # which tensors to be saved for the bwd graph. num_forward captures + # this information. + self.num_forward = self.num_forward_returns + self.num_outputs_rng_offset + + def make_runtime_safe(self) -> None: + """ + There are various fields in ViewAndMutationMeta that aren't serializable. This function is called after all tracing + is completed to simplify certain fields in the metadata so that they can be safely cached. + + Doing so may lose information (in the case of traced_tangents), but none of the information is needed at runtime. + """ + # TODO: This function is only a best effort: there are other fields that may not be cache safe + # (i.e., there's no guarantee that tensor_flatten() returns a serializable result), or that + # SubclassCreationMeta is cache safe. + if self.traced_tangent_metas is not None: + raise AssertionError( + "traced_tangent_metas should be None before calling make_runtime_safe" + ) + + def extract_metadata(t: object) -> tuple[Sequence[str], object] | None: + if isinstance(t, torch.Tensor) and is_traceable_wrapper_subclass(t): + (inner_tensors, flatten_spec) = t.__tensor_flatten__() # type: ignore[attr-defined] + # Technically, we only need the flatten_spec, not the inner tensors. + # However, some Tensor subclasses (like TwoTensor) may have flatten_spec = None. + # And we want to be able to assert that this metadata is non-None, + # to distinguish between "this was a tensor subclass with no metadata" vs. + # "this wasn't a tensor subclass at all". + return (inner_tensors, flatten_spec) + else: + return None + + self.traced_tangent_metas = [extract_metadata(t) for t in self.traced_tangents] + # Clear traced tangents at runtime + self.traced_tangents = [] + for inp_meta in self.subclass_inp_meta: + if isinstance(inp_meta, SubclassCreationMeta): + inp_meta.make_runtime_safe() + for inp_meta in self.subclass_fw_graph_out_meta: + if isinstance(inp_meta, SubclassCreationMeta): + inp_meta.make_runtime_safe() + for inp_meta in self.subclass_tangent_meta: + if isinstance(inp_meta, SubclassCreationMeta): + inp_meta.make_runtime_safe() + + # Clear view_meta_sequence when it has symbolic inputs, since it won't + # be used at runtime anyway (gen_alias_from_base skips view replay for + # symbolic inputs) and the SymInt references make it unpicklable. + for i, out_info in enumerate(self.output_info): + if out_info.view_meta_sequence is not None and any( + vm.has_symbolic_inputs for vm in out_info.view_meta_sequence.sequence + ): + self.output_info[i] = replace(out_info, view_meta_sequence=None) + + @property + def tensors_saved_for_backwards_slice(self) -> slice: + if self.num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + if self.num_tensors_saved_with_no_vc_check is None: + raise AssertionError("num_tensors_saved_with_no_vc_check must not be None") + # Fast-path: if no tensors without VC check, just return the VC check slice + if self.num_tensors_saved_with_no_vc_check == 0: + return self.tensors_saved_for_backwards_with_vc_check_slice + # Invariant: total tensors activations = (acts_with_vc_check, acts_no_vc_check) + vc_slice = self.tensors_saved_for_backwards_with_vc_check_slice + no_vc_slice = self.tensors_saved_for_backwards_no_vc_check_slice + # Start should be the same (self.num_forward) + if vc_slice.start != self.num_forward: + raise AssertionError( + f"vc_slice.start ({vc_slice.start}) != self.num_forward ({self.num_forward})" + ) + # End is the end of the no_vc_check slice + return slice(vc_slice.start, no_vc_slice.stop) + + @property + def tensors_saved_for_backwards_with_vc_check_slice(self) -> slice: + """ + Slice of forward outputs that are tensors saved for backward that + require version counter checks (i.e., were saved via save_for_backward). + """ + # See Note [Activations with no version counter checks in eager] + if self.num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + if self.num_tensors_saved_with_no_vc_check is None: + raise AssertionError("num_tensors_saved_with_no_vc_check must not be None") + # The tensors with VC check come first, followed by tensors without VC check + num_no_vc_check = self.num_tensors_saved_with_no_vc_check + num_opaque = self.num_opaque_objects_saved_for_bw or 0 + num_symints = self.num_symints_saved_for_bw + num_trailing = num_no_vc_check + num_opaque + num_symints + if num_trailing > 0: + return slice(self.num_forward, -num_trailing if num_trailing != 0 else None) + else: + return slice(self.num_forward, None) + + @property + def tensors_saved_for_backwards_no_vc_check_slice(self) -> slice: + """ + Slice of forward outputs that are tensors saved for backward that + do NOT require version counter checks (i.e., were stashed on ctx + rather than via save_for_backward in an autograd.Function). + """ + if self.num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + if self.num_tensors_saved_with_no_vc_check is None: + raise AssertionError("num_tensors_saved_with_no_vc_check must not be None") + num_no_vc_check = self.num_tensors_saved_with_no_vc_check + num_opaque = self.num_opaque_objects_saved_for_bw or 0 + num_symints = self.num_symints_saved_for_bw + if num_no_vc_check == 0: + return slice(0, 0) # empty slice + num_trailing = num_opaque + num_symints + if num_trailing > 0: + return slice(-num_no_vc_check - num_trailing, -num_trailing) + else: + return slice(-num_no_vc_check, None) + + @property + def opaque_objects_saved_for_backwards_slice(self) -> slice: + num_opaque = self.num_opaque_objects_saved_for_bw or 0 + num_symints = self.num_symints_saved_for_bw or 0 + if num_opaque > 0: + if num_symints > 0: + return slice(-num_opaque - num_symints, -num_symints) + else: + return slice(-num_opaque, None) + else: + return slice(0, 0) # empty slice + + @property + def symints_saved_for_backwards_slice(self) -> slice: + if self.num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + if self.num_symints_saved_for_bw > 0: + return slice(-self.num_symints_saved_for_bw, None) + else: + return slice(0, 0) # empty slice + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ViewAndMutationMeta): + return NotImplemented + return ( + self.input_info == other.input_info + and self.output_info == other.output_info + and self.num_intermediate_bases == other.num_intermediate_bases + and self.keep_input_mutations == other.keep_input_mutations + and self.is_rng_op_functionalized == other.is_rng_op_functionalized + and self.num_outputs_rng_offset == other.num_outputs_rng_offset + and len(self.traced_tangents) == len(other.traced_tangents) + and all( + x.shape == y.shape and x.dtype == y.dtype + for x, y in zip(self.traced_tangents, other.traced_tangents) + ) + and self.num_backward_tokens == other.num_backward_tokens + ) + + +@dataclass(eq=False) +class SubclassMeta: + # A copy of all forward metadata, but computed on the *dense* tensor forward (after desugaring subclasses) + # So for example, if the user had a model containing two `TwoTensor` inputs, + # Then `SubclassMeta.fw_metadata.input_infos` would have length 4 here. + fw_metadata: ViewAndMutationMeta + + # Note: [Computing Subclass Metadata about grad_inputs] + # Given a list of flattened, plain tensor grad_inputs, this tells us how to reconstruct the grad_input subclasses + # + # You might think: why not just assume that all grad_inputs will have the same subclass-ness as the original inputs? + # (AOTAutograd generally assumes other properties, e.g. that grad_outputs are contiguous) + # + # This doesn't really work though. take this example: + # + # def f(DoubleTensor, DenseTensor): + # return DoubleTensor * DenseTensor + # + # In the above example, the .grad field of *both* DoubleTensor and DenseTensor will be a DoubleTensor. + # When we trace out a joint fw-bw graph, we'll end up returning two subclasses for the two grad_inputs. + # This means that our backward graph will return 4 outputs (two dense tensors for each DoubleTensor grad_input) + # and we need to properly store the metadata that tells us how to turn these 4 outputs back into DoubleTensors. + # + # Note that this info **cannot** easily be figured out from ViewAndMutationMeta. + # We can only compute this info by tracing the entire joint and examining the grad_inputs that we computed. + # + # See Note: [AOTAutograd Backward Guards] + # This will also eventually require us to install backward guards, + # in case we made incorrect assumptions about the subclass-ness of our grad_outputs + # + # Optional field because we don't compute for inference graphs + grad_input_metas: list[PlainTensorMeta | SubclassCreationMeta] | None = None + + def __init__(self) -> None: + # The fields in this class get set after its construction. + pass + + +# This class exists because: +# - the autograd.Function.forward() in aot autograd returns outputs that might alias inputs +# - we only care about the metadata on those aliases, so we can regenerate them. +# We do not want them to participate in the autograd.Function. +# We do that by wrapping them in an opaque class, so the autograd.Function +# does not know to treat them as tensors. +@dataclass(frozen=True) +class TensorAlias: + alias: torch.Tensor + + +@dataclass +class BackwardSignature: + """ + Provides information about the backward section of an exported + joint forward-backward graph. + For a particular fx GraphModule, this class contains information on: + (1) A mapping from each gradient (backwards output) to the parameter + it corresponds to (forward input) + (2) A mapping from each gradient (backwards output) to the user input + it corresponds to (forward input) + (3) Which of the forward outputs corresponds to the loss, that we backprop on. + + Each string name is the `node.name` of the corresponding node in the fx graph. + """ + + gradients_to_parameters: dict[str, str] + gradients_to_user_inputs: dict[str, str] + loss_output: str + + +GraphOutputName = NewType("GraphOutputName", str) +GraphInputName = NewType("GraphInputName", str) +FQN = NewType("FQN", str) + + +@dataclass +class GraphSignature: + """ + Provides information about an exported module. + For a particular fx GraphModule, this class contains information on: + (1) Which graph inputs are parameters, buffers, or user inputs + (2) (for params/buffers) a mapping from the name of each graph argument + to its parameter/buffer FQN in the original nn.Module. + (3) If there are input mutations, these are represented as extra outputs + in the fx GraphModule. We provide a mapping from these + extra output names to the names of the actual inputs. + (4) The pytree metadata on how to flatten/unflatten inputs and outputs. + The corresponding FX GraphModule only accepts and returns + pytree-flattened inputs/outputs. + (5) (Optionally) if the FX is a joint forward-backward graph, we provide + a signature on the backward section of the joint graph. + """ + + parameters: list[FQN] + buffers: list[FQN] + + user_inputs: list[GraphInputName] + user_outputs: list[GraphOutputName] + inputs_to_parameters: dict[GraphInputName, FQN] + inputs_to_buffers: dict[GraphInputName, FQN] + + # If the user's module mutates a buffer, + # it's represented in the graph as an extra graph output. + # This dict is a mapping from + # "graph outputs that correspond to updated buffers" + # to the FQN names of those mutated buffers. + buffers_to_mutate: dict[GraphOutputName, FQN] + parameters_to_mutate: dict[GraphOutputName, FQN] + user_inputs_to_mutate: dict[GraphOutputName, GraphInputName] + + in_spec: pytree.TreeSpec + out_spec: pytree.TreeSpec + + backward_signature: BackwardSignature | None + + input_tokens: list[GraphInputName] + output_tokens: list[GraphOutputName] + + @classmethod + def from_tracing_metadata( + cls, + *, + in_spec: pytree.TreeSpec, + out_spec: pytree.TreeSpec, + graph_input_names: list[str], + graph_output_names: list[str], + view_mutation_metadata: ViewAndMutationMeta, + named_parameters: list[str], + named_buffers: list[str], + num_user_inputs: int, + num_user_outputs: int, + trace_joint: bool, + loss_index: int | None, + backward_signature: BackwardSignature | None, + ) -> GraphSignature: + graph_inputs = graph_input_names + graph_outputs = graph_output_names + parameters = list(named_parameters) + buffers = list(named_buffers) + num_tokens = len(view_mutation_metadata.tokens) + + # Calling convention assumptions: + # (1) graph inputs = (input_tokens, params, buffers, user_inputs) + # (2) graph outputs = (output_tokens, mutated_inputs, user_outs, param_gradients) + # (If we are capturing an inference graph, this convention is identical + # except that param_gradients is empty) + # See Note [Side-Effectful Tokens in AOTAutograd] for information on tokens + + # Address input calling conventions: + start, stop = 0, num_tokens + input_tokens = graph_inputs[start:stop] + + start, stop = stop, stop + len(parameters) + inputs_to_parameters = dict(zip(graph_inputs[start:stop], parameters)) + + start, stop = stop, stop + len(buffers) + inputs_to_buffers = dict( + zip( + graph_inputs[start:stop], + buffers, + ) + ) + + start, stop = stop, stop + num_user_inputs + user_inputs = graph_inputs[start:stop] + + # We should've gone through all the inputs now + if len(graph_inputs) - stop != 0: + raise AssertionError( + f"expected all graph_inputs consumed, but {len(graph_inputs) - stop} remain" + ) + + # Address output calling conventions: + start, stop = 0, num_tokens + output_tokens = graph_outputs[start:stop] + + names = [*input_tokens, *parameters, *buffers, *user_inputs] + mutations: list[str] = [] + for idx, input_info in enumerate(view_mutation_metadata.input_info): + if input_info.mutates_data: + if trace_joint: + # Only buffers can be mutated, not parameters + if idx < len(parameters): + raise AssertionError( + f"expected idx ({idx}) >= len(parameters) ({len(parameters)}) when tracing joint" + ) + mutations.append(names[idx + num_tokens]) + + if len(mutations) != view_mutation_metadata.num_mutated_inp_runtime_indices: + raise AssertionError( + f"len(mutations) ({len(mutations)}) != " + f"num_mutated_inp_runtime_indices ({view_mutation_metadata.num_mutated_inp_runtime_indices})" + ) + + start, stop = ( + stop, + stop + view_mutation_metadata.num_mutated_inp_runtime_indices, + ) + outputs_to_mutations = dict(zip(graph_outputs[start:stop], mutations)) + + user_inputs_to_mutate: dict[GraphOutputName, GraphInputName] = {} + buffers_to_mutate: dict[GraphOutputName, FQN] = {} + parameters_to_mutate: dict[GraphOutputName, FQN] = {} + for output_name, mutation_name in outputs_to_mutations.items(): + if mutation_name in user_inputs: + # pyrefly: ignore [unsupported-operation] + user_inputs_to_mutate[output_name] = mutation_name + else: + if mutation_name not in buffers and mutation_name not in parameters: + raise AssertionError( + f"mutation_name '{mutation_name}' not found in buffers or parameters" + ) + if mutation_name in buffers: + # pyrefly: ignore [unsupported-operation] + buffers_to_mutate[output_name] = mutation_name + else: + # pyrefly: ignore [unsupported-operation] + parameters_to_mutate[output_name] = mutation_name + + start, stop = stop, stop + num_user_outputs + user_outputs = graph_outputs[start:stop] + + unused_outputs = len(graph_outputs) - stop + if backward_signature is not None: + unused_outputs -= len(backward_signature.gradients_to_parameters) + len( + backward_signature.gradients_to_user_inputs + ) + if unused_outputs != 0: + raise AssertionError(f"expected unused_outputs == 0, got {unused_outputs}") + + return GraphSignature( + parameters=parameters, # type: ignore[arg-type] + buffers=buffers, # type: ignore[arg-type] + user_inputs=user_inputs, # type: ignore[arg-type] + user_outputs=user_outputs, # type: ignore[arg-type] + inputs_to_buffers=inputs_to_buffers, # type: ignore[arg-type] + inputs_to_parameters=inputs_to_parameters, # type: ignore[arg-type] + user_inputs_to_mutate=user_inputs_to_mutate, + buffers_to_mutate=buffers_to_mutate, # type: ignore[arg-type] + parameters_to_mutate=parameters_to_mutate, # type: ignore[arg-type] + in_spec=in_spec, + out_spec=out_spec, + backward_signature=backward_signature, + input_tokens=input_tokens, # type: ignore[arg-type] + output_tokens=output_tokens, # type: ignore[arg-type] + ) + + +@dataclass +class AOTAutogradCacheInfo: + cache_key: str + start_time_ns: int + forward_symints: list[torch.SymInt] + + +@dataclass +class CacheableAOTConfig: + """ + Serializable subset of AOTConfig used by cache keys and cached entries. + """ + + num_params_buffers: int + aot_id: int + keep_inference_input_mutations: bool + is_export: bool = False + no_tangents: bool = False + dynamic_shapes: bool = False + aot_autograd_arg_pos_to_source: list[Source] | None = None + static_input_indices: list[int] | None = None + enable_log: bool = True + # this is always false outside of export. + pre_dispatch: bool = False + precompile_backend_id: str | None = None + + def __post_init__(self) -> None: + if self.pre_dispatch and not self.is_export: + raise AssertionError("Can only have pre_dispatch IR for export.") + + +@dataclass(frozen=True) +class AOTConfig: + """ + Configuration for AOTDispatcher + """ + + fw_compiler: Callable[..., Any] | None + bw_compiler: Callable[..., Any] | None + partition_fn: Callable[..., Any] | None + decompositions: dict[OpOverload, Callable[..., Any]] | None + num_params_buffers: int + aot_id: int + keep_inference_input_mutations: bool + is_export: bool = False + no_tangents: bool = False + dynamic_shapes: bool = False + aot_autograd_arg_pos_to_source: list[Source] | None = None + static_input_indices: list[int] | None = None + inference_compiler: Callable[..., Any] | None = None + enable_log: bool = True + # this is always false outside of export. + pre_dispatch: bool = False + # Key to use for AOTAutogradCache + cache_info: AOTAutogradCacheInfo | None = None + # If we should ignore the shape_env in the ambient tracing_context. + # The net effect is that if dynamic shapes are on, we end up + # specializing on example_inputs. + # Used only by standalone_compile. + ignore_shape_env: bool = False + precompile_backend_id: str | None = None + force_non_lazy_backward_lowering: bool = False + # This config makes sure to check certain things like + # mutating input with req_grad in export joint tracing. + export_trace_joint: bool = False + disable_functionalization: bool = False + # If True, disable TorchFunctionMetadataMode during make_fx tracing. + # This mode is used to track torch_fn metadata but can interfere with + # certain tracing scenarios. + _disable_torch_fn_metadata_mode: bool = False + + def to_cacheable(self) -> CacheableAOTConfig: + return CacheableAOTConfig( + num_params_buffers=self.num_params_buffers, + aot_id=self.aot_id, + keep_inference_input_mutations=self.keep_inference_input_mutations, + is_export=self.is_export, + no_tangents=self.no_tangents, + dynamic_shapes=self.dynamic_shapes, + aot_autograd_arg_pos_to_source=self.aot_autograd_arg_pos_to_source, + static_input_indices=self.static_input_indices, + enable_log=self.enable_log, + pre_dispatch=self.pre_dispatch, + precompile_backend_id=self.precompile_backend_id, + ) + + def __post_init__(self) -> None: + if self.pre_dispatch: + if not self.is_export: + raise AssertionError("Can only have pre_dispatch IR for export.") + + +# TODO: types here +# plain_tensor_trace_fn, when it is joint, has tuple structure on the trace +# info too! +# TODO: this needs to be generic, parameterized on AOTDescriptor +SubclassTracingInfo = collections.namedtuple( + "SubclassTracingInfo", + [ + "plain_tensor_trace_fn", + "plain_tensor_args", + "plain_tensor_args_descs", + "maybe_subclass_meta", + ], +) + + +@dataclass +class AOTState: + """ + When we run AOTAutograd, this class encapsulates the state in the compiler which + must be preserved across stages. This is state in the traditional sense (not an + environment) because some values in this structure change as we progress through + pipelines in AOTAutograd. + """ + + # Whether or not we need to handle autograd when doing graph capture and + # compilation. Although the calling convention for non-autograd graph + # capture in AOTAutograd is simple and can be relied upon, the autograd + # capture calling convention is quite complicated and in general you are + # only expected to pass to aot_stage2_compile to process. + needs_autograd: bool + + # The FAKE flat arguments which we will do tracing with. Although you + # might naively expect this to be immutable, it's not: when we perform + # tracing, we may execute code that modifies the metadata of inputs, + # causing the args to become "invalid". It's also nontrivial to have a + # "golden" set of fake values and deepcopy them just in time when you + # might destructively mutate them (Voz and I tried very hard to do this). + # So we just periodically renew this field. Don't worry too much about + # this unless you're specifically trying to track down an input metadata + # mutation bug. + # + # (By the way, this is NEVER the joint inputs! Those only ever go in + # AOTGraphCapture) + flat_args: list[FxValue] + + # The descriptor for each argument in flat_args. + flat_args_descs: list[AOTInput] + + # This contains view and mutation information about the function, which we + # detected by doing an initial trace when we created this state. + fw_metadata: ViewAndMutationMeta + + # Top-level configuration. Stage-local compiler choices are threaded + # explicitly rather than mutating this object in place. + aot_config: AOTConfig + + # When performing AOTAutograd traces and other passes, we typically + # require a lot of active context managers; most typically these either + # (1) ensure we are faithfully replicating the original PyTorch context + # managers or (2) toggle some behaviors in PyTorch to make it more + # suitable for tracing. When you use AOTState, you're expected to have + # created an ExitStack, entered it; then while we are running AOTAutograd + # we will add things onto the stack as necessary. When you're all done + # with processing AOTAutograd, you can exit this stack. All functions + # that take AOTState expect the ExitStack to not have been exited yet. + # + # TODO: We potentially could offer a resumable context manager, where you + # can cancel it and reenable it later when you need it. + stack: contextlib.ExitStack + + # The fake tensor mode used during tracing. This is useful for later + # operations that need to create new fake tensors consistent with the + # original trace. + fake_mode: FakeTensorMode + + +FxValue = Tensor | int | SymInt | BackwardState | CustomClassBase + + +class CompilerWrapper: + """ + AOTAutograd needs to do many transformations to the calling convention of the user function + it is tracing, e.g., deduplicating inputs, unpacking subclasses, etc. CompilerWrapper lets + us factor these into compositional stages so we can handle each transformation incrementally + instead of having to do it all at once. + + Since there is a calling convention change, there are two parts to the wrapper: + + 1. The prologue, which is about compile-time behavior: given this original function, what + is the new function with modified calling convention that we should trace with AOTAutograd + to get the FX graph we will do joint passes, partitioning and ultimate Inductor compilation on? + We get (flat_fn, flat_args), the original function under trace and inputs we were + going to feed it, and produce a new function and new inputs to feed it. + + 2. The epilogue, which is about run-time behavior: we have now compiled the modified calling + convention function, we need to wrap it so that we have a new function that has the + original calling convention of the original function, so that our users can call it + at the old signature they expected. We get (compiled_fn, real arguments), the newly + compiled function we need to wrap. + + Note about caching: we do NOT directly serialize the runtime wrappers; instead, they + are reapplied to compiled_fn after we have finished deserializing the compiled_fn. + + Extra metadata that is needed to compute pre or post compile can be passed in via attributes. + """ + + def pre_compile( + self, + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[TraceFn, list[FxValue], list[AOTInput], ViewAndMutationMeta]: + """ + Process the inputs to the compiler_fn. You can pass in extra metadata via kwargs. + Args: + flat_fn: The function to compile + flat_args: Metadata from example inputs of the function to compile + aot_config: AOTConfig passed in at compile time + fw_metadata: ViewAndMutationMeta generated from flat_fn and flat_args + """ + return flat_fn, flat_args, flat_args_descs, fw_metadata + + def post_compile( + self, + compiled_fn: Callable[_P, _R], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[_P, _R]: + """ + Given an output of the compiler, wrap it with information received from prologue. + Args: + compiled_fn: Callable after calling compiler_fn + aot_config: AOTConfig after calling prologue + runtime_metadata: ViewAndMutationMeta after calling all wrappers's pre_compile steps. + Example: + + def wrapped_compiled_fn(args): + # do something with args, aot_config, fw_metadata + return compiled_fn(args) + + return wrapped_compiled_fn + """ + return compiled_fn + + +class InductorWrapper: + """ + This is sort of like CompilerWrapper, but it happens at a different part of the lifecycle: + it talks about transformations we do to the traced and partitioned FX graph before we + send it to the Inductor compiler. + + Once again, there are two parts: + + 1. The prologue, which "modifies" the FX graph before we send it to + Inductor. I say "modifies" because... we don't really actually do + anything nontrivial in either of our two implementations. + 2. The epilogue, which modifies the compiled function produced by Inductor + + Although hypothetically these wrappers could be used compositionally in a centralized + wrappers list, in practice they seem to just be invoked manually when needed. + + NB: The flat_args input is sometimes mutated. This is probably naughty but whatever. + """ + + def pre_compile( + self, + fw_module: torch.fx.GraphModule, + flat_args: list[Tensor], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> None: + """ + Process the inputs to the compiler_fn. You can pass in extra metadata via kwargs. + Args: + flat_fn: The function to compile + flat_args: Metadata from example inputs of the function to compile + aot_config: AOTConfig passed in at compile time + fw_metadata: ViewAndMutationMeta generated from flat_fn and flat_args + """ + return + + def post_compile( + self, + compiled_fn: Callable[_P, _R], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[_P, _R]: + """ + Given an output of the compiler, wrap it with information received from prologue. + Args: + compiled_fn: Callable after calling compiler_fn + aot_config: AOTConfig after calling prologue + runtime_metadata: ViewAndMutationMeta after calling all wrappers's pre_compile steps. + Example: + + def wrapped_compiled_fn(args): + # do something with args, aot_config, fw_metadata + return compiled_fn(args) + + return wrapped_compiled_fn + """ + return compiled_fn + + +@dataclass +class AOTGraphCapture: # Produced by aot_stage1_graph_capture + # AOTAutograd typically operates by taking complicated graphs and + # desugaring them into simpler graphs that use PyTorch features. These + # wrappers establish invariants so that when we actually do tracing we can + # assume these invariants hold, leading to a simpler tracing + # implementation. However, this means that we have to keep track of how + # to enter/exit these wrappers when passing inputs into the compiled + # graph, among other things! + wrappers: list[CompilerWrapper] + + # The actual captured graph module. In some circumstances (export) this + # graph has a specific calling convention that can be relied upon by + # external callers. In other situations, the calling convention is + # unspecified and only aot_stage2_compile knows how to deal with them. + graph_module: torch.fx.GraphModule + + # When compiling with autograd support, this is the joint_inputs, which is + # larger than the original flat_args as all tangents get inputs. The + # tuple organizes into primals and tangents. When not autograd it's just + # a plain list. + updated_flat_args: list[Any] | tuple[list[Any], list[Any]] + + updated_flat_args_descs: list[AOTInput] | tuple[list[AOTInput], list[AOTInput]] + + # Metadata about subclass inputs/outputs in the graph trace. + maybe_subclass_meta: Any + + +FakifiedFlatArgs = NewType("FakifiedFlatArgs", list[Any]) + + +TOutputCode = TypeVar("TOutputCode", bound="OutputCode") + + +class AOTDispatchCompiler(Protocol): + """ + Represents a fw or bw_compiler passed to AOTAutograd. + """ + + def __call__( + self, + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType], + ) -> Any: ... + + +# TODO: bikeshed on this name +class SerializableAOTDispatchCompiler(AOTDispatchCompiler): + """ + Represents an AOTDispatchCompiler that returns an OutputCode, and is + therefore cacheable. SerializableAOTDispatchCompiler always return an OutputCode. + A _CompileFxCallable usually gets converted into an AOTDispatchCompiler after binding all of + the kwargs in _CompileFxKwargs. + """ + + def __init__( + self, + output_code_ty: type[TOutputCode], + compiler_fn: Callable[[torch.fx.GraphModule, Sequence[InputType]], TOutputCode], + ) -> None: + # pyrefly: ignore [invalid-type-var] + self.output_code_ty = output_code_ty + # pyrefly: ignore [invalid-type-var] + self.compiler_fn = compiler_fn + + def __call__( + self, + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType], + ) -> OutputCode: + output_code = self.compiler_fn(gm, example_inputs) + return output_code + + +class FlatFn(Protocol): + def __call__(self, *args: FxValue) -> list[FxValue]: ... + + +class TraceFn(Protocol): + def __call__(self, *args: FxValue) -> tuple[list[FxValue], list[AOTOutput]]: ... + + +class PreppedForAutogradTraceFn(Protocol): + def __call__( + self, + *args: FxValue, + ) -> tuple[tuple[list[FxValue], list[bool]], list[AOTOutput]]: ... + + +class JointTraceFn(Protocol): + handle: JointFnHandle + + def __call__( + self, primals: list[FxValue], tangents: list[FxValue] + ) -> tuple[ + tuple[list[FxValue], list[Tensor | None]], + tuple[list[AOTOutput], list[AOTOutput | None]], + ]: ... + + +@dataclass +class JointWithDescriptors: + _aot_state: AOTState + _aot_graph_capture: AOTGraphCapture + + # The exact order parameters and buffers are expected to be passed into + # the final compiled function. Parameters before buffers. + params_spec: list[str] + buffers_spec: list[str] + + in_spec: pytree.TreeSpec + out_spec: pytree.TreeSpec + + @property + def graph_module(self) -> torch.fx.GraphModule: + return self._aot_graph_capture.graph_module + + @graph_module.setter + def graph_module(self, value: torch.fx.GraphModule) -> None: + self._aot_graph_capture.graph_module = value + + @property + def fake_mode(self) -> FakeTensorMode: + return self._aot_state.fake_mode + + def cache_hash(self) -> str: + """ + Return a hash string suitable for use as a cache key. This method + exists to decouple cache key generation from __str__/__repr__, so + that display-oriented changes don't accidentally affect caching. + """ + from hashlib import sha256 + + return sha256(str(self).encode("utf-8")).hexdigest() diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/source_emit.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/source_emit.py new file mode 100644 index 0000000000000000000000000000000000000000..23799fb6522c2690ae284173e47e8940a8b0c681 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/source_emit.py @@ -0,0 +1,537 @@ +"""Reconstruct live Python values as standalone, auditable source. + +The composer (to_standalone_python.py) inlines AOTAutograd's runtime wrappers, which +close over baked metadata objects (view-replay recipes, tensor-subclass specs, ...). +This module turns such a live object into a Python expression that reconstructs an +EQUAL value -- emitted as readable source, never a pickle / base64 blob -- or raises +NotImplementedError if it cannot be expressed. ``emit_value`` is the public entry +point; ``_emit_value`` is the internal recursion (it threads the traversal state); +``_emit_via_reduce`` is the pickle-reduce-as-source fallback and ``_REBUILD_HELPER`` is +the ``_rebuild`` function it references in generated code. Kept as a leaf module so it +is safe to import anywhere in the package. +""" + +from __future__ import annotations + +import inspect +from typing import Any, NewType, TYPE_CHECKING + + +# id() returns an object identity used here only as a recursion/alias key, not an +# arbitrary int. Shadowing the builtin under TYPE_CHECKING tags every ``id(obj)`` as +# ``_ObjId`` so ``set[_ObjId]`` propagates without wrapping each call site; the real +# builtin runs at runtime (NewType is identity), so behavior is unchanged. +_ObjId = NewType("_ObjId", int) + +if TYPE_CHECKING: + + def id(obj: object, /) -> _ObjId: ... + + +# The runtime helper for reduce-based metadata reconstruction (see _emit_via_reduce). +# Emitted only when some baked value actually needs it -- many graphs (e.g. a plain +# module with no tensor-subclass metadata) reference none, so it would just be dead +# code. Includes its own trailing blank lines so the splice stays clean. +_REBUILD_HELPER: list[str] = [ + "def _rebuild(obj, state):", + " # Apply pickle-style reduce state to a freshly __new__'d object, emitted as", + " # readable source instead of an opaque blob (no pickle.loads). Used for the", + " # opaque value leaves of baked metadata -- e.g. tensor-subclass placement", + " # objects -- mirroring pickle's load_build: prefer __setstate__, else update", + " # __dict__ (and slot state for the (dict, slots) 2-tuple form).", + " if state is None:", + " return obj", + " if hasattr(obj, '__setstate__'):", + " obj.__setstate__(state)", + " return obj", + " slotstate = None", + " if isinstance(state, tuple) and len(state) == 2:", + " state, slotstate = state", + " if state:", + " obj.__dict__.update(state)", + " if slotstate:", + " for _k, _v in slotstate.items():", + " setattr(obj, _k, _v)", + " return obj", + "", + "", +] + + +def _emit_importable(obj: Any, imports: set[str]) -> str: + """Return an expression referencing ``obj`` via its defining module (recording the + import). Works for classes, functions, and modules. Raises if ``obj`` is not + reachable as ``module.qualname`` (e.g. a local or lambda), since then it cannot be + reproduced in the standalone module without embedding it.""" + import importlib + + module = getattr(obj, "__module__", None) + qualname = getattr(obj, "__qualname__", None) + if not module or not qualname or "<" in qualname: + raise NotImplementedError( + f"compile_to_python cannot reference {obj!r} by import: it has no " + "module/qualname or is a local definition." + ) + target: Any = importlib.import_module(module) + for part in qualname.split("."): + target = getattr(target, part, None) + if target is not obj: + raise NotImplementedError( + f"compile_to_python cannot reference {qualname} from {module}: it does " + "not round-trip to the same object." + ) + imports.add(f"import {module}") + return f"{module}.{qualname}" + + +def _reject_shared_mutable(obj: Any, _seen: set[_ObjId]) -> None: + """Fail loud when a mutable object is reached more than once in a single traversal: + it would be emitted as two independent source literals, silently dropping the + shared-identity aliasing (mutating one copy would no longer affect the other), which + is not expressible as a source literal today. Routed here are the kinds reconstructed + as fresh MUTABLE copies whose aliasing a flat literal cannot preserve: list / dict / + set, bytearray, non-frozen dataclasses, and the opaque _emit_via_reduce value objects. + Kinds treated as immutable value objects are exempt -- scalars, tuple / frozenset, frozen + dataclasses, and the recipe-like value objects emitted by their own branches + (functools.partial, ViewMeta, ViewMetaSequence), which are never mutated after + reconstruction -- so a shared one of those still emits fine. ``_seen`` is threaded in + place across the whole traversal (unlike the per-level in-progress cycle set), so it + catches shared siblings, not just self-referential ancestors.""" + if id(obj) in _seen: + raise NotImplementedError( + f"compile_to_python cannot bake a shared mutable {type(obj).__qualname__}: " + "it is reached more than once in the value being baked, so emitting it as " + "independent source literals would silently drop the shared-identity " + "aliasing." + ) + _seen.add(id(obj)) + + +def emit_value(obj: Any, imports: set[str]) -> str: + """Emit a Python expression (valid in the generated module) that rebuilds ``obj`` + from source -- the pickle-free replacement for embedding a base64 blob. + + Public entry point: recurses through containers and metadata so the artifact stays + auditable and exec'ing it never runs ``pickle.loads``. Bottoms out for opaque value + objects (e.g. tensor-subclass placement objects) at the pickle reduce protocol, but + EMITTED AS SOURCE via ``_rebuild`` (see ``_emit_via_reduce``). Raises + NotImplementedError at any leaf that cannot be expressed as source (a live tensor, a + lambda, a still-symbolic Sym*), for a self-referential structure, or for a shared + mutable object whose aliasing a flat source literal cannot preserve. + + Any import needed by the emitted expression is recorded into ``imports`` (as ``import + module`` statements).""" + return _emit_value(obj, imports, set(), set()) + + +def _emit_value( + obj: Any, + imports: set[str], + _in_progress: set[_ObjId], + _seen: set[_ObjId], +) -> str: + """Internal recursion behind ``emit_value``; requires the traversal state its guards + thread. Call ``emit_value`` from outside this module. + + ``_in_progress`` is an identity-keyed set of the objects currently being emitted on + this recursion PATH (copied per level, like a call stack): revisiting one means the + metadata is self-referential and cannot be a source literal, so we raise rather than + recurse forever. ``_seen`` is an identity-keyed set of every MUTABLE object already + emitted anywhere in this traversal (threaded in place, like ``imports``): revisiting + one means the same mutable object is shared across positions, whose aliasing a flat + literal cannot preserve, so we raise (see ``_reject_shared_mutable``).""" + import dataclasses + import enum + import functools + import math + import types + + import torch + from torch._C import _functionalization as _F + from torch.fx.experimental.symbolic_shapes import SymIntEqByExpr + + from .functional_utils import ViewMetaSequence + + # Live tensors / storages must never be baked: their reduce form is a + # ``torch.storage._load_from_bytes(b'...')`` pickle blob, which both embeds the + # raw weight bytes and invokes ``pickle.loads`` at exec time -- violating the + # module's no-weights-baked / never-pickle.loads / fully-auditable guarantees. + # Reject them explicitly here, before they can fall through to _emit_via_reduce. + # A non-Tensor object whose reduce IS ``_load_from_bytes`` (a wrapper that + # delegates pickling to a storage's bytes) is caught at the reduce callable in + # _emit_via_reduce, where that callable is actually visible. + if isinstance( + obj, (torch.Tensor, torch.storage.TypedStorage, torch.UntypedStorage) + ): + raise NotImplementedError( + f"compile_to_python cannot bake a live {type(obj).__qualname__} into " + "standalone source: that would embed raw tensor bytes and require " + "pickle.loads at exec time. The standalone artifact bakes no weights." + ) + + # Primitives first, before any cycle / alias bookkeeping: those guards never matter + # for immutable scalars, and returning here skips the per-level in-progress copy and + # the mutable-alias check for the (very common) scalar leaves. + # + # Non-finite floats: repr() gives bare ``inf`` / ``-inf`` / ``nan``, which are + # NameErrors in the generated module (it imports no such names). Emit a + # self-contained constructor instead. Likewise for a complex with a non-finite + # component (repr would be e.g. ``(inf+0j)``). + if isinstance(obj, float) and not math.isfinite(obj): + if math.isnan(obj): + return "float('nan')" + return "float('inf')" if obj > 0 else "float('-inf')" + if isinstance(obj, complex) and not ( + math.isfinite(obj.real) and math.isfinite(obj.imag) + ): + # Use the module-level recursion directly (the in-body shadow is not defined until + # after the guards below); the components are floats, so they bottom out above. + real = _emit_value_recurse(obj.real, imports, _in_progress, _seen) + imag = _emit_value_recurse(obj.imag, imports, _in_progress, _seen) + return f"complex({real}, {imag})" + # Plain constants reproduce via repr (but not IntEnum/StrEnum members, whose repr + # is not valid source -- those fall through to the enum handler below). Match EXACT + # builtin types only: a subclass of a builtin scalar (e.g. a ``str`` subclass, or an + # ``int`` subclass with a constructor-style ``__repr__``) would mis-bake under repr + # -- losing its type or emitting a NameError -- so it must fall through to the + # importable/reduce path, which reconstructs it faithfully or raises. + if obj is None or ( + not isinstance(obj, enum.Enum) + and type(obj) in (bool, int, float, complex, str, bytes) + ): + return repr(obj) + # bytearray is the one mutable builtin whose repr round-trips, so it is emitted as a + # repr literal like the immutable scalars above -- but being mutable it needs the same + # shared-alias guard the containers get (reached twice it would become two independent + # literals, silently dropping the aliasing). It cannot be self-referential, so it needs + # only the alias check and no cycle guard. + if type(obj) is bytearray: + _reject_shared_mutable(obj, _seen) + return repr(obj) + + # Cycle guard: thread an identity-keyed in-progress set down the recursion so a + # self-referential metadata object raises NotImplementedError naming the offending + # type instead of recursing until RecursionError. Primitives already returned above, + # so no immutable-scalar exemption is needed here. + if id(obj) in _in_progress: + raise NotImplementedError( + f"compile_to_python cannot bake {type(obj).__qualname__}: it is " + "self-referential, which is not expressible as source." + ) + # Alias guard: a mutable container reached twice anywhere in the traversal would be + # emitted as two independent literals, silently dropping the shared-identity aliasing. + # Match EXACT list/dict/set only -- those are the types the container branches below + # emit; a subclass falls through to _emit_via_reduce, which tracks it there (matching + # here too would double-count the same object and falsely reject a single subclass). + if type(obj) in (list, dict, set): + _reject_shared_mutable(obj, _seen) + + _child = _in_progress | {id(obj)} + + def _emit_value(obj: Any, imports: set[str]) -> str: + # Shadow the module-level recursion entry point so every recursive call in + # this function body automatically threads the current in-progress set (with + # the parent ``obj`` added) plus the traversal-wide seen set, without touching + # each call site. + return _emit_value_recurse(obj, imports, _child, _seen) + + # torch scalar singletons whose repr round-trips, plus device/Size/SymInt. + if isinstance(obj, (torch.dtype, torch.layout, torch.memory_format)): + imports.add("import torch") + return repr(obj) + if isinstance(obj, torch.device): + imports.add("import torch") + return f"torch.device({str(obj)!r})" + if isinstance(obj, torch.Size): + imports.add("import torch") + return f"torch.Size([{', '.join(_emit_value(x, imports) for x in obj)}])" + if isinstance(obj, torch.SymInt): + concrete = obj.node.maybe_as_int() + if concrete is None: + raise NotImplementedError( + "compile_to_python cannot bake a symbolic SymInt; precompile " + "specializes to static shapes." + ) + return repr(concrete) + # SymBool / SymFloat get the same treatment as SymInt (bake the concrete value, reject + # a still-symbolic one with the static-shapes message) so all sym scalar types are + # handled consistently instead of falling into the reduce path with an opaque error. + if isinstance(obj, torch.SymBool): + concrete_bool = obj.node.maybe_as_bool() + if concrete_bool is None: + raise NotImplementedError( + "compile_to_python cannot bake a symbolic SymBool; precompile " + "specializes to static shapes." + ) + return repr(concrete_bool) + if isinstance(obj, torch.SymFloat): + concrete_float = obj.node.maybe_as_float() + if concrete_float is None: + raise NotImplementedError( + "compile_to_python cannot bake a symbolic SymFloat; precompile " + "specializes to static shapes." + ) + return repr(concrete_float) + + # Importable definitions: classes, functions, modules. + if isinstance(obj, type) or inspect.isfunction(obj) or inspect.isbuiltin(obj): + return _emit_importable(obj, imports) + if isinstance(obj, types.ModuleType): + imports.add(f"import {obj.__name__}") + return obj.__name__ + + # Python enums and pybind11 enums (e.g. InverseReturnMode) both reference a member + # by name off the importable type. pybind enum members are not singletons (as_tuple + # hands back fresh copies), so match by value via the type's __members__ map. + members = getattr(type(obj), "__members__", None) + name = getattr(obj, "name", None) + is_enum_like = isinstance(obj, enum.Enum) or ( + members is not None and name in members and members[name] == obj + ) + if is_enum_like: + if name is not None and members is not None and name in members: + return f"{_emit_importable(type(obj), imports)}.{name}" + # A combined Flag/IntFlag member (A | B) has no single member name, so emit by + # value -- ``Type(value)`` reproduces the same combined member. A non-Flag enum + # with no resolvable name is not source-expressible, so reject it rather than + # emit ``Type.None`` (a SyntaxError that would break the whole module). + if isinstance(obj, enum.Flag): + cls = _emit_importable(type(obj), imports) + return f"{cls}({_emit_value(obj.value, imports)})" + # Defensive backstop, effectively unreachable for constructible inputs: a + # pure-Python non-Flag enum.Enum always resolves a name in __members__ (it rejects + # unregistered values with ValueError) and so returns by-name above, and a pybind + # enum-like value only reaches here via the ``name in members`` arm that already + # returned. Kept so any future name-less enum-like type fails loudly, not silently. + raise NotImplementedError( + f"compile_to_python cannot bake enum member {obj!r}: it has no resolvable " + "member name and is not a Flag." + ) + + if isinstance(obj, functools.partial): + parts = [_emit_value(obj.func, imports)] + parts += [_emit_value(a, imports) for a in obj.args] + parts += [ + f"{k}={_emit_value(v, imports)}" for k, v in (obj.keywords or {}).items() + ] + imports.add("import functools") + return f"functools.partial({', '.join(parts)})" + + # AOT view-replay recipes: ViewMeta C++ objects round-trip through as_tuple(); + # ViewMetaSequence has no public constructor so use its _from_parts factory; + # SymIntEqByExpr wraps a sympy expr that must be a concrete integer here. + if isinstance(obj, _F.ViewMeta): + # as_tuple lives on the ViewMeta subclass bindings (create_binding_with_pickle), + # not on the base ViewMeta stub, so pyrefly cannot see it on the isinstance type. + tup = obj.as_tuple() # pyrefly: ignore[missing-attribute] + return f"{_emit_importable(type(obj), imports)}({_emit_value(tuple(tup), imports)})" + if isinstance(obj, ViewMetaSequence): + cls = _emit_importable(ViewMetaSequence, imports) + seq = _emit_value(list(obj.sequence), imports) + return f"{cls}._from_parts({seq}, {_emit_value(obj.metadata, imports)})" + if isinstance(obj, SymIntEqByExpr): + if not getattr(obj.val, "is_Integer", False): + raise NotImplementedError( + "compile_to_python cannot bake symbolic view metadata; precompile " + "specializes to static shapes." + ) + return f"{_emit_importable(SymIntEqByExpr, imports)}({int(obj.val)})" + + # namedtuple before plain tuple (it has a richer, by-name constructor). The plain + # container branches match EXACT builtin types only (like the scalar branch above): a + # container SUBCLASS (e.g. a ``list`` subclass carrying extra state) would otherwise be + # silently downcast to its base type, dropping the subclass and its state. Subclasses + # fall through to _emit_via_reduce, which reconstructs them faithfully or rejects them + # (its listitems/dictitems guard fires for list/dict subclasses). + if isinstance(obj, tuple) and hasattr(obj, "_fields"): + cls = _emit_importable(type(obj), imports) + return f"{cls}({', '.join(_emit_value(x, imports) for x in obj)})" + if type(obj) is tuple: + items = [_emit_value(x, imports) for x in obj] + return f"({items[0]},)" if len(items) == 1 else f"({', '.join(items)})" + if type(obj) is list: + return f"[{', '.join(_emit_value(x, imports) for x in obj)}]" + if type(obj) is set or type(obj) is frozenset: + ctor = "frozenset" if isinstance(obj, frozenset) else "set" + # Iteration order of a set is not byte-stable across processes, so emit the + # elements in a canonical order: sort them by their EMITTED SOURCE EXPRESSION -- + # the exact text that lands in the artifact, so it is the only key guaranteed to + # be byte-stable across processes. A ``repr``-keyed sort would silently admit a + # custom-but-nondeterministic ``__repr__`` (e.g. one embedding ``id(self)``), + # making the emitted source differ run to run, and a numeric sort would raise on a + # ``nan`` element (``sorted`` does not) and does not exist for mixed types. Each + # element is emitted exactly once (into the real ``imports``, since every element + # emitted is one that lands in the output) and then the resulting expressions are + # sorted -- which forces each element through the same source-expressibility gate, + # so a non-source-expressible element raises here exactly as at final emit. + exprs = sorted(_emit_value(x, imports) for x in obj) + return f"{ctor}([{', '.join(exprs)}])" + if type(obj) is dict: + items = [ + f"{_emit_value(k, imports)}: {_emit_value(v, imports)}" + for k, v in obj.items() + ] + return f"{{{', '.join(items)}}}" + + # Dataclasses (e.g. MetadataKey, SubclassViewMetaSequence) reproduce field-by-field + # through their generated constructor, passing only the init fields. That path is + # faithful ONLY when the object carries no state outside those init fields: a + # non-init field (init=False) holding state, or a __post_init__ that derives state + # the constructor call would not reproduce, would be silently dropped. Guard it the + # same way the rest of this module guards opaque leaves -- reject rather than emit a + # subtly-wrong artifact -- by round-tripping through the constructor and requiring + # the rebuilt instance to compare equal to the original. The in-scope metadata + # types (e.g. MetadataKey) are plain value dataclasses, so they round-trip and keep + # working; a type with hidden/derived state does not and raises NotImplementedError + # naming itself. This strategy needs value equality: a dataclass declared eq=False + # inherits object.__eq__ (identity), so rebuilt == obj is ALWAYS False even for a + # pure value object -- detect that and fall through to _emit_via_reduce (which has its + # own source-expressibility rejects) rather than spuriously rejecting it. + if ( + dataclasses.is_dataclass(obj) + and not isinstance(obj, type) + and type(obj).__eq__ is not object.__eq__ + ): + # A non-frozen dataclass is mutable, so it gets the same shared-alias guard as the + # containers: reached twice it would be emitted as two independent constructor + # calls, silently dropping the shared-identity aliasing. A frozen dataclass is + # immutable and stays exempt, like a tuple. + if not obj.__dataclass_params__.frozen: + _reject_shared_mutable(obj, _seen) + cls = _emit_importable(type(obj), imports) + fields = dataclasses.fields(obj) + init_kwargs = {f.name: getattr(obj, f.name) for f in fields if f.init} + try: + # type(obj) is the concrete dataclass at runtime, not the protocol pyrefly + # infers from the is_dataclass narrowing; the call is correct. + rebuilt = type(obj)(**init_kwargs) # pyrefly: ignore[bad-instantiation] + round_trips = rebuilt == obj + except Exception: + round_trips = False + if not round_trips: + raise NotImplementedError( + f"compile_to_python cannot bake dataclass {type(obj).__qualname__}: it " + "does not round-trip through its constructor from its init fields alone " + "(it likely has a stateful non-init field or a __post_init__ deriving " + "state the constructor call would not reproduce), so emitting only the " + "init fields would silently drop that state." + ) + kw = [f"{k}={_emit_value(v, imports)}" for k, v in init_kwargs.items()] + return f"{cls}({', '.join(kw)})" + + return _emit_via_reduce(obj, imports, _child, _seen) + + +# The recursion entry point used by the in-body shadow of ``_emit_value`` and by +# ``_emit_via_reduce`` to thread the identity-keyed in-progress + seen traversal sets. +_emit_value_recurse = _emit_value + + +def _emit_via_reduce( + obj: Any, + imports: set[str], + _in_progress: set[_ObjId], + _seen: set[_ObjId], +) -> str: + """Last resort for opaque value objects (e.g. DTensor placements, which are C++ + objects with no source-friendly constructor): reconstruct from the pickle reduce + protocol, but EMITTED AS SOURCE -- ``cls.__new__(cls)`` plus ``_rebuild`` applying + the reduce state -- so there is no ``pickle.loads`` at exec time and the bytes + are readable. The reduce state recurses back through ``_emit_value``, so any + non-source-expressible leaf inside it still raises.""" + import copyreg + + import torch + + # These reduce value objects are mutable, so the same guard the containers get in + # _emit_value applies: an object reached twice would be emitted as two independent + # reconstructions, silently dropping the shared-identity aliasing. + _reject_shared_mutable(obj, _seen) + + def _emit_value(obj: Any, imports: set[str]) -> str: + # Continue threading the cycle guard + seen set through the reduce-state recursion. + return _emit_value_recurse(obj, imports, _in_progress, _seen) + + try: + reduced = obj.__reduce_ex__(2) + except Exception as e: + raise NotImplementedError( + f"compile_to_python cannot make {type(obj).__module__}." + f"{type(obj).__qualname__} self-contained: it is not source-expressible " + f"and has no usable reduce ({type(e).__name__})." + ) from e + if not isinstance(reduced, tuple) or len(reduced) < 2: + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: " + "unsupported __reduce__ form." + ) + func, args = reduced[0], reduced[1] + # The reduce protocol requires the second element to be a tuple of constructor args; + # validate once here so all three func branches below normalize a malformed reduce + # into the uniform NotImplementedError contract rather than leaking a bare TypeError. + if not isinstance(args, tuple): + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: reduce " + "args field is not a tuple." + ) + state = reduced[2] if len(reduced) > 2 else None + listitems = reduced[3] if len(reduced) > 3 else None + dictitems = reduced[4] if len(reduced) > 4 else None + # A reduce whose callable is ``torch.storage._load_from_bytes`` would embed raw + # bytes and require a pickle.loads-equivalent at exec time. This is the ONLY place + # that callable is visible (it is the reduce result's func, not the object's + # __reduce_ex__ method), so reject it here to uphold the no-bytes / fully-auditable + # guarantee for any non-Tensor wrapper that delegates pickling to storage bytes. + if func is getattr(torch.storage, "_load_from_bytes", None): + raise NotImplementedError( + f"compile_to_python cannot bake {type(obj).__qualname__} into standalone " + "source: its reduce is torch.storage._load_from_bytes, which would embed " + "raw bytes and require pickle.loads at exec time." + ) + if listitems is not None or dictitems is not None: + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: reduce " + "produced list/dict items (container subclass)." + ) + # A non-None 6th element is a protocol-5 ``state_setter``: the object opted out of + # the default __setstate__/__dict__ install that ``_rebuild`` implements, so applying + # state via _rebuild would silently use the wrong mechanism. Reject rather than emit + # a subtly-wrong object. + state_setter = reduced[5] if len(reduced) > 5 else None + if state_setter is not None: + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: reduce " + "produced a state_setter (protocol-5 form) that _rebuild cannot apply." + ) + if func is getattr(copyreg, "__newobj__", None): + if not args: + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: " + "__newobj__ reduce produced no class argument." + ) + cls = _emit_value(args[0], imports) + extra = ", ".join(_emit_value(a, imports) for a in args[1:]) + base = f"{cls}.__new__({cls}{', ' + extra if extra else ''})" + elif func is getattr(copyreg, "__newobj_ex__", None): + if not ( + isinstance(args, tuple) + and len(args) == 3 + and isinstance(args[1], tuple) + and isinstance(args[2], dict) + ): + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: " + "__newobj_ex__ reduce did not produce a (cls, args, kwargs) triple." + ) + cls_obj, new_args, new_kwargs = args + cls = _emit_value(cls_obj, imports) + pos = ", ".join(_emit_value(a, imports) for a in new_args) + kw = ", ".join(f"{k}={_emit_value(v, imports)}" for k, v in new_kwargs.items()) + joined = ", ".join(p for p in (pos, kw) if p) + base = f"{cls}.__new__({cls}{', ' + joined if joined else ''})" + else: + func_expr = _emit_value(func, imports) + base = f"{func_expr}({', '.join(_emit_value(a, imports) for a in args)})" + if state is None: + return base + return f"_rebuild({base}, {_emit_value(state, imports)})" diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/standalone_runtime.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/standalone_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..9c02774b31ff745648edfdf839518df334a8d256 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/standalone_runtime.py @@ -0,0 +1,43 @@ +"""Runtime-support surface for standalone artifacts. + +Modules emitted by ``torch._functorch.aot_autograd.compile_to_python`` inline +AOTAutograd's codegen'd prelude/epilogue, which closes over a few small runtime +helpers (output-alias regeneration, etc.). Rather than have the generated code +reach into scattered AOTAutograd internals -- whose exact locations are not a +stable contract -- it imports those helpers from this one module. This is the +intentional, single dependency surface of a standalone artifact: keep it small and +stable, and update generated-artifact compatibility deliberately if it changes. +""" + +# Importing ``runtime_wrappers`` directly in a fresh process pulls in a name +# (e.g. AutogradLazyBackwardCompileInfo) that is only bound once the dynamo init +# chain has run, so importing it first triggers a circular ImportError. Force the +# dynamo/aot chain to fully initialize before the ``from .runtime_wrappers`` +# import below so a bare ``import torch`` artifact stays self-contained. +import torch._dynamo # noqa: F401 +from torch._prims_common import CUDARngStateHelper + +# IDENTITY CONTRACT: these names MUST be plain re-exports that preserve the original +# object identity -- never wrap, decorate, or alias them (e.g. functools.wraps, a thin +# forwarding lambda, a partial). to_standalone_python._known_helper_table keys on +# id() of these exact objects to recognize a global the codegen'd wrappers close over. +# A wrapper would change id(), so the table lookup would silently miss and that global +# would route to its internal AOTAutograd location instead of this stable surface. +# The same contract covers ``CUDARngStateHelper`` (imported above for circular-import +# ordering): the table keys on id() of its ``get_torch_state_as_tuple`` / +# ``set_new_offset`` staticmethods, so it too must not be wrapped or aliased. +from .functional_utils import gen_alias_from_base +from .runtime_wrappers import ( + _unwrap_tensoralias, + mark_dynamo_propagated_dynamic_indices, +) +from .utils import normalize_as_list + + +__all__ = [ + "gen_alias_from_base", + "_unwrap_tensoralias", + "mark_dynamo_propagated_dynamic_indices", + "normalize_as_list", + "CUDARngStateHelper", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/streams.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..63e21f66b6af249adfdd672e29e80660cfc0f489 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/streams.py @@ -0,0 +1,979 @@ +import operator +from collections.abc import Callable +from typing import Any, TYPE_CHECKING, TypeAlias + +import torch.fx +import torch.fx.traceback +import torch.utils._pytree as pytree +from torch._dynamo.graph_utils import _get_flat_args +from torch._dynamo.variables.streams import get_current_stream, new_event +from torch.fx.node import map_arg +from torch.utils._ordered_set import OrderedSet +from torch.utils._runtime_estimation import ( + _FLOAT_TYPES, + _IGNORE_OPS, + get_compute_time, + get_transfer_time, +) + + +if TYPE_CHECKING: + from .schemas import ViewAndMutationMeta + +from .indexed_dict import IndexedDict + + +aten = torch.ops.aten + +Node: TypeAlias = torch.fx.Node +Graph: TypeAlias = torch.fx.Graph +Partition: TypeAlias = bool + +FORWARD: Partition = False +BACKWARD: Partition = True +_EMPTY_LOCATIONS: frozenset[tuple[Partition, int]] = frozenset() + +_SYNC_OPS = ( + torch.ops.streams.record_event.default, + torch.ops.streams.wait_event.default, + torch.ops.streams.wait_stream.default, + torch.ops.streams.synchronize_event.default, + torch.ops.streams.synchronize_device.default, + torch.ops.streams.synchronize_stream.default, +) + + +def get_roofline_estimate(node: Node) -> float: + if node.op != "call_function": + raise AssertionError(f"non-func node in roofline estimate: {node.op}") + + def map_value(x: Any) -> Any: + return x.meta.get("value", x) if isinstance(x, Node) else x + + func = node.target + if func in _IGNORE_OPS: + return 0.0 + + mapped_args = torch.fx.map_arg(node.args, map_value) + mapped_kwargs = torch.fx.map_arg(node.kwargs, map_value) + flat_args_kwargs = [map_value(x) for x in _get_flat_args(node, {})] + flat_outs, _ = pytree.tree_flatten(node.meta.get("value", node)) + out = node.meta.get("value", node) + out_dtypes = { + t.dtype + for t in flat_outs + if isinstance(t, torch.Tensor) and t.dtype in _FLOAT_TYPES + } + + return ( + max( + get_transfer_time(flat_args_kwargs, flat_outs), + get_compute_time(func, mapped_args, mapped_kwargs, out, out_dtypes), + ) + / 1e6 + ) + + +def is_gradient_acc(node: Node) -> bool: + return node.meta.get("is_gradient_acc", False) + + +def is_bwd_node(node: Node) -> Partition: + tag = node.meta.get("partitioner_tag") + return tag == "is_backward" or tag == "must_be_in_backward" + + +def get_device(node: Node) -> torch.device: + return node.meta["val"].device + + +def get_stream(node: Node) -> int | None: + maybe_annotation = node.meta.get("custom", None) + if maybe_annotation is not None: + return node.meta["custom"].get("stream", None) + else: + return None + + +def get_stream_or_current_stream(node: Node) -> int: + ind = get_stream(node) + if ind is None: + ind = get_current_stream(get_device(node)) + return ind + + +def set_stream(node: Node, ind: int) -> None: + if "custom" in node.meta: + node.meta["custom"].update({"stream": ind}) + else: + node.meta["custom"] = {"stream": ind} + + +def insert_record_event_after_node(graph: Graph, node: Node, event_ind: int) -> Node: + with graph.inserting_after(node): + node = graph.call_function( + torch.ops.streams.record_event.default, + ( + event_ind, + get_stream_or_current_stream(node), + ), + ) + node.meta["partitioner_tag"] = "must_be_in_backward" + + return node + + +def insert_wait_event_before_node(graph: Graph, node: Node, event_ind: int) -> Node: + with graph.inserting_before(node): + node = graph.call_function( + torch.ops.streams.wait_event.default, + ( + event_ind, + get_stream_or_current_stream(node), + ), + ) + node.meta["partitioner_tag"] = "must_be_in_backward" + + return node + + +def populate_stream_timeline( + stream_to_timeline: dict[int | None, IndexedDict[Node, float]], + graph: Graph, + stream_index: int | None, +) -> IndexedDict[Node, float]: + if stream_index not in stream_to_timeline: + stream_to_timeline[stream_index] = IndexedDict() + total_time = 0.0 + for node in graph.nodes: + # mlazos: not sure if we should include forward here too but don't think it matters + if ( + node.op == "call_function" + and is_bwd_node(node) + and get_stream(node) == stream_index + ): + total_time += get_roofline_estimate(node) + stream_to_timeline[stream_index][node] = ( + total_time # NB: total time includes the node's runtime + ) + + return stream_to_timeline[stream_index] + + +# NB: we start all estimates at 0, estimating the total runtime of each stream with timestamps at each node +# we then try and use these timestamps to estimate when to deallocate tensors used in side streams +# See https://docs.pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html#torch.Tensor.record_stream +# for details on the problem being addressed. Rather than using the automatic memory management approach of record_stream +# we attempt to find the point which to deallocate based on the estimated timestamps. +def handle_synced_deallocation( + graph: Graph, + stream_to_exec_trace: dict[int | None, IndexedDict[Node, float]], + node: Node, + last_usage: Node, +) -> None: + if not is_bwd_node(node): + raise AssertionError( + "synced allocations should only be handled on backward nodes" + ) + if not is_bwd_node(last_usage): + raise AssertionError( + "synced allocations should only be handled on backward nodes" + ) + allocating_stream = get_stream(node) + side_stream = get_stream(last_usage) + if allocating_stream == side_stream: + raise AssertionError( + "allocating and side stream should be different for synced deallocations" + ) + if not torch.accelerator.is_available(): + # fallback to record_stream in this case + with graph.inserting_after(node): + rs = graph.call_function( + torch.ops.streams.record_stream.default, + ( + node, + get_stream_or_current_stream(last_usage), + ), + {}, + ) + rs.meta["partitioner_tag"] = "must_be_in_backward" + + allocating_stream_trace = populate_stream_timeline( + stream_to_exec_trace, graph, allocating_stream + ) + side_stream_trace = populate_stream_timeline( + stream_to_exec_trace, graph, side_stream + ) + + alloc_ptr = node + target_side_stream_time = side_stream_trace[last_usage] + # linear search from first usage of tensor to a point in time after the side stream has finished + while alloc_ptr is not None: + alloc_time = allocating_stream_trace[alloc_ptr] + + if alloc_time >= target_side_stream_time: + break + elif alloc_time < target_side_stream_time: + next_ptr = allocating_stream_trace.next_key(alloc_ptr) + if next_ptr is not None: + alloc_ptr = next_ptr + else: + break + + wait_event = new_event() + record_node = insert_record_event_after_node(graph, last_usage, wait_event) + with graph.inserting_after(max(alloc_ptr, record_node)): + sd = graph.call_function( + torch.ops.streams.sync_dealloc.default, + (wait_event, get_stream_or_current_stream(alloc_ptr), node), + {}, + ) + sd.meta["partitioner_tag"] = "must_be_in_backward" + + +def insert_sync( + graph: Graph, + consumer: Node, + producer: Node, + node_to_wait_event_ind: dict[Node, int], +) -> None: + if producer not in node_to_wait_event_ind: + node_to_wait_event_ind[producer] = new_event() + + insert_record_event_after_node( + graph, producer, node_to_wait_event_ind[producer] + ) + insert_wait_event_before_node(graph, consumer, node_to_wait_event_ind[producer]) + + +def assign_backward_streams(gm: torch.fx.GraphModule) -> None: + """Assigns backward streams to gradient accumulation nodes""" + + # NB: iterate in reverse order to more closely match eager + # the user node stream will be populated first + for node in reversed(list(gm.graph.nodes)): + if is_gradient_acc(node): + # Accumulation stream selection. Follow the rules from top to bottom to determine the accumulation stream: + # 1. Match first stream assignment of the first user with a stream + # 2. Match first stream assignment encountered in the args from left to right + # This differs from eager in some cases: + # Specifically the eager code uses the autograd node to determine the stream, + # crucially this does not necessarily correspond to the FX graph node. For example, + # in the backward for an add node with a constant we will passthrough and during backward tracing, + # no op will be added to the FX graph, so our stream assignment will differ in this case. + gradients = _get_flat_args(node, {}) + users = list(node.users.keys()) + + # All gradients will be on same device, they will be coerced if they were not with a .to() node + for neighbor in users + gradients: + ind = get_stream(neighbor) + if ind is not None: + set_stream(node, ind) + break + + +def insert_backward_syncs(gm: torch.fx.GraphModule) -> None: + """Inserts stream syncs for backward nodes if consumer and producer are on different streams""" + node_to_wait_event_ind: dict[Node, int] = {} + for node in gm.graph.nodes: + if node.op == "call_function" and is_bwd_node(node): + flat_args = _get_flat_args(node, {}) + cur_node_stream = get_stream(node) + + for arg in flat_args: + if arg.op == "call_function" and is_bwd_node(arg): + arg_stream = get_stream(arg) + if arg_stream != cur_node_stream and get_device(arg).type != "cpu": + insert_sync(gm.graph, node, arg, node_to_wait_event_ind) + + +def sync_deallocations(gm: torch.fx.GraphModule) -> None: + """Handles https://docs.pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html#torch.Tensor.record_stream""" + # Note: this is only needed if the last usage of a tensor is on a stream other than + # the stream the tensor was allocated on + + # an estimated timestamp from the beginning of graph execution (assuming 0 CPU overhead) + # I think this is fine because you should have large tensors if you're using streams + # although perhaps I could add a constant 10us per op ahead of the first stream op? + # a trace of all the nodes running in a given stream + stream_to_exec_trace: dict[int | None, IndexedDict[Node, float]] = {} + for node in gm.graph.nodes: + if node.op == "call_function" and is_bwd_node(node): + allocating_stream = get_stream(node) + users = list(node.users.keys()) + if not users: + continue + last_user = max(user for user in users) + if last_user.op == "output": + continue + side_stream = get_stream(last_user) + if allocating_stream != side_stream: + handle_synced_deallocation( + gm.graph, stream_to_exec_trace, node, last_user + ) + + +def assign_epilogue_copy_streams(gm: torch.fx.GraphModule) -> None: + for epi_copy in gm.graph.find_nodes(op="call_function", target=aten.copy_.default): + arg_stream = get_stream(epi_copy.args[1]) + copy_stream = get_stream(epi_copy) + if arg_stream != copy_stream: + set_stream(epi_copy, get_stream_or_current_stream(epi_copy.args[1])) + + +def populate_fw_metadata_with_stream_indices( + gm: torch.fx.GraphModule, fw_metadata: "ViewAndMutationMeta" +) -> None: + """ + Populates fw_metadata.mutated_inp_stream_indices with stream indices from the compiled graph. + + The forward graph outputs are structured as: + (*mutated_inputs, *user_outputs, *intermediate_bases, *saved_tensors, *saved_symints) + + We extract the stream index for each mutated input from the graph's output node. + """ + + num_mutated_inps = fw_metadata.num_mutated_inp_runtime_indices + if num_mutated_inps == 0: + fw_metadata.mutated_inp_stream_indices = [] + return + + # Find the output node in the graph + output_node = None + for node in gm.graph.find_nodes(op="output"): + output_node = node + break + + if output_node is None: + raise AssertionError( + "No output node found in the graph when extracting stream indices" + ) + + # The output node's args[0] is a tuple/list of all outputs + output_args = output_node.args[0] + + # Extract stream indices for the first num_mutated_inps outputs + stream_indices = [] + for i in range(num_mutated_inps): + if i < len(output_args): + output_arg = output_args[i] + # Get the stream index from the node metadata + stream_idx = ( + get_stream(output_arg) + if isinstance(output_arg, torch.fx.Node) + else None + ) + stream_indices.append(stream_idx) + else: + stream_indices.append(None) + + fw_metadata.mutated_inp_stream_indices = stream_indices + + +def _expand_dict_returning_deps( + deps: list[Node], + visited: set[Node], + graph: torch.fx.Graph, + sync_node: Node, +) -> list[Node]: + """Expand triton_kernel_wrapper_functional dict deps into per-key getitems. + + ``triton_kernel_wrapper_functional`` returns a flat ``dict[str, Tensor]``. + If such a node is threaded through ``control_deps`` as a pass-through + value, ``decompose_triton_kernel_wrapper_functional`` later replaces it + with a raw Python dict, corrupting every user that expected an FX Node. + + To avoid this, we insert ``operator.getitem`` nodes *before* the sync for + each after-sync getitem user, so that only tensor-valued nodes are passed + through ``control_deps``. The dict node may still appear in + ``additional_deps`` (ordering-only) which is safe since that tuple is + never decomposed. + """ + expanded: list[Node] = [] + for dep in deps: + if not ( + dep.op == "call_function" + and dep.target is torch.ops.higher_order.triton_kernel_wrapper_functional + ): + expanded.append(dep) + continue + + after_sync_getitems = [ + user + for user in dep.users + if user not in visited + and user.op == "call_function" + and user.target is operator.getitem + ] + if not after_sync_getitems: + expanded.append(dep) + continue + + with graph.inserting_before(sync_node): + for old_gi in after_sync_getitems: + key = old_gi.args[1] + new_gi = graph.call_function(operator.getitem, args=(dep, key)) + new_gi.meta.update(old_gi.meta) + if isinstance(new_gi.meta.get("val"), dict): + raise AssertionError( + f"nested dict in triton kernel output for key {key}" + ) + visited.add(new_gi) + expanded.append(new_gi) + old_gi.replace_all_uses_with(new_gi) + graph.erase_node(old_gi) + + return expanded + + +def _wrap_sync_node( + gm: torch.fx.GraphModule, + sync_node: Node, + deps_before_sync: list[Node], + visited: set[Node], + partition_scoped_deps: set[Node] | None = None, +) -> tuple[Node, list[Node]]: + """ + Core logic: wrap a single sync node in control_deps. + + Returns (control_deps_node, passthrough_getitems) where passthrough_getitems + are the getitem nodes that thread dependencies through the control_deps node. + ``visited`` is the set of nodes at or before the sync node in graph order, + used to distinguish pre-sync vs post-sync users. + """ + from torch._inductor.fx_passes.control_dependencies import ( + _create_subgraph_for_node, + control_deps, + get_subgraph_name, + ) + + graph = gm.graph + if partition_scoped_deps is None: + partition_scoped_deps = set() + + sync_is_bwd = is_bwd_node(sync_node) + + def _user_rewrite_pred(dep: Node) -> Callable[[Node], bool]: + if dep in partition_scoped_deps: + + def pred(user: Node) -> bool: + if user in visited: + return False + if user.op == "output": + return sync_is_bwd + return is_bwd_node(user) == sync_is_bwd + + return pred + + dep_is_bwd = is_bwd_node(dep) + + def pred(user: Node) -> bool: + return user not in visited and (user.op != "output" or dep_is_bwd) + + return pred + + # Use dep.users to find deps with uses after the sync — avoids a forward walk. + deps_with_uses_after_sync = [] + for dep in deps_before_sync: + pred = _user_rewrite_pred(dep) + if any(pred(user) for user in dep.users): + deps_with_uses_after_sync.append(dep) + + # Expand dict-returning nodes (triton_kernel_wrapper_functional) into + # individual getitem outputs. Passing a dict-valued node through + # control_deps breaks post-grad passes: reinplace + decomposition replace + # the dict node with a Python dict, corrupting any user that expected an + # FX Node. Unwrapping here ensures only tensor-valued nodes flow through. + deps_with_uses_after_sync = _expand_dict_returning_deps( + deps_with_uses_after_sync, visited, graph, sync_node + ) + + # Create subgraph that executes sync and passes through only used dependencies + subgraph_module = _create_subgraph_for_node( + graph, sync_node, deps_with_uses_after_sync + ) + subgraph_attr_name = get_subgraph_name(gm, sync_node.name) + setattr(gm, subgraph_attr_name, subgraph_module) + + # Create control_deps call + # Note: sync nodes (record_event/wait_event) only take int args, no Node args. + with graph.inserting_before(sync_node): + get_subgraph = graph.get_attr(subgraph_attr_name) + control_deps_node = graph.call_function( + control_deps, + args=( + tuple(deps_before_sync), # additional_deps (all deps for ordering) + get_subgraph, # subgraph + *deps_with_uses_after_sync, # only pass through deps that are used + ), + kwargs={}, + ) + + # Propagate partitioner_tag so the partitioner can distinguish + # forward vs backward sync control_deps during graph extraction. + if "partitioner_tag" in sync_node.meta: + control_deps_node.meta["partitioner_tag"] = sync_node.meta["partitioner_tag"] + + # Mark newly created nodes as visited so subsequent syncs don't + # misclassify them as "after the sync" during replacement. + visited.add(get_subgraph) + visited.add(control_deps_node) + + # The output is (sync_result, *deps_with_uses_after_sync) + # Reuse the val the subgraph output already carries: the min-cut + # partitioner's _size_of() raises on any node without `val`, and its escape + # hatch covers only get_attr and zero-return OpOverloads, not a schema-less + # HOP. The subgraph output is unwrapped when it has no pass-through deps. + sg_val = subgraph_module.graph.output_node().meta.get("val") + control_deps_node.meta["val"] = sg_val if isinstance(sg_val, tuple) else (sg_val,) + + # Create getitem nodes only for dependencies that have uses after sync + replacements: dict[Node, Node] = {} + with graph.inserting_after(control_deps_node): + for i, dep in enumerate(deps_with_uses_after_sync): + getitem_node = graph.call_function( + operator.getitem, + args=(control_deps_node, i + 1), # +1 because index 0 is sync result + ) + getitem_node.meta.update(dep.meta) + # The getitem is a passthrough projection of an existing value, not + # a node that *produces* an unbacked symbol - the original ``dep`` + # (still inside the subgraph) is the binding site. Leaving the + # binding on the getitem trips Inductor's run_node assertion that + # ``new_unbacked_defs >= renamed_unbacked_bindings``. + getitem_node.meta.pop("unbacked_bindings", None) + replacements[dep] = getitem_node + visited.add(getitem_node) + + # Replace uses of dependencies that come after sync_node. + # Use map_arg to handle nested structures (e.g. output node's list args). + for dep, getitem_node in replacements.items(): + pred = _user_rewrite_pred(dep) + for user in list(dep.users.keys()): + if user is control_deps_node: + continue + if not pred(user): + continue + + def _replace(n: Node) -> Node: + return getitem_node if n is dep else n + + if ( + user.op == "call_function" + and user.target is torch.ops.aten.copy_.default + and user.args[0] is dep + and dep in partition_scoped_deps + ): + # AOT functionalization leaves keep_input_mutations epilogue + # copy_ as the only writer of a partition-scoped placeholder. + # Preserve the destination identity used by mutation bookkeeping. + user.args = (dep, *map_arg(user.args[1:], _replace)) + else: + user.args = map_arg(user.args, _replace) + user.kwargs = map_arg(user.kwargs, _replace) + + # Remove original sync node + sync_node.replace_all_uses_with(control_deps_node) + graph.erase_node(sync_node) + return control_deps_node, list(replacements.values()) + + +def _collect_sync_forward_deps( + graph: torch.fx.Graph, +) -> tuple[dict[Node, OrderedSet[Node]], dict[Node, OrderedSet[Node]]]: + """Collect values that must cross sync boundaries. + + ``live_inputs[partition][stream]`` tracks values whose passthrough can anchor + later work in that partition on that stream. Demand labels propagate through + producers while each producer also seeds its own execution stream. This is a + single reverse liveness traversal; the forward pass still handles sync/event + state introduced while rewriting the graph. + """ + stream_sync_deps: dict[Node, OrderedSet[Node]] = {} + full_barrier_deps: dict[Node, OrderedSet[Node]] = {} + live_inputs: dict[Partition, dict[int, OrderedSet[Node]]] = { + FORWARD: {}, + BACKWARD: {}, + } + locations: dict[Node, OrderedSet[tuple[Partition, int]]] = {} + full_barriers = ( + torch.ops.streams.synchronize_device.default, + torch.ops.streams.synchronize_event.default, + torch.ops.streams.synchronize_stream.default, + ) + + def _add_live(node: Node, partition: Partition, stream: int) -> None: + stream_inputs = live_inputs[partition].get(stream) + if stream_inputs is None: + stream_inputs = live_inputs[partition][stream] = OrderedSet() + stream_inputs.add(node) + node_locations = locations.get(node) + if node_locations is None: + node_locations = locations[node] = OrderedSet() + node_locations.add((partition, stream)) + + for node in reversed(graph.nodes): + if node.op == "call_function" and node.target in full_barriers: + deps = OrderedSet( + dep + for stream_inputs in live_inputs[is_bwd_node(node)].values() + for dep in stream_inputs + ) + if deps: + full_barrier_deps[node] = deps + continue + if ( + node.op == "call_function" + and node.target is torch.ops.streams.wait_stream.default + ): + waiting_stream: int = node.args[0] # type: ignore[assignment] + deps = live_inputs[is_bwd_node(node)].get(waiting_stream) + if deps: + stream_sync_deps[node] = deps.copy() + continue + if ( + node.op == "call_function" + and node.target is torch.ops.streams.wait_event.default + ): + waiting_stream: int = node.args[1] # type: ignore[assignment] + deps = live_inputs[is_bwd_node(node)].get(waiting_stream, ()) + graph_inputs = OrderedSet(dep for dep in deps if dep.op == "placeholder") + if graph_inputs: + stream_sync_deps[node] = graph_inputs + continue + if node.op != "call_function" or node.target in _SYNC_OPS: + continue + + inherited_locations = locations.pop(node, _EMPTY_LOCATIONS) + for partition, stream in inherited_locations: + live_inputs[partition][stream].discard(node) + execution_stream = get_stream(node) + if execution_stream is None: + execution_stream = 0 + target_locations = OrderedSet( + (*inherited_locations, (is_bwd_node(node), execution_stream)) + ) + + def _collect(n: Node) -> Node: + if "val" in n.meta: + for partition, stream in target_locations: + _add_live(n, partition, stream) + return n + + map_arg(node.args, _collect) + map_arg(node.kwargs, _collect) + return stream_sync_deps, full_barrier_deps + + +def _collect_full_barrier_deps( + stream_to_nodes: dict[int | None, list[Node]], + stream_sync_deps: dict[int | None, list[Node]], + bwd: bool = False, +) -> list[Node]: + """Collect all still-live cross-stream deps for a full CPU barrier + (synchronize_stream/device/event). + + These ops block the CPU, so a consumer is only ordered after them by an + explicit control_deps edge (nothing on the consumer's stream waits for a CPU + barrier). Includes live compute nodes (stream_to_nodes) plus the ctrl/ + passthrough nodes accumulated by prior sync ops that already cleared + stream_to_nodes (stream_sync_deps), deduped by identity preserving order. + + ``bwd`` marks a backward barrier: its accumulated sync deps are filtered to + backward nodes only, so it never depends on a forward control_deps node. + That edge would cross the fwd/bwd boundary onto a node that is neither + saveable nor recomputable, making the min-cut partitioner infeasible. + Forward compute deps (stream_to_nodes) are kept -- backward legitimately + depends on forward activations. + """ + all_deps = [n for nodes in stream_to_nodes.values() for n in nodes] + seen = set(all_deps) + for deps in stream_sync_deps.values(): + for dep in deps: + if dep in seen or (bwd and not is_bwd_node(dep)): + continue + all_deps.append(dep) + seen.add(dep) + return all_deps + + +def wrap_all_sync_nodes_with_control_deps(gm: torch.fx.GraphModule) -> None: + """ + Single-pass wrap of all sync nodes in control_deps. + + Iterates through the graph once, accumulating per-stream node lists. + When a sync node is encountered, it is wrapped using the accumulated deps + for that stream, then the deps are reset to the control_deps node + (maintaining the ordering chain for subsequent syncs on the same stream). + """ + graph = gm.graph + if len(graph.nodes) == 0: + raise RuntimeError("Expected a non-empty graph") + + stream_sync_forward_deps, full_barrier_forward_deps = _collect_sync_forward_deps( + graph + ) + + stream_to_nodes: dict[int | None, list[Node]] = {} + # Maps event_index to its latest ordering anchor: either the control_deps that + # wrapped record_event or a raw record_event with no dependencies. + event_to_anchor: dict[int, Node] = {} + # Maps event_index -> getitem nodes threaded through record_event's control_deps, + # so synchronize_event can thread them through to subsequent ops. + event_to_passthrough: dict[int, list[Node]] = {} + # Maps event_index -> stream that the event was recorded on, + # so synchronize_event can infer its stream. + event_to_stream: dict[int, int | None] = {} + # Tracks the most recent control_deps node and its passthrough + # getitems per stream. synchronize_stream/device consults this to + # depend on prior sync ops (ctrl_node for ordering) and thread + # cross-stream data through (passthrough for data edges), even + # after stream_to_nodes has been cleared by those sync ops. + stream_sync_deps: dict[int | None, list[Node]] = {} + visited: set[Node] = set() + found_sync = False + + # Walk the node linked-list manually so we can mutate the graph + # (wrapping sync nodes inserts/erases nodes) without losing our place. + node = next(iter(graph.nodes)) + while node.op != "root": + next_node = node.next + visited.add(node) + + if node.op == "call_function": + if node.target in _SYNC_OPS: + # synchronize_device and synchronize_stream block the CPU, + # so all subsequent kernel launches are host-ordered after + # them. Treat both as full barriers across all streams. + if node.target in ( + torch.ops.streams.synchronize_device.default, + torch.ops.streams.synchronize_stream.default, + ): + all_stream_deps = _collect_full_barrier_deps( + stream_to_nodes, stream_sync_deps, bwd=is_bwd_node(node) + ) + existing_deps = set(all_stream_deps) + for dep in full_barrier_forward_deps.get(node, ()): + if dep not in existing_deps: + all_stream_deps.append(dep) + existing_deps.add(dep) + if all_stream_deps: + found_sync = True + ctrl_node_sync, passthrough_sync = _wrap_sync_node( + gm, node, all_stream_deps, visited + ) + else: + ctrl_node_sync = None + passthrough_sync: list[Node] = [] + stream_to_nodes.clear() + stream_sync_deps.clear() + sync_anchor = ctrl_node_sync if ctrl_node_sync is not None else node + stream_sync_deps[None] = [sync_anchor, *passthrough_sync] + while ( + getattr(next_node, "_erased", False) and next_node.op != "root" + ): + next_node = next_node.next + node = next_node + continue + + # wait_stream(waiting, waited_on) creates a dependency on + # the waited_on stream: all prior work there must complete + # before the waiting stream proceeds. + if node.target is torch.ops.streams.wait_stream.default: + waiting_stream: int = node.args[0] # type: ignore[assignment] + waited_on_stream: int = node.args[1] # type: ignore[assignment] + deps_before_sync = list(stream_to_nodes.get(waited_on_stream, ())) + if waiting_stream != waited_on_stream: + deps_before_sync.extend(stream_to_nodes.get(waiting_stream, ())) + if None in stream_to_nodes and waited_on_stream is not None: + deps_before_sync.extend(stream_to_nodes[None]) + participating_streams = dict.fromkeys( + (waited_on_stream, waiting_stream, None) + ) + prior_syncs = list( + dict.fromkeys( + dep + for stream in participating_streams + for dep in stream_sync_deps.get(stream, ()) + ) + ) + if is_bwd_node(node): + prior_syncs = [n for n in prior_syncs if is_bwd_node(n)] + deps_before_sync.extend(prior_syncs) + # Also include inputs of subsequent waiting-stream nodes + # so they get threaded through control_deps, creating a + # forward ordering constraint (waiting-stream work must + # come after wait_stream). + existing_deps = set(deps_before_sync) + for dep in stream_sync_forward_deps.get(node, ()): + if dep not in existing_deps: + deps_before_sync.append(dep) + existing_deps.add(dep) + if deps_before_sync: + found_sync = True + ctrl_node_ws, passthrough_ws = _wrap_sync_node( + gm, node, deps_before_sync, visited + ) + else: + ctrl_node_ws = None + passthrough_ws: list[Node] = [] + wait_anchor = ctrl_node_ws if ctrl_node_ws is not None else node + # Key under both streams: the wait executes on waiting_stream + # and subsumes the waited-on work used to anchor it. + stream_sync_deps[waiting_stream] = [ + wait_anchor, + *passthrough_ws, + ] + stream_sync_deps[waited_on_stream] = [ + wait_anchor, + *passthrough_ws, + ] + stream_to_nodes[waited_on_stream] = [] + if None in stream_to_nodes: + stream_to_nodes[None] = [] + while ( + getattr(next_node, "_erased", False) and next_node.op != "root" + ): + next_node = next_node.next + node = next_node + continue + + event_index: int = node.args[0] # type: ignore[assignment] + + # synchronize_event blocks the CPU thread, so it acts + # as a barrier across all streams. Collect deps from every + # stream and reset them all afterward. If the event was + # recorded externally, thread the graph inputs through so + # that any post-sync uses depend on the synchronize. + partition_scoped_deps: list[Node] = [] + if node.target is torch.ops.streams.synchronize_event.default: + sync_stream: int | None = event_to_stream.get(event_index) + # Like synchronize_stream/device, this is a CPU-side barrier, + # so fold in still-live cross-stream data accumulated by prior + # sync ops (which cleared stream_to_nodes). + all_stream_deps = _collect_full_barrier_deps( + stream_to_nodes, stream_sync_deps, bwd=is_bwd_node(node) + ) + deps_before_sync = [ + *all_stream_deps, + *full_barrier_forward_deps.get(node, ()), + ] + else: + sync_stream = node.args[1] # type: ignore[assignment] + deps_before_sync = list(stream_to_nodes.get(sync_stream, ())) + partition_scoped_deps = ( + list(stream_sync_forward_deps.get(node, ())) + if node.target is torch.ops.streams.wait_event.default + and event_index not in event_to_anchor + else [] + ) + deps_before_sync.extend(partition_scoped_deps) + # Nodes without explicit stream annotation (custom.stream=None) + # run on the current/default stream. Include them when the sync + # op references a stream, since the unannotated nodes are + # implicitly on that stream. + if None in stream_to_nodes and sync_stream is not None: + deps_before_sync.extend(stream_to_nodes[None]) + # Order this sync op after the prior sync on its own stream + # (and after any full barrier, keyed under None). Without this, + # a record/wait whose stream_to_nodes was reset by an earlier + # sync would have no deps, stay unwrapped, and float as a bare + # side-effectful node -- capturing nothing, the same failure as + # an unanchored synchronize_stream. + prior_syncs = [ + *stream_sync_deps.get(sync_stream, ()), + *stream_sync_deps.get(None, ()), + ] + # A backward sync must anchor only on backward sync nodes: + # depending on a forward control_deps node crosses the fwd/bwd + # boundary onto a node that is neither saveable nor + # recomputable, which makes the min-cut partitioner infeasible. + if is_bwd_node(node): + prior_syncs = [n for n in prior_syncs if is_bwd_node(n)] + deps_before_sync.extend(prior_syncs) + + # For wait_event and synchronize_event, depend on the matching + # record_event's control_deps node (ordering) and thread its + # passthrough getitems through (data edge), so consumers of + # recorded values are rewired through the wait/synchronize + # and the scheduler sees the dependency. + if node.target in ( + torch.ops.streams.wait_event.default, + torch.ops.streams.synchronize_event.default, + ): + if event_index in event_to_anchor: + deps_before_sync = [ + event_to_anchor[event_index], + *deps_before_sync, + ] + if event_index in event_to_passthrough: + deps_before_sync = [ + *deps_before_sync, + *event_to_passthrough[event_index], + ] + elif ( + node.target is torch.ops.streams.record_event.default + and event_index in event_to_anchor + ): + # Re-recording replaces an event's state, but the host-side + # record operations must retain program order even when the + # new record is on an otherwise-empty stream. + deps_before_sync.insert(0, event_to_anchor[event_index]) + + # Deduplicate (preserving order): the folded stream_sync_deps and + # the event's own anchor/passthrough can overlap. + deps_before_sync = list(OrderedSet(deps_before_sync)) + + if deps_before_sync: + found_sync = True + ctrl_node, passthrough = _wrap_sync_node( + gm, + node, + deps_before_sync, + visited, + set(partition_scoped_deps) + if node.target is torch.ops.streams.wait_event.default + else None, + ) + else: + ctrl_node = None + passthrough: list[torch.fx.Node] = [] + + if node.target is torch.ops.streams.record_event.default: + event_to_stream[event_index] = sync_stream + event_to_anchor[event_index] = ( + ctrl_node if ctrl_node is not None else node + ) + event_to_passthrough[event_index] = passthrough + + sync_anchor = ctrl_node if ctrl_node is not None else node + stream_sync_deps[sync_stream] = [sync_anchor, *passthrough] + + # Reset: ops between this sync and the next will accumulate + # fresh. Ordering with prior ops is already enforced because + # their uses were rewired through getitems from control_deps. + # synchronize_event is a full barrier, so its own passthrough + # subsumes all prior per-stream data: clear then re-seed. Key the + # reseed under None (like synchronize_stream/device) so a later + # record/wait on any stream chains after it. + if node.target is torch.ops.streams.synchronize_event.default: + stream_to_nodes.clear() + stream_sync_deps.clear() + stream_sync_deps[None] = [sync_anchor, *passthrough] + else: + stream_to_nodes[sync_stream] = [] + if None in stream_to_nodes: + stream_to_nodes[None] = [] + elif "val" in node.meta: + stream = get_stream(node) + stream_to_nodes.setdefault(stream, []).append(node) + + # _wrap_sync_node may erase nodes after the sync (e.g. + # _expand_dict_returning_deps erases getitems). Skip erased nodes + # so we don't re-process a dead node into stream_to_nodes. + while getattr(next_node, "_erased", False) and next_node.op != "root": + next_node = next_node.next + node = next_node + + if found_sync: + gm.recompile() diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_codegen.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..3f31e5d29d6d6da9573fbc100dca328f9adb8974 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_codegen.py @@ -0,0 +1,623 @@ +""" +Codegen for AOTDispatchSubclassWrapper. + +Generates a Python function that replaces the data-driven +runtime_unwrap_tensor_subclasses / wrap_tensor_subclasses loop with +a straight-line function where all metadata (indices, attr names, +subclass types, symint positions) is baked in at compile time. +""" + +import functools +import keyword +from collections.abc import Callable, Iterable +from typing import cast, TYPE_CHECKING + +from torch import SymInt + +from .codegen import _compile_and_exec_source, PySourceBuilder +from .schemas import ActInputPaths, OpaqueMeta, PlainTensorMeta, SubclassCreationMeta +from .utils import import_async_collective_tensor_type + + +if TYPE_CHECKING: + from torch.distributed._functional_collectives import AsyncCollectiveTensor + + +def _is_symint_placeholder(x: None | int | SymInt) -> bool: + """Check whether a size/stride entry is symbolic and needs a runtime value. + + Works both before make_runtime_safe() (entries are SymInt) and after + (symbolic entries replaced with None, nested ints with -1). + """ + if x is None: + return True + if isinstance(x, SymInt) and not x.node.is_nested_int(): + return True + return False + + +def _compute_placeholders(outer: Iterable[None | int | SymInt]) -> list[bool]: + return [_is_symint_placeholder(s) for s in outer] + + +def _safe_attr_access(var: str, attr: str) -> str: + if attr.isidentifier() and not keyword.iskeyword(attr): + return f"{var}.{attr}" + return f"getattr({var}, {attr!r})" + + +class _OutputWrapState: + def __init__( + self, + *, + remaining_min_count: int, + remaining_max_count: int, + optional_symint_check: str, + ) -> None: + self.remaining_min_count = remaining_min_count + self.remaining_max_count = remaining_max_count + self.optional_symint_check = optional_symint_check + + def mark_required(self) -> None: + self.remaining_min_count -= 1 + self.remaining_max_count -= 1 + + def mark_optional(self) -> None: + self.remaining_max_count -= 1 + + +def _maybe_wait_async_collective_tensor( + x: object, + AsyncCollectiveTensor: type["AsyncCollectiveTensor"], +) -> object: + """Wait on ACT values and leave all other runtime inputs unchanged.""" + if isinstance(x, AsyncCollectiveTensor): + return cast("AsyncCollectiveTensor", x).trigger_wait() + return x + + +def _codegen_unwrap_subclass( + state: PySourceBuilder, + meta: SubclassCreationMeta, + var: str, + indent: int = 1, + include_symints: bool = True, + act_input_paths: set[tuple[str, ...]] | None = None, + act_wait_fn: str | None = None, +) -> None: + """Emit code to recursively unwrap a single subclass input.""" + act_input_paths = act_input_paths or set() + + def emit_plain_tensor_symints(var: str, meta: PlainTensorMeta) -> None: + if not include_symints: + return + + if any(meta.size_symbol_placeholders): + size_var = state.fresh_name("_size") + state.emit(f"{size_var} = {var}.size()", indent=indent) + for i, is_sym in enumerate(meta.size_symbol_placeholders): + if is_sym: + state.emit(f"unwrapped_args.append({size_var}[{i}])", indent=indent) + + if any(meta.stride_symbol_placeholders): + stride_var = state.fresh_name("_stride") + state.emit(f"{stride_var} = {var}.stride()", indent=indent) + for i, is_sym in enumerate(meta.stride_symbol_placeholders): + if is_sym: + state.emit( + f"unwrapped_args.append({stride_var}[{i}])", indent=indent + ) + + for attr, attr_meta in meta.attrs.items(): + attr_expr = _safe_attr_access(var, attr) + attr_act_input_paths = { + path[1:] for path in act_input_paths if path and path[0] == attr + } + match attr_meta: + case PlainTensorMeta(): + if attr_act_input_paths: + if attr_act_input_paths != {()}: + raise AssertionError( + f"ACT path for {attr} continues past a leaf meta" + ) + if act_wait_fn is None: + raise AssertionError("missing ACT wait function") + resolved_var = state.fresh_name("_resolved") + state.emit( + f"{resolved_var} = {act_wait_fn}({attr_expr})", + indent=indent, + ) + attr_expr = resolved_var + state.emit(f"unwrapped_args.append({attr_expr})", indent=indent) + emit_plain_tensor_symints(attr_expr, attr_meta) + case OpaqueMeta(): + if attr_act_input_paths: + if attr_act_input_paths != {()}: + raise AssertionError( + f"ACT path for {attr} continues past a leaf meta" + ) + if act_wait_fn is None: + raise AssertionError("missing ACT wait function") + resolved_var = state.fresh_name("_resolved") + state.emit( + f"{resolved_var} = {act_wait_fn}({attr_expr})", + indent=indent, + ) + state.emit(f"unwrapped_args.append({resolved_var})", indent=indent) + else: + state.emit( + f"unwrapped_args.append({attr_expr})", + indent=indent, + ) + case SubclassCreationMeta(): + if () in attr_act_input_paths: + raise AssertionError(f"ACT path for {attr} stops at subclass meta") + inner_var = state.fresh_name("_inner") + state.emit(f"{inner_var} = {attr_expr}", indent=indent) + _codegen_unwrap_subclass( + state, + attr_meta, + inner_var, + indent=indent, + include_symints=include_symints, + act_input_paths=attr_act_input_paths, + act_wait_fn=act_wait_fn, + ) + + if include_symints: + size_placeholders = _compute_placeholders(meta.outer_size) + stride_placeholders = _compute_placeholders(meta.outer_stride) + if any(size_placeholders) or any(stride_placeholders): + size_var = state.fresh_name("_size") + state.emit(f"{size_var} = {var}.size()", indent=indent) + for i, is_sym in enumerate(size_placeholders): + if is_sym: + state.emit(f"unwrapped_args.append({size_var}[{i}])", indent=indent) + + stride_var = state.fresh_name("_stride") + state.emit(f"{stride_var} = {var}.stride()", indent=indent) + for i, is_sym in enumerate(stride_placeholders): + if is_sym: + state.emit( + f"unwrapped_args.append({stride_var}[{i}])", indent=indent + ) + + +def _concrete_value(val: None | int | SymInt) -> int: + """Get the concrete int value for a non-symbolic size/stride entry. + + Used for entries that are NOT symbolic placeholders, meaning they are + concrete ints or nested ints (represented as -1 after make_runtime_safe). + """ + if isinstance(val, int): + return val + # Before make_runtime_safe: nested ints are SymInts; use -1 as dummy. + # After make_runtime_safe: they're already -1. + if isinstance(val, SymInt) and val.node.is_nested_int(): + return -1 + raise AssertionError(f"Expected concrete int, got {type(val)}: {val}") + + +def _is_optional_symint_output(val: object) -> bool: + return isinstance(val, (int, SymInt)) + + +def _codegen_wrap_subclass( + state: PySourceBuilder, + meta: SubclassCreationMeta, + output_state: _OutputWrapState, +) -> str: + """Emit code to reconstruct one subclass output. Returns the variable name.""" + inner_dict_var = state.fresh_name("_out_inner") + entries: list[str] = [] + attr_exprs: dict[str, str] = {} + + for attr, attr_meta in meta.attrs.items(): + match attr_meta: + case PlainTensorMeta(): + attr_expr = state.fresh_name("_out_attr") + state.emit(f"{attr_expr} = unwrapped_outs[_out_idx]") + state.emit("_out_idx += 1") + output_state.mark_required() + _emit_optional_plain_tensor_symint_skips(state, output_state, attr_meta) + case OpaqueMeta(): + attr_expr = state.fresh_name("_out_attr") + state.emit(f"{attr_expr} = unwrapped_outs[_out_idx]") + state.emit("_out_idx += 1") + output_state.mark_required() + case SubclassCreationMeta(): + attr_expr = _codegen_wrap_subclass(state, attr_meta, output_state) + attr_exprs[attr] = attr_expr + entries.append(f"{attr!r}: {attr_expr}") + + state.emit(f"{inner_dict_var} = {{{', '.join(entries)}}}") + + # Reconstruct outer_size and outer_stride + size_placeholders = _compute_placeholders(meta.outer_size) + stride_placeholders = _compute_placeholders(meta.outer_stride) + + def _build_tuple( + outer: Iterable[None | int | SymInt], placeholders: list[bool] + ) -> str: + parts: list[str] = [] + for val, is_sym in zip(outer, placeholders): + if is_sym: + sym_expr = state.fresh_name("_out_sym") + state.emit(f"{sym_expr} = unwrapped_outs[_out_idx]") + state.emit("_out_idx += 1") + output_state.mark_required() + parts.append(sym_expr) + else: + parts.append(repr(_concrete_value(val))) + if len(parts) == 1: + return f"({parts[0]},)" + return f"({', '.join(parts)})" + + def _consume_optional_placeholders(placeholders: list[bool]) -> None: + for is_sym in placeholders: + if is_sym: + _emit_optional_symint_skip(state, output_state) + + outer_size_from_attr = meta.outer_size_from_attr + outer_stride_from_attr = meta.outer_stride_from_attr + if outer_size_from_attr is not None: + size_expr = f"{attr_exprs[outer_size_from_attr]}.size()" + _consume_optional_placeholders(size_placeholders) + else: + size_expr = _build_tuple(meta.outer_size, size_placeholders) + + if outer_stride_from_attr is not None: + stride_expr = f"{attr_exprs[outer_stride_from_attr]}.stride()" + _consume_optional_placeholders(stride_placeholders) + else: + stride_expr = _build_tuple(meta.outer_stride, stride_placeholders) + + type_name = state.add_global( + state.fresh_name("_subclass_type"), + meta.original_subclass_type or type(meta.original_subclass), + ) + meta_name = state.add_global(state.fresh_name("_meta"), meta.meta) + + result_var = state.fresh_name("_out") + state.emit( + f"{result_var} = {type_name}.__tensor_unflatten__(" + f"{inner_dict_var}, {meta_name}, {size_expr}, {stride_expr})" + ) + return result_var + + +def _count_output_args( + meta: PlainTensorMeta | SubclassCreationMeta, + *, + include_subclass_symints: bool, +) -> int: + if isinstance(meta, PlainTensorMeta): + return meta.arg_count if include_subclass_symints else 1 + + total = 0 + for attr_meta in meta.attrs.values(): + if isinstance(attr_meta, OpaqueMeta): + total += 1 + else: + total += _count_output_args( + attr_meta, include_subclass_symints=include_subclass_symints + ) + + if include_subclass_symints: + total += sum(_compute_placeholders(meta.outer_size)) + total += sum(_compute_placeholders(meta.outer_stride)) + else: + if meta.outer_size_from_attr is None: + total += sum(_compute_placeholders(meta.outer_size)) + if meta.outer_stride_from_attr is None: + total += sum(_compute_placeholders(meta.outer_stride)) + return total + + +def _emit_optional_symint_skip( + state: PySourceBuilder, + output_state: _OutputWrapState, +) -> None: + remaining_var = state.fresh_name("_remaining_outs") + include_var = state.fresh_name("_include_symints") + later_min_count = output_state.remaining_min_count + later_max_count = output_state.remaining_max_count - 1 + max_fits = ( + f"{remaining_var} - 1 >= {later_min_count} and " + f"{remaining_var} - 1 <= {later_max_count}" + ) + min_fits = ( + f"{remaining_var} >= {later_min_count} and {remaining_var} <= {later_max_count}" + ) + + state.emit(f"{remaining_var} = _num_wrapped_outs - _out_idx") + state.emit( + f"{include_var} = ({max_fits}) and " + f"{output_state.optional_symint_check}(unwrapped_outs[_out_idx])" + ) + state.emit( + f"assert {include_var} or ({min_fits}), " + "'could not match output layout with optional SymInt outputs'" + ) + state.emit(f"if {include_var}:") + state.emit("_out_idx += 1", indent=2) + output_state.mark_optional() + + +def _emit_optional_plain_tensor_symint_skips( + state: PySourceBuilder, + output_state: _OutputWrapState, + meta: PlainTensorMeta, +) -> None: + for is_sym in meta.size_symbol_placeholders: + if is_sym: + _emit_optional_symint_skip(state, output_state) + for is_sym in meta.stride_symbol_placeholders: + if is_sym: + _emit_optional_symint_skip(state, output_state) + + +def _emit_output_wrapping( + state: PySourceBuilder, + out_metas: list[PlainTensorMeta | SubclassCreationMeta], + num_fw_outs_saved_for_bw: int | None, +) -> tuple[list[str], int]: + """Emit wrapping code for output metas. + + Returns (result_exprs, num_args_tallied) where result_exprs are Python + expression strings referencing each wrapped output. + """ + result_exprs: list[str] = [] + num_args_tallied = 0 + saved_for_bw = num_fw_outs_saved_for_bw or 0 + min_counts = [ + _count_output_args(meta, include_subclass_symints=False) for meta in out_metas + ] + max_counts = [ + _count_output_args(meta, include_subclass_symints=True) for meta in out_metas + ] + min_wrapped_outputs = sum(min_counts) + max_wrapped_outputs = sum(max_counts) + + optional_symint_check = ( + state.add_global( + state.fresh_name("_is_optional_symint_output"), + _is_optional_symint_output, + ) + if min_wrapped_outputs != max_wrapped_outputs + else "" + ) + state.emit("_out_idx = 0") + if saved_for_bw: + state.emit(f"_num_wrapped_outs = len(unwrapped_outs) - {saved_for_bw}") + else: + state.emit("_num_wrapped_outs = len(unwrapped_outs)") + if min_wrapped_outputs != max_wrapped_outputs: + state.emit( + "assert " + f"{min_wrapped_outputs} <= _num_wrapped_outs <= {max_wrapped_outputs}, " + f"f'expected between {min_wrapped_outputs} and {max_wrapped_outputs} " + "wrapped outputs, got {_num_wrapped_outs}'" + ) + else: + state.emit( + f"assert _num_wrapped_outs == {max_wrapped_outputs}, " + f"f'expected {max_wrapped_outputs} wrapped outputs, " + "got {_num_wrapped_outs}'" + ) + + output_state = _OutputWrapState( + remaining_min_count=min_wrapped_outputs, + remaining_max_count=max_wrapped_outputs, + optional_symint_check=optional_symint_check, + ) + for meta in out_metas: + if isinstance(meta, PlainTensorMeta): + out_expr = state.fresh_name("_out_plain") + state.emit(f"{out_expr} = unwrapped_outs[_out_idx]") + state.emit("_out_idx += 1") + output_state.mark_required() + _emit_optional_plain_tensor_symint_skips(state, output_state, meta) + result_exprs.append(out_expr) + num_args_tallied += meta.arg_count + else: + result_var = _codegen_wrap_subclass(state, meta, output_state) + result_exprs.append(result_var) + num_args_tallied += meta.arg_count + + if output_state.remaining_min_count != 0 or output_state.remaining_max_count != 0: + raise AssertionError( + "output wrapping counts did not balance: " + f"{output_state.remaining_min_count}, " + f"{output_state.remaining_max_count}" + ) + state.emit( + "assert _out_idx == _num_wrapped_outs, " + "f'wrapped {_out_idx} outputs, expected {_num_wrapped_outs}'" + ) + return result_exprs, num_args_tallied + + +def _emit_input_unwrapping( + state: PySourceBuilder, + inp_metas: list[PlainTensorMeta | SubclassCreationMeta], + frozen_inp_indices: frozenset[int] = frozenset(), + include_symints: bool = True, + act_input_paths_by_input: dict[int, set[tuple[str, ...]]] | None = None, + act_wait_fn: str | None = None, +) -> None: + """Emit unwrapping code for input metas into unwrapped_args. + + Caller must have already emitted ``unwrapped_args = []``. + """ + act_input_paths_by_input = act_input_paths_by_input or {} + for i, meta in enumerate(inp_metas): + input_act_paths = act_input_paths_by_input.get(i, set()) + if isinstance(meta, PlainTensorMeta): + if input_act_paths: + if input_act_paths != {()}: + raise AssertionError( + f"ACT path for input {i} continues past a plain meta" + ) + if act_wait_fn is None: + raise AssertionError("missing ACT wait function") + state.emit(f"unwrapped_args.append({act_wait_fn}(args[{i}]))") + else: + state.emit(f"unwrapped_args.append(args[{i}])") + elif i in frozen_inp_indices: + # Frozen by inductor freezing: constant already baked into graph. + state.emit("unwrapped_args.append(None)") + else: + if () in input_act_paths: + raise AssertionError(f"ACT path for input {i} stops at subclass meta") + inp_var = state.fresh_name("_inp") + type_name = state.add_global( + state.fresh_name("_expected_type"), + meta.original_subclass_type or type(meta.original_subclass), + ) + state.emit(f"{inp_var} = args[{i}]") + state.emit( + f"assert type({inp_var}) is {type_name}, " + f"f'expected {{{type_name}}}, got {{type({inp_var})}}'", + ) + _codegen_unwrap_subclass( + state, + meta, + inp_var, + indent=1, + include_symints=include_symints, + act_input_paths=input_act_paths, + act_wait_fn=act_wait_fn, + ) + + +def _codegen_subclass_wrapper_source( + inp_metas: list[PlainTensorMeta | SubclassCreationMeta], + out_metas: list[PlainTensorMeta | SubclassCreationMeta], + num_fw_outs_saved_for_bw: int | None, + frozen_inp_indices: frozenset[int] = frozenset(), + act_input_paths: ActInputPaths | None = None, +) -> tuple[str, dict[str, object]]: + """Generate source and globals for a subclass wrapper. + + Returns (source, globals_dict). The globals_dict will NOT contain + ``compiled_fn`` — the caller is responsible for adding it before exec. + """ + state = PySourceBuilder() + + state.emit("def inner_fn(args):", indent=0) + + act_input_paths_by_input: dict[int, set[tuple[str, ...]]] = {} + act_wait_fn = None + if act_input_paths: + AsyncCollectiveTensor = import_async_collective_tensor_type() + act_wait_fn = state.add_global( + state.fresh_name("_maybe_wait_act"), + functools.partial( + _maybe_wait_async_collective_tensor, + AsyncCollectiveTensor=AsyncCollectiveTensor, + ), + ) + for i, attr_path in act_input_paths: + act_input_paths_by_input.setdefault(i, set()).add(attr_path) + + # --- Input unwrapping --- + state.emit("unwrapped_args = []") + _emit_input_unwrapping( + state, + inp_metas, + frozen_inp_indices=frozen_inp_indices, + act_input_paths_by_input=act_input_paths_by_input, + act_wait_fn=act_wait_fn, + ) + + # Pass through any trailing args not covered by inp_metas + # (e.g. rng seed/offset added by FunctionalizedRngRuntimeWrapper). + num_inp_metas = len(inp_metas) + state.emit(f"unwrapped_args.extend(args[{num_inp_metas}:])") + state.emit("args.clear()") + + # --- Call compiled function --- + state.emit("unwrapped_outs = compiled_fn(unwrapped_args)") + + # --- Output wrapping --- + result_exprs, _ = _emit_output_wrapping(state, out_metas, num_fw_outs_saved_for_bw) + result_tuple = f"({', '.join(result_exprs)},)" if result_exprs else "()" + if num_fw_outs_saved_for_bw is not None: + state.emit( + f"_activation_start = len(unwrapped_outs) - {num_fw_outs_saved_for_bw}" + ) + state.emit(f"return {result_tuple} + tuple(unwrapped_outs[_activation_start:])") + else: + state.emit(f"return {result_tuple}") + + source = state.getvalue() + return source, state.globals + + +def _codegen_subclass_wrap_source( + out_metas: list[PlainTensorMeta | SubclassCreationMeta], +) -> tuple[str, dict[str, object]]: + """Generate source for wrapping flat outputs into subclasses. + + Used for the backward epilogue. Shares output-wrapping logic with + _codegen_subclass_wrapper_source via _emit_output_wrapping. + """ + state = PySourceBuilder() + state.emit("def wrap_fn(unwrapped_outs):", indent=0) + result_exprs, _ = _emit_output_wrapping( + state, out_metas, num_fw_outs_saved_for_bw=None + ) + result_tuple = f"({', '.join(result_exprs)},)" if result_exprs else "()" + state.emit(f"return {result_tuple}") + source = state.getvalue() + return source, state.globals + + +def codegen_backward_subclass_fns( + grad_input_metas: list[PlainTensorMeta | SubclassCreationMeta] | None = None, +) -> tuple[Callable[..., object], Callable[..., object] | None]: + """Generate codegen'd unwrap and wrap functions for the backward pass. + + Returns (unwrap_fn, wrap_fn). unwrap_fn is used by the backward prologue + to unwrap non-tangent subclass inputs (always an identity in AOT dispatch + since the compiled forward operates on unwrapped inner tensors). wrap_fn + is used by the backward epilogue to wrap flat grad inputs back into + subclasses; it is None when grad_input_metas is None. + """ + source = "def unwrap_fn(args):\n return list(args)" + globals_dict: dict[str, object] = {} + unwrap_fn = _compile_and_exec_source( + source, globals_dict, "unwrap_fn", "backward_subclass_unwrap" + ) + + wrap_fn = None + if grad_input_metas is not None: + wrap_source, wrap_globals = _codegen_subclass_wrap_source(grad_input_metas) + wrap_fn = _compile_and_exec_source( + wrap_source, wrap_globals, "wrap_fn", "backward_subclass_wrapper" + ) + + return unwrap_fn, wrap_fn + + +def codegen_subclass_wrapper( + compiled_fn: Callable[..., object], + inp_metas: list[PlainTensorMeta | SubclassCreationMeta], + out_metas: list[PlainTensorMeta | SubclassCreationMeta], + num_fw_outs_saved_for_bw: int | None, + frozen_inp_indices: frozenset[int] = frozenset(), + act_input_paths: ActInputPaths | None = None, +) -> Callable[..., object]: + """Generate a specialized wrapper function for subclass unwrap/wrap.""" + source, globals_dict = _codegen_subclass_wrapper_source( + inp_metas, + out_metas, + num_fw_outs_saved_for_bw, + frozen_inp_indices, + act_input_paths=act_input_paths, + ) + globals_dict["compiled_fn"] = compiled_fn + return _compile_and_exec_source( + source, globals_dict, "inner_fn", "subclass_wrapper", wrapped_fn=compiled_fn + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py new file mode 100644 index 0000000000000000000000000000000000000000..f32087850cf2d2693d1cd36bf23fe22808766b29 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +import dataclasses +import itertools +from typing import Any, TYPE_CHECKING + +import torch +from torch._custom_class_base import CustomClassBase +from torch._library.opaque_object import is_opaque_symbolic_type +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .schemas import OpaqueMeta + + +if TYPE_CHECKING: + from collections.abc import Iterable + + +# This is technically very similar to SubclassCreatingMeta +# in aot_autograd, but we don't need all the stuff in there +# so just recreated a new dataclass. +@dataclasses.dataclass +class SubclassCreationMeta: + start_idx: int + num_tensors: int + class_type: Any + # None means the attr is a plain tensor (base case of recursion) + attrs: dict[str, SubclassCreationMeta | OpaqueMeta | None] + metadata: Any + outer_size: Iterable[None | int | torch.SymInt] + outer_stride: Iterable[None | int | torch.SymInt] + + +class UnwrapTensorSubclass(torch.nn.Module): + def forward(self, *tensors) -> torch.Tensor: # type: ignore[no-untyped-def] + todo: list[torch.Tensor | CustomClassBase] = list(tensors) + + def _unwrap_tensor_subclasses(subclass_meta, tensors, offset): # type: ignore[no-untyped-def] + if subclass_meta is None: + return tensors[offset], offset + 1 + inner_tensors = {} + for attr, meta in subclass_meta.attrs.items(): + if isinstance(meta, OpaqueMeta): + inner_tensors[attr] = tensors[offset] + offset += 1 + else: + built_tensor, offset = _unwrap_tensor_subclasses( + meta, tensors, offset + ) + inner_tensors[attr] = built_tensor + rebuilt = subclass_meta.class_type.__tensor_unflatten__( + inner_tensors, + subclass_meta.metadata, + subclass_meta.outer_size, + subclass_meta.outer_stride, + ) + return rebuilt, offset + + return _unwrap_tensor_subclasses(self.subclass_meta, todo, 0)[0] + + def right_inverse( + self, tensor: torch.Tensor + ) -> list[torch.Tensor | CustomClassBase]: + if type(tensor) is torch.Tensor: + raise AssertionError("tensor must be a subclass, not torch.Tensor") + plain_tensors: list[torch.Tensor | CustomClassBase] = [] + + def _create_subclass_meta(tensor, idx, plain_tensor_container): # type: ignore[no-untyped-def] + if type(tensor) is torch.Tensor: + plain_tensor_container.append(tensor) + return None, idx + 1 + inner_tensors_attrnames, metadata = tensor.__tensor_flatten__() # type: ignore[attr-defined] + new_idx = idx + attr_to_meta: dict[str, SubclassCreationMeta | OpaqueMeta | None] = {} + for attr in inner_tensors_attrnames: + val = getattr(tensor, attr) + match val: + case CustomClassBase(): + if not is_opaque_symbolic_type(type(val)): + raise ValueError( + f"{type(val).__name__!r} found in tensor attrs of " + f"{type(tensor).__name__}.__tensor_flatten__(). " + "Only tensors and reference-type opaques are allowed " + "in tensor attrs." + ) + attr_to_meta[attr] = OpaqueMeta() + plain_tensor_container.append(val) + new_idx += 1 + case torch.Tensor(): + subclass_meta, new_idx = _create_subclass_meta( + val, new_idx, plain_tensor_container + ) + attr_to_meta[attr] = subclass_meta + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(val)}" + ) + return ( + SubclassCreationMeta( + start_idx=idx, + num_tensors=new_idx - idx, + class_type=type(tensor), + attrs=attr_to_meta, + metadata=metadata, + outer_size=tensor.size(), + outer_stride=tensor.stride(), + ), + new_idx, + ) + + self.subclass_meta = _create_subclass_meta(tensor, 0, plain_tensors)[0] + return plain_tensors + + +def unwrap_tensor_subclass_parameters(module: torch.nn.Module) -> torch.nn.Module: + """ + Model transformation that replaces all the parameters that are subclasses to plain tensors. + This reduces runtime overhead of flattening/unflattening the parameters. + + This transformation adds parametrization with `torch.nn.utils.parametrize`. + The FQNs of the subclass parameters will be changed and state_dict will become incompatible with the original model. + E.g. + Original model state_dict: {"p1": torch.testing._internal.TwoTensor} + becomes: {"parametrizations.p2.original0": torch.Tensor, "parametrizations.p2.original1": torch.Tensor} + + """ + for name, tensor in itertools.chain( + list(module.named_parameters(recurse=False)), + # pyrefly: ignore [bad-argument-type, no-matching-overload] + list(module.named_buffers(recurse=False)), + ): + if is_traceable_wrapper_subclass(tensor): + torch.nn.utils.parametrize.register_parametrization( + module, name, UnwrapTensorSubclass() + ) + + for child in module.children(): + unwrap_tensor_subclass_parameters(child) + + return module diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9361a5a8ea4dc2b9bb8daeef82fd7324b882cbb5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py @@ -0,0 +1,784 @@ +""" +This file contains utilities for tracing through __torch_dispatch__ based tensor subclasses and modes. +AOTAutograd's responsibility is to trace through all pytorch capabilities that live in the pytorch dispatcher, +and this includes tensor subclasses that implement __torch_dispatch__. +""" + +import collections +from collections.abc import Callable, Iterable, Sequence +from typing import Any, TypeGuard, TypeVar + +import torch +import torch.utils._pytree as pytree +from torch import SymInt, Tensor +from torch._custom_class_base import CustomClassBase +from torch._library.fake_class_registry import maybe_unwrap_fake_script_object +from torch._library.opaque_object import is_opaque_symbolic_type +from torch._subclasses.fake_tensor import get_plain_tensors +from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq +from torch.types import IntLikeType +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + TraceableWrapperSubclass, +) + +from .descriptors import ( + AOTInput, + AOTOutput, + DummyAOTInput, + SubclassGetAttrAOTInput, + SubclassGetAttrAOTOutput, + SubclassSizeAOTInput, + SubclassSizeAOTOutput, + SubclassStrideAOTInput, + SubclassStrideAOTOutput, +) +from .schemas import ( + FakifiedFlatArgs, + FxValue, + MutationType, + OpaqueMeta, + PlainTensorMeta, + SubclassCreationMeta, + ViewAndMutationMeta, +) +from .utils import strict_zip + + +zip = strict_zip + +T = TypeVar("T", bound=torch.Tensor) + + +def requires_subclass_dispatch( + args: FakifiedFlatArgs, fw_metadata: ViewAndMutationMeta +) -> bool: + args_flattened = pytree.arg_tree_leaves(*args) + any_subclass_args = any( + is_traceable_wrapper_subclass(x) + for x in args_flattened + if isinstance(x, Tensor) + ) + from torch._functorch._aot_autograd.schemas import SubclassCreationMeta + + any_subclass_outputs = any( + type(x) is SubclassCreationMeta for x in fw_metadata.subclass_fw_graph_out_meta + ) + # This tells us whether or not we need to perform any unwrapping/wrapping of tensor subclasses at runtime. + return bool(any_subclass_args or any_subclass_outputs) + + +from .schemas import MemoryFormatMeta + + +def maybe_suggest_memory_format( + t: Tensor, with_memory_format: bool +) -> MemoryFormatMeta | None: + if not with_memory_format: + return None + + return MemoryFormatMeta.from_tensor(t) + + +def _safe_metadata_eq( + outer: Iterable[IntLikeType], + inner: Iterable[IntLikeType], +) -> bool: + return guard_or_false(sym_eq(tuple(outer), tuple(inner))) + + +def _find_attr_matching_outer_metadata( + a: Tensor, + inner_keys: Sequence[str], + *, + metadata_fn: Callable[[Tensor], Iterable[IntLikeType]], +) -> str | None: + tensor_attrs = [key for key in inner_keys if isinstance(getattr(a, key), Tensor)] + if not tensor_attrs: + return None + + outer_metadata = tuple(metadata_fn(a)) + # Only use an attr as the runtime source when every tensor attr agrees + # with the wrapper metadata; otherwise there is no single attr to trust. + if all( + _safe_metadata_eq(outer_metadata, metadata_fn(getattr(a, key))) + for key in tensor_attrs + ): + return tensor_attrs[0] + return None + + +def _symint_placeholders(lst: Iterable[IntLikeType]) -> tuple[bool, ...]: + return tuple(isinstance(s, SymInt) and not s.node.is_nested_int() for s in lst) + + +def get_subclass_typing_container( + tensor_subclass: torch.Tensor, +) -> dict[type[torch.Tensor], list[type[torch.Tensor]]]: + """ + Given a subclass, returns a recursive dictionary mapping each + inner tensors to its subclass types. + """ + + def _get_types_for_subclass(tensor_subclass: torch.Tensor) -> None: + if not is_traceable_wrapper_subclass(tensor_subclass): + return + tracker[type(tensor_subclass)].append(tensor_subclass) + inner_keys, _ = tensor_subclass.__tensor_flatten__() + for key in inner_keys: + match getattr(tensor_subclass, key): + case torch.Tensor() as inner_value: + _get_types_for_subclass(inner_value) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + tracker: dict[Any, list[Any]] = collections.defaultdict(list) + _get_types_for_subclass(tensor_subclass) + return tracker + + +def create_subclass_metadata( + a: Any, + start_idx: int, + count_symints: bool, + with_memory_format: bool = False, +) -> tuple[Any, int]: + if not is_traceable_wrapper_subclass(a): + size_symbol_placeholders = ( + _symint_placeholders(a.size()) if count_symints else () + ) + stride_symbol_placeholders = ( + _symint_placeholders(a.stride()) if count_symints else () + ) + meta = PlainTensorMeta( + start_idx + 1, + memory_format=maybe_suggest_memory_format(a, with_memory_format), + size_symbol_placeholders=size_symbol_placeholders, + stride_symbol_placeholders=stride_symbol_placeholders, + ) + return ( + meta, + start_idx + meta.arg_count, + ) + + inner_keys, metadata = a.__tensor_flatten__() + new_start_idx = start_idx + attrs: dict[str, SubclassCreationMeta | PlainTensorMeta | OpaqueMeta] = {} + + for key in inner_keys: + inner_value = getattr(a, key) + match inner_value: + case CustomClassBase(): + # During tracing, opaques are wrapped in FakeScriptObject; + # unwrap to check the real type. + real_type = type(maybe_unwrap_fake_script_object(inner_value)) + if not is_opaque_symbolic_type(real_type): + raise RuntimeError( + f"{real_type.__name__!r} found in tensor attrs of " + f"{type(a).__name__}.__tensor_flatten__(). " + "Only tensors and reference-type opaques are allowed " + "in tensor attrs." + ) + attrs[key] = OpaqueMeta() + new_start_idx += 1 + case Tensor(): + new_subclass_meta, new_start_idx = create_subclass_metadata( + inner_value, + new_start_idx, + count_symints=count_symints, + with_memory_format=with_memory_format, + ) + attrs[key] = new_subclass_meta + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(inner_value)}" + ) + + # It *must* be because is_traceable_wrapper_subclass() - but mypy is not smart. + if not isinstance(a, Tensor): + raise AssertionError(f"expected Tensor, got {type(a)}") + + new_start_idx = ( + new_start_idx + + count_symints * len(enumerate_filter_symints(a.size())) + + count_symints * len(enumerate_filter_symints(a.stride())) + ) + + return ( + SubclassCreationMeta( + flat_tensor_start_idx=start_idx, + arg_count=new_start_idx - start_idx, + included_subclass_symints=count_symints, + attrs=attrs, + meta=metadata, + outer_size=a.size(), # type: ignore[attr-defined, arg-type] + outer_stride=a.stride(), # type: ignore[arg-type] + original_subclass=a, + memory_format=maybe_suggest_memory_format(a, with_memory_format), + outer_size_from_attr=_find_attr_matching_outer_metadata( + a, inner_keys, metadata_fn=lambda t: t.size() + ), + outer_stride_from_attr=_find_attr_matching_outer_metadata( + a, inner_keys, metadata_fn=lambda t: t.stride() + ), + ), + new_start_idx, + ) + + +# Given a flat list of arguments, some of which may be tensor subclasses, +# computes metadata about "how to reconstruct the current list of subclasses, +# if we were given their flattened dense tensors instead" +def create_subclass_meta( + curr_args: list[Any] | tuple[Any, ...], + *, + count_symints: bool = True, + with_memory_format: bool = False, +) -> list[PlainTensorMeta | SubclassCreationMeta]: + idx = 0 + infos: list[PlainTensorMeta | SubclassCreationMeta] = [] + for a in curr_args: + if is_traceable_wrapper_subclass(a): + if not isinstance(a, Tensor): + raise AssertionError( + f"expected Tensor for traceable wrapper subclass, got {type(a)}" + ) + start_idx = idx + subclass_meta, _ = create_subclass_metadata( + a, + start_idx, + count_symints=count_symints, + with_memory_format=with_memory_format, + ) + infos.append(subclass_meta) + cnt = subclass_meta.arg_count + else: + infos.append( + PlainTensorMeta( + idx, + memory_format=maybe_suggest_memory_format(a, with_memory_format), + ) + ) + cnt = 1 + idx += cnt + return infos + + +def enumerate_filter_symints(lst: Iterable[IntLikeType]) -> list[tuple[int, SymInt]]: + # Capture all SymInts from the iterable. + def symint_check(s: IntLikeType) -> TypeGuard[SymInt]: + return isinstance(s, SymInt) and not s.node.is_nested_int() + + return [(i, s) for i, s in enumerate(lst) if symint_check(s)] + + +def compute_symint_placeholders(lst: Iterable[None | int | SymInt]) -> list[bool]: + # Non-nested symints are replaced with None in `make_runtime_safe()` + return [s is None for s in lst] + + +# Intended to make it easier to define function that is +# either (AOTInput -> AOTInput) or (AOTOutput -> AOTOutput) +# but not the other combos +AOTDescriptor = TypeVar("AOTDescriptor", AOTInput, AOTOutput) + + +# This function takes in a pytree of arguments and unwraps any tensor +# subclasses. +# +# NOTE: The reason for "append_symints": +# +# * At compile time: we append extra symint args when unwrapping primals +# (but not tangents, because they should always share symints with primals). +# We also append extra symints when unwrapping the subclass outputs of the +# traced function, so we can return them as extra outputs +# +# * At runtime: we similarly append subclass sizes when we unwrap subclass +# primals (but not tangents) on entry to the forward. See the runtime version of +# this function below. +def unwrap_tensor_subclasses( + wrapped_args: list[FxValue], + wrapped_args_descs: Sequence[AOTDescriptor], + *, + append_symints: bool, +) -> tuple[list[FxValue], list[AOTDescriptor]]: + def _maybe_fakeify_opaque(v: Any) -> Any: + # Registered opaque types need to be wrapped as FakeScriptObject for + # compile-time FX tracing (proxy slot tracking, hashability, etc.). + if isinstance(v, CustomClassBase): + from torch._guards import detect_fake_mode + from torch._library.fake_class_registry import maybe_to_fake_obj + from torch._library.opaque_object import is_custom_class + + fake_mode = detect_fake_mode() + if fake_mode is not None and is_custom_class(type(v)): + return maybe_to_fake_obj(fake_mode, v) + return v + + def flatten_subclass( + t: FxValue, + desc: AOTDescriptor, + *, + out: tuple[list[FxValue], list[AOTDescriptor]], + ) -> None: + # unwrap a subclass into plain tensors and their size/stride if "append_symint" + # is True + if not is_traceable_wrapper_subclass(t): + out[0].append(_maybe_fakeify_opaque(t)) + out[1].append(desc) + if ( + append_symints + and isinstance(t, Tensor) + and isinstance( + desc, (SubclassGetAttrAOTInput, SubclassGetAttrAOTOutput) + ) + ): + sizes = enumerate_filter_symints(t.size()) + strides = enumerate_filter_symints(t.stride()) + out[0].extend(s for _, s in sizes) + out[0].extend(s for _, s in strides) + if isinstance(desc, AOTInput): + out[1].extend(SubclassSizeAOTInput(desc, i) for i, _ in sizes) + out[1].extend(SubclassStrideAOTInput(desc, i) for i, _ in strides) + else: + out[1].extend(SubclassSizeAOTOutput(desc, i) for i, _ in sizes) + out[1].extend(SubclassStrideAOTOutput(desc, i) for i, _ in strides) + return + + attrs, _ = t.__tensor_flatten__() + + SubclassGetAttr: Callable[[AOTInput | AOTOutput, str], AOTDescriptor] + SubclassSize: Callable[[AOTInput | AOTOutput, int], AOTDescriptor] + SubclassStride: Callable[[AOTInput | AOTOutput, int], AOTDescriptor] + if isinstance(desc, AOTInput): + SubclassGetAttr = SubclassGetAttrAOTInput # type: ignore[bad-assignment] + SubclassSize = SubclassSizeAOTInput # type: ignore[bad-assignment] + SubclassStride = SubclassStrideAOTInput # type: ignore[bad-assignment] + else: + SubclassGetAttr = SubclassGetAttrAOTOutput # type: ignore[bad-assignment] + SubclassSize = SubclassSizeAOTOutput # type: ignore[bad-assignment] + SubclassStride = SubclassStrideAOTOutput # type: ignore[bad-assignment] + + for attr in attrs: + inner_value = getattr(t, attr) + n_desc: Any = SubclassGetAttr(desc, attr) + flatten_subclass(inner_value, n_desc, out=out) + + if append_symints: + sizes = enumerate_filter_symints(t.size()) + strides = enumerate_filter_symints(t.stride()) + out[0].extend(s for _, s in sizes) + out[0].extend(s for _, s in strides) + out[1].extend(SubclassSize(desc, i) for i, _ in sizes) + out[1].extend(SubclassStride(desc, i) for i, _ in strides) + + xs_inner: list[FxValue] = [] + descs_inner: list[AOTDescriptor] = [] + + for x, desc in zip(wrapped_args, wrapped_args_descs): + flatten_subclass(x, desc, out=(xs_inner, descs_inner)) + + return xs_inner, descs_inner + + +# subclass_metas is needed at runtime to compute which indices are symints in +# the outer_size/outer_stride +def runtime_unwrap_tensor_subclasses( + wrapped_args: list[Tensor | int], + *, + append_symints: bool, + subclass_metas: list[PlainTensorMeta | SubclassCreationMeta] | None = None, +) -> list[int | Tensor | SymInt | CustomClassBase]: + def flatten_subclass( + x: Tensor | TraceableWrapperSubclass, + subclass_meta: PlainTensorMeta | SubclassCreationMeta | OpaqueMeta | None, + *, + out: list[CustomClassBase | SymInt | Tensor | int], + ) -> list[CustomClassBase | SymInt | Tensor | int]: + def append_plain_tensor_symints(tensor: Tensor, meta: PlainTensorMeta) -> None: + size = tensor.size() + if len(size) != len(meta.size_symbol_placeholders): + raise AssertionError( + f"size length mismatch: {len(size)} != {len(meta.size_symbol_placeholders)}" + ) + out.extend( + [ + r + for (r, is_symint) in zip(size, meta.size_symbol_placeholders) + if is_symint + ] + ) + + stride = tensor.stride() + if len(stride) != len(meta.stride_symbol_placeholders): + raise AssertionError( + f"stride length mismatch: {len(stride)} != {len(meta.stride_symbol_placeholders)}" + ) + out.extend( + [ + r + for (r, is_symint) in zip(stride, meta.stride_symbol_placeholders) + if is_symint + ] + ) + + if not is_traceable_wrapper_subclass(x): + out.append(x) + if append_symints and isinstance(subclass_meta, PlainTensorMeta): + append_plain_tensor_symints(x, subclass_meta) + return out + + if not isinstance(x, Tensor): + raise AssertionError(f"expected Tensor, got {type(x)}") + if not isinstance(subclass_meta, SubclassCreationMeta): + raise AssertionError("subclass_meta should be a SubclassCreationMeta") + + attrs, _ = x.__tensor_flatten__() + + for attr in attrs: + inner_value = getattr(x, attr) + match inner_value: + case CustomClassBase(): + out.append(inner_value) + case Tensor(): + inner_meta = subclass_meta.attrs.get(attr) + flatten_subclass(inner_value, inner_meta, out=out) + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(inner_value)}" + ) + + if append_symints: + # outer_size + size = x.size() + symint_placeholders = compute_symint_placeholders(subclass_meta.outer_size) + if len(size) != len(symint_placeholders): + raise AssertionError( + f"size length mismatch: {len(size)} != {len(symint_placeholders)}" + ) + out.extend( + [r for (r, is_symint) in zip(size, symint_placeholders) if is_symint] + ) + + # outer_stride + stride = x.stride() + symint_placeholders = compute_symint_placeholders( + subclass_meta.outer_stride + ) + if len(stride) != len(symint_placeholders): + raise AssertionError( + f"stride length mismatch: {len(stride)} != {len(symint_placeholders)}" + ) + out.extend( + [r for (r, is_symint) in zip(stride, symint_placeholders) if is_symint] + ) + return out + + xs_inner: list[int | Tensor | SymInt | CustomClassBase] = [] + + if append_symints: + if subclass_metas is None: + raise AssertionError( + "subclass_metas must not be None when append_symints is True" + ) + + for idx, x in enumerate(wrapped_args): + if not is_traceable_wrapper_subclass(x): + xs_inner.append(x) + continue + + if subclass_metas is None: + get_plain_tensors(x, out=xs_inner) + else: + subclass_meta = subclass_metas[idx] + if not isinstance(subclass_meta, SubclassCreationMeta): + raise AssertionError( + f"expected SubclassCreationMeta, got {type(subclass_meta)}" + ) + flatten_subclass(x, subclass_meta, out=xs_inner) + + return xs_inner + + +def unwrap_tensor_subclasses_with_indices_to_original( + wrapped_args: list[Any], +) -> tuple[list[Any], list[int]]: + ret_unwrapped = [] + ret_indices_to_original = [] + for i, a in enumerate(wrapped_args): + a_unwrapped, _ = unwrap_tensor_subclasses( + [a], [DummyAOTInput(9999)], append_symints=False + ) + ret_unwrapped.extend(a_unwrapped) + n = len(a_unwrapped) + ret_indices_to_original.extend([i] * n) + + return ret_unwrapped, ret_indices_to_original + + +def remap_unwrapped_subclass_arg_indices( + wrapped_args: list[Any], static_input_indices: list[int] +) -> list[int]: + def static_arg_slots(arg: Any, *, include_plain_tensor_symints: bool) -> list[bool]: + # Forwarded SymInts occupy flattened arg positions, but static input indices + # describe tensor/opaque slots whose value should not be copied. + if not is_traceable_wrapper_subclass(arg): + if include_plain_tensor_symints and isinstance(arg, Tensor): + num_symints = len(enumerate_filter_symints(arg.size())) + len( + enumerate_filter_symints(arg.stride()) + ) + return [True] + [False] * num_symints + return [True] + + slots = [] + attrs, _ = arg.__tensor_flatten__() + for attr in attrs: + inner_value = getattr(arg, attr) + match inner_value: + case CustomClassBase(): + slots.append(True) + case Tensor(): + slots.extend( + static_arg_slots(inner_value, include_plain_tensor_symints=True) + ) + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(inner_value)}" + ) + + slots.extend( + [False] + * ( + len(enumerate_filter_symints(arg.size())) + + len(enumerate_filter_symints(arg.stride())) + ) + ) + return slots + + static_input_indices_set = set(static_input_indices) + new_ind = 0 + remapped_static_indices = [] + for i, arg in enumerate(wrapped_args): + slots = ( + static_arg_slots(arg, include_plain_tensor_symints=False) + if is_traceable_wrapper_subclass(arg) + else [True] + ) + + for is_static_arg_slot in slots: + if i in static_input_indices_set and is_static_arg_slot: + remapped_static_indices.append(new_ind) + + new_ind += 1 + + return remapped_static_indices + + +# Turns a flattened list of tensor arguments into (maybe) subclass tensors. +# This function is used both at trace time and runtime, so we have an is_runtime flag telling us which context we're in. +def wrap_tensor_subclasses( + unwrapped_args: Sequence[Any], + *, + subclass_metas: list[PlainTensorMeta | SubclassCreationMeta], + num_fw_outs_saved_for_bw: int | None = None, + included_subclass_symints: bool = False, + is_runtime: bool = False, + make_subclass_override: Callable[..., Any] | None = None, +) -> tuple[Any, ...]: + # pyrefly: ignore [implicit-any] + wrapped_args = [] + num_args_tallied = 0 + for subclass_meta in subclass_metas: + if isinstance(subclass_meta, PlainTensorMeta): + wrapped_args.append(unwrapped_args[subclass_meta.unwrapped_idx]) + num_args_tallied += subclass_meta.arg_count + else: + if not isinstance(subclass_meta, SubclassCreationMeta): + raise AssertionError( + f"expected SubclassCreationMeta, got {type(subclass_meta)}" + ) + if subclass_meta.included_subclass_symints != included_subclass_symints: + raise AssertionError( + f"included_subclass_symints mismatch: {subclass_meta.included_subclass_symints} != {included_subclass_symints}" + ) + + if make_subclass_override: + wrapped_args.append( + make_subclass_override(subclass_meta, is_runtime, unwrapped_args) + ) + else: + wrapped_args.append( + subclass_meta.creation_fn( + unwrapped_args, + is_runtime=is_runtime, + ) + ) + num_args_tallied += subclass_meta.arg_count + + # Note: [Partitioner handling for Subclasses, Part 2] + # At the beginning of AOTAutograd, we collect metadata on the inputs and outputs of the user fw, + # to figure out which inputs/outputs are subclasses, and how to reconstruct the subclasses after flattening them. + # + # When this function is called at runtime in the forward, + # we have been passed a list of (flattened) dense-tensor fw-outs, and need to reconstruct any subclass fw outs. + # + # One reasonable question that you should ask: when should the dense_tensor -> subclass_tensor wrapping happen? + # Answer: we do it **inside of our compiled autograd.Function**. + # This seems like morally the right place: autograd happens above subclass desugaring, + # so autograd should see actual tensor subclasses at runtime, and not flattened dense tensors. + # + # This causes a tricky interaction though: when we run the min-cut partitioner to divvy up the joint graph + # into a forward and backward graph, we end up with some activations that show up as extra outputs + # in the compiled forward graph, that are **not** user outputs. + # These activations are not visible to the user, and so there's no need for us to wrap them back into subclasses. + # + # On top of that, when we first computed subclass metadata (in `run_functionalized_fw_and_collect_metadata`), + # we computed subclass metadata on every forward output, but this did **not** include activations + # created by the partitioner. + # as a result, `unwrapped_args` here will correspond to (*unwrapped_user_fw_outs, *activations), + # but `subclass_metas` will only correspond to subclass metadata on `user_fw_outs`. + # We then need to make sure that we return (*wrapped_user_fw_outs, *activations). + if num_fw_outs_saved_for_bw is not None: + if len(unwrapped_args) != num_args_tallied + num_fw_outs_saved_for_bw: + raise AssertionError( + f"Expected the number actual unwrapped-subclass outputs {len(unwrapped_args)} to equal " + f"the number of args calculated from subclasses ({num_args_tallied}) plus the number of " + f"additional activations saved for the backward pass ({num_fw_outs_saved_for_bw})" + ) + activations = unwrapped_args[num_args_tallied:] + if isinstance(wrapped_args, tuple) and isinstance(activations, tuple): + return wrapped_args + activations + return tuple(list(wrapped_args) + list(activations)) + else: + if len(unwrapped_args) != num_args_tallied: + raise AssertionError( + f"Expected {len(unwrapped_args)} == {num_args_tallied}" + ) + return tuple(wrapped_args) + + +# Given a bunch of "dense" tensor arguments, this function (potentially) wraps them into tensor subclasses. +# This function carefully handles the inference vs. joint cases: +# - when is_joint_structure is True, args is (primals, tangents) +# - when is_joint_structure is False, args is [*primals] +def wrap_tensor_subclasses_maybe_joint( + unwrapped_args: Sequence[Any], + *, + is_joint_structure: bool, + meta: ViewAndMutationMeta, +) -> tuple[Any, ...]: + # Since this function is reused for both inference and joint graphs, + if is_joint_structure: + if not (isinstance(unwrapped_args, tuple) and len(unwrapped_args) == 2): + unwrapped_len = ( + len(unwrapped_args) + if isinstance(unwrapped_args, (tuple, list)) + else "N/A" + ) + raise AssertionError( + f"expected tuple of length 2 for joint structure, " + f"got {type(unwrapped_args)} with length {unwrapped_len}" + ) + if not ( + isinstance(unwrapped_args[0], (tuple, list)) + and isinstance(unwrapped_args[1], (tuple, list)) + ): + raise AssertionError( + f"expected primals and tangents to be tuple or list, got {type(unwrapped_args[0])} and {type(unwrapped_args[1])}" + ) + primals, tangents = unwrapped_args[0], unwrapped_args[1] + wrapped_primals = wrap_tensor_subclasses( + primals, + subclass_metas=meta.subclass_inp_meta, + included_subclass_symints=True, + ) + wrapped_tangents = wrap_tensor_subclasses( + tangents, + subclass_metas=meta.subclass_tangent_meta, + included_subclass_symints=False, + ) + return (wrapped_primals, wrapped_tangents) + else: + wrapped_args = wrap_tensor_subclasses( + unwrapped_args, + subclass_metas=meta.subclass_inp_meta, + included_subclass_symints=True, + ) + return wrapped_args + + +def compute_inner_mutated_inp_indices_from_subclass_meta( + fw_metadata: ViewAndMutationMeta, + inner_metadata: ViewAndMutationMeta, +) -> list[int]: + # Note: [Recomputing subclass mutation handling] + # + # Generally, if a subclass requires grad, its components will not require grad. + # But for the purposes of tracking returned tensors, we should treat those component + # tensors as if they require grad. + # + # For example, if the subclass tensor requires grad and will be mutated in a way that + # requires us to handle the mutation outside of the graph, we need to return it + # from the forward graph. The inner_meta data won't consider the component tensors + # as if they need to be returned, because they don't require grad; but really, we + # should handle those tensors the same way we handle the subclass tensor itself; i.e. + # if we'd include the subclass tensor as part of the outputs, then we should also + # include the component tensors. + # + # To do this, we patch num_mutated_inp_runtime_indices below by expanding the inputs + # from the outer subclass tensors and propagating + + updated_input_info = [] + inner_idx = 0 + if not fw_metadata.subclass_inp_meta: + # Sometimes we don't have subclass info, e.g. synthetic_base codepaths + return inner_metadata.mutated_inp_runtime_indices + if len(fw_metadata.subclass_inp_meta) != len(fw_metadata.input_info): + raise AssertionError( + f"subclass_inp_meta length ({len(fw_metadata.subclass_inp_meta)}) != input_info length ({len(fw_metadata.input_info)})" + ) + for outer_idx, inp_meta in enumerate(fw_metadata.subclass_inp_meta): + if isinstance(inp_meta, PlainTensorMeta): + if outer_idx >= len(fw_metadata.input_info): + raise AssertionError( + f"outer_idx ({outer_idx}) >= len(fw_metadata.input_info) ({len(fw_metadata.input_info)})" + ) + if inner_metadata is not None: + if inner_idx >= len(inner_metadata.input_info): + raise AssertionError( + f"inner_idx ({inner_idx}) >= len(inner_metadata.input_info) ({len(inner_metadata.input_info)})" + ) + if ( + inner_metadata.input_info[inner_idx] + != fw_metadata.input_info[outer_idx] + ): + raise AssertionError( + f"input_info mismatch at inner_idx={inner_idx}, outer_idx={outer_idx}: " + f"{inner_metadata.input_info[inner_idx]} != {fw_metadata.input_info[outer_idx]}" + ) + updated_input_info.append(fw_metadata.input_info[outer_idx]) + inner_idx += 1 + else: + if inp_meta.original_subclass is None: + raise AssertionError( + "inp_meta.original_subclass must not be None for SubclassCreationMeta" + ) + for _ in range(inp_meta.arg_count): + updated_input_info.append(fw_metadata.input_info[outer_idx]) + inner_idx += 1 + if inner_metadata is not None: + if len(inner_metadata.input_info) != len(updated_input_info): + raise AssertionError( + f"inner_metadata.input_info length ({len(inner_metadata.input_info)}) " + f"!= updated_input_info length ({len(updated_input_info)})" + ) + + return [ + i + for i, inp in enumerate(updated_input_info) + if inp.mutation_type == MutationType.MUTATED_OUT_GRAPH + ] diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/to_standalone_python.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/to_standalone_python.py new file mode 100644 index 0000000000000000000000000000000000000000..218897c1c1be34f7c0f2983ed2eaed22776736be --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/to_standalone_python.py @@ -0,0 +1,999 @@ +"""Lower a GraphModule to a self-contained Python module via AOTAutograd + Inductor. + +This is the AOT half of the backend contract behind ``torch.compiler.precompile``: + + python_code, cache = compile_to_python(gm, example_inputs) + +``inductor.compile_to_python`` produces only the inner Inductor ``call`` (kernels +for the post-AOTAutograd dense graph). This module wraps that with the prelude / +epilogue (input-mutation reflection, output-alias regen, subclass wrap/unwrap, +...) by COMPOSING AOTAutograd's own codegen'd runtime-wrapper source -- captured +during compile -- rather than reimplementing it. Every wrapper is spliced verbatim as a +real top-level ``def``, with its closed-over globals hoisted to module-scope assignments, +so the module reads as ordinary code. These nest in the SAME order the runtime builds: +the INNER chain wrappers (subclass / functionalized-RNG) wrap the inner ``call`` and are +composed inside the orchestration, while the OUTER ``CompilerWrapper``s (dedup / synthetic +base) wrap the orchestration itself (via a single-arg adapter over it). Cross-wrapper references, the inner ``call`` chain, +public helpers, and baked metadata objects (reconstructed as source -- see +``_emit_value``) are wired by name; a guard rejects the rare case where a wrapper def +name or hoisted global would collide with another top-level name (a sibling wrapper or +an inner-module binding) rather than silently rebinding one. +The result is a standalone module exposing ``call(flat_inputs) -> outputs`` that +runs on its own (JIT-compiling kernels); ``cache`` is an opaque acceleration (or +None). + +Baked metadata is emitted as plain Python source (no pickle / base64 blobs), so the +generated module is fully auditable and exec'ing it never invokes ``pickle.loads``. +A leaf that cannot be expressed as source raises NotImplementedError rather than +falling back to an opaque embedding. + +Contract note: the standalone ``call`` deliberately substitutes ``nullcontext`` / a +no-op for the runtime's first-invocation context and profiler prologue, dropping the +cold-start custom-op aliasing analysis and the profiler prologue -- both diagnostics +with no effect on numerics (see the generated-call emission site). One caveat: that +dropped first-invocation custom-op aliasing analysis can itself RAISE under +``config.error_on_custom_op_aliasing`` (default on in CI), so a graph whose custom op +violates the aliasing contract runs SILENTLY in the standalone artifact where the +eager / compiled path would error -- an intentional trade-off, not a numerics bug. +""" + +from __future__ import annotations + +import ast +import re +import threading +from typing import Any, TYPE_CHECKING + +from .codegen import capture_generated_sources, GeneratedSource +from .source_emit import _REBUILD_HELPER, emit_value + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Sequence + + from torch.fx import GraphModule + + +# Serializes compile_to_python: the wrapper-source capture is thread-local, but the +# AOTAutograd capture pass and the inner inductor compile swap process-global cache state +# (see the THREADING note on compile_to_python), so concurrent compiles must not overlap. +# An RLock (not a +# plain Lock) because this entry point is re-entrant on a single thread: a custom +# backend or inductor pass invoked while the lock is held may call back into this +# lowering to compile a subgraph on the SAME thread, and a plain Lock would +# self-deadlock on that re-entry. On-thread re-entry is safe here: the capture sink and +# the cache-state swap (CacheArtifactManager.with_fresh_cache) are each self-contained +# per call, so a nested compile neither corrupts the outer capture nor the outer cache +# scope. +_COMPILE_LOCK = threading.RLock() + + +# ====================================================================== +# WHAT IS GOING ON HERE: composing AOTAutograd's runtime wrappers as source +# ====================================================================== +# +# AOTAutograd does not hand back a single flat function. The dense graph Inductor +# compiles (the inner ``call``) is only the arithmetic core; around it AOTAutograd +# wraps a prelude/epilogue that does what the core cannot express: reflecting input +# mutations back onto the caller's tensors, regenerating outputs that alias an input +# or each other, wrapping/unwrapping tensor subclasses, de-duplicating aliased +# inputs, and threading functionalized RNG state. At runtime AOTAutograd emits each +# wrapper as Python *source*, exec's it (the chokepoint is _compile_and_exec_source +# in codegen.py), and the resulting function runs while closing over a +# globals dict supplied in-process -- i.e. a wrapper is (source text) + +# ({local_name: live_object}). +# +# The objects a wrapper closes over come in a few kinds: +# - public runtime helpers the codegen'd source references (e.g. increment_version, +# gen_alias_from_base, _unwrap_tensoralias, mark_dynamo_propagated_dynamic_indices, +# the CUDARngStateHelper staticmethods) -- ordinary importable objects; +# - the inner Inductor ``call`` that the chain ultimately invokes; +# - sibling captured wrappers -- the next link of the runtime chain (an inner subclass / +# functionalized-RNG wrapper, or an outer dedup / synthetic-base wrapper, whose body +# calls the link it wraps -- the orchestration's outer closure for the innermost outer +# wrapper), plus the orchestration's output-alias and mutation epilogue helpers, which +# it closes over directly by reference; +# - per-graph metadata baked at compile time (e.g. a ViewMetaSequence for alias +# regen, tensor-subclass metadata) -- live objects with no import path. +# +# Concretely, the module emitted for ``x.view(-1)`` (an output aliasing its input) has +# one of each (heavily trimmed; the (1)-(4) tags match the kinds listed above): +# +# from ...standalone_runtime import gen_alias_from_base # (1) public helper +# +# _inner_call = call # (2) the inner call +# _vms_0 = ViewMetaSequence._from_parts(...) # (4) metadata as source +# def _alias_fn(orig_inputs, fw_outs): # (3) sibling wrapper +# return [gen_alias_from_base(orig_inputs[0], fw_outs[0], False, _vms_0, ...)] +# _replay_aliases_ = _alias_fn # (3) orchestration's ref +# def _runtime_wrapper(_compiled_fn_, _first_ctx_, _on_before_call_, args): +# all_outs = _compiled_fn_(args) # (2) inner call invoked +# return _replay_aliases_(orig_inputs, all_outs) # (3) sibling invoked +# def call(flat_inputs): +# return _runtime_wrapper( +# _inner_call, contextlib.nullcontext, lambda: None, list(flat_inputs)) +# +# We do NOT reimplement any of this. We CAPTURE AOTAutograd's exact codegen'd wrapper +# source together with the (pre-exec) globals dict each wrapper closed over: a +# thread-local sink in codegen.py records one GeneratedSource per wrapper. +# To trigger the capture we run AOTAutograd ourselves (under no_grad, the inference path) +# with a capture-only inner compiler: it grabs the dense inner graph and returns a +# placeholder callable, so AOTAutograd still codegen's the runtime-wrapper chain AROUND +# that placeholder -- which is what the sink records. Inductor does not run in that pass; +# it runs once afterward on the captured dense graph (via inductor.compile_to_python), and +# the composer swaps the placeholder for the inner inductor ``call`` by object identity. +# +# THE COMPOSITION PROBLEM. To turn a captured wrapper into a real top-level ``def`` in +# the standalone module we splice its source verbatim. But that source refers to each +# global by the LOCAL ALIAS AOTAutograd happened to choose (e.g. ``compiled_fn`` for +# the inner call), not by any importable name. So for each ``{name: obj}`` in the +# captured globals dict we emit a top-level binding ``name = `` (see +# _emit_inline) -- except when the resolved expression already IS that module-scope +# name (an import, or ``torch``), which needs no binding. The hard part is the right- +# hand side: given only a live object, produce source that reproduces it. That requires +# RECOGNIZING what the object is, the job of _resolve_global and the id-keyed +# structures it consults, in order: +# - inner_call_id -> the inner ``call`` becomes ``_inner_call`` +# - fn_id_to_name -> a sibling wrapper's fn becomes that wrapper's own name +# - _known_helper_table() -> an importable helper becomes (import, expr) +# - anything else: reconstruct field-by-field as source (_emit_value), or raise. +# Recognition is by id() (object identity), not value-equality: for "is this the EXACT +# object the wrapper closed over," == is the wrong tool (functions don't compare by +# value, and an equal-but-different object would mis-resolve). Value-equality IS used, +# but later and for a different job -- _emit_value round-trip-checks reconstructed +# metadata (rebuilt == obj) before trusting it. Every hoisted name is _reserve'd: a +# collision with a sibling wrapper's name or an inner-module binding fails loudly +# rather than silently rebinding. +# +# WHY THIS IS SAFE ACROSS PROCESSES AND MACHINES. Every id() above is consulted ONLY +# here, during composition, in the process that just ran the compile -- where all the +# candidate objects (helpers, the inner call, sibling wrappers) are simultaneously +# alive, held by the GeneratedSource records and the captured globals dicts, so no +# address can be freed and reused mid-pass. Nothing the composer emits carries an id() +# value, a live object, or any thread-local capture state: it emits only import lines, +# ``name = expr`` bindings, and verbatim def source (the inner Inductor source is +# likewise spliced as text). Grep the GENERATED module and there is no ``id(`` to +# find. By the time the user holds the Python, all the process/thread-local state the +# composer leaned on is gone; what ships is imports + name bindings + verbatim code. +# Load it on another machine with the same torch version and the imports resolve by +# name and the bindings reconstruct -- identity was a compile-time recognition device, +# never a serialized artifact (live tensors / pickle / base64 blobs are rejected +# outright rather than embedded). +# +# So the one genuine cross-machine contract is not id() but that the *names* the +# artifact imports still resolve on load. Helpers are emitted as either ``import +# torch`` (the torch module and stable public paths, e.g. +# torch.autograd.graph.increment_version) or an import from the single small surface +# standalone_runtime.py (for the AOTAutograd-area internals -- plus CUDARngStateHelper, +# re-exported there for import-ordering -- whose locations are not themselves a stable +# contract). That file's IDENTITY CONTRACT -- re-exports must preserve object id -- +# exists purely so the COMPOSER's id-lookup keeps matching; it is a compile-time +# requirement, and the runtime artifact has no id dependency of its own. +# ====================================================================== + + +# Global objects the codegen'd wrappers close over that are reproducible as an +# import in the standalone module (rather than reconstructed field-by-field). Maps +# object id -> (import_statement, expression). Built lazily to avoid import cycles. +def _known_helper_table() -> dict[int, tuple[str, str]]: + # Generated artifacts import runtime helpers from the single stable surface + # ``standalone_runtime`` (not scattered AOTAutograd internals). + import torch + + from . import standalone_runtime as rt + + _RT = "from torch._functorch._aot_autograd.standalone_runtime import" + table: dict[int, tuple[str, str]] = { + id(torch): ("import torch", "torch"), + id(rt.normalize_as_list): (f"{_RT} normalize_as_list", "normalize_as_list"), + id(rt.mark_dynamo_propagated_dynamic_indices): ( + f"{_RT} mark_dynamo_propagated_dynamic_indices", + "mark_dynamo_propagated_dynamic_indices", + ), + id(torch.autograd.graph.increment_version): ( + "import torch", + "torch.autograd.graph.increment_version", + ), + id(rt.gen_alias_from_base): ( + f"{_RT} gen_alias_from_base", + "gen_alias_from_base", + ), + id(rt._unwrap_tensoralias): ( + f"{_RT} _unwrap_tensoralias", + "_unwrap_tensoralias", + ), + id(rt.CUDARngStateHelper.get_torch_state_as_tuple): ( + f"{_RT} CUDARngStateHelper", + "CUDARngStateHelper.get_torch_state_as_tuple", + ), + id(rt.CUDARngStateHelper.set_new_offset): ( + f"{_RT} CUDARngStateHelper", + "CUDARngStateHelper.set_new_offset", + ), + } + return table + + +_MODULE_HEADER = """\ +# Generated by torch._functorch.aot_autograd.compile_to_python -- do not edit. +# +# Self-contained, executable module exposing ``call(flat_inputs) -> outputs`` for +# the post-AOTAutograd graph. The Inductor kernels JIT-compile from the inlined +# source on first call (no cache needed). The prelude/epilogue is AOTAutograd's own +# codegen'd runtime wrappers, not reimplemented: each (the orchestration and any chain +# wrappers) is spliced as a real top-level ``def`` with its closed-over globals (inner +# ``call``, sibling wrappers, public helpers, baked metadata reconstructed as source) +# hoisted to module-scope assignments -- so results match eager. The companion opaque +# cache is only an acceleration; this module never reads it. +""" + + +def _resolve_global( + obj: object, + helper_table: dict[int, tuple[str, str]], + inner_call_id: int | None, + fn_id_to_name: dict[int, str], + imports: set[str], + orch_closure_id: int | None = None, + orch_entry_name: str | None = None, +) -> str: + """Return a Python expression (valid in the generated module) that reproduces + ``obj``, recording any needed import. Raises NotImplementedError if ``obj`` is + neither the inner call, a sibling wrapper, a known helper, nor source- + reconstructible (see ``_emit_value``).""" + if inner_call_id is not None and id(obj) == inner_call_id: + return "_inner_call" + # An OUTER wrapper (dedup / synthetic base) closes over the orchestration's outer + # closure as its inner. That closure is not a captured wrapper and has no import + # path, so wire it to the single-arg orchestration entry adapter the composer emits. + if orch_closure_id is not None and id(obj) == orch_closure_id: + if orch_entry_name is None: + raise AssertionError("expected orch_entry_name to be not None") + return orch_entry_name + if id(obj) in fn_id_to_name: + return fn_id_to_name[id(obj)] + if id(obj) in helper_table: + import_stmt, expr = helper_table[id(obj)] + if import_stmt: + imports.add(import_stmt) + return expr + # Not a wired reference (inner call / sibling wrapper / helper): emit ``obj`` as + # plain reconstruction source. Raises if it is not source-expressible. + return emit_value(obj, imports) + + +def _module_level_names(tree: ast.Module) -> set[str]: + """Names bound at module scope by a parsed module. Used to seed ``_reserve`` so an + inlined wrapper's def name or hoisted global (chain wrapper or orchestration) cannot + silently shadow a top-level name the inner Inductor module already binds.""" + names: set[str] = set() + for n in tree.body: + if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.add(n.name) + elif isinstance(n, ast.Assign): + # Walk each target so tuple/list/starred unpacking (``a, b = ...`` / + # ``first, *rest = ...``) is covered, not just bare-name targets. + for t in n.targets: + names.update(x.id for x in ast.walk(t) if isinstance(x, ast.Name)) + elif isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name): + names.add(n.target.id) + elif isinstance(n, (ast.Import, ast.ImportFrom)): + names.update(a.asname or a.name.split(".")[0] for a in n.names) + elif isinstance(n, ast.Delete): + # Inductor's inner module does ``async_compile = AsyncCompile()`` then + # ``del async_compile`` at module scope; a del'd name does not survive, so it + # must not be reserved (else a hoisted wrapper global of the same name would + # trip a spurious collision). Body order is assign-then-del, so removing here + # leaves only names that actually persist. + for t in n.targets: + names.difference_update( + x.id for x in ast.walk(t) if isinstance(x, ast.Name) + ) + return names + + +def _compose_standalone_module( + inner_python: str, captured: list[GeneratedSource], inner_call_obj: Any +) -> str: + """Compose the inner Inductor ``call`` with AOTAutograd's captured runtime + wrappers into one standalone module exposing ``call(flat_inputs) -> outputs``. + + Every wrapper (chain wrappers and the orchestration) is spliced as a real top-level + ``def`` with its closed-over globals hoisted to module-scope assignments (resolved + here). They are chained by name in the SAME nesting the runtime builds: the + orchestration is invoked with the INNER InductorWrapper chain head (subclass / RNG) + as its inner, and any OUTER ``CompilerWrapper`` (dedup / synthetic base, applied + AROUND the orchestration in ``graph_compile._aot_stage2c_make_inference_function``) + wraps a single-arg adapter over the orchestration. + + ``inner_call_obj`` is the placeholder the capture pass returned for the inner call; + its identity is authoritative (see the note at the inner-call site below). + """ + # The capture sink is duration-scoped over the inner inductor compile, with no + # originating-graph id at install time, so a re-entrant on-thread AOTAutograd / + # inductor lowering during that window that codegen's wrappers into THIS sink would + # append ITS wrappers here too. (A nested compile_to_python installs its OWN sink via + # capture_generated_sources, so its wrappers go there, not here -- it is not this + # case.) Each captured wrapper is tagged at append time with its TracingContext + # identity (origin_id), which separates such a foreign lowering when it ran under a + # DISTINCT TracingContext. A same-context re-entrant lowering reuses the ambient + # TracingContext via try_get() and so shares this origin_id; that case is instead + # caught by the orchestration count/wiring guards below (a second orchestration trips + # the len() != 1 check). Filter to the target graph's origin before composing. The + # target is the origin of the LAST captured orchestration wrapper: a foreign lowering + # appends its orchestration before the outer one finishes, so the final orchestration + # is always the outer/target one. + orchestrations = [ + g for g in captured if g.artifact_name == "runtime_wrapper_orchestration" + ] + if orchestrations: + # target_origin is None only without an ambient TracingContext, which the real + # precompile path never hits (capture always runs under one); in that defensive + # case the filter keeps every None-origin wrapper and the count/wiring guards + # below remain the backstop. + target_origin = orchestrations[-1].origin_id + captured = [g for g in captured if g.origin_id == target_origin] + + # Backward wrappers are out of scope for forward lowering; reject them up front. + # Every other wrapper that can appear in a composable (cacheable) forward graph is + # codegen'd as source and captured here. The one non-codegen'd wrapper, + # FakifiedOutWrapper, only activates under fakify_first_call, which makes the graph + # non-cacheable -- so such a graph is rejected before it ever reaches composition. + unsupported = [g.artifact_name for g in captured if "backward" in g.artifact_name] + if unsupported: + raise NotImplementedError( + "aot_autograd.compile_to_python cannot yet compose these runtime " + f"wrappers into standalone source: {sorted(set(unsupported))}." + ) + + orchestration = [ + g for g in captured if g.artifact_name == "runtime_wrapper_orchestration" + ] + if len(orchestration) != 1: + raise NotImplementedError( + "aot_autograd.compile_to_python expected exactly one forward " + f"orchestration wrapper, captured {len(orchestration)}." + ) + orch = orchestration[0] + non_orch = [g for g in captured if g is not orch] + + # The generated ``call`` invokes the orchestration POSITIONALLY by its own name (see + # the bottom of this function): _runtime_wrapper(chain_head, contextlib.nullcontext, + # lambda: None, flat_inputs). That mapping is hardcoded to the codegen'd signature in + # runtime_wrappers.py (``def _runtime_wrapper(_compiled_fn_, _first_ctx_, + # _on_before_call_, args)``). Verify the captured signature still matches so a future + # rename/reorder fails loudly here instead of silently passing wrong arguments. + expected_orch_params = ["_compiled_fn_", "_first_ctx_", "_on_before_call_", "args"] + orch_def = next( + ( + n + for n in ast.walk(ast.parse(orch.source)) + if isinstance(n, ast.FunctionDef) and n.name == orch.fn_name + ), + None, + ) + args_node = orch_def.args if orch_def is not None else None + if args_node is None: + orch_params = None + else: + # Compare the FULL signature, not just positional params: the standalone call is + # purely positional, so a keyword-only / *args / **kwargs param (e.g. an added + # kw-only-with-default) would be silently dropped. Surface any such param so it + # trips this guard rather than passing. + orch_params = [a.arg for a in (*args_node.posonlyargs, *args_node.args)] + orch_params += [a.arg for a in args_node.kwonlyargs] + if args_node.vararg is not None: + orch_params.append("*" + args_node.vararg.arg) + if args_node.kwarg is not None: + orch_params.append("**" + args_node.kwarg.arg) + if orch_params != expected_orch_params: + raise NotImplementedError( + "aot_autograd.compile_to_python: the orchestration wrapper signature " + f"changed (expected {expected_orch_params}, got {orch_params}); the " + "standalone module invokes it positionally and must be updated to match." + ) + + helper_table = _known_helper_table() + # Every wrapper is inlined (below) as a real def at module scope under its OWN codegen'd + # name, so references resolve to that name. Note these names are NOT distinct in general + # -- the subclass, dedup, and debug-assert chain wrappers all codegen ``inner_fn``; what + # holds today is that at most one chain wrapper appears per composable forward graph (see + # the test note on multi-link chains), so the names don't actually clash. ``_reserve`` + # fails loudly if that ever stops holding (the old ``_wrapper_{i}`` scheme could carry + # multiple same-named wrappers in private exec namespaces; inlining deliberately cannot). + fn_id_to_name = {id(g.fn): g.fn_name for g in non_orch} + + # A chain wrapper references the inner it wraps via one of these globals + # (subclass/dedup use ``compiled_fn``; the functionalized-RNG wrapper uses + # ``_compiled_fn_``). The orchestration takes its inner as a call-time arg, not a + # global, so it is never a chain wrapper. MAINTAINERS: if AOTAutograd adds a + # forward chain wrapper that names its inner via a new global, add that name here, + # otherwise inner-call/chain-head detection silently bypasses it. + _INNER_NAMES = ("compiled_fn", "_compiled_fn_") + + def _inner_ref(g: GeneratedSource) -> Any: + for nm in _INNER_NAMES: + if nm in g.globals_dict: + return g.globals_dict[nm] + return None + + # The inner Inductor call is AUTHORITATIVE: it is the placeholder object the capture + # pass returned (threaded in as ``inner_call_obj``), NOT inferred from capture order. + # This is what lets the composer tell the inner call apart from the orchestration's + # own outer closure -- both surface as some wrapper's inner-ref yet neither is a + # captured wrapper fn -- which is precisely how INNER wrappers (subclass / RNG, + # wrapping the inner call, composed INSIDE the orchestration) are distinguished from + # OUTER wrappers (dedup / synthetic base, ``CompilerWrapper``s applied AROUND the + # orchestration in graph_compile._aot_stage2c_make_inference_function). + inner_call_id: int = id(inner_call_obj) + + # Name of the single-arg adapter emitted over the orchestration; the innermost outer + # wrapper closes over the orchestration's outer closure and is wired to this name. + _ORCH_ENTRY = "_orchestration_entry" + + # The orchestration's outer closure is the object outer wrappers wrap. The composer + # never captures it directly (the captured orchestration ``fn`` is the inner + # ``_codegen_runtime_wrapper``), so recognize it structurally: an inner-ref that is + # neither the inner call nor any captured wrapper's fn can only be that closure. + orch_closure_ids = { + id(_inner_ref(g)) + for g in non_orch + if _inner_ref(g) is not None + and id(_inner_ref(g)) != inner_call_id + and id(_inner_ref(g)) not in fn_id_to_name + } + if len(orch_closure_ids) > 1: + raise NotImplementedError( + "aot_autograd.compile_to_python: captured multiple wrappers whose inner " + "reference is neither the inner call nor a captured wrapper; cannot tell " + "which wraps the orchestration." + ) + orch_closure_id: int | None = next(iter(orch_closure_ids), None) + + # Walk the OUTER chain outward from the orchestration closure: the innermost outer + # wrapper wraps the closure, the next wraps that wrapper's fn, and so on. Everything + # else is inner-side -- the subclass / RNG chain wrappers plus the alias / mutation + # epilogue helpers the orchestration closes over (which reference no inner at all). + outer_wrappers: list[GeneratedSource] = [] + if orch_closure_id is not None: + target_id: int | None = orch_closure_id + while target_id is not None: + nxt = next( + ( + g + for g in non_orch + if g not in outer_wrappers + and _inner_ref(g) is not None + and id(_inner_ref(g)) == target_id + ), + None, + ) + if nxt is None: + break + outer_wrappers.append(nxt) + target_id = id(nxt.fn) + outer_ids = {id(g) for g in outer_wrappers} + inner_side = [g for g in non_orch if id(g) not in outer_ids] + + # Chain head passed to the orchestration: the outermost INNER InductorWrapper (last + # inner-side wrapper that wraps via an inner reference), else the inner call. Computed + # up front (a pure capture-order check) so the order-inversion guard below fires + # before the later name-uniqueness guard -- a mis-ordered chain is the more specific + # diagnosis. + chain_head = "_inner_call" + chain_head_g: GeneratedSource | None = None + for g in inner_side: + if _inner_ref(g) is not None: + chain_head = fn_id_to_name[id(g.fn)] + chain_head_g = g + + # "Last with an inner-ref == outermost" holds only when INNER capture order is + # innermost-to-outermost (it is today: subclass before functionalized-RNG). Back that + # assumption with a guard: the true outermost inner wrapper is the one NO other inner + # wrapper wraps, i.e. whose fn is not referenced as another inner wrapper's inner. If + # the chosen head is itself wrapped, capture order inverted and the chain would be + # mis-ordered -- reject rather than silently emit a wrong chain (the wiring guard + # below would not catch this, since every wrapper is still referenced somewhere). + referenced_inner_ids = { + id(_inner_ref(g)) for g in inner_side if _inner_ref(g) is not None + } + if chain_head_g is not None and id(chain_head_g.fn) in referenced_inner_ids: + raise NotImplementedError( + "aot_autograd.compile_to_python: the selected chain head is itself wrapped " + "by another captured wrapper, so capture order is not innermost-to-outermost " + "as assumed; refusing to emit a mis-ordered runtime-wrapper chain." + ) + + imports: set[str] = set() + + # Parse the inner module once: to verify it binds a module-level ``call`` (the + # inner-call contract, checked below) and to collect its top-level names so no inlined + # wrapper's def name or hoisted global can silently shadow one. + inner_tree = ast.parse(inner_python) + inner_module_names = _module_level_names(inner_tree) + + # Every runtime wrapper is inlined: its def is spliced at module scope and its + # closed-over globals hoisted to top-level assignments (no exec / private namespace). + # So every emitted top-level name -- each wrapper's def name and each hoisted global -- + # must be unique and must not shadow a name the inner Inductor module binds. This holds + # in practice because at most one chain wrapper appears per composable forward graph, so + # its def name (``inner_fn`` is shared across subclass/dedup/debug-assert wrappers) and + # the inner-ref global ``compiled_fn`` each occur once, and metadata globals are + # per-wrapper suffixed. ``_reserve`` guards it: a collision fails loudly (rename/namespace + # needed) rather than silently rebinding a name. + emitted_names = set(inner_module_names) | { + "call", + "_inner_call", + "_rebuild", + "contextlib", + _ORCH_ENTRY, + } + + def _reserve(name: str) -> None: + if name in emitted_names: + raise NotImplementedError( + "aot_autograd.compile_to_python: generated top-level name " + f"{name!r} collides with another top-level name in the composed module; " + "inlining the runtime wrappers would shadow a binding." + ) + emitted_names.add(name) + + # Reserve every wrapper def name up front (before hoists) so a hoisted global cannot + # shadow a def and two wrappers cannot share a name. + for _g in (*non_orch, orch): + _reserve(_g.fn_name) + + def _resolve_globals(globals_dict: dict[str, object]) -> list[tuple[str, str]]: + # Resolve each global a wrapper closes over to a standalone source expression. + # ``globals_dict`` is the pre-exec snapshot from codegen.py, so the + # interpreter ``__builtins__`` is absent; the skip is kept defensively in case a + # future caller hands us a post-exec live dict. + out: list[tuple[str, str]] = [] + for gname, gobj in globals_dict.items(): + if gname == "__builtins__": + continue + expr = _resolve_global( + gobj, + helper_table, + inner_call_id, + fn_id_to_name, + imports, + orch_closure_id, + _ORCH_ENTRY, + ) + out.append((gname, expr)) + return out + + def _emit_inline(source: str, globals_dict: dict[str, object]) -> str: + # Splice the wrapper's def verbatim at module scope, hoisting each closed-over global + # to a top-level assignment (skipping a name already module-available -- an imported + # helper or ``torch`` -- detected as gname == its resolved expr). No exec / private + # namespace: the def reads as ordinary code and is referenced by its own name. Each + # hoisted name is ``_reserve``'d so a collision fails loudly rather than rebinding. + hoists: list[str] = [] + for gname, expr in _resolve_globals(globals_dict): + if gname == expr: + continue # already at module scope (an import / ``torch``) + _reserve(gname) + hoists.append(f"{gname} = {expr}") + return "\n".join(hoists + [source, ""]) + + # Inner-side wrappers first (subclass / RNG chain wrappers innermost-to-outermost, + # plus the epilogue helpers), then the orchestration, then the outer wrappers -- all + # spliced as real defs. An inner wrapper's hoisted inner-ref (``compiled_fn``) + # references ``_inner_call`` / a sibling emitted earlier; an outer wrapper's inner-ref + # references the orchestration entry adapter / a sibling emitted earlier -- so order + # is satisfied. + inner_blocks = [_emit_inline(g.source, g.globals_dict) for g in inner_side] + orch_block = _emit_inline(orch.source, orch.globals_dict) + outer_blocks = [_emit_inline(g.source, g.globals_dict) for g in outer_wrappers] + + # Imports (helper table + whatever emit_value added) are emitted BEFORE the inner + # module and the wrapper blocks, so a later top-level binding of the same name -- an + # inner-module binding or a hoisted wrapper global -- would shadow the import. And + # _emit_inline skips hoisting a global whose resolved expr already equals its own name + # (an imported helper referenced as ``gname == expr``), so such a wrapper would then + # silently bind to the shadowing object instead of the helper. ``from X import Y`` + # names bind a specific (non-module) object and are the ones at risk; plain ``import + # mod`` names resolve to the same singleton module no matter who imports them, so a + # duplicate binding is benign and is left unchecked (else ``import torch`` -- which the + # inner module also emits -- would trip a spurious collision). ``_reserve`` fails loudly + # if an inner-module name or a hoisted global collides with one of these import names. + for stmt in sorted(imports): + node = ast.parse(stmt).body[0] + if isinstance(node, ast.ImportFrom): + for alias in node.names: + _reserve(alias.asname or alias.name) + + # The final ``call`` invokes the outermost outer wrapper (else the orchestration + # directly). Build that line now so the wiring guard's corpus includes it -- the + # outermost outer wrapper is referenced ONLY there. + if outer_wrappers: + outermost_name = fn_id_to_name[id(outer_wrappers[-1].fn)] + final_invoke = f" return {outermost_name}(list(flat_inputs))" + else: + final_invoke = ( + f" return {orch.fn_name}(\n" + f" {chain_head}, contextlib.nullcontext, lambda: None, " + "list(flat_inputs)\n )" + ) + + # The single-arg adapter over the orchestration (emitted only when outer wrappers + # wrap it). The outer wrappers call their inner as ``fn(args)``; this adapts the + # orchestration's positional (_compiled_fn_, _first_ctx_, _on_before_call_, args) + # signature to that. When there are no outer wrappers the orchestration is invoked + # directly in ``call`` (see final_invoke). + orch_invoke_comment = [ + " # The 2nd/3rd positional args INTENTIONALLY substitute contextlib.nullcontext", + " # for the runtime's first-invocation context (_FirstInvocationContext) and a", + " # no-op for the profiler-prologue exit. This drops two cold-start diagnostics:", + " # the first-call custom-op aliasing analysis (_AnalyzeCustomOpInputOutputMode,", + " # active when check_custom_op_aliasing is set, which can even RAISE under", + " # error_on_custom_op_aliasing) and the profiler prologue. Neither affects", + " # numerics, so this is not a bug -- the standalone artifact deliberately omits", + " # them. (See the positional-mapping note in _compose_standalone_module.)", + ] + entry_block: list[str] = [] + if outer_wrappers: + entry_block = [ + f"def {_ORCH_ENTRY}(args):", + " # Single-arg adapter so the CompilerWrappers applied AROUND the", + " # orchestration (dedup / synthetic base) can invoke it as ``fn(args)``.", + *orch_invoke_comment, + f" return {orch.fn_name}(", + f" {chain_head}, contextlib.nullcontext, lambda: None, args", + " )", + "", + ] + + # _INNER_NAMES detection is a hardcoded allowlist (see above). If AOTAutograd adds + # a forward wrapper that names its inner via an unrecognized global, that wrapper + # is captured but may never be wired into the module -- silently composing a + # structurally-wrong result. Enforce that every captured non-orch wrapper is + # actually referenced somewhere: as the inner chain head, in the final ``call`` + # (the outermost outer wrapper), or by name in another block (another wrapper's + # globals, the orchestration's epilogue helpers -- e.g. ``_alias_fn`` / + # ``_apply_mutations`` -- or the entry adapter). A wrapper whose name appears in no + # other block went unwired, so reject rather than emit a wrong module. + block_of = {id(g): b for g, b in zip(inner_side, inner_blocks)} + block_of.update({id(g): b for g, b in zip(outer_wrappers, outer_blocks)}) + other_text = "\n".join( + inner_blocks + [orch_block] + entry_block + outer_blocks + [final_invoke] + ) + for g in non_orch: + name = fn_id_to_name[id(g.fn)] + own = block_of[id(g)] + elsewhere = other_text.replace(own, "", 1) + # Whole-token match: ``name`` is a wrapper def name (e.g. ``inner_fn``); a raw + # substring test would treat ``inner_fn`` as wired whenever a longer token like + # ``inner_fn2`` is referenced, silently defeating this guard. + wired = re.search(r"\b" + re.escape(name) + r"\b", elsewhere) is not None + if name != chain_head and not wired: + raise NotImplementedError( + "aot_autograd.compile_to_python could not wire captured runtime " + f"wrapper {g.fn_name!r} into the module (an inner-call global may be " + "unrecognized; see _INNER_NAMES)." + ) + + # The module splices ``_inner_call = call`` below, relying on inner_python binding a + # module-level ``call`` entry point. Inductor emits this in one of two forms: the + # flat path defines ``def call(args):`` (FunctionDef) while the graph_partition Runner + # path binds ``call = runner.call`` (Assign with a Name target). Verify one is present + # so a future inductor codegen drift fails loudly here -- like the orchestration / + # chain / wiring guards above -- instead of surfacing as a bare NameError at exec of + # the generated module. (``inner_tree`` was parsed once up front.) + binds_call = any( + (isinstance(n, ast.FunctionDef) and n.name == "call") + or ( + isinstance(n, ast.Assign) + and any(isinstance(t, ast.Name) and t.id == "call" for t in n.targets) + ) + for n in inner_tree.body + ) + if not binds_call: + raise NotImplementedError( + "compile_to_python: inner Inductor module does not bind a module-level " + "'call' entry point (the inner-call contract); the standalone module " + "splices ``_inner_call = call`` and must be updated to match." + ) + + # Only emit the _rebuild helper if a baked value actually reconstructs through it. + needs_rebuild = any( + "_rebuild(" in b for b in (*inner_blocks, orch_block, *outer_blocks) + ) + + # ``call`` invokes the orchestration directly when nothing wraps it; when outer + # wrappers do, its body just calls the outermost of them (which drives the entry + # adapter, then the orchestration) -- so the orchestration-substitution comment lives + # on whichever site actually invokes the orchestration. + if outer_wrappers: + call_body = [ + " # Invokes the outer CompilerWrapper chain (dedup / synthetic base), which", + f" # wraps {_ORCH_ENTRY} (the orchestration adapter).", + final_invoke, + ] + else: + call_body = [ + " # AOTAutograd orchestration: disables grad, invokes the inner chain,", + " # bumps mutated-input versions, applies the output epilogue.", + " #", + *orch_invoke_comment, + final_invoke, + ] + + parts = [ + _MODULE_HEADER, + "import contextlib", + *sorted(imports), + "", + "", + *(_REBUILD_HELPER if needs_rebuild else []), + "# " + "=" * 70, + "# Inner Inductor output code (kernels + ``call``)", + "# " + "=" * 70, + inner_python, + "_inner_call = call", + "", + "# " + "=" * 70, + "# AOTAutograd runtime wrappers (codegen'd): each inlined as a real def with its", + "# closed-over globals hoisted to module scope -- inner chain wrappers first, then", + "# the orchestration, then any outer wrappers (dedup / synthetic base) that wrap it", + "# " + "=" * 70, + *inner_blocks, + orch_block, + *entry_block, + *outer_blocks, + "", + "def call(flat_inputs): # noqa: F811", + *call_body, + "", + ] + return "\n".join(parts) + + +def _find_effectful_op(gm: GraphModule, get_effect: Any) -> Any: + """Return the first effectful op target reachable from ``gm``, or None. + + The target may be an ``OpOverload`` (e.g. ``aten::_print``) or a + ``HigherOrderOperator`` -- ``call_torchbind`` / ``hop_print`` / + ``invoke_leaf_function`` are registered ``_EffectType.ORDERED`` HOPs, not + OpOverloads -- so both are checked (``get_effect`` returns None for a + non-effectful HOP like ``cond``). + + Walks the graph and descends into any child GraphModule a node references -- a + HOP (cond/while_loop/scan) holds its body as a get_attr'd submodule or passes it + directly as a node arg -- so an effect nested inside a HOP subgraph is caught, not + just effects at the top level.""" + import torch + from torch.fx import GraphModule as _GraphModule + + seen: set[int] = set() + + def _scan(g: _GraphModule) -> Any: + if id(g) in seen: + return None + seen.add(id(g)) + for node in g.graph.nodes: + if ( + node.op == "call_function" + and isinstance( + node.target, + (torch._ops.OpOverload, torch._ops.HigherOrderOperator), + ) + and get_effect(node.target) is not None + ): + return node.target + for sub in _iter_subgraphs(g, node): + found = _scan(sub) + if found is not None: + return found + return None + + def _walk_values(value: Any) -> Iterator[_GraphModule]: + # A GraphModule can appear as a direct node arg OR nested one level (or more) + # inside a list/tuple/dict arg -- some HOPs pass their branch/body callables + # inside a container -- so descend into containers before the isinstance check, + # otherwise the recursive effect scan would never enter that nested subgraph. + if isinstance(value, _GraphModule): + yield value + elif isinstance(value, (list, tuple)): + for item in value: + yield from _walk_values(item) + elif isinstance(value, dict): + for item in value.values(): + yield from _walk_values(item) + + def _iter_subgraphs(g: _GraphModule, node: Any) -> Iterator[_GraphModule]: + # A child graph reaches a node either as an attribute fetched by get_attr or + # as a (possibly container-nested) argument (the form HOPs use for their + # branch/body callables). make_fx emits FLAT get_attr targets (e.g. + # true_graph_0) since _scan recurses per-GraphModule, so a plain getattr + # suffices (no dotted walk needed here). + if node.op == "get_attr": + attr = getattr(g, node.target, None) + if isinstance(attr, _GraphModule): + yield attr + for arg in (*node.args, *node.kwargs.values()): + yield from _walk_values(arg) + + return _scan(gm) + + +def _graph_has_dynamic_shapes(gm: GraphModule) -> bool: + """True if any placeholder is itself a SymInt or carries symbolic (SymInt) size, + stride, or storage-offset metadata -- i.e. the graph was traced with dynamic dims. + Drives the shapes mode for the capture pass: dynamic graphs stay dynamic, static + graphs specialize so the composer can bake their (static) view metadata. Strides and + storage offset are checked too, not just sizes: a graph dynamic solely via symbolic + strides has static sizes, and treating it as static would silently specialize the + artifact to the example strides. (Unbacked symints appearing only in intermediates, + not on any placeholder, are still missed here, but such a graph fails loudly + downstream when emit_value rejects the still-symbolic metadata.)""" + import torch + + def _is_symbolic(v: Any) -> bool: + return isinstance(v, torch.SymInt) + + for node in gm.graph.nodes: + if node.op != "placeholder": + continue + val = node.meta.get("val") + if _is_symbolic(val): + return True + if isinstance(val, torch.Tensor) and ( + any(_is_symbolic(s) for s in val.shape) + or any(_is_symbolic(s) for s in val.stride()) + or _is_symbolic(val.storage_offset()) + ): + return True + return False + + +def compile_to_python( + gm: GraphModule, + example_inputs: Sequence[Any], + *, + options: dict[str, Any] | None = None, +) -> tuple[str, bytes | None]: + """Compile ``gm`` to ``(python_code, cache)``; see the module docstring. + + THREADING: serialized by a process-global lock (``_COMPILE_LOCK``). The wrapper-source + capture is thread-local, but the AOTAutograd pass and the inner inductor compile both + swap process-global cache state (``CacheArtifactManager.with_fresh_cache()``); a + concurrent compile on another thread would corrupt the captured wrappers or cache + artifacts, so concurrent calls (including via ``torch.compiler.precompile``) are + serialized rather than run in parallel. + """ + import copy + + import torch + from torch._higher_order_ops.effects import _get_effect + from torch._inductor import compile_to_python as _inductor_compile_to_python + from torch._inductor.compile_fx import compile_fx + from torch._inductor.standalone_compile import ( + _resolve_ignore_shape_env, + _standalone_context, + ) + from torch.fx.graph_module import _share_torchbind_and_process_group_on_deepcopy + + from .utils import make_boxed_func + + # Validate up front: this layer dereferences ``gm.graph`` (the effectful-op scan + # below) before reaching inductor's own type-check, so a non-GraphModule would + # otherwise surface as an opaque AttributeError instead of this clear contract error. + if not isinstance(gm, torch.fx.GraphModule): + raise TypeError( + "aot_autograd.compile_to_python expects a post-AOTAutograd " + f"torch.fx.GraphModule, got {type(gm)}." + ) + + # Effectful ops thread effect tokens through a calling convention the standalone + # composition does not reproduce (and their with_effects HOP is non-cacheable); + # reject them up front with a concrete reason. Not supported yet. (Detected here + # too, not only in torch.compiler.precompile's capture-time guard, so direct callers of + # this lowering get the same clear failure rather than a silently-wrong artifact.) + # Scan recursively: a HOP (cond/while_loop/scan) carries its body as a child + # GraphModule referenced by a get_attr node (or passed directly as a node arg), so + # effects nested in such a subgraph would be missed by a top-level-only scan. + effectful = _find_effectful_op(gm, _get_effect) + if effectful is not None: + raise NotImplementedError( + "aot_autograd.compile_to_python cannot lower this graph to standalone " + f"source: it contains an effectful op ({effectful}), which is not " + "supported yet." + ) + + with _COMPILE_LOCK: + # Run AOTAutograd ONCE to do two things: (1) produce the dense, decomposed, + # functionalized inner graph, and (2) codegen its runtime-wrapper chain, which the + # thread-local ``capture_generated_sources`` sink records. A capture-only inner + # compiler grabs the dense graph and returns a placeholder boxed callable, so + # AOTAutograd still builds and codegen's the wrappers AROUND it -- that codegen is + # what we capture. Inductor is NOT run in this pass; it runs exactly once below, on + # the captured dense graph, via the ``_inductor_compile_to_python`` call (which + # drives inductor's ``compile_fx_inner`` directly, not a re-entry into AOTAutograd). + # The composer swaps the placeholder (the wrappers' inner reference) for the + # inner inductor ``call`` by object identity, so the placeholder is only a + # compile-time token and never runs. + captured: list[GeneratedSource] = [] + dense: dict[str, Any] = {} + + def _capture_inner_compile(dense_gm, dense_inputs, **kwargs): + if "gm" in dense: + raise NotImplementedError( + "aot_autograd.compile_to_python does not support a graph whose " + "AOTAutograd lowering emits more than one inner forward graph." + ) + dense["gm"] = dense_gm + # Retain the placeholder's IDENTITY: it is the authoritative inner call the + # runtime-wrapper chain closes over. The composer needs it to tell the inner + # call apart from the orchestration's own outer closure (both surface as a + # wrapper's inner-ref yet neither is a captured wrapper fn), which is what + # separates INNER wrappers from the OUTER dedup / synthetic-base wrappers. + placeholder = make_boxed_func(dense_gm.forward) + dense["placeholder"] = placeholder + return placeholder + + # Drive inductor's own ``compile_fx`` (i.e. its exact AOTAutograd invocation -- + # decomposition table + aot config) but swap in the capture inner compiler so the + # dense graph is intercepted before codegen and no inductor compile happens. Using + # compile_fx (rather than calling aot_autograd directly) guarantees the dense graph + # matches what the step-2 inductor compile below expects. Pick the shapes mode from + # the graph (there is no dynamic_shapes knob): a symbolically-traced graph uses + # ``"from_graph"`` to stay dynamic, a static one ``"from_example_inputs"`` to + # specialize -- matching what the composer can bake (symbolic view metadata is + # rejected downstream). no_grad pins the inference path (one forward module). + # Deepcopy first so compile_fx cannot mutate the caller's gm (torchbind + # ProcessGroups smuggled through as shared references). Note: the raw-collective / + # torchbind rewrites are inductor-lowering prereqs and belong to the step-2 inductor + # compile, which applies them to the dense graph -- not duplicated here. + shapes_mode = ( + "from_graph" if _graph_has_dynamic_shapes(gm) else "from_example_inputs" + ) + with ( + torch.no_grad(), + _standalone_context(gm, shapes_mode, aot=False), + capture_generated_sources(captured), + ): + with _share_torchbind_and_process_group_on_deepcopy(): + gm_owned = copy.deepcopy(gm) + compile_fx( + gm_owned, + example_inputs, + # Placeholder returns a boxed callable, not a full OutputCode; AOTAutograd + # only wraps it (never inductor-post-compiles it), so this is fine at runtime. + inner_compile=_capture_inner_compile, # pyrefly: ignore[bad-argument-type] + ignore_shape_env=_resolve_ignore_shape_env(shapes_mode), + ) + if "gm" not in dense: + raise RuntimeError( + "aot_autograd.compile_to_python: AOTAutograd never reached the inner " + "forward compiler, so no dense graph was captured." + ) + + inner_python, cache = _inductor_compile_to_python( + dense["gm"], example_inputs, options=options + ) + source = _compose_standalone_module( + inner_python, captured, dense["placeholder"] + ) + return source, cache + + +def load_from_python( + python_code: str, cache: bytes | None = None +) -> Callable[..., Any]: + """Load the module emitted by ``compile_to_python`` into a runnable ``call`` -- the + inverse of ``compile_to_python``: (python_code, cache) in, runnable ``call`` out. + + The composed module is self-contained -- the inductor kernels and the pure-Python + runtime wrappers are inlined -- so this delegates straight to the inductor loader: + ``python_code`` runs standalone (kernels JIT-compile on first use), and ``cache`` (the + inductor accelerator bundle this layer forwards) warms the kernel caches so exec loads + the precompiled binaries instead of recompiling. There is no separate aot-level load + step: exec'ing the module yields the aot-composed top-level ``call`` directly, and the + wrappers carry no kernels to load. + """ + from torch._inductor import load_from_python as _inductor_load_from_python + + return _inductor_load_from_python(python_code, cache) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..50e0cb5d9fed8f41f01da498ac60c639443bd775 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py @@ -0,0 +1,907 @@ +""" +Contains various utils for AOTAutograd, including those for handling collections. +""" + +import copy +import dataclasses +import logging +import operator +import sys +import warnings +from collections.abc import Callable, Sequence +from contextlib import nullcontext +from functools import partial, wraps +from typing import Any, overload, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar, TypeVarTuple, Unpack + +import torch +import torch.utils._pytree as pytree +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class_obj +from torch._logging import getArtifactLogger +from torch._subclasses.fake_tensor import is_fake_tensor +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import py_sym_types + + +_T = TypeVar("_T") +if TYPE_CHECKING: + from torch.distributed._functional_collectives import AsyncCollectiveTensor + + from .schemas import AOTConfig, ViewAndMutationMeta + + +KNOWN_TYPES = [ + torch.Tensor, + BackwardState, + int, + str, + float, + bool, + type(None), + *py_sym_types, + FakeScriptObject, + torch.ScriptObject, +] + +aot_graphs_effects_log = getArtifactLogger(__name__, "aot_graphs_effects") +annotation_log = getArtifactLogger(__name__, "annotation") + +strict_zip = partial(zip, strict=True) + + +def get_loaded_async_collective_tensor_type() -> type["AsyncCollectiveTensor"] | None: + """Return the ACT type if distributed collectives are already loaded.""" + if "torch.distributed._functional_collectives" not in sys.modules: + return None + from torch.distributed._functional_collectives import AsyncCollectiveTensor + + return AsyncCollectiveTensor + + +def import_async_collective_tensor_type() -> type["AsyncCollectiveTensor"]: + """Import and return the ACT type.""" + from torch.distributed._functional_collectives import AsyncCollectiveTensor + + return AsyncCollectiveTensor + + +def is_async_collective_tensor_type(pytype: type) -> bool: + """Whether pytype is the AsyncCollectiveTensor type (False if not loaded).""" + act = get_loaded_async_collective_tensor_type() + return act is not None and pytype is act + + +def partial_flatten_asdict(obj: object) -> Any: + if dataclasses.is_dataclass(obj): + return { + field.name: getattr(obj, field.name) for field in dataclasses.fields(obj) + } + elif isinstance(obj, (list, tuple)): + return obj.__class__([partial_flatten_asdict(item) for item in obj]) + elif isinstance(obj, dict): + return {k: partial_flatten_asdict(v) for k, v in obj.items()} + else: + return obj + + +@overload +def normalize_as_list(x: _T) -> list[_T]: ... +@overload +def normalize_as_list(x: tuple[_T, ...]) -> list[_T]: ... +@overload +def normalize_as_list(x: list[_T]) -> list[_T]: ... + + +def normalize_as_list(x: object) -> list[object]: + if isinstance(x, tuple): + return list(x) + elif isinstance(x, list): + return x + return [x] + + +def _get_autocast_states() -> list[Any]: + return [ + torch.is_autocast_enabled("cuda"), + torch.is_autocast_enabled("cpu"), + torch.get_autocast_dtype("cuda"), + torch.get_autocast_dtype("cpu"), + torch.is_autocast_cache_enabled(), + ] + + +def make_boxed_func(f: Callable[..., Any]) -> Callable[[list[Any]], Any]: + @simple_wraps(f) + def g(args: list[Any]) -> Any: + return f(*args) + + # pyrefly: ignore[missing-attribute] + g._boxed_call = True + return g + + +def make_boxed_compiler( + compiler: Callable[..., Any], +) -> Callable[..., Any]: + @wraps(compiler) + def f(fx_g: Any, inps: Any) -> Any: + out_f = compiler(fx_g, inps) + fx_g = make_boxed_func(out_f) + return fx_g + + return f + + +def call_func_at_runtime_with_args( + f: Callable[..., Any], + args: Sequence[Any], + steal_args: bool = False, + disable_amp: bool = False, +) -> list[Any]: + if not steal_args: + args = list(args) + if not isinstance(args, list): + raise AssertionError(f"args must be a list, got {type(args)}") + + context = torch._C._DisableAutocast if disable_amp else nullcontext + with context(): + if getattr(f, "_boxed_call", False): + out = normalize_as_list(f(args)) + else: + # TODO: Please remove soon + # https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 + warnings.warn( + "Your compiler for AOTAutograd is returning a function that doesn't take boxed arguments. " + "Please wrap it with functorch.compile.make_boxed_func or handle the boxed arguments yourself. " + "See https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 for rationale.", + stacklevel=2, + ) + out = normalize_as_list(f(*args)) + return out + + +# Inspired by autodidax (thanks!) +class PytreeThunk: + spec: pytree.TreeSpec | None = None + # These are some kinda dumb microoptimizations that save about 3-4 us of overhead. + is_simple: bool | None = ( + None # if the output spec is a tuple/list, we won't bother unflattening it. + ) + is_really_simple: bool | None = None # if the output spec is a LeafSpec + + def set(self, spec: pytree.TreeSpec) -> None: + if not (self.spec is None or self.spec == spec): + raise AssertionError(f"spec mismatch: existing={self.spec}, new={spec}") + if spec is None: + raise AssertionError("spec must not be None") + self.spec: pytree.TreeSpec = spec + if self.spec.type in {tuple, list} and all( + child.is_leaf() for child in spec.children() + ): + self.is_simple = True + if self.spec.is_leaf(): + self.is_really_simple = True + + def unflatten(self, x: Sequence[Any]) -> Any: + if self.is_really_simple: + return x[0] + if self.is_simple: + return x + if self.spec is None: + raise AssertionError("spec must be set before calling unflatten") + return pytree.tree_unflatten(x, self.spec) + + +# Creates a function that returns flattened inputs and outputs +# Also returns the output tree spec, which is needed to recover the "unflattened" +# output tree structure later. +def create_tree_flattened_fn( + fn: Callable[..., Any], + args: Sequence[Any], + kwargs: dict[str, Any] | None = None, +) -> tuple[Callable[..., list[Any]], PytreeThunk]: + if kwargs is None: + kwargs = {} + # Save the args_spec for flat_tensor_args to unflatten while tracing + _, tensor_args_spec = pytree.tree_flatten((args, kwargs)) + out_spec = PytreeThunk() + + def flat_fn(*flat_args: Any) -> list[Any]: + # The input are flattened tensor args. Prepare the args in the + # order that original function expects. Add static args as well. + # They will appear as tensor constants in the traced graph. + nonlocal out_spec + args, kwargs = pytree.tree_unflatten(flat_args, tensor_args_spec) + tree_out = fn(*args, **kwargs) + flat_out, spec = pytree.tree_flatten(tree_out) + for i in flat_out: + is_known_type = isinstance(i, tuple(KNOWN_TYPES)) or is_custom_class_obj(i) + if not is_known_type: + raise RuntimeError( + f"Found {type(i)} in output, which is not a known type. " + "If this type holds tensors, you need to register a pytree for it. " + "See https://github.com/pytorch/functorch/issues/475 for a brief " + "explanation why. If you don't need to register a pytree, please " + "leave a comment explaining your use case and we'll make this more " + "ergonomic to deal with" + ) + out_spec.set(spec) + return flat_out + + # Can't use functools.wraps here because the wrapper has different + # calling convention + if hasattr(fn, "_orig_mod"): + # pyrefly: ignore[missing-attribute] + flat_fn._orig_mod = fn._orig_mod + + return flat_fn, out_spec + + +# This function takes in a tensor t, and returns one of t, t.view(), or t.clone(). +# When tracing the joint forward + backward, for any inputs in the graph that are mutated, +# we need to clone them first (and similarly for metadata-only mutations, we need to view them first). +# The idea is that when we trace the backward, we need to pass in the *original* primals +# to autograd.grad(), before they were mutated. +# Note: when we have synthetic base inputs, we need to clone them *before* creating views off of them. +# This means that "idx" here represents the index of the (potentially) synthetic base. +# What we need to do is: +# (1) map the current (post-synthetic-base calling convention) input argument index +# to int index pre-synthetic-base-calling-convention. +# (2) There could be multiple, if this index corresponds to a synthetic base +# that has multiple input aliases. +# (3) If any of those corresponding inputs get metadata mutations, then we clone the base. +def maybe_to_fresh_input(idx: int, t: Any, meta: "ViewAndMutationMeta") -> Any: + if not isinstance(t, torch.Tensor): + return t + if idx in meta.mutated_inp_runtime_indices: + # We only need to bother cloning mutated inputs that participate in autograd. + if meta.input_info[idx].requires_grad and meta.input_info[idx].mutates_data: + # Make sure the primal we pass to autograd.grad() + # sees the tensor before the mutation + return t.clone() + if meta.input_info[idx] and meta.input_info[idx].mutates_metadata: + # Make sure the primal we pass to autograd.grad() + # sees the tensor before the metadata mutation + return t.view(t.shape) + return t + + +def is_with_effects(node: torch.fx.Node) -> bool: + if ( + node.op == "call_function" + and node.target is torch.ops.higher_order.with_effects + ): + return True + elif ( + node.op == "call_function" + and node.target is torch.ops.higher_order.invoke_subgraph + ): + # Check if subgraph has effects by looking in the cache + from torch._guards import InvokeSubgraphCache, TracingContext + + tracing_ctx = TracingContext.try_get() + if tracing_ctx: + invoke_subgraph_cache = tracing_ctx.hop_dispatch_set_cache.get_cache( + torch.ops.higher_order.invoke_subgraph + ) + if invoke_subgraph_cache: + if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache): + raise AssertionError( + f"expected InvokeSubgraphCache, got {type(invoke_subgraph_cache)}" + ) + # pyrefly: ignore[bad-argument-type] + effects = invoke_subgraph_cache.get_effects(node.args[1]) + return effects is not None + return False + + +def unlift_tokens( + fw_module: torch.fx.GraphModule, + fw_metadata: "ViewAndMutationMeta", + aot_config: "AOTConfig", + bw_module: torch.fx.GraphModule | None = None, +) -> None: + # Remove the tokens from the inputs/outputs of the graph since inductor does + # not want these extra inputs/outputs, and replace them with + # _make_token() to create a token, and _sink_tokens() to collect the + # tokens. See Note [Side-Effectful Tokens in AOTAutograd] + # Logic: + # 1. In the case of with_effects: + # Before: + # ``` + # def forward(self, token, arg1_1): + # with_effects = torch.ops.higher_order.with_effects(token, ...) + # getitem = with_effects[0] + # getitem_1 = with_effects[0] + # return (getitem, getitem_1) + # ``` + # + # After: + # ``` + # def forward(self, arg1_1): + # _make_token_default = torch.ops.prims._make_token.default() + # with_effects = torch.ops.higher_order.with_effects(_make_token_default, ...) + # getitem = with_effects[0] + # getitem_1 = with_effects[0] + # _sink_tokens_default = torch.ops.prims._sink_tokens.default([getitem]); + # return (getitem_1,) + # ``` + # + # 2. In the case of an invoke_subgraph node, we will use the + # InvokeSubgraphCache to determine if the subgraph has effects. Then we will + # turn it into a `with_effects` node. This is so that at the toplevel graph, + # the nodes will have the correct with_effects threading. We will apply this + # pass recursively to submodules so the tokens will be removed from the + # subgraph's inputs. + # + # Before: + # ``` + # def forward(self, token, arg1_1): + # repeated_subgraph0 = self.repeated_subgraph0 + # invoke_subgraph = torch.ops.higher_order.invoke_subgraph( + # repeated_subgraph0, 'subgraph_0', token, x, arg1_1) + # getitem = invoke_subgraph[0] + # getitem_1 = invoke_subgraph[1] + # return (getitem, getitem1) + # ``` + # + # After: + # ``` + # def forward(self, arg1_1): + # _make_token_default = torch.ops.prims._make_token.default() + # repeated_subgraph0 = self.repeated_subgraph0 + # with_effects_1 = torch.ops.higher_order.with_effects( + # _make_token_default, torch.ops.higher_order.invoke_subgraph, + # repeated_subgraph0, 'subgraph_0', arg1_1) + # getitem = with_effects_1[0] + # getitem_1 = with_effects_1[1]; with_effects_1 = None + # _sink_tokens_default = torch.ops.prims._sink_tokens.default([getitem]) + # return (getitem_1,) + # ``` + # + # 3. The toplevel module should have the following invariants: + # forward: + # expected_num_erased_inputs == len(fw_metadata.tokens) + # expected_num_erased_outputs == len(fw_metadata.tokens) + # backward: + # expected_num_erased_inputs == fw_metadata.num_backward_tokens + # expected_num_erased_outputs == fw_metadata.num_backward_tokens + num_forward_tokens = len(fw_metadata.tokens) + num_backward_tokens = fw_metadata.num_backward_tokens + + def replace_input_token_with_make_token( + module: torch.fx.GraphModule, node: torch.fx.Node + ) -> None: + with module.graph.inserting_before(node): + new_token_node = module.graph.call_function( + torch.ops.prims._make_token.default, () + ) + new_token_node.meta["val"] = torch.tensor([]) + new_token_node.meta["tensor_meta"] = torch.tensor([]) + node.replace_all_uses_with(new_token_node) + module.graph.erase_node(node) + + def get_output_tokens(node: torch.fx.Node) -> set[torch.fx.Node]: + output_tokens = set() + for user in list(node.users.keys()): + # Check if this is a getitem accessing index 0 (the token) + if ( + user.op == "call_function" + and user.target is operator.getitem + and len(user.args) > 1 + and user.args[1] == 0 + ): + # Check if this getitem is used in an output + for user_user in list(user.users.keys()): + if user_user.op == "output": + output_tokens.add(user) + return output_tokens + + def _unlift_tokens_from_module_helper( + module: torch.fx.GraphModule, + subgraph_str: str, + expected_num_erased: int | None, + ) -> None: + input_token_nodes = set() + output_token_nodes = set() + + for node in module.graph.nodes: + if ( + node.op == "call_function" + and node.target is torch.ops.higher_order.with_effects + ): + if node.args[0].op == "placeholder": + input_token_nodes.add(node.args[0]) + replace_input_token_with_make_token(module, node.args[0]) + + tokens_from_with_effects = get_output_tokens(node) + output_token_nodes = output_token_nodes | tokens_from_with_effects + + elif ( + node.op == "call_function" + and node.target is torch.ops.higher_order.invoke_subgraph + ): + subgraph_node, identifier, *operands = node.args + + # Check if subgraph has effects by looking in the cache + from torch._guards import InvokeSubgraphCache, TracingContext + + effects = None + tracing_ctx = TracingContext.try_get() + if tracing_ctx: + invoke_subgraph_cache = ( + tracing_ctx.hop_dispatch_set_cache.get_cache( + torch.ops.higher_order.invoke_subgraph + ) + ) + if invoke_subgraph_cache: + if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache): + raise AssertionError( + f"expected InvokeSubgraphCache, got {type(invoke_subgraph_cache)}" + ) + effects = invoke_subgraph_cache.get_effects(identifier) + + if effects is not None: + # Wrap invoke_subgraph with with_effects + # Before: invoke_subgraph(subgraph, id, token, *args) -> (token_out, result) + # After: with_effects(token, invoke_subgraph, subgraph, id, *args) -> (token_out, result) + # + # Note: The subgraph itself will be unlifted separately when we iterate + # through named_modules() below. + + num_tokens = len(effects) + if num_tokens != 1: + raise AssertionError( + f"Multiple token subgraph NYI, got {num_tokens} tokens" + ) + token_args = operands[:num_tokens] + non_token_args = operands[num_tokens:] + + # Create with_effects wrapper around invoke_subgraph + # with_effects(token, op, *args) where op is invoke_subgraph + # Pass the subgraph and non-token args to invoke_subgraph + with module.graph.inserting_before(node): + new_node = module.graph.call_function( + torch.ops.higher_order.with_effects, + # pyrefly: ignore [bad-argument-type] + ( + token_args[0], # pyrefly: ignore[bad-argument-type] + torch.ops.higher_order.invoke_subgraph, + subgraph_node, + identifier, + *tuple(non_token_args), + ), + ) + node.replace_all_uses_with(new_node) + new_node.meta = node.meta + module.graph.erase_node(node) + + for token in token_args: + if token.op == "placeholder": + input_token_nodes.add(token) + replace_input_token_with_make_token(module, token) + + # Get output tokens from the new with_effects node + tokens_from_invoke_subgraph = get_output_tokens(new_node) + output_token_nodes = ( + output_token_nodes | tokens_from_invoke_subgraph + ) + + if not output_token_nodes and not input_token_nodes: + return + + output_node = next(reversed(module.graph.find_nodes(op="output"))) + if output_node is None: + raise AssertionError("output node not found in graph") + with module.graph.inserting_before(output_node): + module.graph.call_function( + torch.ops.prims._sink_tokens.default, + (list(output_token_nodes),), + ) + new_out_args = tuple( + [out for out in output_node.args[0] if out not in output_token_nodes] + ) + output_node.args = (new_out_args,) + + if expected_num_erased: + if len(input_token_nodes) != expected_num_erased: + raise AssertionError( + f"{subgraph_str} num_erased_inputs:{len(input_token_nodes)} " + f"{input_token_nodes} != expected {expected_num_erased} \n" + f"{fw_module.print_readable(print_output=False)}" + ) + if len(output_token_nodes) != expected_num_erased: + raise AssertionError( + f"{subgraph_str} num_erased_outs:{len(output_token_nodes)} " + f"{output_token_nodes} != expected {expected_num_erased} \n" + f"{fw_module.print_readable(print_output=False)}" + ) + + module.recompile() + + def unlift_tokens_from_module( + module: torch.fx.GraphModule, subgraph_str: str, expected_num_erased: int + ) -> None: + for name, m in module.named_modules(): + if isinstance(m, torch.fx.GraphModule): + if name == "": + _unlift_tokens_from_module_helper( + m, subgraph_str, expected_num_erased + ) + else: + # Subgraph -- we may or may not have effects applied + _unlift_tokens_from_module_helper(m, f"{subgraph_str}_{name}", None) + + if num_forward_tokens > 0: + if aot_config.enable_log: + from torch._dynamo.utils import lazy_format_graph_code + + aot_graphs_effects_log.debug( + "%s", + lazy_format_graph_code( + "Forward graph before unlifting tokens", + fw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + unlift_tokens_from_module( + fw_module, + "forward", + num_forward_tokens, + ) + + if bw_module is not None and num_backward_tokens > 0: + if aot_config.enable_log: + from torch._dynamo.utils import lazy_format_graph_code + + aot_graphs_effects_log.debug( + "%s", + lazy_format_graph_code( + "Backward graph before unlifting tokens", + bw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + unlift_tokens_from_module(bw_module, "backward", num_backward_tokens) + + # This is sad, but we need to update the metadata to get rid of + # the tokens. + fw_metadata.tokens = {} + fw_metadata.num_backward_tokens = 0 + + +def root_module_when_exporting_non_strict( + flat_fn: Callable[..., Any], +) -> torch.nn.Module | None: + # When exporting in non-strict mode, we wrap the root module in a specific pattern. + # See `_aot_export_non_strict` in torch.export._trace.py. + # We look for that wrapping pattern here. + if hasattr(flat_fn, "_orig_mod") and hasattr(flat_fn._orig_mod, "_export_root"): + return flat_fn._orig_mod._export_root + else: + return None + + +def _is_forward_node_with_seq_nr(node: torch.fx.Node) -> bool: + # For now, assume that if nn_module_stack_metadata is populated, this + # node is from the forward. Ignore nodes without `seq_nr`. + # TODO(future): there is likely a less brittle way to do this by walking + # the descendants of graph inputs corresponding to fwd inputs, didn't + # seem obvious at first glance on how to partition graph inputs into + # fwd vs bwd without relying on string names. + return node.meta.get("partitioner_tag") != "is_backward" and "seq_nr" in node.meta + + +def _is_backward_node_with_seq_nr(node: torch.fx.Node) -> bool: + # For now, assume that if nn_module_stack_metadata is not populated, + # this node is from the backward. Ignore nodes without `seq_nr`. + # TODO(future): there is likely a less brittle way to do this, same + # as with the forward. + return node.meta.get("partitioner_tag") == "is_backward" and "seq_nr" in node.meta + + +def _collect_fwd_nodes_from_subgraph( + fx_g: torch.fx.GraphModule, fwd_seq_nr_to_node: dict[str, torch.fx.Node] +) -> None: + """Collect forward nodes from a single subgraph into the global mapping.""" + for node in fx_g.graph.nodes: + if not _is_forward_node_with_seq_nr(node): + continue + seq_nr = node.meta["seq_nr"] + if seq_nr in fwd_seq_nr_to_node: + # If we already saw an op with the current `seq_nr`, that means + # that the current op did not create an autograd node, and there + # is no corresponding backward node, so we skip. + continue + fwd_seq_nr_to_node[seq_nr] = node + + +def _copy_metadata_to_bw_nodes_in_subgraph( + fx_g: torch.fx.GraphModule, fwd_seq_nr_to_node: dict[str, torch.fx.Node] +) -> None: + """Copy metadata from forward nodes to backward nodes in a single subgraph.""" + for node in fx_g.graph.nodes: + annotation_log.debug("node: %s", node.name) + seq_nr = node.meta.get("seq_nr") + annotation_log.debug("seq_nr: %s", seq_nr) + + if not _is_backward_node_with_seq_nr(node): + continue + + # We exclude gradient accumulation nodes from copying tags + if node.meta.get("is_gradient_acc", False): + annotation_log.debug("is_gradient_acc") + continue + + # fwd_node should always exist, but handle non-existence just in case + fwd_node = fwd_seq_nr_to_node.get(node.meta["seq_nr"]) + if fwd_node is not None: + node.meta["fwd_nn_module_stack"] = fwd_node.meta.get("nn_module_stack") + node.meta["fwd_source_fn_stack"] = fwd_node.meta.get("source_fn_stack") + # TODO: better to change to a specific field of custom? + custom = fwd_node.meta.get("custom") + if custom is not None: + # Merge rather than overwrite so bw-only keys survive + # fw keys win on conflict. + node.meta["custom"] = { + **node.meta.get("custom", {}), + **copy.deepcopy(custom), + } + + +def copy_fwd_metadata_to_bw_nodes(fx_g: torch.fx.GraphModule) -> None: + """ + Input: `fx_g` which contains the joint fwd+bwd FX graph created by + aot_autograd. + + This function walks the graph and copies over metadata from forward nodes + to backward nodes, using the `seq_nr` field as a one-to-many mapping + from forward node to backward node. This metadata is useful for performance + profiling and debugging. + + This function supports matching forward and backward nodes across different + subgraphs (e.g., in recursive submodules from HOPs), enabling backward nodes + in any submodule to match forward nodes in any submodule. + """ + + # Build a global mapping of seq_nr to forward nodes across all subgraphs + fwd_seq_nr_to_node: dict[str, torch.fx.Node] = {} + + # First pass: collect all forward nodes from all subgraphs + for submod in fx_g.modules(): + if isinstance(submod, torch.fx.GraphModule): + _collect_fwd_nodes_from_subgraph(submod, fwd_seq_nr_to_node) + + if annotation_log.isEnabledFor(logging.DEBUG): + for k, v in fwd_seq_nr_to_node.items(): + annotation_log.debug("forward:: key: %s, value: %s", k, v) + + # Second pass: copy metadata to backward nodes in all subgraphs + # using the global forward mapping + for submod in fx_g.modules(): + if isinstance(submod, torch.fx.GraphModule): + _copy_metadata_to_bw_nodes_in_subgraph(submod, fwd_seq_nr_to_node) + + +def register_buffer_assignment_hook( + mod: torch.nn.Module, assigned_buffers: dict[str, str] +) -> Any: + """ + Register a hook that intercepts buffer assignments. + This is used to detect when a buffer is assigned to, and then we can + map that buffer to the corresponding proxy node in the graph. + """ + + def _map_assigned_buffer_to_proxy( + _mod: torch.nn.Module, name: str, buffer: Any + ) -> Any: + # We intercept buffer assignments on the root module through this hook. + if _mod._buffers is mod._buffers: + # either buffer is a functional tensor, which wraps a fake tensor + if isinstance(buffer, FunctionalTensor): + buffer = buffer.from_functional() + # or buffer is a fake tensor + if not is_fake_tensor(buffer): + raise AssertionError(f"expected FakeTensor, got {type(buffer)}") + # The fake tensor in turn is associated with a proxy node. + proxy_mode = torch.fx.experimental.proxy_tensor.get_proxy_mode() + if proxy_mode is None: + raise AssertionError("proxy_mode must not be None") + proxy = torch.fx.experimental.proxy_tensor.get_proxy_slot( + buffer, proxy_mode.tracer + ).proxy.node + # We map the assigned buffer to this proxy node. + assigned_buffers[name] = proxy.name + return buffer + + return torch.nn.modules.module.register_module_buffer_registration_hook( + _map_assigned_buffer_to_proxy + ) + + +def contain_metadata_mutation_ops(module: torch.fx.GraphModule) -> bool: + """ + Checks if the module contains any metadata mutation ops. + """ + for node in module.graph.nodes: + if ( + node.op == "call_function" + and hasattr(node.target, "tags") + and torch.Tag.inplace_view in node.target.tags + ): + return True + return False + + +_GRAPHSAFE_RNG_DEVICE_TYPES: set[str] = {"cuda"} + + +def register_graphsafe_rng_device_type(device_type: str) -> None: + """Register a device type as supporting graphsafe RNG operations. + + The device backend module (``torch.``) must provide: + - ``_get_generator(device: torch.device) -> Generator``: return the default + generator for the given device. The generator must implement + ``graphsafe_get_state()``, ``graphsafe_set_state(state)``, and + ``clone_state()``. + - ``get_rng_state(device_index: int) -> Tensor``: return the current RNG + state tensor. + + Args: + device_type: The device type string (e.g. "cuda", "xpu"). + """ + from torch._prims.rng_prims import register_graphsafe_rng_dispatch + + key_name = torch._C._dispatch_key_for_device(device_type) + dispatch_key = getattr(torch._C.DispatchKey, key_name) + _GRAPHSAFE_RNG_DEVICE_TYPES.add(device_type) + register_graphsafe_rng_dispatch(dispatch_key) + + +def supports_graphsafe_rng(device: torch.device) -> bool: + """Check whether a device supports graphsafe RNG operations.""" + return device.type in _GRAPHSAFE_RNG_DEVICE_TYPES + + +def get_default_generator(device: torch.device) -> Any: + """Get the default RNG generator for a device. + + Calls ``torch.._get_generator(device)``. + """ + device_mod = getattr(torch, device.type, None) + if device_mod is None or not hasattr(device_mod, "_get_generator"): + raise AssertionError( + f"Device type '{device.type}' does not implement _get_generator. " + f"Registered graphsafe RNG types: {sorted(_GRAPHSAFE_RNG_DEVICE_TYPES)}." + ) + return device_mod._get_generator(device) + + +def get_device_rng_state(device: torch.device) -> torch.Tensor: + """Get the RNG state tensor for a device.""" + device_mod = getattr(torch, device.type, None) + if device_mod is not None and hasattr(device_mod, "get_rng_state"): + idx = device.index if device.index is not None else 0 + return device_mod.get_rng_state(idx) + return torch.get_rng_state() + + +def top_saved_tensors_hooks() -> Any: + return torch._C._autograd._top_saved_tensors_default_hooks(True) + + +def saved_tensors_hooks_are_inlineable(hooks: Any) -> bool: + if not hooks: + return False + pack, unpack = hooks + return isinstance(pack, torch.fx.GraphModule) and isinstance( + unpack, torch.fx.GraphModule + ) + + +_P = ParamSpec("_P") +_T = TypeVar("_T") +_S = TypeVar("_S") + + +def without_output_descs(f: Callable[_P, tuple[_T, _S]]) -> Callable[_P, _T]: + @wraps(f) + @simple_wraps(f) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _T: + return f(*args, **kwargs)[0] + + return inner + + +_P2 = ParamSpec("_P2") +_R = TypeVar("_R") +_R2 = TypeVar("_R2") + + +def simple_wraps( + f: Callable[_P, _R], +) -> Callable[[Callable[_P2, _R2]], Callable[_P2, _R2]]: + # NB: omit ('__module__', '__name__', '__qualname__') for ease of + # debugging + return wraps(f, assigned=("__doc__", "__annotations__", "__type_params__")) + + +_Ts = TypeVarTuple("_Ts") + + +def call_and_expect_output_descs( + fn: Callable[[*_Ts], tuple[Any, Any]], args: tuple[Unpack[_Ts]] +) -> tuple[Any, Any]: + from .descriptors import AOTOutput + + outs_pair = fn(*args) + if not (isinstance(outs_pair, tuple) and len(outs_pair) == 2): + raise AssertionError( + f"expected tuple of length 2, got {type(outs_pair)} with value {outs_pair}" + ) + outs, outs_descs = outs_pair + # The Tensor tests protects against the test when there are no outputs + out_vals, out_spec = pytree.tree_flatten(outs) + out_desc_vals, out_desc_spec = pytree.tree_flatten(outs_descs) + if out_spec != out_desc_spec: + raise AssertionError( + f"output spec mismatch: {fn_wrappers(fn)}, outs={outs}, outs_descs={outs_descs}, " + f"out_spec={out_spec}, out_desc_spec={out_desc_spec}" + ) + if any(isinstance(x, AOTOutput) for x in out_vals): + raise AssertionError( + f"unexpected AOTOutput in out_vals: {fn_wrappers(fn)}, outs={outs}, " + f"outs_descs={outs_descs}, out_vals={out_vals}" + ) + if not all( + isinstance(d, AOTOutput) + for (x, d) in zip(out_vals, out_desc_vals) + if isinstance(x, (torch.Tensor, torch.SymInt)) or type(x) is int + ): + raise AssertionError( + f"expected all descriptors to be AOTOutput: {fn_wrappers(fn)}, outs={outs}, " + f"outs_descs={outs_descs}, out_vals={out_vals}, out_desc_vals={out_desc_vals}" + ) + return outs_pair + + +def fn_wrappers(fn: Callable[..., Any]) -> list[Callable[..., Any]]: + fns = [fn] + f = fn + while hasattr(f, "__wrapped__"): + f = f.__wrapped__ + fns.append(f) + return fns + + +def _is_primal(node: torch.fx.Node) -> bool: + return ( + node.op == "placeholder" + and "tangents" not in str(node.target) + and not _is_bwd_seed_offset(node) + and not _is_fwd_seed_offset(node) + ) + + +def _is_tangent(node: torch.fx.Node) -> bool: + return node.op == "placeholder" and "tangents" in str(node.target) + + +def _is_bwd_seed_offset(node: torch.fx.Node) -> bool: + return node.op == "placeholder" and ( + "bwd_seed" in str(node.target) or "bwd_base_offset" in str(node.target) + ) + + +def _is_fwd_seed_offset(node: torch.fx.Node) -> bool: + return node.op == "placeholder" and ( + "fwd_seed" in str(node.target) or "fwd_base_offset" in str(node.target) + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py b/.venv/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..a160ab80542ba34c5249f462eb554e5dccdce2f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py @@ -0,0 +1,1971 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import itertools +import time +from contextlib import nullcontext +from functools import wraps +from typing import Any, cast, Literal, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar +from unittest.mock import patch + +import torch +import torch._dynamo.logging +import torch.nn as nn +import torch.utils._pytree as pytree +import torch.utils.dlpack +from torch import Tensor +from torch._decomp.decompositions_for_rng import PhiloxStateTracker, rng_decompositions +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo import compiled_autograd +from torch._dynamo.utils import ( + CompileEventLogger, + dynamo_timed, + preserve_rng_state, + set_feature_use, +) +from torch._guards import detect_fake_mode +from torch._inductor.codecache import resolve_pre_grad_pass_timing + +# Runtime annotation consumers still resolve BoxedBool from module globals. +from torch._subclasses import FakeTensorMode +from torch._subclasses.fake_tensor import maybe_get_fake_mode +from torch.export._tree_utils import reorder_kwargs +from torch.fx.experimental.proxy_tensor import make_fx + +from . import config +from ._aot_autograd import autograd_cache +from ._aot_autograd.autograd_cache import ( + AOTAutogradCache, + should_use_local_autograd_cache, + should_use_remote_autograd_cache, +) +from ._aot_autograd.collect_metadata_analysis import ( + run_functionalized_fw_and_collect_metadata, +) +from ._aot_autograd.descriptors import ( + AOTInput, + BufferAOTInput, + DifferentiableAOTInput, + ParamAOTInput, + PlainAOTInput, +) +from ._aot_autograd.frontend_utils import ( + _detect_attribute_assignment, + _try_get_metadata_from_dynamo, + construct_fake_mode, + process_inputs, +) +from ._aot_autograd.functional_utils import ( # noqa: F401 + _check_if_mutation_can_be_in_graph, + are_all_mutations_hidden_from_autograd, + are_all_mutations_under_no_grad_or_inference_mode, + assert_functional_graph, + from_fun, + gen_alias_from_base, + has_data_mutation, + has_metadata_mutation, + is_fun, + sync_functional_tensor, + to_fun, +) +from ._aot_autograd.graph_capture_wrappers import ( # noqa: F401 + aot_dispatch_subclass, + create_functional_call, + create_functionalized_fn, + create_functionalized_rng_ops_wrapper, + create_joint, + fn_input_mutations_to_outputs, + fn_prepped_for_autograd, +) +from ._aot_autograd.graph_compile import ( + aot_stage1_graph_capture, + aot_stage2_compile, + aot_stage2_export, +) +from ._aot_autograd.input_output_analysis import ( # noqa: F401 + compute_overlapping_inputs, + create_graph_signature, + create_synthetic_base_metadata, + remove_dupe_metadata, +) +from ._aot_autograd.logging_utils import ( # noqa: F401 + callback_set, + describe_input, + format_guard_bug_msg, + get_aot_compilation_context, + get_aot_graph_name, + get_graph_being_compiled, + graph_being_compiled, + model_name, + nth_graph, + set_model_name, + setup_stacktrace_preservation_hooks, + track_graph_compiling, +) +from ._aot_autograd.runtime_wrappers import ( # noqa: F401 + AOTDedupeWrapper, + AOTSyntheticBaseWrapper, + SerializableCompiledFunction, +) +from ._aot_autograd.schemas import ( # noqa: F401 + ActInputPath, + AOTConfig, + AOTDispatchCompiler, + AOTGraphCapture, + AOTState, + BackwardSignature, + FakifiedFlatArgs, + FQN, + GraphInputName, + GraphOutputName, + GraphSignature, + InputAliasInfo, + JointWithDescriptors, + MutationType, + OpaqueMeta, + OutputAliasInfo, + OutputType, + SerializableAOTDispatchCompiler, + SubclassCreationMeta, + SubclassMeta, + TensorAlias, + ViewAndMutationMeta, +) +from ._aot_autograd.subclass_utils import ( # noqa: F401 + requires_subclass_dispatch, + unwrap_tensor_subclasses, + unwrap_tensor_subclasses_with_indices_to_original, + wrap_tensor_subclasses, + wrap_tensor_subclasses_maybe_joint, +) +from ._aot_autograd.to_standalone_python import ( # noqa: F401 + compile_to_python, + load_from_python, +) +from ._aot_autograd.utils import ( # noqa: F401 + _get_autocast_states, + call_func_at_runtime_with_args, + create_tree_flattened_fn, + KNOWN_TYPES, + make_boxed_compiler, + make_boxed_func, + maybe_to_fresh_input, + normalize_as_list, + partial_flatten_asdict, + PytreeThunk, + root_module_when_exporting_non_strict, + simple_wraps, + strict_zip, +) +from .partitioners import default_partition + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._inductor.compile_fx import CompilerConfigExtra + from torch._inductor.output_code import OutputCode + from torch._inductor.utils import InputType + from torch._ops import OpOverload + from torch.fx.experimental.symbolic_shapes import ShapeEnv + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +zip = strict_zip + +# This global counter increments every time we compile a graph with +# AOTAutograd. You can use this to correlate runtime error messages +# with compile time (e.g., if you get an error at runtime saying +# compiled graph 3 failed, you can set a breakpoint at compile time +# for this graph number to investigate further at compile time.) +# +# NB: this is different from get_aot_compilation_context, which tracks +# each underlying graph that is compiled. In contrast, AOT_COUNTER +# corresponds to top-level invocations of aot_module/aot_function; +# one counter is allocated per entire compiled block (but this block +# may involve compiling multiple subgraphs; e.g., for forwards/backwards) +AOT_COUNTER = itertools.count() + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# AOT Autograd contains a pretty non-trivial amount of logic to handle edge cases around aliasing and mutation +# that are external to the graph (they show up as side effects in some way when you run the graph). +# +# Take a look at `test_aotdispatch.py TestAOTAutograd.test_input_mutation*` tests for some examples functions +# and what they're compiled graphs looks like. +# Below is a very long comment detailing several edge cases, and showing how AOT Autograd handles them. +# +# Note [AOT Autograd: input data mutations] +# +# If we compile a function that mutates inputs, then those input mutations are real side effects +# that a user expects to see after running the compiled graph. +# However, the graph that we want to send to a backend needs to be *entirely* functional. +# The way we reconcile this difference is that we remove the mutations completely from the graph that we compile +# but we update the graph to return (updated_inputs, user_outputs). +# In the epilogue that runs after the compiled graph is executed, we copy the updated inputs back to the originals. +# +# Example: original user code: +# def f(x): +# x.mul_(2) +# out = x.mul(3) +# return out +# +# After AOT Autograd compiles, we end up with a: +# (a) compiled graph +# (b) autograd.Function.forward() method, that executes the compiled graph +# (c) wrapper function, that calls the autograd.Function.forward() and performs the epilogue +# +# The output of (a, b, c) are all written below. +# +# def compiled_forward_graph(x): +# x_updated = x.mul(2) +# out = x_updated.mul(3) +# return x_updated, out +# +# # x_updated gets a gradient in the compiled backward +# def compiled_backward_graph(grad_x_updated, grad_out): +# grad_x = ... +# return grad_x +# +# def autograd.Function.forward(x): +# x_updated, out = compiled_forward_graph(x) +# return x_updated, out +# +# def compiled_wrapper(x): +# x_updated, out = autograd.Function.apply(x) +# x.copy_(x_updated) +# return out +# +# Another important thing to note is that updated inputs (due to data mutations) *do* participate +# in the compiled backward graph! Since the compiled forward graph gets N extra outputs +# (due to updated inputs showing up as graph outputs), +# The compiled backward gets an additional N inputs. +# That way, during the x.copy_(x_updated) bit in the epilogue, gradients will flow from the updated input +# back to the original input. + + +# Note [AOT Autograd: input metadata mutations] +# +# For the same reason as input mutations, we also don't put input metadata mutations in the graph. +# Instead, we return the updated version of the input (a view), and mutate the input's metadata outside of the graph +# +# Example: original user code: +# def f(x): +# x.t_() +# out = x.mul(3) +# return out +# +# AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function): +# def compiled_forward_graph(x): +# x_updated = x.t() +# out = x_updated.mul(3) +# return x_updated, out +# +# # x_updated does *not* get a gradient in the compiled backward +# def compiled_backward_graph(grad_out): +# grad_x = ... +# return grad_x +# +# def autograd.Function.forward(x): +# x_updated, out = compiled_forward_graph(x) +# return x_updated, out +# +# def compiled_wrapper(x): +# x_updated, out = autograd.Function.apply(x) +# x.as_strided_(x_updated) +# return out + + +# Note [AOT Autograd: outputs aliasing inputs or intermediates!] +# +# AOT Autograd needs special handling for outputs that alias graph inputs or intermediates! +# Why? +# (1) autograd.Function.forward() has a limitation, where views that returned in the forward cannot later be mutated. +# (2) views don't need to be compiled in the graph anyway - it's cheap to generate them outside of the compiled graph, +# in an epilogue. +# For outputs that alias inputs, we do the following: +# (a) *still* return the aliased output as a graph output +# (b) In the AOT Autograd wrapper/epilogue, we don't return that aliased output. Instead, we use it to regenerate the output. +# +# For outputs that alias *intermediates*, we do the following: +# (a) Return the output in the compiled forward, **and** return it's ._base (a graph intermediates) as an output in the forward +# (b) Use (output, graph_intermediate) to regenerate the alias, and return that to the user (instead of the compiled fw output). +# You might wonder why we return the aliased output directly in the graph (and making the graph compute it), +# only to not return it and instead generate a fresh alias off of the intermediate, +# instead of (say) just storing metadata about the size/stride of the output somewhere to generate the alias. There are two reasons: +# (1) Getting the actual alias tensor allows us to use view-replay to generate the alias, instead of an as_strided() call +# (2) Inductor (and other backends) are free to change the memory format of graph outputs, if it results in better performance. +# This can result in problems if a user later tries to .view() that output expecting it to have one set of strides, +# when it has a different set of strides. +# By including the view op directly in the graph, inductor takes that into account when deciding what memory format +# the graph intermediate should be. +# +# Another important thing to note is how our traced backward() graph handles aliases. +# (this applies to outputs aliasing inputs, outputs aliasing intermediates, +# *and* updated inputs returned in the compiled forward due to metadata-only mutations). +# Any outputs that alias (either inputs or intermediates) do NOT participate in the compiled backward graph +# It would be wasteful to include them in the compiled backward(), because we regenerate them eagerly +# at the end of the forward. +# +# Example: original user code: +# def f(x): +# out1 = x.t() +# intermediate = x.mul(2) +# out2 = intermediate.view(-1) +# return out1, out2 +# +# AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function): +# def compiled_forward_graph(x): +# out1 = x.t() +# intermediate = x.mul(2) +# out2 = intermediate.view(-1) +# # the compiled graph also returns the intermediate +# return out1, out2, intermediate +# +# # intermediate gets a gradient in the compiled backward. +# # both output aliases (out1 and out2) do not. +# def compiled_backward_graph(grad_intermediate): +# grad_x = ... +# return grad_x +# +# def autograd.Function.forward(x): +# out1, out2, intermediate = compiled_forward_graph(x) +# return out1, out2, intermediate +# +# def compiled_wrapper(x): +# out1, out2, intermediate = autograd.Function.apply(x) +# # regenerate out1 from the input +# out1_regenerated = out1._view_func(x) +# # regenerate out1 from the intermediate +# out2_regenerated = out2._view_func(intermediate) +# return out1_regenerated, out2_regenerated + + +# Note [AOT Autograd: mutations to inputs that alias other inputs] +# +# Another edge case that is (only partially) handled today is when an input is mutated, but itself aliases another input. +# AOT Autograd needs to **ensure** that functionalization knows that the two inputs are aliased to each other. +# That way, when the aliased input is accessed later in the graph, functionalization knows to "update" the alias +# given the mutation that occurred. +# +# This is handled by updating the calling convention: we create a "synthetic base" that becomes a new input +# in the compiled function, and we regenerate the original (aliased) inputs directly off of the base +# inside of the compiled function. +# +# This logic is fully encapsulated in aot_wrapper_synthetic_base() +# +# Example: original user code: +# def f(x, x_view): +# x.mul_(2) +# out = x * x_view +# return out +# f(x, x.view(-1)) +# +# AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function): +# def compiled_forward_graph(base) +# x = generate_x(base) +# x_view = generate_x_view(base) +# x_updated = x.mul(2) +# x_view_updated = x_updated.view(-1) +# out = x_updated * x_view_updated +# return x_updated, out +# +# # The calling convention change from (aliases) -> (base) happens +# # *outside* of the autograd.Function.forward(). +# # That means the forward() only has 1 input (base), +# # and the backward() only has 1 output (grad_base) +# def compiled_backward_graph(grad_out): +# grad_base = ... +# return grad_base +# +# def autograd.Function.forward(base): +# x_updated, out = compiled_forward_graph(base) +# return x_updated, out +# +# # The compiled wrapper is where we create synthetic bases. +# # The info on which inputs are mutated is also tracked *before* synthetic base creation. +# def compiled_wrapper(x, x_view): +# base = merge_view_inputs(x, x_view) +# x_updated, out = autograd.Function.apply(base) +# # x and x_view are aliased in eager mode, so this mutation to x will automatically affect x_view. +# x.copy_(x_updated) +# return out + + +# Note [AOT Autograd: Views to avoid tangents aliasing inputs] +# +# We view every forward output when creating out tangent tensors to handle the problematic +# case in which a subclass does extra aliasing between graph outputs/inputs in a way that +# is not visible above the subclass. +# +# Ordinarily, when constructing the joint function that we want to trace in AOTAutograd, +# we're guaranteed that the tangent tensors that we pass +# into the joint are distinct tensors from the primals. This is because when +# decide which forward outputs to create tangents for, we only create tangents +# for forward outputs that are not aliases of inputs (See Note +# [AOT Autograd: outputs aliasing inputs or intermediates!]). +# +# However, when wrapper tensor subclasses enter the picture, it is possible +# to have an output of the forward that is a subclass that is not an +# input / alias of an input, but one of its inner tensors is an alias! +# NestedTensor is an example: Performing an out-of-place pointwise op on a +# NestedTensor constructs a fresh NestedTensor that holds onto the input's +# offsets tensor directly. +# +# Having tangent tensors that are the same as the (primal) forward inputs, +# can cause problems during tracing as make_fx() will specialize on our +# duplicate inputs: If we passed in the same tensor for primals_1 and +# tangents_1 during tracing, make_fx() will happily sub out all usages of +# tangents_1 with primals_1 in the graph, which is not what we want. +# +# To work around this, we view every forward output when creating out tangent +# tensors so that tangents can never be the same as forward inputs even if +# forward inputs alias forward outputs. + +# Note [Side-Effectful Tokens in AOTAutograd] +# +# We allow some side-effectful operators in +# the post-AOTAutograd (functional) graph, such as prints and torchbind operations. +# To ensure that these side-effects are compatible to future graph passes that +# assume that the graph is functional, we will thread "effect tokens" to show +# data dependence between these side-effectful operators. Practically speaking, +# effect tokens are just dummy values (torch.tensor([])). The graph would look +# like the following: +# +# def gm(self, token0, reader): +# token1, frame = with_token(ordered_effect_op, (reader,), token0) +# frame = frame * 2 +# token2, frame2 = with_token(ordered_effect_op, (reader,), token1) +# frame2 = frame2 * 2 +# return token2, frame, frame2 +# +# We will pass the token as an input to the graph, thread it through +# side-effectful operators using the `with_effects` high order operator, and then +# return the updated token as an output. +# So the signature of the graph input would look something like +# (*tokens, *params_buffers, *user_inputs), and the signature of the graph +# output would look something like (*tokens, *outputs). +# +# However, Inductor does not want the concept of tokens in the final generated +# code's input and output. Since changing the graph signature inside of inductor +# is difficult, after generating the forward graph, we will run a pass to +# remove the tokens from the input and generate the following graph for Inductor, where +# the tokens are created and sunk within the graph, rather than as inputs and +# outputs: +# +# def gm(self, reader): +# token0 = torch.ops.prims._make_token() +# token1, frame = with_token(ordered_effect_op, (reader,), token0) +# frame = frame * 2 +# token2, frame2 = with_token(ordered_effect_op, (reader,), token1) +# frame2 = frame2 * 2 +# sink_token = torch.ops.prims._sink_tokens([token2]) +# return frame, frame2 + +# +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +aot_autograd_decompositions: dict[OpOverload, Callable[..., Any]] = {} + + +def create_aot_state( + stack: contextlib.ExitStack, + flat_fn: Callable[_P, _R], + fake_flat_args: FakifiedFlatArgs, + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + fake_mode: FakeTensorMode, + shape_env: ShapeEnv | None, +) -> AOTState: + """ + Traces the forward and backward graphs of the attr:`flat_fn` to generate a + joint graph. The joint graph is an Fx graph with Aten ops. Please refer to + the tracing mechanism to understand the graph capturing details. + + The joint graph is then passed through attr:`partition_fn` to isolate the + forward and backward portions, which are then respectively compiled via the + provided attr:`fw_compiler` and attr:`bw_compiler`. + + The resulting compiled forward and backward graphs are then wrapped up in a + ``torch.autograd.Function`` object. + + The calling convention here is that the first aot_config.num_params_buffers + inputs in flat_args are parameters and buffers, and the rest are inputs. + + We use this to assume that parameters/buffer's shapes don't change. + """ + + # Old name for now to avoid messing with stats. Also, note this is pushed + # on the stack, so it extends BEYOND this function + stack.enter_context( + dynamo_timed("create_aot_dispatcher_function", log_pt2_compile_event=True) + ) + + # This is the main entry point. + # TODO: Chillee argues that dynamo itself should pass in fake tensors to + # the list of arguments when compiling; at the moment we do not do this + + decompositions = aot_config.decompositions or {} + decompositions = { + **aot_autograd_decompositions, + **decompositions, + } + + if config.functionalize_rng_ops: + # Update the decompositions with functionalized random decompositions + decompositions = { + **rng_decompositions, + **decompositions, + } + + aot_config = dataclasses.replace( + aot_config, + decompositions=cast("dict[OpOverload, Callable[..., Any]]", decompositions), + ) + + # Check flat_args to see if they're already fake. If so, use that fake + # mode instead. + + python_dispatcher_mode = ( + enable_python_dispatcher() if shape_env is not None else nullcontext() + ) + + # See NOTE: [Deferring tensor pack/unpack hooks until runtime] + # If any saved tensor hooks are active, we **don't** want to trace them. + # Instead, we'll let them run at runtime, around the custom autograd.Function + # that we generate in torch.compile. + stack.enter_context(torch.autograd.set_multithreading_enabled(False)) + stack.enter_context(preserve_rng_state()) + stack.enter_context(fake_mode) + stack.enter_context(python_dispatcher_mode) + stack.enter_context(PhiloxStateTracker()) + stack.enter_context( + torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing() + ) + + from torch._library.fake_class_registry import FakeScriptObject, maybe_to_fake_obj + from torch._library.opaque_object import is_custom_class + + # Tracing may mutate the states the fake script object, + # so we need to duplicate the fake script objects so that subsequent tracing + # won't be affected. + def _dup_fake_script_obj(fake_flat_args: FakifiedFlatArgs) -> list[Any]: + return [ + maybe_to_fake_obj(detect_fake_mode(fake_flat_args), arg.real_obj) + if isinstance(arg, FakeScriptObject) or is_custom_class(type(arg)) + else arg + for arg in fake_flat_args + ] + + needs_autograd = any( + x.requires_grad for x in fake_flat_args if isinstance(x, Tensor) + ) + + with enable_python_dispatcher(): + # Patch set_rng_state as set_rng_state with fake tensors is + # nonsensical. This does not affect the collection of metadata. + with patch("torch.cuda.set_rng_state", lambda *args: None): + mod = root_module_when_exporting_non_strict(flat_fn) + if mod is not None: + ctx = _detect_attribute_assignment(mod) + else: + ctx = nullcontext() + + if torch._functorch.config.fake_tensor_propagate_real_tensors: + # Running dynamo_timed causes fake tensor issues when + # propagate real tensor is switched on. + dynamo_timed_ctx = nullcontext() + else: + dynamo_timed_ctx = dynamo_timed( + "aot_collect_metadata", log_pt2_compile_event=True + ) + + with ( + dynamo_timed_ctx, + ctx, + torch._dynamo.eval_frame._use_eager_on_nested_compile(), + ): + fw_metadata = run_functionalized_fw_and_collect_metadata( + flat_fn, + flat_args_descs=flat_args_descs, + static_input_indices=aot_config.static_input_indices, + keep_input_mutations=aot_config.keep_inference_input_mutations, + pre_dispatch=aot_config.pre_dispatch, + )(*_dup_fake_script_obj(fake_flat_args)) + + req_subclass_dispatch = requires_subclass_dispatch( + fake_flat_args, fw_metadata + ) + CompileEventLogger.try_add_pt2_compile( + "backend_compile", requires_subclass_dispatch=req_subclass_dispatch + ) + + output_and_mutation_safe = not any( + x.requires_grad + # view-type operations preserve requires_grad even in no_grad. + # Do not count aliases of inputs with requires_grad as reason to make a training graph, + # as AOTAutograd will perform view-replay to regenerate the view outputs at runtime, + # setting their grad_fn properly. + and not ( + x.output_type in (OutputType.alias_of_input, OutputType.is_input) + and x.base_idx is not None + and fw_metadata.input_info[x.base_idx].requires_grad + ) + for x in fw_metadata.output_info + ) and not any( + x.requires_grad + and x.mutates_data + and not x.mutations_under_no_grad_or_inference_mode + and not x.mutations_hidden_from_autograd + for x in fw_metadata.input_info + ) + + if needs_autograd and output_and_mutation_safe: + # We realized that none of the outputs require grad, + # and none of the inputs that require grad are mutated. + # so we actually have an inference graph. + needs_autograd = False + + if fw_metadata.num_intermediate_bases > 0: + if req_subclass_dispatch: + raise AssertionError(f"""\ +torch.compile is currently being used with tensor subclass inputs. +We are attempting to a compile a graph with two graph outputs +that alias one another, specifically output indices: + + {[i for i, x in enumerate(fw_metadata.output_info) if x.output_type == OutputType.alias_of_intermediate]} + +ANY output aliasing (even for regular tensors) is currently unsupported if +there are any subclass outputs. If you run into this, please file a github +issue""") + + if aot_config.is_export: + # aot_export: ban input metadata mutations for now to keep shared code paths simpler. + # Keeping .resize_() in the graph will require some work + # Allowing it but keeping the graph functional will require some calling convention changes. + if len([x for x in fw_metadata.input_info if x.mutates_metadata]) != 0: + raise RuntimeError( + f"""\ +Found an input that received a metadata mutation, through e.g. a call to `.resize_()` or `.transpose_()`. +This is currently banned in the aot_export workflow. If you need this functionality, please file a github issue. + +fw_metadata={str(fw_metadata)}""" + ) + # In export, banning data mutations on inputs that require grad for now. + # This should be rare, and is tricky to get right. When we trace the backward, + # we currently trace with autograd.grad instead of .backward(), which makes it difficult + # to ensure that we run autograd all the way through the input **before** it saw the mutation. + if ( + len( + [ + x + for x in fw_metadata.input_info + if x.requires_grad and x.mutates_data + ] + ) + != 0 + and aot_config.export_trace_joint + ): + raise RuntimeError( + f"""\ +Found a graph input that requires gradients, and received a mutation. +This is currently banned in the aot_export workflow. If you need this functionality, please file a github issue. + +fw_metadata={str(fw_metadata)}""" + ) + if req_subclass_dispatch: + raise RuntimeError( + """\ +aot_export is not currently supported with traceable tensor subclass. +If you need this feature, please comment on """ + ) + + # Need to decide on a strategy for functionalized RNG: toggling via global config seems bad, + # and turning it on will require a non-trivial calling convention change for any export runtime. + if config.functionalize_rng_ops: + raise RuntimeError( + """\ +Functionalized RNG is not currently supported in the aot_export workflow. Please file a github issue, +or otherwise set torch._functorch.config.functionalize_rng_ops = False.""" + ) + + return AOTState( + needs_autograd=needs_autograd, + flat_args=_dup_fake_script_obj(fake_flat_args), + flat_args_descs=flat_args_descs, + fw_metadata=fw_metadata, + # Packaging this just for later use + aot_config=aot_config, + stack=stack, + fake_mode=fake_mode, + ) + + +def aot_function( + fn: Callable[_P, _R], + fw_compiler: AOTDispatchCompiler, + bw_compiler: AOTDispatchCompiler | None = None, + partition_fn: Callable[..., Any] = default_partition, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + num_params_buffers: int = 0, + keep_inference_input_mutations: bool = False, + inference_compiler: AOTDispatchCompiler | None = None, + *, + # Whether or not to trace with dynamic shapes + dynamic: bool = False, + enable_log: bool = True, + disable_functionalization: bool = False, + _disable_torch_fn_metadata_mode: bool = False, +) -> Callable[_P, Any]: + """ + Traces the forward and backward graph of :attr:`fn` using torch dispatch + mechanism, and then compiles the generated forward and backward graphs + through :attr:`fw_compiler` and :attr:`bw_compiler`. + + :func:`aot_function` traces the forward and backward graph ahead of time, + and generates a joint forward and backward graph. :attr:`partition_fn` is + then used to separate out forward and backward graphs. The partitioner + function can be used to perform optimizations such as recomputation. One can + set `decompositions` dictionary to decompose the operators into a sequence + of core or simpler operators supported by the backend compilers. + + .. warning:: + This API is experimental and likely to change. + + Args: + fn (Callable): A Python function that takes one or more arguments. Must + return one or more Tensors. + fw_compiler (Callable): A Python function that accepts an Fx graph with + Aten ops and input args, and returns a Callable that semantically is + equivalent to the input Fx graph. + bw_compiler (Optional[Callable]): A Python function that accepts an + Fx graph with Aten ops and input args, and returns a Callable that + semantically is equivalent to the input Fx graph. Default: None + (when None, it defaults to the :attr:`fw_compiler`) + partition_fn (Callable): A Python function that takes a joint forward + and backward graph, and partitions it into separate forward and + backward graphs. + decompositions (Dict): A dictionary to define the decomposition of + larger Aten ops into simpler or core Aten ops. + inference_compiler (Optional[Callable]): A Python function that accepts an + Fx graph with Aten ops and input args, and returns a Callable that + semantically is equivalent to the input Fx graph. inference_compiler is invoked + if no autograd is needed. Default: None + (when None, it defaults to the :attr:`fw_compiler`) + Returns: + Returns a ``Callable`` that retains the eager behavior of the original + :attr:`fn`, but with forward and backward graph compiled via + :attr:`fw_compile` and :attr:`bw_compile`. + + A simple example usage of :func:`aot_function` is as follows. This example + will print the forward and backward graphs of the function ``fn`` + + >>> fn = lambda x: x.sin().cos() + >>> def print_compile_fn(fx_module, args): + >>> print(fx_module) + >>> return fx_module + >>> aot_fn = aot_function(fn, print_compile_fn) + >>> x = torch.randn(4, 5, requires_grad=True) + >>> aot_fn(x) + """ + + aot_config = AOTConfig( + fw_compiler=None, + bw_compiler=None, + inference_compiler=None, + partition_fn=None, + decompositions=decompositions, + num_params_buffers=num_params_buffers, + aot_id=next(AOT_COUNTER), + keep_inference_input_mutations=keep_inference_input_mutations, + dynamic_shapes=dynamic, + aot_autograd_arg_pos_to_source=None, + is_export=False, + no_tangents=False, + enable_log=enable_log, + disable_functionalization=disable_functionalization, + _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode, + ) + cached_res = None + + @wraps(fn) + def returned_function(*args: _P.args, **kwargs: _P.kwargs) -> Any: + nonlocal cached_res + # Now flatten the tensor args + flat_args = pytree.arg_tree_leaves(*args, **kwargs) + + # Compile the function and save it in the cache + if cached_res is None: + flat_fn, out_spec = create_tree_flattened_fn(fn, args, kwargs) + (fake_mode, shape_env) = construct_fake_mode(flat_args, aot_config) + fake_flat_args: FakifiedFlatArgs + fake_flat_args, act_input_paths = process_inputs( + flat_args, aot_config, fake_mode, shape_env + ) + # TODO: We actually could use the pytree path to make better descs. + # Also, the descs here are bad if you do aot_module. + fake_flat_args_descs: list[AOTInput] = [ + PlainAOTInput(i) for i in range(len(fake_flat_args)) + ] + with contextlib.ExitStack() as stack: + aot_state = create_aot_state( + stack, + flat_fn, + fake_flat_args, + fake_flat_args_descs, + aot_config, + fake_mode, + shape_env, + ) + aot_state.fw_metadata.act_input_paths = act_input_paths + aot_graph_capture = aot_stage1_graph_capture(aot_state, flat_fn) + compiled_fn, _ = aot_stage2_compile( + aot_state, + aot_graph_capture, + partition_fn, + fw_compiler, + bw_compiler, + inference_compiler, + ) + cached_res = (compiled_fn, out_spec) + + cached_fn, out_spec = cached_res + out = cached_fn(flat_args) + return out_spec.unflatten(out) + + return returned_function + + +def aot_module(mod: nn.Module, *args: Any, **kwargs: Any) -> nn.Module: + """ + Traces the forward and backward graph of :attr:`mod` using torch dispatch + tracing mechanism. It is wrapper function, that underneath uses + :func:`aot_function` to perform tracing and compilation. + + :func:`aot_module` lifts the parameters and buffers of ``nn.Module`` as inputs + to a new callable which is then compiled through :func:`aot_function`. + + .. warning:: + This API is experimental and likely to change. + + Args: + mod (Callable): A ``nn.Module`` module. + args : args to be passed to :func:`aot_function` + kwargs : kwargs to be passed to :func:`aot_function` + + Returns: + Returns a ``nn.Module`` that retains the eager behavior of the original + :attr:`mod`, but with forward and backward graph compiled. + + """ + # See Note: [Fake Modules and AOTAutograd] + torch._dynamo.utils.assert_no_fake_params_or_buffers(mod) + + def functional_call( + named_params: dict[str, torch.nn.Parameter], + named_buffers: dict[str, torch.Tensor], + *args: Any, + **kwargs: Any, + ) -> Any: + params_and_buffers = {**named_params, **named_buffers} + return torch.func.functional_call(mod, params_and_buffers, args, kwargs) + + named_params = dict(mod.named_parameters(remove_duplicate=False)) + named_buffers = dict(mod.named_buffers(remove_duplicate=False)) + num_params_buffers = len(named_params) + len(named_buffers) + compiled_f = aot_function( + functional_call, + *args, + # pyrefly: ignore[bad-keyword-argument] + num_params_buffers=num_params_buffers, + **kwargs, + ) + + class AOTModule(nn.Module): + def __init__(self) -> None: + super().__init__() + self.orig_module = mod + + def forward(self, *args: Any, **kwargs: Any) -> Any: + return compiled_f( + named_params, + named_buffers, + *args, + **kwargs, + ) + + return AOTModule() + + +def autograd_cache_key( + graph, + example_inputs, + ignore_shape_env: bool, + decompositions, + compiler_config_extra: CompilerConfigExtra, + keep_inference_input_mutations: bool = False, + disable_functionalization: bool = False, +): + ( + _params_buffers_flat, + _params_spec, + _buffers_spec, + full_args, + _full_args_descs, + aot_config, + ) = prepare_aot_config( + graph, + example_inputs, + decompositions, + keep_inference_input_mutations, + ignore_shape_env, + force_non_lazy_backward_lowering=config.force_non_lazy_backward_lowering, + disable_functionalization=disable_functionalization, + ) + + fake_mode, shape_env = construct_fake_mode(full_args, aot_config) + fake_flat_args, act_input_paths = process_inputs( + full_args, aot_config, fake_mode, shape_env, ignore_shape_env + ) + + return autograd_cache.autograd_cache_key( + graph, fake_flat_args, aot_config, compiler_config_extra, act_input_paths + ) + + +def prepare_aot_config( + mod: nn.Module, + args: Iterable[Any], + decompositions: dict[OpOverload, Callable[..., Any]] | None, + keep_inference_input_mutations: bool, + ignore_shape_env: bool, + *, + force_non_lazy_backward_lowering: bool = False, + disable_functionalization: bool = False, + _disable_torch_fn_metadata_mode: bool = False, +) -> tuple[ + list[torch.nn.Parameter | Tensor], + list[str], + list[str], + list[Any], + list[Any], + AOTConfig, +]: + # TODO: There's something a bit suspicious here; typically simplified + # module shouldn't actually have any parameters... + params = dict(mod.named_parameters(remove_duplicate=False)) + buffers = dict(dict(mod.named_buffers(remove_duplicate=False))) + + params_flat, params_spec = list(params.values()), list(params.keys()) + params_len = len(params_flat) + + buffers_flat, buffers_spec = list(buffers.values()), list(buffers.keys()) + buffers_len = len(buffers_flat) + + params_buffers = {**params, **buffers} + params_buffers_flat = params_flat + buffers_flat + + full_args = [*params_flat, *buffers_flat, *args] + + # OK, set up the descs + + full_args_descs: list[DifferentiableAOTInput] = [] + full_args_descs.extend(ParamAOTInput(fqn) for fqn in params_spec) + full_args_descs.extend(BufferAOTInput(fqn) for fqn in buffers_spec) + + # TODO: These tracing_context fields should become unnecessary once we + # always maintain sources on all arguments + if tracing_context := torch._guards.TracingContext.try_get(): + # NB: TracingContext misnames this, the "params" here also contains + # buffers + tracing_context.params_flat = params_buffers_flat + ( + tracing_context.params_flat_unwrap_subclasses, + tracing_context.params_unwrapped_to_flat_index, + ) = unwrap_tensor_subclasses_with_indices_to_original(params_buffers_flat) + + # TODO: Might be nice to hold on to the Dynamo source here in full_args_descs! + ( + aot_autograd_arg_pos_to_source, + static_input_indices, + ) = _try_get_metadata_from_dynamo( + mod, params_buffers.keys(), len(full_args), full_args_descs + ) + + dynamic_shapes = False + for x in full_args: + fake_mode = maybe_get_fake_mode(x) + if fake_mode is not None: + dynamic_shapes = fake_mode.shape_env is not None + break + + aot_config = AOTConfig( + fw_compiler=None, + bw_compiler=None, + inference_compiler=None, + partition_fn=None, + decompositions=decompositions, + num_params_buffers=params_len + buffers_len, + aot_id=next(AOT_COUNTER), + keep_inference_input_mutations=keep_inference_input_mutations, + dynamic_shapes=dynamic_shapes, + # pyrefly: ignore[bad-argument-type] + aot_autograd_arg_pos_to_source=aot_autograd_arg_pos_to_source, + static_input_indices=static_input_indices, + is_export=False, + no_tangents=False, + cache_info=None, + ignore_shape_env=ignore_shape_env, + precompile_backend_id=getattr(mod, "_backend_id", None), + force_non_lazy_backward_lowering=force_non_lazy_backward_lowering, + disable_functionalization=disable_functionalization, + _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode, + ) + + return ( + params_buffers_flat, + params_spec, + buffers_spec, + full_args, + full_args_descs, + aot_config, + ) + + +def prepare_aot_module_simplified( + mod: nn.Module, + args: Iterable[Any], + kwargs: dict[str, Any] | None, + decompositions: dict[OpOverload, Callable[..., Any]] | None, + keep_inference_input_mutations: bool, + ignore_shape_env: bool, + flatten: bool, + *, + force_non_lazy_backward_lowering: bool = False, + disable_functionalization: bool = False, + _record_nn_module_stack: bool = False, + _disable_torch_fn_metadata_mode: bool = False, +) -> tuple[ + Any, + list[torch.nn.Parameter | Tensor], + list[str], + list[str], + FakifiedFlatArgs, + list[Any], + AOTConfig, + FakeTensorMode, + ShapeEnv | None, + pytree.TreeSpec | None, + PytreeThunk | None, + list[ActInputPath], +]: + if not flatten: + if kwargs is not None: + raise AssertionError("kwargs must be None when flatten=False") + elif kwargs is None: + kwargs = {} + + ( + params_buffers_flat, + params_spec, + buffers_spec, + full_args, + full_args_descs, + aot_config, + ) = prepare_aot_config( + mod, + args, + decompositions, + keep_inference_input_mutations, + ignore_shape_env, + force_non_lazy_backward_lowering=force_non_lazy_backward_lowering, + disable_functionalization=disable_functionalization, + _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode, + ) + + params_buffers_spec = params_spec + buffers_spec + + # NB: This doesn't change the in/out convention, except adding the + # parameters as explicit arguments + functional_call = create_functional_call( + mod, + params_buffers_spec, + aot_config.num_params_buffers, + strict_out_tuple=not flatten, + # We need this for export to run ModuleStackTracer + # instead of PythonKeyTracer + store_orig_mod=_record_nn_module_stack, + ) + + in_spec, out_spec = None, None + if flatten: + functional_call, out_spec = create_tree_flattened_fn( + functional_call, full_args, kwargs + ) + full_args, in_spec = pytree.tree_flatten((full_args, kwargs)) + + # TODO: it would be better to put pytree information in here + full_args_descs.extend( + PlainAOTInput(i) for i in range(len(full_args) - len(full_args_descs)) + ) + + fake_mode, shape_env = construct_fake_mode(full_args, aot_config) + # NB: full_args_descs not needed here, fake_flat_args is 1:1 with full_args + fake_flat_args, act_input_paths = process_inputs( + full_args, aot_config, fake_mode, shape_env, ignore_shape_env + ) + + return ( + functional_call, + params_buffers_flat, + params_spec, + buffers_spec, + fake_flat_args, + full_args_descs, + aot_config, + fake_mode, + shape_env, + in_spec, + out_spec, + act_input_paths, + ) + + +def aot_module_simplified( + mod: torch.fx.GraphModule | torch._dynamo.utils.GmWrapper, + args: Sequence[Any], + fw_compiler: AOTDispatchCompiler, + bw_compiler: AOTDispatchCompiler | None = None, + partition_fn: Callable[..., Any] = default_partition, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + keep_inference_input_mutations: bool = False, + inference_compiler: AOTDispatchCompiler | None = None, + # TODO: This doesn't seem to be used in any nontrivial way, check if it's + # actually needed + compiler_config_extra: CompilerConfigExtra | None = None, + ignore_shape_env: bool = False, + disable_functionalization: bool = False, + # Optional callback to run passes on the module at the start of AOT autograd. + pre_grad_passes: Callable[ + [torch.fx.GraphModule, Sequence[InputType]], torch.fx.GraphModule + ] + | None = None, + compile_region_name: str | None = None, +) -> Callable[..., Any]: + """ + This is the simplified or low overhead version of aot_module. For frontends + like TorchDynamo, the input functions/modules to AOT are static and have + unpacked inputs/outputs. This gives us an opportunity to remove the + (1) pytree overhead to parse inputs/outputs, + (2) AOT Autograd cache, + (3) Reading of params/buffers in every forward call + + :func:`aot_module_simplified` removes these overheads. + """ + + pre_grad_pass_timing: Literal["early", "late"] = resolve_pre_grad_pass_timing() + + if ( + pre_grad_pass_timing == "early" + and pre_grad_passes + and isinstance(mod, torch.fx.GraphModule) + ): + mod = pre_grad_passes(mod, args) + + with contextlib.ExitStack() as stack: + ( + functional_call, + params_buffers_flat, + _params_spec, + _buffers_spec, + fake_flat_args, + full_args_descs, + aot_config, + fake_mode, + shape_env, + _in_spec, + _out_spec, + act_input_paths, + ) = prepare_aot_module_simplified( + mod, + args, + None, + decompositions, + keep_inference_input_mutations, + ignore_shape_env, + flatten=False, + force_non_lazy_backward_lowering=config.force_non_lazy_backward_lowering, + disable_functionalization=disable_functionalization, + ) + + compiled_fn = None + + if ( + isinstance(fw_compiler, SerializableAOTDispatchCompiler) + or torch._functorch.config.force_autograd_cache + ): + local = should_use_local_autograd_cache() + remote = should_use_remote_autograd_cache() + if local or remote: + set_feature_use("aot_autograd_remote_cache", remote) + compiled_fn, aot_config = AOTAutogradCache.try_load( + mod, + fake_flat_args, + aot_config, + compiler_config_extra, + local, + remote, + act_input_paths, + compile_region_name=compile_region_name, + ) + + if compiled_fn is None: + if ( + pre_grad_pass_timing == "late" + and pre_grad_passes + and isinstance(mod, torch.fx.GraphModule) + ): + mod = pre_grad_passes(mod, args) + + stack.enter_context(compiled_autograd._disable()) + aot_state = create_aot_state( + stack, + functional_call, + fake_flat_args, + full_args_descs, + aot_config, + fake_mode, + shape_env, + ) + aot_state.fw_metadata.act_input_paths = act_input_paths + aot_graph_capture = aot_stage1_graph_capture(aot_state, functional_call) + compiled_fn, _ = aot_stage2_compile( + aot_state, + aot_graph_capture, + partition_fn, + fw_compiler, + bw_compiler, + inference_compiler, + ) + if compiled_fn is None: + raise AssertionError("compiled_fn must not be None") + if isinstance(mod, torch._dynamo.utils.GmWrapper): + # This function is called by the flatten_graph_inputs wrapper, which boxes + # the inputs so that they can be freed before the end of this scope. + # For overhead reasons, this is not the default wrapper, see comment: + # https://github.com/pytorch/pytorch/pull/122535/files#r1560096481 + @simple_wraps(compiled_fn) + def forward(runtime_args: list[Any]) -> Any: + flat_args = [] + flat_args.extend(params_buffers_flat) + flat_args.extend(runtime_args) + runtime_args.clear() + if compiled_fn is None: + raise AssertionError("compiled_fn must not be None") + return compiled_fn(flat_args) + + else: + # TODO: There is something deeply wrong here; compiled_fn running with + # the boxed calling convention, but aot_module_simplified somehow + # historically returned a function that was not the boxed calling + # convention. This should get fixed... + # NB: GraphModule/nn.Module rely on the non-boxed calling convention here + @simple_wraps(compiled_fn) + def forward(*runtime_args: tuple[Any]) -> Any: + full_args = [] + full_args.extend(params_buffers_flat) + # pyrefly: ignore[bad-argument-type] + full_args.extend(runtime_args) + if compiled_fn is None: + raise AssertionError("compiled_fn must not be None") + return compiled_fn(full_args) + + # Just for convenience + forward.zero_grad = mod.zero_grad # type: ignore[attr-defined] + forward.named_parameters = mod.named_parameters # type: ignore[attr-defined] + forward.named_buffers = mod.named_buffers # type: ignore[attr-defined] + + # Add a serialize function + def grab_serialize_fn(fn: Any) -> Callable[..., Any] | None: + if isinstance(fn, SerializableCompiledFunction): + return fn.serialize_fn + elif hasattr(fn, "__wrapped__"): + return grab_serialize_fn(fn.__wrapped__) + else: + return None + + forward.serialize = grab_serialize_fn(forward) # type: ignore[attr-defined] + return forward + + +def boxed_nop_preserve_node_meta( + gm: torch.fx.GraphModule, example_inputs: Sequence[InputType] +) -> Any: + def run(args: list[Any]) -> OutputCode: + with torch.fx.traceback.preserve_node_meta(): + return torch.fx.Interpreter(gm).boxed_run(args) + + run._boxed_call = True # type: ignore[attr-defined] + return run + + +def aot_export_joint_with_descriptors( + stack: contextlib.ExitStack, + mod: nn.Module, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + keep_inference_input_mutations: bool = False, + ignore_shape_env: bool = False, + disable_functionalization: bool = False, + _record_nn_module_stack: bool = False, + _disable_torch_fn_metadata_mode: bool = False, +) -> JointWithDescriptors: + """ + This API captures the joint graph for an nn.Module. However, unlike + aot_export_joint_simple or aot_export_module(trace_joint=True), the + calling convention of the produced joint graph follows no fixed positional + schema; for example, you cannot rely on the second argument of the traced + joint graph to correspond to the second argument of the module you traced. + However, the inputs and outputs of the traced graph are schematized + with **descriptors**, annotated on meta['desc'] on the placeholder and + return FX nodes, which you can use to determine the meaning of arguments. + + The major benefit of using this export rather than aot_export_joint_simple + is that we have feature parity with all situations that torch.compile + supports (via aot_module_simplified), including handling for more + complicated cases such as multiple differentiable outputs, input mutations + that must be handled outside of the graph, tensor subclasses, etc. + + What can you do with one of these joint graphs with descriptors? The + motivating use case (autoparallel) involves taking the joint graph, doing + optimizations on it, and then turning it back into a callable so it can be + torch.compile'd at a later point in time. This cannot be done as a + traditional torch.compile joint graph pass for two reasons: + + 1. The sharding of parameters must be decided before parameter + initialization / checkpoint load, far before torch.compile would + ordinarily run. + + 2. We need to change the meaning of parameters (e.g., we might replace + a replicated parameter with a sharded version of it, changing its + input size). torch.compile is ordinarily semantics preserving, and + not allowed to change the meaning of inputs. + + Some descriptors can be quite exotic, so we recommend thinking carefully + if there is a safe fallback you can apply to descriptors you don't understand. + For example, you should have some way to handle not finding a particular + input exactly as is in the final FX graph inputs. + + Note: When using this API, you must create and enter an ExitStack context + manager, which will be passed into this function. This context manager + must remain active if you call the compile function to finish compilation. + (TODO: We may relax this requirement by having AOTAutograd keep track of + how to reconstruct all the context managers at a later point in time.) + + NB: You're not obligated to do a /full/ compile in stage2; instead you can + leave the forward/backward compilers unspecified in which case the + partitioned FX graphs will directly run. The overall autograd Function + can be allowed in graph so you can reprocess it in the context of a + (potentially larger) compiled region later. + + NB: These APIs do NOT hit cache, as we only ever cache the final compile results, + not the intermediate export result. + + NB: If the passed nn.Module has parameters and buffers on it, we will + generate extra implicit parameter/buffer arguments and assign ParamAOTInput + and BufferAOTInput descriptors to them. However, if you generate the input + nn.Module from a mechanism like Dynamo, you will NOT get these descriptors + (because Dynamo will already have taken care of lifting the parameters/buffers + into arguments!) In that case, it would be necessary to analyze the Sources + of the inputs to determine if inputs are parameters and their FQNs. + """ + + ( + functional_call, + _params_buffers_flat, + params_spec, + buffers_spec, + fake_flat_args, + full_args_descs, + aot_config, + fake_mode, + shape_env, + in_spec, + out_spec, + act_input_paths, + ) = prepare_aot_module_simplified( + mod, + args, + kwargs, + # In contrast, decompositions are needed at this stage. + decompositions, + keep_inference_input_mutations, + ignore_shape_env, + flatten=True, + # Without this, we will attempt to "compile" the backward lazily + # at runtime, but this is pointless because it's just boxed_nop, + # it's trivial. But this will get Inductor confused about scoping + # Metric(s) {'is_forward'} have already been set in the current + # context. + force_non_lazy_backward_lowering=True, + disable_functionalization=disable_functionalization, + _record_nn_module_stack=_record_nn_module_stack, + _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode, + ) + + # TODO: Maybe this should be in create_aot_state? Not sure, that would + # increase its scope + stack.enter_context(compiled_autograd._disable()) + + aot_state = create_aot_state( + stack, + functional_call, + fake_flat_args, + full_args_descs, + aot_config, + fake_mode, + shape_env, + ) + aot_state.fw_metadata.act_input_paths = act_input_paths + + # NB: no cache lookup! + aot_graph_capture = aot_stage1_graph_capture(aot_state, functional_call) + + if out_spec is None or out_spec.spec is None: + raise AssertionError("out_spec and out_spec.spec must not be None") + if in_spec is None: + raise AssertionError("in_spec must not be None") + return JointWithDescriptors( + _aot_state=aot_state, + _aot_graph_capture=aot_graph_capture, + params_spec=params_spec, + buffers_spec=buffers_spec, + in_spec=in_spec, + out_spec=out_spec.spec, + ) + + +def aot_compile_joint_with_descriptors( + jd: JointWithDescriptors, + *, + partition_fn: Callable[..., Any] = default_partition, + fw_compiler: AOTDispatchCompiler = boxed_nop_preserve_node_meta, + bw_compiler: AOTDispatchCompiler | None = boxed_nop_preserve_node_meta, + serializable: bool = False, +) -> Callable[..., Any]: + """ + Companion function for aot_export_joint_with_descriptors which compiles the joint + graph into a callable function that follows a standard calling convention. + params_flat all are arguments. + + Note: We do NOT instantiate the module; this gives you the flexibility to subclass it and + customize its behavior without having to worry about FQN rebinding. + + Args: + serializable: If True, configures the compilation to produce a serializable + callable by leveraging AOTAutogradCache machinery. This sets up the + necessary cache_info and patches config options required for serialization. + When True, this function will always return a BundledAOTAutogradSerializableCallable. + """ + # TODO: Consider if we should allow_in_graph the result by default. + from torch._dynamo.aot_compile_types import ( + BundledAOTAutogradSerializableCallable, + SerializableCallable, + ) + from torch._functorch._aot_autograd.schemas import AOTAutogradCacheInfo + from torch._guards import detect_fake_mode + from torch._inductor.output_code import OutputCode + + fw_compiler = SerializableAOTDispatchCompiler(OutputCode, fw_compiler) + + cache_ctx = nullcontext() + if serializable: + jd._aot_state.aot_config = dataclasses.replace( + jd._aot_state.aot_config, + cache_info=AOTAutogradCacheInfo( + jd.cache_hash(), + time.time_ns(), + forward_symints=[], + ), + ) + cache_ctx = torch._functorch.config.patch( + { + "strict_autograd_cache": True, + "bundled_autograd_cache": True, + "force_non_lazy_backward_lowering": True, + "bypass_autograd_cache_key": True, + } + ) + + # Set up a TracingContext if one isn't already available. + # This is needed for compilers (like regional_inductor) that call + # standalone_compile with dynamic_shapes="from_tracing_context". + tracing_context = torch._guards.TracingContext.try_get() + if tracing_context is None: + fake_mode = detect_fake_mode(jd._aot_state.flat_args) + if fake_mode is not None: + tracing_context = torch._guards.TracingContext(fake_mode) + tracing_ctx = torch._guards.tracing(tracing_context) + else: + tracing_ctx = nullcontext() + else: + tracing_ctx = nullcontext() + + with cache_ctx, tracing_ctx: + compiled_fn, _ = aot_stage2_compile( + jd._aot_state, + jd._aot_graph_capture, + partition_fn, + fw_compiler, + bw_compiler, + ) + + if not isinstance(compiled_fn, SerializableCallable) and hasattr( + compiled_fn, "serialize" + ): + compiled_fn = BundledAOTAutogradSerializableCallable(compiled_fn) + + # Cribbed from torch/export/pt2_archive/_package.py + @simple_wraps(compiled_fn) + @torch._dynamo.nonstrict_trace # allow recursive compilation + def unflattened_compiled_fn(*args: Any, **kwargs: Any) -> Any: + flat_inputs = pytree.tree_flatten((args, reorder_kwargs(kwargs, jd.in_spec)))[0] + # TODO: do I need to filter? I hope not! + flat_outputs = compiled_fn(flat_inputs) + return pytree.tree_unflatten(flat_outputs, jd.out_spec) + + return unflattened_compiled_fn + + +def aot_export_module( + mod: nn.Module, + args: Iterable[Any], + *, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + # If true, we'll return a joint forward-backward graph, + # As well as metadata on the loss + gradients in the backward. + trace_joint: bool, + # If trace_joint is True, we expect your module to return a scalar loss. + # Your module can return multiple outputs, so you must specify which output the loss is. + output_loss_index: int | None = None, + pre_dispatch: bool = False, + # If None, will be inferred from inputs and mod.graph.nodes if mod is a graph module, but the inferred result might be wrong. + dynamic_shapes: bool | None = None, + kwargs: dict[str, Any] | None = None, +) -> tuple[Callable[..., Any] | torch.fx.GraphModule, GraphSignature]: + """ + This function takes in a module, and returns: + (1) an FX graph that can be exported + (2) some metadata about the graph + + If `trace_joint=True` we will return a joint graph of the forward + backward. + + The traced FX graph will have the following properties compared to the original module: + (1) Inputs and outputs to the module will be pytree-flattened + (2) Parameters and buffers on the module will be lifted into graph inputs, + graph_inputs = (*parameters, *buffers, *user_inputs) + (3) The graph will be fully functionalized + (4) Any input mutations will be converted into additional outputs in the graph, + meaning whoever calls this graph is responsible for applying the mutations + back to the original inputs. + (5) If is_joint is provided the graph will return parameter gradients in addition to user outputs. + The graph output will look like: + graph_outputs = (*updated_inputs, *user_outputs, *param_gradients) + + There are also several restrictions on what modules can use this API. In particular: + (1) If trace_joint is specified, we expect the loss function to be **fused** + into the module forward. One of the outputs to the forward must be a scalar loss, + which is specified with `output_loss_index`. + All other outputs to the forward are presumed to not require gradients. + (2) This API cannot capture optimizers (although in theory we could build an API for this). + (3) Metadata mutations on params/buffers/inputs are banned. + (4) Data mutations on anything that requires gradients are banned (parameters) + (5) If an input is mutated, it is not allowed to alias any other inputs. + (6) Parameters must not be duplicated. + """ + if pre_dispatch and trace_joint: + raise RuntimeError("pre_dispatch is not supported when trace_joint is True.") + named_parameters = dict(mod.named_parameters(remove_duplicate=False)) + named_buffers = dict(mod.named_buffers(remove_duplicate=False)) + + params_and_buffers = { + **dict(named_parameters), + **dict(named_buffers), + } + params_and_buffers_flat, params_spec = pytree.tree_flatten(params_and_buffers) + params_and_buffers_flat = tuple(params_and_buffers_flat) + params_len = len(params_and_buffers_flat) + + kwargs = kwargs or {} + + functional_call = create_functional_call( + mod, params_spec, params_len, store_orig_mod=True + ) + + num_fw_outs = None + + if trace_joint: + # This helper effectively just adds some extra asserts about what the backward will look like: + # Outputs must include a scalar loss, that we compute gradients w.r.t. + # We don't compute gradients w.r.t. anything else: so just in case we detach() + # and other output tensors. + def fn_to_trace(*args: Any) -> Any: + nonlocal num_fw_outs + out = functional_call(*args) + if output_loss_index is None: + raise RuntimeError( + """\ +If trace_joint=Trueit is required that one of your forward outputs must be a scalar loss. +You must specify the which (index) output is the loss with output_loss_index.""" + ) + if isinstance(out, (torch.Tensor)): + out = (out,) + if not isinstance(out, (tuple, list)): + raise RuntimeError( + f"Expected forward output to be either a tensor or a list/tuple of tensors. found {type(out)}" + ) + + for i, o in enumerate(out): + # We only want to create a backward graph w.r.t. the loss that the user passed in. + # This implies that every other output should not require gradients. + # Instead of making this an error (and forcing the user to detach all other outputs + # of their forward), + # we'll automatically detach them here. + if o.requires_grad and i != output_loss_index: + raise RuntimeError( + f"""\ +Found an output of the forward that requires gradients, that was not the scalar loss. +We require all outputs to the forward that are not the scalar loss to not require gradient, +because we will only compute a backward graph against the scalar loss. +You can fix this by calling .detach() on each of your forward outputs that is not the loss. +You specified that output index {output_loss_index} is the loss, but we found that +the output at index {i} requires gradients.""" + ) + out_loss = out[output_loss_index] + num_fw_outs = len(out) + if not out_loss.requires_grad: + raise RuntimeError( + f"""\ +The output at index {output_loss_index} was marked as the loss, but it does not require gradients""" + ) + if out_loss.numel() != 1: + raise RuntimeError( + f"""\ +We require the output marked as the loss (at index {output_loss_index}) to be a scalar, but it has shape {out_loss.shape}""" + ) + return out + + ctx = nullcontext + else: + # Run under no_grad, so our tracing machinery only traces an inference graph. + # However if pre_dispatch=True, we want to correctly trace set_grad_enabled calls for training. + ctx = nullcontext if pre_dispatch else torch.no_grad + fn_to_trace = functional_call + + full_args = [] + # First, the params + # NB: It is REQUIRED that parameters come first, Inductor infers "fixed" + # parameters by looking at the difference in parameter count outside + # and inside AOTAutograd, and assumes the prefix of arguments are fixed + # arguments + full_args.extend(params_and_buffers_flat) + # Next, the input args + full_args.extend(args) + + with ctx(): + fx_g, metadata, in_spec, out_spec = _aot_export_function( + fn_to_trace, + tuple(full_args), + decompositions=decompositions, + num_params_buffers=params_len, + no_tangents=True, + pre_dispatch=pre_dispatch, + dynamic_shapes=dynamic_shapes, + trace_joint=trace_joint, + kwargs=kwargs, + ) + + # TODO: subsume this path with the aot_stage2_graph_capture path + if trace_joint: + + @wraps(functional_call) + def flattened_joint(*args: Any) -> Any: + # The idea here is that the joint graph that AOTAutograd creates has some strict properties: + # (1) It accepts two arguments (primals, tangents), and pytree_flattens them + # (2) It returns a tuple of (fw_outs, gradients) + # This is a very useful convention for anyone who wants to partition the joint graph + # into a separate forward and backward graph. + # However, + # (1) for people exporting a single joint graph, it would be preferable not to have + # any pytrees in the graph. + # (2) We are guaranteed in the aot_export_module case that the forward outputs a loss, + # and there are therefore no tangents that are needed to run the joint graph. + # (3) AOTAutograd creates a grad_input for every input in the forward, + # including None's for inputs that are not grad-requiring tensors. + # we don't want these in our export graph. + # and there are therefore no tangents that are needed to run the joint graph. + # This function "fixes" both of the above by removing any tangent inputs, + # and removing pytrees from the original FX graph. + fake_tangents = [ + None + for _ in range( + metadata.num_outputs + metadata.num_mutated_inp_runtime_indices + ) + ] + fw_outs, gradients = fx_g(args, fake_tangents) + if len(gradients) != len(args): + raise AssertionError( + f"len(gradients)={len(gradients)} != len(args)={len(args)}" + ) + output_gradients = [] + for a, grad in zip(args, gradients): + if isinstance(a, torch.Tensor) and a.requires_grad: + if grad is None: + raise AssertionError("""\ +Found a parameter that did not receive a gradient. +"This is most likely a bug, but if this needs to be supported please comment on this Github issue: +https://github.com/pytorch/pytorch/issues/101192 +""") + output_gradients.append(grad) + else: + if grad is not None: + raise AssertionError( + f"expected grad to be None for non-tensor or non-requires_grad input, got {type(grad)}" + ) + return *fw_outs, *output_gradients + + fx_g = make_fx(flattened_joint, record_module_stack=True)(*full_args) + + user_args_flat = pytree.arg_tree_leaves(*args, **kwargs) + if out_spec is None: + raise AssertionError("out_spec must not be None") + return fx_g, create_graph_signature( + # type: ignore[bad-argument-type] + fx_g, + metadata, + in_spec, + out_spec, + user_args_flat=user_args_flat, + params_and_buffers_flat=list(params_and_buffers_flat), + param_names=list(named_parameters.keys()), + buffer_names=list(named_buffers.keys()), + trace_joint=trace_joint, + num_user_fw_outs=num_fw_outs, + loss_index=output_loss_index, + ) + + +def aot_export_joint_simple( + func: Callable[..., Any], + args: tuple[Any, ...], + *, + trace_joint: bool, + # It looks like the main consequence of this API is that for dynamic shapes, + # it will assume that params/buffers are static. + # With the new inferred dynamic shapes API, maybe this doesn't matter? + num_params_buffers: int = 0, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, +) -> Callable[..., Any]: + """ + A simplified version of export. Used by higher order operators. + + This function makes a high-level "no calling convention changes" guarantee: + - If no inputs require grad (so we export an inference graph), + there are *no* calling convention change between the exported graph, and "func". + - If at least one input requires grad (so we trace out and export a joint fw-bw graph), + Then if you were partition the graph into a separate forward and backward graph, + The forward graph will have no calling convention changes compared to "func". + + The above also relies on some strong restrictions around which functions this API accepts: + (1) `args` cannot contain any pytrees (they must have been pytree_flattened already) + (2) `func` cannot mutate any inputs + (3) The outputs of `func` cannot alias any inputs. + + Note: this function is only lightly tested today. It will probably be tested more heavily by higher order ops. + """ + if trace_joint: + ctx = nullcontext + else: + # Run under no_grad, so our tracing machinery only traces an inference graph. + ctx = torch.no_grad + + with ctx(): + fx_g, metadata, in_spec, out_spec = _aot_export_function( + func, + args, + decompositions=decompositions, + trace_joint=trace_joint, + ) + in_spec, _kw_in_spec = in_spec.children() + # At this point, we can just directly return the (joint or inference graph) that we traced. + # First though: a bunch of assertions to make sure that our graph doesn't require + # any calling convention changes compared to the original function. + # These restrictions are *in addition to* the general restrictions on export. + + # No input mutations + if ( + len([x for x in metadata.input_info if x.mutates_data or x.mutates_metadata]) + != 0 + ): + raise RuntimeError( + f"aot_export_joint_simple does not support input mutations. {str(metadata)}" + ) + # No output aliasing + if ( + len([x for x in metadata.output_info if x.output_type != OutputType.non_alias]) + != 0 + ): + raise RuntimeError( + f"aot_export_joint_simple does not support outputs that alias inputs. {str(metadata)}" + ) + # No pytrees + if in_spec.is_leaf(): + raise RuntimeError( + f"aot_export_joint_simple requires inputs to be a single list/tuple. in_spec={str(in_spec)}" + ) + if not all(child.is_leaf() for child in in_spec.children()): + raise RuntimeError( + f"aot_export_joint_simple requires individual inputs not to be pytrees. in_spec={str(in_spec)}" + ) + + if out_spec is None: + raise AssertionError("out_spec must not be None") + if out_spec.is_leaf(): + raise RuntimeError( + f"aot_export_joint_simple requires outputs to be a single list/tuple. out_spec={str(out_spec)}" + ) + if not all(child.is_leaf() for child in out_spec.children()): + raise RuntimeError( + f"aot_export_joint_simple requires individual outputs not to be pytrees. out_spec={str(out_spec)}" + ) + # TODO: we might have to temporarily patch config.functionalize_rng + # so that it doesn't run when we're exporting a higher order op. + + if config.debug_assert: + # Smoke test that after partitioning, we can run the forward without any calling convention changes. + fw_module, _bw_module = default_partition( + # type: ignore[bad-argument-type] + fx_g, + args, + # type: ignore[unknown-name] + num_fwd_outputs=len(fw_metadata.output_infos), # noqa: F821 + ) + # Attempt to run the fw_module with the original user inputs + fake_mode = detect_fake_mode(args) + if fake_mode is None: + fake_mode = FakeTensorMode() + with fake_mode: + fw_module(*args) + return fx_g + + +# Private for now because we aren't providing a contract on what to return +# for joint graphs (we could when there's a clearer use case) +# In the future, we may need to add more export API's that provide their own strong guarantees. +# This is meant as a general helper function for handling various export-y use cases. +def _aot_export_function( + func: Callable[..., Any], + args: tuple[Any, ...], + *, + num_params_buffers: int = 0, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + # If we're exporting a joint graph and we don't want any tangent inputs in the graph + # (because we are backpropping through a scalar 1 loss), + # we need to explicitly specify not to include tangents in the graph. + # It's not enough just to check that our tangent is a scalar, since we also + # need to know if it is a 1 (no need to make it a graph input), or something else + # (requiring it to be a graph input). + # We don't know this info at trace time though, so we need to make it an explicit config. + no_tangents: bool = False, + pre_dispatch: bool = False, + # If None, `dynamic_shapes` will be inferred from inputs, but the inferred result might be wrong. + dynamic_shapes: bool | None = None, + keep_input_mutations: bool = False, + # Under export, configures whether we are getting inference or training IR + trace_joint: bool = False, + kwargs: dict[str, Any] | None = None, +) -> tuple[ + Callable[..., Any], ViewAndMutationMeta, pytree.TreeSpec, pytree.TreeSpec | None +]: + kwargs = kwargs or {} + + flat_fn, out_spec = create_tree_flattened_fn(func, args, kwargs) + flat_args, in_spec = pytree.tree_flatten((args, kwargs)) + + fake_mode = None + if dynamic_shapes is None: + # Try to infer `dynamic_shapes from inputs and graph nodes + fake_mode = detect_fake_mode(flat_args) + if ( + fake_mode is None + and hasattr(func, "_orig_mod") + and isinstance(func._orig_mod, torch.fx.GraphModule) + ): + vals = [ + node.meta["val"] + for node in func._orig_mod.graph.nodes + if "val" in node.meta + ] + fake_mode = detect_fake_mode(vals) + dynamic_shapes = fake_mode is not None and fake_mode.shape_env is not None + + # The export use case doesn't care about several bits of AOTConfig + # (1) compilers (we just export the graph) + # (2) partitioners (export is only full graph, user can partition themselves) + aot_config = AOTConfig( # type: ignore[arg-type] + fw_compiler=None, + bw_compiler=None, + inference_compiler=None, + partition_fn=None, + decompositions=decompositions, + num_params_buffers=num_params_buffers, + aot_id=next(AOT_COUNTER), + keep_inference_input_mutations=keep_input_mutations, + dynamic_shapes=dynamic_shapes, + aot_autograd_arg_pos_to_source=None, + is_export=True, + no_tangents=no_tangents, + pre_dispatch=pre_dispatch, + export_trace_joint=trace_joint, + ) + if fake_mode is None: + fake_mode, shape_env = construct_fake_mode(flat_args, aot_config) + else: + shape_env = fake_mode.shape_env + fake_flat_args, act_input_paths = process_inputs( + flat_args, aot_config, fake_mode, shape_env + ) + # TODO: Improve the descs here with pytree information + fake_flat_args_descs: list[AOTInput] = [ + PlainAOTInput(i) for i in range(len(fake_flat_args)) + ] + + with contextlib.ExitStack() as stack: + aot_state = create_aot_state( + stack, + flat_fn, + fake_flat_args, + fake_flat_args_descs, + aot_config, + fake_mode, + shape_env, + ) + aot_state.fw_metadata.act_input_paths = act_input_paths + aot_graph_capture = aot_stage1_graph_capture(aot_state, flat_fn) + fx_g, meta = aot_stage2_export(aot_state, aot_graph_capture) + + return fx_g, meta, in_spec, out_spec.spec + + +compiled_function = aot_function +compiled_module = aot_module diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/apis.py b/.venv/lib/python3.12/site-packages/torch/_functorch/apis.py new file mode 100644 index 0000000000000000000000000000000000000000..e33f46cf49b51e15583db31c90ee2ca3e000ede7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/apis.py @@ -0,0 +1,510 @@ +# NOTE: We allow Dynamo to see this file (via torch/_dynamo/trace_rules.py) so that it can +# trace through functorch transforms. +# Currently, we can't allow Dynamo to see `eager_transforms.py`/`vmap.py` as that break a lot of thing +# and there isn't a mechanism to selectively expose only some functions (eg. grad) from a file +# to Dynamo. + +from __future__ import annotations + +import functools +from typing import Any, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +from torch._functorch.utils import argnums_t, exposed_in +from torch._functorch.vmap import ( + _check_out_dims_is_int_or_int_pytree, + _check_randomness_arg, + _chunked_vmap, + _process_batched_inputs, + Callable, + in_dims_t, + out_dims_t, + vmap_impl, +) + + +if TYPE_CHECKING: + from collections.abc import Iterable + + import torch + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +# functools.wraps copies __dict__, but these attrs describe the original +# compiled callable, not the transformed function wrapper. +_DYNAMO_WRAPPER_ATTRS = ( + "_torchdynamo_inline", + "_torchdynamo_orig_callable", + "_torchdynamo_wrapper_id", + "_isolate_recompiles_id", + "get_compiler_config", + "aot_compile", + "_is_torch_compile", +) + + +def _wraps_without_dynamo_attrs( + func: Callable[..., Any], +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + def inner(wrapper: Callable[_P, _R]) -> Callable[_P, _R]: + wrapper = functools.wraps(func)(wrapper) + for attr in _DYNAMO_WRAPPER_ATTRS: + wrapper.__dict__.pop(attr, None) + return wrapper + + return inner + + +# vmap(func)(inputs) wraps all Tensor inputs to be batched in BatchedTensors, +# sends those into func, and then unwraps the output BatchedTensors. Operations +# on BatchedTensors perform the batched operations that the user is asking for. +# +# vmap's randomness behavior differs from JAX's, which would require a PRNG key +# to be passed everywhere. + + +@exposed_in("torch.func") +def vmap( + func: Callable[_P, _R], + in_dims: in_dims_t = 0, + out_dims: out_dims_t = 0, + randomness: str = "error", + *, + chunk_size: int | None = None, +) -> Callable[_P, _R]: + """ + vmap is the vectorizing map; ``vmap(func)`` returns a new function that + maps ``func`` over some dimension of the inputs. Semantically, vmap + pushes the map into PyTorch operations called by ``func``, effectively + vectorizing those operations. + + vmap is useful for handling batch dimensions: one can write a function + ``func`` that runs on examples and then lift it to a function that can + take batches of examples with ``vmap(func)``. vmap can also be used to + compute batched gradients when composed with autograd. + + .. note:: + :func:`torch.vmap` is aliased to :func:`torch.func.vmap` for + convenience. Use whichever one you'd like. + + Args: + func (function): A Python function that takes one or more arguments. + Must return one or more Tensors. + in_dims (int or nested structure): Specifies which dimension of the + inputs should be mapped over. ``in_dims`` should have a + structure like the inputs. If the ``in_dim`` for a particular + input is None, then that indicates there is no map dimension. + Default: 0. + out_dims (int or Tuple[int]): Specifies where the mapped dimension + should appear in the outputs. If ``out_dims`` is a Tuple, then + it should have one element per output. Default: 0. + randomness (str): Specifies whether the randomness in this + vmap should be the same or different across batches. If 'different', + the randomness for each batch will be different. If 'same', the + randomness will be the same across batches. If 'error', any calls to + random functions will error. Default: 'error'. WARNING: this flag + only applies to random PyTorch operations and does not apply to + Python's random module or numpy randomness. + chunk_size (None or int): If None (default), apply a single vmap over inputs. + If not None, then compute the vmap :attr:`chunk_size` samples at a time. + Note that :attr:`chunk_size=1` is equivalent to computing the vmap with a for-loop. + If you run into memory issues computing the vmap, please try a non-None chunk_size. + + Returns: + Returns a new "batched" function. It takes the same inputs as + ``func``, except each input has an extra dimension at the index + specified by ``in_dims``. It takes returns the same outputs as + ``func``, except each output has an extra dimension at the index + specified by ``out_dims``. + + .. warning: + :func:`vmap` works best with functional-style code. Please do not + perform any side-effects in ``func``, with the exception of + in-place PyTorch operations. Examples of side-effects include mutating + Python data structures and assigning values to variables not captured + in ``func``. + + One example of using :func:`vmap` is to compute batched dot products. PyTorch + doesn't provide a batched ``torch.dot`` API; instead of unsuccessfully + rummaging through docs, use :func:`vmap` to construct a new function. + + >>> torch.dot # [D], [D] -> [] + >>> batched_dot = torch.func.vmap(torch.dot) # [N, D], [N, D] -> [N] + >>> x, y = torch.randn(2, 5), torch.randn(2, 5) + >>> batched_dot(x, y) + + :func:`vmap` can be helpful in hiding batch dimensions, leading to a simpler + model authoring experience. + + >>> batch_size, feature_size = 3, 5 + >>> weights = torch.randn(feature_size, requires_grad=True) + >>> + >>> def model(feature_vec): + >>> # Very simple linear model with activation + >>> return feature_vec.dot(weights).relu() + >>> + >>> examples = torch.randn(batch_size, feature_size) + >>> result = torch.vmap(model)(examples) + + :func:`vmap` can also help vectorize computations that were previously difficult + or impossible to batch. One example is higher-order gradient computation. + The PyTorch autograd engine computes vjps (vector-Jacobian products). + Computing a full Jacobian matrix for some function f: R^N -> R^N usually + requires N calls to ``autograd.grad``, one per Jacobian row. Using :func:`vmap`, + we can vectorize the whole computation, computing the Jacobian in a single + call to ``autograd.grad``. + + >>> # Setup + >>> N = 5 + >>> f = lambda x: x**2 + >>> x = torch.randn(N, requires_grad=True) + >>> y = f(x) + >>> I_N = torch.eye(N) + >>> + >>> # Sequential approach + >>> jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0] + >>> for v in I_N.unbind()] + >>> jacobian = torch.stack(jacobian_rows) + >>> + >>> # vectorized gradient computation + >>> def get_vjp(v): + >>> return torch.autograd.grad(y, x, v) + >>> jacobian = torch.vmap(get_vjp)(I_N) + + :func:`vmap` can also be nested, producing an output with multiple batched dimensions + + >>> torch.dot # [D], [D] -> [] + >>> batched_dot = torch.vmap( + ... torch.vmap(torch.dot) + ... ) # [N1, N0, D], [N1, N0, D] -> [N1, N0] + >>> x, y = torch.randn(2, 3, 5), torch.randn(2, 3, 5) + >>> batched_dot(x, y) # tensor of size [2, 3] + + If the inputs are not batched along the first dimension, ``in_dims`` specifies + the dimension that each inputs are batched along as + + >>> torch.dot # [N], [N] -> [] + >>> batched_dot = torch.vmap(torch.dot, in_dims=1) # [N, D], [N, D] -> [D] + >>> x, y = torch.randn(2, 5), torch.randn(2, 5) + >>> batched_dot( + ... x, y + ... ) # output is [5] instead of [2] if batched along the 0th dimension + + If there are multiple inputs each of which is batched along different dimensions, + ``in_dims`` must be a tuple with the batch dimension for each input as + + >>> torch.dot # [D], [D] -> [] + >>> batched_dot = torch.vmap(torch.dot, in_dims=(0, None)) # [N, D], [D] -> [N] + >>> x, y = torch.randn(2, 5), torch.randn(5) + >>> batched_dot( + ... x, y + ... ) # second arg doesn't have a batch dim because in_dim[1] was None + + If the input is a Python struct, ``in_dims`` must be a tuple containing a struct + matching the shape of the input: + + >>> f = lambda dict: torch.dot(dict["x"], dict["y"]) + >>> x, y = torch.randn(2, 5), torch.randn(5) + >>> input = {"x": x, "y": y} + >>> batched_dot = torch.vmap(f, in_dims=({"x": 0, "y": None},)) + >>> batched_dot(input) + + By default, the output is batched along the first dimension. However, it can be batched + along any dimension by using ``out_dims`` + + >>> f = lambda x: x**2 + >>> x = torch.randn(2, 5) + >>> batched_pow = torch.vmap(f, out_dims=1) + >>> batched_pow(x) # [5, 2] + + For any function that uses kwargs, the returned function will not batch the kwargs but will + accept kwargs + + >>> x = torch.randn([2, 5]) + >>> def fn(x, scale=4.): + >>> return x * scale + >>> + >>> batched_pow = torch.vmap(fn) + >>> assert torch.allclose(batched_pow(x), x * 4) + >>> batched_pow(x, scale=x) # scale is not batched, output has shape [2, 2, 5] + + .. note:: + vmap does not provide general autobatching or handle variable-length + sequences out of the box. + """ + from torch.compiler import is_compiling + + _check_randomness_arg(randomness) + if not (chunk_size is None or chunk_size > 0): + raise ValueError( + f"vmap: chunk_size should be None or greater than 0. (got {chunk_size})" + ) + + def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: + # pyrefly: ignore[bad-argument-type] + return vmap_impl( + # pyrefly: ignore[bad-argument-type] + func, + in_dims, + out_dims, + randomness, + chunk_size, + *args, + **kwargs, + ) + + if not is_compiling(): + wrapped = _wraps_without_dynamo_attrs(func)(wrapped) + + return wrapped + + +def chunk_vmap( + func: Callable[_P, _R], + in_dims: in_dims_t = 0, + out_dims: out_dims_t = 0, + randomness: str = "error", + chunks: int = 2, +) -> Callable[_P, _R]: + """ + chunk_vmap is the vectorizing map (vmap) using chunks of input data. It is a mix of vmap (which vectorizes + everything) and map (which executes things sequentially). ``chunk_vmap`` vectorizes the input with number of + chunks at a time. For more details about vectorizing map, see :func:`vmap`. + + .. note:: + Please use :func:`vmap` with ``chunk_size`` argument instead of this API. + + Args: + func (function): A Python function that takes one or more arguments. + Must return one or more Tensors. + in_dims (int or nested structure): Specifies which dimension of the + inputs should be mapped over. ``in_dims`` should have a + structure like the inputs. If the ``in_dim`` for a particular + input is None, then that indicates there is no map dimension. + Default: 0. + out_dims (int or Tuple[int]): Specifies where the mapped dimension + should appear in the outputs. If ``out_dims`` is a Tuple, then + it should have one element per output. Default: 0. + randomness (str): Specifies whether the randomness in this + vmap should be the same or different across batches. If 'different', + the randomness for each batch will be different. If 'same', the + randomness will be the same across batches. If 'error', any calls to + random functions will error. Default: 'error'. WARNING: this flag + only applies to random PyTorch operations and does not apply to + Python's random module or numpy randomness. + chunks (int): Number of chunks to use to split the input data. Default is 2. + If equals to 1 then :func:`vmap` is called. + + Returns: + Returns a new "batched" function. It takes the same inputs as + ``func``, except each input has an extra dimension at the index + specified by ``in_dims``. It takes returns the same outputs as + ``func``, except each output has an extra dimension at the index + specified by ``out_dims``. + """ + _check_randomness_arg(randomness) + + if chunks == 1: + return vmap(func, in_dims=in_dims, out_dims=out_dims, randomness=randomness) + + def _get_chunk_flat_args( + flat_args_: Iterable[Any], + flat_in_dims_: Iterable[int | None], + chunks_: int, + ) -> Iterable[Any]: + flat_args_chunks = tuple( + t.chunk(chunks_, dim=in_dim) + if in_dim is not None + else [ + t, + ] + * chunks_ + for t, in_dim in zip(flat_args_, flat_in_dims_) + ) + # transpose chunk dim and flatten structure + # chunks_flat_args is a list of flatten args + chunks_flat_args = zip(*flat_args_chunks) + return chunks_flat_args + + @_wraps_without_dynamo_attrs(func) + def wrapped_with_chunks(*args: _P.args, **kwargs: _P.kwargs) -> _R: + _check_out_dims_is_int_or_int_pytree(out_dims, func) + _, flat_in_dims, flat_args, args_spec = _process_batched_inputs( + in_dims, args, func + ) + # Chunk flat arguments + chunks_flat_args = _get_chunk_flat_args(flat_args, flat_in_dims, chunks) + + # Apply vmap on chunks + return _chunked_vmap( + # pyrefly: ignore[bad-argument-type] + func, + flat_in_dims, + chunks_flat_args, + args_spec, + out_dims, + randomness, + **kwargs, + ) + + return wrapped_with_chunks + + +# TODO: Improve the return type of this function +@exposed_in("torch.func") +def grad( + func: Callable[_P, Any], argnums: argnums_t = 0, has_aux: bool = False +) -> Callable[_P, Any]: + """``grad`` operator helps computing gradients of ``func`` with respect to the + input(s) specified by ``argnums``. This operator can be nested to + compute higher-order gradients. + + Args: + func (Callable): A Python function that takes one or more arguments. + Must return a single-element Tensor. If specified ``has_aux`` equals ``True``, + function can return a tuple of single-element Tensor and other auxiliary objects: + ``(output, aux)``. + argnums (int or Tuple[int]): Specifies arguments to compute gradients with respect to. + ``argnums`` can be single integer or tuple of integers. Default: 0. + has_aux (bool): Flag indicating that ``func`` returns a tensor and other + auxiliary objects: ``(output, aux)``. Default: False. + + Returns: + Function to compute gradients with respect to its inputs. By default, the output of + the function is the gradient tensor(s) with respect to the first argument. + If specified ``has_aux`` equals ``True``, tuple of gradients and output auxiliary objects + is returned. If ``argnums`` is a tuple of integers, a tuple of output gradients with + respect to each ``argnums`` value is returned. + + Example of using ``grad``: + + >>> # xdoctest: +SKIP + >>> from torch.func import grad + >>> x = torch.randn([]) + >>> cos_x = grad(lambda x: torch.sin(x))(x) + >>> assert torch.allclose(cos_x, x.cos()) + >>> + >>> # Second-order gradients + >>> neg_sin_x = grad(grad(lambda x: torch.sin(x)))(x) + >>> assert torch.allclose(neg_sin_x, -x.sin()) + + When composed with ``vmap``, ``grad`` can be used to compute per-sample-gradients: + + >>> # xdoctest: +SKIP + >>> from torch.func import grad, vmap + >>> batch_size, feature_size = 3, 5 + >>> + >>> def model(weights, feature_vec): + >>> # Very simple linear model with activation + >>> assert feature_vec.dim() == 1 + >>> return feature_vec.dot(weights).relu() + >>> + >>> def compute_loss(weights, example, target): + >>> y = model(weights, example) + >>> return ((y - target) ** 2).mean() # MSELoss + >>> + >>> weights = torch.randn(feature_size, requires_grad=True) + >>> examples = torch.randn(batch_size, feature_size) + >>> targets = torch.randn(batch_size) + >>> inputs = (weights, examples, targets) + >>> grad_weight_per_example = vmap(grad(compute_loss), in_dims=(None, 0, 0))( + ... *inputs + ... ) + + Example of using ``grad`` with ``has_aux`` and ``argnums``: + + >>> # xdoctest: +SKIP + >>> from torch.func import grad + >>> def my_loss_func(y, y_pred): + >>> loss_per_sample = (0.5 * y_pred - y) ** 2 + >>> loss = loss_per_sample.mean() + >>> return loss, (y_pred, loss_per_sample) + >>> + >>> fn = grad(my_loss_func, argnums=(0, 1), has_aux=True) + >>> y_true = torch.rand(4) + >>> y_preds = torch.rand(4, requires_grad=True) + >>> out = fn(y_true, y_preds) + >>> # > output is ((grads w.r.t y_true, grads w.r.t y_preds), (y_pred, loss_per_sample)) + + .. note:: + Using PyTorch ``torch.no_grad`` together with ``grad``. + + Case 1: Using ``torch.no_grad`` inside a function: + + >>> # xdoctest: +SKIP + >>> def f(x): + >>> with torch.no_grad(): + >>> c = x ** 2 + >>> return x - c + + In this case, ``grad(f)(x)`` will respect the inner ``torch.no_grad``. + + Case 2: Using ``grad`` inside ``torch.no_grad`` context manager: + + >>> # xdoctest: +SKIP + >>> with torch.no_grad(): + >>> grad(f)(x) + + In this case, ``grad`` will respect the inner ``torch.no_grad``, but not the + outer one. This is because ``grad`` is a "function transform": its result + should not depend on the result of a context manager outside of ``f``. + + """ + # To avoid cyclical dependency. + import torch._functorch.eager_transforms as eager_transforms + from torch.compiler import is_compiling + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> tuple[Any, torch.Tensor]: + return eager_transforms.grad_impl(func, argnums, has_aux, args, kwargs) + + if not is_compiling(): + wrapper = _wraps_without_dynamo_attrs(func)(wrapper) + + return wrapper + + +# TODO: Improve the return type of this function +@exposed_in("torch.func") +def grad_and_value( + func: Callable[_P, Any], argnums: argnums_t = 0, has_aux: bool = False +) -> Callable[_P, tuple[Any, Any]]: + """ + Returns a function to compute a tuple of the gradient and primal, or + forward, computation. + + Args: + func (Callable): A Python function that takes one or more arguments. + Must return a single-element Tensor. If specified ``has_aux`` + equals ``True``, function can return a tuple of single-element + Tensor and other auxiliary objects: ``(output, aux)``. + argnums (int or Tuple[int]): Specifies arguments to compute gradients + with respect to. ``argnums`` can be single integer or tuple of + integers. Default: 0. + has_aux (bool): Flag indicating that ``func`` returns a tensor and + other auxiliary objects: ``(output, aux)``. Default: False. + + Returns: + Function to compute a tuple of gradients with respect to its inputs + and the forward computation. By default, the output of the function is + a tuple of the gradient tensor(s) with respect to the first argument + and the primal computation. If specified ``has_aux`` equals + ``True``, tuple of gradients and tuple of the forward computation with + output auxiliary objects is returned. If ``argnums`` is a tuple of + integers, a tuple of a tuple of the output gradients with respect to + each ``argnums`` value and the forward computation is returned. + + See :func:`grad` for examples + """ + from torch._functorch import eager_transforms + from torch.compiler import is_compiling + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> tuple[Any, torch.Tensor]: + return eager_transforms.grad_and_value_impl( + func, argnums, has_aux, args, kwargs + ) + + if not is_compiling(): + wrapper = _wraps_without_dynamo_attrs(func)(wrapper) + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/autograd_function.py b/.venv/lib/python3.12/site-packages/torch/_functorch/autograd_function.py new file mode 100644 index 0000000000000000000000000000000000000000..ed77cd7a0158c93ee8f4adb50b0848dff97956ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/autograd_function.py @@ -0,0 +1,935 @@ +from __future__ import annotations + +from typing import Any, NamedTuple, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +import torch +import torch.utils._pytree as pytree +from torch._C._functorch import ( + _unwrap_for_grad, + _wrap_for_grad, + current_level, + TransformType, +) +from torch._functorch.apis import vmap +from torch._functorch.utils import enable_single_level_autograd_function +from torch._functorch.vmap import ( + _add_batch_dim, + _broadcast_to_and_flatten, + restore_vmap, + unwrap_batched, + wrap_batched, +) +from torch._ops import HigherOrderOperator +from torch.autograd.forward_ad import _set_fwd_grad_enabled + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._functorch.pyfunctorch import FuncTorchInterpreter, VmapInterpreter + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +# autograd.Function technically runs before the regular PyTorch dispatcher. +# This is how features like autocast and torch_dispatch (e.g. PythonTLSSnapshot) +# work with it. One day we might decide to change this, but until then, +# we need to give the illusion that autograd.Function runs before those things. +# +# We do this by using creating a custom HigherOrderOperator that only functorch +# dispatches specially. +class CustomFunctionHigherOrderOperator(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("custom_function_call") + + def __call__( + self, + autograd_function: type[torch.autograd.Function], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> Any: + # When custom_function_call is done dispatching through functorch, + # it should just invoke the autograd.Function. This is consistent + # with the autograd.Function behavior of being invoked before the + # PyTorch dispatcher. + # + # This will lead us into trouble later down the line, but this is + # pre-existing. There is an invariant that a function traced by + # make_fx should have the same behavior when provided the same + # Tensor. However, make_fx sees autograd.Function as a composite + # (because autograd.Function happens before the Python dispatch key) + # and only traces the forward pass. + if torch._C._are_functorch_transforms_active(): + # pyrefly: ignore [missing-attribute] + return super().__call__(autograd_function, *args, **kwargs) + return autograd_function.apply(*args, **kwargs) + + +# "custom_function_call" +# This is the mechanism for an autograd.Function that works with functorch transforms. +# It wraps an autograd.Function; interactions with functorch transforms are defined +# via PyDispatcher and HigherOrderOperator rather than through the traditional PyTorch +# dispatcher. +custom_function_call = CustomFunctionHigherOrderOperator() + + +# The grad rule for custom_function_call is to construct a new _SingleLevelFunction +# (autograd.Function that only works with a single layer (level) of functorch) that: +# - unwraps the inputs +# - redispatches to custom_function_call +# - wraps the outputs +# and whose backward pass calls the original autograd.Function's backward. +# +# Why do we need to redispatch to custom_function_call? +# ----------------------------------------------------- +# This is consistent with how ATen operators work with functorch's grad transform: +# they always redispatch to the original operator. +# Consider torch.sin, and let's say we do grad0(grad1(torch.sin))(x) +# +# grad1 will: +# - set up the autograd graph +# - unwrap the inputs +# - redispatch to at::sin (*) +# - rewrap the outputs on the return +# +# On the redispatch in (*), grad0 will: +# - set up the autograd graph +# - unwrap the inputs +# - redispatch to at::sin +# - rewrap the outputs on the return +# +# To "set up the autograd graph", we generate a _SingleLevelFunction +# and apply it. +@custom_function_call.py_impl(TransformType.Grad) +@custom_function_call.py_impl(TransformType.Jvp) +def custom_function_call_grad( + interpreter: FuncTorchInterpreter, + autograd_function: type[torch.autograd.Function], + *operands: Any, +) -> Any: + Generated = generate_single_level_function(interpreter, autograd_function) + with enable_single_level_autograd_function(): + # pyrefly: ignore [missing-attribute] + flat_out = Generated.apply(*operands) + return flat_out + + +def generate_single_level_function( + interpreter: FuncTorchInterpreter, + autograd_function: type[torch.autograd.Function], +) -> type[torch.autograd.function._SingleLevelFunction]: + level = interpreter.level() + + def forward(*operands: Any) -> Any: + unwrapped_operands = pytree.tree_map_only( + torch.Tensor, lambda x: _unwrap_for_grad(x, level), operands + ) + # Both enable_grad() and _set_fwd_grad_enabled() are necessary no matter + # the transform. _SingleLevelFunction will turn off both fwd and bwd + # gradient computation and we need to turn it back on here. + with torch.enable_grad(), _set_fwd_grad_enabled(True), interpreter.lower(): + unwrapped_output = custom_function_call( + autograd_function, *unwrapped_operands + ) + + # See NOTE [mark_dirty object identity check] + def wrap_fn(output: torch.Tensor) -> torch.Tensor: + return _wrap_for_grad(output, level) + + return wrap_outputs_maintaining_identity( + unwrapped_output, unwrapped_operands, operands, wrap_fn + ) + + def setup_context(ctx: Any, inputs: Any, output: Any) -> Any: + return autograd_function.setup_context(ctx, inputs, output) + + # backward is only used if the transform is TransformType.Grad + def backward(ctx: Any, *grads: Any) -> Any: + result = autograd_function.backward(ctx, *grads) + return result + + # jvp is only used if the transform is TransformType.Jvp + def jvp(ctx: Any, *tangents: Any) -> Any: + result = autograd_function.jvp(ctx, *tangents) + return result + + # This is the sequence of magic words to dynamically generate a Subclass with + # a given name. A Tensor's .grad_fn field has a class name that is the original + # autograd.Function's name + Backward, so we do this to generate some + # meaningful name. + name = f"{autograd_function.__name__}Generated" + Generated = type( + name, + (torch.autograd.function._SingleLevelFunction,), + { + "forward": staticmethod(forward), + "backward": staticmethod(backward), + "jvp": staticmethod(jvp), + "setup_context": staticmethod(setup_context), + }, + ) + return Generated + + +# wrap_outputs_maintaining_identity handles outputs from the vmap, +# backward (vjp), and jvp staticmethod. The way it distinguishes +# between the vmap case and the {backward, jvp} case is if the out_dims +# are specified or not. +# +# NB: we cannot use out_dims=None as the deciding factor. This because +# out_dims=None can still happen in the vmap staticmethod! What the +# user is saying in that case is that their output does not have a +# dimension that is being vmapped over, which is valid. +NO_OUT_DIMS = "not specified" + + +# NOTE [mark_dirty object identity check] +# autograd.Function's ctx.mark_dirty expect a returned input +# to have the same object identity as the input. +# Mode-only functorch will greatly simplify this logic. +def wrap_outputs_maintaining_identity( + outputs: Any, + unwrapped_inputs: Any, + orig_inputs: Any, + wrap_fn: Callable[..., Any], + out_dims: Any = NO_OUT_DIMS, +) -> Any: + flat_unwrapped_inputs = pytree.arg_tree_leaves(*unwrapped_inputs) + flat_orig_inputs = pytree.arg_tree_leaves(*orig_inputs) + + unwrapped_input_to_orig_input = { + id(unwrapped): orig + for unwrapped, orig in zip(flat_unwrapped_inputs, flat_orig_inputs) + } + + flat_outputs, spec = pytree.tree_flatten(outputs) + result = [] + + out_dims_specified = out_dims != NO_OUT_DIMS + + flat_out_dims = None + if out_dims_specified: + flat_out_dims = _broadcast_to_and_flatten(out_dims, spec) + # _broadcast_to_and_flatten returns None if it is unable to broadcast. + # TODO: update following link from master to stable once that's out + if flat_out_dims is None: + raise RuntimeError( + f"The autograd.Function's vmap staticmethod returned an " + f"incompatible (output, out_dims) tuple. " + f"Expected out_dims={out_dims} " + f"to be compatible with the structure of `output`. " + f"out_dims has structure {pytree.tree_flatten(out_dims)[1]} " + f"but output has structure {spec}. " + f"For more details, please see " + f"https://pytorch.org/docs/main/notes/extending.func.html" + ) + + for i, output in enumerate(flat_outputs): + if not isinstance(output, torch.Tensor): + result.append(output) + continue + if id(output) in unwrapped_input_to_orig_input: + result.append(unwrapped_input_to_orig_input[id(output)]) + continue + if out_dims_specified: + if flat_out_dims is None: + raise AssertionError( + "flat_out_dims must not be None when out_dims is specified" + ) + result.append(wrap_fn(output, flat_out_dims[i])) + else: + result.append(wrap_fn(output)) + + return pytree.tree_unflatten(result, spec) + + +# NOTE: [functorch vjp and autograd interaction] +# There's an edge case with the functorch vjp and autograd interaction +# that will eventually be fixed by mode-only functorch. +# The TL;DR is that there's no way to unwrap a dead GradTensorWrapper, +# so we (the framework) need to do it manually. Regular PyTorch operators +# automatically do so this is consistent. +# +# class MyExp(torch.autograd.Function): +# @staticmethod +# def forward(x): +# return x.exp() +# +# @staticmethod +# def setup_context(ctx, inputs, output): +# y = output +# ctx.save_for_backward(y) +# +# @staticmethod +# def backward(gy): +# y, = ctx.saved_tensors() +# return MyMul.apply(gy, y) +# +# x = torch.randn([], requires_grad=True) +# gy = torch.randn([], requires_grad=True) +# _, vjp_fn = vjp(MySin.apply, x) +# result = vjp_fn(gy) +# +# MyMul is an autograd.Function that is not shown here. +# It saves a `y` for backward (since gy requires grad). +# +# in vjp_fn(gy), we get: +# > MyMul.apply(gy, GradTensorWrapper(y, level=dead)) +# Because the y that is saved for backward by MyExp is a GradTensorWrapper +# but is now dead since we are outside the vjp context. +# +# PyTorch dispatcher operations, upon seeing a dead GradTensorWrapper, +# will automatically unwrap the GradTensorWrapper when applied. +# But since autograd.Function technically sits above the regular PyTorch +# dispatcher, it doesn't get this treatment. So we manually do +# the unwrapping to be consistent with regular PyTorch dispatcher operations. + + +class VmapInfo(NamedTuple): + batch_size: int + randomness: str + + +def has_overridden_vmap_rule( + autograd_function: type[torch.autograd.Function], +) -> bool: + return autograd_function.vmap is not torch.autograd.Function.vmap + + +def validate_vmap_returns_tuple_of_two_elements(result: Any) -> None: + base_error_msg = ( + "Expected the vmap staticmethod to have two returns, an output " + "and out_dims with pytree structure compatible with the output. " + ) + if not isinstance(result, tuple): + raise RuntimeError(base_error_msg + f"Got a {type(result)} instead") + if not len(result) == 2: + raise RuntimeError(base_error_msg + f"Got {len(result)} returns instead") + + +@custom_function_call.py_impl(TransformType.Vmap) +def custom_function_call_vmap( + interpreter: VmapInterpreter, + autograd_function: type[torch.autograd.Function], + *operands: Any, + **kwargs: Any, +) -> Any: + if any( + isinstance(val, torch.Tensor) + for val in torch.utils._pytree.tree_flatten(kwargs)[0] + ): + raise NotImplementedError( + f"Run vmap on autograd.Function with kwarg-only Tensor args. " + f"Please do not pass kwarg-only Tensors to autograd.Function. " + f"Got: {kwargs}" + ) + + if autograd_function.generate_vmap_rule: + if has_overridden_vmap_rule(autograd_function): + # TODO: Update link to stable once that's out + # https://github.com/pytorch/pytorch/issues/92029 + raise RuntimeError( + f"You tried to vmap over {autograd_function.__name__}, but " + f"it has both generate_vmap_rule=True and an overridden vmap " + f"staticmethod. Please set generate_vmap_rule=False or delete " + f"the overridden vmap staticmethod to avoid ambiguity. " + f"For more details, please see " + f"https://pytorch.org/docs/main/notes/extending.func.html" + ) + return custom_function_call_vmap_generate_rule( + interpreter, autograd_function, *operands + ) + + if not has_overridden_vmap_rule(autograd_function): + # TODO: Update link to stable once that's out + # https://github.com/pytorch/pytorch/issues/92029 + raise RuntimeError( + f"You tried to vmap over {autograd_function.__name__}, but " + f"it does not have vmap support. Please override and implement the " + f"vmap staticmethod or set generate_vmap_rule=True. " + f"For more details, please see " + f"https://pytorch.org/docs/main/notes/extending.func.html" + ) + + return custom_function_call_vmap_helper( + interpreter, autograd_function.vmap, autograd_function, *operands, **kwargs + ) + + +def custom_function_call_vmap_helper( + interpreter: VmapInterpreter, + vmap_function: Callable[..., Any], + op: Any, + *operands: Any, + **kwargs: Any, +) -> Any: + current_level = interpreter.level() + info = VmapInfo( + batch_size=interpreter.batch_size(), + randomness=interpreter.randomness(), + ) + # We're either in the autograd.Function case (vmap staticmethod) + # or the torch.library.register_vmap case. + autograd_function_case = isinstance(op, torch.autograd.function.FunctionMeta) + + def lower_to_next() -> Any: + if autograd_function_case: + return interpreter.lower() + else: + return torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.FuncTorchBatched) + ) + + unwrapped_operands, in_dims = unwrap_batched(operands, current_level) + # If none of the tensors are batched at the current level, then we skip the + # current level. This saves the user from needing to handle this case in + # their vmap staticmethod (and is consistent with our C++ batching rule API) + if pytree.tree_all(lambda dim: dim is None, in_dims): + with lower_to_next(): + if autograd_function_case: + return custom_function_call(op, *operands) + else: + return op(*operands, **kwargs) + + with lower_to_next(): + result = vmap_function(info, in_dims, *unwrapped_operands, **kwargs) + validate_vmap_returns_tuple_of_two_elements(result) + unwrapped_output, out_dims = result + + # See NOTE [mark_dirty object identity check] + def wrap_fn(output: torch.Tensor, out_dim: int | None) -> torch.Tensor: + return ( + output + if out_dim is None + else _add_batch_dim(output, out_dim, current_level) + ) + + return wrap_outputs_maintaining_identity( + unwrapped_output, unwrapped_operands, operands, wrap_fn, out_dims=out_dims + ) + + +def unpack_outputs(outputs: tuple[Any, ...]) -> tuple[Any, Any]: + out_dims = outputs[-1] + if isinstance(out_dims, tuple): + outputs = outputs[:-1] + else: + outputs = outputs[0] + return outputs, out_dims + + +def custom_function_call_vmap_generate_rule( + interpreter: VmapInterpreter, + autograd_function: type[torch.autograd.Function], + *operands: Any, +) -> Any: + unwrapped_operands, in_dims = unwrap_batched(operands, interpreter.level()) + vmapped_function = vmapify_autograd_function( + autograd_function, + in_dims, + interpreter.batch_size(), + interpreter.randomness(), + ) + with interpreter.lower(): + outputs = custom_function_call(vmapped_function, *unwrapped_operands) + + if not isinstance(outputs, tuple): + raise AssertionError(f"expected outputs to be a tuple, got {type(outputs)}") + outputs, out_dims = unpack_outputs(outputs) + return wrap_batched(outputs, out_dims, interpreter.level()) + + +@custom_function_call.py_impl(TransformType.Functionalize) +def custom_function_call_functionalize( + interpreter: FuncTorchInterpreter, + autograd_function: type[torch.autograd.Function], + generate_vmap_rule: bool, + *operands: Any, +) -> Any: + raise RuntimeError("NYI: Functionalize rule for custom_function_call") + + +def vmapify_autograd_function( + autograd_function: type[torch.autograd.Function], + in_dims: Any, + batch_size: int, + randomness: str, +) -> type[torch.autograd.Function]: + def forward(*operands: Any) -> Any: + outputs, out_dims = restore_vmap( + autograd_function.forward, in_dims, batch_size, randomness + )(*operands) + if isinstance(outputs, torch.Tensor): + return outputs, out_dims + else: + return *outputs, out_dims + + def setup_context(ctx: Any, inputs: Any, outputs: Any) -> None: + outputs, out_dims = unpack_outputs(outputs) + key = id(Generated) + + def inner(inputs: Any, outputs: Any) -> None: + # wrapped_ctx.save_for_backward will: + # - unwrap batchedtensors into (tensor, bdim) + # - save_for_backward(*unwrapped_tensors) + # - assign the bdims to wrapped_ctx._pt_saved_tensors_bdims + wrapped_ctx = CtxCustomSave(ctx, current_level()) + autograd_function.setup_context(wrapped_ctx, inputs, outputs) + + # input_shapes are used for reductify later to reduce expanded gradients + # to the correct shape. + # See NOTE: [Why can't we rely on autograd to reduce expanded gradients?] + # for more details + input_shapes = tuple( + inp.shape if isinstance(inp, torch.Tensor) else None for inp in inputs + ) + if not hasattr(ctx, "_pt_input_shapes"): + # pyrefly: ignore [implicit-any] + ctx._pt_input_shapes = {} + ctx._pt_input_shapes.update({key: input_shapes}) + + if not hasattr(ctx, "_pt_saved_tensors_bdims_stack"): + # pyrefly: ignore [implicit-any] + ctx._pt_saved_tensors_bdims_stack = {} + ctx._pt_saved_tensors_bdims_stack.update( + {key: (wrapped_ctx._pt_saved_tensors_bdims)} + ) + + # See NOTE: [Why do we need to run setup_context under a vmap?] + restore_vmap( + inner, + (in_dims, out_dims), + batch_size, + randomness, + )(inputs, outputs) + + if not hasattr(ctx, "_pt_out_dims"): + # pyrefly: ignore [implicit-any] + ctx._pt_out_dims = {} + ctx._pt_out_dims.update({key: out_dims}) + + def jvp(ctx: Any, *tangents: Any) -> Any: + key = id(Generated) + + def jvp_no_context(saved_tensors: Any, tangents: Any) -> Any: + wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors) + return autograd_function.jvp(wrapped_ctx, *tangents) + + tangent_in_dims = get_tangents_in_dims(in_dims, tangents) + out_tangents, out_tangents_dims = restore_vmap( + jvp_no_context, + (ctx._pt_saved_tensors_bdims_stack[key], tangent_in_dims), + batch_size, + randomness, + )(ctx.saved_tensors, tangents) + + result = reductify( + out_tangents, out_tangents_dims, ctx._pt_out_dims[key], batch_size + ) + if isinstance(result, torch.Tensor): + return result, None + else: + return *result, None + + def backward(ctx: Any, *grad_outputs: Any) -> Any: + key = id(Generated) + grad_outputs_ = grad_outputs[:-1] + grad_outputs_in_dims = ctx._pt_out_dims[key] + + if not isinstance(grad_outputs_in_dims, tuple): + grad_outputs_in_dims = (grad_outputs_in_dims,) + + grad_outputs_in_dims = tuple( + in_dim if grad_output is not None else None + for grad_output, in_dim in zip(grad_outputs_, grad_outputs_in_dims) + ) + + def backward_no_context(inputs: Any) -> Any: + saved_tensors, grad_outputs = inputs + wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors) + return autograd_function.backward(wrapped_ctx, *grad_outputs) + + grad_ins, grad_ins_dims = restore_vmap( + backward_no_context, + ((ctx._pt_saved_tensors_bdims_stack[key], grad_outputs_in_dims),), + batch_size, + randomness, + )((ctx.saved_tensors, grad_outputs_)) + result = reductify( + grad_ins, grad_ins_dims, in_dims, batch_size, ctx._pt_input_shapes[key] + ) + return result + + name = f"Vmapped{autograd_function.__name__}" + Generated = type( + name, + (torch.autograd.Function,), + { + "forward": staticmethod(forward), + "backward": staticmethod(backward), + "jvp": staticmethod(jvp), + "setup_context": staticmethod(setup_context), + "generate_vmap_rule": True, + }, + ) + + return Generated + + +# tangents might be None, so we need to replace +# the corresponding in_dims with None. +def get_tangents_in_dims(input_dims: Any, tangents: tuple[Any, ...]) -> Any: + flat_in_dims, spec = pytree.tree_flatten(input_dims) + flat_tangents = pytree.arg_tree_leaves(*tangents) + result = [ + None if tangent is None else in_dim + for in_dim, tangent in zip(flat_in_dims, flat_tangents) + ] + return pytree.tree_unflatten(result, spec) + + +# NOTE: [Why do we need to run setup_context under a vmap?] +# Consider the following autograd.Function +# +# class Sum(torch.autograd.Function): +# @staticmethod +# def forward(x): +# return x.sum() +# @staticmethod +# def setup_context(ctx, inputs, outputs): +# ctx.x_shape = inputs[0] +# @staticmethod +# def backward(ctx, gy): +# return gy.expand(ctx.x_shape) +# +# x = torch.randn(B, 4) +# in_dims = 0 +# vmap(Sum.apply, in_dims)(x) +# +# Let's assume for a moment that we didn't vmap setup_context in VmappedSum: +# +# class VmappedSum(torch.autograd.Function): +# @staticmethod +# def forward(x): +# return vmap(Sum.forward, in_dims)(x) +# +# @staticmethod +# def setup_context(ctx, inputs, outputs): +# Sum.setup_context(ctx, inputs, outputs) +# +# @staticmethod +# def backward(ctx, gy): +# def backward_no_context(gy): +# return gy.expand(ctx.x_shape) +# +# dims = (0,) +# gx = vmap(backward_no_context, dims)(gy) +# return gx +# +# We end up saving [B, 4] as x_shape. In the backward, gy has shape [B], +# and we're doing: +# +# def backward_no_context(gy): +# return gy.expand([B, 4]) +# +# gx = vmap(backward_no_context, dims)(gy: "Tensor[B]") +# +# This gives us the wrong result (gx has shape [B, B, 4], but it should +# have shape [4]). Performing vmap over setup_context means the shape +# saved has shape [4] and leads to a correct result shape for gx. + + +# Wraps a ctx object. Forwards all attr accesses to the underlying object +# except for the attrs in _pt_attrs +class WrappedCtx: + _pt_reserved_attrs: tuple[str, ...] = ("_pt_reserved_attrs", "_pt_inner_ctx") + + def __init__(self, ctx: Any) -> None: + if not isinstance(ctx, WrappedCtx): + reserved_attrs = type(self)._pt_reserved_attrs + for name in reserved_attrs: + if not hasattr(ctx, name): + continue + raise RuntimeError( + f"PyTorch reserves the {reserved_attrs} field on ctx. " + "Please name your fields on ctx something else to avoid name " + "collision." + ) + self._pt_inner_ctx = ctx + + def __getattr__(self, name: str) -> Any: + return getattr(self._pt_inner_ctx, name) + + def __setattr__(self, name: str, value: Any) -> None: + if name in type(self)._pt_reserved_attrs: + self.__dict__[name] = value + return + return setattr(self._pt_inner_ctx, name, value) + + +# Wraps ctx to create a new ctx object that overrides saved_tensors. +class CtxWithSavedTensors(WrappedCtx): + _pt_reserved_attrs = ("_pt_new_saved_tensors", *WrappedCtx._pt_reserved_attrs) + + def __init__(self, ctx: Any, new_saved_tensors: Sequence[torch.Tensor]) -> None: + super().__init__(ctx) + self._pt_new_saved_tensors = new_saved_tensors + + @property + def saved_tensors(self) -> Sequence[torch.Tensor]: + return self._pt_new_saved_tensors + + +class CtxCustomSave(WrappedCtx): + _pt_reserved_attrs = ( + "_pt_saved_tensors_bdims", + "_pt_current_level", + *WrappedCtx._pt_reserved_attrs, + ) + + def __init__(self, ctx: Any, current_level: int) -> None: + super().__init__(ctx) + self._pt_saved_tensors_bdims: tuple[Any, ...] = () + self._pt_current_level = current_level + + def save_for_backward(self, *tensors: torch.Tensor) -> None: + unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level) + self._pt_inner_ctx.save_for_backward(*unwrapped_tensors) + self._pt_saved_tensors_bdims = bdims + + def save_for_forward(self, *tensors: torch.Tensor) -> None: + unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level) + self._pt_inner_ctx.save_for_forward(*unwrapped_tensors) + self._pt_saved_tensors_bdims = bdims + + +def reductify( + grad_input: torch.Tensor | tuple[torch.Tensor, ...], + grad_input_bdim: int | tuple[int, ...], + input_bdim: int | tuple[int, ...], + batch_size: int, + target_shape_without_bdim_to_reduce_to: Any = None, +) -> tuple[Any, ...]: + if not isinstance(grad_input, tuple): + grad_input = (grad_input,) + if not isinstance(grad_input_bdim, tuple): + grad_input_bdim = (grad_input_bdim,) + if not isinstance(input_bdim, tuple): + input_bdim = (input_bdim,) + + if target_shape_without_bdim_to_reduce_to is None: + target_shape_without_bdim_to_reduce_to = len(grad_input) * (None,) + result = tuple( + reductify_leaf(gi, gi_bdim, i_bdim, batch_size, maybe_ishape) + for gi, gi_bdim, i_bdim, maybe_ishape in zip( + grad_input, + grad_input_bdim, + input_bdim, + target_shape_without_bdim_to_reduce_to, + ) + ) + return result + + +def reductify_leaf( + grad_input: torch.Tensor | None, + grad_input_bdim: int | None, + input_bdim: int | None, + batch_size: int, + target_shape_without_bdim_to_reduce_to: Any = None, +) -> torch.Tensor | None: + if grad_input is None: + return None + + if grad_input_bdim is None and input_bdim is None: + return grad_input + + if grad_input_bdim is not None and input_bdim is None: + return grad_input.sum(grad_input_bdim) + + # NOTE: [Why can't we rely on autograd to reduce expanded gradients?] + # For reverse-mode AD, + # given a grad_input and input, it is valid for the user to return a + # grad_input that has a broadcasted shape when compared to the input. + # In this situation, autograd automatically reduces the grad_input to + # the shape of the input. + # + # However, when input_bdim is not None, we have problems. + # + # [example 1] + # grad_input: Tensor[3, 4], input: Tensor[B, 4] + # We can expand grad_input to Tensor[B, 3, 4], but that isn't broadcastable + # from [B, 4]. + # + # [example 2] + # grad_input: Tensor[3, B, 4], input: Tensor[B, 4] + # We can swizzle grad_input to Tensor[B, 3, 4], but that isn't broadcastable + # from [B, 4]. + # + # This means that we need to also reduce the grad_input to the shape of the + # input. This behavior is controlled by the `target_shape_without_bdim_to_reduce_to` flag; + # if not-None then we do the reducing manually, otherwise, we do not do a reduction. + if input_bdim is None: + raise AssertionError("input_bdim must not be None") + + if grad_input_bdim is None: + grad_input = grad_input.unsqueeze(input_bdim) + new_shape = list(grad_input.shape) + new_shape[input_bdim] = batch_size + grad_input = grad_input.expand(new_shape) + grad_input_bdim = input_bdim + + if target_shape_without_bdim_to_reduce_to is not None: + return vmap( + torch.Tensor.sum_to_size, + in_dims=(grad_input_bdim, None), + out_dims=input_bdim, + )(grad_input, target_shape_without_bdim_to_reduce_to) + + if input_bdim != grad_input_bdim: + grad_input = grad_input.movedim(grad_input_bdim, input_bdim) + return grad_input + + +def autograd_function_forward_rewritten( + original_forward: Callable[_P, _R], + original_setup_context: Callable[..., Any], +) -> Callable[..., _R]: + def new_forward(ctx: Any, *args: _P.args, **kwargs: _P.kwargs) -> _R: + output = original_forward(*args, **kwargs) + original_setup_context(ctx, args, output) + return output + + return new_forward + + +class AutogradFunctionApply(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("autograd_function_apply") + + def __call__( + self, + fwd: torch.fx.GraphModule, + bwd: torch.fx.GraphModule, + *fwd_args: Any, + **fwd_kwargs: Any, + ) -> Any: + saved_values: Iterable[Any] | None = None + dirty_idx = fwd_kwargs.get("dirty_idx", []) + dirty_idx_set = set(dirty_idx) + non_differentiable_idx = fwd_kwargs["non_differentiable_idx"] + saved_for_backward_idx = fwd_kwargs["saved_for_backward_idx"] + + class ApplyTemplate(torch.autograd.Function): + @staticmethod + def forward(*args: Any, **kwargs: Any) -> Any: + nonlocal saved_values + + # The Interpreter here is required to propagate metadata + # from the dynamo graph body to the local_map graph body. + # This is required for fx_traceback.annotate for work. + output, saved_values = torch.fx.Interpreter(fwd).run(*args) + + # See Note [Activations with no version counter checks in eager] + # Mark tensors that came from ctx.save_for_backward with metadata. + # This allows AOT autograd to distinguish between tensors saved via + # save_for_backward vs those stashed directly on ctx (e.g., ctx.x = x). + from torch.fx.experimental.proxy_tensor import _get_proxies + + for idx, t in enumerate(saved_values): + if idx not in saved_for_backward_idx: + for proxy in _get_proxies(t): + proxy.node.meta["saved_tensor_with_no_vc_check"] = True + + return output + + @staticmethod + def setup_context(ctx: Any, inputs: tuple[Any, ...], output: Any) -> None: + def selected_outputs(idx: Iterable[int]) -> list[Any]: + idx_set = set(idx) + if isinstance(output, (tuple, list)): + return [x for i, x in enumerate(output) if i in idx_set] + return [output] if 0 in idx_set else [] + + # If users call ctx.mark_dirty() in the original fwd function. + if len(dirty_idx) > 0: + ctx.mark_dirty(*selected_outputs(dirty_idx_set)) + + # If users call ctx.mark_non_differentiable() in the original fwd function. + if len(non_differentiable_idx) > 0: + ctx.mark_non_differentiable( + *selected_outputs(non_differentiable_idx) + ) + + @staticmethod + def backward(ctx: Any, *grad: Any) -> Any: + # The Interpreter here is required to propagate metadata + # from the dynamo graph body to the local_map graph body. + # This is required for fx_traceback.annotate for work. + + if saved_values is None: + raise AssertionError("saved_values must not be None") + return torch.fx.Interpreter(bwd).run(*grad, *saved_values) + + return ApplyTemplate.apply(*fwd_args) + + +autograd_function_apply = AutogradFunctionApply() + + +class DynamoAutogradFunctionTraceHelper: + @staticmethod + def fwd_trace_helper(orig_fwd: Callable[_P, Any]) -> Callable[_P, Any]: + # autograd.Function forward does more than just running the forward method. Most + # of this logic is in C++. Here, we rewrite that functionality in python and let + # Dynamo trace it. + def inner(*args: _P.args, **kwargs: _P.kwargs) -> Any: + with torch.no_grad(): + outs = orig_fwd(*args, **kwargs) + + ctx = args[0] + dirty_tensors = getattr(ctx, "dirty_tensors", None) + + def is_dirty_tensor(tensor: torch.Tensor) -> bool: + if dirty_tensors is None: + return False + return any( + tensor is dirty_tensor + for dirty_tensor in dirty_tensors + if isinstance(dirty_tensor, torch.Tensor) + ) + + def is_tensor_arg(tensor: torch.Tensor) -> bool: + return any( + arg is tensor for arg in args if isinstance(arg, torch.Tensor) + ) + + # Handle the case where if the input is passed on directly to the output, we call view_as + # Refer to https://github.com/pytorch/pytorch/blob/main/torch/csrc/autograd/custom_function.cpp#L254 + if isinstance(outs, torch.Tensor): + if is_tensor_arg(outs) and not is_dirty_tensor(outs): + return outs.view_as(outs) + else: + return outs + + new_outs = [] + for out in outs: + if isinstance(out, torch.Tensor): + if is_tensor_arg(out) and not is_dirty_tensor(out): + new_outs.append(out.view_as(out)) + else: + new_outs.append(out) + else: + new_outs.append(out) + return tuple(new_outs) + + # TODO - there is missing functionality here, where + # autograd.Function overwrites the requires_grad_ of the output + # tensors depending on the `mark_non_differentiable`. Currently, + # this is handled hackily in Dynamo, where we just overwrite the + # variable trackers requires_grad. Refer to the function - + # overwrite_tensor_vt_requires_grad + + return inner diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/batch_norm_replacement.py b/.venv/lib/python3.12/site-packages/torch/_functorch/batch_norm_replacement.py new file mode 100644 index 0000000000000000000000000000000000000000..77aa9b9c2d7c78647d2c850b550754e43c4fe592 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/batch_norm_replacement.py @@ -0,0 +1,27 @@ +import torch.nn as nn +from torch._functorch.utils import exposed_in + + +def batch_norm_without_running_stats(module: nn.Module) -> None: + if ( + isinstance(module, nn.modules.batchnorm._BatchNorm) + and module.track_running_stats + ): + module.running_mean = None + module.running_var = None + module.num_batches_tracked = None + module.track_running_stats = False + + +@exposed_in("torch.func") +def replace_all_batch_norm_modules_(root: nn.Module) -> nn.Module: + """ + In place updates :attr:`root` by setting the ``running_mean`` and ``running_var`` to be None and + setting track_running_stats to be False for any nn.BatchNorm module in :attr:`root` + """ + # base case + batch_norm_without_running_stats(root) + + for obj in root.modules(): + batch_norm_without_running_stats(obj) + return root diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/benchmark_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/benchmark_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4a9f003aab1ece4114ee999ae3a17089bd04c436 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/benchmark_utils.py @@ -0,0 +1,245 @@ +from __future__ import annotations + +import contextlib +import json +import operator +import os +import time +from contextlib import AbstractContextManager +from typing import Any, TYPE_CHECKING +from typing_extensions import TypeVar + +import torch +from torch.profiler import profile, ProfilerActivity + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +_R = TypeVar("_R") + + +def synchronize() -> None: + pass + + +def dump_chrome_trace( + f: Callable[[tuple[Any, ...]], _R], + input_: tuple[Any, ...], + trace_filename: str, + optimize_ctx: AbstractContextManager[Any], + activities: Sequence[ProfilerActivity], + num_runs: int = 1, + devices: list[str] | None = None, + kwargs_for_f: dict[str, Any] | None = None, + kwargs_for_profiler: dict[str, Any] | None = None, +) -> float: + """ + Output the chrome trace of running f(input_, **kwargs_for_f) with [optimize_ctx] + [num_runs] times to [trace_filename]. + + [activities] are the activities that the profiler will record, e.g. ProfilerActivity.CUDA. + Return total runtime without the profiler + + Outputs to trace_filename + """ + + if devices is None: + devices = ["cuda"] + + global synchronize + if devices != ["cpu"] and torch.accelerator.is_available(): + synchronize = torch.accelerator.synchronize + + if kwargs_for_f is None: + kwargs_for_f = {} + if kwargs_for_profiler is None: + kwargs_for_profiler = {} + + with optimize_ctx: + torch.manual_seed(1337) + for _ in range(5): # warmup runs + f(input_, **kwargs_for_f) + synchronize() + torch.manual_seed(1337) + t0 = time.perf_counter() + for _ in range(num_runs): + f(input_, **kwargs_for_f) + synchronize() + t1 = time.perf_counter() + timing = t1 - t0 + + with profile(activities=activities, **kwargs_for_profiler) as prof: + with optimize_ctx: + synchronize() + torch.manual_seed(1337) + for _ in range(num_runs): + f(input_, **kwargs_for_f) + synchronize() + prof.export_chrome_trace(trace_filename) + + return timing + + +def get_chrome_trace_events(filename: str) -> list[dict[str, Any]]: + with open(filename) as f: + data = json.load(f) + events = data["traceEvents"] + return events + + +def is_gpu_compute_event(event: dict[str, Any]) -> bool: + global gpu_pids + return ( + "pid" in event + and event["pid"] in gpu_pids + and "ph" in event + and event["ph"] == "X" + ) + + +def get_sorted_gpu_events(events: list[dict[str, Any]]) -> list[dict[str, Any]]: + sorted_gpu_events: list[dict[str, Any]] = [] + for event in events: + if not is_gpu_compute_event(event): + continue + sorted_gpu_events.append(event) + return sorted(sorted_gpu_events, key=operator.itemgetter("ts")) + + +def get_duration(sorted_gpu_events: list[dict[str, Any]]) -> int: + if len(sorted_gpu_events) == 0: + return 0 + event = sorted_gpu_events[0] + current_end_time = event["ts"] + event["dur"] + total_duration = event["dur"] + for event in sorted_gpu_events[1:]: + start_time = max(event["ts"], current_end_time) + end_time = event["ts"] + event["dur"] + total_duration = total_duration + max(end_time - start_time, 0) + current_end_time = max(current_end_time, end_time) + return total_duration + + +def get_sorted_gpu_mm_conv_events(events: list[dict[str, Any]]) -> list[dict[str, Any]]: + def is_mm_conv_event(event: dict[str, Any]) -> bool: + return "name" in event and ( + "gemm" in event["name"] + or "conv" in event["name"] + or "cutlass" in event["name"] + or "wgrad" in event["name"] + ) + + gpu_events = get_sorted_gpu_events(events) + sorted_events: list[dict[str, Any]] = [] + for event in gpu_events: + if not is_mm_conv_event(event): + continue + sorted_events.append(event) + return sorted_events + + +gpu_pids: list[Any] = [] + + +def compute_utilization(filename: str, total_length: float) -> tuple[float, float]: + """ + Process the chrome traces outputs by the pytorch profiler to compute GPU Utilization + and percent of times spent on matmul and convolution + + Args: + filename(str): Name of chrome traces file produced by pytorch profiler + + total_length(float): total length of the process without profiler in second + + Return: + tuple: (GPU Utilization, percent of time spent on matmul and convolution) + """ + events = get_chrome_trace_events(filename) + + # get pids of GPU events + global gpu_pids + gpu_pids = [] + for event in events: + if "name" not in event: + continue + if event["name"] == "process_labels" and "GPU" in event["args"]["labels"]: + gpu_pids.append(event["pid"]) + + total_length = total_length * 1e6 + sorted_gpu_events = get_sorted_gpu_events(events) + utilization = get_duration(sorted_gpu_events) / total_length + + sorted_gpu_mm_conv_events = get_sorted_gpu_mm_conv_events(events) + mm_conv_utilization = get_duration(sorted_gpu_mm_conv_events) / total_length + + return utilization, mm_conv_utilization + + +def benchmark_utilization( + f: Callable[[tuple[Any, ...]], _R], + input_: tuple[Any, ...], + trace_folder: str, + optimize_ctx: AbstractContextManager[Any] | None = None, + trace_file_name: str = "tmp_chrome_trace", + num_runs: int = 1, +) -> tuple[float, float]: + """ + Benchmark the GPU Utilization and percent of time spent on matmul and convolution operations of + running f(input_, **kwargs_for_f) with [optimize_ctx] [num_runs] times. + It will produce a chrome trace file in trace_folder/trace_file_name.json + + Example: + + ``` + def f(a): + return a.sum() + + + a = torch.rand(2**20, device="cuda") + utilization, mm_conv_utilization = benchmark_utilization( + f, a, "tmp", trace_file_name="tmp_chrome_trace" + ) + ``` + + Args: + f: function to benchmark + + input_: input to :attr:`f` + + trace_folder: name of the folder to store the chrome trace + + optimize_ctx: the context in which f will run + + trace_file_name: name of the dumped chrome trace file, default to "tmp_chrome_trace" + + num_runs: number of times to run f, excluding the warm-up runs, default to 1. + + Return: + tuple: (GPU Utilization, percent of time spent on matmul and convolution) + + """ + isExist = os.path.exists(trace_folder) + if not isExist: + os.makedirs(trace_folder) + print("create folder " + trace_folder) + + if optimize_ctx is None: + optimize_ctx = contextlib.nullcontext() + + chrome_trace_file_name = os.path.join(trace_folder, trace_file_name + ".json") + total_length = dump_chrome_trace( + f, + input_, + chrome_trace_file_name, + optimize_ctx, + [ProfilerActivity.CUDA], + num_runs=num_runs, + devices=["cuda"], + ) + utilization, mm_conv_utilization = compute_utilization( + chrome_trace_file_name, total_length + ) + + return utilization, mm_conv_utilization diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/compile_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/compile_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..732188f9afdf7b956b84a6247e94d002014512ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/compile_utils.py @@ -0,0 +1,306 @@ +from __future__ import annotations + +import dataclasses +import operator +import struct +from typing import Any, TYPE_CHECKING + +import sympy + +import torch +import torch.fx as fx +from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils import _pytree as pytree +from torch.utils._pytree import tree_flatten + + +if TYPE_CHECKING: + from collections.abc import Callable, Hashable + + from torch._ops import OpOverloadPacket + from torch.utils._pytree import TreeSpec + +aten = torch.ops.aten + + +@dataclasses.dataclass(frozen=True) +class _ScalarKey: + tag: str + bits: bytes + + +def _normalize_cse_arg(val: Any) -> Any: + # Python float hash/eq is not value-identity: nan != nan (hash(nan) is + # id-based) while -0.0 == 0.0 and hashes equal. Key by bit pattern instead. + if type(val) is float: + return _ScalarKey("float", struct.pack(">d", val)) + if type(val) is complex: + return _ScalarKey("complex", struct.pack(">dd", val.real, val.imag)) + return val + + +def get_aten_target(node: fx.Node) -> OpOverloadPacket | Callable[..., Any] | str: + if hasattr(node.target, "overloadpacket"): + return node.target.overloadpacket + return node.target + + +rand_ops = [ + aten.dropout, + aten._fused_dropout, + aten._standard_gamma, + aten.bernoulli, + aten.multinomial, + aten.native_dropout, + aten.normal, + aten.poisson, + aten.binomial, + aten.rrelu, + aten.rand_like, + aten.rand, + aten.randint, + aten.randn, + aten.randperm, +] + + +# return a new copy of torch.fx.graph.Graph with CSE applied to the input graph +def fx_graph_cse( + fx_g: torch.fx.graph.Graph, + extra_node_key: Callable[[fx.Node], Hashable] | None = None, +) -> fx.Graph: + new_graph = fx.Graph() + env: dict[ + fx.Node, fx.Node + ] = {} # map from node in the old graph to node in the new graph + hash_env: dict[ + tuple[Any, Hashable | None, int], fx.Node + ] = {} # map from hash to a node in the new graph + token_map: dict[ + tuple[Any, Hashable | None, int], dict[str, Any] + ] = {} # map from hash to token + + from torch._inductor.pattern_matcher import ( + compute_mutation_region_ids, + same_mutation_regions, + ) + + compute_mutation_region_ids(fx_g) # type: ignore[arg-type] + + # Make a set of separate storages returned from the output, which will be preserved + # when pruning. This prevents us from deduplicating returned tensors which have + # experienced identical operations, but are separate data structures in eager mode. + output_node: fx.Node = list(fx_g.nodes)[-1] + if output_node.op != "output": + raise AssertionError( + f"expected output_node.op to be 'output', got '{output_node.op}'" + ) + + def checkable_node(node: fx.Node) -> bool: + """We can evaluate only nodes that represent tensors with defined storage.""" + if "val" not in node.meta or not isinstance(node.meta["val"], torch.Tensor): + return False + + try: + node.meta["val"].untyped_storage() + except NotImplementedError: + return False + + return True + + def custom_context_key(node: fx.Node) -> tuple[int, int | None, int | None]: + custom = node.meta.get("custom", {}) + return ( + custom.get("stream", 0), + custom.get("mempool"), + custom.get("mempool_device"), + ) + + output_storages = { + StorageWeakRef(n.meta["val"].untyped_storage()) + for n in output_node.all_input_nodes + if checkable_node(n) + } + nodes_that_alias_outputs = { + n + for n in fx_g.nodes + if checkable_node(n) + and StorageWeakRef(n.meta["val"].untyped_storage()) in output_storages + } + + # A node used as the mutable base of a functional-wrapper op is a distinct + # mutable buffer. Two identical factory ops feeding distinct bases (e.g. the + # forward and backward ``aten.full`` from a pair of ``ones_like`` calls) must + # not be CSE-merged, or the later mutation aliases a buffer that still has a + # live downstream view and reinplacing fails (mirrors the aten.empty + # exclusion below). See pytorch/pytorch#170160. + from torch._higher_order_ops.auto_functionalize import get_mutable_args + from torch._higher_order_ops.triton_kernel_wrap import ( + triton_kernel_wrapper_functional, + ) + + def _add_base(node: Any, bases: set[fx.Node]) -> None: + for b in node if isinstance(node, (list, tuple)) else (node,): + if isinstance(b, fx.Node): + bases.add(b) + + nodes_used_as_mutation_base: set[fx.Node] = set() + for n in fx_g.find_nodes( + op="call_function", target=torch.ops.higher_order.auto_functionalized_v2 + ): + # v2 lists its mutable buffers explicitly in ``_all_bases``. + for base in n.kwargs.get("_all_bases", ()): + _add_base(base, nodes_used_as_mutation_base) + for n in fx_g.find_nodes( + op="call_function", target=torch.ops.higher_order.auto_functionalized + ): + # v1 has no ``_all_bases``; the mutated tensors are the args named by the + # wrapped op's schema (``_mutable_op`` is the first positional). + mutable_op = n.args[0] + mutable_args_names, _ = get_mutable_args(mutable_op) + for name in mutable_args_names: + _add_base(n.kwargs.get(name), nodes_used_as_mutation_base) + for n in fx_g.find_nodes( + op="call_function", target=triton_kernel_wrapper_functional + ): + inner_kwargs = n.kwargs.get("kwargs", {}) + for name in n.kwargs.get("tensors_to_clone", ()): + _add_base(inner_kwargs.get(name), nodes_used_as_mutation_base) + + for n in fx_g.nodes: + # The placeholder, output, and get_attr nodes are copied to the new graph without change + # do not CSE away random operations + if ( + n.op == "placeholder" + or n.op == "output" + or n.op == "get_attr" + or n.is_impure() + or get_aten_target(n) in rand_ops + # aten.empty is non-deterministic, so don't CSE it. + # Also, aten.empty is almost always fusible into its consumer, + # so it's not worth CSEing. + or get_aten_target(n) is aten.empty + or n in nodes_that_alias_outputs + # Keep distinct functional-wrapper mutation bases independent. + or n in nodes_used_as_mutation_base + # This CSE pass currently doesn't handle re-propagation of unbacked + # meta where it'll sometimes eliminate a _local_scalar_dense but not + # replace the meta of downstream users. eg. one bug we've seen is: + # + # _local_scalar_dense_11: "Sym(u14)" = torch.ops.aten._local_scalar_dense.default(select_10); + # sym_sum_2: "Sym(u19 + u20 + u21)" = torch.sym_sum((_local_scalar_dense_11, _local_scalar_dense_12, _local_scalar_dense_13)) + # + # Notice how _local_scalar_dense_11 is u14 but sym_sum_2's meta is incorrectly the old + # pre-cse value of u19. + or ( + "val" in n.meta + and isinstance(n.meta["val"], sympy.Symbol) + and free_unbacked_symbols(n.meta["val"]) + ) + ): + new_node = new_graph.node_copy(n, lambda x: env[x]) + env[n] = new_node + else: # n.op == 'call_function', should never see n.op == 'call_module' or 'call_method' + # substitute args and kwargs members to their mapping in env if exists + # specs can be used to reconstruct nested list/dictionaries + def substitute( + arg_list: list[Any] | tuple[Any, ...], + ) -> tuple[tuple[Any, ...], TreeSpec]: + arg_list, spec = tree_flatten(arg_list) + for i in range(len(arg_list)): + v = arg_list[i] + if isinstance(v, torch.fx.node.Node) and v in env: + arg_list[i] = env[v] + if isinstance(v, (torch.SymBool, torch.SymInt, torch.SymFloat)): + arg_list[i] = v.node + arg_list[i] = _normalize_cse_arg(arg_list[i]) + return tuple(arg_list), spec + + args, args_spec = substitute(n.args) + kwargs, kwargs_spec = substitute(n.kwargs) + + # each token corresponds to a unique node + # nodes with the same token can be substituted + extra_key = extra_node_key(n) if extra_node_key is not None else None + token = { + "target": n.target, + "extra_key": extra_key, + "args": args, + "args_spec": args_spec, + "kwargs": kwargs, + "kwargs_spec": kwargs_spec, + "custom_context": custom_context_key(n), + } + + # hash substituted args to a number, do not hash specs because specs are not hashable + # We need to add type into hash to avoid situations like: + # hash((primals_2, 1.0)) == hash((primals_2, 1)) + hash_arg = hash( + (tuple((a, type(a)) for a in args), tuple((a, type(a)) for a in kwargs)) + ) + hash_val = (n.target, extra_key, hash_arg) + + # check if a node has a substitute and can be eliminated + hash_val_in_hash_env = hash_val in hash_env + overwrite_due_to_mutation = False + if hash_val_in_hash_env and token_map[hash_val] == token: + duplicate_n_prev = hash_env[hash_val] + if same_mutation_regions(n, duplicate_n_prev): + env[n] = duplicate_n_prev + continue + else: + # any futures duplicates should replace with n, not duplicate_n_prev + overwrite_due_to_mutation = True + + new_node = new_graph.node_copy(n, lambda x: env[x]) + env[n] = new_node + if overwrite_due_to_mutation or not hash_val_in_hash_env: + hash_env[hash_val] = new_node + token_map[hash_val] = token + + return new_graph + + +def raise_getitems(gm: fx.GraphModule) -> fx.GraphModule: + # Pre-create a list of nodes to iterate over, as modifying the node order + # during the loop can lead to infinite loops if not handled properly. + getitem_nodes = list( + gm.graph.find_nodes(op="call_function", target=operator.getitem) + ) + + # loop through getitem nodes in the graph and raise them to the parent node + # in reverse order to preserve their original relative order + for node in reversed(getitem_nodes): + if len(node.all_input_nodes) != 1: + raise AssertionError( + f"expected node {node.name} to have 1 input node, got {len(node.all_input_nodes)}" + ) + parent = node.all_input_nodes[0] + parent.append(node) + + gm.recompile() + return gm + + +def strip_overloads(gm: fx.GraphModule) -> None: + """ + Modifies the target of graph nodes in :attr:`gm` to strip overloads. + + Args: + gm(fx.GraphModule): The input Fx graph module to be modified + """ + for node in gm.graph.nodes: + if isinstance(node.target, torch._ops.OpOverload): + node.target = node.target.overloadpacket + gm.recompile() + + +def get_placeholders(graph: fx.Graph) -> list[Any]: + return graph.find_nodes(op="placeholder") + + +def get_outputs(graph: fx.Graph) -> list[fx.Node]: + for node in graph.find_nodes(op="output"): + return pytree.tree_leaves(node.args[0]) + raise AssertionError("No output node found") diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/compilers.py b/.venv/lib/python3.12/site-packages/torch/_functorch/compilers.py new file mode 100644 index 0000000000000000000000000000000000000000..2858fedce8b159d082c388c3a2981b2384ac69d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/compilers.py @@ -0,0 +1,505 @@ +from __future__ import annotations + +import copy +import logging +import os +import pickle +import random +from contextlib import contextmanager +from functools import partial +from typing import Any, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +import sympy + +import torch +import torch.fx as fx +import torch.nn as nn +import torch.utils._pytree as pytree +from torch import SymInt +from torch._decomp import get_decompositions +from torch.fx.experimental.symbolic_shapes import bind_symbols + +from .aot_autograd import aot_function, aot_module, make_boxed_compiler +from .compile_utils import strip_overloads +from .partitioners import ( + default_partition, + draw_graph, + min_cut_rematerialization_partition, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Sequence + + from torch.fx.node import Node + from torch.types import IntLikeType + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +log = logging.getLogger(__name__) + + +# These canonicalizations are needed here (and not decompositions), as the ops +# we're trying to canonicalize to CompositeImplicitAutograd. +def _canonicalize(fx_g: fx.GraphModule) -> fx.GraphModule: + for node in fx_g.graph.find_nodes( + op="call_function", target=torch.ops.aten._to_copy + ): + node.target = torch.ops.aten.to + fx_g.recompile() + return fx_g + + +@contextmanager +def _disable_jit_autocast() -> Generator[None, None, None]: + # pyrefly: ignore [missing-attribute] + old_jit_autocast_flag = torch._C._jit_set_autocast_mode(False) + try: + yield + finally: + # pyrefly: ignore [missing-attribute] + torch._C._jit_set_autocast_mode(old_jit_autocast_flag) + + +@make_boxed_compiler +def ts_compile(fx_g: fx.GraphModule, inps: Sequence[Any]) -> torch.jit.ScriptModule: + """ + Compiles the :attr:`fx_g` with Torchscript compiler. + + .. warning:: + This API is experimental and likely to change. + + Args: + fx_g(fx.GraphModule): The input Fx graph module to be compiled. + + Returns: + Torch scripted model. + """ + + from torch.fx._lazy_graph_module import _unwrap_lazy_graph_module + + fx_g = _unwrap_lazy_graph_module(fx_g) + + with _disable_jit_autocast(): + strip_overloads(fx_g) + + for node in fx_g.graph.find_nodes( + op="call_function", target=torch.ops.aten._to_copy + ): + if len(node.args) == 1 and len(node.kwargs) == 1 and "dtype" in node.kwargs: + node.target = torch.ops.aten.to + + for node in fx_g.graph.nodes: + new_kwargs = {} + for k, v in node.kwargs.items(): + if isinstance(v, torch.device): + v = v.type + new_kwargs[k] = v + node.kwargs = new_kwargs + + fx_g.graph.lint() + + fx_g.recompile() + + f = torch.jit.script(fx_g) + + # pyrefly: ignore [missing-attribute] + torch._C._jit_pass_remove_mutation(f.graph) + + f = torch.jit.freeze(f.eval()) + f = torch.jit.optimize_for_inference(f) + if not any(torch._subclasses.fake_tensor.is_fake_tensor(t) for t in inps): + f(*inps) + return f + + +def _draw_graph_compile( + fx_g: fx.GraphModule, _: Any, name: str, clear_meta: bool = True +) -> fx.GraphModule: + print(fx_g.code) + draw_graph(fx_g, name, clear_meta=clear_meta) + return fx_g + + +def draw_graph_compile( + name: str, +) -> Callable[[fx.GraphModule, list[Any]], fx.GraphModule]: + return make_boxed_compiler(partial(_draw_graph_compile, name=name)) + + +@make_boxed_compiler +def nop(fx_g: fx.GraphModule, _: Any) -> fx.GraphModule: + """ + Returns the :attr:`fx_g` Fx graph module as it is. This is a no-op compiler + and can be used to check accuracy. + + .. warning:: + This API is experimental and likely to change. + + """ + return fx_g + + +class DebugInterpreter(fx.Interpreter): + def run( + self, + *args: Any, + initial_env: dict[Node, Any] | None = None, + enable_io_processing: bool = True, + ) -> Any: + self.symbol_mapping = bind_symbols( + # pyrefly: ignore[bad-argument-type] + self.module, + *args, + ) + return super().run( + *args, initial_env=initial_env, enable_io_processing=enable_io_processing + ) + + def run_node(self, n: Node) -> Any: + def subst_symint(ni: IntLikeType) -> int: + if not isinstance(ni, SymInt): + return ni + r = sympy.expand(ni.node.expr.xreplace(self.symbol_mapping)) + if not r.is_number: + raise AssertionError(f"expected r to be a number, got {r}") + return int(r) + + def subst_symint_tuple(nis: tuple[IntLikeType, ...]) -> tuple[int, ...]: + return tuple(subst_symint(ni) for ni in nis) + + def check_significant_strides(a: torch.Tensor, b: torch.Tensor) -> bool: + if subst_symint(a.numel()) > 0: + for idx in range(a.ndim): + if ( + subst_symint(a.stride(idx)) != b.stride(idx) + and subst_symint(a.size(idx)) > 1 + ): + return False + return True + + def check(nv: torch.Tensor, rv: torch.Tensor, desc: Callable[[], str]) -> None: + if not callable(desc): + raise AssertionError(f"expected desc to be callable, got {type(desc)}") + if nv.dtype != rv.dtype: + raise AssertionError(f"{desc()}: {nv.dtype} != {rv.dtype}") + if subst_symint_tuple(nv.size()) != rv.size(): + raise AssertionError( + f"{desc()}: {nv.size()} aka {subst_symint_tuple(nv.size())} != {rv.size()}" + ) + same_strides = check_significant_strides(nv, rv) + if not same_strides: + raise AssertionError( + f"{desc()}: {nv.stride()} aka {subst_symint_tuple(nv.stride())} != {rv.stride()}" + ) + + r = super().run_node(n) + if "val" in n.meta: + n_vals, _n_spec = pytree.tree_flatten(n.meta["val"]) + r_vals, _r_spec = pytree.tree_flatten(r) + # TODO: There is some sort of problem where we record that an + # operator returned a tuple/list, and then later it turns out the + # real version of the operator returned a list/tuple. Need to + # figure out what's actually going on here, the error itself is + # harmless enough as we only getitem out the outputs. + # assert n_spec == r_spec, f"{n_spec} != {r_spec}" + if len(n_vals) != len(r_vals): + raise AssertionError(f"{len(n_vals)} != {len(r_vals)}") + for i, nv, rv in zip(range(len(n_vals)), n_vals, r_vals): + if not isinstance(rv, torch.Tensor): + continue + check(nv, rv, lambda: f"output {i} where {self.symbol_mapping}") + return r + + +@make_boxed_compiler +def debug_nop( + fx_g: fx.GraphModule, _: Any +) -> Callable[[DebugInterpreter, Any, dict[Node, Any] | None, bool], Any]: + """ + Returns a (slow) interpreter over the FX graph module that also checks + various debugging properties (e.g., that tracing strides matched real + strides.) + """ + return DebugInterpreter(fx_g).run + + +@make_boxed_compiler +def simple_ts_compile(fx_g: fx.GraphModule, _: Any) -> torch.jit.ScriptModule: + strip_overloads(fx_g) + f = torch.jit.script(fx_g) + f = torch.jit.freeze(f.eval()) + return f + + +def nnc_jit(f: Callable[..., Any]) -> Callable[..., Any]: + return aot_function(f, simple_ts_compile) + + +aten = torch.ops.aten +default_decompositions = { + aten.detach, + aten.gelu_backward, + aten.leaky_relu_backward, + aten.sigmoid_backward, + aten.threshold_backward, + aten.hardtanh_backward, + aten.hardsigmoid_backward, + aten.hardswish_backward, + aten.tanh_backward, + aten.silu_backward, + aten.elu_backward, + aten.cudnn_batch_norm, + aten.cudnn_batch_norm_backward, + aten.masked_fill.Scalar, + aten.masked_fill.Tensor, + aten.elu, + aten.leaky_relu, + aten.hardtanh, + aten.hardswish, + aten.hardsigmoid, + aten.conj_physical, + aten.is_same_size, +} + +# pyrefly: ignore[bad-argument-type] +default_decompositions = get_decompositions(default_decompositions) + + +@make_boxed_compiler +def print_compile(fx_g: fx.GraphModule, _: Any) -> fx.GraphModule: + print(fx_g.code) + return fx_g + + +def memory_efficient_fusion( + fn: Callable[_P, _R] | nn.Module, + **kwargs: Any, +) -> Callable[_P, _R] | nn.Module: + """ + Wrapper function over :func:`aot_function` and :func:`aot_module` to perform + memory efficient fusion. It uses the + :func:`min_cut_rematerialization_partition` partitioner to perform efficient + recomputation. It uses NVFuser to compile the generated forward and backward + graphs. + + .. warning:: + This API is experimental and likely to change. + + Args: + fn (Union[Callable, nn.Module]): A Python function or a ``nn.Module`` + that takes one or more arguments. Must return one or more Tensors. + **kwargs: Any other overrides you want to make to the settings + + Returns: + Returns a ``Callable`` or ``nn.Module`` that retains the eager behavior + of the original :attr:`fn`, but whose forward and backward graphs have + gone through recomputation optimizations, and the graphs have been + compiled with nvfuser. + + """ + config = { + "fw_compiler": ts_compile, + "bw_compiler": ts_compile, + "partition_fn": min_cut_rematerialization_partition, + "decompositions": default_decompositions, + } + config.update(kwargs) + if isinstance(fn, torch.nn.Module): + return aot_module(fn, **config) # pyrefly: ignore[bad-argument-type] + else: + return aot_function(fn, **config) # pyrefly: ignore[bad-argument-type] + + +def debug_compile( + fx_g: fx.GraphModule, inps: Sequence[torch.Tensor] +) -> torch.jit.ScriptModule: + fx_g.to_folder("foo") + print( + f""" +############################################################## +# To minimize FX graph, copy and paste the below and run it # +############################################################## + +import torch +import torch.fx as fx +from functorch.compile import minifier, check_nvfuser_subprocess, check_nvfuser_correctness_subprocess + +inps = {[(i.shape, i.dtype) for i in inps]} +inps = [torch.ones(shape, dtype=dtype, device='cuda') for (shape, dtype) in inps] +from foo import FxModule +mod = FxModule().cuda() + +with torch.jit.fuser("fuser2"): + # check_nvfuser_subprocess can be replaced with check_nvfuser_correctness_subprocess + minifier(fx.symbolic_trace(mod), inps, check_nvfuser_subprocess) +""" + ) + # pyrefly: ignore[missing-import, missing-module-attribute] + from foo import FxModule + + FxModule().cuda()(*inps) + + return ts_compile(fx_g, inps) + + +graph_index: int = 0 + + +def get_inputs(input_data_path: str) -> list[torch.Tensor]: + """ + Return a random input for the given inputs meta generated from _save_fx_default. + """ + inputs: list[torch.Tensor] = [] + with open(input_data_path, "rb") as f: + inputs_meta = pickle.load(f) + inputs = [] + for meta in inputs_meta: + if len(meta) == 1: + type = meta + input_ = type(random.random()) + else: + type, shape, _stride, dtype, device = meta + if dtype in { + torch.int, + torch.int32, + torch.int64, + torch.bool, + torch.int, + torch.uint8, + int, + float, + }: + input_ = torch.randint(0, 1, shape, dtype=dtype, device=device) + else: + input_ = torch.rand(shape, dtype=dtype, device=device) + inputs.append(input_) + return inputs + + +def _save_fx_default( + current_name: str, + folder_name: str, + dump_example_input: bool, + gm: torch.fx.GraphModule, + example_inputs: list[torch.Tensor], +) -> nn.Module: + """ + The forward, backward, and joint computation graph will be stored in + {folder_name}/{current_name}/{current_name}_forward_{graph_index}, + {folder_name}/{current_name}/{current_name}_backward_{graph_index}, and + {folder_name}/{current_name}/{current_name}_joint_{graph_index} respectively. + The input shape of the graphs will be stored in the .input files. + These files can be loaded with pickle, + and is a list of format (type, shape, stride, dtype, device). + In the case of type = int or float, it is just (type,). + For joint graph input, it is a nested list [[],[]] + where the two inner lists have the same format. + If dump_example_input is True, example_inputs will be stored in .pt file. + Since each function might produce multiple graphs, + the graph_index is used to distinguish different graphs + """ + from functorch.compile import aot_module_simplified + + def get_input_meta(args: Any) -> list[Any]: + input_meta = [] + if len(args) > 0 and isinstance(args[0], tuple): # joint input + input_meta += get_input_meta(args[0]) + input_meta += get_input_meta(args[1]) + return input_meta + for arg in args: + if type(arg) is int or type(arg) is float: + input_meta.append((type(arg),)) + else: + input_meta.append( + (type(arg), arg.shape, arg.stride(), arg.dtype, arg.device) + ) + return input_meta + + def graph_saver_helper( + gm_to_save: fx.GraphModule, args: Any, type_name: str + ) -> None: + global graph_index + if len(gm_to_save.graph.nodes) == 0: + log.log( + logging.WARNING, + "No nodes in graph {%s}_{%s}_{%s}.", + current_name, + type_name, + graph_index, + ) + return + + gm = copy.deepcopy(gm_to_save) + gm.graph.set_codegen(torch.fx.graph.CodeGen()) # remove codegen + gm.recompile() + + input_meta = get_input_meta(args) + + os.makedirs(f"{folder_name}/{current_name}", exist_ok=True) + gm.to_folder( + f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}" + ) + with open( + f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}/{current_name}_{type_name}_{graph_index}.input", + "wb", + ) as f: + pickle.dump(input_meta, f) + if dump_example_input: + torch.save( + args, + f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}/{current_name}_{type_name}_{graph_index}.pt", + ) + + def graph_saver_forward( + gm: fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> fx.GraphModule: + graph_saver_helper(gm, example_inputs, "forward") + return gm + + def graph_saver_backward( + gm: fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> fx.GraphModule: + graph_saver_helper(gm, example_inputs, "backward") + global graph_index + graph_index += 1 + return gm + + def graph_saver_joint( + gm: fx.GraphModule, joint_args: list[torch.Tensor] + ) -> tuple[fx.GraphModule, fx.GraphModule]: + graph_saver_helper(gm, joint_args, "joint") + return default_partition(gm, joint_args) # pyrefly: ignore[missing-argument] + + # pyrefly: ignore[bad-return] + return aot_module_simplified( + gm, + example_inputs, + fw_compiler=graph_saver_forward, # pyrefly: ignore[bad-argument-type] + bw_compiler=graph_saver_backward, # pyrefly: ignore[bad-argument-type] + partition_fn=graph_saver_joint, + decompositions=default_decompositions, # pyrefly: ignore[bad-argument-type] + ) + + +# WARNING: This isn't tested anywhere!! +def graph_dumper_aot( + current_name: str, folder_name: str, dump_example_input: bool = False +) -> Callable[[bool, nn.Module], Any]: + """ + Dump the forward, backward, and joint computation graph. + Example Usage: + save_fx_func = graph_dumper_aot(current_name, folder_name, dump_example_input = False) + optimize_ctx = torchdynamo.optimize( + save_fx_func + ) + with torch.enable_grad(): + with optimize_ctx: + result = forward_and_backward_pass(model, example_inputs) + """ + global graph_index + graph_index = 0 + return partial(_save_fx_default, current_name, folder_name, dump_example_input) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/config.py b/.venv/lib/python3.12/site-packages/torch/_functorch/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a7dbde4a4181ac233187739fe215b7e91f9f19d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/config.py @@ -0,0 +1,464 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from collections.abc import Callable + + +""" +Global flags for aot autograd +""" + +import os +import sys +from typing import Literal, TYPE_CHECKING + +from torch.utils._config_module import Config, install_config_module + + +# [@compile_ignored: debug] +_save_config_ignore = [ + # callable not serializable + "joint_custom_pass", + # callable configs with uuid() for caching, or raw callables + "activation_memory_budget_runtime_estimator", + "activation_memory_budget_solver", +] + + +# Converts torch rng ops to their functional philox rng equivalents. Note that +# we functionalize only CUDA rng ops today. +functionalize_rng_ops = False + +# can be useful for debugging if we are incorrectly creating meta fake tensors +fake_tensor_allow_meta = os.environ.get("FAKE_ALLOW_META", "1") != "0" + +# Enables optional asserts in hotpath code to check for errors. If +# you are seeing weird accuracy problems, try turning this on. +# This is currently off by default as it will harm tracing time, +# but it is on by default for aot_eager. +debug_assert = False + +debug_partitioner = os.environ.get("AOT_PARTITIONER_DEBUG", "0") != "0" + +# See # NOTE [Export custom triton op] +decompose_custom_triton_ops = True + +static_weight_shapes = True + +# See https://github.com/pytorch/pytorch/issues/141881 +# Tells partitioner that parameters are free to save for backward. +treat_parameters_as_free_to_save = True + +# Applies CSE to the graph before partitioning +cse = True + +# When the partitioner's _size_of encounters a (Fake)ScriptObject in node +# metadata, it has no general way to know the object's true memory footprint: +# a ScriptObject may hold tensors internally. By default we raise rather than +# guess. Enabling this flag makes _size_of assume such objects are zero size, +# which unblocks dynamic-shapes compilation of models containing ScriptObject +# parameters (e.g. embedding-table configs from FBGEMM) at the cost of +# soundness. This is a temporary escape hatch until we have a principled way to +# probe the size of a (Fake)ScriptObject. +unsafe_treat_script_objects_as_zero_size = False + +from torch._environment import is_fbcode + + +enable_autograd_cache: bool = Config( + justknob="pytorch/remote_cache:enable_local_autograd_cache", + env_name_force="TORCHINDUCTOR_AUTOGRAD_CACHE", + default=True, +) + +autograd_cache_allow_custom_autograd_functions: bool = Config( + env_name_force="TORCHINDUCTOR_AUTOGRAD_CACHE_ALLOW_CUSTOM_AUTOGRAD", default=False +) + +# For now, this is just for enabling unit testing in test_aot_autograd_cache.py +# We will either make this the default with AOTAutogradCache, or +# we'll just use it in the precompile flow. So there's no +# need to add env vars or make it configurable +bundled_autograd_cache: bool = False + +bypass_autograd_cache_key: bool = False + +# Whether or not to normalize placeholder names in graphs +# from dynamo in AOTAutogradCache +autograd_cache_normalize_inputs = not is_fbcode() + +# Enable debug mode at first invocation to check if custom ops are valid. +# When enabled, this checks that custom operators don't violate aliasing constraints. +# +# check_custom_op_aliasing: Controls whether to run the custom op aliasing check at all. +# - When True: The check runs on first invocation of compiled functions. +# - When False: The check is skipped entirely. +# +# error_on_custom_op_aliasing: Controls behavior when a violation is detected. +# Only has effect when check_custom_op_aliasing is True. +# - When True: Raises RuntimeError on aliasing violations. +# - When False: Emits UserWarning on aliasing violations. +# +# Deprecated: Custom ops returning aliased outputs is deprecated and will +# become an error in a future version of PyTorch. Currently error_on_custom_op_aliasing +# is True in CI unless explicitly overridden. +check_custom_op_aliasing = True +error_on_custom_op_aliasing: bool = Config( + env_name_force="TORCHINDUCTOR_ERROR_ON_CUSTOM_OP_ALIASING", + default=bool(os.getenv("CI")), +) + + +def remote_autograd_cache_default() -> bool | None: + if os.environ.get("TORCHINDUCTOR_AUTOGRAD_REMOTE_CACHE") == "1": + return True + if os.environ.get("TORCHINDUCTOR_AUTOGRAD_REMOTE_CACHE") == "0": + return False + return None + + +enable_remote_autograd_cache = remote_autograd_cache_default() + + +# When AOTAutograd regenerates aliased graph outputs, +# attempt to use functionalization's view-replay logic +# before falling back to the autograd engine's view replay or as_strided. +# This can have some perf implications +# (although for many models this will not matter). +# (1) If you have many view ops chained together, replaying all of them +# at runtime can have more overhead compared to a single as_strided call +# (2) If you are doing training, AsStridedBackward is quite slow, +# and the individual view op backward formulas will likely be faster. +# (3) Some backends like XLA do not support as_strided + +# Temporary hack: disable this flag for internal +# (needed to fix an internal issue while avoiding bumping XLA pin) +# eventually: either default this config to false completely +# once XLA pin update works, +# or default config to true and fix relevant bugs + + +# View replay is currently not compatible with AOTAutogradCache, since +# FunctionalTensors are not serializable. We'll need to make them +# serializable before enabling warm cache with this config turned on. +view_replay_for_aliased_outputs = not is_fbcode() + +# Restricts the amount of computation AOTAutograd can do. +# NB: We have essentially disabled this heuristic now. However, this is kept +# here for now in case it's useful. Setting it low can artificially reduce the +# amount of recomputation AOTAutograd performs, although not in any kind of +# principled way. +max_dist_from_bw = 1000 + + +# Bans recomputation of nodes that are reading from nodes that are far before +# the current node +ban_recompute_used_far_apart = True +# Breaks up long chain of fusible ops, as otherwise we can have an arbitrarily +# long chain of recomputation in the backwards pass. +ban_recompute_long_fusible_chains = True +# Bans recomputation of nodes that must be materialized in the backwards pass +# (used by a non-fusible node) +ban_recompute_materialized_backward = True +# Chooses to ban recomputation of nodes based off an allowlist. Setting it to +# False changes it to use a denylist. Main change is on operators like +# sort/pool/stuff that isn't cheap enough to be fusible for free but also isn't +# that expensive +ban_recompute_not_in_allowlist = True +# Chooses to ban recomputation of reductions. This is generally a good idea, as +# the result of reductions is generally very small but recomputing reductions in +# a fusion can be expensive. +ban_recompute_reductions = True +# Prevents the partitioner from ever saving views (i.e. always recompute them). +# Generally a good idea since views are free to recompute. +recompute_views = False +# Set this flag to enable considering non-built-in ops, including triton and custom +# ops, for recomputation during the knapsack optimization solver. +is_non_builtin_to_include = False + +# Rematerialize AC nodes for graphs with forward+loss+backward in one graph. +# This optimization minimizes activation checkpoint node lifetimes by computing them +# just-in-time. For AC nodes only used in backward, they are deferred to backward region +# instead of being computed and saved in forward. This reduces peak memory usage. +# Note: This only applies to forward+loss+backward graphs where torch.autograd.grad is allowed +# in the graph. Joint graphs (standard AOTAutograd) use the partitioner instead. +remat_using_tags_for_fwd_loss_bwd_graph = True + +# By default, the partitioner is purely trying to optimize for runtime (although +# it should always use less memory than eager) +# This knob controls the partitioner to make that tradeoff for you, choosing the +# fastest option that saves less activations than the memory budget. +# Specifically, 0.0 corresponds to the activation memory from applying +# activation checkpointing to the full compiled region, and 1.0 corresponds to +# the activation memory from the default runtime-optimized strategy. So, 0.4 +# would result in a strategy that saves 40% of the activations compared to the +# default strategy. +# It solves a 0-1 knapsack to find the minimum recompute necessary to stay below +# the activation memory budget. +# NOTE: This *cannot* be treated as +activation_memory_budget = 1.0 + +# This controls how we estimate the runtime when deciding what the cheapest +# operators to recompute are. The 3 options are +# "flops": Bases it off of the flop count provided by torch.utils.flop_counter +# "profile": Benchmarks each operator to come up with a runtime +# "testing": Returns 1 for everything +activation_memory_budget_runtime_estimator = "flops" + +# This controls the solver used for the 0-1 knapsack. By default we use a +# quantized DP solution ("dp"). The other approaches are a "greedy", an "ilp" +# (which has a scipy dependency) and "dp_knapsack_sliding_hirschberg", which +# used memory-efficient quantized DP solution +activation_memory_budget_solver = "dp" + +# This dumps out an SVG visualization of the expected runtime vs. activation +# memory tradeoffs for all memory budget values from 0 to 1 in increments of +# 0.5. See an example here: +# https://github.com/pytorch/pytorch/pull/126320#discussion_r1625104015 +visualize_memory_budget_pareto = ( + os.environ.get("PARTITIONER_MEMORY_BUDGET_PARETO", "0") == "1" +) + +# This controls the directory in which to dump the SVG plot with the pareto +# frontier of the activation checkpointing memory-vs-runtime tradeoffs. +memory_budget_pareto_dir = os.environ.get("PARTITIONER_MEMORY_BUDGET_PARETO_DIR") + +# Sets all of the ban_recompute heuristics to False except ban_recompute_reductions +# Generally, this will probably result in some memory improvement, but at the +# cost of some performance +aggressive_recomputation = False + +# activation offloading enablement (testing purpose) +enable_activation_offloading = False + +# activation offloading with separate CUDA stream +activation_offload_separate_stream = False + +# activation offloading wait sinking when using separate stream (fwd graph) +activation_offload_sink_wait = False + +# activation reloading with prefetching when using separate streams (bwd graph) +activation_reload_prefetch = False + +# CPU ↔ GPU bandwidth in GB/s, used to estimate transfer times for prefetch +# scheduling. This is hardware-specific and should be set by the user. +activation_offload_cpu_gpu_bw: float = 50.0 + +# If FakeTensor.data_ptr() should error. +# This option is independent of AOTAutograd and torch.compile, but our policy +# is to turn it off during torch.compile. +fake_tensor_allow_unsafe_data_ptr_access = True + +# Unlifts effect tokens from the inputs/outputs in the traced graph and instead +# inserts make_token/sink_token calls in the graph to create tokens and then +# sink them at the end. Note that this means the graph is no longer functional +# which may lead to silent errors unless the backend knows how to handle the +# tokens. +unlift_effect_tokens = False + +# NOTE: [The default layout constraint for custom operators.] +# This must be the name of one of the layout constraint tags +# (that is, one of {"needs_fixed_stride_order", "flexible_layout"}), +# If the custom op does not have a layout constraint tag already +# then we assume the following applies. +# +# This config is respected by Inductor and we recommend other backends also +# respect it. +# This config is in torch._functorch and not torch._inductor because it affects +# ProxyTensor tracing. +custom_op_default_layout_constraint: Literal[ + "needs_exact_strides", "needs_fixed_stride_order", "flexible_layout" +] = "needs_exact_strides" + + +# Run aot eager decomp partition with CrossRefFakeMode +# options = False, "all", "custom_ops" +fake_tensor_crossref = False + +# This mode specifies that we should also keep track of the real +# tensor along with the fake tensor, and do real compute. While +# seemingly this eliminates the whole point of fake tensors, there are +# two obvious use cases for it: +# +# 1. When users call item()/other data dependent operations, +# if we propagate_real_tensors we are able to determine what +# the true value is and keep going. +# +# 2. It can be useful for testing, when you want to see if the fake +# and real tensors agree with each other. (Note that there are +# currently known inaccuracies in how we clone real tensors, that +# would have to be tightened up for this to be useful in this +# case.) +# +# Note that fake tensors are typically understood to be cheap to store +# indefinitely, so we tend to hold on to them longer than we would +# hold onto the real tensors. So we also support you explicitly +# deallocating the real tensor associated with a fake tensor, at which +# point we will stop propagating real tensors. +# +# One more thing: when you provide a real tensor to fakeify, we will +# clone it, so that we can safely perform mutations on it if necessary. +# This will increase live memory usage. This could potentially be +# optimized by using COW. We also currently do not faithfully +# maintain autograd metadata on the real tensor; this is fine because +# AOTAutograd will only use the fake tensor to determine leafness/etc +# of tensors in question. +fake_tensor_propagate_real_tensors = False + +# AOTDispatcher traces out a backward graph at the time of the forward pass. +# This flag controls whether or not that backward graph gets autocast behavior +# applied to it. +# +# The options are either: +# - "same_as_forward". We assume that the backward of the torch.compile'ed region +# will be run under the same autocast context manager that the region was run +# under. This is equivalent to running the following code in eager: +# +# with torch.amp.autocast(...): +# y = region(x) +# ... +# z.backward() +# +# - "off". We assume that the backward of the torch.compile'd region will +# not be run under any autocast context managers. +# This is equivalent to running the following code in eager: +# +# with torch.amp.autocast(...): +# y = region(x) +# ... +# z.backward() +# +# - or a list of kwargs dicts that represent an autocast context manager to turn +# on during the backward pass. +# +# e.g. [{"device_type": "cuda"}] is equivalent to running the following code in eager: +# +# y = region(x) +# ... +# with torch.amp.autocast(device="cuda"): +# z.backward() +backward_pass_autocast = "same_as_forward" + +# This controls whether we collect donated buffers. This flag must be set +# False if a user wants to retain_graph=True for backward. +donated_buffer = not is_fbcode() + +# Controls the default graph output format used by draw_graph. +# Most supported formats are defined here https://graphviz.org/docs/outputs/. +# The "dot" and "raw" formats write raw DOT text without invoking Graphviz. +torch_compile_graph_format = os.environ.get("TORCH_COMPILE_GRAPH_FORMAT", "svg") + +# Valid only if fake_tensor_propagate_real_tensors = True; if a fake-real +# kernel mismatch is detected, bypasses by making a fake kernel from the +# real tensor outputs. +generate_fake_kernels_from_real_mismatches = False + +# When there are device mismatches in FakeTensor device propagation, +# prefer a specific device type over others. This is particularly useful +# in full compiled mode where intermediate tensors with device mismatches +# represent only logical differences during compilation - these intermediate +# tensors will never physically materialize in the binary execution, so the +# device mismatch is not a real runtime concern. Enabling this allows the +# compiler to proceed with compilation by choosing the preferred device type +# for consistency. For example, set to "mtia" to prefer MTIA devices over +# CPU, or "cuda" to prefer CUDA devices over CPU. +fake_tensor_prefer_device_type: str | None = None + +# CUDAGraph safe run_with_rng functionalization. +graphsafe_rng_functionalization = True + +# Whether or not to eagerly compile the backward +# used by AOT compile and other settings +# TODO: once AOT compile calls aot autograd directly instead of +# through compile_fx, we can remove this +force_non_lazy_backward_lowering = False + +# only for testing, used to turn functionalization off in AOTDispatcher +_test_disable_functionalization = True + +# Error on BypassAOTAutogradCache instead of just a warning +# Used for tests +strict_autograd_cache = False + +# Note [Recomputing collectives in the partitioner] +# The purpose of this config is as follows: +# - We have many passes in the compiler (min-cut partitioning, DCE, etc) +# which can reorder or delete duplicate nodes in the graph +# - If any of these passes reorder/delete/duplicate a collective +# in a setting where the compiler is being run independently on multiple +# ranks, we run the risk that the compiler will make a different decision on +# different ranks, resulting in a NCCL hang when using torch.compile +# To handle this, we will (by default) ensure that collectives are not modified +# by the compiler. +# +# A few examples: +# - don't dead-code-eliminate collectives +# (in case they are dead on rank i but not rank j) +# - don't recompute collectives in partitioning +# (in case we recompute on rank i but not rank j) +# +# Today this flag **must** be set to false, but eventually +# we want the option to set it to true. +# In order to potentially optimize collectives, we'll need the compiler +# to broadcast information across ranks at compile time to ensure +# that any decisions on collectives are made consistently. +unsafe_allow_optimization_of_collectives = False + +# See Note [AOTAutograd Tangent Subclassness for mutated inputs] +# TODO(ivankobzarev): Remove this config, being able to deduce it compile time. +disable_guess_zero_tangent_for_mutated_input_subclass = False + +# See Note [Tangents memory format] +# By default tangents strideness is guessed to be contiguous, +# At runtime non contiguous tangents will be coerced to be contiguous. +# This config changes this guess for tangents strides to be the same as outputs. +# TODO(ivankobzarev): Remove this config once extra memory usage is investigated. +guess_tangent_strides_as_outputs = not is_fbcode() + + +# This is a temporary config to ensure all ranks take the same decision in the partitioner +# it will ultimately be removed once we share size_hints across ranks through compiler collectives +_sync_decision_cross_ranks = False + +# By default apply inlined saved_tensors_hooks only for "donated" buffers. +# "donated" buffers are invisible to the user, they are intermediates of the forward graph. +# Applying saved tensors hooks for memory optimizations only for intermediates +# guarantees that original saved tensors could be deallocated. +# This config enables saved_tensors_hooks are applied for **all** saved tensors, +# that could include inputs, parameters, outputs. +# "donated" - applied only to saved intermediates of the graph +# "no_static" - applied to all saved but not "static" +# (this includes parameters and user marked as static) +# "all" - no filtering, everything saved for backward. +saved_tensors_hooks_filtering_mode = "donated" + + +# This callback is invoked on the joint graph before partitioning +joint_custom_pass: Callable = None # type: ignore[assignment] + +force_autograd_cache = False + +# Note [Selective Decomposition] +# This config allows selective decomposition of certain operators in the graph. +# When True, it does NOT decompose any nodes, except those nodes that users explicitly +# annotated with regional inductor compile. Please read torch.fx.passes.regional_inductor +# on to explicitly annotate. This is currently only used by inductor lite mode. +selective_decompose: bool = False + +# Complex Support +# This config disallows decomposition of complex-valued Tensors using +# `torch._subclasses.complex_tensor.ComplexTensor` by decomposing everything into +# real-valued operations, passing through the regular pipeline as necessary, +# then converting back to a regular tensor. +enable_complex_wrapper: bool = False + + +if TYPE_CHECKING: + from torch.utils._config_typing import * # noqa: F403 + + +# adds patch, save_config, invalid config checks, etc +install_config_module(sys.modules[__name__]) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/deprecated.py b/.venv/lib/python3.12/site-packages/torch/_functorch/deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..0e66a55bb6cbe18feb8ad87a5b51ce1e38e22b2a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/deprecated.py @@ -0,0 +1,188 @@ +""" +The APIs in this file are exposed as `functorch.*`. They are thin wrappers +around the torch.func.* APIs that have deprecation warnings -- we're trying +to move people to the torch.func.* equivalents. + +NB: We don't use *args, **kwargs in the signatures because that changes the +documentation. +""" + +from __future__ import annotations + +import textwrap +import warnings +from typing import Any, TYPE_CHECKING + +import torch._functorch.apis as apis +import torch._functorch.eager_transforms as _impl +import torch._functorch.make_functional as _nn_impl +import torch.nn as nn + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torch._functorch.eager_transforms import argnums_t + from torch._functorch.vmap import in_dims_t, out_dims_t + + +def get_warning( + api: str, new_api: str | None = None, replace_newlines: bool = False +) -> str: + if new_api is None: + new_api = f"torch.func.{api}" + warning = ( + f"We've integrated functorch into PyTorch. As the final step of the \n" + f"integration, `functorch.{api}` is deprecated as of PyTorch \n" + f"2.0 and will be deleted in a future version of PyTorch >= 2.3. \n" + f"Please use `{new_api}` instead; see the PyTorch 2.0 release notes \n" + f"and/or the `torch.func` migration guide for more details \n" + f"https://pytorch.org/docs/main/func.migrating.html" + ) + if replace_newlines: + warning = warning.replace("\n", "") + return warning + + +def warn_deprecated(api: str, new_api: str | None = None) -> None: + warning = get_warning(api, new_api, replace_newlines=True) + warnings.warn(warning, FutureWarning, stacklevel=3) + + +def setup_docs( + functorch_api: Callable[..., Any], + torch_func_api: Callable[..., Any] | None = None, + new_api_name: str | None = None, +) -> None: + api_name = functorch_api.__name__ + if torch_func_api is None: + torch_func_api = getattr(_impl, api_name) + # See https://docs.python.org/3/using/cmdline.html#cmdoption-OO + if torch_func_api.__doc__ is None: + return + + warning = get_warning(api_name, new_api_name) + warning_note = "\n.. warning::\n\n" + textwrap.indent(warning, " ") + warning_note = textwrap.indent(warning_note, " ") + functorch_api.__doc__ = torch_func_api.__doc__ + warning_note + + +def vmap( + func: Callable[..., Any], + in_dims: in_dims_t = 0, + out_dims: out_dims_t = 0, + randomness: str = "error", + *, + chunk_size: int | None = None, +) -> Callable[..., Any]: + warn_deprecated("vmap", "torch.vmap") + return apis.vmap(func, in_dims, out_dims, randomness, chunk_size=chunk_size) + + +def grad( + func: Callable[..., Any], argnums: argnums_t = 0, has_aux: bool = False +) -> Callable[..., Any]: + warn_deprecated("grad") + return apis.grad(func, argnums, has_aux) + + +def grad_and_value( + func: Callable[..., Any], argnums: argnums_t = 0, has_aux: bool = False +) -> Callable[..., Any]: + warn_deprecated("grad_and_value") + return apis.grad_and_value(func, argnums, has_aux) + + +def vjp(func: Callable[..., Any], *primals: Any, has_aux: bool = False) -> Any: + warn_deprecated("vjp") + return _impl.vjp(func, *primals, has_aux=has_aux) + + +def jvp( + func: Callable[..., Any], + primals: Any, + tangents: Any, + *, + strict: bool = False, + has_aux: bool = False, +) -> Any: + warn_deprecated("jvp") + return _impl.jvp(func, primals, tangents, strict=strict, has_aux=has_aux) + + +def jacrev( + func: Callable[..., Any], + argnums: int | tuple[int, ...] = 0, + *, + has_aux: bool = False, + chunk_size: int | None = None, + _preallocate_and_copy: bool = False, +) -> Callable[..., Any]: + warn_deprecated("jacrev") + return _impl.jacrev( + func, + argnums, + has_aux=has_aux, + chunk_size=chunk_size, + _preallocate_and_copy=_preallocate_and_copy, + ) + + +def jacfwd( + func: Callable[..., Any], + argnums: argnums_t = 0, + has_aux: bool = False, + *, + randomness: str = "error", +) -> Callable[..., Any]: + warn_deprecated("jacfwd") + return _impl.jacfwd(func, argnums, has_aux, randomness=randomness) + + +def hessian(func: Callable[..., Any], argnums: int = 0) -> Callable[..., Any]: + warn_deprecated("hessian") + return _impl.hessian(func, argnums=argnums) + + +def functionalize( + func: Callable[..., Any], *, remove: str = "mutations" +) -> Callable[..., Any]: + warn_deprecated("functionalize") + return _impl.functionalize(func, remove=remove) + + +def make_functional(model: nn.Module, disable_autograd_tracking: bool = False) -> Any: + warn_deprecated("make_functional", "torch.func.functional_call") + return _nn_impl.make_functional(model, disable_autograd_tracking) + + +def make_functional_with_buffers( + model: nn.Module, disable_autograd_tracking: bool = False +) -> Any: + warn_deprecated("make_functional_with_buffers", "torch.func.functional_call") + return _nn_impl.make_functional_with_buffers(model, disable_autograd_tracking) + + +def combine_state_for_ensemble(models: list[nn.Module]) -> Any: + warn_deprecated("combine_state_for_ensemble", "torch.func.stack_module_state") + return _nn_impl.combine_state_for_ensemble(models) + + +setup_docs(vmap, apis.vmap, "torch.vmap") +setup_docs(grad, apis.grad) +setup_docs(grad_and_value, apis.grad_and_value) +setup_docs(vjp) +setup_docs(jvp) +setup_docs(jacrev) +setup_docs(jacfwd) +setup_docs(hessian) +setup_docs(functionalize) +setup_docs(make_functional, _nn_impl.make_functional, "torch.func.functional_call") +setup_docs( + make_functional_with_buffers, _nn_impl.make_functional, "torch.func.functional_call" +) +setup_docs( + combine_state_for_ensemble, + _nn_impl.combine_state_for_ensemble, + "torch.func.stack_module_state", +) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/eager_transforms.py b/.venv/lib/python3.12/site-packages/torch/_functorch/eager_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..69b10bca1a51b35e28db79701c9e7d2e09bc1d13 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/eager_transforms.py @@ -0,0 +1,1960 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +import contextlib +from functools import partial +from typing import Any, overload, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +import torch +import torch.autograd.forward_ad as fwAD +from torch._C._functorch import ( + _assert_wrapped_functional, # type: ignore[attr-defined] + _func_decrement_nesting, # type: ignore[attr-defined] + _func_increment_nesting, # type: ignore[attr-defined] + _grad_decrement_nesting, + _grad_increment_nesting, + _propagate_functional_input_mutation, # type: ignore[attr-defined] + _unwrap_functional_tensor, + _wrap_for_grad, + _wrap_functional_tensor, + get_inplace_requires_grad_allowed, + get_unwrapped, + is_functorch_wrapped_tensor, + set_inplace_requires_grad_allowed, +) +from torch._functorch.predispatch import ( + _jvp_decrement_nesting, + _jvp_increment_nesting, + _unwrap_for_grad, +) +from torch._functorch.utils import argnums_t, exposed_in +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx.experimental import const_fold +from torch.fx.experimental.proxy_tensor import make_fx +from torch.utils import _pytree as pytree +from torch.utils._pytree import ( + tree_flatten, + tree_map, + tree_map_, + tree_map_only, + tree_unflatten, + treespec_pprint, +) + +from .apis import _wraps_without_dynamo_attrs, vmap +from .vmap import doesnt_support_saved_tensors_hooks, get_chunk_sizes + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Sequence + + +_P = ParamSpec("_P") +_R = TypeVar("_R") +_T = TypeVar("_T") + + +def lazy_dynamo_disallow(func: Callable[_P, _R]) -> Callable[_P, _R]: + import torch._dynamo + + return torch._dynamo.disallow_in_graph(func) + + +@contextlib.contextmanager +def enable_inplace_requires_grad(enabled: bool) -> Generator[None, None, None]: + prev_state = get_inplace_requires_grad_allowed() + set_inplace_requires_grad_allowed(enabled) + try: + yield + finally: + set_inplace_requires_grad_allowed(prev_state) + + +def _set_tensor_requires_grad(x: torch.Tensor) -> torch.Tensor: + # avoid graph-break on x.requires_grad_() + # https://github.com/pytorch/pytorch/pull/110053 + return x.requires_grad_() + + +def _create_differentiable(inps: Any, level: int | None = None) -> Any: + def create_differentiable(x: torch.Tensor | Any) -> torch.Tensor: + if isinstance(x, torch.Tensor): + with enable_inplace_requires_grad(True): + return _set_tensor_requires_grad(x) + raise ValueError(f"Thing passed to transform API must be Tensor, got {type(x)}") + + return tree_map(create_differentiable, inps) + + +_Tensors = torch.Tensor | tuple[torch.Tensor, ...] +_TensorsT = TypeVar("_TensorsT", bound=_Tensors) +_TensorsU = TypeVar("_TensorsU", bound=_Tensors) + + +def _undo_create_differentiable(inps: _TensorsT, level: int | None = None) -> _TensorsT: + def unwrap_tensors(x: _TensorsU) -> _TensorsU: + if isinstance(x, torch.Tensor): + if level is None: + raise AssertionError("level must not be None when unwrapping tensors") + # pyrefly: ignore[bad-return] + return _unwrap_for_grad(x, level) + # TODO: Remove the following hack for namedtuples + if isinstance(x, tuple): + return tree_map(unwrap_tensors, tuple(x)) + + raise RuntimeError(f"Expected tensors, got unsupported type {type(x)}") + + return tree_map(unwrap_tensors, inps) + + +def _is_differentiable(maybe_tensor: object) -> bool: + if not isinstance(maybe_tensor, torch.Tensor): + return False + return maybe_tensor.requires_grad + + +def _any_differentiable( + tensor_or_tuple_of_tensors: _Tensors, +) -> bool: + flat_args, _ = tree_flatten(tensor_or_tuple_of_tensors) + return any(tuple(map(_is_differentiable, flat_args))) + + +def _wrap_tensor_for_grad(maybe_tensor: _T, level: int) -> _T: + if not isinstance(maybe_tensor, torch.Tensor): + return maybe_tensor + # pyrefly: ignore[bad-return] + return _wrap_for_grad(maybe_tensor, level) + + +def _wrap_all_tensors(tensor_pytree: _T, level: int) -> _T: + return tree_map(partial(_wrap_tensor_for_grad, level=level), tensor_pytree) + + +# TODO: this is more accurate - enable in 3.11 +# _Ts = TypeVarTuple("_Ts") +# @overload +# def _as_tuple(val: tuple[*_Ts]) -> tuple[*_Ts]: ... +@overload +def _as_tuple(val: tuple[_R, ...]) -> tuple[_R]: ... +@overload +def _as_tuple(val: _R) -> tuple[_R]: ... +def _as_tuple(val: object) -> object: + if isinstance(val, tuple): + return val + return (val,) + + +# Version of autograd.grad that handles outputs that don't depend on inputs + + +def _autograd_grad( + outputs: Sequence[torch.Tensor], + inputs: Sequence[torch.Tensor], + grad_outputs: Sequence[torch.Tensor] | None = None, + retain_graph: bool = False, + create_graph: bool = True, +) -> tuple[torch.Tensor, ...]: + if grad_outputs is None: + diff_outputs = tuple(out for out in outputs if out.requires_grad) + else: + result = tuple( + (out, go) for out, go in zip(outputs, grad_outputs) if out.requires_grad + ) + if len(result) == 0: + diff_outputs, grad_outputs = (), () + else: + diff_outputs, grad_outputs = zip(*result) + if len(diff_outputs) == 0: + return tuple(torch.zeros_like(inp) for inp in inputs) + with torch._dynamo.compiled_autograd._disable(): + grad_inputs = torch.autograd.grad( + diff_outputs, + inputs, + grad_outputs, + retain_graph=retain_graph, + create_graph=create_graph, + allow_unused=True, + ) + grad_inputs = tuple( + torch.zeros_like(inp) if gi is None else gi + for gi, inp in zip(grad_inputs, inputs) + ) + return grad_inputs + + +# NOTE [grad and vjp interaction with no_grad] +# +# def f(x): +# with torch.no_grad(): +# c = x ** 2 +# return x - c +# +# The thing to consider is if enable_grad is on/off before grad gets called. +# +# Case 1: enable_grad is on. +# grad(f)(x) +# In this case, `grad` should respect the inner torch.no_grad. +# +# Case 2: enable_grad is off +# with torch.no_grad(): +# grad(f)(x) +# In this case, `grad` should respect the inner torch.no_grad, but not the +# outer one. This is because `grad` is a "function transform": its result +# should not depend on the result of a context manager outside of `f`. +# +# This gives us the following desired behavior: +# - (nested) grad transforms must obey torch.no_grad inside them +# - (nested) grad transforms should not obey torch.no_grad outside them +# +# To achieve this behavior, upon entering grad/vjp: +# - we save the current ("previous") is_grad_enabled (*) +# - we unconditionally enable grad. +# +# Inside DynamicLayerBackFallback, when we're temporarily popping `grad` layer +# off the stack: +# - if grad_mode is disabled, then we do nothing. (there is a torch.no_grad +# active, all subsequent grad transforms must obey it). +# - if grad_mode is enabled, and the previous is_grad_enabled (*) is False, +# then we temporarily restore the previous `is_grad_enabled`. This is +# because we're crossing the boundary from a `grad` outside the +# no_grad to a `grad` inside the no_grad. +# +# NB: vjp has some interesting behavior because the vjp's Callable[..., Any] can be called +# under a different grad_mode than the forward computation... +# +# NB: forward-mode AD: forward-mode AD doesn't respect torch.no_grad, but +# it respects c10::AutoFwGradMode. We've implemented the same logic for +# our jvp transform (it will have special handling if FwGradMode is disabled). + + +# How do we increment and decrement the nesting? I don't think we can. +@exposed_in("torch.func") +def vjp( + func: Callable[..., Any], *primals: Any, has_aux: bool = False +) -> tuple[Any, Callable[..., Any]] | tuple[Any, Callable[..., Any], Any]: + """ + Standing for the vector-Jacobian product, returns a tuple containing the + results of ``func`` applied to ``primals`` and a function that, when + given ``cotangents``, computes the reverse-mode Jacobian of ``func`` with + respect to ``primals`` times ``cotangents``. + + Args: + func (Callable[..., Any]): A Python function that takes one or more arguments. Must + return one or more Tensors. + primals (Tensors): Positional arguments to ``func`` that must all be + Tensors. The returned function will also be computing the + derivative with respect to these arguments + has_aux (bool): Flag indicating that ``func`` returns a + ``(output, aux)`` tuple where the first element is the output of + the function to be differentiated and the second element is + other auxiliary objects that will not be differentiated. + Default: False. + + Returns: + Returns a ``(output, vjp_fn)`` tuple containing the output of ``func`` + applied to ``primals`` and a function that computes the vjp of + ``func`` with respect to all ``primals`` using the cotangents passed + to the returned function. If ``has_aux is True``, then instead returns a + ``(output, vjp_fn, aux)`` tuple. + The returned ``vjp_fn`` function will return a tuple of each VJP. + + When used in simple cases, :func:`vjp` behaves the same as :func:`grad` + + >>> x = torch.randn([5]) + >>> f = lambda x: x.sin().sum() + >>> (_, vjpfunc) = torch.func.vjp(f, x) + >>> grad = vjpfunc(torch.tensor(1.0))[0] + >>> assert torch.allclose(grad, torch.func.grad(f)(x)) + + However, :func:`vjp` can support functions with multiple outputs by + passing in the cotangents for each of the outputs + + >>> x = torch.randn([5]) + >>> f = lambda x: (x.sin(), x.cos()) + >>> (_, vjpfunc) = torch.func.vjp(f, x) + >>> vjps = vjpfunc((torch.ones([5]), torch.ones([5]))) + >>> assert torch.allclose(vjps[0], x.cos() + -x.sin()) + + :func:`vjp` can even support outputs being Python structs + + >>> x = torch.randn([5]) + >>> f = lambda x: {"first": x.sin(), "second": x.cos()} + >>> (_, vjpfunc) = torch.func.vjp(f, x) + >>> cotangents = {"first": torch.ones([5]), "second": torch.ones([5])} + >>> vjps = vjpfunc(cotangents) + >>> assert torch.allclose(vjps[0], x.cos() + -x.sin()) + + The function returned by :func:`vjp` will compute the partials with + respect to each of the ``primals`` + + >>> x, y = torch.randn([5, 4]), torch.randn([4, 5]) + >>> (_, vjpfunc) = torch.func.vjp(torch.matmul, x, y) + >>> cotangents = torch.randn([5, 5]) + >>> vjps = vjpfunc(cotangents) + >>> assert len(vjps) == 2 + >>> assert torch.allclose(vjps[0], torch.matmul(cotangents, y.transpose(0, 1))) + >>> assert torch.allclose(vjps[1], torch.matmul(x.transpose(0, 1), cotangents)) + + ``primals`` are the positional arguments for ``f``. All kwargs use their + default value + + >>> x = torch.randn([5]) + >>> def f(x, scale=4.): + >>> return x * scale + >>> + >>> (_, vjpfunc) = torch.func.vjp(f, x) + >>> vjps = vjpfunc(torch.ones_like(x)) + >>> assert torch.allclose(vjps[0], torch.full(x.shape, 4.0)) + + .. note:: + Using PyTorch ``torch.no_grad`` together with ``vjp``. + Case 1: Using ``torch.no_grad`` inside a function: + + >>> def f(x): + >>> with torch.no_grad(): + >>> c = x ** 2 + >>> return x - c + + In this case, ``vjp(f)(x)`` will respect the inner ``torch.no_grad``. + + Case 2: Using ``vjp`` inside ``torch.no_grad`` context manager: + + >>> # xdoctest: +SKIP(failing) + >>> with torch.no_grad(): + >>> vjp(f)(x) + + In this case, ``vjp`` will respect the inner ``torch.no_grad``, but not the + outer one. This is because ``vjp`` is a "function transform": its result + should not depend on the result of a context manager outside of ``f``. + """ + return _vjp_with_argnums(func, *primals, has_aux=has_aux) + + +@contextlib.contextmanager +def _disable_inference_mode() -> Generator[None, None, None]: + # Disable inference_mode without clobbering grad_mode / fw_grad_mode. + # torch.inference_mode(False) unconditionally sets grad_mode=True and + # fw_grad_mode=True; we save and restore those to avoid that. + # No-op when inference_mode is already off. + if not torch.is_inference_mode_enabled(): + yield + return + prev_grad = torch.is_grad_enabled() + prev_fw_grad = torch._C._is_fwd_grad_enabled() + with torch.inference_mode(False): + torch._C._set_grad_enabled(prev_grad) + torch._C._set_fwd_grad_enabled(prev_fw_grad) + yield + + +@contextlib.contextmanager +def grad_increment_nesting() -> Generator[int, None, None]: + try: + grad_level = _grad_increment_nesting() + yield grad_level + finally: + _grad_decrement_nesting() + + +def enter_jvp_nesting() -> int: + global JVP_NESTING + jvp_level = _jvp_increment_nesting() + JVP_NESTING += 1 + return jvp_level + + +def exit_jvp_nesting() -> None: + global JVP_NESTING + _jvp_decrement_nesting() + JVP_NESTING -= 1 + + +@contextlib.contextmanager +def jvp_increment_nesting() -> Generator[int, None, None]: + try: + yield enter_jvp_nesting() + finally: + exit_jvp_nesting() + + +@doesnt_support_saved_tensors_hooks +def _vjp_with_argnums( + func: Callable[..., Any], + *primals: Any, + argnums: argnums_t | None = None, + has_aux: bool = False, +) -> tuple[Any, Callable[..., Any]] | tuple[Any, Callable[..., Any], Any]: + # This is the same function as vjp but also accepts an argnums argument + # All args are the same as vjp except for the added argument + # argnums (int or tuple[int,...] | None): Optional, specifies the argument(s) to compute gradients with respect to. + # If None, computes the gradients with respect to all inputs (used for vjp). Default: None + # + # WARN: Users should NOT call this function directly and should just be calling vjp. + # It is only separated so that inputs passed to jacrev but not differentiated get the correct wrappers. + # + # NOTE: All error messages are produced as if vjp was being called, even if this was called by jacrev + # + # Returns the same two elements as :func:`vjp` but the function returned, vjp_fn, returns a tuple of VJPs + # for only the primal elements given by argnums. + with grad_increment_nesting() as level: + # See NOTE [grad and vjp interaction with no_grad] + with torch.enable_grad(): + primals = _wrap_all_tensors(primals, level) + if argnums is None: + diff_primals = _create_differentiable(primals, level) + else: + diff_primals = _slice_argnums(primals, argnums, as_tuple=False) + tree_map_(partial(_create_differentiable, level=level), diff_primals) + primals_out = func(*primals) + + aux: Any = None + if has_aux: + if not (isinstance(primals_out, tuple) and len(primals_out) == 2): + raise RuntimeError( + "vjp(f, *primals): output of function f should be a tuple: (output, aux) " + "if has_aux is True" + ) + primals_out, aux = primals_out + aux = _undo_create_differentiable(aux, level) + + flat_primals_out, primals_out_spec = tree_flatten(primals_out) + assert_non_empty_tensor_output(flat_primals_out, "vjp(f, *primals)") + flat_diff_primals, primals_spec = tree_flatten(diff_primals) + results = _undo_create_differentiable(primals_out, level) + + for primal_out in flat_primals_out: + if not isinstance(primal_out, torch.Tensor): + raise AssertionError( + f"expected primal_out to be a Tensor, got {type(primal_out)}" + ) + if primal_out.is_floating_point() or primal_out.is_complex(): + continue + raise RuntimeError( + "vjp(f, ...): All outputs of f must be " + "floating-point or complex Tensors, got Tensor " + f"with dtype {primal_out.dtype}" + ) + + def wrapper( + cotangents: Any, + retain_graph: bool = True, + create_graph: bool | None = None, + ) -> Any: + if create_graph is None: + create_graph = torch.is_grad_enabled() + flat_cotangents, cotangents_spec = tree_flatten(cotangents) + if primals_out_spec != cotangents_spec: + raise RuntimeError( + f"Expected pytree structure of cotangents to be the same " + f"as pytree structure of outputs to the function. " + f"cotangents: {treespec_pprint(cotangents_spec)}, " + f"primal output: {treespec_pprint(primals_out_spec)}" + ) + # This closure runs after grad_increment_nesting exits, so + # inference_mode may have been restored. Disable it for autograd. + # Skip under Dynamo — tracing through the generator CM emits + # spurious _enter_inference_mode nodes. + ctx = ( + contextlib.nullcontext() + if torch.compiler.is_compiling() + else _disable_inference_mode() + ) + with ctx: + result = _autograd_grad( + flat_primals_out, + flat_diff_primals, + flat_cotangents, + retain_graph=retain_graph, + create_graph=create_graph, + ) + return tree_unflatten(result, primals_spec) + + if has_aux: + return results, wrapper, aux # type: ignore[possibly-unbound] + else: + return results, wrapper + + +def _safe_zero_index(x: tuple[_R, ...]) -> _R: + if len(x) != 1: + raise AssertionError(f"expected tuple of length 1, got length {len(x)}") + return x[0] + + +# jacrev and jacfwd don't support complex functions +# Helper function to throw appropriate error. +def error_if_complex(func_name: str, args: Any, is_input: bool) -> None: + flat_args = pytree.tree_leaves(args) + for idx, arg in enumerate(flat_args): + if isinstance(arg, torch.Tensor) and arg.dtype.is_complex: + input_or_output = "inputs" if is_input else "outputs" + err_msg = ( + f"{func_name}: Expected all {input_or_output} " + f"to be real but received complex tensor at flattened input idx: {idx}" + ) + raise RuntimeError(err_msg) + + +@exposed_in("torch.func") +def jacrev( + func: Callable[..., Any], + argnums: int | tuple[int, ...] = 0, + *, + has_aux: bool = False, + chunk_size: int | None = None, + _preallocate_and_copy: bool = False, +) -> Callable[..., Any]: + """ + Computes the Jacobian of ``func`` with respect to the arg(s) at index + ``argnum`` using reverse mode autodiff + + .. note:: + Using :attr:`chunk_size=1` is equivalent to computing the jacobian + row-by-row with a for-loop i.e. the constraints of :func:`vmap` are + not applicable. + + Args: + func (function): A Python function that takes one or more arguments, + one of which must be a Tensor, and returns one or more Tensors + argnums (int or tuple[int, ...]): Optional, integer or tuple of integers, + saying which arguments to get the Jacobian with respect to. + Default: 0. + has_aux (bool): Flag indicating that ``func`` returns a + ``(output, aux)`` tuple where the first element is the output of + the function to be differentiated and the second element is + auxiliary objects that will not be differentiated. + Default: False. + chunk_size (None or int): If None (default), use the maximum chunk size + (equivalent to doing a single vmap over vjp to compute the jacobian). + If 1, then compute the jacobian row-by-row with a for-loop. + If not None, then compute the jacobian :attr:`chunk_size` rows at a time + (equivalent to doing multiple vmap over vjp). If you run into memory issues computing + the jacobian, please try to specify a non-None chunk_size. + + Returns: + Returns a function that takes in the same inputs as ``func`` and + returns the Jacobian of ``func`` with respect to the arg(s) at + ``argnums``. If ``has_aux is True``, then the returned function + instead returns a ``(jacobian, aux)`` tuple where ``jacobian`` + is the Jacobian and ``aux`` is auxiliary objects returned by ``func``. + + A basic usage with a pointwise, unary operation will give a diagonal array + as the Jacobian + + >>> from torch.func import jacrev + >>> x = torch.randn(5) + >>> jacobian = jacrev(torch.sin)(x) + >>> expected = torch.diag(torch.cos(x)) + >>> assert torch.allclose(jacobian, expected) + + If you would like to compute the output of the function as well as the + jacobian of the function, use the ``has_aux`` flag to return the output + as an auxiliary object: + + >>> from torch.func import jacrev + >>> x = torch.randn(5) + >>> + >>> def f(x): + >>> return x.sin() + >>> + >>> def g(x): + >>> result = f(x) + >>> return result, result + >>> + >>> jacobian_f, f_x = jacrev(g, has_aux=True)(x) + >>> assert torch.allclose(f_x, f(x)) + + :func:`jacrev` can be composed with vmap to produce batched + Jacobians: + + >>> from torch.func import jacrev, vmap + >>> x = torch.randn(64, 5) + >>> jacobian = vmap(jacrev(torch.sin))(x) + >>> assert jacobian.shape == (64, 5, 5) + + Additionally, :func:`jacrev` can be composed with itself to produce + Hessians + + >>> from torch.func import jacrev + >>> def f(x): + >>> return x.sin().sum() + >>> + >>> x = torch.randn(5) + >>> hessian = jacrev(jacrev(f))(x) + >>> assert torch.allclose(hessian, torch.diag(-x.sin())) + + By default, :func:`jacrev` computes the Jacobian with respect to the first + input. However, it can compute the Jacobian with respect to a different + argument by using ``argnums``: + + >>> from torch.func import jacrev + >>> def f(x, y): + >>> return x + y ** 2 + >>> + >>> x, y = torch.randn(5), torch.randn(5) + >>> jacobian = jacrev(f, argnums=1)(x, y) + >>> expected = torch.diag(2 * y) + >>> assert torch.allclose(jacobian, expected) + + Additionally, passing a tuple to ``argnums`` will compute the Jacobian + with respect to multiple arguments + + >>> from torch.func import jacrev + >>> def f(x, y): + >>> return x + y ** 2 + >>> + >>> x, y = torch.randn(5), torch.randn(5) + >>> jacobian = jacrev(f, argnums=(0, 1))(x, y) + >>> expectedX = torch.diag(torch.ones_like(x)) + >>> expectedY = torch.diag(2 * y) + >>> assert torch.allclose(jacobian[0], expectedX) + >>> assert torch.allclose(jacobian[1], expectedY) + + .. note:: + Using PyTorch ``torch.no_grad`` together with ``jacrev``. + Case 1: Using ``torch.no_grad`` inside a function: + + >>> def f(x): + >>> with torch.no_grad(): + >>> c = x ** 2 + >>> return x - c + + In this case, ``jacrev(f)(x)`` will respect the inner ``torch.no_grad``. + + Case 2: Using ``jacrev`` inside ``torch.no_grad`` context manager: + + >>> with torch.no_grad(): + >>> jacrev(f)(x) + + In this case, ``jacrev`` will respect the inner ``torch.no_grad``, but not the + outer one. This is because ``jacrev`` is a "function transform": its result + should not depend on the result of a context manager outside of ``f``. + """ + if not (chunk_size is None or chunk_size > 0): + raise ValueError("jacrev: `chunk_size` should be greater than 0.") + + @_wraps_without_dynamo_attrs(func) + def wrapper_fn(*args: Any) -> Any: + error_if_complex("jacrev", args, is_input=True) + vjp_out = _vjp_with_argnums(func, *args, argnums=argnums, has_aux=has_aux) + aux: Any = None + if has_aux: + # pyrefly: ignore[bad-unpacking] + output, vjp_fn, aux = vjp_out + else: + # pyrefly: ignore[bad-unpacking] + output, vjp_fn = vjp_out + + # See NOTE: [Computing jacobian with vmap and vjp for multiple outputs] + flat_output, output_spec = tree_flatten(output) + + error_if_complex("jacrev", flat_output, is_input=False) + + # NB: vjp already checks that all outputs are tensors + # Step 1: Construct grad_outputs by splitting the standard basis + flat_output_numels = tuple(out.numel() for out in flat_output) + + primals = _slice_argnums(args, argnums) + flat_primals, primals_spec = tree_flatten(primals) + + def compute_jacobian_stacked() -> list[Any]: + # Helper function to compute chunked Jacobian + # The intermediate chunked calculation are only + # scoped at this function level. + chunked_results: list[list[Any]] = [] + for flat_basis_chunk in _chunked_standard_basis_for_( + flat_output, flat_output_numels, chunk_size=chunk_size + ): + if chunk_size == 1: + # sanity check. + for t in flat_basis_chunk: + if t.size(0) != 1: + raise AssertionError( + f"expected t.size(0) to be 1, got {t.size(0)}" + ) + + flat_basis_chunk = tree_map( + lambda t: torch.squeeze(t, 0), flat_basis_chunk + ) + + basis = tree_unflatten(flat_basis_chunk, output_spec) + + if chunk_size == 1: + # Behaviour with `chunk_size=1` is same as `for-loop` + # i.e. user shouldn't deal with the limitations of vmap. + chunked_result = vjp_fn(basis) + else: # chunk_size is None or chunk_size != 1 + chunked_result = vmap(vjp_fn)(basis) + + flat_results = pytree.tree_leaves(chunked_result) + + if chunk_size == 1: + flat_results = tree_map( + lambda t: torch.unsqueeze(t, 0), flat_results + ) + + chunked_results.append(flat_results) + + if len(chunked_results) == 1: + # Short-circuit if we used a single chunk + return chunked_results[0] + + # Concatenate chunks. + flat_results = [] + # Iterate and concat the jacobians of different + # inputs. + for idx in range(len(flat_primals)): + r = tuple(r_[idx] for r_ in chunked_results) + flat_results.append(torch.cat(r, 0)) + + return flat_results + + def compute_jacobian_preallocate_and_copy() -> list[Any]: + # Helper function to compute chunked Jacobian + # The intermediate chunked calculation are only + # scoped at this function level. + out_vec_size = sum(flat_output_numels) + + # Don't pre-allocate if we have a single chunk. + stacked_results: list[torch.Tensor] = [] + if not (chunk_size is None or chunk_size >= out_vec_size): + stacked_results = [ + primal.new_zeros(out_vec_size, *primal.shape) + for primal in flat_primals + ] + + for idx, flat_basis_chunk in enumerate( + _chunked_standard_basis_for_( + flat_output, flat_output_numels, chunk_size=chunk_size + ) + ): + if chunk_size == 1: + # sanity check. + for t in flat_basis_chunk: + if t.size(0) != 1: + raise AssertionError( + f"expected t.size(0) to be 1, got {t.size(0)}" + ) + + flat_basis_chunk = [torch.squeeze(t, 0) for t in flat_basis_chunk] + + basis = tree_unflatten(flat_basis_chunk, output_spec) + + if chunk_size == 1: + # Behaviour with `chunk_size=1` is same as `for-loop` + # i.e. user shouldn't deal with the limitations of vmap. + chunked_result = vjp_fn(basis) + else: # chunk_size is None or chunk_size != 1 + chunked_result = vmap(vjp_fn)(basis) + + flat_results = pytree.tree_leaves(chunked_result) + + # Short-circuit if we have a single chunk. + if chunk_size is None or chunk_size >= out_vec_size: + if chunk_size == 1: # and out_vec_size == 1 + # Since we squeezed the output dim + flat_results = tree_map( + lambda t: torch.unsqueeze(t, 0), flat_results + ) + return flat_results + + for r, sr in zip(flat_results, stacked_results): # type: ignore[possibly-unbound] + sr[idx * chunk_size : (idx + 1) * chunk_size].copy_(r) + + return stacked_results # type: ignore[possibly-unbound] + + if _preallocate_and_copy: + flat_jacobians_per_input = compute_jacobian_preallocate_and_copy() + else: + flat_jacobians_per_input = compute_jacobian_stacked() + + # Step 2: The returned jacobian is one big tensor per input. In this step, + # we split each Tensor by output. + flat_jacobians_per_input = [ + torch.split(result, list(flat_output_numels), dim=0) + for result in flat_jacobians_per_input + ] + flat_input_flat_output = [ + tuple( + split.view(out.shape + primal.shape) + for split, out in zip(splits, flat_output) + ) + for splits, primal in zip(flat_jacobians_per_input, flat_primals) + ] + + # Step 3: Right now, `jacobian` is a List[List[Tensor]]. + # The outer List corresponds to the number of primals, + # the inner List corresponds to the number of outputs. + # We need to: + # a. Exchange the order of the outer List and inner List + # b. tree_unflatten the inner Lists (which correspond to the primals) + # c. handle the argnums=int case + # d. tree_unflatten the outer List (which corresponds to the outputs) + flat_output_flat_input = tuple(zip(*flat_input_flat_output)) + + flat_output_input = tuple( + tree_unflatten(flat_input, primals_spec) + for flat_input in flat_output_flat_input + ) + + if isinstance(argnums, int): + flat_output_input = tuple( + _safe_zero_index(flat_input) for flat_input in flat_output_input + ) + output_input = tree_unflatten(flat_output_input, output_spec) + if has_aux: + return output_input, aux # type: ignore[possibly-unbound] + return output_input + + return wrapper_fn + + +# NOTE: [Computing jacobian with vmap and vjp for multiple outputs] +# +# Let's consider f(x) = (x**2, x.sum()) and let x = torch.randn(3). +# It turns out we can compute the jacobian of this function with a single +# call to autograd.grad by using vmap over the correct grad_outputs. +# +# Firstly, one way to compute the jacobian is to stack x**2 and x.sum() +# into a 4D vector. E.g., use g(x) = torch.stack([x**2, x.sum()]) +# +# To get the first row of the jacobian, we call +# >>> autograd.grad(g(x), x, grad_outputs=torch.tensor([1, 0, 0, 0])) +# To get the 2nd row of the jacobian, we call +# >>> autograd.grad(g(x), x, grad_outputs=torch.tensor([0, 1, 0, 0])) +# and so on. +# +# Using vmap, we can vectorize all 4 of these computations into one by +# passing the standard basis for R^4 as the grad_output. +# vmap(partial(autograd.grad, g(x), x))(torch.eye(4)). +# +# Now, how do we compute the jacobian *without stacking the output*? +# We can just split the standard basis across the outputs. So to +# compute the jacobian of f(x), we'd use +# >>> autograd.grad(f(x), x, grad_outputs=_construct_standard_basis_for(...)) +# The grad_outputs looks like the following: +# ( torch.tensor([[1, 0, 0], +# [0, 1, 0], +# [0, 0, 1], +# [0, 0, 0]]), +# torch.tensor([[0], +# [0], +# [0], +# [1]]) ) +# +# But we're not done yet! +# >>> vmap(partial(autograd.grad(f(x), x, grad_outputs=...))) +# returns a Tensor of shape [4, 3]. We have to remember to split the +# jacobian of shape [4, 3] into two: +# - one of shape [3, 3] for the first output +# - one of shape [ 3] for the second output + + +def _chunked_standard_basis_for_( + tensors: Sequence[torch.Tensor], + tensor_numels: Sequence[int], + chunk_size: int | None = None, +) -> Generator[tuple[torch.Tensor, ...], None, None]: + # This function: + # - constructs a N=sum(tensor_numels) standard basis. i.e. an NxN identity matrix. + # - Splits the identity matrix into chunks with each chunk size determined by `tensor_numels`. + # - Each chunk corresponds to one tensor. The chunk has the same dtype and + # device as the tensor + # + # For example, with tensor_numels = [1, 2, 1], this function returns: + # ( tensor([[1], tensor([[0, 0], tensor([[0], + # [0], [1, 0], [0], + # [0], [0, 1], [0], + # [0]]) , [0, 0]]) , [1]]) ) + # + # Precondition: tensor_numels == tuple(tensor.numel() for tensor in tensors) + # Precondition: tensors always has at least one element. + # + # See NOTE: [Computing jacobian with vmap and grad for multiple tensors] + # for context behind this function. + # NOTE: Argument `chunk_size` is used to generate chunked basis instead of + # one huge basis matrix. `chunk_size` dictates the maximum size of the + # basis matrix along dim=0. + if len(tensors) != len(tensor_numels): + raise AssertionError( + f"len(tensors)={len(tensors)} != len(tensor_numels)={len(tensor_numels)}" + ) + if len(tensors) == 0: + raise AssertionError("tensors must have at least one element") + if chunk_size is not None and chunk_size <= 0: + raise AssertionError(f"chunk_size must be > 0 or None, got {chunk_size}") + total_numel = sum(tensor_numels) + if chunk_size and chunk_size < total_numel: + chunk_numels = get_chunk_sizes(total_numel, chunk_size) + else: # chunk_size is None or chunk_size >= total_numel + chunk_size = total_numel + chunk_numels = [total_numel] + + diag_start_indices = [] + diag_start_idx = 0 + for tensor_numel in tensor_numels: + diag_start_indices.append(diag_start_idx) + diag_start_idx -= tensor_numel + + for chunk_idx, total_numel in enumerate(chunk_numels): + chunks = tuple( + tensor.new_zeros(total_numel, tensor_numel) + for tensor, tensor_numel in zip(tensors, tensor_numels) + ) + + for chunk, diag_start_idx in zip(chunks, diag_start_indices): + offset = int(diag_start_idx) + chunk_idx * chunk_size + chunk.diagonal(offset).fill_(1) + chunks = tuple( + chunk.view(total_numel, *tensor.shape) + for chunk, tensor in zip(chunks, tensors) + ) + yield chunks + + +def _construct_standard_basis_for( + tensors: Sequence[torch.Tensor], tensor_numels: Sequence[int] +) -> tuple[torch.Tensor, ...] | None: + for basis in _chunked_standard_basis_for_(tensors, tensor_numels, chunk_size=None): + return basis + return None + + +def _validate_and_wrap_argnum(argnum: int, num_args: int) -> int: + if not isinstance(argnum, int): + raise RuntimeError(f"argnum must be int, got: {type(argnum)}") + if argnum >= 0 and argnum < num_args: + return argnum + if argnum < 0 and argnum >= -num_args: + return argnum + num_args + raise RuntimeError(f"Got argnum={argnum}, but only {num_args} positional inputs") + + +def _check_unique_non_empty(argnums: argnums_t) -> None: + if isinstance(argnums, tuple): + if len(argnums) == 0: + raise RuntimeError("argnums must be non-empty") + if len(set(argnums)) != len(argnums): + raise RuntimeError(f"argnums elements must be unique, got {argnums}") + + +def _replace_args( + old_args: tuple[Any, ...], new_args: tuple[Any, ...], argnums: argnums_t +) -> tuple[Any, ...]: + if isinstance(argnums, int): + if len(new_args) != 1: + raise RuntimeError( + f"new_args should be of size 1, was of size {len(new_args)}" + ) + return tuple( + new_args[0] if i == argnums else old_args[i] for i in range(len(old_args)) + ) + if isinstance(argnums, tuple): + if len(new_args) != len(argnums): + raise RuntimeError( + "new_args should have the same size as argnums. " + f"Argnums size {len(argnums)}, new_args size {len(new_args)}" + ) + + argnums_tuple = argnums + + def get_right_elem(i: int) -> Any: + return ( + new_args[argnums_tuple.index(i)] if i in argnums_tuple else old_args[i] + ) + + return tuple(get_right_elem(i) for i in range(len(old_args))) + raise RuntimeError(f"argnums must be int or Tuple[int, ...], got: {type(argnums)}") + + +def _validate_and_wrap_argnums(argnums: argnums_t, num_args: int) -> argnums_t: + if isinstance(argnums, int): + return _validate_and_wrap_argnum(argnums, num_args) + if isinstance(argnums, tuple): + return tuple(_validate_and_wrap_argnum(argnum, num_args) for argnum in argnums) + raise AssertionError("Should never get here") + + +def _slice_argnums( + args: tuple[Any, ...], argnums: argnums_t, as_tuple: bool = True +) -> Any: + if not isinstance(argnums, int) and not isinstance(argnums, tuple): + raise RuntimeError( + f"argnums must be int or Tuple[int, ...], got: {type(argnums)}" + ) + argnums = _validate_and_wrap_argnums(argnums, len(args)) + _check_unique_non_empty(argnums) + if isinstance(argnums, int): + if as_tuple: + return (args[argnums],) + else: + return args[argnums] + return tuple(args[i] for i in argnums) + + +JVP_NESTING = 0 + + +def assert_flat_tuple_of_tensors(elts: Any, api: str, argname: str) -> None: + if not isinstance(elts, tuple): + raise RuntimeError( + f"{api}: Expected {argname} to be a tuple of Tensors, got {type(elts)}" + ) + for elt in elts: + if isinstance(elt, torch.Tensor): + continue + raise RuntimeError( + f"{api}: Expected {argname} to be a tuple of Tensors, got " + f"a tuple with an element of type {type(elt)}" + ) + if len(elts) == 0: + raise RuntimeError( + f"{api}: Expected {argname} to be a non-empty tuple of Tensors." + ) + + +def assert_non_empty_tensor_output(output: list[Any], api: str) -> None: + if (len(output) == 1 and output[0] is None) or len(output) < 1: + raise RuntimeError( + f"{api}: Expected f to be a function that has non-empty output (got output = {output})" + ) + for o in output: + if not isinstance(o, torch.Tensor): + raise RuntimeError( + f"{api}: expected f(*primals) to return only tensors" + f", got unsupported type {type(o)}" + ) + + +def assert_output_is_tensor_or_tensors(output: Any, api: str) -> None: + if isinstance(output, torch.Tensor): + return + if not isinstance(output, tuple): + raise RuntimeError( + f"{api}: Expected output of f to be a Tensor or Tensors, got {type(output)}" + ) + if len(output) == 0: + raise RuntimeError( + f"{api}: Expected output of f to be a non-empty tuple of Tensors." + ) + for out in output: + if isinstance(out, torch.Tensor): + continue + raise RuntimeError( + f"{api}: Expected output of f to be a Tensor or Tensors, got " + f"{type(out)} as an output" + ) + + +def assert_non_empty_list_of_tensors( + output: list[torch.Tensor], api: str, argname: str +) -> None: + if len(output) == 0: + raise RuntimeError(f"{api}: Expected {argname} to contain at least one Tensor.") + for out in output: + if isinstance(out, torch.Tensor): + continue + raise RuntimeError( + f"{api}: Expected {argname} to only contain Tensors, got {type(out)}" + ) + + +jvp_str = "jvp(f, primals, tangents)" + + +def safe_unpack_dual( + dual: torch.Tensor, strict: bool +) -> tuple[torch.Tensor, torch.Tensor]: + if not isinstance(dual, torch.Tensor): + raise RuntimeError( + f"{jvp_str}: expected f(*args) to return only tensors" + f", got unsupported type {type(dual)}" + ) + + primal, tangent = fwAD.unpack_dual(dual) + if tangent is None: + if strict: + raise RuntimeError( + "jvp(f, primals, tangents, strict=True): " + "The output of f is independent of " + "the inputs. This is not allowed with strict=True." + ) + tangent = torch.zeros_like(primal) + return primal, tangent + + +@exposed_in("torch.func") +def jvp( + func: Callable[..., Any], + primals: Any, + tangents: Any, + *, + strict: bool = False, + has_aux: bool = False, +) -> tuple[Any, Any] | tuple[Any, Any, Any]: + """ + Standing for the Jacobian-vector product, returns a tuple containing + the output of `func(*primals)` and the "Jacobian of ``func`` evaluated at + ``primals``" times ``tangents``. This is also known as forward-mode autodiff. + + Args: + func (function): A Python function that takes one or more arguments, + one of which must be a Tensor, and returns one or more Tensors + primals (Tensors): Positional arguments to ``func`` that must all be + Tensors. The returned function will also be computing the + derivative with respect to these arguments + tangents (Tensors): The "vector" for which Jacobian-vector-product is + computed. Must be the same structure and sizes as the inputs to + ``func``. + has_aux (bool): Flag indicating that ``func`` returns a + ``(output, aux)`` tuple where the first element is the output of + the function to be differentiated and the second element is + other auxiliary objects that will not be differentiated. + Default: False. + + Returns: + Returns a ``(output, jvp_out)`` tuple containing the output of ``func`` + evaluated at ``primals`` and the Jacobian-vector product. + If ``has_aux is True``, then instead returns a ``(output, jvp_out, aux)`` tuple. + + .. note:: + You may see this API error out with "forward-mode AD not implemented + for operator X". If so, please file a bug report and we will prioritize it. + + jvp is useful when you wish to compute gradients of a function R^1 -> R^N + + >>> from torch.func import jvp + >>> x = torch.randn([]) + >>> f = lambda x: x * torch.tensor([1.0, 2.0, 3]) + >>> warnings.filterwarnings( + ... "ignore", message=".*torch.jit.script" + ... ) # docs: hide + >>> value, grad = jvp(f, (x,), (torch.tensor(1.0),)) + >>> assert torch.allclose(value, f(x)) + >>> assert torch.allclose(grad, torch.tensor([1.0, 2, 3])) + + :func:`jvp` can support functions with multiple inputs by passing in the + tangents for each of the inputs + + >>> from torch.func import jvp + >>> x = torch.randn(5) + >>> y = torch.randn(5) + >>> f = lambda x, y: (x * y) + >>> _, output = jvp(f, (x, y), (torch.ones(5), torch.ones(5))) + >>> assert torch.allclose(output, x + y) + + """ + + return _jvp_with_argnums( + func, primals, tangents, argnums=None, strict=strict, has_aux=has_aux + ) + + +def _jvp_with_argnums( + func: Callable[..., Any], + primals: Any, + tangents: Any, + argnums: argnums_t | None, + *, + strict: bool = False, + has_aux: bool, +) -> tuple[Any, Any] | tuple[Any, Any, Any]: + # This is the same function as jvp but also accepts an argnums argument + # Most args are the same as jvp except for the added argument + # argnums (int or tuple[int, ...]): Optional, specifies the argument(s) to compute gradients with respect to. + # If None, computes the gradients with respect to all inputs (used for jvp). Default: None + # Because of this, tangents must be of length argnums and matches up to the corresponding primal whose index is + # given by argnums + # + # WARN: Users should NOT call this function directly and should just be calling jvp. + # It is only separated so that inputs passed to jacfwd but not differentiated get the correct wrappers. + # + # NOTE: All error messages are produced as if jvp was being called, even if this was called by jacfwd + # + # Returns the same two elements as :func:`jvp` but the returned tuple, ``jvp_out``, only has JVPs with respect to + # the primals given by argnums + if not isinstance(primals, tuple): + raise RuntimeError( + f"{jvp_str}: Expected primals to be a tuple. " + f"E.g. it should be valid to call f(*primals)." + ) + diff_args = primals if argnums is None else _slice_argnums(primals, argnums) + flat_primals, primals_spec = tree_flatten(diff_args) + flat_tangents, tangents_spec = tree_flatten(tangents) + if primals_spec != tangents_spec: + raise RuntimeError( + f"{jvp_str}: Expected primals and tangents to have the same python " + f"structure. For example, if primals is a tuple of 3 tensors, " + f"tangents also must be. Got primals with structure {primals_spec} " + f"and tangents with structure {tangents_spec}" + ) + assert_non_empty_list_of_tensors(flat_primals, jvp_str, "primals") + assert_non_empty_list_of_tensors(flat_tangents, jvp_str, "tangents") + + global JVP_NESTING + + with jvp_increment_nesting() as level: + with fwAD._set_fwd_grad_enabled(True): + ctx = fwAD.dual_level if JVP_NESTING == 1 else contextlib.nullcontext + with ctx(): + flat_duals = tuple( + fwAD.make_dual(p, t) for p, t in zip(flat_primals, flat_tangents) + ) + duals = tree_unflatten(flat_duals, primals_spec) + if argnums is not None: + primals = _wrap_all_tensors(primals, level) + duals = _replace_args(primals, duals, argnums) + result_duals = func(*duals) + aux: Any = None + if has_aux: + if not (isinstance(result_duals, tuple) and len(result_duals) == 2): + raise RuntimeError( + f"{jvp_str}: output of function f should be a tuple: (output, aux) " + "if has_aux is True" + ) + result_duals, aux = result_duals + aux = _undo_create_differentiable(aux, level) + + result_duals, spec = tree_flatten(result_duals) + assert_non_empty_tensor_output(result_duals, jvp_str) + + primals_out, tangents_out = zip( + *[safe_unpack_dual(dual, strict) for dual in result_duals] + ) + primals_out = tree_map( + partial(_undo_create_differentiable, level=level), primals_out + ) + tangents_out = tree_map( + partial(_undo_create_differentiable, level=level), tangents_out + ) + + primals_out_unflatten = tree_unflatten(primals_out, spec) + tangents_out_unflatten = tree_unflatten(tangents_out, spec) + if has_aux: + return primals_out_unflatten, tangents_out_unflatten, aux # type: ignore[possibly-unbound] + + return primals_out_unflatten, tangents_out_unflatten + + +def safe_unflatten(tensor: torch.Tensor, dim: int, shape: torch.Size) -> torch.Tensor: + if len(shape) == 0: + if tensor.shape[dim] != 1: + raise AssertionError( + f"expected tensor.shape[{dim}] to be 1, got {tensor.shape[dim]}" + ) + return tensor.squeeze(dim) + return tensor.unflatten(dim, shape) + + +@exposed_in("torch.func") +def jacfwd( + func: Callable[..., Any], + argnums: argnums_t = 0, + has_aux: bool = False, + *, + randomness: str = "error", +) -> Callable[..., Any]: + """ + Computes the Jacobian of ``func`` with respect to the arg(s) at index + ``argnum`` using forward-mode autodiff + + Args: + func (function): A Python function that takes one or more arguments, + one of which must be a Tensor, and returns one or more Tensors + argnums (int or tuple[int, ...]): Optional, integer or tuple of integers, + saying which arguments to get the Jacobian with respect to. + Default: 0. + has_aux (bool): Flag indicating that ``func`` returns a + ``(output, aux)`` tuple where the first element is the output of + the function to be differentiated and the second element is + auxiliary objects that will not be differentiated. + Default: False. + randomness(str): Flag indicating what type of randomness to use. + See :func:`vmap` for more detail. Allowed: "different", "same", "error". + Default: "error" + + Returns: + Returns a function that takes in the same inputs as ``func`` and + returns the Jacobian of ``func`` with respect to the arg(s) at + ``argnums``. If ``has_aux is True``, then the returned function + instead returns a ``(jacobian, aux)`` tuple where ``jacobian`` + is the Jacobian and ``aux`` is auxiliary objects returned by ``func``. + + .. note:: + You may see this API error out with "forward-mode AD not implemented + for operator X". If so, please file a bug report and we will prioritize it. + An alternative is to use :func:`jacrev`, which has better operator coverage. + + A basic usage with a pointwise, unary operation will give a diagonal array + as the Jacobian + + >>> from torch.func import jacfwd + >>> x = torch.randn(5) + >>> jacobian = jacfwd(torch.sin)(x) + >>> expected = torch.diag(torch.cos(x)) + >>> assert torch.allclose(jacobian, expected) + + :func:`jacfwd` can be composed with vmap to produce batched + Jacobians: + + >>> from torch.func import jacfwd, vmap + >>> x = torch.randn(64, 5) + >>> jacobian = vmap(jacfwd(torch.sin))(x) + >>> assert jacobian.shape == (64, 5, 5) + + If you would like to compute the output of the function as well as the + jacobian of the function, use the ``has_aux`` flag to return the output + as an auxiliary object: + + >>> from torch.func import jacfwd + >>> x = torch.randn(5) + >>> + >>> def f(x): + >>> return x.sin() + >>> + >>> def g(x): + >>> result = f(x) + >>> return result, result + >>> + >>> jacobian_f, f_x = jacfwd(g, has_aux=True)(x) + >>> assert torch.allclose(f_x, f(x)) + + Additionally, :func:`jacrev` can be composed with itself or :func:`jacrev` + to produce Hessians + + >>> from torch.func import jacfwd, jacrev + >>> def f(x): + >>> return x.sin().sum() + >>> + >>> x = torch.randn(5) + >>> hessian = jacfwd(jacrev(f))(x) + >>> assert torch.allclose(hessian, torch.diag(-x.sin())) + + By default, :func:`jacfwd` computes the Jacobian with respect to the first + input. However, it can compute the Jacobian with respect to a different + argument by using ``argnums``: + + >>> from torch.func import jacfwd + >>> def f(x, y): + >>> return x + y ** 2 + >>> + >>> x, y = torch.randn(5), torch.randn(5) + >>> jacobian = jacfwd(f, argnums=1)(x, y) + >>> expected = torch.diag(2 * y) + >>> assert torch.allclose(jacobian, expected) + + Additionally, passing a tuple to ``argnums`` will compute the Jacobian + with respect to multiple arguments + + >>> from torch.func import jacfwd + >>> def f(x, y): + >>> return x + y ** 2 + >>> + >>> x, y = torch.randn(5), torch.randn(5) + >>> jacobian = jacfwd(f, argnums=(0, 1))(x, y) + >>> expectedX = torch.diag(torch.ones_like(x)) + >>> expectedY = torch.diag(2 * y) + >>> assert torch.allclose(jacobian[0], expectedX) + >>> assert torch.allclose(jacobian[1], expectedY) + + """ + + @_wraps_without_dynamo_attrs(func) + def wrapper_fn(*args: Any) -> Any: + error_if_complex("jacfwd", args, is_input=True) + primals = args if argnums is None else _slice_argnums(args, argnums) + flat_primals, primals_spec = tree_flatten(primals) + flat_primals_numels = tuple(p.numel() for p in flat_primals) + flat_basis = _construct_standard_basis_for(flat_primals, flat_primals_numels) + if flat_basis is None: + raise AssertionError("flat_basis must not be None") + basis = tree_unflatten(flat_basis, primals_spec) + + def push_jvp(basis: Any) -> Any: + output = _jvp_with_argnums( + func, args, basis, argnums=argnums, has_aux=has_aux + ) + # output[0] is the output of `func(*args)` + error_if_complex("jacfwd", output[0], is_input=False) + if has_aux: + _, jvp_out, aux = output # pyrefly: ignore[bad-unpacking] + return jvp_out, aux + _, jvp_out = output # pyrefly: ignore[bad-unpacking] + return jvp_out + + results = vmap(push_jvp, randomness=randomness)(basis) + aux: Any = None + if has_aux: + results, aux = results + # aux is in the standard basis format, e.g. NxN matrix + # We need to fetch the first element as original `func` output + flat_aux, aux_spec = tree_flatten(aux) + flat_aux = [value[0] for value in flat_aux] + aux = tree_unflatten(flat_aux, aux_spec) + + jac_outs, spec = tree_flatten(results) + # Most probably below output check can never raise an error + # as jvp should test the output before + # assert_non_empty_output(jac_outs, 'jacfwd(f, ...)(*args)') + + jac_outs_ins = tuple( + tuple( + safe_unflatten(jac_out_in, -1, primal.shape) + for primal, jac_out_in in zip( + flat_primals, + torch.split( + jac_out.movedim(0, -1), list(flat_primals_numels), dim=-1 + ), + ) + ) + for jac_out in jac_outs + ) + jac_outs_ins = tuple( + tree_unflatten(jac_ins, primals_spec) for jac_ins in jac_outs_ins + ) + + if isinstance(argnums, int): + jac_outs_ins = tuple(jac_ins[0] for jac_ins in jac_outs_ins) + if has_aux: + return tree_unflatten(jac_outs_ins, spec), aux # type: ignore[possibly-unbound] + return tree_unflatten(jac_outs_ins, spec) + + return wrapper_fn + + +@exposed_in("torch.func") +def hessian(func: Callable[..., Any], argnums: argnums_t = 0) -> Callable[..., Any]: + """ + Computes the Hessian of ``func`` with respect to the arg(s) at index + ``argnum`` via a forward-over-reverse strategy. + + The forward-over-reverse strategy (composing ``jacfwd(jacrev(func))``) is + a good default for good performance. It is possible to compute Hessians + through other compositions of :func:`jacfwd` and :func:`jacrev` like + ``jacfwd(jacfwd(func))`` or ``jacrev(jacrev(func))``. + + Args: + func (function): A Python function that takes one or more arguments, + one of which must be a Tensor, and returns one or more Tensors + argnums (int or tuple[int, ...]): Optional, integer or tuple of integers, + saying which arguments to get the Hessian with respect to. + Default: 0. + + Returns: + Returns a function that takes in the same inputs as ``func`` and + returns the Hessian of ``func`` with respect to the arg(s) at + ``argnums``. + + .. note:: + You may see this API error out with "forward-mode AD not implemented + for operator X". If so, please file a bug report and we will prioritize it. + An alternative is to use ``jacrev(jacrev(func))``, which has better + operator coverage. + + A basic usage with a R^N -> R^1 function gives a N x N Hessian: + + >>> from torch.func import hessian + >>> def f(x): + >>> return x.sin().sum() + >>> + >>> x = torch.randn(5) + >>> hess = hessian(f)(x) # equivalent to jacfwd(jacrev(f))(x) + >>> assert torch.allclose(hess, torch.diag(-x.sin())) + + """ + return jacfwd(jacrev(func, argnums), argnums) + + +@doesnt_support_saved_tensors_hooks +def grad_and_value_impl( + func: Callable[..., Any], + argnums: argnums_t, + has_aux: bool, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> tuple[Any, Any]: + with grad_increment_nesting() as level: + output, aux, grad_input = None, None, None + # See NOTE [grad and vjp interaction with no_grad] + with torch.enable_grad(): + args = _wrap_all_tensors(args, level) + kwargs = _wrap_all_tensors(kwargs, level) + diff_args = _slice_argnums(args, argnums, as_tuple=False) + tree_map_(partial(_create_differentiable, level=level), diff_args) + + output = func(*args, **kwargs) + if has_aux: + if not (isinstance(output, tuple) and len(output) == 2): + raise RuntimeError( + "grad_and_value(f)(*args): output of function f should be a tuple: (output, aux) " + "if has_aux is True" + ) + output, aux = output + + if not isinstance(output, torch.Tensor): + raise RuntimeError( + "grad_and_value(f)(*args): Expected f(*args) " + f"to return a Tensor, got {type(output)}" + ) + if output.dim() != 0: + raise RuntimeError( + "grad_and_value(f)(*args): Expected f(*args) " + "to return a scalar Tensor, got tensor with " + f"{output.dim()} dims. Maybe you wanted to " + "use the vjp or jacrev APIs instead?" + ) + + flat_diff_args, spec = tree_flatten(diff_args) + + # NB: need create_graph so that backward pass isn't run in no_grad mode + flat_outputs = _as_tuple(output) + flat_grad_input = _autograd_grad( + flat_outputs, flat_diff_args, create_graph=True + ) + grad_input = tree_unflatten(flat_grad_input, spec) + + grad_input = _undo_create_differentiable(grad_input, level) + output = _undo_create_differentiable(output, level) + if has_aux: + # pyrefly: ignore[bad-specialization] + aux = _undo_create_differentiable(aux, level) + + if has_aux: + return grad_input, (output, aux) + return grad_input, output + + +def grad_impl( + func: Callable[..., Any], + argnums: argnums_t, + has_aux: bool, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> Any: + results = grad_and_value_impl(func, argnums, has_aux, args, kwargs) + if has_aux: + grad, (_, aux) = results + return grad, aux + grad, _ = results + return grad + + +def _maybe_wrap_functional_tensor( + maybe_tensor: Any, level: int, *, _python_functionalize: bool = False +) -> Any: + if not isinstance(maybe_tensor, torch.Tensor): + return maybe_tensor + wrapped = _wrap_functional_tensor(maybe_tensor, level) + _assert_wrapped_functional(maybe_tensor, wrapped) + if _python_functionalize: + # pyrefly: ignore[missing-argument] + out = FunctionalTensor(wrapped) + # pyrefly: ignore[missing-attribute] + torch._mirror_autograd_meta_to(maybe_tensor, out) + return out + return wrapped + + +def _wrap_all_tensors_to_functional( + tensor_pytree: Any, level: int, *, _python_functionalize: bool = False +) -> Any: + return tree_map( + partial( + lambda x: _maybe_wrap_functional_tensor( + x, level, _python_functionalize=_python_functionalize + ) + ), + tensor_pytree, + ) + + +def _maybe_unwrap_functional_tensor(maybe_tensor: Any, *, reapply_views: bool) -> Any: + if not isinstance(maybe_tensor, torch.Tensor): + return maybe_tensor + if isinstance(maybe_tensor, FunctionalTensor): + maybe_tensor = maybe_tensor.elem + + if not torch._is_functional_tensor(maybe_tensor): + # If it's not a functional tensor, just return it. + # This can happen if we functionalize a fn that returns a global, + # which was never wrapped properly. + return maybe_tensor + # Sync any pending updates on the output tensor + torch._sync(maybe_tensor) + return _unwrap_functional_tensor(maybe_tensor, reapply_views) + + +def _unwrap_all_tensors_from_functional( + tensor_pytree: Any, *, reapply_views: bool +) -> Any: + return tree_map( + lambda t: _maybe_unwrap_functional_tensor(t, reapply_views=reapply_views), + tensor_pytree, + ) + + +@exposed_in("torch.func") +def functionalize( + func: Callable[..., Any], *, remove: str = "mutations" +) -> Callable[..., Any]: + """ + functionalize is a transform that can be used to remove (intermediate) + mutations and aliasing from a function, while preserving the function's + semantics. + + ``functionalize(func)`` returns a new function with the same semantics + as ``func``, but with all intermediate mutations removed. + Every inplace operation performed on an intermediate tensor: + ``intermediate.foo_()`` + gets replaced by its out-of-place equivalent: + ``intermediate_updated = intermediate.foo()``. + + functionalize is useful for shipping a pytorch program off to + backends or compilers that aren't able to easily represent + mutations or aliasing operators. + + Args: + func (Callable[..., Any]): A Python function that takes one or more arguments. + remove (str): An optional string argument, that takes on either + the value 'mutations' or 'mutations_and_views'. + If 'mutations' is passed in then all mutating operators + will be replaced with their non-mutating equivalents. + If 'mutations_and_views' is passed in, then additionally, all aliasing + operators will be replaced with their non-aliasing equivalents. + Default: 'mutations'. + + Returns: + Returns a new "functionalized" function. It takes the same inputs as + ``func``, and has the same behavior, but any mutations + (and optionally aliasing) performed on intermediate tensors + in the function will be removed. + + functionalize will also remove mutations (and views) that were performed on function inputs. + However to preserve semantics, functionalize will "fix up" the mutations after + the transform has finished running, by detecting if any tensor inputs "should have" + been mutated, and copying the new data back to the inputs if necessary. + + + Example:: + + >>> # xdoctest: +SKIP + >>> import torch + >>> from torch.fx.experimental.proxy_tensor import make_fx + >>> from torch.func import functionalize + >>> + >>> # A function that uses mutations and views, but only on intermediate tensors. + >>> def f(a): + ... b = a + 1 + ... c = b.view(-1) + ... c.add_(1) + ... return b + ... + >>> inpt = torch.randn(2) + >>> + >>> out1 = f(inpt) + >>> out2 = functionalize(f)(inpt) + >>> + >>> # semantics are the same (outputs are equivalent) + >>> print(torch.allclose(out1, out2)) + True + >>> + >>> f_traced = make_fx(f)(inpt) + >>> f_no_mutations_traced = make_fx(functionalize(f))(inpt) + >>> f_no_mutations_and_views_traced = make_fx(functionalize(f, remove='mutations_and_views'))(inpt) + >>> + >>> print(f_traced.code) + + + + def forward(self, a_1): + add = torch.ops.aten.add(a_1, 1); a_1 = None + view = torch.ops.aten.view(add, [-1]) + add_ = torch.ops.aten.add_(view, 1); view = None + return add + + >>> print(f_no_mutations_traced.code) + + + + def forward(self, a_1): + add = torch.ops.aten.add(a_1, 1); a_1 = None + view = torch.ops.aten.view(add, [-1]); add = None + add_1 = torch.ops.aten.add(view, 1); view = None + view_1 = torch.ops.aten.view(add_1, [2]); add_1 = None + return view_1 + + >>> print(f_no_mutations_and_views_traced.code) + + + + def forward(self, a_1): + add = torch.ops.aten.add(a_1, 1); a_1 = None + view_copy = torch.ops.aten.view_copy(add, [-1]); add = None + add_1 = torch.ops.aten.add(view_copy, 1); view_copy = None + view_copy_1 = torch.ops.aten.view_copy(add_1, [2]); add_1 = None + return view_copy_1 + + + >>> # A function that mutates its input tensor + >>> def f(a): + ... b = a.view(-1) + ... b.add_(1) + ... return a + ... + >>> f_no_mutations_and_views_traced = make_fx(functionalize(f, remove='mutations_and_views'))(inpt) + >>> # + >>> # All mutations and views have been removed, + >>> # but there is an extra copy_ in the graph to correctly apply the mutation to the input + >>> # after the function has completed. + >>> print(f_no_mutations_and_views_traced.code) + + + + def forward(self, a_1): + view_copy = torch.ops.aten.view_copy(a_1, [-1]) + add = torch.ops.aten.add(view_copy, 1); view_copy = None + view_copy_1 = torch.ops.aten.view_copy(add, [2]); add = None + copy_ = torch.ops.aten.copy_(a_1, view_copy_1); a_1 = None + return view_copy_1 + + + There are a few "failure modes" for functionalize that are worth calling out: + (1) Like other torch.func transforms, `functionalize()` doesn't work with functions + that directly use `.backward()`. The same is true for torch.autograd.grad. + If you want to use autograd, you can compute gradients directly + with `functionalize(grad(f))`. + (2) Like other torch.func transforms, `functionalize()` doesn't work with global state. + If you call `functionalize(f)` on a function that takes views / mutations of + non-local state, functionalization will simply no-op and pass the view/mutation + calls directly to the backend. + One way to work around this is to ensure that any non-local state creation + is wrapped into a larger function, which you then call functionalize on. + (3) `resize_()` has some limitations: functionalize will only work on programs + that use resize_()` as long as the tensor being resized is not a view. + (4) `as_strided()` has some limitations: functionalize will not work on + `as_strided()` calls that result in tensors with overlapping memory. + + + Finally, a helpful mental model for understanding functionalization is that + most user pytorch programs are writing with the public torch API. + When executed, torch operators are generally decomposed into + our internal C++ "ATen" API. + The logic for functionalization happens entirely at the level of ATen. + Functionalization knows how to take every aliasing operator in ATen, + and map it to its non-aliasing equivalent + (e.g. ``tensor.view({-1})`` -> ``at::view_copy(tensor, {-1})``), + and how to take every mutating operator in ATen, + and map it to its non-mutating equivalent + (e.g. ``tensor.add_(1)`` -> ``at::add(tensor, -1)``), + while tracking aliases and mutations out-of-line to know when to fix things up. + Information about which ATen operators are aliasing or mutating all comes from + https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/native_functions.yaml. + """ + if remove == "mutations": + reapply_views = True + elif remove == "mutations_and_views": + reapply_views = False + else: + raise RuntimeError( + f"functionalize(f, remove='mutations'): received invalid argument for remove={remove}." + " Valid options are:\n" + " remove='mutations': all inplace and out= operators will be removed from the program, and replaced" + " with their out-of-place equivalents.\n" + " remove='mutations_and_views': In addition to the above, all aliasing operators {view} will be" + " replaced with their non-aliasing counterparts, {view}_copy.\n" + ) + + @_wraps_without_dynamo_attrs(func) + def wrapped(*args: Any, **kwargs: Any) -> Any: + try: + func_level = _func_increment_nesting(reapply_views) + func_args = _wrap_all_tensors_to_functional(args, func_level) + func_kwargs = _wrap_all_tensors_to_functional(kwargs, func_level) + + flattened_unwrapped_args = pytree.arg_tree_leaves(*args) + flattened_wrapped_args = pytree.arg_tree_leaves(*func_args) + flattened_unwrapped_kwargs = pytree.arg_tree_leaves(**kwargs) + flattened_wrapped_kwargs = pytree.arg_tree_leaves(**func_kwargs) + + func_outputs = func(*func_args, **func_kwargs) + outputs = _unwrap_all_tensors_from_functional( + func_outputs, reapply_views=reapply_views + ) + + for a in flattened_wrapped_args + flattened_wrapped_kwargs: + if isinstance(a, torch.Tensor): + # Call sync_() on the inputs, to ensure that any pending mutations have been applied. + torch._sync(a) + + # And if any mutations were applied to the inputs, we need to propagate them back to the user. + for unwrapped, wrapped in zip( + flattened_unwrapped_args, flattened_wrapped_args + ): + if isinstance(unwrapped, torch.Tensor) and isinstance( + wrapped, torch.Tensor + ): + _propagate_functional_input_mutation(unwrapped, wrapped) + for unwrapped, wrapped in zip( + flattened_unwrapped_kwargs, flattened_wrapped_kwargs + ): + if isinstance(unwrapped, torch.Tensor) and isinstance( + wrapped, torch.Tensor + ): + _propagate_functional_input_mutation(unwrapped, wrapped) + + return outputs + finally: + _func_decrement_nesting() + + return wrapped + + +@exposed_in("torch.func") +def linearize( + func: Callable[..., Any], *primals: Any +) -> tuple[Any, Callable[..., Any]]: + """ + Returns the value of ``func`` at ``primals`` and linear approximation + at ``primals``. + + Args: + func (Callable[..., Any]): A Python function that takes one or more arguments. + primals (Tensors): Positional arguments to ``func`` that must all be + Tensors. These are the values at which the function is linearly approximated. + + Returns: + Returns a ``(output, jvp_fn)`` tuple containing the output of ``func`` + applied to ``primals`` and a function that computes the jvp of + ``func`` evaluated at ``primals``. + + linearize is useful if jvp is to be computed multiple times at ``primals``. However, + to achieve this, linearize saves intermediate computation and has higher memory requirements + than directly applying `jvp`. So, if all the ``tangents`` are known, it maybe more efficient + to compute vmap(jvp) instead of using linearize. + + .. note:: + linearize evaluates ``func`` twice. Please file an issue for an implementation + with a single evaluation. + + Example:: + + >>> import torch + >>> from torch.func import linearize + >>> def fn(x): + ... return x.sin() + ... + >>> warnings.filterwarnings("ignore", message=".*Attempted to insert a get_attr Node with no underlying reference") # docs: hide + >>> output, jvp_fn = linearize(fn, torch.zeros(3, 3)) + >>> jvp_fn(torch.ones(3, 3)) + tensor([[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]) + >>> + + """ + # Note: We evaluate `fn` twice. + # Once for returning the output and other while + # tracing the graph. + # If this becomes a bottle-neck, we should update + # make_fx such that it also returns the output. + + output = func(*primals) + _, output_spec = tree_flatten(output) + + flat_primals, primals_argspec = tree_flatten(primals) + + # tangents for tracing + flat_tangents = tuple(p.new_empty(()).expand_as(p) for p in flat_primals) + + # function to trace + def trace_fn(flat_tangents: tuple[torch.Tensor, ...]) -> Any: + with fwAD.dual_level(): + flat_duals = tuple( + fwAD.make_dual(p, t) for p, t in zip(flat_primals, flat_tangents) + ) + duals = tree_unflatten(flat_duals, primals_argspec) + output = func(*duals) + tangents = tree_map_only( + torch.Tensor, lambda dual: safe_unpack_dual(dual, False)[1], output + ) + + return tangents + + jvp_graph = lazy_dynamo_disallow(make_fx)(trace_fn)(flat_tangents) + const_folded_jvp_graph = lazy_dynamo_disallow(const_fold.split_const_subgraphs)( + jvp_graph + ) + + # Hold only the meta-data regarding the primals. + flat_primals_shape = tuple(p.shape for p in flat_primals) + flat_primals_device = tuple(p.device for p in flat_primals) + flat_primals_dtype = tuple(p.dtype for p in flat_primals) + + def forward_ad_checks(flat_tangents: Sequence[torch.Tensor]) -> None: + for idx, t in enumerate(flat_tangents): + if t.shape != flat_primals_shape[idx]: + msg = ( + f"tangent:{idx} with shape {t.shape} in flattened " + f"pytree doesn't match the shape {flat_primals_shape[idx]} " + "of the corresponding primal." + ) + raise RuntimeError(msg) + + if t.device != flat_primals_device[idx]: + msg = ( + f"tangent:{idx} with device {t.device} in flattened " + f"pytree doesn't match the device {flat_primals_device[idx]} " + "of the corresponding primal." + ) + raise RuntimeError(msg) + + if t.dtype != flat_primals_dtype[idx]: + msg = ( + f"tangent:{idx} with dtype {t.dtype} in flattened " + f"pytree doesn't match the dtype {flat_primals_dtype[idx]} " + "of the corresponding primal." + ) + raise RuntimeError(msg) + + # jvp_fn : Callable[..., Any] to return + # It takes care of checking the argspec of tangents, + # calling the folded fx graph and unflattening fx graph output + def jvp_fn(*tangents: Any) -> Any: + flat_tangents, tangent_argspec = tree_flatten(tangents) + if tangent_argspec != primals_argspec: + raise RuntimeError( + f"Expected the tangents {tangent_argspec} to have " + f"the same argspec as the primals {primals_argspec}" + ) + + forward_ad_checks(flat_tangents) # type: ignore[arg-type] + + flat_output = const_folded_jvp_graph(*flat_tangents) + # const folded graph can return flat output, + # so transform output. + return tree_unflatten(flat_output, output_spec) + + return output, jvp_fn + + +@exposed_in("torch.func") +def debug_unwrap(tensor: torch.Tensor, *, recurse: bool = True) -> torch.Tensor: + """Unwraps a functorch tensor (e.g. BatchedTensor, GradTrackingTensor) to its underlying tensor. + + This function should only be used in a debug setting (e.g. trying to print the + value of a Tensor in a debugger). Otherwise, using the result of function + inside of a function being transformed will lead to undefined behavior. + """ + if not is_functorch_wrapped_tensor(tensor): + return tensor + result = get_unwrapped(tensor) + if recurse: + return debug_unwrap(result) + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/einops.py b/.venv/lib/python3.12/site-packages/torch/_functorch/einops.py new file mode 100644 index 0000000000000000000000000000000000000000..0c8a1b2c77ece0773b3fad127a0982e3a1265e28 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/einops.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import torch +from torch._functorch.utils import exposed_in + + +__all__ = ["rearrange"] + + +@exposed_in("torch.func") +def rearrange( + tensor: torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor, ...], + pattern: str, + **axes_lengths: int, +) -> torch.Tensor: + r"""A native implementation of `einops.rearrange`, a reader-friendly smart element reordering for multidimensional + tensors. This operation includes functionality of transpose (axes permutation), reshape (view), squeeze, unsqueeze, + stack, concatenate and other operations. + + See: https://einops.rocks/api/rearrange/ + + Args: + tensor (Tensor or sequence of Tensor): the tensor(s) to rearrange + pattern (str): the rearrangement pattern + axes_lengths (int): any additional length specifications for dimensions + + Returns: + Tensor: the rearranged tensor + + Examples: + >>> from torch.func import rearrange + >>> # suppose we have a set of 32 images in "h w c" format (height-width-channel) + >>> images = torch.randn((32, 30, 40, 3)) + + >>> # stack along first (batch) axis, output is a single array + >>> rearrange(images, "b h w c -> b h w c").shape + torch.Size([32, 30, 40, 3]) + + >>> # concatenate images along height (vertical axis), 960 = 32 * 30 + >>> rearrange(images, "b h w c -> (b h) w c").shape + torch.Size([960, 40, 3]) + + >>> # concatenated images along horizontal axis, 1280 = 32 * 40 + >>> rearrange(images, "b h w c -> h (b w) c").shape + torch.Size([30, 1280, 3]) + + >>> # reordered axes to "b c h w" format for deep learning + >>> rearrange(images, "b h w c -> b c h w").shape + torch.Size([32, 3, 30, 40]) + + >>> # flattened each image into a vector, 3600 = 30 * 40 * 3 + >>> rearrange(images, "b h w c -> b (c h w)").shape + torch.Size([32, 3600]) + + >>> # split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2 + >>> rearrange(images, "b (h1 h) (w1 w) c -> (b h1 w1) h w c", h1=2, w1=2).shape + torch.Size([128, 15, 20, 3]) + + >>> # space-to-depth operation + >>> rearrange(images, "b (h h1) (w w1) c -> b h w (c h1 w1)", h1=2, w1=2).shape + torch.Size([32, 15, 20, 12]) + """ + if not isinstance(tensor, torch.Tensor): + tensor = torch.stack(tensor) + + # Lazy import to avoid circular import: + # torch._functorch.einops -> functorch.einops (package __init__) -> torch._functorch.einops + from functorch.einops.rearrange import _create_rearrange_callable + + rearrange_callable = _create_rearrange_callable( + tensor.ndim, pattern, **axes_lengths + ) + + return rearrange_callable(tensor) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/functional_call.py b/.venv/lib/python3.12/site-packages/torch/_functorch/functional_call.py new file mode 100644 index 0000000000000000000000000000000000000000..051681a044f0b3f35b2a9fd142f37977be8f26c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/functional_call.py @@ -0,0 +1,264 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +import torch +import torch.nn as nn +from torch import Tensor +from torch._functorch.utils import exposed_in + + +@exposed_in("torch.func") +def functional_call( + module: torch.nn.Module, + parameter_and_buffer_dicts: dict[str, Tensor] | Sequence[dict[str, Tensor]], + args: Any = None, + kwargs: dict[str, Any] | None = None, + *, + tie_weights: bool = True, + strict: bool = False, +) -> Any: + r"""Performs a functional call on the module by replacing the module parameters + and buffers with the provided ones. + + .. note:: If the module has active parametrizations, passing a value in the + :attr:`parameter_and_buffer_dicts` argument with the name set to the regular parameter + name will completely disable the parametrization. + If you want to apply the parametrization function to the value passed + please set the key as ``{submodule_name}.parametrizations.{parameter_name}.original``. + + .. note:: If the module performs in-place operations on parameters/buffers, these will be reflected + in the ``parameter_and_buffer_dicts`` input. + + + Example:: + + >>> a = {'foo': torch.zeros(())} + >>> # xdoctest: +SKIP + >>> mod = Foo() # does self.foo = self.foo + 1 + >>> print(mod.foo) # tensor(0.) + >>> functional_call(mod, a, torch.ones(())) + >>> print(mod.foo) # tensor(0.) + >>> print(a['foo']) # tensor(1.) + + .. note:: If the module has tied weights, whether or not functional_call respects the tying is determined by the + tie_weights flag. + + Example:: + + >>> a = {'foo': torch.zeros(())} + >>> # xdoctest: +SKIP + >>> mod = Foo() # has both self.foo and self.foo_tied which are tied. Returns x + self.foo + self.foo_tied + >>> print(mod.foo) # tensor(1.) + >>> mod(torch.zeros(())) # tensor(2.) + >>> functional_call(mod, a, torch.zeros(())) # tensor(0.) since it will change self.foo_tied too + >>> functional_call(mod, a, torch.zeros(()), tie_weights=False) # tensor(1.)--self.foo_tied is not updated + >>> new_a = {'foo': torch.zeros(()), 'foo_tied': torch.zeros(())} + >>> functional_call(mod, new_a, torch.zeros()) # tensor(0.) + + An example of passing multiple dictionaries + + .. code-block:: python + + a = ( + {"weight": torch.ones(1, 1)}, + {"buffer": torch.zeros(1)}, + ) # two separate dictionaries + mod = nn.Bar(1, 1) # return self.weight @ x + self.buffer + print(mod.weight) # tensor(...) + print(mod.buffer) # tensor(...) + x = torch.randn((1, 1)) + print(x) + functional_call(mod, a, x) # same as x + print(mod.weight) # same as before functional_call + + + And here is an example of applying the grad transform over the parameters + of a model. + + .. code-block:: python + + import torch + import torch.nn as nn + from torch.func import functional_call, grad + + x = torch.randn(4, 3) + t = torch.randn(4, 3) + model = nn.Linear(3, 3) + + + def compute_loss(params, x, t): + y = functional_call(model, params, x) + return nn.functional.mse_loss(y, t) + + + grad_weights = grad(compute_loss)(dict(model.named_parameters()), x, t) + + .. note:: If the user does not need grad tracking outside of grad transforms, they can detach all of the + parameters for better performance and memory usage + + Example:: + + >>> detached_params = {k: v.detach() for k, v in model.named_parameters()} + >>> grad_weights = grad(compute_loss)(detached_params, x, t) + >>> grad_weights.grad_fn # None--it's not tracking gradients outside of grad + + This means that the user cannot call ``grad_weight.backward()``. However, if they don't need autograd tracking + outside of the transforms, this will result in less memory usage and faster speeds. + + Args: + module (torch.nn.Module): the module to call + parameters_and_buffer_dicts (Dict[str, Tensor] or tuple of Dict[str, Tensor]): the parameters that will be used in + the module call. If given a tuple of dictionaries, they must have distinct keys so that all dictionaries can + be used together + args (Any or tuple): arguments to be passed to the module call. If not a tuple, considered a single argument. + kwargs (dict): keyword arguments to be passed to the module call + tie_weights (bool, optional): If True, then parameters and buffers tied in the original model will be treated as + tied in the reparameterized version. Therefore, if True and different values are passed for the tied + parameters and buffers, it will error. If False, it will not respect the originally tied parameters and + buffers unless the values passed for both weights are the same. Default: True. + strict (bool, optional): If True, then the parameters and buffers passed in must match the parameters and + buffers in the original module. Therefore, if True and there are any missing or unexpected keys, it will + error. Default: False. + + Returns: + Any: the result of calling ``module``. + """ + if isinstance(parameter_and_buffer_dicts, dict): + parameters_and_buffers = parameter_and_buffer_dicts + elif isinstance(parameter_and_buffer_dicts, Sequence): + if not all(isinstance(d, dict) for d in parameter_and_buffer_dicts): + raise ValueError( + "Expected all elements of parameter_and_buffer_dicts to be dictionaries" + ) + all_keys = [k for d in parameter_and_buffer_dicts for k in d] + all_keys_counter: dict[str, int] = {} + for k in all_keys: + v = all_keys_counter.get(k, 0) + all_keys_counter[k] = v + 1 + repeated_keys = [key for key, n in all_keys_counter.items() if n > 1] + if len(repeated_keys) > 0: + raise ValueError( + f"{repeated_keys} appeared in multiple dictionaries; behavior of functional call is ambiguous" + ) + parameters_and_buffers = { + k: v for d in parameter_and_buffer_dicts for k, v in d.items() + } + else: + raise ValueError( + f"Expected parameter_and_buffer_dicts to be a dict, or a list/tuple of dicts, " + f"but got {type(parameter_and_buffer_dicts)}" + ) + + return nn.utils.stateless._functional_call( + module, + parameters_and_buffers, + args, + kwargs, + tie_weights=tie_weights, + strict=strict, + ) + + +@exposed_in("torch.func") +def stack_module_state( + models: Sequence[nn.Module] | nn.ModuleList, +) -> tuple[dict[str, Any], dict[str, Any]]: + """stack_module_state(models) -> params, buffers + + Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`. + + Given a list of ``M`` ``nn.Modules`` of the same class, returns two dictionaries + that stack all of their parameters and buffers together, indexed by name. + The stacked parameters are optimizable (i.e. they are new leaf nodes in the + autograd history that are unrelated to the original parameters and can be + passed directly to an optimizer). + + Here's an example of how to ensemble over a very simple model: + + .. code-block:: python + + num_models = 5 + batch_size = 64 + in_features, out_features = 3, 3 + models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)] + data = torch.randn(batch_size, 3) + + + def wrapper(params, buffers, data): + return torch.func.functional_call(models[0], (params, buffers), data) + + + params, buffers = stack_module_state(models) + output = vmap(wrapper, (0, 0, None))(params, buffers, data) + + assert output.shape == (num_models, batch_size, out_features) + + When there's submodules, this follows state dict naming conventions + + .. code-block:: python + + import torch.nn as nn + + + class Foo(nn.Module): + def __init__(self, in_features, out_features): + super().__init__() + hidden = 4 + self.l1 = nn.Linear(in_features, hidden) + self.l2 = nn.Linear(hidden, out_features) + + def forward(self, x): + return self.l2(self.l1(x)) + + + num_models = 5 + in_features, out_features = 3, 3 + models = [Foo(in_features, out_features) for i in range(num_models)] + params, buffers = stack_module_state(models) + print(list(params.keys())) # "l1.weight", "l1.bias", "l2.weight", "l2.bias" + + .. warning:: + All of the modules being stacked together must be the same (except for + the values of their parameters/buffers). For example, they should be in the + same mode (training vs eval). + """ + if len(models) == 0: + raise RuntimeError("stack_module_state: Expected at least one model, got 0.") + if not (all(m.training for m in models) or all(not m.training for m in models)): + raise RuntimeError( + "stack_module_state: Expected all models to have the same training/eval mode." + ) + model0_typ = type(models[0]) + if not all(type(m) is model0_typ for m in models): + raise RuntimeError( + "stack_module_state: Expected all models to be of the same class." + ) + all_params = [dict(model.named_parameters()) for model in models] + params = { + k: construct_stacked_leaf(tuple(params[k] for params in all_params), k) + for k in all_params[0] + } + all_buffers = [dict(model.named_buffers()) for model in models] + buffers = { + k: construct_stacked_leaf(tuple(buffers[k] for buffers in all_buffers), k) + for k in all_buffers[0] + } + + return params, buffers + + +def construct_stacked_leaf( + tensors: tuple[Tensor, ...] | list[Tensor], name: str +) -> Tensor: + all_requires_grad = all(t.requires_grad for t in tensors) + none_requires_grad = all(not t.requires_grad for t in tensors) + if not all_requires_grad and not none_requires_grad: + raise RuntimeError( + f"Expected {name} from each model to have the same .requires_grad" + ) + result = torch.stack(tensors) + if all_requires_grad: + result = result.detach().requires_grad_() + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/fx_minifier.py b/.venv/lib/python3.12/site-packages/torch/_functorch/fx_minifier.py new file mode 100644 index 0000000000000000000000000000000000000000..95ddd9ef46afc3cde232fe7d0c3502f4b1cbd8dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/fx_minifier.py @@ -0,0 +1,562 @@ +from __future__ import annotations + +import copy +import math +import os +import sys +from dataclasses import dataclass +from functools import partial, wraps +from typing import Any, TYPE_CHECKING + +import torch +import torch.fx as fx +from torch.hub import tqdm +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._content_store import ContentStoreWriter + +from .compile_utils import get_outputs, get_placeholders + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +is_tuple = object() + + +@dataclass +class LoadTensorMeta: + size: tuple[int, ...] + stride: tuple[int, ...] + dtype: torch.dtype + device: torch.device + + +class ConcreteProp(torch.fx.Interpreter): + def __init__( + self, + mod: fx.GraphModule, + *, + writer: ContentStoreWriter | None = None, + skip_offload: bool = False, + ) -> None: + super().__init__(mod) + self.writer = writer + self.skip_offload = skip_offload + self.seen_storages: set[StorageWeakRef] = set() + self.pbar: Any = None + + def run_node(self, n: fx.Node) -> Any: + self.pbar.update(1) + r = super().run_node(n) + name = n.name + + if isinstance(r, torch.Tensor): + if self.writer is None: + n.meta["concrete_value"] = r + else: + if StorageWeakRef(r.untyped_storage()) in self.seen_storages: + # Refuse to offload tensors which alias other live + # tensors, because this will violate operator contracts + n.meta["concrete_value"] = None + else: + if not self.skip_offload: + self.writer.write_tensor(os.path.join("eager", name), r) + n.meta["concrete_value"] = LoadTensorMeta( + r.size(), r.stride(), r.dtype, r.device + ) + self.seen_storages.add(StorageWeakRef(r.untyped_storage())) + else: + n.meta["concrete_value"] = is_tuple + + return r + + def propagate(self, *args: Any) -> Any: + mod = self.module + if not isinstance(mod, fx.GraphModule): + raise AssertionError(f"expected fx.GraphModule, got {type(mod)}") + with tqdm( + desc="Saving intermediates for delta debugging", + total=len(mod.graph.nodes), + disable=self.writer is None, + ) as pbar: + self.pbar = pbar + r = super().run(*args) + if not self.skip_offload: + pbar.set_description( + "Saved! To skip next time, run with --skip-saving-eager-intermediates" + ) + return r + + +def is_load_tensor_node(node: fx.Node) -> bool: + return ( + node.op == "call_function" + and node.target is torch.ops.debugprims.load_tensor.default + ) + + +# inplace modifies node/inps +def _convert_node_to_placeholder( + graph: fx.Graph, node: fx.Node, inps: list[torch.Tensor] +) -> bool: + if node.op == "output" or node.op == "placeholder": + return False + + if is_load_tensor_node(node): + return False + + concrete_val = node.meta.get("concrete_value", None) + + if isinstance(concrete_val, torch.Tensor): + node.op = "placeholder" + node.target = node.name + node.args = () + node.kwargs = {} + + inps.append(concrete_val) + return True + + elif concrete_val is None: + return False + + elif concrete_val is is_tuple: + r = False + for tuple_user in list(node.users): + r = _convert_node_to_placeholder(graph, tuple_user, inps) or r + # NB: We must not erase the node at this point, because + # we are iterating over the nodes and this would change + # the iteration order + # graph.erase_node(node) + return r + + elif isinstance(concrete_val, LoadTensorMeta): + node.op = "call_function" + node.target = torch.ops.debugprims.load_tensor.default + node.args = ( + os.path.join("eager", node.name), + concrete_val.size, + concrete_val.stride, + ) + node.kwargs = { + "device": concrete_val.device, + "dtype": concrete_val.dtype, + } + return True + + return False + + +def create_minified_hlo_graph( + minified_fx_graph: fx.GraphModule, inputs: Sequence[torch.Tensor] +) -> None: + """ + Takes minified FX graph as primary input, and ports it to HLO via StableHLO + Provides minified HLO graph as output, and archive them to local directory + """ + hlo_dir = f"{os.getcwd()}/hlo_files" + os.makedirs(hlo_dir, exist_ok=True) + + from torch_xla.stablehlo import save_torch_model_as_stablehlo + + save_torch_model_as_stablehlo(minified_fx_graph, inputs, hlo_dir) + + +def dump_state(fx_g: fx.GraphModule, inps: Sequence[torch.Tensor]) -> None: + print( + f""" +# Working Repro with {len(fx_g.graph.nodes)} nodes +inps = {[(i.shape, i.dtype, str(i.device)) for i in inps]} +inps = [torch.zeros(())] + [torch.ones(shape, dtype=dtype, device=device) for (shape, dtype, device) in inps] +{fx_g.code} +""" + ) + + +def is_power_of_two(n: int) -> bool: + if n == 0: + return False + return (n & (n - 1)) == 0 + + +@dataclass +class ReproState: + graph: fx.Graph + inps: Sequence[torch.Tensor] + + def __post_init__(self) -> None: + ph_nodes = get_placeholders(self.graph) + if len(ph_nodes) != len(self.inps): + raise AssertionError( + f"len(ph_nodes)={len(ph_nodes)} != len(self.inps)={len(self.inps)}" + ) + + +def minifier( + fail_f: fx.GraphModule, + inps: Sequence[torch.Tensor], + module_fails: Callable[[fx.GraphModule, Sequence[torch.Tensor]], bool], + dump_state: Callable[[fx.GraphModule, Sequence[torch.Tensor]], None] = dump_state, + *, + save_dir: str | None = None, + offload_to_disk: bool = False, + skip_offload: bool = False, + skip_sanity: bool = False, + max_granularity: int | None = None, +) -> tuple[fx.GraphModule, Sequence[torch.Tensor]]: + """ + Minimizes a FX graph with given inputs, such that the resulting FX graph still returns True for module_fails. + + Does 2 main strategies: + 1. Truncates suffix: Removes some suffix from the graph and sets a new output. + 2. Delta Debugging: Tries replacing half of the graph with inputs. If fails, + tries replacing quarter of the graph, etc. + + >>> # xdoctest: +SKIP(failing) + >>> failing_function = fx.symbolic_trace(f) + >>> minimize(failing_function, [torch.randn(5)], lambda fx_g, inps: fx_g(*inps)) + + note: module_fails returns True if it fails. + """ + + failing_graph = fail_f.graph + cur_size = len(failing_graph.nodes) + + if max_granularity is not None and not is_power_of_two(max_granularity): + raise RuntimeError(f"max_granularity {max_granularity} not power of two") + + num_queries = 0 + + def deepcopy_fx_graph(fx_graph: fx.Graph) -> fx.Graph: + return fx.GraphModule(fail_f, copy.deepcopy(fx_graph)).graph + + def graph_fails(graph: fx.Graph, inps: Sequence[torch.Tensor]) -> bool: + nonlocal num_queries + graph = copy.deepcopy(graph) + num_queries += 1 + mod = fx.GraphModule(fail_f, graph) + mod.graph.lint() + return module_fails(mod, inps) + + writer = None + if offload_to_disk: + if save_dir is None: + raise AssertionError("save_dir must not be None when offload_to_disk=True") + writer = ContentStoreWriter(save_dir) + + ConcreteProp(fail_f, writer=writer, skip_offload=skip_offload).propagate(*inps) + if not skip_sanity and not graph_fails(failing_graph, inps): + raise RuntimeError("Input graph did not fail the tester") + print(f"Started off with {cur_size} nodes", file=sys.stderr) + + def _register_strategy( + strategy: Callable[[fx.Graph, Sequence[torch.Tensor], int], ReproState | None], + name: str, + ) -> Callable[[ReproState, int], ReproState | None]: + @wraps(strategy) + def new_func(old_state: ReproState, granularity: int = 1) -> ReproState | None: + print(file=sys.stderr) + print( + f"Strategy: {name} (G: {granularity}) " + f"({len(old_state.graph.nodes)} nodes, {len(old_state.inps)} inputs)", + file=sys.stderr, + ) + new_state = strategy( + deepcopy_fx_graph(old_state.graph), list(old_state.inps), granularity + ) + if new_state is not None: + new_nodes = len(new_state.graph.nodes) + old_nodes = len(old_state.graph.nodes) + new_inps = len(new_state.inps) + old_inps = len(old_state.inps) + new_outs = len(get_outputs(new_state.graph)) + old_outs = len(get_outputs(old_state.graph)) + progress_made = False + if new_nodes < old_nodes: + progress_made = True + print( + f"SUCCESS: Went from {old_nodes} to {new_nodes} nodes", + file=sys.stderr, + ) + if new_inps > old_inps: + progress_made = True + print( + f"SUCCESS: Went from {old_inps} to {new_inps} inputs", + file=sys.stderr, + ) + if new_outs < old_outs: + progress_made = True + print( + f"SUCCESS: Went from {old_outs} to {new_outs} outputs", + file=sys.stderr, + ) + + if not progress_made: + raise RuntimeError("Success raised but no progress made?") + + if not graph_fails(new_state.graph, new_state.inps): + print( + "WARNING: Something went wrong, not applying this minification", + file=sys.stderr, + ) + return None + return new_state + else: + print(f"FAIL: {name}", file=sys.stderr) + return None + + return new_func + + def register_strategy( + name: str, + ) -> Callable[ + [Callable[[fx.Graph, Sequence[torch.Tensor], int], ReproState | None]], + Callable[[ReproState, int], ReproState | None], + ]: + return partial(_register_strategy, name=name) + + @register_strategy("Truncate suffix") + def remove_suffix( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + tested: set[int] = set() + new_graph = fx.Graph() + env: dict[fx.Node, fx.Node] = {} + for idx, node in enumerate(cur_graph.nodes): + new_node = new_graph.node_copy(node, lambda x: env[x]) + if node.op not in ["placeholder", "output"]: + # If idx is divisible by (granularity * 2), it would have been checked already. + if ( + idx % granularity == 0 + and (idx % (granularity * 2) != 0) + and idx not in tested + ): + output_node = new_graph.output((new_node,)) + if len(new_graph.nodes) < len(cur_graph.nodes) and graph_fails( + new_graph, cur_inps + ): + return ReproState(new_graph, cur_inps) + else: + tested.add(idx) + new_graph.erase_node(output_node) + env[node] = new_node + return None + + @register_strategy("Remove outputs") + def remove_outputs( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + granularity = max(1, granularity // 2) + output: fx.Node | None = None + for idx, node in enumerate(cur_graph.nodes): + node.idx = idx # type: ignore[attr-defined] + if node.op == "output": + output = node + break + + if output is None: + return None + + if isinstance(output.args[0], fx.Node): + return None + + # output.args[0] is a tuple/list of nodes when returning multiple outputs + output_args_raw = output.args[0] + if not isinstance(output_args_raw, (list, tuple)): + raise AssertionError( + f"expected output_args_raw to be list or tuple, got {type(output_args_raw)}" + ) + output_args = sorted( + output_args_raw, + key=lambda x: x.idx if isinstance(x, fx.Node) else int(1e9), # type: ignore[attr-defined] + ) + if len(output_args) == 1: + return None + + for idx in range(0, len(output_args), granularity): + output.args = (output_args[:idx] + output_args[idx + granularity :],) + if graph_fails(cur_graph, cur_inps): + return ReproState(cur_graph, cur_inps) + return None + + def remove_unused_inputs_unchecked(cur_state: ReproState) -> ReproState | None: + cur_graph = cur_state.graph + cur_inps = cur_state.inps + ph_nodes = list(get_placeholders(cur_graph)) + if len(ph_nodes) != len(cur_inps): + raise AssertionError( + f"len(ph_nodes)={len(ph_nodes)} != len(cur_inps)={len(cur_inps)}" + ) + + new_inps: list[torch.Tensor] = [] + for idx in range(len(ph_nodes)): + if len(ph_nodes[idx].users) == 0: + cur_graph.erase_node(ph_nodes[idx]) + else: + new_inps.append(cur_inps[idx]) + if len(new_inps) < len(cur_inps): + return ReproState(cur_graph, new_inps) + return None + + def remove_unused_inputs_checked(cur_state: ReproState) -> ReproState | None: + new_state = remove_unused_inputs_unchecked(cur_state) + if new_state is not None and graph_fails(new_state.graph, new_state.inps): + return new_state + return None + + def _remove_unused_wrapper( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + return remove_unused_inputs_checked(ReproState(cur_graph, cur_inps)) + + remove_unused_inputs = register_strategy("Remove unused inputs")( + _remove_unused_wrapper + ) + + @register_strategy("Eliminate dead code") + def eliminate_dead_code( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + if cur_graph.eliminate_dead_code() and graph_fails(cur_graph, cur_inps): + return ReproState(cur_graph, cur_inps) + return None + + def _consolidate_placeholders( + cur_graph: fx.Graph, inps: list[torch.Tensor] + ) -> fx.Graph: + new_graph = fx.Graph() + env = {} + seen_non_placeholder = False + + # Move all placeholders to the front; also, if any load_tensor + # is at the front, convert it into an input (because it can be live + # all the time) + for node in cur_graph.nodes: + if node.op == "placeholder": + new_node = new_graph.node_copy(node, lambda x: env[x]) + env[node] = new_node + elif not seen_non_placeholder and is_load_tensor_node(node): + new_node = new_graph.placeholder(node.name) + env[node] = new_node + inps.append( + torch.ops.debugprims.load_tensor.default(*node.args, **node.kwargs) + ) + else: + seen_non_placeholder = True + + # Move everyone else + for node in cur_graph.nodes: + if node not in env: + new_node = new_graph.node_copy(node, lambda x: env[x]) + env[node] = new_node + return new_graph + + @register_strategy("Delta Debugging") + def delta_debugging( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + num_nodes = len(cur_graph.nodes) + for start_range in range(0, num_nodes, granularity): + is_removing = False + new_graph = deepcopy_fx_graph(cur_graph) + new_inps = list(cur_inps[:]) + end_range = min(num_nodes, start_range + granularity) + for idx in range(start_range, end_range): + new_node = list(new_graph.nodes)[idx] + if _convert_node_to_placeholder(new_graph, new_node, new_inps): + is_removing = True + if not is_removing: + continue + new_graph.eliminate_dead_code() + new_graph = _consolidate_placeholders(new_graph, new_inps) + new_state = remove_unused_inputs_unchecked(ReproState(new_graph, new_inps)) + if new_state is None: + new_state = ReproState(new_graph, new_inps) + if graph_fails(new_state.graph, new_state.inps): + return ReproState(new_state.graph, new_state.inps) + + return None + + @register_strategy("Consolidate Inputs") + def consolidate_inputs( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + old_len = len(cur_inps) + new_inps = list(cur_inps[:]) + cur_graph = _consolidate_placeholders(cur_graph, new_inps) + if len(cur_inps) > old_len and graph_fails(cur_graph, new_inps): + return ReproState(cur_graph, new_inps) + return None + + failing_state = ReproState(failing_graph, inps) + + def try_granularity( + failing_state: ReproState, granularity: int, use_non_granular: bool + ) -> ReproState | None: + print(f"Trying granularity {granularity}", file=sys.stderr) + + strategies = [] + num_nodes = len(failing_state.graph.nodes) + num_outputs = len(get_outputs(failing_state.graph)) + if num_outputs > num_nodes // 2: + strategies += [remove_outputs] + + if use_non_granular: + strategies += [ + eliminate_dead_code, + remove_unused_inputs, + consolidate_inputs, + ] + + strategies += [remove_suffix, delta_debugging] + + for strategy in strategies: + new_state = strategy(failing_state, granularity) + if new_state is not None: + return new_state + return None + + while True: + dump_state(fx.GraphModule(fail_f, failing_state.graph), failing_state.inps) + granularity = int(2 ** (math.floor(math.log2(len(failing_state.graph.nodes))))) + if max_granularity is not None: + granularity = min(max_granularity, granularity) + new_state = try_granularity(failing_state, granularity, use_non_granular=True) + if new_state is not None: + failing_state = new_state + continue + + granularity //= 2 + has_progress = False + while granularity >= 1: + new_state = try_granularity( + failing_state, granularity, use_non_granular=False + ) + if new_state is not None: + failing_state = new_state + has_progress = True + break + granularity //= 2 + if has_progress: + continue + + new_state = remove_outputs(failing_state, 1) + if new_state is not None: + failing_state = new_state + continue + + break + + if not graph_fails(failing_state.graph, failing_state.inps): + raise RuntimeError("Uh oh, something went wrong :( Final graph is not failing") + + print(f"Made {num_queries} queries", file=sys.stderr) + failing_fx = fx.GraphModule(fail_f, failing_state.graph) + + # If XLA debugging environment is enabled, create minified HLO graph as well + if "XLA_HLO_DEBUG" in os.environ: + create_minified_hlo_graph(failing_fx, failing_state.inps) + + dump_state(failing_fx, failing_state.inps) + print("Wrote minimal repro out to repro.py", file=sys.stderr) + return failing_fx, failing_state.inps diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/make_functional.py b/.venv/lib/python3.12/site-packages/torch/_functorch/make_functional.py new file mode 100644 index 0000000000000000000000000000000000000000..65b77627b1dc8f922d1c511a345859ae9eb60346 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/make_functional.py @@ -0,0 +1,669 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +import copy +from typing import Any, NoReturn, TYPE_CHECKING + +import torch +import torch.nn as nn +from torch import Tensor +from torch.nn.utils._named_member_accessor import NamedMemberAccessor + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + +# Utilities to make nn.Module "functional" +# In particular the goal is to be able to provide a function that takes as input +# the parameters and evaluate the nn.Module using fixed inputs. + + +def raise_parameter_tying_error() -> NoReturn: + raise RuntimeError( + "make_functional(module): we don't yet support models that " + "do parameter tying (also sometimes known as weight sharing). " + "Please try to rewrite your model by replacing all instances of the " + "tied parameter with another and/or comment your support in " + "https://github.com/pytorch/functorch/issues/446" + ) + + +def create_names_map( + named_params: dict[str, Tensor] | Iterable[tuple[str, Tensor]], + tied_named_params: dict[str, Tensor] | Iterable[tuple[str, Tensor]], +) -> dict[str, list[str]]: + """ + named_params is a dictionary of tensors: {'A': A, 'B': B} + tied_named_params is another dictionary of tensors {'A': A, 'B': B, 'B_tied': B} + with potentially tied (or 'duplicated') tensors + + This function creates a mapping from the names in named_params to the + names in tied_named_params: {'A': ['A'], 'B': ['B', 'B_tied']}. + """ + named_params_dict = dict(named_params) + tied_named_params_dict = dict(tied_named_params) + + tensors_dict_keys = set(named_params_dict.keys()) + tied_tensors_dict_keys = set(tied_named_params_dict.keys()) + if not tensors_dict_keys.issubset(tied_tensors_dict_keys): + raise AssertionError( + f"tensors_dict_keys {tensors_dict_keys} is not a subset of " + f"tied_tensors_dict_keys {tied_tensors_dict_keys}" + ) + + tensor_to_mapping: dict[Tensor, tuple[str, list[str]]] = {} + for key, tensor in named_params_dict.items(): + tensor_to_mapping[tensor] = (key, []) + for key, tensor in tied_named_params_dict.items(): + if tensor not in tensor_to_mapping: + raise AssertionError( + f"tensor for key '{key}' not found in tensor_to_mapping" + ) + tensor_to_mapping[tensor][1].append(key) + return dict(tensor_to_mapping.values()) + + +def _extract_members( + mod: nn.Module, + named_members: Callable[..., Iterable[tuple[str, Tensor]]], + subclass: Callable[[Tensor], Tensor], +) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]: + all_named_members = tuple(named_members(remove_duplicate=False)) + unique_named_members = tuple(named_members(remove_duplicate=True)) + names_map = create_names_map(unique_named_members, all_named_members) + + # Remove all the members in the model + # pyrefly: ignore [implicit-any] + memo = {} + accessor = NamedMemberAccessor(mod) + for name, p in all_named_members: + if p not in memo: + memo[p] = subclass(torch.empty_like(p, device="meta")) + replacement = memo[p] + accessor.set_tensor(name, replacement) + + if len(unique_named_members) == 0: + names, params = (), () + else: + names, params = zip(*unique_named_members) # type: ignore[assignment] + return params, names, names_map + + +def extract_weights( + mod: nn.Module, +) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]: + """ + This function removes all the Parameters from the model and + return them as a tuple as well as their original attribute names. + The weights must be re-loaded with `load_weights` before the model + can be used again. + Note that this function modifies the model in place and after this + call, mod.parameters() will be empty. + """ + return _extract_members(mod, mod.named_parameters, nn.Parameter) + + +def extract_buffers( + mod: nn.Module, +) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]: + return _extract_members(mod, mod.named_buffers, lambda x: x) + + +def load_weights( + mod: nn.Module, + names: Sequence[str], + params: Sequence[Tensor], + as_params: bool = False, +) -> None: + """ + Reload a set of weights so that `mod` can be used again to perform a forward pass. + Note that the `params` are regular Tensors (that can have history) and so are left + as Tensors. This means that mod.parameters() will still be empty after this call. + """ + accessor = NamedMemberAccessor(mod) + if as_params: + params = [nn.Parameter(p) for p in params] + accessor.set_tensors(names, params) + + +def _swap_state( + mod: nn.Module, names_map: dict[str, list[str]], elems: Iterable[Tensor] +) -> list[Tensor]: + result: list[Tensor] = [] + accessor = NamedMemberAccessor(mod) + for (_, attr_names), elem in zip(names_map.items(), elems): + for i, attr_name in enumerate(attr_names): + if i == 0: + result.append(accessor.swap_tensor(attr_name, elem)) + else: + accessor.set_tensor(attr_name, elem) + return result + + +def load_buffers( + mod: nn.Module, + names: Sequence[str], + buffers: Sequence[Tensor], + as_params: bool = False, +) -> None: + accessor = NamedMemberAccessor(mod) + accessor.set_tensors(names, buffers) + + +def load_state( + model: nn.Module, + weights: Sequence[Tensor], + weight_names: Sequence[str], + buffers: Sequence[Tensor] = (), + buffer_names: Sequence[str] = (), +) -> nn.Module: + """load_state(model, weights, weight_names, buffers=(), buffer_names=()) -> model + + load_state takes `weights` and `buffers` and assigns them to the model. + This is the inverse operation of `make_functional_deprecated_v1`. + """ + if len(weight_names) != len(weights): + raise AssertionError( + f"len(weight_names)={len(weight_names)} != len(weights)={len(weights)}" + ) + load_weights(model, weight_names, weights) + if len(buffers) > 0: + if len(buffer_names) != len(buffers): + raise AssertionError( + f"len(buffer_names)={len(buffer_names)} != len(buffers)={len(buffers)}" + ) + load_buffers(model, buffer_names, buffers) + return model + + +def make_functional_deprecated_v1( + model: nn.Module, +) -> tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]: + """make_functional_deprecated_v1(model) -> weights, func, weight_names + + Given an nn.Module, make_functional_deprecated_v1 extracts the state (weights) + and returns a functional version of the model, `func`. This makes + it so that it is possible use transforms over the parameters of + `model`. + + `func` can be invoked as follows: + ``` + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + weights, func, _ = make_functional_deprecated_v1(model) + func(weights, (x,)) + ``` + + And here is an example of applying the grad transform: + ``` + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + weights, _, func = make_functional_deprecated_v1(model) + grad_weights = grad(func)(weights, (x,)) + ``` + + To put the state back into a model, use `load_state`. + """ + buffers = list(model.buffers()) + if len(buffers) > 0: + raise RuntimeError( + "make_functional_deprecated_v1(model): `model` has buffers. Please use " + "make_functional_with_buffers_deprecated_v1(model) instead." + ) + weights, descriptors, _ = extract_weights(model) + + def fun(weights: tuple[Tensor, ...], data: tuple[Any, ...]) -> Any: + mutable_model = copy.deepcopy(model) + load_weights(mutable_model, descriptors, weights) + return mutable_model(*data) + + return weights, fun, descriptors + + +def make_functional_with_buffers_deprecated_v1( + model: nn.Module, +) -> tuple[ + tuple[Tensor, ...], + tuple[Tensor, ...], + Callable[..., Any], + tuple[str, ...], + tuple[str, ...], +]: + """make_functional_with_buffers_deprecated_v1(model) -> weights, buffers, func, weight_names, buffer_names + + Given an nn.Module, make_functional_with_buffers_deprecated_v1 extracts the state (weights and buffers) + and returns a functional version of the model, `func`. + + `func` can be invoked as follows: + ``` + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + weights, buffers, func, _, _ = make_functional_with_buffers_deprecated_v1(model) + func(weights, buffers, (x,)) + ``` + + And here is an example of applying the grad transform: + ``` + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + weights, buffers, func, _, _ = make_functional_with_buffers_deprecated_v1(model) + func(weights, buffers, (x,)) + grad_weights = grad(func)(weights, buffers, (x,)) + ``` + + To put the state back into a model, use `load_state`. + """ + weights, weight_descriptors, _ = extract_weights(model) + buffers, buf_descriptors, _ = extract_buffers(model) + + def fun( + weights: tuple[Tensor, ...], + buffers: tuple[Tensor, ...], + data: tuple[Any, ...], + ) -> Any: + mutable_model = copy.deepcopy(model) + load_weights(mutable_model, weight_descriptors, weights) + load_buffers(mutable_model, buf_descriptors, buffers) + return mutable_model(*data) + + return weights, buffers, fun, weight_descriptors, buf_descriptors + + +class FunctionalModuleWithBuffers(nn.Module): + """ + This is the callable object returned by :func:`make_functional_with_buffers`. + """ + + def __init__( + self, + stateless_model: nn.Module, + param_names: tuple[str, ...], + buffer_names: tuple[str, ...], + param_names_map: dict[str, list[str]], + buffer_names_map: dict[str, list[str]], + ) -> None: + super().__init__() + self.stateless_model = stateless_model + self.param_names = param_names + self.buffer_names = buffer_names + + self.all_names_map = dict(param_names_map) + self.all_names_map.update(buffer_names_map) + + @staticmethod + def _create_from( + model: nn.Module, disable_autograd_tracking: bool = False + ) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]: + # TODO: We don't need to copy the model to create a stateless copy + model_copy = copy.deepcopy(model) + params, param_names, param_names_map = extract_weights(model_copy) + buffers, buffer_names, buffer_names_map = extract_buffers(model_copy) + if disable_autograd_tracking: + for param in params: + param.requires_grad_(False) + return ( + FunctionalModuleWithBuffers( + model_copy, param_names, buffer_names, param_names_map, buffer_names_map + ), + params, + buffers, + ) + + def forward( + self, + params: Iterable[Tensor], + buffers: Iterable[Tensor], + *args: Any, + **kwargs: Any, + ) -> Any: + # Temporarily load the state back onto self.stateless_model + old_state = _swap_state( + self.stateless_model, + self.all_names_map, + tuple(params) + tuple(buffers), + ) + try: + return self.stateless_model(*args, **kwargs) + finally: + # Remove the loaded state on self.stateless_model + _swap_state(self.stateless_model, self.all_names_map, old_state) + + +class FunctionalModule(nn.Module): + """ + This is the callable object returned by :func:`make_functional`. + """ + + def __init__( + self, + stateless_model: nn.Module, + param_names: tuple[str, ...], + names_map: dict[str, list[str]], + ) -> None: + super().__init__() + self.stateless_model = stateless_model + self.param_names = param_names + self.names_map = names_map + + @staticmethod + def _create_from( + model: nn.Module, disable_autograd_tracking: bool = False + ) -> tuple[FunctionalModule, tuple[Tensor, ...]]: + # TODO: We don't need to copy the model to create a stateless copy + model_copy = copy.deepcopy(model) + params, param_names, names_map = extract_weights(model_copy) + if disable_autograd_tracking: + for param in params: + param.requires_grad_(False) + return FunctionalModule(model_copy, param_names, names_map), params + + def forward(self, params: Iterable[Tensor], *args: Any, **kwargs: Any) -> Any: + # Temporarily load the state back onto self.stateless_model + old_state = _swap_state(self.stateless_model, self.names_map, params) + try: + return self.stateless_model(*args, **kwargs) + finally: + # Remove the loaded state on self.stateless_model + _swap_state(self.stateless_model, self.names_map, old_state) + + +def make_functional( + model: nn.Module, disable_autograd_tracking: bool = False +) -> tuple[FunctionalModule, tuple[Tensor, ...]]: + """make_functional(model, disable_autograd_tracking=False) -> func, params + + Given a ``torch.nn.Module``, :func:`make_functional` extracts the state + (params) and returns a functional version of the model, ``func``. This + makes it so that it is possible use transforms over the parameters of + ``model``. + + ``func`` can be invoked as follows: + + .. code-block:: python + + import torch + import torch.nn as nn + from functorch import make_functional + + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + func, params = make_functional(model) + func(params, x) + + And here is an example of applying the grad transform over the parameters + of a model. + + .. code-block:: python + + import torch + import torch.nn as nn + from functorch import make_functional, grad + + x = torch.randn(4, 3) + t = torch.randn(4, 3) + model = nn.Linear(3, 3) + func, params = make_functional(model) + + + def compute_loss(params, x, t): + y = func(params, x) + return nn.functional.mse_loss(y, t) + + + grad_weights = grad(compute_loss)(params, x, t) + + If the model has any buffers, please use :func:`make_functional_with_buffers` instead. + + Args: + model (torch.nn.Module): Input model. + disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters. + The returned params are unrelated to the set of params from the original model. If False (default), + the params will have ``requires_grad=True`` on them (aka they will be trackable with regular + PyTorch autograd), matching the requires_grad-ness of the params from the original model. + Otherwise, the returned params will have ``requires_grad=False``. Default, False. + If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or + ``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``. + Otherwise, if you're only planning on using functorch's gradient transforms, + then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking + history with PyTorch autograd. + + """ + buffers = list(model.buffers()) + if len(buffers) > 0: + raise RuntimeError( + "make_functional(model): `model` has buffers. Please use " + "make_functional_with_buffers(model) instead." + ) + return FunctionalModule._create_from( + model, disable_autograd_tracking=disable_autograd_tracking + ) + + +def make_functional_with_buffers( + model: nn.Module, disable_autograd_tracking: bool = False +) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]: + """make_functional_with_buffers(model, disable_autograd_tracking=False) -> func, params, buffers + + Given a ``torch.nn.Module``, make_functional_with_buffers extracts the + state (params and buffers) and returns a functional version of the model + ``func`` that can be invoked like a function. + + ``func`` can be invoked as follows: + + .. code-block:: python + + import torch + import torch.nn as nn + from functorch import make_functional_with_buffers + + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + func, params, buffers = make_functional_with_buffers(model) + func(params, buffers, x) + + And here is an example of applying the grad transform over the parameters + of a model: + + .. code-block:: python + + import torch + import torch.nn as nn + from functorch import make_functional_with_buffers, grad + + x = torch.randn(4, 3) + t = torch.randn(4, 3) + model = nn.Linear(3, 3) + func, params, buffers = make_functional_with_buffers(model) + + + def compute_loss(params, buffers, x, t): + y = func(params, buffers, x) + return nn.functional.mse_loss(y, t) + + + grad_weights = grad(compute_loss)(params, buffers, x, t) + + Args: + model (torch.nn.Module): Input model. + disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters. + The returned params are unrelated to the set of params from the original model. If False (default), + the params will have ``requires_grad=True`` on them (aka they will be trackable with regular + PyTorch autograd), matching the requires_grad-ness of the params from the original model. + Otherwise, the returned params will have ``requires_grad=False``. Default, False. + If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or + ``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``. + Otherwise, if you're only planning on using functorch's gradient transforms, + then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking + history with PyTorch autograd. + + """ + return FunctionalModuleWithBuffers._create_from( + model, disable_autograd_tracking=disable_autograd_tracking + ) + + +def transpose_stack( + tuple_of_tuple_of_tensors: tuple[tuple[Tensor, ...], ...], +) -> tuple[Tensor, ...]: + tuple_of_tuple_of_tensors = tuple(zip(*tuple_of_tuple_of_tensors)) + results = tuple( + torch.stack(shards).detach() for shards in tuple_of_tuple_of_tensors + ) + return results + + +def combine_state_for_ensemble( + models: Sequence[nn.Module], +) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]: + """combine_state_for_ensemble(models) -> func, params, buffers + + Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`. + + Given a list of ``M`` ``nn.Modules`` of the same class, stacks all of their + parameters and buffers together to make ``params`` and ``buffers``. + Each parameter and buffer in the result will have an additional dimension + of size ``M``. + + :func:`combine_state_for_ensemble` also returns ``func``, a functional + version of one of the models in :attr:`models`. One cannot directly run + ``func(params, buffers, *args, **kwargs)`` directly, you probably want to + use ``vmap(func, ...)(params, buffers, *args, **kwargs)`` + + Here's an example of how to ensemble over a very simple model: + + .. code-block:: python + + num_models = 5 + batch_size = 64 + in_features, out_features = 3, 3 + models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)] + data = torch.randn(batch_size, 3) + + fmodel, params, buffers = combine_state_for_ensemble(models) + output = vmap(fmodel, (0, 0, None))(params, buffers, data) + + assert output.shape == (num_models, batch_size, out_features) + + .. warning:: + All of the modules being stacked together must be the same (except for + the values of their parameters/buffers). For example, they should be in the + same mode (training vs eval). + + This API is subject to change -- we're investigating better ways to + create ensembles and would love your feedback how to improve this. + """ + if len(models) == 0: + raise RuntimeError( + "combine_state_for_ensemble: Expected at least one model, got 0." + ) + if not (all(m.training for m in models) or all(not m.training for m in models)): + raise RuntimeError( + "combine_state_for_ensemble: Expected all models to " + "have the same training/eval mode." + ) + model0_typ = type(models[0]) + if not all(type(m) is model0_typ for m in models): + raise RuntimeError( + "combine_state_for_ensemble: Expected all models to be of the same class." + ) + funcs, params, buffers = zip( + *[make_functional_with_buffers(model) for model in models] + ) + params = transpose_stack(params) + buffers = transpose_stack(buffers) + return funcs[0], params, buffers + + +def functional_init( + model_class: type[nn.Module], + ensemble_shape: tuple[()] | tuple[int, ...] = (), + device: torch.types.Device = "cpu", +) -> Callable[..., tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]]: + def wrapped( + *args: Any, **kwargs: Any + ) -> tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]: + if len(ensemble_shape) >= 2: + raise ValueError("NYI: ensemble_shape with more than 1 element") + if len(ensemble_shape) == 0: + model = model_class(*args, **kwargs).to(device) + return make_functional_deprecated_v1(model) + num_models = ensemble_shape[0] # type: ignore[misc] + if num_models <= 0: + raise ValueError(f"num_models {num_models} should be > 0") + # NB: Not very efficient, more of a POC + models = tuple( + model_class(*args, **kwargs).to(device) for _ in range(num_models) + ) + _, fn, names = make_functional_deprecated_v1(model_class(*args, **kwargs)) + weights = tuple(make_functional_deprecated_v1(model)[0] for model in models) + weights = tuple(zip(*weights)) + weights = tuple(torch.stack(shards).detach() for shards in weights) + return weights, fn, names + + return wrapped + + +def functional_init_with_buffers( + model_class: type[nn.Module], + ensemble_shape: tuple[()] | tuple[int, ...] = (), + device: torch.types.Device = "cpu", +) -> Callable[ + ..., + tuple[ + tuple[Tensor, ...], + tuple[Tensor, ...], + Callable[..., Any], + tuple[str, ...], + tuple[str, ...], + ] + | tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]], +]: + def wrapped( + *args: Any, **kwargs: Any + ) -> ( + tuple[ + tuple[Tensor, ...], + tuple[Tensor, ...], + Callable[..., Any], + tuple[str, ...], + tuple[str, ...], + ] + | tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]] + ): + if len(ensemble_shape) >= 2: + raise ValueError("NYI: ensemble_shape with more than 1 element") + if len(ensemble_shape) == 0: + model = model_class(*args, **kwargs).to(device) + return make_functional_deprecated_v1(model) + num_models = ensemble_shape[0] # type: ignore[misc] + if num_models <= 0: + raise ValueError(f"num_models {num_models} should be > 0") + # NB: Not very efficient, more of a POC + models = tuple( + model_class(*args, **kwargs).to(device) for _ in range(num_models) + ) + ( + _, + _, + fn, + weight_names, + buffer_names, + ) = make_functional_with_buffers_deprecated_v1(model_class(*args, **kwargs)) + weights, buffers = zip( + *tuple( + make_functional_with_buffers_deprecated_v1(model)[:2] + for model in models + ) + ) + weights = tuple(zip(*weights)) + weights = tuple(torch.stack(shards).detach() for shards in weights) + buffers = tuple(zip(*buffers)) + buffers = tuple(torch.stack(shards).detach() for shards in buffers) + return weights, buffers, fn, weight_names, buffer_names + + return wrapped diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/partitioners.py b/.venv/lib/python3.12/site-packages/torch/_functorch/partitioners.py new file mode 100644 index 0000000000000000000000000000000000000000..528f27550aa8acc31afd437d469f09f5e8d495aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/partitioners.py @@ -0,0 +1,4407 @@ +from __future__ import annotations + +import copy +import functools +import hashlib +import heapq +import itertools +import logging +import math +import operator +import os +import os.path +import re +import warnings +from collections import defaultdict, deque +from collections.abc import Callable, Iterator +from dataclasses import dataclass, replace +from typing import Any, cast, TYPE_CHECKING + +import sympy + +import torch +import torch._inductor.inductor_prims +import torch.distributed +import torch.fx as fx +import torch.utils._pytree as pytree +from torch._dynamo.utils import counters, is_node_meta_valid +from torch._functorch._activation_checkpointing.ac_logging_utils import ( + create_structured_trace_for_min_cut_info, +) +from torch._functorch._aot_autograd.streams import _SYNC_OPS +from torch._functorch._aot_autograd.utils import is_with_effects +from torch._inductor import config as inductor_config +from torch._inductor.custom_graph_pass import ( + CustomKnapsackSolver, + CustomRuntimeEstimator, +) +from torch._inductor.fx_passes.control_dependencies import ( + control_deps as control_deps_hop, + get_subgraph_name, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_opaque_value +from torch._library.utils import is_builtin +from torch._logging import LazyString, trace_structured +from torch._logging._internal import trace_log +from torch._subclasses.fake_tensor import extract_tensor_metadata +from torch._subclasses.meta_utils import is_sparse_any +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import is_sym_node, py_sym_types +from torch.fx.experimental.sym_node import magic_methods, method_to_operator, SymNode +from torch.fx.experimental.symbolic_shapes import ( + _get_placeholder_expr, + find_symbol_binding_fx_nodes, + free_symbols, + is_symbol_binding_fx_node, + is_symbolic, + optimization_hint, + statically_known_false, + statically_known_true, +) +from torch.fx.passes import graph_drawer +from torch.fx.traceback import _get_memory_budget_annotation +from torch.utils._ordered_set import OrderedSet +from torch.utils.checkpoint import CheckpointPolicy + +from . import config +from ._activation_checkpointing.graph_info_provider import GraphInfoProvider +from ._activation_checkpointing.knapsack import ( + dp_knapsack, + dp_knapsack_sliding_hirschberg, + greedy_knapsack, + ilp_knapsack, +) +from ._activation_checkpointing.knapsack_evaluator import KnapsackEvaluator +from ._aot_autograd.descriptors import ( + AOTOutput, + SavedForBackwardsAOTOutput, + SavedForBackwardsNoVcCheckAOTOutput, +) +from ._aot_autograd.functional_utils import _is_functional_graph +from ._aot_autograd.graph_compile import is_opaque_node +from ._aot_autograd.logging_utils import get_aot_graph_name +from ._aot_autograd.utils import ( + _is_bwd_seed_offset, + _is_fwd_seed_offset, + _is_primal, + _is_tangent, + get_default_generator, + get_device_rng_state, + supports_graphsafe_rng, +) +from .compile_utils import fx_graph_cse, get_aten_target, raise_getitems + + +if TYPE_CHECKING: + import networkx as nx + + +AOT_PARTITIONER_DEBUG: bool = config.debug_partitioner +log: logging.Logger = logging.getLogger(__name__) + +aten = torch.ops.aten +prims = torch.ops.prims + + +@dataclass +class OpTypes: + """Class for keeping track of different operator categories""" + + fusible_ops: OrderedSet[Callable[..., Any]] + compute_intensive_ops: OrderedSet[Callable[..., Any]] + random_ops: OrderedSet[Callable[..., Any]] + view_ops: OrderedSet[Callable[..., Any]] + recomputable_ops: OrderedSet[Callable[..., Any]] + + def is_fusible(self, node: fx.Node) -> bool: + return get_aten_target(node) in self.fusible_ops + + def is_compute_intensive(self, node: fx.Node) -> bool: + return get_aten_target(node) in self.compute_intensive_ops + + def is_random(self, node: fx.Node) -> bool: + return get_aten_target(node) in self.random_ops + + def is_view(self, node: fx.Node) -> bool: + return get_aten_target(node) in self.view_ops + + def is_recomputable(self, node: fx.Node) -> bool: + return get_aten_target(node) in self.recomputable_ops + + +@dataclass +class NodeInfo: + # Be careful about iterating over these explicitly, as their order may not + # be deterministic + inputs: list[fx.Node] + _required_fw_nodes: OrderedSet[fx.Node] + required_bw_nodes: OrderedSet[fx.Node] + tangents_closure: OrderedSet[fx.Node] + unclaimed_nodes: OrderedSet[fx.Node] + fw_order: dict[fx.Node, int] + # Effectively maps to which of our primals are parameters + static_lifetime_input_nodes: OrderedSet[fx.Node] + + @functools.cached_property + def required_fw_nodes(self) -> list[fx.Node]: + return sorted( + (n for n in self._required_fw_nodes), key=lambda n: self.fw_order[n] + ) + + def is_required_fw(self, n: fx.Node) -> bool: + return n in self._required_fw_nodes + + def is_required_bw(self, n: fx.Node) -> bool: + return n in self.required_bw_nodes + + def is_unclaimed(self, n: fx.Node) -> bool: + return n in self.unclaimed_nodes + + def get_fw_order(self, n: fx.Node) -> int: + if n not in self._required_fw_nodes: + raise AssertionError(f"Node {n} not in fw nodes!") + return self.fw_order[n] + + +@dataclass +class MinCutOptions: + ban_if_used_far_apart: bool + ban_if_long_fusible_chains: bool + ban_if_materialized_backward: bool + ban_if_not_in_allowlist: bool + ban_if_reduction: bool + + +def must_recompute(node: fx.Node) -> bool: + return node.meta.get("recompute", None) in [ + CheckpointPolicy.MUST_RECOMPUTE, + CheckpointPolicy.PREFER_RECOMPUTE, + ] + + +def get_schema_arg_idx(target: object, arg_name: str) -> int | None: + """Return the positional schema index for an operator argument name.""" + if not isinstance(target, torch._ops.OpOverload): + return None + for idx, arg in enumerate(target._schema.arguments): + if arg.name == arg_name: + return idx + return None + + +def is_nonzero_dropout_sdpa(node: fx.Node) -> bool: + """Return True unless SDPA-family dropout is statically known to be disabled.""" + target = node.target + if not isinstance(target, torch._ops.OpOverload): + return True + + dropout_arg_idx = get_schema_arg_idx(target, "dropout_p") + if dropout_arg_idx is None: + return True + + dropout_arg = target._schema.arguments[dropout_arg_idx] + if len(node.args) > dropout_arg_idx: + dropout_p = node.args[dropout_arg_idx] + elif "dropout_p" in node.kwargs: + dropout_p = node.kwargs["dropout_p"] + elif dropout_arg.default_value is not None: + dropout_p = dropout_arg.default_value + else: + return True + + return not statically_known_true(cast(bool | torch.SymBool, dropout_p == 0.0)) + + +def is_rng_op(node: fx.Node) -> bool: + """Return True when a node's seeded nondeterminism cannot be statically ruled out.""" + if not ( + hasattr(node.target, "tags") + and torch.Tag.nondeterministic_seeded in node.target.tags + ): + return False + + if get_schema_arg_idx(node.target, "dropout_p") is not None: + return is_nonzero_dropout_sdpa(node) + + return True + + +def _is_assert_only_symbool(node: fx.Node) -> bool: + return ( + isinstance(node.meta.get("val"), torch.SymBool) + and len(node.users) > 0 + and all( + user.target is torch.ops.aten._assert_scalar.default for user in node.users + ) + ) + + +def has_recomputable_ops(fx_g: fx.GraphModule) -> bool: + for node in fx_g.graph.nodes: + if must_recompute(node): + return True + return False + + +def has_recomputable_rng_ops(fx_g: fx.GraphModule) -> bool: + for node in fx_g.graph.nodes: + if must_recompute(node) and is_rng_op(node): + return True + return False + + +def sym_node_size(node: fx.Node) -> int: + if isinstance(node.meta["val"], (torch.SymInt, torch.SymBool)): + return 1 + if not isinstance(node.meta["val"], torch.SymFloat): + raise AssertionError( + f"expected node.meta['val'] to be SymFloat, got {type(node.meta['val'])}" + ) + return 4 + + +class InvalidNodeBase: + def __repr__(self) -> str: + return "Invalid Node" + + +# Run DCE while overriding the definition of is_impure_node +def is_not_collective(node: fx.Node) -> bool: + return getattr(node.target, "namespace", None) != "_c10d_functional" + + +InvalidNode = InvalidNodeBase() + + +def _get_ho_op_original_input(getitem_node: fx.Node) -> fx.Node | None: + """Given a getitem node, check if it extracts from a higher-order op + that has kwargs mapping the key back to an original input. + + Returns the original input node if found, None otherwise. + """ + if getitem_node.target != operator.getitem: + return None + ho_result = getitem_node.args[0] + key = getitem_node.args[1] + if not isinstance(ho_result, fx.Node) or ho_result.op != "call_function": + return None + if "kwargs" not in ho_result.kwargs: + return None + kwargs = ho_result.kwargs["kwargs"] + # pyrefly: ignore [not-iterable, unsupported-operation] + if key not in kwargs: + return None + # pyrefly: ignore [bad-index, unsupported-operation] + original_input = kwargs[key] + if isinstance(original_input, fx.Node): + return original_input + return None + + +def _is_copy_node_bw_only(node: fx.Node) -> fx.Node | None: + """Check if node is a view/reshape of a higher-order op output that aliases an input. + + Returns the original input node from the higher-order op's kwargs if the pattern + matches, None otherwise. + """ + if node.target not in (torch.ops.aten.view.default, torch.ops.aten.reshape.default): + return None + source = node.args[0] + if not isinstance(source, fx.Node): + return None + return _get_ho_op_original_input(source) + + +def _find_input_for_invalid_output( + node: fx.Node, + env: dict[fx.Node, Any], +) -> fx.Node | None: + """Try to find a valid input replacement for an invalid forward output. + + This handles cases where a forward output depends on backward nodes but + semantically aliases an input. For example, a view of a getitem from a + triton kernel that mutates a buffer in backward, or a direct getitem from + such a higher-order op. The original input may be a primal or a valid + intermediate node already present in the forward graph. + """ + # Pattern 1: view/reshape(getitem(ho_op, key)) -> ho_op.kwargs["kwargs"][key] + original_input = _is_copy_node_bw_only(node) + if ( + original_input is not None + and original_input in env + and not isinstance(env[original_input], InvalidNodeBase) + ): + return env[original_input] + # Pattern 2: getitem(ho_op, key) -> ho_op.kwargs["kwargs"][key] + original_input = _get_ho_op_original_input(node) + if ( + original_input is not None + and original_input in env + and not isinstance(env[original_input], InvalidNodeBase) + ): + return env[original_input] + return None + + +def _control_deps_has_sync_op(node: fx.Node) -> bool: + """Check if a control_deps node's subgraph has a sync operation.""" + sg_node = node.args[1] + if not ( + isinstance(sg_node, fx.Node) + and sg_node.op == "get_attr" + and isinstance(sg_node.target, str) + ): + raise AssertionError(f"expected get_attr subgraph node, got {sg_node}") + owning_mod = node.graph.owning_module + if owning_mod is None: + raise AssertionError("expected graph to have an owning_module") + sg_mod = getattr(owning_mod, sg_node.target) + if not isinstance(sg_mod, fx.GraphModule): + raise AssertionError(f"expected GraphModule, got {type(sg_mod)}") + return any( + n.op == "call_function" and n.target in _SYNC_OPS for n in sg_mod.graph.nodes + ) + + +def _build_see_through_map(cd_node: fx.Node) -> dict[int, fx.Node]: + """Build a mapping from getitem indices to underlying dep nodes. + + For a control_deps(additional_deps, subgraph, *deps), getitem index k + (k >= 1) corresponds to deps[k-1] which is args[k+1]. + """ + deps = cd_node.args[2:] + return {i + 1: dep for i, dep in enumerate(deps) if isinstance(dep, fx.Node)} + + +def _try_clone_subgraph_filtering_deps( + original_sg_mod: fx.GraphModule, + valid_dep_indices: list[int], +) -> tuple[fx.Graph, dict[int, int]] | None: + """Clone a control_deps subgraph, keeping only valid-dep placeholders. + + Preserves any call_function nodes (the side-effecting operation) as long + as all placeholders they reference are in the valid set. Returns + (new_graph, idx_remap) where idx_remap maps old getitem indices to new + ones, or None if the operation uses an invalid dep. + """ + orig_phs = original_sg_mod.graph.find_nodes(op="placeholder") + valid_dep_set = OrderedSet(valid_dep_indices) + dropped_phs = OrderedSet( + [ph for i, ph in enumerate(orig_phs) if i not in valid_dep_set] + ) + + for n in original_sg_mod.graph.nodes: + if n.op == "call_function": + if any(inp in dropped_phs for inp in n.all_input_nodes): + return None + + sg = fx.Graph() + sg_env: dict[fx.Node, fx.Node] = {} + for n in original_sg_mod.graph.nodes: + if n.op == "output" or n in dropped_phs: + continue + sg_env[n] = sg.node_copy(n, lambda x, _env=sg_env: _env[x]) + + orig_out_arg = original_sg_mod.graph.output_node().args[0] + if isinstance(orig_out_arg, tuple): + sg.output( + tuple( + sg_env[item] if isinstance(item, fx.Node) else item + for item in orig_out_arg + if not isinstance(item, fx.Node) or item in sg_env + ) + ) + elif isinstance(orig_out_arg, fx.Node) and orig_out_arg in sg_env: + sg.output(sg_env[orig_out_arg]) + else: + sg.output(orig_out_arg) + + preserved_op = any(n.op == "call_function" for n in sg.nodes) + idx_remap: dict[int, int] = { + old_i + 1: new_j + 1 for new_j, old_i in enumerate(valid_dep_indices) + } + if preserved_op: + idx_remap[0] = 0 + return sg, idx_remap + + +def _rebuild_control_deps_for_extract( + node: fx.Node, + env: dict[fx.Node, Any], + new_graph: fx.Graph, +) -> tuple[fx.Node, dict[int, int]] | None: + """Rebuild a control_deps node with only valid deps for graph extraction. + + When a control_deps node mixes valid (forward) and invalid (backward) args, + this creates a new control_deps in new_graph with only the valid deps and a + matching subgraph. Returns (new_node, idx_remap) where idx_remap maps old + getitem indices to new getitem indices, or None if no valid deps remain. + + additional_deps (args[0]) and deps (args[2:]) are filtered independently -- + additional_deps are ordering-only constraints and may reference nodes that + are not in the deps set. + """ + deps = node.args[2:] + valid_dep_indices = [ + i + for i, dep in enumerate(deps) + if isinstance(dep, fx.Node) and not isinstance(env.get(dep), InvalidNodeBase) + ] + if not valid_dep_indices: + return None + + # pyrefly: ignore [bad-index] + new_deps = tuple(env[deps[i]] for i in valid_dep_indices) + + additional_deps = node.args[0] + if not isinstance(additional_deps, (tuple, list)): + raise AssertionError( + f"expected tuple/list additional_deps, got {type(additional_deps)}" + ) + valid_additional_deps = tuple( + env[d] + for d in additional_deps + if isinstance(d, fx.Node) and not isinstance(env.get(d), InvalidNodeBase) + ) + + owning_mod = node.graph.owning_module + if owning_mod is None: + raise AssertionError("expected graph to have an owning_module") + + sg_node = node.args[1] + if not ( + isinstance(sg_node, fx.Node) + and sg_node.op == "get_attr" + and isinstance(sg_node.target, str) + ): + raise AssertionError(f"expected get_attr subgraph node, got {sg_node}") + original_sg_mod = getattr(owning_mod, sg_node.target) + if not isinstance(original_sg_mod, fx.GraphModule): + raise AssertionError(f"expected GraphModule, got {type(original_sg_mod)}") + + result = _try_clone_subgraph_filtering_deps(original_sg_mod, valid_dep_indices) + if result is not None: + sg, idx_remap = result + else: + sg = fx.Graph() + sg_placeholders = [sg.placeholder(f"dep_{i}") for i in range(len(new_deps))] + sg.output((None, *sg_placeholders)) + idx_remap = { + old_i + 1: new_j + 1 for new_j, old_i in enumerate(valid_dep_indices) + } + + sg_name = get_subgraph_name(owning_mod, "cd_extract") + setattr(owning_mod, sg_name, fx.GraphModule(torch.nn.Module(), sg)) + new_sg_node = new_graph.get_attr(sg_name) + + new_cd = new_graph.create_node( + "call_function", + control_deps_hop, + args=(valid_additional_deps, new_sg_node, *new_deps), + name=node.name, + ) + new_cd.meta = node.meta.copy() + if "val" in node.meta and isinstance(node.meta["val"], tuple): + orig_val = node.meta["val"] + new_cd.meta["val"] = (orig_val[0],) + tuple( + orig_val[i + 1] for i in valid_dep_indices if i + 1 < len(orig_val) + ) + + return new_cd, idx_remap + + +def _extract_graph_with_inputs_outputs( + joint_graph: fx.Graph, + inputs: list[fx.Node], + outputs: list[fx.Node], + outputs_descs: list[AOTOutput], + subgraph: str | None = None, + ignore_must_be_in_fw_bw: bool = False, +) -> fx.Graph: + """ + Given a graph, extracts out a subgraph that takes the specified nodes as + inputs and returns the specified outputs. + + This includes specifying non-placeholder nodes as inputs. + + The general strategy is to initialize all inputs with proxies as we + encounter them, and trace through the graph, only keeping values which take + in valid proxies. Then, all dead code is eliminated. + """ + new_graph = fx.Graph() + env: dict[fx.Node, fx.Node] = {} + # For control_deps nodes with mixed valid/invalid args, we create a new + # control_deps with only the valid deps. This dict maps the original + # control_deps node to a {old_getitem_idx: new_getitem_idx} remapping so + # downstream getitem nodes can be rewritten to the correct indices. + _control_deps_idx_remap: dict[fx.Node, dict[int, int]] = {} + # For forward sync control_deps eliminated during backward extraction, + # maps the control_deps node to {getitem_idx: joint_graph_dep_node}. + # Getitems resolve directly to env[dep_node], bypassing the control_deps. + _control_deps_see_through: dict[fx.Node, dict[int, fx.Node]] = {} + + # Add new placeholder nodes in the order specified by the inputs + for node in inputs: + new_node = new_graph.placeholder(node.name) + # Can't use node_copy here as we may be turning previous call_function into placeholders + new_node.meta = node.meta + # pyrefly: ignore [unsupported-operation] + env[node] = new_node + + for node in joint_graph.nodes: + if not ignore_must_be_in_fw_bw: + if ( + _must_be_in_backward(node) + and subgraph != "backward" + and node not in inputs + ): + env[node] = InvalidNode # type: ignore[assignment] + continue + + if ( + _must_be_in_forward(node) + and subgraph != "forward" + and node not in inputs + ): + env[node] = InvalidNode # type: ignore[assignment] + continue + + if node in env: + # Node must be one of our inputs. (Any member of env which wasn't an + # input to start must have been created by this loop and won't be in + # joint_graph.nodes). + continue + elif node.op == "placeholder": + env[node] = InvalidNode # type: ignore[assignment] + elif node.op == "call_function": + if ( + node.target is operator.getitem + and node.args[0] in _control_deps_see_through + ): + dep_map = _control_deps_see_through[node.args[0]] + idx = node.args[1] + if idx in dep_map: + env[node] = env[dep_map[idx]] + else: + env[node] = InvalidNode # type: ignore[assignment] + continue + if ( + node.target is operator.getitem + and node.args[0] in _control_deps_idx_remap + ): + idx_map = _control_deps_idx_remap[node.args[0]] + idx = node.args[1] + if idx in idx_map: + new_idx = idx_map[idx] + new_getitem = new_graph.create_node( + "call_function", + operator.getitem, + args=(env[node.args[0]], new_idx), + name=node.name, + ) + new_getitem.meta = node.meta + env[node] = new_getitem + else: + env[node] = InvalidNode # type: ignore[assignment] + continue + + all_args = pytree.arg_tree_leaves(*node.args, **node.kwargs) + all_args = [ + isinstance(env[x], InvalidNodeBase) + for x in all_args + if isinstance(x, fx.Node) + ] + if any(all_args): + if node.target is control_deps_hop: + # During backward extraction, eliminate forward sync + # control_deps entirely -- their subgraphs reference + # forward-only runtime state (streams/events) that is + # dead at backward time. Getitems are resolved directly + # to the underlying deps via _control_deps_see_through. + if ( + subgraph == "backward" + and not ( + _has_tag_is_backward(node) + or _has_tag_must_be_in_backward(node) + ) + and _control_deps_has_sync_op(node) + ): + _control_deps_see_through[node] = _build_see_through_map(node) + env[node] = InvalidNode # type: ignore[assignment] + continue + new_cd_node = _rebuild_control_deps_for_extract( + node, env, new_graph + ) + if new_cd_node is not None: + env[node] = new_cd_node[0] + _control_deps_idx_remap[node] = new_cd_node[1] + continue + env[node] = InvalidNode # type: ignore[assignment] + continue + # During backward extraction, eliminate forward sync control_deps + # entirely. See above for rationale. + if ( + node.target is control_deps_hop + and subgraph == "backward" + and not ( + _has_tag_is_backward(node) or _has_tag_must_be_in_backward(node) + ) + and _control_deps_has_sync_op(node) + ): + _control_deps_see_through[node] = _build_see_through_map(node) + env[node] = InvalidNode # type: ignore[assignment] + continue + # pyrefly: ignore [unsupported-operation, bad-argument-type] + env[node] = new_graph.node_copy(node, lambda x: env[x]) + elif node.op == "get_attr": + # pyrefly: ignore [unsupported-operation, bad-argument-type] + env[node] = new_graph.node_copy(node, lambda x: env[x]) + elif node.op == "output": + pass + output_values = [] + for x, x_desc in zip(outputs, outputs_descs): + if isinstance(x, fx.Node): + if x not in env: + raise RuntimeError(f"Node {x} couldn't be found in env") + if isinstance(env[x], InvalidNodeBase): + # For forward outputs that are invalid (depend on backward), try + # to find a valid replacement. + replacement = None + # For copy_ nodes that are backward-only, use the destination + # (first arg) which is the original input. + if ( + x.target is torch.ops.aten.copy_.default + and _must_be_in_backward(x) + and len(x.args) >= 1 + and isinstance(x.args[0], fx.Node) + and x.args[0] in env + and not isinstance(env[x.args[0]], InvalidNodeBase) + ): + replacement = env[x.args[0]] + # For view/reshape outputs that trace back to a getitem of a + # higher-order op that mutates an input, find that input. + # This handles custom_function_view outputs from triton kernels. + if replacement is None: + replacement = _find_input_for_invalid_output(x, env) + if replacement is not None: + output_values.append(replacement) + continue + raise AssertionError(f"Node {x} was invalid, but is output") + output_values.append(env[x]) + else: + output_values.append(x) + out = new_graph.output(tuple(output_values)) + out.meta["desc"] = outputs_descs + # Snapshot stack traces on the output node before passes run, + # as later passes may strip stack_trace from individual nodes. + out.meta["output_stack_traces"] = [ + v.meta.get("stack_trace") if isinstance(v, fx.Node) else None + for v in output_values + ] + + new_graph.eliminate_dead_code() + new_graph.lint() + return new_graph + + +def is_non_builtin_to_include(node: fx.Node) -> bool: + return config.is_non_builtin_to_include and ( + (isinstance(node.target, torch._ops.OpOverload) and not is_builtin(node.target)) + or node.target == torch.ops.higher_order.triton_kernel_wrapper_functional + ) + + +def _is_backward_state(node: fx.Node) -> bool: + return node.op == "placeholder" and isinstance(node.meta.get("val"), BackwardState) + + +def _has_tag_is_backward(node: fx.Node) -> bool: + return node.meta.get("partitioner_tag", None) == "is_backward" + + +def _has_tag_is_forward(node: fx.Node) -> bool: + return node.meta.get("partitioner_tag", None) == "is_forward" + + +def _has_tag_must_be_in_forward(node: fx.Node) -> bool: + return node.meta.get("partitioner_tag", None) == "must_be_in_forward" + + +def _has_tag_must_be_in_backward(node: fx.Node) -> bool: + return node.meta.get("partitioner_tag", None) == "must_be_in_backward" + + +def _must_be_in_forward(node: fx.Node) -> bool: + if _has_tag_must_be_in_forward(node): + return True + + is_mutable = ( + isinstance(node.target, torch._ops.OpOverload) + and node.target._schema.is_mutable + ) + return ( + not _has_tag_is_backward(node) + and not _has_tag_must_be_in_backward(node) + and is_mutable + ) + + +def _must_be_in_backward(node: fx.Node) -> bool: + if _has_tag_must_be_in_backward(node): + return True + is_mutable = ( + isinstance(node.target, torch._ops.OpOverload) + and node.target._schema.is_mutable + ) + return _has_tag_is_backward(node) and is_mutable + + +def _iter_input_exprs_without_replacements(val: Any) -> Iterator[sympy.Basic]: + # Keep this traversal in sync with symbolic_shapes._iterate_exprs. + if isinstance(val, py_sym_types): + if is_symbolic(val): + yield _get_placeholder_expr(val.node) + elif isinstance(val, SymNode): + yield _get_placeholder_expr(val) + elif isinstance(val, sympy.Basic): + yield val + elif isinstance(val, (int, float, bool, str)): + pass + elif isinstance(val, (tuple, list)): + for s in val: + yield from _iter_input_exprs_without_replacements(s) + elif isinstance(val, dict): + for s in itertools.chain(val.keys(), val.values()): + yield from _iter_input_exprs_without_replacements(s) + elif is_sparse_any(val): + yield from _iter_input_exprs_without_replacements(val.size()) + elif isinstance(val, torch.Tensor): + yield from _iter_input_exprs_without_replacements(val.size()) + yield from _iter_input_exprs_without_replacements(val.stride()) + yield from _iter_input_exprs_without_replacements(val.storage_offset()) + elif val is None: + pass + elif isinstance(val, torch.Generator) or is_opaque_value(val): + pass + elif isinstance(val, FakeScriptObject): + pass + else: + raise AssertionError(f"cannot extract sympy expressions from {val} {type(val)}") + + +def _free_symbols_without_replacements(val: Any) -> OrderedSet[sympy.Symbol]: + symbols: OrderedSet[sympy.Symbol] = OrderedSet() + for expr in _iter_input_exprs_without_replacements(val): + symbols.update(expr.free_symbols) + return symbols + + +def _extract_fwd_bwd_outputs( + joint_module: fx.GraphModule, *, num_fwd_outputs: int +) -> tuple[list[fx.Node], list[fx.Node], list[AOTOutput], list[AOTOutput]]: + outputs = pytree.arg_tree_leaves( + *(node.args for node in joint_module.graph.find_nodes(op="output")) + ) + outputs_descs = pytree.arg_tree_leaves( + next(iter(joint_module.graph.find_nodes(op="output"))).meta.get( + "desc", [None] * len(outputs) + ) + ) + fwd_outputs = outputs[:num_fwd_outputs] + bwd_outputs = outputs[num_fwd_outputs:] + fwd_outputs_descs = outputs_descs[:num_fwd_outputs] + bwd_outputs_descs = outputs_descs[num_fwd_outputs:] + return fwd_outputs, bwd_outputs, fwd_outputs_descs, bwd_outputs_descs + + +def _remove_by_name(saved_values: list[fx.Node], name: str) -> None: + for saved_value in saved_values: + if saved_value.name == name: + saved_values.remove(saved_value) + break + + +def find_first_sym_node( + fwd_module_outputs: list[fx.Node] | tuple[fx.Node, ...], +) -> int: + idx = len(fwd_module_outputs) + for i in range(len(fwd_module_outputs) - 1, -1, -1): + if not is_sym_node(fwd_module_outputs[i]): + idx = i + 1 + break + return idx + + +def calculate_quantization_scaling( + graph: torch.fx.Graph, + node: torch.fx.Node, + max: float = 57344.0, + min: float = 1e-12, + position: int = 0, +) -> torch.fx.Node: + with graph.inserting_after(node): + abs_node = graph.call_function( + torch.ops.aten.abs.default, + args=(node,), + ) + abs_node.meta["val"] = torch.ops.aten.abs.default(node.meta["val"]) + abs_node.meta["tensor_meta"] = extract_tensor_metadata(abs_node.meta["val"]) + with graph.inserting_after(abs_node): + amax_node = graph.call_function( + torch.ops.aten.amax.default, + args=(abs_node, [-1], True), + ) + amax_node.meta["val"] = torch.ops.aten.amax.default( + abs_node.meta["val"], [-1], True + ) + amax_node.meta["tensor_meta"] = extract_tensor_metadata(amax_node.meta["val"]) + with graph.inserting_after(amax_node): + amax_64_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(amax_node, torch.float64), + ) + amax_64_node.meta["val"] = torch.ops.prims.convert_element_type.default( + amax_node.meta["val"], torch.float64 + ) + amax_64_node.meta["tensor_meta"] = extract_tensor_metadata( + amax_64_node.meta["val"] + ) + with graph.inserting_after(amax_64_node): + clamp_min_node = graph.call_function( + torch.ops.aten.clamp_min.default, + args=(amax_64_node, min), + ) + clamp_min_node.meta["val"] = torch.ops.aten.clamp_min.default( + amax_64_node.meta["val"], min + ) + clamp_min_node.meta["tensor_meta"] = extract_tensor_metadata( + clamp_min_node.meta["val"] + ) + with graph.inserting_after(clamp_min_node): + reciprocal_node = graph.call_function( + torch.ops.aten.reciprocal.default, + args=(clamp_min_node,), + ) + reciprocal_node.meta["val"] = torch.ops.aten.reciprocal.default( + clamp_min_node.meta["val"] + ) + reciprocal_node.meta["tensor_meta"] = extract_tensor_metadata( + reciprocal_node.meta["val"] + ) + with graph.inserting_after(reciprocal_node): + mul_node = graph.call_function( + torch.ops.aten.mul.Tensor, + args=(reciprocal_node, max), + ) + mul_node.meta["val"] = torch.ops.aten.mul.Tensor( + reciprocal_node.meta["val"], max + ) + mul_node.meta["tensor_meta"] = extract_tensor_metadata(mul_node.meta["val"]) + with graph.inserting_after(mul_node): + scale_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(mul_node, torch.float32), + name=f"fp8_scale_pos_{position}_{node.name}", + ) + scale_node.meta["val"] = torch.ops.prims.convert_element_type.default( + mul_node.meta["val"], torch.float32 + ) + scale_node.meta["tensor_meta"] = extract_tensor_metadata(scale_node.meta["val"]) + return scale_node + + +def perform_quantization( + graph: torch.fx.Graph, + node: torch.fx.Node, + scale_node: torch.fx.Node, + quant_type: torch.dtype, + clamp_min: float, + clamp_max: float, + position: int, +) -> torch.fx.Node: + with graph.inserting_after(scale_node): + target_node_32 = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(node, torch.float32), + ) + target_node_32.meta["val"] = torch.ops.prims.convert_element_type.default( + node.meta["val"], torch.float32 + ) + target_node_32.meta["tensor_meta"] = extract_tensor_metadata( + target_node_32.meta["val"] + ) + with graph.inserting_after(target_node_32): + scaled_target_node = graph.call_function( + torch.ops.aten.mul.Tensor, + args=(target_node_32, scale_node), + ) + scaled_target_node.meta["val"] = torch.ops.aten.mul.Tensor( + target_node_32.meta["val"], scale_node.meta["val"] + ) + scaled_target_node.meta["tensor_meta"] = extract_tensor_metadata( + scaled_target_node.meta["val"] + ) + with graph.inserting_after(scaled_target_node): + clamp_min_scaled_node = graph.call_function( + torch.ops.aten.clamp_min.default, + args=(scaled_target_node, clamp_min), + ) + clamp_min_scaled_node.meta["val"] = torch.ops.aten.clamp_min.default( + scaled_target_node.meta["val"], clamp_min + ) + clamp_min_scaled_node.meta["tensor_meta"] = extract_tensor_metadata( + clamp_min_scaled_node.meta["val"] + ) + with graph.inserting_after(clamp_min_scaled_node): + clamp_max_scaled_node = graph.call_function( + torch.ops.aten.clamp_max.default, + args=(clamp_min_scaled_node, clamp_max), + ) + clamp_max_scaled_node.meta["val"] = torch.ops.aten.clamp_max.default( + clamp_min_scaled_node.meta["val"], clamp_max + ) + clamp_max_scaled_node.meta["tensor_meta"] = extract_tensor_metadata( + clamp_max_scaled_node.meta["val"] + ) + with graph.inserting_after(clamp_max_scaled_node): + quant_activation_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(clamp_max_scaled_node, quant_type), + name=f"fp8_quant_pos_{position}_{node.name}", + ) + quant_activation_node.meta["val"] = ( + torch.ops.prims.convert_element_type.default( + clamp_max_scaled_node.meta["val"], quant_type + ) + ) + quant_activation_node.meta["tensor_meta"] = extract_tensor_metadata( + quant_activation_node.meta["val"] + ) + return quant_activation_node + + +def calculate_tensor_size(tensor: torch.Tensor) -> float: + """ + Calculate the size of a PyTorch tensor in megabytes (MB). + + Args: + tensor (torch.Tensor): Input tensor + + Returns: + float: Memory size in MB + """ + # Get number of elements and size per element + num_elements = tensor.numel() + element_size = tensor.element_size() + + return (num_elements * element_size) / (1024 * 1024) + + +def get_allowed_dtypes() -> list[torch.dtype]: + allowed_dtypes = torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("allowed_dtypes", "torch.bfloat16") + allowed_dtypes = [ + getattr(torch, dtype.split(".")[-1]) for dtype in allowed_dtypes.split(";") + ] + return allowed_dtypes + + +def should_quantize(node: torch.fx.Node) -> bool: + allowed_dtypes = get_allowed_dtypes() + if not is_node_meta_valid(node) or node.meta["val"].dtype not in allowed_dtypes: + return False + size_threshold = torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("size_in_mb", 100) + # calculate the size of the node + size_in_mb = calculate_tensor_size(node.meta["val"]) + if not torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("skip_dynamo_guards", False): + return size_in_mb >= size_threshold + else: + # case 1: we always quantize tensors with dynamic shapes + if torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("quantize_dynamic_shape", False): + return statically_known_true( + size_in_mb >= size_threshold + ) or not statically_known_false(size_in_mb >= size_threshold) + else: + # case 2: we always not quantize tensors with dynamic shapes + return statically_known_true(size_in_mb >= size_threshold) + + +def get_quant_type() -> torch.dtype: + quant_type = torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("quant_type", "torch.float8_e5m2") + + return getattr(torch, quant_type.split(".")[-1]) + + +def calculate_range(dtype: torch.dtype) -> tuple[float, float]: + """ + Calculate the range of values for a given torch.dtype. + Args: + dtype (torch.dtype): The input dtype. + Returns: + tuple: A tuple containing the minimum and maximum values. + """ + info = torch.finfo(dtype) + return info.min, info.max + + +def quantize_activation_fw(graph: torch.fx.Graph, num_fwd_outputs: int = 0) -> None: + output = graph.find_nodes(op="output")[0] + fwd_outputs = output.args[0] + quant_type = get_quant_type() + clamp_min, clamp_max = calculate_range(quant_type) + position_to_quant = dict() + tensor_scale_nodes: list[fx.Node] = [] + sym_scale_nodes: list[fx.Node] = [] + for position, node in enumerate(fwd_outputs): + # Don't quantize user-visible forward outputs. A tensor may appear as + # both a user output and a saved-for-backward activation (same FX node + # at two positions). Quantizing the user output position would: + # 1. Return fp8 to the user instead of the original precision + # 2. Create duplicate fp8_quant/fp8_scale backward placeholders that + # shift the stride mapping in _aot_stage2b_bw_compile (T264303372) + if position < num_fwd_outputs: + continue + # check if the activation node is the node saved for quantization + if node.meta.get("saved_for_quantization", False): + # case: use scaling + if torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("use_scaling", True): + # calculating the scale + scale_node = calculate_quantization_scaling( + graph, node, clamp_max, 1e-12, position + ) + + # converting to fp8 + quant_node = perform_quantization( + graph, node, scale_node, quant_type, clamp_min, clamp_max, position + ) + if not is_sym_node(scale_node): + tensor_scale_nodes.append(scale_node) + else: + sym_scale_nodes.append(scale_node) + else: + # case: do not use scaling + with graph.inserting_after(node): + quant_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(node, quant_type), + name=f"fp8_quant_pos_{position}_{node.name}", + ) + quant_node.meta["val"] = ( + torch.ops.prims.convert_element_type.default( + node.meta["val"], quant_type + ) + ) + quant_node.meta["tensor_meta"] = extract_tensor_metadata( + quant_node.meta["val"] + ) + + position_to_quant[position] = quant_node + + # Use position-based lookup for building output + # only update the return node args, and remain all other users unchanged + output_updated_args = [ + position_to_quant.get(i, node) for i, node in enumerate(fwd_outputs) + ] + # add the scale nodes to the output find the first sym_node in the output + # pyrefly: ignore [bad-argument-type] + idx = find_first_sym_node(output_updated_args) + scale_nodes = tensor_scale_nodes + sym_scale_nodes + if scale_nodes: + output_updated_args = ( + output_updated_args[:idx] + scale_nodes + output_updated_args[idx:] + ) + + output.update_arg(0, tuple(output_updated_args)) + counters["inductor"]["activation_quantization_fwd_aten_pass"] += 1 + + +def quantize_activation_bw(graph: torch.fx.Graph) -> None: + bw_inputs = [node for node in graph.nodes if node.op == "placeholder"] + activation_node = None + for node in bw_inputs: + if node.meta.get("saved_for_quantization", False): + node.meta.pop("saved_for_quantization") + dequant_type = node.meta.pop("dequant_type") + # dequantize the node + if torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("use_scaling", False): + # case: use scaling + with graph.inserting_after(node): + # find corresponding scale node + scale_name = "fp8_scale_" + node.name.replace("fp8_quant_", "") + scale_node = next( + bwd_input + for bwd_input in bw_inputs + if bwd_input.name == scale_name + ) + with graph.inserting_after(scale_node): + activation_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(node, dequant_type), + ) + activation_node.meta["val"] = ( + torch.ops.prims.convert_element_type.default( + node.meta["val"], dequant_type + ) + ) + activation_node.meta["tensor_meta"] = extract_tensor_metadata( + activation_node.meta["val"] + ) + with graph.inserting_after(activation_node): + divided_target_node_32 = graph.call_function( + torch.ops.aten.div.Tensor, + args=(activation_node, scale_node), + ) + divided_target_node_32.meta["val"] = torch.ops.aten.div.Tensor( + activation_node.meta["val"], scale_node.meta["val"] + ) + divided_target_node_32.meta["tensor_meta"] = ( + extract_tensor_metadata(divided_target_node_32.meta["val"]) + ) + with graph.inserting_after(divided_target_node_32): + dequant_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(divided_target_node_32, dequant_type), + ) + dequant_node.meta["val"] = ( + torch.ops.prims.convert_element_type.default( + divided_target_node_32.meta["val"], dequant_type + ) + ) + dequant_node.meta["tensor_meta"] = extract_tensor_metadata( + dequant_node.meta["val"] + ) + else: + with graph.inserting_after(node): + dequant_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(node, dequant_type), + name="dequant_" + str(node.name), + ) + dequant_node.meta["val"] = ( + torch.ops.prims.convert_element_type.default( + node.meta["val"], dequant_type + ) + ) + dequant_node.meta["tensor_meta"] = extract_tensor_metadata( + dequant_node.meta["val"] + ) + # find the users of the node and replace them with the new node except the dequant_node + for user in list(node.users.keys()): + if user != dequant_node and user != activation_node: + user.replace_input_with(node, dequant_node) + + counters["inductor"]["activation_quantization_bwd_aten_pass"] += 1 + + +def perform_fp8_activation_quantization( + fwd_module: fx.GraphModule, + bwd_module: fx.GraphModule, + bwd_module_inputs: dict[str, fx.Node], + num_fwd_outputs: int = 0, +) -> None: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "before_activation_quantization_fwd_aten_pass", + "encoding": "string", + }, + payload_fn=lambda: fwd_module.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + quantize_activation_fw(fwd_module.graph, num_fwd_outputs) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "after_activation_quantization_fwd_aten_pass", + "encoding": "string", + }, + payload_fn=lambda: fwd_module.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "before_activation_quantization_bwd_aten_pass", + "encoding": "string", + }, + payload_fn=lambda: bwd_module.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + quant_fwd_module_outputs = fwd_module.graph.find_nodes(op="output")[0].args[0] + # update the corresponding bwd_inputs due to the fwd_outputs quantization + for fwd_node in quant_fwd_module_outputs: + if "fp8_quant_" in fwd_node.name: + bwd_input = bwd_module_inputs[ + re.sub(r"^fp8_quant_pos_\d+_", "", fwd_node.name) + ] + with bwd_module.graph.inserting_after(bwd_input): + quant_bwd_input = bwd_module.graph.placeholder(name=fwd_node.name) + dequant_type = bwd_input.meta["dequant_type"] + quant_bwd_input.meta.update(fwd_node.meta) + quant_bwd_input.meta["saved_for_quantization"] = True + quant_bwd_input.meta["dequant_type"] = dequant_type + bwd_input.replace_all_uses_with(quant_bwd_input) + bwd_module.graph.erase_node(bwd_input) + # update the bwd_inputs if quantization with scaling is used + if torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("use_scaling", True): + quant_bwd_module_inputs = list(bwd_module.graph.find_nodes(op="placeholder")) + # update the corresponding bwd input nodes find the last non-tangent node + bwd_input_loc = quant_bwd_module_inputs[-1] + for bw_input in reversed(quant_bwd_module_inputs): + if not _is_tangent(bw_input): + bwd_input_loc = bw_input + break + + scaled_fwd_module_outputs = fwd_module.graph.find_nodes(op="output")[0].args[0] + for fwd_node in scaled_fwd_module_outputs: + if "fp8_scale_" in fwd_node.name: + # fwd node is a scale node + with bwd_module.graph.inserting_after(bwd_input_loc): + scale_bwd_input = bwd_module.graph.placeholder(name=fwd_node.name) + scale_bwd_input.meta.update(fwd_node.meta) + bwd_input_loc = scale_bwd_input + + quantize_activation_bw(bwd_module.graph) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "after_activation_quantization_bwd_aten_pass", + "encoding": "string", + }, + payload_fn=lambda: bwd_module.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + +def enable_activation_quantization( + saved_values: list[fx.Node], + fwd_module: fx.GraphModule, + bwd_module: fx.GraphModule, + static_lifetime_input_nodes: OrderedSet[fx.Node] | None = None, + num_fwd_outputs: int = 0, +) -> None: + static_input_names: list[str] = ( + [node.name for node in static_lifetime_input_nodes] + if static_lifetime_input_nodes + else [] + ) + saved_values_names = {node.name: node for node in saved_values} + if torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("exclude_primals", False): + saved_values_names = { + node.name: node for node in saved_values if "primals" not in node.name + } + fwd_module_outputs = fwd_module.graph.find_nodes(op="output")[0].args[0] + bwd_module_inputs = { + node.name: node for node in bwd_module.graph.find_nodes(op="placeholder") + } + should_perform_fp8_quant = False + for node in fwd_module_outputs: + if node.name in saved_values_names and should_quantize(node): + if node.name in static_input_names: + log.debug("Skipping quantization of static input %s: ", node.name) + continue + node.meta["saved_for_quantization"] = True + node.meta["dequant_type"] = node.meta["val"].dtype + # some of the fwd outputs and bwd inputs are not share the same object + bwd_module_inputs[node.name].meta["saved_for_quantization"] = True + bwd_module_inputs[node.name].meta["dequant_type"] = node.meta["val"].dtype + should_perform_fp8_quant = True + + if should_perform_fp8_quant: + perform_fp8_activation_quantization( + fwd_module, bwd_module, bwd_module_inputs, num_fwd_outputs + ) + + +def _extract_fwd_bwd_modules( + joint_module: fx.GraphModule, + saved_values: list[fx.Node], + saved_sym_nodes: list[fx.Node], + saved_opaque_nodes: list[fx.Node] | None = None, + *, + num_fwd_outputs: int, + static_lifetime_input_nodes: OrderedSet[fx.Node] | None = None, + ignore_must_be_in_fw_bw: bool = False, + omit_aot_autograd_runtime: bool = False, +) -> tuple[fx.GraphModule, fx.GraphModule]: + """Extract forward and backward graph modules from a joint graph. + + Args: + ignore_must_be_in_fw_bw: When True, disables forward/backward placement + enforcement in _extract_graph_with_inputs_outputs. Needed when the + joint_module is not an original fwd+bwd joint graph (e.g. a backward + graph being re-partitioned for dI/dW splitting). + omit_aot_autograd_runtime: When True, skips postprocessing that is + only needed when the resulting modules will be wrapped in a custom + autograd.Function (the AOTAutograd path). This includes: tangent input + handling, version-counter check sorting of saved tensors, opaque object + (FakeScriptObject) separation, and fp8 activation quantization. Set this + to True when the fwd/bwd modules will be executed directly without autograd. + """ + fwd_outputs, bwd_outputs, fwd_outputs_descs, bwd_outputs_descs = ( + _extract_fwd_bwd_outputs(joint_module, num_fwd_outputs=num_fwd_outputs) + ) + placeholders = joint_module.graph.find_nodes(op="placeholder") + primal_inputs = [*filter(_is_primal, placeholders)] + tangent_inputs = ( + [] if omit_aot_autograd_runtime else [*filter(_is_tangent, placeholders)] + ) + fwd_seed_offset_inputs = [*filter(_is_fwd_seed_offset, placeholders)] + bwd_seed_offset_inputs = [*filter(_is_bwd_seed_offset, placeholders)] + backward_state_inputs = [*filter(_is_backward_state, placeholders)] + + if saved_opaque_nodes is None: + saved_opaque_nodes = [] + + bwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + saved_sym_nodes + + saved_opaque_nodes + + saved_values + + tangent_inputs + + bwd_seed_offset_inputs, + bwd_outputs, + bwd_outputs_descs, + "backward", + ignore_must_be_in_fw_bw=ignore_must_be_in_fw_bw, + ) + + distributed_enabled = torch.distributed.is_available() + + for node in bwd_graph.find_nodes(op="placeholder"): + # This is to filter out saved values that don't actually end up being used by the backwards pass + if not node.users: + _remove_by_name(saved_values, node.name) + _remove_by_name(saved_sym_nodes, node.name) + _remove_by_name(saved_opaque_nodes, node.name) + # wait_tensor is a bit special: if we have a "dead activation" that is not used in the bw, + # but this dead activation is actually a collective, + # then the collective will generally by followed by a wait_tensor() call. + # we need to peek one node further to see if this wait_tensor is dead as well. + elif distributed_enabled and all( + n.target is torch.ops._c10d_functional.wait_tensor.default + and len(n.users) == 0 + for n in node.users + ): + _remove_by_name(saved_values, node.name) + _remove_by_name(saved_sym_nodes, node.name) + _remove_by_name(saved_opaque_nodes, node.name) + elif _is_backward_state(node): + # BackwardState is saved directly + _remove_by_name(saved_values, node.name) + if not backward_state_inputs: + raise AssertionError("backward_state_inputs must not be empty") + + # Now that we have the finalized list of saved values, we need to ensure + # we propagate all symbols which are referenced by backwards inputs. + # These are not directly used in the graph but are required for downstream + # sizevar assignment + saved_symbols: OrderedSet[sympy.Symbol] = OrderedSet() + saved_sym_nodes_binding = [] + saved_sym_nodes_derived = [] + + # Some symbols may already be bound in the directly saved_sym_nodes, + # keep track of them so we don't re-bind them + for node in saved_sym_nodes: + symbol = is_symbol_binding_fx_node(node) + if symbol: + saved_symbols.add(symbol) + saved_sym_nodes_binding.append(node) + else: + saved_sym_nodes_derived.append(node) + + # Now go through all of the prospective backward inputs and track any + # other symbols we need to bind + symbol_bindings = find_symbol_binding_fx_nodes(joint_module.graph) + for node in itertools.chain(saved_sym_nodes_derived, saved_values, tangent_inputs): + if "val" not in node.meta: + continue + # Bind both the unreplaced symbols (needed by runtime assertions, which + # preserve raw placeholder expressions -- see #155468) and the replaced + # symbols (needed by sizevar codegen and FxGraphCache guards, which use + # ShapeEnv replacements). Binding only one side can leave the other's + # symbols undefined in the backward: e.g. an offsets size that is a + # symbol replaced to `s + 1` leaves the base symbol `s` unbound, which + # surfaces as a KeyError during backward FxGraphCache guard evaluation. + new_symbols = ( + _free_symbols_without_replacements(node.meta["val"]) + | free_symbols(node.meta["val"]) + ) - saved_symbols + # NB: Deterministic order please! + for s in sorted(new_symbols, key=lambda s: s.name): + # NB: For well formed graphs, the symbol should always be present, + # but we also have ways to produce ill-formed graphs, e.g., direct + # make_fx usages, so don't choke in this case + if s not in symbol_bindings: + continue + saved_sym_nodes_binding.append(symbol_bindings[s]) + saved_symbols |= new_symbols + + # Update saved_sym_nodes that are now reordered to have all bindings at + # front. This can also be used later on to figure out the position of saved + # sym nodes in the output of fwd graph. + saved_sym_nodes.clear() + saved_sym_nodes.extend(saved_sym_nodes_binding + saved_sym_nodes_derived) + + if not omit_aot_autograd_runtime: + # See Note [Activations with no version counter checks in eager] + # Sort saved_values so that tensors with saved_tensor_with_no_vc_check=True + # are at the end. This allows us to have two consecutive slices: + # 1. tensors_saved_with_vc_check_slice - tensors saved via save_for_backward + # 2. tensors_saved_with_no_vc_check_slice - tensors stashed on ctx without save_for_backward + # The sort is stable, so the relative order within each group is preserved. + # + # Additionally, separate out opaque objects (FakeScriptObject) from tensors. + # Opaque objects should be placed after tensors in the forward outputs. + saved_values_with_vc_check = [] + saved_values_no_vc_check = [] + saved_opaque_objects = [] + for node in saved_values: + # Check if this is an opaque object + if isinstance(node.meta.get("val"), FakeScriptObject): + saved_opaque_objects.append(node) + elif node.meta.get("saved_tensor_with_no_vc_check", False): + saved_values_no_vc_check.append(node) + else: + saved_values_with_vc_check.append(node) + saved_values.clear() + saved_values.extend(saved_values_with_vc_check + saved_values_no_vc_check) + no_vc_check_start_idx = len(saved_values_with_vc_check) + + # debug assert: given saved_values where the last k of them are expected to not + # require VC checks, they should all have node metadata indicating so. + for i, node in enumerate(saved_values): + if i >= no_vc_check_start_idx: + if not node.meta.get("saved_tensor_with_no_vc_check", False): + raise AssertionError( + f"i={i}, no_vc_check_start_idx={no_vc_check_start_idx}, len(saved_values)={len(saved_values)}" + ) + + # Now, we re-generate the fwd/bwd graphs. + # NB: This might increase compilation time, but I doubt it matters + # Convention for saved acts is (tensors_with_vc_check, tensors_no_vc_check, opaque_objects, symints, opaque_nodes) + fwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + primal_inputs + fwd_seed_offset_inputs, + fwd_outputs + + saved_values + + saved_opaque_objects + + saved_opaque_nodes + + saved_sym_nodes, + fwd_outputs_descs + + [ + SavedForBackwardsNoVcCheckAOTOutput(i) + if i >= no_vc_check_start_idx and i < len(saved_values) + else SavedForBackwardsAOTOutput(i) + for i in range( + len(saved_values) + + len(saved_opaque_objects) + + len(saved_opaque_nodes) + + len(saved_sym_nodes) + ) + ], + "forward", + ignore_must_be_in_fw_bw=ignore_must_be_in_fw_bw, + ) + bwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + saved_sym_nodes + + saved_values + + saved_opaque_objects + + saved_opaque_nodes + + tangent_inputs + + bwd_seed_offset_inputs + + backward_state_inputs, + bwd_outputs, + bwd_outputs_descs, + "backward", + ignore_must_be_in_fw_bw=ignore_must_be_in_fw_bw, + ) + else: + # Raw fwd/bwd split for direct execution without autograd + fwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + primal_inputs + fwd_seed_offset_inputs, + fwd_outputs + saved_values + saved_sym_nodes, + fwd_outputs_descs + + [ + SavedForBackwardsAOTOutput(i) + for i in range(len(saved_values) + len(saved_sym_nodes)) + ], + "forward", + ignore_must_be_in_fw_bw=ignore_must_be_in_fw_bw, + ) + bwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + saved_values + + saved_sym_nodes + + bwd_seed_offset_inputs + + backward_state_inputs, + bwd_outputs, + bwd_outputs_descs, + "backward", + ignore_must_be_in_fw_bw=ignore_must_be_in_fw_bw, + ) + + for node in bwd_graph.nodes: + if node.op in ("call_function", "get_attr"): + node.meta["autograd_backward"] = True + + fwd_module = fx._lazy_graph_module._make_graph_module(joint_module, fwd_graph) + bwd_module = fx._lazy_graph_module._make_graph_module(joint_module, bwd_graph) + if ( + inductor_config.post_grad_fusion_options.get( + "activation_quantization_aten_pass", None + ) + is not None + ): + enable_activation_quantization( + saved_values, + fwd_module, + bwd_module, + static_lifetime_input_nodes, + num_fwd_outputs, + ) + return fwd_module, bwd_module + + +def default_partition( + joint_module: fx.GraphModule, + _joint_inputs: Any, + *, + num_fwd_outputs: int, + static_lifetime_input_indices: list[int] | None = None, + static_lifetime_input_nodes: OrderedSet[fx.Node] | None = None, +) -> tuple[fx.GraphModule, fx.GraphModule]: + """ + Partitions the :attr:`joint_module` in a manner that closely resembles the + behavior observed in the original ``.forward()`` and ``.backward()`` of the + callable, i.e., the resulting forward graph contains those operators that + are executed in the original ``.forward()`` callable passed to + :func:`aot_function`. + + The default partitioner collects the operators that are between the forward + inputs and the forward outputs. This helps in finding the tensors which have + to be stashed for the backward pass. These stashed tensors become the output + of the generated forward graph. The remaining operators are then placed in + the backward graph. + + .. warning:: + This API is experimental and likely to change. + + Args: + joint_module(fx.GraphModule): The joint forward and backward graph. This + is the result of AOT Autograd tracing. + + Returns: + Returns the generated forward and backward Fx graph modules. + """ + # Respect the original placement of ops rather than rely on dataflow. + forward_nodes = [] + last_node = None + for node in joint_module.graph.nodes: + if _has_tag_is_forward(node) or _is_primal(node) or _is_fwd_seed_offset(node): + last_node = node + if last_node is None: + raise AssertionError("last_node must not be None") + for node in joint_module.graph.nodes: + if not _is_tangent(node): + forward_nodes.append(node) + if node is last_node: + break + forward_node_names = OrderedSet( + node.name for node in forward_nodes if node.op != "output" + ) + graph_has_recomputable_ops = has_recomputable_ops(joint_module) + graph_has_recomputable_rng_ops = has_recomputable_rng_ops(joint_module) + if graph_has_recomputable_ops: + if _is_functional_graph(joint_module.graph)[0] is not None: + # Fall-back to previous behavior to avoid bc-breaking, although can + # eventually flip the switch to make this a hard error. + warnings.warn( + "Trying to unsafely apply AC to a non-functional graph with the " + "default partitioner. Falling back to min-cut partitioner." + ) + return min_cut_rematerialization_partition( + joint_module, + _joint_inputs, + num_fwd_outputs=num_fwd_outputs, + static_lifetime_input_indices=static_lifetime_input_indices, + ) + + joint_module = cleanup_recompute_tags(joint_module, is_default_partition=True) + + if not config.unsafe_allow_optimization_of_collectives: + force_save_collectives(joint_module) + + force_save_effectful_ops(joint_module) + force_save_bw_mutation_src(joint_module) + + if static_lifetime_input_indices is None: + static_lifetime_input_indices = [] + node_info = classify_nodes( + joint_module, static_lifetime_input_indices, num_fwd_outputs + ) + + saved_values = [] + saved_sym_nodes = [] + saved_opaque_nodes = [] + + distributed_enabled = torch.distributed.is_available() + + def is_tensor(node: fx.Node) -> bool: + return "tensor_meta" in node.meta or isinstance( + node.meta.get("val"), torch._subclasses.FakeTensor + ) + + def is_multi_output(node: fx.Node) -> bool: + return ( + all(user.target == operator.getitem for user in node.users) + and len(node.users) > 0 + ) + + def is_impure(node: fx.Node) -> bool: + # wait tensor is an "impure" op according to DCE's definition of impure + # (see is_impure in torch/fx/node.py), but it survives past + # functionalization and can be safely dup'd and reordered under the + # assumption SPMD. + return ( + node.is_impure(impure_random=False) + and node.op + not in ( + "placeholder", + "output", + ) + and ( + not distributed_enabled + or node.target is not torch.ops._c10d_functional.wait_tensor.default + ) + ) + + for node in joint_module.graph.nodes: + if node.name not in forward_node_names: + continue + if node.op == "get_attr" and node.name in ( + k for k, v in joint_module.named_modules() + ): + continue + if node.target in ( + torch.ops.aten._assert_scalar.default, + torch.ops.aten._assert_async.default, + torch.ops.aten._assert_async.msg, + # Profiler record_function ops are technically impure (they set up + # profiling spans), but they're safe to duplicate during AC recompute. + # We skip both enter and exit to keep profiling spans balanced. + torch.ops.profiler._record_function_enter_new.default, + torch.ops.profiler._record_function_enter.default, + torch.ops.profiler._record_function_exit.default, + torch.ops.profiler._record_function_exit._RecordFunction, + ): + continue + if is_sym_node(node): + # Symints must be kept separate from tensors so that PythonFunction only calls + # save_for_backward on tensors and stashes symints in autograd .ctx + saved_sym_nodes.append(node) + continue + if is_multi_output(node): + # Must be ordered before MUST_SAVE tags to avoid saving tuples marked MUST_SAVE. + continue + if node.meta.get("recompute") == CheckpointPolicy.MUST_SAVE: + if is_opaque_node(node): + saved_opaque_nodes.append(node) + else: + saved_values.append(node) + continue + if is_impure(node): + if graph_has_recomputable_ops: + raise AssertionError( + f"Trying to apply AC on a graph with impure op: {node}, {node.target}" + ) + if is_opaque_node(node): + saved_opaque_nodes.append(node) + else: + saved_values.append(node) + continue + if is_opaque_node(node): + saved_opaque_nodes.append(node) + continue + if not is_tensor(node) and node.op == "call_function": + raise AssertionError(f"Expected {node} to be a tensor") + backward_usages = [n for n in node.users if n.name not in forward_node_names] + if all(is_sym_node(n) for n in backward_usages): + # If we have a tensor in the forward, where only its sizes/strides are needed in the backward, + # and not the actual tensor data, + # then it will be a lot cheaper to save only the sizes/strides, and not the actual tensor. + # + # Note that saving the tensor could also cause compilation problems: + # If the user mutated an input in the forward and uses its sizes/strides in the backward, + # then we would be obligated to clone the input before saving it to appease autograd. + # (This is how we originally found this bug). + saved_sym_nodes.extend(backward_usages) + continue + if not must_recompute(node): + saved_values.append(node) + + saved_values = list(dict.fromkeys(saved_values).keys()) + saved_sym_nodes = list(dict.fromkeys(saved_sym_nodes).keys()) + # Skip SymBool nodes whose only consumers are _assert_scalar calls. + # These are runtime assertion intermediates and are not needed in backward + # for any real computation. + saved_sym_nodes = [ + node for node in saved_sym_nodes if not _is_assert_only_symbool(node) + ] + saved_opaque_nodes = list(dict.fromkeys(saved_opaque_nodes).keys()) + + if config._sync_decision_cross_ranks: + saved_values = _sync_decision_cross_ranks(joint_module.graph, saved_values) + + if static_lifetime_input_nodes is None: + static_lifetime_input_nodes = node_info.static_lifetime_input_nodes + fw_module, bw_module = _extract_fwd_bwd_modules( + joint_module, + saved_values, + saved_sym_nodes=saved_sym_nodes, + saved_opaque_nodes=saved_opaque_nodes, + num_fwd_outputs=num_fwd_outputs, + static_lifetime_input_nodes=static_lifetime_input_nodes, + ) + + # Run DCE while overriding the definition of is_impure_node + fw_module.graph.eliminate_dead_code(is_impure_node=is_not_collective) + bw_module.graph.eliminate_dead_code(is_impure_node=is_not_collective) + + if graph_has_recomputable_ops: + if graph_has_recomputable_rng_ops: + fw_module, bw_module = functionalize_rng_ops( + joint_module, fw_module, bw_module, len(saved_sym_nodes) + ) + bw_module = reordering_to_mimic_autograd_engine(bw_module) + + # pyrefly: ignore [unbound-name] + if config.enable_activation_offloading: + from ._activation_offloading.activation_offloading import ( + enable_activation_offloading, + ) + + enable_activation_offloading( + fw_module, + bw_module, + num_fwd_outputs, + static_lifetime_input_nodes, + ) + + # raise all getitem ops to as early as possible + # this is helpful for memory, especially in the case of aot_eager backend + fw_module = raise_getitems(fw_module) + bw_module = raise_getitems(bw_module) + + fw_module = thread_graphsafe_rng_from_hops(fw_module, is_backward=False) + if len(node_info.required_bw_nodes) > 0: + bw_module = thread_graphsafe_rng_from_hops(bw_module, is_backward=True) + + return fw_module, bw_module + + +INT_INF = int(1e6) + + +def _tensor_nbytes(numel: int, dtype: torch.dtype) -> int: + return numel * dtype.itemsize + + +def _size_of(node: fx.Node) -> int: + def object_nbytes(x: object) -> int: + if not isinstance(x, torch.Tensor): + return 0 + return _tensor_nbytes(optimization_hint(x.numel(), fallback=4096), x.dtype) + + if "val" in node.meta: + val = node.meta["val"] + if isinstance(val, py_sym_types): + return 1 + # NB: The fallback values here are meaningless, maybe we should respect + # torch._inductor.config.unbacked_symint_fallback (but this is a + # layering violation) + elif isinstance(val, (list, tuple)): + return sum(object_nbytes(n) for n in val) + elif isinstance(val, dict): + return sum(object_nbytes(n) for n in val.values()) + elif isinstance(val, torch.Tensor): + return object_nbytes(val) + elif isinstance(val, (torch.ScriptObject, FakeScriptObject)): + # A (Fake)ScriptObject may hold tensors internally, so we cannot + # soundly compute its size here. Only treat it as zero size when the + # user has explicitly opted in via this escape hatch. + if config.unsafe_treat_script_objects_as_zero_size: + return 0 + raise RuntimeError( + f"Cannot compute the size of {type(val)} on node {node}. A " + "ScriptObject may hold tensors internally and the partitioner " + "has no general way to measure its memory footprint. Set " + "torch._functorch.config.unsafe_treat_script_objects_as_zero_size" + " = True to assume such objects are zero size (unsound)." + ) + + raise RuntimeError(f"Unknown metadata type {type(val)} on node {node}") + if node.op == "get_attr" or ( + isinstance(node.target, torch._ops.OpOverload) + and len(node.target._schema.returns) == 0 + ): + return 0 + raise RuntimeError( + f"Node {node} didn't have `val` metadata; we should always have `val` metadata on the nodes." + ) + + +# Used for some investigative purposes +def _count_ops(graph: fx.Graph) -> None: + from collections import defaultdict + + cnt: dict[str, int] = defaultdict(int) + for node in graph.nodes: + if node.op == "call_function": + cnt[node.target.__name__] += 1 + log.info("%s", sorted(cnt.items(), key=operator.itemgetter(1), reverse=True)) + + +@functools.cache +def pointwise_ops() -> list[torch._ops.OpOverloadPacket]: + ops: list[torch._ops.OpOverloadPacket] = [] + for attr_name in dir(torch.ops.aten): + opoverloadpacket = getattr(torch.ops.aten, attr_name) + if not isinstance(opoverloadpacket, torch._ops.OpOverloadPacket): + continue + + for op_overload in opoverloadpacket.op_overloads(): + if torch.Tag.pointwise in op_overload.tags: + # currently aot autograd uses packet not overload + ops.append(opoverloadpacket) + break + + return ops + + +def sort_depths( + args: tuple[Any, ...], depth_map: dict[fx.Node, int] +) -> list[tuple[fx.Node, int]]: + arg_depths = { + arg: depth_map[arg] for arg in args if isinstance(arg, torch.fx.node.Node) + } + return sorted(arg_depths.items(), key=operator.itemgetter(1), reverse=True) + + +def reordering_to_mimic_autograd_engine(gm: fx.GraphModule) -> fx.GraphModule: + """ + This pass finds the first bwd node in the graph (by looking at users of + tangents) and then reorders the graph by walking from this node to all the + way to the end of the graph. At each op in this traversal, we insert this op + in a new graph and try to bring only the relevant subgraph from the other + non-bwd edges relevant for this op. This closely mimics the behavior of + autograd engine. + + Why is this pass required in the first place? + + This is an artifact of how partitioners work today. The starting point of + partitioner is a joint graph, which is fwd and then bwd graph. In the case + of checkpointing, we keep portions of fwd graph in their original place in + the joint graph, while obtaining a bwd graph. As a result, the resulting bwd + graph has copies of recomputed fwd subgraphs followed by the original bwd + graph. If we run this naively, this leads to bad memory footprint, because + the fwd subgraphs are live for way longer duration than necessary. This pass + reorders the operations such that we prioritize the ops for the original bwd + graph while only realizing those ops from the fwd graph that are necessary + at any given point in the graph. + """ + + new_graph = fx.Graph() + env: dict[fx.Node, fx.Node] = {} + + # Add new placeholder nodes in the order specified by the inputs + for node in gm.graph.find_nodes(op="placeholder"): + env[node] = new_graph.node_copy(node, lambda x: env[x]) + + order = {node: idx for idx, node in enumerate(gm.graph.nodes)} + + def insert_node_in_graph(node: fx.Node) -> None: + cur_nodes = [node] + insertable_nodes: OrderedSet[fx.Node] = OrderedSet() + while len(cur_nodes) > 0: + node = cur_nodes.pop() + if node in insertable_nodes or node in env: + continue + insertable_nodes.add(node) + + # Bias traversal towards the nodes that have higher depth - prioritizes + # critical path first. + cur_nodes += node.all_input_nodes + + # pyrefly: ignore [bad-assignment] + insertable_nodes = sorted(insertable_nodes, key=lambda n: order[n]) + for node in insertable_nodes: + env[node] = new_graph.node_copy(node, lambda x: env[x]) + + # Find first bwd node in the graph + tangent_inputs = list(filter(_is_tangent, gm.graph.nodes)) + first_node_in_bwd = None + minimum_order = math.inf + for tangent in tangent_inputs: + for user in tangent.users: + if order[user] < minimum_order: + minimum_order = order[user] + first_node_in_bwd = user + + # If gradInp does not depend upon gradOut, we may not find any nodes in the "backwards pass" + if first_node_in_bwd is None: + return gm + + # Build the graph op-by-op by starting from the node all the way to the end + # copy_ can be not using tangents at all, we must copy it. + for node in list(gm.graph.nodes)[: order[first_node_in_bwd]]: + if node.op == "call_function" and node.target is torch.ops.aten.copy_.default: + insert_node_in_graph(node) + + for node in list(gm.graph.nodes)[order[first_node_in_bwd] :]: + insert_node_in_graph(node) + + # The output node is already built by the traversal. + new_gm = torch.fx.GraphModule(gm, new_graph) + return new_gm + + +def apply_graphsafe_rng_functionalization( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + fw_node: torch.fx.Node, + bw_node: torch.fx.Node, + device: torch.device, + rng_count: int, + last_fwd_input: torch.fx.Node, + last_bwd_input: torch.fx.Node, +) -> tuple[torch.fx.Node, torch.fx.Node]: + """ + Note [CUDA Graph Safe RNG Functionalization] + + CUDA Graph capture doesn't work with get_rng_state and set_rng_state because these functions operate on CPU values, + while CUDA Graph RNG capture uses on-device CUDA tensors. To solve this, we use graphsafe_set_state with a + CUDA Generator registered to the CUDA Graph before capture begins. graphsafe_set_state updates the generator's pointer + to reference a different GeneratorImpl, ensuring subsequent calls are correctly forwarded to the desired generator + (and its cuda-tensor RNG state during graph capture). + + For each RNG operation's forward/backward pair: + + - We create two generators initialized with identical values + - Each forward and backward call advances its respective generator equally + - This keeps generators synchronized so forward and backward operations use matching RNG values + + When forward is called multiple times before backward (causing desynchronization): + + - We save the forward RNG state + - We update the backward Generator's state before executing backward + + This function modifies both forward and backward computation graphs by: + + Creating RNG state placeholders for both passes + Updating the forward node to use graph-safe RNG state + Updating the backward node to use graph-safe RNG state + + For more details: https://github.com/pytorch/pytorch/issues/113541 + """ + device_idx = device.index + if device_idx is None: + raise AssertionError("device_idx must not be None") + fw_graph = fw_module.graph + bw_graph = bw_module.graph + graphsafe_run_with_rng_state = torch._prims.rng_prims.graphsafe_run_with_rng_state + + # Handle forward pass + + # Note: [Generator arguments in AOTDispatcher] + # Generator arguments in AOTDispatcher are added to support graphsafe rng + # functionalization. See note above [CUDA Graph Safe RNG Functionalization] + with fw_module.graph.inserting_after(last_fwd_input): + fwd_rng_state = fw_module.graph.placeholder(f"fwd_rng_state_{rng_count}") + fwd_rng_state.meta["val"] = get_default_generator(device).clone_state() + last_fwd_input = fwd_rng_state + + # Handle backward pass + with bw_module.graph.inserting_after(last_bwd_input): + bwd_rng_state = bw_module.graph.placeholder(f"bwd_rng_state_{rng_count}") + # as above, clone so that meta val generator will not contain tensors + bwd_rng_state.meta["val"] = get_default_generator(device).clone_state() + last_bwd_input = bwd_rng_state + + # Update forward node + fw_kwargs = dict(fw_node.kwargs) + fw_kwargs["rng_state"] = fwd_rng_state + with fw_module.graph.inserting_after(fw_node): + functional_fw_node = fw_graph.create_node( + "call_function", + graphsafe_run_with_rng_state, + args=(fw_node.target, *fw_node.args), # type: ignore[arg-type] + kwargs=fw_kwargs, + ) + fw_node.replace_all_uses_with(functional_fw_node) + fw_graph.erase_node(fw_node) + + # Update backward node + bwd_kwargs = dict(bw_node.kwargs) + bwd_kwargs["rng_state"] = bwd_rng_state + with bw_graph.inserting_before(bw_node): + rng_output = bw_graph.create_node( + "call_function", + graphsafe_run_with_rng_state, + args=(bw_node.target, *bw_node.args), # type: ignore[arg-type] + kwargs=bwd_kwargs, + ) + bw_node.replace_all_uses_with(rng_output) + bw_graph.erase_node(bw_node) + + return last_fwd_input, last_bwd_input + + +def functionalize_rng_ops( + joint_module: fx.GraphModule, + fw_module: fx.GraphModule, + bw_module: fx.GraphModule, + num_sym_nodes: int, +) -> tuple[fx.GraphModule, fx.GraphModule]: + # During user-driven activation checkpointing, we have to ensure that a rng + # op in fwd yields the same output as the recomputed rng op in the bwd. To + # do this, we use functionalize wrappers to wrap the random ops and share + # rng state between the fwd and bwd graphs. + + # There are 3 main steps to do this + # Step 1 - Construct a mapping of rng node between the fwd and its counterpart in bwd. + # Step 2 - Modify the fwd pass such that + # 1) Replace rand with run_and_save_rng_state wrapper + # 2) Replace the users of the original op with the output[1] of this op. + # 3) Collect all the rng_state - output[0] of each op, and make them + # output nodes. Special care needs to be taken here because fwd outputs + # has symints at the very end. + # Step 3 - Modify the bwd pass such that + # 1) Add the input nodes just before the tangents for the stashed rng states + # 2) Replace rand with run_with_save_rng_state wrappers + # 3) Use the stashed states as inputs to these ops + + # Unique id to generate name + uid = itertools.count() + + def get_rng_ops(gmod: fx.GraphModule) -> dict[str, fx.Node]: + random_nodes: dict[str, fx.Node] = {} + for node in gmod.graph.nodes: + if node.op == "call_function" and is_rng_op(node): + random_nodes[node.name] = node + return random_nodes + + def get_device(node: fx.Node) -> torch.device | None: + """ + Check the example value of the node outputs to find the device type. + """ + if "val" not in node.meta: + return None + + candidates = node.meta["val"] + if not isinstance(candidates, tuple): + candidates = (candidates,) + + for candidate in candidates: + if isinstance(candidate, torch.Tensor): + if supports_graphsafe_rng(candidate.device): + return candidate.device + + return torch.device("cpu") + + def get_sample_rng_state(device: torch.device | None) -> torch.Tensor: + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode() + if fake_mode is None: + raise AssertionError("fake_mode must not be None") + with fake_mode: + if device is not None and supports_graphsafe_rng(device): + return fake_mode.from_tensor(get_device_rng_state(device)) + return fake_mode.from_tensor(torch.get_rng_state()) + + # Step 1 - Construct a mapping of rng node between the fwd and its counterpart in bwd. + joint_graph_rng_ops = get_rng_ops(joint_module) + fw_graph_rng_ops = get_rng_ops(fw_module) + bw_graph_rng_ops = get_rng_ops(bw_module) + recomputable_rng_ops_map = {} + for node in joint_module.graph.nodes: + if must_recompute(node) and is_rng_op(node): + # Skip if the node doesn't exist in both forward and backward graphs. + # This can happen when the RNG op's output is not needed for gradient + # computation and gets eliminated by dead code elimination. + if node.name not in fw_graph_rng_ops or node.name not in bw_graph_rng_ops: + continue + base_node = joint_graph_rng_ops[node.name] + fw_node = fw_graph_rng_ops[node.name] + bw_node = bw_graph_rng_ops[node.name] + recomputable_rng_ops_map[base_node] = {"fwd": fw_node, "bwd": bw_node} + + run_and_save_rng = torch._prims.rng_prims.run_and_save_rng_state + run_with_rng_state = torch._prims.rng_prims.run_with_rng_state + + bw_tangent_start_node = None + for node in bw_module.graph.find_nodes(op="placeholder"): + if "tangent" in node.name: + bw_tangent_start_node = node + break + if bw_tangent_start_node is None: + raise RuntimeError( + "Couldn't find tangent node in graph inputs. This is unexpected, please file a bug if you see this" + ) + + fw_rng_state_outputs: list[fx.Node] = [] + + last_fwd_input = next(reversed(fw_module.graph.find_nodes(op="placeholder"))) + last_bwd_input = next(reversed(bw_module.graph.find_nodes(op="placeholder"))) + + devices = OrderedSet( + get_device(node_pair["fwd"]) for node_pair in recomputable_rng_ops_map.values() + ) + # pyrefly: ignore [unbound-name] + devices.discard(torch.device("cpu")) + # multiple graphsafe devices won't work with cudagraphs anyway, + # fallback to non graphsafe rng checkpointing + multi_graphsafe_devices = len(devices) > 1 + + # this changes numerics, so if fallback_random is set we will not use it + # pyrefly: ignore [unbound-name] + ind_config = torch._inductor.config + use_rng_graphsafe_rng_functionalization = ( + config.graphsafe_rng_functionalization + and not multi_graphsafe_devices + and ( + not ind_config.fallback_random + or ind_config.test_configs.graphsafe_rng_func_ignores_fallback_random + ) + ) + + for rng_count, node_pair in enumerate(recomputable_rng_ops_map.values()): + # Step 2 - Modify the fwd pass such that + fw_node = node_pair["fwd"] + bw_node = node_pair["bwd"] + device = get_device(fw_node) + + fw_graph = fw_module.graph + bw_graph = bw_module.graph + + if ( + use_rng_graphsafe_rng_functionalization + and device is not None + and supports_graphsafe_rng(device) + ): + last_fwd_input, last_bwd_input = apply_graphsafe_rng_functionalization( + fw_module, + bw_module, + fw_node, + bw_node, + device, + rng_count, + last_fwd_input, + last_bwd_input, + ) + else: + with fw_graph.inserting_before(fw_node): + functional_fw_node = fw_graph.create_node( + "call_function", + run_and_save_rng, + # pyrefly: ignore [bad-argument-type] + args=( + fw_node.target, + *fw_node.args, + ), # pyrefly: ignore[bad-argument-type] + kwargs=fw_node.kwargs, + ) + state = fw_graph.create_node( + "call_function", + operator.getitem, + args=(functional_fw_node, 0), + kwargs={}, + ) + state.meta["val"] = get_sample_rng_state(device) + + rng_output = fw_graph.create_node( + "call_function", + operator.getitem, + args=( + functional_fw_node, + 1, + ), + kwargs={}, + ) + # Copy the meta data from the original node + rng_output.meta = copy.copy(fw_node.meta) + + fw_node.replace_all_uses_with(rng_output) + fw_graph.erase_node(fw_node) + fw_rng_state_outputs.append(state) + + # Step 3 - Modify the bwd pass such that + with bw_graph.inserting_before(bw_tangent_start_node): + state_name = f"rng_state_output_{next(uid)}" + bw_rng_state_node = bw_graph.placeholder(state_name) + bw_rng_state_node.meta["val"] = get_sample_rng_state(device) + + with bw_graph.inserting_before(bw_node): + rng_output = bw_graph.create_node( + "call_function", + run_with_rng_state, + # pyrefly: ignore [bad-argument-type] + args=( + bw_rng_state_node, + bw_node.target, + *bw_node.args, + ), # pyrefly: ignore[bad-argument-type] + kwargs=bw_node.kwargs, + ) + + bw_node.replace_all_uses_with(rng_output) + bw_graph.erase_node(bw_node) + + # Add the rng states in the output of the fwd graph. AOT Autograd assumes + # that symints are at the end of forward graph outputs. So, insert the new + # rng states accordingly. + if fw_rng_state_outputs: + fw_output_node = next(iter(fw_module.graph.find_nodes(op="output"))) + fw_outputs = fw_output_node.args[0] + sym_node_start_idx = len(fw_outputs) - num_sym_nodes + outputs = ( + fw_outputs[:sym_node_start_idx] + + tuple(fw_rng_state_outputs) + + fw_outputs[sym_node_start_idx:] + ) + fw_module.graph.output(outputs) + fw_module.graph.erase_node(fw_output_node) + fw_module.recompile() + bw_module.recompile() + return fw_module, bw_module + + +def force_save_collectives(joint_module: fx.GraphModule) -> None: + """ + By default, the partitioner is not allowed to recompute collectives + unless they come from a user-annotated AC region. + See Note [Recomputing collectives in the partitioner] + """ + for node in joint_module.graph.nodes: + if ( + isinstance(node.target, torch._ops.OpOverload) + and node.target.namespace == "_c10d_functional" + and not must_recompute(node) + ): + node.meta["recompute"] = CheckpointPolicy.MUST_SAVE + + +def force_save_effectful_ops(joint_module: fx.GraphModule) -> None: + """ + Force save outputs from with_effects nodes wrapping effectful ops. + + Effectful ops (registered via _register_effectful_op) should not be recomputed + because they may have arbitrary global side effects (I/O, RNG state, collectives, + etc.). We mark the tensor outputs of with_effects as MUST_SAVE to prevent + recomputation of the effectful op. + + The with_effects node returns a tuple (token, result). We recursively find all + leaf outputs extracted via getitem and mark them as MUST_SAVE. Since these are + saved, the with_effects op doesn't need to be recomputed in backward. + """ + + def mark_getitem_outputs(node: fx.Node) -> None: + for user in node.users: + if user.target is operator.getitem: + mark_getitem_outputs(user) + if not isinstance(user.meta.get("val"), (tuple, list)): + user.meta["recompute"] = CheckpointPolicy.MUST_SAVE + + for node in joint_module.graph.nodes: + if ( + is_with_effects(node) + and not must_recompute(node) + and not _has_tag_is_backward(node) + ): + mark_getitem_outputs(node) + + +def force_save_bw_mutation_src(joint_module: fx.GraphModule) -> None: + # If we have mutations of the same primal in forward and backward, + # We must not recompute the source of mutation to not apply twice. + has_mutation_in_bw: OrderedSet[torch.fx.Node] = OrderedSet() + for node in reversed(joint_module.graph.nodes): + if node.op == "output": + continue + + is_copy_ = node.target is torch.ops.aten.copy_.default + if is_copy_: + if _has_tag_must_be_in_backward(node): + has_mutation_in_bw.add(node.args[0]) + + if _has_tag_must_be_in_forward(node) and node.args[0] in has_mutation_in_bw: + node.args[1].meta["recompute"] = CheckpointPolicy.MUST_SAVE + else: + # We use invariant of aotdispatch joint graph, + # That we emit copy_ only in the end of it. + # We do not want to iterate through all the joint graph, + # so break at the first non-output, non-copy_ node. + break + + +def is_getitem_of_multi_output(node: fx.Node) -> bool: + if node.target != operator.getitem: + return False + parent = node.args[0] + if type(parent) is not fx.Node: + raise AssertionError(f"expected parent to be fx.Node, got {type(parent)}") + return "tensor_meta" not in parent.meta and node.op == "call_function" + + +def cleanup_recompute_tags( + joint_module: fx.GraphModule, *, is_default_partition: bool +) -> fx.GraphModule: + """ + If there are two consecutive checkpointed blocks with no operator in + between, we would still want to stash the tensor at the boundary of + checkpointed blocks. The following pass makes the last output node + non-recomputable to allow for that. + """ + for node in joint_module.graph.nodes: + if must_recompute(node): + for user in node.users: + if ( + must_recompute(user) + and "ac_graph_id" in user.meta + and "ac_graph_id" in node.meta + and user.meta["ac_graph_id"] > node.meta["ac_graph_id"] + ): + node.meta["recompute"] = CheckpointPolicy.MUST_SAVE + if node.meta.get("has_backward_hook", False) and not any( + must_recompute(user) for user in node.users + ): + # If node is AC region output and has a backward hook on it, we intentionally choose to save it. + # This is to work around circular dependencies with backward hooks + AC. + # Example: + # ``` + # out = fully_shard(utils.checkpoint(module))(x) + # norm_out = layer_norm(out) + # ``` + # Here there is a circular dependency: + # 1. In backward, grad_input of layer_norm aka. `out_grad` is actually dependent on `out`. + # 2. `out` depends on `out`'s backward hook created by FSDP2 (which does all-gather for `module` weights) + # in order to be recomputed. + # 3. `out`'s backward hook, as is the case for all eager backward hooks, depends on `out_grad` + # -> circular dependency with (1)! + # + # Solution: check whether `out` has a backward hook, and if so, intentionally save `out` + # in forward graph outputs. With this, we can break the above circular dependency. + node.meta["recompute"] = CheckpointPolicy.MUST_SAVE + elif ( + "ac_graph_id" not in node.meta + and any(must_recompute(user) for user in node.users) + and not ( + # Avoid saving getitem nodes which are not labeled with "ac_graph_id" + is_getitem_of_multi_output(node) and "ac_graph_id" in node.args[0].meta + ) + and is_default_partition + ): + # This node is not part of the AC region and a user is marked as recompute. + # This means it's an input to the AC region and we should save it. + # For ease of landing, gate this to default partitioner only, but we should think + # about flipping the switch in general as well. + node.meta["recompute"] = CheckpointPolicy.MUST_SAVE + return joint_module + + +def solve_min_cut( + joint_graph: fx.Graph, + node_info: NodeInfo, + min_cut_options: MinCutOptions, + dont_ban: OrderedSet[fx.Node] | None = None, +) -> tuple[list[fx.Node], OrderedSet[fx.Node]]: + if dont_ban is None: + dont_ban = OrderedSet() + op_types = get_default_op_list() + + if AOT_PARTITIONER_DEBUG: + joint_module_ops = OrderedSet( + str(node.target._overloadpacket) + for node in joint_graph.nodes + if node.op == "call_function" and hasattr(node.target, "_overloadpacket") + ) + ops_ignored = joint_module_ops - OrderedSet( + str(i) for i in op_types.recomputable_ops + ) + log.info("Ops banned from re-materialization: %s", ops_ignored) + + def can_fuse_into_auto_functionalized(a: fx.Node, b: fx.Node) -> bool: + if b.target != torch.ops.higher_order.auto_functionalized: + return False + mutable_op = b.args[0] + ( + mutable_arg_names, + _, + ) = torch._higher_order_ops.auto_functionalize.get_mutable_args( + # pyrefly: ignore[bad-argument-type] + mutable_op + ) + for name in mutable_arg_names: # pyrefly: ignore [not-iterable] + arg = b.kwargs[name] + if a is arg: + return True + if isinstance(arg, list): + if a in arg: + return True + return False + + def can_fuse_into_triton_kernel_wrapper_functional(a: fx.Node, b: fx.Node) -> bool: + if b.target != torch.ops.higher_order.triton_kernel_wrapper_functional: + return False + mutable_arg_names = b.kwargs["tensors_to_clone"] + for name in mutable_arg_names: # pyrefly: ignore [not-iterable] + kwargs: Any = b.kwargs["kwargs"] + if kwargs is None: + raise AssertionError("kwargs must not be None") + arg = kwargs[name] + if a is arg: + return True + return False + + def is_fusible(a: fx.Node, b: fx.Node) -> bool: + # We can perform "memory fusion" into a cat, but cat cannot be a + # producer to a fusion + if get_aten_target(b) == aten.cat: + return True + if can_fuse_into_auto_functionalized(a, b): + return True + if can_fuse_into_triton_kernel_wrapper_functional(a, b): + return True + if ( + a.target is operator.getitem + and a.args[0].target # pyrefly: ignore [missing-attribute] + is torch.ops.higher_order.triton_kernel_wrapper_functional + ): + # if a is the output of a user triton kernel, + # then (by default) we will not be able to fuse b into it + return False + return op_types.is_fusible(a) and op_types.is_fusible(b) + + try: + import networkx as nx + except ImportError as e: + raise RuntimeError( + "Need networkx installed to perform smart recomputation heuristics" + ) from e + + def is_materialized_backwards(node: fx.Node) -> bool: + if op_types.is_view(node): + return False + cur_nodes = OrderedSet([node]) + while len(cur_nodes) > 0: + cur = cur_nodes.pop() + for user in cur.users: + if not node_info.is_required_fw(user) and not is_fusible(cur, user): + return True + if op_types.is_view(user): + cur_nodes.add(user) + + return False + + def should_ban_recomputation(node: fx.Node) -> str | None: + """Returns reason string if node should be banned from recomputation, None otherwise.""" + if node.op != "call_function": + return None + if node.target is operator.getitem: + return None + if node.meta.get("recompute", None) == CheckpointPolicy.MUST_SAVE: + return "marked MUST_SAVE" + if config.recompute_views and op_types.is_view(node): + return None + if node.target in [aten.lift_fresh_copy.default, aten.lift_fresh.default]: + return None + + if min_cut_options.ban_if_not_in_allowlist: + if not op_types.is_recomputable(node): + return "not in recomputable allowlist" + else: + if op_types.is_random(node): + return "random op" + if op_types.is_compute_intensive(node): + return "compute intensive op" + if is_non_builtin_to_include(node): + return "non-builtin op" + + # If a node *must* be materialized in the backwards pass, then we + # should never recompute it. This is a pretty subtle point. In + # general, the assumption we make is that recomputing a node in the + # backwards pass is "free". However, if a node must be materialized + # in the backwards pass, then recomputing it is never free. + if min_cut_options.ban_if_materialized_backward and is_materialized_backwards( + node + ): + log.debug("materialized backwards: %s %s", node, tuple(node.users)) + return "materialized in backward" + + # Arbitrary hack that sometimes seems to help things. The above + # modification appears to have made this heuristic a lot less critical + # for performance. + # NB: As of PR #121692, this hack no longer seems necessary. + if ( + # pyrefly: ignore [missing-attribute] + node.dist_from_bw < 1000 and node.dist_from_bw > config.max_dist_from_bw + ): + return "too far from backward" + + # If the output of an op is 4x smaller (arbitrary choice), + # then we don't allow recomputation. The idea here is that for + # things like reductions, saving the output of the reduction is very + # cheap/small, and it makes sure we don't do things like recompute + # normalizations in the backwards. + if min_cut_options.ban_if_reduction: + input_tensors_size = sum( + _size_of(i) for i in node.args if isinstance(i, fx.Node) + ) + output_size = _size_of(node) + if output_size * 4 < input_tensors_size: + return "reduction op" + return None + + def is_materialized(node: fx.Node) -> bool: + if node.op == "placeholder": + return True + + return not all(is_fusible(node, user) for user in node.users) + + def get_node_weight( + node: fx.Node, static_lifetime_input_nodes: OrderedSet[fx.Node] + ) -> tuple[float, str | None]: + """Returns (weight, cannot_save_reason). + + cannot_save_reason is None for finite weights, or a string explaining + why the node cannot be saved for infinite weights. + """ + if ( + config.treat_parameters_as_free_to_save + and node in static_lifetime_input_nodes + ): + return 0, None + mem_sz = _size_of(node) + if config.recompute_views and op_types.is_view(node): + # If `config.recompute_views=True`, we don't save views. This is generally + # a good idea since views are free to recompute, and it makes it a bit simpler + # to analyze. + # NB: If they're not free to recompute (e.g. nested tensors)... I + # think we should modify checks for view_ops to `is_view` and check + # that. Basically, with nested tensors, `aten.view` is not a "view + # op". + return math.inf, "view op (recompute_views=True)" + + if isinstance(node.meta["val"], py_sym_types): + # We never want to save symfloats + if not isinstance(node.meta["val"], torch.SymInt): + return INT_INF, "SymFloat (non-SymInt symbolic value)" + + # Heuristic to bias towards nodes closer to the backwards pass + # Complete guess about current value + mem_sz = int( + # pyrefly: ignore [missing-attribute] + mem_sz * (1.1 ** max(min(node.dist_from_bw, 100), 1)) + ) + if is_materialized(node): + return mem_sz, None + else: + return mem_sz * 2, None + + nx_graph = nx.DiGraph() + banned_nodes: OrderedSet[fx.Node] = OrderedSet() + + def ban_recomputation_if_allowed(node: fx.Node, reason: str = "") -> bool: + if op_types.is_view(node): + return False + if node in dont_ban: + # collectives are *always* banned from recompute, overriding `dont_ban` + # (in particular, the activation memory budget logic is not allowed to recompute collectives) + is_collective = ( + isinstance(node.target, torch._ops.OpOverload) + and node.target.namespace == "_c10d_functional" + ) + if config.unsafe_allow_optimization_of_collectives or not is_collective: + return False + # This bans recomputation of the node unless we've been forced not to by + # user annotation + if must_recompute(node): + return False + + if "val" in node.meta and isinstance(node.meta["val"], torch.SymFloat): + return False + banned_nodes.add(node) + # A node will only ever be recomputed if there is a path from an + # ancestor of this node to the backwards path through this node that + # doesn't go through any saved value. If this node is saved, then that + # condition is not possible. + nx_graph.add_edge( + "source", + node.name + "_in", + capacity=math.inf, + reason=f"cannot recompute: {reason}" if reason else "cannot recompute", + ) + return True + + for node in joint_graph.nodes: + if node.op == "output": + continue + + if node in node_info.required_bw_nodes: + # See Note: [tangents_closure vs required_bw_nodes] + if node not in node_info.tangents_closure: + nx_graph.add_edge( + node.name + "_out", + "sink", + capacity=math.inf, + reason="must be available for backward: input required for gradient", + ) + else: + nx_graph.add_edge( + node.name + "_in", + "sink", + capacity=math.inf, + reason="must be computed in backward: required for gradient", + ) + continue + + if must_recompute(node): + # If user explicitly says they want to recompute a node, we honor it + # by adding an inf-capacity edge from X_in to the sink. + # This way, X_in node is guaranteed to be part of the subgraph that contains "sink" + # after the cut, thus guaranteeing that X op will be recomputed. + nx_graph.add_edge( + node.name + "_in", + "sink", + capacity=math.inf, + reason="must recompute: marked by checkpoint policy", + ) + continue + + if _is_primal(node): + ban_recomputation_if_allowed(node, "primal input") + elif _is_fwd_seed_offset(node): + ban_recomputation_if_allowed(node, "forward RNG seed") + + # If a node can't be recomputed (too expensive or involves randomness), + # we prevent it from being recomputed by adding an inf edge to the source + # We only need to ban nodes in the fw pass, as those are the only ones that would be recomputed. + ban_reason = should_ban_recomputation(node) + if node_info.is_required_fw(node) and ban_reason: + ban_recomputation_if_allowed(node, ban_reason) + + # Checks if a node is actually a tuple. Can be simplified to just an isinstance check if we always use faketensors. + is_non_tensor_node = ( + "val" not in node.meta and "tensor_meta" not in node.meta + ) or ("val" in node.meta and not isinstance(node.meta["val"], torch.Tensor)) + + if is_sym_node(node): + weight = float(sym_node_size(node)) + cannot_save_reason = None + elif is_non_tensor_node: + # FakeScriptObjects and opaque objects should have weight 0.0 + # so they can be properly partitioned between forward and + # backward, like BackwardState. + if isinstance( + node.meta.get("val"), (BackwardState, FakeScriptObject) + ) or is_opaque_node(node): + weight = 0.0 + cannot_save_reason = None + else: + weight = math.inf + cannot_save_reason = "non-tensor output" + else: + weight, cannot_save_reason = get_node_weight( + node, node_info.static_lifetime_input_nodes + ) + + # Creates the weights on the "node" edge + if cannot_save_reason and (weight == math.inf or weight == INT_INF): + nx_graph.add_edge( + node.name + "_in", + node.name + "_out", + capacity=weight, + reason=f"cannot save: {cannot_save_reason}", + ) + else: + nx_graph.add_edge(node.name + "_in", node.name + "_out", capacity=weight) + + for user in node.users: + nx_graph.add_edge( + node.name + "_out", + user.name + "_in", + capacity=math.inf, + reason="data dependency", + ) + + # todo(chilli): This is the most questionable of the 3 heuristics for banning recompute. + # Some example models to look at where this helps perf: poolformer_m36, + # mixer_b16_224, cait_m36_384 + + # The "rough" idea here is that if you have some node that is used by both a + # node nearby downstream as well as a node far downstream, if we recompute + # both of the downstream nodes, we're unlikely to be able to fuse both + # downstream nodes together. + + # Thus, we shouldn't aim to recompute far downstream nodes that depend on + # this node. That intuition of "far downstream" is captured by whether + # there's an unfusible op along the chain somewhere + + # It could probably be improved by properly analyzing what's going on in the + # backwards pass instead of only relying on whether it's unfusible in the + # forwards. + + def find_first_unfusible(start_nodes: list[fx.Node], max_range: int) -> int: + """ + Finds the first unfusible node in the chain of nodes starting from + `start_nodes` and returns its position. + """ + sorted_nodes: list[tuple[int, fx.Node, bool]] = [] + for n in start_nodes: + heapq.heappush(sorted_nodes, (node_info.get_fw_order(n), n, True)) + + while len(sorted_nodes) > 0: + _, node, node_is_fusible = heapq.heappop(sorted_nodes) + if not node_is_fusible: + return node_info.get_fw_order(node) + for user in node.users: + if node_info.is_required_fw(user): + if node_info.get_fw_order(user) > max_range: + continue + val: tuple[int, fx.Node, bool] = ( + node_info.get_fw_order(user), + user, + is_fusible(node, user), + ) + if val not in sorted_nodes: + heapq.heappush(sorted_nodes, val) + return max_range + + if min_cut_options.ban_if_used_far_apart: + for used_node in node_info.required_fw_nodes: + orders = [ + node_info.get_fw_order(user) + for user in used_node.users + if node_info.is_required_fw(user) + ] + fw_users = [ + user for user in used_node.users if node_info.is_required_fw(user) + ] + if len(orders) > 0: + first_unfusible_use = find_first_unfusible(fw_users, max(orders)) + for user in tuple(used_node.users): + if ( + node_info.is_required_fw(user) + and node_info.get_fw_order(user) > first_unfusible_use + and is_fusible(used_node, user) + ): + if user in banned_nodes: + continue + log.info( + "used above/below fusible %s:(%s) -> %s -> %s:(%s)", + used_node, + node_info.get_fw_order(used_node), + first_unfusible_use, + user, + node_info.get_fw_order(user), + ) + ban_recomputation_if_allowed(user) + + # This heuristic is fairly straightforward. The idea is that although it is + # cheap to recompute bandwidth-bound ops, we don't want to end up in a situation + # where we have a long chain of pointwise ops from the beginning to the end + # of the model (like say, residual connections) + + # todo: I'm not totally sure why this heuristic matters. It's possible that this is + # working around Inductor fusion decisions, or that it's a patch over + # suboptimal partitioning decisions + + # Some models it improves perf on are cait_m36_384, mixer_b16_224, poolformer_m36 + + if min_cut_options.ban_if_long_fusible_chains: + visited: OrderedSet[fx.Node] = OrderedSet() + for start_node in joint_graph.nodes: + if not node_info.is_required_fw(start_node): + continue + fusible: list[tuple[int, fx.Node]] = [ + (node_info.get_fw_order(start_node), start_node) + ] + start_order = node_info.get_fw_order(start_node) + while len(fusible) > 0: + _, cur = heapq.heappop(fusible) + if cur in visited: + continue + visited.add(cur) + # 100 is arbitrary choice to try and prevent degenerate cases + if ( + node_info.get_fw_order(cur) > start_order + 100 + and len(fusible) == 0 + ): + log.info( + "too long %s %s %s %s", + cur, + start_node, + node_info.get_fw_order(cur), + node_info.get_fw_order(start_node), + ) + ban_recomputation_if_allowed(cur) + break + + for user in cur.users: + if ( + node_info.is_required_fw(user) + and is_fusible(cur, user) + and user not in banned_nodes + ): + heapq.heappush(fusible, (node_info.get_fw_order(user), user)) + + try: + cut_value, partition = nx.minimum_cut(nx_graph, "source", "sink") + except nx.NetworkXUnbounded as unbounded_exc: + # Check if structured tracing is enabled (for production job debugging via tlparse) + structured_tracing_enabled = bool(trace_log.handlers) + + # Dump the FX graph for debugging + fx_graph_file: str | None = None + fx_graph_str: str | None = None + joint_module = joint_graph.owning_module + try: + fx_graph_str = ( + joint_module.print_readable( + print_output=False, include_stride=True, include_device=True + ) + if joint_module is not None + else str(joint_graph) + ) + # Always log to structured trace for production debugging + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "min_cut_failed_fx_graph", + "encoding": "string", + }, + payload_fn=lambda: fx_graph_str, + ) + # Also write to local file for local debugging + fx_graph_file = _get_unique_path("min_cut_failed_graph", ".txt") + with open(fx_graph_file, "w") as f: + f.write(fx_graph_str) + except Exception as e: + fx_graph_file = f"(failed to write: {e})" + + # Dump the min-cut edge list to structured trace + edge_list_str = "\n".join(nx.readwrite.edgelist.generate_edgelist(nx_graph)) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "min_cut_failed_edge_list", + "encoding": "string", + }, + payload_fn=lambda: edge_list_str, + ) + + # Find and report the infinite-capacity path + inf_path = _find_infinite_capacity_path(nx_graph) + if inf_path: + # Group edges by FX node and format for user understanding + # inf_path is a list of (from_node, to_node, reason) tuples + # + # Edge types and what they mean: + # - source -> X_in: X cannot be recomputed + # - X_in -> X_out (inf): X's output cannot be saved + # - X_out -> Y_in: Y depends on X (data flow) + # - X_in -> sink: X must be computed in backward + # - X_out -> sink: X's output must be available for backward + + # Build a user-friendly explanation grouped by FX node + node_constraints: dict[str, list[str]] = {} + raw_path_nodes = ["source"] + + def get_base_name(node_name: str) -> str: + for suffix in ("_in", "_out"): + if node_name.endswith(suffix): + return node_name[: -len(suffix)] + return node_name + + for from_node, to_node, reason in inf_path: + raw_path_nodes.append(to_node) + + # Skip source/sink, focus on FX nodes + if from_node == "source": + base = get_base_name(to_node) + node_constraints.setdefault(base, []).append(reason) + elif to_node == "sink": + base = get_base_name(from_node) + node_constraints.setdefault(base, []).append(reason) + elif get_base_name(from_node) == get_base_name(to_node): + # Internal edge (X_in -> X_out) + base = get_base_name(from_node) + node_constraints.setdefault(base, []).append(reason) + else: + # Data dependency edge (X_out -> Y_in) + from_base = get_base_name(from_node) + to_base = get_base_name(to_node) + node_constraints.setdefault(to_base, []).append( + f"depends on {from_base}" + ) + + # Format the constraints nicely + constraint_lines: list[str] = [] + for node_name, constraints in node_constraints.items(): + constraint_lines.append(f" {node_name}:") + for c in constraints: + constraint_lines.append(f" - {c}") + + constraints_str = "\n".join(constraint_lines) + raw_path_str = " -> ".join(raw_path_nodes) + + # Try to visualize (logs to structured trace and writes local file) + svg_path, svg_content = visualize_min_cut_graph(nx_graph) + if svg_content: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "min_cut_failed_svg", + "encoding": "string", + }, + payload_fn=lambda: svg_content, + ) + + # Build file location messages + local_files_msg = ( + f"FX graph dump: {fx_graph_file}\n" if fx_graph_file else "" + ) + if svg_path: + local_files_msg += f"Min-cut graph visualization: {svg_path}\n" + + # Suggest tlparse if structured tracing is enabled + tlparse_msg = "" + if structured_tracing_enabled: + tlparse_msg = ( + "[Production debugging: Use tlparse to extract debug artifacts " + "(min_cut_failed_fx_graph, min_cut_failed_edge_list, min_cut_failed_svg)]\n" + ) + + raise RuntimeError( + f"AOT Autograd failed to partition the joint forward-backward graph.\n\n" + f"The partitioner determines which intermediate values to save from the " + f"forward pass vs recompute in the backward pass. This error means a value " + f"is required for backward, but cannot be saved AND cannot be recomputed.\n\n" + f"This is a bug in PyTorch. Please file an issue at " + f"https://github.com/pytorch/pytorch/issues\n\n" + f"Nodes involved in the conflict:\n" + f"{constraints_str}\n\n" + f"[For PyTorch developers: one of the above constraints is wrong. " + f"Either the node should be recomputable, saveable, or not required for backward.]\n\n" + f"[Debug: min-cut path] {raw_path_str}\n" + f"{local_files_msg}" + f"{tlparse_msg}" + ) from unbounded_exc + + # Fallback if we couldn't find the path + log.info("Failed to compute min-cut on following graph:") + log.info( + "%s", + LazyString( + lambda: "\n".join(nx.readwrite.edgelist.generate_edgelist(nx_graph)) + ), + ) + visualize_min_cut_graph(nx_graph) + raise + except Exception: + log.info("Failed to compute min-cut on following graph:") + log.info( + "%s", + LazyString( + lambda: "\n".join(nx.readwrite.edgelist.generate_edgelist(nx_graph)) + ), + ) + visualize_min_cut_graph(nx_graph) + raise + + reachable, non_reachable = partition + cutset: OrderedSet[tuple[str, str]] = OrderedSet() + for u, nbrs in ((n, nx_graph[n]) for n in reachable): + cutset.update((u, v) for v in nbrs if v in non_reachable) + + cut_nodes: OrderedSet[str] = OrderedSet() + for node_in, node_out in cutset: + if node_in[:-3] != node_out[:-4]: + raise AssertionError( + f"node_in[:-3]={node_in[:-3]} != node_out[:-4]={node_out[:-4]}" + ) + node_name = node_in[:-3] + cut_nodes.add(node_name) + + name_to_node = get_name_to_node(joint_graph) + # To make this stuff deterministic + node_idx = {node: idx for idx, node in enumerate(joint_graph.nodes)} + saved_values = sorted( + (name_to_node[node] for node in cut_nodes), key=lambda x: node_idx[x] + ) + return saved_values, banned_nodes + + +def _find_infinite_capacity_path( + nx_graph: nx.DiGraph[str, dict[str, Any]], +) -> list[tuple[str, str, str]] | None: + """BFS from source to sink following only infinite-capacity edges. + + Returns a list of (from_node, to_node, reason) tuples representing the path, + or None if no such path exists. + """ + + visited = OrderedSet(["source"]) + # Each queue item: (current_node, path_of_edges) + # where path_of_edges is a list of (from_node, to_node, reason) tuples + queue: deque[tuple[str, list[tuple[str, str, str]]]] = deque([("source", [])]) + + while queue: + node, edge_path = queue.popleft() + for neighbor in nx_graph.successors(node): + if neighbor in visited: + continue + edge_data = nx_graph[node][neighbor] + capacity = edge_data.get("capacity", 0) + # Check for infinite capacity (either math.inf or INT_INF) + if capacity == math.inf or capacity == INT_INF: + reason = edge_data.get("reason", "unknown") + new_edge = (node, neighbor, reason) + new_path = edge_path + [new_edge] + if neighbor == "sink": + return new_path + visited.add(neighbor) + queue.append((neighbor, new_path)) + return None + + +def _get_unique_path(base_name: str, extension: str) -> str: + """Get a unique file path, appending a counter if the file already exists. + + For example, if "min_cut_failed.svg" exists, returns "min_cut_failed_1.svg". + """ + path = f"{base_name}{extension}" + if not os.path.exists(path): + return path + + counter = 1 + while os.path.exists(f"{base_name}_{counter}{extension}"): + counter += 1 + return f"{base_name}_{counter}{extension}" + + +def visualize_min_cut_graph( + nx_graph: nx.DiGraph[str, dict[str, Any]], +) -> tuple[str | None, str | None]: + """Visualize the min-cut graph to an SVG file. + + Returns (path_to_svg, svg_content) tuple. Both are None if pydot is unavailable. + """ + import networkx as nx + + try: + import pydot + except ImportError: + log.info( + "Install pydot to visualize the min-cut graph for debugging: pip install pydot", + exc_info=True, + ) + return None, None + + dot_format = nx.nx_pydot.to_pydot(nx_graph).to_string() + dot_graph = pydot.graph_from_dot_data(dot_format)[0] # type: ignore[index] + for edge in dot_graph.get_edges(): + weight = nx_graph[edge.get_source()][edge.get_destination()]["capacity"] + # Set edge label to weight + edge.set_label(str(weight)) # type: ignore[union-attr] + # Color edges with weight 'inf' as red + if weight == float("inf"): + edge.set_color("red") # type: ignore[union-attr] + + # Generate SVG content + svg_content = dot_graph.create_svg().decode("utf-8") # type: ignore[union-attr] + + # Write to local file + svg_path = _get_unique_path("min_cut_failed", ".svg") + with open(svg_path, "w") as f: + f.write(svg_content) + + return svg_path, svg_content + + +def get_default_op_list() -> OpTypes: + default_recomputable_ops: list[Callable[..., Any]] = [ + aten.add, + aten.sub, + aten.div, + aten.atan2, + aten.mul, + aten.max, + aten.min, + aten.pow, + aten.remainder, + aten.fmod, + aten.__and__, + aten.__or__, + aten.__xor__, + aten.__lshift__, + aten.__rshift__, + aten.eq, + aten.ne, + aten.ge, + aten.gt, + aten.le, + aten.lt, + aten.abs, + aten.bitwise_not, + aten.ceil, + aten.floor, + aten.frac, + aten.neg, + aten.relu, + aten.round, + aten.silu, + aten.trunc, + aten.log, + aten.log10, + aten.log1p, + aten.log2, + aten.lgamma, + aten.exp, + aten.expm1, + aten.erf, + aten.erfc, + aten.cos, + aten.acos, + aten.cosh, + aten.sin, + aten.asin, + aten.sinh, + aten.tan, + aten.atan, + aten.tanh, + aten.atanh, + aten.sqrt, + aten.rsqrt, + aten.reciprocal, + aten.sigmoid, + aten.softplus, + aten.threshold, + aten.threshold_backward, + aten.clamp, + aten.where, + aten.lerp, + aten.addcmul, + aten.gelu, + aten.gelu_backward, + aten.sum, + aten.mean, + aten._grad_sum_to_size, + aten.sum_to_size, + aten.amax, + aten.to, + aten.type_as, + operator.getitem, + aten.squeeze, + aten.unsqueeze, + aten.rsub, + aten._to_copy, + ] + recomputable_view_ops = [aten.squeeze, aten.unsqueeze, aten.alias] + recomputable_view_ops += [ + aten.view, + aten.slice, + aten.t, + prims.broadcast_in_dim, + aten.expand, + aten.as_strided, + aten.permute, + aten.select, + aten.split, + ] + view_ops = recomputable_view_ops + default_recomputable_ops += [ + prims.div, + prims.convert_element_type, + prims.prepare_softmax_online, + aten.clone, + aten._to_copy, + aten.full_like, + prims.var, + prims.sum, + aten.var, + aten.std, + prims.broadcast_in_dim, + aten.select, + aten._unsafe_view, + aten.view, + aten.expand, + aten.slice, + aten.reshape, + aten.broadcast_tensors, + aten.scalar_tensor, + aten.ones, + aten.new_zeros, + aten.lift_fresh_copy, + aten.arange, + aten.triu, + aten.var_mean, + aten.isinf, + aten.any, + aten.full, + aten.as_strided, + aten.zeros, + aten.empty, + aten.empty_like, + aten.argmax, + aten.maximum, + prims.iota, + prims._low_memory_max_pool_offsets_to_indices, + ] + # Natalia said that we should allow recomputing indexing :) + default_recomputable_ops += [aten.index, aten.gather] + default_recomputable_ops += view_ops + + default_recomputable_ops += pointwise_ops() + + default_recomputable_ops += [ + aten.zeros_like, + ] + + default_recomputable_ops += [method_to_operator(m) for m in magic_methods] + recomputable_ops = OrderedSet(default_recomputable_ops) + + random_ops = OrderedSet[Callable[..., Any]]( + [aten.native_dropout, aten.rand_like, aten.randn_like] + ) + compute_intensive_ops = [ + aten.mm, + aten.convolution, + aten.convolution_backward, + aten.bmm, + aten.addmm, + aten._scaled_dot_product_flash_attention, + aten._scaled_dot_product_efficient_attention, + aten._flash_attention_forward, + aten._efficient_attention_forward, + aten.upsample_bilinear2d, + aten._scaled_mm, + ] + + fusible_ops = recomputable_ops | random_ops + return OpTypes( + fusible_ops, + OrderedSet(compute_intensive_ops), + random_ops, + OrderedSet(view_ops), + recomputable_ops, + ) + + +def get_name_to_node(graph: fx.Graph) -> dict[str, fx.Node]: + name_to_node: dict[str, fx.Node] = {} + for node in graph.nodes: + name_to_node[node.name] = node + return name_to_node + + +def _optimize_runtime_with_given_memory( + joint_graph: fx.Graph, + memory: list[float], + runtimes: list[float], + max_memory: float, + node_info: NodeInfo, + all_recomputable_banned_nodes: list[fx.Node], +) -> tuple[float, list[int], list[int]]: + SOLVER = config.activation_memory_budget_solver + if SOLVER == "greedy": + return greedy_knapsack(memory, runtimes, max_memory) + elif SOLVER == "ilp": + return ilp_knapsack(memory, runtimes, max_memory) + elif SOLVER == "dp": + return dp_knapsack(memory, runtimes, max_memory) + elif SOLVER == "dp_knapsack_sliding_hirschberg": + return dp_knapsack_sliding_hirschberg(memory, runtimes, max_memory) + elif SOLVER == "dynamic_memory_budget_dp": + log.warning( + "dynamic_memory_budget_dp is an experimental solver. " + "It does not guarantee performance improvements. " + "Additionally, it is not guaranteed to be stable." + ) + graph_info_provider = GraphInfoProvider.inialize_from_graph( + joint_graph=joint_graph, + all_recomputable_banned_nodes=all_recomputable_banned_nodes, + recorded_knapsack_input_memories=memory, + recorded_knapsack_input_runtimes=runtimes, + ) + return dp_knapsack( + memory, + runtimes, + KnapsackEvaluator( + graph_info_provider=graph_info_provider, + ).get_knee_point_memory_budget( + knapsack_algo=dp_knapsack, + max_mem_budget=max_memory, + ), + ) + elif isinstance(SOLVER, CustomKnapsackSolver): + saved_node_idx, recomp_node_idx = SOLVER( + memory, joint_graph, max_memory, node_info, all_recomputable_banned_nodes + ) + return (0.0, saved_node_idx, recomp_node_idx) + else: + raise RuntimeError(f"Not aware of memory budget knapsack solver: {SOLVER}") + + +from torch.utils._mode_utils import no_dispatch + + +# replace symbols in size and strides with their hints without guarding. +def _remove_symbols_without_guarding(x: torch.Tensor, fallback: int) -> torch.Tensor: + shape = list(x.shape) + + def realize_symbol(d: torch.SymInt | int) -> int: + return optimization_hint(d, fallback=fallback) + + shape = [realize_symbol(s) for s in shape] + stride = [realize_symbol(s) for s in x.stride()] + return x.new_empty_strided(shape, stride=stride) + + +def estimate_runtime(node: fx.Node) -> float: + RUNTIME_MODE = config.activation_memory_budget_runtime_estimator + + def materialize_arg(x: Any) -> Any: + if isinstance(x, fx.Node) and isinstance(x.meta["val"], torch.Tensor): + return _remove_symbols_without_guarding(x.meta["val"], fallback=4096) + elif isinstance(x, fx.Node) and isinstance(x.meta["val"], torch.SymInt): + return optimization_hint(x.meta["val"], fallback=4096) + elif isinstance(x, fx.Node) and isinstance(x.meta["val"], torch.SymFloat): + return 1.0 + elif isinstance(x, fx.Node) and isinstance(x.meta["val"], torch.SymBool): + return True + else: + return x + + if RUNTIME_MODE == "testing": + return 1 + + elif RUNTIME_MODE == "profile": + with no_dispatch(): + from torch._inductor.runtime.benchmarking import benchmarker + + args, kwargs = pytree.tree_map(materialize_arg, (node.args, node.kwargs)) + # pyrefly: ignore[not-callable] + ms = benchmarker.benchmark_gpu(lambda: node.target(*args, **kwargs)) + return ms + + elif RUNTIME_MODE == "flops": + # todo(chilli): Normalize this to also return ms + from torch.utils.flop_counter import FlopCounterMode + + args, kwargs = pytree.tree_map(materialize_arg, (node.args, node.kwargs)) + with FlopCounterMode(display=False) as mode: + # pyrefly: ignore[not-callable] + node.target(*args, **kwargs) + counted_flops = mode.get_total_flops() + return max(counted_flops, 1) + + elif isinstance(RUNTIME_MODE, CustomRuntimeEstimator): + return RUNTIME_MODE(node) + + else: + raise RuntimeError(f"Not aware of runtime estimator: {RUNTIME_MODE}") + + +def choose_saved_values_set( + joint_graph: fx.Graph, + node_info: NodeInfo, + memory_budget: float = 1, +) -> list[fx.Node]: + if memory_budget > 1 or memory_budget < 0: + raise RuntimeError( + f"The valid ranges for memory budget are 0 <= m <= 1. The provided value is {memory_budget}" + ) + min_cut_options = MinCutOptions( + ban_if_used_far_apart=config.ban_recompute_used_far_apart, + ban_if_long_fusible_chains=config.ban_recompute_long_fusible_chains, + ban_if_materialized_backward=config.ban_recompute_materialized_backward, + ban_if_not_in_allowlist=config.ban_recompute_not_in_allowlist, + ban_if_reduction=config.ban_recompute_reductions, + ) + + if config.aggressive_recomputation: + min_cut_options = replace( + min_cut_options, + ban_if_used_far_apart=False, + ban_if_long_fusible_chains=False, + ban_if_materialized_backward=False, + ban_if_not_in_allowlist=False, + ) + if memory_budget == 0: + return node_info.inputs + + runtime_optimized_saved_values, _ = solve_min_cut( + joint_graph, + node_info, + min_cut_options, + ) + # return runtime_optimized_saved_values + if memory_budget == 1: + return runtime_optimized_saved_values + + def estimate_activations_size(saved_values: list[fx.Node]) -> float: + return sum(map(_size_of, saved_values)) / 1e9 + + min_act_size = estimate_activations_size(node_info.inputs) + max_act_size = estimate_activations_size(runtime_optimized_saved_values) + # The optimized choice is smaller than the inputs anyways + if max_act_size <= min_act_size: + return runtime_optimized_saved_values + + def get_normalized_size(sz: float) -> float: + return (sz / 1e9) / (max_act_size - min_act_size) + + def get_mem_ratio(activations: list[fx.Node]) -> float: + return (estimate_activations_size(activations) - min_act_size) / ( + max_act_size - min_act_size + ) + + more_aggressive_options = replace( + min_cut_options, + ban_if_used_far_apart=False, + ban_if_long_fusible_chains=False, + ban_if_materialized_backward=False, + ) + more_aggressive_saved_values, _ = solve_min_cut( + joint_graph, node_info, more_aggressive_options + ) + more_aggressive_saved_values_mem_ratio = get_mem_ratio(more_aggressive_saved_values) + if more_aggressive_saved_values_mem_ratio < memory_budget: + return more_aggressive_saved_values + + aggressive_options = replace( + more_aggressive_options, + ban_if_not_in_allowlist=False, + ) + aggressive_recomputation_saved_values, banned_nodes = solve_min_cut( + joint_graph, node_info, aggressive_options + ) + + aggressive_recomputation_saved_values_mem_ratio = get_mem_ratio( + aggressive_recomputation_saved_values + ) + if aggressive_recomputation_saved_values_mem_ratio < memory_budget: + return aggressive_recomputation_saved_values + + from torch._inductor.fx_utils import get_node_storage + + input_storages = OrderedSet(get_node_storage(node) for node in node_info.inputs) + + def get_recomputable_banned_nodes( + banned_nodes: OrderedSet[fx.Node], + ) -> list[fx.Node]: + return [ + i + for i in banned_nodes + if ( + # Only allow recomputing nodes that are actually required for BW + i.dist_from_bw < int(1e9) # type: ignore[attr-defined] + and ( + get_node_storage(i) not in input_storages + or is_non_builtin_to_include(i) + ) + ) + ] + + recomputable_banned_nodes = get_recomputable_banned_nodes(banned_nodes) + must_save_nodes = [ + i + for i in recomputable_banned_nodes + if i.meta.get("recompute", False) == CheckpointPolicy.MUST_SAVE + ] + recomputable_banned_nodes = [ + i for i in recomputable_banned_nodes if i not in must_save_nodes + ] + + # default: runtime_optimized_saved_values + # more aggressive: more_aggressive_saved_values + # full aggressive: aggressive_recomputation_saved_values + + all_recomputable_banned_nodes = sorted( + recomputable_banned_nodes, key=_size_of, reverse=True + ) + if len(all_recomputable_banned_nodes) == 0: + # Nothing left for the knapsack to trade off, so this is the same cut the + # knapsack would return with an empty dont_ban. + return aggressive_recomputation_saved_values + memories_banned_nodes = [ + get_normalized_size(_size_of(i)) for i in all_recomputable_banned_nodes + ] + runtimes_banned_nodes = [ + estimate_runtime(node) for node in all_recomputable_banned_nodes + ] + from torch.utils._mode_utils import no_dispatch + + def get_saved_values_knapsack( + memory_budget: float, node_info: NodeInfo, joint_graph: fx.Graph + ) -> tuple[list[fx.Node], float]: + with no_dispatch(): + ( + expected_runtime, + saved_node_idxs, + recomputable_node_idxs, + ) = _optimize_runtime_with_given_memory( + joint_graph, + memories_banned_nodes, + runtimes_banned_nodes, + max(memory_budget, 0), + node_info, + all_recomputable_banned_nodes, + ) + dont_ban: OrderedSet[fx.Node] = OrderedSet() + for idx in recomputable_node_idxs: + # if idx in all_recomputable_banned_nodes: + try: + dont_ban.add(all_recomputable_banned_nodes[idx]) + except BaseException: + pass + + if not dont_ban.issubset(all_recomputable_banned_nodes): + raise AssertionError( + "dont_ban must be a subset of all_recomputable_banned_nodes" + ) + + saved_values, _ = solve_min_cut( + joint_graph, + node_info, + aggressive_options, + dont_ban, + ) + if AOT_PARTITIONER_DEBUG: + create_structured_trace_for_min_cut_info( + joint_graph=joint_graph, + all_recomputable_banned_nodes=all_recomputable_banned_nodes, + saved_node_idxs=saved_node_idxs, + recomputable_node_idxs=recomputable_node_idxs, + expected_runtime=expected_runtime, + memories_banned_nodes=[ + _size_of(i) for i in all_recomputable_banned_nodes + ], + normalized_memories_banned_nodes=memories_banned_nodes, + runtimes_banned_nodes=runtimes_banned_nodes, + min_cut_saved_values=saved_values, + memory_budget=memory_budget, + min_act_size=min_act_size, + max_act_size=max_act_size, + saved_values_act_size=estimate_activations_size(saved_values), + more_aggressive_saved_values_mem_ratio=more_aggressive_saved_values_mem_ratio, + aggressive_recomputation_saved_values_mem_ratio=aggressive_recomputation_saved_values_mem_ratio, + ) + return saved_values, expected_runtime + + if config.visualize_memory_budget_pareto: + + def estimate_for_budget(b: float) -> tuple[float, float, float]: + saved_values, expected_runtime = get_saved_values_knapsack( + b, node_info=node_info, joint_graph=joint_graph + ) + return ( + b, + sum(runtimes_banned_nodes) - expected_runtime, + get_mem_ratio(saved_values), + ) + + options = [estimate_for_budget(0.0), estimate_for_budget(1.0)] + + if options[0][1:] != options[1][1:]: + bisects = [(options[0], options[1])] + while bisects: + lhs, rhs = bisects.pop() + if rhs[0] - lhs[0] < 1e-3: + options.append(lhs) + options.append(rhs) + continue + mid = estimate_for_budget((lhs[0] + rhs[0]) / 2) + if mid[1:] != lhs[1:]: + bisects.append((lhs, mid)) + if mid[1:] != rhs[1:]: + bisects.append((mid, rhs)) + options.sort() + + import matplotlib.pyplot as plt + + x_values = [item[2] for item in options] + y_values = [item[1] for item in options] + + # Plotting the values with updated axis labels and chart title + plt.figure(figsize=(10, 6)) + plt.plot(x_values, y_values, marker="o") + + # Adding labels for each point + for i, txt in enumerate(x_values): + plt.annotate( + f"{txt:.4f}", + (txt, y_values[i]), + textcoords="offset points", + xytext=(0, 10), + ha="center", + ) + + plt.xlabel("Memory Budget") + plt.ylabel("Runtime of Recomputed Components") + plt.title("Pareto Frontier of Memory Budget vs. Recomputation Runtime") + plt.grid(True) + fig = plt.gcf() + plt.show() + fig_dir = os.getcwd() + if config.memory_budget_pareto_dir is not None: + fig_dir = config.memory_budget_pareto_dir + os.makedirs(fig_dir, exist_ok=True) + rank_suffix = "" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + rank_suffix = f"_rank_{torch.distributed.get_rank()}" + fig_name = os.path.join( + fig_dir, f"memory_budget_pareto{rank_suffix}_{get_aot_graph_name()}.svg" + ) + fig.savefig(fig_name) + log.warning("Generated Pareto frontier curve at %s", fig_name) + + # todo(chilli): Estimated doesn't align exactly with actual - actual is + # usually less memory than estimated. i'm guessing (actually quite + # unsure about this) that's because estimated is just only including + # tensors we actually banned from recompute, but there may be other + # tensors that we choose to save. + + return get_saved_values_knapsack( + memory_budget=memory_budget, node_info=node_info, joint_graph=joint_graph + )[0] + + +def _stable_target_str(target: Any) -> str: + """Stringify a node target stably across processes. + + ``str()`` on a plain Python-function target (e.g. ``torch.sym_not``) renders + its ``repr`` including the object's memory address (````), which differs per process. That poisons cross-rank graph hashing. + Use FX's qualified name for callables so equal graphs hash equally. + """ + from torch.fx.node import _get_qualified_name + + if callable(target): + try: + return _get_qualified_name(target) + except Exception: + return str(target) + return str(target) + + +def _cone_hashes(graph: torch.fx.Graph) -> dict[torch.fx.Node, str]: + """Compute a forward-looking structural hash for each node. + + Each node's hash captures its "role" in the graph toward the output: + hash(self_key, sorted(cone_hash(user) for user in users)). + + For placeholders, self_key uses tensor metadata instead of the node name + (which varies across ranks). This makes the hash invariant to the original + node naming and ordering. + """ + hashes: dict[torch.fx.Node, str] = {} + for node in reversed(list(graph.nodes)): + if node.op == "placeholder": + val = node.meta.get("val") + if isinstance(val, torch.Tensor): + # Exclude shape: different ranks may have different input + # shapes (e.g., shard sizes) for structurally identical graphs. + self_key: tuple[Any, ...] = ( + "placeholder", + str(val.dtype), + val.requires_grad, + ) + elif isinstance(val, torch.SymInt): + self_key = ("placeholder", "symint") + else: + self_key = ("placeholder",) + elif node.op == "output": + self_key = ("output",) + else: + self_key = (node.op, _stable_target_str(node.target)) + + user_hashes = tuple(sorted(hashes[u] for u in node.users)) + hashes[node] = hashlib.sha256( + str((self_key, user_hashes)).encode("utf-8") + ).hexdigest() + + return hashes + + +def _canonical_node_names(graph: torch.fx.Graph) -> dict[torch.fx.Node, str]: + """Build a canonical name mapping for graph nodes using Kahn's algorithm. + + Returns a dict mapping each node to a deterministic name like "node_0", + "node_1", etc. The mapping is invariant to the original node ordering and + naming, so structurally equivalent graphs (e.g., traced with different dict + iteration orders across distributed ranks) produce identical mappings. + + Does NOT modify the graph. + """ + cone = _cone_hashes(graph) + + indeg: dict[torch.fx.Node, int] = dict.fromkeys(graph.nodes, 0) + for node in graph.nodes: + for user in node.users: + indeg[user] += 1 + + canonical_idx: dict[torch.fx.Node, int] = {} + + def _canonical_key(node: torch.fx.Node) -> tuple[Any, ...]: + if node.op == "placeholder": + val = node.meta.get("val") + if isinstance(val, torch.Tensor): + # Exclude shape: different ranks may have different input + # shapes (e.g., shard sizes) for structurally identical graphs. + meta_key: tuple[Any, ...] = ( + str(val.dtype), + val.requires_grad, + ) + elif isinstance(val, torch.SymInt): + meta_key = ("symint",) + else: + meta_key = () + return (0, meta_key, cone[node]) + elif node.op == "get_attr": + return (1, str(node.target)) + elif node.op == "output": + return (3,) + else: + input_indices = tuple(canonical_idx[n] for n in node.all_input_nodes) + return (2, _stable_target_str(node.target), input_indices) + + # Seed the heap with nodes that have no dependencies. + # The counter ensures deterministic ordering when keys are equal. + counter = 0 + ready: list[tuple[tuple[Any, ...], int, fx.Node]] = [] + for node in graph.nodes: + if indeg[node] == 0: + heapq.heappush(ready, (_canonical_key(node), counter, node)) + counter += 1 + + canonical_order: list[fx.Node] = [] + + while ready: + _, _, cur = heapq.heappop(ready) + canonical_order.append(cur) + canonical_idx[cur] = len(canonical_idx) + + for user in cur.users: + indeg[user] -= 1 + if indeg[user] == 0: + heapq.heappush(ready, (_canonical_key(user), counter, user)) + counter += 1 + + return {node: f"node_{i}" for i, node in enumerate(canonical_order)} + + +def _sync_decision_cross_ranks( + joint_graph: torch.fx.Graph, saved_values: list[torch.fx.Node] +) -> list[torch.fx.Node]: + # use the same policy across different GPUs + from torch._subclasses.fake_tensor import unset_fake_temporarily + + def has_collectives(joint_graph: torch.fx.Graph) -> bool: + for node in joint_graph.nodes: + if isinstance( + node.target, torch._ops.OpOverload + ) and node.target.namespace in {"_c10d_functional", "c10d_functional"}: + return True + return False + + if not ( + torch.distributed.is_available() + and torch.distributed.is_initialized() + and torch.distributed.get_world_size() > 1 + and has_collectives(joint_graph) + ): + return saved_values + + canonical = _canonical_node_names(joint_graph) + reverse_canonical = {v: k for k, v in canonical.items()} + + def has_same_nodes(joint_graph: torch.fx.Graph) -> bool: + # Use canonical names for a hash that is invariant to node ordering + # and naming. This correctly identifies structurally equivalent graphs + # even when different ranks trace with different dict iteration orders. + def _node_hash_str(n: torch.fx.Node) -> str: + # For placeholders, n.target is the rank-local name (e.g., + # primals_1) which may refer to different inputs on different + # ranks. Use only the canonical name and op for these. + if n.op == "placeholder": + return f"{canonical[n]}:{n.op}" + return f"{canonical[n]}:{n.op}:{_stable_target_str(n.target)}" + + node_str = "/".join( + _node_hash_str(n) + for n in sorted(joint_graph.nodes, key=lambda n: canonical[n]) + ) + inputs = hashlib.sha256(node_str.encode("utf-8")).hexdigest() + all_inputs = [None for _ in range(torch.distributed.get_world_size())] + with no_dispatch(), unset_fake_temporarily(): + # TODO: maybe use a different process group? + torch.distributed.all_gather_object(all_inputs, inputs) + for rank, x in enumerate(all_inputs): + if all_inputs[0] != x: + log.debug( + "Skipping sync decision cross rank due to different inputs between rank 0 and rank %s", + rank, + ) + return False + return True + + if has_same_nodes(joint_graph): + with no_dispatch(), unset_fake_temporarily(): + # Communicate saved values using canonical names so that + # node names (which may differ across ranks) don't matter. + objects = [[canonical[x] for x in saved_values]] + saved_ops_names_all_ranks: list[list[str]] = [ + [] for _ in range(torch.distributed.get_world_size()) + ] + torch.distributed.all_gather_object(saved_ops_names_all_ranks, objects[0]) + saved_sizes: list[int] = [] + saved_ops_with_sizes: dict[str, int] = {} + + for idx, saved_ops_names in enumerate(saved_ops_names_all_ranks): + saved_nodes = [ + reverse_canonical[op_name] for op_name in saved_ops_names + ] + saved_size = 0 + for node in saved_nodes: + size_of_node = _size_of(node) + saved_size += size_of_node + if idx == torch.distributed.get_rank(): + saved_ops_with_sizes[node.name] = size_of_node + saved_ops_with_sizes["total size"] = saved_size + saved_sizes.append(saved_size) + + saved_sizes_tensor = torch.tensor( + saved_sizes, + device=torch.distributed.distributed_c10d._get_object_coll_device(), + ) + torch.distributed.all_reduce( + saved_sizes_tensor, op=torch.distributed.distributed_c10d.ReduceOp.MAX + ) + + picked_rank_idx = int(torch.argmin(saved_sizes_tensor).item()) + sync_decision_cross_ranks_str = f"picked_rank_idx={picked_rank_idx}, saved_nodes of current rank={saved_ops_with_sizes}" + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_joint_graph_sync_decision_cross_ranks", + "encoding": "string", + }, + payload_fn=lambda: sync_decision_cross_ranks_str, + ) + + saved_values = [ + reverse_canonical[n] for n in saved_ops_names_all_ranks[picked_rank_idx] + ] + + return saved_values + + +def thread_graphsafe_rng_from_hops( + module: fx.GraphModule, is_backward: bool +) -> fx.GraphModule: + """ + Graph-safe RNG lets torch.compile use CUDA Graphs for graphs with RNG ops. + For graphs without HOPs, the partitioner adds placeholder nodes + fwd_rng_state_* and bw_rng_state_* to the forward and backward graphs. At + runtime, the AOTDispatcher retrieves these RNG states and passes them to the + compiled graphs. + + This works well for no-HOP graphs. With HOPs, the partitioner runs + recursively: it first partitions the HOP (producing forward/backward HOP + subgraphs) and then stitches them back into the outer joint graph. For HOPs + that contain RNG ops, the outer joint graph now includes HOP subgraph + modules with extra RNG placeholders. We must thread these placeholders + through the outer module partitioned forward and backward graphs—this + function does exactly that. It collects the RNG placeholder nodes from the + HOPs and creates corresponding placeholders in the outer forward and + backward graphs. + + There is a catch: for a short period, the joint graph is in a “bad” state. + The HOP subgraphs expect additional inputs (because of the new + placeholders), but the outer graph call sites don't yet provide them. We + can't fix this in the joint graph because the joint graph's input signature + is fixed (primals, tangents). As a compromise, we keep the joint graph in + somewhat of a bad state for some time and, once the outer forward and + backward graphs are partitioned, insert the corresponding RNG placeholders + and wire up the calls. + """ + + rng_count = 0 + rng_string = "bwd_rng_state" if is_backward else "fwd_rng_state" + last_input = next(reversed(module.graph.find_nodes(op="placeholder"))) + for hop_node in module.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ): + subgraph = getattr(module, hop_node.args[0].target) + if isinstance(subgraph, fx.GraphModule): + new_rng_inputs: list[fx.Node] = [] + for placeholder_node in subgraph.graph.find_nodes(op="placeholder"): + if rng_string in placeholder_node.name: + # Found a rng state placeholder in the hop graph, lets add + # the corresponding node in the outer graph + with module.graph.inserting_after(last_input): + rng_state = module.graph.placeholder( + f"{rng_string}_{rng_count}" + ) + rng_count += 1 + rng_state.meta["val"] = placeholder_node.meta["val"] + last_input = rng_state + new_rng_inputs.append(rng_state) + + if new_rng_inputs: + # Pass on the new args that include the new_rng_inputs + with module.graph.inserting_after(hop_node): + new_hop_node_with_fixed_args = module.graph.create_node( + "call_function", + torch.ops.higher_order.invoke_subgraph, + (*hop_node.args, *new_rng_inputs), # type: ignore[arg-type] + {}, + ) + hop_node.replace_all_uses_with( + new_hop_node_with_fixed_args, propagate_meta=True + ) + + # Setup the eager_input_vals + eager_vals = hop_node.meta.get("eager_input_vals") + if eager_vals: + eager_args, eager_kwargs = eager_vals + new_eager_args = ( + *eager_args, + *[inp.meta["val"] for inp in new_rng_inputs], + ) + new_hop_node_with_fixed_args.meta["eager_input_vals"] = ( + new_eager_args, + eager_kwargs, + ) + module.graph.erase_node(hop_node) + + return module + + +def classify_nodes( + joint_module: fx.GraphModule, + static_lifetime_input_indices: list[int], + num_fwd_outputs: int, +) -> NodeInfo: + name_to_node = get_name_to_node(joint_module.graph) + required_bw_nodes: OrderedSet[fx.Node] = OrderedSet() + for node in joint_module.graph.nodes: + if node.op == "placeholder" and "tangents" in node.target: + required_bw_nodes.add(node) + elif _must_be_in_backward(node): + required_bw_nodes.add(node) + + if node in required_bw_nodes: + if node.op == "call_function" and node.target is control_deps_hop: + # control_deps mixes forward and backward deps. Only + # propagate required_bw to getitem users that extract a + # backward-only dep. getitem(cd, k) with k>=1 maps to + # deps[k-1] (args[k+1]). + deps = node.args[2:] + for user in node.users: + if ( + user.target is operator.getitem + and isinstance(user.args[1], int) + and 1 <= user.args[1] <= len(deps) + ): + dep = deps[user.args[1] - 1] + if isinstance(dep, fx.Node) and dep in required_bw_nodes: + required_bw_nodes.add(user) + else: + # Chained control_deps (e.g. wait/sync cd depends on + # the record's cd via additional_deps) -- taint + # conservatively. + required_bw_nodes.add(user) + else: + required_bw_nodes.update(node.users) + + primal_inputs = list(filter(_is_primal, joint_module.graph.nodes)) + fwd_seed_offset_inputs = list(filter(_is_fwd_seed_offset, joint_module.graph.nodes)) + inputs = primal_inputs + fwd_seed_offset_inputs + fwd_outputs, bwd_outputs, fwd_outputs_descs, bwd_outputs_descs = ( + _extract_fwd_bwd_outputs(joint_module, num_fwd_outputs=num_fwd_outputs) + ) + # Note: [tangents_closure vs required_bw_nodes] + # + # required_bw_nodes is used to determine which nodes need edges to + # the sink. It is important to also track tangents closure because + # that determines whether you can save that tensor, i.e., whether you + # want to connect x_in or x_out to the sink. + tangents_closure = required_bw_nodes.copy() + required_bw_nodes.update( + o for o in bwd_outputs if o is not None and o.op != "output" + ) + forward_only_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, inputs, fwd_outputs, fwd_outputs_descs, "forward" + ) + required_fw_nodes: OrderedSet[fx.Node] = OrderedSet( + name_to_node[node.name] + for node in forward_only_graph.nodes + if node.op != "output" and node.name in name_to_node + ) + unclaimed_nodes: OrderedSet[fx.Node] = OrderedSet( + node + for node in joint_module.graph.nodes + if node not in required_fw_nodes and node not in required_bw_nodes + ) + static_lifetime_input_nodes = OrderedSet( + p for i, p in enumerate(primal_inputs) if i in static_lifetime_input_indices + ) + fw_cnt = 0 + fw_order = {} + for node in joint_module.graph.nodes: + if node in required_fw_nodes: + fw_order[node] = fw_cnt + fw_cnt += 1 + return NodeInfo( + inputs, + required_fw_nodes, + required_bw_nodes, + tangents_closure, + unclaimed_nodes, + fw_order, + static_lifetime_input_nodes, + ) + + +def min_cut_rematerialization_partition( + joint_module: fx.GraphModule, + _joint_inputs: Any, + compiler: str = "inductor", + *, + num_fwd_outputs: int, + static_lifetime_input_indices: list[int] | None = None, +) -> tuple[fx.GraphModule, fx.GraphModule]: + """ + Partitions the joint graph such that the backward recomputes the forward. + Recomputing helps in trading off memory bandwidth with computation. + + To create the fwd and bwd graph, we copy the joint graph, manually set the + outputs to just original forward or backward outputs. And then we run the + resulting graphs through dead code elimination. + + .. warning:: + This API is experimental and likely to change. + + Args: + joint_module(fx.GraphModule): The joint forward and backward graph. This + is the result of AOT Autograd tracing. + _joint_inputs: The inputs to the joint graph. This is unused. + compiler: This option determines the default set of recomputable ops. + Currently, there are two options: ``nvfuser`` and ``inductor``. + recomputable_ops: This is an optional set of recomputable ops. If this + is not None, then this set of ops will be used instead of the + default set of ops. + num_fwd_outputs: The number of outputs from the forward graph. + + Returns: + Returns the generated forward and backward Fx graph modules. + """ + + joint_module.graph.eliminate_dead_code() + joint_module.recompile() + + fx_g = joint_module.graph + + # add the CSE pass + if config.cse: + # CSE runs before partitioning, so do not merge a forward-only value + # with a value that is also needed by the backward graph. Otherwise the + # partitioner may save the merged value as an extra forward output. + _, bwd_outputs, _, _ = _extract_fwd_bwd_outputs( + joint_module, num_fwd_outputs=num_fwd_outputs + ) + backward_dependencies: OrderedSet[fx.Node] = OrderedSet() + + backward_dependency_stack = [ + output + for output in bwd_outputs + if output is not None and output.op != "output" + ] + while backward_dependency_stack: + node = backward_dependency_stack.pop() + if node in backward_dependencies: + continue + backward_dependencies.add(node) + backward_dependency_stack.extend(node.all_input_nodes) + + def partition_key(node: fx.Node) -> bool: + return node in backward_dependencies + + cse_graph = fx_graph_cse(fx_g, extra_node_key=partition_key) + joint_module.graph = cse_graph + joint_graph = joint_module.graph + + graph_has_recomputable_ops = has_recomputable_ops(joint_module) + graph_has_recomputable_rng_ops = has_recomputable_rng_ops(joint_module) + if graph_has_recomputable_ops: + joint_module = cleanup_recompute_tags(joint_module, is_default_partition=False) + if not config.unsafe_allow_optimization_of_collectives: + force_save_collectives(joint_module) + + force_save_effectful_ops(joint_module) + force_save_bw_mutation_src(joint_module) + + if static_lifetime_input_indices is None: + static_lifetime_input_indices = [] + node_info = classify_nodes( + joint_module, static_lifetime_input_indices, num_fwd_outputs + ) + + # networkx blows up on graphs with no required backward nodes + # Since there's nothing to partition anyway, and the default partitioner can "handle" + # this case, send our graph over to the default partitioner. + if len(node_info.required_bw_nodes) == 0: + return default_partition( + joint_module, + _joint_inputs, + num_fwd_outputs=num_fwd_outputs, + static_lifetime_input_indices=static_lifetime_input_indices, + static_lifetime_input_nodes=node_info.static_lifetime_input_nodes, + ) + + for node in reversed(joint_module.graph.nodes): + if node.op == "output": + node.dist_from_bw = int(1e9) + elif not node_info.is_required_fw(node): + node.dist_from_bw = 0 + else: + node.dist_from_bw = int(1e9) + for user in node.users: + node.dist_from_bw = min(node.dist_from_bw, user.dist_from_bw + 1) + + # memory_budget override resolution, in increasing precedence: + # 1. config.activation_memory_budget (global default). + # 2. Legacy node.meta["memory_budget"], set by the old + # `MemoryBudgetMode` / `set_memory_budget` allow_in_graph marker. First + # matching node wins (preserves prior behavior); we may want to remove + # this path later. + # 3. `torch.autograd.graph.region_activation_memory_budget(...)`, read off + # node.meta["custom"] via `_get_memory_budget_annotation` and propagated + # onto every annotated node via _COPY_META_FIELDS["custom"]; overrides + # the legacy reader. + memory_budget = config.activation_memory_budget + for node in joint_graph.nodes: + if isinstance(node.meta.get("memory_budget", None), float): + memory_budget = node.meta["memory_budget"] + break + + # The partitioner applies a single budget per joint graph, so all annotated + # nodes must agree and the annotation must cover every forward op; otherwise + # the caller mixed budgets or annotated only part of a graph (across a graph + # break each graph is resolved independently). Collect both in one pass. + region_budgets: OrderedSet[float] = OrderedSet() + unannotated_fw_ops: list[fx.Node] = [] + for node in joint_graph.nodes: + budget = _get_memory_budget_annotation(node) + if budget is not None: + region_budgets.add(budget) + elif node.op == "call_function" and node_info.is_required_fw(node): + unannotated_fw_ops.append(node) + + # A budget must consistently cover the entire forward, including HOP bodies. + # Recurse into nested subgraph modules: collect their budgets (for the + # agreement check) and flag any unannotated call_function (for coverage). In + # a consistent graph every node in every body carries the budget, so an + # unannotated body op means the budget did not cover that HOP. + all_budgets: OrderedSet[float] = OrderedSet(region_budgets) + for _, sub in joint_module.named_modules(): + if isinstance(sub, fx.GraphModule) and sub.graph is not joint_graph: + for node in sub.graph.nodes: + b = _get_memory_budget_annotation(node) + if b is not None: + all_budgets.add(b) + elif node.op == "call_function": + unannotated_fw_ops.append(node) + if len(all_budgets) > 1: + raise RuntimeError( + f"torch.autograd.graph.region_activation_memory_budget: " + f"conflicting budgets within a single joint graph (including nested " + f"subgraphs): {sorted(all_budgets)}. Use a graph break to separate " + f"regions that need different budgets." + ) + + if all_budgets: + if unannotated_fw_ops: + raise RuntimeError( + f"torch.autograd.graph.region_activation_memory_budget: must " + f"cover the entire forward of a graph (including HOP bodies), but " + f"{len(unannotated_fw_ops)} forward op(s) are unannotated. Wrap " + f"the whole forward in a single region; use a graph break to scope " + f"different budgets to different graphs. Note that a graph break " + f"inside the annotated region can also cause unannotated ops here. " + f"Unannotated ops: {[n.name for n in unannotated_fw_ops]}." + ) + memory_budget = next(iter(all_budgets)) + saved_values = choose_saved_values_set( + joint_graph, + node_info, + memory_budget=memory_budget, + ) + # pyrefly: ignore [unbound-name] + if config._sync_decision_cross_ranks: + saved_values = _sync_decision_cross_ranks(joint_graph, saved_values) + + saved_sym_nodes = list( + filter( + lambda n: is_sym_node(n) and not _is_assert_only_symbool(n), saved_values + ) + ) + saved_opaque_nodes = list(filter(is_opaque_node, saved_values)) + saved_values = list( + filter(lambda n: not is_sym_node(n) and not is_opaque_node(n), saved_values) + ) + + # NB: saved_sym_nodes will be mutated to reflect the actual saved symbols + fw_module, bw_module = _extract_fwd_bwd_modules( + joint_module, + saved_values, + # pyrefly: ignore [bad-argument-type] + saved_sym_nodes=saved_sym_nodes, + saved_opaque_nodes=saved_opaque_nodes, + num_fwd_outputs=num_fwd_outputs, + static_lifetime_input_nodes=node_info.static_lifetime_input_nodes, + ) + if graph_has_recomputable_ops: + if graph_has_recomputable_rng_ops: + fw_module, bw_module = functionalize_rng_ops( + joint_module, fw_module, bw_module, len(saved_sym_nodes) + ) + bw_module = reordering_to_mimic_autograd_engine(bw_module) + + # pyrefly: ignore [unbound-name] + if config.enable_activation_offloading: + from ._activation_offloading.activation_offloading import ( + enable_activation_offloading, + ) + + enable_activation_offloading( + fw_module, + bw_module, + num_fwd_outputs, + node_info.static_lifetime_input_nodes, + ) + + # raise all getitem ops to as early as possible + # this is helpful for memory, especially in the case of aot_eager backend + fw_module = raise_getitems(fw_module) + bw_module = raise_getitems(bw_module) + + fw_module = thread_graphsafe_rng_from_hops(fw_module, is_backward=False) + bw_module = thread_graphsafe_rng_from_hops(bw_module, is_backward=True) + + if AOT_PARTITIONER_DEBUG: + # Calculate sorted sizes of saved values + sorted_sizes = sorted([(_size_of(i), str(i)) for i in saved_values]) + + # Log total theoretical activations stored + total_activations_size_gb = sum(_size_of(i) for i in saved_values) / 1e9 + log.info("Theoretical Activations Stored: %.2f GB", total_activations_size_gb) + + # Log theoretical per activation storage sizes + log.info("Theoretical Per Activation Storage Sizes: %s", sorted_sizes) + fw_module_nodes = OrderedSet( + node.name for node in fw_module.graph.nodes if node.op == "call_function" + ) + bw_module_nodes = OrderedSet( + node.name for node in bw_module.graph.nodes if node.op == "call_function" + ) + remat_nodes = fw_module_nodes & bw_module_nodes + + counts: dict[str, int] = defaultdict(int) + for node in fw_module.graph.nodes: + if node.name in remat_nodes and hasattr(node.target, "_overloadpacket"): + counts[str(node.target._overloadpacket)] += 1 + log.info( + "# remat/fw/bw: %d/%d/%d", + len(remat_nodes), + len(fw_module_nodes), + len(bw_module_nodes), + ) + rematerialized_ops = sorted( + counts.items(), key=operator.itemgetter(1), reverse=True + ) + log.info("Count of Ops Rematerialized: %s", rematerialized_ops) + return fw_module, bw_module + + +def draw_graph( + traced: torch.fx.GraphModule, + fname: str, + figname: str = "fx_graph", + clear_meta: bool = True, + prog: str | list[str] | None = None, + parse_stack_trace: bool = False, + dot_graph_shape: str | None = None, +) -> None: + if clear_meta: + new_graph = copy.deepcopy(traced.graph) + traced = fx.GraphModule(traced, new_graph) + for node in traced.graph.nodes: + node.meta = {} # pyrefly: ignore[implicit-any] + base, ext = os.path.splitext(fname) + if not ext: + ext = "." + config.torch_compile_graph_format + log.info("Writing FX graph to file: %s%s", base, ext) + g = graph_drawer.FxGraphDrawer( + traced, + figname, + parse_stack_trace=parse_stack_trace, + dot_graph_shape=dot_graph_shape, + ) + x = g.get_main_dot_graph() + fname = f"{base}{ext}" + graph_format = ext.lstrip(".") + if graph_format in {"dot", "raw"}: + # pydot's write_dot() invokes Graphviz with -Tdot. For large FX graphs + # that layout step can dominate compile debugging, so write raw DOT + # source directly for text graph dumps. + x.write(fname) + elif prog is None: + write_method = getattr(x, "write_" + graph_format) + write_method(fname) + else: + write_method = getattr(x, "write_" + graph_format) + write_method(fname, prog=prog) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/predispatch.py b/.venv/lib/python3.12/site-packages/torch/_functorch/predispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..c482ff18cefa595786d7c9c9f9a672bb7def8673 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/predispatch.py @@ -0,0 +1,297 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +""" +This module contains pre-dispatch wrappers for functorch operations +that enable proper tracing in PT2 non-strict export/compile fx graph. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from torch._C import ( + _enter_dual_level as _enter_dual_level_impl, + _exit_dual_level as _exit_dual_level_impl, +) +from torch._C._functorch import ( + _add_batch_dim as _add_batch_dim_impl, + _jvp_decrement_nesting as _jvp_decrement_nesting_impl, + _jvp_increment_nesting as _jvp_increment_nesting_impl, + _remove_batch_dim as _remove_batch_dim_impl, + _unwrap_for_grad as _unwrap_for_grad_impl, + _vmap_decrement_nesting as _vmap_decrement_nesting_impl, + _vmap_increment_nesting as _vmap_increment_nesting_impl, +) +from torch._VF import ( # type: ignore[attr-defined] + _make_dual as _make_dual_impl, + _unpack_dual as _unpack_dual_impl, +) + + +if TYPE_CHECKING: + import threading + + +def _add_batch_dim(self: torch.Tensor, batch_dim: int, level: int) -> torch.Tensor: + """ + Thin wrapper around torch._C._add_batch_dim that is used to proxy in + PT2 export/compile fx graph + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + batch_dim = self.ndim + batch_dim if batch_dim < 0 else batch_dim + + if mode: + return torch.overrides.handle_torch_function( + _add_batch_dim, (self,), self, batch_dim, level + ) + + res = _add_batch_dim_impl(self, batch_dim, level) + return res + + +def _remove_batch_dim( + self: torch.Tensor, level: int, batch_size: int, out_dim: int +) -> torch.Tensor: + """ + Thin wrapper around torch._C._remove_batch_dim that is used to proxy in + PT2 export/compile fx graph + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _remove_batch_dim, (self,), self, level, batch_size, out_dim + ) + + res = _remove_batch_dim_impl(self, level, batch_size, out_dim) + return res + + +def _vmap_increment_nesting(batch_size: int, randomness: str) -> int: + """ + Thin wrapper around torch._C._vmap_increment_nesting that is used + to proxy in export/compile graph + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _vmap_increment_nesting, (batch_size,), batch_size, randomness + ) + res = _vmap_increment_nesting_impl(batch_size, randomness) + return res + + +def _vmap_decrement_nesting() -> int: + """ + Thin wrapper around torch._C._vmap_increment_nesting that is used + to proxy in export/compile graph + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _vmap_decrement_nesting, + (), + ) + return _vmap_decrement_nesting_impl() + + +# Global variables for lazy_load_decompositions +DECOMPOSITIONS_LOADED: bool = False +DECOMPOSITIONS_LOCK: threading.Lock | None = None +VMAP_DECOMPOSITIONS_LIB: torch.library.Library | None = None + + +def lazy_load_decompositions() -> None: + """ + Lazy loading of vmap decompositions with pre-dispatch support. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function(lazy_load_decompositions, ()) + + global DECOMPOSITIONS_LOADED, DECOMPOSITIONS_LOCK, VMAP_DECOMPOSITIONS_LIB + + if DECOMPOSITIONS_LOADED: + return + + # Initialize lock if needed + if DECOMPOSITIONS_LOCK is None: + import threading + + DECOMPOSITIONS_LOCK = threading.Lock() + + with DECOMPOSITIONS_LOCK: + if DECOMPOSITIONS_LOADED: + return + + import os + + if not (os.environ.get("PYTORCH_JIT", "1") == "1" and __debug__): + DECOMPOSITIONS_LOADED = True + return + + # use an alternate way to register an operator into the decomposition table + # _register_jit_decomposition doesn't work for some operators, e.g. addr, + # because the Tensor types generated cannot be unioned by torchscript + # decomp should be type OpOverload + VMAP_DECOMPOSITIONS_LIB = torch.library.Library( + "aten", "IMPL", "FuncTorchBatched" + ) + + from torch._decomp import decomposition_table + + def _register_python_decomposition_vmap(decomp: torch._ops.OpOverload) -> None: + if VMAP_DECOMPOSITIONS_LIB is None: + raise AssertionError("VMAP_DECOMPOSITIONS_LIB must not be None") + if decomp in decomposition_table: + VMAP_DECOMPOSITIONS_LIB.impl(decomp, decomposition_table[decomp]) + else: + raise RuntimeError(f"could not find decomposition for {decomp}") + + _register_python_decomposition_vmap(torch.ops.aten.mse_loss_backward.default) + _register_python_decomposition_vmap( + torch.ops.aten.smooth_l1_loss_backward.default + ) + _register_python_decomposition_vmap(torch.ops.aten.huber_loss_backward.default) + _register_python_decomposition_vmap(torch.ops.aten.nll_loss_forward.default) + _register_python_decomposition_vmap(torch.ops.aten.nll_loss2d_forward.default) + _register_python_decomposition_vmap(torch.ops.aten.nll_loss_backward.default) + _register_python_decomposition_vmap(torch.ops.aten.nll_loss2d_backward.default) + _register_python_decomposition_vmap(torch.ops.aten.addr.default) + + DECOMPOSITIONS_LOADED = True + + +def _make_dual( + tensor: torch.Tensor, tangent: torch.Tensor, *, level: int = 0 +) -> torch.Tensor: + """ + Thin wrapper around torch._VF._make_dual that is used to proxy in + PT2 export/compile fx graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _make_dual, (tensor, tangent), tensor, tangent, level=level + ) + + return _make_dual_impl(tensor, tangent, level=level) + + +def _unpack_dual( + tensor: torch.Tensor, *, level: int = 0 +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Thin wrapper around torch._VF._unpack_dual that is used to proxy in + PT2 export/compile fx graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _unpack_dual, (tensor,), tensor, level=level + ) + + return _unpack_dual_impl(tensor, level=level) + + +def _jvp_increment_nesting() -> int: + """ + Thin wrapper around torch._C._functorch._jvp_increment_nesting that is + used to proxy in export/compile graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _jvp_increment_nesting, + (), + ) + return _jvp_increment_nesting_impl() + + +def _jvp_decrement_nesting() -> int: + """ + Thin wrapper around torch._C._functorch._jvp_decrement_nesting that is + used to proxy in export/compile graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _jvp_decrement_nesting, + (), + ) + return _jvp_decrement_nesting_impl() + + +def _unwrap_for_grad(tensor: torch.Tensor, level: int) -> torch.Tensor: + """ + Thin wrapper around torch._C._functorch._unwrap_for_grad that is used + to proxy in PT2 export/compile fx graph for functorch transforms (grad, vjp, jvp). + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _unwrap_for_grad, (tensor,), tensor, level + ) + + return _unwrap_for_grad_impl(tensor, level) + + +def _enter_dual_level() -> int: + """ + Thin wrapper around torch._C._enter_dual_level that is used to proxy in + PT2 export/compile fx graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function(_enter_dual_level, ()) + return _enter_dual_level_impl() + + +def _exit_dual_level(*, level: int) -> None: + """ + Thin wrapper around torch._C._exit_dual_level that is used to proxy in + PT2 export/compile fx graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function(_exit_dual_level, (), level=level) + return _exit_dual_level_impl(level=level) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/pyfunctorch.py b/.venv/lib/python3.12/site-packages/torch/_functorch/pyfunctorch.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b09a6adb06bd1a50ce44fafaa76afc83f21f9e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/pyfunctorch.py @@ -0,0 +1,338 @@ +from __future__ import annotations + +import contextlib +from abc import ABC, abstractmethod +from functools import cached_property +from typing import Any, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch._C._functorch import ( + CFunctionalizeInterpreterPtr, + CGradInterpreterPtr, + CInterpreter, + CJvpInterpreterPtr, + CVmapInterpreterPtr, + pop_dynamic_layer_stack, + push_dynamic_layer_stack, + RandomnessType, + TransformType, +) +from torch.autograd.forward_ad import _set_fwd_grad_enabled + + +if TYPE_CHECKING: + from collections.abc import Generator + + +""" +This file contains the functorch integration with PyDispatcher. + +PyDispatcher does not understand functorch's DynamicLayerStack dispatching +logic because it is entirely implemented in C++ in the fallbacks for two +dispatch keys, FuncTorchDynamicLayer{Front, Back}Mode (PyDispatcher is unable +to directly reuse C++ boxed fallbacks). + +Instead of trying to hammer PyDispatcher into understanding those fallbacks, +we re-implement the logic of peeking the top of the stack for an interpreter, +selecting the interpreter to dispatch on, etc, in Python. This leads to a +simpler design. + +The main difference between C++ functorch and PyDispatcher's functorch logic +is that: +- C++ functorch needs to manually tweak dispatch keys to ping-pong between + DynamicLayerFrontMode and DynamicLayerBackMode. +- PyDispatcher's functorch logic pops an Interpreter from the top of the stack + and asks it to execute the rule associated with the Interpreter. + +In C++ we do the ping-pong because e.g. vmap rules are associated with the +batched DispatchKey, but in PyDispatcher we are able to avoid this by asking +the user to register a batching rule directly to a transform that an +interpreter then invokes. +""" + + +# FuncTorchInterpreter is the Python version of Interpreter (recall that +# the DynamicLayerStack is a stack of interpreters). +# It is a wrapper around the actual C++ Interpreter object. +# +# Keep the methods in sync with aten/src/ATen/functorch/Interpreter.h +class FuncTorchInterpreter(ABC): + def __init__(self, cptr: Any) -> None: + self._cptr = cptr + + # Process an operation. eg for vmap, this is invoking a batching rule. + # Conceptually this is analogous to Interpreter::process in C++ + @abstractmethod + def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + pass + + # lower an operation from this Interpreter to the next Interpreter on the stack. + # Concretely, this involves temporarily popping the current Interpreter. + # Conceptually this is analogous to Interpreter::sendToNextInterpreter in C++ + def lower(self) -> contextlib.AbstractContextManager[Any]: + return temporarily_pop_interpreter_stack() + + def level(self) -> int: + return self._cptr.level() + + def key(self) -> TransformType: + return self._cptr.key() + + def get_state(self) -> tuple[Any, ...]: + raise NotImplementedError + + def check_state(self, state: tuple[Any, ...]) -> bool: + return state == self.get_state() + + def __getstate__(self) -> dict[str, Any]: + state = self.__dict__.copy() + state.pop("_cptr", None) + return state + + +@contextlib.contextmanager +def temporarily_pop_interpreter_stack() -> Generator[None, None, None]: + try: + saved = pop_dynamic_layer_stack() + yield + finally: + push_dynamic_layer_stack(saved) + + +@contextlib.contextmanager +def temporarily_clear_interpreter_stack() -> Generator[list[Any], None, None]: + stack: list[Any] = [] + try: + while torch._C._functorch.peek_interpreter_stack() is not None: + stack.append(pop_dynamic_layer_stack()) + yield list(stack) + finally: + while stack: + push_dynamic_layer_stack(stack.pop()) + + +@contextlib.contextmanager +def temporarily_restore_interpreter_stack( + stack: list[Any] | None, +) -> Generator[None, None, None]: + pushed: list[Any] = [] + if stack is None: + return + try: + for s in reversed(stack): + push_dynamic_layer_stack(s) + pushed.append(s) + yield + finally: + for _ in reversed(pushed): + # TODO: would be nice to assert that the layers are the same, but + # Python object identity is not preserved + pop_dynamic_layer_stack() + + +class VmapInterpreter(FuncTorchInterpreter): + def __init__(self, cdata: CInterpreter) -> None: + if cdata.key() != TransformType.Vmap: + raise AssertionError(f"expected TransformType.Vmap, got {cdata.key()}") + # NOTE: [Interpreter cdata vs cptr] + # cdata is a generic CInterpreter. We wrap it in a CVmapInterpreterPtr + # so that we can access methods specific to the vmap interpreter + self._cdata = cdata + + @cached_property + # pyrefly: ignore [bad-override] + def _cptr(self) -> CVmapInterpreterPtr: + return CVmapInterpreterPtr(self._cdata) + + def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + kernel = op.functorch_table[TransformType.Vmap] + return kernel(self, *args, **kwargs) + + def batch_size(self) -> int: + return self._cptr.batchSize() + + def randomness(self) -> str: + typ = self._cptr.randomness() + if typ == RandomnessType.Error: + return "error" + elif typ == RandomnessType.Same: + return "same" + elif typ == RandomnessType.Different: + return "different" + raise RuntimeError(f"Unknown RandomnessType: {typ}") + + def get_state(self) -> tuple[Any, ...]: + return (self.key().name, self.level(), self.randomness()) + + +@contextlib.contextmanager +def nested( + *contexts: contextlib.AbstractContextManager[Any], +) -> Generator[tuple[contextlib.AbstractContextManager[Any], ...], None, None]: + with contextlib.ExitStack() as stack: + for ctx in contexts: + stack.enter_context(ctx) + yield contexts + + +class GradInterpreter(FuncTorchInterpreter): + def __init__(self, cdata: CInterpreter) -> None: + if cdata.key() != TransformType.Grad: + raise AssertionError(f"expected TransformType.Grad, got {cdata.key()}") + # See NOTE: [Interpreter cdata vs cptr] + self._cdata = cdata + + @cached_property + # pyrefly: ignore [bad-override] + def _cptr(self) -> CGradInterpreterPtr: + return CGradInterpreterPtr(self._cdata) + + def lift( + self, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> tuple[tuple[Any, ...], dict[str, Any]]: + args, kwargs = pytree.tree_map_only( + torch.Tensor, self._cptr.lift, [args, kwargs] + ) + return args, kwargs + + def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + kernel = op.functorch_table[TransformType.Grad] + args, kwargs = self.lift(args, kwargs) + return kernel(self, *args, **kwargs) + + # GradInterpreter has custom lower because of the no_grad interaction + # See NOTE [grad and vjp interaction with no_grad] + # This logic is mirrored from C++ GradInterpreterPtr::sendToNextInterpreter + def lower(self) -> contextlib.AbstractContextManager[Any]: + prev_grad_mode = self.prev_grad_mode() + if not prev_grad_mode: + return nested(torch.no_grad(), super().lower()) + return super().lower() + + def prev_grad_mode(self) -> bool: + return self._cptr.prevGradMode() + + def get_state(self) -> tuple[Any, ...]: + return (self.key().name, self.level(), self.prev_grad_mode()) + + +class JvpInterpreter(FuncTorchInterpreter): + def __init__(self, cdata: CInterpreter) -> None: + if cdata.key() != TransformType.Jvp: + raise AssertionError(f"expected TransformType.Jvp, got {cdata.key()}") + # See NOTE: [Interpreter cdata vs cptr] + self._cdata = cdata + + @cached_property + # pyrefly: ignore [bad-override] + def _cptr(self) -> CJvpInterpreterPtr: + return CJvpInterpreterPtr(self._cdata) + + def lift( + self, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> tuple[tuple[Any, ...], dict[str, Any]]: + args, kwargs = pytree.tree_map_only( + torch.Tensor, self._cptr.lift, [args, kwargs] + ) + return args, kwargs + + def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + kernel = op.functorch_table[TransformType.Jvp] + args, kwargs = self.lift(args, kwargs) + return kernel(self, *args, **kwargs) + + # Jvp has custom lower because of the no_fwd_grad interaction + # See NOTE [grad and vjp interaction with no_grad] for related info. + # This logic is mirrored from C++ JvpInterpreterPtr::sendToNextInterpreter + def lower(self) -> contextlib.AbstractContextManager[Any]: + prev_fwd_grad_mode = self.prev_fwd_grad_mode() + if not prev_fwd_grad_mode: + return nested(_set_fwd_grad_enabled(False), super().lower()) + return super().lower() + + def prev_fwd_grad_mode(self) -> bool: + return self._cptr.prevFwdGradMode() + + def get_state(self) -> tuple[Any, ...]: + return (self.key().name, self.level(), self.prev_fwd_grad_mode()) + + +class FunctionalizeInterpreter(FuncTorchInterpreter): + def __init__(self, cdata: CInterpreter) -> None: + if cdata.key() != TransformType.Functionalize: + raise AssertionError( + f"expected TransformType.Functionalize, got {cdata.key()}" + ) + self._cdata = cdata + + @cached_property + # pyrefly: ignore [bad-override] + def _cptr(self) -> CFunctionalizeInterpreterPtr: + return CFunctionalizeInterpreterPtr(self._cdata) + + def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + kernel = op.functorch_table[TransformType.Functionalize] + return kernel(self, *args, **kwargs) + + def functionalize_add_back_views(self) -> bool: + return self._cptr.functionalizeAddBackViews() + + def get_state(self) -> tuple[Any, ...]: + return (self.key().name, self.level()) + + +def coerce_cinterpreter(cinterpreter: CInterpreter) -> FuncTorchInterpreter: + key = cinterpreter.key() + if key == TransformType.Grad: + return GradInterpreter(cinterpreter) + if key == TransformType.Vmap: + return VmapInterpreter(cinterpreter) + if key == TransformType.Jvp: + return JvpInterpreter(cinterpreter) + if key == TransformType.Functionalize: + return FunctionalizeInterpreter(cinterpreter) + raise RuntimeError(f"NYI: PyDispatcher has not implemented support for {key}") + + +def retrieve_current_functorch_interpreter() -> FuncTorchInterpreter: + interpreter = torch._C._functorch.peek_interpreter_stack() + if interpreter is None: + raise AssertionError("interpreter must not be None") + return coerce_cinterpreter(interpreter) + + +def retrieve_all_functorch_interpreters() -> list[FuncTorchInterpreter]: + cis = torch._C._functorch.get_interpreter_stack() + if cis is None: + return [] + return [coerce_cinterpreter(ci) for ci in cis] + + +def compare_functorch_state(states: list[tuple[Any, ...]]) -> bool: + # There are four possible cases covered here: + # 1. Current stack empty AND stack when generated not empty -> Invalidate + # 2. Current stack not empty AND stack when generated empty -> Invalidate + # 3. Current stack and generated stack empty -> Valid FX graph + # 4. Current stack and generated stack not empty -> Valid if both states match + peek = torch._C._functorch.peek_interpreter_stack() + if (peek is None and len(states) != 0) or (peek is not None and len(states) == 0): + return False + + cis = retrieve_all_functorch_interpreters() + return len(cis) == len(states) and all( + ci.check_state(state) for ci, state in zip(cis, states) + ) + + +def dispatch_functorch(op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + interpreter = retrieve_current_functorch_interpreter() + # In traditional PyTorch operators, DispatchKey::FuncTorchTensorWrapper's + # unwrap_dead_tensors fallback handles unwrapping dead tensor wrappers. + # PyDispatcher sidesteps the PyTorch dispatcher when dealing with functorch + # transforms, so we manually unwrap the dead tensors here. + # This logic won't need to exist when we have mode-only functorch. + args, kwargs = pytree.tree_map_only( + torch.Tensor, torch._C._functorch.unwrap_if_dead, (args, kwargs) + ) + return interpreter.process(op, args, kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/python_key.py b/.venv/lib/python3.12/site-packages/torch/_functorch/python_key.py new file mode 100644 index 0000000000000000000000000000000000000000..557334f68928a057a6a9e036c904c8c0bd3231c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/python_key.py @@ -0,0 +1,15 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. +__all__ = ["make_fx", "dispatch_trace", "PythonKeyTracer", "pythonkey_decompose"] +from torch.fx.experimental.proxy_tensor import ( + decompose, + dispatch_trace, + make_fx, + PythonKeyTracer, +) + + +pythonkey_decompose = decompose diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/pytree_hacks.py b/.venv/lib/python3.12/site-packages/torch/_functorch/pytree_hacks.py new file mode 100644 index 0000000000000000000000000000000000000000..96dea7ad100705ae53139aa5ae729fd2206182af --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/pytree_hacks.py @@ -0,0 +1,23 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import warnings + +# TODO: remove this file when the migration of the pytree utility is done +from torch.utils._pytree import tree_map_, treespec_pprint + + +__all__ = ["tree_map_", "treespec_pprint"] + + +with warnings.catch_warnings(): + warnings.simplefilter("always") + warnings.warn( + "`torch._functorch.pytree_hacks` is deprecated and will be removed in a future release. " + "Please `use torch.utils._pytree` instead.", + DeprecationWarning, + stacklevel=2, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/top_operators_github_usage.py b/.venv/lib/python3.12/site-packages/torch/_functorch/top_operators_github_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..2e11b6b9cdcbe4aab352a5f206f3b957e8026df3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/top_operators_github_usage.py @@ -0,0 +1,630 @@ +from __future__ import annotations + + +""" +From https://docs.google.com/spreadsheets/d/12R3nCOLskxPYjjiNkdqy4OdQ65eQp_htebXGODsjSeA/edit#gid=0 +Try to keep this list in sync with that. +""" + +import operator + + +top_torch: list[tuple[str, int]] = [ + ("t", 6837449), + ("tensor", 585786), + ("mode", 462182), + ("cat", 394818), + ("max", 368038), + ("zeros", 329495), + ("load", 327756), + ("no_grad", 294694), + ("save", 265130), + ("from_numpy", 243063), + ("manual_seed", 165044), + ("ones", 153696), + ("randn", 150796), + ("stack", 133358), + ("sum", 130772), + ("arange", 98087), + ("rand", 94715), + ("mean", 88546), + ("exp", 73883), + ("zeros_like", 72831), + ("min", 72248), + ("sigmoid", 66798), + ("log", 62135), + ("matmul", 47811), + ("clamp", 45304), + ("sqrt", 44911), + ("abs", 43535), + ("tanh", 42793), + ("empty", 40311), + ("argmax", 38435), + ("bmm", 33984), + ("pow", 33571), + ("norm", 31125), + ("mm", 30995), + ("is_tensor", 29546), + ("ones_like", 29512), + ("nonzero", 28681), + ("full", 28373), + ("unsqueeze", 27911), + ("where", 26585), + ("randperm", 26450), + ("eye", 24342), + ("mul", 23236), + ("topk", 22537), + ("as_tensor", 21967), + ("sort", 21412), + ("squeeze", 20863), + ("randint", 20771), + ("linspace", 20041), + ("add", 19201), + ("transpose", 18663), + ("split", 18325), + ("gather", 17904), + ("set_grad_enabled", 16013), + ("sin", 15669), + ("cos", 15562), + ("div", 15513), + ("index_select", 14866), + ("multinomial", 14331), + ("flatten", 14267), + ("isnan", 14170), + ("randn_like", 13096), + ("eq", 12680), + ("einsum", 12480), + ("round", 12367), + ("floor", 11628), + ("allclose", 11000), + ("reshape", 10605), + ("diag", 10167), + ("chunk", 9581), + ("std", 9379), + ("set_default_tensor_type", 9281), + ("triu", 8559), + ("meshgrid", 8292), + ("set_num_threads", 8126), + ("unique", 7964), + ("full_like", 7780), + ("tril", 7538), + ("dot", 7275), + ("sign", 6943), + ("equal", 6916), + ("normal", 6750), + ("cumsum", 6556), + ("dist", 6058), + ("isfinite", 6030), + ("gt", 5935), + ("set_printoptions", 5888), + ("range", 5491), + ("empty_like", 5351), + ("flip", 5342), + ("masked_select", 5341), + ("bernoulli", 5262), + ("atan", 5253), + ("var", 5247), + ("prod", 5200), + ("erf", 5088), + ("inverse", 5072), + ("addmm", 4854), + ("logsumexp", 4582), + ("fft", 4436), + ("lt", 4421), + ("log2", 4316), + ("enable_grad", 4238), + ("rand_like", 4187), + ("argsort", 3972), + ("seed", 3932), + ("mv", 3547), + ("ger", 3309), + ("ge", 3248), + ("atan2", 3210), + ("ceil", 3202), + ("ne", 3075), + ("bincount", 3063), + ("acos", 3055), + ("rsqrt", 3031), + ("svd", 3029), + ("numel", 3003), + ("log1p", 2840), + ("unbind", 2808), + ("le", 2714), + ("isinf", 2707), + ("cross", 2646), + ("set_default_dtype", 2536), + ("argmin", 2535), + ("sparse_coo_tensor", 2489), + ("log10", 2304), + ("kthvalue", 2192), + ("set_rng_state", 2158), + ("get_rng_state", 1996), + ("get_default_dtype", 1879), + ("det", 1868), + ("qr", 1864), + ("histc", 1852), + ("symeig", 1832), + ("trace", 1801), + ("median", 1795), + ("addcmul", 1751), + ("remainder", 1717), + ("baddbmm", 1693), + ("lgamma", 1665), + ("repeat_interleave", 1598), + ("fmod", 1576), + ("reciprocal", 1575), + ("tan", 1560), + ("initial_seed", 1532), + ("take", 1529), + ("stft", 1487), + ("get_num_threads", 1477), + ("real", 1459), + ("quantize_per_tensor", 1392), + ("diag_embed", 1364), + ("lerp", 1363), + ("asin", 1345), + ("eig", 1333), + ("trunc", 1290), + ("diagonal", 1287), + ("cosh", 1279), + ("rfft", 1269), + ("cumprod", 1260), + ("addr", 1211), + ("roll", 1198), + ("narrow", 1188), + ("digamma", 1172), + ("square", 1163), + ("sinh", 1131), + ("logspace", 1084), + ("broadcast_tensors", 1070), + ("irfft", 1013), + ("frac", 997), + ("hann_window", 994), + ("solve", 989), + ("logdet", 977), + ("expm1", 968), + ("cdist", 946), + ("addmv", 903), + ("randint_like", 888), + ("tensordot", 888), + ("ifft", 877), + ("true_divide", 854), + ("erfinv", 830), + ("addcdiv", 819), + ("addbmm", 813), + ("renorm", 781), + ("pinverse", 753), + ("isclose", 740), + ("erfc", 729), + ("is_storage", 725), + ("triangular_solve", 723), + ("rot90", 709), + ("logical_not", 686), + ("geqrf", 681), + ("slogdet", 677), + ("lu", 665), + ("hamming_window", 659), + ("orgqr", 651), + ("ormqr", 622), + ("is_floating_point", 602), + ("diagflat", 562), + ("cholesky_solve", 559), + ("tril_indices", 552), + ("chain_matmul", 551), + ("triu_indices", 548), + ("angle", 522), + ("poisson", 505), + ("matrix_power", 485), + ("unique_consecutive", 471), + ("quantize_per_channel", 465), + ("std_mean", 458), + ("bartlett_window", 447), + ("var_mean", 428), + ("lstsq", 421), + ("logical_and", 419), + ("mvlgamma", 411), + ("blackman_window", 400), + ("bitwise_not", 395), + ("cholesky_inverse", 388), + ("as_strided", 384), + ("floor_divide", 353), + ("cartesian_prod", 321), + ("lu_solve", 317), + ("set_flush_denormal", 310), + ("empty_strided", 283), + ("logical_xor", 282), + ("polygamma", 282), + ("logical_or", 280), + ("set_num_interop_threads", 278), + ("combinations", 274), + ("trapz", 270), + ("matrix_rank", 260), + ("lu_unpack", 255), + ("result_type", 244), + ("conj", 231), + ("cummax", 230), + ("lobpcg", 229), + ("bitwise_xor", 217), + ("promote_types", 213), + ("get_num_interop_threads", 211), + ("cummin", 205), + ("bitwise_and", 198), + ("dequantize", 192), + ("bitwise_or", 191), + ("imag", 191), + ("can_cast", 184), + ("istft", 180), + ("compiled_with_cxx11_abi", 159), + ("is_complex", 151), + ("block_diag", 136), + ("pca_lowrank", 124), + ("absolute", 122), + ("svd_lowrank", 108), + ("neg", 2), +] + +top_nn_functional: list[tuple[str, int]] = [ + ("nn.functional.softmax", 10522), + ("nn.functional.relu", 8572), + ("nn.functional.interpolate", 7277), + ("nn.functional.pad", 5207), + ("nn.functional.log_softmax", 4699), + ("nn.functional.normalize", 2338), + ("nn.functional.cross_entropy", 2083), + ("nn.functional.grid_sample", 1970), + ("nn.functional.one_hot", 1967), + ("nn.functional.mse_loss", 1920), + ("nn.functional.conv2d", 1593), + ("nn.functional.dropout", 1516), + ("nn.functional.softplus", 1385), + ("nn.functional.sigmoid", 1128), + ("nn.functional.linear", 1036), + ("nn.functional.gelu", 930), + ("nn.functional.avg_pool2d", 899), + ("nn.functional.max_pool2d", 876), + ("nn.functional.nll_loss", 863), + ("nn.functional.embedding", 737), + ("nn.functional.tanh", 664), + ("nn.functional.leaky_relu", 640), + ("nn.functional.adaptive_avg_pool2d", 633), + ("nn.functional.cosine_similarity", 627), + ("nn.functional.unfold", 609), + ("nn.functional.conv1d", 596), + ("nn.functional.binary_cross_entropy_with_logits", 591), + ("nn.functional.l1_loss", 571), + ("nn.functional.binary_cross_entropy", 492), + ("nn.functional.elu", 416), + ("nn.functional.batch_norm", 413), + ("nn.functional.upsample", 413), + ("nn.functional.fold", 305), + ("nn.functional.affine_grid", 298), + ("nn.functional.max_pool1d", 297), + ("nn.functional.torch", 294), + ("nn.functional.threshold", 263), + ("nn.functional.smooth_l1_loss", 262), + ("nn.functional.pairwise_distance", 253), + ("nn.functional.logsigmoid", 243), + ("nn.functional.adaptive_max_pool2d", 235), + ("nn.functional.relu6", 213), + ("nn.functional.pixel_shuffle", 209), + ("nn.functional.avg_pool3d", 203), + ("nn.functional.bilinear", 203), + ("nn.functional.conv_transpose2d", 201), + ("nn.functional.gumbel_softmax", 197), + ("nn.functional.max_unpool2d", 196), + ("nn.functional.kl_div", 191), + ("nn.functional.hardtanh", 189), + ("nn.functional.ctc_loss", 185), + ("nn.functional.layer_norm", 178), + ("nn.functional.conv3d", 172), + ("nn.functional.max_unpool3d", 167), + ("nn.functional.hardshrink", 165), + ("nn.functional.hardswish", 156), + ("nn.functional.selu", 156), + ("nn.functional.glu", 155), + ("nn.functional.assert_int_or_pair", 150), + ("nn.functional.hardsigmoid", 146), + ("nn.functional.upsample_bilinear", 146), + ("nn.functional.max_pool3d", 140), + ("nn.functional.adaptive_avg_pool3d", 139), + ("nn.functional.instance_norm", 124), + ("nn.functional.embedding_bag", 122), + ("nn.functional.upsample_nearest", 110), + ("nn.functional.avg_pool1d", 105), + ("nn.functional.prelu", 102), + ("nn.functional.celu", 92), + ("nn.functional.dropout2d", 86), + ("nn.functional.hinge_embedding_loss", 82), + ("nn.functional.softsign", 81), + ("nn.functional.max_unpool1d", 74), + ("nn.functional.silu", 74), + ("nn.functional.softshrink", 70), + ("nn.functional.leaky_relu_", 68), + ("nn.functional.softmin", 67), + ("nn.functional.channel_shuffle", 66), + ("nn.functional.multilabel_margin_loss", 66), + ("nn.functional.dropout3d", 65), + ("nn.functional.multi_margin_loss", 65), + ("nn.functional.lp_pool2d", 64), + ("nn.functional.conv_transpose1d", 62), + ("nn.functional.triplet_margin_loss", 62), + ("nn.functional.tanhshrink", 61), + ("nn.functional.adaptive_max_pool1d", 59), + ("nn.functional.cosine_embedding_loss", 58), + ("nn.functional.multi_head_attention_forward", 58), + ("nn.functional.max_pool1d_with_indices", 53), + ("nn.functional.poisson_nll_loss", 53), + ("nn.functional.margin_ranking_loss", 52), + ("nn.functional.soft_margin_loss", 52), + ("nn.functional.adaptive_max_pool3d", 51), + ("nn.functional.group_norm", 51), + ("nn.functional.local_response_norm", 51), + ("nn.functional.multilabel_soft_margin_loss", 51), + ("nn.functional.relu_", 50), + ("nn.functional.alpha_dropout", 49), + ("nn.functional.feature_alpha_dropout", 49), + ("nn.functional.lp_pool1d", 49), + ("nn.functional.adaptive_max_pool1d_with_indices", 48), + ("nn.functional.adaptive_max_pool2d_with_indices", 48), + ("nn.functional.adaptive_max_pool3d_with_indices", 48), + ("nn.functional.fractional_max_pool2d", 48), + ("nn.functional.fractional_max_pool2d_with_indices", 48), + ("nn.functional.fractional_max_pool3d", 48), + ("nn.functional.fractional_max_pool3d_with_indices", 48), + ("nn.functional.max_pool2d_with_indices", 48), + ("nn.functional.max_pool3d_with_indices", 48), + ("nn.functional.handle_torch_function", 47), + ("nn.functional.has_torch_function", 47), + ("nn.functional.adaptive_avg_pool1d", 43), + ("nn.functional.pdist", 43), + ("nn.functional.rrelu_", 37), + ("nn.functional.elu_", 34), + ("nn.functional.boolean_dispatch", 33), + ("nn.functional.hardtanh_", 26), + ("nn.functional.triplet_margin_with_distance_loss", 23), + ("nn.functional.selu_", 20), + ("nn.functional.pixel_unshuffle", 19), + ("nn.functional.conv_transpose3d", 18), + ("nn.functional.gaussian_nll_loss", 15), + ("nn.functional.has_torch_function_unary", 15), + ("nn.functional.has_torch_function_variadic", 15), + ("nn.functional.celu_", 13), + ("nn.functional.huber_loss", 7), + ("nn.functional.mish", 4), + ("nn.functional.threshold_", 3), + ("nn.functional.grad", 2), + ("nn.functional.conv_tbc", 1), + ("nn.functional.math", 1), +] + +top_nn_module: list[tuple[str, int, str | None]] = [ + ("nn.Module", 927129, None), + ("nn.Linear", 530688, "nn.functional.linear"), + ("nn.Sequential", 384968, None), + ("nn.Conv2d", 383320, "nn.functional.conv2d"), + ("nn.ReLU", 318877, "nn.functional.relu"), + ("nn.BatchNorm2d", 233265, "nn.functional.batch_norm"), + ("nn.Dropout", 179268, "nn.functional.dropout"), + ("nn.ModuleList", 171225, None), + ("nn.Parameter", 153291, None), + ("nn.CrossEntropyLoss", 152696, "nn.functional.cross_entropy"), + ("nn.MaxPool2d", 138619, "nn.functional.max_pool2d"), + ("nn.Embedding", 111844, "nn.functional.embedding"), + ("nn.DataParallel", 104238, None), + ("nn.MSELoss", 82954, "nn.functional.mse_loss"), + ("nn.Sigmoid", 75810, "nn.functional.sigmoid"), + ("nn.LeakyReLU", 65632, "nn.functional.leaky_relu"), + ("nn.BatchNorm1d", 65374, "nn.functional.batch_norm"), + ("nn.Softmax", 65114, "nn.functional.softmax"), + ("nn.Tanh", 59445, "nn.functional.tanh"), + ("nn.AdaptiveAvgPool2d", 59071, "nn.functional.adaptive_avg_pool2d"), + ("nn.AvgPool2d", 58377, "nn.functional.avg_pool2d"), + ("nn.ConvTranspose2d", 57524, "nn.functional.conv_transpose2d"), + ("nn.LSTM", 57411, None), + ("nn.Conv1d", 41108, "nn.functional.conv1d"), + ("nn.LayerNorm", 36089, "nn.functional.layer_norm"), + ("nn.BCELoss", 34005, "nn.functional.binary_cross_entropy"), + ("nn.Upsample", 32527, "nn.functional.interpolate"), + ("nn.BCEWithLogitsLoss", 29944, "nn.functional.binary_cross_entropy_with_logits"), + ("nn.GRU", 25421, None), + ("nn.Dropout2d", 23512, "nn.functional.dropout2d"), + ("nn.LogSoftmax", 22897, "nn.functional.log_softmax"), + ("nn.L1Loss", 22778, "nn.functional.l1_loss"), + ("nn.GroupNorm", 22183, "nn.functional.group_norm"), + ("nn.NLLLoss", 21751, "nn.functional.nll_loss"), + ("nn.Conv3d", 20874, "nn.functional.conv3d"), + ("nn.Identity", 17911, None), + ("nn.InstanceNorm2d", 16426, "nn.functional.instance_norm"), + ("nn.BatchNorm3d", 16378, "nn.functional.batch_norm"), + ("nn.PReLU", 13472, "nn.functional.prelu"), + ("nn.ReLU6", 12622, "nn.functional.relu6"), + ("nn.ELU", 12508, "nn.functional.elu"), + ("nn.LSTMCell", 10885, None), + ("nn.Flatten", 10384, "torch.flatten"), + ("nn.ModuleDict", 10255, None), + ("nn.ReflectionPad2d", 9954, "nn.functional.pad"), + ("nn.MaxPool3d", 9526, "nn.functional.max_pool3d"), + ("nn.MaxPool1d", 9154, "nn.functional.max_pool1d"), + ("nn.RNN", 9154, None), + ("nn.ZeroPad2d", 8847, "nn.functional.pad"), + ("nn.ParameterList", 7702, None), + ("nn.SyncBatchNorm", 6814, None), + ("nn.PixelShuffle", 6571, "nn.functional.pixel_shuffle"), + ("nn.SmoothL1Loss", 6517, "nn.functional.smooth_l1_loss"), + ("nn.Hardswish", 6458, "nn.functional.hardswish"), + ("nn.AdaptiveMaxPool2d", 6071, "nn.functional.adaptive_max_pool2d"), + ("nn.SELU", 6043, "nn.functional.selu"), + ("nn.ConvTranspose3d", 6039, "nn.functional.conv_transpose3d"), + ("nn.GRUCell", 5840, None), + ("nn.ReplicationPad2d", 5600, "nn.functional.pad"), + ("nn.KLDivLoss", 5541, "nn.functional.kl_div"), + ("nn.ConvTranspose1d", 5183, "nn.functional.conv_transpose1d"), + ("nn.Softplus", 5120, "nn.functional.softplus"), + ("nn.SiLU", 4895, "nn.functional.silu"), + ("nn.AvgPool3d", 4523, "nn.functional.avg_pool3d"), + ("nn.CosineSimilarity", 4058, "nn.functional.cosine_similarity"), + ("nn.GELU", 3932, "nn.functional.gelu"), + ("nn.UpsamplingBilinear2d", 3673, "nn.functional.interpolate"), + ("nn.InstanceNorm1d", 3658, "nn.functional.instance_norm"), + ("nn.Transformer", 3604, None), + ("nn.MultiheadAttention", 3435, "nn.functional.multi_head_attention_forward"), + ("nn.AvgPool1d", 3195, "nn.functional.avg_pool1d"), + ("nn.Dropout3d", 2964, "nn.functional.dropout3d"), + ("nn.AdaptiveAvgPool3d", 2915, "nn.functional.adaptive_avg_pool3d"), + ("nn.InstanceNorm3d", 2893, "nn.functional.instance_norm"), + ("nn.Hardtanh", 2613, "nn.functional.hardtanh"), + ("nn.MarginRankingLoss", 2568, "nn.functional.margin_ranking_loss"), + ("nn.GLU", 2526, "nn.functional.glu"), + ("nn.AdaptiveAvgPool1d", 2481, "nn.functional.adaptive_avg_pool1d"), + ("nn.EmbeddingBag", 2344, "nn.functional.embedding_bag"), + ("nn.TransformerEncoderLayer", 2292, None), + ("nn.TransformerEncoder", 2091, None), + ("nn.MaxUnpool2d", 2031, "nn.functional.max_unpool2d"), + ("nn.UpsamplingNearest2d", 2004, "nn.functional.interpolate"), + ("nn.ConstantPad1d", 1904, "nn.functional.pad"), + ("nn.ConstantPad2d", 1791, "nn.functional.pad"), + ("nn.CTCLoss", 1789, "nn.functional.ctc_loss"), + ("nn.AdaptiveMaxPool1d", 1713, "nn.functional.adaptive_max_pool1d"), + ("nn.AdaptiveLogSoftmaxWithLoss", 1665, None), + ("nn.Bilinear", 1664, "nn.functional.bilinear"), + ("nn.RNNCell", 1653, None), + ("nn.MultiLabelSoftMarginLoss", 1624, "nn.functional.multilabel_soft_margin_loss"), + ("nn.Unfold", 1452, "nn.functional.unfold"), + ("nn.RReLU", 1431, "nn.functional.rrelu"), + ("nn.CosineEmbeddingLoss", 1357, "nn.functional.cosine_embedding_loss"), + ("nn.LocalResponseNorm", 1331, "nn.functional.local_response_norm"), + ("nn.Softmax2d", 1300, "nn.functional.softmax"), + ("nn.PairwiseDistance", 1241, "nn.functional.pairwise_distance"), + ("nn.LogSigmoid", 1235, "nn.functional.logsigmoid"), + ("nn.TripletMarginLoss", 1230, "nn.functional.triplet_margin_loss"), + ("nn.RNNBase", 1133, None), + ("nn.Threshold", 1043, "nn.functional.threshold"), + ("nn.AdaptiveMaxPool3d", 1025, "nn.functional.adaptive_max_pool3d"), + ("nn.CELU", 1018, "nn.functional.celu"), + ("nn.NLLLoss2d", 966, "nn.functional.nll_loss"), + ("nn.Softsign", 877, "nn.functional.softsign"), + ("nn.ReplicationPad1d", 862, "nn.functional.pad"), + ("nn.SoftMarginLoss", 856, "nn.functional.soft_margin_loss"), + ("nn.ParameterDict", 742, None), + ("nn.ReflectionPad1d", 731, "nn.functional.pad"), + ("nn.Softshrink", 713, "nn.functional.softshrink"), + ("nn.AlphaDropout", 710, "nn.functional.alpha_dropout"), + ("nn.Tanhshrink", 681, "nn.functional.tanhshrink"), + ("nn.PoissonNLLLoss", 676, "nn.functional.poisson_nll_loss"), + ("nn.MaxUnpool3d", 660, "nn.functional.max_unpool3d"), + ("nn.Fold", 630, "nn.functional.fold"), + ("nn.MultiMarginLoss", 622, "nn.functional.multi_margin_loss"), + ("nn.TransformerDecoderLayer", 614, None), + ("nn.TransformerDecoder", 607, None), + ("nn.Hardshrink", 592, "nn.functional.hardshrink"), + ("nn.ConstantPad3d", 582, "nn.functional.pad"), + ("nn.MultiLabelMarginLoss", 580, "nn.functional.multilabel_margin_loss"), + ("nn.LPPool2d", 550, "nn.functional.lp_pool2d"), + ("nn.Softmin", 537, "nn.functional.softmin"), + ("nn.MaxUnpool1d", 518, "nn.functional.max_unpool1d"), + ("nn.FractionalMaxPool2d", 484, "nn.functional.fractional_max_pool2d"), + ("nn.Hardsigmoid", 477, "nn.functional.hardsigmoid"), + ("nn.ReplicationPad3d", 470, "nn.functional.pad"), + ("nn.HingeEmbeddingLoss", 442, "nn.functional.hinge_embedding_loss"), + ("nn.LPPool1d", 386, "nn.functional.lp_pool1d"), + ("nn.FractionalMaxPool3d", 252, "nn.functional.fractional_max_pool3d"), + ("nn.Container", 217, None), + ("nn.Unflatten", 206, "nn.functional.unflatten"), + ("nn.FeatureAlphaDropout", 136, "nn.functional.feature_alpha_dropout"), + ( + "nn.TripletMarginWithDistanceLoss", + 107, + "nn.functional.triplet_margin_with_distance_loss", + ), + ("nn.ChannelShuffle", 90, "nn.functional.channel_shuffle"), + ("nn.RNNCellBase", 88, None), + ("nn.LazyLinear", 81, "nn.functional.linear"), + ("nn.UninitializedParameter", 60, None), + ("nn.CrossMapLRN2d", 59, None), + ("nn.GaussianNLLLoss", 55, "nn.functional.gaussian_nll_loss"), + ("nn.PixelUnshuffle", 45, "nn.functional.pixel_unshuffle"), + ("nn.Mish", 31, "nn.functional.mish"), + ("nn.ReflectionPad3d", 22, "nn.functional.pad"), + ("nn.HuberLoss", 18, "nn.functional.huber_loss"), + ("nn.LazyConv2d", 15, None), + ("nn.LazyConv1d", 9, None), + ("nn.LazyConv3d", 8, None), + ("nn.LazyConvTranspose1d", 8, None), + ("nn.LazyConvTranspose2d", 8, None), + ("nn.LazyConvTranspose3d", 8, None), + ("nn.LazyBatchNorm1d", 3, None), + ("nn.LazyBatchNorm2d", 3, None), + ("nn.LazyBatchNorm3d", 3, None), + ("nn.UninitializedBuffer", 3, None), +] + +# No rankings because these are a little hard to get rankings for +method_only_ops: list[str] = [ + "bfloat16", + "bool", + "byte", + "char", + "contiguous", + "cpu", + "cuda", + "detach", + "double", + "expand", + "expand_as", + "float", + "get_device", + "half", + "hardshrink", + "index_add", + "index_copy", + "index_fill", + "index_put", + "int", + "is_contiguous", + "is_pinned", + "is_set_to", + "is_shared", + "is_signed", + "item", + "long", + "masked_scatter", + "masked_fill", + "narrow_copy", + "numpy", + "pin_memory", + "repeat", + "reshape_as", + "select", + "short", + "storage_offset", + "sum_to_size", + "to", + "to_mkldnn", + "tolist", + "type", + "type_as", + "unfold", + "view", + "view_as", +] + + +def get_nn_functional_top_list() -> list[tuple[str, int]]: + top_nn_functional_: dict[str, int] = dict(top_nn_functional) + for _, count, functional_name in top_nn_module: + if functional_name is None: + continue + if functional_name == "torch.flatten": + continue + if functional_name not in top_nn_functional_: + top_nn_functional_[functional_name] = count + else: + top_nn_functional_[functional_name] += count + + top_nn_functional_list = list(top_nn_functional_.items()) + top_nn_functional_list.sort(key=operator.itemgetter(1), reverse=True) + return top_nn_functional_list + + +usage_count: dict[str, int] = dict(get_nn_functional_top_list()) +usage_count.update(top_torch) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..048271343465f7b450f12bb9c374c5c67d3b54eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/utils.py @@ -0,0 +1,30 @@ +import contextlib +from collections.abc import Generator + +from torch._C._functorch import ( + get_single_level_autograd_function_allowed, + set_single_level_autograd_function_allowed, + unwrap_dead_wrappers, +) +from torch.utils._exposed_in import exposed_in + + +__all__ = [ + "exposed_in", + "argnums_t", + "enable_single_level_autograd_function", + "unwrap_dead_wrappers", +] + + +@contextlib.contextmanager +def enable_single_level_autograd_function() -> Generator[None, None, None]: + try: + prev_state = get_single_level_autograd_function_allowed() + set_single_level_autograd_function_allowed(True) + yield + finally: + set_single_level_autograd_function_allowed(prev_state) + + +argnums_t = int | tuple[int, ...] diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/vmap.py b/.venv/lib/python3.12/site-packages/torch/_functorch/vmap.py new file mode 100644 index 0000000000000000000000000000000000000000..bc758f172e534b6159b89d79c2f225e3c7a80a89 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/vmap.py @@ -0,0 +1,567 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +import contextlib +import functools +import itertools +from collections.abc import Callable # noqa: TC003 +from functools import partial +from typing import Any, cast, NoReturn, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +import torch +from torch import Tensor +from torch._C._functorch import is_batchedtensor +from torch._functorch.predispatch import ( + _add_batch_dim, + _remove_batch_dim, + _vmap_decrement_nesting, + _vmap_increment_nesting, + lazy_load_decompositions, +) +from torch.utils._pytree import ( + _broadcast_to_and_flatten, + tree_flatten, + tree_map_, + tree_unflatten, + TreeSpec, +) + + +if TYPE_CHECKING: + from collections.abc import Generator, Iterable + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +in_dims_t = int | tuple[Any, ...] +out_dims_t = int | tuple[int, ...] | None + + +def doesnt_support_saved_tensors_hooks(f: Callable[_P, _R]) -> Callable[_P, _R]: + message = ( + "torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. " + "Please open an issue with your use case." + ) + + @functools.wraps(f) + def fn(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with torch.autograd.graph.disable_saved_tensors_hooks(message): + return f(*args, **kwargs) + + return fn + + +# Checks that all args-to-be-batched have the same batch dim size +def _validate_and_get_batch_size( + flat_in_dims: list[int | None], flat_args: list[Any] +) -> int: + batch_sizes = [ + arg.size(in_dim) + for in_dim, arg in zip(flat_in_dims, flat_args) + if in_dim is not None + ] + if len(batch_sizes) == 0: + raise ValueError("vmap: Expected at least one Tensor to vmap over") + if batch_sizes and any(size != batch_sizes[0] for size in batch_sizes): + raise ValueError( + f"vmap: Expected all tensors to have the same size in the mapped " + f"dimension, got sizes {batch_sizes} for the mapped dimension" + ) + return batch_sizes[0] + + +def _num_outputs(batched_outputs: Tensor | tuple[Tensor, ...]) -> int: + if isinstance(batched_outputs, tuple): + return len(batched_outputs) + return 1 + + +# If value is a tuple, check it has length `num_elements`. +# If value is not a tuple, make a tuple with `value` repeated `num_elements` times + + +def _as_tuple( + value: tuple[_R, ...] | _R, + num_elements: int, + error_message_lambda: Callable[[], str], +) -> tuple[_R, ...]: + if not isinstance(value, tuple): + return (value,) * num_elements + if len(value) != num_elements: + raise ValueError(error_message_lambda()) + return value + + +def _process_batched_inputs( + in_dims: in_dims_t, args: tuple[Any, ...], func: Callable[..., Any] +) -> tuple[int, list[int | None], list[Any], TreeSpec]: + if not isinstance(in_dims, int) and not isinstance(in_dims, tuple): + raise ValueError( + f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): " + f"expected `in_dims` to be int or a (potentially nested) tuple " + f"matching the structure of inputs, got: {type(in_dims)}." + ) + if len(args) == 0: + raise ValueError( + f"vmap({_get_name(func)})(): got no inputs. Maybe you forgot to add " + f"inputs, or you are trying to vmap over a function with no inputs. " + f"The latter is unsupported." + ) + + flat_args, args_spec = tree_flatten(args) + flat_in_dims = _broadcast_to_and_flatten(in_dims, args_spec) + if flat_in_dims is None: + raise ValueError( + f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): " + f"in_dims is not compatible with the structure of `inputs`. " + f"in_dims has structure {tree_flatten(in_dims)[1]} but inputs " + f"has structure {args_spec}." + ) + + for i, (arg, in_dim) in enumerate(zip(flat_args, flat_in_dims)): + if not isinstance(in_dim, int) and in_dim is not None: + raise ValueError( + f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): " + f"Got in_dim={in_dim} for an input but in_dim must be either " + f"an integer dimension or None." + ) + if isinstance(in_dim, int) and not isinstance(arg, Tensor): + raise ValueError( + f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): " + f"Got in_dim={in_dim} for an input but the input is of type " + f"{type(arg)}. We cannot vmap over non-Tensor arguments, " + f"please use None as the respective in_dim" + ) + if in_dim is not None and (in_dim < -arg.dim() or in_dim >= arg.dim()): + raise ValueError( + f"vmap({_get_name(func)}, in_dims={in_dims}, ...)(): " + f"Got in_dim={in_dim} for some input, but that input is a Tensor " + f"of dimensionality {arg.dim()} so expected in_dim to satisfy " + f"-{arg.dim()} <= in_dim < {arg.dim()}." + ) + if in_dim is not None and in_dim < 0: + flat_in_dims[i] = in_dim % arg.dim() + + return ( + _validate_and_get_batch_size(flat_in_dims, flat_args), + flat_in_dims, + flat_args, + args_spec, + ) + + +# Creates BatchedTensors for every Tensor in arg that should be batched. +# Returns the (potentially) batched arguments and the batch_size. + + +# TODO: See if we can explain how flat works to the type checker +def _create_batched_inputs( + flat_in_dims: list[int | None], + flat_args: list[Any], + vmap_level: int, + args_spec: TreeSpec, +) -> tuple[Any, ...]: + # See NOTE [Ignored _remove_batch_dim, _add_batch_dim] + batched_inputs = [ + arg if in_dim is None else _add_batch_dim(arg, in_dim, vmap_level) + for in_dim, arg in zip(flat_in_dims, flat_args) + ] + return tree_unflatten(batched_inputs, args_spec) + + +def _maybe_remove_batch_dim( + name: str, + batched_output: Any, + vmap_level: int, + batch_size: int, + out_dim: int | None, +) -> torch.Tensor: + if out_dim is None: + if isinstance(batched_output, torch.Tensor) and is_batchedtensor( + batched_output + ): + raise ValueError( + f"vmap({name}, ...): `{name}` can not return a " + f"BatchedTensor when out_dim is None" + ) + return batched_output + + # out_dim is non None + if not isinstance(batched_output, torch.Tensor): + raise ValueError( + f"vmap({name}, ...): `{name}` must only return " + f"Tensors, got type {type(batched_output)}. " + "Did you mean to set out_dims= to None for output?" + ) + + return _remove_batch_dim(batched_output, vmap_level, batch_size, out_dim) + + +# Undoes the batching (and any batch dimensions) associated with the `vmap_level`. +def _unwrap_batched( + batched_outputs: Tensor | tuple[Tensor, ...], + out_dims: out_dims_t, + vmap_level: int, + batch_size: int, + func: Callable[..., Any], +) -> tuple[Any, ...]: + flat_batched_outputs, output_spec = tree_flatten(batched_outputs) + + def incompatible_error() -> NoReturn: + raise ValueError( + f"vmap({_get_name(func)}, ..., out_dims={out_dims})(): " + f"out_dims is not compatible with the structure of `outputs`. " + f"out_dims has structure {tree_flatten(out_dims)[1]} but outputs " + f"has structure {output_spec}." + ) + + flat_out_dims: list[int | None] = [] + if isinstance(batched_outputs, torch.Tensor): + # Some weird edge case requires us to spell out the following + # see test_out_dims_edge_case + if isinstance(out_dims, int): + flat_out_dims = [out_dims] + elif isinstance(out_dims, tuple) and len(out_dims) == 1: + flat_out_dims = list(out_dims) + elif out_dims is None: + flat_out_dims = [out_dims] + else: + incompatible_error() + else: + broadcast_result = _broadcast_to_and_flatten(out_dims, output_spec) + if broadcast_result is None: + incompatible_error() + else: + flat_out_dims = broadcast_result + + flat_outputs = [ + _maybe_remove_batch_dim( + _get_name(func), batched_output, vmap_level, batch_size, out_dim + ) + for batched_output, out_dim in zip(flat_batched_outputs, flat_out_dims) + ] + return tree_unflatten(flat_outputs, output_spec) + + +def _check_int_or_none(x: Any, func: Callable[..., Any], out_dims: out_dims_t) -> None: + if isinstance(x, int): + return + if x is None: + return + raise ValueError( + f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must be " + f"an int, None or a python collection of ints representing where in the outputs the " + f"vmapped dimension should appear." + ) + + +def _check_out_dims_is_int_or_int_pytree( + out_dims: out_dims_t, func: Callable[..., Any] +) -> None: + if isinstance(out_dims, int): + return + tree_map_(partial(_check_int_or_none, func=func, out_dims=out_dims), out_dims) + + +def _get_name(func: Callable[..., Any]) -> str: + if hasattr(func, "__name__"): + return func.__name__ + + if isinstance(func, functools.partial): + return f"functools.partial({_get_name(func.func)}, ...)" + + # Not all callables have __name__, in fact, only static functions/methods + # do. A callable created via nn.Module, to name one example, doesn't have a + # __name__. + return repr(func) + + +def vmap_impl( + func: Callable[_P, Tensor | tuple[Tensor, ...]], + in_dims: in_dims_t, + out_dims: out_dims_t, + randomness: str, + chunk_size: int | None, + *args: _P.args, + **kwargs: _P.kwargs, +) -> Any: + lazy_load_decompositions() + _check_out_dims_is_int_or_int_pytree(out_dims, func) + batch_size, flat_in_dims, flat_args, args_spec = _process_batched_inputs( + in_dims, args, func + ) + + if chunk_size is not None: + chunks_flat_args = _get_chunked_inputs( + flat_args, flat_in_dims, batch_size, chunk_size + ) + return _chunked_vmap( + func, + flat_in_dims, + chunks_flat_args, + args_spec, + out_dims, + randomness, + **kwargs, + ) + + # If chunk_size is not specified. + return _flat_vmap( + func, + batch_size, + flat_in_dims, + flat_args, + args_spec, + out_dims, + randomness, + **kwargs, + ) + + +def get_chunk_sizes(total_elems: int, chunk_size: int) -> list[int]: + n_chunks = total_elems // chunk_size + chunk_sizes = [chunk_size] * n_chunks + # remainder chunk + remainder = total_elems % chunk_size + if remainder != 0: + chunk_sizes.append(remainder) + return chunk_sizes + + +def _get_chunked_inputs( + flat_args: list[Any], + flat_in_dims: list[int | None], + batch_size: int, + chunk_size: int | None, +) -> Iterable[tuple[Any, ...]]: + split_idxs = (batch_size,) + if chunk_size is not None: + chunk_sizes = get_chunk_sizes(batch_size, chunk_size) + split_idxs = tuple(itertools.accumulate(chunk_sizes)) + + flat_args_chunks = tuple( + ( + t.tensor_split(split_idxs, dim=in_dim) + if in_dim is not None + else [ + t, + ] + * len(split_idxs) + ) + for t, in_dim in zip(flat_args, flat_in_dims) + ) + + # transpose chunk dim and flatten structure + # chunks_flat_args is a list of flatten args + chunks_flat_args = zip(*flat_args_chunks) + return chunks_flat_args + + +def _flatten_chunks_output( + chunks_output_: list[Any], +) -> tuple[list[tuple[Any, ...]], TreeSpec]: + # chunks_output is a list of chunked outputs + # flatten chunked outputs: + flat_chunks_output: list[list[Any]] = [] + arg_spec: TreeSpec | None = None + for output in chunks_output_: + flat_output, arg_specs = tree_flatten(output) + flat_chunks_output.append(flat_output) + if arg_spec is None: + arg_spec = arg_specs + + # transpose chunk dim and flatten structure + # flat_output_chunks is flat list of chunks + flat_output_chunks = list(zip(*flat_chunks_output)) + if arg_spec is None: + raise AssertionError("arg_spec must not be None") + return flat_output_chunks, arg_spec + + +def _concat_chunked_outputs( + out_dims: out_dims_t, + arg_spec: TreeSpec, + flat_output_chunks: list[tuple[Any, ...] | None], +) -> list[Tensor]: + # concat chunks on out_dim + flat_out_dims = _broadcast_to_and_flatten(out_dims, arg_spec) + if flat_out_dims is None: + raise AssertionError("flat_out_dims must not be None") + if len(flat_out_dims) != len(flat_output_chunks): + raise AssertionError( + f"len(flat_out_dims)={len(flat_out_dims)} != len(flat_output_chunks)={len(flat_output_chunks)}" + ) + flat_output: list[Tensor] = [] + for idx, out_dim in enumerate(flat_out_dims): + chunk = flat_output_chunks[idx] + if chunk is None: + raise AssertionError(f"chunk at index {idx} must not be None") + flat_output.append(torch.cat(chunk, dim=out_dim)) + # release tensors + flat_output_chunks[idx] = None + + return flat_output + + +# Applies vmap on chunked_input and returns concatenated output over the chunks. +def _chunked_vmap( + func: Callable[_P, Tensor | tuple[Tensor, ...]], + flat_in_dims: list[int | None], + chunks_flat_args: Iterable[tuple[Any, ...]], + args_spec: TreeSpec, + out_dims: out_dims_t, + randomness: str, + **kwargs: Any, +) -> Any: + chunks_output: list[Any] = [] + rs = torch.get_rng_state() if randomness == "same" else None + for flat_args_tuple in chunks_flat_args: + flat_args = list(flat_args_tuple) + batch_size = _validate_and_get_batch_size(flat_in_dims, flat_args) + + # The way we compute split the input in `_get_chunked_inputs`, + # we may get a tensor with `0` batch-size. We skip any computation + # in that case. + # Eg. + # >>> chunk_size = 1 + # >>> batch_size = 6 + # >>> t = torch.zeros(batch_size, 1) + # >>> t.tensor_split([1, 2, 3, 4, 5, 6]) + # (tensor([[0.]]), tensor([[0.]]), tensor([[0.]]), tensor([[0.]]), + # tensor([[0.]]), tensor([[0.]]), tensor([], size=(0, 1))) + if batch_size == 0: + continue + + if rs is not None: + torch.set_rng_state(rs) + chunks_output.append( + _flat_vmap( + func, + batch_size, + flat_in_dims, + flat_args, + args_spec, + out_dims, + randomness, + **kwargs, + ) + ) + + flat_output_chunks, arg_spec = _flatten_chunks_output(chunks_output) + + # chunked output tensors are held by both `flat_output_chunks` and `chunks_output`. + # eagerly remove the reference from `chunks_output`. + del chunks_output + + # concat chunks on out_dim + # Note: We use cast since flat_output_chunks is modified in _concat_chunked_outputs + # to set elements to None after processing + flat_output = _concat_chunked_outputs( + out_dims, arg_spec, cast(list[tuple[Any, ...] | None], flat_output_chunks) + ) + + # finally unflatten the output + return tree_unflatten(flat_output, arg_spec) + + +# Vmap refactored helper functions: +def _check_randomness_arg(randomness: str) -> None: + if randomness not in ["error", "different", "same"]: + raise RuntimeError( + f"Only allowed values for randomness are 'error', 'different', or 'same'. Got {randomness}" + ) + + +@contextlib.contextmanager +def vmap_increment_nesting( + batch_size: int, randomness: str +) -> Generator[int, None, None]: + try: + vmap_level = _vmap_increment_nesting(batch_size, randomness) + yield vmap_level + finally: + _vmap_decrement_nesting() + + +def _flat_vmap( + func: Callable[..., Tensor | tuple[Tensor, ...]], + batch_size: int, + flat_in_dims: list[int | None], + flat_args: list[Any], + args_spec: TreeSpec, + out_dims: out_dims_t, + randomness: str, + **kwargs: Any, +) -> Any: + with vmap_increment_nesting(batch_size, randomness) as vmap_level: + batched_inputs = _create_batched_inputs( + flat_in_dims, flat_args, vmap_level, args_spec + ) + batched_outputs = func(*batched_inputs, **kwargs) + return _unwrap_batched(batched_outputs, out_dims, vmap_level, batch_size, func) + + +# `restore_vmap` is a private helper function. It is vmap but has the following +# differences: +# - instead of returning outputs, it returns an (outputs, out_dims) tuple. +# out_dims is a pytree of same shape as outputs and contains Optional[int] +# specifying where the vmapped dimension, if it exists, is in the corresponding output. +# - does no validation on in_dims or inputs (vmap expects at least one Tensor to be vmapped). +# restore_vmap allows for no inputs to have the vmap dimension +# - does no validation on outputs (vmap expects only Tensor outputs) +# restore_vmap allows for return of arbitrary outputs (not just Tensors) +# +# The TL;DR is that restore_vmap is more general than vmap and has a slightly +# different API. The relaxations are so that we can "pause" vmap in the middle +# of its execution and then "restore" it later (this is what we do in +# the generate_vmap_rule=True implementation of autograd.Function). +# +# restore_vmap can be technically used in the implementation of vmap, but doing +# that refactor is a bit technically challenging because: +# - vmap couples the tensor-wrapping code with error checking +# - vmap's tensor unwrapping code is in C++; we would need to rewrite part of it +# in python because it overlaps with unwrap_batched +def restore_vmap( + func: Callable[..., _R], in_dims: in_dims_t, batch_size: int, randomness: str +) -> Callable[..., tuple[Any, Any]]: + def inner(*args: Any, **kwargs: Any) -> tuple[Any, Any]: + with vmap_increment_nesting(batch_size, randomness) as vmap_level: + batched_inputs = wrap_batched(args, in_dims, vmap_level) + batched_outputs = func(*batched_inputs, **kwargs) + return unwrap_batched(batched_outputs, vmap_level) + + return inner + + +def wrap_batched( + args: tuple[Any, ...], bdims: in_dims_t, level: int +) -> tuple[Any, ...]: + flat_args, spec = tree_flatten(args) + flat_bdims = _broadcast_to_and_flatten(bdims, spec) + if flat_bdims is None: + raise AssertionError("flat_bdims must not be None") + result = _create_batched_inputs(flat_bdims, flat_args, level, spec) + return result + + +def unwrap_batched(args: Any, level: int) -> tuple[Any, Any]: + flat_args, spec = tree_flatten(args) + if len(flat_args) == 0: + return args, () + result = [ + ( + torch._C._functorch._unwrap_batched(arg, level) + if isinstance(arg, torch.Tensor) + else (arg, None) + ) + for arg in flat_args + ] + output, bdims = zip(*result) + return tree_unflatten(output, spec), tree_unflatten(bdims, spec) diff --git a/.venv/lib/python3.12/site-packages/torch/_guards.py b/.venv/lib/python3.12/site-packages/torch/_guards.py new file mode 100644 index 0000000000000000000000000000000000000000..0b1eac5bf3a996d9dabc7a543942832ec4714689 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_guards.py @@ -0,0 +1,1610 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import enum +import functools +import logging +import re +import sys +import threading +import traceback +import unittest.mock +import weakref +from abc import abstractmethod +from collections import defaultdict +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Any, Generic, NamedTuple, overload, TYPE_CHECKING, TypeVar +from typing_extensions import dataclass_transform + +import torch +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils._traceback import CapturedTraceback, format_frame +from torch.utils.weak import WeakTensorKeyDictionary + + +log = logging.getLogger(__name__) + + +if TYPE_CHECKING: + import dis + from collections.abc import Callable, Generator, Iterator + from types import CodeType + + import sympy + + from torch._dynamo.backends.distributed import DDPOptimizerContext + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.guards import GuardCheckSpec + from torch._dynamo.output_graph import CodeOptions + from torch._functorch._aot_autograd.schemas import ViewAndMutationMeta + from torch._higher_order_ops.invoke_subgraph import NestedCompileRegionOptions + from torch._subclasses.fake_tensor import FakeTensorMode + + +""" +torch._guards is the definitional source of truth for general purpose guard structures. + +An important thing to keep in mind here is the preservation of layering. There should be no dynamo notions, +and no guard installation notions here. +""" + +COMPILE_ID_PATTERN = re.compile(r"^(?P\d+)/(?P\d+)$") +CA_COMPILE_ID_PATTERN = re.compile( + r"^!(?P\d+)(?:/(?P\d+)/(?P\d+))?$" +) + +# [Note: Updating CompiledId] +# +# CompiledId represents a unique program-level identifier, and we want to keep that +# property as the codebase evolves. This property is relied on even outside of the pytorch +# repo, e.g. tlparse or other internal tooling. The in-memory format can be freely changed, +# as those dependencies only consume the string serialization. +# +# The string form should be: +# 1. Program-level uid: CompileId can uniquely identify a compiled graph. +# 2. Storage efficient: This object is logged in nearly every entry. We should elide symbols when possible. +# 3. Compact: The string form is directly displayed by some tools. Special symbols are okay. + + +@dataclass(frozen=True, kw_only=True, slots=True) +class CompileId: + frame_id: int | None + # This id is per-frame, and counts how many times we've compiled this + # frame. This could have been a global id but having this be per-frame + # gives you a better intuitive sense for how many recompiles have occurred + # so far. + frame_compile_id: int | None + + # torch.compiling a compiled autograd graph + compiled_autograd_id: int | None = None + + # TODO: consider also tracking the recompilation count + # See Note: Updating CompileId + + def __str__(self) -> str: + # NOTE: Keep this in sync with both from_string and the tlparse repo + if self.compiled_autograd_id is not None: + if (self.frame_id is None) != (self.frame_compile_id is None): + raise AssertionError( + f"frame_id and frame_compile_id must both be None or both be set, " + f"got frame_id={self.frame_id}, frame_compile_id={self.frame_compile_id}" + ) + frame_str = "" + if self.frame_id is not None: + frame_str = f"/{self.frame_id}/{self.frame_compile_id}" + + return f"!{self.compiled_autograd_id}{frame_str}" + else: + if self.frame_id is None or self.frame_compile_id is None: + raise AssertionError( + f"frame_id and frame_compile_id must not be None, " + f"got frame_id={self.frame_id}, frame_compile_id={self.frame_compile_id}" + ) + return f"{self.frame_id}/{self.frame_compile_id}" + + @classmethod + def from_string(cls, compile_id: str | None) -> CompileId | None: + """ + Factory method that creates a CompileId from its string representation. + Keep this in sync with the __str__ method. + """ + if compile_id is None: + return None + try: + for pattern in (COMPILE_ID_PATTERN, CA_COMPILE_ID_PATTERN): + if match := pattern.match(compile_id): + groups = match.groupdict() + for k, v in groups.items(): + if v is not None: + groups[k] = int(v) + return cls(**groups) # type: ignore[arg-type] + else: + raise ValueError + + except Exception as e: + raise ValueError(f"Invalid compile_id '{compile_id}'") from e + + +class TraceId(NamedTuple): + compile_id: CompileId + # This starts off as 0, and every time we restart analysis it goes + # up by one + attempt: int + + def __str__(self) -> str: + # Keep this in sync with tlparse repo + if self.attempt == 0: + return str(self.compile_id) + else: + return f"{self.compile_id}_{self.attempt}" + + +class GuardSource(enum.Enum): + LOCAL = 0 + GLOBAL = 1 + LOCAL_SPECIALIZED_NN_MODULE = 2 + GLOBAL_SPECIALIZED_NN_MODULE = 3 + CONSTANT = 4 + RANDOM_VALUE = 5 + SHAPE_ENV = 6 + LOCAL_FSDP_MODULE = 7 + GLOBAL_FSDP_MODULE = 8 + BACKWARD_STATE = 9 + EPHEMERAL = 10 + SYNTHETIC_LOCAL = 11 + LOCAL_UNSPECIALIZED_NN_MODULE = 12 + GLOBAL_UNSPECIALIZED_NN_MODULE = 13 + LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 14 + GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 15 + TEMP_LOCAL = 16 + + def is_fsdp_module(self) -> bool: + return self in (GuardSource.GLOBAL_FSDP_MODULE, GuardSource.LOCAL_FSDP_MODULE) + + def is_specialized_nn_module(self) -> bool: + import torch._dynamo.config as config + + if config._unsafe_skip_fsdp_module_guards: + return ( + self + in ( + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + ) + or self.is_fsdp_module() + ) + return self in ( + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + ) + + def is_unspecialized_nn_module(self) -> bool: + return self in ( + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + ) + + def is_unspecialized_builtin_nn_module(self) -> bool: + return self in ( + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + ) + + def is_local(self) -> bool: + return self in ( + GuardSource.LOCAL, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_FSDP_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + ) + + +""" +Base class for a "GuardBuilder" role. + +The GuardBuilderBase role is to represent a scope within which to build a guard. The name is a little +confusing, as it's not a builder, but for the sake of avoiding a lot of renames and keeping the original reference +to torchdynamo's GuardBuilder. + +Note: create_fn is invoked with a GuardBuilderBase and a Guard. A GuardBuilder is chosen based +on GuardSource's select function. + +There is value in keeping this GuardBuilderBase empty to keep layering clean. +""" + + +class GuardBuilderBase: + pass + + +@dataclasses.dataclass(frozen=True) +class SLoc: + framework_loc: traceback.FrameSummary | str | None + maybe_user_loc: str | None + + def __str__(self) -> str: + floc = ( + self.framework_loc + if isinstance(self.framework_loc, str) + else "" + if self.framework_loc is None + else format_frame(self.framework_loc) + ) + if self.maybe_user_loc is not None: + return f"{self.maybe_user_loc} ({floc})" + else: + return f"({floc})" + + +class ShapeGuard(NamedTuple): + expr: sympy.logic.boolalg.Boolean + sloc: SLoc + size_oblivious: bool + + +@dataclasses.dataclass(slots=True) +class Guard: + # originating_source is the source that called the make_guard method to + # construct this guard object. The property name specifies what exactly it + # is the guard is guarding on. The meaning of the name is dependent on the + # create_fn; you must look at the use-site inside create_fn to know what + # name means. + # + # That being said, although you might think this is just a "name", name is + # usually an arbitrary Python expression that will be evaluated with all + # globals (and locals, if you create a LOCAL guard) to extract the Python + # object that we want to perform guard tests on. This evaluation + # typically happens in GuardBuilder.eval. In these cases, name is + # typically produced by originating_source.name (not to be confused with + # GuardSource - the property source). + # + # Occasionally, name is not a valid Python expression; sometimes + # it is meaningless. Example create_fns that are like this include + # GRAD_MODE and SHAPE_ENV. + originating_source: Source + create_fn: Callable[[GuardBuilderBase, Guard], None] + + # Export only. These values are written to at time of guard check_fn creation. + guard_types: list[str] | None = None + code_list: list[str] | None = None + obj_weakref: object | None = None + guarded_class_weakref: weakref.ReferenceType[Any] | None = None + + stack: CapturedTraceback | None = None + user_stack: traceback.StackSummary | None = None + _hash: int | None = None + _unserializable: bool = False + _force_dict_keys_match: bool = False + + def __hash__(self) -> int: + if self._hash is None: + self._hash = hash((self.name, self.source, id(self.create_fn))) + return self._hash + + def sort_key(self) -> tuple[bool, int, int, str, int]: + # Put the duplicate input guards at the end. The duplicate guards have + # two sources while guard.name only considers one source. + + is_duplicate_input = ( + isinstance(self.create_fn, functools.partial) + and self.create_fn.func is torch._dynamo.guards.GuardBuilder.DUPLICATE_INPUT + ) + return ( + is_duplicate_input, + self.source.value if self.source else -1, + len(self.name), + self.name, + self.inner_create_fn().__code__.co_firstlineno, + ) + + def __lt__(self, other: Guard) -> bool: + return self.sort_key() < other.sort_key() + + def inner_create_fn(self) -> Callable[[GuardBuilderBase, Guard], Any]: + if isinstance(self.create_fn, functools.partial): + return self.create_fn.func + else: + return self.create_fn + + @property + def name(self) -> str: + return self.originating_source.name + + @property + def source(self) -> GuardSource: + return self.originating_source.guard_source + + @staticmethod + def weakref_to_str(obj_weakref: object) -> str: + """ + This is a workaround of a Python weakref bug. + + `obj_weakref` is instance returned by `weakref.ref`, + `str(obj_weakref)` is buggy if the original obj overrides __getattr__, e.g: + + class MyConfig(dict): + def __getattr__(self, x): + return self[x] + + obj = MyConfig(offset=5) + obj_weakref = weakref.ref(obj) + str(obj_weakref) # raise error: KeyError: '__name__' + """ + if isinstance(obj_weakref, weakref.ReferenceType): + obj = obj_weakref() + if obj is not None: + return f"" + else: + return f"" + else: + return str(obj_weakref) + + def __repr__(self) -> str: + s = f""" + {self.source.name.lower() if self.source else ""} {repr(self.name)} {self.inner_create_fn().__name__} + {{ + 'guard_types': {self.guard_types}, + 'code': {self.code_list}, + 'obj_weakref': {self.weakref_to_str(self.obj_weakref)} + 'guarded_class': {self.guarded_class_weakref} + }} + """ + return s + + def __str__(self) -> str: + output = f"Name: {repr(self.name)}\n" + source = self.source.name.lower() if self.source else "" + output += f" Source: {source}\n" + output += f" Create Function: {self.inner_create_fn().__name__}\n" + output += f" Guard Types: {self.guard_types}\n" + output += f" Code List: {self.code_list}\n" + output += f" Object Weakref: {self.weakref_to_str(self.obj_weakref)}\n" + output += f" Guarded Class Weakref: {self.guarded_class_weakref}\n" + return output + + def create(self, builder: GuardBuilderBase) -> Any: + try: + return self.create_fn(builder, self) + except Exception: + log.exception("Error while creating guard:\n%s", str(self).rstrip()) + if self.stack: + log.error("Created at:\n%s", "".join(self.stack.format()[-4:]).rstrip()) + raise + + def is_specialized_nn_module(self) -> bool: + return self.source.is_specialized_nn_module() + + def is_fsdp_module(self) -> bool: + return self.source.is_fsdp_module() + + def is_local(self) -> bool: + return self.source.is_local() + + def create_fn_name(self) -> str: + if isinstance(self.create_fn, functools.partial): + create_fn = self.create_fn.func # type: ignore[attr-defined] + else: + create_fn = self.create_fn + return create_fn.__name__ + + def set_export_info( + self, + guard_type: str, + guarded_class: weakref.ReferenceType[Any] | None, + code_list: list[str], + obj_weakref: object, + ) -> None: + if not self.guard_types: + self.guard_types = [] + + self.guard_types.append(guard_type) + + if self.guarded_class_weakref not in (guarded_class, None): + raise AssertionError( + f"Guarded class id must be identical, or None, " + f"got {self.guarded_class_weakref} vs {guarded_class}" + ) + self.guarded_class_weakref = guarded_class + + if not self.code_list: + self.code_list = code_list + else: + self.code_list.extend(code_list) + + # Some objects are ephemeral, e.g., list[slice(1, 2)]. If we have + # multiple guards on the same object, the weakref can die between the + # invocation of set_export_info calls. So a dead weakref is also + # acceptable. + is_valid = ( + self.obj_weakref in (obj_weakref, None) + or callable(self.obj_weakref) + and self.obj_weakref() is None + ) + if not is_valid: + raise AssertionError( + f"Guarded object must be identical, None or ephemeral (dead weakref), " + f"got {self.obj_weakref} vs {obj_weakref}" + ) + self.obj_weakref = obj_weakref + + +T = TypeVar("T") + +""" +Parent structure for guard env expressions. +A GuardEnvExpr can have any subtype. +Note: All subtypes must be handled exhaustively in +torch._dynamo.guards._parse_guard_env_guards to avoid a RuntimeError. +""" + + +@dataclasses.dataclass(frozen=True) +class GuardEnvExpr: + pass + + +""" +A class representing a pair of duplicate inputs. +input_pos_a and input_pos_b are input positions we have deduped. +""" + + +@dataclasses.dataclass(frozen=True) +class DuplicateInputs(GuardEnvExpr): + input_source_a: Source + input_source_b: Source + + def __post_init__(self) -> None: + if self.input_source_a == self.input_source_b: + raise AssertionError( + f"input_source_a and input_source_b must be different, " + f"got {self.input_source_a}" + ) + + +""" +A class representing storage overlap relations among inputs that aliases the same storage. + +Given that a set of tensors alias the same storage, this guard checks whether they actually +have overlapping storages. + +While non_overlapping_sources represent input tensors that definitely don't have any storage +overlapping with any other input, overlapping_sources represent tensors that either: + +1. Do overlap some other input tensor +2. Might not overlap some other input tensor, but we are not sure +""" + + +@dataclasses.dataclass(frozen=True) +class StorageOverlap(GuardEnvExpr): + overlapping_sources: list[Source] + non_overlapping_sources: list[Source] + + +""" +Checkpointable is an interface for driving state snapshotting, left purposely vague for now. + +copy_graphstate() -> T, a somewhat legacy name, is expected to emit a snapshot of any type that +can also be taken in at restore_graphstate(T) calls. + +When to snapshot, is, at the moment, an implementation detail of upstream callers. Checkpointable +does not provide any guarantees around consistency, idempotency, or safety of calling its APIs, yet. + +In the future, it will have a closer coupling to a generic Checkpoint management system. +""" + + +class Checkpointable(Generic[T]): + @abstractmethod + def copy_graphstate(self) -> T: ... + + @abstractmethod + def restore_graphstate(self, state: T) -> None: ... + + +class GuardsCheckpointState: + """ + The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext + """ + + dynamo_guards: OrderedSet[Guard] + + def __init__(self, dynamo_guards: OrderedSet[Guard]) -> None: + self.dynamo_guards = dynamo_guards + + def diff(self, other: GuardsCheckpointState) -> OrderedSet[Guard] | None: + """ + Produces a delta against another GuardsCheckpointState. + + Returns None if no delta is found, otherwise, return an OrderedSet() of mismatched + Guard type objects. + """ + r = self.dynamo_guards.difference(other.dynamo_guards) + if len(r) == 0: + return None + return r + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GuardsCheckpointState): + return False + return self.diff(other) is None + + +class ModuleContextCheckpointState: + nn_modules: dict[str, torch.nn.Module] = {} + + def __init__(self, nn_modules: dict[str, torch.nn.Module]) -> None: + self.nn_modules = nn_modules + + def diff(self, other: ModuleContextCheckpointState) -> set[str] | None: + """ + Produces a delta against another ModuleContextCheckpointState. + + Returns None if no delta is found, otherwise, return a set() of mismatched + module key names. + """ + r = set(self.nn_modules.keys()).difference(set(other.nn_modules.keys())) + if len(r) == 0: + return None + return r + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ModuleContextCheckpointState): + return False + return self.diff(other) is None + + +class ModuleContext(Checkpointable[ModuleContextCheckpointState]): + def __init__(self) -> None: + self.nn_modules: dict[str, Any] = {} + + def copy_graphstate(self) -> ModuleContextCheckpointState: + return ModuleContextCheckpointState(dict(self.nn_modules)) + + def restore_graphstate(self, state: ModuleContextCheckpointState) -> None: + if not isinstance(state, ModuleContextCheckpointState): + raise AssertionError( + f"expected ModuleContextCheckpointState, got {type(state)}" + ) + self.nn_modules = state.nn_modules + + +class GlobalContextCheckpointState: + global_state: dict[str, tuple[Callable, Any]] = {} + + def __init__(self, global_states: dict[str, tuple[Callable, Any]]) -> None: + self.global_state = global_states + + def diff(self, other: GlobalContextCheckpointState) -> set[str] | None: + """ + Produces a delta against another GlobalContextCheckpointState. + + Returns None if no delta is found, otherwise, return a set() of mismatched + global key names. + """ + r = set(self.global_state.keys()).difference(set(other.global_state.keys())) + if len(r) == 0: + return None + return r + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GlobalContextCheckpointState): + return False + return self.diff(other) is None + + +class GlobalContext(Checkpointable[GlobalContextCheckpointState]): + """ + This keeps track of the global torch state during tracing of a function. + For example, torch.is_grad_enabled. + """ + + _supported_global_states = { + "grad_enabled", + "autocast_enabled", + "autocast_cpu_enabled", + "autocast_gpu_dtype", + "autocast_cpu_dtype", + "autocast_cache_enabled", + } + + def __init__(self) -> None: + self.global_state: dict[str, tuple[Callable, Any]] = {} + + def copy_graphstate(self) -> GlobalContextCheckpointState: + return GlobalContextCheckpointState(self.global_state) + + def restore_graphstate(self, state: GlobalContextCheckpointState) -> None: + if not isinstance(state, GlobalContextCheckpointState): + raise AssertionError( + f"expected GlobalContextCheckpointState, got {type(state)}" + ) + self.global_state = state.global_state + if not ( + len(self.global_state) == len(self._supported_global_states) + and set(self.global_state.keys()) == self._supported_global_states + ): + raise AssertionError( + f"Global state mismatch: got keys {set(self.global_state.keys())}, " + f"expected {self._supported_global_states}" + ) + for func, args in self.global_state.values(): + func(args) + + +# Like a Set[Guard] but will record the user stack on all guards at the +# time they were installed at their destination +class GuardsSet: + def __init__(self, inner: OrderedSet[Guard] | None = None) -> None: + if inner is None: + self.inner: OrderedSet[Guard] = OrderedSet() + else: + self.inner = inner + # Map from source to list of guards with that source. Incrementally + # built in `add` method. + self.source_to_guards: defaultdict[Source, list[Guard]] = defaultdict(list) + for guard in self.inner: + self.track_guard_by_source(guard) + + def track_guard_by_source(self, guard: Guard) -> None: + source = guard.originating_source + self.source_to_guards[source].append(guard) + + def __iter__(self) -> Iterator[Guard]: + return iter(self.inner) + + def __len__(self) -> int: + return len(self.inner) + + # Subtraction along with bool is typically used to determine the delta of + # added guards between checkpoints for higher order ops + def __sub__(self, other: GuardsSet) -> GuardsSet: + return GuardsSet(self.inner - other.inner) + + def __bool__(self) -> bool: + return bool(self.inner) + + def clear(self) -> None: + self.inner = OrderedSet() + self.source_to_guards = defaultdict(list) + + def add( + self, guard: Guard, *, collect_debug_stack: bool = True, skip: int = 0 + ) -> None: + if guard in self.inner: + return + if collect_debug_stack: + if guard.stack is None: + guard.stack = CapturedTraceback.extract(skip=1 + skip) + if guard.user_stack is None: + guard.user_stack = TracingContext.extract_stack() + self.inner.add(guard) + self.track_guard_by_source(guard) + + def update(self, *others: set[Guard]) -> None: + for o in others: + for g in o: + self.add(g, skip=1) + + def get_guards_for_source(self, source: Source) -> list[Guard]: + """Return all guards with the given originating_source.""" + return list(self.source_to_guards[source]) + + def remove_guards_with_source(self, source: Source) -> None: + """Delete all guards that contains a given source""" + from ._dynamo.source import is_from_source + + self.inner = OrderedSet( + g for g in self.inner if not is_from_source(g.originating_source, source) + ) + # Rebuild the index since is_from_source walks the chain, so + # multiple source keys may need removal. + self.source_to_guards = defaultdict(list) + for guard in self.inner: + self.track_guard_by_source(guard) + + +""" +A GuardsContext is a checkpointable representation of all the guards in the current tracing +context. Its lifecycle is bound 1:1 to the tracing context, and it should never be instantiated +directly outside of it. For passing around internal state representations of this object, +prefer to extract them with copy_graphstate to produce a GuardsCheckpointState. +""" + + +class GuardsContext(Checkpointable[GuardsCheckpointState]): + def __init__(self) -> None: + self.dynamo_guards: GuardsSet = GuardsSet() + self.aotautograd_guards: list[GuardEnvExpr] = [] + self.skip_install: bool = False + + @contextlib.contextmanager + def skip_guard_install(self) -> Generator[None, None, None]: + old = self.skip_install + self.skip_install = True + try: + yield + finally: + self.skip_install = old + + def copy_graphstate(self) -> GuardsCheckpointState: + return GuardsCheckpointState(OrderedSet(self.dynamo_guards.inner)) + + def restore_graphstate(self, state: GuardsCheckpointState) -> None: + # NB: "steals" the passed in state + if not isinstance(state, GuardsCheckpointState): + raise AssertionError(f"expected GuardsCheckpointState, got {type(state)}") + self.dynamo_guards = GuardsSet(state.dynamo_guards) + + +class HopSubgraphCache: + @abstractmethod + def add_dynamo_installed_submodule( + self, fn_code: CodeType, identifier: str + ) -> None: ... + + @abstractmethod + def get_dynamo_installed_submodules(self, fn_code: CodeType) -> list[str]: ... + + @abstractmethod + def add_autograd_key_entry(self, identifier: str, key: Callable) -> None: ... + + @abstractmethod + def get_autograd_key_entry(self, identifier: str) -> Callable | None: ... + + @abstractmethod + def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None: ... + + @abstractmethod + def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None: ... + + @abstractmethod + def add_functionalize_schema_entry( + self, key: object, schema: torch._C.FunctionSchema + ) -> None: ... + + @abstractmethod + def get_functionalize_schema_entry( + self, key: object + ) -> torch._C.FunctionSchema | None: ... + + @abstractmethod + def add_lazy_bwd_entry( + self, + identifier: str, + tangent_metadata: tuple[object], + gmod: torch.fx.GraphModule, + ) -> int: ... + + @abstractmethod + def get_lazy_bwd_entry( + self, identifier: str, tangent_metadata: tuple[object] + ) -> tuple[torch.fx.GraphModule | None, int | None]: ... + + +@dataclass +class InvokeSubgraphReuseEntry: + body_name: str + body_gmod: torch.fx.GraphModule + config: NestedCompileRegionOptions | None + subgraph_input_mapping: list[ + Any + ] # list[LiftedArgOrigin] - defined in invoke_subgraph.py + single_tensor_output: bool + # Per-output tensor metadata (shape, stride, dtype, device, requires_grad) + # cached from the first trace so we can construct fresh FakeTensors on + # cache hit without re-running body_gmod. + output_metadata: list[ + tuple[torch.Size, tuple[int, ...], torch.dtype, torch.device, bool] + ] + # 1-1 mapping to flat_vts: source for each flattened arg/kwarg, or None if + # the VT has no source. On cache hit, we build a source replacement mapping + # (old arg sources → new arg sources) to rewrite captured variable sources + # for the current invocation. + arg_sources: list[Source | None] + # Number of user-visible outputs (from the function return value). + # The graph may have additional outputs from side-effect intermediates; + # stamp_out_subgraph uses this to return only the user-visible slice. + num_user_outputs: int = 0 + + +@dataclass +class InvokeSubgraphReuseCondition: + # Per flattened input VT: (InputTag, metadata). + # (InputTag.TENSOR, TensorMetadata) + # (InputTag.SYMNODE, sym_num — same object implies same symbol) + # (InputTag.CONSTANT, value) + # (InputTag.OBJECT, None) + # Tensor metadata is checked here because TENSOR_MATCH guards for + # subgraph inputs may already exist before tracing and thus won't + # appear in the guard delta. + input_checks: list[tuple[Any, object]] # list[tuple[InputTag, object]] + + # Guards captured during the trace (delta + source-mapped). + # Each entry: (source, handler, expected_value, guard) + # handler is a pre-resolved GuardCheckSpec from GUARD_VALUE_DISPATCH. + guards: list[tuple[Source, GuardCheckSpec, object, Guard]] + + # TreeSpec from pytree.tree_flatten of the (args, kwargs) structure. + # On cache hit, we verify the new call has the same treespec. + treespec: pytree.TreeSpec | None = None + + # All sources accessed via VariableBuilder during the subgraph trace. + # On cache hit, we check if any modified VT's source is a base of one + # of these to detect mutations on captured variables. + traced_sources: OrderedSet[Source] = dataclasses.field(default_factory=OrderedSet) + + +class InvokeSubgraphCache(HopSubgraphCache): + def __init__(self) -> None: + self.autograd_cache: dict[str, Callable] = {} + self.proxy_dispatch_cache: dict[str, Callable] = {} + self.functionalize_schema_cache: dict[object, torch._C.FunctionSchema] = {} + self.dynamo_installed_submodules: dict[CodeType, list[str]] = defaultdict(list) + self.lazy_bwd_cache: dict[ + str, dict[tuple[object], tuple[torch.fx.GraphModule, int]] + ] = defaultdict(dict) + self.effects_cache: dict[ + str, set + ] = {} # Maps identifier -> set of effect types + # fn.__code__ → list of (condition, cache_entry) pairs. Walked linearly + # on lookup; first matching condition wins. + self.subgraph_reuse_cache: dict[ + CodeType, + list[tuple[InvokeSubgraphReuseCondition, InvokeSubgraphReuseEntry]], + ] = defaultdict(list) + # fn_code → {hash_key → cache_entry}. Used by user-provided + # reuse_hash_fn for O(1) subgraph reuse lookup. + self.subgraph_reuse_key_cache: dict[ + CodeType, dict[int, InvokeSubgraphReuseEntry] + ] = defaultdict(dict) + + def add_dynamo_installed_submodule( + self, fn_code: CodeType, identifier: str + ) -> None: + self.dynamo_installed_submodules[fn_code].append(identifier) + + def get_dynamo_installed_submodules(self, fn_code: CodeType) -> list[str]: + return self.dynamo_installed_submodules.get(fn_code, []) + + def add_autograd_key_entry(self, identifier: str, key: Callable) -> None: + self.autograd_cache[identifier] = key + + def get_autograd_key_entry(self, identifier: str) -> Callable | None: + return self.autograd_cache.get(identifier, None) + + def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None: + self.proxy_dispatch_cache[identifier] = key + + def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None: + return self.proxy_dispatch_cache.get(identifier, None) + + def add_functionalize_schema_entry( + self, key: object, schema: torch._C.FunctionSchema + ) -> None: + self.functionalize_schema_cache[key] = schema + + def get_functionalize_schema_entry( + self, key: object + ) -> torch._C.FunctionSchema | None: + return self.functionalize_schema_cache.get(key, None) + + def add_lazy_bwd_entry( + self, + identifier: str, + tangent_metadata: tuple[object], + gmod: torch.fx.GraphModule, + ) -> int: + # Save the number of existing graph modules in the dictionary to get the suffix + num_gmods = len(self.lazy_bwd_cache[identifier]) + self.lazy_bwd_cache[identifier][tangent_metadata] = (gmod, num_gmods) + return num_gmods + + def get_lazy_bwd_entry( + self, identifier: str, tangent_metadata: tuple[object] + ) -> tuple[torch.fx.GraphModule | None, int | None]: + if identifier not in self.lazy_bwd_cache: + return (None, None) + + return self.lazy_bwd_cache[identifier].get(tangent_metadata, (None, None)) + + def add_effects(self, identifier: str, effects: set) -> None: + """Store the effect types for a given invoke_subgraph identifier.""" + if prev_effects := self.effects_cache.get(identifier, None): + if effects != prev_effects: + raise AssertionError( + "Different number of effects were found for invoke_subgraph " + f"call with identifier {identifier}. \n" + f"Previously we had the following effects: {prev_effects}.\n" + f"But now we have: {effects}." + ) + self.effects_cache[identifier] = effects + + def get_effects(self, identifier: str) -> set | None: + """Retrieve the effect types for a given invoke_subgraph identifier.""" + return self.effects_cache.get(identifier, None) + + def add_reuse_entry( + self, + fn_code: CodeType, + condition: InvokeSubgraphReuseCondition, + entry: InvokeSubgraphReuseEntry, + max_reuse_entries: int = 8, + ) -> None: + entries = self.subgraph_reuse_cache[fn_code] + if len(entries) >= max_reuse_entries: + raise RuntimeError( + f"invoke_subgraph: exceeded maximum reuse entries " + f"({max_reuse_entries}) for function code {fn_code}. " + f"This most likely means a guard keeps failing on every " + f"invocation, preventing subgraph reuse. " + f"Set TORCH_LOGS='+hierarchical_compile' to identify which " + f"guard is failing. If reuse is genuinely not possible and " + f"you need more cache entries, increase the limit via the " + f"max_reuse_entries argument to nested_compile_region()." + ) + entries.append((condition, entry)) + + def find_reuse_entry( + self, + fn_code: CodeType, + evaluator: Callable[ + [InvokeSubgraphReuseCondition, InvokeSubgraphReuseEntry], bool + ], + ) -> InvokeSubgraphReuseEntry | None: + entries = self.subgraph_reuse_cache.get(fn_code, []) + for i, (condition, entry) in enumerate(entries): + if evaluator(condition, entry): + # MRU: move the hit entry to the front for faster future lookups + if i > 0: + entries.insert(0, entries.pop(i)) + return entry + return None + + def find_reuse_entry_by_key( + self, fn_code: CodeType, hash_key: int + ) -> InvokeSubgraphReuseEntry | None: + return self.subgraph_reuse_key_cache.get(fn_code, {}).get(hash_key) + + def add_reuse_entry_by_key( + self, + fn_code: CodeType, + hash_key: int, + entry: InvokeSubgraphReuseEntry, + max_reuse_entries: int = 8, + ) -> None: + key_cache = self.subgraph_reuse_key_cache[fn_code] + if len(key_cache) >= max_reuse_entries and hash_key not in key_cache: + raise RuntimeError( + f"invoke_subgraph: exceeded maximum reuse entries " + f"({max_reuse_entries}) for function code {fn_code} (hash-key path). " + f"Increase the limit via the max_reuse_entries argument to " + f"nested_compile_region()." + ) + key_cache[hash_key] = entry + + +class HopDispatchSetCache: + def __init__(self) -> None: + # Delayed import to avoid circular dependency + from torch._higher_order_ops.invoke_subgraph import invoke_subgraph + + self.hop_cache_map = {invoke_subgraph: InvokeSubgraphCache()} + + def get_cache(self, op: torch._ops.HigherOrderOperator) -> HopSubgraphCache | None: + if op not in self.hop_cache_map: + return None + return self.hop_cache_map[op] # type: ignore[index] + + +class _TLSStorage(threading.local): + # Default the hot-path attributes to None per thread so that + # TracingContext.try_get() / CompileContext.try_get() -- called on every + # torch.compile'd call -- hit a present attribute instead of paying for an + # AttributeError raise+catch inside getattr(). Without this, a thread that + # never ran compilation itself (e.g. a worker thread executing compiled code + # compiled on another thread) takes the slow getattr-miss path on every call. + def __init__(self) -> None: + self.tracing_context: TracingContext | None = None + self.compile_context: CompileContext | None = None + + +_TLS = _TLSStorage() + +""" +TracingContext is the source of truth for all currently accumulated information +needed to trace. Its lifecycle is kept 1:1 when using TorchDynamo, but other systems +are open to managing their own TracingContext with that in mind. + +The purpose of TracingContext is not to be a dumping ground, or god object, but rather to avoid +having to plumb complex subsystems across multiple verticals. + +Ex: A common example is guard accumulation between dynamo, shape_env, aot_autograd, and inductor. +Accessing the current tracing context via +TracingContext.get() allows users to accumulate their own guards for processing, without needing to know how +to plumb objects back up to where frame interpretation happened. + +Note that you can end up with multiple TracingContext for a single compilation +of a frame, as we reset the TracingContext whenever we restart analysis. +CompileContext is a more overarching context that encompasses multiple restarts. +""" + + +class CompileContext: + @staticmethod + def get() -> CompileContext: + if _TLS.compile_context is None: + raise AssertionError("compile_context is not set") + return _TLS.compile_context + + @staticmethod + def try_get() -> CompileContext | None: + return getattr(_TLS, "compile_context", None) + + def __init__(self, compile_id: CompileId | None) -> None: + if compile_id is not None and not isinstance(compile_id, CompileId): + raise AssertionError( + f"compile_id must be None or CompileId, got {type(compile_id)}" + ) + self.compile_id: CompileId | None = compile_id + self.attempt = 0 + # Verbose ShapeEnv guards produced. + self.shape_env_guards: list[str] = [] + + @staticmethod + def current_compile_id() -> CompileId | None: + self = CompileContext.try_get() + if self is None: + return None + return self.compile_id + + @staticmethod + def current_trace_id() -> TraceId | None: + self = CompileContext.try_get() + if self is None: + return None + if self.compile_id is None: + return None + return TraceId(self.compile_id, self.attempt) + + +@dataclass +class InlinedCodeCache: + """Cache for code-object-derived data used during inlining.""" + + instructions: list[Any] + indexof: dict[Any, int] + code_options: CodeOptions + + +class TracingContext: + """ + Provides the currently installed TracingContext, or None. + + Note that it is a staticmethod, and invocations outside of `with tracing()` (see below), are valid but + will return None. + """ + + @staticmethod + def try_get() -> TracingContext | None: + return getattr(_TLS, "tracing_context", None) + + @staticmethod + def get() -> TracingContext: + if ctx := TracingContext.try_get(): + return ctx + raise RuntimeError( + "TracingContext.get() must be called within an ongoing trace." + ) + + def __init__(self, fake_mode: FakeTensorMode | None) -> None: + self.guards_context = GuardsContext() + self.module_context = ModuleContext() + self.global_context = GlobalContext() + self.previously_inlined_functions: dict[Any, Any] = dict() + self.previously_cleaned_instructions: dict[Any, Any] = dict() + # Combined cache for inlined code data (instructions, indexof, code_options) + self.inlined_code_cache: dict[Any, InlinedCodeCache] = dict() + self.fake_mode: FakeTensorMode | None = fake_mode + self.frame_summary_stack: list[traceback.FrameSummary] = [] + # This is morally part of frame_summary_stack, but it is kept separate + # for clarity. As we process a frame, this variable gets updated + # to keep track of what line we are in the function. We make a + # function call, this gets cleared and the frame location is pushed + # to frame_summary_stack (prepping this variable for the inner frame's + # progress) + self.loc_in_frame: tuple[str, int, str] | None = None + self.loc_in_frame_positions: dis.Positions | None = None + # this is only set after aot_autograd + self.fw_metadata: ViewAndMutationMeta | None = None + # this is only set when the DDPOptimizer is used + self.ddp_optimizer_ctx: DDPOptimizerContext | None = None + # this is only set after aot_autograd + self.aot_graph_name: list[str] | None = None + self.params_flat: list[Any] | None = None + self.params_flat_unwrap_subclasses: list[Any] | None = None + self.params_unwrapped_to_flat_index: list[Any] | None = None + # this is for extended return calling convention from backend + # compiler to aot_autograd + # Per output, what the compiler specified stride of the output is, + # or None if no stride is known. This is always the HINT, it + # is never a SymInt (it would be better if it was a SymInt, but + # I can't conveniently get this from Inductor atm. Also, be + # careful not to accidentally induce guards on the SymInt if + # you ever do change this in aot_autograd.py; you should check + # on permutations preferentially.) + self.output_strides: list[tuple[int, ...] | None] | None = None + # When this is True, whenever we encounter an int in Dynamo tracing, + # we will (1) force unspec it and (2) force it as a size-like unbacked + # integer. This is currently used when processing certain lists of + # ints that are known to be size-like and may have 0/1 entries that we + # must not specialize on. + self.force_unspec_int_unbacked_size_like = False + # See note [Tensor Fakification and Symbol Caching] + self.tensor_to_context = WeakTensorKeyDictionary() + + # If this true, Aot Autograd will return output Fake Tensors with appropriate + # meta on the first invocation + # see note: [Returning Fake Tensors on First AOT Autograd Call] + self.fakify_first_call = False + self.hop_dispatch_set_cache = HopDispatchSetCache() + # list of code objects for inlined functions + self.traced_code: list[CodeType] = [] + self.cudagraph_annotation: Any = None + + def clear(self) -> None: + # Look at the note in output_graph.py in function `save_global_state` + # for the context on clearing global context. + self.global_context.global_state = {} + self.previously_inlined_functions.clear() + self.previously_cleaned_instructions.clear() + self.inlined_code_cache.clear() + + @staticmethod + @contextmanager + def patch(**kwargs: Any) -> Generator[None, None, None]: + prior = {} + ctx = TracingContext.get() + + for key in kwargs: + # KeyError on invalid entry + prior[key] = getattr(ctx, key) + for key, val in kwargs.items(): + setattr(ctx, key, val) + try: + yield + finally: + for key, val in prior.items(): + setattr(ctx, key, val) + + @staticmethod + def extract_stack() -> traceback.StackSummary: + self = TracingContext.try_get() + if self is None: + return traceback.StackSummary() + stack = self.frame_summary_stack + if self.loc_in_frame is not None: + stack = stack + [self._populate_loc_in_frame_summary()] + return traceback.StackSummary.from_list(stack) + + def _populate_loc_in_frame_summary(self) -> traceback.FrameSummary: + if self.loc_in_frame is None: + raise AssertionError("loc_in_frame must not be None") + filename, lineno, frame_name = self.loc_in_frame + # colno/end_colno kwargs were added to FrameSummary in 3.11 + kwargs: dict[str, Any] = {} + if sys.version_info >= (3, 11) and self.loc_in_frame_positions is not None: + kwargs["colno"] = self.loc_in_frame_positions.col_offset + kwargs["end_colno"] = self.loc_in_frame_positions.end_col_offset + return traceback.FrameSummary( + filename, + lineno, + frame_name, + lookup_line=False, + **kwargs, + ) + + # Call this when you want to call into some code that isn't necessarily + # associated with the current frame state + @staticmethod + @contextlib.contextmanager + def clear_frame() -> Generator[None, None, None]: + tc = TracingContext.get() + with ( + unittest.mock.patch.object(tc, "frame_summary_stack", []), + unittest.mock.patch.object(tc, "loc_in_frame", None), + unittest.mock.patch.object(tc, "loc_in_frame_positions", None), + ): + try: + yield + except Exception as e: + # Prevent real_stack from getting attached + # + # The invariant is that if an Exception as real_stack, we've + # appropriately attached a user stack and we no longer need to + # attach anything. Because we cannot conveniently interpose + # when an exception is thrown, we instead interpose everywhere + # we set what the user stack is set (using the context + # manager). However, our compiler stack does "tail calls" + # (when it calls into user compiler), at which point the + # parent exception frames would incorrectly attach an + # incorrect frame. + # + # However, if, somehow, someone raised an exception with this + # scope that had a stack (for example, because they are + # restoring the user stack state appropriately as they process + # node by node), we should respect it. Thus, we cannot + # unconditionally set None. + if not hasattr(e, "real_stack"): + e.real_stack = None # type: ignore[attr-defined] + raise + + @staticmethod + @contextlib.contextmanager + def current_frame( + frame_summary: traceback.FrameSummary | None, + ) -> Generator[None, None, None]: + # frame_summary can be None to solely take advantage of real_stack + # attachment to thrown exceptions + tc = TracingContext.get() + if frame_summary is not None: + tc.frame_summary_stack.append(frame_summary) + old = tc.loc_in_frame + old_positions = tc.loc_in_frame_positions + tc.loc_in_frame = None + tc.loc_in_frame_positions = None + try: + yield + except Exception as e: + if not hasattr(e, "real_stack"): + e.real_stack = tc.extract_stack() # type: ignore[attr-defined] + raise + finally: + if frame_summary is not None: + tc.frame_summary_stack.pop() + tc.loc_in_frame = old + tc.loc_in_frame_positions = old_positions + + @staticmethod + @contextlib.contextmanager + def report_output_strides() -> Generator[ + list[tuple[int, ...] | None] | None, None, None + ]: + tc = TracingContext.try_get() + if tc is None: + yield None + return + old_output_strides = tc.output_strides + tc.output_strides = [] + try: + yield tc.output_strides + finally: + tc.output_strides = old_output_strides + + @staticmethod + def set_current_loc( + filename: str, + lineno: int, + frame_name: str, + positions: dis.Positions | None = None, + ) -> None: + # Save the current location in the frame. Lazily generate the + # framesummary. + tc = TracingContext.get() + tc.loc_in_frame = (filename, lineno, frame_name) + tc.loc_in_frame_positions = positions + + @staticmethod + def get_traced_code() -> list[CodeType] | None: + tc = TracingContext.try_get() + if tc is None: + return None + return tc.traced_code + + +@contextmanager +def compile_context( + context: CompileContext | None, +) -> Generator[CompileContext | None, None, None]: + old_context = getattr(_TLS, "compile_context", None) + _TLS.compile_context = context + try: + yield context + finally: + _TLS.compile_context = old_context + + +@contextmanager +def tracing( + context: TracingContext | None, +) -> Generator[TracingContext | None, None, None]: + """ + This function installs the passed in tracing context as a dynamic scoped + global variable. + + Calls to TracingContext.get() while not under a `with tracing()` context + will return None. + """ + old_context = getattr(_TLS, "tracing_context", None) + _TLS.tracing_context = context + try: + yield context + except Exception as e: + if not hasattr(e, "real_stack") and context is not None: + e.real_stack = context.extract_stack() # type: ignore[attr-defined] + raise + finally: + if ( + context is not None + and context.fake_mode is not None + and context.fake_mode.shape_env is not None + ): + context.fake_mode.shape_env.cleanup() + _TLS.tracing_context = old_context + + +@overload +def dataclass_with_cached_hash(cls: type[T], **kwargs: Any) -> type[T]: ... + + +@overload +def dataclass_with_cached_hash( + cls: None = None, **kwargs: Any +) -> Callable[[type[T]], type[T]]: ... + + +@dataclass_transform() +def dataclass_with_cached_hash( + cls: type[T] | None = None, **kwargs: Any +) -> type[T] | Callable[[type[T]], type[T]]: + def wrap(cls_inner: type[T]) -> type[T]: + new_cls = dataclasses.dataclass(cls_inner, **kwargs) + old_hash = cls_inner.__hash__ + + def __hash__(self) -> int: + if not hasattr(self, "_hash"): + object.__setattr__(self, "_hash", old_hash(self)) + return self._hash + + def __reduce__(self): + # Exclude _hash from pickling to ensure deterministic cache keys. + # The _hash is a cached value that can be nondeterministically computed + # (e.g., based on id() of objects), so it should not affect pickling. + fields = dataclasses.fields(self) + field_values = tuple(getattr(self, f.name) for f in fields if f.init) + return (self.__class__, field_values) + + new_cls.__hash__ = __hash__ + new_cls.__reduce__ = __reduce__ + return new_cls # type: ignore[return-value] + + if cls is None: + return wrap + + return wrap(cls) + + +# Subclasses can be found in torch/_dynamo/source.py +# TODO(voz): Consider a toplevel torch/_source.py +@dataclass_with_cached_hash(frozen=True) +class Source: + def is_dict_key(self) -> bool: + return False + + def is_ephemeral(self) -> bool: + return False + + def reconstruct(self, codegen: PyCodegen) -> None: + raise NotImplementedError + + def reconstruct_pycode(self, codegen: PyCodegen) -> str: + """ + Reconstructs the source into a string of Python code. This method should + be eventually implemented for all subclasses of Source to achieve full + coverage of python wrapper code generation. + """ + raise NotImplementedError + + @functools.cached_property + def guard_source(self) -> GuardSource: + raise NotImplementedError + + @property + def _name_template(self) -> str: + """ + A template for the name of the source. Used to prevent code duplication between + `name` and `get_value`. + + For non-ChainedSources, `name` and `get_value` use the returned string directly. + + For ChainedSources, `name` and `get_value` expect the return to be a format string + with `{0}` present - `name` and `get_value` will apply different values to this function's + returned format string. + """ + raise NotImplementedError + + @functools.cached_property + def name(self) -> str: + return self._name_template + + def get_value( + self, + globals: dict[str, Any], + locals: dict[str, Any], + cache: dict[Source, Any], + ) -> Any: + if self in cache: + return cache[self] + value = eval(self._name_template, globals, locals) + cache[self] = value + return value + + def make_guard(self, fn: Callable[..., Any]) -> Guard: + if self.guard_source is GuardSource.CONSTANT: + raise NotImplementedError + return Guard(self, fn) + + def is_specialized_nn_module(self) -> bool: + return self.guard_source.is_specialized_nn_module() + + def subguards_allowed(self) -> bool: + """True if you can guard on attributes of this""" + return self.guard_source != GuardSource.SYNTHETIC_LOCAL + + def clone(self, transform_fn: Callable[[Source], Source] | None = None) -> Source: + # Frozen dataclass, so returning self is effectively a clone. + # Subclasses with mutable state should override. + if transform_fn is not None: + return transform_fn(self) + return self + + +# Subclasses can be found in torch/_dynamo/source.py +@dataclass_with_cached_hash(frozen=True) +class ChainedSource(Source): + base: Source + + def is_dict_key(self) -> bool: + # Recurse until you either hit a ConstDictKey or a Source + return self.base.is_dict_key() + + def is_ephemeral(self) -> bool: + return self.base.is_ephemeral() + + @functools.cached_property + def guard_source(self) -> GuardSource: + return self.base.guard_source + + def get_base(self) -> Source: + current: Source = self + while isinstance(current, ChainedSource): + current = current.base + return current + + @functools.cached_property + def name(self) -> str: + return self._name_template.format(self.base.name) + + def get_value( + self, + globals: dict[str, Any], + locals: dict[str, Any], + cache: dict[Source, Any], + ) -> Any: + if self in cache: + return cache[self] + tmpvar = "tmp" + counter = 0 + while tmpvar in locals: + tmpvar = f"tmp{counter}" + counter += 1 + locals[tmpvar] = self.base.get_value(globals, locals, cache) + value = eval(self._name_template.format(tmpvar), globals, locals) + del locals[tmpvar] + cache[self] = value + return value + + def clone(self, transform_fn: Callable[[Source], Source] | None = None) -> Source: + cloned_fields: dict[str, Any] = {"base": self.base.clone(transform_fn)} + for f in dataclasses.fields(self): + if f.name == "base": + continue + val = getattr(self, f.name) + if isinstance(val, Source): + cloned_fields[f.name] = val.clone(transform_fn) + result = dataclasses.replace(self, **cloned_fields) + if transform_fn is not None: + result = transform_fn(result) + return result + + +def detect_fake_mode(inputs: Any = None) -> FakeTensorMode | None: + """ + Attempts to "detect" what the current fake mode is. If there is one ambiently + available from TracingContext, we preferentially use that. Otherwise, we + heuristically detect the fake mode via the following sources, in order of + priority: + + - Currently active fake mode on stack + - Fake mode associated with passed in tensors (inputs does not + have to be flattened) + """ + from torch._subclasses.fake_tensor import ( + FakeTensor, + FakeTensorMode, + get_plain_tensors, + is_fake_tensor, + maybe_get_fake_mode, + ) + + # If TracingContext has a fake_mode, use it authoritatively. + # This is the case when Dynamo is driving compilation - any fake tensors + # from other modes in the inputs will be refakified by the caller. + if context := TracingContext.try_get(): + fake_mode = context.fake_mode + if fake_mode is not None: + return fake_mode + + fake_modes = [] + + from torch.utils._python_dispatch import _get_current_dispatch_mode_stack + + for i, m in enumerate(reversed(_get_current_dispatch_mode_stack())): + if isinstance(m, FakeTensorMode): + fake_modes.append((m, "active fake mode", i)) + + flat_inputs = pytree.tree_leaves(inputs) + for i, flat_input in enumerate(flat_inputs): + if is_fake_tensor(flat_input): + fake_modes.append((maybe_get_fake_mode(flat_input), "fake tensor input", i)) + if is_traceable_wrapper_subclass(flat_input): + out: list[torch.Tensor | int | torch.SymInt] = [] + get_plain_tensors(flat_input, out=out) # type: ignore[arg-type] + fake_tensors: list[FakeTensor] = [ + x + for x in out + if isinstance(x, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR + ] + fake_modes.extend( + [ + (maybe_get_fake_mode(tensor), f"subclass input {i}", ix) + for ix, tensor in enumerate(fake_tensors) + ] + ) + + if fake_modes: + fake_mode, desc1, i1 = fake_modes[0] + for m, desc2, i2 in fake_modes[1:]: + if fake_mode is not m: + raise AssertionError( + f"fake mode ({fake_mode}) from {desc1} {i1} doesn't match mode ({m}) from {desc2} {i2}\n\n" + f"fake mode from {desc1} {i1} allocated at:\n{fake_mode.stack}\n" + f"fake mode from {desc2} {i2} allocated at:\n{m.stack}" + ) + + return fake_mode + else: + return None + + +def active_fake_mode() -> FakeTensorMode | None: + """ + Inspects the dispatch mode stack for an active fake mode and returns it. + Returns None if no fake mode is active. + """ + from torch._subclasses.fake_tensor import FakeTensorMode + from torch.utils._python_dispatch import _get_current_dispatch_mode_stack + + for _, m in enumerate(reversed(_get_current_dispatch_mode_stack())): + if isinstance(m, FakeTensorMode): + return m + + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__init__.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea54032864d872aa9ebb815d9abd24b2bd7a1a93 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__init__.py @@ -0,0 +1,91 @@ +from torch._higher_order_ops._invoke_quant import ( + invoke_quant, + invoke_quant_packed, + InvokeQuant, +) +from torch._higher_order_ops.aoti_call_delegate import aoti_call_delegate +from torch._higher_order_ops.associative_scan import associative_scan +from torch._higher_order_ops.auto_functionalize import ( + auto_functionalized, + auto_functionalized_v2, +) +from torch._higher_order_ops.base_hop import BaseHOP +from torch._higher_order_ops.cond import cond +from torch._higher_order_ops.effects import with_effects +from torch._higher_order_ops.executorch_call_delegate import executorch_call_delegate +from torch._higher_order_ops.flat_apply import flat_apply +from torch._higher_order_ops.flex_attention import ( + flex_attention, + flex_attention_backward, +) +from torch._higher_order_ops.flex_gemm import flex_gemm +from torch._higher_order_ops.foreach_map import _foreach_map, foreach_map +from torch._higher_order_ops.hints_wrap import hints_wrapper +from torch._higher_order_ops.inline_asm_elementwise import inline_asm_elementwise +from torch._higher_order_ops.invoke_leaf_function import invoke_leaf_function +from torch._higher_order_ops.invoke_subgraph import invoke_subgraph +from torch._higher_order_ops.local_map import local_map_hop +from torch._higher_order_ops.map import map +from torch._higher_order_ops.out_dtype import out_dtype +from torch._higher_order_ops.print import print +from torch._higher_order_ops.run_const_graph import run_const_graph +from torch._higher_order_ops.scan import scan +from torch._higher_order_ops.strict_mode import strict_mode +from torch._higher_order_ops.switch import switch +from torch._higher_order_ops.torchbind import call_torchbind +from torch._higher_order_ops.while_loop import ( + while_loop, + while_loop_stack_output_op as while_loop_stack_output, +) +from torch._higher_order_ops.wrap import ( + dynamo_bypassing_wrapper, + inductor_compiled_code, + tag_activation_checkpoint, + wrap_activation_checkpoint, + wrap_with_autocast, + wrap_with_set_grad_enabled, +) + + +__all__ = [ + "cond", + "switch", + "while_loop", + "invoke_subgraph", + "scan", + "map", + "flex_attention", + "flex_attention_backward", + "hints_wrapper", + "BaseHOP", + "flat_apply", + "foreach_map", + "_foreach_map", + "flex_gemm", + "with_effects", + "tag_activation_checkpoint", + "auto_functionalized", + "auto_functionalized_v2", + "associative_scan", + "out_dtype", + "executorch_call_delegate", + "call_torchbind", + "run_const_graph", + "InvokeQuant", + "invoke_leaf_function", + "invoke_quant", + "invoke_quant_packed", + "wrap_with_set_grad_enabled", + "wrap_with_autocast", + "wrap_activation_checkpoint", + "dynamo_bypassing_wrapper", + "strict_mode", + "aoti_call_delegate", + "map", + "while_loop_stack_output", + "local_map_hop", + "print", + "inductor_compiled_code", + "inline_asm_elementwise", + "register_hook", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd3623e46bcab59ca58860ca376a3a8fbfbeb8d4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8411c8ffa5248d490dd0e33b7eb1f8a365454f42 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad5dcc63d409013601304aeca7abad2c315e2ac2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/associative_scan.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/associative_scan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40257a4db79aae24d059709c24d2f884b58d19fa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/associative_scan.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..477e47d85877d7fc2671bc5683b2e2af9f365bf0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/base_hop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/base_hop.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3107c2b55996b4bfe6aed1b048eca39d9234e565 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/base_hop.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cond.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cond.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60c73e959101670dcb569272bced26e038db8256 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cond.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cudagraph_conditional_nodes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cudagraph_conditional_nodes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68f49ce4fba92da14bb5e1d052d75faf542e046c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cudagraph_conditional_nodes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/effects.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/effects.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1c7bba30ebbcdf4943934ea2f4ecf9d8b0da666 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/effects.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50386c56f76aac05c80254dcf6e3e627cb7e1b29 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flat_apply.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flat_apply.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baf9c89fc1aca1a79309a4261d7daa14035119e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flat_apply.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_attention.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b2650530e2b350d700ab81c7ac1f6ceb5f8e0d0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_attention.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8320701a0baae4eeaddbd4393bfe1804c8bbf70 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/foreach_map.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/foreach_map.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7a6b47852b3585a7403ddc4463c6c57527622f9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/foreach_map.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/hints_wrap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/hints_wrap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..130ebb82ec2d6ed607b2aae1ceb17182fd363693 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/hints_wrap.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/inline_asm_elementwise.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/inline_asm_elementwise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8abb125e930026a620d216549024a6c3d512476e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/inline_asm_elementwise.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_leaf_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_leaf_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08682594cc0e1211576543a6763f9c2e743d6a74 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_leaf_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd8fece28d69b4d1c93438572689d802099735ab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/local_map.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/local_map.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1647ceeb0b5837e98da8f8ac86187080f5fd9fb9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/local_map.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/map.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/map.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1df8b6d5f497a16cbdbe9de01f21d0e432812f55 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/map.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/out_dtype.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/out_dtype.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e6290a74cead3c122717f5cae3b0db92f555249 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/out_dtype.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/partitioner.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/partitioner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07675017cb51abae31c852864d78d5e431f5d8d0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/partitioner.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/print.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/print.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a31bce3e25111adb82140e9d8a9dc50fc34c47b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/print.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/register_hook.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/register_hook.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cc2d86ad4791ebcafddbaf6ccc1dfd914d3bc9b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/register_hook.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/run_const_graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/run_const_graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53a6205dc583dd90f298b34a87d3a97dfe1d08d6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/run_const_graph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/scan.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/scan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4feca4e3856170116670241d9614c55663299320 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/scan.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/schema.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c54cd5cb82a592ab6dc5a3484202c48b88cc7a8f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/schema.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/strict_mode.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/strict_mode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07a5ec8a7eee1efb4296362e47b7b08a0f9c45cd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/strict_mode.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/switch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/switch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60c9d82a7287e3b86567118902bad47c92e2c2b2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/switch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/torchbind.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/torchbind.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..694d87ff178a98987c74e6111bb975b96f53dd44 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/torchbind.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cb28f87f613032691930eb03cf8ed3ca652c373 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:033b54c9fbf4a9cd1d4d8a86af580f0fa486e638cd804d6c95e3e4fa04d4e6f7 +size 100564 diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4179cfbff8358e2d5f33c8a9eec0dc55d70cc3c4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/while_loop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/while_loop.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5677077a1299a245ab7cb79912d5acbb02b065d9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/while_loop.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/wrap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/wrap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b3bd39b83b1f2eb03d36bf5fde40f6a01beb6c0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/wrap.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/_invoke_quant.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/_invoke_quant.py new file mode 100644 index 0000000000000000000000000000000000000000..4e125e68fa4f4e0b19af801301d9d04e7d1d0e41 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/_invoke_quant.py @@ -0,0 +1,61 @@ +# mypy: allow-untyped-defs +# need to fix prim_hop_base type annotations first + +import dataclasses + +import torch +from torch._higher_order_ops.base_hop import BaseHOP, FunctionWithNoFreeVars + + +class InvokeQuantTracer(BaseHOP): + def __init__(self) -> None: + super().__init__("invoke_quant_packed") + + def __call__(self, subgraph, *operands, scheme=None, quant_options=None): + subgraph = FunctionWithNoFreeVars(subgraph) + return super().__call__( + subgraph, *operands, scheme=scheme, quant_options=quant_options + ) + + +invoke_quant_packed = InvokeQuantTracer() + + +class InvokeQuantUnpacked(BaseHOP): + def __init__(self) -> None: + super().__init__("invoke_quant") + + +invoke_quant = InvokeQuantUnpacked() + + +@dataclasses.dataclass(frozen=True, repr=True) +class InvokeQuant: + """ + Invoke a quantization function that will be preserved as a single operator. Preservation + as a single operator aids in pattern matching and custom lowerings. + + The operation appears as: + torch.ops.higher_order.invoke_quant(subgraph, *args, scheme=scheme) + + Args: + codegen_low_precision: Use observed subgraph dtypes for codegen instead of + upcasting to fp32. Can improve performance for prologue fusion but + requires careful testing of numerics. + """ + + codegen_low_precision: bool = True + + def __call__( + self, + *args, + scheme: str | None = None, + **kwargs, + ): + if not torch.compiler.is_compiling(): + return args[0](*args[1:], **kwargs) + + if scheme is not None: + kwargs["scheme"] = scheme + + return invoke_quant_packed(*args, **kwargs, quant_options=self) # type: ignore[call-arg] diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/aoti_call_delegate.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/aoti_call_delegate.py new file mode 100644 index 0000000000000000000000000000000000000000..87f34284047f039f79ea7f3c3df05525790d8fe6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/aoti_call_delegate.py @@ -0,0 +1,164 @@ +# mypy: allow-untyped-defs + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +import torch +import torch.utils._pytree as pytree +from torch._higher_order_ops.utils import register_fake +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import is_fake_tensor +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +AOTI_LOWERED_MODULE = "AOTInductorEPModule/AOTInductorRunnerWrapper" + + +class AOTICallDelegate(HigherOrderOperator): + """aoti_call_delegate is a HOP for calling AOTInductor lowered submodule in ExportedProgram. + + It has the following signature: + aoti_call_delegate( + lowered_module: Union[AOTInductorEPModule, AOTInductorRunnerWrapper] + original_gm:fx.GraphModule, + weight_args: List[Tensor], + input_args: List[Tensor], + ) -> outputs: List[Tensor] + + where, + - lowered_module is the AOTInductor lowered submodule, backed by compiled .so file, supporting real tensor inputs + - original_gm is the stateless version of the original GraphModule before lowering, allowing FakeTensor propagation + - weight_args is the list of weights in original GraphModule, including parameters and buffers + - input_args is the list of flatten inputs + """ + + def __init__(self) -> None: + super().__init__("aoti_call_delegate") + + def __call__( + self, + lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type] + original_gm: torch.fx.GraphModule, + weight_args: list[torch.Tensor], + input_args: list[torch.Tensor], + ) -> list[torch.Tensor]: + # pyrefly: ignore [missing-attribute] + return super().__call__(lowered_module, original_gm, weight_args, input_args) + + +aoti_call_delegate = AOTICallDelegate() +aoti_call_delegate.fallthrough(torch._C.DispatchKey.PythonDispatcher) +aoti_call_delegate.fallthrough(torch._C.DispatchKey.PythonTLSSnapshot) +aoti_call_delegate.fallthrough(torch._C.DispatchKey.ADInplaceOrView) +aoti_call_delegate.fallthrough(torch._C.DispatchKey.AutocastCPU) + + +@aoti_call_delegate.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd) +def call_delegate_cpu( + lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type] + original_gm: torch.fx.GraphModule, + weight_args: list[torch.Tensor], + input_args: list[torch.Tensor], +) -> list[torch.Tensor]: + # FX creates this immutable_dict/list concept. Get rid of this. + map_types: dict[type, type] = { + torch.fx.immutable_collections.immutable_dict: dict, + torch.fx.immutable_collections.immutable_list: list, + } + new_args = pytree.tree_map_only( + tuple(map_types.keys()), + lambda a: map_types[type(a)](a), + weight_args + input_args, + lambda a: isinstance(a, tuple(map_types.keys())), + ) + has_fake_args = any(is_fake_tensor(arg) for arg in new_args) + if has_fake_args: + # use stateless original_gm for tracing with fake tensors + fake_out = original_gm(*new_args) + return fake_out + else: + # use AOTI Runner for real tensors + new_input_args = new_args[len(weight_args) :] + if type(lowered_module).__name__ == "AOTInductorRunnerWrapper": + return lowered_module(*new_input_args) # type: ignore[misc] + elif type(lowered_module).__name__ == "AOTInductorEPModule": + return lowered_module(new_input_args) # type: ignore[misc] + else: + raise RuntimeError( + f"Unexpected lowered_module type: {type(lowered_module)}." + ) + + +def trace_aoti_call_delegate( + proxy_mode, func_overload, lowered_module, original_gm, weight_args, input_args +): + proxy_mode.tracer.root.register_module("lowered_module", lowered_module) + proxy_mode.tracer.root.register_module("original_gm", original_gm) + + node_args = (lowered_module, original_gm, weight_args, input_args) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {}, name="aoti_call_delegate" + ) + with disable_proxy_modes_tracing(): + out = call_delegate_cpu(lowered_module, original_gm, weight_args, input_args) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@aoti_call_delegate.py_impl(ProxyTorchDispatchMode) +def call_delegate_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, + lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type] + original_gm: torch.fx.GraphModule, + weight_args: list[torch.Tensor], + input_args: list[torch.Tensor], +): + res = trace_aoti_call_delegate( + mode, aoti_call_delegate, lowered_module, original_gm, weight_args, input_args + ) + return res + + +@register_fake(aoti_call_delegate, skip_cache=True) +def call_delegate_fake_tensor_mode( + lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type] + original_gm: torch.fx.GraphModule, + weight_args: list[torch.Tensor], + input_args: list[torch.Tensor], +) -> list[torch.Tensor]: + return call_delegate_cpu(lowered_module, original_gm, weight_args, input_args) + + +@aoti_call_delegate.py_functionalize_impl +def call_delegate_functionalize( + ctx, + lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type] + original_gm: torch.fx.GraphModule, + weight_args: list[torch.Tensor], + input_args: list[torch.Tensor], +): + unwrapped_weight_args = tuple( + ctx.unwrap_tensors(weight_arg) for weight_arg in weight_args + ) + unwrapped_input_args = tuple( + ctx.unwrap_tensors(input_arg) for input_arg in input_args + ) + with ctx.redispatch_to_next(): + res = aoti_call_delegate( + lowered_module, + original_gm, + unwrapped_weight_args, # type: ignore[arg-type] + unwrapped_input_args, # type: ignore[arg-type] + ) + return ctx.wrap_tensors(res) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/associative_scan.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/associative_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..79576095ef2a3531a6f0e037d1a36832f3b0df94 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/associative_scan.py @@ -0,0 +1,928 @@ +# mypy: allow-untyped-defs +import functools +import itertools +from collections.abc import Callable +from typing import Any + +import torch +import torch._prims_common as utils +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + _maybe_compile_and_run_fn, + _maybe_run_with_interpreter, + check_input_alias_and_mutation_return_outputs, + check_meta_consistency, + create_bw_fn, + first_slice_copy, + first_slice_copy_with_grad, + materialize_as_graph, + reenter_make_fx, + register_fake, + save_values_for_backward, + saved_values, + split_into_chunks, + unique_graph_id, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +aten = torch._ops.ops.aten + + +def wrap_combine_fn_flat(*args, combine_fn, spec, num_leaves): + if len(args) != 2 * num_leaves: + raise AssertionError( + f"Combine_fn received wrong number of arguments, expected {2 * num_leaves}, but got {len(args)}" + ) + lhs = pytree.tree_unflatten(args[:num_leaves], spec) + rhs = pytree.tree_unflatten(args[num_leaves:], spec) + return combine_fn(lhs, rhs) + + +def _interleave(a, b, dim=0): + # https://stackoverflow.com/questions/60869537/how-can-i-interleave-5-pytorch-tensors + if b_trunc := (a.shape[dim] == b.shape[dim] + 1): + pad = ( + [0] * ((b.ndim - dim - 1) * 2 + 1) + + [1] + + [0] * (b.ndim * 2 - ((b.ndim - dim - 1) * 2 + 2)) + ) + b = torch.nn.functional.pad(b, pad) + + stacked = torch.stack([a, b], dim=dim + 1) + interleaved = torch.flatten(stacked, start_dim=dim, end_dim=dim + 1) + # pyrefly: ignore [unbound-name] + if b_trunc: + # TODO: find torch alternative for slice_along dim for torch.jit.script to work + interleaved = aten.slice(interleaved, dim, 0, b.shape[dim] + a.shape[dim] - 1) + return interleaved + + +def safe_map(f, *args): + args = list(map(list, args)) + n = len(args[0]) + for arg in args[1:]: + if len(arg) != n: + raise ValueError("length mismatch: {list(map(len, args))}") + + def nf(a): + return f(*a) + + return list(map(nf, zip(*args))) + + +class AssociativeScanOp(HigherOrderOperator): + def __init__(self): + super().__init__("associative_scan") + + def __call__(self, combine_fn, xs, additional_inputs): + # There is currently an issue that the ScanOp is sometimes called with + # the additional_inputs being a list. See https://github.com/pytorch/pytorch/issues/145785 + # Once this issue is resolved, the assertion should only allow tuples + # and the tuple cast should be removed + if not isinstance(additional_inputs, (tuple, list)): + raise AssertionError( + f"additional_inputs must be a tuple or list, got {type(additional_inputs)}" + ) + additional_inputs = ( + tuple(additional_inputs) + if isinstance(additional_inputs, list) + else additional_inputs + ) + validate_subgraph_args_types(additional_inputs) + # pyrefly: ignore [missing-attribute] + return super().__call__(combine_fn, xs, additional_inputs) + + # pyrefly: ignore [bad-override] + def gen_schema(self, combine_fn, xs, additional_inputs): + from torch._higher_order_ops.schema import HopSchemaGenerator + + # For associative scan, we need two copies of xs for the combine function + # The combine function takes two elements and returns one element + xs_slice1 = [first_slice_copy(x) for x in xs] + xs_slice2 = [first_slice_copy(x) for x in xs] + all_inputs = tuple(xs_slice1 + xs_slice2 + list(additional_inputs)) + + combine_gm: torch.fx.GraphModule = materialize_as_graph(combine_fn, all_inputs) + ( + _, + _, + _, + mutated_inputs, + outputs, + ) = check_input_alias_and_mutation_return_outputs(combine_gm) + if len(mutated_inputs) > 0: + raise RuntimeError( + "For associative_scan, combine_fn cannot have in-place mutations but found " + f"{mutated_inputs}-th inputs are mutated." + ) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("combine_fn", combine_gm) + + for idx, x in enumerate(xs): + schema_gen.add_arg(f"xs{idx}", x) + + for idx, arg in enumerate(additional_inputs): + schema_gen.add_arg( + f"additional_input{idx}", + arg, + ) + + for out in outputs: + schema_gen.add_output(out) + + schema_gen.add_schema_tree_spec(combine_fn, xs, additional_inputs) + return schema_gen.gen_schema() + + +associative_scan_op = AssociativeScanOp() + + +def associative_scan( + combine_fn: Callable[[pytree.PyTree, pytree.PyTree], pytree.PyTree], + xs: pytree.PyTree, + dim: int, + reverse: bool = False, + combine_mode: str = "pointwise", +) -> torch.Tensor: + r""" + Performs an inclusive scan with an associative combine function. + + .. warning:: + + ``torch.associative_scan`` is a prototype feature in PyTorch. It currently + does not support autograd and you may run into miscompiles. + Read more about feature classification at: + https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + With ``combine_mode="pointwise"``, efficient execution requires runtime code + generation via ``torch.compile``, and codegen is only supported on backends + with scan support (currently CUDA and XPU). On other devices the operator + still runs eagerly via the generic fallback. + + Args: + combine_fn (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``, + or if input is a pytree ``(pytree, pytree) -> pytree``. + This function must be pure, i.e., no lifted arguments are supported at the moment, + satisfy the associative property and have no side-effects. + xs (torch.Tensor): The input tensor, or nested pytree of tensors. + dim (int): the dimension to scan over + reverse (bool): A boolean stating if the scan should be reversed with respect to ``dim``, default ``False``. + combine_mode (str): A string indicating whether the ``combine_fn`` is ``pointwise`` or ``generic``, default ``pointwise``. + If ``combine_mode=pointwise``, ``combine_fn`` must be pure and may only contain pointwise + operations; under ``torch.compile`` ``xs`` must be on a backend with scan codegen support + (CUDA or XPU), otherwise the generic fallback is used. + In all other cases ``combine_mode=generic`` should be used. + Note: ``combine_mode=pointwise`` is more efficient than ``combine_mode=generic``. + + Returns: + A pytree of the same structure and shape as ``xs``. If the scan dimension has size 0, + the output mirrors the (empty) input unchanged. The gradient with respect to ``xs`` + is also empty (size 0 along ``dim``), since there are no elements to differentiate through. + + Example:: + + def add(x: torch.Tensor, y: torch.Tensor): + return x + y + + + cumsum = associative_scan(add, x, dim) + + """ + # TODO: Support lifted arguments in inductor for associative_scan + # TODO: Support autograd for cases with lifted arguments for combine_mode=pointwise + + # The reason we flatten xs before calling into dynamo is that + # we want to create a consistent input ordering for combine_fn + # and we also want to the input ordering matches the output ordering. + leaves_xs_orig, spec_xs = pytree.tree_flatten(xs) + + def _validate_input(cfn, lxs, d, r, cm): + # Basic arguments check + if not callable(cfn): + raise ValueError(f"Combine_fn must be a callable, but got {cfn}") + if not isinstance(d, int): + raise ValueError("Dim must be an int, but got " + str(type(d))) + if not isinstance(r, bool): + raise RuntimeError("Reverse must be a bool, but got " + str(type(r))) + if cm not in ["pointwise", "generic"]: + raise ValueError( + f"Combine_mode must either 'pointwise' or 'generic', but got {cm}" + ) + + # Checks for xs + if len(lxs) == 0: + raise ValueError("Expected at least 1 xs leaf") + if any(not isinstance(x, torch.Tensor) for x in lxs): + raise ValueError("xs leaves must be a Tensor") + if any(x.is_sparse for x in lxs): + raise ValueError( + "xs leaves must dense Tensors, consider using `to_dense()`" + ) + if any(x.ndim <= d for x in lxs): + raise ValueError("All xs leaves must have at least 'dim + 1' dimensions") + + ndim = leaves_xs_orig[0].ndim + dim = utils.canonicalize_dim(ndim, dim) + + _validate_input(combine_fn, leaves_xs_orig, dim, reverse, combine_mode) + + # Move scan dim to 0 and always perform scan on dim 0 + leaves_xs = [torch.movedim(elem, dim, 0) for elem in leaves_xs_orig] + + if reverse: + leaves_xs = [torch.flip(elem, [0]) for elem in leaves_xs] + + if combine_mode == "generic": + # The generic_associative_scan implementation calls the combine_fn with a `batch` along the scan dimension + # For example, consider: + # def add(x: torch.Tensor, y: torch.Tensor): + # return x + y + # leaves = torch.tensor([[0.0, 1.0, 2.0, 3.0] + # [0.0, 1.0, 2.0, 3.0]]) + # which has shape 2 x 4; + # dim = 1; + # In the first iteration of `_scan` the combine_fn gets invoked with + # combine_fn([torch.tensor([[0.0, 2.0], + # [0.0, 2.0]])], + # [torch.tensor([[1.0, 3.0], + # [1.0, 3.0]])]) + # The arguments are of shape 2 x 2, but can be evaluated in parallel along the scan dimension. + combine_fn = functools.partial( + wrap_combine_fn_flat, + combine_fn=torch.vmap( + combine_fn, + in_dims=( + pytree.tree_unflatten([0] * len(leaves_xs), spec_xs), + pytree.tree_unflatten([0] * len(leaves_xs), spec_xs), + ), + out_dims=0, + ), + spec=spec_xs, + num_leaves=len(leaves_xs), + ) + out = generic_associative_scan(combine_fn, leaves_xs, additional_inputs=()) + out = pytree.tree_unflatten(out, spec_xs) + else: + combine_fn = functools.partial( + wrap_combine_fn_flat, + combine_fn=combine_fn, + spec=spec_xs, + num_leaves=len(leaves_xs), + ) + + def run_flattened_associative_scan(combine_fn, leaves_xs): + return associative_scan_op(combine_fn, leaves_xs, additional_inputs=()) + + out = _maybe_compile_and_run_fn( + run_flattened_associative_scan, + combine_fn, + leaves_xs, + ) + + if reverse: + out = pytree.tree_map(lambda elem: elem.flip([0]), out) + + out = pytree.tree_map(lambda elem: torch.movedim(elem, 0, dim), out) + + return out + + +def generic_associative_scan(operator, leaves, dim=0, additional_inputs=()): + r""" + This function performs the associative_scan operation. + The algorithm works by recursively collecting neighbours of ``leaves`` and subsequently + applying the ``operator`` on all pairs in parallel along ``dim``. + The results of the recursive calls are later combined. + + Args: + operator (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``, + or if input is a pytree ``(pytree, pytree) -> pytree``. + This function must be pure, pointwise, and satisfy the associative property. + leaves (torch.Tensor): A list of torch.Tensors converted from the pytree of + ``xs`` provided to ``associative_scan``. + All inputs are expected to have the same shape. + dim (int): the dimension to scan over + additional_inputs (Tuple of tensors): A tuple of lifted parameters from the global scope. + This parameter will be populated internally. + + Example:: + + def add(x: torch.Tensor, y: torch.Tensor): + return x + y + + leaves = torch.tensor([0.0, 1.0, 2.0, 3.0]) + + First iteration of _scan -> + # odd_elems -> apply operator on all neighbours + # odd_elems = operator([torch.tensor([0.0, 2.0])], + # [torch.tensor([1.0, 3.0])]) + odd_elems = torch.tensor([1.0, 5.0]) + Second iteration of _scan -> + # odd_elems = operator([torch.tensor([1.0])], + # [torch.tensor([5.0])]) + odd_elems = torch.tensor([6.0]) + # even_elems -> apply operator on all odd_elems and + # every second element of ``elems``, starting from the second element. + # even_elems is expanded with the first element of ``elems`` + even_elems = [1.0] + # Merges odd_elems and even_elems + res = torch.tensor([1.0, 6.0]) + # even_elems -> apply operator on all odd_elems and + # every second element of ``elems``, starting from the second element. + # even_elems is expanded with the first element of ``elems`` + even_elems = [0.0, 3.0] + # Merges odd_elems and even_elems + res = torch.tensor([0.0, 1.0, 3.0, 6.0]) + + """ + + def call_operator(*args): + return pytree.tree_leaves(operator(*args)) + + def _scan(elems): + """Perform the actual recursive scan on ``elems``.""" + num_elems = elems[0].shape[dim] + + if num_elems < 2: + return elems + + reduced_elems = call_operator( + *[aten.slice(elem, dim, 0, -1, 2) for elem in elems], + *[aten.slice(elem, dim, 1, None, 2) for elem in elems], + *additional_inputs, + ) + + # Recursively compute scan for partially reduced tensors. + odd_elems = _scan(reduced_elems) + + if num_elems % 2 == 0: + even_elems = call_operator( + *[aten.slice(e, dim, 0, -1) for e in odd_elems], + *[aten.slice(e, dim, 2, None, 2) for e in elems], + *additional_inputs, + ) + else: + even_elems = call_operator( + *odd_elems, + *[aten.slice(e, dim, 2, None, 2) for e in elems], + *additional_inputs, + ) + + # The first element of a scan is the same as the first element + # of the original `elems`. + even_elems = [ + torch.cat([aten.slice(elem, dim, 0, 1), result], dim=dim) + if result.shape.numel() > 0 and elem.shape[dim] > 0 + else result + if result.shape.numel() > 0 + else aten.slice( + elem, dim, 0, 1 + ) # Jax allows/ignores concat with 0-dim, Pytorch does not + for (elem, result) in zip(elems, even_elems) + ] + + return list( + safe_map(functools.partial(_interleave, dim=dim), even_elems, odd_elems) + ) + + scans = _scan(leaves) + + return scans + + +def trace_associative_scan( + proxy_mode, + func_overload, + combine_fn: Callable, + xs: list[torch.Tensor], + additional_inputs: tuple[torch.Tensor], +): + from torch._dynamo.utils import clone_input + + with disable_proxy_modes_tracing(): + sample_xs = [first_slice_copy(x) for x in itertools.chain(xs, xs)] + sample_additional_inputs = [ + clone_input(x) if isinstance(x, torch.Tensor) else x + for x in additional_inputs + ] + combine_graph = reenter_make_fx(combine_fn)( + *sample_xs, *sample_additional_inputs + ) + + outputs = None + for node in combine_graph.graph.nodes: + if node.op == "output": + if outputs is not None: + raise AssertionError("found multiple output nodes in combine_graph") + if len(node.args) != 1: + raise AssertionError( + f"expected output node to have 1 arg, got {len(node.args)}" + ) + outputs = node.args[0] + + if outputs is None: + raise AssertionError("no output node found in combine_graph") + outputs = pytree.tree_leaves(outputs) + if len(outputs) != len(xs): + raise AssertionError( + f"expected combine_fn to return {len(xs)} results but got {len(outputs)}" + ) + + xs_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [ + first_slice_copy(x) for x in xs + ] + output_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [ + c.meta["val"] for c in outputs + ] + check_meta_consistency( + xs_fake_tensors, output_fake_tensors, "init", "carry", include_contiguity=False + ) + + _, combine_graph_name = unique_graph_id( + proxy_mode, prefix="associative_scan_combine_graph" + ) + + proxy_mode.tracer.root.register_module(combine_graph_name, combine_graph) + + args = (combine_graph, xs, additional_inputs) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {}, name="associative_scan" + ) + + with disable_proxy_modes_tracing(): + out = tuple(aten.clone(x) for x in xs) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@associative_scan_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def associative_scan_op_dense(combine_fn, xs, additional_inputs): + return generic_associative_scan(combine_fn, xs, additional_inputs=additional_inputs) + + +class AssociativeScanAutogradOp(torch.autograd.Function): + r""" associative_scan + Example:: + xs = torch.arange(1, 5) = [1, 2, 3, 4] + + def combine_fn(a: torch.Tensor, b: torch.Tensor): + return a * b + + ys = associative_scan(comine_fn, xs), + which can be unpacked as: + ys0 = xs0 = 1 + ys1 = combine_fn(ys0, xs1) = combine_fn(1, 2) = 2 + ... + ysT = combine_fn(ys(T-1), xsT) = combine_fn(6, 4) = 24 + ys = [1, 2, 6, 24] + + This creates a recursive data dependency structure where each output yst + depends on all prior inputs xs0 through xst. The dependency can be visualized as: + + Level 0 (Input): xs0 xs1 xs2 xs3 xs4 + \ / | | | + \ / | | | + Level 1: ys1 ───────┘ | | + \ / | + \ / | + Level 2: ys2 ────────┘ | + \ / + \ / + Level 3: ys3 ────────────┘ + \ + \ + Level 4: ys4 + + + We could get the following backward gradient graph: + + + Level 0 (output): g_xs0 g_xs1 g_xs2 g_xs3 g_xs4 + \ / | | | + \ / | | | + Level 1: gl_ys1 ─> g_ys1 ──────┘ | | + \ / | + \ / | + Level 2: gl_ys2 ─> g_ys2 ────────┘ | + \ / + \ / + Level 3: gl_ys3 ─> g_ys3 ────────────┘ + \ + \ + Level 4: gl_ys4 ─> g_ys4, + + where gl_y1 is the gradient of the loss with respect to ys1 and the input of backward. + + To calculate the gradients of the inputs, the chain rule suggests: + + g_xs0 = g_ys1 + g_xs1 = g_ys1 * bw(ys0, xs1) = g_ys1 * bwxs01 + g_xs2 = g_ys2 * bw(ys1, xs2) = g_ys2 * bwxs12 + g_xs3 = g_ys3 * bw(ys2, xs3) = g_ys3 * bwxs23 + g_xs4 = g_ys4 * bw(ys3, xs4) = g_ys4 * bwxs34 + + Notice the bw(...) is just the single step bw (instantaneous gradients), whose formula can be computed from combine_fn. + For example bw(ys3, xs4) (also abbreviated with bwxs34) computes the gradients ∂/∂xs4 combine_fn(ys3, xs4). + Similarly, bw(ys4, ys3) (also abbreviated with bwys43) computes the gradients ∂/∂ys3 combine_fn(ys3, xs4). + + Let's break down how to calculate g_ys by recursively substituting the unknowns: + + g_ys1 = gl_ys1 + g_ys2 * bw(ys2, ys1) + = gl_ys1 + (gl_ys2 + g_ys3 * bw(ys3, ys2)) * bw(ys2, ys1) + = gl_ys1 + gl_ys2 * bw(ys2, ys1) + g_ys3 * bw(ys3, ys2) * bw(y2, y1) + = gl_ys1 + gl_ys2 * bw(ys2, ys1) + gl_ys3 * bw(ys3, ys2) * bw(y2, y1) \ + + g_ys4 * bw(ys4, ys3) * bw(ys3, ys2) * bw(ys2, ys1) + = gl_ys1 + gl_ys2 * bw(ys2, ys1) + gl_ys3 * bw(ys3, ys2) * bw(y2, y1) \ + + gl_ys4 * bw(ys4, ys3) * bw(ys3, ys2) * bw(ys2, ys1) + + Let's do the same for all the g_ys: + g_ys2 = gl_ys2 + gl_ys3 * bw(ys3, ys2) + gl_y4 * bw(ys4, ys3) * bw(ys3, ys2) + g_ys3 = gl_ys3 + gl_ys4 * bw(ys4, ys3) + g_ys4 = gl_ys4 + + Notice that the above can be re-written as columnwise multiplication of y_mat and gl_ys: + + g_ys1 1, bwys21, bwys321, bwys4321 gl_ys1 + g_ys2 = 0, 1 , bwys321, bwys4321 . gl_ys2 + g_ys3 0, 0 , 1 , bwys4321 gl_ys3 + g_ys4 0, 0 , 0 , 1 gl_ys4, + + where bwys21 is an abbreviation for bw(ys2, ys1), + bwys321 is an abbreviation for bw(ys3, ys2) * bw(ys2, ys1) so on and so forth. + + We could effectively compute the upper triangular matrix y_mat with: + cumprod([1, bwys21, bwys32, bwys43]) then masking out the values as needed. + Thus, only [1, bwys21, bwys32, bwys43] are required to compute the y_mat. + + + References: https://justintchiu.com/blog/pscan_diff/ + + NOTE: [associative_scan autograd implementation] + + The forward of associative_scan can be computed with the following steps: + + 1.) Compute the forward output of the associative_scan + ys = associative_scan(combine_fn, xs, additional_inputs) + + The backward of associative_scan can be computed with the following steps: + + 2.) Prepare the backward graph + We prepare the backward graph to be used in the backward function. + We utilize ``create_bw_fn`` to generate the joint function: + combine_fn_bw = create_bw_fn(combine_fn, operands) + where operands = [ys{t-1}, xst, additional_inputs] + + 3.) Materialize the ``combine_fn_bw`` + This is required because torch.compile and torch.autograd.grad + cannot trace through the joint backward function dynamically. + + 4.) Compute the single step bw (instantaneous gradients) at every step t + bwys{t-1}, bwxst = combine_fn_bw(ys{t-1}, xst, 1.) + Here we pass 1 as the upstream gradient to obtain the local partial derivatives. + + This gives: + bwys = [bw(ys1, ys0), bw(ys2, ys1), ..., bw(ysT, ys{T-1})] + bwxs = [bw(ys1, xs0), bw(ys2, xs1), ..., bw(ys{T-1}, xsT)] + + 5.) Compute the gradient transition matrix y_mat + + As shown in the example above, each input xst affects all later outputs ysi for i ≥ t. + According to the chain rule, each such path contributes a product of local gradients g_ysk. + + For example: + ∂ysT/∂xst = ∂ysT/∂ys{T-1} * ∂ys{T-1}/∂ys{T-2} * ... * ∂ys{t+1}/∂yst * ∂yst/∂xst + = bw(ysT, ys{T-1}) * bw(ys{T-1}, ys{T-2}) * ... * bw(ys{t+1}, yst) * bw(ys{t-1}, xst) + + This motivates the use of a cumulative product over bwys to compute all such paths efficiently. + + We now construct the matrix of gradient transition paths: + + 5.1 Repeat g_y values to form the base matrix + y_mat = [[1, bwys21, bwys32, bwys43], + [1, bwys21, bwys32, bwys43], + [1, bwys21, bwys32, bwys43], + [1, bwys21, bwys32, bwys43]] + + 5.2 Mask the lower triangle (inclusive) with 1s + y_mat = [[1, bwys21, bwys32, bwys43], + [1, 1 , bwys32, bwys43], + [1, 1 , 1 , bwys43], + [1, 1 , 1 , 1 ]] + + 5.3 Apply cumulative product row-wise + y_mat = cumprod(y_mat, dim=1) + Resulting in: + y_mat = [[1, bwys21, bwys32 * bwys21, bwys43 * bwys32 * bwys21], + [1, 1 , bwys32 , bwys43 * bwys32 ], + [1, 1 , 1 , bwys43 ], + [1, 1 , 1 , 1 ]] + + 5.4 Zero out the lower triangle (exclusive) + Final y_mat: + y_mat = [[1, bwys21, bwys32 * bwys21, bwys43 * bwys32 * bwys21], + [0, 1 , bwys32 , bwys43 * bwys32 ], + [0, 0 , 1 , bwys43 ], + [0, 0 , 0 , 1 ]] + + 6.) Scale the y_mat with the upstream gradients gl_ys + scaled_y_mat = y_mat * gl_ys + Each entry now holds the full contribution of ∂L/∂ysj to ∂L/∂xsi via the path through ysj. + + 7.) Reduce the scaled_y_mat with a row-wise sum + summed_y_mat = scaled_y_mat.sum(dim=1) + This accumulates all downstream contributions for each xst. + + 8.) Scale with the instantaneous input gradients bwxs + g_xs = summed_y_mat * bwxs + + This gives the final input gradients: + g_xs = [∂L/∂xs0, ∂L/∂xs1, ..., ∂L/∂xsT] + + NOTE: [scan partial grad handling] + If any element of xs or of the outputs does not require gradients + (i.e., requires_grad=False), then the corresponding gradients will be returned + as tensors of zeros with the same shape as the element. + """ + + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + combine_fn, + num_xs, + num_additional_inputs, + *operands, + ): + ctx._num_xs = num_xs + ctx._num_additional_inputs = num_additional_inputs + ctx._combine_fn = combine_fn + xs, additional_inputs = split_into_chunks( + operands, [num_xs, num_additional_inputs] + ) + + scan_length = xs[0].shape[0] + ctx._scan_length = scan_length + + # We snapshot the dispatch keys in forward for materializing + # the bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + + with torch._C._AutoDispatchBelowAutograd(): + # 1.) Compute the forward output of the associative_scan + ys = associative_scan_op(combine_fn, xs, additional_inputs) + save_values_for_backward(ctx, list(operands) + list(ys)) + + return (*ys,) + + @staticmethod + def backward(ctx, *gl_ys): + r""" + This function computes the gradients of the scan operation. + For a detailed description see the document above. + + Args: + flat_grads (torch.Tensor): The tensor of upstream gradients, or a nested pytree of tensors. + E.g.: Gradient of the loss with respect to the forward output ys + """ + + # The backward of associative_scan is always performed on the first dimension + dim = 0 + scan_length = ctx._scan_length + num_xs = ctx._num_xs + num_additional_inputs = ctx._num_additional_inputs + + # Extract the inputs to the forward path and outputs from the forward path + flat_args = saved_values(ctx) + xs, additional_inputs, outs = split_into_chunks( + flat_args, [num_xs, num_additional_inputs, num_xs] + ) + + if scan_length == 0: + return ( + *[None] * 3, + *[torch.zeros_like(x) for x in xs], + *[None] * num_additional_inputs, + ) + + ndim = outs[0].ndim + + # First_slice_copy does not keep the original requires_grad flag, + # but we need it here in order to compute the correcte gradients + xs_slices = first_slice_copy_with_grad(itertools.chain(xs, xs)) + + # Construct the operands from the forward, fw_operands + # and the operands for a single event t of the forward, fw_operands_slice + fw_operands = (*xs, *additional_inputs) + fw_operands_slice = (*xs_slices, *additional_inputs) + + # 2.) Prepare the backward graph + combine_fn_bw = create_bw_fn(ctx._combine_fn, fw_operands_slice) + + # 3.) Materialize the ``combine_fn_bw`` + # TODO: we need to materialize the bw graphs because dynamo is unable to + # trace through the joint function when torch.compile torch.autograd.grad. + combine_fn_bw_gm = materialize_as_graph( + combine_fn_bw, + ( + *fw_operands_slice, + *[first_slice_copy(o) for o in outs], + ), + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + + # vmap joint graph over scan dimension to compute the individual + # gradients for each time slice ``t`` in parallel. + # This computation can be parallelized, as these are just the instantaneous gradients and not the full chain-rule + # pyrefly: ignore [bad-argument-type] + mapped_combine_fn_bw_gm = torch.vmap(combine_fn_bw_gm, 0, 0) + + # 4.) Compute the single step bw (instantaneous gradients) at every step ``t`` + # Use a ones_like tensor in order not to scale the bwyst and bwxst, + # with the upstream gradients yet. + # Note: All bwyst and bwxst are computed in parallel, thus the tensors bwys and bwxs are the result. + dummy_upstream_grad = (torch.ones_like(x) for x in gl_ys) + grads = mapped_combine_fn_bw_gm( + *(o.roll(1, dim) for o in outs), *fw_operands, *dummy_upstream_grad + ) + bwys, bwxs = split_into_chunks(grads, [num_xs, num_xs]) + + def compute_y_mat(bwys: torch.Tensor) -> torch.Tensor: + # Prepare a ones and a zeros helper mask in order to easily compute the y_mat + def compute_helper_tril_mask(diagonal): + def expand_masks(mask): + for _ in range(ndim - 1): + mask = mask.unsqueeze(-1) + return mask + + tril_mask = torch.tril( + torch.ones( + scan_length, scan_length, device=bwys.device, dtype=torch.bool + ), + diagonal=diagonal, + ) + tril_mask = expand_masks(tril_mask) + tril_mask = tril_mask.expand(-1, -1, *bwys.shape[1:]) + return tril_mask + + # The ones mask is used to fill the main diagonal and all elements below it with 1s + ones_mask = compute_helper_tril_mask(0) + + # The zero mask is used to set all elements below the main diagonal to 0 + zeros_mask = compute_helper_tril_mask(-1) + + # 5.1) Repeat the elements of bwys to form the square matrix + y_mat = bwys.unsqueeze(dim).repeat_interleave(scan_length, dim) + + # 5.2) Fill the lower triangular part, including the diagonal, + # of the h_mat with 1s. I.e., use the ones_mask to fill with 1s. + y_mat.masked_fill_(ones_mask, 1.0) + + # 5.3) Compute the cumulative products across dim + 1 + y_mat = y_mat.cumprod(dim=dim + 1) + + # 5.4) Replace the elements we filled with 1s before with 0s + y_mat.masked_fill_(zeros_mask, 0.0) + + return y_mat + + def compute_grad(bwxs, bwys, gl_ys): + # Set the first gradient component of bwxs to 1.0, per definition. + torch.select(bwxs, dim, 0).fill_(1.0) + + # 5.) Compute the gradient transition matrix + y_mat = compute_y_mat(bwys) + + # 6.) scale the y_mat with the upstream gradients gl_ys + scaled_y_mat = y_mat * gl_ys + + # 7.) Reduce the y_mat with sum along the columns to get the total contributions for xs_t + summed_y_mat = scaled_y_mat.sum(dim + 1) + + # 8.) Scale with the bwxs to obtain the final gradients g_xs + g_xs = summed_y_mat * bwxs + + return g_xs + + # Stack all leaves of the gradients along the first dimension. + # This is useful as later the gradients of those leaves can be computed in parallel. + bwxs_stacked_leaves = torch.stack(bwxs) + bwys_stacked_leaves = torch.stack(bwys) + gl_ys_stacked_leaves = torch.stack(gl_ys) + + # The compute_grad function is parallelized across all individual leaves of xs + # as these gradients can be computed independently from each other + # TODO: torch.vmap may create composability issues + compute_grad_mapped = torch.vmap(compute_grad, 0, 0) + + g_xs = compute_grad_mapped( + bwxs_stacked_leaves, bwys_stacked_leaves, gl_ys_stacked_leaves + ) + + # TODO: Currently the gradients for the additional_inputs are not computed properly + return *[None] * 3, *g_xs, *[None] * num_additional_inputs + + +@associative_scan_op.py_autograd_impl +def associative_scan_autograd(combine_fn, xs, additional_inputs): + num_xs = len(xs) + num_additional_inputs = len(additional_inputs) + + if num_additional_inputs > 0: + raise RuntimeError( + "Associative_scan does currently not support gradients for lifted parameters!" + ) + + flat_out = AssociativeScanAutogradOp.apply( + combine_fn, + num_xs, + num_additional_inputs, + *(tuple(xs) + tuple(additional_inputs)), + ) + return (*flat_out,) + + +@associative_scan_op.py_impl(ProxyTorchDispatchMode) +def associative_scan_proxy_mode(mode, combine_fn, xs, additional_inputs): + return trace_associative_scan( + mode, associative_scan_op, combine_fn, xs, additional_inputs + ) + + +@register_fake(associative_scan_op, skip_cache=True) +def assoiciative_scan_fake_tensor_mode(combine_fn, xs, additional_inputs): + return tuple(x.clone() for x in xs) + + +@associative_scan_op.py_functionalize_impl +def associative_scan_functionalize(ctx, combine_fn, xs, additional_inputs): + from torch._higher_order_ops.utils import _check_alias_and_mutation + + unwrapped_xs = ctx.unwrap_tensors(xs) + unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs) + with ctx.redispatch_to_next(): + functional_combine_fn = ctx.functionalize( + _maybe_run_with_interpreter(combine_fn) + ) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + sample_unwrapped_xs_sliced = [ + first_slice_copy(inp) for inp in itertools.chain(unwrapped_xs, unwrapped_xs) + ] + sample_inputs = list( + itertools.chain( + sample_unwrapped_xs_sliced, + unwrapped_additional_inputs, + ) + ) + _check_alias_and_mutation( + combine_fn, sample_inputs, "associative_scan", pre_dispatch + ) + ret = associative_scan_op( + functional_combine_fn, + unwrapped_xs, + unwrapped_additional_inputs, + ) + return ctx.wrap_tensors(ret) + + +def _fake_associative_scan(combine_fn, xs, dim, reverse=False): + inp_leaves, spec = pytree.tree_flatten(xs) + result_flat: list[Any] = [] + num_leaves = len(inp_leaves) + op = reversed if reverse else lambda x: x + + for ind in op(range(inp_leaves[0].size(dim))): + r = [ + inp_leaves[leave_ind][(slice(None),) * dim + (ind,)] + for leave_ind in range(num_leaves) + ] + if (ind > 0 and not reverse) or ( + ind < (inp_leaves[0].size(dim) - 1) and reverse + ): + r = combine_fn( + pytree.tree_unflatten(result_flat[-1], spec), + pytree.tree_unflatten(r, spec), + ) + r_flat, _ = pytree.tree_flatten(r) + result_flat.append(r_flat) + + if len(result_flat) == 0: + results = list(inp_leaves) + else: + results = [ + torch.stack([e[leave_ind] for e in op(result_flat)], dim) + for leave_ind in range(num_leaves) + ] + return pytree.tree_unflatten(results, spec) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/auto_functionalize.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/auto_functionalize.py new file mode 100644 index 0000000000000000000000000000000000000000..7798dd5e617eeaac8602b20f8bf040167d8f8e54 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/auto_functionalize.py @@ -0,0 +1,1244 @@ +# mypy: allow-untyped-defs +import warnings +from abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Any, get_args + +import torch +import torch._library.utils as library_utils +import torch.utils._pytree as pytree +from torch import Tensor +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + _has_gen_schema, + call_op, + HopInstance, + HopSchema, + materialize_callable_in_args, + register_fake, + unique_graph_id, +) +from torch._ops import HigherOrderOperator, OperatorBase, OpOverload +from torch._prims_common import clone_preserve_strides +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +class SchemaHolder: + def __init__(self, schema: torch.FunctionSchema): + self.schema = schema + + def __eq__(self, other): + return self.schema == other.schema + + def __hash__(self) -> int: + return hash(self.schema) + + @classmethod + def from_tree_spec(cls, tree_spec: pytree.TreeSpec): + if tree_spec is None: + raise AssertionError("tree_spec cannot be None") + return cls(pytree.tree_unflatten([], tree_spec).schema) + + +# register_constant allows us to get a tree_spec from pytree.tree_flatten(SchemaHolder(FunctionSchema)). +# The tree_spec is proxable in the graph and we can get back the schema via +# schema = pytree.tree_unflatten([], tree_spec).schema +pytree.register_constant(SchemaHolder) + + +def get_base(tensor): + if torch.is_inference_mode_enabled(): + return tensor._inference_mode_base + else: + return tensor._base + + +class ViewInfo(ABC): + base_index: int + + def __init__(self, base_index): + self.base_index = base_index + + @abstractmethod + def regenerate_view(self, bases_list: list[Tensor]): + pass + + +@dataclass +class AsStridedViewInfo(ViewInfo): + size: Sequence[int | torch.SymInt] + stride: Sequence[int | torch.SymInt] + storage_offset: int + + def __init__(self, base_index, size, stride, storage_offset): + super().__init__(base_index) + self.size = size + self.stride = stride + self.storage_offset = storage_offset + + def regenerate_view(self, bases_list: list[Tensor]): + return torch.as_strided( + bases_list[self.base_index], + self.size, + self.stride, + self.storage_offset, + ) + + +@dataclass +class SliceViewInfo(ViewInfo): + dim: int | torch.SymInt + start: int | torch.SymInt + end: int | torch.SymInt + + def __init__(self, base_index, dim, start, end): + super().__init__(base_index) + self.dim = dim + self.start = start + self.end = end + + def regenerate_view(self, bases_list: list[Tensor]): + return torch.ops.aten.slice.Tensor( + bases_list[self.base_index], self.dim, self.start, self.end + ) + + +@dataclass +class AliasViewInfo(ViewInfo): + def __init__(self, base_index): + super().__init__(base_index) + + def regenerate_view(self, bases_list: list[Tensor]): + return torch.ops.aten.alias.default(bases_list[self.base_index]) + + +@dataclass +class NotView(ViewInfo): + def __init__(self, base_index): + super().__init__(base_index) + + def regenerate_view(self, bases_list: list[Tensor]): + return bases_list[self.base_index] + + +def is_alias(base, tensor): + from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq + + return all( + statically_known_true(a) + for a in [ + sym_eq(base.storage_offset(), tensor.storage_offset()), + sym_eq(base.stride(), tensor.stride()), + sym_eq(base.size(), tensor.size()), + ] + ) + + +# return None or (dim, start, end) +def try_use_slice(base, tensor): + from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq + + # This condition should never be triggered. + if is_alias(base, tensor): + return (0, 0, base.size()[0]) + + # TODO is there cases can we use slice even if stride or len(sizes) are not equal? + if not statically_known_true(sym_eq(tensor.stride(), base.stride())): + return None + if not statically_known_true(sym_eq(len(tensor.size()), len(base.size()))): + return None + + dim = None + count = 0 + for i in range(len(tensor.size())): + if base.size()[i] != tensor.size()[i]: + dim = i + count = count + 1 + if count != 1: + return None + + if tensor.storage_offset() % tensor.stride()[dim] != 0: + return None + start = tensor.storage_offset() // tensor.stride()[dim] + end = start + tensor.size()[dim] + return (dim, start, end) + + +def write_view_information_to_args( + mutable_arg_names: list[str], + mutable_arg_types: list[torch.Type], + kwargs: dict[str, Any], + arg_to_base_index: dict[str, Any], +): + """ + This function writes the view information into kwargs. It reads mutable_args from kwargs. + and uses arg_to_base_index and tensor information to write ViewInfo into kwargs. + mutable_arg_names: mutable custom operator arg names. + mutable_arg_types: mutable custom operator arg types. + kwargs: the original custom operator args. + arg_to_base_index: maps mutable_arg_name to int | [int] that refers to the base tensor that + corresponds to the input tensor + """ + + def write_single_view(prefix: str, tensor: Tensor, base_index: int): + if f"{prefix}_base_index" in kwargs: + raise AssertionError(f"{prefix}_base_index already in kwargs") + if f"{prefix}_size" in kwargs: + raise AssertionError(f"{prefix}_size already in kwargs") + if f"{prefix}_stride" in kwargs: + raise AssertionError(f"{prefix}_stride already in kwargs") + if f"{prefix}_storage_offset" in kwargs: + raise AssertionError(f"{prefix}_storage_offset already in kwargs") + + if f"{prefix}_slice_dim" in kwargs: + raise AssertionError(f"{prefix}_slice_dim already in kwargs") + if f"{prefix}_slice_start" in kwargs: + raise AssertionError(f"{prefix}_slice_start already in kwargs") + if f"{prefix}_slice_end" in kwargs: + raise AssertionError(f"{prefix}_slice_end already in kwargs") + + def use_as_strided(tensor): + kwargs[f"{prefix}_size"] = tensor.size() + kwargs[f"{prefix}_stride"] = tensor.stride() + kwargs[f"{prefix}_storage_offset"] = tensor.storage_offset() + + def use_slice(dim, start, end): + kwargs[f"{prefix}_slice_dim"] = dim + kwargs[f"{prefix}_slice_start"] = start + kwargs[f"{prefix}_slice_end"] = end + + def use_alias(): + kwargs[f"{prefix}_alias"] = True + + # The start if the function + if tensor is None: + kwargs[f"{prefix}_base_index"] = None + else: + base = get_base(tensor) + kwargs[f"{prefix}_base_index"] = base_index + if base is None: + # no need to add anything else other than _base_index + return + elif is_alias(base, tensor): + use_alias() + elif (slice_info := try_use_slice(base, tensor)) is not None: + use_slice(*slice_info) + else: + use_as_strided(tensor) + + for arg_name, arg_type in zip(mutable_arg_names, mutable_arg_types): + arg = kwargs[arg_name] + if library_utils.is_tensorlist_like_type(arg_type): + if arg is None: + kwargs[f"_{arg_name}_length"] = None + else: + kwargs[f"_{arg_name}_length"] = len(arg) + for i, elem in enumerate(arg): + write_single_view( + f"_{arg_name}_{i}", elem, arg_to_base_index[arg_name][i] + ) + + elif library_utils.is_tensor_like_type(arg_type): + write_single_view( + f"_{arg_name}", + kwargs[arg_name], + arg_to_base_index.get(arg_name), # type: ignore[arg-type] + ) + else: + raise RuntimeError(f"Unsupported type {arg_type}") + + +# Returns a dict of arg_name -> ViewInfo | [ViewInfo] +def read_view_information_from_args( + mutable_arg_names: list[str], + mutable_arg_types: list[torch.Type], + kwargs: dict[str, Any], + all_bases: list[Tensor], +): + """ + This reads the view information added by `write_view_information_to_args` from kwargs, pop them, + and returns a dict arg_name -> ViewInfo | [ViewInfo](if the input is list). that maps each mutable arg + to its view information. + mutable_arg_names: mutable custom operator arg names. + mutable_arg_types: mutable custom operator arg types. + kwargs : args of auto_functionalize(custom_op, kwargs) + """ + + def get_arg(name): + return kwargs.pop(name) + + def read_single_view(prefix): + base_index = get_arg(f"{prefix}_base_index") + if base_index is None: + return None + elif f"{prefix}_alias" in kwargs: + get_arg(f"{prefix}_alias") + return AliasViewInfo(base_index) + elif f"{prefix}_storage_offset" in kwargs: + # The view is regenerated using as_strided. + size = get_arg(f"{prefix}_size") + stride = get_arg(f"{prefix}_stride") + storage_offset = get_arg(f"{prefix}_storage_offset") + return AsStridedViewInfo(base_index, size, stride, storage_offset) + elif f"{prefix}_slice_dim" in kwargs: + dim = get_arg(f"{prefix}_slice_dim") + start = get_arg(f"{prefix}_slice_start") + end = get_arg(f"{prefix}_slice_end") + return SliceViewInfo(base_index, dim, start, end) + else: + # This means that the argument is the base tensor + return NotView(base_index) + + args_view_info: dict[str, Any] = {} + for arg_name, arg_type in zip(mutable_arg_names, mutable_arg_types): + if library_utils.is_tensorlist_like_type(arg_type): + length = get_arg(f"_{arg_name}_length") + if length is None: + # The whole list is None. + args_view_info[arg_name] = None + else: + args_view_info[arg_name] = [ + read_single_view(f"_{arg_name}_{i}") for i in range(length) + ] + + elif library_utils.is_tensor_like_type(arg_type): + args_view_info[arg_name] = read_single_view(f"_{arg_name}") + else: + raise RuntimeError(f"Unsupported type {arg_type}") + return args_view_info + + +# NOTE: [auto-functionalizing custom ops] +# Users may wish to torch.compile custom ops that mutate their inputs. +# torch.compile will automatically support this op without anyone needing +# to provide a functionalization kernel for it. Here's how. +# +# Let's say we have a hypothetical mylib::sin_(Tensor(a!) x) -> () +# op. First, when FakeTensor sees this op: +# - If the schema says it returns nothing, we can generate a trivial +# FakeTensor rule for it (that returns nothing). +# - Otherwise, the user needs to provide a FakeTensor impl (fake impl) +# +# Next, when Python FunctionalTensor sees the op, it will functionalize +# it by emitting a call to an auto_functionalize(op, ["x"], {"x": ...}) +# HOP and replacing the mutated inputs with corresponding outputs of this HOP. +# This HOP effectively runs the functional version of the op when +# called: it clones inputs that will be mutated, runs the op, and +# then returns (output, Tensors with the new values) +# +# auto_functionalize_v2 is an improved version of auto_functionalize that better handle +# re-inplacing views. + + +class AutoFunctionalized(HigherOrderOperator): + """auto_functionalized(_mutable_op, **kwargs) + + This HOP runs a "functional" version of _mutable_op. + + Concretely, it looks at all the arguments that are mutable through + _mutable_op's operator schema, clones those kwargs, runs + `out = _mutable_op(**kwargs)` with the cloned values, and then returns the + operator output concatenated with the cloned values that were mutated. + + We have some restrictions on `_mutable_op`. + See `can_auto_functionalize` for the restrictions. We can likely lift + many of these if users request it. + + The reason why _mutable_op is prefixed with an + underscore is to prevent collisions with kwarg names in **kwargs. + """ + + def __init__(self) -> None: + super().__init__("auto_functionalized", cacheable=True) + + def __call__( + self, + /, + _mutable_op: OpOverload, + **kwargs: Any, + ) -> tuple[Any, tuple[Tensor, ...]]: + if not can_auto_functionalize(_mutable_op): + raise AssertionError(f"Cannot auto-functionalize op {_mutable_op}") + if not isinstance(kwargs, dict): + raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}") + # pyrefly: ignore [missing-attribute] + return super().__call__(_mutable_op, **kwargs) + + +auto_functionalized = AutoFunctionalized() +auto_functionalized.__module__ = "torch.ops.higher_order" + +auto_functionalized.fallthrough(DispatchKey.AutogradCPU) +auto_functionalized.fallthrough(DispatchKey.AutogradCUDA) + + +_MutableOpType = OpOverload | HigherOrderOperator + + +class AutoFunctionalizedV2(HigherOrderOperator): + """auto_functionalized_v2(_mutable_op, **kwargs) + + This HOP runs a "functional" version of _mutable_op. + Unlike AutoFunctionalized, this version is improved to better handle + view tensors. This version is only used in non export mode. + """ + + def __init__(self) -> None: + super().__init__("auto_functionalized_v2", cacheable=True) + + def __call__( + self, + /, + _mutable_op: _MutableOpType, + **kwargs: Any, + ) -> tuple[Any, tuple[Tensor, ...]]: + _op_to_check: OpOverload | HopInstance | None = None + if isinstance(_mutable_op, HigherOrderOperator): + _op_to_check = HopInstance( + _mutable_op, + SchemaHolder.from_tree_spec(kwargs.get("_op_schema")).schema, # type: ignore[arg-type] + ) + else: + _op_to_check = _mutable_op + + if _op_to_check is None: + raise AssertionError("_op_to_check cannot be None") + if not can_auto_functionalize(_op_to_check): + raise AssertionError(f"Cannot auto-functionalize op {_op_to_check}") + if not isinstance(kwargs, dict): + raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}") + # pyrefly: ignore [missing-attribute] + return super().__call__(_mutable_op, **kwargs) + + +auto_functionalized_v2 = AutoFunctionalizedV2() +auto_functionalized_v2.__module__ = "torch.ops.higher_order" + +auto_functionalized_v2.fallthrough(DispatchKey.AutogradCPU) +auto_functionalized_v2.fallthrough(DispatchKey.AutogradCUDA) + + +def can_auto_functionalize( + op: OperatorBase | HopInstance, +) -> bool: + if isinstance(op, HopInstance): + # HOPs that implement gen_schema and schema is not functional are auto_functionalizable. + if not _has_gen_schema(op._op): + return False + + else: + if not isinstance(op, OpOverload): + return False + + if torch._library.utils.is_builtin(op): + # We control the built-ins. These may (in rare cases) + # do input metadata mutation (which we have banned on custom ops) + return False + + schema = op._schema + if not schema.is_mutable: + return False + schema = op._schema + + for arg in schema.arguments: + if arg.alias_info is None: + continue + if not arg.alias_info.is_write: + continue + if torch._library.utils.is_tensor_like_type(arg.type): + continue + if torch._library.utils.is_tensorlist_like_type(arg.type): + continue + return False + + if len(schema.returns) == 1 and isinstance(schema.returns[0].type, torch.NoneType): + # Skip schema returns -> None + return True + if isinstance(op, OpOverload): + if torch._library.utils.is_out(op): + # Out ops have aliased returns (returns alias the mutable args). + # This is fine because the mutable args are write-only output buffers. + pass + elif torch._library.utils.is_inplace(op): + # Inplace ops have aliased returns (return aliases the first mutable arg). + pass + else: + # The returns of OpOverload must not alias anything + for ret in schema.returns: + if ret.alias_info is None and type(ret.type) is torch.TensorType: + continue + # Not yet supported: List[Tensor] return. + return False + if torch._C._dispatch_has_kernel_for_dispatch_key(op.name(), "Functionalize"): + return False + return True + + +def get_mutable_args_from_schema( + schema: torch.FunctionSchema, +) -> tuple[list[str], list[torch.Type]]: + """ + Returns the list of argument names that get mutated according to the + schema and their types. + """ + mutable_args_names = [ + arg.name + for arg in schema.arguments + if arg.alias_info is not None and arg.alias_info.is_write + ] + + mutable_args_types = [ + arg.type + for arg in schema.arguments + if arg.alias_info is not None and arg.alias_info.is_write + ] + return mutable_args_names, mutable_args_types # type: ignore[return-value] + + +def get_mutable_args(op: OpOverload) -> tuple[list[str], list[torch.Type]]: + return get_mutable_args_from_schema(op._schema) + + +def do_auto_functionalize( + mode: "torch._subclasses.functional_tensor.FunctionalTensorMode", + op: OpOverload, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> Any: + """Functionalizes a call to op(*args, **kwargs) by emitting a call to + `outs = auto_functionalized(op, normalized_kwargs)` + and replacing the mutated (args, kwargs) with the corresponding outputs. + + The normalized_kwargs are just the (args, kwargs), but all in kwarg form. + This makes handling easier for the auto_functionalized HOP. + """ + from torch._subclasses.functional_tensor import PythonFunctionalizeAPI + + ctx = PythonFunctionalizeAPI(mode=mode) + + # All of the (args, kwargs), but all as kwargs. The names for the + # args come from the schema. This makes it easier for us to work with them. + normalized_kwargs = {} + schema = op._schema + for idx, arg in enumerate(schema.arguments): + # NB: torch_dispatch kwargs are the args defined as kwarg-only in the schema + if arg.name in kwargs: + normalized_kwargs[arg.name] = kwargs[arg.name] + elif idx < len(args): + # if its out of bounds we don't need to do anything + # as it means the optional arg was passed with its default + # value + normalized_kwargs[arg.name] = args[idx] + else: + normalized_kwargs[arg.name] = arg.default_value + + unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type] + if "self" in unwrapped_kwargs or "self_" in unwrapped_kwargs: + warnings.warn( + "Using `self` or `self_` as an argument in the definition of custom ops may lead to ambiguous parsing. " + "Please consider using a different name for this argument to avoid potential issues.", + stacklevel=2, + ) + with ctx.redispatch_to_next(): + unwrapped_outs = auto_functionalized( + op, + **unwrapped_kwargs, # type: ignore[arg-type] + ) + + # List of the name of args that get mutated (according to the schema) + mutable_args_names, _ = get_mutable_args(op) + + unwrapped_actual_out: Any | tuple[Any] = unwrapped_outs[: -len(mutable_args_names)] + unwrapped_mutable_out = unwrapped_outs[-len(mutable_args_names) :] + + if len(op._schema.returns) == 0: + if unwrapped_actual_out[0] is not None: + raise AssertionError( + f"Expected None for op with no returns, got {unwrapped_actual_out[0]}" + ) + unwrapped_actual_out = None + elif len(op._schema.returns) == 1: + if len(unwrapped_actual_out) != 1: + raise AssertionError(f"Expected 1 output, got {len(unwrapped_actual_out)}") + unwrapped_actual_out = unwrapped_actual_out[0] + else: + if len(unwrapped_actual_out) != len(op._schema.returns): + raise AssertionError( + f"Expected {len(op._schema.returns)} outputs, got {len(unwrapped_actual_out)}" + ) + + for name, unwrapped_out in zip(mutable_args_names, unwrapped_mutable_out): + # Can be None if input was `Tensor(a!)?` + if unwrapped_out is None: + continue + + # We only handle Tensor or List[Tensor] here for now. + def sync_update(o, orig_arg): + ctx.replace(orig_arg, o) + ctx.commit_update(orig_arg) + ctx.sync(orig_arg) + + orig_arg = normalized_kwargs[name] + + if isinstance(unwrapped_out, torch.Tensor): + sync_update(unwrapped_out, orig_arg) + elif isinstance(unwrapped_out, list) and all( + isinstance(o, torch.Tensor) for o in unwrapped_out + ): + if len(orig_arg) != len(unwrapped_out): + raise AssertionError( + f"orig_arg length ({len(orig_arg)}) != unwrapped_out length ({len(unwrapped_out)})" + ) + for orig_a, o in zip(orig_arg, unwrapped_out): + sync_update(o, orig_a) + else: + raise RuntimeError( + f"unsupported type for auto-functionalization: {unwrapped_out}" + ) + + return ctx.wrap_tensors(unwrapped_actual_out) # type: ignore[arg-type] + + +# Wrapper for GraphModule that applies functionalization during execution to enable +# epilogue graph inlining and better fusion opportunities in subgraphs +# When tracing this wrapper, we'll get a graph module with epilogue. +# +# We want to hash it according to the original graph module, so that when we go +# from Functional mode -> fake mode for multiple invoke_subgraph calls that share, +# the same inner graph module, we can hit the cache. +class FunctionalCallableWithEpilogue: + def __init__(self, orig_callable: Callable): + self.orig_callable = orig_callable + # Propagate so callers pass inputs as a list, enabling input deallocation. + self._boxed_call = getattr(orig_callable, "_boxed_call", False) + + def __call__(self, *args, **kwargs): + # Functionalize to inline the epilogue graph (copy_ ops) for better fusion. + # Python functionalization so mutable custom ops reach auto_functionalized_v2. + from torch._subclasses.functional_tensor import ( + dispatch_functionalize, + FunctionalTensorMode, + ) + + functionalized = dispatch_functionalize( + self.orig_callable, + FunctionalTensorMode(), + propagate_input_mutations=True, + ) + if self._boxed_call: + # Not all callers respect _boxed_call (e.g. reenter_make_fx + # always calls f(*args)). Detect which convention was used. + if len(args) == 1 and isinstance(args[0], list): + return tuple(functionalized(args[0])) + return tuple(functionalized(list(args))) + return functionalized(*args, **kwargs) + + def __hash__(self): + return id(self.orig_callable) + + +def do_auto_functionalize_v2( + mode: "torch._subclasses.functional_tensor.FunctionalTensorMode", + op: OpOverload | HopInstance, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> Any: + from torch._subclasses.functional_tensor import PythonFunctionalizeAPI + + ctx = PythonFunctionalizeAPI(mode=mode) + + # All of the (args, kwargs), but all as kwargs. The names for the + # args come from the schema. This makes it easier for us to work with them. + normalized_kwargs = {} + + schema = op._schema + # pyrefly: ignore [bad-assignment] + op = op._op if isinstance(op, HopInstance) else op + if not isinstance(op, get_args(_MutableOpType)): + raise AssertionError(f"Expected _MutableOpType, got {type(op)}") + + subgraph_arg_names = { + arg_info.name + for arg_info in schema.arguments + if isinstance(arg_info.type, torch._C.AnyType) + } + + def _maybe_functionalize(name: str, arg: Any) -> Any: + if name in subgraph_arg_names and callable(arg): + return FunctionalCallableWithEpilogue(arg) + return arg + + args = tuple( + _maybe_functionalize(schema.arguments[i].name, a) + if i < len(schema.arguments) + else a + for i, a in enumerate(args) + ) + kwargs = {k: _maybe_functionalize(k, v) for k, v in kwargs.items()} + + for idx, arg in enumerate(schema.arguments): + # NB: torch_dispatch kwargs are the args defined as kwarg-only in the schema + if arg.name in kwargs: + normalized_kwargs[arg.name] = kwargs[arg.name] + elif idx < len(args): + # if its out of bounds we don't need to do anything + # as it means the optional arg was passed with its default + # value + normalized_kwargs[arg.name] = args[idx] + else: + normalized_kwargs[arg.name] = arg.default_value + + if isinstance(op, OpOverload) and torch._library.utils.is_out(op): + return _do_auto_functionalize_v2_for_out_operator( + ctx, op, schema, normalized_kwargs + ) + if isinstance(op, OpOverload) and torch._library.utils.is_inplace(op): + return _do_auto_functionalize_v2_for_inplace_operator( + ctx, op, schema, normalized_kwargs + ) + return _do_auto_functionalize_v2_for_generic_mutable_operator( + ctx, op, schema, normalized_kwargs + ) + + +def _do_auto_functionalize_v2_for_out_operator( + ctx: Any, + op: OpOverload, + schema: Any, + normalized_kwargs: dict[str, Any], +) -> Any: + """Handle functionalization for out= operators. + + Out= operators have write-only mutable args. These are not inputs to + auto_functionalized_v2; we encode their tensor properties so the dense + impl can create empty tensors. + """ + mutable_args_names, _ = get_mutable_args_from_schema(schema) + + # Save references to the original FunctionalTensors for post-call sync + out_arg_originals = [normalized_kwargs[name] for name in mutable_args_names] + + # Encode tensor properties and remove the actual out tensors from kwargs + for arg_name in mutable_args_names: + arg = normalized_kwargs[arg_name] + normalized_kwargs[f"_{arg_name}_size"] = arg.size() + normalized_kwargs[f"_{arg_name}_stride"] = arg.stride() + normalized_kwargs[f"_{arg_name}_dtype"] = arg.dtype + normalized_kwargs[f"_{arg_name}_device"] = arg.device + del normalized_kwargs[arg_name] + + unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type] + auto_func_kwargs = dict(unwrapped_kwargs, _all_bases=[]) + + with ctx.redispatch_to_next(): + unwrapped_outs = auto_functionalized_v2( + op, + **auto_func_kwargs, # type: ignore[arg-type] + ) + + # For out= ops, the functional HOP returns exactly the out tensors. + # auto_functionalized_v2 returns a bare tensor for single return, + # tuple for multiple. + results = unwrapped_outs if isinstance(unwrapped_outs, tuple) else (unwrapped_outs,) + for orig_arg, result in zip(out_arg_originals, results, strict=True): + ctx.replace(orig_arg, result) + ctx.commit_update(orig_arg) + ctx.sync(orig_arg) + + return ctx.wrap_tensors(unwrapped_outs) # type: ignore[arg-type] + + +def _do_auto_functionalize_v2_for_inplace_operator( + ctx: Any, + op: OpOverload, + schema: Any, + normalized_kwargs: dict[str, Any], +) -> Any: + """Handle functionalization for inplace operators. + + Inplace operators mutate their first positional argument (self) and return + it. Unlike out= operators (write-only), self is read by the operator, so + it must be passed as a base for clone analysis during reinplacing. + """ + mutable_args_names, mutable_args_types = get_mutable_args_from_schema(schema) + + self_arg_name = mutable_args_names[0] + self_arg = normalized_kwargs[self_arg_name] + + # self is both read and written; pass its base for clone analysis + base = self_arg if get_base(self_arg) is None else get_base(self_arg) + + arg_to_base_index: dict[str, Any] = {self_arg_name: 0} + write_view_information_to_args( + mutable_args_names, mutable_args_types, normalized_kwargs, arg_to_base_index + ) + del normalized_kwargs[self_arg_name] + + unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type] + all_bases_unwrapped = ctx.unwrap_tensors([base]) + auto_func_kwargs = dict(unwrapped_kwargs, _all_bases=all_bases_unwrapped) + + with ctx.redispatch_to_next(): + unwrapped_outs = auto_functionalized_v2( + op, + **auto_func_kwargs, # type: ignore[arg-type] + ) + + # HOP returns (op_result, mutated_self_base). + # op_result aliases mutated_self_base (inplace semantics). + unwrapped_result = unwrapped_outs[0] + unwrapped_mutated_base = unwrapped_outs[1] + + ctx.replace(base, unwrapped_mutated_base) + ctx.commit_update(base) + ctx.sync(base) + + return ctx.wrap_tensors(unwrapped_result) # type: ignore[arg-type] + + +def _do_auto_functionalize_v2_for_generic_mutable_operator( + ctx: Any, + op: Any, + schema: Any, + normalized_kwargs: dict[str, Any], +) -> Any: + """Handle functionalization for generic mutable operators via the + auto_functionalized_v2 HOP.""" + mutable_args_names, mutable_args_types = get_mutable_args_from_schema(schema) + + # A list of all bases of mutable args without duplication + all_bases: list[Any] = [] + all_bases_addresses: list[int] = [] + + # Map arg_name to the index of its base in all_bases. + arg_to_base_index: dict[str, Any] = {} + + def update_dict(tensor, arg_name, index=None): + base = tensor if get_base(tensor) is None else get_base(tensor) + + def set_result(base_index): + if index is None: + arg_to_base_index[arg_name] = base_index + else: + arg_to_base_index[arg_name][index] = base_index + + if not all_bases_addresses.__contains__(base._cdata): + all_bases_addresses.append(base._cdata) + all_bases.append(base) + set_result(len(all_bases) - 1) + else: + set_result(all_bases_addresses.index(base._cdata)) + + for arg_name in mutable_args_names: + arg = normalized_kwargs[arg_name] + if arg is None: + continue + + if isinstance(arg, list): + arg_to_base_index[arg_name] = {} + for i, tensor in enumerate(arg): + if tensor is None: + arg_to_base_index[arg_name].append(None) + continue + + update_dict(tensor, arg_name, i) + + else: + update_dict(arg, arg_name) + + # add view_meta for each args into unwrapped_kwargs. + write_view_information_to_args( + mutable_args_names, + mutable_args_types, + normalized_kwargs, + arg_to_base_index, + ) + + # remove mutated args from the kwargs (its a function of _all_bases now) + for arg_name in mutable_args_names: + del normalized_kwargs[arg_name] # type: ignore[arg-type] + + unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type] + if "self" in unwrapped_kwargs or "self_" in unwrapped_kwargs: + warnings.warn( + "Using `self` or `self_` as an argument in the definition of custom ops may lead to ambiguous parsing. " + "Please consider using a different name for this argument to avoid potential issues.", + stacklevel=2, + ) + all_basis_unwrapped = ctx.unwrap_tensors(all_bases) + + if "_all_bases" in unwrapped_kwargs: + raise AssertionError(f"_all_bases already in unwrapped_kwargs for {op}") + auto_func_kwargs = dict(unwrapped_kwargs, _all_bases=all_basis_unwrapped) + if isinstance(op, HigherOrderOperator): + if "_ops_schema" in unwrapped_kwargs: + raise AssertionError(f"_ops_schema already in unwrapped_kwargs for {op}") + # We pass in the tree_spec of tree_flatten(SchemaHolder) to make it proxable + auto_func_kwargs.update( + {"_op_schema": pytree.tree_flatten(SchemaHolder(schema))[1]} + ) + + with ctx.redispatch_to_next(): + unwrapped_outs = auto_functionalized_v2( + op, + **auto_func_kwargs, # type: ignore[arg-type] + ) + + unwrapped_actual_out: Any | tuple[Any] = ( + unwrapped_outs if len(all_bases) == 0 else unwrapped_outs[: -len(all_bases)] + ) + + unwrapped_mutable_out = ( + [] if len(all_bases) == 0 else unwrapped_outs[-len(all_bases) :] + ) + + if isinstance(op, HigherOrderOperator): + if len(schema.returns) <= 0: + raise AssertionError( + f"hop is expected to return at least one output {schema}." + ) + if len(unwrapped_actual_out) != len(schema.returns): + raise AssertionError( + f"Expected {len(schema.returns)} outputs, got {len(unwrapped_actual_out)}" + ) + else: + if len(schema.returns) == 0: + if unwrapped_actual_out[0] is not None: + raise AssertionError( + f"Expected None for op with no returns, got {unwrapped_actual_out[0]}" + ) + unwrapped_actual_out = None + elif len(schema.returns) == 1: + if len(unwrapped_actual_out) != 1: + raise AssertionError( + f"Expected 1 output, got {len(unwrapped_actual_out)}" + ) + unwrapped_actual_out = unwrapped_actual_out[0] + else: + if len(unwrapped_actual_out) != len(schema.returns): + raise AssertionError( + f"Expected {len(schema.returns)} outputs, got {len(unwrapped_actual_out)}" + ) + + for orig_arg, unwrapped_out in zip(all_bases, unwrapped_mutable_out): + # Can be None if input was `Tensor(a!)?` + if unwrapped_out is None: + continue + + # We only handle Tensor or List[Tensor] here for now. + def sync_update(o, orig_arg): + ctx.replace(orig_arg, o) + ctx.commit_update(orig_arg) + ctx.sync(orig_arg) + + if isinstance(unwrapped_out, torch.Tensor): + sync_update(unwrapped_out, orig_arg) + elif isinstance(unwrapped_out, list) and all( + isinstance(o, torch.Tensor) for o in unwrapped_out + ): + if len(orig_arg) != len(unwrapped_out): + raise AssertionError( + f"orig_arg length ({len(orig_arg)}) != unwrapped_out length ({len(unwrapped_out)})" + ) + for orig_a, o in zip(orig_arg, unwrapped_out): + sync_update(o, orig_a) + else: + raise RuntimeError( + f"unsupported type for auto-functionalization: {unwrapped_out}" + ) + + return ctx.wrap_tensors(unwrapped_actual_out) # type: ignore[arg-type] + + +# auto_functionalize functions +@auto_functionalized.py_impl(DispatchKey.CompositeExplicitAutograd) +def auto_functionalized_dense( + _mutable_op: OpOverload, + _only_clone_these_tensors: tuple[str, ...] | None = None, + **kwargs: Any, +) -> tuple[Any, tuple[Tensor, ...]]: + new_kwargs = dict(**kwargs) + result = [] + + _mutable_args_names, _ = get_mutable_args(_mutable_op) + for name in _mutable_args_names: + if ( + _only_clone_these_tensors is not None + and name not in _only_clone_these_tensors + ): + new_kwargs[name] = kwargs[name] + else: + new_kwargs[name] = ( + [clone_preserve_strides(x) for x in kwargs[name]] + if kwargs[name] is not None and isinstance(kwargs[name], list) + else ( + clone_preserve_strides(kwargs[name]) + if kwargs[name] is not None + else None + ) + ) + result.append(new_kwargs[name]) + out = _mutable_op(**new_kwargs) + + if isinstance(out, tuple): + return (*out, *result) # type: ignore[return-value] + else: + return (out, *result) # type: ignore[return-value] + + +@register_fake(auto_functionalized, skip_cache=True) +def auto_functionalized_fake( + _mutable_op: OpOverload, + **kwargs: Any, +) -> tuple[Any, tuple[Tensor, ...]]: + result = auto_functionalized_dense( + _mutable_op, _only_clone_these_tensors=None, **kwargs + ) + return result + + +@auto_functionalized.py_impl(ProxyTorchDispatchMode) +def auto_functionalized_proxy( + mode, + _mutable_op: OpOverload, + **kwargs: Any, +) -> tuple[Any, tuple[Tensor, ...]]: + with disable_proxy_modes_tracing(): + out = auto_functionalized(_mutable_op, **kwargs) + + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + out_proxy = mode.tracer.create_proxy( + "call_function", + auto_functionalized, + (_mutable_op,), + proxy_kwargs, + ) + result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + return result + + +@auto_functionalized.py_functionalize_impl +def auto_functionalized_func(ctx, _mutable_op, **kwargs): + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + with ctx.redispatch_to_next(): + result = auto_functionalized(_mutable_op, **unwrapped_kwargs) + return ctx.wrap_tensors(result) + + +# auto_functionalized_v2 functions +@auto_functionalized_v2.py_impl(DispatchKey.CompositeExplicitAutograd) +def auto_functionalized_v2_dense( + _mutable_op: _MutableOpType, + _only_clone_these_bases: tuple[int, ...] | None = None, + **kwargs: Any, +) -> tuple[Any, tuple[Tensor, ...]]: + _all_bases: list[Tensor] = kwargs.pop("_all_bases", []) + if _only_clone_these_bases is None: + _only_clone_these_bases = tuple(range(len(_all_bases))) + + if isinstance(_mutable_op, OpOverload): + schema: torch._C.FunctionSchema = _mutable_op._schema + else: + schema = pytree.tree_unflatten([], kwargs.pop("_op_schema")).schema + + if isinstance(_mutable_op, OpOverload): + _callable_op: HopInstance | OpOverload = _mutable_op + else: + if not isinstance(schema, HopSchema): + raise AssertionError(f"Expected HopSchema, got {type(schema)}") + _callable_op = HopInstance(_mutable_op, schema) + + _is_out = isinstance(_mutable_op, OpOverload) and torch._library.utils.is_out( + _mutable_op + ) + + op_kwargs_new, all_bases_new = _generate_new_op_kwargs_from_bases( + schema, + kwargs, + _all_bases, + _only_clone_these_bases, + _is_out, + ) + + out = call_op( + _callable_op, + tuple(), + op_kwargs_new, + ) + + if _is_out: + return out # type: ignore[return-value] + + if isinstance(out, tuple): + return (*out, *all_bases_new) # type: ignore[return-value] + else: + return (out, *all_bases_new) # type: ignore[return-value] + + +def _generate_new_op_kwargs_from_bases( + schema, kwargs, all_bases, _only_clone_these_bases, _is_out +): + mutable_args_names, mutable_args_types = get_mutable_args_from_schema(schema) + + if _is_out: + # For out= ops, _all_bases is empty. Create empty tensors from the + # metadata that was encoded by _do_auto_functionalize_v2_for_out_operator. + new_kwargs = dict(**kwargs) + created_out_tensors = [] + for arg_name in mutable_args_names: + size = new_kwargs.pop(f"_{arg_name}_size") + stride = new_kwargs.pop(f"_{arg_name}_stride") + dtype = new_kwargs.pop(f"_{arg_name}_dtype") + device = new_kwargs.pop(f"_{arg_name}_device") + t = torch.empty_strided(size, stride, dtype=dtype, device=device) + new_kwargs[arg_name] = t + created_out_tensors.append(t) + return new_kwargs, created_out_tensors + + args_view_info = read_view_information_from_args( + mutable_args_names, mutable_args_types, kwargs, all_bases + ) + + def maybe_copy(i, t): + if t is None: + return None + if i in _only_clone_these_bases: + return clone_preserve_strides(t) + else: + return t + + all_bases_new = [maybe_copy(i, t) for i, t in enumerate(all_bases)] + + # create new args + new_kwargs = dict(**kwargs) + + # re-generate all inputs from all_bases_new using args_view_info and add them to new_kwargs. + for arg_name in mutable_args_names: + if args_view_info[arg_name] is None: + new_kwargs[arg_name] = None + elif isinstance(args_view_info[arg_name], list): + new_kwargs[arg_name] = [] + for i, elem in enumerate(args_view_info[arg_name]): + if elem is None: + new_kwargs[arg_name].append(None) + else: + view_info = args_view_info[arg_name][i] + new_kwargs[arg_name].append( + view_info.regenerate_view(all_bases_new) + ) + else: + new_kwargs[arg_name] = args_view_info[arg_name].regenerate_view( + all_bases_new + ) + + return new_kwargs, all_bases_new + + +@register_fake(auto_functionalized_v2, skip_cache=True) +def auto_functionalized_v2_fake( + _mutable_op: _MutableOpType, + **kwargs: dict[str, Any], +) -> tuple[Any, tuple[Tensor, ...]]: + result = auto_functionalized_v2_dense( + _mutable_op, _only_clone_these_bases=None, **kwargs + ) + return result + + +@auto_functionalized_v2.py_impl(ProxyTorchDispatchMode) +def auto_functionalized_v2_proxy( + mode, + _mutable_op: _MutableOpType, + **kwargs: Any, +) -> tuple[Any, tuple[Tensor, ...]]: + if isinstance(_mutable_op, HigherOrderOperator): + # Note [materialize callable inputs as graph] + # Below code materializes the callable inputs to the hop as graph modules. + # kwargs may contain general callables, that are not proxable e.g. FunctionWithNoFreeVars + # this could happen when we auto_functionalize the backward of the hop, + # where backward fn is a callable that wraps forward graph module. + # This function materialize the callable args according to the schema of the hop. + + # We cannot materialize the callables in kwargs directly because the inputs to callable + # vary from hops to hop. To make the materialiation process generic to all hops, + # we trace a function that wraps the hop and let each hop itself figure out how to trace + # its callable inputs. Then we look at the schema of the traced hop node and replace the + # callable in original kwarg with the traced subgraphs. + # + # Specifically, we first trace a wrapped_fn that calls into the hop. Then we look for the + # hop node in the traced graph and graph module inputs to the hop. Finally, we replace the + # original kwarg's callable with the graph module. + all_bases = kwargs.get("_all_bases", []) + _only_clone_these_bases = kwargs.get("_only_clone_these_bases") + if _only_clone_these_bases is None: + _only_clone_these_bases = tuple(range(len(all_bases))) + + schema = pytree.tree_unflatten([], kwargs.get("_op_schema")).schema # type: ignore[arg-type] + new_kwargs, _ = _generate_new_op_kwargs_from_bases( + schema, + {k: v for k, v in kwargs.items() if k not in ("_all_bases", "_op_schema")}, + all_bases, + _only_clone_these_bases, + _is_out=False, + ) + + _, materialized_kwargs = materialize_callable_in_args( + HopInstance(_mutable_op, schema), tuple(), new_kwargs + ) + + # Only replace the callables in kwargs with the materialized subgraphs. + # The rest of the kwargs are kept unchanged. + subgraph_arg_names = { + arg_info.name + for arg_info in schema.arguments + if isinstance(arg_info.type, torch._C.AnyType) + } + for k, v in kwargs.items(): + if k in subgraph_arg_names and callable(v): + if k not in materialized_kwargs or not isinstance( + materialized_kwargs[k], torch.fx.GraphModule + ): + raise AssertionError( + f"Expected {k} to be in materialized_kwargs as a GraphModule" + ) + kwargs[k] = materialized_kwargs[k] + + with disable_proxy_modes_tracing(): + out = auto_functionalized_v2(_mutable_op, **kwargs) + + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + + if isinstance(_mutable_op, HigherOrderOperator): + + def _maybe_register_subgraph(val: Any): + if isinstance(val, torch.fx.GraphModule): + _, graph_name = unique_graph_id( + mode, prefix="auto_functionalized_subgraph" + ) + mode.tracer.root.register_module(graph_name, val) + return val + return val + + proxy_kwargs = pytree.tree_map(_maybe_register_subgraph, proxy_kwargs) + + out_proxy = mode.tracer.create_proxy( + "call_function", + auto_functionalized_v2, + (_mutable_op,), + proxy_kwargs, + ) + result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + return result + + +@auto_functionalized_v2.py_functionalize_impl +def auto_functionalized_v2_func(ctx, _mutable_op, **kwargs): + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + with ctx.redispatch_to_next(): + result = auto_functionalized_v2(_mutable_op, **unwrapped_kwargs) + return ctx.wrap_tensors(result) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/base_hop.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/base_hop.py new file mode 100644 index 0000000000000000000000000000000000000000..89095b60a2e2aa8cb2a88ff76ca7c1e2cfefb048 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/base_hop.py @@ -0,0 +1,279 @@ +# mypy: allow-untyped-defs + +import abc + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._dispatch.python import suspend_functionalization +from torch._higher_order_ops.auto_functionalize import FunctionalCallableWithEpilogue +from torch._higher_order_ops.utils import ( + check_input_alias_and_mutation_return_outputs, + HopInstance, + materialize_as_graph, + reenter_make_fx, + register_fake, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.functional_tensor import disable_functional_mode +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +class BaseHOP(HigherOrderOperator, abc.ABC): + """ + This is the "Base" HOP implementation for a HOP that looks like: + + call_subgraph_hop(subgraph, *operands, **kwargs) + + That is: + 1) the HOP stays alive until Inductor + 2) the HOP's semantics are subgraph(*operands) + 3) kwargs may be some config options but aren't passed directly to the subgraph. + + To use this, please subclass this class and override methods as necessary: + ``` + class InvokeQuant(BaseHOP): + def __init__(self): + return super().__init__("invoke_quant") + + + invoke_quant = InvokeQuant() + + + def g(x): + return x.sin().cos() + + + @torch.compile(backend="aot_eager") + def f(x): + return invoke_quant(g, x, scheme="nf4") + ``` + + NOTE: don't subclass BaseHOP out of tree! That is not allowed. All + usages must be in tree. + """ + + def __init__(self, hop_name) -> None: + super().__init__(hop_name) + + # Set up the registrations + # If you want to override any of these, override them in your subclass. + self.py_autograd_impl(self._call_Autograd) + self.py_functionalize_impl(self._call_Functionalize) + self.py_impl(ProxyTorchDispatchMode)(self._call_ProxyTorchDispatchMode) + register_fake(self, self._fake_impl, skip_cache=True) + self.py_impl(DispatchKey.CompositeExplicitAutograd)( + self._call_CompositeExplicitAutograd + ) + + def __call__(self, subgraph, *operands, **kwargs): + if not isinstance( + subgraph, + ( + torch.fx.GraphModule, + FunctionWithNoFreeVars, + FunctionalCallableWithEpilogue, + ), + ): + raise RuntimeError( + f"{self._name}: when calling this API without torch.compile, " + f"we require that the subgraph be a torch.fx.GraphModule (or " + f"a function we know doesn't have free variables)." + ) + # pyrefly: ignore [missing-attribute] + return super().__call__(subgraph, *operands, **kwargs) + + def _call_Autograd(self, subgraph, *operands, **kwargs): + if isinstance(subgraph, torch.fx.GraphModule): + pass + + # We assume the subgraph doesn't mutate inputs and there is no aliasing. + # In the PT2 stack, this is Dynamo's responsibility to figure out. + return BaseHOPFunction.apply(self, subgraph, kwargs, *operands) + + def _call_CompositeExplicitAutograd(self, subgraph, *operands, **kwargs): + from torch.utils._python_dispatch import _get_current_dispatch_mode + + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + return subgraph(*operands) + + def _call_ProxyTorchDispatchMode(self, proxy_mode, subgraph, *operands, **kwargs): + traced_graph = reenter_make_fx(subgraph)(*operands) + if not isinstance(proxy_mode.tracer, torch.fx.Tracer): + raise AssertionError( + f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}" + ) + qualname = proxy_mode.tracer.get_fresh_qualname("subgraph") + proxy_mode.tracer.root.register_module(qualname, traced_graph) + + node_args = (traced_graph, *operands) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) # type: ignore[attr-defined] + proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, kwargs) # type: ignore[attr-defined] + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", self, proxy_args, proxy_kwargs + ) + + out = self(subgraph, *operands, **kwargs) + return track_tensor_tree( + out, + out_proxy, + constant=None, + tracer=proxy_mode.tracer, # type: ignore[arg-type] + ) + + def _fake_impl(self, subgraph, *operands, **kwargs): + return subgraph(*operands) + + # NOTE [Support input mutation of hops] + # To support input mutation, hop's subgraph must be functionalized because many inductor passes are + # applied to subgraph recursively and only work on functional graph. However, we could inline an + # epilogue graph (i.e. the copy_) into the subgraph because this is how input mutation + # is implemented in the top-level graph when no hop is presented. All passes must have been and will be + # aware of the epilogue graph. + # + # Since we've supported input mutation for custom op with auto_functionalized, we share the infra for hops + # The plan is: + # 1. In hop's Functionalization key, it calls do_auto_functionalize_v2 if subgraph mutates input + # 2. In do_auto_functionalize_v2: + # a. we functionalize the callables in hop's argument. This is to make the subgraphs functional so we + # could recursively run passes on them. Also the epilogue graph is inlined at the end. + # b. we call auto_functionalized_v2 and pass in an additional schema in order to properly invoke + # the hop with normalized kwargs. + # 3. In inductor, we decompose the auto_functionalized hop by calling into the dense implementation, which + # copies the mutated inputs to the hop if necessary and call the hop. + # After these steps, the rest of the inductor stack knows how to fuse the copy_ in subgraph with other ops. + def _call_Functionalize(self, ctx, subgraph, *operands, **kwargs): + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, + ) + + # invoke_quant has non-proxable argument of type InvokeQuant that + # we cannot generate schema for. + if self is not torch.ops.higher_order.invoke_quant_packed: + hop_instance = HopInstance.create(self, subgraph, *operands, **kwargs) + if can_auto_functionalize(hop_instance): + return do_auto_functionalize_v2( + ctx.mode, hop_instance, (subgraph, *operands), kwargs + ) + + unwrapped_operands = ctx.unwrap_tensors(operands) + with ctx.redispatch_to_next(): + # We assume the subgraph doesn't mutate inputs and there is no aliasing. + # In the PT2 stack, this is Dynamo's responsibility to figure out. + functionalized_subgraph = FunctionWithNoFreeVars( + ctx.functionalize(subgraph) + ) + out = self(functionalized_subgraph, *unwrapped_operands, **kwargs) + return ctx.wrap_tensors(out) + + # pyrefly: ignore [bad-override] + def gen_schema(self, subgraph, *operands, **kwargs): + from .schema import HopSchemaGenerator + + subgraph = materialize_as_graph(subgraph, operands) + ( + inp_inp_alias, + inp_out_alias, + out_out_alias, + mutated_inp_idx, + output, + ) = check_input_alias_and_mutation_return_outputs(subgraph) + + if not ( + len(inp_inp_alias) == 0 + and len(inp_out_alias) == 0 + and len(out_out_alias) == 0 + ): + # TODO: turn this into an error. + # test_foreach_map_backward_binary_foreach_map_addrecip_op fails the alias test. + import warnings + + warnings.warn( + "Aliasing is not supported for HOP subgraph.\n" + f"{subgraph.print_readable(print_output=False)}\n" + f"Alias info: inp-inp alias: {inp_inp_alias}, inp-out alias: {inp_out_alias}, out-out alias{out_out_alias}" + f"This may lead to silent incorrectness.", + stacklevel=2, + ) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("subgraph", subgraph) + for idx, arg in enumerate(operands): + schema_gen.add_arg(f"arg{idx}", arg, is_mutated=idx in mutated_inp_idx) + + for name, arg in kwargs.items(): + schema_gen.add_arg(name, arg, default_value=arg, kw_only=True) + + for out in output: + schema_gen.add_output(out) + + return schema_gen.gen_schema() + + +class BaseHOPFunction(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx, hop, subgraph, kwargs, *operands): + ctx.hop = hop + ctx.operands = operands + ctx.subgraph = subgraph + ctx.kwargs = kwargs + + with torch._C._AutoDispatchBelowAutograd(): + return hop(subgraph, *operands, **kwargs) + + @staticmethod + def backward(ctx, *grad_outputs): + subgraph = ctx.subgraph + operands = ctx.operands + kwargs = ctx.kwargs + + # TODO: Something special needs to happen with min cut partitioner + with ( + suspend_functionalization(), + disable_functional_mode(), + torch.enable_grad(), + ): + with disable_proxy_modes_tracing(): + from .invoke_subgraph import create_fw_bw_graph + from .utils import _from_fun + + fw_inputs = pytree.tree_map(_from_fun, operands) + ( + _, + joint_graph, + _, + ) = create_fw_bw_graph(subgraph, fw_inputs, grad_outputs) + + # The joint graph returns (*grad_inputs, *fwd_outputs). + # We only need the grad_inputs. + def bwd_fn(*args): + operands = args[: -len(grad_outputs)] + grad_outs = args[-len(grad_outputs) :] + result = joint_graph(*operands, *grad_outs) + grad_inputs = result[: -len(grad_outputs)] + return grad_inputs + + return ( + None, + None, + None, + *ctx.hop( + FunctionWithNoFreeVars(bwd_fn), *operands, *grad_outputs, **kwargs + ), + ) + + +class FunctionWithNoFreeVars: + def __init__(self, fn): + self.fn = fn + + def __call__(self, *args, **kwargs): + return self.fn(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cond.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cond.py new file mode 100644 index 0000000000000000000000000000000000000000..a55255b7f248b102643bba8f06025beccd080baf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cond.py @@ -0,0 +1,793 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import contextlib +import logging +import warnings +from collections.abc import Callable +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._C._functorch import ( + _add_batch_dim, + get_unwrapped, + is_batchedtensor, + maybe_get_bdim, +) +from torch._functorch.utils import exposed_in +from torch._higher_order_ops.utils import ( + _maybe_run_with_interpreter, + check_input_alias_and_mutation_return_outputs, + create_bw_fn, + create_fn_remove_none, + fill_none_with_masks, + materialize_as_graph, + reenter_make_fx, + save_values_for_backward, + saved_values, + unique_graph_id, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.utils._python_dispatch import _get_current_dispatch_mode + + +log = logging.getLogger(__name__) + +""" +We're going to define a `cond_op` operation. +In order to do this, we need implementations for each of the dispatch keys. +""" + + +class CondOp(HigherOrderOperator): + def __init__(self): + super().__init__("cond") + + def __call__(self, pred, true_fn, false_fn, operands): + validate_subgraph_args_types(operands) + # pyrefly: ignore [missing-attribute] + return super().__call__(pred, true_fn, false_fn, operands) + + # pyrefly: ignore [bad-override] + def gen_schema(self, pred, true_fn, false_fn, operands): + from torch._higher_order_ops.schema import HopSchemaGenerator + from torch._higher_order_ops.utils import materialize_as_graph + + then_gm: torch.fx.GraphModule = materialize_as_graph(true_fn, operands) + else_gm: torch.fx.GraphModule = materialize_as_graph(false_fn, operands) + ( + _, + _, + _, + then_mutated_inputs, + then_outputs, + ) = check_input_alias_and_mutation_return_outputs(then_gm) + ( + _, + _, + _, + else_mutated_inputs, + else_outputs, + ) = check_input_alias_and_mutation_return_outputs(else_gm) + mutated_inputs = set(then_mutated_inputs) | set(else_mutated_inputs) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("pred", pred) + schema_gen.add_arg("true_fn", then_gm) + schema_gen.add_arg("false_fn", else_gm) + for idx, arg in enumerate(operands): + schema_gen.add_arg(f"operand{idx}", arg, is_mutated=idx in mutated_inputs) + + for out in then_outputs: + schema_gen.add_output(out) + schema_gen.add_schema_tree_spec(pred, true_fn, false_fn, operands) + return schema_gen.gen_schema() + + +cond_op = CondOp() + + +@exposed_in("torch") +def cond( + pred: bool | int | float | torch.Tensor, + true_fn: Callable, + false_fn: Callable, + operands: tuple | list = (), +) -> Any: + r""" + Conditionally applies `true_fn` or `false_fn`. + + .. warning:: + + `torch.cond` is a prototype feature in PyTorch. It has limited support for input and output types. + Please look forward to a more stable implementation in a future version of PyTorch. + Read more about feature classification at: https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + `cond` is structured control flow operator. That is, it is like a Python if-statement, + but has restrictions on `true_fn`, `false_fn`, and `operands` that enable it to be + capturable using torch.compile and torch.export. + + Assuming the constraints on `cond`'s arguments are met, `cond` is equivalent to the following:: + + def cond(pred, true_branch, false_branch, operands): + if pred: + return true_branch(*operands) + else: + return false_branch(*operands) + + Args: + pred (Union[bool, torch.Tensor]): A boolean expression or a tensor with one element, + indicating which branch function to apply. + + true_fn (Callable): A callable function (a -> b) that is within the + scope that is being traced. + + false_fn (Callable): A callable function (a -> b) that is within the + scope that is being traced. The true branch and false branch must + have consistent input and outputs, meaning the inputs have to be + the same, and the outputs have to be the same type and shape. Int + output is also allowed. We'll make the output dynamic by turning it + into a symint. + + operands (Tuple of possibly nested dict/list/tuple of torch.Tensor): A tuple of inputs to the + true/false functions. It can be empty if true_fn/false_fn doesn't require input. Defaults to (). + + Example:: + + def true_fn(x: torch.Tensor): + return x.cos() + + + def false_fn(x: torch.Tensor): + return x.sin() + + + return cond(x.shape[0] > 4, true_fn, false_fn, (x,)) + + Restrictions: + - The conditional statement (aka `pred`) must meet one of the following constraints: + + - It's a `torch.Tensor` with only one element, and torch.bool dtype + + - It's a boolean expression, e.g. `x.shape[0] > 10` or `x.dim() > 1 and x.shape[1] > 10` + + - The branch function (aka `true_fn`/`false_fn`) must meet all of the following constraints: + + - The function signature must match with operands. + + - The function must return a tensor with the same metadata, e.g. shape, + dtype, etc. + + - The function cannot have in-place mutations on global variables. + (Note: in-place tensor operations such as `add_` for intermediate results + are allowed in a branch) + + - The function can perform in-place mutations on its input tensors during inference (i.e., + when `torch.is_grad_enabled()` is False). + Note: When using `torch.compile()` with a non-constant predicate, the outputs will always + be new tensors that do not share object identity with the original inputs. + + Example:: + + def true_fn(x): + return x.sin_() + + + def false_fn(x): + return x + 1 + + + def f(x): + return cond(x.sum() > 0, true_fn, false_fn, (x,)) + + + x = torch.ones(4) + with torch.no_grad(): + result = torch.compile(f)(x) + assert result is not x # result is a new tensor, not the original x + + """ + if torch.compiler.is_dynamo_compiling(): + return cond_op(pred, true_fn, false_fn, operands) + + if isinstance(pred, (bool, int, float)): + # This is the non-strict export case. Strict export and torch.compile are + # handled above in dynamo. + if torch.compiler.is_exporting(): + warnings.warn( + "Pred is a Python constant. When used with torch.cond, it specializes on one of the branches." + " If you want torch.cond to preserve two branches, please make the predicate a boolean tensor or a SymBool.", + UserWarning, + stacklevel=2, + ) + # This is the eager case. We can just run the true or false branch. + if pred: + return true_fn(*operands) + else: + return false_fn(*operands) + + def _validate_input(pred, true_fn, false_fn, operands): + if not isinstance(pred, (bool, torch.Tensor, torch.SymBool)): + raise RuntimeError(f"Expected pred to be bool or tensor, but got {pred}.") + + if isinstance(pred, torch.Tensor) and pred.numel() != 1: + raise RuntimeError( + f"Expected pred to be bool or single-element tensor, but got {pred}." + ) + + if not callable(true_fn) or not callable(false_fn): + raise RuntimeError("Expect both branches to be callable.") + + if not isinstance(operands, (tuple, list)) or pytree.tree_any( + lambda t: not isinstance(t, torch.Tensor), operands + ): + raise RuntimeError( + "Expect operands to be a tuple of possibly nested dict/list/tuple that only " + f"consists of tensor leaves, but got {operands}." + ) + + _validate_input(pred, true_fn, false_fn, operands) + + if not torch._dynamo.is_dynamo_supported(): + raise RuntimeError("torch.cond requires dynamo support.") + + # Dynamo is expecting a callable with "__code__" attribute. + # We cannot directly pass cond_op to it. So we wrap it in a dummy function. + def _cond_op_wrapper(*args, **kwargs): + return cond_op(*args, **kwargs) + + from torch._higher_order_ops.utils import _hop_compile_and_call + + return _hop_compile_and_call(_cond_op_wrapper, (pred, true_fn, false_fn, operands)) + + +def trace_cond(proxy_mode, func_overload, pred, true_fn, false_fn, operands): + if not isinstance(operands, (list, tuple)): + raise AssertionError( + f"Cond operands must be a list or tuple of tensors and SymInts {operands}" + ) + + true_graph = reenter_make_fx(true_fn)(*operands) + false_graph = reenter_make_fx(false_fn)(*operands) + + true_outs = [] + false_outs = [] + for node in true_graph.graph.nodes: + if node.op == "output": + true_outs.extend(node.args) + + for node in false_graph.graph.nodes: + if node.op == "output": + false_outs.extend(node.args) + + flat_true_outs = pytree.arg_tree_leaves(*true_outs) + flat_false_outs = pytree.arg_tree_leaves(*false_outs) + if len(flat_true_outs) != len(flat_false_outs): + raise torch._dynamo.exc.CondOpArgsMismatchError( + f"Expected to return same number of outputs but got:" + f"\n true branch returns {len(flat_true_outs)} item(s)" + f"\n false branch returns {len(flat_false_outs)} item(s)" + ) + + i, true_name = unique_graph_id(proxy_mode, prefix="true_graph") + + false_name = f"false_graph_{i}" + if hasattr(proxy_mode.tracer.root, false_name): + raise AssertionError( + f"proxy_mode.tracer.root already has attribute {false_name}" + ) + + proxy_mode.tracer.root.register_module(true_name, true_graph) + proxy_mode.tracer.root.register_module(false_name, false_graph) + + args = (pred, true_graph, false_graph, operands) + + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {} + ) + + out = func_overload(pred, true_graph, false_graph, operands) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@cond_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def cond_op_dense(pred, true_fn, false_fn, operands): + if not all(isinstance(o, (torch.Tensor, int)) for o in operands): + raise AssertionError( + f"Dense implementation operands must be a list of tensors and ints {operands}" + ) + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + if pred: + return true_fn(*operands) + else: + return false_fn(*operands) + + +class CondAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + pred, + true_fn, + false_fn, + *operands, + ): + ctx._pred = pred + ctx._true_bw_fn = create_bw_fn( + true_fn, + operands, + ) + ctx._false_bw_fn = create_bw_fn( + false_fn, + operands, + ) + # We snapshot the dispatch keys in forward for materializing + # the bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + save_values_for_backward(ctx, operands) + + with torch._C._AutoDispatchBelowAutograd(): + return cond_op(pred, true_fn, false_fn, operands) + + @staticmethod + def backward(ctx, *flat_grads): + operands = saved_values(ctx) + args = operands + flat_grads + # TODO: we need to materialize the bw graphs because dynamo is unable to + # trace through the joint function when torch.compile torch.autograd.grad. + true_wrapped, grads_tensor_masks = create_fn_remove_none(ctx._true_bw_fn) + true_bw_gm = materialize_as_graph( + true_wrapped, + args, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + false_wrapped, _ = create_fn_remove_none(ctx._false_bw_fn) + false_bw_gm = materialize_as_graph( + false_wrapped, + args, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + grads = cond_op( + ctx._pred, + true_bw_gm, + false_bw_gm, + args, + ) + return None, None, None, *fill_none_with_masks(grads, grads_tensor_masks) + + +# Note: +# As long as one of the tensors in pred or operands requires grad, +# all the output would require grad with backward fn set to be the CondAutogradOp. +# This is consistent with autograd.Function's semantic. +@cond_op.py_autograd_impl +def cond_autograd(pred, true_fn, false_fn, operands): + return CondAutogradOp.apply( + pred, + true_fn, + false_fn, + *operands, + ) + + +@cond_op.py_impl(ProxyTorchDispatchMode) +def inner(mode, pred, true_fn, false_fn, operands): + return trace_cond(mode, cond_op, pred, true_fn, false_fn, operands) + + +@cond_op.py_impl(FakeTensorMode) +def cond_fake_tensor_mode(mode, pred, true_fn, false_fn, operands): + # Ignore here, because if you've gotten here but you're not manually + # tracing the inner graphs, that means that you intend to reuse the graph + # directly. Which means the old unbacked symbol bindings are appropriate. + # This strategy will not work if unbacked symbols can escape. + ignore_fresh_unbacked = contextlib.nullcontext() + if mode.shape_env: + ignore_fresh_unbacked = mode.shape_env.ignore_fresh_unbacked_symbols() + + with mode, ignore_fresh_unbacked: + flat_true_outs, true_out_spec = pytree.tree_flatten(true_fn(*operands)) + flat_false_outs, false_out_spec = pytree.tree_flatten(false_fn(*operands)) + if true_out_spec != false_out_spec: + raise RuntimeError( + "Unmatched output spec from torch.cond branches: " + f"true branch tree_spec {true_out_spec} vs false branch tree_spec {false_out_spec}." + ) + + merged_outs = [] + for true_out, false_out in zip(flat_true_outs, flat_false_outs): + merged_outs.append(_merge_output(true_out, false_out, mode)) + return pytree.tree_unflatten(merged_outs, true_out_spec) + + +def check_tensor_meta_match( + t1: torch.Tensor, t2: torch.Tensor, attr_names: tuple[str, ...], msg_prefix: str +) -> None: + def _get_attr_maybe_call(t: torch.Tensor, attr_name: str) -> Any: + attr = getattr(t, attr_name) + if callable(attr): + return attr() + return attr + + for attr_name in attr_names: + lattr = _get_attr_maybe_call(t1, attr_name) + rattr = _get_attr_maybe_call(t2, attr_name) + torch._check( + lattr == rattr, + lambda: f"{msg_prefix} expected same {attr_name} but got {lattr} and {rattr}.", + ) + + +def _merge_ints_to_symint( + values: list[int], mode: FakeTensorMode +) -> int | torch.SymInt: + """Merge N concrete ints into a single unbacked SymInt bounded [min, max]. + + Returns the value unchanged when all values are equal. + """ + if all(v == values[0] for v in values): + return values[0] + if mode.shape_env is None: + raise AssertionError("mode.shape_env is None") + merged = mode.shape_env.create_unbacked_symint() + mode.shape_env.constrain_symbol_range(merged.node.expr, min(values), max(values)) + return merged + + +def _merge_output( + a: torch.Tensor | int | None, + b: torch.Tensor | int | None, + mode: FakeTensorMode, +): + from torch.fx.experimental.symbolic_shapes import ( + has_free_unbacked_symbols, + SymIntEqByExpr, + ) + + if a is None or b is None: + if not (a is None and b is None): + raise AssertionError(f"expected both a and b to be None, got a={a}, b={b}") + return None + + def min_max(s0, s1): + def _bound(s0, lower_bound: bool): + if isinstance(s0, int): + return s0 + r = mode.shape_env.var_to_range.get( # type: ignore[union-attr] + s0.node.expr, + torch.utils._sympy.value_ranges.ValueRanges.unknown(), + ) + return r.lower if lower_bound else r.upper + + return min(_bound(s0, True), _bound(s1, True)), max( + _bound(s0, False), _bound(s1, False) + ) + + if type(a) is int and type(b) is int: + return _merge_ints_to_symint([a, b], mode) + + if not (type(a) is FakeTensor and type(b) is FakeTensor): + raise AssertionError( + f"expected both a and b to be FakeTensor, got a={type(a)}, b={type(b)}" + ) + + # Note: we don't check size, stride because + # they'll be merged with unbacked symints if they differ. + _meta_to_check = { + "dtype", + "device", + "layout", + "dim", + "is_quantized", + "is_conj", + "is_sparse", + "storage_offset", + } + check_tensor_meta_match( + a, + b, + tuple(_meta_to_check), + msg_prefix="When merging two branches' output in torch.cond, ", + ) + # NYI + if a.is_quantized or b.is_quantized: + raise AssertionError("quantized tensors not yet implemented") + if a.is_sparse or b.is_sparse: + raise AssertionError("sparse tensors not yet implemented") + if a.is_conj() or b.is_conj(): + raise AssertionError("conjugate tensors not yet implemented") + + """ + Step 1: create unbacked symints for sizes that are different + along the same axis. For example: + a.size is [s0, 4, s0, 5, 4, 5] + b.size is [s1, 4, s2, 8, 4, 7] + merged_size will be [u0, 4, u1, u2, 4, u3], where + u0 has range [min(s0, s1), max(s0, s1)] + u1 has range [min(s0, s2), max(s0, s2)] + u2 has range [5, 8] + u3 has range [5, 7] + """ + merged_size: list[int | torch.SymInt] = [] + + def _has_unbacked_symbols(s: int | torch.SymInt) -> bool: + if isinstance(s, int): + return False + else: + return has_free_unbacked_symbols(s.node.expr) + + for s0, s1 in zip(a.size(), b.size()): + # If there are unbacked symbols leaked out of true_branch or false_branch + # we need to merge them with a new unbacked symbol and track in parent graph. + if ( + not _has_unbacked_symbols(s0) + and not _has_unbacked_symbols(s1) + and SymIntEqByExpr(s0) == SymIntEqByExpr(s1) + ): + merged_size.append(s0) + else: + if mode.shape_env is None: + raise AssertionError("mode.shape_env is None") + new_size = mode.shape_env.create_unbacked_symint() + mode.shape_env.constrain_symbol_range(new_size.node.expr, *min_max(s0, s1)) + merged_size.append(new_size) + + """ + This follows the logic in symbolic_shapes._compute_symbolic_stride + Step 2: Since tensor stride is an accumulative multiplication of the sizes, which is a permutated + (due to view ops) non-descending sequence. + + Case 1: No size is 1. In this case, strides have unique values. + For example, suppose we have a tensor with: + size [3, 4, 3, 5, 4, 5], + stride (1200, 300, 1, 12, 3, 60), + merged_size [u0, u1, u2, u3, u4, u5]. + + We visit the strides in ascending order: 1, 3, 12, 60, 300, 1200. In each step, we check whether + the current stride is bounded or not and bound next stride by setting. + stride_expr[next_stride] = current_stride_expr * current_size_expr + 1st round: + current_stride is 1, current_size is 3, so next_stride is 1 * 3 = 3, + current_stride_expr is set to 1, current_size_expr is u2, so stride_expr[3] is therefore 1 * u2 = u2 + 2nd round: + current_stride is 3, current_size is 4, so next_stride is 3 * 4 = 12, + current_stride_expr is stride_expr[3] i.e. u2, current_size_expr is u4, so stride_expr[12] = u2 * u4 + ... + + Case 2: At least one dimension has size 1, which can produce duplicates in strides. + In this case, theoretically, we cannot uniquely determine the expr of strides because + the accessing stride_expr with same key in different order causes the final stride expression + to be different. + + Suppose we have: + size: (3, 1) + stride: (1, 1) + merged_size: (u0, u1) + + The stride expr could either be (u1, 1) or (1, u0) depending on whether we start with u1 or u0. + For this reason, we try to break tie by sorting via descending index so we always get (u1, 1). + + Note that backend might optimize the strides anyway so this is usually not a problem as long + as two branches matches. See relevant discussions in https://github.com/pytorch/pytorch/issues/142024. + + Case 3: Dim has 0 stride. 0 stride doesn't participate in the accumulative multiplication of + sizes. So they're always treated as constant even if their corresponding size is turned into unbacked symint. + + Suppose we have: + size: (3, 3) + stride: (0, 1) + merged_size: (u0, u1) + + The merged stride would be (0, 1) + """ + + def _bound_stride( + a_ex_size: torch.Size, + b_ex_size: torch.Size, + a_ex_stride: tuple[int, ...], + b_ex_stride: tuple[int, ...], + merged_size: list[int | torch.SymInt], + ) -> list[int | torch.SymInt]: + from torch._inductor.ir import get_stride_order + + a_sorted_stride_idx = get_stride_order(a_ex_stride, mode.shape_env) + b_sorted_stride_idx = get_stride_order(b_ex_stride, mode.shape_env) + + a_stride_li: list[tuple[int | torch.SymInt, int] | None] = [None] * len( + a_ex_stride + ) + b_stride_li: list[tuple[int | torch.SymInt, int] | None] = [None] * len( + b_ex_stride + ) + for i, idx in enumerate(a_sorted_stride_idx): + a_stride_li[idx] = (a_ex_stride[i], -i) + for i, idx in enumerate(b_sorted_stride_idx): + b_stride_li[idx] = (b_ex_stride[i], -i) + + for a_pair, b_pair in zip(a_stride_li, b_stride_li): + if a_pair is None or b_pair is None: + raise AssertionError( + f"expected a_pair and b_pair to be non-None, got a_pair={a_pair}, b_pair={b_pair}" + ) + _, a_idx = a_pair + _, b_idx = b_pair + + if a_idx != b_idx: + raise RuntimeError( + f"The sorted order of strides of the two branches' output doesn't match." + f"this indicates the contiguousness of the two branches are different. " + f"True branch has stride {a_ex_stride} but false branch has stride {b_ex_stride}." + f"Consider using contiguous() to make the two branches have the same contiguousness." + ) + + def _maybe_expr(s: int | torch.SymInt): + if isinstance(s, int): + return s + return s.node.expr + + a_stride_expr: dict[Any, int | torch.SymInt] = {} + b_stride_expr: dict[Any, int | torch.SymInt] = {} + merged_strides: list[int | torch.SymInt] = [None] * len(a_ex_stride) # type: ignore[list-item] + for a_pair, b_pair in zip(a_stride_li, b_stride_li): + if a_pair is None or b_pair is None: + raise AssertionError( + f"expected a_pair and b_pair to be non-None, got a_pair={a_pair}, b_pair={b_pair}" + ) + a_val, neg_i = a_pair + b_val, _ = b_pair + + i = -neg_i + if a_val == 0: + if b_val != 0: + raise AssertionError( + f"expected b_val == 0 when a_val == 0, got a_val={a_val}, b_val={b_val}" + ) + merged_strides[i] = 0 + continue + + if _maybe_expr(a_val) in a_stride_expr: + a_expr = a_stride_expr[_maybe_expr(a_val)] + if b_stride_expr[_maybe_expr(b_val)] != a_expr: + raise AssertionError( + f"a_stride_expr:{a_stride_expr}, b_stride_expr:{b_stride_expr}" + ) + merged_strides[i] = a_expr + else: + if a_val == 1: + if b_val != 1: + raise AssertionError( + f"expected b_val == 1 when a_val == 1, got b_val={b_val}" + ) + a_stride_expr[_maybe_expr(a_val)] = 1 + b_stride_expr[_maybe_expr(b_val)] = 1 + merged_strides[i] = 1 + else: + # If we cannot find the expr of a_val in a_stride_expr, it means + # the strides is not a simple accumulative multiplication of sizes. + # In this case, we cannot determine the expr of strides from the new + # shapes so we error out and hint users to call contiguous(). + raise RuntimeError( + f"It seems one of cond's output stride is not a simple accumulative multiplication of sizes. " + f"This could be because cond returns a slice of a tensor, which is not dense in memory. " + f"True branch has size {a_ex_size}, stride {a_ex_stride} and false branch has size {b_ex_size} " + f"stride {b_ex_stride}. Hint: can call t.contiguous(). " + ) + nxt_merged_stride_expr = merged_strides[i] * merged_size[i] + a_stride_expr[_maybe_expr(a_val * a_ex_size[i])] = nxt_merged_stride_expr + b_stride_expr[_maybe_expr(b_val * b_ex_size[i])] = nxt_merged_stride_expr + # fake tensors accumulate contiguous strides as stride * max(size, 1) + a_max_key = _maybe_expr(a_val * torch.sym_max(a_ex_size[i], 1)) + b_max_key = _maybe_expr(b_val * torch.sym_max(b_ex_size[i], 1)) + a_stride_expr.setdefault(a_max_key, nxt_merged_stride_expr) + b_stride_expr.setdefault(b_max_key, nxt_merged_stride_expr) + return merged_strides + + merged_stride: list[int | torch.SymInt] = _bound_stride( + a.size(), b.size(), a.stride(), b.stride(), merged_size + ) + + with mode: + return torch.empty_strided( + merged_size, merged_stride, dtype=a.dtype, device=a.device + ) + + +@cond_op.py_functionalize_impl +def cond_func(ctx, pred, true_fn, false_fn, inputs): + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, + ) + from torch._higher_order_ops.utils import _check_alias_and_mutation, HopInstance + + hop_instance = HopInstance.create(cond_op, pred, true_fn, false_fn, inputs) + # For now, we only support auto-functionalization for cond when using python + # functionalization mode + if can_auto_functionalize(hop_instance) and hasattr(ctx, "mode"): + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + tuple(pytree.tree_flatten((pred, true_fn, false_fn, inputs))[0]), + {}, + ) + + unwrapped_inputs = ctx.unwrap_tensors(inputs) + unwrapped_pred = ctx.unwrap_tensors(pred) + with ctx.redispatch_to_next(): + functional_true = ctx.functionalize(_maybe_run_with_interpreter(true_fn)) + functional_false = ctx.functionalize(_maybe_run_with_interpreter(false_fn)) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + for branch, branch_name in [(true_fn, "cond_true"), (false_fn, "cond_false")]: + _check_alias_and_mutation( + branch, unwrapped_inputs, branch_name, pre_dispatch + ) + + cond_return = cond_op( + unwrapped_pred, functional_true, functional_false, unwrapped_inputs + ) + return ctx.wrap_tensors(cond_return) + + +@cond_op.py_impl(torch._C._functorch.TransformType.Vmap) +def cond_batch_rule(interpreter, pred, true_fn, false_fn, inputs): + if not isinstance(inputs, (list, tuple)): + raise AssertionError( + f"Cond inputs must be a list or tuple of tensors, got {type(inputs)}" + ) + if not all(isinstance(i, torch.Tensor) for i in inputs): + raise AssertionError( + f"Cond inputs must be a list of tensors, got {[type(i) for i in inputs]}" + ) + + pred_is_batched = isinstance(pred, torch.Tensor) and is_batchedtensor(pred) + pred_ = get_unwrapped(pred) if pred_is_batched else pred + + # unbatched tensors are not vmapped + tensors, in_dims = zip( + *[ + (get_unwrapped(t), maybe_get_bdim(t)) if is_batchedtensor(t) else (t, None) + for t in inputs + ] + ) + + if pred_is_batched: + # prepend "pred" and vmap everything + tensors = (pred_,) + tensors + in_dims = (0,) + in_dims + + def fn(p, *args): + t = true_fn(*args) + f = false_fn(*args) + return torch.where(p, t[0], f[0]) + + with interpreter.lower(): + result = torch.vmap(fn, in_dims=in_dims)(*tensors) + + else: + # predicate is known at this stage and it is a boolean expression or a + # tensor with one element. + true_fn = torch.vmap(true_fn, in_dims=in_dims) + false_fn = torch.vmap(false_fn, in_dims=in_dims) + + with interpreter.lower(): + result = cond_op(pred, true_fn, false_fn, tensors) + + if not isinstance(result, tuple): + result = (result,) + lvl = interpreter.level() + return tuple(_add_batch_dim(r, 0, lvl) for r in result) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cudagraph_conditional_nodes.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cudagraph_conditional_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..d8bc93d1a58f5c20c4de9f997bce7e151569f1de --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cudagraph_conditional_nodes.py @@ -0,0 +1,238 @@ +# mypy: allow-untyped-defs +from collections.abc import Generator +from contextlib import contextmanager + +import torch +import torch.utils._pytree as pytree +from torch.utils._python_dispatch import TorchDispatchMode + + +class CUDAGraphCaptureControlFlowOpDispatchMode(TorchDispatchMode): + @classmethod + def ignore_compile_internals(cls) -> bool: + return True + + def __init__( + self, + ) -> None: + self.supports_higher_order_operators = True + super().__init__() + + def __torch_dispatch__( + self, + func, + types, + args=(), + kwargs=None, + ): + kwargs = {} if kwargs is None else kwargs + if func is torch.ops.higher_order.cond: + # Re-enter the mode to support nested conditionals + _check_no_cond_kwargs(kwargs) + with self: + return if_else_node(*args) + if func is torch.ops.higher_order.while_loop: + # Re-enter the mode to support nested control flow + _check_no_while_loop_kwargs(kwargs) + with self: + return while_loop_node(*args) + return func(*args, **kwargs) + + +class ControlFlowOpWarmupDispatchMode(TorchDispatchMode): + """Warm up control-flow subgraphs before CUDA graph capture. + + Data-dependent control flow does not necessarily execute every subgraph, so + operations in an untaken torch.cond branch or a torch.while_loop body may + not have been warmed up. This mode uses a relaxed stream capture, whose + final CUDA graph is discarded, to warm up both cond branches and execute a + while_loop body once. This works because stream capture does not execute GPU + code and the branch and body functions are FX graphs without CPU side + effects. + """ + + @classmethod + def ignore_compile_internals(cls) -> bool: + return True + + def __init__( + self, + ) -> None: + super().__init__() + self.supports_higher_order_operators = True + self.capture_stream = torch.cuda.Stream() + + def __torch_dispatch__( + self, + func, + types, + args=(), + kwargs=None, + ): + kwargs = {} if kwargs is None else kwargs + + # Warm up both sides of this torch.cond() + if func is torch.ops.higher_order.cond: + if torch.cuda.is_current_stream_capturing(): + # This is a call to torch.cond() nested within another + # control-flow function. + _check_no_cond_kwargs(kwargs) + with self: + # We re-enter the mode in case of nested calls to torch.cond() + return if_else_node(*args) + else: + _check_no_cond_kwargs(kwargs) + with ( + torch.cuda.graph( + torch.cuda.CUDAGraph(), + pool=None, + stream=self.capture_stream, + capture_error_mode="relaxed", + ), + self, + ): + if_else_node(*args) + + return func(*args, **kwargs) + elif func is torch.ops.higher_order.while_loop: + _check_no_while_loop_kwargs(kwargs) + if torch.cuda.is_current_stream_capturing(): + # This is a call to torch.while_loop() nested within another + # control-flow function. + with self: + return while_loop_node(*args) + else: + with ( + torch.cuda.graph( + torch.cuda.CUDAGraph(), + pool=None, + stream=self.capture_stream, + capture_error_mode="relaxed", + ), + self, + ): + while_loop_node(*args) + + return func(*args, **kwargs) + else: + return func(*args, **kwargs) + + +def _check_no_cond_kwargs(kwargs) -> None: + if kwargs: + raise RuntimeError("CUDA graph conditional torch.cond does not support kwargs") + + +def _check_no_while_loop_kwargs(kwargs) -> None: + if kwargs: + raise RuntimeError( + "CUDA graph conditional torch.while_loop does not support kwargs" + ) + + +def _is_boolean_scalar_cuda_tensor(pred: object) -> bool: + return ( + isinstance(pred, torch.Tensor) + and pred.size() == torch.Size([]) + and pred.dtype == torch.bool + and pred.is_cuda + ) + + +@contextmanager +def _if_body(pred: torch.Tensor) -> Generator[None, None, None]: + current_cuda_graph = torch.cuda.CUDAGraph.get_currently_capturing_graph() + current_cuda_graph.begin_capture_to_if_node(pred) + try: + yield + finally: + current_cuda_graph.end_capture_to_conditional_node() + + +def if_else_node(pred: torch.Tensor, true_fn, false_fn, operands): + if not pred.is_cuda: + raise ValueError( + "Conditions must be on a cuda device to use conditional node in cuda graphs" + ) + # if-else is not supported until CUDA 12.8. Therefore, we use two + # if conditions, where one evaluates !pred + outs = [] + + for lazy_pred, fn in [ + (lambda: pred, true_fn), + (lambda: torch.logical_not(pred), false_fn), + ]: + with _if_body(lazy_pred()): + outs.append(fn(*operands)) + + # The output of the else branch gets copied into the + # output of the if branch. This is done because the rest + # of the cudagraph after the conditional node has fixed + # inputs, so we need to merge the two outputs into a + # single output. + if len(outs) == 2: + for if_out, else_out in zip( + pytree.tree_iter(outs[0]), pytree.tree_iter(outs[1]) + ): + if_out.copy_(else_out) + return outs[0] + + +@contextmanager +def _while_body(pred: torch.Tensor): + current_cuda_graph = torch.cuda.CUDAGraph.get_currently_capturing_graph() + current_cuda_graph.begin_capture_to_while_node(pred) + try: + yield current_cuda_graph + finally: + current_cuda_graph.end_capture_to_conditional_node() + + +def while_loop_node( + cond_fn, + body_fn, + carried_inputs, + additional_inputs, +): + flat_carried_inputs, carried_spec = pytree.tree_flatten(carried_inputs) + if not all(isinstance(inp, torch.Tensor) for inp in flat_carried_inputs): + raise RuntimeError( + "CUDA graph while_loop conditional nodes only support tensor carried_inputs" + ) + + loop_carried = pytree.tree_map_only( + torch.Tensor, lambda inp: inp.clone(), carried_inputs + ) + flat_loop_carried = pytree.tree_leaves(loop_carried) + + pred = cond_fn(*loop_carried, *additional_inputs) + if not _is_boolean_scalar_cuda_tensor(pred): + raise RuntimeError( + f"cond_fn must return a boolean scalar CUDA tensor but got {pred}" + ) + + with _while_body(pred) as current_cuda_graph: + body_out = body_fn(*loop_carried, *additional_inputs) + flat_body_out, body_out_spec = pytree.tree_flatten(body_out) + if body_out_spec != carried_spec: + raise RuntimeError( + "body_fn should return the same pytree structure as carried_inputs" + ) + if not all(isinstance(out, torch.Tensor) for out in flat_body_out): + raise RuntimeError( + "CUDA graph while_loop conditional nodes only support tensor " + "body_fn outputs" + ) + + for carried, out in zip(flat_loop_carried, flat_body_out): + if carried.data_ptr() != out.data_ptr(): + carried.copy_(out) + + pred = cond_fn(*loop_carried, *additional_inputs) + if not _is_boolean_scalar_cuda_tensor(pred): + raise RuntimeError( + f"cond_fn must return a boolean scalar CUDA tensor but got {pred}" + ) + current_cuda_graph.set_conditional_handle_for_current_node(pred) + + return loop_carried diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/effects.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/effects.py new file mode 100644 index 0000000000000000000000000000000000000000..9806e14d4edbf1a45b7d438f24da681e32926daa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/effects.py @@ -0,0 +1,342 @@ +# mypy: allow-untyped-defs +from typing import Any, cast, Union + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.invoke_leaf_function import invoke_leaf_function +from torch._higher_order_ops.print import print as hop_print +from torch._higher_order_ops.schema import HopSchema +from torch._higher_order_ops.torchbind import call_torchbind +from torch._higher_order_ops.utils import register_fake +from torch._library.custom_ops import CustomOpDef +from torch._library.effects import EffectType +from torch._library.utils import RegistrationHandle +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +_op_identifier = Union[ + str, + "torch._ops.OpOverload", + "torch._library.custom_ops.CustomOpDef", + "torch._ops.HigherOrderOperator", +] +OpType = Union["torch._ops.HigherOrderOperator", "torch._ops.OpOverload"] + +_EffectType = EffectType + + +def _get_op_qualname(op: _op_identifier) -> str: + """Convert an op identifier to a qualified string key.""" + if isinstance(op, torch._ops.OpOverload): + return op._name + elif isinstance(op, torch._ops.HigherOrderOperator): + return f"{op.namespace}::{op.name()}" + elif isinstance(op, CustomOpDef): + return op._qualname + elif isinstance(op, str): + return op + + raise ValueError(f"Invalid operator input {op}") + + +def _register_effectful_op( + op: _op_identifier, effect: EffectType | None +) -> RegistrationHandle: + qualname = _get_op_qualname(op) + entry = torch._library.simple_registry.singleton.find(qualname) + handle = entry.effect.register(effect) + return handle + + +def _get_effect(op: _op_identifier) -> _EffectType | None: + qualname = _get_op_qualname(op) + entry = torch._library.simple_registry.singleton.find(qualname) + return entry.effect.effect + + +_register_effectful_op("aten::_print", _EffectType.ORDERED) +# _linalg_check_errors has no tensor output, but it raises on invalid linalg +# results and must be preserved by functionalization/DCE. +_register_effectful_op("aten::_linalg_check_errors", _EffectType.ORDERED) +_register_effectful_op("profiler::_record_function_exit._RecordFunction", None) +_register_effectful_op(call_torchbind, _EffectType.ORDERED) +_register_effectful_op(hop_print, _EffectType.ORDERED) +_register_effectful_op(invoke_leaf_function, _EffectType.ORDERED) + + +class WithEffects(HigherOrderOperator): + """ + with_effects(token, op, args, kwargs) -> (new_token, op_results) + + This HOP helps ensure ordering between side effectful ops like prints or ops + using torchbind objects. This is needed to ensure a traced graph from + AOTAutograd is functional so that future optimization passes do not reorder + these operators. This is done through threading "effect tokens" through the + graph to enforce data dependence between side effectful ops. + + The tokens are basically dummy values (torch.tensor([])). We create a token + per "effect type", which are enumerated in the _EffectType enum. + """ + + def __init__(self) -> None: + super().__init__("with_effects") + + def __call__( + self, + token, + op: OpType, + *args: tuple[Any, ...], + **kwargs: dict[str, Any], + ) -> tuple[Any, ...]: + if not isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload)): + raise AssertionError( + f"op must be HigherOrderOperator or OpOverload, got {type(op)}" + ) + if has_aliasing(op): + raise AssertionError("Ops with aliasing is not supported") + if not isinstance(kwargs, dict): + raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}") + # pyrefly: ignore [missing-attribute] + return super().__call__(token, op, *args, **kwargs) + + +with_effects = WithEffects() + + +def has_aliasing(op: OpType): + # NOT FOR PUBLIC USE + if isinstance(op, torch._ops.HigherOrderOperator): + return False + + for arg in op._schema.arguments: + if arg.alias_info is not None: + return True + for arg in op._schema.returns: + if arg.alias_info is not None: + return True + return False + + +def has_effects(op) -> bool: + return ( + isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload)) + and not has_aliasing(op) + and _get_effect(op) is not None + ) + + +def new_token_tensor() -> torch.Tensor: + return torch.tensor([]) + + +@with_effects.py_impl(DispatchKey.CompositeExplicitAutograd) +def with_effects_dense( + token: torch.Tensor, + op: torch._ops.OpOverload, + *args: tuple[Any, ...], + **kwargs: dict[str, Any], +) -> tuple[torch.Tensor, ...]: + out = op(*args, **kwargs) + new_token = new_token_tensor() + # [NOTE: with_effects return type] + # Note that we should only do *out for tuple type, but not list type. + # This is to match the schema of the op. + # For tuple output, the length of schema output is the same as the length of out. + # For list output, the length of schema output is 1 (e.g. Tensor[]) regardless of the + # length of the list. + if isinstance(out, tuple): + return (new_token, *out) + return (new_token, out) + + +@register_fake(with_effects, skip_cache=True) +def with_effects_fake( + token: torch.Tensor, + op: torch._ops.OpOverload, + *args: tuple[Any, ...], + **kwargs: dict[str, Any], +) -> tuple[torch.Tensor, ...]: + result = with_effects_dense(token, op, *args, **kwargs) + return result + + +@with_effects.py_impl(ProxyTorchDispatchMode) +def with_effects_proxy( + mode, + token: torch.Tensor, + op: torch._ops.OpOverload, + *args: tuple[Any, ...], + **kwargs: dict[str, Any], +) -> tuple[torch.Tensor, ...]: + with disable_proxy_modes_tracing(): + out = with_effects(token, op, *args, **kwargs) + + proxy_token = mode.tracer.unwrap_proxy(token) + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + + from torch.fx.node import has_side_effect + + # To avoid the being DCEed by graph.eliminate_dead_code if they. + # don't have output or their outputs are not used. + has_side_effect(op) + + out_proxy = mode.tracer.create_proxy( + "call_function", + with_effects, + (proxy_token, op, *proxy_args), + proxy_kwargs, + ) + result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + return result + + +with_effects.fallthrough(DispatchKey.AutogradCPU) +with_effects.fallthrough(DispatchKey.AutogradCUDA) + + +@with_effects.py_functionalize_impl +def with_effects_functional( + ctx, + token: torch.Tensor, + op: torch._ops.OpOverload, + *args: tuple[Any, ...], + **kwargs: dict[str, Any], +) -> tuple[torch.Tensor, ...]: + # with_effects is already functional, so just re-emit it. + unwrapped_token, unwrapped_args, unwrapped_kwargs = ctx.unwrap_tensors( + [token, args, kwargs] + ) + with ctx.redispatch_to_next(): + result = with_effects(unwrapped_token, op, *unwrapped_args, **unwrapped_kwargs) + return ctx.wrap_tensors(result) + + +_EFFECTFUL_HOPS_WITH_SCHEMA = {hop_print, invoke_leaf_function} + + +def _get_schema(op, args, kwargs: dict | None = None) -> torch.FunctionSchema: + if isinstance(op, torch._ops.OpOverload): + return op._schema + elif op == call_torchbind: + return getattr(args[0], args[1]).schema + elif op in _EFFECTFUL_HOPS_WITH_SCHEMA: + extra_kwargs = kwargs or {} + return op.gen_schema(*args, **extra_kwargs) + else: + raise RuntimeError(f"Unable to get schema for op {op}") + + +def handle_effects( + allow_token_discovery: bool, + tokens: dict[_EffectType, torch.Tensor], + op: OpType, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> Any: + """ + Args: + allow_token_discovery: Whether or not we are discovering tokens. If this + is true, we will create a token for every side effect type seen that + does not have a token assigned yet. If this is false, the tokens + should've all been created ahead of time, so we will error if there is + no token mapping to every effect type. + + tokens: Map of effect type to tokens. This is to chain operators of the + same effects together so that they do not get reordered in later + optimization passes. + """ + + # Get a token. We can't do `tokens.get(op, torch.tensor([]))` because + # this will create an empty tensor during proxy mode tracing if the token + # doesn't exist. But the tokens should always exist during proxy mode tracing. + key = _get_effect(op) + if key is None: + raise AssertionError(f"effect key must not be None for op {op}") + if key not in tokens: + if not allow_token_discovery: + raise AssertionError( + f"Could not find a token for effect {key} which came from the function {op}" + ) + proxy_tensor_mode = cast( + "ProxyTorchDispatchMode | None", + torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.PROXY), + ) + if proxy_tensor_mode is not None: + # If we discovered a new token during tracing, we are in backward. + # Then we patch the graph, adding additional tangents_token as input to the joint graph. + tracer = proxy_tensor_mode.tracer + + from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + track_tensor_tree, + ) + + with disable_proxy_modes_tracing(): + token_tensor = new_token_tensor() + + token_proxy = proxy_tensor_mode.tracer.create_proxy( + "placeholder", "tangents_token", (), {}, name="tangents_token" + ) + track_tensor_tree(token_tensor, token_proxy, constant=None, tracer=tracer) + + tokens[key] = token_tensor + else: + tokens[key] = new_token_tensor() + + token = tokens[key] + + from torch._subclasses.functional_tensor import PythonFunctionalizeAPI + + ctx = PythonFunctionalizeAPI() + + unwrapped_token = ctx.unwrap_tensors([token])[0] + unwrapped_args = ctx.unwrap_tensors(args) + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type] + with ctx.redispatch_to_next(): + (new_token, *unwrapped_outs) = with_effects( + unwrapped_token, op, *unwrapped_args, **unwrapped_kwargs + ) + + schema = _get_schema(op, unwrapped_args, unwrapped_kwargs) + + if isinstance(schema, HopSchema): + if len(schema.returns) == 0: + unwrapped_outs = () + else: + if len(unwrapped_outs) != len(schema.returns): + raise AssertionError( + f"expected {len(schema.returns)} outputs but got {len(unwrapped_outs)}" + ) + unwrapped_outs = tuple(unwrapped_outs) + elif len(schema.returns) == 0: + if unwrapped_outs[0] is not None: + raise AssertionError(f"expected no outputs but got {unwrapped_outs[0]}") + unwrapped_outs = None # type: ignore[assignment] + elif len(schema.returns) == 1: + if len(unwrapped_outs) != 1: + raise AssertionError(f"expected 1 output but got {len(unwrapped_outs)}") + unwrapped_outs = unwrapped_outs[0] + else: + if len(unwrapped_outs) != len(schema.returns): + raise AssertionError( + f"expected {len(schema.returns)} outputs but got {len(unwrapped_outs)}" + ) + + # Add the newly created token into the tokens map for a following call to + # use this token. + wrapped_token = ctx.wrap_tensors(new_token) + if not isinstance(wrapped_token, torch.Tensor): + raise AssertionError( + f"expected wrapped_token to be torch.Tensor, got {type(wrapped_token)}" + ) + tokens[key] = wrapped_token + + # pyrefly: ignore [bad-argument-type] + return ctx.wrap_tensors(unwrapped_outs) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/executorch_call_delegate.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/executorch_call_delegate.py new file mode 100644 index 0000000000000000000000000000000000000000..a3770350dd8fb7a8ed8a7a5d989d3f0b97d76bf5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/executorch_call_delegate.py @@ -0,0 +1,181 @@ +# mypy: allow-untyped-defs + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-strict + +from __future__ import annotations + +from typing import Any, cast + +import torch +import torch.utils._pytree as pytree +from torch._higher_order_ops.utils import register_fake +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + get_proxy_slot, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.utils._pytree import tree_flatten + + +class ExecutorchCallDelegate(HigherOrderOperator): + def __init__(self): + super().__init__("executorch_call_delegate") + + def __call__(self, lowered_module, *args): + # pyrefly: ignore [missing-attribute] + return super().__call__(lowered_module, *args) + + +executorch_call_delegate = ExecutorchCallDelegate() +executorch_call_delegate.fallthrough(torch._C.DispatchKey.PythonDispatcher) +executorch_call_delegate.fallthrough(torch._C.DispatchKey.PythonTLSSnapshot) +executorch_call_delegate.fallthrough(torch._C.DispatchKey.ADInplaceOrView) +executorch_call_delegate.fallthrough(torch._C.DispatchKey.AutocastCPU) + +LOWERED_BACKEND_MODULE_TYPE = "LoweredBackendModule" + + +# pyre-ignore +def trace_call_delegate(proxy_mode, func_overload, lowered_module, *args): + # pyre-ignore + def _unwrap_proxy(e): + if not isinstance(e, (torch.Tensor, torch.SymInt, torch.SymFloat)): + return e + return get_proxy_slot( + cast(torch.Tensor, e), + proxy_mode.tracer, + e, + lambda e: e.proxy, # type: ignore[attr-defined] + ) + + if not is_lowered_module(lowered_module): + raise ValueError( + "executorch_call_delegate()'s first argument must be a LoweredBackendModule" + ) + + with disable_proxy_modes_tracing(): + out = call_delegate_cpu(lowered_module, *args) + + get_lowered_module_name(proxy_mode.tracer.root, lowered_module) + + node_args = (lowered_module, *args) + proxy_args = pytree.tree_map(_unwrap_proxy, node_args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {}, name="executorch_call_delegate" + ) + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@executorch_call_delegate.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd) +# pyre-ignore +def call_delegate_cpu(lowered_module, *args): + # FX creates this immutable_dict/list concept. Get rid of this. + map_types: dict[type, type] = { + torch.fx.immutable_collections.immutable_dict: dict, + torch.fx.immutable_collections.immutable_list: list, + } + new_args = pytree.tree_map_only( + tuple(map_types.keys()), + lambda a: map_types[type(a)](a), + args, + lambda a: isinstance(a, tuple(map_types.keys())), + ) + return lowered_module.original_module.module()(*new_args) + + +@executorch_call_delegate.py_autograd_impl +# pyre-ignore +def call_delegate_autograd(lowered_module, *args): + # TODO: support autograd + flat_operands, _ = tree_flatten([lowered_module, *args]) + requires_grad = any( + f.requires_grad for f in flat_operands if isinstance(f, torch.Tensor) + ) + + with torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.AutogradCPU) + ): + res = executorch_call_delegate(lowered_module, *args) + + if requires_grad: + # Create aliases of the output that has requires_grad=True. We need + # at least one of the inputs to err_fn to require grad so that the + # output will have a grad_fn. + + # pyre-ignore + def fake_requires_grad(var): + if var is not None: + var = var.detach() + if torch.is_floating_point(var) or torch.is_complex(var): + var.requires_grad = True + return var + + return pytree.tree_map_only(torch.Tensor, fake_requires_grad, res) + + return res + + +@executorch_call_delegate.py_impl(ProxyTorchDispatchMode) +# pyre-ignore +def call_delegate_proxy_torch_dispatch_mode(mode, lowered_module, *args): + res = trace_call_delegate(mode, executorch_call_delegate, lowered_module, *args) + return res + + +@register_fake(executorch_call_delegate, skip_cache=True) +# pyre-ignore +def call_delegate_fake_tensor_mode(lowered_module, *args): + return call_delegate_cpu(lowered_module, *args) + + +@executorch_call_delegate.py_functionalize_impl +# pyre-ignore +def call_delegate_functionalize(ctx, lowered_module, *args): + unwrapped_args = tuple(ctx.unwrap_tensors(arg) for arg in args) + with ctx.redispatch_to_next(): + res = executorch_call_delegate(lowered_module, *unwrapped_args) + return ctx.wrap_tensors(res) + + +# pyre-ignore: Missing parameter annotation [2]: Parameter `obj` must have a type other than `Any`.Pyre +def is_lowered_module(obj: Any) -> bool: + """ + This function is added to avoid using isinstance(obj, + LoweredBackendModule) as it will import LoweredBackendModule, which may + cause a circular import. + """ + return type(obj).__name__ == LOWERED_BACKEND_MODULE_TYPE + + +def get_lowered_module_name( + root: torch.nn.Module, + # pyre-ignore: Undefined or invalid type [11]: Annotation `LoweredBackendModule` is not defined as a type. + lowered_module: LOWERED_BACKEND_MODULE_TYPE, # type: ignore[valid-type] +) -> str: + """ + Adds the given lowered_module into the given root module and returns the + name of the module added. + """ + # Find a qualifying name for the lowered submodule + qualname = None + i = 0 + while True: + qualname = f"lowered_module_{i}" + if not hasattr(root, qualname): + break + i += 1 + if qualname is None: + raise AssertionError( + "qualname must not be None after finding unused module slot" + ) + + root.add_module(qualname, lowered_module) + return qualname diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flat_apply.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flat_apply.py new file mode 100644 index 0000000000000000000000000000000000000000..413757a9fdb938616526fbcf02800bb6173dbdec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flat_apply.py @@ -0,0 +1,183 @@ +import typing +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Generic, overload, TypeAlias, TypeVar +from typing_extensions import ParamSpec, TypeIs, TypeVarTuple, Unpack + +import torch +import torch.fx.node +import torch.utils._pytree as pytree +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch._ops import HigherOrderOperator + + +_R = TypeVar("_R") +_P = ParamSpec("_P") +_Ts = TypeVarTuple("_Ts") + + +def is_graphable(val: object) -> TypeIs[torch.fx.node.BaseArgumentTypes]: + """Definition: a graphable type is a type that is an acceptable input/output type to a FX node.""" + return isinstance( + val, (*torch.fx.node.base_types, FakeScriptObject) + ) or is_custom_class(type(val)) + + +def is_graphable_type(typ: type[object]) -> bool: + """Return whether the given type is graphable.""" + return ( + issubclass(typ, torch.fx.node.base_types) + or is_custom_class(typ) + or issubclass(typ, FakeScriptObject) + ) + + +def to_graphable(stuff: pytree.PyTree) -> tuple[list[object], pytree.TreeSpec]: + """Flattens stuff into a flat list of graphable types.""" + # We can consider preserving things like List[int] to improve + # perf and readability (right now that is all flattened out) + flat_args, spec = pytree.tree_flatten(stuff) + for arg in flat_args: + if not is_graphable(arg): + raise RuntimeError( + f"Expected all pytree.tree_leaves of (args, kwargs) to be graphable types, but found " + f"non-fx-graphable type {type(arg)}. If this type is meant to be constant, mark it as " + f"via pytree.register_constant; otherwise, register it as a pytree." + ) + return flat_args, spec + + +def from_graphable( + flat_args: tuple[Unpack[_Ts]], spec: pytree.TreeSpec +) -> pytree.PyTree: + """The inverse of to_graphable.""" + stuff = pytree.tree_unflatten(flat_args, spec) + return stuff + + +def func_to_graphable( + func: Callable[..., object], +) -> tuple[list[object], pytree.TreeSpec]: + """ + Pack and flatten a function type into graphable types. + This is useful for legalizing the function argument of `flat_apply`. + """ + return pytree.tree_flatten(_ConstantFunction(func)) + + +@dataclass(frozen=True, slots=True) +class _ConstantFunction(Generic[_P, _R]): + func: Callable[_P, _R] + + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: + return self.func(*args, **kwargs) + + +pytree.register_constant(_ConstantFunction) + + +_OpTypes = ( + torch._ops.OpOverload | torch._ops.OpOverloadPacket | torch._ops.HigherOrderOperator +) +_op_types = typing.get_args(_OpTypes) + + +_Base: TypeAlias = torch.fx.node.BaseArgumentTypes +# pyrefly bug: pyrefly is complaining: Expected a type form, got instance of `Literal['_FXOutput'] +# pyrefly: ignore[not-a-type] +_FXOutput = _Base | Sequence["_FXOutput"] + + +class FlatApply(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("flat_apply") + + def __call__( + self, + func: _OpTypes | pytree.TreeSpec, + in_spec: pytree.TreeSpec, + *flat_args: Unpack[_Ts], + # If True then the output is checked to be valid. If False then it is up + # to the caller to ensure the output is appropriate. + checked_output: bool = True, + **_unused: object, + ) -> object: + """ + Functions that take in non-graphable types cannot directly be put into FX graph. + + Given func(*args, **kwargs), if all of the non-graphable types are pytrees, + then we're able to store a call to flat_apply(func, in_spec, *flat_args) in the FX graph. + + The semantics of flat_apply(func, in_spec, *flat_args) are roughly equivalent to: + + >>> def flat_apply_impl(func, in_spec, *flat_args): + >>> args, kwargs = pytree.tree_unflatten(flat_args, in_spec) + >>> output = func(*args, **kwargs) + >>> return output + + flat_apply supports the following two cases: + - an input type is a container type (e.g. of tensors) registered as a pytree. + We'll tree_flatten the input type and store the spec. + - an input type is a constant type (i.e. torch.compile will specialize on it) + registered with pytree.register_constant. The constant type goes directly + into the spec. + """ + if not ( + isinstance(func, _op_types) + or is_custom_class(type(func)) + or pytree._is_constant_holder(func) + ): + raise AssertionError( + f"func must be an op type, constant holder, or opaque callable, got {type(func)}" + ) + if len(_unused) != 0: + raise AssertionError(f"unexpected keyword arguments: {_unused}") + # pyrefly: ignore[bad-argument-type] # pyrefly bug? + return impl(func, in_spec, flat_args, checked_output) + + +@overload +def is_valid_output(x: tuple[object, ...]) -> TypeIs[tuple[_FXOutput, ...]]: ... + + +@overload +def is_valid_output(x: Sequence[object]) -> TypeIs[Sequence[_FXOutput]]: ... + + +def is_valid_output(x: object) -> bool: + if isinstance(x, (tuple, list)): + return all(map(is_valid_output, x)) + return is_graphable(x) + + +def impl( + func: _OpTypes | pytree.TreeSpec, + in_spec: pytree.TreeSpec, + flat_args: tuple[Unpack[_Ts]], + checked_output: bool, +) -> _FXOutput: + if isinstance(func, pytree.TreeSpec): + # assume _ConstantFunction + func = pytree._retrieve_constant(func) + if not isinstance(func, _ConstantFunction): + raise AssertionError( + f"expected retrieved constant to be _ConstantFunction, got {type(func)}" + ) + + from torch._higher_order_ops.invoke_leaf_function import unflatten_args_with_modules + + with unflatten_args_with_modules(flat_args, in_spec) as (args, kwargs): + out = func(*args, **kwargs) + + if checked_output: + # For "normal" usage all outputs must either be graphable or + # lists/tuples of graphables. + if not is_valid_output(out): + raise AssertionError( + f"output must be graphable or nested list/tuple of graphables, got {type(out)}" + ) + return out + + +flat_apply = FlatApply() diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_attention.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..3d03c43b3ec69fa115a9d026f198803d97b59c85 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_attention.py @@ -0,0 +1,1543 @@ +import contextlib +import math +from collections.abc import Callable, Sequence +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch import Tensor +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + _has_potential_branch_input_mutation, + _maybe_reenter_make_fx, + autograd_not_implemented, + has_user_subclass, + redirect_to_mode, + reenter_make_fx, + register_fake, + save_values_for_backward, + saved_values, + UnsupportedAliasMutationException, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses import FakeTensor +from torch.amp.autocast_mode import _cast as _autocast_cast +from torch.fx.experimental.proxy_tensor import ( + make_fx, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.fx.graph_module import GraphModule +from torch.fx.traceback import annotate, current_meta +from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode + + +# Duplicate of _inductor/kernel/flex_attention.py to avoid circular import +def _construct_strides( + sizes: Sequence[int], + fill_order: Sequence[int], +) -> Sequence[int]: + """From a list of sizes and a fill order, construct the strides of the permuted tensor.""" + # Initialize strides + if len(sizes) != len(fill_order): + raise AssertionError( + f"Length of sizes must match the length of the fill order, got {len(sizes)} vs {len(fill_order)}" + ) + strides = [0] * len(sizes) + + # Start with stride 1 for the innermost dimension + current_stride = 1 + + # Iterate through the fill order populating strides + for dim in fill_order: + strides[dim] = current_stride + current_stride *= sizes[dim] + + return strides + + +def _permute_strides(out: torch.Tensor, query_strides: tuple[int, ...]) -> torch.Tensor: + """ + Create a new tensor with the same data and shape as the input, + but with strides permuted based on the input tensor's stride order. + + Args: + out (torch.Tensor): The output tensor of attention. + query_strides (List[int]): The stride order of the input query tensor + + Returns: + torch.Tensor: A new tensor with same shape and data as the input, + but with strides permuted based on the query tensor's stride order. + """ + from torch._inductor.ir import get_fill_order + + fill_order = get_fill_order(query_strides) + if out.storage_offset() != 0: + raise AssertionError( + f"Only support storage_offset == 0, got {out.storage_offset()}" + ) + out_strides = _construct_strides(out.shape, fill_order) + + # Attention kernels require stride[-1]=1 for efficient memory access. + # Ensure this by moving last dim to front of fill_order if needed. + if out_strides[-1] != 1: + last_dim = len(out.shape) - 1 + fill_order = list(fill_order) + fill_order.remove(last_dim) + fill_order = [last_dim] + fill_order + out_strides = _construct_strides(out.shape, fill_order) + + new_out = out.new_empty_strided(out.shape, out_strides) + new_out.copy_(out) + return new_out + + +class FlexAttentionHOP(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("flex_attention", cacheable=True) + + def __call__( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + validate_subgraph_args_types(score_mod_other_buffers + mask_mod_other_buffers) + # pyrefly: ignore [missing-attribute] + return super().__call__( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +flex_attention = FlexAttentionHOP() + + +class FlexAttentionBackwardHOP(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("flex_attention_backward", cacheable=True) + + def __call__( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor | None, + grad_logsumexp: torch.Tensor | None, + fw_graph: Callable | GraphModule, + joint_graph: GraphModule, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), + ) -> tuple[ + torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...] + ]: + validate_subgraph_args_types(score_mod_other_buffers + mask_mod_other_buffers) + + # pyrefly: ignore [missing-attribute] + return super().__call__( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + fw_graph, + joint_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +flex_attention_backward = FlexAttentionBackwardHOP() + + +def _math_attention_inner( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor]: + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + working_precision = torch.float64 if query.dtype == torch.float64 else torch.float32 + + scores = query.to(working_precision) @ key.to(working_precision).transpose(-2, -1) + + b = torch.arange(0, scores.size(0), device=scores.device) + h = torch.arange(0, scores.size(1), device=scores.device) + m = torch.arange(0, scores.size(2), device=scores.device) + n = torch.arange(0, scores.size(3), device=scores.device) + + captured_buffers_in_dim = (None,) * len(score_mod_other_buffers) + from torch.nn.attention.flex_attention import _vmap_for_bhqkv + + # first input is score + score_mod = _vmap_for_bhqkv(score_mod, prefix=(0,), suffix=captured_buffers_in_dim) + + mask_mod = block_mask[-1] + mask_mod_in_dim_buffers = (None,) * len(mask_mod_other_buffers) + mask_mod = _vmap_for_bhqkv(mask_mod, prefix=(), suffix=mask_mod_in_dim_buffers) + + with TransformGetItemToIndex(): + scores = (scores * scale).to(working_precision) + post_mod_scores = torch.where( + mask_mod(b, h, m, n, *mask_mod_other_buffers), + score_mod(scores, b, h, m, n, *score_mod_other_buffers), + torch.tensor(-float("inf"), dtype=working_precision, device=scores.device), + ) + + return scores, post_mod_scores + + +def math_attention( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Eager implementation + + This implementation uses vmap to vectorize the score_mod function over the batch, head, m, and n dimensions. + We then apply the vectorized score_mod function to the scores matrix. Each wrap of vmap applies one of the + batch, head, m, or n dimensions. We need to apply vmap 4 times to vectorized over all 4 dimensions. + + Args: + query: The query tensor + key: The key tensor + value: The value tensor + score_mod: The score_mod function + other_buffers: Other buffers that are passed to the score_mod function + + Notes: + Query and Keys are dtype cast up to float64 (if query.dtype is float64) and float32 otherwise. + Scores and Values are dtype cast to input query.dtype at the end. + """ + # broadcast query & key along head dim for GQA + G = query.size(1) // key.size(1) + value = torch.repeat_interleave(value, G, dim=1) + key = torch.repeat_interleave(key, G, dim=1) + + Bq, Bkv = query.size(0), key.size(0) + if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)): + raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}") + + key = key.expand((Bq, *key.size()[1:])) + value = value.expand((Bq, *value.size()[1:])) + + _, post_mod_scores = _math_attention_inner( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + # Set fully masked rows' sumexp to 0.0 + logsumexp = post_mod_scores.logsumexp(dim=-1) + masked_rows = torch.all(post_mod_scores == -float("inf"), dim=-1) + logsumexp = torch.where(masked_rows, -float("inf"), logsumexp) + + # working precision will be used so no need to cast to fp32 + max_scores = torch.max(post_mod_scores, dim=-1)[0] + + post_mod_scores = torch._safe_softmax(post_mod_scores, dim=-1) + + # NB: kernel computes in ln2 space, we always convert back at the top level op, so + # for math impl we divide by log(2) because we will multiply by log(2) + + return ( + post_mod_scores.to(query.dtype) @ value.to(query.dtype), + logsumexp / math.log(2), + max_scores / math.log(2), + ) + + +def _flex_attention_autocast_impl( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple, + mask_mod_other_buffers: tuple, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Forward-only autocast shim: cast Q/K/V to the active autocast dtype, then + redispatch with Autocast keys excluded so we hit the normal implementation. + """ + device_type = query.device.type + autocast_dtype = torch.get_autocast_dtype(device_type) + + query = _autocast_cast(query, device_type, autocast_dtype) + key = _autocast_cast(key, device_type, autocast_dtype) + value = _autocast_cast(value, device_type, autocast_dtype) + + autocast_keyset = torch._C.DispatchKeySet( + DispatchKey.AutocastCPU + ) | torch._C.DispatchKeySet(DispatchKey.AutocastCUDA) + with torch._C._ExcludeDispatchKeyGuard(autocast_keyset): + return flex_attention( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +@flex_attention.py_impl(DispatchKey.AutocastCUDA) +def flex_attention_autocast_cuda( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + return _flex_attention_autocast_impl( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +@flex_attention.py_impl(DispatchKey.AutocastCPU) +def flex_attention_autocast_cpu( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + return _flex_attention_autocast_impl( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +@flex_attention.py_impl(DispatchKey.CompositeExplicitAutograd) +def sdpa_dense( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + out, lse, max_scores = math_attention( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + out = _permute_strides(out, query.stride()) + return out, lse, max_scores + + +def trace_flex_attention( + proxy_mode: ProxyTorchDispatchMode, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Traces the flex_attention operator with the given score_mod function and other_buffers. + + Trace SDPA will call make_fx with "fake" example vals and then trace the score_mod function + This will produce a GraphModule that will be stored on the root tracer as "sdpa_score". We + access this graph module in inductor to inline the score_mod function to the triton template. + """ + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + example_out = flex_attention( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + example_vals = [query.new_zeros((), requires_grad=query.requires_grad)] + [ + query.new_zeros((), dtype=torch.int) for _ in range(4) + ] + mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)] + mask_mod = block_mask[-1] + with TransformGetItemToIndex(): + score_graph = reenter_make_fx(score_mod)( + *example_vals, *score_mod_other_buffers + ) + mask_graph = reenter_make_fx(mask_mod)( + *mask_example_vals, *mask_mod_other_buffers + ) + if not isinstance(proxy_mode.tracer, torch.fx.Tracer): + raise AssertionError( + f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}" + ) + block_mask = block_mask[:-1] + (mask_graph,) + qualname = proxy_mode.tracer.get_fresh_qualname("sdpa_score") + proxy_mode.tracer.root.register_module(qualname, score_graph) + mask_qualname = proxy_mode.tracer.get_fresh_qualname("sdpa_mask") + proxy_mode.tracer.root.register_module(mask_qualname, mask_graph) + node_args = ( + query, + key, + value, + score_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + # pyrefly: ignore [missing-attribute] + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) + with torch.fx.experimental.proxy_tensor.set_original_aten_op(flex_attention): + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", flex_attention, proxy_args, {} + ) + return track_tensor_tree( + example_out, + out_proxy, + constant=None, + tracer=proxy_mode.tracer, + ) + + +@flex_attention.py_impl(ProxyTorchDispatchMode) +def flex_attention_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if mode is None: + raise AssertionError("Mode should always be enabled for python fallback key") + return trace_flex_attention( + mode, + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +@flex_attention.py_functionalize_impl +def flex_attention_functionalize( + ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Defines the functionalization rules for the flex_attention operator. + + Right now we are unwrapping each tensor and then redispatching to the next, however we want to + guard against any mutations in the score_mod function, to the other_buffers since those + are free variables. + """ + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + query_unwrapped = ctx.unwrap_tensors(query) + key_unwrapped = ctx.unwrap_tensors(key) + value_unwrapped = ctx.unwrap_tensors(value) + block_mask_unwrapped = ctx.unwrap_tensors(block_mask) + score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers) + mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers) + + # Appease the mypy overlords + if not isinstance(query_unwrapped, torch.Tensor): + raise AssertionError( + f"expected query_unwrapped to be torch.Tensor, got {type(query_unwrapped)}" + ) + if not isinstance(key_unwrapped, torch.Tensor): + raise AssertionError( + f"expected key_unwrapped to be torch.Tensor, got {type(key_unwrapped)}" + ) + if not isinstance(value_unwrapped, torch.Tensor): + raise AssertionError( + f"expected value_unwrapped to be torch.Tensor, got {type(value_unwrapped)}" + ) + if not isinstance(block_mask_unwrapped, tuple): + raise AssertionError( + f"expected block_mask_unwrapped to be tuple, got {type(block_mask_unwrapped)}" + ) + if not isinstance(score_mod_other_buffers_unwrapped, tuple): + raise AssertionError( + f"expected score_mod_other_buffers_unwrapped to be tuple, got {type(score_mod_other_buffers_unwrapped)}" + ) + if not isinstance(mask_mod_other_buffers_unwrapped, tuple): + raise AssertionError( + f"expected mask_mod_other_buffers_unwrapped to be tuple, got {type(mask_mod_other_buffers_unwrapped)}" + ) + + example_vals = ( + [query_unwrapped.new_zeros(())] + + [query_unwrapped.new_zeros((), dtype=torch.int) for _ in range(4)] + + list(score_mod_other_buffers_unwrapped) + ) + with ctx.redispatch_to_next(): + functional_score_mod = ctx.functionalize(score_mod) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + with TransformGetItemToIndex(): + # TODO: So far only the input mutations are checked + # In the other HOPs, also aliases are checked which is + # omitted here + mutates = _has_potential_branch_input_mutation( + score_mod, example_vals, pre_dispatch + ) + # We only care about mutations of existing buffers since we can't replay these. + # However, we can just error if anything is detected + if mutates: + raise UnsupportedAliasMutationException("Mutations detected in score_mod") + + out = flex_attention( + query_unwrapped, + key_unwrapped, + value_unwrapped, + functional_score_mod, + block_mask_unwrapped, + scale, + kernel_options, + score_mod_other_buffers_unwrapped, + mask_mod_other_buffers_unwrapped, + ) + return ctx.wrap_tensors(out) # type: ignore[return-value, arg-type] + + +@register_fake(flex_attention) +def flex_attention_fake_impl( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if has_user_subclass( + ( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ), + allowed_subclasses=(FakeTensor,), + ): + return NotImplemented + + v_head_dim = value.size(-1) + batch_size, num_heads, seq_len_q, _q_head_dim = query.shape + logsumexp = query.new_empty(batch_size, num_heads, seq_len_q, dtype=torch.float32) + max_scores = query.new_empty(batch_size, num_heads, seq_len_q, dtype=torch.float32) + out_shape = (batch_size, num_heads, seq_len_q, v_head_dim) + out = query.new_empty(out_shape) + out = _permute_strides(out, query.stride()) + return out, logsumexp, max_scores + + +# Registers dispatches for SAC +redirect_to_mode(flex_attention, _CachingTorchDispatchMode) +redirect_to_mode(flex_attention, _CachedTorchDispatchMode) + + +# ---------------------------- Autograd Implementation ---------------------------- +def create_fw_bw_graph( + score_mod: Callable, + index_values: tuple[Tensor, Tensor, Tensor, Tensor, Tensor], + other_buffers: tuple[Tensor, ...], +) -> tuple[Callable, Callable]: + # See Note:[HOP create fw_bw graph] + + # All of these imports need to be here in order to avoid circular dependencies + from torch._dispatch.python import suspend_functionalization + from torch._dynamo._trace_wrapped_higher_order_op import mod_index + from torch._functorch.aot_autograd import AOTConfig, create_joint + from torch._subclasses.fake_tensor import FakeTensorMode, is_fake_tensor + from torch._subclasses.functional_tensor import disable_functional_mode + from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing + + dummy_aot_config = AOTConfig( + fw_compiler=None, # type: ignore[arg-type] + bw_compiler=None, # type: ignore[arg-type] + partition_fn=None, # type: ignore[arg-type] + decompositions={}, + num_params_buffers=0, + aot_id=0, + keep_inference_input_mutations=False, + ) + + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + + def _from_fun( + t: Tensor | torch.SymInt | int, + ) -> Tensor | torch.SymInt | int: + if isinstance(t, torch.Tensor): + return torch.empty_strided( + t.size(), + t.stride(), + device=t.device, + dtype=t.dtype, + requires_grad=t.requires_grad, + ) + return t + + # If someone runs this hop under the default compiler backend ("eager") + # Then this path will be run with the actual user inputs. We convert them + # to fake tensors in order to not perform any actual compute. + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(index_values) + if fake_mode is None: + fake_mode = FakeTensorMode(allow_non_fake_inputs=True) + + with fake_mode: + unwrapped_score_mod_indexes = pytree.tree_map(_from_fun, index_values) + unwrapped_other_buffers = pytree.tree_map(_from_fun, other_buffers) + + if not all( + is_fake_tensor(t) or isinstance(t, (int, torch.SymInt)) + for t in unwrapped_score_mod_indexes + unwrapped_other_buffers + ): + raise AssertionError( + f"all unwrapped values must be FakeTensor, int, or SymInt, got " + f"{[type(t) for t in unwrapped_score_mod_indexes + unwrapped_other_buffers]}" + ) + + example_flat_out = pytree.tree_map( + _from_fun, + score_mod(*unwrapped_score_mod_indexes, *unwrapped_other_buffers), + ) + if not isinstance(example_flat_out, torch.Tensor): + raise RuntimeError( + "Expected output of score_mod to be a tensor." + f"Got type {type(example_flat_out)}." + ) + example_grad = _from_fun(example_flat_out) + + def joint_f( + score: Tensor, + b: Tensor, + h: Tensor, + m: Tensor, + n: Tensor, + example_grad: Tensor, + *other_buffers: tuple[Tensor, ...], + ) -> list[Tensor | None]: + def fw_with_masks( + *args: tuple[Tensor, ...], + ) -> tuple[tuple[Tensor], tuple[bool]]: + captured_args = [ + mod_index(buffer, []) + if ( + isinstance(buffer, torch.Tensor) + and buffer.requires_grad + and buffer.ndim == 0 + ) + else buffer + for buffer in args[5:] + ] + fw_out = score_mod(*args[:5], *captured_args) + out_requires_grad = fw_out.requires_grad + return ((fw_out,), (out_requires_grad,)) + + joint = create_joint(fw_with_masks, aot_config=dummy_aot_config) + args = [score, b, h, m, n] + list(other_buffers) + optional_grad = [example_grad] if example_grad.requires_grad else [] + _, grads = joint(args, optional_grad) + if grads[0] is None: + raise RuntimeError( + "flex_attention backward requires the output of score_mod to " + "depend on score. Got a score_mod whose output does not " + "require gradients with respect to score." + ) + + return grads + + joint_graph = make_fx(joint_f)( + *unwrapped_score_mod_indexes, example_grad, *unwrapped_other_buffers + ) + # pyrefly: ignore [bad-return] + return score_mod, joint_graph + + +class FlexAttentionAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx: Any, + query: Tensor, + key: Tensor, + value: Tensor, + fw_graph: Callable, + joint_graph: Callable, + block_mask: tuple[Any, ...], + scale: float, + kernel_options: dict[str, Any], + mask_mod_other_buffers: tuple[Any, ...], + *score_mod_other_buffers: tuple[Any, ...], + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + ctx.set_materialize_grads(False) + # Capture sparsity_hint from tracing metadata so backward can re-annotate + ctx._sparsity_hint = current_meta.get("custom", {}).get("sparsity_hint", 0.0) + any_buffer_requires_grad = any( + buffer.requires_grad + for buffer in mask_mod_other_buffers + if isinstance(buffer, torch.Tensor) + ) + if any_buffer_requires_grad: + raise AssertionError( + "Captured buffers from mask mod that require grad are not supported." + ) + ctx._fw_graph = fw_graph + ctx._joint_graph = joint_graph + ctx._mask_graph = block_mask[-1] + ctx.scale = scale + ctx.kernel_options = kernel_options + ctx._score_mod_other_buffers_len = len(score_mod_other_buffers) + with torch._C._AutoDispatchBelowAutograd(): + out, logsumexp, max_scores = flex_attention( + query, + key, + value, + fw_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + # no grads for you sir + ctx.mark_non_differentiable(max_scores) + save_values_for_backward( + ctx, + ( + query, + key, + value, + out, + logsumexp, + max_scores, + *block_mask[:-1], + *score_mod_other_buffers, + *mask_mod_other_buffers, + ), + ) + return out, logsumexp, max_scores + + @staticmethod + def backward( # type: ignore[override] + ctx: Any, + grad_out: Tensor, + grad_logsumexp: Tensor, + grad_max_scores: Tensor, + ) -> tuple[Tensor | None, ...]: + fw_args = saved_values(ctx) + ( + query, + key, + value, + out, + logsumexp, + max_scores, + query_lengths, + kv_lengths, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + dq_write_order, + dq_write_order_full, + dq_kv_order, + dq_kv_order_spt, + Q_BLOCK_SIZE, + KV_BLOCK_SIZE, + *other_buffers, + ) = fw_args + fw_graph = ctx._fw_graph + joint_graph = ctx._joint_graph + mask_graph = ctx._mask_graph + scale = ctx.scale + kernel_options = ctx.kernel_options + score_mod_other_buffers = tuple( + other_buffers[: ctx._score_mod_other_buffers_len] + ) + mask_mod_other_buffers = tuple( + other_buffers[ctx._score_mod_other_buffers_len :] + ) + # We have asserted that mask_mod_other_buffers do not require grad, + # but score_mod_other_buffers can require grad. + none_grads = [None] * 6 + _sparsity_ctx = ( + annotate({"sparsity_hint": ctx._sparsity_hint}) + if ctx._sparsity_hint > 0 + else contextlib.nullcontext() + ) + with _sparsity_ctx: + ( + grad_query, + grad_key, + grad_value, + grad_score_mod_captured, + ) = flex_attention_backward( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + fw_graph, + joint_graph, + ( + query_lengths, + kv_lengths, + kv_num_blocks, + kv_indices, + full_kv_num_blocks, + full_kv_indices, + q_num_blocks, + q_indices, + full_q_num_blocks, + full_q_indices, + dq_write_order, + dq_write_order_full, + dq_kv_order, + dq_kv_order_spt, + Q_BLOCK_SIZE, + KV_BLOCK_SIZE, + mask_graph, + ), + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + return grad_query, grad_key, grad_value, *none_grads, *grad_score_mod_captured + + +# TODO: Rework DispatchKey.Autograd to py_autograd_impl +@flex_attention.py_impl(DispatchKey.Autograd) +def flex_attention_autograd( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple[Tensor, ...] = (), + mask_mod_other_buffers: tuple[Tensor, ...] = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + with TransformGetItemToIndex(): + input_requires_grad = any( + isinstance(t, torch.Tensor) and t.requires_grad + for t in (query, key, value, *score_mod_other_buffers) + ) + if torch.is_grad_enabled() and input_requires_grad: + if block_mask[7] is None: + raise RuntimeError( + "BlockMask q_indices is None. Backward pass requires q_indices to be computed. " + "Please create the BlockMask with compute_q_blocks=True" + ) + example_vals = ( + query.new_zeros((), requires_grad=input_requires_grad), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + ) + fw_graph, bw_graph = create_fw_bw_graph( + score_mod, example_vals, score_mod_other_buffers + ) + else: + fw_graph, bw_graph = score_mod, None + out, logsumexp, max_scores = FlexAttentionAutogradOp.apply( + query, + key, + value, + fw_graph, + bw_graph, + block_mask, + scale, + kernel_options, + mask_mod_other_buffers, + *score_mod_other_buffers, + ) + return out, logsumexp, max_scores + + +# ---------------------------- Backward HOP Implementation ---------------------------- + + +@flex_attention_backward.py_impl(DispatchKey.CompositeExplicitAutograd) +def sdpa_dense_backward( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor | None, + grad_logsumexp: torch.Tensor | None, + fw_graph: Callable, # GraphModule type hint? + joint_graph: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple, + mask_mod_other_buffers: tuple, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]: + if query.dtype != key.dtype or query.dtype != value.dtype: + raise ValueError( + f"Backward pass with mixed query, key, and value dtype is not supported, " + f"got query.dtype={query.dtype}, key.dtype={key.dtype}, " + f"and value.dtype={value.dtype}" + ) + if joint_graph is None: + example_vals = ( + query.new_zeros((), requires_grad=True), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + ) + _, joint_graph = create_fw_bw_graph( + fw_graph, example_vals, score_mod_other_buffers + ) + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + Bq, Hq, seq_len_q, qk_head_dim = query.shape + Bkv, Hkv, seq_len_kv, v_head_dim = value.shape + + # Get outputs before calling repeat interleave and permute to input stride orders + actual_grad_query = query.new_empty((Bq, Hq, seq_len_q, qk_head_dim)) + actual_grad_query = _permute_strides(actual_grad_query, query.stride()) + + actual_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim)) + actual_grad_key = _permute_strides(actual_grad_key, key.stride()) + + actual_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim)) + actual_grad_value = _permute_strides(actual_grad_value, value.stride()) + + actual_grad_score_mod_captured = _new_captured_grad_buffers( + score_mod_other_buffers, joint_graph + ) + + Bq, Bkv = query.size(0), key.size(0) + if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)): + raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}") + + key = key.expand((Bq, *key.size()[1:])) + value = value.expand((Bq, *value.size()[1:])) + + G = query.size(1) // key.size(1) + key = torch.repeat_interleave(key, G, dim=1) + value = torch.repeat_interleave(value, G, dim=1) + + if grad_out is None: + grad_out = torch.zeros_like(out) + if grad_logsumexp is None: + grad_logsumexp = torch.zeros_like(logsumexp) + + # logsumexp is expected in log2 scale (as returned by the forward HOP). + # The public flex_attention API converts lse to natural log before returning, + # so callers using the public API must not pass that value here directly. + logsumexp = logsumexp * math.log(2) + # The backwards formula for the log -> log2 change of base in the forwards + grad_logsumexp = grad_logsumexp / math.log(2) + scores, post_mod_scores = _math_attention_inner( + query, + key, + value, + fw_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + masked_out_rows = logsumexp == -float("inf") + softmax_scores = torch.exp(post_mod_scores - logsumexp.unsqueeze(-1)) + softmax_scores = torch.where(masked_out_rows.unsqueeze(-1), 0, softmax_scores) + + grad_value = softmax_scores.to(query.dtype).transpose(-2, -1) @ grad_out + + grad_softmax_scores = grad_out.to(dtype=softmax_scores.dtype) @ value.to( + dtype=softmax_scores.dtype + ).transpose(-2, -1) + + sum_scores = torch.sum( + out.to(dtype=softmax_scores.dtype) * grad_out.to(dtype=softmax_scores.dtype), + -1, + keepdim=True, + ) + grad_score_mod = softmax_scores * ( + grad_softmax_scores - sum_scores + grad_logsumexp.unsqueeze(-1) + ) + + b = torch.arange(0, scores.size(0), device=scores.device) + h = torch.arange(0, scores.size(1), device=scores.device) + m = torch.arange(0, scores.size(2), device=scores.device) + n = torch.arange(0, scores.size(3), device=scores.device) + + mask_graph = block_mask[-1] + # Gradient of the inline score_mod function, with respect to the scores + captured_buffers_in_dim = (None,) * len(score_mod_other_buffers) + out_dims = [0, None, None, None, None] + [None] * len(score_mod_other_buffers) + from torch.nn.attention.flex_attention import _vmap_for_bhqkv + + # inputs are [score, b, h, q_idx, kv_idx, gradOut, ...] + # score and gradOut are "fully" batched + joint_score_mod = _vmap_for_bhqkv( + joint_graph, + prefix=(0,), + suffix=(0,) + captured_buffers_in_dim, + out_dims=out_dims, + ) + with TransformGetItemToIndex(): + grad_scores, _, _, _, _, *grad_score_mod_captured = joint_score_mod( + scores, b, h, m, n, grad_score_mod, *score_mod_other_buffers + ) + grad_scores = grad_scores * scale + grad_scores = grad_scores.to(query.dtype) + + mask_mod = _vmap_for_bhqkv( + mask_graph, prefix=(), suffix=(None,) * len(mask_mod_other_buffers) + ) + with TransformGetItemToIndex(): + mask_scores = mask_mod(b, h, m, n, *mask_mod_other_buffers) + grad_scores = torch.where( + mask_scores, grad_scores, torch.tensor(0, dtype=query.dtype) + ) + + grad_query = grad_scores @ key + grad_key = grad_scores.transpose(-2, -1) @ query + + # Reduce DK, DV along broadcasted heads. + grad_key = grad_key.view( + grad_key.size(0), -1, G, grad_key.size(-2), grad_key.size(-1) + ) + grad_value = grad_value.view( + grad_value.size(0), -1, G, grad_value.size(-2), grad_value.size(-1) + ) + + grad_key = torch.sum(grad_key, 2, keepdim=False) + grad_value = torch.sum(grad_value, 2, keepdim=False) + + # Fill to correctly strided outputs + actual_grad_query.copy_(grad_query) + actual_grad_key.copy_(grad_key) + actual_grad_value.copy_(grad_value) + + if Bq != Bkv: + if not (Bq > 1 and Bkv == 1): + raise AssertionError( + f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}" + ) + + actual_grad_key = torch.sum(actual_grad_key, 0, keepdim=True) + actual_grad_value = torch.sum(actual_grad_value, 0, keepdim=True) + + score_mod_other_buffer_grads = [] + for actual_grad, grad in zip( + actual_grad_score_mod_captured, grad_score_mod_captured + ): + if not isinstance(grad, torch.Tensor): + score_mod_other_buffer_grads.append(None) + continue + if actual_grad is None: + raise AssertionError("Expected a captured grad buffer for a tensor grad") + score_mod_other_buffer_grads.append(actual_grad.copy_(grad)) + + return ( + actual_grad_query, + actual_grad_key, + actual_grad_value, + tuple(score_mod_other_buffer_grads), + ) + + +def _captured_grad_buffer_mask( + joint_graph: Callable | GraphModule, num_captures: int +) -> tuple[bool, ...]: + """Return which score_mod captures need concrete grad buffers. + + A capture can require grad but still be dead in score_mod, for example when + the function reads a closed-over tensor but returns the original score. AOT + represents that as a None grad in the joint graph, and that None must stay a + None instead of being copied into a materialized buffer. + + Conversely, this is independent of the saved capture's requires_grad flag: + compiled backward may save an intermediate whose grad is needed to propagate + to earlier user inputs. + """ + if not isinstance(joint_graph, GraphModule): + # The @register_fake path for direct flex_attention_backward HOP calls + # can see callable subgraphs before make_fx materializes them. In that + # metadata-only phase, no capture is provably dead. + return (True,) * num_captures + + output_node = next(node for node in joint_graph.graph.nodes if node.op == "output") + score_mod_arg_grads = 5 + captured_grad_outputs = output_node.args[0][score_mod_arg_grads:] + if len(captured_grad_outputs) != num_captures: + raise AssertionError( + f"Expected {num_captures} captured grad outputs, " + f"got {len(captured_grad_outputs)}" + ) + return tuple(grad is not None for grad in captured_grad_outputs) + + +def _new_captured_grad_buffers( + score_mod_other_buffers: tuple, joint_graph: Callable | GraphModule +) -> tuple[torch.Tensor | None, ...]: + """Allocate only the captured grad buffers that the joint graph can produce.""" + needs_grad_buffer = _captured_grad_buffer_mask( + joint_graph, len(score_mod_other_buffers) + ) + # The lowering returns captured grads as contiguous buffers, so match that here. + return tuple( + torch.empty_like(buffer, memory_format=torch.contiguous_format) + if isinstance(buffer, torch.Tensor) and needs_buffer + else None + for buffer, needs_buffer in zip(score_mod_other_buffers, needs_grad_buffer) + ) + + +def trace_flex_attention_backward( + proxy_mode: ProxyTorchDispatchMode, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor, + grad_logsumexp: torch.Tensor, + fw_graph: Callable | GraphModule, + joint_graph: GraphModule, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]: + """We already have the forward graph and joint graph from the forward pass, so we create a proxy attach both graphs""" + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + requires_grad = any(pytree.tree_map(lambda x: x.requires_grad, (query, key))) + fw_example_vals = [query.new_zeros((), requires_grad=requires_grad)] + [ + query.new_zeros((), dtype=torch.int) for _ in range(4) + ] + bw_example_vals = fw_example_vals + [query.new_zeros(())] + mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)] + mask_graph = block_mask[-1] + with TransformGetItemToIndex(): + # There's no active make_fx during the compiled autograd graph's initial capture + fw_graph = _maybe_reenter_make_fx(fw_graph)( + *fw_example_vals, *score_mod_other_buffers + ) + joint_graph = _maybe_reenter_make_fx(joint_graph)( + *bw_example_vals, *score_mod_other_buffers + ) + mask_graph = _maybe_reenter_make_fx(mask_graph)( + *mask_example_vals, *mask_mod_other_buffers + ) + block_mask = block_mask[:-1] + (mask_graph,) + example_out = flex_attention_backward( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + fw_graph, + joint_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + if not isinstance(proxy_mode.tracer, torch.fx.Tracer): + raise AssertionError( + f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}" + ) + + qualname = proxy_mode.tracer.get_fresh_qualname("fw_graph") + proxy_mode.tracer.root.register_module(qualname, fw_graph) # type: ignore[arg-type] + qualname = proxy_mode.tracer.get_fresh_qualname("joint_graph") + proxy_mode.tracer.root.register_module(qualname, joint_graph) + qualname = proxy_mode.tracer.get_fresh_qualname("mask_graph") + proxy_mode.tracer.root.register_module(qualname, mask_graph) + + node_args = ( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + fw_graph, + joint_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + # pyrefly: ignore [missing-attribute] + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", + flex_attention_backward, + proxy_args, + {}, + name="flex_attention_backward", + ) + return track_tensor_tree( + example_out, + out_proxy, + constant=None, + tracer=proxy_mode.tracer, + ) + + +@flex_attention_backward.py_impl(ProxyTorchDispatchMode) +def flex_attention_backward_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor, + grad_logsumexp: torch.Tensor, + fw_graph: Callable | GraphModule, + joint_graph: GraphModule, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]: + if mode is None: + raise AssertionError("Mode should always be enabled for python fallback key") + with torch.fx.experimental.proxy_tensor.set_original_aten_op( + flex_attention_backward + ): + return trace_flex_attention_backward( + mode, + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + fw_graph, + joint_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +@flex_attention_backward.py_functionalize_impl +def flex_attention_backward_functionalize( + ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor, + grad_logsumexp: torch.Tensor, + fw_graph: Callable | GraphModule, + joint_graph: GraphModule, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]: + """Defines the functionalization rules for the flex_attention operator. + + Right now we are unwrapping each tensor and then redispatching to the next, + since we know that the forward score mod function is assured to be free of mutations + to the other_buffers, we skip that mutate check and go straight to redispatching. + """ + + query_unwrapped = ctx.unwrap_tensors(query) + key_unwrapped = ctx.unwrap_tensors(key) + value_unwrapped = ctx.unwrap_tensors(value) + out_unwrapped = ctx.unwrap_tensors(out) + logsumexp_unwrapped = ctx.unwrap_tensors(logsumexp) + grad_out_unwrapped = ctx.unwrap_tensors(grad_out) + grad_logsumexp_unwrapped = ctx.unwrap_tensors(grad_logsumexp) + block_mask_unwrapped = ctx.unwrap_tensors(block_mask) + score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers) + mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers) + + # Appease the mypy overlords + if not isinstance(query_unwrapped, torch.Tensor): + raise AssertionError( + f"expected query_unwrapped to be torch.Tensor, got {type(query_unwrapped)}" + ) + if not isinstance(key_unwrapped, torch.Tensor): + raise AssertionError( + f"expected key_unwrapped to be torch.Tensor, got {type(key_unwrapped)}" + ) + if not isinstance(value_unwrapped, torch.Tensor): + raise AssertionError( + f"expected value_unwrapped to be torch.Tensor, got {type(value_unwrapped)}" + ) + if not isinstance(out_unwrapped, torch.Tensor): + raise AssertionError( + f"expected out_unwrapped to be torch.Tensor, got {type(out_unwrapped)}" + ) + if not isinstance(logsumexp_unwrapped, torch.Tensor): + raise AssertionError( + f"expected logsumexp_unwrapped to be torch.Tensor, got {type(logsumexp_unwrapped)}" + ) + if grad_out_unwrapped is not None and not isinstance( + grad_out_unwrapped, torch.Tensor + ): + raise AssertionError( + f"expected grad_out_unwrapped to be torch.Tensor or None, got {type(grad_out_unwrapped)}" + ) + if grad_logsumexp_unwrapped is not None and not isinstance( + grad_logsumexp_unwrapped, torch.Tensor + ): + raise AssertionError( + f"expected grad_logsumexp_unwrapped to be torch.Tensor or None, got {type(grad_logsumexp_unwrapped)}" + ) + if not isinstance(block_mask_unwrapped, tuple): + raise AssertionError( + f"expected block_mask_unwrapped to be tuple, got {type(block_mask_unwrapped)}" + ) + if not isinstance(score_mod_other_buffers_unwrapped, tuple): + raise AssertionError( + f"expected score_mod_other_buffers_unwrapped to be tuple, got {type(score_mod_other_buffers_unwrapped)}" + ) + if not isinstance(mask_mod_other_buffers_unwrapped, tuple): + raise AssertionError( + f"expected mask_mod_other_buffers_unwrapped to be tuple, got {type(mask_mod_other_buffers_unwrapped)}" + ) + + with ctx.redispatch_to_next(): + # pyrefly: ignore [bad-argument-type] + functional_fw_graph = ctx.functionalize(fw_graph) + # pyrefly: ignore [bad-argument-type] + functional_joint_graph = ctx.functionalize(joint_graph) + + ( + grad_query, + grad_key, + grad_value, + grad_score_mod_captured, + ) = flex_attention_backward( + query_unwrapped, + key_unwrapped, + value_unwrapped, + out_unwrapped, + logsumexp_unwrapped, + grad_out_unwrapped, + grad_logsumexp_unwrapped, + functional_fw_graph, # type: ignore[arg-type] + functional_joint_graph, # type: ignore[arg-type] + block_mask_unwrapped, + scale, + kernel_options, + score_mod_other_buffers_unwrapped, + mask_mod_other_buffers_unwrapped, + ) + + return ctx.wrap_tensors((grad_query, grad_key, grad_value, grad_score_mod_captured)) # type: ignore[return-value,arg-type] + + +@register_fake(flex_attention_backward) +def flex_attention_backward_fake_tensor_mode( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor, + grad_logsumexp: torch.Tensor, + fw_graph: Callable | GraphModule, + joint_graph: GraphModule, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]: + if has_user_subclass( + ( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ), + allowed_subclasses=(FakeTensor,), + ): + return NotImplemented + Bq, _, _, qk_head_dim = query.shape + Bkv, Hkv, seq_len_kv, v_head_dim = value.shape + + grad_query = query.new_empty(query.shape) + grad_query = _permute_strides(grad_query, query.stride()) + + grad_score_mod_captured = _new_captured_grad_buffers( + score_mod_other_buffers, joint_graph + ) + + broadcasted_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim)) + broadcasted_grad_key = _permute_strides(broadcasted_grad_key, key.stride()) + + broadcasted_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim)) + broadcasted_grad_value = _permute_strides(broadcasted_grad_value, value.stride()) + + from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_and + + # This branch chooses fake tensor metadata, including strides. Guarding is + # valid for backed symbolic sizes, while unbacked/data-dependent predicates + # conservatively fall through to the non-broadcast contract below. + if guard_or_false(sym_and(Bkv == 1, Bq > 1)): + grad_key = torch.sum(broadcasted_grad_key, dim=0, keepdim=True) + grad_value = torch.sum(broadcasted_grad_value, dim=0, keepdim=True) + else: + torch._check( + Bq == Bkv, + lambda: "grad_key/grad_value batch must match key/value batch.", + ) + grad_key = broadcasted_grad_key + grad_value = broadcasted_grad_value + + return grad_query, grad_key, grad_value, grad_score_mod_captured + + +flex_attention_backward.py_autograd_impl( + autograd_not_implemented(flex_attention_backward, deferred_error=True) +) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_gemm.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..5be03bddc15c0cb13518e68101a6797746fb4a83 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_gemm.py @@ -0,0 +1,355 @@ +# mypy: allow-untyped-defs +import dataclasses +from collections.abc import Callable, Mapping +from functools import partial +from typing import Any, cast + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.inline_asm_elementwise import inline_asm_elementwise +from torch._higher_order_ops.utils import ( + _check_alias_and_mutation, + autograd_not_implemented, + reenter_make_fx, + register_fake, + unique_graph_id, +) +from torch._ops import HigherOrderOperator +from torch._prims_common import ELEMENTWISE_TYPE_PROMOTION_KIND +from torch._prims_common.wrappers import elementwise_type_promotion_wrapper +from torch._subclasses.fake_tensor import is_fake +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree + + +@dataclasses.dataclass(frozen=True) +class FlexGemmOpSpec: + """Canonical operand positions for a supported FlexGEMM op.""" + + name: str + mat1_index: int + mat2_index: int + input_ndim: int + bias_index: int | None = None + + +FLEX_GEMM_OP_SPECS = { + torch.ops.aten.mm.default: FlexGemmOpSpec("mm", 0, 1, input_ndim=2), + torch.ops.aten.addmm.default: FlexGemmOpSpec( + "addmm", 1, 2, input_ndim=2, bias_index=0 + ), + torch.ops.aten.bmm.default: FlexGemmOpSpec("bmm", 0, 1, input_ndim=3), + torch.ops.aten.baddbmm.default: FlexGemmOpSpec( + "baddbmm", 1, 2, input_ndim=3, bias_index=0 + ), +} +FLEX_GEMM_OP_ALIASES = { + torch.mm: torch.ops.aten.mm.default, + torch.addmm: torch.ops.aten.addmm.default, + torch.bmm: torch.ops.aten.bmm.default, + torch.baddbmm: torch.ops.aten.baddbmm.default, +} +_SUPPORTED_BACKENDS = {"NVGEMM", "QUACK", "TRITON"} + + +_SUPPORTED_FLEX_GEMM_OP_NAMES = "/".join( + spec.name for spec in FLEX_GEMM_OP_SPECS.values() +) +_PRESERVE_FLEX_GEMM_GEMM_OP = "preserve_flex_gemm_gemm_op" + +# Note [Preserving FlexGEMM body GEMMs] +# FlexGEMM lowering materializes the captured epilogue by finding the body GEMM +# node whose target matches the HOP-carried gemm_op. Generic graph passes can +# rewrite batch-size-1 bmm into mm(...).unsqueeze(0), which removes the matching +# node. This body pass tags FlexGEMM GEMM nodes so bmm_to_mm in joint_graph.py +# skips them. + + +def mark_flex_gemm_body_gemm_node( + body_graph: torch.fx.GraphModule, gemm_op: torch._ops.OpOverload +) -> None: + """Mark body GEMMs so Inductor's batch-1 bmm rewrite keeps them matchable.""" + for node in body_graph.graph.find_nodes(op="call_function", target=gemm_op): + node.meta[_PRESERVE_FLEX_GEMM_GEMM_OP] = True + + +FLEX_GEMM_BODY_GRAPH_PASSES: tuple[ + Callable[[torch.fx.GraphModule, torch._ops.OpOverload], None], ... +] = (mark_flex_gemm_body_gemm_node,) + + +@elementwise_type_promotion_wrapper( + type_promoting_args=("x",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def flex_gemm_fast_math_sigmoid(x: torch.Tensor) -> torch.Tensor: + """Use the tanh sigmoid identity selected by QUACK fast math.""" + return torch.tanh(x * 0.5) * 0.5 + 0.5 + + +@elementwise_type_promotion_wrapper( + type_promoting_args=("x",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def flex_gemm_fast_math_silu(x: torch.Tensor) -> torch.Tensor: + """Use the tanh SiLU identity selected by QUACK fast math.""" + half = x * 0.5 + return half * torch.tanh(half) + half + + +def flex_gemm_fast_math_gelu( + x: torch.Tensor, + approximate: str = "none", + *, + fallback: Callable[..., Any], +) -> torch.Tensor: + """Select the standard tanh GELU approximation for exact GELU calls.""" + if approximate == "none": + approximate = "tanh" + return fallback(x, approximate) + + +FLEX_GEMM_FAST_MATH_DECOMPOSITIONS: dict[torch._ops.OpOverload, Callable[..., Any]] = { + torch.ops.aten.sigmoid.default: flex_gemm_fast_math_sigmoid, + torch.ops.aten.silu.default: flex_gemm_fast_math_silu, +} + + +def flex_gemm_body_decomposition_table( + kernel_options: dict[str, Any], + decomposition_table: Mapping[torch._ops.OpOverload, Callable[..., Any]], +) -> dict[torch._ops.OpOverload, Callable[..., Any]] | None: + """Override composite body decompositions enabled by QUACK fast math.""" + if ( + kernel_options.get("backend") != "QUACK" + or kernel_options.get("fast_math") is not True + ): + return None + merged_decompositions = dict(decomposition_table) + merged_decompositions.update(FLEX_GEMM_FAST_MATH_DECOMPOSITIONS) + gelu = torch.ops.aten.gelu.default + if gelu in merged_decompositions: + merged_decompositions[gelu] = partial( + flex_gemm_fast_math_gelu, fallback=merged_decompositions[gelu] + ) + return merged_decompositions + + +def nvfp4_pack(input: torch.Tensor) -> torch.Tensor: + """Pack adjacent Float32 values into E2M1x2 storage for FlexGEMM tests. + + This private helper lets tests spell the intended epilogue with public inline + assembly while a blessed user-facing quantization API is still being decided. + The last dimension is one low/high pair: the PTX x2 conversion consumes both + values and emits one byte, whose same-width dtype view supplies the logical + ``torch.float4_e2m1fn_x2`` type without changing storage. + """ + if input.dtype is not torch.float32 or input.ndim == 0 or input.shape[-1] != 2: + raise ValueError( + "NVFP4 pack input must be Float32 with innermost dimension 2, " + f"got dtype={input.dtype}, shape={tuple(input.shape)}" + ) + if torch.compiler.is_compiling() or is_fake(input): + low = input[..., 0] + high = input[..., 1] + packed = inline_asm_elementwise( + high, + low, + asm_str=( + "{ .reg .b8 packed; " + "cvt.rn.satfinite.e2m1x2.f32 packed, $1, $2; " + "cvt.u32.u8 $0, packed; }" + ), + constraints="=r,r,r", + dtype=torch.uint8, + ) + return packed.contiguous().view(torch.float4_e2m1fn_x2) + + # Eager path is mostly for testing. + input_bits = input.view(torch.int32) + sign = input_bits & 0x80000000 + magnitude = (input_bits ^ sign).view(torch.float32) + saturated = magnitude >= 6.0 + denormal = (~saturated) & (magnitude < 1.0) + normal = ~(saturated | denormal) + denormal_code = ((magnitude + 4194304.0).view(torch.int32) - 1249902592).to( + torch.uint8 + ) + normal_bits = magnitude.view(torch.int32) + mantissa_odd = (normal_bits >> 22) & 1 + normal_code = ((normal_bits - 1054867457 + mantissa_odd) >> 22).to(torch.uint8) + codes = torch.full_like(magnitude, 7, dtype=torch.uint8) + codes = torch.where(denormal, denormal_code, codes) + codes = torch.where(normal, normal_code, codes) + codes = codes | (((sign >> 28).to(torch.uint8)) & 8) + packed = (codes[..., 1] << 4) | codes[..., 0] + return packed.contiguous().view(torch.float4_e2m1fn_x2) + + +def apply_flex_gemm_body_graph_passes( + body_graph: torch.fx.GraphModule, gemm_op: torch._ops.OpOverload +) -> None: + """Apply FlexGEMM body annotations before generic Inductor graph passes.""" + for graph_pass in FLEX_GEMM_BODY_GRAPH_PASSES: + graph_pass(body_graph, gemm_op) + + +class FlexGemm(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("flex_gemm") + + def __call__( + self, + gemm_op: torch._ops.OpOverload, + body_fn: Callable[..., Any], + gemm_args: tuple[Any, ...], + gemm_kwargs: dict[str, Any], + kernel_options: dict[str, Any], + ) -> Any: + if gemm_op not in FLEX_GEMM_OP_SPECS: + raise RuntimeError(f"unsupported GEMM op for FlexGEMM: {gemm_op}") + if not isinstance(gemm_args, (tuple, list)): + raise RuntimeError(f"gemm_args must be a tuple/list, got {type(gemm_args)}") + gemm_args = tuple(gemm_args) + if not all( + isinstance( + arg, + ( + torch.Tensor, + torch.SymInt, + torch.SymFloat, + torch.SymBool, + int, + float, + bool, + ), + ) + for arg in gemm_args + ): + raise RuntimeError( + "gemm_args must be a tuple of tensors, SymInts, SymFloats, " + f"SymBools, ints, floats, or bools, got {gemm_args}" + ) + if not isinstance(gemm_kwargs, dict): + raise RuntimeError(f"gemm_kwargs must be a dict, got {type(gemm_kwargs)}") + if any( + isinstance(value, torch.Tensor) for value in pytree.tree_leaves(gemm_kwargs) + ): + raise RuntimeError( + "gemm_kwargs must not contain tensor values; pass tensor inputs through gemm_args" + ) + if not isinstance(kernel_options, dict): + raise RuntimeError( + f"kernel_options must be a dict, got {type(kernel_options)}" + ) + + kernel_options = dict(kernel_options) + kernel_options.setdefault("backend", "TRITON") + backend = kernel_options["backend"] + if backend not in _SUPPORTED_BACKENDS: + raise RuntimeError( + f"unsupported FlexGEMM backend: {backend}; " + f"expected one of {sorted(_SUPPORTED_BACKENDS)}" + ) + return super().__call__( + gemm_op, body_fn, gemm_args, gemm_kwargs, kernel_options + ) + + +flex_gemm_hop = FlexGemm() + + +def flex_gemm( + gemm_op: Callable[..., Any], + gemm_args: tuple[Any, ...], + epilogue_fn: Callable[[Any], Any], + *, + gemm_kwargs: dict[str, Any] | None = None, + kernel_options: dict[str, Any] | None = None, +) -> Any: + if gemm_kwargs is None: + gemm_kwargs = {} + if kernel_options is None: + kernel_options = {} + gemm_op = cast(torch._ops.OpOverload, FLEX_GEMM_OP_ALIASES.get(gemm_op, gemm_op)) + + def body_fn(*args: Any) -> Any: + # Keep the traced body positional-only; the HOP carries gemm_kwargs for lowering. + return epilogue_fn(gemm_op(*args, **gemm_kwargs)) + + return flex_gemm_hop(gemm_op, body_fn, gemm_args, gemm_kwargs, kernel_options) + + +@flex_gemm_hop.py_impl(DispatchKey.CompositeExplicitAutograd) +def flex_gemm_dense(gemm_op, body_fn, args, kwargs, kernel_options): + return body_fn(*args) + + +flex_gemm_hop.py_autograd_impl( + autograd_not_implemented(flex_gemm_hop, deferred_error=True) +) + + +@register_fake(flex_gemm_hop) +def flex_gemm_fake_tensor_mode(gemm_op, body_fn, args, kwargs, kernel_options): + return body_fn(*args) + + +@flex_gemm_hop.py_functionalize_impl +def flex_gemm_functionalize(ctx, gemm_op, body_fn, args, kwargs, kernel_options): + unwrapped_args = ctx.unwrap_tensors(args) + with ctx.redispatch_to_next(): + _check_alias_and_mutation( + body_fn, + unwrapped_args, + "flex_gemm", + hasattr(ctx, "mode") and ctx.mode.pre_dispatch, + ) + return ctx.wrap_tensors( + flex_gemm_hop( + gemm_op, + ctx.functionalize(body_fn), + unwrapped_args, + ctx.unwrap_tensors(kwargs), + ctx.unwrap_tensors(kernel_options), + ) + ) + + +@flex_gemm_hop.py_impl(ProxyTorchDispatchMode) +def flex_gemm_proxy_torch_dispatch_mode( + proxy_mode, gemm_op, body_fn, args, kwargs, kernel_options +): + if proxy_mode.enable_tracing: + flat_args = tuple(args) + + def tracing_body_fn(*flat_body_args): + return body_fn(*flat_body_args) + + body_graph = reenter_make_fx( + tracing_body_fn, + subgraph_decomp_table=flex_gemm_body_decomposition_table( + kernel_options, proxy_mode.decomposition_table + ), + )(*flat_args) + apply_flex_gemm_body_graph_passes(body_graph, gemm_op) + _, body_graph_name = unique_graph_id(proxy_mode, prefix="flex_gemm_body_graph") + proxy_mode.tracer.root.register_module(body_graph_name, body_graph) + proxy_args = pytree.tree_map( + proxy_mode.tracer.unwrap_proxy, + (gemm_op, body_graph, flat_args, kwargs, kernel_options), + ) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", + flex_gemm_hop, + proxy_args, + {}, + name="flex_gemm", + ) + return track_tensor_tree( + body_fn(*flat_args), + out_proxy, + constant=None, + tracer=proxy_mode.tracer, + ) + return flex_gemm_hop(gemm_op, body_fn, args, kwargs, kernel_options) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/foreach_map.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/foreach_map.py new file mode 100644 index 0000000000000000000000000000000000000000..0d02515d555d3be737011bd4cab32393acbe5b07 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/foreach_map.py @@ -0,0 +1,24 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +from collections.abc import Callable +from typing import Any + +from torch._higher_order_ops.base_hop import BaseHOP, FunctionWithNoFreeVars + + +class ForeachMap(BaseHOP): + def __init__(self): + super().__init__("foreach_map") + + def __call__(self, fn, *operands, **kwargs): # type: ignore[override] + fn = FunctionWithNoFreeVars(fn) + return super().__call__(fn, *operands, **kwargs) + + +_foreach_map = ForeachMap() + + +def foreach_map(op: Callable, *operands: Any, **kwargs: dict[str, Any]): + from torch._dynamo.polyfills import foreach_map_fn + + return _foreach_map(foreach_map_fn, op, *operands, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/hints_wrap.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/hints_wrap.py new file mode 100644 index 0000000000000000000000000000000000000000..925e1f5d946b5c74fdf1d928a11f9ad11e59b498 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/hints_wrap.py @@ -0,0 +1,141 @@ +# mypy: allow-untyped-defs +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + autograd_not_implemented, + reenter_make_fx, + register_fake, + unique_graph_id, +) +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree + + +# used for wrapping a function/op with context hints +class HintsWrapper(HigherOrderOperator): + def __init__(self): + super().__init__("hints_wrapper") + + def __call__(self, body_fn, args, kwargs, hints): + r""" + Call implementation of hints_wrapper + + Args: + body_fn (Callable): A callable function that is within the scope + that is being traced. + + args (Tuple of torch.Tensor/int/float/bool): A tuple of inputs to + body_fn. + + kwargs (dict): Keyword argument to the body_fn. + + hints (dict): A dict of context hints which could be passed to + backend compiler. + """ + if not isinstance(args, tuple): + args = tuple(args) + + if not all(isinstance(t, (torch.Tensor, int, float, bool)) for t in args): + raise RuntimeError( + f"args must be a tuple of tensors, ints, floats, or bools, got {args}" + ) + + if not isinstance(kwargs, dict): + raise RuntimeError(f"kwargs must be a dict, got {type(kwargs)}") + + if len(kwargs) > 0: + raise RuntimeError( + f"kwargs except for hints are not supported, got {kwargs}" + ) + + if not isinstance(hints, dict): + raise RuntimeError(f"hints must be a dict, got {type(hints)}") + + for k, v in hints.items(): + if not isinstance(k, str): + raise RuntimeError(f"hints key must be a str, got {k}.") + + if not isinstance(v, (int, float, bool, str)): + raise RuntimeError( + "hints must be a dict containing int, float, bool or str " + f"value, got value {v} for key {k}." + ) + + # pyrefly: ignore [missing-attribute] + return super().__call__(body_fn, args, kwargs, hints) + + +hints_wrapper = HintsWrapper() + + +@hints_wrapper.py_impl(DispatchKey.CompositeExplicitAutograd) +def hints_wrapper_dense(body_fn, args, kwargs, hints): + return body_fn(*args, **kwargs) + + +hints_wrapper.py_autograd_impl( + autograd_not_implemented(hints_wrapper, deferred_error=True) +) + + +@register_fake(hints_wrapper, skip_cache=True) +def hints_wrapper_fake_tensor_mode(body_func, args, kwargs, hints): + flat_args = pytree.tree_leaves(args) + return body_func(*flat_args, **kwargs) + + +@hints_wrapper.py_functionalize_impl +def hints_wrapper_functionalize(ctx, body_fn, args, kwargs, hints): + from torch._higher_order_ops.utils import _check_alias_and_mutation + + unwrapped_args = ctx.unwrap_tensors(args) + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + unwrapped_hints = ctx.unwrap_tensors(hints) + with ctx.redispatch_to_next(): + functional_body_fn = ctx.functionalize(body_fn) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + _check_alias_and_mutation( + body_fn, unwrapped_args, "hints_wrapper", pre_dispatch + ) + + outputs = hints_wrapper( + functional_body_fn, + unwrapped_args, + unwrapped_kwargs, + unwrapped_hints, + ) + return ctx.wrap_tensors(outputs) + + +def trace_hints_wrapper(proxy_mode, hints_wrapper, body_fn, args, kwargs, hints): + flat_args = tuple(pytree.tree_leaves(args)) + body_graph = reenter_make_fx(body_fn)(*flat_args, **kwargs) + + _, body_graph_name = unique_graph_id(proxy_mode, prefix="hints_wrapper_body_graph") + proxy_mode.tracer.root.register_module(body_graph_name, body_graph) + + new_args: tuple = (body_graph, flat_args, {}) + # merge hints into kwargs + new_kwargs = {} + new_kwargs["hints"] = hints + + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, new_args) + proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, new_kwargs) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", hints_wrapper, proxy_args, proxy_kwargs, name="hints_wrapper" + ) + + out = body_fn(*flat_args, **kwargs) + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@hints_wrapper.py_impl(ProxyTorchDispatchMode) +def inner(proxy_mode, body_fn, args, kwargs, hints): + if proxy_mode.enable_tracing: + return trace_hints_wrapper( + proxy_mode, hints_wrapper, body_fn, args, kwargs, hints + ) + else: + return hints_wrapper(body_fn, args, kwargs, hints) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/inline_asm_elementwise.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/inline_asm_elementwise.py new file mode 100644 index 0000000000000000000000000000000000000000..039b220841f7e8caa27b45b7938fecd27653ff2c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/inline_asm_elementwise.py @@ -0,0 +1,297 @@ +# mypy: allow-untyped-defs +import functools +import re + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import autograd_not_implemented, register_fake +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree + + +__all__ = ["inline_asm_elementwise"] + + +class InlineAsmElementwiseOp(HigherOrderOperator): + """Execute inline PTX assembly elementwise over tensors. + + This is an elementwise map where the function body is inline assembly. + Input tensors are implicitly broadcast to the same shape. + + Each invocation of the inline asm processes ``pack`` elements at a time. + Exactly which set of inputs a given invocation receives is unspecified. + + Output strides follow PyTorch's standard pointwise striding propagation + rules. + + In eager mode, the assembly is executed via the CUDA Jiterator. Under + ``torch.compile`` the assembly is lowered to Triton's + ``tl.inline_asm_elementwise`` via Inductor, which allows fusion with + surrounding operators. + + Args: + *inputs: Input tensors whose values are passed to the asm block. + asm_str: PTX assembly string. Operands use ``$N`` syntax + (e.g. ``$0`` for the first output, ``$1`` for the first input). + constraints: Inline-asm constraints in LLVM format. Output constraints + are prefixed with ``=`` (e.g. ``"=f,f,f"`` for one float output + and two float inputs). + dtype: Element type of the returned tensor. + is_pure: Must be ``True``. If true, the compiler may assume the asm + block has no side-effects. + pack: Number of elements processed per asm invocation. When + ``pack > 1``, the constraint string must list ``pack`` outputs + and ``pack`` copies of each input. Requires ``torch.compile``. + + Returns: + A tensor with the broadcast shape of the inputs and the given dtype. + + Example:: + + >>> # xdoctest: +SKIP(requires CUDA) + >>> # Float32 fused multiply-add via PTX + >>> result = inline_asm_elementwise( + ... a, b, c, + ... asm_str="fma.rn.f32 $0, $1, $2, $3;", + ... constraints="=f,f,f,f", + ... dtype=torch.float32, + ... ) + + >>> # xdoctest: +SKIP(requires CUDA) + >>> # pack=2: each asm invocation processes two elements + >>> result = inline_asm_elementwise( + ... x, + ... asm_str="mov.b32 $0, $2; mov.b32 $1, $3;", + ... constraints="=r,=r,r,r", + ... dtype=torch.float32, + ... pack=2, + ... ) + """ + + def __init__(self): + super().__init__("inline_asm_elementwise") + + def __call__( + self, + *inputs: torch.Tensor, + asm_str: str, + constraints: str, + dtype: torch.dtype, + is_pure: bool = True, + pack: int = 1, + ) -> torch.Tensor: + if not is_pure: + raise ValueError("inline_asm_elementwise only supports is_pure=True") + # pyrefly: ignore [missing-attribute] + return super().__call__( + *inputs, + asm_str=asm_str, + constraints=constraints, + dtype=dtype, + is_pure=True, + pack=pack, + ) + + +inline_asm_elementwise = InlineAsmElementwiseOp() + + +def _parse_constraints(constraints: str) -> tuple[int, int]: + parts = [p.strip() for p in constraints.split(",")] + n_outputs = sum(1 for p in parts if p.startswith("=")) + n_inputs = len(parts) - n_outputs + return n_outputs, n_inputs + + +_DTYPE_TO_CUDA_TYPE = { + torch.float32: "float", + torch.float64: "double", + torch.float16: "__half", + torch.bfloat16: "__nv_bfloat16", + torch.int32: "int", + torch.int64: "long long", + torch.int16: "short", + torch.int8: "signed char", + torch.uint8: "unsigned char", + torch.uint16: "unsigned short", + torch.uint32: "unsigned int", + torch.bool: "bool", +} + + +_TRITON_ARG_RE = re.compile(r"\$(\d+)") + + +def _triton_asm_to_cuda_asm(asm_str: str) -> str: + return _TRITON_ARG_RE.sub(r"%\1", asm_str) + + +@functools.lru_cache +def _get_jiterator_fn( + asm_str: str, + constraints: str, + n_inputs: int, + input_dtype: torch.dtype, + output_dtype: torch.dtype, +): + from torch.cuda.jiterator import _create_jit_fn + + cuda_asm = _triton_asm_to_cuda_asm(asm_str) + + constraint_parts = [p.strip() for p in constraints.split(",")] + output_constraints = [p.lstrip("=") for p in constraint_parts if p.startswith("=")] + input_constraints = [p for p in constraint_parts if not p.startswith("=")] + + if input_dtype not in _DTYPE_TO_CUDA_TYPE: + raise ValueError(f"Unsupported input dtype for inline asm: {input_dtype}") + if output_dtype not in _DTYPE_TO_CUDA_TYPE: + raise ValueError(f"Unsupported output dtype for inline asm: {output_dtype}") + + input_type = _DTYPE_TO_CUDA_TYPE[input_dtype] + output_type = _DTYPE_TO_CUDA_TYPE[output_dtype] + + input_params = ", ".join(f"{input_type} in{i}" for i in range(n_inputs)) + out_constraints_str = ", ".join(f'"={c}"(result)' for c in output_constraints) + in_constraints_str = ", ".join( + f'"{c}"(in{i})' for i, c in enumerate(input_constraints) + ) + escaped_asm = ( + cuda_asm.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + ) + + code = f""" +template +{output_type} inline_asm_kernel({input_params}) {{ + {output_type} result; + asm volatile ( + "{escaped_asm}" + : {out_constraints_str} + : {in_constraints_str} + ); + return result; +}} +""" + + return _create_jit_fn(code) + + +def _inline_asm_dense(*inputs, asm_str, constraints, dtype, is_pure, pack): + if not inputs: + raise ValueError("inline_asm_elementwise requires at least one input tensor") + + inputs = torch.broadcast_tensors(*inputs) + + if not inputs[0].is_cuda: + raise RuntimeError("inline_asm_elementwise only supports CUDA tensors") + + if pack > 1: + raise RuntimeError( + "inline_asm_elementwise with pack > 1 requires torch.compile" + ) + + n_outputs, n_inputs = _parse_constraints(constraints) + + if n_outputs != 1: + raise ValueError(f"Expected 1 output constraint, got {n_outputs}") + + if n_inputs != len(inputs): + raise ValueError( + f"Constraint string specifies {n_inputs} inputs but got " + f"{len(inputs)} tensor(s)" + ) + + # Jiterator generates a single input type for all inputs — mixed dtypes + # would produce incorrect CUDA code. + input_dtypes = {inp.dtype for inp in inputs} + if len(input_dtypes) > 1: + raise ValueError( + f"All inputs must have the same dtype for eager execution, " + f"got {sorted(str(d) for d in input_dtypes)}" + ) + + jit_fn = _get_jiterator_fn( + asm_str=asm_str, + constraints=constraints, + n_inputs=len(inputs), + input_dtype=inputs[0].dtype, + output_dtype=dtype, + ) + + return jit_fn(*inputs) + + +@inline_asm_elementwise.py_impl(DispatchKey.CompositeExplicitAutograd) +def _(*inputs, asm_str, constraints, dtype, is_pure=True, pack=1): + return _inline_asm_dense( + *inputs, + asm_str=asm_str, + constraints=constraints, + dtype=dtype, + is_pure=is_pure, + pack=pack, + ) + + +inline_asm_elementwise.py_autograd_impl( + autograd_not_implemented(inline_asm_elementwise, deferred_error=True) +) + + +def _elementwise_output_like(*inputs, dtype): + from torch._prims_common import compute_elementwise_output_logical_to_physical_perm + + broadcasted = torch.broadcast_tensors(*inputs) + l2p_perm, _ = compute_elementwise_output_logical_to_physical_perm(*broadcasted) + return torch.empty_permuted( + broadcasted[0].shape, l2p_perm, dtype=dtype, device=broadcasted[0].device + ) + + +@register_fake(inline_asm_elementwise, skip_cache=True) +def _(*inputs, asm_str, constraints, dtype, is_pure=True, pack=1): + return _elementwise_output_like(*inputs, dtype=dtype) + + +@inline_asm_elementwise.py_impl(ProxyTorchDispatchMode) +def _(mode, *inputs, asm_str, constraints, dtype, is_pure=True, pack=1): + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, inputs) + + out_proxy = mode.tracer.create_proxy( + "call_function", + inline_asm_elementwise, + proxy_args, + { + "asm_str": asm_str, + "constraints": constraints, + "dtype": dtype, + "is_pure": is_pure, + "pack": pack, + }, + name="inline_asm_elementwise", + ) + + out = inline_asm_elementwise( + *inputs, + asm_str=asm_str, + constraints=constraints, + dtype=dtype, + is_pure=is_pure, + pack=pack, + ) + return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + + +@inline_asm_elementwise.py_functionalize_impl +def _(ctx, *inputs, asm_str, constraints, dtype, is_pure=True, pack=1): + unwrapped_inputs = ctx.unwrap_tensors(inputs) + + with ctx.redispatch_to_next(): + res = inline_asm_elementwise( + *unwrapped_inputs, + asm_str=asm_str, + constraints=constraints, + dtype=dtype, + pack=pack, + ) + return ctx.wrap_tensors(res) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_leaf_function.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_leaf_function.py new file mode 100644 index 0000000000000000000000000000000000000000..9a57edbbd91b472caa2647530981d2bba5f94761 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_leaf_function.py @@ -0,0 +1,946 @@ +import contextlib +import functools +from collections.abc import Callable, Generator, Sequence +from dataclasses import dataclass +from typing import Any, NamedTuple + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey, DispatchKeySet +from torch._custom_class_base import CustomClassBase +from torch._higher_order_ops.utils import register_fake +from torch._library.opaque_object import register_custom_class +from torch._ops import HigherOrderOperator +from torch.autograd.graph import get_gradient_edge +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.nn.utils.stateless import _reparametrize_module + + +_leaf_function_module_retriever: Callable[[int], Any] | None = None + +# Separate storage for the make_fx / _invoke_leaf_function_python path. +# We can't use Dynamo's register_user_object because it requires a Source +# (for bytecode generation) and adds entries to index_to_bytecode_constructor. +# In the make_fx path we have neither a Source nor bytecode generation, so we +# maintain our own dict keyed by negative indices to avoid collisions with +# Dynamo's non-negative indices. +_makefx_module_storage: dict[int, torch.nn.Module] = {} +_makefx_next_index = 0 + + +def store_makefx_modules(modules: list[torch.nn.Module]) -> tuple[int, ...]: + """Store modules for the make_fx path and return their assigned indices. + + Uses negative indices to avoid collisions with Dynamo's register_user_object + which uses non-negative indices. + """ + global _makefx_next_index + indices = [] + for mod in modules: + _makefx_next_index -= 1 + _makefx_module_storage[_makefx_next_index] = mod + indices.append(_makefx_next_index) + return tuple(indices) + + +def reset_makefx_module_storage() -> None: + global _makefx_next_index + _makefx_next_index = 0 + _makefx_module_storage.clear() + + +class _LeafCallable(CustomClassBase): + def __init__(self, fn: Callable) -> None: + self._fn = fn + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self._fn(*args, **kwargs) + + +register_custom_class(_LeafCallable, typ="symbolic") + + +def set_leaf_function_module_retriever(retriever: Callable[[int], Any]) -> None: + global _leaf_function_module_retriever + _leaf_function_module_retriever = retriever + + +class LeafModuleState(NamedTuple): + """ + In dynamo, nn.Module arguments to leaf functions are converted to this + pytree format (index, parameters, buffers). This structure is then + flattened to produce the actual inputs to invoke_leaf_function. + + At runtime, the original module is reconstructed from it. + """ + + nn_module_index: int + named_parameters: dict[str, torch.nn.Parameter] + named_buffers: dict[str, torch.Tensor] + + +def convert_modules_to_states(values: Any, module_to_index: dict[int, int]) -> Any: + """Replace nn.Module instances in a pytree with LeafModuleState objects. + + Args: + values: A pytree of values that may contain nn.Module instances. + module_to_index: Mapping from id(module) to its integer index. + """ + + def module_to_state(val: Any) -> Any: + if isinstance(val, torch.nn.Module): + return LeafModuleState( + nn_module_index=module_to_index[id(val)], + named_parameters=dict(val.named_parameters()), + named_buffers=dict(val.named_buffers()), + ) + return val + + return pytree.tree_map(module_to_state, values) + + +def _resolve_mutated_flat_indices( + fn: Callable, + mutates_args: frozenset[str], + num_flat_args: int, + input_spec: pytree.TreeSpec, +) -> str: + """Resolve mutates_args expressions to a comma-separated string of flat-arg indices. + + Each expression in mutates_args (e.g. "x", "model.running_mean") is evaluated + against sentinel values to determine which flat-arg positions are mutated. + + Example: for ``def fn(x, model)`` where model is an nn.Module with parameters + ``weight`` and ``bias``, the flat args are ``[x, nn_module_index, weight, bias]``. + Given ``mutates_args={"model.weight"}``, this assigns sentinels ``[0, 1, 2, 3]`` + to the flat args, evaluates ``model.weight`` to ``2``, and returns ``"2"``. + """ + import inspect + + class _AttrDict: + pass + + def _set_nested_attr(obj: _AttrDict, fqn: str, value: Any) -> None: + parts = fqn.split(".") + for part in parts[:-1]: + if not hasattr(obj, part): + setattr(obj, part, _AttrDict()) + obj = getattr(obj, part) + setattr(obj, parts[-1], value) + + def _lms_to_attr_dict(val: Any) -> Any: + if isinstance(val, LeafModuleState): + target = _AttrDict() + for fqn, sentinel in val.named_parameters.items(): + _set_nested_attr(target, fqn, sentinel) + for fqn, sentinel in val.named_buffers.items(): + _set_nested_attr(target, fqn, sentinel) + return target + return val + + sig = inspect.signature(fn) + sentinels = list(range(num_flat_args)) + args_struct, kwargs_struct = pytree.tree_unflatten(sentinels, input_spec) + args_eval, kwargs_eval = pytree.tree_map( + _lms_to_attr_dict, + (args_struct, kwargs_struct), + is_leaf=lambda x: isinstance(x, LeafModuleState), + ) + namespace = dict(sig.bind(*args_eval, **kwargs_eval).arguments) + + indices: list[int] = [] + for expr in mutates_args: + # Empty __builtins__ prevents access to builtins like __import__, open, exec. + result = eval(expr, {"__builtins__": {}}, namespace) + leaves = pytree.tree_leaves(result) + for sentinel in leaves: + if not isinstance(sentinel, int): + raise ValueError( + f"mutates_args expression '{expr}' resolved to a non-leaf value " + f"of type {type(sentinel).__name__}. Expressions must resolve to " + f"individual tensor positions, e.g. 'model.weight' not 'model'." + ) + indices.append(sentinel) + indices.sort() + return ",".join(str(i) for i in indices) + + +@dataclass +class GradientInfo: + """ + We need the gradient edge to trigger the autograd engine backward. + + We need the tensor metadata (size, stride, dtype, device) to create zeros when + gradient is None at runtime but required by the backward graph (because the graph + is traced with fake implementation). + """ + + edge: torch.autograd.graph.GradientEdge + size: torch.Size + stride: tuple[int, ...] + dtype: torch.dtype + device: torch.device + + +def _retrieve_module_by_index(nn_module_index: int) -> torch.nn.Module: + # Check make_fx storage first (used by _invoke_leaf_function_python). + # Fall back to the Dynamo retriever (used by the compiled path). + if nn_module_index in _makefx_module_storage: + if nn_module_index >= 0: + raise RuntimeError( + f"Expected negative nn_module_index for non-strict trace over leaf_function, but got {nn_module_index}." + ) + return _makefx_module_storage[nn_module_index] + + if _leaf_function_module_retriever is None: + raise RuntimeError("Leaf function module retriever not set.") + + mod = _leaf_function_module_retriever(nn_module_index) + if not isinstance(mod, torch.nn.Module): + raise TypeError( + f"Expected nn.Module at index {nn_module_index} for leaf function invocation, " + f"but got {type(mod).__name__}." + ) + return mod + + +def check_escaped_gradients( + outputs: Any, + inputs: Sequence[Any], + requires_grad_indices: set[int], +) -> None: + """ + Check if autograd graph depends on tensors that are not passed as explicit inputs. + + Controlled by torch._dynamo.config.leaf_function_check_escaped_gradients. + """ + if not requires_grad_indices: + return + + import torch._dynamo.config as config + + if not config.leaf_function_check_escaped_gradients: + return + + input_nodes: set[torch.autograd.graph.Node] = set() + for i, inp in enumerate(inputs): + if ( + isinstance(inp, torch.Tensor) + and i in requires_grad_indices + and inp.requires_grad + ): + edge = get_gradient_edge(inp) + if edge.node is not None: + input_nodes.add(edge.node) + + flat_outputs = outputs if isinstance(outputs, tuple) else (outputs,) + start_nodes: set[torch.autograd.graph.Node] = { + out.grad_fn + for out in flat_outputs + if isinstance(out, torch.Tensor) + and out.requires_grad + and out.grad_fn is not None + } + if not start_nodes: + return + + escaped: set[torch.autograd.graph.Node] = set() + visited: set[torch.autograd.graph.Node] = set() + stack = list(start_nodes) + + while stack: + node = stack.pop() + if node in visited or node in input_nodes: + continue + visited.add(node) + + for next_node, _ in node.next_functions: + if next_node is None or next_node in input_nodes: + continue + if not next_node.next_functions: + escaped.add(next_node) + else: + stack.append(next_node) + + if escaped: + tensor_info = [] + for node in escaped: + if hasattr(node, "variable"): + t = node.variable + tensor_info.append( + f" - Tensor(shape={list(t.shape)}, dtype={t.dtype})" + ) + tensor_details = ( + "\n".join(tensor_info) if tensor_info else " (tensor details unavailable)" + ) + + raise RuntimeError( + f"@leaf_function detected {len(escaped)} tensor(s) with requires_grad=True " + f"that are not passed as explicit inputs:\n{tensor_details}\n" + f"Gradients will not flow back to closure-captured or global tensors. " + f"Pass them as explicit arguments to the leaf function." + ) + + +@contextlib.contextmanager +def unflatten_args_with_modules( + flat_args: tuple[Any, ...], input_spec: pytree.TreeSpec +) -> Generator[tuple[list[Any] | tuple[Any, ...], dict[str, Any]], None, None]: + args, kwargs = pytree.tree_unflatten(flat_args, input_spec) + + with contextlib.ExitStack() as stack: + + def process_module_state(state: LeafModuleState) -> torch.nn.Module: + orig_module = _retrieve_module_by_index(state.nn_module_index) + stack.enter_context( + _reparametrize_module( + orig_module, + {**state.named_parameters, **state.named_buffers}, + ) + ) + return orig_module + + new_args, new_kwargs = pytree.tree_map_only( + LeafModuleState, + process_module_state, + (args, kwargs), + is_leaf=lambda x: isinstance(x, LeafModuleState), + ) + yield new_args, new_kwargs + + +def flatten_args_with_modules( + args_kwargs: tuple[Any, ...], +) -> list[Any]: + def expand_module(x: Any) -> Any: + if isinstance(x, torch.nn.Module): + return LeafModuleState( + nn_module_index=-1, + named_parameters=dict(x.named_parameters()), + named_buffers=dict(x.named_buffers()), + ) + return x + + expanded = pytree.tree_map(expand_module, args_kwargs) + return pytree.tree_leaves(expanded) + + +def make_leaf_function_wrappers( + real_fn: Callable[..., Any], + fake_fn: Callable[..., Any], + captured_out_spec: list[pytree.TreeSpec | None], +) -> tuple[Callable[..., tuple[Any, ...]], Callable[..., tuple[Any, ...]]]: + """Wrap real_fn and fake_fn to flatten outputs and capture the output TreeSpec. + + Both wrappers share the same captured output spec: the first call (typically + fake_fn during tracing) records it, and subsequent calls verify consistency. + The caller passes in a single-element list and reads captured_out_spec[0] + after the wrappers have been called. + + Used by both the Dynamo path (_call_leaf_function in torch.py) and the + make_fx path (_invoke_leaf_function_python in decorators.py). + """ + + def _wrap(fn: Callable[..., Any]) -> Callable[..., tuple[Any, ...]]: + if len(captured_out_spec) != 1: + raise RuntimeError( + f"captured_out_spec must be a single-element list, got length {len(captured_out_spec)}" + ) + + def wrapper(*args: Any, **kwargs: Any) -> tuple[Any, ...]: + out = fn(*args, **kwargs) + + flat_out, out_spec = pytree.tree_flatten(out) + if captured_out_spec[0] is None: + captured_out_spec[0] = out_spec + elif captured_out_spec[0] != out_spec: + raise AssertionError( + f"leaf_function output structure mismatch: " + f"expected {captured_out_spec[0]}, got {out_spec}. " + f"This can happen if the real function and fake function return " + f"different pytree structures (e.g., dict vs tuple, different number " + f"of elements). Ensure both functions return the same structure." + ) + return tuple(flat_out) + + return wrapper + + return _wrap(real_fn), _wrap(fake_fn) + + +def autograd_grad_with_gradient_info( + output_infos: Sequence[GradientInfo | None], + input_infos: Sequence[GradientInfo | None], + grad_outputs: Sequence[Any] | None = None, + retain_graph: bool | None = None, + create_graph: bool = False, + allow_unused: bool = False, +) -> tuple[torch.Tensor | None, ...]: + """ + Compute gradients using GradientInfo, it additionally handles the case + where input and output infos are None. + + Args: + output_infos: GradientInfo for each output (None if no grad_fn), + input_infos: GradientInfo for each input (None if not requires_grad) + grad_outputs: Gradients w.r.t. outputs + + Returns a tuple of gradients with None for inputs that don't require grad. + """ + filtered_output_edges = [] + filtered_grad_outputs = [] + for i, info in enumerate(output_infos): + if info is not None and info.edge.node is not None: + filtered_output_edges.append(info.edge) + if grad_outputs is not None: + filtered_grad_outputs.append(grad_outputs[i]) + + filtered_input_edges = [] + filtered_input_infos = [] + input_indices = [] + for i, info in enumerate(input_infos): + if info is not None: + filtered_input_edges.append(info.edge) + filtered_input_infos.append(info) + input_indices.append(i) + + if not filtered_output_edges or not filtered_input_edges: + return tuple(None for _ in input_infos) + + grads = torch.autograd.grad( + outputs=filtered_output_edges, + inputs=filtered_input_edges, + grad_outputs=filtered_grad_outputs if grad_outputs is not None else None, + retain_graph=retain_graph, + create_graph=create_graph, + allow_unused=allow_unused, + ) + + # Reconstruct full gradient tuple with Nones at proper positions. + # + # NB: For unused inputs that require grad, we return zeros instead of None. + # This is necessary because during AOT tracing, we use fake_impl to determine + # the backward graph structure. fake_impl may not accurately reflect which + # inputs are truly used for gradients in real_impl. For example, users often + # write fake_impl by returning torch.empty_like(input) to get the right shape + # without actually using the input in a differentiable computation. So we must + # be permissive and assume all inputs with requires_grad=True could need + # gradients. When multiple invoke_leaf_function calls share an input (e.g., + # a module's forward + hook both receiving the same tensor), the traced + # backward graph generates explicit add operations to accumulate their + # gradients. At runtime, if one leaf function doesn't actually use the input, + # autograd.grad returns None for it, and the traced add(grad1, grad2) fails + # because one operand is None. Returning zeros ensures the add always works. + result: list[torch.Tensor | None] = [None] * len(input_infos) + for filtered_idx, original_idx in enumerate(input_indices): + grad = grads[filtered_idx] + if grad is None: + info = filtered_input_infos[filtered_idx] + grad = torch.empty_strided( + info.size, info.stride, dtype=info.dtype, device=info.device + ).zero_() + result[original_idx] = grad + + return tuple(result) + + +def _make_forward( + fn: Callable, + include_keys: DispatchKeySet, + exclude_keys: DispatchKeySet, +) -> tuple[Callable, dict[str, Any]]: + state: dict[str, Any] = {"inputs": None, "outputs": None} + + @functools.wraps(fn) + def forward(*args, **kwargs): + effective_keys = include_keys + if include_keys.has(DispatchKey.PythonDispatcher): + effective_keys = effective_keys.remove(DispatchKey.PythonDispatcher) + if effective_keys.has(DispatchKey.Python): + effective_keys = effective_keys.remove(DispatchKey.Python) + with torch._C._ForceDispatchKeyGuard(effective_keys, exclude_keys): + with torch.enable_grad(): + outputs = fn(*args, **kwargs) + + flat_inputs = flatten_args_with_modules((args, kwargs)) + requires_grad_indices = { + i + for i, inp in enumerate(flat_inputs) + if isinstance(inp, torch.Tensor) and inp.requires_grad + } + check_escaped_gradients(outputs, flat_inputs, requires_grad_indices) + + state["inputs"] = tuple( + GradientInfo( + edge=get_gradient_edge(inp), + size=inp.size(), + stride=inp.stride(), + dtype=inp.dtype, + device=inp.device, + ) + if isinstance(inp, torch.Tensor) and inp.requires_grad + else None + for inp in flat_inputs + ) + + if outputs is None: + state["outputs"] = () + else: + state["outputs"] = tuple( + GradientInfo( + edge=get_gradient_edge(out), + size=out.size(), + stride=out.stride(), + dtype=out.dtype, + device=out.device, + ) + if isinstance(out, torch.Tensor) + and out.requires_grad + and out.grad_fn is not None + else None + for out in outputs + ) + + return pytree.tree_map_only( + torch.Tensor, + lambda t: t.detach().requires_grad_(t.requires_grad), + outputs, + ) + + return forward, state + + +class InvokeLeafFunction(HigherOrderOperator): + def __init__(self): + super().__init__("invoke_leaf_function", supports_training_input_mutation=True) + + def __call__( + self, + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices="", + ): + """ + real_fn_callable: _LeafCallable wrapping the real function + fake_fn_callable: _LeafCallable wrapping the fake function + input_spec: pytree.TreeSpec for unflattening flat_args back to (args, kwargs) + mutated_arg_indices: comma-separated string of flat-arg indices that are + declared as mutated (e.g. "1,2"), or "" for no mutations. Encoded as a + string so it is a pytree leaf for the HOP schema infrastructure. + requires_grad_indices: comma-separated string of flat-arg indices that + require grad (e.g. "0,1"), or "" for none. + """ + return super().__call__( # type: ignore[attr-defined] + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices=requires_grad_indices, + ) + + # pyrefly: ignore [bad-override] + def gen_schema( + self, + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices="", + ): + from torch._higher_order_ops.schema import HopSchemaGenerator + from torch._higher_order_ops.utils import _maybe_fake_prop_ignore_unbacked + from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing + + mutated_set = _parse_mutated_arg_indices(mutated_arg_indices) + + with disable_proxy_modes_tracing(): + if mutated_set: + schema_flat_args = tuple( + arg.detach().clone() + if isinstance(arg, torch.Tensor) and i in mutated_set + else arg + for i, arg in enumerate(flat_args) + ) + else: + schema_flat_args = flat_args + + def run_fake(*unfunc_flat_args): + with unflatten_args_with_modules(unfunc_flat_args, input_spec) as ( + args, + kwargs, + ): + return fake_fn_callable(*args, **kwargs) + + fake_outputs = _maybe_fake_prop_ignore_unbacked(run_fake, schema_flat_args) + + gen = HopSchemaGenerator(self) + gen.add_arg("real_fn_callable", real_fn_callable) + gen.add_arg("fake_fn_callable", fake_fn_callable) + gen.add_arg("input_spec", input_spec) + gen.add_arg("mutated_arg_indices", mutated_arg_indices) + for i, arg in enumerate(flat_args): + gen.add_arg(f"arg{i}", arg, is_mutated=i in mutated_set) + gen.add_arg( + "requires_grad_indices", + requires_grad_indices, + default_value="", + kw_only=True, + ) + + if isinstance(fake_outputs, tuple): + for out in fake_outputs: + gen.add_output(out) + else: + if fake_outputs is not None: + raise AssertionError( + f"Expected fake_outputs to be a tuple or None, got {type(fake_outputs)}" + ) + gen.add_output(fake_outputs) + + return gen.gen_schema() + + +invoke_leaf_function = InvokeLeafFunction() + + +# NOTE: [Autograd support for invoke_leaf_function] +# +# The overall idea is that when the real forward executes, we are going to build an autograd graph +# and save it. When the real backward executes, we are going to invoke the autograd graph. +# We need to build these "real_forward" and "real_backward" functions from the "real_fn". +# +# Inputs: +# real_fn_callable/fake_fn_callable are _LeafCallable objects that wrap real_fn and fake_fn. +# These functions were created in dynamo by wrapping the user's original leaf function and fake function: +# - They accept *flat_args (flattened LeafModuleState objects + other args) +# - They unflatten flat_args and convert LeafModuleState back to nn.Modules +# - They call the user's original leaf function with the reconstructed args +# - They return the user function's outputs +# +# We wrap real_fn (via _make_forward) to handle autograd properly: +# 1. Detach inputs and outputs to isolate the leaf function's autograd graph from the +# outer graph (gradients flow through our backward, not internal ops) +# 2. Real function is invoked at backend dispatch keys (i.e. CompositeExplicitAutograd) +# where autograd is disabled. We re-enable grad and restore dispatch keys for the autograd engine to work. +# 3. Store GradientInfo (gradient edges + tensor metadata) instead of full tensors for backward, +# which is sufficient for autograd.grad and avoids keeping tensors alive. +# +# We automatically generate backward functions: +# - real_backward uses the stored input/output GradientInfo and invokes the autograd engine +# - fake_backward creates empty gradients for inputs that requires grad + + +class InvokeLeafFunctionAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + ): + include_keys = torch._C._dispatch_tls_local_include_set() + exclude_keys = torch._C._dispatch_tls_local_exclude_set() + + requires_grad_indices = ",".join( + str(i) + for i, arg in enumerate(flat_args) + if isinstance(arg, torch.Tensor) and arg.requires_grad + ) + + real_forward, real_state = _make_forward( + real_fn_callable, include_keys, exclude_keys + ) + + def real_backward(*grads): + if real_state["inputs"] is None or real_state["outputs"] is None: + raise RuntimeError( + "invoke_leaf_function backward expects inputs/outputs to be set in forward." + ) + return autograd_grad_with_gradient_info( + output_infos=real_state["outputs"], + input_infos=real_state["inputs"], + grad_outputs=grads, + allow_unused=True, + ) + + input_infos_for_fake = tuple( + GradientInfo( + edge=None, # type: ignore[arg-type] + size=arg.size(), + stride=arg.stride(), + dtype=arg.dtype, + device=arg.device, + ) + if isinstance(arg, torch.Tensor) and arg.requires_grad + else None + for arg in flat_args + ) + + def fake_backward(*grads): + return tuple( + torch.empty_strided( + info.size, info.stride, dtype=info.dtype, device=info.device + ) + if info is not None + else None + for info in input_infos_for_fake + ) + + new_real_fn_callable = _LeafCallable(real_forward) + + with torch._C._AutoDispatchBelowAutograd(): + fw_outputs = invoke_leaf_function( + new_real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices=requires_grad_indices, + ) + + hook_real = getattr(real_fn_callable, "_leaf_hook_real_fn", None) + hook_fake = getattr(real_fn_callable, "_leaf_hook_fake_fn", None) + if hook_real is not None: + if hook_fake is None: + raise AssertionError("expected hook_fake to be not None") + hook_captured_out_spec: list[pytree.TreeSpec | None] = [None] + wrapped_hook_real, wrapped_hook_fake = make_leaf_function_wrappers( + hook_real, hook_fake, hook_captured_out_spec + ) + hook_real_callable = _LeafCallable(wrapped_hook_real) + hook_fake_callable = _LeafCallable(wrapped_hook_fake) + + grad_tensors = [ + arg + for arg in flat_args + if isinstance(arg, torch.Tensor) and arg.requires_grad + ] + if grad_tensors: + + @torch._dynamo.disable + def _multi_grad_callback( + grads: Sequence[torch.Tensor], + ) -> None: + _, hook_spec = pytree.tree_flatten((tuple(grads), {})) + invoke_leaf_function( + hook_real_callable, + hook_fake_callable, + hook_spec, + "", + *grads, + ) + + torch.autograd.graph.register_multi_grad_hook( + grad_tensors, _multi_grad_callback + ) + + ctx.real_backward = real_backward + ctx.fake_backward = fake_backward + + return fw_outputs + + @staticmethod + # pyrefly: ignore [bad-override] + def backward(ctx, *grads): + real_bw_callable = _LeafCallable(ctx.real_backward) + fake_bw_callable = _LeafCallable(ctx.fake_backward) + _, bw_input_spec = pytree.tree_flatten((grads, {})) + fw_grads = invoke_leaf_function( + real_bw_callable, fake_bw_callable, bw_input_spec, "", *grads + ) + return None, None, None, None, *fw_grads + + +@invoke_leaf_function.py_autograd_impl +def invoke_leaf_function_autograd( + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices="", +): + return InvokeLeafFunctionAutogradOp.apply( + real_fn_callable, fake_fn_callable, input_spec, mutated_arg_indices, *flat_args + ) + + +# TODO: aliasing is not allowed +@invoke_leaf_function.py_functionalize_impl +def invoke_leaf_function_functionalization(ctx, *all_args, **kwargs): + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, + ) + from torch._higher_order_ops.utils import HopInstance + + unwrapped_args = ctx.unwrap_tensors(all_args) + hop_instance = HopInstance.create(invoke_leaf_function, *unwrapped_args, **kwargs) + if can_auto_functionalize(hop_instance): + return do_auto_functionalize_v2(ctx.mode, hop_instance, all_args, kwargs) + + from torch._higher_order_ops.effects import handle_effects + + return handle_effects( + ctx.mode._allow_token_discovery, + ctx.mode._tokens, + invoke_leaf_function, + all_args, + kwargs, + ) + + +@invoke_leaf_function.py_impl(ProxyTorchDispatchMode) +def invoke_leaf_function_proxy_mode(proxy_mode, *all_args, **kwargs): + out = invoke_leaf_function(*all_args, **kwargs) + proxies = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, all_args) + proxy = proxy_mode.tracer.create_proxy( + "call_function", invoke_leaf_function, proxies, kwargs + ) + return track_tensor_tree(out, proxy, constant=None, tracer=proxy_mode.tracer) + + +def _validate_outputs_match( + fake_output: Any, + real_output: Any, +) -> None: + """ + Validate that fake_fn and real_fn outputs have matching pytree structure, + shapes, and dtypes. + + Raises: + RuntimeError: If outputs don't match with detailed error message. + """ + fake_flat, fake_spec = pytree.tree_flatten(fake_output) + real_flat, real_spec = pytree.tree_flatten(real_output) + + if fake_spec != real_spec: + raise RuntimeError( + f"Output structure mismatch in @leaf_function decorator.\n" + f"fake_impl returned structure: {fake_spec}\n" + f"real_impl returned structure: {real_spec}\n" + f"The fake_impl must return outputs with the same pytree structure as real_impl." + ) + + if len(fake_flat) != len(real_flat): + raise RuntimeError( + f"Output count mismatch in @leaf_function decorator.\n" + f"fake_impl returned {len(fake_flat)} values\n" + f"real_impl returned {len(real_flat)} values" + ) + + for i, (fake_val, real_val) in enumerate(zip(fake_flat, real_flat)): + fake_is_tensor = isinstance(fake_val, torch.Tensor) + real_is_tensor = isinstance(real_val, torch.Tensor) + + if fake_is_tensor != real_is_tensor: + raise RuntimeError( + f"Output type mismatch at position {i} in @leaf_function decorator.\n" + f"fake_impl returned: {type(fake_val).__name__}\n" + f"real_impl returned: {type(real_val).__name__}" + ) + + if fake_is_tensor: + if fake_val.shape != real_val.shape: + raise RuntimeError( + f"Shape mismatch at output position {i} in @leaf_function decorator.\n" + f"fake_impl output shape: {list(fake_val.shape)}\n" + f"real_impl output shape: {list(real_val.shape)}\n" + f"The fake_impl must produce tensors with the same shapes as real_impl." + ) + + if fake_val.dtype != real_val.dtype: + raise RuntimeError( + f"Dtype mismatch at output position {i} in @leaf_function decorator.\n" + f"fake_impl output dtype: {fake_val.dtype}\n" + f"real_impl output dtype: {real_val.dtype}\n" + f"The fake_impl must produce tensors with the same dtypes as real_impl." + ) + + +def _parse_mutated_arg_indices(s: str) -> set[int]: + return {int(x) for x in s.split(",") if x} + + +def _check_no_input_mutation( + flat_args: tuple[Any, ...], + version_before: list[int], + mutated_arg_indices: str = "", +) -> None: + mutated_set = _parse_mutated_arg_indices(mutated_arg_indices) + for i, arg in enumerate(flat_args): + if isinstance(arg, torch.Tensor) and arg._version != version_before[i]: + if i not in mutated_set: + raise RuntimeError( + f"Undeclared in-place mutation on input tensor at position {i}. " + f"Declare it in @leaf_function(mutates_args=...) or avoid mutating inputs." + ) + + +@register_fake(invoke_leaf_function) +def invoke_leaf_function_fake( + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices="", +): + with unflatten_args_with_modules(flat_args, input_spec) as (args, kwargs): + return fake_fn_callable(*args, **kwargs) + + +def _detach_with_grad_dtype(arg): + # Tensor.detach() resets grad_dtype to the tensor's own dtype, dropping + # any caller-set grad_dtype (e.g. param.grad_dtype = torch.float32 on a + # bf16 weight). Propagate it back so the inner autograd graph accumulates + # the kernel's gradient at the requested dtype. grad_dtype is only + # meaningful on leaf tensors. + if not isinstance(arg, torch.Tensor): + return arg + detached = arg.detach() + if arg is not detached and arg.is_leaf and arg.grad_dtype != detached.grad_dtype: + detached.grad_dtype = arg.grad_dtype + return detached + + +@invoke_leaf_function.py_impl(DispatchKey.CompositeExplicitAutograd) +def invoke_leaf_function_dense( + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices="", +): + from torch._dynamo import config as dynamo_config + + version_before = [ + arg._version if isinstance(arg, torch.Tensor) else 0 for arg in flat_args + ] + + flat_args = tuple(_detach_with_grad_dtype(arg) for arg in flat_args) + requires_grad_indices_set = _parse_mutated_arg_indices(requires_grad_indices) + flat_args = tuple( + arg.requires_grad_(True) if idx in requires_grad_indices_set else arg + for idx, arg in enumerate(flat_args) + ) + + with unflatten_args_with_modules(flat_args, input_spec) as (args, kwargs): + real_output = real_fn_callable(*args, **kwargs) + + _check_no_input_mutation(flat_args, version_before, mutated_arg_indices) + + if dynamo_config.leaf_function_validate_outputs: + fake_output = fake_fn_callable(*args, **kwargs) + _validate_outputs_match(fake_output, real_output) + + return real_output diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_subgraph.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_subgraph.py new file mode 100644 index 0000000000000000000000000000000000000000..ee3b37d65b3d7cad67df6cc16b9e06ea4a7381d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_subgraph.py @@ -0,0 +1,1457 @@ +# mypy: allow-untyped-defs + +import contextlib +import copy +import functools +import threading +from collections import defaultdict +from collections.abc import Callable +from contextlib import nullcontext +from dataclasses import dataclass, field, replace +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._dispatch.python import suspend_functionalization +from torch._higher_order_ops.utils import ( + _from_fun, + _maybe_reenter_make_fx, + clone_outputs_aliasing_inputs, + FunctionalizeCtxWrapper, + get_dummy_aot_autograd_config, + HopInstance, + prepare_fw_with_masks, + redirect_to_mode, + reenter_make_fx, + register_fake, + save_values_for_backward, + saved_values, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch._ops import HigherOrderOperator +from torch._subclasses.functional_tensor import disable_functional_mode +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.fx.graph_module import GraphModule +from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts +from torch.utils._debug_mode import DebugMode +from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode + + +invoke_subgraph_counter = 0 + + +# During the tracing of the joint graph, we construct this information. This is +# used to filter out grad_outs/tangents in the `backward` method of +# InvokeSubgraphAutogradOp. +@dataclass +class OutputMetadata: + num_fw_outs: int | None = None + indexes_with_symint: set[int] = field(default_factory=set) + indexes_with_no_grad: set[int] = field(default_factory=set) + + +# This config will be stored in invoke_subgraph HOP node.meta["custom"]["nested_region_config"] +# as well as the subgraph's gm.meta["nested_region_config"]. +@dataclass +class NestedCompileRegionOptions: + # A Callable that takes (gm, example_inputs, decompositions=None, **kwargs) as inputs. + # Returns AOTCompiledArtifact + fw_compiler: Callable | None = None + bw_compiler: Callable | None = None + + # Note: [InvokeSubgraphHOP Partitioner] + # If not None, add "partitioner" to HOP node meta. + # If Callable, directly assign the callable, but the callable cannot be pickled + # If str, the options are "default_partition" and "min_cut_rematerialization_partition". + # The HOP joint graph will be partitioned using the corresponding functions in + # torch/_functorch/partitioners.py + partitioner: Callable | str | None = None + + # If it's None, we'll inherit the parent call's decompositions. + # Otherwise, the nested region will use this decompositions. + decompositions: dict[str, Any] | None = None + + # Inductor config patches to apply while compiling this nested region through + # Inductor's normal invoke_subgraph lowering path. Also used for the backward + # unless bw_inductor_config_patches replaces it. + inductor_config_patches: dict[str, Any] | None = None + + # If set, the full inductor config for the backward subgraph, used instead of + # inductor_config_patches (a replacement, not merged with it), mirroring + # aot_autograd's separate fw_compiler/bw_compiler. If None, the backward + # reuses the forward config. + bw_inductor_config_patches: dict[str, Any] | None = None + + +def _extract_nested_region_config(fn): + """ + Extract the NestedCompileRegionOptions from the HOP subgraph gm.meta["nested_region_config"] + """ + gm_to_compile = None + if isinstance(fn, torch.fx.GraphModule): + gm_to_compile = fn + elif isinstance(fn, FunctionalizeCtxWrapper): + gm_to_compile = fn.subgraph + + if ( + isinstance(gm_to_compile, torch.fx.GraphModule) + and hasattr(gm_to_compile, "meta") + and "nested_region_config" in gm_to_compile.meta + ): + if isinstance( + gm_to_compile.meta["nested_region_config"], NestedCompileRegionOptions + ): + return gm_to_compile.meta["nested_region_config"].decompositions + return None + + +def get_backward_nested_region_config( + fw_config: NestedCompileRegionOptions | None, +) -> NestedCompileRegionOptions | None: + """Region config for compiling the backward subgraph. + + When the region sets bw_inductor_config_patches, the backward compiles under + it (a replacement for inductor_config_patches, not merged with it). Otherwise + the forward config is reused unchanged, so the returned object is identical + (callers rely on this identity to detect a distinct backward config). + """ + if ( + isinstance(fw_config, NestedCompileRegionOptions) + and fw_config.bw_inductor_config_patches is not None + ): + return replace( + fw_config, + inductor_config_patches=fw_config.bw_inductor_config_patches, + bw_inductor_config_patches=None, + ) + return fw_config + + +# Per-call id used by downstream graph passes to pair fw and bw +# invoke_subgraph HOP nodes (e.g. run_joint_graph_passes_on_hops). The +# autograd Function pushes the id around its fw and bw dispatches; the +# proxy-mode handler stamps it on the resulting FX nodes via +# meta["custom"]["call_id"]. +_invoke_subgraph_call_state = threading.local() + + +def _next_invoke_subgraph_call_id() -> int: + counter = getattr(_invoke_subgraph_call_state, "counter", 0) + _invoke_subgraph_call_state.counter = counter + 1 + return counter + + +def _current_invoke_subgraph_call_id() -> int | None: + return getattr(_invoke_subgraph_call_state, "current", None) + + +@contextlib.contextmanager +def _set_invoke_subgraph_call_id(call_id: int): + prev = getattr(_invoke_subgraph_call_state, "current", None) + _invoke_subgraph_call_state.current = call_id + try: + yield + finally: + _invoke_subgraph_call_state.current = prev + + +def warn_and_trace_duplicate_backward( + identifier: str | None, + suffix: int, + bw_graph: torch.fx.GraphModule, + num_primals: int, + tangents: tuple[Any, ...], +) -> None: + if suffix == 0: + return + + from torch._dynamo.utils import warn_once + from torch._logging import trace_structured + + placeholders = [node for node in bw_graph.graph.nodes if node.op == "placeholder"] + tangent_summaries: list[dict[str, Any]] = [] + for idx, tangent in enumerate(tangents): + summary: dict[str, Any] = {} + backward_input_idx = num_primals + idx + if backward_input_idx < len(placeholders): + summary["backward_input_name"] = placeholders[backward_input_idx].name + + if not isinstance(tangent, torch.Tensor): + summary["type"] = "non-Tensor" + tangent_summaries.append(summary) + continue + + summary.update( + { + "shape": [ + int(s) if isinstance(s, int) else str(s) for s in tangent.shape + ], + "stride": [ + int(s) if isinstance(s, int) else str(s) for s in tangent.stride() + ], + "dtype": str(tangent.dtype), + "device": str(tangent.device), + } + ) + tangent_summaries.append(summary) + + warn_once( + "invoke_subgraph traced multiple backward graphs for the same forward " + f"identifier {identifier!r}. This usually means the incoming backward " + "tangent metadata differs across backward invocations. This can happen " + "when upstream backward formulas produce gradients with different " + "layouts, aliases, or other tensor metadata. This can increase compile " + "time and code size. Use tlparse and look for the " + "invoke_subgraph_backward_duplicate artifact for tangent details." + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "invoke_subgraph_backward_duplicate", + "encoding": "json", + }, + payload_fn=lambda: { + "forward_identifier": identifier, + "backward_identifier": f"bw_{identifier}_{suffix}", + "new_variant_suffix": suffix, + "num_variants_for_identifier": suffix + 1, + "new_variant": { + "backward_identifier": f"bw_{identifier}_{suffix}", + "tangents": tangent_summaries, + }, + "explanation": ( + "invoke_subgraph caches backward graphs by both the forward " + "identifier and tangent metadata. Multiple backward variants " + "for one forward identifier usually mean the backward tangents " + "have different tensor metadata, commonly stride." + ), + "common_cause": ( + "This can happen when equivalent forward invocations receive backward " + "tangents from different upstream formulas, or from the same " + "formula with different input metadata. For example, an " + "upstream backward may return a view, alias, slice, expanded " + "tensor, or otherwise non-contiguous gradient whose metadata " + "does not match the tangent seen by another use." + ), + "suggested_action": ( + "If the duplicate backward graph is undesirable, materialize a " + "consistent tangent layout before the nested region backward. " + "One model-level workaround is a custom autograd.Function whose " + "forward returns the input and whose backward returns " + "grad.contiguous()." + ), + }, + ) + + +class InvokeSubgraphHOP(HigherOrderOperator): + def __init__(self) -> None: + # Invoke subgraph does not have any state, it is just a wrapper over a + # subgraph, so we can safely cache the HOP. + super().__init__("invoke_subgraph", cacheable=True) + # This is used by the fake tensor cache key validator to extract the + # subgraph and iterate over the nodes to find if all nodes are fake + # tensor cacheable. + self.subgraph_indexes = [ + 0, + ] + + # identifier is setup by upper part of the stack. This helps us in + # identifying two invoke_subgraph calls have same subgraph. + def __call__( + self, + subgraph: GraphModule | FunctionalizeCtxWrapper, + identifier: str | None, + *operands, + ): + if identifier is not None and not isinstance(identifier, str): + raise AssertionError( + f"identifier must be None or a string, got {type(identifier)}" + ) + + if not all( + isinstance( + o, (torch.Tensor, int, torch.SymInt, torch.Generator, FakeScriptObject) + ) + or is_custom_class(type(o)) + for o in operands + if o is not None + ): + raise AssertionError( + f"invoke_subgraph operands must be a list of tensors/ints/SymInts/Generator, got {operands}" + ) + + # pyrefly: ignore [missing-attribute] + return super().__call__(subgraph, identifier, *operands) + + # pyrefly: ignore [bad-override] + def gen_schema(self, subgraph, identifier, *operands): + from torch._higher_order_ops.schema import HopSchemaGenerator + from torch._higher_order_ops.utils import ( + check_input_alias_and_mutation_return_outputs, + materialize_as_graph, + ) + from torch._subclasses.functional_tensor import FunctionalTensor + + subgraph_decomp_table = _extract_nested_region_config(subgraph) + # When the subgraph is a GraphModule whose captured buffers are + # already FunctionalTensors (produced by an enclosing + # FunctionalTensorMode, e.g. the non-strict export path or + # ``run_decompositions`` on an ExportedProgram that preserved an + # ``invoke_subgraph`` HOP), re-tracing through + # ``materialize_as_graph`` would pop that mode via + # ``_disable_current_modes`` and trigger "FunctionalTensor on its + # own" when the inner trace touches the captured constants. In that + # case the existing graph has already been functionalized by the + # outer pass, so reuse it for schema / mutation analysis. + gm: torch.fx.GraphModule | None = None + if isinstance(subgraph, FunctionalizeCtxWrapper): + candidate = subgraph.subgraph + elif isinstance(subgraph, torch.fx.GraphModule): + candidate = subgraph + else: + candidate = None + bufs = ( + list(candidate.buffers()) + if isinstance(candidate, torch.fx.GraphModule) + else [] + ) + if bufs and all(isinstance(buf, FunctionalTensor) for buf in bufs): + gm = candidate + if gm is None: + gm = materialize_as_graph( + subgraph, operands, subgraph_decomp_table=subgraph_decomp_table + ) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("subgraph", gm) + schema_gen.add_arg("identifier", identifier) + ( + _, + _, + _, + mutated_inputs, + outputs, + ) = check_input_alias_and_mutation_return_outputs(gm) + for idx, arg in enumerate(operands): + schema_gen.add_arg(f"arg{idx}", arg, is_mutated=idx in mutated_inputs) + for out in outputs: + schema_gen.add_output(out) + + return schema_gen.gen_schema() + + +invoke_subgraph = InvokeSubgraphHOP() + + +def invoke_subgraph_infer( + subgraph: GraphModule | FunctionalizeCtxWrapper, + *operands, +): + """Inference-only entrypoint for invoke_subgraph that auto-generates identifier. + + This is intended for use cases where we are building an inference graph and + don't need the forward/backward caching that requires a stable identifier. + The identifier is automatically computed based on the current proxy mode's + tracer state. + + If no proxy mode is active, the subgraph is called directly. + """ + from torch.fx.experimental.proxy_tensor import get_proxy_mode + + proxy_mode = get_proxy_mode() + if proxy_mode is None: + # No tracing active, just call the subgraph directly + if getattr(subgraph, "_boxed_call", False): + return subgraph(list(operands)) + else: + return subgraph(*operands) + + from torch._dynamo.utils import get_unique_name_wrt + + # How exactly should we allocate names for the HOP invoke_subgraph we + # are going to put into the graph? This is a bit tricky. In the + # original design of invoke_subgraph, this HOP never shows up in the + # wild: it is only generated Dynamo, so Dynamo can take sure of + # ensuring it picks unique names in the context of the particular + # Dynamo compilation. However, these invoke_subgraph are different: + # they live as Dynamo compiled code that can potentially get traced + # multiple times! If they get retraced several times in the same + # trace, deduplication occurs; but if I make_fx a function f once, + # and then do a separate new trace, there's no relationship between + # these. Additionally, we also want the name we put in the graph to + # be deterministic, and for it to be indifferent to how many + # unrelated invoke_subgraphs/make_fxs we've done, prior to THIS + # particular make_fx. + # + # To satisfy all of these constraints, it's impossible to preallocate + # a name before tracing actually goes through us (since those names + # would have to all be unique even if a subgraph never gets used.) + # So we allocate the subgraph a fresh name PER proxy mode, and then + # consistently reuse it if it hits again. + # + # Note we do NOT do equality comparison subgraph, since it has + # reference equality semantics. + + if subgraph in proxy_mode._invoke_subgraph_cache: + name = proxy_mode._invoke_subgraph_cache[subgraph] + else: + name = get_unique_name_wrt( + "invoke_subgraph", + proxy_mode._invoke_subgraph_names, + requires_suffix=True, + ) + proxy_mode._invoke_subgraph_names.add(name) + proxy_mode._invoke_subgraph_cache[subgraph] = name + + return invoke_subgraph(subgraph, name, *operands) + + +# Registers dispatches for SAC +redirect_to_mode(invoke_subgraph, _CachingTorchDispatchMode) +redirect_to_mode(invoke_subgraph, _CachedTorchDispatchMode) + + +def invoke_subgraph_placeholder(func, *args, **kwargs): + if torch.compiler.is_dynamo_compiling(): + # This is just a placeholder for Dynamo to replace with invoke_subgraph + raise RuntimeError("invoke_subgraph should not be called directly in Dynamo") + + if torch.compiler.is_exporting(): + # For non-strict export tracing, we still want to go through Dynamo + + def _invoke_subgraph_placeholder_wrapper(func, args, kwargs): + return invoke_subgraph_placeholder(func, *args, **kwargs) + + from torch._higher_order_ops.utils import _hop_compile_and_call + + return _hop_compile_and_call( + _invoke_subgraph_placeholder_wrapper, (func, args, kwargs) + ) + + return func(*args, **kwargs) + + +def mark_compile_region( + fn=None, + options: NestedCompileRegionOptions | None = None, + max_reuse_entries: int = 8, + reuse_hash_fn=None, +): + """ + This wrapper instructs torch.compile to compile the wrapped region once and + reuse the compiled artifact, instead of the usual way of aggressively + inlining the function. + + Under the hood, it tells TorchDynamo to use InvokeSubgraph HOP for the + region. For PyTorch eager, this is a no-op. + + Args: + fn: The function to wrap + options: Optional config to use for compiling the subgraph. + Warning: this is an experimental feature under development and + not ready for use yet. + max_reuse_entries: Maximum number of reuse cache entries per function + before raising an error. If this limit is hit, guards keep failing + across invocations and hierarchical compilation is not effective. + """ + + def wrap(func): + def inner(*args, **kwargs): + # Get the innermost function to avoid nested compile regions + inner_func = func + while hasattr(inner_func, "__marked_compile_region_fn__"): + inner_func = inner_func.__marked_compile_region_fn__ + return invoke_subgraph_placeholder(inner_func, *args, **kwargs) + + inner.__marked_compile_region_fn__ = func # type: ignore[attr-defined] + func.__marked_compile_region_config__ = options # type: ignore[attr-defined] + func.__marked_compile_region_max_reuse_entries__ = max_reuse_entries # type: ignore[attr-defined] + func.__marked_compile_region_reuse_hash_fn__ = reuse_hash_fn # type: ignore[attr-defined] + + return inner + + if fn: + return wrap(fn) + else: + return wrap + + +def get_invoke_subgraph_cache(): + cache = None + if tracing_ctx := torch._guards.TracingContext.try_get(): + cache = tracing_ctx.hop_dispatch_set_cache.get_cache(invoke_subgraph) + return cache + + +# TODO (@anijain2305) - Delete this function when base_hop uses invoke_subgraph infra +def trace_joint_graph(fn, fw_inputs, fw_outputs): + """ + Naively trace out a joint graph. This simplifies the reconstruction of joint + graph in the min-cut partitioner later on. + """ + from torch._functorch.aot_autograd import create_joint + + dummy_aot_config = get_dummy_aot_autograd_config() + + # This joint_fn is inserted as the backward graph as is. This simplifies the + # min-cut partitioner work later on. + # Input signature - (*primals, *tangents) + # Output signature - (*grads, *fw_outs) + # The output signature is deliberately kept grads first and fw_outs second. + # Having grads first makes the min-cut partitioner HOP graph stitching + # easier. + def joint_fn(*primals_and_tangents): + primals = primals_and_tangents[: len(fw_inputs)] + tangents = primals_and_tangents[len(fw_inputs) :] + + fw_outs, grads = create_joint( + prepare_fw_with_masks(fn), aot_config=dummy_aot_config + )(primals, tangents) + + maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents) + + # return signature is deliberately kept (*grads, *fw_outs). This + # simplifies partitioning work later on. + return pytree.tree_map(maybe_clone, tuple(grads + list(fw_outs))) + + primals = list(fw_inputs) + # This assumes that the tangent strides match fw_outputs strides. Check the + # InvokeSubgraphAutogradOp backward op for the contiguous call. + tangents = [_from_fun(out) for out in fw_outputs] + + joint_operands = primals + tangents + + return _maybe_reenter_make_fx(joint_fn)(*joint_operands) + + +# TODO (@anijain2305) - Delete this function when base_hop uses invoke_subgraph infra +def create_fw_bw_graph(subgraph, operands, grad_outputs=None): + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + # args are functional tensors, generate some example tensors + fw_inputs = pytree.tree_map(_from_fun, operands) + + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(fw_inputs) + context = ( + nullcontext() + if fake_mode is None or fake_mode.shape_env is None + else fake_mode.shape_env.ignore_fresh_unbacked_symbols() + ) + + with context: + fw_outs = pytree.tree_map(_from_fun, subgraph(*fw_inputs)) + + num_fw_outs = len(fw_outs) + + # Collect the indexes of none in the output to check that the grad + # is None at the corresponding index in the backward. This check is + # performed in the autograd.Function - InvokeSubgraphAutogradOp. + # Also collect the indexes of no_grad in the output to filter out + # the grad_outs in the `backward` method. + output_metadata = OutputMetadata() + + output_metadata.num_fw_outs = num_fw_outs + for idx, fw_out in enumerate(fw_outs): + if isinstance(fw_out, torch.SymInt): + output_metadata.indexes_with_symint.add(idx) + elif not fw_out.requires_grad: + output_metadata.indexes_with_no_grad.add(idx) + + if grad_outputs is None: + # Infer grad_outputs to be the same properties as the fw_outputs + # if they're not passed in + # Although fw_outs are equivalent to grad_outputs for tracing + # purposes, we have to carefully handle the None and fw_out that do + # not have require_grad. At those indexes, we will have None in the + # backward graph. + grad_outputs = fw_outs + grad_outputs = [grad for grad in grad_outputs if grad is not None] + grad_outputs = [grad for grad in grad_outputs if grad.requires_grad] + + # Force grad_out to be contiguous. This is because at runtime, + # grad_out could have different strides than fw_outs. So, we + # force the grad_outs to be contiguous for both tracing and + # runtime. + grad_outputs = [grad.contiguous() for grad in grad_outputs] + + if any( + not isinstance(out, torch.Tensor) + for out in grad_outputs + if out is not None + ): + raise RuntimeError( + "Expect outputs of invoke_subgraph to only contains tensors or None. " + f"Got types {[type(out) for out in grad_outputs]}." + ) + + # Trace the forward subgraph + fw_graph = _maybe_reenter_make_fx(subgraph)(*fw_inputs) + + # Trace the joint graph and assign it to the bwd graph + bw_graph = trace_joint_graph( + subgraph, + fw_inputs, + grad_outputs, + ) + return fw_graph, bw_graph, output_metadata + + +def get_output_metadata(subgraph, *operands): + """ + Extract metadata about the subgraph outputs WITHOUT executing the subgraph. + This avoids running side-effectful operations twice (once here, once in forward). + We analyze the graph structure statically to extract metadata. + """ + # Unwrap FunctionalizeCtxWrapper if present + if isinstance(subgraph, FunctionalizeCtxWrapper): + subgraph = subgraph.subgraph + + # If not a GraphModule, fall back to execution-based metadata extraction + if not isinstance(subgraph, torch.fx.GraphModule): + return _get_output_metadata_by_execution(subgraph, *operands) + + output_metadata = OutputMetadata() + + # Extract output arguments from the output node + # The output node has args=(output_values,) where output_values is a tuple/list + output_node = next(reversed(subgraph.graph.find_nodes(op="output"))) + output_metadata.num_fw_outs = len(output_node.args[0]) + + for idx, output_arg in enumerate(output_node.args[0]): + if not isinstance(output_arg, torch.fx.Node): + if isinstance(output_arg, int): + output_metadata.indexes_with_symint.add(idx) + output_metadata.indexes_with_no_grad.add(idx) + continue + + # Check node metadata for type information + if output_arg.meta.get("val") is None: + # If we don't have complete metadata for all outputs, fall back to execution + # This is important for correctness (e.g., detecting SymInts) even though it + # runs side-effectful operations + return _get_output_metadata_by_execution(subgraph, *operands) + + val = output_arg.meta["val"] + if isinstance(val, torch.SymInt): + output_metadata.indexes_with_symint.add(idx) + output_metadata.indexes_with_no_grad.add(idx) + elif isinstance(val, torch.Tensor): + # Check if tensor requires grad from metadata + if hasattr(val, "requires_grad") and not val.requires_grad: + output_metadata.indexes_with_no_grad.add(idx) + else: + # Non-tensor, non-symint (shouldn't happen but be safe) + output_metadata.indexes_with_no_grad.add(idx) + + return output_metadata + + +def _get_output_metadata_by_execution(subgraph, *operands): + """ + Fallback: Extract metadata by executing the subgraph. + This should only be used when static analysis fails. + WARNING: This will run side-effectful operations! + """ + + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + # args are functional tensors, generate some example tensors + fw_inputs = pytree.tree_map(_from_fun, operands) + + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(fw_inputs) + context = ( + nullcontext() + if fake_mode is None or fake_mode.shape_env is None + else fake_mode.shape_env.ignore_fresh_unbacked_symbols() + ) + + with context: + fw_outs = pytree.tree_map(_from_fun, subgraph(*fw_inputs)) + + num_fw_outs = len(fw_outs) + + output_metadata = OutputMetadata() + output_metadata.num_fw_outs = num_fw_outs + + for idx, fw_out in enumerate(fw_outs): + if isinstance(fw_out, torch.SymInt): + output_metadata.indexes_with_symint.add(idx) + elif not fw_out.requires_grad: + output_metadata.indexes_with_no_grad.add(idx) + + return output_metadata + + +def trace_joint_graph_as_bwd( + subgraph, num_primals, joint_operands, include_key_set, exclude_key_set +): + """ + Naively trace out a joint graph. This simplifies the reconstruction of joint + graph in the min-cut partitioner later on. + """ + from torch._functorch.aot_autograd import create_joint + + dummy_aot_config = get_dummy_aot_autograd_config() + + if isinstance(subgraph, torch.fx.GraphModule): + + def graph_with_interpreter(*args): + # Running graph with interpreter is needed for propagating the stack_trace + with torch.fx.traceback.preserve_node_meta(): + return torch.fx.Interpreter(subgraph).run(*args) + + fn = graph_with_interpreter + else: + fn = subgraph + + # This joint_fn is inserted as the backward graph as is. This simplifies the + # min-cut partitioner work later on. + # Input signature - (*primals, *tangents) + # Output signature - (*grads, *fw_outs) + # The output signature is deliberately kept grads first and fw_outs second. + # Having grads first makes the min-cut partitioner HOP graph stitching + # easier. + def joint_fn(*primals_and_tangents): + primals = primals_and_tangents[:num_primals] + tangents = primals_and_tangents[num_primals:] + + fw_outs, grads = create_joint( + prepare_fw_with_masks(fn), aot_config=dummy_aot_config + )(primals, tangents) + + maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents) + + # return signature is deliberately kept (*grads, *fw_outs). This + # simplifies partitioning work later on. + return pytree.tree_map(maybe_clone, tuple(grads + list(fw_outs))) + + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + joint_operands = [_from_fun(arg) for arg in joint_operands] + with contextlib.ExitStack() as stack: + stack.enter_context( + torch._C._ForceDispatchKeyGuard(include_key_set, exclude_key_set), + ) + subgraph_decomp_table = _extract_nested_region_config(subgraph) + with torch.enable_grad(): + return _maybe_reenter_make_fx( + joint_fn, subgraph_decomp_table=subgraph_decomp_table + )(*joint_operands) + + +def get_non_differentiable_indices(subgraph) -> list[int]: + """Inspect a subgraph's output node metadata to find outputs that + were non-differentiable (requires_grad=False) during Dynamo tracing. + + This uses the example_value stored on each output node, which reflects + the correct requires_grad from the original tracing (where inner + autograd.Functions DID run and mark_non_differentiable was called). + + InvokeSubgraphAutogradOp runs the subgraph under + _AutoDispatchBelowAutograd, which suppresses the autograd key. Inner + autograd.Functions (e.g. FlexAttentionAutogradOp) therefore never call + mark_non_differentiable. The outer autograd engine then sets + requires_grad=True on ALL outputs because the inputs require grad. + We use the Dynamo-traced example_value to restore the correct + non-differentiable status at the outer level. + """ + if not isinstance(subgraph, torch.fx.GraphModule): + return [] + + output_nodes = [n for n in subgraph.graph.nodes if n.op == "output"] + if not output_nodes: + return [] + + output_args = output_nodes[0].args[0] + if not isinstance(output_args, (tuple, list)): + output_args = [output_args] + + non_differentiable: list[int] = [] + for out_idx, arg in enumerate(output_args): + if not isinstance(arg, torch.fx.Node): + continue + example = arg.meta.get("example_value") + if isinstance(example, torch.Tensor) and not example.requires_grad: + non_differentiable.append(out_idx) + + return non_differentiable + + +class InvokeSubgraphAutogradOp(torch.autograd.Function): + """ + Saves the subgraph, i.e. original callable, in the forward method. And then + traces out a joint graph in the backward. This delaying of tracing in + backward, also called as lazy backward, ensures that the assumptions about + the grad_out strides and tensor-subclass-ness are already accounted for. + """ + + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + subgraph, + identifier, + output_metadata, + *operands, + ): + # We want to delay the backward graph construction until the backward. + # So in forward, we just run the fw callable as is. And save all the + # information necessary to construct the backward graph in the ctx. + ctx._subgraph = subgraph + ctx._identifier = identifier + ctx._output_metadata = output_metadata + ctx._call_id = _next_invoke_subgraph_call_id() + # We snapshot the dispatch keys in forward for materializing + # the bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + + save_values_for_backward(ctx, operands) + + with ( + torch._C._AutoDispatchBelowAutograd(), + _set_invoke_subgraph_call_id(ctx._call_id), + ): + out = invoke_subgraph( + subgraph, + f"fw_{identifier}", + *operands, + ) + + # Check that int (coming from symint) is at expected indexes. + for idx, o in enumerate(out): + if isinstance(o, int): + if idx not in output_metadata.indexes_with_symint: + raise AssertionError( + f"unexpected int output at index {idx}, not in indexes_with_symint" + ) + + # Propagate non-differentiable status from the inner subgraph. + # See get_non_differentiable_indices for details on why this is needed. + non_differentiable_indices = get_non_differentiable_indices(subgraph) + if non_differentiable_indices: + non_differentiable = [ + out[i] + for i in non_differentiable_indices + if isinstance(out[i], torch.Tensor) + ] + if non_differentiable: + ctx.mark_non_differentiable(*non_differentiable) + ctx._non_differentiable_indices = non_differentiable_indices + + return out + + @staticmethod + def backward( + ctx, + *grad_outs, + ): + from torch._dynamo.utils import dynamo_timed + + subgraph = ctx._subgraph + identifier = ctx._identifier + output_metadata = ctx._output_metadata + primals = saved_values(ctx) + + # Filter out grads that are None or do not require_grad. This was + # the assumption we made during the tracing of joint_graph. + non_differentiable_indices = ctx._non_differentiable_indices + filtered_grad_outs = [] + for idx, o in enumerate(grad_outs): + if o is None: + if ( + idx not in output_metadata.indexes_with_symint + and idx not in non_differentiable_indices + ): + raise AssertionError( + f"unexpected None grad_out at index {idx}, not in indexes_with_symint" + ) + elif ( + idx in output_metadata.indexes_with_no_grad + or idx in non_differentiable_indices + ): + # Deliberately skip over the grad_outs which we know should be + # None because the corresponding fwd_out does not require_grad. + pass + else: + filtered_grad_outs.append(o) + filtered_grad_outs = tuple(filtered_grad_outs) + + # Important note - Even though the forward graph can be same for + # different invoke_subgraphs, the backward graph can be different + # because the tangent strides can be different. So, here we cache on + # tangent_metadata in addition to identifier + from torch._guards import detect_fake_mode + from torch._subclasses._fake_tensor_utils import _CacheKeyState + from torch._subclasses.fake_tensor import extract_tensor_metadata + + fake_mode = detect_fake_mode(primals + filtered_grad_outs) + if fake_mode is None: + raise AssertionError("fake_mode should be enabled for HOPs") + state = _CacheKeyState(fake_mode.shape_env) + + tangent_metadata: list[object] = [] + for tangent in filtered_grad_outs: + metadata = extract_tensor_metadata(tangent) + metadata._flatten_into(tangent_metadata, fake_mode, state) + + # Add aliasing information to tangent_metadata + # Two tangents are aliased if they are the same tensor object (using id()) + # We create a tuple of tuples where each inner tuple contains indices of aliased tensors + # e.g. ((0, 1),) would mean there is one aliasing group, and the first and second tangents are aliased + # e.g. () would mean there is no aliasing between tangents + tensor_to_indices: dict[int, list[int]] = defaultdict(list) + for i, tangent in enumerate(filtered_grad_outs): + if isinstance(tangent, torch.Tensor): + tensor_to_indices[id(tangent)].append(i) + + aliasing_groups = tuple( + sorted( + tuple(indices) + for indices in tensor_to_indices.values() + if len(indices) > 1 + ) + ) + tangent_metadata.append(aliasing_groups) + + # pyrefly: ignore [bad-assignment] + tangent_metadata = tuple(tangent_metadata) + + # bw_graph is a joint graph with signature (*primals_and_tangents) and + # returns (*grads_and_fw_outs). To get the grads, we use the num_fw_outs + # to extract the grads. + primals_and_tangents = primals + filtered_grad_outs + + # Check if we have already traced the bwd subgraph. + bw_graph = None + suffix = None + invoke_subgraph_cache = get_invoke_subgraph_cache() + cache_hit = False + if invoke_subgraph_cache: + bw_graph, suffix = invoke_subgraph_cache.get_lazy_bwd_entry( + identifier, tangent_metadata + ) + cache_hit = bw_graph is not None + + if bw_graph is None: + if suffix is not None: + raise AssertionError( + f"suffix should be None when bw_graph is None, got {suffix}" + ) + with dynamo_timed( + "invoke_subgraph_trace_joint_graph", log_pt2_compile_event=True + ): + bw_graph = trace_joint_graph_as_bwd( + subgraph, + len(primals), + primals_and_tangents, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + ) + if ( + hasattr(subgraph, "meta") + and "nested_region_config" in subgraph.meta + ): + bw_graph.meta["nested_region_config"] = subgraph.meta[ + "nested_region_config" + ] + + if invoke_subgraph_cache and not cache_hit: + suffix = invoke_subgraph_cache.add_lazy_bwd_entry( + identifier, tangent_metadata, bw_graph + ) + warn_and_trace_duplicate_backward( + identifier, suffix, bw_graph, len(primals), filtered_grad_outs + ) + + with _set_invoke_subgraph_call_id(ctx._call_id): + grads = invoke_subgraph( + bw_graph, f"bw_{identifier}_{suffix}", *primals_and_tangents + )[: -output_metadata.num_fw_outs] + return None, None, None, *grads + + +@invoke_subgraph.py_autograd_impl +def _(subgraph, identifier, *operands): + from torch._guards import detect_fake_mode + + # Eager backends run the captured HOP with real tensors and no AOTAutograd + # fake mode. Let regular autograd record through the subgraph in that case. + if detect_fake_mode(operands) is None: + if getattr(subgraph, "_boxed_call", False): + return subgraph(list(operands)) + return subgraph(*operands) + + # Check if we have already traced the subgraph. + invoke_subgraph_cache = get_invoke_subgraph_cache() + if invoke_subgraph_cache: + if saved_autograd_fn := invoke_subgraph_cache.get_autograd_key_entry( + identifier + ): + return saved_autograd_fn(*operands) + + output_metadata = get_output_metadata(subgraph, *operands) + + def autograd_fn_callable(*args): + return InvokeSubgraphAutogradOp.apply( + subgraph, identifier, output_metadata, *args + ) + + # Save the autograd_fn_callable in the dispatch set cache. + if invoke_subgraph_cache: + invoke_subgraph_cache.add_autograd_key_entry(identifier, autograd_fn_callable) + + return autograd_fn_callable(*operands) + + +@invoke_subgraph.py_impl(DebugMode) +def _(debug_mode, subgraph, identifier, *operands): + # record HOP call + call = torch.utils._debug_mode._OpCall( + invoke_subgraph, + (identifier, *operands), + kwargs={}, + call_depth=debug_mode.call_depth + 1, + stack=debug_mode.record_stack_trace, + ) + debug_mode._record_call(call) + + debug_mode.call_depth += 1 + debug_mode._handle_annotate(f"[enter InvokeSubgraph HOP] {identifier}") + + # If the HOP is dispatched from DebugMode, we should enable debug_mode + # for the subgraph call. + with debug_mode: + if getattr(subgraph, "_boxed_call", False): + result = subgraph(list(operands)) + else: + result = subgraph(*operands) + debug_mode._handle_annotate(f"[exit InvokeSubgraph HOP] {identifier}") + debug_mode.call_depth -= 1 + # record output of HOP + debug_mode._record_call_output(call, result) + return result + + +@invoke_subgraph.py_impl(DispatchKey.CompositeExplicitAutograd) +def _(subgraph, identifier, *operands): + from torch.utils._python_dispatch import _get_current_dispatch_mode + + mode = _get_current_dispatch_mode() + + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + + if getattr(subgraph, "_boxed_call", False): + return subgraph(list(operands)) + else: + return subgraph(*operands) + + +@invoke_subgraph.py_functionalize_impl +def _(ctx, subgraph, identifier, *operands): + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, + ) + + # (in the functionalization metadata phase) Capture tokens before + tokens_before = dict(ctx.mode._tokens) + + # Check if this subgraph has effects stored in the cache + invoke_subgraph_cache = get_invoke_subgraph_cache() + effects = None + if invoke_subgraph_cache: + effects = invoke_subgraph_cache.get_effects(identifier) + + if effects: + if len(effects) != 1: + raise AssertionError( + f"Multiple effects within a subgraph NYI, got {len(effects)} effects" + ) + tokens = ctx.mode._tokens + effects = next(iter(effects)) + token_input = tokens[effects] + + operands = (token_input, *operands) + + def wrap_subgraph(subgraph): + def wrapped_subgraph(token, *args): + res = subgraph(*args) + return ctx.unwrap_tensors(ctx.mode._tokens[effects]), *res + + return wrapped_subgraph + + subgraph = wrap_subgraph(subgraph) + + unwrapped_operands = ctx.unwrap_tensors(operands) + + functionalize_schema = None + schema_cache_key = None + if invoke_subgraph_cache: + schema_cache_key = ( + id(subgraph), + identifier, + tuple(type(operand) for operand in operands), + ) + functionalize_schema = invoke_subgraph_cache.get_functionalize_schema_entry( + schema_cache_key + ) + + if functionalize_schema is None: + hop_instance = HopInstance.create( + invoke_subgraph, subgraph, identifier, *operands + ) + if invoke_subgraph_cache and schema_cache_key is not None: + invoke_subgraph_cache.add_functionalize_schema_entry( + schema_cache_key, hop_instance._schema + ) + else: + hop_instance = HopInstance(invoke_subgraph, functionalize_schema) + + functionalized_identifier = None + if can_auto_functionalize(hop_instance): + # NOTE: [auto_functionalize x invoke_subgraph caching] + # invoke_subgraph is special because of its identifier based caching mechanism. + # In invoke_subgraph's functionalization key implementation, we create a new + # identifier because the subgraph is replaced by FunctionWithNoFreeVars in a + # functional + epilogue form. + if not isinstance(identifier, str): + raise AssertionError( + f"identifier must be a string for auto_functionalize, got {type(identifier)}" + ) + + if ctx.mode._keep_input_mutations: + # With keep_input_mutations=True, wrap invoke_subgraph in + # auto_functionalized_v2. This allows copy_ epilogues in the subgraph for + # Inductor to fuse where useful. + # See NOTE [Support input mutation of hops] for the overall design. + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + (subgraph, "auto_functionalized_" + identifier, *operands), + {}, + ) + + # With keep_input_mutations=False, the subgraph must not mutate its inputs. + # Return updated inputs so AOTAutograd can generate the copy_ epilogue. + mutated_operand_indices = tuple( + idx + for idx, arg in enumerate(hop_instance._schema.arguments[2:]) + if arg.alias_info is not None and arg.alias_info.is_write + ) + functionalized_subgraph = FunctionalizeCtxWrapper( + ctx, subgraph, mutated_input_indices=mutated_operand_indices + ) + functionalized_identifier = "functionalized_" + identifier + with ctx.redispatch_to_next(): + out = invoke_subgraph( + functionalized_subgraph, + functionalized_identifier, + *unwrapped_operands, + ) + + num_outputs = len(hop_instance._schema.returns) + actual_out = out[:num_outputs] + mutated_out = out[num_outputs:] + for operand_idx, updated_operand in zip(mutated_operand_indices, mutated_out): + operand = operands[operand_idx] + ctx.replace(operand, updated_operand) + ctx.commit_update(operand) + ctx.sync(operand) + out = actual_out + else: + with ctx.redispatch_to_next(): + # NB: There is an assumption that subgraph does not mutate inputs and + # there is no aliasing. It's Dynamo's responsibility to prevent formation + # of invoke_subgraph ops if input aliasing/mutation is detected. + functionalized_subgraph = FunctionalizeCtxWrapper(ctx, subgraph) + out = invoke_subgraph( + functionalized_subgraph, identifier, *unwrapped_operands + ) + + if effects: + (new_token, *out) = out + ctx.mode._tokens[effects] = new_token + + # (in the functionalization metadata phase) Capture tokens after and see if + # there are any differences (there are new effects or the token value for an + # effect type has changed) + tokens_after = dict(ctx.mode._tokens) + discovered_effects = set() + for effect_type, token in tokens_after.items(): + if effect_type not in tokens_before or tokens_before[effect_type] is not token: + discovered_effects.add(effect_type) + + if discovered_effects: + if not ctx.mode._allow_token_discovery: + raise AssertionError( + f"Number of tokens changed by {len(discovered_effects)} when tracing subgraph {subgraph}." + ) + # Later passes look up effects using the identifier on the emitted HOP. + if invoke_subgraph_cache: + invoke_subgraph_cache.add_effects(identifier, discovered_effects) + if functionalized_identifier is not None: + invoke_subgraph_cache.add_effects( + functionalized_identifier, discovered_effects + ) + + return ctx.wrap_tensors(out) + + +# Register the hop fake fn. This will be called in the fake_tensor _dispatch_impl. +@register_fake(invoke_subgraph) +def _(subgraph, identifier, *operands): + from torch._dynamo.utils import dynamo_timed + + with dynamo_timed("invoke_subgraph_fake_tensor", log_pt2_compile_event=True): + if getattr(subgraph, "_boxed_call", False): + return subgraph(list(operands)) + return subgraph(*operands) + + +@invoke_subgraph.py_impl(ProxyTorchDispatchMode) +def _(proxy_mode: ProxyTorchDispatchMode, subgraph, identifier, *operands): + # Check if we have already traced the subgraph. + graph = None + invoke_subgraph_cache = get_invoke_subgraph_cache() + if invoke_subgraph_cache: + graph = invoke_subgraph_cache.get_proxy_dispatch_entry(identifier) + + if graph is None: + from torch._dynamo.utils import dynamo_timed + + with dynamo_timed("invoke_subgraph_proxy_tensor", log_pt2_compile_event=True): + subgraph_decomp_table = _extract_nested_region_config(subgraph) + + # NB: invoke_subgraph subgraph re-trace seq_nr + # The joint graph seq_nr will get wrong in the subsequent re-trace (all nodes will have the same seq_nr), + # so we preserve the original graph's seq_nr here. + with torch.fx.traceback._preserve_node_seq_nr(): + graph = reenter_make_fx( + subgraph, subgraph_decomp_table=subgraph_decomp_table + )(*operands) + + # Propagate nested_region_config from the original subgraph to the + # re-traced graph so it's available for regional compilation. + if ( + isinstance(subgraph, torch.fx.GraphModule) + and hasattr(subgraph, "meta") + and "nested_region_config" in subgraph.meta + and "nested_region_config" not in graph.meta + ): + graph.meta["nested_region_config"] = subgraph.meta["nested_region_config"] + + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(operands) + # Only insert deferred runtime asserts when we have dynamic shapes. + # When shape_env is None (static shapes), there are no deferred asserts to insert. + if fake_mode is not None and fake_mode.shape_env is not None: + insert_deferred_runtime_asserts( + graph, + fake_mode.shape_env, + "invoke_subgraph_proxy_torch_dispatch_mode", + export=True, + ) + graph.recompile() + + if not isinstance(proxy_mode.tracer, torch.fx.Tracer): + raise AssertionError( + f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}" + ) + if invoke_subgraph_cache: + invoke_subgraph_cache.add_proxy_dispatch_entry(identifier, graph) + + node_args = (graph, identifier, *operands) + + def _unwrap_proxy(arg): + if isinstance(arg, torch.fx.GraphModule): + # NOTE: [invoke_subgraph proxy_mode x auto_functionalize] + # Previously, we assumed that `invoke_subgraph` would always be traced with the same tracer. + # This allowed us to cache modules by their identifiers, assuming they were already registered. + # + # However, this assumption no longer holds when we auto-functionalize `invoke_subgraph`. + # auto_functionalize functionalizes the subgraph and wrap it with `FunctionWithNoFreeVars`. + # In the proxy mode implementation of `auto_functionalized_v2`, we need to materialize `FunctionWithNoFreeVars` + # input as a graph module. To do this, we re-trace the `invoke_subgraph` hop, which starts a new sub-tracer + # (see NOTE [materialize callable inputs as graph]). # When the new sub-tracer traces the `invoke_subgraph` + # with a previously cached identifier, the corresponding graph module might not + # exist as a submodule in the new tracer's root. Therefore, we register it as a submodule below. + # + # The alternative is to give a new identifier when we re-trace the invoke_subgraph but this will increase + # the compilation time, which defeats the purpose of caching. + registered_before = False + for ( + _, + submod, + ) in proxy_mode.tracer.root.named_modules(): # type: ignore[union-attr] + if arg is submod: + registered_before = True + + if not registered_before: + qualname = proxy_mode.tracer.get_fresh_qualname("repeated_subgraph") # type: ignore[union-attr] + proxy_mode.tracer.root.register_module(qualname, arg) # type: ignore[union-attr] + return proxy_mode.tracer.unwrap_proxy(arg) # type: ignore[union-attr] + + proxy_args = pytree.tree_map(_unwrap_proxy, node_args) # type: ignore[union-attr] + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", invoke_subgraph, proxy_args, {} + ) + + # Propagate nested_region_config to the node metadata so the regional + # inductor compiler can compile backward invoke_subgraph nodes. + # Dynamo sets this for forward nodes during tracing. For backward + # nodes created during joint tracing, the config lives on the subgraph + # module (set by InvokeSubgraphAutogradOp.backward) but may be wrapped + # by FunctionalizeCtxWrapper — unwrap to find it. + nested_config = None + orig_subgraph = ( + subgraph.subgraph if isinstance(subgraph, FunctionalizeCtxWrapper) else subgraph + ) + for gm in (graph, orig_subgraph): + if ( + isinstance(gm, torch.fx.GraphModule) + and hasattr(gm, "meta") + and "nested_region_config" in gm.meta + ): + nested_config = gm.meta["nested_region_config"] + break + + call_id = _current_invoke_subgraph_call_id() + + if nested_config is not None or call_id is not None: + node = out_proxy.node + if "custom" not in node.meta: + node.meta["custom"] = {} + if nested_config is not None: + node.meta["custom"]["nested_region_config"] = nested_config + if call_id is not None: + node.meta["custom"]["call_id"] = call_id + + example_out = invoke_subgraph(graph, identifier, *operands) + return track_tensor_tree( + example_out, out_proxy, constant=None, tracer=proxy_mode.tracer + ) + + +def invoke_subgraph_inductor_compile( + gm, example_inputs, inductor_config_patches=None, **kwargs +): + from torch._functorch._aot_autograd.runtime_wrappers import ( + SerializableCompiledFunction, + ) + from torch._functorch._aot_autograd.utils import simple_wraps + from torch._inductor import config + from torch._inductor.compile_fx import compile_fx_inner + from torch._inductor.standalone_compile import AOTCompiledArtifact + + # Used for testing only, should only be changed via _testing_capture_invoke_subgraph_inductor_compile_gms() + if ( + torch._dynamo.testing._testing_invoke_subgraph_inductor_compile_captured_gms + is not None + ): + torch._dynamo.testing._testing_invoke_subgraph_inductor_compile_captured_gms.append( + copy.deepcopy(gm) + ) + + if inductor_config_patches is None: + inductor_config_patches = {} + + # Saved tensors flow across the HOP boundary into a separately-compiled bw + # subgraph whose IR was traced with natural (unpadded) strides. Mark every + # output of this subgraph as user-visible so Inductor's comprehensive_padding + # leaves their strides alone — otherwise the bw's assert_size_stride on the + # incoming saved tensor will fire (e.g. F.linear output padded 200008 -> 200064). + from torch._inductor.compile_fx import _recursive_record_user_visible_output_idxs + + output_node = next(iter(gm.graph.find_nodes(op="output"))) + output_node.meta["user_visible_output_idxs"] = [ + idx + for idx in range(len(output_node.args[0])) + if isinstance(output_node.args[0][idx], torch.fx.Node) + ] + _recursive_record_user_visible_output_idxs(gm) + + compile_fn = config.patch(inductor_config_patches)(compile_fx_inner) + compiled_fn_inner = compile_fn(gm, example_inputs) + if not compiled_fn_inner._boxed_call: + raise AssertionError( + "compiled_fn_inner must have _boxed_call attribute set to True" + ) + + # Follow boxed calling convention + @simple_wraps(compiled_fn_inner) + def forward(*runtime_args: tuple[Any]): + full_args = [] + full_args.extend(runtime_args) + return compiled_fn_inner(full_args) + + # Just for convenience + forward.zero_grad = gm.zero_grad # type: ignore[attr-defined] + forward.named_parameters = gm.named_parameters # type: ignore[attr-defined] + forward.named_buffers = gm.named_buffers # type: ignore[attr-defined] + + # TODO: Do we need the post compile passes in _aot_stage2b_compile_forward_or_inference? + # TODO: add a real serialize function for SerializableCompiledFunction like _cache_inference_info + forward.serialize = SerializableCompiledFunction(forward, lambda: None) # type: ignore[attr-defined] + return AOTCompiledArtifact(forward) + + +def get_invoke_subgraph_compile_options( + fw_inductor_config_patches=None, + decompositions=None, + partitioner="min_cut_rematerialization_partition", + *, + bw_inductor_config_patches=None, +): + if fw_inductor_config_patches is None: + fw_inductor_config_patches = {"triton.autotune_at_compile_time": True} + + # The backward uses bw_inductor_config_patches when set (independently of the + # forward), otherwise it reuses the forward config. + bw_patches = ( + bw_inductor_config_patches + if bw_inductor_config_patches is not None + else fw_inductor_config_patches + ) + + from torch._inductor import config as inductor_config + + # Validate that all config keys exist + for patches in (fw_inductor_config_patches, bw_inductor_config_patches): + for key in patches or {}: + if not hasattr(inductor_config, key): + raise ValueError( + f"Invalid inductor config key '{key}' in get_invoke_subgraph_compile_options. " + f"Available config keys can be found in torch._inductor.config" + ) + + fw_compiler = functools.partial( + invoke_subgraph_inductor_compile, + inductor_config_patches=fw_inductor_config_patches, + ) + bw_compiler = functools.partial( + invoke_subgraph_inductor_compile, + inductor_config_patches=bw_patches, + ) + + return NestedCompileRegionOptions( + fw_compiler=fw_compiler, + bw_compiler=bw_compiler, + partitioner=partitioner, + decompositions=decompositions, + inductor_config_patches=fw_inductor_config_patches, + bw_inductor_config_patches=bw_inductor_config_patches, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/local_map.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/local_map.py new file mode 100644 index 0000000000000000000000000000000000000000..88d6cb542d0206d4eb4fa41a82575f83cc649230 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/local_map.py @@ -0,0 +1,664 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +# NOTE: this file may be removed once we move to a dynamo frontend + +import contextlib +from collections.abc import Callable, Generator, Sequence +from contextlib import contextmanager +from typing import Any, TypeAlias + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + clone_outputs_aliasing_inputs, + redirect_to_mode, + register_fake, + save_values_for_backward, + saved_values, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensor, is_fake_tensor +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx import GraphModule +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode + + +# Proxy the HOP instead of inlining into it +# And trace it with local shapes for AP +_DEFER_INLINING = False + +GraphArg: TypeAlias = tuple[torch.Tensor, int, torch.SymInt, None] + + +@contextmanager +def defer_inlining() -> Generator[None, None, None]: + global _DEFER_INLINING + prior = _DEFER_INLINING + try: + _DEFER_INLINING = True + yield + finally: + _DEFER_INLINING = prior + + +# Used to unwrap tensors classes like FunctionalTensor and Parameter +def _new_tensor( + t: Any, + new_shape: Sequence[int] | None = None, + new_stride: Sequence[int] | None = None, +) -> Any: + if isinstance(t, torch.Tensor): + if type(t) not in (FunctionalTensor, FakeTensor, torch.Tensor): + raise AssertionError(f"No subclasses support for now, found {type(t)}") + return torch.empty_strided( + t.size() if new_shape is None else new_shape, + t.stride() if new_stride is None else new_stride, + device=t.device, + dtype=t.dtype, + requires_grad=t.requires_grad, + ) + return t + + +# Autoparallel specific, we want to treat plain tensors as DTensors +def _redistribute( + args: Any, + all_placements: tuple[Any], + mesh: Any, + shape_stride_fn: Callable[[torch.Tensor, Any, Any], tuple[list[int], list[int]]], +) -> GraphArg: + from torch._dispatch.python import suspend_functionalization + from torch._guards import detect_fake_mode + from torch._subclasses.functional_tensor import disable_functional_mode + from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing + + with ( + suspend_functionalization(), + disable_functional_mode(), + disable_proxy_modes_tracing(), + ): + fake_mode = detect_fake_mode(args) + if fake_mode is None: + raise AssertionError("defer_inlining() is only supported for FakeTensors") + + with fake_mode: + new_args = list(pytree.tree_map(_new_tensor, args)) + for i, (tensor, placements) in enumerate(zip(new_args, all_placements)): + if tensor is None: + # Sometimes gradients can be None + continue + + new_shape, new_stride = shape_stride_fn( + tensor, + mesh, + placements, + ) + new_args[i] = _new_tensor( + tensor, new_shape=new_shape, new_stride=new_stride + ) + + new_args = tuple(new_args) + if not all( + (is_fake_tensor(t) or isinstance(t, (int, torch.SymInt, type(None)))) + for t in new_args + ): + raise AssertionError(f"Unexpected element in {args=}") + + return new_args + + +def redistribute_fw_inputs( + global_args: Any, all_placements: Any, mesh: Any, _: int | None = None +) -> GraphArg: + if len(global_args) != len(all_placements): + raise AssertionError( + f"global_args length ({len(global_args)}) != all_placements length ({len(all_placements)})" + ) + return _redistribute( + global_args, + all_placements, + mesh, + torch.distributed.tensor._utils.compute_local_tensor_info, + ) + + +def redistribute_fw_outputs( + local_outs: Any, all_placements: Any, mesh: Any, num_activations: int +) -> GraphArg: + if len(local_outs) != len(all_placements) + num_activations: + raise AssertionError( + f"local_outs length ({len(local_outs)}) != " + f"all_placements length ({len(all_placements)}) + num_activations ({num_activations})" + ) + num_fw_outs = len(local_outs) - num_activations + if num_fw_outs <= 0: + raise AssertionError(f"num_fw_outs must be > 0, got {num_fw_outs}") + outs, activations = local_outs[:num_fw_outs], local_outs[num_fw_outs:] + return ( + *_redistribute( + outs, + all_placements, + mesh, + torch.distributed.tensor._utils.compute_global_tensor_info, + ), + *activations, + ) + + +def redistribute_bw_inputs( + global_args: Any, all_placements: Any, mesh: Any, num_activations: int +) -> GraphArg: + if len(global_args) != len(all_placements) + num_activations: + raise AssertionError( + f"global_args length ({len(global_args)}) != " + f"all_placements length ({len(all_placements)}) + num_activations ({num_activations})" + ) + activations, inputs = global_args[:num_activations], global_args[num_activations:] + if len(inputs) <= 0: + raise AssertionError("inputs must not be empty") + local_inputs = _redistribute( + inputs, + all_placements, + mesh, + torch.distributed.tensor._utils.compute_local_tensor_info, + ) + return ( + *activations, + *local_inputs, + ) + + +def redistribute_bw_outputs( + local_outs: Any, all_placements: Any, mesh: Any, _: int | None = None +) -> GraphArg: + if len(local_outs) != len(all_placements): + raise AssertionError( + f"local_outs length ({len(local_outs)}) != all_placements length ({len(all_placements)})" + ) + return _redistribute( + local_outs, + all_placements, + mesh, + torch.distributed.tensor._utils.compute_global_tensor_info, + ) + + +class LocalMapHOP(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("local_map_hop") + + def __call__(self, gm: GraphModule, *args: Any, **kwargs: Any) -> Any: + # pyrefly: ignore [missing-attribute] + return super().__call__(gm, *args, **kwargs) + + +local_map_hop = LocalMapHOP() + +# Registers dispatches for SAC +redirect_to_mode(local_map_hop, _CachingTorchDispatchMode) +redirect_to_mode(local_map_hop, _CachedTorchDispatchMode) + + +def create_hop_fw_bw( + fw_gm: GraphModule, + *_args: Any, +) -> tuple[GraphModule, GraphModule, int, int, set[int]]: + """ + Traces a joint, applies passes and partitions it + """ + # Keeping these imports here + # Avoid circular dependencies once we upstream with dynamo frontend + from torch._dispatch.python import suspend_functionalization + from torch._functorch.aot_autograd import AOTConfig, create_joint + from torch._guards import detect_fake_mode + from torch._subclasses.fake_tensor import FakeTensorMode + from torch._subclasses.functional_tensor import disable_functional_mode + from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing, make_fx + + local_map_kwargs = fw_gm.meta["local_map_kwargs"] # type: ignore[attr-defined] + if "in_placements" not in local_map_kwargs: + raise AssertionError("'in_placements' not found in local_map_kwargs") + if "out_placements" not in local_map_kwargs: + raise AssertionError("'out_placements' not found in local_map_kwargs") + if "device_mesh" not in local_map_kwargs: + raise AssertionError("'device_mesh' not found in local_map_kwargs") + if len(local_map_kwargs["in_placements"]) != len(_args): + raise AssertionError( + f"in_placements length ({len(local_map_kwargs['in_placements'])}) != _args length ({len(_args)})" + ) + + dummy_aot_config = AOTConfig( + fw_compiler=None, # type: ignore[arg-type] + bw_compiler=None, # type: ignore[arg-type] + partition_fn=None, # type: ignore[arg-type] + decompositions={}, + num_params_buffers=0, + aot_id=0, + keep_inference_input_mutations=False, + ) + + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + # If someone runs this hop under the default compiler backend ("eager") + # Then this path will be run with the actual user inputs. We convert them + # to fake tensors in order to not perform any actual compute. + + fake_mode = detect_fake_mode(_args) + if fake_mode is None: + fake_mode = FakeTensorMode(allow_non_fake_inputs=True) + + with fake_mode: + fw_inputs = redistribute_fw_inputs( + _args, + local_map_kwargs["in_placements"], + local_map_kwargs["device_mesh"], + ) + if len(fw_inputs) != len(local_map_kwargs["in_placements"]): + raise AssertionError( + f"fw_inputs length ({len(fw_inputs)}) != " + f"in_placements length ({len(local_map_kwargs['in_placements'])})" + ) + + if not all( + (is_fake_tensor(t) or isinstance(t, (int, torch.SymInt))) + for t in fw_inputs + ): + raise AssertionError(f"Unexpected element in {fw_inputs=}") + + ctx = ( + fake_mode.shape_env.ignore_fresh_unbacked_symbols + if fake_mode.shape_env is not None + else contextlib.nullcontext + ) + with ctx(): + fw_outs = fw_gm(*fw_inputs) + + example_grads = pytree.tree_map( + _new_tensor, + fw_outs, + ) + if not isinstance(example_grads, (list, tuple)): + example_grads = [example_grads] + + num_fw_inputs = len(fw_inputs) + num_fw_outputs = len(example_grads) + + def joint_f( + *primals_and_tangents: list[torch.Tensor], + ) -> Any: + primals = primals_and_tangents[:num_fw_inputs] + tangents = primals_and_tangents[num_fw_inputs:] + + def prepare_fw_with_masks( + fw_gm: torch.fx.GraphModule, + ) -> Callable[..., Any]: + def fw_with_masks(*args: Any) -> tuple[tuple[Any], list[bool]]: + # The Interpreter here is required to propagate metadata + # from the dynamo graph body to the local_map graph body. + # This is required for fx_traceback.annotate for work. + fw_out = torch.fx.Interpreter(fw_gm).run(*args) + if not isinstance(fw_out, tuple): + raise AssertionError( + "Dynamo traced submodule should return tuple" + ) + return fw_out, [ + bool(isinstance(ret, torch.Tensor) and ret.requires_grad) + for ret in fw_out + ] + + return fw_with_masks + + fw_outs, grads = create_joint( + prepare_fw_with_masks(fw_gm), aot_config=dummy_aot_config + )(primals, tangents) + from torch.fx.experimental.symbolic_shapes import has_free_unbacked_symbols + + if has_free_unbacked_symbols((*fw_outs, *grads)): + raise AssertionError( + "Unbacked symints leaking outside of the joint graph is not yet supported." + ) + + maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents) + # put grads first to work with existing hop utils + return pytree.tree_map(maybe_clone, (*grads, *fw_outs)) + + filtered_grads_idx = set() + for i, example_grad in enumerate(example_grads): + # Filter out grads that are None or do not require_grad. + # The AOTAutograd utils we rely on force this assumption. + # We must also filter the runtime tangents too. + if example_grad is not None and ( + isinstance(example_grad, torch.Tensor) and example_grad.requires_grad + ): + filtered_grads_idx.add(i) + + primals_and_tangents = [ + *fw_inputs, + *[example_grads[i] for i in filtered_grads_idx], + ] + joint_hop_gm = make_fx(joint_f)(*primals_and_tangents) + from torch._functorch._aot_autograd.graph_capture import ( + copy_fwd_metadata_to_bw_nodes, + ) + + copy_fwd_metadata_to_bw_nodes(joint_hop_gm) + + from torch._functorch._aot_autograd.graph_compile import prepare_for_partitioner + from torch._inductor.compile_fx import partition_fn + + # Match partitioner convention + prepped_joint_hop_gm = prepare_for_partitioner( + joint_hop_gm, num_fw_inputs, num_fw_outputs + ) + with disable_proxy_modes_tracing(): + # Also runs joint passes + new_fw_gm, new_bw_gm = partition_fn( + prepped_joint_hop_gm, + [], + num_fwd_outputs=num_fw_outputs, + static_lifetime_input_indices=[], + ) + + # Fix tags because min-cut does not respect fw/bw boundary, breaking + # default partitioner's assumptions. + for node in new_fw_gm.graph.nodes: + node.meta["partitioner_tag"] = "is_forward" + node.meta.pop("autograd_backward", None) + for node in new_bw_gm.graph.nodes: + node.meta["partitioner_tag"] = "is_backward" + node.meta["autograd_backward"] = True + + # Propagate meta onto fw/bw graphs, later will be set on proxied nodes + new_fw_gm.meta["local_map_kwargs"] = local_map_kwargs + new_bw_gm.meta["local_map_kwargs"] = {**local_map_kwargs} + # Okay because Autoparallel assumes same sharding between param and grads + new_bw_gm.meta["local_map_kwargs"]["in_placements"] = tuple( + [local_map_kwargs["out_placements"][i] for i in filtered_grads_idx] + ) + new_bw_gm.meta["local_map_kwargs"]["out_placements"] = local_map_kwargs[ + "in_placements" + ] + + # Validate Forward + fw_kwargs = new_fw_gm.meta["local_map_kwargs"] + expected_fw_inputs = len(fw_kwargs["in_placements"]) + expected_fw_outputs = len(fw_kwargs["out_placements"]) + actual_fw_inputs = len(new_fw_gm.graph.find_nodes(op="placeholder")) + actual_fw_outputs = num_fw_outputs + if expected_fw_inputs != actual_fw_inputs: + raise AssertionError( + f"expected_fw_inputs ({expected_fw_inputs}) != actual_fw_inputs ({actual_fw_inputs})" + ) + if expected_fw_outputs != actual_fw_outputs: + raise AssertionError( + f"expected_fw_outputs ({expected_fw_outputs}) != actual_fw_outputs ({actual_fw_outputs})" + ) + + # Validate Activations + if len(new_fw_gm.graph.find_nodes(op="output")) != 1: + raise AssertionError( + f"Expected exactly 1 output node, got {len(new_fw_gm.graph.find_nodes(op='output'))}" + ) + num_activations = ( + len(new_fw_gm.graph.find_nodes(op="output")[0].args[0]) - num_fw_outputs + ) + # tensors first, then symints + if num_activations < 0: + raise AssertionError(f"num_activations must be >= 0, got {num_activations}") + + # Validate Backward + bw_kwargs = new_bw_gm.meta["local_map_kwargs"] + expected_bw_inputs = len(bw_kwargs["in_placements"]) + expected_bw_outputs = len(bw_kwargs["out_placements"]) + actual_bw_inputs = ( + len(new_bw_gm.graph.find_nodes(op="placeholder")) - num_activations + ) + if actual_bw_inputs <= 0: + raise AssertionError( + f"actual_bw_inputs must be > 0, got {actual_bw_inputs}" + ) + if expected_fw_inputs + expected_bw_inputs != len(primals_and_tangents): + raise AssertionError( + f"expected_fw_inputs ({expected_fw_inputs}) + expected_bw_inputs ({expected_bw_inputs}) " + f"!= primals_and_tangents length ({len(primals_and_tangents)})" + ) + if actual_fw_inputs + actual_bw_inputs != len(primals_and_tangents): + raise AssertionError( + f"actual_fw_inputs ({actual_fw_inputs}) + actual_bw_inputs ({actual_bw_inputs}) " + f"!= primals_and_tangents length ({len(primals_and_tangents)})" + ) + if len(new_bw_gm.graph.find_nodes(op="output")) != 1: + raise AssertionError( + f"Expected exactly 1 bw output node, got {len(new_bw_gm.graph.find_nodes(op='output'))}" + ) + actual_bw_outputs = len(new_bw_gm.graph.find_nodes(op="output")[0].args[0]) + if expected_bw_inputs != actual_bw_inputs: + raise AssertionError( + f"expected_bw_inputs ({expected_bw_inputs}) != actual_bw_inputs ({actual_bw_inputs})" + ) + if expected_bw_outputs != actual_bw_outputs: + raise AssertionError( + f"expected_bw_outputs ({expected_bw_outputs}) != actual_bw_outputs ({actual_bw_outputs})" + ) + + new_fw_gm.meta["num_activations"] = num_activations + new_fw_gm.meta["is_backward"] = False + new_bw_gm.meta["num_activations"] = num_activations + new_bw_gm.meta["is_backward"] = True + + return new_fw_gm, new_bw_gm, num_fw_inputs, num_fw_outputs, filtered_grads_idx + + +class LocalMapAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx: Any, + fw_gm: GraphModule, + bw_gm: GraphModule, + num_fw_ins: int, + num_fw_outs: int, + filtered_grads_idx: set[int], + *args: Any, + **kwargs: Any, + ) -> tuple[torch.Tensor | None, ...]: + from torch._functorch._aot_autograd.schemas import MemoryFormatMeta + + ctx.bw_gm = bw_gm + ctx.num_fw_ins = num_fw_ins + ctx.filtered_grads_idx = filtered_grads_idx + + with torch._C._AutoDispatchBelowAutograd(): + fw_outs_with_saved_activations = local_map_hop(fw_gm, *args, **kwargs) + + fw_outs = fw_outs_with_saved_activations[:num_fw_outs] + saved_activations = fw_outs_with_saved_activations[num_fw_outs:] + save_values_for_backward(ctx, saved_activations) + + # Force memory_format path (not exact size/stride) because local_map forward + # operates on local shapes but backward receives global-shaped tangents. + # TODO(ivankobzarev): Support exact size/stride by converting between local/global shapes. + ctx.expected_tangent_metadata = { + i: MemoryFormatMeta.from_tensor(fw_outs[i], force_use_memory_format=True) + for i in filtered_grads_idx + } + return fw_outs + + @staticmethod + def backward( + ctx: Any, *_grads: tuple[torch.Tensor] + ) -> tuple[torch.Tensor | None, ...]: + from torch._functorch._aot_autograd.runtime_wrappers import ( + coerce_to_expected_memory_format, + ) + + if ctx.pos != sorted(ctx.pos): + raise AssertionError( + "Interleaving saved tensor activations and symints is not expected from min-cut partitioner." + ) + ctx.pos = list(reversed(ctx.pos)) # make saved_values return symints first + saved_activations = saved_values(ctx) + with torch._C._AutoDispatchBelowAutograd(): + # Filter out grads that are None or do not require_grad. + # The AOTAutograd utils we rely on force this assumption. + grads = [_grads[i] for i in ctx.filtered_grads_idx] + if len(grads) != len(ctx.expected_tangent_metadata): + raise AssertionError( + f"{len(grads)=} vs {len(ctx.expected_tangent_metadata)}" + ) + + for i, meta in ctx.expected_tangent_metadata.items(): + grads[i] = coerce_to_expected_memory_format(grads[i], meta) + + grad_ins = local_map_hop(ctx.bw_gm, *saved_activations, *grads) + if len(grad_ins) != ctx.num_fw_ins: + raise RuntimeError( + f"Expected {ctx.num_fw_ins} grad_ins, got {len(grad_ins)}" + ) + return None, None, None, None, None, *grad_ins + + +@local_map_hop.py_impl(torch._C.DispatchKey.Autograd) +def autograd_key( + fw_gm: GraphModule, + *args: Any, + **kwargs: Any, +) -> Any: + local_map_kwargs = fw_gm.meta["local_map_kwargs"] # type: ignore[attr-defined] + if local_map_kwargs.get("in_grad_placements", None) is not None: + raise AssertionError("local_map in_grad_placements are not yet supported.") + if _DEFER_INLINING: + fw_gm, bw_gm, num_fw_ins, num_fw_outs, filtered_grads_idx = create_hop_fw_bw( + fw_gm, *args + ) + return LocalMapAutogradOp.apply( + fw_gm, bw_gm, num_fw_ins, num_fw_outs, filtered_grads_idx, *args, **kwargs + ) + + # TODO: get rid of this when we can install as a subgraph + return torch.fx.Interpreter(fw_gm).run(*args, **kwargs) + + +@local_map_hop.py_functionalize_impl +def functional_mode_key( + ctx: Any, gm: GraphModule, *args: Any, **kwargs: Any +) -> tuple[torch.Tensor]: + if kwargs: + raise AssertionError(f"kwargs must be empty, got {kwargs}") + + unwrapped_inputs = ctx.unwrap_tensors(args) + with ctx.redispatch_to_next(): + out = local_map_hop(gm, *unwrapped_inputs) + return ctx.wrap_tensors(out) + + +@register_fake(local_map_hop, skip_cache=True) +def fake_mode_key( + gm: GraphModule, + *args: Any, + **kwargs: Any, +) -> GraphArg: + if not _DEFER_INLINING: + return gm(*args, **kwargs) + + # otherwise, we need to convert to local shapes for AP + # invoke_subgraph runs its body below Autograd, so local_map_hop's Autograd + # key may not have partitioned the body or set fw/bw metadata. + is_backward = gm.meta.get("is_backward", False) + num_activations = gm.meta.get("num_activations", 0) + redistribute_inputs = ( + redistribute_bw_inputs if is_backward else redistribute_fw_inputs + ) + local_args = redistribute_inputs( + args, + gm.meta["local_map_kwargs"]["in_placements"], + gm.meta["local_map_kwargs"]["device_mesh"], + num_activations, + ) + local_outs = gm(*local_args) + redistribute_outputs = ( + redistribute_bw_outputs if is_backward else redistribute_fw_outputs + ) + global_outs = redistribute_outputs( + local_outs, + gm.meta["local_map_kwargs"]["out_placements"], + gm.meta["local_map_kwargs"]["device_mesh"], + num_activations, + ) + return global_outs + + +def _proxy_mode_arg( + proxy_mode: ProxyTorchDispatchMode, + arg: Any, +) -> Any: + if isinstance(arg, torch.fx.GraphModule): + # Install local_map bodies as real submodules so FX source emission can + # reload them through self instead of closing over a local Python target. + registered = any( + arg is submod + for _, submod in proxy_mode.tracer.root.named_modules() # type: ignore[union-attr] + ) + if not registered: + qualname = proxy_mode.tracer.get_fresh_qualname("local_map_body") # type: ignore[union-attr] + proxy_mode.tracer.root.register_module(qualname, arg) # type: ignore[union-attr] + return proxy_mode.tracer.unwrap_proxy(arg) # type: ignore[union-attr] + + +def proxy_mode_key_common( + proxy_mode: ProxyTorchDispatchMode, + gm: GraphModule, + *args: Any, + **kwargs: Any, +) -> tuple[torch.Tensor]: + if proxy_mode is None: + raise AssertionError("Mode should always be enabled for python fallback key") + if len(kwargs) != 0: + raise AssertionError(f"kwargs must be empty, got {kwargs}") + + example_out = local_map_hop(gm, *args, **kwargs) + proxy_args = pytree.tree_map( + lambda arg: _proxy_mode_arg(proxy_mode, arg), + (gm, *args), + ) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", local_map_hop, proxy_args, {} + ) + + # extract local_map args, post-dispatch operates on GraphModules + if not gm.meta["local_map_kwargs"]: + raise AssertionError("gm.meta['local_map_kwargs'] must be set") + local_map_kwargs = gm.meta["local_map_kwargs"] + + # propagate local_map args to the call_function node + out_proxy.node.meta["local_map_kwargs"] = local_map_kwargs + + return track_tensor_tree( + example_out, out_proxy, constant=None, tracer=proxy_mode.tracer + ) + + +@local_map_hop.py_impl(ProxyTorchDispatchMode) +def proxy_mode_key( + proxy_mode: ProxyTorchDispatchMode, + gm: GraphModule, + *args: Any, + **kwargs: Any, +) -> tuple[torch.Tensor]: + return proxy_mode_key_common(proxy_mode, gm, *args, **kwargs) + + +# Running HOP in eager with real tensors +@local_map_hop.py_impl(DispatchKey.CompositeExplicitAutograd) +def real_impl( + gm: GraphModule, + *args: Any, + **kwargs: Any, +) -> tuple[torch.Tensor]: + return gm(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/map.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/map.py new file mode 100644 index 0000000000000000000000000000000000000000..f1c3f4119fcd508218e763a6fc4ec5ae0b1300e3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/map.py @@ -0,0 +1,426 @@ +# mypy: allow-untyped-defs +import functools +from collections.abc import Callable, Sequence +from typing import Any +from typing_extensions import TypeVarTuple + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._dispatch.python import suspend_functionalization +from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, +) +from torch._higher_order_ops.utils import ( + _from_fun, + _maybe_run_with_interpreter, + _stack_pytree, + _unstack_pytree, + create_bw_fn, + fill_none_with_masks, + filter_with_masks, + first_slice_copy, + get_graph_output_example_values, + HopInstance, + materialize_as_graph, + reenter_make_fx, + register_fake, + save_values_for_backward, + saved_values, + split_into_chunks, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.functional_tensor import disable_functional_mode +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +class MapImpl(HigherOrderOperator): + def __init__(self): + super().__init__("map_impl") + + def __call__( + self, + f: Callable[..., Any], + xs: Sequence[torch.Tensor], + pos_args: Sequence[torch.fx.node.BaseArgumentTypes], + *, + mutated_arg_indices: str = "", + ) -> Any: + # pyrefly: ignore [missing-attribute] + return super().__call__( + f, xs, pos_args, mutated_arg_indices=mutated_arg_indices + ) + + # pyrefly: ignore [bad-override] + def gen_schema(self, f, xs, pos_args, mutated_arg_indices: str = ""): + from torch._higher_order_ops.schema import HopSchemaGenerator + + all_inputs = tuple( + [ + torch.empty_strided( + x.shape[1:], + x.stride()[1:], + dtype=x.dtype, + device=x.device, + requires_grad=x.requires_grad, + ) + for x in xs + ] + + list(pos_args) + ) + body_gm = materialize_as_graph(f, all_inputs) + + # Mutation semantics for map: + # - xs is mutable: each iteration sees a storage-disjoint slice + # (xs[t] and xs[t+1] share no storage), so in-place writes are + # race-free regardless of evaluation order, preserving map's + # "iterations are independent" contract. + # - pos_args is NOT mutable: every iteration sees the same + # tensor, so mutating it makes iterations depend on each + # other, breaking the independence contract and introducing a + # data race under any parallel lowering. Users who need a + # shared mutable buffer should use scan / while_loop, where + # sequential iteration is part of the contract. + outputs = get_graph_output_example_values(body_gm) + mutated_set = {int(i) for i in mutated_arg_indices.split(",") if i} + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("f", body_gm) + + for idx, x in enumerate(xs): + schema_gen.add_arg(f"xs{idx}", x, is_mutated=idx in mutated_set) + + for idx, arg in enumerate(pos_args): + schema_gen.add_arg(f"additional_input{idx}", arg) + + for out in outputs: + schema_gen.add_output(out) + + schema_gen.add_schema_tree_spec(f, xs, pos_args) + return schema_gen.gen_schema() + + +map_impl = MapImpl() + + +def map( + f: Callable[[pytree.PyTree, tuple[pytree.PyTree, ...]], pytree.PyTree], + xs: pytree.PyTree | torch.Tensor, + *args: TypeVarTuple, +): + r""" + Performs a map of f with xs. Intuitively, you can think of the semantic being:: + + out = [] + for idx in len(xs.size(0)): + xs_sliced = xs.select(0, idx) + out.append(f(xs_sliced, *args)) + torch.stack(out) + + .. warning:: + + ``torch._higher_order_ops.map`` is a prototype feature in PyTorch. It currently + does not support autograd and you may run into miscompiles. + Read more about feature classification at: + https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + + Args: + f (Callable): a callable that takes an input x, that could either be a single Tensor + or a nested dict, list of tensors and some additional inputs + xs: the inputs that're to be mapped over. We'll iterate over the first dim of each x + and perform f on each slice. + + *args: additional arguments provided to each step of f. They could also be omitted and + map is able to automatically figure out the read dependency. + + Return: + the stacked output for each step of f + + Example:: + + def f(xs): + return xs[0] + xs[1] + const1 + const2 + + + xs = [torch.randn(2, 3), torch.randn(2, 3)] + const1 = torch.randn(2, 3) + const2 = torch.randn(2, 3) + # returns a tensor of shape [2, 2, 3] + torch._higher_order_ops.map(f, xs) + + """ + flat_xs, xs_spec = pytree.tree_flatten(xs) + flat_args, args_spec = pytree.tree_flatten(args) + if not all(isinstance(t, torch.Tensor) for t in flat_xs): + raise RuntimeError(f"Mapped xs can only consist of tensors. Got xs {flat_xs}.") + + shapes = [xs.shape for xs in flat_xs] + leading_dim_size = shapes[0][0] + if leading_dim_size == 0: + raise RuntimeError("Leading dimensions of mapped xs cannot be 0.") + + if any(cur_shape[0] != leading_dim_size for cur_shape in shapes): + raise RuntimeError( + f"Leading dimensions of mapped xs must be consistent. Got shapes {shapes}." + ) + + def run_flattened_map(f, flat_xs, flat_args): + def wrapped_fn(*flat_args, f, xs_tree_spec, args_tree_spec, num_xs): + xs = pytree.tree_unflatten(flat_args[:num_xs], xs_tree_spec) + args = pytree.tree_unflatten(flat_args[num_xs:], args_tree_spec) + return f(xs, *args) + + inner_f = functools.partial( + wrapped_fn, + f=f, + xs_tree_spec=xs_spec, + args_tree_spec=args_spec, + num_xs=len(flat_xs), + ) + return map_impl(inner_f, flat_xs, flat_args) + + from torch._higher_order_ops.utils import _maybe_compile_and_run_fn + + return _maybe_compile_and_run_fn(run_flattened_map, f, flat_xs, flat_args) + + +class MapAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx, f, num_mapped_args, *flat_args): + ctx._f = f + ctx._num_mapped_args = num_mapped_args + ctx._num_pos_args = len(flat_args) - num_mapped_args + + # We snapshot the dispatch keys in forward for materializing + # the bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + save_values_for_backward(ctx, flat_args) + with torch._C._AutoDispatchBelowAutograd(): + return ( + *map_impl(f, flat_args[:num_mapped_args], flat_args[num_mapped_args:]), + ) + + @staticmethod + def backward(ctx, *flat_grads): + fw_args = saved_values(ctx) + num_mapped_args = ctx._num_mapped_args + num_pos_args = ctx._num_pos_args + num_grads = len(flat_grads) + + fw_mapped_args, pos_args = split_into_chunks( + fw_args, + [ + num_mapped_args, + num_pos_args, + ], + ) + + bw_f = create_bw_fn(ctx._f, fw_args) + + grads_tensor_masks = [] + + # Create a wrapper around thefor the bw_f + def bw_f_wrapper(*args): + nonlocal grads_tensor_masks + + # Dissect args and re-order them for the ``ctx._bw_f`` + # args provided to the wrapper are composed of [*fw_mapped_args, *flat_grads, *pos_args] + # The content of ``bw_f_tangents`` are the upstream gradients, i.e. flat_grads + # The content of ``bw_f_primals`` are the fw_args, i.e., [*fw_mapped_args, *pos_args] + # The bw_f requires *bw_f_primals, *bw_f_tangents + fw_m_args, bw_f_tangents, pos_args = split_into_chunks( + args, [num_mapped_args, num_grads, num_pos_args] + ) + bw_f_primals = *fw_m_args, *pos_args + gradients = bw_f(*bw_f_primals, *bw_f_tangents) + grads_tensor_masks = [ + True if isinstance(out, torch.Tensor) else out for out in gradients + ] + return filter_with_masks(gradients, grads_tensor_masks) + + def construct_args_single_step_bw(): + unwrapped_mapped_xs = pytree.tree_map(_from_fun, fw_mapped_args) + # Use first_slice_copy instead of _unstack_pytree to avoid + # iterating over batch dim, which would guard on symbolic sizes. + example_xs = [ + first_slice_copy(x).requires_grad_(x.requires_grad) + for x in unwrapped_mapped_xs + ] + unwrapped_grads = pytree.tree_map(_from_fun, flat_grads) + example_grads = [ + first_slice_copy(x).requires_grad_(x.requires_grad) + for x in unwrapped_grads + ] + example_pos_args = [ + _from_fun(arg) if isinstance(arg, torch.Tensor) else arg + for arg in pos_args + ] + return *example_xs, *example_grads, *example_pos_args + + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + args_single_step_bw = construct_args_single_step_bw() + + # TODO: we need to materialize the bw graphs because dynamo is unable to + # trace through the joint function when torch.compile torch.autograd.grad. + fn_bw_gm = materialize_as_graph( + bw_f_wrapper, + args_single_step_bw, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + + grads = map_impl(fn_bw_gm, fw_mapped_args + flat_grads, pos_args) + + return None, None, *fill_none_with_masks(grads, grads_tensor_masks) + + +def _broadcast_to_batch(output, batch_size): + """Expand each tensor in output pytree to include batch dimension. + + Note: Although outputs are flattened in the compiled path (via torch.compile), + users may call map_impl directly with pytree outputs, so we support pytrees + for backward compatibility. + """ + + def expand_with_batch(t): + if isinstance(t, torch.Tensor): + # Use contiguous_format to match torch.stack behavior + return ( + t.unsqueeze(0) + .expand(batch_size, *t.shape) + .clone(memory_format=torch.contiguous_format) + ) + return t + + return pytree.tree_map(expand_with_batch, output) + + +def trace_map( + proxy_mode, + func_overload: HigherOrderOperator, + f: Callable[..., Any], + xs: Sequence[torch.Tensor], + pos_args: Sequence[torch.fx.node.BaseArgumentTypes], + mutated_arg_indices: str = "", +) -> Any: + with disable_proxy_modes_tracing(): + # Use first_slice_copy instead of _unstack_pytree to avoid + # iterating over batch dim, which would guard on symbolic sizes. + example_input = pytree.tree_map(first_slice_copy, xs) + + body_graph = reenter_make_fx(f)(*example_input, *pos_args) + + next_name = proxy_mode.tracer.get_fresh_qualname("body_graph_") + proxy_mode.tracer.root.register_module(next_name, body_graph) + + fake_outs = map_impl( + body_graph, xs, pos_args, mutated_arg_indices=mutated_arg_indices + ) + + node_args = (body_graph, list(xs), list(pos_args)) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", + func_overload, + proxy_args, + {"mutated_arg_indices": mutated_arg_indices} if mutated_arg_indices else {}, + name="map_impl", + ) + return track_tensor_tree( + fake_outs, out_proxy, constant=None, tracer=proxy_mode.tracer + ) + + +@map_impl.py_impl(DispatchKey.CompositeExplicitAutograd) +def map_dense(f, xs, pos_args, mutated_arg_indices=""): + pytrees = [f(*inp, *pos_args) for inp in _unstack_pytree(xs)] + return _stack_pytree(pytrees) + + +@map_impl.py_autograd_impl +def map_autograd(f, xs, pos_args, mutated_arg_indices=""): + num_mapped_args = len(xs) + flat_out = MapAutogradOp.apply(f, num_mapped_args, *xs, *pos_args) + return flat_out + + +@map_impl.py_impl(ProxyTorchDispatchMode) +def map_proxy_torch_dispatch_mode(mode, f, xs, pos_args, mutated_arg_indices=""): + return trace_map( + mode, map_impl, f, xs, pos_args, mutated_arg_indices=mutated_arg_indices + ) + + +@register_fake(map_impl, skip_cache=True) +def map_fake_tensor_mode(f, xs, pos_args, mutated_arg_indices=""): + # Use first_slice_copy instead of _unstack_pytree to avoid + # iterating over batch dim, which would guard on symbolic sizes. + first_row = pytree.tree_map(first_slice_copy, xs) + example_output = f(*first_row, *pos_args) + + flat_xs, _ = pytree.tree_flatten(xs) + batch_size = flat_xs[0].shape[0] + + return _broadcast_to_batch(example_output, batch_size) + + +@map_impl.py_functionalize_impl +def map_functionalize(ctx, f, xs, pos_args, mutated_arg_indices=""): + from torch._higher_order_ops.utils import _check_alias_and_mutation + + if hasattr(ctx, "mode"): + hop_instance = HopInstance.create( + map_impl, + f, + xs, + pos_args, + mutated_arg_indices=mutated_arg_indices, + ) + if can_auto_functionalize(hop_instance): + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + tuple(pytree.tree_flatten((f, xs, pos_args))[0]), + {}, + ) + + unwrapped_xs = ctx.unwrap_tensors(xs) + unwrapped_args = ctx.unwrap_tensors(pos_args) + wrapped_fn = ctx.functionalize(_maybe_run_with_interpreter(f)) + + with ctx.redispatch_to_next(): + # Use first_slice_copy instead of _unstack_pytree to avoid + # iterating over batch dim, which would guard on symbolic sizes. + example_inputs = ( + *pytree.tree_map(first_slice_copy, unwrapped_xs), + *unwrapped_args, + ) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + _check_alias_and_mutation(f, example_inputs, "map", pre_dispatch) + map_return = map_impl( + wrapped_fn, + unwrapped_xs, + unwrapped_args, + mutated_arg_indices=mutated_arg_indices, + ) + return ctx.wrap_tensors(map_return) + + +def _fake_map(f, x, *args): + from functorch.experimental.control_flow import _stack_pytree, _unstack_pytree + + x_pytrees = _unstack_pytree(x) + zs = [] + for xp in x_pytrees: + zs.append(f(xp, *args)) + return _stack_pytree(zs) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/out_dtype.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/out_dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..75dbf8e79f421ea5fe3a6987ff958b358b48c149 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/out_dtype.py @@ -0,0 +1,161 @@ +# mypy: allow-untyped-defs + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import autograd_not_implemented, register_fake +from torch._ops import HigherOrderOperator +from torch._prims_common import elementwise_dtypes, ELEMENTWISE_TYPE_PROMOTION_KIND +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + maybe_handle_decomp, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +# TODO to figure out a more generic approach +ALLOWABLE_OPS = [ + torch.ops.aten.linear.default, + torch.ops.aten.mm.default, + torch.ops.aten.conv2d.default, + torch.ops.aten.convolution.default, + torch.ops.aten.mul.Tensor, + torch.ops.aten.mul.Scalar, + torch.ops.aten.div.Tensor, + torch.ops.aten.div.Scalar, +] + + +class OutDtypeOperator(HigherOrderOperator): + """ + The out_dtype operator takes an existing ATen functional operator, an + `out_dtype` argument, and arguments to the original operator, and executes + the original operator and returns a Tensor with the `out_dtype` precision. + This operator does not mandate a compute precision so it allows the + representation to not be opinionated about the exact implementation. + + The general implementation for all operators will be the following: + 1. Promote inputs dtypes based on default PyTorch dtype promotion rules, + using the dtypes of all input Tensors/Scalars and the `out_dtype` + argument. + 2. Execute the operator + 3. Cast the output to `out_dtype` + """ + + def __init__(self) -> None: + super().__init__("out_dtype") + + def __call__(self, op, output_dtype, *args): + if not isinstance(op, torch._ops.OpOverload): + raise ValueError("out_dtype's first argument must be an OpOverload") + if op._schema.is_mutable: + raise ValueError( + "out_dtype's first argument needs to be a functional operator" + ) + if not ( + len(op._schema.returns) == 1 + and isinstance(op._schema.returns[0].type, torch.TensorType) + ): + raise ValueError( + "out_dtype's can only apply to ops that return a single tensor" + f"Instead got {[r.type for r in op._schema.returns]}" + ) + + if op not in ALLOWABLE_OPS: + raise ValueError( + f"out_dtype only allows the following operators: {ALLOWABLE_OPS}." + ) + + # pyrefly: ignore [missing-attribute] + res = super().__call__(op, output_dtype, *args) + + return res + + +out_dtype = OutDtypeOperator() + + +def trace_out_dtype(proxy_mode, func_overload, op, output_dtype, *args): + # NB: Long-term we should put the decomposition logic into + # ProxyTorchDispatchMode so that people do not need to call maybe_handle_decomp + # in all HigherOrderOp proxy implementations. + r = maybe_handle_decomp(proxy_mode, func_overload, (op, output_dtype, *args), {}) + if r is not NotImplemented: + return r + + with disable_proxy_modes_tracing(): + # This is a simplified implementation of this operator just for tracing. + # Actual implementation may also first promote the arguments + out = op(*args).to(dtype=output_dtype) + + node_args = (op, output_dtype, *args) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {}, name="out_dtype" + ) + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@out_dtype.py_impl(DispatchKey.CompositeExplicitAutograd) +def out_dtype_dense(op: torch._ops.OpOverload, output_dtype: torch.dtype, *args): + if is_int_mm(op, output_dtype, args): + return torch._int_mm(*args) + return out_dtype_fallback(op, output_dtype, *args) + + +def is_int_mm(op, output_dtype, args): + return ( + op is torch.ops.aten.mm.default + and output_dtype == torch.int32 + and len(args) == 2 + and args[0].dtype == torch.int8 + and args[1].dtype == torch.int8 + and (args[0].is_cuda or args[0].is_xpu) + and (args[1].is_cuda or args[1].is_xpu) + ) + + +def out_dtype_fallback(op, output_dtype, *args): + flat_inputs = pytree.arg_tree_leaves(*args) + [torch.ones(1, dtype=output_dtype)] + promote_dtype: torch.dtype = elementwise_dtypes( + *flat_inputs, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + )[0] + + casted_args = pytree.tree_map_only( + torch.Tensor, lambda arg: arg.to(dtype=promote_dtype), args + ) + res = op(*casted_args).to(dtype=output_dtype) + return res + + +out_dtype.py_autograd_impl(autograd_not_implemented(out_dtype, deferred_error=True)) + + +@out_dtype.py_impl(ProxyTorchDispatchMode) +def out_dtype_proxy( + mode: ProxyTorchDispatchMode, + op: torch._ops.OpOverload, + output_dtype: torch.dtype, + *args, +): + return trace_out_dtype(mode, out_dtype, op, output_dtype, *args) + + +@register_fake(out_dtype, skip_cache=True) +def out_dtype_fake_tensor_mode( + op: torch._ops.OpOverload, + output_dtype: torch.dtype, + *args, +): + return out_dtype_dense(op, output_dtype, *args) + + +@out_dtype.py_functionalize_impl +def out_dtype_func(ctx, op, output_dtype, *args): + unwrapped_args = tuple(ctx.unwrap_tensors(arg) for arg in args) + + with ctx.redispatch_to_next(): + res = out_dtype(op, output_dtype, *unwrapped_args) + return ctx.wrap_tensors(res) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/partitioner.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/partitioner.py new file mode 100644 index 0000000000000000000000000000000000000000..7bdcc24e45e75d730eb74f8da1653e19f7c6869f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/partitioner.py @@ -0,0 +1,378 @@ +import logging +from collections.abc import Callable +from typing import Any + +import torch +from torch._higher_order_ops.utils import create_bw_fn, materialize_as_graph + + +logger: logging.Logger = logging.getLogger(__name__) + + +def _find_hop_subgraph_outputs(gm: torch.fx.GraphModule) -> tuple[torch.fx.Node]: + output_node_args = gm.graph.find_nodes(op="output")[0].args + if not isinstance(output_node_args, tuple): + raise AssertionError( + f"expected output_node_args to be tuple, got {type(output_node_args)}" + ) + return output_node_args[0] + + +def is_complex_expr(expr: Any) -> bool: + return not expr.is_symbol and not expr.is_constant() + + +class HopPartitionedGraph: + def __init__( + self, + fw_gm: torch.fx.GraphModule, + bw_gm: torch.fx.GraphModule, + n_fw_outputs: int, + n_intermediates: int, + no_complex_exprs_at_boundary: bool, + ): + self.fw_gm = fw_gm + self.bw_gm = bw_gm + self.n_fw_outputs = n_fw_outputs + self.n_intermediates = n_intermediates + self.no_complex_exprs_at_boundary = no_complex_exprs_at_boundary + self._reorder_fw_output() + self._check_partition_boundary() + + def _check_partition_boundary(self) -> None: + """check partitioned graph is in valid state.""" + invalid_reasons = [] + fw_outputs = _find_hop_subgraph_outputs(self.fw_gm) + for i, out in enumerate(fw_outputs): + if "val" not in out.meta: + invalid_reasons.append(f"fw_gm output[{i}] doesn't have a 'val' meta.") + elif not isinstance(out.meta["val"], (torch.SymInt, torch.Tensor)): + invalid_reasons.append( + f"fw_gm output[{i}] is of type {type(out.meta['val'])} but only SymInt or Tensor are allowed." + ) + + elif ( + isinstance(out.meta["val"], torch.SymInt) + and is_complex_expr(out.meta["val"].node.expr) + and self.no_complex_exprs_at_boundary + ): + invalid_reasons.append( + f"fw_gm output[{i}] must be of type SymInt with basic symbols or " + f"Tensor but got {type(out.meta['val'])} {out.meta['val']}" + ) + + if len(fw_outputs) != self.n_fw_outputs + self.n_intermediates: + invalid_reasons.append( + f"len(fw_outputs) ({len(fw_outputs)}) != n_fw_outputs ({self.n_fw_outputs}) + n_intermediates ({self.n_intermediates})" + ) + + bw_phs = list(self.bw_gm.graph.find_nodes(op="placeholder")) + + if len(fw_outputs) != len(bw_phs): + invalid_reasons.append( + f"Expect number of fw_gm's output to be the same as bw_gm's input but " + f"fw_gm has {len(fw_outputs)} outputs, bw_gm takes {len(bw_phs)} inputs." + ) + + original_forward_outputs = fw_outputs[: self.n_fw_outputs] + fw_intermediates = fw_outputs[self.n_fw_outputs :] + + bw_intermediates = bw_phs[: -self.n_fw_outputs] + bw_grads = bw_phs[-self.n_fw_outputs :] + + def _match_size_or_expr( + val1: torch.SymInt | torch.Tensor, + val2: torch.SymInt | torch.Tensor, + ) -> bool: + if type(val1) is not type(val2): + return False + + if isinstance(val1, torch.SymInt) and isinstance(val2, torch.SymInt): + return val1.node.expr == val2.node.expr + elif isinstance(val1, torch.Tensor) and isinstance(val2, torch.Tensor): + return val1.size() == val2.size() + + return False + + for fw, bw in zip(fw_intermediates, bw_intermediates): + if fw.name != bw.name or not _match_size_or_expr( + fw.meta["val"], bw.meta["val"] + ): + invalid_reasons.append("fw intermediates don't match bw intermediates") + + for fw_out, bw_grad in zip(original_forward_outputs, bw_grads): + if not _match_size_or_expr(fw_out.meta["val"], bw_grad.meta["val"]): + invalid_reasons.append("fw outputs don't match bw gradients") + + if len(invalid_reasons) > 0: + newline = "\n" + raise RuntimeError( + f"Invalid HopPartitionedGraph. Reasons:\n{newline.join(invalid_reasons)}" + ) + + def _reorder_fw_output(self) -> None: + """ + Before the pass, fw_gm returns (*fw_outputs, *intermediates1) + and bw_gm takes (*intermediates2, *grad_fw_outputs) as input. + intermediates1 and intermediates2 share the same node names but + they might be in different order. E.g. this could happen if there + are inputs that contain symints. + + To simplify downstream processing, this graph pass normalizes the output of fw_gm + to be consistent with the backward inputs: + + fw_gm: + - input: fw_args + - output: (*fw_outputs, *intermediates) + + bw_gm: + - input: (*intermediates, *grad_fw_outputs) + - output: grad_fw_args + + Example: + + def fw_gm(x, y, z): + a, b, c = f(x), g(y), k(z) + return a, b, c, f_tmp, g_tmp, k_tmp + + , where a, b, c are fw_outputs, f_tmp, g_tmp, k_tmp are intermediates + + The corresponding bw_gm has the following signature: + + def bw_gm(f_tmp, g_tmp, k_tmp, grad_a, grad_b, grac): + return grad_x, grad_y, grad_z + """ + fw_gm_output_nodes = _find_hop_subgraph_outputs(self.fw_gm) + fw_outputs_nodes = fw_gm_output_nodes[: self.n_fw_outputs] + fw_intermediates_nodes = fw_gm_output_nodes[self.n_fw_outputs :] + if len(fw_intermediates_nodes) > 0: + fw_intermediates_name_to_node = {n.name: n for n in fw_intermediates_nodes} + + # First n_intermediates placeholders + bw_names: list[str] = [ + ph.name + for ph in list(self.bw_gm.graph.find_nodes(op="placeholder"))[ + : self.n_intermediates + ] + ] + new_fw_outputs = list(fw_outputs_nodes) + [ + fw_intermediates_name_to_node[name] for name in bw_names + ] + + output_node = self.fw_gm.graph.find_nodes(op="output")[0] + output_node.args = (tuple(new_fw_outputs),) + + self.fw_gm.graph.lint() + self.fw_gm.recompile() + + +class HopJointGraph: + def __init__( + self, + joint_gm: torch.fx.GraphModule, + n_primals: int, + n_fw_outputs: int, + *, + functionalized: bool, + ): + self.joint_gm = joint_gm + self.n_primals = n_primals + self.n_fw_outputs = n_fw_outputs + self.functionalized = functionalized + + self._rename_phs() + self._remove_redundant_sym_size_ops() + + def _rename_phs(self) -> None: + """ + Rename the placeholders for joint_gm so that the partitioner + could recognize which inputs are primals and which are tangents. + """ + self.n_tangents = 0 + for i, ph in enumerate(self.joint_gm.graph.find_nodes(op="placeholder")): + if i < self.n_primals: + ph.target = f"primals_{i}" + ph.name = f"primals_{i}" + else: + self.n_tangents += 1 + ph.target = f"tangents_{i - self.n_primals}" + ph.name = f"tangents_{i - self.n_primals}" + + self.joint_gm.graph.lint() + self.joint_gm.compile() + + def _remove_redundant_sym_size_ops(self) -> None: + """ + Deletes torch.ops.sym_size.int operators whose output is a + corresponding placeholder that holds the same symbol, and replace all usage + of the sym_size node to be directly using the placeholders. + + This is to make sure all basic symbols come from inputs. + """ + placeholder_exprs = {} + for node in self.joint_gm.graph.nodes: + if ( + isinstance(node, torch.fx.Node) + and node.op == "placeholder" + and hasattr(node, "meta") + and "val" in node.meta + ): + val = node.meta["val"] + if isinstance(val, torch.SymInt): + placeholder_exprs[val.node.expr] = node + + nodes_to_remove = [] + for node in self.joint_gm.graph.find_nodes( + op="call_function", target=torch.ops.aten.sym_size.int + ): + if not (hasattr(node, "meta") and "val" in node.meta): + raise AssertionError( + f"node {node} must have 'meta' attribute with 'val' key" + ) + val = node.meta["val"] + expr = val.node.expr + if expr in placeholder_exprs: + placeholder_node = placeholder_exprs[expr] + node.replace_all_uses_with(placeholder_node) + nodes_to_remove.append(node) + + for node in nodes_to_remove: + self.joint_gm.graph.erase_node(node) + + self.joint_gm.graph.lint() + self.joint_gm.recompile() + + def _mark_complex_exprs_as_must_recompute(self) -> None: + """ + For control flow operators such as scan, we don't want to + have symint in the partitioning boundaries because otherwise we would need to support stacking + the symints up, which causes more entropy in the stack. + + By marking the recompute polify for complex nodes as MUST_RECOMPUTE, the partitioning boundary + no longer contains complex expressions. + + Note that this pass doesn't exclude basic symbols from partitioning boundary + and it's up to the downstream to decide whether to return the basic symbol + or have a separate graph pass to remove them. + """ + + from torch._functorch.partitioners import CheckpointPolicy + + for n in ( + node for node in self.joint_gm.graph.nodes if node.op == "call_function" + ): + if "val" not in n.meta: + continue + val = n.meta["val"] + if isinstance(val, torch.SymInt) and is_complex_expr(val.node.expr): + if n.meta.get("recompute", None) is not None: + raise AssertionError( + f"node {n} with complex SymInt expression should not have recompute policy set" + ) + + n.meta["recompute"] = CheckpointPolicy.MUST_RECOMPUTE + + self.joint_gm.graph.lint() + self.joint_gm.recompile() + + def partition( + self, partition_fn: Callable, always_recompute_complex_exprs: bool + ) -> HopPartitionedGraph: + if logger.isEnabledFor(logging.DEBUG): + logger.debug( + "before min_cut_partition:\n%s", + self.joint_gm.print_readable(print_output=False), + ) + + if always_recompute_complex_exprs: + self._mark_complex_exprs_as_must_recompute() + + fw_gm, bw_gm = partition_fn( + self.joint_gm, None, num_fwd_outputs=self.n_fw_outputs + ) + + if logger.isEnabledFor(logging.DEBUG): + logger.debug("after partition_fn:") + logger.debug("fw_gm:\n%s", fw_gm.print_readable(print_output=False)) + logger.debug("bw_gm:\n%s", bw_gm.print_readable(print_output=False)) + + n_intermediates = len(_find_hop_subgraph_outputs(fw_gm)) - self.n_fw_outputs + + return HopPartitionedGraph( + fw_gm, + bw_gm, + self.n_fw_outputs, + n_intermediates, + always_recompute_complex_exprs, + ) + + +def create_hop_joint_graph( + fw_fn: Callable, + fw_args: tuple[torch.Tensor | torch.SymInt, ...], + functionalize: bool, +) -> HopJointGraph: + fw_gm = materialize_as_graph(fw_fn, fw_args, force_enable_grad=True) + fw_gm_output_nodes = _find_hop_subgraph_outputs(fw_gm) + + if not all( + isinstance(n, torch.fx.Node) and "val" in n.meta for n in fw_gm_output_nodes + ): + raise AssertionError( + "all fw_gm output nodes must be torch.fx.Node with 'val' in meta" + ) + fw_gm_output_vals = tuple(n.meta["val"] for n in fw_gm_output_nodes) # type: ignore[arg-type] + + if not all(isinstance(val, torch.Tensor) for val in fw_gm_output_vals): + raise AssertionError( + f"all fw_gm output values must be torch.Tensor, got {[type(v) for v in fw_gm_output_vals]}" + ) + example_grads = tuple(torch.zeros_like(val) for val in fw_gm_output_vals) + + joint_fn = create_bw_fn(fw_fn, fw_args, return_fw_outputs=True) + joint_gm = materialize_as_graph( + joint_fn, fw_args + example_grads, force_enable_grad=True + ) + if functionalize: + # Need to first trace out the joint_fn with autograd info on + # then functionalize the graph otherwise the grad information is lost + joint_gm = materialize_as_graph( + # pyrefly: ignore [bad-argument-type] + torch.func.functionalize(joint_gm, remove="mutations_and_views"), + fw_args + example_grads, + ) + + return HopJointGraph( + joint_gm, + len(fw_args), + len(fw_gm_output_nodes), + functionalized=functionalize, + ) + + +class HopGraphMinCutPartitioner: + @staticmethod + def create_partitioned_graph( + fw_fn: Callable, + fw_args: tuple[torch.Tensor | torch.SymInt, ...], + *, + always_recompute_complex_exprs: bool = False, + ) -> HopPartitionedGraph: + """ + Inputs: + - fw_fn: the forward function that we'll use to create a joint graph and partition + - fw_args: the flat_args to fw_fn + - always_recompute_complex_exprs: when set to True, the bw_gm will do a re-compute + for inputs that are complex expressions such that the partitioning boundary + only consists of basic symbols and tensors. + + Returns a HopPartitionedGraph + """ + from torch._functorch.partitioners import min_cut_rematerialization_partition + + joint_graph: HopJointGraph = create_hop_joint_graph( + fw_fn, fw_args, functionalize=True + ) + return joint_graph.partition( + min_cut_rematerialization_partition, always_recompute_complex_exprs + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__init__.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ce0b13cffe9c1e4bd7fbdaecf550d94a668f838 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/inline_invoke_subgraph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/inline_invoke_subgraph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5da00f8be5015ad681bf660efb1cd633ab313898 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/inline_invoke_subgraph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/inline_invoke_subgraph.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/inline_invoke_subgraph.py new file mode 100644 index 0000000000000000000000000000000000000000..0509a1bda8ddc84645435b7b323dc25a64d9be28 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/inline_invoke_subgraph.py @@ -0,0 +1,153 @@ +import operator +from collections import Counter +from typing import Any, TYPE_CHECKING + +import torch +from torch.fx.graph_module import GraphModule + + +if TYPE_CHECKING: + from torch.fx.node import Node + + +def count_subgraph_uses(gm: GraphModule) -> Counter[str]: + """Count invoke_subgraph references by identifier string across all + descendant GraphModules.""" + counts: Counter[str] = Counter() + for mod in gm.modules(): + if not isinstance(mod, GraphModule): + continue + for node in mod.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ): + counts[str(node.args[1])] += 1 + return counts + + +def inline_single_use_invoke_subgraph(gm: GraphModule) -> GraphModule: + """Inline invoke_subgraph HOPs whose subgraph module has exactly one call + site across the entire module tree. + + When a subgraph has only a single caller, invoke_subgraph adds overhead + without any deduplication benefit, so we inline it unconditionally. + Subgraph modules that are shared across sibling modules (e.g. two AC body + modules referencing the same nested_compile_region) are counted globally + by module identity and preserved when referenced more than once. + """ + global_counts = count_subgraph_uses(gm) + inline_single_use_recursive(gm, global_counts) + return gm + + +def inline_single_use_recursive(gm: GraphModule, global_counts: Counter[str]) -> None: + # Recursively apply to nested subgraph modules first. + for name, mod in gm.named_modules(): + if name and isinstance(mod, GraphModule): + inline_single_use_recursive(mod, global_counts) + + invoke_nodes = list( + gm.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ) + ) + if not invoke_nodes: + return + + single_use_nodes = [ + node + for node in invoke_nodes + if global_counts[str(node.args[1])] == 1 + and not getattr(gm, str(node.args[0].target)).meta.get( + "nested_region_config", None + ) + ] + if not single_use_nodes: + return + + inline_invoke_subgraph_nodes(gm, single_use_nodes) + + +def hoist_submodules(gm: GraphModule, subgraph: GraphModule) -> dict[str, str]: + """Move submodules of *subgraph* onto *gm*, returning a name-remap dict. + + For each direct child module of *subgraph* (e.g. ``fwd_body_0``), register + it on *gm* under a unique name and return a mapping from the old name to the + new name so that ``get_attr`` targets copied from *subgraph*'s graph can be + rewritten. + """ + name_map: dict[str, str] = {} + existing_names = {name for name, _ in gm.named_children()} + for child_name, child_mod in list(subgraph.named_children()): + new_name = child_name + counter = 0 + while new_name in existing_names: + new_name = f"{child_name}_{counter}" + counter += 1 + gm.add_module(new_name, child_mod) + existing_names.add(new_name) + name_map[child_name] = new_name + return name_map + + +def inline_invoke_subgraph_nodes(gm: GraphModule, invoke_nodes: list["Node"]) -> None: + """Shared helper that inlines a list of invoke_subgraph nodes.""" + for node in invoke_nodes: + get_attr_node: torch.fx.Node = node.args[0] # pyrefly: ignore[bad-assignment] + operands = node.args[2:] + + subgraph: GraphModule = getattr(gm, str(get_attr_node.target)) + + # Hoist sub-submodules (e.g. fwd_body_0, bwd_body_0) to gm so that + # get_attr nodes copied from the subgraph resolve correctly. + name_map = hoist_submodules(gm, subgraph) + + env: dict[Node, Any] = dict( + zip(subgraph.graph.find_nodes(op="placeholder"), operands) + ) + + with gm.graph.inserting_before(node): + for sub_node in subgraph.graph.nodes: + if sub_node.op in ("placeholder", "output"): + continue + new_node = gm.graph.node_copy(sub_node, lambda n: env[n]) + if sub_node.op == "get_attr" and sub_node.target in name_map: + new_node.target = name_map[sub_node.target] + env[sub_node] = new_node + + output_values = subgraph.graph.output_node().args[0] + + for user in list(node.users): + if user.op == "call_function" and user.target is operator.getitem: + idx = user.args[1] + user.replace_all_uses_with(env[output_values[idx]]) # pyrefly: ignore + gm.graph.erase_node(user) + + gm.graph.erase_node(node) + + if not get_attr_node.users: + gm.graph.erase_node(get_attr_node) + + +def inline_invoke_subgraph(gm: GraphModule) -> GraphModule: + """Inline all invoke_subgraph HOPs, producing a flat FX graph. + + This is useful when downstream compilers (like vllm-compile) don't support + HOPs or prefer a flat graph, but we still want the Dynamo tracing-time + benefits of auto-caching (trace once, stamp out cached calls). + """ + # Recursively inline nested invoke_subgraph calls inside subgraph + # modules first, so their graphs are flat before we inline them here. + for name, mod in gm.named_modules(): + if name and isinstance(mod, GraphModule): + inline_invoke_subgraph(mod) + + invoke_nodes = list( + gm.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ) + ) + if not invoke_nodes: + return gm + + inline_invoke_subgraph_nodes(gm, invoke_nodes) + return gm diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/print.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/print.py new file mode 100644 index 0000000000000000000000000000000000000000..9ef6666b15bdb734c06124ac5e388840782cf769 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/print.py @@ -0,0 +1,153 @@ +import builtins + +import torch +import torch.utils._pytree as pytree +from torch._higher_order_ops.utils import register_fake +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode + + +class Print(HigherOrderOperator): + """ + print(format_str, *args, **kwargs) -> None + + This Higher Order Operator (HOP) provides a functional version of print for use in PyTorch graphs. + It supports the calling conventions of print(format_str.format(*args, **kwargs)): + + 1. Format string with keyword arguments (named placeholders): + torch._higher_order_ops.print("moo {x} {y}", x=1, y=2) + Output: "moo 1 2" + + 2. Format string with positional arguments (positional placeholders): + torch._higher_order_ops.print("moo {} {}", 1, 2) + Output: "moo 1 2" + + 3. Mixed positional and keyword arguments: + torch._higher_order_ops.print("moo {} {y}", 1, y=2) + Output: "moo 1 2" + + 4. DTensor support: + DTensor args are unwrapped to local tensors via to_local() (no collective). + Each rank prints its own local view, prefixed with [rank N]. + For the global view of a sharded tensor, call full_tensor() before + passing to print. + + dt = DTensor.from_local(local_shard, mesh, [Shard(0)]) + torch._higher_order_ops.print("activations: {}", dt) + # Output: [rank 0] activations: tensor([0., 1.]) + + This HOP enables printing without causing graph break. + """ + + def __init__(self) -> None: + super().__init__("print") + + def __call__(self, format_str: str, *args: object, **kwargs: object) -> None: + if not isinstance(format_str, str): + raise AssertionError(f"format_str must be a string, got {type(format_str)}") + # pyrefly: ignore [missing-attribute] + return super().__call__(format_str, *args, **kwargs) + + # pyrefly: ignore [bad-override] + def gen_schema( + self, format_str: str, *args: object, **kwargs: object + ) -> torch.FunctionSchema: + from torch._higher_order_ops.schema import HopSchemaGenerator + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("format_str", format_str[0]) + + # Add each positional arg + for i, value in enumerate(args): + schema_gen.add_arg(f"arg{i}", value) + + # Add each kwarg as a keyword-only argument + for key, value in kwargs.items(): + schema_gen.add_arg(key, value, kw_only=True) + + schema_gen.add_schema_tree_spec(format_str, *args, **kwargs) + + return schema_gen.gen_schema() + + +print = Print() + + +@print.py_impl(ProxyTorchDispatchMode) +# pyre-ignore +def print_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, format_str: str, *args: object, **kwargs: object +) -> None: + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) # type: ignore[union-attr] + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) # type: ignore[union-attr] + mode.tracer.create_proxy( + "call_function", print, (format_str, *proxy_args), proxy_kwargs + ) + + +@register_fake(print, skip_cache=True) +# pyre-ignore +def print_fake_tensor_mode(format_str: str, *args: object, **kwargs: object): + return None + + +@print.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd) +# pyre-ignore +def print_impl(format_str: str, *args: object, **kwargs: object) -> None: + # Ensure all immutable_dict/list in args and kwargs are converted to regular dict/list + map_types: dict[type, type] = { + torch.fx.immutable_collections.immutable_dict: dict, + torch.fx.immutable_collections.immutable_list: list, + } + new_args, new_kwargs = pytree.tree_map_only( + tuple(map_types.keys()), + lambda a: map_types[type(a)](a), + (args, kwargs), + lambda a: isinstance(a, tuple(map_types.keys())), + ) + # Use built-in print to avoid recursion with the HOP print + builtins.print(format_str.format(*new_args, **new_kwargs)) + + +print.fallthrough(torch._C.DispatchKey.AutogradCPU) +print.fallthrough(torch._C.DispatchKey.AutogradCUDA) + + +def _register_dtensor_impl() -> None: + from torch.distributed.tensor import DTensor + + @print.py_impl(DTensor) # pyrefly: ignore [missing-attribute] + # pyre-ignore + def print_dtensor(format_str: str, *args: object, **kwargs: object) -> None: + # Unwrap DTensors to local tensors via to_local() — no collective is + # introduced so there is no OOM or performance risk. Every rank prints + # its own local view (including Replicate, where to_local() already + # holds the full tensor). + # + # The output is prefixed with [rank N] so users can identify which rank + # produced each line. + # + # If the user needs the global view of a sharded tensor, they can call + # full_tensor() explicitly before passing it to print. + import torch.distributed as dist + + local_args = pytree.tree_map_only(DTensor, DTensor.to_local, args) + local_kwargs = pytree.tree_map_only(DTensor, DTensor.to_local, kwargs) + if dist.is_initialized() and dist.get_world_size() > 1: + format_str = f"[rank {dist.get_rank()}] {format_str}" + print( # pyrefly: ignore [no-matching-overload] + format_str, *local_args, **local_kwargs + ) + + +@print.py_functionalize_impl +def print_func(ctx, format_str: str, *args: object, **kwargs: object): + from torch._higher_order_ops.effects import handle_effects + + return handle_effects( + ctx.mode._allow_token_discovery, + ctx.mode._tokens, + print, # type: ignore[arg-type] + (format_str, *args), + kwargs, # type: ignore[arg-type] + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/register_hook.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/register_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..56ca41983521cf47be34cc2357700258da9a5eeb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/register_hook.py @@ -0,0 +1,34 @@ +from collections.abc import Callable +from typing import Any + +import torch +from torch._ops import HigherOrderOperator + + +class RegisterHookOp(HigherOrderOperator): + """HOP that registers a backward hook on a tensor. + + The hook body is a traced subgraph that takes (grad, *freevars) + and returns the modified gradient. During make_fx tracing, the + hook registers on the FakeTensor and fires on the accumulated + gradient during backward tracing, capturing the hook's effect + in the joint graph. + """ + + def __init__(self) -> None: + super().__init__("register_hook", cacheable=True) + + def __call__( + self, + tensor: torch.Tensor, + hook_body: Callable[..., Any], + *freevars: Any, + ) -> torch.Tensor: + def hook(grad: torch.Tensor) -> torch.Tensor | None: + return hook_body(grad, *freevars) + + tensor.register_hook(hook) + return tensor + + +register_hook_op = RegisterHookOp() diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/run_const_graph.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/run_const_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..11c9a9ed366471c1e615ef3071947627f94ebc52 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/run_const_graph.py @@ -0,0 +1,83 @@ +from typing import Any, TYPE_CHECKING + +import torch +from torch._C import DispatchKey +from torch._higher_order_ops.utils import autograd_not_implemented, register_fake +from torch._ops import HigherOrderOperator + + +if TYPE_CHECKING: + from torch._subclasses.functional_tensor import BaseFunctionalizeAPI + +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.utils import _pytree as pytree + + +class RunConstGraph(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("run_const_graph") + + def __call__(self, graph: torch.fx.GraphModule, args: tuple[object, ...]) -> object: + # pyrefly: ignore [missing-attribute] + return super().__call__(graph, args) + + +run_const_graph = RunConstGraph() + + +@run_const_graph.py_impl(ProxyTorchDispatchMode) +def run_const_graph_dispatch_mode( + mode: ProxyTorchDispatchMode, graph: torch.fx.GraphModule, args: tuple[object, ...] +) -> object: + const_gm, weights = graph, args + p_args = pytree.tree_map(mode.tracer.unwrap_proxy, (graph, args)) # type: ignore[union-attr] + if not isinstance(const_gm, torch.fx.GraphModule): + raise AssertionError( + f"expected const_gm to be torch.fx.GraphModule, got {type(const_gm)}" + ) + if hasattr(mode.tracer.root, "_const_graph"): # type: ignore[union-attr] + raise AssertionError("mode.tracer.root already has _const_graph attribute") + mode.tracer.root.register_module("_const_graph", const_gm) # type: ignore[union-attr] + + proxy = mode.tracer.create_proxy("call_function", run_const_graph, p_args, {}) + + out = const_gm(*weights) + return track_tensor_tree(out, proxy, constant=None, tracer=mode.tracer) + + +@run_const_graph.py_functionalize_impl +def run_const_graph_functional( + ctx: "BaseFunctionalizeAPI", graph: torch.fx.GraphModule, args: tuple[Any, ...] +) -> Any: + unwrapped_args = ctx.unwrap_tensors(args) + + with ctx.redispatch_to_next(): + out = run_const_graph(graph, unwrapped_args) + return ctx.wrap_tensors(out) # type: ignore[arg-type] + + +run_const_graph.py_autograd_impl( + autograd_not_implemented(run_const_graph, deferred_error=True) +) + + +@register_fake(run_const_graph, skip_cache=True) +def run_const_graph_fake_tensor_mode( + graph: torch.fx.GraphModule, args: tuple[object, ...] +) -> object: + if not isinstance(graph, torch.fx.GraphModule): + raise AssertionError( + f"expected graph to be torch.fx.GraphModule, got {type(graph)}" + ) + return graph(*args) + + +@run_const_graph.py_impl(DispatchKey.CPU) +def run_const_graph_cpu( + graph: torch.fx.GraphModule, args: tuple[object, ...] +) -> object: + if not isinstance(graph, torch.fx.GraphModule): + raise AssertionError( + f"expected graph to be torch.fx.GraphModule, got {type(graph)}" + ) + return graph(*args) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/scan.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/scan.py new file mode 100644 index 0000000000000000000000000000000000000000..2b0231c836296cd7293480a0e54936af098a49d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/scan.py @@ -0,0 +1,1280 @@ +# mypy: allow-untyped-defs +import enum +import functools +import itertools +import logging +from collections.abc import Callable +from typing import Any + +import torch +import torch._prims_common as utils +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._functorch.vmap import restore_vmap, unwrap_batched, wrap_batched +from torch._guards import detect_fake_mode +from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, +) +from torch._higher_order_ops.partitioner import ( + _find_hop_subgraph_outputs, + HopGraphMinCutPartitioner, + HopPartitionedGraph, +) +from torch._higher_order_ops.utils import ( + _maybe_compile_and_run_fn, + check_meta_consistency, + fill_none_with_masks, + filter_with_masks, + first_slice_copy, + get_graph_output_example_values, + get_tensor_mask, + HopInstance, + mask_list, + materialize_as_graph, + reenter_make_fx, + split_into_chunks, + unique_graph_id, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensorMode, is_fake_tensor +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.utils._python_dispatch import _get_current_dispatch_mode + + +logger: logging.Logger = logging.getLogger(__name__) +aten = torch._ops.ops.aten + + +def wrap_combine_fn_flat( + *args, combine_fn, spec_init, spec_xs, num_init_leaves, num_inp_leaves +): + if len(args) != (num_init_leaves + num_inp_leaves): + raise AssertionError( + f"combine_fn received wrong number of arguments, expected {num_init_leaves + num_inp_leaves}, but got {len(args)}" + ) + carry = pytree.tree_unflatten(args[:num_init_leaves], spec_init) + xs = pytree.tree_unflatten(args[num_init_leaves:], spec_xs) + return combine_fn(carry, xs) + + +def _extract_carry_and_out(flat_out: list[Any], num_carry: int): + return split_into_chunks(flat_out, [num_carry, len(flat_out) - num_carry]) + + +# We also do a clone with contiguous_format. This is to be consistent with +# eager semantic of scan, which stacks the outputs. The result is contiguous +# as a result of the stack operation. +def stack_y(y: torch.Tensor, scan_length: int) -> torch.Tensor: + return ( + y.unsqueeze(0) + .repeat(*([scan_length] + [1] * y.ndim)) + .clone(memory_format=torch.contiguous_format) + ) + + +def call_operator(operator, *args): + return pytree.tree_leaves(operator(*args)) + + +def _build_empty_output_for_length_zero( + combine_fn: Callable, init: pytree.PyTree +) -> pytree.PyTree: + """Probe combine_fn(init, None) to learn the output structure for length==0.""" + fake_mode = detect_fake_mode(pytree.tree_leaves(init)) or FakeTensorMode() + with fake_mode: + fake_init = pytree.tree_map( + lambda t: fake_mode.from_tensor(t) + if isinstance(t, torch.Tensor) and not is_fake_tensor(t) + else t, + init, + ) + _, sample_y = combine_fn(fake_init, None) + + def _empty_or_passthrough(l): + if isinstance(l, torch.Tensor): + return torch.empty([0] + list(l.shape), dtype=l.dtype, device=l.device) + if l is not None: + raise AssertionError(f"Expected leaf to be a Tensor or None, got {type(l)}") + return l + + return pytree.tree_map(_empty_or_passthrough, sample_y) + + +def scan( + combine_fn: Callable[ + [pytree.PyTree, pytree.PyTree], tuple[pytree.PyTree, pytree.PyTree] + ], + init: pytree.PyTree, + xs: pytree.PyTree, + *, + dim: int = 0, + reverse: bool = False, + length: int | None = None, +) -> tuple[pytree.PyTree, pytree.PyTree]: + r""" + Performs an inclusive scan with a combine function. + + .. warning:: + + ``torch.scan`` is a prototype feature in PyTorch. You may run into miscompiles. + Read more about feature classification at: + https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + Args: + combine_fn (Callable): A binary callable with type ``(Tensor, Tensor) -> (Tensor, Tensor)``, + or if xs is a pytree ``(pytree, pytree) -> (pytree, pytree)``. + The first input to ``combine_fn`` is the previous or initial scan carry + and the second input element to ``combine_fn`` is a slice of the input along dim. + The first output element of ``combine_fn`` is the next scan carry + and the second output of ``combine_fn`` represents a slice of the output. + This function must be pure, i.e., no lifted arguments are supported at the moment + and may not have any side effects. + init (torch.Tensor or pytree with tensor leaves): The initial scan carry, a tensor, or nested pytree of tensors. + The ``init`` is expected to have the same pytree structure as the first output element (i.e. carry) + of ``combine_fn``. + xs (torch.Tensor or pytree with tensor leaves or None): The input tensor, or nested pytree of tensors. + May be ``None`` when ``length`` is provided, in which case ``combine_fn`` receives ``None`` as ``x`` + each step (counter-loop mode). + + Keyword Args: + dim (int): the dimension to scan over, default 0. + reverse (bool): A boolean stating if the scan should be reversed with respect to ``dim``, default ``False``. + length (int or None): Optional number of scan iterations, default ``None``. + When ``xs`` has tensor leaves, ``length`` is optional; if given it must equal + ``xs.shape[dim]`` and serves only as a consistency check (no constraint when + ``length`` is ``None``). When ``xs`` has no leaves (``None`` or empty pytree), + ``length`` drives the number of iterations and ``combine_fn`` receives + ``x=None`` each step. ``length=0`` with no xs tensors is supported in + eager mode only; it is not supported under ``torch.compile``. + + Returns: + final_carry (torch.Tensor or pytree with tensor leaves), + the final carry of the scan operation with same pytree structure as init. + out (torch.Tensor or pytree with tensor leaves), + each tensor leaf is a stacked output along first dim, where each slice is the output of a scan iteration. + If the scan dimension has size 0, ``final_carry`` equals ``init`` unchanged and each output leaf has + size 0 along ``dim``. The gradient of ``final_carry`` with respect to ``init`` is the identity + (not zero), since the body is never called and the carry passes through untouched. + + Restrictions: + - The combine_fn shouldn't have any aliasing between input-input, input-output, and output-output. E.g. return a view + or the same tensor as input is not supported. As a workaround, can clone the output to avoid aliasing. + + - The combine_fn shouldn't mutate any inputs. We'll remove the mutation restriction for inference soon. Please file an issue + if you input mutation support for training is needed. + + - The combine_fn's init carry should match the next_carry in pytree structure and in tensor metadata. + + Example:: + + def add(x: torch.Tensor, y: torch.Tensor): + next_carry = y = x + y + # clone the output to avoid output-output aliasing + return next_carry, y.clone() + + + i0 = torch.zeros(1) + xs = torch.arange(5) + # returns torch.tensor([10.]), torch.tensor([[0], [1.], [3.], [6.], [10.]]) + last_carry, cumsum = scan(add, init=i0, xs=xs) + + + """ + # The reason we flatten init and xs before calling into dynamo is that + # we want to create a consistent input ordering for combine_fn + # and we also want to the input ordering matches the output ordering. + leaves_init, spec_init = pytree.tree_flatten(init) + leaves_xs_orig, spec_xs = pytree.tree_flatten(xs) + + # Determine whether xs carries any tensor data. + xs_has_tensors = any(isinstance(l, torch.Tensor) for l in leaves_xs_orig) + + # short-cuts + if length is not None: + if isinstance(length, bool) or not isinstance(length, int) or length < 0: + raise RuntimeError( + f"scan() length must be a non-negative integer, got {length!r}" + ) + + if not xs_has_tensors: + if length == 0: + if torch.compiler.is_dynamo_compiling(): + # TODO: Resolve this in a follow-up PR + raise RuntimeError( + "scan() with length=0 and no xs tensors is not supported under torch.compile" + ) + return init, _build_empty_output_for_length_zero(combine_fn, init) + + # No real xs: fabricate a length-N dummy purely as an iteration counter. + # the wrapped combine_fn below discards each slice and passes x=None to the body. + leaves_xs_orig = [torch.zeros(length, dtype=torch.int64)] + spec_xs = pytree.tree_structure(None) + _user_combine_fn = combine_fn + + def combine_fn(carry, _ignored): # noqa: E306 + return _user_combine_fn(carry, None) + elif not xs_has_tensors: + return init, [] + + def _validate_input(cfn, lxs, linit, d, r, l): + # Basic arguments check + if not callable(cfn): + raise RuntimeError(f"Combine_fn must be a callable, but got {cfn}") + if not isinstance(d, int): + raise RuntimeError("Dim must be an int, but got " + str(type(d))) + if not isinstance(r, bool): + raise RuntimeError("Reverse must be a bool, but got " + str(type(r))) + + if l is not None and xs_has_tensors and lxs[0].shape[d] != l: + raise RuntimeError( + f"scan() length={l} does not match xs size along dim={d}: " + f"{lxs[0].shape[d]}" + ) + + # Checks for init + if len(linit) == 0: + raise RuntimeError("scan() operator requires init leaves.") + for x in linit: + if not isinstance(x, torch.Tensor): + raise RuntimeError(f"All init leaves must be a Tensor but got {x}") + + # Checks for xs + for x in lxs: + if not isinstance(x, torch.Tensor): + raise RuntimeError(f"All xs leaves must be a Tensor but got {x}") + if any(x.ndim <= d for x in lxs): + raise RuntimeError("All xs leaves must have at least 'dim + 1' dimensions") + if any(x.shape[d] != lxs[0].shape[d] for x in lxs[1:]): + raise RuntimeError("All xs leaves must have the same scan dimension size") + + ndim = leaves_xs_orig[0].ndim + dim = utils.canonicalize_dim(ndim, dim) + + _validate_input(combine_fn, leaves_xs_orig, leaves_init, dim, reverse, length) + + # Move scan dim to 0 and always perform scan on dim 0 + leaves_xs = [] + for elem in leaves_xs_orig: + leaves_xs.append(torch.movedim(elem, dim, 0) if dim != 0 else elem) + + if reverse: + leaves_xs = [torch.flip(elem, [0]) for elem in leaves_xs] + + # TODO: Support _inductor lowering + # TODO: Unify handling of pytrees for control flow ops, such as cond, while_loop, etc. + + combine_fn = functools.partial( + wrap_combine_fn_flat, + combine_fn=combine_fn, + spec_init=spec_init, + spec_xs=spec_xs, + num_init_leaves=len(leaves_init), + num_inp_leaves=len(leaves_xs), + ) + + def run_flattened_scan(combine_fn, leaves_init, leaves_xs): + return scan_op(combine_fn, leaves_init, leaves_xs, ()) + + carry, out = _maybe_compile_and_run_fn( + run_flattened_scan, + combine_fn, + leaves_init, + leaves_xs, + ) + + if reverse: + out = pytree.tree_map(lambda elem: elem.flip([0]), out) + + # Move the scan dimension from 0 back to the user-specified `dim`. + if dim != 0: + out = pytree.tree_map( + lambda elem: torch.movedim(elem, 0, dim) if dim < elem.ndim else elem, + out, + ) + + return carry, out + + +class ScanOp(HigherOrderOperator): + def __init__(self): + super().__init__("scan") + + def __call__( + self, + combine_fn, + init, + xs, + additional_inputs, + *, + mutated_arg_indices: str = "", + ): + # There is currently an issue that the ScanOp is sometimes called with + # the additional_inputs being a list. See https://github.com/pytorch/pytorch/issues/145785 + # Once this issue is resolved, the assertion should only allow tuples + # and the tuple cast should be removed + if not isinstance(additional_inputs, (tuple, list)): + raise AssertionError( + f"additional_inputs must be a tuple or list, got {type(additional_inputs)}" + ) + additional_inputs = ( + tuple(additional_inputs) + if isinstance(additional_inputs, list) + else additional_inputs + ) + validate_subgraph_args_types(additional_inputs) + kwargs = {} + if mutated_arg_indices: + kwargs["mutated_arg_indices"] = mutated_arg_indices + # pyrefly: ignore [missing-attribute] + return super().__call__(combine_fn, init, xs, additional_inputs, **kwargs) + + # pyrefly: ignore [bad-override] + def gen_schema( + self, combine_fn, init, xs, additional_inputs, mutated_arg_indices="" + ): + from torch._higher_order_ops.schema import HopSchemaGenerator + + all_inputs = tuple( + list(init) + + [ + torch.empty_strided( + x.shape[1:], + x.stride()[1:], + dtype=x.dtype, + device=x.device, + requires_grad=x.requires_grad, + ) + for x in xs + ] + + list(additional_inputs) + ) + combine_gm = materialize_as_graph(combine_fn, all_inputs) + + # Mutation semantics for scan: + # - additional_inputs is mutable: loop-invariant tensor identity + # across sequential iterations, same semantics as while_loop's + # additional_inputs (CUDA-graph-friendly lifted / pre-allocated + # buffers such as KV caches or workspace scratch). + # - init is NOT mutable: init is only the *initial* carry, + # thus an in-place update to init only affects step 0. + # - xs is NOT mutable: each iteration sees a fresh, storage-disjoint + # slice (xs[t] and xs[t+1] share no storage), so a mutation on + # xs[t] cannot be observed by iteration t+1. The only externally- + # observable effect is "write-back to xs's t-th slice", which is + # already expressible via the ys output path at no extra cost. + # If xs-like in-place updates are required, pass the buffer via + # additional_inputs and index into it inside combine_fn. + outputs = get_graph_output_example_values(combine_gm) + mutated_set = ( + {int(i) for i in mutated_arg_indices.split(",") if i} + if mutated_arg_indices + else set() + ) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("combine_fn", combine_gm) + + for idx, arg in enumerate(init): + schema_gen.add_arg(f"init{idx}", arg) + + for idx, arg in enumerate(xs): + schema_gen.add_arg(f"xs{idx}", arg) + + offset = len(init) + len(xs) + for idx, arg in enumerate(additional_inputs): + schema_gen.add_arg( + f"additional_input{idx}", + arg, + is_mutated=(offset + idx) in mutated_set, + ) + + for out in outputs: + schema_gen.add_output(out) + + schema_gen.add_schema_tree_spec(combine_fn, init, xs, additional_inputs) + return schema_gen.gen_schema() + + +scan_op = ScanOp() + + +def generic_scan(operator, init, xs, dim=0, additional_inputs=()): + def _scan(init, xs): + """Perform scan on `elems` using `elems_init.""" + carry = init + if len(xs) == 0: + return carry, [] + + num_elems = xs[0].shape[dim] + num_init_leaves = len(init) + + proto_xs = [first_slice_copy(x, dim) for x in xs] + + # Process element 0 to infer output shapes for pre-allocation + # AND produce the first real result in a single call. The previous + # approach used first_slice_copy() for shape inference and then + # re-processed element 0 in the main loop, calling the operator + # num_elems+1 times. That extra invocation is incorrect for + # operators with side effects. + carry, out_0 = _extract_carry_and_out( + call_operator( + operator, + *carry, + *proto_xs, + *additional_inputs, + ), + num_init_leaves, + ) + + out_tensor_mask = get_tensor_mask(out_0) + out_0_masked = mask_list(out_tensor_mask, out_0) + + # Pre-allocate + # outs -> Output matrix + # idxs -> Index matrix for scatter_ + # out: (num_elems, M, N, ...) + # idx: (1, M, N) + outs = [ + torch.empty( + [num_elems] + list(e.size()), + dtype=e.dtype, + device=e.device, + ) + for e in out_0_masked + ] + idxs = [ + torch.ones_like(e, dtype=torch.int64).unsqueeze(0) for e in out_0_masked + ] + + if num_elems == 0: + outs_expanded = [ + outs.pop(0) if out_m else None for out_m in out_tensor_mask + ] + return (*init, *outs_expanded) + + def store_out_in_outs(out, ind): + # Store the intermediate out in the outs matrix + for o, x, idx in zip(outs, out, idxs): + # o: (num_elems, M, N ...) + # x: (M, N, ...) -> (1, M, N) + # ind * idx: (1, M, N,) with values to be ind + # essentially: o[ind][n][k] = x[0][n][k] + o.scatter_(0, ind * idx, x.unsqueeze(0)) + + # Store element 0's result, then continue from element 1. + store_out_in_outs(out_0_masked, 0) + + for i in range(1, num_elems): + carry, out = _extract_carry_and_out( + call_operator( + operator, + *carry, + *[elem.select(dim, i) for elem in xs], + *additional_inputs, + ), + num_init_leaves, + ) + + store_out_in_outs(mask_list(out_tensor_mask, out), i) + + # Expand outs with None depending on the tensor mask of the output + outs_expanded = [outs.pop(0) if out_m else None for out_m in out_tensor_mask] + + return (*carry, *outs_expanded) + + scans = _scan(init, xs) + return scans + + +def trace_scan( + proxy_mode, + func_overload, + combine_fn: Callable, + init: list[torch.Tensor], + xs: list[torch.Tensor], + additional_inputs: tuple[torch.Tensor], + mutated_arg_indices: str = "", +): + from torch._dynamo.utils import clone_input + + with disable_proxy_modes_tracing(): + sample_inits = [clone_input(x_init) for x_init in init] + sample_inputs = [first_slice_copy(x) for x in xs] + sample_additional_inputs = [ + clone_input(x) if isinstance(x, torch.Tensor) else x + for x in additional_inputs + ] + combine_graph = reenter_make_fx(combine_fn)( + *sample_inits, *sample_inputs, *sample_additional_inputs + ) + + outputs = None + for node in combine_graph.graph.nodes: + if node.op == "output": + if outputs is not None: + raise AssertionError("found multiple output nodes in combine_graph") + if len(node.args) != 1: + raise AssertionError( + f"expected output node to have 1 arg, got {len(node.args)}" + ) + outputs = node.args[0] + + if outputs is None: + raise AssertionError("no output node found in combine_graph") + + carry, output = _extract_carry_and_out(outputs, len(init)) + init_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [ + i.clone() for i in init + ] + carry_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [ + c.meta["val"] for c in carry + ] + check_meta_consistency( + init_fake_tensors, carry_fake_tensors, "init", "carry", include_contiguity=False + ) + + _, combine_graph_name = unique_graph_id(proxy_mode, prefix="scan_combine_graph") + + proxy_mode.tracer.root.register_module(combine_graph_name, combine_graph) + + args = (combine_graph, init, xs, additional_inputs) + kwargs = {} + if mutated_arg_indices: + kwargs["mutated_arg_indices"] = mutated_arg_indices + + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, kwargs, name="scan" + ) + + with disable_proxy_modes_tracing(): + scan_length = xs[0].shape[0] + fake_carry, fake_outputs = _extract_carry_and_out( + [o.meta["val"] if o is not None else None for o in outputs], len(init) + ) + for t in fake_outputs: + if not isinstance(t, torch.Tensor) and t is not None: + raise AssertionError( + f"Expected leaf to be a Tensor or None, got {type(t)}" + ) + out = ( + *fake_carry, + *( + stack_y(t, scan_length) if isinstance(t, torch.Tensor) else t + for t in fake_outputs + ), + ) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@scan_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def scan_op_dense(combine_fn, init, xs, additional_inputs, mutated_arg_indices=""): + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + return generic_scan(combine_fn, init, xs, additional_inputs=additional_inputs) + + +class ScanAutogradOp(torch.autograd.Function): + """ + NOTE: [scan partial grad handling] + If any element of init, of xs, of the outputs or of the additional_inputs does not require gradients, + i.e., requires_grad=False, there will be still gradients returned for those elements, + but those gradients will be a tensor filled with zeros of the same shape as the element itself. + + A special case are additional_inputs that are not tensors. Such inputs can occur for example with symbolic tracing, + where the shape symbol (SymInt) becomes an additional_input. + For such cases, we compute a ``additional_inputs_tensor_mask``, which is True for elements of additional_inputs + that are tensors and False otherwise. Gradients of additional_inputs are only accumulated if this mask is True, + otherwise, the value of initial_g_additional_inputs is passed, which is None for non-Tensor values. + """ + + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + hop_partitioned_graph, + n_init, + n_xs, + n_additional_inputs, + *operands, + ): + init, xs, additional_inputs = split_into_chunks( + operands, [n_init, n_xs, n_additional_inputs] + ) + ctx._scan_impl = ScanAutogradImpl( + hop_partitioned_graph, init, xs, additional_inputs + ) + with torch._C._AutoDispatchBelowAutograd(): + return ctx._scan_impl.call_forward() + + @staticmethod + def backward(ctx, *grad_fw_outputs): + return ( + None, + None, + None, + None, + *ctx._scan_impl.call_backward(*grad_fw_outputs), + ) + + +class ScanForwardIntermediatesHandlingPolicy(enum.Enum): + """ + Partitioner can add intermediates to the output of original graph. + These intermediates fall into 4 categories and we want to have different policies for handling them by + modifying the graph: + + CLONE: we clone the intermediate when it is a carried input (i.e. init). In this case, this carry will be + replaced with new values at each forward step so we need to clone the carry as part of return (i.e. ys) + so as to remove the aliasing and that each step's intermediate will be stacked together and saved in backward. + + REMOVE_XS: we remove the intermediate from output when it is part of xs. Since xs is read-only, in this case, + we can directly save them for backward to use. + + REMOVE_ADDITIONAL_INPUTS: we remove the intermediate from output when it is part of additional_inputs. additional_inputs + are also read-only in each step, we can directly save them for backward to use. We differentiate XS and ADDITIONAL_INPUTS + so that we could have different treatment for them in backward. In backward, we need to put xs intermediates in carry but + put additional_inputs as backward scan's additional_inputs. + + KEEP: this corresponds to a real intermediate tensor operations' output. It varies at each forward step, we could just keep + it as part of ys. + + """ + + KEEP = 0 + CLONE = 1 + REMOVE_XS = 2 + REMOVE_ADDITIONAL_INPUTS = 3 + + +class ScanAutogradImpl: + """ + Wraps over partitioned graph and encapsulates scan-specific implementation details + """ + + def __init__( + self, hop_partitioned_graph: HopPartitionedGraph, init, xs, additional_inputs + ): + self.hop_partitioned_graph = hop_partitioned_graph + self.init = init + self.xs = xs + self.additional_inputs = additional_inputs + self.forward_intermediates_handling_policies: list[ + ScanForwardIntermediatesHandlingPolicy + ] = [] + self.saved_fw_xs: list[Any] = [] + self.saved_fw_additional_inputs: list[Any] = [] + self.saved_intermediates: list[Any] = [] + self.fw_spec = pytree.tree_flatten((init, xs, additional_inputs))[1] + self._optimize_forward_intermediates() + self._break_bw_input_output_aliasing() + + def _insert_clone( + self, need_copy_node: torch.fx.Node, output_node: torch.fx.Node + ) -> torch.fx.Node: + graph: torch.fx.Graph = output_node.graph + with graph.inserting_before(output_node): + clone_node = graph.call_function( + torch.ops.aten.clone.default, + args=(need_copy_node,), + ) + clone_node.meta = ( + need_copy_node.meta.copy() if hasattr(need_copy_node, "meta") else {} + ) + return clone_node + + def _break_bw_input_output_aliasing(self) -> None: + """ + The min-cut partitioner can produce a ``bw_gm`` whose output aliases + an input placeholder. The most common case is a direct placeholder + return (e.g. when an input doesn't require grad and its gradient is + ``zeros_like(input)`` saved as a forward intermediate), but transitive + aliases (views, ``_unsafe_view``, slices, ...) can hit the same path. + + When ``bw_gm`` is wrapped as the per-step backward inside ``scan_op``, + any input returned as an output violates ``scan_op``'s aliasing-free + invariant and surfaces as ``UncapturedHigherOrderOpError`` under + dynamo. Clone bw_gm outputs that are direct placeholders or whose + ``meta['val']`` shares storage with any placeholder. + """ + from torch.multiprocessing.reductions import StorageWeakRef + + bw_gm = self.hop_partitioned_graph.bw_gm + bw_output_node = next(iter(bw_gm.graph.find_nodes(op="output"))) + if len(bw_output_node.args) != 1: + raise AssertionError( + f"expected bw_gm output to have 1 arg, got {len(bw_output_node.args)}" + ) + bw_outputs = bw_output_node.args[0] + + ph_storages: set = set() + for ph in bw_gm.graph.find_nodes(op="placeholder"): + val = ph.meta.get("val", None) if hasattr(ph, "meta") else None + if isinstance(val, torch.Tensor): + ph_storages.add(StorageWeakRef(val._typed_storage())) + + def _aliases_placeholder(node: torch.fx.Node) -> bool: + if node.op == "placeholder": + return True + val = node.meta.get("val", None) if hasattr(node, "meta") else None + if isinstance(val, torch.Tensor): + return StorageWeakRef(val._typed_storage()) in ph_storages + return False + + new_bw_outputs = [] + rewrote = False + for out in bw_outputs: + if isinstance(out, torch.fx.Node) and _aliases_placeholder(out): + new_bw_outputs.append(self._insert_clone(out, bw_output_node)) + rewrote = True + else: + new_bw_outputs.append(out) + if rewrote: + bw_output_node.args = (tuple(new_bw_outputs),) + bw_gm.graph.lint() + bw_gm.recompile() + + def _optimize_forward_intermediates(self): + """ + We optimize the forward intermediates by categorize forward intermediates into categories + and construct a ScanForwardIntermediatesHandlingPolicy for them + + """ + if logger.isEnabledFor(logging.DEBUG): + logger.debug( + "Need remove aliasing in fw_gm:\n%s", + self.hop_partitioned_graph.fw_gm.print_readable(print_output=False), + ) + + fw_gm = self.hop_partitioned_graph.fw_gm + fw_all_outputs = _find_hop_subgraph_outputs(fw_gm) + phs = list(fw_gm.graph.find_nodes(op="placeholder")) + fw_outputs = fw_all_outputs[: self.hop_partitioned_graph.n_fw_outputs] + fw_intermediates = fw_all_outputs[self.hop_partitioned_graph.n_fw_outputs :] + + init_phs, xs_phs, additional_inputs_phs = pytree.tree_unflatten( + phs, self.fw_spec + ) + init_node_set, xs_node_set, addi_node_set = ( + set(init_phs), + set(xs_phs), + set(additional_inputs_phs), + ) + + if len(self.forward_intermediates_handling_policies) != 0: + raise AssertionError( + "forward_intermediates_handling_policies should be empty" + ) + if len(self.saved_fw_xs) != 0: + raise AssertionError("saved_fw_xs should be empty") + if len(self.saved_fw_additional_inputs) != 0: + raise AssertionError("saved_fw_additional_inputs should be empty") + intermediate_idx_to_ph_idx = {} + ph_idx = {ph: i for i, ph in enumerate(phs)} + for i, out in enumerate(fw_intermediates): + if out in init_node_set: + self.forward_intermediates_handling_policies.append( + ScanForwardIntermediatesHandlingPolicy.CLONE + ) + intermediate_idx_to_ph_idx[i] = ph_idx[out] + elif out in xs_node_set: + self.forward_intermediates_handling_policies.append( + ScanForwardIntermediatesHandlingPolicy.REMOVE_XS + ) + intermediate_idx_to_ph_idx[i] = ph_idx[out] + elif out in addi_node_set: + self.forward_intermediates_handling_policies.append( + ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS + ) + intermediate_idx_to_ph_idx[i] = ph_idx[out] + else: + self.forward_intermediates_handling_policies.append( + ScanForwardIntermediatesHandlingPolicy.KEEP + ) + + new_output_node = [] + real_graph_inputs = ( + list(self.init) + list(self.xs) + list(self.additional_inputs) + ) + fw_output_node = next(iter(fw_gm.graph.find_nodes(op="output"))) + for intermediate_idx, (node, policy) in enumerate( + zip(fw_intermediates, self.forward_intermediates_handling_policies) + ): + if policy == ScanForwardIntermediatesHandlingPolicy.CLONE: + new_output_node.append(self._insert_clone(node, fw_output_node)) + elif policy == ScanForwardIntermediatesHandlingPolicy.REMOVE_XS: + if intermediate_idx not in intermediate_idx_to_ph_idx: + raise AssertionError( + f"intermediate_idx {intermediate_idx} not in intermediate_idx_to_ph_idx" + ) + inp_idx = intermediate_idx_to_ph_idx[intermediate_idx] + self.saved_fw_xs.append(real_graph_inputs[inp_idx]) + elif ( + policy + == ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS + ): + if intermediate_idx not in intermediate_idx_to_ph_idx: + raise AssertionError( + f"intermediate_idx {intermediate_idx} not in intermediate_idx_to_ph_idx for REMOVE_ADDITIONAL_INPUTS" + ) + inp_idx = intermediate_idx_to_ph_idx[intermediate_idx] + self.saved_fw_additional_inputs.append(real_graph_inputs[inp_idx]) + else: + new_output_node.append(node) + + fw_output_node.args = (tuple(fw_outputs) + tuple(new_output_node),) + fw_gm.graph.lint() + fw_gm.recompile() + + if logger.isEnabledFor(logging.DEBUG): + logger.debug( + "after removing aliasing:\n%s", fw_gm.print_readable(print_output=False) + ) + + def call_forward(self): + fw_outputs_and_intermediates: tuple[Any] = scan_op( + self.hop_partitioned_graph.fw_gm, self.init, self.xs, self.additional_inputs + ) # type: ignore[return-type] + fw_outs = fw_outputs_and_intermediates[ + : self.hop_partitioned_graph.n_fw_outputs + ] + saved_intermediates = fw_outputs_and_intermediates[ + self.hop_partitioned_graph.n_fw_outputs : + ] + if len(self.saved_intermediates) != 0: + raise AssertionError( + "saved_intermediates should be empty before call_forward" + ) + self.saved_intermediates.extend(saved_intermediates) + return tuple(fw_outs) + + def call_backward(self, *grad_fw_outputs): + """ + Recall that fw_outputs = (*carry, *ys), bw_gm takes in (*fw_intermediates, *grad_carry, *grad_ys) + and returns (*grad_init, *grad_xs, *grad_additional_inputs) + The backward is a reversed scan that can be constructed as follows: + + grad_additional_inputs = torch.zeros_like(additional_inputs) + bw_init = (grad_carry, grad_additional_inputs) + bw_xs = (fw_intermediates, grad_ys) + grad_init, grad_additional_inputs, grad_xs = scan( + combine_fn, + bw_init, + bw_xs, + reverse = True + ) + , where combine_fn is defined as follows: + + def combine_fn(bw_init, bw_xs): + grad_carry, grad_additional_inputs = bw_init + fw_intermediates, grad_y = bw_xs + nxt_grad_carry, grad_x, nxt_grad_additional_inputs = bw_gm(*fw_intermediates, *grad_carry, *grad_y) + return (nxt_grad_carry, grad_additional_inputs + nxt_grad_additional_inputs), grad_x + + Note that grad_additional_inputs is accumulated with add, grad_carry is carried over to next iteration and + grad_x is the ys output, which will be stacked together after the loop and will have the same shape as xs. + """ + fw_policy = self.forward_intermediates_handling_policies + saved_intermediates = self.saved_intermediates + saved_fw_xs = self.saved_fw_xs + saved_fw_additional_inputs = self.saved_fw_additional_inputs + + n_carry = len(self.init) + + grad_carry, grad_ys = grad_fw_outputs[:n_carry], grad_fw_outputs[n_carry:] + additional_inputs_tensor_masks = [ + bool(isinstance(t, torch.Tensor)) for t in self.additional_inputs + ] + grad_additional_inputs = [ + torch.zeros_like(t) + for t in filter_with_masks( + self.additional_inputs, additional_inputs_tensor_masks + ) + ] + + bw_init = [grad_carry, grad_additional_inputs] + bw_xs = [ + grad_ys, + saved_fw_xs, + saved_intermediates, + ] + bw_additional_inputs = saved_fw_additional_inputs + + _, flat_spec = pytree.tree_flatten((bw_init, bw_xs, bw_additional_inputs)) + + grad_spec = None + + def bw_single_step_wrapper(*args): + bw_init, bw_xs, bw_additional_inputs = pytree.tree_unflatten( + args, flat_spec + ) + grad_carry, grad_additional_inputs = bw_init + grad_y, saved_fw_xs, saved_intermediates = bw_xs + saved_fw_additional_inputs = bw_additional_inputs + + fw_intermediates = [] + xs_it = iter(saved_fw_xs) + carry_it = iter(saved_intermediates) + addi_it = iter(saved_fw_additional_inputs) + for policy in fw_policy: + if policy in ( + ScanForwardIntermediatesHandlingPolicy.CLONE, + ScanForwardIntermediatesHandlingPolicy.KEEP, + ): + fw_intermediates.append(next(carry_it)) + elif policy == ScanForwardIntermediatesHandlingPolicy.REMOVE_XS: + fw_intermediates.append(next(xs_it)) + elif ( + policy + == ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS + ): + fw_intermediates.append(next(addi_it)) + else: + raise RuntimeError(f"Unknown policy: {policy}") + + grad_fw_outputs = (*grad_carry, *grad_y) + + flat_out = self.hop_partitioned_graph.bw_gm( + *fw_intermediates, + *grad_fw_outputs, + ) + + next_grad_carry, grad_xs, grad_addi = split_into_chunks( + flat_out, # type: ignore[arg-type] + [len(self.init), len(self.xs), len(self.additional_inputs)], + ) + + nonlocal grad_spec + flat_grads, grad_spec = pytree.tree_flatten( + ( + next_grad_carry, + [ + prev + cur + for prev, cur in zip( + grad_additional_inputs, + filter_with_masks( + grad_addi, additional_inputs_tensor_masks + ), + ) + ], + grad_xs, + ) + ) + return flat_grads + + single_step_bw_xs = pytree.tree_map(first_slice_copy, bw_xs) + bw_single_step_gm = materialize_as_graph( + bw_single_step_wrapper, + tuple( + pytree.tree_flatten((bw_init, single_step_bw_xs, bw_additional_inputs))[ + 0 + ] + ), + ) + + flat_grads = scan_op( + bw_single_step_gm, + pytree.tree_flatten(bw_init)[0], + # TODO: torch.flip copies the tensor, we should optimize it away + [torch.flip(x, (0,)) for x in pytree.tree_flatten(bw_xs)[0]], + pytree.tree_flatten(bw_additional_inputs)[0], + ) + if grad_spec is None: + raise AssertionError("grad_spec must not be None after scan_op") + grad_init, grad_additional_inputs, grad_xs = pytree.tree_unflatten( + flat_grads, grad_spec + ) + return ( + *grad_init, + *[torch.flip(elem, (0,)) for elem in grad_xs], + *fill_none_with_masks( + grad_additional_inputs, additional_inputs_tensor_masks + ), + ) + + +@scan_op.py_autograd_impl +def scan_autograd(combine_fn, init, xs, additional_inputs, mutated_arg_indices=""): + with disable_proxy_modes_tracing(): + # If init was passed in with requires_grad=False, AOT joint creation drops it from + # grad_primals and zero-fills, severing the carry chain and silently + # zeroing gradients that should reach closed-over additional_inputs from + # earlier steps. Thus, we temporarily flip requires_grad on the init tensors + # during tracing and restore it afterwards; this only affects the traced + # graphs, not the operands passed to apply. init elements are leaves. + flipped = [ + t + for t in init + if (t.dtype.is_floating_point or t.dtype.is_complex) and not t.requires_grad + ] + try: + for t in flipped: + t.requires_grad_(True) + hop_partitioned_graph: HopPartitionedGraph = ( + HopGraphMinCutPartitioner.create_partitioned_graph( + combine_fn, + (*init, *[first_slice_copy(x) for x in xs], *additional_inputs), + always_recompute_complex_exprs=True, + ) + ) + finally: + for t in flipped: + t.requires_grad_(False) + + return ScanAutogradOp.apply( + hop_partitioned_graph, + len(init), + len(xs), + len(additional_inputs), + *init, + *xs, + *additional_inputs, + ) + + +@scan_op.py_impl(ProxyTorchDispatchMode) +def scan_proxy_mode( + mode, combine_fn, init, xs, additional_inputs, mutated_arg_indices="" +): + return trace_scan( + mode, + scan_op, + combine_fn, + init, + xs, + additional_inputs, + mutated_arg_indices=mutated_arg_indices, + ) + + +@scan_op.py_impl(FakeTensorMode) +def scan_fake_tensor_mode( + mode, combine_fn, init, xs, additional_inputs, mutated_arg_indices="" +): + with mode: + scan_length = xs[0].shape[0] + carry, outputs = _extract_carry_and_out( + combine_fn( + *init, + *[first_slice_copy(inp) for inp in xs], + *additional_inputs, + ), + len(init), + ) + for t in outputs: + if not isinstance(t, torch.Tensor) and t is not None: + raise AssertionError( + f"Expected leaf to be a Tensor or None, got {type(t)}" + ) + out = ( + *carry, + *( + stack_y(t, scan_length) if isinstance(t, torch.Tensor) else t + for t in outputs + ), + ) + return out + + +@scan_op.py_functionalize_impl +def scan_functionalize( + ctx, combine_fn, init, xs, additional_inputs, mutated_arg_indices="" +): + from torch._higher_order_ops.utils import ( + _check_alias_and_mutation, + _maybe_run_with_interpreter, + ) + + if hasattr(ctx, "mode"): + hop_instance = HopInstance.create( + scan_op, + combine_fn, + init, + xs, + additional_inputs, + mutated_arg_indices=mutated_arg_indices, + ) + if can_auto_functionalize(hop_instance): + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + tuple( + pytree.tree_flatten((combine_fn, init, xs, additional_inputs))[0] + ), + {}, + ) + + unwrapped_xs = ctx.unwrap_tensors(xs) + unwrapped_init = ctx.unwrap_tensors(init) + unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs) + + with ctx.redispatch_to_next(): + functional_combine_fn = ctx.functionalize( + _maybe_run_with_interpreter(combine_fn) + ) + sample_unwrapped_xs_sliced = ( + [first_slice_copy(inp) for inp in unwrapped_xs] + if len(unwrapped_xs) > 0 + else [None] + ) + sample_inputs = list( + itertools.chain( + unwrapped_init, + sample_unwrapped_xs_sliced, + unwrapped_additional_inputs, + ) + ) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + _check_alias_and_mutation(combine_fn, sample_inputs, "scan", pre_dispatch) + ret = scan_op( + functional_combine_fn, + unwrapped_init, + unwrapped_xs, + unwrapped_additional_inputs, + mutated_arg_indices=mutated_arg_indices, + ) + return ctx.wrap_tensors(ret) + + +@scan_op.py_impl(torch._C._functorch.TransformType.Vmap) +def scan_batch_rule( + interpreter, combine_fn, init, xs, additional_inputs, mutated_arg_indices="" +): + unbatched_args, in_dims = unwrap_batched( + (init, xs, additional_inputs), interpreter.level() + ) + # move to last dim to not interfere with scan's batching + unbatched_init, unbatched_xs, unbatched_additional_inputs = pytree.tree_map( + lambda x, bdim: x.movedim(bdim, -1) if bdim is not None else x, + unbatched_args, + in_dims, + ) + after_move_dims = tuple( + pytree.tree_flatten( + pytree.tree_map(lambda x: -1 if x is not None else None, in_dims) + )[0] + ) + + with interpreter.lower(): + out_dims = None + + def wrapper(*args): + nonlocal out_dims + outputs, per_slice_out_dims = restore_vmap( + combine_fn, + after_move_dims, + interpreter.batch_size(), + interpreter.randomness(), + )(*args) + # Note: outputs are not batched, we just move the batch dim to the end + # this is to avoid it interfering with scan's batching + outputs = tuple( + pytree.tree_map( + lambda out, out_bdim: out.movedim(out_bdim, -1) + if out_bdim is not None + else out, + outputs, + per_slice_out_dims, + ) + ) + out_dims = tuple( + pytree.tree_map( + lambda out_bdim: -1 if out_bdim is not None else None, + per_slice_out_dims, + ) + ) + return outputs + + op_kwargs = {} + if mutated_arg_indices: + op_kwargs["mutated_arg_indices"] = mutated_arg_indices + unwrapped_out = scan_op( + wrapper, + unbatched_init, + unbatched_xs, + unbatched_additional_inputs, + **op_kwargs, + ) + + if out_dims is None: + raise AssertionError("out_dims must not be None after scan_op") + batched_out = wrap_batched(unwrapped_out, out_dims, interpreter.level()) + return batched_out + + +# dense implementation for scan. Used for testing only. +def _fake_scan(combine_fn, init, xs=None, dim=0, reverse=False, length=None): + carry_leaves, carry_spec = pytree.tree_flatten(init) + inp_leaves, inp_spec = pytree.tree_flatten(xs) + xs_has_tensors = any(isinstance(l, torch.Tensor) for l in inp_leaves) + + if length is not None and not xs_has_tensors: + if length == 0: + return init, _build_empty_output_for_length_zero(combine_fn, init) + + _user_combine_fn = combine_fn + + def combine_fn(carry, _ignored): + return _user_combine_fn(carry, None) + + # Dummy length-N iteration counter; the wrapped combine_fn passes x=None. + inp_leaves = [torch.zeros(length, dtype=torch.int64)] + inp_spec = pytree.tree_structure(None) + xs_has_tensors = True + + if not xs_has_tensors: + return init, [] + result_flat = [] + carry = carry_leaves + op = reversed if reverse else lambda x: x + + _, dummy_out = combine_fn( + pytree.tree_unflatten(carry, carry_spec), + pytree.tree_unflatten( + [first_slice_copy(elem, dim) for elem in inp_leaves], + inp_spec, + ), + ) + dummy_out_leaves, dummy_out_spec = pytree.tree_flatten(dummy_out) + + for ind in op(range(inp_leaves[0].size(dim))): + xs = [elem.select(dim, ind) for elem in inp_leaves] + + carry, y = combine_fn( + pytree.tree_unflatten(carry, carry_spec), + pytree.tree_unflatten(xs, inp_spec), + ) + carry, _ = pytree.tree_flatten(carry) + y, _ = pytree.tree_flatten(y) + result_flat.append(y) + + results: list[torch.Tensor | None] = [] + for leaf_idx, leaf in enumerate(dummy_out_leaves): + if isinstance(leaf, torch.Tensor): + if len(result_flat) == 0: + stacked = torch.empty( + [0] + list(leaf.shape), dtype=leaf.dtype, device=leaf.device + ) + else: + stacked = torch.stack([e[leaf_idx] for e in op(result_flat)]) + results.append( + torch.movedim(stacked, 0, dim) if dim < stacked.ndim else stacked + ) + else: + if leaf is not None: + raise AssertionError( + f"Expected leaf to be a Tensor or None, got {type(leaf)}" + ) + results.append(leaf) + return ( + pytree.tree_unflatten(carry, carry_spec), + pytree.tree_unflatten(results, dummy_out_spec), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/schema.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..e0e80774ddd1af103bf9f3b13e7bde611dbf8604 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/schema.py @@ -0,0 +1,323 @@ +import copy +from dataclasses import dataclass +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch.fx.node import Target + + +# Below is an implementation of generating FunctionSchema from example values. +# This is helpful for generating FunctionSchema for HigherOrderOperator, where +# we don't have a function to inspect and each call of the higher order operator +# would have different schema. +@dataclass(frozen=True, slots=True) +class HopArgumentInfo: + # Could give a name to the operand by default it's empty string. + name: str + example_value: Any + # Provide a default_value + default_value: Any + # Whether this argument gets mutated in the hop subgraph. + # For output, this should always be False + is_mutated: bool + kw_only: bool + + +class HopArgumentInfoGen: + @staticmethod + def from_example( + example_value: Any, + *, + name: str = "", + default_value: Any | None = None, + is_mutated: bool = False, + kw_only: bool = False, + ) -> HopArgumentInfo: + if default_value is not None: + if type(example_value) is not type(default_value): + raise AssertionError( + f"example_value type {type(example_value)} doesn't match default_value type: {type(default_value)}" + ) + + return HopArgumentInfo( + name=name, + example_value=example_value, + default_value=default_value, + is_mutated=is_mutated, + kw_only=kw_only, + ) + + +class CTypeGen: + convert_to_base_ty = { + int: torch._C.IntType.get(), + float: torch._C.FloatType.get(), + str: torch._C.StringType.get(), + bool: torch._C.BoolType.get(), + } + + # should return torch._C.JitType but that annotation is busted + @staticmethod + def from_example(obj: Any) -> Any: + import torch + + if isinstance(obj, torch.fx.GraphModule): + return torch._C.AnyType.get() + elif isinstance(obj, torch.SymInt): + return torch._C.SymIntType.get() + elif isinstance(obj, torch.SymBool): + return torch._C.SymBoolType.get() + elif isinstance(obj, torch.SymFloat): + return torch._C.FloatType.get() + elif isinstance(obj, (FakeScriptObject, pytree.TreeSpec)) or is_custom_class( + type(obj) + ): + return torch._C.PyObjectType.get() # pyrefly: ignore[missing-attribute] + return torch._C._jit_try_infer_type(obj).type() + + +class CArgumentGen: + @staticmethod + def from_hop_argument_info( + arg_idx: int, arg_info: HopArgumentInfo, is_output: bool = False + ) -> Any: + typ = CTypeGen.from_example(arg_info.example_value) + if is_output: + return torch._C.Argument("", typ, None, None, False, None) + + alias_set = set({f"alias::a{arg_idx}"}) if arg_info.is_mutated else set() + alias_info = torch._C._AliasInfo(arg_info.is_mutated, alias_set, alias_set) # type: ignore[attr-defined] + return torch._C.Argument( + arg_info.name, + typ, + None, + arg_info.default_value, + arg_info.kw_only, + alias_info, + ) + + +class HopSchemaGenerator: + def __init__(self, hop: torch._ops.HigherOrderOperator): + self.arg_infos: list[HopArgumentInfo] = [] + self.example_outputs: list[Any] = [] + self.schema_tree_spec: pytree.TreeSpec | None = None + self.hop = hop + + def add_arg( + self, + name: str, + example_value: Any, + default_value: Any | None = None, + is_mutated: bool = False, + kw_only: bool = False, + ) -> None: + if callable(example_value) and not is_custom_class(type(example_value)): + if not isinstance( + example_value, (torch.fx.GraphModule, torch._ops.OperatorBase) + ): + raise AssertionError( + "Expect callable to be a GraphModule or an OperatorBase. Please call materialize_as_graph first " + f"to turn callable arguments {example_value} into a GraphModule." + ) + _, flat_spec = pytree.tree_flatten(example_value) + if not flat_spec.is_leaf(): + raise RuntimeError( + f"example_value {example_value} is not a leaf node. " + "Please only add flattened inputs to the hop schema. " + "If you need some structure in the arguments, please" + "add_arg for flattened args one by one then " + "call add_schema_tree_spec to register the original pytree " + " spec of the args." + ) + + arg_info = HopArgumentInfoGen.from_example( + example_value=example_value, + name=name, + default_value=default_value, + is_mutated=is_mutated, + kw_only=kw_only, + ) + self.arg_infos.append(arg_info) + + def add_output(self, output: Any) -> None: + self.example_outputs.append(output) + + def add_schema_tree_spec(self, *args: Any, **kwargs: Any) -> None: + """schema tree spec is the tree spec from flattening all inputs to the hop with pytree.tree_flatten + Since torch.FunctionSchema only have proper mutation/alias support for flattened inputs, we need + to store the tree spec in order to reconstruct the inputs to the hop. + """ + self.schema_tree_spec = pytree.tree_flatten((args, kwargs))[1] + + def gen_schema(self) -> torch._C.FunctionSchema: + for i, arg_info in enumerate(self.arg_infos): + arg_spec = pytree.tree_flatten(arg_info.example_value)[1] + if not arg_spec.is_leaf() and self.schema_tree_spec is None: + raise RuntimeError( + f"example_value of arg_infos[{i}] is {arg_info.example_value}, which is not a leaf node. " + "Please call add_schema_tree_spec to add a schema tree spec first. " + "Or consider changing the hop's signature to only take flattened arguments." + ) + + return CFunctionSchemaGen.from_hop_argument_info( + str(self.hop), + self.arg_infos, + HopArgumentInfoGen.from_example(tuple(self.example_outputs), name="out"), + self.schema_tree_spec, + ) + + +class CFunctionSchemaGen: + """ + Note: [HigherOrderOperator schema generation] + Each invocation of a HigherOrderOperator will have a different schema. + For example, the schema of torch.cond varies depending on the true_fn and + false_fn. So we need a way to generate the schema for each invocation of a HOP. + + We want to enforce the following invariants for HOP's schema: + 1. Flattened inputs. There should be no pytree structure in it. + 2. Flattened outputs. Note even if the hop returns a single value, it should be wrapped as a tuple. + 3. No aliasing. This includes inp-inp aliasing, inp-out aliasing and out-out aliasing. + + By enforcing these invariants, we could make HOP's schema meets the requirement of schema parser + and makes hop easier to handle downstream. For example, suppose we have an invoke_quant_test HOP: + + class GraphModule(torch.nn.Module): + def forward(self, l_x_, l_y_): + subgraph_0 = self.subgraph_0 + invoke_quant_test = torch.ops.higher_order.invoke_quant_test(subgraph_0, l_x_, l_y_, scheme = 'nf4'); + + class subgraph_0(torch.nn.Module): + def forward(self, l_x_, l_y_): + add_ = l_x_.add_(1) + matmul = l_x_ @ l_y_ + sin = matmul.sin() + child = sin.cos() + child_1 = l_x_ + l_y_ + child_2 = l_x_ - l_y_ + child_3 = l_x_ @ l_y_ + return (child, child_1, child_2, child_3) + + By encoding the inputs of hop into a list of HopArgumentInfo and output as a single HopArgumentInfo, + we would get the following schema: + invoke_quant_test(Any arg0, Tensor(!) arg1, Tensor arg2, str scheme="\\"nf4\\"") -> (Tensor, Tensor, Tensor, Tensor) + """ + + @staticmethod + def from_hop_argument_info( + op_name: str, + inp_argument_info: list[HopArgumentInfo], + out_argument_info: HopArgumentInfo, + schema_tree_spec: pytree.TreeSpec | None, + ) -> Any: + args = [] + for i, arg_info in enumerate(inp_argument_info): + args.append(CArgumentGen.from_hop_argument_info(i, arg_info)) + + # NOTE: we want the output to always be a single argument with torch._C.TupleType. + if not isinstance(out_argument_info.example_value, tuple): + raise AssertionError( + f"expect out_argument_info's example_value to be a tuple but got {out_argument_info.example_value}" + ) + if out_argument_info.is_mutated: + raise AssertionError( + "out_argument_info.is_mutated should always be set to False." + ) + rets = None + if len(out_argument_info.example_value) == 1: + rets = [CArgumentGen.from_hop_argument_info(0, out_argument_info, True)] + else: + rets = [ + CArgumentGen.from_hop_argument_info( + i, + HopArgumentInfoGen.from_example( + name=f"out{i}", + example_value=val, + default_value=None, + is_mutated=False, + ), + is_output=True, + ) + for i, val in enumerate(out_argument_info.example_value) + ] + + return HopSchema( + op_name, + "", + args, + rets, + False, + False, + schema_tree_spec, + ) + + +class HopSchema(torch._C.FunctionSchema): + def __init__( + self, + name: str, + overload_name: str, + arguments: list[torch._C.Argument], + returns: list[torch._C.Argument], + is_vararg: bool, + is_varret: bool, + schema_tree_spec: pytree.TreeSpec | None, + ): + self.tree_spec = schema_tree_spec + self.is_vararg = is_vararg + self.is_varret = is_varret + super().__init__( + name, + overload_name, + arguments, + returns, + self.is_vararg, + self.is_varret, + ) + + def __deepcopy__(self, memo: Any) -> "HopSchema": + # Need to additionally copy the tree_spec since + # it's not a member of torch._C.FunctionSchema + return HopSchema( + self.name, + self.overload_name, + self.arguments, + self.returns, + self.is_vararg, + self.is_varret, + copy.deepcopy(self.tree_spec), + ) + + +def find_hop_schema( + gm: torch.fx.GraphModule, target: Target +) -> list[torch._C.FunctionSchema]: + schemas = [] + for node in gm.graph.find_nodes(op="call_function", target=target): + + def _get_example_value(node: torch.fx.Node) -> Any: + if node.op == "get_attr": + if not isinstance(node.target, str): + raise AssertionError( + f"expected node.target to be str for get_attr, got {type(node.target)}" + ) + return getattr(gm, node.target) + else: + return ( + node.meta["example_value"] + if "example_value" in node.meta + else node.meta["val"] + ) + + fake_args, fake_kwargs = pytree.tree_map_only( + torch.fx.Node, + _get_example_value, + (node.args, node.kwargs), + ) + schema = node.target.gen_schema(*fake_args, **fake_kwargs) + schemas.append(schema) + return schemas diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/strict_mode.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/strict_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..0257e3edd82879e65f16a6befcab8b2fed57cd43 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/strict_mode.py @@ -0,0 +1,92 @@ +# mypy: allow-untyped-defs + +import torch +import torch._subclasses.functional_tensor +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._functorch.utils import exposed_in +from torch._higher_order_ops.utils import autograd_not_implemented, register_fake +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + make_fx, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.utils._python_dispatch import _get_current_dispatch_mode + + +@exposed_in("torch") +def strict_mode(callable, operands): + if torch.compiler.is_dynamo_compiling(): + return strict_mode_op(callable, operands) + + from torch._higher_order_ops.utils import _hop_compile_and_call + + return _hop_compile_and_call(strict_mode_op, (callable, operands)) + + +class StrictMode(HigherOrderOperator): + def __init__(self): + super().__init__("strict_mode") + + def __call__(self, callable, operands): + # pyrefly: ignore [missing-attribute] + return super().__call__(callable, operands) + + +strict_mode_op = StrictMode() + + +@strict_mode_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def strict_mode_op_dense(callable, operands): + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + return callable(*operands) + + +strict_mode_op.py_autograd_impl( + autograd_not_implemented(strict_mode_op, deferred_error=True) +) + + +@strict_mode_op.py_impl(ProxyTorchDispatchMode) +def inner(mode, callable, operands): + return trace_strict_mode(mode, strict_mode_op, callable, operands) + + +def trace_strict_mode(mode, strict_mode_op, callable, operands): + pre_dispatch = getattr(mode, "pre_dispatch", False) + + with disable_proxy_modes_tracing(): + graph = make_fx(callable, pre_dispatch=pre_dispatch)(*operands) + + graph_name = mode.tracer.get_fresh_qualname("strict_graph_") + mode.tracer.root.register_module(graph_name, graph) + + args = (graph, operands) + + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) + + out_proxy = mode.tracer.create_proxy( + "call_function", strict_mode_op, proxy_args, {}, name="strict_mode" + ) + + out = graph(*operands) + return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + + +@register_fake(strict_mode_op, skip_cache=True) +def strict_mode_fake_tensor_mode(callable, operands): + return callable(*operands) + + +@strict_mode_op.py_functionalize_impl +def strict_mode_func(ctx, callable, inputs): + unwrapped_inputs = ctx.unwrap_tensors(inputs) + with ctx.redispatch_to_next(): + functional_callable = ctx.functionalize(callable) + + cond_return = strict_mode_op(functional_callable, unwrapped_inputs) + return ctx.wrap_tensors(cond_return) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/switch.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/switch.py new file mode 100644 index 0000000000000000000000000000000000000000..4651afa5d9c6526f01c82340059fc10b8cb88413 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/switch.py @@ -0,0 +1,424 @@ +import contextlib +import functools +import logging +import warnings +from collections.abc import Callable +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._functorch.utils import exposed_in +from torch._higher_order_ops.utils import ( + _maybe_compile_and_run_fn, + _maybe_run_with_interpreter, + check_input_alias_and_mutation_return_outputs, + create_bw_fn, + create_fn_remove_none, + fill_none_with_masks, + materialize_as_graph, + reenter_make_fx, + save_values_for_backward, + saved_values, + unique_graph_id, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.utils._python_dispatch import _get_current_dispatch_mode + + +log = logging.getLogger(__name__) + + +class SwitchOp(HigherOrderOperator): + def __init__(self): + super().__init__("switch") + + def __call__(self, index, branches, operands): + validate_subgraph_args_types(operands) + # pyrefly: ignore [missing-attribute] + return super().__call__(index, branches, operands) + + # pyrefly: ignore [bad-override] + def gen_schema(self, index, branches, operands): + from torch._higher_order_ops.schema import HopSchemaGenerator + from torch._higher_order_ops.utils import materialize_as_graph + + branch_gms: list[torch.fx.GraphModule] = [] + branch0_outputs: list[Any] | tuple[Any, ...] = [] + mutated_inputs: set[int] = set() + for branch in branches: + gm = materialize_as_graph(branch, operands) + ( + _, + _, + _, + branch_mutated_inputs, + branch_outputs, + ) = check_input_alias_and_mutation_return_outputs(gm) + branch_gms.append(gm) + if not branch0_outputs: + branch0_outputs = branch_outputs + mutated_inputs |= set(branch_mutated_inputs) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("index", index) + for i, gm in enumerate(branch_gms): + schema_gen.add_arg(f"branch{i}_fn", gm) + for idx, arg in enumerate(operands): + schema_gen.add_arg(f"operand{idx}", arg, is_mutated=idx in mutated_inputs) + + for out in branch0_outputs: + schema_gen.add_output(out) + schema_gen.add_schema_tree_spec(index, branches, operands) + return schema_gen.gen_schema() + + +switch_op = SwitchOp() + + +def wrap_branch_fn_flat(*args, branch_fn, spec_operands): + operands = pytree.tree_unflatten(args, spec_operands) + return branch_fn(*operands) + + +def _get_branch(branches, idx): + if not 0 <= idx < len(branches): + raise AssertionError( + f"switch index {idx} out of range for {len(branches)} branches" + ) + return branches[idx] + + +@exposed_in("torch") +def switch( + index: int | torch.SymInt | torch.Tensor, + branches: tuple[Callable, ...] | list[Callable], + operands: tuple | list = (), +) -> Any: + r""" + Selects and runs one of N branch functions by index. + + .. warning:: + + `torch.switch` is a prototype feature in PyTorch. It has limited support for input and + output types. Please look forward to a more stable implementation in a future version of + PyTorch. Read more about feature classification at: + https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + Equivalent to: ``branches[index](*operands)`` with index in ``[0, len(branches))``. + + Args: + index (Union[int, torch.Tensor]): An int or single-element integer tensor + indicating which branch to run. Out-of-range values are clamped into + ``[0, len(branches))``. + + branches (Union[tuple[Callable, ...], list[Callable]]): Non-empty sequence of + callables. Each must accept operands and return the same structure of outputs. + + operands (Tuple of possibly nested dict/list/tuple of torch.Tensor): Inputs to + the branch functions. Defaults to (). + + Restrictions: + - Each branch must have the same signature as operands and return the same + output structure (shape, dtype, etc.). Constant ``int`` and ``None`` leaves + are also permitted in branch outputs and are merged across branches (an + unbacked SymInt is introduced when ``int`` leaves differ between branches). + - Branches cannot have in-place mutations on inputs or global variables. + """ + + # Flatten operands so the HOP only sees a flat list of tensors. + # Each branch is wrapped to unflatten the leaves + # back to the user-facing pytree before invocation. + leaves_operands, spec_operands = pytree.tree_flatten(operands) + + def _validate_input(index, branches, operands): + if not isinstance(index, (int, torch.SymInt, torch.Tensor)): + raise RuntimeError( + f"Expected index to be int or single-element tensor, but got {index}." + ) + + if isinstance(index, torch.Tensor) and index.numel() != 1: + raise RuntimeError( + f"Expected index to be int or single-element tensor, but got {index}." + ) + + if not isinstance(branches, (tuple, list)) or len(branches) == 0: + raise RuntimeError( + "Expected branches to be a non-empty tuple or list of callables." + ) + + for i, branch in enumerate(branches): + if not callable(branch): + raise RuntimeError( + f"Expected all branches to be callable. branch{i} is not callable." + ) + + for x in operands: + if not isinstance(x, torch.Tensor): + raise RuntimeError(f"All operand leaves must be a Tensor but got {x}") + + _validate_input(index, branches, leaves_operands) + + wrapped_branches = tuple( + functools.partial( + wrap_branch_fn_flat, + branch_fn=branch_fn, + spec_operands=spec_operands, + ) + for branch_fn in branches + ) + + # Early shortcut: single-branch switch degenerates to a plain call + num_branches = len(wrapped_branches) + if num_branches == 1: + return wrapped_branches[0](*leaves_operands) + + # Clamp out-of-range indices to [0, len(branches) - 1] + if isinstance(index, torch.Tensor): + index = index.clamp(0, num_branches - 1) + elif isinstance(index, torch.SymInt): + index = torch.sym_max(0, torch.sym_min(index, num_branches - 1)) + elif isinstance(index, int): + index = max(0, min(index, num_branches - 1)) + + # Constant index shortcut for eager mode. + if not torch.compiler.is_dynamo_compiling() and isinstance(index, int): + # This is the non-strict export case. Strict export and torch.compile are + # handled below via _maybe_compile_and_run_fn. + if torch.compiler.is_compiling(): + warnings.warn( + "Index is a Python constant. When used with torch.switch, it specializes on one of the branches." + " If you want torch.switch to preserve the branches, please make the index an int tensor or a SymInt.", + UserWarning, + stacklevel=2, + ) + + return _get_branch(wrapped_branches, index)(*leaves_operands) + + # Use _maybe_compile_and_run_fn pattern from scan/associative_scan + def run_switch(index, wrapped_branches, leaves_operands): + return switch_op(index, wrapped_branches, leaves_operands) + + return _maybe_compile_and_run_fn( + run_switch, index, wrapped_branches, leaves_operands + ) + + +def trace_switch(proxy_mode, func_overload, index, branches, operands): + if not isinstance(operands, (list, tuple)): + raise AssertionError( + f"Switch operands must be a list or tuple of tensors and SymInts {operands}" + ) + if not isinstance(branches, (list, tuple)) or len(branches) == 0: + raise AssertionError( + "Switch branches must be a non-empty list or tuple of callables" + ) + + branch_graphs = [reenter_make_fx(branch)(*operands) for branch in branches] + + branch_outs = [list() for _ in branches] + for i, branch_graph in enumerate(branch_graphs): + for node in branch_graph.graph.nodes: + if node.op == "output": + branch_outs[i].extend(node.args) + + branch_out_spec = [pytree.tree_flatten(outs)[1] for outs in branch_outs] + for i, spec in enumerate(branch_out_spec): + if branch_out_spec[0] != spec: + raise RuntimeError( + "Unmatched output spec from torch.switch branches: " + f"branch0 tree_spec {branch_out_spec[0]} vs branch{i} tree_spec {spec}" + ) + + uid, _ = unique_graph_id(proxy_mode, prefix="branch0_graph") + for i, branch_graph in enumerate(branch_graphs): + proxy_mode.tracer.root.register_module(f"branch{i}_graph_{uid}", branch_graph) + + args = (index, branch_graphs, operands) + + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {} + ) + + out = func_overload(index, branch_graphs, operands) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@switch_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def switch_op_dense(index, branches, operands): + if not all(isinstance(o, (torch.Tensor, int)) for o in operands): + raise RuntimeError( + f"Dense implementation operands must be a list of tensors and ints {operands}" + ) + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + idx: int = int(index.item()) if isinstance(index, torch.Tensor) else int(index) + return _get_branch(branches, idx)(*operands) + + +class SwitchAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + index, + branches, + *operands, + ): + ctx._index = index + # Build one bw fn per branch. + ctx._branch_bw_fns = [ + create_bw_fn(create_fn_remove_none(branch)[0], operands) + for branch in branches + ] + + # We snapshot the dispatch keys in forward for materializing the + # bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + save_values_for_backward(ctx, operands) + + with torch._C._AutoDispatchBelowAutograd(): + outs = switch_op(index, branches, operands) + + # Record which output slots are Tensors. Non-Tensor slots (None, + # int/SymInt) carry no tangent in backward and the joint is built + # to omit them. + ctx._fw_output_is_tensor = [ + isinstance(o, torch.Tensor) for o in pytree.tree_leaves(outs) + ] + return outs + + @staticmethod + def backward(ctx, *flat_grads): + operands = saved_values(ctx) + tensor_grads = tuple( + g for g, keep in zip(flat_grads, ctx._fw_output_is_tensor) if keep + ) + args = operands + tensor_grads + # TODO: we need to materialize the bw graphs because dynamo is unable to + # trace through the joint function when torch.compile torch.autograd.grad. + + branches_bw_gm: list[torch.fx.GraphModule] = [] + grads_tensor_masks: list[bool] = [] + # All branches share the same input signature (see _validate_input) + for bw_fn in ctx._branch_bw_fns: + wrapped_bw, mask = create_fn_remove_none(bw_fn) + bw_gm = materialize_as_graph( + wrapped_bw, + args, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + branches_bw_gm.append(bw_gm) + if not grads_tensor_masks: + grads_tensor_masks = mask + + grads = switch_op( + ctx._index, + branches_bw_gm, + args, + ) + return None, None, *fill_none_with_masks(grads, grads_tensor_masks) + + +@switch_op.py_autograd_impl +def switch_autograd(index, branches, operands): + return SwitchAutogradOp.apply( + index, + branches, + *operands, + ) + + +@switch_op.py_impl(ProxyTorchDispatchMode) +def inner(mode, index, branches, operands): + return trace_switch(mode, switch_op, index, branches, operands) + + +@switch_op.py_impl(FakeTensorMode) +def switch_fake_tensor_mode(mode, index, branches, operands): + # Ignore here, because if you've gotten here but you're not manually + # tracing the inner graphs, that means that you intend to reuse the graph + # directly. Which means the old unbacked symbol bindings are appropriate. + # This strategy will not work if unbacked symbols can escape. + ignore_fresh_unbacked = contextlib.nullcontext() + if mode.shape_env: + ignore_fresh_unbacked = mode.shape_env.ignore_fresh_unbacked_symbols() + + with mode, ignore_fresh_unbacked: + flat_branch_outs, branch_out_spec = zip( + *[pytree.tree_flatten(branch(*operands)) for branch in branches] + ) + for i, spec in enumerate(branch_out_spec): + if branch_out_spec[0] != spec: + raise RuntimeError( + "Unmatched output spec from torch.switch branches: " + f"branch0 tree_spec {branch_out_spec[0]} vs branch{i} tree_spec {spec}" + ) + + merged_outs = [] + for branches_out in zip(*flat_branch_outs): + merged_outs.append(_merge_output(branches_out, mode)) + return pytree.tree_unflatten(merged_outs, branch_out_spec[0]) + + +def _merge_output(xs: tuple[torch.Tensor | int | None, ...], mode: FakeTensorMode): + from torch._higher_order_ops.cond import ( + _merge_ints_to_symint, + _merge_output as cond_merge_output, + ) + + # Shortcut if a branch produces None outputs; then all branches need to produce None + if any(x is None for x in xs): + if not all(x is None for x in xs): + raise AssertionError(f"expected all leaves to be None, got {xs}") + return None + + # In case all branches return an int, use an unbacked symbol as the merge result + if all(type(x) is int for x in xs): + return _merge_ints_to_symint(list(xs), mode) # type: ignore[arg-type] + + return functools.reduce(lambda a, b: cond_merge_output(a, b, mode), xs) + + +@switch_op.py_functionalize_impl +def switch_func(ctx, index, branches, inputs): + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, + ) + from torch._higher_order_ops.utils import _check_alias_and_mutation, HopInstance + + hop_instance = HopInstance.create(switch_op, index, branches, inputs) + if can_auto_functionalize(hop_instance) and hasattr(ctx, "mode"): + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + tuple(pytree.tree_flatten((index, branches, inputs))[0]), + {}, + ) + + unwrapped_inputs = ctx.unwrap_tensors(inputs) + unwrapped_index = ctx.unwrap_tensors(index) + with ctx.redispatch_to_next(): + functional_branches = [ + ctx.functionalize(_maybe_run_with_interpreter(fn)) for fn in branches + ] + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + for i, branch in enumerate(branches): + _check_alias_and_mutation( + branch, unwrapped_inputs, f"switch_branch{i}", pre_dispatch + ) + switch_return = switch_op( + unwrapped_index, functional_branches, unwrapped_inputs + ) + return ctx.wrap_tensors(switch_return) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/torchbind.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/torchbind.py new file mode 100644 index 0000000000000000000000000000000000000000..bad486b0f025070256954a38204b082825cc6abb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/torchbind.py @@ -0,0 +1,168 @@ +# mypy: allow-untyped-defs +import logging +from contextlib import contextmanager + +import torch +from torch._C import DispatchKey # @manual +from torch._functorch._aot_autograd.utils import KNOWN_TYPES +from torch._higher_order_ops.utils import autograd_not_implemented +from torch._library.fake_class_registry import ( + _is_script_object, + _ns_and_class_name, + FakeScriptObject, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.fx.node import has_side_effect +from torch.utils import _pytree as pytree + + +log = logging.getLogger(__name__) + + +# The call_torchbind operator represents a method invocation on a torchbind +# object. The calling convention is: +# call_torchbind(self: ScriptObject, method_name: str, *method_args, **method_kwargs) +# We do not expect users to write this operator directly. Instead it will be +# emitted by Dynamo when tracing encounters a torchbind object. +class CallTorchBind(HigherOrderOperator): + def __init__(self): + super().__init__("call_torchbind") + + def __call__(self, obj, method, *args, **kwargs): + # pyrefly: ignore [missing-attribute] + return super().__call__(obj, method, *args, **kwargs) + + @staticmethod + def schema(obj, method) -> torch.FunctionSchema: + """ + Returns the schema of ``CallTorchbind.__call__``. + """ + if not isinstance(obj, torch._inductor.ir.TorchBindObject): + raise AssertionError(f"expected obj to be TorchBindObject, got {type(obj)}") + val = obj.get_real_obj() + schema = val._get_method(method).schema + schema_str = str(schema) + new_schema_str = f"call_torchbind({str(schema.arguments[0].real_type)} {schema.arguments[0].name}," + first_comma_index = schema_str.find(",") + if first_comma_index == -1: + # If no comma is found, find the last closing parenthesis + first_comma_index = schema_str.rfind(") ->") + new_schema_str = new_schema_str + " str method" + schema_str[first_comma_index:] + new_schema = torch._C.parse_schema(new_schema_str) + return new_schema + + +call_torchbind = CallTorchBind() + +# Register this operator as side-effectful with FX. +# TODO: this is not really sufficient. While passes (hopefully) check +# Node.is_impure() and make good decisions, we also assume we can execute the +# graph as many times as we want without changing behavior, which is NOT true of +# ops that mutate torchbind object state. +has_side_effect(call_torchbind) + +_orig_scriptmethod_call = torch.ScriptMethod.__call__ + + +def torchbind_method_redispatch(self, *args, **kwargs): + if _is_script_object(self.raw_owner): + return call_torchbind(self.raw_owner, self.name, *args, **kwargs) + return _orig_scriptmethod_call(self, *args, **kwargs) + + +@contextmanager +def enable_torchbind_tracing(): + """Context manager that acts as a feature flag to enable torchbind tracing + behavior. Once torchbind tracing has been stabilized, we can remove this and + turn it always on. + """ + try: + KNOWN_TYPES.append(torch.ScriptObject) + torch.ScriptMethod.__call__ = torchbind_method_redispatch # type: ignore[method-assign] + yield + finally: + if KNOWN_TYPES.pop() is not torch.ScriptObject: + raise AssertionError( + "Someone else messed with KNOWN_TYPES during tracing, exploding." + ) + torch.ScriptMethod.__call__ = _orig_scriptmethod_call # type: ignore[method-assign] + + +@call_torchbind.py_impl(DispatchKey.CompositeExplicitAutograd) +def call_torchbind_impl(obj, method, *args, **kwargs): + if isinstance(obj, torch.ScriptObject): + return _orig_scriptmethod_call(getattr(obj, method), *args, **kwargs) + elif isinstance(obj, FakeScriptObject): + return getattr(obj.wrapped_obj, method)(*args, **kwargs) + else: + raise RuntimeError(f"Unsupported first arg type {type(obj)} for call_torchbind") + + +@call_torchbind.py_impl(ProxyTorchDispatchMode) +def inner(mode, *args, **kwargs): + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + + out_proxy = mode.tracer.create_proxy( + "call_function", + call_torchbind, + proxy_args, + proxy_kwargs, + ) + out = call_torchbind(*args, **kwargs) + + obj, method, *_rest_args = args + if isinstance(obj, torch.ScriptObject): + ns, class_name = _ns_and_class_name( + obj._type().qualified_name() # type: ignore[attr-defined] + ) + log.warning( + "Tracing torchbind method %s.%s with real ScriptObject. This may" + " cause the original object being mutated. If this is not intended," + ' You can register a fake class with torch._library.register_fake_class("%s::%s").', + class_name, + method, + ns, + class_name, + ) + + ret = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + if "val" not in out_proxy.node.meta: + if out is not None and not isinstance(out, (int, float, bool)): + raise AssertionError( + f"Currently, only these constant dtypes are supported to be returned from torchbind methods, got {type(out)}" + ) + out_proxy.node.meta["val"] = out + return ret + + +# When tracing with fake script object, the call_torchbind op will return a fake tensor +# When tracing with real script object, the call_torchbind op may return a real tensor, +# we need to convert it to fake tensor manually. Dynamic shape is supported. +@call_torchbind.py_impl(FakeTensorMode) +def call_torchbind_fake(mode, *args, **kwargs): + with mode: + out = call_torchbind_impl(*args, **kwargs) + return pytree.tree_map_only( + torch.Tensor, + lambda x: mode.from_tensor(x, static_shapes=True) + if not torch._subclasses.fake_tensor.is_fake_tensor(x) + else x, + out, + ) + + +call_torchbind.py_autograd_impl( + autograd_not_implemented(call_torchbind, deferred_error=True) +) + + +@call_torchbind.py_functionalize_impl +def call_torchbind_func(ctx, *args, **kwargs): + from torch._higher_order_ops.effects import handle_effects + + return handle_effects( + ctx.mode._allow_token_discovery, ctx.mode._tokens, call_torchbind, args, kwargs + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/triton_kernel_wrap.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/triton_kernel_wrap.py new file mode 100644 index 0000000000000000000000000000000000000000..4c16850e55427785840b06534f55e8c7860849c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/triton_kernel_wrap.py @@ -0,0 +1,2676 @@ +import ast +import collections +import copy +import dataclasses +import functools +import inspect +import itertools +import logging +import operator +import threading +import typing +from collections import defaultdict +from collections.abc import Callable, Sequence +from typing import Any, Optional, Protocol, TYPE_CHECKING, Union +from typing_extensions import Never + +import sympy + +import torch.fx as fx +import torch.utils._pytree as pytree +from torch import SymBool, SymFloat, SymInt, Tensor +from torch._C import _dispatch_keys, DispatchKey +from torch._higher_order_ops.utils import redirect_to_mode, register_fake +from torch._ops import HigherOrderOperator +from torch._prims_common import clone_preserve_strides +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.fx.experimental.symbolic_shapes import guard_scalar +from torch.types import IntLikeType +from torch.utils._ordered_set import OrderedSet +from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode + + +if TYPE_CHECKING: + from triton._C.libtriton.ir import ( + module as TritonIRModule, + operation as TritonIROperation, + ) + + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.constant import ConstantVariable + from torch._dynamo.variables.functions import TritonKernelVariable + from torch._guards import Source + from torch._inductor.dependencies import ReadWrites + from torch._subclasses.functional_tensor import BaseFunctionalizeAPI + from torch.fx.proxy import Proxy + from torch.utils._triton import has_triton + + TritonMetaParamsType = dict[str, int] + TritonGridTupleType = tuple[int | sympy.Expr | SymInt, ...] + TritonGridCallableType = Callable[[TritonMetaParamsType], tuple[int, ...]] + TritonGridType = TritonGridTupleType | TritonGridCallableType + + if has_triton(): + from triton.runtime.autotuner import Autotuner, Config as TritonConfig + from triton.runtime.jit import JITFunction + else: + + class Autotuner: # type: ignore[no-redef] + pass + + class JITFunction: # type: ignore[no-redef] + pass + + TritonKernelType = Autotuner | JITFunction + # mypy specifically complains that TritonAutotunerType is not a valid type if Autotuner is not inside of a Union. + TritonAutotunerType = Union[Autotuner] # noqa: UP007 + +log = logging.getLogger("torch._dynamo") + +# e.g. for a host-side Triton TMA API call ``create_2d_tma_descriptor(ptr, 50, 60, 32, 15, 4)``, +# the metadata will look like ``("experimental", ([50, 60], [32, 15], 4))`` +TMAExperimentalMetadata = tuple[ + str, # type of TMA (should be "experimental") + tuple[ + list[IntLikeType], # dims + list[IntLikeType], # block_dims + IntLikeType, # element_size + ], +] + +# e.g. for host-side Triton TMA API call ``TensorDescriptor.from_tensor(ptr, [32, 64])`` +# the metadata will look like ``("stable", ([32, 64],))`` +TMAStableMetadata = tuple[ + str, # type of TMA ("experimental" or "stable") + tuple[list[IntLikeType],], # block_shape +] + + +def create_tma_experimental_metadata( + dims: list[IntLikeType], + block_dims: list[IntLikeType], + element_size: IntLikeType, +) -> TMAExperimentalMetadata: + return ("experimental", (dims, block_dims, element_size)) + + +def maybe_unpack_tma_experimental_metadata( + tma_meta: TMAExperimentalMetadata | TMAStableMetadata, +) -> tuple[list[IntLikeType], list[IntLikeType], IntLikeType] | None: + if not tma_meta or len(tma_meta) != 2: + return None + if tma_meta[0] == "experimental": + return tma_meta[1] # type: ignore[return-value] + return None + + +def create_tma_stable_metadata( + block_shape: list[IntLikeType], +) -> TMAStableMetadata: + return ("stable", (block_shape,)) + + +def maybe_unpack_tma_stable_metadata( + tma_meta: TMAExperimentalMetadata | TMAStableMetadata, +) -> tuple[list[IntLikeType]] | None: + if not tma_meta or len(tma_meta) != 2: + return None + if tma_meta[0] == "stable": + return tma_meta[1] # type: ignore[return-value] + return None + + +# TMADescriptorMetadata maps kernel parameter names to the metadata that allows +# reconstructing TMA descriptors from the underlying tensors (passed as kernel +# arguments in the fx graph, instead of the TMA descriptors). +# +# Since there are two TMA APIs (the old "experimental" API and the new "stable" API), +# each entry in the dict is a tuple that starts with a string, either "experimental" +# or "stable". The second entry in the tuple is another tuple, with data that depends +# on the API type (see TMAExperimentalMetadata and TMAStableMetadata above). +# +# These are stored as raw tuples (instead of classes) for ease of serialization. +TMADescriptorMetadata = dict[ + str, # kernel parameter name + TMAExperimentalMetadata | TMAStableMetadata, +] + + +############################################################################### +# Kernel Side Table + + +# We cannot put Triton Kernels into the FX graph as the graph nodes +# do not support arbitrary functions. +# Use a side table. +# We use two dicts so that fetching both the kernel and id are O(1) +class KernelSideTable: + id_to_kernel: dict[int, "TritonKernelType"] = {} + kernel_to_id: dict["TritonKernelType", int] = {} + constant_args: dict[int, dict[str, Any]] = {} + lock = threading.Lock() + + # Returns index on the table + def add_kernel(self, kernel: "TritonKernelType") -> int: + with self.lock: + if kernel in self.kernel_to_id: + return self.kernel_to_id[kernel] + + idx = len(self.id_to_kernel) + self.id_to_kernel[idx] = kernel + self.kernel_to_id[kernel] = idx + return idx + + # Returns the triton kernel at the given index + def get_kernel(self, idx: int) -> "TritonKernelType": + # No need to lock here as fetching from dict is atomic + if idx not in self.id_to_kernel: + raise AssertionError(f"Kernel index {idx} not found in id_to_kernel") + return self.id_to_kernel[idx] + + # Not every constant arg can be added to the graph. Use this side table + # for constant args. + def add_constant_args(self, args: dict[str, Any]) -> int: + with self.lock: + idx = len(self.constant_args) + self.constant_args[idx] = args + return idx + + # Returns the constant args + def get_constant_args(self, idx: int) -> dict[str, Any]: + # No need to lock here as fetching from dict is atomic + if idx not in self.constant_args: + raise AssertionError( + f"Constant args index {idx} not found in constant_args" + ) + return self.constant_args[idx] + + # Resets the table (only meant to be used in unit tests) + # This is only safe assuming single threaded execution + def reset_table(self) -> None: + self.id_to_kernel = {} + self.kernel_to_id = {} + self.constant_args = {} + + +kernel_side_table = KernelSideTable() + + +############################################################################### +# Mutation Tracker + + +@dataclasses.dataclass(frozen=True, slots=True) +class Param: + idx: int + + +@dataclasses.dataclass(frozen=True, slots=True) +class Intermediate: + idx: int + + def fake(self) -> bool: + return self.idx < 0 + + +@dataclasses.dataclass(frozen=True, slots=True) +class Op: + name: str + fn_call_name: str | None + args: list[Param | Intermediate] + ret: Intermediate = dataclasses.field(repr=False) + # used for scf.yield: see [Note: scf.yield fix-up] + sub_idx: int | None = None + # used for tt.elementwise_inline_asm + # `is_pure = True` assumes the asm block has no side-effects + is_pure: bool = False + + def __post_init__(self) -> None: + if self.name == "tt.call": + if self.fn_call_name is None: + raise AssertionError("fn_call_name must not be None for tt.call op") + else: + if self.fn_call_name is not None: + raise AssertionError( + f"fn_call_name must be None for non-tt.call op, got {self.fn_call_name}" + ) + + +def generate_ttir( + kernel: "TritonKernelType", + kwargs: dict[str, Any], + tma_descriptor_metadata: TMADescriptorMetadata, +) -> tuple["TritonIRModule", list[str]]: + """ + Uses Triton's internal code generation to create TTIR + """ + import sympy + import triton + import triton.runtime.jit + from triton.compiler.compiler import ASTSource + from triton.runtime.autotuner import Autotuner + from triton.runtime.jit import JITFunction + + from torch._inductor.utils import ( + get_triton_attrs_descriptor_version, + triton_version_uses_attrs_dict, + TritonAttrsDescriptorVersion, + ) + from torch.utils._triton import has_triton_tensor_descriptor_host_tma + + triton_version = get_triton_attrs_descriptor_version() + + import torch._inductor.ir + from torch._subclasses.fake_tensor import is_fake_tensor + + if isinstance(kernel, Autotuner): + if len(kernel.configs) > 0: + # If we are autotuning, then it doesn't matter which version gets + # picked for tracing purposes, so lets pick the first one + kwargs = {**kwargs, **kernel.configs[0].kwargs} + kernel = kernel.fn + + if not isinstance(kernel, JITFunction): + raise AssertionError(f"Expected kernel to be a JITFunction, got {type(kernel)}") + + context = triton._C.libtriton.ir.context() + target = triton.runtime.driver.active.get_current_target() + backend = triton.compiler.compiler.make_backend(target) + options = backend.parse_options({}) + + # ignore backend-specific kwargs same way as in the native Triton code + # https://github.com/triton-lang/triton/blob/a6bb57d6285e723c58e87dd7cba263db6efff789/python/triton/runtime/jit.py#L594-L596 + # why this is important for user-defined Triton kernels on AMD: https://github.com/pytorch/pytorch/issues/140800 + for name in list(kwargs): + if name not in kernel.arg_names and name in options.__dict__: + kwargs.pop(name) + + if len(kwargs) != len(kernel.arg_names): + raise ValueError( + "Incorrect number of arguments passed to kernel: " + f"passed {list(kwargs.keys())}, expected {kernel.arg_names}." + ) + + # Replace all SymExprs with a regular value for TTIR generation + # Replace all FakeTensor/TensorBox with real tensors + # These replacements are needed for triton's type, key and config functions + ordered_args: dict[str, Any] = {} + for name in kernel.arg_names: + a = kwargs[name] + if isinstance(a, (torch.SymInt, torch.SymFloat, torch.SymBool, sympy.Expr)): + ordered_args[name] = 2 + elif ( + stable_meta := maybe_unpack_tma_stable_metadata( + # pyrefly: ignore [bad-argument-type] + tma_descriptor_metadata.get(name, None) + ) + ) is not None: + from triton.tools.tensor_descriptor import TensorDescriptor + + block_shape = stable_meta[0] + with torch._C._DisableTorchDispatch(): + # need 16-byte aligned strides + elements_per_dim = max(1, 16 // a.dtype.itemsize) + base_tensor = torch.empty( + [elements_per_dim] * len(block_shape), dtype=a.dtype + ) + + ordered_args[name] = TensorDescriptor.from_tensor(base_tensor, block_shape) + elif is_fake_tensor(a) or isinstance(a, torch._inductor.ir.TensorBox): + with torch._C._DisableTorchDispatch(): + ordered_args[name] = torch.empty(2, dtype=a.dtype) + else: + ordered_args[name] = a + + def is_stable_tensor_descriptor_arg(arg: Any) -> bool: + if has_triton_tensor_descriptor_host_tma(): + from triton.tools.tensor_descriptor import TensorDescriptor + + if isinstance(arg, TensorDescriptor): + return True + return False + + def _is_constexpr_or_none(name: str, arg: Any) -> bool: + param_idx = kernel.arg_names.index(name) + return kernel.params[param_idx].is_constexpr or arg is None + + # Note: one would expect that each input to the triton kernel maps to + # one input parameter in the TTIR. This is _not_ true for TMA descriptors: + # one TMA descriptor gets converted into: + # * one TMA descriptor input + # * N strides, for a rank-N tensor + # * N sizes, for a rank-N tensor + # To account for this, we inject some fake arg names as placeholders for + # the stride and size parameters. + # + # Additionally, tensors and scalars are both included as TTIR parameters, + # whereas `constexpr` are inlined, and None are excluded. We both preserve + # scalars and tensors as this matters for "odd" ordering, + # eg. [tensor, scalar, tensor]. + def get_arg_names(name: str, arg: Any) -> list[str]: + if _is_constexpr_or_none(name, arg): + return [] + + if is_stable_tensor_descriptor_arg(arg): + stable_meta = maybe_unpack_tma_stable_metadata( + tma_descriptor_metadata[name] + ) + if stable_meta is None: + raise AssertionError(f"Failed to unpack stable TMA metadata for {name}") + block_shape = stable_meta[0] + tensor_rank = len(block_shape) + names = [name] + names.extend(name + f" STRIDE PLACEHOLDER {i}" for i in range(tensor_rank)) + names.extend(name + f" SIZE PLACEHOLDER {i}" for i in range(tensor_rank)) + return names + + return [name] + + ordered_arg_names = list( + itertools.chain.from_iterable( + get_arg_names(name, arg) for name, arg in ordered_args.items() + ) + ) + + def _get_specialization(args): # type: ignore[no-untyped-def] + # Support multiple triton versions. + # This code basically copies JITFunction.run() logic to get the attrs to construct an ASTSource. + if triton_version == TritonAttrsDescriptorVersion.V1_COMPILER: + return kernel._get_config(*args) + elif triton_version in { + TritonAttrsDescriptorVersion.V2_BACKENDS, + TritonAttrsDescriptorVersion.V3_BACKENDS_TUPLE, + }: + from triton.backends.compiler import AttrsDescriptor # noqa: F401 + + target = triton.runtime.driver.active.get_current_target() + backend_ = triton.compiler.compiler.make_backend(target) + + return backend_.get_attrs_descriptor(args, kernel.params) + else: + if ( + get_triton_attrs_descriptor_version() + != TritonAttrsDescriptorVersion.V4_DICT + ): + raise AssertionError( + f"Expected Triton attrs descriptor version V4_DICT, " + f"got {get_triton_attrs_descriptor_version()}" + ) + # specialize_impl switched to create_specialize_impl in https://github.com/triton-lang/triton/pull/6099 + if hasattr(triton.runtime.jit, "create_specialize_impl"): + try: + # Latest versions of Triton take specialize_extra as an arg to create_specialize_impl + specialize_impl = triton.runtime.jit.create_specialize_impl( + specialize_extra=backend.get_arg_specialization + ) + except TypeError: # Unknown arg `specialize_extra` + # Older versions of Triton take specialize_extra as an arg to specialize_impl + specialize_impl = functools.partial( + triton.runtime.jit.create_specialize_impl(), + specialize_extra=backend.get_arg_specialization, + ) + # create_specialize_impl is removed in https://github.com/triton-lang/triton/pull/7771 + # switch to native_specialize_impl instead + elif hasattr(triton.runtime.jit, "native_specialize_impl"): + from triton.backends import BaseBackend + from triton.runtime.jit import native_specialize_impl + + def _native_specialize_impl( + arg: Any, + is_const: bool = False, + specialize_value: bool = True, + align: bool = True, + ) -> Callable: + return native_specialize_impl( + BaseBackend, arg, is_const, specialize_value, align + ) + + specialize_impl = _native_specialize_impl + else: + from triton.runtime.jit import specialize_impl as specialize_impl_orig + + specialize_impl = functools.partial( + specialize_impl_orig, + specialize_extra=backend.get_arg_specialization, + ) + + from triton._utils import find_paths_if, get_iterable_path + + # logic is copied from: binder = create_function_from_signature(self.signature, self.params, backend) + attrvals = [] + for arg, kp in zip(args, kernel.params): + if kp.is_constexpr: + attrvals.append(arg) + else: + spec = specialize_impl( + arg, + is_const=kp.is_const, + specialize_value=not kp.do_not_specialize, + align=not kp.do_not_specialize_on_alignment, + ) + # pyrefly: ignore [unsupported-operation] + attrvals.append(spec[1]) + + attrs = find_paths_if(attrvals, lambda _, x: isinstance(x, str)) + attrs = { + k: backend.parse_attr(get_iterable_path(attrvals, k)) for k in attrs + } + return attrs + + specialization = _get_specialization(ordered_args.values()) + # Triton explicitly interprets ASTSource.constants entries as constexpr + # Thus, only None and arguments marked `is_constexpr` should be treated as such. + constants = { + name: arg + for name, arg in ordered_args.items() + if _is_constexpr_or_none(name, arg) + } + + if (mangle_type := getattr(triton.runtime.jit, "mangle_type", None)) is not None: + + def get_signature_value(idx: int, arg: Any) -> str: + if kernel.params[idx].is_constexpr: + return "constexpr" + # pyrefly: ignore [not-callable] + result = mangle_type(arg) + # Workaround for Triton i1/u1 AOTI bug: PyTorch stores bool + # tensors as uint8 (1 byte per element), but *i1/*u1 causes + # the compiled kernel to generate bit-packed loads. Use *u8 + # so loads correctly read 1 byte per element. + if result in ("*i1", "*u1"): + result = "*u8" + return result + + else: + + def get_signature_value(idx: int, arg: Any) -> str: + return kernel._type_of(kernel.key_of(arg)) + + if triton_version_uses_attrs_dict(): + # In newer versions of Triton, the signature includes constexpr args + signature = { + name: get_signature_value(i, arg) + for i, (name, arg) in enumerate(ordered_args.items()) + } + else: + # In older versions of Triton, the signature does not include constexpr args + constexprs = [p.num for p in kernel.params if p.is_constexpr] + signature = { + name: get_signature_value(i, arg) + for i, (name, arg) in enumerate(ordered_args.items()) + if i not in constexprs + } + + triton._C.libtriton.ir.load_dialects(context) + backend.load_dialects(context) + + src = ASTSource(kernel, signature, constants, specialization) + + # Triton changes ASTSource.make_ir to take 3/4 arguments. Handle + # backward compatibility here. + make_ir_sig_params = len(inspect.signature(src.make_ir).parameters) + get_codegen_implementation_sig_params = len( + inspect.signature(backend.get_codegen_implementation).parameters + ) + if make_ir_sig_params == 2: + ttir_module = src.make_ir(options, context) + elif make_ir_sig_params == 3: + codegen_fns = backend.get_codegen_implementation() + + ttir_module = src.make_ir(options, codegen_fns, context) + elif make_ir_sig_params == 4: + codegen_args = [options] if get_codegen_implementation_sig_params == 1 else [] + + codegen_fns = backend.get_codegen_implementation(*codegen_args) + module_map = backend.get_module_map() + + ttir_module = src.make_ir(options, codegen_fns, module_map, context) + else: + codegen_args = [options] if get_codegen_implementation_sig_params == 1 else [] + + codegen_fns = backend.get_codegen_implementation(*codegen_args) + module_map = backend.get_module_map() + + ttir_module = src.make_ir(target, options, codegen_fns, module_map, context) + if not ttir_module.verify(): + raise RuntimeError("Verification for TTIR module has failed") + + return ttir_module, ordered_arg_names + + +def ttir_to_functions( + ttir_module: "TritonIRModule", +) -> dict[str, dict[Intermediate, list[Op]]]: + """ + Walk the `ttir_module` bottom up to mine the `functions` from + the structured MLIR entities representing the Triton kernel + (mlir::Operation, mlir::Block, mlir::Region). + """ + functions: dict[str, dict[Intermediate, list[Op]]] = {} + + # block id --> op result (Intermediate) --> one or more ops + op_stack: dict[int, dict[Intermediate, list[Op]]] = defaultdict( + lambda: defaultdict(list) + ) + region_id_to_block_ids: dict[int, list[int]] = defaultdict(list) + block_id_to_block_arg_ids: dict[int, list[int]] = {} + replacements: dict[int, Intermediate | Param] = {} + reindex_map: dict[int, int] = {} + next_fake_intermediate = 0 + + def reindex(idx: int) -> int: + if idx not in reindex_map: + reindex_map[idx] = len(reindex_map) + return reindex_map[idx] + + def mlir_to_functions(op: "TritonIROperation") -> None: + name: str = op.get_name() + if name == "builtin.module": + # this wraps all tt.func ops + return + + operand_ids: list[int] = [ + reindex(op.get_operand(i).id()) for i in range(op.get_num_operands()) + ] + result_ids: list[int] = [ + reindex(op.get_result(i).id()) for i in range(op.get_num_results()) + ] + + child_block_ids: list[int] = [] + for i in [op.get_region(i).id() for i in range(op.get_num_regions())]: + # as the walk is bottom-up, the region_id_to_block_ids[i] + # must be populated by the time we process the enclosing op + child_block_ids.extend(region_id_to_block_ids[i]) + + parent_block_id = -1 + parent_block = op.get_block() + if parent_block is not None: + parent_block_id = parent_block.id() + if parent_block_id not in block_id_to_block_arg_ids: + block_id_to_block_arg_ids[parent_block_id] = [] + for i in range(parent_block.get_num_arguments()): + block_id_to_block_arg_ids[parent_block_id].append( + reindex(parent_block.get_argument(i).id()), + ) + # the region info is collected via ops' parent blocks to be + # used later when the region's enclosing op is traversed + parent_region = parent_block.get_parent() + if parent_region is not None: + region_id_to_block_ids[parent_region.id()].append(parent_block_id) + + nonlocal next_fake_intermediate + + if name == "tt.func": + # for function ops: gather and inline + # the ops from all child blocks + fn_ops = defaultdict(list) + for child_block_id in child_block_ids: + for result, block_fn_ops in op_stack.pop(child_block_id).items(): + for block_fn_op in block_fn_ops: + fn_ops[result].append(block_fn_op) + + # replace the corresponding Intermediates in the + # child op args with the function args (Params) + for i, idx in enumerate(block_id_to_block_arg_ids[child_block_ids[0]]): + replacements[idx] = Param(i) + + for fn_op_list in fn_ops.values(): + for fn_op in fn_op_list: + for i in range(len(fn_op.args)): + arg = fn_op.args[i] + seen = set() # to break cycles + # there can be transitive replacements, but likely + # no cycles (we keep the `seen` set just in case) + while ( + isinstance(arg, Intermediate) + and arg.idx in replacements + and arg.idx not in seen + ): + seen.add(arg.idx) + arg = fn_op.args[i] = replacements[arg.idx] + + # next function capture starts + # with empty replacements + replacements.clear() + + fn_name = op.get_str_attr("sym_name") + functions[fn_name] = fn_ops + elif child_block_ids: + if name in {"scf.if", "scf.for", "scf.while", "tt.reduce", "tt.scan"}: + # for blocked ops: inline the enclosed ops into + # the parent block + rewire the last op in each + # child block to return the block result + return_ops = [] + for block_id in child_block_ids: + if name == "scf.for": + # example: + # %result = scf.for %iv = %lb to %ub step %step iter_args(%arg = %init) -> (i32) ... + # block args: 2 (%iv, %arg) + # op operands: 4 (%lb, %ub, %step, %init) + # `%arg` is mapping to `%init` + for i, idx in enumerate(block_id_to_block_arg_ids[block_id]): + if i == 0: + next_fake_intermediate -= 1 + replacements[idx] = Intermediate(next_fake_intermediate) + else: + replacements[idx] = Intermediate(operand_ids[i + 2]) + elif name == "scf.while": + # example: + # %3:3 = scf.while (%arg2 = %1, %arg3 = %2, %arg4 = %c0_i32_8) ... + # block args: 3 (%arg2, %arg3, %arg4) + # op operands: 3 (%1, %2, %c0_i32_8) + # `%arg2` is mapping to `%1`, `%arg3` is mapping to `%2`, ... + for i, idx in enumerate(block_id_to_block_arg_ids[block_id]): + replacements[idx] = Intermediate(operand_ids[i]) + elif name == "scf.if": + # the scf block args are ignored by the pass. but, as they + # may be used as operands of the ops inside the block + # (and nested blocks inlined in the current block by now), + # they are replaced by new fake Intermediates to avoid "this + # operand is not returned by any other op in the fn" error + # in the downstream analysis + for idx in block_id_to_block_arg_ids[block_id]: + next_fake_intermediate -= 1 + replacements[idx] = Intermediate(next_fake_intermediate) + else: + if name not in ("tt.reduce", "tt.scan"): + raise AssertionError( + f"Expected op name to be 'tt.reduce' or 'tt.scan', got {name}" + ) + # wire the block arguments to the op arguments + num_operands = len(operand_ids) + block_arg_ids = block_id_to_block_arg_ids[block_id] + if len(block_arg_ids) != 2 * num_operands: + raise AssertionError( + f"{name} is expected to have twice as " + "many block arguments as op arguments: " + f"{operand_ids=}, {block_arg_ids=}." + ) + for i, idx in enumerate(block_arg_ids): + # for a tt.reduce/tt.scan op with N arguments, the block + # arguments comprise N reduced values followed by + # N current values corresponding to the N op args + replacements[idx] = Intermediate( + operand_ids[i % num_operands] + ) + + if block_id in op_stack: + block_ops = op_stack.pop(block_id) + if not block_ops: + continue + last_ret, last_ops = block_ops.popitem() + if all( + op.name + in ("scf.yield", "tt.reduce.return", "tt.scan.return") + for op in last_ops + ): + # if last_ops are all return ops, treat them separately + return_ops.extend(last_ops) + else: + # otherwise, return last_ops to the block + block_ops[last_ret] = last_ops + for op_result, child_ops in block_ops.items(): + op_stack[parent_block_id][op_result].extend(child_ops) + + scf_results = [Intermediate(idx) for idx in result_ids] + + if return_ops and all( + (op.name == "scf.yield" and len(result_ids) == len(op.args)) + for op in return_ops + ): + # [Note: scf.yield fix-up] + # + # TL;DR: if our scf.yield takes N args, then we'll create N scf.yield ops to handle each of the + # args. + # + # **Context**: + # During mutation analysis, the analysis pass will identify mutating ops (e.g. tt.store) + # and then DFS upwards towards the parameters of the function. Specifically, the analysis pass + # looks at the mutated arg in tt.store; then looks for its source ops; and then recurses on the + # arguments to each of the source ops. + # + # In the case of scf.if/scf.for, we may have multiple return ops, each passed as an arg + # to scf.yield: + # + # %18:2 = scf.if %... -> (!tt.ptr, !tt.ptr) { + # ... + # scf.yield %1, %2 + # } else { + # scf.yield %3, %4 + # } + # + # And for each of the returns of the scf.if, we'd naively assign the source op of each of the + # return values to be the scf.yields. But the scf.yields take _all_ the returns as arguments. + # Therefore, if _any_ of the return values of the scf.if are mutated, then the analysis pass + # would mark _all_ of the yield args as mutated. + # + # **Solution**: + # For the purposes of this analysis pass, we create N yield ops - one for each + # return-val/yield-arg. In the example above, we'll have two scf.yield's for each branch of the + # scf.if. + + for return_op in return_ops: + for i, (scf_result, yield_arg) in enumerate( + zip(scf_results, return_op.args) + ): + sub_yield_op = Op( + return_op.name, + return_op.fn_call_name, + [yield_arg], + return_op.ret, + sub_idx=i, + ) + op_stack[parent_block_id][scf_result].append(sub_yield_op) + + else: + for scf_result in scf_results: + for return_op in return_ops: + op_stack[parent_block_id][scf_result].append(return_op) + else: + raise RuntimeError( + f"Unknown blocked function: {name}. Can't capture the TTIR." + ) + else: + callee = None + if name == "tt.call": + callee = op.get_flat_symbol_ref_attr("callee") + args: list[Param | Intermediate] = [ + Intermediate(operand) for operand in operand_ids + ] + block_ops = op_stack[parent_block_id] + + is_pure = False + # Handle the case for tt.elementwise_inline_asm to set `is_pure` for mutation analysis + if name == "tt.elementwise_inline_asm": + is_pure = op.get_bool_attr("pure") + + if result_ids: + for result_id in result_ids: + res = Intermediate(result_id) + block_ops[res].append(Op(name, callee, args, res, is_pure=is_pure)) + else: + next_fake_intermediate -= 1 + fake_res = Intermediate(next_fake_intermediate) + block_ops[fake_res].append( + Op(name, callee, args, fake_res, is_pure=is_pure) + ) + + ttir_module.walk(mlir_to_functions) + + return functions + + +class MemoizeWithCycleCheck: + fn: Callable[..., Any] + cache: dict[tuple[Any], Any] + + def __init__(self, fn: Callable[..., Any]) -> None: + self.fn = fn + self.reset() + + def __call__( + self, + functions: dict[str, dict[Intermediate, list[Op]]], + fn_name: str, + *args: Any, + ) -> Any: + key: tuple[Any, ...] = (fn_name, *args) + if key not in self.cache: + self.cache[key] = None + self.cache[key] = self.fn(functions, fn_name, *args) + if self.cache[key] is None: + raise RuntimeError("Recursion is not supported") + return self.cache[key] + + def reset(self) -> None: + self.cache = {} + + +@MemoizeWithCycleCheck +def get_tma_stores( + functions: dict[str, dict[Intermediate, list[Op]]], fn_name: str +) -> set[Intermediate | Param]: + """ + Identifies all intermediates and parameters that are written to by a + `tt.experimental_descriptor_store`. It tracks only the specific values + written to via experimental_descriptor_store and the input values to + `tt.reinterpret_tensor_descriptor` used to construct the direct inputs + to tt.experimental_descriptor_store - not any recursive values + used to construct those values. + + For example: for + tt.reinterpret_tensor_descriptor(Intermediate(idx=0), ...) + Intermediate(idx=1) = tt.experimental_descriptor_store(Intermediate(idx=0), ...) + this function will return [Intermediate(idx=0), Intermediate(idx=1)], + + However + Intermediate(idx=4) = arith.addptr(Intermediate(idx=2), Intermediate(idx=3)) + Intermediate(idx=5) = tt.experimental_descriptor_store(Intermediate(idx=4), ...) + tt.experimental_descriptor_store(Intermediate(idx=5), ...) + this function will mark only idx=4 and idx=5 (but not idx=2 or idx=3) + + If an intermediate/parameter is passed into a function and is written to + via experimental_descriptor_store within that function, the argument to the + function will also be marked. + """ + + result: set[Intermediate | Param] = set() + + ops = functions[fn_name] + for op_list in ops.values(): + for op in op_list: + if op.name == "tt.call": + if op.fn_call_name not in functions: + raise AssertionError( + f"Function {op.fn_call_name} not found in functions for TMA stores" + ) + # pyrefly: ignore [bad-argument-type] + tma_stores = get_tma_stores(functions, op.fn_call_name) + for i, inp in enumerate(op.args): + if Param(idx=i) in tma_stores: + result.add(inp) + else: + op_info = _KERNEL_ACCESS_OPS.get(op.name) + if ( + op_info is not None + and op_info.is_tma_store + and op_info.write_indexes is not None + ): + result.update(op.args[idx] for idx in op_info.write_indexes(op)) + + for val in list(result): + if val in ops: + if not isinstance(val, Intermediate): + continue + for op in ops[val]: + if op.name == "tt.reinterpret_tensor_descriptor": + if len(op.args) < 1: + raise AssertionError( + "tt.reinterpret_tensor_descriptor expected at least 1 arg, " + f"got {len(op.args)}" + ) + result.add(op.args[0]) + + return result + + +@dataclasses.dataclass +class TensorAccesses: + read_writes: "ReadWrites" + can_fuse_epilogue: bool + + +class IgnoreUnknownOp(Protocol): + """Returns True if the op should be skipped; otherwise the caller raises.""" + + def __call__(self, op: Op) -> bool: ... + + +class ReadWriteIndexes(Protocol): + """Return the argument indexes read / written.""" + + def __call__(self, op: Op) -> Sequence[int]: ... + + +def first_arg(op: Op) -> list[int]: + """Return the first argument index after checking that it exists.""" + if len(op.args) < 1: + raise AssertionError(f"{op.name} expected at least 1 arg, got {len(op.args)}") + return [0] + + +@dataclasses.dataclass(frozen=True) +class _KernelAccessOpInfo: + read_indexes: ReadWriteIndexes | None = None + write_indexes: ReadWriteIndexes | None = None + is_tma_store: bool = False + ignore_if: IgnoreUnknownOp | None = None + + +# List from Triton Github include/triton/Dialect/Triton/IR/TritonOps.td. +# What if Triton exposed this? +_KERNEL_ACCESS_OPS: dict[str, _KernelAccessOpInfo] = { + "tt.experimental_descriptor_store": _KernelAccessOpInfo( + write_indexes=first_arg, is_tma_store=True + ), + "tt.descriptor_store": _KernelAccessOpInfo( + write_indexes=first_arg, is_tma_store=True + ), + "tt.store": _KernelAccessOpInfo(write_indexes=first_arg), + "tt.atomic_cas": _KernelAccessOpInfo(write_indexes=first_arg), + "tt.atomic_rmw": _KernelAccessOpInfo( + read_indexes=first_arg, write_indexes=first_arg + ), + "tt.experimental_tensormap_create": _KernelAccessOpInfo(write_indexes=first_arg), + "tt.load": _KernelAccessOpInfo(read_indexes=first_arg), + "tt.load_tensor_descriptor": _KernelAccessOpInfo(read_indexes=first_arg), + "tt.descriptor_load": _KernelAccessOpInfo(read_indexes=first_arg), + "tt.elementwise_inline_asm": _KernelAccessOpInfo(ignore_if=lambda op: op.is_pure), +} + + +def _read_write_indexes(indexes: Sequence[int] | ReadWriteIndexes) -> ReadWriteIndexes: + if callable(indexes): + return indexes + index_tuple = tuple(indexes) + return lambda op: index_tuple + + +def register_kernel_access_op( + name: str, + *, + read_indexes: Sequence[int] | ReadWriteIndexes | None = None, + write_indexes: Sequence[int] | ReadWriteIndexes | None = None, + is_tma_store: bool = False, + ignore_if: IgnoreUnknownOp | None = None, +) -> None: + """Register a Triton op for kernel read/write analysis.""" + if is_tma_store and write_indexes is None: + raise AssertionError( + f"{name} is marked as a TMA store but has no write indexes" + ) + has_indexes = read_indexes is not None or write_indexes is not None + if ignore_if is not None and has_indexes: + raise AssertionError( + f"{name}: ignore_if cannot be combined with read/write indexes" + ) + _KERNEL_ACCESS_OPS[name] = _KernelAccessOpInfo( + read_indexes=( + None if read_indexes is None else _read_write_indexes(read_indexes) + ), + write_indexes=( + None if write_indexes is None else _read_write_indexes(write_indexes) + ), + is_tma_store=is_tma_store, + ignore_if=ignore_if, + ) + + +def unregister_kernel_access_op(name: str) -> None: + """ + Unregister a Triton op from kernel read/write analysis. + + This is mainly useful for tests and temporary backend registrations. It + does not reset memoized analysis, so direct analyze_kernel_access callers + must reset their own caches. + """ + _KERNEL_ACCESS_OPS.pop(name, None) + + +@MemoizeWithCycleCheck +def analyze_kernel_access( + functions: dict[str, dict[Intermediate, list[Op]]], + fn_name: str, + num_args: int, + tensor_names: tuple[str, ...], + tensor_arg_indices: frozenset[int] | None, +) -> TensorAccesses: + """ + Analyzes the graph to detect which arguments are written to and which are read. + + For writes: traverses from write sinks (tt.store, tt.atomic_cas, etc.) backwards + to identify input pointers that are written to. + + For reads: traverses from read operations (tt.load) backwards to identify + input pointers that are read from. + + Returns ReadWrites with StarDep objects for each accessed tensor. + """ + from torch._inductor.dependencies import Dep, ReadWrites, StarDep + + write_stack: list[Param | Intermediate] = [] + read_stack: list[Param | Intermediate] = [] + + ops = functions[fn_name] + tma_stores = get_tma_stores(functions, fn_name) + + for op_list in ops.values(): + for op in op_list: + # If we encounter an operation with effects that cannot be reliably analyzed + # (e.g. `tt.elementwise_inline_asm`), we assume it does not mutate any input parameters. + op_info = _KERNEL_ACCESS_OPS.get(op.name) + if op_info is not None and op_info.ignore_if is not None: + if op_info.ignore_if(op): + continue + raise RuntimeError( + f"ttir analysis hit an op we do not know how to analyze: {op.name}" + ) + + if op.name == "tt.experimental_tensormap_create": + # Note: this is how we implement experimental_descriptor_store mutation analysis. + # for on-device TMA. + # experimental_tensormap_store(a, b, ...) stores b to the location specified + # by descriptor in the memory of a. + # To track this, we first find all the intermediates/params to which we store via + # experimental_tensormap_store (get_tma_stores, called above). Then, during this + # analysis we wait to find the corresponding experimental_tensormap_create (if it + # exists), at which point we will mark the global_ptr as mutated (as done below). + if len(op.args) < 2: + raise AssertionError( + f"tt.experimental_tensormap_create expected at least 2 args, " + f"got {len(op.args)}" + ) + if op.args[0] in tma_stores: + write_stack.append(op.args[1]) + + if op.name == "tt.call": + if op.fn_call_name not in functions: + raise AssertionError( + f"Function {op.fn_call_name} not found in functions dict" + ) + # Create placeholder names for nested function arguments + nested_names = tuple(f"_arg{i}" for i in range(len(op.args))) + + # Do not pass tensor_arg_indices, most outer call of + # analyze_kernel_access will filter Param nodes. + accesses = analyze_kernel_access( + functions, + # pyrefly: ignore [bad-argument-type] + op.fn_call_name, + len(op.args), + nested_names, + None, + ) + # Map back from StarDep names to args + written_set = {dep.name for dep in accesses.read_writes.writes} + read_set = {dep.name for dep in accesses.read_writes.reads} + for arg, name in zip(op.args, nested_names): + if name in written_set: + write_stack.append(arg) + if name in read_set: + read_stack.append(arg) + else: + if op_info is not None and op_info.write_indexes is not None: + write_stack.extend( + op.args[idx] for idx in op_info.write_indexes(op) + ) + if op_info is not None and op_info.read_indexes is not None: + read_stack.extend(op.args[idx] for idx in op_info.read_indexes(op)) + + # For these ops, only the first argument (base pointer) refers to actual + # memory. The remaining arguments are shape/stride/offset metadata and + # should not be traced during mutation analysis. + POINTER_ONLY_OPS = { + "tt.make_tensor_ptr", + "tt.advance", + "tt.make_tensor_descriptor", + } + + def _find_arg_access_count( + initial_stack: list[Param | Intermediate], + skip_loads: bool, + ) -> dict[int, int]: + """DFS traversal to find argument indices that are accessed (and how many times they are accessed).""" + access_count = dict() + stack = initial_stack[:] + + while stack: + arg = stack.pop() + + if isinstance(arg, Param): + if arg.idx >= num_args: + continue + if tensor_arg_indices is not None and arg.idx not in tensor_arg_indices: + continue + if arg.idx not in access_count: + access_count[arg.idx] = 1 + else: + access_count[arg.idx] += 1 + elif isinstance(arg, Intermediate) and not arg.fake(): + for op in ops[arg]: + if skip_loads and op.name == "tt.load": + continue + if op.name in POINTER_ONLY_OPS: + stack.append(op.args[0]) + else: + stack.extend(op.args) + + return access_count + + write_count = _find_arg_access_count(write_stack, skip_loads=True) + read_count = _find_arg_access_count(read_stack, skip_loads=False) + + writes: OrderedSet[Dep] = OrderedSet( + StarDep(tensor_names[i]) for i in sorted(write_count.keys()) + ) + reads: OrderedSet[Dep] = OrderedSet( + StarDep(tensor_names[i]) for i in sorted(read_count.keys()) + ) + + read_writes = ReadWrites( + reads=reads, + writes=writes, + index_exprs=OrderedSet(), + ) + + def _decide_can_fuse_epilogue(): + # only do epilogue fusion if the kernel has a single output tensor + if len(write_count) != 1: + return False + + written_arg_index = next(iter(write_count)) + # only do epilogue fusion if the written tensor is written exactly once + if write_count[written_arg_index] != 1: + return False + + written_arg_name = next(iter(writes)).name + # cannot fuse if the kernel also reads from the output buffer + if any(read_dep.name == written_arg_name for read_dep in reads): + return False + + return True + + can_fuse_epilogue = _decide_can_fuse_epilogue() + + return TensorAccesses(read_writes=read_writes, can_fuse_epilogue=can_fuse_epilogue) + + +def identify_accessed_tensors( + kernel: "TritonKernelType", + kwargs: dict[str, Any], + tma_descriptor_metadata: TMADescriptorMetadata, +) -> TensorAccesses: + """ + Given a triton kernel and the arguments for this kernel, this function + 1) Retrieves the TTIR converted version of the kernel from Triton's API. + 2) Parses the TTIR and creates a control flow graph + 3) Analyzes the graph to detect which input tensors are read and/or written + """ + + from torch._inductor.dependencies import Dep, ReadWrites, StarDep + from torch._inductor.ir import TensorBox + + ttir_module = None + functions = None + try: + ttir_module, ordered_arg_names = generate_ttir( + kernel, kwargs, tma_descriptor_metadata + ) + + # extract functions from TTIR using MLIR bindings exposed by Triton code + functions = ttir_to_functions(ttir_module) + + if functions is None: + raise AssertionError("ttir_to_functions returned None") + kernel_name = next(iter(functions.keys())) + # Triton codegen modifies the name + # pyrefly: ignore [missing-attribute] + kernel_fn_name = kernel.fn.__name__ + if kernel_fn_name not in kernel_name: + raise AssertionError( + f"Kernel name {kernel_fn_name} not found in TTIR kernel name {kernel_name}" + ) + # Reset the cache between top level invocations + # The cache for analyze kernel access is mainly used for cycle + # detection, so each top level invocation needs a clean cache + analyze_kernel_access.reset() + get_tma_stores.reset() + + # Build frozenset of indices corresponding to tensor args only. + # Used to filter out scalars which are transitively captured as mutated + # during traversal. + tensor_arg_indices = frozenset( + i + for i, name in enumerate(ordered_arg_names) + if isinstance(kwargs.get(name), (Tensor, TensorBox)) + ) + + return analyze_kernel_access( + functions, + kernel_name, + len(ordered_arg_names), + tuple(ordered_arg_names), + tensor_arg_indices, + ) + except Exception: + log.warning( + "Encountered an exception in identify_accessed_tensors, assuming every input is mutated", + exc_info=True, + ) + if ttir_module is not None: + log.debug("TTIR:\n%s", ttir_module) + if functions is not None: + log.debug("functions:") + for name, fn in functions.items(): + log.debug("===\t%s\t===", name) + for ret, ops in fn.items(): + log.debug("%s\t=>\t%s", ret, ops) + + all_tensor_names = [ + key + for key, value in kwargs.items() + if isinstance(value, (Tensor, TensorBox)) + ] + all_deps = OrderedSet(StarDep(name) for name in all_tensor_names) + all_deps = typing.cast(OrderedSet[Dep], all_deps) + return TensorAccesses( + ReadWrites( + reads=all_deps, + writes=all_deps, + index_exprs=OrderedSet(), + ), + can_fuse_epilogue=False, + ) + + +@dataclasses.dataclass +class TritonStore: + store_node: ast.Call + store_pointer_node: ast.Expr + store_value_node: ast.Expr + + +@dataclasses.dataclass +class TritonStores: + stores: list[TritonStore] + + +@functools.cache +def identify_triton_stores(source_code: str) -> TritonStores: + """ + Parse Python source code of triton kernel and find all tl.store calls. + Returns a TritonStores object containing information about pointer, value, and mask. + + tl.store signature: store(pointer, value, mask=None, boundary_check=(), ...) + """ + return identify_triton_stores_from_ast(ast.parse(source_code)) + + +def identify_triton_stores_from_ast(tree: ast.Module) -> TritonStores: + stores = [] + + def _extract_arg(node, arg_name, positional_index): + """ + Extract an argument from a Call node, checking both positional and keyword args. + Returns the AST node for the argument, or None if not found. + """ + # Check positional args first + if len(node.args) > positional_index: + return node.args[positional_index] + + # Check keyword args + for keyword in node.keywords: + if keyword.arg == arg_name: + return keyword.value + + return None + + for node in ast.walk(tree): + if isinstance(node, ast.Call): + # Check if this is a tl.store call + if ( + isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) + and node.func.value.id == "tl" + and node.func.attr == "store" + ): + # Extract required arguments + pointer_node = _extract_arg(node, "pointer", 0) + value_node = _extract_arg(node, "value", 1) + + if pointer_node is None or value_node is None: + continue + + stores.append(TritonStore(node, pointer_node, value_node)) + + return TritonStores(stores=stores) + + +############################################################################### +# Triton Kernel Wrappers + + +class _TritonKernelWrapper(HigherOrderOperator): + def _get_overloaded_args( + self, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> tuple[Tensor, ...]: + overloaded_args = list(super()._get_overloaded_args(args, kwargs)) + triton_kwargs = kwargs.get("kwargs") + if isinstance(triton_kwargs, dict): + overloaded_args.extend( + arg + for arg in triton_kwargs.values() + if isinstance(arg, Tensor) and _dispatch_keys(arg).has("Python") + ) + return tuple(overloaded_args) + + +# Used for wrapping a Triton Kernel +class TritonKernelWrapperMutation(_TritonKernelWrapper): + def __init__(self) -> None: + super().__init__("triton_kernel_wrapper_mutation", cacheable=True) + + def __call__( + self, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, + ) -> Any: + hop_kwargs: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": kwargs, + } + if launch_kwargs: + hop_kwargs["launch_kwargs"] = launch_kwargs + + # pyrefly: ignore [missing-attribute] + return super().__call__(**hop_kwargs) + + +triton_kernel_wrapper_mutation = TritonKernelWrapperMutation() + + +# Used for wrapping a Triton Kernel in a functional manner +class TritonKernelWrapperFunctional(_TritonKernelWrapper): + def __init__(self) -> None: + super().__init__("triton_kernel_wrapper_functional", cacheable=True) + + def __call__( + self, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + tensors_to_clone: list[str], + launch_kwargs: tuple[str, ...] | None = None, + ) -> dict[str, Any]: + hop_kwargs: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": kwargs, + "tensors_to_clone": tensors_to_clone, + } + if launch_kwargs: + hop_kwargs["launch_kwargs"] = launch_kwargs + + # pyrefly: ignore [missing-attribute] + return super().__call__(**hop_kwargs) + + +triton_kernel_wrapper_functional = TritonKernelWrapperFunctional() + + +def get_kernel(kernel_idx: int) -> "TritonKernelType": + return kernel_side_table.get_kernel(kernel_idx) + + +@triton_kernel_wrapper_mutation.py_impl(DispatchKey.CompositeExplicitAutograd) +def triton_kernel_wrapper_mutation_dense( + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, +) -> None: + from torch._inductor.codegen.wrapper import user_defined_kernel_grid_fn_code + + kernel = kernel_side_table.get_kernel(kernel_idx) + constant_args = kernel_side_table.get_constant_args(constant_args_idx) + + if len(grid) == 1: + grid_fn = grid[0] + else: + fn_name, code = user_defined_kernel_grid_fn_code( + # pyrefly: ignore [missing-attribute] + kernel.fn.__name__, + # pyrefly: ignore [missing-attribute] + kernel.configs, + grid, + ) + namespace: dict[str, Any] = {} + exec(code, namespace) + grid_fn = namespace[fn_name] + + if tma_descriptor_metadata: + # as we need to launch the kernel here, we "unwrap" the + # tma_descriptor_metadata, create the TMA descriptors + # from it, and replace the tensors in the kwargs by the + # corresponding TMA descriptors before launching + kwargs = kwargs.copy() + for k, v in tma_descriptor_metadata.items(): + tensor = kwargs[k] + if (exp_meta := maybe_unpack_tma_experimental_metadata(v)) is not None: + from triton.tools.experimental_descriptor import ( + create_1d_tma_descriptor, + create_2d_tma_descriptor, + ) + + dims, block_dims, element_size = exp_meta + create_tma_descriptor = ( + create_1d_tma_descriptor + if len(dims) == 1 + else create_2d_tma_descriptor + ) + kwargs[k] = create_tma_descriptor( + tensor.data_ptr(), + *dims, + *block_dims, + element_size, + ) + else: + stable_meta = maybe_unpack_tma_stable_metadata(v) + if stable_meta is None: + raise AssertionError( + f"Failed to unpack stable TMA metadata for key {k}" + ) + from triton.tools.tensor_descriptor import TensorDescriptor + + block_shape = stable_meta[0] + + kwargs[k] = TensorDescriptor.from_tensor(tensor, block_shape) + + # move as many positional arguments from dicts to args as we + # can to circumvent the bug with the kwargs and pre_/post_hook: + # https://github.com/triton-lang/triton/issues/5082 + # TODO: remove this when the Triton issue above is fixed + args = [] + # copy kwargs and constant_args here to + # avoid mutating the original inputs + kwargs = kwargs.copy() + constant_args = constant_args.copy() + launch_kwargs = () if launch_kwargs is None else launch_kwargs + # pyrefly: ignore [missing-attribute] + for name in kernel.arg_names: + if name in launch_kwargs: + # Preserve the original kwarg form for launch kwargs. Triton's + # binder uses the kwarg to bind the kernel parameter, and + # _pack_args still exposes launch kwargs to backend.parse_options() + # so the same name may also be parsed as a compiler option. + # + # Stop positional packing entirely at this point. A later kernel + # parameter cannot be safely packed positionally after an earlier + # parameter is intentionally left in kwargs/constant_args; doing so + # would shift it into the wrong argument slot. Triton accepts the + # remaining parameters by keyword, so the only trade-off is that + # the triton#5082 workaround no longer applies after this first + # backend-option/kernel-parameter overlap. + break + if name in kwargs: + args.append(kwargs.pop(name)) + elif name in constant_args: + args.append(constant_args.pop(name)) + else: + break + + # pyrefly: ignore [bad-index, index-error] + kernel[grid_fn](*args, **kwargs, **constant_args) + + +@register_fake(triton_kernel_wrapper_mutation, skip_cache=True) +def triton_kernel_wrapper_mutation_fake_tensor_mode( + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, +) -> None: + return None + + +@triton_kernel_wrapper_mutation.py_impl(DispatchKey.Meta) +def _( + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, +) -> None: + return None + + +def trace_triton_kernel_wrapper( + proxy_mode: ProxyTorchDispatchMode, + func_overload: Callable[..., Any], + node_args: dict[str, Any], +) -> dict[str, Any] | None: + with disable_proxy_modes_tracing(): + out = func_overload(**node_args) + + proxy_args = pytree.tree_map( + proxy_mode.tracer.unwrap_proxy, # type: ignore[union-attr] + node_args, + ) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", + func_overload, + (), + proxy_args, + name=func_overload.__name__ + "_proxy", + ) + + ret = track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + return ret + + +@triton_kernel_wrapper_mutation.py_impl(ProxyTorchDispatchMode) +def triton_kernel_wrapper_mutation_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, +) -> None: + node_args: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": kwargs, + } + if launch_kwargs: + node_args["launch_kwargs"] = launch_kwargs + + trace_triton_kernel_wrapper( + mode, + triton_kernel_wrapper_mutation, + node_args, + ) + + return None + + +def get_mutated_tensors( + kernel_idx: int, + constant_args_idx: int, + kwargs: dict[str, Any], + tma_descriptor_metadata: TMADescriptorMetadata, +) -> list[str]: + kernel = kernel_side_table.get_kernel(kernel_idx) + constant_args = kernel_side_table.get_constant_args(constant_args_idx) + tensor_accesses = identify_accessed_tensors( + kernel, {**kwargs, **constant_args}, tma_descriptor_metadata + ) + # Filter to only tensor kwargs: with Triton 3.7+, ordered_arg_names + # includes scalars, so writes may reference non-tensor args like SymInts. + return [ + dep.name + for dep in tensor_accesses.read_writes.writes + if isinstance(kwargs.get(dep.name), Tensor) + ] + + +@triton_kernel_wrapper_mutation.py_functionalize_impl +def triton_kernel_wrapper_mutation_functionalize( + ctx: "BaseFunctionalizeAPI", + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, +) -> None: + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type] + # TODO(oulgen): Preexisting bug, if two kernel inputs are views of each + # other, and one gets mutated in kernel, and later another gets mutated, + # they are no longer equal. Fix this by graph breaking on this condition + # earlier in dynamo. + tensors_to_clone = get_mutated_tensors( + kernel_idx, constant_args_idx, unwrapped_kwargs, tma_descriptor_metadata + ) + with ctx.redispatch_to_next(): + functional_kwargs: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": unwrapped_kwargs, + "tensors_to_clone": tensors_to_clone, + } + if launch_kwargs: + functional_kwargs["launch_kwargs"] = launch_kwargs + unwrapped_outputs = triton_kernel_wrapper_functional(**functional_kwargs) + + if not set(unwrapped_outputs.keys()).issubset(set(kwargs.keys())): + raise AssertionError( + f"Output keys {set(unwrapped_outputs.keys())} not subset of input keys {set(kwargs.keys())}" + ) + for key, output_arg in unwrapped_outputs.items(): + if not isinstance(output_arg, Tensor): + continue + input_arg = kwargs[key] + if not isinstance(input_arg, Tensor): + raise AssertionError( + f"Expected input_arg for key {key} to be a Tensor, got {type(input_arg)}" + ) + + ctx.replace(input_arg, output_arg) + # indicate that above replace is hidden from autograd + ctx.mark_mutation_hidden_from_autograd(input_arg) + ctx.commit_update(input_arg) + ctx.sync(input_arg) + return None + + +@triton_kernel_wrapper_functional.py_impl(DispatchKey.CompositeExplicitAutograd) +def triton_kernel_wrapper_functional_dense( + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + tensors_to_clone: list[str], + launch_kwargs: tuple[str, ...] | None = None, +) -> dict[str, Any]: + # TODO(oulgen): For performance reasons, we want to ensure that these + # `clone_preserve_strides` calls are never executed at runtime + # (inductor should always optimize them away). + # Requires https://github.com/pytorch/pytorch/issues/109240 + kwargs = { + key: (clone_preserve_strides(val) if key in tensors_to_clone else val) + for key, val in kwargs.items() + } + mutation_kwargs: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": kwargs, + } + if launch_kwargs: + mutation_kwargs["launch_kwargs"] = launch_kwargs + triton_kernel_wrapper_mutation(**mutation_kwargs) + return {key: val for key, val in kwargs.items() if key in tensors_to_clone} + + +@register_fake(triton_kernel_wrapper_functional, skip_cache=True) +def triton_kernel_wrapper_functional_fake_tensor_mode( + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + tensors_to_clone: list[str], + launch_kwargs: tuple[str, ...] | None = None, +) -> dict[str, Any]: + # TODO(oulgen): For performance reasons, we want to ensure that these + # `clone_preserve_strides` calls are never executed at runtime + # (inductor should always optimize them away). + # Requires https://github.com/pytorch/pytorch/issues/109240 + return { + key: clone_preserve_strides(val) + for key, val in kwargs.items() + if key in tensors_to_clone + } + + +@triton_kernel_wrapper_functional.py_impl(ProxyTorchDispatchMode) +def triton_kernel_wrapper_functional_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + tensors_to_clone: list[str], + launch_kwargs: tuple[str, ...] | None = None, +) -> dict[str, Any]: + node_args: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": kwargs, + "tensors_to_clone": tensors_to_clone, + } + if launch_kwargs: + node_args["launch_kwargs"] = launch_kwargs + + ret = trace_triton_kernel_wrapper( + mode, + triton_kernel_wrapper_functional, + node_args, + ) + if ret is None: + raise AssertionError("trace_triton_kernel_wrapper returned None") + return ret + + +@triton_kernel_wrapper_functional.py_functionalize_impl +def triton_kernel_wrapper_functional_functionalize( + ctx: "BaseFunctionalizeAPI", + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + tensors_to_clone: list[str], + launch_kwargs: tuple[str, ...] | None = None, +) -> dict[str, Any]: + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type] + with ctx.redispatch_to_next(): + functional_kwargs: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": unwrapped_kwargs, + "tensors_to_clone": tensors_to_clone, + } + if launch_kwargs: + functional_kwargs["launch_kwargs"] = launch_kwargs + outputs = triton_kernel_wrapper_functional(**functional_kwargs) + return ctx.wrap_tensors(outputs) # type: ignore[return-value,arg-type] + + +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.PythonDispatcher) # type: ignore[attr-defined] +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.PythonTLSSnapshot) # type: ignore[attr-defined] +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.ADInplaceOrView) +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.BackendSelect) +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutocastCPU) # type: ignore[attr-defined] +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutocastCUDA) # type: ignore[attr-defined] +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutogradCUDA) +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutogradCPU) + +triton_kernel_wrapper_functional.fallthrough(DispatchKey.PythonDispatcher) # type: ignore[attr-defined] +triton_kernel_wrapper_functional.fallthrough(DispatchKey.PythonTLSSnapshot) # type: ignore[attr-defined] +triton_kernel_wrapper_functional.fallthrough(DispatchKey.ADInplaceOrView) +triton_kernel_wrapper_functional.fallthrough(DispatchKey.BackendSelect) +triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutocastCPU) # type: ignore[attr-defined] +triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutocastCUDA) # type: ignore[attr-defined] +triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutogradCUDA) +triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutogradCUDA) +triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutogradCPU) + +# Adds SAC support for triton ops +redirect_to_mode(triton_kernel_wrapper_mutation, _CachingTorchDispatchMode) +redirect_to_mode(triton_kernel_wrapper_mutation, _CachedTorchDispatchMode) + +############################################################################### +# The "TritonHOPifier": a class that transforms a call to a triton kernel into +# a call to the triton_kernel_wrapper_mutation HOP. + + +class TritonHOPifier: + """Orchestrator for converting a user-defined triton kernel into a call + to the triton_kernel_wrapper_mutation HOP. + + It has two main use cases. + + 1. When Dynamo sees a triton kernel, it wraps it into a TritonKernelVariable + and uses the TritonHOPifier to convert calls to the TritonKernelVariable + into a call to the HOP. + + 2. In order to capture a user-defined triton kernel while performing + tracing (via make_fx or non-strict export), a user must annotate their + triton kernel with the `wrap_triton` decorator. The decorator uses + TritonHOPifier to convert calls to the triton kernel into a call + to the HOP (which can then be traced). + + Because Dynamo has its own calling conventions for e.g. invoking a user-defined function + TritonHOPifier is an abstract class that can be overridden by its subclasses. + """ + + def raise_unsupported(self, msg: str) -> Never: + raise NotImplementedError("abstract method") + + def is_callable(self, maybe_callable: Any) -> bool: + raise NotImplementedError("abstract method") + + def get_value(self, val: Any) -> Any: + raise NotImplementedError("abstract method") + + def call_grid( # type: ignore[no-untyped-def] + self, + grid, + meta, + tx, + ) -> tuple[int | sympy.Expr | SymInt, ...] | tuple["Proxy", ...]: + raise NotImplementedError("abstract method") + + def wrap_user_defined_obj( + self, + user_obj: Any, + tx: Optional["InstructionTranslatorBase"], + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"] | None, + name: str, + ) -> Any: + raise NotImplementedError("abstract method") + + def call_user_defined_fn( + self, + user_fn: Callable[..., Any], + args: list, + kwargs: dict, + tx: Optional["InstructionTranslatorBase"], + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"] | None, + ) -> Any: + raise NotImplementedError("abstract method") + + def maybe_unpack_configs( + self, configs: list["TritonConfig"], tx: Optional["InstructionTranslatorBase"] + ) -> list["TritonConfig"]: + raise NotImplementedError("abstract method") + + def maybe_unpack_heuristic_result(self, result: Any) -> Any: + raise NotImplementedError("abstract method") + + @staticmethod + def do_prune_configs( # type: ignore[no-untyped-def] + autotuner: "TritonAutotunerType", + early_config_prune: Callable | None, + perf_model: Callable | None, + top_k: float, + configs: list, + named_args: dict, + kwargs: dict, + ) -> list["TritonConfig"]: + # Reimplement autotuner.prune_configs(...) here + # see: https://github.com/triton-lang/triton/blob/e57b46897191b3b3061c78d0d60e58e94be565b6/python/triton/runtime/autotuner.py + # We do this to avoid calling prune_configs, which in turn calls early_config_prune and perf_model + # These are both user-defined functions which can contain side effects, so we want to sandbox them in Dynamo + + if early_config_prune: + configs = early_config_prune(configs, named_args, **kwargs) + + if perf_model: + # we assert top_k is a float before calling this + if isinstance(top_k, float) and top_k <= 1.0: + top_k = int(len(configs) * top_k) + elif not isinstance(top_k, int): + """ + Slice index must be an integer, SupportsIndex or None + """ + raise TypeError( + "Error while pruning configs, top_k must be either 1) a float <= 1.0 or 2) an int" + ) + if len(configs) > top_k: + est_timing = [ + ( + config, + float( + perf_model(**named_args, **kwargs, **config.all_kwargs()) + ), + ) + for config in configs + ] + configs = [ + config[0] + for config in sorted(est_timing, key=operator.itemgetter(1))[:top_k] + ] + return configs + + def call_HOP( # type: ignore[no-untyped-def] + self, + variable, + grids, + combined_args: dict[str, Any], + launch_kwargs: tuple[str, ...], + kernel_arg_names: set[str], + tx, + ) -> Optional["ConstantVariable"]: + raise NotImplementedError("abstract method") + + def check_grid( # type: ignore[no-untyped-def] + self, grid + ) -> tuple[int | sympy.Expr | SymInt, ...] | tuple["Proxy", ...]: + raise NotImplementedError("abstract method") + + def init_variable( + self, + variable: Union["TraceableTritonKernelWrapper", "TritonKernelVariable"], + kernel: "TritonKernelType", + kernel_idx: int | None, + grid: Optional["TritonGridType"], + ) -> None: + from triton.runtime.autotuner import Autotuner + + if kernel is None: + raise AssertionError("kernel cannot be None") + + variable.kernel = kernel + variable.kernel_idx = kernel_side_table.add_kernel(kernel) + + if kernel_idx is not None and variable.kernel_idx != kernel_idx: + raise AssertionError( + f"kernel_idx mismatch: expected {kernel_idx}, got {variable.kernel_idx}" + ) + + # pyrefly: ignore [bad-assignment] + variable.grid = grid + + if isinstance(kernel, Autotuner): + import torch + import torch._dynamo + + # We only support configs, keys, and restore_value arguments + # of triton.autotune. Make sure other arguments are defaulted. + defaults = inspect.signature(Autotuner.__init__).parameters + # Newer version of triton change attribute name from warmup to num_warmup and rep to num_rep. + # The call to get_first_attr is to maintain backward-compatibility. + + def defaults_ok( + attr: str, alternates: tuple[str, ...], values: tuple[Any, ...] + ) -> bool: + if attr not in defaults: + return True + value = torch._dynamo.utils.get_first_attr(kernel, attr, *alternates) + if value == defaults[attr].default: + return True + return value in values + + if ( + not torch._inductor.config.unsafe_ignore_unsupported_triton_autotune_args + and ( + not defaults_ok("num_warmups", ("warmup",), (25, None)) + or not defaults_ok("num_reps", ("rep",), (100, None)) + or not defaults_ok("use_cuda_graph", (), (False,)) + ) + ): + self.raise_unsupported( + "Only configs, keys, restore_value, and reset_to_zero are supported for triton.autotune" + ) + if ( + not torch._inductor.config.unsafe_ignore_unsupported_triton_autotune_args + and ( + # pre_hook requires running arbitrary code at runtime, which we cannot handle at this time + # https://github.com/pytorch/pytorch/issues/139059 + # we can't support pre_hook or post_hook in user defined triton kernels at the moment, + # as they require the ability to execute code at runtime (AOTI can't support this) + ( + hasattr(kernel, "user_defined_pre_hook") + and kernel.user_defined_pre_hook is not False + ) + or ( + hasattr(kernel, "user_defined_post_hook") + and kernel.user_defined_post_hook is not False + ) + or ( + # Check Config passed to autotuner in configs + any(cfg.pre_hook is not None for cfg in kernel.configs) + ) + ) + ): + self.raise_unsupported( + "pre_hook and post_hook are not supported in triton.Autotune or triton.Config" + ) + + @staticmethod + def get_kernel_source( + variable: "TritonKernelVariable | TraceableTritonKernelWrapper", + ) -> "Source | None": + kernel_source = getattr(variable, "kernel_source", None) + if kernel_source is None: + kernel_source = getattr(variable, "source", None) + return kernel_source + + def recreate_variable( + self, + variable: "TritonKernelVariable | TraceableTritonKernelWrapper", + *, + kernel: "TritonKernelType", + kernel_idx: int | None, + grid: "TritonGridType | None", + ) -> "TritonKernelVariable | TraceableTritonKernelWrapper": + return type(variable)( + kernel=kernel, + kernel_idx=kernel_idx, + grid=grid, + kernel_source=self.get_kernel_source(variable), + ) + + def call_getitem( + self, + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"], + args: Sequence[Any], + ) -> Union["TritonKernelVariable", "TraceableTritonKernelWrapper"]: + # __getitem__ should only be called if we don't already have a grid + # Only grid needs to be passed + if variable.grid is not None or len(args) != 1: + self.raise_unsupported( + "Triton kernels should be called with only a single grid" + ) + + return self.recreate_variable( + variable, + kernel=variable.kernel, + kernel_idx=variable.kernel_idx, + grid=args[0], + ) + + def call_run( + self, + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"], + args: Sequence[Any], + kwargs: dict[str, Any], + tx: Optional["InstructionTranslatorBase"], + ) -> Optional["ConstantVariable"]: + if "grid" not in kwargs: + self.raise_unsupported("Triton kernel requires to be called with a grid") + grid = kwargs.pop("grid") + kwargs.pop("warmup", None) + # rewrite kernel.run(*args, grid=grid) to kernel[grid](*args) + return self.call_triton_kernel( + self.recreate_variable( + variable, + kernel=variable.kernel, + kernel_idx=variable.kernel_idx, + grid=grid, + ), + args, + kwargs, + tx, + ) + + def call_triton_kernel( + self, + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"], + args: Sequence[Any], + kwargs: dict[str, Any], + tx: Optional["InstructionTranslatorBase"], + ) -> Optional["ConstantVariable"]: + from triton import JITFunction + from triton.runtime.autotuner import autotune, Autotuner, Config, Heuristics + + # Check if num_ctas is in kwargs + if "num_ctas" in kwargs: + self.raise_unsupported( + "Passing num_ctas directly to the Triton kernel is not supported. " + "Please use a Config in @triton.autotune instead." + ) + + # Make sure the kernel has a grid + if variable.grid is None: + self.raise_unsupported("Triton kernels should always be called with a grid") + + # raise an exception if there are multiple @triton.autotune decorators + iter_kernel = variable.kernel + autotuner_count = 0 + while not isinstance(iter_kernel, JITFunction): + if isinstance(iter_kernel, Autotuner): + autotuner_count += 1 + if autotuner_count > 1: + self.raise_unsupported( + "Passing multiple @triton.autotune decorators is not supported. " + "Please use a single @triton.autotune decorator instead." + ) + + iter_kernel = iter_kernel.fn + + jit_arg_names = set(iter_kernel.arg_names) + + # Process the @triton.heuristics decorator: + # - We know there is only 1 autotuner decorator here + # - We can apply the heuristic to all triton.Configs in the order that the decorators appear + # This way, when the config is selected, the heuristics have already been applied. + # - Decorators that appear *before* the autotuner are already processed correctly + if isinstance(variable.kernel, Autotuner) and isinstance( + variable.kernel.fn, Heuristics + ): + # unwrap the heuristics decorator, we don't need it anymore + # variable.kernel ==> Autotuner + # variable.kernel.fn ==> Heuristics + # ... + # There can be arbitrarily many heuristics wrappers here! + # ... + # variable.kernel.fn ==> JITFunction + + # Copy the configs, we are going to be modifying them + new_configs = copy.deepcopy(variable.kernel.configs) + + named_args = dict(zip(variable.kernel.arg_names, args)) + + # Iterate through all of the heuristics wrappers that come after the autotune wrapper + iter_kernel = variable.kernel.fn + while isinstance(iter_kernel, Heuristics): + # For each config, apply the heuristic fn(s) + for config_idx in range(len(new_configs)): + for kwarg_key, heuristic_fn in iter_kernel.values.items(): + # Run heuristics on the combined configs + kwargs + heuristic_result = self.call_user_defined_fn( + heuristic_fn, + [ + { + **named_args, + **kwargs, + **new_configs[config_idx].__dict__["kwargs"], + }, + ], + {}, + tx, + variable, + ) + + # Update the kwargs in each config + # maybe_unpack_heuristic_result raises unsupported if the value is non-constant + new_configs[config_idx].__dict__["kwargs"][kwarg_key] = ( + self.maybe_unpack_heuristic_result(heuristic_result) + ) + + iter_kernel = iter_kernel.fn + if not isinstance(iter_kernel, JITFunction): + raise AssertionError( + f"Expected iter_kernel to be a JITFunction, got {type(iter_kernel)}" + ) + prune_configs_by = { + "perf_model": variable.kernel.perf_model, + "early_config_prune": variable.kernel.early_config_prune, + "configs_top_k": variable.kernel.configs_top_k, + } + new_kernel = autotune( + configs=new_configs, key=[], prune_configs_by=prune_configs_by + )(iter_kernel) + # create a new variable to contain the new (wrapped) kernel; + # skip kernel_idx to get a new record in the kernel side table + new_var = self.recreate_variable( + variable, + kernel=new_kernel, + kernel_idx=None, + grid=variable.grid, + ) + return self.call_triton_kernel(new_var, args, kwargs, tx) + + SPECIAL_CONFIG_NAMES = { + "num_warps", + "num_stages", + "num_ctas", + "num_consumer_groups", + "num_buffers_warp_spec", + "num_cpu_threads", + } + + # move special config names to configs out of kwargs + special_kwargs = {} + for name in SPECIAL_CONFIG_NAMES: + if name in kwargs: + # remove special kwargs from `kwargs` + val = kwargs.pop(name) + special_kwargs[name] = self.get_value(val) + + if special_kwargs: + if isinstance(variable.kernel, Autotuner): + # if there is Autotuner already, set + # special kwargs to each of its configs + new_configs = copy.deepcopy(variable.kernel.configs) + for config in new_configs: + config.__dict__.update(special_kwargs) + prune_configs_by = { + "perf_model": variable.kernel.perf_model, + "early_config_prune": variable.kernel.early_config_prune, + "configs_top_k": variable.kernel.configs_top_k, + } + + new_kernel = autotune( + configs=new_configs, key=[], prune_configs_by=prune_configs_by + )(variable.kernel.fn) + else: + # if there is no Autotuner, wrap the kernel into a + # new one with a single config with special kwargs + new_config = Config(kwargs={}, **special_kwargs) + + new_kernel = autotune(configs=[new_config], key=[])(variable.kernel) + + # create a new variable to contain the new (wrapped) kernel; + # skip kernel_idx to get a new record in the kernel side table + new_var = self.recreate_variable( + variable, + kernel=new_kernel, + kernel_idx=None, + grid=variable.grid, + ) + return self.call_triton_kernel(new_var, args, kwargs, tx) + + if isinstance(variable.kernel, Autotuner): + special_param_names = [] + for name in SPECIAL_CONFIG_NAMES: + if name in jit_arg_names: + special_param_names.append(name) + + if special_param_names: + # If the Triton kernel has SPECIAL_CONFIG_NAMES in parameters, those should + # be passed from the kernel configs: the behavior of Triton runtime is that + # those values get folded into the kernel arguments iff there are parameters + # with the same name. Normally the values of those parameters are defined + # outside the `kwargs` part of the autotuning configs. Here we move them to + # the `kwargs` part (if they're absent there) to facilitate passing them as + # arguments to the kernel downstream. + updated = False + new_configs = copy.deepcopy(variable.kernel.configs) + for config in new_configs: + for name in special_param_names: + if name not in config.__dict__["kwargs"]: + if name not in config.__dict__: + raise AssertionError( + f"{name} must be in autotuning configs to be used " + "as a kernel parameter" + ) + config.__dict__["kwargs"][name] = config.__dict__[name] + updated = True + + if updated: + prune_configs_by = { + "perf_model": variable.kernel.perf_model, + "early_config_prune": variable.kernel.early_config_prune, + "configs_top_k": variable.kernel.configs_top_k, + } + + new_kernel = autotune( + configs=new_configs, prune_configs_by=prune_configs_by, key=[] + )(variable.kernel.fn) + new_var = self.recreate_variable( + variable, + kernel=new_kernel, + kernel_idx=None, + grid=variable.grid, + ) + return self.call_triton_kernel(new_var, args, kwargs, tx) + + # These are the default values in upstream Triton + # see: https://github.com/triton-lang/triton/blob/e57b46897191b3b3061c78d0d60e58e94be565b6/python/triton/runtime/autotuner.py + default_perf_model = None + default_early_config_prune = None + + # run prune_configs_by + if isinstance(variable.kernel, Autotuner) and ( + variable.kernel.perf_model != default_perf_model + or variable.kernel.early_config_prune != default_early_config_prune + ): + # Prune the configs + named_args = dict(zip(variable.kernel.arg_names, args)) + + # The source information is important here so the guards are installed correctly + + wrapped_early_configs_prune = self.wrap_user_defined_obj( + variable.kernel.early_config_prune, + tx, + variable, + "early_config_prune", + ) + + wrapped_perf_model = self.wrap_user_defined_obj( + variable.kernel.perf_model, tx, variable, "perf_model" + ) + + wrapped_configs_top_k = self.wrap_user_defined_obj( + variable.kernel.configs_top_k, tx, variable, "configs_top_k" + ) + + wrapped_configs = self.wrap_user_defined_obj( + variable.kernel.configs, tx, variable, "configs" + ) + + pruned_configs = self.call_user_defined_fn( + self.do_prune_configs, + [ + variable, + wrapped_early_configs_prune, + wrapped_perf_model, + wrapped_configs_top_k, + wrapped_configs, + named_args, + kwargs, + ], + {}, + tx, + variable, + ) + + pruned_configs = self.maybe_unpack_configs(pruned_configs, tx) + + # after pruning the configs, create a new autotuner object with + # these configs and recurse. + new_kernel = autotune(configs=pruned_configs, key=[])(variable.kernel.fn) + # create a new variable to contain the new (wrapped) kernel; + # skip kernel_idx to get a new record in the kernel side table + new_var = self.recreate_variable( + variable, + kernel=new_kernel, + kernel_idx=None, + grid=variable.grid, + ) + return self.call_triton_kernel(new_var, args, kwargs, tx) + + # Triton passes launch kwargs to backend.parse_options(), even when a + # kwarg also binds a kernel parameter. Preserve the launch-site names; + # values stay in combined_args_raw so Inductor materializes backend + # options only after the target backend is known. + launch_kwargs = tuple(kwargs) + + if isinstance(variable.kernel, Autotuner): + config_kwarg_names = set().union( + *(set(config.kwargs) for config in variable.kernel.configs) + ) + config_conflicts = sorted(set(launch_kwargs) & config_kwarg_names) + if config_conflicts: + self.raise_unsupported( + "Triton launch kwargs conflict with autotune config kwargs: " + f"{config_conflicts!r}." + ) + + positional_arg_names = iter_kernel.arg_names[: len(args)] + if len(args) > len(iter_kernel.arg_names): + self.raise_unsupported( + f"{iter_kernel.__name__}() takes {len(iter_kernel.arg_names)} " + f"positional arguments but {len(args)} were given" + ) + + duplicate_kwargs = sorted(set(positional_arg_names) & set(kwargs)) + if duplicate_kwargs: + self.raise_unsupported( + f"{iter_kernel.__name__}() got multiple values for argument " + f"{duplicate_kwargs[0]!r}" + ) + + # Both for grid's meta as well as for the kernel, we need combined + # args and launch kwargs combined and normalized. Non-signature launch + # kwargs are included here so Inductor can later recover their values + # when materializing target-specific backend options. + + combined_args_raw = {**dict(zip(iter_kernel.arg_names, args)), **kwargs} + + # precompute the grid for the kernel + configs = ( + [config.kwargs for config in variable.kernel.configs] + if isinstance(variable.kernel, Autotuner) + else [{}] + ) + grids = [] + for config_args in configs: + # If the grid is a function, then lets execute it and convert it to + # a list + grid = variable.grid + if grid is None: + raise AssertionError("grid cannot be None at this point") + if self.is_callable(grid): + # Populate the special "meta" argument to call the grid function + meta = {**combined_args_raw, **config_args} + grid = self.call_grid(grid, meta, tx) # type: ignore[arg-type] + grids.append(self.check_grid(grid)) + + for i in range(len(grids)): + if not isinstance(grids[i], tuple): + self.raise_unsupported("Only tuple grids are supported") + # inductor expects all grids to be 3-tuple so lets make it + if len(grids[i]) == 1: + grids[i] = (grids[i][0], 1, 1) + elif len(grids[i]) == 2: + grids[i] = (grids[i][0], grids[i][1], 1) + elif len(grids[i]) > 3: + self.raise_unsupported("Grid can have at most rank 3") + + if len(grids) == 0: + raise AssertionError("grids cannot be empty") + if isinstance(variable.kernel, JITFunction): + constexprs = [p.num for p in variable.kernel.params if p.is_constexpr] + arg_names = [p.name for p in variable.kernel.params] + else: + # If we are looking at an @triton.autotune decorator, the nested function should be a JITFunction + # This is because we don't support @triton.heuristics or nested @triton.autotune decorators yet + if not isinstance(variable.kernel, Autotuner): + raise AssertionError( + f"Expected variable.kernel to be an Autotuner, got {type(variable.kernel)}" + ) + constexprs = [p.num for p in variable.kernel.fn.params if p.is_constexpr] + arg_names = [p.name for p in variable.kernel.fn.params] + + for idx, arg_name in enumerate(arg_names): + if idx in constexprs: + if arg_name in combined_args_raw: + # [Note: Specialize tl.constexpr args in user-defined triton kernels] + # This arg is marked as tl.constexpr. That means that triton will recompile every time + # this value changes. + # https://github.com/pytorch/pytorch/issues/136504 + # One option is to correctly pass the symints in so that the symbolic expressions are defined + # when the triton code is being executed. + # But since triton will have to recompile either way, we instead just specialize on the value. + # + # Depending on the type of `variable` we might expect different types for the symbolic args: + # either SymNodeVariables (for TritonKernelVariables) or SymInts (TracingTritonKernelWrapper) + combined_args_raw[arg_name] = variable.specialize_symbolic( + combined_args_raw[arg_name] + ) + return self.call_HOP( + variable, grids, combined_args_raw, launch_kwargs, jit_arg_names, tx + ) + + +############################################################################### +# Helpers for wrap_triton API that makes a user-defined triton kernel traceable into +# a graph via make_fx or non-strict export (coming soon) + + +class TracingTritonHOPifier(TritonHOPifier): + def raise_unsupported(self, msg: str) -> Never: + raise RuntimeError(msg) + + def is_callable(self, maybe_callable: Any) -> bool: + return callable(maybe_callable) + + def get_value(self, val: Any) -> Any: + return val + + def call_grid( + self, + grid: "TritonGridCallableType", + meta: "TritonMetaParamsType", + tx: None, + ) -> tuple[int | sympy.Expr | SymInt, ...]: + if tx is not None: + raise AssertionError("tx must be None for TracingTritonHOPifier") + if not isinstance(meta, dict): + raise AssertionError(f"meta must be a dict, got {type(meta)}") + if not callable(grid): + raise AssertionError(f"grid must be callable, got {type(grid)}") + return grid(meta) + + def wrap_user_defined_obj( + self, + user_obj: Any, + tx: Optional["InstructionTranslatorBase"], + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"] | None, + name: str, + ) -> Any: + if tx is not None: + raise AssertionError("tx must be None for TracingTritonHOPifier") + return user_obj + + def call_user_defined_fn( + self, + user_fn: Callable[..., Any], + args: list, + kwargs: dict, + tx: Optional["InstructionTranslatorBase"], + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"] | None, + ) -> Any: + if not isinstance(args, list): + raise AssertionError(f"args must be a list, got {type(args)}") + if not isinstance(kwargs, dict): + raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}") + if not callable(user_fn): + raise AssertionError(f"user_fn must be callable, got {type(user_fn)}") + return user_fn(*args, **kwargs) + + def maybe_unpack_configs( + self, configs: list["TritonConfig"], tx: Optional["InstructionTranslatorBase"] + ) -> list["TritonConfig"]: + if not isinstance(configs, list): + raise AssertionError(f"configs must be a list, got {type(configs)}") + return configs + + def maybe_unpack_heuristic_result(self, result: Any) -> Any: + return result + + def check_grid( + self, + grid: "TritonGridType", + ) -> tuple[int | sympy.Expr | SymInt, ...]: + if not isinstance(grid, collections.abc.Sequence): + raise RuntimeError( + "wrap_triton can only handle grids that resolve to Sequence[int]." + ) + # normalize to tuple + return tuple(grid) + + def store_non_graphable_args( + self, + combined_args: dict[str, Any], + ) -> tuple[dict, int]: + """ + Some args cannot be stored in the FX graph. + Put them in the side table. + """ + + def is_graphable(val: Any) -> bool: + return isinstance(val, (fx.node.base_types, fx.Node)) + + non_graphable_args = { + k: v for k, v in combined_args.items() if not is_graphable(v) + } + graphable_args = {k: v for k, v in combined_args.items() if is_graphable(v)} + + constant_args_idx = kernel_side_table.add_constant_args(non_graphable_args) + + return graphable_args, constant_args_idx + + def is_dynamic_backend_option(self, value: Any) -> bool: + # Backend options are compile-time values. In proxy tracing, a value can + # be a Proxy/Node directly or be nested inside a tuple/list option such + # as backend_option=(sym_size,). Reject those unless the name is later + # identified as a real kernel parameter. + leaves, _ = pytree.tree_flatten(value) + return any( + isinstance( + leaf, + ( + fx.Node, + fx.Proxy, + Tensor, + SymInt, + SymBool, + SymFloat, + ), + ) + for leaf in leaves + ) + + def call_HOP( + self, + variable: "TraceableTritonKernelWrapper", + grids: list["TritonGridTupleType"], + combined_args: dict[str, Any], + launch_kwargs: tuple[str, ...], + kernel_arg_names: set[str], + tx: None, + ) -> None: + if tx is not None: + raise AssertionError("tx must be None for TracingTritonHOPifier") + if not isinstance(variable, TraceableTritonKernelWrapper): + raise AssertionError( + f"Expected TraceableTritonKernelWrapper, got {type(variable)}" + ) + + graphable_args, constant_args_idx = self.store_non_graphable_args(combined_args) + # launch_kwargs records the names passed as kwargs at the Triton launch + # site. A non-kernel launch kwarg can only be a compiler option, so it + # must be concrete before entering the graph. Kernel launch kwargs may + # also be compiler options, but that target-specific check happens in + # Inductor after backend.parse_options(). + non_const_options = [ + k + for k in launch_kwargs + if k not in kernel_arg_names + and self.is_dynamic_backend_option(combined_args[k]) + ] + if non_const_options: + self.raise_unsupported( + "Triton backend options must be concrete values: " + f"{sorted(non_const_options)!r}." + ) + + if not isinstance(variable.kernel_idx, int): + raise AssertionError( + f"kernel_idx must be an int, got {type(variable.kernel_idx)}" + ) + return triton_kernel_wrapper_mutation( + kernel_idx=variable.kernel_idx, + constant_args_idx=constant_args_idx, + grid=grids, # type: ignore[arg-type] + # TMA descriptor capturing not yet + # supported in non-dynamo tracing + tma_descriptor_metadata={}, + kwargs=graphable_args, + launch_kwargs=launch_kwargs, + ) + + +tracing_triton_hopifier_singleton = TracingTritonHOPifier() + + +class TraceableTritonKernelWrapper: + kernel: "TritonKernelType" + kernel_idx: int | None + grid: Optional["TritonGridType"] + kernel_source: "Source | None" + + def __init__( + self, + kernel: "TritonKernelType", + kernel_idx: int | None, + grid: Optional["TritonGridType"], + kernel_source: "Source | None" = None, + ) -> None: + self.kernel = None + self.grid = None + self.kernel_source = kernel_source + tracing_triton_hopifier_singleton.init_variable(self, kernel, kernel_idx, grid) + if self.kernel is None: + raise AssertionError("kernel was not initialized properly") + + def __getitem__(self, *args: Sequence[Any]) -> "TraceableTritonKernelWrapper": + return tracing_triton_hopifier_singleton.call_getitem(self, args) # type: ignore[return-value] + + def run(self, *args: Sequence[Any], **kwargs: dict[str, Any]) -> Any: + from torch._library.triton import is_wrap_triton_enabled + + if is_wrap_triton_enabled(): + return tracing_triton_hopifier_singleton.call_run(self, args, kwargs, None) + else: + if self.kernel is None: + raise AssertionError("kernel cannot be None") + # pyrefly: ignore [missing-attribute] + return self.kernel.run(*args, **kwargs) + + def __call__(self, *args: Sequence[Any], **kwargs: dict[str, Any]) -> Any: + from torch._library.triton import is_wrap_triton_enabled + + if is_wrap_triton_enabled(): + return tracing_triton_hopifier_singleton.call_triton_kernel( + self, args, kwargs, None + ) + else: + if self.kernel is None: + raise AssertionError("kernel cannot be None") + # pyrefly: ignore [bad-index, index-error] + return self.kernel[self.grid](*args, **kwargs) + + def specialize_symbolic(self, arg: Sequence[Any]) -> Any: + import torch + + # See [Note: Specialize tl.constexpr args in user-defined triton kernels] + if isinstance(arg, (torch.SymInt, torch.SymBool, torch.SymFloat)): + return guard_scalar(arg) + return arg diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/utils.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..57dc8115395e2e76cb62dd9210afd551a2d5497c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/utils.py @@ -0,0 +1,1498 @@ +# mypy: allow-untyped-defs +import contextlib +import functools +from collections.abc import Callable, Iterable, Mapping, Sequence +from contextlib import AbstractContextManager, contextmanager, ExitStack, nullcontext +from dataclasses import dataclass +from typing import Any, overload, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch.fx.traceback as fx_traceback +import torch.utils._pytree as pytree +from torch._dispatch.python import suspend_functionalization +from torch._guards import detect_fake_mode +from torch._higher_order_ops.schema import HopSchema +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch._ops import HigherOrderOperator, OperatorBase, OpOverload +from torch._subclasses.fake_tensor import ( + FakeTensor, + is_fake_tensor, + maybe_get_fake_mode, +) +from torch._subclasses.functional_tensor import ( + disable_functional_mode, + FunctionalTensor, +) +from torch.fx.experimental.proxy_tensor import ( + _temp_remove_metadata_torch_function_mode, + disable_proxy_modes_tracing, + make_fx, +) +from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts +from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + +@dataclass +class UnsupportedAliasMutationException(RuntimeError): + reason: str + + +def autograd_not_implemented_inner( + operator: OperatorBase, delayed_error: bool, *args: Any, **kwargs: Any +) -> Any: + """If autograd is enabled and any of the arguments require grad this will either + raise an error or return a DelayedError depending on the value of delayed. + + Args: + operator: The Operator to call with the *args and **kwargs with + op_name: The name of the Operator + delayed_error: If True, return a DelayedError instead of raising an error + args: The flattened operands to the Operator + kwargs: The keyword arguments to the Operator + + Raises: + RuntimeError: If autograd is enabled and any of the arguments to the Operator + """ + with torch._C._AutoDispatchBelowAutograd(): + result = operator(*args, **kwargs) + flat_operands = pytree.arg_tree_leaves(*args) + if torch.is_grad_enabled() and any( + f.requires_grad for f in flat_operands if isinstance(f, torch.Tensor) + ): + if delayed_error: + err_fn = torch._C._functions.DelayedError( + f"Autograd not implemented for {str(operator)}", + 1, + ) + + def fake_requires_grad(tensor): + if torch.is_floating_point(tensor) or torch.is_complex(tensor): + tensor = tensor.detach() + tensor.requires_grad = True + return tensor + + return pytree.tree_map_only( + torch.Tensor, lambda x: err_fn(fake_requires_grad(x)), result + ) + else: + raise RuntimeError(f"Autograd not implemented for {str(operator)}") + return result + + +def autograd_not_implemented(op: OperatorBase, deferred_error: bool) -> Callable: + def inner(*args, **kwargs): + return autograd_not_implemented_inner(op, deferred_error, *args, **kwargs) + + return inner + + +def _maybe_run_with_interpreter(fn): + maybe_interpreted_fn = fn + if isinstance(fn, torch.fx.GraphModule) and fx_traceback.has_preserved_node_meta(): + # Running graph with interpreter is needed for propagating the stack_trace + def graph_with_interpreter(*args): + with fx_traceback.preserve_node_meta(): + return torch.fx.Interpreter(fn).run(*args) + + maybe_interpreted_fn = graph_with_interpreter + return maybe_interpreted_fn + + +def _hop_compile_and_call(fn, args, kwargs=None): + """Compile and call fn with fullgraph=True for HOP eager execution. + + Pre-activates the fullgraph counter so that compile_wrapper treats this as + a nested compile. This avoids erroring when a non-infra dispatch mode + causes the frame to be skipped — the function still executes eagerly within + compile_wrapper and returns normally. + """ + from torch._dynamo.eval_frame import set_fullgraph_compiled_frame_count + + with setup_compilation_env() as backend: + old_count = set_fullgraph_compiled_frame_count(0) + try: + return torch.compile(fn, backend=backend, fullgraph=True)( + *args, **(kwargs or {}) + ) + finally: + set_fullgraph_compiled_frame_count(old_count) + + +def _maybe_compile_and_run_fn(fn, *args): + if not torch.compiler.is_dynamo_compiling(): + return _hop_compile_and_call(fn, args) + else: + return fn(*args) + + +def reenter_make_fx(fn, subgraph_decomp_table=None): + from torch.fx.experimental.proxy_tensor import _CURRENT_MAKE_FX_TRACER + + @functools.wraps(fn) + def wrapped(*args): + if _CURRENT_MAKE_FX_TRACER is None: + raise AssertionError( + "Cannot reenter make_fx when we're not under a make_fx tracing session" + ) + if subgraph_decomp_table is None: + gm = _CURRENT_MAKE_FX_TRACER.trace_subgraph( + _maybe_run_with_interpreter(fn), *args + ) + else: + gm = _CURRENT_MAKE_FX_TRACER.trace_subgraph_custom_decomp( + _maybe_run_with_interpreter(fn), subgraph_decomp_table, *args + ) + + return gm + + return wrapped + + +def _maybe_reenter_make_fx(fn, subgraph_decomp_table=None): + from torch.fx.experimental.proxy_tensor import _CURRENT_MAKE_FX_TRACER + + if _CURRENT_MAKE_FX_TRACER is not None: + return reenter_make_fx(fn, subgraph_decomp_table=subgraph_decomp_table) + else: + + def _maybe_make_fx_with_fake_mode(fn): + @functools.wraps(fn) + def wrapped(*args): + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(args) + if fake_mode is None: + # we creaeta a fake_mode here to make sure we could + # trace the graph with data-dependent calls e.g. .item() + return make_fx( + fn, + tracing_mode="fake", + decomposition_table=subgraph_decomp_table, + )(*args) + # Tracing with real if all inputs have been fakfied + return make_fx(fn, decomposition_table=subgraph_decomp_table)(*args) + + return wrapped + + return _maybe_make_fx_with_fake_mode(fn) + + +def check_meta_consistency( + lhs_list: list[torch.Tensor | torch.SymInt | int], + rhs_list: list[torch.Tensor | torch.SymInt | int], + lhs_name: str, + rhs_name: str, + include_contiguity: bool = True, +) -> None: + def diff_meta_pairs( + lhs_list: list[torch.Tensor | torch.SymInt | int], + rhs_list: list[torch.Tensor | torch.SymInt | int], + ) -> list[str]: + def diff_meta( + lhs: torch.Tensor | torch.SymInt | int, + rhs: torch.Tensor | torch.SymInt | int, + ) -> str: + if isinstance(lhs, torch.Tensor) and isinstance(rhs, torch.Tensor): + return ", ".join( + diff_tensor_meta( + _extract_tensor_metadata( + lhs, include_contiguity=include_contiguity + ), + _extract_tensor_metadata( + rhs, include_contiguity=include_contiguity + ), + check_grad=False, + ) + ) + else: + + def _both_int_types(lhs, rhs): + return isinstance(lhs, (int, torch.SymInt)) and isinstance( + rhs, (int, torch.SymInt) + ) + + def _both_tensor(lhs, rhs): + return isinstance(lhs, torch.Tensor) and isinstance( + rhs, torch.Tensor + ) + + if not _both_int_types(lhs, rhs) and not _both_tensor(lhs, rhs): + return f"type: {lhs} vs {rhs}" + + return "" + + # Manually check the device of lhs and rhs as this field is currently not part of TensorMetadata + def diff_device( + lhs: torch.Tensor | torch.SymInt | int, + rhs: torch.Tensor | torch.SymInt | int, + ) -> str: + if isinstance(lhs, torch.Tensor) and isinstance(rhs, torch.Tensor): + if ( + rhs.device.type == lhs.device.type + and rhs.device.index == lhs.device.index + ): + return "" + else: + return "device" + return "" + + if len(lhs_list) != len(rhs_list): + raise torch._dynamo.exc.UncapturedHigherOrderOpError( + f"Expected {lhs_name} and {rhs_name} to have same number of outputs but got lhs:{lhs_list} and rhs:{rhs_list}" + ) + all_diffs = [] + for i, (lhs, rhs) in enumerate(zip(lhs_list, rhs_list)): + if diff := diff_meta(lhs, rhs): + all_diffs.append( + f"pair[{i}] differ in {diff}, where lhs is {lhs} and rhs is {rhs}" + ) + if diff := diff_device(lhs, rhs): + all_diffs.append( + f"pair[{i}] differ in {diff}, where lhs is {lhs} and rhs is {rhs}" + ) + return all_diffs + + if all_diffs := diff_meta_pairs(lhs_list, rhs_list): + diff_str = "\n".join(all_diffs) + raise torch._dynamo.exc.UncapturedHigherOrderOpError( + f"Expected {lhs_name} and {rhs_name} to have same metadata but found:\n{diff_str}" + ) + + +# Thread-local flag to indicate we're inside HOP internal compilation +import threading + + +_hop_compile_tls = threading.local() + + +def _in_hop_compile() -> bool: + return getattr(_hop_compile_tls, "in_hop_compile", False) + + +@contextmanager +def setup_compilation_env(): + """ + Context manager that sets up proper environment and backend when invoking torch.compile + inside torch.export region or inside HOP. + """ + from torch._dynamo.backends.debugging import ( + make_eager_backend_with_torch_function_modes, + ) + from torch._dynamo.backends.registry import lookup_backend + from torch.fx.experimental.proxy_tensor import ( + _temp_remove_pre_dispatch_torch_function_mode, + ) + + old_in_hop_compile = getattr(_hop_compile_tls, "in_hop_compile", False) + _hop_compile_tls.in_hop_compile = True + try: + with ( + _set_compilation_env(), + torch._dynamo.utils.disable_cache_limit(), + _temp_remove_pre_dispatch_torch_function_mode() as pre_dispatch_mode, + _temp_remove_metadata_torch_function_mode() as metadata_mode, + ): + modes = [ + mode for mode in (pre_dispatch_mode, metadata_mode) if mode is not None + ] + if modes: + yield make_eager_backend_with_torch_function_modes(modes) + else: + yield lookup_backend("eager") + finally: + _hop_compile_tls.in_hop_compile = old_in_hop_compile + + +@contextmanager +def _set_compilation_env(): + _old_is_tracing = torch.fx._symbolic_trace._get_is_fx_tracing() + _old_allow_empty_graphs = torch._dynamo.config.allow_empty_graphs + _old_capture_scalar_outputs = torch._dynamo.config.capture_scalar_outputs + # The issue is tracked in https://github.com/pytorch/pytorch/issues/144360: when dynamo finds + # the top-level frame produces no graph, the default behavior is to fallback to eager. + # Then when it encounters an inner function, it will try to trace that function again, which is unnecessary. + # For while_loop, during inspecting the inner call, we trace into the python dispatcher + # logic, which is not tracable as of today. So the proper fix can be either 1. allow dispatch + # logic to be dynamo tracable or 2. fixing https://github.com/pytorch/pytorch/issues/144360. + # but it exposes some bugs in existing tests so we have to have a temporary flag to control + # the behavior, which allows dynamo to store an empty graph for a frame without falling back to eager + try: + # We need to turn off the is_fx_tracing_flag. Remove this flag check from dynamo + # once we are confident fx tracing works with dynamo. + torch.fx._symbolic_trace._set_is_fx_tracing(False) + # pyrefly: ignore [bad-assignment] + torch._dynamo.config.allow_empty_graphs = True + torch._dynamo.config.capture_scalar_outputs = True + yield + finally: + torch.fx._symbolic_trace._set_is_fx_tracing(_old_is_tracing) + torch._dynamo.config.allow_empty_graphs = _old_allow_empty_graphs + torch._dynamo.config.capture_scalar_outputs = _old_capture_scalar_outputs + + +# The invariant here is that we always trace the branch with fake tensor +def _maybe_fake_tracing(fn, inputs: list[Any], pre_dispatch): + fake_mode_det = None + for inp in pytree.tree_leaves(inputs): + if is_fake_tensor(inp): + fake_mode_det = maybe_get_fake_mode(inp) + break + + fake_mode: AbstractContextManager = nullcontext() + tracing_mode = "fake" + if fake_mode_det is not None: + fake_mode = fake_mode_det + tracing_mode = "real" + + # Note: we need to turn off proxy tensor mode to avoid tracing infra + # code that happens in make_fx e.g. we now call as_strided when wrapping tensor + # as fake tensor. + with fake_mode, disable_proxy_modes_tracing(): + gm = make_fx( + fn, + tracing_mode=tracing_mode, + pre_dispatch=pre_dispatch, + _error_on_data_dependent_ops=False, + )(*inputs) + if not isinstance(fake_mode, nullcontext) and fake_mode.shape_env is not None: # type: ignore[attr-defined] + insert_deferred_runtime_asserts( + gm, + fake_mode.shape_env, # type: ignore[attr-defined] + "hoo_maybe_fake_tracing", + export=True, # type: ignore[attr-defined] + ) + return gm + + +def potential_input_alias_or_mutation(gm, inputs, pre_dispatch=False): + try: + gm = _maybe_fake_tracing(gm, inputs, pre_dispatch) + except UnsupportedAliasMutationException: + # this can happen when nested cond_op is + # functionalized + return True + except Exception as e: + raise e + + example_inputs = [ + ph.meta.get("val", None) for ph in gm.graph.find_nodes(op="placeholder") + ] + ( + inp_inp_alias_map, + inp_out_alias_map, + out_out_alias_map, + inp_mutation, + ) = check_input_alias_and_mutation(gm, example_inputs) + return (inp_inp_alias_map, inp_out_alias_map, out_out_alias_map), inp_mutation + + +def analyze_potential_input_alias_or_mutation(name, aliases, input_mutations): + if any(len(a) > 0 for a in aliases): + # TODO: Investigate here further which node is exactly aliasing + raise RuntimeError( + f"{name} where aliases appear. " + + f"In particular, these inputs \ + {set(el for el_map in aliases if len(el_map.keys()) > 0 for el in el_map)} " # noqa: C401 + + "get aliased. Please ensure that this doesn't happen." + ) + if len(input_mutations): + # TODO: Investigate here further which node is exactly mutating the inputs + raise RuntimeError( + f"{name} where the inputs are mutated. " + + f"In particular, these nodes are mutating the inputs \ + {set(el for el in input_mutations)}." # noqa: C401 + + "Please ensure that this doesn't happen." + ) + + +def _has_potential_branch_input_mutation(gm, inputs, pre_dispatch=False): + ( + (_, _, _), + inp_mutation, + ) = potential_input_alias_or_mutation(gm, inputs, pre_dispatch) + + return len(inp_mutation) > 0 + + +def has_potential_input_alias_or_mutation(gm, inputs, pre_dispatch=False): + ( + ( + inp_inp_alias_map, + inp_out_alias_map, + out_out_alias_map, + ), + inp_mutation, + ) = potential_input_alias_or_mutation(gm, inputs, pre_dispatch) + return ( + any( + ( + len(inp_inp_alias_map) > 0, + len(inp_out_alias_map) > 0, + len(out_out_alias_map) > 0, + ) + ), + len(inp_mutation) > 0, + ) + + +def _collect_fake_inputs(inputs): + from torch._subclasses.fake_tensor import FakeTensor + + # Get the example values of the inputs. + inputs_fake: list[FakeTensor | torch.Tensor | int] = [] + for inp in inputs: + if isinstance(inp, (torch.fx.proxy.Proxy, torch.fx.node.Node)): + inp = inp.node if isinstance(inp, torch.fx.proxy.Proxy) else inp + if hasattr(inp, "meta"): + val = inp.meta["example_value"] + if isinstance(val, torch.Tensor): + if torch._C._functorch.is_batchedtensor( + val + ) or torch._C._functorch.is_functionaltensor(val): + # This case is for batched or functional tensors + # Unwrap the tensors + while torch._C._functorch.is_batchedtensor( + val + ) or torch._C._functorch.is_functionaltensor(val): + val = torch._C._functorch.get_unwrapped(val) + if not is_fake_tensor(val): + raise AssertionError( + f"Expected FakeTensor after unwrapping, got {type(val)}" + ) + inputs_fake.append(val) + elif is_traceable_wrapper_subclass(val): + for attr_name in val.__tensor_flatten__()[0]: + unwrapped_input = getattr(val, attr_name) + if not isinstance(unwrapped_input, torch.Tensor): + continue + if not is_fake_tensor(unwrapped_input): + raise AssertionError( + f"Expected FakeTensor after unwrapping, got {type(unwrapped_input)}" + ) + inputs_fake.append(unwrapped_input) + else: + # This is the standard case of a TensorVariable + if not is_fake_tensor(val): + raise AssertionError( + f"Expected FakeTensor, got {type(val)}" + ) + inputs_fake.append(val) + else: + # This case is for SymInts and other non-Tensor elements + if isinstance(val, torch.Tensor): + raise AssertionError(f"Expected non-Tensor, got {type(val)}") + inputs_fake.append(val) + else: + # This case is for ints + if not isinstance(inp, int): + raise AssertionError(f"Expected int, got {type(inp)}") + inputs_fake.append(inp) + + return inputs_fake + + +def _check_alias_and_mutation(graph_module, inputs_fake, name, pre_dispatch): + aliases, inp_mutation = has_potential_input_alias_or_mutation( + graph_module, inputs_fake, pre_dispatch=pre_dispatch + ) + if aliases: + raise RuntimeError(f"{name} might be aliasing the input or the output!") + if inp_mutation: + raise RuntimeError(f"{name} might be modifying the input!") + + +def unique_graph_id(proxy_mode, prefix): + """Returns a unique name and id for a graph to be added to a proxy_mode tracer""" + # There are probably better ways - I know that create_arg has some self incrementing name + # magic to it, but since we explicitly have to get the name for register_module, + # I was not sure how to do that. This kinda simulates it. + return unique_graph_name_with_root(proxy_mode.tracer.root, prefix) + + +def unique_graph_name_with_root( + root: torch.fx.GraphModule, prefix: str +) -> tuple[int, str]: + next_name = None + i = 0 + # pyrefly: ignore [bad-assignment] + while not next_name: + candidate = f"{prefix}_{i}" + if hasattr(root, candidate): + i += 1 + else: + next_name = candidate + return i, next_name + + +def _from_fun(t): + from torch._functorch.aot_autograd import from_fun + + if isinstance(t, torch.Tensor): + if t.dtype != torch.bool: + return torch.empty_strided( + t.size(), + t.stride(), + dtype=t.dtype, + requires_grad=t.requires_grad, + device=t.device, + ) + else: + # clone of a functional tensor produces a functional tensor + # but we want to avoid it so we clone a non-functional version + maybe_unfunc_t = t + if isinstance(t, FunctionalTensor): + torch._sync(t) + maybe_unfunc_t = from_fun(t) + elif torch._is_functional_tensor(t): + # need to handle both types of functionalization here: + # these are the tensors that came from the user, + # which could be either FunctionalTensorWrapper or FunctionalTensor + torch._sync(t) + maybe_unfunc_t = torch._from_functional_tensor(t) + # pyrefly: ignore[missing-attribute] + return maybe_unfunc_t.clone() + return t + + +def clone_outputs_aliasing_inputs(args): + input_storage = { + StorageWeakRef(arg._typed_storage()) + for arg in args + if isinstance(arg, torch.Tensor) + } + + def maybe_clone(t): + if ( + isinstance(t, torch.Tensor) + and StorageWeakRef(t._typed_storage()) in input_storage + ): + return t.clone() + return t + + return maybe_clone + + +def query_requires_grad(t: torch.Tensor) -> bool: + """requires_grad of ``t``, looking through a functional wrapper. + + A FunctionalTensor does not carry the autograd metadata of the tensor it + wraps, so asking it directly reports False for something that does require + grad. This matters when the joint is traced with functionalization active. + """ + if torch._is_functional_tensor(t): + t = torch._from_functional_tensor(t) + return t.requires_grad + + +def prepare_fw_with_masks(fn): + def fw_with_masks(*args): + fw_out = fn(*args) + return fw_out, [ + bool(isinstance(ret, torch.Tensor) and query_requires_grad(ret)) + for ret in fw_out + ] + + return fw_with_masks + + +def prepare_fw_with_masks_all_requires_grad(fn): + def fw_with_masks(*args): + fw_out = fn(*args) + # Note [force all outputs to be require grad] + # Instead of using the original fn, we set the output of original + # fn to all require grad. This is consistent with the behavior + # of autograd.Function, where if any one of the inputs requires grad + # all output will be require grad. This also makes the downstream + # require_gradness reasoning much easier. + if pytree.tree_any_only(torch.Tensor, lambda t: t.requires_grad, args): + fw_out = pytree.tree_map_only( + torch.Tensor, + lambda x: x.requires_grad_(True) if x.dtype.is_floating_point else x, + fw_out, + ) + + return fw_out, pytree.tree_map_only(torch.Tensor, query_requires_grad, fw_out) + + return fw_with_masks + + +# This function replaces None gradients with all-zero gradients. +# `None` gradients are problematic for CUDA graphs. Those gradients are +# replaced with an all-zero tensor for better optimization +def unmask_none_gradients(grads, operands): + allowed_types = (torch.Tensor, int, torch.SymInt) + if not all(isinstance(o, allowed_types) for o in operands): + raise AssertionError( + f"operands can only be of {allowed_types} but got {[type(o) for o in operands]}" + ) + + unmasked_grads = [] + for g, o in zip(grads, operands): + if g is not None: + unmasked_grads.append(g) + else: + # In case the operand is an int or a torch.SymInt, return None + # This can happen for lifted_arguments. E.g., the shapes of a dynamic tensor are lifted and passed + # as additional arguments + unmasked_grads.append( + torch.zeros_like(o) if isinstance(o, torch.Tensor) else None + ) + + return unmasked_grads + + +def _maybe_fake_prop_ignore_unbacked(fn, args): + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + unfunc_args = [_from_fun(arg) for arg in args] + with ExitStack() as ctx_stack: + ctx_stack.enter_context( + torch.utils._python_dispatch._disable_current_modes() + ) + if (fake_mode := detect_fake_mode(unfunc_args)) is not None: + ctx_stack.enter_context(fake_mode) + if fake_mode.shape_env is not None: + ctx_stack.enter_context( + fake_mode.shape_env.ignore_fresh_unbacked_symbols() + ) + return fn(*unfunc_args) + + +def redirect_to_mode(hop: OperatorBase, mode): + """Utility for redispatching HOP to underlying mode + + Args: + hop: The HOP to redispatch + mode: The mode to redispatch to + + Returns: + A decorated function that implements the HOP for the given mode + """ + + @hop.py_impl(mode) + def impl(mode, *args, **kwargs): + return mode.__torch_dispatch__(hop, [], args, kwargs) + + return impl + + +# TODO: The parameter use_output_and_grad_bw is required because some operations +# that utilize this function, such as the while_loop, may require (grad, fwd_outputs) +def create_fw_bw_graph(fn, use_output_and_grad_bw, fw_inputs, fw_outputs): + from torch._functorch.aot_autograd import AOTConfig, create_joint + + # Note:[HOP create fw_bw graph] We create "clean" environments for make_fx by suspending all dispatch keys + # between Autograd and Python key. Currently, we only suspend functionalization but more can be + # added when required. Will encounter two problems if we don't suspend functionalization: + # + # 1. make_fx fails to capture operations on input: the inputs are wrapped as _to_functional_tensor_wrapper, + # but they will be unwrapped before entering ProxyTorchDispatchMode as part of the dispatching. + # However, it's the outside wrapper that tracer creates proxies for. This casuses tracer fail to + # fetch the proxy for the inputs and fail to capture any operations on them. + # + # 2. make_fx fails to capture output: the outputs after ProxyTorchDispatchMode are further + # wrapped as FunctionalTensorWrapper in Functionalize key after return. However, the tracer + # only associates the inner tensor with proxy in ProxyTorchDispatchMode. Therefore, + # when creating the output node, it fails to associate the wrapped tensor with its proxy. + # Instead, it will create _tensor_constant as output. + + dummy_aot_config = AOTConfig( + fw_compiler=None, # type: ignore[arg-type] + bw_compiler=None, # type: ignore[arg-type] + partition_fn=None, # type: ignore[arg-type] + decompositions={}, + num_params_buffers=0, + aot_id=0, + keep_inference_input_mutations=False, + ) + + example_grad = [_from_fun(out) for out in fw_outputs] + num_grads = len(example_grad) + fw_graph = _maybe_reenter_make_fx(fn)(*fw_inputs) + + def joint_fn(*joint_operands_grads): + if use_output_and_grad_bw: + grads = joint_operands_grads[0] + inputs = joint_operands_grads[1][-1:] + else: + grads = joint_operands_grads[:num_grads] + inputs = joint_operands_grads[num_grads:] + + joint = create_joint(prepare_fw_with_masks(fn), aot_config=dummy_aot_config) + _, grads = joint( + list(inputs), + [grad for grad in grads if grad is not None and grad.requires_grad], + ) + + # Unmask None gradients to all-zero gradients + unmasked_grads = unmask_none_gradients(grads, inputs) + + # In order to keep map functional for backward graph, + # we clone outputs that are aliasing inputs + maybe_clone = clone_outputs_aliasing_inputs(joint_operands_grads) + + return pytree.tree_map(maybe_clone, unmasked_grads) + + if use_output_and_grad_bw: + example_xs_out = list(fw_inputs) + list(fw_outputs) + joint_graph = _maybe_reenter_make_fx(joint_fn)( + (list(example_grad), list(example_xs_out)) + ) + else: + example_xs_out = list(fw_inputs) + joint_graph = _maybe_reenter_make_fx(joint_fn)( + *(list(example_grad) + list(example_xs_out)) + ) + + return fw_graph, joint_graph + + +def _unstack_pytree(xs): + flat_xs, inspec = pytree.tree_flatten(xs) + if not all(isinstance(xs, torch.Tensor) for xs in flat_xs): + raise RuntimeError(f"Leaves of xs must be Tensor {flat_xs}") + + if not all(xs.shape[0] == flat_xs[0].shape[0] for xs in flat_xs): + raise RuntimeError( + f"Leaves of xs must have same leading dimension size {[xs.shape for xs in flat_xs]}" + ) + + a = zip(*flat_xs) + + pytrees = [pytree.tree_unflatten(tuple, inspec) for tuple in a] + return pytrees + + +def _stack_pytree(pytrees): + flat_out = [] + out_spec = None + for pt in pytrees: + flat_pt, out_spec = pytree.tree_flatten(pt) + flat_out.append(flat_pt) + if out_spec is None: + raise AssertionError("out_spec cannot be None") + b = zip(*flat_out) + stacked_out = [] + for leaves in b: + if all(isinstance(leaf, torch.Tensor) for leaf in leaves): + stacked_out.append(torch.stack(leaves)) + elif all(leaf is None for leaf in leaves): + # Backward graph can return None output when forward inputs doesn't require grad. + # When we eagerly execute backward graph, we need to call _stack_pytree on its output, + # therefore we need to deal with None output. + stacked_out.append(None) # type: ignore[arg-type] + else: + raise RuntimeError(f"Cannot stack {leaves}.") + return pytree.tree_unflatten(stacked_out, out_spec) + + +# We cannot call save_for_backward for symints. This helper function +# can be used to save symints as direct attributes of ctx in autograd.Function. +# +# For example, if args = (x, y, s0, z, s1), +# save_values_for_backward will partition the args into two lists, and a bookkeeping list pos: +# partitioned_args[0] = (x, y, z) +# partitioned_args[1] = (s0, s1) +# pos = (0, 0, 1, 0, 1) +# pos list keeps track of which partition the args +# is partitioned into in order to recover it in saved_values. +# +# In saved_values, we can recover the original args by: +# iterating over the pos list and pop one item from the front of partitioned_args[pos[i]]. +# We use t_idx and s_idx to keep track of the next index of the item we are going to pop for the two lists. +def save_values_for_backward(ctx, args): + if not all( + isinstance(arg, (torch.Tensor, torch.SymInt, int, type(None), FakeScriptObject)) + or is_custom_class(type(arg)) + for arg in args + ): + raise AssertionError(f"Invalid arg types in {args}") + partitioned_args: list[Any] = [[], []] + pos = [] + for arg in args: + idx = 0 if isinstance(arg, torch.Tensor) else 1 + partitioned_args[idx].append(arg) + pos.append(idx) + + if hasattr(ctx, "non_tensor_args"): + raise AssertionError("ctx already has non_tensor_args attribute.") + if hasattr(ctx, "pos"): + raise AssertionError("ctx already has pos attribute.") + ctx.save_for_backward(*partitioned_args[0]) + ctx.non_tensor_args = partitioned_args[1] + ctx.pos = pos + + +def saved_values(ctx): + args = [] + t_idx = 0 + s_idx = 0 + saved_tensors = ctx.saved_tensors + for p in ctx.pos: + if p == 0: + args.append(saved_tensors[t_idx]) + t_idx += 1 + else: + args.append(ctx.non_tensor_args[s_idx]) + s_idx += 1 + if t_idx + s_idx != len(ctx.pos): + raise AssertionError( + f"t_idx ({t_idx}) + s_idx ({s_idx}) != len(ctx.pos) ({len(ctx.pos)})" + ) + return tuple(args) + + +def split_into_chunks(iterable: Sequence[Any], chunk_sizes: list[int]) -> list[Any]: + if sum(chunk_sizes) != len(iterable): + raise AssertionError( + f"the sum of all chunks ({sum(chunk_sizes)}) needs to match the length of the iterable ({len(iterable)})." + ) + elements = [] + idx = 0 + for size in chunk_sizes: + elements.append(iterable[idx : idx + size]) + idx += size + return elements + + +def _clone_aliasing_output(inputs: Sequence[Any], outputs: Sequence[Any]): + # For tensors whose grad is None, create zero tensors as gradients + # This invariant is useful for cudagraph. + + # Elimitate input-output, output-output aliasing + seen_input_storages = { + StorageWeakRef(t._typed_storage()) + for t in inputs + if isinstance(t, torch.Tensor) + } + seen_output_storages = set() + final_outputs = [] + for out in outputs: + if isinstance(out, torch.Tensor): + out_storage = StorageWeakRef(out._typed_storage()) + if ( + out_storage in seen_input_storages + or out_storage in seen_output_storages + ): + out = out.clone() + seen_output_storages.add(StorageWeakRef(out._typed_storage())) + final_outputs.append(out) + return final_outputs + + +def create_bw_fn( + fn: Callable, args: tuple[Any, ...], return_fw_outputs: bool = False +) -> Callable: + """ + For a fn that accepts flat inputs and returns flat outputs: + fw_out = fn(*args), + this function returns: + grad_args = bw_fn(*args_and_grad_output) + with the following invariants: + 1. args + fw_out has an 1-1 correspondence to args_and_grad_output + 2. grad_args has an 1-1 corresponsence to args + 3. for tensor arg whose requires_grad is False, its corresponding grad in + grad_args will be a zero tensor with the same shape. + """ + + from torch._functorch.aot_autograd import AOTConfig, create_joint + + # pyrefly: ignore [missing-module-attribute] + from torch._higher_order_ops.utils import prepare_fw_with_masks_all_requires_grad + + dummy_aot_config = AOTConfig( + fw_compiler=None, # type: ignore[arg-type] + bw_compiler=None, # type: ignore[arg-type] + partition_fn=None, # type: ignore[arg-type] + decompositions={}, + num_params_buffers=0, + aot_id=0, + keep_inference_input_mutations=False, + ) + n_primals = len(args) + + bw_fn = create_joint( + prepare_fw_with_masks_all_requires_grad(fn), aot_config=dummy_aot_config + ) + + def flat_fn(*args_and_grad_outs): + primals = args_and_grad_outs[:n_primals] + tangents = args_and_grad_outs[n_primals:] + fw_outs, grad_args = bw_fn(primals, tangents) + if len(args) != len(grad_args): + raise AssertionError( + f"Expected {len(args)} grad_args, got {len(grad_args)}" + ) + + # For tensors whose grad is None, create zero tensors as gradients + # This invariant is useful for cudagraph. + grad_args = [ + torch.zeros_like(arg) + if isinstance(arg, torch.Tensor) and grad is None + else grad + for grad, arg in zip(grad_args, primals) + ] + + final_grads = _clone_aliasing_output(args_and_grad_outs, grad_args) + if return_fw_outputs: + return *fw_outs, *final_grads + return final_grads + + return flat_fn + + +def get_dummy_aot_autograd_config(): + from torch._functorch.aot_autograd import AOTConfig + + return AOTConfig( + fw_compiler=None, # type: ignore[arg-type] + bw_compiler=None, # type: ignore[arg-type] + partition_fn=None, # type: ignore[arg-type] + decompositions={}, + num_params_buffers=0, + aot_id=0, + keep_inference_input_mutations=False, + ) + + +# Slices off the first element of a given dimension. Used to build a +# representative single slice for subgraph tracing of control-flow ops. +# When `dim` has size 0 (e.g. a zero-length scan) there is no real slice to +# take, so return an uninitialized tensor with `dim` removed. +def first_slice_copy(t: torch.Tensor, dim: int = 0) -> torch.Tensor: + if t.shape[dim] == 0: + shape = list(t.shape) + del shape[dim] + return t.new_zeros(shape) + return torch.select_copy(t, dim, 0) + + +# Returns a mask whether a list element is a tensor or not +def get_tensor_mask(tensor_list: Iterable[Any]) -> list[bool]: + return [bool(isinstance(v, torch.Tensor)) for v in tensor_list] + + +def mask_list( + mask: list[bool], inp: list[Any], other: list[Any] | None = None +) -> list[Any]: + # Masks elements on an `inp` list. + # If other is None, then the elements of the `inp` list where the mask is False are removed + # If other is not None, then the elements of the `inp` list where the mask is False are + # replaced with the elements of the `other` list + if len(mask) != len(inp): + raise AssertionError( + f"The length of the mask ({len(mask)}) needs to be identical to the length of the input ({len(inp)})" + ) + if other is not None: + if len(inp) != len(other): + raise AssertionError( + f"If an input and an other list is provided, they need to have the same length ({len(inp)} != {len(other)})" + ) + return [i if m else o for m, i, o in zip(mask, inp, other)] + else: + return [i for m, i in zip(mask, inp) if m] + + +def first_slice_copy_with_grad(li: Iterable[Any]) -> list[Any]: + # First_slice_copy does not keep the original requires_grad flag, + # but we need it for materialize_as_graph + # in order to compute the correct gradients + # The reason why first_slice_copy doesn't keep requires_grad flag is + # because it's called in torch.autograd.Function.backward/forward. + slc = [first_slice_copy(x).requires_grad_(x.requires_grad) for x in li] + return slc + + +# Reports the difference between meta of two tensors in a string +def diff_tensor_meta( + meta1: TensorMetadata, meta2: TensorMetadata, check_grad=True +) -> list[str]: + from torch.fx.experimental.symbolic_shapes import GuardOnDataDependentSymNode + + pair_diffs = [] + for meta_name in TensorMetadata._fields: + if not check_grad and meta_name == "requires_grad": + continue + val1 = getattr(meta1, meta_name) + val2 = getattr(meta2, meta_name) + try: + if val1 != val2: + pair_diffs.append(f"'{meta_name}: {val1} vs {val2}'") + except GuardOnDataDependentSymNode: + pair_diffs.append(f"'{meta_name}: {val1} vs {val2}'") + continue + return pair_diffs + + +# Note [lifted arg types in hop] +# For dynamoed hops, we automatically lift the free symbols in tensors as arguments. +# This has implications for the types of lifted args for different dispatch keys: +# 1. functionalization, FakeTensorMode, ProxyTorchDispatchMode, Autograd need to support torch.Symint +# lifted args because it's on the path of torch.compile(dynamic=True). +# 2. functionalization, FakeTensorMode, ProxyTorchDispatchMode, Autograd, CompositeExplicitAutograd need +# to support int arguments. In the eager run case, we re-trace the subgraph in AutogradKey, so inner +# hops may receive int inputs from the shape of outer tensor inputs. +# However, CompositeExplicitAutograd won't receive SymInt inputs because it only accepts real tensor inputs. +def validate_subgraph_args_types(lifted_args: tuple[Any, ...] | list[Any]): + allowed_types = (torch.Tensor, int, torch.SymInt) + if not all( + isinstance(arg, (torch.Tensor, int, torch.SymInt)) for arg in lifted_args + ): + raise AssertionError( + f"{lifted_args} can only be of {allowed_types} but got {tuple(type(arg) for arg in lifted_args)}" + ) + + +# TODO: Return a more detailed information as to which node +# causes a mutation or an alias. This may requires a per operator tensor version checking +def check_input_alias_and_mutation( + gm: torch.fx.GraphModule, + fake_args: list[FakeTensor], +) -> tuple[dict[int, int], dict[int, int], dict[int, int], list[int]]: + ( + inp_inp_alias_map, + inp_out_alias_map, + out_out_alias_map, + mutated_inputs, + ) = check_input_alias_and_mutation_return_outputs(gm)[:-1] + # pyrefly: ignore [bad-return] + return inp_inp_alias_map, inp_out_alias_map, out_out_alias_map, mutated_inputs + + +def _tensor_storage(t) -> StorageWeakRef: + return StorageWeakRef(t._typed_storage()) + + +def _get_example_value(n): + if not isinstance(n, torch.fx.Node): + return n + if "val" in n.meta: + return n.meta["val"] + if "example_value" in n.meta: + return n.meta["example_value"] + return None + + +def get_graph_output_example_values(gm: torch.fx.GraphModule) -> list[Any]: + output_node = gm.graph.find_nodes(op="output")[0] + return [_get_example_value(n) for n in pytree.tree_flatten(output_node.args[0])[0]] + + +def check_input_alias_and_mutation_return_outputs( + gm: torch.fx.GraphModule, +) -> tuple[ + dict[int, int], + dict[int, int], + dict[int, int], + list[int], + tuple[Any, ...] | list[Any], +]: + fake_args = [ + _get_example_value(n) + for n in gm.graph.find_nodes(op="placeholder") + if isinstance(n, torch.fx.Node) and "val" in n.meta + ] + outputs = get_graph_output_example_values(gm) + + # We need to analyze the original fake_args to detect + # inp-inp alias. + inp_storage_map = { + _tensor_storage(inp): i + for i, inp in enumerate(fake_args) + if isinstance(inp, torch.Tensor) + } + out_storage_map = { + _tensor_storage(out): i + for i, out in enumerate(outputs) + if isinstance(out, torch.Tensor) + } + inp_inp_alias_map = { + i: inp_storage_map[_tensor_storage(inp)] + for i, inp in enumerate(fake_args) + if isinstance(inp, torch.Tensor) and inp_storage_map[_tensor_storage(inp)] != i + } + out_out_alias_map = { + i: out_storage_map[_tensor_storage(out)] + for i, out in enumerate(outputs) + if isinstance(out, torch.Tensor) and out_storage_map[_tensor_storage(out)] != i + } + inp_out_alias_map = { + i: out_storage_map[_tensor_storage(inp)] + for i, inp in enumerate(fake_args) + if isinstance(inp, torch.Tensor) and _tensor_storage(inp) in out_storage_map + } + mutated_inputs = [] + for node in gm.graph.nodes: + if node.op == "call_function" and isinstance( + node.target, torch._ops.OpOverload + ): + for arg_node, arg_schema in zip(node.args, node.target._schema.arguments): + if arg_schema.is_write: + arg_val = _get_example_value(arg_node) + if not isinstance(arg_val, torch.Tensor): + raise AssertionError( + f"Expected arg_val to be a Tensor, got {type(arg_val)}" + ) + if _tensor_storage(arg_val) in inp_storage_map: + mutated_inputs.append(inp_storage_map[_tensor_storage(arg_val)]) + + return ( + inp_inp_alias_map, + inp_out_alias_map, + out_out_alias_map, + mutated_inputs, + outputs, + ) + + +registered_hop_fake_fns: dict[torch._ops.OpOverload, Callable] = {} + +# Set skip_cache=True for HOPs that should not be cached in FakeTensorMode +# (previously these ops were registered with .py_impl(FakeTensorMode)) and +# were never cached so we are just preserving original behaviour +hops_that_skip_faketensor_cache: set[torch._ops.OpOverload] = set() + + +F = TypeVar("F", bound=Callable) +_P = ParamSpec("_P") + + +@overload +def register_fake( + hop, fn: None = None, *, skip_cache: bool = ... +) -> Callable[[F], F]: ... + + +@overload +def register_fake(hop, fn: F, *, skip_cache: bool = ...) -> F: ... + + +def register_fake(hop, fn=None, *, skip_cache=False): + """ + Register a fake function for a HOP. This is conceptually equivalent of the + register_fake utility for the custom ops. The registered function is called + inside the fake_tensor _dispatch_impl. + + Set skip_cache=True to keep a HOP's fake output out of the FakeTensorMode + cache -- either to preserve the historical uncached behavior of + py_impl(FakeTensorMode), or because its outputs alias in ways the cache + cannot reconstruct (e.g. auto_functionalized). + """ + if hop in registered_hop_fake_fns: + raise AssertionError(f"hop {hop} already registered in registered_hop_fake_fns") + + def register(func: F) -> F: + from torch._subclasses.fake_tensor import FakeTensorMode + + redirect_to_mode(hop, FakeTensorMode) + + registered_hop_fake_fns[hop] = func + if skip_cache: + hops_that_skip_faketensor_cache.add(hop) + return func + + if fn is None: + return register + return register(fn) + + +class SubgraphCallableWrapper: + """ + Wraps a callable while preserving the original subgraph identity for + fake tensor caching. Without this, passing a plain closure to + invoke_subgraph would bypass the dispatch cache entirely. + """ + + def __init__(self, fn, subgraph): + self.fn = fn + self.subgraph = subgraph + self._boxed_call = getattr(subgraph, "_boxed_call", False) + + def __hash__(self): + return id(self.subgraph) + + def __call__(self, *args, **kwargs): + return self.fn(*args, **kwargs) + + +class FunctionalizeCtxWrapper(SubgraphCallableWrapper): + """Functionalizes a subgraph and optionally returns selected input updates. + + Each update is a new tensor; the original input is not mutated. + """ + + # Prevents PYTORCH_TEST_WITH_DYNAMO=1 test failures + @torch._disable_dynamo + def __init__(self, ctx, subgraph, mutated_input_indices=()): + super().__init__(subgraph, subgraph) + self.ctx = ctx + self.mutated_input_indices = mutated_input_indices + + def __repr__(self): + return f"FunctionalizeCtxWrapper on subgraph {self.subgraph})" + + def __call__(self, *args, **kwargs): + def append_mutated_inputs(fn): + if not self.mutated_input_indices: + return fn + + def wrapped(*args, **kwargs): + inputs = args[0] if self._boxed_call else args + # Snapshot before a boxed GraphModule clears its input list. + mutated_inputs = tuple(inputs[i] for i in self.mutated_input_indices) + # Dynamo normalizes invoke_subgraph outputs to tuples. + return (*fn(*args, **kwargs), *mutated_inputs) + + return wrapped + + if isinstance(self.subgraph, torch.fx.GraphModule): + if self._boxed_call: + # Not all callers respect _boxed_call (e.g. reenter_make_fx). + functionalized = self.ctx.functionalize( + append_mutated_inputs(self.subgraph) + ) + if len(args) == 1 and isinstance(args[0], list): + return functionalized(args[0]) + return functionalized(list(args)) + else: + # Running graph with interpreter is needed for propagating the stack_trace + with fx_traceback.preserve_node_meta(): + return self.ctx.functionalize( + append_mutated_inputs(torch.fx.Interpreter(self.subgraph).run) + )(*args, **kwargs) + functionalized = self.ctx.functionalize(append_mutated_inputs(self.subgraph)) + if self._boxed_call: + if len(args) == 1 and isinstance(args[0], list): + return functionalized(args[0]) + return functionalized(list(args)) + return functionalized(*args, **kwargs) + + +# A wrapper over HigherOrderOperator that also carries its schema +class HopInstance: + def __init__(self, op: HigherOrderOperator, schema: HopSchema): + if not isinstance(op, HigherOrderOperator): + raise AssertionError(f"Expected HigherOrderOperator, got {type(op)}") + self._op = op + # Using "_" to be consistent with how we access _schema of OpOverload + self._schema = schema + + def __call__(self, *args, **kwargs): + return self._op(*args, **kwargs) + + @staticmethod + def create(hop: HigherOrderOperator, *args, **kwargs): + return HopInstance(hop, hop.gen_schema(*args, **kwargs)) + + +# This call_op can be used to call a HopInstance with +# flat args and kwargs. We need to make use of the hop's schema's tree_spec +# to unflatten the args and kwargs before calling the hop. +def call_op(op: OpOverload | HopInstance, args, kwargs): + if isinstance(op, OpOverload): + return op(*args, **kwargs) + + if not isinstance(op, HopInstance): + raise AssertionError(f"Expected HopInstance, got {type(op)}") + schema = op._schema + bound_args = list(args) + bound_kwargs = {} + for arg in schema.arguments[len(bound_args) :]: + if arg.name not in kwargs: + raise AssertionError(f"arg {arg.name} not in kwargs: {kwargs}") + val = kwargs[arg.name] + if not arg.kwarg_only: + bound_args.append(val) + else: + bound_kwargs[arg.name] = val + + if schema.tree_spec is not None: + if len(bound_args) != len(schema.arguments) or len(bound_kwargs) != 0: + raise AssertionError( + f"Expected {len(schema.arguments)} bound_args and 0 bound_kwargs, " + f"got {len(bound_args)} and {len(bound_kwargs)}" + ) + args, kwargs = pytree.tree_unflatten(bound_args, schema.tree_spec) + return op(*args, **kwargs) + else: + if len(bound_args) + len(bound_kwargs) != len(schema.arguments): + raise AssertionError( + f"Expected {len(schema.arguments)} total args, " + f"got {len(bound_args)} + {len(bound_kwargs)}" + ) + return op(*bound_args, **bound_kwargs) + + +def materialize_as_graph( + fn: Callable, + args: tuple[Any, ...], + include_key_set: torch._C.DispatchKeySet | None = None, + exclude_key_set: torch._C.DispatchKeySet | None = None, + force_enable_grad=False, + subgraph_decomp_table: Mapping[OpOverload, Callable] | None = None, +) -> torch.fx.GraphModule: + if include_key_set is None: + include_key_set = torch._C._dispatch_tls_local_include_set() + if exclude_key_set is None: + exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + + @torch._dynamo.disable(recursive=True, reason=None) + def _materialize_as_graph_inner(): + from torch._guards import active_fake_mode + from torch.fx.experimental.proxy_tensor import _CURRENT_MAKE_FX_TRACER + + with suspend_functionalization(), disable_functional_mode(): + fake_mode = None + if _CURRENT_MAKE_FX_TRACER is not None: + fake_mode = _CURRENT_MAKE_FX_TRACER.fake_tensor_mode + if fake_mode is None: + fake_mode = active_fake_mode() + + with contextlib.ExitStack() as stack: + stack.enter_context( + torch.utils._python_dispatch._disable_current_modes() + ) + if fake_mode is not None: + stack.enter_context(fake_mode) + + with disable_proxy_modes_tracing(): + unfunc_t = [_from_fun(arg) for arg in args] + + stack.enter_context( + torch._C._ForceDispatchKeyGuard(include_key_set, exclude_key_set), + ) + if force_enable_grad: + stack.enter_context(torch.enable_grad()) + return _maybe_reenter_make_fx( + fn, subgraph_decomp_table=subgraph_decomp_table + )(*unfunc_t) + + gm = _materialize_as_graph_inner() + if gm is None: + raise AssertionError("materialize_as_graph returned None") + return gm + + +def materialize_callable_in_args(op: HopInstance, args, kwargs): + schema = op._schema + hop = op._op + flat_args, flat_spec = pytree.tree_flatten((args, kwargs)) + + def wrapped_fn(*flat_args): + return call_op(op, args, kwargs) + + # We need to trace the higher order op in order to materilaize the callable inputs that + # are a callable (e.g. after functionalization key) + gm = reenter_make_fx(wrapped_fn)(*flat_args) + hop_node = gm.graph.find_nodes(op="call_function", target=hop)[0] + arg_proxies = pytree.tree_leaves((hop_node.args, hop_node.kwargs)) + if not isinstance(schema, torch._C.FunctionSchema) or len(arg_proxies) != len( + schema.arguments + ): + raise AssertionError( + f"Expected FunctionSchema with {len(arg_proxies)} arguments" + ) + + # call_op preserves ordering of proxies via schema + materialized_args = [] + for i, proxy in enumerate(arg_proxies): + if ( + isinstance(proxy, torch.fx.Node) + and proxy.op == "get_attr" + and isinstance(getattr(gm, proxy.target), torch.fx.GraphModule) # type: ignore[arg-type] + ): + if not callable(flat_args[i]): + raise AssertionError( + f"Expected flat_args[{i}] to be callable for {schema}" + ) + materialized_args.append(getattr(gm, proxy.target)) # type: ignore[arg-type] + else: + materialized_args.append(flat_args[i]) + + return pytree.tree_unflatten(materialized_args, flat_spec) + + +def has_user_subclass(args, allowed_subclasses): + """Check if any tensor arguments are user subclasses. + + This is used to determine if tensor subclasses should get a chance to run + their own implementation first before falling back to the default implementation. + + Args: + args: Arguments to check (will be flattened with pytree) + allowed_subclasses: Tuple of allowed subclass types + + Returns: + True if user tensor subclasses are found, False otherwise + """ + flat_args, _ = pytree.tree_flatten(args) + + val = any( + isinstance(a, torch.Tensor) + and type(a) is not torch.Tensor + and not isinstance(a, allowed_subclasses) + for a in flat_args + ) + return val + + +def _has_gen_schema(op: HigherOrderOperator): + # There is an InvokeQuant argument we cannot gen_schema. + if op is torch.ops.higher_order.invoke_quant_packed: + return False + method = "gen_schema" + return hasattr(type(op), method) and getattr(type(op), method) is not getattr( + HigherOrderOperator, method + ) + + +def filter_with_masks(data: list[torch.Tensor | None], masks: list[bool]): + if len(data) != len(masks): + raise AssertionError( + f"data length ({len(data)}) != masks length ({len(masks)})" + ) + return [item for item, keep in zip(data, masks) if keep] + + +def fill_none_with_masks(data: list[torch.Tensor | None], masks: list[bool]): + data_iter = iter(data) + return [next(data_iter) if kept else None for kept in masks] + + +def create_fn_remove_none( + fn: Callable[_P, Any], +) -> tuple[Callable[_P, list[torch.Tensor]], list[bool]]: + """Wrap ``fn`` so its non-Tensor output leaves are dropped, and expose the + mask of which leaves survived. + + Returns ``(wrapped, mask)``: + - ``wrapped(*args)`` calls ``fn(*args)``, flattens the pytree result and + returns only its Tensor leaves as a list. + - ``mask`` is a list populated whenever ``wrapped`` runs -- one bool per + leaf, ``True`` where the leaf is a Tensor. Callers should read it + AFTER invoking ``wrapped`` (typically indirectly via + ``materialize_as_graph``), then pass it to ``fill_none_with_masks`` + to reconstruct the full output with ``None`` at the dropped slots. + + Used in HOP autograd impls in two places: + - Around a forward branch that may return non-Tensor leaves (None, + int/SymInt), so ``create_bw_fn``'s joint sees a tensor-only signature. + - Around the resulting backward joint whose grad list contains ``None`` + at non-differentiable input slots, so the materialized ``GraphModule`` + returns a uniform Tensor list. + """ + mask: list[bool] = [] + + @functools.wraps(fn) + def wrapped(*args, **kwargs): + leaves = pytree.tree_leaves(fn(*args, **kwargs)) + mask.clear() + mask.extend(isinstance(o, torch.Tensor) for o in leaves) + return filter_with_masks(leaves, mask) + + return wrapped, mask diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/while_loop.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/while_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..9805c91ec15e7252dd359ea8e48688ee787541c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/while_loop.py @@ -0,0 +1,1020 @@ +# mypy: allow-untyped-defs +import contextlib +import functools +from collections.abc import Callable + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, +) +from torch._higher_order_ops.utils import ( + _check_alias_and_mutation, + _maybe_run_with_interpreter, + autograd_not_implemented, + check_meta_consistency, + fill_none_with_masks, + filter_with_masks, + get_graph_output_example_values, + HopInstance, + materialize_as_graph, + reenter_make_fx, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +class WhileLoopOp(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("while_loop") + + def __call__( + self, + cond_fn: Callable, + body_fn: Callable, + carried_inputs: tuple[torch.Tensor | int | float | bool], + additional_inputs: tuple[torch.Tensor | torch.SymInt | int, ...], + /, + *, + mutated_arg_indices: str = "", + ): + if not isinstance(carried_inputs, (tuple, list)): + raise RuntimeError( + f"carried_inputs must be a tuple or list, got {type(carried_inputs)}" + ) + if not isinstance(additional_inputs, (tuple, list)): + raise RuntimeError( + f"additional_inputs must be a tuple or list, got {type(additional_inputs)}" + ) + + validate_subgraph_args_types(carried_inputs) + validate_subgraph_args_types(additional_inputs) + kwargs = {} + if mutated_arg_indices: + kwargs["mutated_arg_indices"] = mutated_arg_indices + # pyrefly: ignore [missing-attribute] + return super().__call__( + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + **kwargs, + ) + + # pyrefly: ignore [bad-override] + def gen_schema( + self, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + mutated_arg_indices="", + ): + from torch._higher_order_ops.schema import HopSchemaGenerator + from torch._higher_order_ops.utils import materialize_as_graph + + all_inputs = carried_inputs + additional_inputs + + cond_gm: torch.fx.GraphModule = ( + cond_fn + if isinstance(cond_fn, torch.fx.GraphModule) + else materialize_as_graph(cond_fn, all_inputs) + ) + body_gm: torch.fx.GraphModule = ( + body_fn + if isinstance(body_fn, torch.fx.GraphModule) + else materialize_as_graph(body_fn, all_inputs) + ) + + body_outputs = get_graph_output_example_values(body_gm) + mutated_inputs = ( + {int(i) for i in mutated_arg_indices.split(",") if i} + if mutated_arg_indices + else set() + ) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("cond_fn", cond_gm) + schema_gen.add_arg("body_fn", body_gm) + + for idx, arg in enumerate(carried_inputs): + schema_gen.add_arg( + f"carried_input{idx}", arg, is_mutated=idx in mutated_inputs + ) + + for idx, arg in enumerate(additional_inputs): + additional_idx = len(carried_inputs) + idx + schema_gen.add_arg( + f"additional_input{idx}", + arg, + is_mutated=additional_idx in mutated_inputs, + ) + + for out in body_outputs: + schema_gen.add_output(out) + + schema_gen.add_schema_tree_spec( + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + ) + return schema_gen.gen_schema() + + +while_loop_op = WhileLoopOp() + + +def while_loop(cond_fn, body_fn, carried_inputs): + r""" + Run ``body_fn(*carried_inputs)`` while ``cond_fn(*carried_inputs)`` returns + a True scalar tensor. Returns the output of body_fn or initial + carried_inputs. + + .. warning:: + + `torch.while_loop` is a prototype feature in PyTorch. It has limited support for input and output types and + doesn't support training currently. Please look forward to a more stable implementation in a future version of PyTorch. + Read more about feature classification at: https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + `while_loop` is a structured control flow operator. It preserves the loop semantic across the torch.compile and torch.export. + + `while_loop` is equivalent to the following:: + + def while_loop(cond_fn, body_fn, carried_inputs): + val = carried_inputs + while cond_fn(*val): + val = body_fn(*val) + return val + + Args: + cond_fn (Callable): A callable function that returns a boolean Scalar tensor or a python boolean. + + body_fn (Callable): A callable function that takes the same inputs as `cond_fn` and returns a tuple of tensors or ints + + carried_inputs (Tuple of possibly nested dict/list/tuple of tensors or ints): A tuple of inputs to cond_fn and body_fn. + It's also the initial value of states that are carried across iterations. Note that when pass an integer as carry, + the corresponding return of while_loop will be another int with unknown values because we don't know how many + iterations while_loop will run. + + Example 1:: + + def cond_fn(iter, x): + return iter.sum() < 10 + + + def body_fn(iter, x): + return iter + 1, x.sin() + + + while_loop(cond_fn, body_fn, (torch.zeros(1), torch.randn(3, 4))) + + Example 2:: + + def cond_fn(int_iter, x): + return 2 * int_iter < x.shape[0] + + + def body_fn(int_iter, x): + return int_iter + 1, x + int_iter + + + while_loop(cond_fn, body_fn, (0, torch.randn(3, 4))) + + Restrictions: + + - body_fn must return tensors or int with the same metadata (e.g.shape, dtype) as inputs. + + - body_fn and cond_fn must not in-place mutate the carried_inputs. A clone before the mutation is required. + + - body_fn and cond_fn must not mutate python variables (e.g. list/dict) created outside of the body_fn. + + - body_fn and cond_fn's output cannot alias any of the inputs. A clone is required. + + - During inference, body_fn and cond_fn can in-place mutate tensors that are not + carried_inputs, such as module buffers and captured tensors from the enclosing scope. + + """ + + # Currently, additional_inputs is not a user-facing input. It will be automatically set in dynamo. + # parameters and buffers accessed in cond_fn or body_fn or tensor closures will become additional_inputs. + additional_inputs: tuple = () + + # The reason we flatten the output before calling into dynamo is that + # we want to create a consistent input ordering for cond_fn and body_fn. + # and we also want to the input ordering matches the output ordering. + # Also see NOTE: [why we cannot use "automatic" for while_loop] + # Construct flat cond_fn and flat_body_fn, which takes flattened inputs + flat_inputs, in_spec = pytree.tree_flatten((carried_inputs, additional_inputs)) + + def flat_cond_fn(*flat_args): + carried, additional = pytree.tree_unflatten(flat_args, in_spec) + return cond_fn(*carried, *additional) + + def flat_body_fn(*flat_args): + carried, additional = pytree.tree_unflatten(flat_args, in_spec) + return body_fn(*carried, *additional) + + if torch.compiler.is_dynamo_compiling(): + return while_loop_op(flat_cond_fn, flat_body_fn, tuple(flat_inputs), tuple()) + + def _validate_input(cond_fn, body_fn, carried_inputs): + from torch._higher_order_ops.utils import validate_subgraph_args_types + + if not callable(cond_fn) or not callable(body_fn): + raise RuntimeError("Expect cond_fn and body_fn to be callable.") + + validate_subgraph_args_types(flat_inputs) + + if not pytree.tree_all( + lambda t: isinstance(t, (torch.Tensor, torch.SymInt, int)), carried_inputs + ): + raise RuntimeError( + "Expect carried_inputs to be a tuple of possibly nested dict/list/tuple that only" + f"consists of tensor or int leaves, but got {carried_inputs}." + ) + + _validate_input(cond_fn, body_fn, carried_inputs) + + # Dynamo is expecting a callable with "__code__" attribute. + # We cannot directly pass cond_op to it. So we wrap it in a dummy function. + def _while_loop_op_wrapper(*args, **kwargs): + return while_loop_op(*args, **kwargs) + + from torch._higher_order_ops.utils import _hop_compile_and_call + + return _hop_compile_and_call( + _while_loop_op_wrapper, + (flat_cond_fn, flat_body_fn, tuple(flat_inputs), tuple()), + ) + + +@while_loop_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def while_loop_dense( + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + stack_output=False, + mutated_arg_indices="", +): + carried_vals = carried_inputs + + def _validate_cond_output(pred): + if ( + isinstance(pred, torch.Tensor) + and pred.size() == torch.Size([]) + and pred.dtype == torch.bool + ) or isinstance(pred, bool): + return + else: + raise RuntimeError( + f"cond_fn must return a boolean scalar tensor or a boolean but got {pred}" + ) + + if not isinstance(carried_inputs, (tuple, list)): + raise RuntimeError( + f"carried_inputs must be a tuple or list but got {type(carried_inputs)}" + ) + + # Check condition and set up flag + should_loop = cond_fn(*carried_vals, *additional_inputs) + _validate_cond_output(should_loop) + + if not should_loop: + if stack_output: + return tuple( + val.unsqueeze(0).clone() if isinstance(val, torch.Tensor) else val + for val in carried_vals + ) + else: + return tuple( + val.clone() if isinstance(val, torch.Tensor) else val + for val in carried_vals + ) + + outputs: list[list[torch.Tensor]] = [[] for _ in carried_vals] + + while should_loop: + out = body_fn(*carried_vals, *additional_inputs) + if stack_output: + for i, o in enumerate(out): + outputs[i].append(o) + + if not isinstance(out, tuple): + raise AssertionError(f"body_fn should return a tuple but got {type(out)}") + if len(out) != len(carried_inputs): + raise AssertionError( + f"body_fn should return the same number of elements as carried_inputs, got {len(out)} vs {len(carried_inputs)}" + ) + carried_vals = out + + should_loop = cond_fn(*carried_vals, *additional_inputs) + + if stack_output: + outs: list[torch.Tensor] = [] + for out in outputs: + outs.append(torch.stack(out, dim=0)) + return tuple(outs) + + return carried_vals + + +@while_loop_op.py_autograd_impl +def while_loop_autograd( + cond_fn, body_fn, operands, additional_inputs, mutated_arg_indices="" +): + return WhileLoopAutogradOp.apply( + cond_fn, + body_fn, + len(operands), + len(additional_inputs), + *operands, + *additional_inputs, + ) + + +def _find_or_create_fake_mode() -> FakeTensorMode: + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + fake_mode = torch._guards.detect_fake_mode() + if fake_mode is None: + fake_mode = FakeTensorMode(shape_env=ShapeEnv()) + + return fake_mode + + +def _create_unbacked_symint( + fake_mode: FakeTensorMode, ignore_fresh_unbacked_symbols: bool +) -> torch.SymInt: + if fake_mode is None or fake_mode.shape_env is None: + raise AssertionError("Must provide a fake_mode with shape_env.") + ctx = ( + contextlib.nullcontext() + if not ignore_fresh_unbacked_symbols + else fake_mode.shape_env.ignore_fresh_unbacked_symbols() + ) + with ctx: + return fake_mode.shape_env.create_unbacked_symint() + + +@while_loop_op.py_impl(ProxyTorchDispatchMode) +def while_loop_tracing( + mode, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + stack_output=False, + mutated_arg_indices="", +): + op = while_loop_stack_output_op if stack_output else while_loop_op + + def _trace_while_loop( + proxy_mode, + op, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + mutated_arg_indices, + ): + # NOTE [unspecialize int carry with unbacked symints] + # When we support int carry, we'll also need to support int output of body_fn because. + # previous iteration's output is next iteration's input and they must match. + # For carries, when we start tracing while_loop, they can be + # - constants e.g. (0, [1, 3]) + # - backed symints (x.shape[0], [x.shape[1] + x.stride[1], x.shape[2]]) + # - unbacked symints e.g. (u0, [u0 + u1, u2]) + # We choose the most conservative design: in all cases, we create new unbacked symints to trace the + # subgraph. It's possible to do some analysis on initial carry and the output of first + # iteration to determine a better range for the output unbacked symbol e.g. when input is an unbacked + # symint >= 0 before the while_loop but in general this is difficult because we don't know + # the number of iterations. Users would have to re-constrain the unbacked symint in subgraph if needed. + # + # For output of fake cond_fn, it could be constant bool or SymBool (e.g. return x.shape[0] < 4, + # where x.shape[0] can be either static of dynamic). In the case of constant bool, we should do a + # specialization (NYI). + + # For output of fake body_fn, it could be all three types though from user's point of view, + # they're all integers e.g. + + # init_carry = (0, s0, u1, t) + # def body_fn(u0, s0, u1, t): + # ... + # return (t.shape[0], t.shape[1], t.shape[2], y + 1) + # + # It may seem that a constant output isn't possible: users shouldn't write a while_loop + # that always return 0. But it could be that a shape is not set as dynamic properly (e.g. + # automatic dynamic hasn't been triggered). + # + # For this reason, we treat int, symint outputs in the same way: + # - they can match against any of int, symint carry + # - we unspecialize them with new unbacked symints in fake while_loop + # Similarly, we could do some analysis to refine the output ranges but it's easier to start with + # fresh unbacked symints. One surprising case can be: an input unbacked symint is constrained by + # users to be >= 0 (either before while_loop or inside body_fn) and it increments by 1 in each + # iteration. Ideally, we should know that the final output is >= 0 but we didn't constrain the + # unbacked symint output of subgraph as of today because this requires a smart range analysis. + fake_mode: FakeTensorMode = _find_or_create_fake_mode() + + def _unspecialize_carried_inputs(x): + if isinstance(x, (int, torch.SymInt)): + return _create_unbacked_symint( + fake_mode, ignore_fresh_unbacked_symbols=True + ) + # Note: [unspecialize constant tensor carry] + # We need to disable constant specialization for tensor inputs that become loop carries. + # Here's the problem: when a user creates a constant tensor e.g. torch.tensor(0), PyTorch calls aten.lift_fresh_copy + # to create a safe copy (avoiding aliasing issues), which creates a FakeTensor with constant=True. + # But when this FakeTensor becomes a loop carry, we have a problem: + # - Operations like .item() will read the constant value and bake it into the traced code + # - This is incorrect because carry variables change between loop iterations + # - The traced code would use the wrong constant value for all iterations + # Solution: We clone the constant tensors and mark the cloned tensor as non-constant so they won't + # be specialized to fixed values during tracing body_fn or cond_fn. + elif isinstance(x, torch.Tensor): + x = x.clone() + if hasattr(x, "constant") and x.constant is not None: + # pyrefly: ignore [missing-attribute] + x.constant = None + return x + + with disable_proxy_modes_tracing(): + unspecialized_carried_inputs = pytree.tree_map_only( + (int, torch.SymInt, torch.Tensor), + # For temporarily created unbacked symints, we don't need to bind them to any proxy + lambda x: _unspecialize_carried_inputs(x), + carried_inputs, + ) + + def produce_graph(fn): + cloned_carried_inputs = pytree.tree_map_only( + torch.Tensor, lambda x: x.clone(), unspecialized_carried_inputs + ) + return reenter_make_fx(fn)(*cloned_carried_inputs, *additional_inputs) + + cond_graph = produce_graph(cond_fn) + body_graph = produce_graph(body_fn) + + next_name = None + i = 0 + # pyrefly: ignore [bad-assignment] + while not next_name: + candidate = f"while_loop_cond_graph_{i}" + if hasattr(proxy_mode.tracer.root, candidate): + i += 1 + else: + next_name = candidate + cond_graph_name = next_name + body_graph_name = f"while_loop_body_graph_{i}" + if hasattr(proxy_mode.tracer.root, body_graph_name): + raise AssertionError( + f"proxy_mode.tracer.root already has attribute {body_graph_name}" + ) + + proxy_mode.tracer.root.register_module(cond_graph_name, cond_graph) + proxy_mode.tracer.root.register_module(body_graph_name, body_graph) + + args = (cond_graph, body_graph, carried_inputs, additional_inputs) + kwargs = {} + if not stack_output and mutated_arg_indices: + kwargs["mutated_arg_indices"] = mutated_arg_indices + + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", op, proxy_args, kwargs, name=op._name + ) + + out = op( + cond_graph, + body_graph, + unspecialized_carried_inputs, + additional_inputs, + **kwargs, + ) + return track_tensor_tree( + out, out_proxy, constant=None, tracer=proxy_mode.tracer + ) + + return _trace_while_loop( + mode, + op, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + mutated_arg_indices, + ) + + +@while_loop_op.py_impl(FakeTensorMode) +def while_loop_fake_tensor_mode( + mode, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + stack_output=False, + mutated_arg_indices="", +): + with mode: + # NOTE: [Handling unback symints in subgraph of while_loop] + # The idea is that the scope of unbacked symints are limited to the subgraph. + # + # We're implementing the fake tensor mode of while_loop operator. + # and we run body_fn once to get an fake output. + # Let's first consider the case that unbacked symints are tensor shapes: + # + # Case 1: + # if the unbacked symints is local to the subgraph e.g. + # def body_fn(it, x): + # nz = x.nonzero() + # return it+1. nz.sum() + # we can just ignore the newly created unbacked symints because it has + # no effect on the output of while_loop and it's tracked when we tracing. + # the subgraph. + # + # Case 2: + # if the unbacked symints are shape of output of while_loop e.g. + # def body_fn(it, x): + # nz = x.nonzero() + # return it+1, nz + # This will fail the shape check because in each iteration, the carried_input's shape + # must match the output shape as nz.shape contains newly allocated unbacked symint, this + # won't match the carried_input's shape. + # + # Case 3: + # if the unbacked symints are shape of carried_inputs e.g. + # nz = a.nonzero() + # body_fn(it, nz): + # return it+1. nz.sin() + 1, + # There's no new unbacked symints allocated in subgraph, so we're safe. + with mode.shape_env.ignore_fresh_unbacked_symbols(): + # body_fn return output with the same pytree and tensor meta data as carried_inputs + # so we could just return the output after one iteration. + body_outs = body_fn(*carried_inputs, *additional_inputs) + check_meta_consistency( + carried_inputs, + body_outs, + "carried_inputs", + "body_output", + include_contiguity=False, + ) + + if stack_output: + n_iter = _create_unbacked_symint(mode, ignore_fresh_unbacked_symbols=False) + if not all(isinstance(x, torch.Tensor) for x in carried_inputs): + raise AssertionError( + f"all carried_inputs must be tensors for stack_output, got {[type(x) for x in carried_inputs]}" + ) + fake_outputs = tuple( + out.clone() + .unsqueeze(0) + .repeat((n_iter,) + tuple(1 for _ in range(out.dim()))) + for out in body_outs + ) + return pytree.tree_map_only( + (int, torch.SymInt), + # For while_loop's unbacked symint output, we want them to be bound + # to the proxy of while_loop's output. + lambda _: _create_unbacked_symint( + mode, ignore_fresh_unbacked_symbols=False + ), + fake_outputs, + ) + + # See NOTE [unspecialize int carry with unbacked symints] + return pytree.tree_map_only( + (int, torch.SymInt), + # For while_loop's unbacked symint output, we want them to be bound + # to the proxy of while_loop's output. + lambda _: _create_unbacked_symint( + mode, ignore_fresh_unbacked_symbols=False + ), + body_outs, + ) + + +@while_loop_op.py_functionalize_impl +def while_loop_func( + ctx, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + stack_output=False, + mutated_arg_indices="", +): + op = while_loop_stack_output_op if stack_output else while_loop_op + # For now, we only support auto-functionalization for while_loop when using python + # functionalization mode + if not stack_output and hasattr(ctx, "mode"): + hop_instance = HopInstance.create( + op, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + mutated_arg_indices=mutated_arg_indices, + ) + if can_auto_functionalize(hop_instance): + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + tuple( + pytree.tree_flatten( + (cond_fn, body_fn, carried_inputs, additional_inputs) + )[0] + ), + {}, + ) + + unwrapped_carried_inputs = ctx.unwrap_tensors(carried_inputs) + unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs) + unwrapped_inputs = unwrapped_carried_inputs + unwrapped_additional_inputs + with ctx.redispatch_to_next(): + functional_cond_fn = ctx.functionalize(_maybe_run_with_interpreter(cond_fn)) + functional_body_fn = ctx.functionalize(_maybe_run_with_interpreter(body_fn)) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + for fn, fn_name in [ + (cond_fn, "cond_fn"), + (body_fn, "body_fn"), + ]: + _check_alias_and_mutation(fn, unwrapped_inputs, fn_name, pre_dispatch) + op_kwargs = {} + if not stack_output and mutated_arg_indices: + op_kwargs["mutated_arg_indices"] = mutated_arg_indices + ret = op( + functional_cond_fn, + functional_body_fn, + unwrapped_carried_inputs, + unwrapped_additional_inputs, + **op_kwargs, + ) + return ctx.wrap_tensors(ret) + + +class WhileLoopStackOutputOp(HigherOrderOperator): + """ + while_loop_stack_output is a variant of while_loop that returns a stack of outputs. + Its semantic can be illurated using python code as: + def while_loop_stack_output(cond_fn, body_fn, carried_inputs, additional_inputs): + outs = [] + while cond_fn(*carried_inputs, *additional_inputs): + out = body_fn(*carried_inputs, *additional_inputs) + outs.append(out) + return torch.stack(outs) + + It's useful for supporting autograd of while_loop. + """ + + def __init__(self) -> None: + super().__init__("while_loop_stack_output") + + def __call__( + self, + cond_fn: Callable, + body_fn: Callable, + carried_inputs: tuple[torch.Tensor | int | float | bool], + additional_inputs: tuple[torch.Tensor | torch.SymInt | int, ...], + /, + ): + if not isinstance(carried_inputs, (tuple, list)): + raise RuntimeError( + f"carried_inputs must be a tuple or list, got {type(carried_inputs)}" + ) + if not isinstance(additional_inputs, (tuple, list)): + raise RuntimeError( + f"additional_inputs must be a tuple or list, got {type(additional_inputs)}" + ) + + validate_subgraph_args_types(carried_inputs) + validate_subgraph_args_types(additional_inputs) + # pyrefly: ignore [missing-attribute] + return super().__call__(cond_fn, body_fn, carried_inputs, additional_inputs) + + +# Note [while_loop autograd] +# Consider wthe following while_loop that can be visualized as: +# additional_inputs +# ┌─────┬─────┼─────┬─────┐ +# | | | | | +# ↓ ↓ ↓ ↓ ↓ +# x ──→ y0 ─→ y1 ─→ y2 ─→ y3 ─→ y4 +# +# The backward can be visualized as follows: +# +# g_additional_inputs +# ┌──────┬──────┼──────┬──────┐ +# | | | | | +# | | | | | +# gx <── gy0 <─ gy1 <─ gy2 <─ gy3 <─ gy4 +# +# We can compute gx using chain rule: +# +# gx = gy0 * bw(y0, x), +# +# where gy0 denotes the gradient of loss with respect to y0, and bw(y0, x) denotes the gradient of y0 with +# respect to x. Note that bw can be computed from forward body_fn easily using torch.autograd.grad. +# We could substitute the unknowns gy0, gy1, ..., with chain rule until gy4: +# +# gx = gy1 * bw(y1, y0) * bw(y0, x) +# = gy2 * bw(y2, y1) * bw(y1, y0) * bw(y0, x) +# = ... +# = gy4 * bw(y4, y3) * bw(y3, y2) * bw(y2, y1) * bw(y1, y0) * bw(y0, x) +# +# since gy4 is the gradient of the final output, which is given as the backward input, we've got a formula +# to compute gx. A abbr for the formula is: gy4 * bw43210x +# +# In a similar way, we can compute g_additional_inputs using chain rule: +# +# g_additional_inputs = gy0 * bw(y0, addi) + gy1 * bw(y1, addi) + gy2 * bw(y2, addi) + ... + gy4 * bw(y4, addi) +# +# Notice that gy0 = gy4 * bw43210, gy1 = gy4 * bw4321 etc, we now also get a formula for g_additional_inputs. +# +# Implementation: +# The idea of implementation is to construct a while_loop to calculate both gx and g_additional_inputs. +# Specifically, we can implement the backward of while_loop with as follows: +# +# def cond_fn(idx, grad_carries, grad_additional_inputs, fw_additional_inputs, fw_inps): +# return idx < fw_inps.size(0) +# +# def body_fn(idx, grad_carries, grad_additional_inputs, fw_additional_inputs, fw_inps): +# reversed_idx = fw_inps.size(0) - 1 - idx +# next_grad_carry, next_grad_additional_inputs = bw(fw_inps[reversed_idx], fw_additional_inputs, grad_carries) +# return idx + 1, next_grad_carry, next_grad_additional_inputs + grad_additional_inputs +# +# idx = 0 +# init_grad_carries = grads +# init_grad_additional_inputs = torch.zeros_like(g_additional_inputs) +# fw_inps = torch.cat([ctx.fw_carried_inputs, fw_outputs[:-1]]) +# while_loop(cond_fn, body_fn, (idx, init_grad_carries, init_grad_additional_inputs,), (fw_additional_inputs, fw_inps)) + + +class WhileLoopAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + cond_fn, + body_fn, + num_carried_inputs, + num_additional_inputs, + *carries_and_inputs, + ): + from torch._higher_order_ops.scan import split_into_chunks + + carries, additional_inputs = split_into_chunks( + carries_and_inputs, [num_carried_inputs, num_additional_inputs] + ) + with torch._C._AutoDispatchBelowAutograd(): + fw_outputs = while_loop_stack_output_op( + cond_fn, body_fn, carries, additional_inputs + ) + + if hasattr(ctx, "fw_cond_fn"): + raise AssertionError("ctx already has fw_cond_fn attribute") + if hasattr(ctx, "fw_body_fn"): + raise AssertionError("ctx already has fw_body_fn attribute") + if hasattr(ctx, "carries"): + raise AssertionError("ctx already has carries attribute") + if hasattr(ctx, "additional_inputs"): + raise AssertionError("ctx already has additional_inputs attribute") + if hasattr(ctx, "fw_outputs"): + raise AssertionError("ctx already has fw_outputs attribute") + ctx.fw_cond_fn = cond_fn + ctx.fw_body_fn = body_fn + ctx.carries = carries + ctx.additional_inputs = additional_inputs + ctx.fw_outputs = fw_outputs + loop_count = None + # pyrefly: ignore [bad-assignment] + for out in fw_outputs: + if isinstance(out, torch.Tensor): + if loop_count is not None: + if out.size(0) != loop_count: + raise AssertionError( + f"inconsistent loop_count: expected {loop_count}, got {out.size(0)}" + ) + else: + loop_count = out.size(0) + if loop_count is None: + raise AssertionError( + "loop_count must not be None after processing fw_outputs" + ) + + # Remove the loop_count from pending_fresh_unbacked_symbols + # because it's not part of forward output and it's impossible + # to bind it to a proxy in forward graph anyways. + if ( + isinstance(loop_count, torch.SymInt) + and (shape_env := loop_count.node.shape_env) + and loop_count in shape_env.pending_fresh_unbacked_symbols + ): + shape_env.pending_fresh_unbacked_symbols.remove(loop_count) + + # Even when body function is not executed, we clone and unsqueeze the input + # to avoid the aliasing, therefore loop_count is always >= 1 + torch._check(loop_count >= 1) + # We snapshot the dispatch keys in forward for materializing the + # the bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + if len(fw_outputs) <= 0: + raise AssertionError("fw_outputs shouldn't be empty") + # Only the last of the output fw_outputs need to be returned + return tuple(ckp[-1] for ckp in fw_outputs) + + @staticmethod + def backward(ctx, *grads): + from torch._higher_order_ops.cond import create_bw_fn + from torch._higher_order_ops.scan import split_into_chunks + + # set up single step bw fn + bw_body_fn = create_bw_fn(ctx.fw_body_fn, ctx.carries + ctx.additional_inputs) + # Note [Handle inputs that're not differentiable] + # When a forward input is non-differentiable e.g. a symint or an integer tensor, their gradients + # will be None. However, we don't want to return None in the subgraph because this complicates the + # inductor codegen, where we need to do a non-uniform treatment for None and tensors. + # So we set up masks and filter the None gradients so that only tensors are returned from each step. + carries_tensor_masks = [ + bool(isinstance(t, torch.Tensor) and t.dtype.is_floating_point) + for t in ctx.carries + ] + additional_inputs_tensor_masks = [ + bool(isinstance(t, torch.Tensor) and t.dtype.is_floating_point) + for t in ctx.additional_inputs + ] + + init_idx = torch.zeros((), dtype=torch.int64) + # Autograd can pass view gradients. The generated backward while_loop + # needs stable carry metadata across iterations, so canonicalize tensor + # gradients before they become carries. + init_grad_carries = tuple( + grad.clone(memory_format=torch.contiguous_format) + if isinstance(grad, torch.Tensor) + else grad + for grad in filter_with_masks(grads, carries_tensor_masks) # type: ignore[arg-type] + ) + init_grad_additional_inputs = tuple( + torch.zeros_like(t) + for need_keep, t in zip( + additional_inputs_tensor_masks, ctx.additional_inputs + ) + if need_keep + ) + # We need to the forward inputs to each iteration to compute the backward + # which is the concatenation of first iteration input i.e. ctx.carries and all iterations' + # output except the last iteration. + fw_carries = [ + torch.cat([carry.unsqueeze(0), carries[:-1]]) + for carry, carries in zip(ctx.carries, ctx.fw_outputs) + ] + for fw_carry, carry in zip(fw_carries, ctx.carries): + fw_carry.requires_grad_(carry.requires_grad) + + _, spec = pytree.tree_flatten( + ( + init_idx, + init_grad_carries, + init_grad_additional_inputs, + ctx.fw_outputs, + ctx.additional_inputs, + ) + ) + + def cond_fn(*flat_args): + ( + idx, + grad_carries, + grad_additional_inputs, + fw_carries, + additional_inputs, + ) = pytree.tree_unflatten(flat_args, spec) + if not isinstance(fw_carries[0], torch.Tensor): + raise AssertionError( + f"expected fw_carries[0] to be torch.Tensor, got {type(fw_carries[0])}" + ) + # excluding the last iteration's output + return idx < fw_carries[0].size(0) + + def body_fn(*flat_args): + ( + idx, + grad_carries, + grad_additional_inputs, + fw_carries, + additional_inputs, + ) = pytree.tree_unflatten(flat_args, spec) + reversed_idx = fw_carries[0].size(0) - idx - 1 + selected_fw_carries = [ + ckp.select(0, reversed_idx.item()) for ckp in fw_carries + ] + cur_grad_carries, cur_grad_additional_inputs = split_into_chunks( + bw_body_fn(*selected_fw_carries, *additional_inputs, *grad_carries), + [len(ctx.carries), len(ctx.additional_inputs)], + ) + if not all(isinstance(t, torch.Tensor) for t in cur_grad_carries): + raise AssertionError( + f"all cur_grad_carries must be tensors, got {[type(t) for t in cur_grad_carries]}" + ) + cur_grad_carries_tensors = filter_with_masks( + cur_grad_carries, carries_tensor_masks + ) + cur_grad_additional_inputs_tensors = filter_with_masks( + cur_grad_additional_inputs, additional_inputs_tensor_masks + ) + return ( + idx + 1, + *cur_grad_carries_tensors, + *( + cur_grad + grad + for cur_grad, grad in zip( + cur_grad_additional_inputs_tensors, grad_additional_inputs + ) + ), + ) + + args_single_step_bw = ( + init_idx, + *init_grad_carries, + *init_grad_additional_inputs, + *fw_carries, + *ctx.additional_inputs, + ) + + cond_gm = materialize_as_graph( + cond_fn, + args_single_step_bw, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + + body_gm = materialize_as_graph( + body_fn, + args_single_step_bw, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + + _, final_grad_carries, final_grad_additional_inputs = split_into_chunks( + while_loop_op( + # pyrefly: ignore [bad-argument-type] + cond_gm, + # pyrefly: ignore [bad-argument-type] + body_gm, + # pyrefly: ignore [bad-argument-type] + ( + init_idx, + *init_grad_carries, + *init_grad_additional_inputs, + ), + (*fw_carries, *ctx.additional_inputs), + ), + [1, len(init_grad_carries), len(init_grad_additional_inputs)], + ) + return ( + None, + None, + None, + None, + *fill_none_with_masks(final_grad_carries, carries_tensor_masks), + *fill_none_with_masks( + final_grad_additional_inputs, additional_inputs_tensor_masks + ), + ) + + +while_loop_stack_output_op = WhileLoopStackOutputOp() + +while_loop_stack_output_op.py_impl(DispatchKey.CompositeExplicitAutograd)( + functools.partial(while_loop_dense, stack_output=True) +) + +while_loop_stack_output_op.py_impl(ProxyTorchDispatchMode)( + functools.partial(while_loop_tracing, stack_output=True) +) + +while_loop_stack_output_op.py_impl(FakeTensorMode)( + functools.partial(while_loop_fake_tensor_mode, stack_output=True) +) + +while_loop_stack_output_op.py_functionalize_impl( + functools.partial(while_loop_func, stack_output=True) +) + +while_loop_stack_output_op.py_autograd_impl( + autograd_not_implemented(while_loop_stack_output_op, deferred_error=True) +) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/wrap.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/wrap.py new file mode 100644 index 0000000000000000000000000000000000000000..cf3711ffecf6042c092364c04c921eb155890dd3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/wrap.py @@ -0,0 +1,547 @@ +# mypy: allow-untyped-defs +import inspect +import itertools +import logging +import weakref +from collections.abc import Callable +from typing import Any +from typing_extensions import ParamSpec, TypeVar + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + redirect_to_mode, + reenter_make_fx, + register_fake, +) +from torch._logging import warning_once +from torch._ops import HigherOrderOperator +from torch.fx import GraphModule +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.types import _dtype +from torch.utils._debug_mode import DebugMode +from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +log = logging.getLogger(__name__) + + +uid = itertools.count(1) + + +# Used for testing the HigherOrderOperator mechanism +class Wrap(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("wrap") + + def __call__( + self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs + ) -> _R: + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo # noqa: F401 + from torch._dynamo import disable + + @disable + def wrapper(): + result = func(*args, **kwargs) + return result + + return wrapper() + + +wrap = Wrap() + + +class InductorCompiledCode(HigherOrderOperator): + """ + Defines a HOP for wrapping inductor compiled functions as a callable. + When used with torch.compile via "wrap_inductor_compiled_regions", + this HOP will automatically be wrapped and redirect various torch dispatch modes. + """ + + def __init__(self) -> None: + super().__init__("inductor_compiled_code") + self._boxed_arg_indices = (1,) + + def __call__(self, func, inputs, *, name: str | None = None): + # pyrefly: ignore [missing-attribute] + return super().__call__(func, inputs, name=name) + + +inductor_compiled_code = InductorCompiledCode() +inductor_compiled_code.fallthrough(DispatchKey.AutogradCPU) +inductor_compiled_code.fallthrough(DispatchKey.AutogradCUDA) + + +_inductor_compiled_callable_id = itertools.count() + + +class InductorCompiledCallable: + """ + A wrapper class that holds both the Inductor-compiled callable and the + original FX graph for fake tensor propagation. + Each instance gets a globally unique idx at creation (via atomic itertools.count). + """ + + def __init__( + self, + compiled_callable, + original_gm=None, + compile_region_name: str | None = None, + ): + self.idx = next(_inductor_compiled_callable_id) + self.compiled_callable = compiled_callable + self.original_gm = original_gm + self.compile_region_name = compile_region_name + # AOT autograd needs this to know inputs are passed as a list + self._boxed_call = True + + def __call__(self, inputs): + return self.compiled_callable(inputs) + + +class InductorCodeSideTable: + """ + Side table for storing InductorCompiledCallable objects. + + We cannot put InductorCompiledCallable objects directly into the FX graph + as graph nodes do not support arbitrary objects. We use this side table + and pass callable.idx instead. + + Uses WeakValueDictionary so entries are automatically removed when + the InductorCompiledCallable is no longer referenced elsewhere + (e.g. after dynamo.reset() drops the compiled code cache). + """ + + def __init__(self): + self.id_to_callable: weakref.WeakValueDictionary[ + int, InductorCompiledCallable + ] = weakref.WeakValueDictionary() + + def add_callable(self, callable_obj: InductorCompiledCallable) -> int: + """Register a callable and return its idx.""" + self.id_to_callable[callable_obj.idx] = callable_obj + return callable_obj.idx + + def get_callable(self, idx: int) -> InductorCompiledCallable: + """Get the callable at the given index.""" + if idx not in self.id_to_callable: + raise AssertionError(f"Invalid inductor code index: {idx}") + return self.id_to_callable[idx] + + def __getstate__(self): + # Convert WeakValueDictionary to regular dict for pickling + return {"id_to_callable": dict(self.id_to_callable)} + + def __setstate__(self, state): + self.id_to_callable = weakref.WeakValueDictionary(state["id_to_callable"]) + + def reset_table(self) -> None: + """Reset the table.""" + self.id_to_callable = weakref.WeakValueDictionary() + + +inductor_code_side_table = InductorCodeSideTable() + + +def _resolve_inductor_callable( + func: int | InductorCompiledCallable, +) -> InductorCompiledCallable: + """ + Resolve func to an InductorCompiledCallable. + + func is either an InductorCompiledCallable directly (from post_compile) + or an int index into the side table (from a traced FX graph node). + """ + if isinstance(func, int): + return inductor_code_side_table.get_callable(func) + if not isinstance(func, InductorCompiledCallable): + raise AssertionError(f"Unexpected func type: {type(func)}") + return func + + +@inductor_compiled_code.py_impl(DispatchKey.CompositeExplicitAutograd) +def inductor_compiled_code_impl(func, inputs, *, name=None): + resolved = _resolve_inductor_callable(func) + return resolved.compiled_callable(inputs) + + +redirect_to_mode(inductor_compiled_code, DebugMode) +redirect_to_mode(inductor_compiled_code, _CachingTorchDispatchMode) +redirect_to_mode(inductor_compiled_code, _CachedTorchDispatchMode) + + +@register_fake(inductor_compiled_code) +def inductor_compiled_code_fake(func, inputs, *, name=None): + resolved = _resolve_inductor_callable(func) + if resolved.original_gm is None: + raise RuntimeError( + "inductor_compiled_code original_gm is None — the compiled graph may " + "have been serialized without it. Recompile to restore." + ) + # Run the original FX graph under FakeTensorMode to re-derive output + # shapes, dtypes, and aliasing from the input fake tensors. + return tuple(resolved.original_gm(*inputs)) + + +@inductor_compiled_code.py_functionalize_impl +def inductor_compiled_code_functionalize(ctx, func, inputs, *, name=None): + # Unwrap the functional tensors to get the underlying tensors + unwrapped_inputs = ctx.unwrap_tensors(inputs) + + # Redispatch to the next handler in the dispatch chain + with ctx.redispatch_to_next(): + kwargs = {"name": name} if name is not None else {} + result = inductor_compiled_code(func, unwrapped_inputs, **kwargs) + return ctx.wrap_tensors(result) + + +@inductor_compiled_code.py_impl(ProxyTorchDispatchMode) +def inductor_compiled_code_proxy(mode, func, inputs, *, name=None): + resolved = _resolve_inductor_callable(func) + + # Run the fake impl to get example outputs for tracing + kwargs = {"name": name} if name is not None else {} + example_out = inductor_compiled_code(func, inputs, **kwargs) + + # Register in side table so the FX node stores a serializable int + callable_idx = inductor_code_side_table.add_callable(resolved) + + proxy_inputs = pytree.tree_map(mode.tracer.unwrap_proxy, inputs) + + out_proxy = mode.tracer.create_proxy( + "call_function", + inductor_compiled_code, + (callable_idx, proxy_inputs), + kwargs, + ) + + return track_tensor_tree(example_out, out_proxy, constant=None, tracer=mode.tracer) + + +class WrapWithSetGradEnabled(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("wrap_with_set_grad_enabled") + + def __call__( + self, + enable_grad: bool, + wrapped_func: Callable[_P, _R], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> _R: + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo + from torch._dynamo import disable + + @disable + def wrapper(): + prev = torch.is_grad_enabled() + torch.set_grad_enabled(enable_grad) + res = wrapped_func(*args, **kwargs) + torch.set_grad_enabled(prev) + return res + + return wrapper() + + +wrap_with_set_grad_enabled = WrapWithSetGradEnabled() + + +class WrapWithAutocast(HigherOrderOperator): + def __init__(self): + super().__init__("wrap_with_autocast") + + def __call__( + self, + device_type: str, + dtype: _dtype | None, + enabled: bool, + cache_enabled: bool | None, + wrapped_func: Callable[_P, _R], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> _R: + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo + from torch._dynamo import disable + + @disable + def wrapper(): + with torch.autocast(device_type, dtype, enabled, cache_enabled): + return wrapped_func(*args, **kwargs) + + return wrapper() + + +wrap_with_autocast = WrapWithAutocast() + + +# This HOP allows you to bypass dynamo tracing of the wrapper function while +# still tracing the inner function. +# Takes two callables: The first, `wrapper_fn`, accepts `inner_fn` and returns a +# callable with the same signature. The second is the `inner_fn` itself. Any +# extra *args and **kwargs are forwarded to `wrapper_fn(inner_fn)` when it is +# executed. +class DynamoBypassingWrapper(HigherOrderOperator): + def __init__(self): + super().__init__("dynamo_bypassing_wrapper") + + def __call__( + self, + wrapper_fn_or_key, + inner_fn, + *args, + **kwargs, + ): + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo + from torch._dynamo import disable + + is_compiling = isinstance(wrapper_fn_or_key, str) + if is_compiling: + if not isinstance(inner_fn, torch.fx.GraphModule): + raise AssertionError( + f"expected inner_fn to be torch.fx.GraphModule, got {type(inner_fn)}" + ) + wrapper_fn = inner_fn.meta[wrapper_fn_or_key] + else: + wrapper_fn = wrapper_fn_or_key + + @disable + def wrapper(): + return wrapper_fn(inner_fn)(*args, **kwargs) + + return wrapper() + + +dynamo_bypassing_wrapper = DynamoBypassingWrapper() + + +class WrapActivationCheckpoint(HigherOrderOperator): + """ + This operator is used to wrap torch.utils.checkpoint. This avoids + TorchDynamo to look into saved tensor hooks and directly passes the control + to AOT Autograd, which is ok with tracing saved tensor hooks. As a result of + AOT tracing torch.utils.checkpoint code, we have a backward graph with + recomputed forward nodes. + + However, we might deprecate this operator soon. The difficulty arises in the + functionalization of rng ops. Today, there are two different + functionalization of rng ops - one at AOT autograd and other at Inductor. + And they are difficult to map to each other. The rng states also complicate + pattern matching in Inductor. Due to the ease of implementation, we are + currently inclined towards functionalization at Inductor level, which means + that duplication/recomputation is done as a compiler pass in the + partitioners. See TagActivationCheckpoint for more information. + """ + + def __init__(self) -> None: + super().__init__("wrap_activation_checkpoint", cacheable=False) + + def __call__(self, function: GraphModule, *args: Any, **kwargs: Any) -> Any: + # use_reentrant is set to False because this op is going to be traced. + # And we ensure that AOT Autograd traces through the non reentrant + # version of checkpointing. + import torch.fx.traceback as fx_traceback + from torch.fx import Interpreter + + kwargs["use_reentrant"] = False + kwargs["preserve_rng_state"] = False + # Using interpreter allows preservation of metadata through torch.compile stack. + with fx_traceback.preserve_node_meta(): + from torch.utils.checkpoint import checkpoint + + return checkpoint(Interpreter(function).run, *args, **kwargs) + + +wrap_activation_checkpoint = WrapActivationCheckpoint() + + +class TagActivationCheckpoint(HigherOrderOperator): + """ + This operator is supposed to be used only with torch.compile stack. This + accepts a Fx graph module which needs to be checkpointed. This operator adds + "recomputable" tag to the nodes of the Fx graph that should be recomputed. + + The goal is to: + 1. Avoid using Dynamo to trace through saved tensor hooks. + 2. For selective checkpointing case, let AOTAutograd trace through + saved tensor hooks but has special logic with TorchDispatchMode to override + the usual saved_tensor_hooks fn logic in order to tag the nodes. + 3. Rely on the partitioners to actually duplicate the nodes. + This sits well in the torch.compile stack, because by the time graph + reaches partitioner, inductor has already run its functionalization of rng + ops (by setting fixed seed for each random op, see `replace_random_passes`). + Therefore, the duplication of nodes, by design, respects the rng states in + the forward and recomputed forward in backward. + """ + + def __init__(self) -> None: + super().__init__("tag_activation_checkpoint", cacheable=True) + + @staticmethod + def divide_kwargs(kwargs): + """ + checkpoint fn can have mixed kwargs between checkpointed fn and + checkpoint fn itself. For example + >> def gn(x, y, z=None): + >> a = torch.matmul(x, y) + >> if z is not None: + >> return torch.matmul(a, z) + >> return a + >> def fn(x, y, z): + >> return torch.cos(checkpoint(gn, x, y, use_reentrant=False, z=z)) + In the above case, z belongs to checkpointed function gn, but + use_reentrant belongs to the checkpoint function. This function splits + the kwargs into checkpoint_kwargs and gmod_kwargs (or + checkpointed_fn_kwargs). + We do sorting to ensure same graph from run to run for better + debuggability. It is not required for correctness. + """ + from torch.utils.checkpoint import checkpoint + + ckpt_signature = inspect.signature(checkpoint) + checkpoint_keys = set() + for name in ckpt_signature.parameters: + if name in ("function", "args", "kwargs"): + continue + checkpoint_keys.add(name) + + # `preserve_rng_state` is not a regular kwarg + checkpoint_keys.add("preserve_rng_state") + + checkpoint_kwargs = { + name: kwargs[name] for name in kwargs if name in checkpoint_keys + } + gmod_kwargs = { + name: kwargs[name] for name in kwargs if name not in checkpoint_keys + } + return checkpoint_kwargs, gmod_kwargs + + def __call__(self, gmod, *args, **kwargs): + dispatch_key_set = torch._ops._compute_keyset( + args, kwargs, self.non_fallthrough_keys + ) + dispatch_key = dispatch_key_set.highestPriorityTypeId() + if dispatch_key == torch._C.DispatchKey.PreDispatch: + # pyrefly: ignore [missing-attribute] + return super().__call__(gmod, *args, **kwargs) + + return tag_activation_checkpoint_impl(gmod, *args, **kwargs) + + +tag_activation_checkpoint = TagActivationCheckpoint() + + +def _always_prefer_recompute(ctx, op, *args, **kwargs): + from torch.utils.checkpoint import CheckpointPolicy + + return CheckpointPolicy.PREFER_RECOMPUTE + + +def tag_activation_checkpoint_impl(gmod, *args, **kwargs): + import functools + + import torch.fx.traceback as fx_traceback + from torch.fx import Interpreter + from torch.utils.checkpoint import create_selective_checkpoint_contexts + + unique_graph_id = next(uid) + if "_checkpoint_context_fn" in gmod.meta: + context_fn = gmod.meta["_checkpoint_context_fn"] + warning_once( + log, + """ +Detected that context_fn is passed to torch.utils.checkpoint under torch.compile. +Please make sure the checkpointed region does not contain in-place ops (e.g. torch.relu_). +""", + ) + else: + # Vanilla AC: use the SAC path with a policy that always recomputes. + context_fn = functools.partial( + create_selective_checkpoint_contexts, _always_prefer_recompute + ) + + def context_fn_with_graph_id(): + fwd_ctx, recomp_ctx = context_fn() + # Plumb ac_graph_id so _CachingTorchDispatchMode tags all nodes + # (including ops from desugared HOPs like custom autograd.Function). + fwd_ctx.ac_graph_id = unique_graph_id + return fwd_ctx, recomp_ctx + + # use_reentrant is set to False because this op is going to be traced. + # And we ensure that AOT Autograd traces through the non reentrant + # version of checkpointing. + kwargs["use_reentrant"] = False + # preserve_rng_state is set to False because we want to prevent AOTAutograd from tracing through + # `torch.random.fork_rng` op (which is not supported yet under CUDA). + # This doesn't mean that we don't preserve RNG state. Instead, we will always preserve RNG state + # regardless of this flag (by doing RNG functionalization via `replace_random_passes` in Inductor + # instead of in AOTAutograd). + kwargs["preserve_rng_state"] = False + kwargs["context_fn"] = context_fn_with_graph_id + # Disable early stop to prevent _StopRecomputationError from interrupting + # recomputation between _vmap_increment_nesting and _vmap_decrement_nesting, + # which would leak a functorch dynamic layer. + kwargs["early_stop"] = False + # Using interpreter allows preservation of metadata through torch.compile stack. + # We use a wrapper instead of passing Interpreter(gmod).run directly because + # checkpoint's recompute_fn captures the function in a closure. A bound method + # reference would keep the Interpreter alive, whose env dict retains the output + # tensors and prevents the autograd graph from being freed. + + def run_with_interpreter(*args): + return Interpreter(gmod).run(*args) + + with fx_traceback.preserve_node_meta(): + from torch.utils.checkpoint import checkpoint + + return checkpoint(run_with_interpreter, *args, **kwargs) + + +@tag_activation_checkpoint.py_impl(ProxyTorchDispatchMode) +def proxy_mode_key( + proxy_mode: ProxyTorchDispatchMode, + gmod: GraphModule, + *args: Any, + **kwargs: Any, +) -> tuple[torch.Tensor]: + import torch.fx.traceback as fx_traceback + from torch.fx import Interpreter + + if not proxy_mode.pre_dispatch: + raise AssertionError( + "post-dispatch mode should have inlined in the Autograd key" + ) + example_out = tag_activation_checkpoint(gmod, *args, **kwargs) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) # type: ignore[union-attr] + proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, kwargs) # type: ignore[union-attr] + qualname = proxy_mode.tracer.get_fresh_qualname("wrap_body") # type: ignore[union-attr] + + # TODO (tmanlaibaatar) don't we need flat_apply here?? + # Dynamo already traced the gmod body without kwargs + flat_args, _ = pytree.tree_flatten(args) + with fx_traceback.preserve_node_meta(): + gmod_aten = reenter_make_fx(Interpreter(gmod).run)(*flat_args) + gmod_aten.meta["_checkpoint_context_fn"] = gmod.meta["_checkpoint_context_fn"] + proxy_mode.tracer.root.register_module(qualname, gmod_aten) # type: ignore[union-attr] + proxy_gmod = proxy_mode.tracer.unwrap_proxy(gmod_aten) # type: ignore[union-attr, call-overload] + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", + tag_activation_checkpoint, + (proxy_gmod, *proxy_args), + proxy_kwargs, + ) + return track_tensor_tree( + example_out, out_proxy, constant=None, tracer=proxy_mode.tracer + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__autotune_main__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/__autotune_main__.py new file mode 100644 index 0000000000000000000000000000000000000000..1eb5ca86e8c185e9c355e6dea152b53a3f181519 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__autotune_main__.py @@ -0,0 +1,33 @@ +import argparse +import logging +import os + +from torch._inductor.autotune_process import TuningProcess +from torch._inductor.compile_worker.utils import _async_compile_initializer + + +log = logging.getLogger(__name__) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--parent", type=int) + parser.add_argument("--read-fd", type=int) + parser.add_argument("--write-fd", type=int) + args = parser.parse_args() + read_pipe = os.fdopen(args.read_fd, "rb") + write_pipe = os.fdopen(args.write_fd, "wb") + + try: + # Ensures the subprocess exits if the parent crashes: + _async_compile_initializer(args.parent) + TuningProcess.process_main(read_pipe, write_pipe) + except Exception: + log.exception("Uncaught exception in autotune subprocess") + finally: + read_pipe.close() + write_pipe.close() + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..812f79dda45a2c91695eb2b27171dd46e04236b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__init__.py @@ -0,0 +1,482 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import dataclasses +import io +import logging +import os +from typing import Any, IO, Literal, Optional, TYPE_CHECKING, Union + +import torch.fx + +from .standalone_compile import ( + compile_to_python, + CompiledArtifact, + DynamicShapesType, + load_from_python, +) + + +if TYPE_CHECKING: + from torch._inductor.utils import InputType + from torch._subclasses import FakeTensorMode + from torch.export import ExportedProgram + from torch.export.pt2_archive._package import AOTICompiledModel + from torch.export.pt2_archive._package_weights import Weights + from torch.types import FileLike + +__all__ = [ + "compile", + "compile_to_python", + "load_from_python", + "list_mode_options", + "list_options", + "cudagraph_mark_step_begin", + "standalone_compile", +] + + +log = logging.getLogger(__name__) + + +def compile( + gm: torch.fx.GraphModule, + example_inputs: list[InputType], + options: dict[str, Any] | None = None, +): + """ + Compile a given FX graph with TorchInductor. This allows compiling + FX graphs captured without using TorchDynamo. + + Args: + gm: The FX graph to compile. + example_inputs: List of tensor inputs. + options: Optional dict of config options. See `torch._inductor.config`. + + Returns: + Callable with same behavior as gm but faster. + """ + from .compile_fx import compile_fx + + return compile_fx(gm, example_inputs, config_patches=options) + + +def aoti_compile_and_package( + exported_program: ExportedProgram, + _deprecated_unused_args=None, + _deprecated_unused_kwargs=None, + *, + package_path: FileLike | None = None, + inductor_configs: dict[str, Any] | None = None, +) -> str: + """ + Compiles the exported program with AOTInductor, and packages it into a .pt2 + artifact specified by the input package_path. To load the package, you can + call ``torch._inductor.aoti_load_package(package_path)``. + + An example usage is as follows: + + .. code-block:: python + + ep = torch.export.export(M(), ...) + aoti_file = torch._inductor.aoti_compile_and_package( + ep, package_path="my_package.pt2" + ) + compiled_model = torch._inductor.aoti_load_package("my_package.pt2") + + To compile and save multiple models into a single ``.pt2`` artifact, you can do + the following: + + .. code-block:: python + + ep1 = torch.export.export(M1(), ...) + aoti_file1 = torch._inductor.aot_compile( + ep1, ..., options={"aot_inductor.package": True} + ) + ep2 = torch.export.export(M2(), ...) + aoti_file2 = torch._inductor.aot_compile( + ep2, ..., options={"aot_inductor.package": True} + ) + + from torch._inductor.package import package_aoti, load_package + + package_aoti("my_package.pt2", {"model1": aoti_file1, "model2": aoti_file2}) + + compiled_model1 = load_package("my_package.pt2", "model1") + compiled_model2 = load_package("my_package.pt2", "model2") + + Args: + exported_program: An exported program created through a call from torch.export + package_path: Optional specified path to the generated .pt2 artifact. + inductor_configs: Optional dictionary of configs to control inductor. + + Returns: + Path to the generated artifact + """ + from torch.export import ExportedProgram + + from .debug import aot_inductor_minifier_wrapper + + if not isinstance(exported_program, ExportedProgram): + raise ValueError("Only ExportedProgram is supported") + + if exported_program.example_inputs is None: + raise RuntimeError( + "exported_program.example_inputs is required to be set in order " + "for AOTInductor compilation." + ) + + if _deprecated_unused_args is not None or _deprecated_unused_kwargs is not None: + log.warning( + "You no longer need to specify args/kwargs to aoti_compile_and_package " + "as we can get this information from exported_program.example_inputs." + ) + + if not ( + package_path is None + or ( + isinstance(package_path, (io.IOBase, IO)) + and package_path.writable() + and package_path.seekable() + ) + or ( + isinstance(package_path, (str, os.PathLike)) + and os.fspath(package_path).endswith(".pt2") + ) + ): + raise AssertionError( + f"Expect package path to be a file ending in .pt2, is None, or is a buffer. Instead got {package_path}" + ) + + inductor_configs = inductor_configs or {} + inductor_configs["aot_inductor.package"] = True + + if inductor_configs.get("aot_inductor.output_path"): + raise RuntimeError( + "Please pass in a package path to aot_inductor_compile() instead " + "of setting the aot_inductor.output_path config." + ) + + # a wrapper around aoti_compile_and_package_inner. + return aot_inductor_minifier_wrapper( + _aoti_compile_and_package_inner, + exported_program, + package_path=package_path, + inductor_configs=inductor_configs, + ) + + +def _aoti_compile_and_package_inner( + gm: torch.nn.Module, + # flat_example_inputs: List[Any], + args: tuple[Any], + kwargs: dict[str, Any] | None = None, + *, + load_and_run: bool = False, + check_accuracy: str | None = None, + package_path: str | io.BytesIO | None = None, + inductor_configs: dict[str, Any] | None = None, +): + """ + See docstring for aoti_compile_and_package. + + If `load_and_run` is True, this function will load the compiled model and run it. + This is for the minifier to check the correctness of the compiled model. + + If `check_accuracy` is set, this function will check the accuracy of the compiled + model against gm. kwargs must be None if check_accuracy is set. + "strict_accuracy" means "we will minify any time we see anything that + diverges", whereas "accuracy" is more conservative, and will only minify if there + is a meaningful fp64 divergence + """ + + if check_accuracy: + if not (kwargs is None or len(kwargs) == 0): + raise AssertionError( + "when checking for accuracy, the inputs must have been flattened and kwargs is None" + ) + + from .package import package_aoti + + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"expected torch.fx.GraphModule, got {type(gm)}") + + kwargs = kwargs or {} + + aoti_files = aot_compile(gm, args, kwargs, options=inductor_configs) + if not isinstance(aoti_files, list): + raise AssertionError( + f"expected aoti_files to be a list, got {type(aoti_files)}" + ) + + if package_path is None: + path = [ + os.path.splitext(file)[0] + for file in aoti_files + if isinstance(file, str) and os.path.splitext(file)[1] == ".so" + ] + if len(path) == 0: + path = [ + os.path.splitext(file)[0] + for file in aoti_files + if isinstance(file, str) and os.path.splitext(file)[1] == ".cpp" + ] + package_path = path[0] + ".pt2" + + res = package_aoti(package_path, aoti_files) + if res != package_path: + raise AssertionError( + f"expected res == package_path, got {res} != {package_path}" + ) + + if load_and_run or check_accuracy: + compiled_model = aoti_load_package(package_path) + if check_accuracy: + from torch._dynamo.debug_utils import AccuracyError, same_two_models + + # This might look inverted but it's not. strict_accuracy means "we will + # minify any time we see anything that diverges", whereas accuracy is more + # conservative, and will only minify if there is a meaningful fp64 + # divergence + not_strict_accuracy = check_accuracy == "accuracy" + if not same_two_models( + gm, + compiled_model, # type: ignore[arg-type] + args, + only_fwd=True, + require_fp64=not_strict_accuracy, + ignore_non_fp=not_strict_accuracy, + ): + raise AccuracyError("Bad accuracy detected") + else: + compiled_model(*args, **kwargs) + + return package_path + + +def aoti_load_package( + path: FileLike, run_single_threaded: bool = False, device_index: int = -1 +) -> AOTICompiledModel: + """ + Loads the model from the PT2 package. + + If multiple models were packaged into the PT2, this will load the default + model. To load a specific model, you can directly call the load API + + .. code-block:: python + + from torch._inductor.package import load_package + + compiled_model1 = load_package("my_package.pt2", "model1") + compiled_model2 = load_package("my_package.pt2", "model2") + + Args: + path: Path to the .pt2 package + run_single_threaded (bool): Whether the model should be run without + thread synchronization logic. This is useful to avoid conflicts with + CUDAGraphs. + device_index (int): The index of the device to which the PT2 package is + to be loaded. By default, `device_index=-1` is used, which corresponds + to the device `cuda` when using CUDA. Passing `device_index=1` would + load the package to `cuda:1`, for example. + """ + from torch._inductor.package import load_package + + return load_package( + path, run_single_threaded=run_single_threaded, device_index=device_index + ) + + +def aot_compile( + gm: torch.fx.GraphModule, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + options: dict[str, Any] | None = None, +) -> str | list[str | Weights] | torch.fx.GraphModule: + """ + Ahead-of-time compile a given FX graph with TorchInductor into a shared library. + + Args: + gm: The FX graph to compile. + args: Example arguments + kwargs: Example keyword arguments + options: Optional dict of config options. See `torch._inductor.config`. + + Returns: + Path to the generated shared library, or a list of files generated by + AOTI if aot_inductor.package=True. + TODO: make it return a list by default + """ + from .compile_fx import _aoti_flatten_inputs, compile_fx_aot + + if hasattr(gm, "_guards_fn"): + # Do not compile the guards function, since it may contain checks + # that are not currently supported by AOTI. In particular, non-Tensor + # arguments are converted to None and will fail specialization checks. + node = next(iter(gm.graph.find_nodes(op="call_module", target="_guards_fn"))) + gm.graph.erase_node(node) + delattr(gm, "_guards_fn") + gm.recompile() + + flat_example_inputs, options = _aoti_flatten_inputs( + gm, args, kwargs, options=options + ) + from torch._export.utils import _compiling_state_context + + with _compiling_state_context(): + return compile_fx_aot( + gm, + flat_example_inputs, # type: ignore[arg-type] + config_patches=options, + ) + + +lite_mode_options = { + # Fallback by default unless users explicitly annotated with + # regional inductor compile. + "fallback_by_default": True, + "selective_decompose": True, + # Disable reorder optimizations + "reorder_for_peak_memory": False, + "reorder_for_compute_comm_overlap": False, + "triton.reorder_for_reducing_graph_partitions": False, + # Disable pre-, joint-, post-grad passes + "use_pre_grad_passes": False, + "use_joint_graph_passes": False, + "use_post_grad_passes": False, + # Disable dead code elimination (dce) and buffer reuse + "use_dce": False, + "allow_buffer_reuse": False, +} + + +def list_mode_options( + mode: str | None = None, dynamic: bool | None = None +) -> dict[str, Any]: + r"""Returns a dictionary describing the optimizations that each of the available + modes passed to `torch.compile()` performs. + + Args: + mode (str, optional): The mode to return the optimizations for. + If None, returns optimizations for all modes + dynamic (bool, optional): Whether dynamic shape is enabled. + + Example:: + >>> torch._inductor.list_mode_options() + """ + + mode_options: dict[str, dict[str, bool]] = { + "default": {}, + # lite backend for opt-in optimizations + "lite": lite_mode_options, + # enable cudagraphs + "reduce-overhead": { + "triton.cudagraphs": True, + }, + # enable max-autotune + "max-autotune-no-cudagraphs": { + "max_autotune": True, + "coordinate_descent_tuning": True, + }, + # enable max-autotune + # enable cudagraphs + "max-autotune": { + "max_autotune": True, + "triton.cudagraphs": True, + "coordinate_descent_tuning": True, + }, + } + try: + return mode_options[mode] if mode else mode_options + except KeyError as e: + raise RuntimeError( + f"Unrecognized mode={mode}, should be one of: {', '.join(mode_options.keys())}" + ) from e + + +def list_options() -> list[str]: + r"""Returns a dictionary describing the optimizations and debug configurations + that are available to `torch.compile()`. + + The options are documented in `torch._inductor.config`. + + Example:: + + >>> torch._inductor.list_options() + """ + + from torch._inductor import config + + current_config: dict[str, Any] = config.get_config_copy() + + return list(current_config.keys()) + + +def cudagraph_mark_step_begin(): + "Indicates that a new iteration of inference or training is about to begin." + from .cudagraph_trees import mark_step_begin + + mark_step_begin() + + +def standalone_compile( + gm: torch.fx.GraphModule, + example_inputs: list[InputType], + *, + dynamic_shapes: DynamicShapesType = "from_graph", + options: dict[str, Any] | None = None, + aot: bool = False, # AOT mode, which uses BundledAOTAutogradCache + donate_graph_module: bool = False, + fake_mode: FakeTensorMode | None = None, +) -> CompiledArtifact: + """ + Precompilation API for inductor. + + .. code-block:: python + + compiled_artifact = torch._inductor.standalone_compile(gm, args) + compiled_artifact.save(path=path, format="binary") + + # Later on a new process + loaded = torch._inductor.CompiledArtifact.load(path=path, format="binary") + compiled_out = loaded(*args) + + Args: + gm: Graph Module + example_inputs: Inputs for the graph module + dynamic_shapes: If "from_graph" (default), we will use the dynamic + shapes in the passed-in graph module. + If "from_tracing_context", we use the dynamic shape info in the + ambient tracing context. + If "from_example_inputs", we will specialize the graph on the + example_inputs. + options: Inductor compilation options + donate_graph_module: If True, standalone_compile takes ownership of + the graph module and may mutate it, avoiding an internal deepcopy. + Defaults to False for backwards compatibility. + fake_mode: Optional FakeTensorMode to use when + dynamic_shapes="from_example_inputs". The mode must have a ShapeEnv. + When omitted, a fresh FakeTensorMode is created as before. + + Returns: + CompiledArtifact that can be saved to disk or invoked directly. + """ + from .standalone_compile import standalone_compile + + options = options if options else {} + return standalone_compile( + gm, + example_inputs, + dynamic_shapes=dynamic_shapes, + options=options, + aot=aot, + donate_graph_module=donate_graph_module, + fake_mode=fake_mode, + ) + + +@dataclasses.dataclass +class _CudagraphAnnotation: + fwd: bool | None + bwd: bool | None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__autotune_main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__autotune_main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e0b25cb4a4c3cb30e09614147cada04bc25d9b3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__autotune_main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6836eb4dd23f712e2826ce80d36d6cbaf2239e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/_functionalize_collectives.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/_functionalize_collectives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3e3890d51dd359b97564606a3379759f6e6c870 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/_functionalize_collectives.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/analyze_preserves_zero_mask.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/analyze_preserves_zero_mask.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bda7c4d725c0f68d70eb5a6cde627a42eeb0c701 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/analyze_preserves_zero_mask.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/aoti_eager.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/aoti_eager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adcb0b7842532b7c0fe323e9779ac6baf44841fe Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/aoti_eager.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/async_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/async_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e79aa9cebb0e83f815b7f158cfb33cafdb7a037 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/async_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/augmented_graph_helper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/augmented_graph_helper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73aede45dda0bba6b20d2f75bf44acd16507cdf9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/augmented_graph_helper.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autotune_process.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autotune_process.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f399541c0b8a752b9cc1cb31d43589690a67cccf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autotune_process.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autows_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autows_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e073139bf88b95c7aeea208f2f7470b7a8022181 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autows_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/await_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/await_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edad66bd25e3b240755e988d1f7eab94bc325597 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/await_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/bounds.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/bounds.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf5024f5e096e6e8ea5d0ff070fed5e3fdae8016 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/bounds.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..194bb8ea1ec6819daf0c77ba71be29756591c4bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache_key.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache_key.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ad906d9239598d3327a74c221a7bfa172b34153 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache_key.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/choices.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/choices.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ad0149a08695c75e3856e1bba56c45d4cffe1d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/choices.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/codecache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/codecache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..134c6a8e0e400bd3d7cf6eaed3581dd0e4c04dbb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/codecache.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33f6eca55b4b869b5d71edb06b70b1adcfa4d5ee412991a06da5bd6e2345183d +size 236970 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6706e97b6f8313959e3aff6e5821e4da742083a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_lowering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_lowering.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04bcaf9a653b845c9373cd7dc84ad1ccfd07db9e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_lowering.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..954f333cff3cf8a796138e9f01124ff86898f758 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms_debug.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms_debug.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32e694aff6c2058215ccf26a58aac65fbfe776ed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms_debug.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..164831ceb77071b7f81af3a93fac4f4f0ac588c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26bcde47491027cc58aa68bedfe1ebca31539a665c27b602d11271dbb12cd3b2 +size 137781 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_async.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_async.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e30f4c7a308d53b778f46811f2a3222ff33bf9c5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_async.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_ext.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_ext.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9328a229db0b21ae3e8ab3f138786cedf5135e3c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_ext.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_subproc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_subproc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd3049cfae7b217ffa41e606b1445fde4a6f8367 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_subproc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compiler_bisector.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compiler_bisector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d8fdd015baf76d4f84373a139084a37362cd1f9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compiler_bisector.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a3cba1945b5b1b464e5ca15248f15b57bfa0a6e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config_comms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config_comms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90d6465530e746344d18b088c8ad5a89657453cf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config_comms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/constant_folding.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/constant_folding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e726c310ff3e622bd6ad65614a555af1cdc3114 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/constant_folding.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpp_builder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpp_builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b625e2822871579b9542711b40b85d1b465c98f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpp_builder.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af115f2c901b26586b2d3d59c0df71877fef7d5bf88542a0b89fdc5e5eaff339 +size 121438 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpu_vec_isa.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpu_vec_isa.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c57f6813e82a372878deacb974a19478afc21a8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpu_vec_isa.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ac38271f814c932a9722cffbdc8bca13b150f1e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49e2e49eb436bd4d7001db2152b0904f3197838ade499b2b5e78ca46a769f4cb +size 137043 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d94e0dbfce53c61046b732b52f17d04ca1ed164 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/custom_graph_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/custom_graph_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b3117489b8fbbd5226ae361e3a1a682b1337796 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/custom_graph_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/debug.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/debug.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57367e6955e0c7991a5e144204a4f223b5efda5a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/debug.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/decomposition.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/decomposition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b522c7e492d01630474084981071497c9738f90 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/decomposition.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dependencies.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dependencies.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ebdc1afd7c988ba9ee085e11193fb296d1762f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dependencies.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/distributed_autotune.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/distributed_autotune.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1df5b7689e4579b476d02b45fcccbae8928d1813 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/distributed_autotune.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dtype_propagation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dtype_propagation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63d0d5d09aac226f2b7d7e5e365550beaf946cab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dtype_propagation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/exc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/exc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0890310ce15bf95b25e3a7bf3cb55362050185ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/exc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/extern_node_serializer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/extern_node_serializer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f527ae65aec2cd6cc7ee0243c4aa8d322f11f410 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/extern_node_serializer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..866a80177f8de298fe734dd5745b01362c8a5fee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e5d1c608641ccdb329278ef7897583023b932b9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fuzzer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fuzzer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ac9ba61a228f2f85eeab678c309d66d0891297 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fuzzer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fx_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fx_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a3e8f321924eaa1b1159e980845c7d9148313d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fx_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8df2c362750319f1eef65d52f23a1723b416c0f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/graph.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:160222280b6715040f44eddbfac4b16c6b955bf849377fedad34cf922a85253a +size 139308 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/hooks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/hooks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3cae4f882c8f38a6fb5add748d8f066d0482f7a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/hooks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/index_propagation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/index_propagation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ca95552bb76fd576ba015b2beb83af05f1831ee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/index_propagation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/inductor_prims.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/inductor_prims.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d5f6bf2cbe94d15aa0deb136bb921b26faf4a03 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/inductor_prims.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/invert_expr_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/invert_expr_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad91a7ddae9faaccb1cd2a41868ac5599e1614cb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/invert_expr_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ir.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ir.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30db6ce324782b53ea8ba75d10e6f03631e55337 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ir.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c0618d3762bc8d5750c0f2ef6c80b02ee4d93a6d3a9f2e428e94f9236a5fe79 +size 535082 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/jagged_lowerings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/jagged_lowerings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb2ed01fa1dd1749be642934225053136b2bb4e7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/jagged_lowerings.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_inputs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_inputs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac2066de23fd1a41cfad5c91d0d4d0a05d3b0a58 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_inputs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_template_choice.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_template_choice.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bd2744c618916c5b27d17cf4b2537986f5a2ef6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_template_choice.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/loop_body.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/loop_body.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85cbdb1ee5dc883d3d9bdb78aec46e5d9010ff22 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/loop_body.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/lowering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/lowering.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e1e46317de4ed20e2edb31b1d468adbef61043d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/lowering.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b65d1c07128421aeb9d1aa5c3bf90537364e481285347bb6c2aaf7c1a11eb8d +size 430031 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/memory.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..497216134844cfc519638427f2fa9e2cb5ece6c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/memory.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/metrics.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf33b8d854deed25997b93c16c15a67dbdc30cf2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/metrics.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_ir.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_ir.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bc76047972156fe07de1f86b36208ac2ea1dfaf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_ir.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_lowerings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_lowerings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01fd34b02a42e2203d1c7e6efa4a0e7f815ba1d2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_lowerings.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mock_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mock_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a748ae1459e6cb86712f8a5d5f80f8676517da6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mock_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ops_handler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ops_handler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0198be6f82024d9acc341dad342057e3e16ccbaf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ops_handler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/optimize_indexing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/optimize_indexing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c10967fe2970d19c5882c1354ac7c486b35af419 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/optimize_indexing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/output_code.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/output_code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c72dec09e33f61cc6dd538f59982718e3f69bd1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/output_code.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfe89dda8eb977a2cb5e8ccaa4818a4dc000bf6d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ff8d3ff9ebd219f4ead9ddeb317e86abff83f18f697d2d0ac7f5c010f0636aa +size 142840 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/profiler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/profiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d1ad044ef47b0cfa9566ec23fe6069acbd542b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/profiler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/quantized_lowerings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/quantized_lowerings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..204f618e66ce0c2ea99899fd698a2b01c254ee9c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/quantized_lowerings.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ac088c88c697616daa4b742e58cb80a489cfa7e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_gemm_autotune_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_gemm_autotune_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb454a037a927e8cdeae3663923439b5ebb48dab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_gemm_autotune_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/rocm_multiarch_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/rocm_multiarch_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f949dcde62c770e5a548b45ecf7ed68a222d56b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/rocm_multiarch_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/scheduler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/scheduler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..181b50f5835d49f691c63a7b6f516cb9204bcb6a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/scheduler.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92ff0cf9e3aa868072c79f0b80d0fc3cea314d098276a184c9aa08af35d0e864 +size 484481 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b52ee3f31f6fc915e876f446c3ad47cdabcc14d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94160e09779b7fd68401a088940241eba7c391bbc016816467a98153e828fa06 +size 268738 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/shape_propagation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/shape_propagation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7715ed0072cc06d937d97e57c31ff7484830c747 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/shape_propagation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/sizevars.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/sizevars.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68c907c0d2c74470f4a5aa93c0db74b755c63337 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/sizevars.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/standalone_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/standalone_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b327c95c90549812b9d2aba929097e4cac36988 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/standalone_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_constants.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2b5dd91666b906da979b89ab74535e3d23e8f94 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_constants.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae9c859474cc2daf69e528463dfdb5c56c9675e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/subgraph_lowering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/subgraph_lowering.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c2c6f2c7d3489e4ef521fb77f8d614c354d2191 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/subgraph_lowering.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_case.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_case.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da6b21fccee181933e42cc72669501cded87e21a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_case.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312-pytest-9.1.1.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82f758716a210e89ec19d4164cb4bc3298b57a00 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312-pytest-9.1.1.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b589382338b2740ec1daa61452b4c0b95ebe0fd1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/tiling_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/tiling_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaca787708420edcd0b889677d5a5ea8f73b4f5f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/tiling_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/triton_bundler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/triton_bundler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..331b1752331aa45b8f679c0fc2cb4a588fc3f9b4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/triton_bundler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..474364fe9132944793e38078a7bee8f63ab18fe2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/utils.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5539c8cf92f9ffdeb8473ee14e4fba9cccfaf6ed35e78f183f974157975af34 +size 218651 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/virtualized.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/virtualized.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad330b0dd278b6147fb606156a3001efc2dc16cf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/virtualized.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/wrapper_benchmark.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/wrapper_benchmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..958bf1cd18914142c3bb8c78d7dcec4e36e935f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/wrapper_benchmark.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/_functionalize_collectives.py b/.venv/lib/python3.12/site-packages/torch/_inductor/_functionalize_collectives.py new file mode 100644 index 0000000000000000000000000000000000000000..6a25c0a64b07a9b71085eee5a9e8d965e02fdc34 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/_functionalize_collectives.py @@ -0,0 +1,283 @@ +"""Rewrite raw ``c10d.{op}_`` inplace ops produced by ``make_fx`` into +``_c10d_functional.{op}`` + ``wait_tensor`` + ``aten.copy_`` form so +``standalone_compile`` (and Inductor's collective machinery underneath) can +recognize and lower them. + +The structure separates concerns: + * Arg resolution (PG, ReduceOp) lives in ``_resolve_*``. + * The functional + wait + copy_ chain construction lives in + ``_emit_collective_chain`` (used by every per-op rewrite). + * Use redirection lives in ``_redirect_*_work_uses`` keyed by output schema. + * Per-op rewrites (``_rewrite__``) glue these together. + * The driver ``_functionalize_inplace_collectives`` walks the graph, + dispatches by target, and runs final cleanup. +""" + +from __future__ import annotations + +import operator +from collections.abc import Callable +from typing import Any + +import torch +from torch.fx.graph_module import _assign_attr, _del_attr, _get_attr + + +def _resolve_reduce_op_str( + gm: torch.fx.GraphModule, arg: torch.fx.node.Argument +) -> str: + """Get the lower-case op string (``"sum"``/``"avg"``/...) for a c10d + ReduceOp ``get_attr`` arg, converting from the torchbind ScriptObject + form if needed. + + Only the ``get_attr`` (constant-baked) shape is supported today. Any + other producer (placeholder, call_function, ...) would require + ``_c10d_functional.*`` to accept ReduceOp directly (today it only + takes the string form); deferred to a follow-up PR. + """ + import torch.distributed as dist + from torch.distributed._functional_collectives import REDUCE_OP_TO_STR + + if not isinstance(arg, torch.fx.Node) or arg.op != "get_attr": + raise NotImplementedError( + f"ReduceOp arg must be a constant ``get_attr``; got {arg!r}." + ) + reduce_op = _get_attr(gm, arg.target) # type: ignore[arg-type] + if isinstance(reduce_op, torch.ScriptObject): + reduce_op = dist.ReduceOp.RedOpType(reduce_op.op()) # type: ignore[attr-defined] + return REDUCE_OP_TO_STR[reduce_op] + + +def _emit_collective_chain( + gm: torch.fx.GraphModule, + before: torch.fx.Node, + input_t: torch.fx.Node, + output_t: torch.fx.Node, + functional_target: Any, + extra_args: tuple[Any, ...], + pg_arg: torch.fx.Node, + custom: Any, +) -> torch.fx.Node: + """Insert ``_c10d_functional.(input, *extra_args, pg_arg)`` -> + ``wait_tensor`` -> ``aten.copy_(output, wait)`` immediately before + ``before`` and return the ``wait_tensor`` node. + + Propagates ``output_t.meta["val"]`` onto every new node — every functional + collective we rewrite to produces a tensor with the same shape/dtype as + ``output_t``, and ``aten.copy_`` returns ``output_t``. Also carries the + rewritten node's ``custom`` annotation forward so region scooping continues + to work. + """ + val = output_t.meta.get("val") + with gm.graph.inserting_before(before): + ar = gm.graph.call_function(functional_target, (input_t, *extra_args, pg_arg)) + wait = gm.graph.call_function( + torch.ops._c10d_functional.wait_tensor.default, (ar,) + ) + copy_ = gm.graph.call_function(torch.ops.aten.copy_.default, (output_t, wait)) + if val is not None: + ar.meta["val"] = wait.meta["val"] = copy_.meta["val"] = val + if custom is not None: + ar.meta["custom"] = wait.meta["custom"] = copy_.meta["custom"] = custom + return wait + + +def _redirect_inplace_collective_uses( + gm: torch.fx.GraphModule, + node: torch.fx.Node, + wait_nodes: list[torch.fx.Node], +) -> None: + """Re-route uses for an inplace c10d op with output schema + ``(Tensor[], Work)`` — e.g. ``allreduce_``, ``broadcast_``, + ``reduce_scatter_``, ``alltoall_``. + + ``make_fx`` lowers tensor consumers into ``getitem(node, 0)[i]``; replace + each with ``wait_nodes[i]``. The work-handle ``getitem(node, 1)`` is erased + if unused (live users raise — functional collectives have no Work object + to forward to, so we can't preserve that synchronization). + + TODO: extend to ``(Tensor, Work)`` schemas (``_allgather_base_``, + ``_reduce_scatter_base_``) when those rewrites are added. There the + ``getitem(node, 0)`` is itself the tensor consumer (no inner + ``getitem`` chain), so the inner loop below would need to fall back to + ``use.replace_all_uses_with(wait_nodes[0])`` when ``use`` has no inner + ``getitem`` users. + """ + for use in list(node.users): + if use.op != "call_function" or use.target is not operator.getitem: + raise AssertionError( + f"Cannot functionalize {node.target}: unexpected use {use} " + f"(op={use.op!r}, target={use.target!r}). The c10d inplace " + f"output is a tuple consumed via ``getitem`` in ``make_fx`` " + f"graphs; non-getitem users are not supported by this pass." + ) + if use.args[1] == 0: + for sub_use in list(use.users): + if ( + sub_use.op != "call_function" + or sub_use.target is not operator.getitem + ): + raise AssertionError( + f"Cannot functionalize {node.target}: tensor list " + f"consumed by non-getitem user {sub_use}. Extend " + f"_redirect_inplace_collective_uses to support this " + f"schema if needed." + ) + sub_use.replace_all_uses_with(wait_nodes[sub_use.args[1]]) # type: ignore[index] + gm.graph.erase_node(sub_use) + gm.graph.erase_node(use) + elif use.args[1] == 1: + if use.users: + raise AssertionError( + f"Cannot functionalize {node.target}: Work handle has " + f"{len(use.users)} live use(s) ({list(use.users)}). " + f"Functional collectives express synchronization via " + f"``wait_tensor`` on the data tensor, so the Work object " + f"has no equivalent to forward to." + ) + gm.graph.erase_node(use) + + +def _rewrite_allreduce_(gm: torch.fx.GraphModule, node: torch.fx.Node) -> None: + """Reference rewrite — use this as a template for new collectives. + + Schema: ``c10d::allreduce_(Tensor[] tensors, ProcessGroup pg, ReduceOp op, + Tensor? sparse_indices, bool async_op, int timeout=-1) -> (Tensor[], Work)``. + + Before:: + + allreduce_ = c10d.allreduce_([t0, t1], pg, reduce_op, None, False) + getitem = allreduce_[0] + getitem_1 = getitem[0] # consumer of t0 post-allreduce + getitem_2 = getitem[1] # consumer of t1 post-allreduce + ... = allreduce_[1] # work handle (unused) + + After (per input tensor; ``pg`` is the original ``get_attr`` Node — a + later pass will bake it into a ``group_name`` string):: + + ar_i = _c10d_functional.all_reduce(t_i, op_str, pg) + wait_i = _c10d_functional.wait_tensor(ar_i) + _ = aten.copy_(t_i, wait_i) # preserves inplace semantics + # downstream uses of ``getitem_`` are redirected to ``wait_i`` + """ + tensors = node.args[0] + pg_arg = node.args[1] + if not isinstance(tensors, (list, tuple)): + raise AssertionError(f"expected ``Tensor[]`` arg list, got {type(tensors)}") + if not isinstance(pg_arg, torch.fx.Node): + raise AssertionError(f"expected ProcessGroup as fx.Node, got {type(pg_arg)}") + op_str = _resolve_reduce_op_str(gm, node.args[2]) + custom = node.meta.get("custom") + waits = [] + for t in tensors: + if not isinstance(t, torch.fx.Node): + raise AssertionError(f"expected tensor entry as fx.Node, got {type(t)}") + waits.append( + _emit_collective_chain( + gm, + node, + t, + t, + torch.ops._c10d_functional.all_reduce.default, + (op_str,), + pg_arg, + custom, + ) + ) + _redirect_inplace_collective_uses(gm, node, waits) + + +_InplaceCollectiveRewrite = Callable[[torch.fx.GraphModule, torch.fx.Node], None] + + +def _inplace_c10d_rewrites() -> dict[Any, _InplaceCollectiveRewrite] | None: + """Map inplace ``c10d.{op}_`` op targets to per-op rewrite functions. + + Returns ``None`` if ``torch.distributed`` is not available. + + To support a new collective: write ``_rewrite__`` (typically a few + lines using ``_resolve_reduce_op_str`` / ``_emit_collective_chain`` / + ``_redirect_inplace_collective_uses``), then register it here. + """ + if not torch.distributed.is_available(): + return None + return { + torch.ops.c10d.allreduce_.default: _rewrite_allreduce_, + } + + +def _functionalize_inplace_collectives( + gm: torch.fx.GraphModule, +) -> torch.fx.GraphModule: + """Rewrite raw ``torch.ops.c10d.{op}_`` inplace calls in ``gm`` into + ``_c10d_functional.{op}`` + ``wait_tensor`` + ``aten.copy_`` form so + Inductor's collective machinery can recognize and lower them. + """ + rewrites = _inplace_c10d_rewrites() + if rewrites is None: + return gm + + found = False + for node in list(gm.graph.nodes): + if node.op != "call_function": + continue + rewrite = rewrites.get(node.target, None) + if rewrite is None: + continue + rewrite(gm, node) + # Snapshot ``get_attr`` args before erasing the rewritten node. + # Inplace c10d ops are impure; ``eliminate_dead_code`` keeps them + # alive even with no users, so erase explicitly. Then drop any + # ``get_attr`` arg that became orphan (e.g. the ReduceOp whose + # value got baked into ``op_str``) along with its backing module + # attribute. Live ones (e.g. the ProcessGroup, still referenced + # by the new ``_c10d_functional`` call) are kept. + get_attr_args = [ + a for a in node.args if isinstance(a, torch.fx.Node) and a.op == "get_attr" + ] + gm.graph.erase_node(node) + for a in get_attr_args: + if not a.users: + _del_attr(gm, a.target) # type: ignore[arg-type] + gm.graph.erase_node(a) + found = True + + if found: + gm.recompile() + return gm + + +def _unbox_process_group_torchbinds( + gm: torch.fx.GraphModule, +) -> torch.fx.GraphModule: + """Replace ProcessGroup torchbind attrs with their unboxed Python + ``dist.ProcessGroup``. + + ``make_fx`` traces ``dist.*`` collectives with a torchbind + ``__torch__.torch.classes.c10d.ProcessGroup`` baked in as a graph attr. + Inductor's collective ops (``_c10d_functional.{op}``) accept either a + ``group_name`` string or a Python ``dist.ProcessGroup`` — but **not** a + raw torchbind, which fails at runtime with:: + + all_reduce_(): argument 'group_name' must be either a string ... + but got __torch__.torch.classes.c10d.ProcessGroup + + Unboxing the attribute in-place (without changing the FX graph) makes + the PG acceptable to the runtime collective op. The deepcopy + share-by-reference hook in ``GraphModule.__deepcopy__`` is what lets + ``standalone_compile``'s deepcopy of the gm survive the non-pickleable + Python ``dist.ProcessGroup``. + """ + import torch.distributed as dist + + if not torch.distributed.is_available(): + return gm + + for node in gm.graph.find_nodes(op="get_attr"): + attr = _get_attr(gm, node.target) # type: ignore[arg-type] + if not isinstance(attr, torch.ScriptObject): + continue + if attr._type().qualified_name() != "__torch__.torch.classes.c10d.ProcessGroup": # type: ignore[attr-defined] + continue + _assign_attr(dist.ProcessGroup.unbox(attr), gm, node.target) # type: ignore[arg-type] + return gm diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85f59e1a1ad8225e2be86c295e1eca5b480f36a3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/device_info.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/device_info.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddd4071a68d046ae3aec8c1a089353002b56b83f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/device_info.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/profile_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/profile_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c6a5f51a5ea730c3b8cbefa66b75e67a760892d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/profile_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/device_info.py b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/device_info.py new file mode 100644 index 0000000000000000000000000000000000000000..737ead7be59806bdb708dbe1c258a6a6cf61dcf2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/device_info.py @@ -0,0 +1,345 @@ +import logging +from dataclasses import dataclass + +import torch + + +log = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class DeviceInfo: + """ + Theoretical numbers from data sheet. When a data sheet reports both + Tensor/Matrix-Core and non-Tensor-Core numbers, the higher (Tensor Core) + number is used. + + NVIDIA data sheets since Hopper (H100) only publish Tensor-Core TFLOPS + with 2:4 structured sparsity (marked ``*With sparsity``). For devices + whose ``tops`` include sparsity, set ``tops_sparsity_factor`` to 2 so + that callers can recover the dense (non-sparse) throughput used by + cuBLAS / cuDNN in normal (non-sparse) workloads. + + Bandwidth numbers are tricky, because there are platform differences + that may not show up in the profiler trace. + """ + + tops: dict[torch.dtype | str, float] + dram_bw_gbs: float + dram_gb: float + tops_sparsity_factor: int = 1 + + +# Indexing is based on `torch.cuda.get_device_name()`, normalized to upper-case. +# TODO investigate profiler support for tf32 and allow device to report correct number when it's turned on. +_device_mapping: dict[str, DeviceInfo] = { + # Source: + # @lint-ignore https://www.nvidia.com/en-us/data-center/h100/ + # Tensor Core values are *with sparsity* per the datasheet. + "NVIDIA H100": DeviceInfo( + tops={ + torch.float64: 67.0, + torch.float32: 67.0, + "torch.tf32": 989.0, + torch.bfloat16: 1979.0, + torch.float16: 1979.0, + torch.float8_e8m0fnu: 3958.0, + torch.float8_e8m0fnu: 3958.0, + torch.float8_e4m3fnuz: 3958.0, + torch.float8_e5m2: 3958.0, + torch.float8_e5m2fnuz: 3958.0, + torch.float8_e8m0fnu: 3958.0, + torch.int8: 3958.0, + }, + dram_bw_gbs=3350, + dram_gb=80, + tops_sparsity_factor=2, + ), + # Source: + # @lint-ignore https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/ + # nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf + "NVIDIA A100": DeviceInfo( + tops={ + torch.float64: 19.5, + torch.float32: 19.5, + torch.bfloat16: 312.5, + torch.float16: 312.5, + # Not in datasheet: float8 + torch.int8: 624.0, + "torch.tf32": 156.0, + }, + dram_bw_gbs=2039.0, + dram_gb=80.0, + ), + # Source: + # @lint-ignore https://resources.nvidia.com/en-us-gpu-resources/l4-tensor-datasheet + "NVIDIA L4": DeviceInfo( + tops={ + # This is a guess, not in datasheet + torch.float64: 15.1, + torch.float32: 30.3, + "torch.tf32": 120.0, + torch.bfloat16: 242.0, + torch.float16: 242.0, + torch.float8_e8m0fnu: 485.0, + torch.float8_e8m0fnu: 485.0, + torch.float8_e4m3fnuz: 485.0, + torch.float8_e5m2: 485.0, + torch.float8_e5m2fnuz: 485.0, + torch.float8_e8m0fnu: 485.0, + torch.int8: 485.0, + }, + dram_bw_gbs=3350, + dram_gb=24, + ), + # Source: + # @lint-ignore https://www.amd.com/content/dam/amd/en/documents\ + # /instinct-tech-docs/product-briefs/amd-instinct-mi350x-gpu-brochure.pdf + "AMD MI350X": DeviceInfo( + tops={ + torch.float64: 72.1, + torch.float32: 144.2, + # not specified, fall back to float32 numbers + "torch.tf32": 144.2, + torch.bfloat16: 2309.6, + torch.float16: 2309.6, + torch.float8_e8m0fnu: 4614.0, + torch.float8_e8m0fnu: 4614.0, + torch.float8_e4m3fnuz: 4614.0, + torch.float8_e5m2: 4614.0, + torch.float8_e5m2fnuz: 4614.0, + torch.float8_e8m0fnu: 4614.0, + torch.int8: 4614.0, + }, + dram_bw_gbs=8000.0, + dram_gb=288.0, + ), + # Source: + # @lint-ignore https://www.amd.com/content/dam/amd/en/documents\ + # /instinct-tech-docs/data-sheets/amd-instinct-mi300a-data-sheet.pdf + "AMD MI300A": DeviceInfo( + tops={ + torch.float64: 122.6, + torch.float32: 122.6, + "torch.tf32": 490.3, + torch.bfloat16: 980.6, + torch.float16: 980.6, + torch.float8_e8m0fnu: 1961.2, + torch.float8_e8m0fnu: 1961.2, + torch.float8_e4m3fnuz: 1961.2, + torch.float8_e5m2: 1961.2, + torch.float8_e5m2fnuz: 1961.2, + torch.float8_e8m0fnu: 1961.2, + torch.int8: 1961.2, + }, + dram_bw_gbs=5300.0, + dram_gb=128.0, + ), + # Source: + # @lint-ignore https://www.amd.com/content/dam/amd/en/documents/\ + # instinct-tech-docs/data-sheets/amd-instinct-mi300x-data-sheet.pdf + "AMD MI300X": DeviceInfo( + tops={ + torch.float64: 163.4, + torch.float32: 163.4, + "torch.tf32": 653.7, + torch.bfloat16: 1307.4, + torch.float16: 1307.4, + torch.float8_e8m0fnu: 2614.9, + torch.float8_e8m0fnu: 2614.9, + torch.float8_e4m3fnuz: 2614.9, + torch.float8_e5m2: 2614.9, + torch.float8_e5m2fnuz: 2614.9, + torch.float8_e8m0fnu: 2614.9, + torch.int8: 2614.9, + }, + dram_bw_gbs=5300.0, + dram_gb=192.0, + ), + # Source: + # @lint-ignore https://www.amd.com/content/dam/amd/\ + # en/documents/instinct-business-docs/product-briefs/instinct-mi210-brochure.pdf + "AMD MI210X": DeviceInfo( + tops={ + torch.float64: 45.3, + torch.float32: 45.3, + # not specified, fall back to float32 numbers + "torch.tf32": 45.3, + torch.bfloat16: 181.0, + torch.float16: 181.0, + # not specified, fall back to float16 numbers + torch.float8_e8m0fnu: 181.0, + torch.float8_e8m0fnu: 181.0, + torch.float8_e4m3fnuz: 181.0, + torch.float8_e5m2: 181.0, + torch.float8_e5m2fnuz: 181.0, + torch.float8_e8m0fnu: 181.0, + torch.int8: 181.0, + }, + # pcie4.0x16 + dram_bw_gbs=1600.0, + dram_gb=64.0, + ), + # Source: + # @lint-ignore https://www.intel.com/content/www/us/en/products/sku/241598/ + # intel-arc-b580-graphics/specifications.html + "INTEL B580": DeviceInfo( + tops={ + # Estimated from published single-precision throughput. + torch.float64: 6.83, + torch.float32: 13.67, + "torch.tf32": 116.5, + torch.bfloat16: 116.5, + torch.float16: 116.5, + # not specified, fall back to fp16 matrix throughput + torch.float8_e8m0fnu: 116.5, + torch.float8_e4m3fnuz: 116.5, + torch.float8_e5m2: 116.5, + torch.float8_e5m2fnuz: 116.5, + torch.int8: 233, + }, + dram_bw_gbs=456.0, + dram_gb=12.0, + ), + # Source: + # @lint-ignore https://www.intel.com/content/www/us/en/products/sku/245797/ + # intel-arc-pro-b70-graphics/specifications.html + "INTEL B70": DeviceInfo( + tops={ + torch.float64: 11.47, + torch.float32: 22.94, + "torch.tf32": 183.5, + torch.bfloat16: 183.5, + torch.float16: 183.5, + torch.float8_e8m0fnu: 183.5, + torch.float8_e4m3fnuz: 183.5, + torch.float8_e5m2: 183.5, + torch.float8_e5m2fnuz: 183.5, + torch.int8: 367, + }, + dram_bw_gbs=608.0, + dram_gb=32.0, + ), + # Source: + # @lint-ignore https://www.intel.com/content/www/us/en/products/sku/232876/\ + # intel-data-center-gpu-max-1100/specifications.html + "Intel(R) Data Center GPU Max 1100": DeviceInfo( + # XeCore count: 56, + # vector/matrix engines per XeCore: 8 + # freq: 1.55GHz + tops={ + # Vector engine + torch.float64: 11.1, + torch.float32: 22.2, + # not specified, fall back to float32 numbers + "torch.tf32": 22.2, + # Matrix engine + torch.float16: 355.5, + torch.bfloat16: 355.5, + # not supported, fall back to float32 numbers + torch.float8_e8m0fnu: 22.2, + torch.float8_e4m3fnuz: 22.2, + torch.float8_e5m2: 22.2, + torch.float8_e5m2fnuz: 22.2, + torch.int8: 711.1, + }, + dram_bw_gbs=1228.8, + dram_gb=48, + ), +} +_device_mapping["AMD INSTINCT MI350X"] = _device_mapping["AMD MI350X"] +_device_mapping["AMD INSTINCT MI300X"] = _device_mapping["AMD MI300X"] +_device_mapping["AMD INSTINCT MI210X"] = _device_mapping["AMD MI210X"] +_device_mapping["Intel(R) Arc(TM) B580 Graphics"] = _device_mapping["INTEL B580"] +_device_mapping["Intel(R) Arc(TM) Pro B70 Graphics"] = _device_mapping["INTEL B70"] + +# Enforce the upper-case-key invariant so entries cannot silently miss +# `lookup_device_info` (which upper-cases the query before lookup). +_device_mapping = {k.upper(): v for k, v in _device_mapping.items()} + + +def lookup_device_info(name: str) -> DeviceInfo | None: + """ + Problem: when diffing profiles between amd and nvidia, we don't have access to the device information + of the other one. Also, since the analysis is static, we should be able to do it on another device unrelated + to the recorded device. Therefore, _device_mapping statically contains the information for lots of devices. + If one is missing, please run DeviceInfo.get_device_info() and add it to _device_mapping. + name (str): name of the device to lookup. Should map onto torch.cuda.get_device_name(). + Will be upper-cased before lookup. + """ + return _device_mapping.get(name.upper()) + + +def datasheet_tops( + dtype: torch.dtype, is_tf32: bool = False, device_name: str | None = None +) -> float | None: + """ + Get the theoretical *dense* TFLOPS of the device for a given dtype. + + If the datasheet values include 2:4 structured sparsity + (``tops_sparsity_factor > 1``), they are divided by that factor so + callers always receive the throughput achievable by cuBLAS/cuDNN on + non-sparse data. + + If ``device_name`` is given, the datasheet is looked up for that named + device instead of querying the current device. This lets callers pin a + device spec for deterministic, hardware-independent estimates. + """ + if device_name is not None: + name: str | None = device_name + elif torch.cuda.is_available(): + name = torch.cuda.get_device_name() + elif torch.xpu.is_available(): + name = torch.xpu.get_device_name() + else: + log.info("No supported device available, skipping datasheet lookup") + return None + + if name is None: + log.info("No device found, returning None") + return None + device_info = lookup_device_info(name) + if device_info is None: + log_str = f"Device {name} not in datasheet, returning None" + log.info(log_str) + return None + if dtype not in device_info.tops: + log.info( + "Device %s does not have a datasheet entry for %s, returning None", + name, + dtype, + ) + return None + + tops = device_info.tops[ + "torch.tf32" if dtype == torch.float32 and is_tf32 else dtype + ] + return tops / device_info.tops_sparsity_factor + + +def datasheet_dram_bw_gbs(device_name: str | None = None) -> float | None: + """ + Get the theoretical DRAM bandwidth (GB/s) of a device from the datasheet, + or None if the device is not present. + + If ``device_name`` is given, that named device is looked up; otherwise the + current CUDA/XPU device is queried. + """ + if device_name is None: + if torch.cuda.is_available(): + device_name = torch.cuda.get_device_name() + elif torch.xpu.is_available(): + device_name = torch.xpu.get_device_name() + else: + log.info("No supported device available, skipping datasheet lookup") + return None + + if device_name is None: + log.info("No device found, returning None") + return None + + device_info = lookup_device_info(device_name) + if device_info is None: + log.info("Device %s not in datasheet, returning None", device_name) + return None + return device_info.dram_bw_gbs diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/profile_analysis.py b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/profile_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba32ec7a16ca478ed5a72c1355520d083378f2d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/profile_analysis.py @@ -0,0 +1,859 @@ +import json +import logging +import math +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Optional + +import torch +from torch._inductor.analysis.device_info import DeviceInfo, lookup_device_info +from torch._inductor.utils import tabulate_2d, zip_dicts +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet +from torch.utils.flop_counter import flop_registry + + +log = logging.getLogger(__name__) + + +ATEN_PREFIX = "aten::" + + +@dataclass +class ProfileEvent: + category: str + key: str + self_device_time_ms: float + # the benchmark is run multiple times and we average the count across all the + # runs. It should be an integer but define a float just in case. + count: float + + +# adapters convert the json trace into a format that works with flops_counter +ArgsType = tuple[tuple[Any, ...], dict[Any, Any]] +AdapterType = Callable[[tuple[Any, ...], tuple[Any, ...]], ArgsType] +adapters_map: dict[str, AdapterType] = {} + + +def parse_list(lst: str) -> list[int]: + lst = lst.replace("[", "").replace("]", "") + substrings = lst.split(",") + + return [int(substring.strip()) for substring in substrings] + + +def register_adapter( + aten: str | list[str], +) -> Callable[ + [AdapterType], + AdapterType, +]: + def decorator(func: AdapterType) -> AdapterType: + # pyrefly: ignore [unknown-name] + global _adapters_map + + if isinstance(aten, str): + adapters_map[aten] = func + else: + for at in aten: + adapters_map[at] = func + return func + + return decorator + + +@register_adapter(["_slow_conv2d_forward"]) +def _slow_conv2d_adapter( + shapes: tuple[Any, ...], concrete: tuple[Any, ...] +) -> tuple[tuple[Any], dict[Any, Any]]: + tmp = list(shapes) + tmp.append(False) + tmp2 = list(concrete) + if len(tmp2) < 5: + raise ParseException("slow conv2d has less than 5 concrete inputs") + tmp2[3] = tmp2[4] + return conv_adapter(tuple(tmp), tuple(tmp2)) + + +@register_adapter( + ["convolution", "_convolution", "cudnn_convolution", "convolution_overrideable"] +) +def conv_adapter( + shapes: tuple[Any, ...], concrete: tuple[Any, ...] +) -> tuple[tuple[Any], dict[Any, Any]]: + tmp = list(shapes) + if len(tmp) == 4: + transposed = False + elif len(tmp) > 6: + transposed = bool(tmp[6]) + tmp[6] = transposed + else: + raise ParseException(f"Convolution has the wrong number of inputs: {len(tmp)}") + + kwargs: dict[Any, Any] = {} + if not transposed: + # calculate output shape if not transposed. + def conv_out_dims(x: int, kernel: int, stride: int) -> int: + return (x - kernel) // stride + 1 + + stride = parse_list(concrete[3]) + inp = shapes[0] + w = shapes[1] + out_x_y = [conv_out_dims(*args) for args in zip(inp[2:], w[2:], stride)] + out = [inp[0], w[0]] + out_x_y # we only need the xy values + kwargs["out_val"] = out + + return tuple(tmp), kwargs + + +def default_adapter( + shapes: tuple[Any], concrete: tuple[Any] +) -> tuple[tuple[Any], dict[Any, Any]]: + return shapes, {} + + +@register_adapter("addmm") +def addmm_adapter( + shapes: tuple[Any], concrete: tuple[Any] +) -> tuple[tuple[Any], dict[Any, Any]]: + tmp = list(shapes)[:3] + return tuple(tmp), {} + + +@register_adapter("bmm") +def bmm_adapter( + shapes: tuple[Any], concrete: tuple[Any] +) -> tuple[tuple[Any], dict[Any, Any]]: + tmp = list(shapes) + return tuple(tmp[:2]), {} + + +@register_adapter("baddbmm") +def baddbmm_adapter( + shapes: tuple[Any], concrete: tuple[Any] +) -> tuple[tuple[Any], dict[Any, Any]]: + tmp = list(shapes)[:3] + return tuple(tmp), {} + + +@register_adapter("mm") +def mm_adapter( + shapes: tuple[Any], concrete: tuple[Any] +) -> tuple[tuple[Any], dict[Any, Any]]: + return shapes, {} + + +def _parse_kernel_name(name: str) -> str | None: + """ + parse the name of the kernel from the event name. + """ + if name.startswith(ATEN_PREFIX): + return name[len(ATEN_PREFIX) :] + elif "conv" in name: + return "convolution" + elif "addmm" in name: + return "addmm" + elif "bmm" in name: + return "bmm" + elif "baddbmm" in name: + return "baddbmm" + elif "_mm" in name: + return "mm" + else: + return None + + +def _calculate_flops(event: dict[str, Any]) -> int: + """ + This function has to parse the kernel name, which is error prone. There doesn't seem to be another solution that + will support all the different backends that can generate kernels, so make sure to update this function when new + ops and backends are desired. + """ + name = event["name"] + if "kernel_flop" in event["args"] and event["args"]["kernel_flop"] != 0: + return event["args"]["kernel_flop"] + op_name = _parse_kernel_name(name) + if op_name is None: + return 0 + + op_obj = getattr(torch.ops.aten, op_name, None) + if op_obj is None or op_obj not in flop_registry: + return 0 + + flop_function = flop_registry[op_obj] + + if "Input Dims" not in event["args"] or "Concrete Inputs" not in event["args"]: + return 0 + input_shapes = event["args"]["Input Dims"] + concrete = event["args"]["Concrete Inputs"] + if op_name in adapters_map: + try: + args, kwargs = adapters_map[op_name](input_shapes, concrete) + except ParseException as e: + msg = f"Failed to parse {op_name} with {e}" + log.warning(msg) + return 0 + else: + try: + args, kwargs = default_adapter(input_shapes, concrete) + except ParseException as e: + msg = f"Failed to parse {op_name} with {e}" + log.warning(msg) + return 0 + return flop_function(*args, **kwargs) + + +def _get_size_from_string(type_string: str) -> int: + if not hasattr(torch, type_string): + return 1 + else: + return getattr(torch, type_string).itemsize + + +def _default_estimate_gb(event: dict[str, Any]) -> float: + sizes_and_types = zip(event["args"]["Input Dims"], event["args"]["Input type"]) + bw = 0 + for size, typ in sizes_and_types: + isize = _get_size_from_string(typ) + bw += isize * math.prod(pytree.tree_flatten(size)[0]) + return bw / 1e9 + + +def _estimate_gb(event: dict[str, Any]) -> float: + """ + Our best effort to estimate the gb, should be refactored soon with MemoryCounter. + """ + name = event["name"] + if "kernel_num_gb" in event["args"] and event["args"]["kernel_num_gb"] != 0: + return event["args"]["kernel_num_gb"] + if "Input type" not in event["args"] or "Input Dims" not in event["args"]: + return 0 + op_name = _parse_kernel_name(name) + if op_name is None: + return _default_estimate_gb(event) + + op_obj = getattr(torch.ops.aten, op_name, None) + if op_obj is None: + return _default_estimate_gb(event) + + if "Input Dims" not in event["args"] or "Concrete Inputs" not in event["args"]: + return _default_estimate_gb(event) + input_shapes = event["args"]["Input Dims"] + + # NOTE these will be refactored into a similar object to FlopCounter soon + def mm_formula(M: int, N: int, K: int, size: int) -> int: + return 2 * (M * K + N * K + M * N) * size + + if op_name == "addmm": + add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0]) + add_type_size = _get_size_from_string(event["args"]["Input type"][0]) + M = input_shapes[1][0] + N = input_shapes[1][1] + if input_shapes[1][1] != input_shapes[2][0]: + raise AssertionError( + f"Shape mismatch for addmm: {input_shapes[1][1]} != {input_shapes[2][0]}" + ) + K = input_shapes[2][1] + mul_type_size = _get_size_from_string(event["args"]["Input type"][1]) + return (mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size) / 1e9 + elif op_name == "mm": + M = input_shapes[0][0] + N = input_shapes[0][1] + if input_shapes[0][1] != input_shapes[1][0]: + raise AssertionError( + f"Shape mismatch for mm: {input_shapes[0][1]} != {input_shapes[1][0]}" + ) + K = input_shapes[1][1] + type_size = _get_size_from_string(event["args"]["Input type"][0]) + return mm_formula(M, N, K, type_size) / 1e9 + elif op_name == "baddbmm": + add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0]) + add_type_size = _get_size_from_string(event["args"]["Input type"][0]) + B = input_shapes[0][0] + M = input_shapes[1][1] + N = input_shapes[1][2] + K = input_shapes[2][2] + mul_type_size = _get_size_from_string(event["args"]["Input type"][1]) + return ( + B * mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size + ) / 1e9 + elif op_name == "bmm": + add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0]) + add_type_size = _get_size_from_string(event["args"]["Input type"][0]) + B = input_shapes[0][0] + M = input_shapes[0][1] + N = input_shapes[0][2] + K = input_shapes[1][2] + mul_type_size = _get_size_from_string(event["args"]["Input type"][1]) + return ( + B * mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size + ) / 1e9 + elif op_name in [ + "convolution", + "_convolution", + "cudnn_convolution", + "_slow_conv2d_forward", + ]: + concrete = event["args"]["Concrete Inputs"] + + def conv_out_dim(x: int, kernel: int, stride: int) -> int: + return (x - kernel) // stride + 1 + + stride = parse_list( + concrete[3] if op_name != "_slow_conv2d_forward" else concrete[4] + ) + inp = input_shapes[0] + w = input_shapes[1] + out_x_y = [conv_out_dim(*args) for args in zip(inp[2:], w[2:], stride)] + out = [inp[0], w[0]] + out_x_y + # each output element reads in * w * w chunk + input_reads = out[0] * out[1] * out[2] * out[3] * inp[1] * w[2] * w[3] + # Assume weights are in cache, so only read once + weight_reads = w[0] * w[1] * w[2] * w[3] + return (input_reads + weight_reads) / 1e9 + + return _default_estimate_gb(event) + + +def _create_extern_mapping( + data: dict[str, Any], +) -> defaultdict[int, list[dict[str, Any]]]: + """ + compute a mapping from external ids to non kernels, which contain the information we need to estimate flops etc + """ + extern_mapping: defaultdict[int, list[dict[str, Any]]] = defaultdict(list) + for event in data["traceEvents"]: + if ( + "args" not in event + or "External id" not in event["args"] + or event["cat"] != "cpu_op" + ): + continue + if len(extern_mapping[event["args"]["External id"]]) > 0: + raise ParseException("duplicate external id in event") + extern_mapping[event["args"]["External id"]].append(event) + return extern_mapping + + +def _augment_trace_helper(data: dict[str, Any]) -> dict[str, Any]: + extern_mapping = _create_extern_mapping(data) + + for event in data["traceEvents"]: + if "cat" not in event or event["cat"] != "kernel": + continue + if "args" not in event: + raise ParseException(f"kernel has no args: {event}") + if "External id" not in event["args"]: + event_str = f"kernel has no External id: {event}" + log.info(event_str) + continue + + external_op = extern_mapping[event["args"]["External id"]][0] + flops = _calculate_flops(external_op) + if flops == 0: + flops = _calculate_flops(event) + external_op["args"]["kernel_flop"] = flops + external_op["args"]["kernel_num_gb"] = _estimate_gb(external_op) + event["args"]["kernel_flop"] = external_op["args"]["kernel_flop"] + event["args"]["kernel_num_gb"] = external_op["args"]["kernel_num_gb"] + return data + + +_dtype_map: dict[str, torch.dtype] = { + "float": torch.float, + "float32": torch.float, + "double": torch.double, + "float64": torch.double, + "int": torch.int, + "int8": torch.int8, + "int16": torch.int16, + "int32": torch.int, + "long": torch.long, + "long int": torch.long, + "signed char": torch.int8, + "unsigned char": torch.uint8, + "bool": torch.bool, + "bfloat16": torch.bfloat16, + "float16": torch.float16, + "c10::BFloat16": torch.bfloat16, + "c10::Half": torch.float16, + "c10::complex": torch.complex64, + "c10::complex": torch.complex128, +} + + +@dataclass(frozen=True) +class KernelStats: + flops: int + bw: float + latency: float # us + achieved_flops: float + achieved_bandwidth: float + + +KernelNameMap = defaultdict[str, OrderedSet[KernelStats]] + + +@dataclass(frozen=False) +class Device: + name: str + index: int + info: DeviceInfo | None + stats: KernelNameMap + + def __repr__(self) -> str: + return f"Device({self.name}, {self.index}): {self.info}" + + +DeviceMap = dict[int, Device] +Table = tuple[list[str], dict[str, list[str]]] + + +class JsonProfile: + _devices: DeviceMap + + def __init__( + self, + path: str, + benchmark_name: str | None = None, + dtype: torch.dtype | str | None = None, + ): + """ + Convenience class for running common operations on chrome/perfetto json traces. + """ + self.path = path + with open(path) as f: + self.data = json.load(f) + self.events = self.data["traceEvents"] + self.benchmark_name = benchmark_name + if dtype is None: + self.dtype = None + elif isinstance(dtype, torch.dtype): + # pyrefly: ignore [bad-assignment] + self.dtype = dtype + else: + # pyrefly: ignore [bad-assignment] + self.dtype = _dtype_map.get(dtype) + self._create_devices() + + def convert_dtype(self, event: dict[str, Any]) -> torch.dtype | None: + """ + Each op has a list of dtypes for each input arg. We need to convert these into a single dtype for flop estimation. + Issues: + - converting the strings to concrete torch.dtypes + - What if we have float32, float, float16 all in the inputs? Our choice is to use the largest buffer dtype. + """ + + if ( + "Input Dims" not in event["args"] + or "Input type" not in event["args"] + or "Concrete Inputs" not in event["args"] + ): + if "bfloat16" in event["name"]: + return torch.bfloat16 + elif "float16" in event["name"]: + return torch.float16 + else: + return None + + input_sizes = event["args"]["Input Dims"] + input_types = event["args"]["Input type"] + concrete_inputs = event["args"]["Concrete Inputs"] + if len(input_sizes) != len(input_types): + raise AssertionError( + f"input_sizes and input_types length mismatch: " + f"{len(input_sizes)} != {len(input_types)}" + ) + if len(input_types) != len(concrete_inputs): + raise AssertionError( + f"input_types and concrete_inputs length mismatch: " + f"{len(input_types)} != {len(concrete_inputs)}" + ) + + if len(input_sizes) == 0: + raise RuntimeError("Empty input_sizes and input_types") + + biggest_size = 0 + biggest_index = 0 + for i in range(len(input_sizes)): + if concrete_inputs[i] != "": + # concrete inputs are usually small tensors, so we can just skip + continue + my_size = input_sizes[i] + total_size = sum(parse_list(my_size)) + if total_size > biggest_size: + biggest_size = total_size + biggest_index = i + ret_type = input_types[biggest_index] + if ret_type in _dtype_map: + return _dtype_map[ret_type] + raise RuntimeError(f"Unknown type: {ret_type}. Please add to _dtype_map.") + + def _create_devices(self) -> None: + self._devices = {} + for dev in self.data["deviceProperties"]: + name = dev["name"] + device_info = lookup_device_info(name) + + if device_info is None: + log.info( + "Unsupported device in profile: %s, please consider contributing to _device_mapping.", + name, + ) + self._devices[dev["id"]] = Device( + name, dev["id"], device_info, defaultdict(OrderedSet) + ) + + def calculate_flops(self, event: dict[str, Any]) -> int: + return _calculate_flops(event) + + def estimate_gb(self, event: dict[str, Any]) -> float: + return _estimate_gb(event) + + def augment_trace(self) -> None: + self.data = _augment_trace_helper(self.data) + + def _compute_stats(self) -> None: + """populates the name -> stats map""" + for event in self.events: + if "cat" not in event or "args" not in event or event["cat"] != "kernel": + continue + if "device" not in event["args"]: + continue + dev_tmp = event["args"]["device"] + if dev_tmp not in self._devices: + continue + dev = self._devices[event["args"]["device"]] + + dur = event["dur"] # us + if "kernel_flop" in event["args"]: + if dur == 0: + raise AssertionError( + "Event duration is 0 for kernel_flop calculation" + ) + # 1,000,000us/s * flop / us + op_flops = event["args"]["kernel_flop"] / (dur / 1e6) + else: + op_flops = 0 + + if "kernel_num_gb" in event["args"]: + if dur == 0: + raise AssertionError( + "Event duration is 0 for kernel_num_gb calculation" + ) + # 1,000,000us/s * gb = gb/s + op_gbps = event["args"]["kernel_num_gb"] / (dur / 1e6) + else: + op_gbps = 0 + + if dev.info is not None: + dtype = self.convert_dtype(event) or self.dtype + if dtype is None: + raise RuntimeError( + "dtype is not found on tensor and default dtype is not set" + ) + achieved_flops = 100 * op_flops / (1e12 * dev.info.tops[dtype]) + achieved_bandwidth = 100 * op_gbps / dev.info.dram_bw_gbs + else: + achieved_flops = 0 + achieved_bandwidth = 0 + + if "name" not in event["args"]: + continue + dev.stats[event["name"]].add( + KernelStats( + flops=op_flops, + bw=op_gbps, + latency=dur, + achieved_bandwidth=achieved_bandwidth, + achieved_flops=achieved_flops, + ) + ) + + def _create_single_table(self, dev: Device) -> Table: + """Create a table with the devices mapped to indices.""" + headers = [ + "Kernel Name", + "Kernel Count", + "FLOPS", + "Kernel Reads (GB)", + "Dur (us)", + "Achieved FLOPS %", + "Achieved Bandwidth %", + ] + rows: dict[str, list[str]] = {} + + def safe_div_format(x: float, y: float) -> str: + if y == 0: + return "0.0" + return f"{x / y:.4f}" + + for kernel_name, stats_set in dev.stats.items(): + ker_count = 0 + flops = 0 + flops_count = 0 + achieved_flops = 0.0 + bw = 0.0 + bw_count = 0 + achieved_bandwidth = 0.0 + latency = 0.0 + for stats in stats_set: + if stats.flops != 0: + flops += stats.flops + achieved_flops += stats.achieved_flops + flops_count += 1 + if stats.bw != 0: + bw += stats.bw + achieved_bandwidth += stats.achieved_bandwidth + bw_count += 1 + latency += stats.latency + ker_count += 1 + if ker_count == 0: + raise AssertionError("ker_count is 0 when computing kernel stats") + rows[kernel_name] = [ + str(ker_count), + safe_div_format(flops, flops_count), + safe_div_format(bw, bw_count), + safe_div_format(latency, ker_count), + safe_div_format(achieved_flops, flops_count), + safe_div_format(achieved_bandwidth, bw_count), + ] + + return headers, rows + + def _create_tables(self, devs: DeviceMap) -> dict[int, Table]: + return {idx: self._create_single_table(dev) for idx, dev in devs.items()} + + def _combine_tables( + self, table1: Table, table1_name: str, table2: Table, table2_name: str + ) -> Table: + new_headers = ( + ["Kernel Name"] + + [f"{table1_name} {head}" for head in table1[0][1:]] + + [f"{table2_name} {head}" for head in table2[0][1:]] + ) + t1_length = len(table1[0][1:]) + t2_length = len(table2[0][1:]) + new_rows = {} + + for key, row1, row2 in zip_dicts( + table1[1], + table2[1], + d1_default=["Empty"] * t1_length, + d2_default=["Empty"] * t2_length, + ): + if row1 is None: + raise AssertionError("row1 must not be None in table combination") + if row2 is None: + raise AssertionError("row2 must not be None in table combination") + new_rows[key] = row1 + row2 + return new_headers, new_rows + + def report( + self, other: Optional["JsonProfile"] = None, name_limit: int = 40 + ) -> str: + def create_ret( + table_headers: list[str], table_rows: dict[str, list[str]] + ) -> str: + table_flattened = [ + [kernel_name[:name_limit], *kernel_vals] + for kernel_name, kernel_vals in table_rows.items() + ] + return tabulate_2d(table_flattened, headers=table_headers) + + if other is not None: + self._compute_stats() + other._compute_stats() + + self_tables = self._create_tables(self._devices) + other_tables = self._create_tables(other._devices) + + self_name = ( + self.benchmark_name if self.benchmark_name is not None else "Table 1" + ) + other_name = ( + other.benchmark_name if other.benchmark_name is not None else "Table 2" + ) + + ret = [] + if self._devices.keys() != other._devices.keys(): + raise AssertionError( + f"Device key mismatch: {self._devices.keys()} != {other._devices.keys()}" + ) + for device_idx, t1, t2 in zip_dicts( + self_tables, other_tables, d1_default=None, d2_default=None + ): + if t1 is None: + raise AssertionError("t1 must not be None for device comparison") + if t2 is None: + raise AssertionError("t2 must not be None for device comparison") + table_headers, table_rows = self._combine_tables( + t1, self_name, t2, other_name + ) + tab_string = create_ret(table_headers, table_rows) + # pyrefly: ignore [bad-argument-type] + ret.append(f"{self._devices[device_idx]}:\n{tab_string}") + return "\n".join(ret) + self._compute_stats() + + self_tables = self._create_tables(self._devices) + + ret = [] + for idx, table in self_tables.items(): + table_headers, table_rows = table + tab_string = create_ret(table_headers, table_rows) + # pyrefly: ignore [bad-argument-type] + ret.append(f"{self._devices[idx]}:\n{tab_string}") + return "\n".join(ret) + + def dump(self, out: str) -> None: + with open(out, "w") as f: + json.dump(self.data, f) + + def combine_with(self, other: "JsonProfile") -> "JsonProfile": + """ + Combine this profile with another profile by merging their trace events. + Returns a new JsonProfile object with combined data. + """ + # Create a new combined data structure + combined_data = { + "traceEvents": self.data["traceEvents"] + other.data["traceEvents"], + "deviceProperties": self.data.get("deviceProperties", []), + } + + # Merge device properties, avoiding duplicates + other_device_props = other.data.get("deviceProperties", []) + existing_device_ids = OrderedSet( + [dev["id"] for dev in combined_data["deviceProperties"]] + ) + + for device_prop in other_device_props: + if device_prop["id"] not in existing_device_ids: + combined_data["deviceProperties"].append(device_prop) + + # Copy any other top-level properties from the first profile + for key, value in self.data.items(): + if key not in combined_data: + combined_data[key] = value + + import os + + # Create a temporary file to write the combined data + import tempfile + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".json", delete=False + ) as tmp_file: + json.dump(combined_data, tmp_file) + tmp_path = tmp_file.name + + try: + # Create new JsonProfile from the combined data + combined_profile = JsonProfile( + tmp_path, + benchmark_name=f"{self.benchmark_name or 'Profile1'}_+_{other.benchmark_name or 'Profile2'}", + dtype=self.dtype or other.dtype, + ) + return combined_profile + finally: + # Clean up temporary file + os.unlink(tmp_path) + + +class ParseException(RuntimeError): + pass + + +def main() -> None: + """ + Main function for the profile analysis script. + """ + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--diff", + nargs=5, + metavar=( + "input_file1", + "name1", + "input_file2", + "name2", + "dtype", + ), + help="Two json traces to compare with, specified as ", + ) + parser.add_argument( + "--name_limit", + type=int, + help="the maximum name size in the final report", + ) + parser.add_argument( + "--augment_trace", + "-a", + nargs=3, + metavar=("input_file", "output_file", "dtype"), + help="Augment a trace with inductor meta information. Provide input and output file paths.", + ) + parser.add_argument( + "--analysis", + nargs=2, + metavar=("input_file", "dtype"), + help="Run analysis on a single trace, specified as ", + ) + parser.add_argument( + "--combine", + nargs="+", + metavar=("input_files", "output_file"), + help="Combine multiple profiles into a single profile by merging trace events. Specify as \ + [input_file3 ...] . The last argument is the output file, all preceding arguments are \ +input files to combine.", + ) + args = parser.parse_args() + + if args.diff: + p1 = JsonProfile(args.diff[0], args.diff[1], dtype=args.diff[4]) + p1.augment_trace() + p2 = JsonProfile(args.diff[2], args.diff[3], dtype=args.diff[4]) + p2.augment_trace() + if args.name_limit: + print(p1.report(p2, name_limit=args.name_limit)) + else: + print(p1.report(p2)) + if args.analysis: + p1 = JsonProfile( + args.analysis[0], + dtype=args.analysis[1], + ) + p1.augment_trace() + if args.name_limit: + print(p1.report(name_limit=args.name_limit)) + else: + print(p1.report()) + if args.augment_trace: + p = JsonProfile(args.augment_trace[0], dtype=args.augment_trace[2]) + p.augment_trace() + p.dump(args.augment_trace[1]) + if args.combine: + input_files = args.combine[:-1] # All arguments except the last one + output_file = args.combine[-1] # Last argument is the output file + + if len(input_files) < 2: + print("Error: At least 2 input files are required for combining") + return + + # Load the first profile + combined = JsonProfile(input_files[0], dtype=None) + + # Iteratively combine with all other profiles + for input_file in input_files[1:]: + profile = JsonProfile(input_file, dtype=None) + combined = combined.combine_with(profile) + + combined.dump(output_file) + print(f"Successfully combined {', '.join(input_files)} into {output_file}") + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analyze_preserves_zero_mask.py b/.venv/lib/python3.12/site-packages/torch/_inductor/analyze_preserves_zero_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..1e838eb90a2f0617e6f8518270f45a649c615c3d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/analyze_preserves_zero_mask.py @@ -0,0 +1,171 @@ +import dataclasses +import itertools +from typing import Any, TYPE_CHECKING + +import sympy + +import torch +from torch._inductor import config +from torch._inductor.dtype_propagation import DtypePropagationOpsHandler +from torch._inductor.index_propagation import SymPyOps, TypedExpr + +from .ops_handler import DefaultHandler +from .virtualized import StoreMode, V + + +if TYPE_CHECKING: + from torch._inductor.scheduler import SchedulerNode + + +def construct_symbol(count: int, dtype: torch.dtype) -> sympy.Symbol: + return sympy.Symbol(f"unknown_{count}") + + +class PreservesZeros(SymPyOps, DefaultHandler): + """ + For prologue kernels where the loads are masked, does the final store of this kernel preserve + the zeros. + """ + + def __init__(self) -> None: + self.count = itertools.count(0) + self.store_preserves_zeros: bool | None = None + self.dtype_prop = DtypePropagationOpsHandler() + + def load(self, name: str, index: sympy.Expr) -> TypedExpr: + # In prologue fusion, all loads get broadcasted + dtype = self.dtype_prop.load(name, index) + return TypedExpr( + sympy.Float(0) if dtype.is_floating_point else sympy.Integer(0), dtype + ) + + def store( + self, name: str, index: sympy.Expr, value: TypedExpr, mode: "StoreMode" = None + ) -> None: + if not isinstance(self, PreservesZeros): + raise AssertionError(f"expected PreservesZeros, got {type(self)}") + # should only have a single store in prologue + if self.store_preserves_zeros is not None: + raise AssertionError("prologue should only have a single store") + self.store_preserves_zeros = value.is_constant() and value.expr == 0 + + def indirect_indexing(self, *args: Any, **kwargs: Any) -> sympy.Expr: + return construct_symbol(next(self.count), torch.int32) + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + from torch._inductor.codegen.common import OpDecompositions + + if hasattr(OpDecompositions, name): + return getattr(OpDecompositions, name)(*args, **kwargs).value + + dtype = getattr(self.dtype_prop, name)(*args, **kwargs) + return TypedExpr(construct_symbol(next(self.count), dtype), dtype) + + +def prologue_preserves_zero_mask(prologue: "SchedulerNode") -> bool: + """ + Does this prologue preserve zero masks + """ + preserves_zeros = PreservesZeros() + with V.set_ops_handler(preserves_zeros): + prologue._body(*prologue.get_ranges()) + + store_preserves_zeros = preserves_zeros.store_preserves_zeros + if not isinstance(store_preserves_zeros, bool): + raise AssertionError( + f"expected bool store_preserves_zeros, got {type(store_preserves_zeros)}" + ) + + return store_preserves_zeros + + +@dataclasses.dataclass +class DTypeContainer: + dtype: torch.dtype + is_scalar: bool = False + + +class RecordLowPrecisionOps(DefaultHandler): + def __init__(self, disallow_fp32_ops: bool = False) -> None: + self.disallow_fp32_ops = disallow_fp32_ops + self.low_precision_numeric_op = False + self.dtype_prop = DtypePropagationOpsHandler() + self.non_numeric_ops = ( + "to_dtype", + "constant", + "where", + ) + + def load(self, name: str, index: sympy.Expr) -> DTypeContainer: + return DTypeContainer(self.dtype_prop.load(name, index)) + + @staticmethod + def store( + name: str, index: sympy.Expr, value: TypedExpr, mode: "StoreMode" = None + ) -> None: + pass + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + pass + + @staticmethod + # pyrefly: ignore [bad-override] + def indirect_indexing(*args: Any, **kwargs: Any) -> sympy.Expr: + return sympy.S.Zero + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + out_dtype = getattr(self.dtype_prop, name)(*args, **kwargs) + out = DTypeContainer(out_dtype, is_scalar=(name == "constant")) + if name == "constant": + return DTypeContainer(torch.float, is_scalar=True) + + uses_low_prec = any( + isinstance(dtype_cont, DTypeContainer) + and dtype_cont.dtype is not None + and low_prec_float(dtype_cont.dtype) + for dtype_cont in itertools.chain((out,), args, kwargs.values()) + ) + + if uses_low_prec and name not in self.non_numeric_ops: + self.low_precision_numeric_op = True + + if ( + self.disallow_fp32_ops + and out.dtype in (torch.float32, torch.float64) + and not out.is_scalar + ): + self.low_precision_numeric_op = True + + return out + + +def low_prec_float(dtype: torch.dtype) -> bool: + return dtype.is_floating_point and dtype.itemsize < 4 + + +def can_codegen_without_upcasts( + prologue: "SchedulerNode", + disallow_fp32_ops: bool = False, +) -> bool: + """ + Can this prologue be run without `upcast_to_fp32` while preserving numerics. + + This is only true if the node only contains dtype conversions, indexing, and other non-arithmetic operators. + + If disallow_fp32_ops is True, then we also disallow ops that are explicitly computed in fp32 or fp64. + """ + if prologue.get_operation_names() <= V.graph.low_precision_codegen_ops: + return True + + low_prec_analysis = RecordLowPrecisionOps(disallow_fp32_ops) + + # Need to turn off upcasting to do analysis of whether we can turn it off + with ( + config.patch("triton.codegen_upcast_to_fp32", False), + V.set_ops_handler(low_prec_analysis), + ): + prologue._body(*prologue.get_ranges()) + + return not low_prec_analysis.low_precision_numeric_op diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/aoti_eager.py b/.venv/lib/python3.12/site-packages/torch/_inductor/aoti_eager.py new file mode 100644 index 0000000000000000000000000000000000000000..1b4afe242d25b189b779a89453e45db5355ae9c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/aoti_eager.py @@ -0,0 +1,388 @@ +import json +import logging +import os +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any +from unittest import mock + +import torch +import torch._export +from torch._inductor.utils import is_cpu_device + +from .runtime.runtime_utils import cache_dir + + +log = logging.getLogger(__name__) + + +@dataclass +class AOTICompileBackend: + compile_fn: Callable[..., str] + load_fn: Callable[[str, str, str], list[dict[str, Any] | None]] + + +_aoti_compile_backends: dict[str, AOTICompileBackend] = {} + + +def register_aoti_compile_backend( + device_type: str, + compile_fn: Callable[..., str], + load_fn: Callable[[str, str, str], list[dict[str, Any] | None]], +) -> None: + _aoti_compile_backends[device_type] = AOTICompileBackend( + compile_fn=compile_fn, + load_fn=load_fn, + ) + + +def aoti_eager_cache_dir(namespace: str, device: str) -> Path: + return Path(cache_dir()) / "aoti_eager" / namespace / device + + +def aoti_eager_op_conf_lock(op_func_name_with_overload: str) -> Any: + # Avoid circular import + from torch._inductor.codecache import get_lock_dir, LOCK_TIMEOUT + from torch.utils._filelock import FileLock + + op_conf_lock_file = f"{op_func_name_with_overload}.lock" + lock_dir = get_lock_dir() + return FileLock(os.path.join(lock_dir, op_conf_lock_file), timeout=LOCK_TIMEOUT) + + +def load_aoti_eager_cache( + ns: str, op_func_name_with_overload: str, device_type: str +) -> list[dict[str, Any] | None]: + backend = _aoti_compile_backends.get(device_type) + if backend: + return backend.load_fn(ns, op_func_name_with_overload, device_type) + + device_kernel_cache = aoti_eager_cache_dir(ns, device_type) + op_conf = device_kernel_cache / f"{op_func_name_with_overload}.json" + if not op_conf.exists(): + return [] + + try: + with aoti_eager_op_conf_lock(op_func_name_with_overload): + with open(op_conf) as f: + json_data = json.load(f) + for item in json_data: + # Get absolute path for kernel library + kernel_lib_abs_path = device_kernel_cache / item["kernel_path"] + item["kernel_path"] = kernel_lib_abs_path.as_posix() + + # Check if the kernel library exists + if not kernel_lib_abs_path.exists(): + return [] + + for metadata in item["meta_info"]: + if metadata.get("is_dynamic"): + raise NotImplementedError( + "Only support static shape for now" + ) + if ( + "device_type" in metadata + and metadata["device_type"] == "cpu" + ): + metadata["device_index"] = -1 + for dtype_key in ["dtype", "dtype_value"]: + if dtype_key in metadata: + metadata[dtype_key] = getattr( + torch, metadata[dtype_key].split(".")[-1] + ) + if "layout_value" in metadata: + metadata["layout_value"] = getattr( + torch, metadata["layout_value"].split(".")[-1] + ) + if "memory_format_value" in metadata: + metadata["memory_format_value"] = getattr( + torch, metadata["memory_format_value"].split(".")[-1] + ) + + return json_data + except Exception as e: + err_msg = f"Failed to load aoti eager cache: {e}" + log.exception(err_msg) + return [] + + +def supported_builtin_dtype_torch_dtype() -> dict[type, torch.dtype]: + return {int: torch.int32, float: torch.float, bool: torch.bool} + + +def supported_scalar_types() -> tuple[type, ...]: + type_to_torch_dtype = supported_builtin_dtype_torch_dtype() + return tuple(type_to_torch_dtype.keys()) + + +def extract_tensor_metadata(dynamic: bool, input: torch.Tensor) -> dict[str, Any]: + metadata: dict[str, Any] = {} + metadata["is_dynamic"] = dynamic + + if not isinstance(input, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(input)}") + metadata["device_type"] = f"{input.device.type}" + if is_cpu_device([input]): + metadata["device_index"] = -1 + else: + metadata["device_index"] = input.device.index + metadata["dtype"] = f"{input.dtype}" + metadata["sizes"] = list(input.size()) + metadata["strides"] = list(input.stride()) + metadata["requires_grad"] = input.requires_grad + metadata["dispatch_key_set"] = torch._C._dispatch_keys(input).raw_repr() + return metadata + + +def extract_tensor_list_metadata( + dynamic: bool, + input: list[torch.Tensor], +) -> dict[str, Any]: + metadata_list = [] + for item in input: + if not isinstance(item, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(item)}") + metadata_list.append(extract_tensor_metadata(dynamic, item)) + + metadata: dict[str, Any] = {} + metadata["tensor_list"] = metadata_list + return metadata + + +def extract_scalar_metadata(device_type: str, input: Any) -> dict[str, Any]: + if not isinstance(input, supported_scalar_types()): + raise AssertionError(f"expected a supported scalar type, got {type(input)}") + metadata: dict[str, Any] = {} + metadata["is_dynamic"] = False + # Scalar tensor + metadata["device_type"] = device_type + metadata["device_index"] = -1 if device_type == "cpu" else 0 + type_to_torch_dtype = supported_builtin_dtype_torch_dtype() + metadata["dtype"] = f"{type_to_torch_dtype[type(input)]}" + metadata["scalar_value"] = input + return metadata + + +def extract_string_metadata(input: str) -> dict[str, Any]: + if not isinstance(input, str): + raise AssertionError(f"expected str, got {type(input)}") + metadata: dict[str, Any] = {} + metadata["string_value"] = input + return metadata + + +def extract_dtype_metadata(input: torch.dtype) -> dict[str, Any]: + if not isinstance(input, torch.dtype): + raise AssertionError(f"expected torch.dtype, got {type(input)}") + metadata: dict[str, Any] = {} + metadata["dtype_value"] = f"{input}" + return metadata + + +def extract_device_metadata(input: torch.device) -> dict[str, Any]: + if not isinstance(input, torch.device): + raise AssertionError(f"expected torch.device, got {type(input)}") + metadata: dict[str, Any] = {} + metadata["device_type_value"] = f"{input.type}" + metadata["device_index_value"] = input.index + return metadata + + +def extract_layout_metadata(input: torch.layout) -> dict[str, Any]: + if not isinstance(input, torch.layout): + raise AssertionError(f"expected torch.layout, got {type(input)}") + metadata: dict[str, Any] = {} + metadata["layout_value"] = f"{input}" + return metadata + + +def extract_int_list_metadata(input: list[int]) -> dict[str, Any]: + if not ( + isinstance(input, (list, tuple)) + and all(isinstance(item, int) and not isinstance(item, bool) for item in input) + ): + raise AssertionError(f"expected a list/tuple of int, got {input!r}") + metadata: dict[str, Any] = {} + metadata["int_list_value"] = list(input) + return metadata + + +def aoti_compile_with_persistent_cache( + ns: str, + op_func_name_with_overload: str, + device_type: str, + dynamic: bool, + f: Callable[..., Any], + args: tuple[Any], + kwargs: dict[str, Any], + *, + dynamic_shapes: dict[str, Any] | None = None, + options: dict[str, Any] | None = None, + remove_runtime_assertions: bool = False, + disable_constraint_solver: bool = False, +) -> str: + """ + Compile the given function with persistent cache for AOTI eager mode. + """ + backend = _aoti_compile_backends.get(device_type) + if backend: + return backend.compile_fn( + ns, + op_func_name_with_overload, + device_type, + dynamic, + f, + args, + kwargs, + dynamic_shapes=dynamic_shapes, + options=options, + remove_runtime_assertions=remove_runtime_assertions, + disable_constraint_solver=disable_constraint_solver, + ) + + if dynamic: + raise AssertionError("Only support static shape for now") + flattened_inputs = list(args) + list(kwargs.values()) + if not all( + isinstance( + input, + ( + supported_scalar_types(), + torch.Tensor, + list, + str, + torch.dtype, + torch.device, + torch.layout, + ), + ) + for input in flattened_inputs + ): + err_msg = f"Unsupported input types: {flattened_inputs}" + log.exception(err_msg) + raise NotImplementedError(err_msg) + + for input in flattened_inputs: + if isinstance(input, list) and not all( + isinstance(item, torch.Tensor) for item in input + ): + err_msg = f"_impl_with_aoti_compile encounters unsupported input types: {flattened_inputs}" + log.exception(err_msg) + raise NotImplementedError(err_msg) + + persistent_cache = aoti_eager_cache_dir(ns, device_type) + if not persistent_cache.exists(): + persistent_cache.mkdir(parents=True) + + persistent_cache_lib = persistent_cache / "lib" + if not persistent_cache_lib.exists(): + persistent_cache_lib.mkdir() + + with mock.patch.dict( + os.environ, + {"TORCHINDUCTOR_CACHE_DIR": persistent_cache_lib.absolute().as_posix()}, + ): + try: + kernel_lib_path = torch._export.aot_compile( + f, + args, + kwargs, + dynamic_shapes=dynamic_shapes, + remove_runtime_assertions=remove_runtime_assertions, + disable_constraint_solver=disable_constraint_solver, + # Some operations may have non-Tensor parameters like int, float, bool. These + # non-Tensor parameters will not be the input of the graph. Therefore, we do + # need to keep the same signature. + same_signature=False, + ) + if not isinstance(kernel_lib_path, str): + raise AssertionError( + f"expected kernel_lib_path to be str, got {type(kernel_lib_path)}" + ) + + kernel_metadata_items = [] + + for idx, input in enumerate(flattened_inputs): + # Skip explicit-None args (e.g. an optional `int[1]? dim`) so the + # written metadata vector matches the cache reader, which also + # drops None entries. + if input is None: + continue + if isinstance(input, torch.Tensor): + metadata = extract_tensor_metadata(dynamic, input) + elif isinstance(input, (list, tuple)) and all( + isinstance(item, int) and not isinstance(item, bool) + for item in input + ): + # `int[]` / `SymInt[]` params. Checked before the Tensor-list + # branch so an empty list/tuple is tagged INT_LIST, matching + # the cache reader and C++ unpack_input_parameters for an + # empty `int[]`. An empty `Tensor[]` is the converse case: + # C++ tags it TENSOR_LIST (isTensorList() is checked before + # isIntList()) while this tags it INT_LIST -- only a cache + # miss/recompile (per-op cache, fixed schema type per slot -> + # no aliasing), and it does not arise for real ops + # (`cat([])`/`stack([])` raise in eager). + metadata = extract_int_list_metadata(list(input)) + elif isinstance(input, (list, tuple)) and all( + isinstance(item, torch.Tensor) for item in input + ): + metadata = extract_tensor_list_metadata(dynamic, list(input)) + elif isinstance(input, supported_scalar_types()): + metadata = extract_scalar_metadata(device_type, input) + elif isinstance(input, str): + metadata = extract_string_metadata(input) + elif isinstance(input, torch.dtype): + metadata = extract_dtype_metadata(input) + elif isinstance(input, torch.device): + metadata = extract_device_metadata(input) + elif isinstance(input, torch.layout): + metadata = extract_layout_metadata(input) + else: + raise NotImplementedError(f"Unsupported input type: {type(input)}") + + metadata["arg_order"] = idx + kernel_metadata_items.append(metadata) + + kernel_meta_info: dict[str, Any] = {} + kernel_meta_info["meta_info"] = kernel_metadata_items + kernel_meta_info["kernel_path"] = ( + Path(kernel_lib_path).relative_to(persistent_cache).as_posix() + ) + + json_data = [] + update_json = True + op_conf = persistent_cache / f"{op_func_name_with_overload}.json" + mode = "r" if op_conf.exists() else "w" + with aoti_eager_op_conf_lock(op_func_name_with_overload): + with open(op_conf, mode) as op_conf_file: + try: + json_data = json.load(op_conf_file) + except Exception: + json_data = [] + + if not isinstance(json_data, list): + raise AssertionError( + f"expected json_data to be list, got {type(json_data)}" + ) + for item in json_data: + if not isinstance(item, dict): + raise AssertionError( + f"expected item to be dict, got {type(item)}" + ) + # Same kernel meta info already exists in the json file + if item["meta_info"] == kernel_metadata_items: + update_json = False + break + + if update_json: + json_data.append(kernel_meta_info) + with open(op_conf, "w") as op_conf_file: + json.dump(json_data, op_conf_file, indent=4) + + return kernel_lib_path + except Exception as e: + err_msg = f"Failed to compile {op_func_name_with_overload}: {e}" + log.exception(err_msg) + return "" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/async_compile.py b/.venv/lib/python3.12/site-packages/torch/_inductor/async_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8c84be48acd161157983c03fa3c25a29c6d58c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/async_compile.py @@ -0,0 +1,987 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import atexit +import functools +import json +import logging +import multiprocessing +import os +import re +import sys +from concurrent.futures import ( + Future, + ThreadPoolExecutor, + TimeoutError as FuturesTimeoutError, +) +from concurrent.futures.process import BrokenProcessPool +from functools import partial +from time import time, time_ns +from typing import Any, TYPE_CHECKING + +import torch +from torch._dynamo.device_interface import get_registered_device_interfaces +from torch._dynamo.utils import ( + counters, + dynamo_timed, + get_metrics_context, + set_feature_use, +) +from torch._inductor import config +from torch._inductor.codecache import ( + _load_triton_kernel_from_source, + code_hash, + CodeCacheFuture, + CppCodeCache, + CppPythonBindingsCodeCache, + CUDACodeCache, + HalideCodeCache, + LambdaFuture, + ROCmCodeCache, + StaticAutotunerFuture, + torch_key, + XPUCodeCache, +) +from torch._inductor.compile_worker.subproc_pool import ( + AnyPool, + SubprocException, + SubprocPool, +) +from torch._inductor.compile_worker.tracked_process_pool import ( + TrackedProcessPoolExecutor, +) +from torch._inductor.compile_worker.utils import _async_compile_initializer +from torch._inductor.runtime.compile_tasks import ( + _set_triton_libdevice_path, + _set_triton_ptxas_path, + _worker_compile_pycodecache_kernel, + _worker_compile_triton, +) +from torch._inductor.utils import clear_on_fresh_cache +from torch._inductor.virtualized import V +from torch._utils_internal import log_triton_builds +from torch.hub import _Faketqdm, tqdm +from torch.utils._ordered_set import OrderedSet +from torch.utils._triton import has_triton_package + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torch._inductor.runtime.hints import HalideMeta + from torch._inductor.runtime.triton_heuristics import CachingAutotuner + +# timing metrics for time spent in the compilation +_cumulative_compile_time = 0.0 +_t0: float | None = None + +kernel_code_log = torch._logging.getArtifactLogger(__name__, "kernel_code") + +log = logging.getLogger(__name__) + +_triton_kernel_metrics: dict[str, dict[str, Any]] | None = None + +size_hints_regex = re.compile( + r"size_hints=(\{.*?\})", +) + + +def _pycodecache_kernel_compile_env() -> dict[str, str | None]: + env_vars = [ + "TORCHINDUCTOR_CACHE_DIR", + "TRITON_CACHE_DIR", + "TORCHINDUCTOR_CUTLASS_DIR", + ] + return {v: os.environ.get(v) for v in env_vars} + + +def pre_fork_setup(): + """ + Setup that must be done prior to forking with a process pool. + """ + # ensure properties have been calculated before processes + # are forked + caching_device_properties() + + # Computing the triton key can be slow. If we call it before fork, + # it will be cached for the forked subprocesses. + from torch._inductor.runtime.triton_compat import HAS_TRITON, triton_key + + if HAS_TRITON: + triton_key() + + +def caching_device_properties(): + for _, device_interface in get_registered_device_interfaces(): + if device_interface.is_available(): + device_interface.Worker.get_device_properties() + + +def _compile_start() -> None: + global _t0, _triton_kernel_metrics + if _t0 is None: + _t0 = time() + if _triton_kernel_metrics is None: + _triton_kernel_metrics = {} + + +def _compile_end() -> None: + global _cumulative_compile_time, _t0, _triton_kernel_metrics + if _t0 is not None: + t1 = time() + _cumulative_compile_time += t1 - _t0 + _t0 = None + # print("CUMULATIVE COMPILE TIME", _cumulative_compile_time) + if _triton_kernel_metrics: + # Log triton kernel info + sorted_info = dict(sorted(_triton_kernel_metrics.items())) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "triton_kernel_info", + "encoding": "json", + }, + payload_fn=lambda: json.dumps(sorted_info), + ) + _triton_kernel_metrics = None + + +def _add_triton_kernel_info(kernel_name: str, info: dict[str, Any]): + global _triton_kernel_metrics + # Must be called between _compile_start and _compile_end + if _triton_kernel_metrics is not None: + _triton_kernel_metrics[kernel_name] = info + + +def _emit_triton_kernel_compile_metric( + kernel: CachingAutotuner, + kernel_name: str, + elapsed_us: int, +) -> None: + """Emit per-kernel ``compile_time_us`` to both the dynamo + ``_triton_kernel_metrics`` map and the ``MetricsContext`` top-N. + + Note: ``kernel.autotune_cache_info`` is only mutated in place when + non-empty; when ``None`` or ``{}`` the metric still reaches + ``_triton_kernel_metrics`` via a throwaway dict, but the kernel + attribute stays untouched. + """ + info = kernel.autotune_cache_info or {} + info["compile_time_us"] = elapsed_us + _add_triton_kernel_info(kernel_name, info) + get_metrics_context().add_top_n( + "triton_kernel_compile_times_us", kernel_name, elapsed_us + ) + + +_IS_WINDOWS = sys.platform == "win32" + +log = logging.getLogger(__name__) + +# Used to keep track of all process pools invoked so far. +_pool_set = OrderedSet[AnyPool]() + + +def shutdown_compile_workers() -> None: + """Shut down all outstanding compile-worker pools.""" + for pool in _pool_set: + pool.shutdown() + AsyncCompile._ready_future = None + after_fork() + + +def after_fork(): + """Reset pools to initial state without shutting them down""" + _pool_set.clear() + AsyncCompile._ready_future = None + AsyncCompile.process_pool.cache_clear() + + +try: + os.register_at_fork(after_in_child=after_fork) +except AttributeError: + pass # register_at_fork does not exist on windows + + +def get_compile_threads() -> int: + """ + Temporary for internal rollout. Assign config.compile_threads lazily and return it. + TODO: remove after rollout. + """ + if config.compile_threads is None: + config.compile_threads = config.decide_compile_threads() + return config.compile_threads + + +def _process_pool_allowed() -> bool: + # Multiprocessing daemons are not allowed to create child processes. This + # only applies to direct multiprocessing modes: SubprocPool starts its + # sidecar with subprocess.Popen, so the sidecar does not inherit the + # multiprocessing daemon flag and can own its own ProcessPoolExecutor. + return ( + config.worker_start_method == "subprocess" + or not multiprocessing.current_process().daemon + ) + + +@clear_on_fresh_cache +class CompiledTritonKernels: + """ + In memory cache for storing compiled triton kernels. + + Each triton kernel is keyed by the hash of its source code. Each value stored + in the cache is a return value of AsyncCompile.triton(). + + Currently, the cache stores Future objects, but it should be generalizable for any kernels. + """ + + _cache: dict[str, CodeCacheFuture] = {} + + @staticmethod + def key(kernel_src: str): + """ + Generates a cache key given a triton kernel's full source code. + This source includes the inductor meta, compilation metadata, the kernel itself, etc. + `kernel_src` should be the exact string passed to async_compile.triton()'s first argument. + """ + # Hashes the kernel source with torch_key into a single hash key + return code_hash(kernel_src, extra=torch_key()) + + @staticmethod + def save(kernel_src: str, future: CodeCacheFuture): + """ + Saves a compiled triton kernel to the cache. + TODO: We store a LambdaFuture as that's the callable returned by async_compile.triton, + but the real type we want to return here is actually an abstract triton kernel. + + TODO: Source code here is not just the kernel's source code, but also includes the inductor preamble, etc. + so it could be less strict. + """ + key = CompiledTritonKernels.key(kernel_src) + CompiledTritonKernels._cache[key] = future + + @staticmethod + def get(kernel_src: str) -> CodeCacheFuture | None: + key = CompiledTritonKernels.key(kernel_src) + return CompiledTritonKernels._cache.get(key, None) + + @staticmethod + def cache_clear(): + CompiledTritonKernels._cache = {} + + @staticmethod + def remove_future(kernel_src: str) -> None: + key = CompiledTritonKernels.key(kernel_src) + + # Delete the LambdaFuture if there is one + if key in CompiledTritonKernels._cache: + del CompiledTritonKernels._cache[key] + + +class AsyncCompile: + """ + Utilities to compile in thread pools or subprocess pools (in the case of Triton). + """ + + _ready_future: Future[Any] | None = None + _metal_sources: list[tuple[str, str, list[str]]] | None = None + + def __init__(self) -> None: + pass + + @staticmethod + @functools.lru_cache(1) + def pool() -> ThreadPoolExecutor: + if get_compile_threads() <= 1: + raise AssertionError( + f"expected get_compile_threads() > 1, got {get_compile_threads()}" + ) + return ThreadPoolExecutor(get_compile_threads()) + + @staticmethod + def _get_ready(): + """No-op function to help mark when the subprocess pool is ready.""" + return "ready" + + @staticmethod + @functools.lru_cache(1) + def process_pool() -> AnyPool: + if get_compile_threads() <= 1: + raise AssertionError( + f"expected get_compile_threads() > 1, got {get_compile_threads()}" + ) + if not _process_pool_allowed(): + raise RuntimeError( + "Inductor async compile process pools are disabled in daemonic " + "multiprocessing processes. Set " + "torch._inductor.config.worker_start_method = 'subprocess' " + "(or TORCHINDUCTOR_WORKER_START=subprocess) to use the " + "SubprocPool path, which is not affected by the daemon restriction." + ) + AsyncCompile._ready_future = None + log.info( + "Creating '%s' pool with %d workers", + config.worker_start_method, + get_compile_threads(), + ) + + pool: AnyPool + if config.worker_start_method == "subprocess": + # Wrapper around ProcessPoolExecutor forks in a new process we control + pool = SubprocPool( + get_compile_threads(), quiesce=config.quiesce_async_compile_pool + ) + else: + if config.worker_start_method == "spawn": + # Avoid creating pools in the spawned subprocs themselves: + os.environ["TORCH_WARM_POOL"] = "0" + pre_fork_setup() + ctx = multiprocessing.get_context(config.worker_start_method) + pool = TrackedProcessPoolExecutor( + get_compile_threads(), + mp_context=ctx, + initializer=partial(_async_compile_initializer, os.getpid()), + ) + + # When this pool is created in a multiprocessing subprocess, the normal + # atexit handler may not run, and we need to register our own handler. + # exitpriority has to be high, because another one of the finalizers will + # kill the worker thread that sends the shutdown message to the workers. + multiprocessing.util.Finalize(None, pool.shutdown, exitpriority=sys.maxsize) + + _pool_set.add(pool) + return pool + + @classmethod + def warm_pool(cls) -> None: + if get_compile_threads() <= 1 or not _process_pool_allowed(): + return + _compile_start() + # Pool is created on first access. Note for a SubprocPool, the sidecar process starts, + # but its ProcessPoolExecutor does not initialize until a wakeup() call or the first + # job is submitted. + cls.process_pool() + _compile_end() + + @classmethod + def wait_pool_ready(cls, timeout=120) -> None: + cls.use_process_pool() + if cls._ready_future is not None: + cls._ready_future.result(timeout=timeout) + + @classmethod + def submit(cls, task: Callable[..., Any]) -> Any: + if get_compile_threads() <= 1: + return task() + return cls.pool().submit(task) + + @classmethod + def use_process_pool(cls): + if get_compile_threads() <= 1 or not _process_pool_allowed(): + return False + + # Proton instrumentation backend requires compilation to happen in the main + # process so it can instrument the Triton IR during JIT compilation. + # Force synchronous compilation when proton profiling is enabled. + if config.triton.proton_profiling: + return False + + # Create a dummy job to check if the pool is ready. Submit it here instead of at + # pool creation so we don't launch the full pool of worker subprocesses until + # we're sure they're needed. + if not cls._ready_future: + cls._ready_future = cls.process_pool().submit(cls._get_ready) + return cls._ready_future.done() + + @classmethod + def wait_process_pool_ready(cls, timeout: float = 120) -> bool: + """Block (up to ``timeout`` s) until the process pool is ready, returning + whether it's usable. + + Like use_process_pool() but blocking. Use when a backend's serial + fallback is far costlier than the warmup wait -- e.g. NVGEMM subprocess + precompile, where skipping the pool forces ~15x-slower lazy compilation + at benchmark time. (use_process_pool()'s non-blocking readiness check can + race pool warmup when little other compilation precedes the decision.) + On timeout, degrade gracefully (return False -> serial) rather than hang + on a stuck worker. + """ + if get_compile_threads() <= 1 or not _process_pool_allowed(): + return False + if config.triton.proton_profiling: + return False + if not cls._ready_future: + cls._ready_future = cls.process_pool().submit(cls._get_ready) + try: + cls._ready_future.result(timeout=timeout) + except FuturesTimeoutError: + log.warning( + "Process pool not ready after %ss; falling back to serial", timeout + ) + return False + except (BrokenProcessPool, RuntimeError) as e: + # A warmup worker died or the pool was closed. The readiness probe + # failing must degrade to serial (the documented contract), not + # propagate and abort the caller's algorithm selection. + log.warning("Process pool unusable (%s); falling back to serial", e) + return False + return True + + @classmethod + def wakeup(cls) -> None: + """ + If using a SubprocPool, signal the sidecar process to start up its + ProcessPoolExecutor. + """ + if not cls.use_process_pool(): + return + pool = cls.process_pool() + if isinstance(pool, SubprocPool): + pool.wakeup() + + def triton(self, kernel_name: str, source_code: str, device_str: str = "cuda"): + """ + Async_compile.triton is more complicated than the other backends because + we're trying to optimize compile time as much as possible for this hot callsite. + + First of all, the function is cached by CompiledTritonKernels; if there's a kernel + already compiled, we grab it directly from the cache and return. + + Otherwise, if we have multiple compile threads, we kick off triton compilations on each + worker process by giving it a kernel and source code to compile. The worker initializes + a CachingAutotuner, runs triton compilation, and pickles the kernel back to us. + We use TritonCompileResult to represent the objects being pickled back to us by each + worker. + + Some maybe not obvious things that are pickled back to us: + - Most of the time, we can avoid sending back CachingAutotuner.fn and other metadata + and do not have to pay the cost of loading the triton kernel on the parent. But certain + cases, like coordesc tuning and dynamic_scale_rblock, require us to reload the function + in the parent lazily when we require it. + - The AutotuneCache, if enabled, is constructed on each worker per triton config + and pickled by to us via `CachingAutotuner.save_cache_hook`. + """ + load_kernel = functools.partial( + _load_triton_kernel_from_source, kernel_name, source_code + ) + + def reload_kernel_in_parent(): + # Benchmark how often this happens + with dynamo_timed("reload_kernel_in_parent"): + return load_kernel() + + counters["inductor"]["async_compile_cache_miss"] += 1 + + kernel_code_log.info("Triton Kernel:\n%s", source_code) + _compile_start() + + if os.environ.get("TRITON_INTERPRET", "0") == "1": + return getattr( + torch._inductor.codecache.PyCodeCache.load(source_code), kernel_name + ) + + is_parallel = self.use_process_pool() + set_feature_use("parallel_compile_post_warmup", is_parallel) + + compile_id = torch._guards.CompileContext.current_compile_id() + is_backward = getattr(V.graph, "is_backward", False) + + if (future := CompiledTritonKernels.get(source_code)) is not None: + counters["inductor"]["async_compile_cache_hit"] += 1 + # Set reload_kernel_from_src properly based on source_code + if isinstance(future, StaticAutotunerFuture): + # Remove the future now that we've cache hit + CompiledTritonKernels.remove_future(source_code) + future.reload_kernel_from_src = reload_kernel_in_parent + if is_parallel: + return future + else: + return future.result() + + # Cache miss + if is_parallel: + # Ensure libdevice path is set in os.environ before passing to workers + _set_triton_libdevice_path() + # We want to support changing these env vars after (and while) the + # process pool is running, so pass them to the subprocess to reset. + env_vars = [ + "TORCHINDUCTOR_CACHE_DIR", + "TRITON_CACHE_DIR", + "TRITON_LIBDEVICE_PATH", + ] + extra_env = {v: os.environ.get(v) for v in env_vars} + extra_config = { + "use_static_triton_launcher": torch._inductor.config.use_static_triton_launcher + } + + if len(torch._inductor.config.autotune_lookup_table) > 0: + m = size_hints_regex.search(source_code) + if m: + size_hints_str = m.group(1) + else: + size_hints_str = str(None) + + triton_src = source_code.split("@triton.jit\n")[1] + from torch._inductor.runtime.triton_heuristics import ( + generate_lookup_hash_from_source_code, + ) + + fn_hash = generate_lookup_hash_from_source_code( + size_hints_str, triton_src + ) + + if fn_hash in torch._inductor.config.autotune_lookup_table: + extra_config["autotune_lookup_table"] = { # type: ignore[assignment] + fn_hash: torch._inductor.config.autotune_lookup_table[fn_hash] + } + + task = self.process_pool().submit( + _worker_compile_triton, + load_kernel, + extra_env, + extra_config, + ) + + def get_result() -> CachingAutotuner: + try: + kernel, elapsed_us = task.result() + except SubprocException as e: + raise e.with_name(kernel_name) from e + + # Now that we've compiled, we should clear the future + # so it can't be used again + kernel.set_compile_info(compile_id, is_backward) + CompiledTritonKernels.remove_future(source_code) + + kernel.restore_after_unpickle(old_values=None) + + kernel.precompile( + warm_cache_only=False, + reload_kernel=reload_kernel_in_parent, + static_triton_bundle_key=CompiledTritonKernels.key(source_code), + ) + _emit_triton_kernel_compile_metric(kernel, kernel_name, elapsed_us) + return kernel + + future = LambdaFuture(get_result, future=task) + CompiledTritonKernels.save(source_code, future) + return future + else: + with dynamo_timed( + "async_compile.precompile", + log_pt2_compile_event=True, + dynamo_compile_column_us="triton_compile_time_us", + log_waitcounter=True, + waitcounter_name_override="compile_triton", + ): + fail = None + try: + start_ns = time_ns() + _set_triton_ptxas_path() + _set_triton_libdevice_path() + kernel = load_kernel() + kernel.set_compile_info(compile_id, is_backward) + kernel.precompile( + warm_cache_only=False, + static_triton_bundle_key=CompiledTritonKernels.key(source_code), + ) + elapsed_us = (time_ns() - start_ns) // 1000 + _emit_triton_kernel_compile_metric(kernel, kernel_name, elapsed_us) + return kernel + except Exception as e: + fail = str(e) + raise + finally: + log_triton_builds(fail=fail) + + def multi_kernel(self, *args, **kwargs) -> Any: + from torch._inductor.codegen.multi_kernel import MultiKernelCall + + # no need to call this in parallel since the sub-kernels are already parallel tasks + return MultiKernelCall(*args, **kwargs) + + def size_hint_multi_kernel(self, *args, **kwargs) -> Any: + from torch._inductor.codegen.multi_kernel import SizeHintMultiKernelCall + + return SizeHintMultiKernelCall(*args, **kwargs) + + def cpp(self, source_code: str): + kernel_code_log.info("CPP Kernel:\n%s", source_code) + if get_compile_threads() <= 1: + return CppCodeCache.load(source_code).kernel + else: + get_result = CppCodeCache.load_async(source_code, submit_fn=self.submit) + return LambdaFuture(lambda: get_result().kernel) + + def cpp_pybinding(self, argtypes: list[str], source_code: str): + kernel_code_log.info("CPP+Bindings Kernel:\n%s", source_code) + if get_compile_threads() <= 1: + return CppPythonBindingsCodeCache.load_pybinding(argtypes, source_code) + else: + get_result = CppPythonBindingsCodeCache.load_pybinding_async( + argtypes, source_code, submit_fn=self.submit + ) + return LambdaFuture(get_result) + + def cutlass(self, cache_cls, source_code, dst_file_ext, aot_compile=False): + def task(): + if aot_compile: + # We rely on JITInductor to compile the CUDA code, + # so that we can load it into AOTInductor. + output_path, *_ = cache_cls.compile(source_code, "o") + cache_cls.aot_kernels_o.append(output_path) + return cache_cls.load(source_code, dst_file_ext)[0] + + return self.submit(task) + + def cuda(self, source_code, dst_file_ext, aot_compile=False): + kernel_code_log.info("CUDA Kernel:\n%s", source_code) + return self.cutlass(CUDACodeCache, source_code, dst_file_ext, aot_compile) + + def xpu(self, source_code, dst_file_ext, aot_compile=False): + kernel_code_log.info("XPU Kernel:\n%s", source_code) + return self.cutlass(XPUCodeCache, source_code, dst_file_ext, aot_compile) + + def rocm( + self, + source_code, + dst_file_ext, + aot_compile=False, + ): + kernel_code_log.info("ROCm Kernel:\n%s", source_code) + + def task(): + if aot_compile: + output_path, *_ = ROCmCodeCache.compile(source_code, dst_file_ext="o") + ROCmCodeCache.aot_kernels_o.append(output_path) + if config.rocm.generate_test_runner: + _ = ROCmCodeCache.compile(source_code, dst_file_ext="exe") + return ROCmCodeCache.load(source_code, dst_file_ext)[0] + + return self.submit(task) + + def halide(self, meta: HalideMeta, source_code: str): + kernel_code_log.info("Halide Kernel:\n%r\n%s", meta, source_code) + if get_compile_threads() <= 1: + return HalideCodeCache.generate_halide(meta, source_code) + else: + get_result = HalideCodeCache.generate_halide_async( + meta, source_code, submit_fn=self.submit + ) + return LambdaFuture(get_result) + + def _load_kernel_wrapper(self, kernel_name, main_suffix, wrapper_cls, key, path): + """Reload a kernel module from PyCodeCache and wrap the entry point.""" + mod = torch._inductor.codecache.PyCodeCache.load_by_key_path(key, path) + main_func_name = f"{kernel_name}_{main_suffix}" + return wrapper_cls(getattr(mod, main_func_name), kernel_path=path) + + def cutedsl(self, kernel_name: str, source_code: str, precompile_metadata=None): + """ + Compile CuteDSL (CUTLASS Python DSL) kernels. + + Args: + kernel_name: Name of the kernel to be defined + source_code: Source code of the CuteDSL kernel, as a string + precompile_metadata: Optional dict with shapes/dtypes for triggering + real CuTe DSL compilation in the subprocess worker. + + Note: + CuteDSL currently requires source files to do its compilation, there we + use the PyCodeCache to write the source code to a file and load it. + """ + from torch._inductor.codegen.cutedsl.cutedsl_kernel import ( + CuteDSLKernelWrapper, + MAIN_SUFFIX, + ) + + kernel_code_log.info("CuteDSL Kernel:\n%s", source_code) + _compile_start() + + is_parallel = self.use_process_pool() + + if is_parallel: + extra_env = _pycodecache_kernel_compile_env() + + subprocess_task = self.process_pool().submit( + _worker_compile_pycodecache_kernel, + kernel_name, + source_code, + MAIN_SUFFIX, + extra_env, + precompile_metadata, + ) + + def get_result() -> CuteDSLKernelWrapper: + try: + key, path, elapsed_us = subprocess_task.result() + except SubprocException as e: + raise e.with_name(kernel_name) from e + log.debug( + "CuteDSL kernel %s compiled in subprocess in %dus", + kernel_name, + elapsed_us, + ) + return self._load_kernel_wrapper( + kernel_name, MAIN_SUFFIX, CuteDSLKernelWrapper, key, path + ) + + return LambdaFuture(get_result, future=subprocess_task) + else: + key, path = torch._inductor.codecache.PyCodeCache.write(source_code) + mod = torch._inductor.codecache.PyCodeCache.load_by_key_path(key, path) + + main_func_name = f"{kernel_name}_{MAIN_SUFFIX}" + if not hasattr(mod, main_func_name): + available = [name for name in dir(mod) if callable(getattr(mod, name))] + raise RuntimeError( + f"Could not find CuteDSL main kernel function '{main_func_name}'. Available callables: {available}" + ) + + return CuteDSLKernelWrapper(getattr(mod, main_func_name), kernel_path=path) + + def pallas(self, kernel_name: str, source_code: str): + """ + Compile Pallas (JAX experimental) kernels. + + Args: + kernel_name: Name of the kernel to be defined + source_code: Source code of the Pallas kernel, as a string + + Note: + Pallas kernels are Python code that uses JAX and Pallas APIs. + We use the PyCodeCache to write the source code to a file and load it. + """ + from torch._inductor.codegen.pallas import MAIN_SUFFIX, PallasKernelWrapper + + kernel_code_log.info("Pallas Kernel:\n%s", source_code) + + def task(): + key, path = torch._inductor.codecache.PyCodeCache.write(source_code) + mod = torch._inductor.codecache.PyCodeCache.load_by_key_path(key, path) + + # Find our special entry point named function + main_func_name = f"{kernel_name}_{MAIN_SUFFIX}" + if not hasattr(mod, main_func_name): + available = [name for name in dir(mod) if callable(getattr(mod, name))] + raise RuntimeError( + f"Could not find Pallas main kernel function '{main_func_name}'. Available callables: {available}" + ) + + return PallasKernelWrapper(getattr(mod, main_func_name), kernel_path=path) + + if get_compile_threads() <= 1: + return task() + else: + future = self.submit(task) + return LambdaFuture(lambda: future.result()) + + def nv_universal_gemm( + self, kernel_name: str, source_code: str, precompile_metadata=None + ): + """ + Compile NVIDIA Universal GEMM kernels. + + Args: + kernel_name: Name of the kernel to be defined + source_code: Source code of the kernel, as a string + precompile_metadata: Optional dict with shapes/dtypes for triggering + real CuTe DSL compilation in the subprocess worker. + + Note: + NVIDIA Universal GEMM kernels are Python code that calls the cutlass.operators library. + We use the PyCodeCache to write the source code to a file and load it. + """ + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import ( + NVUniversalGemmKernelWrapper, + ) + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_scheduling import ( + MAIN_SUFFIX, + ) + + kernel_code_log.info("NVIDIA Universal GEMM Kernel:\n%s", source_code) + _compile_start() + + is_parallel = self.use_process_pool() + + if is_parallel: + extra_env = _pycodecache_kernel_compile_env() + + subprocess_task = self.process_pool().submit( + _worker_compile_pycodecache_kernel, + kernel_name, + source_code, + MAIN_SUFFIX, + extra_env, + precompile_metadata, + ) + + def get_result() -> NVUniversalGemmKernelWrapper: + try: + key, path, elapsed_us = subprocess_task.result() + except SubprocException as e: + raise e.with_name(kernel_name) from e + log.debug( + "NV Universal GEMM kernel %s compiled in subprocess in %dus", + kernel_name, + elapsed_us, + ) + return self._load_kernel_wrapper( + kernel_name, MAIN_SUFFIX, NVUniversalGemmKernelWrapper, key, path + ) + + return LambdaFuture(get_result, future=subprocess_task) + else: + key, path = torch._inductor.codecache.PyCodeCache.write(source_code) + mod = torch._inductor.codecache.PyCodeCache.load_by_key_path(key, path) + + main_func_name = f"{kernel_name}_{MAIN_SUFFIX}" + if not hasattr(mod, main_func_name): + available = [name for name in dir(mod) if callable(getattr(mod, name))] + raise RuntimeError( + f"Could not find NVIDIA Universal GEMM main kernel function " + f"'{main_func_name}'. Available callables: {available}" + ) + + return NVUniversalGemmKernelWrapper( + getattr(mod, main_func_name), kernel_path=path + ) + + def nvgemm_precompile( + self, + kernel_name, + variant_name, + accumulator_type, + input_tensor_meta, + output_tensor_meta, + cuda_ctx, + scale_type_a=None, + scale_type_b=None, + swizzle_type_a=None, + swizzle_type_b=None, + has_bias_epilogue=False, + swap_ab=False, + metadata=None, + ): + """Submit NVGEMM kernel precompilation to the subprocess pool. + + Compiles the CuTeDSL kernel artifact in a subprocess worker so the + thread-unsafe kernel.compile() call is process-isolated. The compiled + artifact is saved to the disk cache; the main process loads it on the + next cache lookup during benchmarking. + """ + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import ( + _worker_nvgemm_autotuning_precompile, + ) + + extra_env = _pycodecache_kernel_compile_env() + + return self.process_pool().submit( + _worker_nvgemm_autotuning_precompile, + kernel_name, + variant_name, + accumulator_type, + input_tensor_meta, + output_tensor_meta, + extra_env, + cuda_ctx, + scale_type_a, + scale_type_b, + swizzle_type_a, + swizzle_type_b, + has_bias_epilogue, + swap_ab, + metadata, + ) + + def metal(self, kernel_name: str, source: str, headers: list[str]) -> None: + """Register a Metal kernel body; wait() compiles all registered kernels into one library.""" + if self._metal_sources is None: + self._metal_sources = [] + self._metal_sources.append((kernel_name, source, headers)) + + def wait(self, scope: dict[str, Any]) -> None: + if get_compile_threads() > 1: + with dynamo_timed( + "async_compile.wait", + log_pt2_compile_event=True, + dynamo_compile_column_us="triton_compile_time_us", + log_waitcounter=True, + waitcounter_name_override="compile_triton", + ): + self._wait_futures(scope) + + if self._metal_sources: + from torch._inductor.runtime.runtime_utils import compile_mps_shaders + + scope.update(compile_mps_shaders(self._metal_sources)) + self._metal_sources.clear() + + _compile_end() + + def _wait_futures(self, scope: dict[str, Any]) -> None: + kernels = { + key: value + for key, value in scope.items() + if isinstance(value, (Future, CodeCacheFuture)) + } + pbar = tqdm( + total=len(kernels), + desc="Inductor Compilation", + disable=config.disable_progress, + delay=0, + ) + # compile_worker_wait_timeout=0 (default) means "wait forever"; map + # it to None so both Future.result() and CodeCacheFuture.result() + # receive the same "no timeout" sentinel. + wait_timeout = config.compile_worker_wait_timeout or None + for key, result in kernels.items(): + if config.verbose_progress and not isinstance(pbar, _Faketqdm): + pbar.set_postfix_str(key) + try: + kernel = result.result(timeout=wait_timeout) + scope[key] = kernel + except FuturesTimeoutError as e: + # concurrent.futures.TimeoutError became an alias of the + # builtin TimeoutError in Python 3.11; on 3.10 it is a + # distinct class, so catch it explicitly. + raise RuntimeError( + f"Inductor compile-worker future for {key!r} did not " + f"complete within {wait_timeout}s. Override with " + "TORCHINDUCTOR_COMPILE_WORKER_WAIT_TIMEOUT=." + ) from e + except BrokenProcessPool as e: + raise RuntimeError( + "A compilation subprocess exited unexpectedly. This " + "is likely due to a crash. To facilitate debugging, " + "you can re-run with TORCHINDUCTOR_COMPILE_THREADS=1 " + "to cause compilation to occur in the main process." + ) from e + pbar.update(1) + + +def maybe_warm_pool() -> None: + if ( + os.environ.get("TORCH_TNT_IN_USE", "0") == "1" + or os.environ.get("TORCH_WARM_POOL", "1") != "1" + # The subprocess pool is only used for the Triton backend + or not has_triton_package() + # Skip for fbcode. We have internal reports of usages inside multiprocessing + # pools that lead a multiplicative number of compile subprocesses. + or config.is_fbcode() + ): + return + + AsyncCompile.warm_pool() + # TODO: This starts the SubprocPool's internal process pool as early as possible at + # the expense of creating a bunch of worker processes that might not be needed. We + # could start them lazily if we're willing to lose a small amount of compile time. + AsyncCompile.wakeup() + + +# On exit give the workers a chance to clean themselves up. Without this the +# resource_tracker can complain about leaked semaphores coming from the +# ProcessPoolExecutor: +# UserWarning: resource_tracker: There appear to be 5 leaked semaphore objects +# to clean up at shutdown +atexit.register(shutdown_compile_workers) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/augmented_graph_helper.py b/.venv/lib/python3.12/site-packages/torch/_inductor/augmented_graph_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..63a19ede7786d16228864eeba0ca7a8b4f0badf4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/augmented_graph_helper.py @@ -0,0 +1,281 @@ +import logging +from collections import defaultdict + +import torch +import torch.fx as fx +from torch._inductor.fx_passes.utils import BitsetAncestors +from torch._logging import trace_structured +from torch.utils._ordered_set import OrderedSet + + +log = logging.getLogger(__name__) + + +class AugmentedGraphHelper: + """ + Graph helper that augments the original graph with additional + dependencies and uses, plus tracks node equivalences for coalescing. + + TODO: if this becomes too large of compile time, consider binding + graphcycles.cc + """ + + def __init__( + self, + graph: fx.Graph, + node_ancestors: BitsetAncestors | None = None, + ): + # Each node starts in its own singleton set + self.graph = graph + self.merge_sets = {node: OrderedSet([node]) for node in graph.nodes} + + # Extra dependencies: node depends on dep (dep must come before node) + self.extra_deps: dict[fx.Node, OrderedSet[fx.Node]] = defaultdict(OrderedSet) + # Extra uses: reverse of extra_deps (node is used by user) + self.extra_uses: dict[fx.Node, OrderedSet[fx.Node]] = defaultdict(OrderedSet) + # Note: only reflect original ancestors, not maintained through additional deps + # or merge sets + self.node_ancestors = node_ancestors + + def add_extra_dep(self, *, n: fx.Node, dep: fx.Node) -> None: + """Add extra dependency: node depends on dep.""" + self.extra_deps[n].add(dep) + self.extra_uses[dep].add(n) + + def remove_extra_dep(self, *, n: fx.Node, dep: fx.Node) -> None: + if dep in self.extra_deps[n]: + self.extra_deps[n].discard(dep) + self.extra_uses[dep].discard(n) + + def merge_to_set(self, existing_node: fx.Node, new_node: fx.Node) -> None: + """ + Merge new_node into existing_node's set. The new node must be a singleton set. + """ + existing_set = self.merge_sets[existing_node] + new_set = self.merge_sets[new_node] + if len(new_set) != 1: + raise AssertionError( + f"new_node must be a singleton set, got size {len(new_set)}" + ) + + # Add all nodes from new_set to existing_set + existing_set.update(new_set) + + # Update all nodes from new_set to point to existing_set + for node in new_set: + self.merge_sets[node] = existing_set + + def unmerge_node(self, node: fx.Node) -> None: + """Remove a node from its merge set, making it singleton.""" + old_set = self.merge_sets[node] + + # If already singleton, nothing to do + if len(old_set) == 1: + return + + # Remove from old set + old_set.remove(node) + + # Make node singleton + self.merge_sets[node] = OrderedSet([node]) + + def get_merged_deps(self, node: fx.Node) -> OrderedSet[fx.Node]: + """ + Get all dependencies of a node considering merges and extra deps. + Combines: + 1. Direct deps (all_input_nodes) of node and its merge equivalents + 2. Extra deps of node and its merge equivalents + """ + deps: OrderedSet[fx.Node] = OrderedSet() + + # For each node in the merge set + for merged_node in self.merge_sets[node]: + # Add direct dependencies from all_input_nodes + deps.update(merged_node.all_input_nodes) + # Add extra dependencies + deps.update(self.extra_deps[merged_node]) + + return deps + + def has_cycle(self) -> bool: + return torch._dynamo.graph_deduplication._has_cycle( + self.graph, self.get_all_extra_deps() + ) + + def _get_all_ancestors(self, node: fx.Node) -> OrderedSet[fx.Node]: + """Transitive ancestors through both data deps and extra deps.""" + ancestors: OrderedSet[fx.Node] = OrderedSet() + stack: list[fx.Node] = list(node.all_input_nodes) + stack.extend(self.extra_deps.get(node, ())) + while stack: + n = stack.pop() + if n not in ancestors: + ancestors.add(n) + stack.extend(n.all_input_nodes) + stack.extend(self.extra_deps.get(n, ())) + return ancestors + + def has_path(self, source: fx.Node, target: fx.Node) -> bool: + """Check if there's a path from source to target.""" + # we should not be checking path from node to itself + if self.merge_sets[source] is self.merge_sets[target]: + raise AssertionError("source and target must not be in the same merge set") + + # search backwards from target to source + visited: OrderedSet[fx.Node] = OrderedSet() + queue = [target] + visited.add(target) + + while queue: + current = queue.pop() + + for dep in self.get_merged_deps(current): + # Check if we reached source or its equivalent + if dep in self.merge_sets[source]: + return True + + if dep in visited: + continue + + # We are searching from target, so this node is necessarily an ancestor + # of target. + # If dep is an ancestor of source, any path through dep to source would imply a cycle + if self.node_ancestors: + source_set = self.merge_sets[source] + is_ancestor_of_source = any( + self.node_ancestors.is_ancestor(dep, s) for s in source_set + ) + # Add to visited to avoid recomputing this check if we see dep again + if is_ancestor_of_source: + visited.add(dep) + continue + + visited.add(dep) + queue.append(dep) + + return False + + def transfer_erased_node_deps( + self, erased_to_new: dict[fx.Node, fx.Node | None] + ) -> None: + """ + Transfer all extra dependencies from erased nodes to their replacements, handling + cross-dependencies between erased nodes correctly. + + Skips deps where both endpoints resolve to replacement nodes from the + same erasure batch — these are intra-bucket deps that would create + cycles (e.g. new_start <-> new_wait within the same bucket). + """ + erased_merge_sets: dict[fx.Node, fx.Node | None] = {} + + for replaced, new in erased_to_new.items(): + for equiv in self.merge_sets[replaced]: + erased_merge_sets[equiv] = new + + # Transfer dependencies + for old_node, new_node in erased_merge_sets.items(): + if new_node is None: + # Clean up references to removed node + for extra_use in list(self.extra_uses[old_node]): + updated_use = erased_merge_sets.get(extra_use, extra_use) + if updated_use is not None: + self.extra_deps[updated_use].discard(old_node) + for extra_dep in list(self.extra_deps[old_node]): + updated_dep = erased_merge_sets.get(extra_dep, extra_dep) + if updated_dep is not None: + self.extra_uses[updated_dep].discard(old_node) + else: + # Transfer dependencies FROM old_node (what old_node depended on) + for extra_dep in self.extra_deps[old_node]: + updated_dep = erased_merge_sets.get(extra_dep, extra_dep) + if updated_dep is not None and updated_dep != new_node: + # Skip if reverse dep already exists (extra or data) + if new_node in self.extra_deps.get( + updated_dep, () + ) or new_node in OrderedSet(updated_dep.all_input_nodes): + continue + self.extra_deps[new_node].add(updated_dep) + self.extra_uses[updated_dep].discard(old_node) + self.extra_uses[updated_dep].add(new_node) + + # Transfer dependencies TO old_node (what depended on old_node) + for extra_use in self.extra_uses[old_node]: + updated_use = erased_merge_sets.get(extra_use, extra_use) + if updated_use is not None and updated_use != new_node: + # Skip if reverse dep already exists (extra or data) + if updated_use in self.extra_deps.get( + new_node, () + ) or updated_use in OrderedSet(new_node.all_input_nodes): + continue + self.extra_deps[updated_use].discard(old_node) + self.extra_deps[updated_use].add(new_node) + self.extra_uses[new_node].add(updated_use) + + # Clean up erased nodes + for old_node in erased_merge_sets: + self.extra_deps[old_node].clear() + self.extra_uses[old_node].clear() + del self.merge_sets[old_node] + + def remove_erased_extra_deps(self) -> None: + """Remove extra deps referencing erased nodes.""" + for node in list(self.extra_deps): + if node._erased: + for dep in list(self.extra_deps[node]): + self.remove_extra_dep(n=node, dep=dep) + continue + for dep in list(self.extra_deps[node]): + if dep._erased: + self.remove_extra_dep(n=node, dep=dep) + + def check_and_maybe_autofix_cyclic_extra_deps( + self, *, autofix: bool = False + ) -> None: + """Check for and optionally remove extra deps that create cycles. + + Args: + autofix: If True, silently remove cyclic deps. If False (default), + raise an error so the root cause gets investigated. + """ + if not self.has_cycle(): + return + removed = [] + for node in list(self.extra_deps): + for dep in list(self.extra_deps[node]): + ancestors = self._get_all_ancestors(dep) + if node in ancestors: + removed.append((node.name, dep.name)) + self.remove_extra_dep(n=node, dep=dep) + if not removed: + return + msg = ( + f"Overlap scheduling: detected {len(removed)} cyclic extra " + f"dep(s): {removed}. Please report this to the overlap " + f"scheduling developers." + ) + log.warning(msg) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_overlap_cyclic_extra_deps", + "encoding": "string", + }, + payload_fn=lambda: msg, + ) + if not autofix: + raise RuntimeError( + f"{msg}\nTo unblock, set " + f"torch._inductor.config.aten_distributed_optimizations" + f".overlap_scheduling_autofix_cycles = True" + ) + + def get_all_extra_deps(self) -> dict[fx.Node, OrderedSet[fx.Node]]: + """ + Get all extra dependencies in a format suitable for topological sort. + Returns a copy to avoid external modifications. + """ + return { + node: OrderedSet(deps) + for node, deps in self.extra_deps.items() + if deps # Only include nodes with non-empty deps + } diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be6e909f56827a5dda201f035d6b7b591288aaa1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9879e3beeb625b50a28e1a08e075919cad966b93 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee0728ce8d22e7463c9ba64316dcb1d70bb668c3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learned_heuristic_controller.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learned_heuristic_controller.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..966461ea1e8083482339bd03a34bb4c82326ef13 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learned_heuristic_controller.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learnedheuristic_interface.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learnedheuristic_interface.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bc903c4465a14d06ff20398331c3305fe274807 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learnedheuristic_interface.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py new file mode 100644 index 0000000000000000000000000000000000000000..c87561d6eb3e40874dc10a2928c22b6aa8636345 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py @@ -0,0 +1,296 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mm/ +from typing import List, Optional, Tuple + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class MMRankingA100(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 166912 + and str(metadata.device_capa) == "(8, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.0 + + def get_choice(self, idx: int) -> str | None: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('extern_mm') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4') + + def get_name(self) -> str: + return 'mm' + + def get_best_choices(self, context: AHContext) -> list[tuple[float, int]] | None: + if context.get_value('arith_intensity') <= 52.6245059967041: + if context.get_value('n') <= 34.0: + if context.get_value('n') <= 18.0: + if context.get_value('k*n') <= 312.0: + return [(0.093, 12), (0.081, 16), (0.081, 148), (0.070, 10), (0.070, 17), (0.070, 149), (0.070, 151), (0.070, 150), (0.070, 14), (0.058, 11), (0.058, 15), (0.058, 13), (0.058, 122), (0.047, 121), (0.035, 123), (0.012, 92)] + else: + if context.get_value('k') <= 40.0: + return [(0.083, 42), (0.083, 46), (0.083, 44), (0.083, 40), (0.083, 128), (0.067, 45), (0.067, 43), (0.067, 41), (0.067, 169), (0.067, 171), (0.067, 168), (0.067, 129), (0.067, 170), (0.033, 103), (0.017, 121)] + else: + return [(0.112, 137), (0.104, 136), (0.101, 0), (0.081, 1), (0.073, 135), (0.069, 67), (0.066, 187), (0.058, 41), (0.050, 71), (0.046, 68), (0.046, 70), (0.031, 44), (0.027, 43), (0.027, 170), (0.019, 189), (0.019, 188), (0.015, 169), (0.015, 171), (0.012, 115), (0.012, 168), (0.012, 69), (0.004, 103)] + else: + if context.get_value('mat1_stride_0') <= 20.0: + return [(0.069, 0), (0.059, 157), (0.059, 22), (0.059, 153), (0.059, 155), (0.059, 25), (0.059, 23), (0.059, 19), (0.044, 21), (0.044, 18), (0.044, 152), (0.044, 158), (0.044, 154), (0.044, 156), (0.044, 20), (0.044, 124), (0.044, 24), (0.030, 125), (0.029, 126), (0.015, 97), (0.015, 95), (0.015, 96), (0.010, 2), (0.010, 75)] + else: + if context.get_value('k') <= 68.0: + return [(0.087, 72), (0.087, 74), (0.087, 73), (0.086, 76), (0.077, 75), (0.067, 192), (0.058, 190), (0.048, 47), (0.048, 193), (0.048, 49), (0.048, 51), (0.048, 191), (0.038, 53), (0.019, 133), (0.019, 50), (0.019, 175), (0.019, 172), (0.019, 48), (0.019, 174), (0.010, 173), (0.010, 177), (0.010, 52), (0.010, 54), (0.010, 178), (0.010, 176)] + else: + return [(0.154, 52), (0.154, 72), (0.102, 75), (0.087, 49), (0.087, 73), (0.086, 51), (0.057, 176), (0.045, 2), (0.038, 191), (0.038, 178), (0.038, 190), (0.029, 173), (0.029, 76), (0.026, 138), (0.013, 139), (0.013, 140), (0.003, 0)] + else: + if context.get_value('k') <= 35.0: + if context.get_value('k') <= 18.0: + if context.get_value('m*n') <= 19505152.0: + return [(0.151, 159), (0.140, 160), (0.129, 164), (0.055, 127), (0.051, 29), (0.044, 161), (0.044, 147), (0.040, 146), (0.040, 31), (0.037, 145), (0.026, 28), (0.022, 90), (0.022, 93), (0.022, 94), (0.022, 100), (0.022, 125), (0.022, 158), (0.022, 157), (0.011, 87), (0.011, 88), (0.011, 89), (0.011, 91), (0.011, 95), (0.011, 96), (0.011, 98), (0.011, 99)] + else: + return [(0.069, 7), (0.069, 5), (0.067, 147), (0.066, 8), (0.061, 145), (0.058, 146), (0.052, 124), (0.049, 29), (0.049, 159), (0.046, 31), (0.043, 157), (0.041, 9), (0.041, 4), (0.040, 6), (0.035, 164), (0.035, 160), (0.026, 158), (0.017, 125), (0.017, 28), (0.017, 32), (0.017, 162), (0.017, 27), (0.017, 30), (0.017, 161), (0.009, 33), (0.009, 26), (0.009, 163), (0.006, 0)] + else: + if context.get_value('n') <= 68.0: + return [(0.101, 182), (0.101, 59), (0.088, 57), (0.076, 184), (0.076, 61), (0.076, 179), (0.076, 62), (0.076, 58), (0.063, 180), (0.063, 60), (0.051, 56), (0.050, 181), (0.025, 130), (0.025, 177), (0.025, 183), (0.013, 178), (0.013, 55)] + else: + return [(0.089, 180), (0.079, 60), (0.066, 35), (0.066, 181), (0.066, 38), (0.066, 58), (0.066, 179), (0.066, 57), (0.062, 184), (0.053, 37), (0.044, 166), (0.040, 55), (0.040, 39), (0.040, 36), (0.040, 165), (0.040, 167), (0.027, 177), (0.027, 34), (0.022, 159)] + else: + if context.get_value('m*n') <= 309760.0: + return [(0.298, 0), (0.097, 140), (0.080, 83), (0.072, 86), (0.044, 84), (0.036, 178), (0.036, 117), (0.036, 82), (0.032, 120), (0.032, 85), (0.028, 119), (0.024, 130), (0.024, 109), (0.020, 108), (0.020, 118), (0.012, 104), (0.012, 116), (0.012, 141), (0.012, 144), (0.008, 105), (0.008, 106), (0.008, 111), (0.008, 114), (0.008, 107), (0.008, 132), (0.004, 101), (0.004, 102), (0.004, 110), (0.004, 112), (0.004, 113), (0.004, 131)] + else: + if context.get_value('n') <= 72.0: + return [(0.227, 77), (0.118, 78), (0.102, 194), (0.086, 80), (0.059, 57), (0.054, 81), (0.049, 196), (0.048, 197), (0.048, 59), (0.043, 79), (0.032, 195), (0.027, 180), (0.022, 3), (0.021, 141), (0.016, 60), (0.016, 142), (0.011, 183), (0.011, 0), (0.011, 144)] + else: + return [(0.140, 186), (0.132, 185), (0.109, 63), (0.085, 65), (0.078, 37), (0.077, 35), (0.062, 197), (0.047, 194), (0.046, 165), (0.046, 57), (0.039, 78), (0.039, 79), (0.039, 66), (0.039, 64), (0.016, 195), (0.008, 159)] + else: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('m*n') <= 815360.0: + if context.get_value('k') <= 1184.0: + return [(0.218, 140), (0.205, 0), (0.154, 144), (0.115, 141), (0.051, 185), (0.051, 104), (0.039, 78), (0.038, 116), (0.026, 165), (0.026, 130), (0.026, 178), (0.013, 57), (0.013, 195), (0.013, 167), (0.013, 186)] + else: + return [(0.901, 0), (0.030, 144), (0.030, 134), (0.016, 3), (0.006, 78), (0.006, 77), (0.002, 57), (0.002, 194), (0.002, 59), (0.002, 60), (0.002, 143)] + else: + if context.get_value('arith_intensity') <= 187.23922729492188: + if context.get_value('mat1_stride_0') <= 198.0: + return [(0.273, 63), (0.158, 37), (0.152, 35), (0.127, 57), (0.097, 165), (0.053, 185), (0.031, 0), (0.028, 64), (0.014, 60), (0.014, 78), (0.009, 55), (0.008, 134), (0.005, 34), (0.005, 167), (0.005, 179), (0.005, 65), (0.005, 66), (0.005, 186), (0.005, 194), (0.002, 166)] + else: + return [(0.296, 63), (0.235, 0), (0.132, 64), (0.074, 37), (0.069, 78), (0.051, 185), (0.051, 35), (0.030, 57), (0.020, 77), (0.016, 194), (0.008, 66), (0.007, 65), (0.003, 3), (0.003, 165), (0.003, 141), (0.001, 134), (0.001, 166)] + else: + return [(0.405, 0), (0.246, 37), (0.177, 63), (0.145, 35), (0.005, 185), (0.005, 65), (0.005, 64), (0.004, 57), (0.003, 66), (0.002, 165), (0.001, 78), (0.001, 55)] + else: + return [(0.357, 0), (0.112, 165), (0.101, 57), (0.094, 179), (0.086, 64), (0.074, 167), (0.067, 60), (0.064, 159), (0.033, 35), (0.007, 195), (0.002, 180), (0.001, 34), (0.001, 166), (0.001, 78)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingH100.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingH100.py new file mode 100644 index 0000000000000000000000000000000000000000..74812d9f0b404bbb5d7040d298e2bd597f9bba8e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingH100.py @@ -0,0 +1,321 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mm/ +from typing import List, Optional, Tuple + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class MMRankingH100(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 232448 + and str(metadata.device_capa) == "(9, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.0 + + def get_choice(self, idx: int) -> str | None: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('extern_mm') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4') + + def get_name(self) -> str: + return 'mm' + + def get_best_choices(self, context: AHContext) -> list[tuple[float, int]] | None: + if context.get_value('arith_intensity') <= 29.89772129058838: + if context.get_value('n') <= 34.0: + if context.get_value('n') <= 18.0: + if context.get_value('k*n') <= 432.0: + if context.get_value('arith_intensity') <= 7.8700292110443115: + return [(0.098, 128), (0.098, 129), (0.098, 127), (0.073, 14), (0.073, 16), (0.073, 12), (0.073, 154), (0.073, 156), (0.073, 157), (0.073, 155), (0.049, 10), (0.049, 94), (0.049, 95), (0.048, 96)] + else: + return [(0.091, 154), (0.073, 10), (0.073, 15), (0.073, 13), (0.073, 11), (0.073, 17), (0.073, 16), (0.073, 14), (0.073, 12), (0.055, 127), (0.054, 157), (0.054, 156), (0.054, 155), (0.036, 129), (0.036, 128), (0.018, 41), (0.018, 43)] + else: + if context.get_value('k') <= 40.0: + return [(0.070, 39), (0.069, 45), (0.069, 41), (0.069, 43), (0.069, 111), (0.069, 112), (0.056, 38), (0.056, 40), (0.056, 42), (0.056, 44), (0.056, 174), (0.056, 173), (0.056, 175), (0.056, 134), (0.056, 172), (0.056, 135), (0.014, 154), (0.014, 127)] + else: + return [(0.147, 144), (0.119, 143), (0.087, 142), (0.083, 0), (0.073, 191), (0.059, 69), (0.050, 67), (0.046, 70), (0.041, 1), (0.036, 174), (0.032, 43), (0.032, 123), (0.028, 40), (0.027, 42), (0.027, 173), (0.023, 175), (0.018, 66), (0.014, 192), (0.014, 193), (0.014, 139), (0.014, 68), (0.014, 127)] + else: + if context.get_value('mat1_stride_0') <= 40.0: + if context.get_value('mat1_stride_0') <= 20.0: + return [(0.109, 23), (0.109, 21), (0.109, 20), (0.088, 0), (0.087, 131), (0.066, 18), (0.065, 130), (0.065, 132), (0.065, 159), (0.065, 160), (0.065, 161), (0.065, 158), (0.022, 22), (0.022, 19)] + else: + return [(0.065, 46), (0.064, 52), (0.064, 50), (0.064, 48), (0.064, 51), (0.064, 49), (0.064, 47), (0.064, 53), (0.064, 181), (0.064, 177), (0.064, 179), (0.064, 176), (0.038, 130), (0.038, 136), (0.026, 182), (0.026, 178), (0.026, 180), (0.026, 137), (0.025, 158), (0.013, 114), (0.013, 113)] + else: + if context.get_value('mat1_stride_0') <= 68.0: + return [(0.138, 140), (0.125, 195), (0.100, 71), (0.100, 74), (0.100, 196), (0.100, 194), (0.100, 197), (0.075, 75), (0.062, 72), (0.062, 73), (0.012, 180), (0.012, 51), (0.012, 182)] + else: + return [(0.124, 180), (0.124, 182), (0.114, 75), (0.103, 74), (0.093, 51), (0.093, 71), (0.072, 72), (0.062, 194), (0.052, 145), (0.052, 195), (0.021, 48), (0.021, 50), (0.021, 47), (0.020, 124), (0.010, 147), (0.010, 146), (0.010, 46)] + else: + if context.get_value('k') <= 18.0: + if context.get_value('m*k') <= 528.0: + return [(0.097, 88), (0.087, 92), (0.077, 90), (0.058, 105), (0.058, 103), (0.058, 104), (0.058, 99), (0.058, 100), (0.058, 106), (0.058, 93), (0.057, 91), (0.057, 97), (0.057, 98), (0.057, 101), (0.048, 102), (0.029, 87), (0.029, 89)] + else: + if context.get_value('n') <= 80.0: + return [(0.057, 161), (0.057, 130), (0.057, 24), (0.056, 164), (0.056, 163), (0.056, 166), (0.056, 168), (0.056, 30), (0.056, 28), (0.056, 26), (0.056, 25), (0.056, 27), (0.056, 29), (0.056, 31), (0.042, 131), (0.028, 99), (0.028, 101), (0.028, 100), (0.028, 167), (0.028, 165), (0.028, 133)] + else: + return [(0.110, 164), (0.108, 163), (0.106, 168), (0.069, 161), (0.066, 151), (0.060, 152), (0.055, 165), (0.050, 27), (0.050, 29), (0.048, 131), (0.043, 153), (0.037, 133), (0.037, 130), (0.028, 8), (0.028, 5), (0.027, 7), (0.026, 26), (0.016, 162), (0.012, 9), (0.007, 4), (0.005, 100), (0.005, 6), (0.005, 24)] + else: + if context.get_value('k') <= 36.0: + if context.get_value('n') <= 68.0: + return [(0.097, 184), (0.097, 56), (0.086, 186), (0.086, 183), (0.086, 188), (0.086, 58), (0.086, 60), (0.065, 54), (0.043, 187), (0.043, 185), (0.043, 57), (0.043, 61), (0.032, 55), (0.032, 130), (0.032, 59), (0.011, 181), (0.011, 163), (0.011, 136), (0.011, 138)] + else: + return [(0.117, 184), (0.117, 170), (0.117, 169), (0.107, 183), (0.106, 188), (0.075, 181), (0.064, 130), (0.064, 56), (0.053, 171), (0.032, 57), (0.032, 59), (0.032, 185), (0.011, 163), (0.011, 32), (0.011, 37), (0.011, 34), (0.011, 33), (0.011, 35), (0.011, 36), (0.011, 54)] + else: + if context.get_value('mat2_stride_0') <= 384.0: + return [(0.244, 0), (0.061, 76), (0.061, 79), (0.030, 3), (0.030, 183), (0.030, 189), (0.030, 187), (0.030, 64), (0.030, 190), (0.030, 62), (0.030, 198), (0.030, 201), (0.030, 77), (0.030, 200), (0.030, 80), (0.030, 199), (0.030, 78), (0.030, 184), (0.020, 86), (0.020, 84), (0.020, 120), (0.020, 81), (0.020, 121), (0.020, 85), (0.020, 122), (0.010, 83), (0.010, 118), (0.010, 119), (0.010, 82)] + else: + return [(0.274, 83), (0.171, 86), (0.152, 0), (0.071, 85), (0.061, 125), (0.050, 84), (0.020, 109), (0.020, 117), (0.020, 81), (0.020, 118), (0.020, 121), (0.020, 108), (0.020, 115), (0.020, 116), (0.010, 110), (0.010, 120), (0.010, 103), (0.010, 107), (0.010, 119), (0.010, 122)] + else: + if context.get_value('arith_intensity') <= 56.995582580566406: + if context.get_value('n') <= 68.0: + if context.get_value('k*n') <= 4448.0: + if context.get_value('m*n') <= 29626368.0: + return [(0.107, 198), (0.107, 200), (0.107, 201), (0.107, 199), (0.106, 76), (0.106, 79), (0.064, 197), (0.063, 56), (0.043, 184), (0.043, 187), (0.042, 80), (0.042, 77), (0.042, 183), (0.021, 78)] + else: + return [(0.073, 201), (0.073, 198), (0.073, 200), (0.073, 199), (0.073, 197), (0.073, 56), (0.073, 58), (0.073, 79), (0.073, 76), (0.072, 59), (0.072, 78), (0.072, 77), (0.072, 80), (0.018, 184), (0.018, 55), (0.018, 54)] + else: + if context.get_value('k') <= 348.0: + return [(0.206, 76), (0.183, 77), (0.169, 198), (0.160, 199), (0.053, 59), (0.046, 56), (0.038, 3), (0.030, 148), (0.030, 58), (0.030, 187), (0.023, 184), (0.015, 0), (0.008, 55), (0.008, 54)] + else: + return [(0.146, 198), (0.145, 199), (0.145, 148), (0.126, 0), (0.084, 76), (0.084, 77), (0.042, 80), (0.042, 79), (0.021, 149), (0.021, 150), (0.021, 3), (0.014, 46), (0.014, 74), (0.014, 75), (0.014, 124), (0.014, 194), (0.014, 195), (0.007, 145), (0.007, 146), (0.007, 2), (0.007, 72), (0.007, 147), (0.007, 71)] + else: + if context.get_value('m') <= 3264.0: + return [(0.247, 147), (0.115, 197), (0.066, 199), (0.066, 201), (0.066, 198), (0.049, 0), (0.049, 169), (0.049, 171), (0.033, 140), (0.033, 125), (0.033, 114), (0.016, 126), (0.016, 183), (0.016, 184), (0.016, 185), (0.016, 182), (0.016, 188), (0.016, 78), (0.016, 148), (0.016, 138), (0.016, 77), (0.016, 56), (0.016, 59)] + else: + if context.get_value('k') <= 62.5: + return [(0.226, 190), (0.226, 189), (0.122, 62), (0.122, 64), (0.055, 77), (0.055, 78), (0.037, 198), (0.036, 201), (0.036, 33), (0.024, 163), (0.018, 56), (0.018, 35), (0.018, 169), (0.006, 171)] + else: + return [(0.162, 35), (0.118, 33), (0.096, 189), (0.096, 190), (0.088, 169), (0.074, 62), (0.073, 56), (0.066, 171), (0.051, 198), (0.051, 201), (0.044, 59), (0.037, 64), (0.029, 63), (0.007, 0), (0.007, 77)] + else: + if context.get_value('m*n') <= 1097728.0: + return [(0.403, 0), (0.179, 141), (0.134, 150), (0.086, 147), (0.051, 148), (0.048, 3), (0.024, 189), (0.020, 199), (0.017, 64), (0.010, 65), (0.010, 77), (0.007, 114), (0.003, 138), (0.003, 59), (0.003, 182)] + else: + if context.get_value('m*n') <= 3244032.0: + return [(0.295, 189), (0.176, 64), (0.157, 65), (0.090, 0), (0.069, 62), (0.059, 63), (0.046, 77), (0.039, 169), (0.023, 199), (0.020, 35), (0.013, 33), (0.010, 171), (0.003, 141)] + else: + if context.get_value('n') <= 136.0: + return [(0.197, 189), (0.197, 63), (0.161, 77), (0.157, 62), (0.061, 33), (0.044, 65), (0.039, 35), (0.039, 64), (0.030, 169), (0.026, 0), (0.017, 199), (0.017, 148), (0.009, 56), (0.004, 3)] + else: + return [(0.460, 0), (0.145, 62), (0.138, 63), (0.081, 35), (0.047, 33), (0.043, 189), (0.023, 64), (0.018, 77), (0.013, 169), (0.009, 65), (0.009, 56), (0.005, 32), (0.005, 59), (0.002, 183), (0.002, 163)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMA100.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMA100.py new file mode 100644 index 0000000000000000000000000000000000000000..a781767a3ce520a073f9630b834154f156a5fe5f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMA100.py @@ -0,0 +1,150 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mixed_mm/ +from typing import List, Optional, Tuple + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class MixedMMA100(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 166912 + and str(metadata.device_capa) == "(8, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.0 + + def get_choice(self, idx: int) -> str | None: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('extern_fallback_mixed_mm') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + + def get_name(self) -> str: + return 'mixed_mm' + + def get_best_choices(self, context: AHContext) -> list[tuple[float, int]] | None: + if str(context.get_value('1LEQmLEQ16')) != 'True': + if context.get_value('m') <= 32.5: + if context.get_value('n') <= 6976.0: + if context.get_value('n') <= 3520.0: + if context.get_value('m*n') <= 37632.0: + return None + else: + return [(1.000, 13)] + else: + if context.get_value('m*k') <= 452352.0: + return [(0.590, 13), (0.256, 8), (0.103, 7), (0.051, 11)] + else: + return [(0.778, 8), (0.222, 13)] + else: + if context.get_value('k*n') <= 102776832.0: + if context.get_value('n') <= 14656.0: + return [(1.000, 11)] + else: + return [(0.889, 11), (0.111, 13)] + else: + return [(1.000, 11)] + else: + if context.get_value('m*n') <= 446464.0: + if context.get_value('m*n') <= 223424.0: + if context.get_value('mat1_stride_0') <= 3968.0: + return None + else: + return None + else: + if context.get_value('m*n') <= 346112.0: + return [(0.960, 16), (0.040, 7)] + else: + return [(0.750, 16), (0.136, 14), (0.114, 7)] + else: + if str(context.get_value('33LEQmLEQ64')) != 'True': + if context.get_value('n') <= 6976.0: + return [(1.000, 14)] + else: + return [(0.753, 2), (0.222, 1), (0.015, 7), (0.007, 16), (0.004, 12)] + else: + if context.get_value('n') <= 13888.0: + return [(0.710, 14), (0.275, 21), (0.014, 12)] + else: + return [(0.374, 19), (0.339, 20), (0.106, 21), (0.101, 16), (0.066, 17), (0.009, 14), (0.004, 18)] + else: + if context.get_value('n') <= 3520.0: + if context.get_value('arith_intensity') <= 3.994754433631897: + if str(context.get_value('mat2_dtype')) != 'torch.uint8': + if context.get_value('m*k') <= 18944.0: + return [(0.577, 5), (0.423, 6)] + else: + return [(0.988, 5), (0.012, 6)] + else: + if context.get_value('arith_intensity') <= 2.9899919033050537: + return None + else: + return None + else: + if context.get_value('arith_intensity') <= 7.956453561782837: + if context.get_value('k*n') <= 9244032.0: + return [(0.822, 5), (0.178, 6)] + else: + return [(0.977, 5), (0.023, 0)] + else: + if context.get_value('m*k') <= 978944.0: + return [(1.000, 5)] + else: + return [(0.971, 5), (0.029, 0)] + else: + if context.get_value('n') <= 13632.0: + if context.get_value('n') <= 6976.0: + return [(1.000, 6)] + else: + if context.get_value('k') <= 3968.0: + return [(0.617, 3), (0.111, 5), (0.099, 7), (0.086, 9), (0.062, 6), (0.025, 8)] + else: + return [(0.779, 8), (0.119, 5), (0.053, 7), (0.035, 6), (0.013, 3)] + else: + if context.get_value('k*n') <= 39518208.0: + return [(0.385, 4), (0.327, 3), (0.192, 6), (0.038, 7), (0.038, 10), (0.019, 5)] + else: + if context.get_value('n') <= 20800.0: + return [(0.821, 6), (0.121, 7), (0.029, 4), (0.014, 5), (0.007, 3), (0.007, 8)] + else: + return [(0.530, 7), (0.386, 6), (0.046, 8), (0.021, 3), (0.015, 4), (0.002, 5)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py new file mode 100644 index 0000000000000000000000000000000000000000..a149cc39d7f6c5c98c76961a2b250a667d1220f1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py @@ -0,0 +1,149 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mixed_mm/ +from typing import Optional + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class MixedMMH100(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 232448 + and str(metadata.device_capa) == "(9, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.0 + + def get_choice(self, idx: int) -> str | None: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('extern_fallback_mixed_mm') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8') + + def get_name(self) -> str: + return 'mixed_mm' + + def get_best_choices(self, context: AHContext) -> list[tuple[float, int]] | None: + if context.get_value('arith_intensity') <= 15.988086223602295: + if context.get_value('n') <= 25280.0: + if context.get_value('n') <= 1344.0: + if context.get_value('mat1_stride_0') <= 7808.0: + return [(0.581, 7), (0.419, 6)] + else: + if context.get_value('m*n') <= 7680.0: + return [(0.875, 0), (0.125, 6)] + else: + return [(0.833, 0), (0.167, 7)] + else: + if context.get_value('n') <= 8512.0: + if str(context.get_value('mat2_dtype')) != 'torch.int8': + return [(0.763, 6), (0.237, 7)] + else: + return [(0.725, 7), (0.275, 6)] + else: + if str(context.get_value('mat1_dtype')) != 'torch.bfloat16': + return [(0.736, 7), (0.197, 9), (0.048, 6), (0.014, 8), (0.005, 10)] + else: + return [(0.473, 7), (0.398, 6), (0.097, 9), (0.032, 10)] + else: + if context.get_value('n') <= 42254.0: + if context.get_value('n') <= 33856.0: + if context.get_value('k*n') <= 68157440.0: + return [(0.370, 4), (0.370, 5), (0.074, 7), (0.074, 8), (0.074, 11), (0.037, 6)] + else: + return [(0.916, 8), (0.036, 7), (0.036, 9), (0.012, 4)] + else: + return [(0.659, 5), (0.341, 6)] + else: + if context.get_value('k*n') <= 326052992.0: + if context.get_value('n') <= 55232.0: + return [(0.571, 6), (0.321, 7), (0.036, 4), (0.036, 8), (0.036, 9)] + else: + return [(0.506, 6), (0.325, 8), (0.104, 7), (0.039, 5), (0.026, 9)] + else: + if context.get_value('n') <= 57024.0: + return [(0.462, 9), (0.385, 7), (0.115, 6), (0.038, 8)] + else: + return [(0.598, 8), (0.223, 9), (0.107, 6), (0.071, 7)] + else: + if context.get_value('m*n') <= 543936.0: + if str(context.get_value('17LEQmLEQ32')) != 'True': + if context.get_value('m*n') <= 262272.0: + if context.get_value('n') <= 1592.5: + return [(0.860, 0), (0.140, 9)] + else: + return None + else: + if context.get_value('m*k') <= 1294336.0: + return [(0.833, 17), (0.150, 18), (0.017, 15)] + else: + return [(0.917, 17), (0.083, 8)] + else: + if context.get_value('n') <= 12416.0: + if context.get_value('m*n') <= 43008.0: + return None + else: + return [(0.853, 14), (0.147, 9)] + else: + return [(0.625, 12), (0.375, 14)] + else: + if context.get_value('m') <= 32.5: + if context.get_value('mat2_stride_1') <= 6656.0: + if context.get_value('n') <= 69184.0: + return [(0.611, 12), (0.361, 14), (0.028, 13)] + else: + return [(1.000, 12)] + else: + if context.get_value('mat2_stride_1') <= 20864.0: + return [(1.000, 12)] + else: + return [(0.958, 12), (0.042, 9)] + else: + if context.get_value('m*n') <= 1085440.0: + if context.get_value('n') <= 9152.0: + return [(1.000, 18)] + else: + return [(0.780, 18), (0.160, 16), (0.060, 20)] + else: + if context.get_value('m') <= 67.0: + return [(0.650, 16), (0.203, 19), (0.122, 18), (0.016, 20), (0.008, 1)] + else: + return [(0.561, 3), (0.185, 16), (0.096, 20), (0.083, 19), (0.076, 2)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMA100.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMA100.py new file mode 100644 index 0000000000000000000000000000000000000000..c19817f98484acb745a1fa600e25e1e3f3586307 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMA100.py @@ -0,0 +1,265 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/pad_mm/ +from typing import Optional + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class PadMMA100(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 166912 + and str(metadata.device_capa) == "(8, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.9294871794871795 + + def get_choice(self, idx: int) -> Optional[str]: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('orig') + self.choices.append('pad') + + def get_name(self) -> str: + return 'pad_mm' + + def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]: + if str(context.get_value('mat1_innermost_needs_padding')) != 'False': + if context.get_value('arith_intensity') <= 880.0238037109375: + if str(context.get_value('m_multiple_2')) != 'True': + if context.get_value('n') <= 652.0: + if context.get_value('m') <= 2022.0: + if str(context.get_value('using_tf32')) != 'False': + return [(0.579, 1), (0.421, 0)] + else: + return [(1.000, 0)] + else: + return [(1.000, 0)] + else: + if context.get_value('m*k') <= 107278336.0: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('m') <= 23691.0: + return [(0.993, 1), (0.007, 0)] + else: + return [(0.840, 1), (0.160, 0)] + else: + if context.get_value('arith_intensity') <= 793.3185424804688: + return [(0.958, 0), (0.042, 1)] + else: + return [(0.792, 1), (0.208, 0)] + else: + if context.get_value('arith_intensity') <= 795.6242370605469: + if context.get_value('mat2_stride_1') <= 2048.5: + return [(0.929, 0), (0.071, 1)] + else: + return [(1.000, 1)] + else: + if context.get_value('arith_intensity') <= 796.3460388183594: + return [(0.957, 1), (0.043, 0)] + else: + return [(0.778, 0), (0.222, 1)] + else: + if context.get_value('mat2_stride_0') <= 2432.0: + if str(context.get_value('k_multiple_2')) != 'False': + if context.get_value('n') <= 1024.5: + if str(context.get_value('prepadded_mat1')) != 'False': + return [(0.580, 0), (0.420, 1)] + else: + return [(0.986, 0), (0.014, 1)] + else: + if context.get_value('mat1_stride_0') <= 5125.0: + return [(0.551, 0), (0.449, 1)] + else: + return [(0.916, 0), (0.084, 1)] + else: + if context.get_value('mat2_align_size') <= 6.0: + if str(context.get_value('using_tf32')) != 'True': + return [(1.000, 0)] + else: + return [(0.800, 0), (0.200, 1)] + else: + if context.get_value('mat2_stride_1') <= 3820.0: + return [(0.986, 1), (0.014, 0)] + else: + return [(0.532, 0), (0.468, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('m*n') <= 5244928.0: + if str(context.get_value('k_multiple_2')) != 'True': + return [(0.971, 1), (0.029, 0)] + else: + return [(0.646, 1), (0.354, 0)] + else: + if context.get_value('k/(m*n)') <= 9.468618827668251e-06: + return [(0.800, 1), (0.200, 0)] + else: + return [(1.000, 1)] + else: + if context.get_value('mat1_stride_1') <= 1288.0: + if context.get_value('k') <= 5717.0: + return [(0.983, 0), (0.017, 1)] + else: + return [(0.800, 0), (0.200, 1)] + else: + return [(0.588, 0), (0.412, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('n') <= 2640.0: + if context.get_value('m_padded_length') <= 1.5: + if context.get_value('mat2_stride_1') <= 6021.0: + return [(1.000, 1)] + else: + if context.get_value('mat2_stride_1') <= 6069.0: + return [(0.900, 1), (0.100, 0)] + else: + return [(1.000, 1)] + else: + if str(context.get_value('m_multiple_2')) != 'False': + if context.get_value('m*k') <= 24444928.0: + return [(0.593, 0), (0.407, 1)] + else: + return [(0.923, 0), (0.077, 1)] + else: + return [(1.000, 1)] + else: + if context.get_value('m*k') <= 404182016.0: + if str(context.get_value('mat2_innermost_needs_padding')) != 'False': + if context.get_value('m*k') <= 12328960.0: + return [(0.732, 1), (0.268, 0)] + else: + return [(0.989, 1), (0.011, 0)] + else: + if context.get_value('m*k') <= 389028864.0: + return [(0.998, 1), (0.002, 0)] + else: + return [(0.922, 1), (0.078, 0)] + else: + if context.get_value('m*n') <= 137631744.0: + if context.get_value('m*k') <= 405715968.0: + return [(0.611, 1), (0.389, 0)] + else: + return [(0.946, 1), (0.054, 0)] + else: + return [(0.714, 0), (0.286, 1)] + else: + if context.get_value('mat2_stride_0') <= 3902.5: + return [(0.941, 0), (0.059, 1)] + else: + return [(0.583, 1), (0.417, 0)] + else: + if context.get_value('n_padded_length') <= 0.5: + if str(context.get_value('mat2_innermost_needs_padding')) != 'False': + if str(context.get_value('k_multiple_2')) != 'True': + if context.get_value('arith_intensity') <= 884.5185852050781: + if context.get_value('arith_intensity') <= 743.931884765625: + return [(1.000, 0)] + else: + return [(0.583, 0), (0.417, 1)] + else: + return [(1.000, 1)] + else: + if context.get_value('k/(m*n)') <= 0.00023481580865336582: + return [(0.900, 0), (0.100, 1)] + else: + return [(1.000, 0)] + else: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('m*k') <= 93734912.0: + if context.get_value('mat1_stride_0') <= 1344.0: + if context.get_value('n') <= 7168.0: + return [(1.000, 0)] + else: + return [(0.970, 0), (0.030, 1)] + else: + if context.get_value('m') <= 22883.5: + return [(0.977, 0), (0.023, 1)] + else: + return [(0.800, 0), (0.200, 1)] + else: + if context.get_value('arith_intensity') <= 1914.3681030273438: + if str(context.get_value('prepadded_mat1')) != 'False': + return [(0.981, 0), (0.019, 1)] + else: + return [(0.995, 0), (0.005, 1)] + else: + return [(1.000, 0)] + else: + if str(context.get_value('prepadded_mat1')) != 'False': + if context.get_value('mat2_stride_1') <= 256.5: + if context.get_value('m') <= 5880.5: + return [(1.000, 0)] + else: + return [(0.800, 0), (0.200, 1)] + else: + if context.get_value('m*k') <= 6318080.0: + return [(0.618, 1), (0.382, 0)] + else: + return [(0.880, 0), (0.120, 1)] + else: + if context.get_value('k/(m*n)') <= 0.0009747986623551697: + if context.get_value('k/(m*n)') <= 0.0006397514371201396: + return [(0.951, 0), (0.049, 1)] + else: + return [(0.857, 0), (0.143, 1)] + else: + return [(1.000, 0)] + else: + if str(context.get_value('using_tf32')) != 'False': + if str(context.get_value('n_multiple_2')) != 'False': + if context.get_value('m') <= 2024.0: + if context.get_value('mat2_stride_0') <= 1629.0: + if context.get_value('k*n') <= 1288704.0: + return [(0.600, 0), (0.400, 1)] + else: + return [(0.982, 0), (0.018, 1)] + else: + if context.get_value('mat1_stride_0') <= 768.0: + return [(0.619, 0), (0.381, 1)] + else: + return [(0.812, 1), (0.188, 0)] + else: + if context.get_value('m*n') <= 5803008.0: + return [(0.500, 0), (0.500, 1)] + else: + if context.get_value('mat2_stride_1') <= 896.0: + return [(1.000, 1)] + else: + return [(0.818, 1), (0.182, 0)] + else: + if context.get_value('mat2_stride_1') <= 2560.0: + if context.get_value('num_dims_needs_padding') <= 1.5: + if context.get_value('mat2_stride_1') <= 896.0: + return [(1.000, 1)] + else: + return [(0.857, 1), (0.143, 0)] + else: + return [(0.727, 1), (0.273, 0)] + else: + return [(0.667, 1), (0.333, 0)] + else: + if context.get_value('k/(m*n)') <= 0.00015462777810171247: + return [(0.857, 0), (0.143, 1)] + else: + if context.get_value('k/(m*n)') <= 0.0019917909521609545: + return [(1.000, 0)] + else: + return [(0.900, 0), (0.100, 1)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMH200.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMH200.py new file mode 100644 index 0000000000000000000000000000000000000000..1527b02319c105579be9b5aae81716142a9bf2ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMH200.py @@ -0,0 +1,175 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/pad_mm/ +from typing import Optional + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class PadMMH200(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 232448 + and str(metadata.device_capa) == "(9, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.7710651828298887 + + def get_choice(self, idx: int) -> Optional[str]: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('orig') + self.choices.append('pad') + + def get_name(self) -> str: + return 'pad_mm' + + def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]: + if str(context.get_value('mat1_innermost_needs_padding')) != 'True': + if str(context.get_value('mat2_innermost_needs_padding')) != 'True': + if context.get_value('n_padded_length') <= 0.5: + if str(context.get_value('prepadded_mat1')) != 'True': + if str(context.get_value('using_tf32')) != 'False': + return [(1.000, 0)] + else: + if context.get_value('mat1_stride_0') <= 3584.0: + return [(1.000, 0)] + else: + if context.get_value('mat2_stride_0') <= 3584.0: + return [(1.000, 0)] + else: + return [(0.528, 0), (0.472, 1)] + else: + if context.get_value('n') <= 2304.0: + if context.get_value('m*k') <= 25198592.0: + if context.get_value('arith_intensity') <= 1103.9319458007812: + return [(1.000, 0)] + else: + return [(0.885, 0), (0.115, 1)] + else: + if context.get_value('m*k') <= 25688064.0: + return [(1.000, 1)] + else: + return [(0.771, 0), (0.229, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('m') <= 27825.0: + return [(0.948, 0), (0.052, 1)] + else: + return [(0.855, 0), (0.145, 1)] + else: + if context.get_value('mat2_stride_0') <= 3584.0: + return [(1.000, 0)] + else: + return [(0.917, 1), (0.083, 0)] + else: + if context.get_value('m') <= 1823.5: + if str(context.get_value('n_multiple_2')) != 'False': + if context.get_value('k*n') <= 7859200.0: + return [(0.600, 0), (0.400, 1)] + else: + return [(1.000, 0)] + else: + if context.get_value('k/(m*n)') <= 0.00040277576772496104: + return [(1.000, 1)] + else: + return [(0.800, 1), (0.200, 0)] + else: + if context.get_value('n') <= 3602.0: + return [(0.800, 1), (0.200, 0)] + else: + return [(1.000, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + if str(context.get_value('n_multiple_16')) != 'False': + if str(context.get_value('k_multiple_2')) != 'True': + if context.get_value('arith_intensity') <= 744.8332214355469: + return [(0.600, 0), (0.400, 1)] + else: + return [(1.000, 1)] + else: + if context.get_value('m*n') <= 8912896.0: + if context.get_value('m*k') <= 5934080.0: + return [(0.800, 0), (0.200, 1)] + else: + return [(1.000, 0)] + else: + return [(1.000, 1)] + else: + return [(1.000, 1)] + else: + return [(1.000, 0)] + else: + if context.get_value('arith_intensity') <= 895.8767395019531: + if str(context.get_value('m_multiple_2')) != 'False': + if context.get_value('mat1_stride_1') <= 3421.0: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('mat2_stride_1') <= 10706.5: + if context.get_value('mat2_stride_0') <= 1024.5: + return [(0.816, 1), (0.184, 0)] + else: + return [(1.000, 1)] + else: + if str(context.get_value('k_multiple_2')) != 'True': + return [(0.905, 1), (0.095, 0)] + else: + return [(1.000, 0)] + else: + if str(context.get_value('prepadded_mat2')) != 'True': + if str(context.get_value('mat2_innermost_needs_padding')) != 'False': + return [(1.000, 0)] + else: + return [(0.932, 0), (0.068, 1)] + else: + if context.get_value('arith_intensity') <= 742.1241760253906: + return [(0.889, 0), (0.111, 1)] + else: + return [(0.765, 1), (0.235, 0)] + else: + if context.get_value('n') <= 1216.0: + if str(context.get_value('using_tf32')) != 'True': + if context.get_value('mat1_stride_1') <= 5567.0: + return [(0.896, 0), (0.104, 1)] + else: + return [(0.999, 0), (0.001, 1)] + else: + return [(1.000, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + return [(1.000, 1)] + else: + return [(1.000, 0)] + else: + if str(context.get_value('using_tf32')) != 'False': + return [(1.000, 1)] + else: + if context.get_value('mat2_stride_1') <= 2688.0: + return [(1.000, 0)] + else: + return [(0.500, 0), (0.500, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + return [(1.000, 1)] + else: + if str(context.get_value('mat2_innermost_needs_padding')) != 'True': + return [(1.000, 0)] + else: + return [(0.800, 0), (0.200, 1)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingA100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingA100.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e12f044406d9347d1f26471e3b3e7733c7c29b06 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingA100.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingH100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingH100.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35aa76709bf0acc79ca43bb4f482d888f1e69981 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingH100.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMA100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMA100.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0319b4d5509c60aac40cb4b81b9d4a1dd8827c5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMA100.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMH100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMH100.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f268466335d27165504ec741b7ab60889465b69 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMH100.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMA100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMA100.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12ebcaf1fa1ff58151f6a9d49126aab7ce88dcf7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMA100.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMH200.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMH200.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5526b80090990fb48d114a6a492b67a60d77ab70 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMH200.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b8a52cb52a7713b9b81e8fa2837620628368426 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b97a026d4fe622eacaad74bdd3a808e03379c2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic.py @@ -0,0 +1,320 @@ +import json +import os +from collections.abc import Callable +from functools import partial +from typing import Any + +import torch +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + AHOperation, + Choice, + CHOICE_COL, + Feedback, + FEEDBACK_COL, + get_metadata_str_from_log, +) +from torch._inductor.autoheuristic.learned_heuristic_controller import ( + LearnedHeuristicController, +) +from torch._inductor.ir import ChoiceCaller +from torch._inductor.runtime.runtime_utils import cache_dir +from torch._inductor.utils import get_gpu_shared_memory + + +class LocalFeedback: + """ + To be able to collect data for a choice, a function providing feedback given a choice has to be provided. + LocalFeedback can be used when AutoHeuristic should immediately run the function to collect feedback for each choice + (see pad_mm.py, where the autotuning happens locally, for an example). + """ + + def __init__(self, feedback_fn: Callable[[Choice], Feedback]) -> None: + self.feedback_fn = feedback_fn + + def __call__(self, choice: Choice) -> Feedback: + return self.feedback_fn(choice) + + +class InconsistentMetadata(Exception): + """ + Exception that is thrown when AutoHeuristic tries to log data to a file where the metadata stored in the file does + not match the metadata it would store if the file didn't exist. + """ + + +class AutoHeuristic: + """ + AutoHeuristic is a framework that allows one to collect data, learn a heuristic (i.e. a regression tree) and + generate the heuristic to code. This class allows one to collect data. The collected data can then be used to train + a heuristic (see torchgen/autoheuristic/). + """ + + collected_feedback: dict[Choice, Feedback] + + def __init__( + self, + fallback: Callable[[], Choice], + choices: list[Choice], + feedback: LocalFeedback | None, + context: AHContext, + name: str, + augment_context: list[AHOperation] | None = None, + precondition: Callable[[AHMetadata, AHContext], bool] | None = None, + ) -> None: + """ + Initializes an instance of the AutoHeuristic class. + + Args: + fallback: A callable that returns a Choice when the heuristic is unsure which choice to make, or + AutoHeuristic is in data collection mode. + choices: A list of possible choices the heuristic can make. + feedback: An instance of LocalFeedback that provides feedback for a given choice. + context: Context to store with each choice and feedback. + name: A string that identifies the heuristic. + augment_context: An optional list of AHOperation instances that augment the context. + precondition: A callable that returns a boolean indicating whether AutoHeuristic should run. + """ + self.fallback = fallback + self.choices = choices + self.feedback = feedback + self.context = context + self.name = name + self.collected_feedback = {} + self.augment_context = augment_context + self.metadata = AHMetadata( + get_gpu_shared_memory(), + torch.cuda.get_device_capability() if torch.cuda.is_available() else (0, 0), + self.choices, + self.name, + ) + self.precondition = precondition + + if not self.satisfies_precondition(): + return + + if torch._inductor.config.autoheuristic_log_path == "DEFAULT": + self.log_path = self.get_default_log_path() + else: + self.log_path = torch._inductor.config.autoheuristic_log_path + + if torch._inductor.config.collect_autoheuristic(self.name): + if self.feedback is not None: + for choice in self.choices: + feedback_val = self.feedback(choice) + self.save_data(choice, feedback_val) + + def satisfies_precondition(self) -> bool: + return self.precondition is None or self.precondition( + self.metadata, self.context + ) + + def get_choice(self) -> Choice: + """ + Returns the chosen option based on the value of autoheuristic_use. + If self.name is one of the comma separated strings in autoheuristic_use, + it queries a learned heuristic to make a decision. Otherwise, it returns the fallback option. + """ + + if not self.satisfies_precondition(): + return self.fallback() + + if torch._inductor.config.use_autoheuristic(self.name): + if self.augment_context is not None: + self.context.apply_operations(self.augment_context) + controller = LearnedHeuristicController( + self.metadata, + self.context, + ) + decision = controller.get_decision() + if decision not in self.choices: + # TODO(AlnisM): We might want to allow this in the future + return self.fallback() + if decision is not None: + return decision + return self.fallback() + + def get_top_k_choices( + self, top_k: int, always_included: list[str] | None = None + ) -> list[Choice] | None: + if not self.satisfies_precondition(): + return None + if torch._inductor.config.use_autoheuristic(self.name): + if self.augment_context is not None: + self.context.apply_operations(self.augment_context) + controller = LearnedHeuristicController( + self.metadata, + self.context, + ) + choices = controller.get_decisions_ranked(top_k) + if choices is None: + return None + if always_included is not None: + for choice in always_included: + if choice not in choices: + choices.append(choice) + return choices + return None + + def get_collected_feedback(self, choice: Choice) -> Any: + return self.collected_feedback.get(choice, None) + + @staticmethod + def get_device_identifier() -> str: + # a heuristic might work well for one GPU, but not for another + # we store the collected data per GPU model and learn a heuristic per GPU model + + # TODO(AlnisM): just using the device name for now, but the same GPU model can have different names + if torch.cuda.is_available(): + device_name = torch.cuda.get_device_name().replace(" ", "_") + return device_name + return "non_cuda_device" + + def get_default_log_path(self) -> str: + device_name = self.get_device_identifier() + path = f"{cache_dir()}/autoheuristic/{device_name}/" + os.makedirs(path, exist_ok=True) + path += f"{self.name}.txt" + return path + + def serialize_metadata(self) -> str: + metadata_dict = self.metadata.to_dict() + ( + num_features, + cat_features, + ) = self.context.get_numerical_and_categorical_features() + metadata_dict["numerical_features"] = num_features + metadata_dict["categorical_features"] = cat_features + return json.dumps(metadata_dict) + + def save_data(self, choice: Choice, feedback_val: Feedback) -> None: + self.collected_feedback[choice] = feedback_val + log_path = self.log_path + + lines = [] + log_exists = os.path.exists(log_path) + if log_exists: + # if log already exists, make sure it is consistent + metadata = self.serialize_metadata() + existing_metadata = get_metadata_str_from_log(self.log_path) + if existing_metadata != metadata: + raise InconsistentMetadata( + "Given metadata does not match existing metadata" + ) + else: + lines.append(self.serialize_metadata()) + feature_header = self.context.get_feature_names_csv() + header = feature_header + "," + CHOICE_COL + "," + FEEDBACK_COL + lines.append(header) + + line = "" + feature_values = self.context.get_feature_values_csv() + line += feature_values + "," + choice + "," + str(feedback_val) + lines.append(line) + + with open(log_path, "a") as f: + f.write("\n".join(lines) + "\n") + + +class AutoHeuristicSelectAlgorithm(AutoHeuristic): + """ + AutoHeuristicSelectAlgorithm is a subclass of AutoHeuristic that allows one to collect data and learn a heuristic + when one wants to use AutoHeuristic for kernel choice selection. + """ + + def __init__( + self, + fallback: Callable[[], ChoiceCaller | None], + choices: list[ChoiceCaller], + input_nodes: list[Any], + context: AHContext, + name: str, + augment_context: list[AHOperation] | None = None, + precondition: Callable[[AHMetadata, AHContext], bool] | None = None, + ) -> None: + """ + The arguments choices, input_nodes and name have to match the ones used in the call to + autotune_select_algorithm(), e.g. if the following call is made + autotune_select_algorithm(name, choices, input_nodes, layout), the same name, choices and input_nodes + have to be used here. + """ + self.input_nodes = input_nodes + self.choicestr2choice: dict[str, ChoiceCaller] = {} + for choice in choices: + self.choicestr2choice[choice.autoheuristic_id()] = choice + choices_str = list(self.choicestr2choice.keys()) + + def fallback_str() -> str: + fallback_choice = fallback() + if fallback_choice is None: + # TODO: Find a nicer way to handle this + return "unsure" + return fallback_choice.autoheuristic_id() + + super().__init__( + fallback_str, + choices_str, + None, + context, + name, + augment_context, + precondition, + ) + + if ( + torch._inductor.config.collect_autoheuristic(self.name) + and self.satisfies_precondition() + ): + self.register_global_feedback(input_nodes, choices) + + def register_global_feedback( + self, input_nodes: list[Any], choices: list[ChoiceCaller] + ) -> None: + """ + Registers a callback in select_algorithm, which is called with the timing of each choice. + """ + + from torch._inductor.select_algorithm import ( + add_feedback_saver, + create_inputs_key, + create_precompile_key, + ) + + def store_global_feedback( + ah_inputs_key: str, + ah_precompile_key: str, + timings: dict[ChoiceCaller, float], + name: str, + input_nodes: list[Any], + choices: list[ChoiceCaller], + profiled_time: Callable[[], dict[ChoiceCaller, float]], + precompile_times: dict[ChoiceCaller, float], + ) -> None: + current_inputs_key = create_inputs_key(input_nodes) + if current_inputs_key != ah_inputs_key: + return + current_precompile_key = create_precompile_key( + name, current_inputs_key, choices + ) + if current_precompile_key != ah_precompile_key: + return + for choice, time in timings.items(): + self.save_data(choice.autoheuristic_id(), time) + + inputs_key = create_inputs_key(input_nodes) + precompile_key = create_precompile_key(self.name, inputs_key, choices) + feedback_saver = partial(store_global_feedback, inputs_key, precompile_key) + add_feedback_saver(feedback_saver) + + def get_choice_caller(self) -> ChoiceCaller | None: + choice = self.get_choice() + return self.choicestr2choice.get(choice, None) + + def get_top_k_choices_caller( + self, top_k: int, always_included: list[str] | None = None + ) -> list[ChoiceCaller] | None: + choices = self.get_top_k_choices(top_k, always_included) + if choices is None: + return None + return [self.choicestr2choice[choice] for choice in choices] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bcdf48cae094bc22d20ebf2f87d07311725664db --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic_utils.py @@ -0,0 +1,340 @@ +import functools +from collections.abc import Callable +from typing import Any + +import torch + + +Feedback = float +Choice = str +Value = Any + +CHOICE_COL = "choice" +FEEDBACK_COL = "feedback" + + +class AHFeature: + """ + The context, that AutoHeuristic stores, is a list of features. AutoHeuristic needs to know whether a feature is + categorical (i.e., not a continuous variable) to learn a machine learning model. + """ + + def __init__(self, name: str, value: Value, is_categorical: bool = False) -> None: + self.name = name + self.value = value + self.is_categorical = is_categorical + + +class AHOperation: + """ + AHOperation can be used to augment the data collected by AutoHeuristic. + One might for example store features like m, k, n, but also want to use + features like m*n, or k*n, to learn a heuristic. Instead of storing features + that can be created from the collected data, one can use AHOperation to + create new features from the collected data. + """ + + def __init__( + self, name: str, func: Callable[[Any], Value], is_categorical: bool = False + ) -> None: + self.name = name + self.func = func + self.is_categorical = is_categorical + + def apply_operation(self, data: Any) -> None: + data[self.name] = self.func(data) + + +class AHContext: + """ + This class is used to specify which information AutoHeuristic should store. For each choice, AutoHeuristic will + store the context and the collected feedback. The context could be something like the shape of a tensor, i.e., + information that will help to learn a heuristic. + """ + + features: list[AHFeature] + context_dict: dict[str, Value] + + def __init__(self) -> None: + self.features = [] + self.context_dict = {} + + def add_feature( + self, name: str, value: Value, is_categorical: bool = False + ) -> None: + self.features.append(AHFeature(name, value, is_categorical=is_categorical)) + self.context_dict[name] = value + + def get_numerical_and_categorical_features(self) -> tuple[list[str], list[str]]: + numerical_features = [] + categorical_features = [] + for feature in self.features: + if feature.is_categorical: + categorical_features.append(feature.name) + else: + numerical_features.append(feature.name) + + return numerical_features, categorical_features + + def get_feature_names_csv(self) -> str: + return ",".join(feature.name for feature in self.features) + + def get_feature_values_csv(self) -> str: + return ",".join(str(feature.value) for feature in self.features) + + def get_value(self, name: str) -> Value: + return self.context_dict[name] + + def apply_operations(self, operations: list[AHOperation]) -> None: + for op in operations: + op.apply_operation(self.context_dict) + + +class AHMetadata: + def __init__( + self, + shared_memory: Any, + device_capa: tuple[int, int], + choices: list[Choice], + name: str, + ) -> None: + # use amount of shared_memory and device_capability to identify GPU + # TODO(AlnisM): there might be a better way to do this + self.shared_memory = shared_memory + self.device_capa = device_capa + self.choices = choices + self.name = name + + def to_dict(self) -> dict[str, Value]: + return { + "shared_memory": self.shared_memory, + "device_capa": self.device_capa, + "name": self.name, + } + + +def get_metadata_str_from_log(log_path: str) -> str: + with open(log_path, newline="") as file: + json_string = file.readline().strip() + return json_string + + +def check_minsize(context: AHContext, minsize: int) -> bool: + return ( + context.get_value("m") >= minsize + and context.get_value("k") >= minsize + and context.get_value("n") >= minsize + ) + + +def pad_mm_precondition(metadata: AHMetadata, context: AHContext) -> bool: + if metadata.shared_memory == 166912 and metadata.device_capa == (8, 0): + # A100 precondition + return check_minsize(context, 512) + elif metadata.shared_memory == 232448 and metadata.device_capa == (9, 0): + # H100 precondition + return check_minsize(context, 768) + return True + + +def get_mixedmm_precondition(metadata: AHMetadata, context: AHContext) -> bool: + m = context.get_value("m") + k = context.get_value("k") + n = context.get_value("n") + if m > 128 or k < 1024 or n < 1024: + return False + mat1_iscontig = context.get_value("mat1_iscontig") + mat2_iscontig = context.get_value("mat2_iscontig") + return mat1_iscontig and not mat2_iscontig + + +def get_mult_dims_ops() -> list[AHOperation]: + m_times_k_op = AHOperation("m*k", lambda data: data["m"] * data["k"]) + m_times_n_op = AHOperation("m*n", lambda data: data["m"] * data["n"]) + k_times_n_op = AHOperation("k*n", lambda data: data["k"] * data["n"]) + return [m_times_k_op, m_times_n_op, k_times_n_op] + + +def get_arith_intensity(data: Any) -> float: + m = data["m"] + k = data["k"] + n = data["n"] + if m == 0 or k == 0 or n == 0: + return 0.0 + return m * k * n / (m * k + k * n + m * n) + + +def pad_mm_operations() -> list[AHOperation]: + mult_dims_ops = get_mult_dims_ops() + k_div_m_times_n_op = AHOperation( + "k/(m*n)", lambda data: data["k"] / (data["m"] * data["n"]) + ) + + def bfloat_perf_hit(data: Any) -> bool: + m = data["m"] + k = data["k"] + n = data["n"] + is_bfloat = str(data["mat1_dtype"]) == "torch.bfloat16" + return k > (m * 1024) and k > (n * 1024) and is_bfloat + + bfloat_perf_hit_op = AHOperation( + "bfloat_perf_hit", bfloat_perf_hit, is_categorical=True + ) + + arith_intensity_op = AHOperation("arith_intensity", get_arith_intensity) + dims_need_padding_ops = get_dims_need_padding_ops() + dims_multiple_ops = get_dims_multiple_ops() + is_contig_ops = get_is_contig_ops() + + ah_operations = mult_dims_ops + [ + k_div_m_times_n_op, + bfloat_perf_hit_op, + arith_intensity_op, + ] + ah_operations.extend(dims_need_padding_ops) + ah_operations.extend(dims_multiple_ops) + ah_operations.extend(is_contig_ops) + return ah_operations + + +def between_op(data: Any, dim: str, lower: int, upper: int) -> bool: + return data[dim] >= lower and data[dim] <= upper + + +def between_ops() -> list[AHOperation]: + dims = ["m", "k", "n"] + limits = [(1, 16), (17, 32), (33, 64), (65, 128), (129, 256)] + ah_operations = [] + for dim in dims: + for lower, upper in limits: + between_op_fn = functools.partial( + between_op, dim=dim, lower=lower, upper=upper + ) + # using 'LEQ' instead of '<=' because '<=' cannot be exported to dot + between_op_name = f"{lower}LEQ{dim}LEQ{upper}" + ah_operations.append( + AHOperation(between_op_name, between_op_fn, is_categorical=True) + ) + return ah_operations + + +def pow2_op(data: Any, dim: str, exponent: int) -> bool: + return data[dim] == 2**exponent + + +def mm_operations() -> list[AHOperation]: + mult_dims_ops = get_mult_dims_ops() + arith_intensity_op = AHOperation("arith_intensity", get_arith_intensity) + return mult_dims_ops + [arith_intensity_op] + + +def mixed_mm_operations() -> list[AHOperation]: + return mm_operations() + between_ops() + + +def is_multiple(data: Any, dim: str, mult: int) -> bool: + return data[dim] % mult == 0 + + +def get_dims_multiple_ops() -> list[AHOperation]: + multiples = [2, 4, 8, 16, 32] + dims = ["m", "k", "n"] + dims_multiple_ops = [] + for dim in dims: + for mult in multiples: + is_multiple_fn = functools.partial(is_multiple, dim=dim, mult=mult) + dims_multiple_op = AHOperation( + f"{dim}_multiple_{mult}", is_multiple_fn, is_categorical=True + ) + dims_multiple_ops.append(dims_multiple_op) + return dims_multiple_ops + + +def get_dims_need_padding_ops() -> list[AHOperation]: + def mat1_innermost_needs_padding_fn(data: Any) -> bool: + mat1_stride_0 = data["mat1_stride_0"] + mat1_stride_1 = data["mat1_stride_1"] + m_padded_length = data["m_padded_length"] + k_padded_length = data["k_padded_length"] + mat1_innermost_needs_padding = False + if mat1_stride_0 == 1 and m_padded_length != 0: + mat1_innermost_needs_padding = True + if mat1_stride_1 == 1 and k_padded_length != 0: + mat1_innermost_needs_padding = True + return mat1_innermost_needs_padding + + mat1_innermost_op = AHOperation( + "mat1_innermost_needs_padding", + mat1_innermost_needs_padding_fn, + is_categorical=True, + ) + + def mat2_innermost_needs_padding_fn(data: Any) -> bool: + mat2_stride_0 = data["mat2_stride_0"] + mat2_stride_1 = data["mat2_stride_1"] + k_padded_length = data["k_padded_length"] + n_padded_length = data["n_padded_length"] + mat2_innermost_needs_padding = False + if mat2_stride_0 == 1 and k_padded_length != 0: + mat2_innermost_needs_padding = True + if mat2_stride_1 == 1 and n_padded_length != 0: + mat2_innermost_needs_padding = True + return mat2_innermost_needs_padding + + mat2_innermost_op = AHOperation( + "mat2_innermost_needs_padding", + mat2_innermost_needs_padding_fn, + is_categorical=True, + ) + + def num_dims_needs_padding_fn(data: Any) -> int: + m_padded_length = data["m_padded_length"] + k_padded_length = data["k_padded_length"] + n_padded_length = data["n_padded_length"] + num_dims_needs_padding = 0 + if m_padded_length != 0: + num_dims_needs_padding += 1 + if k_padded_length != 0: + num_dims_needs_padding += 1 + if n_padded_length != 0: + num_dims_needs_padding += 1 + return num_dims_needs_padding + + num_dims_op = AHOperation("num_dims_needs_padding", num_dims_needs_padding_fn) + return [mat1_innermost_op, mat2_innermost_op, num_dims_op] + + +def get_is_contig_ops() -> list[AHOperation]: + def mat1_is_contig_fn(data: Any) -> bool: + stride_0 = data["mat1_stride_0"] + stride_1 = data["mat1_stride_1"] + k = data["k"] + return stride_0 == k and stride_1 == 1 + + mat1_is_contig_op = AHOperation( + "mat1_iscontig", mat1_is_contig_fn, is_categorical=True + ) + + def mat2_is_contig_fn(data: Any) -> bool: + stride_0 = data["mat2_stride_0"] + stride_1 = data["mat2_stride_1"] + n = data["n"] + return stride_0 == n and stride_1 == 1 + + mat2_is_contig_op = AHOperation( + "mat2_iscontig", mat2_is_contig_fn, is_categorical=True + ) + + return [mat1_is_contig_op, mat2_is_contig_op] + + +def context_add_strides(context: AHContext, name: str, stride: tuple[int, ...]) -> None: + for i, s in enumerate(stride): + context.add_feature(f"{name}_stride_{i}", s) + + +def context_add_using_tf32(context: AHContext, dtype: torch.dtype) -> None: + using_tf32 = "not_float_32" + if dtype == torch.float32: + using_tf32 = torch.backends.cuda.matmul.fp32_precision == "tf32" + context.add_feature("using_tf32", using_tf32, is_categorical=True) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learned_heuristic_controller.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learned_heuristic_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..26f03e3838c33b3a2bdf3b1a325ffa6bce19ff2e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learned_heuristic_controller.py @@ -0,0 +1,119 @@ +import importlib +import inspect +import pkgutil +from collections import defaultdict +from typing import Any + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import LearnedHeuristic + + +def find_and_instantiate_subclasses( + package_name: str, base_class: Any +) -> list[LearnedHeuristic]: + instances = [] + + package = importlib.import_module(package_name) + for _, module_name, _ in pkgutil.walk_packages( + package.__path__, package.__name__ + "." + ): + try: + module_basename = module_name.split(".")[-1] + if not module_basename.startswith("_"): + # learned heuristics start with an underscore + continue + module = importlib.import_module(module_name) + + # look for classes that are subclasses of base_class + for _name, obj in inspect.getmembers(module): + if ( + inspect.isclass(obj) + and issubclass(obj, base_class) + and obj != base_class + ): + instance = obj() + instances.append(instance) + except Exception as e: + print(f"Error processing module {module_name}: {e}") + + return instances + + +class LearnedHeuristicController: + """ + Class that finds and instantiates all learned heuristics. It also provides + a way to get the decision of a learned heuristic. + """ + + existing_heuristics: dict[str, list[LearnedHeuristic]] = defaultdict(list) + """ + A dictionary that stores all the learned heuristics for each optimization. + The key is the optimization name, and the value is a list of LearnedHeuristic objects. + """ + + heuristics_initialized: bool = False + """ + A flag that indicates whether the learned heuristics have been initialized. + Set to true when the get_decision() function is called for the first time. + """ + + def __init__( + self, + metadata: AHMetadata, + context: AHContext, + ) -> None: + self.metadata = metadata + self.context = context + + def get_heuristics(self, name: str) -> list[LearnedHeuristic]: + """ + Returns a list of learned heuristics for the given optimization name. + """ + + if not LearnedHeuristicController.heuristics_initialized: + # learned heuristics are generated into the following package + learned_heuristics_package = "torch._inductor.autoheuristic.artifacts" + + # learned heuristics have to be of type LearnedHeuristic + base_class = LearnedHeuristic + found_heuristics = find_and_instantiate_subclasses( + learned_heuristics_package, base_class + ) + + for learned_heuristic in found_heuristics: + opt_name = learned_heuristic.get_name() + LearnedHeuristicController.existing_heuristics[opt_name].append( + learned_heuristic + ) + LearnedHeuristicController.heuristics_initialized = True + + return LearnedHeuristicController.existing_heuristics[name] + + def get_decision(self) -> Choice | None: + """ + Returns the decision made by the learned heuristic or None if no heuristic was found or the heuristic is unsure + which choice to make. + """ + + heuristics = self.get_heuristics(self.metadata.name) + for heuristic in heuristics: + if heuristic.check_precondition(self.metadata, self.context): + return heuristic.get_decision(self.context, self.metadata.choices) + return None + + def get_decisions_ranked(self, top_k: int) -> list[Choice] | None: + heuristics = self.get_heuristics(self.metadata.name) + for heuristic in heuristics: + if heuristic.check_precondition(self.metadata, self.context): + choices = heuristic.get_decisions_ranked(self.context) + if choices is None: + return None + avail_choices = [ + choice for choice in choices if choice in self.metadata.choices + ] + return avail_choices[:top_k] + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learnedheuristic_interface.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learnedheuristic_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..85558cf8e488c7f56fa99c4f59b6150eb37ff592 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learnedheuristic_interface.py @@ -0,0 +1,82 @@ +import operator + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) + + +class LearnedHeuristic: + """ + LearnedHeuristic is a base class for all learned heuristics. + """ + + def __init__(self) -> None: + pass + + def check_precondition( + self, + metadata: AHMetadata, + context: AHContext, + ) -> bool: + return True + + def get_decision(self, context: AHContext, choices: list[Choice]) -> Choice | None: + return None + + def get_confidence_threshold(self) -> float: + return 1.0 + + def get_name(self) -> str: + return "" + + def get_decisions_ranked(self, context: AHContext) -> list[str] | None: + return None + + +class LearnedHeuristicRegression(LearnedHeuristic): + def get_feedback(self, context: AHContext, choice: Choice) -> float: + return 1.0 + + def get_decision(self, context: AHContext, choices: list[Choice]) -> Choice | None: + choice2feedback = {} + for choice in choices: + predicted_feedback = self.get_feedback(context, choice) + choice2feedback[choice] = predicted_feedback + sorted_choices_feedback = sorted( + choice2feedback.items(), key=operator.itemgetter(1) + ) + highest_feedback = sorted_choices_feedback[-1][1] + second_highest_feedback = sorted_choices_feedback[-2][1] + if highest_feedback / second_highest_feedback > self.get_confidence_threshold(): + return sorted_choices_feedback[-1][0] + # We are not sure which choice is the best one + return None + + +class LearnedHeuristicDecision(LearnedHeuristic): + def get_choice(self, idx: int) -> str | None: + return None + + def get_decision(self, context: AHContext, choices: list[Choice]) -> Choice | None: + best_choices = self.get_best_choices(context) + if not best_choices: + return None + (best_choice_proba, best_choice_idx) = best_choices[0] + if best_choice_proba <= self.get_confidence_threshold(): + return None + return self.get_choice(best_choice_idx) + + def get_decisions_ranked(self, context: AHContext) -> list[str] | None: + feedback_idx_list = self.get_best_choices(context) + if feedback_idx_list is None: + return None + choices = [ + self.get_choice(feedback_idx[1]) for feedback_idx in feedback_idx_list + ] + choices = [choice for choice in choices if choice is not None] + return choices + + def get_best_choices(self, context: AHContext) -> list[tuple[float, int]] | None: + return [] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autotune_process.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autotune_process.py new file mode 100644 index 0000000000000000000000000000000000000000..e65dc3f67cbbcfc677c5add90c610e8680dd0768 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autotune_process.py @@ -0,0 +1,1685 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import atexit +import contextvars +import ctypes +import dataclasses +import functools +import logging +import multiprocessing as mp +import os +import pickle +import queue +import selectors +import subprocess +import sys +import threading +import time +import warnings +from collections.abc import Callable, Iterable, Sequence +from concurrent.futures import Future, ProcessPoolExecutor, ThreadPoolExecutor +from ctypes import byref, c_size_t, c_void_p, CDLL +from typing import Any, IO, TYPE_CHECKING +from typing_extensions import override + +import torch +import torch._inductor.async_compile +from torch._dynamo.device_interface import get_interface_for_device +from torch._dynamo.testing import rand_strided +from torch._inductor import ir +from torch._inductor.codecache import ( + CppCodeCache, + CUDACodeCache, + DLLWrapper, + get_hash, + PyCodeCache, + write, + XPUCodeCache, +) +from torch._inductor.compile_worker.timer import Timer +from torch._inductor.utils import ( + apply_subprocess_env, + clear_caches, + clear_on_fresh_cache, + do_bench_using_profiling, + get_gpu_type, + get_ld_library_path, + is_gpu, + python_subprocess_env, +) +from torch._logging import getArtifactLogger +from torch.utils._ordered_set import OrderedSet + + +# Inactivity timeout for AutotuneProcessPool in seconds. +# Default: 600 seconds (10 minutes). Set to 0 to disable. +AUTOTUNE_POOL_INACTIVITY_TIMEOUT = int( + os.environ.get("TORCHINDUCTOR_AUTOTUNE_POOL_INACTIVITY_TIMEOUT", "600") +) + +if TYPE_CHECKING: + from types import ModuleType + + from torch._inductor.select_algorithm import ( + ChoiceCaller, + PartialRender, + TritonTemplateCaller, + ) + +from . import config +from .runtime.benchmarking import benchmarker +from .virtualized import V + + +CUDA_VISIBLE_DEVICES = "CUDA_VISIBLE_DEVICES" + + +_visible_device_env_var_maps = { + "cuda": "CUDA_VISIBLE_DEVICES", + "xpu": "ZE_AFFINITY_MASK", +} + + +def get_visible_devices_env_var(gpu_type: str | None = None) -> str: + if gpu_type is None: + gpu_type = get_gpu_type() + if gpu_type not in _visible_device_env_var_maps: + raise ValueError(f"Unsupported gpu_type: {gpu_type}") + return _visible_device_env_var_maps[gpu_type] + + +autotuning_log = getArtifactLogger(__name__, "autotuning") + + +class NonzeroWorkspaceNotSupportedError(Exception): + pass + + +def _cache_env_for_subprocess() -> dict[str, str | None]: + env_vars = ["TORCHINDUCTOR_CACHE_DIR", "TRITON_CACHE_DIR"] + return {v: os.environ.get(v) for v in env_vars} + + +_last_applied_cache_env: dict[str, str | None] | None = None + + +def _apply_subprocess_env_and_clear_caches( + extra_env: dict[str, str | None] | None, +) -> None: + global _last_applied_cache_env + + if extra_env is None: + return + + if extra_env != _last_applied_cache_env: + clear_caches() + _last_applied_cache_env = extra_env.copy() + apply_subprocess_env(extra_env) + + +def _run_with_subprocess_env( + fn: Callable[..., Any], + extra_env: dict[str, str | None], + *args: Any, + **kwargs: Any, +) -> Any: + _apply_subprocess_env_and_clear_caches(extra_env) + return fn(*args, **kwargs) + + +class TuningProcess: + """ + Class to launch and interact with a benchmarking subprocess. + """ + + @staticmethod + def process_main(read_pipe: IO[bytes], write_pipe: IO[bytes]) -> None: + """ + Entry point for the child process. + """ + autotuning_log.debug( + "Started autotune subprocess %s. Visible devices: %s", + os.getpid(), + os.environ.get(get_visible_devices_env_var()), + ) + + def workloop(): + while True: + job, extra_env = TuningProcess.recv(read_pipe) + if job is None: + # None is a sentinel for the child to shut down + break + try: + _apply_subprocess_env_and_clear_caches(extra_env) + result = job() + except Exception as e: + result = e + TuningProcess.send(result, write_pipe) + + try: + workloop() + except EOFError: + # The parent closed the pipe + pass + + @staticmethod + def send( + obj: Any, write_pipe: IO[bytes], extra_env: dict[str, str | None] | None = None + ) -> None: + pickle.dump((obj, extra_env), write_pipe) + write_pipe.flush() + + @staticmethod + def recv(read_pipe: IO[bytes]) -> Any: + return pickle.load(read_pipe) + + def __init__(self, device: int | None): + self.device = device + self.start() + + def start(self): + """ + Start the benchmarking subprocess. + """ + entry = os.path.join(os.path.dirname(__file__), "__autotune_main__.py") + + subproc_read_fd, write_fd = os.pipe() + read_fd, subproc_write_fd = os.pipe() + self.write_pipe = os.fdopen(write_fd, "wb") + self.read_pipe = os.fdopen(read_fd, "rb") + + self.selector = selectors.DefaultSelector() + self.selector.register(self.read_pipe, selectors.EVENT_READ) + + cmd = [ + sys.executable, + entry, + f"--parent={os.getpid()}", + f"--read-fd={str(subproc_read_fd)}", + f"--write-fd={str(subproc_write_fd)}", + ] + env = { + **python_subprocess_env(), + # We shouldn't be using the Triton async compile subprocess pool, + # but as a precaution set the env var that disables its creation. + "TORCH_WARM_POOL": "0", + # Some internal usages need a modified LD_LIBRARY_PATH. + "LD_LIBRARY_PATH": get_ld_library_path(), + # This will cause the subprocs to profile using the profiler. + "TORCHINDUCTOR_PROFILE_WITH_DO_BENCH_USING_PROFILING": "1" + if config.profile_bandwidth_with_do_bench_using_profiling + else "0", + } + if self.device is not None: + env[get_visible_devices_env_var()] = str(self.device) + self.process = subprocess.Popen( + cmd, + env=env, + pass_fds=(subproc_read_fd, subproc_write_fd), + ) + os.close(subproc_read_fd) + os.close(subproc_write_fd) + + self.running = True + + def alive(self) -> bool: + """ + True if the subprocess is still running. + """ + return self.running and self.process.poll() is None + + def put(self, req: Any, extra_env: dict[str, str | None] | None = None) -> None: + """ + Push a work item to the child process. + """ + if not self.alive(): + self.start() + TuningProcess.send(req, self.write_pipe, extra_env=extra_env) + + def get(self, timeout: float = 120.0) -> Any: + """ + Get a response from the child process. Raises TimeoutError on timeout; + raises EOFError if the subprocess crashes. + """ + try: + if not self.selector.select(timeout): + raise TimeoutError(f"Timeout in autotune subprocess {self.process.pid}") + result, _ = TuningProcess.recv(self.read_pipe) + except TimeoutError: + self.kill() + raise + except EOFError: + # The subprocess crashed + self.close() + raise + except Exception: + autotuning_log.exception( + "Unexpected exception in autotune subprocess %s", self.process.pid + ) + self.kill() + raise + + if isinstance(result, Exception): + raise result + return result + + def shutdown(self, wait: bool = True) -> None: + """ + Signal the child process to shut down gracefully. + """ + if self.alive(): + TuningProcess.send(None, self.write_pipe) + if wait: + self.wait() + + def wait(self) -> None: + """ + Wait for the child process to exit. + """ + if self.alive(): + self.process.wait() + self.close() + + def close(self) -> None: + """ + Close resources. + """ + self.selector.close() + self.read_pipe.close() + self.write_pipe.close() + self.running = False + + def kill(self) -> None: + """ + Send a SIGKILL to the child process. + """ + if self.alive(): + autotuning_log.error( + "Sending SIGKILL to autotune subprocess %d", + self.process.pid, + ) + self.process.kill() + self.close() + + def restart(self) -> None: + """ + Gracefully restarts the child process. + """ + self.shutdown(wait=True) + self.start() + + +class TuningProcessPool: + """ + Maintains a pool of TuningProcesses to benchmark kernels in parallel + across devices. By default, we create one TuningProcess per device and + set the sub-process environment to make only that device visible. + """ + + def __init__(self) -> None: + """ + Start the child processes. + """ + devices = self.get_device_list() + autotuning_log.debug("Sub-process autotune device list: %s", devices) + + # Launch the child processes. + self.processes = [TuningProcess(device=device) for device in devices] + + self.process_queue: queue.Queue[TuningProcess] = queue.Queue() + for p in self.processes: + self.process_queue.put(p) + + # Use a thread pool to manage distributing work to the subprocesses. + # Threads block on an available process, so it makes sense to match + # the number of threads with the number of devices. + self.executor = ThreadPoolExecutor(max_workers=len(devices)) + + @staticmethod + def get_device_list() -> Sequence[int | None]: + """ + Gather the list of devices to be used in the pool. + """ + if not config.autotune_multi_device: + # Don't use multiple devices + return [None] + + gpu_type = get_gpu_type() + device_interface = get_interface_for_device(gpu_type) + count = device_interface.device_count() + visible_devices_env_var = get_visible_devices_env_var(gpu_type) + + # If the user specified the visible devices in the env, use those. + if visible_devices_env_var in os.environ: + devices = [int(d) for d in os.environ[visible_devices_env_var].split(",")] + if not len(devices) <= count: + raise AssertionError( + f"{visible_devices_env_var} specifies {len(devices)} devices, " + f"but only {count} devices are available" + ) + return devices + + return list(range(count)) + + def shutdown(self) -> None: + """ + Signal all child processes to exit. + """ + self.executor.shutdown() + + for p in self.processes: + p.shutdown(wait=False) + for p in self.processes: + p.wait() + + def target(self, choice: TritonTemplateCaller) -> float: + """ + Entry point for the thread-pool helper threads: Wait for an open TuningProcess, + remove it from the queue, execute the benchmark in that subprocess, and return + the TuningProcess to the queue. + """ + if choice.bmreq is None: + raise AssertionError( + f"Expected choice.bmreq to be set, but got None for choice '{choice}'" + ) + + extra_env = _cache_env_for_subprocess() + process = self.process_queue.get() + process.put(choice.bmreq.benchmark, extra_env=extra_env) + try: + return process.get( + config.max_autotune_subproc_result_timeout_seconds, + ) + except TimeoutError: + warnings.warn( + f"Timed out benchmarking choice '{choice}'. It will be ignored. " + "Please debug the root cause in case the choice can bring perf gains." + ) + # Set to INF so this choice will be ignored + return float("inf") + except Exception as process_exception: + warnings.warn( + f"Failed to benchmark choice '{choice}'. It will be ignored. " + "Please debug the root cause in case the choice can bring perf gains." + ) + # Sticky CUDA errors corrupt the context, making it unrecoverable. + # The process must be restarted to restore CUDA functionality. + error_msg = str(process_exception) + if ( + "cudaErrorLaunchFailure" in error_msg + or "cudaErrorIllegalAddress" in error_msg + ): + process.restart() + # Set to INF so this choice will be ignored + return float("inf") + finally: + self.process_queue.put(process) + + def benchmark( + self, + choices: list[TritonTemplateCaller], + ) -> dict[TritonTemplateCaller, float]: + """ + Benchmark each choice in a separate process. + """ + + # Use a ThreadExecutorPool to spread the work across the subprocesses and + # to grab subprocesses as soon as they're free. + results = dict(zip(choices, self.executor.map(self.target, choices))) + + return results + + +LayoutOrBuffer = ir.Layout | ir.Buffer + + +@dataclasses.dataclass +class TensorMeta: + device: torch.device + dtype: torch.dtype + sizes: torch._prims_common.ShapeType + strides: torch._prims_common.StrideType + offset: int + name: str | None = None + + @classmethod + def from_irnodes( + cls, irnodes: LayoutOrBuffer | Sequence[LayoutOrBuffer] + ) -> TensorMeta | list[TensorMeta]: + from torch._inductor.select_algorithm import get_strides_with_layout_constraints + + if isinstance(irnodes, Sequence): + result: list[Any] = [cls.from_irnodes(x) for x in irnodes] + if not all(isinstance(x, TensorMeta) for x in result): + raise AssertionError( + f"Expected all elements to be TensorMeta, got types: " + f"{[type(x) for x in result if not isinstance(x, TensorMeta)]}" + ) + return result + + node = irnodes + if isinstance(node, ir.Layout): + node = ir.Buffer(name="fake", layout=node) + + dtype = node.get_dtype() + if dtype is None: + raise AssertionError( + f"Expected node to have a dtype, but get_dtype() returned None for node '{node}'" + ) + device = node.get_device() + if device is None: + raise AssertionError( + f"Expected node to have a device, but get_device() returned None for node '{node}'" + ) + + return TensorMeta( + device=device, + dtype=dtype, + sizes=V.graph.sizevars.optimization_hints(node.get_size()), + strides=V.graph.sizevars.optimization_hints( + get_strides_with_layout_constraints(node) + ), + offset=V.graph.sizevars.optimization_hint(node.get_layout().offset), + name=node.get_name(), + ) + + def to_tensor(self) -> torch.Tensor: + return rand_strided( + self.sizes, + self.strides, + device=self.device, + dtype=self.dtype, + extra_size=self.offset, + ) + + +@dataclasses.dataclass +class BenchmarkRequest: + """ + Only handle triton template benchmark for now. The extern kernel benchmark + can be done inside the same process since they usually don't cause crash. + + Important: Instances of this class and subclasses have to be serializable + across process boundaries. Do not put CUDA Tensors in here! + """ + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + extra_args: Iterable[Any], + ) -> None: + # the kernel name defined in the module + self.kernel_name = kernel_name + + if isinstance(input_tensor_meta, TensorMeta): + self.input_tensor_meta: list[TensorMeta] = [input_tensor_meta] + else: + self.input_tensor_meta: list[TensorMeta] = input_tensor_meta + + if output_tensor_meta and isinstance(output_tensor_meta, (tuple, list)): + if len(output_tensor_meta) > 1: + # Each output with same meta for Grouped GEMM + if not all( + getattr(output_tensor_meta[0], attr) == getattr(x, attr) + for x in output_tensor_meta + for attr in ["device", "dtype", "sizes", "strides", "offset"] + ): + raise AssertionError( + "All output tensor metas in a Grouped GEMM must have matching " + "device, dtype, sizes, strides, and offset" + ) + self.output_tensor_meta = output_tensor_meta[0] + else: + # pyrefly: ignore [bad-assignment] + self.output_tensor_meta: TensorMeta = output_tensor_meta + + self.extra_args = extra_args + self.benchmark_with_cudagraphs = False + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + raise NotImplementedError + + def cleanup_run_fn(self) -> None: + pass + + def do_bench( + self, + fn, + *input_tensors: torch.Tensor, + out: torch.Tensor | None = None, + ) -> float: + raise NotImplementedError + + def benchmark( + self, + *input_tensors: torch.Tensor, + out: torch.Tensor | None = None, + ) -> float: + debug = autotuning_log.isEnabledFor(logging.DEBUG) + if debug: + start_ts = time.time() + + # create args and out tensor + if out is None: + if not (self.input_tensor_meta and self.output_tensor_meta): + raise AssertionError( + "Input and output tensor meta must be populated when input_tensors is empty" + ) + if not len(input_tensors) == 0: + raise AssertionError( + f"Expected no input_tensors when out is None, but got {len(input_tensors)}" + ) + input_tensors = tuple(x.to_tensor() for x in self.input_tensor_meta) + out = self.output_tensor_meta.to_tensor() + + if debug: + create_tensor_elapse = time.time() - start_ts # type: ignore[possibly-undefined] + start_ts = time.time() + try: + try: + fn = self.make_run_fn(*input_tensors, out=out) + except NonzeroWorkspaceNotSupportedError: + # Skipping all ops with nonzero workspace requirements + autotuning_log.info("Skipping op due to nonzero workspace requirement") + return float("inf") + + if debug: + load_elapse = time.time() - start_ts # type: ignore[possibly-undefined] + start_ts = time.time() + + if self.benchmark_with_cudagraphs: + res = benchmarker.benchmark_gpu_with_cuda_graph(fn) + else: + res = self.do_bench(fn, *input_tensors, out) + + if debug: + bench_elapse = time.time() - start_ts # type: ignore[possibly-undefined] + autotuning_log.debug( + "InChildProcess %s: load %f, create tensor %f, bench %f", + self, + load_elapse, # type: ignore[possibly-undefined] + create_tensor_elapse, # type: ignore[possibly-undefined] + bench_elapse, + ) + return res + finally: + self.cleanup_run_fn() + + +class _TestBenchmarkRequest(BenchmarkRequest): + """ + Supports unit testing. Defined in this file instead of the test file so the + TuningProcess sub-process can unpickle these objects. + """ + + def __init__( + self, + result: float = 0.0, + device: int | None = None, + sleep: float | None = None, + exc: Exception | None = None, + crash: bool = False, + ): + self.result = result + self.device = device + self.sleep = sleep + self.exc = exc + self.crash = crash + + def benchmark( + self, *input_tensors: torch.Tensor, out: torch.Tensor | None = None + ) -> float: + if self.device is not None: + visible_devices_env_var = get_visible_devices_env_var() + if os.environ.get(visible_devices_env_var, None) != str(self.device): + raise AssertionError( + f"Expected {visible_devices_env_var}='{self.device}', " + f"but got '{os.environ.get(visible_devices_env_var, None)}'" + ) + if self.sleep: + time.sleep(self.sleep) + if self.exc: + raise self.exc + if self.crash: + sys.exit(1) + return self.result + + +class _TestEnvBenchmarkRequest: + """ + Supports unit testing subprocess environment propagation. + """ + + def __init__(self, key: str): + self.key = key + + def benchmark( + self, *input_tensors: torch.Tensor, out: torch.Tensor | None = None + ) -> str | None: + return os.environ.get(self.key) + + +@clear_on_fresh_cache +class _TestCodeCache: + @classmethod + def cache_clear(cls) -> None: + cls.write.cache_clear() + + @classmethod + @functools.lru_cache(None) + def write(cls, source_code: str) -> tuple[str, str]: + return write(source_code, "txt") + + +class _TestCodeCacheBenchmarkRequest: + """ + Supports unit testing subprocess codecache resets. + """ + + source_code = "test codecache contents\n" + + def benchmark( + self, *input_tensors: torch.Tensor, out: torch.Tensor | None = None + ) -> str: + _, input_path = _TestCodeCache.write(self.source_code) + return input_path + + +class GPUDeviceBenchmarkMixin: + def do_bench( + self, + fn, + *input_tensors: torch.Tensor, + out: torch.Tensor | None = None, + ) -> float: + device_idx_set = OrderedSet( + tensor.device.index + for tensor in [*input_tensors, out] + if isinstance(tensor, torch.Tensor) + and is_gpu(tensor.device.type) + and tensor.device.index is not None + ) + if not len(device_idx_set) <= 1: + raise AssertionError(f"Can not mix devices {device_idx_set}") + device_type = next( + ( + tensor.device.type + for tensor in input_tensors + if is_gpu(tensor.device.type) + ), + "cuda", + ) + device_interface = get_interface_for_device(device_type) + if len(device_idx_set) == 1: + device_idx = next(iter(device_idx_set)) + else: + device_idx = device_interface.current_device() + with device_interface.device(device_idx): # type: ignore[attr-defined] + res = benchmarker.benchmark(fn, device=device_type) + device_interface.synchronize() # shake out any CUDA errors + + return res + + +class CPUDeviceBenchmarkMixin: + def do_bench( + self, + fn, + *input_tensors: torch.Tensor, + out: torch.Tensor | None = None, + ) -> float: + return benchmarker.benchmark_cpu(fn) + + +class TritonBenchmarkRequest(BenchmarkRequest): + """ + Represents a standalone benchmark request for a Triton Template. + + Important: Instances of this class have to be serializable + across process boundaries. Do not put CUDA Tensors in here! + """ + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + extra_args: Iterable[Any], + module_path: str, # the path of the module defining the triton kernel + module_cache_key: str, + num_stages: int, + num_warps: int, + num_consumer_groups: int = 0, + num_buffers_warp_spec: int = 0, + matrix_instr_nonkdim: int = 0, # only used for hip to choose the shape of mfma instruction. + waves_per_eu: int = 0, # only used for hip to schedule waves per execution unit + kpack: int = 0, # ROCm specific gemm parameter + workspace_size: int | None = None, # size of workspace buffer in bytes + workspace_zero_fill: bool = False, # whether to zero-fill workspace + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + self.module_path = module_path + self.module_cache_key = module_cache_key + self.num_stages = num_stages + self.num_warps = num_warps + self.num_consumer_groups = num_consumer_groups + self.num_buffers_warp_spec = num_buffers_warp_spec + self.matrix_instr_nonkdim = matrix_instr_nonkdim + self.waves_per_eu = waves_per_eu + self.kpack = kpack + self.workspace_size = workspace_size + self.workspace_zero_fill = workspace_zero_fill + self._benchmark_module: Any | None = None + + @override + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + mod = PyCodeCache.load_by_key_path( + self.module_cache_key, + self.module_path, + set_sys_modules=False, + ) + self._benchmark_module = mod + autotuning_log.debug( + "benchmark module key: %s, path: %s", + self.module_cache_key, + self.module_path, + ) + + run_method = getattr(mod, self.kernel_name).run + extra_args = list(self.extra_args) + + # Recreate workspace tensor if needed (for TMA templates) + # The workspace tensor couldn't be pickled, so we recreate it here + # It should be inserted before the grid values (last 3 elements) + if self.workspace_size is not None: + from torch._inductor.select_algorithm import WORKSPACE_ARG_PLACEHOLDER + + workspace_tensor = torch.empty( + (self.workspace_size,), + dtype=torch.uint8, + device=out.device, + ) + if self.workspace_zero_fill: + workspace_tensor.zero_() + workspace_index = extra_args.index(WORKSPACE_ARG_PLACEHOLDER) + extra_args[workspace_index] = workspace_tensor + + run_method.__self__.with_bandwidth_info = False + + # Newer version of triton add warmup argument to JITFunction.run. + # This code handles backward-compatibility. + warmup_arg = {} + import inspect + + if "warmup" in inspect.signature(run_method).parameters: + warmup_arg["warmup"] = False + + if out.device.type == "cpu": + device_interface = None + device_index = 0 + else: + device_type = out.device.type + device_interface = get_interface_for_device(device_type) + device_index = self.output_tensor_meta.device.index + + is_debug_autotuner = isinstance( + getattr(mod, self.kernel_name), + torch._inductor.runtime.triton_heuristics.DebugAutotuner, + ) + + # Resolve the stream at call time (not at closure-creation time) so that + # CUDA graph capture on a different stream works correctly. + def run_fn() -> None: + stream = ( + 0 + if device_interface is None + else device_interface.get_raw_stream(device_index) + ) + if is_debug_autotuner: + run_method( + *input_tensors, + out, + *extra_args, + **warmup_arg, + stream=stream, + ) + else: + run_method( + *input_tensors, + out, + *extra_args, + **warmup_arg, + stream=stream, + benchmark_run=True, + ) + + return run_fn + + def cleanup_run_fn(self) -> None: + # Authoritative cleanup for one benchmark module load. Higher-level + # finally blocks may call this again as safety nets, so keep it idempotent. + mod = self._benchmark_module + self._benchmark_module = None + + cached_mod = PyCodeCache.modules_no_attr.pop(self.module_path, None) + if mod is None: + mod = cached_mod + + if mod is not None: + kernel = getattr(mod, self.kernel_name, None) + release_benchmark_artifacts = getattr( + kernel, "release_benchmark_artifacts", None + ) + if release_benchmark_artifacts is not None: + release_benchmark_artifacts() + release_static_launchers = getattr( + kernel, "_release_static_launchers_except", None + ) + if ( + release_benchmark_artifacts is None + and release_static_launchers is not None + ): + release_static_launchers(None) + elif release_benchmark_artifacts is None: + for launcher in getattr(kernel, "launchers", ()) or (): + close = getattr(getattr(launcher, "__self__", None), "close", None) + if close is not None: + close() + for compile_result in getattr(kernel, "compile_results", ()) or (): + close = getattr( + getattr(compile_result, "kernel", None), "close", None + ) + if close is not None: + close() + + PyCodeCache.modules[:] = [ + module + for module in PyCodeCache.modules + if getattr(module, "__file__", None) != self.module_path + ] + PyCodeCache.linemaps.pop(self.module_path, None) + + def precompile(self): + try: + mod = PyCodeCache.load_by_key_path( + self.module_cache_key, + self.module_path, + set_sys_modules=False, + ) + self._benchmark_module = mod + kernel = getattr(mod, self.kernel_name) + kernel.precompile() + + self.n_regs = kernel.launchers[0].n_regs + finally: + self.cleanup_run_fn() + + def __str__(self) -> str: + return f"{self.kernel_name=}, {self.module_path=}, {self.module_cache_key=}" + + +class TritonGPUBenchmarkRequest(GPUDeviceBenchmarkMixin, TritonBenchmarkRequest): + pass + + +class TritonCPUBenchmarkRequest(CPUDeviceBenchmarkMixin, TritonBenchmarkRequest): + pass + + +class ExternKernelBenchmarkRequest(BenchmarkRequest): + """ + A class to handle extern kernel benchmark requests. This allows extern kernels + (like aten::mm) to be benchmarked in a subprocess, similar to Triton kernels. + + Important: Instances of this class have to be serializable across + process boundaries. Do not put CUDA Tensors in here! + """ + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + extra_args: Iterable[Any], + callable_path: str, # Module path to the callable (e.g., "extern_kernels.mm") + kwargs: dict[str, Any] | None = None, + has_out_variant: bool = True, + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + self.callable_path = callable_path + self.kwargs = kwargs or {} + self.has_out_variant = has_out_variant + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + fn = self.to_callable() + if self.has_out_variant: + # For out=variant, pass output as keyword arg + return functools.partial(fn, *input_tensors, out=out) + else: + # For non-out variant, just call with inputs + return functools.partial(fn, *input_tensors) + + def benchmark(self, *input_tensors: torch.Tensor, out: torch.Tensor | None = None): + if out is not None and out.numel() == 0: + # no need to run the kernel or do benchmarking + return 0.0 + if self.has_out_variant or len(input_tensors) == 0: + return super().benchmark(*input_tensors, out=out) + else: + algo = self.to_callable() + out_new = algo(*input_tensors) + if out is not None: + torch._C._dynamo.guards.assert_size_stride( + out_new, tuple(out.size()), tuple(out.stride()) + ) + out.copy_(out_new) # for correctness checking + if self.benchmark_with_cudagraphs: + return benchmarker.benchmark_gpu_with_cuda_graph( + lambda: algo(*input_tensors) + ) + if config.profile_bandwidth_with_do_bench_using_profiling: + return do_bench_using_profiling(lambda: algo(*input_tensors)) + return benchmarker.benchmark(algo, input_tensors, {}) + + def precompile(self) -> None: + # Extern kernels don't need precompilation - they're already compiled + pass + + def to_callable(self): + # While ExternKernelChoice also has a to_callable method, + # we avoid calling the ExternKernelChoice version here to make sure + # this is picklable + from torch._inductor.select_algorithm import extern_kernels + + fn = getattr(extern_kernels, self.kernel_name) + if self.kwargs: + return functools.partial(fn, **self.kwargs) + + return fn + + def __str__(self) -> str: + return f"ExternKernelBenchmarkRequest({self.callable_path})" + + +class ExternKernelGPUBenchmarkRequest( + GPUDeviceBenchmarkMixin, ExternKernelBenchmarkRequest +): + pass + + +class ExternKernelCPUBenchmarkRequest( + CPUDeviceBenchmarkMixin, ExternKernelBenchmarkRequest +): + pass + + +class SubgraphBenchmarkRequest(BenchmarkRequest): + """ + Benchmark request for subgraph choices. + + Pre-compiles the subgraph in the main process and stores + the module path/cache key for loading in subprocess. + """ + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + extra_args: Iterable[Any], + module_path: str, + module_cache_key: str, + sym_input_values: list[int], + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + self.module_path = module_path + self.module_cache_key = module_cache_key + self.sym_input_values = sym_input_values + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + mod = PyCodeCache.load_by_key_path( + self.module_cache_key, + self.module_path, + set_sys_modules=False, + ) + sym_input_values = self.sym_input_values + # Create a new list each call since mod.call does args.clear() + return lambda: mod.call([*sym_input_values, *input_tensors]) + + def precompile(self) -> None: + # Module is already compiled in main process, no precompilation needed + pass + + def __str__(self) -> str: + return f"SubgraphBenchmarkRequest({self.kernel_name}, {self.module_path})" + + +class SubgraphGPUBenchmarkRequest(GPUDeviceBenchmarkMixin, SubgraphBenchmarkRequest): + pass + + +class SubgraphCPUBenchmarkRequest(CPUDeviceBenchmarkMixin, SubgraphBenchmarkRequest): + pass + + +class CUTLASSBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest): + """ + A class to handle CUDA (CUTLASS) benchmark requests. This class is for + managing the lifecycle of a CUDA kernel benchmark, including compiling + the source code, managing workspace memory, and executing the kernel. + + Important: Instances of this class have to be serializable across + process boundaries. Do not put CUDA Tensors in here! + """ + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + extra_args: Iterable[Any], + source_code: str, + device_type: str = "cuda", + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + self.source_code = source_code + self.workspace_size: int = 0 + self.workspace: torch.Tensor | None = None + self.DLL: DLLWrapper | None = None + self._workspace_size_updated = False + self.hash_key: str = "" + self.source_file: str = "" + self.device_type = device_type + self.codecache_cls = XPUCodeCache if device_type == "xpu" else CUDACodeCache + self.device_interface = get_interface_for_device(device_type) + self.hash_key, self.source_file = self.codecache_cls.write( + self.source_code, "so" + ) + + def precompile(self): + """ + Precompile the CUDA source code to populate the CUDACodeCache. + This may happen in a separate thread pool. + """ + autotuning_log.debug("Precompiling %s", self) + self.codecache_cls.compile(self.source_code, "so") + autotuning_log.debug("Done precompiling %s", self) + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + """ + Create a function to run the CUDA/XPU kernel with the given input and output tensors. + """ + + self.ensure_dll_loaded() + self.update_workspace_size() + args = [c_void_p(tensor.data_ptr()) for tensor in list(input_tensors) + [out]] + autotuning_log.debug( + "make_run_fn: self.kernel_name=%s, self.source_file=%s, self.hash_key=%s, self.DLL=%s, args=%s, self.extra_args=%s", + self.kernel_name, + self.source_file, + self.hash_key, + self.DLL, + args, + self.extra_args, + ) + stream_ptr = c_void_p( + self.device_interface.get_raw_stream(self.device_interface.current_device()) + ) + run_method = getattr(self.DLL, self.kernel_name) + workspace_ptr = c_void_p(0) + if self.workspace_size > 0: + self.workspace = torch.zeros( + (self.workspace_size + 7) // 8, + dtype=torch.float64, + device=out.device, + ) + workspace_ptr = c_void_p(self.workspace.data_ptr()) + + # Generate partial function. + ret = functools.partial( + run_method, + *args, + *self.extra_args, + None, # null workspace size ptr + workspace_ptr, # set workspace ptr, + stream_ptr, + ) + + # sanity check to make sure we cleanup run fn properly + try: + ret() + except RuntimeError as e: + err_msg = str(e) + + def raise_runtime_error(): + raise RuntimeError(err_msg) + + self.cleanup_run_fn() + return raise_runtime_error + + return ret + + def update_workspace_size(self) -> None: + if self._workspace_size_updated: + return + self.ensure_dll_loaded() + unique_input_count = len( + dict.fromkeys(meta.name for meta in self.input_tensor_meta) + ) + args = [c_void_p(None) for _ in range(unique_input_count + 1)] + stream_ptr = c_void_p( + self.device_interface.get_raw_stream(self.device_interface.current_device()) + ) + + run_method = getattr(self.DLL, self.kernel_name) + # Retrieve workspace_size and initialize workspace. + c_workspace_size = c_size_t() + run_method( + *args, # input ptrs and output ptrs + *self.extra_args, + byref( + c_workspace_size + ), # set workspace size ptr to retrieve workspace size + None, # null workspace ptr + stream_ptr, + ) + self.device_interface.synchronize() # shake out any device errors + self.workspace_size = c_workspace_size.value + autotuning_log.debug( + "update_workspace_size called: new workspace size=%d, self.kernel_name=%s, self.source_file=%s, self.hash_key=%s, self.DLL=%s, args=%s, self.extra_args=%s", + self.workspace_size, + self.kernel_name, + self.source_file, + self.hash_key, + self.DLL, + args, + self.extra_args, + ) + self._workspace_size_updated = True + + def ensure_dll_loaded(self): + if self.DLL is None: + self.DLL, self.hash_key, self.source_file = self.codecache_cls.load( + self.source_code, "so" + ) + self.DLL.open() + + def cleanup_run_fn(self) -> None: + if self.DLL is not None: + self.DLL.close() + self.DLL = None + self.workspace = None + + def __str__(self) -> str: + return f"{self.kernel_name=}, {self.source_file=}, {self.hash_key=}" + + def __getstate__(self) -> dict[str, Any]: + state = self.__dict__.copy() + state["DLL"] = None + state["workspace"] = None + state["_workspace_size_updated"] = False + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__.update(state) + + +class CppBenchmarkRequest(CPUDeviceBenchmarkMixin, BenchmarkRequest): + # Important: Instances of this class have to be serializable + # across process boundaries. Do not put Tensors in here! + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + extra_args: Iterable[Any], + source_code: str, + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + self.source_code = source_code + self.hash_key = get_hash(source_code) + self.DLL: CDLL | ModuleType | None = None + + def precompile(self): + # Prepopulate CppCodeCache + # may happen in separate Threadpool + autotuning_log.debug("Precompiling %s", self) + CppCodeCache.load(self.source_code, device_type="cpu") + autotuning_log.debug("Done precompiling %s", self) + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + # TODO(jgong5): use CppPythonBindingsCodeCache for better binding perf + self.DLL = CppCodeCache.load(self.source_code, device_type="cpu") + args = [tensor.data_ptr() for tensor in list(input_tensors) + [out]] + autotuning_log.debug( + "make_run_fn: self.kernel_name=%s, self.DLL=%s, args=%s, self.extra_args=%s", + self.kernel_name, + self.DLL, + args, + self.extra_args, + ) + run_method = getattr(self.DLL, self.kernel_name) + # Assume only size with type ctypes.c_ulonglong in extra_args + if not all(isinstance(arg, ctypes.c_ulonglong) for arg in self.extra_args): + raise AssertionError( + f"Expected all extra_args to be ctypes.c_ulonglong, got types: " + f"{[type(arg) for arg in self.extra_args if not isinstance(arg, ctypes.c_ulonglong)]}" + ) + run_method.argtypes = [ctypes.c_ulonglong] * ( + len(args) + len(list(self.extra_args)) + ) + + # Generate partial function. + return functools.partial( + run_method, + *args, + *self.extra_args, + ) + + def __str__(self) -> str: + return f"{self.kernel_name=}" + + +class CuteDSLBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest): + """Benchmark request for CuteDSL (CUTLASS Python DSL) kernels.""" + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + extra_args: tuple[Any, ...], + source_code: PartialRender, + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + + # Template-specific precompile hooks reuse the finalized module source in subprocesses. + self.source_code = source_code.finalize_all() + self.module_cache_key, self.module_path = PyCodeCache.write(self.source_code) + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + """ + Create a function to run the CuteDSL kernel with the given input and output tensors. + Similar to TritonBenchmarkRequest.make_run_fn but for CuteDSL kernels. + """ + mod = PyCodeCache.load_by_key_path( + self.module_cache_key, + self.module_path, + set_sys_modules=False, + ) + + # Logic replicated async_compile + from .codegen.cutedsl.cutedsl_kernel import MAIN_SUFFIX + + main_func_name = f"{self.kernel_name}_{MAIN_SUFFIX}" + + if not hasattr(mod, main_func_name): + available = [name for name in dir(mod) if callable(getattr(mod, name))] + raise RuntimeError( + f"Could not find CuteDSL main kernel function '{main_func_name}'. Available callables: {available}" + ) + + kernel_func = getattr(mod, main_func_name) + + def run_kernel(): + device_interface = get_interface_for_device("cuda") + stream = device_interface.get_raw_stream(out.device.index) + return kernel_func(*input_tensors, out, *self.extra_args, stream=stream) + + return run_kernel + + +@functools.cache +def get_tuning_process_pool() -> TuningProcessPool: + pool = TuningProcessPool() + atexit.register(pool.shutdown) + return pool + + +def benchmark_in_sub_process( + choices: list[TritonTemplateCaller], +) -> dict[TritonTemplateCaller, float]: + """ + Do benchmarking in a subprocess and return the perf number (latency). + """ + return get_tuning_process_pool().benchmark(choices) + + +class AutotuneProcessPool: + """ + Singleton pool manager for running autotuning (precompilation + benchmarking) + in a separate process. + """ + + _instance: AutotuneProcessPool | None = None + _lock: threading.Lock = threading.Lock() + _shutdown_for_inactivity: bool = False + + def __init__(self): + self._pool: ProcessPoolExecutor | None = self._init_pool() + self._warmup_future: Future[Any] | None = None + self._warmup_start_time: float | None = None + self._timer: Timer | None = self._init_timer() + + @classmethod + def get_instance(cls): + """Get or create the singleton pool instance.""" + if cls._instance is None: + with cls._lock: + if cls._instance is None: + # num_workers=1 to avoid GPU contention during benchmarking + cls._instance = cls() + return cls._instance + + @property + def pool(self): + """Get the process pool.""" + if not config.pipeline_max_autotune_gemm: + raise AssertionError( + "To use AutotuneProcessPool, pipeline_max_autotune_gemm must be enabled" + ) + if self._pool is None: + self._pool = self._init_pool() + self._timer = self._init_timer() + return self._pool + + def _init_timer(self) -> Timer | None: + if AUTOTUNE_POOL_INACTIVITY_TIMEOUT > 0: + return Timer(AUTOTUNE_POOL_INACTIVITY_TIMEOUT, self._on_inactivity_timeout) + return None + + def _record_activity(self) -> None: + if self._timer is not None: + self._timer.record_call() + + def _on_inactivity_timeout(self) -> None: + autotuning_log.info( + "AutotuneProcessPool shutting down due to inactivity (timeout=%ds)", + AUTOTUNE_POOL_INACTIVITY_TIMEOUT, + ) + + with self._lock: + if self._pool is not None: + self._pool.shutdown(wait=False) + self._pool = None + self._timer = None + + # Mark that the pool was shut down for inactivity. + # This prevents the pool from being recreated on recompiles + # which likely do not require large amounts of autotuning. + AutotuneProcessPool._shutdown_for_inactivity = True + + def _init_pool(self): + """ + Get or create the process pool. + + Uses ProcessPoolExecutor with 'spawn' context for CUDA safety. + ProcessPoolExecutor is lazily initialized - workers are not spawned + until the first submit() call, making this property non-blocking. + """ + # Use 'spawn' context to avoid CUDA fork issues + # Workers are spawned lazily on first submit(), not here + ctx = mp.get_context("spawn") + pool = ProcessPoolExecutor( + max_workers=1, + mp_context=ctx, + ) + atexit.register(self._shutdown) + autotuning_log.info("AutotuneProcessPool created (workers spawn lazily)") + + return pool + + def warm_up(self) -> Future[Any]: + """ + Submit a warmup job to eagerly spawn workers and initialize CUDA. + + This is optional - call it early to hide spawn latency. + Returns the warmup future which can be ignored or awaited. + """ + if self._warmup_future is None: + with self._lock: + if self._warmup_future is None: + self._warmup_start_time = time.perf_counter() + self._warmup_future = self.submit( + _init_autotune_subprocess, + fp32_precision=torch.backends.cuda.matmul.fp32_precision, + ) + self._warmup_future.add_done_callback(self._on_warmup_complete) + autotuning_log.info("Warmup job submitted") + # pyrefly: ignore[bad-return] + return self._warmup_future + + def _on_warmup_complete(self, future: Future[Any]) -> None: + """Callback invoked when the warmup job completes.""" + warmup_elapsed_time = None + if self._warmup_start_time is not None: + warmup_elapsed_time = time.perf_counter() - self._warmup_start_time + + try: + result = future.result() + autotuning_log.info( + "AutotuneProcessPool warmup completed successfully in %.4f seconds: %s", + warmup_elapsed_time, + result, + ) + self._record_activity() + except Exception as e: + autotuning_log.error( + "AutotuneProcessPool warmup failed after %.4f seconds", + warmup_elapsed_time, + ) + raise e + + def submit(self, fn, *args, **kwargs) -> Future[Any]: + """Submit a job to the pool and return a Future.""" + future = self.pool.submit( + _run_with_subprocess_env, + fn, + _cache_env_for_subprocess(), + *args, + **kwargs, + ) + if self._timer is not None: + future.add_done_callback(lambda _: self._record_activity()) + return future + + def _shutdown(self): + """Shutdown the pool on exit.""" + if self._timer is not None: + self._timer.quit() + self._timer = None + if self._pool is not None: + self._pool.shutdown(wait=False) + self._pool = None + + @classmethod + def shutdown_instance(cls): + """Explicitly shutdown the singleton instance.""" + if cls._instance is not None: + with cls._lock: + if cls._instance is not None: + cls._instance._shutdown() + cls._instance = None + + +def use_pipelined_autotuning() -> bool: + return ( + config.pipeline_max_autotune_gemm + and not AutotuneProcessPool._shutdown_for_inactivity + ) + + +def _init_autotune_subprocess(fp32_precision: str) -> bool: + """ + Warmup function run in the autotune subprocess. + """ + import torch + + # Initialize dummy tensor for CUDA context + if torch.cuda.is_available(): + torch.zeros(1, device="cuda") + + torch.backends.cuda.matmul.fp32_precision = fp32_precision + + return True + + +def run_autotune_in_subprocess( + benchmark_request: BenchmarkRequest, +) -> float: + """ + Run autotuning benchmarks in a subprocess. + + This function is submitted to AutotuneProcessPool and runs in isolation + to prevent GPU contention with the main compilation process. + + Args: + picklable_choices: List of picklable choice information + + Returns: + timing + """ + + try: + # Run the benchmark directly - bmreq is already a BenchmarkRequest + timing = benchmark_request.benchmark() + + return timing + + except Exception: + autotuning_log.warning( + "Failed to benchmark choice %s", + benchmark_request, + exc_info=True, + ) + # Use infinity for failed benchmarks so they're not selected + return float("inf") + + +class PrecompileThreadPool: + """ + Thread pool for running precompilation asynchronously. + + This allows the main compilation process to continue while + precompilation happens in background threads. + """ + + _instance: PrecompileThreadPool | None = None + _lock = threading.Lock() + + def __init__(self, max_workers: int = 4): + self._executor = ThreadPoolExecutor(max_workers=max_workers) + + @classmethod + def get_instance(cls) -> PrecompileThreadPool: + from torch._inductor.select_algorithm import get_num_workers + + if cls._instance is None: + with cls._lock: + if cls._instance is None: + cls._instance = cls(get_num_workers()) + return cls._instance + + def submit(self, fn, *args, **kwargs): + ctx = contextvars.copy_context() + # Need to copy context so workers have access to the correct config settings + fn = functools.partial(ctx.run, fn) + return self._executor.submit(fn, *args, **kwargs) + + def _shutdown(self, wait: bool = False): + return self._executor.shutdown(wait=wait) + + @classmethod + def shutdown_instance(cls) -> None: + if cls._instance is not None: + with cls._lock: + if cls._instance is not None: + cls._instance._shutdown(wait=False) + cls._instance = None + + +class AsyncAutotuner: + """ + Handles asynchronous autotuning of kernel choices in a separate process. + + This class manages the lifecycle of autotuning: + 1. Accepts precompiled choices from the main process + 2. Submits benchmarking work to AutotuneProcessPool + 3. Returns results via a Future + + Usage: + autotuner = AsyncAutotuner(choices) + autotuner.start() # Kicks off async benchmarking + timings = autotuner.get_results() # Blocks until complete + """ + + choice_hash_to_future = {} + + @staticmethod + def get_choice_hash(choice: ChoiceCaller, inputs_key: str) -> str: + return choice.hash_key() + inputs_key + + @classmethod + def start(cls, choices: list[ChoiceCaller], inputs_key: str): + """ + Start asynchronous autotuning in a subprocess. + + This method: + 1. Extracts picklable benchmark requests from choices + 2. Submits benchmarking work to AutotuneProcessPool + 3. Returns immediately (non-blocking) + """ + + for choice in choices: + choice_hash = AsyncAutotuner.get_choice_hash(choice, inputs_key) + + if choice_hash in AsyncAutotuner.choice_hash_to_future: + continue + + if not getattr(choice, "bmreq", None) is not None: + raise AssertionError("bmreq is None for choice") + + autotune_future = AutotuneProcessPool.get_instance().submit( + run_autotune_in_subprocess, + choice.bmreq, + ) + + AsyncAutotuner.choice_hash_to_future[choice_hash] = autotune_future + + @classmethod + def get_results( + cls, choices: list[ChoiceCaller], inputs_key: str + ) -> dict[ChoiceCaller, float]: + """ + Get autotuning results, blocking until complete. + + Args: + timeout: Maximum time to wait in seconds. None means wait forever. + + Returns: + Dict mapping ChoiceCaller to benchmark timing + """ + + timings = {} + for choice in choices: + choice_hash = AsyncAutotuner.get_choice_hash(choice, inputs_key) + timings[choice] = AsyncAutotuner.choice_hash_to_future[choice_hash].result() + return timings diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autows_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autows_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7b5fec2ee801e5034347194feeaea675a7e5c419 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autows_utils.py @@ -0,0 +1,24 @@ +"""Utils for Meta Triton autoWS.""" + +from __future__ import annotations + +import functools + + +@functools.cache +def has_meta_ws() -> bool: + """Whether Meta Triton autoWS is available.""" + try: + from triton import knobs + except ImportError: + return False + return hasattr(getattr(knobs, "nvidia", None), "use_meta_ws") + + +def meta_ws_enabled() -> bool: + """Whether Meta Triton autoWS is available and enabled via its knob.""" + if not has_meta_ws(): + return False + from triton import knobs + + return bool(knobs.nvidia.use_meta_ws) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/await_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/await_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fcb4549066eddb64b80947179bbf4016cbfa483a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/await_utils.py @@ -0,0 +1,178 @@ +import asyncio +import sys +import weakref +from asyncio import AbstractEventLoop, Future +from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterator +from contextlib import contextmanager, ExitStack +from contextvars import Context +from typing import Any, Protocol, TypeVar + +from torch.utils._ordered_set import OrderedSet + + +T = TypeVar("T") +TCoro = Generator[Any, None, T] + +if sys.version_info >= (3, 11): + + class TaskFactory(Protocol): + def __call__( + self, + __loop: AbstractEventLoop, + __factory: Coroutine[None, None, object] | Generator[None, None, object], + __context: Context | None = None, + /, + ) -> asyncio.futures.Future[object]: ... + + TaskFactoryType = TaskFactory +else: + TaskFactoryType = Callable[[AbstractEventLoop, Generator[TCoro, None, T]], Future] # type: ignore[valid-type] + + +def await_sync(awaitable: Awaitable[T]) -> T: + with get_loop() as loop: + return loop.run_until_complete(awaitable) + + +@contextmanager +def get_loop( + always_create_new_loop: bool = False, +) -> Iterator[AbstractEventLoop]: + try: + loop = asyncio.get_event_loop() + except RuntimeError as re: + if "There is no current event loop in thread" in str(re): + with _new_loop() as loop: + yield loop + return + else: + raise + + @contextmanager + def _restore_loop( + loop: asyncio.AbstractEventLoop, + ) -> Iterator[None]: + try: + yield + finally: + asyncio.set_event_loop(loop) + + @contextmanager + def _restore_running_loop() -> Iterator[None]: + loop_from_events = asyncio.events._get_running_loop() + asyncio.events._set_running_loop(None) + try: + yield + finally: + asyncio.events._set_running_loop(loop_from_events) + + with ExitStack() as stack: + if loop.is_running(): + stack.enter_context(_restore_running_loop()) + stack.enter_context(_restore_loop(loop=loop)) + loop = stack.enter_context(_new_loop(loop.get_task_factory())) # type: ignore[arg-type] + elif loop.is_closed(): + loop = stack.enter_context(_new_loop()) # type: ignore[arg-type] + elif always_create_new_loop: + stack.enter_context(_restore_loop(loop=loop)) + loop = stack.enter_context(_new_loop()) # type: ignore[arg-type] + yield loop + + +@contextmanager +def _new_loop( + task_factory: TaskFactoryType | None = None, +) -> Iterator[asyncio.AbstractEventLoop]: + loop = asyncio.new_event_loop() + tasks = _patch_loop(loop) + + if task_factory: + # pyre-ignore[6] + loop.set_task_factory(task_factory) # type: ignore[arg-type] + + asyncio.set_event_loop(loop) + try: + yield loop + finally: + try: + _cancel_all_tasks(loop, tasks) + finally: + asyncio.set_event_loop(None) + loop.close() + + +def _cancel_all_tasks( + loop: AbstractEventLoop, + tasks: OrderedSet[Future], # type: ignore[type-arg] +) -> None: + to_cancel = [task for task in tasks if not task.done()] + + if not to_cancel: + return + + # pyre-fixme[1001]: Awaitable assigned to `task` is never awaited. + for task in to_cancel: + task.cancel() + + # pyrefly: ignore [bad-argument-type] + loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True)) + + for task in to_cancel: + if task.cancelled(): + continue + if task.exception() is not None: + loop.call_exception_handler( + { + "message": "unhandled exception during asyncio.run() shutdown", + "exception": task.exception(), + "task": task, + } + ) + + +def _patch_loop(loop: AbstractEventLoop) -> OrderedSet[Future]: # type: ignore[type-arg] + tasks: weakref.WeakSet[Future] = weakref.WeakSet() # type: ignore[type-arg] + + task_factories: list[TaskFactoryType | None] = [None] + + def _set_task_factory(factory: TaskFactoryType | None) -> None: + task_factories[0] = factory + + def _get_task_factory() -> TaskFactoryType | None: + return task_factories[0] + + def _safe_task_factory( + loop: AbstractEventLoop, + coro: TCoro, # type: ignore[type-arg] + *, + context: Context | None = None, + ) -> asyncio.Future: # type: ignore[valid-type, type-arg] + task_factory = task_factories[0] + if task_factory is None: + if sys.version_info >= (3, 11): + # pyrefly: ignore [bad-argument-type] + task = asyncio.Task(coro, loop=loop, context=context) + else: + task = asyncio.Task(coro, loop=loop) + # pyre-ignore[16]: `Task` has no attribute `_source_traceback`. + if task._source_traceback: # type: ignore[attr-defined] + del task._source_traceback[ # type: ignore[attr-defined] + -1 + ] # pragma: no cover # type: ignore[attr-defined] + else: + if sys.version_info >= (3, 11): + task = task_factory(loop, coro, context=context) # type: ignore[arg-type, call-arg, assignment] + else: + task = task_factory(loop, coro) # type: ignore[arg-type] + # `Union[Task[Any], Future[Any]]`. + tasks.add(task) + return task + + # pyre-ignore[6] + loop.set_task_factory(_safe_task_factory) # type: ignore[method-assign, arg-type] + # pyre-ignore[8] + loop.set_task_factory = _set_task_factory # type: ignore[method-assign, assignment] + # pyre-ignore[8] + loop.get_task_factory = _get_task_factory # type: ignore[method-assign, assignment] + + return tasks # type: ignore[return-value] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/bounds.py b/.venv/lib/python3.12/site-packages/torch/_inductor/bounds.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c7e36d2c422ec5f3630b6b0f056934bd0c5010 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/bounds.py @@ -0,0 +1,273 @@ +import logging +import operator +from collections.abc import Callable +from functools import partial +from typing import Any + +import sympy +from sympy import Expr + +import torch +from torch.utils._sympy.value_ranges import ( + bound_sympy, + SymPyValueRangeAnalysis, + ValueRanges, +) + +from ..utils._sympy.functions import PowByNatural +from ..utils._sympy.numbers import int_oo +from .loop_body import InterpreterShim, LoopBody, LoopBodyBlock +from .ops_handler import DefaultHandler, ReductionType, StoreMode +from .utils import cache_on_self, dominated_nodes +from .virtualized import V + + +log = logging.getLogger(__name__) + + +class BoundVars: + """ + Performs Value Range Analysis on LoopBody's fx graph by calling BoundVars.run() + It exposes the ranges of the nodes in the `bounds` variable + + Note. A current limitation of this analysis is that it just works on a per-loop basis. + We should be able to propagate the bounds between across the whole graph. This may benefit + the case a bounded variable is returned by a kernel and fed into another. + """ + + def __init__(self, loop_body: LoopBody) -> None: + def upper_bound(v: Expr | int) -> int: + return bound_sympy(v).upper if isinstance(v, Expr) else v + + self.loop_body = loop_body + self.replacement_vals = { + k: ValueRanges[Expr](0, upper_bound(v) - 1) + for k, v in loop_body.var_ranges.items() + } + # avoid computing these values, pessimistically assume that they are unbounded + self.unbounded_vars = dominated_nodes( + node + for node in self.loop_body.get_nodes() + if node.target in ["load", "reduction", operator.getitem] + or "masked_subblock" in node.target + ) + # To access this variable call `get_bounds()` + self._bounds: dict[torch.fx.Node, ValueRanges[Expr]] = {} + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(" + f"loop_body={self.loop_body},\n " + f"replacement_vals={self.replacement_vals}, \n" + f"unbounded_vars={self.unbounded_vars}, \n" + f"_bounds={self._bounds})" + ) + + @cache_on_self + def get_bounds(self) -> dict[torch.fx.Node, ValueRanges[Expr]]: + submodules = self.swap_submodules(self.loop_body.submodules) + + # Initialize the environment with the unbounded variables + for node in self.unbounded_vars: + # we need to evaluate masked_subblock to recurse, and we need to set indirect values + if not isinstance(node.target, str) or ( + "masked_subblock" not in node.target + and "set_indirect" not in node.target + ): + self._bounds[node] = ValueRanges[Expr].unknown() + + with V.set_ops_handler(ValueRangeAnalysis()): + interpreter = InterpreterShim(self.loop_body.root_block.graph, submodules) + log.debug("get_bounds:\n%s", self.loop_body.root_block.graph) + interpreter.run(V.get_ops_handler(), initial_env=self._bounds) + return self._bounds + + def swap_submodules( + self, submodules: dict[str, Callable[..., Any]] + ) -> dict[str, Callable[..., ValueRanges[Expr]]]: + result: dict[str, Callable[..., ValueRanges[Expr]]] = {} + for key in submodules: + if key == "get_index": + result[key] = self.get_index + elif "masked_subblock" in key: + subblock = self.loop_body.subblocks[key] + # The result within the lambda will reference to the final + # set of modules at the end of the for-loop as it stores a reference to it + + # bind subblock in a function because python lambdas close over by reference + # moving the lambda out of make_fn would close over the reference to subblock, + # so all lambdas would have the same subblock reference that is the final + # subblock in the loop + def make_fn( + subblock: LoopBodyBlock, + ) -> Callable[[Any, Any], ValueRanges[Expr]]: + return lambda mask, value: self.masked_subblock( + subblock, self._bounds, mask, value, result + ) + + result[key] = make_fn(subblock) + elif "set_indirect" in key: + idx = int(key[len("set_indirect") :]) + var = self.loop_body.indirect_vars[idx] + indirect = partial(self.set_indirect, var) + result[key] = indirect + else: + if "scan" not in key: + raise AssertionError( + f"expected 'scan' in submodule key, got {key!r}" + ) + result[key] = submodules[key] + + return result + + def masked_subblock( + self, + subblock: LoopBodyBlock, + env: dict[torch.fx.Node, ValueRanges[Expr]], + mask: Any, + value: Any, + submodules: dict[str, Callable[..., Any]], + ) -> ValueRanges[Expr]: + interp = InterpreterShim(subblock.graph, submodules) + interp.run(V.get_ops_handler(), initial_env=env) + output = [node for node in subblock.graph.nodes if node.target == "output"] + if len(output) != 1: + raise AssertionError(f"expected exactly 1 output node, got {len(output)}") + # don't bother unioning with value since the load from buffer will be + # pessimistically assumed to be inf anyway + return interp.env[output[0]] + + def set_indirect(self, old: Expr, new: ValueRanges[Expr]) -> ValueRanges[Expr]: + if not isinstance(new, ValueRanges): + raise AssertionError(f"expected ValueRanges, got {type(new)}") + self.replacement_vals[old] = new + return new + + def get_index(self, name: str) -> ValueRanges[Expr]: + expr = self.loop_body.indexing_exprs[name] + bound = self.replacement_vals.get(expr) + if bound is None: + bound = bound_sympy(expr, self.replacement_vals) + # The following assertion is true at the time of this writing + # We don't assert is as to not execute bound_sympy when bound is not None + # assert bound is None or bound == bound_sympy(expr, self.replacement_vals) + self.replacement_vals[name] = bound + return bound + + +class ValueRangeAnalysis(SymPyValueRangeAnalysis, DefaultHandler): + def __init__(self) -> None: + self.name = "ValueRangeAnalysis" + boolean_operators = ( + "xor", + "logical_and", + "logical_or", + "logical_not", + ) + for op in boolean_operators: + setattr(self, op, self.bool_handler) + + @staticmethod + def bool_handler(*args: Any, **kwargs: Any) -> ValueRanges[Any]: + # just assuming bools can have both values + return ValueRanges(sympy.false, sympy.true) # type: ignore[arg-type] + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + # many ops are unlikely to show up in optimizable indexing compute, + # so we don't have full coverage + return ValueRanges.unknown() + + def load(self, name: str, index: sympy.Expr) -> ValueRanges[Any]: + return ValueRanges.unknown() + + def store( + self, name: str, index: sympy.Expr, value: Any, mode: StoreMode = None + ) -> None: + return + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: Any, + ) -> ValueRanges[Any]: + return ValueRanges.unknown() + + @classmethod + def index_expr(cls, index: Any, dtype: torch.dtype) -> ValueRanges[Any]: + if not isinstance(index, ValueRanges): + raise AssertionError(f"expected ValueRanges, got {type(index)}") + return cls.to_dtype(index, dtype) + + @classmethod + def value_expr(cls, index: Any, dtype: torch.dtype) -> ValueRanges[Any]: + return cls.index_expr(index, dtype) + + @staticmethod + # pyrefly: ignore [bad-override] + def to_dtype( + x: Any, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = True, + ) -> ValueRanges[Any]: + x = ValueRanges.wrap(x) + + if dtype == torch.bool: + if x.is_singleton(): + return ValueRanges.wrap(x.lower != 0) + elif x.is_bool: + return x + elif 0 not in x: + return ValueRanges.wrap(sympy.true) + else: + return ValueRanges(sympy.false, sympy.true) + + def cast(x: Any, dtype: torch.dtype) -> sympy.Expr: + # dtype is int or float + if dtype.is_floating_point: + return sympy.Float(x) + else: + if x in (int_oo, -int_oo): + return x + try: + return sympy.Integer(x) + except TypeError: + # inf cannot be cast to Integer + return x + + if x.is_bool: + if x.is_singleton(): + val = 1 if x.lower else 0 + return ValueRanges.wrap(cast(val, dtype)) + else: + return ValueRanges(cast(0, dtype), cast(1, dtype)) + else: + # int to float or float to int + return ValueRanges(cast(x.lower, dtype), cast(x.upper, dtype)) + + @staticmethod + # pyrefly: ignore [bad-override] + def square(x: Any) -> ValueRanges[Any]: + return ValueRanges.convex_min_zero_map(x, lambda y: PowByNatural(y, 2)) + + @staticmethod + # pyrefly: ignore [bad-override] + def neg(x: Any) -> ValueRanges[Any]: + return ValueRanges.decreasing_map(x, operator.neg) + + # TODO: this is slightly inaccurate because truncdiv operates at integer + # precision, but we're going through float truediv which means we can + # potentially lose precision on the bounds + @classmethod + def truncdiv(cls, a: Any, b: Any) -> ValueRanges[Any]: + x = cls.truediv(a, b) + if x == ValueRanges.unknown(): + return x + + return cls.trunc(x) + + @classmethod + def sub(cls, a: Any, b: Any) -> ValueRanges[Any]: + return cls.add(a, cls.neg(b)) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..118bbf2828799d8fd63a96427b5e88573d6adf19 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/cache.py @@ -0,0 +1,419 @@ +from __future__ import annotations + +import pickle +from abc import ABC, abstractmethod +from ast import literal_eval +from functools import cached_property +from hashlib import sha256 +from os import getenv +from pathlib import Path +from tempfile import gettempdir +from threading import Lock +from typing import Any, Generic, TYPE_CHECKING, TypeVar +from typing_extensions import assert_never, override, Self + +from torch.utils._filelock import FileLock + + +if TYPE_CHECKING: + from concurrent.futures import Future, ThreadPoolExecutor + + +# TypeVars can't be recursive, so generic types that fall within +# Key or Value can't be bound properly; for example, Key should +# only take tuples of other Key types: tuple[Key, ...]. this is +# a known shortcoming of torch's typing +Key = TypeVar("Key", str, int, tuple[Any, ...]) +Value = TypeVar("Value", str, int, tuple[Any, ...], bytes, dict[Any, Any], list[Any]) + + +class CacheError(ValueError): + """ + Exception raised for errors encountered during cache operations. + """ + + +class Cache(ABC, Generic[Key, Value]): + """ + Abstract base class for cache implementations. + Provides the interface for cache operations. + """ + + @abstractmethod + def get(self: Self, key: Key) -> Value | None: + """ + Retrieve a value from the cache. + Args: + key (Key): The key to look up. + Returns: + Value | None: The cached value if present, else None. + """ + + @abstractmethod + def insert(self: Self, key: Key, value: Value) -> bool: + """ + Insert a value into the cache. + Args: + key (Key): The key to insert. + value (Value): The value to associate with the key. + Returns: + bool: True if the value was inserted, False if the key already exists. + """ + + +class InMemoryCache(Cache[Key, Value]): + """ + In-memory cache implementation using a dictionary and thread lock. + """ + + def __init__(self: Self) -> None: + """ + Initialize an empty in-memory cache. + """ + self._cache: dict[Key, Value] = {} + self._lock: Lock = Lock() + + def get(self: Self, key: Key) -> Value | None: + """ + Retrieve a value from the cache. + Args: + key (Key): The key to look up. + Returns: + Value | None: The cached value if present, else None. + """ + with self._lock: + if (value := self._cache.get(key)) is not None: + return value + return None + + def insert(self: Self, key: Key, value: Value) -> bool: + """ + Insert a value into the cache. + Args: + key (Key): The key to insert. + value (Value): The value to associate with the key. + Returns: + bool: True if the value was inserted, False if the key already exists. + """ + with self._lock: + if key in self._cache: + # no overwrites for insert! + return False + self._cache[key] = value + return True + + @classmethod + def from_env_var(cls, env_var: str) -> Self: + """ + Create an in-memory cache from an environment variable. + Args: + env_var (str): Name of the environment variable containing cache data. + Returns: + InMemoryCache: An instance populated from the environment variable. + Raises: + CacheError: If the environment variable is malformed or contains invalid data. + """ + cache = cls() + + if (env_val := getenv(env_var)) is None: + # env_var doesn't exist = empty cache + return cache + + for kv_pair in env_val.split(";"): + # ignore whitespace prefix/suffix + kv_pair = kv_pair.strip() + + if not kv_pair: + # kv_pair could be '' if env_val is '' or has ; suffix + continue + + try: + # keys and values should be comma separated + key_bytes_repr, value_bytes_repr = kv_pair.split(",", 1) + except ValueError as err: + raise CacheError( + f"Malformed kv_pair {kv_pair!r} from env_var {env_var!r}, likely missing comma separator." + ) from err + + # ignore whitespace prefix/suffix, again + key_bytes_repr, value_bytes_repr = ( + key_bytes_repr.strip(), + value_bytes_repr.strip(), + ) + + try: + # check that key_bytes_str is an actual, legitimate encoding + key_bytes = literal_eval(key_bytes_repr) + except (ValueError, SyntaxError) as err: + raise CacheError( + f"Malformed key_bytes_repr {key_bytes_repr!r} in kv_pair {kv_pair!r}, encoding is invalid." + ) from err + try: + # check that value_bytes_str is an actual, legitimate encoding + value_bytes = literal_eval(value_bytes_repr) + except (ValueError, SyntaxError) as err: + raise CacheError( + f"Malformed value_bytes_repr {value_bytes_repr!r} in kv_pair {kv_pair!r}, encoding is invalid." + ) from err + + try: + key = pickle.loads(key_bytes) + except pickle.UnpicklingError as err: + raise CacheError( + f"Malformed key_bytes_repr {key_bytes_repr!r} in kv_pair {kv_pair!r}, not un-pickle-able." + ) from err + try: + value = pickle.loads(value_bytes) + except pickle.UnpicklingError as err: + raise CacheError( + f"Malformed value_bytes_repr {value_bytes_repr!r} in kv_pair {kv_pair!r}, not un-pickle-able." + ) from err + + # true duplicates, i.e. multiple occurrences of the same key => value + # mapping are ok and treated as a no-op; key duplicates with differing + # values, i.e. key => value_1 and key => value_2 where value_1 != value_2, + # are not okay since we don't allow overwriting cached values (it's bad regardless) + if (not cache.insert(key, value)) and (cache.get(key) != value): + raise CacheError( + f"Multiple values for key {key!r} found, got {cache.get(key)!r} and {value!r}." + ) + + return cache + + @classmethod + def from_file_path(cls, fpath: Path) -> Self: + """ + Create an in-memory cache from a file path. + Args: + fpath (Path): Path to the file containing pickled cache data. + Returns: + InMemoryCache: An instance populated from the file. + Raises: + CacheError: If the file is not a valid pickled dictionary. + """ + cache = cls() + + if not fpath.is_file(): + # fpath doesn't exit = empty cache + return cache + + try: + with open(fpath, "rb") as fp: + cache._cache = pickle.load(fp) + except pickle.UnpicklingError as err: + raise CacheError( + f"Failed to create cache from file path {fpath}, file contents are un-pickle-able." + ) from err + + if not isinstance(cache._cache, dict): + raise CacheError( + f"Failed to create cache from file path {fpath}, file contents not pickled dict[Key, Value]." + ) + + return cache + + +class AsyncCache(Cache[Key, Value]): + """ + Asynchronous cache implementation using ThreadPoolExecutor. + """ + + def get_async( + self: Self, key: Key, executor: ThreadPoolExecutor + ) -> Future[Value | None]: + """ + Retrieve a value from the cache asynchronously. + Args: + key (Key): The key to look up. + executor (ThreadPoolExecutor): Executor for async execution. + Returns: + Future[Value | None]: Future for the cached value or None. + """ + return executor.submit(self.get, key) + + def insert_async( + self: Self, key: Key, value: Value, executor: ThreadPoolExecutor + ) -> Future[bool]: + """ + Insert a value into the cache asynchronously. + Args: + key (Key): The key to insert. + value (Value): The value to associate with the key. + executor (ThreadPoolExecutor): Executor for async execution. + Returns: + Future[bool]: Future for the result of insertion. + """ + return executor.submit(self.insert, key, value) + + +class OnDiskCache(AsyncCache[Key, Value]): + """ + On-disk cache implementation using files and file locks. + Stores cache data in files on disk, with atomic operations and versioning. + Supports custom cache directory names. + Attributes: + version (int): The version used for cache versioning. + name (str): The name of the cache directory. + """ + + version: int = 0 + + def __init__(self: Self, name: str | None = None) -> None: + """ + Initialize an on-disk cache instance. + Args: + name (str | None, optional): The name of the cache directory. If None, + defaults to "on_disk_cache". + """ + self.name = name or "on_disk_cache" + + @cached_property + def base_dir(self: Self) -> Path: + """ + Get the base directory for the cache. + Returns: + Path: The base directory path for storing cache files. + """ + return Path(gettempdir()) / "cache" / self.name + + def _fpath_from_key(self: Self, key: Key) -> Path: + """ + Get the file path for a given key. + Args: + key (Key): The key to convert to a file path. + Returns: + Path: The file path for the key. + Raises: + CacheError: If the key is not pickle-able. + """ + try: + return self.base_dir / sha256(pickle.dumps(key)).hexdigest()[:32] + except (AttributeError, pickle.PicklingError) as err: + raise CacheError( + f"Failed to get fpath for key {key!r}, key is not pickle-able." + ) from err + # pyrefly: ignore [bad-argument-type] + assert_never(key) + + def _flock_from_fpath(self: Self, fpath: Path) -> FileLock: + """ + Get a file lock for a given file path. + Args: + fpath (Path): The file path. + Returns: + FileLock: The file lock for the path. + """ + # fpath.name is a hex digest, meaning there are 16^4 potential values + # for fpath.name[:4]; this is more than enough unique locks to not + # cause additional overhead from shared locks and it also saves our + # cache dir from becoming 50 percent locks + # pyrefly: ignore [bad-return] + return FileLock(str(fpath.parent / "locks" / fpath.name[:4]) + ".lock") + + @property + def version_prefix(self: Self) -> bytes: + """ + Get the version prefix for the cache. + Returns: + bytes: The version prefix as bytes, derived from the cache version string. + """ + return sha256(str(OnDiskCache.version).encode()).digest()[:4] + + @override + def get(self: Self, key: Key) -> Value | None: + """ + Retrieve a value from the cache. + Args: + key (Key): The key to look up. + Returns: + Value | None: The cached value if present and version matches, else None. + Raises: + CacheError: If the value is corrupted or cannot be unpickled. + Side Effects: + Removes stale cache files if the version prefix does not match. + """ + fpath = self._fpath_from_key(key) + flock = self._flock_from_fpath(fpath) + + with flock: + if not fpath.is_file(): + return None + + value_bytes = None + prefix_length = len(self.version_prefix) + with open(fpath, "rb") as fp: + if fp.read(prefix_length) == self.version_prefix: + value_bytes = fp.read() + + if value_bytes is None: + # version_prefix did not match, so we can't read the stale + # cached value; we should also remove the stale cached value, + # so that key can be re-cached by the newer version + fpath.unlink() + return None + + try: + value = pickle.loads(value_bytes) + except pickle.UnpicklingError as err: + raise CacheError( + f"Failed to get key {key!r}, value is potentially corrupted (value is not un-pickle-able)." + ) from err + + return value + + @override + def insert(self: Self, key: Key, value: Value) -> bool: + """ + Insert a value into the cache. + Args: + key (Key): The key to insert. + value (Value): The value to associate with the key. + Returns: + bool: True if the value was inserted, False if the key already exists. + Raises: + CacheError: If the value is not pickle-able. + Side Effects: + Creates the cache directory if it does not exist. + """ + fpath = self._fpath_from_key(key) + flock = self._flock_from_fpath(fpath) + fpath.parent.mkdir(parents=True, exist_ok=True) + try: + # "x" mode is exclusive creation, meaning the file will be created + # iff the file does not already exist (atomic w/o overwrite); use + # flock for added atomicity guarantee and to prevent partial writes + with flock as _, open(fpath, "xb") as fp: + fp.write(self.version_prefix) + pickle.dump(value, fp) + except pickle.PicklingError as err: + raise CacheError( + f"Failed to insert key {key!r} with value {value!r}, value is not pickle-able." + ) from err + except FileExistsError: + return False + return True + + +class InductorOnDiskCache(OnDiskCache[Key, Value]): + """ + Inductor-specific on-disk cache implementation. + Uses a custom base directory for Inductor cache files. + """ + + def __init__(self: Self) -> None: + """ + Initialize an inductor on-disk cache instance. + Sets the cache directory name to "inductor_on_disk_cache". + """ + super().__init__("inductor_on_disk_cache") + + @cached_property + def base_dir(self: Self) -> Path: + """ + Get the base directory for the Inductor cache. + Returns: + Path: The base directory path for Inductor cache files. + """ + from torch._inductor.runtime.runtime_utils import default_cache_dir + + return Path(default_cache_dir(), "cache", self.name) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/cache_key.py b/.venv/lib/python3.12/site-packages/torch/_inductor/cache_key.py new file mode 100644 index 0000000000000000000000000000000000000000..cfef4170a15b4557afaef0f1298bae1098e9f82c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/cache_key.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import base64 +import dataclasses +import hashlib +import json +from typing import Any, Literal, Protocol +from typing_extensions import assert_never + + +CacheKeyComponent = str | bytes | bytearray | memoryview + + +class _HashLike(Protocol): + def update(self, data: bytes, /) -> None: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + + +@dataclasses.dataclass(frozen=True) +class CacheKeyStrategy: + """ + Describes how an Inductor cache turns stable components into a cache key. + + Different caches intentionally use different key formats for compatibility + with existing on-disk and remote cache layouts. Keeping those choices in + named strategies makes the composition explicit at the call site. + """ + + # Human-readable label for repr/debugging; it is not part of the cache key. + name: str + digest_format: Literal["base32", "hex"] + prefix: str = "" + separator: bytes | None = None + base32_length: int = 51 + + @staticmethod + def _to_bytes(component: CacheKeyComponent) -> bytes: + if isinstance(component, str): + return component.encode("utf-8") + if isinstance(component, bytes): + return component + if isinstance(component, bytearray): + return bytes(component) + if isinstance(component, memoryview): + return component.tobytes() + raise TypeError(f"Unsupported cache key component: {type(component)!r}") + + def _hasher(self, components: tuple[CacheKeyComponent, ...]) -> _HashLike: + hasher = hashlib.sha256() + for idx, component in enumerate(components): + if idx > 0 and self.separator is not None: + hasher.update(self.separator) + hasher.update(self._to_bytes(component)) + return hasher + + def digest(self, *components: CacheKeyComponent) -> str: + hasher = self._hasher(components) + if self.digest_format == "hex": + return hasher.hexdigest() + if self.digest_format == "base32": + # [:51] strips the "Q====" suffix common to every SHA256 base32 digest. + return ( + base64.b32encode(hasher.digest())[: self.base32_length] + .decode("utf-8") + .lower() + ) + assert_never(self.digest_format) + + def key(self, *components: CacheKeyComponent) -> str: + return f"{self.prefix}{self.digest(*components)}" + + def key_from_json(self, value: Any, *, sort_keys: bool = True) -> str: + return self.key(json.dumps(value, sort_keys=sort_keys)) + + +COMPACT_CACHE_KEY_STRATEGY = CacheKeyStrategy( + name="compact", + digest_format="base32", +) + +CODE_CACHE_KEY_STRATEGY = CacheKeyStrategy( + name="code", + digest_format="base32", + prefix="c", + separator=b"||", +) + +FX_GRAPH_CACHE_KEY_STRATEGY = CacheKeyStrategy( + name="fx_graph", + digest_format="base32", + prefix="f", +) + +SYSTEM_CACHE_KEY_STRATEGY = CacheKeyStrategy( + name="system", + digest_format="hex", +) + +AUTOTUNE_CACHE_KEY_STRATEGY = CacheKeyStrategy( + name="autotune", + digest_format="hex", + # Preserve the existing autotune cache format, which concatenates components. + separator=None, +) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/choices.py b/.venv/lib/python3.12/site-packages/torch/_inductor/choices.py new file mode 100644 index 0000000000000000000000000000000000000000..3f11e59acb3c02ec265f27be113eb7d7ba359533 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/choices.py @@ -0,0 +1,787 @@ +from __future__ import annotations + +import dataclasses +import typing +from typing import Any, TYPE_CHECKING + +import sympy + +import torch +from torch._inductor.runtime.runtime_utils import next_power_of_2 +from torch._inductor.scheduler import MixOrderReduction +from torch.utils._sympy.value_ranges import bound_sympy + +from . import config +from .codecache import write_text +from .heuristics.template import get_template_heuristic +from .heuristics.template.triton import ( + _origami_enabled, + BaseConfigHeuristic, + CPUConfigHeuristic, + CUDAConfigHeuristic, + IS_ROCM, + MTIAConfigHeuristic, + ROCmConfigHeuristic, + XPUConfigHeuristic, +) +from .kernel_inputs import KernelInputs, MMKernelInputs +from .kernel_template_choice import make_ktc_generator +from .metrics import get_metric_table, is_metric_table_enabled +from .runtime.hints import DeviceProperties, ReductionHint +from .scheduler import BaseSchedulerNode, Scheduler, WhyNoFuse +from .select_algorithm import ExternKernelChoice +from .utils import _use_autotune_backend +from .virtualized import V + + +if TYPE_CHECKING: + from collections.abc import Generator + from functools import partial + + from triton import Config as TritonConfig + + from .codegen.common import KernelTemplate + from .codegen.simd_kernel_features import SIMDKernelFeatures + from .codegen.triton import TritonKernel + from .ir import ChoiceCaller + from .kernel_template_choice import KernelTemplateChoice + + from torch.utils._ordered_set import OrderedSet # isort: skip + + +if TYPE_CHECKING or not config.is_fbcode(): + + def _maybe_log_inductor_mm_shape( + kernel_inputs: KernelInputs, + op_name: str, + context_fn: Any = None, + ) -> None: + return + +else: + from torch._inductor.fb.shape_logging import ( + log_inductor_mm_shape as _maybe_log_inductor_mm_shape, + ) + + +class Sortable(typing.Protocol): + """Anything that can be used as a list.sort() key (int/tuple/etc)""" + + def __lt__(self, other: typing.Self) -> bool: ... + + +@dataclasses.dataclass +class FusionScore: + template_score: int + node_type_score: int + memory_score: int + buffer_overlap_score: int + proximity_score: int + + def __lt__(self, other): + """ + node_type_score orders same-kind fusions above mixed-kind fusions unless + the memory_score differs too much. Nested reduction candidates use -1 + so they rank below ordinary mixed-kind fusions; mix-order reductions + are still scored through memory_score. + + buffer_overlap_score is prioritized below memory_score so that + strict global memory savings (exact dep matches) are preferred + over buffer overlap scoring (same buffer, different indexing). + """ + threshold = 16 + if self.template_score != other.template_score: + return self.template_score < other.template_score + + if ( + max(self.memory_score, other.memory_score) + > min(self.memory_score, other.memory_score) * threshold + ): + return self.memory_score < other.memory_score + + return ( + self.node_type_score, + self.memory_score, + self.buffer_overlap_score, + self.proximity_score, + ) < ( + other.node_type_score, + other.memory_score, + other.buffer_overlap_score, + other.proximity_score, + ) + + +class InductorChoices: + """ + This class contains a collection of default heuristics that affect performance of our generated + code. We try to not put correctness requirements in this file. + + You can override the choices made here by doing: + + class MyHeuristics(InductorChoices): + ... + + torch._inductor.virtualized.V.set_choices_handler(MyHeuristics()) + + Subclasses used with inductor_choices_class must implement uuid() for + cache key computation. + """ + + def get_config_heuristics( + self, device_type: str | None = "cuda" + ) -> BaseConfigHeuristic: + if device_type == "cuda": + if torch.version.hip is None: + return CUDAConfigHeuristic() + else: + return ROCmConfigHeuristic() + elif device_type == "xpu": + return XPUConfigHeuristic() + elif device_type == "cpu": + return CPUConfigHeuristic() + elif device_type == "mtia": + return MTIAConfigHeuristic() + else: + return BaseConfigHeuristic() + + # Conv configs + def get_conv_configs( + self, device_type: str | None = "cuda" + ) -> partial[Generator[TritonConfig, None, None]]: + conv_heuristics = self.get_config_heuristics(device_type) + return conv_heuristics.get_conv_configs() + + def get_depthwise_conv_configs(self, device_type: str | None = "cuda") -> list[Any]: + heuristics = self.get_config_heuristics(device_type) + return heuristics.get_depthwise_conv_configs() + + # Flex attention configs + # TODO(coconutruben): break out flexattention/decode configs into the new retrieval mechanism + def get_flex_attention_fwd_configs( + self, + head_dim: int, + seq_len: sympy.Expr, + dtype: torch.dtype, + device_type: str | None = "cuda", + ) -> list[Any]: + flex_heuristics = self.get_config_heuristics(device_type) + return flex_heuristics.get_flex_attn_fwd_configs(head_dim, seq_len, dtype) + + def get_flex_attention_bwd_configs( + self, head_dim: int, dtype: torch.dtype, device_type: str | None = "cuda" + ) -> list[Any]: + flex_heuristics = self.get_config_heuristics(device_type) + return flex_heuristics.get_flex_attn_bwd_configs(head_dim, dtype) + + def get_flex_decode_configs( + self, head_dim: int, dtype: torch.dtype, device_type: str | None = "cuda" + ) -> list[Any]: + flex_heuristics = self.get_config_heuristics(device_type) + return flex_heuristics.get_flex_decode_configs(head_dim, dtype) + + def append_flex_attention_choices( + self, + choices: list[Any], + configs: list[Any], + input_nodes: list[Any], + subgraphs: list[Any], + layout: Any, + kernel_options: dict[str, Any], + sparse_q_block_size: int, + sparse_kv_block_size: int, + ) -> list[Any]: + """Append backend-specific flex-attention template choices. + + Default is a no-op. Subclasses may override to inject additional + autotuning candidates (e.g. TLX templates in fbcode). + """ + return choices + + def _logging_context(self) -> dict[str, Any]: + """Extra fields for the per-shape log row. Subclasses may override.""" + return {} + + def _finalize_template_configs( + self, + template_choices: dict[str, Generator[KernelTemplateChoice, None, None]], + kernel_inputs: KernelInputs, + templates: list[KernelTemplate | ExternKernelChoice], + op_name: str, + kwarg_overrides: dict[str, dict[str, Any]] | None = None, + ) -> list[KernelTemplateChoice]: + """ + This method can be subclassed to perform any override/modification of the choices. + The incoming parameters are cheap (generators), so you can do any overrides without + incurring too much cost. Override this method to customize the kernel template choices + before they are converted to ChoiceCaller objects, which is expensive on template codegen. + + The full list of arguments are here to facilitate any overrides you may want to do, + as they can be used to start from scratch for each template if so desired. + + Args: + template_choices: Dictionary mapping template UIDs to generators of KernelTemplateChoice objects + kernel_inputs: MMKernelInputs containing input tensor nodes and matrix indices + templates: List of template objects (KernelTemplate or ExternKernelChoice) in use + op_name: Operation name (e.g., "bmm", "baddbmm", "addmm") + kwarg_overrides: Optional dict of kwargs to override for each template heuristic + + Returns: + Flattened list of KernelTemplateChoice objects across all templates + """ + if isinstance(kernel_inputs, MMKernelInputs): + _maybe_log_inductor_mm_shape( + kernel_inputs, op_name, context_fn=self._logging_context + ) + choices: list[KernelTemplateChoice] = [] + for choice_gen in template_choices.values(): + choices.extend(choice_gen) + return choices + + def get_ktc( + self, + kernel_inputs: KernelInputs, + template: KernelTemplate | ExternKernelChoice, + op_name: str, + kwarg_overrides: dict[str, Any] | None = None, + ) -> Generator[KernelTemplateChoice, None, None]: + """ + Utility to get the KernelTemplateChoice generator for a specific input. + + This is a per template/op call, whereas get_template_configs is an op wide call (all templates). + Consider when overriding/using at which level you need to make decisions + """ + # Extract device_type from kernel_inputs + device_type = kernel_inputs.device_type + if device_type is None: + raise AssertionError("get_ktc requires a valid device type") + # Extract template_name from the template object + template_name = template.uid + + # Get the appropriate template-specific heuristic + heuristic = get_template_heuristic(template_name, device_type, op_name) + cs = heuristic.get_template_configs( + kernel_inputs, + op_name, + ) + # adjust the kernel inputs to the template-specific heuristic, if needed + # default here is to just return the kernel_inputs as is + inputs_val = heuristic.adjust_kernel_inputs(kernel_inputs, op_name) + extra_kwargs = heuristic.get_extra_kwargs(kernel_inputs, op_name) + # Create KernelTemplateChoice generator using the moved function + overrides = kwarg_overrides or {} + return make_ktc_generator( + template=template, + cs=cs, + extra_kwargs=extra_kwargs, + overrides=overrides, + layout=kernel_inputs.output_layout(), + inputs=inputs_val, + ) + + def _need_to_fix_layout( + self, + adjusted_choices: list[KernelTemplateChoice], + op_name: str, + ) -> bool: + """Return True if any active backend requires fixed (non-flexible) tensor layouts.""" + # TODO: debug and fix + # NOTE: on mps, we see issues with flexible layouts on baddmm. This check just makes sure + # that for mps, everything stays as it was before this optimization + if len(adjusted_choices) > 0: + if adjusted_choices[0].inputs.device_type == "mps" and op_name not in [ + "mm", + "addmm", + ]: + return True + + # Origami requires fixed layouts (grid/workgroup mappings depend on exact + # strides). Gate on IS_ROCM so a stray TORCHINDUCTOR_ORIGAMI=1 on CUDA + # doesn't disable flexible layouts unnecessarily. Also gate on max-autotune: + # origami only contributes Triton GEMM configs under autotuning, so with it + # off there is nothing that needs fixed strides and flexible layouts should + # be preserved (matches non-origami behavior). + if ( + _origami_enabled() + and IS_ROCM + and (config.max_autotune or config.max_autotune_gemm) + ): + return True + # Since the following backends are not using get_mm_configs yet through the singular call, + if not (config.max_autotune or config.max_autotune_gemm): + # no danger of using other backends than ATEN + if not config.max_autotune_allow_flexible_layouts and op_name not in [ + # The historical implementation for mm and addmm allowed had flexible layouts in the + # not max-autotune world + "mm", + "addmm", + ]: + # TODO: deprecate this by migrating users to the new behavior + return True + return False + + if not config.max_autotune_allow_flexible_layouts: + # we always need to fix the layout + return True + + # Since the following backends are not using get_template_configs yet through the singular call, + # we don't know if they are a valid choice or not. Instead, just skip the optimization + # defensively. + # TODO(coconutruben): remove this once CPP,CK,CUTLASS are supported + if _use_autotune_backend("CUTLASS"): + return True + if _use_autotune_backend("CK") or _use_autotune_backend("CKTILE"): + return True + if _use_autotune_backend("CPP"): + return True + return any( + not isinstance(ktc.template, ExternKernelChoice) for ktc in adjusted_choices + ) + + def get_template_configs( + self, + kernel_inputs: KernelInputs, + templates: list[KernelTemplate | ExternKernelChoice], + op_name: str, + kwarg_overrides: dict[str, dict[str, Any]] | None = None, + ) -> list[ChoiceCaller]: + """ + Get list of ChoiceCallers for MM templates using template-specific heuristics. + + Args: + kernel_inputs: MMKernelInputs containing input tensor nodes and matrix indices + layout: Output layout + templates: List of template objects (KernelTemplate or ExternKernelChoice) + op_name: Operation name (e.g., "bmm", "baddbmm", "addmm", "mm_plus_mm") + kwarg_overrides: Optional dict of kwargs to override for each template heuristic, + indexed by template.uid. These only override the per config kwargs, not the extra kwargs + Returns: + List of ChoiceCaller objects from the templates + """ + if kwarg_overrides is None: + kwarg_overrides = {} + input_tensors = kernel_inputs.nodes() + if len(input_tensors) < 2: + raise ValueError(f"Need at least 2 input tensors, got {len(input_tensors)}") + layout = kernel_inputs.output_layout() + # First pass: Create dict of template.uid to generator of KernelTemplateChoice objects + template_choices = {} + for template in templates: + template_choices[template.uid] = self.get_ktc( + kernel_inputs, + template, + op_name, + kwarg_overrides.get(template.uid, {}), + ) + + # Second pass: Adjust the template choices + adjusted_choices = self._finalize_template_configs( + template_choices, + kernel_inputs, + templates, + op_name, + kwarg_overrides, + ) + # Layout optimization: if all choices are ExternKernelChoice and layout is FixedLayout, convert to FlexibleLayout + if self._need_to_fix_layout(adjusted_choices, op_name): + layout = kernel_inputs.output_layout(flexible=False) + for ktc in adjusted_choices: + ktc.layout = layout + # for good measure, delete the cached ChoiceCaller from the ktc if it existed. + # ExternKernelChoice are cheap to generate + if hasattr(ktc, "_choice"): + del ktc._choice + # Third pass: Convert to ChoiceCaller objects + return [ktc.choice for ktc in adjusted_choices if ktc.choice is not None] + + def triton_kernel_kwargs( + self, + kernel_cls: type[TritonKernel], + features: SIMDKernelFeatures, + groups: list[sympy.Expr], + kernel_kwargs: dict[str, Any], + ) -> dict[str, Any]: + """Hook to change the kwargs passed to TritonKernel, used to apply fixed configurations""" + return kernel_kwargs + + def override_best_choice( + self, + best_choice: ChoiceCaller, + timings: dict[ChoiceCaller, float], + ) -> ChoiceCaller: + """Hook to override the autotuning best choice after benchmarking.""" + return best_choice + + def customize_fused_kernel_name(self, fused_name: str, src_code: str) -> str: + """Hook to transform fused kernel names during codegen""" + return fused_name + + @staticmethod + def should_use_cooperative_reduction( + device: torch.device, numel: sympy.Expr, reduction_numel: sympy.Expr + ) -> bool: + """Heuristic to decide if a cooperative reduction should be used.""" + if config.triton.force_cooperative_reductions: + return True + if not config.triton.cooperative_reductions or device.type == "cpu": + return False + + xhint = V.graph.sizevars.optimization_hint(numel, fallback=2) + if xhint <= 8: + threshold = 32768 * xhint + elif xhint <= 16: + threshold = 2097152 + else: + return False + # TODO(jansel): should this default on for dynamic shapes? + # TODO(laith) What if hint(reduction_numel) >= threshold ? + # shall we compare hints instead + return V.graph.sizevars.statically_known_geq(reduction_numel, threshold) + + @staticmethod + def should_use_persistent_reduction( + features: SIMDKernelFeatures, + cooperative_reduction: bool, + ) -> bool: + """ + Heuristic to decide if a persistent reduction should be used. + """ + if not config.triton.persistent_reductions: + return False + reduction_hint = features.get_reduction_hint() + rblock = features.strict_sum_rblock() + if rblock is not None and not features.has_strict_sum_multirow_reduction(): + if not ( + V.graph.sizevars.statically_known_geq(rblock, features.reduction_numel) + ): + return False + threshold = { + ReductionHint.INNER: 1024, + }.get(reduction_hint, 64) + + if reduction_hint not in ( + ReductionHint.INNER, + ReductionHint.OUTER_TINY, + ): + bounds = bound_sympy(features.reduction_numel) + lower = bounds.lower + upper = bounds.upper + + if not all( + ( + (isinstance(bound, int) or bound.is_constant()) + and not torch.utils._sympy.numbers.is_infinite(bound) + ) + for bound in (lower, upper) + ): + return False + + lower = next_power_of_2(int(lower)) + upper = next_power_of_2(int(upper)) + + # If we are coalescing on xblock (not ReductionHint.INNER) and this is not a tiny kernel + # (not ReductionHint.OUTER_TINY), do not use persistent reduction if it induces tile + # quantization. Persistent reduction forces rblock == rnumel, if the bounds between lower + # and upper are large, for the lower values we will be masking off large % of read/writes, + # when we could expand the coalescing xblock instead. + if lower != upper: + return False + + if cooperative_reduction: + # The RSPLIT of cooperative reductions means each thread block is operating on fewer elements + # The default fallback will be used if optimizations hint is not provided. The default fallback + # is >> 32. + threshold *= 32 // min( + V.graph.sizevars.optimization_hint(features.numel), 32 + ) + + # If multi_kernel is enabled, we do more aggressive persistent reduction. + # This may result in some persistent reductions slower than the + # corresponding non-persistent reductions. MultiKernel will do benchmarking + # to pick the faster one. + if config.triton.multi_kernel: + threshold *= 16 + + return V.graph.sizevars.statically_known_leq( + features.reduction_numel, threshold + ) # type: ignore[arg-types] + + def _inner_reduction_no_split_threshold( + self, + props: DeviceProperties, + xnumel: int, + num_sm: int, + ) -> int: + # Benchmark results from two scenarios: + # (1) Standalone ops/small models: CPU wall time measures end-to-end + # latency and generally prefers a large no-split threshold. + # (2) Sections inside large compiled models: kernel/device time is the + # local codegen signal and prefers the smaller xnumel-dependent + # threshold. Kernel launch overhead is amortized by cuda-graph. + # Benchmarked ops: sum, entropy, RMSNorm, Welford, GroupNorm(+SiLU), + # plus Stable Diffusion v1.5 UNet batch-1/8 validation. + # Chosen GB200 thresholds: 32768 for xnumel < num_sm, otherwise 40960. + # Reducing these thresholds further did not improve scenario (2), but + # hurts scenario (1). + if props.major is not None and props.major >= 10: + if xnumel < num_sm: + return 32768 + return 40960 + return 8192 + + def reduction_split_factor( + self, + device: torch.device, + reduction_numel_hint: int, + numel_hint: int, + inner_reduction: bool, + ) -> int: + """Heuristic to decide the RSPLIT used for split reductions. + When a reduction has a small number of outputs there is not enough parallelism, + so we will do the reduction in two phases.""" + props = DeviceProperties.create(device) + num_sm = props.multi_processor_count + warp_size = props.warp_size_or_default + max_threads_per_sm = ( + props.max_threads_per_multi_processor + if props.max_threads_per_multi_processor is not None + else 2048 + ) + min_elements_per_thread = warp_size + max_elements_per_thread = 512 + threads_per_sm = max_threads_per_sm + min_elements_per_device = min_elements_per_thread * num_sm * threads_per_sm + max_elements_per_device = max_elements_per_thread * num_sm * threads_per_sm + num_warps = 8 + num_threads = warp_size * num_warps + + if inner_reduction: + # do heuristics that's close to eager mode for split inner reduction + # we leak reduction autotune configs here, and will need to refactor to avoid this later + if numel_hint >= 2 * num_sm: # don't split if there are enough outputs + return 1 + no_split_threshold = self._inner_reduction_no_split_threshold( + props, numel_hint, num_sm + ) + if reduction_numel_hint <= no_split_threshold: + return 1 + if reduction_numel_hint * numel_hint <= min_elements_per_device: + split_size = min_elements_per_thread + elif reduction_numel_hint * numel_hint < max_elements_per_device: + target_blocks = num_sm * threads_per_sm // (2 * num_threads) + blocks_per_output = (target_blocks + numel_hint - 1) // numel_hint + tmp_split_size = ( + reduction_numel_hint + num_threads * blocks_per_output - 1 + ) // (num_threads * blocks_per_output) + divisors = sympy.divisors(reduction_numel_hint) + closest = min(divisors, key=lambda x: abs(x - tmp_split_size)) + if abs(closest - tmp_split_size) < 30: + # prefer even splits, but never smaller than min_elements_per_thread + split_size = max(closest, min_elements_per_thread) + else: + split_size = tmp_split_size + else: + divisors = sympy.divisors(reduction_numel_hint) + closest = min(divisors, key=lambda x: abs(x - max_elements_per_thread)) + if abs(closest - max_elements_per_thread) < 50: + # prefer even splits + split_size = closest + else: + split_size = max_elements_per_thread + return (reduction_numel_hint + split_size * num_threads - 1) // ( + split_size * num_threads + ) + else: + # TODO the best heuristic currently has XBLOCK (corresponding to numel_hint) 128 + # extend to even smaller number of outputs + rvals_per_thread = 4 # comes from heuristics, refactor to not leak here + xvals_per_block = 128 + xblocks = (numel_hint + xvals_per_block - 1) // xvals_per_block + if reduction_numel_hint * numel_hint < min_elements_per_device: + split_size = min_elements_per_thread + elif reduction_numel_hint * numel_hint < max_elements_per_device: + target_blocks = num_sm * threads_per_sm // (num_threads) + target_blocks = (target_blocks + xblocks - 1) // xblocks + tmp_split_size = ( + reduction_numel_hint + rvals_per_thread * target_blocks - 1 + ) // (rvals_per_thread * target_blocks) + divisors = sympy.divisors(reduction_numel_hint) + closest = min(divisors, key=lambda x: abs(x - tmp_split_size)) + if abs(tmp_split_size - closest) < 20: + split_size = max(closest, min_elements_per_thread) + else: + split_size = tmp_split_size + else: + divisors = sympy.divisors(reduction_numel_hint) + closest = min(divisors, key=lambda x: abs(x - max_elements_per_thread)) + if abs(closest - max_elements_per_thread) < 50: + # prefer even splits + split_size = closest + else: + split_size = max_elements_per_thread + + return (reduction_numel_hint + rvals_per_thread * split_size - 1) // ( + rvals_per_thread * split_size + ) + + @staticmethod + def can_fuse( + scheduler: Scheduler, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + shared_data_score: int, + ) -> bool: + """ + Heuristics to prevent fusion applied to both horizontal and vertical fusions. Heuristics here should not + be needed for correctness and tweaking them may yield additional performance. + + See also some related heuristics that can be changed via config: + - config.triton.tiling_prevents_pointwise_fusion + - config.triton.tiling_prevents_reduction_fusion + - config.aggressive_fusion (will cause this function to be called more times) + """ + if shared_data_score == 0 and ( + not config.aggressive_fusion or node1.is_reduction() or node2.is_reduction() + ): + if is_metric_table_enabled("fusion_failure_due_to_indexing_mismatch"): + common_buf_names: OrderedSet[str] = ( + node1.read_writes.buffer_names() & node2.read_writes.buffer_names() + ) + if len(common_buf_names) > 0: + get_metric_table("fusion_failure_due_to_indexing_mismatch").add_row( + # pyrefly: ignore [bad-argument-type] + lambda: { + "pre_grad_graph_id": V.graph.graph_id, + "post_grad_graph_id": V.graph.post_grad_graph_id, + "node1_name": node1.get_name(), + "node2_name": node2.get_name(), + "node1_debug_str": write_text(node1.debug_str()), + "node2_debug_str": write_text(node2.debug_str()), + "common_buffer_names": list(common_buf_names), # type: ignore[dict-item] + "failure_reason": scheduler.decide_fusion_fail_reason( + node1, node2, common_buf_names + ), + } + ) + + WhyNoFuse(node1, node2)("no shared data due to indexing mismatch") + return False + WhyNoFuse(node1, node2)("no shared data") + return False # heuristic not needed for correctness + + if ( + not node1.is_foreach() + and not node2.is_foreach() + and len(node1.get_nodes()) + len(node2.get_nodes()) > config.max_fusion_size + ): + WhyNoFuse(node1, node2)("exceeds max fusion") + return False # heuristic not needed for correctness + + if scheduler.can_fusion_increase_peak_memory(node1, node2): + WhyNoFuse(node1, node2)("Fusion will increase peak memory") + return False + + if ( + config.max_fusion_unique_io_buffers is not None + and scheduler.fusion_prevent_too_many_reads_and_writes( + node1, + node2, + config.max_fusion_unique_io_buffers, + ) + ): + WhyNoFuse(node1, node2)("fusion_prevent_too_many_reads_and_writes") + return False + + return True + + @staticmethod + def can_fuse_vertical( + scheduler: Scheduler, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + shared_data_score: int, + ) -> bool: + """Hook for heuristics to prevent vertical (producer/consumer) fusions""" + return True + + @staticmethod + def can_fuse_horizontal( + scheduler: Scheduler, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + shared_data_score: int, + ) -> bool: + """Hook for heuristics to prevent horizontal (consumer/consumer) fusions""" + if MixOrderReduction.can_fuse(node1, node2): + # For mix order reduction, we disregard shared data or + # distance. + return True + if shared_data_score < config.score_fusion_memory_threshold: + WhyNoFuse(node1, node2)("score_fusion_memory_threshold") + return False + if scheduler.are_long_distant_nodes(node1, node2): + WhyNoFuse(node1, node2)( + "Nodes are too far away. Fusing them may increase peak memory." + ) + return False + return True + + @staticmethod + def score_fusion( + scheduler: Scheduler, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + ) -> Sortable: + """ + Assign a score (higher comes first) to the fusion of node1 and node2. + When different fusions conflict with each other, this is the way we + decide what order to run them in. + + Our current score is based on: + - The type of fusion (template/reduction/etc) + - Estimate of the saved memory operations + - Fusions closer together in original graph order + """ + + memory_score, buffer_overlap_score, is_mix_order_reduction = ( + scheduler.score_fusion_memory( + node1, node2, return_is_mix_order_reduction=True + ) + ) + proximity_score = -max( + abs(node1.min_order - node2.max_order), + abs(node2.min_order - node1.max_order), + ) + + # prologue fusion always last + if node2.is_template(): + template_score = 0 + else: + template_score = 1 + ( + (node1.is_template() == config.epilogue_fusion_first) + and memory_score > 0 + ) + + node_type_score = int( + node1.is_reduction() == node2.is_reduction() and memory_score > 0 + ) + if ( + config.triton.nested_reduction + and node1.is_reduction() + and node2.is_reduction() + and node1.get_operation_names() & node2.ancestors + ): + # Mix-order reductions are sibling reductions. Only dependent + # cross-reduction-size reductions get the lower nested score here. + _, (_, rnumel1) = node1.group + _, (_, rnumel2) = node2.group + if not V.graph.sizevars.statically_known_equals(rnumel1, rnumel2): + node_type_score = -1 + + return FusionScore( + template_score, + node_type_score, + memory_score, + buffer_overlap_score, + proximity_score, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codecache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codecache.py new file mode 100644 index 0000000000000000000000000000000000000000..53d5b52f9682b4a4b9084e502150eb9c581d8431 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codecache.py @@ -0,0 +1,5542 @@ +from __future__ import annotations + +import base64 +import copyreg +import dataclasses +import functools +import hashlib +import importlib +import importlib.resources +import io +import itertools +import json +import logging +import os +import pickle +import pkgutil +import platform +import re +import shlex +import shutil +import struct +import subprocess +import sys +import tempfile +import textwrap +import threading +import warnings +from bisect import bisect_right +from collections.abc import Set as AbstractSet +from copy import copy +from ctypes import c_void_p, CDLL, cdll +from datetime import timedelta +from functools import lru_cache, partial +from pathlib import Path +from tempfile import _TemporaryFileWrapper +from time import time, time_ns +from types import ( + BuiltinFunctionType, + BuiltinMethodType, + FunctionType, + MethodType, + ModuleType, +) +from typing import Any, cast, Generic, Literal, NoReturn, TYPE_CHECKING, TypeVar +from typing_extensions import NotRequired, override, Self, TypedDict + +import torch +import torch._library.opaque_object as opaque_object +import torch.distributed as dist +from torch import SymInt, Tensor +from torch._dynamo.device_interface import get_interface_for_device +from torch._dynamo.exc import SkipFrame +from torch._dynamo.utils import ( + CompileEventLogger, + counters, + dynamo_timed, + get_metrics_context, +) +from torch._inductor import config, config_comms, exc, metrics +from torch._inductor.codegen.common import ( + custom_backend_codegen_configs, + custom_backend_passes, + init_backend_registration, +) +from torch._inductor.codegen.cuda import compile_utils as cuda_compile_utils +from torch._inductor.codegen.rocm.compile_command import ( + rocm_compile_command, + rocm_compiler, +) +from torch._inductor.compile_worker.utils import in_toplevel_process +from torch._inductor.cpp_builder import ( + _LINKER_SCRIPT, + _set_gpu_runtime_env, + _TORCH_PATH, + batch_convert_cubins_to_obj, + convert_cubin_to_obj, + CppBuilder, + CppOptions, + CppTorchDeviceOptions, + get_compiler_version_info, + get_cpp_compiler, + get_ld_and_objcopy, + get_name_and_dir_from_output_file_path, + normalize_path_separator, + run_asm_build_object, +) +from torch._inductor.cpu_vec_isa import invalid_vec_isa, pick_vec_isa +from torch._inductor.custom_graph_pass import ( + CustomGraphModulePass, + CustomGraphPass, + CustomGraphPassCallable, + CustomPartitionerFn, + CustomPartitionerFnType, + CustomPassBase, + CustomSchedulerPass, + get_custom_graph_passes, +) +from torch._inductor.freezing_utils import has_frozen_params, is_frozen_param +from torch._inductor.runtime.compile_tasks import _reload_python_module +from torch._inductor.runtime.runtime_utils import cache_dir, default_cache_dir +from torch._inductor.utils import ( + ALIGN_BYTES, + clear_on_fresh_cache, + determine_aoti_mmap_flags, + is_linux, + is_windows, + parallel_num_threads, + XPU_KERNEL_FORMAT, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_opaque_symbolic_type +from torch._logging import trace_structured +from torch._subclasses.fake_tensor import ( + extract_tensor_metadata, + FakeTensor, + TensorMetadata, +) +from torch._utils_internal import log_cache_bypass +from torch.compiler import config as cconfig +from torch.compiler._cache import ( + CacheArtifact, + CacheArtifactFactory, + CacheArtifactRecorder, +) +from torch.export.pt2_archive._package_weights import TensorProperties, Weights +from torch.export.pt2_archive.constants import CUSTOM_OBJ_FILENAME_PREFIX +from torch.fx.experimental.symbolic_shapes import ( + guarding_hint_or_throw, + has_guarding_hint, + ShapeEnv, +) +from torch.utils._device import _device_constructors +from torch.utils._ordered_set import OrderedSet + +from .cache_key import ( + CODE_CACHE_KEY_STRATEGY, + COMPACT_CACHE_KEY_STRATEGY, + FX_GRAPH_CACHE_KEY_STRATEGY, + SYSTEM_CACHE_KEY_STRATEGY, +) +from .output_code import CompiledFxGraph +from .remote_cache import cache_stats, create_cache +from .runtime import autotune_cache +from .runtime.autotune_cache import AutotuneCacheBundler +from .triton_bundler import TritonBundler +from .virtualized import V + + +T = TypeVar("T") + + +class SystemDeviceInfo(TypedDict): + name: str | None + + +class SystemVersionInfo(TypedDict, total=False): + triton: str | None + cuda: str + hip: str | None + + +class SystemInfo(TypedDict): + hash: str + device: NotRequired[SystemDeviceInfo] + version: NotRequired[SystemVersionInfo] + + +class CacheInfo(TypedDict, total=False): + cache_state: Literal["bypass", "hit", "miss"] + cache_status_detailed: str + cache_status_guard_expr: str + triton_bundler_meta: str + time_saved_ns: int + time_taken_ns: int + ephemeral_timeout_increase: int + cache_bypass_reason: str + cache_event_time: int + key: str + components: list[str] + cache_bypass_exception_type: str + cache_bypass_traceback: list[str] + cache_bypass_hard_exception: bool + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, KeysView, Sequence + from concurrent.futures import Future + + from .compile_fx import _CompileFxKwargs + from .cpp_builder import BuildOptionsBase + from .graph import GraphLowering + from .ir import ChoiceCaller + from .output_code import CompiledFxGraphConstants, OutputCode + from .remote_cache import JsonDataTy, RemoteCache + from .runtime.hints import HalideInputSpec, HalideMeta + from .runtime.triton_heuristics import CachingAutotuner + from .utils import InputType + + +_IS_WINDOWS = sys.platform == "win32" +LOCK_TIMEOUT = config.file_lock_timeout + +output_code_log = torch._logging.getArtifactLogger(__name__, "output_code") +autotuning_log = torch._logging.getArtifactLogger(__name__, "autotuning") +log = logging.getLogger(__name__) + +AOTAUTOGRAD_CACHE_PREFIX = "a" + + +def _device_constructor_sort_key(target: Any) -> str: + return ".".join( + x + for x in ( + getattr(target, "__module__", None), + getattr(target, "__qualname__", None), + getattr(target, "__name__", None), + repr(target), + ) + if x + ) + + +@lru_cache(None) +def _default_device_constructor_targets() -> tuple[Any, ...]: + return tuple(sorted(_device_constructors(), key=_device_constructor_sort_key)) + + +@lru_cache(None) +def _default_device_constructor_overload_packets() -> tuple[Any, ...]: + packets: list[Any] = [] + for target in _default_device_constructor_targets(): + if (name := getattr(target, "__name__", None)) is None: + continue + if (packet := getattr(torch.ops.aten, name, None)) is not None: + packets.append(packet) + return tuple(packets) + + +def get_cpp_wrapper_cubin_path_name() -> str: + return "cubin_path" if torch.version.hip is None else "hsaco_path" + + +def get_kernel_bin_format(device: str) -> str: + if device == "cuda": + return "cubin" if torch.version.hip is None else "hsaco" + elif device == "xpu": + return XPU_KERNEL_FORMAT + else: + return "" + + +def _cuda_fatbin_command( + asm_file: str, + cubin_file: str, + raw_cubin_file: str | None, + nvcc: str | None, + fatbinary: str | None, + current_arch: str | None = None, +) -> list[str]: + if not current_arch: + current_arch = cuda_compile_utils._nvcc_arch_as_compile_option_or_raise() + gencode_options = cuda_compile_utils._cuda_multi_arch_gencode_options(current_arch) + if ( + fatbinary is not None + and raw_cubin_file is not None + and os.path.exists(raw_cubin_file) + and not cuda_compile_utils._cuda_gencode_options_have_non_current_sass( + gencode_options, current_arch + ) + ): + # Avoid re-running ptxas; the CUDA toolkit can lag the PTX version + # emitted by Triton. This path is only valid when no extra SASS images + # beyond the current GPU generation were requested. + return [ + fatbinary, + f"--create={cubin_file}", + "-64", + f"--image3=kind=elf,sm={current_arch},file={raw_cubin_file}", + f"--image3=kind=ptx,sm={current_arch},file={asm_file}", + ] + + if nvcc is None: + raise RuntimeError("nvcc is required to build fatbin") + + cmd = [ + *shlex.split(nvcc), + "-fatbin", + asm_file, + "-o", + cubin_file, + ] + for gencode_option in gencode_options: + cmd.extend(["-gencode", gencode_option]) + return cmd + + +def get_device_information(device_type: str) -> dict[str, str]: + """ + Gets all the current device information used to compile the .so. + """ + metadata: dict[str, str] = { + "AOTI_PLATFORM": sys.platform, + "AOTI_MACHINE": platform.machine(), + "AOTI_CPU_ISA": str(torch._inductor.cpu_vec_isa.pick_vec_isa()).upper(), + "AOTI_COMPUTE_CAPABILITY": str( + get_interface_for_device(device_type).get_compute_capability() + ), + } + return metadata + + +from torch.utils._functools import prefetchable_cache as torch_key_cache + + +@torch_key_cache +def triton_key() -> str | None: + from torch._inductor.runtime.triton_compat import ( + HAS_TRITON, + triton_key as _triton_key_impl, + ) + + # Use triton_key instead of triton.__version__ as the version + # is not updated with each code change + if HAS_TRITON: + return _triton_key_impl() + return None + + +class CacheBase: + @staticmethod + @functools.cache + def get_system() -> SystemInfo: + with dynamo_timed("CacheBase.get_system.triton_key"): + triton_version = triton_key() + + try: + device_info: SystemDeviceInfo = {"name": None} + version_info: SystemVersionInfo = {"triton": triton_version} + device_properties = torch.cuda.get_device_properties( + torch.cuda.current_device() + ) + if torch.version.cuda is not None: + device_info["name"] = device_properties.name + version_info["cuda"] = torch.version.cuda + else: + device_info["name"] = device_properties.gcnArchName + version_info["hip"] = torch.version.hip + hash_input: dict[str, Any] = { + "device": device_info, + "version": version_info, + } + return { + "device": device_info, + "version": version_info, + "hash": SYSTEM_CACHE_KEY_STRATEGY.key_from_json(hash_input), + } + except (AssertionError, RuntimeError): + # If cuda is not installed, none of the above config is relevant. + return {"hash": SYSTEM_CACHE_KEY_STRATEGY.key_from_json({})} + + @staticmethod + @clear_on_fresh_cache + @functools.cache + def get_local_cache_path() -> Path: + return Path(os.path.join(cache_dir(), "cache", CacheBase.get_system()["hash"])) + + def __init__(self) -> None: + self.system = CacheBase.get_system() + + def get_local_cache(self) -> dict[str, Any]: + local_cache_path = self.get_local_cache_path() + if not local_cache_path.is_file(): + return {} + with open(local_cache_path) as local_cache_fp: + local_cache = json.load(local_cache_fp) + return local_cache["cache"] + + def update_local_cache(self, local_cache: dict[str, Any]) -> None: + local_cache_path = self.get_local_cache_path() + write_atomic( + str(local_cache_path), + json.dumps({"system": self.system, "cache": local_cache}, indent=4), + make_dirs=True, + ) + + +class LocalCache(CacheBase): + def lookup(self, *keys: str) -> dict[str, Any] | None: + cache = self.get_local_cache() + + sub_cache = cache + for key in keys: + if key in cache: + sub_cache = cache[key] + else: + return None + + return sub_cache + + def set_value(self, *keys: str, value: Any) -> None: + cache = self.get_local_cache() + + sub_cache = cache + for key in keys[0:-1]: + sub_cache.setdefault(key, {}) + sub_cache = sub_cache[key] + sub_cache[keys[-1]] = value + + self.update_local_cache(cache) + + +class PersistentCache(CacheBase): + def lookup( + self, + choices: list[ChoiceCaller], + op: str, + inputs: str, + benchmark: Callable[[Any], dict[ChoiceCaller, float]] | None, + hint_override: int | None = None, + ) -> dict[ChoiceCaller, float]: + """ + Check to see if we have benchmarked the given choice callers. For each + choice caller: + + 1. Check local_cache[op][inputs][choice][precision], return benchmark if cached. + 2. If benchmark is not None: + a. `max_autotune_gemm=True`: benchmark the choice, update + local_cache[op][inputs][choice], and return the benchmark. + b. `max_autotune_gemm=False`: don't benchmark the choice, return nothing. + """ + precision = torch.get_float32_matmul_precision() + cache_key = f"{inputs}_{hint_override}" if hint_override is not None else inputs + + timings = {} + + def check_cache(cache: dict[str, Any]) -> bool: + """Check if `cache` contains data for all the choices""" + hit = True + for choice in choices: + choice_hash = choice.hash_key() + if choice_hash in cache.get(op, {}).get(cache_key, {}).get( + precision, {} + ): + # cache hit + timings[choice] = cache[op][cache_key][precision][choice_hash] + else: + # cache miss + hit = False + break + return hit + + local_cache = self.get_local_cache() if config.autotune_local_cache else {} + if (not check_cache(local_cache)) and (benchmark is not None): + # re-benchmark everything to try to get consistent numbers from the same machine + timings = benchmark(choices) + if not all(choice in timings for choice in choices): + missing = [c for c in choices if c not in timings] + raise AssertionError( + f"Benchmark results missing for choices: {missing}" + ) + local_cache.setdefault(op, {}) + local_cache[op].setdefault(cache_key, {}).setdefault(precision, {}) + for choice, timing in timings.items(): + local_cache[op][cache_key][precision][choice.hash_key()] = timing + + self.update_local_cache(local_cache) + + return timings + + +def get_lock_dir() -> str: + lock_dir = os.path.join(cache_dir(), "locks") + if not os.path.exists(lock_dir): + os.makedirs(lock_dir, exist_ok=True) + return lock_dir + + +def sha256_hash(data: bytes) -> str: + return COMPACT_CACHE_KEY_STRATEGY.key(data) + + +def code_hash(code: str | bytes, extra: str | bytes = "") -> str: + if extra: + return CODE_CACHE_KEY_STRATEGY.key(code, extra) + return CODE_CACHE_KEY_STRATEGY.key(code) + + +def get_path( + basename: str, extension: str, specified_dir: str = "" +) -> tuple[str, str, str]: + if specified_dir: + if os.path.isabs(specified_dir): + subdir = specified_dir + else: + subdir = os.path.join(cache_dir(), specified_dir) + else: + subdir = os.path.join(cache_dir(), basename[1:3]) + path = os.path.join(subdir, f"{basename}.{extension}") + return basename, subdir, path + + +def get_hash(content: str | bytes, extra: str = "", hash_type: str = "code") -> str: + if hash_type in {"amdgcn", "code", "ptx", "spv"}: + return code_hash(content, extra) + if hash_type in {"cubin", "hsaco", XPU_KERNEL_FORMAT}: + return code_hash(repr(content)) + raise AssertionError(f"Unknown hash type {hash_type}") + + +class WritableTempFile: + """ + Avoid "Permission denied error" on Windows: + with tempfile.NamedTemporaryFile("w", suffix=".gv") as temp_file: + # Not writable on Windows: + # https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile + + Example: + with WritableTempFile("w", suffix=".gv") as temp_file: + tree.to_dotfile(temp_file.name) + """ + + def __init__( + self, mode: str = "w", *, encoding: Any = None, suffix: Any = None + ) -> None: + self.mode = mode + self.encoding = encoding + self.suffix = suffix + + def __enter__(self) -> _TemporaryFileWrapper[Any]: + self.temp_file = tempfile.NamedTemporaryFile( + self.mode, encoding=self.encoding, suffix=self.suffix, delete=False + ) + return self.temp_file + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.temp_file.close() + try: + os.unlink(self.temp_file.name) + except OSError as e: + if _IS_WINDOWS: + # On Windows, some case temp file is opened and fail to unlink. Need to ignore it. + pass + else: + raise e + + +def write( + content: str | bytes, + extension: str, + extra: str = "", + hash_type: str = "code", + specified_dir: str = "", + key: str | None = None, +) -> tuple[str, str]: + if key is None: + # use striped content to compute hash so we don't end up with different + # hashes just because the content begins/ends with different number of + # spaces. + key = get_hash(content.strip(), extra, hash_type) + basename, _subdir, path = get_path(key, extension, specified_dir) + if not os.path.exists(path): + write_atomic(path, content, make_dirs=True) + return basename, path + + +def write_text(text: str) -> str: + """ + Write the `text` to a file and return the path computed based on the hash. + """ + return write(text, "txt")[1] + + +def write_atomic( + path_: str, + content: str | bytes, + make_dirs: bool = False, + encode_utf_8: bool = False, +) -> None: + # Write into temporary file first to avoid conflicts between threads + # Avoid using a named temporary file, as those have restricted permissions + if not isinstance(content, (str, bytes)): + raise AssertionError("Only strings and byte arrays can be saved in the cache") + path = Path(path_) + if make_dirs: + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = path.parent / f".{os.getpid()}.{threading.get_ident()}.tmp" + write_mode = "w" if isinstance(content, str) else "wb" + with tmp_path.open(write_mode, encoding="utf-8" if encode_utf_8 else None) as f: + f.write(content) + try: + tmp_path.rename(target=path) + except FileExistsError: + if not _IS_WINDOWS: + raise + # On Windows file exist is expected: https://docs.python.org/3/library/pathlib.html#pathlib.Path.rename + # Below two lines code is equal to `tmp_path.rename(path)` on non-Windows OS. + # 1. Copy tmp_file to Target(Dst) file. + shutil.copy2(src=tmp_path, dst=path) + # 2. Delete tmp_file. + os.remove(tmp_path) + + +@dataclasses.dataclass +class TensorMetadataAndValues: + """ + TensorMetadata plus the elements as a list of raw values. + Used for hashing inlined constants. + """ + + tensor_metadata: TensorMetadata + values: list[Any] + + +def _ident(x: T) -> T: + return x + + +def _unpicklable_error(key: str) -> NoReturn: + raise RuntimeError( + f"Attempted to unpickle an object that was pickled only for cache-key " + f"hashing and cannot be reconstructed (key={key!r})" + ) + + +def extract_tensor_metadata_for_cache_key(t: Tensor) -> TensorMetadata: + """ + Extracts the tensor metadata and removes fields of the TensorMetadata + that are not needed for caching + """ + meta = extract_tensor_metadata(t) + if not hasattr(t, "_is_inductor_static"): + meta = dataclasses.replace(meta, storage_offset=0, storage_bytes=None) + + return meta + + +# Types that pickle handles natively via GLOBAL/INST opcodes even though their +# __reduce_ex__ may raise TypeError. We must not treat these as unpicklable in +# reducer_override to avoid infinite recursion. +# We use a tuple for isinstance() checks so subclasses are also matched +# (e.g. ABCMeta is a subclass of type). +_PICKLE_NATIVE_TYPES_TUPLE = ( + FunctionType, + BuiltinFunctionType, + BuiltinMethodType, + MethodType, + type, +) + + +def _get_stable_obj_key(obj: object) -> str | None: + """Produce a deterministic string key for an otherwise-unpicklable object. + + Used by FxGraphCachePickler.reducer_override as a fallback for objects + whose types don't support default pickling (e.g. pybind11 enums). + + The key is derived from the object's fully-qualified type name plus + values obtained via known accessor patterns (pybind11 enum, Python enum, + etc.). Returns ``None`` if no accessor succeeds, letting the caller + decide how to handle the failure. + """ + t = type(obj) + type_id = f"{t.__module__}.{t.__qualname__}" + parts = [] + for accessor in ( + lambda o: o.type.name, # pybind11 enum pattern + lambda o: o.name, # Python enum / named constant pattern + lambda o: o.value, # value-based pattern + ): + try: + parts.append(str(accessor(obj))) + except Exception: + continue + if parts: + return f"{type_id}:{repr(parts)}" + return None + + +class FxGraphCachePickler(pickle.Pickler): + """ + Custom pickler to customize the pickling of some objects (Tensors), only for the + purpose of computing a hash for keying into the FxGraphCache. Tensors contain + objects that don't pickle and/or vary between runs, and we want to capture the + data that allow us to compute a stable, but safe hash. + """ + + # Cache probe results so we only call __reduce_ex__ once per type. + # Maps type -> True (pickleable) or False (unpickleable). + # Class-level because a type's picklability doesn't change at runtime. + _pickleable_type_cache: dict[type, bool] = {} + + def __init__( + self, + gm: torch.fx.GraphModule, + has_user_defined_triton_kernels: bool = False, + device_id_agnostic: bool = False, + ) -> None: + """ + Create an FX graph pickler. If include_non_inlined=True, then pickling will + include the _values_ for all Tensors. (Note that any tensors are constants + attached as attributes to the GraphModule). Otherwise, pickling will include + only the metadata for these tensors. + + If device_id_agnostic=True, device indices in TensorMetadata are normalized + to 0, so that the same graph on different GPUs produces identical bytes. + """ + self._stream = io.BytesIO() + self._device_id_agnostic = device_id_agnostic + super().__init__(self._stream) + + self.dispatch_table = copyreg.dispatch_table.copy() + self.dispatch_table.update( + { + FakeTensor: functools.partial(self._reduce_fake_tensor), + torch.Tensor: functools.partial(self._reduce_tensor), + torch.nn.parameter.Parameter: functools.partial(self._reduce_tensor), + torch.SymInt: functools.partial(self._reduce_symint), + torch.SymBool: functools.partial(self._reduce_symbool), + torch.fx.experimental._backward_state.BackwardState: functools.partial( + self._reduce_unsupported + ), + FakeScriptObject: functools.partial(self._reduce_fake_script_object), + } + ) + if has_user_defined_triton_kernels: + # Need to use runtime type as GraphModule generates a singleton in __new__ function + self.dispatch_table[gm.__class__] = functools.partial( + self._reduce_graph_module + ) + + # Run with pickler.fast so it doesn't intern strings, making the hash result more predictable + # TODO: pickler.fast is technically deprecated. Will this work on new python versions? + self.fast = True + + # pyrefly: ignore [bad-override] + def reducer_override(self, obj: Any) -> Any: + """Fallback reducer for objects not registered in dispatch_table. + + This handles extension types (e.g. pybind11 enums) that don't support + default pickling. Instead of bypassing the FX graph cache entirely, + we serialize a deterministic string representation of the object which + is sufficient for cache-key hashing. + """ + t = type(obj) + # Types already registered or handled by default pickle. + # Use isinstance for _PICKLE_NATIVE_TYPES to cover subclasses + # (e.g. ABCMeta is a subclass of type, and pickle handles all + # type/class objects natively via GLOBAL opcode). + if t in self.dispatch_table or isinstance(obj, _PICKLE_NATIVE_TYPES_TUPLE): + return NotImplemented + # Fast path: type already probed. + if (pickleable := self._pickleable_type_cache.get(t)) is not None: + if not pickleable: + return self._reduce_unpicklable(obj) + return NotImplemented + # First encounter: probe whether the default reduce protocol works. + try: + result = obj.__reduce_ex__(pickle.DEFAULT_PROTOCOL) + except (TypeError, AttributeError, pickle.PicklingError): + self._pickleable_type_cache[t] = False + return self._reduce_unpicklable(obj) + except RuntimeError as e: + if "is not pickleable" in str(e): + self._pickleable_type_cache[t] = False + return self._reduce_unpicklable(obj) + raise + # Default pickling works – let pickle handle it. + self._pickleable_type_cache[t] = True + return result + + @staticmethod + def _reduce_unpicklable(obj: Any) -> Any: + key = _get_stable_obj_key(obj) + if key is None: + raise BypassFxGraphCache( + f"Cannot produce stable cache key for unpicklable type " + f"{type(obj).__qualname__}" + ) + return _unpicklable_error, (key,) + + def _reduce_fake_tensor( + self, t: Tensor + ) -> tuple[Callable[[T], T], tuple[TensorMetadata]]: + """ + Custom reducer to pickle FakeTensors. + """ + metadata = extract_tensor_metadata_for_cache_key(t) + if self._device_id_agnostic: + metadata = dataclasses.replace( + metadata, device=torch.device(metadata.device.type, 0) + ) + return (_ident, (metadata,)) + + def _reduce_tensor( + self, t: Tensor + ) -> tuple[Callable[[T], T], tuple[TensorMetadata | TensorMetadataAndValues]]: + """ + Custom reducer to pickle Tensors. If we see tensors, we know they're constants + stored as attributes on the GraphModule. + """ + from .graph import GraphLowering + + if t.is_mkldnn: + # TODO: These tensors don't currently pickle, so we can't cache a compiled + # graph containing them. Just fail now. If mkldnn tensors get pickling + # support, we can remove this. + CacheabilityValidator.check_tensor(t) + + metadata = extract_tensor_metadata_for_cache_key(t) + if self._device_id_agnostic: + metadata = dataclasses.replace( + metadata, device=torch.device(metadata.device.type, 0) + ) + + # If this is a non-inlined frozen parameter, we consider the metadata only. + if is_frozen_param(t) and not GraphLowering.can_inline_constant(t): + return (_ident, (metadata,)) + + # Very large tensors will be expensive to copy to cpu and hash. Let's at least + # report any slowness. + start = time() + values = t.tolist() + elapsed = time() - start + if elapsed > 1.0: + warnings.warn( + f"FX graph cache copying of a large constant took {elapsed:.1}s. " + "Please file an issue." + ) + + return (_ident, (TensorMetadataAndValues(metadata, values),)) + + def _reduce_symint(self, s: SymInt) -> tuple[Callable[[T], T], tuple[str]]: + """ + Custom reducer to pickle SymInts. + """ + # For hashing purposes, we only care about the name of the symbol and not the + # backed value. We evaluate guards stored with a cached graph to ensure a cached + # entity with SymInt args is safe to reuse. + return (_ident, (str(s),)) + + def _reduce_symbool(self, s: torch.SymBool) -> tuple[Callable[[T], T], tuple[str]]: + """ + Custom reducer to pickle SymBools. + """ + # Same approach as _reduce_symint: use the string representation for + # hashing. Guards ensure correctness on cache reload. + return (_ident, (str(s),)) + + def _reduce_unsupported(self, s: Any) -> NoReturn: + """ + Custom reducer to handle any objects that we don't support and therefore + raise to bypass caching. + """ + CacheabilityValidator.bypass("Reduce unsupported") + + def _reduce_graph_module( + self, gm: torch.fx.GraphModule + ) -> tuple[Any, tuple[dict[str, Any], str]]: + """ + Custom reducer for graph module to handle irrelevant data for user + defined triton kernels + Essentially what we are doing here is a huge hack where user defined + triton kernel contain a dynamo time side table and the arguments to the + call_function are indices into this side table. These arguments are not + for hashing purposes since we included the source code into the cache + key and the numbers are prone to give false negatives due to ordering. + """ + fn, (data, imports) = gm.__reduce__() + code = data["_code"] + code = re.sub(r"kernel_idx = \d+", "", code) + code = re.sub(r"constant_args_idx = \d+", "", code) + data["_code"] = code + return fn, (data, imports) + + def _reduce_fake_script_object( + self, t: FakeScriptObject + ) -> tuple[Callable[..., Any], tuple[Any, ...]]: + if t.real_obj is not None: + cls = type(t.real_obj) + # This is the only case where I'm sure it's cache safe. + # I have not worked out the details for everything else + # but I'm sure we could + if ( + opaque_object.is_custom_class(cls) + and opaque_object.should_hoist(cls) + and not opaque_object.has_members(cls) + ): + return (_ident, (t.script_class_name,)) + if opaque_object.is_custom_class(cls): + # Opaque types (e.g., DeviceMesh) may have cyclic references + # that fast-mode pickling cannot handle. Disable fast mode + # before the subtree is pickled so the memo table tracks cycles. + self.fast = False + return (_ident, (t.wrapped_obj, t.script_class_name, t.real_obj)) + + def dumps(self, obj: Any) -> bytes: + """ + Pickle an object and return a byte string. + """ + try: + self.dump(obj) + return self._stream.getvalue() + except (TypeError, AttributeError, pickle.PicklingError, ValueError) as e: + CacheabilityValidator.bypass_for_pickle_error(e) + except RuntimeError as e: + # pybind11 raises RuntimeError with message like: + # " is not pickleable." + if "pybind11" in str(e) and "is not pickleable" in str(e): + CacheabilityValidator.bypass_for_pickle_error(e) + raise + finally: + # Reset our stream for the next dump. + self._stream.seek(0) + self._stream.truncate(0) + + def get_hash(self, obj: Any) -> str: + """ + Serialize an object and return a hash of the bytes. + """ + serialized_data = self.dumps(obj) + return COMPACT_CACHE_KEY_STRATEGY.key(serialized_data) + + def get_key(self, obj: Any) -> str: + """ + Serialize an object and return an FX graph cache key. + """ + serialized_data = self.dumps(obj) + return FX_GRAPH_CACHE_KEY_STRATEGY.key(serialized_data) + + def debug_lines(self, inp: FxGraphHashDetails) -> list[str]: + """ + Get a printable string describing in more detail all the attributes + comprising an object. Useful for debugging when one graph hashes + to a different value than another. + """ + + def get_str(obj: Any) -> str: + if isinstance(obj, torch.Tensor): + return str(extract_tensor_metadata_for_cache_key(obj)) + elif isinstance(obj, bytes): + val = obj.decode("utf-8", errors="replace") + return val if len(val) <= 1024 else val[:1024] + "..." + elif type(obj) in self.dispatch_table: + # Run the reducer on the object + return str(self.dispatch_table[type(obj)](obj)[1]) + else: + return str(obj) + + lines = [] + for attr, obj in vars(inp).items(): + if isinstance(obj, list): + for ii in range(len(obj)): + h = self.get_hash(obj[ii]) + lines.append(f"[{h}] {attr}[{ii}]: {get_str(obj[ii])}") + elif isinstance(obj, dict): + for k, v in obj.items(): + h = self.get_hash(v) + lines.append(f"[{h}] {attr}[{k}]: {get_str(v)}") + else: + h = self.get_hash(obj) + lines.append(f"[{h}] {attr}: {get_str(obj)}") + return lines + + +def build_code_hash( + roots: list[str] | None, prefix: str, hasher: hashlib._Hash +) -> None: + for lib in sorted(pkgutil.iter_modules(roots, prefix), key=lambda x: x.name): + spec = lib.module_finder.find_spec(lib.name, None) + if spec is None: + raise AssertionError(f"Failed to find spec for module {lib.name}") + module = spec.origin + if module is None: + raise AssertionError(f"Module spec for {lib.name} has no origin") + with open(module, "rb") as f: + hasher.update(spec.name.encode("utf-8")) + hasher.update(f.read()) + if lib.ispkg: + # need to also hash submodules + build_code_hash(spec.submodule_search_locations, f"{spec.name}.", hasher) + + +@torch_key_cache +def torch_key() -> bytes: + """ + Compute a key that contains relevant information about torch source files + """ + with dynamo_timed("inductor_codecache_torch_key", log_pt2_compile_event=False): + if not config.is_fbcode(): + + def get_code_hash(root: str) -> bytes: + # This function isn't meant to be used outside of torch_key, just a + # helper for clarity. Instead, use torch_key() directly when you need + # a hash representing the state of the source code. + extra_files = ( + "codegen/aoti_runtime/interface.cpp", + "codegen/aoti_runtime/streams.h", + "script.ld", + ) + inductor_root = os.path.dirname(__file__) + extra_files = [os.path.join(inductor_root, x) for x in extra_files] + hasher = hashlib.sha256() + hasher.update(torch.__version__.encode("utf-8")) + build_code_hash([root], "", hasher) + for path in extra_files: + if os.path.exists(path): + with open(path, "rb") as f: + hasher.update(f.read()) + return hasher.digest() + + return get_code_hash(_TORCH_PATH) + + from libfb.py import parutil + + return parutil.get_file_contents("torch/src_hash.txt").rstrip().encode("ascii") + + +def get_inductor_root() -> str: + return os.path.dirname(__file__) + + +@dataclasses.dataclass +class OrderedSetHolder: + """ + See FxGraphHashDetails. Holds a sorted list to support stable hashing + of set kwargs. + """ + + items: list[Any] + + +class BypassFxGraphCache(Exception): + """ + Exception to indicate that the FxGraphCache should be bypassed. + """ + + +@dataclasses.dataclass(frozen=True) +class CacheabilityValidator: + """ + Centralized validation for deciding whether an FX graph can use the cache. + + The cache key pickler still defends itself when serializing arbitrary objects, + but non-cacheable inputs should be rejected here before hashing starts. + """ + + gm: torch.fx.GraphModule + example_inputs: Sequence[InputType] = () + fx_kwargs: _CompileFxKwargs | None = None + require_shape_env: bool = True + shape_env: ShapeEnv | None = None + + def validate(self) -> None: + self._check_custom_passes() + self._check_nested_region_inductor_config_patches() + self._check_frozen_params() + self._check_runtime_constant_folding() + self._check_compiler_bisector() + self._check_shape_env() + self.validate_graph(include_constants=True) + self._check_cache_key_object(self.example_inputs) + if self.fx_kwargs is not None: + self._check_cache_key_object(self.fx_kwargs) + + def validate_graph(self, include_constants: bool) -> None: + for module in self.gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + if ( + isinstance(node.target, torch._ops.HigherOrderOperator) + and not node.target.cacheable() + ): + self.bypass( + f"Can't cache HigherOrderOperator: {node.target.name()}" + ) + # TODO: this check is broken in two ways: + # 1. FX uses "get_attr" (with underscore), not "getattr" + # 2. It only checks for ScriptObject, not FakeScriptObject + # Fixing it would also bypass AOTAutogradCache (which calls + # _check_can_cache), so we'd need to decouple the two first. + if node.op == "getattr" and isinstance( + getattr(self.gm, node.target), torch._C.ScriptObject + ): + self.bypass("Can't cache torchbind objects") + if include_constants and node.op == "get_attr": + try: + attr = self._get_attr(module, node.target) + except AttributeError: + continue + self._check_cache_key_object(attr) + + @staticmethod + def check_tensor(t: Tensor) -> None: + if t.is_mkldnn: + CacheabilityValidator.bypass("mkldnn tensors unpickleable") + + @staticmethod + def bypass(reason: str) -> NoReturn: + raise BypassFxGraphCache(reason) + + @staticmethod + def bypass_for_pickle_error(e: Exception) -> NoReturn: + log.warning( + "Failed to pickle cache key", + exc_info=(type(e), e, e.__traceback__), + ) + raise BypassFxGraphCache("Failed to pickle cache key") from e + + @staticmethod + def _get_attr(module: torch.fx.GraphModule, target: str) -> Any: + from torch.fx.graph_module import _get_attr + + return _get_attr(module, target) + + def _check_custom_passes(self) -> None: + # Custom passes must implement the CustomGraphPass or we don't + # know how to include them in the cache key calculation. + # When timing is EARLY, pre-grad passes already ran before the cache + # lookup so there's nothing to validate here. + if resolve_pre_grad_pass_timing() != "early": + for p in get_custom_graph_passes(config.pre_grad_custom_pass): + if not isinstance(p, CustomGraphPass) or not p.uuid(): + self.bypass("Unsupported pre grad custom pass") + for p in itertools.chain( + get_custom_graph_passes(config.post_grad_custom_pre_pass), + get_custom_graph_passes(config.post_grad_custom_post_pass), + ): + if not isinstance(p, CustomGraphPass) or not p.uuid(): + self.bypass("Unsupported post grad custom pass") + # Same with the joint custom passes + for p in itertools.chain( + get_custom_graph_passes(config.joint_custom_pre_pass), + get_custom_graph_passes(config.joint_custom_post_pass), + ): + if not isinstance(p, CustomGraphPass) or not p.uuid(): + self.bypass("Unsupported joint custom pass") + # We should find any users of _pre_fusion_custom_pass and _fuse_ddp_communication_passes + # and ensure they are not passing us raw callables + if config._pre_fusion_custom_pass is not None: + if not isinstance(config._pre_fusion_custom_pass, CustomSchedulerPass): + self.bypass("Unsupported _pre_fusion_custom_pass") + if config._post_fusion_custom_pass is not None: + if not isinstance(config._post_fusion_custom_pass, CustomSchedulerPass): + self.bypass("Unsupported _post_fusion_custom_pass") + for p in config._fuse_ddp_communication_passes: + if callable(p) and not isinstance(p, CustomGraphPass): + self.bypass("Unsupported _fuse_ddp_communication_pass") + + def _check_nested_region_inductor_config_patches(self) -> None: + # Nested region config patches are hashed by pickling their raw value + # (see _collect_nested_region_inductor_config_patches_for_hash). Unlike + # top-level custom passes there is no uuid() fallback, so any callable or + # custom-pass value is conservatively treated as uncacheable, including a + # CustomGraphPass that provides a stable uuid(). + for _, config_patches in _collect_nested_region_inductor_config_patches( + self.gm + ): + for key, value in config_patches.items(): + # A value may be a list of callables (e.g. + # _fuse_ddp_communication_passes), so look inside sequences too. + values = value if isinstance(value, (list, tuple)) else (value,) + if any(callable(v) for v in values): + self.bypass( + f"Uncacheable nested region config '{key}': callable value" + ) + if key in _NESTED_REGION_UNCACHEABLE_CONFIG_KEYS and value: + self.bypass( + f"Uncacheable nested region config '{key}': custom pass" + ) + + def _check_frozen_params(self) -> None: + # Freezing can embed constants that wouldn't be static across runs. + if has_frozen_params(self.gm) and not torch._utils_internal.justknobs_check( + "pytorch/inductor:allow_freezing_with_caching" + ): + self.bypass("Skipping graph with frozen constants") + + def _check_runtime_constant_folding(self) -> None: + if config.aot_inductor.use_runtime_constant_folding: + self.bypass( + "Runtime constant folding can introduce constants that aren't " + "static across runs" + ) + + def _check_compiler_bisector(self) -> None: + from torch._inductor.compiler_bisector import CompilerBisector + + if CompilerBisector.bisection_enabled: + log.debug("don't cache graph when bisect enabled") + self.bypass("compiler bisector enabled") + + def _check_shape_env(self) -> None: + # The treatment of guards in the caching implementation requires that + # we have a shape env. + if self.require_shape_env and self.shape_env is None: + log.debug("fx graph cache no shape env") + self.bypass("No shape env") + + def _check_cache_key_object( + self, + obj: Any, + seen: set[int] | None = None, # noqa: set_linter + ) -> None: + if seen is None: + seen = set() # noqa: set_linter + + obj_id = id(obj) + if obj_id in seen: + return + seen.add(obj_id) + + if isinstance(obj, torch.Tensor): + self.check_tensor(obj) + return + elif isinstance(obj, torch.fx.experimental._backward_state.BackwardState): + self.bypass("Reduce unsupported") + elif isinstance(obj, dict): + for key, value in obj.items(): + self._check_cache_key_object(key, seen) + self._check_cache_key_object(value, seen) + elif isinstance(obj, (list, tuple, AbstractSet)): + for item in obj: + self._check_cache_key_object(item, seen) + + +_warned_pre_grad_pass_missing_uuid: OrderedSet[str] = OrderedSet() + + +def _custom_pass_has_uuid(custom_pass: Any) -> bool: + return isinstance(custom_pass, CustomGraphPass) and custom_pass.uuid() is not None + + +def _custom_pass_name(custom_pass: Any) -> str: + return getattr(custom_pass, "__qualname__", None) or type(custom_pass).__qualname__ + + +def resolve_pre_grad_pass_timing() -> Literal["early", "late"]: + """Resolve the effective pre-grad pass timing from the config. + + "default" is resolved based on whether the custom pass provides a UUID: + passes with a UUID (or no custom pass) run "late" (after cache lookup), + passes without a UUID run "early" (before cache lookup). + + Raises RuntimeError if a custom pass without a UUID is explicitly set to + run "late", since the cache key cannot account for it. + """ + timing: Literal["early", "late", "default"] = config.pre_grad_pass_timing + custom_passes = get_custom_graph_passes(config.pre_grad_custom_pass) + passes_missing_uuid = [ + custom_pass + for custom_pass in custom_passes + if not _custom_pass_has_uuid(custom_pass) + ] + missing_uuid_pass_names = ( + ", ".join(_custom_pass_name(custom_pass) for custom_pass in passes_missing_uuid) + if passes_missing_uuid + else "" + ) + + if timing == "default": + supports_late = not passes_missing_uuid + timing = "late" if supports_late else "early" + if timing == "early" and custom_passes: + if missing_uuid_pass_names not in _warned_pre_grad_pass_missing_uuid: + _warned_pre_grad_pass_missing_uuid.add(missing_uuid_pass_names) + log.warning( + "pre_grad_custom_pass %s does not implement uuid(); " + "falling back to early timing (pre-grad pass cache will be bypassed). " + "Implement uuid() on your CustomGraphPass to enable caching.", + missing_uuid_pass_names, + ) + CompileEventLogger.try_add_pt2_compile( + "backend_compile", + pre_grad_pass_missing_uuid=True, + pre_grad_pass_name=missing_uuid_pass_names, + ) + + if timing == "late" and passes_missing_uuid: + raise RuntimeError( + f"pre_grad_custom_pass {missing_uuid_pass_names} must implement uuid() to run late " + "(after cache lookup). Either implement uuid() or set " + "pre_grad_pass_timing to 'early'." + ) + + return timing + + +@dataclasses.dataclass +class HashableOpaqueValue: + ordinal: int + + +_NESTED_REGION_UNCACHEABLE_CONFIG_KEYS = OrderedSet( + [ + "custom_partitioner_fn", + "joint_custom_post_pass", + "joint_custom_pre_pass", + "post_grad_custom_post_pass", + "post_grad_custom_pre_pass", + "pre_grad_custom_pass", + "_post_fusion_custom_pass", + "_pre_fusion_custom_pass", + ] +) + + +def _collect_nested_region_inductor_config_patches( + gm: torch.fx.GraphModule, +) -> tuple[tuple[str, dict[str, Any]], ...]: + patches: list[tuple[str, dict[str, Any]]] = [] + + def add_patches(name: str, nested_config: Any) -> None: + config_patches = getattr(nested_config, "inductor_config_patches", None) + if config_patches: + patches.append((name, config_patches)) + + for name, module in gm.named_modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + add_patches(name, getattr(module, "meta", {}).get("nested_region_config")) + for node in module.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ): + add_patches( + f"{name}.{node.name}", + node.meta.get("custom", {}).get("nested_region_config"), + ) + return tuple(patches) + + +def _collect_nested_region_inductor_config_patches_for_hash( + gm: torch.fx.GraphModule, +) -> tuple[tuple[str, tuple[tuple[str, Any], ...]], ...]: + return tuple( + ( + name, + tuple((key, config_patches[key]) for key in sorted(config_patches)), + ) + for name, config_patches in _collect_nested_region_inductor_config_patches(gm) + ) + + +class FxGraphHashDetails: + """ + Object to capture all the details for a compiled FX graph relevant to computing + a safe and stable cache key. + """ + + # Excluded kwargs param that are not stable between runs or that + # don't affect compiled output (like compile_region_name which is + # just a debug label). + EXCLUDED_KWARGS = ["graph_id", "compile_region_name"] + TENSOR_METADATA_KEYS = ("val", "example_value") + LIKE_FACTORY_TARGETS = ( + torch.empty_like, + torch.full_like, + torch.ones_like, + torch.rand_like, + torch.randint_like, + torch.randn_like, + torch.zeros_like, + ) + LIKE_FACTORY_PACKETS = ( + torch.ops.aten.empty_like, + torch.ops.aten.full_like, + torch.ops.aten.ones_like, + torch.ops.aten.rand_like, + torch.ops.aten.randint_like, + torch.ops.aten.randn_like, + torch.ops.aten.zeros_like, + ) + + @classmethod + def _contains_tensor(cls, value: Any) -> bool: + if isinstance(value, torch.Tensor): + return True + if isinstance(value, (list, tuple, OrderedSet, frozenset)): + return any(cls._contains_tensor(x) for x in value) + if isinstance(value, dict): + return any( + cls._contains_tensor(x) + for x in itertools.chain(value.keys(), value.values()) + ) + return False + + @classmethod + def _contains_cpu_tensor(cls, value: Any) -> bool: + if isinstance(value, torch.Tensor): + return value.device.type == "cpu" + if isinstance(value, (list, tuple, OrderedSet, frozenset)): + return any(cls._contains_cpu_tensor(x) for x in value) + if isinstance(value, dict): + return any( + cls._contains_cpu_tensor(x) + for x in itertools.chain(value.keys(), value.values()) + ) + return False + + @staticmethod + def _device_type(value: Any) -> str | None: + if isinstance(value, torch.device): + return value.type + if isinstance(value, str): + try: + return torch.device(value).type + except RuntimeError: + return None + return None + + @classmethod + def _is_factory_target( + cls, target: Any, targets: tuple[Any, ...], packets: tuple[Any, ...] + ) -> bool: + if target in targets or target in packets: + return True + overload_packet = getattr(target, "overloadpacket", None) + return overload_packet in packets + + @classmethod + def _tensor_metadata(cls, node: torch.fx.Node) -> tuple[Any, ...]: + return tuple( + node.meta[key] for key in cls.TENSOR_METADATA_KEYS if key in node.meta + ) + + @classmethod + def _factory_device_type(cls, node: torch.fx.Node) -> str | None: + if node.op != "call_function": + return None + + is_default_device_factory = cls._is_factory_target( + node.target, + _default_device_constructor_targets(), + _default_device_constructor_overload_packets(), + ) + is_like_factory = cls._is_factory_target( + node.target, + cls.LIKE_FACTORY_TARGETS, + cls.LIKE_FACTORY_PACKETS, + ) + if not (is_default_device_factory or is_like_factory): + return None + + device_type = cls._device_type(node.kwargs.get("device")) + if device_type is not None: + return device_type + + schema = getattr(node.target, "_schema", None) + if schema is not None: + for arg, value in zip(schema.arguments, node.args): + if arg.name == "device": + device_type = cls._device_type(value) + if device_type is not None: + return device_type + + if is_like_factory: + return None + return torch.device(torch.get_default_device()).type + + @classmethod + def _may_generate_cpu_cpp_code( + cls, gm: torch.fx.GraphModule | None, example_inputs: Sequence[InputType] + ) -> bool: + if cls._contains_cpu_tensor(example_inputs): + return True + if gm is None: + return False + for module in gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + tensor_metadata = cls._tensor_metadata(node) + if cls._contains_cpu_tensor(tensor_metadata): + return True + if not cls._contains_tensor(tensor_metadata) and ( + cls._factory_device_type(node) == "cpu" + ): + return True + return False + + def __init__( + self, + gm: torch.fx.GraphModule | None, + example_inputs: Sequence[InputType], + fx_kwargs: _CompileFxKwargs, + inputs_to_check: Sequence[int], + ) -> None: + self.gm = gm + # Replace opaque references with hashable ordinals. What's important + # is that if the same reference appears twice then it's the same hash + # value for each. + processed_inputs: list[InputType | HashableOpaqueValue] = [] + seen_opaques: dict[int, HashableOpaqueValue] = {} + for inp in example_inputs: + if is_opaque_symbolic_type(type(inp)): + if id(inp) not in seen_opaques: + seen_opaques[id(inp)] = HashableOpaqueValue(len(seen_opaques)) + processed_inputs.append(seen_opaques[id(inp)]) + else: + processed_inputs.append(inp) + self.example_inputs = processed_inputs + self.cache_key_tag = cconfig.cache_key_tag + self.nested_inductor_config_patches = ( + _collect_nested_region_inductor_config_patches_for_hash(gm) + if gm is not None + else () + ) + + # Order kwargs so hashing is stable to changes in kwarg order. Although + # it's technically a _CompileFxKwargs we don't actually need it typed as + # such since we're just using it to generate a hash. + self.fx_kwargs: dict[str, object] = {} + for k, v in sorted(fx_kwargs.items()): + if k not in self.EXCLUDED_KWARGS: + if type(v) in (set, OrderedSet): # noqa: set_linter + # Special case to handle set params. Python sets can't be + # ordered, so sort the elements and store them in a proxy. + self.fx_kwargs[k] = OrderedSetHolder(sorted(v)) # type: ignore[call-overload] + else: + self.fx_kwargs[k] = v + + from torch._higher_order_ops.triton_kernel_wrap import ( + kernel_side_table, + triton_kernel_wrapper_functional, + triton_kernel_wrapper_mutation, + ) + from torch._inductor.codegen.wrapper import ( + user_defined_triton_kernel_transitive_closure_source_code, + ) + + # Node meta will not be part of gm's reduce function, so lets remember + # the kernel source code separately + self.user_defined_triton_source: list[Any] = [] + if gm is not None: + for module in gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in itertools.chain( + module.graph.find_nodes( + op="call_function", target=triton_kernel_wrapper_functional + ), + module.graph.find_nodes( + op="call_function", target=triton_kernel_wrapper_mutation + ), + ): + from triton.runtime.autotuner import Autotuner + + kernel = kernel_side_table.get_kernel(node.kwargs["kernel_idx"]) + configs = None + if isinstance(kernel, Autotuner): + if kernel.configs: + configs = str( + sorted( + sorted(str(kv) for kv in c.all_kwargs().items()) + for c in kernel.configs + ) + ) + kernel = kernel.fn + + kernel_source = ( + user_defined_triton_kernel_transitive_closure_source_code( + kernel + ) + ) + constant_args = kernel_side_table.get_constant_args( + node.kwargs["constant_args_idx"] + ) + self.user_defined_triton_source.append( + (kernel_source, constant_args, configs) + ) + + no_tensor_inputs = not any(isinstance(x, torch.Tensor) for x in example_inputs) + # This device index is usually already encoded by the device of the inputs + # but fx graphs don't necessarily have tensor inputs. If there aren't any, + # we need to guard on the device index in case we allocate cuda tensors + if no_tensor_inputs and torch.accelerator.is_available(): + self.default_cuda_device_index = torch.accelerator.current_device_index() + + # 'Deterministic algorithms' can affect codegen via lowering to cuda kernels. + self.deterministic_algorithms_settings = ( + torch.are_deterministic_algorithms_enabled(), + torch.is_deterministic_algorithms_warn_only_enabled(), + torch.utils.deterministic.fill_uninitialized_memory, # type: ignore[attr-defined] + ) + + # CPU C++ kernels specialize on torch.get_num_threads() when cpp.threads + # is left at its runtime default and dynamic threading is disabled. + # Include that resolved value so FX graph cache entries compiled under + # one thread count are not reused under another. + if ( + config.cpp.threads < 1 + and not config.cpp.dynamic_threads + and self._may_generate_cpu_cpp_code(gm, example_inputs) + ): + self.cpp_runtime_thread_count = parallel_num_threads() + + # Provenance tracking level affects whether provenance data is stored + # in the CompiledFxGraph, so it must be part of the cache key. + # Note: the "trace" prefix is excluded from _cache_config_ignore_prefix, + # so we add this explicitly. + self.provenance_tracking_level = config.effective_provenance_tracking_level() + self.provenance_tracking_to_timeline = ( + config.trace.provenance_tracking_to_timeline + ) + + # Factory ops with dtype=None are lowered using the ambient default dtype, + # so cached code compiled under one default dtype is not valid under another. + self.default_dtype = torch.get_default_dtype() + + # Global settings affecting matmul codegen. + self.cuda_matmul_settings = ( + torch.backends.cuda.matmul.fp32_precision, + torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction, + torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction, + ) + + # compile-on-one-rank changes wrapper and kernel codegen (runtime device + # resolution, DeviceProperties(index=None)) even for graphs that contain no + # coor::current_device node, so an entry compiled with it off must not be served + # to a compile with it on -- that would hand back the device-baked artifact CooR + # exists to avoid. + from torch.fx.experimental.proxy_tensor import _coor_enabled + + self.compile_on_one_rank = _coor_enabled() + + # Include cudagraph annotation in cache key only when it changes + # behavior. When both fwd and bwd are overridden to the same value, + # normalize to a simple boolean (equivalent to flipping the config). + # When fwd and bwd differ, include the full annotation. + if gm is not None: + annotation = gm.meta.get("cudagraph_annotation") + if annotation is not None: + default = config.triton.cudagraphs + if annotation.fwd == annotation.bwd and annotation.fwd is not None: + if annotation.fwd != default: + self.cudagraph_override = annotation.fwd + elif (annotation.fwd is not None and annotation.fwd != default) or ( + annotation.bwd is not None and annotation.bwd != default + ): + self.cudagraph_annotation = annotation + + # Also hash on various system info (including the triton compiler version). + self.torch_version = torch_key() + self.system_info = CacheBase.get_system() + self.inductor_config = config.save_config_portable( + ignore_private_configs=False, readonly_values=True + ) + # pyrefly: ignore [missing-attribute] + self.inductor_config_comms = config_comms.save_config_portable( + ignore_private_configs=False, readonly_values=True + ) + + # Custom passes should provide an ID to hash when they run late (after cache lookup). + if resolve_pre_grad_pass_timing() != "early": + self.pre_grad_custom_pass = self._get_custom_pass_detail( + config.pre_grad_custom_pass + ) + self.post_grad_custom_pre_pass = self._get_custom_pass_detail( + config.post_grad_custom_pre_pass + ) + # TODO: change to more holistic config rather than bundled_autograd_cache + self.precompile_enabled = torch._functorch.config.bundled_autograd_cache + self.post_grad_custom_post_pass = self._get_custom_pass_detail( + config.post_grad_custom_post_pass + ) + self.joint_custom_pre_pass = self._get_custom_pass_detail( + config.joint_custom_pre_pass + ) + self.joint_custom_post_pass = self._get_custom_pass_detail( + config.joint_custom_post_pass + ) + self._pre_fusion_custom_pass = self._get_custom_pass_detail_unsafe( + config._pre_fusion_custom_pass + ) + self._post_fusion_custom_pass = self._get_custom_pass_detail_unsafe( + config._post_fusion_custom_pass + ) + self._fuse_ddp_communication_passes = self._get_custom_pass_detail_unsafe( + config._fuse_ddp_communication_passes + ) + + # Register inductor backends and custom passes and get their UUIDs. + init_backend_registration() + self.custom_backend_passes = tuple( + map(self._get_custom_pass_detail, custom_backend_passes.values()) + ) + + # Save custom inductor codegen configs + self.custom_backend_codegen_configs = { + device: custom_config.save_config_portable( + ignore_private_configs=False, readonly_values=True + ) + for device, custom_config in custom_backend_codegen_configs.items() + if custom_config is not None + } + + # Register the custom partitioner function + self._custom_partitioner_fn = self._get_custom_partitioner_fn_detail( + config.custom_partitioner_fn + ) + + # Include hint overrides in the cache key because _reduce_symint + # only hashes symbol names, not hint values. + self.var_to_hint_override: dict[str, int] = {} + shape_env = FxGraphCache._get_shape_env() + if shape_env is not None and shape_env.var_to_hint_override: + self.var_to_hint_override = { + str(sym): val + for sym, val in sorted( + shape_env.var_to_hint_override.items(), key=lambda x: str(x[0]) + ) + } + + # This is mainly added to handle these two inductor configs, which are (unfortunately) + # sometimes cache safe: + # - _pre_fusion_custom_pass + # - _post_fusion_custom_pass + # - _fuse_ddp_communication_passes + # Their types can be found in `torch/_inductor/config.py`, but: + # - if they are string names, we can cache them safely (one is by default) + # - if any of them are set to custom callables, we will need to cache miss + # Future work is for someone to find any places where these functions are used + # and force them to be of type CustomGraphPass, so we can guarantee serialization. + def _get_custom_pass_detail_unsafe(self, custom_pass: Any) -> Any | None: + if not custom_pass: + return None + if isinstance(custom_pass, list): + return [self._get_custom_pass_detail_unsafe(x) for x in custom_pass] + if isinstance(custom_pass, tuple): + return tuple(self._get_custom_pass_detail_unsafe(x) for x in custom_pass) + if isinstance(custom_pass, str): + return custom_pass + if isinstance(custom_pass, CustomPassBase): + return custom_pass.uuid() + if callable(custom_pass): + # Returning None is safe here because we raise an explicit bypass error + # later if we detect these passes are set to callables + return None + raise AssertionError(f"unknown config type: {str(type(custom_pass))}") + + def _get_custom_pass_detail( + self, + custom_pass: ( + CustomGraphPassCallable + | list[CustomGraphPassCallable] + | tuple[CustomGraphPassCallable, ...] + | CustomGraphModulePass + | None + ), + ) -> Any | None: + if not custom_pass: + # Empty custom-pass lists mean no passes, matching None. + return None + if isinstance(custom_pass, (list, tuple)): + return tuple(self._get_custom_pass_detail(x) for x in custom_pass) + if not isinstance(custom_pass, (CustomGraphPass, CustomGraphModulePass)): + raise AssertionError(f"unknown custom pass type: {str(type(custom_pass))}") + return custom_pass.uuid() + + def _get_custom_partitioner_fn_detail( + self, custom_partitioner_fn: CustomPartitionerFnType + ) -> Any | None: + if not custom_partitioner_fn: + return None + if not isinstance(custom_partitioner_fn, CustomPartitionerFn): + raise AssertionError( + f"Expected CustomPartitionerFn, got {type(custom_partitioner_fn)}" + ) + return custom_partitioner_fn.uuid() + + +def compiled_fx_graph_hash( + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType], + fx_kwargs: _CompileFxKwargs, + inputs_to_check: Sequence[int], +) -> tuple[str, list[str]]: + """ + Generate a unique hash of the FX graph for caching. + """ + details = FxGraphHashDetails(gm, example_inputs, fx_kwargs, inputs_to_check) + has_user_defined_triton_kernels = len(details.user_defined_triton_source) != 0 + pickler = FxGraphCachePickler(gm, has_user_defined_triton_kernels) + + # The prefix distinguishes among the other kinds of objects we + # cache in this module. + key = pickler.get_key(details) + debug_lines = pickler.debug_lines(details) + debug_str = "\n".join(debug_lines) + log.debug(f"FX graph cache hash details for key {key}:\n{debug_str}") # noqa: G004 + return key, debug_lines + + +def add_ephemeral_timeout_increase_for_distributed(time_saved_ns: int) -> int: + """ + Ephemerally increases the NCCL timeout when compiling for a distributed job + Returns amount of seconds increased + """ + if not torch.distributed.is_available() or not torch.distributed.is_initialized(): + return 0 + + increased_timeout_sec = int(time_saved_ns // 1e9) # convert to seconds + + if config.is_fbcode(): + fudge_factor = torch._utils_internal.justknobs_getval_int( + "pytorch/remote_cache:ephemeral_timeout_fudge_factor_percentage" + ) + log.info( + "Ephemeral NCCL timeout increase fudge factor %d and original increase value %d", + fudge_factor, + increased_timeout_sec, + ) + increased_timeout_sec += int(increased_timeout_sec * fudge_factor / 100) + + log.info("Increasing NCCL timeout by %d", increased_timeout_sec) + dist.distributed_c10d._add_ephemeral_timeout_for_all_pgs( + timedelta(seconds=increased_timeout_sec) + ) + return increased_timeout_sec + + +class GuardedCache(Generic[T]): + """ + Mixin for caches that have guards associated with their entries. + """ + + @classmethod + def _get_tmp_dir_for_key(cls: type[GuardedCache[T]], _key: str) -> str: + raise NotImplementedError("Implement _get_tmp_dir_for_key on parent class") + + @classmethod + def _record_result( + cls: type[GuardedCache[T]], + key: str, + local_hit: bool, + local_miss: bool, + remote_hit: bool, + remote_miss: bool, + ) -> None: + raise NotImplementedError("Implement _record_result on parent class") + + @classmethod + def iterate_over_candidates( + cls: type[GuardedCache[T]], + local: bool, + remote_cache: RemoteCache[JsonDataTy] | None, + key: str, + ) -> Generator[tuple[T, bytes, bool], None, None]: + if local: + subdir = cls._get_tmp_dir_for_key(key) + if os.path.exists(subdir): + for path in sorted(os.listdir(subdir)): + if path.startswith("."): + continue # Skip temp files from concurrent write_atomic() calls + try: + with open(os.path.join(subdir, path), "rb") as f: + content = f.read() + yield pickle.loads(content), content, True + except Exception: + log.warning( + "fx graph cache unable to load compiled graph", + exc_info=True, + ) + + if remote_cache: + try: + if (cache_data := remote_cache.get(key)) is not None: + if not isinstance(cache_data, dict): + raise AssertionError( + f"Expected dict from remote cache, got {type(cache_data)}" + ) + data = cache_data["data"] + if not isinstance(data, (str, bytes)): + raise AssertionError( + f"Expected str or bytes for cache data, got {type(data)}" + ) + content = base64.b64decode(data) + yield pickle.loads(content), content, False + except Exception: + log.warning( + "%s unable to load compiled graph", cls.__name__, exc_info=True + ) + + @classmethod + def find_guarded_entry( + cls: type[GuardedCache[T]], + key: str, + local: bool, + remote_cache: RemoteCache[JsonDataTy] | None, + evaluate_guards: Callable[[str, list[int] | list[torch.SymInt]], bool], + hints: list[int], + ) -> tuple[T | None, bytes | None, CacheInfo]: + """ + Find the first cache entry in iterate_over_candidates that passes `evaluate_guards`. + + Args: + key: The cache key to look up + local: Whether to check the local cache + remote_cache: The remote cache to check, if any + evaluate_guards: Function that evaluates whether a guard passes the check, + given a list of hint values and the guard expression. + hints: List of symint hints paired with evaluate_guards + + Returns: + A tuple of (graph, pickled_content) if found, or (None, None) if not found + """ + graph = None + pickled_content = None + result_status = "full_miss" + sample_guards_expr = None + in_local = False + + # Iterate over any entries in the subdir for this key and evaluate + # guards to determine whether there's a hit. + + for candidate, content, in_local in cls.iterate_over_candidates( + local, remote_cache, key + ): + if not hasattr(candidate, "guards_expr"): + raise AssertionError( + f"Cache candidate {type(candidate)} missing 'guards_expr' attribute" + ) + if not candidate.guards_expr: # type: ignore[attr-defined] + # No guards to evaluate, so this is a hit. + graph = candidate + pickled_content = content + result_status = "hit" + break + + # Evaluate the guard expression in the current context. + # If there's not a cache hit, we don't want the evaluation to + # affect the current env, e.g., cause the creation of new guards, + # so we evaluate with the hints instead of the symbols. + hit = bool(evaluate_guards(candidate.guards_expr, hints)) # type: ignore[attr-defined] + if hit: + graph = candidate + pickled_content = content + result_status = "hit" + sample_guards_expr = candidate.guards_expr + break + else: + # At least one guard missed, log this + result_status = "guard_miss" + sample_guards_expr = candidate.guards_expr + + info: CacheInfo = {"cache_status_detailed": result_status} + if sample_guards_expr is not None: + info["cache_status_guard_expr"] = sample_guards_expr + + # Record hits/misses for compilation event logging. The tricky part is that a + # remote hit would imply a local miss (if local caching is enabled). + local_hit = graph is not None and in_local + remote_hit = graph is not None and not in_local + local_miss = (graph is None or remote_hit) and local + remote_miss = graph is None and remote_cache is not None + cls._record_result( + key, + local_hit=local_hit, + local_miss=local_miss, + remote_hit=remote_hit, + remote_miss=remote_miss, + ) + + return graph, pickled_content, info + + @classmethod + def _filter_backed_symints( + cls: type[GuardedCache[T]], inputs: Sequence[InputType] + ) -> list[torch.SymInt]: + """ + Get the backed SymInt objects from the input list. Note that we can never + have guards that depend on unbacked symint. + """ + return [ + s for s in inputs if isinstance(s, torch.SymInt) and has_guarding_hint(s) + ] + + @classmethod + def _get_shape_env(cls: type[GuardedCache[T]]) -> ShapeEnv | None: + """ + Helper to get the shape env from the tracing context. + """ + ctx = torch._guards.TracingContext.try_get() + if not ctx or not ctx.fake_mode: + return None + return ctx.fake_mode.shape_env + + +@CacheArtifactFactory.register +class InductorCacheArtifact(CacheArtifact): + @override + def populate_cache(self) -> None: + FxGraphCache._write_to_local_cache(self.key, self.content) + + @override + @staticmethod + def type() -> str: + return "inductor" + + +class FxGraphCache(GuardedCache[CompiledFxGraph]): + """ + Supports caching and reusing compiled Fx graphs. + + The overall strategy is as follows: + - This cache stores entries on disk. When saving an entry, we can't + serialize callables (that could be C++, Triton, etc.), so we serialize + their own disk cache location. We then recreate the compiled artifact + after fetching from disk. + - For indexing the cache, we gather the fields relevant to identifying an + FxGraph (the graph module, graph inputs, system settings etc.) into an + FxGraphCacheDetails object, pickle it, and compute a hash for the key. + See FxGraphCachePickler. + - Among the metadata we store, we also include a guards expression that's + appropriate for validating any symbols for Tensor arguments that have + symbolic bounds. On cache lookup then, we evaluate those guards in the + current context to validate that a cached entry can be served. + - A given graph could have multiple compiled versions, corresponding to + different sets of guards. Therefore, we store cache entries in the form: + // + - On lookup, we compute the key from the graph details, iterate over all + leaf files in the corresponding subdirectory, deserialize the entry, and + evaluate its guards expression. If the evaluation succeeds, we have a + cache hit. If it fails, we compile the graph and store a new entry. + - Finally, on a cache hit, we need to make sure any guards that would + have been created during compilation are added to the current context. + """ + + # TODO(masnesral): Investigate whether it's beneficial to store compiled graphs + # in an in-memory cache after loading from disk. + @staticmethod + def _get_tmp_dir() -> str: + """ + Get the toplevel temporary directory for storing compiled graphs. + """ + return os.path.join(cache_dir(), "fxgraph") + + @classmethod + def _get_tmp_dir_for_key(cls: type[FxGraphCache], key: str) -> str: + """ + Return the disk location for a given cache key. + """ + return os.path.join(FxGraphCache._get_tmp_dir(), key[1:3], key) + + @classmethod + def _record_result( + cls: type[FxGraphCache], + key: str, + local_hit: bool, + local_miss: bool, + remote_hit: bool, + remote_miss: bool, + ) -> None: + """ + Called by GuardedCache to record hit/miss statistics. + """ + if local_hit: + cache_stats.hit("LocalFxGraphCache") + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "inductor_fx_local_cache_hit_count", + ) + if remote_hit: + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "inductor_fx_remote_cache_hit_count", + ) + CompileEventLogger.try_( + CompileEventLogger.add_to_set_toplevel, + "inductor_fx_remote_cache_hit_keys", + key, + ) + if local_miss: + cache_stats.miss("LocalFxGraphCache") + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "inductor_fx_local_cache_miss_count", + ) + if remote_miss: + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "inductor_fx_remote_cache_miss_count", + ) + CompileEventLogger.try_( + CompileEventLogger.add_to_set_toplevel, + "inductor_fx_remote_cache_miss_keys", + key, + ) + + @staticmethod + def cache_hit_post_compile( + graph: CompiledFxGraph, + cache_info: CacheInfo, + constants: CompiledFxGraphConstants, + ) -> tuple[CompiledFxGraph | None, CacheInfo]: + """ + Cache specific post compile steps that need to run if we find a graph in the cache + This includes putting bundled triton artifacts in the right place, + reloading the PyCodeCache artifact, etc. + + These don't always happen (i.e. on a cache miss, so they are in a separate function from + CompiledFxGraph.post_compile) + """ + if bundle := graph._triton_bundle: + triton_bundler_meta = TritonBundler.read_and_emit(bundle) + if (meta := triton_bundler_meta) is not None: + cache_info["triton_bundler_meta"] = str(meta) + CompileEventLogger.try_add_pt2_compile( + "inductor_compile", cached_kernel_names=meta.cached_kernel_names + ) + CompileEventLogger.try_add_pt2_compile( + "AOTAutogradCache.inductor_load", + cached_kernel_names=meta.cached_kernel_names, + ) + if len(meta.cached_kernel_names) > 0: + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, "num_triton_bundles" + ) + + try: + artifact_path = graph.after_deserialization(constants) + + from .graph import GraphLowering + + # This is used by tests to check the output for specific details. + if GraphLowering.save_output_code is not None: + GraphLowering.save_output_code(graph.source_code) + + except OSError: + # Not expected, but in case the PyCodeCache entry is removed from + # underneath us, treat it as a cache miss and recompile. + return None, cache_info + + inductor_meta = autotune_cache.inductor_meta_from_config() + code = graph.source_code + AutotuneCacheBundler.begin_compile(inductor_meta, code=code) + graph._set_compile_context_for_autotune_cache() + + # Increment the cached metrics/counters by the amounts recorded when the FX + # graph was compiled for this cache entry. Pretending these counters + # were incremented normally is useful for testing with the cache enabled. + metrics.CachedMetricsHelper.apply_deltas(graph.metrics_deltas) + counters["inductor"] += graph.counter_deltas + + output_code_log.debug("Output code: \n%s", code) + output_code_log.debug("Output code written to: %s", artifact_path) + # On cache hit, use artifact path as filename + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_graph_runnable", + "encoding": "string", + }, + payload_fn=lambda: graph.runnable_graph_str, + ) + trace_structured( + "inductor_post_grad_graph", + payload_fn=lambda: graph.inductor_post_grad_graph_str, + ) + trace_structured( + "inductor_output_code", + lambda: { + "filename": artifact_path, + "file_path": os.path.abspath(artifact_path), + }, + payload_fn=lambda: code, + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_provenance_tracking_node_mappings", + "encoding": "json", + }, + payload_fn=lambda: graph.inductor_provenance_mapping_str, + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_provenance_tracking_kernel_stack_traces", + "encoding": "json", + }, + payload_fn=lambda: graph.inductor_provenance_stack_traces_str, + ) + if ( + get_metrics_context().in_progress() + and graph.inductor_provenance_stack_traces_str + ): + get_metrics_context().add_to_set( + "inductor_provenance", graph.inductor_provenance_stack_traces_str + ) + return graph, cache_info + + @staticmethod + def _lookup_graph( + key: str, + example_inputs: Sequence[InputType], + local: bool, + remote_cache: RemoteCache[JsonDataTy] | None, + constants: CompiledFxGraphConstants, + evaluate_guards: Callable[[str, list[int] | list[torch.SymInt]], bool] + | None = None, + ) -> tuple[CompiledFxGraph | None, CacheInfo]: + """ + Lookup a compiled graph in the cache by key. On a hit, return the + deserialized CompiledFxGraph object. On a miss, return None. + `constants` tracks a list of constants, or a way to obtain the list of constants + associated with a given cache entry + `evaluate_guards` allows AOTAutogradCache and other callers to customize + what constitutes a guard success. Normally, a guard hit happens if + `shape_env.evaluate_guards_expression` returns True. + """ + shape_env = FxGraphCache._get_shape_env() + if shape_env is None: + raise AssertionError("ShapeEnv is not set for guard evaluation") + + symints = FxGraphCache._filter_backed_symints(example_inputs) + hints = [guarding_hint_or_throw(s) for s in symints] + + # If this config is turned on, everything is a guard hit and we check nothing + if config.unsafe_skip_cache_dynamic_shape_guards: + # This also makes it so we don't add anything to the dynamic + # shape environment + evaluate_guards = lambda x, y: True # noqa: E731 + + if evaluate_guards is None: + evaluate_guards = shape_env.evaluate_guards_expression + + cache_info: CacheInfo = {} + + # Use the find_graph_for_key method to find a graph for the given key + graph, pickled_content, guard_info = FxGraphCache.find_guarded_entry( + key, local, remote_cache, evaluate_guards, hints + ) + cache_info.update(guard_info) + if graph is None: + return None, cache_info + + # Validate extern_libs (e.g. libdevice) match the current env. + if graph.extern_libs_key is not None: + try: + backend = torch.utils._triton.triton_backend() + current = torch.utils._triton._extern_libs_key(backend) + except Exception: + current = None + if current != graph.extern_libs_key: + cache_info["cache_status_detailed"] = "guard_miss" + return None, cache_info + + CacheArtifactRecorder(InductorCacheArtifact.type(), key).record_if_present( + pickled_content + ) + + # Now re-evaluate with the symints to add any guards to the current env. + if graph.guards_expr: + check = bool(evaluate_guards(graph.guards_expr, symints)) + if check is not True: + raise AssertionError(f"expected check to be True, got {check}") + log.debug( + "fx graph cache key %s post-load guards: %s", key, shape_env.guards + ) + + return FxGraphCache.cache_hit_post_compile(graph, cache_info, constants) + + @staticmethod + def _write_to_local_cache(key: str, content: bytes) -> None: + subdir = FxGraphCache._get_tmp_dir_for_key(key) + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + + # Use a hash of the serialized CompiledFxGraph to get a unique file + # name. The specific name doesn't matter since a lookup involves + # iterating over all entries in the parent subdir. + path = os.path.join(subdir, sha256_hash(content)) + write_atomic(path, content, make_dirs=True) + + @staticmethod + def _save_graph( + key: str, + compiled_graph: OutputCode, + example_inputs: Sequence[InputType], + local: bool, + remote_cache: RemoteCache[JsonDataTy] | None, + ) -> None: + """ + Store a serialized CompiledFxGraph on disk. + """ + from .compile_fx import CompiledFxGraph + + if not isinstance(compiled_graph, CompiledFxGraph): + raise AssertionError(f"serialization for {type(compiled_graph)} NYI") + + # Before serializing, compute the guard expression that will be used to + # ensure that a CompiledFxGraph is valid when loaded from the cache. It's + # sufficient to consider only the SymInt args to the fx graph since the + # Tensor shapes are already captured in the hash for the cache key. Any + # Tensor arg with a symbolic shape will have a SymInt arg for the graph. + shape_env = FxGraphCache._get_shape_env() + if shape_env is None: + raise AssertionError("ShapeEnv is not set for cache serialization") + symints = FxGraphCache._filter_backed_symints(example_inputs) + guards = shape_env.get_pruned_guards(symints) + compiled_graph.guards_expr = shape_env.produce_guards_expression( + placeholders=symints, guards=guards + ) + try: + backend = torch.utils._triton.triton_backend() + compiled_graph.extern_libs_key = torch.utils._triton._extern_libs_key( + backend + ) + except Exception: + pass + disk_compiled_graph = copy(compiled_graph) + disk_compiled_graph.prepare_for_serialization() + + try: + content = pickle.dumps(disk_compiled_graph) + except Exception: + log.warning( + "fx graph cache unable to serialize compiled graph", exc_info=True + ) + counters["inductor"]["fxgraph_cache_pickle_error"] += 1 + return + + try: + CacheArtifactRecorder(InductorCacheArtifact.type(), key).record(content) + if local: + FxGraphCache._write_to_local_cache(key, content) + cache_stats.put("LocalFxGraphCache") + + if remote_cache: + time_taken_ms = int((disk_compiled_graph._time_taken_ns or 0) // 1e6) + cache_data: JsonDataTy = { + "data": base64.b64encode(content).decode("ascii"), + "time_taken_ms": time_taken_ms, + } + remote_cache.put(key, cache_data) + except Exception: + log.warning("fx graph unable to write to cache", exc_info=True) + counters["inductor"]["fxgraph_cache_write_error"] += 1 + + @staticmethod + def _check_for_hop(gm: torch.fx.GraphModule) -> None: + CacheabilityValidator(gm, require_shape_env=False).validate_graph( + include_constants=False + ) + + @staticmethod + def _check_can_cache( + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType] = (), + fx_kwargs: _CompileFxKwargs | None = None, + require_shape_env: bool = True, + ) -> None: + """ + Check some conditions that would preclude caching and raise BypassFxGraphCache + to bypass in case caching is not possible. + """ + shape_env = FxGraphCache._get_shape_env() if require_shape_env else None + CacheabilityValidator( + gm, + example_inputs=example_inputs, + fx_kwargs=fx_kwargs, + require_shape_env=require_shape_env, + shape_env=shape_env, + ).validate() + + @staticmethod + def prepare_key( + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType], + fx_kwargs: _CompileFxKwargs, + inputs_to_check: Sequence[int], + remote: bool, + ) -> tuple[tuple[str, list[str]] | None, CacheInfo]: + """ + Checks that the inductor input is cacheable, then computes + and returns the cache key for the input. + Returns (key_info, cache_info) where: + - key_info is (hash_key, debug_lines), and + - cache_info will contain debug info in the event of BypassFxGraphCache. + + NB: It is possible to have this function return a union instead. But + I personally believe it is more annoying/difficult to read in that format. + """ + try: + FxGraphCache._check_can_cache(gm, example_inputs, fx_kwargs) + key, debug_lines = compiled_fx_graph_hash( + gm, example_inputs, fx_kwargs, inputs_to_check + ) + except BypassFxGraphCache as e: + counters["inductor"]["fxgraph_cache_bypass"] += 1 + log.info("Bypassing FX Graph Cache because '%s'", e) + if remote: + log_cache_bypass("bypass_fx_graph", str(e)) + cache_info: CacheInfo = { + "cache_state": "bypass", + "cache_bypass_reason": str(e), + "cache_event_time": time_ns(), + } + return None, cache_info + # If key exists, then cache_info will come from load_with_key + return (key, debug_lines), {} + + @staticmethod + def get_remote_cache() -> RemoteCache[JsonDataTy] | None: + """ + Attempts to load the remote cache, returns None on error. + """ + cache_id = "fx-graph-v1" + return create_cache( + cache_id, + config.is_fbcode(), + "FbRemoteFxGraphCache", + "RemoteFxGraphCache", + ) + + @staticmethod + def load_with_key( + key: str, + debug_lines: list[str], + example_inputs: Sequence[InputType], + local: bool, + remote_cache: RemoteCache[JsonDataTy] | None, + is_backward: bool, + constants: CompiledFxGraphConstants, + evaluate_guards: Callable[[str, list[int] | list[torch.SymInt]], bool] + | None = None, + ) -> tuple[CompiledFxGraph | None, CacheInfo]: + """ + Lookup the graph with the given key, and return results and metadata. + Doesn't do any logging on its own, because AOTAutograd handles a cache miss + differently from FXGraphCache. + """ + compiled_graph, cache_info = FxGraphCache._lookup_graph( + key, example_inputs, local, remote_cache, constants, evaluate_guards + ) + cache_info: CacheInfo = { + **cache_info, + "key": key, + "components": debug_lines, + "cache_event_time": time_ns(), + } + if compiled_graph is not None: + log.info("fx graph cache hit for key %s", key) + counters["inductor"]["fxgraph_cache_hit"] += 1 + cache_info["cache_state"] = "hit" + + if (time_saved_ns := compiled_graph._time_taken_ns) is not None: + cache_info["time_saved_ns"] = time_saved_ns + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "distributed_ephemeral_timeout_us", + time_saved_ns // 1000, + ) + if ( + ephemeral_increase + := add_ephemeral_timeout_increase_for_distributed(time_saved_ns) + ) != 0: + cache_info["ephemeral_timeout_increase"] = ephemeral_increase + else: + log.info("fx graph cache miss for key %s", key) + counters["inductor"]["fxgraph_cache_miss"] += 1 + cache_info["cache_state"] = "miss" + + return compiled_graph, cache_info + + @staticmethod + def clear() -> None: + """ + Clear out the on-disk cache. + """ + try: + shutil.rmtree(FxGraphCache._get_tmp_dir()) + except FileNotFoundError: + pass + + +@functools.cache +def split_aot_inductor_output_path(path: str) -> tuple[str, str]: + def get_module_ext_type() -> str: + if _IS_WINDOWS: + return ".pyd" + else: + return ".so" + + """Returns the path where the AOT Inductor compiled kernels are stored.""" + if path.endswith(get_module_ext_type()): + return os.path.split(path) + elif path.endswith(".pt2"): + return os.path.split(path) + else: + return path, "" + + +@clear_on_fresh_cache +class CudaKernelParamCache: + cache: dict[str, dict[str, Any]] = {} + cache_clear = staticmethod(cache.clear) + + @classmethod + def set( + cls, + key: str, + params: dict[str, str | None], + cubin: str, + bin_type: str, + asm: str | None = None, + asm_type: str | None = None, + ) -> None: + basename = None + if config.aot_inductor.package_cpp_only: + if not config.triton.unique_kernel_names: + raise AssertionError( + "package_cpp_only requires triton kernel names to be unique" + ) + if not params["mangled_name"]: + raise AssertionError("Missing kernel name") + basename = params["mangled_name"] + + _, bin_path = write( + cubin, + bin_type, + hash_type=bin_type, + specified_dir=split_aot_inductor_output_path( + config.aot_inductor.output_path + )[0], + key=basename, + ) + # Multi-arch mode rewrites cubin_path to an artifact built later. + runtime_bin_path = bin_path + # Retrieve the basename again in case it is a generated hashcode + basename, _ = get_name_and_dir_from_output_file_path(bin_path) + + if config.aot_inductor.emit_multi_arch_kernel: + # Distinct from the single-arch .hsaco the JIT pass reloads, so + # the multi-arch bundle doesn't clobber it. + bin_type_to_ext = { + "cubin": ".fatbin", + XPU_KERNEL_FORMAT: ".spv", + "hsaco": "_multiarch.hsaco", + } + if bin_type not in bin_type_to_ext: + raise AssertionError( + "multi_arch_kernel_binary only supported in CUDA/XPU/ROCm" + ) + base_path, _ = os.path.splitext(bin_path) + bin_path = base_path + bin_type_to_ext[bin_type] + + asm_path: str = "" + + # Kernel assembly/IR requirements for AOT Inductor: + # - CUDA/XPU: Always require PTX/SPV + # - ROCm multi-arch: Require LLVM IR (.ll) for bundle compilation + if ( + config.aot_inductor.emit_multi_arch_kernel + or config.aot_inductor.package_cpp_only + ): + # Allow ROCm single-arch to skip (asm=None OK), require for everything else + if torch.version.hip is None or (asm and asm_type): + if not asm: + raise AssertionError("Missing kernel assembly code") + if not asm_type: + raise AssertionError("Missing kernel assembly type") + + # Cache directory mapping: asm_type → hash_type + # Problem: LLVM IR extension ".ll" isn't a recognized cache category + # Solution: Map to "code" (generic category for non-standard formats) + # Recognized categories: "ptx", "amdgcn", "spv", "code" + hash_kind = asm_type if asm_type in {"amdgcn", "ptx", "spv"} else "code" + + _, asm_path = write( + asm, + asm_type, + hash_type=hash_kind, + specified_dir=split_aot_inductor_output_path( + config.aot_inductor.output_path + )[0], + key=basename, + ) + + params[get_cpp_wrapper_cubin_path_name()] = bin_path + params["runtime_bin_path"] = runtime_bin_path + params["asm"] = asm_path + cls.cache[key] = params + + @classmethod + def get(cls, key: str) -> dict[str, Any] | None: + return cls.cache.get(key, None) + + @classmethod + def get_keys(cls) -> KeysView[str]: + return cls.cache.keys() + + +@clear_on_fresh_cache +class CpuTritonKernelCache: + """AOTI counterpart of CudaKernelParamCache for CPU Triton kernels.""" + + cache: dict[str, dict[str, Any]] = {} + cache_clear = staticmethod(cache.clear) + + @classmethod + def set( + cls, + key: str, + kernel_bytes: bytes, + launcher_bytes: bytes, + kernel_symbol: str, + signature: dict[str, Any], + ) -> None: + out_dir = split_aot_inductor_output_path(config.aot_inductor.output_path)[0] + _, kernel_so_path = write( + kernel_bytes, "so", hash_type="code", specified_dir=out_dir + ) + _, launcher_so_path = write( + launcher_bytes, "so", hash_type="code", specified_dir=out_dir + ) + cls.cache[key] = { + "kernel_so_path": kernel_so_path, + "launcher_so_path": launcher_so_path, + "kernel_symbol": kernel_symbol, + "signature": signature, + } + + @classmethod + def get(cls, key: str) -> dict[str, Any] | None: + return cls.cache.get(key, None) + + @classmethod + def get_keys(cls) -> KeysView[str]: + return cls.cache.keys() + + +class AotCodeCompiler: + """ + Compile AOT Inductor generated code. + """ + + @classmethod + def compile( + cls, + graph: GraphLowering, + wrapper_code: str, + kernel_code: str, + serialized_extern_kernel_nodes: str | None, + *, + device_type: str, + additional_files: list[str], + ) -> list[str | Weights] | str: + """ + Returns the .so path, or returns a list of files that were generated if + config.aot_inductor.package=True. + """ + generated_files: list[str | Weights] = additional_files # type: ignore[assignment] + + _set_gpu_runtime_env() # cpp_extension consults the env + + picked_vec_isa = pick_vec_isa() + vec_isa_cmd_gen = CppBuilder( + name="o", + sources="i", + BuildOption=CppTorchDeviceOptions( + vec_isa=picked_vec_isa, + device_type=device_type, + aot_mode=graph.aot_mode, + ), + ) + # write function will calc source_code hash, the same source code with different + # ISA level should be generate different hash. + # So we need get a command_line which contains isa related parameter as a part of hash key. + # And then pass the command_line to below write function as extra parameter to + # guarantee the source code hash contains ISA difference. + cpp_command = repr(vec_isa_cmd_gen.get_command_line()) + + # Meta internal AOTInductor CPU + use_relative_path = ( + config.is_fbcode() and device_type == "cpu" and graph.aot_mode + ) + + ( + specified_output_path, + specified_artifact_name, + ) = split_aot_inductor_output_path(config.aot_inductor.output_path) + + # TODO (benjaminglass1): the CMake packaging path doesn't support linking files + # built with different flags. Until that's implemented, append the kernel code + # to the wrapper and build everything at max optimization. + if config.aot_inductor.package_cpp_only: + wrapper_code = "\n".join((wrapper_code, kernel_code)) + kernel_code = "" + + wrapper_key, wrapper_path = write( + wrapper_code, + "wrapper.cpp", + extra=cpp_command, + specified_dir=specified_output_path, + key=config.aot_inductor.model_name_for_generated_files, + ) + kernel_code = ( + f"// Triton kernels are embedded as comments in {wrapper_path}\n" + + kernel_code + ) + _, kernel_path = write( + kernel_code, + "kernel.cpp", + extra=cpp_command, + specified_dir=specified_output_path, + key=config.aot_inductor.model_name_for_generated_files, + ) + + header_code = "" + header_path = "" + if not config.aot_inductor.dynamic_linkage: + # to link statically, we also need a header file + with open( + os.path.join( + os.path.dirname(os.path.dirname(__file__)), + "csrc", + "inductor", + "aoti_runtime", + "model.h", + ) + ) as f: + # model_name_for_generated_files is guaranteed to be non-empty when compile_standalone + model_class_name = config.aot_inductor.model_name_for_generated_files + class_name = f"AOTInductorModel{model_class_name}" + header_code = f.read() + + # we replace like this to avoid replacing + # AOTInductorModelBase and AOTInductorModelKernelsBase + header_code = ( + header_code.replace("", f"<{class_name}>") + .replace("AOTInductorModel(", f"{class_name}(") + .replace("AOTInductorModel :", f"{class_name} :") + ) + _, header_path = write( + header_code, + "h", + specified_dir=specified_output_path, + key=model_class_name, + ) + + # Log the AOTInductor wrapper and kernel code, if needed. + with WritableTempFile("w+") as t: + """ + Avoid "Permission denied error" on Windows: + with tempfile.NamedTemporaryFile("w", suffix=".gv") as temp_file: + # Not writable on Windows: + # https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile + + Example: + with WritableTempFile("w", suffix=".gv") as temp_file: + tree.to_dotfile(temp_file.name) + """ + t.writelines((wrapper_code, "\n", kernel_code, "\n")) + t.flush() + V.debug.output_code(t.name, extension="cpp") + + if config.aot_inductor.package: + generated_files.append(wrapper_path) + if not config.aot_inductor.package_cpp_only: + generated_files.append(kernel_path) + if not config.aot_inductor.dynamic_linkage: + generated_files.append(header_path) + + output_code_log.info("AOT wrapper code written to: %s", wrapper_path) + output_code_log.info("AOT kernel code written to: %s", kernel_path) + trace_structured( + "graph_dump", + lambda: { + "name": "inductor_aot_wrapper_code", + "type": "cpp", + "filename": wrapper_path, + }, + payload_fn=lambda: wrapper_code, + ) + trace_structured( + "graph_dump", + lambda: { + "name": "inductor_aot_kernel_code", + "type": "cpp", + "filename": kernel_path, + }, + payload_fn=lambda: kernel_code, + ) + if not config.aot_inductor.dynamic_linkage: + output_code_log.info("Header code written to: %s", header_path) + trace_structured( + "graph_dump", + lambda: { + "name": "inductor_aot_header_code", + "type": "cpp", + "filename": header_path, + }, + payload_fn=lambda: header_code, + ) + + # We use a file lock below to protect FS operations. The lock file + # is scoped to the 'key', so make sure the consts_s is protected + # by the same lock: + wrapper_path_operator = Path(wrapper_path) + kernel_path_operator = Path(kernel_path) + specified_sub_dir = wrapper_path_operator.parent / wrapper_key + if not specified_sub_dir.exists(): + specified_sub_dir.mkdir(exist_ok=True) + cmake_path = str(Path(specified_sub_dir) / "CMakeLists.txt") + + def _compile_consts(consts: bytes | bytearray, platform: str) -> str: + # Load from aot_inductor, and update the value on demand. + use_asm_build: bool = config.aot_inductor.use_consts_asm_build + + if platform == "linux": + if graph.mutated_buffers & OrderedSet(graph.constants.keys()): + # .data section is between .text and .bss. When the size of .data is large, + # during the linking, the relocation of .text against .bss may overflow. + # Rename it to .ldata so that it won't be in between the .text and .bss section + if len(consts) > 2_000_000_000: + raise ValueError( + "Models with buffer mutation included doesn't support constants greater than 2GB!" + ) + section_attr = '.ldata, "aw"' + else: + section_attr = '.lrodata, "a"' + symbol_prefix = "" + elif platform == "darwin": + section_attr = "__DATA,__data" + symbol_prefix = "_" + elif platform == "win32": + symbol_prefix = "" + # ASM build is not supported on Windows, force use CPP build. + use_asm_build = False + else: + raise RuntimeError(f"Unsupported platform: {platform}") + + # Intel compiler failed to compile this manually constructed assembly file. + # Switch XPU to use consts cpp build. + if device_type == "xpu": + use_asm_build = False + + is_large_consts = len(consts) > 1024 + is_zero_size_consts = len(consts) == 0 + + def format_consts_to_gnu_asm( + consts: bytes | bytearray, + align_bytes: int, + symbol_prefix: str, + is_large_consts: bool, + ) -> tuple[str, str]: + consts_asm = f"\t.section\t{section_attr}\n" + consts_asm += f"\t.balign {align_bytes}\n" + consts_asm += f"\t.globl\t{symbol_prefix}_binary_constants_bin_start\n" + consts_asm += f"{symbol_prefix}_binary_constants_bin_start:\n" + if not is_large_consts: + for c in consts: + consts_asm += f"\t.byte {c}\n" + # Add one element even if constants are empty + # Otherwise assembler will not put them in data section + if not consts: + consts_asm += "\t.space 1\n" + else: + consts_asm += "\t.quad 0x1234567899abcdef\n" + consts_asm += f"\t.space {len(consts) - 8}\n" + consts_asm += f".globl\t{symbol_prefix}_binary_constants_bin_end\n" + consts_asm += f"{symbol_prefix}_binary_constants_bin_end:\n" + return consts_asm, "weights.S" + + # Use c++ to convert consts to object file can support more compilers, such as msvc and icx. + def format_consts_to_cpp( + consts: bytes | bytearray, align_bytes: int, symbol_prefix: str + ) -> tuple[str, str]: + consts_size = len(consts) + asan_attr = """#if defined(__clang__) || defined (__GNUC__)\t\n\ +#define ATTRIBUTE_NO_SANITIZE_ADDRESS __attribute__((no_sanitize("address")))\t\n\ +#else\t\n\ +#define ATTRIBUTE_NO_SANITIZE_ADDRESS\t\n\ +#endif\t\n\ +\t\n\ +ATTRIBUTE_NO_SANITIZE_ADDRESS\t\n""" + const_cpp = asan_attr + const_cpp += f"alignas({align_bytes}) extern " + const_cpp += f"unsigned char {symbol_prefix}_binary_constants_bin_start[{consts_size}] = {{\t\n" + count_bytes = 0 + for c in consts: + const_cpp += f"{c}, " + count_bytes = count_bytes + 1 + if count_bytes % 16 == 0: + const_cpp += "\t\n" + const_cpp += "};\t\n" + const_cpp += f"alignas({align_bytes}) extern unsigned char * {symbol_prefix}_binary_constants_bin_end;\t\n" + return const_cpp, "weights.cpp" + + def get_zero_consts_asm_code( + align_bytes: int, + symbol_prefix: str, + ) -> tuple[str, str]: + """ + This function handles zero-sized constants because the C++ standard prohibits zero-length arrays: + https://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c + + On Windows (MSVC): + The compiler reports error C2466 for zero-sized arrays: + https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2466 + Solution: Use assembly compilation to handle this case. + + Why not use Win32 assembly for all paths? + ml64 only supports alignment up to 16 bytes, which isn't optimal for performance. + + Cross-platform implementation: + Linux: Added '-pedantic' to disable zero-sized arrays in C++ compiler + Windows: MSVC naturally rejects zero-sized arrays by default + """ + if _IS_WINDOWS: + # Windows ml64 is max support align to 16, but it is no effect to zero size data. + asm_code = """ +option casemap:none +.data +?_binary_constants_bin_start@@3PAEA: +align 16 +?_binary_constants_bin_end@@3PAEA: +align 16 +public ?_binary_constants_bin_start@@3PAEA +public ?_binary_constants_bin_end@@3PAEA +end +""" + asm_ext = "asm" + else: + asm_code = f"\t.section\t{section_attr}\n" + asm_code += f"\t.balign {align_bytes}\n" + asm_code += ( + f"\t.globl\t{symbol_prefix}_binary_constants_bin_start\n" + ) + asm_code += f"{symbol_prefix}_binary_constants_bin_start:\n" + asm_code += f".globl\t{symbol_prefix}_binary_constants_bin_end\n" + asm_code += f"{symbol_prefix}_binary_constants_bin_end:\n" + asm_ext = "S" + return asm_code, asm_ext + + if use_asm_build: + consts_code, code_ext = format_consts_to_gnu_asm( + consts, ALIGN_BYTES, symbol_prefix, is_large_consts + ) + else: + if is_zero_size_consts: + consts_code, code_ext = get_zero_consts_asm_code( + ALIGN_BYTES, symbol_prefix + ) + else: + consts_code, code_ext = format_consts_to_cpp( + consts, ALIGN_BYTES, symbol_prefix + ) + + _, consts_s = write( + consts_code, + code_ext, + specified_dir=str(specified_sub_dir), + key=config.aot_inductor.model_name_for_generated_files, + ) + consts_s = Path(consts_s) + object_build_options = CppTorchDeviceOptions( + device_type=device_type, + aot_mode=graph.aot_mode, + compile_only=True, + use_relative_path=use_relative_path, + ) + object_builder = CppBuilder( + name=str(consts_s.stem), + sources=str(consts_s), + output_dir=str(consts_s.parent), + BuildOption=object_build_options, + ) + consts_o = object_builder.get_target_file_path() + if use_asm_build is False and is_zero_size_consts: + run_asm_build_object(str(consts_s), consts_o, str(consts_s.parent)) + else: + object_builder.build() + + if is_large_consts and use_asm_build: + with open(consts_o, "r+b") as f: + f.seek(0) + hdr = f.read(1024) + # Search for magic number and write the actual data over it + start_idx = ( + hdr.find(b"\xef\xcd\xab\x99\x78\x56\x34\x12") + if sys.byteorder == "little" + else hdr.find(b"\x12\x34\x56\x78\x99\xab\xcd\xef") + ) + if start_idx == -1: + raise AssertionError( + "Magic number not found in constants header" + ) + f.seek(start_idx) + pos = 0 + while pos < len(consts): + rc = f.write(consts[pos:]) + pos += rc + + # Remove the .S file to save space + os.remove(consts_s) + + return consts_o + + from torch.utils._filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock( + os.path.join(lock_dir, wrapper_key + ".lock"), timeout=LOCK_TIMEOUT + ) + with lock: + if serialized_extern_kernel_nodes: + extern_kernel_nodes_json = str( + wrapper_path_operator.with_suffix(".json") + ) + with open(extern_kernel_nodes_json, "w") as f: + f.write(serialized_extern_kernel_nodes) + + if config.aot_inductor.package: + generated_files.append(extern_kernel_nodes_json) + + metadata = config.aot_inductor.metadata + metadata["AOTI_DEVICE_KEY"] = device_type + + # Add environment information to ensure .so compatibility + metadata.update(get_device_information(device_type)) + + # Save user provided metadata + meta_json = str( + wrapper_path_operator.with_name( + f"{wrapper_path_operator.stem}_metadata.json" + ) + ) + for k, v in config.aot_inductor.metadata.items(): + if not isinstance(k, str) or not isinstance(v, str): + raise AssertionError("Metadata must only contain strings") + + with open(meta_json, "w") as f: + f.write(json.dumps(config.aot_inductor.metadata)) + + kernel_meta_json = str( + kernel_path_operator.with_name( + f"{kernel_path_operator.stem}_metadata.json" + ) + ) + shutil.copy(meta_json, kernel_meta_json) + + if config.aot_inductor.package: + generated_files.append(meta_json) + if not config.aot_inductor.package_cpp_only: + generated_files.append(kernel_meta_json) + + output_so = ( + config.aot_inductor.output_path + if specified_artifact_name + else str(wrapper_path_operator.with_suffix(".so")) + ) + all_cuda = all( + graph.get_original_value_of_constant(name).is_cuda + for name in graph.constants + if name not in graph.folded_constants + ) + + import ctypes + + def _constant_nbytes(t: torch.Tensor) -> int: + if t.numel() == 0: + return 0 + if t.is_mkldnn: + return torch.ops.mkldnn._nbytes(t) + return t.untyped_storage().nbytes() + + if ( + config.aot_inductor.package_constants_in_so + or config.aot_inductor.package_constants_on_disk_format == "binary_blob" + ): + with dynamo_timed( + "aoti_serialize_constants", log_pt2_compile_event=True + ): + constant_names = [ + name + for name in graph.constants + if name not in graph.folded_constants + ] + if constant_names: + from concurrent.futures import ThreadPoolExecutor + + # Compute offsets up front so each worker can write into a + # disjoint slice of a single pre-allocated buffer independently + offsets: list[int] = [] + sizes: list[int] = [] + total_size = 0 + for name in constant_names: + t = graph.get_original_value_of_constant(name) + n = _constant_nbytes(t) + offsets.append(total_size) + sizes.append(n) + total_size += ( + n + if all_cuda + else (n + ALIGN_BYTES - 1) // ALIGN_BYTES * ALIGN_BYTES + ) + + serialized_weights = bytearray(total_size) + # Hold one persistent view so the bytearray can't be resized, + # and cache the base address for pointer arithmetic. + buf_view = (ctypes.c_ubyte * total_size).from_buffer( + serialized_weights + ) + base_addr = ctypes.addressof(buf_view) + + def _worker(i: int) -> None: + n = sizes[i] + if n == 0: + return + t = graph.get_original_value_of_constant(constant_names[i]) + if t.is_mkldnn: + data_ptr = torch.ops.mkldnn.data_ptr(t) + ctypes.memmove(base_addr + offsets[i], data_ptr, n) + else: + # Hold the CPU storage until memmove finishes — + # otherwise it may be freed and data_ptr dangles. + t_cpu = t.untyped_storage().cpu() + ctypes.memmove( + base_addr + offsets[i], t_cpu.data_ptr(), n + ) + + with ThreadPoolExecutor() as pool: + # Consume iterator to surface any worker exceptions. + for _ in pool.map(_worker, range(len(constant_names))): + pass + + del buf_view + else: + serialized_weights = b"" + else: + serialized_weights = b"" + + if config.aot_inductor.package_constants_on_disk_format == "pickle_weights": + # We need to return a storage key here because the original value tensor might be a clone + weights_dict = Weights( + { + graph.allocated_constant_name[name]: ( + graph.get_original_value_of_constant(name), + TensorProperties(graph.constants[name]), + ) + for name in graph.constants + if name not in graph.folded_constants + } + ) + generated_files.append(weights_dict) + + consts_size = len(serialized_weights) + + use_external_weights, use_mmap_weights = determine_aoti_mmap_flags( + consts_size + ) + if use_external_weights and use_mmap_weights: + # Should never reach here, just a check for sanity + raise RuntimeError( + "use_external_weights and use_mmap_weights cannot both be True." + ) + + external_weights_path = None + if use_external_weights: + external_weights_filename = f"{wrapper_path_operator.stem}_weights.blob" + external_weights_path = str( + wrapper_path_operator.with_name(external_weights_filename) + ) + + compile_command: dict[str, Any] = { + "aot_mode": graph.aot_mode, + "device_type": device_type, + "use_mmap_weights": use_mmap_weights, + "use_mmap_weights_external": use_external_weights, + "use_relative_path": use_relative_path, + "vec_isa": picked_vec_isa, + } + # If we're packaging via CMake, we build the whole code at max optimization. + wrapper_build_options = CppTorchDeviceOptions( + compile_only=True, + min_optimize=not config.aot_inductor.package_cpp_only, + **compile_command, + ) + kernel_build_options = CppTorchDeviceOptions( + compile_only=True, + **compile_command, + ) + + # potentially, precompile the AOT header for this device + if config.aot_inductor.precompile_headers and not _IS_WINDOWS: + with dynamo_timed("aoti_precompile_header", log_pt2_compile_event=True): + header_file = _get_cpp_wrapper_header( + device_type, aot_mode=graph.aot_mode + ) + wrapper_build_options.precompiled_header = _precompile_header( + header_file, + cpp_command, + min_optimize=not config.aot_inductor.package_cpp_only, + **compile_command, + ) + if cpp_prefix := _get_cpp_prefix_header(device_type): + kernel_build_options.precompiled_header = _precompile_header( + cpp_prefix, + cpp_command, + **compile_command, + ) + + wrapper_builder = CppBuilder( + name=str(wrapper_path_operator.stem), + sources=wrapper_path, + output_dir=str(wrapper_path_operator.parent), + BuildOption=wrapper_build_options, + ) + wrapper_compile_cmd = wrapper_builder.get_command_line() + wrapper_o = wrapper_builder.get_target_file_path() + + kernel_builder = CppBuilder( + name=str(kernel_path_operator.stem), + sources=kernel_path, + output_dir=str(wrapper_path_operator.parent), + BuildOption=kernel_build_options, + ) + kernel_compile_cmd = kernel_builder.get_command_line() + kernel_o = kernel_builder.get_target_file_path() + + log.debug("aot wrapper compilation command: %s", wrapper_compile_cmd) + log.debug("aot kernel compilation command: %s", kernel_compile_cmd) + if config.aot_inductor.package_cpp_only: + # Not doing the actual compilation here + compile_flags = str( + wrapper_path_operator.with_name( + f"{wrapper_path_operator.stem}_compile_flags.json" + ) + ) + wrapper_build_options.save_flags_to_json(compile_flags) + generated_files.append(compile_flags) + wrapper_builder.save_compile_cmd_to_cmake(cmake_path, device_type) + wrapper_builder.save_src_to_cmake(cmake_path, wrapper_path) + generated_files.append(cmake_path) + else: + try: + wrapper_builder.build() + except (exc.CppCompileError, SkipFrame) as e: + if " is too big to optimize" in str(e): + raise RuntimeError( + "Please use torch._inductor.config.aot_inductor.compile_wrapper_opt_level = 'O0' flag." + ) from e + raise e + kernel_builder.build() + + if not use_mmap_weights: + aot_constants = serialized_weights + magic_number = 0 + if use_external_weights: + aot_constants = struct.pack("q", consts_size) + if external_weights_path is None: + raise AssertionError( + "external_weights_path must be set when use_external_weights is True" + ) + # For external weights, write weights to separate file and embed minimal placeholder + with open(external_weights_path, "wb") as f_weights: + f_weights.write(serialized_weights) + generated_files.append(external_weights_path) + else: + # we'll append weights binary to the end of .so file and mmap it when loading + magic_number = cast( + int, torch.randint(0, torch.iinfo(torch.int64).max, (1,)).item() + ) + aot_constants = struct.pack("qq", consts_size + 8, magic_number) + + consts_o = _compile_consts(aot_constants, sys.platform) + custom_obj_idx = 0 + # Note that custom_objs_config.json file is different from the model_constants_config.json file produced + # in package_sigmoid(). The keys in custom_objs_config.json directly correspond to the arg name in extern + # nodes json. The key in model_constants_config.json produced by package_sigmoid is the attribute name in the + # user model code. + + qual_name_to_id = {} # Map from constant name to its name in constants folder + for custom_obj_idx, (name, constant) in enumerate( + graph.torchbind_constants.items() + ): + if isinstance( + constant, torch._library.fake_class_registry.FakeScriptObject + ): + constant = constant.real_obj + if not isinstance(constant, torch._C.ScriptObject): + raise AssertionError(f"Expected ScriptObject, got {type(constant)}") + custom_obj_name = f"{CUSTOM_OBJ_FILENAME_PREFIX}{custom_obj_idx}" + + log.debug("saving script object %s as %s", name, custom_obj_name) + + qual_name_to_id[name] = custom_obj_name + custom_obj_bytes = torch._C._pickle_save(constant) + custom_obj_path = os.path.join( + wrapper_path_operator.parent, custom_obj_name + ) + + write_atomic(custom_obj_path, custom_obj_bytes, True) + generated_files.append(custom_obj_path) + + if qual_name_to_id: + constants_config_json = os.path.join( + wrapper_path_operator.parent, "custom_objs_config.json" + ) + with open(constants_config_json, "w") as f: + f.write(json.dumps(qual_name_to_id)) + generated_files.append(constants_config_json) + + cache_cls = { + "rocm": ROCmCodeCache, + "cuda": CUDACodeCache, + "xpu": XPUCodeCache, + }.get("rocm" if torch.version.hip else device_type, CUDACodeCache) + + gpu_codecache = cache_cls() + gpu_kernels_o = gpu_codecache.aot_kernels_o.copy() + # clear the list of aot kernels after each linking + gpu_codecache.aot_kernels_o.clear() + + if gpu_kernels_o: + if config.aot_inductor.emit_multi_arch_kernel: + raise AssertionError( + "TODO: add emit_multi_arch_kernel support for cutlass kernels" + ) + + cubins_o = [] + asm_files = [] + fatbin_cmds: list[tuple[str, str, str | None, str | None]] = [] + if not _IS_WINDOWS: + cubins_to_embed: list[tuple[str, str]] = [] + ld, objcopy = get_ld_and_objcopy(use_relative_path) + kernels = getattr(V.graph.wrapper_code, "_kernel_name_to_body", {}) + for kernel_name, value in CudaKernelParamCache.cache.items(): + if kernel_name not in kernels: + # It is possible that CudaKernelParamCache contains more Triton kernels + # than what the current graph uses + continue + + if asm_file := value["asm"]: + asm_files.append(asm_file) + + cubin_file = value[get_cpp_wrapper_cubin_path_name()] + if ( + config.aot_inductor.emit_multi_arch_kernel + and device_type == "cuda" + ): + if torch.version.hip is None: + fatbin_cmds.append( + ( + asm_file, + cubin_file, + value.get("runtime_bin_path"), + value.get("cuda_arch"), + ) + ) + + else: + # ROCm multi-arch: compile LLVM IR to multi-arch bundle + from torch._inductor.rocm_multiarch_utils import ( + compile_multiarch_bundle_from_llvm_ir, + ) + + # pyrefly: ignore [unbound-name] + if not os.path.exists(asm_file): + raise RuntimeError( + f"Multi-arch ROCm compilation requires LLVM IR file, " + # pyrefly: ignore [unbound-name] + f"but {asm_file} not found. " + f"Ensure asm_type='ll' is captured in triton_heuristics.py" + ) + + # Compile for multiple archs and bundle them + success = compile_multiarch_bundle_from_llvm_ir( + # pyrefly: ignore [unbound-name] + llvm_ir_path=asm_file, + output_bundle_path=cubin_file, + target_archs=None, + ) + + if not success: + raise RuntimeError( + f"Failed to compile multi-arch bundle for kernel {kernel_name}. " + f"Check that ROCm toolchain is available and LLVM IR is valid." + ) + + log.info("Created multi-arch bundle: %s", cubin_file) + + if config.aot_inductor.embed_kernel_binary: + cubins_to_embed.append((cubin_file, kernel_name)) + + # Build CUDA fatbins in parallel before cubin embedding below. + if fatbin_cmds: + from concurrent.futures import ThreadPoolExecutor + + nvcc = cuda_compile_utils._cuda_compiler() + fatbinary = shutil.which("fatbinary") + if nvcc is not None and (nvcc_dir := os.path.dirname(nvcc)): + candidate = os.path.join(nvcc_dir, "fatbinary") + if os.path.exists(candidate): + fatbinary = candidate + + def _compile_fatbin( + asm_cubin_and_raw: tuple[str, str, str | None, str | None], + ) -> None: + asm_f, cubin_f, raw_cubin_f, cuda_arch = asm_cubin_and_raw + cmd = _cuda_fatbin_command( + asm_f, cubin_f, raw_cubin_f, nvcc, fatbinary, cuda_arch + ) + try: + subprocess.run( + cmd, capture_output=True, text=True, check=True + ) + except subprocess.CalledProcessError as e: + print( + f"{shlex.join(cmd)} failed with:\nstdout:\n{e.stdout}\nstderr:\n{e.stderr}", + file=sys.stderr, + ) + raise + + with ( + dynamo_timed("aoti_compile_fatbin", log_pt2_compile_event=True), + ThreadPoolExecutor() as pool, + ): + list(pool.map(_compile_fatbin, fatbin_cmds)) + + if cubins_to_embed: + # Batch all cubins into a single .o using .incbin assembly. + # This replaces N * 3 subprocess calls (ld + 2x objcopy per + # cubin) with a single compiler invocation. + try: + combined_obj = batch_convert_cubins_to_obj( + cubins_to_embed, + os.path.dirname(output_so), + cpp_compiler=get_cpp_compiler(), + ) + cubins_o.append(combined_obj) + except subprocess.CalledProcessError: + log.warning( + "Batched cubin embedding failed, " + "falling back to per-cubin objcopy" + ) + for cubin_file, kernel_name in cubins_to_embed: + cubins_o.append( + convert_cubin_to_obj( + cubin_file, kernel_name, ld, objcopy + ) + ) + + output_name, output_dir = get_name_and_dir_from_output_file_path(output_so) + so_build_options = CppTorchDeviceOptions( + vec_isa=picked_vec_isa, + device_type=device_type, + aot_mode=graph.aot_mode, + use_relative_path=use_relative_path, + ) + + if gpu_kernels_o and device_type == "xpu": + so_build_options = CppTorchDeviceOptions( + compiler="icpx", + vec_isa=picked_vec_isa, + device_type=device_type, + aot_mode=graph.aot_mode, + use_relative_path=use_relative_path, + extra_flags=[ + "-fsycl", + "-fsycl-targets=intel_gpu_pvc", + "-Xspirv-translator", + ( + "-spirv-ext=" + "+SPV_INTEL_split_barrier," + "+SPV_INTEL_2d_block_io," + "+SPV_INTEL_subgroup_matrix_multiply_accumulate" + ), + ], + ) + + obj_srcs = [wrapper_o, kernel_o, consts_o, *gpu_kernels_o, *cubins_o] + so_builder = CppBuilder( + name=output_name, + sources=obj_srcs, + output_dir=output_dir, + BuildOption=so_build_options, + ) + link_cmd = so_builder.get_command_line() + output_so = so_builder.get_target_file_path() + + log.debug("aot linkage command: %s", link_cmd) + + # Append cmds to the end of codegen-ed wrapper file + with open(wrapper_path, "a") as f: + f.write("\n") + f.write(f"// Compile cmd\n// {wrapper_compile_cmd}\n") + f.write(f"// Link cmd\n// {link_cmd}\n") + + with open(kernel_path, "a") as f: + f.write("\n") + f.write(f"// Compile cmd\n// {kernel_compile_cmd}\n") + f.write(f"// Link cmd\n// {link_cmd}\n") + + if config.aot_inductor.package_cpp_only: + linker_flags = str( + wrapper_path_operator.with_name( + f"{wrapper_path_operator.stem}_linker_flags.json" + ) + ) + so_build_options.save_flags_to_json(linker_flags) + generated_files.append(linker_flags) + generated_files.append(_LINKER_SCRIPT) + + # If we only want to package the cpp, then we need to save the + # weights separately into a bin, and we also need to prevent compiling the so + if use_mmap_weights: + weight_file = str( + wrapper_path_operator.with_name( + f"{wrapper_path_operator.stem}_serialized_weights.bin" + ) + ) + with open(weight_file, "wb") as f_weights: + f_weights.write(serialized_weights) + f_weights.write(struct.pack("q", magic_number)) + + generated_files.append(weight_file) + else: + # TODO: unify to always use mmap_weights + generated_files.append(consts_o) + so_builder.save_src_to_cmake(cmake_path, consts_o) + + # Different CMake strategies for CUDA vs ROCm: + # - CUDA: Save asm for CMake to recompile (user has nvcc) + # - ROCm: Link pre-compiled bundle (user may lack dev tools) + if ( + config.aot_inductor.emit_multi_arch_kernel + and torch.version.hip is None + ): + so_builder.save_kernel_asm_to_cmake(cmake_path, asm_files) + generated_files.extend(asm_files) + else: + # ROCm multi-arch + all single-arch: Link pre-compiled objects + # Bundle already embedded in .o files - just link into .so + obj_srcs = [*gpu_kernels_o, *cubins_o] + generated_files.extend(obj_srcs) + for obj in obj_srcs: + so_builder.save_src_to_cmake(cmake_path, obj) + + so_builder.save_link_cmd_to_cmake(cmake_path) + else: + so_builder.build() + for o_file in obj_srcs: + if o_file in gpu_kernels_o: + continue + # Remove these as they are not needed anymore + os.remove(o_file) + + if use_mmap_weights: + if config.aot_inductor.cross_target_platform == "windows": + raise RuntimeError( + "when cross_target_platform is windows, use_mmap_weights should not be true." + ) + + def get_page_size() -> int: + # Don't use resource.getpagesize() on Windows, as it is a Unix specific package + # as seen in https://docs.python.org/2/library/resource.html + if _IS_WINDOWS: + from ctypes import ( + byref, + Structure, + windll, # pyrefly: ignore [missing-module-attribute] + ) + from ctypes.wintypes import DWORD, LPVOID, WORD + + class SYSTEM_INFO(Structure): + _fields_ = [ + ("wProcessorArchitecture", WORD), + ("wReserved", WORD), + ("dwPageSize", DWORD), + ("lpMinimumApplicationAddress", LPVOID), + ("lpMaximumApplicationAddress", LPVOID), + ("dwActiveProcessorMask", DWORD), + ("dwNumberOfProcessors", DWORD), + ("dwProcessorType", DWORD), + ("dwAllocationGranularity", DWORD), + ("wProcessorLevel", WORD), + ("wProcessorRevision", WORD), + ] + + si = SYSTEM_INFO() + windll.kernel32.GetSystemInfo(byref(si)) + sys_page_size = si.dwPageSize + else: + import resource + + sys_page_size = resource.getpagesize() + + return sys_page_size + + page_size_ = get_page_size() + page_size = max(16384, page_size_) + + with open(output_so, "a+b") as f_so: + so_size = f_so.tell() + # Page align the weights + f_so.write(b" " * (page_size - so_size % page_size)) + f_so.write(serialized_weights) + f_so.write(struct.pack("q", magic_number)) + + if config.aot_inductor.package: + generated_files.append(output_so) + + if config.effective_provenance_tracking_level() != 0: + kernel_info = torch._inductor.debug.create_kernel_information_json() + kernel_info_json = os.path.join( + wrapper_path_operator.parent, "kernel_information.json" + ) + with open(kernel_info_json, "w") as f: + f.write(json.dumps(kernel_info, indent=4)) + generated_files.append(kernel_info_json) + + if config.aot_inductor.package: + # We want to return the directory that contains all the AOTI + # generated files, not just the so + # return os.path.split(output_so)[0] + return generated_files + + return output_so + + +_libgomp: CDLL | None = None + + +def custom_op_wrapper(op: str, *args: Any) -> list[c_void_p] | c_void_p | None: + # This function will be called from generated cpp wrapper code in the JIT mode. + # Because tensors will be passed in as AtenTensorHandle, we need to explicitly convert them. + def convert_arg(arg: Any) -> Any: + if str(type(arg)) == "": + # No easy way to do isinstance check on PyCapsule + return torch._C._aoti.alloc_tensor_by_stealing_from_void_ptr(arg) + elif isinstance(arg, (list, tuple)): + return type(arg)(convert_arg(a) for a in arg) + else: + return arg + + converted_args = [convert_arg(arg) for arg in args] + + if not op.startswith("torch.ops."): + raise AssertionError(op + " can not be called through custom_op_wrapper") + func = None + for i, s in enumerate(op.split(".")): + if i == 0: + func = importlib.import_module(s) + func = getattr(func, s) + + if not callable(func): + raise AssertionError(op + " can not be loaded through custom_op_wrapper") + + # convert any kwarg-only arguments to kwargs + kwargs = dict() + # pyrefly: ignore [missing-attribute] + for func_arg, conv_arg in zip(func._schema.arguments, converted_args): + if func_arg.kwarg_only: + kwargs[func_arg.name] = conv_arg + if kwargs: + del converted_args[-len(kwargs) :] + + result = func(*converted_args, **kwargs) + if result is None: + return None + + if isinstance(result, (list, tuple)): + # unsafe_alloc_void_ptrs_from_tensors expects result contains tensor only + result = [torch.tensor([]) if r is None else r for r in result] + for r in result: + if not isinstance(r, torch.Tensor): + raise AssertionError(op + " returns a list of non-tensors") + return torch._C._aoti.unsafe_alloc_void_ptrs_from_tensors(result) # type: ignore[arg-type] + + if not isinstance(result, torch.Tensor): + raise AssertionError(op + " returns a non-tensor") + return torch._C._aoti.unsafe_alloc_void_ptr_from_tensor(result) + + +# Precompiled headers are persistent past program runtime, but associated with one +# specific compiler version and set of flags. We explicitly use default_cache_dir here +# because these headers need to be global, rather than ignored by fresh_cache. +_HEADER_DIR = os.path.join(default_cache_dir(), "precompiled_headers") +_HEADER_LOCK_DIR = os.path.join(_HEADER_DIR, "locks") +_VEC_ISA_CPP_SOURCE_MARKERS = ("at::vec::", "prod_masked_reduce(") + + +@functools.cache +def _precompile_header( + header: str, + hashable_cmd_line: str, + **compile_command: Any, +) -> str: + if _IS_WINDOWS: + raise AssertionError( + "CppBuilder does not currently support precompiling on Windows!" + ) + + # extra_flags carries link-time inputs (e.g. precompiled kernel .so paths + # for CUTLASS/ROCm CK under JIT cpp_wrapper). Preprocessing and PCH + # compilation don't link, so g++ rejects .so paths as unused linker + # input. Strip them here. + compile_command.pop("extra_flags", None) + + # Get the preprocessed output from the header file to be precompiled. This allows + # us to properly invalidate the file cache when any header dependency changes. This + # is thread-safe, as each thread will get its own temporary directory. + # + # N.B. we can't use NamedTemporaryFile here because Windows errors out on attempts + # to read from a file with an open write handle. + with tempfile.TemporaryDirectory() as preprocessing_dir: + preprocessing_header = Path(preprocessing_dir) / "header.hpp" + preprocessing_header.write_text(f"#include <{header}>\n") + preprocessor = CppBuilder( + name=str(preprocessing_header)[:-4], # strip off the .hpp extension + sources=str(preprocessing_header), + BuildOption=CppTorchDeviceOptions(**compile_command, preprocessing=True), + ) + preprocessor.build() + + def _get_file_checksum(filename: str) -> str: + """Reading the whole preprocessed header in for hashing is very expensive, + but calling a fast hashing utility in a subprocess is cheap.""" + # If Windows support needs to be added here, use certutil -hashfile. + cmd_output = subprocess.run( + ("openssl", "sha512", filename), capture_output=True, text=True + ) + return cmd_output.stdout.split()[-1] + + preprocessor_hash = _get_file_checksum(preprocessor.get_target_file_path()) + + header_build_option = CppTorchDeviceOptions(**compile_command, precompiling=True) + header_hash, header_full_path = write( + content=f"#include <{header}>\n", + extension="h", + extra=( + hashable_cmd_line + + preprocessor_hash + + get_compiler_version_info(header_build_option.get_compiler()) + ), + specified_dir=_HEADER_DIR, + ) + cpp_builder = CppBuilder( + name=header_full_path, + sources=header_full_path, + BuildOption=header_build_option, + ) + # _worker_compile_cpp will automatically ignore any compilation whose result already + # exists, so this is always safe. + os.makedirs(_HEADER_LOCK_DIR, exist_ok=True) + _worker_compile_cpp( + os.path.join(_HEADER_LOCK_DIR, f"{header_hash}.lock"), + (cpp_builder,), + ) + + return header_full_path + + +def _get_cpp_prefix_header(device: str) -> str | None: + if device.startswith("cpu"): + return "torch/csrc/inductor/cpp_prefix.h" + return None + + +def _get_cpp_wrapper_header(device: str, aot_mode: bool = False) -> str: + """Given a device type (and optionally whether we're in AOT Inductor mode), returns + the path to the cpp_wrapper header file to be precompiled.""" + base_device = device.split(":", maxsplit=1)[0] + is_array_ref = config.aot_inductor.allow_stack_allocation and base_device == "cpu" + return ( + "torch/csrc/inductor/" + f"{'aoti_include' if aot_mode else 'cpp_wrapper'}/" + f"{'array_ref' if is_array_ref else base_device}.h" + ) + + +def _resolve_needs_vec_isa( + base_device_type: str, source: str | None, explicit: bool | None +) -> bool: + if explicit is not None: + return explicit + if source is None: + return False + if base_device_type == "cpu": + return True + return any(marker in source for marker in _VEC_ISA_CPP_SOURCE_MARKERS) + + +@clear_on_fresh_cache +class CppCodeCache: + """Compiles and caches C++ libraries. Users of this class supply the source code to + be compiled, while compilation flags are set by CppBuilder.""" + + cache: dict[str, Callable[[], CDLL | ModuleType]] = {} + cache_clear = staticmethod(cache.clear) + cpp_compile_command_flags: dict[str, Any] = {} + + @staticmethod + def _load_library_inner(path: str, key: str) -> CDLL | ModuleType: + return cdll.LoadLibrary(path) + + @classmethod + def _load_library(cls, path: str, key: str) -> CDLL | ModuleType: + try: + result = cls._load_library_inner(path, key) + result.key = key # type: ignore[union-attr] + return result + except (ImportError, OSError) as e: + if "gomp" in str(e) and os.path.exists("/usr/lib64/libgomp.so.1"): + # hacky workaround for fbcode/buck + global _libgomp + _libgomp = cdll.LoadLibrary("/usr/lib64/libgomp.so.1") + result = cls._load_library_inner(path, key) + result.key = key # type: ignore[union-attr] + return result + if "failed to map segment from shared object" in str(e): + raise OSError( + f"{e}. The most common reason this may occur is if the {tempfile.gettempdir()} folder " + "is mounted with noexec (e.g., by default Docker mounts tmp file systems " + f"as noexec). Please remount {tempfile.gettempdir()} with exec enabled, or set another " + "temporary directory with TORCHINDUCTOR_CACHE_DIR environment variable." + ) from e + raise + + @classmethod + def _get_uncompiled_header(cls, device: str) -> str | None: + """ + Given a device type, returns the path to a CPP header file to be precompiled. + """ + return None + + @classmethod + def load_async( + cls, + main_code: str, + device_type: str = "cpu", + submit_fn: Any = None, + extra_flags: Sequence[str] = (), + optimized_code: str | None = None, + needs_vec_isa: bool | None = None, + kernel_needs_vec_isa: bool | None = None, + ) -> Any: + """Compile and load a C++ library. Returns a callable that returns the loaded + library.""" + base_device_type = device_type.split(":", maxsplit=1)[0] + main_needs_vec_isa = _resolve_needs_vec_isa( + base_device_type, main_code, needs_vec_isa + ) + kernel_needs_vec_isa = _resolve_needs_vec_isa( + base_device_type, optimized_code, kernel_needs_vec_isa + ) + picked_vec_isa = ( + pick_vec_isa() + if main_needs_vec_isa or kernel_needs_vec_isa + else invalid_vec_isa + ) + shared_compile_command = { + **cls.cpp_compile_command_flags, + "device_type": device_type, + "extra_flags": extra_flags, + "use_relative_path": config.is_fbcode(), + } + main_compile_command = { + **shared_compile_command, + "vec_isa": picked_vec_isa if main_needs_vec_isa else invalid_vec_isa, + } + optimized_compile_command = { + **shared_compile_command, + "vec_isa": picked_vec_isa if kernel_needs_vec_isa else invalid_vec_isa, + } + + _set_gpu_runtime_env() # cpp_extension consults the env + + # Note the distinction between the two booleans. We do minimal optimization if + # the optimized_code argument is present at all, since that's how the user of + # this function opts in, but we do compilation and linking in one step if the + # optimized_code argument is empty (as a micro-optimization). + # On GPU the C++ wrapper is just glue — the real kernels are compiled + # separately by Triton/CUDA. Always use -O1 to cut compile time. + min_optimize = optimized_code is not None or device_type != "cpu" + main_build_option = CppTorchDeviceOptions( + compile_only=bool(optimized_code), + min_optimize=min_optimize, + # pyrefly: ignore [bad-argument-type] + **main_compile_command, + ) + optimized_build_option = CppTorchDeviceOptions( + # pyrefly: ignore [bad-argument-type] + compile_only=True, + # pyrefly: ignore [bad-argument-type] + **optimized_compile_command, + ) + + def get_hashable_command_line(build_option: BuildOptionsBase) -> str: + """Writing the code to file will calculate a hash, which we need to vary if + the command line flags change. This implements a mostly-generic way of + validating that.""" + return CppBuilder( + name="o", sources="i", BuildOption=build_option + ).get_command_line() + + main_cmd_line = get_hashable_command_line(main_build_option) + optimized_cmd_line = get_hashable_command_line(optimized_build_option) + + key, main_path = write( + main_code, "main.cpp", extra=f"{optimized_code} {main_cmd_line}" + ) + + # Don't bother writing if the argument is empty. + if optimized_code: + _, optimized_path = write( + optimized_code, "optimized.cpp", extra=optimized_cmd_line + ) + else: + # Unused, but makes type checkers happy. + optimized_path = os.devnull + + if key not in cls.cache: + from torch.utils._filelock import FileLock + + lock_path = os.path.join(get_lock_dir(), key + ".lock") + future: Future[Any] | None = None + lib = None + + # if requested, pre-compile any headers + if config.cpp_cache_precompile_headers and not _IS_WINDOWS: + if header := cls._get_uncompiled_header(device_type): + main_build_option.precompiled_header = _precompile_header( + header, + main_cmd_line, + min_optimize=min_optimize, + **main_compile_command, + ) + + # Currently, the optimized_code field is only used for cpp kernel code, + # so go ahead and precompile the relevant header here. Revisit this + # decision if that ever changes. + if optimized_code and (header := _get_cpp_prefix_header(device_type)): + optimized_build_option.precompiled_header = _precompile_header( + # pyrefly: ignore [unbound-name] + header, + optimized_cmd_line, + **optimized_compile_command, + ) + + main_name, output_dir = get_name_and_dir_from_output_file_path(main_path) + main_builder = CppBuilder( + name=main_name, + sources=main_path, + BuildOption=main_build_option, + output_dir=output_dir, + ) + + if optimized_code: + optimized_name, _ = get_name_and_dir_from_output_file_path( + optimized_path + ) + optimized_builder = CppBuilder( + name=optimized_name, + sources=optimized_path, + BuildOption=optimized_build_option, + output_dir=output_dir, + ) + + linker = CppBuilder( + name=main_name, + sources=[ + main_builder.get_target_file_path(), + optimized_builder.get_target_file_path(), + ], + # pyrefly: ignore [bad-argument-type] + BuildOption=CppTorchDeviceOptions(**shared_compile_command), + output_dir=output_dir, + ) + + worker_fn = functools.partial( + _worker_compile_cpp, + lock_path, + (main_builder, optimized_builder, linker), + ) + binary_path = normalize_path_separator(linker.get_target_file_path()) + else: + worker_fn = functools.partial( + _worker_compile_cpp, lock_path, (main_builder,) + ) + binary_path = normalize_path_separator( + main_builder.get_target_file_path() + ) + + def load_fn() -> Any: + nonlocal lib + if lib is None: + if future is not None: + future.result() + result = worker_fn() + if result is not None: + raise AssertionError( + f"worker_fn expected to return None, got {type(result)}" + ) + lib = cls._load_library(binary_path, key) + if lib is None: + raise AssertionError( + f"Failed to load library from {binary_path}" + ) + return lib + + if submit_fn is not None: + with FileLock(lock_path, timeout=LOCK_TIMEOUT): + if not os.path.exists(binary_path): + future = submit_fn(worker_fn) + + cls.cache[key] = load_fn + + return cls.cache[key] + + @classmethod + def load(cls, *args: Any, **kwargs: Any) -> Any: + return cls.load_async(*args, **kwargs)() + + +def _worker_compile_cpp( + lock_path: str, + cpp_builders: Sequence[CppBuilder], +) -> None: + from torch.utils._filelock import FileLock + + with FileLock(lock_path, timeout=LOCK_TIMEOUT): + for builder in cpp_builders: + if not os.path.exists(builder.get_target_file_path()): + builder.build() + + +# Customized Python binding for cpp kernels +@clear_on_fresh_cache +class CppPythonBindingsCodeCache(CppCodeCache): + cache: dict[str, Callable[[], CDLL | ModuleType]] = {} + _loaded_module_names: OrderedSet[str] = OrderedSet() + + @staticmethod + def cache_clear() -> None: + CppPythonBindingsCodeCache.cache.clear() + for name in CppPythonBindingsCodeCache._loaded_module_names: + sys.modules.pop(name, None) + CppPythonBindingsCodeCache._loaded_module_names.clear() + + cpp_compile_command_flags = { + # kernels have no dependency on libtorch + "include_pytorch": False, + "shared": True, + } + entry_function = "kernel" + call_entry_function = "kernel({}); Py_RETURN_NONE;" + extra_parse_arg = "" + suffix_template = textwrap.dedent( + """ + // Python bindings to call {entry_func}(): + #define PY_SSIZE_T_CLEAN + #include + #include + #include + #include + + // This is defined in guards.cpp so we don't need to import PyTorch headers that are slooow. + // We manually link it below to workaround issues with fbcode build. + static void* (*_torchinductor_pyobject_tensor_data_ptr)(PyObject* obj); + + template static inline T parse_arg(PyObject* args, size_t n) {{ + static_assert(std::is_pointer_v, "arg type must be pointer or long"); + return static_cast(_torchinductor_pyobject_tensor_data_ptr(PyTuple_GET_ITEM(args, n))); + }} + template <> inline int64_t parse_arg(PyObject* args, size_t n) {{ + auto result = PyLong_AsSsize_t(PyTuple_GET_ITEM(args, n)); + if(result == -1 && PyErr_Occurred()) [[unlikely]] + throw std::runtime_error("expected int arg"); + return result; + }} + template <> inline uintptr_t parse_arg(PyObject* args, size_t n) {{ + auto result = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, n)); + if(result == reinterpret_cast(-1) && PyErr_Occurred()) [[unlikely]] + throw std::runtime_error("expected int arg"); + return reinterpret_cast(result); + }} + template <> inline float parse_arg(PyObject* args, size_t n) {{ + auto result = PyFloat_AsDouble(PyTuple_GET_ITEM(args, n)); + if(result == -1.0 && PyErr_Occurred()) [[unlikely]] + throw std::runtime_error("expected float arg"); + return static_cast(result); + }} + + {extra_parse_arg} + + static PyObject* {entry_func}_py(PyObject* self, PyObject* args) {{ + try {{ + if(!PyTuple_CheckExact(args)) [[unlikely]] + throw std::runtime_error("tuple args required"); + if(PyTuple_GET_SIZE(args) != {arg_len}) [[unlikely]] + throw std::runtime_error("requires {arg_len} args"); + {call_entry_func} + }} catch(std::exception const& e) {{ + PyErr_SetString(PyExc_RuntimeError, e.what()); + return nullptr; + }} catch(...) {{ + PyErr_SetString(PyExc_RuntimeError, "unhandled error"); + return nullptr; + }} + }} + + static PyMethodDef py_methods[] = {{ + {{"{entry_func}", {entry_func}_py, METH_VARARGS, ""}}, + {{NULL, NULL, 0, NULL}}}}; + + static struct PyModuleDef py_module = + {{PyModuleDef_HEAD_INIT, "{entry_func}", NULL, -1, py_methods}}; + + PyMODINIT_FUNC PyInit_{entry_func}(void) {{ + const char* str_addr = std::getenv("_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR"); + if(!str_addr) {{ + PyErr_SetString(PyExc_RuntimeError, "_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR must be set"); + return nullptr; + }} + + char* endptr = nullptr; + errno = 0; + uintptr_t addr = std::strtoull(str_addr, &endptr, 10); + if(errno != 0 || endptr == str_addr || addr == 0) {{ + PyErr_SetString(PyExc_RuntimeError, "Failed to parse _TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR"); + return nullptr; + }} + _torchinductor_pyobject_tensor_data_ptr = + reinterpret_cast(addr); + PyObject* module = PyModule_Create(&py_module); + if (module == NULL) {{ + return NULL; + }} + #ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED); + #endif + return module; + }} + """ + ) + + @classmethod + # pyrefly: ignore [bad-override] + def _load_library_inner(cls, path: str, key: str) -> ModuleType: + os.environ["_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR"] = str( + torch._C._dynamo.guards._torchinductor_pyobject_tensor_data_ptr # type: ignore[attr-defined] + ) + module_name = f"{key}.{cls.entry_function}" + try: + return sys.modules[module_name] + except KeyError: + pass + spec = importlib.util.spec_from_file_location(module_name, path) + if spec is None: + raise AssertionError( + f"Failed to create module spec for {module_name} from {path}" + ) + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + CppPythonBindingsCodeCache._loaded_module_names.add(module_name) + if spec.loader is None: + raise AssertionError(f"Module spec for {module_name} has no loader") + spec.loader.exec_module(module) + return module + + @classmethod + def _get_uncompiled_header(cls, device: str) -> str | None: + return _get_cpp_prefix_header(device) + + @classmethod + def load_pybinding_async( + cls, + argtypes: Sequence[str], + main_code: str, + device_type: str = "cpu", + needs_vec_isa: bool | None = None, + kernel_needs_vec_isa: bool | None = None, + num_outputs: int = -1, + submit_fn: Any = None, + extra_flags: Sequence[str] = (), + kernel_code: str | None = None, + ) -> Any: + """ + Wrap a C++ function in fast Python bindings. + + Args: + argtypes: The types of args to ENTRY_FUNCTION(), e.g. ["float*", "long"] + main_code: C++ source code containing ENTRY_FUNCTION(). Will be built at + -O3 if kernel_code is None (to maximize performance in any kernels that + are present), or -O1 otherwise (to minimize compile time). + needs_vec_isa: Whether the generated wrapper requires CPU vectorized + host helpers. If omitted, this is inferred from the generated + source as a conservative fallback. + kernel_needs_vec_isa: Whether the separately compiled kernel source + requires CPU vectorized host helpers. Only relevant when + kernel_code is provided. + kernel_code: If present, C++ source code that will be built at -O3 and + linked to main_code. + + Returns: + A python version of ENTRY_FUNCTION() + """ + parseargs = ", ".join( + f"parse_arg<{argtype.replace('const ', '')}>(args, {n})" + for n, argtype in enumerate(argtypes) + ) + suffix = cls.suffix_template.format( + arg_len=len(argtypes), + call_entry_func=cls.call_entry_function.format(parseargs), + entry_func=cls.entry_function, + extra_parse_arg=cls.extra_parse_arg.format(array_len=num_outputs), + ) + get_result = cls.load_async( + main_code + suffix, + device_type, + submit_fn=submit_fn, + extra_flags=extra_flags, + optimized_code=kernel_code, + needs_vec_isa=needs_vec_isa, + kernel_needs_vec_isa=kernel_needs_vec_isa, + ) + result = None + + def future() -> Any: + nonlocal result + if result is None: + result = get_result() + if not isinstance(result, ModuleType): + raise AssertionError(f"Expected ModuleType, got {type(result)}") + return getattr(result, cls.entry_function) + + return future + + @classmethod + def load_pybinding(cls, *args: Any, **kwargs: Any) -> Any: + return cls.load_pybinding_async(*args, **kwargs)() + + +@clear_on_fresh_cache +class CppWrapperCodeCache(CppPythonBindingsCodeCache): + cache: dict[str, Callable[[], CDLL | ModuleType]] = {} + + @staticmethod + def cache_clear() -> None: + CppWrapperCodeCache.cache.clear() + + @classmethod + def load_pybinding(cls, *args: Any, **kwargs: Any) -> Any: + # The cpp_wrapper host glue is compiled synchronously here (in the JIT + # torch.compile path this runs while importing the generated wrapper + # module, and in AOTI it runs during the autotune pass). Time it under a + # dedicated key so the host C++ cold-compile cost is attributed to + # cpp_wrapper instead of being hidden inside the generic + # PyCodeCache.load_by_key_path timer. + with dynamo_timed("cpp_wrapper_compile", log_pt2_compile_event=True): + return super().load_pybinding(*args, **kwargs) + + cpp_compile_command_flags = { + "include_pytorch": True, + "shared": True, + } + entry_function = "inductor_entry_cpp" + call_entry_function = "return inductor_entry_cpp({});" + extra_parse_arg = textwrap.dedent( + """ + #include + + static inline std::vector unpack_tensor_handle_list(PyObject* pyvec) {{ + std::vector result; + size_t result_len = PyList_GET_SIZE(pyvec); + result.reserve(result_len); + for (size_t i = 0; i < result_len; i++) {{ + PyObject* item = PyList_GET_ITEM(pyvec, i); + if (item == Py_None) {{ + result.push_back(nullptr); + continue; + }} + // AtenTensorHandle is essentially a pointer + void* elem = PyCapsule_GetPointer(item, NULL); + if (elem == nullptr && PyErr_Occurred()) {{ + PyErr_Clear(); + throw std::runtime_error( + "expected input handle to be a PyCapsule or None" + ); + }} + result.push_back(reinterpret_cast(elem)); + }} + return result; + }} + + static inline PyObject* pack_tensor_handle_list(const std::array& arr) {{ + PyObject* result = PyList_New({array_len}); + for (size_t i = 0; i < {array_len}; i++) {{ + PyObject *elem = + arr[i] == nullptr + ? Py_NewRef(Py_None) + // Store AtenTensorHandle as PyCapsulate + : PyCapsule_New(reinterpret_cast(arr[i]), NULL, NULL); + PyList_SET_ITEM(result, i, elem); + }} + return result; + }} + + template <> inline std::vector parse_arg>(PyObject* args, size_t n) {{ + return unpack_tensor_handle_list(PyTuple_GET_ITEM(args, n)); + }} + + PyObject* inductor_entry_cpp(std::vector&& input_handles) {{ + // For outputs, we only allocate an array to hold returned tensor handles, + // not the actual output tensor storage. + std::array output_handles{{}}; + try {{ + inductor_entry_impl(input_handles.data(), output_handles.data()); + if (PyErr_Occurred()) {{ + return nullptr; + }} + return pack_tensor_handle_list(output_handles); + }} catch(std::exception const& e) {{ + PyErr_SetString(PyExc_RuntimeError, e.what()); + return nullptr; + }} catch(...) {{ + PyErr_SetString(PyExc_RuntimeError, "unhandled error"); + return nullptr; + }} + }} + """ + ) + + @classmethod + def _get_uncompiled_header(cls, device: str) -> str | None: + return _get_cpp_wrapper_header(device) + + +@clear_on_fresh_cache +class HalideCodeCache(CppPythonBindingsCodeCache): + cache: dict[str, Callable[[], ModuleType | CDLL]] = {} + cache_clear = staticmethod(cache.clear) + _standalone_runtime_path: str | None = None + prefix = textwrap.dedent( + """ + #include "{halideruntime_h}" + #include "{headerfile}" + #include + #include + + namespace c10 {{ + inline long div_floor_integer(long a, long b) {{ + if ((a<0) != (b<0)) {{ + const auto quot = a / b; + const auto rem = a % b; + return rem ? quot - 1 : quot; + }} + return a / b; + }} + }} + """ + ) + glue_template_cpp = prefix + textwrap.dedent( + """ + void kernel({argdefs}) {{ + {buffers} + int err = halide_kernel({buffer_names}); + if(err != 0) throw std::runtime_error("halide_kernel failed"); + }} + """ + ) + glue_template_cuda = prefix + textwrap.dedent( + """ + #include + static const halide_device_interface_t* cuda_interface = halide_cuda_device_interface(); + + void kernel({argdefs}, uintptr_t stream) {{ + {buffers} + int err = halide_kernel(reinterpret_cast(stream), {buffer_names}); + if(err != 0) throw std::runtime_error("halide_kernel failed"); + }} + """ + ) + standalone_runtime_cuda_init = textwrap.dedent( + """ + #include "{}" + #include + + static int acquire_context(void* user_context, + void** cuda_context_out, + bool create) {{ + return cuCtxGetCurrent(reinterpret_cast(cuda_context_out)); + }} + + static int release_context(void* user_context) {{ + return 0; + }} + + static int get_stream(void* user_context, + void* cuda_context, + void** stream_out) {{ + *stream_out = user_context; + return 0; + }} + + static int register_halide_hooks() {{ + halide_set_cuda_acquire_context(&acquire_context); + halide_set_cuda_release_context(&release_context); + halide_set_cuda_get_stream(&get_stream); + return 0; + }} + + int inductor_register_halide_hooks_result = register_halide_hooks(); + """ + ) + + @classmethod + def _codegen_buffer(cls, name: str, arg: HalideInputSpec, cuda: bool) -> list[str]: + if arg.shape is None: + raise AssertionError(f"arg.shape is None for {name}") + if arg.stride is None or len(arg.shape) != len(arg.stride): + raise AssertionError( + f"arg.stride is None or shape/stride length mismatch for {name}: " + f"shape={arg.shape}, stride={arg.stride}" + ) + if arg.offset is None: + raise AssertionError(f"arg.offset is None for {name}") + data_ptr = f"{arg.alias_of or arg.name} + {arg.offset}" + if cuda: + device = f"reinterpret_cast({data_ptr})" + device_interface = "cuda_interface" + host = "nullptr" + flags = "halide_buffer_flag_device_dirty" + else: + device = "0" + device_interface = "nullptr" + host = f"reinterpret_cast({data_ptr})" + flags = "halide_buffer_flag_host_dirty" + + dims = [] + for size, stride in zip(arg.shape, arg.stride): + dims.append(f"halide_dimension_t(0, {size}, {stride})") + + return [ + f"halide_buffer_t {name};", + f"halide_dimension_t {name}_dims[] = {{{', '.join(dims)}}};" + if len(dims) > 0 + else f"halide_dimension_t * {name}_dims = nullptr;", + f"{name}.device = {device};", + f"{name}.device_interface = {device_interface};", + f"{name}.host = {host};", + f"{name}.flags = {flags};", + f"{name}.type = {arg.halide_type()};", + f"{name}.dimensions = {len(dims)};", + f"{name}.dim = {name}_dims;", + f"{name}.padding = nullptr;", + ] + + @classmethod + def _codegen_glue(cls, meta: HalideMeta, headerfile: object) -> str: + is_cuda = meta.is_cuda() + if is_cuda is not ("user_context" in meta.target): + raise AssertionError( + f"is_cuda={is_cuda} inconsistent with meta.target={meta.target}" + ) + if "no_runtime" not in meta.target: + raise AssertionError(f"'no_runtime' not found in meta.target={meta.target}") + buffers = [] + buffer_names = [] + for i, arg in enumerate(meta.argtypes): + if arg.is_buffer(): + # pyrefly: ignore [bad-argument-type] + buffer_names.append(f"&hl_buf_{i}") + buffers.extend(cls._codegen_buffer(f"hl_buf_{i}", arg, is_cuda)) + else: + if "*" in arg.ctype: + raise AssertionError( + f"Unexpected pointer type in non-buffer arg: {arg.ctype}" + ) + # pyrefly: ignore [bad-argument-type] + buffer_names.append(arg.name) + buffers = "\n".join([f" {line}" for line in buffers]).lstrip() + + glue_template = cls.glue_template_cuda if is_cuda else cls.glue_template_cpp + glue_code = glue_template.format( + halideruntime_h=cls.find_header( + "HalideRuntimeCuda.h" if is_cuda else "HalideRuntime.h" + ), + headerfile=headerfile, + argdefs=", ".join( + f"{a.bindings_type()} {a.name}" + for a in meta.argtypes + if a.alias_of is None + ), + buffers=buffers, + buffer_names=", ".join(buffer_names), + ) + return glue_code + + @classmethod + @functools.cache + def config_hash(cls) -> str: + command_gen = CppBuilder( + name="O", + sources="I", + BuildOption=CppOptions(), + ) + command_line = command_gen.get_command_line() + return sha256_hash( + "\n".join( + [ + cls.glue_template_cpp, + cls.glue_template_cuda, + cls.standalone_runtime_cuda_init, + command_line, + ] + ).encode("utf-8") + ) + + @staticmethod + def _search_for_file(suffix: str, errmsg: str) -> str: + spec = importlib.machinery.PathFinder.find_spec("halide") + if spec is None or not spec.submodule_search_locations: + raise RuntimeError("halide python bindings not installed") + try: + search = spec.submodule_search_locations[0] + for file in os.listdir(search): + if file.endswith(".so"): + try: + out = subprocess.check_output( + ["ldd", os.path.join(search, file)] + ) + except subprocess.SubprocessError: + continue + m = re.search(r"(/.*)/libHalide.so", out.decode("utf-8")) + if m: + path = os.path.join(os.path.abspath(m.group(1)), suffix) + if os.path.exists(path): + return os.path.abspath(path) + except Exception as e: + raise RuntimeError(errmsg) from e + raise RuntimeError(errmsg) + + @staticmethod + @functools.cache + def find_libautoschedule(name: str) -> str: + sofile = f"libautoschedule_{name.lower()}.so" + if "HALIDE_LIB" in os.environ: + path = os.path.join(os.environ["HALIDE_LIB"], sofile) + if os.path.exists(path): + return path + errmsg = ( + f"Can't find {sofile}, set env HALIDE_LIB to the directory containing it" + ) + return HalideCodeCache._search_for_file(sofile, errmsg) + + @staticmethod + @functools.cache + def find_header(name: str) -> str: + if "HALIDE_INCLUDE" in os.environ: + path = os.path.join(os.environ["HALIDE_INCLUDE"], name) + if os.path.exists(path): + return path + if "HALIDE_LIB" in os.environ: + path = os.path.abspath( + os.path.join(os.environ["HALIDE_LIB"], f"../include/{name}") + ) + if os.path.exists(path): + return path + errmsg = ( + f"Can't find {name}, set env HALIDE_INCLUDE to the directory containing it" + ) + return HalideCodeCache._search_for_file(f"../include/{name}", errmsg) + + @classmethod + def generate_halide_async( + cls, meta: HalideMeta, source_code: str, submit_fn: Any = None + ) -> Callable[[], Any]: + dirpath = Path( + get_path( + code_hash( + source_code, + extra=repr((cls.config_hash(), meta)), + ), + "halide", + )[2] + ) + os.makedirs(dirpath, exist_ok=True) + wait_for_compile = None + genfile = str(dirpath / "generate_kernel.py") + libfile = str(dirpath / "halide_kernel.a") + headerfile = str(dirpath / "halide_kernel.h") + donefile = str(dirpath / "done") + lockfile = str(dirpath / "lock") + need_compile = not os.path.exists(donefile) + jobs: list[Any] = [] + if need_compile: + write_atomic(genfile, source_code) + cmd = [ + sys.executable, + genfile, + "-g", + "kernel", + "-o", + f"{dirpath}", + "-f", + "halide_kernel", + "-e", + "static_library,h,schedule", + ] + if meta.scheduler: + cmd.extend(["-p", cls.find_libautoschedule(meta.scheduler)]) + cmd.extend(meta.args()) + jobs.append(functools.partial(subprocess.check_call, cmd)) + + binding_types = [ + arg.bindings_type() for arg in meta.argtypes if arg.alias_of is None + ] + if meta.is_cuda(): + binding_types.append("uintptr_t") # stream + bindings_future = cls.load_pybinding_async( + binding_types, + cls._codegen_glue(meta, headerfile), + extra_flags=(libfile, cls.build_standalone_runtime()), + submit_fn=jobs.append if need_compile else None, + device_type="cuda" if meta.is_cuda() else "cpu", + ) + + if need_compile: + jobs.append(functools.partial(touch, donefile)) + task = functools.partial(_worker_task_halide, lockfile, jobs) + if submit_fn: + wait_for_compile = submit_fn(task).result + else: + task() + + def load() -> Callable[[], Any]: + if wait_for_compile: + wait_for_compile() + return bindings_future() + + return load + + @classmethod + def generate_halide(cls, *args: Any, **kwargs: Any) -> Callable[[], Any]: + return cls.generate_halide_async(*args, **kwargs)() + + @classmethod + def build_standalone_runtime(cls) -> str: + if cls._standalone_runtime_path and os.path.exists( + cls._standalone_runtime_path + ): + return cls._standalone_runtime_path + device_type = "cuda" if torch.cuda.is_available() else "cpu" + libname = "libStandaloneHalideRuntime.so" + target = "host-cuda" if device_type == "cuda" else "host" + if cls._standalone_runtime_path: + if os.path.exists(cls._standalone_runtime_path): + raise AssertionError( + f"Standalone runtime path already exists: {cls._standalone_runtime_path}" + ) + # We hit this case in unittests when we run with fresh_cache() + # Generating a fresh runtime over and over causes errors because we initialize + # cuda hundreds of times in the same process and run out of file descriptors. + # Workaround by jail breaking the current fresh_cache(). + base = default_cache_dir() + else: + base = cache_dir() + dirpath = Path(base) / f"halide-runtime-{target}-{cls.config_hash()}" + os.makedirs(dirpath, exist_ok=True) + done_file = str(dirpath / "done") + lock_file = str(dirpath / "lock") + hook_file = str(dirpath / "hooks.cpp") + a_file = str(dirpath / "standalone_halide_runtime.a") + so_file = str(dirpath / libname) + if not os.path.exists(done_file): + import halide as hl # type: ignore[import-untyped,import-not-found] + + from torch.utils._filelock import FileLock + + with FileLock(lock_file, LOCK_TIMEOUT): + if not os.path.exists(done_file): + with open(hook_file, "w") as f: + if device_type == "cuda": + f.write( + cls.standalone_runtime_cuda_init.format( + cls.find_header("HalideRuntimeCuda.h") + ) + ) + hl.compile_standalone_runtime(a_file, hl.Target(target)) + + name, output_dir = get_name_and_dir_from_output_file_path(so_file) + halide_cmd_gen = CppBuilder( + name=name, + sources=[hook_file, a_file], + output_dir=output_dir, + BuildOption=CppTorchDeviceOptions( + device_type=device_type, + ), + ) + + subprocess.check_call( + shlex.split(halide_cmd_gen.get_command_line()) + ) + touch(done_file) + if not os.path.exists(so_file): + raise AssertionError(f"Halide runtime .so not found at {so_file}") + cls._standalone_runtime_path = so_file + return so_file + + @classmethod + def _get_uncompiled_header(cls, device: str) -> str | None: + """Header precompiling is currently disabled for halide.""" + return None + + +def _worker_task_halide(lockfile: str, jobs: list[partial[Any]]) -> None: + from torch.utils._filelock import FileLock + + try: + with FileLock(lockfile, LOCK_TIMEOUT): + for job in jobs: + job() + except subprocess.SubprocessError as e: + if os.environ.get("HALIDE_REPRO") == "1": + cmd: list[Any] + python, script, *cmd = getattr(e, "cmd", ("", "", "")) + if os.path.basename(python).startswith("python"): + code = Path(script).read_text() + main = " hl.main()" + if code.count(main) != 1: + raise AssertionError( + f"Expected exactly 1 occurrence of {main!r} in code, " + f"found {code.count(main)}" + ) from e + + class Out: + def __repr__(self) -> str: + return "out" + + ci = cmd.index("-o") + if not isinstance(ci, int): + raise AssertionError( + f"Expected int index from cmd.index, got {type(ci)}" + ) from e + # pyrefly: ignore [unsupported-operation] + cmd[ci + 1] = Out() + repl = textwrap.indent( + textwrap.dedent( + f"""\ + import sys, tempfile + with tempfile.TemporaryDirectory() as out: + sys.argv = {["repro.py", *cmd]!r} + hl.main() + """ + ), + " ", + ) + code = code.replace(main, repl) + with open("repro.py", "w") as fd: + fd.write(code.lstrip()) + raise RuntimeError(f"wrote repro.py: {e}") from e + raise + + +def touch(filename: str) -> None: + with open(filename, "a"): + pass + + +@clear_on_fresh_cache +class PyCodeCache: + """Caches generated Python modules and their source mappings.""" + + # Track the loaded modules so we can remove the on-disk artifacts when + # clearing the cache. Note also that we may load the same path more + # than once, but attach different attributes, i.e., due to different + # constant values. + modules: list[ModuleType] = [] + + # Modules loaded without extra attributes are stored here, those do not + # need to be re-loaded. + modules_no_attr: dict[str, ModuleType] = {} + + linemaps: dict[str, list[tuple[Any, ...]]] = {} + + @classmethod + def write(cls, source_code: str, extra: str = "") -> tuple[str, str]: + return write(source_code, "py", extra=extra) + + @classmethod + def load( + cls, + source_code: str, + extra: str = "", + *, + set_sys_modules: bool | None = None, + ) -> ModuleType: + key, path = write(source_code, "py", extra=extra) + return cls.load_by_key_path(key, path, set_sys_modules=set_sys_modules) + + @classmethod + def load_by_key_path( + cls, + key: str, + path: str, + linemap: list[tuple[int, str]] | None = None, + attrs: dict[str, Any] | None = None, + *, + set_sys_modules: bool | None = None, + ) -> ModuleType: + if linemap is None: + linemap = [] + + in_toplevel = in_toplevel_process() + set_sys_modules = in_toplevel if set_sys_modules is None else set_sys_modules + + # we only cache when attrs is None + if attrs is None and path in cls.modules_no_attr: + mod = cls.modules_no_attr[path] + if set_sys_modules: + sys.modules.setdefault(mod.__name__, mod) + return mod + + mod = _reload_python_module(key, path, set_sys_modules=set_sys_modules) + + # unzip into separate lines/nodes lists + if set_sys_modules: + cls.linemaps[path] = list(zip(*linemap)) + + if attrs is not None: + for k, v in attrs.items(): + setattr(mod, k, v) + + if in_toplevel: + # we only cache when attrs is None + if attrs is None: + cls.modules_no_attr[path] = mod + + cls.modules.append(mod) + return mod + + @classmethod + def cache_clear(cls, purge: bool = False) -> None: + """ + Clear the in-memory module cache. If purge=True, also delete all the + corresponding on-disk source files. + """ + if purge: + for mod in cls.modules: + try: + if not mod.__file__: + raise AssertionError(f"Module {mod} has no __file__ attribute") + os.remove(mod.__file__) + except FileNotFoundError: + pass + cls.modules.clear() + cls.modules_no_attr.clear() + + @classmethod + @functools.cache + def stack_frames_for_code( + cls, path: str, lineno: int + ) -> list[dict[str, Any]] | None: + if path not in cls.linemaps: + return None + if len(cls.linemaps[path]) == 0: + return None + # [(starting_line, ), ...] + lines, nodes = cls.linemaps[path] + p = bisect_right(lines, lineno) + if p == 0: + return None + entry = nodes[p - 1] + if not entry: + return None + + def parse_stack_trace(stack_trace: str) -> list[dict[str, Any]]: + # ideally fx stores stack traces as data rather than a string + # but this is not along a performance critical path + regex = r'File "(.+)", line (\d+), in (.+)\n' + matches = re.findall(regex, stack_trace) + return [ + {"filename": f, "line": int(l), "name": n} + for f, l, n in reversed(matches) + ] + + return parse_stack_trace(entry) + + +def _load_triton_kernel_from_source( + kernel_name: str, source_code: str +) -> CachingAutotuner: + return getattr(PyCodeCache.load(source_code), kernel_name) + + +@torch_key_cache +def cutlass_key() -> bytes: + """ + Compute a key representing the state of the CUTLASS library. + + Note: OSS and fbcode will have different keys. + """ + if config.is_fbcode(): + with ( + importlib.resources.path( + "cutlass_library", "src_hash.txt" + ) as resource_path, + open(resource_path) as resource_file, + ): + return resource_file.read().encode() + + combined_hash = hashlib.sha256() + build_code_hash([config.cutlass.cutlass_dir], "", combined_hash) + return combined_hash.digest() + + +class DLLWrapper: + """A wrapper for a dynamic library.""" + + def __init__( + self, + lib_path: str, + ) -> None: + self.lib_path = lib_path + self.is_open = False + self.open() + + def open(self) -> None: + if not self.is_open: + self.DLL = cdll.LoadLibrary(self.lib_path) + self.is_open = True + + def close(self) -> None: + if self.is_open: + self._dlclose() + self.is_open = False + + def _dlclose(self) -> None: + f_dlclose = None + # During Python interpreter shutdown, importing modules or calling + # dlclose is unsafe. Silently skip cleanup in that case. + try: + import sys + + if sys.is_finalizing(): + return + except Exception: + # import machinery may already be torn down + return + if is_linux(): + syms = CDLL(None) + if not hasattr(syms, "dlclose"): + # Apline Linux + syms = CDLL("libc.so") + + if hasattr(syms, "dlclose"): + f_dlclose = syms.dlclose + elif is_windows(): + import ctypes + + kernel32 = ctypes.CDLL("kernel32", use_last_error=True) + + f_dlclose = kernel32.FreeLibrary + else: + raise NotImplementedError("Unsupported env, failed to do dlclose!") + + if f_dlclose is not None: + if is_linux(): + f_dlclose.argtypes = [c_void_p] + f_dlclose(self.DLL._handle) + elif is_windows(): + import ctypes + from ctypes import wintypes + + f_dlclose.argtypes = [wintypes.HMODULE] + f_dlclose(self.DLL._handle) + else: + log.warning( + "dll unloading function was not found, library may not be unloaded properly!" + ) + + def __getattr__(self, name: str) -> Callable[..., None]: + if not self.is_open: + raise RuntimeError(f"Cannot use closed DLL library: {self.lib_path}") + + method = getattr(self.DLL, name) + + def _wrapped_func(*args: Any) -> None: + err = method(*args) + if err: + raise RuntimeError(f"Error in function: {method.__name__}") + + return _wrapped_func + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: Any) -> None: + self.close() + + def __del__(self) -> None: + self.close() + + +@lru_cache +def binary_error_path(output_path: str) -> str: + """ + standard format for the error path + """ + return output_path + ".error" + + +class CUTLASSCodeCache: + """ + A cache for managing the compilation and loading source code specifically for CUTLASS. + This class handles writing source code to files, compiling them into shared objects, and caching + the results to avoid redundant compilations. It also manages error handling and logging for the + compilation process. + """ + + @dataclasses.dataclass + class CacheEntry: + input_path: str + output_path: str + error_json: str | None = None + + cache: dict[str, CacheEntry] = {} + aot_kernels_o: list[str] = [] + + _SOURCE_CODE_SUFFIX: str = "" + _BACKEND: str = "" + _COMPILE_ERROR: type[exc.CppCompileError] = exc.CUDACompileError + + @classmethod + def cache_clear(cls) -> None: + cls.cache.clear() + cls.aot_kernels_o.clear() + cls.write.cache_clear() + + @staticmethod + @lru_cache(maxsize=4) + def get_kernel_binary_remote_cache( + caching_enabled: bool, caching_available: bool + ) -> Any | None: + """ + Get or create the class instance of the CUTLASSKernelBinaryRemoteCache. + + Args: + caching_enabled: Whether binary remote caching is enabled + caching_available: Whether we're in fbcode environment + + Returns: + CUTLASSKernelBinaryRemoteCache: The class instance of the kernel binary remote cache + """ + if not caching_enabled: + log.debug("CUTLASSKernelBinaryRemoteCache not requested, skipping") + return None + if not caching_available: + return None + + try: + from torch._inductor.fb.kernel_binary_remote_cache import ( + CUTLASSKernelBinaryRemoteCache, + ) + + return CUTLASSKernelBinaryRemoteCache() + except ImportError: + log.debug( + "CUTLASSKernelBinaryRemoteCache not available, remote caching disabled" + ) + return None + + @classmethod + def _use_re_build(cls) -> bool: + raise NotImplementedError + + @classmethod + def _compile_command( + cls, + src_files: list[str], + dst_file: str, + dst_file_ext: str, + extra_args: list[str] | None = None, + ) -> str: + raise NotImplementedError + + @classmethod + def _source_code_extra(cls) -> str: + raise NotImplementedError + + @classmethod + @lru_cache(None) + def write(cls, source_code: str, dst_file_ext: str) -> tuple[str, str]: + """ + Writes source code into a file with dst_file_ext as the file extension. + Returns the hash key of source code, and the path to the file. + """ + + if config.cutlass.cutlass_hash_with_compile_cmd: + compile_command = repr( + cls._compile_command(["dummy_input"], "dummy_output", dst_file_ext) + ) + extra = compile_command + else: + extra = cls._source_code_extra() + + key, input_path = write(source_code, cls._SOURCE_CODE_SUFFIX, extra=extra) + return key, input_path + + @classmethod + def compile( + cls, source_code: str, dst_file_ext: str, extra_args: list[str] | None = None + ) -> tuple[str, str, str]: + """ + Compiles CUDA source_code into a file with dst_file_ext extension. + If dst_file_ext is "so", first compiles to ".o" and then links to ".so". + Returns a tuple of dst_file_path, hash_key, source_code_path + """ + if dst_file_ext == "so": + # Two-step compilation: first compile to .o, then link to .so + obj_path, _, _ = cls.compile(source_code, "o", extra_args) + key, input_path = cls.write(source_code, dst_file_ext) + src_files, operation_name = [obj_path], "Linking" + else: + # Regular compilation for non-.so files + key, input_path = cls.write(source_code, dst_file_ext) + src_files, operation_name = [input_path], "Compilation" + + key_with_ext = key + dst_file_ext + if key_with_ext not in cls.cache: + from torch.utils._filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT) + with lock: + output_path = input_path[: -len(cls._SOURCE_CODE_SUFFIX)] + dst_file_ext + error_path = binary_error_path(output_path) + binary_remote_cache = cls.get_kernel_binary_remote_cache( + caching_enabled=config.cutlass.use_binary_remote_cache + and not config.force_disable_caches, + caching_available=config.is_fbcode(), + ) + if binary_remote_cache is not None: + # The remote cache implementation will only download if the file does + # not already exist locally + binary_remote_cache.get(output_path, error_path) + + if os.path.exists(error_path): + with open(error_path, encoding="utf-8") as fh: + error_json = fh.read() + cmd_parts, error_output = json.loads(error_json) + if ( + binary_remote_cache is not None + and config.cutlass.upload_to_binary_remote_cache + ): + # This ensures that a local error is uploaded to the remote cache, + # as we make no assumptions about the remote cache having the same + # information as the local cache + binary_remote_cache.put( + error_path, config.cutlass.binary_remote_cache_force_write + ) + cls.cache[key_with_ext] = cls.CacheEntry( + input_path, output_path, error_json + ) + raise cls._COMPILE_ERROR(cmd_parts, error_output) + if not os.path.exists(output_path): + cmd = cls._compile_command( + src_files, output_path, dst_file_ext, extra_args + ) + with open(input_path, "a") as f: + f.write("\n") + f.write(f"// {cls._BACKEND} {operation_name} cmd\n// {cmd}\n") + start_time = time() + log.debug("%s %s: %s", cls._BACKEND, operation_name, cmd) + cmd_parts = shlex.split(cmd) + try: + if cls._use_re_build(): + from triton.fb.re_build_helper import run_build_command + + run_build_command( + cmd_parts, + os.path.dirname(input_path), + os.path.basename(output_path), + ) + else: + subprocess.check_output( + cmd_parts, stderr=subprocess.STDOUT, env=os.environ + ) + except subprocess.CalledProcessError as error: + cls._record_compile_error( + error.output.decode("utf-8"), + key_with_ext, + cmd_parts, + input_path, + output_path, + binary_remote_cache, + ) + raise cls._COMPILE_ERROR(cmd_parts, error.output) from error + except Exception as error: + if "COMPILE FAILED WITH" in str(error): + cls._record_compile_error( + str(error), + key_with_ext, + cmd_parts, + input_path, + output_path, + binary_remote_cache, + ) + raise cls._COMPILE_ERROR(cmd_parts, str(error)) from error + raise error + end_time = time() + log_duration_msg = f"{cls._BACKEND} {operation_name} took {end_time - start_time} seconds. Command: {cmd}" + log.info(log_duration_msg) + + else: + log.debug( + "%s %s skipped: %s since output already exists", + cls._BACKEND, + operation_name, + output_path, + ) + # Upload to remote cache if enabled + if ( + binary_remote_cache is not None + and config.cutlass.upload_to_binary_remote_cache + ): + # will log on errors, but not fail out + binary_remote_cache.put( + output_path, config.cutlass.binary_remote_cache_force_write + ) + cls.cache[key_with_ext] = cls.CacheEntry(input_path, output_path, None) + + cache_entry: CUTLASSCodeCache.CacheEntry = cls.cache[key_with_ext] + if cache_entry.error_json is not None: + # Restore cached Exception and raise it as if we had compiled + cmd_parts, error_output = json.loads(cache_entry.error_json) + raise cls._COMPILE_ERROR(cmd_parts, error_output.encode("utf-8")) + return (cls.cache[key_with_ext].output_path, key, input_path) + + @classmethod + def load(cls, source_code: str, dst_file_ext: str) -> tuple[DLLWrapper, str, str]: + """ + Compiles source code and loads the generated .so file. + Returns a tuple of DLLWrapper, hash_key, source_code_path + """ + + if dst_file_ext != "so": + raise RuntimeError( + f"Only support loading a .so file for now. " + f"Requested file extension: {dst_file_ext}. Source code: {source_code}" + ) + dst_file_path, hash_key, source_code_path = cls.compile( + source_code, dst_file_ext + ) + return (DLLWrapper(dst_file_path), hash_key, source_code_path) + + @classmethod + def _record_compile_error( + cls, + error_str: str, + key_with_ext: str, + cmd_parts: list[str], + input_path: str, + output_path: str, + # Any here, as the import and type will only work in fbcode + # TODO: Make the typing hint strong here + binary_remote_cache: Any = None, + ) -> None: + error_json = json.dumps([cmd_parts, error_str]) + cls.cache[key_with_ext] = cls.CacheEntry(input_path, output_path, error_json) + error_path = binary_error_path(output_path) + with open(error_path, "w", encoding="utf-8") as fh: + fh.write(error_json) + + # Upload to remote cache directly from memory if enabled + if ( + binary_remote_cache is not None + and config.cutlass.upload_to_binary_remote_cache + ): + binary_remote_cache.put( + error_path, config.cutlass.binary_remote_cache_force_write + ) + + +@clear_on_fresh_cache +class CUDACodeCache(CUTLASSCodeCache): + _SOURCE_CODE_SUFFIX = "cu" + _BACKEND = "CUDA" + + @classmethod + def _use_re_build(cls) -> bool: + return cuda_compile_utils.use_re_build() + + @classmethod + def _compile_command( + cls, + src_files: list[str], + dst_file: str, + dst_file_ext: str, + extra_args: list[str] | None = None, + ) -> str: + return cuda_compile_utils.cuda_compile_command( + src_files, dst_file, dst_file_ext, extra_args=extra_args + ) + + @classmethod + def _source_code_extra(cls) -> str: + extra = repr( + [ + # nvcc and cuda hash + cuda_compile_utils._cuda_compiler(), + # cutlass flags and gcc hash + cuda_compile_utils._nvcc_compiler_options(), + # flags + cuda_compile_utils._nvcc_host_compiler_options(), + # cutlass key + cutlass_key(), + # hack to deal with AOTI .o compilation + ] + ) + return extra + + +from torch._inductor.codegen.xpu import compile_utils as xpu_compile_utils + + +@clear_on_fresh_cache +class XPUCodeCache(CUTLASSCodeCache): + _SOURCE_CODE_SUFFIX = "cpp" + _BACKEND = "XPU" + _COMPILE_ERROR: type[exc.CppCompileError] = exc.XPUCompileError + dll_cache: dict[str, DLLWrapper] = {} + + @classmethod + def cache_clear(cls) -> None: + super().cache_clear() + cls.dll_cache.clear() + + @classmethod + def _use_re_build(cls) -> bool: + return False + + @classmethod + def _compile_command( + cls, + src_files: list[str], + dst_file: str, + dst_file_ext: str, + extra_args: list[str] | None = None, + ) -> str: + return xpu_compile_utils.xpu_compile_command( + src_files, dst_file, dst_file_ext, extra_args=extra_args + ) + + @classmethod + def _source_code_extra(cls) -> str: + extra = repr( + [ + xpu_compile_utils._sycl_compiler(), + xpu_compile_utils._sycl_compiler_options(), + cutlass_key(), + ] + ) + return extra + + @classmethod + def load(cls, source_code: str, dst_file_ext: str) -> tuple[DLLWrapper, str, str]: + """ + Compiles source code and loads the generated .so file. + Returns a tuple of DLLWrapper, hash_key, source_code_path + """ + + if dst_file_ext != "so": + raise RuntimeError( + f"Only support loading a .so file for now. " + f"Requested file extension: {dst_file_ext}. Source code: {source_code}" + ) + dst_file_path, hash_key, source_code_path = cls.compile( + source_code, dst_file_ext + ) + if dst_file_path not in cls.dll_cache: + cls.dll_cache[dst_file_path] = DLLWrapper(dst_file_path) + + return (cls.dll_cache[dst_file_path], hash_key, source_code_path) + + +@clear_on_fresh_cache +class ROCmCodeCache: + """ + A cache for managing the compilation and loading source code specifically for ROCm. + This class handles writing source code to files, compiling them into shared objects, and caching + the results to avoid redundant compilations. + """ + + @dataclasses.dataclass + class CacheEntry: + input_path: str + output_path: str + + cache: dict[str, CacheEntry] = {} + aot_kernels_o: list[str] = [] + _SOURCE_CODE_SUFFIX = "cpp" + _logged_compiler_version = False + + @staticmethod + def cache_clear() -> None: + ROCmCodeCache.cache.clear() + ROCmCodeCache.aot_kernels_o.clear() + + @classmethod + def write(cls, source_code: str, dst_file_ext: str) -> tuple[str, str]: + """ + Writes source code into a file with dst_file_ext as the file extension. + Returns the hash key of source code, and the path to the file. + """ + + cuda_command = repr( + rocm_compile_command(["dummy_input"], "dummy_output", dst_file_ext) + ) + key, input_path = write( + source_code, cls._SOURCE_CODE_SUFFIX, extra=cuda_command + ) + return key, input_path + + @classmethod + def compile( + cls, source_code: str, dst_file_ext: str, extra_args: list[str] | None = None + ) -> tuple[str, str, str]: + """ + Compiles source_code into a file with dst_file_ext extension, + using the compile command specific for the ROCm platform. + Returns a tuple of dst_file_path, hash_key, source_code_path + """ + if not cls._logged_compiler_version: + cls._logged_compiler_version = True + log.debug(get_compiler_version_info(str(rocm_compiler()))) + + key, input_path = cls.write(source_code, dst_file_ext) + if key not in cls.cache: + from torch.utils._filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT) + with lock: + output_path = input_path[: -len(cls._SOURCE_CODE_SUFFIX)] + dst_file_ext + if not os.path.exists(output_path): + cmd = rocm_compile_command( + [input_path], output_path, dst_file_ext, extra_args + ) + start_time = time() + cmd_parts = cmd.split(" ") + try: + output = subprocess.check_output( + cmd_parts, + stderr=subprocess.STDOUT, + text=True, + env=os.environ, + ) + log.debug("Compilation output: %s", output) + except subprocess.CalledProcessError as error: + raise exc.CUDACompileError(cmd_parts, error.output) from error + end_time = time() + log_duration_msg = f"Compilation took {end_time - start_time} seconds. Compile command: {cmd}" + log.info(log_duration_msg) + else: + log.debug( + "Skip compiling %s: output %s already exists", + input_path, + output_path, + ) + cls.cache[key] = ROCmCodeCache.CacheEntry(input_path, output_path) + + return (cls.cache[key].output_path, key, input_path) + + @classmethod + def load(cls, source_code: str, dst_file_ext: str) -> tuple[DLLWrapper, str, str]: + """ + Compiles source code and loads the generated .so file. + Returns a tuple of DLLWrapper, hash_key, source_code_path + """ + + if dst_file_ext != "so": + raise RuntimeError( + f"Only support loading a .so file for now. " + f"Requested file extension: {dst_file_ext}. Source code: {source_code}" + ) + dst_file_path, hash_key, source_code_path = cls.compile( + source_code, dst_file_ext + ) + return (DLLWrapper(dst_file_path), hash_key, source_code_path) + + +class CodeCacheFuture: + def result(self, timeout: float | None = None) -> Callable[..., Any]: + raise NotImplementedError + + +class LambdaFuture(CodeCacheFuture): + def __init__( + self, result_fn: Callable[..., Any], future: Future[Any] | None = None + ) -> None: + self.result_fn = result_fn + self.future = future + + def result(self, timeout: float | None = None) -> Callable[..., Any]: + if timeout is not None and self.future is not None: + # Wait on the underlying cross-process future with the caller's + # timeout; raises concurrent.futures.TimeoutError if it does not + # resolve in time. result_fn will then consume the completed + # future without blocking further. + self.future.result(timeout=timeout) + return self.result_fn() + + +class StaticAutotunerFuture(CodeCacheFuture): + """ + A statically launchable CachingAutotuner, loaded from TritonBundler + """ + + def __init__(self, static_autotuner: CachingAutotuner) -> None: + # Pickled version of CachingAutotuner + self.static_autotuner = static_autotuner + # This needs to be set in AsyncCompile.triton, in case + # we need to reload the CachingAutotuner from its source code + # We don't store the source code on the CachingAutotuner itself + # since it can be very large. + self.reload_kernel_from_src: Callable[[], Any] | None = None + + def result(self, timeout: float | None = None) -> CachingAutotuner: + # timeout is accepted for interface parity with other CodeCacheFuture + # subclasses; this work is synchronous in-process and has no pending + # future to wait on. + if self.reload_kernel_from_src is None: + raise AssertionError( + "reload_kernel_from_src must be set before calling result()" + ) + with dynamo_timed("StaticAutotunerFuture.warm_precompile"): + self.static_autotuner.recheck_autotune_cache( + reload_kernel_from_src=self.reload_kernel_from_src + ) + self.static_autotuner.precompile( # type: ignore[union-attr] + warm_cache_only=False, + reload_kernel=self.reload_kernel_from_src, + static_triton_bundle_key=None, # no need to save again + ) + return self.static_autotuner diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..960c9874fa7ca379d27cbc1d9f15caa910fd93b6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/aoti_hipify_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/aoti_hipify_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8579bde8fc1a8fece8625fe883fbe5a4572641d7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/aoti_hipify_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/block_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/block_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1616915a3099905bad83739d343e1f24bdfa6df3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/block_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d68ccf8ad3841dc9fdee8de8464f15ee2867b2ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7580c2d8c245d106654e3a17c7f77f9103be2ce1040eefc2c408f0a3bae2a5a1 +size 150073 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95a558c9e34d111da68f03d6b016d84b2f7eb5b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9bb32737923397f47a5eef74f245dfb33c5daba559c0220c275fd80a3fab5bad +size 295482 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_bmm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_bmm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..177187e2f3622eed89efa43fec9b7f51bf03f92d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_bmm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_flex_attention_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_flex_attention_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8f041a01dd9dbe46fd79652ae7e89cba9f0746c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_flex_attention_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_gemm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_gemm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a94caba6e0379967158d7c4d56e502c82d536fe2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_gemm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_grouped_gemm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_grouped_gemm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71671b9099a6bb4bc86645cdcf4558f794f0fac3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_grouped_gemm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_micro_gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_micro_gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fa96173b7a32e284e8a5a74929219cea39467ee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_micro_gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3175073347193d7adb6a0f4c0d7ce7721230e2d8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c852609eec35790ba1956337bbbb72bb5d362a0c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c06498476769359a3581a77d6cae0c464c104a8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10777a80fe959fd6a799e1361d2eea45e5d04d4a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5b4dfccff5574d081508c18d5f610a1598a85954fbaa9c78a5a515d630a64c5 +size 216475 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu_array_ref.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu_array_ref.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f5d273b6dfe5699d98d9b9cce2264263662b032 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu_array_ref.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_gpu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_gpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeffd0c8418b5d8521d9f76ddfd4602ea7c6c4c8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_gpu.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_mps.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_mps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7a06e3c0ff36a6e9e3ba0f80b7ab67ac7be4ab5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_mps.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpu_device_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpu_device_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f316a65b1b826c835e735cf309462dc1b00ceaa9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpu_device_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cuda_combined_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cuda_combined_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78377d889b418447f4cf00c9b4a2908078a5c079 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cuda_combined_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/custom_extern_kernel_codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/custom_extern_kernel_codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c40046375aff65dd19290d8b0abf8d5369bef22 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/custom_extern_kernel_codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/debug_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/debug_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdc8825adcfc873a7265dd87a7336da2f5e2f1d4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/debug_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/halide.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/halide.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7459875c335d82727879f0f4687230fe99519d1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/halide.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/memory_planning.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/memory_planning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8b2a706ff09f3857d5decc727c695e430a00f7f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/memory_planning.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/metal_flex_attention_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/metal_flex_attention_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04dd9c1a8f6a58ab534b1df8e5bfc6b3d29e43eb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/metal_flex_attention_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e233ab2379013fb8cbd7f08937a5d401f4fb3ac8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps_device_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps_device_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7418cc1d85929bab80c5d27a3904694befe2ef1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps_device_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/multi_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/multi_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b3991fb8b735c727bf81d070944222e33a6df11 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/multi_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/pallas.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/pallas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a14500427f5e21cb76ac5327f569d7a68a5d4143 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/pallas.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f819bbe4e1417e68614e4047a56347e87c59ee903eb63dcf552052505c86db3 +size 211817 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/python_wrapper_mtia.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/python_wrapper_mtia.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baef629bce0c924e1312bcd1cb2900a2b47b1ba6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/python_wrapper_mtia.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/segmented_tree.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/segmented_tree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5eb5ddf7874c3a085d1264fadd1c5ee522ab12af Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/segmented_tree.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a32e1b9c0020d2031941ab29896bdf537dfe5c3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c78c72bc7463cb2838977be1d3a03c599489fe7fc0660998fad0d2fc8f80c2b7 +size 214585 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd_kernel_features.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd_kernel_features.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c19ef4724cd29d4d18349ead32fe87e39fcf7fdc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd_kernel_features.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/subgraph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/subgraph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66b2d9b26f011ef7930f4250dac1fb528e2bd4da Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/subgraph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5624821aa4556965c2a9825e0ad0f2794824231 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:05d6c248c591fa0e297fba04a0ec8b293eb381db0a7c87de1b6ffffa5de68fcb +size 378153 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_combo_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_combo_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84c53997a17a17b2e7148e9b354e8a6b665cea6b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_combo_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_split_scan.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_split_scan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2e27260f6e766177e763525d65edb7b0d73fc4d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_split_scan.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf67bdc7668c8e174d054eece4043d8301b65841 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8a29db0da56be4a0196783618f273834285ac95 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:901bc6bbd4c0e99ff473213312300d08be1a4793f2476340d37aedbeda591675 +size 261743 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper_fxir.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper_fxir.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aae2c285ac56c23506ea069519a88d61c33eab7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper_fxir.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_hipify_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_hipify_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bc6b5807c95f697bd8bb29666e4b9123de076094 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_hipify_utils.py @@ -0,0 +1,38 @@ +import re + +import torch + + +# It is not a good idea to directly apply hipify_torch to codegen, which will be vulnerable to cases like: +# "... +# from ..codecache import CudaKernelParamCache +# ..." +# In such cases, we do not need to hipify_torch the original class/file name in codegen/codecache + + +def maybe_hipify_code_wrapper(source_codes: str, force_hipify: bool = False) -> str: + if torch.version.hip is None and not force_hipify: + return source_codes + + try: + from torch.utils.hipify.hipify_python import PYTORCH_MAP, PYTORCH_TRIE + except ImportError: + # hipify not available for non-AMD builds + return source_codes + + def c2_repl(m: re.Match[str]) -> object: + return PYTORCH_MAP[m.group(0)] + + # We need to redefine RE_PYTORCH_PREPROCESSOR here since in hipify_torch, + # it will apply positive lookbehind (?<=\W) to the pattern to avoid matching + # keyword at the beginning of code line. However, this can happen in codegen, + # which will cause the pattern to not match. + + # Note that lookahead (?=\W|$) is still needed to keep hipification idempotent, for example + # we need to skip replacing "getStreamFromExternal" in "getStreamFromExternalMasqueradingAsCUDA". + # End-of-string must also count as a boundary so bare-token inputs like "CUfunction" + # (returned by device_codegen.cpp_kernel_type()) get hipified too. + RE_PYTORCH_PREPROCESSOR = re.compile(rf"({PYTORCH_TRIE.export_to_regex()})(?=\W|$)") + + source_codes = RE_PYTORCH_PREPROCESSOR.sub(c2_repl, source_codes) # type: ignore[arg-type] + return source_codes diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/interface.cpp b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/interface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a4416fba3d740509c23622c7cfd949b27a94903b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/interface.cpp @@ -0,0 +1,719 @@ +// Definition of AOTI runtime interface functions + +#include +#include + +#include +#include +#include +#include + +// Stores the last error message from a failed AOTI runtime call so that +// callers on the other side of the C ABI boundary can retrieve it via +// AOTInductorGetLastError(). Without this, exception messages (e.g. +// "CUDA error: an illegal memory access was encountered") are lost when +// CONVERT_EXCEPTION_TO_ERROR_CODE catches them and returns an error code. +static thread_local std::string g_aoti_last_error; + +#define CONVERT_EXCEPTION_TO_ERROR_CODE(...) \ + try { \ + g_aoti_last_error.clear(); \ + __VA_ARGS__ \ + } catch (const std::exception& e) { \ + g_aoti_last_error = e.what(); \ + std::cerr << "Error: " << e.what() << '\n'; \ + return AOTI_RUNTIME_FAILURE; \ + } catch (...) { \ + g_aoti_last_error = "Unknown exception"; \ + std::cerr << "Unknown exception occurred.\n"; \ + return AOTI_RUNTIME_FAILURE; \ + } \ + return AOTI_RUNTIME_SUCCESS; + +#define AOTI_VECTOR_SIZE_CHECK(actual_size, expected_size, name) \ + do { \ + AOTI_RUNTIME_CHECK( \ + actual_size == expected_size, \ + "expected " + std::string(name) + " vector size to be " + \ + std::to_string(expected_size) + ", but got " + \ + std::to_string(actual_size)); \ + } while (0) + +// AOTInductor uses at::addmm_out, which doesn't supports +// arguments that requires gradient. For this reason, we +// enforce no_grad context for run APIs. +// +// A RAII, thread local (!) guard that enables or disables grad mode upon +// construction, and sets it back to the original value upon destruction. +struct AOTINoGradGuard { + AOTINoGradGuard() { + aoti_torch_grad_mode_set_enabled(false); + } + AOTINoGradGuard(const AOTINoGradGuard&) = delete; + AOTINoGradGuard(AOTINoGradGuard&&) noexcept = delete; + ~AOTINoGradGuard() { + aoti_torch_grad_mode_set_enabled(prev_mode); + } + AOTINoGradGuard& operator=(const AOTINoGradGuard&) = delete; + AOTINoGradGuard& operator=(AOTINoGradGuard&&) noexcept = delete; + bool prev_mode{aoti_torch_grad_mode_is_enabled()}; +}; + +namespace { + +std::unordered_map constant_map_from_pairs( + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs) { + std::unordered_map input_map; + input_map.reserve(num_pairs); + for (size_t i = 0; i < num_pairs; ++i) { + input_map.emplace(pairs[i].name, pairs[i].handle); + } + return input_map; +} + +// Shared constructor for AOTInductorModelCreate / AOTInductorModelCreateV2. +// `populate(constant_map)` is called between model construction and +// optional embedded-blob loading. +template +AOTIRuntimeError createModelImpl( + AOTInductorModelHandle* model_handle, + bool load_constants_from_blob, + Populate&& populate) { + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto constant_map = std::make_shared(); + auto constant_array = std::make_shared< + std::vector>(); + auto* model = new torch::aot_inductor::AOTInductorModel( + constant_map, + constant_array, + // device_str is hardcoded, as AOTInductorModelCreate is only used + // for CPU models. + "cpu", + ""); + populate(*constant_map); + if (load_constants_from_blob) { + model->load_constants(); + } + *model_handle = reinterpret_cast(model); + }) +} + +} // namespace + +extern "C" { + +AOTIRuntimeError AOTInductorModelContainerCreate( + AOTInductorModelContainerHandle* container_handle, + size_t num_models, + bool is_cpu, + const char* cubin_dir) { + return AOTInductorModelContainerCreateWithDevice( + container_handle, + num_models, + is_cpu ? "cpu" : "cuda", + cubin_dir); +} + +AOTIRuntimeError AOTInductorModelContainerCreateWithDevice( + AOTInductorModelContainerHandle* container_handle, + size_t num_models, + const char* device_str, + const char* cubin_dir) { + + if (num_models == 0) { + std::cerr << "Error: num_models must be positive, but got 0\n"; + return AOTI_RUNTIME_FAILURE; + } + CONVERT_EXCEPTION_TO_ERROR_CODE({ + std::optional cubin_dir_opt; + if (cubin_dir != nullptr) { + cubin_dir_opt.emplace(cubin_dir); + } + auto* container = new torch::aot_inductor::AOTInductorModelContainer( + num_models, std::string(device_str), cubin_dir_opt); + *container_handle = + reinterpret_cast(container); + }) +} + + +AOTIRuntimeError AOTInductorModelContainerCreateWithExternalConstants( + AOTInductorModelContainerHandle* container_handle, + size_t num_models, + const char* device_str, + const char* cubin_dir, + const AOTInductorConstantMapEntry* constant_entries, + size_t num_constant_entries) { + if (num_models == 0) { + std::cerr << "Error: num_models must be positive, but got 0\n"; + return AOTI_RUNTIME_FAILURE; + } + if (num_constant_entries != 0 && constant_entries == nullptr) { + std::cerr << "Error: constant_entries is null but num_constant_entries is " + << num_constant_entries << "\n"; + return AOTI_RUNTIME_FAILURE; + } + CONVERT_EXCEPTION_TO_ERROR_CODE({ + std::optional cubin_dir_opt; + if (cubin_dir != nullptr) { + cubin_dir_opt.emplace(cubin_dir); + } + // Rebuild the std map on the DSO side of the boundary so no std container + // crosses the ABI; the entries are C-compatible (name + AtenTensorHandle). + std::unordered_map constants; + constants.reserve(num_constant_entries); + for (size_t i = 0; i < num_constant_entries; ++i) { + constants.emplace(constant_entries[i].name, constant_entries[i].handle); + } + auto* container = new torch::aot_inductor::AOTInductorModelContainer( + num_models, + std::string(device_str), + constants, + cubin_dir_opt); + *container_handle = + reinterpret_cast(container); + }) +} + +AOTIRuntimeError AOTInductorModelContainerDelete( + AOTInductorModelContainerHandle container_handle) { + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto* container = + reinterpret_cast( + container_handle); + delete container; + }); +} + +AOTIRuntimeError AOTInductorModelContainerRun( + AOTInductorModelContainerHandle container_handle, + AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + size_t num_inputs, + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + size_t num_outputs, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle) { + auto* container = + reinterpret_cast( + container_handle); + AOTI_VECTOR_SIZE_CHECK(num_inputs, container->num_inputs(), "inputs"); + AOTI_VECTOR_SIZE_CHECK(num_outputs, container->num_outputs(), "outputs"); + + auto stream = + reinterpret_cast(stream_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + AOTINoGradGuard guard; + container->run( + input_handles, output_handles, stream, proxy_executor_handle); + }) +} + +AOTIRuntimeError AOTInductorModelContainerRunSingleThreaded( + AOTInductorModelContainerHandle container_handle, + AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + size_t num_inputs, + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + size_t num_outputs, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle) { + auto* container = + reinterpret_cast( + container_handle); + AOTI_VECTOR_SIZE_CHECK(num_inputs, container->num_inputs(), "inputs"); + AOTI_VECTOR_SIZE_CHECK(num_outputs, container->num_outputs(), "outputs"); + + auto stream = + reinterpret_cast(stream_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + AOTINoGradGuard guard; + container->run_single_threaded( + input_handles, output_handles, stream, proxy_executor_handle); + }) +} + +AOTIRuntimeError AOTInductorModelContainerGetNumConstants( + AOTInductorModelContainerHandle container_handle, + size_t* num_constants) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *num_constants = container->num_constants(); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantName( + AOTInductorModelContainerHandle container_handle, + size_t idx, + const char** name) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *name = container->constant_name(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantOriginalFQN( + AOTInductorModelContainerHandle container_handle, + size_t idx, + const char** original_fqn) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *original_fqn = container->constant_original_fqn(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantFromFolded( + AOTInductorModelContainerHandle container_handle, + size_t idx, + bool* from_folded) { + auto* container = + reinterpret_cast(container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ *from_folded = container->constant_from_folded(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantType( + AOTInductorModelContainerHandle container_handle, + size_t idx, + int32_t* type) { + auto* container = + reinterpret_cast(container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ *type = container->constant_type(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantDtype( + AOTInductorModelContainerHandle container_handle, + size_t idx, + int32_t* dtype) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *dtype = container->constant_dtype(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantDataSize( + AOTInductorModelContainerHandle container_handle, + size_t idx, + size_t* data_size) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *data_size = container->constant_data_size(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerExtractConstantsMap( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive) { + auto* container = + reinterpret_cast( + container_handle); + auto constants_map = reinterpret_cast*>(constant_map_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { const auto ret = container->extract_constants_map(use_inactive); + for (const auto& pair: ret) { + constants_map->emplace(pair.first, pair.second); + } + }) +} + +AOTIRuntimeError AOTInductorModelContainerExtractConstantsMapEntries( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry** entries, + size_t* num_entries, + bool use_inactive) { + if (!entries || !num_entries) { + return AOTI_RUNTIME_FAILURE; + } + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + const auto& extracted = + container->extract_constants_map_entries(use_inactive); + *entries = extracted.empty() ? nullptr : extracted.data(); + *num_entries = extracted.size(); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateUserManagedConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast( + container_handle); + auto input_map = reinterpret_cast*>(constant_map_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + *input_map, use_inactive, validate_full_update, /* user_managed = */ true); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateUserManagedConstantBufferPairs( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast(container_handle); + // Build a local unordered_map inside + std::unordered_map input_map; + input_map.reserve(num_pairs); + for (size_t i = 0; i < num_pairs; ++i) { + input_map.emplace(pairs[i].name, pairs[i].handle); + } + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + input_map, use_inactive, validate_full_update, /*user_managed=*/true); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast( + container_handle); + auto input_map = reinterpret_cast*>(constant_map_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + *input_map, use_inactive, validate_full_update); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateConstantBufferPairs( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast( + container_handle); + auto input_map = constant_map_from_pairs(pairs, num_pairs); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + input_map, use_inactive, validate_full_update); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateConstantBufferFromCpu( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast( + container_handle); + auto input_map = reinterpret_cast*>(constant_map_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + *input_map, + use_inactive, + validate_full_update, + /*user_managed=*/false, + /*allow_h2d_copy=*/true); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateConstantBufferFromCpuPairs( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast( + container_handle); + auto input_map = constant_map_from_pairs(pairs, num_pairs); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + input_map, + use_inactive, + validate_full_update, + /*user_managed=*/false, + /*allow_h2d_copy=*/true); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateInactiveConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle) { + return AOTInductorModelContainerUpdateConstantBuffer( + container_handle, + constant_map_handle, + /*use_inactive=*/true, + /*validate_full_update=*/true); +} + +AOTIRuntimeError AOTInductorModelContainerUpdateInactiveConstantBufferPairs( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs) { + return AOTInductorModelContainerUpdateConstantBufferPairs( + container_handle, + pairs, + num_pairs, + /*use_inactive=*/true, + /*validate_full_update=*/true); +} + +AOTIRuntimeError AOTInductorModelContainerFreeInactiveConstantBuffer( + AOTInductorModelContainerHandle container_handle) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->free_inactive_constant_buffer(); + }) +} + +AOTIRuntimeError AOTInductorModelContainerRunConstantFolding( + AOTInductorModelContainerHandle container_handle, + bool use_inactive, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle) { + auto* container = + reinterpret_cast( + container_handle); + auto stream = + reinterpret_cast(stream_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + AOTINoGradGuard guard; + container->run_const_fold(use_inactive, stream, proxy_executor_handle); + }) +} + +AOTIRuntimeError AOTInductorModelContainerSwapConstantBuffer( + AOTInductorModelContainerHandle container_handle) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->swap_constant_buffer(); + }) +} + +AOTIRuntimeError AOTInductorModelContainerGetNumInputs( + AOTInductorModelContainerHandle container_handle, + size_t* ret_num_inputs) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *ret_num_inputs = container->num_inputs(); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetInputName( + AOTInductorModelContainerHandle container_handle, + size_t input_idx, + const char** ret_input_names) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *ret_input_names = container->input_name(input_idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetNumOutputs( + AOTInductorModelContainerHandle container_handle, + size_t* ret_num_outputs) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *ret_num_outputs = container->num_outputs(); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetOutputName( + AOTInductorModelContainerHandle container_handle, + size_t output_idx, + const char** ret_output_names) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *ret_output_names = container->output_name(output_idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetCallSpec( + AOTInductorModelContainerHandle container_handle, + const char** in_spec, + const char** out_spec) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + *in_spec = container->get_in_spec(); + *out_spec = container->get_out_spec(); + }) +} + +AOTIRuntimeError AOTInductorModelCreate( + AOTInductorModelHandle* model_handle, + AOTInductorConstantMapHandle constant_map_handle) { + return createModelImpl( + model_handle, constant_map_handle == nullptr, [=](auto& constant_map) { + auto* input_map = reinterpret_cast< + std::unordered_map*>( + constant_map_handle); + if (input_map) { + for (const auto& kv : *input_map) { + constant_map.emplace(kv.first, kv.second); + } + } + }); +} + +AOTIRuntimeError AOTInductorModelCreateV2( + AOTInductorModelHandle* model_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs) { + return createModelImpl( + model_handle, pairs == nullptr || num_pairs == 0, [=](auto& constant_map) { + if (pairs && num_pairs > 0) { + constant_map.reserve(num_pairs); + for (size_t i = 0; i < num_pairs; ++i) { + constant_map.emplace(pairs[i].name, pairs[i].handle); + } + } + }); +} + +AOTIRuntimeError AOTInductorModelRun( + AOTInductorModelHandle model_handle, + AtenTensorHandle* input_handles, + AtenTensorHandle* output_handles) { + auto model = + reinterpret_cast(model_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + AOTINoGradGuard guard; + model->run_impl( + input_handles, + output_handles, + (torch::aot_inductor::DeviceStreamType) nullptr, + nullptr); + }) +} + +AOTIRuntimeError AOTInductorModelDelete(AOTInductorModelHandle model_handle){ + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto model = reinterpret_cast( + model_handle); + delete model; + })} + +AOTIRuntimeError AOTInductorModelGetNumOutputs( + AOTInductorModelHandle model_handle, + size_t* ret_num_outputs) { + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto model = reinterpret_cast(model_handle); + *ret_num_outputs = model->num_outputs(); + }) +} + +AOTIRuntimeError AOTInductorModelUpdateConstantsMap( + AOTInductorModelHandle model_handle, + AOTInductorConstantMapHandle constant_map_handle) { + auto model = + reinterpret_cast(model_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto constant_map = std::make_shared(); + auto input_map = + reinterpret_cast*>( + constant_map_handle); + + for (auto const& kv : *input_map) { + constant_map->emplace(kv.first, kv.second); + } + model->update_constants_map(std::move(constant_map)); + }) +} + +// C-ABI-safe variant: uses an array of (name, handle) pairs instead of an +// opaque pointer to std::unordered_map, so the host and DSO can use +// different C++ standard libraries without ABI conflicts. +AOTIRuntimeError AOTInductorModelUpdateConstantsMapV2( + AOTInductorModelHandle model_handle, + const AOTInductorConstantMapEntry* pairs, + int32_t num_pairs) { + auto model = + reinterpret_cast(model_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto constant_map = std::make_shared(); + constant_map->reserve(num_pairs); + for (int32_t i = 0; i < num_pairs; ++i) { + constant_map->emplace(pairs[i].name, pairs[i].handle); + } + model->update_constants_map(std::move(constant_map)); + }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantsBlobSize( + AOTInductorModelContainerHandle container_handle, + uint64_t* ret_size) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *ret_size = container->constant_blob_size(); }) +} + +AOTIRuntimeError AOTInductorModelContainerDidCallLoadConstants( + AOTInductorModelContainerHandle container_handle, + bool* did_call_load_constants) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *did_call_load_constants = container->did_call_load_constants(); }) +} + + +// Load weights from a single blob in weight_blob_ptr +AOTIRuntimeError AOTInductorModelUpdateConstantsFromBlob( + AOTInductorModelContainerHandle container_handle, + const uint8_t* weight_blob_ptr){ + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + {container->update_constants_from_blob(weight_blob_ptr); }) + } + +AOTIRuntimeError AOTInductorSetUsePinnedAsyncConstantsCopy(bool enabled) { + CONVERT_EXCEPTION_TO_ERROR_CODE({ + torch::aot_inductor::setUsePinnedAsyncConstantsCopy(enabled); + }) +} + +AOTIRuntimeError AOTInductorSetPinnedAsyncConstantsCopyStageBufferBytes( + size_t bytes) { + CONVERT_EXCEPTION_TO_ERROR_CODE({ + torch::aot_inductor::setPinnedAsyncConstantsCopyStageBufferBytes(bytes); + }) +} + +AOTIRuntimeError AOTInductorGetLastError( + const char** error_msg) { + *error_msg = g_aoti_last_error.c_str(); + return AOTI_RUNTIME_SUCCESS; +} + +} // extern "C" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/streams.h b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/streams.h new file mode 100644 index 0000000000000000000000000000000000000000..32e1c06459556c8ee7e85e16b0fac97728d908a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/streams.h @@ -0,0 +1,123 @@ +#ifndef AOTI_RUNTIME_STREAMS_H +#define AOTI_RUNTIME_STREAMS_H + +#include +#include +#include + +namespace torch::aot_inductor { + +struct AOTIPerThreadEventCache { + std::vector> events_by_device; + + std::vector& events(int device_idx) { + AOTI_RUNTIME_CHECK(device_idx >= 0, "AOTI event cache device index < 0"); + const auto slot = static_cast(device_idx); + if (events_by_device.size() <= slot) { + events_by_device.resize(slot + 1); + } + return events_by_device[slot]; + } + + void create(std::vector& events, std::size_t slot) { + AOTI_RUNTIME_CUDA_CHECK( + cudaEventCreateWithFlags(&events[slot], cudaEventDisableTiming)); + } + + cudaEvent_t get(int event_idx, int device_idx) { + AOTI_RUNTIME_CHECK(event_idx >= 0, "AOTI event cache event index < 0"); + auto& device_events = events(device_idx); + const auto slot = static_cast(event_idx); + if (device_events.size() <= slot) { + device_events.resize(slot + 1, nullptr); + } + if (device_events[slot] == nullptr) { + create(device_events, slot); + } + return device_events[slot]; + } + + ~AOTIPerThreadEventCache() { + for (auto& device_events : events_by_device) { + for (auto event : device_events) { + if (event == nullptr) { + continue; + } + auto code = cudaEventDestroy(event); + if (code != cudaSuccess) { + std::cerr + << "Failed to destroy CUDA event in AOTInductor stream cache: " + << cudaGetErrorString(code) << '\n'; + } + } + } + } +}; + +struct AOTIPerThreadStreamCache { + std::vector> streams_by_device; + + void check_not_capturing(cudaStream_t caller_stream) { + cudaStreamCaptureStatus capture_status; + AOTI_RUNTIME_CUDA_CHECK( + cudaStreamIsCapturing(caller_stream, &capture_status)); + AOTI_RUNTIME_CHECK( + capture_status == cudaStreamCaptureStatusNone, + "AOTI user streams are not supported during CUDA graph capture"); + } + + std::vector& streams(int device_idx) { + AOTI_RUNTIME_CHECK(device_idx >= 0, "AOTI stream cache device index < 0"); + const auto slot = static_cast(device_idx); + if (streams_by_device.size() <= slot) { + streams_by_device.resize(slot + 1); + } + return streams_by_device[slot]; + } + + void ensure(std::size_t count, int device_idx, cudaStream_t caller_stream) { + check_not_capturing(caller_stream); + auto& device_streams = streams(device_idx); + const std::size_t old_size = device_streams.size(); + if (old_size >= count) { + return; + } + device_streams.resize(count, nullptr); + for (std::size_t i = old_size; i < count; ++i) { + if (i == 0) { + continue; + } + AOTI_RUNTIME_CUDA_CHECK( + cudaStreamCreateWithFlags(&device_streams[i], cudaStreamNonBlocking)); + } + } + + cudaStream_t get(int stream_idx, int device_idx, cudaStream_t caller_stream) { + AOTI_RUNTIME_CHECK( + stream_idx > 0, + "AOTI aux stream cache slot 0 is reserved for the caller stream"); + const auto slot = static_cast(stream_idx); + ensure(slot + 1, device_idx, caller_stream); + return streams(device_idx)[slot]; + } + + ~AOTIPerThreadStreamCache() { + for (auto& device_streams : streams_by_device) { + for (auto stream : device_streams) { + if (stream == nullptr) { + continue; + } + auto code = cudaStreamDestroy(stream); + if (code != cudaSuccess) { + std::cerr + << "Failed to destroy CUDA stream in AOTInductor stream cache: " + << cudaGetErrorString(code) << '\n'; + } + } + } + } +}; + +} // namespace torch::aot_inductor + +#endif // AOTI_RUNTIME_STREAMS_H diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/block_analysis.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/block_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..adf9f293c4dc80358a5b2df30fdcff2ee1613124 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/block_analysis.py @@ -0,0 +1,222 @@ +import collections +import functools +import textwrap + +import sympy +from sympy import Expr, Symbol + +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import FloorDiv, ModularIndexing + +from ..utils import sympy_dot, sympy_subs +from ..virtualized import V + + +class BlockPatternMatcher: + """ + Matches block indexing expressions. + """ + + _indexing_wild_signed_int = functools.partial( + sympy.Wild, properties=[lambda x: x.is_integer] + ) + _indexing_wild_unsigned_int = functools.partial( + sympy.Wild, properties=[lambda x: x.is_integer and x.is_nonnegative] + ) + + @classmethod + def get_subexpr_involving_symbol(cls, expr: Expr, symbol: Symbol) -> Expr: + """ + Given a sympy expression, return the subexpression comprised only of terms + involving the specified symbol. + + For example, if `expr` is `x * 5 + x ** 2 + y * 2 + 5`, and `symbol` is `x`, + this returns `x * 5 + x ** 2`. + """ + expr = cls._preprocess(expr) + return sympy.S.Zero + sum( + term for term in sympy.Add.make_args(expr) if symbol in term.free_symbols + ) + + @staticmethod + def factor_index_expr(expr: sympy.Expr, index_var: Symbol) -> sympy.Expr: + """ + Given an index expression, factor the expression around + - FloorDiv(index_var, ...) + - ModularIndexing(index_var, ...) + - xindex + + e.g. FloorDiv(index_var, d0)*s0 + FloorDiv(index_var, d0)*s1 -> + FloorDiv(index_var, d0) * (s0 + s1) + """ + centres = OrderedSet() + for sub in sympy.preorder_traversal(expr): + if isinstance(sub, FloorDiv) and sub.args[0] == index_var: + centres.add(sub) + elif isinstance(sub, ModularIndexing) and sub.args[0] == index_var: + centres.add(sub) + centres.add(index_var) + + expr_out = expr + for c in centres: + expr_out = sympy.collect(expr_out, c) + return expr_out + + @staticmethod + def get_slice_numels(dims: list[Expr]) -> list[Expr]: + """ + Compute the cumulative size of each dimension's slice. + This proceeds from the last dim up to the second. + """ + numels = collections.deque([sympy.S.One]) + for dim in dims[:0:-1]: + numel = dim * numels[0] + numels.appendleft(numel) + return [*numels] + + @staticmethod + def _preprocess(expr: Expr) -> Expr: + # Remove any Identity nodes, e.g. expand x + (5 * y) to x + 5 * y. + # Disable mul and multinomial as those expansions affect op trees: + # e.g. sympy expects to match Mul(a, b), but expansion has simplified + # to Add(...). Even though they may be algebraically equivalent, + # sympy `match` performs structural pattern matching + return expr.expand(mul=False, multinomial=False, identity=True) + + @classmethod + def match_mod_div_block_expr( + cls, + index: Expr, + index_var: Symbol, + numel: Expr, + num_dims: int, + ) -> tuple[list[Expr], list[Expr], list[Expr]] | None: + """ + Matches modular indexing expressions, converting them to implied block dimensions and strides. + See triton.py for more information. + + Warning: this function requires that `index`, `numel` and any other sympy + expression does not have precomputed replacements since otherwise block + pattern matching may fail. + See [Note: Precomputed replacements with BlockPatternMatch] + """ + index = cls._preprocess(index) + + # Pattern match to find the strides and offset. + wild_unsigned_int = functools.partial( + cls._indexing_wild_unsigned_int, exclude=[index_var] + ) + wild_signed_int = functools.partial( + cls._indexing_wild_signed_int, exclude=[index_var] + ) + dims: list[Expr] = [ + wild_unsigned_int(f"dim_mod{idx}") for idx in range(num_dims) + ] + strides: list[Expr] = [ + wild_signed_int(f"stride_mod{idx}") for idx in range(num_dims) + ] + + # The first dimension's index is computed by division. + # The remaining are computed by modulo. + slice_numels = cls.get_slice_numels(dims[:num_dims]) + block_index_exprs = [FloorDiv(index_var, slice_numels[0])] + [ + ModularIndexing(index_var, numel, dim) + for dim, numel in zip(dims[1:], slice_numels[1:]) + ] + + # Calculate a linear index from block indices. + match_expr = sympy_dot(strides, block_index_exprs) + + # Heuristic: if the number of dimensions is high, check that the minimum requirements + # are met before attempting an expensive full match. see triton.py:match_mod_div_block + # for more details. In short, here we check that each subexpression in sympy.Add contains + # only FloorDiv or ModularIndexing expressions. + if num_dims >= 5: + stride = sympy.symbols("stride", cls=wild_signed_int) + denom, other = sympy.symbols("denominator other", cls=wild_unsigned_int) + mod_div_pattern = stride * ModularIndexing(index_var, denom, other) + floor_div_pattern = stride * FloorDiv(index_var, denom) + first_dim_floor_div_matched = False + match_failed = False + for arg in sympy.Add.make_args(index): + if arg.match(floor_div_pattern): + # There should only be a single FloorDiv(index, denom) expression + # corresponding to the first dimension + if first_dim_floor_div_matched: + match_failed = True + break + first_dim_floor_div_matched = True + elif arg.match(mod_div_pattern): + continue + else: + match_failed = True + break + + if match_failed: + return None + + # Pattern match. + match = index.match(match_expr) + if match is None: + return None + + # Provide default values for unmatched dims and strides. + for dim in dims[1:]: + if dim not in match: + match[dim] = sympy.S.One + for stride in strides[1:]: + if stride not in match: + match[stride] = sympy.S.Zero + + # Replace wildcards with matched expressions. + dims = [dims[0]] + [match[dim] for dim in dims[1:]] + strides = [match[stride] for stride in strides] + slice_numels = cls.get_slice_numels(dims) + block_index_exprs = [sympy_subs(expr, match) for expr in block_index_exprs] + + sizevars = V.graph.sizevars + + # The leading dimension is not directly matched in our expression. + # We solve for it by dividing the range tree numel by the product of + # all other dimensions. We quit if they are not known to be divisible. + if dims[0] in match: + raise AssertionError("Expected not to match the leading dimension!") + if not sizevars.statically_known_multiple_of(numel, slice_numels[0]): + return None + dims[0] = numel / slice_numels[0] + + # Sanity check that we can recover the index from the matched subexpressions. + matched_index = sympy_dot(strides, block_index_exprs) + if not sizevars.statically_known_equals( + matched_index, + index, + ): + raise AssertionError( + textwrap.dedent( + f""" + Invalid match! + Index: {index} + Matched expression: {matched_index} + """ + ) + ) + + return dims, strides, block_index_exprs + + @classmethod + def match_affine_block_expr( + cls, + index: Expr, + index_var: Symbol, + ) -> Expr | None: + """ + Matches simple expressions of the form stride * index, returning the + stride. + """ + index = cls._preprocess(index) + stride = cls._indexing_wild_signed_int(name="stride", exclude=[index_var]) + m = index.match(index_var * stride) + if m is None: + return None + + return m[stride] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/common.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/common.py new file mode 100644 index 0000000000000000000000000000000000000000..4a1470efee625867a3c9c476ad152e839996a461 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/common.py @@ -0,0 +1,3154 @@ +from __future__ import annotations + +import atexit +import contextlib +import dataclasses +import enum +import functools +import itertools +import logging +import math +import operator +import os +import re +import tempfile +import threading +from abc import ABC, abstractmethod +from enum import auto, Enum +from itertools import chain +from typing import Any, cast, ClassVar, Generic, NamedTuple, TYPE_CHECKING +from typing_extensions import Self, TypeVar + +import sympy + +import torch +import torch.fx +from torch._prims_common import ELEMENTWISE_TYPE_PROMOTION_KIND +from torch.utils import _pytree as pytree +from torch.utils._config_module import ConfigModule +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import Max +from torch.utils._sympy.numbers import int_oo +from torch.utils._sympy.printers import PythonPrinter as _PythonPrinter +from torch.utils._sympy.symbol import free_symbol_is_type, symbol_is_type, SymT +from torch.utils._sympy.value_ranges import bound_sympy, ValueRanges + +from .. import config, metrics +from ..dtype_propagation import DtypePropagationOpsHandler +from ..ops_handler import BasicMathOpsMixin, DefaultHandler +from ..shape_propagation import ShapePropagationOpsHandler +from ..utils import ( + boolean_ops, + DeferredLineBase, + generate_assert, + get_current_backend, + IndentedBuffer, + ir_dataclass, + ScopedDict, + sympy_dot, + sympy_index_symbol, + sympy_subs, + triton_type, + unique, +) +from ..virtualized import ( + NullHandler, + ops, + OpsHandler, + OpsValue, + ReductionType, + StoreMode, + V, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, MutableMapping, Sequence + + from torch.fx import GraphModule + + from ..custom_graph_pass import CustomGraphModulePass + from ..ir import Buffer, ChoiceCaller, FixedLayout, IRNode + from ..loop_body import LoopBody + from ..scheduler import BaseScheduling, Scheduler, SchedulerNode + from ..shape_propagation import BlockShapeType + from .wrapper import PythonWrapperCodegen + + _T = TypeVar("_T") + SchedulingConstructor = Callable[[Scheduler | None], BaseScheduling] + WrapperConstructor = type[PythonWrapperCodegen] + SymbolLike = str | sympy.Symbol + + # OpVarT should really be Union[CSEVariable, str], however this + # causes typing errors in subclasses (defined in other files). + OpVarT = str + +schedule_log = torch._logging.getArtifactLogger(__name__, "schedule") +log = logging.getLogger(__name__) + + +def data_type_logger(msg: str) -> None: + if schedule_log.isEnabledFor(logging.DEBUG): + schedule_log.debug("Data type propagation: %s", msg) + + +@dataclasses.dataclass +class FileBackedGraphModule: + """ + Output of FX wrapper codegen. Exposes the same methods as ModuleType, but these + map back to a GraphModule instead of Python source. + """ + + gm: GraphModule + compiled_fn: Callable[..., Any] + + def __post_init__(self) -> None: + # Write the code to a file for compatibility with debugging utilities. + # The file is deleted upon program termination. + self.tempfile = tempfile.NamedTemporaryFile( # noqa: SIM115 + mode="w+", suffix=".py", delete=False + ) + atexit.register(os.remove, self.tempfile.name) + with self.tempfile as f: + f.write(self.value) + + @property + def __file__(self) -> str: + return self.tempfile.name + + def call(self, args: list[Any]) -> Any: + return self.compiled_fn(*args) + + @property + def value(self) -> str: + return self.gm.code + + +class WorkspaceZeroMode(enum.Enum): + UNINITIALIZED = 0 + ZERO_ON_CALL = 1 # kernel may leave workspace dirty + ZERO_PER_GRAPH = 2 # must be re-zeroed by kernel + + @staticmethod + def combine(a: WorkspaceZeroMode, b: WorkspaceZeroMode) -> WorkspaceZeroMode: + if a == b or b == WorkspaceZeroMode.UNINITIALIZED: + return a + if a == WorkspaceZeroMode.UNINITIALIZED: + return b + raise NotImplementedError(f"WorkspaceZeroMode.combine({a!r}, {b!r})") + + @staticmethod + def from_bool(zero_fill: bool) -> WorkspaceZeroMode: + if zero_fill: + return WorkspaceZeroMode.ZERO_ON_CALL + return WorkspaceZeroMode.UNINITIALIZED + + +class CodegenSymbol(ABC): + """ + An IR object possibly corresponding to a variable in the wrapper code. + """ + + @abstractmethod + def get_name(self) -> str: + pass + + @abstractmethod + def get_example(self) -> torch.Tensor | sympy.Symbol: + pass + + +@ir_dataclass(frozen=True) +class WorkspaceArg(CodegenSymbol): + """A temporary buffer used for a single kernel, then discarded. + + Not registered as a traditional buffer since there are no users, + so it would be dead code eliminated. + + Args: + nbytes: The size of the buffer in bytes. + zero_fill: Whether the buffer should be initialized to zero. + + """ + + count: sympy.Expr + zero_mode: WorkspaceZeroMode + device: torch.device + outer_name: str + inner_name: str = "ws_ptr" + dtype: torch.dtype = torch.uint8 + + @staticmethod + def unique_name(prefix: str = "workspace_") -> str: + return f"{prefix}{next(V.graph.workspace_id)}" + + @staticmethod + def can_join(a: WorkspaceArg, b: WorkspaceArg) -> bool: + return ( + a.inner_name == b.inner_name and a.dtype == b.dtype and a.device == b.device + ) + + @staticmethod + def join(a: WorkspaceArg, b: WorkspaceArg) -> WorkspaceArg: + return WorkspaceArg( + count=a.count + b.count, + zero_mode=WorkspaceZeroMode.combine(a.zero_mode, b.zero_mode), + dtype=a.dtype, + device=a.device, + inner_name=a.inner_name, + outer_name=a.outer_name, + ) + + @staticmethod + def maximum(a: WorkspaceArg, b: WorkspaceArg) -> WorkspaceArg: + if not ( + a.dtype == b.dtype and a.device == b.device and a.inner_name == b.inner_name + ): + raise AssertionError( + "WorkspaceArg.maximum requires matching dtype, device, and inner_name" + ) + return WorkspaceArg( + count=Max(a.count, b.count), + zero_mode=WorkspaceZeroMode.combine(a.zero_mode, b.zero_mode), + dtype=a.dtype, + device=a.device, + inner_name=a.inner_name, + outer_name=a.outer_name, + ) + + # These methods let WorkspaceArg pretend it is a buffer to reuse allocation code + def get_device(self) -> torch.device: + return self.device + + get_device_or_error = get_device + + def get_dtype(self) -> torch.dtype: + return self.dtype + + def get_example(self) -> torch.Tensor | sympy.Symbol: + return self.get_layout().get_example() + + def get_layout(self) -> FixedLayout: + from ..ir import FixedLayout + + return FixedLayout( + device=self.device, + dtype=self.dtype, + size=[self.count], + stride=[1], + ) + + @property + def layout(self) -> FixedLayout: + return self.get_layout() + + get_output_spec = get_layout + maybe_get_output_spec = get_layout + maybe_get_layout = get_layout + + def get_offset(self) -> sympy.Expr: + return sympy.S.Zero + + def get_size(self) -> list[sympy.Expr]: + return [self.count] + + def get_stride(self) -> list[sympy.Expr]: + return [sympy.S.One] + + def get_name(self) -> str: + return self.outer_name + + def get_is_pinned(self) -> bool: + return False + + def get_inputs_that_alias_output(self) -> list[str]: + return [] + + +class TritonScratchWorkspace: + def __init__(self, size: int, generate_dtype_str: Callable[..., str]): + self.size = size + self._generate_dtype_str = generate_dtype_str + + def generate_dtype_str(self) -> str: + return self._generate_dtype_str() + + +@dataclasses.dataclass +class TensorArg: + name: str + buffer: str + dtype: torch.dtype + offset: sympy.Expr = sympy.S.Zero # c++ only + alias_of: str | None = None # halide only + + +@dataclasses.dataclass +class SizeArg: + name: str + expr: sympy.Expr + + @property + def alias_of(self) -> str | None: + return None + + +@dataclasses.dataclass +class ConstexprArg: + name: str + + +@dataclasses.dataclass +class TMADescriptorArg: + name: str + api_type: str # "experimental" or "stable" + block_shape: list[sympy.Expr] | None # only needed for "stable" + dtype: torch.dtype | None # only needed for "stable" + + +@dataclasses.dataclass +class DeviceCodegen: + scheduling: SchedulingConstructor + wrapper_codegen: WrapperConstructor + cpp_wrapper_codegen: WrapperConstructor | None = None + fx_wrapper_codegen: WrapperConstructor | None = None + + +KernelArgType = WorkspaceArg | TensorArg | SizeArg | TMADescriptorArg | ConstexprArg + +# Device index to emit into generated code: either a literal compile-time index, or a +# code expression evaluated at run time (e.g. current_device_idx_expr() under +# compile-on-one-rank). +DeviceIdx = int | str + +device_codegens: dict[str, DeviceCodegen] = {} + + +class DeviceOpOverrides: + def import_get_raw_stream_as(self, name: str) -> str: + raise NotImplementedError + + def set_device(self, device_idx: DeviceIdx) -> str: + raise NotImplementedError + + def synchronize(self) -> str: + raise NotImplementedError + + def device_guard(self, device_idx: DeviceIdx) -> str: + raise NotImplementedError + + def current_device_idx_expr(self) -> str: + # Runtime expression evaluating to the current device index. Used under + # compile-on-one-rank so the wrapper resolves its device at run time + # (rank-agnostic) instead of baking the compile-time index. Only CUDA/ROCm + # implements this today; raise something actionable rather than a bare + # NotImplementedError from deep inside device-context codegen. + raise RuntimeError( + f"compile-on-one-rank (device-as-parameter) is not supported on " + f"{type(self).__name__}: it has no current_device_idx_expr(), so the " + f"generated wrapper would bake the compile-time device index and not be " + f"rank-portable." + ) + + def current_stream(self) -> str: + raise NotImplementedError + + def stream_handle(self, stream_name: str) -> str: + return f"{stream_name}.native_handle" + + def cpp_device_guard(self) -> str: + raise NotImplementedError + + def cpp_aoti_device_guard(self) -> str: + raise NotImplementedError + + def cpp_stream_guard(self) -> str: + raise NotImplementedError + + def cpp_aoti_stream_guard(self) -> str: + raise NotImplementedError + + def cpp_getStreamFromExternal(self) -> str: + raise NotImplementedError + + def kernel_header(self) -> str: + raise NotImplementedError + + def kernel_driver(self) -> str: + raise NotImplementedError + + def cpp_stream_type(self) -> str: + raise NotImplementedError + + def aoti_get_stream(self) -> str: + raise NotImplementedError + + def cpp_kernel_type(self) -> str: + raise NotImplementedError + + def cpp_device_ptr(self) -> str: + raise NotImplementedError + + def tma_descriptor_helpers(self) -> str: + raise NotImplementedError + + def cpp_scratch( + self, idx: int, workspace: TritonScratchWorkspace, prefix: str | None = None + ) -> tuple[list[str], str] | None: + # optionally return (scratch definition, arg name) + raise NotImplementedError + + +# Thread-safe lazy initialization for device op overrides +device_op_overrides_lock = threading.RLock() +device_op_overrides_dict: dict[str, DeviceOpOverrides] = {} +_device_op_overrides_initialized = False +custom_backend_passes: dict[str, CustomGraphModulePass | None] = {} +custom_backend_codegen_configs: dict[str, ConfigModule | None] = {} + + +# The code generated by Inductor consists of two main parts: kernel code and wrapper code. +# For any new backend looking to integrate with Inductor, customization of these two main +# parts are necessary to generate its specific code. +# +# Kernel code generation is determined by different Scheduling. Consequently, a new +# backend needs to provide a custom Scheduling for its unique kernel code generation. Currently, +# CppScheduling and TritonScheduling serve the C++/OpenMP and Triton backends, respectively. +# +# For the Wrapper, Inductor provides a PythonWrapperCodegen class to generate the Python wrapper code +# that bridges kernels. This allows out-of-tree backends to inherit from PythonWrapperCodegen, +# and override specific member functions to create backend-specific Python wrapper code. +# +# Other classes, such as CppKernel and TritonKernel, used for code generation, typically form part +# of the logic for either Scheduling or PythonWrapperCodegen. So the Scheduling and PythonWrapperCodegen interfaces +# provide flexibility to the backend. A backend can choose to implement these classes from scratch, +# or reuse them by extending and overriding as necessary. And Inductor provides the registration API, +# register_backend_for_device, to equip a new backend at runtime. +# +# Intel has developed a new backend on top of Triton to support Intel GPUs, leveraging these interfaces. +# This backend can be used as a reference: +# https://github.com/intel/intel-extension-for-pytorch/blob/5dcc9d57e5422cf295e1a1ee97896d6b6a554a85/intel_extension_for_pytorch/_inductor/__init__.py#L9 +def register_backend_for_device( + device: str, + device_scheduling: SchedulingConstructor, + device_wrapper_codegen: WrapperConstructor, + device_cpp_wrapper_codegen: WrapperConstructor | None = None, + device_fx_wrapper_codegen: WrapperConstructor | None = None, + device_custom_pass: CustomGraphModulePass | None = None, + device_custom_config: ConfigModule | None = None, +) -> None: + device_codegens[device] = DeviceCodegen( + device_scheduling, + device_wrapper_codegen, + device_cpp_wrapper_codegen, + device_fx_wrapper_codegen, + ) + custom_backend_passes[device] = device_custom_pass + if device_custom_config: + if not ( + isinstance(device_custom_config, ConfigModule) + and device_custom_config is not config + ): + raise AssertionError( + f"{device_custom_config=} cannot be the same as the default inductor config {config=}" + ) + custom_backend_codegen_configs[device] = device_custom_config + + +class BackendFeature(Enum): + FOREACH = auto() + BUCKETIZE = auto() + INPLACE_BUFFERS = auto() + MASKED_SCATTER_WITH_INDEX = auto() + SCAN = auto() + SORT = auto() + TUPLE_REDUCTION = auto() + PREFER_STORE_LOOP_ORDER = auto() + TRITON_TEMPLATES = auto() + REDUCE_TO_SINGLE_ELEMENT = auto() + + +def get_backend_features( + device: torch.device | str | None, +) -> OrderedSet[BackendFeature]: + if device is None: + return OrderedSet() + init_backend_registration() + if isinstance(device, torch.device): + device_type = device.type + else: + if not isinstance(device, str): + raise AssertionError(type(device)) + device_type = device + device = torch.device(device_type) + scheduling_ctor = get_scheduling_for_device(device_type) + if not scheduling_ctor: + raise AssertionError(f"no scheduling registered for device {device_type}") + scheduling = scheduling_ctor(None) + return scheduling.get_backend_features(device) + + +def has_backend_feature( + device: torch.device | str | None, feature: BackendFeature +) -> bool: + """See also V.graph.has_feature""" + if not isinstance(feature, BackendFeature): + raise AssertionError(f"expected BackendFeature, got {type(feature)}") + return feature in get_backend_features(device) + + +def get_scheduling_for_device(device: str) -> SchedulingConstructor | None: + return device_codegens[device].scheduling if device in device_codegens else None + + +def get_wrapper_codegen_for_device( + device: str, cpp_wrapper: bool = False, fx_wrapper: bool = False +) -> WrapperConstructor | None: + if device in device_codegens: + wrapper_codegen_obj: DeviceCodegen = device_codegens[device] + if fx_wrapper: + return wrapper_codegen_obj.fx_wrapper_codegen + elif cpp_wrapper: + cpp_wrapper_codegen = wrapper_codegen_obj.cpp_wrapper_codegen + # allow_stack_allocation is a per-compile config, so the arrayref CPU + # wrapper must follow the current config value rather than whatever it + # happened to be at first registration (see init_backend_registration). + if device == "cpu" and config.aot_inductor.allow_stack_allocation: + from .cpp_wrapper_cpu import CppWrapperCpu + from .cpp_wrapper_cpu_array_ref import CppWrapperCpuArrayRef + + if cpp_wrapper_codegen is CppWrapperCpu: + return CppWrapperCpuArrayRef + return cpp_wrapper_codegen + else: + return wrapper_codegen_obj.wrapper_codegen + return None + + +def get_custom_backend_pass_for_device(device: str) -> CustomGraphModulePass | None: + return custom_backend_passes.get(device) + + +def get_custom_backend_config_for_device(device: str) -> ConfigModule | None: + return custom_backend_codegen_configs.get(device) + + +@functools.cache +def init_backend_registration() -> None: + """ + Register the backend for different devices, including the scheduling + for kernel code generation and the host side wrapper code generation. + """ + from .cpp import CppScheduling + from .cpp_wrapper_cpu import CppWrapperCpu + from .cpp_wrapper_gpu import CppWrapperGpu + from .cpp_wrapper_mps import CppWrapperMps + from .cuda_combined_scheduling import CUDACombinedScheduling + from .halide import HalideScheduling + from .mps import MetalScheduling + from .pallas import PallasScheduling + from .python_wrapper_mtia import PythonWrapperMtia + from .triton import TritonScheduling + from .wrapper import PythonWrapperCodegen + from .wrapper_fxir import WrapperFxCodegen + from .xpu.xpu_combined_scheduling import XPUCombinedScheduling + + if get_scheduling_for_device("cpu") is None: + cpu_backends = { + "cpp": CppScheduling, + "halide": HalideScheduling, + "triton": TritonScheduling, + "pallas": PallasScheduling, + } + register_backend_for_device( + "cpu", + lambda scheduling: cpu_backends[config.cpu_backend](scheduling), + PythonWrapperCodegen, + # allow_stack_allocation selects CppWrapperCpuArrayRef, but that is a + # per-compile config; the choice is made dynamically in + # get_wrapper_codegen_for_device rather than frozen here at the + # process's first registration. + CppWrapperCpu, + WrapperFxCodegen, + ) + + if get_scheduling_for_device("cuda") is None: + # CUDACombinedScheduling combines Triton and CUDA C++ scheduling for CUDA devices via delegation + cuda_backends = { + "triton": CUDACombinedScheduling, + "halide": HalideScheduling, + "pallas": PallasScheduling, + } + register_backend_for_device( + "cuda", + lambda scheduling: cuda_backends[config.cuda_backend](scheduling), + PythonWrapperCodegen, + CppWrapperGpu, + WrapperFxCodegen, + ) + + if get_scheduling_for_device("tpu") is None: + register_backend_for_device( + "tpu", + PallasScheduling, + PythonWrapperCodegen, + # CppWrapperGpu, + # WrapperFxCodegen, + ) + + if get_scheduling_for_device("xpu") is None: + register_backend_for_device( + "xpu", + XPUCombinedScheduling, + PythonWrapperCodegen, + CppWrapperGpu, + WrapperFxCodegen, + ) + + if get_scheduling_for_device("tpu") is None: + tpu_backends = { + "pallas": PallasScheduling, + } + register_backend_for_device( + "tpu", + lambda scheduling: tpu_backends[config.tpu_backend](scheduling), + PythonWrapperCodegen, + ) + + if get_scheduling_for_device("mps") is None: + register_backend_for_device( + "mps", + MetalScheduling, + PythonWrapperCodegen, + CppWrapperMps, + WrapperFxCodegen, + ) + + if get_scheduling_for_device("mtia") is None: + register_backend_for_device( + "mtia", + TritonScheduling, + PythonWrapperMtia, + CppWrapperGpu, + WrapperFxCodegen, + ) + + private_backend = torch._C._get_privateuse1_backend_name() + if ( + private_backend != "privateuseone" + and get_scheduling_for_device(private_backend) is None + ): + from torch.utils.backend_registration import _get_custom_mod_func + + try: + device_scheduling = _get_custom_mod_func("Scheduling") + wrapper_codegen = _get_custom_mod_func("PythonWrapperCodegen") + cpp_wrapper_codegen = _get_custom_mod_func("CppWrapperCodegen") + fx_wrapper_codegen = _get_custom_mod_func("WrapperFxCodegen") + if device_scheduling and wrapper_codegen and cpp_wrapper_codegen: + register_backend_for_device( + private_backend, + device_scheduling, + wrapper_codegen, + cpp_wrapper_codegen, + fx_wrapper_codegen, + ) + except RuntimeError: + pass + + +def index_prevent_reordering( + index: Sequence[sympy.Expr], + index_vars: Sequence[sympy.Expr], + sizes: Sequence[sympy.Expr], +) -> list[sympy.Expr]: + from ..ir import FlexibleLayout + + # added contiguous index prevents reordering + return [*index, sympy_dot(index_vars, FlexibleLayout.contiguous_strides(sizes))] + + +def register_device_op_overrides( + device: str, device_op_overrides: DeviceOpOverrides +) -> None: + with device_op_overrides_lock: + device_op_overrides_dict[device] = device_op_overrides + + +def _initialize_device_op_overrides(): + # Use a flag rather than checking device_op_overrides_dict, since external/test + # code may partially populate it before we are called. + global _device_op_overrides_initialized + if _device_op_overrides_initialized: + return + + with device_op_overrides_lock: + if _device_op_overrides_initialized: + return + + from . import mps_device_op_overrides # noqa: F401 + from .cpu_device_op_overrides import CpuDeviceOpOverrides + from .cuda import device_op_overrides # noqa: F401 + from .mtia import device_op_overrides as mtia_op_overrides # noqa: F401 + from .xpu import device_op_overrides as xpu_op_overrides # noqa: F401 + + # TPU uses Pallas for codegen and only needs no-op overrides + register_device_op_overrides("tpu", CpuDeviceOpOverrides()) + + _device_op_overrides_initialized = True + + +def get_device_op_overrides(device: str) -> DeviceOpOverrides: + if not isinstance(device, str): + raise AssertionError(type(device)) + _initialize_device_op_overrides() + return device_op_overrides_dict[device] + + +DTYPE_TO_COMPUTATION_DTYPE: dict[torch.dtype, torch.dtype] = { + torch.bfloat16: torch.float, + torch.float16: torch.float, + **{ + dtype: dtype + for dtype in [ + torch.bool, + torch.float32, + torch.float64, + torch.int8, + torch.int16, + torch.int32, + torch.int64, + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + ] + }, +} + + +def deduce_output_dtype_by_name( + op_name: str, + *args: Any, + **kwargs: Any, +) -> torch.dtype | None: + """ + Given op name and a list of input dtypes, deduce the output dtype + """ + if op_name in boolean_ops(): + return torch.bool + elif op_name in ( + "to_dtype", + "index_expr", + "value_expr", + ): + return kwargs["dtype"] if "dtype" in kwargs else args[-1] + elif op_name in ( + "rand", + "randn", + ): + return torch.float + elif op_name in ( + "get_index", + "randint64", + "load_seed", + ): + return torch.int64 + elif op_name == "reduction": + return kwargs["dtype"] if "dtype" in kwargs else args[1] + elif op_name == "constant": + return kwargs["dtype"] if "dtype" in kwargs else args[-1] + elif op_name in ( + "load", + "store", + "store_reduction", + ): + buf_name = args[1] + return V.graph.get_dtype(buf_name) # type: ignore[arg-type] + elif op_name == "to_dtype_bitcast": + return kwargs["dtype"] if "dtype" in kwargs else args[-2] + return None + + +def _is_runtime_triton_assert_target() -> bool: + return ( + get_current_backend() == "triton" + and V.graph.get_current_device_or_throw().type != "cpu" + and hasattr(V.kernel, "triton_tensor_ndim") + ) + + +def check_dtype( + buffer: IndentedBuffer, var: CSEVariableType, dtype: torch.dtype +) -> None: + backend = get_current_backend() + if ( + config.test_configs.runtime_triton_dtype_assert + and _is_runtime_triton_assert_target() + ): + buffer.writeline(f"tl.static_assert({var}.dtype == {triton_type(dtype)})") + elif config.test_configs.static_cpp_dtype_assert and backend == "cpp": + from .cpp_utils import CppCSEVariable, DTYPE_TO_CPP + + if not isinstance(var, CppCSEVariable): + raise AssertionError(type(var)) + if dtype == torch.bool: + if var.is_vec: + is_same_dt = f"IsVecMaskType::value" + else: + # operator&(bool, bool) returns int and it can be used as boolean in C++ + is_same_dt = f"std::is_same_v || std::is_same_v" + else: + c_var_type = f"decltype({var})" + if var.is_vec: + c_var_type = f"typename {c_var_type}::value_type" + is_same_dt = f"std::is_same_v<{c_var_type}, {DTYPE_TO_CPP[dtype]}>" + + buffer.writeline(f"static_assert({is_same_dt});") + + +def check_shape( + buffer: IndentedBuffer, var: CSEVariableType, shape: BlockShapeType +) -> None: + if shape is None: + raise AssertionError("expected shape to be not None") + if ( + config.test_configs.runtime_triton_shape_assert + and _is_runtime_triton_assert_target() + ): + shape_str = ( + ", ".join(str(d) for d in shape) if len(shape) != 1 else f"{shape[0]}," + ) + buffer.writeline(f"tl.static_assert({var}.shape == ({shape_str}))") + + +def check_nan(buffer: IndentedBuffer, var: CSEVariableType) -> None: + backend = get_current_backend() + if backend == "triton": + msg = "NaN or Inf found" + buffer.writeline( + f"tl.device_assert(({var} == {var}) & ({var} != float('inf')) & ({var} != float('-inf')), '{msg}')" + ) + + +class DataTypePropagation: + def __init__(self, body: LoopBody) -> None: + self.body = body + self.graphs: dict[Callable[..., Any] | str, Any] = { + "root": body.root_block.graph + } + for k, v in body.subblocks.items(): + self.graphs[k] = v.graph + + def deduce_node_dtype_by_inputs(self, node: torch.fx.Node) -> torch.dtype | None: + inputs = node.all_input_nodes + input_nodes = [ + n for n in inputs if isinstance(n, torch.fx.Node) and n.op != "placeholder" + ] + if len(input_nodes) == 0: + return None + + all_input_nodes_propagated = all( + OptimizationContext.key in n.meta + and n.meta[OptimizationContext.key].dtype is not None + for n in input_nodes + ) + if not all_input_nodes_propagated: + return None + + return functools.reduce( + torch.promote_types, + [n.meta[OptimizationContext.key].dtype for n in input_nodes], + ) + + def deduce_node_dtype_by_subgraph(self, node: torch.fx.Node) -> torch.dtype: + sub_graph = self.graphs[node.target] + dtype = self.propagate_graph(sub_graph) + if not dtype: + raise AssertionError("expected subgraph to propagate a dtype") + return dtype + + def deduce_node_dtype(self, node: torch.fx.Node) -> torch.dtype | None: + if node.op == "placeholder": + return None + + if node.target == "output" and len(node.args) != 1: + # we can infer output node if it only have 1 arg + return None + + if node.target is operator.getitem: + node_arg = node.args[0] + if not isinstance(node_arg, torch.fx.Node): + raise AssertionError(type(node_arg)) + return self.deduce_node_dtype(node_arg) + + if not isinstance(node.target, str): + raise AssertionError(type(node.target)) + + if node.target.startswith("masked_subblock"): + return self.deduce_node_dtype_by_subgraph(node) + + if ( + output_dtype := deduce_output_dtype_by_name( + node.target, + *node.args, + **node.kwargs, + ) + ) is not None: + return output_dtype + + return self.deduce_node_dtype_by_inputs(node) + + def propagate_graph(self, graph: torch.fx.Graph) -> torch.dtype | None: + if not graph.nodes: + raise AssertionError("expected graph to have nodes") + graph_dtype: torch.dtype | None = None + # For masked_subblock, we use output's dtype to represent + # the dtype of this subgraph. For other cases, graph_dtype + # might be None + for node in graph.nodes: + if OptimizationContext.key in node.meta: + opt_ctx = node.meta[OptimizationContext.key] + else: + opt_ctx = OptimizationContext() + + opt_ctx.dtype = self.deduce_node_dtype(node) + node.meta[OptimizationContext.key] = opt_ctx + if node.target == "output": + graph_dtype = opt_ctx.dtype + return graph_dtype + + def propagate(self) -> torch.dtype | None: + return self.propagate_graph(self.graphs["root"]) + + @classmethod + def propagate_loopbody(cls, body: LoopBody) -> torch.dtype | None: + return cls(body).propagate() + + @classmethod + def propagate_scheduler_node(cls, node: SchedulerNode) -> torch.dtype | None: + from ..loop_body import LoopBody + from ..scheduler import SchedulerNode + + if not isinstance(node, SchedulerNode): + raise AssertionError(type(node)) + if not isinstance(node._body, LoopBody): + raise AssertionError(type(node._body)) + return DataTypePropagation.propagate_loopbody(node._body) + + +class PythonPrinter(_PythonPrinter): + def doprint( + self, expr: sympy.Expr, *, simplify: bool = True, p: bool = True + ) -> str: + # TODO: why are people passing strings to the printer here :think: + if simplify and isinstance(expr, sympy.Expr) and hasattr(V.graph, "sizevars"): + expr = V.graph.sizevars.simplify(expr) + return super().doprint(expr) + + def parenthesize(self, item: sympy.Expr, level: int, strict: bool = False) -> str: + if isinstance(item, sympy.Mod): + # use parenthesis to enforce precedence. + # in sympy 1.13.3, -2*Mod(x,y) becomes -2*x%y, which is wrong. + # pyrefly: ignore [missing-attribute] + return f"({self._print(item)})" + else: + return super().parenthesize(item, level, strict) + + +class OpDecompositions: + """ + Decomposes inductor ops + """ + + @staticmethod + def identity(value: OpVarT) -> OpVarT: + # used to trigger cse + return value + + @staticmethod + def reciprocal(x: OpVarT) -> OpVarT: + # Use float32 constant so that div_rn can be applied when + # eager_numerics.division_rounding is enabled + return ops.truediv(ops.constant(1.0, torch.float32), x) + + @staticmethod + def square(x: OpVarT) -> OpVarT: + return ops.mul(x, x) + + @staticmethod + def erfc(x: OpVarT) -> OpVarT: + return ops.sub(ops.constant(1, torch.float32), ops.erf(x)) + + @staticmethod + def erfcx(x: OpVarT) -> OpVarT: + return ops.mul(ops.exp(ops.square(x)), ops.erfc(x)) + + @staticmethod + def expm1(x: OpVarT) -> OpVarT: + return ops.sub(ops.exp(x), ops.constant(1, torch.float32)) + + @staticmethod + def log10(x: OpVarT) -> OpVarT: + return ops.mul(ops.log(x), ops.constant(1 / math.log(10), torch.float32)) + + @staticmethod + def log2(x: OpVarT) -> OpVarT: + return ops.mul(ops.log(x), ops.constant(1 / math.log(2), torch.float32)) + + @staticmethod + def exp2(x: OpVarT) -> OpVarT: + return ops.exp(ops.mul(x, ops.constant(math.log(2), torch.float32))) + + @staticmethod + def log1p(x: OpVarT) -> OpVarT: + return ops.log(ops.add(x, ops.constant(1, torch.int32))) + + @staticmethod + def sigmoid(x: OpVarT) -> OpVarT: + one = ops.constant(1, torch.int32) + return ops.truediv(one, ops.add(one, ops.exp(ops.neg(x)))) + + @staticmethod + def relu(x: OpVarT) -> OpVarT: + return ops.maximum(x, ops.constant(0, torch.int32)) + + @staticmethod + def fma(x: OpVarT, y: OpVarT, z: OpVarT) -> OpVarT: + # for backends that don't override this (halide) + return ops.add(ops.mul(x, y), z) + + @staticmethod + def mul_rn(x: OpVarT, y: OpVarT) -> OpVarT: + # for backends that don't override this, just use regular mul + return ops.mul(x, y) + + @staticmethod + def div_rn(x: OpVarT, y: OpVarT) -> OpVarT: + # for backends that don't override this, just use regular div + return ops.truediv(x, y) + + @staticmethod + def floor_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.floor(a), dtype) + + @staticmethod + def ceil_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.ceil(a), dtype) + + @staticmethod + def trunc_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.trunc(a), dtype) + + @staticmethod + def remainder(a: OpVarT, b: OpVarT) -> OpVarT: + r = ops.mod(a, b) + cond = ops.and_( + ops.ne(r, ops.constant(0, torch.int32)), + ops.ne(ops.signbit(r), ops.signbit(b)), + ) + return ops.where(cond, ops.add(r, b), r) + + @staticmethod + def round_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.round(a), dtype) + + +_RE_PAREN_NOT_NEEDED = re.compile(r"[a-z0-9_.]+|\([^)]*\)|", flags=re.IGNORECASE) + + +def _all_in_parens(string: str) -> bool: + if string[0] != "(" or len(string) < 2: + return False + count = 1 + for i, char in enumerate(string[1:]): + if char == "(": + count += 1 + elif char == ")": + count -= 1 + if count == 0 and i != len(string) - 2: + return False + if count != 0: + raise AssertionError(f"expected balanced count == 0, got {count}") + return True + + +# pyrefly: ignore [inconsistent-inheritance] +class OpOverrides(BasicMathOpsMixin, OpDecompositions, OpsHandler[Any]): + @staticmethod + def paren(string: OpVarT) -> OpVarT: + if ( + isinstance(string, CSEVariable) + or _RE_PAREN_NOT_NEEDED.fullmatch(string) + or _all_in_parens(string) + ): + # don't put extra parens for strings that are already wrapped in parens + + return string + return f"({string})" + + @staticmethod + def constant(value: bool | float | int, dtype: torch.dtype) -> OpVarT: + return repr(value) + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_not(x: OpVarT) -> OpVarT: + return f"~{OpOverrides.paren(x)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_not(a: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(a)} == 0" + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_and(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} & {OpOverrides.paren(y)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_or(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} | {OpOverrides.paren(y)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_xor(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} ^ {OpOverrides.paren(y)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_left_shift(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} << {OpOverrides.paren(y)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_right_shift(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} >> {OpOverrides.paren(y)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def int_truediv(a: OpVarT, b: OpVarT) -> OpVarT: + # TODO: this is wrong + # TODO: an easy bandaid is to generate runtime asserts that it's + # <= 2**53, which is when this equation is correct + return ops.truediv(a, b) + + @staticmethod + def load_seed(name: str, offset: OpVarT) -> OpVarT: + return ops.load(name, sympy.Integer(offset)) + + def indirect_indexing( + self, + var: OpVarT, + size: sympy.Expr | int, + check: bool = True, + wrap_neg: bool = True, + ) -> sympy.Symbol: + return sympy_index_symbol(str(var)) + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + raise NotImplementedError( + f"{type(self).__name__}: check_bounds should be handled by CSEProxy" + ) + + def load(self, name: str, index: sympy.Expr) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: load should be handled by CSEProxy" + ) + + def store( + self, name: str, index: sympy.Expr, value: OpVarT, mode: StoreMode = None + ) -> None: + raise NotImplementedError( + f"{type(self).__name__}: store should be handled by CSEProxy" + ) + + def device_assert_async(self, cond: CSEVariable, msg: str) -> None: + raise NotImplementedError( + f"{type(self).__name__}: device_assert_async should be handled by CSEProxy" + ) + + def store_reduction(self, name: str, index: sympy.Expr, value: OpVarT) -> None: + raise NotImplementedError( + f"{type(self).__name__}: store_reduction should be handled by CSEProxy" + ) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: OpVarT | tuple[OpVarT, ...], + ) -> OpVarT | tuple[OpVarT, ...]: + raise NotImplementedError( + f"{type(self).__name__}: reduction should be handled by CSEProxy" + ) + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[OpVarT, ...], tuple[OpVarT, ...]], + tuple[OpVarT, ...], + ], + values: tuple[OpVarT, ...], + ) -> tuple[OpVarT, ...]: + raise NotImplementedError( + f"{type(self).__name__}: scan should be handled by CSEProxy" + ) + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[OpVarT, ...], + stable: bool, + descending: bool, + ) -> tuple[OpVarT, ...]: + raise NotImplementedError( + f"{type(self).__name__}: sort should be handled by CSEProxy" + ) + + def bucketize( + self, + values: OpVarT, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: OpVarT, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: OpVarT | None = None, + ) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: bucketize should be handled by CSEProxy" + ) + + def halide_clamp(self, value: OpVarT, size: sympy.Expr, check: bool) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: halide_clamp only implemented for Halide backend" + ) + + def dot(self, x: OpVarT, y: OpVarT) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: dot only implemented for Triton backend" + ) + + def inline_asm_elementwise( + self, + *inputs: OpVarT, + asm: str, + constraints: str | None = None, + dtype: torch.dtype = torch.float32, + is_pure: bool = True, + pack: int = 1, + input_dtypes: tuple[torch.dtype, ...] | None = None, + ) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: inline_asm_elementwise only implemented for Triton backend" + ) + + def output(self, *args: OpVarT) -> None: + raise AssertionError( + f"{type(self).__name__}: ops.output should not appear at codegen time" + ) + + def placeholder(self, index: int) -> OpVarT: + raise AssertionError( + f"{type(self).__name__}: ops.placeholder should not appear at codegen time" + ) + + @staticmethod + def _unimplemented(name: str) -> Callable[..., OpVarT]: + def unimplemented(self: OpOverrides, *args: Any, **kwargs: Any) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__} does not implement ops.{name}" + ) + + unimplemented.__name__ = name + unimplemented.is_unimplemented = True # type: ignore[attr-defined] + return unimplemented + + @classmethod + def _is_unimplemented(cls, name: str) -> bool: + fn = getattr(cls, name, None) + default_fn = getattr(OpsHandler, name, None) + return not fn or fn == default_fn or getattr(fn, "is_unimplemented", False) + + @classmethod + def _initialize_pointwise_overrides(cls, target: str) -> None: + if target not in ("triton", "cpp", "cppvec", "halide", "mps"): + raise AssertionError(target) + + for funcname, data in pointwise_overrides_data.items(): + impl = getattr(data, target) + if impl is None: + if cls._is_unimplemented(funcname): + setattr(cls, funcname, cls._unimplemented(funcname)) + else: + if funcname in cls.__dict__: + raise AssertionError( + f"multiple definitions of {funcname} on {cls.__name__}" + ) + impl.__name__ = funcname + setattr(cls, funcname, staticmethod(impl)) + + +@dataclasses.dataclass +class OverridesData: + name: str + cpp: Callable[..., str] + # None when not impl in libdevice/triton + triton: Callable[..., str] | None = None + # None when not impl in aten/.../vec + cppvec: Callable[..., str] | None = None + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND = ( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + halide: Callable[..., str] | None = None + mps: Callable[..., str] | None = None + + +def _triton_bessel(order: int, kind: str, x: str) -> str: + # PyTorch eager returns NaN for +/-inf, while libdevice returns + # the mathematical limit. x - x yields NaN in x's dtype + # (avoids fp32 literal promotion under tl.where for float64 inputs) + return ( + f"tl.where(tl_math.abs({x}) == float('inf'), " + f"{x} - {x}, " + f"libdevice.{kind}{order}({x}))" + ) + + +def _triton_cyl_bessel_i(order: int, x: str) -> str: + # PyTorch's Cephes-derived kernels return NaN for infinities; libdevice + # returns signed infinities, so synthesize a same-dtype NaN with x - x. + return ( + f"tl.where(tl.abs({x}) == float('inf'), " + f"{x} - {x}, " + f"libdevice.cyl_bessel_i{order}({x}))" + ) + + +# NB: if you add a new special function, don't forget to update +# torch._inductor.ops_handler too +pointwise_overrides_data: dict[str, OverridesData] = dict( + airy_ai=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"airy_ai_forward({x})", + name="special_airy_ai", + ), + bessel_j0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_j0_forward({x})", + triton=lambda x: _triton_bessel(0, "j", x), + name="special_bessel_j0", + ), + bessel_j1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_j1_forward({x})", + triton=lambda x: _triton_bessel(1, "j", x), + name="special_bessel_j1", + ), + bessel_y0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_y0_forward({x})", + triton=lambda x: _triton_bessel(0, "y", x), + name="special_bessel_y0", + ), + bessel_y1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_y1_forward({x})", + triton=lambda x: _triton_bessel(1, "y", x), + name="special_bessel_y1", + ), + digamma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_digamma({x})", + cppvec=lambda x: f"{x}.digamma()", + name="digamma", + ), + # no cpp nor triton implementation for entr, it is defined as decomposition + # erf, erfc + erfcx=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_erfcx({x})", + triton=lambda x: f"libdevice.erfcx({x})", + name="special_erfcx", + ), + fma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y, z: f"std::fma({x}, {y}, {z})", + cppvec=lambda x, y, z: f"fmadd({x}, {y}, {z})", + # NOTE: We use tl.fma instead of libdevice.fma because libdevice.fma + # has Flush-To-Zero (FTZ) behavior for subnormal values, which causes + # numerical differences compared to eager CUDA execution. tl.fma + # preserves subnormals and matches eager's FMA precision. + triton=lambda x, y, z: f"tl.fma({x}, {y}, {z})", + name="fma", + ), + # mul_rn: Multiplication with round-to-nearest. This prevents Triton's + # compiler from fusing the multiplication with subsequent operations, + # which is needed to match eager's rounding behavior in operations like + # addcmul where the product must be rounded before use. + # Note: libdevice.mul_rn is not supported on ROCm, so we fall back to + # regular multiplication there. + mul_rn=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + cpp=lambda x, y: f"({x}) * ({y})", # C++ doesn't need special handling + triton=lambda x, y: f"({x}) * ({y})" + if torch.version.hip + else f"libdevice.mul_rn({x}, {y})", + name="mul_rn", + ), + # erfinv, exp2, expit, gammaln + igamma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igamma({x}, {y})", + name="igamma", + ), + igammac=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igammac({x}, {y})", + name="igammac", + ), + gammainc=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igamma({x}, {y})", + name="special_gammainc", + ), + gammaincc=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igammac({x}, {y})", + name="special_gammaincc", + ), + i0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i0({x})", + triton=lambda x: _triton_cyl_bessel_i(0, x), + cppvec=lambda x: f"{x}.i0()", + name="i0", + ), + i0e=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i0e({x})", + cppvec=lambda x: f"{x}.i0e()", + name="special_i0e", + ), + i1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i1({x})", + triton=lambda x: _triton_cyl_bessel_i(1, x), + name="special_i1", + ), + i1e=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i1e({x})", + name="special_i1e", + ), + log_ndtr=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_log_ndtr({x})", + name="special_log_ndtr", + ), + # logit + modified_bessel_i0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_i0_forward({x})", + triton=lambda x: _triton_cyl_bessel_i(0, x), + name="special_modified_bessel_i0", + ), + modified_bessel_i1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_i1_forward({x})", + triton=lambda x: _triton_cyl_bessel_i(1, x), + name="special_modified_bessel_i1", + ), + modified_bessel_k0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_k0_forward({x})", + name="special_modified_bessel_k0", + ), + modified_bessel_k1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_k1_forward({x})", + name="special_modified_bessel_k1", + ), + # multigamma + ndtr=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_ndtr({x})", + name="special_ndtr", + ), + ndtri=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_ndtri({x})", + name="special_ndtri", + ), + polygamma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, + y: f"{x} == 0 ? calc_digamma({y}) : ({x} == 1 ? trigamma({y}) : calc_polygamma({y}, {x}))", + name="polygamma", + ), + # psi - alias to digamma + # round + scaled_modified_bessel_k0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"scaled_modified_bessel_k0_forward({x})", + name="special_scaled_modified_bessel_k0", + ), + scaled_modified_bessel_k1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"scaled_modified_bessel_k1_forward({x})", + name="special_scaled_modified_bessel_k1", + ), + # sinc + spherical_bessel_j0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"spherical_bessel_j0_forward({x})", + name="special_spherical_bessel_j0", + ), + zeta=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"zeta({x}, {y})", + name="special_zeta", + ), + chebyshev_polynomial_t=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_t_forward({x}, {y})", + name="special_chebyshev_polynomial_t", + ), + chebyshev_polynomial_u=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_u_forward({x}, {y})", + name="special_chebyshev_polynomial_u", + ), + chebyshev_polynomial_v=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_v_forward({x}, {y})", + name="special_chebyshev_polynomial_v", + ), + chebyshev_polynomial_w=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_w_forward({x}, {y})", + name="special_chebyshev_polynomial_w", + ), + legendre_polynomial_p=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"legendre_polynomial_p_forward({x}, {y})", + name="special_legendre_polynomial_p", + ), + shifted_chebyshev_polynomial_t=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_t_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_t", + ), + shifted_chebyshev_polynomial_u=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_u_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_u", + ), + shifted_chebyshev_polynomial_v=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_v_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_v", + ), + shifted_chebyshev_polynomial_w=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_w_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_w", + ), + hermite_polynomial_h=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"hermite_polynomial_h_forward({x}, {y})", + name="special_hermite_polynomial_h", + ), + hermite_polynomial_he=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"hermite_polynomial_he_forward({x}, {y})", + name="special_hermite_polynomial_he", + ), + laguerre_polynomial_l=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"laguerre_polynomial_l_forward({x}, {y})", + name="special_laguerre_polynomial_l", + ), +) + + +def is_buffer_removed(name: str) -> bool: + return any( + name in x + for x in ( + V.graph.removed_buffers, + V.kernel.removed_buffers, + V.graph.inplaced_to_remove, + V.kernel.inplaced_to_remove, + ) + ) + + +class DeferredLine(DeferredLineBase): + """A line that can be 'unwritten' by adding name to V.graph.removed_buffers""" + + def __init__(self, name: str, line: str): + super().__init__(line) + self.name = name + if isinstance(line, DeferredLineBase): + raise AssertionError("line must not be a DeferredLineBase") + + def __call__(self) -> str | None: + if not is_buffer_removed(self.name): + return self.line + return None + + def _new_line(self, line: str) -> DeferredLine: + return DeferredLine(self.name, line) + + +class BracesBuffer(IndentedBuffer): + def indent(self, offset: int = 1) -> contextlib.AbstractContextManager[None]: + @contextlib.contextmanager + def ctx() -> Iterator[None]: + for _ in range(offset): + self.writeline("{") + self._indent += 1 + for _ in range(-offset): + self._indent -= 1 + self.writeline("}") + yield + for _ in range(-offset): + self.writeline("{") + self._indent += 1 + for _ in range(offset): + self._indent -= 1 + self.writeline("}") + + return ctx() + + +class InplacedBuffer(NamedTuple): + inner_name: str + other_names: list[str] + + +@dataclasses.dataclass +class ArgName: + name: str + # is_constexpr=True is used to attach a " : tl.constexpr" into the argument list + is_constexpr: bool = False + + def full_name(self) -> str: + return f"{self.name}{' : tl.constexpr' if self.is_constexpr else ''}" + + +class RemovedArg: + def __str__(self) -> str: + return "REMOVED" + + +REMOVED = RemovedArg() + + +class KernelArgs: + @staticmethod + def _lookup( + prefix: str, + odict: dict[_T, str | RemovedArg] | dict[_T, str], + name: _T, + ) -> str: + result: str | RemovedArg = odict.get(name, REMOVED) + if isinstance(result, RemovedArg): + odict[name] = new_result = f"{prefix}{len(odict)}" + return new_result + return result + + def __init__(self) -> None: + self.input_buffers: dict[str, str] = {} + self.output_buffers: dict[str, str | RemovedArg] = {} + self.inplace_buffers: dict[str, InplacedBuffer | RemovedArg] = {} + self.sizevars: dict[sympy.Expr, str] = {} + self.workspace_args: list[WorkspaceArg] = [] + + def __repr__(self) -> str: + return "KernelArgs({})".format( + ", ".join( + map( + repr, + [ + self.input_buffers, + self.output_buffers, + self.inplace_buffers, + self.sizevars, + ], + ) + ) + ) + + @staticmethod + def _buffer_is_marked_removed(name: Any) -> bool: + # this function is needed by MTIA + return isinstance(name, RemovedArg) + + def input(self, name: str) -> str: + if V.graph.scheduler: + name = V.graph.scheduler.mutation_real_name.get(name, name) + if name in V.graph.removed_buffers: + raise AssertionError(name) + if name in self.output_buffers: + return cast(str, self.output_buffers[name]) + if name in self.inplace_buffers: + return cast(InplacedBuffer, self.inplace_buffers[name]).inner_name + if name.startswith("seed"): + return self._lookup("seed", self.input_buffers, name) + return self._lookup("in_ptr", self.input_buffers, name) + + def output(self, name: str) -> str: + if V.graph.scheduler: + name = V.graph.scheduler.mutation_real_name.get(name, name) + if name in V.graph.removed_buffers: + raise AssertionError(name) + if name in self.inplace_buffers: + return cast(InplacedBuffer, self.inplace_buffers[name]).inner_name + return self._lookup("out_ptr", self.output_buffers, name) + + def make_inplace(self, input_name: str, output_name: str) -> None: + if input_name in V.graph.unaligned_buffers: + V.graph.unaligned_buffers.add(output_name) + if output_name in self.inplace_buffers: + raise AssertionError(output_name) + if input_name in self.inplace_buffers: + buf = self.inplace_buffers[input_name] + if isinstance(buf, RemovedArg): + raise AssertionError("buf must not be a RemovedArg") + buf.other_names.append(output_name) + self.inplace_buffers[output_name] = buf + else: + alive_buffers = [ + val + for val in self.inplace_buffers.values() + if not isinstance(val, RemovedArg) + ] + removed_buffers = [ + val + for val in self.inplace_buffers.values() + if isinstance(val, RemovedArg) + ] + inplace_buffer_idx = len(unique(alive_buffers)) + len(removed_buffers) + buf = InplacedBuffer( + f"in_out_ptr{inplace_buffer_idx}", + [input_name, output_name], + ) + self.inplace_buffers[input_name] = buf + self.inplace_buffers[output_name] = buf + + def workspace( + self, nelem: sympy.Expr, zero_fill: bool, dtype: torch.dtype = torch.uint8 + ) -> tuple[str, str, int]: + """ + Allocate or extend a workspace buffer of nelem elements. + + This function manages the allocation of a workspace buffer. It either creates + a new WorkspaceArg or extends an existing one. + + Note: + - Calling this function will in-place mutate the args by adding or updating + a WorkspaceArg. + - The codegen for generating the Python argdefs and call_defs will check + this field and allocate the buffer accordingly. + - A new argument "ws_ptr" will be present in the generated code. + + Args: + nelem (sympy.Expr): The number of elements to allocate. + zero_fill (bool): Whether to initialize the buffer to zero. + dtype (torch.dtype): the dtype of the workspace tensor + + Returns: + Tuple[str, str, int]: A tuple containing: + - "ws_ptr": A string identifier for the workspace pointer. + - "workspace_{i}": a graph level unique identifier for + the workspace tensor. + - offset: An integer representing the item offset in the workspace. + """ + arg = WorkspaceArg( + count=nelem, + zero_mode=WorkspaceZeroMode.from_bool(zero_fill), + device=V.graph.get_current_device_or_throw(), + outer_name=WorkspaceArg.unique_name(), + dtype=dtype, + ) + for i, existing_arg in enumerate(self.workspace_args): + if WorkspaceArg.can_join(existing_arg, arg): + offset = existing_arg.count + self.workspace_args[i] = WorkspaceArg.join(existing_arg, arg) + return existing_arg.inner_name, existing_arg.outer_name, offset + if not ( + existing_arg.inner_name != arg.inner_name + and existing_arg.outer_name != arg.outer_name + ): + raise AssertionError(existing_arg) + self.workspace_args.append(arg) + return arg.inner_name, arg.outer_name, 0 + + def semaphores(self, min_size: sympy.Expr) -> str: + """ + Lazily allocate a graph-wide semaphores buffer with at least min_size. This is a single buffer shared by + all kernels and zero initialized once at graph start. Each kernel must leave the buffer zeroed on exit. + + Warning: multiple calls to this function will return the same buffer. + + Args: + min_size: the number of int32 semaphores required + + Returns: + name of the semaphores buffer + """ + from torch.fx.experimental.proxy_tensor import _coor_enabled + + current_device = V.graph.get_current_device_or_throw() + # This name is emitted into the wrapper, so under compile-on-one-rank it cannot + # carry the rank's device index (the graph is single-device there, so the type + # alone still distinguishes buffers). + suffix = "" if _coor_enabled() else f"_{current_device.index}" + arg = WorkspaceArg( + count=min_size, + zero_mode=WorkspaceZeroMode.ZERO_PER_GRAPH, + dtype=torch.uint32, + inner_name="sem_ptr", + outer_name=f"semaphores_{current_device.type}{suffix}", + device=current_device, + ) + for existing_arg in self.workspace_args: + if existing_arg.inner_name == arg.inner_name: + if arg != existing_arg: + raise AssertionError((arg, existing_arg)) + self.workspace_args.append(arg) + return arg.inner_name + + def seed_offset(self, name: str, value: int) -> str: + if not isinstance(value, int): + raise AssertionError((type(value), value)) + # here we are lifting a constant integer into an arg to the kernel to try to get additional cache hits + value = sympy.Integer(value) + if value in self.sizevars: + return self.sizevars[value] + if name in self.sizevars.values(): + name = ( + f"{name}{sum(1 for v in self.sizevars.values() if v.startswith(name))}" + ) + self.sizevars[value] = name + return name + + def size(self, name: sympy.Symbol) -> str: + if not isinstance(name, sympy.Symbol): + raise AssertionError((type(name), name)) + if name.name == "seed": + self.sizevars[name] = "seed" # don't manage the name of seeds + return "seed" + return self._lookup("ks", self.sizevars, name) + + def call_names(self) -> Iterator[str]: + return chain( + self.input_buffers.keys(), self.output_buffers.keys(), self.sizevars.keys() + ) + + def arg_name(self, name: str) -> str | None: + """ + Returns inner name of a given outer name. + """ + inplaced = self.inplace_buffers.get(name, None) + if inplaced is not None and not isinstance(inplaced, RemovedArg): + return inplaced.inner_name + output_name = self.output_buffers.get(name, None) + if output_name is not None and not isinstance(output_name, RemovedArg): + return output_name + return self.input_buffers.get(name, None) + + def wrap_ptr_arg(self, buf: str, dtype: torch.dtype) -> str: + return buf + + def wrap_size_arg(self, size: SymbolLike) -> str: + return str(size) + + def cpp_argdefs( + self, dtype_to_cpp_type: dict[torch.dtype, str] | None = None + ) -> tuple[list[str], list[str], list[str]]: + from .cpp_utils import INDEX_TYPE + + if dtype_to_cpp_type is None: + from .cpp_utils import DTYPE_TO_CPP + + dtype_to_cpp_type = DTYPE_TO_CPP + + call_args = [] + arg_defs = [] + arg_types = [] + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + outer = inplaced.other_names[-1] + inner = inplaced.inner_name + dtype = V.graph.get_dtype(outer) + cpp_dtype = dtype_to_cpp_type[dtype] + arg_defs.append(f"{cpp_dtype}* {inner}") + call_args.append(self.wrap_ptr_arg(outer, dtype)) + arg_types.append(f"{cpp_dtype}*") + for outer, inner in self.input_buffers.items(): + if outer in self.inplace_buffers: + continue + dtype = V.graph.get_dtype(outer) + cpp_dtype = dtype_to_cpp_type[dtype] + arg_defs.append(f"const {cpp_dtype}* {inner}") + call_args.append(self.wrap_ptr_arg(outer, dtype)) + arg_types.append(f"const {cpp_dtype}*") + for outer, maybe_inner in self.output_buffers.items(): + if outer in self.inplace_buffers or isinstance(maybe_inner, RemovedArg): + continue + dtype = V.graph.get_dtype(outer) + cpp_dtype = dtype_to_cpp_type[dtype] + arg_defs.append(f"{cpp_dtype}* {maybe_inner}") + call_args.append(self.wrap_ptr_arg(outer, dtype)) + arg_types.append(f"{cpp_dtype}*") + for outer, inner in self.sizevars.items(): + if isinstance(outer, sympy.Symbol) and symbol_is_type( + outer, (SymT.UNBACKED_FLOAT) + ): + arg_defs.append(f"const float {inner}") + arg_types.append("const float") + else: + arg_defs.append(f"const {INDEX_TYPE} {inner}") + arg_types.append(f"const {INDEX_TYPE}") + call_args.append(self.wrap_size_arg(outer)) + if V.graph.wrapper_code: + V.graph.wrapper_code.ensure_size_computed(outer) + if self.workspace_args: + raise AssertionError("Workspace not supported on CPU ") + return arg_defs, call_args, arg_types + + def python_argdefs( + self, + ) -> tuple[list[ArgName], list[str], list[KernelArgType], list[Any]]: + arg_defs: list[ArgName] = [] + call_args: list[str] = [] + arg_types: list[Any] = [] + precompile_args: list[KernelArgType] = [] + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + arg_defs.append(ArgName(inplaced.inner_name)) + call_args.append(inplaced.other_names[-1]) + arg_types.append(V.graph.get_dtype(inplaced.other_names[-1])) + precompile_args.append( + TensorArg( + name=inplaced.inner_name, + buffer=inplaced.other_names[-1], + dtype=V.graph.get_dtype(inplaced.other_names[-1]), + ) + ) + for outer, inner in chain( + self.input_buffers.items(), + # pyrefly: ignore [bad-argument-type] + self.output_buffers.items(), + ): + if outer in self.inplace_buffers or isinstance(inner, RemovedArg): + continue + arg_defs.append(ArgName(inner)) + call_args.append(outer) + arg_types.append(V.graph.get_dtype(outer)) + precompile_args.append( + TensorArg( + name=inner, + buffer=outer, + dtype=V.graph.get_dtype(outer), + ) + ) + for outer, inner in self.sizevars.items(): + arg_defs.append(ArgName(inner)) + call_args.append(outer) + arg_types.append(type(outer)) + precompile_args.append(SizeArg(inner, outer)) + if V.graph.wrapper_code: + V.graph.wrapper_code.ensure_size_computed(outer) + for arg in self.workspace_args: + arg_defs.append(ArgName(arg.inner_name)) + call_args.append(arg.outer_name) + precompile_args.append(arg) + arg_types.append(arg.dtype) + return arg_defs, call_args, precompile_args, arg_types + + def aliases(self) -> Iterator[tuple[str, str]]: + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + for other in inplaced.other_names: + if ( + other in V.graph.inplaced_to_remove + or other in V.kernel.inplaced_to_remove + ): + continue + if other in self.input_buffers: + yield self.input_buffers[other], inplaced.inner_name + if other in self.output_buffers: + yield cast(str, self.output_buffers[other]), inplaced.inner_name + + def is_removed(self, name: str) -> bool: + return isinstance( + self.output_buffers.get(name, REMOVED), RemovedArg + ) and isinstance(self.inplace_buffers.get(name, REMOVED), RemovedArg) + + # Includes inplace buffers, excludes removed buffers. Essentially, + # after you do a call into this kernel, which buffers actually contain + # updated data? Modeled off of python_argdefs. + def live_output_buffers(self) -> OrderedSet[str]: + live_outs: OrderedSet[str] = OrderedSet() + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + live_outs.add(inplaced.other_names[-1]) + for outer, inner in self.output_buffers.items(): + if outer in self.inplace_buffers or isinstance(inner, RemovedArg): + continue + live_outs.add(outer) + return live_outs + + +class CSEVariable: + """A CSEVariable is just a name for an expression but it is useful to be able to annotate them on a backend dependent basis. + To do so, the backends can simply overload `Kernel.create_cse_var` + The "CSEVariable.update_on_args" method gives you a hook for annotations + See example of TritonCSEVariable in triton.py + """ + + def __init__( + self, + name: str, + bounds: ValueRanges[Any], + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ): + super().__init__() + if not isinstance(bounds, ValueRanges): + raise AssertionError(type(bounds)) + self.name = name + self.bounds = bounds + self.use_count = 1 # track how many times this expression is used + self.dtype = dtype + self.shape = shape + + def __str__(self) -> str: + return self.name + + def __hash__(self) -> int: + return hash(self.name) + + def __eq__(self, other: object) -> bool: + return isinstance(other, CSEVariable) and other.name == self.name + + def update_on_args(self, name: str, args: Any, kwargs: Any) -> None: + pass + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.name!r})" + + +AugmentedKeyT = TypeVar("AugmentedKeyT", default=str) +CSEVariableType = TypeVar("CSEVariableType", bound=CSEVariable, default=CSEVariable) + +if TYPE_CHECKING: + ReductionCacheKey = tuple[ + torch.dtype, + ReductionType, + CSEVariable | tuple[CSEVariable, ...], + ] + + +class CSE(Generic[CSEVariableType, AugmentedKeyT]): + """Common subexpression elimination""" + + def __init__( + self, + prefix: str = "", + suffix: str = "", + name_prefix: str = "tmp", + iter_buffers: itertools.count[int] | None = None, + store_cache: MutableMapping[str, CSEVariableType] | None = None, + reduction_cache: MutableMapping[ReductionCacheKey, CSEVariableType] + | None = None, + varname_map: dict[str, CSEVariableType] | None = None, + ): + self.prefix = prefix + self.suffix = suffix + self._cache: MutableMapping[AugmentedKeyT, CSEVariableType] = {} + self.name_prefix = name_prefix + self.store_cache: MutableMapping[str, CSEVariableType] = store_cache or {} + self.reduction_cache: MutableMapping[ReductionCacheKey, CSEVariableType] = ( + reduction_cache or {} + ) + self.iter_buffer_ids: itertools.count[int] = iter_buffers or itertools.count() + self.invalidated_stores: OrderedSet[str] = OrderedSet() + self.varname_map: dict[str, CSEVariableType] = varname_map or {} + + def invalidate(self, keep_vars: OrderedSet[CSEVariable]) -> None: + for name, tmp in [*self.store_cache.items()]: + if tmp not in keep_vars: + del self.store_cache[name] + self.invalidated_stores.add(name) + if keep_vars: + self._cache = {k: v for k, v in self._cache.items() if v in keep_vars} + else: + self._cache = {} + + def clone(self) -> Self: + return type(self)( + prefix=self.prefix, + suffix=self.suffix, + name_prefix=self.name_prefix, + iter_buffers=self.iter_buffer_ids, + store_cache=self.store_cache, + varname_map=self.varname_map, + reduction_cache=self.reduction_cache, + ) + + def scoped_copy(self) -> Self: + """Return a copy of using ScopedDict so changes to *_cache aren't visible in self""" + new_cse = self.clone() + new_cse._cache = ScopedDict(self._cache) + new_cse.reduction_cache = ScopedDict(self.reduction_cache) + new_cse.store_cache = ScopedDict(self.store_cache) + return new_cse + + def augment_key(self, cache_key: str) -> AugmentedKeyT: + "Override this method to augment cache key with backend specifics" + return cast(AugmentedKeyT, cache_key) + + def put(self, cache_key: str, val: CSEVariableType) -> None: + self._cache[self.augment_key(cache_key)] = val + + def contains(self, cache_key: str) -> bool: + return self.augment_key(cache_key) in self._cache + + def try_get(self, cache_key: str) -> CSEVariableType | None: + return self._cache.get(self.augment_key(cache_key), None) + + def get(self, cache_key: str) -> CSEVariableType: + return self._cache[self.augment_key(cache_key)] + + def generate( + self, + buffer: IndentedBuffer, + expr: str | CSEVariable | OpsValue | IndentedBuffer | DeferredLineBase, + *, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + write: bool = True, + assignment: bool = True, + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ) -> CSEVariableType: + if isinstance(expr, OpsValue): + expr = expr.value + + if not (write or assignment): + raise AssertionError("expected write or assignment to be set") + if isinstance(expr, CSEVariable): + # If the expressions were always created with all the information, we could + # assert expr.bounds == bounds, but sometimes the expression is created + # with the loose ValueRanges.unknown(), so we need to tighten the bounds + expr.bounds = expr.bounds.tighten(bounds) + expr.use_count += 1 + return cast(CSEVariableType, expr) + elif isinstance(expr, IndentedBuffer): + cache_key = expr.getvalue() + elif isinstance(expr, DeferredLineBase): + cache_key = expr.line + else: + if not isinstance(expr, str): + raise AssertionError(f"expected str, got {type(expr)}") + cache_key = expr + var = self.try_get(cache_key) + if shape is None and not assignment: + # since there's no assignment to a variable, use any shape here + # other than None to avoid the unknown shape failures + shape = () + if not var: + var = self.newvar(bounds, dtype, shape) + self.put(cache_key, var) + if write: + if V.kernel.current_node: + V.kernel.current_node.codegen_originating_info( + buffer, only_once=True + ) + if isinstance(expr, IndentedBuffer): + if assignment: + buffer.writeline(f"{self.prefix}{var} =") + buffer.splice(expr) + buffer.writeline(self.suffix) + elif isinstance(expr, DeferredLineBase): + if not assignment: + raise AssertionError("expected assignment to be set") + buffer.writeline( + expr._new_line(f"{self.prefix}{var} = {expr.line}{self.suffix}") + ) + else: + if assignment: + line = f"{self.prefix}{var} = {expr}{self.suffix}" + else: + line = f"{expr}{self.suffix}" + buffer.writeline(line) + + # cpp backend cannot determine is_vec at this point + if ( + assignment + and ( + config.test_configs.runtime_triton_dtype_assert + or config.test_configs.static_cpp_dtype_assert + ) + and dtype is not None + and get_current_backend() != "cpp" + ): + check_dtype(buffer, var, dtype) + + else: + var.bounds = var.bounds.tighten(bounds) + var.use_count += 1 + + return var + + def newvar( + self, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ) -> CSEVariableType: + var_name = f"{self.name_prefix}{next(self.iter_buffer_ids)}" + var = cast( + "CSEVariableType", V.kernel.create_cse_var(var_name, bounds, dtype, shape) + ) + self.varname_map[var_name] = var + return var + + def namedvar( + self, + name: str, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ) -> CSEVariableType: + torch._check_value( + name not in self.varname_map, lambda: f"duplicate name: {name}" + ) + var = cast( + "CSEVariableType", V.kernel.create_cse_var(name, bounds, dtype, shape) + ) + self.varname_map[name] = var + return var + + +class CodeGen: + def __init__(self) -> None: + super().__init__() + self.exit_stack = contextlib.ExitStack() + + def __enter__(self) -> Self: + self.exit_stack.__enter__() + return self + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.exit_stack.__exit__(exc_type, exc_val, exc_tb) + + +class Kernel(CodeGen, Generic[CSEVariableType]): + """Base class for generated kernels and their code buffers.""" + + newvar_prefix: str = "" + suffix: str = "" + overrides: Callable[[], OpsHandler[Any]] | None = None + + def __init__( + self, args: KernelArgs | None = None, increase_kernel_count: bool = True + ) -> None: + super().__init__() + if increase_kernel_count: + # pyrefly: ignore [bad-assignment] + metrics.generated_kernel_count += 1 + self.args = args or KernelArgs() + self.loads = IndentedBuffer() + self.compute = IndentedBuffer() + self.stores = IndentedBuffer() + + self.atomic_add_found = False + self.num_load = 0 + self.num_store = 0 + self.num_reduction = 0 + + self.cse: CSE[CSEVariableType, Any] = CSE(self.newvar_prefix, self.suffix) + self.must_keep_buffers: OrderedSet[str] = OrderedSet() + self.store_buffer_names: OrderedSet[str] = OrderedSet() + self._load_mask: str | None = None + self._load_other: None | int | float = None + # OrderedSet in set_current_node + self.current_node: SchedulerNode | None = None + self.node_to_bounds: dict[torch.fx.Node, ValueRanges[Any]] | None = None + + self.removed_buffers: OrderedSet[str] = OrderedSet() + self.inplaced_to_remove: OrderedSet[str] = OrderedSet() + + # key: the buffer to write + # value: the buffer to read and whose memory can be reused for + # the buffer specified by key + self.inplace_update_buffers: dict[str, str] = {} + # Set minimum number of elements processed per thread. + self.min_elem_per_thread = 1 + self.kernel_name: str | None = None + + @contextlib.contextmanager + def set_current_node(self, node: SchedulerNode) -> Iterator[None]: + prior = self.current_node + self.current_node = node + self.node_to_bounds = node._body.bounds().get_bounds() + try: + yield + finally: + self.current_node = prior + + @contextlib.contextmanager + def swap_buffers( + self, + lb: IndentedBuffer, + cb: IndentedBuffer | None = None, + sb: IndentedBuffer | None = None, + ) -> Iterator[None]: + if cb is None: + cb = lb + if disallow_stores := sb is None: + sb = IndentedBuffer() + loads = self.loads + compute = self.compute + stores = self.stores + cse = self.cse + self.loads = lb + self.compute = cb + self.stores = sb + self.cse = cse.scoped_copy() + try: + yield + finally: + self.loads = loads + self.compute = compute + self.stores = stores + self.cse = cse + # pyrefly: ignore [unbound-name] + if disallow_stores: + if sb: + raise AssertionError("unexpected store inside swap_buffers") + + def emit_kernel_override( + self, + wrapper, + src_code: str, + kernel_name: str, + node_schedule, + kernel_path: str, + get_kernel_metadata, + ) -> bool: + """Override kernel emission. Return True if overridden, False to use default. + + External template handlers (e.g. Helion) can override this method + to implement custom kernel emission to the wrapper. + """ + return False + + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + raise NotImplementedError + + def indirect_load(self, name: str, index: sympy.Expr) -> CSEVariable: + """A load that depends on an index we have read""" + prior = self.loads + try: + # put the load in the compute section as it might have deps + self.loads = self.compute + return self.load(name, index) + finally: + self.loads = prior + + def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None: + raise NotImplementedError + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + raise NotImplementedError + + def device_assert_async(self, cond: CSEVariable, msg: str) -> None: + raise NotImplementedError( + f"{type(self).__name__}: device_assert_async should be handled by CSEProxy" + ) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + raise NotImplementedError + + def partial_accumulate( + self, + name: str, + reduction_type: ReductionType, + value: CSEVariable, + extra_meta: dict[str, Any], + ) -> None: + raise NotImplementedError + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], tuple[CSEVariable, ...] + ], + values: tuple[CSEVariable, ...], + ) -> tuple[CSEVariable, ...]: + raise NotImplementedError + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[CSEVariable, ...], + stable: bool, + descending: bool, + ) -> tuple[CSEVariable, ...]: + raise NotImplementedError + + def var_ranges(self) -> dict[sympy.Symbol, sympy.Expr]: + raise NotImplementedError + + def bucketize( + self, + values: CSEVariable, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: CSEVariable, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: CSEVariable | None = None, + ) -> CSEVariable: + """ + See [Note: Inductor bucketize op] + """ + raise NotImplementedError + + @property + def assert_function(self) -> str: + raise NotImplementedError + + def indirect_assert( + self, + var: CSEVariable | str, + lower: str | None, + upper: str | None, + mask: CSEVariable | str | None = None, + ) -> str: + if isinstance(var, CSEVariable): + var = str(var) + if not isinstance(var, str): + raise AssertionError(type(var)) + if not (lower is None or isinstance(lower, str)): + raise AssertionError(f"expected lower to be None or str, got {type(lower)}") + if not (upper is None or isinstance(upper, str)): + raise AssertionError(f"expected upper to be None or str, got {type(upper)}") + if lower and upper: + # The conditions need to be in parens because of Python's operator precedence. + # It'd be less error-prone to use and/or/not, which is supported by triton + cond = f"({lower} <= {var}) & ({var} < {upper})" + cond_print = f"{lower} <= {var} < {upper}" + elif lower: + cond = f"{lower} <= {var}" + cond_print = cond + else: + if not upper: + raise AssertionError("expected upper to be set") + cond = f"{var} < {upper}" + cond_print = cond + + if mask: + cond = f"({cond}) | ~({mask})" + + return f'{self.assert_function}({cond}, "index out of bounds: {cond_print}")' + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + raise NotImplementedError + + def index_to_str(self, index: sympy.Expr) -> str: + raise NotImplementedError + + def __enter__(self) -> Self: + super().__enter__() + if not self.overrides: + raise AssertionError("expected overrides to be set") + self.exit_stack.enter_context( + V.set_ops_handler(CSEProxy(self, self.overrides())) + ) + self.exit_stack.enter_context(V.set_kernel_handler(self)) + return self + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.remove_kernel_local_buffers() + super().__exit__(exc_type, exc_val, exc_tb) + + def remove_kernel_local_buffers(self) -> None: + """ + Any buffers that are both created and have a last use in the + same kernel can be removed. + + Note that V.graph.scheduler can be None when codegening triton template + kernels. + """ + scheduler = V.graph.scheduler + if not scheduler: + return + fused_node_names = OrderedSet( + scheduler.name_to_buf[buf].defining_op_name() + for buf in self.store_buffer_names + if buf in scheduler.name_to_buf + ) + names_to_remove: OrderedSet[str] = OrderedSet() + for name in self.store_buffer_names: + if ( + name not in self.must_keep_buffers + and name not in self.args.input_buffers + and scheduler.can_buffer_be_removed_through_fusion( + name, fused_node_names + ) + ): + self.num_store -= 1 + names_to_remove.add(name) + + for name in names_to_remove: + if name in self.args.inplace_buffers: + buf = self.args.inplace_buffers[name] + if isinstance(buf, RemovedArg): + continue + remove = all(n in names_to_remove for n in buf.other_names) + if remove: + self.remove_inplace_buffer(name) + self.inplaced_to_remove.add(name) + else: + self.remove_buffer(name) + + def remove_buffer(self, name: str) -> None: + # Assign a special value instead of deleting the entry + # because we still rely on output_buffers's length to + # generate unique arg name. + log.debug("remove_buffer(%r)", name) + self.args.output_buffers[name] = REMOVED + self.removed_buffers.add(name) + + def remove_inplace_buffer(self, name: str) -> None: + log.debug("removing_inplace_buffer(%r)", name) + self.args.inplace_buffers[name] = REMOVED + self.removed_buffers.add(name) + + def rename_indexing( + self, index: list[sympy.Expr] | tuple[sympy.Expr, ...] | sympy.Expr + ) -> sympy.Expr: + # adds the necessary kernel args for index expressions + # and renames variables in index expressions to kernel arg names + if isinstance(index, (list, tuple)): + return [self.rename_indexing(x) for x in index] + index = V.graph.sizevars.simplify(index) + sorted_symbols = sorted(index.free_symbols, key=lambda s: s.name) + replacements = { + x: self.args.size(x) + for x in sorted_symbols + if symbol_is_type( + x, + ( + SymT.UNBACKED_INT, + SymT.SIZE, + SymT.PRECOMPUTED_SIZE, + SymT.UNBACKED_FLOAT, + ), + ) + } + return sympy_subs(index, replacements) + + def create_cse_var(self, *args: Any, **kwargs: Any) -> CSEVariable: + return CSEVariable(*args, **kwargs) + + def arg_name(self, node: IRNode) -> str | None: + """ + Returns arg name of a given input or output node. + """ + if node is None: + return None + return self.args.arg_name(node.get_name()) + + def record_op_trace( + self, + name: str, + args: tuple[Any, ...], + kwargs: dict[str, Any], + result: Any = None, + ) -> None: + pass + + +@dataclasses.dataclass +class OptimizationContext: + key: ClassVar[str] = "opt_ctx" + + dtype: torch.dtype | None = None + ops_name: str = "" + + +@functools.cache +def jinja2_env() -> Any: + try: + import jinja2 + + return jinja2.Environment( + undefined=jinja2.StrictUndefined, + ) + except ImportError: + return None + + +class KernelTemplate: + """ + Base class for defining kernel templates. + + Children classes: TritonTemplate, CUTLASSTemplate + """ + + @staticmethod + def indent_except_first( + source: str, num_indents: int, indents_spacing: int = 4 + ) -> str: + lines = source.splitlines(True) + if len(lines) > 1: + lines[1:] = [ + (" " * indents_spacing * num_indents) + line for line in lines[1:] + ] + return "".join(lines) + + @staticmethod + def _template_from_string(source: str) -> Any: + env = jinja2_env() + if env is None: + return None + env.filters["indent_except_first"] = KernelTemplate.indent_except_first + from jinja2 import TemplateSyntaxError + + try: + return env.from_string(source) + except TemplateSyntaxError as e: + + class DetailedTemplateSyntaxError(TemplateSyntaxError): + def __init__(self, original_error: TemplateSyntaxError) -> None: + super().__init__( + original_error.message, + original_error.lineno, + original_error.name, + original_error.filename, + ) + self.original_error = original_error + + def __str__(self) -> str: + error_info = f"Error in template at line {self.lineno}\n" + error_info += f"Error message: {self.message}\n" + if hasattr(self.original_error, "source"): + lines = self.original_error.source.split("\n") + error_info += "Context:\n" + start = max(0, self.lineno - 2) + end = min(len(lines), self.lineno + 2) + for i in range(start, end): + if i == self.lineno - 1: + error_info += f"{i + 1}: --> {lines[i]}\n" + if hasattr(self.original_error, "column"): + error_info += ( + " " + + " " * (self.original_error.column - 1) + + "^\n" + ) + else: + error_info += f"{i + 1}: {lines[i]}\n" + return error_info + + raise DetailedTemplateSyntaxError(e) from e + + @staticmethod + def _fake_get_dtype( + fake_outs: list[Buffer] | Buffer, + ) -> Callable[[str], torch.dtype]: + _get_dtype_real = V.graph.get_dtype + if isinstance(fake_outs, (list, tuple)): + lookup = {buf.get_name(): buf.get_dtype() for buf in fake_outs} + else: + lookup = {fake_outs.get_name(): fake_outs.get_dtype()} + + def get_dtype(name: str) -> torch.dtype: + result = lookup.get(name) + if result is not None: + return result + return _get_dtype_real(name) + + return get_dtype + + def __init__(self, name: str, hash: str | None = None) -> None: + self.name = name + self._hash = hash + + @property + def uid(self) -> str: + """ + entry point to override for templates to ensure a uid e.g. through a prefix + + the purpose of this is that every KernelTemplate/ExternKernelChoice is unique + in the system, but reproducible e.g. restarting pytorch should yield the same id + """ + # TODO(coconutruben): add some central registration to assert on global uniqueness + return self.name + + @property + def src_hash(self) -> str | None: + """ + source hash for a Template. + + Templates can optionally provide a src hash to make it easier to cache/validate that + a template has not changed from one version to another. Override this if that detection + is different for your specific Template + """ + return self._hash + + def choice_or_none(self, **kwargs: Any) -> ChoiceCaller | None: + """ + Maybe generates a new ChoiceCaller and returns it, or None if generation fails. + + kwargs: Additional kwargs to be passed to self.generate() to generate a new ChoiceCaller. + """ + temp_choices: list[Any] = [] + result = self.maybe_append_choice(temp_choices, **kwargs) + if result is None and len(temp_choices) == 1: + return temp_choices[0] + return None + + def maybe_append_choice( + self, choices: list[Any], **kwargs: Any + ) -> NotImplementedError | None: + """ + Maybe generates a new ChoiceCaller and appends it into existing choices. + Returns None if success, otherwise returns the error. + + choices: A list of ChoiceCallers. + kwargs: Additional kwargs to be passed to self.generate() to generate a new ChoiceCaller. + """ + + try: + choices.append(self.generate(**kwargs)) + return None + except NotImplementedError as e: + log.info( + "Cannot Append Choice: %s. KernelTemplate type is %s", + e, + type(self), + stack_info=log.getEffectiveLevel() < logging.INFO, + ) + return e + + def generate(self, **kwargs: Any) -> ChoiceCaller: + """ + Generates a ChoiceCaller instance from the given arguments. + """ + + raise NotImplementedError + + +class CSEProxy(DefaultHandler): + """A ops handler that proxies calls to `kernel` and its + handler and returns `CSEVariable`s with correct shape and dtype. + """ + + name = "CSEProxy" + + def __init__(self, kernel: Kernel[Any], parent_handler: OpsHandler[Any]): + super().__init__() + from ..bounds import ValueRangeAnalysis + + self.vr_analysis = ValueRangeAnalysis() + self.kernel = kernel + self.parent_handler = parent_handler + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + bounds = self._bound_variable(name, *args, **kwargs) + + value = getattr(self.parent_handler, name)(*args, **kwargs) + dtype_handler = DtypePropagationOpsHandler() + shape_handler = ShapePropagationOpsHandler() + + backend = get_current_backend() + + shape_op = getattr(shape_handler, name) + output_dtype = None + output_shape = None + + if name == "masked" and backend == "triton": + output_dtype = value.dtype + output_shape = value.shape + elif name == "masked" and backend == "cpp": + output_dtype = V.interpreter.current_node.meta.get( + OptimizationContext.key, None + ).dtype + # TODO: fix me + output_shape = None + elif backend in ("triton", "cpp", "mps"): + dtype_op = getattr(dtype_handler, name) + output_dtype = dtype_op(*args, **kwargs) + output_shape = shape_op(*args, **kwargs) + + if backend in ("triton", "cpp"): + # maybe there are some exceptions on mps? + if output_dtype is None: + raise AssertionError("expected output_dtype to be not None") + + output_idx = 0 + + def do_cse(v: str | CSEVariable) -> CSEVariable: + # we tree_map over the output, so we need to fetch corresponding dtype + nonlocal output_idx + var_dtype: torch.dtype | None = ( + output_dtype[output_idx] + if isinstance(output_dtype, (list, tuple)) + else output_dtype + ) + var_shape: BlockShapeType = ( + output_shape[output_idx] # type: ignore[assignment] + if isinstance(output_shape, (list, tuple)) + and len(output_shape) > 0 + and isinstance(output_shape[0], (list, tuple)) + else output_shape + ) + output_idx += 1 + + # some cpp op implementations don't set the dtype + if isinstance(v, CSEVariable): + if backend == "cpp" and v.dtype is None: + v.dtype = var_dtype + if v.shape is None: + v.shape = var_shape + + csevar = V.kernel.cse.generate( + V.kernel.compute, + v, + bounds=bounds, + # pyrefly: ignore[bad-argument-type] + dtype=output_dtype, + shape=output_shape, + ) + + csevar.update_on_args(name, args, kwargs) + + if ( + config.test_configs.runtime_triton_dtype_assert + or config.test_configs.static_cpp_dtype_assert + ) and var_dtype is not None: + check_dtype(V.kernel.compute, csevar, var_dtype) + + if ( + config.test_configs.runtime_triton_shape_assert + and _is_runtime_triton_assert_target() + ): + shape_to_check = csevar.shape if csevar.shape is not None else var_shape + if shape_to_check is not None: + check_shape(V.kernel.compute, csevar, shape_to_check) + + if config.runtime_triton_nan_asserts: + check_nan(V.kernel.compute, csevar) + + return csevar + + result = pytree.tree_map(do_cse, value) + self.kernel.record_op_trace(name, args, kwargs, result) + return result + + def _bound_variable(self, name: str, *args: Any, **kwargs: Any) -> ValueRanges[Any]: + """ + If the variable comes from an FX node, we forward the bound we have already computed + Else, if the variable when codegen'ing another op, we try to compute its bounds + """ + from ..bounds import ValueRangeAnalysis + from ..select_algorithm import TritonTemplateKernel + from .cutlass.kernel import CUTLASSTemplateKernel + + if isinstance(V.kernel, TritonTemplateKernel): + return ValueRanges.unknown() + + if isinstance(V.kernel, CUTLASSTemplateKernel): + return ValueRanges.unknown() + + if isinstance(V.interpreter, NullHandler): + return ValueRanges.unknown() + + fx_node = V.interpreter.current_node + if fx_node.target == name and self.kernel.node_to_bounds is not None: + if not isinstance(self.kernel.node_to_bounds, dict): + raise AssertionError(type(self.kernel.node_to_bounds)) + return self.kernel.node_to_bounds.get(fx_node, ValueRanges.unknown()) + elif config.compute_all_bounds and hasattr(ValueRangeAnalysis, name): + # These create lots of inner strings. We would need to compute the bounds at the ops + # We will also likely not get much from computing VRs on these nodes + if any(s in fx_node.target for s in ("set_indirect", "reduction", "scan")): + return ValueRanges.unknown() + + # We assume that the inputs come from `ops.` and are not strings. If you want to generate + # intermediary strings, wrap them in CSE variables with properly initialised bounds. + + # If there is no FX bound but we know how to compute one we do so + if kwargs: + raise AssertionError("expected no kwargs") + + def arg_to_bound(x: Any) -> Any: + if isinstance(x, CSEVariable): + return x.bounds + elif isinstance(x, sympy.Expr): + return bound_sympy(x) + else: + return x + + arg_bounds = list(map(arg_to_bound, args)) + return getattr(self.vr_analysis, name)(*arg_bounds) + return ValueRanges.unknown() + + def indirect_indexing( + self, + var: CSEVariable, + size: sympy.Expr | int, + check: bool = True, + wrap_neg: bool = True, + ) -> sympy.Symbol: + if isinstance(size, int): + size = sympy.Integer(size) + if not isinstance(size, sympy.Expr): + raise AssertionError((type(size), size)) + # Skip CSE since this doesn't return an expression + + if var.bounds.lower < 0: + if wrap_neg: + stm = ops.add(var, ops.index_expr(size, torch.long)) + # Mixed negative and non-negative + if var.bounds.upper >= 0: + lt = ops.lt(var, 0) + stm = ops.where(lt, stm, var) + else: + stm = var + + # Propagate bounds as we know how to compute them properly. + # When wrap_neg=False, negative indices stay negative and must keep + # their original bounds so lower-bound checks are not elided. + new_bounds = var.bounds if not wrap_neg else ValueRanges.unknown() + if ( + wrap_neg + and var.bounds != ValueRanges.unknown() + and isinstance(size, sympy.Number) + ): + # Take the negative part of the bound and add size to it + # Then take union of that and the positive part + # This is a tighter bound than that of a generic ops.where, as we have info on the cond + neg_bounds = var.bounds & ValueRanges(-int_oo, -1) + new_bounds = ValueRanges( + neg_bounds.lower + size, neg_bounds.upper + size + ) + # We don't have a good way of representing the empty range + if var.bounds.upper >= 0: + pos = var.bounds & ValueRanges(0, int_oo) + new_bounds = new_bounds | pos + + var = self.kernel.cse.generate( + self.kernel.compute, + stm, + bounds=new_bounds, + dtype=var.dtype, + shape=var.shape, + ) + + sympy_var = self.parent_handler.indirect_indexing(var, size, check) + if generate_assert(check): + assert_lower = not (var.bounds.lower >= 0) + # value ranges cannot x < s when x and s are symbols + assert_upper = not isinstance(size, sympy.Number) or not ( + var.bounds.upper < size + ) + self.kernel.check_bounds(sympy_var, size, assert_lower, assert_upper) + return sympy_var + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + return self.kernel.check_bounds(expr, size, lower, upper) + + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + if name in self.kernel.cse.invalidated_stores: + # A load from an invalidated store requires us to + # keep the actual buffer around + V.kernel.must_keep_buffers.add(name) + if free_symbol_is_type(index, SymT.TMP): + return self.kernel.indirect_load(name, index) + store_cache = self.kernel.cse.store_cache + if name in store_cache: + return store_cache[name] + out = self.kernel.load(name, index) + # count load that is not in the store_cache, and also not in the + # cse cache. + if out.use_count == 1: + self.kernel.num_load += 1 + self.kernel.record_op_trace("load", (name, index), {}, out) + return out + + def _update_store_cache(self, name: str, value: CSEVariable) -> None: + self.kernel.cse.store_cache[name] = value + if self.kernel.current_node and name in V.graph.name_to_buffer: + buf = self.kernel.current_node.get_output(name) + for other_name in buf.get_mutations(): + self.kernel.cse.store_cache[other_name] = value + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + self.kernel.store_buffer_names.add(name) + # Update store cache when mode is None or "tma" + if mode != "atomic_add": + self._update_store_cache(name, value) + if name not in V.graph.removed_buffers: + self.kernel.store(name, index, value, mode=mode) + self.kernel.num_store += 1 + self.kernel.record_op_trace("store", (name, index, value, mode), {}) + + def device_assert_async(self, cond: CSEVariable, msg: str) -> None: + self.kernel.device_assert_async(cond, msg) + self.kernel.record_op_trace("device_assert_async", (cond, msg), {}) + + # pyrefly: ignore [bad-override] + def partial_accumulate(self, *args: Any) -> None: + self.kernel.partial_accumulate(*args) + + def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None: + self.kernel.store_buffer_names.add(name) + self._update_store_cache(name, value) + + if name not in V.graph.removed_buffers: + self.kernel.num_store += 1 + return self.kernel.store_reduction(name, index, value) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + self.kernel.num_reduction += 1 + return self.kernel.reduction(dtype, src_dtype, reduction_type, value) + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], + tuple[CSEVariable, ...], + ], + values: tuple[CSEVariable, ...], + ) -> tuple[CSEVariable, ...]: + return self.kernel.scan(dtypes, combine_fn, values) + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[CSEVariable, ...], + stable: bool, + descending: bool, + ) -> tuple[CSEVariable, ...]: + return self.kernel.sort(dtypes, values, stable, descending) + + def bucketize( + self, + values: CSEVariable, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: CSEVariable, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: CSEVariable | None = None, + ) -> CSEVariable: + """ + [Note: Inductor bucketize op] + + Inputs: + ------- + values: the values to be bucketized. + boundaries: a tuple containing + (a) the name of the boundaries tensor (which must be sorted, unless + the sorting tensor is present), + (b) the length of the tensor in the last dimension (i.e. the length of + one set of boundaries), + (c) the number of elements in the underlying storage (i.e. the length + of the flattened tensor, ignoring striding), and + (d) the stride of the tensor in the last dimension. + boundary_indices: indices into a flattened version of the boundaries + tensor, of the same size and shape as "values". Each index points to + the first element in the set of boundaries to be used for the + corresponding value. + indexing_dtype: the dtype to use when indexing into the boundaries + tensor. This must be int64 or int32. This additionally specifies the + dtype of the return value. + right: see "Details" below. + sorter: an optional tuple containing + (a) the name of an optional sorting tensor, used to access unsorted + boundaries without reordering the boundaries tensor, and + (b) the stride of the tensor in the last dimension. + The values in the sorting tensor are used as indices into the *last* + dimension of the boundaries tensor, with all other indices matching. + The size of the sorting and boundaries tensors must be equivalent. + sorter_indices: must be present if the sorting array is present; see + "boundary_indices" for the equivalent definition for the boundaries + tensor. + + Output: + ------- + The buckets each value belongs in, within a given set of boundaries. 0 + indicates a position before the first boundary, and len(boundaries_set) + represents a position after the last boundary. + + Details: + -------- + Given a value and a set of boundaries, calculate the bucket that each + value belongs to. This works differently in 1-D and N-D cases. + + for values [[-1, 0, 1, 2], [3, 4, 5, 9]], boundaries [0, 4, 4, 8], right=True + return = [[ 0, 1, 1, 1], [1, 3, 3, 4]]. + + for values [[-1, 0, 1, 2], [3, 4, 5, 9]], boundaries [[0, 4], [4, 8]], right=True + return = [[ 0, 1, 1, 1], [0, 1, 1, 2]] + + Note that in the N-D boundaries case, the shape of "values" and + "boundaries" must match in every dimension _except_ the last. + + When right == False, bucket i refers to range (boundaries[i], boundaries[i+1]]. + When right == True, bucket i refers to range [boundaries[i], boundaries[i+1]). + + Boundaries must be non-decreasing, or a sorter must be provided which + would re-index offsets in a non-decreasing order (e.g. the second output + of torch.sort(offsets)). Otherwise, the result is undefined. + """ + return self.kernel.bucketize( + values, + boundaries, + boundary_indices, + indexing_dtype, + right, + sorter, + sorter_indices, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp.py new file mode 100644 index 0000000000000000000000000000000000000000..76ab9cadc22086daa43dffa51ff06724eb1d386f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp.py @@ -0,0 +1,6482 @@ +# mypy: allow-untyped-defs +import contextlib +import dataclasses +import functools +import itertools +import math +import operator +import os +import re +import sys +import warnings +from collections.abc import Callable, Sequence +from enum import Enum +from typing import Any, cast, ClassVar, Literal, Optional + +import sympy + +import torch +import torch.fx +from torch._inductor import dependencies +from torch._prims_common import is_float_dtype, is_integer_dtype +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import CeilDiv, FloorDiv, ModularIndexing +from torch.utils._sympy.symbol import free_symbol_is_type, symbol_is_type, SymT + +from ..._dynamo.utils import counters +from .. import config, cpp_builder, cpu_vec_isa, ir, metrics +from ..debug import set_kernel_post_grad_provenance_tracing +from ..loop_body import LoopBody +from ..scheduler import ( + BaseSchedulerNode, + BaseScheduling, + ExternKernelSchedulerNode, + ForeachKernelSchedulerNode, + FusedSchedulerNode, + Scheduler, + SchedulerNode, +) +from ..sizevars import stride_at_vec_range +from ..utils import ( + cache_on_self, + get_bounds_index_expr, + get_fused_kernel_name, + has_free_symbols, + is_multi_outputs_template, + is_welford_reduction, + parallel_num_threads, + Placeholder, + sympy_index_symbol, + sympy_index_symbol_with_prefix, + sympy_product, + sympy_subs, +) +from ..virtualized import NullKernelHandler, ops, OpsValue, V +from .common import ( + BackendFeature, + BracesBuffer, + CSE, + CSEVariable, + DataTypePropagation, + DeferredLine, + DTYPE_TO_COMPUTATION_DTYPE, + IndentedBuffer, + Kernel, + KernelArgs, + OpOverrides, + OptimizationContext, +) +from .cpp_utils import ( + _get_dtype_from_loopbodies, + _get_loop_body, + cexpr, + cexpr_index, + codegen_rand, + CppCSEVariable, + DTYPE_TO_CPP, + get_promote_dtype, + INDEX_TYPE, + LocalBufferContext, + may_unify_binary_op_mask_type, + promote_args, + template_fusion_with_epilogues_supported, + unify_mask_base_type, + value_to_cpp, +) + + +_IS_WINDOWS = sys.platform == "win32" + + +@functools.cache +def get_export_declaration(): + return "__declspec(dllexport)" if _IS_WINDOWS else "" + + +schedule_log = torch._logging.getArtifactLogger(__name__, "schedule") + +NATIVE_OMP_RTYPES = OrderedSet(["+", "*", "^", "||", "min", "max"]) +RTYPE_TO_CPP = { + "sum": "+", + "prod": "*", + "xor_sum": "^", + "min": "min", + "max": "max", + "argmin": "argmin", + "argmax": "argmax", + "any": "||", + "welford_reduce": "welford", + "welford_combine": "welford", +} +VECTORIZABLE_RTYPES = OrderedSet( + [ + "max", + "min", + "sum", + "prod", + "xor_sum", + "welford_reduce", + "welford_combine", + "argmin", + "argmax", + "any", + ] +) + +PYTHON_TO_CPP = { + "Tensor": "at::Tensor", + "int": "long", + "float": "double", + "bool": "bool", + "str": "std::string", + "ScalarType": "c10::ScalarType", + "MemoryFormat": "at::MemoryFormat", + "Layout": "at::Layout", + "Device": "at::Device", + "number": "at::Scalar", +} + +CONTAINER_PYTHON_TO_CPP = { + "List": "std::vector", + "Optional": "std::optional", +} + +DTYPE_LOWP_FP = [ + torch.bfloat16, + torch.float16, +] + +VECTORIZABLE_DTYPES: list[torch.dtype] = [ + torch.float64, + torch.float, + torch.bfloat16, + torch.float16, + torch.bool, + torch.uint8, + torch.int8, + torch.int32, + torch.int64, + torch.float8_e4m3fn, + torch.float8_e5m2, +] + + +def reduction_init(reduction_type, dtype): + if dtype in DTYPE_LOWP_FP: + # Since load promotes all half-precision inputs to float, the initial + # constant for reduction must be promoted as well + dtype = torch.float32 + if reduction_type in ("xor_sum", "sum", "any"): + return 0 + if reduction_type == "prod": + return 1 + if reduction_type in ("max", "argmax", "min", "argmin"): + cdtype = DTYPE_TO_CPP[dtype] + if dtype == torch.bool and reduction_type in ("argmin", "argmax"): + cdtype = DTYPE_TO_CPP[torch.float] + min_var = ( + f"-std::numeric_limits<{cdtype}>::infinity()" + if is_float_dtype(dtype) + else f"std::numeric_limits<{cdtype}>::min()" + ) + max_var = ( + f"std::numeric_limits<{cdtype}>::infinity()" + if is_float_dtype(dtype) + else f"std::numeric_limits<{cdtype}>::max()" + ) + init_var = min_var if reduction_type in ("max", "argmax") else max_var + return ( + init_var + if reduction_type in ("max", "min") + else f"IndexValue<{cdtype}>{{0, {init_var}}}" + ) + if is_welford_reduction(reduction_type): + return f"Welford<{DTYPE_TO_CPP[dtype]}>()" + raise AssertionError(reduction_type) + + +def reduction_acc_type(reduction_type, dtype): + scalar_type = DTYPE_TO_CPP[DTYPE_TO_COMPUTATION_DTYPE[dtype]] + if is_welford_reduction(reduction_type): + return f"Welford<{scalar_type}>" + if reduction_type in ("argmin", "argmax"): + if dtype == torch.bool: + scalar_type = DTYPE_TO_CPP[torch.float] + return f"IndexValue<{scalar_type}>" + return scalar_type + + +def reduction_combine( + reduction_type, + var, + next_value, + helper_val=None, + index: sympy.Expr | CSEVariable | None = None, + src_dtype=None, +): + is_bool = src_dtype == torch.bool + if reduction_type == "sum": + if helper_val: + return f"cascade_sum_combine({next_value}, &{helper_val})" + else: + conjunction = "|" if is_bool else "+" + return f"{var} {conjunction} {next_value}" + if reduction_type == "prod": + return f"{var} * {next_value}" + if reduction_type == "xor_sum": + return f"{var} ^ {next_value}" + if reduction_type == "any": + return f"{var} || {next_value}" + if reduction_type in ("min", "max"): + return f"{reduction_type}_propagate_nan({var}, {next_value})" + if reduction_type == "welford_reduce": + if helper_val: + return f"welford_combine({var}, {next_value}, &{helper_val})" + else: + return f"welford_combine({var}, {next_value})" + if reduction_type == "welford_combine": + if isinstance(next_value, tuple): + mean, m2, weight = next_value + else: + mean, m2, weight = reduction_project(reduction_type, next_value) + return f"welford_combine({var}, {{{mean}, {m2}, {weight}}})" + if reduction_type in ("argmin", "argmax"): + if ( + hasattr(next_value, "dtype") + and next_value.dtype == torch.bool + and not next_value.is_vec + ): + if index is not None: + return f"{reduction_type}_combine({var}, static_cast({next_value}), {index})" + else: + return ( + f"{reduction_type}_combine({var}, static_cast({next_value}))" + ) + if index is not None: + return f"{reduction_type}_combine({var}, {next_value}, {index})" + else: + return f"{reduction_type}_combine({var}, {next_value})" + raise AssertionError(reduction_type) + + +def reduction_project(reduction_type, acc): + if is_welford_reduction(reduction_type): + return f"{acc}.mean", f"{acc}.m2", f"{acc}.weight" + elif reduction_type in ("argmin", "argmax"): + return f"{acc}.index" + return acc + + +def move_code_under_inner_loop( + code: IndentedBuffer, + iter_var: sympy.Expr, + new_iter_var: str, + loop_start: sympy.Expr, + loop_end: sympy.Expr, +) -> BracesBuffer: + r""" + f(iter_var) is transformed to f(new_iter_var) under the inner loop + \/ + for (new_iter_var = loop_start; new_iter_var < loop_end; new_iter_var++) { + f(new_iter_var) + } + Please be careful while using this function, + as the variable defined in f(iter_var) will be invalid outside the for loop. + For example: + auto tmp0 = in_ptr[x0]; -> + for (new_x0 = start; new_x0 < end; new_x0++){ + auto tmp0 = in_ptr[new_x0]; + } + The tmp0 is invalid outside the loop. + """ + transformed_code = BracesBuffer() + with contextlib.ExitStack() as stack: + transformed_code.writeline( + f"for ({INDEX_TYPE} {new_iter_var} = {cexpr_index(loop_start)};" + + f"{new_iter_var} < {cexpr_index(loop_end)}; {new_iter_var}++)" + ) + stack.enter_context(transformed_code.indent()) + for _, line in enumerate(code._lines): + if not ( + isinstance( + line, + ( + str, + DeferredLine, + ), + ) + ): + raise AssertionError( + "expected isinstance( line, ( str, DeferredLine, ), )" + ) + deferred_name = None + if isinstance(line, DeferredLine): + deferred_name = line.name + line = line.line + new_line = re.sub(r"\b" + f"{iter_var}" + r"\b", f"{new_iter_var}", line) + if deferred_name: + new_line = DeferredLine(deferred_name, new_line) # type: ignore[assignment] + transformed_code.writeline(new_line) + return transformed_code + + +def reduction_prefix_array( + acc_var: str | CSEVariable, + acc_type: str, + reduction_type: str, + dtype: torch.dtype, + len: str | int, + init_fn, +): + """ + MSVC don't support dynamic array(VLA). So we use std::unique_ptr here. + Ref: https://stackoverflow.com/questions/56555406/creating-dynamic-sized-array-using-msvc-c-compiler + MSVC is the only one compiler without VLA. support. Since MSVC can't get good performance here. + We just use unique_ptr make it works on MSVC. + For other compilers, we continue to use VLA to get best performance. + """ + code_buffer = IndentedBuffer() + acc_decl = ( + f"auto {acc_var}_arr = std::make_unique<{acc_type}[]>({len});" + if cpp_builder.is_msvc_cl() + else f"{acc_type} {acc_var}_arr[{len}];" + ) + code_buffer.writeline(f"{acc_decl}") + code_buffer.writelines( + [ + f"for (int i = 0; i < {len}; i++)", + "{", + f" {acc_var}_arr[i] = {init_fn(reduction_type, dtype)};", + "}", + ], + ) + return code_buffer + + +def replace_acc_name(buffer: IndentedBuffer, name: str, new_name: str): + for i, line in enumerate(buffer._lines): + if not ( + isinstance( + line, + ( + str, + DeferredLine, + ), + ) + ): + raise AssertionError("expected isinstance( line, ( str, DeferredLine, ), )") + if isinstance(line, DeferredLine): + line.line = re.sub(r"\b" + f"{name}" + r"\b", f"{new_name}", line.line) + else: + buffer._lines[i] = re.sub(r"\b" + f"{name}" + r"\b", f"{new_name}", line) + + +def replace_cascade_sum_with_add(buffer: IndentedBuffer): + """ + Replaces `acc = cascade_sum_combine(value, ...)` with `acc = acc + value;` + """ + + pattern = r"(.*?)\s*=\s*cascade_sum_combine\(([^,]+),.*?\);" + for i, line in enumerate(buffer._lines): + if not ( + isinstance( + line, + ( + str, + DeferredLine, + ), + ) + ): + raise AssertionError("expected isinstance( line, ( str, DeferredLine, ), )") + content = line.line if isinstance(line, DeferredLine) else line + match = re.search(pattern, content) + if match: + acc, value = match.groups() + new_content = re.sub(pattern, f"{acc} = {acc} + {value};", content) + if isinstance(line, DeferredLine): + line.line = new_content + else: + buffer._lines[i] = new_content + + +@dataclasses.dataclass +class ParallelDepth: + """ + A class representing parallel depth. + Includes the starting depth of parallelism and the depth of parallelism. + """ + + parallel_depth: int + start_depth: int + + +class OuterLoopFusedSchedulerNode(FusedSchedulerNode): + @classmethod + def fuse( # type: ignore[override] + cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode, outer_loop_fusion_depth + ): + if node1.scheduler is not node2.scheduler: + raise AssertionError("expected node1.scheduler is node2.scheduler") + if not ( + all( + type(node) + in ( + OuterLoopFusedSchedulerNode, + SchedulerNode, + FusedSchedulerNode, + ) + for node in (node1, node2) + ) + ): + raise AssertionError( + "expected all nodes to be OuterLoopFusedSchedulerNode, " + "SchedulerNode, or FusedSchedulerNode" + ) + if any(type(node) is OuterLoopFusedSchedulerNode for node in (node1, node2)): + return cls( + node1.scheduler, + # pyrefly: ignore [bad-argument-type] + ( + list(node1.get_outer_nodes()) + if type(node1) is OuterLoopFusedSchedulerNode + else [ + node1, + ] + ) + + ( + list(node2.get_outer_nodes()) + if type(node2) is OuterLoopFusedSchedulerNode + else [ + node2, + ] + ), + outer_loop_fusion_depth, + ) + else: + return cls(node1.scheduler, [node1, node2], outer_loop_fusion_depth) # type: ignore[list-item] + + def __init__( + self, + scheduler: "Scheduler", + outer_fused_nodes: list[FusedSchedulerNode | SchedulerNode], + outer_loop_fusion_depth, + ): + self.outer_fused_nodes: list[FusedSchedulerNode | SchedulerNode] = ( + outer_fused_nodes + ) + self.outer_loop_fusion_depth = outer_loop_fusion_depth + flatten_snodes = [] + for _node in self.outer_fused_nodes: + if not isinstance(_node, (SchedulerNode, FusedSchedulerNode)): + raise AssertionError( + "expected isinstance(_node, (SchedulerNode, FusedSchedulerNode))" + ) + flatten_snodes.extend(list(_node.get_nodes())) + super().__init__(scheduler, flatten_snodes) # type: ignore[arg-type] + + def get_outer_nodes(self): + return self.outer_fused_nodes + + def check_outer_fusion_loop_level_attr( + self, cpp_kernel_proxy_list, outer_loop_fusion_depth + ): + # This function ensures that the same tiling split is applied at each loop level within the outer loop fusion depth. + # In the fusion stage, we only examine nodes with same vars and reduce. + # However, for nodes with same vars and reduce, the loops may still have different tile splits. + # For example (test_expr_vec_non_contiguous in test_cpu_repro.py): + # * buf0 tiling along the 2nd loop level, buf1 tiling along the 3rd loop level. + # If the check failed, we should fall back to standard loop codegen. + def _inner( + left_loop_nest: LoopNest, + right_loop_nest: LoopNest, + loop_fusion_depth: int, + current_checking_depth: int, + ) -> bool: + if not left_loop_nest.loops: + raise AssertionError("expected left_loop_nest.loops") + if not right_loop_nest.loops: + raise AssertionError("expected right_loop_nest.loops") + left_loop_level = left_loop_nest.loops[current_checking_depth] + right_loop_level = right_loop_nest.loops[current_checking_depth] + # Check if same loop level attr + outer_loops_attr_compare_list = [ + "var", + "size", + "offset", + "steps", + ] + if not ( + all( + getattr(left_loop_level, attr_compare) + == getattr(right_loop_level, attr_compare) + for attr_compare in outer_loops_attr_compare_list + ) + ): + return False + + if loop_fusion_depth < 1: + raise AssertionError("expected loop_fusion_depth >= 1") + if (loop_fusion_depth := loop_fusion_depth - 1) > 0: + # Check next loop level attr + current_checking_depth = current_checking_depth + 1 + if current_checking_depth >= len(left_loop_nest.loops): + raise AssertionError( + "expected current_checking_depth < len(left_loop_nest.loops)" + ) + if current_checking_depth >= len(right_loop_nest.loops): + raise AssertionError( + "expected current_checking_depth < len(right_loop_nest.loops)" + ) + if not _inner( + left_loop_nest, + right_loop_nest, + loop_fusion_depth, + current_checking_depth, + ): + return False + + return True + + for idx in range(len(cpp_kernel_proxy_list) - 1): + left_loop_nest = cpp_kernel_proxy_list[idx].loop_nest + right_loop_nest = cpp_kernel_proxy_list[idx + 1].loop_nest + if not _inner( + left_loop_nest, + right_loop_nest, + outer_loop_fusion_depth, + 0, + ): + return False + + for cpp_kernel_proxy in cpp_kernel_proxy_list: + outer_ranges = functools.reduce( + operator.mul, + cpp_kernel_proxy.ranges[:outer_loop_fusion_depth], + ) + # When the range of the first inner loop is much larger than the range of + # all outer loops, do not fuse outer loop and fallback to standard loop codegen, + # so that the inner loops with larger range have a chance to be parallelized. + # We set a conservative threshold here: + # First inner loop range / all outer loops range > 300. + if ( + len(cpp_kernel_proxy.ranges) > outer_loop_fusion_depth + and isinstance(outer_ranges, sympy.Integer) + and isinstance( + cpp_kernel_proxy.ranges[outer_loop_fusion_depth], + sympy.Integer, + ) + and outer_ranges * 300 + < cpp_kernel_proxy.ranges[outer_loop_fusion_depth] + ): + return False + + return True + + def merge_outer_fusion_kernels( + self, + cpp_kernel_proxy_list, + ): + kernel_group = cpp_kernel_proxy_list[0].kernel_group + outer_loop_fused_kernel = OuterLoopFusedKernel(kernel_group) + outer_loop_fused_kernel.inner = [ + proxy.loop_nest.from_loop_level(self.outer_loop_fusion_depth) + for proxy in cpp_kernel_proxy_list + ] + outer_fused_proxy = cpp_kernel_proxy_list[0] + outer_fused_proxy.loop_nest.kernel = outer_loop_fused_kernel + outer_fused_proxy.loop_nest.loops = outer_fused_proxy.loop_nest.loops[ + : self.outer_loop_fusion_depth + ] + return outer_fused_proxy + + +class RecordOptimizationContext: + def __init__(self, func_name: str = ""): + self.func_name = func_name + self.current_node: torch.fx.Node | None = None + self.opt_ctx: OptimizationContext | None = None + + def __enter__(self): + if not V.interpreter: + raise AssertionError("expected V.interpreter") + if not V.interpreter.current_node: + raise AssertionError("expected V.interpreter.current_node") + + self.current_node = V.interpreter.current_node + if self.current_node is None: + raise AssertionError("expected self.current_node is not None") + if OptimizationContext.key in self.current_node.meta: + self.opt_ctx = self.current_node.meta[OptimizationContext.key] + else: + self.opt_ctx = OptimizationContext() + if self.opt_ctx is None: + raise AssertionError("expected self.opt_ctx is not None") + self.opt_ctx.ops_name = self.func_name + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if not self.current_node: + raise AssertionError("expected self.current_node") + if not self.opt_ctx: + raise AssertionError("expected self.opt_ctx") + self.current_node.meta[OptimizationContext.key] = self.opt_ctx + + def get_opt_ctx(self): + return self.opt_ctx + + def get_fx_node(self): + if not self.current_node: + raise AssertionError("expected self.current_node") + return self.current_node + + +def arith_promoted(op, a, b): + args = (a, b) + if any(isinstance(arg, CppCSEVariable) and arg.is_vec for arg in args): + raise AssertionError("Promotion of vector types is not supported") + + dtype = get_promote_dtype(args) + cpp_type = DTYPE_TO_CPP[dtype] if dtype is not None else f"decltype({a})" + if dtype in (torch.int32, torch.int64): + # signed overflow is UB in C++; int8/int16 promote to int and cannot overflow + cast = f"static_cast>" + return f"{cpp_type}({cast}({a}) {op} {cast}({b}))" + return f"{cpp_type}({a} {op} {b})" + + +class CppOverrides(OpOverrides): + """Map element-wise ops to C++""" + + @staticmethod + def add(a, b): + return arith_promoted("+", a, b) + + @staticmethod + def sub(a, b): + return arith_promoted("-", a, b) + + @staticmethod + def mul(a, b): + return arith_promoted("*", a, b) + + @staticmethod + def to_dtype(x, dtype, src_dtype=None, use_compute_types=True): + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if src_dtype is None: + src_dtype = x.dtype + expr = V.kernel.get_to_dtype_expr(x, dtype, src_dtype) + csevar = V.kernel.cse.generate(V.kernel.compute, expr) + csevar.update_on_args("to_dtype", (x, dtype), {"src_dtype": src_dtype}) + if ( + use_compute_types + and dtype in DTYPE_LOWP_FP + and src_dtype == torch.float + and not config.emulate_precision_casts + ): + """ + https://github.com/pytorch/pytorch/issues/115260 + For FusedSchedulerNode[node1, node2], the node2 loads what node1 stores and the buffer is + in low-precision floating point data type. When the output of node1 also serves as the output of the + kernel, the result of nodes would be different from the case when output of node1 is not the output + of the kernel (where we don't need to insert `to_dtype` for legalization). To address the problem, on + storing the lowp node1 output, we also add the inverse dtype conversion to high precision data type + to the cse cache. + + Example (pseudo code): + node1_output = ... + node1_output_lowp = to_dtype(node1_output, dtype=torch.bfloat16) + store(buf, node1_output_lowp) + node2_input_lowp = load(buf) + node2_input = to_dtype(node2_input_lowp, dtype=torch.float) + + Without cse cache trick: + node1_output = ... + node1_output_lowp = to_dtype(node1_output, dtype=torch.bfloat16) + store(buf, node1_output_lowp) + node2_input_lowp = node_output_lowp # hit store cache + node2_input = to_dtype(node2_input_lowp, dtype=torch.float) + + With cse cache trick: + node1_output = ... + node1_output_lowp = to_dtype(node1_output, dtype=torch.bfloat16) + # also add `to_dtype(node1_input_lowp, dtype=torch.float)` -> `node1_output` to cse cache + store(buf, node1_output_lowp) + node2_input_lowp = node_output_lowp # hit store cache + node2_input = node1_output # hit cse cache + + This cache trick skips the lowp->fp32 round-trip rounding, so it is + disabled under emulate_precision_casts, where that rounding must be + preserved (e.g. an explicit fp32->fp16->fp32 user cast). See #185337. + """ + V.kernel.cache_dtype_convert(x, src_dtype, csevar, dtype) + return csevar + + @staticmethod + # pyrefly: ignore [bad-override] + def round_to_int(x, dtype, src_dtype=None, use_compute_types=True): + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if src_dtype is None: + src_dtype = x.dtype + expr = V.kernel.get_to_dtype_expr(x, dtype, src_dtype, rounding=True) + csevar = V.kernel.cse.generate(V.kernel.compute, expr) + csevar.update_on_args("round_to_int", (x, dtype), {"src_dtype": src_dtype}) + if ( + dtype in DTYPE_LOWP_FP + and src_dtype == torch.float + and not config.emulate_precision_casts + ): + V.kernel.cache_dtype_convert(x, src_dtype, csevar, dtype) + return csevar + + @staticmethod + def to_dtype_bitcast(x, dtype, src_dtype): + if dtype not in DTYPE_TO_CPP: + raise AssertionError(f"{dtype} missing from {__name__}.DTYPE_TO_CPP") + return f"c10::bit_cast<{DTYPE_TO_CPP[dtype]}>({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def abs(x): + if isinstance(x, CppCSEVariable) and x.dtype in ( + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + ): + # abs(x) == x for unsigned types; return identity to avoid + # -Wtautological-compare and unsigned unary minus warnings. + return f"{x}" + return f"std::abs({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sin(x): + return f"std::sin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cos(x): + return f"std::cos({x})" + + @staticmethod + def neg(x): + return f"decltype({x})(-{x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def exp(x): + # return f"Sleef_expf_u10({x})" + return f"std::exp({x})" + + @staticmethod + def exp2(x): + return f"std::exp2({x})" + + @staticmethod + def expm1(x): + return f"std::expm1({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def erf(x): + return f"std::erf({x})" + + @staticmethod + def erfc(x): + return f"std::erfc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def erfinv(x): + return f"calc_erfinv({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sqrt(x): + return f"std::sqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def rsqrt(x): + return f"1 / std::sqrt({x})" + + @staticmethod + def log1p(x): + bug = config.cpp.inject_log1p_bug_TESTING_ONLY + if bug == "accuracy": + return f"{x} + decltype({x})(1)" + elif bug is None: + return f"std::log1p({x})" + else: + raise AssertionError( + f"unrecognized config cpp.inject_log1p_bug_TESTING_ONLY = {bug!r}" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def tan(x): + return f"std::tan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tanh(x): + return f"std::tanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def signbit(x): + """ + On windows std::signbit only support float type. + Ref: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/signbit?view=msvc-170 + """ + return ( + f"std::signbit(static_cast({x}))" + if _IS_WINDOWS + else f"std::signbit({x})" + ) + + @staticmethod + def pow(a, b): + return f"std::pow({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def log(x): + return f"std::log({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def round(x): + return f"std::nearbyint({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def floor(x): + return f"std::floor({x})" + + @staticmethod + def floordiv(a, b): + # a and b are integer type + return f"floor_divide_integral({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def ceil(x): + return f"std::ceil({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def trunc(x): + return f"std::trunc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def truncdiv(a, b): + # a and b are integer type + return f"{a} / {b}" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmod(a, b): + return f"std::fmod({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def isinf(x): + return f"std::isinf({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def isnan(x): + return f"std::isnan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def lgamma(x): + return f"std::lgamma({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acos(x): + return f"std::acos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acosh(x): + return f"std::acosh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cosh(x): + return f"std::cosh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sinh(x): + return f"std::sinh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asin(x): + return f"std::asin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asinh(x): + return f"std::asinh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan2(x, y): + return f"std::atan2({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x): + return f"std::atan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atanh(x): + return f"std::atanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def copysign(x, y): + return f"std::copysign({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def frexp(x): + cache_keys = f"frexp({x})[0]", f"frexp({x})[1]" + if all(V.kernel.cse.try_get(cache_key) is not None for cache_key in cache_keys): + return tuple(V.kernel.cse.try_get(cache_key) for cache_key in cache_keys) + + code = BracesBuffer() + exponent = V.kernel.cse.newvar(dtype=torch.int32, shape=x.shape) + mantissa = V.kernel.cse.newvar(dtype=x.dtype, shape=x.shape) + code.writeline(f"int32_t {exponent};") + code.writeline(f"auto {mantissa} = std::frexp({x}, &{exponent});") + V.kernel.compute.splice(code) + cse_vars = (mantissa, exponent) + for cache_key, cse_var in zip(cache_keys, cse_vars): + V.kernel.cse.put(cache_key, cse_var) + return mantissa, exponent + + @staticmethod + # pyrefly: ignore [bad-override] + def hypot(x, y): + return f"std::hypot({x}, {y})" + + @staticmethod + def log10(x): + return f"std::log10({x})" + + @staticmethod + def log2(x): + return f"std::log2({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def ldexp(x, n): + return f"std::ldexp({x}, {n})" + + @staticmethod + # pyrefly: ignore [bad-override] + def nextafter(x, y): + return f"std::nextafter({x}, {y})" + + @staticmethod + def relu(x): + bug = config.cpp.inject_relu_bug_TESTING_ONLY + if bug == "compile_error": + return "compile error!" + elif bug == "runtime_error": + return f"{x}; throw 1" + elif bug == "accuracy": + return f"{x} + decltype({x})(1)" + elif bug is None: + return f"std::max({x}, decltype({x})(0))" + else: + raise AssertionError( + f"unrecognized config cpp.inject_relu_bug_TESTING_ONLY = {bug!r}" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a, b): + return f"min_propagate_nan({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a, b): + return f"max_propagate_nan({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmaximum(a, b): + return f"std::max({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def where(a, b, c): + return f"{a} ? {b} : {c}" + + @staticmethod + def mod(a, b): + return f"mod({a}, {b})" + + @staticmethod + def constant(val, dtype): + return value_to_cpp(val, DTYPE_TO_CPP[dtype]) + + @staticmethod + def index_expr(expr, dtype): + idx_str = cexpr(V.kernel.rename_indexing(expr)) + var = V.kernel.cse.generate( + V.kernel.compute, idx_str, bounds=get_bounds_index_expr(expr) + ) + return ops.to_dtype(var, dtype) + + @staticmethod + def value_expr(expr, dtype): + # C++ index_expr already emits the requested dtype, so value_expr has + # the same lowering here. + return CppOverrides.index_expr(expr, dtype) + + @staticmethod + def masked(mask, body, other): + code = BracesBuffer() + + # Write masked operation into a lambda + body_var = V.kernel.cse.newvar() + code.writeline(f"auto {body_var} = [&]") + with V.kernel.swap_buffers(code), code.indent(): + result = body() + code.writeline(f"return {result};") + code.writeline(";") + V.kernel.compute.splice(code) + + # Use the lambda's return type as the type of other + other_code = value_to_cpp(other, f"decltype({body_var}())") + return f"{mask} ? {body_var}() : {other_code}" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_and(a, b): + return f"{a} && {b}" + + @staticmethod + def logical_not(a): + return f"!{a}" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_or(a, b): + return f"{a} || {b}" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_xor(a, b): + return f"{a} != {b}" + + @staticmethod + def bitwise_and(a, b): + return f"decltype({a})({a} & {b})" + + @staticmethod + def bitwise_not(a): + return f"decltype({a})(~{a})" + + @staticmethod + def bitwise_or(a, b): + return f"decltype({a})({a} | {b})" + + @staticmethod + def bitwise_xor(a, b): + return f"decltype({a})({a} ^ {b})" + + @staticmethod + def bitwise_left_shift(a, b): + code = BracesBuffer() + code.writeline("[&]()") + with code.indent(): + scalar_t = DTYPE_TO_CPP[a.dtype] + code.writeline( + f"constexpr decltype({b}) max_shift = sizeof({scalar_t}) * CHAR_BIT;" + ) + code.writeline( + f"if ((static_cast>({b}) < 0) || ({b} >= max_shift))" + ) + with code.indent(): + code.writeline(f"return decltype({a})(0);") + code.writeline( + f"return decltype({a})(static_cast>({a}) << {b});" + ) + code.writeline("()") + return code + + @staticmethod + def bitwise_right_shift(a, b): + code = BracesBuffer() + code.writeline("[&]()") + with code.indent(): + scalar_t = DTYPE_TO_CPP[a.dtype] + code.writeline( + f"constexpr decltype({b}) max_shift = sizeof({scalar_t}) * CHAR_BIT - std::is_signed_v<{scalar_t}>;" + ) + code.writeline( + f"if ((static_cast>({b}) < 0) || ({b} >= max_shift))" + ) + with code.indent(): + code.writeline(f"return decltype({a})({a} >> max_shift);") + code.writeline(f"return decltype({a})({a} >> {b});") + code.writeline("()") + return code + + @staticmethod + def rand(seed: sympy.Expr, offset: sympy.Expr): + return f"normalized_rand_cpu({seed}, {offset})" + + @staticmethod + def rand_eager( + seed: sympy.Expr, + base_offset: sympy.Expr, + threads_per_round: sympy.Expr, + tid: sympy.Expr, + vec: sympy.Expr, + ): + # NOTE: This is a codegen fallback used by the C++ backend for eager random. + # It is not intended to provide CPU parity; parity target is CUDA eager vs compiled. + # Keep this hook to satisfy codegen paths and CI. + return f"normalized_rand_cpu({seed}, {base_offset})" + + @staticmethod + def randn(seed: sympy.Expr, offset: sympy.Expr): + return f"randn_cpu({seed}, {offset})" + + @staticmethod + def randint64(seed: sympy.Expr, offset: sympy.Expr, low, high): + return f"randint64_cpu({seed}, {offset}, {low}, {high})" + + @staticmethod + def sigmoid(x): + return f"decltype({x})(1) / (decltype({x})(1) + std::exp(-{x}))" + + @staticmethod + # pyrefly: ignore [bad-override] + def sign(x): + code = BracesBuffer() + scalar_zero = f"decltype({x})(0)" + scalar_one = f"decltype({x})(1)" + code.writeline("[&]()") + with code.indent(): + code.writeline(f"auto left = {x} > 0 ? {scalar_one} : {scalar_zero};") + code.writeline(f"auto right = {x} < 0 ? {scalar_one} : {scalar_zero};") + code.writeline("return left - right;") + code.writeline("()") + return code + + def partial_accumulate( + self, + name: str, + reduction_type: str, + value: CSEVariable, + extra_meta: dict[str, Any], + ) -> None: + raise NotImplementedError + + +CppOverrides._initialize_pointwise_overrides("cpp") + + +class CppVecOverrides(CppOverrides): + """Map element-wise ops to aten vectorization C++""" + + def __new__(cls, *args, **kargs): + self = super().__new__(cls) + + def wrap(func): + # `CppVecKernel` generates both scalar ops and vector ops according to + # whether the inputs are scalars or vectors while all ops in `CppVecOverrides` + # (except for some ops explained below) assume the inputs are vectors. We wrap the ops in + # `CppVecOverrides` to broadcast scalar inputs to vectors if needed or fallback to + # `CppOverrides` when all inputs are scalars. + # + # Notes on ops handled separately in their own functions: + # `ops.masked`: + # needs recursive handling of masked body. + # `ops.index_expr`: + # needs to further analyze the dependency of the index expression on + # the tiling itervar. + def wrapper(*args, **kwargs): + scalars = [ + arg + for arg in args + if isinstance(arg, (int, sympy.Expr)) + or (isinstance(arg, CppCSEVariable) and not arg.is_vec) + ] + vectors = [ + arg + for arg in args + if isinstance(arg, CppCSEVariable) and arg.is_vec + ] + new_args = list(args) + if scalars and vectors: + new_args = [] + for arg in args: + if isinstance(arg, (int, sympy.Expr)): + if isinstance(arg, sympy.Expr) and not arg.is_number: + arg = ops.index_expr(arg, torch.int64) + else: + arg = ops.constant(arg, torch.int64) + arg = arg.value if isinstance(arg, OpsValue) else arg + new_args.append(arg) + + # DType Promotion + if vectors: + # We have saw several data type mismatch issues related with index_expr in + # the lowering phase of torch.int8. torch.int32, torch.int64. + # 1. int32 and int64 in test_torchinductor.py::test_max_pool2d_with_indices_backward3_cpu + # 2. int8 and int32 in test_torchinductor.py::test_max_pool2d5_cpu + # 3. int32 and fp32 in test_torchinductor_dynamic_shapes.py::test_avg_pool2d8_dynamic_shapes_cpu + if len(new_args) == 2: + new_args = promote_args(new_args) + elif func is CppVecOverrides.where: + new_args[1:] = promote_args(new_args[1:]) + + # Broadcast scalar args to vector + if scalars and vectors: + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError( + "expected isinstance(V.kernel, CppVecKernel)" + ) + new_args = [ + ( + V.kernel.broadcast(new_arg) + if ( + isinstance(new_arg, CppCSEVariable) + and not new_arg.is_vec + and func + not in [ + CppVecOverrides.rand, + CppVecOverrides.randn, + CppVecOverrides.randint64, + ] + ) + else new_arg + ) + for new_arg in new_args + ] + + if vectors: + return func(*new_args, **kwargs) + else: + # fallback to scalar ops + scalar_ops = super(CppVecOverrides, self) + scalar_func = getattr(scalar_ops, func.__name__) + if scalar_func is None: + raise AssertionError("expected scalar_func is not None") + return scalar_func(*args, **kwargs) + + return wrapper + + for name, method in vars(CppVecOverrides).items(): + if getattr(method, "__class__", None) is staticmethod and name not in [ + "masked", + "index_expr", + "value_expr", + ]: + setattr(self, name, wrap(method.__func__)) + + return self + + @staticmethod + def add(a, b): + return f"{a} + {b}" + + @staticmethod + def sub(a, b): + return f"{a} - {b}" + + @staticmethod + def mul(a, b): + return f"{a} * {b}" + + @staticmethod + def truediv(a, b): + return f"{a} / {b}" + + @staticmethod + def abs(x): + if isinstance(x, CppCSEVariable) and x.dtype in ( + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + ): + # Unsigned identity bypass for vectorized path + return f"{x}" + return f"{x}.abs()" + + @staticmethod + def sin(x): + return f"{x}.sin()" + + @staticmethod + def cos(x): + return f"{x}.cos()" + + @staticmethod + def exp(x): + return f"{x}.exp()" + + @staticmethod + def exp2(x): + return f"{x}.exp2()" + + @staticmethod + def expm1(x): + return f"{x}.expm1()" + + @staticmethod + def erf(x): + return f"{x}.erf()" + + @staticmethod + def erfc(x): + return f"{x}.erfc()" + + @staticmethod + def erfinv(x): + return f"{x}.erfinv()" + + @staticmethod + def sqrt(x): + return f"{x}.sqrt()" + + @staticmethod + def eq(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} == {y})" + + @staticmethod + def ne(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype == torch.bool: + if y.dtype != torch.bool: + raise AssertionError("expected y.dtype == torch.bool") + x_cast, y_cast = unify_mask_base_type(V.kernel.compute, (x, y)) + return f"{x_cast} != {y_cast}" + else: + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} != {y})" + + @staticmethod + def lt(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} < {y})" + + @staticmethod + def gt(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} > {y})" + + @staticmethod + def le(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} <= {y})" + + @staticmethod + def ge(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} >= {y})" + + @staticmethod + def and_(x, y): + return f"{x} & {y}" + + @staticmethod + def rsqrt(x): + return f"{x}.rsqrt()" + + @staticmethod + def pow(a, b): + return f"{a}.pow({b})" + + @staticmethod + def log(x): + return f"{x}.log()" + + @staticmethod + def round(x): + return f"{x}.round()" + + @staticmethod + def floor(x): + return f"{x}.floor()" + + @staticmethod + def ceil(x): + return f"{x}.ceil()" + + @staticmethod + def trunc(x): + return f"{x}.trunc()" + + @staticmethod + def fmod(a, b): + return f"{a}.fmod({b})" + + @staticmethod + def lgamma(x): + return f"{x}.lgamma()" + + @staticmethod + def logical_and(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} & {b}" + + @staticmethod + def logical_not(a): + return f"~{a}" + + @staticmethod + def logical_or(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} | {b}" + + @staticmethod + def logical_xor(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} ^ {b}" + + @staticmethod + def bitwise_and(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} & {b}" + + @staticmethod + def bitwise_not(a): + return f"~{a}" + + @staticmethod + def bitwise_or(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} | {b}" + + @staticmethod + def bitwise_xor(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} ^ {b}" + + @staticmethod + def bitwise_left_shift(a, b): + return f"{a} << {b}" + + @staticmethod + def bitwise_right_shift(a, b): + return f"{a} >> {b}" + + @staticmethod + def load_seed(name, offset): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + return f"{V.kernel.load(name, offset)}" + + @staticmethod + def rand(seed, offset): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + code = BracesBuffer() + rand_function = ( + f"result[offset_idx] = normalized_rand_cpu({seed}, offset[offset_idx]);" + ) + return codegen_rand(offset, code, rand_function) + + @staticmethod + def randn(seed, offset): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + code = BracesBuffer() + rand_function = f"result[offset_idx] = randn_cpu({seed}, offset[offset_idx]);" + return codegen_rand(offset, code, rand_function) + + @staticmethod + def randint64(seed, offset, low, high): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + code = BracesBuffer() + rand_function = f"result[offset_idx] = randint64_cpu({seed}, offset[offset_idx], {low}, {high});" + return codegen_rand(offset, code, rand_function, torch.int64) + + @staticmethod + def remainder(a, b): + if a.dtype != b.dtype: + raise AssertionError( + "remainder vec implementation expect the same inputs' dtype." + ) + if is_integer_dtype(a.dtype): + # Doing blend to set the remaining bits of b to non-zero + _t = f"decltype({a})" + if V.kernel._get_raw_num_vectors(b.dtype) < 1: + b = f"{_t}::blend<{(1 << V.kernel.tiling_factor) - 1}>({_t}(1), {b})" + return f"remainder_integral({a}, {b})" + return f"{a} - ({CppVecOverrides.floordiv(a, b)}) * {b}" + + @staticmethod + def tan(a): + return f"{a}.tan()" + + @staticmethod + def tanh(a): + if config.cpp.use_decompose_tanh: + vec_one = f"decltype({a})(1)" + vec_two = f"decltype({a})(2)" + vec_minus_two = f"decltype({a})(-2)" + return ( + f"{vec_two} / ({vec_one} + ({vec_minus_two} * {a}).exp()) - {vec_one}" + ) + else: + return f"{a}.tanh()" + + @staticmethod + def reciprocal(a): + return f"{a}.reciprocal()" + + @staticmethod + def atan(x): + return f"{x}.atan()" + + @staticmethod + def acos(x): + return f"{x}.acos()" + + @staticmethod + def asin(x): + return f"{x}.asin()" + + @staticmethod + def cosh(x): + return f"{x}.cosh()" + + @staticmethod + def sinh(x): + return f"{x}.sinh()" + + @staticmethod + def log10(x): + return f"{x}.log10()" + + @staticmethod + def log2(x): + return f"{x}.log2()" + + @staticmethod + def nextafter(x, y): + return f"{x}.nextafter({y})" + + @staticmethod + def copysign(a, b): + return f"{a}.copysign({b})" + + @staticmethod + def atan2(a, b): + return f"{a}.atan2({b})" + + @staticmethod + def hypot(a, b): + return f"{a}.hypot({b})" + + @staticmethod + def atanh(x): + # For real x, atanh(x) = 1/2 * log((1+x)/(1-x)) + vec_one = f"decltype({x})(1)" + vec_one_half = f"decltype({x})(0.5)" + return f"{vec_one_half} * (({vec_one} + {x})/({vec_one} - {x})).log()" + + @staticmethod + def asinh(x): + vec_t = f"decltype({x})" + code = BracesBuffer() + code.writeline("[&]()") + with code.indent(): + # Avoid Vectorized::asinh/SLEEF here: it overflows internally for + # large finite fp32 inputs where eager std::asinh remains finite. + # This is asinh(x) = sign(x) * log(abs(x) + sqrt(abs(x)^2 + 1)), + # rewritten with 1 / abs(x) to avoid squaring large values. + code.writeline(f"auto abs_x = {x}.abs();") + code.writeline(f"auto one = {vec_t}(1);") + code.writeline("auto inv_abs_x = one / abs_x;") + code.writeline( + "auto correction = " + "(one / (one + inv_abs_x)) / " + "((one + inv_abs_x * inv_abs_x).sqrt() + inv_abs_x);" + ) + code.writeline("auto result = abs_x.log1p() + correction.log1p();") + code.writeline(f"return result.copysign({x});") + code.writeline("()") + return code + + @staticmethod + def acosh(x): + return f"{x}.acosh()" + + @staticmethod + def relu(x): + bug = config.cpp.inject_relu_bug_TESTING_ONLY + if bug == "compile_error": + return "compile error!" + elif bug == "runtime_error": + return f"{x}; throw 1" + elif bug == "accuracy": + return f"{x} + decltype({x})(1)" + elif bug is None: + return f"at::vec::clamp_min({x}, decltype({x})(0))" + else: + raise AssertionError( + f"unrecognized config cpp.inject_relu_bug_TESTING_ONLY = {bug!r}" + ) + + # TODO: this seems to be dead + @staticmethod + def sigmoid(x): + return f"decltype({x})(1)/(decltype({x})(1) + {x}.neg().exp())" + + @staticmethod + def neg(x): + return f"{x}.neg()" + + @staticmethod + def floordiv(a, b): + if is_float_dtype(a.dtype): + if a.dtype != b.dtype: + raise AssertionError( + "div_floor_floating_vec implementation expect the same inputs' dtype." + ) + return f"div_floor_floating_vec({a}, {b})" + else: + if not (all(is_integer_dtype(item.dtype) for item in [a, b])): + raise AssertionError( + "expected all(is_integer_dtype(item.dtype) for item in [a, b])" + ) + # a and b are integer type + _t = f"decltype({b})" + b = f"{_t}::set({_t}(1), {b}, {cexpr_index(V.kernel.num_elems)})" + return f"floor_divide_integral({a}, {b})" + + @staticmethod + def truncdiv(a, b): + # a and b are integer type + _t = f"decltype({b})" + b = f"{_t}::set({_t}(1), {b}, {cexpr_index(V.kernel.num_elems)})" + return f"{a} / {b}" + + @staticmethod + def minimum(a, b): + if a.dtype == torch.bool: + if b.dtype != torch.bool: + raise AssertionError("expected b.dtype == torch.bool") + a_cast, b_cast = unify_mask_base_type(V.kernel.compute, (a, b)) + return f"{a_cast} & {b_cast}" + else: + return f"at::vec::minimum({a}, {b})" + + @staticmethod + def maximum(a, b): + if a.dtype == torch.bool: + if b.dtype != torch.bool: + raise AssertionError("expected b.dtype == torch.bool") + a_cast, b_cast = unify_mask_base_type(V.kernel.compute, (a, b)) + return f"{a_cast} | {b_cast}" + else: + return f"at::vec::maximum({a}, {b})" + + @staticmethod + def fmaximum(a, b): + return f"decltype({a})::blendv({a}, {b}, {a} < {b})" + + @staticmethod + def square(a): + return f"{a} * {a}" + + @staticmethod + def where(a, b, c): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if b.dtype == torch.bool: + if c.dtype != torch.bool: + raise AssertionError("expected c.dtype == torch.bool") + blendv_a, blendv_b, blendv_c = unify_mask_base_type( + V.kernel.compute, (a, b, c) + ) + return f"decltype({blendv_b})::blendv({blendv_c}, {blendv_b}, {blendv_a})" + else: + return f"decltype({b})::blendv({c}, {b}, {V.kernel._get_mask_cast(a, b.dtype)})" + + @staticmethod + def sign(x): + code = BracesBuffer() + vec_zero = f"decltype({x})(0)" + vec_one = f"decltype({x})(1)" + blendv_l = f"decltype({x})::blendv({vec_zero}, {vec_one}, {vec_zero} < {x})" + blendv_r = f"decltype({x})::blendv({vec_zero}, {vec_one}, {x} < {vec_zero})" + code.writeline("[&]()") + with code.indent(): + code.writeline(f"auto left = {blendv_l};") + code.writeline(f"auto right = {blendv_r};") + code.writeline("return left - right;") + code.writeline("()") + return code + + @staticmethod + def to_dtype(x, dtype, src_dtype=None, use_compute_types=True): + if dtype not in [ + torch.bool, + torch.float64, + torch.float, + torch.bfloat16, + torch.float16, + torch.uint8, + torch.int8, + torch.int32, + torch.int64, + torch.float8_e4m3fn, + torch.float8_e5m2, + ]: + raise AssertionError(f"{__name__} does not support {dtype}") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + src_dtype = x.dtype + expr = V.kernel.get_to_dtype_expr(x, dtype, src_dtype) + csevar = V.kernel.cse.generate(V.kernel.compute, expr) + csevar.update_on_args("to_dtype", (x, dtype), {"src_dtype": src_dtype}) + if ( + use_compute_types + and dtype in DTYPE_LOWP_FP + and src_dtype == torch.float + and not config.emulate_precision_casts + ): + V.kernel.cache_dtype_convert(x, src_dtype, csevar, dtype) + return csevar + + @staticmethod + def round_to_int(x, dtype, src_dtype=None, use_compute_types=True): + if dtype not in [ + torch.uint8, + torch.int8, + torch.int32, + ]: + raise AssertionError(f"{__name__} does not support {dtype}") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + src_dtype = x.dtype + expr = V.kernel.get_to_dtype_expr(x, dtype, src_dtype, rounding=True) + csevar = V.kernel.cse.generate(V.kernel.compute, expr) + csevar.update_on_args("round_to_int", (x, dtype), {"src_dtype": src_dtype}) + if ( + dtype in DTYPE_LOWP_FP + and src_dtype == torch.float + and not config.emulate_precision_casts + ): + V.kernel.cache_dtype_convert(x, src_dtype, csevar, dtype) + return csevar + + @staticmethod + def log1p(x): + bug = config.cpp.inject_log1p_bug_TESTING_ONLY + if bug == "accuracy": + return f"{x} + decltype({x})(1)" + elif bug is None: + return f"{x}.log1p()" + else: + raise AssertionError( + f"unrecognized config cpp.inject_log1p_bug_TESTING_ONLY = {bug!r}" + ) + + @staticmethod + def masked(mask, body, other): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + code = BracesBuffer() + var = V.kernel.cse.newvar() + with V.kernel.masked(mask) as new_mask: + code.writeline(f"auto {var} = [&]") + with V.kernel.swap_buffers(code), code.indent(): + result = body() + code.writeline(f"return {result};") + code.writeline(";") + V.kernel.compute.splice(code) + + dtype = result.dtype + body_code = f"{var}()" + + def maskify_or_vecify(code): + return ( + f"{V.kernel._get_mask_type()}::from({code})" + if dtype == torch.bool + else f"{V.kernel._get_vec_type(dtype)}({code})" + ) + + if result.is_vec: + body_code_vec = body_code + else: + body_code_vec = maskify_or_vecify(body_code) + other_code = value_to_cpp(other, DTYPE_TO_CPP[dtype]) + # loading bool as VecMask + other_code_vec = maskify_or_vecify(other_code) + if not isinstance(new_mask, CppCSEVariable): + raise AssertionError(new_mask) + if new_mask.is_vec: + code = BracesBuffer() + code.writeline("[&]") + with V.kernel.swap_buffers(code), code.indent(): + code.writeline(f"if ({new_mask}.all_zero())") + with code.indent(): + code.writeline(f"return {other_code_vec};") + code.writeline("else") + with code.indent(): + # Create cse variable to reuse kernel.overrides.where + body_vec_var = V.kernel.cse.generate( + V.kernel.compute, + body_code_vec, + ) + other_vec_var = V.kernel.cse.generate( + V.kernel.compute, + other_code_vec, + ) + if not isinstance(body_vec_var, CppCSEVariable): + raise AssertionError(body_vec_var) + if not isinstance(other_vec_var, CppCSEVariable): + raise AssertionError(other_vec_var) + body_vec_var.dtype = dtype + other_vec_var.dtype = dtype + overrides: type[CppOverrides | CppVecOverrides] = ( + # pyrefly: ignore [bad-assignment] + V.kernel.overrides + ) # type: ignore[has-type] + code.writeline( + f"return {overrides.where(new_mask, body_vec_var, other_vec_var)};" + ) + code.writeline("()") + csevar = V.kernel.cse.generate( + V.kernel.compute, + code, + ) + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + csevar.is_vec = True + elif result.is_vec: + csevar = V.kernel.cse.generate( + V.kernel.compute, f"{mask} ? {body_code_vec} : {other_code_vec}" + ) + else: + csevar = V.kernel.cse.generate( + V.kernel.compute, f"{mask} ? {body_code} : {other_code}" + ) + # `result` is explicitly added to the args for correct propagation + # of relevant itervars and vectorization status. + csevar.update_on_args("masked", (mask, body, other, result), {}) + return csevar + + @staticmethod + def index_expr(expr, dtype): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + index = V.kernel.rename_indexing(expr) + tiling_var = V.kernel.itervars[V.kernel.tiling_idx] + stride = V.kernel._try_get_const_stride(index, tiling_var) + if stride == 0: + return CppOverrides.index_expr(expr, dtype) + elif stride is not None: + idx = V.kernel.cse.generate( + V.kernel.compute, cexpr(index), bounds=get_bounds_index_expr(expr) + ) + value = ops.to_dtype(idx, dtype) + if isinstance(value, OpsValue): + value = value.value + csevar = V.kernel.arange(value, stride) + else: + csevar = V.kernel._load_or_store_non_contiguous( # type: ignore[assignment] + None, index, dtype, V.kernel.compute + ) + # pyrefly: ignore [missing-attribute] + csevar.update_on_args("index_expr", (expr, dtype), {}) + return csevar + + @staticmethod + def value_expr(expr, dtype): + # C++ index_expr already emits the requested dtype, so value_expr has + # the same lowering here. + return CppVecOverrides.index_expr(expr, dtype) + + @staticmethod + def frexp(x): + cache_keys = f"frexp({x})[0]", f"frexp({x})[1]" + if all(V.kernel.cse.try_get(cache_key) is not None for cache_key in cache_keys): + return tuple(V.kernel.cse.try_get(cache_key) for cache_key in cache_keys) + + cdtype = DTYPE_TO_CPP[x.dtype] + size = V.kernel.tail_size if V.kernel.tail_size else V.kernel.tiling_factor + code = BracesBuffer() + exponent = V.kernel.cse.newvar(dtype=torch.int32) + mantissa = V.kernel.cse.newvar(dtype=x.dtype) + exponent.update_on_args("frexp", (x,), kwargs={}) + mantissa.update_on_args("frexp", (x,), kwargs={}) + n_vec = V.kernel._get_num_vectors(x.dtype) + mantissa_t = ( + f"at::vec::Vectorized<{cdtype}>" + if n_vec == 1 + else f"at::vec::VectorizedN<{cdtype}, {n_vec}>" + ) + code.writeline( + f"at::vec::Vectorized {exponent};" + if n_vec == 1 + else f"at::vec::VectorizedN {exponent};" + ) + code.writeline(f"{mantissa_t} {mantissa};") + code.writeline("[&]()") + with code.indent(): + code.writeline( + f"__at_align__ std::array<{cdtype}, {V.kernel.tiling_factor}> tmpbuf;" + ) + code.writeline(f"{x}.store(tmpbuf.data(), {cexpr_index(size)});") + code.writeline( + f"__at_align__ std::array tmpbuf_exponent;" + ) + code.writeline( + f"__at_align__ std::array<{cdtype}, {V.kernel.tiling_factor}> tmpbuf_mantissa;" + ) + code.writeline(f"for (int i = 0; i < {cexpr_index(size)}; i++)") + with code.indent(): + code.writeline( + "tmpbuf_mantissa[i] = std::frexp(tmpbuf[i], &tmpbuf_exponent[i]);" + ) + code.writeline( + f"{exponent} = at::vec::Vectorized::loadu(tmpbuf_exponent.data(), {cexpr_index(size)});" + if n_vec == 1 + else f"{exponent} = at::vec::VectorizedN::loadu(tmpbuf_exponent.data(), {cexpr_index(size)});" + ) + code.writeline( + f"{mantissa} = {mantissa_t}::loadu(tmpbuf_mantissa.data(), {cexpr_index(size)});" + ) + code.writeline("();") + V.kernel.compute.splice(code) + cse_vars = (mantissa, exponent) + for cache_key, cse_var in zip(cache_keys, cse_vars): + V.kernel.cse.put(cache_key, cse_var) + return mantissa, exponent + + @classmethod + def _scalarize(cls, scalar_func): + def inner(*args, **kwargs): + if kwargs: + raise AssertionError("expected not kwargs") + kernel = V.kernel + if not isinstance(kernel, CppVecKernel): + raise AssertionError("expected isinstance(kernel, CppVecKernel)") + code = BracesBuffer() + code.writeline("[&]()") + vec_dtype = args[0].dtype + n_vec = kernel._get_num_vectors(vec_dtype) + size = kernel.tail_size if kernel.tail_size else kernel.tiling_factor + scalar_args = [] + cdtype = DTYPE_TO_CPP[vec_dtype] + output_mask = scalar_func.__name__ in ( + "isinf", + "isnan", + "signbit", + ) + octype = "bool" if output_mask else cdtype + octype = ( + DTYPE_TO_CPP[args[-2]] + if (scalar_func.__name__ == "to_dtype_bitcast") + else octype + ) + with code.indent(): + for argidx, arg in enumerate(args): + if isinstance(arg, CppCSEVariable): + if not arg.is_vec: + raise AssertionError("expected arg.is_vec") + if arg.dtype != vec_dtype: + raise AssertionError("expected arg.dtype == vec_dtype") + code.writeline( + f"__at_align__ std::array<{cdtype}, {kernel.tiling_factor}> tmpbuf{argidx};" + ) + code.writeline( + f"{arg}.store(tmpbuf{argidx}.data(), {cexpr_index(size)});" + ) + scalar_args.append(f"tmpbuf{argidx}[i]") + else: + scalar_args.append(arg) + code.writeline( + f"__at_align__ std::array<{octype}, {kernel.tiling_factor}> tmpbuf_out;" + ) + res = scalar_func(*scalar_args) + code.writeline(f"for (int i = 0; i < {cexpr_index(size)}; i++)") + with code.indent(): + code.writeline(f"tmpbuf_out[i] = {res};") + load_args = f"tmpbuf_out.data(), {cexpr_index(size)}" + if output_mask: + load_fn = f"at::vec::VecMask<{cdtype},{n_vec}>::from" + elif n_vec == 1: + load_fn = f"at::vec::Vectorized<{octype}>::loadu" + else: + load_fn = f" at::vec::VectorizedN<{octype}, {n_vec}>::loadu" + code.writeline(f"return {load_fn}({load_args});") + code.writeline("()") + return code + + return inner + + @classmethod + def _initialize_scalarize(cls): + vec_vars = vars(CppVecOverrides) + for name, method in vars(CppOverrides).items(): + if isinstance(method, staticmethod) and name not in vec_vars: + func = cls._scalarize(method.__func__) + func.__name__ = name + setattr(cls, name, staticmethod(func)) + + +CppVecOverrides._initialize_pointwise_overrides("cppvec") +CppVecOverrides._initialize_scalarize() + + +class CppTile2DOverrides(CppVecOverrides): + @staticmethod + def index_expr(expr, dtype): + if not isinstance(V.kernel, CppTile2DKernel): + raise AssertionError("expected isinstance(V.kernel, CppTile2DKernel)") + expr = V.kernel.transform_indexing(expr) + return CppVecOverrides.index_expr(expr, dtype) + + @staticmethod + def value_expr(expr, dtype): + # C++ index_expr already emits the requested dtype, so value_expr has + # the same lowering here. + return CppTile2DOverrides.index_expr(expr, dtype) + + +class CppKernel(Kernel): + """ + Base class for C++ kernel code generation in PyTorch Inductor. + This class is responsible for generating C++ code from the intermediate representation. + + Args: + args: Kernel arguments used for code generation + num_threads: Number of threads for parallel execution + """ + + overrides = CppOverrides # type: ignore[assignment] + sexpr = cexpr + newvar_prefix = "auto " + suffix = ";" + + def __init__(self, args, num_threads): + super().__init__(args) + # Indicate when this kernel is active, for example + # {x0, {24, 26}} -> this kernel is active when x0 >= 24 and x0 < 26 + self.active_ranges: dict[sympy.Expr, tuple[sympy.Expr, ...]] = {} + # Indicate this kernel will be moved under the inner for-loop + # See move_code_under_inner_loop + self.inner_itervars: list[sympy.Symbol] = [] + self.call_ranges: tuple[sympy.Expr, ...] | None = None + self.ranges: list[sympy.Expr] = [] + self.itervars: list[sympy.Symbol] = [] + self.reduction_depth = None + self.reduction_prefix = IndentedBuffer() + # We need this because when we run "reduction" nodes here, we lack + # "loop" information to decide whether we need a scalar init or an array init + # in the reduction prefix. Meanwhile, we have other information like + # reduction types and dtype to generate the reduction prefix. We record the information + # with a callable lambda function, and when we have enough information to finalize + # the reduction prefix, we can invoke the functions here with additional information. + self.reduction_prefix_generators: list[Callable] = [] # type: ignore[type-arg] + self.reduction_suffix = IndentedBuffer() + self.parallel_reduction_prefix = IndentedBuffer() + self.parallel_reduction_suffix = IndentedBuffer() + self.local_reduction_init = IndentedBuffer() + self.local_reduction_stores = IndentedBuffer() + self.is_reduction = False + self.non_parallel_reduction_prefix = IndentedBuffer() + self.non_parallel_reduction_suffix = IndentedBuffer() + self.reduction_cse = CSE(self.newvar_prefix, self.suffix, name_prefix="tmp_acc") + self.welford_helper_cse = CSE( + self.newvar_prefix, self.suffix, name_prefix="welford_helper" + ) + self.cascade_helper_cse = CSE( + self.newvar_prefix, self.suffix, name_prefix="cascade_helper" + ) + self.preloads = IndentedBuffer() + self.poststores = IndentedBuffer() + self.num_threads = num_threads # num_threads the kernel specialized for + self.reduction_omp_dec: dict[tuple[str, str], str] = {} + self.reduction_var_names: list[str] = [] + + def _gen_parallel_reduction_buffers( + self, + acc, + acc_type, + reduction_type, + dtype, + reduction_combine_fn=reduction_combine, + reduction_init_fn=reduction_init, + ): + if config.cpp.dynamic_threads and not self.parallel_reduction_prefix: + self.parallel_reduction_prefix.writeline( + "int max_threads = omp_get_max_threads();" + ) + acc_local = f"{acc}_local" + num_threads = ( + "max_threads" if config.cpp.dynamic_threads else parallel_num_threads() + ) + acc_local_in_array = f"{acc}_arr[tid]" + self.local_reduction_init.writeline( + f"{acc_type} {acc_local} = {reduction_init_fn(reduction_type, dtype)};" + ) + self.parallel_reduction_prefix.splice( + reduction_prefix_array( + acc, + acc_type, + reduction_type, + dtype, + num_threads, + reduction_init_fn, + ) + ) + self.local_reduction_stores.writeline(f"{acc_local_in_array} = {acc_local};") + self.parallel_reduction_suffix.writelines( + [ + f"for (int tid = 0; tid < {num_threads}; tid++)", + "{", + f" {acc} = {reduction_combine_fn(reduction_type, acc, acc_local_in_array, src_dtype=dtype)};", + "}", + ], + ) + + def update_stores_with_parallel_reduction(self): + for var_name in self.reduction_var_names: + replace_acc_name(self.stores, var_name, f"{var_name}_local") + + def gen_body(self, code: BracesBuffer | None = None): + if code is not None: + raise AssertionError("expected code is None") + code = BracesBuffer() + with contextlib.ExitStack() as stack: + if hasattr(self, "codegen_inner_loops"): + code.splice(self.preloads) + self.codegen_inner_loops(code) + stack.enter_context(code.indent()) + code.splice(self.loads) + code.splice(self.compute) + code.splice(self.stores) + if hasattr(self, "codegen_inner_loops"): + code.splice(self.poststores) + + if self.inner_itervars: + for idx in self.inner_itervars: + start, end = self.active_ranges[idx] + code = move_code_under_inner_loop(code, idx, f"{idx}_tail", start, end) + return code + + @contextlib.contextmanager + def masked(self, mask): + """Context manager to add an additional mask to loads and stores.""" + prior = self._load_mask + if prior: + mask = ops.and_(mask, prior) + if isinstance(mask, OpsValue): + mask = mask.value + if not isinstance(mask, CppCSEVariable): + raise AssertionError("expected isinstance(mask, CppCSEVariable)") + # see NOTE [dtype of CppCSEVariable] + # mask's dtype should be bool + mask.dtype = torch.bool + + self._load_mask = mask + try: + yield mask + finally: + self._load_mask = prior + + def scale_index_with_offset( + self, index: sympy.Expr, scale=1, itervar_idx=-1, offset=0 + ): + var = self.itervars[itervar_idx] + replacement = {var: var * scale + offset} + new_index = sympy_subs(index, replacement) + return new_index + + def index_to_str(self, index: sympy.Expr) -> str: + """ + Convert an index expr to a string that can be used in cpp code. + e.g. a sympy expression "s2" may actually appear as "ks1" in the cpp kernel. + """ + return cexpr(self.rename_indexing(index)) + + def index_indirect_depends_on(self, index: sympy.Expr, itervar: sympy.Symbol): + """ + Check if an index has free symbol CppCSEVariable that depends on `itervar`. + """ + return any( + self.cse.varname_map[s.name].depends_on(itervar) # type: ignore[attr-defined] + for s in index.free_symbols + if s.name in self.cse.varname_map # type: ignore[attr-defined] + and isinstance(self.cse.varname_map[s.name], CppCSEVariable) # type: ignore[attr-defined] + ) + + def index_depends_on(self, index: sympy.Expr, itervar: sympy.Symbol): + return itervar in index.free_symbols or self.index_indirect_depends_on( + index, itervar + ) + + def var_ranges(self): + return dict(zip(self.itervars, self.ranges)) + + def check_bounds( + self, + expr: sympy.Expr, + size: sympy.Expr, + lower: bool, + upper: bool, + ): + if not (lower or upper): + return + + indirect = free_symbol_is_type(expr, SymT.TMP) + if indirect: + # indexing in compute + csevar = ops.index_expr(expr, torch.int64).value + buffer = V.kernel.compute + else: + # Prefer to put the assert in loads so it runs before the actual + # memory access. However, if the index expression may have already + # been CSE'd into compute by a prior ops.index_expr call, placing a + # reference to it in loads would be a forward reference (loads are + # emitted before compute in the kernel body). In that case fall + # back to compute. + idx_str = cexpr(self.rename_indexing(expr)) + if self.cse.try_get(idx_str) is not None: + csevar = ops.index_expr(expr, torch.int64).value + buffer = V.kernel.compute + else: + prior_compute = V.kernel.compute + try: + V.kernel.compute = self.loads + csevar = ops.index_expr(expr, torch.int64).value + finally: + V.kernel.compute = prior_compute + buffer = self.loads + + size_str = V.kernel.sexpr(self.rename_indexing(size)) if upper else None + + line = self.indirect_assert( + csevar, "0" if lower else None, size_str, self._load_mask + ) + self.cse.generate(buffer, line, assignment=False) + + def load(self, name: str, index: sympy.Expr): + var = self.args.input(name) + index = self.rename_indexing(index) + line = f"{var}[{cexpr_index(index)}]" + csevar = self.cse.generate(self.loads, line, dtype=V.graph.get_dtype(name)) + csevar.update_on_args("load", (self, name, index), {}) + return csevar + + def _use_parallel_atomic_add(self): + return config.cpp.dynamic_threads or self.num_threads != 1 + + def store(self, name, index, value, mode=None): + if "buf" not in name: + raise AssertionError('expected "buf" in name') + var = self.args.output(name) + index = self.rename_indexing(index) + if mode is None: + line = f"{var}[{cexpr_index(index)}] = {value};" + elif mode == "atomic_add": + if not self._use_parallel_atomic_add(): + line = f"{var}[{cexpr_index(index)}] += {value};" + else: + dtype = V.graph.get_dtype(name) + # mirroring static_cast(...) in load: + value = f"static_cast<{DTYPE_TO_CPP[dtype]}>({value})" + line = f"atomic_add(&{var}[{cexpr_index(index)}], {value});" + else: + raise NotImplementedError(f"store mode={mode}") + self.stores.writeline(DeferredLine(name, line)) + + def device_assert_async(self, cond, msg): + self.compute.writeline( + f'({cond} ? 0 : (throw std::runtime_error("{msg}"), 0));' + ) + + def _gen_reduction_prefix( + self, + acc: CSEVariable | str, + acc_type: str, + rtype: str, + dtype: torch.dtype, + init_fn, + ): + # Generate reduction prefix + # If size is None, we will define and initialize a single reduction variable + # => float tmp_acc0 = 0; + # Otherwise, we will define and initialize a reduction array + # => float tmp_acc0_arr[size]; + # => for (int i = 0; i < size; i++) tmp_acc0_arr[i] = 0; + def inner(size: int | None = None): + if size is None: + return f"{acc_type} {acc} = {init_fn(rtype, dtype)};" + else: + return reduction_prefix_array( + acc, + acc_type, + rtype, + dtype, + size, + init_fn, + ) + + return inner + + def finalize_reduction_prefix(self, size: int | None = None): + for gen_fn in self.reduction_prefix_generators: + self.reduction_prefix.splice(gen_fn(size)) + + def need_use_acc_helper(self, reduction_type, dtype, use_scalar): + # Check if we need accumulate helper for the reduction operation. + # using accumulate helper generates the necessary code to improve precision for + # sum and welford + # Note: using helper has non-negligible impact on performance + + if reduction_type == "welford_reduce": + return True + + # TODO add supports for more data types when needed + if reduction_type == "sum" and dtype == torch.float: + if self.call_ranges is None: + raise AssertionError("expected self.call_ranges is not None") + reduction_size = functools.reduce( + operator.mul, self.call_ranges[self.reduction_depth :] + ) + + # chunk size to balance accuracy and performance + chunk_size = 4096 + + return V.graph.sizevars.guard_or_false(sympy.Gt(reduction_size, chunk_size)) + return False + + def _acc_helper_init( + self, + reduction_type, + helper_val, + helper_range, + dtype, + num_threads=None, + use_scalar=False, + ): + num_range_thread = ( + CeilDiv(helper_range, num_threads) if num_threads else helper_range + ) + num_range_thread_expr = cexpr_index(num_range_thread) + if reduction_type not in ["welford_reduce", "sum"]: + raise AssertionError('expected reduction_type in ["welford_reduce", "sum"]') + chunk_size = 4096 + num_chunks = CeilDiv(num_range_thread, chunk_size) + helper_type = ( + "WelfordHelper" + if reduction_type == "welford_reduce" + else "CascadeSumHelper" + ) + if use_scalar: + h_type = DTYPE_TO_CPP[dtype] + else: + h_type = ( + self._get_vec_type(dtype) + if hasattr(self, "_get_vec_type") + else DTYPE_TO_CPP[dtype] + ) + helper_init_line = ( + f"{helper_type}<{h_type}, {chunk_size}> {helper_val}" + f"(" + f"{num_range_thread_expr}" + f");" + ) + if reduction_type == "sum": + return helper_init_line + if isinstance(num_chunks, sympy.Integer) and num_chunks <= 1: + # When the number of chunks <= 1, there is no need to use cascade summation to improve + # reduction accuracy. We can initialize a static WelfordHelper to improve performance. + return f"static {helper_init_line}" + else: + return helper_init_line + + def _use_acc_helper( + self, reduction_type, acc, helper_val, helper_range, dtype, use_scalar=False + ): + num_threads = ( + "max_threads" if config.cpp.dynamic_threads else parallel_num_threads() + ) + self.non_parallel_reduction_prefix.writeline( + self._acc_helper_init( + reduction_type, helper_val, helper_range, dtype, None, use_scalar + ) + ) + self.local_reduction_init.writeline( + self._acc_helper_init( + reduction_type, helper_val, helper_range, dtype, num_threads, use_scalar + ) + ) + result = acc if use_scalar else f"{acc}_vec" + if reduction_type == "welford_reduce": + self.non_parallel_reduction_suffix.writeline( + f"{result} = welford_combine({result}, &{helper_val});" + ) + self.local_reduction_stores.writeline( + f"{result}_local = welford_combine({result}_local, &{helper_val});" + ) + else: + self.non_parallel_reduction_suffix.writeline( + f"{result} = cascade_sum_final(&{helper_val});" + ) + self.local_reduction_stores.writeline( + f"{result}_local = cascade_sum_final(&{helper_val});" + ) + + def reduction(self, dtype, src_dtype, reduction_type, value): + argmax_or_argmin = reduction_type in ("argmax", "argmin") + logical_index = None + if argmax_or_argmin and isinstance(value, tuple): + value, logical_index = value + + if logical_index is not None: + logical_index_key = cast(CSEVariable, logical_index) + reduction_key = src_dtype, reduction_type, (value, logical_index_key) + else: + reduction_key = src_dtype, reduction_type, value + if reduction_key in self.reduction_cse.reduction_cache: + return self.reduction_cse.reduction_cache[reduction_key] + + acc = self.reduction_cse.generate( + self.loads, f"reduction {reduction_key}", write=False + ) + self.reduction_var_names.append(f"{acc}") + self.is_reduction = True + init_dtype = src_dtype if argmax_or_argmin else dtype + acc_type = reduction_acc_type(reduction_type, init_dtype) + self.reduction_prefix_generators.append( + self._gen_reduction_prefix( + acc, acc_type, reduction_type, init_dtype, reduction_init + ) + ) + + if self.need_use_acc_helper(reduction_type, dtype, True): + # use cascade_helper for vec kernel + reduction_size = functools.reduce( + operator.mul, self.ranges[self.reduction_depth :] + ) + # use welford_helper/cascade_helper for vec kernel + if reduction_type == "welford_reduce": + helper_val = self.welford_helper_cse.generate( + self.compute, f"reduction {reduction_key}", write=False + ) + else: + helper_val = self.cascade_helper_cse.generate( + self.compute, f"reduction {reduction_key}", write=False + ) + # rename the helper variable to distinguish it from vectorized version + scalar_helper_val = f"scalar_{helper_val}" + self._use_acc_helper( + reduction_type, + acc, + scalar_helper_val, + reduction_size, + dtype, + use_scalar=True, + ) + self.stores.writeline( + f"{acc} = {reduction_combine(reduction_type, acc, value, scalar_helper_val)};" + ) + else: + if logical_index is not None: + index = logical_index + else: + if self.reduction_depth is None: + raise AssertionError("expected self.reduction_depth is not None") + index = self.itervars[self.reduction_depth] + for i in range(self.reduction_depth + 1, len(self.itervars)): + index = index * self.ranges[i] + self.itervars[i] + self.stores.writeline( + f"{acc} = {reduction_combine(reduction_type, acc, value, index=index)};" + ) + + self._gen_parallel_reduction_buffers(acc, acc_type, reduction_type, init_dtype) + result = reduction_project(reduction_type, acc) + self.reduction_cse.reduction_cache[reduction_key] = result + return result + + def store_reduction(self, name, index, value): + index = self.rename_indexing(index) + var = self.args.output(name) + self.reduction_suffix.writeline( + DeferredLine(name, f"{var}[{cexpr_index(index)}] = {value};") + ) + + def set_ranges(self, lengths, reduction_lengths): + if self.call_ranges: + if self.call_ranges != tuple(lengths) + tuple(reduction_lengths): + raise AssertionError( + f"{self.call_ranges} == {tuple(lengths)} + {tuple(reduction_lengths)}" + ) + if self.reduction_depth != len(lengths): + raise AssertionError("expected self.reduction_depth == len(lengths)") + else: + self.call_ranges = tuple(lengths) + tuple(reduction_lengths) + self.ranges = [self.rename_indexing(x) for x in self.call_ranges] + self.itervars = [ + sympy_index_symbol_with_prefix(SymT.XBLOCK, n) + for n in range(len(self.ranges)) + ] + # pyrefly: ignore [bad-assignment] + self.reduction_depth = len(lengths) + return ( + self.itervars[: self.reduction_depth], + self.itervars[self.reduction_depth :], + ) + + def size_hint(self): + if self.call_ranges is None: + raise AssertionError("expected self.call_ranges is not None") + expr = sympy_product(self.call_ranges) + return V.graph.sizevars.optimization_hint(expr) + + def codegen_loops_impl(self, loop_nest, code, worksharing): + if not isinstance(self, CppKernelProxy): + raise AssertionError("expected isinstance(self, CppKernelProxy)") + threads = parallel_num_threads() + if self.call_ranges is None: + raise AssertionError("expected self.call_ranges is not None") + if isinstance(loop_nest.kernel, OuterLoopFusedKernel): + par_depth = loop_nest.kernel.decide_parallel_depth( + loop_nest.max_parallel_depth(), threads + ) + else: + par_depth = self.decide_parallel_depth( + loop_nest.max_parallel_depth(), threads + ) + + is_reduction_loop = ( + loop_nest.loops is not None + and loop_nest.loops[par_depth.start_depth].is_reduction + ) + with contextlib.ExitStack() as stack: + if par_depth.parallel_depth: + if is_reduction_loop: + # need to close the worksharing scope to define reduction vars outside it + worksharing.close() + else: + worksharing.parallel(threads) + loop_nest.mark_parallel(par_depth) + elif threads > 1: + if worksharing.single(): + stack.enter_context(code.indent()) + + def gen_kernel(_loop_nest: LoopNest): + def is_parallel_reduction(): + if not _loop_nest.loops: + raise AssertionError("expected _loop_nest.loops") + root = _loop_nest.loops[par_depth.start_depth] + return root.is_reduction and root.parallel + + kernel = _loop_nest.get_kernel() + if isinstance(kernel, OuterLoopFusedKernel): + for _loop_nest in kernel.inner: + gen_loop_nest(_loop_nest) + else: + if not isinstance(kernel, CppKernelProxy): + raise AssertionError( + "expected isinstance(kernel, CppKernelProxy)" + ) + if _loop_nest.loops is not None and is_parallel_reduction(): + kernel.update_stores_with_parallel_reduction() + with contextlib.ExitStack() as stack: + stack.enter_context(code.indent()) + kernel.gen_body(code) + + def get_reduction_prefix_suffix(kernel, parallel=False, is_suffix=False): + if is_suffix: + suffix = kernel.reduction_suffix + if parallel: + suffix = kernel.parallel_reduction_suffix + suffix + else: + suffix = kernel.non_parallel_reduction_suffix + suffix + return suffix + else: + prefix = kernel.reduction_prefix + if parallel: + prefix = prefix + kernel.parallel_reduction_prefix + else: + prefix = prefix + kernel.non_parallel_reduction_prefix + return prefix + + def gen_loop_with_reduction( + _loop_nest: LoopNest, depth: int = 0, in_reduction=False + ): + kernel = _loop_nest.get_kernel() + if not _loop_nest.loops: + raise AssertionError("expected _loop_nest.loops") + loop = _loop_nest.loops[depth] + with contextlib.ExitStack() as stack_outer: + if loop.is_reduction and not in_reduction: + reduction_prefix = get_reduction_prefix_suffix( + kernel, loop.parallel, is_suffix=False + ) + if reduction_prefix: + stack_outer.enter_context(code.indent()) + code.splice(reduction_prefix) + if is_reduction_loop and loop.parallel: + worksharing.parallel(threads) + if kernel.local_reduction_init: + if not kernel.local_reduction_stores: + raise AssertionError( + "expected kernel.local_reduction_stores" + ) + code.splice(kernel.local_reduction_init) + + gen_loop_at(_loop_nest, depth) + + if is_reduction_loop and loop.parallel: + if kernel.local_reduction_stores: + code.splice(kernel.local_reduction_stores) + worksharing.close() + if loop.is_reduction and not in_reduction: + code.splice( + get_reduction_prefix_suffix( + kernel, loop.parallel, is_suffix=True + ) + ) + + def gen_loop_at(_loop_nest: LoopNest, depth: int = 0): + with contextlib.ExitStack() as stack: + if not _loop_nest.loops: + raise AssertionError("expected _loop_nest.loops") + loop = _loop_nest.loops[depth] + loop_lines = loop.lines() + if loop_lines is None: + return + code.writelines(loop_lines) + stack.enter_context(code.indent()) + gen_loop_nest(_loop_nest, depth + 1, loop.is_reduction) + + def gen_loop_nest( + _loop_nest: LoopNest, + depth: int = 0, + in_reduction: bool = False, + ): + if _loop_nest.loops is None or depth == len(_loop_nest.loops): # type: ignore[arg-type] + gen_kernel(_loop_nest) + else: + gen_loop_with_reduction(_loop_nest, depth, in_reduction) + + stack.enter_context(code.indent()) + + if ( + isinstance(loop_nest.kernel, OuterLoopFusedKernel) + and isinstance(V.local_buffer_context, LocalBufferContext) + and V.local_buffer_context.local_buffers + ): + # Allocate local buffer + local_buffers = V.local_buffer_context.local_buffers + for local_buffer in local_buffers.values(): + # For dynamic size, rename s to ks + local_buf_size = sympy_product( + [ + self.rename_indexing(size_val) + for size_val in local_buffer.get_layout().size + ] + ) + local_buf_dtype = DTYPE_TO_CPP[local_buffer.get_layout().dtype] + allocate = f"std::make_unique<{local_buf_dtype} []>({cexpr(local_buf_size)})" + local_buffer_name = local_buffer.get_name() + code.splice( + f"std::unique_ptr<{local_buf_dtype} []> buf_{local_buffer_name} = {allocate};" + ) + code.splice( + f"{local_buf_dtype}* {local_buffer_name} = buf_{local_buffer_name}.get();" + ) + gen_loop_nest(loop_nest) + + def codegen_loops(self, code, worksharing): + loop_nest = LoopNest.build(self) + self.codegen_loops_impl(loop_nest, code, worksharing) + + @property + def assert_function(self) -> str: + if V.graph.aot_mode: + return "AOTI_TORCH_CHECK" + else: + return "TORCH_CHECK" + + def decide_parallel_depth(self, max_parallel_depth, threads): + if self.call_ranges is None: + raise AssertionError("expected self.call_ranges is not None") + ranges = self.call_ranges[ + max_parallel_depth.start_depth : ( + max_parallel_depth.start_depth + max_parallel_depth.parallel_depth + ) + ] + seq = self.size_hint() + par = 1 + depth = 0 + for expr in ranges: + hint = V.graph.sizevars.optimization_hint(expr, fallback=8192) + if par >= 2 * threads or par == threads: + break + if seq // threads < config.cpp.min_chunk_size: + # not enough work + break + depth += 1 + par *= hint + seq /= hint + # if we assume thread number is dynamic, make sure we + # have at least one parallel scope and let OMP runtime + # to manage the serial vs. parallel. + if config.cpp.dynamic_threads and depth == 0 and len(ranges) > 0: + depth = 1 + return ParallelDepth( + parallel_depth=depth, start_depth=max_parallel_depth.start_depth + ) + + @contextlib.contextmanager + def write_to_suffix(self): + prior = (self.loads, self.compute, self.stores, self.cse) + self.loads = IndentedBuffer() + self.compute = IndentedBuffer() + self.stores = IndentedBuffer() + self.cse = self.cse.clone() + yield + self.reduction_suffix.splice(self.loads) + self.reduction_suffix.splice(self.compute) + self.reduction_suffix.splice(self.stores) + (self.loads, self.compute, self.stores, self.cse) = prior + + def create_cse_var(self, *args, **kwargs): + return CppCSEVariable(*args, **kwargs) + + def get_to_dtype_expr(self, src, dtype, src_dtype, rounding=False): + if ( + rounding + and dtype in [torch.int8, torch.uint8] + and src_dtype in [torch.float, torch.double] + ): + return f"c10::convert<{DTYPE_TO_CPP[dtype]}>(std::round({src}))" + return f"c10::convert<{DTYPE_TO_CPP[dtype]}>({src})" + + def cache_dtype_convert(self, dst, dst_dtype, src, src_dtype): + expr = self.get_to_dtype_expr(src, dst_dtype, src_dtype) + self.cse.put(expr, dst) + + def codegen_conditions( + self, + code: BracesBuffer, + prefix: str | None = None, + var: sympy.Symbol | None = None, + ): + if prefix is None: + prefix = "" + if not self.active_ranges: + return True + conditions = [] + + def gen(start, end, var): + if start == end: + return False + var_id = None + for i, _var in enumerate(self.itervars): + if var == _var: + var_id = i + break + if ( + type(self) is CppKernel + and var_id + and start == 0 + and end == self.ranges[var_id] + ): + end = 1 + # pyrefly: ignore [bad-argument-type] + conditions.append(f"{var} >= {cexpr_index(start)}") + # pyrefly: ignore [bad-argument-type] + conditions.append(f"{var} < {cexpr_index(end)}") + return True + + if var is not None: + if var not in self.active_ranges: + raise AssertionError("expected var in self.active_ranges") + start, end = self.active_ranges[var] + if not gen(start, end, var): + return False + else: + for _var, _range in self.active_ranges.items(): + start, end = _range + if not gen(start, end, _var): + return False + joined_conditions = " && ".join(conditions) + if joined_conditions: + code.writeline(f"if({prefix}({joined_conditions}))") + return True + else: + return False + + +class CppVecKernel(CppKernel): + overrides = CppVecOverrides # type: ignore[assignment] + + def __init__( + self, + args, + num_threads, + tiling_factor, + tiling_idx, + tail_size=None, + ): + super().__init__(args, num_threads) + self.vec_isa = cpu_vec_isa.pick_vec_isa() + if not self.vec_isa: + raise AssertionError("expected self.vec_isa") + if tiling_factor <= 0: + raise AssertionError("Expect pass in Non-Zero tiling_factor explicitly") + self.tiling_factor = tiling_factor + self.tiling_idx = tiling_idx + self.tail_size = tail_size + self.num_elems = tail_size if tail_size else tiling_factor + + def _try_get_const_stride(self, index: sympy.Expr, itervar: sympy.Symbol): + if self.index_indirect_depends_on(index, itervar): + return None + for indirect_var in ( + self.cse.varname_map[s.name] # type: ignore[attr-defined] + for s in index.free_symbols + if symbol_is_type(s, SymT.TMP) + ): + if not isinstance(indirect_var, CppCSEVariable): + raise AssertionError( + "expected isinstance(indirect_var, CppCSEVariable)" + ) + if indirect_var.is_vec: + return None + stride = stride_at_vec_range(index, itervar, self.tiling_factor) + return stride if stride.is_number else None + + def _get_num_vectors(self, dtype: torch.dtype) -> int: + num_vectors = math.ceil( + self.tiling_factor * dtype.itemsize * 8 / self.vec_isa.bit_width() + ) + if num_vectors < 1: + raise AssertionError("expected num_vectors >= 1") + return num_vectors + + def _get_raw_num_vectors(self, dtype: torch.dtype) -> float: + # This utility function is used to check if the vector lanes has been + # fully utilized. For example, uint8 will only use 1/4 of the vector lanes. + return self.tiling_factor * dtype.itemsize * 8 / self.vec_isa.bit_width() + + def _get_vec_type(self, dtype: torch.dtype) -> str: + num_vectors = self._get_num_vectors(dtype) + if num_vectors == 1: + return f"at::vec::Vectorized<{DTYPE_TO_CPP[dtype]}>" + else: + return f"at::vec::VectorizedN<{DTYPE_TO_CPP[dtype]},{num_vectors}>" + + def _get_mask_type(self, dtype: torch.dtype = torch.float) -> str: + if dtype == torch.bool: + return "" + num_vectors = self._get_num_vectors(dtype) + return f"at::vec::VecMask<{DTYPE_TO_CPP[dtype]},{num_vectors}>" + + def _get_mask_cast(self, mask: CppCSEVariable, dtype: torch.dtype) -> str: + if mask.dtype != torch.bool: + raise AssertionError(repr(mask)) + num_vectors = self._get_num_vectors(dtype) + return f"{mask}.template cast<{DTYPE_TO_CPP[dtype]},{num_vectors}>()" + + def _get_vec_load_line( + self, + var: str, + index: sympy.Expr, + dtype: torch.dtype, + load_mask: CppCSEVariable | None = None, + ): + """ + Get a load line str that loads a vector from `var` at `index` of type `dtype`. + If `load_mask` is not None, we do a masked load accordingly. + Notes on the `dtype`: + 1. We always load `self.tiling_factor` number of elements regardless of the `dtype`. + It means we load half of the vector lanes for 16-bit data types and quarter of the + vector lanes for 8-bit data types. + 2. `torch.bool` and `torch.uint8` could mean masks and we load them as float mask vectors. + """ + cpp_type = DTYPE_TO_CPP[dtype] + num_vectors = self._get_num_vectors(dtype) + load_mask_str = None + if load_mask: + if not load_mask.is_vec: + # TODO: avoid hard-code torch.float + load_mask_str = f"{self._get_mask_type(torch.float)}::from({load_mask})" + else: + load_mask_str = f"{self._get_mask_cast(load_mask, torch.float)}" + loadbuf = f"{var} + {cexpr_index(index)}" if index != 0 else var + if dtype == torch.bool: + # TODO: should we consider load mask here? + line = f"{self._get_mask_type()}::from({loadbuf}, {cexpr_index(self.num_elems)})" + else: + line = ( + f"{load_mask_str}.template loadu<{cpp_type},{num_vectors}>({loadbuf})" + if load_mask_str + else f"{self._get_vec_type(dtype)}::loadu({loadbuf}, {cexpr_index(self.num_elems)})" + ) + return line + + def _load_or_store_non_contiguous( + self, + var: str | None, + index: sympy.Expr, + dtype: torch.dtype, + buffer: IndentedBuffer | None = None, + store_value: str | CppCSEVariable | None = None, + accu_store: bool = False, + ) -> CppCSEVariable | None: + """ + Load or store a vector in a non-contiguous way. The vector is initialized from an array that is + filled in an inner loop over the tiling factor. + :param var: buffer to load from or store to, i.e. `var[transformed(index)]`. If None, we load the index + as index expression, i.e. `transformed(index)`. + :param index: index into the `var` or the index expression by its own if `var` is None. + The `index` could contain indirect indexing or the tiling itervar. When used in + the inner loop, the index is transformed as follows: + 1. the index is linearized along the tiling dim. + 2. the indirect indexing vector variables are transformed into arrays over the tiling dim. + :param dtype: data type of `var` or `index` if `var` is None. + :param buffer: the code buffer to write the generated code to. If None, we write to `self.loads`. + :param store_value: the value to store. If None, we load the vector. + :param accu_store: whether accumulate the store_value to store_ptr. If True, a store_value should be provided + :return: a CppCSEVariable that represents the loaded vector or None if it is a store. + """ + if store_value and var is None: + raise AssertionError("store var must be provided") + if accu_store: + if not store_value: + raise AssertionError("expected store_value") + if buffer is None: + buffer = self.loads + + def get_result_size(dtype: torch.dtype) -> int: + if dtype.itemsize < 4: + return self.num_elems * (4 // dtype.itemsize) + else: + return self.num_elems + + def get_tiling_size(dtype: torch.dtype) -> int: + if dtype.itemsize < 4: + return self.tiling_factor * (4 // dtype.itemsize) + else: + return self.tiling_factor + + def vec_to_array(vec_var: CppCSEVariable) -> CppCSEVariable: + if not vec_var.is_vec: + raise AssertionError("expected vec_var.is_vec") + code = BracesBuffer() + code.writeline("[&]") + with code.indent(): + vec_dtype = vec_var.dtype + if vec_dtype is None: + raise AssertionError("expected vec_dtype is not None") + if vec_dtype == torch.bool: + vec_dtype = torch.float + result_size = get_result_size(vec_dtype) + tiling_size = get_tiling_size(vec_dtype) + code.writeline( + f"__at_align__ std::array<{DTYPE_TO_CPP[vec_dtype]}, {tiling_size}> tmpbuf;" + ) + line = f"{vec_var}.store(tmpbuf.data(), {cexpr_index(result_size)});" + code.writeline(line) + code.writeline("return tmpbuf;") + code.writeline("()") + csevar = self.cse.generate(buffer, code) + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + return csevar + + code = BracesBuffer() + code.writeline("[&]") + with code.indent(): + result_size = get_result_size(dtype) + tiling_size = get_tiling_size(dtype) + result_declare = ( + f"__at_align__ std::array<{DTYPE_TO_CPP[dtype]}, {tiling_size}> tmpbuf;" + ) + code.writeline(result_declare) + if store_value: + code.writeline( + f"{store_value}.store(tmpbuf.data(), {cexpr_index(result_size)});" + ) + itervar_inner = sympy_index_symbol( + f"{self.itervars[self.tiling_idx]}_inner" + ) + replacements = {} + for indirect_var in ( + self.cse.varname_map[s.name] # type: ignore[attr-defined] + for s in index.free_symbols + if symbol_is_type(s, SymT.TMP) + ): + if not isinstance(indirect_var, CppCSEVariable): + raise AssertionError( + "expected isinstance(indirect_var, CppCSEVariable)" + ) + if indirect_var.is_vec: + array_var = vec_to_array(indirect_var) + replacements[indirect_var] = f"{array_var}[{itervar_inner}]" + index = self.scale_index_with_offset( + index, itervar_idx=self.tiling_idx, offset=itervar_inner + ) + load_mask = None + if self._load_mask is not None: + if store_value: + raise AssertionError("unexpected store with load mask") + if not isinstance(self._load_mask, CppCSEVariable): + raise AssertionError(self._load_mask) + if self._load_mask.is_vec: + load_mask = f"{self._load_mask}.is_masked({itervar_inner})" + else: + load_mask = f"{self._load_mask} != 0" + if cpp_builder.is_gcc(): + code.writeline(f"#pragma GCC unroll {self.tiling_factor}") + else: + code.writeline(f"#pragma unroll {self.tiling_factor}") + code.writeline( + f"for (long {itervar_inner} = 0; " + + f"{itervar_inner} < {cexpr_index(self.num_elems)}; " + + f"{itervar_inner}++)" + ) + with code.indent(), contextlib.ExitStack() as stack: + index_c = cexpr_index(index) + # pyrefly: ignore [bad-assignment] + for indirect_var in replacements: + index_c = re.sub( + r"\b" + f"{indirect_var}" + r"\b", + replacements[indirect_var], + index_c, + ) + rhs = f"{var}[{index_c}]" if var is not None else f"{index_c}" + if load_mask: + code.writeline(f"if ({load_mask})") + stack.enter_context(code.indent()) + if store_value: + conjunction = "+=" if accu_store else "=" + code.writeline(f"{rhs} {conjunction} tmpbuf[{itervar_inner}];") + else: + code.writeline(f"tmpbuf[{itervar_inner}] = {rhs};") + if not store_value: + load_line = self._get_vec_load_line("tmpbuf.data()", 0, dtype) # type: ignore[arg-type] + code.writeline(f"return {load_line};") + code.writeline("()") + if store_value: + code.writeline(";") + buffer.splice(code) + return None + else: + csevar = self.cse.generate(buffer, code, dtype=dtype) + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + csevar.is_vec = True + return csevar + + def load(self, name: str, index: sympy.Expr): + var = self.args.input(name) + index = self.rename_indexing(index) + dtype = V.graph.get_dtype(name) + tiling_var = self.itervars[self.tiling_idx] + stride = self._try_get_const_stride(index, tiling_var) + if stride == 0: + # load scalar and lazily broadcast it on demand + return super().load(name, index) + elif stride == 1: + # load contiguously + line = self._get_vec_load_line(var, index, dtype, self._load_mask) # type: ignore[arg-type] + csevar = self.cse.generate(self.loads, line, dtype=dtype) # type: ignore[assignment] + else: + csevar = self._load_or_store_non_contiguous(var, index, dtype) # type: ignore[assignment] + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + csevar.update_on_args("load", (self, name, index), {}) + csevar.is_vec = True + return csevar + + def _get_store_line( + self, + value: str | CppCSEVariable, + var: str, + index: sympy.Expr, + dtype: torch.dtype, + accu_store: bool = False, + ): + """ + Get a store line buffer that stores `value` into `var` at `index` of `dtype`. It handles + both contiguous and non-contiguous store cases. + :param value: Vectorized type templaterized on `dtype`. + :param var: buffer to store into. + :index: index into the `var`. + """ + # when value's type is str (e.g., welford reduction), caller should make sure + # it is a vector + if not ( + isinstance(value, str) + or (isinstance(value, CppCSEVariable) and value.is_vec) + ): + raise AssertionError(value) + tiling_var = self.itervars[self.tiling_idx] + var_expr = f"{var} + {cexpr_index(index)}" + stride = self._try_get_const_stride(index, tiling_var) + code = IndentedBuffer() + if stride == 1: + if accu_store: + load = ( + f"{self._get_vec_type(dtype)}::loadu({var_expr})" + if dtype == torch.float and self.tail_size is None + else f"{self._get_vec_type(dtype)}::loadu({var_expr}, {cexpr_index(self.num_elems)})" + ) + value = f"({value} + {load})" + if dtype == torch.float and self.tail_size is None: + code.writeline(f"{value}.store({var_expr});") + else: + code.writeline( + f"{value}.store({var_expr}, {cexpr_index(self.num_elems)});" + ) + else: + self._load_or_store_non_contiguous( + var, index, dtype, buffer=code, store_value=value, accu_store=accu_store + ) + return code + + def store(self, name, index, value, mode=None): + if "buf" not in name: + raise AssertionError('expected "buf" in name') + if not isinstance(value, CppCSEVariable): + raise AssertionError(value) + if not value.is_vec: + # this happens when we store a scalar into a vectorized buffer like "fill" + value = self.broadcast(value) + var = self.args.output(name) + index = self.rename_indexing(index) + dtype = V.graph.get_dtype(name) + if mode is None: + code = self._get_store_line(value, var, index, dtype) + self.stores.splice(code.map(lambda x: DeferredLine(name, x))) + elif mode == "atomic_add": + if not self._use_parallel_atomic_add(): + code = self._get_store_line( + f"{value}", + var, + index, + dtype, + accu_store=True, + ) + self.stores.splice(code.map(lambda x: DeferredLine(name, x))) + else: + n_src = self._get_num_vectors(dtype) + n_idx = self._get_num_vectors(torch.int64) + cdtype = DTYPE_TO_CPP[dtype] + # ops.index_expr re-applies subclass index transforms, so a caller + # that already transformed must pass the untransformed index + index = ops.index_expr(index, torch.int64).value + if isinstance(index, CppCSEVariable) and not index.is_vec: + index = self.broadcast(index) + if not (isinstance(index, CppCSEVariable) and index.is_vec): + raise AssertionError( + "expected isinstance(index, CppCSEVariable) and index.is_vec" + ) + if self.tail_size: + line = f"atomic_add_vec<{cdtype}, {n_idx}, {n_src}>({var}, {index}, {value}, {cexpr_index(self.tail_size)});" + else: + line = f"atomic_add_vec<{cdtype}, {n_idx}, {n_src}>({var}, {index}, {value});" + self.stores.writeline(DeferredLine(name, line)) + else: + raise NotImplementedError(f"store mode={mode}") + + def _adjust_argreduce_index(self, index: sympy.Expr) -> sympy.Expr: + return index + + def reduction(self, dtype, src_dtype, reduction_type, value): + """ + Perform vectorized reduction operation. + + This method handles vectorized reduction for different reduction types. + It manages special cases for low-precision floating point types and + employs precision improvement techniques for certain reduction operations. + + Args: + dtype: The output data type for the reduction result + src_dtype: The source data type of the input value + reduction_type: Type of reduction operation (sum, min, max, etc.) + value: The input value to reduce + + Returns: + The result of the reduction operation + """ + # Note: For argmax and argmin on bool type, we always convert bool to float. + # Fix issue: https://github.com/pytorch/pytorch/issues/143568 + if reduction_type not in VECTORIZABLE_RTYPES: + raise AssertionError("expected reduction_type in VECTORIZABLE_RTYPES") + argmax_or_argmin = reduction_type in ("argmax", "argmin") + logical_index = None + if argmax_or_argmin and isinstance(value, tuple): + value, logical_index = value + + horizontal_reduction = self.tiling_idx >= self.reduction_depth + init_dtype = src_dtype if argmax_or_argmin else dtype + if not isinstance(value, CppCSEVariable): + raise AssertionError(value) + if not isinstance(logical_index, (CppCSEVariable, type(None))): + raise AssertionError(logical_index) + + if not value.is_vec: + value = self.broadcast(value) + + if logical_index is not None: + logical_index_key = cast(CppCSEVariable, logical_index) + reduction_key = src_dtype, reduction_type, (value, logical_index_key) + else: + reduction_key = src_dtype, reduction_type, value + if reduction_key in self.reduction_cse.reduction_cache: + return self.reduction_cse.reduction_cache[reduction_key] + + vec_ns = "at::vec" + vec = f"{vec_ns}::Vectorized<{DTYPE_TO_CPP[dtype]}>" + acc_type = reduction_acc_type(reduction_type, init_dtype) + acc_type_vec = self.reduction_acc_type_vec(reduction_type, init_dtype) + + acc = self.reduction_cse.generate( + self.loads, f"reduction {reduction_key}", write=False + ) + if not isinstance(acc, CppCSEVariable): + raise AssertionError("expected isinstance(acc, CppCSEVariable)") + acc_vec = f"{acc}_vec" + masked_acc = f"masked_{acc}" + masked_acc_vec = f"masked_{acc_vec}" + self.reduction_var_names += [f"{acc}", acc_vec, masked_acc_vec] + self.is_reduction = True + self.reduction_prefix_generators.append( + self._gen_reduction_prefix( + acc, acc_type, reduction_type, init_dtype, reduction_init + ) + ) + self.reduction_prefix_generators.append( + self._gen_reduction_prefix( + acc_vec, + acc_type_vec, + reduction_type, + init_dtype, + self.reduction_init_vec, + ) + ) + + use_acc_helper = self.need_use_acc_helper(reduction_type, dtype, False) + if use_acc_helper: + if logical_index is not None: + raise AssertionError(logical_index) + # use masked acc_vec for tail vec kernel + self.reduction_prefix_generators.append( + self._gen_reduction_prefix( + masked_acc_vec, + acc_type_vec, + reduction_type, + dtype, + self.reduction_init_vec, + ) + ) + + # use welford_helper/cascade_helper for vec kernel + if self.reduction_depth is None: + raise AssertionError("expected self.reduction_depth is not None") + reduction_size = functools.reduce( + operator.mul, self.ranges[self.reduction_depth :] + ) + if reduction_type == "welford_reduce": + helper_val = self.welford_helper_cse.generate( + self.compute, f"reduction {reduction_key}", write=False + ) + else: + helper_val = self.cascade_helper_cse.generate( + self.compute, f"reduction {reduction_key}", write=False + ) + masked_helper_val = f"masked_{helper_val}" + helper_vec_range = ( + ( + FloorDiv(reduction_size, self.ranges[self.tiling_idx]) + * FloorDiv(self.ranges[self.tiling_idx], self.tiling_factor) + if self.tiling_idx >= self.reduction_depth + else reduction_size + ) + if FloorDiv(self.ranges[self.tiling_idx], self.tiling_factor) + else sympy.Integer(0) + ) + masked_helper_vec_range = ( + ( + FloorDiv(reduction_size, self.ranges[self.tiling_idx]) + if self.tiling_idx >= self.reduction_depth + else reduction_size + ) + if self.ranges[self.tiling_idx] % self.tiling_factor + else sympy.Integer(0) + ) + # scalar helper for scalar welford_reduce/sum is also needed when vec kernel is included + scalar_helper_val = f"scalar_{helper_val}" + self._use_acc_helper( + reduction_type, + acc, + scalar_helper_val, + reduction_size, + dtype, + use_scalar=True, + ) + self._use_acc_helper( + reduction_type, acc, helper_val, helper_vec_range, dtype + ) + self._use_acc_helper( + reduction_type, + masked_acc, + masked_helper_val, + masked_helper_vec_range, + dtype, + ) + + # use masked acc_vec for tail vec kernel + acc_vec_ = masked_acc_vec if self.tail_size else acc_vec + helper_val_ = masked_helper_val if self.tail_size else helper_val + if reduction_type == "sum": + self.stores.writeline( + f"{acc_vec_} = {self.reduction_combine_vec(reduction_type, acc_vec_, value, helper_val_)};" + ) + else: + self.stores.writeline( + f"{acc_vec_} = {self.reduction_combine_vec(reduction_type, acc_vec_, value, helper_val_)};" + ) + else: + if logical_index is not None: + index = logical_index + index_horizontal_reduction = False + else: + if self.reduction_depth is None: + raise AssertionError("expected self.reduction_depth is not None") + index = self.itervars[self.reduction_depth] + for i in range(self.reduction_depth + 1, len(self.itervars)): + index = index * self.ranges[i] + self.itervars[i] + index_horizontal_reduction = horizontal_reduction + kwargs = { + "next_value": value, + "index": index, + "horizontal_reduction": index_horizontal_reduction, + "src_dtype": src_dtype, + } + self.stores.writeline( + f"{acc_vec} = {self.reduction_combine_vec(reduction_type, acc_vec, **kwargs)};" + ) + self._gen_parallel_reduction_buffers( + acc_vec, + acc_type_vec, + reduction_type, + init_dtype, + reduction_combine_fn=self.reduction_combine_vec, + reduction_init_fn=self.reduction_init_vec, + ) + self._gen_parallel_reduction_buffers( + acc, + acc_type, + reduction_type, + init_dtype, + reduction_combine_fn=reduction_combine, + reduction_init_fn=reduction_init, + ) + if use_acc_helper: + # use masked acc_vec for tail vec kernel + self._gen_parallel_reduction_buffers( + masked_acc_vec, + acc_type_vec, + reduction_type, + dtype, + reduction_combine_fn=self.reduction_combine_vec, + reduction_init_fn=self.reduction_init_vec, + ) + tmpvar: str | CSEVariable + is_bool = dtype == torch.bool + if horizontal_reduction: + # Horizontal reduction + if is_welford_reduction(reduction_type): + if self._get_num_vectors(dtype) not in [ + 1, + 2, + ]: + raise AssertionError( + "Welford reduction does not support VectorizedN (N>2)" + ) + next_value = f"welford_vec_reduce_all({acc_vec})" + masked_next_value = f"welford_vec_reduce_all({masked_acc_vec})" + self.reduction_suffix.writeline( + f"{acc} = {reduction_combine(reduction_type, acc, masked_next_value)};" + ) + elif argmax_or_argmin: + next_value = f"{reduction_type}_vec_reduce_all({acc_vec})" + elif is_bool: + if reduction_type in ( + "any", + "sum", + "max", + ): + next_value = f"!{acc_vec}.all_zero()" + else: + if reduction_type != "min": + raise AssertionError('expected reduction_type == "min"') + next_value = f"{acc_vec}.all_masked()" + else: + reduce_all_body = ( + "{ return " + + self.reduction_combine_vec(reduction_type, "x", "y") + + "; }" + ) + is_bool = dtype == torch.bool + # we are using at::vec::VecMask for bool + vec_dtype = torch.float if is_bool else dtype + vec = f"at::vec::Vectorized<{DTYPE_TO_CPP[vec_dtype]}>" + vec_reduce_all_func = f"at::vec::vec_reduce_all<{DTYPE_TO_CPP[vec_dtype]}, {self._get_num_vectors(vec_dtype)}>" + result_vec = f"{acc_vec}" + if use_acc_helper: + if reduction_type != "sum": + raise AssertionError('expected reduction_type == "sum"') + result_vec = f"{acc_vec} + {masked_acc_vec}" + next_value = f"{vec_reduce_all_func}([]({vec}& x, {vec}& y) {reduce_all_body}, {result_vec})" + + self.reduction_suffix.writeline( + f"{acc} = {reduction_combine(reduction_type, acc, next_value, src_dtype=src_dtype)};" + ) + tmpvar = acc + else: + tmpvar = acc_vec + if is_welford_reduction(reduction_type): + masked_tmpvar = f"masked_{tmpvar}" + self.reduction_suffix.writeline( + f"{tmpvar} = {reduction_combine(reduction_type, tmpvar, masked_tmpvar)};" + ) + elif use_acc_helper: + if reduction_type != "sum": + raise AssertionError('expected reduction_type == "sum"') + masked_tmpvar = f"masked_{tmpvar}" + self.reduction_suffix.writeline( + f"{tmpvar} = {tmpvar} + {masked_tmpvar};" + ) + + result = reduction_project(reduction_type, tmpvar) + self.reduction_cse.reduction_cache[reduction_key] = result + return result + + def store_reduction(self, name, index, value): + index = self.rename_indexing(index) + var = self.args.output(name) + out_dtype = V.graph.get_dtype(name) + if out_dtype.is_floating_point and out_dtype != torch.double: + dtype = torch.float + else: + dtype = out_dtype + out_num_vectors = V.kernel._get_num_vectors(out_dtype) + src_num_vectors = V.kernel._get_num_vectors(dtype) + code = IndentedBuffer() + if self.tiling_idx >= self.reduction_depth: + # Horizontal reduction + code.writeline( + f"{var}[{cexpr_index(index)}] = static_cast<{DTYPE_TO_CPP[out_dtype]}>({value});" + ) + else: + # Vertical reduction + if out_dtype != dtype: + converted_value = ( + f"{DTYPE_TO_CPP[out_dtype].replace('::', '_')}_{value}" + ) + if out_dtype == torch.bool: + convert = f"{value}.template cast()" + else: + if src_num_vectors == out_num_vectors == 1: + convert = ( + f"at::vec::convert<{DTYPE_TO_CPP[out_dtype]}>({value})" + ) + else: + convert = ( + f"at::vec::convert<{DTYPE_TO_CPP[out_dtype]}," + f"{out_num_vectors},{DTYPE_TO_CPP[dtype]},{src_num_vectors}>({value})" + ) + code.writeline(f"auto {converted_value} = {convert};") + value = converted_value + code.splice(self._get_store_line(value, var, index, out_dtype)) + self.reduction_suffix.splice(code.map(lambda x: DeferredLine(name, x))) + + def broadcast(self, scalar_var: CppCSEVariable) -> CppCSEVariable: + if scalar_var.is_vec: + raise AssertionError("expected not scalar_var.is_vec") + if scalar_var.dtype == torch.bool: + vec_var = self.cse.generate( + self.compute, f"{self._get_mask_type()}::from({scalar_var.name})" + ) + else: + if scalar_var.dtype is None: + raise AssertionError("expected scalar_var.dtype is not None") + vec_var = self.cse.generate( + self.compute, + f"{self._get_vec_type(scalar_var.dtype)}({scalar_var.name})", + ) + if not isinstance(vec_var, CppCSEVariable): + raise AssertionError("expected isinstance(vec_var, CppCSEVariable)") + vec_var.dtype = scalar_var.dtype + vec_var.dependent_itervars = scalar_var.dependent_itervars + vec_var.is_vec = True + return vec_var + + def arange(self, index: CppCSEVariable, stride: sympy.Symbol) -> CppCSEVariable: + if index.is_vec: + raise AssertionError("expected not index.is_vec") + if index.dtype is None: + raise AssertionError("expected index.dtype is not None") + csevar = self.cse.generate( + self.compute, + f"{self._get_vec_type(index.dtype)}::arange({index}, {stride})", + ) + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + csevar.dtype = index.dtype + csevar.is_vec = True + return csevar + + def reduction_init_vec(self, reduction_type, dtype): + scalar_type = DTYPE_TO_COMPUTATION_DTYPE[dtype] + vec_type = self._get_vec_type(scalar_type) + + if is_welford_reduction(reduction_type): + return f"Welford<{vec_type}>()" + + if reduction_type in ("argmin", "argmax"): + # For bool argmin/argmax, we use float for computations + compute_dtype = torch.float if dtype == torch.bool else scalar_type + cdtype = DTYPE_TO_CPP[compute_dtype] + acc_type = self.reduction_acc_type_vec(reduction_type, dtype) + if reduction_type == "argmin": + val = ( + f"std::numeric_limits<{cdtype}>::infinity()" + if is_float_dtype(dtype) or dtype == torch.bool + else f"std::numeric_limits<{cdtype}>::max()" + ) + else: + val = ( + f"-std::numeric_limits<{cdtype}>::infinity()" + if is_float_dtype(dtype) or dtype == torch.bool + else f"std::numeric_limits<{cdtype}>::min()" + ) + return f"{acc_type}({val})" + + if reduction_type == "any": + return f"{self._get_mask_type()}::from(0)" + + scalar_init = reduction_init(reduction_type, dtype) + vec_init = f"{vec_type}({scalar_init})" + if dtype == torch.bool: + if reduction_type not in ("min", "max", "sum"): + raise AssertionError('expected reduction_type in ("min", "max", "sum")') + return f"{self._get_mask_type()}::from({scalar_init})" + return vec_init + + def reduction_acc_type_vec(self, reduction_type, dtype): + scalar_type = DTYPE_TO_COMPUTATION_DTYPE[dtype] + vec_type = self._get_vec_type(scalar_type) + if is_welford_reduction(reduction_type): + return f"Welford<{vec_type}>" + if reduction_type in ("argmin", "argmax"): + n_idx = self._get_num_vectors(torch.int64) + if dtype == torch.bool: + # For bool argmin/argmax, we use float for computations + # so n_src must be computed from float, not bool + n_src = self._get_num_vectors(torch.float) + return f"IndexValueVec<{DTYPE_TO_CPP[torch.float]}, {n_src}, {n_idx}>" + n_src = self._get_num_vectors(scalar_type) + return f"IndexValueVec<{DTYPE_TO_CPP[scalar_type]}, {n_src}, {n_idx}>" + if dtype == torch.bool: + if reduction_type not in ("min", "max", "any", "sum"): + raise AssertionError( + 'expected reduction_type in ("min", "max", "any", "sum")' + ) + return f"{self._get_mask_type()}" + return vec_type + + def reduction_combine_vec( + self, + reduction_type, + var, + next_value, + helper_val=None, + index: sympy.Expr | CppCSEVariable | None = None, + horizontal_reduction: bool | None = None, + src_dtype: torch.dtype | None = torch.float32, + ): + """Emit the C++ expression for combining vector reduction values.""" + is_bool = src_dtype == torch.bool + if reduction_type == "max": + if self.tail_size: + return f"max_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return ( + f"{var} | {next_value}" + if is_bool + else f"at::vec::maximum({var}, {next_value})" + ) + elif reduction_type == "min": + if self.tail_size: + return f"min_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return ( + f"{var} & {next_value}" + if is_bool + else f"at::vec::minimum({var}, {next_value})" + ) + elif reduction_type == "sum": + if helper_val: + if self.tail_size: + return f"cascade_sum_combine({next_value}, {cexpr_index(self.tail_size)}, &{helper_val})" + else: + return f"cascade_sum_combine({next_value}, &{helper_val})" + else: + if self.tail_size: + return f"sum_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + conjunction = "|" if is_bool else "+" + return f"{var} {conjunction} {next_value}" + elif reduction_type == "prod": + if self.tail_size: + return f"prod_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return f"{var} * {next_value}" + elif reduction_type == "xor_sum": + if self.tail_size: + return f"xor_sum_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return f"{var} ^ {next_value}" + elif reduction_type == "welford_reduce": + if helper_val: + if self.tail_size: + return f"welford_combine({var}, {next_value}, {cexpr_index(self.tail_size)}, &{helper_val})" + else: + return f"welford_combine({var}, {next_value}, &{helper_val})" + else: + if self.tail_size: + return f"welford_combine({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return f"welford_combine({var}, {next_value})" + elif reduction_type == "welford_combine": + if isinstance(next_value, tuple): + # When reading a value from Inductor IR we have a tuple of variable names + mean, m2, weight = next_value + else: + # When combining intermediate accumulators we have a Welford struct + mean, m2, weight = reduction_project(reduction_type, next_value) + if self.tail_size: + return f"welford_combine({var}, {{{mean}, {m2}, {weight}}}, {cexpr_index(self.tail_size)})" + else: + return f"welford_combine({var}, {{{mean}, {m2}, {weight}}})" + elif reduction_type in ("argmin", "argmax"): + if src_dtype is None: + raise AssertionError("expected src_dtype is not None") + cdtype = DTYPE_TO_CPP[src_dtype] + compute_dtype = src_dtype + if src_dtype == torch.bool: + # For bool argmin/argmax, we use float for computations + cdtype = DTYPE_TO_CPP[torch.float] + compute_dtype = torch.float + # Convert bool VecMask to float vector for argmax_combine_vec + if isinstance(next_value, CppCSEVariable) and next_value.is_vec: + (next_value,) = unify_mask_base_type(self.compute, (next_value,)) + n_src = self._get_num_vectors(compute_dtype) + n_idx = self._get_num_vectors(torch.int64) + t_extra = "" + arg_extra = "" + if index is not None: + if isinstance(index, CppCSEVariable): + if index.is_vec: + arg_extra = f", {index}" + else: + t_extra = ", false" + arg_extra = f", {index}" + else: + if horizontal_reduction is None: + raise AssertionError( + "expected horizontal_reduction is not None" + ) + t_extra = f", {str(horizontal_reduction).lower()}" + arg_extra = f", {self._adjust_argreduce_index(index)}" + if self.tail_size: + return ( + f"{reduction_type}_combine_vec<{cdtype}, {n_src}, {n_idx}{t_extra}>" + f"({var}, {next_value}{arg_extra}, {cexpr_index(self.tail_size)})" + ) + else: + return f"{reduction_type}_combine_vec<{cdtype}, {n_src}, {n_idx}{t_extra}>({var}, {next_value}{arg_extra})" + elif reduction_type == "any": + if isinstance(next_value, CppCSEVariable): + if next_value.dtype != torch.bool: + raise AssertionError("expected next_value.dtype == torch.bool") + (next_value,) = unify_mask_base_type(V.kernel.compute, (next_value,)) + if self.tail_size: + return f"any_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return f"{var} | {next_value}" + else: + raise NotImplementedError + + def indirect_assert(self, var, lower, upper, mask=None): + if not isinstance(var, CppCSEVariable): + raise AssertionError("expected isinstance(var, CppCSEVariable)") + if var.dtype is None: + raise AssertionError("expected var.dtype is not None") + if not var.is_vec: + if isinstance(mask, CppCSEVariable) and mask.is_vec: + mask = f"({mask}).all_masked()" + return super().indirect_assert(var, lower, upper, mask) + lower_scalar = lower + upper_scalar = upper + if lower: + lower = f"{self._get_vec_type(var.dtype)}({lower})" + if upper: + upper = f"{self._get_vec_type(var.dtype)}({upper})" + if lower and upper: + cond = f"({lower} <= {var}) & ({var} < {upper})" + cond_print = f"{lower_scalar} <= {var} < {upper_scalar}" + elif lower: + cond = f"{lower} <= {var}" + cond_print = f"{lower_scalar} <= {var}" + else: + if not upper: + raise AssertionError("expected upper") + cond = f"{var} < {upper}" + cond_print = f"{var} < {upper_scalar}" + cond = f"{self._get_mask_type(var.dtype)}({cond})" + if mask: + if not mask.is_vec: + mask = f"{self._get_mask_type(var.dtype)}::from({mask})" + # We need not check when the mask is False + cond = f"({cond}) | ~({mask})" + if self.tail_size: + cond = ( + f"{self._get_mask_type(var.dtype)}::set({self._get_mask_type(var.dtype)}::from(1)" + f", ({cond}), {cexpr_index(self.tail_size)})" + ) + cond = f"({cond}).all_masked()" + return f'{self.assert_function}({cond}, "index out of bounds: {cond_print}")' + + def get_to_dtype_expr(self, src, dtype, src_dtype, rounding=False): + if not isinstance(src, CppCSEVariable): + raise AssertionError("expected isinstance(src, CppCSEVariable)") + if not src.is_vec: + return super().get_to_dtype_expr(src, dtype, src_dtype, rounding) + src_cpp_type = DTYPE_TO_CPP[src_dtype] + src_num_vectors = self._get_num_vectors(src_dtype) + dst_cpp_type = DTYPE_TO_CPP[dtype] + dst_num_vectors = self._get_num_vectors(dtype) + expr = f"({src})" + if src_dtype != torch.bool and dtype == torch.bool: + expr = f"{self._get_mask_type(src_dtype)}::from<{src_cpp_type},{src_num_vectors}>({src})" + elif src_dtype == torch.bool and dtype != torch.bool: + expr = f"{src}.to<{dst_cpp_type},{dst_num_vectors}>()" + elif src_dtype != dtype: + expr = "" + if ( + rounding + and src_dtype in [torch.float, torch.double] + and dtype in [torch.int8, torch.uint8] + ): + expr = "at::vec::round_convert" + else: + expr = "at::vec::convert" + if src_num_vectors == dst_num_vectors == 1: + expr = expr + f"<{dst_cpp_type}>({src})" + else: + expr = ( + expr + + f"<{dst_cpp_type},{dst_num_vectors},{src_cpp_type},{src_num_vectors}>({src})" + ) + return expr + + +class CppTile2DKernel(CppVecKernel): + """ + A vector kernel that handles the 2d tiles with the tile size defined in `tiling_factor` on + the inner-most loop level and one of the outer loop level (`outer_tiling_idx`). When the data + tile is accessed in a contiguous way from the outer loop axis, a transposition is applied on the + tile to make the access contiguous from the inner-most loop axis. Then, the same vectorization + logic from its parent `CppVecKernel` is leveraged for load/store/compute. The transposed tile load + and store are generated into kernel.preloads and kernel.poststores buffers. + + The loop structure looks like below: + for ... + for i_outer ... + for ... + for inner_most ... + // generated by CppTile2DKernel + float tmp0[16*16]; at::vec::transpose_mxn<...>(tmp0, in_ptr0 + ..., ...); // into kernel.preloads + float tmp1[16*16]; // into kernel.preloads + for i_inner ... { // the kernel inner loop + vectorized loads/compute/stores (e.g., load tmp0, store tmp1) // into kernel.loads/compute/stores + } + at::vec::transpose_mxn(out_ptr0 + ..., tmp1, ...) // into kernel.poststores + for inner_most ... (tail) + // generated by CppVecKernel + ... + for i_outer ... (tail) + for ... + for ... + // generated by CppKernel + ... + """ + + overrides = CppTile2DOverrides # type: ignore[assignment] + + def __init__( + self, + args, + num_threads, + tiling_factor, + tiling_indices, + inner_tail_size=None, + outer_tail_size=None, + ): + super().__init__( + args, + num_threads, + tiling_factor, + tiling_indices[1], + inner_tail_size, + ) + self.tiling_indices = tiling_indices + self.inner_tail_size = inner_tail_size + self.outer_tail_size = outer_tail_size + self.inner_num_elems = inner_tail_size if inner_tail_size else tiling_factor + self.outer_num_elems = outer_tail_size if outer_tail_size else tiling_factor + self.inner_is_tiling_idx = True + + def inner_itervar(self): + return sympy_index_symbol(f"{self.itervars[self.outer_idx]}_inner") + + def need_vec_transpose(self, index): + outer_var = self.itervars[self.outer_idx] + inner_var = self.itervars[self.tiling_idx] + # Indirect indexing (SymT.TMP) variables are declared inside the inner + # loop, but transpose_mxn is emitted into preloads (before the loop). + if free_symbol_is_type(index, SymT.TMP): + return False + outer_stride = stride_at_vec_range(index, outer_var, self.tiling_factor) + inner_stride = stride_at_vec_range(index, inner_var, self.tiling_factor) + return ( + self._load_mask is None # TODO: support transposition with mask + and outer_stride == 1 + and index.has(inner_var) + and not inner_stride.has(inner_var) + and not inner_stride.has(outer_var) + ) + + def gen_transposed_tile_load_store( + self, name, var, index, is_store, store_mode=None + ): + # transposed tile load/store outside the kernel inner loop + dtype = V.graph.get_dtype(name) + factor = self.tiling_factor + src = f"{var} + {cexpr_index(index)}" + dst = "__place_holder__" + ld_src = f"{cexpr_index(stride_at_vec_range(index, self.itervars[self.tiling_idx], self.tiling_factor))}" + ld_dst = f"{cexpr_index(self.num_elems)}" + if is_store: + src, dst = dst, src + ld_src, ld_dst = ld_dst, ld_src + + need_define = True + if self.inner_is_tiling_idx ^ is_store: + M, N = self.inner_num_elems, self.outer_num_elems + else: + M, N = ( + self.outer_num_elems, + self.inner_num_elems, + ) + atomic_add = "true" if (is_store and (store_mode == "atomic_add")) else "false" + if (isinstance(M, sympy.Expr) and not M.is_number) or ( + isinstance(N, sympy.Expr) and not N.is_number + ): + load_or_store = ( + f"transpose_mxn<{DTYPE_TO_CPP[dtype]},{atomic_add}>" + f"({src}, {ld_src}, {dst}, {ld_dst}, {cexpr_index(M)}, {cexpr_index(N)});" + ) + else: + load_or_store = ( + f"transpose_mxn<{DTYPE_TO_CPP[dtype]},{cexpr_index(M)},{cexpr_index(N)},{atomic_add}>" + f"({src}, {ld_src}, {dst}, {ld_dst});" + ) + if is_store: + tile_var = self.cse.newvar() + elif not self.cse.contains(load_or_store): + tile_var = self.cse.generate(self.preloads, load_or_store, write=False) + else: + need_define = False + tile_var = self.cse.get(load_or_store) + + if need_define: + cpp_dtype = DTYPE_TO_CPP[dtype] + # tiling_factor might be smaller than the alignment of cpp_dtype, such as + # with a vector that only holds 4 elements due to NEON 128-bit vectors and + # cpp_dtype being a 64-bit integer. + alignas = f"alignas(std::max(std::size_t({factor}), alignof({cpp_dtype})))" + define_line = f"{alignas} {cpp_dtype} {tile_var}[{factor}*{factor}];" + self.preloads.writeline(define_line) + + load_or_store = load_or_store.replace("__place_holder__", str(tile_var)) + if is_store: + self.poststores.writeline(DeferredLine(name, load_or_store)) + else: + self.preloads.writeline(load_or_store) + + return tile_var + + def load(self, name: str, index: sympy.Expr): + var = self.args.input(name) + index = self.rename_indexing(index) + + inner = self.inner_itervar() + if self.need_vec_transpose(index): + tile_var = self.gen_transposed_tile_load_store( + name, var, index, is_store=False + ) + # vector load inside the kernel inner loop + loadbuf = f"{tile_var} + {cexpr_index(inner * self.num_elems)}" + dtype = V.graph.get_dtype(name) + line = self._get_vec_load_line(loadbuf, 0, dtype) # type: ignore[arg-type] + csevar = self.cse.generate(self.loads, line, dtype=dtype) + csevar.update_on_args("load", (self, name, index), {}) + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + csevar.is_vec = True + return csevar + else: + new_index = self.transform_indexing(index) + return super().load(name, new_index) + + def store(self, name, index, value, mode=None): + if "buf" not in name: + raise AssertionError('expected "buf" in name') + if not isinstance(value, CppCSEVariable): + raise AssertionError(value) + if not value.is_vec: + # this happens when we store a scalar into a vectorized buffer like "fill" + value = self.broadcast(value) + + var = self.args.output(name) + + inner = self.inner_itervar() + index = self.rename_indexing(index) + if self.need_vec_transpose(index): + tile_var = self.gen_transposed_tile_load_store( + name, var, index, is_store=True, store_mode=mode + ) + # vector store inside the kernel inner loop + storebuf = f"{tile_var} + {cexpr_index(inner * self.num_elems)}" + if self.tail_size or V.graph.get_dtype(name) in DTYPE_LOWP_FP + [ + torch.uint8, + torch.int8, + torch.float8_e4m3fn, + torch.float8_e5m2, + ]: + line = f"{value}.store({storebuf}, {cexpr_index(self.num_elems)});" + else: + line = f"{value}.store({storebuf});" + self.stores.writeline(DeferredLine(name, line)) + else: + # the parallel atomic_add path re-applies transform_indexing via ops.index_expr + vec_atomic_add = mode == "atomic_add" and self._use_parallel_atomic_add() + new_index = index if vec_atomic_add else self.transform_indexing(index) + super().store(name, new_index, value, mode) + + def codegen_inner_loops(self, code): + inner = self.inner_itervar() + if self.inner_is_tiling_idx: + code.writeline( + f"for (long {inner} = 0; {inner} < {cexpr_index(self.outer_num_elems)}; {inner}++)" + ) + else: + code.writeline( + f"for (long {inner} = 0; {inner} < {cexpr_index(self.inner_num_elems)}; {inner}++)" + ) + + def set_ranges(self, group, reduction_group): + vars = super().set_ranges(group, reduction_group) + # do vertical reduction as the tail loop + self.outer_idx, self.tiling_idx = ( + self.tiling_indices + if self.tiling_indices[1] < self.reduction_depth + else reversed(self.tiling_indices) + ) + if self.tiling_idx == self.tiling_indices[0]: + self.tail_size = self.outer_tail_size + self.num_elems = self.outer_num_elems + self.inner_is_tiling_idx = False + else: + self.tail_size = self.inner_tail_size + self.num_elems = self.inner_num_elems + self.inner_is_tiling_idx = True + return vars + + def transform_indexing(self, index: sympy.Expr) -> sympy.Expr: + return self.scale_index_with_offset( + index, + itervar_idx=self.outer_idx, + offset=self.inner_itervar(), + ) + + def _adjust_argreduce_index(self, index: sympy.Expr) -> sympy.Expr: + return self.transform_indexing(index) + + +def get_loop_body_lowp_fp(_body: LoopBody) -> tuple[torch.dtype | None, bool]: + """ + Returns the low precision data type (torch.float16/torch.bfloat16) contained in the nodes + and if all the nodes can codegen with this data type without converting to float. + Otherwise returns None and True. + """ + sub_blocks = [_body.root_block] + list(_body.subblocks.values()) + + _lowp_fp_type: torch.dtype | None = None + _use_fp32 = False + for sub_block in sub_blocks: + for _node in sub_block.graph.nodes: + if _node.op == "placeholder" or _node.target in ( + "get_index", + "index_expr", + "value_expr", + ): + continue + + # Fast path if all operations can support bf16/fp16 without converting to fp32 + if _node.target not in [ + "load", + "store", + "abs", + "neg", + "output", + ]: + _use_fp32 = True + + if hasattr(_node, "meta") and _node.meta: + if OptimizationContext.key not in _node.meta: + raise AssertionError( + "expected OptimizationContext.key in _node.meta" + ) + opt_ctx: OptimizationContext = _node.meta[OptimizationContext.key] + if not opt_ctx.dtype or opt_ctx.dtype not in DTYPE_LOWP_FP: + _use_fp32 = True + elif _lowp_fp_type is not None: + if _lowp_fp_type != opt_ctx.dtype: + warnings.warn("bf16 and fp16 are mixed in the scheduler node.") + else: + _lowp_fp_type = opt_ctx.dtype + else: + _use_fp32 = True + + return _lowp_fp_type, _use_fp32 + + +@dataclasses.dataclass +class KernelOpStats: + """Op statistics collected during tiling selection.""" + + # Ratio of non-contiguous/mask ops to total ops above which vectorization + # is considered unprofitable (used both for disabling vectorization entirely + # and for deciding whether tail vectorization is worthwhile). + OVERHEAD_RATIO_THRESHOLD: ClassVar[float] = 0.12 + + op_counter: dict[str, int] = dataclasses.field(default_factory=dict) + non_contig_indexing_op_counter: dict[str, int] = dataclasses.field( + default_factory=dict + ) + mask_op_count: int = 0 + + +class TilingSelect: + """ + Implement the heuristic to select the tiling factors and tiling indices. + In the future, we can implement advanced heuristic in a subclass. + """ + + def select_tiling( + self, + fn_list, + var_sizes_list, + ) -> tuple[list[int], list[int], KernelOpStats]: + # TODO(jgong5): support alternative tiling factors and data types + loop_bodies = _get_loop_body(fn_list) + all_dtypes = _get_dtype_from_loopbodies(loop_bodies) + if not all_dtypes: + raise AssertionError("expected all_dtypes") + if any(dtype not in VECTORIZABLE_DTYPES for dtype in all_dtypes): + return [], [], KernelOpStats() + dtype = torch.float + _lowp_fp_dtype = get_loop_body_lowp_fp(loop_bodies[0])[0] + if _lowp_fp_dtype and all( + (get_loop_body_lowp_fp(loop_body)[0] == _lowp_fp_dtype) + for loop_body in loop_bodies[1:] + ): + dtype = _lowp_fp_dtype + + tiling_factor = cpu_vec_isa.pick_vec_isa().nelements(dtype=dtype) + tiling_indices = self._select_tiling_indices( + fn_list, var_sizes_list, tiling_factor + ) + + if tiling_indices: + group, reduction_group = max( + var_sizes_list, key=lambda sizes: len(sizes[1]) + ) + call_ranges = tuple(group) + tuple(reduction_group) + + stats = KernelOpStats() + if config.cpp.enable_tiling_heuristics: + + def _try_get_stride( + index, + itervars, + tiling_factor, + tiling_indices, + ): + itervar = itervars[tiling_indices[0]] + stride = stride_at_vec_range(index, itervar, tiling_factor) + return stride if stride.is_number else None + + def _update_negative_op_count( + node_name, non_contig_indexing_op_counter + ): + if node_name not in non_contig_indexing_op_counter: + non_contig_indexing_op_counter[node_name] = 1 + else: + non_contig_indexing_op_counter[node_name] += 1 + + def _is_valid_indices( + itervars, + tiling_indices, + ): + return ( + len(tiling_indices) == 1 + and len(itervars) > 0 + and ( + tiling_indices[0] + if tiling_indices[0] >= 0 + else tiling_indices[0] + len(itervars) + ) + < len(itervars) + ) + + itervars = [ + sympy_index_symbol_with_prefix(SymT.XBLOCK, n) + for n in range(len(call_ranges)) + ] + reduction_depth = len(group) + vars, reduction_vars = ( + itervars[:reduction_depth], + itervars[reduction_depth:], + ) + for _body in loop_bodies: + sub_blocks = [_body.root_block] + list(_body.subblocks.values()) + for sub_block in sub_blocks: + for _node in sub_block.graph.nodes: + if _node.target in [ + "index_expr", + "value_expr", + "load", + "store", + ]: + # get the index and replace prefix from z to x + arg_idx = ( + 1 + if _node.target in ("index_expr", "value_expr") + else 2 + ) + index = sub_block.body.indexing_from_args( + (vars, reduction_vars) + )[_node.args[arg_idx].args[0]] + if _is_valid_indices(itervars, tiling_indices): + stride = _try_get_stride( + index, itervars, tiling_factor, tiling_indices + ) + if ( + stride is None + if _node.target in ("index_expr", "value_expr") + else stride not in [0, 1] + ): + _update_negative_op_count( + _node.target, + stats.non_contig_indexing_op_counter, + ) + if isinstance(_node.target, str): + # Only count "where" and "masked" as mask ops — + # they generate actual mask/blend instructions. + if _node.target in ("where", "masked"): + stats.mask_op_count += 1 + if not ( + _node.target.startswith("masked_subblock") + or _node.target + in ["ops", "output", "constant", "get_index"] + ): + if _node.target not in stats.op_counter: + stats.op_counter[_node.target] = 1 + else: + stats.op_counter[_node.target] += 1 + + op_num = sum(stats.op_counter.values()) + non_contig_indexing_op_num = sum( + stats.non_contig_indexing_op_counter.values() + ) + quantity_threshold = 35 + if non_contig_indexing_op_num >= quantity_threshold or ( + op_num > 0 + and non_contig_indexing_op_num / op_num + >= stats.OVERHEAD_RATIO_THRESHOLD + ): + # Too many non-contiguous load/store/index/value_expr which hurts the + # vectorization performance. Disable vectorization when exceeding + # the thresholds. + return [], [], stats + + if ( + not reduction_group + and group + and len(tiling_indices) == 1 + and not has_free_symbols( + [ + group[tiling_indices[0]], + ] + ) + and group[tiling_indices[0]] < tiling_factor / 4 + and op_num < 10 + ): + # We found that when the number of elements in the inner loop range is + # relatively small(< tiling_factor / 4) and the number of operations is + # not large(< 10), vectorization is not efficient. + # And found that `#pragma GCC ivdep` has better performance than + # `#pragma omp simd simdlen(8)` for these cases. + return [], [], stats + + if dtype in DTYPE_LOWP_FP: + # For lower precision data type, if the call_range is not long enough, + # use tiling_factor // 2 for better performance + factor_lowp = cpu_vec_isa.pick_vec_isa().nelements(dtype=dtype) + for tiling_indice in tiling_indices: + if tiling_indice < 0: + tiling_indice = tiling_indice + len(call_ranges) + if tiling_indice < 0 or tiling_indice >= len(call_ranges): + continue + if has_free_symbols(call_ranges): + call_range = V.graph.sizevars.optimization_hint( + call_ranges[tiling_indice], fallback=0 + ) + if call_range < factor_lowp: + V.graph.sizevars.check_lt(call_range, factor_lowp) # type: ignore[arg-type] + tiling_factor = factor_lowp // 2 + break + elif call_ranges[tiling_indice] < factor_lowp: + tiling_factor = factor_lowp // 2 + break + + if len(tiling_indices) == 1: + return [tiling_factor], tiling_indices, stats + if len(tiling_indices) == 2: + return [tiling_factor, tiling_factor], tiling_indices, stats + return [], [], KernelOpStats() + + def _select_tiling_indices( + self, + fn_list, + var_sizes_list, + tiling_factor, + ): + all_index = [] + for fn, var_sizes in zip(fn_list, var_sizes_list): + rw = dependencies.extract_read_writes(fn, *var_sizes) + all_index += [dep.index for dep in itertools.chain(rw.reads, rw.writes)] + contig_vars = OrderedSet[int]() + contig_vars_list = [] + non_contig_stride_const = OrderedSet[int]() + non_contig_stride_other = OrderedSet[int]() + for index in all_index: + for var in index.free_symbols: + if not re.search(r"^d\d+$", var.name): + continue + stride = stride_at_vec_range(index, var, tiling_factor) + if stride == 0: + continue + elif stride == 1: + contig_vars.add(int(var.name[1:])) + contig_vars_list.append(int(var.name[1:])) + elif all(symbol_is_type(s, SymT.SIZE) for s in stride.free_symbols): + non_contig_stride_const.add(int(var.name[1:])) + else: + non_contig_stride_other.add(int(var.name[1:])) + contig_only = contig_vars - non_contig_stride_const - non_contig_stride_other + group, reduction_group = max(var_sizes_list, key=lambda sizes: len(sizes[1])) + num_itervars = len(group) + len(reduction_group) + if len(contig_vars) == 0: + # no contiguous vars + return [num_itervars - 1] + if contig_only: + return sorted(contig_only)[-1:] + contig_and_const_stride = ( + contig_vars & non_contig_stride_const + ) - non_contig_stride_other + contig_vars_sorted = sorted(contig_vars) + if ( + len(contig_vars_sorted) == 2 + and contig_vars_sorted[-1] in contig_and_const_stride + and contig_vars_sorted[-1] == num_itervars - 1 + ): + return contig_vars_sorted + return sorted(contig_vars_sorted, key=contig_vars_list.count)[-1:] + + +class CppKernelProxy(CppKernel): + # Subclass CppKernel, CppVecKernel, etc., to customize code generation. + # Override CppOverrides or CppVecOverrides to emit custom ops. + # Earlier, this meant copying codegen_functions() to use your subclasses. + # Now, use kernel_cls and vec_kernel_cls class attributes instead. + # This lets CppKernelProxy subclasses inject custom behavior cleanly. + # No need to duplicate codegen_functions() just to swap kernel classes. + kernel_cls: type[CppKernel] = CppKernel + vec_kernel_cls: type[CppVecKernel] = CppVecKernel + tile2d_kernel_cls: type[CppTile2DKernel] = CppTile2DKernel + + def __init__(self, kernel_group): + super().__init__(kernel_group.args, kernel_group.ws.num_threads) + self.kernel_group = kernel_group + self.loop_nest = None + self.call_ranges = None + self.picked_vec_isa: cpu_vec_isa.VecISA = cpu_vec_isa.pick_vec_isa() + self.kernels: list[CppKernel] = [] + + def data_type_propagation(self, nodes): + for _node in nodes: + if not isinstance(_node, SchedulerNode): + raise AssertionError("expected isinstance(_node, SchedulerNode)") + DataTypePropagation.propagate_scheduler_node(_node) + + # Check if all the nodes of a given fx graph can support BF16/FP16 + def is_lowp_fp_scheduler(self, scheduler_node: SchedulerNode): + if not isinstance(scheduler_node._body, LoopBody): + return True + # Propagate the dtype to check if all the fx node is bf16/fp16 + DataTypePropagation.propagate_scheduler_node(scheduler_node) + return ( + get_loop_body_lowp_fp(scheduler_node._body)[0] is not None + and not get_loop_body_lowp_fp(scheduler_node._body)[1] + ) + + def legalize_lowp_fp_dtype_loopbody(self, loop_body: LoopBody): + def add_to_dtype(sub_graph: torch.fx.Graph): + def get_input_dtype(node: torch.fx.Node) -> torch.dtype | None: + """Get input dtype for nodes that may consumes lowp fp dt""" + if node.target == "store": + return V.graph.get_dtype(node.args[1]) # type: ignore[arg-type] + elif node.target == "to_dtype_bitcast": + return node.args[-1] # type: ignore[return-value] + elif node.target == "to_dtype": + if len(node.args) > 3: + return node.args[3] # type: ignore[return-value] + else: + return node.kwargs.get("src_dtype", None) # type: ignore[return-value] + else: + return None + + def get_output_dtype(node: torch.fx.Node) -> torch.dtype | None: + """Get output dtype for nodes that may produce lowp fp dt""" + if node.target == "load": + if len(node.args) != 3: + raise AssertionError("expected len(node.args) == 3") + return V.graph.get_dtype(node.args[1]) # type: ignore[arg-type] + elif node.target in [ + "to_dtype", + "constant", + "index_expr", + "value_expr", + ]: + return node.args[-1] # type: ignore[return-value] + elif node.target == "to_dtype_bitcast": + return node.args[2] # type: ignore[return-value] + else: + return None + + def is_lowp_fp_source(node: torch.fx.Node, dt: torch.dtype): + """Check if the given node produces output with expected low precision floating point data type.""" + if dt not in DTYPE_LOWP_FP: + raise AssertionError("expected dt in DTYPE_LOWP_FP") + return get_output_dtype(node) == dt + + def is_lowp_fp_sink(node: torch.fx.Node, dt: torch.dtype): + """Check if the given node accept input with expected low precision floating point data type.""" + if dt not in DTYPE_LOWP_FP: + raise AssertionError("expected dt in DTYPE_LOWP_FP") + if input_dtype := get_input_dtype(node): + return input_dtype == dt + elif node.target == "to_dtype": + # The `src_dtype` of a `to_dtype` node might miss, in which case the node accept any input dtype. + return True + else: + return False + + def is_lowp_fp_source_no_promote(node: torch.fx.Node, dt: torch.dtype): + """Check if the node is a lowp fp sources which are all directly fed to ops that accepts lowp fp input + thus no need to promote to float + """ + return is_lowp_fp_source(node, dt) and all( + is_lowp_fp_sink(user, dt) for user in node.users + ) + + sub_graph_nodes = list(sub_graph.nodes) + to_lowp_fp_legalized_nodes = [] + for _node in sub_graph_nodes: + if ( + _node.target in ["load", "index_expr", "value_expr"] + and (dt := get_output_dtype(_node)) in DTYPE_LOWP_FP + ): + # No need to promote to float if all users are ops that accepts lowp fp input + # pyrefly: ignore [bad-argument-type] + if all(is_lowp_fp_sink(user, dt) for user in _node.users): + continue + ops = _node.args[0] + with sub_graph.inserting_after(_node): + to_type_node = sub_graph.call_method( + "to_dtype", args=(ops, _node, torch.float) + ) + _node.replace_all_uses_with( + to_type_node, lambda n: n is not to_type_node + ) + # pyrefly: ignore [bad-assignment] + metrics.cpp_to_dtype_count += 1 + elif ( + _node.target == "store" + and (dt := get_input_dtype(_node)) in DTYPE_LOWP_FP + ): + ops, name, _, value_var, _ = _node.args + # pyrefly: ignore [bad-argument-type] + if is_lowp_fp_source_no_promote(value_var, dt): + continue + dtype = V.graph.get_dtype(name) + with sub_graph.inserting_before(_node): + to_type_node = sub_graph.call_method( + "to_dtype", args=(ops, value_var, dtype) + ) + _node.replace_input_with(value_var, to_type_node) + # pyrefly: ignore [bad-assignment] + metrics.cpp_to_dtype_count += 1 + elif _node.target == "reduction": + ( + ops, + dtype, + src_dtype, + reduction_type, + value, + ) = _node.args + if src_dtype in DTYPE_LOWP_FP: + # Since we always convert the load/store value to float if the tensor is bfloat16/float16. + # Therefore, the reduction should never work with bfloat16/float16 value. Hence, we update + # the bfloat16/float16 reduction by + # 1) updating the src_dtype to float + # and 2) updating the dtype to float if it is bfloat16/float16. + if dtype not in [ + torch.float, + torch.bfloat16, + torch.float16, + torch.int64, + ]: + raise AssertionError( + "expected dtype in [ torch.float, torch.bfloat16, torch.float16, to..." + ) + _node.args = ( + ops, + torch.float if dtype in DTYPE_LOWP_FP else dtype, + torch.float, + reduction_type, + value, + ) + elif _node.target == "constant" and _node.args[-1] in DTYPE_LOWP_FP: + # No need to promote to float if all users are ops that accepts lowp fp input + (ops, value, dt) = _node.args + if all(is_lowp_fp_sink(user, dt) for user in _node.users): # type: ignore[arg-type] + continue + _node.args = (ops, value, torch.float) + elif _node.target == "to_dtype" and _node.args[-1] in DTYPE_LOWP_FP: + # No need to promote to float if all users are ops that accepts lowp fp input + (ops, x, dt) = _node.args + if all(is_lowp_fp_sink(user, dt) for user in _node.users): # type: ignore[arg-type] + continue + # The legalization always loads the BF16/FP16 tensor as FP32 for computation + # and converts back to BF16/FP16 after the computation. + # Hence, there should be no computation w/ BF16/FP16. + # Therefore, we update the to_dtype by replacing the bf16/fp16 dtype with fp32. + # Save the legalized to_dtype node for the elimination(eliminate_to_dtype step): + # 1) Eliminate the redundant to_dtype node if we have a pattern as follows: + # graph(): + # %lowp_fp_legalized = call_method[target=to_dtype](args = (%ops, %input, torch.float)) + # %to_dtype2 = call_method[target=to_dtype](args = (%ops, %lowp_fp_legalized, torch.bfloat16/float16)) + # Regarding the first to_dtype, it is redundant because + # the second to_type also converts to the torch.bfloat16/torch.float16. + # Hence, we remove the first to_type. + to_lowp_fp_legalized_nodes.append(_node) + _node.args = (ops, x, torch.float) + elif _node.target == "to_dtype_bitcast": + (ops, value_var, dtype, src_dtype) = _node.args + + # to_dtype_bitcast act as a lowp fp sink: + # c10::bit_cast requires the source and target have the same bitwidth. Because the input tensor's + # dtype could be promoted, e.g. from float16 to float, we have to cast the tensor to its original + # source dtype before invoking bit_cast. + if src_dtype in DTYPE_LOWP_FP: + # No need to promote to float if it is a user of a lowp fp sources + # which are all directly fed to ops that accepts lowp fp input + if not is_lowp_fp_source_no_promote(value_var, src_dtype): + with sub_graph.inserting_before(_node): + to_type_node = sub_graph.call_method( + "to_dtype", args=(ops, value_var, src_dtype) + ) + _node.replace_input_with(value_var, to_type_node) + # pyrefly: ignore [bad-assignment] + metrics.cpp_to_dtype_count += 1 + + # to_dtype_bitcast act as a lowp fp source: + # We also need to convert the bit-casted tensor back to float to make sure we keep using higher + # precision values for the rest of the computation. + if dtype in DTYPE_LOWP_FP: + # No need to promote to float if all users are ops that accepts lowp fp input + if not ( + all(is_lowp_fp_sink(user, dtype) for user in _node.users) + ): + ops = _node.args[0] + with sub_graph.inserting_after(_node): + to_type_node = sub_graph.call_method( + "to_dtype", args=(ops, _node, torch.float) + ) + _node.replace_all_uses_with( + to_type_node, lambda n: n is not to_type_node + ) + # pyrefly: ignore [bad-assignment] + metrics.cpp_to_dtype_count += 1 + + def eliminate_to_dtype(sub_graph: torch.fx.Graph): + def _eliminate_duplicate_to_node(sub_graph: torch.fx.Graph): + # Eliminate the redundant to_dtype node. Let's consider a pattern as follows: + # graph(): + # %to_dtype1 = call_method[target=to_dtype](args = (%ops, %input, torch.float), kwargs = {}) + # %to_dtype2 = call_method[target=to_dtype](args = (%ops, %to_dtype1, torch.float), kwargs = {}) + # Regarding the first to_dtype, it is redundant because the second to_type also converts to the + # torch.float. Hence, we remove the first to_type + def _used_by_to(to_node: torch.fx.Node): + return all(usr.target == "to_dtype" for usr in to_node.users) + + all_to_nodes = [ + node for node in sub_graph.nodes if node.target == "to_dtype" + ] + all_to_nodes_and_users = [ + {node: node.users} for node in all_to_nodes if _used_by_to(node) + ] + for node_users in all_to_nodes_and_users: + for node, users in node_users.items(): + if node in sub_graph.nodes and ( + all(usr.args[-1] == node.args[-1] for usr in users) + or ( + node in to_lowp_fp_legalized_nodes + and all( + usr.args[-1] in DTYPE_LOWP_FP for usr in users + ) + ) + ): + val_node = node.all_input_nodes[-1] + node.replace_all_uses_with(val_node) + sub_graph.erase_node(node) + + # For debug mode, the graph of LoopBody will attach a new GraphModule as + # owning_module for debugging while the release mode will not. The lint will + # check whether the graph has owning_module to decide if it needs to check + # call_module. LoopBody might contain get_index as a module call. But it + # is just a function. Hence, it cannot pass the lint check for debug mode. + # We bypass the check if the owning_module is None. Eventually, we should call + # get_index via call_function but not call_module. + if sub_graph.owning_module is None: + sub_graph.lint() + + _eliminate_duplicate_to_node(sub_graph) + + eliminate_to_dtype(sub_graph) + + sub_blocks = [loop_body.root_block] + list(loop_body.subblocks.values()) + for sub_block in sub_blocks: + add_to_dtype(sub_block.graph) + + def legalize_lowp_fp_dtype(self, nodes): + if all( + isinstance(_node, SchedulerNode) and self.is_lowp_fp_scheduler(_node) + for _node in nodes + ): + # Mark the load node to load bf16/fp16 + for _node in nodes: + sub_blocks = [_node._body.root_block] + list( + _node._body.subblocks.values() + ) + for sub_block in sub_blocks: + for fx_node in sub_block.graph.nodes: + if fx_node.target in ["load", "store"]: + if not fx_node.meta: + raise AssertionError("expected fx_node.meta") + if OptimizationContext.key not in fx_node.meta: + raise AssertionError( + "expected OptimizationContext.key in fx_node.meta" + ) + opt_ctx: OptimizationContext = fx_node.meta[ + OptimizationContext.key + ] + if opt_ctx.dtype not in DTYPE_LOWP_FP: + raise AssertionError( + "expected opt_ctx.dtype in DTYPE_LOWP_FP" + ) + + # Bypass the legalization as the kernel can run with bf16/fp16 directly + return + + for _node in nodes: + if not isinstance(_node, SchedulerNode): + raise AssertionError("expected isinstance(_node, SchedulerNode)") + if not isinstance(_node._body, LoopBody): + raise AssertionError("expected isinstance(_node._body, LoopBody)") + body: LoopBody = _node._body + if not body.is_memory_copy(): + self.legalize_lowp_fp_dtype_loopbody(body) + + def codegen_functions(self, fn_list, var_sizes_list): + """Generate scalar and vectorized C++ kernels with tiling for the given functions.""" + if len(fn_list) != len(var_sizes_list): + raise AssertionError("expected len(fn_list) == len(var_sizes_list)") + kernel_group = self.kernel_group + group, reduction_group = max(var_sizes_list, key=lambda sizes: len(sizes[1])) + + self.set_ranges(group, reduction_group) + + def codegen_kernel(cls, *args): + with kernel_group.new_kernel(cls, *args) as kernel: + # Ugly hack to maintain the metrics kernel count since + # we only count in CppKernelProxy, not those contained in it + # pyrefly: ignore [bad-assignment] + metrics.generated_kernel_count -= 1 + + run(kernel) + return kernel + + def run(kernel): + vars, reduction_vars = kernel.set_ranges(group, reduction_group) + in_suffix = False + for fn, var_sizes in zip(fn_list, var_sizes_list): + if var_sizes in [ + (group, reduction_group), + (tuple(itertools.chain(group, reduction_group)), ()), + ]: + if in_suffix: + raise AssertionError("expected not in_suffix") + fn(vars, reduction_vars) + else: + in_suffix = True + if not ( + var_sizes + == ( + group, + (), + ) + ): + raise AssertionError( + f"unexpected group: {var_sizes} != {group}, {reduction_group}" + ) + # we can fuse in some extra pointwise into the suffix + with kernel.write_to_suffix(): + fn(vars, ()) + + scalar_kernel = codegen_kernel(self.kernel_cls) + V.graph.removed_buffers |= scalar_kernel.removed_buffers + V.graph.inplaced_to_remove |= scalar_kernel.inplaced_to_remove + self.loop_nest = LoopNest.build(scalar_kernel) + + if not self.picked_vec_isa or not self.itervars: + self.kernels = [scalar_kernel] + self.aggregate_reduction_buffers(False, None) + self.loop_nest.set_kernel(self) + return + + # Kernels share the same global contexts like V.graph.wrapper_code, V.kernel.args. + # But the generated scalar kernel has updated these global contexts. Hence, the other kernels + # should not do this again to avoid context conflict. By now, we only control the + # config.inplace_buffers. In the future, we could maintain more contexts. + with torch._inductor.config.patch(inplace_buffers=False): + tiling_select = TilingSelect() + tiling_factors, tiling_indices, tiling_stats = tiling_select.select_tiling( + fn_list, var_sizes_list + ) + + def _tail_vec_worthwhile(tail_size, tiling_factor) -> bool: + # Tail vectorization has non-trivial mask/cast/blend overhead. + # Only vectorize tail when it is large enough to amortize overhead. + op_num = sum(tiling_stats.op_counter.values()) + if ( + op_num > 0 + and ( + tiling_stats.mask_op_count + + sum(tiling_stats.non_contig_indexing_op_counter.values()) + ) + / op_num + > tiling_stats.OVERHEAD_RATIO_THRESHOLD + ): + hint_tail_size = V.graph.sizevars.optimization_hint(tail_size) + return 2 * hint_tail_size > tiling_factor + return True + + if len(tiling_factors) != len(tiling_indices): + raise AssertionError( + "expected len(tiling_factors) == len(tiling_indices)" + ) + _inner_loop_reduction_outer_not = False + _tiled_loop_reduction_descendant = False + _outer_loop = None + if tiling_indices: + inner_loop_reduction = False + outer_loop_level = tiling_indices[0] + inner_loop_level = outer_loop_level + 1 + if len(self.loop_nest.loops) > inner_loop_level: + inner_loop_reduction = self.loop_nest.loops[ + inner_loop_level + ].is_reduction + outer_loop_reduction = self.loop_nest.loops[ + outer_loop_level + ].is_reduction + _inner_loop_reduction_outer_not = ( + inner_loop_reduction and not outer_loop_reduction + ) + _tiled_loop_reduction_descendant = not outer_loop_reduction and any( + loop.is_reduction + for loop in self.loop_nest.loops[inner_loop_level:] + ) + + if len(tiling_indices) == 1: + # pyrefly: ignore [bad-assignment] + metrics.generated_cpp_vec_kernel_count += 1 + loop = self.loop_nest.tile(tiling_indices[0], factor=tiling_factors[0]) + vec_kernel = codegen_kernel( + self.vec_kernel_cls, tiling_factors[0], tiling_indices[0] + ) + tail_size = loop.size - loop.tiled_size + vec_kernel.active_ranges = {loop.var: (0, loop.tiled_size)} + if config.cpp.enable_loop_tail_vec and _tail_vec_worthwhile( + tail_size, tiling_factors[0] + ): + tail_kernel = codegen_kernel( + self.vec_kernel_cls, + tiling_factors[0], + tiling_indices[0], + tail_size, + ) + else: + tail_kernel = scalar_kernel + scalar_kernel.inner_itervars = [loop.var] + tail_kernel.active_ranges = {loop.var: (loop.tiled_size, loop.size)} + self.kernels = [vec_kernel, tail_kernel] + _outer_loop = loop + elif len(tiling_indices) == 2: + if not ( + tiling_indices[1] == len(self.itervars) - 1 + and tiling_factors[0] == tiling_factors[1] + ): + raise AssertionError( + "expected tiling_indices[1] == len(self.itervars) - 1 and tiling_fa..." + ) + + # pyrefly: ignore [bad-assignment] + metrics.generated_cpp_vec_kernel_count += 2 + outer_loop = self.loop_nest.tile( + tiling_indices[0], factor=tiling_factors[0] + ) + outer_ranges = { + "main": (0, outer_loop.tiled_size), + "tail": (outer_loop.tiled_size, outer_loop.size), + } + outer_tail_size = outer_loop.size - outer_loop.tiled_size + inner_loop = self.loop_nest.tile( + tiling_indices[1], factor=tiling_factors[0] + ) + inner_ranges = { + "main": (0, inner_loop.tiled_size), + "tail": (inner_loop.tiled_size, inner_loop.size), + } + inner_tail_size = inner_loop.size - inner_loop.tiled_size + tile2d_kernel = codegen_kernel( + self.tile2d_kernel_cls, + tiling_factors[0], + tiling_indices, + ) + tile2d_kernel.active_ranges = { + outer_loop.var: outer_ranges["main"], + inner_loop.var: inner_ranges["main"], + } + tail_kernel = [] + if config.cpp.enable_loop_tail_vec and _tail_vec_worthwhile( + inner_tail_size, tiling_factors[0] + ): + for outer_r, inner_r in ( + ("main", "tail"), + ("tail", "main"), + ("tail", "tail"), + ): + _inner_tail_size = ( + inner_tail_size if inner_r == "tail" else None + ) + _outer_tail_size = ( + outer_tail_size if outer_r == "tail" else None + ) + kernel = codegen_kernel( + self.tile2d_kernel_cls, + tiling_factors[0], + tiling_indices, + _inner_tail_size, + _outer_tail_size, + ) + kernel.active_ranges = { + outer_loop.var: outer_ranges[outer_r], + inner_loop.var: inner_ranges[inner_r], + } + tail_kernel.append(kernel) + else: + vec_kernel = codegen_kernel( + self.vec_kernel_cls, tiling_factors[0], tiling_indices[0] + ) + vec_kernel.active_ranges = { + outer_loop.var: outer_ranges["main"], + inner_loop.var: inner_ranges["tail"], + } + vec_kernel.inner_itervars = [inner_loop.var] + tail_kernel.append(vec_kernel) + scalar_kernel.active_ranges = { + outer_loop.var: outer_ranges["tail"], + inner_loop.var: (0, inner_loop.size), + } + scalar_kernel.inner_itervars = [inner_loop.var, outer_loop.var] + tail_kernel.append(scalar_kernel) + self.kernels = [tile2d_kernel] + tail_kernel + _outer_loop = outer_loop + else: + self.kernels = [scalar_kernel] + # A non-reduction tiled loop with a nested reduction needs its + # reduction suffix selected by the same main/tail active range. + self.aggregate_reduction_buffers( + _inner_loop_reduction_outer_not + or (len(tiling_indices) == 1 and _tiled_loop_reduction_descendant), + _outer_loop, + ) + self.loop_nest.set_kernel(self) + + def codegen_loop_bodies(self, loop_bodies, var_sizes_list): + for body in loop_bodies: + self.legalize_lowp_fp_dtype_loopbody(body) + DataTypePropagation.propagate_loopbody(body) + self.codegen_functions(loop_bodies, var_sizes_list) + + def codegen_nodes(self, nodes: list[SchedulerNode]): + # Legalize BF16 node by adding to_dtype explicitly + self.legalize_lowp_fp_dtype(nodes) + self.data_type_propagation(nodes) + if len(nodes) < 1: + raise AssertionError("expected len(nodes) >= 1") + + def fn(node, *index_vars): + node.decide_inplace_update() + node.mark_run() + if isinstance(V.kernel, NullKernelHandler): + return node._body(*index_vars) + else: + return node.codegen(index_vars) + + fn_list = [functools.partial(fn, node) for node in nodes] + + if ( + isinstance(V.local_buffer_context, LocalBufferContext) + and V.local_buffer_context.local_buffers + ): + + def wrap_fn(fn): + wrapped_fn = V.local_buffer_context.localize_function( + fn, + ) + wrapped_fn.original_fn = fn + return wrapped_fn + + fn_list = [wrap_fn(fn) for fn in fn_list] + + var_sizes_list = [node.group[1] for node in nodes] + self.codegen_functions(fn_list, var_sizes_list) + + def codegen_loops(self, code, worksharing): + self.codegen_loops_impl(self.loop_nest, code, worksharing) + + def update_stores_with_parallel_reduction(self): + for kernel in self.kernels: + kernel.update_stores_with_parallel_reduction() + + def gen_body(self, code: BracesBuffer | None = None): + if code is None: + raise AssertionError("expected code is not None") + if_prefix = "C10_LIKELY" + for kernel in self.kernels: + with contextlib.ExitStack() as stack: + if kernel.codegen_conditions(code, if_prefix): + if_prefix = "C10_UNLIKELY" + stack.enter_context(code.indent()) + code.splice(kernel.gen_body()) + + def aggregate_reduction_buffers( + self, inner_loop_reduction_outer_not: bool, outer_loop: Optional["LoopLevel"] + ): + """ + CppKernel/CppVecKernel/CppTile2dKernel have reduction buffers themselves. + Here, we decide how to aggregate them together and place new reduction buffers + under CppKernelProxy. + """ + + def aggregate_reduction_prefix_suffix(outer_loop: "LoopLevel"): + if len(self.kernels) < 2: + raise AssertionError("expected len(self.kernels) >= 2") + main_loop_kernel = self.kernels[0] + tail_loop_kernel = self.kernels[-1] + if not isinstance(main_loop_kernel, self.vec_kernel_cls): + raise AssertionError( + "expected isinstance(main_loop_kernel, self.vec_kernel_cls)" + ) + + # Prefix + if type(tail_loop_kernel) is self.kernel_cls: + # if tail loop kernel is a scalar kernel, we need to extend tmp_acc -> tmp_acc_arr[] to + # hold the temporary inner loop acc result for outer tail loop + tail_loop_kernel.finalize_reduction_prefix( + main_loop_kernel.tiling_factor + ) + main_loop_kernel.finalize_reduction_prefix() + self.reduction_prefix.splice( + tail_loop_kernel.reduction_prefix + + main_loop_kernel.reduction_prefix + ) + else: + main_loop_kernel.finalize_reduction_prefix() + self.reduction_prefix.splice(main_loop_kernel.reduction_prefix) + + # Suffix + suffix_buf = BracesBuffer() + with contextlib.ExitStack() as stack: + if main_loop_kernel.codegen_conditions( + suffix_buf, "C10_LIKELY", outer_loop.var + ): + stack.enter_context(suffix_buf.indent()) + suffix_buf.splice(main_loop_kernel.reduction_suffix) + with contextlib.ExitStack() as stack: + if tail_loop_kernel.codegen_conditions( + suffix_buf, "C10_UNLIKELY", outer_loop.var + ): + stack.enter_context(suffix_buf.indent()) + if type(tail_loop_kernel) is self.kernel_cls: + reduction_vars = tail_loop_kernel.reduction_var_names + for name in reduction_vars: + new_name = f"{name}_arr[{outer_loop.var}_tail - {cexpr_index(outer_loop.tiled_size)}]" + replace_acc_name(tail_loop_kernel.stores, name, new_name) + replace_acc_name( + tail_loop_kernel.reduction_suffix, name, new_name + ) + # If tail loop kernel is a scalar kernel, use direct sum instead of cascade_sum_combine + # as the reduction vars are extended: tmp_acc -> tmp_acc_arr[]. + replace_cascade_sum_with_add(tail_loop_kernel.stores) + suffix_buf.splice( + move_code_under_inner_loop( + tail_loop_kernel.reduction_suffix, + outer_loop.var, + f"{outer_loop.var}_tail", + outer_loop.tiled_size, + outer_loop.size, + ) + ) + else: + suffix_buf.splice(tail_loop_kernel.reduction_suffix) + self.reduction_suffix = suffix_buf + + main_kernel = self.kernels[0] + if inner_loop_reduction_outer_not: + if not outer_loop: + raise AssertionError("expected outer_loop") + aggregate_reduction_prefix_suffix(outer_loop) + else: + main_kernel.finalize_reduction_prefix() + self.reduction_prefix.splice(main_kernel.reduction_prefix) + self.reduction_suffix.splice(main_kernel.reduction_suffix) + self.parallel_reduction_prefix.splice(main_kernel.parallel_reduction_prefix) + self.parallel_reduction_suffix.splice(main_kernel.parallel_reduction_suffix) + self.local_reduction_init.splice(main_kernel.local_reduction_init) + self.local_reduction_stores.splice(main_kernel.local_reduction_stores) + self.non_parallel_reduction_prefix.splice( + main_kernel.non_parallel_reduction_prefix + ) + self.non_parallel_reduction_suffix.splice( + main_kernel.non_parallel_reduction_suffix + ) + + +class OuterLoopFusedKernel(CppKernel): + def __init__(self, kernel_group): + super().__init__(kernel_group.args, kernel_group.ws.num_threads) + self.inner: list[LoopNest] = [] + + def decide_parallel_depth(self, max_parallel_depth, threads): + kernels_parallel_depth = [] + nested_kernels: list[CppKernel] = [ + loop_nest.get_kernel() for loop_nest in self.inner + ] + # TODO(leslie-fang-intel): only enable parallel within all outer loop levels. + for kernel in nested_kernels: + # For any ScalarKernel, VecKernel, or Tile2DKernel, + # they should all have the same call_ranges + call_ranges = kernel.call_ranges + if call_ranges is None: + raise AssertionError("expected call_ranges is not None") + kernels_parallel_depth.append( + kernel.decide_parallel_depth( + ParallelDepth( + parallel_depth=( + len(call_ranges) - max_parallel_depth.start_depth + ), + start_depth=max_parallel_depth.start_depth, + ), + threads, + ).parallel_depth + ) + return ParallelDepth( + parallel_depth=min( + max_parallel_depth.parallel_depth, max(kernels_parallel_depth) + ), + start_depth=max_parallel_depth.start_depth, + ) + + +class ReasonFusedNodes(Enum): + SAME_VARS_REDUCE = "same_vars_reduce" + COMPATIBLE_REDUCTION = "compatible_reduction" + COMPATIBLE_RANGES_NO_REDUCTION = "compatible_ranges_no_reduction" + + +class CppScheduling(BaseScheduling): + # Subclass CppKernelProxy to customize codegen without copying codegen_node(). + # Use kernel_proxy_cls to inject custom proxies in CppScheduling subclasses. + # Avoid duplicating codegen_node() just to swap in a custom kernel proxy class. + kernel_proxy_cls: type[CppKernelProxy] = CppKernelProxy + # ctypes limits the number of args to 1024, refer to: + # https://github.com/python/cpython/commit/a285af7e626d1b81cf09f8b2bf7656f100bc1237 + # We set a conservative threshold here. + MAX_FUSED_KERNEL_ARGS_NUM = 500 + backend_features = OrderedSet( + [ + BackendFeature.INPLACE_BUFFERS, + BackendFeature.REDUCE_TO_SINGLE_ELEMENT, + ] + ) + + @classmethod + def get_backend_features(cls, device: torch.device) -> OrderedSet[BackendFeature]: + return cls.backend_features + + def __init__(self, scheduler): + super().__init__(scheduler) + if scheduler: + self.reset_kernel_group() + self._ready_to_flush = False + + def _set_flush_status(self, status: bool): + self._ready_to_flush = status + + def group_fn(self, sizes): + return tuple(tuple(map(V.graph.sizevars.simplify, s)) for s in sizes) + + def reset_kernel_group(self): + self.kernel_group = KernelGroup() + + def _get_indexing_ranges_exprs(self, node) -> ir.ExtraIndexingConstraints: + if isinstance(node, FusedSchedulerNode): + if len(node.snodes) <= 0: + raise AssertionError(node.snodes) + var_ranges = None + indexing_exprs = OrderedSet[Any]() + for snode in node.snodes: + constraints = self._get_indexing_ranges_exprs(snode) + if var_ranges is None: + var_ranges = constraints.ranges + if var_ranges != constraints.ranges: + raise AssertionError((var_ranges, constraints.ranges, node.snodes)) + indexing_exprs.update(constraints.exprs) + if var_ranges is None: + raise AssertionError("expected at least one snode to set var_ranges") + return ir.ExtraIndexingConstraints(var_ranges, list(indexing_exprs)) + + if not isinstance(node, SchedulerNode): + raise AssertionError("expected isinstance(node, SchedulerNode)") + comp_buffer = node.node + if not isinstance(comp_buffer, ir.ComputedBuffer): + raise AssertionError("expected isinstance(comp_buffer, ir.ComputedBuffer)") + _, body, _ = comp_buffer.get_default_sizes_body() + return ir.ExtraIndexingConstraints( + body.var_ranges, list(body.indexing_exprs.values()) + ) + + def _snapshot_node_loop_states(self, node): + if isinstance(node, SchedulerNode): + return [(node, node.snapshot_loop_state())] + + if not isinstance(node, FusedSchedulerNode): + raise AssertionError("expected isinstance(node, FusedSchedulerNode)") + snapshots = [] + for snode in node.snodes: + if not isinstance(snode, SchedulerNode): + raise AssertionError("expected isinstance(snode, SchedulerNode)") + snapshots.append((snode, snode.snapshot_loop_state())) + return snapshots + + def _align_compatible_range_nodes(self, node1, node2): + if not isinstance(node1, (SchedulerNode, FusedSchedulerNode)): + raise AssertionError( + "expected isinstance(node1, (SchedulerNode, FusedSchedulerNode))" + ) + if not isinstance(node2, (SchedulerNode, FusedSchedulerNode)): + raise AssertionError( + "expected isinstance(node2, (SchedulerNode, FusedSchedulerNode))" + ) + + _, (vars1, reduce1) = node1.group + _, (vars2, reduce2) = node2.group + if not (reduce1 == () and reduce2 == ()): + raise AssertionError((reduce1, reduce2)) + + node_to_recomp = node1 if len(vars1) < len(vars2) else node2 + ref_node = node2 if len(vars1) < len(vars2) else node1 + if not isinstance(node_to_recomp, SchedulerNode): + raise AssertionError("expected isinstance(node_to_recomp, SchedulerNode)") + + ref_indexing_constraints = self._get_indexing_ranges_exprs(ref_node) + node_to_recomp.recompute_size_and_body( + extra_indexing_constraints=ref_indexing_constraints + ) + + _, (vars1, _) = node1.group + _, (vars2, _) = node2.group + if vars1 == vars2: + return True + + node_to_recomp_indexing_constraints = self._get_indexing_ranges_exprs( + node_to_recomp + ) + if isinstance(ref_node, SchedulerNode): + ref_node.recompute_size_and_body( + extra_indexing_constraints=node_to_recomp_indexing_constraints + ) + else: + if not isinstance(ref_node, FusedSchedulerNode): + raise AssertionError( + "expected isinstance(ref_node, FusedSchedulerNode)" + ) + for snode in ref_node.snodes: + if not isinstance(snode, SchedulerNode): + raise AssertionError("expected isinstance(snode, SchedulerNode)") + snode.recompute_size_and_body( + extra_indexing_constraints=node_to_recomp_indexing_constraints + ) + + _, (vars1, _) = node1.group + _, (vars2, _) = node2.group + return vars1 == vars2 + + def fuse(self, node1, node2): + if node1.is_foreach() or node2.is_foreach(): + return ForeachKernelSchedulerNode.fuse(node1, node2) + elif node1.is_template(): + if node2.is_template(): + raise AssertionError("expected not node2.is_template()") + return FusedSchedulerNode.fuse(node1, node2) + else: + if ( + self._why_fuse_nodes(node1, node2) + == ReasonFusedNodes.COMPATIBLE_RANGES_NO_REDUCTION + ): + if not (self._align_compatible_range_nodes(node1, node2)): + raise AssertionError( + ( + node1.group, + node2.group, + ) + ) + return FusedSchedulerNode.fuse(node1, node2) + elif self.can_fuse_vertical_outer_loop(node1, node2): + return OuterLoopFusedSchedulerNode.fuse( + node1, node2, self._get_outer_loop_fusion_depth(node1, node2) + ) + else: + return FusedSchedulerNode.fuse(node1, node2) + + def _why_fuse_nodes(self, node1, node2) -> ReasonFusedNodes | None: + _, (vars1, reduce1) = node1.group + _, (vars2, reduce2) = node2.group + + if vars1 == vars2 and reduce1 == reduce2: + return ReasonFusedNodes.SAME_VARS_REDUCE + if reduce1 == () and vars1 == vars2 + reduce2: + return ReasonFusedNodes.COMPATIBLE_REDUCTION + if self._can_fuse_nodes_with_compatible_ranges(node1, node2): + return ReasonFusedNodes.COMPATIBLE_RANGES_NO_REDUCTION + # TODO(jansel): allow fusion pointwise (vars1, ()) suffix? + return None + + def _can_fuse_nodes_with_compatible_ranges(self, node1, node2): + # Here we try to fuse SchedulerNode/FusedSchedulerNode with compatible ranges + # e.g. (s0, s1, s2) and (s0 * s1 * s2) + _, (vars1, reduce1) = node1.group + _, (vars2, reduce2) = node2.group + + c1 = reduce1 == () and reduce2 == () + c2 = math.prod(vars1) == math.prod(vars2) + c3 = len(vars1) == 1 or len(vars2) == 1 + if not (c1 and c2 and c3): + return False + + node_to_recomp = node1 if len(vars1) < len(vars2) else node2 + ref_node = node2 if len(vars1) < len(vars2) else node1 + + # We can not recompute sizes and body for nodes other than SchedulerNode + # TODO: we can extend fusion support with compatible ranges for FusedSchedulerNode + if isinstance(node_to_recomp, FusedSchedulerNode): + return False + + # It may happen that node1 and node2 compatible number of elements + # but different original ranges, for example: + # {d0: s0, d1: s1, d2: s2} vs {d0: s0*s1*s2} + # See https://github.com/pytorch/pytorch/pull/120077/files#r1500427848 for more details + # TODO: we can fix if it allows us to CSE at least one of the variables + + if not isinstance(node_to_recomp, SchedulerNode): + raise AssertionError("expected isinstance(node_to_recomp, SchedulerNode)") + if isinstance(node_to_recomp.node, ir.TemplateBuffer): + return False + if not isinstance(node_to_recomp.node, ir.ComputedBuffer): + raise AssertionError( + "expected isinstance(node_to_recomp.node, ir.ComputedBuffer)" + ) + # node.data.get_size() is a cheaper version of node.get_read_writes().var_ranges + # but without variable name + ranges2 = node_to_recomp.node.data.get_size() + ranges1 = None + if isinstance(ref_node, FusedSchedulerNode): + ranges_set = OrderedSet[tuple[Any, ...]]() + for snode in ref_node.snodes: + if not isinstance(snode, SchedulerNode): + raise AssertionError("expected isinstance(snode, SchedulerNode)") + if isinstance(snode.node, ir.TemplateBuffer): + break + if not isinstance(snode.node, ir.ComputedBuffer): + raise AssertionError( + "expected isinstance(snode.node, ir.ComputedBuffer)" + ) + ranges_set.add(tuple(snode.node.data.get_size())) + + if len(ranges_set) != 1: + return False + + ranges1 = list(next(iter(ranges_set))) + else: + if not isinstance(ref_node, SchedulerNode): + raise AssertionError("expected isinstance(ref_node, SchedulerNode)") + if not isinstance(ref_node.node, ir.ComputedBuffer): + raise AssertionError( + "expected isinstance(ref_node.node, ir.ComputedBuffer)" + ) + ranges1 = ref_node.node.data.get_size() # type: ignore[assignment] + + if ranges1 != ranges2: + return False + + snapshots = self._snapshot_node_loop_states(node_to_recomp) + snapshots.extend(self._snapshot_node_loop_states(ref_node)) + try: + return self._align_compatible_range_nodes(node1, node2) + finally: + for node, state in reversed(snapshots): + node.restore_loop_state(state) + + def _can_fuse_horizontal_impl(self, node1, node2): + if not ( + isinstance( + node1, (FusedSchedulerNode, SchedulerNode, ExternKernelSchedulerNode) + ) + ): + raise AssertionError( + "expected isinstance( node1, (FusedSchedulerNode, SchedulerNode, Ex..." + ) + if not isinstance(node2, (FusedSchedulerNode, SchedulerNode)): + raise AssertionError( + "expected isinstance(node2, (FusedSchedulerNode, SchedulerNode))" + ) + if any( + isinstance(node, (OuterLoopFusedSchedulerNode, ExternKernelSchedulerNode)) + for node in (node1, node2) + ): + return False + return self._why_fuse_nodes(node1, node2) is not None + + def can_fuse_horizontal(self, node1, node2): + if node1.is_template() or node2.is_template(): + return False + if ( + len(node1.get_nodes()) + len(node2.get_nodes()) + > config.cpp.max_horizontal_fusion_size + ): + return False + + return self._can_fuse_horizontal_impl(node1, node2) + + def can_fuse_multi_outputs_template( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if template_buf := node1.get_template_node(): + return ( + isinstance(template_buf.layout, ir.MultiOutputLayout) + and isinstance(node2.node, ir.MultiOutput) + and len(node2.node.inputs) == 1 + and node2.node.inputs[0].get_name() == template_buf.name # type: ignore[union-attr] + ) + return False + + def _get_outer_loop_fusion_depth(self, node1, node2): + DISABLE_OUTER_LOOP_FUSION = 0 + if not all( + type(node) + in (OuterLoopFusedSchedulerNode, FusedSchedulerNode, SchedulerNode) + for node in (node1, node2) + ): + return DISABLE_OUTER_LOOP_FUSION + + _node1 = ( + node1.get_outer_nodes()[-1] + if isinstance(node1, OuterLoopFusedSchedulerNode) + else node1 + ) + if not isinstance(_node1, (FusedSchedulerNode, SchedulerNode)): + raise AssertionError( + "expected isinstance(_node1, (FusedSchedulerNode, SchedulerNode))" + ) + _node2 = ( + node2.get_outer_nodes()[0] + if isinstance(node2, OuterLoopFusedSchedulerNode) + else node2 + ) + if not isinstance(_node2, (FusedSchedulerNode, SchedulerNode)): + raise AssertionError( + "expected isinstance(_node2, (FusedSchedulerNode, SchedulerNode))" + ) + + _, (vars1, reduce1) = _node1.group + _, (vars2, reduce2) = _node2.group + if vars1 == () and vars2 == () and reduce1 != () and reduce2 != (): + # Reduction only + return DISABLE_OUTER_LOOP_FUSION + if all(type(node) is OuterLoopFusedSchedulerNode for node in (node1, node2)): + return ( + node1.outer_loop_fusion_depth + if node1.outer_loop_fusion_depth == node2.outer_loop_fusion_depth + else DISABLE_OUTER_LOOP_FUSION + ) + outer_loop_fusion_depth = min(len(vars1), len(vars2)) + if ( + outer_loop_fusion_depth >= 1 + and vars1[:outer_loop_fusion_depth] == vars2[:outer_loop_fusion_depth] + ): + if any( + type(node) is OuterLoopFusedSchedulerNode for node in (node1, node2) + ): + _compare_node = ( + node1 if type(node1) is OuterLoopFusedSchedulerNode else node2 + ) + if _compare_node.outer_loop_fusion_depth == outer_loop_fusion_depth: + # Same outer loop fusion depth as prev nodes in OuterLoopFusedSchedulerNode + return outer_loop_fusion_depth + else: + return DISABLE_OUTER_LOOP_FUSION + else: + # First 2 nodes to generate OuterLoopFusedSchedulerNode + return outer_loop_fusion_depth + return DISABLE_OUTER_LOOP_FUSION + + def can_fuse_vertical_outer_loop(self, node1, node2): + return ( + not node1.is_template() + and not node2.is_template() + and node1.get_operation_names() & node2.ancestors + and not ( + self._can_fuse_horizontal_impl(node1, node2) + and not node1.is_reduction() + ) + and self._get_outer_loop_fusion_depth(node1, node2) >= 1 + ) + + def get_fusion_pair_priority(self, node1, node2): + if self.can_fuse_vertical_outer_loop(node1, node2): + # Outer loop fusion with lower priority + return 1 + else: + return 0 + + def can_fuse_vertical(self, node1, node2): + if node2.is_template(): + # TODO(jgong5): support pre-op fusion with template + return False + if node1.is_template(): + template_fusion_supported, _ = template_fusion_with_epilogues_supported( + node1, [node2] + ) + return not node2.is_reduction() and template_fusion_supported + return ( + self._can_fuse_horizontal_impl(node1, node2) and not node1.is_reduction() + ) or self.can_fuse_vertical_outer_loop(node1, node2) + + def try_loop_split(self, nodes: list[SchedulerNode]): + """ + Apply loop split optimization. + When one of the indexing_exprs contains a division, we eliminate the division by splitting the loop + to avoid non-contiguous loads, subject to the following conditions: + 1. No reduction and no mudular index for all nodes. + 2. The indexing_exprs of all nodes contain only one (or more, but all the same) division, + where the divisor is an integer and not too small (the divisor > 8), the dividend is + one of the iter_vars, and this var, i.e. the dimension that needs to be split, is + contiguous in all other indexing_exprs. + + For example, if the node's var_ranges: {z0: 2, z1: 9216, z2: 960} and indexing_exprs: + {'index0': 8847360*z0 + 960*z1 + z2, 'index1': 32*z0 + (z2//30), 'index2': z2}, + we will split z2 -> 30*z2 + z3, then the node's var_ranges will be changed to + {z0: 2, z1: 9216, z2: 32, z3: 30} and indexing_exprs will be changed to + {'index0': 8847360*z0 + 960*z1 + 30*z2 + z3, 'index1': 32*z0 + z2, 'index2': 30*z2 + z3}. + """ + + # No reduction and no mudular + if any( + len(node.group[1][1]) != 0 + or any( + expr.has(ModularIndexing) for expr in node._body.indexing_exprs.values() + ) + for node in nodes + ): + return nodes + + split_var = None + split_number = None + num_div = 0 + div_expr_ = None + match_div = False + matched_index_size = None + + # Collect node info for later compatibility check + node_bodies: list[tuple[Any, Any]] = [] + + for node in nodes: + if not isinstance(node.node, ir.ComputedBuffer): + raise AssertionError( + "expected isinstance(node.node, ir.ComputedBuffer)" + ) + sizes_body = node.node.get_default_sizes_body() + node_bodies.append((node, sizes_body)) + (index_size, _), original_body, _ = sizes_body + for name, expr in original_body.indexing_exprs.items(): + if not isinstance(expr, sympy.Expr): + continue + for div_expr in expr.find(FloorDiv): + if ( + any(div_expr.has(var) for var in original_body.iter_vars) + and div_expr != div_expr_ + ): + div_expr_ = div_expr + num_div += 1 + if num_div > 1: + return nodes + if ( + isinstance(div_expr.args[1], sympy.core.numbers.Integer) + and div_expr.args[0] in original_body.iter_vars + and name is not None + and all( + stride_at_vec_range(expr_, div_expr.args[0]) in (0, 1) + for name_, expr_ in original_body.indexing_exprs.items() + if name_ != name + ) + and div_expr.args[1] > 8 + ): + split_var = div_expr.args[0] + split_number = div_expr.args[1] + match_div = True + matched_index_size = index_size + + # Only one node contains a division, and the split dimension is contiguous in all other indexing_exprs. + if not match_div: + return nodes + + # Check if all nodes have split_var in their iter_vars and have compatible sizes + # (same number of index dimensions). If not, bail out to avoid incompatible + # var_ranges after loop split which would cause assertion failures in + # simplify_and_reorder or codegen_functions. + if matched_index_size is None: + raise AssertionError("expected matched_index_size is not None") + matched_num_dims = len(matched_index_size) + + for node, ((index_size, _), original_body, _) in node_bodies: + if split_var not in original_body.iter_vars: + return nodes + if len(index_size) != matched_num_dims: + return nodes + + def loop_split(sizes, body, vars): + index_size, reduce_size = sizes + index_vars, reduce_vars = vars + split_idx = index_vars.index(split_var) + new_index_size = index_size.copy() + new_index_size[split_idx] = index_size[split_idx] // split_number + new_index_size.insert(split_idx + 1, split_number) + (new_index_vars, _), var_ranges = dependencies.index_vars_no_squeeze( + new_index_size, reduce_size, prefix="y" + ) + iter_vars = new_index_vars.copy() + divisor_var = iter_vars.pop(split_idx + 1) + iter_vars[split_idx] = split_number * iter_vars[split_idx] + divisor_var + body = ir.LoopBody( + body, [iter_vars, reduce_vars], var_ranges, new_index_vars, reduce_vars + ) + return ( + (new_index_size, reduce_size), + body, + (new_index_vars, reduce_vars), + ) + + extra_indexing_ranges = None + extra_indexing_exprs = OrderedSet[Any]() + for _, sizes_body in node_bodies: + _, split_body, _ = loop_split(*sizes_body) + if extra_indexing_ranges is None: + extra_indexing_ranges = split_body.var_ranges + if extra_indexing_ranges != split_body.var_ranges: + raise AssertionError( + ( + extra_indexing_ranges, + split_body.var_ranges, + ) + ) + extra_indexing_exprs.update(split_body.indexing_exprs.values()) + + if extra_indexing_ranges is None: + raise AssertionError("extra_indexing_ranges is None") + extra_indexing_constraints = ir.ExtraIndexingConstraints( + extra_indexing_ranges, + list(extra_indexing_exprs), + ) + + snapshots = [(node, node.snapshot_loop_state()) for node in nodes] + for node in nodes: + node.recompute_size_and_body( + extra_indexing_constraints=extra_indexing_constraints, + recompute_sizes_body_func=loop_split, + ) + + # Keep the post-split leaves compatible with CppKernelProxy.codegen_functions. + # If simplification still picks different loop factorizations, skip this + # optional optimization and codegen the original fused pointwise group. + group = nodes[0].group[1] + if any(node.group[1] != group for node in nodes[1:]): + for node, state in reversed(snapshots): + node.restore_loop_state(state) + + return nodes + + def codegen_outer_loop_node( + self, + node: OuterLoopFusedSchedulerNode, + ): + """ + Generate the code for the outer loop fused scheduler node. + 1. Codegen with fused outer loop: depends on the analysis of + the outer loop fused scheduler node, with or without the local buffer. + 2. If failed, fallback to standard codegen. + """ + kernel_group = self.kernel_group + generated_cpp_vec_kernel_count = metrics.generated_cpp_vec_kernel_count + cpp_kernel_proxy_list: list[self.kernel_proxy_cls] = [] # type: ignore[name-defined] + nodes_list: list[list[SchedulerNode]] = [] + if not isinstance(node, OuterLoopFusedSchedulerNode): + raise AssertionError( + "expected isinstance(node, OuterLoopFusedSchedulerNode)" + ) + + def try_outer_loop_fusion_with_local_buf(node: OuterLoopFusedSchedulerNode): + """ + Codegen code with fused outer loop and local Buffer. + """ + if not isinstance(node, OuterLoopFusedSchedulerNode): + raise AssertionError( + "expected isinstance(node, OuterLoopFusedSchedulerNode)" + ) + cpp_kernel_proxy_list.clear() + nodes_list.clear() + + def get_call_ranges(node: BaseSchedulerNode): + if not isinstance(node, (SchedulerNode, FusedSchedulerNode)): + raise AssertionError( + "expected isinstance(node, (SchedulerNode, FusedSchedulerNode))" + ) + nodes: list[SchedulerNode] = node.get_nodes() # type: ignore[assignment] + _, (group, reduction_group) = max( + nodes, key=lambda x: int(x.is_reduction()) + ).group + call_ranges = tuple(group) + tuple(reduction_group) + return call_ranges + + local_buffers: list[ir.Buffer] = [] + # Map local buffer name to a list of global buffers + local_to_global_buffers: dict[str, list[ir.Buffer]] = {} + if all( + len(get_call_ranges(_node)) == node.outer_loop_fusion_depth + 1 + for _node in node.get_outer_nodes() + ): + # Ref to the typical case of local buffer in + # https://github.com/pytorch/pytorch/blob/1115a25c36340554442f28f9570abd42f0aface2/aten/src/ATen/native/cpu/SoftMaxKernel.cpp#L159 + # where the buffer is with size of last dim and contiguous. + # Only support this typical case at first. + visited_scheduler_nodes: OrderedSet[str] = OrderedSet() + for scheduler_node in node.get_nodes(): + # all users inside same OuterLoopFusedSchedulerNode + if not isinstance(scheduler_node, SchedulerNode): + raise AssertionError( + "expected isinstance(scheduler_node, SchedulerNode)" + ) + visited_scheduler_nodes.add(scheduler_node.get_name()) + if ( + scheduler_node.is_reduction() + or len(scheduler_node.get_outputs()) != 1 + ): + continue + + scheduler_buffer = scheduler_node.get_outputs()[0] + if all( + user.node in node.get_nodes() for user in scheduler_buffer.users + ): + global_buffer = scheduler_buffer.node + if not isinstance(global_buffer, ir.ComputedBuffer): + raise AssertionError( + "expected isinstance(global_buffer, ir.ComputedBuffer)" + ) + global_buffer_layout = global_buffer.get_layout() + size_offset = node.outer_loop_fusion_depth - len( + get_call_ranges(scheduler_node) + ) + + def is_all_write_read_contiguous(): + contiguous_index_expr = 0 + stride = 1 + for var, range in reversed( + # pyrefly: ignore [missing-attribute] + scheduler_node._body.var_ranges.items() + ): + contiguous_index_expr += stride * var + stride *= range + # pyrefly: ignore [missing-attribute] + write_index_expr = scheduler_node._body.get_write_expr( + scheduler_buffer.get_name() + ) + + def is_contiguous_index(x): + return x == contiguous_index_expr + + return is_contiguous_index(write_index_expr) and all( + isinstance(user.node, SchedulerNode) + and is_contiguous_index( + user.node._body.get_read_expr( + scheduler_buffer.get_name() + ), + ) + for user in scheduler_buffer.users + ) + + if not ( + global_buffer_layout.is_contiguous() + and is_all_write_read_contiguous() + ): + continue + # Local Buffer is a view of global buffer + local_buffer_stride: list[int] = [] + stride = global_buffer_layout.stride[-1] + local_buffer_size = get_call_ranges(scheduler_node)[ + size_offset: + ] + for sz in reversed(local_buffer_size): + local_buffer_stride.insert(0, stride) + stride *= sz + local_buffer_layout = ir.FixedLayout( + global_buffer_layout.device, + global_buffer_layout.dtype, + local_buffer_size, + local_buffer_stride, + ) + + def try_share_local_buffer(local_buffer_layout, local_buffers): + for local_buf in local_buffers: + if local_buffer_layout == local_buf.layout and all( + all( + user.node.get_name() in visited_scheduler_nodes + for user in V.graph.scheduler.name_to_buf[ + global_buffer.name + ].users + ) + for global_buffer in local_to_global_buffers[ + local_buf.name + ] + if global_buffer.name is not None + ): + return local_buf + return None + + local_buf_prefix = "local_buffer_data" + # Share existing local buffer + local_buffer_used = try_share_local_buffer( + local_buffer_layout, local_buffers + ) + if not local_buffer_used: + # Create new local buffer + local_buffer_used = ir.Buffer( + name=f"{local_buf_prefix}_{len(local_buffers)}", + layout=local_buffer_layout, + ) + local_buffers.append(local_buffer_used) + local_to_global_buffers[local_buffer_used.name] = [] # type: ignore[index] + + local_to_global_buffers[local_buffer_used.name].append( + global_buffer, + ) + + with LocalBufferContext(kernel_group.args) as scope: + if len(local_buffers) > 0: + for local_buffer in local_buffers: + if local_buffer.name is None: + raise AssertionError( + "expected local_buffer.name is not None" + ) + scope.add_local_buffer( + local_buffer, local_to_global_buffers[local_buffer.name] + ) + for _node in node.get_outer_nodes(): + if not isinstance(_node, (FusedSchedulerNode, SchedulerNode)): + raise AssertionError( + "expected isinstance(_node, (FusedSchedulerNode, SchedulerNode))" + ) + cpp_kernel_proxy = self.kernel_proxy_cls(kernel_group) + cpp_kernel_proxy.codegen_nodes(_node.get_nodes()) # type: ignore[arg-type] + cpp_kernel_proxy_list.append(cpp_kernel_proxy) + nodes_list.append(_node.get_nodes()) # type: ignore[arg-type] + + def fallback_without_local_buffers() -> Literal[False]: + for removed_buffer in scope.removed_buffers: + # Restore the removed buffers by this context before + # fallback to codegen without using Local Buffer. + V.graph.removed_buffers.remove(removed_buffer) + return False + + # Local buffers omit fused outer dimensions. If an omitted + # outer loop is tiled, one local buffer slot would be reused for + # multiple outer elements in the same loop iteration. + def has_tiled_fused_outer_loop() -> bool: + for cpp_kernel_proxy in cpp_kernel_proxy_list: + loop_nest = cpp_kernel_proxy.loop_nest + if loop_nest is None: + raise AssertionError("expected loop_nest is not None") + loops = loop_nest.loops + if loops is None: + raise AssertionError("expected loops is not None") + for loop in loops[: node.outer_loop_fusion_depth]: + if loop.steps != sympy.S.One: + return True + return False + + if len(local_buffers) > 0 and has_tiled_fused_outer_loop(): + return fallback_without_local_buffers() + + if not node.check_outer_fusion_loop_level_attr( + cpp_kernel_proxy_list, node.outer_loop_fusion_depth + ): + return fallback_without_local_buffers() + metrics.cpp_outer_loop_fused_inner_counts.append( + metrics.CppOuterLoopFusedCount( + len(cpp_kernel_proxy_list), + local_buffer_number=len(scope.local_buffers), + ) + ) + outer_fusion_cpp_kernel_proxy = node.merge_outer_fusion_kernels( + cpp_kernel_proxy_list, + ) + kernel_group.finalize_kernel( + outer_fusion_cpp_kernel_proxy, + [*itertools.chain.from_iterable(nodes_list)], + ) + + return True + + if not try_outer_loop_fusion_with_local_buf(node): + # Reset generated_cpp_vec_kernel_count to codegen again + metrics.generated_cpp_vec_kernel_count = generated_cpp_vec_kernel_count + cpp_kernel_proxy_list.clear() + nodes_list.clear() + # Similar as comment in + # https://github.com/pytorch/pytorch/blob/469383755fe416eb1c41fa724762ad3eaecdff07/torch/_inductor/codegen/cpp.py#L3269-L3272 + # Kernels share the same global contexts like V.graph.wrapper_code, V.kernel.args. + with torch._inductor.config.patch(inplace_buffers=False): + for _node in node.get_outer_nodes(): + if not isinstance(_node, (FusedSchedulerNode, SchedulerNode)): + raise AssertionError( + "expected isinstance(_node, (FusedSchedulerNode, SchedulerNode))" + ) + _nodes: list[SchedulerNode] = _node.get_nodes() # type: ignore[assignment] + cpp_kernel_proxy = self.kernel_proxy_cls(kernel_group) + cpp_kernel_proxy.codegen_nodes(_nodes) + kernel_group.finalize_kernel(cpp_kernel_proxy, _nodes) + + def codegen_node( + self, + node: OuterLoopFusedSchedulerNode | FusedSchedulerNode | SchedulerNode, + ): + """ + Turn a set of pre-fused nodes into a C++ kernel. + """ + kernel_group = self.kernel_group + + if isinstance(node, OuterLoopFusedSchedulerNode): + self.codegen_outer_loop_node(node) + else: + nodes: list[SchedulerNode] = node.get_nodes() # type: ignore[assignment] + nodes = self.try_loop_split(nodes) + cpp_kernel_proxy = self.kernel_proxy_cls(kernel_group) + cpp_kernel_proxy.codegen_nodes(nodes) + kernel_group.finalize_kernel(cpp_kernel_proxy, nodes) + + args_num = self._get_scheduled_num_args() + if args_num > CppScheduling.MAX_FUSED_KERNEL_ARGS_NUM: + self._set_flush_status(True) + + def is_cpp_template(self, node: BaseSchedulerNode) -> bool: + return isinstance(node, SchedulerNode) and isinstance( + node.node, ir.CppTemplateBuffer + ) + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + ): + """ + Codegen a CPP template, possibly with fused epilogues + """ + if prologue_nodes: + raise AssertionError("expected not prologue_nodes") + + # remove MultiOutput from epilogue_nodes + epilogue_nodes = [ + epilogue_node + for epilogue_node in epilogue_nodes + if isinstance(epilogue_node, (SchedulerNode, FusedSchedulerNode)) + ] + # The counter cpp_templated_kernel_counter is used for verifying if a + # a templated kernel was successfully compiled in a UT + counters["inductor"]["cpp_templated_kernel_counter"] += 1 + counters["inductor"]["cpp_epilogue_fusion_counter"] += len(epilogue_nodes) + if not (self.is_cpp_template(template_node)): + raise AssertionError( + "Template node passed to CppScheduler.codegen_template must be a SchedulerNode that wraps a CppTemplateBuffer" + ) + template_node = cast(SchedulerNode, template_node) + _, (_, rnumel) = template_node.group + if rnumel != (): + raise AssertionError("expected rnumel == ()") + ctb: ir.CppTemplateBuffer = cast(ir.CppTemplateBuffer, template_node.node) + epilogue_ir_nodes: list[ir.Operation | None] = [n.node for n in epilogue_nodes] + if not (all(isinstance(n, ir.ComputedBuffer) for n in epilogue_ir_nodes)): + raise AssertionError( + "Epilogue nodes must all be instances of ir.ComputedBuffer" + ) + + def template_buffer_has_other_users( + template_buffer, outputs_by_name, epilogue_nodes + ): + if not epilogue_nodes: + return False + + if template_buffer.get_name() not in outputs_by_name: + raise AssertionError( + "expected template_buffer.get_name() in outputs_by_name" + ) + users = outputs_by_name[template_buffer.get_name()].users + return not all( + isinstance(user.node, BaseSchedulerNode) + and user.node.node in epilogue_nodes + for user in users + ) + + flag_template_buffer_has_other_users = template_buffer_has_other_users( + ctb, template_node.outputs_by_name, epilogue_ir_nodes + ) + kernel, render = ctb.make_kernel_render( # type: ignore[misc] + ctb, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_ir_nodes, + ) + with kernel: + if not is_multi_outputs_template(template_node.node): + template_node.mark_run() # type: ignore[attr-defined] + for node in epilogue_nodes: + node.mark_run() # type: ignore[attr-defined] + src_code = render() + + with V.set_kernel_handler(kernel): + node_schedule = [template_node, *epilogue_nodes] + kernel_name = self.define_kernel(src_code, node_schedule, kernel.args) + + if is_multi_outputs_template(template_node.node): + # For multi outputs template, allocate buffers for each output after the epilogue + # codegen to which determines if the buffer has been removed. + if len(template_node.outputs) != 1: + raise AssertionError( + "Multi outputs template should be with 1 output template buffer of MultiOutputLayout" + ) + for user in template_node.outputs[0].users: + if not isinstance(user.node, ExternKernelSchedulerNode): + raise AssertionError( + "Multi outputs template should be with ExternKernelSchedulerNode" + ) + if not isinstance(user.node.node, ir.MultiOutput): + raise AssertionError( + "Multi outputs template has multi users with MultiOutput" + ) + user.node.mark_run() + + self.codegen_comment(node_schedule, kernel_name) + kernel.call_kernel(kernel_name, ctb) + V.graph.removed_buffers |= kernel.removed_buffers + self.free_buffers_in_scheduler() + + def _get_scheduled_num_args(self): + return self.kernel_group.get_num_args() + + def ready_to_flush(self): + return self._ready_to_flush + + def codegen_sync(self): + pass + + def define_kernel(self, src_code, nodes, kernel_args=None): + wrapper = V.graph.wrapper_code + if src_code in wrapper.src_to_kernel: + kernel_name = wrapper.src_to_kernel[src_code] + else: + fused_name = ( + get_fused_kernel_name(nodes, config.cpp.descriptive_names) + if config.cpp.descriptive_names + else "" + ) + kernel_name = "_".join(["cpp", fused_name, wrapper.next_kernel_suffix()]) + wrapper.src_to_kernel[src_code] = kernel_name + kernel_decl_name = kernel_name if V.graph.cpp_wrapper else "kernel" + src_code = src_code.replace(str(Placeholder.KERNEL_NAME), kernel_decl_name) + src_code = src_code.replace(str(Placeholder.DESCRIPTIVE_NAME), kernel_name) + # TODO(voz): Ostensibly, we should not need this. But there are cases where C++ codegen does + # not use BracesBuffer, so we have no good indicator of a C++ buffer atm. + src_code = src_code.replace("#pragma CMT", "//") + + # Get the lines in the source code representing the function definition, + # excluding the first line including cpp_prefix.h. + first_char = src_code.rfind('extern "C"') + last_char = src_code.find(")", first_char) + if _IS_WINDOWS: + # get_export_declaration introduced one more ')' in Windows + last_char = src_code.find(")", last_char + 1) + kernel_definition = f"{src_code[first_char : last_char + 1]};\n" + + compile_wrapper = IndentedBuffer() + args = self.kernel_group.args if kernel_args is None else kernel_args + _, _, arg_types = args.cpp_argdefs() + if not V.graph.cpp_wrapper: + compile_wrapper.writeline( + f"async_compile.cpp_pybinding({arg_types!r}, r'''" + ) + compile_wrapper.splice(src_code, strip=True) + if not V.graph.cpp_wrapper: + compile_wrapper.writeline("''')") + wrapper.define_kernel( + kernel_name, + compile_wrapper.getvalue(), + gpu=False, + cpp_definition=kernel_definition, + ) + return kernel_name + + def flush(self): + src_code = self.kernel_group.codegen_group() + if src_code: + kernel_name = self.define_kernel( + src_code, self.kernel_group.scheduled_nodes + ) + self.codegen_comment(self.kernel_group.scheduled_nodes, kernel_name) + if config.cpp.enable_kernel_profile: + V.graph.wrapper_code.write_kernel_context_guard_begin() + if ( + config.cpp.enable_kernel_profile + and config.cpp.enable_kernel_context_guard + ): + V.graph.wrapper_code.write_kernel_context_guard( + kernel_name, + self.kernel_group.scheduled_nodes, # type: ignore[arg-type] + ) + self.kernel_group.call_kernel(V.graph.wrapper_code, kernel_name) + if config.cpp.enable_kernel_profile: + V.graph.wrapper_code.write_kernel_context_guard_end() + + self.reset_kernel_group() + self._set_flush_status(False) + + def codegen_comment(self, node_schedule, kernel_name=None): + # below add provenance tracing info for cpu CppKernel types + wrapper = V.graph.wrapper_code + debug_handle = set_kernel_post_grad_provenance_tracing( + node_schedule, # type: ignore[arg-type] + # pyrefly: ignore [bad-argument-type] + kernel_name, + ) + wrapper.write_provenance_debug_handle(kernel_name, debug_handle) + + +class KernelGroup: + def __init__(self): + super().__init__() + self.args = KernelArgs() + self.loops_code = BracesBuffer() + self.ws = WorkSharing(self.loops_code) + self.stack = contextlib.ExitStack() + self.stack.enter_context(self.ws) + self.scheduled_nodes = [] + + def new_kernel(self, cls, *args): + return cls(self.args, parallel_num_threads(), *args) + + def finalize_kernel(self, new_kernel, nodes): + self.scheduled_nodes += nodes + code = self.loops_code + ws = self.ws + new_kernel.codegen_loops(code, ws) + + def get_num_args(self): + arg_defs, _call_args, _arg_types = self.args.cpp_argdefs() + args_num = len(arg_defs) + return args_num + + def codegen_group(self, name=None) -> str: + self.stack.close() + if not self.scheduled_nodes: + return "" + code = BracesBuffer() + # 1. Include header files + # TODO: support kernel profile on other platforms + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + if enable_kernel_profile: + code.writelines(["#include "]) + code.writeline("#include ") + + # 2. Function definition + kernel_decl_name = str(Placeholder.KERNEL_NAME) if name is None else name + kernel_name = str(Placeholder.DESCRIPTIVE_NAME) if name is None else name + arg_defs, _, _ = self.args.cpp_argdefs() + arg_defs = ",\n".ljust(25).join(arg_defs) + func_export_decl = get_export_declaration() + inline_attr = ( + "C10_ALWAYS_INLINE_ATTRIBUTE" if config.cpp.force_inline_kernel else "" + ) + code.writeline( + f'extern "C" {func_export_decl} void {inline_attr} {kernel_decl_name}({arg_defs})' + ) + + # 3. Function body + with code.indent(): + code.writeline("std::atomic inductor_cpu_integer_div_error{0};") + code.writeline( + "inductor_cpu_integer_div_error_flag = &inductor_cpu_integer_div_error;" + ) + if enable_kernel_profile: + graph_id = V.graph.graph_id + prefix = "graph_" + str(graph_id) + "_" if graph_id is not None else "" + code.writelines( + [ + ( + "torch::aot_inductor::RAIIAtenRecordFunctionHandle " + f'record_{prefix + kernel_name}_("{prefix + kernel_name}", nullptr);' + ) + ] + ) + for old, new in self.args.aliases(): + code.writeline(f"auto {old} = {new};") + code.splice(self.loops_code) + code.writeline("inductor_cpu_integer_div_error_flag = nullptr;") + code.writeline( + "inductor_cpu_throw_if_integer_div_error(inductor_cpu_integer_div_error);" + ) + return code.getvalue() + + def call_kernel(self, wrapper, kernel_name): + _, call_args, arg_types = self.args.cpp_argdefs() + wrapper.generate_kernel_call( + kernel_name, + call_args, + triton=False, + arg_types=arg_types, + ) + + +class WorkSharing: + def __init__(self, code): + self.code = code + self.in_parallel = False + self.num_threads = None + self.stack = contextlib.ExitStack() + + def parallel(self, threads): + if self.in_parallel and threads != self.num_threads: + # wrong number of threads + self.close() + if not self.in_parallel: + self.num_threads = threads + self.in_parallel = True + # Decide whether to use dynamic threading + use_dynamic = False + if config.cpp.threads >= 1: + # User explicitly set config.cpp.threads (hardcode it) + use_dynamic = False + elif threads == os.cpu_count(): + # Thread count matches system CPU count (most likely default, use dynamic) + use_dynamic = True + else: + # Thread count differs from system (user probably set it so hardcode) + use_dynamic = False + + if use_dynamic or config.cpp.dynamic_threads: + self.code.writeline("#pragma omp parallel") + else: + self.code.writeline(f"#pragma omp parallel num_threads({threads})") + self.stack.enter_context(self.code.indent()) + self.code.writeline( + "int tid = omp_get_thread_num();", + ) + + def single(self): + if self.in_parallel: + self.code.writeline("#pragma omp single") + return self.in_parallel + + def close(self): + self.stack.close() + self.in_parallel = False + + def __enter__(self): + self.stack.__enter__() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.stack.__exit__(exc_type, exc_val, exc_tb) + + +@dataclasses.dataclass +class LoopLevel: + var: sympy.Expr | None = None + size: sympy.Expr | None = None + offset: sympy.Expr = sympy.S.Zero + # Note [tiled_size] + # We may do loop-tiling at this loop level. + # When var is in [offset, tiled_size), we will perform the vectorization kernel. + # When var is in [tiled_size, size), we will perform the scalar or masked vectorization kernel. + # for (var = offset; var < size; var += steps) { + # if (var >= offset && var < tiled_size) vec_loop_body(); + # if (var >= tiled_size && var < size) scalar_or_maskvec_loop_body(); + # } + tiled_size: sympy.Expr = sympy.S.Zero + steps: sympy.Expr = sympy.S.One + parallel: int = 0 + simd_omp: bool = False + simd_vec: bool = False + collapsed: bool = False + is_reduction: bool = False + + def __post_init__(self): + # Regarding the C++/OpenMP backend, `cpu_vec_isa.pick_vec_isa()` to check + # vectorization ISA is a time-consuming and one-shot operation. It leads + # to taking a longer time to import `codegen.cpp` package because the + # `LoopLevel` of the package is decorated by `@dataclasses.dataclass` while + # the decorator will invoke `cpu_vec_isa.pick_vec_isa()` to initialize the + # `simd_nelements` of the `LoopLevel`. It might introduce additional compilation + # overhead to the Triton backend. Therefore, we moved the `simd_nelements` to + # `__post_init__` + picked_vec_isa: cpu_vec_isa.VecISA = cpu_vec_isa.pick_vec_isa() + self.simd_nelements: int = picked_vec_isa.nelements() if picked_vec_isa else 0 + + def tile(self, factor): + sympy_factor = sympy.Integer(factor) + loop = LoopLevel(self.var, self.size) + loop.steps = sympy_factor + loop.simd_vec = True + loop.tiled_size = FloorDiv(loop.size, sympy_factor) * sympy_factor + loop.parallel = self.parallel + loop.collapsed = False + loop.is_reduction = self.is_reduction + return loop + + def lines(self): + offset_expr = cexpr_index(self.offset) + size_expr = cexpr_index(self.size) + if config.cpp.no_redundant_loops and offset_expr == size_expr: + return None + simd = ( + f"simd simdlen({self.simd_nelements}) " + if self.simd_omp and self.simd_nelements > 1 + else "" + ) + if self.parallel: + # TODO(jansel): look into chunk size and other schedules + line1 = "#pragma omp for" + if self.parallel > 1: + line1 += f" collapse({self.parallel})" + if self.simd_omp: + line1 = line1.replace(" for ", f" for {simd}") + elif self.simd_vec: + line1 = "" + elif self.simd_omp: + line1 = f"#pragma omp {simd}" + elif not self.is_reduction and cpp_builder.is_gcc(): + line1 = "#pragma GCC ivdep" + else: + line1 = "" + offset_str = f"{INDEX_TYPE} {self.var}={offset_expr}" + size_str = f"{self.var}<{size_expr}" + if self.steps.is_number: + steps_str = f"{self.var}+={cexpr_index(self.steps)}" + else: + # If the step size is 0, change it to 1 because a step size of 0 + # will cause floating point exception (core dump) during parallelization. + steps_str = ( + f"{self.var}+=({cexpr_index(self.steps)} == 0 ? " + f"1 : {cexpr_index(self.steps)})" + ) + line2 = f"for({offset_str}; {size_str}; {steps_str})" + if self.collapsed or not line1: + return [line2] + return [line1, line2] + + +@dataclasses.dataclass +class LoopNest: + """ + A loop-nest-like structure. It is built with the `build` method + as a loop nest and then will perform loop-tiling at some depth. + + A typical case is for vectorization, where we typically do loop-tiling + at the innermost loop level. A more complicated case is when we do + 2D tiling at both the innermost and outer levels. + """ + + loops: list[LoopLevel] | None = None + kernel: CppKernel | None = None + + @staticmethod + def build(kernel: CppKernel): + """Build a LoopNest with the given `kernel` as the leaf""" + itervars = kernel.itervars + ranges = kernel.ranges + reduction_depth = kernel.reduction_depth + if reduction_depth is None: + raise AssertionError("expected reduction_depth is not None") + + loops: list[LoopLevel] | None = None + for loop_idx, (var, size) in enumerate(zip(itervars, ranges)): + loop = LoopLevel(var, size) + if not loops: + loops = [loop] + else: + loops.append(loop) + if loop_idx >= reduction_depth: + loop.is_reduction = kernel.is_reduction + + loop_nest = LoopNest(loops) + return loop_nest + + def __bool__(self): + return bool(self.loops) + + @cache_on_self + def max_parallel_depth(self): + """ + Maximal allowed depth for parallelism: All reduction or non-reduction levels. + When the range of the first inner loop beyond the maximum parallel depth is much + larger than the range of all outer loops within the maximum parallel depth, + change the starting depth of parallelism to the first inner loop and recalculate + the maximum parallel depth. + """ + if self.loops is None: + return ParallelDepth(parallel_depth=0, start_depth=0) + + start_depth = 0 + max_depth = 0 + is_reduction = self.loops[0].is_reduction + num_steps = sympy.Integer(1) + for loop in self.loops: + if loop.is_reduction != is_reduction: + break + num_steps = num_steps * FloorDiv(loop.size, loop.steps) + max_depth += 1 + + def get_simd_vec_depth(loops): + # Return the first loop level which is simd_vec + for i, loop in enumerate(loops): + if loop.simd_vec: + return i + return None + + simd_vec_depth = get_simd_vec_depth(self.loops) + + def has_scalar_kernel(loop_nest: LoopNest): + if not isinstance(loop_nest.kernel, CppKernelProxy): + raise AssertionError( + "expected isinstance(loop_nest.kernel, CppKernelProxy)" + ) + return any( + not isinstance(kernel, CppVecKernel) + for kernel in loop_nest.kernel.kernels + ) + + # When the number of steps of the first inner loop is much larger than the number of steps of + # all outer loops, change `start_depth` to the first inner loop and recalculate `max_depth`. + if ( + max_depth < len(self.loops) + and isinstance(num_steps, sympy.Integer) + and isinstance(self.loops[max_depth].size, sympy.Integer) + and num_steps * 300 + < FloorDiv(self.loops[max_depth].size, self.loops[max_depth].steps) + and not ( + # Disable parallel reduction under the vec loop + simd_vec_depth is not None + and max_depth > simd_vec_depth + and self.loops[max_depth].is_reduction + and has_scalar_kernel(self) + ) + ): + start_depth = max_depth + max_depth = 0 + is_reduction = self.loops[start_depth].is_reduction + for i in range(start_depth, len(self.loops)): + if self.loops[i].is_reduction != is_reduction: + break + max_depth += 1 + return ParallelDepth(parallel_depth=max_depth, start_depth=start_depth) + + def mark_parallel(self, par_depth): + if par_depth.parallel_depth > self.max_parallel_depth().parallel_depth: + raise AssertionError( + "Parallel depth cannot exceed the maximal allowed parallel depth" + ) + if self.loops is None: + raise AssertionError("expected self.loops is not None") + if len(self.loops) < par_depth.parallel_depth: + raise AssertionError("expected len(self.loops) >= par_depth.parallel_depth") + loop = self.loops[par_depth.start_depth] + loop.parallel = par_depth.parallel_depth + if loop.is_reduction: + # pyrefly: ignore [bad-assignment] + metrics.parallel_reduction_count += 1 + for i in range(par_depth.start_depth + 1, par_depth.parallel_depth): + self.loops[i].collapsed = True + + def tile(self, depth, factor): + """ + Do loop-tiling at the `depth` level with `factor`. + for (x0 = 0; x0 < x0_end; x0++) + -> + for (x0 = 0; x0 < x0_end; x0 += factor) + See details in Note [tiled_size]. + """ + if not self.loops: + raise AssertionError("expected self.loops") + self.loops[depth] = self.loops[depth].tile(factor) + return self.loops[depth] + + def get_kernel(self) -> CppKernel: + if not self.kernel: + raise AssertionError("expected self.kernel") + return self.kernel + + def set_kernel(self, kernel): + self.kernel = kernel + + def from_loop_level(self, level: int): + if not self.loops: + raise AssertionError("expected self.loops") + if len(self.loops) < level: + raise AssertionError("expected len(self.loops) >= level") + loops = None if level == len(self.loops) else self.loops[level:] + return LoopNest(loops, self.kernel) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_bmm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_bmm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..1c8d324a13dee32dd1a0168e6374d8880d568511 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_bmm_template.py @@ -0,0 +1,270 @@ +# mypy: allow-untyped-defs +import contextlib +import itertools +from collections.abc import Callable +from typing import Any +from unittest.mock import patch + +import sympy + +from .. import ir +from ..select_algorithm import PartialRender +from ..virtualized import V +from .common import ArgName +from .cpp_gemm_template import CppGemmTemplate, GEMM_TEMPLATE +from .cpp_micro_gemm import LayoutType +from .cpp_template_kernel import CppTemplateKernel +from .cpp_utils import DTYPE_TO_CPP, GemmBlocking + + +# We pass all sizevars present in BY to the GEMM templates so variables are not renamed in the BMM definition +GEMM_SINGLE_THREAD_MM_STUB = r""" +{{kernel.def_kernel( + inputs={"X": X, "W": W}, + outputs={"Y": Y_2d}, + aliases=aliases, + function_name=kernel_name+"_single_thread_mm", + extra_sizevars=BY_sizevars + [b_index], + placeholder="")}}""" + +GEMM_THREADED_MM_STUB = r""" +{{kernel.def_kernel( + inputs={"X": X, "W": W}, + outputs={"Y": Y_2d}, + aliases=aliases, + function_name=kernel_name+"_threaded_mm", + extra_sizevars=BY_sizevars + [b_index], + placeholder="")}}""" + +BMM_TEMPLATE = r""" +{{ template.codegen_microkernel_def() }} +{{ template.codegen_single_thread_gemm() }} +{{ template.codegen_multi_thread_gemm() }} + +extern "C" +{{kernel.def_kernel(inputs={"X": BX, "W": BW}, outputs={"Y": BY}, aliases=aliases)}} +{ + const int64_t B = {{kernel.size(BY_2d, 0)}}; + {%- if num_threads > 1 %} + constexpr int64_t num_threads = {{num_threads}}; + int64_t B_single_thread_block = (B / num_threads) * num_threads; + + {%- set use_dynamic_threads = ((config.cpp.threads < 1) and (num_threads == cpu_count)) or config.cpp.dynamic_threads %} + {%- if use_dynamic_threads %} + #pragma omp parallel for + {%- else %} + #pragma omp parallel for num_threads({{num_threads}}) + {%- endif %} + {%- else %} + int64_t B_single_thread_block = B; + {%- endif %} + for (int64_t b_start = 0; b_start < B_single_thread_block; ++b_start) { + {{template.get_gemm_function_call( + kernel, + kernel_name+"_single_thread_mm", + "", + b_index="b_start", + )}} + } + for (int64_t b_start = B_single_thread_block; b_start < B; ++b_start) { + {{template.get_gemm_function_call( + kernel, + kernel_name+"_threaded_mm", + "", + b_index="b_start", + )}} + } +} +""" + + +class CppBmmTemplate(CppGemmTemplate): + def __init__( + self, + input_nodes, + layout: ir.Layout, + num_threads: int, + register_blocking: GemmBlocking, + beta=1, + alpha=1, + has_bias=False, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + should_block_weights: bool = False, + name="bmm", + ): + """ + In order to simplify the implementation and increase code reuse, the BMM template implements + two versions of the GEMM kernel: a single-threaded version and a multi-threaded version. + GEMM kernels are called in a loop over the batch dimension, with single-threaded GEMM calls + for all but the last (B % num_threads), which are handled by the multi-threaded GEMM kernel. + + We use an extra sizevar `b_index` to index the batch dimension, which we pass into the GEMM + template as a sympy.Symbol. This allows us to slice the 3D batch tensors in the GEMM template + without any changes to the GEMM template itself. + """ + super().__init__( + input_nodes, + layout, + num_threads, + register_blocking, + beta=beta, + alpha=alpha, + has_bias=has_bias, + epilogue_creator=epilogue_creator, + should_block_weights=should_block_weights, + name=name, + ) + self.b_index = sympy.Symbol("s_b_index", integer=True, nonnegative=True) + + @staticmethod + def get_padded_size(n, block_n, k, should_block_weight): + if should_block_weight: + # Tensor is constant or not contiguous, so we will pad and block + new_size, padded_n = CppGemmTemplate.get_padded_size( + n, block_n, k, should_block_weight + ) + # Add the new batch dimension + new_size.insert(0, -1) + return new_size, padded_n + else: + new_size = [-1, k, n] + return new_size, n + + @staticmethod + def check_if_block_weight(W, micro_gemm): + if not isinstance(W, ir.IRNode): + raise AssertionError(f"expected W to be an ir.IRNode, got {type(W)}") + _, n = W.get_size()[-2:] + result = ( + not W.get_layout().is_contiguous() + or W.get_name() in V.graph.constants + or ( + n % micro_gemm.register_blocking.block_n != 0 + and micro_gemm.get_b_layout != LayoutType.NORMAL + ) + ) + return result + + def get_gemm_function_call( + self, + kernel: CppTemplateKernel, + function_name: str, + placeholder: str, + b_index: str, + ) -> str: + """ + Similar to 'def_kernel' in cpp_template_kernel, but instead of generating a function definition, + generate a function call for the GEMM kernel. + Args: + placeholder: The string to replace the function call with + b_index: The index for slicing the 3D batch tensors + """ + + def hook(): + arg_defs, call_args, _, _ = kernel.args.python_argdefs() + for i, buf in enumerate(call_args): + if buf == self.b_index: + arg_defs[i] = ArgName(b_index) + call = f"{function_name}({', '.join(x.full_name() for x in arg_defs)});" + return call + + if placeholder in kernel.render_hooks: + raise AssertionError(f"render hook already registered for {placeholder}") + kernel.render_hooks[placeholder] = hook + return placeholder + + def get_default_reindexers(self, epilogues): + def reindexer(args): + # if epilogue nodes exist, they have 3D ranges but args are 2D, so add 0 index + return [self.b_index] + args + + return [reindexer] * len(epilogues) + + def get_options( + self, + kernel: CppTemplateKernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + flag_template_buffer_has_other_users: bool | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + **kwargs, + ) -> dict[str, Any]: + options = super().get_options( + kernel=kernel, + template_buffer_node=template_buffer_node, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_nodes, + **kwargs, + ) + + BX, BW, BY = options["X"], options["W"], options["Y"] + options["BX"], options["BW"], options["BY"] = BX, BW, BY + options["BY_2d"] = options["Y_2d"] + for kword in ["X", "W", "GemmOut", "Y_2d"]: + options[kword] = kernel.select(options[kword], 0, self.b_index) + for kword in ["X", "W", "Y_2d"]: + options[kword + "_dtype"] = DTYPE_TO_CPP[options[kword].dtype] + options["b_index"] = self.b_index + options["BY_sizevars"] = [ + s + for sym in itertools.chain(BY.get_size(), BY.get_stride()) + if isinstance(sym, sympy.Expr) + for s in sym.free_symbols + ] + options["kernel_name"] = kernel.kernel_name + + return options + + def render( # type: ignore[override, return] + self, + kernel: CppTemplateKernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + flag_template_buffer_has_other_users: bool | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + **kwargs, + ) -> str: + options = self.get_options( + kernel=kernel, + template_buffer_node=template_buffer_node, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_nodes, + **kwargs, + ) + self.render_options = options + + with contextlib.ExitStack() as stack: + for buf in options["fake_buffers"]: + stack.enter_context( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf)) + ) + result = self._template_from_string(BMM_TEMPLATE).render(**options) + + # Finalize the function definitions for the gemm routines + sub_mm_hooks = { + name: hook + for name, hook in kernel.render_hooks.items() + if "FOR_BMM" in name + } + result = PartialRender(result, sub_mm_hooks).finalize_all() + for name in sub_mm_hooks: + del kernel.render_hooks[name] + del kernel.args.sizevars[options["b_index"]] + return result + + def codegen_single_thread_gemm(self): + stub = self._template_from_string(GEMM_SINGLE_THREAD_MM_STUB).render( + self.render_options + ) + return stub + self._template_from_string(GEMM_TEMPLATE).render( + {**self.render_options, "num_threads": 1} + ) + + def codegen_multi_thread_gemm(self): + stub = self._template_from_string(GEMM_THREADED_MM_STUB).render( + self.render_options + ) + return stub + self._template_from_string(GEMM_TEMPLATE).render( + self.render_options + ) + + def codegen_gemm_stub_def(self): + return "" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_flex_attention_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_flex_attention_template.py new file mode 100644 index 0000000000000000000000000000000000000000..87bedb35d0716dbd2ca384ecd92c101bb75f3cb7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_flex_attention_template.py @@ -0,0 +1,1515 @@ +# mypy: allow-untyped-defs +import contextlib +import logging +import re +from unittest.mock import patch + +import sympy + +import torch +import torch.utils + +from ...utils._ordered_set import OrderedSet +from .. import ir +from ..ir import TensorBox +from ..select_algorithm import DataProcessorTemplateWrapper +from ..utils import parallel_num_threads +from ..virtualized import V +from .cpp_template import CppTemplate +from .cpp_utils import GemmBlocking + + +log = logging.getLogger(__name__) + +# TODO: reuse cpp codegen to generate below pointwise/reduction kernels +SOFTMAX_FUSIONS = r""" +// 1) out = exp(a - val) +// 2) val = sum(out) +template +inline void {{kernel_name}}_exp_reduce_sum_fusion_kernel( + T1* a, + const int& size, + T2* out, + T1& val) { + auto vec_size = at::vec::Vectorized::size(); + auto vec_max = at::vec::Vectorized(val); + T1 tmp_sum = 0; + auto vec_tmp_sum = at::vec::Vectorized(tmp_sum); + for (long i = 0; i < vec_size * (size / vec_size); i += vec_size) { + auto tmp0 = at::vec::Vectorized::loadu(a + i); + auto tmp1 = tmp0 - vec_max; + auto tmp2 = tmp1.exp_u20(); + vec_tmp_sum += tmp2; + at::native::_store(out + i, tmp2); + } + tmp_sum = at::vec::vec_reduce_all( + [](at::vec::Vectorized& x, at::vec::Vectorized& y) { + return x + y; + }, + vec_tmp_sum); + for (long i = vec_size * (size / vec_size); i < size; i++) { + auto tmp0 = a[i]; + auto tmp1 = tmp0 - val; + auto tmp2 = exp(tmp1); + tmp_sum += tmp2; + out[i] = tmp2; + } + val = tmp_sum; +} + +// 1) out = a * scale +// 2) max = max(out) +template +inline void {{kernel_name}}_mul_reduce_max_fusion_kernel( + const scalar_t* a, + const scalar_t& scale, + const int& size, + scalar_t* out, + scalar_t& max) { + auto vec_size = at::vec::Vectorized::size(); + auto vec_scale = at::vec::Vectorized(scale); + scalar_t tmp_max = -std::numeric_limits::infinity(); + auto vec_tmp_max = at::vec::Vectorized(tmp_max); + for (long i = 0; i < vec_size * (size / vec_size); i += vec_size) { + auto tmp0 = at::vec::Vectorized::loadu(a + i); + auto tmp1 = tmp0 * vec_scale; + vec_tmp_max = at::vec::maximum(vec_tmp_max, tmp1); + at::native::_store(out + i, tmp1); + } + for (long i = vec_size * (size / vec_size); i < size; i++) { + auto tmp0 = a[i]; + auto tmp1 = tmp0 * scale; + tmp_max = std::max(tmp_max, tmp1); + out[i] = tmp1; + } + max = std::max( + tmp_max, + at::vec::vec_reduce_all( + [](at::vec::Vectorized& x, at::vec::Vectorized& y) { + return at::vec::maximum(x, y); + }, + vec_tmp_max)); +} + +template +static inline scalar_t* {{kernel_name}}_conditional_data_ptr(scalar_t* ptr, scalar_t* ptr2) { + TORCH_CHECK(ptr2 == nullptr); + return ptr; +} + +template , int> = 0> +static inline scalar_t* {{kernel_name}}_conditional_data_ptr(float* ptr, scalar_t* ptr2) { + return ptr2; +} + +template +inline void {{kernel_name}}_fill_stub(scalar_t* data, scalar_t val, int64_t size) { + using Vec = at::vec::Vectorized; + Vec data_vec = Vec(val); + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + data_vec.store(data + d); + } + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (; d < size; d++) { + data[d] = val; + } +} + +// out = a * scale +template +inline void {{kernel_name}}_mul_scale_kernel( + scalar_t* a, + scalar_t scale, + int64_t size) { + auto vec_size = at::vec::Vectorized::size(); + auto vec_scale = at::vec::Vectorized(scale); + for (int64_t i = 0; i < vec_size * (size / vec_size); i += vec_size) { + auto tmp0 = at::vec::Vectorized::loadu(a + i); + auto tmp1 = tmp0 * vec_scale; + at::native::_store(a + i, tmp1); + } + for (int64_t i = vec_size * (size / vec_size); i < size; i++) { + auto tmp0 = a[i]; + auto tmp1 = tmp0 * scale; + a[i] = tmp1; + } +} + +""" + +BRGEMM_PACK_FUNCTIONS = r""" +template +inline void {{kernel_name}}_copy_value_with_pad( + const scalar_t* value_ptr, + scalar_t* dst_ptr, + int64_t rows, + int64_t cols, + int64_t prows, + int64_t pcols, + int64_t ldi) { + auto vec_size = at::vec::Vectorized::size(); + int64_t i = 0; + for (; i < rows; i++) { + int64_t j = 0; + for (; j < cols - (cols % vec_size); j += vec_size) { + auto vec_v = + at::vec::Vectorized::loadu(value_ptr + i * ldi + j); + vec_v.store(dst_ptr + i * pcols + j); + } + + if (j < cols) { + auto vec_v = at::vec::Vectorized::loadu( + value_ptr + i * ldi + j, cols - j); + vec_v.store(dst_ptr + i * pcols + j, cols - j); + } + + // col padding + auto psize = pcols - cols; + if (psize > 0) { + auto zero_vec = at::vec::Vectorized(0); + int64_t pj = 0; + for (; pj < psize - (psize % vec_size); pj += vec_size) { + zero_vec.store(dst_ptr + i * pcols + cols + pj); + } + if (pj < psize) { + zero_vec.store(dst_ptr + i * pcols + cols + pj, psize - pj); + } + } + } + // row padding + for (; i < prows; i++) { + auto zero_vec = at::vec::Vectorized(0); + int64_t j = 0; + for (; j < pcols - (pcols % vec_size); j += vec_size) { + zero_vec.store(dst_ptr + i * pcols + j); + } + if (j < pcols) { + zero_vec.store(dst_ptr + i * pcols + j, pcols - j); + } + + } +} +""" + +MICRO_GEMM_TEMPLATE = r""" +GEMM_DEFINE +""" + +ALLOCATE_BUFFER = r""" + int64_t {{buffer_name}}_dtype_itemsize = c10::is_reduced_floating_point_v<{{buffer_dtype}}> ? 2 : 4; + auto& {{buffer_name}}_allocator = *at::getCPUAllocator(); + auto {{buffer_name}}_work_data = {{buffer_name}}_allocator.allocate({{buffer_size}}*{{buffer_name}}_dtype_itemsize); + void* {{buffer_name}}_data_ptr = {{buffer_name}}_work_data.get(); + {{buffer_dtype}}* {{buffer_name}} = ({{buffer_dtype}}*){{buffer_name}}_data_ptr; +""" + +INIT_PARAMS = r""" +{{template.header().getvalue()}} +#include +#include +#include +{{template.codegen_micro_gemm(kernel.kernel_name)}} +{{template.codegen_softmax_fusion(kernel.kernel_name)}} +{{template.codegen_brgemm_pack_function(kernel.kernel_name)}} +{%- set kernel_args = {"query": query, "key": key, "value": value, + "kv_num_blocks": kv_num_blocks, "kv_indices": kv_indices, + "full_kv_num_blocks": full_kv_num_blocks, "full_kv_indices": full_kv_indices } %} +{%- set kernel_args = template.update_kernel_args(kernel_args) %} + +extern "C" +{{kernel.def_kernel(inputs=kernel_args, outputs={"output": output}, extra_sizevars=template.extra_sizevars)}} +{ + {{ kernel.maybe_codegen_profile() }} + + // dtypes + using scalar_t = {{kernel.dtype(query)}}; + constexpr bool is_reduced_type = c10::is_reduced_floating_point_v; + using accum_t = at::opmath_type<{{kernel.dtype(query)}}>; + using Vec = at::vec::Vectorized; + accum_t scaling_factor = {{scale}}; + + // sizes + int64_t qBlockSize = {{qBlockSize}}; + int64_t kvBlockSize = {{kvBlockSize}}; + int64_t num_thread = {{num_thread}}; + int64_t batchSize = {{kernel.size(query, 0)}}; + int64_t qSize = {{kernel.size(query, 1)}}; + int64_t num_head = {{kernel.size(query, 2)}}; + int64_t headSize = {{kernel.size(query, 3)}}; + int64_t batchSize_k = {{kernel.size(key, 0)}}; + int64_t num_head_k = {{kernel.size(key, 2)}}; + int64_t headSize_v = {{kernel.size(value, 3)}}; + bool is_broadcast_bs_kv = batchSize != batchSize_k; + bool is_broadcast_head_kv = num_head != num_head_k; + int64_t gqa_shards = num_head / num_head_k; + int64_t bs_shards = batchSize / batchSize_k; + + int64_t batchSize_kvi = {{kernel.size(kv_indices, 0)}}; + int64_t num_head_kvi = {{kernel.size(kv_indices, 1)}}; + int64_t block_num_kvi = {{kernel.size(kv_indices, 3)}}; + bool is_broadcast_bs_kvi = batchSize != batchSize_kvi; + bool is_broadcast_head_kvi = num_head != num_head_kvi; + int64_t gqa_shards_kvi = num_head / num_head_kvi; + int64_t bs_shards_kvi = batchSize / batchSize_kvi; + + int64_t kvSize = {{kernel.size(key, 1)}}; + + int64_t qSplitSize = qBlockSize; + int64_t kvSplitSize = kvBlockSize; + + qSplitSize = qSplitSize > qSize ? qSize : qSplitSize; + kvSplitSize = kvSplitSize > kvSize ? kvSize : kvSplitSize; + int64_t qSlice = (qSize + qSplitSize - 1) / qSplitSize; + int64_t kvSlice = (kvSize + kvSplitSize - 1) / kvSplitSize; + int64_t kvTail = (kvSize - 1) % kvSplitSize + 1; + + // Strides + int64_t kviStrideB = {{kernel.stride(kv_indices, 0)}}; + int64_t kviStrideH = {{kernel.stride(kv_indices, 1)}}; + int64_t kviStrideQ = {{kernel.stride(kv_indices, 2)}}; + + int64_t num_kviStrideB = {{kernel.stride(kv_num_blocks, 0)}}; + int64_t num_kviStrideH = {{kernel.stride(kv_num_blocks, 1)}}; + +{%- if has_full_kv_block %} + int64_t full_kviStrideB = {{kernel.stride(full_kv_indices, 0)}}; + int64_t full_kviStrideH = {{kernel.stride(full_kv_indices, 1)}}; + int64_t full_kviStrideQ = {{kernel.stride(full_kv_indices, 2)}}; + + int64_t full_num_kviStrideB = {{kernel.stride(full_kv_num_blocks, 0)}}; + int64_t full_num_kviStrideH = {{kernel.stride(full_kv_num_blocks, 1)}}; + auto full_kv_indices_data = full_kv_indices; + auto full_kv_num_blocks_data = full_kv_num_blocks; +{%- endif %} + + auto kv_num_blocks_data = kv_num_blocks; + auto kv_indices_data = kv_indices; + + int64_t qStrideB = {{kernel.stride(query, 0)}}; + int64_t qStrideM = {{kernel.stride(query, 1)}}; + int64_t qStrideH = {{kernel.stride(query, 2)}}; + int64_t kStrideB = {{kernel.stride(key, 0)}}; + int64_t kStrideN = {{kernel.stride(key, 1)}}; + int64_t kStrideH = {{kernel.stride(key, 2)}}; + int64_t vStrideB = {{kernel.stride(value, 0)}}; + int64_t vStrideN = {{kernel.stride(value, 1)}}; + int64_t vStrideH = {{kernel.stride(value, 2)}}; + int64_t oStrideB = {{kernel.stride(output, 0)}}; + int64_t oStrideM = {{kernel.stride(output, 2)}}; + int64_t oStrideH = {{kernel.stride(output, 1)}}; + + // Inputs/outputs buffers + const scalar_t* q_data = query; + const scalar_t* k_data = key; + const scalar_t* v_data = value; + scalar_t* out_data = output; + +""" + +FLEX_ATTENTION_TEMPLATE = r""" + bool need_pack = false; + // Whether pack is needed for BFloat16/Half + if (is_reduced_type) { + // check platform ability + need_pack = std::is_same_v ? at::native::cpublas::could_pack(at::kBFloat16) + : at::native::cpublas::could_pack(at::kHalf); + } + if (need_pack) { + // When the number of gemm is greater than the number of pack, + // the pack overhead can be overlapped. + int64_t thresh_size = 64; + need_pack = kvSize >= thresh_size && qSize >= thresh_size; + if (need_pack) { + double pack_size = batchSize * num_head * kvSize * headSize; + double qs_per_thread = (batchSize * num_head * qSlice + num_thread - 1) / num_thread; + double gemm_size_per_thread = qs_per_thread * qSplitSize * kvSize * headSize; + need_pack = gemm_size_per_thread / pack_size >= 4; + } + } + // Pad is needed for packing when K is not even + bool headSize_even = headSize % 2 == 0; + int64_t eheadSize = need_pack && !headSize_even ? headSize + 1: headSize; + int64_t ekvSplitSize = need_pack && (kvSplitSize % 2 != 0) ? kvSplitSize + 1 : kvSplitSize; + int64_t ekvTail = need_pack && (kvTail % 2 != 0) ? kvTail + 1 : kvTail; + int64_t kv_padding_size = (kvSize - 1) / kvSplitSize * ekvSplitSize + ekvTail; + + // Allocate per thread temp buf (accumulate type) + int64_t _size_per_thread = + /* qk */ qSplitSize * kvSplitSize + + /* qk_max */ qSplitSize + + /* qk_sum */ qSplitSize + + /* dst */ qSplitSize * headSize_v; + + // Buffers to store accum results, padding query and transpose/packing key/value + {{template.codegen_allocate_buffer("buf_data", "accum_t", "num_thread*_size_per_thread")}} + {{template.codegen_allocate_buffer("buf_reduced_data", "scalar_t", "num_thread*qSplitSize*ekvSplitSize")}} + {{template.codegen_allocate_buffer("key_reorder_ptr", "scalar_t", "batchSize_k*num_head_k*eheadSize*kvSize")}} + {{template.codegen_allocate_buffer("value_reorder_ptr", "scalar_t", "batchSize_k*num_head_k*kv_padding_size*headSize_v")}} + {{template.codegen_allocate_buffer("transpose_buffer_ptr", "scalar_t", "num_thread*kvSplitSize*headSize")}} + {{template.codegen_allocate_buffer("query_padding_ptr", "scalar_t", "num_thread*qSplitSize*eheadSize")}} + if (need_pack) { + // Pack K, V + at::parallel_for(0, batchSize_k * num_head_k * kvSlice, 1, [&](int64_t begin, int64_t end) { + int ompIdx = at::get_thread_num(); + int64_t i = 0, j = 0, l = 0, n = 0; + scalar_t* transpose_ptr = need_pack? transpose_buffer_ptr + ompIdx * kvSplitSize * headSize : nullptr; + at::native::data_index_init(begin, i, batchSize_k, j, num_head_k, l, kvSlice); + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + n = l * kvSplitSize; + int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n); + auto k_addr = + k_data + i * kStrideB + j * kStrideH + n * kStrideN; + auto v_addr = + v_data + i * vStrideB + j * vStrideH + n * vStrideN; + // transpose [cur_kvSplitSize, headSize] -> [headSize, cur_kvSplitSize] + at::native::utils::transpose( + cur_kvSplitSize, + headSize, + /* src_ptr */ + reinterpret_cast(k_addr), + /* ld_src */ kStrideN, + /* dst */ reinterpret_cast(transpose_ptr), + /* ld_dst */ cur_kvSplitSize); + + // Pack [headSize, cur_kvSplitSize] + at::vec::pack_vnni2( + /* src */ reinterpret_cast(transpose_ptr), + /* dst */ reinterpret_cast(key_reorder_ptr + i * num_head_k * eheadSize * kvSize + + j * eheadSize * kvSize + n * eheadSize), + /* ld_src */ cur_kvSplitSize, + /* K */ headSize, + /* N */ cur_kvSplitSize); + + // Pack [cur_kvSplitSize, headSize_v] + at::vec::pack_vnni2( + /* src */ reinterpret_cast(v_addr), + /* dst */ reinterpret_cast(value_reorder_ptr + + i * num_head_k * kv_padding_size * headSize_v + + j * kv_padding_size * headSize_v + n * headSize_v), + /* ld_src */ vStrideN, + /* K */ cur_kvSplitSize, + /* N */ headSize_v); + // Move to the next query + at::native::data_index_step(i, batchSize_k, j, num_head_k, l, kvSlice); + } + }); + } + // Attention loop below + at::parallel_for(0, batchSize * num_head * qSlice, 1, [&](int64_t begin, int64_t end) { + int64_t i = 0, j = 0, k = 0; + at::native::data_index_init(begin, i, batchSize, j, num_head, k, qSlice); + int ompIdx = at::get_thread_num(); + accum_t* buf_ptr = buf_data + ompIdx * _size_per_thread; + accum_t* qk_data = buf_ptr; + accum_t* qk_max_data = qk_data + qSplitSize * kvSplitSize; + accum_t* qk_sum_data = qk_max_data + qSplitSize; + accum_t* dst_data = qk_sum_data + qSplitSize; + scalar_t *qk_reduced_data = + is_reduced_type + ? buf_reduced_data + ompIdx * qSplitSize * ekvSplitSize + : nullptr; + scalar_t* query_t_padding_ptr = (!headSize_even && need_pack) + ? query_padding_ptr + ompIdx * qSplitSize * eheadSize + : nullptr; + + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + auto i_kvi = is_broadcast_bs_kvi ? i/bs_shards_kvi : i; + auto j_kvi = is_broadcast_head_kvi ? j/gqa_shards_kvi : j; + auto kv_logical_num_data = kv_num_blocks_data + i_kvi * num_kviStrideB + + j_kvi * num_kviStrideH + k; + int kv_indice_num = *kv_logical_num_data; + std::vector kv_indice_list(kv_indice_num); + for(int kv_i = 0; kv_i < kv_indice_num; kv_i++){ + auto kv_logical_data = kv_indices_data + i_kvi * kviStrideB + + j_kvi * kviStrideH + k*kviStrideQ + kv_i; + kv_indice_list[kv_i] = *kv_logical_data; + } + bool is_skip_kv = kv_indice_num > 0 ? false : true; +{%- if has_full_kv_block %} + auto full_kv_logical_num_data = full_kv_num_blocks_data + i_kvi * num_kviStrideB + + j_kvi * num_kviStrideH + k; + int full_kv_indice_num = *full_kv_logical_num_data; + std::vector full_kv_indice_list(full_kv_indice_num); + for(int kv_i = 0; kv_i < full_kv_indice_num; kv_i++){ + auto full_kv_logical_data = full_kv_indices_data + i_kvi * full_kviStrideB + + j_kvi * full_kviStrideH + k*full_kviStrideQ + kv_i; + full_kv_indice_list[kv_i] = *full_kv_logical_data; + } + is_skip_kv = kv_indice_num + full_kv_indice_num > 0 ? false : true; +{%- endif %} + int64_t m = k * qSplitSize; + int64_t cur_qSplitSize = std::min(qSplitSize, qSize - m); + if (!is_skip_kv){ + // Initialize max and sum + {{kernel.kernel_name}}_fill_stub(qk_max_data, + -std::numeric_limits::infinity(), cur_qSplitSize); + {{kernel.kernel_name}}_fill_stub(qk_sum_data, + static_cast(0), cur_qSplitSize); + + if (!headSize_even && need_pack) { + // Pad query if headSize is not even + {{kernel.kernel_name}}_copy_value_with_pad( + q_data + i * qStrideB + j * qStrideH + m * qStrideM, + query_t_padding_ptr, + cur_qSplitSize, + headSize, + cur_qSplitSize, + eheadSize, + qStrideM + ); + } + } + +{%- if has_full_kv_block %} + for (int64_t n_idx = 0; n_idx < kv_indice_num + full_kv_indice_num ; n_idx += 1) { + auto n = n_idx < kv_indice_num ? kv_indice_list[n_idx]*kvSplitSize : full_kv_indice_list[n_idx - kv_indice_num]*kvSplitSize; +{%- else %} + for (int64_t n_idx = 0; n_idx < kv_indice_num ; n_idx += 1) { + auto n = kv_indice_list[n_idx]*kvSplitSize; +{%- endif %} + + auto cur_n = n/kvSplitSize; + int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n); + int64_t cur_ekvSplitSize = (need_pack && cur_kvSplitSize % 2 != 0) ? cur_kvSplitSize + 1 : cur_kvSplitSize; + + // Calculate scale * q @ k.T + auto i_kv = is_broadcast_bs_kv ? i/bs_shards : i; + auto j_kv = is_broadcast_head_kv ? j/gqa_shards : j; + + if (!need_pack) { + auto k_addr = + k_data + i_kv * kStrideB + j_kv * kStrideH + n * kStrideN; + + {{kernel.kernel_name}}_kernel_micro_gemm_transpose_b(false)>( + q_data + i * qStrideB + j * qStrideH + + m * qStrideM, + k_addr, + qk_data, + cur_qSplitSize, + cur_kvSplitSize, + headSize, + qStrideM, + kStrideN, + cur_kvSplitSize); + + } else { + at::native::cpublas::brgemm( + cur_qSplitSize, + cur_kvSplitSize, + eheadSize, + headSize_even ? qStrideM : eheadSize, + cur_kvSplitSize, + cur_kvSplitSize, + false, + !headSize_even + ? query_t_padding_ptr + : q_data + i * qStrideB + j * qStrideH + m * qStrideM, + key_reorder_ptr + i_kv * num_head_k * eheadSize * kvSize + + j_kv * eheadSize * kvSize + n * eheadSize, + qk_data, + need_pack); + } + + {{kernel.kernel_name}}_mul_scale_kernel(qk_data, scaling_factor, cur_qSplitSize*cur_kvSplitSize); + +{%- if score_mod and mask_mod %} + // TODO: reduce the number of calls of q_idx and kv_idx initialization + std::vector q_idx(cur_qSplitSize); + for (int64_t i = 0; i < cur_qSplitSize; ++i) { + q_idx[i] = m + i; + } + + std::vector kv_idx(cur_kvSplitSize); + for (int64_t i = 0; i < cur_kvSplitSize; ++i) { + kv_idx[i] = n + i; + } + + std::vector b_idx = {i}; + std::vector h_idx = {j}; + + accum_t* in_ptr0 = qk_data; + + auto in_ptr1 = b_idx.data(); + auto in_ptr2 = h_idx.data(); + auto in_ptr3 = q_idx.data(); + auto in_ptr4 = kv_idx.data(); + + // apply score mod function + { + {{ template.generate_other_buffer("score_others", 0, "len_score_other", kernel.args) }} + accum_t* out_ptr{{score_buf_idx}} = in_ptr0; + {{ template.modification(score_mod, score_buf_name, score_buf_idx)|indent(12, false) }} + } + + if ((std::find(kv_indice_list.begin(), kv_indice_list.end(), cur_n) != kv_indice_list.end()) ){ + // Apply block mask, fill unused with -inf + { + {{ template.generate_other_buffer("mask_others", -1, "len_mask_other", kernel.args) }} + accum_t* out_ptr{{mask_buf_idx}} = in_ptr0; + {{ template.modification(mask_mod, mask_buf_name, mask_buf_idx)|indent(12, false) }} + } + } + +{%- endif %} + // Update coefficients with Softmax + accum_t tmp_max = 0, tmp_sum = 0, exp_tmp = 0; + for (int64_t row = 0; row < cur_qSplitSize; ++row) { + // apply scaling factor and max per row in fusion + {{kernel.kernel_name}}_mul_reduce_max_fusion_kernel( + qk_data + row * cur_kvSplitSize, + static_cast(1), + cur_kvSplitSize, + qk_data + row * cur_kvSplitSize, + tmp_max); + tmp_max = qk_max_data[row] > tmp_max ? qk_max_data[row] : tmp_max; + if (tmp_max == -std::numeric_limits::infinity()) { + // to avoid `nan = exp2f(-inf - (-inf))` + {{kernel.kernel_name}}_fill_stub( + {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data) + row * cur_ekvSplitSize, + static_cast(0), cur_kvSplitSize); + } else { + tmp_sum = tmp_max; + // qk <- exp(qk - max) and sum per row + {{kernel.kernel_name}}_exp_reduce_sum_fusion_kernel( + qk_data + row * cur_kvSplitSize, cur_kvSplitSize, + {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data) + row * cur_ekvSplitSize, + tmp_sum); + // exp_tmp <- exp(max[row] - max) + exp_tmp = std::exp(qk_max_data[row] - tmp_max); + // sum[row] <- sum + exp_tmp * sum[row] + qk_sum_data[row] = tmp_sum + exp_tmp * qk_sum_data[row]; + // max[row] <- max + qk_max_data[row] = tmp_max; + // dst <- dst * exp_tmp + if (n_idx > 0) { + at::vec::map( + [exp_tmp](Vec x) { return x * Vec(exp_tmp); }, + dst_data + row * headSize_v, + dst_data + row * headSize_v, + headSize_v); + } + } + if (need_pack && cur_kvSplitSize % 2 != 0) { + // Pad: [qSplitSize, cur_kvSplitSize] -> [qSplitSize, cur_kvSplitSize + 1] + *(qk_reduced_data + row * (1 + cur_kvSplitSize) + cur_kvSplitSize) = scalar_t(0); + } + } + // Calculate Softmax(q @ k.T) @ v + if (!need_pack) { + auto v_addr = + v_data + i_kv * vStrideB + j_kv * vStrideH + n * vStrideN; + // Fallback Half brgemm is slower than micro gemm + if (!std::is_same_v) { + at::native::cpublas::brgemm( + cur_qSplitSize, + headSize_v, + cur_ekvSplitSize, + cur_ekvSplitSize, + vStrideN, + headSize_v, + n_idx > 0, + {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data), + v_addr, + dst_data, + need_pack); + } else { + if (n_idx > 0) { + {{kernel.kernel_name}}_kernel_micro_gemm(true)>( + {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data), + v_addr, + dst_data, + cur_qSplitSize, + headSize_v, + cur_ekvSplitSize, + cur_ekvSplitSize, + vStrideN, + headSize_v); + } else { + {{kernel.kernel_name}}_kernel_micro_gemm(false)>( + {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data), + v_addr, + dst_data, + cur_qSplitSize, + headSize_v, + cur_ekvSplitSize, + cur_ekvSplitSize, + vStrideN, + headSize_v); + } + } + } else { + int64_t psize = n / kvSplitSize * ekvSplitSize; + at::native::cpublas::brgemm( + cur_qSplitSize, + headSize_v, + cur_ekvSplitSize, + cur_ekvSplitSize, + headSize_v, + headSize_v, + n_idx > 0, + qk_reduced_data, + value_reorder_ptr + + i_kv * num_head_k * kv_padding_size * headSize_v + + j_kv * kv_padding_size * headSize_v + psize * headSize_v, + dst_data, + need_pack); + } + } + + // dst <- dst / sum[row] + // reorder MHA output with strides + for (int64_t row = 0; row < cur_qSplitSize; ++row) { + // Row sums for full masked out rows are 0, we set them to 1 + // in order to avoid NaNs in the output and instead set fully + // masked out rows to 0 + qk_max_data[row] = qk_max_data[row] == -std::numeric_limits::infinity() ? 0 : qk_max_data[row]; + qk_sum_data[row] = qk_sum_data[row] == 0 ? 1 : qk_sum_data[row]; + accum_t sum_reciprocal = 1 / qk_sum_data[row]; + at::vec::map( + [sum_reciprocal, is_skip_kv](Vec x) { return is_skip_kv ? Vec(0.0) : x * Vec(sum_reciprocal); }, + out_data + i * oStrideB + j * oStrideH + m * oStrideM + row * oStrideM, + dst_data + row * headSize_v, + headSize_v); + } + + // Move to the next query + at::native::data_index_step(i, batchSize, j, num_head, k, qSlice); + } + + at::native::cpublas::brgemm_release(need_pack); + + }); +} +""" + +FLEX_DECODING_TEMPLATE = r""" + int64_t PARTITION_SIZE = {{partition_size}}; + + // Check if score / mask mod dependent on batch_size / num_head + // Go into a fast path if independent + bool bs_head_independent_mod = true; + int64_t first_num_kvblocks = kv_num_blocks[0]; + int64_t first_full_num_kvblocks = full_kv_num_blocks[0]; + for (const auto& b : c10::irange(batchSize_kvi)) { + for (const auto& h : c10::irange(num_head_kvi)) { + if (*(kv_num_blocks + b * num_kviStrideB + h * num_kviStrideH) != first_num_kvblocks + || *(full_kv_num_blocks + b * full_num_kviStrideB + h * full_num_kviStrideH) != first_full_num_kvblocks) { + bs_head_independent_mod = false; + break; + } + } + } + + int64_t num_kvblocks_per_seq = kv_num_blocks[0] + full_kv_num_blocks[0]; + int64_t num_kvblocks_per_partition = PARTITION_SIZE / kvBlockSize; + int64_t num_partitions = (num_kvblocks_per_seq + num_kvblocks_per_partition - 1) / num_kvblocks_per_partition; + if (!bs_head_independent_mod) { + num_partitions = + (kvSize + PARTITION_SIZE - 1) / PARTITION_SIZE; + } + + // Allocate temp buf (accumulate type) + int64_t _accum_buff_size = + /* max_logits_ptr */ batchSize * num_head * num_partitions + + /* exp_sum_ptr */ batchSize * num_head * num_partitions + + /* tmp_out_ptr */ batchSize * num_head * num_partitions * headSize_v + + /* logits_ptrs */ num_thread * PARTITION_SIZE; + + {{template.codegen_allocate_buffer("buf_data", "accum_t", "_accum_buff_size")}} + accum_t* max_logits_ptr = buf_data; + accum_t* exp_sum_ptr = max_logits_ptr + batchSize * num_head * num_partitions; + accum_t* tmp_out_ptr = exp_sum_ptr + batchSize * num_head * num_partitions; + accum_t* logits_ptrs = tmp_out_ptr + batchSize * num_head * num_partitions * headSize_v; + {{template.codegen_allocate_buffer("logits_reduced_ptrs", "scalar_t", "num_thread * PARTITION_SIZE")}} + + auto max_logits_strideN = num_head * num_partitions; + auto max_logits_strideH = num_partitions; + auto exp_sum_strideN = num_head * num_partitions; + auto exp_sum_strideH = num_partitions; + auto tmp_out_strideN = num_head * num_partitions * headSize_v; + auto tmp_out_strideH = num_partitions * headSize_v; + auto tmp_out_strideS = headSize_v; + + // Attention loop + at::parallel_for(0, batchSize * num_head * num_partitions, 1, [&](int64_t begin, int64_t end) { + int64_t i = 0, j = 0, partition_id = 0; + at::native::data_index_init(begin, i, batchSize, j, num_head, partition_id, num_partitions); + int ompIdx = at::get_thread_num(); + accum_t* logits = logits_ptrs + ompIdx * PARTITION_SIZE; + scalar_t* logits_reduced = + is_reduced_type + ? logits_reduced_ptrs + ompIdx * PARTITION_SIZE + : nullptr; + + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + auto kvblock_offset = num_kvblocks_per_partition * partition_id; + auto i_kvi = is_broadcast_bs_kvi ? i/bs_shards_kvi : i; + auto j_kvi = is_broadcast_head_kvi ? j/gqa_shards_kvi : j; + auto kv_logical_num_data = kv_num_blocks_data + i_kvi * num_kviStrideB + + j_kvi * num_kviStrideH; + int64_t kv_indice_num = *kv_logical_num_data; + std::vector kv_indice_list(kv_indice_num); + for(int64_t kv_i = 0; kv_i < kv_indice_num; kv_i++){ + auto kv_logical_data = kv_indices_data + i_kvi * kviStrideB + + j_kvi * kviStrideH + kv_i; + kv_indice_list[kv_i] = *kv_logical_data; + } +{%- if has_full_kv_block %} + auto full_kv_logical_num_data = full_kv_num_blocks_data + i_kvi * num_kviStrideB + + j_kvi * num_kviStrideH; + int64_t full_kv_indice_num = *full_kv_logical_num_data; + std::vector full_kv_indice_list(full_kv_indice_num); + for(int64_t kv_i = 0; kv_i < full_kv_indice_num; kv_i++){ + auto full_kv_logical_data = full_kv_indices_data + i_kvi * full_kviStrideB + + j_kvi * full_kviStrideH + kv_i; + full_kv_indice_list[kv_i] = *full_kv_logical_data; + } +{%- endif %} + int64_t cur_qSplitSize = 1; + auto i_kv = is_broadcast_bs_kv ? i/bs_shards : i; + auto j_kv = is_broadcast_head_kv ? j/gqa_shards : j; + accum_t* tmp_out = tmp_out_ptr + i * tmp_out_strideN + + j * tmp_out_strideH + partition_id * tmp_out_strideS; + + // Initialize logits + {{kernel.kernel_name}}_fill_stub(logits, + static_cast(0), PARTITION_SIZE); + if (is_reduced_type) { + {{kernel.kernel_name}}_fill_stub(logits_reduced, + static_cast(0), PARTITION_SIZE); + } + + + // 1) calculate the matmul(query, key) for this partition + int64_t token_num = 0; +{%- if has_full_kv_block %} + int64_t n_idx_start = kvblock_offset; + int64_t n_idx_end = std::min(kvblock_offset + num_kvblocks_per_partition, kv_indice_num + full_kv_indice_num); + if (!bs_head_independent_mod) { + n_idx_start = 0; + n_idx_end = kv_indice_num + full_kv_indice_num; + } + for (int64_t n_idx : c10::irange(n_idx_start, n_idx_end)) { + auto n = n_idx < kv_indice_num ? kv_indice_list[n_idx]*kvSplitSize : full_kv_indice_list[n_idx - kv_indice_num]*kvSplitSize; +{%- else %} + int64_t n_idx_start = kvblock_offset; + int64_t n_idx_end = std::min(kvblock_offset + num_kvblocks_per_partition, kv_indice_num); + if (!bs_head_independent_mod) { + n_idx_start = 0; + n_idx_end = kv_indice_num; + } + for (int64_t n_idx : c10::irange(n_idx_start, n_idx_end)) { + auto n = kv_indice_list[n_idx]*kvSplitSize; +{%- endif %} + if (!bs_head_independent_mod + && (n < partition_id * PARTITION_SIZE + || n >= std::min(partition_id * PARTITION_SIZE + PARTITION_SIZE, kvSize))) { + continue; + } + auto cur_n = n/kvSplitSize; + int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n); + + auto k_addr = + k_data + i_kv * kStrideB + j_kv * kStrideH + n * kStrideN; + + {{kernel.kernel_name}}_kernel_micro_gemm_transpose_b( + q_data + i * qStrideB + j * qStrideH, + k_addr, + logits + token_num, + cur_qSplitSize, + cur_kvSplitSize, + headSize, + qStrideM, + kStrideN, + cur_kvSplitSize); + + {{kernel.kernel_name}}_mul_scale_kernel(logits + token_num, scaling_factor, cur_qSplitSize*cur_kvSplitSize); + +{%- if score_mod and mask_mod %} + // TODO: reduce the number of calls of q_idx and kv_idx initialization + std::vector q_idx(cur_qSplitSize); + for (int64_t i = 0; i < cur_qSplitSize; ++i) { + q_idx[i] = i; + } + + std::vector kv_idx(cur_kvSplitSize); + for (int64_t i = 0; i < cur_kvSplitSize; ++i) { + kv_idx[i] = n + i; + } + + std::vector b_idx = {i}; + std::vector h_idx = {j}; + + accum_t* in_ptr0 = logits + token_num; + + const auto in_ptr1 = b_idx.data(); + const auto in_ptr2 = h_idx.data(); + const auto in_ptr3 = q_idx.data(); + const auto in_ptr4 = kv_idx.data(); + + // apply score mod function + { + {{ template.generate_other_buffer("score_others", 0, "len_score_other", kernel.args) }} + accum_t* out_ptr{{score_buf_idx}} = in_ptr0; + {{ template.modification(score_mod, score_buf_name, score_buf_idx)|indent(12, false) }} + } + + if ((std::find(kv_indice_list.begin(), kv_indice_list.end(), cur_n) != kv_indice_list.end()) ){ + // Apply block mask, fill unused with -inf + { + {{ template.generate_other_buffer("mask_others", -1, "len_mask_other", kernel.args) }} + accum_t* out_ptr{{mask_buf_idx}} = in_ptr0; + {{ template.modification(mask_mod, mask_buf_name, mask_buf_idx)|indent(12, false) }} + } + } +{%- endif %} + token_num += cur_kvSplitSize; + } + + + // 2) calculate the max and exp_sum for this partition + auto partition_max = -std::numeric_limits::infinity(); + {{kernel.kernel_name}}_mul_reduce_max_fusion_kernel( + logits, + static_cast(1), + token_num, + logits, + partition_max); + if (partition_max == -std::numeric_limits::infinity()) { + partition_max = 0; + } + max_logits_ptr[i * max_logits_strideN + + j * max_logits_strideH + partition_id] = + partition_max; + {{kernel.kernel_name}}_exp_reduce_sum_fusion_kernel( + logits, + token_num, + {{kernel.kernel_name}}_conditional_data_ptr(logits, logits_reduced), + partition_max); + exp_sum_ptr[i * exp_sum_strideN + + j * exp_sum_strideH + partition_id] = partition_max; + + + // 3) calculate the matmul(exp(logits-partition_max), value) for this + // partition, need to divide the global exp_sum in the final result. + token_num = 0; + bool skipped_partition = true; +{%- if has_full_kv_block %} + n_idx_start = kvblock_offset; + n_idx_end = std::min(kvblock_offset + num_kvblocks_per_partition, kv_indice_num + full_kv_indice_num); + if (!bs_head_independent_mod) { + n_idx_start = 0; + n_idx_end = kv_indice_num + full_kv_indice_num; + } + for (int64_t n_idx : c10::irange(n_idx_start, n_idx_end)) { + auto n = n_idx < kv_indice_num ? kv_indice_list[n_idx]*kvSplitSize : full_kv_indice_list[n_idx - kv_indice_num]*kvSplitSize; +{%- else %} + n_idx_start = kvblock_offset; + n_idx_end = std::min(kvblock_offset + num_kvblocks_per_partition, kv_indice_num); + if (!bs_head_independent_mod) { + n_idx_start = 0; + n_idx_end = kv_indice_num; + } + for (int64_t n_idx : c10::irange(n_idx_start, n_idx_end)) { + auto n = kv_indice_list[n_idx]*kvSplitSize; +{%- endif %} + if (!bs_head_independent_mod + && (n < partition_id * PARTITION_SIZE + || n >= std::min(partition_id * PARTITION_SIZE + PARTITION_SIZE, kvSize))) { + continue; + } + skipped_partition = false; + int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n); + + auto v_addr = + v_data + i_kv * vStrideB + j_kv * vStrideH + n * vStrideN; + // Fallback Half brgemm is slower than micro gemm + + if constexpr (!std::is_same_v) { + at::native::cpublas::brgemm( + cur_qSplitSize, + headSize_v, + cur_kvSplitSize, + cur_kvSplitSize, + vStrideN, + headSize_v, + token_num > 0, + {{kernel.kernel_name}}_conditional_data_ptr(logits, logits_reduced) + token_num, + v_addr, + tmp_out, + false); + } else { + if (token_num > 0) { + {{kernel.kernel_name}}_kernel_micro_gemm(true)>( + {{kernel.kernel_name}}_conditional_data_ptr(logits, logits_reduced) + token_num, + v_addr, + tmp_out, + cur_qSplitSize, + headSize_v, + cur_kvSplitSize, + cur_kvSplitSize, + vStrideN, + headSize_v); + } else { + {{kernel.kernel_name}}_kernel_micro_gemm(false)>( + {{kernel.kernel_name}}_conditional_data_ptr(logits, logits_reduced) + token_num, + v_addr, + tmp_out, + cur_qSplitSize, + headSize_v, + cur_kvSplitSize, + cur_kvSplitSize, + vStrideN, + headSize_v); + } + } + token_num += cur_kvSplitSize; + } + if (skipped_partition) { + {{kernel.kernel_name}}_fill_stub(tmp_out, + static_cast(0), headSize_v); + } + + // Move to the next query + at::native::data_index_step(i, batchSize, j, num_head, partition_id, num_partitions); + } + + if constexpr (!std::is_same_v) { + at::native::cpublas::brgemm_release(); + } + }); + + + // Calculate the final output + at::parallel_for(0, batchSize * num_head, 1, [&](int64_t begin, int64_t end) { + int64_t i = 0, j = 0; + at::native::data_index_init(begin, i, batchSize, j, num_head); + + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + auto global_max = -std::numeric_limits::infinity(); + auto global_exp_sum = 0.0; + + // Calculate the global max and exp_sum for this head + global_max = at::vec::reduce_all( + [](Vec& x, Vec& y) { return at::vec::maximum(x, y); }, + max_logits_ptr + i * max_logits_strideN + + j * max_logits_strideH, + num_partitions); + + // Update the partition 0 result with the global max + auto partition0_out_start = + tmp_out_ptr + i * tmp_out_strideN + j * tmp_out_strideH; + auto max_logit0 = max_logits_ptr + [i * max_logits_strideN + j * max_logits_strideH]; + float exp_val = std::exp(max_logit0 - global_max); + global_exp_sum = + exp_sum_ptr[i * exp_sum_strideN + j * exp_sum_strideH] * + exp_val; + at::vec::map( + [exp_val](Vec x) { return x * Vec(exp_val); }, + partition0_out_start, + partition0_out_start, + headSize_v); + + // Accumulate the partition 1 to partition n result into partition 0 + if (num_partitions > 1) { + for (auto partition_id = 1; partition_id < num_partitions; + partition_id++) { + auto tmp_out_start = partition0_out_start + partition_id * tmp_out_strideS; + auto max_logit = max_logits_ptr + [i * max_logits_strideN + j * max_logits_strideH + + partition_id]; + auto exp_sum = exp_sum_ptr + [i * exp_sum_strideN + j * exp_sum_strideH + + partition_id]; + exp_val = std::exp(max_logit - global_max); + global_exp_sum += exp_sum * exp_val; + at::vec::map2( + [exp_val](Vec a, Vec b) { return a + Vec(exp_val) * b; }, + partition0_out_start, + partition0_out_start, + tmp_out_start, + headSize_v); + } + } + + // Rescale the partition 0 result with global exp_sum + // Sum for full masked out rows are 0, we set them to 1 + // in order to avoid NaNs in the output and instead set fully + // masked out rows to 0 + global_exp_sum = global_exp_sum == 0 ? 1 : global_exp_sum; + float sum_reciprocal = 1.0 / global_exp_sum; + // copy the partition 0 result into output + at::vec::map( + [sum_reciprocal](Vec x) { return x * Vec(sum_reciprocal); }, + out_data + i * oStrideB + j * oStrideH, + partition0_out_start, + headSize_v); + + // Move to the next query + at::native::data_index_step(i, batchSize, j, num_head); + } + + }); +} +""" + + +class CppFlexAttentionTemplate(CppTemplate): + """ + CPP template based FlexAttention CPP Template. + + This class supports generation of C++ code for broad attention variants, + with applying Flash Attention and Flash Decoding. It enables template-based + code synthesis according to user-defined score and mask modifications + and configuration settings. + """ + + def __init__( + self, + input_nodes, + layout: ir.Layout, + scale, + score_mod, + mask_mod, + kv_block_size, + q_block_size, + partition_size, + has_other_buffer, + no_full_kv_block, + fake_buffers, + len_score_other, + len_mask_other, + kernel_input_name_to_buffer, + block_vars, + ) -> None: + if layout.dtype not in [torch.float, torch.bfloat16, torch.float16]: + raise AssertionError(f"unsupported layout dtype: {layout.dtype}") + super().__init__("flex_attention", input_nodes, layout, parallel_num_threads()) + self.scale = scale + self.score_mod = score_mod + self.mask_mod = mask_mod + self.score_buf_name = ( + V.graph.register_buffer(self.score_mod) if self.score_mod else None + ) + self.mask_buf_name = ( + V.graph.register_buffer(self.mask_mod) if self.mask_mod else None + ) + + def get_idx(buf_name): + match = re.search(r"\d+", buf_name) + if not match: + raise AssertionError(f"incorrect score buf name: {buf_name}") + return match.group() + + self.score_buf_idx = ( + get_idx(self.score_buf_name) if self.score_buf_name else None + ) + self.mask_buf_idx = get_idx(self.mask_buf_name) if self.mask_buf_name else None + self.kv_block_size = kv_block_size + self.q_block_size = q_block_size + self.partition_size = partition_size + self.has_other_buffer = has_other_buffer + self.no_full_kv_block = no_full_kv_block + self.other_buffer_input_offset = 2 + if self.no_full_kv_block: + self.other_buffer_input_offset = 0 + self.fake_buffers = fake_buffers + self.len_score_other = len_score_other + self.len_mask_other = len_mask_other + self.kernel_input_name_to_buffer = kernel_input_name_to_buffer + self.block_vars = block_vars + self.extra_sizevars = list( + OrderedSet( + val + for val in self.kernel_input_name_to_buffer.values() + if isinstance(val, sympy.Symbol) + ) + ) + self.other_buf_start_idx = 5 + self.score_mod_other_buffers = ( + self.input_nodes[ + self.other_buf_start_idx + + self.other_buffer_input_offset : self.other_buf_start_idx + + self.other_buffer_input_offset + + self.len_score_other + ] + if self.has_other_buffer + else None + ) + self.mask_mod_other_buffers = ( + self.input_nodes[ + self.other_buf_start_idx + + self.other_buffer_input_offset + + self.len_score_other : + ] + if self.has_other_buffer + else None + ) + self.other_ptr_data = {} # type: ignore[var-annotated] + + def update_kernel_args(self, kernel_args): + kernel_args.update( + { + key: value + for key, value in self.kernel_input_name_to_buffer.items() + if not isinstance(value, sympy.Symbol) + } + ) + return kernel_args + + def generate_other_buffer(self, buf_list, start_offset, len_attr, kernel_args): + kernel_input_name_to_buffer_name = { + key: value if isinstance(value, sympy.Symbol) else value.get_name() + for key, value in self.kernel_input_name_to_buffer.items() + } + + def get_arg(name): + return kernel_input_name_to_buffer_name.get(name) + + def get_arg_name(name): + if isinstance(get_arg(name), sympy.Symbol): + return kernel_args.sizevars.get(get_arg(name)) + return kernel_args.input_buffers.get(get_arg(name)) + + if not self.has_other_buffer: + return "" + + if start_offset == -1: + start_offset = self.len_score_other + + length = getattr(self, len_attr) + for i in range(length): + pointer = f"in_ptr{self.other_buf_start_idx + start_offset + i}" + buffer_key = f"{buf_list}_{i}" + if pointer not in self.other_ptr_data: + self.other_ptr_data[pointer] = ( + get_arg_name(buffer_key), + get_arg(buffer_key), + ) + + return "\n".join( + f"auto {ptr} = {name};" for ptr, (name, _) in self.other_ptr_data.items() + ) + + def modification(self, subgraph_buffer, output_name, output_idx): + if not isinstance(subgraph_buffer, ir.ComputedBuffer): + raise AssertionError( + f"expected ir.ComputedBuffer, got {type(subgraph_buffer)}" + ) + subgraph_buffer_data = subgraph_buffer.data + from ..loop_body import LoopBody + from ..utils import sympy_index_symbol_with_prefix, SymT + from ..virtualized import V + from .cpp import CppKernelProxy, KernelGroup, ParallelDepth + + kernel_group = KernelGroup() + kernel_input_args = { + "score": "in_ptr0", + "b": "in_ptr1", + "h": "in_ptr2", + "q_idx": "in_ptr3", + "kv_idx": "in_ptr4", + } + if self.has_other_buffer: + kernel_input_args.update( + {arg: ptr for ptr, (_, arg) in self.other_ptr_data.items()} + ) + + kernel_output_args = {output_name: f"out_ptr{output_idx}"} + + args = kernel_group.args + for name, inp in kernel_input_args.items(): + args.input_buffers[name] = inp + + for name, inp in kernel_output_args.items(): + args.output_buffers[name] = inp + + for name in self.extra_sizevars: + args.sizevars[name] = f"k{name}" + + kernel_group.args = args + + cpp_kernel_proxy = CppKernelProxy(kernel_group) + bodies = [] + var_sizes_list = [] + var_sizes = tuple(subgraph_buffer.get_size()) + var_ranges = { + sympy_index_symbol_with_prefix(SymT.INDEX, i): sz + for i, sz in enumerate(var_sizes) + } + + dst_layout = subgraph_buffer.get_layout() + output_index = dst_layout.make_indexer()([*var_ranges.keys()]) + + def fn(*args): + V.ops.store( + output_name, + output_index, + subgraph_buffer_data.make_loader()(args).value, + ) + + body = LoopBody( + fn, + (list(var_ranges.keys())), + var_ranges, + list(var_ranges.keys()), + tuple(), + ) + + from ..loop_body import MemoryUsageType + + if not all( + mem.buffer_name in kernel_group.args.input_buffers + for mem in body.memory_usage[MemoryUsageType.LOAD] + ): + raise AssertionError( + "All the buffers in the score and mask subgraph should be in kernel_group.args.input_buffers" + ) + + bodies.append(body) + var_sizes_list.append((var_sizes, ())) + + cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list) + + def max_parallel_depth(): + return ParallelDepth(parallel_depth=0, start_depth=0) + + # This loop is not parallelized since it is not the outermost loop. + with patch.object( + cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth + ): + kernel_group.finalize_kernel(cpp_kernel_proxy, []) + output_code = kernel_group.loops_code.getvalue() + + var_q_symbol, var_kv_symbol = self.block_vars + # See [Note] Handle the case where the split sizes are not statically known. + # We don't know the value of qBlockSize and rkvBlockSize during compilation time + # thus we've represented them by symbols. + # We change the symbol strings back to "cur_qSplitSize" and "cur_kvSplitSize" + # in the generated code thus they'll be filled with the real value during runtime. + if var_q_symbol in kernel_group.args.sizevars: + output_code = output_code.replace( + kernel_group.args.sizevars[var_q_symbol], "cur_qSplitSize" + ) + if var_kv_symbol in kernel_group.args.sizevars: + output_code = output_code.replace( + kernel_group.args.sizevars[var_kv_symbol], "cur_kvSplitSize" + ) + + return output_code + + @staticmethod + def add_choices( + choices, + input_nodes, + layout, + scale, + score_mod, + mask_mod, + kv_block_size, + q_block_size, + partition_size, + has_other_buffer, + no_full_kv_block, + fake_buffers, + len_score_other, + len_mask_other, + kernel_input_name_to_buffer, + block_vars, + ): + def preprocessor(input_nodes, layout): + return input_nodes, layout + + def postprocessor(output): + return output + + template = DataProcessorTemplateWrapper( + CppFlexAttentionTemplate, + preprocessor, + postprocessor, + input_nodes=input_nodes, + layout=layout, + scale=scale, + score_mod=score_mod, + mask_mod=mask_mod, + kv_block_size=kv_block_size, + q_block_size=q_block_size, + partition_size=partition_size, + has_other_buffer=has_other_buffer, + no_full_kv_block=no_full_kv_block, + fake_buffers=fake_buffers, + len_score_other=len_score_other, + len_mask_other=len_mask_other, + kernel_input_name_to_buffer=kernel_input_name_to_buffer, + block_vars=block_vars, + ) + template.maybe_append_choice(choices) + return template + + def apply_score_mod(self, score, b, h, q_idx, kv_idx): + return self.score_mod.graph_module(score, b, h, q_idx, kv_idx).item() + + def choose_flex_template( + self, + query: ir.Buffer, + key: ir.Buffer, + num_threads, + ): + # choose from FLEX_ATTENTION or FLEX_DECODING + FLEX_TEMPLATE = FLEX_ATTENTION_TEMPLATE + q_batch_size, q_num_heads, q_seq_len, _ = query.data.data.layout.size # type: ignore[attr-defined] + k_seq_len = key.data.data.layout.size[2] # type: ignore[attr-defined] + if all( + sympy.sympify(val).is_number + for val in [q_batch_size, q_num_heads, q_seq_len, k_seq_len, num_threads] + ): + # if static shape, FLEX_DECODING will be chosen with these conditions: + # 1) partition size is multiple of kv block size, so each partition has several blocks + # 2) decoding scenario: q seq length is 1 + # 3) The actual k seq length (k_seq_len / q_batch_size) is large enough + if ( + self.partition_size % self.kv_block_size == 0 + and q_seq_len == 1 + and k_seq_len / q_batch_size >= max(self.partition_size * 2, 512) + ): + FLEX_TEMPLATE = FLEX_DECODING_TEMPLATE + return FLEX_TEMPLATE + + def render( # type: ignore[override,return] + self, + kernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + **kwargs, + ) -> str: + if epilogue_nodes is not None and epilogue_nodes != []: + raise NotImplementedError( + "Unsupported for `epilogue_nodes` in CppFlexAttentionTemplate." + ) + # Query (Batch x Num_heads x Q_seq_len x Dim_per_head) + # -> (Batch x Q_seq_len x Num_heads x Dim_per_head) + # Key (Batch x Num_heads x KV_seq_len x Dim_per_head) + # -> (Batch x KV_seq_len x Num_heads x Dim_per_head) + # Value (Batch x Num_heads x KV_seq_len x Dim_per_head) + # -> (Batch x KV_seq_len x Num_heads x Dim_per_head) + + query = kernel.permute(self.input_nodes[0], [0, 2, 1, 3]) + key = kernel.permute(self.input_nodes[1], [0, 2, 1, 3]) + value = kernel.permute(self.input_nodes[2], [0, 2, 1, 3]) + self.accumulate_dtype = torch.float + self.input_dtype = query.layout.dtype + + num_threads = parallel_num_threads() + if not isinstance(self.output_node, ir.IRNode): + raise AssertionError(f"expected ir.IRNode, got {type(self.output_node)}") + buf_out = TensorBox.create(self.output_node) + if template_buffer_node is not None: + buf_out = template_buffer_node + options = dict( + query=query, + key=key, + value=value, + kv_num_blocks=self.input_nodes[3], + kv_indices=self.input_nodes[4], + full_kv_num_blocks=( + self.input_nodes[5] if not self.no_full_kv_block else None + ), + full_kv_indices=self.input_nodes[6] if not self.no_full_kv_block else None, + score_mod_other_buffers=self.score_mod_other_buffers, + mask_mod_other_buffers=self.mask_mod_other_buffers, + scale=self.scale, + has_full_kv_block=not self.no_full_kv_block, + accumulate_dtype=self.accumulate_dtype, + query_dtype=self.input_dtype, + kvBlockSize=self.kv_block_size, + qBlockSize=self.q_block_size, + template=self, + output=buf_out, + kernel=kernel, + num_thread=num_threads, + score_mod=self.score_mod, + mask_mod=self.mask_mod, + score_buf_name=self.score_buf_name, + mask_buf_name=self.mask_buf_name, + score_buf_idx=self.score_buf_idx, + mask_buf_idx=self.mask_buf_idx, + partition_size=self.partition_size, + ) + with contextlib.ExitStack() as stack: + for buf in self.fake_buffers: + stack.enter_context( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf)) + ) + FLEX_TEMPLATE = self.choose_flex_template(query, key, num_threads) + return self._template_from_string(INIT_PARAMS + FLEX_TEMPLATE).render( + **options + ) + + def codegen_softmax_fusion(self, kernel_name: str): + # TODO: use inductor IR to rewrite those fusions + return self._template_from_string(SOFTMAX_FUSIONS).render( + dict(kernel_name=kernel_name) + ) + + def codegen_brgemm_pack_function(self, kernel_name: str): + # TODO: make them general for common bmm templates + return self._template_from_string(BRGEMM_PACK_FUNCTIONS).render( + dict(kernel_name=kernel_name) + ) + + def codegen_allocate_buffer(self, buffer_name: str, buffer_dtype, buffer_size): + return self._template_from_string(ALLOCATE_BUFFER).render( + dict( + buffer_name=buffer_name, + buffer_dtype=buffer_dtype, + buffer_size=buffer_size, + ) + ) + + def micro_gemm_define(self, kernel_name: str): + from torch._inductor.codegen.cpp_gemm_template import ( + CppTemplateKernel, + parallel_num_threads, + ) + from torch._inductor.codegen.cpp_micro_gemm import CppMicroGemmFP32Vec + from torch._inductor.virtualized import V + + micro_gemm_trans = CppMicroGemmFP32Vec( + kernel_name + "_kernel_micro_gemm_transpose_b", + self.input_dtype, + self.input_dtype, + self.accumulate_dtype, + self.accumulate_dtype, + GemmBlocking(1, 16, 1), + 1, + True, + True, + ) + + micro_gemm = CppMicroGemmFP32Vec( + kernel_name + "_kernel_micro_gemm", + self.input_dtype, + self.input_dtype, + self.accumulate_dtype, + self.accumulate_dtype, + GemmBlocking(1, 16, 1), + 1, + True, + False, + ) + + with V.set_graph_handler(V.graph): + kernel = CppTemplateKernel("cpp_micro_gemm", parallel_num_threads()) + code_trans = micro_gemm_trans.codegen_define(kernel) + code = micro_gemm.codegen_define(kernel) + return code + code_trans + + def codegen_micro_gemm(self, kernel_name: str): + micro_gemm = self.micro_gemm_define(kernel_name) + GEMM_SOURCE_CODE = MICRO_GEMM_TEMPLATE.replace("GEMM_DEFINE", micro_gemm) + return self._template_from_string(GEMM_SOURCE_CODE).render() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_gemm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_gemm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7f52ed420e051b8a9b9ac70fdca5d8233369f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_gemm_template.py @@ -0,0 +1,1968 @@ +# mypy: allow-untyped-defs +import contextlib +import logging +import math +import os +from collections.abc import Callable +from functools import lru_cache +from typing import Any, cast, TypeVar +from unittest.mock import patch + +import torch +import torch.utils +from torch.utils._ordered_set import OrderedSet + +from ..._dynamo.utils import counters +from .. import config, ir, lowering as L +from ..kernel.mm_common import mm_args +from ..select_algorithm import DataProcessorTemplateWrapper +from ..utils import ( + has_free_symbols, + is_same_mkldnn_tensor, + is_same_tensor, + parallel_num_threads, +) +from ..virtualized import ops, V +from .cpp import get_export_declaration +from .cpp_micro_gemm import ( + CppMicroBrgemm, + CppMicroGemm, + CppMicroGemmAMX, + CppMicroGemmFP32Vec, + create_micro_gemm, + is_int8_woq_gemm_small_m_dim_corner_case, + LayoutType, +) +from .cpp_template import CppTemplate +from .cpp_template_kernel import CppTemplateKernel +from .cpp_utils import ( + create_epilogue_with_attr, + DTYPE_TO_CPP, + GemmBlocking, + get_gemm_template_output_and_compute_dtype, +) + + +log = logging.getLogger(__name__) + +GEMM_TEMPLATE_INIT_BLOCKING_BASIC_BLOCK = r""" + constexpr int64_t num_threads = {{num_threads}}; + constexpr int64_t N = {{N}}; + constexpr int64_t K = {{K}}; + constexpr int64_t Mr = {{micro_gemm.register_blocking.block_m}}; + constexpr int64_t Nr = {{micro_gemm.register_blocking.block_n}}; + constexpr int64_t Kr = {{micro_gemm.register_blocking.block_k}}; + constexpr int64_t Nr_blocks = (N + Nr - 1) / Nr; + constexpr int64_t Kr_blocks = (K + Kr - 1) / Kr; +{%- if is_dynamic_M %} + const int64_t M = {{kernel.size(GemmOut, 0)}}; + const int64_t Mr_blocks = (M + Mr - 1) / Mr; +{%- else %} + constexpr int64_t M = {{kernel.size(GemmOut, 0)}}; + constexpr int64_t Mr_blocks = (M + Mr - 1) / Mr; +{%- endif %} +""" + +GEMM_TEMPLATE_INIT_BLOCKING_EXTENDED = r""" +{%- if is_dynamic_M %} + {%- if num_threads > 1 %} + int64_t Mt_blocks, Nt_blocks, Kt_blocks; + mm_get_thread_blocking(num_threads, {{config.cpp.gemm_max_k_slices}}, M, N, K, Mr, Nr, Kr, Mt_blocks, Nt_blocks, Kt_blocks); + {%- else %} + const auto Mt_blocks = Mr_blocks; + const auto Nt_blocks = Nr_blocks; + const auto Kt_blocks = Kr_blocks; + {%- endif %} + int64_t Mc_blocks, Nc_blocks, Kc_blocks; + uint32_t L1_cache_size = {{L1_cache_size}}; + uint32_t L2_cache_size = {{L2_cache_size}}; + mm_get_cache_blocking<{{kernel.dtype(X)}}, {{kernel.dtype(W)}}>( + num_threads, + M, + N, + K, + Mr, + Nr, + Kr, + Mt_blocks, + Nt_blocks, + Kt_blocks, + Mc_blocks, + Nc_blocks, + Kc_blocks, + L1_cache_size, + L2_cache_size + ); + const int64_t num_Mc_blocks = (Mr_blocks + Mc_blocks - 1) / Mc_blocks; + const int64_t num_Nc_blocks = (Nr_blocks + Nc_blocks - 1) / Nc_blocks; + const int64_t num_Mt_blocks = (Mr_blocks + Mt_blocks - 1) / Mt_blocks; + const int64_t num_Nt_blocks = (Nr_blocks + Nt_blocks - 1) / Nt_blocks; + const int64_t num_Kt_blocks = (Kr_blocks + Kt_blocks - 1) / Kt_blocks; +{%- else %} + constexpr int64_t Mt_blocks = {{template.thread_blocking(num_threads).block_m}}; + constexpr int64_t Nt_blocks = {{template.thread_blocking(num_threads).block_n}}; + constexpr int64_t Kt_blocks = {{template.thread_blocking(num_threads).block_k}}; + constexpr int64_t Mc_blocks = {{template.cache_blocking(num_threads).block_m}}; + constexpr int64_t Nc_blocks = {{template.cache_blocking(num_threads).block_n}}; + constexpr int64_t Kc_blocks = {{template.cache_blocking(num_threads).block_k}}; + constexpr int64_t num_Mc_blocks = (Mr_blocks + Mc_blocks - 1) / Mc_blocks; + constexpr int64_t num_Nc_blocks = (Nr_blocks + Nc_blocks - 1) / Nc_blocks; + constexpr int64_t num_Mt_blocks = (Mr_blocks + Mt_blocks - 1) / Mt_blocks; + constexpr int64_t num_Nt_blocks = (Nr_blocks + Nt_blocks - 1) / Nt_blocks; + constexpr int64_t num_Kt_blocks = (Kr_blocks + Kt_blocks - 1) / Kt_blocks; +{%- endif %} +{%- if is_woq_int4 %} + int64_t group_size = *q_group_size; +{%- endif %} + + // make sure all partitions are assigned + {{kernel.assert_function}}( + Mt_blocks * Nt_blocks * Kt_blocks * {{num_threads}} >= Mr_blocks * Nr_blocks * Kr_blocks, + "Not all partitions are assigned." + ); +""" + +GEMM_TEMPLATE_MULTI_THREADS_PARAMS = r""" +const int64_t k_group_id = tid / num_Kt_blocks; +const int64_t k_slice_id = tid % num_Kt_blocks; +const int64_t n_group_id = k_group_id / num_Nt_blocks; +const int64_t n_slice_id = k_group_id % num_Nt_blocks; +const int64_t k_block_start = k_slice_id * Kt_blocks; +const int64_t k_block_end = std::min(k_block_start + Kt_blocks, Kr_blocks); +const int64_t n_block_start = n_slice_id * Nt_blocks; +const int64_t n_block_end = std::min(n_block_start + Nt_blocks, Nr_blocks); +const int64_t m_block_start = std::min(n_group_id * Mt_blocks, Mr_blocks); +const int64_t m_block_end = std::min(m_block_start + Mt_blocks, Mr_blocks); +const int64_t num_Mc_blocks_per_thread = (m_block_end - m_block_start + Mc_blocks - 1) / Mc_blocks; +""" + +GEMM_TEMPLATE_SINGLE_THREAD_PARAMS = r""" +constexpr int tid = 0; +constexpr int64_t k_group_id = 0; +constexpr int64_t k_slice_id = 0; +constexpr int64_t n_group_id = 0; +constexpr int64_t n_slice_id = 0; +constexpr int64_t m_block_start = 0; +constexpr int64_t n_block_start = 0; +constexpr int64_t n_block_end = Nr_blocks; +constexpr int64_t k_block_start = 0; +constexpr int64_t k_block_end = Kr_blocks; +{%- if is_dynamic_M %} +const int64_t num_Mc_blocks_per_thread = num_Mc_blocks; +const int64_t m_block_end = Mr_blocks; +{%- else %} +constexpr int64_t num_Mc_blocks_per_thread = num_Mc_blocks; +constexpr int64_t m_block_end = Mr_blocks; +{%- endif %} +""" + +GEMM_TEMPLATE_M_LOOP_PARAMS = r""" +const int64_t my_mc_block_id = (mc_block_id + n_slice_id) % num_Mc_blocks_per_thread; +const int64_t mc = m_block_start + my_mc_block_id * Mc_blocks; +const int64_t m_start = mc * Mr; +const int64_t m_end = std::min(std::min(mc + Mc_blocks, m_block_end) * Mr, M); +const int64_t m_size = m_end - m_start; +""" + +GEMM_TEMPLATE_N_LOOP_PARAMS = r""" +const int64_t n_start = nc * Nr; +const int64_t n_end = std::min(std::min(nc + Nc_blocks, n_block_end) * Nr, N); +const int64_t n_size = n_end - n_start; +// NB: assume we pad N, nc_block_end won't exceed padded N here. +const int64_t nc_block_end = std::min(nc + Nc_blocks, n_block_end); +""" + +GEMM_TEMPLATE_MICROKERNEL_DEF = r""" +{{template.header().getvalue()}} + +{{micro_gemm.codegen_define(kernel)}} +""" + +GEMM_TEMPLATE_STUB_DEF = r""" +{%- if x_scale is not none %} + {%- set kernel_args = {"X": X, "W": W, "inp": inp, "x_scale": x_scale, "x_zp": x_zp, "w_scale": w_scale, "w_zp": w_zp,} %} +{%- elif is_woq_int4 %} + {%- set kernel_args = {"X": X, "W": W, "q_group_size": q_group_size, "qscale_and_zeros": qscale_and_zeros} %} +{%- else %} + {%- set kernel_args = {"X": X, "W": W, "inp": inp} %} +{%- endif %} + +extern "C" {{export_declaration}} +{{kernel.def_kernel(inputs=kernel_args, outputs={"Y": Y}, aliases=aliases)}} +""" + +GEMM_TEMPLATE = r""" +{{ template.codegen_gemm_stub_def() }} +{ + {{ kernel.maybe_codegen_profile(template.get_kernel_prefix_name()) }} + {{ template.codegen_blocks( + num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOut, config, L1_cache_size, L2_cache_size, X, W + ) }} + +{%- if maybe_k_slicing %} + std::unique_ptr[]> local_buf_ptrs; + const int64_t num_Mc_blocks_per_thread_block = (Mt_blocks + Mc_blocks - 1) / Mc_blocks; + const int64_t num_Nc_blocks_per_thread_block = (Nt_blocks + Nc_blocks - 1) / Nc_blocks; + if (num_Kt_blocks > 1) { + local_buf_ptrs.reset(new std::unique_ptr<{{DTYPE_TO_CPP[acc_buf_dtype]}}[]>[ + num_Mt_blocks * num_Nt_blocks * + num_Mc_blocks_per_thread_block * num_Nc_blocks_per_thread_block * + num_Kt_blocks + ]); + } +{%- endif %} + +{%- if num_threads > 1 %} + {%- set use_dynamic_threads = ((config.cpp.threads < 1) and (num_threads == cpu_count)) or config.cpp.dynamic_threads %} + {%- if use_dynamic_threads %} + #pragma omp parallel + {%- else %} + #pragma omp parallel num_threads({{num_threads}}) + {%- endif %} + { + {{ micro_gemm.codegen_init(kernel) }} + #pragma omp for schedule(static, 1) + for (int64_t tid = 0; tid < {{num_threads}}; tid++) { + {{ template.codegen_multi_threads_params()|indent(12, false) }} +{%- else %} + { + {{ template.codegen_single_thread_params(is_dynamic_M)|indent(8, false) }} + {{ micro_gemm.codegen_init(kernel) }} +{%- endif %} +{%- if use_local_acc %} + {%- set acc_buf_name = "local_acc_buf" %} + {{ kernel.define_buffer(acc_buf_name, ["Mc_blocks*Mr", "Nc_blocks*Nr"], acc_buf_dtype) }} +{%- endif %} + for (int64_t mc_block_id = 0; mc_block_id < num_Mc_blocks_per_thread; mc_block_id++) { + {{ template.codegen_m_loop_params()|indent(12, false) }} + for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) { + {{ template.codegen_n_loop_params()|indent(16, false) }} +{%- if use_local_acc %} + {%- set acc = kernel.local_buffers[acc_buf_name] %} + {{ kernel.reinit_buffer_if_null(acc_buf_name) }} +{%- else %} + {%- set acc = kernel.slice_nd(GemmOut, [("m_start", "m_end"), ("n_start", "n_end")]) %} +{%- endif %} + for (int64_t kc = k_block_start; kc < k_block_end; kc += Kc_blocks) { + int64_t k_start = kc * Kr; + int64_t k_end = std::min(std::min(kc + Kc_blocks, k_block_end) * Kr, K); +{%- set tile_X = kernel.slice_nd(X, [("m_start", "m_end"), ("k_start", "k_end")]) %} + for (int64_t nci = nc; nci < nc_block_end; nci++) { +{%- set acc_slice = kernel.slice_nd(acc, [("0", "m_end - m_start"), ("(nci - nc)*Nr", "(nci - nc + 1)*Nr")]) %} +{%- if template.should_block_weights and not is_woq_int4 %} +{%- set tile_W_3d = kernel.slice_nd(W, [("nci", "nci + 1"), ("k_start", "k_end"), ()]) %} +{%- set tile_W = kernel.view(tile_W_3d, ["k_end - k_start", micro_gemm.register_blocking.block_n]) %} +{%- else %} + {%- if is_woq_int4 %} + {%- set tile_W = kernel.slice_nd(W, [("nci * Nr", "(nci + 1) * Nr"), ("k_start * Nr / 2", "k_end * Nr / 2")]) %} + {%- set tile_qparam = kernel.slice_nd( + qscale_and_zeros, [("k_start // group_size", "k_end // group_size"), ("nci * Nr", "(nci + 1) * Nr"), ()]) %} + {%- else %} + {%- set tile_W = kernel.slice_nd(W, [("k_start", "k_end"), ("n_start", "n_start + n_size")]) %} + {%- set tile_qparam = None %} + {%- endif %} +{%- endif %} + if (kc == k_block_start) { + {{ micro_gemm.codegen_call(kernel, + tile_X, + tile_W, + acc_slice, + accum=False, + qscale_and_zeros=tile_qparam)|indent(28, false) + }} + } else { + {{ micro_gemm.codegen_call(kernel, + tile_X, + tile_W, + acc_slice, + accum=True, + qscale_and_zeros=tile_qparam)|indent(28, false) + }} + } + } + } +{%- if maybe_k_slicing %} + if (num_Kt_blocks > 1) { + const int64_t n_cache_block_id = (nc - n_block_start) / Nc_blocks; + const int64_t mxn_cache_block_id = + ((n_group_id * num_Nt_blocks + n_slice_id) * + num_Mc_blocks_per_thread_block + my_mc_block_id) * + num_Nc_blocks_per_thread_block + + n_cache_block_id; + local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks + k_slice_id].reset( + {{ kernel.release_buffer(acc_buf_name) }}); + } else +{%- endif %} + { +{%- set tile_Y = kernel.slice_nd(Y_2d, [("m_start", "m_end"), ("n_start", "n_end")]) %} +{%- set tile_acc = kernel.slice_nd(acc, [("0", "m_end - m_start"), ("0", "n_end - n_start")]) %} + {{ kernel.store_output( + tile_Y, tile_acc, GemmOut, epilogue_nodes, offsets=("m_start", "n_start"), reindexers=reindexers + )|indent(20, false) + }} + } + } + } +{%- if num_threads > 1 %} + } +{%- if maybe_k_slicing %} + if (num_Kt_blocks > 1) { + #pragma omp for schedule(static, 1) + for (int64_t tid = 0; tid < {{num_threads}}; tid++) { + {{ template.codegen_multi_threads_params()|indent(16, false) }} + for (int64_t mc = m_block_start; mc < m_block_end; mc += Mc_blocks) { + // We slice M-dim and each thread in the k-slicing group works on a slice + const int64_t m_start_unsliced = mc * Mr; + const int64_t m_end_unsliced = std::min(std::min(mc + Mc_blocks, m_block_end) * Mr, M); + const int64_t m_size_unsliced = m_end_unsliced - m_start_unsliced; + const int64_t m_slice_size = (m_size_unsliced + num_Kt_blocks - 1) / num_Kt_blocks; + const int64_t m_start = std::min(m_start_unsliced + m_slice_size * k_slice_id, m_end_unsliced); + const int64_t m_end = std::min(m_start_unsliced + m_slice_size * (k_slice_id + 1), m_end_unsliced); + const int64_t m_size = m_end - m_start; + const int64_t m_offset = m_start - m_start_unsliced; + const int64_t m_cache_block_id = (mc - m_block_start) / Mc_blocks; + for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) { + const int64_t n_start = nc * Nr; + const int64_t n_end = std::min(std::min(nc + Nc_blocks, n_block_end) * Nr, N); + const int64_t n_size = n_end - n_start; + const int64_t n_cache_block_id = (nc - n_block_start) / Nc_blocks; + const int64_t mxn_cache_block_id = + ((n_group_id * num_Nt_blocks + n_slice_id) * + num_Mc_blocks_per_thread_block + m_cache_block_id) * + num_Nc_blocks_per_thread_block + + n_cache_block_id; + auto {{acc_buf_name}} = local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks].get(); + for (int64_t other_slice = 1; other_slice < num_Kt_blocks; other_slice++) { + auto other_acc = local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks + other_slice].get(); + for (int64_t m = m_offset; m < m_offset + m_size; m++) { + #pragma omp simd + for (int64_t n = 0; n < n_size; n++) { + {{acc_buf_name}}[m*Nc_blocks*Nr + n] += other_acc[m*Nc_blocks*Nr + n]; + } + } + } + {%- set tile_Y_m_slice = kernel.slice_nd(Y_2d, [("m_start", "m_start + m_size"), ("n_start", "n_start + n_size")]) %} + {%- set tile_acc_full = kernel.slice_nd(acc, [("0", "m_size_unsliced"), ("0", "n_size")]) %} + {%- set tile_acc_m_slice = kernel.slice_nd(tile_acc_full, [("m_offset", "m_offset + m_size"), ()]) %} + {{ kernel.store_output( + tile_Y_m_slice, tile_acc_m_slice, GemmOut, epilogue_nodes, offsets=("m_start", "n_start"), reindexers=reindexers + )|indent(20, false) + }} + } + } + } + } +{%- endif %} + {{ micro_gemm.codegen_finalize(kernel) }} + } +{%- else %} + {{ micro_gemm.codegen_finalize(kernel) }} + } +{%- endif %} +} +""" + +SMALL_M_GEMM_TEMPLATE = r""" +{{ template.codegen_gemm_stub_def() }} +{ + {{ kernel.maybe_codegen_profile() }} + {{ template.codegen_blocks( + num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOut, config, L1_cache_size, L2_cache_size, X, W + ) }} + # pragma omp parallel + { + #pragma omp for nowait + for (int64_t nr_block_id = 0; nr_block_id < Nr_blocks; nr_block_id++) { + // Handle one output M * Nr block in each thread + int64_t n_start = nr_block_id * Nr; + int64_t n_end = (nr_block_id + 1) * Nr; +{%- if use_local_acc %} + {%- set acc_buf_name = "local_acc_buf" %} + {{ kernel.define_stack_allocated_buffer(acc_buf_name, ["M", "Nr"], acc_buf_dtype) }} + {%- set acc = kernel.local_buffers[acc_buf_name] %} +{%- else %} + {%- set acc = kernel.slice_nd(GemmOut, [(0, "M"), ("n_start", "n_end")]) %} +{%- endif %} + for (int64_t kr_block_id = 0; kr_block_id < Kr_blocks; kr_block_id++) { + // this loop is not parallelized + int64_t k_start = kr_block_id * Kr; + int64_t k_end = std::min((kr_block_id + 1) * Kr, K); +{%- set tile_X = kernel.slice_nd(X, [(0, "M"), ("k_start", "k_end")]) %} +{%- set tile_W_3d = kernel.slice_nd(W, [("nr_block_id", "nr_block_id + 1"), ("k_start", "k_end"), ()]) %} +{%- set tile_W = kernel.view(tile_W_3d, ["k_end - k_start", micro_gemm.register_blocking.block_n]) %} + if C10_UNLIKELY(kr_block_id == 0) { + {{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=False, prefetch=True)|indent(20, false) }} + } else if C10_UNLIKELY(k_end == K) { + {{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=True, prefetch=False)|indent(20, false) }} + } else { + {{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=True, prefetch=True)|indent(20, false) }} + } + } +{%- set tile_Y = kernel.slice_nd(Y_2d, [("0", "M"), ("n_start", "n_end")]) %} +{%- set tile_acc = kernel.slice_nd(acc, [("0", "M"), ("0", "n_end - n_start")]) %} + {{ kernel.store_output( + tile_Y, tile_acc, GemmOut, epilogue_nodes, offsets=("0", "n_start"), reindexers=reindexers + )|indent(20, false) }} + } + } +} +""" + + +def _is_int8_gemm(inputs): + return ( + isinstance(inputs[0], ir.IRNode) + and inputs[0].get_dtype() in [torch.uint8, torch.int8] + ) or ( + isinstance(inputs[0], torch.Tensor) + and inputs[0].dtype in [torch.uint8, torch.int8] + ) + + +def get_padded_n(n, block_n): + return (n + block_n - 1) // block_n * block_n + + +_T = TypeVar("_T", ir.IRNode, torch.Tensor) + + +def transpose_w(W: _T, trans_w: bool) -> _T: + """ + Transpose W based on the trans_w flag. + """ + if isinstance(W, ir.IRNode): + if trans_w: + if not isinstance(W, ir.TensorBox): + # pyrefly: ignore [bad-assignment] + W = ir.TensorBox(W) + W = L.permute(W, [1, 0]) + else: + if trans_w: + if not isinstance(W, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(W)}") + # pyrefly: ignore [bad-assignment] + W = W.transpose(0, 1) + # pyrefly: ignore [bad-return] + return W + + +def expand_bias(B: _T | None, X: _T) -> _T | None: + """ + Expand Bias to the same size of X. + """ + if B is not None: + if isinstance(B, ir.IRNode): + if not isinstance(B, ir.TensorBox): + # pyrefly: ignore [bad-assignment] + B = ir.TensorBox(B) + if not hasattr(X, "get_size"): + raise AssertionError("expected X to have a get_size attribute") + # pyrefly: ignore [missing-attribute] + B = L.expand(B, (X.get_size()[0], B.get_size()[-1])) + else: + if not isinstance(B, torch.Tensor): + raise AssertionError(f"expected B to be torch.Tensor, got {type(B)}") + if not isinstance(X, torch.Tensor): + raise AssertionError(f"expected X to be torch.Tensor, got {type(X)}") + # pyrefly: ignore [bad-assignment] + B = B.expand(X.shape[0], B.shape[-1]) + return B + + +def prune_tensors(input_nodes: list[ir.IRNode], new_input_nodes: list[ir.IRNode]): + """ + Prune unused tensors from `V.graph` since the GEMM Template use new packed weight. + """ + + def share_storage(base_tensor: torch.Tensor, comp_tensor: torch.Tensor): + return base_tensor.is_mkldnn == comp_tensor.is_mkldnn and ( + is_same_tensor(base_tensor, comp_tensor) + or is_same_mkldnn_tensor(base_tensor, comp_tensor) + ) + + def get_candidates(input_nodes, new_input_nodes): + # Only Constant Buffer like weight and bias might be changed in GEMM Template. + # The Inductor IR Node may changed, but still share the storage. For example: + # bias in bfloat16 case which only do the expand + return [ + node + for node in input_nodes + if ( + node not in new_input_nodes + and isinstance(node, (ir.TensorBox, ir.StorageBox)) + and node.get_name() in V.graph.constants + and not any( + ( + isinstance(new_node, (ir.TensorBox, ir.StorageBox)) + and new_node.get_name() in V.graph.constants + and share_storage( + V.graph.constants[node.get_name()], + V.graph.constants[new_node.get_name()], + ) + ) + for new_node in new_input_nodes + ) + ) + ] + + for candidate_node in get_candidates(input_nodes, new_input_nodes): + # By using the new packed weight for the GEMM template, we can prune the + # old weight if it has no other users. This saves memory but makes the FX graph + # non-retraceable. To support retracing, we can add a repack node to the + # FX graph. For example: + # mkldnn._linear_pointwise <- repack_linear_wgt <- packed_wgt_for_template + candidate_tensor_users = 0 + candidate_tensor = V.graph.constants[candidate_node.get_name()] + for node in reversed(V.graph.graph.nodes): + # Case may happen when the candidate tensor is used by more than 1 get_attr node + # https://github.com/pytorch/pytorch/issues/134998 + if node.op == "get_attr" and hasattr( + V.graph.module, node.target + ): # candidate tensor might already be deleted + comp_tensor = getattr(V.graph.module, node.target) + if isinstance(comp_tensor, torch.Tensor) and share_storage( + candidate_tensor, comp_tensor + ): + candidate_tensor_users += 1 + + for node in reversed(V.graph.graph.nodes): + # The get_attr node has only 1 user fx node + # The candidate tensor has been used by only 1 get_attr node + if ( + node.op == "get_attr" + and node.target == candidate_node.get_name() + and len(node.users) == 1 + and candidate_tensor_users == 1 + ): + del V.graph.constants[node.target] + delattr(V.graph.module, node.target) + delattr(V.graph.graph.owning_module, node.target) + counters["inductor"]["select_algorithm_weight_prune"] += 1 + + +def gen_2d_view_of_epilogue_buf( + Y: ir.Buffer, + template_buffer: ir.Buffer, + epilogue_nodes: list[ir.IRNode], + reindexers: list[Callable[[list[Any]], list[Any]] | None], + default_reindexers: list[Callable[[list[Any]], list[Any]] | None], +) -> tuple[ + ir.Buffer | ir.ReinterpretView, + list[Callable[[list[Any]], list[Any]] | None], +]: + """ + The dimension and the indexing could be different between the GEMM output, i.e. `template_buffer`, which is + 2D with MxN) and the output from the template after epilogues, i.e. `Y`. In the GEMM template code, + we are not aware of the dimension and the indexing of the epilogues and always work on 2D tiles according to + the indexing of the GEMM output. + In this function, we return a 2D buffer (`Y_2d`) according to GEMM output (reinterpreted from `Y` if needed) and + build a reindexer that converts the indexing of `Y` into `Y_2d`. + """ + Y_2d: ir.Buffer | ir.ReinterpretView = Y + if ( + Y.get_size() == template_buffer.get_size() + and Y.get_stride() == template_buffer.get_stride() + ): + reindexers.extend(default_reindexers) + Y_2d = Y + else: + + def get_reindexer(epilogue_node, default_reindexer=None): + # From template_buffer to epilogue_node_ordered (ordered by stride decreasingly, in dense format), for example: + # template_buffer: + # size (324, 512), stride (512, 1) + # epilogue_node_ordered (ordered by stride decreasingly, in dense format): + # size (1, 18, 18, 512), stride (165888, 9216, 512, 1) + stride_order = list( + ir.get_stride_order( + V.graph.sizevars.guarding_hints_or_throw(epilogue_node.get_stride()) + ) + ) + fill_order = ir.stride_order2fill_order(stride_order) + reversed_fill_order = list(reversed(fill_order)) + size_with_stride_ordered_decreasingly = [ + epilogue_node.get_size()[i] for i in reversed_fill_order + ] + reshape_reindex = ir.View.dynamic_reshape_indexer( + size_with_stride_ordered_decreasingly, + template_buffer.get_size(), + ) + if default_reindexer: + reshape_reindex = ir.fuse_reindexing(reshape_reindex, default_reindexer) + + # From epilogue_node_ordered (ordered by stride decreasingly, in dense format) to epilogue_node, for example: + # epilogue_node_ordered (ordered by stride decreasingly, in dense format): + # size (1, 18, 18, 512), stride (165888, 9216, 512, 1) + # epilogue_node: + # size (1, 18, 18, 512), stride (165888, 1, 9216, 512) + from_stride_ordered_decreasingly_to_epilogue_node_order = [ + (len(stride_order) - 1) - stride_order[i] + for i in range(len(stride_order)) + ] + stride_reindex = ir.same_reorder( + from_stride_ordered_decreasingly_to_epilogue_node_order + ) + + reindexer = ir.fuse_reindexing(stride_reindex, reshape_reindex) # type: ignore[var-annotated] + return reindexer + + if default_reindexers is None: + default_reindexers = [None] * len(epilogue_nodes) + new_reindexers = [ + get_reindexer(epilogue_node, default_reindexer) + for epilogue_node, default_reindexer in zip( + epilogue_nodes, default_reindexers + ) + ] + reindexers.extend(new_reindexers) + if isinstance(Y, ir.BaseView): + storage = ir.StorageBox(Y.unwrap_view()) + else: + if not isinstance(Y, ir.Buffer): + raise AssertionError(f"expected ir.Buffer, got {type(Y)}") + storage = ir.StorageBox(Y) + Y_2d = ir.ReinterpretView(data=storage, layout=template_buffer.get_layout()) + return Y_2d, reindexers + + +class CppGemmTemplate(CppTemplate): + """ + GEMM Template for Inductor CPP Backend. + """ + + def __init__( + self, + input_nodes, + layout: ir.Layout, + num_threads: int, + register_blocking: GemmBlocking, + beta=1, + alpha=1, + has_bias=False, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + should_block_weights: bool = True, + name="packed_gemm", + ) -> None: + if layout.dtype not in [ + torch.float, + torch.bfloat16, + torch.half, + torch.uint8, + torch.int8, + ]: + raise AssertionError(f"Unsupported layout dtype: {layout.dtype}") + super().__init__( + name, + input_nodes, + layout, + num_threads, + epilogue_creator=epilogue_creator, + ) + self.beta = beta + self.alpha = alpha + self.has_bias = has_bias + self.register_blocking = register_blocking + m, n = layout.size[-2:] + k = input_nodes[0].get_size()[-1] + self.m, self.n, self.k = m, n, k + self.padded_n = get_padded_n(n, self.register_blocking.block_n) + self.is_dynamic_M = has_free_symbols((m,)) + self.should_block_weights = should_block_weights + self.thread_blocking = self.make_thread_blocking_cache() + self.cache_blocking = self.make_cache_blocking_cache() + + def make_thread_blocking_cache(self): + cache = lru_cache()(self._thread_blocking) + + def thread_blocking(num_threads: int) -> GemmBlocking: + return cache(num_threads) + + return thread_blocking + + def _thread_blocking(self, num_threads: int) -> GemmBlocking: + """ + NOTE [Thread blocking in Cpp GEMM] + We use simple heuristics to decide the thread blocking: + 1. Make sure all threads are occupied as much as possible. + 2. For (m, n) blocks, favor more square-sized thread blocks for better data reuse. + 3. If (m, n) blocks cannot occupy all the threads, we consider k-slicing. + TODO(jgong5): allow tuning various blocking options + """ + + def get_factors(number): + factors = [] + for i in range(int(number**0.5), 0, -1): + if number % i == 0: + factors.append(number // i) + factors.append(i) + return factors + + def get_blocking(m_factor, n_factor, k_factor, m_blocks, n_blocks, k_blocks): + thread_block_k = math.ceil(k_blocks / k_factor) + thread_block_n = math.ceil(n_blocks / n_factor) + thread_block_m = math.ceil(m_blocks / m_factor) + return GemmBlocking(thread_block_m, thread_block_n, thread_block_k) + + if self.is_dynamic_M: + raise AssertionError("Unable to determine thread blocking for dynamic M.") + register_blocking = self.register_blocking + m_blocks = math.ceil(self.m / register_blocking.block_m) + n_blocks = math.ceil(self.n / register_blocking.block_n) + k_blocks = math.ceil(self.k / register_blocking.block_k) + factors = get_factors(num_threads) + if len(factors) == 0: + raise AssertionError(f"expected at least one factor, got {factors}") + + if config.cpp.gemm_thread_factors is not None: + factors = [int(i) for i in config.cpp.gemm_thread_factors.split(",")] + if len(factors) != 3: + raise AssertionError(f"expected 3 thread factors, got {len(factors)}") + if math.prod(factors) != self.num_threads: + raise AssertionError( + f"expected factors product == {self.num_threads}, " + f"got {math.prod(factors)}" + ) + return get_blocking( + factors[0], factors[1], factors[2], m_blocks, n_blocks, k_blocks + ) + + # we favor square-sized thread blocks for good data reuse + def get_better_blocking(blocking, best_blocking): + if best_blocking is None: + best_blocking = blocking + else: + block_m_size = blocking.block_m * register_blocking.block_m + block_n_size = blocking.block_n * register_blocking.block_n + best_block_m_size = best_blocking.block_m * register_blocking.block_m + best_block_n_size = best_blocking.block_n * register_blocking.block_n + if blocking.block_k > best_blocking.block_k: + best_blocking = blocking + elif ( + blocking.block_k == best_blocking.block_k + and block_m_size + block_n_size + < best_block_m_size + best_block_n_size + ): + best_blocking = blocking + return best_blocking + + best_blocking = None + # check if we can have a thread-blocking to occupy all threads without k-slicing + for n_factor in factors: + m_factor = num_threads // n_factor + if n_blocks >= n_factor and m_blocks >= m_factor: + blocking = get_blocking( + m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks + ) + best_blocking = get_better_blocking(blocking, best_blocking) + + if best_blocking is None: + for k_factor in factors: + if k_blocks >= k_factor and ( + config.cpp.gemm_max_k_slices == 0 + or k_factor <= config.cpp.gemm_max_k_slices + ): + n_factors = get_factors(num_threads // k_factor) + for n_factor in n_factors: + m_factor = (num_threads // k_factor) // n_factor + if n_blocks >= n_factor and m_blocks >= m_factor: + blocking = get_blocking( + m_factor, + n_factor, + k_factor, + m_blocks, + n_blocks, + k_blocks, + ) + best_blocking = get_better_blocking(blocking, best_blocking) + + if best_blocking is None: + for n_factor in factors: + m_factor = num_threads // n_factor + if n_blocks >= n_factor or m_blocks >= m_factor: + blocking = get_blocking( + m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks + ) + best_blocking = get_better_blocking(blocking, best_blocking) + + if best_blocking is None: + raise AssertionError("expected a valid thread blocking, got None") + return best_blocking + + def make_cache_blocking_cache(self): + cache = lru_cache()(self._cache_blocking) + + def cache_blocking(num_threads: int) -> GemmBlocking: + return cache(num_threads) + + return cache_blocking + + def _cache_blocking(self, num_threads: int) -> GemmBlocking: + def get_cache_blocking(register_blocking, thread_blocking): + Mr = register_blocking.block_m + Nr = register_blocking.block_n + Kr = register_blocking.block_k + + Mt_blocks = thread_blocking.block_m + Nt_blocks = thread_blocking.block_n + Kt_blocks = thread_blocking.block_k + + if config.cpp.gemm_cache_blocking is not None: + blockings = [int(i) for i in config.cpp.gemm_cache_blocking.split(",")] + if len(blockings) != 3: + raise AssertionError( + f"expected 3 cache blockings, got {len(blockings)}" + ) + Mc_blocks, Nc_blocks, Kc_blocks = blockings + return ( + min(Mc_blocks, Mt_blocks), + min(Nc_blocks, Nt_blocks), + min(Kc_blocks, Kt_blocks), + ) + + # The ratios below are empirically determined to decide + # the effective sizes of L1 and L2. + # TODO: tune the factor here + L1_limit_factor = 0.8 + L2_limit_factor = 0.5 + + L1_cache_size = torch.cpu.get_capabilities().get( + "l1d_cache_size", 0 + ) # per core cache size in Bytes + if L1_cache_size <= 0: + raise AssertionError( + f"Expect L1_cache_size > 0 but got {L1_cache_size}" + ) + L1 = L1_cache_size * L1_limit_factor + + L2_cache_size = torch.cpu.get_capabilities().get( + "l2_cache_size", 0 + ) # per core cache size in Bytes + if L2_cache_size <= 0: + raise AssertionError( + f"Expect L2_cache_size > 0 but got {L2_cache_size}" + ) + L2 = L2_cache_size * L2_limit_factor + + def get_num_byte(dtype): + return torch.tensor([], dtype=dtype).element_size() + + dtype_A = self.input_nodes[0].get_dtype() + dtype_B = self.input_nodes[1].get_dtype() + num_byte_A = get_num_byte(dtype_A) + num_byte_B = get_num_byte(dtype_B) + if dtype_A is torch.bfloat16 and dtype_B is torch.int8 and Kr != 1: + # We will cache dequantized weights (BF16) in L1D for AMX micro-kernel. + # In this case, the choice of the micro-kernel being used can't be decoupled from + # the cache blocking. + # TODO: Decouple the choice of micro-kernel from cache blocking + num_byte_B *= num_byte_A + + # NOTE [CPP GEMM Cache Blocking Algorithm] + # Our overall strategy is to + # 1) Make cache blocks of B L1-reside and reused by multiple rows of A, i.e. Mc. + # Here, B is Kc x Nr where Nr is a single register block. We use L1 size to + # decide Kc. We want to make Mc large enough to better reuse B. + # 2) Make cache blocks of A L2-reside, which would limit Mc. We want to reuse A + # along N, where we have two sub-strategies (see notes below) to decide Mc and Nc. + + # Step 1: Decide Kc assuming B block is L1-reside. + size_cache_B = Kr * Kt_blocks * Nr * num_byte_B + + Kc_blocks = Kt_blocks + if size_cache_B > L1: + Kc_blocks = math.floor(L1 / (Kr * Nr * num_byte_B)) + + if ( + config.cpp.use_small_dequant_buffer + and dtype_A is torch.bfloat16 + and Mt_blocks == 1 + ): + if dtype_B is torch.uint8: + # A16W4 + # Make a small dequant_B buffer for woq int4 [q_group_size, Nr] + # Since when Mt_blocks == 1, L1-reside B block can't be reused by A. + if Kc_blocks * Kr >= self.q_group_size(): + Kc_blocks = self.q_group_size() // Kr + + elif dtype_B is torch.int8: + # A16W8 + # Make A, B, C buffer in L1 + A_buf_size_div_K = self.m * num_byte_A + B_buf_size_div_K = Nr * num_byte_B + # assume acc in float32/int32 and Mc_blocks = Nc_blocks = 1 + C_buf_size = Mr * Nr * 4 + K_block_size = (L1 - C_buf_size) // ( + A_buf_size_div_K + B_buf_size_div_K + ) + if Kc_blocks * Kr >= K_block_size: + Kc_blocks = (K_block_size + Kr - 1) // Kr + + # Step 2: Decide Mc assuming A block is L2-reside. + min_Mc_ratio = 2 # TODO(jgong5): something to tune? + min_Mc_blocks = math.ceil(min_Mc_ratio * Mr / Nr) + if min_Mc_blocks < 1: + raise AssertionError( + f"expected min_Mc_blocks >= 1, got {min_Mc_blocks}" + ) + Kt_bytes = Kt_blocks * Kr * num_byte_A + if min_Mc_blocks * Mr * Kt_bytes < L2: + # Strategy 1: A (Mc x Kt) resides in L2 and reused by all Nt + # when Nc_blocks is kept 1. Mc should be large enough (>= min_Mc_blocks) + # to reuse B (Kc x Nr) in L1. This makes C (Mc x Nr) small enough to reside + # in L1. + Mc_blocks = min(Mt_blocks, math.floor(L2 / (Mr * Kt_bytes))) + Nc_blocks = 1 + else: + # Strategy 2: Kt is too large to hold A (Mc x Kt) in L2, we reuse + # A (Mc x Kc) in L2 by B (Kc x Nc). C (Mc x Nc) resides in L2. + Mc_blocks = Mt_blocks + Nc_blocks = min(math.ceil(Mc_blocks * Mr / Nr), Nt_blocks) + Nc_bytes = Nc_blocks * Nr * 4 # assume C or acc is float32/int32 + Kc_bytes = Kc_blocks * Kr * num_byte_A + if Mc_blocks * Mr * (Kc_bytes + Nc_bytes) > L2: + # The following is the solution for 4*Mc*Nc + Mc*Kc_bytes = L2, + # assuming Mc == Nc for good data reuse. + M_max = (math.sqrt(Kc_bytes * Kc_bytes + 16 * L2) - Kc_bytes) / 8 + if M_max < Mc_blocks * Mr: + Mc_blocks = math.floor(M_max / Mr) + Nc_blocks = min(math.ceil(Mc_blocks * Mr / Nr), Nt_blocks) + + return Mc_blocks, Nc_blocks, Kc_blocks + + if self.is_dynamic_M: + raise AssertionError("Unable to determine cache blocking for dynamic M.") + register_blocking = self.register_blocking + thread_blocking = self.thread_blocking(num_threads) + + return GemmBlocking(*get_cache_blocking(register_blocking, thread_blocking)) + + def log_blockings(self): + log.debug(f"Register blocking: {self.register_blocking}") # noqa: G004 + if self.is_dynamic_M: + # thread and cache blockings are determined at runtime for dynamic shapes + return + log.debug( + f"Cache blocking: {self.cache_blocking(self.num_threads)}" # noqa: G004 + ) + thread_blocking = self.thread_blocking(self.num_threads) + log.debug(f"Thread blocking: {thread_blocking}") # noqa: G004 + + def get_occupancy(): + m_blocks = math.ceil(self.m / self.register_blocking.block_m) + n_blocks = math.ceil(self.n / self.register_blocking.block_n) + k_blocks = math.ceil(self.k / self.register_blocking.block_k) + m = math.ceil(m_blocks / thread_blocking.block_m) + n = math.ceil(n_blocks / thread_blocking.block_n) + k = math.ceil(k_blocks / thread_blocking.block_k) + return (m, n, k) + + log.debug( + f"Number of threads: {self.num_threads}, occupancy: {get_occupancy()}" # noqa: G004 + ) + + def maybe_k_slicing(self): + if self.num_threads == 1: + return False + if self.is_dynamic_M: + # TODO(jgong5): perhaps use size hint to decide? + return True + register_blocking = self.register_blocking + k_blocks = math.ceil(self.k / register_blocking.block_k) + thread_blocking = self.thread_blocking(self.num_threads) + return k_blocks > thread_blocking.block_k + + @classmethod + def add_choices( + cls, + choices, + layout, + input_nodes, + beta=1, + alpha=1, + has_bias=False, + trans_w=False, + input_indices=None, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + act_mapping: dict[int, ir.IRNode] | None = None, + ): + """ + Add choices for the GEMM template. + """ + # Fast path to save the epilogue calculation when x_scale/x_zp/w_scale are constant + use_int8_fast_compensation_path = _is_int8_gemm(input_nodes) and all( + ( + isinstance(input_nodes[idx], ir.TensorBox) + and isinstance(input_nodes[idx].data.data, ir.ConstantBuffer) + ) + for idx in [1, 2, 4] + ) + + if input_indices is None: + input_indices = list(range(len(input_nodes))) + + deduped_input_indices = [] + deduped_name_to_idx: dict[str, int] = {} + for input_node in input_nodes: + input_name = input_node.get_name() + if input_name not in deduped_name_to_idx: + deduped_name_to_idx[input_name] = len(deduped_name_to_idx) + deduped_input_indices.append(deduped_name_to_idx[input_name]) + + def indices_for_inputs(inputs): + if len(inputs) == len(input_nodes): + return input_indices + if len(inputs) != len(deduped_name_to_idx): + raise AssertionError( + f"expected {len(deduped_name_to_idx)} inputs, got {len(inputs)}" + ) + return [deduped_input_indices[idx] for idx in input_indices] + + def reorder_and_filter(inputs, layout_or_out): + current_input_indices = indices_for_inputs(inputs) + if has_bias: + if len(current_input_indices) < 3: + raise AssertionError( + f"expected >= 3 input indices, got {len(current_input_indices)}" + ) + # Assume the input order is [inp, x, w] and we reorder it to [x, w, inp] + inp_idx = current_input_indices[0] + x_idx = current_input_indices[1] + w_idx = current_input_indices[2] + return [ + inputs[x_idx], + inputs[w_idx], + inputs[inp_idx], + *[inputs[idx] for idx in current_input_indices[3:]], + ], layout_or_out + else: + if len(current_input_indices) < 2: + raise AssertionError( + f"expected >= 2 input indices, got {len(current_input_indices)}" + ) + return [inputs[idx] for idx in current_input_indices], layout_or_out + + new_inputs, new_layout = reorder_and_filter(input_nodes, layout) + is_mkldnn_wgt = ( + new_inputs[1].get_name() in V.graph.constants + and V.graph.constants[new_inputs[1].get_name()].is_mkldnn + ) + if is_mkldnn_wgt: + # It shouldn't happen as viewing an mkldnn tensor, we can extend the + # implementation if it does. + if isinstance(new_inputs[1], ir.BaseView): + raise AssertionError("expected mkldnn weight to not be a BaseView") + # Note that the layout of MKLDNN Tensor is with the wrong stride + view_size = new_inputs[1].layout.size + view_stride = new_inputs[1].layout.stride + view_offset = new_inputs[1].layout.offset + + def maybe_to_dense(inputs, layout_or_out): + new_inputs = list(inputs) + if isinstance(inputs[1], torch.Tensor): + W = inputs[1] + new_inputs[1] = W.to_dense() if W.is_mkldnn else W + return new_inputs, layout_or_out + + def normalize_shapes(inputs, layout_or_out): + new_inputs = list(inputs) + if not is_mkldnn_wgt and isinstance(new_inputs[1], torch.Tensor): + if has_free_symbols(view_size): + # If batch size B is dynamic, we need to set the batch size and possibly stride + if has_free_symbols(view_size[1:]): + raise AssertionError( + "expected no free symbols in view_size[1:]" + ) + view_size[:] = V.graph.sizevars.guarding_hints_or_throw(view_size) + view_stride[:] = V.graph.sizevars.guarding_hints_or_throw( + view_stride + ) + # With the assumptation that W is the storage of unwrap view + # thus view it back here + new_inputs[1] = new_inputs[1].as_strided( + view_size, view_stride, view_offset + ) + + if not trans_w: + return new_inputs, layout_or_out + X = new_inputs[0] + W = new_inputs[1] + B = new_inputs[2] if has_bias else None + W = transpose_w(W, trans_w) + B = expand_bias(B, X) # type:ignore[arg-type] + new_inputs[1] = W + if B is not None: + new_inputs[2] = B + return new_inputs, layout_or_out + + # TODO(jgong5): decide proper number of threads per problem size + num_threads = parallel_num_threads() + new_inputs, _ = normalize_shapes(*maybe_to_dense(new_inputs, new_layout)) + m, n, k, *_ = mm_args( + new_inputs[0], + new_inputs[1], + mat2_transposed=cls.is_woq_int4(), + use_4x2_dim=cls.is_woq_int4(), + ) + output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype( + new_inputs[0].get_dtype() + ) + micro_gemm = create_micro_gemm( + "micro_gemm", + m, + n, + k, + input_dtype=new_inputs[0].get_dtype(), + input2_dtype=new_inputs[1].get_dtype(), + output_dtype=output_dtype, + compute_dtype=compute_dtype, + alpha=alpha, + num_threads=num_threads, + use_ref=not cls.is_woq_int4(), + q_group_size=cls.q_group_size(), + ) + if micro_gemm is None: + raise AssertionError("expected micro_gemm to be created, got None") + pre_block_weights = cls.check_if_block_weight(new_inputs[1], micro_gemm) + micro_gemm.use_local_vnni_blocking(not pre_block_weights) + cpp_arg_indices: list[int] | None = None + + def dedupe_runtime_inputs(inputs): + nonlocal cpp_arg_indices + if not isinstance(inputs[0], torch.Tensor): + cpp_arg_indices = [] + seen_names: OrderedSet[str] = OrderedSet() + for idx, input_node in enumerate(inputs): + input_name = input_node.get_name() + if input_name not in seen_names: + seen_names.add(input_name) + cpp_arg_indices.append(idx) + return inputs + if cpp_arg_indices is None: + raise AssertionError("expected cpp_arg_indices to be initialized") + return [inputs[idx] for idx in cpp_arg_indices] + + def preprocessor(inputs, layout): + new_inputs, new_layout = normalize_shapes( + *maybe_to_dense(*reorder_and_filter(inputs, layout)) + ) + new_inputs, new_layout = cls.prep_weight( + new_inputs, + new_layout, + # pyrefly: ignore [bad-argument-type] + micro_gemm, + pre_block_weights, + use_int8_fast_compensation_path, + ) + return dedupe_runtime_inputs(new_inputs), new_layout + + def postprocessor(output): + if isinstance(output, ir.TensorBox): + # prepack the weight as input to the template buffer + template_buffer = ir.InputsKernel.unwrap_storage_for_input(output) + if not isinstance(template_buffer, ir.CppTemplateBuffer): + raise AssertionError( + f"expected CppTemplateBuffer, got {type(template_buffer)}" + ) + new_input_nodes, _ = reorder_and_filter(input_nodes, layout) + + W_node = new_input_nodes[1] + if W_node.get_name() not in V.graph.constants: + return output + W = V.graph.constants[W_node.get_name()] + new_input_nodes[1] = W + new_input_nodes, new_layout = normalize_shapes( + *maybe_to_dense(new_input_nodes, layout) + ) + new_input_nodes, _ = cls.prep_weight( + new_input_nodes, + new_layout, + # pyrefly: ignore [bad-argument-type] + micro_gemm, + pre_block_weights, + use_int8_fast_compensation_path, + skip_int8_compensation=True, + ) + W_packed = new_input_nodes[1] + W_packed_constant = V.graph.add_tensor_constant(W_packed) + new_input_nodes[1] = W_packed_constant + + # Prune unused tensors + prune_tensors(input_nodes, new_input_nodes) + + template_buffer.inputs[1] = ir.InputsKernel.unwrap_storage_for_input( + W_packed_constant + ) + return output + + template = DataProcessorTemplateWrapper( + cls, + preprocessor, + postprocessor, + input_nodes=input_nodes, + layout=layout, + num_threads=num_threads, + register_blocking=micro_gemm.register_blocking, + beta=beta, + alpha=alpha, + has_bias=has_bias, + epilogue_creator=epilogue_creator, + should_block_weights=pre_block_weights, + name=micro_gemm.__class__.__name__, + ) + template.maybe_append_choice(choices) + return template + + @staticmethod + def get_padded_size(n, block_n, k, should_block_weight): + padded_n = get_padded_n(n, block_n) + # We assume that all GEMM weight tensors should be blocked and padded + new_size = [padded_n // block_n, k, block_n] + return new_size, padded_n + + @staticmethod + def _maybe_remove_storage_offset(node: ir.IRNode): + if node.get_layout().offset == 0: + return node + # node may be contiguous but still have a non-zero storage offset. + # GEMM_TEMPLATE emits code like: + # W.data_ptr[node.offset + ...] + # but runtime W.data_ptr (after normalize_shapes()) already includes this offset. + # To avoid double-offsetting, we remove the offset in the node also in the generated code. + # W.data_ptr[...] + return ir.ExternKernel.copy_input(node) + + @classmethod + def prep_weight( + cls, + inputs, + layout: ir.Layout, + micro_gemm: CppMicroGemm, + should_block_weight: bool, + use_int8_fast_compensation_path: bool = False, + skip_int8_compensation: bool = False, + ): + """ + NOTE Weight prep consists of 2 separate steps: + 1. Blocking the weight tensor into a 3D shape: [n//block_n, k, block_n] + This is always done if the weight tensor is constant, i.e. for all GEMM and some BMM. + For BMM, we also block non-contiguous weight tensors, since they would be reshaped anyway. + This assumes that blocked, contiguous weights will be more efficient for the GEMM kernel, + and is worth the overhead of reshape and blocking. + + This blocking includes additional padding, when n is not a multiple of block_n. + This padding allows a more efficient microkernel implementation. For BMM, this is only done + if reshape would happen anyway, i.e. if the weight tensor is constant, is not contiguous, + or is using AMX VNNI layout. + 2. Packing the weight tensor into a VNNI-friendly shape. For constant input, + this is done at the same time as the weight blocking. + + At compile time, the constant weight tensors are blocked and packed. For non-constant tensors (e.g. BMM) + which will be blocked (non-contiguous or VNNI-layout tensors), the weight tensor is blocked and packed at runtime. + + CppBmmTemplate overrides the methods get_padded_size, and block_weight in order to accommodate + an additional dimension for the batch size and to determine if the weight tensor should be blocked. + """ + W = inputs[1] + new_inputs = list(inputs) + if cls.is_woq_int4(): + if not ( + len(W.get_size()) == 2 + if isinstance(W, ir.IRNode) + else len(W.shape) == 2 + ): + raise AssertionError("expected WOQ int4 weight to be 2D") + n, k = W.get_size() if isinstance(W, ir.IRNode) else W.shape + else: + k, n = W.get_size()[-2:] if isinstance(W, ir.IRNode) else W.shape[-2:] + _, block_n, _ = micro_gemm.register_blocking + new_size, padded_n = cls.get_padded_size(n, block_n, k, should_block_weight) + padding = padded_n - n + + if should_block_weight and not cls.is_woq_int4(): + blocked_w = cls.block_weight(W, new_size, padding) + new_inputs[1] = cls.pack_vnni_weight(blocked_w, micro_gemm, new_size) + elif should_block_weight: + if not cls.is_woq_int4(): + raise AssertionError("expected WOQ int4 in this branch") + new_inputs[1] = cls.block_weight(W, new_size, padding) + elif isinstance(W, ir.IRNode): + # Require W layout to be fixed & contiguous, happens inplace. + ir.ExternKernel.require_contiguous(W) + new_inputs[1] = cls._maybe_remove_storage_offset(W) + + if not skip_int8_compensation and _is_int8_gemm(new_inputs): + BCompensate = None + x_w_scale = None + + def _get_compensation_node(W, use_int8_fast_compensation_path): + BCompensate = V.graph.add_tensor_constant( + V.graph.constants[W.get_name() + "_BMatrixCompens"], + W.get_name() + "_BMatrixCompens", + ) + x_w_scale = None + if use_int8_fast_compensation_path: + x_w_scale = V.graph.add_tensor_constant( + V.graph.constants[W.get_name() + "_x_w_compens"], + W.get_name() + "_x_w_compens", + ) + return BCompensate, x_w_scale + + if use_int8_fast_compensation_path: + # new_inputs has been reordered: [x, w, optional[bias], x_scale, x_zp, w_scale, w_zp] + x_scale = new_inputs[-4] + x_zp = new_inputs[-3] + w_scale = new_inputs[-2] + if isinstance(W, ir.IRNode): + BCompensate, x_w_scale = _get_compensation_node( + W, use_int8_fast_compensation_path + ) + else: + # Use the original W, not the blocked_w in new_inputs[1] to calculate BCompensate + BCompensate = torch.sum(W.to_dense().to(torch.float), dim=0) # type: ignore[assignment] + if not all( + isinstance(item, torch.Tensor) + for item in (x_scale, x_zp, w_scale) + ): + raise AssertionError( + "expected x_scale, x_zp, w_scale to be tensors" + ) + BCompensate = BCompensate * x_scale * w_scale * x_zp + x_w_scale = x_scale * w_scale + new_inputs.append(BCompensate) + new_inputs.append(x_w_scale) + else: + if isinstance(W, ir.IRNode): + BCompensate, _ = _get_compensation_node( + W, use_int8_fast_compensation_path + ) + else: + # Use the original W, not the blocked_w in new_inputs[1] to calculate BCompensate + BCompensate = torch.sum(W.to_dense().to(torch.float), dim=0) # type: ignore[assignment] + new_inputs.append(BCompensate) + return new_inputs, layout + + @staticmethod + def check_if_block_weight(W, micro_gemm): + return True + + @classmethod + def block_weight(cls, W, new_size, padding): + # These are separated into two methods to allow subclasses to override them separately + if isinstance(W, ir.IRNode): + if W.get_name() in V.graph.constants: + # Create a new buffer, representing the constant blocked tensor + blocked_w = ir.Buffer( + name=W.get_name(), # Borrow the registered buffer name + layout=ir.FixedLayout( + W.get_device_or_error(), + W.get_dtype(), + new_size, + ir.FlexibleLayout.contiguous_strides(new_size), + 0, + ), + ) + else: + if not isinstance(W, ir.TensorBox): + W = ir.TensorBox(W) + permute_dims = list(range(len(new_size))) + permute_dims[-2], permute_dims[-3] = permute_dims[-3], permute_dims[-2] + permute_size = list(new_size) + permute_size[-2], permute_size[-3] = permute_size[-3], permute_size[-2] + blocked_w = L.constant_pad_nd(W, (0, padding)) + blocked_w = L.permute( + L.view(blocked_w, permute_size), + permute_dims, + ) + else: + if not isinstance(W, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(W)}") + # Pad the weight tensor and reshape it into a 3D blocked shape + blocked_size = list(new_size) + blocked_size[-2], blocked_size[-3] = blocked_size[-3], blocked_size[-2] + blocked_w = ( + torch.nn.functional.pad(W, (0, padding)) # type: ignore[assignment] + .reshape(*blocked_size) + .transpose(-3, -2) + .contiguous() + ) + return blocked_w + + @classmethod + def pack_vnni_weight(cls, W, micro_gemm, new_size): + # WOQ INT4 weights are reordered in microkernel so do not pack them here + should_pack = ( + micro_gemm.get_b_layout() != LayoutType.NORMAL + and not micro_gemm.is_woq_int4() + ) + + # These are separated into two methods to allow subclasses to override them separately + if isinstance(W, ir.IRNode): + if isinstance(W, ir.Buffer) and W.get_name() in V.graph.constants: + return W + k = new_size[-2] + if not isinstance(W, ir.TensorBox): + W = ir.TensorBox(W) + if should_pack: + permute_dims = list(range(len(new_size) + 1)) + permute_dims[-1], permute_dims[-2] = permute_dims[-2], permute_dims[-1] + vnni_size = 4 if micro_gemm.get_b_layout() == LayoutType.VNNI4 else 2 + vnni_view_size = list(new_size) + vnni_view_size[-2] = k // vnni_size + vnni_view_size.insert(-1, vnni_size) + W = L.view( + L.permute(L.view(W, vnni_view_size), permute_dims), + new_size, + ) + W = ir.ExternKernel.realize_input(W) + W = ir.ExternKernel.require_contiguous(W) + return W + else: + k = new_size[-2] + # Apply VNNI packing to the weight tensor + if should_pack: + # TODO: Move VNNI weight packing for non-constant tensors into the template, + # to improve cache locality and avoid full-tensor copy. + layout_str = ( + "VNNI4" + if micro_gemm.get_b_layout() == LayoutType.VNNI4 + else "VNNI2" + ) + if micro_gemm.get_b_layout() not in [ + LayoutType.VNNI2, + LayoutType.VNNI4, + ]: + raise AssertionError(f"We only support {layout_str} for now") + vnni_size = 4 if micro_gemm.get_b_layout() == LayoutType.VNNI4 else 2 + if k % vnni_size != 0: + raise AssertionError( + f"k should be divisible by vnni_size for {layout_str} layout" + ) + vnni_view_size = list(new_size) + vnni_view_size[-2] = k // vnni_size + vnni_view_size.insert(-1, vnni_size) + W = W.view(vnni_view_size).transpose(-1, -2).reshape(new_size) + # normalize stride to be "contiguous_strides" per size + # this avoids the problems in L.view during template codegen + new_stride = [1] + for sz in reversed(W.shape[1:]): + new_stride.insert(0, new_stride[0] * sz) + W = W.as_strided(W.shape, new_stride) + return W + + def get_default_reindexers(self, epilogues): + return [None] * len(epilogues) + + def get_options( + self, + kernel: CppTemplateKernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + flag_template_buffer_has_other_users: bool | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + ) -> dict[str, Any]: + if len(self.input_nodes) < 2: + raise AssertionError( + f"expected >= 2 input nodes, got {len(self.input_nodes)}" + ) + + int8_gemm = self.input_nodes[0].get_dtype() in [torch.uint8, torch.int8] + x_scale = None + x_zp = None + w_scale = None + w_zp = None + inp = None + q_group_size_node = None + qscale_and_zeros = None + if int8_gemm: + X, W = self.input_nodes[0], self.input_nodes[1] + bias_idx = 2 if self.has_bias else 1 + inp = self.input_nodes[bias_idx] if self.has_bias else None + x_scale = self.input_nodes[bias_idx + 1] + x_zp = self.input_nodes[bias_idx + 2] + w_scale = self.input_nodes[bias_idx + 3] + w_zp = self.input_nodes[bias_idx + 4] + Y = self.output_node + elif self.is_woq_int4(): + X, W = self.input_nodes[0], self.input_nodes[1] + Y = self.output_node + q_group_size_node = self.input_nodes[2] + qscale_and_zeros = self.input_nodes[3] + else: + X, W = self.input_nodes[0], self.input_nodes[1] + Y = self.output_node + inp = self.input_nodes[2] if self.has_bias else None + + template_buffer_has_other_users = None + + if template_buffer_node is not None: + # Use the updated prepacked weight buffer + W = template_buffer_node.inputs[1] + Y = template_buffer_node + + if flag_template_buffer_has_other_users is None: + raise AssertionError( + "expected flag_template_buffer_has_other_users to be set" + ) + template_buffer_has_other_users = flag_template_buffer_has_other_users + + template_buffer = Y + gemm_output_buffer = template_buffer + + epilogues: list[ir.IRNode] = [] + reindexers: list[Callable[[list[Any]], list[Any]] | None] = [] + epilogue_creators: list[Callable[[ir.Buffer], ir.Pointwise]] = [] + fake_buffers: list[ir.Buffer] = [] + Y_aliases: OrderedSet[str] = OrderedSet() + + use_local_acc = ( + self.layout.dtype != torch.float + or template_buffer_has_other_users + or int8_gemm + or self.padded_n != self.n + or self.maybe_k_slicing() + or (epilogue_nodes and epilogue_nodes[-1].get_dtype() != self.layout.dtype) + ) + + # TODO(jgong5): for int8 gemm, bias-add is handled outside of gemm template, + # but we'd better move it here to align with fp. + if inp is not None and self.beta != 0 and not int8_gemm: + # add an epilogue for bias add + def _bias_add_epilogue(buf): + return create_epilogue_with_attr( + buf, "bias_add", other=inp, beta=self.beta, dtype=self.layout.dtype + ) + + epilogue_creators.append(_bias_add_epilogue) + + if self.epilogue_creator is not None: + epilogue_creators.append(self.epilogue_creator) + + # When the GEMM output buffer is localized but it has users other than the epilogue nodes, + # we need to copy the value in the GEMM output local buffer to a global buffer. + def need_copy_from_local_to_global_buffer_epilogue( + use_local_acc, template_buffer_has_other_users, epilogue_creators + ): + # The GEMM output buffer is a global buffer, thus copy is not needed. + if not use_local_acc: + return False + + # The possible value of template_buffer_has_other_users is (None, False, True) + # It is None when generating the gemm template during autotune and it will have value during scheduler codegen. + # extra copy_from_local_to_global_buffer_epilogue is not needed in either of the below two cases: + # 1. template_buffer_has_other_users is None (i.e. when doing the codegen during autotune) + # 2. template_buffer_has_other_users is False, which means it's safe to keep the value in the + # GEMM output buffer in local buffer only (no users outside of the epilogues will use its value). + if not template_buffer_has_other_users: + return False + + # When bias is not None or self.epilogue_creator is not None, + # there will be epilogue_creators after the GEMM. + # The GEMM output buffer is localized while + # the output buffer of the epilogue_creators is a global buffer. + if epilogue_creators: + return False + + return True + + if need_copy_from_local_to_global_buffer_epilogue( + use_local_acc, template_buffer_has_other_users, epilogue_creators + ): + + def copy_from_local_to_global_buffer_epilogue(input_buffer: ir.Buffer): + dtype = self.layout.dtype + input_loader = input_buffer.make_loader() + + def copy_inner(index): + input = input_loader(index) + result = ops.to_dtype(input, dtype) + return result + + return ir.Pointwise( + device=input_buffer.get_device_or_error(), + dtype=self.layout.dtype, + inner_fn=copy_inner, + ranges=input_buffer.get_size(), + ) + + epilogue_creators.append(copy_from_local_to_global_buffer_epilogue) + + # NOTE [How CPP GEMM template epilogues are organized] + # gemm_output_buffer + # --> zero or more in-template epilogues (created by `epilogue_creators`) --> + # template_buffer + # --> zero or more out-of-template epilogues (`epilogue_nodes`) --> + # Y + if epilogue_creators: + if not isinstance(template_buffer, ir.IRNode): + raise AssertionError(f"expected ir.IRNode, got {type(template_buffer)}") + gemm_output_name = f"{template_buffer.get_name()}_GemmOut" + gemm_output_buffer = ir.Buffer( + name=gemm_output_name, + # pyrefly: ignore [missing-attribute] + layout=template_buffer.layout, + ) + current_input_buffer = gemm_output_buffer + # In-template epilogues are built over the GEMM output buffer's ranges, + # whose rank can exceed that of the 2D tiles the template stores into + # (the BMM template keeps a leading batch dim). Let the template supply + # the reindexers mapping the 2D tile indices onto those ranges. + creator_reindexers = self.get_default_reindexers(epilogue_creators) + for i, creator in enumerate(epilogue_creators): + if i == len(epilogue_creators) - 1: + buffer_name = template_buffer.get_name() + else: + buffer_name = f"{gemm_output_name}_epilogue_{i}" + epilogues.append( + ir.ComputedBuffer( + name=buffer_name, + # pyrefly: ignore [missing-attribute] + layout=template_buffer.layout, + data=creator(current_input_buffer), + ) + ) + fake_buffers.append(current_input_buffer) + Y_aliases.add(current_input_buffer.get_name()) + reindexers.append(creator_reindexers[i]) + if i < len(epilogue_creators) - 1: + current_input_buffer = ir.Buffer( + name=buffer_name, + # pyrefly: ignore [missing-attribute] + layout=template_buffer.layout, + ) + + if not isinstance(Y, (ir.Buffer, ir.ReinterpretView)): + raise AssertionError( + f"expected ir.Buffer or ir.ReinterpretView, got {type(Y)}" + ) + Y_2d: ir.Buffer | ir.ReinterpretView = Y + + if epilogue_nodes: + if not template_buffer_has_other_users: + if not isinstance(template_buffer, ir.IRNode): + raise AssertionError( + f"expected ir.IRNode, got {type(template_buffer)}" + ) + Y_aliases.add(template_buffer.get_name()) + epilogues.extend(epilogue_nodes) + if Y.get_numel() != epilogues[-1].get_numel(): + raise AssertionError( + f"expected Y numel == epilogue numel, got {Y.get_numel()} " + f"and {epilogues[-1].get_numel()}" + ) + Y = cast(ir.Buffer, epilogues[-1]) + if not isinstance(template_buffer, ir.Buffer): + raise AssertionError(f"expected ir.Buffer, got {type(template_buffer)}") + Y_2d, reindexers = gen_2d_view_of_epilogue_buf( + Y, + template_buffer, + epilogue_nodes, + reindexers, + default_reindexers=self.get_default_reindexers(epilogue_nodes), + ) + + output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype( + X.get_dtype() + ) + micro_gemm = create_micro_gemm( + f"{kernel.kernel_name}_micro_gemm", + self.m, + self.n, + self.k, + input_dtype=X.get_dtype(), + input2_dtype=W.get_dtype(), + output_dtype=output_dtype, + compute_dtype=compute_dtype, + alpha=self.alpha, + num_threads=self.num_threads, + use_ref=not self.is_woq_int4(), + q_group_size=self.q_group_size(), + ) + if micro_gemm is None: + raise AssertionError("expected micro_gemm to be created, got None") + micro_gemm.use_local_vnni_blocking(not self.should_block_weights) + if self.register_blocking != micro_gemm.register_blocking: + raise AssertionError( + f"expected register_blocking == {micro_gemm.register_blocking}, " + f"got {self.register_blocking}" + ) + self.log_blockings() + if isinstance(micro_gemm, CppMicroGemmAMX): + counters["inductor"]["cpp_micro_gemm_amx_counter"] += 1 + if isinstance(micro_gemm, CppMicroBrgemm): + counters["inductor"]["cpp_micro_brgemm_counter"] += 1 + + L1_cache_size = torch.cpu.get_capabilities().get( + "l1d_cache_size", 0 + ) # per core cache size in Bytes + if L1_cache_size <= 0: + raise AssertionError(f"Expect L1_cache_size > 0 but got {L1_cache_size}") + + L2_cache_size = torch.cpu.get_capabilities().get( + "l2_cache_size", 0 + ) # per core cache size in Bytes + if L2_cache_size <= 0: + raise AssertionError(f"Expect L2_cache_size > 0 but got {L2_cache_size}") + + options = dict( + X=X, + W=W, + inp=inp, + Y=Y, + N=self.n, + K=self.k, + PADDED_N=self.padded_n, + GemmOut=gemm_output_buffer, + aliases={alias: Y.get_name() for alias in Y_aliases}, + beta=self.beta, + alpha=self.alpha, + num_threads=self.num_threads, + micro_gemm=micro_gemm, + is_dynamic_M=self.is_dynamic_M, + template=self, + kernel=kernel, + export_declaration=get_export_declaration(), + epilogue_nodes=epilogues, + reindexers=reindexers, + Y_2d=Y_2d, + use_local_acc=use_local_acc, + maybe_k_slicing=self.maybe_k_slicing(), + x_scale=x_scale, + x_zp=x_zp, + w_scale=w_scale, + w_zp=w_zp, + acc_buf_dtype=torch.int32 if int8_gemm else torch.float, + DTYPE_TO_CPP=DTYPE_TO_CPP, + L1_cache_size=L1_cache_size, + L2_cache_size=L2_cache_size, + config=config, + fake_buffers=fake_buffers, + is_woq_int4=self.is_woq_int4(), + q_group_size=q_group_size_node, + qscale_and_zeros=qscale_and_zeros, + cpu_count=os.cpu_count(), + ) + return options + + def is_int8_woq_gemm_small_m_dim( + self, + X: ir.ReinterpretView, + W: ir.ReinterpretView, + N, + K, + micro_gemm, + ): + """Use SMALL_M_GEMM_TEMPLATE""" + return ( + isinstance(micro_gemm, CppMicroGemmFP32Vec) + and is_int8_woq_gemm_small_m_dim_corner_case( + micro_gemm, X.get_size()[0], N, K + ) + and X.get_dtype() is torch.bfloat16 + and W.get_dtype() is torch.int8 + ) + + def get_kernel_prefix_name(self) -> str: + return f"gemm_m{self.m}n{self.n}k{self.k}" + + def render( # type: ignore[override, return] + self, + kernel: CppTemplateKernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + flag_template_buffer_has_other_users: bool | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + **kwargs, + ) -> str: + options = self.get_options( + kernel=kernel, + template_buffer_node=template_buffer_node, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_nodes, + ) + self.render_options = options + + with contextlib.ExitStack() as stack: + for buf in options["fake_buffers"]: + stack.enter_context( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf)) + ) + if not options["is_dynamic_M"] and self.is_int8_woq_gemm_small_m_dim( + options["X"], + options["W"], + options["N"], + options["K"], + options["micro_gemm"], + ): + template_str = SMALL_M_GEMM_TEMPLATE + else: + template_str = GEMM_TEMPLATE + return self._template_from_string(template_str).render(**options) + + def codegen_blocks( + self, + num_threads, + N, + K, + micro_gemm, + is_dynamic_M, + kernel, + GemmOut, + config, + L1_cache_size, + L2_cache_size, + X, + W, + ): + options = dict( + num_threads=num_threads, + N=N, + K=K, + micro_gemm=micro_gemm, + is_dynamic_M=is_dynamic_M, + kernel=kernel, + GemmOut=GemmOut, + config=config, + L1_cache_size=L1_cache_size, + L2_cache_size=L2_cache_size, + template=self, + X=X, + W=W, + is_woq_int4=self.is_woq_int4(), + ) + template_str = GEMM_TEMPLATE_INIT_BLOCKING_BASIC_BLOCK + if not ( + not is_dynamic_M + and self.is_int8_woq_gemm_small_m_dim(X, W, N, K, micro_gemm) + ): + template_str += GEMM_TEMPLATE_INIT_BLOCKING_EXTENDED + return self._template_from_string(template_str).render(options) + + def codegen_microkernel_def(self): + return self._template_from_string(GEMM_TEMPLATE_MICROKERNEL_DEF).render( + self.render_options + ) + + def codegen_gemm_stub_def(self): + microkernel = self.codegen_microkernel_def() + return microkernel + self._template_from_string(GEMM_TEMPLATE_STUB_DEF).render( + self.render_options + ) + + def codegen_multi_threads_params(self): + return self._template_from_string(GEMM_TEMPLATE_MULTI_THREADS_PARAMS).render() + + def codegen_single_thread_params(self, is_dynamic_M): + options = dict( + is_dynamic_M=is_dynamic_M, + ) + return self._template_from_string(GEMM_TEMPLATE_SINGLE_THREAD_PARAMS).render( + options + ) + + def codegen_m_loop_params(self): + return self._template_from_string(GEMM_TEMPLATE_M_LOOP_PARAMS).render() + + def codegen_n_loop_params(self): + return self._template_from_string(GEMM_TEMPLATE_N_LOOP_PARAMS).render() + + @classmethod + def is_woq_int4(cls): + return False + + @classmethod + def q_group_size(cls): + return None + + +class CppWoqInt4GemmTemplateMeta(type): + def __getitem__(cls, q_group_size): + class CppWoqInt4GemmTemplateInstance(CppGemmTemplate): + def __init__( + self, + *args, + **kwargs, + ) -> None: + super().__init__( + *args, + **kwargs, + ) + + @classmethod + def is_woq_int4(cls): + return True + + @classmethod + def q_group_size(cls): + return q_group_size + + @staticmethod + def check_if_block_weight(W, micro_gemm): + # For WOQ INT4, weight is already packed + # However, for AMX microkernel, we want to change the blocking of weight + from .cpp_micro_gemm import CppMicroGemmWoQInt4Amx + + return isinstance(micro_gemm, CppMicroGemmWoQInt4Amx) + + @classmethod + def block_weight(cls, W, new_size, padding): + # This method is called only if AMX microkernels are used. + # In this case, we unpack and repack weight so that block_n=32 + # the format of packed weight is described here: + # https://github.com/pytorch/pytorch/blob/32eee8ed225d9f10fbbcb38c24b8b44c24c0c97c/aten/src/ATen/native/cpu/int4mm_kernel.cpp#L583 + if isinstance(W, ir.IRNode): + # in this case, we do nothing + ir.ExternKernel.require_contiguous(W) + blocked_w = W + else: + # in this case, we unpack and repack weight + if not isinstance(W, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(W)}") + if W.dim() != 2: + raise AssertionError(f"expected 2D weight, got {W.dim()}D") + N = W.size(0) + K = W.size(-1) * 2 + G = cls.q_group_size() + # x and qscales_and_zeros are in bfloat16 instead of float to use the optimized kernel + # so that the unpacking process is faster + x = torch.eye(K).bfloat16() + # Here we use scale=1 and qzero=8 because we want to unpack weight + # without dequantizing it. The qzero here is 8 instead of 0 because + # int4 values are converted to [-7, 8] in the _weight_int4pack_mm_for_cpu kernel: + # https://github.com/pytorch/pytorch/blob/32eee8ed225d9f10fbbcb38c24b8b44c24c0c97c/aten/src/ATen/native/cpu/int4mm_kernel.cpp#L95 + qscales_and_zeros = ( + torch.tensor([1.0, 8.0]) + .bfloat16() + .expand(K // G, N, 2) + .contiguous() + ) + # shape: [K, N] + unpacked_w = torch.ops.aten._weight_int4pack_mm_for_cpu( + x, + W, + G, + qscales_and_zeros, + ).to(torch.uint8) + block_n = 32 + # shape: [N // block_n, K, block_n] + w_blocked = ( + unpacked_w.view(K, N // block_n, block_n) + .permute(1, 0, 2) + .contiguous() + ) + # pack 2 int4 -> 1 int8 + # block_n: [a0, a1, ..., a15, b0, b1, ..., b15] + # -> [(a0 & 0xf) | (b0 << 4), (a1 & 0xf) | (b1 << 4), ...] + # shape: [N // block_n, K, 2, block_n // 2] + w_blocked = w_blocked.view(N // block_n, K, 2, block_n // 2) + # shape: [N // block_n, K, block_n // 2] + w_blocked_packed = (w_blocked[:, :, 0, :] & 0xF) | ( + w_blocked[:, :, 1, :] << 4 + ) + # shape: [N, K // 2] + blocked_w = w_blocked_packed.view(N, K // 2) + + return blocked_w + + return CppWoqInt4GemmTemplateInstance + + +class CppWoqInt4GemmTemplate(metaclass=CppWoqInt4GemmTemplateMeta): + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_grouped_gemm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_grouped_gemm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..5ce9381fa2df71cfe5e2e165acc7790403aae7ce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_grouped_gemm_template.py @@ -0,0 +1,554 @@ +import contextlib +import logging +import os +from collections.abc import Callable +from typing import Any, cast, TypeVar +from unittest.mock import patch + +import torch +import torch.utils +from torch.utils._ordered_set import OrderedSet + +from ..._dynamo.utils import counters +from .. import config, ir +from ..kernel.mm_common import mm_args +from ..select_algorithm import ChoiceCaller, DataProcessorTemplateWrapper +from ..utils import parallel_num_threads +from ..virtualized import V +from .cpp import get_export_declaration +from .cpp_gemm_template import ( + CppGemmTemplate, + expand_bias, + gen_2d_view_of_epilogue_buf, + prune_tensors, + transpose_w, +) +from .cpp_micro_gemm import CppMicroGemmAMX, create_micro_gemm +from .cpp_template_kernel import CppTemplateKernel +from .cpp_utils import ( + create_epilogue_with_attr, + GemmBlocking, + get_gemm_template_output_and_compute_dtype, +) + + +log = logging.getLogger(__name__) + +GEMM_TEMPLATE = r""" +{{template.header().getvalue()}} +{{micro_gemm.codegen_define(kernel)}} + +extern "C" {{export_declaration}} +{{kernel.def_kernel(inputs=kernel_args, outputs=Y_list, aliases=aliases)}} +{ + {{kernel.maybe_codegen_profile(template.get_kernel_prefix_name())}} + {{ template.codegen_blocks( + num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOuts[0], config, L1_cache_size, L2_cache_size, X_list[0], W_list[0] + ) }} +{%- if num_threads > 1 %} + {%- set use_dynamic_threads = ((config.cpp.threads < 1) and (num_threads == cpu_count)) or config.cpp.dynamic_threads %} + {%- if use_dynamic_threads %} + #pragma omp parallel + {%- else %} + #pragma omp parallel num_threads({{num_threads}}) + {%- endif %} + { + {{ micro_gemm.codegen_init(kernel) }} + #pragma omp for schedule(static, 1) + for (int64_t tid = 0; tid < {{num_threads}}; tid++) { + {{ template.codegen_multi_threads_params()|indent(12, false) }} +{%- else %} + { + {{ template.codegen_single_thread_params(is_dynamic_M)|indent(8, false) }} + {{ micro_gemm.codegen_init(kernel) }} +{%- endif %} +{%- set acc_buf_name_list=[] %} +{%- set acc_buf_name_prefix = "local_acc_buf_" %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set acc_buf_name = acc_buf_name_prefix + gemm_idx|string %} + {{ kernel.define_buffer(acc_buf_name, ["Mc_blocks*Mr", "Nc_blocks*Nr"], acc_buf_dtype) }} + {%- set acc_buf_name_list=acc_buf_name_list.append(acc_buf_name) %} +{%- endfor %} + for (int64_t mc_block_id = 0; mc_block_id < num_Mc_blocks_per_thread; mc_block_id++) { + {{ template.codegen_m_loop_params()|indent(12, false) }} + for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) { + {{ template.codegen_n_loop_params()|indent(16, false) }} +{%- set acc_list=[] %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set acc_list = acc_list.append( kernel.local_buffers[acc_buf_name_list[gemm_idx]] ) %} + {{ kernel.reinit_buffer_if_null(acc_buf_name_list[gemm_idx]) }} +{%- endfor %} + for (int64_t kc = k_block_start; kc < k_block_end; kc += Kc_blocks) { + int64_t k_start = kc * Kr; + int64_t k_end = std::min(std::min(kc + Kc_blocks, k_block_end) * Kr, K); +{%- set tile_X_list=[] %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set tile_X_list = tile_X_list.append( kernel.slice_nd(X_list[gemm_idx], [("m_start", "m_end"), ("k_start", "k_end")]) ) %} +{%- endfor %} + for (int64_t nci = nc; nci < nc_block_end; nci++) { +{%- set tile_W_3d_list=[] %} +{%- set tile_W_list=[] %} +{%- set acc_slice_list=[] %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set acc_slice_list = acc_slice_list.append( + kernel.slice_nd(acc_list[gemm_idx], [("0", "m_end - m_start"), ("(nci - nc)*Nr", "(nci - nc + 1)*Nr")]) + ) %} + {%- set tile_W_3d_list = tile_W_3d_list.append( + kernel.slice_nd(W_list[gemm_idx], [("nci", "nci + 1"), ("k_start", "k_end"), ()]) + ) %} +{%- endfor %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set tile_W_list = tile_W_list.append( + kernel.view(tile_W_3d_list[gemm_idx], ["k_end - k_start", micro_gemm.register_blocking.block_n]) + ) %} +{%- endfor %} + if (kc == k_block_start) { + {%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {{ micro_gemm.codegen_call( + kernel, tile_X_list[gemm_idx], tile_W_list[gemm_idx], acc_slice_list[gemm_idx], accum=False + )|indent(28, false) }} + {%- endfor %} + } else { + {%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {{ micro_gemm.codegen_call( + kernel, tile_X_list[gemm_idx], tile_W_list[gemm_idx], acc_slice_list[gemm_idx], accum=True + )|indent(28, false) }} + {%- endfor %} + } + } + } + { +{%- set tile_acc_list = [] %} +{%- set tile_Y_list = [] %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set tile_acc_list = tile_acc_list.append( + kernel.slice_nd(acc_list[gemm_idx], [("0", "m_end - m_start"), ("0", "n_end - n_start")]) + ) %} + {%- set tile_Y_list = tile_Y_list.append( + kernel.slice_nd(Y_2d_list[gemm_idx], [("m_start", "m_end"), ("n_start", "n_end")]) + ) %} +{%- endfor %} + {{ kernel.store_outputs( + tile_Y_list, + tile_acc_list, + GemmOuts, + epilogue_nodes, + offsets=("m_start", "n_start"), + reindexers=reindexers, + multi_output_buffers=multi_output_buffers + )|indent(20, false) + }} + } + } + } +{%- if num_threads > 1 %} + } + {{ micro_gemm.codegen_finalize(kernel) }} + } +{%- else %} + {{ micro_gemm.codegen_finalize(kernel) }} + } +{%- endif %} +} +""" + + +def get_deduplicated_act(act_mapping: dict[int, ir.IRNode]) -> list[ir.IRNode]: + act_deduplicated = [] + act_deduplicated_name: OrderedSet[str] = OrderedSet() + for act_idx in range(len(act_mapping.values())): + act = act_mapping[act_idx] + if act.get_name() not in act_deduplicated_name: + act_deduplicated.append(act) + act_deduplicated_name.add(act.get_name()) + return act_deduplicated + + +class CppGroupedGemmTemplate(CppGemmTemplate): + def __init__( + self, + input_nodes: list[ir.IRNode], + layout: ir.Layout, + num_threads: int, + register_blocking: GemmBlocking, + beta: int = 1, + alpha: int = 1, + has_bias: bool = False, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + act_mapping: dict[int, ir.IRNode] | None = None, + gemm_grouped_num: int = 1, + ) -> None: + """ + Template for Group of GEMMs: + * Each GEMM has the same dimensions (m, n, k) and the same leading dimensions (lda, ldb, ldc) + for their A, B, and C matrices. + * Each GEMM has distinct or shared activations, has distinct weight, has unique bias or no bias, has distinct epilogues. + * In the current implementation, the outputs of all GEMMs are accumulated using pointwise epilogues. + This behavior can be extended in the future if needed. + """ + super().__init__( + input_nodes, + layout, + num_threads, + register_blocking, + beta, + alpha, + has_bias, + epilogue_creator, + ) + self.act_mapping = act_mapping + self.gemm_grouped_num = gemm_grouped_num + # pyrefly: ignore [bad-override] + self.output_node: list[ir.Buffer] = [ + ir.Buffer(name="buf_out" + str(idx), layout=layout) + for idx in range(gemm_grouped_num) + ] + + @classmethod + # pyrefly: ignore [bad-override] + def add_choices( + cls, + choices: list[ChoiceCaller], + layout: ir.Layout, + input_nodes: list[ir.IRNode], + beta: int = 1, + alpha: int = 1, + has_bias: tuple[bool, ...] = (False, False), + trans_w: bool = False, + input_indices: list[int] | None = None, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + act_mapping: dict[int, ir.IRNode] | None = None, # gemm idx to its act buf + ) -> DataProcessorTemplateWrapper: + # Input nodes order: x, optional[x1], ... w0, w1, ... optional[b0], optional[b1], ... + gemm_grouped_num = len(has_bias) + if not act_mapping: + raise AssertionError("expected non-empty act_mapping") + act_deduplicated = get_deduplicated_act(act_mapping) + wgt_start_idx = len(act_deduplicated) + bias_start_idx = wgt_start_idx + gemm_grouped_num + input_indices = list(range(len(input_nodes))) + + _T = TypeVar("_T", ir.IRNode, torch.Tensor) + _U = TypeVar("_U", ir.Layout, torch.Tensor) + + def reorder_and_filter( + inputs: list[_T], + layout_or_out: _U, + ) -> tuple[list[_T], _U]: + if input_indices is None: + raise AssertionError("input_indices must be set") + return [inputs[idx] for idx in input_indices], layout_or_out + + new_inputs, new_layout = reorder_and_filter(input_nodes, layout) + + def maybe_to_dense( + inputs: list[_T], + layout_or_out: _U, + ) -> tuple[list[_T], _U]: + new_inputs = list(inputs) + for idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num): + if isinstance(inputs[idx], torch.Tensor): + W = inputs[idx] + if not isinstance(W, torch.Tensor): + raise AssertionError("W must be a torch.Tensor") + # pyrefly: ignore [unsupported-operation] + new_inputs[idx] = W.to_dense() if W.is_mkldnn else W + return new_inputs, layout_or_out + + def normalize_shapes( + inputs: list[_T], + layout_or_out: _U, + ) -> tuple[list[_T], _U]: + new_inputs: list[_T] = list(inputs) + if not trans_w: + return new_inputs, layout_or_out + X = new_inputs[0] + for wgt_idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num): + new_input = new_inputs[wgt_idx] + new_inputs[wgt_idx] = transpose_w(new_input, trans_w) + for bias_idx in range(bias_start_idx, len(new_inputs)): + # pyrefly: ignore [bad-argument-type] + new_bias = expand_bias(new_inputs[bias_idx], X) + if new_bias is None: + raise AssertionError("expected new_bias to be not None") + # pyrefly: ignore [unsupported-operation] + new_inputs[bias_idx] = new_bias + return new_inputs, layout_or_out + + num_threads = parallel_num_threads() + new_inputs, _ = normalize_shapes(*maybe_to_dense(new_inputs, new_layout)) + m, n, k, *_ = mm_args(new_inputs[0], new_inputs[wgt_start_idx]) + output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype( + new_inputs[0].get_dtype() + ) + micro_gemm = create_micro_gemm( + "micro_gemm", + m, + n, + k, + input_dtype=new_inputs[0].get_dtype(), + input2_dtype=new_inputs[wgt_start_idx].get_dtype(), + output_dtype=output_dtype, + compute_dtype=compute_dtype, + alpha=alpha, + num_threads=num_threads, + ) + if micro_gemm is None: + raise AssertionError("expected micro_gemm to be not None") + _, block_n, _ = micro_gemm.register_blocking + new_size, padded_n = cls.get_padded_size( + n, block_n, k, should_block_weight=True + ) + padding = padded_n - n + + def pack_weight( + inputs: list[_T], + layout_or_out: _U, + ) -> tuple[list[_T], _U]: + new_W_list = [] + new_inputs = list(inputs) + W_list = new_inputs[wgt_start_idx : wgt_start_idx + gemm_grouped_num] + for W in W_list: + blocked_w = cls.block_weight(W, new_size, padding) + new_W_list.append(cls.pack_vnni_weight(blocked_w, micro_gemm, new_size)) + new_inputs[wgt_start_idx : wgt_start_idx + gemm_grouped_num] = new_W_list + return new_inputs, layout_or_out + + def preprocessor( + inputs: list[_T], + layout: _U, + ) -> tuple[list[_T], _U]: + return pack_weight( + *normalize_shapes(*maybe_to_dense(*reorder_and_filter(inputs, layout))) + ) + + def postprocessor(output: _T) -> _T: + if isinstance(output, ir.TensorBox): + template_buffer = ir.InputsKernel.unwrap_storage_for_input(output) + if not isinstance(template_buffer, ir.CppTemplateBuffer): + raise AssertionError( + "expected template_buffer to be ir.CppTemplateBuffer" + ) + new_input_nodes, _ = reorder_and_filter(input_nodes, layout) + W_nodes = new_input_nodes[ + wgt_start_idx : wgt_start_idx + gemm_grouped_num + ] + W_tensor = [] + for W_node in W_nodes: + if W_node.get_name() not in V.graph.constants: + raise AssertionError( + f"expected {W_node.get_name()} in V.graph.constants" + ) + # pyrefly: ignore [bad-argument-type] + W_tensor.append(V.graph.constants[W_node.get_name()]) + # pyrefly: ignore [unsupported-operation] + new_input_nodes[wgt_start_idx : wgt_start_idx + gemm_grouped_num] = ( + W_tensor # type: ignore[assignment] + ) + new_input_nodes, _ = pack_weight( + *normalize_shapes(*maybe_to_dense(new_input_nodes, layout)) + ) + # Prune unused tensors + prune_tensors(input_nodes, new_input_nodes) + for idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num): + W_packed = new_input_nodes[idx] + if not isinstance(W_packed, torch.Tensor): + raise AssertionError("expected W_packed to be a torch.Tensor") + W_packed_constant = V.graph.add_tensor_constant(W_packed) + template_buffer.inputs[idx] = ( + ir.InputsKernel.unwrap_storage_for_input(W_packed_constant) + ) + + return output + + template = DataProcessorTemplateWrapper( + CppGroupedGemmTemplate, + preprocessor, + postprocessor, + input_nodes=input_nodes, + layout=layout, + num_threads=num_threads, + register_blocking=micro_gemm.register_blocking, + beta=beta, + alpha=alpha, + has_bias=has_bias, + epilogue_creator=epilogue_creator, + act_mapping=act_mapping, + gemm_grouped_num=gemm_grouped_num, + ) + template.maybe_append_choice(choices) + return template + + def get_kernel_prefix_name(self) -> str: + return f"grouped_gemm_g{self.gemm_grouped_num}m{self.m}n{self.n}k{self.k}" + + def render( # type: ignore[override,return,no-untyped-def] + self, + kernel: CppTemplateKernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + flag_template_buffer_has_other_users: bool | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + **kwargs, + ) -> str: + if not self.act_mapping: + raise AssertionError("expected non-empty self.act_mapping") + act_deduplicated = get_deduplicated_act(self.act_mapping) + wgt_start_idx = len(act_deduplicated) + bias_start_idx = wgt_start_idx + self.gemm_grouped_num + X_list = list(self.act_mapping.values()) + W_list = self.input_nodes[wgt_start_idx : wgt_start_idx + self.gemm_grouped_num] + inp_list = [] + cur_idx = bias_start_idx + for inp_idx in range(self.gemm_grouped_num): + inp = None + # pyrefly: ignore [bad-index, index-error] + if self.has_bias[inp_idx]: + inp = self.input_nodes[cur_idx] + cur_idx += 1 + inp_list.append(inp) + + Y_list = self.output_node + multi_output_buffers = None + if template_buffer_node is not None: + W_list = template_buffer_node.inputs[ + wgt_start_idx : wgt_start_idx + self.gemm_grouped_num + ] + if not isinstance(template_buffer_node.outputs, list): + raise AssertionError( + "expected template_buffer_node.outputs to be a list" + ) + Y_list = template_buffer_node.outputs + counters["inductor"]["cpp_grouped_gemm_template"] += 1 + multi_output_buffers = template_buffer_node.outputs + + template_buffer = Y_list[0] + fake_buffers: list[ir.Buffer] = [] + Y_2d_list = Y_list + output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype( + X_list[0].get_dtype() + ) + micro_gemm = create_micro_gemm( + f"{kernel.kernel_name}_micro_gemm", + self.m, + self.n, + self.k, + input_dtype=X_list[0].get_dtype(), + input2_dtype=W_list[0].get_dtype(), + output_dtype=output_dtype, + compute_dtype=compute_dtype, + alpha=self.alpha, + num_threads=self.num_threads, + ) + if micro_gemm is None: + raise AssertionError("expected micro_gemm to be not None") + if self.register_blocking != micro_gemm.register_blocking: + raise AssertionError( + "expected self.register_blocking == micro_gemm.register_blocking" + ) + self.log_blockings() + if isinstance(micro_gemm, CppMicroGemmAMX): + counters["inductor"]["cpp_micro_gemm_amx_counter"] += 1 + + L1_cache_size = torch.cpu.get_capabilities().get( + "l1d_cache_size", 0 + ) # per core cache size in Bytes + if L1_cache_size <= 0: + raise AssertionError(f"Expect L1_cache_size > 0 but got {L1_cache_size}") + + L2_cache_size = torch.cpu.get_capabilities().get( + "l2_cache_size", 0 + ) # per core cache size in Bytes + if L2_cache_size <= 0: + raise AssertionError(f"Expect L2_cache_size > 0 but got {L2_cache_size}") + + epilogues: list[ir.IRNode] = [] + reindexers: list[Callable[[list[Any]], list[Any]] | None] = [] + gemm_output_buffers: list[ir.Buffer] = [] + for out_buf_idx in range(self.gemm_grouped_num): + gemm_output_name = f"{template_buffer.get_name()}_GemmOut" + str( + out_buf_idx + ) + gemm_output_buffers.append( + ir.Buffer(name=gemm_output_name, layout=template_buffer.layout) + ) + + if self.epilogue_creator: + raise AssertionError( + "epilogue_creator is not supported yet in Grouped GEMM Template" + ) + + kernel_args: dict[str, ir.IRNode | None] = {} + for x_idx in range(wgt_start_idx): + kernel_args["X" + str(x_idx)] = act_deduplicated[x_idx] + for w_idx in range(self.gemm_grouped_num): + kernel_args["W" + str(w_idx)] = W_list[w_idx] + for inp_idx in range(self.gemm_grouped_num): + kernel_args["inp" + str(inp_idx)] = inp_list[inp_idx] + + def _bias_add_epilogue(buf: ir.IRNode, inp: ir.IRNode) -> ir.Pointwise: + return create_epilogue_with_attr( + buf, "bias_add", other=inp, beta=self.beta, dtype=self.layout.dtype + ) + + for gemm_idx, inp in enumerate(inp_list): + if inp: + buffer_name = Y_list[gemm_idx].get_name() + epilogues.append( + ir.ComputedBuffer( + name=buffer_name, + layout=template_buffer.layout, + data=_bias_add_epilogue(gemm_output_buffers[gemm_idx], inp), + ) + ) + reindexers.append(None) + + if epilogue_nodes: + epilogues.extend(epilogue_nodes) + for epilogue_node in epilogue_nodes: + Y = cast(ir.Buffer, epilogue_node) + _, reindexers = gen_2d_view_of_epilogue_buf( + Y, + template_buffer, + [ + epilogue_node, + ], + reindexers, + default_reindexers=[ + None, + ], + ) + + options = dict( + N=self.n, + K=self.k, + PADDED_N=self.padded_n, + aliases={}, + beta=self.beta, + alpha=self.alpha, + num_threads=self.num_threads, + micro_gemm=micro_gemm, + is_dynamic_M=self.is_dynamic_M, + template=self, + kernel=kernel, + export_declaration=get_export_declaration(), + acc_buf_dtype=torch.float, + L1_cache_size=L1_cache_size, + L2_cache_size=L2_cache_size, + config=config, + epilogue_nodes=epilogues, + GemmOuts=gemm_output_buffers, + reindexers=reindexers, + kernel_args=kernel_args, + X_list=X_list, + W_list=W_list, + gemm_grouped_num=self.gemm_grouped_num, + Y_list={"Y" + str(idx): Y for idx, Y in enumerate(Y_list)}, + Y_2d_list=Y_2d_list, + multi_output_buffers=multi_output_buffers, + cpu_count=os.cpu_count(), + ) + with contextlib.ExitStack() as stack: + stack.enter_context( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(fake_buffers)) + ) + return self._template_from_string(GEMM_TEMPLATE).render(**options) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_micro_gemm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_micro_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..979230917aba5ea1f9e8a6dd8590ace58a3d7f05 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_micro_gemm.py @@ -0,0 +1,2278 @@ +# mypy: allow-untyped-defs +import dataclasses +import operator +import sys +from collections.abc import Callable +from enum import Enum + +import torch + +from .. import cpp_builder, ir +from ..cpu_vec_isa import ( + pick_vec_isa, + VecAMX, + VecAVX2, + VecAVX512, + VecAVX512VNNI, + VecISA, + VecNEON, + VecSVE, +) +from ..utils import IndentedBuffer, parallel_num_threads +from ..virtualized import V +from .common import KernelTemplate +from .cpp_template_kernel import CppTemplateKernel +from .cpp_utils import DTYPE_TO_CPP, GemmBlocking, value_to_cpp + + +class LayoutType(Enum): + NORMAL = 0 + VNNI2 = 1 + VNNI4 = 2 + + +_IS_WINDOWS = sys.platform == "win32" + + +def get_restrict_keyword() -> str: + if _IS_WINDOWS: + # https://learn.microsoft.com/en-us/cpp/cpp/extension-restrict?view=msvc-170 + return "__restrict" + else: + return "__restrict__" + + +class CppMicroGemm: + """ + A class that codegens a kernel that computes small-sized matrix multiplication. + + A micro GEMM kernel is responsible for register blocking, instruction selection, + and other CPU architecture-specific optimizations. + + The subclasses need to override `codegen_define` to define the kernel function + that is called by the code generated by `codegen_call`. + """ + + # TODO(jgong5): support constant shapes and lds as template args. + DECLARE_KERNEL = r""" +template +inline void {{kernel_name}}( +{%- if kernel_extra_args_declare %} + {{kernel_extra_args_declare}} +{%- endif %} + const {{input_t}}* {{restrict_keyword}} A, + const {{input2_t}}* {{restrict_keyword}} B, + {{output_t}}* {{restrict_keyword}} C, + int64_t M, + int64_t N, + int64_t K, + int64_t lda, + int64_t ldb, + int64_t ldc +) +""" + + def __init__( + self, + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + register_blocking, + alpha=1, + ) -> None: + self.name = name + self.input_dtype = input_dtype + if input2_dtype is None: + raise AssertionError("expected input2_dtype to be set, got None") + self.input2_dtype = input2_dtype + self.output_dtype = output_dtype + self.compute_dtype = compute_dtype + self.register_blocking = register_blocking + self.alpha = alpha + self.pack_vnni_B_locally = False + + def get_common_options(self): + if self.input_dtype in [torch.uint8, torch.int8]: + if self.compute_dtype != torch.int32: + raise AssertionError( + f"expected compute_dtype == torch.int32, got {self.compute_dtype}" + ) + if self.output_dtype != torch.int32: + raise AssertionError( + f"expected output_dtype == torch.int32, got {self.output_dtype}" + ) + if self.input2_dtype != torch.int8: + raise AssertionError( + f"expected input2_dtype == torch.int8, got {self.input2_dtype}" + ) + return { + "torch": torch, + "kernel_name": self.name, + "input_dtype": self.input_dtype, + "input2_dtype": self.input2_dtype, + "output_dtype": self.output_dtype, + "compute_dtype": self.compute_dtype, + "input_t": DTYPE_TO_CPP[self.input_dtype], + "input2_t": DTYPE_TO_CPP[self.input2_dtype], + "output_t": DTYPE_TO_CPP[self.output_dtype], + "compute_t": DTYPE_TO_CPP[self.compute_dtype], + "alpha": self.alpha, + "kernel_extra_args_declare": self.get_kernel_extra_args_declare(), + "int8_gemm": self.input_dtype in [torch.uint8, torch.int8], + "vnni_size": 4 if self.input_dtype in [torch.uint8, torch.int8] else 2, + "restrict_keyword": get_restrict_keyword(), + "pack_vnni_B_locally": self.pack_vnni_B_locally, + "template": self, + "is_woq_int4": self.is_woq_int4(), + } + + def get_kernel_declaration(self): + options = self.get_common_options() + return KernelTemplate._template_from_string(self.DECLARE_KERNEL).render(options) + + def get_kernel_extra_args_declare(self) -> str: + return "" + + def get_kernel_extra_args(self, **kwargs) -> list[str]: + return [] + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + raise NotImplementedError + + def codegen_call( + self, + kernel: CppTemplateKernel, + A: ir.Buffer, + B: ir.Buffer, + C: ir.Buffer, + accum: bool, + prefetch: bool = False, + **kwargs_for_extra_args, + ) -> str: + """ + Generate the code for calling the templated kernel that computes + `C += alpha * A @ B` if `accum` is True, or `C = alpha * A @ B` otherwise. + """ + A_ptr = f"&({kernel.index(A, [0, 0])})" + B_ptr = f"&({kernel.index(B, [0, 0])})" + C_ptr = f"&({kernel.index(C, [0, 0])})" + M = kernel.size(C, 0) + N = kernel.size(C, 1) + K = kernel.size(A, 1) + lda = kernel.stride(A, 0) + ldb = kernel.stride(B, 0) + ldc = kernel.stride(C, 0) + res = IndentedBuffer() + res.writeline( + f"{self.name}<{value_to_cpp(accum, 'bool')}, {value_to_cpp(prefetch, 'bool')}>(" + ) + with res.indent(): + kwargs_for_extra_args.update({"kernel": kernel}) + extra_args = self.get_kernel_extra_args(**kwargs_for_extra_args) + for arg in extra_args: + res.writeline(arg) + res.writeline(f"{A_ptr},") + res.writeline(f"{B_ptr},") + res.writeline(f"{C_ptr},") + res.writeline(f"{M},") + res.writeline(f"{N},") + res.writeline(f"{K},") + res.writeline(f"{lda},") + res.writeline(f"{ldb},") + res.writeline(f"{ldc}") + res.writeline(");") + return res.getvalue() + + def use_local_vnni_blocking(self, should_block_weight: bool): + self.pack_vnni_B_locally = should_block_weight + + def codegen_init( + self, + kernel: CppTemplateKernel, + ) -> str: + return "" + + def codegen_finalize( + self, + kernel: CppTemplateKernel, + ) -> str: + return "" + + def get_b_layout(self) -> LayoutType: + return LayoutType.NORMAL + + ALLOCATE_WEIGHT_BUFFER = r""" + {%- if is_msvc_compiler %} + // MSVC doesn't support stack-allocated dynamic-sized arrays, so using heap memory here. + auto heap_deq_b_buf_ptr = std::make_unique<{{buffer_dtype}}[]>({{buffer_size}}); + {{buffer_dtype}}* {{buffer_name}} = heap_deq_b_buf_ptr.get(); + {%- else %} + // It's safe to use a stack-allocated array since the blocking strategy would + // require us to allocate an array that's smaller than the size of L1D cache, + // and the default per thread max stack size on Linux is quite higher, + // so we need not worry about stack overflow. + alignas(4096) {{buffer_dtype}} {{buffer_name}}[{{buffer_size}}]; + {%- endif %} +""" + + def codegen_allocate_weight_buffer( + self, buffer_name: str, buffer_dtype: str, *size_args + ) -> str: + buffer_size = " * ".join(map(str, size_args)) + return KernelTemplate._template_from_string(self.ALLOCATE_WEIGHT_BUFFER).render( + { + "buffer_name": buffer_name, + "buffer_dtype": buffer_dtype, + "buffer_size": buffer_size, + "is_msvc_compiler": cpp_builder.is_msvc_cl(), + } + ) + + def is_woq_int4(self): + return False + + +@dataclasses.dataclass +class CppMicroGemmConfig: + input_dtype: torch.dtype + input2_dtype: torch.dtype + output_dtype: torch.dtype + compute_dtype: torch.dtype + vec_isa_cls: type[VecISA] + register_blocking: GemmBlocking + extra_check: Callable[..., bool] | None = None + + +micro_gemm_configs: dict[type[CppMicroGemm], list[CppMicroGemmConfig]] = {} + + +def register_micro_gemm(*configs): + def inner(cls): + if cls in micro_gemm_configs: + raise AssertionError(f"Duplicate micro_gemm registration for {cls}") + if len(configs) <= 0: + raise AssertionError(f"No micro_gemm configs provided for {cls}") + micro_gemm_configs[cls] = list(configs) + return cls + + return inner + + +def generate_gemm_config( + vec_isa_cls, + register_blockings, + input_dtype=torch.float, + input2_dtype=None, + output_dtype=None, + compute_dtype=None, + extra_check=None, +): + if output_dtype is None: + output_dtype = input_dtype + if compute_dtype is None: + compute_dtype = output_dtype + if input2_dtype is None: + input2_dtype = input_dtype + return [ + CppMicroGemmConfig( + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + vec_isa_cls, + GemmBlocking(*blocking), + extra_check, + ) + for blocking in register_blockings + ] + + +class CppMicroGemmRef(CppMicroGemm): + """ + A reference implementation of the CppMicroGemm class with naive C++ code. + It is used for correctness debugging. + """ + + TEMPLATE_ENTRY = r""" +{{declare_kernel}} { + for (int64_t m = 0; m < M; ++m) { + for (int64_t n = 0; n < N; ++n) { + {{compute_t}} result = accum ? C[m * ldc + n] : 0; + for (int64_t k = 0; k < K; ++k) { + result += ({{compute_t}})A[m * lda + k] * ({{compute_t}})B[k * ldb + n] * {{alpha}}; + } + C[m * ldc + n] = result; + } + } +} +""" + + def __init__( + self, name, input_dtype, input2_dtype, output_dtype, compute_dtype, alpha + ) -> None: + super().__init__( + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + GemmBlocking(1, 1, 1), + alpha, + ) + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + options = { + "declare_kernel": self.get_kernel_declaration(), + **self.get_common_options(), + } + return KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(options) + + +def is_int8_woq_gemm_small_m_dim_corner_case(config, m, n, k): + return ( + k % config.register_blocking.block_k == 0 + and n % config.register_blocking.block_n == 0 + and m < 16 + ) + + +# extra check for small M dimension for int8 WoQ case +def check_int8_woq_small_m_dim(config, m, n, k, alpha, num_threads, **kwargs): + return is_int8_woq_gemm_small_m_dim_corner_case(config, m, n, k) and not kwargs.get( + "dynamic_M", False + ) + + +# For int8 WoQ GEMM with small M, we use different blockings that shouldn't be used otherwise +def do_not_use_with_small_m_for_int8_woq(config, m, n, k, alpha, num_threads, **kwargs): + return not check_int8_woq_small_m_dim(config, m, n, k, alpha, num_threads, **kwargs) + + +@register_micro_gemm( + *generate_gemm_config( + VecAVX512, + [(8, 48, 1), (8, 32, 1), (16, 16, 1)], + input_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX512, + [(8, 48, 1), (8, 32, 1), (16, 16, 1)], + input_dtype=torch.bfloat16, + output_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX512, + [(8, 48, 1), (8, 32, 1), (16, 16, 1)], + input_dtype=torch.half, + output_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX512, + [(8, 48, 1), (8, 32, 1), (16, 16, 1)], + input_dtype=torch.bfloat16, + input2_dtype=torch.int8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=do_not_use_with_small_m_for_int8_woq, + ), + *generate_gemm_config( + VecAVX512, + [ + (4, 32, 64), + (8, 32, 64), + ], + input_dtype=torch.bfloat16, + input2_dtype=torch.int8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=check_int8_woq_small_m_dim, + ), + *generate_gemm_config( + VecAVX2, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX2, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.bfloat16, + output_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX2, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.half, + output_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX2, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.bfloat16, + input2_dtype=torch.int8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=do_not_use_with_small_m_for_int8_woq, + ), + *generate_gemm_config( + VecAVX2, + [ + (2, 16, 64), + (4, 16, 64), + ], + input_dtype=torch.bfloat16, + input2_dtype=torch.int8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=check_int8_woq_small_m_dim, + ), + *generate_gemm_config( + VecNEON, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.float, + input2_dtype=torch.float, + output_dtype=torch.float, + compute_dtype=torch.float, + ), + *generate_gemm_config( + VecSVE, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.float, + input2_dtype=torch.float, + output_dtype=torch.float, + compute_dtype=torch.float, + ), +) +class CppMicroGemmFP32Vec(CppMicroGemm): + """ + This class generates the code for micro gemm using fp32 vec instructions for compute. + It supports input types of torch.float, torch.bfloat16, and torch.half with fp32 output. + The output of the microkernel is in FP32, but it would be converted to BF16/FP16 in the template, + if the desired output is BF16/FP16. + """ + + TEMPLATE_ENTRY = r""" +{{declare_kernel}} { + using Vectorized = at::vec::Vectorized<{{compute_t}}>; + constexpr auto VLEN = Vectorized::size(); + {{kernel.assert_function}}({{block_n}} % VLEN == 0, "block_n dimension must be multiple of Vector size"); + {{kernel.assert_function}}(K % {{block_k}} == 0, "K dimension must be multiple of {{block_k}}"); + // TODO(jgong5): loop unroll for M and N + for (int64_t m = 0; m < M; m += {{block_m}}) { + int64_t block_m = std::min(M - m, {{block_m}}); + for (int64_t n = 0; n < N; n += {{block_n}}) { + int64_t block_n = std::min(N - n, {{block_n}}); + if (block_m == {{block_m}} && block_n == {{block_n}}) { +{%- if not trans_b %} + {{kernel_name}}_kernel<{{block_m}}, {{block_n}}, accum, prefetch>( +{%- else %} + {{kernel_name}}_transpose_b_kernel<{{block_m}}, {{block_n}}, accum, prefetch>( +{%- endif %} + A + m * lda, +{%- if not trans_b %} + B + n, +{%- else %} + B + n * ldb, +{%- endif %} + C + m * ldc + n, + K, + lda, + ldb, + ldc + ); +{%- if tail_n %} + } else if (block_n == {{block_n}}){ +{%- else %} + } else { +{%- endif %} + switch (block_m) { +{%- for b in range(block_m - 1, 0, -1) %} + case {{b}}: + {%- if not trans_b %} + {{kernel_name}}_kernel<{{b}}, {{block_n}}, accum, prefetch>( + {%- else %} + {{kernel_name}}_transpose_b_kernel<{{b}}, {{block_n}}, accum, prefetch>( + {%- endif %} + A + m * lda, + {%- if not trans_b %} + B + n, + {%- else %} + B + n * ldb, + {%- endif %} + C + m * ldc + n, + K, + lda, + ldb, + ldc + ); + break; +{%- endfor %} + default: + {{kernel.assert_function}}(false, "Unsupported block_m: {{block_m}}"); + } + +{%- if tail_n %} + } else { + switch (block_m) { + {%- for b in range(block_m, 0, -1) %} + case {{b}}: + {%- if not trans_b %} + {{kernel_name}}_ntail_kernel<{{b}}, {{block_n}}, accum, prefetch>( + {%- else %} + {{kernel_name}}_ntail_transpose_b_kernel<{{b}}, {{block_n}}, accum, prefetch>( + {%- endif %} + A + m * lda, + {%- if not trans_b %} + B + n, + {%- else %} + B + n * ldb, + {%- endif %} + C + m * ldc + n, + block_n, + K, + lda, + ldb, + ldc + ); + break; + {%- endfor %} + default: + {{kernel.assert_function}}(false, "Unsupported block_m: {{block_m}}"); + } + } +{%- else %} + } +{%- endif %} + } + } +} +""" + + TEMPLATE_KERNEL = r""" + +template +{%- if not trans_b %} + {%- if tail_n %} +inline void {{kernel_name}}_ntail_kernel( + {%- else %} +inline void {{kernel_name}}_kernel( + {%- endif %} +{%- else %} + {%- if tail_n %} +inline void {{kernel_name}}_ntail_transpose_b_kernel( + {%- else %} +inline void {{kernel_name}}_transpose_b_kernel( + {%- endif %} +{%- endif %} + const {{input_t}}* {{restrict_keyword}} A, + const {{input2_t}}* {{restrict_keyword}} B, + {{output_t}}* {{restrict_keyword}} C, +{%- if tail_n %} + int64_t N, +{%- endif %} + int64_t K, + int64_t lda, + int64_t ldb, + int64_t ldc +) { + using Vectorized = at::vec::Vectorized<{{compute_t}}>; +{%- if input2_dtype in [torch.bfloat16, torch.float16] %} + using VectorizedIn = at::vec::Vectorized<{{input_t}}>; +{%- endif %} + +{%- if not trans_b %} + constexpr auto VLEN = Vectorized::size(); + constexpr auto ROWS = BLOCK_M; + constexpr auto COLS = BLOCK_N / VLEN; + + Vectorized va; + at::vec::VectorizedN<{{compute_t}}, COLS> vb; + at::vec::VectorizedN<{{compute_t}}, ROWS*COLS> vc; + + {%- if tail_n %} + int64_t rCOLS = (N + VLEN - 1) / VLEN; + int ntail = N % VLEN; + {%- endif %} + auto loadc = [&](auto i) { + if constexpr (accum) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + {%- if tail_n %} + int load_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN; + if (col < rCOLS) { + vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN, load_size); + } + {%- else %} + vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN); + {%- endif %} + } else { + vc[i] = Vectorized(0.0f); + } + }; + c10::ForcedUnroll{}(loadc); + + auto compute = [&, COLS](auto i, int k) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + {%- if tail_n %} + int load_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN; + {%- endif %} + if constexpr (col == 0) { + {%- if alpha != 1 %} + va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + k]) * {{alpha}}); + {%- else %} + va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + k])); + {%- endif %} + } + + if constexpr (row == 0) { + {%- if tail_n %} + if (col < rCOLS) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + auto b = VectorizedIn::loadu(B + k * ldb + col * VLEN, load_size); + vb[col] = at::vec::convert<{{compute_t}}>(b); + {%- elif input2_dtype == torch.int8 %} + // Convert VLEN int8 elements to int32, and then fp32 + auto b32 = at::vec::convert_to_int32(B + k * ldb + col * VLEN, load_size); + vb[col] = at::vec::convert(b32); + {%- else %} + vb[col] = Vectorized::loadu(B + k * ldb + col * VLEN, load_size); + {%- endif %} + } else { + vb[col] = Vectorized(0.0f); + } + + {%- else %} + + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + auto b = VectorizedIn::loadu(B + k * ldb + col * VLEN, VLEN); + vb[col] = at::vec::convert<{{compute_t}}>(b); + {%- elif input2_dtype == torch.int8 %} + // Convert VLEN int8 elements to int32, and then fp32 + auto b32 = at::vec::convert_to_int32(B + k * ldb + col * VLEN); + if constexpr (prefetch) { + _mm_prefetch(B + (k + {{block_k}}) * ldb + col * VLEN, _MM_HINT_T0); + } + vb[col] = at::vec::convert(b32); + {%- else %} + vb[col] = Vectorized::loadu(B + k * ldb + col * VLEN); + {%- endif %} + {%- endif %} + + } + + constexpr int idx = row * COLS + col; + {%- if tail_n %} + if (col < rCOLS) { + vc[idx] = at::vec::fmadd(va, vb[col], vc[idx]); + } + {%- else %} + vc[idx] = at::vec::fmadd(va, vb[col], vc[idx]); + {%- endif %} + }; + + for (int k = 0; k < K; ++k) { + c10::ForcedUnroll{}(compute, k); + } + + // store to C + auto storec = [&](auto i) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + {%- if tail_n %} + int store_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN; + if (col < rCOLS) { + vc[i].store(C + row * ldc + col * VLEN, store_size); + } + {%- else %} + vc[i].store(C + row * ldc + col * VLEN); + {%- endif %} + }; + c10::ForcedUnroll{}(storec); + +{%- else %} + // Use 2 implementations for the transposed B: + // First implementation: + // Transpose first and then perform outer product calculation in sub-blocks, + // which introduces an additional transpose overhead of [K, N] compared to the non-transpose version. + // Second implementation: + // Directly perform inner product calculation in sub-blocks, + // which introduces an additional vector reduction of [M, N] compared to the non-transpose version. + // Therefore, when M * N / (K * N) is large, the first implementation has better performance. + {%- if tail_n %} + if (K % Vectorized::size() == 0 && N % Vectorized::size() == 0 && 24 * BLOCK_M > K) { + {%- else %} + if (K % Vectorized::size() == 0 && 24 * BLOCK_M > K) { + {%- endif %} + // First implementation: + constexpr auto VLEN = Vectorized::size(); + constexpr auto ROWS = BLOCK_M; + constexpr auto COLS = BLOCK_N / VLEN; + int _K = K / VLEN; + Vectorized va; + at::vec::VectorizedN<{{compute_t}}, VLEN> vb; + at::vec::VectorizedN<{{compute_t}}, ROWS*COLS> vc; + auto loadc = [&](auto i) { + if constexpr (accum) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN); + } else { + vc[i] = Vectorized(0.0f); + } + }; + c10::ForcedUnroll{}(loadc); + auto unroll_loadB = [&](auto i, const {{input2_t}}* {{restrict_keyword}} src_ptr) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + auto b = VectorizedIn::loadu(src_ptr + i * ldb, VLEN); + vb[i] = at::vec::convert<{{compute_t}}>(b); + {%- elif input2_dtype == torch.int8 %} + auto b32 = at::vec::convert_to_int32(src_ptr + i * ldb, VLEN); + vb[i] = at::vec::convert(b32); + {%- else %} + vb[i] = Vectorized::loadu(src_ptr + i * ldb, VLEN); + {%- endif %} + }; + auto compute_trans = [&, COLS](auto i, int k) { + constexpr int row = i % ROWS; + constexpr int col = i / ROWS; + constexpr int e_col = col * VLEN; + int idk = k * VLEN; + if constexpr (row == 0) { + c10::ForcedUnroll{}(unroll_loadB, B + e_col * ldb + idk); + at::vec::transpose_block(vb); + } + constexpr int idx = row * COLS + col; + {{kernel.unroll_pragma(16)}} + for (int j = 0; j < VLEN; j++) { + {%- if alpha != 1 %} + va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + idk + j]) * {{alpha}}); + {%- else %} + va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + idk + j])); + {%- endif %} + vc[idx] = at::vec::fmadd(va, vb[j], vc[idx]); + } + }; + for (int k = 0; k < _K; ++k) { + c10::ForcedUnroll{}(compute_trans, k); + } + // store to C + auto storec = [&](auto i) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + vc[i].store(C + row * ldc + col * VLEN); + }; + c10::ForcedUnroll{}(storec); + } else { + // Second implementation + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + constexpr auto VLEN = VectorizedIn::size(); + {%- else %} + constexpr auto VLEN = Vectorized::size(); + {%- endif %} + int _K = (K + VLEN - 1) / VLEN; + // sub-block size of BLOCK_N and BLOCK_M + constexpr int sM = {{sub_block_m}}; + constexpr int sN = {{sub_block_n}}; + {%- if tail_n %} + int bN = (N + sN - 1) / sN; + {%- else %} + constexpr int bN = (BLOCK_N + sN - 1) / sN; + {%- endif %} + constexpr int bM = (BLOCK_M + sM - 1) / sM; + + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + at::vec::VectorizedN<{{compute_t}}, 2> va; + at::vec::VectorizedN<{{compute_t}}, 2 * sN> vb; + {%- else %} + at::vec::Vectorized<{{compute_t}}> va; + at::vec::VectorizedN<{{compute_t}}, sN> vb; + {%- endif %} + at::vec::VectorizedN<{{compute_t}}, sN * sM> vmid; + + {%- if tail_n %} + int ntail = N % sN; + {%- else %} + constexpr int ntail = BLOCK_N % sN; + {%- endif %} + constexpr int mtail = BLOCK_M % sM; + int ktail = K % VLEN; + + auto compute_trans = [&](int m, int n, int k) { + {%- if tail_n %} + int e_n = (n == bN - 1 && ntail != 0) ? (N - n * sN) : sN; + {%- else %} + int e_n = (n == bN - 1 && ntail != 0) ? (BLOCK_N - n * sN) : sN; + {%- endif %} + int e_m = (m == bM - 1 && mtail != 0) ? (BLOCK_M - m * sM) : sM; + int e_k = (k == _K - 1 && ktail != 0) ? (K - k * VLEN) : VLEN; + {{kernel.unroll_pragma(sub_block_n)}} + for (int i = 0; i < e_n; i++) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + auto b = VectorizedIn::loadu(B + (sN * n + i) * ldb + k * VLEN, e_k); + std::tie(vb[2 * i], vb[2 * i + 1]) = at::vec::convert_to_float<{{input_t}}>(b); + {%- elif input2_dtype == torch.int8 %} + auto b32 = at::vec::convert_to_int32(B + (sN * n + i) * ldb + k * VLEN, e_k); + vb[i] = at::vec::convert(b32); + {%- else %} + vb[i] = Vectorized::loadu(B + (sN * n + i) * ldb + k * VLEN, e_k); + {%- endif %} + } + + {{kernel.unroll_pragma(sub_block_m)}} + for (int s = 0; s < e_m; s++) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + auto a = VectorizedIn::loadu(A + (sM * m + s) * lda + k * VLEN, e_k); + std::tie(va[0], va[1]) = at::vec::convert_to_float<{{input_t}}>(a); + {%- elif input2_dtype == torch.int8 %} + auto a32 = at::vec::convert_to_int32(A + (sM * m + s) * lda + k * VLEN, e_k); + va = at::vec::convert(a32); + {%- else %} + va = Vectorized::loadu(A + (sM * m + s) * lda + k * VLEN, e_k); + {%- endif %} + + {%- if alpha != 1 %} + va = va * Vectorized({{alpha}}); + {%- endif %} + if (k == 0) { + {{kernel.unroll_pragma(sub_block_n)}} + for (int i = 0; i < e_n; i++) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + vmid[sN * s + i] = at::vec::fmadd(va[0], vb[2 * i], Vectorized(0.0f)); + vmid[sN * s + i] = at::vec::fmadd(va[1], vb[2 * i + 1], vmid[sN * s + i]); + {%- else %} + vmid[sN * s + i] = at::vec::fmadd(va, vb[i], Vectorized(0.0f)); + {%- endif %} + } + } else { + {{kernel.unroll_pragma(sub_block_n)}} + for (int i = 0; i < e_n; i++) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + vmid[sN * s + i] = at::vec::fmadd(va[0], vb[2 * i], vmid[sN * s + i]); + vmid[sN * s + i] = at::vec::fmadd(va[1], vb[2 * i + 1], vmid[sN * s + i]); + {%- else %} + vmid[sN * s + i] = at::vec::fmadd(va, vb[i], vmid[sN * s + i]); + {%- endif %} + } + } + } + + // store to C + if (k == _K - 1) { + {{kernel.unroll_pragma(sub_block_m)}} + for (int s = 0; s < e_m; s++) { + {{kernel.unroll_pragma(sub_block_n)}} + for (int i = 0; i < e_n; i++) { + auto v = at::vec::vec_reduce_all([](Vectorized& x, Vectorized& y) { return x + y; }, vmid[sN * s + i]); + if constexpr (accum) { + auto c = *(C + (sM * m + s) * ldc + sN * n + i); + *(C + (sM * m + s) * ldc + sN * n + i) = c + v; + } else { + *(C + (sM * m + s) * ldc + sN * n + i) = v; + } + } + } + } + }; + + for (int n = 0; n < bN; ++n) { + for (int m = 0; m < bM; ++m) { + for (int k = 0; k < _K; ++k) { + compute_trans(m, n, k); + } + } + } + } +{%- endif %} +} +""" + + # set trans_b to generate gemm that supports transposed B matrix + # set tail_n to support the tail of N + # TODO add trans_b support for other micro gemms + # and move setting of trans_b to the init of CppMicroGemm + def __init__( + self, + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + register_blocking, + alpha=1, + tail_n=False, + trans_b=False, + ) -> None: + super().__init__( + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + register_blocking, + alpha, + ) + self.tail_n = tail_n + # trans_b is only supported on platforms that + # support avx512 or avx2 since transpose_block is + # only implemented on these platforms + if trans_b: + vec_isa = pick_vec_isa() + if not ( + issubclass(vec_isa.__class__, VecAVX512) + or issubclass(vec_isa.__class__, VecAVX2) + ): + raise AssertionError( + f"trans_b requires AVX512 or AVX2 vec ISA, got {vec_isa.__class__}" + ) + self.trans_b = trans_b + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + options = { + "declare_kernel": self.get_kernel_declaration(), + "kernel": kernel, + "block_m": self.register_blocking.block_m, + "block_n": self.register_blocking.block_n, + "block_k": self.register_blocking.block_k, + "trans_b": False, + "tail_n": False, + "restrict_keyword": get_restrict_keyword(), + **self.get_common_options(), + } + if self.trans_b: + # TODO supports tuning of sub_block_m/sub_block_n + # to get better performance for specific shapes + sub_block_m = min(1, self.register_blocking.block_m) + sub_block_n = min(4, self.register_blocking.block_n) + # update options to generate kernel with trans_b and sub-block size + options.update( + { + "trans_b": self.trans_b, + "sub_block_m": sub_block_m, + "sub_block_n": sub_block_n, + } + ) + result = KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render( + options + ) + # update options to generate the kernel for the tail of N + if self.tail_n: + options.update( + { + "tail_n": self.tail_n, + } + ) + result += KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render( + options + ) + result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render( + options + ) + return result + + +def check_vnni_extra(config, m, n, k, alpha, num_threads, **kwargs): + if not (config.input_dtype == torch.uint8 and config.input2_dtype == torch.int8): + raise AssertionError( + "expected input_dtype == torch.uint8 and input2_dtype == torch.int8, " + f"got {config.input_dtype}, {config.input2_dtype}" + ) + vnni_size = 4 + return k % vnni_size == 0 + + +@register_micro_gemm( + *generate_gemm_config( + VecAVX512VNNI, + # (block_m, block_n, block_k) + [(6, 64, 4)], + input_dtype=torch.uint8, + input2_dtype=torch.int8, + output_dtype=torch.int32, + compute_dtype=torch.int32, + extra_check=check_vnni_extra, + ), +) +class CppMicroGemmAVX512VNNI(CppMicroGemm): + """ + This class generates the code for micro gemm using AVX512 VNNI instructions for compute. + It supports u8s8s32 GEMM only. + AVX512_VNNI ISA has been available since the 3rd gen of Intel Xeon. + """ + + TEMPLATE_ENTRY = r""" +{{declare_kernel}} { + {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}"); + {{kernel.assert_function}}(K % {{vnni_size}} == 0, "K dimension must be multiple of {{vnni_size}}"); + constexpr int64_t M_BLOCK = {{block_m}}; + const int64_t M_TAIL = M % M_BLOCK; + const int64_t M_MAIN = M - M_TAIL; + for (int64_t m = 0; m < M_MAIN; m += M_BLOCK) { + for (int64_t n = 0; n < N; n += {{block_n}}) { + {{kernel_name}}_kernel( + A + m * lda, + B + n, + C + m * ldc + n, + K, + lda, + ldb, + ldc + ); + } + } + if (M_TAIL > 0) { + switch (M_TAIL) { +{%- for m_tail in range(block_m - 1, 0, -1) %} + case ({{m_tail}}): + for (int64_t n = 0; n < N; n += {{block_n}}) { + {{kernel_name}}_kernel<{{m_tail}}, {{block_n}}, accum>( + A + M_MAIN * lda, + B + n, + C + M_MAIN * ldc + n, + K, + lda, + ldb, + ldc + ); + } + break; +{%- endfor %} + default: + {{kernel.assert_function}}(false, "Unsupported M_TAIL"); + } // switch M_TAIL + } // if M_TAIL +} +""" + + TEMPLATE_KERNEL = r""" +template +inline void {{kernel_name}}_kernel( + const {{input_t}}* {{restrict_keyword}} A, + const {{input2_t}}* {{restrict_keyword}} B, + {{output_t}}* {{restrict_keyword}} C, + int64_t K, + int64_t lda, + int64_t ldb, + int64_t ldc +) { + constexpr const int COLS = N / {{vec_len}}; + __m512i va; + __m512i vb[COLS]; + __m512i vc[M * COLS]; + + c10::ForcedUnroll{}([&](auto i) { vc[i] = _mm512_setzero_epi32(); }); + + auto compute = [&](auto i, int k) { + constexpr const int row = i / COLS; + constexpr const int col = i % COLS; + + if constexpr (col == 0) { + va = _mm512_set1_epi32(*(int32_t*)(A + row * lda + k)); + } + + if constexpr (row == 0) { + // B block in VNNI layout: [K / {{vnni_size}}, N, {{vnni_size}}] + int64_t offset = k * ldb + col * {{vec_len}} * {{vnni_size}}; + vb[col] = _mm512_loadu_si512((__m512i const*)(B + offset)); + } + vc[i] = _mm512_dpbusd_epi32(vc[i], va, vb[col]); + }; + + // Accumulate along k + constexpr const int k_unroll = 2; + int k = 0; + int k_limit = K / {{vnni_size}} / k_unroll; + for (; k < k_limit; k++) { + c10::ForcedUnroll{}( + [&](auto i) { + c10::ForcedUnroll{}(compute, {{vnni_size}} * (k * k_unroll + i)); + } + ); + } + k *= {{vnni_size}} * k_unroll; + for (; k < K; k += {{vnni_size}}) { + c10::ForcedUnroll{}(compute, k); + } + + // Store to C + auto store_c = [&](auto i) { + constexpr const int row = i / COLS; + constexpr const int col = i % COLS; + if constexpr (accum) { + __m512i vc_old = _mm512_loadu_si512((__m512i const*)(C + row * ldc + col * {{vec_len}})); + vc[i] = _mm512_add_epi32(vc[i], vc_old); + } + _mm512_storeu_si512((__m512i*)(C + row * ldc + col * {{vec_len}}), vc[i]); + }; + c10::ForcedUnroll{}(store_c); +} +""" + + def __init__( + self, + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + register_blocking, + alpha=1, + ) -> None: + super().__init__( + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + register_blocking, + alpha, + ) + if not (input_dtype == torch.uint8 and input2_dtype == torch.int8): + raise AssertionError( + f"Only u8s8s32 GEMM is supported by AVX512VNNI microkernel, got A:{input_dtype}, B:{input2_dtype}, C:{output_dtype}." + ) + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + options = { + "declare_kernel": self.get_kernel_declaration(), + "kernel": kernel, + "block_m": self.register_blocking.block_m, + "block_n": self.register_blocking.block_n, + "block_k": self.register_blocking.block_k, + "restrict_keyword": get_restrict_keyword(), + "vec_len": 16, # = 512 / 32 for C + **self.get_common_options(), + } + return KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render( + options + ) + KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(options) + + def get_b_layout(self): + return LayoutType.VNNI4 + + +# extra check for CppMicroGemmAMX +def check_amx_extra(config, m, n, k, alpha, num_threads, **kwargs): + vnni_size = 4 if config.input_dtype in [torch.uint8, torch.int8] else 2 + return k % vnni_size == 0 and alpha == 1 + + +def check_int8_bf16_amx_extra(config, m, n, k, alpha, num_threads, **kwargs): + # We need avx512_bf16 to dequant int8 to bf16 + vec_isa = kwargs.get("vec_isa") + if vec_isa is None: + raise AssertionError("expected vec_isa to be set, got None") + return vec_isa.is_avx512_bf16_supported() and check_amx_extra( + config, m, n, k, alpha, num_threads, **kwargs + ) + + +# amx_fp16 need to be checked separately since it is not always supported when amx is supported +def check_amx_fp16_extra(config, m, n, k, alpha, num_threads, **kwargs): + if not (config.input_dtype == torch.float16 and config.output_dtype == torch.float): + raise AssertionError( + "expected input_dtype == torch.float16 and output_dtype == torch.float, " + f"got {config.input_dtype}, {config.output_dtype}" + ) + vec_isa = kwargs.get("vec_isa") + if vec_isa is None: + raise AssertionError("expected vec_isa to be set, got None") + vnni_size = 2 + return vec_isa.is_amx_fp16_supported() and k % vnni_size == 0 and alpha == 1 + + +@register_micro_gemm( + *generate_gemm_config( + VecAMX, + [(32, 32, 64), (48, 16, 64)], + input_dtype=torch.int8, + input2_dtype=torch.int8, + output_dtype=torch.int32, + compute_dtype=torch.int32, + extra_check=check_amx_extra, + ), + *generate_gemm_config( + VecAMX, + [(32, 32, 32), (48, 16, 32)], + input_dtype=torch.bfloat16, + input2_dtype=torch.int8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=check_int8_bf16_amx_extra, + ), + *generate_gemm_config( + VecAMX, + [(32, 16, 32), (32, 32, 32), (48, 16, 32), (16, 48, 32)], + input_dtype=torch.bfloat16, + output_dtype=torch.float, + extra_check=check_amx_extra, + ), + *generate_gemm_config( + VecAMX, + [(32, 32, 32), (48, 16, 32), (16, 48, 32)], + input_dtype=torch.float16, + output_dtype=torch.float, + extra_check=check_amx_fp16_extra, + ), + *generate_gemm_config( + VecAMX, + [(32, 32, 64), (48, 16, 64)], + input_dtype=torch.uint8, + input2_dtype=torch.int8, + output_dtype=torch.int32, + compute_dtype=torch.int32, + extra_check=check_amx_extra, + ), +) +class CppMicroGemmAMX(CppMicroGemm): + """ + This class generates the code for micro gemm using Advanced Matrix extension (AMX) + instructions available in 4th generation Intel Xeon for compute. + It supports input types of torch.bfloat16 with fp32 output. + """ + + TEMPLATE_ENTRY = r""" +{{declare_kernel}} { + {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}"); + {{kernel.assert_function}}(K % 2 == 0, "K dimension must be multiple of 2"); +{%- if pack_vnni_B_locally %} + {{template.codegen_allocate_weight_buffer("packed_B_buf", input2_t, "K", block_n)}} +{%- endif %} +{%- if use_cached_dequantized_B %} + // Create a stack-allocated buffer for tiles of B. + // Except maybe for the tail-case, an AMX tile of B has 16x32 BF16 elements. + // we cache K * {{block_n}} elements of dequantized B + {{template.codegen_allocate_weight_buffer("dequantized_B_buf", input_t, "K", block_n)}} + const auto buf_size = K * {{block_n}}; + auto load_dequantized_B = [&](int base_idx) { + // Load a tile of B & cache it in L1D. + {{input2_t}}* base_addr = const_cast<{{input2_t}}*>(B) + base_idx; + for (int idx_dq = 0, idx_q = 0; idx_dq < buf_size; idx_q += ldb, idx_dq += {{block_n}}) { + {%- for vec_idx in range(0, block_n, 32) %} + _mm_prefetch(base_addr + idx_q + 64 * ldb, _MM_HINT_T0); + {%- if (block_n - vec_idx) >= 32 %} + // 1) Load 32 x int8 + __m256i v8 = _mm256_loadu_si256((const __m256i*)(base_addr + idx_q + {{vec_idx}})); + // 2) Extract two halves + __m128i v8_lo = _mm256_extracti128_si256(v8, 0); + __m128i v8_hi = _mm256_extracti128_si256(v8, 1); + // 3) Widen each half to i32 + __m512i v32_lo = _mm512_cvtepi8_epi32(v8_lo); + __m512i v32_hi = _mm512_cvtepi8_epi32(v8_hi); + // 4) Convert to f32 + __m512 f_lo = _mm512_cvtepi32_ps(v32_lo); + __m512 f_hi = _mm512_cvtepi32_ps(v32_hi); + // 5) f32 -> bf16 (round-to-nearest-even) and pack 32 lanes to 512b + // Packs the second operand (f_lo) into the lower 16 bf16 lanes and the first (f_hi) into the upper 16. + __m512i bf = (__m512i)_mm512_cvtne2ps_pbh(f_hi, f_lo); + // 6) Store 32 x bf16 (512 bits) + _mm512_storeu_si512((__m512i*)(dequantized_B_buf + idx_dq + {{vec_idx}}), bf); + {%- elif (block_n - vec_idx) >= 16 %} + // 1) Load 16 x int8 (128 bits) + __m128i v8 = _mm_loadu_si128((const __m128i*)(base_addr + idx_q + {{vec_idx}})); + // 2) Widen: 16 x i8 -> 16 x i32 + __m512i v32 = _mm512_cvtepi8_epi32(v8); + // 3) Convert to f32 + __m512 f32 = _mm512_cvtepi32_ps(v32); + // 4) Convert f32 -> bf16 (round-to-nearest-even) + __m256i bf16 = (__m256i)_mm512_cvtneps_pbh(f32); + // 5) Store 16 x bf16 (256 bits) + _mm256_storeu_si256((__m256i*)(dequantized_B_buf + idx_dq + {{vec_idx}}), bf16); + {%- else %} + auto b_int8_tail = at::vec::Vectorized::loadu( + base_addr + idx_q + {{block_n - (block_n % 32)}}, + static_cast({{block_n % 32}}) + ); + auto b_bf16_tail = at::vec::convert<{{input_t}}>(b_int8_tail); + b_bf16_tail.store( + dequantized_B_buf + idx_dq + {{block_n - (block_n % 32)}}, + static_cast({{block_n % 32}}) + ); + {%- endif %} + {%- endfor %} + } + }; +{%- endif %} +// The ldb would not be block_n if N != block_n +{%- if use_cached_dequantized_B or pack_vnni_B_locally %} + const int64_t updated_ldb = {{block_n}}; +{%- else %} + const int64_t updated_ldb = ldb; +{%- endif %} + // TODO(jgong5): loop unroll for M and N + for (int64_t n = 0; n < N; n += {{block_n}}) { +{%- if pack_vnni_B_locally %} + // Pack non-constant weights into VNNI interleaved format in packed_B_buf + at::vec::pack_vnni2(B + n, packed_B_buf, ldb, K, {{block_n}}); +{%- elif use_cached_dequantized_B %} + // Dequantize K * block_n int8 B elements into BF16 + load_dequantized_B(n); +{%- endif %} + for (int64_t m = 0; m < M; m += {{block_m}}) { + int64_t block_m = std::min(M - m, {{block_m}}); + int64_t m_tail = m; +{%- for num_rows in range(block_m, 0, -16) %} + {%- if num_rows != block_m %} + else + {%- endif %} + if (block_m >= {{num_rows}}) { + {{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}( + amx_state, + A + m * lda, +{%- if use_cached_dequantized_B %} + dequantized_B_buf, +{%- elif pack_vnni_B_locally %} + packed_B_buf, +{%- else %} + B + n, +{%- endif %} + C + m * ldc + n, + K, + lda, + updated_ldb, + ldc, + 16 + ); + block_m -= {{num_rows}}; + m_tail += {{num_rows}}; + } +{%- endfor %} + if (block_m > 0) { + {{kernel_name}}_amx_kernel_16_{{num_columns}}( + amx_state, + A + m_tail * lda, +{%- if use_cached_dequantized_B %} + dequantized_B_buf, +{%- elif pack_vnni_B_locally %} + packed_B_buf, +{%- else %} + B + n, +{%- endif %} + C + m_tail * ldc + n, + K, + lda, + updated_ldb, + ldc, + block_m + ); + } + } + } +} +""" + + TEMPLATE_KERNEL = r""" + +template +inline void {{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}( + AMXState& amx_state, + const {{input_t}}* {{restrict_keyword}} A, +{%- if use_cached_dequantized_B %} + const {{input_t}}* {{restrict_keyword}} B, +{%- else %} + const {{input2_t}}* {{restrict_keyword}} B, +{%- endif %} + {{output_t}}* {{restrict_keyword}} C, + int64_t K, + int64_t lda, + int64_t ldb, + int64_t ldc, + uint8_t tilecfg_rows +) { + // TODO(jgong5): add prefetch hint for A, B, C + auto loadconfig = [](const amx_tilecfg& cfg) { + _tile_loadconfig(&cfg); + }; + const auto last_k_offset = K / {{block_k}} * {{block_k}}; + const auto tail_k_size = K - last_k_offset; + if C10_LIKELY (last_k_offset > 0) { + amx_state.configure(tilecfg_rows, 64, {{num_rows}} / 16, {{num_columns}}, loadconfig); + } else { + amx_state.configure(tilecfg_rows, tail_k_size * sizeof({{input_t}}), {{num_rows}} / 16, {{num_columns}}, loadconfig); + } + auto load_c = [&]() { +{%- for tile_row in range(num_rows // 16) %} + {%- for tile_col in range(num_columns) %} + {%- set tile_idx = tile_row * num_columns + tile_col %} + _tile_loadd({{tile_idx}}, C + {{tile_row * 16}} * ldc + {{tile_col * 16}}, ldc * sizeof({{output_t}})); + {%- endfor %} +{%- endfor %} + }; + auto zero_c = [&]() { +{%- for tile_row in range(num_rows // 16) %} + {%- for tile_col in range(num_columns) %} + {%- set tile_idx = tile_row * num_columns + tile_col %} + _tile_zero({{tile_idx}}); + {%- endfor %} +{%- endfor %} + }; + + if constexpr (accum) { + load_c(); + } else { + zero_c(); + } + + auto compute = [&](int k) { +{%- set tile_offset_a = num_rows // 16 * num_columns %} +{%- set tile_offset_b = tile_offset_a + num_rows // 16 %} +{%- for tile_row in range(num_rows // 16) %} + {%- for tile_col in range(num_columns) %} + {%- set tile_idx_a = tile_offset_a + tile_row %} + {%- set tile_idx_b = tile_offset_b + tile_col %} + {%- set tile_idx_c = tile_row * num_columns + tile_col %} + {%- if tile_col == 0 %} + _tile_stream_loadd({{tile_idx_a}}, A + {{tile_row * 16}} * lda + k, lda * sizeof({{input_t}})); + {%- endif %} + {%- if tile_row == 0 %} + _tile_loadd({{tile_idx_b}}, B + k * ldb + {{tile_col * 16 * vnni_size}}, ldb * {{vnni_size}} * sizeof({{input_t}})); + {%- endif %} + {%- if int8_gemm %} + {%- if input_dtype == torch.int8 %} + _tile_dpbssd({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}}); + {%- else %} + _tile_dpbusd({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}}); + {%- endif %} + {%- else %} + {%- if input_dtype == torch.float16 %} + _tile_dpfp16ps({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}}); + {%- else %} + _tile_dpbf16ps({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}}); + {%- endif %} + {%- endif %} + {%- endfor %} +{%- endfor %} + }; + + {{kernel.unroll_pragma(4)}} + for (int k = 0; k < last_k_offset; k += {{block_k}}) { + compute(k); + } + + auto store_c = [&]() { + // store to C +{%- for tile_row in range(num_rows // 16) %} + {%- for tile_col in range(num_columns) %} + {%- set tile_idx = tile_row * num_columns + tile_col %} + _tile_stored({{tile_idx}}, C + {{tile_row * 16}} * ldc + {{tile_col * 16}}, ldc * sizeof({{output_t}})); + {%- endfor %} +{%- endfor %} + }; + + // TODO(jgong5): move tail k computation to separate loopnest to save tile configuration overhead + if C10_UNLIKELY (tail_k_size > 0) { + if C10_LIKELY (last_k_offset > 0) { + store_c(); + amx_state.configure(tilecfg_rows, tail_k_size * sizeof({{input_t}}), {{num_rows}} / 16, {{num_columns}}, loadconfig); + load_c(); + } + compute(last_k_offset); + } + + store_c(); +} +""" + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + block_m, block_n, block_k = self.register_blocking + if block_m % 16 != 0: + raise AssertionError("Only support block_m % 16 == 0 for AMX") + if block_n % 16 != 0: + raise AssertionError("Only support block_n % 16 == 0 for AMX") + if self.input_dtype in [torch.uint8, torch.int8]: + if block_k != 64: + raise AssertionError("Only support block_k = 64 for AMX INT8") + else: + if block_k != 32: + raise AssertionError( + "Only support block_k = 32 for AMX Bfloat16/Float16" + ) + num_columns = block_n // 16 + options = { + "declare_kernel": self.get_kernel_declaration(), + "use_cached_dequantized_B": ( + self.input_dtype == torch.bfloat16 + and self.input2_dtype in [torch.int8, torch.uint8] + ), + "kernel": kernel, + "block_m": block_m, + "block_n": block_n, + "block_k": block_k, + "num_columns": num_columns, + "restrict_keyword": get_restrict_keyword(), + **self.get_common_options(), + } + result = "" + for num_rows in range(block_m, 0, -16): + amx_kernel_options = {**options, "num_rows": num_rows} + result += KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render( + amx_kernel_options + ) + result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render( + options + ) + return result + + def codegen_init( + self, + kernel: CppTemplateKernel, + ) -> str: + return "AMXState amx_state;" + + def codegen_finalize( + self, + kernel: CppTemplateKernel, + ) -> str: + return "amx_state.release([]() { _tile_release(); });" + + def get_kernel_extra_args_declare(self) -> str: + return "AMXState& amx_state," + + def get_kernel_extra_args(self, **kwargs) -> list[str]: + return ["amx_state,"] + + def get_b_layout(self): + if self.input_dtype in [torch.uint8, torch.int8]: + return LayoutType.VNNI4 + else: + return LayoutType.VNNI2 + + +# extra check for CppMicroBrgemm +def check_brgemm_extra(config, m, n, k, alpha, num_threads, **kwargs): + if not (config.input_dtype == torch.half and config.output_dtype == torch.float): + raise AssertionError( + "expected input_dtype == torch.half and output_dtype == torch.float, " + f"got {config.input_dtype}, {config.output_dtype}" + ) + vnni_size = 2 + # use brgemm for Half when amx_fp16 is supported + return torch.cpu._is_amx_fp16_supported() and k % vnni_size == 0 and alpha == 1 + + +@register_micro_gemm( + *generate_gemm_config( + VecAMX, + [(32, 32, 32), (48, 16, 32), (16, 48, 32)], + input_dtype=torch.half, + output_dtype=torch.float, + extra_check=check_brgemm_extra, + ), +) +class CppMicroBrgemm(CppMicroGemm): + """ + This class generates the code for micro gemm using oneDNN brgemm. + It supports input types of torch.half. + """ + + TEMPLATE_ENTRY = r""" +#include +{{declare_kernel}} { +{%- if pack_vnni_B_locally %} + {{template.codegen_allocate_weight_buffer("packed_B_buf", input2_t, "K * N")}} + at::vec::pack_vnni2(B, packed_B_buf, ldb, K, N); +{%- endif %} + at::native::cpublas::brgemm( + M, N, K, + {%- if pack_vnni_B_locally %} + lda, N, ldc, + {%- else %} + lda, ldb, ldc, + {%- endif %} + accum, + A, + {%- if pack_vnni_B_locally %} + packed_B_buf, + {%- else %} + B, + {%- endif %} + C); +} +""" + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + options = { + "declare_kernel": self.get_kernel_declaration(), + "kernel": kernel, + "block_m": self.register_blocking.block_m, + "block_n": self.register_blocking.block_n, + "block_k": self.register_blocking.block_k, + "restrict_keyword": get_restrict_keyword(), + **self.get_common_options(), + } + result = "" + result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render( + options + ) + return result + + def codegen_finalize( + self, + kernel: CppTemplateKernel, + ) -> str: + return "at::native::cpublas::brgemm_release();" + + def get_b_layout(self): + if not (self.input_dtype == torch.half and torch.cpu._is_amx_fp16_supported()): + raise AssertionError( + "expected input_dtype == torch.half and AMX fp16 support, " + f"got {self.input_dtype}" + ) + return LayoutType.VNNI2 + + +def check_woq_int4_extra(config, m, n, k, alpha, num_threads, **kwargs): + if alpha != 1: + return False + q_group_size = kwargs.get("q_group_size") + if q_group_size is None: + raise AssertionError("expected q_group_size to be set, got None") + if ( + q_group_size not in [32, 64, 128] + or k % q_group_size != 0 + or config.register_blocking.block_k > q_group_size + ): + return False + return k % config.register_blocking.block_k == 0 and n % 64 == 0 + + +@register_micro_gemm( + # TODO: support float/half input + *generate_gemm_config( + VecAVX512, + [(4, 64, 32), (4, 64, 64), (4, 64, 128)], + input_dtype=torch.bfloat16, + input2_dtype=torch.uint8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=check_woq_int4_extra, + ), +) +class CppMicroGemmWoQInt4Avx512(CppMicroGemmFP32Vec): + """ + This class generates the code for WoQ int4 micro gemm using AVX512 intrinsics. + It is based on the corresponding ATen kernel. + Shape of packed weight = [N // 64, K, 32], viewed as [N, K // 2] + Shape of packed ScalesAndZeros = [K // group_size, N, 2] + """ + + TEMPLATE_ENTRY = r""" +{{declare_kernel}} { + {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}"); + {{kernel.assert_function}}(K % {{block_k}} == 0, "K dimension must be multiple of {{block_k}}"); + auto group_size = q_group_size; + for (int64_t m = 0; m < M; m += {{block_m}}) { + int64_t block_m = std::min(M - m, {{block_m}}); + for (int64_t n = 0; n < N; n += {{block_n}}) { + if (block_m == {{block_m}}) { + {{kernel_name}}_kernel<{{block_m}}, {{block_n}}, accum>( + A + m * lda, + reinterpret_cast(B) + n * ldb, + C + m * ldc + n, + K, + lda, + /* ldb */ {{block_n}} / 2, + ldc, + group_size, + ScaleAndZeros + n * 2, + lds, + k_start + ); + } else { + switch (block_m) { + {%- for b in range(block_m - 1, 0, -1) %} + case {{b}}: + {{kernel_name}}_kernel<{{b}}, {{block_n}}, accum>( + A + m * lda, + reinterpret_cast(B) + n * ldb, + C + m * ldc + n, + K, + lda, + /* ldb */ {{block_n}} / 2, + ldc, + group_size, + ScaleAndZeros + n * 2, + lds, + k_start + ); + break; + {%- endfor %} + default: + {{kernel.assert_function}}(false, "Unsupported block_m"); + } + } + } + } +} +""" + + TEMPLATE_KERNEL = r""" +inline bool {{kernel_name}}_is_block_start(int index, int k_start, int group_size) { + return (k_start + index) % group_size == 0; +} + +inline __m128i {{kernel_name}}_convert_int4_to_int8(const uint8_t* data) { + __m128i tmp = _mm_loadu_si64((const __m128i*)data); + __m128i bytes = _mm_cvtepu8_epi16(tmp); + const __m128i lowMask = _mm_set1_epi8(0xF); + __m128i high = _mm_andnot_si128(lowMask, bytes); + __m128i low = _mm_and_si128(lowMask, bytes); + high = _mm_slli_epi16(high, 4); + bytes = _mm_or_si128(low, high); + return bytes; +} + +template +inline void {{kernel_name}}_kernel( + const {{input_t}}* {{restrict_keyword}} A, + const uint8_t* {{restrict_keyword}} B, + {{output_t}}* {{restrict_keyword}} C, + int64_t K, + int64_t lda, + int64_t ldb, + int64_t ldc, + int64_t q_group_size, + const at::BFloat16* {{restrict_keyword}} ScaleAndZeros, + int64_t lds, // leading dimension of ScaleAndZeros + int64_t k_start) { + constexpr int BLOCK_K = {{block_k}}; + constexpr int ROWS = BLOCK_M; + constexpr int COLS = BLOCK_N / 16; + + const int PREFETCH_SIZE_K = 16 * 4; + const int PREFETCH_SIZE_KB = (PREFETCH_SIZE_K + BLOCK_K - 1) / BLOCK_K; + + // number of blocks on K + const int KB = K / BLOCK_K; + + __m512 va; + __m512 vb[COLS]; + __m512 vc[ROWS * COLS]; + __m512 scale[COLS]; + __m512 zero[COLS]; + + // Lookup table to de-quantize int4 values to bf16. + // Values are dequantized as truly int4 [-8, 7] range; + // + // dequant = (bf16(int4_value) * bf16_scale) + bf16_zero + // + static const __m512 lut = _mm512_set_ps( + 7.0f, 6.0f, 5.0f, 4.0f, + 3.0f, 2.0f, 1.0f, 0.0f, + -1.0f, -2.0f, -3.0f, -4.0f, + -5.0f, -6.0f, -7.0f, -8.0f); + + // index for transpose + static const __m512i idx1 = _mm512_set_epi32( + 30, 28, 26, 24, 22, 20, 18, 16, + 14, 12, 10, 8, 6, 4, 2, 0); + static const __m512i idx2 = _mm512_set_epi32( + 31, 29, 27, 25, 23, 21, 19, 17, + 15, 13, 11, 9, 7, 5, 3, 1); + + // load scale and zero point + auto load_scale_and_zeros = [&](int i, int _kb) { + // load 2x bfloat16 vector + __m512i t = _mm512_loadu_si512((__m512i*)(ScaleAndZeros + _kb * lds + 32 * i)); + _mm_prefetch(ScaleAndZeros + (_kb + PREFETCH_SIZE_KB) * lds + 32 * i, _MM_HINT_T0); + + // convert to 2x f32 vector + __m512 a, b; + at::vec::cvtbf16_fp32(t, a, b); + + // transpose scale_and_zero from {16, 2} to {2, 16} + // inputs: + // a: {s0, z0, s1, z1, ..., s7, z7} + // b: {s8, z8, s9, z9, ..., s15, z15} + // output: + // scale: {s0, s1, s2, ..., s15} + // zero: {z0, z1, z2, ..., z15} + scale[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b); + zero[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b); + }; + + auto loadc = [&](auto i) { + if constexpr (accum) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + vc[i] = _mm512_loadu_ps(C + row * ldc + col * 16); + } else { + vc[i] = _mm512_setzero_ps(); + } + }; + c10::ForcedUnroll{}(loadc); + + auto compute = [&, COLS](auto i, int k) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + + if constexpr (col == 0) { + float aa = static_cast(A[row * lda + k]); + _mm_prefetch(A + row * lda + k + PREFETCH_SIZE_K, _MM_HINT_T0); + va = _mm512_set1_ps(aa); + } + + if constexpr (row == 0) { + if constexpr (COLS == 4) { + // when BLOCK_N = 64, handle each row at a time + // to reduce de-quantize overhead. + if constexpr (col == 0) { + __m256i b4 = _mm256_loadu_si256((__m256i*)(B + k * ldb)); + _mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb, _MM_HINT_T0); + + __m512i b32 = _mm512_cvtepu8_epi32(_mm256_castsi256_si128(b4)); + vb[0] = _mm512_permutexvar_ps(b32, lut); + vb[0] = _mm512_fmadd_ps(vb[0], scale[0], zero[0]); + vb[2] = _mm512_permutexvar_ps(_mm512_srli_epi32(b32, 4), lut); + vb[2] = _mm512_fmadd_ps(vb[2], scale[2], zero[2]); + + b32 = _mm512_cvtepu8_epi32(_mm256_extracti128_si256(b4, 1)); + vb[1] = _mm512_permutexvar_ps(b32, lut); + vb[1] = _mm512_fmadd_ps(vb[1], scale[1], zero[1]); + vb[3] = _mm512_permutexvar_ps(_mm512_srli_epi32(b32, 4), lut); + vb[3] = _mm512_fmadd_ps(vb[3], scale[3], zero[3]); + } + } else { + __m128i b8 = {{kernel_name}}_convert_int4_to_int8(B + k * ldb + col * 8); + __m512i b32 = _mm512_cvtepu8_epi32(b8); + vb[col] = _mm512_permutexvar_ps(b32, lut); + vb[col] = _mm512_fmadd_ps(vb[col], scale[col], zero[col]); + } + } + + constexpr int idx = row * COLS + col; + vc[idx] = _mm512_fmadd_ps(va, vb[col], vc[idx]); + }; + + for (int k = 0, kb = 0; k < K; ++k) { + if ({{kernel_name}}_is_block_start(k, k_start, q_group_size)) { + c10::ForcedUnroll{}(load_scale_and_zeros, kb++); + } + c10::ForcedUnroll{}(compute, k); + } + + //store to C + auto storec = [&, COLS](auto i) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + _mm512_storeu_ps(C + row * ldc + col * 16, vc[i]); + }; + c10::ForcedUnroll{}(storec); +} +""" + + def get_kernel_extra_args_declare(self) -> str: + return ( + "const int64_t q_group_size,\n" + " const at::BFloat16* __restrict__ ScaleAndZeros,\n" + " const int64_t lds,\n" + " int64_t k_start," + ) + + def get_kernel_extra_args(self, **kwargs) -> list[str]: + if "kernel" not in kwargs: + raise AssertionError("expected 'kernel' in kwargs") + if "qscale_and_zeros" not in kwargs: + raise AssertionError("expected 'qscale_and_zeros' in kwargs") + kernel = kwargs["kernel"] + qscale_and_zeros = kwargs["qscale_and_zeros"] + return [ + "group_size,", + f"&({kernel.index(qscale_and_zeros, [0, 0, 0])}),", + "N * 2,", # lds + "k_start,", + ] + + def is_woq_int4(self): + return True + + +@register_micro_gemm( + *generate_gemm_config( + VecAMX, + [ # (block_m, block_n, block_k) + (16, 32, 32), + (32, 32, 32), + ], + input_dtype=torch.bfloat16, + input2_dtype=torch.uint8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=check_amx_extra, + ), +) +class CppMicroGemmWoQInt4Amx(CppMicroGemmAMX): + """ + This class generates the code for WoQ int4 micro gemm using AMX intrinsics, + which are available on 4th and newer generations of Intel Xeon. + Shape of packed weight = [N // 32, K, 16], viewed as [N, K // 2] + Shape of packed ScalesAndZeros = [K // group_size, N, 2] + Reuse TEMPLATE_KERNEL of CppMicroGemmAMX. + """ + + TEMPLATE_ENTRY = r""" +inline bool {{kernel_name}}_is_block_start(int index, int k_start, int group_size) { + // check if (k_start + index) % group_size == 0, assuming group_size = 32/64/128 + return ((k_start + index) & (group_size - 1)) == 0; +} + +{{declare_kernel}} { + {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}"); + {{kernel.assert_function}}(K % 2 == 0, "K dimension must be multiple of 2"); + {{kernel.assert_function}}({{block_n}} == 32, "block_n must be 32 for WOQ int4"); + + // Create a stack-allocated buffer for tiles of B. + // Except maybe for the tail-case, an AMX tile of B has 16x32 BF16 elements. + // we cache K * {{block_n}} elements of dequantized B + {{template.codegen_allocate_weight_buffer("dequantized_B_buf", input_t, "K", block_n)}} + + constexpr int BLOCK_K = {{block_k}}; + constexpr int64_t BLOCK_N = {{block_n}}; + constexpr int COLS = BLOCK_N / 16; + const int PREFETCH_SIZE_K = 16 * 4; + const int PREFETCH_SIZE_KB = (PREFETCH_SIZE_K + BLOCK_K - 1) / BLOCK_K; + const int KB = K / BLOCK_K; + + __m512i b32[COLS * 2]; + __m512 vb[COLS * 2]; + __m512 scale[COLS]; + __m512 zero[COLS]; + + // Lookup table to de-quantize int4 values to bf16. + // Values are dequantized as truly int4 [-8, 7] range; + // + // dequant = (bf16(int4_value) * bf16_scale) + bf16_zero + // + static const __m512 lut = _mm512_set_ps( + 7.0f, 6.0f, 5.0f, 4.0f, + 3.0f, 2.0f, 1.0f, 0.0f, + -1.0f, -2.0f, -3.0f, -4.0f, + -5.0f, -6.0f, -7.0f, -8.0f); + + // index for transpose + static const __m512i idx1 = _mm512_set_epi32( + 30, 28, 26, 24, 22, 20, 18, 16, + 14, 12, 10, 8, 6, 4, 2, 0); + static const __m512i idx2 = _mm512_set_epi32( + 31, 29, 27, 25, 23, 21, 19, 17, + 15, 13, 11, 9, 7, 5, 3, 1); + + // Indices for VNNI layout conversion + __m512i idx_low = _mm512_set_epi32( + 0x17, + 0x07, + 0x16, + 0x06, + 0x15, + 0x05, + 0x14, + 0x04, + 0x13, + 0x03, + 0x12, + 0x02, + 0x11, + 0x01, + 0x10, + 0x00); + __m512i idx_high = _mm512_set_epi32( + 0x1f, + 0x0f, + 0x1e, + 0x0e, + 0x1d, + 0x0d, + 0x1c, + 0x0c, + 0x1b, + 0x0b, + 0x1a, + 0x0a, + 0x19, + 0x09, + 0x18, + 0x08); + + // load scale and zero point + auto load_scale_and_zeros = [&](int i, int _kb) { + // load 2x bfloat16 vector + __m512i t = _mm512_loadu_si512((__m512i*)(ScaleAndZeros + _kb * lds + 32 * i)); + _mm_prefetch(ScaleAndZeros + (_kb + PREFETCH_SIZE_KB) * lds + 32 * i, _MM_HINT_T0); + + // convert to 2x f32 vector + __m512 a, b; + at::vec::cvtbf16_fp32(t, a, b); + + // transpose scale_and_zero from {16, 2} to {2, 16} + // inputs: + // a: {s0, z0, s1, z1, ..., s7, z7} + // b: {s8, z8, s9, z9, ..., s15, z15} + // output: + // scale: {s0, s1, s2, ..., s15} + // zero: {z0, z1, z2, ..., z15} + scale[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b); + zero[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b); + }; + + // Dequantize a B block of 2 * block_n into bf16 + // So, it handles k and k+1 at the same time + auto dequantize_B = [&](int n) { + constexpr int64_t ldb_int4 = BLOCK_N / 2; // 16 + for (int k = 0, kb = 0; k < K; k += 2) { + // Since block_k must be 32 for AMX microkernels, k_start may not be + // a multiple of q_group_size. In that case, we need to load scales + // and zero points immediately when k == 0 here + if ({{kernel_name}}_is_block_start(k, k_start, q_group_size) || k == 0) { + c10::ForcedUnroll{}(load_scale_and_zeros, kb++); + } + + _mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb_int4, _MM_HINT_T0); + + // load 256 bits = 64 elements in int4 + __m128i b4 = _mm_loadu_si128((__m128i*)(B + n / 2 * K + k * ldb_int4)); + b32[0] = _mm512_cvtepu8_epi32(b4); + b32[1] = _mm512_srli_epi32(b32[0], 4); + vb[0] = _mm512_permutexvar_ps(b32[0] , lut); + vb[0] = _mm512_fmadd_ps(vb[0], scale[0], zero[0]); + vb[1] = _mm512_permutexvar_ps(b32[1], lut); + vb[1] = _mm512_fmadd_ps(vb[1], scale[1], zero[1]); + + __m128i b4_2 = _mm_loadu_si128((__m128i*)(B + n / 2 * K + (k + 1) * ldb_int4)); + b32[0 + COLS] = _mm512_cvtepu8_epi32(b4_2); + b32[1 + COLS] = _mm512_srli_epi32(b32[0 + COLS], 4); + vb[0 + COLS] = _mm512_permutexvar_ps(b32[0 + COLS] , lut); + vb[0 + COLS] = _mm512_fmadd_ps(vb[0 + COLS], scale[0], zero[0]); + vb[1 + COLS] = _mm512_permutexvar_ps(b32[1 + COLS], lut); + vb[1 + COLS] = _mm512_fmadd_ps(vb[1 + COLS], scale[1], zero[1]); + + for (int i = 0; i < COLS; i++) { + // convert to VNNI + auto low = _mm512_permutex2var_ps(vb[i], idx_low, vb[i + COLS]); + auto high = _mm512_permutex2var_ps(vb[i], idx_high, vb[i + COLS]); + // convert lower 16 float32 values to bfloat16 + auto v0_bf16 = reinterpret_cast<__m256i>(_mm512_cvtneps_pbh(low)); + // convert higher 16 float32 values to bfloat16 + auto v1_bf16 = reinterpret_cast<__m256i>(_mm512_cvtneps_pbh(high)); + // combine the lower 16 and higher 16 bfloat16 values + auto v = _mm512_castsi256_si512(v0_bf16); + v = _mm512_inserti64x4(v, v1_bf16, 1); + // store the VNNI format bfloat16 values + {{input_t}}* addr = dequantized_B_buf + k * 32 + (i % 2) * 32; + _mm512_storeu_si512(addr, v); + } + } + }; + + for (int64_t n = 0; n < N; n += {{block_n}}) { + // Dequantize K * block_n int8 B elements into BF16 + dequantize_B(n); + for (int64_t m = 0; m < M; m += {{block_m}}) { + int64_t block_m = std::min(M - m, {{block_m}}); + int64_t m_tail = m; + {%- for num_rows in range(block_m, 0, -16) %} + {%- if num_rows != block_m %} + else + {%- endif %} + if (block_m >= {{num_rows}}) { + {{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}( + amx_state, + A + m * lda, + dequantized_B_buf + n * K, + C + m * ldc + n, + K, + lda, + {{block_n}}, + ldc, + 16 + ); + block_m -= {{num_rows}}; + m_tail += {{num_rows}}; + } + {%- endfor %} + if (block_m > 0) { + {{kernel_name}}_amx_kernel_16_{{num_columns}}( + amx_state, + A + m_tail * lda, + dequantized_B_buf + n * K, + C + m_tail * ldc + n, + K, + lda, + {{block_n}}, + ldc, + block_m + ); + } + } // for m + } // for n +} +""" + + def get_kernel_extra_args_declare(self) -> str: + return ( + "AMXState& amx_state,\n" + " const int64_t q_group_size,\n" + " const c10::BFloat16* __restrict__ ScaleAndZeros,\n" + " const int64_t lds,\n" + " int64_t k_start," + ) + + def get_kernel_extra_args(self, **kwargs) -> list[str]: + if "kernel" not in kwargs: + raise AssertionError("expected 'kernel' in kwargs") + if "qscale_and_zeros" not in kwargs: + raise AssertionError("expected 'qscale_and_zeros' in kwargs") + kernel = kwargs["kernel"] + qscale_and_zeros = kwargs["qscale_and_zeros"] + return [ + "amx_state,", + "group_size,", + f"&({kernel.index(qscale_and_zeros, [0, 0, 0])}),", + "N * 2,", # lds + "k_start,", + ] + + def is_woq_int4(self): + return True + + +def create_micro_gemm( + name, + m, + n, + k, + input_dtype, + input2_dtype, + output_dtype=None, + compute_dtype=None, + alpha=1, + num_threads=-1, + use_ref=True, + q_group_size=None, +) -> CppMicroGemm | None: + """ + Based on the provided info, try to find the config of the micro-kernel that would + deliver the best performance in terms of lower latency for this case. + """ + + def create_from_config(cls, config: CppMicroGemmConfig): + return cls( + name, + config.input_dtype, + config.input2_dtype, + config.output_dtype, + config.compute_dtype, + config.register_blocking, + alpha, + ) + + def skip_amx_kernel_for_woq(dynamic_M): + # For WoQ GEMM, AMX micro-kernel may not perform well if m is small. + # Exception: for dynamic shapes, we consider using the AMX micro-kernel. + if ( + dynamic_M + or input_dtype != torch.bfloat16 + or input2_dtype not in [torch.int8, torch.uint8] + ): + return False + m_threshold = 5 + return m < m_threshold + + if not (isinstance(n, int) or n.is_number): + raise AssertionError(n) + if not (isinstance(k, int) or k.is_number): + raise AssertionError(k) + from ..utils import has_free_symbols + + dynamic_M = has_free_symbols((m,)) + m = V.graph.sizevars.optimization_hint(m, fallback=1) + if not (isinstance(m, int) or m.is_number): + raise AssertionError(m) + if output_dtype is None: + output_dtype = input_dtype + if compute_dtype is None: + compute_dtype = output_dtype + if num_threads < 0: + num_threads = parallel_num_threads() + vec_isa = pick_vec_isa() + matched_configs = [] + for cls, configs in micro_gemm_configs.items(): + for config in configs: + if not issubclass(vec_isa.__class__, config.vec_isa_cls): + continue + if ( + config.input_dtype == input_dtype + and config.compute_dtype == compute_dtype + and config.input2_dtype == input2_dtype + and config.output_dtype == output_dtype + # The output_dtype here is the output dtype of the micro-kernel. + # In some cases, the actual output dtype of the op for which the micro-kernel + # is being created would be same as that of the activation, but the micro-kernels + # compute output in Float/int32, which is converted in the GEMM template. This is + # subject to change in the future. + ): + if config.extra_check is not None and not config.extra_check( + config, + m, + n, + k, + alpha, + num_threads, + dynamic_M=dynamic_M, + q_group_size=q_group_size, + vec_isa=vec_isa, + ): + continue + block_m, block_n, block_k = config.register_blocking + if config.vec_isa_cls == VecAMX and skip_amx_kernel_for_woq(dynamic_M): + continue + # Criteria on the ranking of configurations + # 1. ISA: AMX > VNNI > VEC + # 2. Dividable by block sizes (block_m, block_n, block_k) + # 3. Number of mxn blocks is large enough to occupy all the threads + # 4. Register blocks are larger + isa_score = 0 + if config.vec_isa_cls == VecAMX: + isa_score += 2 + elif config.vec_isa_cls == VecAVX512VNNI: + isa_score += 1 + dividable_score = 0 + if m % block_m == 0: + dividable_score += 1 + if n % block_n == 0: + dividable_score += 1 + if k % block_k == 0: + dividable_score += 1 + occupancy_score = 0 + n_blocks = (n + block_n - 1) // block_n + total_mxn_blocks = n_blocks * ((m + block_m - 1) // block_m) + if n_blocks >= num_threads: + occupancy_score += 1 + if total_mxn_blocks >= num_threads: + occupancy_score += 1 + register_bytes = ( + block_m * block_n * config.compute_dtype.itemsize + + (block_m * block_k + block_k * block_n) + * config.input_dtype.itemsize + ) + size_score = register_bytes + # if number of mxn blocks can not occupy all the threads, + # we favor smaller register blocks. + if occupancy_score == 0: + size_score = 0 - register_bytes + matched_configs.append( + ( + (isa_score, dividable_score, occupancy_score, size_score), + cls, + config, + ) + ) + if len(matched_configs) == 0: + if use_ref: + return CppMicroGemmRef( + name, input_dtype, input2_dtype, output_dtype, compute_dtype, alpha + ) + else: + return None + # TODO(jgong5): allow autotuning on choices of configs + return create_from_config(*max(matched_configs, key=operator.itemgetter(0))[1:]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template.py new file mode 100644 index 0000000000000000000000000000000000000000..ee331272d1c2724889786cf7782a406be82671aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template.py @@ -0,0 +1,142 @@ +# mypy: allow-untyped-defs +import ctypes +import functools +import itertools +import logging +import sys +from collections.abc import Callable, Iterable +from unittest.mock import patch + +import sympy + +from .. import config, ir +from ..autotune_process import CppBenchmarkRequest, TensorMeta +from ..utils import IndentedBuffer, Placeholder, unique +from ..virtualized import V +from .common import KernelTemplate +from .cpp_template_kernel import CppTemplateCaller, CppTemplateKernel + + +log = logging.getLogger(__name__) + + +class CppTemplate(KernelTemplate): + index_counter = itertools.count() + + def __init__( + self, + name: str, + input_nodes, + layout: ir.Layout, + num_threads: int, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + ) -> None: + super().__init__(name) + self.input_nodes = input_nodes + self.index = next(self.index_counter) + self.output_node: ir.Buffer | list[ir.Buffer] = ir.Buffer( + name=f"buf_out{self.index}", layout=layout + ) + self.layout = layout + self.num_threads = num_threads + self.epilogue_creator = epilogue_creator + + def generate(self, **kwargs): + kernel_name = f"cpp_{self.name}" + with ( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)), + patch.object(ir.FlexibleLayout, "allow_indexing", True), + V.graph.set_current_device(self.layout.device), + CppTemplateKernel( + kernel_name=kernel_name, num_threads=self.num_threads + ) as kernel, + ): + code = kernel.render(self, **kwargs) + _, call_args, _, _ = kernel.args.python_argdefs() + log.debug("Generated Code:\n%s", code) + log.debug( + "Args: cpp_argdefs: %s, python_argdefs: %s", + kernel.args.cpp_argdefs(), + kernel.args.python_argdefs(), + ) + + expected_args = list( + unique(input_node.get_name() for input_node in self.input_nodes) + ) + if isinstance(self.output_node, Iterable): + expected_args.extend([node.get_name() for node in self.output_node]) + else: + expected_args.extend([self.output_node.get_name()]) + if list(call_args)[: len(expected_args)] != expected_args: + raise AssertionError( + ( + call_args, + expected_args, + ) + ) + # extra_args are only used for benchmarking, not compiled kernel correctness + extra_args = V.graph.sizevars.optimization_hints( + map(sympy.expand, call_args[len(expected_args) :]) + ) + # Cast the size hint from int to ctypes.c_ulonglong explicitly + # since in cpp kernel, we bind it to C long + extra_args = tuple(ctypes.c_ulonglong(x) for x in extra_args) + + kernel_hash_name = f"cpp_{self.name}_{self.index}" + + # Create the BenchmarkRequest for CPP + bmreq = CppBenchmarkRequest( + kernel_name=kernel_name, + input_tensor_meta=TensorMeta.from_irnodes(self.input_nodes), + output_tensor_meta=TensorMeta.from_irnodes(self.output_node), + extra_args=extra_args, + source_code=code, + ) + + def make_kernel_render( + template_node: ir.CppTemplateBuffer, + flag_template_buffer_has_other_users: bool, + epilogue_nodes: list[ir.IRNode] | None = None, + ): + kernel = CppTemplateKernel( + kernel_name=str(Placeholder.KERNEL_NAME), num_threads=self.num_threads + ) + render = functools.partial( + kernel.render, + self, + template_buffer_node=template_node, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_nodes, + **kwargs, + ) + return kernel, render + + return CppTemplateCaller( + kernel_hash_name, + self.name, + self.input_nodes, + # pyrefly: ignore [bad-index, index-error] + self.output_node[0].get_layout() + if isinstance(self.output_node, Iterable) + else self.output_node.get_layout(), + make_kernel_render, + bmreq, + self, + ) + + def header(self) -> IndentedBuffer: + res = IndentedBuffer() + res.writeline("#include ") + # TODO: add c10::ForcedUnroll test to test_aoti_abi_check + res.splice("""#include """) + res.splice("""#include """) + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + if enable_kernel_profile: + res.writelines(["#include "]) + return res + + def render(self, **kwargs) -> str: + raise NotImplementedError diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..6d1f14bea3de835838b782d1481991696fe0694e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template_kernel.py @@ -0,0 +1,666 @@ +# mypy: allow-untyped-defs +import itertools +from collections.abc import Callable, Iterable +from typing import Any +from unittest.mock import patch + +import sympy +from sympy.parsing.sympy_parser import parse_expr + +import torch +from torch._inductor.utils import do_bench_using_profiling +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.symbol import SymT + +from .. import config, cpp_builder, ir, lowering as L +from ..autotune_process import CppBenchmarkRequest +from ..loop_body import LoopBody +from ..select_algorithm import PartialRender +from ..utils import sympy_index_symbol, sympy_index_symbol_with_prefix +from ..virtualized import V +from .common import REMOVED +from .cpp import CppKernel, CppKernelProxy, KernelGroup, ParallelDepth +from .cpp_utils import cexpr_index, DTYPE_TO_CPP, LocalBufferContext + + +def parse_expr_with_index_symbols(expr): + if isinstance(expr, sympy.Expr): + return expr + elif isinstance(expr, (list, tuple)): + return [parse_expr_with_index_symbols(e) for e in expr] + else: + expr = parse_expr(str(expr)) + int_symbols = {sym: sympy_index_symbol(sym.name) for sym in expr.free_symbols} + return expr.subs(int_symbols) + + +def wrap_with_tensorbox(node) -> ir.TensorBox: + return ( + ir.TensorBox.create(node) if isinstance(node, ir.Buffer) else ir.TensorBox(node) + ) + + +class CppTemplateKernel(CppKernel): + def __init__(self, kernel_name, num_threads): + super().__init__(None, num_threads) + self.kernel_name = kernel_name + self.render_hooks = {} + self.local_buffers = {} + + def render(self, template, **kwargs): + return PartialRender( + template.render(kernel=self, **kwargs), self.render_hooks + ).finalize_all() + + def def_kernel( + self, + inputs: dict[str, ir.Buffer], + outputs: dict[str, ir.Buffer], + aliases: dict[str, str] | None = None, + function_name: str = "", + extra_sizevars: list[sympy.Expr] | None = None, + placeholder: str = "", + ) -> str: + if len(function_name) == 0: + function_name = str(self.kernel_name) + for name, inp in inputs.items(): + if inp is not None: + self.args.input_buffers[inp.get_name()] = name + for name, out in outputs.items(): + self.args.output_buffers[out.get_name()] = name + if aliases is not None: + for alias, orig in aliases.items(): + if orig in self.args.input_buffers: + self.args.input_buffers[alias] = self.args.input_buffers[orig] + if orig in self.args.output_buffers: + self.args.output_buffers[alias] = self.args.output_buffers[orig] + + unique_sizevars = OrderedSet( + s + for input in inputs.values() + if input is not None + for sym in itertools.chain(input.get_size(), input.get_stride()) + if isinstance(sym, sympy.Expr) + for s in sym.free_symbols + ) + unique_sizevars.update( + s + for sym in extra_sizevars or [] + if isinstance(sym, sympy.Expr) + for s in sym.free_symbols + ) + unique_sizevars.update( + s + for output in outputs.values() + for sym in itertools.chain(output.get_size(), output.get_stride()) + if isinstance(sym, sympy.Expr) + for s in sym.free_symbols + ) + sizevars = sorted(unique_sizevars, key=str) + for sizevar in sizevars: + self.args.sizevars[sizevar] = f"k{sizevar}" + + def hook(): + # remove all aliases before generate function definition + if aliases is not None: + for alias in aliases: + if alias in self.args.input_buffers: + raise AssertionError( + f"input_buffers cannot be removed: {alias}" + ) + if alias in self.args.output_buffers: + self.args.output_buffers[alias] = REMOVED + cpp_argdefs, _, _ = self.args.cpp_argdefs() + return f"void {function_name}({', '.join(cpp_argdefs)})" + + if placeholder in self.render_hooks: + raise AssertionError(f"placeholder already registered: {placeholder}") + self.render_hooks[placeholder] = hook + return placeholder + + def call_kernel(self, name: str, node: ir.CppTemplateBuffer): + wrapper = V.graph.wrapper_code + _, call_args, arg_types = self.args.cpp_argdefs() + wrapper.generate_kernel_call(name, call_args, triton=False, arg_types=arg_types) + + def dtype(self, node: ir.Buffer) -> str: + return DTYPE_TO_CPP[node.get_dtype()] + + def acc_dtype(self, node: ir.Buffer) -> str: + if node.get_dtype() in [torch.float32, torch.bfloat16, torch.half]: + return "float" + else: + raise NotImplementedError(f"Unsupported dtype: {node.get_dtype()}") + + def size(self, node: ir.Buffer, dim: int) -> str: + return cexpr_index(self.rename_indexing(node.get_size()[dim])) + + def stride(self, node: ir.Buffer, dim: int) -> str: + return cexpr_index(self.rename_indexing(node.get_stride()[dim])) + + def index(self, node: ir.Buffer, indices: list[Any]) -> str: + indexer = node.get_layout().as_fixed().make_indexer() + index = indexer(parse_expr_with_index_symbols(indices)) + index = self.rename_indexing(index) + outer_name = node.get_name() + inner_name = ( + outer_name + if outer_name in self.local_buffers + else self.args.input(node.get_name()) + ) + return f"{inner_name}[{cexpr_index(index)}]" + + def slice_nd(self, node, ranges: list[tuple[Any, Any]]) -> ir.ReinterpretView: + """ + Slice the given node with a list of ranges (start and end) corresponding to its dims. + The dim is not sliced if the corresponding range is empty. + """ + if len(ranges) != len(node.get_size()): + raise AssertionError(f"{ranges=}, {node=}") + sliced = wrap_with_tensorbox(node) + for dim, _range in enumerate(ranges): + if len(_range) == 0: + continue + if len(_range) != 2: + raise AssertionError(f"expected range of length 2, got {len(_range)}") + start, end = parse_expr_with_index_symbols(_range) + sliced = L.slice_(sliced, dim, start, end, clamp=False) + if not isinstance(sliced, ir.TensorBox): + raise AssertionError(f"expected ir.TensorBox, got {type(sliced)}") + if not isinstance(sliced.data, ir.ReinterpretView): + raise AssertionError(sliced.data) + return sliced.data + + def select(self, node, dim: int, idx: int) -> ir.ReinterpretView: + # We avoid using L.select here because we need clamp=False so the dim after slicing + # is 1 instead of a sympy expression of symbol - dim_size. + node = wrap_with_tensorbox(node) + idx = ir.View.handle_negative_index(idx, node.get_size()[dim]) + sliced = L.squeeze(L.slice_(node, dim, idx, idx + 1, clamp=False), dim) + if not isinstance(sliced.data, ir.ReinterpretView): + raise AssertionError(sliced.data) + return sliced.data + + def view(self, node, sizes: list[Any]) -> ir.IRNode: + node = wrap_with_tensorbox(node) + sizes = parse_expr_with_index_symbols(sizes) + return L.view(node, sizes).data + + def permute(self, node, dims): + node = wrap_with_tensorbox(node) + permuted = L.permute(node, dims).data + if not isinstance(permuted, ir.ReinterpretView): + raise AssertionError(f"expected ir.ReinterpretView, got {type(permuted)}") + return permuted + + def maybe_codegen_profile(self, prefix_kernel_name: str | None = None) -> str: + if config.cpp.enable_kernel_profile: + graph_id = V.graph.graph_id + prefix = "graph_" + str(graph_id) + "_" if graph_id is not None else "" + if prefix and prefix_kernel_name: + prefix += prefix_kernel_name + "_" + handle_str = ( + "torch::aot_inductor::RAIIAtenRecordFunctionHandle " + f'record_{prefix}{self.kernel_name}_("{prefix}{self.kernel_name}", nullptr);' + ) + return handle_str + else: + return "" + + def unroll_pragma(self, unroll): + if cpp_builder.is_gcc(): + return f"#pragma GCC unroll {unroll}" + else: + return f"#pragma unroll {unroll}" + + def define_buffer(self, name, sizes: list[Any], dtype=torch.float) -> str: + """Define kernel local buffer""" + sizes = parse_expr_with_index_symbols(sizes) + buf = ir.Buffer( + name=name, layout=ir.FixedLayout(torch.device("cpu"), dtype, sizes) + ) + self.local_buffers[name] = buf + ctype = f"{DTYPE_TO_CPP[dtype]}" + numel = f"{cexpr_index(buf.get_numel())}" + return f"auto _{name} = std::make_unique<{ctype}[]>({numel}); auto {name} = _{name}.get();" + + def define_stack_allocated_buffer( + self, name, sizes: list[Any], dtype=torch.float + ) -> str: + """Define stack-allocated buffer""" + sizes = parse_expr_with_index_symbols(sizes) + buf = ir.Buffer( + name=name, layout=ir.FixedLayout(torch.device("cpu"), dtype, sizes) + ) + self.local_buffers[name] = buf + ctype = f"{DTYPE_TO_CPP[dtype]}" + numel = f"{cexpr_index(buf.get_numel())}" + return f"alignas(64) {ctype} _{name}[{numel}]; {ctype}* {name} = _{name};" + + def reinit_buffer_if_null(self, name): + """Reinit the previously defined local buffer if it is null""" + if name not in self.local_buffers: + raise AssertionError(f"unknown local buffer: {name}") + buf = self.local_buffers[name] + ctype = f"{DTYPE_TO_CPP[buf.layout.dtype]}" + numel = f"{cexpr_index(buf.get_numel())}" + return f"if (_{name} == nullptr) {{ _{name} = std::make_unique<{ctype}[]>({numel}); {name} = _{name}.get(); }}" + + def release_buffer(self, name): + """Codegen the code to release the ownership of a local buffer to others""" + if name not in self.local_buffers: + raise AssertionError(f"unknown local buffer: {name}") + return f"_{name}.release()" + + def store_pointwise_nodes( + self, + dst: ir.Buffer, + nodes: list[ir.IRNode], + offsets: list[sympy.Expr] | None = None, + reindexers: list[Callable[[list[Any]], list[Any]] | None] | None = None, + ) -> str: + var_sizes = (tuple(dst.get_size()), ()) + var_ranges = { + sympy_index_symbol_with_prefix(SymT.INDEX, i): sz + for i, sz in enumerate(var_sizes[0]) + } + if not offsets: + offsets = [sympy.S.Zero] * len(var_sizes[0]) + if not reindexers: + reindexers = [None] * len(nodes) + if len(offsets) != len(var_sizes[0]): + raise AssertionError( + f"expected {len(var_sizes[0])} offsets, got {len(offsets)}" + ) + output_index = dst.get_layout().make_indexer()([*var_ranges.keys()]) + kernel_group = KernelGroup() + kernel_group.args = self.args + cpp_kernel_proxy = CppKernelProxy(kernel_group) + bodies = [] + var_sizes_list = [] + for i, node in enumerate(nodes): + output_name = node.get_name() if i < len(nodes) - 1 else dst.get_name() + node = node.data if isinstance(node, ir.ComputedBuffer) else node + if not isinstance(node, ir.Pointwise): + raise AssertionError(node) + + def fn(*args): + if len(args) != 2: + raise AssertionError(f"expected 2 args, got {len(args)}") + if len(args[0]) != len(var_sizes[0]): + raise AssertionError( + f"expected {len(var_sizes[0])} indices, got {len(args[0])}" + ) + if len(args[1]) != 0: + raise AssertionError( + f"expected no reduction vars, got {len(args[1])}" + ) + new_args = [arg + offset for arg, offset in zip(args[0], offsets)] # type: ignore[arg-type] + if reindexers[i] is not None: + new_args = reindexers[i](new_args) # type: ignore[misc] + V.ops.store( + output_name, + output_index, + node.make_loader()(new_args).value, + ) + + body = LoopBody( + fn, + (list(var_ranges.keys()), ()), + var_ranges, + list(var_ranges.keys()), + tuple(), + ) + bodies.append(body) + var_sizes_list.append(var_sizes) + + cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list) + + def max_parallel_depth(): + return ParallelDepth(parallel_depth=0, start_depth=0) + + # This loop is not parallelized since it is not the outermost loop. + with patch.object( + cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth + ): + kernel_group.finalize_kernel(cpp_kernel_proxy, []) + return kernel_group.loops_code.getvalue() + + def store_grouped_gemm_pointwise_nodes( + self, + dst: tuple[ir.Buffer], + nodes: list[ir.IRNode], + offsets: list[sympy.Expr], + reindexers: list[Callable[[list[Any]], list[Any]] | None], + output_names: list[str], + ) -> str: + ref_dst = dst[0] + var_sizes = (tuple(ref_dst.get_size()), ()) + var_ranges = { + sympy_index_symbol_with_prefix(SymT.INDEX, i): sz + for i, sz in enumerate(var_sizes[0]) + } + if not offsets: + raise AssertionError("offsets should be set outside") + if not all(len(offset) == len(var_sizes[0]) for offset in offsets): + raise AssertionError(f"expected all offsets of length {len(var_sizes[0])}") + output_index = ref_dst.get_layout().make_indexer()([*var_ranges.keys()]) + kernel_group = KernelGroup() + kernel_group.args = self.args + cpp_kernel_proxy = CppKernelProxy(kernel_group) + bodies = [] + var_sizes_list = [] + for i, node in enumerate(nodes): + output_name = output_names[i] + node = node.data if isinstance(node, ir.ComputedBuffer) else node + if not isinstance(node, ir.Pointwise): + raise AssertionError(node) + + def fn(*args): + if len(args) != 2: + raise AssertionError(f"expected 2 args, got {len(args)}") + if len(args[0]) != len(var_sizes[0]): + raise AssertionError( + f"expected {len(var_sizes[0])} indices, got {len(args[0])}" + ) + if len(args[1]) != 0: + raise AssertionError( + f"expected no reduction vars, got {len(args[1])}" + ) + new_args = [arg + offset for arg, offset in zip(args[0], offsets[i])] # type: ignore[arg-type] + if reindexers[i] is not None: + new_args = reindexers[i](new_args) # type: ignore[misc] + V.ops.store( + output_name, + output_index, + node.make_loader()(new_args).value, + ) + + body = LoopBody( + fn, + (list(var_ranges.keys()), ()), + var_ranges, + list(var_ranges.keys()), + tuple(), + ) + bodies.append(body) + var_sizes_list.append(var_sizes) + + cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list) + + def max_parallel_depth(): + return ParallelDepth(parallel_depth=0, start_depth=0) + + # This loop is not parallelized since it is not the outermost loop. + with patch.object( + cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth + ): + kernel_group.finalize_kernel(cpp_kernel_proxy, []) + return kernel_group.loops_code.getvalue() + + def store_output( + self, + dst: ir.Buffer, + src: ir.Buffer, + orig_src: ir.Buffer | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + offsets: list[Any] | None = None, + reindexers: list[Callable[[list[Any]], list[Any]] | None] | None = None, + ): + """ + Store the `src` buffer to the `dst` buffer. The size of `src` and `dst` should match. + If `epilogue_nodes` is provided, the `src` buffer is firstly computed with the epilogues + before stored to `dst`. The `epilogues_nodes` are all pointwise. + + Notes: + 1. `src` and `dst` buffer could be the same buffer in which case we are doing in-place compute + and stores. In case `epilogue_nodes` are not provided, we do nothing. + 2. The `epilogue_nodes`, if exist, have computations on `src` before storing to `dst` but since + they come from the original Inductor IR, they might need to be adjusted before working with + `src` and `dst` as outlined below: + a) `src` or `dst` buffer could be a sub-slice of the ranges the `epilogue_nodes`work on. + In this case, the `offsets` could be provided to adjust the indices passed to + `epilogue_nodes` during codegen and the data ranges are also configured according to + the sizes of `src` and `dst`. + b) `dst` might be indexed in a different way as the `epilogue_nodes`, hence a `reindexer` is + needed on the indices to `epilogue_nodes` to match the indexing of `dst`. + c) If `src` is local, we need to add a local buffer for it and localize the `orig_src` buffer + in `epilogue_nodes` with `src`. + """ + if not isinstance(dst, (ir.Buffer, ir.ReinterpretView)): + raise AssertionError( + f"expected ir.Buffer or ir.ReinterpretView, got {type(dst)}" + ) + if dst.get_size() != src.get_size(): + raise AssertionError(f"{dst=}, {src=}") + if offsets: + offsets = parse_expr_with_index_symbols(offsets) + if epilogue_nodes: + with LocalBufferContext(self.args) as scope: + if orig_src is None: + raise AssertionError("orig_src must not be None") + if orig_src.get_name() != src.get_name(): + scope.add_local_buffer( + src, + [ + orig_src, + ], + ) + epilogue_nodes = scope.localize_nodes(epilogue_nodes) + return self.store_pointwise_nodes( + dst, + epilogue_nodes, # type: ignore[arg-type] + offsets, + reindexers, + ) + else: + if dst.get_name() != src.get_name(): + # src is local + copy = L.copy(dst, src).data.data + with LocalBufferContext(self.args) as scope: + scope.add_local_buffer(src) + + return self.store_pointwise_nodes(dst, [copy]) + else: + if dst.layout != src.layout: + raise AssertionError(f"{dst=}, {src=}") + return "" + + def store_outputs( + self, + dst: tuple[ir.Buffer], + src: tuple[ir.IRNode], + orig_src: tuple[ir.IRNode] | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + offsets: list[Any] | None = None, + reindexers: list[Callable[[list[Any]], list[Any]] | None] | None = None, + multi_output_buffers: tuple[ir.MultiOutput, ...] | None = None, + ): + if not isinstance(dst, Iterable): + raise AssertionError(f"expected Iterable, got {type(dst)}") + if not all(_dst.get_size() == _src.get_size() for _src, _dst in zip(src, dst)): + raise AssertionError("src and dst sizes must match") + if offsets: + offsets = parse_expr_with_index_symbols(offsets) + gemm_num = len(src) + final_offsets = [] + output_names = [] + if epilogue_nodes: + if not reindexers: + reindexers = [None] * len(epilogue_nodes) + with LocalBufferContext(self.args) as scope: + if orig_src is None: + raise AssertionError("orig_src must not be None") + localize_epilogue_nodes = [] + all_read_names = [] + for epilogue in epilogue_nodes: + all_read_names.extend(list(epilogue.get_read_names())) + localize_epilogue_nodes.extend(scope.localize_nodes(epilogue_nodes)) + final_offsets.extend([offsets] * len(localize_epilogue_nodes)) + output_names.extend( + [node.get_name() for node in localize_epilogue_nodes] + ) + for gemm_idx in range(gemm_num): + if orig_src[gemm_idx].get_name() != src[gemm_idx].get_name(): + if orig_src[gemm_idx].get_name() in all_read_names or ( + multi_output_buffers + and multi_output_buffers[gemm_idx].get_name() + in all_read_names + ): + # If any of the Epilogue nodes use this GEMM output, let's localize the GEMM output + global_buffers = [orig_src[gemm_idx]] + if ( + multi_output_buffers + and multi_output_buffers[gemm_idx].get_name() + in all_read_names + and orig_src[gemm_idx].get_name() not in all_read_names + ): + # Epilogue might directly read the MultiOutput, Localize MultiOutput to the local Buffer + # if this MultiOutput has not been stored by in-template epilogue + # otherwise, use the cse store cache if it will be stored before used + global_buffers.append(multi_output_buffers[gemm_idx]) + scope.add_local_buffer( + src[gemm_idx], + global_buffers, + ) + else: + scope.add_local_buffer(src[gemm_idx]) + localize_epilogue_nodes.extend( + [L.copy(dst[gemm_idx], src[gemm_idx]).data.data] + ) + reindexers.append(None) + output_names.append(dst[gemm_idx].get_name()) + final_offsets.append( + [sympy.S.Zero] * len(dst[gemm_idx].get_size()) + ) + res = self.store_grouped_gemm_pointwise_nodes( + dst, + localize_epilogue_nodes, + final_offsets, + reindexers, + output_names=output_names, + ) + for gemm_idx in range(gemm_num): + if ( + multi_output_buffers + and multi_output_buffers[gemm_idx].get_name() in all_read_names + ): + # If the MultiOutput is used in the Epilogue, let's remove it from args + multi_output_name = multi_output_buffers[gemm_idx].get_name() + if ( + multi_output_name in self.args.output_buffers + and self.args.output_buffers[multi_output_name] + is not REMOVED + ): + self.remove_buffer(multi_output_name) + return res + else: + if dst[0].get_name() != src[0].get_name(): + copy_list = [] + with LocalBufferContext(self.args) as scope: + for _src, _dst in zip(src, dst): + copy_list.extend([L.copy(_dst, _src).data.data]) + scope.add_local_buffer(_src) + output_names.append(_dst.get_name()) + final_offsets.append([sympy.S.Zero] * len(_dst.get_size())) + reindexers = [None] * len(copy_list) + return self.store_grouped_gemm_pointwise_nodes( + dst, + nodes=copy_list, + offsets=final_offsets, + reindexers=reindexers, + output_names=output_names, + ) + else: + if not all( + _src.get_name() == _dst.get_name() for _src, _dst in zip(src, dst) + ): + raise AssertionError("src and dst names must match") + if not all( + _src.get_layout() == _dst.get_layout() + for _src, _dst in zip(src, dst) + ): + raise AssertionError("src and dst layouts must match") + return "" + + def check_bounds(self, expr, size, lower, upper): + # CppTemplateKernel does not need codegen related operations + return + + +class CppTemplateCaller(ir.ChoiceCaller): + """ + CppTemplateCaller + + This class represents a caller for CPP template kernels. It is a subclass of ir.ChoiceCaller. + Attributes: + name (str): The name of the caller. + category (str): The category of the caller. + bmreq (CppBenchmarkRequest): The benchmark request for the caller. + template_buffer (ir.CppTemplateBuffer): The template buffer for the caller. + """ + + def __init__( + self, + name: str, + category: str, + input_nodes: list[ir.Buffer], + layout: ir.Layout, + make_kernel_render: Callable[ + [ + ir.CppTemplateBuffer, + bool, + list[ir.IRNode] | None, + ], + str, + ], + bmreq: CppBenchmarkRequest, + template: "CppTemplate", # type: ignore[name-defined] # noqa: F821 + info_kwargs: dict[str, ir.PrimitiveInfoType | list[ir.PrimitiveInfoType]] + | None = None, + ): + super().__init__(name, input_nodes, layout, description="") + self.category = category + self.make_kernel_render = make_kernel_render + self.bmreq = bmreq + self.template = template + self.info_kwargs = info_kwargs + + def precompile(self) -> None: + if self.bmreq is None: + raise AssertionError("bmreq must not be None") + self.bmreq.precompile() + + def benchmark(self, *args, out) -> float: + if self.bmreq is None: + raise AssertionError("bmreq must not be None") + if config.profile_bandwidth_with_do_bench_using_profiling: + algo = self.bmreq.make_run_fn(*args, out=out) + return do_bench_using_profiling(algo) + return self.bmreq.benchmark(*args, out=out) + + def hash_key(self) -> str: + return "-".join( + [ + self.category, + self.bmreq.hash_key, + ] + ) + + def info_dict( + self, + ) -> dict[str, ir.PrimitiveInfoType | list[ir.PrimitiveInfoType]]: + return {"backend": "CPP", "op_type": "unknown"} + + def output_node(self) -> ir.TensorBox: + buffer = ir.CppTemplateBuffer( + layout=self.layout, + inputs=self.input_nodes, + make_kernel_render=self.make_kernel_render, + template=self.template, + choice=self, + ) + # Pass KTC annotation to the buffer for encoding + if "ktc" in self.annotations: + buffer.annotations["ktc"] = self.annotations["ktc"] + return ir.TensorBox.create(buffer) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4c07b5df9472b171a239e2f64635a73297b9e12c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_utils.py @@ -0,0 +1,824 @@ +# mypy: allow-untyped-defs +import contextlib +import dataclasses +import functools +import math +import sys +from collections import namedtuple +from collections.abc import Callable, Sequence +from typing import Any +from unittest.mock import patch + +import sympy + +import torch +from torch._prims_common import is_integer_dtype +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.printers import CppPrinter as _CppPrinter +from torch.utils._sympy.symbol import symbol_is_type, SymT +from torch.utils._sympy.value_ranges import ValueRanges + +from .. import ir +from ..dependencies import Dep +from ..loop_body import LoopBody +from ..scheduler import BaseSchedulerNode, SchedulerBuffer +from ..shape_propagation import BlockShapeType +from ..utils import IndentedBuffer, sympy_index_symbol_with_prefix, sympy_subs +from ..virtualized import ops, OpsValue, V +from .common import CSEVariable, Kernel, KernelArgs, OptimizationContext + + +DTYPE_TO_CPP = { + torch.float32: "float", + torch.float64: "double", + torch.float16: "at::Half", + torch.int64: "int64_t", + torch.int32: "int32_t", + torch.int16: "int16_t", + torch.int8: "int8_t", + torch.uint64: "uint64_t", + torch.uint32: "uint32_t", + torch.uint16: "uint16_t", + torch.uint8: "uint8_t", + torch.bool: "bool", + torch.bfloat16: "at::BFloat16", + torch.complex32: "at::complex", + torch.bcomplex32: "at::complex", + torch.complex64: "at::complex", + torch.complex128: "at::complex", + torch.float8_e4m3fn: "at::Float8_e4m3fn", + torch.float8_e5m2: "at::Float8_e5m2", + torch.float8_e4m3fnuz: "at::Float8_e4m3fnuz", + torch.float8_e5m2fnuz: "at::Float8_e5m2fnuz", + torch.float8_e8m0fnu: "at::Float8_e8m0fnu", +} + +DTYPE_TO_ATEN = { + torch.float32: "at::kFloat", + torch.float64: "at::kDouble", + torch.float16: "at::kHalf", + torch.int64: "at::kLong", + torch.int32: "at::kInt", + torch.int16: "at::kShort", + torch.int8: "at::kChar", + torch.uint64: "at::kUInt64", + torch.uint32: "at::kUInt32", + torch.uint16: "at::kUInt16", + torch.uint8: "at::kByte", + torch.uint32: "at::kUInt32", + torch.uint64: "at::kUInt64", + torch.bool: "at::kBool", + torch.bfloat16: "at::kBFloat16", + torch.complex32: "at::kComplexHalf", + torch.bcomplex32: "at::kBComplex32", + torch.complex64: "at::kComplexFloat", + torch.complex128: "at::kComplexDouble", + torch.float8_e4m3fn: "at::kFloat8_e4m3fn", + torch.float8_e5m2: "at::kFloat8_e5m2", + torch.float8_e4m3fnuz: "at::kFloat8_e4m3fnuz", + torch.float8_e5m2fnuz: "at::kFloat8_e5m2fnuz", + torch.float8_e8m0fnu: "at::kFloat8_e8m0fnu", +} + +DEVICE_TO_ATEN = { + "meta": "at::kMeta", + "cpu": "at::kCPU", + "cuda": "at::kCUDA", + "xpu": "at::kXPU", + "mps": "at::kMPS", +} + +LAYOUT_TO_ATEN = { + torch.strided: "at::kStrided", + torch._mkldnn: "at::kMkldnn", # type: ignore[attr-defined] +} + +# matches c10/core/DeviceType.h +DEVICE_TO_INT = {"cpu": 0, "cuda": 1} + +_IS_WINDOWS = sys.platform == "win32" + +INDEX_TYPE = "int64_t" + +GemmBlocking = namedtuple("GemmBlocking", ["block_m", "block_n", "block_k"]) + + +def get_promote_dtype(args): + return ( + # pyrefly: ignore [no-matching-overload] + functools.reduce( + torch.promote_types, # type: ignore[arg-type] + # pyrefly: ignore [bad-argument-type] + [n.dtype for n in args if isinstance(n, CppCSEVariable)], + ) + if all(n.dtype is not None for n in args if isinstance(n, CppCSEVariable)) + else None # not enough info to calculate the promote dtype + ) + + +def promote_args(new_args): + def promote_arg(arg, promote_type): + if ( + isinstance(arg, CppCSEVariable) + and arg.dtype + and promote_type + and arg.dtype != promote_type + ): + arg = ops.to_dtype(arg, promote_type) + arg = arg.value if isinstance(arg, OpsValue) else arg + arg.dtype = promote_type + return arg + + promote_type = get_promote_dtype(new_args) + promote_fn = functools.partial( + promote_arg, + promote_type=promote_type, + ) + if ( + all( + new_arg.dtype is not None + for new_arg in new_args + if isinstance(new_arg, CppCSEVariable) + ) + and promote_type + ): + new_args = list(map(promote_fn, new_args)) + return new_args + + +class CppCSEVariable(CSEVariable): + def __init__( + self, + name, + bounds: ValueRanges[Any], + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ) -> None: + super().__init__(name, bounds, dtype, shape=shape) + self.is_vec = False + self.dependent_itervars = OrderedSet[sympy.Symbol]() + + def __repr__(self) -> str: + return ( + f"CppCSEVariable(name: {self.name}, bounds: {self.bounds}, is_vec: {self.is_vec}, dtype: {self.dtype}, " + f"dependent_itervars: {self.dependent_itervars})" + ) + + def update_on_args(self, name, args, kwargs): + if name == "load": + # args[2] is index + self._set_dependent_itervars(args[2]) + else: + # propagate relevant itervars and is_vec from args + self.dependent_itervars.update( + *[ + arg.dependent_itervars + for arg in args + if isinstance(arg, CppCSEVariable) + ] + ) + if name in ("index_expr", "value_expr"): + self._set_dependent_itervars(args[0]) + if any(arg.is_vec for arg in args if isinstance(arg, CppCSEVariable)): + self.is_vec = True + + def _set_dependent_itervars(self, index: sympy.Expr): + """ + Set the relevant itervars for this variable based on the `index` expression. + This includes the itervars directly used in the `index` as well as relevant itervars + of other cse variables used in the `index`. + """ + for s in index.free_symbols: + if s in V.kernel.itervars: + self.dependent_itervars.add(s) # type: ignore[arg-type] + elif s.name in V.kernel.cse.varname_map: # type: ignore[attr-defined] + self.dependent_itervars.update( + V.kernel.cse.varname_map[s.name].dependent_itervars # type: ignore[attr-defined] + ) + + def depends_on(self, itervar: sympy.Symbol): + return itervar in self.dependent_itervars + + +class CppPrinter(_CppPrinter): + def doprint(self, expr, *, simplify: bool = True, p=True): + # TODO: why are people passing strings to the printer here :think: + if simplify and isinstance(expr, sympy.Expr) and hasattr(V.graph, "sizevars"): + expr = V.graph.sizevars.simplify(expr) + return super().doprint(expr) + + def parenthesize(self, item: sympy.Expr, level: int, strict: bool = False) -> str: + if isinstance(item, sympy.Mod): + # use parenthesis to enforce precedence. + # in sympy 1.13.3, -2*Mod(x,y) becomes -2*x%y, which is wrong. + # pyrefly: ignore [missing-attribute] + return f"({self._print(item)})" + else: + return super().parenthesize(item, level, strict) + + +# A function to print, useful for printing sympy symbols. +cexpr = CppPrinter().doprint + + +def cexpr_index(index): + return f"static_cast<{INDEX_TYPE}>({cexpr(index)})" + + +def value_to_cpp(value, cpp_type): + if value == float("-inf"): + return f"-std::numeric_limits<{cpp_type}>::infinity()" + elif value == float("inf"): + return f"std::numeric_limits<{cpp_type}>::infinity()" + elif isinstance(value, bool): + return f"static_cast<{cpp_type}>({str(value).lower()})" + elif math.isnan(value): + return f"std::numeric_limits<{cpp_type}>::quiet_NaN()" + else: + return f"static_cast<{cpp_type}>({repr(value)})" + + +def rewrite_index_for_function( + localize_buffer_handler: "LocalizeBufferHandler", + index: sympy.Expr, + global_buf_name: str, +): + # Local buffer at the inner dimensions + snode = V.graph.scheduler.name_to_buf[global_buf_name].defining_op + if snode is None: + raise AssertionError(f"expected defining_op for {global_buf_name}, got None") + local_buf = localize_buffer_handler.global_to_local[global_buf_name] + scheduler_nodes = snode.get_nodes() + _, (group, reduction_group) = max( + scheduler_nodes, key=lambda x: int(x.is_reduction()) + ).group + call_ranges = tuple(group) + tuple(reduction_group) + indices_to_keep = [ + f"x{len(call_ranges) - (idx + 1)}" + for idx in range(len(local_buf.get_layout().size)) + ] + sorted_symbols = sorted(index.free_symbols, key=lambda s: s.name) # type: ignore[attr-defined] + replacements = {} + for x in sorted_symbols: + if x.name.startswith("x") and x.name not in indices_to_keep: # type: ignore[attr-defined] + # Only keep index used by local buffer + replacements[x] = sympy.core.numbers.Zero() + index = sympy_subs(index, replacements) # type: ignore[arg-type] + return index + + +def rewrite_index_for_nodes( + localize_buffer_handler: "LocalizeBufferHandler", + index: sympy.Expr, + global_buf_name: str, +): + used_vars = OrderedSet( + s for s in index.free_symbols if symbol_is_type(s, SymT.INDEX) + ) + index_vars = [] + local_buf = localize_buffer_handler.global_to_local[global_buf_name] + for i in range(len(local_buf.get_size())): + var = sympy_index_symbol_with_prefix(SymT.INDEX, i) + index_vars.append(var if var in used_vars else 0) + index = local_buf.get_layout().make_indexer()(index_vars) + return index + + +class LocalizeBufferHandler(V.WrapperHandler): # type: ignore[name-defined] + def __init__( + self, + inner, + global_to_local: dict[str, ir.Buffer], + rewrite_index: Callable[["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr], + ) -> None: + super().__init__(inner) + self.global_to_local = global_to_local + self.rewrite_index = rewrite_index + + def localize(self, name: str, index: sympy.Expr): + if self.global_to_local and name in self.global_to_local: + if self.rewrite_index is None: + raise AssertionError("expected rewrite_index to be set, got None") + index = self.rewrite_index(self, index, name) + name = self.global_to_local[name].get_name() + return name, index + + def load(self, name: str, index: sympy.Expr): + return self._inner.load(*self.localize(name, index)) + + def store(self, name, index, value, mode=None): + local_buffer_name, local_buffer_index = self.localize(name, index) + res = self._inner.store(local_buffer_name, local_buffer_index, value, mode) + if ( + self.global_to_local + and name in self.global_to_local + and isinstance(V.kernel, Kernel) + ): + # Remove name of local buffer from Kernel.store_buffer_names + # local_buffer_name is added to Kernel.store_buffer_names in Kernel.CSEProxy.store. + V.kernel.store_buffer_names.discard(local_buffer_name) + return res + + def store_reduction(self, name, index, value): + # pyrefly: ignore [bad-argument-count] + return self._inner.store_reduction(*self.localize(name, index), value) + + +class LocalBufferContext: + """ + This class creates a context that helps to generate code involving Inductor IR with + function local buffers. These buffers are constructed during the codegen process and + are used to store intermediate results such as local accumulators. We do not want to + add them to `V.graph` since they are not global and we do not want to add them as + function arguments either. So we patch the codegen processes under this scope to support + these buffers without exposure to the outside world. + """ + + def __init__(self, kernel_args: KernelArgs) -> None: + self.kernel_args = kernel_args + self.exit_stack = contextlib.ExitStack() + # map local buffer name to local buffer + self.local_buffers: dict[str, ir.Buffer] = {} + # map global buffer name to global buffer + self.global_buffers: dict[str, ir.Buffer] = {} + # map global buffer name to local buffer + self.global_to_local: dict[str, ir.Buffer] = {} + # record the global buffers that are removed by this LocalBufferContext + self.removed_buffers: OrderedSet[str] = OrderedSet() + + def __enter__(self): + self.exit_stack.__enter__() + original_get_dtype = V.graph.get_dtype + + def get_dtype(name): + if name in self.local_buffers: + return self.local_buffers[name].get_dtype() + return original_get_dtype(name) + + self.exit_stack.enter_context(patch.object(V.graph, "get_dtype", get_dtype)) + + original_input = self.kernel_args.input + + def input(name): + if name in self.local_buffers: + return name + return original_input(name) + + self.exit_stack.enter_context(patch.object(self.kernel_args, "input", input)) + + original_output = self.kernel_args.output + + def output(name): + if name in self.local_buffers: + return name + return original_output(name) + + self.exit_stack.enter_context(patch.object(self.kernel_args, "output", output)) + + # Set current LocalBufferContext into V + self.exit_stack.enter_context(V.set_local_buffer_context(self)) + + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.local_buffers.clear() + self.exit_stack.__exit__(exc_type, exc_val, exc_tb) + + def add_local_buffer( + self, local_buffer: ir.Buffer, global_buffers: list[ir.Buffer] | None = None + ): + if local_buffer.get_name() in self.local_buffers: + raise AssertionError( + f"local buffer {local_buffer.get_name()} already registered" + ) + self.local_buffers[local_buffer.get_name()] = local_buffer + if global_buffers: + for global_buffer in global_buffers: + global_buffer_name = global_buffer.get_name() + if not ( + global_buffer_name not in self.global_buffers + and global_buffer_name not in self.global_to_local + ): + raise AssertionError( + f"global buffer {global_buffer_name} already registered" + ) + self.global_buffers[global_buffer_name] = global_buffer + self.global_to_local[global_buffer_name] = local_buffer + if global_buffer_name not in V.graph.removed_buffers: + # Record the global buffers that are removed by this LocalBufferContext + # since they may need to be restored. Refer to issue: + # https://github.com/pytorch/pytorch/issues/144186 + self.removed_buffers.add(global_buffer_name) + V.graph.removed_buffers.add(global_buffer_name) + + def localize_function( + self, + fn: Callable[..., Any], + rewrite_index: Callable[ + ["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr + ] = rewrite_index_for_function, + ): + def inner(*args, **kwargs): + with V.set_ops_handler( + LocalizeBufferHandler( + V.get_ops_handler(), + global_to_local=self.global_to_local, + rewrite_index=rewrite_index, + ) + ): + return fn(*args, **kwargs) + + return inner + + def localize_nodes( + self, + nodes: list[ir.IRNode], + rewrite_index: Callable[ + ["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr + ] = rewrite_index_for_nodes, + ) -> list[ir.IRNode]: + """ + Given `local_buf` and `global_buf` registered in current `LocalBufferContext` + though the method of `add_local_buffer`, localizes the `global_buf` to `local_buf` + for the given `nodes` and returns a new list of IR nodes that work on `local_buf` + instead of `global_buf`, i.e., all the loads and stores are redirected to + `local_buf`. This helps the fused loops to work on smaller-sized local buffers + for better data locality. + + The data access of `local_buf` is assumed to be contiguous with the + same order as the `global_buf`. + """ + if len(nodes) <= 0: + raise AssertionError(f"expected non-empty nodes, got {len(nodes)}") + + def wrap_inner_fn_for_node(node: ir.IRNode): + loops = node.data if isinstance(node, ir.ComputedBuffer) else node + if not isinstance(loops, ir.Loops): + raise AssertionError(f"expected ir.Loops, got {type(loops)}") + new_inner_fn = self.localize_function( + loops.inner_fn, + rewrite_index, + ) + + new_loops = dataclasses.replace(loops, inner_fn=new_inner_fn) + if isinstance(node, ir.ComputedBuffer): + new_node = ir.ComputedBuffer( + name=node.get_name(), layout=node.get_layout(), data=new_loops + ) + else: + new_node = new_loops # type: ignore[assignment] + + return new_node + + return [wrap_inner_fn_for_node(node) for node in nodes] + + +def unify_mask_base_type( + buffer: IndentedBuffer, + vars: tuple[CSEVariable, ...], + dtype=torch.float, +): + """ + Given list of cse variables, + Cast each to new mask base dtype and return casted cse variable. + """ + new_vars = ( + V.kernel.cse.generate( + buffer, + f"{V.kernel._get_mask_cast(var, dtype)}", + ) + for var in vars + ) + return new_vars + + +def may_unify_binary_op_mask_type(a, b): + """ + Given two cse variables, when dtype is bool, unify them to the same mask dtype and return casted cse variable. + """ + if a.dtype == torch.bool: + if b.dtype != torch.bool: + raise AssertionError(f"expected b.dtype == torch.bool, got {b.dtype}") + mask_dtype = torch.int32 + return unify_mask_base_type(V.kernel.compute, (a, b), mask_dtype) + return a, b + + +def codegen_rand(offset, code, rand_function, dst_dtype=torch.float32): + if not is_integer_dtype(offset.dtype): + raise AssertionError(f"expected integer dtype, got {offset.dtype}") + code.writeline("[&]()") + with code.indent(): + code.writeline( + f"{DTYPE_TO_CPP[offset.dtype]} offset[{V.kernel.tiling_factor}];" + ) + code.writeline(f"{DTYPE_TO_CPP[dst_dtype]} result[{V.kernel.tiling_factor}];") + code.writeline(f"{offset}.store(offset);") + code.writeline( + f"for( {DTYPE_TO_CPP[offset.dtype]} offset_idx = 0; offset_idx < {V.kernel.tiling_factor}; offset_idx++ )" + ) + with code.indent(): + code.writeline(rand_function) + num_vectors = V.kernel._get_num_vectors(dtype=dst_dtype) + if num_vectors == 1: + code.writeline( + f"return at::vec::Vectorized<{DTYPE_TO_CPP[dst_dtype]}>::loadu(result);" + ) + else: + code.writeline( + f"return at::vec::VectorizedN<{DTYPE_TO_CPP[dst_dtype]}, {num_vectors}>::loadu(result);" + ) + code.writeline("()") + return code + + +def get_gemm_template_output_and_compute_dtype(input_dtype): + if input_dtype in [torch.uint8, torch.int8]: + return (torch.int32, torch.int32) + else: + return (torch.float32, torch.float32) + + +def create_epilogue_with_attr(input_buffer, attr, **kwargs): + input_loader = input_buffer.make_loader() + dtype = input_buffer.get_dtype() + if attr == "relu": + + def inner_fn(index): + input = input_loader(index) + zero = ops.constant(0, dtype) + return ops.maximum(input, zero) + + elif attr == "gelu": + if "algorithm" not in kwargs: + raise AssertionError("expected 'algorithm' in kwargs") + if kwargs["algorithm"] == "none": + + def inner_fn(index): + input = input_loader(index) + if dtype != torch.float: + input = ops.to_dtype(input, torch.float) + half = ops.constant(0.5, torch.float) + one = ops.constant(1.0, torch.float) + const = ops.constant(0.7071067811865476, torch.float) + result = input * half * (ops.erf(input * const) + one) + if dtype != torch.float: + result = ops.to_dtype(result, dtype) + return result + + else: + if kwargs["algorithm"] != "tanh": + raise AssertionError( + f"expected algorithm == 'tanh', got {kwargs['algorithm']}" + ) + + def inner_fn(index): + input = input_loader(index) + if dtype != torch.float: + input = ops.to_dtype(input, torch.float) + half = ops.constant(0.5, torch.float) + one = ops.constant(1.0, torch.float) + const1 = ops.constant(0.7978845608028654, torch.float) + const2 = ops.constant(0.044715, torch.float) + result = ( + half + * input + * ( + one + + ops.tanh(const1 * (input + const2 * input * input * input)) + ) + ) + if dtype != torch.float: + result = ops.to_dtype(result, dtype) + return result + + elif attr == "swish": + + def inner_fn(index): + input = input_loader(index) + result = input * ops.sigmoid(input) + return result + + elif attr == "sigmoid": + + def inner_fn(index): + return ops.sigmoid(input_loader(index)) + + elif attr == "tanh": + + def inner_fn(index): + return ops.tanh(input_loader(index)) + + elif attr == "hardswish" or attr == "hardsigmoid": + + def hardsigmoid_float(input): + zero = ops.constant(0, torch.float) + six = ops.constant(6, torch.float) + three = ops.constant(3, torch.float) + one_over_six = ops.constant(0.16666666666666666, torch.float) + max = ops.maximum(input + three, zero) + min = ops.minimum(max, six) + return min * one_over_six + + def inner_fn(index): + input = input_loader(index) + if dtype != torch.float: + input = ops.to_dtype(input, torch.float) + result = hardsigmoid_float(input) + if attr == "hardswish": + result = input * result + if dtype != torch.float: + result = ops.to_dtype(result, dtype) + return result + + elif attr == "leaky_relu": + if "scalars" not in kwargs: + raise AssertionError("expected 'scalars' in kwargs") + if len(kwargs["scalars"]) != 1: + raise AssertionError(f"expected 1 scalar, got {len(kwargs['scalars'])}") + negative_slope = kwargs["scalars"][0] + + def inner_fn(index): + input = input_loader(index) + if dtype != torch.float: + input = ops.to_dtype(input, torch.float) + zero = ops.constant(0, torch.float) + result = ops.where( + input > zero, input, input * ops.constant(negative_slope, torch.float) + ) + if dtype != torch.float: + result = ops.to_dtype(result, dtype) + return result + + elif attr == "hardtanh": + if "scalars" not in kwargs: + raise AssertionError("expected 'scalars' in kwargs") + if len(kwargs["scalars"]) != 2: + raise AssertionError(f"expected 2 scalars, got {len(kwargs['scalars'])}") + min_value = kwargs["scalars"][0] + max_value = kwargs["scalars"][1] + + def inner_fn(index): + input = input_loader(index) + if dtype != torch.float: + input = ops.to_dtype(input, torch.float) + result = ops.minimum( + ops.maximum(input, ops.constant(min_value, torch.float)), + ops.constant(max_value, torch.float), + ) + if dtype != torch.float: + result = ops.to_dtype(result, dtype) + return result + + elif attr in ["add", "sub", "mul"]: + if "other" not in kwargs: + raise AssertionError("expected 'other' in kwargs") + other = kwargs["other"] + num_input_dims = len(input_buffer.get_size()) + num_other_dims = len(other.get_size()) + dims_diff = num_input_dims - num_other_dims + other_loader = other.make_loader() + + def inner_fn(index): + op = getattr(ops, attr) + if dims_diff != 0: + return op(input_loader(index), other_loader(index[dims_diff:])) + else: + return op(input_loader(index), other_loader(index)) + + elif attr == "bias_add": + if "other" not in kwargs: + raise AssertionError("expected 'other' in kwargs") + if "beta" not in kwargs: + raise AssertionError("expected 'beta' in kwargs") + if "dtype" not in kwargs: + raise AssertionError("expected 'dtype' in kwargs") + beta = kwargs["beta"] + other = kwargs["other"] + dtype = kwargs["dtype"] + bias_loader = other.make_loader() + + def inner_fn(index): + bias = bias_loader(index) + input = input_loader(index) + if beta != 1: + result = ops.constant(beta, torch.float) * bias + input + else: + result = bias + input + return result + + else: + raise ValueError(f"Unsupported epilogue attribute: {attr}") + return ir.Pointwise( + device=input_buffer.get_device(), + dtype=dtype, + inner_fn=inner_fn, + ranges=input_buffer.get_size(), + ) + + +def _get_loop_body(fn_list): + if all(isinstance(fn, LoopBody) for fn in fn_list): + loop_bodies = fn_list + else: + if hasattr(fn_list[0], "original_fn"): + # For the case of local buffer, we wrap the fn with localize_function + if not all(hasattr(fn, "original_fn") for fn in fn_list): + raise AssertionError("expected all fns to have 'original_fn'") + if not all( + isinstance(fn.original_fn.args[0]._body, LoopBody) for fn in fn_list + ): + raise AssertionError("expected all original_fn bodies to be LoopBody") + loop_bodies = [fn.original_fn.args[0]._body for fn in fn_list] + else: + if not all(isinstance(fn, functools.partial) for fn in fn_list): + raise AssertionError("expected all fns to be functools.partial") + if not all(isinstance(fn.args[0]._body, LoopBody) for fn in fn_list): + raise AssertionError("expected all fn bodies to be LoopBody") + loop_bodies = [fn.args[0]._body for fn in fn_list] + if loop_bodies is None: + raise AssertionError("expected loop_bodies to be set, got None") + return loop_bodies + + +def _get_dtype_from_loopbodies(loop_bodies): + dtypes = OrderedSet[torch.dtype]() + for loop_body in loop_bodies: + graphs = [loop_body.root_block.graph] + [ + body.graph for body in list(loop_body.subblocks.values()) + ] + for graph in graphs: + for node in graph.nodes: + if node.op != "call_method": + continue + dtypes.add(node.meta[OptimizationContext.key].dtype) + return dtypes + + +def template_fusion_with_epilogues_supported( + template: BaseSchedulerNode, epilogues: list[BaseSchedulerNode] +) -> tuple[bool, bool]: + def _get_indexes_of_template_buf_read( + epilogue_node: ir.Operation, template_buf_names: list[str] + ) -> list[sympy.Expr]: + return [ + read.index + for read in epilogue_node.get_reads() + if read.name in template_buf_names + ] + + def _check_supported_and_same_indexes( + index_of_template_buf_read: Sequence[sympy.Expr], + epilogue_writes: OrderedSet[Dep], + ) -> tuple[bool, bool]: + num_indexes = len(OrderedSet(index_of_template_buf_read)) + + if num_indexes > 1: + same_index = False + supported = False # Different read indexes not supported + elif num_indexes == 0: + same_index = True + supported = True # No reads, automatically supported + elif num_indexes == 1: + iotbr = index_of_template_buf_read[0] + same_index = all(write.index == iotbr for write in epilogue_writes) + # TODO: Add support of fusion when the read of template buffer and the write of epilogue output + # in the epilogue node don't have the same index and change supported to True + supported = same_index + else: + raise AssertionError("Should not reach here") + + return supported, same_index + + def _template_fusion_supported( + template_outputs: Sequence[SchedulerBuffer], epilogue_nodes: list[ir.Operation] + ) -> tuple[bool, bool]: + template_buf_names = [x.get_name() for x in template_outputs] + indexes_of_template_buf_reads = [ + _get_indexes_of_template_buf_read(epilogue_node, template_buf_names) + for epilogue_node in epilogue_nodes + ] + epilogue_nodes_writes = [ + epilogue_node.get_read_writes().writes for epilogue_node in epilogue_nodes + ] + + results = [ + _check_supported_and_same_indexes(reads, writes) + for reads, writes in zip( + indexes_of_template_buf_reads, epilogue_nodes_writes + ) + ] + supported, same_indexes = zip(*results) + return all(supported), all(same_indexes) + + if not template.is_template(): + raise AssertionError("expected template.is_template() to be True") + template_outputs = template.get_outputs() + + epilogue_nodes = [ + n.node + for epilogue in epilogues + for n in epilogue.get_nodes() + if n.node is not None + ] + return _template_fusion_supported(template_outputs, epilogue_nodes) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..37fbcbbbf4f81b07e2be29fb280a38f8b18712da --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu.py @@ -0,0 +1,4360 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import contextlib +import ctypes +import dataclasses +import functools +import math +import os +import sys +import textwrap +from itertools import chain, count +from typing import Any, Literal, TYPE_CHECKING + +import sympy + +import torch +import torch._higher_order_ops.torchbind +import torch._inductor.async_compile +import torch._ops +from torch import dtype as torch_dtype +from torch._inductor.runtime.runtime_utils import dynamo_timed +from torch.fx.experimental.symbolic_shapes import ConvertIntKey, DivideByKey, SymTypes +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import CleanDiv, FloorDiv, Mod, ModularIndexing +from torch.utils._sympy.symbol import symbol_is_type, SymT + +from .. import config, ir +from ..ir import ExternKernel +from ..utils import ( + _align, + AotOnlyBuffer, + DualIndentedBuffer, + make_codegen_buffer, + normalize_name, +) +from ..virtualized import V +from .aoti_hipify_utils import maybe_hipify_code_wrapper +from .common import get_device_op_overrides, IndentedBuffer, Kernel +from .cpp_utils import ( + cexpr, + DEVICE_TO_ATEN, + DEVICE_TO_INT, + DTYPE_TO_ATEN, + DTYPE_TO_CPP, + LAYOUT_TO_ATEN, +) +from .wrapper import ( + _rewrite_symbol_solution_for_int_codegen, + codegen_reinterpret_view_helper, + EnterSubgraphLine, + ExitSubgraphLine, + HasWriteLine, + PythonWrapperCodegen, + SymbolicCallArg, + WrapperLine, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from ..graph import GraphLowering + from ..runtime.hints import TritonMeta + + # At most, the list nesting can go one layer deep. + _OUTPUT_ARGS_TYPE = list[str | None | list[str | None]] + + from ..scheduler import BaseSchedulerNode + + +@dataclasses.dataclass +class DualWrapperCodeLine(WrapperLine): + jit_code: IndentedBuffer + aot_code: AotOnlyBuffer + + def codegen(self, code: DualIndentedBuffer) -> None: + # In dual-wrapper replay, these route each captured snippet to the + # matching side. If replayed on a plain IndentedBuffer, splice_jit writes + # normally and splice_aot is a no-op, preserving the same selection. + code.splice_jit(self.jit_code) + code.splice_aot(self.aot_code) + + +@dataclasses.dataclass +class DeferredCpuTritonCallWrapper: + """CPU counterpart of DeferredTritonCallWrapper in cpp_wrapper_gpu.py. + + Deferred so wrapper emission can read `CpuTritonKernelCache` entries + after the autotune block has populated them. + + NOTE: CPU doesn't actively use autotuning, but we mirror + the GPU flow for symmetry. + """ + + wrapper_name: str + kernel_name: str + arg_types: list[Any] + triton_meta: TritonMeta | None = None + inductor_meta: dict[str, Any] | None = None + + def _get_cpp_param_type(self, name: str, arg_type: Any) -> str: + if isinstance(arg_type, torch_dtype): + return f"const {name}_type_& {name}" + elif issubclass(arg_type, (SymbolicCallArg, sympy.Expr, int)): + return f"int64_t {name}" + elif arg_type is float: + return f"float {name}" + elif arg_type is bool: + return f"bool {name}" + else: + raise ValueError( + f"Unexpected arg type {arg_type} for CPU triton wrapper arg '{name}'" + ) + + def _resolve_arg_names( + self, + ) -> tuple[list[str], list[str], list[str]]: + """Return (wrapper_arg_names, kernel_arg_names, grid_arg_names). + + Wrapper args exclude *declared* constexpr (the call site doesn't pass + them); kernel args additionally exclude *value-specialized* constexpr + (baked into the binary). Grid args are appended for `run_from_nativert`. + """ + from torch._inductor.codecache import CpuTritonKernelCache + + info = CpuTritonKernelCache.get(self.kernel_name) + if info is None: + raise AssertionError( + f"CpuTritonKernelCache not populated for {self.kernel_name}" + ) + signature = info["signature"] + declared_constexpr_names = OrderedSet( + (self.inductor_meta or {}).get("declared_constexpr_names", []) + ) + wrapper_arg_names = [ + name for name in signature if name not in declared_constexpr_names + ] + kernel_arg_names = [name for name, ty in signature.items() if ty != "constexpr"] + grid_arg_names = list((self.inductor_meta or {}).get("extra_launcher_args", [])) + return wrapper_arg_names + grid_arg_names, kernel_arg_names, grid_arg_names + + def _write_wrapper_signature( + self, + prefix: IndentedBuffer, + wrapper_arg_names: list[str], + ) -> None: + # `cubin_dir_` name reused from GPU so the same AOTI runtime member feeds both. + if len(wrapper_arg_names) != len(self.arg_types): + raise AssertionError( + ( + wrapper_arg_names, + self.arg_types, + ) + ) + template_types = [ + f"typename {name}_type_" + for name, arg_type in zip(wrapper_arg_names, self.arg_types) + if isinstance(arg_type, torch_dtype) + ] + if V.graph.aot_mode: + template_types.append("typename kernels_type_") + if template_types: + prefix.writeline(f"template <{', '.join(template_types)}>") + + param_lines = [ + self._get_cpp_param_type(name, arg_type) + for name, arg_type in zip(wrapper_arg_names, self.arg_types) + ] + if V.graph.aot_mode: + param_lines.append("kernels_type_& kernels_") + param_lines.append( + "const std::optional& cubin_dir_ = std::nullopt" + ) + + prefix.writeline(f"static __attribute__((noinline)) void {self.wrapper_name}(") + with prefix.indent(): + for i, param in enumerate(param_lines): + comma = "," if i < len(param_lines) - 1 else "" + prefix.writeline(f"{param}{comma}") + prefix.writeline("){") + + def _generate_load_kernel( + self, + prefix: IndentedBuffer, + kernel_so: str, + launcher_so: str, + kernel_symbol: str, + ) -> None: + # `std::call_once` keeps init thread-safe under concurrent first calls. + kernel_member = f"kernels_.{self.kernel_name}_kernel_fn" + launcher_member = f"kernels_.{self.kernel_name}_launcher_fn" + prefix.splice(f""" + using namespace torch::aot_inductor; + static std::once_flag {self.kernel_name}_init_flag; + std::call_once({self.kernel_name}_init_flag, [&]() {{ + {kernel_member} = loadCpuTritonKernel( + "{kernel_so}", "{kernel_symbol}", cubin_dir_); + {launcher_member} = loadCpuTritonLauncher( + "{launcher_so}", cubin_dir_); + }}); + """) + + def _generate_launch( + self, + prefix: IndentedBuffer, + kernel_arg_names: list[str], + grid_arg_names: list[str], + signature: dict[str, Any], + ) -> None: + # The launcher uses literal `args[i]` indices over the *original* + # signature, so constexpr slots must be padded (nullptr) to keep + # non-constexpr args at the expected positions. + kernel_member = f"kernels_.{self.kernel_name}_kernel_fn" + launcher_member = f"kernels_.{self.kernel_name}_launcher_fn" + + args_array_entries: list[str] = [] + for name, ty in signature.items(): + if ty == "constexpr": + args_array_entries.append("nullptr") + elif isinstance(ty, str) and ty.startswith("*"): + args_array_entries.append(f"{name}.data_ptr()") + else: + args_array_entries.append(f"&{name}") + args_arr_str = ", ".join(args_array_entries) + + # Grid args are int64_t in the wrapper but the launcher ABI is uint32_t. + grid_x = grid_arg_names[0] if len(grid_arg_names) > 0 else "1" + grid_y = grid_arg_names[1] if len(grid_arg_names) > 1 else "1" + grid_z = grid_arg_names[2] if len(grid_arg_names) > 2 else "1" + + # TODO: thread `num_cpu_threads` from inductor_meta (autotune support). + prefix.splice(f""" + void* args_arr[] = {{ {args_arr_str} }}; + {launcher_member}( + static_cast({grid_x}), + static_cast({grid_y}), + static_cast({grid_z}), + /*num_cpu_threads=*/1, + args_arr, + {kernel_member}); + """) + + def generate(self, wrapper: CppWrapperCpu) -> None: + from torch._inductor.codecache import CpuTritonKernelCache + + info = CpuTritonKernelCache.get(self.kernel_name) + if info is None: + raise RuntimeError( + f"CpuTritonKernelCache not populated for '{self.kernel_name}': " + "the autotune block did not save this kernel. Check that " + "config.triton.autotune_at_compile_time is True and the Triton " + "CPU backend emits a launcher .so exporting `run_from_nativert`." + ) + + signature = info["signature"] + wrapper_arg_names, kernel_arg_names, grid_arg_names = self._resolve_arg_names() + + prefix = wrapper.prefix + self._write_wrapper_signature(prefix, wrapper_arg_names) + with prefix.indent(): + self._generate_load_kernel( + prefix, + info["kernel_so_path"], + info["launcher_so_path"], + info["kernel_symbol"], + ) + self._generate_launch(prefix, kernel_arg_names, grid_arg_names, signature) + prefix.writeline("}") + + # Register .so artifacts so the AOTI packager picks them up. + V.graph.wrapper_code.additional_files.append(info["kernel_so_path"]) + V.graph.wrapper_code.additional_files.append(info["launcher_so_path"]) + + +class CppWrapperCpu(PythonWrapperCodegen): + """ + Generates cpp wrapper for running on CPU and calls cpp kernels + """ + + def __init__(self): + if not hasattr(self, "device"): + self.device = "cpu" + # must be initialized prior to calling super().__init__() + self.included_devices: OrderedSet[str] = OrderedSet() + self.model_class_name_suffix = ( + "" + if config.aot_inductor.dynamic_linkage + else config.aot_inductor.model_name_for_generated_files + ) + self.aoti_model_class_name = f"AOTInductorModel{self.model_class_name_suffix}" + + super().__init__() + + self.declare = "auto " + self.declare_maybe_reference = "decltype(auto) " + self.ending = ";" + self.comment = "//" + self.none_str = "nullptr" + self.supports_intermediate_hooks = False + self.kernel_callsite_id = count() + self.int_array_id = count() # for int array local variable declarations + self.declared_int_array_vars: OrderedSet[str] = OrderedSet() + self.tmp_tensor_id = count() # for tmp tensor local variable declarations + self.arg_var_id = count() + self._aot_output: str | None = None + # Defined kernels drive member declarations; called kernels drive + # `call_` emission. A kernel may be defined without being called. + self._cpu_triton_kernel_names: OrderedSet[str] = OrderedSet() + self._cpu_triton_call_wrappers: dict[str, DeferredCpuTritonCallWrapper] = {} + self.used_cached_devices: OrderedSet[str] = OrderedSet() + self.used_cached_dtypes: OrderedSet[str] = OrderedSet() + self.used_cached_layouts: OrderedSet[str] = OrderedSet() + self.used_cached_memory_formats: OrderedSet[str] = OrderedSet() + self.used_switch_selector: OrderedSet[str] = OrderedSet() + self.cached_output_id = count() + self.scalar_to_tensor_id = count() + self.custom_op_wrapper_loaded = False + # For GEMM kernels that must be initialized and are resolved at linking. + self.initialized_kernels: dict[str, Kernel] = {} + self.device_codegen = get_device_op_overrides(self.device) + self._included_extra_headers: OrderedSet[str] = OrderedSet() + self.codegen_int_array_var_cache = {} + self.needs_vec_isa = self.device == "cpu" + + @contextlib.contextmanager + def _preserve_device_guard_state(self): + last_seen_device_guard_index = self.last_seen_device_guard_index + try: + yield + finally: + self.last_seen_device_guard_index = last_seen_device_guard_index + + @contextlib.contextmanager + def _preserve_codegen_state(self, graphs): + wrapper_state = ( + OrderedSet(self.allocated), + OrderedSet(self.freed), + dict(self.reuses), + dict(self.allocated_workspaces), + OrderedSet(self.declared_int_array_vars), + dict(self.codegen_int_array_var_cache), + OrderedSet(self.kernel_numel_expr), + OrderedSet(self.used_switch_selector), + ) + subgraph_state = [ + ( + graph, + OrderedSet(graph.removed_buffers), + OrderedSet(graph.inplaced_to_remove), + ) + for graph in graphs + ] + try: + yield + finally: + ( + self.allocated, + self.freed, + self.reuses, + self.allocated_workspaces, + self.declared_int_array_vars, + self.codegen_int_array_var_cache, + self.kernel_numel_expr, + self.used_switch_selector, + ) = wrapper_state + for graph, removed_buffers, inplaced_to_remove in subgraph_state: + graph.removed_buffers = removed_buffers + graph.inplaced_to_remove = inplaced_to_remove + + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: ir.GraphPartitionSignature | None = None, + ): + # TODO - support subgraph codegen by lifting functions. Check the + # comment at CppWrapperCpu `codegen_subgraph` function. + return CppWrapperCpu() + + @contextlib.contextmanager + def _target_buf(self, attr: str, buf: IndentedBuffer): + """Temporarily redirect self. to a specific buffer.""" + saved = getattr(self, attr) + setattr(self, attr, buf) + try: + yield + finally: + setattr(self, attr, saved) + + @staticmethod + def _generate_temporary_array_pointer( + c_type: str, elements: Sequence[str], *, force_mutable: bool = False + ) -> str: + """Get a pointer to an array that only exists for the duration of the C++ + statement it's used in.""" + # If the c_type is already a pointer, return a mutable pointer to the array. + # Otherwise, return a const pointer. In the C-shim API, pointer types are only + # const-qualified with respect to the underlying value, not any nested pointers. + # e.g. const double** is possible, but not const double* const*. This means + # that an array containing pointers must _already_ be properly const-qualified + # by the c_type, and not add additional const-ness. + array_expr = f"std::array<{c_type}, {len(elements)}>{{{', '.join(elements)}}}" + if force_mutable or c_type.endswith("*"): + return f"{array_expr}.data()" + + return f"static_cast({array_expr}.data())" + + def _generate_kernel_call_helper( + self, + kernel_name: str, + call_args, + *, + device=None, + triton=True, + arg_types=None, + raw_keys=None, + raw_args=None, + triton_meta: TritonMeta | None = None, + inductor_meta=None, + graph_name="", + original_fxnode_name=None, + current_stream_idx=None, + ): + """ + Generates kernel call code. + + triton: Defines whether the GPU backend uses Triton for codegen. + Otherwise it uses the CUDA language for codegen. + Only valid when cuda == True. + """ + if not (arg_types is not None and len(call_args) == len(arg_types)): + raise AssertionError( + "Mismatch call_args and arg_types in generate_kernel_call:\n" + f"call_args: {call_args}\n" + f"arg_types: {arg_types}" + ) + + # CPU Triton kernel: run the autotune block (populates + # `CpuTritonKernelCache`) and emit `call_(...)`; the body is + # defined later by `DeferredCpuTritonCallWrapper` in `finalize_prefix`. + if triton and kernel_name in self._cpu_triton_kernel_names: + if ( + config.triton.autotune_at_compile_time + and kernel_name not in self.kernel_autotune_names + ): + PythonWrapperCodegen._generate_kernel_call_helper( + self, + kernel_name, + call_args, + device=device, + triton=triton, + arg_types=arg_types, + raw_keys=raw_keys, + raw_args=raw_args, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + original_fxnode_name=original_fxnode_name, + ) + + wrapper_name = f"call_{kernel_name}" + if wrapper_name not in self._cpu_triton_call_wrappers: + self._cpu_triton_call_wrappers[wrapper_name] = ( + DeferredCpuTritonCallWrapper( + wrapper_name=wrapper_name, + kernel_name=kernel_name, + arg_types=list(arg_types), + triton_meta=triton_meta, + inductor_meta=inductor_meta, + ) + ) + + stringified_args = [ + self._stringify_cpu_triton_call_arg(a) for a in call_args + ] + if V.graph.aot_mode: + stringified_args.append("kernels") + stringified_args.append("this->cubin_dir_") + self.writeline(self.wrap_kernel_call(wrapper_name, stringified_args)) + return + + new_args = [] + for idx, arg in enumerate(call_args): + if isinstance(arg_types[idx], str) and "*" in arg_types[idx]: + new_args.append(f"({arg_types[idx]})({arg}.data_ptr())") + else: + # arg is a scalar - ensure it's a string for C++ codegen + # With Triton support, arg might be a SymPy expression or other type + new_args.append(str(arg) if not isinstance(arg, str) else arg) + # debug printer related logic for cpp kernel type. + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + call_args, + kernel_name, + None, + None, + "cpp", + ) + with debug_printer_manager: + self.writeline(self.wrap_kernel_call(kernel_name, new_args)) + + def write_constant(self, name, hashed): + # include a hash so our code cache gives different constants different files + self.header.writeline(f"// {name} {hashed}") + + @staticmethod + def get_device_include_path_jit(device: str) -> str: + return f"#include " + + @staticmethod + def get_device_include_path_aot(device: str) -> str: + return f"#include " + + def add_device_include(self, device: str) -> None: + if device in self.included_devices: + return + + self.included_devices.add(device) + + # Add the default header for this device, plus any C-shim extensions that are + # present. + self.header.splice_jit(self.get_device_include_path_jit(device)) + self.header.splice_aot(self.get_device_include_path_aot(device)) + extend_aoti_c_shim_include = ( + f"torch/csrc/inductor/aoti_torch/generated/extend/c_shim_{self.device}.h" + ) + extend_aoti_c_shim_path = os.path.join( + os.path.dirname(torch.__file__), + "include", + extend_aoti_c_shim_include, + ) + if os.path.exists(extend_aoti_c_shim_path): + self.header.splice(f"#include <{extend_aoti_c_shim_include}>") + + def _write_aoti_interface_header(self): + """Emit the AOTI runtime interface include or inline.""" + if config.aot_inductor.dynamic_linkage: + with open( + os.path.join(os.path.dirname(__file__), "aoti_runtime", "interface.cpp") + ) as f: + self.header.splice_aot(f.read()) + else: + # we produce a separate model header for each model in static linkage + self.header.splice_aot(f"""#include \"{self.model_class_name_suffix}.h\"""") + self.header.splice_aot("\n") + + def write_header(self): + if V.graph.is_const_graph: + # We do not write header for constant graph, it will be written by main module. + return + + if not V.graph.aot_mode: + self.header.splice(''' + import torch + from torch._inductor.codecache import CppWrapperCodeCache + + cpp_wrapper_src = ( + r""" + ''') + + for device in V.graph.device_types: + if device != "meta": + self.add_device_include(device) + if not self.included_devices: + # When only meta device is present, add_device_include is never + # called so we need to pull in the common header explicitly. + if V.graph.aot_mode: + self.header.writeline( + "#include " + ) + else: + self.header.writeline( + "#include " + ) + + if V.graph.aot_mode: + self._write_aoti_interface_header() + + if config.cpp.enable_kernel_profile and config.cpp.enable_kernel_context_guard: + self.header.splice( + "#include " + ) + self.header.splice(""" + namespace torch::aot_inductor { + thread_local KernelContext* tls_kernel_context = nullptr; + } + """) + + def include_extra_header(self, header: str): + # This is needed for cpp to python dtype conversion + if header in self._included_extra_headers: + return + self._included_extra_headers.add(header) + self.header.splice(f"#include <{header}>") + + def mark_output_type(self): + # mark output type to unwrap tensor back to python scalar + from ..ir import ShapeAsConstantBuffer + + output_is_tensor = {} + for idx, x in enumerate(V.graph.graph_outputs): + if isinstance(x, ShapeAsConstantBuffer): + output_is_tensor[idx] = False + else: + output_is_tensor[idx] = True + + self.output_is_tensor = output_is_tensor + + def write_prefix(self): + if V.graph.is_const_graph: + # We do not write prefix for constant graph, it will be written by main module. + return + if config.aot_inductor.custom_ops_to_c_shims: + # custom_ops_to_c_shims contains declaration of custom ops with C shim. + # TODO: this could be auto-generated from a passed-in custom op schema + custom_c_shims = list( + chain(*config.aot_inductor.custom_ops_to_c_shims.values()) + ) + declarations = "\n".join( + [f"extern {textwrap.dedent(shim)};" for shim in custom_c_shims] + ) + self.prefix.splice(f""" + extern "C" {{ + {declarations} + }} + """) + self.prefix.writeline_aot("namespace torch::aot_inductor {") + if not V.graph.is_const_graph: + self.codegen_input_size_and_nan_asserts() + + def write_input_output_info( + self, + info_kind: str, + idx: int, + name: str, + ): + self.prefix.writeline(f"""{info_kind}[{idx}].name = "{name}";""") + + def codegen_input_symbol_assignment( # type: ignore[override] + self, + name: str, + value: ir.TensorBox, + bound_vars: OrderedSet[sympy.Symbol], + deferred_symbol_assignments=None, + ): + """Assign symbolic shapes to C++ locals, with replacement aliases.""" + code = self.prefix + + @functools.cache + def sizeof(name): + self.codegen_input_size_var_decl(code, name) + return f"{name}_size" + + @functools.cache + def strideof(name): + self.codegen_input_stride_var_decl(code, name) + return f"{name}_stride" + + def codegen_symbol( + sym_or_exp: sympy.Symbol | sympy.Expr, + base_name: str, + name_fn: Callable[[str], str], + dim: int, + deferred_symbol_assignments=None, + ) -> bool: + if isinstance(sym_or_exp, sympy.Symbol): + if sym_or_exp in bound_vars: + return False + code.writeline(f"int64_t {sym_or_exp} = {name_fn(base_name)}[{dim}];") + bound_vars.add(sym_or_exp) + if symbol_is_type(sym_or_exp, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT)): + self.unbacked_symbol_decls.add(str(sym_or_exp)) + self.maybe_emit_replacement_aliases(sym_or_exp, bound_vars) + return True + elif isinstance(sym_or_exp, sympy.Expr): + undefined_symbols = [ + sym for sym in sym_or_exp.free_symbols if sym not in bound_vars + ] + if len(undefined_symbols) != 1: + # Skip if expression contains no symbols or if multiple + # symbols exists since we assume each base symbol is defined + # by other codegen_symbol calls. + if ( + len(undefined_symbols) > 1 + and deferred_symbol_assignments is not None + ): + + def retry(deferred_symbol_assignments): + return codegen_symbol( + sym_or_exp, + base_name, + name_fn, + dim, + deferred_symbol_assignments, + ) + + deferred_symbol_assignments.append(retry) + return False + + from torch.utils._sympy.solve import try_solve + + free_symbol = undefined_symbols.pop() + base_name = name_fn(base_name) + # Use a size symbol to solve the free symbol + size_symbol = sympy.Symbol(f"{base_name}_{dim}", integer=True) + solution = try_solve(sympy.Eq(sym_or_exp, size_symbol), free_symbol) + if solution is not None: + code.writeline(f"int64_t {size_symbol} = {base_name}[{dim}];") + expr = _rewrite_symbol_solution_for_int_codegen(solution[1]) + code.writeline(f"int64_t {free_symbol} = {cexpr(expr)};") + bound_vars.add(free_symbol) + if symbol_is_type( + free_symbol, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT) + ): + self.unbacked_symbol_decls.add(str(free_symbol)) + self.maybe_emit_replacement_aliases(free_symbol, bound_vars) + return True + return False + return False + + if isinstance(value, sympy.Expr): + if not isinstance(value, sympy.Symbol) or value in bound_vars: + return + if symbol_is_type(value, (SymT.FLOAT, SymT.UNBACKED_FLOAT)): + decl = "double" + else: + decl = "int64_t" + code.writeline(f"{decl} {value} = {name};") + bound_vars.add(value) + if symbol_is_type(value, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT)): + self.unbacked_symbol_decls.add(str(value)) + self.maybe_emit_replacement_aliases(value, bound_vars) + elif isinstance(value, ir.TensorBox): + for dim, size in enumerate(value.get_size()): + codegen_symbol(size, name, sizeof, dim, deferred_symbol_assignments) + for dim, stride in enumerate(value.get_stride()): + codegen_symbol(stride, name, strideof, dim, deferred_symbol_assignments) + elif isinstance( + value, (ir.TorchBindObject, ir.GeneratorState, ir.OpaqueObjectState) + ): + # Python-only inputs do not define C++ shape symbols. + pass + else: + raise AssertionError(f"Unknown value type: {type(value)}") + + def maybe_emit_replacement_aliases( # type: ignore[override] + self, + sym: sympy.Symbol, + bound_vars: OrderedSet[sympy.Symbol], + ) -> None: + sizevars = getattr(V.graph, "sizevars", None) + shape_env = getattr(sizevars, "shape_env", None) + if shape_env is None: + return + + def is_backed_symbol(s: sympy.Symbol) -> bool: + return not symbol_is_type(s, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT)) + + def decl_type(s: sympy.Symbol) -> str: + if symbol_is_type(s, (SymT.FLOAT, SymT.UNBACKED_FLOAT)): + return "double" + return "int64_t" + + for src, tgt in shape_env.replacements.items(): + if ( + tgt == sym + and isinstance(src, sympy.Symbol) + and src not in bound_vars + and is_backed_symbol(src) + and is_backed_symbol(sym) + ): + self.prefix.writeline(f"{decl_type(src)} {src} = {sym};") + bound_vars.add(src) + elif ( + src == sym + and isinstance(tgt, sympy.Symbol) + and tgt not in bound_vars + and is_backed_symbol(sym) + and is_backed_symbol(tgt) + ): + self.prefix.writeline(f"{decl_type(tgt)} {tgt} = {sym};") + bound_vars.add(tgt) + + def bind_input_symbol( + self, + sym: sympy.Symbol, + input_name: str, + kind: Literal["size", "stride"], + dim: int, + bound_vars: OrderedSet[sympy.Symbol], + ) -> None: + if sym in bound_vars: + return + accessor = "sizes" if kind == "size" else "strides" + self.prefix.writeline(f"int64_t {sym} = {input_name}.{accessor}()[{dim}];") + bound_vars.add(sym) + self.maybe_emit_replacement_aliases(sym, bound_vars) + + def generate_input_output_runtime_checks(self): + """ + In debug_compile mode, we generate checks to ensure the dtype/shape/stride/device of each + real input/output tensor match ones provided at compile time via sample + input/output. + """ + + def gen_check(handle_kind, idx, name, tensor): + # Wrap AtenTensorHandle with ConstantHandle for cleaner utility function access + self.prefix.writeline_aot( + f"ConstantHandle {name} = ConstantHandle({handle_kind}[{idx}]);" + ) + self.prefix.writeline_aot(f"int32_t {name}_dtype;") + self.prefix.writeline_aot( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_dtype({name}, &{name}_dtype));" + ) + expected_dtype_name = DTYPE_TO_ATEN[tensor.dtype] + dtype_str = str(tensor.dtype).split(".")[-1] + self.prefix.splice_aot(f""" + int32_t {name}_expected_dtype = aoti_torch_dtype_{dtype_str}(); + if ({name}_expected_dtype != {name}_dtype) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: unmatched dtype, " + << "expected: " << {name}_expected_dtype << "({expected_dtype_name}), " + << "but got: " << {name}_dtype << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + self.prefix.writeline_aot(f"auto {name}_size = {name}.sizes();") + for dim_idx, d in enumerate(tensor.get_size()): + if isinstance(d, (int, sympy.Integer)): + self.prefix.splice_aot(f""" + if ({d} != {name}_size[{dim_idx}]) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: unmatched dim value at {dim_idx}, " + << "expected: {d}, " << "but got: " << {name}_size[{dim_idx}] + << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + else: + from torch.utils._sympy.value_ranges import bound_sympy + + sym_range = bound_sympy(d, V.graph.sizevars.shape_env.var_to_range) + if config.aot_inductor.check_lowerbound and not math.isinf( + sym_range.lower + ): + self.prefix.splice_aot(f""" + if ({name}_size[{dim_idx}] < {sym_range.lower}) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: dim value is too small at {dim_idx}, " + << "expected it to be >= {sym_range.lower}, " << "but got: " + << {name}_size[{dim_idx}] << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + if not math.isinf(sym_range.upper): + # Limit upper bound to max C long long value (2^63 - 1) + max_long_long = ctypes.c_longlong(2**63 - 1).value + upper_bound = min(sym_range.upper, max_long_long) + self.prefix.splice_aot(f""" + if ({name}_size[{dim_idx}] > {upper_bound}) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: dim value is too large at {dim_idx}, " + << "expected to be <= {upper_bound}, " << "but got: " + << {name}_size[{dim_idx}] << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + + self.prefix.writeline_aot(f"auto {name}_stride = {name}.strides();") + for stride_idx, s in enumerate(tensor.get_stride()): + if not isinstance(s, (int, sympy.Integer)): + continue + self.prefix.splice_aot(f""" + if ({s} != {name}_stride[{stride_idx}]) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: unmatched stride value at {stride_idx}, " + << "expected: {s}, " << "but got: " << {name}_stride[{stride_idx}] + << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + + # check input device type + if isinstance(tensor, ir.TensorBox): + tensor_device = tensor.get_device() + if tensor_device is not None: + expected_device_type = DEVICE_TO_INT.get(tensor_device.type) + if expected_device_type is not None: + self.prefix.writeline_aot(f"int32_t {name}_device_type;") + self.prefix.writeline_aot( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_device_type({name}, &{name}_device_type));" + ) + device_type_str = tensor_device.type + self.prefix.splice_aot(f""" + int32_t {name}_expected_device_type = {expected_device_type}; + if ({name}_expected_device_type != {name}_device_type) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: unmatched device type, " + << "expected: " << {name}_expected_device_type << "{expected_device_type}({device_type_str}), " + << "but got: " << {name}_device_type << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + + # Create a separate function for each input check to avoid "too big to optimize" error + for idx, (name, tensor) in enumerate(V.graph.graph_inputs.items()): + self.prefix.splice_aot(f""" + AOTI_NOINLINE static void check_input_{idx}( + AtenTensorHandle* input_handles + ) {{ + """) + with self.prefix.indent(): + gen_check("input_handles", idx, name, tensor) + self.prefix.writeline_aot("}") + + # force noinline to avoid any potential compilation slowdown due to aggressive + # inline done by the host compiler + self.prefix.splice_aot(""" + static bool _check_aoti_runtime_check_inputs_env() { + const static char* env_var_value = getenv("AOTI_RUNTIME_CHECK_INPUTS"); + const static bool result = env_var_value != nullptr && env_var_value[0] != '0'; + return result; + } + + AOTI_NOINLINE static void __check_inputs_outputs( + AtenTensorHandle* input_handles, + AtenTensorHandle* output_handles) { + if (!_check_aoti_runtime_check_inputs_env()){ + return; + } + """) + with self.prefix.indent(): + for idx in range(len(V.graph.graph_inputs)): + self.prefix.writeline_aot(f"check_input_{idx}(input_handles);") + self.prefix.writeline_aot("}") + + def _write_aoti_entry_point_signature(self): + """Emit the AOTI entry point: run_impl method and _const_run_impl.""" + self.codegen_additional_funcs() + + if V.graph.const_module: + # In dual-wrapper-mode, the const graph's JIT output is emitted separately, + # while its AOTI body is spliced below into the main AOTI source. + # Keep the const graph header out of the main output to avoid + # duplicate standalone header content. + if not V.graph.is_dual_wrapper_mode: + self.header.splice(V.graph.const_module.wrapper_code.header) + if V.graph.const_wrapper_code is None: + raise AssertionError("expected const_wrapper_code to be set") + self.prefix.splice_aot(V.graph.const_wrapper_code) + if V.graph.const_kernel_code is None: + raise AssertionError("expected const_kernel_code to be set") + self.kernel_declarations.splice(V.graph.const_kernel_code) + + if V.graph.is_const_graph: + self.prefix.splice_aot(f""" + void {self.aoti_model_class_name}::_const_run_impl( + std::vector& output_handles, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) {{ + """) + else: + if not config.aot_inductor.use_runtime_constant_folding: + # If we do not split the constant graph, we'll just create + # an empty implementation when wrapping the main module. + self.prefix.splice_aot(f""" + void {self.aoti_model_class_name}::_const_run_impl( + std::vector& output_handles, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) {{}} + + """) + + run_impl_proto = f""" + void {self.aoti_model_class_name}::run_impl( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) {{ + __check_inputs_outputs(input_handles, output_handles); + """ + + self.generate_input_output_runtime_checks() + self.prefix.splice_aot(run_impl_proto) + + def _write_jit_entry_point_signature(self): + """Emit the JIT entry point: inductor_entry_impl free function.""" + self.prefix.splice_jit(""" + void inductor_entry_impl( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed) + ) { + """) + + def _write_entry_point_signature(self): + """Emit the entry point function/method signature. + + AOTI: AOTInductorModel::run_impl with stream and proxy_executor params. + JIT: inductor_entry_impl free function. + Dual-wrapper-mode: both signatures, to their respective buffers. + """ + if V.graph.aot_mode: + self._write_aoti_entry_point_signature() + self._write_jit_entry_point_signature() + + def _write_input_preamble(self): + """Emit input stealing and (in JIT mode) GIL release.""" + # Weights are promoted in the JIT mode + jit_num_args = len(V.graph.graph_inputs) + len(V.graph.constants) + # AOTI const graphs enter through _const_run_impl and have no + # input_handles. Their JIT entry point still receives constants as + # appended input handles. + if not V.graph.is_const_graph: + aoti_num_args = len(V.graph.graph_inputs) + self.prefix.splice_aot( + f"auto inputs = steal_from_raw_handles_to_raii_handles(input_handles, {aoti_num_args});" + ) + # release GIL to support multiple instances inference (in different threads of the same process) + self.prefix.splice_jit("py::gil_scoped_release_simple release;") + self.prefix.splice_jit( + f"auto inputs = steal_from_raw_handles_to_raii_handles(input_handles, {jit_num_args});" + ) + + def _write_input_unpacking(self): + """Emit code to unpack graph inputs from the handles array.""" + inputs_len = len(V.graph.graph_inputs.keys()) + if inputs_len == 0: + return + for idx, input_key in enumerate(V.graph.graph_inputs.keys()): + # unwrap input tensor back to scalar + if isinstance(V.graph.graph_inputs[input_key], sympy.Expr): + from ..graph import may_get_constant_buffer_dtype + + dtype = may_get_constant_buffer_dtype( + V.graph.graph_inputs[input_key] # type: ignore[arg-type] + ) + if dtype is None: + raise AssertionError("Fails to get the dtype of the sympy.Expr") + self.codegen_tensor_item( + dtype, f"inputs[{idx}]", input_key, self.prefix + ) + else: + self.prefix.writeline(f"auto {input_key} = std::move(inputs[{idx}]);") + # debug printing for all input args to AOTI model + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.codegen_model_inputs_value_print( + input_args_to_print=[ + input_key + for input_key in V.graph.graph_inputs + if input_key.startswith("arg") + ] + ) + + def _write_constants_unpacking(self): + """Emit code to unpack constants — from constants_ (AOTI) or inputs (JIT).""" + inputs_len = len(V.graph.graph_inputs.keys()) + if not all( + isinstance(v, torch.Tensor) for v in list(V.graph.constants.values()) + ): + raise AssertionError("Expect all constants to be Tensor") + for idx, constants_key in enumerate(V.graph.constants.keys()): + # AOTI: weights live in constants_ owned by ConstantHandle; never std::move. + # JIT: weights are appended as inputs to the graph. + constants_idx = inputs_len + idx + self.prefix.writeline_aot( + f"[[maybe_unused]] auto& {constants_key} = constants_->at({idx});" + ) + self.prefix.writeline_jit( + f"[[maybe_unused]] auto {constants_key} = std::move(inputs[{constants_idx}]);" + ) + + def _write_entry_point_postamble(self): + """Emit AOTI-specific post-input setup (inputs.clear, kernels ref).""" + if not V.graph.is_const_graph: + self.prefix.writeline_aot("inputs.clear();") + self.prefix.writeline_aot( + "[[maybe_unused]] auto& kernels = static_cast(*this->kernels_.get());" + ) + + def write_wrapper_decl(self): + self._write_entry_point_signature() + with self.prefix.indent(): + self._codegen_entry_impl_prologue() + self._write_input_preamble() + self._write_input_unpacking() + self._write_constants_unpacking() + self.codegen_inputs() + self._write_entry_point_postamble() + + def codegen_tensor_dtype_var_decl(self, code: IndentedBuffer, name): + code.writeline(f"int32_t {name}_dtype;") + code.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_dtype({name}, &{name}_dtype));" + ) + + def codegen_input_size_var_decl(self, code: IndentedBuffer, name): + code.writeline(f"auto {name}_size = {name}.sizes();") + + def codegen_input_stride_var_decl(self, code: IndentedBuffer, name): + code.writeline(f"auto {name}_stride = {name}.strides();") + + def codegen_input_device_type_var_decl(self, code: IndentedBuffer, name): + code.writeline(f"int32_t {name}_device_type;") + code.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_device_type({name}, &{name}_device_type));" + ) + + def codegen_additional_funcs(self): + pass + + def codegen_initialized_kernel_decls(self): + # Tell compiler we need to link with the non-mangled symbols + for kernel in self.initialized_kernels.values(): + if not hasattr(kernel, "get_signature"): + raise AssertionError(f"{kernel} must have get_signature implemented") + signature = kernel.get_signature() + self.prefix.writeline(f'extern "C" {signature};') + + def codegen_model_kernels(self): + self.prefix.writeline("namespace {") + self.codegen_initialized_kernel_decls() + self.prefix.writeline( + "class AOTInductorModelKernels : public AOTInductorModelKernelsBase {" + ) + self.prefix.writeline(" public:") + declare_kernel = OrderedSet(self.src_to_kernel.values()) - OrderedSet( + self.initialized_kernels.keys() + ) + declare_kernel.update( + entry[0] for entry in self.user_defined_kernel_cache.values() + ) + if V.graph.const_module: + declare_kernel.update( + V.graph.const_module.wrapper_code.src_to_kernel.values() + ) + # CPU Triton kernels need a (kernel_fn, launcher_fn) pair, declared + # separately below; skip them in the default single-`void*` loop. + cpu_triton_names = self._cpu_triton_kernel_names + for kernel in sorted(declare_kernel): + if kernel in cpu_triton_names: + continue + self.prefix.writeline( + maybe_hipify_code_wrapper( + f" {self.device_codegen.cpp_kernel_type()} {kernel}{{nullptr}};" + ) + ) + for kernel in sorted(cpu_triton_names): + self.prefix.writeline(f" void* {kernel}_kernel_fn{{nullptr}};") + self.prefix.writeline( + f" torch::aot_inductor::CpuTritonLauncherFn " + f"{kernel}_launcher_fn{{nullptr}};" + ) + for name, kernel in self.initialized_kernels.items(): + if not hasattr(kernel, "get_signature"): + raise AssertionError(f"{kernel} must have get_signature implemented") + kernel_ptr = f"(*{name})" + signature = kernel.get_signature().replace(name, kernel_ptr) + self.prefix.writeline(f" {signature} = torch::aot_inductor::{name};") + self.prefix.writeline("};") + self.prefix.writeline("} // namespace\n\n") + + if config.aot_inductor.embed_kernel_binary: + self.prefix.writeline('extern "C" {') + for name in sorted(declare_kernel): + self.prefix.writeline( + f" extern const unsigned char __{name}_start[];" + ) + if torch.xpu.is_available(): + self.prefix.writeline( + f" extern const unsigned char __{name}_end[];" + ) + self.prefix.writeline("}") + + # MSVC string was longer than the limit of 16380 single-byte characters. + # https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2026 + MSVC_C2026_MAX_STRING_LENGTH = 16000 + + def codegen_write_arg_with_large_length_string( + self, + arg_name: str, + arg_str_val: str, + max_truncate_length: int = MSVC_C2026_MAX_STRING_LENGTH, + ): + def truncate_string(s: str, length: int) -> list[str]: + return [s[i : i + length] for i in range(0, len(s), length)] + + if len(arg_str_val) > max_truncate_length: + truncated_strs = truncate_string(arg_str_val, max_truncate_length) + self.prefix.writeline(f"{arg_name} =") + for truncate_str in truncated_strs: + self.prefix.writeline(f'R"({truncate_str})"') + self.prefix.writeline(";") + else: + self.prefix.writeline(f'{arg_name} = R"({arg_str_val})";') + + def codegen_model_constructor(self): + """ + // Generated code example + AOTInductorModel::AOTInductorModel() + : AOTInductorModelBase(4, 1) { + inputs_info_[0].name = "input0"; + inputs_info_[0].dtype = "torch.float16"; + ... + constants_info_[0].name = "L__self___weight"; + constants_info_[0].dtype = at::kFloat; + constants_info_[0].offset = 0; + constants_info_[0].data_size = 8192; + constants_info_[0].shape = {64, 32}; + constants_info_[0].stride = {32, 1}; + ... + outputs_info_[0].name = "output0"; + outputs_info_[0].dtype = "torch.float16"; + } + """ + + num_inputs = len(V.graph.graph_inputs) + num_outputs = len(V.graph.graph_outputs) + num_constants = len(V.graph.constants) + include_weights = ( + "true" + if config.aot_inductor.package_constants_in_so + and config.aot_inductor.package_constants_on_disk_format != "binary_blob" + else "false" + ) + self.prefix.splice(f""" + {self.aoti_model_class_name}::{self.aoti_model_class_name}(std::shared_ptr constants_map, + std::shared_ptr> constants_array, + const std::string& device_str, + std::optional cubin_dir) + : AOTInductorModelBase({num_inputs}, + {num_outputs}, + {num_constants}, + device_str, + std::move(cubin_dir), + {include_weights}) {{ + """) + + with self.prefix.indent(): + for idx, (name, inp) in enumerate(V.graph.graph_inputs.items()): + if isinstance(inp, sympy.Expr): + raise AssertionError(f"input {name=} cannot be symbolic") + self.write_input_output_info("inputs_info_", idx, name) + + all_cuda = all( + V.graph.get_original_value_of_constant(name).is_cuda + for name in V.graph.constants + if name not in V.graph.folded_constants + ) + for idx, name in enumerate(V.graph.constants.keys()): + tensor = V.graph.get_original_value_of_constant(name) + if not isinstance(tensor, torch.Tensor): + raise AssertionError( + f"expected constant {name} to be a Tensor, got {type(tensor)}" + ) + self.prefix.writeline(f"""constants_info_[{idx}].name = "{name}";""") + self.prefix.writeline( + f"constants_info_[{idx}].dtype = {self.codegen_dtype(tensor.dtype)};" + ) + # Mixed-device constants are only supported when the secondary device is CPU + if tensor.device.type != self.device and tensor.device.type != "cpu": + raise AssertionError( + f"Mixed-device constants are only supported when the secondary " + f"device is CPU. Model device is '{self.device}', but constant " + f"'{name}' is on device '{tensor.device}'." + ) + # device_index is not needed because it can be set at runtime + device_type, _ = self.codegen_device(tensor.device).split(", ") + self.prefix.writeline( + f"constants_info_[{idx}].device_type = {device_type};" + ) + self.prefix.writeline( + f"constants_info_[{idx}].offset = {tensor.storage_offset()};" + ) + + # If constants to serialize contain cpu tensors, we always align data_size it to 64. + # When loading the constants, the valid data will depends on the size + # not the data_size so there won't be correctness issue. + data_size = ( + torch.ops.mkldnn._nbytes(tensor) + if tensor.is_mkldnn + else tensor.untyped_storage().nbytes() + ) + self.prefix.writeline( + f"constants_info_[{idx}].data_size = {data_size if all_cuda else _align(data_size)};" + ) + + from_folded = "true" if name in V.graph.folded_constants else "false" + self.prefix.writeline( + f"constants_info_[{idx}].from_folded = {from_folded};" + ) + + if name in V.graph.folded_constants: + constant_type_str = "FoldedConstant" + elif name.startswith("_tensor_constant"): + constant_type_str = "TensorConstant" + elif any( + name == normalize_name(parameter_name) + for parameter_name in V.graph.named_parameters + ): + constant_type_str = "Parameter" + elif any( + name == normalize_name(buffer_name) + for buffer_name in V.graph.named_buffers + ): + constant_type_str = "Buffer" + else: + constant_type_str = "Unknown" + self.prefix.writeline( + f"constants_info_[{idx}].type = static_cast(torch::aot_inductor::ConstantType::{constant_type_str});" + ) + + size_str = ", ".join([str(s) for s in tensor.size()]) + self.prefix.writeline(f"constants_info_[{idx}].shape = {{{size_str}}};") + + stride_str = ", ".join([str(s) for s in tensor.stride()]) + self.prefix.writeline( + f"constants_info_[{idx}].stride = {{{stride_str}}};" + ) + self.prefix.writeline( + f"constants_info_[{idx}].layout = static_cast({self.codegen_layout(tensor.layout)});" + ) + + if tensor.is_mkldnn: + opaque_metadata_tensor = torch.ops.mkldnn._get_mkldnn_serialized_md( + tensor + ) + if opaque_metadata_tensor.dim() != 1: + raise AssertionError("Expect opaque_metadata_tensor to be 1-D") + + opaque_metadata_list = opaque_metadata_tensor.tolist() + opaque_metadata_str = self.codegen_shape_tuple(opaque_metadata_list) + self.prefix.writeline( + f"constants_info_[{idx}].opaque_metadata = {opaque_metadata_str};" + ) + if name in V.graph.dynamo_flat_name_to_original_fqn: + original_fqn = V.graph.dynamo_flat_name_to_original_fqn.get( + name, name + ) + elif name in V.graph.allocated_constant_name: + original_fqn = V.graph.allocated_constant_name[name] + else: + raise AssertionError("original_fqn must be set for constant") + self.prefix.writeline( + f"""constants_info_[{idx}].original_fqn = "{original_fqn}";""" + ) + self.prefix.writeline("update_constants_map(std::move(constants_map));") + self.prefix.writeline("update_constants_array(std::move(constants_array));") + + def escape_string(x): + return ( + x.replace("\\", "\\\\") + .replace('"', '\\"') + .replace("\n", "\\n") + .replace("\t", "\\t") + ) + + # Origin code: self.prefix.writeline(f'in_spec_ = R"({config.aot_inductor.serialized_in_spec})";') + # Fix msvc C2026 error via codegen_write_arg_with_large_length_string + self.codegen_write_arg_with_large_length_string( + arg_name="in_spec_", arg_str_val=config.aot_inductor.serialized_in_spec + ) + # Origin code: self.prefix.writeline(f'out_spec_ = R"({config.aot_inductor.serialized_out_spec})";') + # Fix msvc C2026 error via codegen_write_arg_with_large_length_string + self.codegen_write_arg_with_large_length_string( + arg_name="out_spec_", + arg_str_val=config.aot_inductor.serialized_out_spec, + ) + + for idx, output in enumerate(V.graph.graph_outputs): + if isinstance(output, sympy.Expr): + raise AssertionError(f"output {name=} cannot be symbolic") + name = f"output{idx}" + self.write_input_output_info("outputs_info_", idx, name) + + self.prefix.writeline( + "this->kernels_ = std::make_unique();" + ) + + self.prefix.writeline("}") + + def codegen_const_run_driver(self): + """ + // Generated code example + std::unordered_map AOTInductorModel::const_run_impl( + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor, + bool initialization + ) { + std::unordered_map folded_constants_map; + std::vector output_handles; + // build up output_handles over here. + _const_run_impl(output_handles, stream, proxy_executor); + // build up folded_constants_map + return folded_constants_map; + } + """ + + self.prefix.splice(f""" + std::unordered_map {self.aoti_model_class_name}::const_run_impl( + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor, + bool initialization + ) {{ + """) + if not config.aot_inductor.use_runtime_constant_folding: + self.prefix.splice(""" + if (!initialization) { + std::cerr << "[WARNING] Calling constant_folding in model, but compiled with config: " + << "aot_inductor.use_runtime_constant_folding=False\\n"; + } + return {}; + } + """) + return + + with self.prefix.indent(): + # This is a mapping to the index of constant folding graph's output + const_index_mapping: list[tuple[int, str] | None] = [None] * len( + V.graph.const_output_index + ) + for idx, (name, _) in enumerate(V.graph.constants.items()): + if name in V.graph.const_output_index: + const_index_mapping[V.graph.const_output_index[name]] = (idx, name) # type: ignore[call-overload] + if None in const_index_mapping: + raise AssertionError( + "Not all constant gets mapped for constant folding graph." + ) + + self.prefix.writeline(f""" + std::unordered_map folded_constants_map; + folded_constants_map.reserve({len(const_index_mapping)}); + std::vector output_handles({len(const_index_mapping)}); + """) + + self.prefix.splice(""" + // The below assignment of output_handles to constants is not used directly. + // It's only used to memo the correspondence of handle and constants. + """) + + for output_idx, (const_idx, _) in enumerate(const_index_mapping): # type: ignore[misc] + self.prefix.writeline( + f"output_handles[{output_idx}] = constants_->at({const_idx});" + ) + + self.prefix.writeline( + "_const_run_impl(output_handles, stream, proxy_executor);" + ) + + for output_idx, (_, const_name) in enumerate(const_index_mapping): # type: ignore[misc] + self.prefix.writeline( + f'folded_constants_map["{const_name}"] = output_handles[{output_idx}];' + ) + self.prefix.writeline("return folded_constants_map;") + + self.prefix.writeline("}") + + def generate(self, is_inference): + with dynamo_timed("CppWrapperCpu.generate", log_pt2_compile_event=True): + self.write_wrapper_decl() + return super().generate(is_inference) + + def _codegen_aoti_model_class(self): + """Emit AOTI model class, constructor, and const_run driver into self.prefix.""" + self.prefix.writeline("namespace torch::aot_inductor {") + self.codegen_model_kernels() + self.codegen_model_constructor() + self.codegen_const_run_driver() + self.prefix.writeline("} // namespace torch::aot_inductor") + self.prefix.writeline("using namespace torch::aot_inductor;") + + def finalize_prefix(self): + prior = self.prefix + + # Build AOTI model class into a temporary buffer (AOTI-only content). + # _codegen_aoti_model_class calls methods that write to self.prefix, + # so redirect self.prefix to the temporary buffer during the call. + aot_mode_decls = IndentedBuffer() + if V.graph.aot_mode and not V.graph.is_const_graph: + with self._target_buf("prefix", aot_mode_decls): + self._codegen_aoti_model_class() + elif not V.graph.is_const_graph and self.initialized_kernels: + # JIT cpp_wrapper: emit extern "C" decls for kernels (CUTLASS, + # ROCm CK) whose precompiled .so files are linked into the + # wrapper via extra_flags. + self.codegen_initialized_kernel_decls() + + # Reset self.prefix and write shared cache decls + CPU triton content. + self.prefix = make_codegen_buffer() + for dtype in self.used_cached_dtypes: + self.prefix.writeline(f"CACHE_TORCH_DTYPE({dtype});") + for device in self.used_cached_devices: + self.prefix.writeline(f"CACHE_TORCH_DEVICE({device});") + for layout in self.used_cached_layouts: + self.prefix.writeline(f"CACHE_TORCH_LAYOUT({layout});") + for memory_format in self.used_cached_memory_formats: + self.prefix.writeline(f"CACHE_TORCH_MEMORY_FORMAT({memory_format});") + + # Includes are needed whenever a kernel was *defined* (the model + # kernels class references `CpuTritonLauncherFn`); `call_` bodies + # only for kernels that were actually *called*. + if self._cpu_triton_kernel_names: + self._write_cpu_triton_runtime_includes(self.prefix) + if self._cpu_triton_call_wrappers: + for wrapper in self._cpu_triton_call_wrappers.values(): + self.prefix.writeline("\n") + wrapper.generate(self) + + # aot_mode_decls is AOTI-only; splice_aot routes correctly across + # all three modes (no-op on plain IndentedBuffer in pure-JIT). + self.prefix.splice_aot(aot_mode_decls) + self.prefix.splice(prior) + + @staticmethod + def _write_cpu_triton_runtime_includes(prefix: IndentedBuffer) -> None: + """One-time includes/guards needed by emitted CPU Triton wrappers.""" + prefix.writeline("// CPU AOTI Triton kernel wrappers") + prefix.writeline("#ifdef _WIN32") + prefix.writeline( + '#error "CPU AOTI Triton kernels are not supported on Windows"' + ) + prefix.writeline("#endif") + prefix.writeline("#include ") + prefix.writeline( + "#include " + ) + + @staticmethod + def _stringify_cpu_triton_call_arg(arg: Any) -> str: + """Render a Triton kernel call argument as a C++ expression.""" + if isinstance(arg, str): + return arg + if isinstance(arg, bool): + return "true" if arg else "false" + if isinstance(arg, (int, float, SymbolicCallArg)): + return str(arg) + return cexpr(V.graph.sizevars.simplify(arg)) + + def _define_kernel_helper( + self, + kernel_name: str, + kernel_body: str, + metadata: str | None = None, + gpu: bool = False, + cpp_definition: str | None = None, + ): + # Misnomer: `gpu` actually means "is this a Triton kernel?" + if gpu: + # Register as a CPU Triton kernel and let the autotune block + # compile it; the C++ wrapper is emitted later in finalize_prefix. + self._cpu_triton_kernel_names.add(kernel_name) + if config.triton.autotune_at_compile_time: + PythonWrapperCodegen._define_kernel_helper( + self, kernel_name, kernel_body, metadata, gpu, cpp_definition + ) + return + if cpp_definition is not None: + self.needs_vec_isa = True + self.header.splice(cpp_definition) + self.kernel_declarations.splice(f"\n{kernel_body}\n") + else: + self.header.splice(f"\n{kernel_body}\n") + + def codegen_scalar_to_tensor(self, output: str): + name = f"scalar_to_tensor_{next(self.scalar_to_tensor_id)}" + self.wrapper_call.writeline( + f"RAIIAtenTensorHandle {name} = scalar_to_tensor_handle({output});" + ) + return name + + def codegen_tensor_item( + self, dtype: torch.dtype, tensor: str, scalar: str, indented_buffer=None + ): + dtype_str = str(dtype).split(".")[-1] + writer = indented_buffer or self + + if dtype == torch.float16 or dtype == torch.bfloat16: + scalar_tmp = f"{scalar}_tmp" + writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar_tmp};") + writer.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar_tmp}));" + ) + writer.writeline(f"float {scalar} = float({scalar_tmp});") + else: + writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar};") + writer.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar}));" + ) + + def generate_return(self, output_refs: list[str]): + cst_names = V.graph.constants.keys() + output2idx: dict[str, int] = {} + + # If any output ref represents an rvalue tensor, materialize it to an lvalue + # RAIIAtenTensorHandle first. This prevents situations where the code for the + # rvalue tensor references tensor handles whose contents are modified below. + output_refs = [ + self.create_tmp_raii_handle_var_if_needed(o, self.wrapper_call) + for o in output_refs + ] + + for idx, output in enumerate(output_refs): + if output == "nullptr": + continue + + is_constant_buffer = output in cst_names + output_buffer = V.graph.graph_outputs[idx] + if isinstance(output_buffer, ir.BaseView): + output_storage = output_buffer.unwrap_view() + if not isinstance(output_storage, (ir.BaseView, ir.MutableBox)): + raise AssertionError( + f"expected output_storage to be BaseView or MutableBox, " + f"got {type(output_storage)}" + ) + if isinstance(output_storage.data, ir.ConstantBuffer): + is_constant_buffer = True + + if isinstance(output_buffer, ir.ShapeAsConstantBuffer): + # Need to wrap scalar into tensor as the main function returns a vector of tensors + output_tensor = self.codegen_scalar_to_tensor(output) + self.wrapper_call.writeline( + f"output_handles[{idx}] = {output_tensor}.release();" + ) + continue + + if is_constant_buffer: + # See NOTE(return_constant) above. + self.wrapper_call.writeline( + "AOTI_TORCH_ERROR_CODE_CHECK(" + f"aoti_torch_clone({output}, &output_handles[{idx}]));" + ) + else: + if output in output2idx: + src_idx = output2idx[output] + self.wrapper_call.writeline( + f"output_handles[{idx}] = output_handles[{src_idx}];" + ) + else: + self.wrapper_call.writeline( + f"output_handles[{idx}] = {output}.release();" + ) + + if output not in output2idx: + output2idx[output] = idx + + def _codegen_entry_impl_prologue(self): + """Hook for subclasses to emit code at the top of inductor_entry_impl, + before the GIL is released. Default no-op.""" + if config.triton.debug_sync_graph: + self.generate_debug_sync(self.prefix) + + def generate_before_suffix(self, result): + # Close the entry function. In dual-wrapper-mode `result` is the JIT side; + # the AOTI side close is emitted by _generate_end_aoti. + if V.graph.aot_mode and not V.graph.is_dual_wrapper_mode: + entry = "_const_run_impl" if V.graph.is_const_graph else "run_impl" + result.writeline(f"}} // {self.aoti_model_class_name}::{entry}") + else: + result.writeline("} // inductor_entry_impl") + + def _generate_end_aoti(self, result): + """Close AOTI namespace. In dual-wrapper-mode, also assemble the + AOTI source string from `.aot` buffers into self._aot_output; the + input `result` is the JIT side and is left untouched in that case. + """ + if V.graph.is_dual_wrapper_mode: + if not isinstance(self.header, DualIndentedBuffer): + raise AssertionError( + f"expected DualIndentedBuffer, got {type(self.header)}" + ) + if not isinstance(self.prefix, DualIndentedBuffer): + raise AssertionError( + f"expected DualIndentedBuffer, got {type(self.prefix)}" + ) + if not isinstance(self.wrapper_call, DualIndentedBuffer): + raise AssertionError( + f"expected DualIndentedBuffer, got {type(self.wrapper_call)}" + ) + aot_result = IndentedBuffer() + aot_result.splice(self.header.aot) + aot_result.splice(self.prefix.aot) + with aot_result.indent(): + aot_result.splice(self.wrapper_call.aot) + entry = "_const_run_impl" if V.graph.is_const_graph else "run_impl" + aot_result.writeline(f"}} // {self.aoti_model_class_name}::{entry}") + aot_result.splice(self.suffix) + if not V.graph.is_const_graph: + aot_result.writeline("} // namespace torch::aot_inductor\n\n\n") + self._aot_output = aot_result.getvalue() + elif not V.graph.is_const_graph: + result.writeline("} // namespace torch::aot_inductor\n\n\n") + + def _generate_end_jit(self, result): + """Close JIT C++ block and emit Python wrapper for loading/calling.""" + if config.cpp_wrapper_build_separate: + # Close the wrapper code block, then write any kernel definitions. + result.splice('"""\n)') + if self.kernel_declarations: + result.splice('\nkernel_src = (\nr"""') + result.splice(self.kernel_declarations.getvalue()) + result.splice('"""\n)') + else: + result.splice(""" + kernel_src = '' + """) + else: + # Merge main code and kernel code + result.splice(self.kernel_declarations.getvalue()) + self.kernel_declarations.clear() + # Close the wrapper code block + result.splice('"""\n)') + + if config.cpp_wrapper_build_separate: + kernel_code = "kernel_src" + needs_vec_isa = "False" + kernel_needs_vec_isa = str(self.needs_vec_isa) + else: + kernel_code = "None" + needs_vec_isa = str(self.needs_vec_isa) + kernel_needs_vec_isa = "None" + # Link any precompiled kernel .so files (CUTLASS, ROCm CK) into the + # wrapper. The .so files are built without -Wl,-soname, so passing + # their absolute paths positionally to the linker encodes them as + # absolute DT_NEEDED entries that resolve at module load (same + # mechanism HalideCodeCache uses for its standalone runtime). + extra_flags_repr = repr(tuple(self.external_kernel_libs)) + # Cpp entry function for JIT with cpp wrapper + result.splice(f""" + inductor_entry = CppWrapperCodeCache.load_pybinding( + argtypes=["std::vector"], + main_code=cpp_wrapper_src, + device_type="{self.device}", + needs_vec_isa={needs_vec_isa}, + kernel_needs_vec_isa={kernel_needs_vec_isa}, + num_outputs={len(V.graph.graph_outputs)}, + kernel_code={kernel_code}, + extra_flags={extra_flags_repr}, + ) + """) + + input_python_indices = [ + idx + for idx, value in enumerate(V.graph.graph_inputs.values()) + if isinstance( + value, + (ir.TorchBindObject, ir.GeneratorState, ir.OpaqueObjectState), + ) + ] + python_only_input_indices = ( + "set()" + if not input_python_indices + else "{" + ", ".join(map(str, input_python_indices)) + "}" + ) + wrapper_body = f""" + python_only_input_indices = {python_only_input_indices} + input_tensors = [] + input_handle_positions = [] + # Preserve graph input slots: Python-only inputs stay None + # and are unpacked as nullptrs by the JIT cpp wrapper. + input_handles = [None] * len(args) + for idx, arg in enumerate(args): + if idx in python_only_input_indices: + continue + input_handle_positions.append(idx) + input_tensors.append( + arg if isinstance(arg, torch.Tensor) else torch.tensor(arg, device='cpu') + ) + """ + if V.graph.constants: + # Append constants to the input args for cpp wrapper. + # Python wrapper directly gets the value inside the wrapper call + # as a global variable passed when calling exec(code, mod.__dict__, mod.__dict__). + # For cpp wrapper, we need to pass this python value to the inductor_entry_impl function explicitly. + if not all( + isinstance(v, torch.Tensor) for v in list(V.graph.constants.values()) + ): + raise AssertionError("Expect all constants to be Tensor") + constants_str = f"[{', '.join(V.graph.constants.keys())}]" + wrapper_body += f""" + constants_tensor = {constants_str} + constants_start_idx = len(input_handles) + input_handles.extend([None] * len(constants_tensor)) + input_handle_positions.extend( + range(constants_start_idx, constants_start_idx + len(constants_tensor)) + ) + input_tensors.extend(constants_tensor) + """ + # Convert vector of at::Tensor to vector of AtenTensorHandle. + # If we pass at::Tensor, the compilation will be too slow. + wrapper_body += """ + packed_input_handles = torch._C._aoti.unsafe_alloc_void_ptrs_from_tensors(input_tensors) + for idx, handle in zip(input_handle_positions, packed_input_handles): + input_handles[idx] = handle + """ + # Release the inputs for memory reuse. + wrapper_body += """ + args.clear() + del input_handle_positions + del packed_input_handles + del input_tensors + """ + + # unwrap output tensor back to python scalar + if all(x for x in self.output_is_tensor.values()): + # If no ShapeAsConstantBuffer in the output, directly return the output as tensors + outputs_str = "output_tensors" + else: + outputs = [ + ( + f"output_tensors[{i}]" + if self.output_is_tensor[i] + else f"output_tensors[{i}].item()" + ) + for i in range(len(V.graph.graph_outputs)) + ] + outputs_str = f"[{', '.join(outputs)}]" + wrapper_body += f""" + output_handles = f(input_handles) + output_tensors = torch._C._aoti.alloc_tensors_by_stealing_from_void_ptrs(output_handles) + return {outputs_str} + """ + + # Wrap the func to support setting result._boxed_call = True + result.splice(f""" + def _wrap_func(f): + def g(args): + {wrapper_body} + return g + + call = _wrap_func(inductor_entry) + """) + + def generate_end(self, result): + """Generates the end of the code block, and any code needed to call it.""" + if V.graph.aot_mode: + self._generate_end_aoti(result) + else: + self._generate_end_jit(result) + + @staticmethod + def get_c_shim_func_name(kernel: str, device: str) -> str: + if kernel.startswith("aoti_torch_"): + return kernel + + if "::" not in kernel: + raise AssertionError( + "Cpp kernel name: " + kernel + " does not contain '::'" + ) + kernel_tokens = kernel.split("::") + kernel_suffix = kernel_tokens[-1] + if kernel_suffix == "call": + kernel_suffix = kernel_tokens[-2] + + shim_fn = f"aoti_torch_{device}_{kernel_suffix}" + return shim_fn + + def generate_c_shim_extern_kernel_call( + self, + kernel: str, + args: list[str], + device: str, + *, + debug_args: list[str] | None = None, + stack_traces: OrderedSet[str] | None = None, + ) -> None: + """debug_args kwarg allows CppWrapperCpuArrayRef to pass in wrapped arguments in + place of args while preserving debug printer output.""" + # We can do this unconditionally, since we cache this call. + self.add_device_include(device) + + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + debug_args if debug_args is not None else args, kernel, None, None, "extern" + ) + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + enable_kernel_context_guard = ( + enable_kernel_profile and config.cpp.enable_kernel_context_guard + ) + with debug_printer_manager: + shim_fn = self.get_c_shim_func_name(kernel, device) + shim_fn_codes = [ + f"AOTI_TORCH_ERROR_CODE_CHECK({shim_fn}({', '.join(args)}));" + ] + if enable_kernel_profile: + call_code = shim_fn_codes[0] + shim_fn_codes = ["{"] + if enable_kernel_context_guard: + stack_trace_str = 'R"(' + if stack_traces: + for stack_trace in stack_traces: + for line in stack_trace.split("\n"): + stack_trace_str += f"\n{line}" + stack_trace_str += "\n" + stack_trace_str += ')"' + shim_fn_codes.append( + f"""KernelContextGuard _ctx("{shim_fn}", {stack_trace_str});""" + ) + shim_fn_codes.extend( + [ + f"""RAIIAtenRecordFunctionHandle record_{shim_fn}_("{shim_fn}", nullptr);""", + call_code, + "}", + ] + ) + self.writelines(shim_fn_codes) + + def generate_c_shim_extern_kernel_alloc( + self, extern_kernel: ir.ExternKernelAlloc, args: list[str] + ) -> None: + # registered output buffer name + name = extern_kernel.name + output_handle_name = f"{name}_handle" + is_inplace = ( + isinstance(extern_kernel.op_overload, torch._ops.OpOverload) + and torch.Tag.inplace_view in extern_kernel.op_overload.tags + ) + + if not is_inplace: + self.writeline(f"AtenTensorHandle {output_handle_name};") + args = [*args, f"&{output_handle_name}"] + + device = d.type if (d := extern_kernel.get_device()) else self.device + + self.generate_c_shim_extern_kernel_call( + extern_kernel.get_kernel_name(), args, device + ) + + if extern_kernel.python_kernel_name in ( + "torch.ops._c10d_functional.all_reduce_.default", + "torch.ops._c10d_functional.wait_tensor.default", + ): + # all_reduce_ is an inplace op and its returned tensor is not used anywhere. + # wait_tensor returns its input without any modification and the returned tensor is not used anywhere. + # In both cases, we can immediately delete the returned AtenTensorHandle to reduce its lifetime. + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_delete_tensor_object({output_handle_name}));" + ) + elif not is_inplace: + self.writeline(f"RAIIAtenTensorHandle {name}({output_handle_name});") + + def _generate_extern_kernel_alloc_helper(self, extern_kernel, args): + if getattr(extern_kernel, "outputs", None): + # ir.ExternKernelAlloc may have outputs if it returns a tuple + self.generate_c_shim_fallback_kernel(extern_kernel, args) + else: + self.generate_c_shim_extern_kernel_alloc(extern_kernel, args) + + def generate_c_shim_fallback_kernel( + self, fallback_kernel: ir.FallbackKernel, args: list[str] + ) -> None: + output_args = [] + output_raii_handles = [] + output_name_base = fallback_kernel.get_name() + for idx, output in enumerate(fallback_kernel.outputs): + if isinstance(output, ir.MultiOutput): + # TODO: handle integer output (e.g., as in attention) + name = f"{output.get_name()}" + output_handle_name = f"{name}_handle" + if output.indices: + if output.indices[0][1] != idx: + raise AssertionError( + f"expected {output.indices[0][1]=} == {idx=} for {output_name_base=}" + ) + self.writeline(f"AtenTensorHandle {output_handle_name};") + output_args.append(f"&{output_handle_name}") + output_raii_handles.append( + f"RAIIAtenTensorHandle {name}({output_handle_name});" + ) + elif isinstance(output, int): + output_name = f"{output_name_base}_{idx}" + self.writeline(f"int64_t {output_name} = {output};") + output_args.append(f"&{output_name}") + elif isinstance(output, sympy.Expr): + output_name = f"{output_name_base}_{idx}" + self.writeline(f"auto {output_name} = {cexpr(output)};") + output_args.append(f"&{output_name}") + elif output is None: + output_args.append("nullptr") + else: + raise NotImplementedError(f"unsupported type of {output=}") + args = args + output_args + device = d.type if (d := fallback_kernel.get_device()) else self.device + + self.generate_c_shim_extern_kernel_call( + fallback_kernel.cpp_kernel_name, # type: ignore[arg-type] + args, + device, + ) + for raii_handle in output_raii_handles: + self.writeline(raii_handle) + + def _generate_extern_kernel_out_helper( + self, + kernel: str, + out: str, + out_view: str | None, + args: list[str], + device: str, + stack_traces: OrderedSet[str] | None = None, + ) -> None: + if out_view: + out_name = f"{out}_as_strided" + self.writeline(f"auto {out_name} = {out_view};") + args.insert(0, out_name) + else: + args.insert(0, out) + + self.generate_c_shim_extern_kernel_call( + kernel, args, device, stack_traces=stack_traces + ) + + def _get_scatter_reduce_enum(self, reduce): + # Follow aten/src/ATen/native/ReductionType.h:get_operator_enum + get_operator_enum = {"add": "sum", "multiply": "prod"} + if reduce in get_operator_enum: + reduce = get_operator_enum[reduce] + + return reduce + + def _generate_scatter_fallback_args(self, inputs: Sequence[Any]) -> list[str]: + return [str(x) for x in inputs] + + def _generate_scatter_fallback( + self, + output, + inputs, + cpp_kernel_name, + python_kernel_name, + src_is_tensor, + reduce, + kwargs, + device, + ): + reduce = self._get_scatter_reduce_enum(reduce) + + # call the ABI shim function instead of the ATen one + self.add_device_include(device) + cpp_kernel_name = self.get_c_shim_func_name(cpp_kernel_name, device) + # TODO: consider remove "_out" and add missing inplace variants to fallback_ops.py + cpp_kernel_name = cpp_kernel_name.replace("__", "_") + "_out" + # str(output) ensures that CppWrapperCpuArrayRef borrows the output tensor + args_wrapped = self._generate_scatter_fallback_args((str(output), *inputs)) + # Wrap in AOTI_TORCH_ERROR_CODE_CHECK so a shim failure + # surfaces instead of being silently swallowed. + line = f"{cpp_kernel_name}({','.join(args_wrapped)}" + + if python_kernel_name.startswith("aten.scatter_reduce"): + line += f", {','.join(kwargs)}" + elif src_is_tensor: + if reduce: + line += f", {V.graph.wrapper_code.val_to_arg_str(reduce)}" + elif reduce is not None: + raise AssertionError( + "Expect reduce to be None for aten.scatter_ with scalar src" + ) + line += ")" + self.writeline(f"AOTI_TORCH_ERROR_CODE_CHECK({line});") + + def _generate_index_put_fallback(self, kernel, x, indices, values, accumulate): + # TODO: update aoti_torch_index_put_out in ir.py to use autogen out version + # See the comment in codegen_reinterpret_view about why having something like + # RAIIAtenTensorHandle(tmp_tensor_handle_2) in a tmp array can cause the corresponding + # tensor prematurely deallocated, thus the temporary array trick here. + indices_str = self._generate_temporary_array_pointer( + "AtenTensorHandle", indices + ) + args = [ + x, + indices_str, + str(len(indices)), + values, + accumulate, + ] + args.insert(0, x) # set x as the output tensor, this fallback mutates x. + # Wrap in AOTI_TORCH_ERROR_CODE_CHECK so a shim failure surfaces instead + # of being silently swallowed. + self.writeline(f"AOTI_TORCH_ERROR_CODE_CHECK({kernel}({', '.join(args)}));") + + def add_benchmark_harness(self, output): + if V.graph.aot_mode: + return + super().add_benchmark_harness(output) + + def _extract_divisors_from_expr( + self, expr: sympy.Expr + ) -> list[tuple[sympy.Expr, str]]: + """ + Walk the sympy expression and extract all divisors/modulos from + FloorDiv, CleanDiv, Mod, and ModularIndexing nodes. + + Returns a list of (divisor_expr, operation_name) tuples for divisors + that are not constant positive integers (which cannot be zero). + """ + divisors: list[tuple[sympy.Expr, str]] = [] + seen: OrderedSet[str] = OrderedSet() + + def is_constant_nonzero(e: sympy.Expr) -> bool: + """Check if expression is a constant that cannot be zero.""" + if isinstance(e, sympy.Integer): + return int(e) != 0 + if isinstance(e, sympy.Number): + return float(e) != 0 + return False + + def maybe_add_divisor(divisor: sympy.Expr, op_name: str) -> None: + """Add divisor to list if it could potentially be zero.""" + if not is_constant_nonzero(divisor): + key = str(divisor) + if key not in seen: + seen.add(key) + divisors.append((divisor, op_name)) + + def walk(e: sympy.Expr) -> None: + if isinstance(e, (FloorDiv, CleanDiv)): + _, div = e.args + maybe_add_divisor(div, "floor division") + elif isinstance(e, Mod): + _, mod = e.args + maybe_add_divisor(mod, "modulo") + elif isinstance(e, ModularIndexing): + _, div, mod = e.args + maybe_add_divisor(div, "modular indexing division") + maybe_add_divisor(mod, "modular indexing modulo") + + # Recurse into arguments + if hasattr(e, "args"): + for arg in e.args: + if isinstance(arg, sympy.Expr): + walk(arg) + + walk(expr) + return divisors + + def codegen_cpp_sizevar(self, x: sympy.Expr, *, simplify: bool = True) -> str: + maybe_simplified_x = V.graph.sizevars.simplify(x) if simplify else x + # In AOT mode, emit runtime checks for potential division/modulo by zero + # to prevent SIGFPE crashes when symbolic tensor shapes can be 0. + if V.graph.aot_mode: + for divisor, op_name in self._extract_divisors_from_expr( + maybe_simplified_x + ): + self.write_assert_div_by_zero(cexpr(divisor), op_name) + return cexpr(maybe_simplified_x) + + def _codegen_assert_div_by_zero( + self, code: IndentedBuffer, divisor_str: str, op_name: str + ) -> None: + """Emit one div-by-zero AOTI check to `code` (replay-phase target). + + Uses writeline_aot so the check is routed to the AOTI side only in + dual-wrapper mode; on plain buffers writeline_aot has the expected + single-stream behavior (AotOnlyBuffer delegates to writeline, plain + IndentedBuffer is a no-op). + """ + code.writeline_aot( + f'AOTI_TORCH_CHECK({divisor_str} != 0, "Integer {op_name} by zero");' + ) + + def codegen_sizevar(self, x: sympy.Expr) -> str: + return self.codegen_cpp_sizevar(x) + + def codegen_tuple_access(self, basename: str, name: str, index: str) -> str: + # in the abi_compatible mode, outputs are returned via arguments + return name + + def codegen_shape_tuple(self, shape: Sequence[sympy.Expr]) -> str: + parts = [*map(self.codegen_sizevar, shape)] + if len(parts) == 0: + return "{}" + if len(parts) == 1: + return f"{{{parts[0]}, }}" + return f"{{{', '.join(parts)}}}" + + def ensure_size_computed(self, sym: sympy.Symbol): + if isinstance(sym, sympy.Symbol) and symbol_is_type(sym, SymT.PRECOMPUTED_SIZE): + if sym in self.computed_sizes: + return + self.computed_sizes.add(sym) + expr = V.graph.sizevars.inv_precomputed_replacements[sym] + self.writeline(f"int64_t {sym} = {cexpr(expr)};") + + def _generate_symbolic_call_arg_helper( + self, arg: SymbolicCallArg, graph: GraphLowering + ) -> None: + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + if enable_kernel_profile or (arg.inner, graph) not in self.kernel_numel_expr: + # When enable_kernel_profile is on, each kernel call is wrapped in + # its own {} scope block, so we must redeclare the variable each + # time since prior declarations are no longer visible. + self.kernel_numel_expr.add((arg.inner, graph)) + self.writeline(f"int64_t {arg.inner} = {cexpr(arg.inner_expr)};") + else: + self.writeline(f"{arg.inner} = {cexpr(arg.inner_expr)};") + + def _codegen_dynamic_scalar(self, node): + (data,) = (t.codegen_reference() for t in node.inputs) + self.codegen_tensor_item(node.inputs[0].get_dtype(), data, f"{node.sym}_raw") + + if len(node.keypath) == 0: + self.writeline(f"auto {node.sym} = {node.sym}_raw;") + elif len(node.keypath) == 1 and isinstance(node.keypath[0], ConvertIntKey): + self.writeline(f"int64_t {node.sym} = {node.sym}_raw ? 1 : 0;") + elif len(node.keypath) == 1 and isinstance(node.keypath[0], DivideByKey): + # TODO: assert divisibility here + self.writeline( + f"int64_t {node.sym} = {node.sym}_raw / {node.keypath[0].divisor};" + ) + else: + raise AssertionError(f"unrecognized keypath {node.keypath}") + + # record in unbacked_symbol_decls so we won't generate a declaration of the symbol again + self.unbacked_symbol_decls.add(str(node.sym)) + + def codegen_dynamic_select_index(self, node, clamp): + index_cpp_str = self.val_to_arg_str_for_prim_type(node.index, int) + size_cpp_str = self.val_to_arg_str_for_prim_type(node.size, int) + + # codegen index + sym = node.unbacked_offset_symbol + index_str = ( + f"{index_cpp_str} < 0 ? {index_cpp_str} + " + f"{self.val_to_arg_str_for_prim_type(node.size, int)}: {index_cpp_str}" + ) + self.writeline(f"auto {sym}_index = {index_str};") + index_str_clamped = ( + f"{sym}_index < 0 ? 0 : ({sym}_index > {size_cpp_str} ? {size_cpp_str} : {sym}_index)" + if clamp + else f"{sym}_index" + ) + self.writeline(f"auto {sym}_index_clamped = {index_str_clamped};") + self.writeline( + f"auto {sym} = {self.val_to_arg_str_for_prim_type(node.base_offset, int)} + " + f"{self.val_to_arg_str_for_prim_type(node.base_dim_stride, int)} * {sym}_index_clamped;" + ) + # record in unbacked_symbol_decls so we won't generate a declaration of the symbol again + self.unbacked_symbol_decls.add(str(sym)) + + def codegen_dynamic_slice_size(self, node): + start_cpp_str = self.val_to_arg_str_for_prim_type(node.start, int) + end_cpp_str = self.val_to_arg_str_for_prim_type(node.end, int) + size_cpp_str = self.val_to_arg_str_for_prim_type(node.size, int) + step_cpp_str = self.val_to_arg_str_for_prim_type(node.step, int) + sym = node.unbacked_size_symbol + + def codegen_clamp(index_str, start=True): + suf = "st" if start else "en" + index_ = f"{sym}_{suf}_index" + self.writeline( + f"int64_t {index_} = {index_str} < 0 ? {index_str} + {size_cpp_str} : {index_str};" + ) + self.writeline( + f"int64_t {sym}_{suf}_cl = {index_} < 0 ? 0 : ({index_} > {size_cpp_str} ? {size_cpp_str} : {index_});" + ) + + codegen_clamp(start_cpp_str, start=True) + codegen_clamp(end_cpp_str, start=False) + if node.step == 1: + step_str = f"{sym}_en_cl - {sym}_st_cl" + else: + step_str = ( + f"({sym}_en_cl - {sym}_st_cl + {step_cpp_str} - 1) / {step_cpp_str}" + ) + self.writeline(f"int64_t {sym}_with_step = {step_str};") + self.writeline(f"int64_t {sym} = {sym}_with_step < 0 ? 0 : {sym}_with_step;") + self.unbacked_symbol_decls.add(str(sym)) + + def make_buffer_free(self, buffer): + return ( + "" + if isinstance(buffer.get_output_spec(), ir.MultiOutputLayout) + or isinstance(buffer, ir.TMADescriptor) + else f"{buffer.get_name()}.reset();" + ) + + def make_free_by_names(self, names_to_del: list[str]): + return " ".join(f"{name}.reset();" for name in names_to_del) + + def codegen_exact_buffer_reuse(self, old_name: str, new_name: str, del_line: str): + return f"auto {new_name} = std::move({old_name}); // reuse" + + def generate_debug_sync(self, buffer): + pass + + def generate_profiler_mark_wrapper_call(self, stack): + self.wrapper_call.writeline( + 'RAIIAtenRecordFunctionHandle record_inductor_wrapper_call_("inductor_wrapper_call", nullptr);' + ) + + def generate_start_graph(self): + pass + + def generate_end_graph(self): + pass + + def generate_inf_and_nan_checker(self, nodes): + for buf in nodes.get_names(): + # TODO: Add buf name directly into check_inf_and_nan. + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_check_inf_and_nan({buf}));" + ) + + def codegen_input_nan_asserts(self) -> None: + self.wrapper_call.writeline("// make sure graph inputs are not nan/inf") + for name, buf in self.get_graph_inputs().items(): + if isinstance(buf, (sympy.Expr, ir.TorchBindObject)): + continue + self.wrapper_call.writeline( + f'AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_check_inf_and_nan("{name}", {name}));' + ) + + def _codegen_assert_size_stride( + self, + code: IndentedBuffer, + name: str, + size: str, + stride: str, + op_name: str, + dtype: torch.dtype | None = None, + ) -> None: + if V.graph.aot_mode and V.graph.is_const_graph: + return + dtype_args = ( + f', {self.codegen_dtype(dtype)}, "{dtype}"' if dtype is not None else "" + ) + stmt = f'assert_size_stride({name}, {size}, {stride}, "{op_name}"{dtype_args});' + if V.graph.aot_mode: + guarded = f"if (_check_aoti_runtime_check_inputs_env()) {{ {stmt} }}" + if V.graph.is_dual_wrapper_mode: + # _check_aoti_runtime_check_inputs_env() is AOTI-only; the JIT + # side gets the plain assert. + code.writeline_jit(stmt) + code.writeline_aot(guarded) + else: + code.writeline(guarded) + else: + code.writeline(stmt) + + def _codegen_assert_size_stride_grouped( + self, code: IndentedBuffer, asserts: list[tuple[str, str, str]], op_name: str + ) -> None: + for name, size, stride in asserts: + self._codegen_assert_size_stride(code, name, size, stride, op_name) + + def codegen_device(self, device): + if device.type not in DEVICE_TO_ATEN: + raise AssertionError(device.type + " not found in DEVICE_TO_ATEN") + device_str = DEVICE_TO_ATEN[device.type][5:].lower() # remove "at::k" + self.used_cached_devices.add(device_str) + return f"cached_torch_device_type_{device_str}, {device.index or 0}" + + def codegen_device_idx(self, device, device_id): + device_id = device_id.strip() + if not V.graph.aot_mode: + return device_id + + if device.type == V.graph.device_type and device.index is not None: + # The primary compile-time device is relocatable via device_index at load. + # Other explicit device indices must stay intact for cross-device copies. + primary_device_idx = next(iter(V.graph.device_idxs), None) + if primary_device_idx is not None and device.index != primary_device_idx: + return device_id + + return "this->device_idx_" + + def codegen_dtype(self, dtype): + dtype_str = str(dtype).split(".")[-1] + self.used_cached_dtypes.add(dtype_str) + return f"cached_torch_dtype_{dtype_str}" + + def codegen_layout(self, layout): + layout_str = str(layout).split(".")[-1] + self.used_cached_layouts.add(layout_str) + return f"cached_torch_layout_{layout_str}" + + def codegen_memory_format(self, memory_format): + memory_format_str = str(memory_format).split(".")[-1] + self.used_cached_memory_formats.add(memory_format_str) + return f"cached_torch_memory_format_{memory_format_str}" + + def codegen_int_array_var( + self, + int_array: str, + writeline: Callable[..., None], + known_statically=False, + graph=None, # for per-graph caching + ) -> str: + # Use id(graph) for caching to avoid circular references + # Bound methods have transient IDs, so we use the ID of the bound object instead. + writeline_id = ( + id(writeline.__self__) if hasattr(writeline, "__self__") else id(writeline) + ) + cache_key = ( + int_array, + writeline_id, + known_statically, + id(graph) if graph else None, + ) + if cache_key not in self.codegen_int_array_var_cache: + self.codegen_int_array_var_cache[cache_key] = ( + self._codegen_int_array_var_impl(int_array, writeline, known_statically) + ) + + return self.codegen_int_array_var_cache[cache_key] + + def _codegen_int_array_var_impl( + self, + int_array: str, + writeline: Callable[..., None], + known_statically: bool, + ) -> str: + # Used for size/stride declaration + # + # Because the memory planning is done in two passes (see the implementation + # of self.generate), the writeline behavior is different in the two passes. + # As a result, the emitted int array declarations may appear in a later + # position of the generated code, so the second pass codegen should not + # reuse int array declarations generated in the first pass. + # This is why writeline needs to explicitly passed in as a parameter. + var = f"int_array_{next(self.int_array_id)}" + ctype = "int64_t" + if int_array == "{}": + # An array of unknown bound cannot be initialized with {}. + if known_statically: + if config.cpp.use_constexpr_for_int_array: + writeline(f"static constexpr {ctype} *{var}=nullptr;") + else: + writeline(f"static const {ctype} *{var}=nullptr;") + else: + writeline(f"const {ctype} *{var}=nullptr;") + else: + if var not in self.declared_int_array_vars: + self.declared_int_array_vars.add(var) + if known_statically: + if config.cpp.use_constexpr_for_int_array: + writeline(f"static constexpr {ctype} {var}[] = {int_array};") + else: + writeline(f"static const {ctype} {var}[] = {int_array};") + else: + writeline(f"const {ctype} {var}[] = {int_array};") + return var + + def make_buffer_allocation(self, buffer): + return self.make_allocation( + buffer.get_name(), + buffer.get_device(), + buffer.get_dtype(), + buffer.get_size(), + buffer.get_stride(), + V.graph.get_allocation_size(buffer), + buffer.get_is_pinned(), + ) + + def make_allocation( + self, name, device, dtype, shape, stride, allocation_shape=None, is_pinned=False + ): + """Emit C++ to allocate a tensor handle via aoti_torch_empty_strided. + + Returns the RAIIAtenTensorHandle binding string; if the allocation + shape differs from the logical shape, a follow-up aoti_torch_as_strided + is emitted to reinterpret the handle. + """ + if allocation_shape is None: + allocation_shape = shape + + orig_stride = stride + device_str = self.codegen_device(device) + dtype_code = self.codegen_dtype(dtype) + size = self.codegen_shape_tuple(shape) + allocation_size = self.codegen_shape_tuple(allocation_shape) + stride = self.codegen_shape_tuple(orig_stride) + + size_array_var = self.codegen_int_array_var( + size, + self.wrapper_call.writeline, + known_statically=self.is_statically_known_list_of_ints(shape), + graph=self.get_codegened_graph(), + ) + + if allocation_size != size: + allocation_size_array_var = self.codegen_int_array_var( + allocation_size, + self.wrapper_call.writeline, + known_statically=self.is_statically_known_list_of_ints( + allocation_shape + ), + graph=self.get_codegened_graph(), + ) + else: + allocation_size_array_var = size_array_var + + stride_array_var = self.codegen_int_array_var( + stride, + self.wrapper_call.writeline, + known_statically=self.is_statically_known_list_of_ints(orig_stride), + graph=self.get_codegened_graph(), + ) + device_type, device_id = device_str.split(",") + handle_name = f"{name}_handle" + self.wrapper_call.writeline(f"AtenTensorHandle {handle_name};") + pinned_str = "_pinned" if is_pinned else "" + + def _alloc_line(device_idx: str) -> str: + args = ", ".join( + [ + str(len(shape)), + allocation_size_array_var, + stride_array_var, + dtype_code, + device_type, + device_idx, + f"&{handle_name}", + ] + ) + return f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided{pinned_str}({args}));" + + # AOTI side: codegen_device_idx returns this->device_idx_ for the + # primary device so the model honors runtime device assignment, but + # keeps concrete indices for non-primary (cross-device) allocations. + # JIT side (pure or dual mode's JIT) has no this->device_idx_ in scope, + # so use the concrete graph device id. + self.wrapper_call.writeline_aot( + _alloc_line(self.codegen_device_idx(device, device_id)) + ) + self.wrapper_call.writeline_jit(_alloc_line(device_id)) + + if allocation_size != size: + old_handle_name, handle_name = handle_name, f"{name}_handle_restrided" + self.wrapper_call.writeline(f"AtenTensorHandle {handle_name};") + args = [ + old_handle_name, + size_array_var, + stride_array_var, + f"&{handle_name}", + ] + self.wrapper_call.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_as_strided({', '.join(args)}));" + ) + self.wrapper_call.writeline( + f"wrap_with_raii_handle_if_needed({old_handle_name});" + ) + + return f"RAIIAtenTensorHandle {name}({handle_name});" + + def codegen_alloc_from_pool( + self, name, offset, dtype, shape, stride + ) -> tuple[str, list[str]]: + size = self.codegen_shape_tuple(shape) + stride = self.codegen_shape_tuple(stride) + tmp_name = f"tmp_tensor_handle_{next(self.tmp_tensor_id)}" + args = [ + name, + cexpr(offset), # bytes not numel + self.codegen_dtype(dtype), + str(len(shape)), + self.codegen_int_array_var( + size, self.wrapper_call.writeline, graph=self.get_codegened_graph() + ), + self.codegen_int_array_var( + stride, self.wrapper_call.writeline, graph=self.get_codegened_graph() + ), + f"&{tmp_name}", + ] + # We return the lines instead of writing here because writing here is bug prone. + # If you write aoti_torch__alloc_from_pool lines, you must write the RAIIAtenTensorHandle + # as well, otherwise you get memory leaks + allocations_to_write = [ + f"AtenTensorHandle {tmp_name};", + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch__alloc_from_pool({', '.join(args)}));", + ] + return f"RAIIAtenTensorHandle({tmp_name})", allocations_to_write + + def codegen_reinterpret_view( + self, + data, + size, + stride, + offset, + writeline: Callable[..., None], + dtype=None, + ) -> str: + """Returns a newly-created, temporary RAII tensor handle containing the + reinterpreted tensor data. Callers of this function are responsible for saving + the handle if persistent access is needed.""" + + d_size, d_stride, d_offset, d_dtype, collapsible = ( + codegen_reinterpret_view_helper(data) + ) + + dim = str(len(size)) + original_offset = offset + offset = self.codegen_sizevar(offset) + call_strs = [] + final_tensor_str = None + + def create_reinterpret_call() -> str: + args = [ + f"{data.get_name()}", + dim, + self.codegen_int_array_var( + self.codegen_shape_tuple(size), + writeline, + known_statically=self.is_statically_known_list_of_ints(size), + graph=self.get_codegened_graph(), + ), + self.codegen_int_array_var( + self.codegen_shape_tuple(stride), + writeline, + known_statically=self.is_statically_known_list_of_ints(stride), + graph=self.get_codegened_graph(), + ), + offset, + ] + return f"wrap_with_raii_handle_if_needed(reinterpret_tensor_wrapper({', '.join(args)}))" + + def create_dtypeview_call(reinterpret_call: str) -> tuple[str, list[str]]: + tmp_AtenTensorHandle = f"tmp_{data.get_name()}_{next(self.tmp_tensor_id)}" + tmp_call_strs = [f"AtenTensorHandle {tmp_AtenTensorHandle};"] + device_name = data.layout.device.type + dtypeview_function = f"aoti_torch_{device_name}_view_dtype" + tmp_call_strs.append( + f"AOTI_TORCH_ERROR_CODE_CHECK({dtypeview_function}" + f"({reinterpret_call}, {self.codegen_dtype(dtype)}, &{tmp_AtenTensorHandle}));" + ) + return f"RAIIAtenTensorHandle({tmp_AtenTensorHandle})", tmp_call_strs + + def create_new_tensor_handle() -> tuple[str, list[str]]: + tmp_AtenTensorHandle = f"tmp_{data.get_name()}_{next(self.tmp_tensor_id)}" + tmp_call_strs = [ + f"AtenTensorHandle {tmp_AtenTensorHandle};", + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_tensor_handle({data.get_name()}, &{tmp_AtenTensorHandle}));", + ] + return f"RAIIAtenTensorHandle({tmp_AtenTensorHandle})", tmp_call_strs + + collapsed = collapsible and original_offset == d_offset + if collapsed: + same_layout = size == d_size and stride == d_stride + base_dtype = d_dtype + else: + same_layout = ( + size == data.layout.size + and stride == data.layout.stride + and original_offset == data.layout.offset + ) + base_dtype = data.dtype + + if same_layout: + # pure dtypeview + if dtype is not None and dtype != base_dtype: + final_tensor_str, tmp_call_strs = create_dtypeview_call(data.get_name()) + else: + final_tensor_str, tmp_call_strs = create_new_tensor_handle() + call_strs.extend(tmp_call_strs) + else: + # firstly create reinterpretview + final_tensor_str = create_reinterpret_call() + if dtype is not None and dtype != base_dtype: + # wrap it with dtypeview + final_tensor_str, tmp_call_strs = create_dtypeview_call( + final_tensor_str + ) + call_strs.extend(tmp_call_strs) + + for line in call_strs: + writeline(line) + + # NB, the return handle here represents a temporary tensor, which will be automatically + # released. + # Here's a sample usage in the cpp wrapper code: + # ``` + # aoti_torch_addmm_out( + # buf1, + # arg1_1, + # RAIIAtenTensorHandle(tmp_tensor_handle_0), + # buf0, + # 1L, + # 1L)); + # ``` + # RAIIAtenTensorHandle(tmp_tensor_handle_0) will be released after the call to addmm_out. + # This could be problematic when it's used in a different pattern, for example: + # ```` + # AtenTensorHandle tensor_args[] = {RAIIAtenTensorHandle(tmp_tensor_handle_2), buf5, buf6}; + # aoti_torch_proxy_executor_call_function(..., tensor_args); + # ```` + # RAIIAtenTensorHandle(tmp_tensor_handle_2) will be invalid when it's used in the latter + # kernel call. + # + # This is solved by updating the proxy_executor invocation to + # ``` + # aoti_torch_proxy_executor_call_function(..., + # std::array{ + # RAIIAtenTensorHandle(tmp_tensor_handle_2), buf5, buf6 + # }.cbegin() + # ); + # ``` + return final_tensor_str + + def codegen_device_copy(self, src, dst, non_blocking: bool | str): + """This function is overridden by cpp_wrapper_cpu_array_ref, so we don't need to + handle cases where dst is not an AtenTensorHandle.""" + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_copy_({dst}, {src}, {non_blocking}));" + ) + + def sync_d2h_copy(self, buffer_name: str) -> None: + # TODO: add AOTI C API for event-based D2H copy synchronization + pass + + def codegen_multi_output(self, node: ir.MultiOutput): + # in the abi_compatible mode, outputs are retrieved by passing + # output pointers, so we skip its codegen here. + pass + + def codegen_subgraph_prefix(self, subgraph, outer_inputs, outer_outputs): + if len(subgraph.graph.graph_inputs) != len(outer_inputs): + raise AssertionError( + f"expected len(subgraph.graph.graph_inputs) == len(outer_inputs), " + f"got {len(subgraph.graph.graph_inputs)} and {len(outer_inputs)}" + ) + + for (inner_input, inner_input_val), outer_input in zip( + subgraph.graph.graph_inputs.items(), outer_inputs + ): + if not isinstance(inner_input_val, ir.TensorBox): + continue + + # in ABI-compatible mode, we copy the underlying at::Tensor of the conditional + # input (outer_input) into another at::Tensor to be used as a subgraph input + # (inner_input) in the nested scope. we can't std::move here, as the codegened + # outer input may be an expression / rvalue (e.g., reinterpret_view(x)), so we + # can't necessarily std::move it back to the origin (x). + self.writeline(f"AtenTensorHandle {inner_input}_handle;") + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors_out({outer_input}, &{inner_input}_handle));" + ) + self.writeline(f"RAIIAtenTensorHandle {inner_input}({inner_input}_handle);") + + def codegen_subgraph_suffix(self, subgraph, outer_inputs, outer_outputs): + for inner_output, outer_output in zip( + subgraph.graph.graph_outputs, outer_outputs + ): + src = inner_output.codegen_reference() + if not isinstance(inner_output, ir.ShapeAsConstantBuffer): + # in ABI-compatible mode, we need to std::move subgraph output (inner_output) + # to the conditional output (outer_output), as RAIIAtenTensorHandle's copy + # constructor is deleted. + src = f"std::move({src})" + # in case the outer_output carried a value + # before (e.g., in the while_loop codegen) + self.writeline(f"{outer_output}.reset();") + self.writeline(f"{outer_output} = {src};") + + @staticmethod + def _get_while_loop_carried_output_names(while_loop): + mutation_output_names = { + mutation_name: mutation_output.get_name() + for mutation_output in while_loop.mutation_outputs + for mutation_name in mutation_output.get_mutation_names() + } + + def resolve_mutation_output_name(name): + seen = OrderedSet() + while name in mutation_output_names: + if name in seen: + raise AssertionError("while_loop mutation outputs contain a cycle") + seen.add(name) + name = mutation_output_names[name] + return name + + output_names = [] + output_idx = 0 + for carried_input in while_loop.carried_inputs: + carried_input_name = carried_input.get_name() + mutation_output_name = resolve_mutation_output_name(carried_input_name) + if mutation_output_name != carried_input_name: + output_names.append(mutation_output_name) + continue + + if output_idx >= len(while_loop.outputs): + raise AssertionError( + "while_loop has fewer non-mutated outputs than carried inputs" + ) + output_names.append(while_loop.outputs[output_idx].get_name()) + output_idx += 1 + + if output_idx != len(while_loop.outputs): + raise AssertionError("while_loop has unused non-mutated outputs") + + return output_names + + def codegen_invoke_subgraph(self, invoke_subgraph): + raise NotImplementedError( + "codegen invoke_subgraph is not implemented for cpp wrapper" + ) + + def codegen_switch(self, node) -> None: + """Emit ABI-compatible C++ for a higher-order cond/switch.""" + outer_inputs = [f"{buf.codegen_reference()}" for buf in node.operands] + outer_outputs = [] + for out in node.outputs: + # in ABI-compatible mode, ir.MultiOutput is not codegened, + # hence pre-declare output variables directly and separately + self.writeline(f"RAIIAtenTensorHandle {out.get_name()};") + outer_outputs.append(out.get_name()) + + if not isinstance(node.selector, ir.ShapeAsConstantBuffer): + # use the ABI shim to extract the scalar selector value from the Tensor; + # always as int64 so the branch loop can use uniform index comparisons + # (cond: True==1, False==0) + selector_var = f"{node.selector.get_name()}_scalar" + if selector_var not in self.used_switch_selector: + self.codegen_tensor_item( + torch.int64, + node.selector.codegen_reference(), + selector_var, + ) + self.used_switch_selector.add(selector_var) + else: + # ShapeAsConstantBuffer yields a C++ bool/int expression; Cast to int64_t. + selector_var = f"static_cast({node.selector.codegen_reference()})" + + def _emit_branch(header: str, branch) -> None: + self.writeline(header) + with self._preserve_device_guard_state(): + self.writeline(EnterSubgraphLine(self, branch.graph)) + self.codegen_subgraph(branch, outer_inputs, outer_outputs) + self.writeline(ExitSubgraphLine(self)) + + def emit_switch_body() -> None: + num_branches = len(node.branches) + for b_idx, branch in enumerate(node.branches): + if b_idx == 0: + header = f"if ({selector_var} == 0) {{" + elif b_idx < num_branches - 1: + header = f"}} else if ({selector_var} == {b_idx}) {{" + else: + header = "} else {" + _emit_branch(header, branch) + self.writeline("}") + + if not V.graph.is_dual_wrapper_mode: + return emit_switch_body() + + graphs = tuple(branch.graph for branch in node.branches) + jit_code = IndentedBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._preserve_codegen_state(graphs), + self._target_buf("wrapper_call", jit_code), + self.set_writeline(jit_code, jit_code.writeline_jit), + ): + # JIT pass: visit each branch once for lazy kernel autotune + for branch in node.branches: + self.writeline("{") + with self._preserve_device_guard_state(): + self.writeline(EnterSubgraphLine(self, branch.graph)) + self.codegen_subgraph(branch, outer_inputs, outer_outputs) + self.writeline(ExitSubgraphLine(self)) + self.writeline("}") + + aot_code = AotOnlyBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._target_buf("wrapper_call", aot_code), + self.set_writeline(aot_code, aot_code.writeline_aot), + ): + emit_switch_body() + + self.writeline(DualWrapperCodeLine(jit_code, aot_code)) + + def codegen_subgraph(self, subgraph, outer_inputs, outer_outputs): + # TODO (desertfire) - This function is the old way of supporting + # subgraph codegen by inlining subgraphs in the output code. For python + # wrapper, we have moved to lifting subgraphs as functions, supported by + # PythonWrapperCode `codegen_subgraph` function. We should perhaps + # support lifting of subgraphs as functions for cpp wrapper as well. + try: + self.push_codegened_graph(subgraph.graph) + self.writeline(f"// subgraph: {subgraph.name}") + self.codegen_subgraph_prefix(subgraph, outer_inputs, outer_outputs) + parent_graph = V.graph + with V.set_graph_handler(subgraph.graph): + subgraph.graph.codegen_subgraph( + parent_graph=parent_graph, + ) + self.codegen_subgraph_suffix(subgraph, outer_inputs, outer_outputs) + finally: + self.pop_codegened_graph() + + def codegen_while_loop(self, while_loop, stack_output=False): + """Emit ABI-compatible C++ for a higher-order while_loop. + + In dual-wrapper mode, keep the real loop on the AOTI side while making + the JIT first pass visit the condition and body once for lazy autotune. + """ + if stack_output: + raise NotImplementedError("NYI cpp wrapper for while_loop_stack_output") + is_bool_pred = isinstance( + while_loop.cond_subgraph.graph.graph_outputs[0], ir.ShapeAsConstantBuffer + ) + name = while_loop.get_name() + outer_carried_inputs = [ + buf.codegen_reference() for buf in while_loop.carried_inputs + ] + outer_additional_inputs = [ + buf.codegen_reference() for buf in while_loop.additional_inputs + ] + carried_output_names = self._get_while_loop_carried_output_names(while_loop) + cond_result_name = f"{name}_cond_result" + if is_bool_pred: + self.writeline(f"bool {cond_result_name};") + else: + self.writeline(f"RAIIAtenTensorHandle {cond_result_name};") + + cond_outer_inputs = [] + for inp, out_name in zip(outer_carried_inputs, carried_output_names): + # in ABI-compatible mode, the carried inputs are codegened + # as buffers outside the while loop and set to the initial + # values. at the end of each while_loop iteration, they + # will be assigned the carried values. + self.writeline(f"AtenTensorHandle {out_name}_handle;") + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors_out({inp}, &{out_name}_handle));" + ) + self.writeline(f"RAIIAtenTensorHandle {out_name}({out_name}_handle);") + cond_outer_inputs.append(out_name) + + # additional inputs will be assigned within the while_loop + # iteration directly from the corresponding outer graph buffers + cond_outer_inputs.extend(outer_additional_inputs) + + cond_outer_outputs = [cond_result_name] + body_outer_inputs = list(cond_outer_inputs) + body_outer_outputs = body_outer_inputs[: len(outer_carried_inputs)] + + def codegen_original_while_loop() -> None: + self.writeline("while (1) {") + with self._preserve_device_guard_state(): + self.writeline(EnterSubgraphLine(self, while_loop.cond_subgraph.graph)) + self.codegen_subgraph( + while_loop.cond_subgraph, cond_outer_inputs, cond_outer_outputs + ) + + if is_bool_pred: + cond_result = f"{cond_result_name}" + else: + cond_result = f"{cond_result_name}_scalar" + self.codegen_tensor_item(torch.bool, cond_result_name, cond_result) + self.writeline(f"if (!{cond_result}) break;") + + self.writeline(ExitSubgraphLine(self)) + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + self.codegen_subgraph( + while_loop.body_subgraph, body_outer_inputs, body_outer_outputs + ) + self.writeline(ExitSubgraphLine(self)) + self.writeline("}") + + if not V.graph.is_dual_wrapper_mode: + return codegen_original_while_loop() + + graphs = ( + while_loop.cond_subgraph.graph, + while_loop.body_subgraph.graph, + ) + jit_code = IndentedBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._preserve_codegen_state(graphs), + self._target_buf("wrapper_call", jit_code), + self.set_writeline(jit_code, jit_code.writeline_jit), + ): + self.writeline("{") + with self._preserve_device_guard_state(): + self.writeline(EnterSubgraphLine(self, while_loop.cond_subgraph.graph)) + self.codegen_subgraph( + while_loop.cond_subgraph, cond_outer_inputs, cond_outer_outputs + ) + self.writeline(ExitSubgraphLine(self)) + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + self.codegen_subgraph( + while_loop.body_subgraph, body_outer_inputs, body_outer_outputs + ) + self.writeline(ExitSubgraphLine(self)) + self.writeline("}") + + aot_code = AotOnlyBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._target_buf("wrapper_call", aot_code), + self.set_writeline(aot_code, aot_code.writeline_aot), + ): + codegen_original_while_loop() + + self.writeline(DualWrapperCodeLine(jit_code, aot_code)) + + def generate_extern_kernel_args_decl_if_needed( + self, + op_overload: torch._ops.OpOverload | torch._ops.HigherOrderOperator, + raw_args: Sequence[Any], + output_args: _OUTPUT_ARGS_TYPE, + raw_outputs: Sequence[ir.Buffer], + ): + """ + Generates declarations for external kernel arguments if needed, based on the provided + operator and its arguments. It processes both input and output arguments, categorizing + them into tensor and integer arguments for further code generation. + """ + schema = None + if isinstance(op_overload, torch._higher_order_ops.torchbind.CallTorchBind): + obj = raw_args[0] + method = raw_args[1] + schema = op_overload.schema(obj, method) + else: + if not isinstance(op_overload, torch._ops.OpOverload): + raise AssertionError(type(op_overload)) + schema = op_overload._schema + if schema is None: + raise AssertionError("expected schema to be set") + arg_types = [x.real_type for x in schema.arguments] + return_types = [x.type for x in schema.returns] + + new_tensor_args = [] + new_int_args = [] + + def fill_args(arg, arg_type): + static_arg_types = ( + torch.FloatType, + torch.BoolType, + torch.StringType, + torch.Type, + torch.DeviceObjType, + ) + inductor_tensor_buffers = ( + ir.Buffer, + ir.ReinterpretView, + ) + + if isinstance(arg_type, torch.TensorType): + if not isinstance(arg, inductor_tensor_buffers): + raise AssertionError(f"got {type(arg)}") + new_tensor_args.append(f"{arg.codegen_reference()}") + elif isinstance(arg_type, torch.IntType): + # int + new_int_args.append(str(arg)) + elif isinstance(arg_type, torch.SymIntType): + # SymInt + expr = arg.node.expr if isinstance(arg, torch.SymInt) else arg + new_int_args.append(cexpr(expr)) + elif isinstance(arg_type, torch.NumberType): + # Scalar of type int + if not isinstance(arg, (int, float, bool)): + raise AssertionError( + f"expected arg to be int, float, or bool, got {type(arg)}" + ) + # Only treat int Scalar as dynamic + if isinstance(arg, int): + new_int_args.append(str(arg)) + elif isinstance(arg, ir.TorchBindObject): + # torchbind objects are loaded in proxy executor + pass + elif isinstance(arg_type, torch.ListType): + if not isinstance(arg, (list, tuple)): + raise AssertionError( + f"expected arg to be list or tuple, got {type(arg)}" + ) + + # List[Tensor] + if isinstance(arg_type.getElementType(), torch.TensorType): + new_tensor_args.extend([f"{a.codegen_reference()}" for a in arg]) + # List[Optional[Tensor]] + elif isinstance( + arg_type.getElementType(), torch.OptionalType + ) and isinstance( + arg_type.getElementType().getElementType(), torch.TensorType + ): + new_tensor_args.extend( + [f"{a.codegen_reference()}" for a in arg if a is not None] + ) + # List[int] + elif isinstance(arg_type.getElementType(), torch.IntType): + new_int_args.extend([str(a) for a in arg]) + # List[SymInt] + elif isinstance(arg_type.getElementType(), torch.SymIntType): + expressions = [ + a.node.expr if isinstance(a, torch.SymInt) else a for a in arg + ] + new_int_args.extend([cexpr(expr) for expr in expressions]) + # List[Scalar] + elif isinstance(arg_type.getElementType(), torch.NumberType): + # Only treat int Scalar as dynamic + is_int_type = [isinstance(a, int) for a in arg] + if any(is_int_type): + if not all(is_int_type): + raise AssertionError( + "AOTInductor only supports int scalars of the same type" + ) + new_int_args.extend([str(a) for a in arg]) + else: + if not isinstance( + arg_type.getElementType(), + static_arg_types, # type: ignore[arg-type] + ): + raise AssertionError( + f"Fall through arguments must be one of static_arg_types, got {type(arg_type)}" + ) + else: + if not isinstance( + arg_type, + static_arg_types, # type: ignore[arg-type] + ): + raise AssertionError( + f"Fall through arguments must be one of static_arg_types, got {type(arg_type)}" + ) + + for arg, arg_type in zip(raw_args, arg_types): + if arg is not None: + if isinstance(arg_type, torch.OptionalType): + fill_args(arg, arg_type.getElementType()) + else: + fill_args(arg, arg_type) + + def fill_output_arg( + arg: str, return_type: torch.JitType, is_mutated_output: bool + ) -> None: + if isinstance(return_type, torch.TensorType): + if not is_mutated_output: + self.writeline(f"AtenTensorHandle {arg}_handle; // output buffer") + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_uninitialized_tensor(&{arg}_handle));" + ) + self.writeline(f"RAIIAtenTensorHandle {arg}({arg}_handle);") + new_tensor_args.append(f"{arg}") + elif isinstance(return_type, torch.SymIntType): + raise NotImplementedError("NYI support for return type: SymInt") + elif isinstance(return_type, torch.ListType) and isinstance( + return_type.getElementType(), torch.SymIntType + ): + raise NotImplementedError("NYI support for return type: List[SymInt]") + else: + raise AssertionError(f"Unsupported return type found: {return_type}") + + # TODO: Only support None and tensor(s) returns for now, SymInt is not implemented yet + for return_type in return_types: + if isinstance( + return_type, (torch.TensorType, torch.NoneType, torch.IntType) + ): + pass + elif isinstance(return_type, torch.OptionalType): + if not isinstance(return_type.getElementType(), torch.TensorType): + raise AssertionError( + f"expected Optional element type to be TensorType, " + f"got {return_type.getElementType()}" + ) + elif isinstance(return_type, torch.ListType): + if not isinstance(return_type.getElementType(), torch.TensorType): + raise AssertionError( + f"expected List element type to be TensorType, " + f"got {return_type.getElementType()}" + ) + else: + raise NotImplementedError( + f"return type {return_type} is not yet supported." + ) + + for output_arg, raw_output_arg in zip(output_args, raw_outputs): # type: ignore[arg-type] + # None output is supported, but Optional return types are not yet supported + if output_arg is None: + continue + elif isinstance(raw_output_arg, int): + new_int_args.append(str(raw_output_arg)) + elif isinstance(output_arg, list): + for out in output_arg: + if out is None: + raise AssertionError(out) + fill_output_arg( + out, + torch.TensorType.get(), + isinstance(raw_output_arg, ir.MutationOutput), + ) + else: + fill_output_arg( + output_arg, + torch.TensorType.get(), + isinstance(raw_output_arg, ir.MutationOutput), + ) + + return new_tensor_args, new_int_args + + @staticmethod + def _compatible_with_stableivalue(op: torch._ops.OpOverload) -> bool: + """Returns true if op_overload._schema only utilizes types supported by the AOT + C-shim *internal* function to_ivalue. to_ivalue is an implementation detail, so + these types are not guaranteed to be supported long-term. When generating code + for cpp_wrapper mode, we don't have to be forward-compatible, so changing this + function's implementation in future is fine.""" + supported_types = ( + torch.BoolType, + torch.DeviceObjType, + torch.FloatType, + # ScalarTypeType, LayoutType, and MemoryFormatType are seen as IntType + # when queried via torch.JitType.type. + torch.IntType, + torch.TensorType, + ) + + def type_supported(t: torch.JitType) -> bool: + if isinstance(t, torch.OptionalType): + return type_supported(t.getElementType()) + return isinstance(t, supported_types) + + def uses_symint(t: torch.JitType) -> bool: + # SymInt/SymBool/SymFloat are reported as Int/Bool/Float by + # JitType.type, so they pass type_supported above. But the + # StableIValue codegen below emits no symbolic-int-aware conversion, + # so route such ops to the boxed dispatch path, which handles + # c10::SymInt correctly. real_type preserves the symbolic types. + if isinstance(t, (torch.OptionalType, torch.ListType)): + return uses_symint(t.getElementType()) + return ( + isinstance(t, (torch.SymIntType, torch.SymBoolType)) + or repr(t) == "SymFloat" + ) + + return all( + type_supported(a.type) and not uses_symint(a.real_type) + for a in chain(op._schema.arguments, op._schema.returns) + ) + + @staticmethod + def _compatible_with_cpp_boxed_dispatch(op: torch._ops.OpOverload) -> bool: + """Returns true if cpp_wrapper JIT can directly codegen c10::IValue boxing + for this schema and can unpack the returned values into tensor handles. + + Unlike the StableIValue path, this is only used for JIT cpp_wrapper, where + we can include ATen/c10 headers and call the dispatcher directly. + """ + + def arg_supported(t: torch.JitType) -> bool: + if isinstance(t, torch.OptionalType): + return arg_supported(t.getElementType()) + if isinstance(t, torch.ListType): + return arg_supported(t.getElementType()) + if isinstance(t, torch.TupleType): + return all(arg_supported(e) for e in t.elements()) + return isinstance( + t, + ( + torch.BoolType, + torch.DeviceObjType, + torch.FloatType, + torch.IntType, + torch.NumberType, + torch.StringType, + torch.SymBoolType, + torch.SymIntType, + torch.TensorType, + ), + ) or repr(t) in ("Layout", "MemoryFormat", "ScalarType", "SymFloat") + + def return_supported(t: torch.JitType) -> bool: + if isinstance(t, torch.OptionalType): + return isinstance(t.getElementType(), torch.TensorType) + return isinstance(t, (torch.NoneType, torch.TensorType)) + + return all(arg_supported(a.real_type) for a in op._schema.arguments) and all( + return_supported(r.real_type) for r in op._schema.returns + ) + + def generate_fallback_kernel_with_runtime_lookup( + self, + buf_name: str, + python_kernel_name: str, + get_args: Callable[[], Sequence[str]], + op_overload: torch._ops.OpOverload | torch._ops.HigherOrderOperator, + raw_args: Sequence[Any], + outputs: Sequence[ir.Buffer], + ) -> None: + """Generate a call to a kernel not contained in the C-shim. This results in + different code paths for AOT Inductor vs cpp_wrapper Inductor mode.""" + + def extract_output_name( + out: ir.Buffer | Sequence[ir.Buffer] | None, + ) -> str | None | _OUTPUT_ARGS_TYPE: + if out is None: + return None + if isinstance( + out, (ir.MultiOutput, ir._CollectiveKernel, ir.FallbackKernel) + ): + return out.get_name() + if isinstance(out, ir.MutationOutput): + mutated_buf_names = out.get_mutation_names() + if not ( + isinstance(mutated_buf_names, list) and len(mutated_buf_names) == 1 + ): + raise AssertionError( + "Expect only one mutated buffer in MutationOutput" + ) + return mutated_buf_names[0] + if isinstance(out, (list, tuple)): + return [extract_output_name(o) for o in out] # type: ignore[misc] + if isinstance(out, int): + return str(out) + raise AssertionError(f"Unexpected output: {type(out)}") + + if isinstance(op_overload, torch._ops.HigherOrderOperator): + if not isinstance( + op_overload, torch._higher_order_ops.torchbind.CallTorchBind + ): + raise AssertionError(type(op_overload)) + if len(raw_args) <= 1: + raise AssertionError(f"expected len(raw_args) > 1, got {len(raw_args)}") + obj = raw_args[0] + method = raw_args[1] + return_schema = op_overload.schema(obj, method).returns + else: + return_schema = op_overload._schema.returns + + # output_args has the same pytree structure as outputs + if not return_schema: + # kernel does not return a value + output_args: _OUTPUT_ARGS_TYPE = [] + elif isinstance(output_name := extract_output_name(outputs), str): + output_args = [output_name] + else: + # If the schema indicates a return value, we should have a non-None value by + # this point. + if not isinstance(output_name, list): + raise AssertionError(type(output_name)) + output_args = output_name + + # In AOT mode, we use a ProxyExecutor to run fallback kernels. + if V.graph.aot_mode and V.graph.is_dual_wrapper_mode: + jit_code = IndentedBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._target_buf("wrapper_call", jit_code), + self.set_writeline(jit_code, jit_code.writeline_jit), + ): + self._generate_fallback_kernel_jit( + buf_name, + python_kernel_name, + get_args, + op_overload, + raw_args, + output_args, + outputs, + ) + + aot_code = AotOnlyBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._target_buf("wrapper_call", aot_code), + self.set_writeline(aot_code, aot_code.writeline_aot), + ): + self.generate_fallback_kernel_with_runtime_lookup_aot( + op_overload, + raw_args, + output_args, + outputs, + ) + + self.writeline(DualWrapperCodeLine(jit_code, aot_code)) + return + + if V.graph.aot_mode: + self.generate_fallback_kernel_with_runtime_lookup_aot( + op_overload, + raw_args, + output_args, + outputs, + ) + + if not V.graph.aot_mode: + self._generate_fallback_kernel_jit( + buf_name, + python_kernel_name, + get_args, + op_overload, + raw_args, + output_args, + outputs, + ) + + def _generate_fallback_kernel_jit( + self, + buf_name, + python_kernel_name, + get_args, + op_overload, + raw_args, + output_args, + outputs, + ): + """Emit JIT-mode fallback kernel code (no-Python dispatcher or Python callback).""" + if not isinstance(op_overload, torch._ops.OpOverload): + raise AssertionError(type(op_overload)) + for output in output_args: + if not (output is None or isinstance(output, str)): + raise AssertionError( + "fallback kernels with runtime lookup currently only support tensor " + "returns, not more complicated types (such as list-of-list-of-tensor)" + ) + + # In non-AOT mode, we use aoti_torch_call_dispatcher if all the inputs and + # outputs of the op can be represented with StableIValue. This avoids the + # overhead of calling back into Python, and covers most remaining fallback ops. + if self._compatible_with_stableivalue(op_overload): + self.generate_fallback_kernel_with_runtime_lookup_nopython( + get_args, + op_overload, + output_args, # type: ignore[arg-type] + outputs, + ) + return + + # For cpp_wrapper JIT, fall back to direct boxed dispatcher calls for + # schemas the StableIValue bridge cannot represent, such as Tensor[]. + if self._compatible_with_cpp_boxed_dispatch(op_overload): + self.generate_fallback_kernel_with_runtime_lookup_boxed( + op_overload, + raw_args, + output_args, # type: ignore[arg-type] + outputs, + ) + return + + # Otherwise, we call back into Python, which has some extra runtime overhead, + # but handles situations like list[Tensor] (currently unrepresentable via + # StableIValue). + self.generate_fallback_kernel_with_runtime_lookup_python( + buf_name, + python_kernel_name, + op_overload, + raw_args, + output_args, # type: ignore[arg-type] + outputs, + ) + + def generate_scoped_gil_acquire(self, declarations_before_scope, lines_in_scope): + scoped_lines = IndentedBuffer() + for declaration in declarations_before_scope: + scoped_lines.writeline(declaration) + + scoped_lines.writeline("{") + with scoped_lines.indent(): + scoped_lines.writeline("py::gil_scoped_acquire_simple acquire;") + scoped_lines.writelines(lines_in_scope.split("\n")) + scoped_lines.writelines("}") + return scoped_lines._lines + + def load_custom_op_wrapper(self): + # TODO: need to support control flow + if self.custom_op_wrapper_loaded: + return + + lines = """ +RAIIPyObject codecache_module(PyImport_ImportModule("torch._inductor.codecache")); +if (!codecache_module) { + throw std::runtime_error("Failed to load torch._inductor.codecache"); +} +custom_op_wrapper = PyObject_GetAttrString(codecache_module, "custom_op_wrapper"); +if (!custom_op_wrapper) { + throw std::runtime_error("Failed to load torch._inductor.codecache.custom_op_wrapper"); +}""" + + declarations_before_scope = ["RAIIPyObject custom_op_wrapper;"] + scope_gil_acquire = self.generate_scoped_gil_acquire( + declarations_before_scope, lines + ) + self.writelines(scope_gil_acquire) + + self.custom_op_wrapper_loaded = True + + def generate_float_value(self, val): + if not isinstance(val, float): + raise AssertionError(f"expected val to be float, got {type(val)}") + if val == float("inf"): + return "std::numeric_limits::infinity()" + elif val == float("-inf"): + return "-std::numeric_limits::infinity()" + elif math.isnan(val): + return "std::numeric_limits::quiet_NaN()" + else: + return f"{val}" + + def generate_py_arg(self, py_args_var, idx, raw_arg, arg_type): + """Generate C++ code that converts a single operator argument into a Python + object and inserts it into a PyTuple at the given index.""" + + def generate_py_arg_inner(lines, raw_arg, arg_type): + def handle_scalar(scalar): + if isinstance(scalar, bool): + return f"PyBool_FromLong({1 if scalar else 0})" + if isinstance(scalar, int): + return f"PyLong_FromLongLong({scalar})" + if isinstance(scalar, float): + return f"PyFloat_FromDouble({self.generate_float_value(scalar)})" + if isinstance(scalar, complex): + real = self.generate_float_value(scalar.real) + imag = self.generate_float_value(scalar.imag) + return f"PyComplex_FromDoubles({real}, {imag})" + if isinstance(scalar, SymTypes): + scalar_var = cexpr(scalar.node.expr) + if isinstance(scalar, torch.SymBool): + return f"PyBool_FromLong({scalar_var})" + if isinstance(scalar, torch.SymFloat): + return f"PyFloat_FromDouble({scalar_var})" + return f"PyLong_FromLongLong({scalar_var})" + raise NotImplementedError( + f"scalar {scalar}, {type(scalar)} cannot be handled by handle_scalar" + ) + + is_any = isinstance(arg_type, torch.AnyType) + + def handle_any(types: type | tuple[type, ...]): + return is_any and isinstance(raw_arg, types) + + if raw_arg is None: + # Py_None is a singleton, so we have to explicitly incref it here + lines.append("Py_INCREF(Py_None);\n") + return "Py_None" + elif isinstance(arg_type, torch.TensorType) or handle_any(ir.IRNode): + # In some cases, scalar arguments may be passed in place of tensors. + if not hasattr(raw_arg, "codegen_reference"): + return handle_scalar(raw_arg) + + # Store AtenTensorHandle as void*. All Python args are constructed in a + # nested scope, so this handle will self-destruct after the function + # call. + base_handle = self.create_tmp_raii_handle_var_if_needed( + raw_arg.codegen_reference(), lines + ) + return f"PyCapsule_New(reinterpret_cast({base_handle}.get()), NULL, NULL)" + elif isinstance(arg_type, torch.OptionalType): + return generate_py_arg_inner(lines, raw_arg, arg_type.getElementType()) + elif isinstance(arg_type, torch.BoolType) or handle_any(bool): + return f"PyBool_FromLong({1 if raw_arg else 0})" + elif isinstance(arg_type, torch.IntType) or handle_any(int): + # int + return f"PyLong_FromLongLong({raw_arg})" + elif isinstance(arg_type, torch.SymIntType) or handle_any(torch.SymInt): + # SymInt + expr = ( + raw_arg.node.expr if isinstance(raw_arg, torch.SymInt) else raw_arg + ) + return f"PyLong_FromLongLong({cexpr(expr)})" + elif isinstance(arg_type, torch.FloatType) or handle_any(float): + return f"PyFloat_FromDouble({self.generate_float_value(raw_arg)})" + elif isinstance(arg_type, torch.StringType) or handle_any(str): + return f'PyUnicode_FromString("{raw_arg}")' + elif isinstance(arg_type, torch.NumberType) or handle_any( + (*SymTypes, torch.types.Number, complex) + ): + # Union[bool, int, float, complex] + # torch/_prims_common/__init__.py + return handle_scalar(raw_arg) + elif isinstance(raw_arg, torch.device): + device_str, device_index = self.codegen_device(raw_arg).split(", ") + return f"torch_python_thp_device_new({device_str}, {device_index})" + elif isinstance(raw_arg, torch.dtype): + return f"torch_python_get_thp_dtype({self.codegen_dtype(raw_arg)})" + elif isinstance(raw_arg, torch.layout): + return f"torch_python_get_thp_layout({self.codegen_layout(raw_arg)})" + elif isinstance(raw_arg, torch.memory_format): + return ( + "torch_python_get_thp_memory_format(" + f"{self.codegen_memory_format(raw_arg)})" + ) + else: + raise NotImplementedError( + f"arg type {arg_type} is not yet supported by custom_op_wrapper" + ) + + def handle_sequence_arg(raw_arg_, arg_type_, lines_): + if not isinstance(raw_arg_, (list, tuple)): + raise AssertionError(str(raw_arg) + " is not a list") + lines_.append( + f"PyObject* {py_args_var}_{idx} = PyList_New({len(raw_arg)});\n" + ) + for i, elem in enumerate(raw_arg_): + lines_.append( + f"PyList_SetItem({py_args_var}_{idx}, {i}, {generate_py_arg_inner(lines, elem, arg_type_.getElementType())});\n" + ) + lines_.append( + f"PyTuple_SetItem({py_args_var}, {idx}, {py_args_var}_{idx});\n" + ) + + lines = [] + if isinstance(arg_type, torch.ListType): + handle_sequence_arg(raw_arg, arg_type, lines) + elif isinstance(arg_type, torch.OptionalType) and isinstance( + arg_type.getElementType(), torch.ListType + ): + if raw_arg is None: + lines.append( + f"PyTuple_SetItem({py_args_var}, {idx}, {generate_py_arg_inner(lines, raw_arg, arg_type)});\n" + ) + else: + handle_sequence_arg(raw_arg, arg_type.getElementType(), lines) + else: + lines.append( + f"PyTuple_SetItem({py_args_var}, {idx}, {generate_py_arg_inner(lines, raw_arg, arg_type)});\n" + ) + return "".join(lines) + + def generate_fallback_kernel_with_runtime_lookup_nopython( + self, + get_args: Callable[[], Sequence[str]], + op_overload: torch._ops.OpOverload, + output_args: Sequence[str | None], + raw_outputs: Sequence[ir.Buffer], + ) -> None: + """Generate fallback kernel calls with runtime (non-AOT) dispatch. This can + only be called in cpp_wrapper mode, and assumes that the input is a non-None + OpOverload. + + In the future, we may switch over to directly calling c10::Dispatcher if we need + to support more datatypes.""" + if raw_outputs: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg, raw_output_arg in zip(output_args, raw_outputs) # type: ignore[arg-type] + if output_arg is not None + and not isinstance(raw_output_arg, ir.MutationOutput) + ] + else: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg in output_args # type: ignore[arg-type] + if output_arg is not None + ] + + dispatch_lines = IndentedBuffer() + dispatch_lines.writelines(declarations_before_scope) + dispatch_lines.writeline("{") + + with dispatch_lines.indent(): + tmp_var_number = count() + + def parse_arg(arg_type: torch.JitType, codegen_arg: str) -> str: + # Strip off any temporary references; we're in an indented context, so + # any saved-off variables will be auto-destroyed. + new_codegen_arg = codegen_arg.removeprefix("&temporary_reference(") + if new_codegen_arg != codegen_arg: + # If we removed temporary_reference, there's a good chance the + # variable ends with get() (which would retrieve an ATenTensorHandle + # from a temporary RAII handle). Strip that off too, since we're + # going to save this in a temporary RAII handle. + if codegen_arg.endswith(".get())"): + codegen_arg = new_codegen_arg.removesuffix(".get())") + else: + codegen_arg = new_codegen_arg.removesuffix(")") + + if isinstance(arg_type, torch.OptionalType): + # If we have a pointer to a variable, strip it off and let + # from handle any internal pointers. + codegen_arg = codegen_arg.removeprefix("&") + + if codegen_arg == "nullptr": + return "torch::stable::detail::from(std::nullopt)" + + var_name = f"tmp_var_{next(tmp_var_number)}" + dispatch_lines.writeline( + f"std::optional {var_name}{{{parse_arg(arg_type.getElementType(), codegen_arg)}}};" + ) + return f"torch::stable::detail::from({var_name})" + + raii_var = self.create_tmp_raii_handle_var_if_needed( + codegen_arg, dispatch_lines + ) + temp_handle = raii_var != codegen_arg + + if isinstance(arg_type, torch.TensorType): + if not temp_handle: + # If the RAII tensor being referenced _isn't_ a temporary, + # scoped to this fallback call, then create a new handle + # referencing it which from can steal. + var_name = f"tmp_var_{next(tmp_var_number)}" + dispatch_lines.writeline(f"AtenTensorHandle {var_name};") + dispatch_lines.writeline( + "AOTI_TORCH_ERROR_CODE_CHECK(" + f"aoti_torch_new_tensor_handle({raii_var}, &{var_name}));" + ) + return f"torch::stable::detail::from({var_name})" + # If the RAII tensor _is_ a temporary scoped to this fallback call, + # simply release and steal the handle. + return f"torch::stable::detail::from({raii_var}.release())" + return f"torch::stable::detail::from({codegen_arg})" + + codegen_args = get_args() + ivalue_args = ( + parse_arg(a.type, c) + for a, c in zip(op_overload._schema.arguments, codegen_args) + ) + array_len = max(len(codegen_args), len(output_args)) + dispatch_lines.writeline( + f"std::array dispatch_vars{{{', '.join(ivalue_args)}}};" + ) + dispatch_lines.writeline("AOTI_TORCH_ERROR_CODE_CHECK(") + with dispatch_lines.indent(): + dispatch_lines.writeline( + f'aoti_torch_call_dispatcher("{op_overload._schema.name}", "{op_overload._schema.overload_name}", dispatch_vars.data())' + ) + dispatch_lines.writeline(");") + + # assign result(s), ignoring None + for idx, output_arg in enumerate(output_args): + if output_arg is None: + continue + dispatch_lines.writeline( + f"{output_arg} = torch::stable::detail::to(dispatch_vars[{idx}]);" + ) + + dispatch_lines.writeline("}") + self.writelines(dispatch_lines.getvalue().splitlines()) + + def generate_fallback_kernel_with_runtime_lookup_boxed( + self, + op_overload: torch._ops.OpOverload, + raw_args: Sequence[Any], + output_args: Sequence[str | None], + raw_outputs: Sequence[ir.Buffer], + ) -> None: + """Generate a JIT-only fallback call through c10::Dispatcher. + + This covers custom C++ ops whose schemas are outside StableIValue's + supported subset without routing through Python. + """ + self.include_extra_header("ATen/core/dispatch/Dispatcher.h") + self.include_extra_header("ATen/core/ivalue.h") + self.include_extra_header("ATen/core/jit_type.h") + self.include_extra_header("torch/csrc/inductor/aoti_torch/utils.h") + + if raw_outputs: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg, raw_output_arg in zip(output_args, raw_outputs) + if output_arg is not None + and not isinstance(raw_output_arg, ir.MutationOutput) + ] + else: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg in output_args + if output_arg is not None + ] + + dispatch_lines = IndentedBuffer() + dispatch_lines.writelines(declarations_before_scope) + dispatch_lines.writeline("{") + + with dispatch_lines.indent(): + tmp_var_number = count() + + def next_tmp(prefix: str) -> str: + return f"{prefix}_{next(tmp_var_number)}" + + def type_expr(t: torch.JitType) -> str: + if isinstance(t, torch.OptionalType): + return f"c10::OptionalType::create({type_expr(t.getElementType())})" + if isinstance(t, torch.ListType): + return f"c10::ListType::create({type_expr(t.getElementType())})" + if isinstance(t, torch.TupleType): + elems = ", ".join(type_expr(e) for e in t.elements()) + var_name = next_tmp("tmp_type") + dispatch_lines.writeline( + f"std::vector {var_name}{{{elems}}};" + ) + return f"c10::TupleType::create(std::move({var_name}))" + if isinstance(t, torch.BoolType): + return "c10::BoolType::get()" + if isinstance(t, torch.DeviceObjType): + return "c10::DeviceObjType::get()" + if isinstance(t, torch.FloatType): + return "c10::FloatType::get()" + if isinstance(t, torch.IntType): + return "c10::IntType::get()" + if isinstance(t, torch.NumberType): + return "c10::NumberType::get()" + if isinstance(t, torch.StringType): + return "c10::StringType::get()" + if isinstance(t, torch.SymBoolType): + return "c10::SymBoolType::get()" + if isinstance(t, torch.SymIntType): + return "c10::SymIntType::get()" + if isinstance(t, torch.TensorType): + return "c10::TensorType::get()" + type_repr = repr(t) + if type_repr == "Layout": + return "c10::LayoutType::get()" + if type_repr == "MemoryFormat": + return "c10::MemoryFormatType::get()" + if type_repr == "ScalarType": + return "c10::ScalarTypeType::get()" + if type_repr == "SymFloat": + return "c10::SymFloatType::get()" + raise AssertionError(f"Unsupported list element type: {t}") + + def codegen_memory_format(memory_format: torch.memory_format) -> str: + return { + torch.contiguous_format: "c10::MemoryFormat::Contiguous", + torch.channels_last: "c10::MemoryFormat::ChannelsLast", + torch.channels_last_3d: "c10::MemoryFormat::ChannelsLast3d", + torch.preserve_format: "c10::MemoryFormat::Preserve", + }[memory_format] + + def codegen_tensor_ivalue(raw_arg: Any, arg_type: torch.JitType) -> str: + if hasattr(raw_arg, "codegen_reference"): + codegen_arg = raw_arg.codegen_reference() + else: + codegen_arg = self.val_to_arg_str(raw_arg, arg_type) + + raii_var = self.create_tmp_raii_handle_var_if_needed( + codegen_arg, dispatch_lines + ) + return ( + "c10::IValue(*torch::aot_inductor::" + f"tensor_handle_to_tensor_pointer({raii_var}))" + ) + + def codegen_ivalue(raw_arg: Any, arg_type: torch.JitType) -> str: + if raw_arg is None: + # A None at a non-optional Tensor arg means an absent tensor. + # Box it as an undefined at::Tensor (ATen's absent-tensor + # sentinel, matching eager value_or(Tensor())); boxing None + # would fail to unbox as `const Tensor&`. Optionals stay None. + if isinstance(arg_type, torch.TensorType): + return "c10::IValue(at::Tensor())" + return "c10::IValue()" + + if isinstance(arg_type, torch.OptionalType): + return codegen_ivalue(raw_arg, arg_type.getElementType()) + + if isinstance(raw_arg, torch.device): + if raw_arg.type not in DEVICE_TO_ATEN: + raise AssertionError( + raw_arg.type + " not found in DEVICE_TO_ATEN" + ) + return ( + "c10::IValue(c10::Device(" + f"{DEVICE_TO_ATEN[raw_arg.type]}, " + f"{raw_arg.index if raw_arg.index is not None else 0}))" + ) + if isinstance(raw_arg, torch.dtype): + return f"c10::IValue({DTYPE_TO_ATEN[raw_arg]})" + if isinstance(raw_arg, torch.layout): + return f"c10::IValue({LAYOUT_TO_ATEN[raw_arg]})" + if isinstance(raw_arg, torch.memory_format): + return f"c10::IValue({codegen_memory_format(raw_arg)})" + + if isinstance(arg_type, torch.TensorType): + return codegen_tensor_ivalue(raw_arg, arg_type) + + if isinstance(arg_type, torch.ListType): + if not isinstance(raw_arg, (list, tuple)): + raise AssertionError(type(raw_arg)) + list_var = next_tmp("tmp_list") + elem_type = arg_type.getElementType() + dispatch_lines.writeline( + f"c10::impl::GenericList {list_var}({type_expr(elem_type)});" + ) + dispatch_lines.writeline(f"{list_var}.reserve({len(raw_arg)});") + for elem in raw_arg: + dispatch_lines.writeline( + f"{list_var}.emplace_back({codegen_ivalue(elem, elem_type)});" + ) + return f"c10::IValue(std::move({list_var}))" + + if isinstance(arg_type, torch.TupleType): + if not isinstance(raw_arg, (list, tuple)): + raise AssertionError(type(raw_arg)) + tuple_var = next_tmp("tmp_tuple") + dispatch_lines.writeline(f"std::vector {tuple_var};") + dispatch_lines.writeline(f"{tuple_var}.reserve({len(raw_arg)});") + for elem, elem_type in zip(raw_arg, arg_type.elements()): + dispatch_lines.writeline( + f"{tuple_var}.emplace_back({codegen_ivalue(elem, elem_type)});" + ) + return ( + "c10::IValue(c10::ivalue::Tuple::create(" + f"std::move({tuple_var})))" + ) + + if isinstance(arg_type, torch.BoolType): + return ( + "c10::IValue(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, bool)}))" + ) + if isinstance(arg_type, torch.IntType): + return ( + "c10::IValue(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, int)}))" + ) + if isinstance(arg_type, torch.FloatType): + return ( + "c10::IValue(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, float)}))" + ) + if isinstance(arg_type, torch.StringType): + return ( + "c10::IValue(std::string(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, str)}))" + ) + if isinstance(arg_type, torch.SymBoolType): + return ( + "c10::IValue(c10::SymBool(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, bool)})))" + ) + if isinstance(arg_type, torch.SymIntType): + return ( + "c10::IValue(c10::SymInt(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, int)})))" + ) + if isinstance(arg_type, torch.NumberType): + return f"c10::IValue({self.val_to_arg_str_for_prim_type(raw_arg, None)})" + + arg_type_repr = repr(arg_type) + if arg_type_repr == "Layout": + if not isinstance(raw_arg, torch.layout): + raise AssertionError(type(raw_arg)) + return f"c10::IValue({LAYOUT_TO_ATEN[raw_arg]})" + if arg_type_repr == "MemoryFormat": + if not isinstance(raw_arg, torch.memory_format): + raise AssertionError(type(raw_arg)) + return f"c10::IValue({codegen_memory_format(raw_arg)})" + if arg_type_repr == "ScalarType": + if not isinstance(raw_arg, torch.dtype): + raise AssertionError(type(raw_arg)) + return f"c10::IValue({DTYPE_TO_ATEN[raw_arg]})" + if arg_type_repr == "SymFloat": + return ( + "c10::IValue(c10::SymFloat(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, float)})))" + ) + + raise AssertionError(f"Unsupported boxed dispatcher arg: {arg_type}") + + stack_var = next_tmp("dispatch_stack") + dispatch_lines.writeline(f"std::vector {stack_var};") + dispatch_lines.writeline( + f"{stack_var}.reserve({len(op_overload._schema.arguments)});" + ) + for raw_arg, schema_arg in zip(raw_args, op_overload._schema.arguments): + dispatch_lines.writeline( + f"{stack_var}.emplace_back({codegen_ivalue(raw_arg, schema_arg.real_type)});" + ) + + dispatch_lines.writeline( + "static auto op = c10::Dispatcher::singleton().findSchemaOrThrow(" + f'"{op_overload._schema.name}", "{op_overload._schema.overload_name}");' + ) + dispatch_lines.writeline(f"op.callBoxed(&{stack_var});") + + stack_idx = 0 + for output_arg, raw_output_arg in zip(output_args, raw_outputs): + if isinstance(raw_output_arg, ir.MutationOutput): + continue + if output_arg is not None: + dispatch_lines.writeline( + f"{output_arg} = torch::aot_inductor::new_tensor_handle(" + f"std::move({stack_var}[{stack_idx}]).toTensor());" + ) + stack_idx += 1 + + dispatch_lines.writeline("}") + self.writelines(dispatch_lines.getvalue().splitlines()) + + def generate_fallback_kernel_with_runtime_lookup_python( + self, + buf_name: str, + python_kernel_name: str, + op_overload: torch._ops.OpOverload, + raw_args: Sequence[Any], + output_args: Sequence[str | None], + raw_outputs: Sequence[ir.Buffer], + ) -> None: + """Generate fallback kernel calls with runtime (non-AOT) dispatch. This can + only be called in cpp_wrapper mode, and assumes that the input is a non-None + OpOverload. + + This function calls into Python to dispatch, which allows it to handle datatypes + that cannot be contained in StableIValue, at the cost of some performance.""" + self.load_custom_op_wrapper() + + num_args = len(raw_args) + py_args_var = f"py_args_{next(self.arg_var_id)}" + # First arg is always the python op name + lines = textwrap.dedent(f""" + RAIIPyObject {py_args_var}(PyTuple_New({num_args + 1})); + if (!{py_args_var}) {{ + throw std::runtime_error("PyTuple_New {py_args_var} failed"); + }} + PyTuple_SetItem({py_args_var}, 0, PyUnicode_FromString("{python_kernel_name}")); + """) + + for idx, (raw_arg, schema_arg) in enumerate( + zip(raw_args, op_overload._schema.arguments) + ): + lines += self.generate_py_arg( + py_args_var, idx + 1, raw_arg, schema_arg.real_type + ) + + lines += textwrap.dedent(f""" + // Call the custom op in Python + RAIIPyObject py_{buf_name}(PyObject_CallObject(custom_op_wrapper, {py_args_var})); + if (!py_{buf_name}) {{ + if (PyErr_Occurred()) {{ + return; + }} + throw std::runtime_error("PyObject_CallObject {python_kernel_name} failed"); + }} + """) + + if raw_outputs: + num_returned_outputs = 0 + returned_output_slots = [] + for output_arg, raw_output_arg in zip(output_args, raw_outputs): + if isinstance(raw_output_arg, ir.MutationOutput): + continue + if output_arg is not None: + returned_output_slots.append((num_returned_outputs, output_arg)) + num_returned_outputs += 1 + else: + num_returned_outputs = len(output_args) + returned_output_slots = [ + (idx, output_arg) + for idx, output_arg in enumerate(output_args) + if output_arg is not None + ] + + # custom_op_wrapper returns a bare capsule only for a single, non-list + # Tensor return. A Tensor[] return (even of length 1) or multiple returns + # come back as a Python list that must be indexed with PyList_GET_ITEM. + schema_returns = op_overload._schema.returns + returns_python_list = len(schema_returns) != 1 or isinstance( + schema_returns[0].real_type, torch.ListType + ) + if ( + num_returned_outputs == 1 + and returned_output_slots + and not returns_python_list + ): + # result is a single tensor + _, output = returned_output_slots[0] + lines += f"{output} = reinterpret_cast(PyCapsule_GetPointer(py_{buf_name}.get(), NULL));\n" + else: + # result is a list of tensors (Tensor[] or multiple returns) + for idx, output_arg in returned_output_slots: + lines += f"{output_arg} = reinterpret_cast(PyCapsule_GetPointer(PyList_GET_ITEM(py_{buf_name}.get(), {idx}), NULL));\n" + + if raw_outputs: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg, raw_output_arg in zip(output_args, raw_outputs) # type: ignore[arg-type] + if output_arg is not None + and not isinstance(raw_output_arg, ir.MutationOutput) + ] + else: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg in output_args # type: ignore[arg-type] + if output_arg is not None + ] + scope_gil_acquire = self.generate_scoped_gil_acquire( + declarations_before_scope, lines + ) + self.writelines(scope_gil_acquire) + + def generate_fallback_kernel_with_runtime_lookup_aot( + self, + op_overload: torch._ops.OpOverload | torch._ops.HigherOrderOperator, + raw_args: Sequence[Any], + output_args: _OUTPUT_ARGS_TYPE, + raw_outputs: Sequence[ir.Buffer], + ) -> None: + ( + tensor_call_args, + int_call_args, + ) = self.generate_extern_kernel_args_decl_if_needed( + op_overload, + raw_args, + output_args, + raw_outputs, + ) + # force both temporary arrays to generate mutable data pointers, since the proxy + # executor signature requires that datatype + int_call_str = self._generate_temporary_array_pointer( + "int64_t", int_call_args, force_mutable=True + ) + tensor_call_args = self.codegen_runtime_lookup_tensor_call_args( + tensor_call_args + ) + tensor_call_str = self._generate_temporary_array_pointer( + "AtenTensorHandle", tensor_call_args, force_mutable=True + ) + + extern_kernel_node_index = len(V.extern_kernel_nodes) - 1 + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_proxy_executor_call_function(proxy_executor, " + f"{extern_kernel_node_index}, " + f"{len(int_call_args)}, " + f"{int_call_str}, " + f"{len(tensor_call_args)}, " + f"{tensor_call_str}));" + ) + + def codegen_runtime_lookup_tensor_call_args( + self, tensor_call_args: Sequence[str] + ) -> Sequence[str]: + return tensor_call_args + + def generate_reset_kernel_saved_flags(self): + pass + + def generate_save_uncompiled_kernels(self): + pass + + def c_type_for_prim_type(self, val, type_) -> str: + if isinstance(type_, torch.OptionalType): + return f"{self.c_type_for_prim_type(val, type_.getElementType())}*" + elif isinstance(type_, torch.TensorType): + return "AtenTensorHandle" + elif isinstance(type_, (torch.IntType, torch.SymIntType)): + return "int64_t" + elif isinstance( + type_, (torch.BoolType, torch.SymBoolType, torch.EnumType) + ) or repr(type_) in ("Layout", "MemoryFormat", "ScalarType"): + return "int32_t" + elif isinstance(type_, torch.FloatType): + return "double" + elif isinstance(type_, torch.NumberType): + if isinstance(val, bool): + return "int32_t" + elif isinstance(val, (int, float)): + return "double" + elif val is None: + # This could happen when val is an optional value + return "double" + else: + raise AssertionError( + f"Unexpected type in c_type_for_prim_type: {type_=}" + ) + elif isinstance(type_, torch.StringType): + return "const char*" + else: + raise AssertionError(f"Unexpected type in c_type_for_prim_type: {type_=}") + + def val_to_arg_str_for_prim_type(self, val, type_) -> str: + # TODO: not using type_ as the first step of refactoring. Will update this later. + if isinstance(val, bool): + return "1" if val else "0" + elif isinstance(val, int): + # uint64_t is long on Linux, but long long on MacOS and Windows + return f"{val}LL" if sys.platform in ["darwin", "win32"] else f"{val}L" + elif isinstance(val, complex): + return f"c10::complex{{ {self.generate_float_value(val.real)}, {self.generate_float_value(val.imag)} }}" + elif isinstance(val, str): + return f'"{val}"' + elif isinstance( + val, (ir.Buffer, ir.ReinterpretView, ir.StorageBox, ir.TensorBox) + ): + return val.codegen_reference() + elif isinstance(val, torch.device): + return self.codegen_device(val) + elif isinstance(val, torch.dtype): + return self.codegen_dtype(val) + elif isinstance(val, torch.layout): + return self.codegen_layout(val) + elif isinstance(val, torch.memory_format): + return self.codegen_memory_format(val) + elif isinstance(val, float): + return self.generate_float_value(val) + elif isinstance(val, (list, tuple)): + # FIXME: This happens because type_ is not always properly set to torch.ListType + return f"{{{', '.join(self.val_to_arg_str(x, None) for x in val)}}}" + elif isinstance(val, SymTypes): + return cexpr(val.node.expr) + elif isinstance(val, sympy.Expr): + return cexpr(val) + else: + return repr(val) + + def val_to_arg_str(self, val, type_=None) -> str: + if val is None: + # None needs special care. It either represent nullopt or an empty tensor + if type_ is None or isinstance(type_, torch.OptionalType): + if type_ is not None and isinstance( + type_.getElementType(), + ( + torch.DeviceObjType, + torch.ListType, + torch.TupleType, + ), + ): + return "nullptr, 0" + return "nullptr" + + if isinstance(type_, torch.TensorType): + # create an empty tensor, the equivalent of at::Tensor() + var_name = f"var_{next(self.arg_var_id)}" + self.writeline(f"AtenTensorHandle {var_name}_handle;") + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_uninitialized_tensor(&{var_name}_handle));" + ) + self.writeline(f"RAIIAtenTensorHandle {var_name}({var_name}_handle);") + return var_name + + raise AssertionError("Can not map None to a known data type") + + if isinstance(type_, torch.OptionalType): + element_type = type_.getElementType() + arg_str = self.val_to_arg_str(val, element_type) + # Handle optional iterables as a special case. Utilize the + # temporary_reference function to avoid saving them off and increasing + # memory usage. + if isinstance(element_type, (torch.ListType, torch.TupleType)): + main_value, aux = arg_str.rsplit(", ", maxsplit=1) + return f"&temporary_reference({main_value}), {aux}" + + # Handle optional tensors as a special case, as above. + if isinstance(element_type, torch.TensorType): + base_handle = self.val_to_arg_str(val, element_type) + return f"&temporary_reference({base_handle}.get())" + + var_name = f"var_{next(self.arg_var_id)}" + if isinstance(element_type, torch.DeviceObjType): + main_value, aux = arg_str.rsplit(", ", maxsplit=1) + self.writeline(f"auto {var_name} = {main_value};") + return f"&{var_name}, {aux}" + + self.writeline( + f"{self.c_type_for_prim_type(val, element_type)} {var_name} = {arg_str};" + ) + return f"&{var_name}" + + if isinstance(type_, (torch.ListType, torch.TupleType)): + if not isinstance(val, (list, tuple)): + raise AssertionError(f"{val} does not match with arg type {type_}") + element_type = type_.getElementType() + + if len(val) == 0: + # Zero-size array is not supported in the C or C++ standard, so return a + # nullptr. + return "nullptr, 0" + + result = [self.val_to_arg_str(x, element_type) for x in val] + if isinstance(element_type, torch.TensorType): + result = [f"{t}.get()" for t in result] + + c_type = self.c_type_for_prim_type(val[0], element_type) + # see the comment in self._generate_temporary_array_pointer for an + # explanation of why this c_type gets modified + if isinstance(element_type, torch.OptionalType) and not c_type.startswith( + "const" + ): + c_type = f"const {c_type}" + + # need to pass the array length, because we can't use the std::array member + # function + return ( + f"{self._generate_temporary_array_pointer(c_type, result)}, {len(val)}" + ) + + val_is_scalar = isinstance(val, (bool, complex, float, int, *SymTypes)) + if isinstance(type_, torch.TensorType) and val_is_scalar: + val_str = self.val_to_arg_str_for_prim_type(val, None) + return self.codegen_scalar_to_tensor(val_str) + + return self.val_to_arg_str_for_prim_type(val, type_) + + def create_tmp_raii_handle_var_if_needed( + self, handle: str, writer: HasWriteLine | list[str] | None = None + ) -> str: + """If the input handle is an rvalue RAII tensor, creates an lvalue variable for + it in writer. Returns a variable name that can be used to access handle.""" + if not handle.startswith( + ( + "borrow_arrayref_tensor_as_tensor(", + "copy_arrayref_tensor_to_tensor(", + "wrap_with_raii_handle_if_needed(", + "RAIIAtenTensorHandle(", + ) + ): + return handle + + tmp_var_name = f"var_{next(self.arg_var_id)}" + call_str = f"auto {tmp_var_name} = {handle};" + + if writer is None: + self.writeline(call_str) + elif isinstance(writer, list): + writer.append(call_str) + else: + writer.writeline(call_str) + + return tmp_var_name + + def write_kernel_context_guard_begin( + self, + ): + # Beginning of a kernel context guarded block. + # The block looks like this: + # { + # KernelContextGuard _ctx("{kernel_name}", {stack_trace_str}); + # ... operations... + # } + self.writeline("{") + + def write_kernel_context_guard_end( + self, + ): + # End of a kernel context guarded block. + self.writeline("}") + + def write_kernel_context_guard( + self, + kernel_name: str, + node_schedule: Sequence[BaseSchedulerNode] | ExternKernel, + ): + def aggregate_stack_traces( + node_schedule: Sequence[BaseSchedulerNode] | ExternKernel, + ) -> OrderedSet[str]: + if isinstance(node_schedule, list): + return functools.reduce( + lambda a, b: a | b, + [ + # pyrefly: ignore [missing-attribute] + node.node.get_stack_traces() + for node in node_schedule + if hasattr(node, "node") and node.node + ], + OrderedSet(), + ) + elif isinstance(node_schedule, ExternKernel): + return node_schedule.get_stack_traces() + else: + return OrderedSet() + + stack_trace_str = 'R"(' + stack_traces = aggregate_stack_traces(node_schedule) + + for stack_trace in stack_traces: + for line in stack_trace.split("\n"): + stack_trace_str += f"\n{line}" + stack_trace_str += "\n" + stack_trace_str += ')"' + self.writeline(f'KernelContextGuard _ctx("{kernel_name}", {stack_trace_str});') diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu_array_ref.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu_array_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..270b9fee9544e6d75311bd99fce78aba1a0fca70 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu_array_ref.py @@ -0,0 +1,1254 @@ +# mypy: allow-untyped-defs +from collections.abc import Callable, Sequence +from typing import Any + +import sympy + +import torch +import torch._inductor.async_compile +import torch._ops +from torch.utils._ordered_set import OrderedSet + +from .. import config, ir +from ..utils import IndentedBuffer, sympy_product +from ..virtualized import V +from .cpp_utils import DTYPE_TO_CPP +from .cpp_wrapper_cpu import CppWrapperCpu +from .wrapper import ( + BufferLike, + EnterSubgraphLine, + ExitSubgraphLine, + MemoryPlanningLine, + MemoryPlanningState, + PythonWrapperCodegen, +) + + +BufferName = str + +# Default thread stack sizes vary by platform: +# - Linux: 8 MB +# - macOS: 512 KB +# - Windows: 1 MB +# Just pick something comfortably smaller than the smallest for now. +MAX_STACK_ALLOCATION_SIZE = 1024 * 100 + + +class CppWrapperCpuArrayRef(CppWrapperCpu): + """ + Generates cpp wrapper for running on CPU and calls cpp kernels + + This class is forked from CppWrapperCpu, with a difference that tensors may be + represented as ArrayRef, see torch/csrc/inductor/aoti_runtime/arrayref_tensor.h + """ + + def __init__(self): + super().__init__() + if self.device != "cpu": + raise AssertionError("ArrayRefTensor only supported on CPU!") + self.allow_stack_allocation = config.aot_inductor.allow_stack_allocation + self.stack_allocated_buffers: dict[BufferName, BufferLike] = {} + self.v2_raw_wrapper_body = IndentedBuffer() + self.v2_raw_output_refs: list[str] | None = None + + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: ir.GraphPartitionSignature | None = None, + ): + # TODO - support subgraph codegen by lifting functions. Check the + # comment at CppWrapperCpu `codegen_subgraph` function. + return CppWrapperCpuArrayRef() + + @staticmethod + def get_input_cpp_type(input): + if not config.aot_inductor.use_minimal_arrayref_interface: + raise AssertionError( + "expected config.aot_inductor.use_minimal_arrayref_interface to be set" + ) + + if isinstance(input, sympy.Expr): + from ..graph import may_get_constant_buffer_dtype + + dtype = may_get_constant_buffer_dtype(input) + if dtype is None: + raise AssertionError(f"Failed to get the dtype of sympy.Expr: {input}") + return DTYPE_TO_CPP[dtype] + return f"ArrayRefTensor<{DTYPE_TO_CPP[input.get_dtype()]}>" + + @staticmethod + def get_input_element_cpp_type(input): + if isinstance(input, sympy.Expr): + from ..graph import may_get_constant_buffer_dtype + + dtype = may_get_constant_buffer_dtype(input) + if dtype is None: + raise AssertionError(f"Failed to get the dtype of sympy.Expr: {input}") + return DTYPE_TO_CPP[dtype] + return DTYPE_TO_CPP[input.get_dtype()] + + @staticmethod + def get_device_include_path_jit(device: str) -> str: + if device != "cpu": + raise AssertionError("ArrayRef only supported on CPU!") + return "#include " + + @staticmethod + def get_device_include_path_aot(device: str) -> str: + if device != "cpu": + raise AssertionError("ArrayRef only supported on CPU!") + return "#include " + + def codegen_input_numel_asserts(self, indented_buffer=None): + writer = indented_buffer or self.prefix + for name, buf in V.graph.graph_inputs.items(): + if isinstance(buf, sympy.Expr): + continue + + # comparing strides for 0 size tensor is tricky. Ignore them for now. + if sympy_product(buf.get_size()) == 0: + continue + numel = buf.get_numel() + writer.writeline(f"assert_numel({name}, {numel});") + + def _codegen_assert_size_stride( + self, + code: IndentedBuffer, + name: str, + size: str, + stride: str, + op_name: str, + dtype: torch.dtype | None = None, + ) -> None: + # Inputs/outputs are ArrayRefTensor, not AtenTensorHandle, so + # assert_size_stride would fail to compile. + return + + def _codegen_v2_raw_input_bindings(self, code: IndentedBuffer): + for idx, (input_key, input_value) in enumerate(V.graph.graph_inputs.items()): + input_cpp_type = CppWrapperCpuArrayRef.get_input_element_cpp_type( + input_value + ) + if isinstance(input_value, sympy.Expr): + # cond / symint wrappers can surface symbolic scalar inputs here. + from ..graph import may_get_constant_buffer_dtype + + dtype = may_get_constant_buffer_dtype(input_value) + if dtype is None: + raise AssertionError("Fails to get the dtype of the sympy.Expr") + input_tensor = f"{input_key}_arrayref_tensor" + code.writeline( + f"auto {input_tensor} = torch::aot_inductor::c_to_arrayref_tensor<{input_cpp_type}>(c_inputs[{idx}]);" + ) + self.codegen_tensor_item(dtype, input_tensor, input_key, code) + else: + code.writeline( + f"auto {input_key} = torch::aot_inductor::c_to_arrayref_tensor<{input_cpp_type}>(c_inputs[{idx}]);" + ) + + def _codegen_v2_raw_input_symbols(self, code: IndentedBuffer) -> None: + bound_vars = OrderedSet[sympy.Symbol]() + graph_inputs = self.get_graph_inputs() + inputs = [ + (k, v) for k, v in graph_inputs.items() if isinstance(v, sympy.Symbol) + ] + [(k, v) for k, v in graph_inputs.items() if not isinstance(v, sympy.Symbol)] + + # Redirect self.prefix so the base class codegen_input_symbol_assignment + # writes into our buffer. + deferred_symbol_assignments = [] + with self._target_buf("prefix", code): + for name, value in inputs: + self.codegen_input_symbol_assignment( + name, value, bound_vars, deferred_symbol_assignments + ) + self._retry_deferred_symbol_assignments(deferred_symbol_assignments) + + for _, value in inputs: + if not isinstance(value, ir.TensorBox): + continue + for expr in [*value.get_size(), *value.get_stride()]: + if not isinstance(expr, sympy.Expr) or isinstance(expr, sympy.Symbol): + continue + undefined_symbols = [ + sym for sym in expr.free_symbols if sym not in bound_vars + ] + if len(undefined_symbols) > 0: + raise AssertionError( + f"For {expr}, expected {undefined_symbols} to have been codegen-ed." + ) + + def _codegen_v2_raw_prelude(self, code: IndentedBuffer): + self._codegen_v2_raw_input_bindings(code) + + if not all( + isinstance(v, torch.Tensor) for v in list(V.graph.constants.values()) + ): + raise AssertionError("Expect all constants to be Tensor") + for idx, constants_key in enumerate(V.graph.constants.keys()): + code.writeline(f"""auto {constants_key} = constants_->at({idx});""") + + self._codegen_v2_raw_input_symbols(code) + + self.codegen_input_numel_asserts(code) + code.writeline( + "[[maybe_unused]] auto& kernels = static_cast(*this->kernels_.get());" + ) + + def _codegen_v2_raw_outputs( + self, code: IndentedBuffer, output_refs: list[str] + ) -> None: + cst_names = V.graph.constants.keys() + + def write_output_to_c_array(idx: int, output: str) -> None: + output_arrayref_name = f"output_arrayref_{idx}" + code.splice( + f""" + std::tuple_element_t<{idx}, AOTInductorModelOutputs> {output_arrayref_name}; + convert_handle_to_arrayref_tensor({output}, {output_arrayref_name}); + torch::aot_inductor::arrayref_tensor_to_c({output_arrayref_name}, c_outputs[{idx}]); + """ + ) + + for idx, output in enumerate(output_refs): + if output == "nullptr": + continue + + is_constant_buffer = output in cst_names + output_buffer = V.graph.graph_outputs[idx] + if isinstance(output_buffer, ir.BaseView): + output_storage = output_buffer.unwrap_view() + if not isinstance(output_storage, (ir.BaseView, ir.MutableBox)): + raise AssertionError( + f"expected output_storage to be BaseView or MutableBox, got " + f"{type(output_storage).__name__}" + ) + if isinstance(output_storage.data, ir.ConstantBuffer): + is_constant_buffer = True + + if isinstance(output_buffer, ir.ShapeAsConstantBuffer): + output_tensor = f"scalar_to_tensor_{next(self.scalar_to_tensor_id)}" + code.writeline( + f"RAIIAtenTensorHandle {output_tensor} = scalar_to_tensor_handle({output});" + ) + write_output_to_c_array(idx, output_tensor) + continue + + output_is_tensor_handle_expr = ( + f"std::is_same_v," + "RAIIAtenTensorHandle> || " + f"std::is_same_v," + "AtenTensorHandle> || " + f"std::is_same_v," + "ConstantHandle>" + ) + code.writeline(f"if constexpr ({output_is_tensor_handle_expr}) {{") + with code.indent(): + cached_output_name = f"cached_output_{next(self.cached_output_id)}" + code.writeline( + f"thread_local RAIIAtenTensorHandle {cached_output_name};" + ) + if is_constant_buffer: + code.splice( + f""" + AtenTensorHandle {cached_output_name}_tmp; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_clone({output}, &{cached_output_name}_tmp)); + {cached_output_name} = {cached_output_name}_tmp; + """ + ) + else: + code.writeline(f"{cached_output_name} = {output}.release();") + write_output_to_c_array(idx, cached_output_name) + code.writeline("} else {") + with code.indent(): + cached_output_name = f"cached_output_{next(self.cached_output_id)}" + output_arrayref_type = f"output_arrayref_{idx}_type" + output_element_type = f"output_arrayref_{idx}_element_type" + output_arrayref_name = f"output_arrayref_{idx}" + code.splice( + f""" + thread_local ThreadLocalCachedOutputArray> + {cached_output_name}{{{output}}}; + {cached_output_name}.copy_data_from({output}); + using {output_arrayref_type} = std::tuple_element_t<{idx}, AOTInductorModelOutputs>; + using {output_element_type} = typename {output_arrayref_type}::value_type; + auto {output_arrayref_name} = {cached_output_name}.arrayref_tensor<{output_element_type}>(); + torch::aot_inductor::arrayref_tensor_to_c({output_arrayref_name}, c_outputs[{idx}]); + """ + ) + code.writeline("}") + + def generate_extern_kernel_alloc(self, *args, **kwargs): + # Disable stack allocation for extern kernels. + self.allow_stack_allocation = False + super().generate_extern_kernel_alloc(*args, **kwargs) + + def generate_extern_kernel_out(self, *args, **kwargs): + # Disable stack allocation for extern kernels. + self.allow_stack_allocation = False + super().generate_extern_kernel_out(*args, **kwargs) + + def generate_fallback_kernel(self, node: ir.FallbackKernel) -> None: + # Disable stack allocation for extern kernels. + self.allow_stack_allocation = False + super().generate_fallback_kernel(node) + + def _generate_kernel_call_helper( + self, + kernel_name: str, + call_args, + *, + device=None, + triton=True, + arg_types=None, + raw_keys=None, + raw_args=None, + triton_meta=None, + inductor_meta=None, + graph_name="", + original_fxnode_name=None, + current_stream_idx=None, + ): + """ + Generates kernel call code. + + triton: Defines whether the GPU backend uses Triton for codegen. + Otherwise it uses the CUDA language for codegen. + Only valid when cuda == True. + """ + if triton: + raise AssertionError( + "CppWrapperCpuArrayRef.generate_kernel_call does not support GPU" + ) + if not (arg_types is not None and len(call_args) == len(arg_types)): + raise AssertionError( + "Mismatch call_args and arg_types in generate_kernel_call" + ) + new_args = [] + for idx, arg in enumerate(call_args): + if "*" in arg_types[idx]: + var_name = f"var_{next(self.arg_var_id)}" + self.writeline(f"auto* {var_name} = get_data_ptr_wrapper({arg});") + new_args.append(f"({arg_types[idx]})({var_name})") + else: + # arg is a scalar + new_args.append(arg) + # debug printer related logic for cpp kernel type. + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + call_args, + kernel_name, + None, + None, + "cpp", + ) + with debug_printer_manager: + self.writeline(self.wrap_kernel_call(kernel_name, new_args)) + + def write_wrapper_decl(self): + """Declare the generated AOTI wrapper entry points.""" + inputs_len = len(V.graph.graph_inputs.keys()) + if V.graph.aot_mode: + if ( + config.aot_inductor.use_minimal_arrayref_interface + and not V.graph.is_const_graph + ): + input_cpp_types = ", ".join( + f"{CppWrapperCpuArrayRef.get_input_cpp_type(x)}" + for x in V.graph.graph_inputs.values() + ) + output_arrayref_types = ", ".join( + f"ArrayRefTensor<{DTYPE_TO_CPP[x.get_dtype()]}>" + for x in V.graph.graph_outputs + ) + + self.prefix.splice( + f""" + using AOTInductorModelInputs = std::tuple<{input_cpp_types}>; + using AOTInductorModelOutputs = std::tuple<{output_arrayref_types}>; + """ + ) + + if V.graph.const_module: + self.header.splice(V.graph.const_module.wrapper_code.header) + + if V.graph.const_wrapper_code is None: + raise AssertionError( + "expected V.graph.const_wrapper_code to be set" + ) + self.prefix.splice(V.graph.const_wrapper_code) + + if V.graph.const_kernel_code is None: + raise AssertionError("expected V.graph.const_kernel_code to be set") + self.kernel_declarations.splice(V.graph.const_kernel_code) + + if V.graph.is_const_graph: + self.prefix.splice( + """ + void AOTInductorModel::_const_run_impl( + std::vector& output_handles, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) { + """ + ) + else: + if not config.aot_inductor.use_runtime_constant_folding: + # If we do not split the constant graph, we'll just create + # an empty implementation when wrapping the main module. + self.prefix.splice( + """ + void AOTInductorModel::_const_run_impl( + std::vector& output_handles, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) {} + + """ + ) + + run_impl_proto = """ + void AOTInductorModel::run_impl( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) { + """ + + self.generate_input_output_runtime_checks() + run_impl_proto += """ + __check_inputs_outputs(input_handles, output_handles); + """ + + if config.aot_inductor.use_minimal_arrayref_interface: + self.prefix.splice( + """ + template <> + AOTInductorModelOutputs AOTInductorModel::run_impl_minimal_arrayref_interface< + AOTInductorModelInputs, AOTInductorModelOutputs>( + const AOTInductorModelInputs& inputs, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) { + """ + ) + self.suffix.splice(run_impl_proto) + self.suffix.splice( + """ + AOTInductorModelInputs inputs; + convert_handles_to_inputs(input_handles, inputs); + auto outputs = run_impl_minimal_arrayref_interface( + inputs, stream, proxy_executor); + // NOTE: outputs is full of ArrayRef to thread_local storage. If in the future we need this + // interface to perform well for a DSO using the minimal arrayref interface, all we need + // to do is provide ThreadLocalCachedTensor for each one! + convert_outputs_to_handles(outputs, output_handles); + } + """ + ) + + self.suffix.splice( + """ + extern "C" AOTIRuntimeError AOTInductorModelRunMinimalArrayrefInterface( + AOTInductorModelHandle model_handle, + const AOTInductorModelInputs& inputs, + AOTInductorModelOutputs& outputs) { + auto model = reinterpret_cast(model_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + outputs = model->run_impl_minimal_arrayref_interface( + inputs, + (torch::aot_inductor::DeviceStreamType)nullptr, + nullptr); + }) + } + """ + ) + + self.suffix.splice( + f""" + // C-ABI-safe variant: uses flat AOTInductorArrayRefTensor arrays + // instead of std::tuple across the DSO boundary, and + // runs directly on the descriptor arrays to avoid + // DSO-side tuple marshaling. + extern "C" AOTIRuntimeError AOTInductorModelRunMinimalArrayrefInterfaceV2( + AOTInductorModelHandle model_handle, + int32_t num_inputs, + const AOTInductorArrayRefTensor* c_inputs, + int32_t num_outputs, + AOTInductorArrayRefTensor* c_outputs) {{ + constexpr int32_t expected_num_inputs = {len(V.graph.graph_inputs)}; + constexpr int32_t expected_num_outputs = {len(V.graph.graph_outputs)}; + auto model = reinterpret_cast(model_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({{ + if (num_inputs != expected_num_inputs) {{ + throw std::runtime_error( + std::string("AOTInductorModelRunMinimalArrayrefInterfaceV2 expected ") + + std::to_string(expected_num_inputs) + + " inputs but got " + + std::to_string(num_inputs)); + }} + if (num_outputs != expected_num_outputs) {{ + throw std::runtime_error( + std::string("AOTInductorModelRunMinimalArrayrefInterfaceV2 expected ") + + std::to_string(expected_num_outputs) + + " outputs but got " + + std::to_string(num_outputs)); + }} + if (num_inputs > 0 && c_inputs == nullptr) {{ + throw std::runtime_error( + "AOTInductorModelRunMinimalArrayrefInterfaceV2 received null input descriptors"); + }} + if (num_outputs > 0 && c_outputs == nullptr) {{ + throw std::runtime_error( + "AOTInductorModelRunMinimalArrayrefInterfaceV2 received null output descriptors"); + }} + model->run_impl_minimal_arrayref_interface_v2_raw( + c_inputs, + c_outputs, + (torch::aot_inductor::DeviceStreamType)nullptr, + nullptr); + }}) + }} + """ + ) + else: + self.prefix.splice(run_impl_proto) + else: + # cpp entry function for JIT with cpp wrapper + self.prefix.splice( + """ + void inductor_entry_impl( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed) + ) { + """ + ) + with self.prefix.indent(): + # assign inputs and outputs in both cases so the later codegen can be simplified + if not config.aot_inductor.use_minimal_arrayref_interface: + if not V.graph.is_const_graph: + if V.graph.aot_mode: + num_args = len(V.graph.graph_inputs) + else: + # Weights are promoted in the JIT mode + num_args = len(V.graph.graph_inputs) + len(V.graph.constants) + # release GIL to support multiple instances inference (in different threads of the same process) + self.prefix.splice("py::gil_scoped_release_simple release;") + + self.prefix.splice( + f""" + auto inputs = steal_from_raw_handles_to_raii_handles(input_handles, {num_args}); + """ + ) + + if inputs_len != 0: + for idx, input_key in enumerate(V.graph.graph_inputs.keys()): + if config.aot_inductor.use_minimal_arrayref_interface: + self.prefix.writeline( + f"auto {input_key} = std::get<{idx}>(inputs);" + ) + continue + # unwrap input tensor back to scalar + if isinstance(V.graph.graph_inputs[input_key], sympy.Expr): + from ..graph import may_get_constant_buffer_dtype + + dtype = may_get_constant_buffer_dtype( + V.graph.graph_inputs[input_key] # type: ignore[arg-type] + ) + if dtype is None: + raise AssertionError( + "Fails to get the dtype of the sympy.Expr" + ) + self.codegen_tensor_item( + dtype, f"inputs[{idx}]", input_key, self.prefix + ) + else: + self.prefix.writeline( + f"auto {input_key} = std::move(inputs[{idx}]);" + ) + + if not all( + isinstance(v, torch.Tensor) for v in list(V.graph.constants.values()) + ): + raise AssertionError("Expect all constants to be Tensor") + for idx, constants_key in enumerate(V.graph.constants.keys()): + if V.graph.aot_mode: + # Weights are stored in constants_ and owned by RAIIAtenTensorHandle there. + # Don't call std::move here because it will cause constants_ to lose the ownership. + self.prefix.writeline( + f"""auto {constants_key} = constants_->at({idx});""" + ) + else: + # Append constants as inputs to the graph + constants_idx = inputs_len + idx + self.prefix.writeline( + f"auto {constants_key} = std::move(inputs[{constants_idx}]);" + ) + + self.codegen_inputs() + + if V.graph.aot_mode: + if not V.graph.is_const_graph: + if config.aot_inductor.use_minimal_arrayref_interface: + # TODO: input shape checking for regular tensor interface as well? + self.codegen_input_numel_asserts() + else: + self.prefix.writeline("inputs.clear();") + self.prefix.writeline( + "[[maybe_unused]] auto& kernels = static_cast(*this->kernels_.get());" + ) + + def generate_return(self, output_refs: list[str]): + cst_names = V.graph.constants.keys() + arr_iface = ( + not V.graph.is_const_graph + and config.aot_inductor.use_minimal_arrayref_interface + ) # For brevity. + + if arr_iface and V.graph.aot_mode: + self.v2_raw_wrapper_body.clear() + self.v2_raw_wrapper_body.splice(self.wrapper_call) + self.v2_raw_output_refs = list(output_refs) + + def use_thread_local_cached_output_tensor(idx, output): + cached_output_name = f"cached_output_{next(self.cached_output_id)}" + cache_type = "Array" if arr_iface else "Tensor" + self.wrapper_call.writeline( + f"thread_local ThreadLocalCachedOutput{cache_type}> " + f"{cached_output_name}{{{output}}};" + ) + if arr_iface: + self.wrapper_call.writeline( + f"{cached_output_name}.copy_data_from({output});" + ) + output_entry = f"std::get<{idx}>(output_arrayref_tensors)" + element_type = f"std::decay_t" + self.wrapper_call.writeline( + f"{output_entry} = {cached_output_name}.arrayref_tensor<{element_type}>();" + ) + else: + self.wrapper_call.writeline( + f"{cached_output_name}.copy_data_from({output});" + ) + self.wrapper_call.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_uninitialized_tensor(&output_handles[{idx}]));" + ) + self.wrapper_call.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors({cached_output_name}.tensor(), " + f"output_handles[{idx}]));" + ) + + if arr_iface: + self.wrapper_call.writeline( + "AOTInductorModelOutputs output_arrayref_tensors;" + ) + + output2idx: dict[str, int] = {} + for idx, output in enumerate(output_refs): + if output == "nullptr": + continue + + is_constant_buffer = output in cst_names + output_buffer = V.graph.graph_outputs[idx] + if isinstance(output_buffer, ir.BaseView): + output_storage = output_buffer.unwrap_view() + if not isinstance(output_storage, (ir.BaseView, ir.MutableBox)): + raise AssertionError( + f"expected output_storage to be BaseView or MutableBox, got " + f"{type(output_storage).__name__}" + ) + if isinstance(output_storage.data, ir.ConstantBuffer): + is_constant_buffer = True + + if isinstance(output_buffer, ir.ShapeAsConstantBuffer): + # Need to wrap scalar into tensor as the main function returns a vector of tensors + output_tensor = self.codegen_scalar_to_tensor(output) + self.wrapper_call.writeline( + f"output_handles[{idx}] = {output_tensor}.release();" + ) + continue + + output_is_tensor_handle_expr = ( + f"std::is_same_v," + "RAIIAtenTensorHandle> || " + f"std::is_same_v," + "AtenTensorHandle> || " + f"std::is_same_v," + "ConstantHandle>" + ) + self.wrapper_call.writeline( + f"if constexpr ({output_is_tensor_handle_expr}) {{" + ) + with self.wrapper_call.indent(): + if arr_iface: + cached_output_name = f"cached_output_{next(self.cached_output_id)}" + self.wrapper_call.writeline( + f"thread_local RAIIAtenTensorHandle {cached_output_name};" + ) + if is_constant_buffer: + # NOTE(return_constant): In some rare cases where we return + # a constant, we have to return a copy of this constant, + # because (1) constants are not owned by the Model instance + # (2) constants remain the same cross inference runs, + # assuming they are not updated at runtime Basically, we + # cannot release or transfer the ownership of any original + # constant to the user. + self.wrapper_call.writeline( + f"AtenTensorHandle {cached_output_name}_tmp;" + ) + self.wrapper_call.writeline( + "AOTI_TORCH_ERROR_CODE_CHECK(" + f"aoti_torch_clone({output}, &{cached_output_name}_tmp));" + ) + self.wrapper_call.writeline( + f"{cached_output_name} = {cached_output_name}_tmp;" + ) + else: + self.wrapper_call.writeline( + f"{cached_output_name} = {output}.release();" + ) + self.wrapper_call.writeline( + f"convert_handle_to_arrayref_tensor({cached_output_name}, " + f"std::get<{idx}>(output_arrayref_tensors));" + ) + else: + if is_constant_buffer: + # See NOTE(return_constant) above. + self.wrapper_call.writeline( + "AOTI_TORCH_ERROR_CODE_CHECK(" + f"aoti_torch_clone({output}, &output_handles[{idx}]));" + ) + else: + if output in output2idx: + src_idx = output2idx[output] + self.wrapper_call.writeline( + f"output_handles[{idx}] = output_handles[{src_idx}];" + ) + else: + self.wrapper_call.writeline( + f"output_handles[{idx}] = {output}.release();" + ) + self.wrapper_call.writeline("} else {") + with self.wrapper_call.indent(): + use_thread_local_cached_output_tensor(idx, output) + self.wrapper_call.writeline("}") + + if output not in output2idx: + output2idx[output] = idx + if arr_iface: + self.wrapper_call.writeline("return output_arrayref_tensors;") + + def generate_before_suffix(self, result): + super().generate_before_suffix(result) + if self.v2_raw_output_refs is None: + return + + raw_impl = IndentedBuffer() + raw_impl.splice( + """ + void AOTInductorModel::run_impl_minimal_arrayref_interface_v2_raw( + const AOTInductorArrayRefTensor* c_inputs, + AOTInductorArrayRefTensor* c_outputs, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) { + """ + ) + with raw_impl.indent(): + self._codegen_v2_raw_prelude(raw_impl) + raw_impl.splice(self.v2_raw_wrapper_body) + self._codegen_v2_raw_outputs(raw_impl, self.v2_raw_output_refs) + raw_impl.writeline( + "} // AOTInductorModel::run_impl_minimal_arrayref_interface_v2_raw" + ) + result.splice(raw_impl) + + def memory_plan(self): + from .memory_planning import MemoryPlanner + + self.lines = MemoryPlanner(self).plan(self.lines) + # TODO: integrate memory planning & stack allocation? + self.allow_stack_allocation = False + + def memory_plan_reuse(self): + out_names = V.graph.get_output_names() + + while ( + self.lines + and isinstance(self.lines[-1], MemoryPlanningLine) + # TODO: this seems legit, NullLine has no node + and self.lines[-1].node.name not in out_names # type: ignore[attr-defined] + ): + # these lines will be pointless + self.lines.pop() + + # codegen allocations in two passes + planning_states = [MemoryPlanningState()] + past_planning_states = [] + for i in range(len(self.lines)): + line = self.lines[i] + if isinstance(line, MemoryPlanningLine): + self.lines[i] = line.plan(planning_states[-1]) + elif isinstance(line, EnterSubgraphLine): + planning_states.append(MemoryPlanningState()) + elif isinstance(line, ExitSubgraphLine): + past_planning_states.append(planning_states.pop()) + past_planning_states.append(planning_states.pop()) + if len(planning_states) != 0: + raise AssertionError( + f"expected planning_states to be empty, got {len(planning_states)}" + ) + + # conservatively use the sum of all allocated buffer sizes + # in potentially nested scopes as the total allocated size + total_allocated_buffer_size = sum( + s.total_allocated_buffer_size for s in past_planning_states + ) + + self.allow_stack_allocation = ( + self.allow_stack_allocation is not False + and config.aot_inductor.allow_stack_allocation + and total_allocated_buffer_size <= MAX_STACK_ALLOCATION_SIZE + ) + + def can_stack_allocate_buffer(self, buffer): + return ( + self.allow_stack_allocation + and buffer.get_device().type == "cpu" + and self.can_prove_buffer_has_static_shape(buffer) + and ir.is_contiguous_strides_for_shape( + buffer.get_stride(), buffer.get_size() + ) + ) + + def make_buffer_free(self, buffer): + return ( + "" + if isinstance(buffer.get_output_spec(), ir.MultiOutputLayout) + or (V.graph.aot_mode and buffer.get_name() in self.stack_allocated_buffers) + or ( + config.aot_inductor.use_minimal_arrayref_interface + and V.graph.aot_mode + and buffer.get_name() in V.graph.graph_inputs + ) + else f"{buffer.get_name()}.reset();" + ) + + def make_buffer_allocation(self, buffer): + return self.make_allocation( + buffer.get_name(), + buffer.get_device(), + buffer.get_dtype(), + buffer.get_size(), + buffer.get_stride(), + buffer if self.can_stack_allocate_buffer(buffer) else None, + buffer.get_is_pinned(), + ) + + def make_allocation( + self, + name, + device, + dtype, + shape, + stride, + buffer_if_can_stack_allocate=None, + is_pinned=False, + ): + orig_stride = stride + device_str = self.codegen_device(device) + dtype_code = self.codegen_dtype(dtype) + size = self.codegen_shape_tuple(shape) + stride = self.codegen_shape_tuple(orig_stride) + size_array_var = self.codegen_int_array_var( + size, + self.wrapper_call.writeline, + known_statically=self.is_statically_known_list_of_ints(shape), + graph=self.get_codegened_graph(), + ) + stride_array_var = self.codegen_int_array_var( + stride, + self.wrapper_call.writeline, + known_statically=self.is_statically_known_list_of_ints(orig_stride), + graph=self.get_codegened_graph(), + ) + device_type, device_id = device_str.split(",") + device_idx = self.codegen_device_idx(device, device_id) + if buffer_if_can_stack_allocate is not None: + self.stack_allocated_buffers[name] = buffer_if_can_stack_allocate + cpp_type = DTYPE_TO_CPP[dtype] + numel = buffer_if_can_stack_allocate.get_numel() + # Note: we don't zero storage because empty_strided doesn't zero either. + self.wrapper_call.writeline(f"{cpp_type} {name}_storage[{numel}];") + args = [ + f"{name}_storage", + size_array_var, + stride_array_var, + device_type, + device_idx, + ] + return f"ArrayRefTensor<{cpp_type}> {name}({', '.join(args)});" + + args = [ + str(len(shape)), + size_array_var, + stride_array_var, + dtype_code, + device_type, + device_idx, + f"&{name}_handle", + ] + + self.wrapper_call.writeline(f"AtenTensorHandle {name}_handle;") + pinned_str = "_pinned" if is_pinned else "" + self.wrapper_call.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided{pinned_str}({', '.join(args)}));" + ) + + return f"RAIIAtenTensorHandle {name}({name}_handle);" + + def make_buffer_reuse(self, old: BufferLike, new: BufferLike, delete_old: bool): + if old.get_dtype() != new.get_dtype(): + raise AssertionError( + f"expected matching dtypes, got {old.get_dtype()} and {new.get_dtype()}" + ) + old_name = old.get_name() + new_name = new.get_name() + del_line = ";" + if old_name not in V.graph.get_output_names() and delete_old: + del_line = f"; {self.make_buffer_free(old)}" + + if old.get_size() == new.get_size() and old.get_stride() == new.get_stride(): + if old_name in self.stack_allocated_buffers: + self.stack_allocated_buffers[new_name] = new + return self.codegen_exact_buffer_reuse(old_name, new_name, del_line) + + reinterpret_view = self.codegen_reinterpret_view( + old, new.get_size(), new.get_stride(), 0, self.wrapper_call.writeline + ) + if reinterpret_view in self.stack_allocated_buffers: + self.stack_allocated_buffers[new_name] = new + # The only way to get into this case is via an exact buffer reuse, since all + # other options result in a new tensor handle. + return self.codegen_exact_buffer_reuse(old_name, new_name, del_line) + return f"{self.declare}{new_name} = {reinterpret_view}{del_line} // reuse" + + def _assert_safe_to_use_borrow_arrayref_tensor_as_tensor(self): + # Borrowing arguments to shim functions is only safe because we know + # that the arguments can't be stack-allocated. Otherwise, to be sure + # we can't return a dangling pointer, we need to either 1) be + # certain that the shim function cannot return an alias of a + # borrowed argument, or 2) be certain that the returned Tensor from + # the shim function cannot escape. + if not self.is_safe_to_use_borrow_arrayref_tensor_as_tensor(): + raise AssertionError( + "borrowing arguments to shim functions is unsafe with " + "stack allocation on! (see comment above this assertion)" + ) + + def is_safe_to_use_borrow_arrayref_tensor_as_tensor(self): + return not self.allow_stack_allocation and not self.stack_allocated_buffers + + def codegen_subgraph_prefix(self, subgraph, outer_inputs, outer_outputs): + if len(subgraph.graph.graph_inputs) != len(outer_inputs): + raise AssertionError( + f"expected {len(outer_inputs)} subgraph inputs, got " + f"{len(subgraph.graph.graph_inputs)}" + ) + + for (inner_input, inner_input_val), outer_input in zip( + subgraph.graph.graph_inputs.items(), outer_inputs + ): + if not isinstance(inner_input_val, ir.TensorBox): + continue + + # Wrap with a generic lambda so if constexpr can discard the + # ill-formed branch (if constexpr only discards in dependent + # contexts, i.e. templates / generic lambdas). + self.writeline(f"AtenTensorHandle {inner_input}_handle;") + self.writeline( + f"[&](auto&& _t) {{ " + f"if constexpr (::torch::aot_inductor::is_arrayref_tensor_type_v" + f">) {{ " + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors_out(" + f"borrow_arrayref_tensor_as_tensor(_t), &{inner_input}_handle)); " + f"}} else {{ " + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors_out(" + f"_t, &{inner_input}_handle)); " + f"}} }}({outer_input});" + ) + self.writeline(f"RAIIAtenTensorHandle {inner_input}({inner_input}_handle);") + + def codegen_while_loop(self, while_loop, stack_output=False): + if stack_output: + raise NotImplementedError("NYI cpp wrapper for while_loop_stack_output") + is_bool_pred = isinstance( + while_loop.cond_subgraph.graph.graph_outputs[0], ir.ShapeAsConstantBuffer + ) + name = while_loop.get_name() + outer_carried_inputs = [ + buf.codegen_reference() for buf in while_loop.carried_inputs + ] + outer_additional_inputs = [ + buf.codegen_reference() for buf in while_loop.additional_inputs + ] + carried_output_names = self._get_while_loop_carried_output_names(while_loop) + cond_result_name = f"{name}_cond_result" + if is_bool_pred: + self.writeline(f"bool {cond_result_name};") + else: + self.writeline(f"RAIIAtenTensorHandle {cond_result_name};") + + cond_outer_inputs = [] + for inp, out_name in zip(outer_carried_inputs, carried_output_names): + self.writeline(f"AtenTensorHandle {out_name}_handle;") + self.writeline( + "AOTI_TORCH_ERROR_CODE_CHECK(" + f"aoti_torch_assign_tensors_out(borrow_arrayref_tensor_as_tensor({inp}), " + f"&{out_name}_handle));" + ) + self.writeline(f"RAIIAtenTensorHandle {out_name}({out_name}_handle);") + cond_outer_inputs.append(out_name) + + cond_outer_inputs.extend(outer_additional_inputs) + + cond_outer_outputs = [cond_result_name] + body_outer_inputs = list(cond_outer_inputs) + body_outer_outputs = body_outer_inputs[: len(outer_carried_inputs)] + + self.writeline("while (1) {") + self.writeline(EnterSubgraphLine(self, while_loop.cond_subgraph.graph)) + self.codegen_subgraph( + while_loop.cond_subgraph, cond_outer_inputs, cond_outer_outputs + ) + + if is_bool_pred: + cond_result = f"{cond_result_name}" + else: + cond_result = f"{cond_result_name}_scalar" + self.codegen_tensor_item(torch.bool, cond_result_name, cond_result) + self.writeline(f"if (!{cond_result}) break;") + + self.writeline(ExitSubgraphLine(self)) + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + self.codegen_subgraph( + while_loop.body_subgraph, body_outer_inputs, body_outer_outputs + ) + self.writeline(ExitSubgraphLine(self)) + self.writeline("}") + + def generate_c_shim_extern_kernel_call( + self, kernel: str, args: list[str], device: str, **_ + ) -> None: + # In the abi_compatible mode, we call fallback aten ops through a C shim layer + # Setting self.allow_stack_allocation to False because the exchange between + # ArrayRefTensor and at::Tensor is still fragile. + self.allow_stack_allocation = False + + wrapped_args = [] + for arg in args: + # We only really *need* borrow_arrayref_tensor_as_tensor for + # ArrayRefTensors. The code flowing into here uses `0` for nullptr, which + # borrow_arrayref_tensor_as_tensor would blindly coerce to int, so just + # avoid wrapping integers. Name matching is to find tensor is hacky, but + # fixing all the ArrayRefTensor issues is not a priority for now. + if isinstance(arg, str) and arg.startswith( + ("buf", "arg", "wrap_with_raii_handle_if_needed") + ): + self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor() + arg = f"borrow_arrayref_tensor_as_tensor({arg})" + wrapped_args.append(arg) + + super().generate_c_shim_extern_kernel_call( + kernel, wrapped_args, device, debug_args=args + ) + + def generate_scatter_fallback(self, node: ir.ScatterFallback): + # No stack allocation when there is a fallback op + self.allow_stack_allocation = False + super().generate_scatter_fallback(node) + + def _generate_scatter_fallback_args(self, inputs: Sequence[Any]) -> list[str]: + self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor() + return [ + f"borrow_arrayref_tensor_as_tensor({x})" if isinstance(x, str) else str(x) + for x in inputs + ] + + def generate_index_put_fallback(self, node: ir.IndexPutFallback) -> None: + # No stack allocation when there is a fallback op + self.allow_stack_allocation = False + super().generate_index_put_fallback(node) + + def _generate_index_put_fallback(self, kernel, x, indices, values, accumulate): + self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor() + # TODO: update aoti_torch_index_put_out in ir.py to use autogen out version + # See the comment in codegen_reinterpret_view about why having something like + # RAIIAtenTensorHandle(tmp_tensor_handle_2) in a tmp array can cause the corresponding + # tensor prematurely deallocated, thus the temporary array trick here. + indices_str = self._generate_temporary_array_pointer( + "AtenTensorHandle", + [f"borrow_arrayref_tensor_as_tensor({i})" for i in indices], + ) + args = [ + f"borrow_arrayref_tensor_as_tensor({x})", + indices_str, + str(len(indices)), + f"borrow_arrayref_tensor_as_tensor({values})", + accumulate, + ] + args.insert( + 0, f"borrow_arrayref_tensor_as_tensor({x})" + ) # set x as the output tensor, this fallback mutates x. + # Wrap in AOTI_TORCH_ERROR_CODE_CHECK so a shim failure surfaces instead + # of being silently swallowed. + self.writeline(f"AOTI_TORCH_ERROR_CODE_CHECK({kernel}({', '.join(args)}));") + + def generate_fallback_kernel_with_runtime_lookup( + self, + buf_name: str, + python_kernel_name: str, + get_args: Callable[[], Sequence[str]], + op_overload: torch._ops.OpOverload | torch._ops.HigherOrderOperator, + raw_args: Sequence[Any], + outputs: Sequence[ir.Buffer], + ) -> None: + # No stack allocation when there is a fallback op + self.allow_stack_allocation = False + super().generate_fallback_kernel_with_runtime_lookup( + buf_name, python_kernel_name, get_args, op_overload, raw_args, outputs + ) + + def codegen_runtime_lookup_tensor_call_args( + self, tensor_call_args: Sequence[str] + ) -> Sequence[str]: + self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor() + return [f"borrow_arrayref_tensor_as_tensor({arg})" for arg in tensor_call_args] + + def codegen_device_copy(self, src, dst, non_blocking: bool | str): + # aoti_torch_tensor_copy_ takes AtenTensorHandle as input, + # while stack-allocation results in ArrayRefTensor + # so disable stack allocation here + self.allow_stack_allocation = False + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_copy_(expensive_copy_to_tensor_if_needed({dst}), {src}, {non_blocking}));" + ) + + def codegen_reinterpret_view( + self, + data, + size, + stride, + offset, + writeline: Callable[..., None], + dtype=None, + ) -> str: + """Returns a newly-created, temporary RAII tensor handle containing the + reinterpreted tensor data. Callers of this function are responsible for saving + the handle if persistent access is needed.""" + dim = str(len(size)) + + def create_reinterpret_call() -> str: + args = [ + f"{data.get_name()}", + dim, + self.codegen_int_array_var( + self.codegen_shape_tuple(size), + writeline, + known_statically=self.is_statically_known_list_of_ints(size), + graph=self.get_codegened_graph(), + ), + self.codegen_int_array_var( + self.codegen_shape_tuple(stride), + writeline, + known_statically=self.is_statically_known_list_of_ints(stride), + graph=self.get_codegened_graph(), + ), + offset, + ] + return f"wrap_with_raii_handle_if_needed(reinterpret_tensor_wrapper({', '.join(args)}))" + + def create_new_tensor_handle() -> tuple[str, list[str]]: + # Calling reset() on ArrayRefTensor does nothing, since the array is + # const-allocated on the stack. Thus, it's safe to return a reference to + # the original array. + if (name := data.get_name()) in self.stack_allocated_buffers: + return name, [] + + tmp_AtenTensorHandle = f"tmp_{name}_{next(self.tmp_tensor_id)}" + tmp_call_strs = [ + f"AtenTensorHandle {tmp_AtenTensorHandle};", + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_tensor_handle({data.get_name()}, &{tmp_AtenTensorHandle}));", + ] + return f"RAIIAtenTensorHandle({tmp_AtenTensorHandle})", tmp_call_strs + + if ( + size == data.layout.size + and stride == data.layout.stride + and offset == data.layout.offset + and (dtype is None or dtype == data.dtype) + ): + final_tensor_str, call_strs = create_new_tensor_handle() + for line in call_strs: + writeline(line) + return final_tensor_str + + return super().codegen_reinterpret_view( + data, size, stride, offset, writeline, dtype + ) + + def val_to_arg_str(self, val, type_=None) -> str: + if ( + val is not None + and isinstance(type_, torch.OptionalType) + and isinstance(type_.getElementType(), torch.TensorType) + ): + # Handle optional tensors as a special case, as in the parent class. + base_handle = self.val_to_arg_str(val, torch.TensorType) + if config.aot_inductor.use_minimal_arrayref_interface: + if self.is_safe_to_use_borrow_arrayref_tensor_as_tensor(): + base_handle = f"borrow_arrayref_tensor_as_tensor({base_handle})" + else: + base_handle = f"copy_arrayref_tensor_to_tensor({base_handle})" + return f"&temporary_reference({base_handle}.get())" + + return super().val_to_arg_str(val, type_) + + def codegen_tensor_item( + self, dtype: torch.dtype, tensor: str, scalar: str, indented_buffer=None + ): + dtype_str = str(dtype).split(".")[-1] + writer = indented_buffer or self + + if dtype == torch.float16 or dtype == torch.bfloat16: + scalar_tmp = f"{scalar}_tmp" + writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar_tmp};") + + # We know that item_ doesn't alias the input, so borrowing should be safe. + tensor = f"borrow_arrayref_tensor_as_tensor({tensor})" + + writer.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar_tmp}));" + ) + writer.writeline(f"float {scalar} = float({scalar_tmp});") + else: + writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar};") + + # We know that item_ doesn't alias the input, so borrowing should be safe. + tensor = f"borrow_arrayref_tensor_as_tensor({tensor})" + + writer.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar}));" + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_gpu.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..ea66a2f109c7de003c903012d3ff37402d1da2e6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_gpu.py @@ -0,0 +1,1886 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import dataclasses +import os +import re +import sys +from itertools import count, zip_longest +from typing import Any, cast +from typing_extensions import Self + +import sympy + +import torch +from torch import dtype as torch_dtype +from torch._inductor.codecache import get_cpp_wrapper_cubin_path_name +from torch._inductor.runtime.runtime_utils import dynamo_timed +from torch.utils._ordered_set import OrderedSet + +from .. import config +from ..codecache import CudaKernelParamCache +from ..ir import ( + GraphPartitionSignature, + TensorBox, + TMADescriptorExperimental, + TMADescriptorStable, +) +from ..runtime.hints import ( + InductorMeta, + TRITON_DEFAULT_BLOCK_SIZES, + TRITON_DEFAULT_RSPLIT, + TRITON_DEFAULT_RSPLIT_SIZE, + TritonMeta, +) +from ..stream_utils import ( + AOTI_SUPPORTED_STREAM_OP_NAMES, + AOTI_UNSUPPORTED_STREAM_OP_REASONS, + get_stream_name, +) +from ..utils import ( + cache_on_self, + DeferredLineBase, + get_gpu_type, + GPU_ALIGN_BYTES, + IndentedBuffer, + make_codegen_buffer, + XPU_KERNEL_FORMAT, +) +from ..virtualized import V +from .aoti_hipify_utils import maybe_hipify_code_wrapper +from .common import get_device_op_overrides, TritonScratchWorkspace +from .cpp_utils import cexpr +from .cpp_wrapper_cpu import CppWrapperCpu +from .multi_kernel import MultiKernelCall +from .triton_utils import should_unwrap_unspec_arg +from .wrapper import PythonWrapperCodegen, SymbolicCallArg + + +_cpp_string_literal_escapes = { + "\\": "\\\\", + '"': '\\"', + "\n": "\\n", + "\t": "\\t", + "\r": "\\r", +} +_cpp_string_literal_pattern = re.compile(r'["\\\n\t\r]') + + +def cpp_string_literal(s: str) -> str: + escaped = _cpp_string_literal_pattern.sub( + lambda match: _cpp_string_literal_escapes[match.group(0)], s + ) + return f'"{escaped}"' + + +def generate_aoti_kernel_config_header(kernel_names: list[str]) -> str: + """Generate a C header defining macros for each lazy-compiled kernel. + + Called after the JIT first-pass runs and populates CudaKernelParamCache. + The AOTI compilation includes this header so that LazyKernelCompileResult + structs get compile-time-initialized with the autotuned values. + """ + + def braced(values: list[int]) -> str: + return "{" + ", ".join(str(v) for v in values) + "}" + + buf = IndentedBuffer() + buf.splice(""" + #pragma once + // Auto-generated kernel configurations for AOTInductor lazy compile. + """) + + for kernel_name in kernel_names: + params = CudaKernelParamCache.get(kernel_name) + if params is None: + raise RuntimeError( + "When autotune_at_compile_time is False, AOTInductor generates" + " both JIT code and AOT code. They are expected to have exactly" + f" the same kernels. However, AOT code contains kernels, {kernel_names}," + " that is not in the JIT code." + ) + + macro_prefix = kernel_name.upper() + cubin_path = cpp_string_literal(params[get_cpp_wrapper_cubin_path_name()]) + mangled_name = cpp_string_literal(params["mangled_name"]) + num_warps = params["num_warps"] + shared_mem = params["shared_mem"] + + # params["config"] is already a dict (from config_to_dict in CachingAutotuner) + config_dict = params.get("config") or {} + + # For combo/foreach kernels, merge default_config + inductor_meta = params.get("inductor_meta") or {} + combo_grid_meta = inductor_meta.get("combo_grid_meta") + default_config = ( + combo_grid_meta.get("default_config") if combo_grid_meta else None + ) + if default_config: + config_dict = {**default_config, **config_dict} + + config_index: int | None = None + grid_type = inductor_meta.get("grid_type") + if grid_type == "PrecomputedGrid": + precomputed_grids = inductor_meta.get("precomputed_grids", []) + for idx, entry in enumerate(precomputed_grids): + entry_config = entry.get("config", {}) + if all(config_dict.get(k) == v for k, v in entry_config.items()): + config_index = idx + break + + # Per-subkernel block sizes for combo kernels, or single-element lists. + num_kernels = combo_grid_meta.get("num_kernels", 1) if combo_grid_meta else 1 + if num_kernels > 1 and "XBLOCK_0" in config_dict: + xblocks = [ + config_dict.get(f"XBLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["XBLOCK"]) + for i in range(num_kernels) + ] + yblocks = [ + config_dict.get(f"YBLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["YBLOCK"]) + for i in range(num_kernels) + ] + zblocks = [ + config_dict.get(f"ZBLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["ZBLOCK"]) + for i in range(num_kernels) + ] + r0blocks = [ + config_dict.get(f"R0_BLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["R0_BLOCK"]) + for i in range(num_kernels) + ] + else: + xblocks = [config_dict.get("XBLOCK", TRITON_DEFAULT_BLOCK_SIZES["XBLOCK"])] + yblocks = [config_dict.get("YBLOCK", TRITON_DEFAULT_BLOCK_SIZES["YBLOCK"])] + zblocks = [config_dict.get("ZBLOCK", TRITON_DEFAULT_BLOCK_SIZES["ZBLOCK"])] + r0blocks = [ + config_dict.get("R0_BLOCK", TRITON_DEFAULT_BLOCK_SIZES["R0_BLOCK"]) + ] + rsplit = config_dict.get("RSPLIT", TRITON_DEFAULT_RSPLIT) + rsplit_size = config_dict.get("RSPLIT_SIZE", TRITON_DEFAULT_RSPLIT_SIZE) + ci = config_index if config_index is not None else -1 + gs = params.get("global_scratch", -1) or -1 + ps = params.get("profile_scratch", -1) or -1 + + buf.writeline("") + buf.splice(f""" + // Kernel: {kernel_name} + #define {macro_prefix}_CUBIN_PATH {cubin_path} + #define {macro_prefix}_MANGLED_NAME {mangled_name} + #define {macro_prefix}_NUM_WARPS {num_warps} + #define {macro_prefix}_SHARED_MEM {shared_mem} + #define {macro_prefix}_XBLOCKS {braced(xblocks)} + #define {macro_prefix}_YBLOCKS {braced(yblocks)} + #define {macro_prefix}_ZBLOCKS {braced(zblocks)} + #define {macro_prefix}_R0BLOCKS {braced(r0blocks)} + #define {macro_prefix}_RSPLIT {rsplit} + #define {macro_prefix}_RSPLIT_SIZE {rsplit_size} + #define {macro_prefix}_CONFIG_INDEX {ci} + #define {macro_prefix}_GLOBAL_SCRATCH {gs} + #define {macro_prefix}_PROFILE_SCRATCH {ps} + """) + + return buf.getvalue() + + +TRITON_SIGNATURE_TO_CPP = { + "i32": "int32_t", + "i64": "int64_t", + "fp32": "float", + "fp64": "double", +} + + +def signature_is_tma_desc(sig: str | None) -> bool: + """Check if a Triton signature represents a TMA descriptor.""" + if not sig: + return False + if sig == "nvTmaDesc": + return True + if sig.startswith("tensordesc<"): + return True + return False + + +def _unpack_tma_descriptor_args(var_name: str, sig_type: str) -> list[str]: + """Unpack a StableTMADescriptor into kernel launch args. + + Given a variable name holding a StableTMADescriptor and its tensordesc<...> + signature, returns the list of pointer args: &var.m, &var.block_shape[i]..., + &var.strides[i]... + """ + match = re.match(r"tensordesc<[^[]*\[([^\]]*)\]", sig_type) + if match is None: + raise AssertionError(f"Cannot parse tensordesc signature: {sig_type}") + ndim = match.group(1).count(",") + 1 + result = [f"&{var_name}.m"] + for i in range(ndim): + result.append(f"&{var_name}.block_shape[{i}]") + for i in range(ndim): + result.append(f"&{var_name}.strides[{i}]") + return result + + +class _LazyTritonCompileKickoffLine(DeferredLineBase): + def __init__(self, lazy_kernel_names: list[str], line: str): + super().__init__(line) + self.lazy_kernel_names = lazy_kernel_names + + def __call__(self) -> str | None: + return self.line if self.lazy_kernel_names else None + + def _new_line(self, line: str) -> _LazyTritonCompileKickoffLine: + return _LazyTritonCompileKickoffLine(self.lazy_kernel_names, line) + + +@dataclasses.dataclass +class DeferredTritonCallWrapper: + """ + When using cpp wrapper, GPU kernel load and launch needs to wait for Triton kernels + to be tuned and stored as cubin files, so use a deferred generating the final wrapper around + the triton kernel until right before the prefix is written. + """ + + wrapper_name: str + kernel_name: str + kernel_name_to_body: dict[str, str] + arg_types: list[Any] + triton_meta: TritonMeta | None = None + inductor_meta: dict[str, Any] | None = None + tma_tensor_args: dict[str, str] = dataclasses.field(default_factory=dict) + + @cache_on_self + def _get_tma_args(self) -> dict[str, str]: + """Get mapping of TMA descriptor arg names to their signature types.""" + triton_meta = self.triton_meta or {} + signature = triton_meta.get("signature", {}) + for name, sig_type in signature.items(): + if sig_type == "nvTmaDesc": + raise RuntimeError( + f"nvTmaDesc (experimental TMA API) is not supported in lazy compile " + f"for arg '{name}'. Use the stable tensordesc API instead." + ) + return { + name: sig_type + for name, sig_type in signature.items() + if isinstance(sig_type, str) and sig_type.startswith("tensordesc<") + } + + def _get_cpp_param_type( + self, name: str, arg_type: Any, signature: dict[str, str] | None = None + ) -> str: + """Get the C++ parameter declaration for a given arg type.""" + if isinstance(arg_type, (torch_dtype, UnwrapUnspecArg)): + # TMA descriptors need non-const references since their fields + # are passed as void* pointers to kernel launch args + if signature and signature_is_tma_desc(signature.get(name)): + return f"{name}_type_& {name}" + return f"const {name}_type_& {name}" + elif issubclass(arg_type, (SymbolicCallArg, sympy.Expr, int)): + return f"int64_t {name}" + elif arg_type is float: + return f"float {name}" + elif arg_type is bool: + return f"bool {name}" + else: + raise ValueError(f"Unexpected arg type {arg_type}") + + def _write_wrapper_signature( + self, + prefix: IndentedBuffer, + wrapper: CppWrapperGpu, + arg_names: list[str], + arg_types: list[Any] | None = None, + signature: dict[str, str] | None = None, + ) -> None: + """Write the wrapper function signature including template and parameters.""" + if arg_types is None: + arg_types = self.arg_types + + template_types = [ + f"typename {name}_type_" + for name, arg_type in zip(arg_names, arg_types) + if isinstance(arg_type, (torch_dtype, UnwrapUnspecArg)) + ] + if template_types: + prefix.writeline_jit(f"template <{', '.join(template_types)}>") + prefix.writeline_aot( + f"template <{', '.join([*template_types, 'typename kernels_type_'])}>" + ) + + cubin_dir_param = "const std::optional& cubin_dir_ = std::nullopt" + kernels_param = "kernels_type_& kernels_" + + shared_params = [ + self._get_cpp_param_type(name, arg_type, signature) + for name, arg_type in zip(arg_names, arg_types) + ] + shared_params.append("int32_t device_idx_") + shared_params.append( + maybe_hipify_code_wrapper( + f"{wrapper.device_codegen.cpp_stream_type()} stream_" + ) + ) + + def emit(writer, params): + for p in params[:-1]: + writer(f"{p},") + writer(params[-1]) + + prefix.writeline(f"static __attribute__((noinline)) void {self.wrapper_name}(") + with prefix.indent(): + emit(prefix.writeline_jit, [*shared_params, cubin_dir_param]) + emit(prefix.writeline_aot, [*shared_params, kernels_param, cubin_dir_param]) + prefix.writeline("){") + + def generate(self, wrapper: CppWrapperGpu): + """ + Generate the GPU kernel definition, as well as load and launch code. + """ + prefix = wrapper.prefix + if self.kernel_name.startswith("multi_kernel_"): + # MultiKernel will select one kernel after running the autotune block + self.kernel_name = MultiKernelCall.lookup_choice(self.kernel_name) + + # Defer compilation to runtime if autotune_at_compile_time is False (JIT only). + # AOTI lazy-compile emission is wired up later in the stack. + if config.triton.autotune_at_compile_time is False: + return self.generate_lazy(wrapper) + + params = CudaKernelParamCache.get(self.kernel_name) + if not params: + raise AssertionError( + f"CudaKernelParamCache not populated for {self.kernel_name}" + ) + def_args = params["def_args"] + arg_types = self.arg_types + inductor_meta = params["inductor_meta"] + + if "extra_launcher_args" in inductor_meta and len(def_args) > len(arg_types): + # extra_launcher_args should already be in def_args + if len(def_args) != len(arg_types) - len( + inductor_meta["extra_launcher_args"] + ): + raise AssertionError( + "expected len(def_args) == len(arg_types) - " + f"len(extra_launcher_args), got {len(def_args)}" + ) + arg_types = arg_types + [SymbolicCallArg] * len( + inductor_meta["extra_launcher_args"] + ) + + if not V.graph.aot_mode: + prefix.writeline( + maybe_hipify_code_wrapper( + f"static {wrapper.device_codegen.cpp_kernel_type()} {self.kernel_name} = nullptr;" + ) + ) + kernel_var_name = self.kernel_name + else: + kernel_var_name = f"kernels_.{self.kernel_name}" + + # Write wrapper function signature + self._write_wrapper_signature(prefix, wrapper, def_args, arg_types) + + with prefix.indent(): + if V.graph.aot_mode: + # Emit the original Triton kernel for debugging purposes + prefix.writeline("/*") + prefix.splice(self.kernel_name_to_body[self.kernel_name]) + prefix.writeline("*/") + self.generate_grid(prefix, inductor_meta, params) + self.generate_load_kernel(prefix, kernel_var_name, params) + self.generate_launch_kernel(prefix, wrapper, kernel_var_name, params) + prefix.writeline("}") + + if not config.aot_inductor.embed_kernel_binary: + # Ensure the cubin file is included in the package + V.graph.wrapper_code.additional_files.append( + params[get_cpp_wrapper_cubin_path_name()] + ) + + def _resolve_lazy_arg_names(self) -> tuple[list[str], list[str]]: + """Compute wrapper and kernel arg names from triton_meta signature. + + Returns (wrapper_arg_names, kernel_arg_names) where: + - wrapper_arg_names: params accepted by the C++ wrapper function + - kernel_arg_names: params passed to the GPU kernel launch (non-constexpr only) + """ + if self.triton_meta is None: + raise AssertionError( + f"triton_meta is required for lazy compile of {self.kernel_name}" + ) + signature = self.triton_meta.get("signature", {}) + inductor_meta = self.inductor_meta or {} + extra_launcher_args_count = len(inductor_meta.get("extra_launcher_args", [])) + tma_tensor_args = self.tma_tensor_args + num_tma_tensor_args = len(tma_tensor_args) + + # Matches internal config params like XBLOCK, RSPLIT_SIZE, and their + # per-subkernel variants like XBLOCK_0, YBLOCK_1. + internal_config_re = re.compile(r"(?:BLOCK|RSPLIT_SIZE|RSPLIT)(?:_\d+)?$") + # Declared constexpr params (tl.constexpr in kernel signature) are excluded + # from arg_types for user-defined kernels, while value-based constexpr params + # (e.g. numel=1, arg=None) are still in arg_types. + declared_constexpr_names = OrderedSet( + inductor_meta.get("declared_constexpr_names", []) + ) + wrapper_arg_names = [] + kernel_arg_names = [] + for name, sig_type in signature.items(): + if internal_config_re.search(name): + continue + if sig_type != "constexpr": + kernel_arg_names.append(name) + if name not in declared_constexpr_names: + wrapper_arg_names.append(name) + + num_wrapper_args = ( + len(self.arg_types) - extra_launcher_args_count - num_tma_tensor_args + ) + if num_wrapper_args != len(wrapper_arg_names): + raise AssertionError( + f"Mismatch between ({num_wrapper_args}) arg_types and " + f"{len(wrapper_arg_names)} wrapper_arg_names for {self.kernel_name}." + ) + + # Append grid args: passed to wrapper. Kernel args will handle grids separately. + for i in range(extra_launcher_args_count): + wrapper_arg_names.append(f"_grid_{i}") + + # Add TMA tensor args after grid args + if tma_tensor_args: + sig_tma_keys = list(self._get_tma_args().keys()) + if list(tma_tensor_args.keys()) != sig_tma_keys: + raise AssertionError( + f"TMA tensor args order mismatch for {self.kernel_name}: " + f"{list(tma_tensor_args.keys())} vs signature order {sig_tma_keys}" + ) + for desc_name in tma_tensor_args: + wrapper_arg_names.append(f"_tma_tensor_{desc_name}") + + return wrapper_arg_names, kernel_arg_names + + def _generate_lazy_grid(self, prefix: IndentedBuffer) -> None: + """Generate grid computation code for lazy-compiled kernels.""" + kernel_name = self.kernel_name + grid_type = self.inductor_meta.get("grid_type") if self.inductor_meta else None + + # For PrecomputedGrid, generate switch statement on config_index + if grid_type == "PrecomputedGrid": + if self.inductor_meta is None: + raise AssertionError("inductor_meta is required for PrecomputedGrid") + precomputed_grids = self.inductor_meta.get("precomputed_grids", []) + extra_launcher_args = self.inductor_meta.get("extra_launcher_args", []) + + switch_cases = [] + for idx, entry in enumerate(precomputed_grids): + cpp_grids = list(entry.get("cpp", ["1L", "1L", "1L"])) + # Replace internal arg names with C++ parameter names + # e.g., _launcher_s0 -> _grid_0 + for i, arg_name in enumerate(extra_launcher_args): + cpp_grids = [g.replace(arg_name, f"_grid_{i}") for g in cpp_grids] + g0 = cpp_grids[0] + g1 = cpp_grids[1] if len(cpp_grids) > 1 else "1" + g2 = cpp_grids[2] if len(cpp_grids) > 2 else "1" + switch_cases.append( + f"case {idx}: grid_0 = {g0}; grid_1 = {g1}; grid_2 = {g2}; break;" + ) + switch_cases.append("default: grid_0 = 1; grid_1 = 1; grid_2 = 1; break;") + switch_body = "\n ".join(switch_cases) + + prefix.splice( + f"""\ + uint32_t grid_0, grid_1, grid_2; + switch ({kernel_name}_result.config_index) {{ + {switch_body} + }} + if (grid_0 == 0) return; + """ + ) + else: + from ..runtime.triton_heuristics import GridExpr + + grid = GridExpr.from_meta_lazy( + cast("InductorMeta | None", self.inductor_meta), kernel_name + ) + for line in grid.prefix: + prefix.writeline(line) + + prefix.splice( + f"""\ + uint32_t grid_0 = {grid.x_grid}; + uint32_t grid_1 = {grid.y_grid}; + uint32_t grid_2 = {grid.z_grid}; + if (grid_0 == 0) return; + """ + ) + + def _generate_lazy_tma_args( + self, + prefix: IndentedBuffer, + call_args_str: str, + kernel_arg_names: list[str], + tma_arg_names: OrderedSet[str], + signature: dict[str, str], + ) -> str: + """Unpack TMA descriptor args into kernel launch args.""" + for arg_name in kernel_arg_names: + if arg_name in tma_arg_names: + tma_parts = _unpack_tma_descriptor_args(arg_name, signature[arg_name]) + tma_str = ", ".join(tma_parts) + call_args_str = ( + f"{call_args_str}, {tma_str}" if call_args_str else tma_str + ) + return call_args_str + + def _generate_lazy_scratch( + self, + prefix: IndentedBuffer, + wrapper: CppWrapperGpu, + call_args_str: str, + ) -> str: + """Generate scratch space allocations with runtime-known sizes.""" + kernel_name = self.kernel_name + dtype_str = wrapper.codegen_dtype(torch.uint8) + device_type, _ = wrapper.codegen_device(torch.device(get_gpu_type())).split( + ", " + ) + device_ptr_type = wrapper.device_codegen.cpp_device_ptr() + # Triton reports per-CTA scratch via kernel.metadata.global_scratch_size; + # the kernel writes its slot at offset (pid * scratch_size). Scale by the + # full launch grid so concurrent CTAs don't collide. + grid_extent = "static_cast(grid_0) * grid_1 * grid_2" + for scratch_name in ("global_scratch", "profile_scratch"): + size_expr = f"{kernel_name}_result.{scratch_name}" + var = f"{scratch_name}_ptr" + prefix.splice( + maybe_hipify_code_wrapper( + f"""\ + int64_t {var}_numel = {size_expr} * {grid_extent}; + RAIIAtenTensorHandle {var}_tensor; + {device_ptr_type} {var} = allocate_scratch_tensor<{device_ptr_type}>( + {var}_numel, {dtype_str}, {device_type}, device_idx_, {var}_tensor); + """ + ) + ) + call_args_str += f", &{var}" + return call_args_str + + def _generate_lazy_launch( + self, + prefix: IndentedBuffer, + wrapper: CppWrapperGpu, + wrapper_arg_names: list[str], + kernel_arg_names: list[str], + ) -> None: + """Generate kernel launch code for lazy-compiled kernels.""" + kernel_name = self.kernel_name + signature = (self.triton_meta or {}).get("signature", {}) + tma_tensor_args = self.tma_tensor_args + num_tma_tensor_args = len(tma_tensor_args) + + # wrapper_arg_names may include grid and TMA tensor args at the end; + # only the leading portion maps 1:1 to kernel signature params. + num_signature_args = len(wrapper_arg_names) - num_tma_tensor_args + inductor_meta = self.inductor_meta or {} + num_signature_args -= len(inductor_meta.get("extra_launcher_args", [])) + + arg_type_lookup = dict( + zip(wrapper_arg_names, self.arg_types[:num_signature_args]) + ) + + # Identify TMA args — they are already passed as StableTMADescriptor params, + # so we just unpack them directly (no need to reconstruct from tensors). + tma_arg_names = OrderedSet(self._get_tma_args().keys()) + + # Non-TMA args go through generate_args_decl + non_tma_arg_names = [n for n in kernel_arg_names if n not in tma_arg_names] + non_tma_arg_types = [ + arg_type_lookup[n] for n in non_tma_arg_names if n in arg_type_lookup + ] + non_tma_arg_sigs = [signature.get(n) for n in non_tma_arg_names] + + call_args_str = wrapper.generate_args_decl( + prefix, + non_tma_arg_names, + non_tma_arg_types, + non_tma_arg_sigs, + ) + + call_args_str = self._generate_lazy_tma_args( + prefix, call_args_str, kernel_arg_names, tma_arg_names, signature + ) + call_args_str = self._generate_lazy_scratch(prefix, wrapper, call_args_str) + + common_launch_args = ( + f"grid_0, grid_1, grid_2," + f" {kernel_name}_result.num_warps," + f" {kernel_name}_result.shared_mem," + f" kernel_args_, stream_" + ) + # stream_ comes from the generated wrapper signature on both JIT and + # AOTI sides. + launch_kernel_args = [ + "grid_0", + "grid_1", + "grid_2", + f"{kernel_name}_result.num_warps", + f"{kernel_name}_result.shared_mem", + ] + + # kernel_args_ is consumed by both JIT and AOT launchKernel calls. + prefix.writeline(f"void* kernel_args_[] = {{{call_args_str}}};") + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + prefix.writeline_jit(f"launchKernel({kernel_name}, {common_launch_args});") + if enable_kernel_profile: + profile_arg_types = [arg_type_lookup.get(n) for n in kernel_arg_names] + profile_arg_sigs = [signature.get(n) for n in kernel_arg_names] + aot_profile = IndentedBuffer(initial_indent=prefix._indent) + self.generate_profiled_launch_kernel( + aot_profile, + f"kernels_.{kernel_name}", + kernel_arg_names, + profile_arg_types, + profile_arg_sigs, + [ + f"kernels_.{kernel_name}", + *launch_kernel_args, + "kernel_args_", + "stream_", + ], + num_warps=f"{kernel_name}_result.num_warps", + shared_mem=f"{kernel_name}_result.shared_mem", + ) + prefix.splice_aot(aot_profile) + else: + prefix.writeline_aot( + f"launchKernel(kernels_.{kernel_name}, {common_launch_args});" + ) + + def generate_lazy(self, wrapper: CppWrapperGpu): + """ + Generate dual-wrapper-mode C++ code for lazy Triton kernel compilation. + + DualIndentedBuffer routes lines into separate JIT and AOTI sources: + - JIT side: embeds Triton source, compiles at runtime, autotunes + with real inputs. + - AOTI side: uses a compile-time-initialized LazyKernelCompileResult + from a config header generated after the JIT first-pass. + + Grid computation and kernel launch are shared between both sides + via the LazyKernelCompileResult struct. + """ + prefix = wrapper.prefix + kernel_name = self.kernel_name + macro_prefix = kernel_name.upper() + + # Track kernel names for parallel initialization (JIT only) + wrapper._lazy_kernel_names.append(kernel_name) + + # Include TMA helpers if any args use TMA descriptors + tma_signature_types = self._get_tma_args() + if tma_signature_types: + wrapper.write_tma_descriptor_helpers_once() + + kernel_type = maybe_hipify_code_wrapper( + wrapper.device_codegen.cpp_kernel_type() + ) + + # JIT-only: static CUfunction and embedded Triton source + prefix.writeline_jit(f"static {kernel_type} {kernel_name} = nullptr;") + kernel_source_str = self.kernel_name_to_body.get(kernel_name, "") + kernel_body = f'R"TRITON(\n{kernel_source_str}\n)TRITON"' + prefix.writeline_jit( + f"static const char* {kernel_name}_source = {kernel_body};" + ) + + # LazyKernelCompileResult: JIT fills at runtime; AOTI uses compile-time + # init from the config header generated after the first pass. + prefix.writeline_jit(f"static LazyKernelCompileResult {kernel_name}_result;") + prefix.splice_aot( + f"""\ + static LazyKernelCompileResult {kernel_name}_result = {{ + {macro_prefix}_CUBIN_PATH, + {macro_prefix}_MANGLED_NAME, + {macro_prefix}_NUM_WARPS, + {macro_prefix}_SHARED_MEM, + {macro_prefix}_XBLOCKS, + {macro_prefix}_YBLOCKS, + {macro_prefix}_ZBLOCKS, + {macro_prefix}_R0BLOCKS, + {macro_prefix}_RSPLIT, + {macro_prefix}_RSPLIT_SIZE, + {macro_prefix}_CONFIG_INDEX, + {macro_prefix}_GLOBAL_SCRATCH, + {macro_prefix}_PROFILE_SCRATCH, + }}; + """ + ) + + wrapper_arg_names, kernel_arg_names = self._resolve_lazy_arg_names() + signature = (self.triton_meta or {}).get("signature", {}) + + # kernels_type_/kernels_ are routed to the AOTI buffer; if prefix is a + # plain IndentedBuffer (pure JIT lazy compile) those writes are dropped. + self._write_wrapper_signature( + prefix, + wrapper, + wrapper_arg_names, + self.arg_types, + signature, + ) + + # Build autotune args - for TMA, pass tensors instead of descriptors. + # Only iterate over signature params and grid args, not the trailing + # TMA tensor params (those are only in the C++ wrapper signature). + tma_tensor_args = self.tma_tensor_args + num_autotune_args = len(wrapper_arg_names) - len(tma_tensor_args) + autotune_arg_list = [] + # Track which args need scalar extraction for the autotune call. + # UnwrapUnspecArg args are 0-dim tensors in C++ that Triton expects + # as Python scalars; we use codegen_tensor_item to extract them. + scalar_extractions: list[tuple[str, str, torch_dtype]] = [] + for idx, name in enumerate(wrapper_arg_names[:num_autotune_args]): + if name in tma_signature_types: + autotune_arg_list.append(f"_tma_tensor_{name}") + elif isinstance(self.arg_types[idx], UnwrapUnspecArg): + scalar_var = f"_autotune_scalar_{name}" + scalar_extractions.append((name, scalar_var, self.arg_types[idx].dtype)) + autotune_arg_list.append(scalar_var) + else: + autotune_arg_list.append(name) + autotune_args = ", ".join(autotune_arg_list) + + with prefix.indent(): + # First-call initialization: JIT lazy compiles, AOTI loads cubin + + # JIT: lazy compile with autotuning on first invocation. + # Build into temp buffer to avoid DualIndentedBuffer dispatch. + jit_init = IndentedBuffer(initial_indent=prefix._indent) + jit_init.writeline(f"if ({kernel_name} == nullptr) {{") + with jit_init.indent(): + for tensor_name, scalar_var, dtype in scalar_extractions: + wrapper.codegen_tensor_item( + dtype, tensor_name, scalar_var, indented_buffer=jit_init + ) + jit_init.splice( + f"""\ + {kernel_name}_result = runTritonKernelWithAutotune( + _module_pending_kernels, "{kernel_name}", stream_, {autotune_args}); + + {kernel_name} = loadKernel( + {kernel_name}_result.cubin_path, + {kernel_name}_result.mangled_name, + {kernel_name}_result.shared_mem); + + // First invocation already ran the kernel, so return early + return; + """ + ) + jit_init.writeline("}") + prefix.splice_jit(jit_init) + + # AOTI: load precompiled cubin from compile-time-initialized result. + loaded_modules_arg = ( + ",\n &kernels_.loaded_modules_" + if V.graph.device_type != "xpu" + else "" + ) + aoti_init = IndentedBuffer(initial_indent=prefix._indent) + aoti_init.writeline(f"if (kernels_.{kernel_name} == nullptr) {{") + with aoti_init.indent(): + aoti_init.splice( + f"""\ + kernels_.{kernel_name} = loadKernel( + {kernel_name}_result.cubin_path, + {kernel_name}_result.mangled_name, + {kernel_name}_result.shared_mem, + cubin_dir_{loaded_modules_arg}); + """ + ) + aoti_init.writeline("}") + prefix.splice_aot(aoti_init) + + # Shared: grid computation and launch using result struct + self._generate_lazy_grid(prefix) + self._generate_lazy_launch( + prefix, + wrapper, + wrapper_arg_names, + kernel_arg_names, + ) + prefix.writeline("}") + + def generate_grid( + self, + prefix: IndentedBuffer, + inductor_meta: dict[str, Any], + params: dict[str, Any], + ): + from ..runtime.triton_heuristics import GridExpr + + grid = GridExpr.from_meta( + cast("InductorMeta", inductor_meta), params["config"], mode="cpp" + ) + for line in grid.prefix: + prefix.writeline(line) + prefix.splice( + f"""\ + uint32_t grid_0 = {grid.x_grid}; + uint32_t grid_1 = {grid.y_grid}; + uint32_t grid_2 = {grid.z_grid}; + """ + ) + prefix.writeline("if (grid_0 == 0 || grid_1 == 0 || grid_2 == 0) return;") + + def generate_load_kernel(self, prefix, kernel_var_name, params): + prefix.writeline(f"if ({kernel_var_name} == nullptr) {{") + with prefix.indent(): + embed_kernel_args = [f"__{params['inductor_meta']['kernel_name']}_start"] + if torch.xpu.is_available(): + # XPU needs the end address of the kernel to calculate the size of the kernel binary. + embed_kernel_args.append( + f"__{params['inductor_meta']['kernel_name']}_end" + ) + + if V.graph.aot_mode and config.aot_inductor.embed_kernel_binary: + load_kernel_args = [ + *embed_kernel_args, + cpp_string_literal(params["mangled_name"]), + str(params["shared_mem"]), + ] + if torch.xpu.is_available(): + is_spv = "true" if XPU_KERNEL_FORMAT == "spv" else "false" + if config.aot_inductor.emit_multi_arch_kernel: + is_spv = "true" + load_kernel_args.append(is_spv) + else: + load_kernel_args = [ + cpp_string_literal(params[get_cpp_wrapper_cubin_path_name()]), + cpp_string_literal(params["mangled_name"]), + str(params["shared_mem"]), + "cubin_dir_", + ] + + # In AOTI mode on CUDA/HIP, pass the loaded_modules_ vector so + # CUmodule handles are tracked and can be unloaded on destruction, + # preventing GPU code object leaks. XPU is excluded because its + # loadKernel returns std::unique_ptr and manages + # cleanup via RAII. + if V.graph.aot_mode and V.graph.device_type != "xpu": + load_kernel_args = load_kernel_args + ["&kernels_.loaded_modules_"] + + prefix.writeline( + f"{kernel_var_name} = loadKernel({', '.join(load_kernel_args)}); " + ) + prefix.writeline("}") + + def generate_launch_kernel(self, prefix, wrapper, kernel_var_name, params): + """ + Generate the GPU kernel launching code. + This is where all the call args are sorted out and generated. + If enable_kernel_profile is enabled, all args related information would be packed in this function. + """ + triton_meta = params["triton_meta"] + if len(self.arg_types) != len(params["def_args"]): + raise AssertionError((self.arg_types, params["def_args"])) + arg_type_lookup = dict(zip(params["def_args"], self.arg_types)) + # difference between Python and C++ wrapper: C++ wrapper strips out equal_to_1 constants + call_args = [ + name for name in params["call_args"] if name not in triton_meta["constants"] + ] + arg_types = [arg_type_lookup[name] for name in call_args] + arg_signatures = [triton_meta["signature"][name] for name in call_args] + num_ctas = params.get("config", {}).get("num_ctas", 1) + scratch_spaces = { + name: params[name] * num_ctas + for name in ["global_scratch", "profile_scratch"] + if params.get(name, None) is not None + } + call_args_str = wrapper.generate_args_decl( + prefix, + call_args, + arg_types, + arg_signatures, + scratch_spaces=scratch_spaces, + ) + prefix.writeline(f"void* kernel_args_[] = {{{call_args_str}}};") + num_warps = str(params["num_warps"]) + shared_mem = str(params["shared_mem"]) + launch_kernel_args = [ + kernel_var_name, + "grid_0", + "grid_1", + "grid_2", + num_warps, + shared_mem, + "kernel_args_", + "stream_", + ] + + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + if enable_kernel_profile: + self.generate_profiled_launch_kernel( + prefix, + kernel_var_name, + call_args, + arg_types, + arg_signatures, + launch_kernel_args, + num_warps=num_warps, + shared_mem=shared_mem, + ) + else: + prefix.writeline(f"launchKernel({', '.join(launch_kernel_args)});") + + def generate_profiled_launch_kernel( + self, + prefix: IndentedBuffer, + kernel_var_name: str, + call_args: list[str], + arg_types: list[Any], + arg_signatures: list[str | None], + launch_kernel_args: list[str], + num_warps: str, + shared_mem: str, + ) -> None: + """Wrap a kernel launch in an AOTI record_function profiling scope.""" + normalized_kernel_name = re.sub(r"[^a-zA-Z0-9_]", "_", kernel_var_name) + prefix.writeline("{") + with prefix.indent(): + prefix.writelines( + [ + f"std::unordered_map kwargs_{normalized_kernel_name};", + "", + ] + ) + # Add launch args info + record_launch_kernel_args = [ + ("grid_0", "grid_0"), + ("grid_1", "grid_1"), + ("grid_2", "grid_2"), + ("num_warps", num_warps), + ("shared_mem", shared_mem), + ] + for k, v in record_launch_kernel_args: + arg_name = f"{normalized_kernel_name}_{k}" + prefix.writelines( + [ + f"// Create c10::IValue for {k}", + f"C10IValueHandle tmp_{arg_name};", + f"aoti_torch_int64_to_ivalue({v}, &tmp_{arg_name});", + f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});", + f'kwargs_{normalized_kernel_name}.emplace("{k}", RAII_{arg_name});', + ] + ) + + # Add input info (This copies the logic from args_decl) + curr_arg_id = -1 + total_args = [] + ordered_argsname = [] + + def write_dummy_scalar_ivalue(arg_name): + # We only care about the shape, therefore we create a dummy scalar here. + prefix.writelines( + [ + f"// Create c10::IValue for arg_{curr_arg_id}", + f"C10IValueHandle tmp_{arg_name};", + f"aoti_torch_int64_to_ivalue(0, &tmp_{arg_name});", + f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});", + ] + ) + # pyrefly: ignore [bad-argument-type] + total_args.append(f"tmp_{arg_name}") + + def process_args_for_input_shape(arg, arg_type, arg_signature=None): + nonlocal curr_arg_id + curr_arg_id += 1 + arg_name = f"{normalized_kernel_name}_arg_{curr_arg_id}" + # ignore tma descriptors, as host-side TMA descriptors need + # to be passed to the compiled Triton kernel by value + if isinstance(arg_type, UnwrapUnspecArg) and not signature_is_tma_desc( + arg_signature + ): + write_dummy_scalar_ivalue(arg_name) + elif isinstance(arg_type, torch_dtype) and not signature_is_tma_desc( + arg_signature + ): + # This is an at::Tensor. + prefix.writelines( + [ + f"// Create c10::IValue for arg_{curr_arg_id}", + f"C10IValueHandle tmp_{arg_name};", + f"aoti_torch_tensor_to_ivalue({arg}, &tmp_{arg_name});", + f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});", + ] + ) + # pyrefly: ignore [bad-argument-type] + total_args.append(f"tmp_{arg_name}") + elif ( + isinstance(arg_type, type(SymbolicCallArg)) + and arg_signature is not None + and arg_signature in TRITON_SIGNATURE_TO_CPP + ) or arg_type in (sympy.Integer, int, sympy.Float, float): + write_dummy_scalar_ivalue(arg_name) + elif arg_signature and arg_signature.startswith("tensordesc<"): + # Skip tma related args + pass + else: + write_dummy_scalar_ivalue(arg_name) + + # Add input name and shape information + for arg, arg_type, arg_signature in zip_longest( + call_args, arg_types, arg_signatures + ): + # pyrefly: ignore [bad-argument-type] + ordered_argsname.append(f'"{arg}"') + process_args_for_input_shape(arg, arg_type, arg_signature) + + # Add input name into kwargs + name_var = f"{normalized_kernel_name}_input_names" + prefix.writelines( + [ + "// Create c10::IValue for input names", + f"C10IValueHandle tmp_{name_var};", + f"std::vector {name_var}({{{', '.join(ordered_argsname)}}});", + f"aoti_torch_strlist_to_ivalue({name_var}.data(), {len(ordered_argsname)}, &tmp_{name_var});", + f"RAIIC10IValueHandle RAII_{name_var}(tmp_{name_var});", + f'kwargs_{normalized_kernel_name}.emplace("Input Args", RAII_{name_var});', + ] + ) + + inputs_info_ = f"{normalized_kernel_name}_inputs_info_" + # We pass in the non-RAII handles, since C10 doesn't automatically free them. + # The RAII will make sure they get freed when they are out of scope. + tmp_args = ",".join(total_args) + prefix.writelines( + [ + "// Aggregate all c10::IValue for inputs", + f"std::vector {inputs_info_}({{{tmp_args}}});", + ] + ) + + # Start recording Function + prefix.writelines( + [ + "", + ( + "torch::aot_inductor::RAIIAtenRecordFunctionHandle " + f"record_{normalized_kernel_name}_" + f'("{kernel_var_name}", ' + f"reinterpret_cast(&kwargs_{normalized_kernel_name}), " + f"{inputs_info_});" + ), + "", + f"launchKernel({', '.join(launch_kernel_args)});", + ] + ) + prefix.writeline("}") + + +class CppWrapperGpu(CppWrapperCpu): + """ + Generates cpp wrapper for running on GPU and calls CUDA kernels + """ + + def __init__(self) -> None: + self.device = get_gpu_type() + self.device_codegen = get_device_op_overrides(self.device) + super().__init__() + self.grid_id = count() + self._kernel_name_to_body: dict[str, str] = {} + self._triton_call_wrappers: dict[str, DeferredTritonCallWrapper] = {} + self.autotune_input_prefix = "_REAL_AUTOTUNE_INPUT" + self._lazy_kernel_names: list[str] = [] + self._declared_aux_stream_slots: OrderedSet[int] = OrderedSet() + self._aoti_current_stream_guard_declared = False + self._aoti_stream_helpers_emitted = False + + def generate_debug_sync(self, buffer): + if self.device == "cuda": + # The fbcode JIT cpp_wrapper CUDA build links only the CUDA driver + # (libcuda), not libcudart, so the runtime cudaDeviceSynchronize symbol + # is undefined at dlopen -> use the driver-API cuCtxSynchronize there. + # On ROCm the driver-context sync hipCtxSynchronize returns + # hipErrorNotSupported at runtime, so keep the runtime cudaDeviceSynchronize + # (which hipifies to hipDeviceSynchronize and IS linked in the ROCm build). + if torch.version.hip is not None: + buffer.writeline( + maybe_hipify_code_wrapper( + "AOTI_RUNTIME_CUDA_CHECK(cudaDeviceSynchronize());" + ) + ) + else: + buffer.writeline("CUDA_DRIVER_CHECK(cuCtxSynchronize());") + return + + raise NotImplementedError( + f"triton debug sync is not supported with {self.device} cpp_wrapper" + ) + + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: GraphPartitionSignature | None = None, + ): + # TODO - support subgraph codegen by lifting functions. Check the + # comment at CppWrapperCpu `codegen_subgraph` function. + return CppWrapperGpu() + + def write_header(self): + if V.graph.is_const_graph and not V.graph.is_dual_wrapper_mode: + # We do not write header for constant graph, it will be written by main module. + return + + super().write_header() + kernel_driver = maybe_hipify_code_wrapper(self.device_codegen.kernel_driver()) + if V.graph.is_const_graph and V.graph.is_dual_wrapper_mode: + # For a dual-wrapper-mode const graph, only the standalone JIT + # output needs this header content. The AOTI const body is spliced + # into the main AOTI source, which has its own kernel driver. + # super().write_header() early-returns for const graphs before it + # can call add_device_include, so emit the JIT device include here; + # otherwise the kernel driver's CUfunction/CUmodule/uint32_t types + # have no declaring header and fail to compile under -nostdinc. + for device in V.graph.device_types: + if device != "meta": + self.header.splice_jit(self.get_device_include_path_jit(device)) + self.header.splice_jit(kernel_driver) + else: + self.header.splice(kernel_driver) + + def _generate(self, is_inference): + # Per-Run()-function state, reset each generation. Do NOT reset + # _aoti_stream_helpers_emitted here: the helper structs are spliced into + # the file-level header once per instance, and _generate can run more + # than once against the same header (resetting it re-splices and yields + # a C++ redefinition). + self._declared_aux_stream_slots.clear() + self._aoti_current_stream_guard_declared = False + return super()._generate(is_inference) + + @cache_on_self + def write_tma_descriptor_helpers_once(self): + self.header.splice(self.device_codegen.tma_descriptor_helpers()) + + def write_get_raw_stream(self, device_idx: int, graph_name: str) -> str: + # Pure AOTI receives the stream as a function parameter. JIT and + # dual-wrapper-mode code use an explicit stream variable so the shared kernel + # call arguments are valid for the JIT entry point. + if V.graph.aot_mode and not V.graph.is_dual_wrapper_mode: + return "stream" + + name = f"stream{device_idx}" + # In dual-wrapper mode, the JIT stream is declared at the entry function + # prologue (see _codegen_entry_impl_prologue) so it stays in scope + # across all kernel call sites. + if V.graph.is_dual_wrapper_mode: + return name + + self.writeline( + maybe_hipify_code_wrapper( + f"{self.device_codegen.cpp_stream_type()} {name};" + ) + ) + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK({self.device_codegen.aoti_get_stream()}({device_idx}, (void**)&{name}));" + ) + return name + + def _ensure_aoti_stream_helpers_emitted(self) -> None: + if self._aoti_stream_helpers_emitted: + return + # The stream/event helpers in streams.h are CUDA-specific (cudaEvent_t, + # cudaStream_t, cudaEventRecord, ...). Guarding here on the device type + # prevents the CUDA-only symbols from being emitted into XPU generated + # code, where SYCL in-order queues handle event ordering implicitly. + if self.device == "xpu": + return + self._aoti_stream_helpers_emitted = True + with open( + os.path.join(os.path.dirname(__file__), "aoti_runtime", "streams.h") + ) as f: + self.header.splice(maybe_hipify_code_wrapper(f.read())) + self.header.splice( + """ + namespace { + + static thread_local torch::aot_inductor::AOTIPerThreadEventCache + _aoti_event_cache; + static thread_local torch::aot_inductor::AOTIPerThreadStreamCache + _aoti_aux_stream_cache; + + } // namespace + """ + ) + + def codegen_stream_info_prologue( + self, + code: IndentedBuffer, + num_streams: int, + stream_idx_to_user_obj_idx: dict[int, int], + ) -> None: + if num_streams <= 1: + return + if not V.graph.aot_mode: + raise NotImplementedError( + "Multi-stream cpp_wrapper codegen is only supported for AOTI." + ) + self._ensure_aoti_stream_helpers_emitted() + code.writeline( + f"_aoti_aux_stream_cache.ensure({num_streams}, this->device_idx_, stream);" + ) + if not self._aoti_current_stream_guard_declared: + code.writeline( + f"std::unique_ptr<{V.graph.device_ops.cpp_aoti_stream_guard()}> " + "_aoti_current_stream_guard;" + ) + self._aoti_current_stream_guard_declared = True + + stream_type = self.device_codegen.cpp_stream_type() + for i in range(1, num_streams): + if i in self._declared_aux_stream_slots: + continue + code.writeline( + maybe_hipify_code_wrapper( + f"{stream_type} {get_stream_name(i)} = " + f"_aoti_aux_stream_cache.get({i}, this->device_idx_, stream);" + ) + ) + self._declared_aux_stream_slots.add(i) + + def codegen_enter_cuda_stream_context( + self, code: IndentedBuffer, stream_idx: int + ) -> None: + if stream_idx == 0: + return + code.writeline( + "_aoti_current_stream_guard = " + f"std::make_unique<{V.graph.device_ops.cpp_aoti_stream_guard()}>(" + f"{self._stream_expr_for_idx(stream_idx)}, this->device_idx_);" + ) + + def codegen_exit_cuda_stream_context(self, code: IndentedBuffer) -> None: + code.writeline("_aoti_current_stream_guard.reset();") + + def _stream_expr_for_idx(self, stream_idx: int) -> str: + if stream_idx == 0: + return "stream" + return f"_aoti_aux_stream_cache.get({stream_idx}, this->device_idx_, stream)" + + def _emit_stream_op_inline(self, kernel_name: str | None, args: list[str]) -> bool: + if kernel_name is None or not V.graph.aot_mode: + return False + if self.device == "xpu": + return False + if kernel_name in AOTI_UNSUPPORTED_STREAM_OP_REASONS: + raise NotImplementedError( + f"{kernel_name} is not supported in AOTI cpp_wrapper. " + f"{AOTI_UNSUPPORTED_STREAM_OP_REASONS[kernel_name]}" + ) + op = AOTI_SUPPORTED_STREAM_OP_NAMES.get(kernel_name) + if op is None: + return False + + def _parse_idx(arg: str) -> int: + return int(arg.rstrip("Ll")) + + self._ensure_aoti_stream_helpers_emitted() + event_idx = _parse_idx(args[0]) + if op == "record_event": + stream_idx = _parse_idx(args[1]) + self.writeline( + maybe_hipify_code_wrapper( + "AOTI_RUNTIME_CUDA_CHECK(cudaEventRecord(" + f"_aoti_event_cache.get({event_idx}, this->device_idx_), " + f"{self._stream_expr_for_idx(stream_idx)}));" + ) + ) + return True + if op == "wait_event": + stream_idx = _parse_idx(args[1]) + self.writeline( + maybe_hipify_code_wrapper( + "AOTI_RUNTIME_CUDA_CHECK(cudaStreamWaitEvent(" + f"{self._stream_expr_for_idx(stream_idx)}, " + f"_aoti_event_cache.get({event_idx}, this->device_idx_), 0));" + ) + ) + return True + if op == "synchronize_event": + self.writeline( + maybe_hipify_code_wrapper( + "AOTI_RUNTIME_CUDA_CHECK(cudaEventSynchronize(" + f"_aoti_event_cache.get({event_idx}, this->device_idx_)));" + ) + ) + return True + return False + + def _generate_extern_kernel_alloc_helper(self, extern_kernel, args): + kernel_name = getattr(extern_kernel, "python_kernel_name", None) + if self._emit_stream_op_inline(kernel_name, args): + if V.extern_kernel_nodes: + V.extern_kernel_nodes.pop() + return + super()._generate_extern_kernel_alloc_helper(extern_kernel, args) + + def generate_fallback_kernel_with_runtime_lookup( + self, + buf_name, + python_kernel_name, + get_args, + op_overload, + raw_args, + outputs, + ): + if self._emit_stream_op_inline(python_kernel_name, list(get_args())): + if V.extern_kernel_nodes: + V.extern_kernel_nodes.pop() + return + super().generate_fallback_kernel_with_runtime_lookup( + buf_name, + python_kernel_name, + get_args, + op_overload, + raw_args, + outputs, + ) + + def get_autotuning_input_name(self, idx): + return f"{self.autotune_input_prefix}_{idx}" + + def codegen_inputs(self): + # See Note: [Input Alignment handling in Inductor] + # + # JIT Inductor does not guard on input alignment. It relies on copy_misaligned_inputs to + # copy misaligned inputs to aligned buffers. For AOTInductor, we need to do the same in cpp. + + if config.is_fbcode(): + # TODO: This is added because FC. Remove this once the newly added shim symbols, + # e.g. aoti_torch_clone_preserve_strides, have landed + return super().codegen_inputs() + + if V.graph.aot_mode and V.graph.inputs_to_check: + for idx in V.graph.inputs_to_check: + input_name = V.graph.graph_input_names[idx] + if input_name not in V.graph.graph_inputs: + raise AssertionError(f"{input_name} not found in graph inputs") + value = V.graph.graph_inputs[input_name] + if not isinstance(value, TensorBox): + raise AssertionError( + f"{input_name} is expected to be tensor but found as {type(value)}" + ) + warn_msg = ( + f"Input {idx} was compiled as {GPU_ALIGN_BYTES}-bytes aligned, " + "but it is not aligned at run time. Copying to an aligned tensor " + "to guarantee correctness, but expect a performance hit." + ) + alignment_check = f""" + if ((reinterpret_cast({input_name}.data_ptr()) & ({GPU_ALIGN_BYTES} -1)) != 0) {{ + AOTI_TORCH_WARN("{warn_msg}"); + AtenTensorHandle {input_name}_aligned; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_clone_preserve_strides({input_name}, &{input_name}_aligned)); + {input_name} = std::move(RAIIAtenTensorHandle({input_name}_aligned)); + }} + """ + self.prefix.splice_aot(alignment_check) + + super().codegen_inputs() + + def _define_kernel_helper( + self, + kernel_name: str, + kernel_body: str, + metadata: str | None = None, + gpu: bool = True, + cpp_definition: str | None = None, + ): + if gpu: + self._kernel_name_to_body[kernel_name] = kernel_body + if config.triton.autotune_at_compile_time: + # Call PythonWrapperCodegen to create the autotune code block + PythonWrapperCodegen._define_kernel_helper( + self, kernel_name, kernel_body, metadata, gpu, cpp_definition + ) + else: + return CppWrapperCpu._define_kernel_helper( + self, kernel_name, kernel_body, metadata, gpu, cpp_definition + ) + + def generate(self, is_inference): + with dynamo_timed("CppWrapperGpu.generate", log_pt2_compile_event=True): + return super().generate(is_inference) + + def _codegen_entry_impl_prologue(self): + super()._codegen_entry_impl_prologue() + # ensure_triton_kernel_compiles_started() is JIT-only; AOTI has no + # Python-dependent lazy compile flow. + self.prefix.writeline_jit( + _LazyTritonCompileKickoffLine( + self._lazy_kernel_names, "ensure_triton_kernel_compiles_started();" + ) + ) + # In dual-wrapper mode, hoist the JIT-side stream declaration to the entry + # function prologue. Kernel calls run inside KernelContextGuard + # scopes, so a per-call declaration would be scoped to the guard + # and unavailable to other kernel calls in the same function. + if V.graph.is_dual_wrapper_mode: + stream_type = maybe_hipify_code_wrapper( + self.device_codegen.cpp_stream_type() + ) + get_stream = self.device_codegen.aoti_get_stream() + for device_idx in sorted(V.graph.device_idxs): + name = f"stream{device_idx}" + self.prefix.writeline_jit(f"{stream_type} {name};") + self.prefix.writeline_jit( + f"AOTI_TORCH_ERROR_CODE_CHECK(" + f"{get_stream}({device_idx}, (void**)&{name}));" + ) + + def finalize_prefix(self): + """Define the triton kernels now that autotuning is finished""" + old_prefix = self.prefix # new content should go at start of prefix + + # Generating triton kernel callers can modify the prefix (cached dtypes), + # so do this before running finalize_prefix(), but put the generated code + # after the finalize_prefix() code. + triton_prefix = make_codegen_buffer() + with self._target_buf("prefix", triton_prefix): + for kernel in self._triton_call_wrappers.values(): + self.prefix.writeline("\n") + kernel.generate(self) + + # Generate parallel kernel compilation initialization function. + # JIT-only since AOTI has no Python dependency. + if self._lazy_kernel_names: + start_compile_body = ( + "loadLazyCompileFuncs();\n" + " _module_pending_kernels = PyDict_New();\n" + ' AOTI_TORCH_CHECK(_module_pending_kernels, "Failed to create pending kernels dict");\n' + " " + + "\n ".join( + f'startKernelCompile(_module_pending_kernels, "{name}", {name}_source);' + for name in self._lazy_kernel_names + ) + ) + self.include_extra_header("mutex") + self.prefix.writeline_jit("") + self.prefix.splice_jit( + f"""\ +// Start parallel compilation of all Triton kernels. +static inline void start_all_triton_kernel_compiles() {{ + {start_compile_body} +}} + +// inductor_entry_impl calls this on every forward; +// std::call_once makes the first call do the work. +static std::once_flag _triton_kernel_compile_init_flag; +static inline void ensure_triton_kernel_compiles_started() {{ + std::call_once(_triton_kernel_compile_init_flag, [] {{ + start_all_triton_kernel_compiles(); + }}); +}} +""" + ) + + self.prefix = make_codegen_buffer() + super().finalize_prefix() + + self.prefix.splice(triton_prefix) + self.prefix.writeline("\n") + self.prefix.splice(old_prefix) + + def generate_tma_descriptor(self, desc): + self.write_tma_descriptor_helpers_once() + + if isinstance(desc, TMADescriptorExperimental): + self._generate_experimental_tma_descriptor(desc) + else: + if not isinstance(desc, TMADescriptorStable): + raise AssertionError(f"expected TMADescriptorStable, got {type(desc)}") + self._generate_stable_tma_descriptor(desc) + + def _generate_experimental_tma_descriptor(self, desc): + # generate data pointer for the source tensor + source = self.generate_args_decl( + code=self, + call_args=[self.val_to_arg_str(desc.tensor)], + arg_types=[desc.tensor.get_dtype()], + arg_signatures=[None], + # these args are passed to initNDTMADescriptor, which is NOT a triton kernel + is_triton_kernel=False, + ) + + desc_name = desc.name + self.writeline(f"alignas(64) CUtensorMap {desc_name};") + + # `source` is in the form of `&var_x`, where `var_x` is the data pointer + # (CUdeviceptr); we dereference `source` and cast to `void*` to pass to + # the data pointer of the source tensor to the helper function + # `init{1,2}DTMADescriptor` + ptr = f"reinterpret_cast(*({source}))" + dims = ", ".join(self.val_to_arg_str(dim) for dim in desc.dims) + block_dims = ", ".join(self.val_to_arg_str(dim) for dim in desc.block_dims) + element_size = self.val_to_arg_str(desc.element_size) + fn = f"init{desc.rank}DTMADescriptor" + args = f"&{desc_name}, {ptr}, {dims}, {block_dims}, {element_size}" + self.writeline(f"{fn}({args});") + + def _generate_stable_tma_descriptor(self, desc): + source = self.generate_args_decl( + code=self, + call_args=[self.val_to_arg_str(desc.tensor)], + arg_types=[desc.tensor.get_dtype()], + arg_signatures=[None], + # these args are passed to initNDTMADescriptor, which is NOT a triton kernel + is_triton_kernel=False, + ) + + desc_name = desc.name + # Pack the relevant information into a StableTMADescriptor struct. + # See [Note: AOTI TMA Stable handling] for more details. + self.writeline(f"alignas(64) StableTMADescriptor {desc_name};") + + def fill_array(name, values): + for i, val in enumerate(values): + self.writeline(f"{name}[{i}] = {val};") + + ptr = f"reinterpret_cast(*({source}))" + rank = len(desc.tensor.get_size()) + + fill_array(f"{desc_name}.block_shape", desc.block_shape) + fill_array(f"{desc_name}.global_shape", desc.tensor.get_size()) + fill_array(f"{desc_name}.strides", desc.tensor.get_stride()) + + element_size = self.val_to_arg_str(desc.tensor.get_dtype().itemsize) + fn = "initTMADescriptor" + args = ", ".join( + str(x) + for x in [ + f"&{desc_name}.m", + ptr, + element_size, + rank, + f"{desc_name}.block_shape", + f"{desc_name}.global_shape", + f"{desc_name}.strides", + ] + ) + self.writeline(f"{fn}({args});") + + def generate_args_decl( + self, + code: IndentedBuffer | Self, + call_args, + arg_types, + arg_signatures, + is_triton_kernel=True, + scratch_spaces: dict[str, int] | None = None, + ): + """ + Generates any declarations of args to pass into a kernel call, and then returns the arg names. + + In more detail: + * declarations: e.g. this function has a side effect of generating lines like `auto var_0 = ...;` + * returns: a string with the list of args, e.g. "var_0, var_1" + + call_args: list of call arguments + arg_types: list of argument types + arg_signatures: list with signatures of all the args + is_triton_kernel: whether these are passed into a triton kernel or not. In particular, + calls to triton kernels will have an additional global scratch space + arg injected at the front of the arg list. + """ + new_args: list[str] = [] + + def process_tma_stable_arg(arg, arg_type, arg_signature, var_name): + # [Note: AOTI TMA Stable handling] + # For most args, a single arg passed to the python triton interface + # maps to a single arg in the cubin interface. However, for host-side + # TMA descriptors, a single python arg turns into 1 + 2 * N args in the + # cubin interface (where N is the rank). + # + # To do this: at TMA codegen time (for aoti), we generate a struct + # (StableTMADescriptor) containing the necessary information; and then + # when we call the function (i.e. here), we unpack the struct members. + code.writeline(f"auto {var_name} = {cexpr(arg)};") + return _unpack_tma_descriptor_args(var_name, arg_signature) + + def process_args(arg, arg_type, arg_signature=None): + var_name = f"var_{next(self.arg_var_id)}" + # ignore tma descriptors, as host-side TMA descriptors need + # to be passed to the compiled Triton kernel by value + if isinstance(arg_type, UnwrapUnspecArg) and not signature_is_tma_desc( + arg_signature + ): + self.codegen_tensor_item( + arg_type.dtype, + arg, + var_name, + indented_buffer=code, + ) + new_args.append(f"&{var_name}") + elif isinstance(arg_type, torch_dtype) and not signature_is_tma_desc( + arg_signature + ): + device_ptr_type = self.device_codegen.cpp_device_ptr() + code.writeline( + maybe_hipify_code_wrapper( + f"{device_ptr_type} {var_name} = reinterpret_cast<{device_ptr_type}>({arg}.data_ptr());" + ) + ) + new_args.append(f"&{var_name}") + # For symbolic call arguments, examine the arg signatures from triton meta + # to explicitly cast to the right type + # Reason: `auto` can infer unexpected type against kernel input signature. + elif ( + isinstance(arg_type, type(SymbolicCallArg)) + and arg_signature is not None + and arg_signature in TRITON_SIGNATURE_TO_CPP + ): + code.writeline( + f"{TRITON_SIGNATURE_TO_CPP[arg_signature]} {var_name} = {cexpr(arg)};" + ) + new_args.append(f"&{var_name}") + elif arg_type in (sympy.Integer, int): + code.writeline(f"int {var_name} = {cexpr(arg)};") + new_args.append(f"&{var_name}") + elif arg_type in (sympy.Float, float): + # Use signature type if available, otherwise default to float + cpp_type = TRITON_SIGNATURE_TO_CPP.get( # pyrefly: ignore[no-matching-overload] + arg_signature, "float" + ) + code.writeline(f"{cpp_type} {var_name} = {cexpr(arg)};") + new_args.append(f"&{var_name}") + elif arg_signature and arg_signature.startswith("tensordesc<"): + new_args.extend( + process_tma_stable_arg(arg, arg_type, arg_signature, var_name) + ) + else: + code.writeline(f"auto {var_name} = {cexpr(arg)};") + new_args.append(f"&{var_name}") + + for arg, arg_type, arg_signature in zip_longest( + call_args, arg_types, arg_signatures + ): + process_args(arg, arg_type, arg_signature) + + for scratch_name, workspace_size in (scratch_spaces or {}).items(): + if ( + is_triton_kernel + and ( + scratch := self.device_codegen.cpp_scratch( + next(self.arg_var_id), + workspace=TritonScratchWorkspace( + size=workspace_size, + generate_dtype_str=( + lambda: self.codegen_dtype(torch.uint8) + ), + ), + prefix=scratch_name, + ) + ) + is not None + ): + scratch_def, scratch_var = scratch + code.writelines([maybe_hipify_code_wrapper(x) for x in scratch_def]) + new_args.append(f"&{scratch_var}") + + return ", ".join(new_args) + + def _generate_kernel_call_helper( + self, + kernel_name: str, + call_args, + *, + device=None, + triton=True, + arg_types=None, + raw_keys=None, + raw_args=None, + triton_meta: TritonMeta | None = None, + inductor_meta=None, + graph_name="", + original_fxnode_name=None, + current_stream_idx=None, + ): + """ + Override the default value of argument 'gpu' to True here. + generate_kernel_call can still be called with gpu=False because of + a mix of cpu kernels and gpu kernels. + """ + device = device or V.graph.get_current_device_or_throw() + if device.type == "cpu": + # Even in CppWrapperGpu, we may see cpp kernels + return CppWrapperCpu._generate_kernel_call_helper( + self, + kernel_name, + call_args, + device=device, + triton=triton, + arg_types=arg_types, + raw_keys=raw_keys, + raw_args=raw_args, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + ) + + if ( + triton + and config.triton.autotune_at_compile_time + and kernel_name not in self.kernel_autotune_names + ): + # Call PythonWrapperCodegen to create the autotune code block + PythonWrapperCodegen._generate_kernel_call_helper( + self, + kernel_name, + call_args, + device=device, + triton=triton, + arg_types=arg_types, + raw_keys=raw_keys, + raw_args=raw_args, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + original_fxnode_name=original_fxnode_name, + ) + + if ( + V.graph.aot_mode + and current_stream_idx is not None + and current_stream_idx != 0 + ): + stream = get_stream_name(current_stream_idx) + else: + stream = self.write_get_raw_stream(device.index, graph_name) + + if triton: + call_args, arg_types = self.prepare_triton_wrapper_args( + call_args, + # pyrefly: ignore [bad-argument-type] + arg_types, + ) + + # For lazy compile mode with TMA, extract underlying tensor names + tma_tensor_args: dict[str, str] = {} + is_lazy_compile = config.triton.autotune_at_compile_time is False + if is_lazy_compile and raw_args and triton_meta: + signature = triton_meta.get("signature", {}) + raw_keys_list = raw_keys or [] + for key, raw_arg in zip(raw_keys_list, raw_args): + sig_type = signature.get(key, "") + if isinstance(sig_type, str) and signature_is_tma_desc(sig_type): + if isinstance(raw_arg, TMADescriptorStable): + # Get the underlying tensor name + tensor_name = raw_arg.get_tensor().get_name() + tma_tensor_args[key] = tensor_name + else: + raise AssertionError("Unsupported TMA descriptor type") + + wrapper_name = f"call_{kernel_name}" + if wrapper_name not in self._triton_call_wrappers: + self._triton_call_wrappers[wrapper_name] = DeferredTritonCallWrapper( + wrapper_name, + kernel_name, + self._kernel_name_to_body, + arg_types, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + tma_tensor_args=tma_tensor_args, + ) + + # For TMA in lazy compile mode, add tensor args to the call + if is_lazy_compile and tma_tensor_args: + for tensor_name in tma_tensor_args.values(): + call_args.append(tensor_name) + arg_types.append( + torch.float32 + ) # dtype doesn't matter, just need tensor type + + # AOTI side uses this->device_idx_ so the model honors runtime device + # assignment; JIT side has no this->device_idx_ in scope, so use the + # concrete graph device index. Similarly, AOTI side always uses the + # `stream` function parameter of run_impl, while JIT side uses the + # locally-declared stream{idx} (see _codegen_entry_impl_prologue). + aoti_device_idx = ( + "this->device_idx_" if V.graph.aot_mode else str(device.index) + ) + jit_device_idx = str(device.index) + jit_call_args = [*call_args, jit_device_idx, stream] + aot_call_args = [*call_args, aoti_device_idx, "stream"] + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + jit_call_args[: len(arg_types)], kernel_name, arg_types, None + ) + # DebugPrinterManager is AOTI-only: route its writes through + # writeline_aot so they're dropped on the JIT side (no-op for the + # pure-JIT IndentedBuffer; AOT-only for DualIndentedBuffer). Without + # this, the JIT buffer would receive before/after-launch prints + # after the JIT launch, reporting post-launch state as pre-launch. + with self.set_writeline(self.wrapper_call, self.wrapper_call.writeline_aot): + with debug_printer_manager: + self.wrapper_call.writeline_jit( + f"{wrapper_name}({', '.join(jit_call_args)});" + ) + self.wrapper_call.writeline_aot( + f"{wrapper_name}({', '.join(aot_call_args)}, " + f"kernels, this->cubin_dir_);" + ) + else: + casted = [] + # pyrefly: ignore [bad-argument-type, no-matching-overload] + for arg_type, arg in zip(arg_types, call_args): + new_arg = arg + if arg_type.endswith("*") and arg != "nullptr": + new_arg = f"{arg}.data_ptr()" + # pyrefly: ignore [bad-argument-type] + casted.append(f"({arg_type}){cexpr(new_arg)}") + call_args_str = ", ".join(casted) + # AOT: dispatch through AOTInductorModelKernels member. + # JIT: call the extern "C" symbol directly (resolved at link time + # via extra_flags pointing at the compiled .so). + kernel_prefix = "kernels." if V.graph.aot_mode else "" + self.writeline(f"{kernel_prefix}{kernel_name}({call_args_str}, {stream});") + + def prepare_triton_wrapper_args( + self, call_args: list[Any], arg_types: list[Any] + ) -> tuple[list[Any], list[Any]]: + if len(call_args) != len(arg_types): + raise AssertionError((call_args, arg_types)) + new_args = [] + new_args_types = [] + for arg, arg_type in zip(call_args, arg_types): + if isinstance(arg, str): + if isinstance(arg_type, torch_dtype) and should_unwrap_unspec_arg(arg): + # dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar + arg_type = UnwrapUnspecArg(dtype=arg_type) + new_args.append(arg) + elif isinstance(arg, bool): + new_args.append(str(arg).lower()) + elif isinstance(arg, (int, float, SymbolicCallArg)): + if isinstance(arg, float): + new_args.append(self.generate_float_value(arg)) + else: + new_args.append(str(arg)) + else: + new_args.append(cexpr(V.graph.sizevars.simplify(arg))) + new_args_types.append(arg_type) + return new_args, new_args_types + + def make_zero_buffer(self, name): + return f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_zero_({name}.get()));" + + +@dataclasses.dataclass +class UnwrapUnspecArg: + """Marker that we need to call .item() on the tensor""" + + dtype: torch_dtype diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_mps.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_mps.py new file mode 100644 index 0000000000000000000000000000000000000000..8ddeeed7678d8704a8ed9221be5ffc9534321fa6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_mps.py @@ -0,0 +1,306 @@ +from typing import Any + +import sympy + +import torch +from torch.utils._ordered_set import OrderedSet + +from ..ir import GraphPartitionSignature +from ..runtime.hints import TritonMeta +from ..virtualized import V +from .cpp_wrapper_cpu import CppWrapperCpu +from .cpp_wrapper_gpu import CppWrapperGpu +from .wrapper import KernelCallLine, PythonWrapperCodegen + + +class CppWrapperMps(CppWrapperGpu): + """ + Generates cpp wrapper for running on MPS and calls metal kernels + """ + + def __init__(self) -> None: + super().__init__() + self._used_kernel_names: OrderedSet[str] = OrderedSet() + self._lambda_counter: int = 0 + + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: GraphPartitionSignature | None = None, + ) -> "CppWrapperMps": + return CppWrapperMps() + + def _generate_kernel_call_helper( + self, + kernel_name: str, + call_args: list[str], + *, + device: torch.device | None = None, + triton: bool = True, + arg_types: tuple[Any, ...] | None = None, + raw_keys: tuple[Any, ...] | None = None, + raw_args: tuple[Any, ...] | None = None, + triton_meta: TritonMeta | None = None, + inductor_meta: dict[str, Any] | None = None, + graph_name: str = "", + original_fxnode_name: str | None = None, + current_stream_idx: int | None = None, + ) -> None: + """ + Generates MPS kernel call code. It should look something like: + ``` + auto mps_lib_0_lambda = [&](AOTIMetalKernelFunctionHandle handle) { + aoti_torch_mps_start_encoding(handle); + aoti_torch_mps_set_arg_tensor(handle, 0, buf0); + aoti_torch_mps_set_arg_tensor(handle, 1, arg0_1); + aoti_torch_mps_set_arg_tensor(handle, 2, arg1_1); + aoti_torch_mps_dispatch_single(handle, static_cast(10LL)); + }; + + std::function mps_lib_0_func_wrapper = mps_lib_0_lambda; + aoti_torch_mps_run_command_block(get_mps_lib_0_handle(), aoti_torch_mps_shared_callback, &mps_lib_0_func_wrapper); + ``` + """ + device = device or V.graph.get_current_device_or_throw() + if device.type == "cpu": + # Even in CppWrapperGpu, we may see cpp kernels + return CppWrapperCpu._generate_kernel_call_helper( + self, + kernel_name, + call_args, + device=device, + triton=triton, + arg_types=arg_types, + raw_keys=raw_keys, + raw_args=raw_args, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + ) + + if device.type != "mps": + raise AssertionError(f"expected device.type == 'mps', got {device.type}") + + if arg_types is None: + raise AssertionError("expected arg_types to not be None") + + new_args = [] + for idx, (arg, arg_type) in enumerate(zip(call_args[:-2], arg_types[:-2])): + if isinstance(arg_type, torch.dtype): + new_args.append(f"aoti_torch_mps_set_arg_tensor(handle, {idx}, {arg});") + elif arg_type in (int, sympy.core.symbol.Symbol): + new_args.append(f"aoti_torch_mps_set_arg_int(handle, {idx}, {arg});") + else: + raise NotImplementedError( + f"Unsupported arg type {arg_type} for arg {arg} for kernel {kernel_name}" + ) + + threads, group_size = call_args[-2], call_args[-1] + if threads is None: + raise NotImplementedError("No threads or group_size provided") + + # Check if threads is a single value or an array-like structure + threads_str = threads + is_single_value = ( + threads_str.startswith("{") + and threads_str.endswith("}") + and threads_str.count(",") == 0 + ) or not threads_str.startswith(("{", "[")) + + if is_single_value: + # Extract single value from braces if present + if threads_str.startswith("{") and threads_str.endswith("}"): + single_value = threads_str[1:-1].strip() # Remove braces + else: + single_value = threads_str + + if group_size is None: + new_args.append( + f"aoti_torch_mps_dispatch_single(handle, {single_value});" + ) + else: + # Extract group size value if it's also in braces + group_size_str = group_size + if group_size_str.startswith("{") and group_size_str.endswith("}"): + group_size_value = group_size_str[1:-1].strip() + else: + group_size_value = group_size_str + new_args.append( + f"aoti_torch_mps_dispatch_single_with_group_size(handle, {single_value}, {group_size_value});" + ) + else: + # Handle array case - need to convert initializer list to array + # Use kernel name to make variable names unique + threads_var = f"{kernel_name}_threads_array" + group_size_var = f"{kernel_name}_group_size_array" + + # Extract array size from the initializer list string + def get_array_size(array_str: str) -> int: + # Remove braces and whitespace + content = array_str.strip() + if content.startswith("{") and content.endswith("}"): + content = content[1:-1].strip() + + if not content: # Empty array + return 0 + + # Count elements by counting commas, accounting for nested structures + depth = 0 + comma_count = 0 + for char in content: + if char in "({[<": + depth += 1 + elif char in ")}]>": + depth -= 1 + elif char == "," and depth == 0: + comma_count += 1 + + return comma_count + 1 # Number of elements = commas + 1 + + threads_size = get_array_size(threads_str) + + if group_size is None: + new_args.append("{") + new_args.append(f" uint64_t {threads_var}[] = {threads};") + new_args.append( + f" aoti_torch_mps_dispatch_array(handle, {threads_var}, {threads_size});" + ) + new_args.append("}") + else: + group_size_str = group_size + group_size_size = get_array_size(group_size_str) + new_args.append("{") + new_args.append(f" uint64_t {threads_var}[] = {threads};") + new_args.append(f" uint64_t {group_size_var}[] = {group_size};") + dispatch_args = f"handle, {threads_var}, {threads_size}, {group_size_var}, {group_size_size}" + new_args.append( + f" aoti_torch_mps_dispatch_array_with_group_size({dispatch_args});" + ) + new_args.append("}") + + # debug printer related logic for cpp kernel type. + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + call_args[:-2], + kernel_name, + None, + None, + "cpp", + ) + with debug_printer_manager: + self.write_mps_kernel_call(kernel_name, new_args) + + def write_mps_kernel_call(self, name: str, call_args: list[str]) -> None: + # Generate unique variable names to avoid duplicate declarations + # when the same MPS lib is used multiple times + unique_suffix = self._lambda_counter + self._lambda_counter += 1 + + lambda_name = f"{name}_lambda_{unique_suffix}" + wrapper_name = f"{name}_func_wrapper_{unique_suffix}" + + # Generate the function call code (in current location) + # Create lambda that captures by reference and pass its pointer through void* + self.writeline( + f"auto {lambda_name} = [&](AOTIMetalKernelFunctionHandle handle) {{" + ) + self.writeline(" aoti_torch_mps_start_encoding(handle);") + + # Output call args directly since we're capturing by reference + for call_arg in call_args: + self.writeline(f" {call_arg}") + self.writeline("};") + self.writeline("") + + # Pass lambda pointer through void* + self.writeline( + f"std::function {wrapper_name} = {lambda_name};" + ) + self.writeline( + f"aoti_torch_mps_run_command_block(get_{name}_handle(), aoti_torch_mps_shared_callback, &{wrapper_name});" + ) + + @staticmethod + def get_device_include_path_aot(device: str) -> str: + return ( + "#include \n" + "#include " + ) + + def codegen_additional_funcs(self) -> None: + """ + Generate thread-safe lazy singleton pattern for MPS shader libraries with RAII cleanup. + + The generated code will look like: + ``` + AOTIMetalKernelFunctionHandle get_mps_lib_0_handle() { + static auto kernel_handle = []() { + AOTIMetalShaderLibraryHandle lib_handle = nullptr; + AOTIMetalKernelFunctionHandle kern_handle = nullptr; + + aoti_torch_mps_create_shader_library(mps_lib_0_source, &lib_handle); + aoti_torch_mps_get_kernel_function(lib_handle, "generated_kernel", &kern_handle); + + // RAII wrapper with custom deleter + auto lib_deleter = [](AOTIMetalShaderLibraryHandle h) { + if (h) aoti_torch_mps_delete_shader_library(h); + }; + + using LibDeleter = decltype(lib_deleter); + using LibPtr = std::unique_ptr; + + // Return pair of kernel handle and library smart pointer for cleanup + return std::make_pair(kern_handle, LibPtr(lib_handle, lib_deleter)); + }(); + return kernel_handle.first; + } + ``` + """ + + # Add shimified handles and functions + shader_libraries: OrderedSet[str] = OrderedSet() + for line in self.lines: + if not isinstance(line, KernelCallLine): + continue + if line.device.type != "mps": + continue + + # Extract library name from kernel name (e.g., "mps_lib_0" from kernel calls) + if line.kernel_name not in self._used_kernel_names: + self._used_kernel_names.add(line.kernel_name) + shader_libraries.add(line.kernel_name) + + # NOTE: For shimified version, we expect the shader source constant to be generated + # by the existing MPS shader generation process, but instead of instantiating the + # DynamicMetalShaderLibrary directly, we'll use our shim functions. + # The existing codegen should produce something like: + # const char* mps_lib_0_source = R"MTL(...shader_source...)MTL"; + # instead of: + # at::native::mps::DynamicMetalShaderLibrary mps_lib_0(R"MTL(...shader_source...)MTL"); + + # Generate thread-safe lazy singleton with RAII for each library + for lib_name in shader_libraries: + self.prefix.splice(f""" +AOTIMetalKernelFunctionHandle get_{lib_name}_handle() {{ + static auto kernel_handle = []() {{ + AOTIMetalShaderLibraryHandle lib_handle = nullptr; + AOTIMetalKernelFunctionHandle kern_handle = nullptr; + + aoti_torch_mps_create_shader_library({lib_name}_source, &lib_handle); + aoti_torch_mps_get_kernel_function(lib_handle, "generated_kernel", &kern_handle); + + // RAII wrapper with custom deleter + auto lib_deleter = [](AOTIMetalShaderLibraryHandle h) {{ + if (h) aoti_torch_mps_delete_shader_library(h); + }}; + + using LibDeleter = decltype(lib_deleter); + using LibPtr = std::unique_ptr; + + // Return pair of kernel handle and library smart pointer for cleanup + return std::make_pair(kern_handle, LibPtr(lib_handle, lib_deleter)); + }}(); + return kernel_handle.first; +}} +""") diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpu_device_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpu_device_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..1843688e900e27d0bceb8daae0d49b333209195b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpu_device_op_overrides.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from textwrap import dedent + +from .common import DeviceIdx, DeviceOpOverrides, register_device_op_overrides + + +class CpuDeviceOpOverrides(DeviceOpOverrides): + def import_get_raw_stream_as(self, name: str) -> str: + return dedent( + """ + def get_raw_stream(_): + return 0 + """ + ) + + def cpp_kernel_type(self) -> str: + return "void*" + + def set_device(self, device_idx: DeviceIdx) -> str: + return "pass" + + def synchronize(self) -> str: + return "pass" + + def device_guard(self, device_idx: DeviceIdx) -> str: + return "torch._ops.contextlib.nullcontext()" + + +register_device_op_overrides("cpu", CpuDeviceOpOverrides()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b5113f8ecefa0b768c98c270a1e9ccc196d07b7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/compile_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/compile_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..152c7c665b8203f0d37082f7ab8ecebc63703464 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/compile_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/cuda_env.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/cuda_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c86dad93bc51847b95ab4423e8c812f5d318bb1a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/cuda_env.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/device_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/device_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..632da3a0a29fdf034f373cec23802851c4f64d77 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/device_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/compile_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/compile_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f795fe56f2ff06d539f514ab7cd9498fbde39bc4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/compile_utils.py @@ -0,0 +1,384 @@ +# mypy: allow-untyped-defs +import logging +import os +import re +import shutil + +import torch +from torch._inductor import config +from torch._inductor.codegen.cuda import cuda_env +from torch._inductor.cpp_builder import _set_gpu_runtime_env, _transform_cuda_paths +from torch._inductor.utils import is_linux +from torch.utils._ordered_set import OrderedSet + + +if config.is_fbcode(): + from triton.fb.build import build_paths + + +log = logging.getLogger(__name__) +autotuning_log = torch._logging.getArtifactLogger(__name__, "autotuning") + + +def use_re_build() -> bool: + """ + Use for CUTLASS compilation only right now. + """ + if config.is_fbcode() and not cuda_env.nvcc_exist(_cuda_compiler()): + from triton.fb.re_build_helper import should_build_locally + + return not should_build_locally() + return False + + +def _cutlass_path() -> str | None: + if config.is_fbcode(): + from libfb.py import parutil + + return parutil.get_dir_path("cutlass-4-headers") + else: + from torch._inductor.codegen.cutlass.utils import try_import_cutlass + + return config.cutlass.cutlass_dir if try_import_cutlass() else None + + +def _cutlass_paths() -> list[str]: + return [ + "include", + "tools/library/include", + "tools/library/src", + "tools/util/include", + ] + + +def _clone_cutlass_paths(build_root: str) -> list[str]: + cutlass_root = _cutlass_path() + if cutlass_root is None: + return [] + paths = [] + for path in _cutlass_paths(): + old_path = os.path.join(cutlass_root, path) + new_path = os.path.join(build_root, path) + shutil.copytree(old_path, new_path, dirs_exist_ok=True) + paths.append(new_path) + return paths + + +def _cutlass_include_paths() -> list[str]: + cutlass_root = _cutlass_path() + if cutlass_root is None: + return [] + return [ + # Use realpath to get canonical absolute paths, in order not to mess up cache keys + os.path.realpath(os.path.join(cutlass_root, path)) + for path in _cutlass_paths() + ] + + +def _cuda_compiler() -> str | None: + if cuda_env.nvcc_exist(config.cuda.cuda_cxx): + return config.cuda.cuda_cxx + if config.is_fbcode(): + return os.path.join(build_paths.sdk_home, "bin", "nvcc") + if cuda_env.nvcc_exist(os.getenv("CUDACXX")): + return os.getenv("CUDACXX", "") + if cuda_env.nvcc_exist(os.getenv("CUDA_HOME")): + return os.path.realpath(os.path.join(os.getenv("CUDA_HOME", ""), "bin/nvcc")) + return "nvcc" + + +def _cuda_lib_options() -> list[str]: + """ + Util function for CUTLASS backend to find the correct CUDA libraries. + """ + _set_gpu_runtime_env() # cpp_extension consults the env + from torch.utils import cpp_extension + + lpaths = cpp_extension.library_paths(device_type="cuda") + if use_re_build(): + lpaths += [ + build_paths.sdk_lib, + os.path.join(build_paths.sdk_lib, "stubs"), + ] + extra_ldflags: list[str] = [] + if is_linux(): + _transform_cuda_paths(lpaths) + for path in lpaths: + if "torch/lib" in path: + # don't want to depend on pytorch + continue + extra_ldflags.append(f"-L{path}") + # -rpath ensures the DLL can find its dependencies when loaded, even + # if the library path is non-standard. + # But do not add the stubs folder to rpath as the driver is expected to be found at runtime + if os.path.basename(path) != "stubs": + extra_ldflags.extend(["-Xlinker", f"-rpath={path}"]) + extra_ldflags.append("-lcuda") + extra_ldflags.append("-lcudart") + else: + raise NotImplementedError( + "Unsupported env, failed to find cuda libs! Currently only Linux is supported." + ) + return extra_ldflags + + +def _nvcc_host_compiler_options() -> list[str]: + return [ + "-fPIC", + "-fno-strict-aliasing", + "-fvisibility=hidden", + "-Wconversion", + ] + + +def _cuda_arch_with_compile_suffix(arch: str) -> str: + arch = _normalize_cuda_arch(arch) + if arch == "90": + # Required by cutlass compilation. + return "90a" + if arch == "100": + return "100a" + if arch == "101": + return "101a" + if arch == "103": + return "103a" + if arch == "107": + return "107a" + if arch == "110": + return "110a" + if arch == "120": + return "120a" + if arch == "121": + return "121a" + return arch + + +def _nvcc_arch_as_compile_option() -> str | None: + arch = cuda_env.get_cuda_arch() + if arch is None: + return arch + return _cuda_arch_with_compile_suffix(arch) + + +def _nvcc_arch_as_compile_option_or_raise() -> str: + arch = _nvcc_arch_as_compile_option() + if arch is None: + raise RuntimeError("Unable to determine CUDA architecture") + return arch + + +def _normalize_cuda_arch(arch: str) -> str: + arch = arch.removeprefix("sm_").removeprefix("compute_").replace(".", "") + if not re.fullmatch(r"\d+[a-z]?", arch): + raise ValueError(f"Unrecognized CUDA arch: {arch}") + return arch + + +def _cuda_arch_number(arch: str) -> int: + arch = _normalize_cuda_arch(arch) + if arch[-1].isalpha(): + arch = arch[:-1] + return int(arch) + + +def _cuda_arch_suffix(arch: str) -> str: + arch = _normalize_cuda_arch(arch) + return arch[-1] if arch[-1].isalpha() else "" + + +def _cuda_arch_same_generation(arch: str, other: str) -> bool: + arch = _normalize_cuda_arch(arch) + other = _normalize_cuda_arch(other) + if _cuda_arch_suffix(arch) or _cuda_arch_suffix(other): + return arch == other + return _cuda_arch_number(arch) == _cuda_arch_number(other) + + +def _cuda_arch_is_compatible_with_current(arch: str, current_arch: str) -> bool: + if _cuda_arch_suffix(current_arch): + return _normalize_cuda_arch(arch) == _normalize_cuda_arch(current_arch) + return _cuda_arch_number(arch) >= _cuda_arch_number(current_arch) + + +def _aoti_cuda_target_arch() -> str: + if config.cuda.arch is not None: + return _cuda_arch_with_compile_suffix(str(config.cuda.arch)) + return _nvcc_arch_as_compile_option_or_raise() + + +def _parse_gencode_options(flags: list[str]) -> OrderedSet[tuple[str, str]]: + options: OrderedSet[tuple[str, str]] = OrderedSet() + for flag in flags: + if flag.startswith("-gencode="): + option = flag.removeprefix("-gencode=") + elif flag.startswith("-gencode "): + option = flag.removeprefix("-gencode ") + else: + continue + + try: + _, code = option.split(",code=", 1) + except ValueError: + continue + code = code.removeprefix("[").removesuffix("]") + for entry in code.split(","): + try: + kind, arch = entry.split("_", 1) + except ValueError: + continue + if kind in ("sm", "compute"): + options.add((kind, _normalize_cuda_arch(arch))) + return options + + +def _cuda_multi_arch_gencode_options(current_arch: str | None = None) -> list[str]: + """ + Return nvcc -gencode option payloads for AOTI CUDA fatbins. + + AOTI captures PTX for the architecture Triton compiled on. That PTX can be + used for the current architecture and newer architectures, but not older + ones, so explicit TORCH_CUDA_ARCH_LIST entries below the current target are + intentionally ignored. + """ + if not current_arch: + current_arch = _nvcc_arch_as_compile_option_or_raise() + current_arch = _normalize_cuda_arch(current_arch) + options: OrderedSet[tuple[str, str]] = OrderedSet() + + arch_list = os.environ.get("TORCH_CUDA_ARCH_LIST") + if arch_list and arch_list != "native": + from torch.utils.cpp_extension import _get_cuda_arch_flags + + for kind, arch in _parse_gencode_options(_get_cuda_arch_flags([])): + if kind == "sm" and _cuda_arch_is_compatible_with_current( + arch, current_arch + ): + options.add((kind, arch)) + elif kind == "sm": + log.warning( + "Ignoring TORCH_CUDA_ARCH_LIST entry sm_%s for AOTI CUDA " + "multi-arch packaging because it is not compatible with " + "target arch %s.", + arch, + current_arch, + ) + + if not any( + kind == "sm" and _cuda_arch_same_generation(arch, current_arch) + for kind, arch in options + ): + options.add(("sm", current_arch)) + + # Always keep a PTX image for the compile architecture as the fallback for + # GPUs newer than the generated SASS images. + options.add(("compute", current_arch)) + + def sort_key(option: tuple[str, str]) -> tuple[int, int, str]: + kind, arch = option + return (_cuda_arch_number(arch), 0 if kind == "sm" else 1, arch) + + return [ + f"arch=compute_{arch},code={kind}_{arch}" + for kind, arch in sorted(options, key=sort_key) + ] + + +def _cuda_gencode_options_have_non_current_sass( + gencode_options: list[str], current_arch: str | None = None +) -> bool: + if not current_arch: + current_arch = _nvcc_arch_as_compile_option_or_raise() + current_arch = _normalize_cuda_arch(current_arch) + for kind, arch in _parse_gencode_options( + [f"-gencode={option}" for option in gencode_options] + ): + if kind == "sm" and not _cuda_arch_same_generation(arch, current_arch): + return True + return False + + +def _nvcc_compiler_options() -> list[str]: + arch = _nvcc_arch_as_compile_option_or_raise() + code = [f"sm_{arch}", f"compute_{arch}"] + if config.cuda.enable_cuda_lto: + code += [f"lto_{arch}"] + options = [ + "-t=0", + "-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1", + "-DCUTLASS_ENABLE_SM90_EXTENDED_MMA_SHAPES=1", + "-DCUTE_SM90_EXTENDED_MMA_SHAPES_ENABLED", + "-w", + f"-gencode=arch=compute_{arch},code=[{','.join(code)}]", + config.cutlass.compile_opt_level, + "-std=c++20", + "--expt-relaxed-constexpr", + "-DNDEBUG", + ] + if config.is_fbcode(): + options.extend(["-ccbin", os.path.dirname(build_paths.gcc)]) + if config.cutlass.enable_debug_info: + options.extend(["-lineinfo", "-g", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"]) + if config.cuda.enable_ptxas_info: + options.extend( + [ + "--keep", # Keep the intermediate files for debugging (including ptx, sass, cubin etc.) + "--ptxas-options=--warn-on-local-memory-usage", # warn us if local memory is used in CUDA Kernels + "--ptxas-options=--warn-on-spills", # warn us if register spilling happens in CUDA Kernels + "--resource-usage", # Report on CUDA resource usage (shared mem, registers etc.) + "--source-in-ptx", + ] + ) # Annotate the ptx file with source information + if config.cutlass.use_fast_math: + options.extend( + [ + "--use_fast_math", + "-DCUTLASS_USE_TANH_FOR_SIGMOID=1", + ] + ) + return options + + +def cuda_compile_command( + src_files: list[str], + dst_file: str, + dst_file_ext: str, + extra_args: list[str] | None = None, +) -> str: + if extra_args is None: + extra_args = [] + if use_re_build(): + build_path = os.path.dirname(dst_file) + include_paths = _clone_cutlass_paths(build_path) + src_files = [os.path.basename(src_file) for src_file in src_files] + dst_file = os.path.basename(dst_file) + else: + include_paths = _cutlass_include_paths() + cuda_lib_options = _cuda_lib_options() + nvcc_host_compiler_options = _nvcc_host_compiler_options() + nvcc_compiler_options = _nvcc_compiler_options() + options = ( + nvcc_compiler_options + + extra_args + + [ + f"-Xcompiler {opt}" if "=" in opt else f"-Xcompiler={opt}" + for opt in nvcc_host_compiler_options + ] + + ["-I" + path for path in include_paths] + + cuda_lib_options + ) + src_file = " ".join(src_files) + res = "" + if dst_file_ext == "o": + res = f"{_cuda_compiler()} {' '.join(options)} -c -o {dst_file} {src_file}" + elif dst_file_ext == "so": + options.append("-shared") + res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}" + elif dst_file_ext == "exe": + res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}" + else: + raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!") + if log.isEnabledFor(logging.DEBUG): + log.debug("CUDA command: %s", res) + else: + autotuning_log.debug("CUDA command: %s", res) + return res diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/cuda_env.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/cuda_env.py new file mode 100644 index 0000000000000000000000000000000000000000..e12bd94d2a677f1e4c03fba78e7fa3b288d046b7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/cuda_env.py @@ -0,0 +1,54 @@ +import functools +import logging +import shutil + +import torch +from torch._inductor.utils import clear_on_fresh_cache + +from ... import config + + +log = logging.getLogger(__name__) + + +@clear_on_fresh_cache +@functools.lru_cache(1) +def get_cuda_arch() -> str | None: + try: + cuda_arch = config.cuda.arch + if cuda_arch is None: + # Get Compute Capability of the first Visible device + major, minor = torch.cuda.get_device_capability(0) + return str(major * 10 + minor) + return str(cuda_arch) + except Exception: + log.exception("Error getting cuda arch") + return None + + +@clear_on_fresh_cache +@functools.lru_cache(1) +def is_datacenter_blackwell_arch() -> bool: + arch = get_cuda_arch() + if arch is None: + return False + arch_number = int(arch) + return arch_number >= 100 and arch_number < 110 + + +@clear_on_fresh_cache +@functools.lru_cache(1) +def get_cuda_version() -> str | None: + try: + cuda_version = config.cuda.version + if cuda_version is None: + cuda_version = torch.version.cuda + return cuda_version + except Exception: + log.exception("Error getting cuda version") + return None + + +@functools.cache +def nvcc_exist(nvcc_path: str | None = "nvcc") -> bool: + return nvcc_path is not None and shutil.which(nvcc_path) is not None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/device_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/device_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..ab67a1ee63e3a441a9aeb2337e9759da905954e1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/device_op_overrides.py @@ -0,0 +1,387 @@ +from __future__ import annotations + +import torch + +from ...runtime.hints import get_warp_size +from ..common import ( + DeviceIdx, + DeviceOpOverrides, + register_device_op_overrides, + TritonScratchWorkspace, +) + + +class CUDADeviceOpOverrides(DeviceOpOverrides): + """ + CUDA-specific codegen functions, see DeviceOpOverrides for details + """ + + def import_get_raw_stream_as(self, name: str) -> str: + return f"from torch._C import _cuda_getCurrentRawStream as {name}" + + def set_device(self, device_idx: DeviceIdx) -> str: + return f"torch.cuda.set_device({device_idx})" + + def synchronize(self) -> str: + return "torch.cuda.synchronize()" + + def device_guard(self, device_idx: DeviceIdx) -> str: + return f"torch.cuda._DeviceGuard({device_idx})" + + def current_device_idx_expr(self) -> str: + return "torch.cuda.current_device()" + + def current_stream(self) -> str: + return "torch.cuda.current_stream()" + + def cpp_device_guard(self) -> str: + return "at::cuda::CUDAGuard" + + def cpp_aoti_device_guard(self) -> str: + return "AOTICudaGuard" + + def cpp_stream_guard(self) -> str: + return "at::cuda::CUDAStreamGuard" + + def cpp_aoti_stream_guard(self) -> str: + return "AOTICudaStreamGuard" + + def cpp_getStreamFromExternal(self) -> str: + return "at::cuda::getStreamFromExternal" + + def kernel_header(self) -> str: + source_codes = """ + #include + #include + #include + """ + return source_codes + + def kernel_driver(self) -> str: + """Return C++ host-side helpers (loadKernel, launchKernel, CUDA_DRIVER_CHECK) + embedded in AOTI-generated wrapper code.""" + # NVIDIA devices have a warp size of 32, while AMD devices can have a + # warp size of 32 or 64 depending on the architecture. + source_codes = """ + #define CUDA_DRIVER_CHECK(EXPR) \\ + do { \\ + CUresult code = EXPR; \\ + const char *msg; \\ + CUresult code_get_error = cuGetErrorString(code, &msg); \\ + if (code_get_error != CUDA_SUCCESS) { \\ + throw std::runtime_error( \\ + std::string("CUDA driver error: ") + \\ + std::string("invalid error code!")); \\ + } \\ + if (code != CUDA_SUCCESS) { \\ + throw std::runtime_error( \\ + std::string("CUDA driver error: ") + \\ + std::string(msg)); \\ + } \\ + } while (0); + + static inline CUfunction loadKernel( + std::string filePath, + const std::string &funcName, + uint32_t sharedMemBytes, + const std::optional &cubinDir = std::nullopt, + std::vector* loaded_modules = nullptr) { + if (cubinDir) { + std::filesystem::path p1{*cubinDir}; + std::filesystem::path p2{filePath}; + filePath = (p1 / p2.filename()).string(); + } + + CUmodule mod; + CUfunction func; + CUDA_DRIVER_CHECK(cuModuleLoad(&mod, filePath.c_str())); + if (loaded_modules) { + loaded_modules->push_back(mod); + } + CUDA_DRIVER_CHECK(cuModuleGetFunction(&func, mod, funcName.c_str())); + if (sharedMemBytes > 0) { + CUDA_DRIVER_CHECK(cuFuncSetAttribute( + func, + CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, + sharedMemBytes + )) + } + return func; + } + + static inline CUfunction loadKernel( + const void* start, + const std::string &funcName, + uint32_t sharedMemBytes, + std::vector* loaded_modules = nullptr) { + CUmodule mod; + CUfunction func; + CUDA_DRIVER_CHECK(cuModuleLoadData(&mod, start)); + if (loaded_modules) { + loaded_modules->push_back(mod); + } + CUDA_DRIVER_CHECK(cuModuleGetFunction(&func, mod, funcName.c_str())); + if (sharedMemBytes > 0) { + CUDA_DRIVER_CHECK(cuFuncSetAttribute( + func, + CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, + sharedMemBytes + )) + } + return func; + } + + static inline void launchKernel( + CUfunction func, + uint32_t gridX, + uint32_t gridY, + uint32_t gridZ, + uint32_t numWarps, + uint32_t sharedMemBytes, + void* args[], + cudaStream_t stream) { + CUDA_DRIVER_CHECK(cuLaunchKernel( + func, gridX, gridY, gridZ, __WARP_SIZE__*numWarps, 1, 1, sharedMemBytes, stream, args, nullptr + )); + } + """ + if torch.version.hip is not None and torch.cuda.is_available(): + device = torch.device("cuda", torch.cuda.current_device()) + warp_size = get_warp_size(device) + else: + warp_size = 32 + return source_codes.replace("__WARP_SIZE__", str(warp_size)) + + def tma_descriptor_helpers(self) -> str: + """ + CUDA helper functions for initializing TMA Descriptors on host side + """ + if torch.version.hip is not None: + raise RuntimeError("Host-side TMA descriptors not supported on HIP.") + + # helper functions for initializing 1D and 2D TMA descriptors in C++. borrowed from the Triton code here: + # Old APIs (fill(1|2)DTMADescriptor): + # https://github.com/triton-lang/triton/blob/6af4f88591c85de079d8a36a4d7dba67918e2b39/third_party/nvidia/backend/driver.c#L283 + # New APIs (fillTMADescriptor): + # https://github.com/triton-lang/triton/blob/main/third_party/nvidia/backend/driver.c#L283 + return """ + #if !defined(USE_ROCM) && defined(CUDA_VERSION) && CUDA_VERSION >= 12000 + [[maybe_unused]] static void init1DTMADescriptor( + CUtensorMap* m, + void* globalAddress, + uint64_t dim, + uint32_t blockDim, + uint32_t elementSize) { + uint64_t dims[1] = {dim}; + uint64_t globalStrides[1] = {dim * elementSize}; + uint32_t tensorDims[1] = {blockDim}; + uint32_t elementStrides[1] = {1}; + + CUtensorMapDataType type; + switch (elementSize) { + case 1: + type = CU_TENSOR_MAP_DATA_TYPE_UINT8; + break; + case 2: + type = CU_TENSOR_MAP_DATA_TYPE_UINT16; + break; + case 4: + type = CU_TENSOR_MAP_DATA_TYPE_UINT32; + break; + default: + throw std::runtime_error("elementSize must be 1, 2, or 4"); + } + + if (elementSize * blockDim < 32) { + throw std::runtime_error("block size too small"); + } + + int rank = 1; + + CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled( + m, type, rank, globalAddress, dims, + globalStrides, tensorDims, elementStrides, CU_TENSOR_MAP_INTERLEAVE_NONE, + CU_TENSOR_MAP_SWIZZLE_NONE, CU_TENSOR_MAP_L2_PROMOTION_NONE, + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE)); + } + + [[maybe_unused]] static void init2DTMADescriptor( + CUtensorMap* m, + void* globalAddress, + uint64_t dim1, + uint64_t dim0, + uint32_t blockDim1, + uint32_t blockDim0, + uint32_t elementSize) { + uint64_t dims[2] = {dim0, dim1}; + uint32_t tensorDims[2] = {blockDim0, blockDim1}; + uint64_t globalStrides[2] = {dims[0] * elementSize, + dims[0] * dims[1] * elementSize}; + uint32_t elementStrides[2] = {1, 1}; + + CUtensorMapDataType type; + switch (elementSize) { + case 1: + type = CU_TENSOR_MAP_DATA_TYPE_UINT8; + break; + case 2: + type = CU_TENSOR_MAP_DATA_TYPE_UINT16; + break; + case 4: + type = CU_TENSOR_MAP_DATA_TYPE_UINT32; + break; + default: + throw std::runtime_error("elementSize must be 1, 2, or 4"); + } + + int rank = 2; + + CUtensorMapSwizzle swizzle = CU_TENSOR_MAP_SWIZZLE_128B; + uint32_t contigDimSizeInByte = elementSize * tensorDims[0]; + if (contigDimSizeInByte >= 128) { + swizzle = CU_TENSOR_MAP_SWIZZLE_128B; + } else if (contigDimSizeInByte >= 64) { + swizzle = CU_TENSOR_MAP_SWIZZLE_64B; + } else if (contigDimSizeInByte >= 32) { + swizzle = CU_TENSOR_MAP_SWIZZLE_32B; + } else { + throw std::runtime_error("block size too small"); + } + + if (contigDimSizeInByte > 128) { + tensorDims[0] = 128 / elementSize; + } + + CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled( + m, type, rank, globalAddress, dims, + globalStrides, tensorDims, elementStrides, CU_TENSOR_MAP_INTERLEAVE_NONE, + swizzle, CU_TENSOR_MAP_L2_PROMOTION_L2_128B, + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE)); + } + + [[maybe_unused]] static void initTMADescriptor( + CUtensorMap* m, + void* globalAddress, + int elemSize, + int rank, + uint32_t* blockSize, + uint64_t* shape, + uint64_t* stride + ) { + uint32_t elementStrides[5] = {1, 1, 1, 1, 1}; + uint32_t blockSizeInt[5]; + uint64_t shapeInt[5]; + uint64_t stridesLL[5]; + + // Reorder blockSize (reverse the order) + for (int i = 0; i < rank; ++i) { + blockSizeInt[rank - i - 1] = blockSize[i]; + } + + // Reorder shape (reverse the order) + for (int i = 0; i < rank; ++i) { + shapeInt[rank - i - 1] = shape[i]; + } + + // Reorder and calculate strides + for (int i = 0; i + 1 < rank; ++i) { + stridesLL[rank - i - 2] = elemSize * stride[i]; + } + stridesLL[rank - 1] = + shapeInt[rank - 1] * (rank == 1 ? elemSize : stridesLL[rank - 2]); + + CUtensorMapDataType type; + // In Triton this is computed ahead of time; but for simplicity + // in the PyTorch version we copied this code from the old + // TMA API handling (i.e. init2DTMADescriptor) + switch (elemSize) { + case 1: + type = CU_TENSOR_MAP_DATA_TYPE_UINT8; + break; + case 2: + type = CU_TENSOR_MAP_DATA_TYPE_UINT16; + break; + case 4: + type = CU_TENSOR_MAP_DATA_TYPE_UINT32; + break; + default: + throw std::runtime_error("elemSize must be 1, 2, or 4"); + } + + // Calculate the size of the most contiguous dimension in bytes + CUtensorMapSwizzle swizzle = CU_TENSOR_MAP_SWIZZLE_128B; + uint32_t contigDimSizeInByte = elemSize * blockSizeInt[0]; + if (rank == 1) { + // rank 1 should not be swizzled + swizzle = CU_TENSOR_MAP_SWIZZLE_NONE; + } else if (contigDimSizeInByte >= 128) { + swizzle = CU_TENSOR_MAP_SWIZZLE_128B; + } else if (contigDimSizeInByte >= 64) { + swizzle = CU_TENSOR_MAP_SWIZZLE_64B; + } else if (contigDimSizeInByte >= 32) { + swizzle = CU_TENSOR_MAP_SWIZZLE_32B; + } else { + throw std::runtime_error("block size too small"); + } + + CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled( + m, type, rank, globalAddress, + shapeInt, stridesLL, blockSizeInt, elementStrides, + CU_TENSOR_MAP_INTERLEAVE_NONE, (CUtensorMapSwizzle)swizzle, + CU_TENSOR_MAP_L2_PROMOTION_L2_128B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE)); + } + + struct StableTMADescriptor { + CUtensorMap m; + uint32_t block_shape[5]; + uint64_t global_shape[5]; + uint64_t strides[5]; + }; + #endif + """ + + def cpp_stream_type(self) -> str: + return "cudaStream_t" + + def aoti_get_stream(self) -> str: + return "aoti_torch_get_current_cuda_stream" + + def cpp_kernel_type(self) -> str: + return "CUfunction" + + def cpp_device_ptr(self) -> str: + return "CUdeviceptr" + + def cpp_scratch( + self, idx: int, workspace: TritonScratchWorkspace, prefix: str | None = None + ) -> tuple[list[str], str] | None: + prefix = f"{prefix}_" if prefix else "" + var_name = f"{prefix}scratch_{idx}" + if workspace.size > 0: + size_expr = ( + f"static_cast({workspace.size}) * grid_0 * grid_1 * grid_2" + ) + size_array = f"int64_t {var_name}_size[] = {{{size_expr}}};" + stride_array = f"int64_t {var_name}_stride[] = {{1}};" + device_type = "cached_torch_device_type_cuda" + device_idx = "device_idx_" + + return ( + [ + f"{size_array}", + f"{stride_array}", + f"AtenTensorHandle {var_name}_handle;", + ( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided(1, {var_name}_size, {var_name}_stride, " + f"{workspace.generate_dtype_str()}, {device_type}, {device_idx}, &{var_name}_handle));" + ), + f"RAIIAtenTensorHandle {var_name}_tensor({var_name}_handle);", + f"CUdeviceptr {var_name} = reinterpret_cast({var_name}_tensor.data_ptr());", + ], + var_name, + ) + else: + return [f"CUdeviceptr {var_name} = 0;"], var_name + + +register_device_op_overrides("cuda", CUDADeviceOpOverrides()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda_combined_scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda_combined_scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..e2636b543295adc951850dfcf4c7048f9a6d6b7d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda_combined_scheduling.py @@ -0,0 +1,301 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import logging +from typing import Any, TYPE_CHECKING + +from ..ir import MultiTemplateBuffer +from ..scheduler import ( + BaseSchedulerNode, + BaseScheduling, + FusedSchedulerNode, + Scheduler, + SchedulerNode, +) +from .cutedsl.cutedsl_scheduling import CuteDSLScheduling +from .cutlass.scheduling import CUTLASSScheduling +from .nv_universal_gemm.nv_universal_gemm_scheduling import NVUniversalGemmScheduling +from .rocm.rocm_cpp_scheduling import ROCmCPPScheduling +from .triton import TritonScheduling + + +log = logging.getLogger(__name__) + + +if TYPE_CHECKING: + from collections.abc import Sequence + from typing import TypeAlias + + from sympy import Expr + + import torch + from torch.utils._ordered_set import OrderedSet + + from .common import BackendFeature + + _IntLike: TypeAlias = int | Expr + + +class CUDACombinedScheduling(BaseScheduling): + """ + Scheduler for CUDA Kernels, which delegates calls as appropriate + to the CUDA-C++ and Triton Schedulers, which both work for CUDA devices + and use a unified-wrapper for codegen. + + If Scheduling code needs to be specialized for the case of mixed Triton / CUDA C++ code, + this would also be the place to do it. + """ + + def __init__(self, scheduler: Scheduler | None) -> None: + super().__init__(scheduler) + self._triton_scheduling = TritonScheduling(scheduler) + self._cutlass_scheduling = CUTLASSScheduling(scheduler) + self._rocm_cpp_scheduling = ROCmCPPScheduling(scheduler) + self._cutedsl_scheduling = CuteDSLScheduling(scheduler) + self._nv_universal_gemm_scheduling = NVUniversalGemmScheduling(scheduler) + + def get_backend_features(self, device: torch.device) -> OrderedSet[BackendFeature]: + return self._triton_scheduling.get_backend_features(device) + + def choose_node_backend(self, node: BaseSchedulerNode) -> BaseScheduling: + if self._cutlass_scheduling.is_cutlass_template(node): + return self._cutlass_scheduling + if self._rocm_cpp_scheduling.is_rocm_cpp_template(node): + return self._rocm_cpp_scheduling + if self._cutedsl_scheduling.is_cutedsl_template(node): + return self._cutedsl_scheduling + if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template(node): + return self._nv_universal_gemm_scheduling + if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_fused_template(node): + return self._nv_universal_gemm_scheduling + return self._triton_scheduling + + def can_fuse_vertical( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if self._cutlass_scheduling.can_fuse_vertical(node1, node2): + return True + elif self._cutlass_scheduling.is_cutlass_template( + node1 + ) or self._cutlass_scheduling.is_cutlass_template(node2): + return False + # CuteDSL doesn't support vertical fusion currently + elif self._cutedsl_scheduling.is_cutedsl_template( + node1 + ) or self._cutedsl_scheduling.is_cutedsl_template(node2): + return False + # Only intercept when node1 is the NVGEMM template (epilogue direction). + # Prologue direction (node1=pointwise, node2=template) must fall through to + # Triton, or NVGEMM-winning MTBs silently lose Triton prologue fusion. + # For MTBs, if NVGEMM can't fuse, fall through to Triton scheduling so + # Triton choices in the same MTB can still attempt epilogue fusion. + elif self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template(node1): + if self._nv_universal_gemm_scheduling.can_fuse_vertical(node1, node2): + return True + if isinstance(node1, SchedulerNode) and isinstance( + node1.node, MultiTemplateBuffer + ): + return self._triton_scheduling.can_fuse_vertical(node1, node2) + return False + elif self._nv_universal_gemm_scheduling.is_nv_universal_gemm_fused_template( + node1 + ): + if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_fused_template( + node2 + ): + return False + return self._nv_universal_gemm_scheduling.can_fuse_vertical(node1, node2) + return self._triton_scheduling.can_fuse_vertical(node1, node2) + + def can_fuse_horizontal( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + for node in (node1, node2): + if self._cutlass_scheduling.is_cutlass_template(node): + return self._cutlass_scheduling.can_fuse_horizontal( + node1, node2 + ) # always False at the moment + if self._cutedsl_scheduling.is_cutedsl_template(node): + return self._cutedsl_scheduling.can_fuse_horizontal( + node1, node2 + ) # always False at the moment + if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template( + node + ) or self._nv_universal_gemm_scheduling.is_nv_universal_gemm_fused_template( + node + ): + return self._nv_universal_gemm_scheduling.can_fuse_horizontal( + node1, node2 + ) # always False at the moment + return self._triton_scheduling.can_fuse_horizontal(node1, node2) + + def can_fuse_reduction_epilogue( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template( + node1 + ) or self._nv_universal_gemm_scheduling.is_nv_universal_gemm_fused_template( + node1 + ): + return self._nv_universal_gemm_scheduling.can_fuse_reduction_epilogue( + node1, node2 + ) + return False + + def group_fn( + self, sizes: Sequence[Sequence[_IntLike]] + ) -> tuple[tuple[_IntLike, ...], ...]: + return self._triton_scheduling.group_fn(sizes) + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + ) -> str | None: + if self._cutlass_scheduling.is_cutlass_template(template_node): + if prologue_nodes: + raise AssertionError("cutlass template does not support prologue nodes") + return self._cutlass_scheduling.codegen_template( + template_node, epilogue_nodes, prologue_nodes + ) + elif self._rocm_cpp_scheduling.is_rocm_cpp_template(template_node): + if epilogue_nodes: + raise AssertionError( + "rocm cpp template does not support epilogue nodes" + ) + if prologue_nodes: + raise AssertionError( + "rocm cpp template does not support prologue nodes" + ) + return self._rocm_cpp_scheduling.codegen_template( + template_node, epilogue_nodes, prologue_nodes + ) + elif self._cutedsl_scheduling.is_cutedsl_template(template_node): + # TODO remove this when we add epilogue support + if epilogue_nodes: + raise AssertionError("cutedsl template does not support epilogue nodes") + if prologue_nodes: + raise AssertionError("cutedsl template does not support prologue nodes") + return self._cutedsl_scheduling.codegen_template( + template_node, epilogue_nodes, prologue_nodes + ) + elif self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template( + template_node + ): + if prologue_nodes: + raise AssertionError( + "NVIDIA Universal GEMM doesn't support prologue fusion yet" + ) + return self._nv_universal_gemm_scheduling.codegen_template( + template_node, epilogue_nodes, prologue_nodes + ) + else: + return self._triton_scheduling.codegen_template( + template_node, epilogue_nodes, prologue_nodes + ) + + def codegen_mix_order_reduction(self, node): + return self._triton_scheduling.codegen_mix_order_reduction(node) + + def codegen_nested_reduction(self, node): + return self._triton_scheduling.codegen_nested_reduction(node) + + def codegen_node(self, node: FusedSchedulerNode | SchedulerNode) -> None: + return self._triton_scheduling.codegen_node(node) + + def codegen_sync(self) -> None: + return self._triton_scheduling.codegen_sync() + + def flush(self) -> None: + return self._triton_scheduling.flush() + + def codegen_combo_kernel(self, *args: Any, **kwargs: Any) -> None: + return self._triton_scheduling.codegen_combo_kernel(*args, **kwargs) + + def benchmark_fused_nodes( + self, nodes: Sequence[BaseSchedulerNode] + ) -> tuple[float, str]: + return self._triton_scheduling.benchmark_fused_nodes(nodes) + + def benchmark_codegened_module(self, module): + if getattr(module, "is_nvgemm", False): + return self._benchmark_nvgemm_module(module) + return self._triton_scheduling.benchmark_codegened_module(module) + + def _benchmark_nvgemm_module(self, module) -> tuple[float, str]: + from torch._dynamo.utils import preserve_rng_state + from torch._inductor.runtime.benchmarking import benchmarker + from torch._inductor.utils import get_interface_for_device + from torch._inductor.virtualized import V + + device_interface = get_interface_for_device(V.graph.device_type) + + with ( + preserve_rng_state(), + device_interface.device(V.graph.get_current_device_or_throw()), + ): + args = module.get_args() + call = module.call + + try: + call(args) + except Exception as e: + log.debug( + "Exception (%s) in compiling NVGEMM fused kernel", + e, + ) + return float("inf"), module.__file__ or "" + + device = V.graph.get_current_device_or_throw() + try: + ms = benchmarker.benchmark( + lambda: call(args), + device=device, + ) + except Exception as e: + log.debug( + "Exception (%s) while benchmarking NVGEMM fused kernel", + e, + ) + return float("inf"), module.__file__ or "" + + return ms, module.__file__ or "" + + def _is_nvgemm_node(self, node) -> bool: + """Check if a template node is currently configured for NVGEMM codegen.""" + from torch._inductor.ir import MultiTemplateBuffer, NVUniversalGemmBuffer + + template_node = node.get_template_node() + if isinstance(template_node, NVUniversalGemmBuffer): + return True + if isinstance(template_node, MultiTemplateBuffer): + return template_node._render_kind == "nvgemm" + return False + + def generate_kernel_code_from_nodes( + self, + nodes: Sequence[Any], + benchmark_kernel: bool = False, + hint_override: int | None = None, + ) -> str: + for node in nodes: + if not (hasattr(node, "is_template") and node.is_template()): + continue + if self._is_nvgemm_node(node): + return ( + self._nv_universal_gemm_scheduling.generate_kernel_code_from_nodes( + nodes, benchmark_kernel, hint_override=hint_override + ) + ) + break + return self._triton_scheduling.generate_kernel_code_from_nodes( + nodes, benchmark_kernel, hint_override=hint_override + ) + + def benchmark_combo_kernel( + self, node_list: Sequence[BaseSchedulerNode], node_benchmark_results + ) -> tuple[float, float, list[str | None]]: + return self._triton_scheduling.benchmark_combo_kernel( + node_list, node_benchmark_results + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/custom_extern_kernel_codegen.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/custom_extern_kernel_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..fd2df36d5aa3a6c7ad8f581250fe70ca43b1513e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/custom_extern_kernel_codegen.py @@ -0,0 +1,101 @@ +""" +Custom extern kernel codegen registry. + +This module provides a registry that maps operators to their custom codegen +implementations. This allows us to keep all custom implementations in one place +and easily extend support for both Python and C++ wrappers. + +To add a new custom implementation: +1. Create a codegen function with signature: + def my_codegen(node: ir.FallbackKernel, writeline: Callable[[str], None]) -> None: +2. Register it in CUSTOM_EXTERN_KERNEL_CODEGEN with the operator name as key + +Example: + CUSTOM_EXTERN_KERNEL_CODEGEN = { + "torch.ops.higher_order.print": CustomCodegen( + python=generate_print_python, + cpp=generate_print_cpp, # Optional + ), + } + +Usage: + codegen = CUSTOM_EXTERN_KERNEL_CODEGEN[op] + codegen.python(node, writeline) # Direct attribute access +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, TYPE_CHECKING + + +if TYPE_CHECKING: + from collections.abc import Callable + + from .. import ir + + # Type alias for codegen function signature (only used for type checking) + CodegenFunc = Callable[[ir.FallbackKernel, Callable[[str], None]], None] + + +@dataclass +class CustomCodegen: + """ + Container for custom codegen implementations. + + Attributes: + python: Codegen function for Python wrapper (optional) + cpp: Codegen function for C++ wrapper (optional) + """ + + python: Any = None + cpp: Any = None + + +def generate_print_python( + node: ir.FallbackKernel, + writeline: Callable[[str], None], +) -> None: + """ + Generate a builtin print call for the print HOP fallback (Python wrapper). + + This function generates Python code that calls the builtin print function + with format string interpolation. + + Args: + node: The FallbackKernel IR node representing the print HOP call. + writeline: A function that writes a line of code to the output buffer. + + Example generated code: + print('x = {}, y = {}'.format(buf0, buf1)) + print('x = {x}, y = {y}'.format(x=buf0, y=buf1)) + print('x = {}, y = {y}'.format(buf0, y=buf1)) + """ + codegen_args: list[str] = node.codegen_args() + codegen_kwargs: list[str] = node.codegen_kwargs() + + # First arg is the format string + if not codegen_args: + raise ValueError( + "generate_print_python requires a format string as the first positional argument" + ) + format_str: str = codegen_args[0] + + # Remaining args are positional arguments for .format() + positional_args = codegen_args[1:] + + args_str = ", ".join(positional_args + codegen_kwargs) + writeline( + f"print({format_str}.format({args_str}))" + if args_str + else f"print({format_str})" + ) + + +# Registry mapping operator names to their custom codegen implementations +# Usage: CUSTOM_EXTERN_KERNEL_CODEGEN[op_name].python(node, writeline) +CUSTOM_EXTERN_KERNEL_CODEGEN: dict[str, CustomCodegen] = { + "torch.ops.higher_order.print": CustomCodegen( + python=generate_print_python, + ), +} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f12fa963fd60c00deb9f36f9515e3e794c9529ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__init__.py @@ -0,0 +1,8 @@ +# mypy: allow-untyped-defs +from .cutedsl_template import CuteDSLTemplate, CuteDSLTemplateCaller + + +__all__ = [ + "CuteDSLTemplate", + "CuteDSLTemplateCaller", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d68f26793efed7647c11a2c22b5a647fa3d487c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_cutedsl_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_cutedsl_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..065f878af047ebab03b7ba9f738a24d27a6fe4a3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_cutedsl_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_inline_asm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_inline_asm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..227130d63c6a65e669ec10b39b634a369939d0b2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_inline_asm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/aux_scalars.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/aux_scalars.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18491a80c648c7041d6a459c4ff63104be220d33 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/aux_scalars.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac7e3fb5879c4c133fb19559b297a8e87c162376 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cebc2e296e889af955ad759aa26ab70d732fa157 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6488b6385117b0402fd8eca31b362ec91bdec720 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15ef936b4e7913f2e9ea462e8da890627c2104f5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/lane_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/lane_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cc969ae600f6583b8ccb756c763d3ee81729306 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/lane_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_cutedsl_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_cutedsl_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..de27f9b09a10866ae546c89dd9945cccdb30690c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_cutedsl_utils.py @@ -0,0 +1,45 @@ +# mypy: disable-error-code=import-not-found +# pyrefly: ignore [import-error, missing-import] +import cutlass +import cutlass.cute as cute + + +@cute.jit # type: ignore[misc] +def ssa_to_indexable(ssa_value: cute.TensorSSA, dtype: str) -> cute.Numeric: + """ + Convert SSA form to indexable non-SSA form. + + Workaround for lack of gather support: SSA values cannot be used directly + as indices in tensor loads. This converts SSA to a register fragment, then + extracts a scalar for indexing. + """ + frag = ssa_to_fragment(ssa_value, dtype) + return frag[0] + + +@cute.jit # type: ignore[misc] +def ssa_to_fragment(ssa_value: cute.TensorSSA, dtype: str) -> cute.Tensor: + """Materialize an SSA vector into a register fragment. + + Casts to the fragment dtype when the SSA dtype differs (e.g. an int64 index + expression materialized into an int32 index fragment), since fragment + stores require matching element types. + """ + if cutlass.const_expr(ssa_value.dtype != dtype): + ssa_value = ssa_value.to(dtype) + frag = cute.make_rmem_tensor(ssa_value.shape, dtype) + frag.store(ssa_value) + return frag + + +@cute.jit # type: ignore[misc] +def result_to_ssa(value: cute.Numeric, dtype: str) -> cute.TensorSSA: + """ + Convert non-SSA result back to SSA form. + + After performing operations with non-SSA values (like indexed loads), + convert the result back to SSA form for further computation. + """ + frag = cute.make_rmem_tensor(1, dtype) + frag[0] = value + return frag.load() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_inline_asm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_inline_asm.py new file mode 100644 index 0000000000000000000000000000000000000000..364df3b7a85af988ebc7a9a207f27832202249a2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_inline_asm.py @@ -0,0 +1,251 @@ +"""Lower elementwise inline PTX over CuteDSL fragments. + +Each assembly invocation consumes `pack` adjacent fragment elements. LLVM +constraints select the physical register type for every operand, so inputs are +bitcast into those registers rather than numerically converted. Multiple outputs +are returned as an LLVM struct and extracted before rebuilding the fragment. +Partial packs are zero-padded, and outputs for padded elements are discarded. + +Integer register results are narrowed to the requested element width. E8M0 codes +1 through 254 map directly to the matching Float32 exponent bits; codes 0 and 255 +map explicitly to `2^-127` and NaN. This lets fused arithmetic use exact Float32 +values while preserving E8M0 as the stored result type. +""" + +import functools +import hashlib +import math +from pathlib import Path + +import cutlass +import cutlass.cute as cute +from cutlass._mlir import ir +from cutlass._mlir.dialects import arith, llvm, vector +from cutlass.cute.tensor import _infer_broadcast_shape +from cutlass.cutlass_dsl import dsl_user_op, T + + +@functools.cache +def inline_asm_cache_key() -> str: + """Include this module's source in generated kernel cache keys.""" + return hashlib.sha256(Path(__file__).read_bytes()).hexdigest() + + +# PTX register classes, as accepted by the NVPTX inline-asm backend. +CONSTRAINT_TYPES = { + "h": T.i16, + "r": T.i32, + "l": T.i64, + "f": T.f32, + "d": T.f64, +} + + +def split_constraints(constraints: str) -> tuple[list[str], list[str]]: + """Split an LLVM constraint list into output and input register classes.""" + outputs, inputs = [], [] + for entry in constraints.split(","): + entry = entry.strip() + target = outputs if entry.startswith("=") else inputs + letter = entry.lstrip("=&") + if letter not in CONSTRAINT_TYPES: + raise NotImplementedError( + f"CuteDSL inline asm supports constraints {sorted(CONSTRAINT_TYPES)}, " + f"got {entry!r}" + ) + target.append(letter) + return outputs, inputs + + +def bitcast_to(value: ir.Value, target: ir.Type) -> ir.Value: + """Reinterpret a value's bits as an equally wide type.""" + if value.type == target: + return value + return arith.bitcast(target, value) + + +def narrow_integer(value: ir.Value, width: int) -> ir.Value: + """Truncate an integer register to `width` bits.""" + if not ir.IntegerType.isinstance(value.type): + raise TypeError(f"expected an integer inline-asm result, got {value.type}") + if ir.IntegerType(value.type).width > width: + return arith.trunci(ir.IntegerType.get_signless(width), value) + return value + + +def decode_e8m0(value: ir.Value) -> ir.Value: + """Decode one biased E8M0 bit pattern to its exact Float32 value.""" + code = arith.extui(T.i32(), narrow_integer(value, 8)) + bits = arith.shli(code, arith.constant(T.i32(), 23)) + is_zero = arith.cmpi(arith.CmpIPredicate.eq, code, arith.constant(T.i32(), 0)) + bits = arith.select(is_zero, arith.constant(T.i32(), 0x00400000), bits) + is_nan = arith.cmpi(arith.CmpIPredicate.eq, code, arith.constant(T.i32(), 255)) + bits = arith.select(is_nan, arith.constant(T.i32(), 0x7FC00000), bits) + return arith.bitcast(T.f32(), bits) + + +def convert_output(value: ir.Value, result_type) -> ir.Value: + """Convert a register result to the requested logical element type.""" + if result_type == cutlass.Float8E8M0FNU: + return decode_e8m0(value) + target = result_type.mlir_type + if value.type == target: + return value + if ir.IntegerType.isinstance(value.type): + value = narrow_integer(value, result_type.width) + return bitcast_to(value, target) + + +def fragment_element(source, index: int) -> ir.Value: + """Extract element `index` from a TensorSSA, or unwrap a scalar value.""" + if isinstance(source, cute.TensorSSA): + return vector.extract(source.ir_value(), [], [index]) + if isinstance(source, ir.Value): + return source + if isinstance(source, (int, float)): + return cutlass.Float32(source).ir_value() + return source.ir_value() + + +def zero_for_constraint(letter: str) -> ir.Value: + """Create a zero in the register type named by an inline-asm constraint.""" + target = CONSTRAINT_TYPES[letter]() + return arith.constant(target, 0.0 if letter in ("f", "d") else 0) + + +def packed_operands( + sources, + input_letters: list[str], + scalar_sources: tuple[bool, ...], + base: int, + count: int, + pack: int, +) -> list[ir.Value]: + """Gather one source-major inline-asm pack, padding a partial tail with zero.""" + operands = [] + for source_index, source in enumerate(sources): + for lane in range(pack): + letter = input_letters[source_index * pack + lane] + index = base + lane + operands.append( + bitcast_to( + fragment_element( + source, 0 if scalar_sources[source_index] else index + ) + if index < count + else zero_for_constraint(letter), + CONSTRAINT_TYPES[letter](), + ) + ) + return operands + + +@dsl_user_op +def inline_asm_elementwise_intrinsic( + *sources, + asm: str, + constraints: str, + result_type, + is_pure: bool = True, + pack: int = 1, + scalar_sources: tuple[bool, ...] = (), + loc=None, + ip=None, +): + """Apply an inline PTX block elementwise across a TensorSSA fragment. + + Args: + sources: Broadcastable TensorSSA fragments or repeated scalar values. + asm: PTX text using `$N` operand syntax, output first. + constraints: LLVM constraint list, e.g. `"=h,r"`. + result_type: Logical cutlass numeric type of the produced fragment. + E8M0 integer results are decoded to Float32 for fused consumers. + is_pure: Whether the block may be reordered and CSEd. + pack: Elements consumed per asm invocation. Missing tail elements are + zero-padded and their corresponding outputs are discarded. + scalar_sources: Sources whose physical TensorSSA value represents one + logical scalar and must be repeated for every lane. + """ + if pack < 1: + raise ValueError(f"CuteDSL inline asm requires pack >= 1, got pack={pack}") + output_letters, input_letters = split_constraints(constraints) + if len(output_letters) != pack: + raise ValueError( + f"inline asm pack={pack} requires {pack} output constraints, " + f"got {len(output_letters)} in {constraints!r}" + ) + expected_inputs = len(sources) * pack + if len(input_letters) != expected_inputs: + raise ValueError( + f"inline asm pack={pack} with {len(sources)} sources requires " + f"{expected_inputs} input constraints, got {len(input_letters)} " + f"in {constraints!r}" + ) + if not scalar_sources: + scalar_sources = (False,) * len(sources) + elif len(scalar_sources) != len(sources): + raise ValueError( + f"inline asm received {len(scalar_sources)} scalar-source flags " + f"for {len(sources)} sources" + ) + + output_types = [CONSTRAINT_TYPES[letter]() for letter in output_letters] + asm_result_type = output_types[0] + if len(output_types) > 1: + fields = ", ".join(str(output_type) for output_type in output_types) + asm_result_type = ir.Type.parse(f"!llvm.struct<({fields})>") + compute_type = ( + cutlass.Float32 if result_type == cutlass.Float8E8M0FNU else result_type + ) + fragments = [ + source + for source, is_scalar in zip(sources, scalar_sources) + if isinstance(source, cute.TensorSSA) and not is_scalar + ] + if fragments: + shape = fragments[0].shape + if any(source.shape != shape for source in fragments[1:]): + shape = _infer_broadcast_shape(*(source.shape for source in fragments)) + sources = tuple( + source.broadcast_to(shape) + if isinstance(source, cute.TensorSSA) and not is_scalar + else source + for source, is_scalar in zip(sources, scalar_sources) + ) + first_fragment = next( + source + for source, is_scalar in zip(sources, scalar_sources) + if isinstance(source, cute.TensorSSA) and not is_scalar + ) + count = math.prod(ir.VectorType(first_fragment.ir_value().type).shape) + else: + count = 1 + shape = None + + converted = [] + for base in range(0, count, pack): + produced = llvm.inline_asm( + asm_result_type, + packed_operands(sources, input_letters, scalar_sources, base, count, pack), + asm, + constraints, + has_side_effects=not is_pure, + is_align_stack=False, + ) + outputs = [produced] + if len(output_types) > 1: + outputs = [ + llvm.extractvalue(output_type, produced, [index]) + for index, output_type in enumerate(output_types) + ] + valid_outputs = min(pack, count - base) + converted.extend( + convert_output(output, result_type) for output in outputs[:valid_outputs] + ) + + if shape is None: + return compute_type(converted[0]) + vector_type = ir.VectorType.get([count], compute_type.mlir_type) + return cute.TensorSSA( + vector.from_elements(vector_type, converted), shape, compute_type + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/aux_scalars.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/aux_scalars.py new file mode 100644 index 0000000000000000000000000000000000000000..85f2defd260d9eff92490082f7c6844845e9dfdd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/aux_scalars.py @@ -0,0 +1,56 @@ +# mypy: allow-untyped-defs + +import dataclasses +from collections.abc import Callable +from typing import ClassVar + +import sympy + + +@dataclasses.dataclass(frozen=True, slots=True) +class CuteDSLAuxScalarBindings: + """Render symbolic shape captures through FA4's runtime aux_scalars tuple. + + Inductor represents captured dynamic ints/floats as SymPy expressions in the + other-buffer list, while tensor captures remain TensorBox-backed aux_tensors. + CuTe kernels receive those scalar values as ordinary kernel arguments, wrap + them for FA4, and rewrite matching symbols in generated score_mod/mask_mod + expressions to tuple lookups. + """ + + symbols: tuple[sympy.Symbol, ...] = () + tuple_name: ClassVar[str] = "aux_scalars" + + def symbol_codes(self) -> dict[sympy.Symbol, str]: + """Render symbols as tuple lookups for CuTe expressions.""" + return { + symbol: f"{self.tuple_name}[{index}]" + for index, symbol in enumerate(self.symbols) + } + + def symbol_codes_with_renames( + self, rename: Callable[[sympy.Symbol], sympy.Expr] + ) -> dict[sympy.Symbol, str]: + """Include Inductor-renamed symbols used in generated kernel signatures.""" + codes = self.symbol_codes() + for symbol, code in list(codes.items()): + renamed = rename(symbol) + if isinstance(renamed, sympy.Symbol): + codes[renamed] = code + return codes + + def tuple_expr( + self, + rename: Callable[[sympy.Symbol], sympy.Expr], + print_expr: Callable[[sympy.Expr], str], + ) -> str: + """Render runtime scalar values with FA4-compatible scalar wrapper types.""" + if not self.symbols: + return "None" + scalar_values = [] + for symbol in self.symbols: + scalar_type = "cutlass.Int64" if symbol.is_integer else "cutlass.Float64" + scalar_values.append(f"{scalar_type}({print_expr(rename(symbol))})") + if len(scalar_values) == 1: + return f"({scalar_values[0]},)" + return f"({', '.join(scalar_values)})" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..9049bb22c38aa0f3c99413470e441737b9fdb744 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_kernel.py @@ -0,0 +1,1163 @@ +# mypy: allow-untyped-defs +import contextlib +import dataclasses +import logging +import textwrap +from collections.abc import Callable +from typing import Any +from unittest.mock import patch + +import sympy + +import torch +from torch._inductor import config +from torch._inductor.codegen.common import ( + CSE, + CSEVariable, + IndentedBuffer, + Kernel, + PythonPrinter, + ValueRanges, +) +from torch._inductor.ir import ( + BaseView, + Buffer, + ComputedBuffer, + ExternKernel, + InputBuffer, + MutableBox, + ReinterpretView, +) +from torch._inductor.ops_handler import StoreMode +from torch._inductor.utils import OrderedSet +from torch._inductor.virtualized import V + +from ...utils import sympy_index_symbol +from .aux_scalars import CuteDSLAuxScalarBindings +from .cutedsl_op_overrides import CuteDSLCSEVariable, CuteDSLOpOverrides +from .lane_analysis import classify_lane_expr + + +# TODO setting the 'main' kernel w/ this suffix. We have 3 should probably just auto generate this +MAIN_SUFFIX = "main" + + +log = logging.getLogger(__name__) +kernel_code_log = torch._logging.getArtifactLogger(__name__, "kernel_code") + + +class CuteDSLPrinter(PythonPrinter): + def _print_ToFloat(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("ToFloat expects exactly one argument") + return f"cutlass.Float64({self.doprint(expr.args[0])})" + + +cutedsl_pexpr = CuteDSLPrinter().doprint + + +class CuteDSLKernelWrapper: + """Wrapper to provide .run() interface for CuteDSL kernels""" + + def __init__(self, kernel_fn: Callable[..., Any], kernel_path: str | None = None): + self.kernel_fn = kernel_fn + self.kernel_path = kernel_path + kernel_code_log.info("CuteDSL kernel path: %s", kernel_path) + + def run(self, *args, stream=None, **kwargs): + """ + Execute the CuteDSL kernel. + + Args: + *args: Arguments to pass to the kernel function + stream: CUDA stream to pass to the kernel function + **kwargs: Additional keyword arguments for the kernel + + Returns: + Result of the kernel execution + """ + return self.kernel_fn(*args, stream=stream, **kwargs) + + +@dataclasses.dataclass(frozen=True, slots=True) +class CuteDSLVectorLoadConfig: + vec_size: int + index: sympy.Symbol + dim: int + + @staticmethod + def from_fixed_inputs( + fixed_inputs: dict[str, Any], + ) -> "CuteDSLVectorLoadConfig | None": + vec_size = fixed_inputs.pop("vector_load_vec_size", None) + index = fixed_inputs.pop("vector_load_index", None) + dim = fixed_inputs.pop("vector_load_dim", None) + if vec_size is None or index is None or dim is None: + return None + return CuteDSLVectorLoadConfig( + vec_size=int(vec_size), + index=sympy_index_symbol(str(index)), + dim=int(dim), + ) + + def normalized_dim(self, ndim: int) -> int: + return self.dim + ndim if self.dim < 0 else self.dim + + +@dataclasses.dataclass(frozen=True, slots=True) +class CuteDSLIndexFragment: + """Generated index expression metadata for CuteDSL tensor loads. + + Attributes: + code: Python source expression for the index or index fragment. + is_static_int: True when code is an inline integer index, not a fragment. + is_lane_uniform: True when every vector lane has the same index. + is_contiguous: True when code is aligned and contiguous for the full + requested vector width. + """ + + code: str + is_static_int: bool + is_lane_uniform: bool = False + is_contiguous: bool = False + contiguous_width: int | None = None + + +@dataclasses.dataclass(frozen=True) +class IndexSymbolInfo: + """What lane analysis may assume about a generated index symbol. + + expr: Recovered semantic index expression, or None when the value's + semantics are unknown (loaded from a captured tensor, or produced by + ops outside the traced index algebra). Unknown semantics force a + per-lane gather: assuming lane-uniform would broadcast lane 0's load + across the vectorized group (#188878). + contiguous_ok: False when the value passed through a negative-index wrap + (idx + size for negative lanes only). Uniform lanes all wrap + identically, so lane-uniformity survives, but a contiguous window + straddling 0 jumps from size-1 back to 0 and we can't prove a window + avoids 0. + """ + + expr: sympy.Expr | None + contiguous_ok: bool = True + + +@dataclasses.dataclass +class CuteDSLSubgraphInfo: + """Minimal subgraph info for CuteDSL kernels.""" + + body: IndentedBuffer + template_mask: str | None = None + template_out: str | None = None + cse: CSE[Any, str] | None = None + + def __post_init__(self): + self.only_copy_if_non_none_fields = ("cse",) + + def to_dict(self): + return { + field.name: getattr(self, field.name) for field in dataclasses.fields(self) + } + + +class CuteDSLTemplateKernel(Kernel): + """ + Template kernel implementation for CuteDSL (CUTLASS Python DSL). + Handles code generation and argument management for CuteDSL CUDA kernels. + Provides CuteDSL-specific functionality for tensor conversion and kernel configuration. + """ + + def __init__( + self, + kernel_name: str, + input_nodes: list[Buffer], + output_node: Buffer, + subgraphs: list[Buffer] | None = None, + ) -> None: + # Call parent Kernel constructor + super().__init__() + self.kernel_name = kernel_name + self.input_nodes = input_nodes + self.output_node = output_node + self.subgraphs = subgraphs + self.subgraph_bodies: dict[str, CuteDSLSubgraphInfo] = {} + + # Template attributes + self.body: IndentedBuffer = IndentedBuffer() + self.template_mask: str | None = None + self.template_out: str | None = None + self.template_indices: list[Any] | None = None + self.render_hooks: dict[str, Any] = {} + + # TODO Additional attributes needed by template system + self.prologue_fused_inputs: OrderedSet[str] = OrderedSet() + self.prologue_fused_inputs_preserve_zero: OrderedSet[str] = OrderedSet() + self.named_input_nodes: dict[str, Buffer] = {} + + # Create named input nodes mapping + for i, input_node in enumerate(input_nodes): + node_name = getattr(input_node, "name", f"input_{i}") + self.named_input_nodes[node_name] = input_node + + self.cse = CSE(name_prefix="tmp") + + # Track all tensor buffers added during modification processing + self.collected_tensor_buffers: list[str] = [] + self.aux_scalar_bindings = CuteDSLAuxScalarBindings() + + # Captured IR nodes keyed by buffer name. Used by call_kernel to emit + # reinterpret_tensor for view captures in the python_argdefs loop. + self._capture_input_nodes: dict[str, Any] = {} + + def set_capture_input_nodes(self, nodes_by_name: dict[str, Any]) -> None: + """Set captured inputs collected while rendering the CuteDSL template.""" + self._capture_input_nodes = nodes_by_name + + def _get_capture_input_node(self, name: str) -> Any | None: + """Return the IR node for a captured input name, if known.""" + graph_captures = getattr(V.graph, "_cutedsl_capture_nodes", {}) + return self._capture_input_nodes.get(name, graph_captures.get(name)) + + @contextlib.contextmanager + def _patch_get_dtype_for_captures(self): + """Teach python_argdefs to resolve synthetic captured input names.""" + original_get_dtype = V.graph.get_dtype + + def get_dtype(name: str) -> torch.dtype: + capture = self._get_capture_input_node(name) + if capture is not None: + return capture.get_dtype() + return original_get_dtype(name) + + with patch.object(V.graph, "get_dtype", get_dtype): + yield + + def kexpr(self, expr: sympy.Expr) -> str: + """Convert sympy expression to CuteDSL string representation.""" + symbol_codes = self.aux_scalar_bindings.symbol_codes_with_renames( + self.rename_indexing + ) + if symbol_codes: + expr = expr.xreplace( + {symbol: sympy.Symbol(code) for symbol, code in symbol_codes.items()} + ) + return cutedsl_pexpr(expr) + + def create_cse_var(self, *args, **kwargs): + return CuteDSLCSEVariable(*args, **kwargs) + + def gen_imports(self) -> str: + """Generate common imports for CuteDSL templates.""" + imports = IndentedBuffer() + imports.splice( + """ + import torch + import cutlass + import cutlass.cute as cute + from cutlass.cute.runtime import from_dlpack + import cuda.bindings.driver as cuda + from cutlass._mlir.dialects import math as mlir_math + import operator + from torch._inductor.codegen.cutedsl._cutedsl_utils import result_to_ssa, ssa_to_fragment, ssa_to_indexable + """ + ) + return imports.getvalue() + + def gen_defines(self, **kwargs) -> str: + """Generate CuteDSL parameter definitions from kwargs, similar to Triton's gen_defines.""" + params = IndentedBuffer() + for name, val in kwargs.items(): + params.writeline(f"{name}: cutlass.Constexpr = {val}") + return params.getvalue() + + def render(self, template, **kwargs): + from torch._inductor.select_algorithm import PartialRender + + """Render the kernel using the template, returning PartialRender object with hooks.""" + self._template_kwargs = dict(kwargs) + self.aux_scalar_bindings = CuteDSLAuxScalarBindings( + tuple(kwargs.get("AUX_SCALAR_SYMBOLS", ())) + ) + + # Available {{}} hooks for jinja rendering + template_env = { + "def_kernel": self.def_kernel, + "gen_defines": lambda: self.gen_defines(**kwargs), + "get_output": self.get_output, + "get_tensor_buffers": self.get_tensor_buffers, + "add_tensor_inputs": self.add_tensor_inputs, + "define_aux_scalars": self.define_aux_scalars, + "unpack_buffers": self.unpack_buffers, + "modification": self.modification, + "set_cute_hash": self.set_cute_hash, + } + + # Render the template with the environment and provided kwargs + rendered_code = template.render( + kernel_name=self.kernel_name, + input_nodes=self.input_nodes, + output_node=self.output_node, + **template_env, + **kwargs, + ) + + # Always prepend the common imports + imports = self.gen_imports() + full_code = imports + rendered_code + + return PartialRender(full_code, self.render_hooks) + + @contextlib.contextmanager + def set_subgraph_body(self, body_name: str): + """Set the active subgraph body for template processing.""" + if not all( + hasattr(self, field.name) + for field in dataclasses.fields(CuteDSLSubgraphInfo) + ): + raise AssertionError( + "expected all CuteDSLSubgraphInfo fields to be set on self" + ) + old_state = { + key.name: getattr(self, key.name) + for key in dataclasses.fields(CuteDSLSubgraphInfo) + } + + if body_name not in self.subgraph_bodies: + self.subgraph_bodies[body_name] = CuteDSLSubgraphInfo( + body=IndentedBuffer(), + template_mask=None, + template_out=None, + cse=None, + ) + + subgraph = self.subgraph_bodies[body_name] + for key, value in subgraph.to_dict().items(): + if value is None and key in getattr( + subgraph, "only_copy_if_non_none_fields", () + ): + continue + setattr(self, key, value) + + try: + yield + finally: + # Save current state back to subgraph + self.subgraph_bodies[body_name] = CuteDSLSubgraphInfo( + **{ + key.name: getattr(self, key.name) + for key in dataclasses.fields(CuteDSLSubgraphInfo) + } + ) + # Restore old state + for key, value in old_state.items(): + setattr(self, key, value) + + @contextlib.contextmanager + def create_subgraph_body(self, body_name: str, *, clear_cse: bool = False): + """Create a new subgraph body for template processing.""" + if body_name in self.subgraph_bodies: + raise AssertionError(f"Subgraph body '{body_name}' already exists") + new_cse = self.cse.clone() if clear_cse else None + self.subgraph_bodies[body_name] = CuteDSLSubgraphInfo( + body=IndentedBuffer(), + template_mask=None, + template_out=None, + cse=new_cse, + ) + with self.set_subgraph_body(body_name): + yield + + def _get_reinterpret_view(self, node) -> ReinterpretView | None: + """Extract or convert to ReinterpretView from a node, handling all views.""" + while isinstance(node, MutableBox): + node = node.data + if isinstance(node, BaseView): + return ExternKernel.convert_to_reinterpret_view(node) + return None + + def def_kernel(self, *argnames): + """Define kernel function signature for CuteDSL templates. + + When inputs are ReinterpretViews of the same underlying buffer (e.g., Q/K/V + from fused QKV projection), we generate separate arguments for each input + even though they share the same underlying buffer. + """ + renames = IndentedBuffer(initial_indent=1) + + # Track template input args - each input gets its own arg even if buffers are shared + self._template_input_args: list[tuple[str, Buffer]] = [] + self._seen_input_args: OrderedSet[str] = OrderedSet() + + for i, input_node in enumerate(self.input_nodes): + buf_name = input_node.get_name() + # Register with args system (may deduplicate, but we track separately) + self.args.input(buf_name) + + if i < len(argnames): + template_name = argnames[i] + arg_name = f"arg_{template_name}" + self.args.input_buffers[buf_name] = arg_name + renames.writeline(f"{template_name} = {arg_name}") + self._template_input_args.append((arg_name, input_node)) + self._seen_input_args.add(arg_name) + + if self.output_node: + self.args.output(self.output_node.get_name()) + + def hook(): + # Generate signature with template input args plus additional args (output, sizevars) + code = IndentedBuffer() + code.writeline(f"# Kernel function signature: {self.kernel_name}") + + # Start with template input args + params = [arg_name for arg_name, _ in self._template_input_args] + + # Get additional args from python_argdefs (output, sizevars, etc.) + with self._patch_get_dtype_for_captures(): + arg_defs, _, _, _ = self.args.python_argdefs() + for arg_def in arg_defs: + if arg_def.full_name() not in self._seen_input_args: + params.append(arg_def.full_name()) + + params.append("stream") + code.writeline( + f"def {self.kernel_name}_{MAIN_SUFFIX}({', '.join(params)}):" + ) + with code.indent(): + code.splice(renames.getvalue()) + return code.getvalue() + + if "" in self.render_hooks: + raise AssertionError(" hook already registered") + # Placeholder-based rendering: hook will be called when template encounters "" + self.render_hooks[""] = hook + return "" + + def get_output(self): + """Get the actual argument name for the output buffer.""" + if not self.output_node: + raise AssertionError("Output node must exist to get output buffer name") + buf_name = self.output_node.get_name() + output = self.args.output_buffers.get(buf_name, None) + if output is None: + raise ValueError(f"Output buffer '{buf_name}' not found in args") + return output + + def set_cute_hash(self, func_name: str, suffix: str = ""): + """Generate code to set __cute_hash__ on a codegen function. + + This allows hash_callable in flash_attn to skip expensive runtime hashing + for Inductor-generated functions. The hash is based on the kernel name + which already contains a unique hash suffix. + """ + hash_value = f"{self.kernel_name}_{suffix}" if suffix else self.kernel_name + return f'{func_name}.__cute_hash__ = "{hash_value}"' + + def get_tensor_buffers(self): + """Get list of tensor buffer names that were collected during modifications.""" + return self.collected_tensor_buffers + + def add_tensor_inputs(self, buffers): + """Register extra tensor buffers and return their rendered input names.""" + buffer_names = [] + for buffer in buffers: + if isinstance(buffer, sympy.Expr): + continue + remapped_name = self.args.input(buffer.get_name()) + if remapped_name not in self.collected_tensor_buffers: + self.collected_tensor_buffers.append(remapped_name) + buffer_names.append(remapped_name) + return buffer_names + + def define_aux_scalars(self, symbols): + """Return the runtime scalar tuple for captured symbolic scalars.""" + if tuple(symbols) != self.aux_scalar_bindings.symbols: + raise AssertionError( + f"Expected aux scalar symbols {self.aux_scalar_bindings.symbols}, " + f"got {tuple(symbols)}" + ) + return self.aux_scalar_bindings.tuple_expr(self.rename_indexing, cutedsl_pexpr) + + def unpack_buffers(self, buffer_list_name: str, *, indent_width: int = 4): + """Generate buffer unpacking code via render hook.""" + + def hook(): + tensor_buffers = self.get_tensor_buffers() + if not tensor_buffers: + return "" + + # Generate unpacking assignments: in_ptr4 = buffers[0], etc. + unpacking_lines = [] + for i, buffer_name in enumerate(tensor_buffers): + # pyrefly: ignore [bad-argument-type] + unpacking_lines.append(f"{buffer_name} = {buffer_list_name}[{i}]") + + indent = " " * indent_width + return "\n" + indent + ("\n" + indent).join(unpacking_lines) + + # Register the hook and return placeholder + placeholder = "" + # TODO: I think double invoking is fine for this specific hook + # assert placeholder not in self.render_hooks + self.render_hooks[placeholder] = hook + return placeholder + + def call_kernel(self, name: str, node=None): + """Call the kernel function. Simplified version of TritonTemplateKernel.call_kernel. + + For inputs that are ReinterpretViews (e.g., Q/K/V slices from fused QKV), + we generate reinterpret_tensor() calls to properly handle the views. + """ + wrapper = V.graph.wrapper_code + + # Build call args matching the signature generated in `def_kernel` + call_args = [] + arg_types = [] + + for _, input_node in self._template_input_args: + reinterpret_view = self._get_reinterpret_view(input_node) + if reinterpret_view is not None: + call_args.append(reinterpret_view.codegen_reference()) + else: + call_args.append(input_node.get_name()) + arg_types.append(V.graph.get_dtype(input_node.get_name())) + + # Add additional args from python_argdefs (output, sizevars, ..) + with self._patch_get_dtype_for_captures(): + orig_arg_defs, orig_call_args, _, orig_arg_types = ( + self.args.python_argdefs() + ) + for arg_def, call_arg, arg_type in zip( + orig_arg_defs, orig_call_args, orig_arg_types + ): + if arg_def.full_name() in self._seen_input_args: + continue + capture = self._get_capture_input_node(call_arg) + if isinstance(capture, ReinterpretView): + # Pass the original view expression so stride/offset metadata is + # preserved at the kernel call site. + call_args.append(capture.codegen_reference()) + else: + call_args.append(call_arg) + arg_types.append(arg_type) + + # TODO this karg really should not be called `triton` + wrapper.generate_kernel_call(name, call_args, triton=True, arg_types=arg_types) + + def _get_subgraph(self, subgraph_number: int): + """Get subgraph by number for modification processing.""" + if not isinstance(subgraph_number, int): + raise AssertionError( + f"expected subgraph_number to be int, got {type(subgraph_number)}" + ) + if not isinstance(self.subgraphs, list): + raise AssertionError( + f"expected self.subgraphs to be list, got {type(self.subgraphs)}" + ) + if subgraph_number >= len(self.subgraphs): + raise AssertionError( + f"Invalid subgraph number provided to create_modification, {subgraph_number} must be < {len(self.subgraphs)}" + ) + if self.body.getvalue() != "": + raise AssertionError("Body should be clear before adding a modification") + return self.subgraphs[subgraph_number] + + def modification( + self, + subgraph_number: int, + output_name: str | None, + mask: str | None = None, + **fixed_inputs, + ) -> str: + """Generate CuteDSL code for a subgraph modification.""" + # Find unique name to avoid collisions between multiple modifications of same subgraph + num = 0 + while f"mod_{subgraph_number}_{num}" in self.subgraph_bodies: + num += 1 + + with self.create_subgraph_body(f"mod_{subgraph_number}_{num}", clear_cse=True): + subgraph = self._get_subgraph(subgraph_number) + modification_handler = ModificationWrapperCuteDSL( + self, subgraph_number, fixed_inputs, mask + ) + with V.set_kernel_handler(self), V.set_ops_handler(modification_handler): + if not isinstance(subgraph, (ComputedBuffer, list)): + raise AssertionError( + f"Expected ComputedBuffer or List[ComputedBuffer], got {type(subgraph)}" + ) + + if isinstance(subgraph, list): + raise NotImplementedError( + "Scatter graphs are not supported for CuteDSL" + ) + + if isinstance(subgraph.data, InputBuffer): + # grad_score_mod can be InputBuffers + out = subgraph.data.make_loader()(()) + else: + # Inline a pointwise lowering into the template + out = subgraph.data.inner_fn(()) + + if output_name is not None: + if out is None: + raise AssertionError( + f"Expected computation result for named output {output_name}" + ) + self.body.writeline(f"{output_name} = {out.value}") + else: + # Side-effect only: no output assignment (currently only for scatter operations) + raise NotImplementedError( + "Side-effect only modifications not yet supported for CuteDSL" + ) + + # Add Buffers that were added during modification + self.collected_tensor_buffers.extend(modification_handler.tensor_buffers) + + return self.body.getvalue() + + +class ModificationWrapperCuteDSL(V.WrapperHandler): # type: ignore[name-defined] + """ + Wrapper handler that enables CuteDSL code generation during subgraph modifications. + + This class sits between the PyTorch IR and CuteDSL code generation, providing: + 1. Operation substitution: converts PyTorch ops to CuteDSL equivalents via CuteDSLOpOverrides + 2. Placeholder handling: resolves fixed_inputs during template processing + 3. Limited operation support: currently restricted to pointwise operations + + """ + + def __init__( + self, + kernel, + subgraph_number: int, + fixed_inputs: dict[str, Any], + mask: str | None, + ): + cutedsl_ops = CuteDSLOpOverrides() + super().__init__(cutedsl_ops) + self.name = f"CuteDSLPlaceholderSubstitution_{subgraph_number}" + self.kernel = kernel + self.fixed_inputs = dict(fixed_inputs) + self.vector_load_config = CuteDSLVectorLoadConfig.from_fixed_inputs( + self.fixed_inputs + ) + self.mask = mask + # Track tensor buffers that get added during modification processing + self.tensor_buffers: list[str] = [] + # Maps generated CSE names to their semantic provenance so vector-load + # analysis can reason about the source indexing semantics. + self._index_symbol_info: dict[sympy.Symbol, IndexSymbolInfo] = {} + # Captured modifications are read-only, so repeated loads from the same + # semantic location can share the generated index and value fragments. + self._captured_load_cache: dict[tuple[str, sympy.Expr], CuteDSLCSEVariable] = {} + + def _get_input_dtype(self, name: str) -> torch.dtype: + """Get the dtype for an input from the kernel's named_input_nodes.""" + if name in self.kernel.named_input_nodes: + return self.kernel.named_input_nodes[name].dtype + # TODO: Fallback for common dimension names - should be replaced with proper dtype tracking + return torch.float32 if name not in ("b", "h", "m", "n") else torch.int32 + + def load(self, name: str, index: sympy.Expr): + """Handle loading from tensor or fixed(template args) input for CuteDSL.""" + from torch._inductor.kernel.flex.flex_flash_attention import HierarchicalIndex + + if name not in self.fixed_inputs: + cache_key = (name, index) + cached = self._captured_load_cache.get(cache_key) + if cached is not None: + return self.kernel.cse.generate(self.kernel.body, cached) + + var = self._add_kernel_input(name) + buffer = self.kernel._get_capture_input_node(name) + if buffer is None: + buffer = V.graph.get_buffer(name) + var_dtype = buffer.dtype + + cute_dtype = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get( + var_dtype, "cutlass.Float32" + ) + dim_indices = ( + index.args if isinstance(index, HierarchicalIndex) else (index,) + ) + dim_sizes = buffer.get_size() + if len(dim_sizes) == 0: + dim_indices = () + # Per-dimension indices into captured buffers are bounded by dim + # sizes (not flattened offsets), so Int32 is safe whatever index + # dtype the consuming kernel passes in; wider index expressions are + # narrowed at fragment materialization. + idx_vars = [ + self._emit_index_fragment( + dim_index, dim_size, "cutlass.Int32", torch.int32 + ) + for dim_index, dim_size in zip(dim_indices, dim_sizes, strict=True) + ] + + val_frag = self._emit_tensor_load_fragment( + var, idx_vars, cute_dtype, var_dtype, buffer + ) + final_expr = f"{val_frag}.load()" + + if ( + var_dtype in (torch.float16, torch.bfloat16) + and config.triton.codegen_upcast_to_fp32 + ): + final_expr = f"({final_expr}).to(cutlass.Float32)" + var_dtype = torch.float32 + + out = self.kernel.cse.generate( + self.kernel.body, + final_expr, + dtype=var_dtype, + bounds=ValueRanges.unknown(), + shape=(1,), + ) + self._captured_load_cache[cache_key] = out + return out + + value = self.fixed_inputs[name] + dtype = self._get_input_dtype(name) + + result = self.kernel.cse.generate( + self.kernel.body, value, bounds=ValueRanges.unknown(), dtype=dtype + ) + if ( + isinstance(result, CuteDSLCSEVariable) + and isinstance(value, str) + and dtype in (torch.int32, torch.int64) + ): + result.index_expr = sympy_index_symbol(value) + return result + + def _emit_tensor_load_fragment( + self, + var: str, + idx_vars: list[CuteDSLIndexFragment], + cute_dtype: str, + var_dtype: torch.dtype, + buffer: Any, + ) -> str: + """ + Emit a register fragment load from a captured tensor. + + Static integer indices can be emitted directly as scalar tensor indices. + Dynamic indices are SSA vectors, which must first be materialized into + register fragments so each lane can be used for scalar gather loads. If + all indices are static, emit a single-element fragment; otherwise size + the value fragment to match the dynamic index lanes. + """ + dynamic_index_fragment = next( + (idx for idx in idx_vars if not idx.is_static_int), None + ) + # Dynamic index fragments all carry the same vector width, so one + # representative fragment is enough to size the loaded value fragment. + val_frag = self.kernel.cse.newvar(dtype=var_dtype) + if len(buffer.get_size()) == 0: + self.kernel.body.writeline( + f"{val_frag} = cute.make_rmem_tensor(1, {cute_dtype})" + ) + self.kernel.body.writeline(f"{val_frag}[0] = ({var}[()])") + return str(val_frag) + if dynamic_index_fragment is None: + self.kernel.body.writeline( + f"{val_frag} = cute.make_rmem_tensor(1, {cute_dtype})" + ) + self.kernel.body.writeline( + f"{val_frag}[0] = ({var}[{', '.join(idx.code for idx in idx_vars)}])" + ) + return str(val_frag) + + self.kernel.body.writeline( + f"{val_frag} = cute.make_rmem_tensor(" + f"cute.size({dynamic_index_fragment.code}.shape), {cute_dtype})" + ) + if self.vector_load_config is None: + vector_dim = len(idx_vars) - 1 + else: + vector_dim = self.vector_load_config.normalized_dim(len(idx_vars)) + if self._can_emit_contiguous_dim_load(idx_vars, buffer, var_dtype, vector_dim): + self._emit_contiguous_dim_load( + var, idx_vars, val_frag, cute_dtype, var_dtype, vector_dim + ) + elif self._can_emit_uniform_load(idx_vars): + self._emit_uniform_load(var, idx_vars, val_frag) + else: + self._emit_per_lane_gather_load(var, idx_vars, val_frag) + return str(val_frag) + + def _can_emit_contiguous_dim_load( + self, + idx_vars: list[CuteDSLIndexFragment], + buffer: Any, + var_dtype: torch.dtype, + vector_dim: int, + ) -> bool: + """Return true when vector lanes form a safe contiguous tensor tile. + + This is stricter than lane-contiguity analysis: CuTe autovec also needs + a real byte-addressable copy type, uniform non-vector dimensions, unit + vector stride, and a statically aligned full-width tile. + """ + if var_dtype is torch.bool: + return False + if not idx_vars or not idx_vars[vector_dim].is_contiguous: + return False + if any( + not (idx.is_static_int or idx.is_lane_uniform) + for dim, idx in enumerate(idx_vars) + if dim != vector_dim + ): + return False + sizes = buffer.get_size() + strides = buffer.get_stride() + vector_size = ( + 1 if self.vector_load_config is None else self.vector_load_config.vec_size + ) + contiguous_width = idx_vars[vector_dim].contiguous_width + has_vector_width = vector_size > 1 + has_unit_stride = V.graph.sizevars.statically_known_equals( + strides[vector_dim], 1 + ) + has_full_width_contiguity = ( + contiguous_width is not None and contiguous_width >= vector_size + ) + is_size_aligned = V.graph.sizevars.statically_known_multiple_of( + sizes[vector_dim], vector_size + ) + is_offset_aligned = V.graph.sizevars.statically_known_multiple_of( + buffer.get_layout().offset, vector_size + ) + are_non_vector_strides_aligned = all( + V.graph.sizevars.statically_known_multiple_of(stride, vector_size) + for dim, stride in enumerate(strides) + if dim != vector_dim + ) + return ( + has_vector_width + and has_unit_stride + and has_full_width_contiguity + and is_size_aligned + and is_offset_aligned + and are_non_vector_strides_aligned + ) + + def _emit_contiguous_dim_load( + self, + var: str, + idx_vars: list[CuteDSLIndexFragment], + val_frag: str, + cute_dtype: str, + var_dtype: torch.dtype, + vector_dim: int, + ) -> None: + """Emit an autovec load for lanes contiguous in one tensor dimension.""" + scalar_indices = [ + idx.code if idx.is_static_int else f"{idx.code}[0]" for idx in idx_vars + ] + vec_size = f"cute.size({val_frag}.shape)" + aligned_idx = self.kernel.cse.newvar(dtype=torch.int32) + source_tile = self.kernel.cse.newvar(dtype=var_dtype) + aligned_ptr = self.kernel.cse.newvar(dtype=var_dtype) + aligned_source = self.kernel.cse.newvar(dtype=var_dtype) + + vector_idx = idx_vars[vector_dim].code + tiler_items = ["1"] * len(idx_vars) + tiler_items[vector_dim] = vec_size + coord_items = scalar_indices + coord_items[vector_dim] = f"{aligned_idx} // {vec_size}" + source_view_items = ["0"] * len(idx_vars) + source_view_items[vector_dim] = "None" + source_view = ( + str(aligned_source) + if len(idx_vars) == 1 + else f"{aligned_source}[{', '.join(source_view_items)}]" + ) + tiler = ( + f"({tiler_items[0]},)" + if len(tiler_items) == 1 + else f"({', '.join(tiler_items)})" + ) + coord = ( + f"({coord_items[0]},)" + if len(coord_items) == 1 + else f"({', '.join(coord_items)})" + ) + self.kernel.body.splice( + f""" + {aligned_idx} = cute.assume({vector_idx}[0], divby={vec_size}) + {source_tile} = cute.local_tile({var}, {tiler}, {coord}) + {aligned_ptr} = cute.make_ptr({cute_dtype}, {source_tile}.iterator.toint(), {source_tile}.iterator.memspace, assumed_align=min(16, {vec_size} * {var_dtype.itemsize})) + {aligned_source} = cute.make_tensor({aligned_ptr}, {source_tile}.layout) + cute.autovec_copy({source_view}, {val_frag}) + """ + ) + + @staticmethod + def _can_emit_uniform_load(idx_vars: list[CuteDSLIndexFragment]) -> bool: + """Return true when every vector lane reads the same tensor element.""" + return all(idx.is_static_int or idx.is_lane_uniform for idx in idx_vars) + + def _emit_uniform_load( + self, var: str, idx_vars: list[CuteDSLIndexFragment], val_frag: str + ) -> None: + """Emit one scalar load and broadcast it across the value fragment.""" + scalar_value = self.kernel.cse.newvar(dtype=None) + scalar_indices = [ + idx.code if idx.is_static_int else f"{idx.code}[0]" for idx in idx_vars + ] + self.kernel.body.writeline( + f"{scalar_value} = ({var}[{', '.join(scalar_indices)}])" + ) + self.kernel.body.writeline( + f"for load_idx in cutlass.range(cute.size({val_frag}.shape), unroll_full=True):" + ) + with self.kernel.body.indent(): + self.kernel.body.writeline(f"{val_frag}[load_idx] = {scalar_value}") + + def _emit_per_lane_gather_load( + self, var: str, idx_vars: list[CuteDSLIndexFragment], val_frag: str + ) -> None: + """Emit scalar per-lane loads for non-contiguous gather indices. + + Lane-uniform index fragments hold a single element, so they are indexed + at [0] rather than [load_idx] (which would read out of bounds and + silently corrupt the gathered rows). + """ + self.kernel.body.writeline( + f"for load_idx in cutlass.range(cute.size({val_frag}.shape), unroll_full=True):" + ) + with self.kernel.body.indent(): + load_indices = [ + idx.code + if idx.is_static_int + else f"{idx.code}[0]" + if idx.is_lane_uniform + else f"{idx.code}[load_idx]" + for idx in idx_vars + ] + self.kernel.body.writeline( + f"{val_frag}[load_idx] = ({var}[{', '.join(load_indices)}])" + ) + + def _emit_index_fragment( + self, + expr: sympy.Expr, + dim_size: sympy.Expr, + cute_dtype: str, + torch_dtype: torch.dtype, + ) -> CuteDSLIndexFragment: + """Materialize an index and preserve enough metadata for load selection.""" + static_expr = self._static_integer_expr(expr) + if static_expr is not None: + return CuteDSLIndexFragment( + self.kernel.kexpr(self._wrap_static_index(static_expr, dim_size)), + is_static_int=True, + ) + + expr = self.kernel.rename_indexing(expr) + is_lane_uniform, is_contiguous, contiguous_width = self._analyze_index_fragment( + expr + ) + result = self.kernel.cse.newvar(dtype=torch_dtype) + self.kernel.body.writeline( + f"{result} = ssa_to_fragment({self.kernel.kexpr(expr)}, {cute_dtype})" + ) + return CuteDSLIndexFragment( + str(result), + is_static_int=False, + is_lane_uniform=is_lane_uniform, + is_contiguous=is_contiguous, + contiguous_width=contiguous_width, + ) + + def _analyze_index_fragment( + self, expr: sympy.Expr + ) -> tuple[bool, bool, int | None]: + if self.vector_load_config is None: + return False, False, None + if self.vector_load_config.vec_size <= 1: + return True, False, None + + contiguous_ok = True + for sym in expr.free_symbols: + info = self._index_symbol_info.get(sym) + if info is not None: + if info.expr is None: + # If we dont know the semantics of the index, we cannot determine lane behavior. + # So we default to safe/pessimistic behavior: per-lane gather, no uniformity, no contiguity. + return False, False, None + contiguous_ok &= info.contiguous_ok + + semantic_expr = self._semantic_index_expr(expr) + if self._has_unresolved_index_symbols(semantic_expr): + # ditto -> we dont know so choose safe/pessimistic behavior + return False, False, None + + lane_info = classify_lane_expr( + semantic_expr, + self.vector_load_config.index, + max_width=self.vector_load_config.vec_size, + uniform_symbols=self._lane_uniform_symbols(), + ) + return ( + lane_info.is_uniform, + lane_info.is_contiguous and contiguous_ok, + lane_info.contiguous_width if contiguous_ok else None, + ) + + def _has_unresolved_index_symbols(self, semantic_expr: sympy.Expr) -> bool: + """Return whether the expression references opaque computed indices. + + Lane analysis treats unknown non-lane symbols as lane-uniform scalars, + which is correct for sizes and fixed inputs but silently broadcasts + lane 0's gather when the symbol is actually per-lane runtime data + (#188878). Recovered semantics substitute away generated CSE names, so + a surviving symbol in the reserved ``tmpN`` namespace means recovery + failed and the load must stay a per-lane gather. + """ + prefix = self.kernel.cse.name_prefix + lane_var = self.vector_load_config.index if self.vector_load_config else None + return any( + sym is not lane_var + and sym.name.startswith(prefix) + and sym.name[len(prefix) :].isdigit() + for sym in semantic_expr.free_symbols + ) + + @staticmethod + def _static_integer_expr(expr: object) -> int | sympy.Integer | None: + if isinstance(expr, int | sympy.Integer): + return expr + if isinstance(expr, sympy.Symbol) and expr.name.lstrip("-").isdigit(): + return int(expr.name) + if isinstance(expr, sympy.Expr): + expr = V.graph.sizevars.simplify(expr) + if expr.is_Integer: + return expr + return None + + @staticmethod + def _wrap_static_index( + index: int | sympy.Integer, dim_size: sympy.Expr + ) -> int | sympy.Expr: + if int(index) < 0: + return V.graph.sizevars.simplify(sympy.Integer(index) + dim_size) + return index + + def _semantic_index_expr(self, expr: sympy.Expr) -> sympy.Expr: + """Recover the original index meaning from generated CSE names.""" + replacements: dict[sympy.Symbol, sympy.Expr] = { + symbol: info.expr + for symbol, info in self._index_symbol_info.items() + if info.expr is not None + } + for var in self.kernel.cse._cache.values(): + if isinstance(var, CuteDSLCSEVariable) and var.index_expr is not None: + replacements[sympy_index_symbol(var.name)] = var.index_expr + return V.graph.sizevars.simplify(expr.xreplace(replacements)) + + def _lane_uniform_symbols(self) -> OrderedSet[sympy.Symbol]: + """Return generated CSE source symbols that are uniform across lanes.""" + vector_index_name = ( + None + if self.vector_load_config is None + else self.vector_load_config.index.name + ) + return OrderedSet( + [ + sympy_index_symbol(source_expr) + for source_expr in self.kernel.cse._cache + if isinstance(source_expr, str) and source_expr != vector_index_name + ] + ) + + def indirect_indexing(self, index_var: str, size, check, wrap_neg=True): + """Convert index variable to symbolic form.""" + if isinstance(index_var, int | sympy.Integer): + if wrap_neg and index_var < 0: + return V.graph.sizevars.simplify(sympy.Integer(index_var) + size) + return sympy.Integer(index_var) + if ( + wrap_neg + and isinstance(index_var, CuteDSLCSEVariable) + and index_var.index_expr is not None + and not V.graph.sizevars.statically_known_geq(index_var.index_expr, 0) + ): + wrapped = self.kernel.cse.newvar(dtype=index_var.dtype) + # Dynamic sizes render as Int64 aux_scalars; cast to the index dtype so + # both cute.where branches agree (per-dim size, so narrowing is safe). + index_cute_dtype = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get( + index_var.dtype, "cutlass.Int32" + ) + size_expr = f"{index_cute_dtype}({self.kernel.kexpr(size)})" + self.kernel.body.writeline( + f"{wrapped} = cute.where(" + f"{index_var} < 0, {index_var} + {size_expr}, {index_var})" + ) + symbol = sympy_index_symbol(str(wrapped)) + # Preserve the pre-wrap semantics so lane analysis sees the true + # lane structure; the wrap remaps negative lanes individually, so + # contiguity of the pre-wrap expression does not survive it. + self._index_symbol_info[symbol] = IndexSymbolInfo( + index_var.index_expr, contiguous_ok=False + ) + return symbol + source_name = None + for expr, var in self.kernel.cse._cache.items(): + if var is index_var: + source_name = expr if isinstance(expr, str) else None + break + symbol = sympy_index_symbol(source_name or str(index_var)) + index_expr = ( + index_var.index_expr if isinstance(index_var, CuteDSLCSEVariable) else None + ) + self._index_symbol_info[symbol] = IndexSymbolInfo(index_expr) + return symbol + + # pyrefly: ignore [bad-override] + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> str: + raise NotImplementedError( + "Store operations not supported - CuteDSL limited to read-only operations" + ) + + def _add_kernel_input(self, name: str): + """Add name as input to kernel and return input ref.""" + # Get the remapped name that will be used in the kernel + remapped_name = self.kernel.args.input(name) + # Track the remapped name for later collection + if remapped_name not in self.tensor_buffers: + self.tensor_buffers.append(remapped_name) + return remapped_name + + def _process_indexing(self, index): + """Process and rename indexing, adding symbols as kernel inputs.""" + renamed = self.kernel.rename_indexing(index) + return self.kernel.kexpr(renamed) + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + try: + return getattr(self._inner, name)(*args, **kwargs) + except NotImplementedError as e: + bar = "=" * 80 + msg = textwrap.dedent(f""" + {bar} + UNSUPPORTED CUTEDSL OPERATION: '{name}' + {bar} + This operation is not yet implemented in Inductor. + + Please open an issue at: https://github.com/pytorch/pytorch/issues + with the following information: + + Operation: {name} + Args: {args!r} + Kwargs: {kwargs!r} + + Title your issue: [CuteDSL] Missing operation: {name} + {bar} + """).strip() + raise NotImplementedError(msg) from e diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..156855373852503d2d64754ef8a641a9a1384c77 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py @@ -0,0 +1,939 @@ +# mypy: allow-untyped-defs +""" +CuteDSL-specific operation overrides for pointwise operations. + +This module provides CuteDSL implementations of common operations used in +template kernels, particularly for flex attention modifications. +""" + +import dataclasses +import math +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar + +import sympy + +import torch +from torch._inductor.codegen.common import CSEVariable, OpOverrides +from torch._inductor.ops_handler import ReductionType +from torch._inductor.utils import get_bounds_index_expr +from torch._inductor.virtualized import OpsValue, V +from torch.utils._sympy.functions import Max, Min +from torch.utils._sympy.value_ranges import ValueRanges + + +class CuteDSLCSEVariable(CSEVariable): + def __init__( + self, + name: str, + bounds: ValueRanges[sympy.Expr], + dtype: torch.dtype | None = None, + shape=None, + *, + is_scalar_expr: bool = False, + index_expr: sympy.Expr | None = None, + ): + super().__init__(name, bounds, dtype, shape) + self.is_scalar_expr = is_scalar_expr + self.index_expr = index_expr + + +CuteDSLArg = CSEVariable | str | bool | float | int + + +_CUTEDSL_FAST_MATH: ContextVar[bool] = ContextVar("cutedsl_fast_math", default=False) + + +@contextmanager +def use_cutedsl_fast_math(enabled: bool) -> Iterator[None]: + """Scope whether CuTeDSL math operations request fast-math lowering.""" + token = _CUTEDSL_FAST_MATH.set(enabled) + try: + yield + finally: + _CUTEDSL_FAST_MATH.reset(token) + + +@dataclasses.dataclass(frozen=True) +class TensorSSAReduction: + """Describe the CuTeDSL lowering for one TensorSSA value reduction.""" + + cute_op: str + init_val: str + combine_expr: str + + +TENSORSSA_REDUCTIONS: dict[str, TensorSSAReduction] = { + "sum": TensorSSAReduction("cute.ReductionOp.ADD", "0.0", "lhs + rhs"), + "prod": TensorSSAReduction("cute.ReductionOp.MUL", "1.0", "lhs * rhs"), + "max": TensorSSAReduction( + "cute.ReductionOp.MAX", 'float("-inf")', "cutlass.max(lhs, rhs)" + ), + "min": TensorSSAReduction( + "cute.ReductionOp.MIN", 'float("inf")', "cutlass.min(lhs, rhs)" + ), +} + + +def tensorssa_reduction(reduction_type: ReductionType) -> TensorSSAReduction: + """Return the TensorSSA descriptor for reductions representable by CuTe.""" + reduction = TENSORSSA_REDUCTIONS.get(reduction_type) + if reduction is None: + raise NotImplementedError( + f"{reduction_type} does not map to a CuTe TensorSSA reduction" + ) + return reduction + + +def upcast_compute_type(dtype: torch.dtype) -> torch.dtype: + """Maybe upcast [b]float16 to float32""" + if dtype in (torch.float16, torch.bfloat16): + return torch.float32 + return dtype + + +class CuteDSLOpOverrides(OpOverrides): + """ + CuteDSL-specific operation overrides that generate code using CuteDSL syntax. + + CuteDSL TensorSSA objects have built-in operator overloads (__add__, __mul__, etc.) + and math functions (cute.math.exp, cute.math.sqrt, etc.) + """ + + TORCH_TO_CUTE_DTYPE = { + torch.float16: "cutlass.Float16", + torch.bfloat16: "cutlass.BFloat16", + torch.float32: "cutlass.Float32", + torch.float64: "cutlass.Float64", + torch.int8: "cutlass.Int8", + torch.int16: "cutlass.Int16", + torch.int32: "cutlass.Int32", + torch.int64: "cutlass.Int64", + torch.uint8: "cutlass.Uint8", + torch.uint16: "cutlass.Uint16", + torch.bool: "cutlass.Boolean", + torch.float8_e4m3fn: "cutlass.Float8E4M3FN", + torch.float8_e8m0fnu: "cutlass.Float8E8M0FNU", + torch.float8_e5m2: "cutlass.Float8E5M2", + } + + # Math constants + LOG2_E = 1.4426950408889634 # 1/ln(2) for converting natural exp to base-2 exp + + @staticmethod + def _get_cse_var(arg: CuteDSLArg) -> CSEVariable | None: + """Extract CSEVariable from arg if it's a tensor (either direct or wrapped in OpsValue).""" + if isinstance(arg, CSEVariable): + return arg + if isinstance(arg, OpsValue) and isinstance(arg.value, CSEVariable): + return arg.value + return None + + @staticmethod + def _as_expr(arg: CuteDSLArg) -> str: + cse_var = CuteDSLOpOverrides._get_cse_var(arg) + if cse_var is not None: + return str(cse_var) + return str(arg) + + @staticmethod + def _node_tensor_flags() -> tuple[bool, bool] | None: + node = V.current_node + if not isinstance(node, torch.fx.Node) or len(node.args) < 2: + return None + + def _is_tensor(raw_arg: object) -> bool: + if hasattr(raw_arg, "meta"): + val = raw_arg.meta.get("val") + return isinstance(val, torch.Tensor) and val.ndim > 0 + return False + + return _is_tensor(node.args[0]), _is_tensor(node.args[1]) + + @staticmethod + def _is_scalar_expr(arg: CuteDSLArg) -> bool: + cse_var = CuteDSLOpOverrides._get_cse_var(arg) + return isinstance(cse_var, CuteDSLCSEVariable) and cse_var.is_scalar_expr + + @staticmethod + def _is_tensor_like(arg: CuteDSLArg) -> bool: + cse_var = CuteDSLOpOverrides._get_cse_var(arg) + return cse_var is not None and not CuteDSLOpOverrides._is_scalar_expr(arg) + + @staticmethod + def _index_expr(arg: CuteDSLArg) -> sympy.Expr | None: + cse_var = CuteDSLOpOverrides._get_cse_var(arg) + if isinstance(cse_var, CuteDSLCSEVariable): + return cse_var.index_expr + if isinstance(arg, (int, sympy.Integer)): + return sympy.Integer(arg) + if isinstance(arg, str) and arg.lstrip("-").isdigit(): + return sympy.Integer(int(arg)) + return None + + @staticmethod + def _ensure_tensor_ssa( + arg: CuteDSLArg, + template_tensor: CuteDSLArg, + *, + is_tensor: bool, + dtype: torch.dtype | None = None, + ) -> str: + """ + Convert scalar arguments to TensorSSA using cute.full_like if needed. + + Args: + arg: The argument to check (CSEVariable for tensors, str for scalars, or OpsValue wrapper) + template_tensor: A tensor argument to use as template for full_like + + Returns: + String representation suitable for CuteDSL operations + """ + arg_expr = CuteDSLOpOverrides._as_expr(arg) + if is_tensor: + return arg_expr + template_expr = CuteDSLOpOverrides._as_expr(template_tensor) + if dtype is None: + return f"cute.full_like({template_expr}, {arg_expr})" + cute_dtype = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE[dtype] + return f"cute.full_like({template_expr}, {arg_expr}, {cute_dtype})" + + @staticmethod + def _extract_dtype_and_bounds( + *args: CuteDSLArg, + ) -> tuple[torch.dtype | None, ValueRanges[sympy.Expr]]: + """Extract dtype and bounds from CSEVariable arguments (including OpsValue wrappers).""" + for arg in args: + cse_var = CuteDSLOpOverrides._get_cse_var(arg) + if cse_var is not None: + return cse_var.dtype, cse_var.bounds + return None, ValueRanges.unknown() + + @staticmethod + def _apply_binary_op( + a: CuteDSLArg, + b: CuteDSLArg, + op_format: str, + index_expr_fn=None, + ) -> CuteDSLArg: + """ + Apply a binary operation with automatic scalar-to-tensor conversion. + + CuteDSL requires both operands to be TensorSSA objects for tensor operations. + This helper automatically converts scalar arguments to TensorSSA using + cute.full_like when at least one argument is a tensor (CSEVariable or OpsValue). + + Args: + a: First operand (CSEVariable for tensors, str for scalars, or OpsValue wrapper) + b: Second operand (CSEVariable for tensors, str for scalars, or OpsValue wrapper) + op_format: Format string with {a} and {b} placeholders for the operation + + Returns: + CSEVariable if at least one operand is a tensor, otherwise string + """ + a_cse = CuteDSLOpOverrides._get_cse_var(a) + b_cse = CuteDSLOpOverrides._get_cse_var(b) + + node_flags = CuteDSLOpOverrides._node_tensor_flags() + if node_flags is not None: + a_is_tensor, b_is_tensor = node_flags + a_is_tensor &= not CuteDSLOpOverrides._is_scalar_expr(a) + b_is_tensor &= not CuteDSLOpOverrides._is_scalar_expr(b) + else: + a_is_tensor = CuteDSLOpOverrides._is_tensor_like(a) + b_is_tensor = CuteDSLOpOverrides._is_tensor_like(b) + + tensor_arg = a if a_is_tensor else (b if b_is_tensor else None) + if tensor_arg is None: + tensor_arg = (a_cse if CuteDSLOpOverrides._is_tensor_like(a) else None) or ( + b_cse if CuteDSLOpOverrides._is_tensor_like(b) else None + ) + + if tensor_arg is not None: + if a_cse is None and b_cse is None: + return op_format.format( + a=CuteDSLOpOverrides._as_expr(a), + b=CuteDSLOpOverrides._as_expr(b), + ) + + a_ssa = CuteDSLOpOverrides._ensure_tensor_ssa( + a, tensor_arg, is_tensor=a_is_tensor + ) + b_ssa = CuteDSLOpOverrides._ensure_tensor_ssa( + b, tensor_arg, is_tensor=b_is_tensor + ) + result_expr = op_format.format(a=a_ssa, b=b_ssa) + + dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds(a, b) + expected = CuteDSLOpOverrides._expected_tensor_val() + if dtype is None: + dtype = expected.dtype if expected is not None else torch.int32 + if a_cse is not None: + shape = a_cse.shape + elif b_cse is not None: + shape = b_cse.shape + else: + shape = tuple(expected.size()) if expected is not None else None + + result = V.kernel.cse.generate( + V.kernel.body, result_expr, bounds=bounds, dtype=dtype, shape=shape + ) + if index_expr_fn is not None and isinstance(result, CuteDSLCSEVariable): + a_expr = CuteDSLOpOverrides._index_expr(a) + b_expr = CuteDSLOpOverrides._index_expr(b) + if a_expr is not None and b_expr is not None: + result.index_expr = V.graph.sizevars.simplify( + index_expr_fn(a_expr, b_expr) + ) + return result + + result_expr = op_format.format( + a=CuteDSLOpOverrides._as_expr(a), + b=CuteDSLOpOverrides._as_expr(b), + ) + if a_cse is None and b_cse is None: + return result_expr + + dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds(a, b) + result = V.kernel.cse.generate( + V.kernel.body, + result_expr, + bounds=bounds, + dtype=dtype if dtype is not None else torch.int32, + ) + result.is_scalar_expr = True + if index_expr_fn is not None and isinstance(result, CuteDSLCSEVariable): + a_expr = CuteDSLOpOverrides._index_expr(a) + b_expr = CuteDSLOpOverrides._index_expr(b) + if a_expr is not None and b_expr is not None: + result.index_expr = V.graph.sizevars.simplify( + index_expr_fn(a_expr, b_expr) + ) + return result + + @staticmethod + def _expected_tensor_val() -> torch.Tensor | None: + """Return the fake-tensor value from the current FX node's metadata, if any.""" + node = V.current_node + if not isinstance(node, torch.fx.Node): + return None + val = node.meta.get("val") + return val if isinstance(val, torch.Tensor) else None + + @staticmethod + def _cast_expr(expr: str, dtype: torch.dtype) -> str: + cute_type = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get(dtype) + if cute_type is None: + return expr + return f"{cute_type}({expr})" + + @staticmethod + def _math_call(name: str, *args: str) -> str: + fast_math = ", fastmath=True" if _CUTEDSL_FAST_MATH.get() else "" + return f"cute.math.{name}({', '.join(args)}{fast_math})" + + @staticmethod + def _apply_unary_op( + x: CuteDSLArg, op_format: str, index_expr_fn=None + ) -> CuteDSLArg: + """ + Apply a unary operation, returning CSEVariable if input is a tensor. + + Args: + x: Input operand (CSEVariable for tensors, str for scalars, or OpsValue wrapper) + op_format: Format string with {x} placeholder for the operation + index_expr_fn: Optional sympy builder to propagate index semantics + through the op for lane analysis + + Returns: + CSEVariable if input is a tensor, otherwise string + """ + cse_var = CuteDSLOpOverrides._get_cse_var(x) + if cse_var is not None: + result_expr = op_format.format(x=str(cse_var)) + result = V.kernel.cse.generate( + V.kernel.body, + result_expr, + bounds=cse_var.bounds, + dtype=cse_var.dtype, + shape=cse_var.shape, + ) + if index_expr_fn is not None and isinstance(result, CuteDSLCSEVariable): + x_expr = CuteDSLOpOverrides._index_expr(x) + if x_expr is not None: + result.index_expr = V.graph.sizevars.simplify(index_expr_fn(x_expr)) + if CuteDSLOpOverrides._is_scalar_expr(x): + result.is_scalar_expr = True + return result + + return op_format.format(x=x) + + @staticmethod + def _apply_math_unary_op(x: CuteDSLArg, name: str) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_unary_op( + x, CuteDSLOpOverrides._math_call(name, "{x}") + ) + + @staticmethod + def constant(value: bool | float | int, dtype: torch.dtype) -> str: + """Generate CuteDSL constant representation.""" + if value == float("-inf"): + return "float('-inf')" + elif value == float("inf"): + return "float('inf')" + elif math.isnan(value): + return "float('nan')" + return repr(value) + + @staticmethod + def index_expr(expr: sympy.Expr, dtype: torch.dtype) -> CuteDSLArg: + if isinstance(expr, (int, sympy.Integer)): + return CuteDSLOpOverrides.constant(int(expr), dtype) + + idx_str = V.kernel.kexpr(V.kernel.rename_indexing(expr)) + result = V.kernel.cse.generate( + V.kernel.body, + idx_str, + bounds=get_bounds_index_expr(expr), + dtype=dtype, + ) + result.is_scalar_expr = True + if isinstance(result, CuteDSLCSEVariable): + result.index_expr = V.graph.sizevars.simplify(expr) + return result + + @staticmethod + def value_expr(expr: sympy.Expr, dtype: torch.dtype) -> CuteDSLArg: + # CuteDSL index_expr already emits the requested dtype, so value_expr + # has the same lowering here. + return CuteDSLOpOverrides.index_expr(expr, dtype) + + @staticmethod + def add(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op( + a, b, "({a} + {b})", lambda a_expr, b_expr: a_expr + b_expr + ) + + @staticmethod + def mul(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op( + a, b, "({a} * {b})", lambda a_expr, b_expr: a_expr * b_expr + ) + + @staticmethod + def sub(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op( + a, b, "({a} - {b})", lambda a_expr, b_expr: a_expr - b_expr + ) + + @staticmethod + def truediv(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} / {b})") + + @staticmethod + def floordiv(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op( + a, b, "({a} // {b})", lambda a_expr, b_expr: a_expr // b_expr + ) + + @staticmethod + def mod(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + # Inductor ops.mod is C-style; SymPy/Python % is Python-style for + # negative values, so don't attach index_expr metadata here. + return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} % {b})") + + @staticmethod + def remainder(a, b): + return CuteDSLOpOverrides._apply_binary_op( + a, b, "({a} % {b})", lambda a_expr, b_expr: a_expr % b_expr + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def exp(x: CuteDSLArg) -> CuteDSLArg: + """Exponential using CuteDSL cute.math.exp2 with log2(e) scaling.""" + if CuteDSLOpOverrides._get_cse_var(x) is None: + x = CuteDSLOpOverrides._cast_expr(str(x), torch.float32) + return CuteDSLOpOverrides._apply_unary_op( + x, + CuteDSLOpOverrides._math_call( + "exp2", f"{{x}} * {CuteDSLOpOverrides.LOG2_E}" + ), + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def exp2(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "exp2") + + @staticmethod + # pyrefly: ignore [bad-override] + def sqrt(x: CuteDSLArg) -> CuteDSLArg: + """Square root using CuteDSL cute.math.sqrt function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x, "sqrt") + + @staticmethod + # pyrefly: ignore [bad-override] + def rsqrt(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "rsqrt") + + @staticmethod + # pyrefly: ignore [bad-override] + def log(x: CuteDSLArg) -> CuteDSLArg: + """Natural logarithm using CuteDSL cute.math.log function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x, "log") + + @staticmethod + # pyrefly: ignore [bad-override] + def log2(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "log2") + + @staticmethod + # pyrefly: ignore [bad-override] + def log10(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "log10") + + @staticmethod + # pyrefly: ignore [bad-override] + def cos(x: CuteDSLArg) -> CuteDSLArg: + """Cosine using CuteDSL cute.math.cos function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x, "cos") + + @staticmethod + # pyrefly: ignore [bad-override] + def sin(x: CuteDSLArg) -> CuteDSLArg: + """Sine using CuteDSL cute.math.sin function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x, "sin") + + @staticmethod + # pyrefly: ignore [bad-override] + def tan(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "tan") + + @staticmethod + # pyrefly: ignore [bad-override] + def acos(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "acos") + + @staticmethod + # pyrefly: ignore [bad-override] + def asin(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "asin") + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "atan") + + @staticmethod + # pyrefly: ignore [bad-override] + def atan2(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op( + a, + b, + CuteDSLOpOverrides._math_call("atan2", "{a}", "{b}"), + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def erf(x: CuteDSLArg) -> CuteDSLArg: + """Error function using CuteDSL cute.math.erf function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x, "erf") + + @staticmethod + # pyrefly: ignore [bad-override] + def sigmoid(x: CuteDSLArg) -> CuteDSLArg: + """Sigmoid with fp32 compute and cast-back to expected output dtype.""" + x_cse = CuteDSLOpOverrides._get_cse_var(x) + if x_cse is not None: + x_fp32: CuteDSLArg = CuteDSLOpOverrides.to_dtype( + x_cse, + torch.float32, + use_compute_types=False, + ) + else: + x_fp32 = CuteDSLOpOverrides._cast_expr(str(x), torch.float32) + + exp = CuteDSLOpOverrides._math_call( + "exp2", f"-{{x}} * {CuteDSLOpOverrides.LOG2_E}" + ) + result = CuteDSLOpOverrides._apply_unary_op( + x_fp32, + f"(1.0 / (1.0 + {exp}))", + ) + + expected = CuteDSLOpOverrides._expected_tensor_val() + expected_dtype = expected.dtype if expected is not None else None + if expected_dtype is not None and expected_dtype != torch.float32: + result_cse = CuteDSLOpOverrides._get_cse_var(result) + if result_cse is not None: + return CuteDSLOpOverrides.to_dtype( + result_cse, + expected_dtype, + use_compute_types=False, + ) + return CuteDSLOpOverrides._cast_expr(str(result), expected_dtype) + return result + + @staticmethod + def _minmax(a: CuteDSLArg, b: CuteDSLArg, *, op: str) -> CuteDSLArg: + index_expr_fn = Max if op == ">" else Min + if CuteDSLOpOverrides._is_tensor_like(a) or CuteDSLOpOverrides._is_tensor_like( + b + ): + return CuteDSLOpOverrides._apply_binary_op( + a, + b, + f"cute.where(({{a}}) {op} ({{b}}), {{a}}, {{b}})", + index_expr_fn, + ) + + lhs = CuteDSLOpOverrides._as_expr(a) + rhs = CuteDSLOpOverrides._as_expr(b) + expected = CuteDSLOpOverrides._expected_tensor_val() + if expected is not None: + lhs = CuteDSLOpOverrides._cast_expr(lhs, expected.dtype) + rhs = CuteDSLOpOverrides._cast_expr(rhs, expected.dtype) + result_expr = f"({lhs} if {lhs} {op} {rhs} else {rhs})" + a_cse = CuteDSLOpOverrides._get_cse_var(a) + b_cse = CuteDSLOpOverrides._get_cse_var(b) + if a_cse is None and b_cse is None: + return result_expr + dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds(a, b) + result = V.kernel.cse.generate( + V.kernel.body, + result_expr, + bounds=bounds, + dtype=dtype if dtype is not None else torch.int32, + ) + if isinstance(result, CuteDSLCSEVariable): + a_expr = CuteDSLOpOverrides._index_expr(a) + b_expr = CuteDSLOpOverrides._index_expr(b) + if a_expr is not None and b_expr is not None: + result.index_expr = V.graph.sizevars.simplify( + index_expr_fn(a_expr, b_expr) + ) + result.is_scalar_expr = True + return result + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._minmax(a, b, op=">") + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._minmax(a, b, op="<") + + @staticmethod + # pyrefly: ignore [bad-override] + def where( + condition: CuteDSLArg, + a: CuteDSLArg, + b: CuteDSLArg, + ) -> CuteDSLArg: + """Conditional selection - handles CSEVariable, OpsValue, and string inputs.""" + a_cse = CuteDSLOpOverrides._get_cse_var(a) + b_cse = CuteDSLOpOverrides._get_cse_var(b) + cond_cse = CuteDSLOpOverrides._get_cse_var(condition) + a_is_tensor = CuteDSLOpOverrides._is_tensor_like(a) + b_is_tensor = CuteDSLOpOverrides._is_tensor_like(b) + cond_is_tensor = CuteDSLOpOverrides._is_tensor_like(condition) + tensor_arg = ( + (a_cse if a_is_tensor else None) + or (b_cse if b_is_tensor else None) + or (cond_cse if cond_is_tensor else None) + ) + + if tensor_arg is not None: + a_ssa = CuteDSLOpOverrides._ensure_tensor_ssa( + a, tensor_arg, is_tensor=a_is_tensor + ) + b_ssa = CuteDSLOpOverrides._ensure_tensor_ssa( + b, tensor_arg, is_tensor=b_is_tensor + ) + cond_ssa = CuteDSLOpOverrides._ensure_tensor_ssa( + condition, tensor_arg, is_tensor=cond_is_tensor, dtype=torch.bool + ) + result_expr = f"cute.where({cond_ssa}, {a_ssa}, {b_ssa})" + + dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds( + a, b, condition + ) + + return V.kernel.cse.generate( + V.kernel.body, result_expr, bounds=bounds, dtype=dtype + ) + + result_expr = ( + f"cute.where({CuteDSLOpOverrides._as_expr(condition)}, " + f"{CuteDSLOpOverrides._as_expr(a)}, {CuteDSLOpOverrides._as_expr(b)})" + ) + if a_cse is None and b_cse is None and cond_cse is None: + return result_expr + dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds(a, b, condition) + result = V.kernel.cse.generate( + V.kernel.body, + result_expr, + bounds=bounds, + dtype=dtype if dtype is not None else torch.int32, + ) + result.is_scalar_expr = True + return result + + @staticmethod + def pow(a: CuteDSLArg, b: CuteDSLArg): + return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} ** {b})") + + @staticmethod + # pyrefly: ignore [bad-override] + def floor(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "floor") + + @staticmethod + # pyrefly: ignore [bad-override] + def abs(x: CuteDSLArg) -> CuteDSLArg: + """Absolute value using CuteDSL cute.math.abs function.""" + if isinstance(x, CSEVariable): + x_dtype = x.dtype + elif isinstance(x, OpsValue) and isinstance(x.value, CSEVariable): + x_dtype = x.value.dtype + else: + x_dtype = torch.float32 + + abs_op = ( + "mlir_math.absf" + if x_dtype in (torch.float16, torch.bfloat16, torch.float32) + else "mlir_math.absi" + ) + if CuteDSLOpOverrides._is_tensor_like(x): + return CuteDSLOpOverrides._apply_unary_op( + x, + f"cute.TensorSSA({abs_op}({{x}}), {{x}}.shape, {{x}}.dtype)", + index_expr_fn=sympy.Abs, + ) + return CuteDSLOpOverrides._apply_unary_op( + x, f"{abs_op}({{x}})", index_expr_fn=sympy.Abs + ) + + @staticmethod + def neg(x: CuteDSLArg) -> CuteDSLArg: + """Negation for both TensorSSA and scalar-like expressions.""" + if CuteDSLOpOverrides._is_tensor_like(x): + return CuteDSLOpOverrides._apply_unary_op( + x, + "cute.TensorSSA(-{x}, {x}.shape, {x}.dtype)", + index_expr_fn=lambda expr: -expr, + ) + return CuteDSLOpOverrides._apply_unary_op( + x, "(-{x})", index_expr_fn=lambda expr: -expr + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def inline_asm_elementwise( + *inputs: CuteDSLArg, + asm: str, + constraints: str | None = None, + dtype: torch.dtype = torch.float32, + is_pure: bool = True, + pack: int = 1, + input_dtypes: tuple[torch.dtype, ...] | None = None, + scalar_sources: tuple[bool, ...] | None = None, + ) -> CuteDSLArg: + """Emit an inline PTX block elementwise over a fragment. + + The requested dtype controls the logical result and eventual storage. + E8M0 results may stay decoded as Float32 while fused consumers use them. + """ + if constraints is None: + raise NotImplementedError( + "CuteDSL inline asm requires an explicit constraint list" + ) + result_type = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get(dtype) + if result_type is None: + raise NotImplementedError( + f"CuteDSL inline asm result dtype not supported: {dtype}" + ) + + constraint_parts = [part.strip() for part in constraints.split(",")] + input_constraints = [ + part.lstrip("=&") for part in constraint_parts if not part.startswith("=") + ] + + cast_inputs = list(inputs) + if input_dtypes is not None: + for source_index, (value, input_dtype) in enumerate( + zip(inputs, input_dtypes) + ): + source_constraints = input_constraints[ + source_index * pack : (source_index + 1) * pack + ] + cse_var = CuteDSLOpOverrides._get_cse_var(value) + if ( + source_constraints + and all(constraint == "h" for constraint in source_constraints) + and input_dtype in (torch.float16, torch.bfloat16) + and (cse_var is None or cse_var.dtype != input_dtype) + ): + if cse_var is None: + cast_inputs[source_index] = CuteDSLOpOverrides._cast_expr( + CuteDSLOpOverrides._as_expr(value), input_dtype + ) + else: + cast_inputs[source_index] = CuteDSLOpOverrides.to_dtype( + value, input_dtype, use_compute_types=False + ) + + operands = ", ".join( + str(CuteDSLOpOverrides._as_expr(value)) for value in cast_inputs + ) + if scalar_sources is None: + scalar_sources = (False,) * len(inputs) + elif len(scalar_sources) != len(inputs): + raise ValueError( + f"CuteDSL inline asm received {len(scalar_sources)} scalar-source " + f"flags for {len(inputs)} inputs" + ) + scalar_sources = tuple( + source_is_scalar or CuteDSLOpOverrides._is_scalar_expr(value) + for source_is_scalar, value in zip(scalar_sources, cast_inputs) + ) + expr = ( + f"inline_asm_elementwise_intrinsic({operands}, asm={asm!r}, " + f"constraints={constraints!r}, result_type={result_type}, " + f"is_pure={is_pure!r}, pack={pack!r}, " + f"scalar_sources={scalar_sources!r})" + ) + compute_dtype = torch.float32 if dtype == torch.float8_e8m0fnu else dtype + if not any( + CuteDSLOpOverrides._get_cse_var(value) is not None for value in inputs + ): + return expr + return V.kernel.cse.generate( + V.kernel.body, + expr, + dtype=compute_dtype, + ) + + @staticmethod + def to_dtype( + x: CuteDSLArg, dtype: torch.dtype, src_dtype=None, use_compute_types=True + ) -> CuteDSLArg: + """Type conversion using CuteDSL TensorSSA.to(Type[Numeric]). + + Maps torch dtypes to cutlass.cute.typing numeric types and emits + `{x}.to(cute.typing.)`. + + Raises NotImplementedError for unsigned integer and unsupported dtypes. + """ + if use_compute_types: + dtype = upcast_compute_type(dtype) + + cute_type = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get(dtype) + if cute_type is None: + raise NotImplementedError( + f"CuteDSL dtype cast not implemented for torch dtype: {dtype}" + ) + + if isinstance(x, CSEVariable): + result_expr = f"{str(x)}.to({cute_type})" + result = V.kernel.cse.generate( + V.kernel.body, + result_expr, + bounds=x.bounds, + dtype=dtype, + shape=x.shape, + ) + if CuteDSLOpOverrides._is_scalar_expr(x): + result.is_scalar_expr = True + if ( + dtype in (torch.int32, torch.int64) + and isinstance(result, CuteDSLCSEVariable) + and isinstance(x, CuteDSLCSEVariable) + ): + result.index_expr = x.index_expr + return result + + return f"{x}.to({cute_type})" + + @staticmethod + def tanh(x0: CuteDSLArg) -> CuteDSLArg: + """Hyperbolic tangent using CuteDSL cute.math.tanh function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x0, "tanh") + + # Logical operations + @staticmethod + def logical_and(x0: CuteDSLArg, x1: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x0, x1, "({a} & {b})") + + @staticmethod + def logical_or(x0: CuteDSLArg, x1: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x0, x1, "({a} | {b})") + + @staticmethod + def logical_xor(x0: CuteDSLArg, x1: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x0, x1, "({a} ^ {b})") + + # Bitwise operations (override parent class to properly CSE) + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_and(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} & {b})") + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_or(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} | {b})") + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_xor(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} ^ {b})") + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_not(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_unary_op(x, "(~{x})") + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_left_shift(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} << {b})") + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_right_shift(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} >> {b})") + + @staticmethod + def logical_not(a): + """Logical NOT.""" + return CuteDSLOpOverrides._apply_unary_op(a, "({x} == 0)") + + # Comparison operations + @staticmethod + def eq(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.eq({a}, {b})") + + @staticmethod + def ne(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.ne({a}, {b})") + + @staticmethod + def lt(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.lt({a}, {b})") + + @staticmethod + def le(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.le({a}, {b})") + + @staticmethod + def gt(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.gt({a}, {b})") + + @staticmethod + def ge(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.ge({a}, {b})") diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..cd893bc13c459a9878cd225bf1cd3adec3da1880 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_scheduling.py @@ -0,0 +1,252 @@ +# mypy: allow-untyped-defs +import hashlib +import logging +from collections.abc import Sequence +from typing import cast + +from torch._inductor.utils import Placeholder +from torch.utils._ordered_set import OrderedSet + +from ... import config +from ...codecache import code_hash, get_path +from ...ir import CuteDSLTemplateBuffer +from ...scheduler import ( + BaseSchedulerNode, + BaseScheduling, + FusedSchedulerNode, + SchedulerNode, +) +from ...select_algorithm import PartialRender +from ...utils import get_fused_kernel_name, get_kernel_metadata +from ...virtualized import V +from ..common import BackendFeature, IndentedBuffer + + +log = logging.getLogger(__name__) + + +class CuteDSLScheduling(BaseScheduling): + """ + Scheduling implementation for CuteDSL (CUTLASS Python DSL) kernels. + This class is intended to be used in combination with other schedulers, + and delegated to by CUDACombinedScheduling. + """ + + @classmethod + def get_backend_features(cls, device) -> OrderedSet[BackendFeature]: + return OrderedSet() + + @staticmethod + def is_cutedsl_template(node: BaseSchedulerNode) -> bool: + """Check if a node is a CuteDSL template.""" + return isinstance(node, SchedulerNode) and isinstance( + node.node, CuteDSLTemplateBuffer + ) + + def is_cutedsl_fused_template(self, node: BaseSchedulerNode) -> bool: + """Check if a node is a fused CuteDSL template.""" + return isinstance(node, FusedSchedulerNode) and self.is_cutedsl_template(node) + + def can_fuse_vertical( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + """ + TODO CuteDSL doesn't support vertical fusion yet. + This could be extended in the future for epilogue fusion. + """ + return False + + def can_fuse_horizontal( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + """CuteDSL doesn't support horizontal fusion yet.""" + return False + + def define_kernel( + self, src_code_str: str, node_schedule, precompile_metadata=None + ) -> str: + """Produce the kernel string + Args: + src_code_str: The finalized kernel code string + node_schedule: List of nodes in the schedule + precompile_metadata: Optional dict with shapes/dtypes for subprocess precompilation + + Note: + This is a little weird since async_compile.cutedsl() has to write the string to + a file in order to cute compile it. Feels bad to have two... + """ + wrapper = V.graph.wrapper_code + + # Use the string as the key for caching + if src_code_str in wrapper.src_to_kernel: + kernel_name = wrapper.src_to_kernel[src_code_str] + else: + fused_name = ( + get_fused_kernel_name(node_schedule, config.triton.descriptive_names) + if config.triton.descriptive_names + else "" + ) + + kernel_hash = hashlib.sha256(src_code_str.encode("utf-8")).hexdigest()[:8] + if fused_name == "fused": + kernel_name = f"cutedsl_{kernel_hash}" + else: + kernel_name = f"cutedsl_{fused_name}_{kernel_hash}" + wrapper.src_to_kernel[src_code_str] = kernel_name + src_code_str = src_code_str.replace( + str(Placeholder.KERNEL_NAME), kernel_name + ) + + _, _, kernel_path = get_path(code_hash(src_code_str), "py") + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline(f"async_compile.cutedsl({kernel_name!r}, r'''") + compile_wrapper.splice(src_code_str, strip=True) + if precompile_metadata is not None: + compile_wrapper.writeline( + f"''', precompile_metadata={precompile_metadata!r})" + ) + else: + compile_wrapper.writeline("''')") + + metadata_comment = f"# kernel path: {kernel_path}" + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + metadata_comment += "\n" + origins + "\n" + detailed_origins + wrapper.define_kernel( + kernel_name, compile_wrapper.getvalue(), metadata_comment + ) + return kernel_name + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + ): + """ + Codegen a CuteDSL template. Currently doesn't support fusion. + """ + if not self.is_cutedsl_template(template_node): + raise AssertionError( + "Template node passed to CuteDSLScheduling.codegen_template must be a " + "SchedulerNode that wraps a CuteDSLTemplateBuffer" + ) + # TODO remove when supported + if epilogue_nodes: + raise AssertionError("CuteDSL doesn't support epilogue fusion yet") + if prologue_nodes: + raise AssertionError("CuteDSL doesn't support prologue fusion yet") + + template_node = cast(SchedulerNode, template_node) + ctb: CuteDSLTemplateBuffer = cast(CuteDSLTemplateBuffer, template_node.node) + + kernel, render = ctb.make_kernel_render(ctb) # type: ignore[misc] + template_node.mark_run() + src_code = render() + # Finalize PartialRender if needed + if isinstance(src_code, PartialRender): + src_code_str = src_code.finalize_all() + else: + src_code_str = src_code + + precompile_metadata = self._build_precompile_metadata(kernel, ctb) + + with V.set_kernel_handler(kernel): + node_schedule = [template_node] + kernel_name = self.define_kernel( + src_code_str, node_schedule, precompile_metadata + ) + self.codegen_comment(node_schedule, kernel_name) + kernel.call_kernel(kernel_name, ctb) + V.graph.removed_buffers |= kernel.removed_buffers + self.free_buffers_in_scheduler() + + def _build_precompile_metadata(self, kernel, ctb): + """Extract shapes and dtypes from kernel inputs/output for subprocess precompilation. + + Returns None if shapes are symbolic (dynamic shapes), in which case the + subprocess will skip precompilation and the kernel compiles lazily on first call. + """ + if not hasattr(kernel, "_template_input_args"): + return None + + precompile_shapes = {} + precompile_strides = {} + precompile_dtypes = {} + + try: + for arg_name, input_node in kernel._template_input_args: + template_name = arg_name.removeprefix("arg_") + size = input_node.get_size() + precompile_shapes[template_name] = [int(s) for s in size] + stride = input_node.get_stride() + precompile_strides[template_name] = [int(s) for s in stride] + precompile_dtypes[template_name] = str( + input_node.get_dtype() + ).removeprefix("torch.") + + output_size = ctb.layout.size + precompile_shapes["output"] = [int(s) for s in output_size] + output_stride = ctb.layout.stride + precompile_strides["output"] = [int(s) for s in output_stride] + precompile_dtypes["output"] = str(ctb.layout.dtype).removeprefix("torch.") + except (TypeError, RuntimeError, ValueError): + log.debug( + "Skipping CuteDSL precompile metadata: symbolic sizes cannot be " + "resolved to concrete values" + ) + return None + + device = ctb.layout.device + device_index = device.index if device.index is not None else 0 + + import torch + + device_capability = None + if torch.cuda.is_available(): + device_capability = torch.cuda.get_device_capability(device_index) + + metadata: dict[str, object] = { + "precompile_shapes": precompile_shapes, + "precompile_strides": precompile_strides, + "precompile_dtypes": precompile_dtypes, + "device_index": device_index, + "device_capability": device_capability, + } + + hw_info = self._build_hw_info(kernel) + if hw_info is not None: + metadata["hw_info"] = hw_info + + return metadata + + @staticmethod + def _build_hw_info(kernel) -> tuple[int, int] | None: + """Compute (sm_count, max_active_clusters) in the main process. + + Reads CLUSTER_M/N from kernel template kwargs and queries + HardwareInfo so subprocess workers never touch CUDA driver APIs. + Returns None if CUTLASS is unavailable or the template has no cluster config. + """ + template_kwargs = getattr(kernel, "_template_kwargs", None) + if template_kwargs is None: + return None + + cluster_m = template_kwargs.get("CLUSTER_M") + cluster_n = template_kwargs.get("CLUSTER_N") + if cluster_m is None or cluster_n is None: + return None + + try: + import cutlass.utils + + cluster_product = int(cluster_m) * int(cluster_n) + hw = cutlass.utils.HardwareInfo() + sm_count = hw.get_max_active_clusters(1) + max_active_clusters = hw.get_max_active_clusters(cluster_product) + return (sm_count, max_active_clusters) + except Exception: + log.debug( + "Could not compute hw_info for CuTe DSL precompile", exc_info=True + ) + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_template.py new file mode 100644 index 0000000000000000000000000000000000000000..7a67b05c530b51de66d6e50824cf376c2db3966a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_template.py @@ -0,0 +1,263 @@ +# mypy: allow-untyped-defs +import functools +import itertools +import logging +from collections.abc import Iterable +from typing import Any +from unittest.mock import patch + +from torch._inductor.utils import Placeholder, unique +from torch._inductor.virtualized import V + +from ...autotune_process import CuteDSLBenchmarkRequest, TensorMeta +from ...ir import Buffer, ChoiceCaller, CuteDSLTemplateBuffer, IRNode, Layout, TensorBox +from ..common import KernelTemplate +from .cutedsl_kernel import CuteDSLTemplateKernel + + +log = logging.getLogger(__name__) + + +class CuteDSLTemplate(KernelTemplate): + """Template for generating CuteDSL (CUTLASS Python DSL) kernels. + + Subclasses may override ``caller_type`` to attach template-specific + metadata or precompile behavior while reusing the common render and + benchmark request construction. + """ + + kernel_type: type[Any] = CuteDSLTemplateKernel + caller_type: type[Any] | None = None + index_counter = itertools.count() + all_templates: dict[str, "CuteDSLTemplate"] = {} + + def __init__( + self, + name: str, + source: str, + subgraph_fn: Any | None = None, + mask_fn: Any | None = None, + ) -> None: + super().__init__(name) + self.source = source + self.subgraph_fn = subgraph_fn + self.mask_fn = mask_fn + self.template = CuteDSLTemplate._template_from_string(source) + # A module that registers templates can be initialized more than once in + # a single process (e.g. a double-import path). Tolerate re-registration + # under an existing name as long as the template source matches, but + # reject a genuine name collision between different templates. + existing = self.all_templates.get(name) + if existing is not None and existing.source != self.source: + raise AssertionError(f"duplicate template name, {name}") + CuteDSLTemplate.all_templates[name] = self + + @staticmethod + @functools.lru_cache(None) + # pyrefly: ignore [bad-override] + def _template_from_string(source: str) -> Any: + return KernelTemplate._template_from_string(source) + + def maybe_append_choice( + self, choices: list[Any], **kwargs: Any + ) -> NotImplementedError | None: + """ + Maybe generates a new ChoiceCaller and appends it into existing choices. + Returns None if success, otherwise returns the error. + """ + try: + choices.append(self.generate(**kwargs)) + return None + except NotImplementedError as e: + log.debug("CuteDSL template choice generation failed: %s", e) + return e + except Exception as e: + log.debug("CuteDSL template choice generation error: %s", e) + return NotImplementedError(f"CuteDSL template failed: {e}") + + def generate(self, **kwargs: Any) -> ChoiceCaller: + """Generate the CuteDSL kernel caller for template autotuning.""" + input_nodes = kwargs.pop("input_nodes") + layout = kwargs.pop("layout") + mutated_inputs = kwargs.pop("mutated_inputs", None) + subgraphs = kwargs.pop("subgraphs", None) + template_kwargs = dict(kwargs) + + kernel_name = f"cutedsl_{self.name}_{next(self.index_counter)}" + + if self.template is None: + raise RuntimeError("Template compilation failed (Jinja2 required)") + + self.output_node: Buffer = Buffer(name="buf_out", layout=layout) + # Patch V.graph.get_dtype to handle the fake buf_out buffer + with patch.object( + V.graph, "get_dtype", KernelTemplate._fake_get_dtype(self.output_node) + ): + kernel = self.kernel_type( + kernel_name=kernel_name, + input_nodes=input_nodes, + output_node=self.output_node, + subgraphs=subgraphs, + ) + code = kernel.render(self.template, **kwargs) + + input_call_args = tuple(kernel.args.input_buffers.keys()) + expected_input_args = tuple(unique(x.get_name() for x in input_nodes)) + if input_call_args[: len(expected_input_args)] != expected_input_args: + raise RuntimeError( + "CuteDSL template input registration order changed while " + "collecting captured subgraph buffers. Expected template " + "inputs to be registered before captured buffers, got " + f"{input_call_args}, expected prefix {expected_input_args}." + ) + extra_capture_names = input_call_args[len(expected_input_args) :] + + # Resolve captured nodes from the graph-level side table + # (populated by realize_captures_for_cutedsl) to get view nodes. + graph_captures = getattr(V.graph, "_cutedsl_capture_nodes", {}) + capture_nodes_by_name: dict[str, Any] = {} + extra_capture_nodes = [] + for name in extra_capture_names: + node = graph_captures.get(name) + if node is None: + node = V.graph.get_buffer(name) + capture_nodes_by_name[name] = node + extra_capture_nodes.append(node) + input_nodes = list(input_nodes) + extra_capture_nodes + + kernel.set_capture_input_nodes(capture_nodes_by_name) + with kernel._patch_get_dtype_for_captures(): + _, call_args, _, _ = kernel.args.python_argdefs() + expected_args = list(input_call_args) + expected_args.append(self.output_node.get_name()) + if list(call_args)[: len(expected_args)] != expected_args: + raise RuntimeError( + "CuteDSL template benchmark argument order changed while " + "collecting dynamic scalar args. Expected prefix " + f"{expected_args}, got {list(call_args)}." + ) + extra_args = tuple( + V.graph.sizevars.optimization_hints(call_args[len(expected_args) :]) + ) + + bmreq = CuteDSLBenchmarkRequest( + kernel_name=kernel_name, + input_tensor_meta=TensorMeta.from_irnodes(input_nodes), + output_tensor_meta=TensorMeta.from_irnodes(self.output_node), + extra_args=extra_args, + source_code=code, + ) + + def make_kernel_render(out_node, hint_override: int | None = None): + """ + Factory function that creates a kernel renderer for the final output. + + This closure captures the current template and parameters, but allows + the output node to be specified later. This is used during the final + kernel selection phase when the actual output buffer is available. + """ + render_kernel = self.kernel_type( + kernel_name=str(Placeholder.KERNEL_NAME), + input_nodes=input_nodes, + output_node=out_node, + subgraphs=subgraphs, + ) + render_kernel.set_capture_input_nodes(capture_nodes_by_name) + + def render(): + return render_kernel.render(self.template, **kwargs) + + return render_kernel, render + + caller_type = self.caller_type or CuteDSLTemplateCaller + return caller_type( + name=kernel_name, + input_nodes=input_nodes, + layout=layout, + make_kernel_render=make_kernel_render, + bmreq=bmreq, + template=self, + mutated_inputs=mutated_inputs, + template_kwargs=template_kwargs, + ) + + +class CuteDSLTemplateCaller(ChoiceCaller): + """Caller for CuteDSL templates that integrates with the autotuning system.""" + + def __init__( + self, + name: str, + input_nodes: list[Buffer], + layout: Layout, + make_kernel_render: Any, + bmreq: CuteDSLBenchmarkRequest, + template: "CuteDSLTemplate", + mutated_inputs: Iterable[IRNode] | None = None, + template_kwargs: dict[str, Any] | None = None, + ): + description = self._build_description(name, template_kwargs) + super().__init__( + name=name, + input_nodes=input_nodes, + layout=layout, + description=description, + ) + self.make_kernel_render = make_kernel_render + self.bmreq = bmreq + self.template = template + self.mutated_inputs = mutated_inputs + + def _build_description( + self, name: str, template_kwargs: dict[str, Any] | None + ) -> str: + if not template_kwargs: + return f"CuteDSL template {name}" + kwargs_desc = ", ".join(f"{k}={v}" for k, v in template_kwargs.items()) + return f"CuteDSL template {name} ({kwargs_desc})" + + def __str__(self) -> str: + return f"CuteDSLTemplateCaller({self.name})" + + def benchmark(self, *args, out) -> float: + """Benchmark the kernel execution.""" + return self.bmreq.benchmark(*args, out=out) + + def output_node(self) -> TensorBox: + """Create the output node for this template choice.""" + buffer = CuteDSLTemplateBuffer( + layout=self.layout, + inputs=self.input_nodes, + make_kernel_render=self.make_kernel_render, + template=self.template, + mutated_inputs=self.mutated_inputs, + ) + # Pass KTC annotation to the buffer for encoding + if "ktc" in self.annotations: + buffer.annotations["ktc"] = self.annotations["ktc"] + return TensorBox.create(buffer) + + def call_name(self) -> str: + """Return the kernel call name.""" + return self.name + + def to_callable(self) -> Any: + """Return callable that can execute this kernel.""" + return self.make_kernel_render + + def hash_key(self) -> str: + """Return unique hash key for this choice.""" + return "-".join( + [ + self.name.rsplit("_", 1)[0], + self.bmreq.module_cache_key, + ] + ) + + def info_dict(self) -> dict[str, Any]: + """Return information about this kernel.""" + return { + "name": self.name, + "backend": "CuteDSL", + "template": self.template.name, + } diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/lane_analysis.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/lane_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..42ca1b50b0f2e40770ac399b5a2218fdab7a25b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/lane_analysis.py @@ -0,0 +1,140 @@ +# mypy: allow-untyped-defs + +import dataclasses + +import sympy + +from torch.utils._ordered_set import OrderedSet + +from ...virtualized import V + + +@dataclasses.dataclass(frozen=True, slots=True) +class LaneExprInfo: + """How an index expression changes across vectorized lanes. + + A lane is one element of a vectorized CuteDSL computation. For a 32-lane + mask/load, lane 0 is the first element in the group and lane 31 is the last. + + Attributes: + is_uniform: All lanes evaluate to the same value, e.g. for flex-flash``b_idx``. + is_contiguous: Lanes evaluate to consecutive aligned values for the + requested width, e.g. ``kv_idx + lane`` when lane 0 is aligned. + contiguous_width: Largest aligned contiguous power-of-two width proven, + or None if no vector-width contiguity is proven. + """ + + is_uniform: bool + is_contiguous: bool + contiguous_width: int | None + + +def classify_lane_expr( + expr: sympy.Expr, + lane_var: sympy.Symbol, + *, + max_width: int, + uniform_symbols: OrderedSet[sympy.Symbol] | None = None, +) -> LaneExprInfo: + """Classify how ``expr`` varies across ``lane_var`` vector lanes. + + ``max_width`` is the requested vector width. We start with this as the + maximum width to check and then decrease in powers of two trying to find a width + that satisfies contiguity across lanes. We cap since we are trying to get vectorized loads + which are at 128 and 256(B200) bits so no need to check higher. + + For example a ``lane_var = kv_idx`` and ``max_width = 8``: + + - No dependency on lane var: ``q_idx`` returns + ``LaneExprInfo(is_uniform=True, is_contiguous=False, contiguous_width=None)``. + - ``kv_idx`` at an 8-aligned group start returns + ``LaneExprInfo(is_uniform=False, is_contiguous=True, contiguous_width=8)``. + - ``kv_idx + 4`` at a 4-aligned but not 8-aligned group start returns + ``LaneExprInfo(is_uniform=False, is_contiguous=False, contiguous_width=4)``. + - ``kv_idx * 2`` returns + ``LaneExprInfo(is_uniform=False, is_contiguous=False, contiguous_width=None)``. + """ + if max_width <= 1: + return LaneExprInfo(True, False, None) + + semantic_expr = V.graph.sizevars.simplify(expr) + if uniform_symbols is not None and semantic_expr.free_symbols <= uniform_symbols: + return LaneExprInfo(True, False, None) + + lane_contiguity = V.graph.sizevars.analyze_lane_contiguity(semantic_expr, lane_var) + contiguous_width = aligned_contiguous_width( + semantic_expr, + lane_var, + max_width=max_width, + lane_contiguity=lane_contiguity, + ) + return LaneExprInfo( + is_uniform=lane_contiguity.is_uniform_for(max_width), + is_contiguous=lane_contiguity.stride == 1 and contiguous_width == max_width, + contiguous_width=contiguous_width, + ) + + +def aligned_contiguous_width( + expr: sympy.Expr, + lane_var: sympy.Symbol, + *, + max_width: int, + lane_contiguity=None, +) -> int | None: + """Return the largest aligned power-of-two contiguous lane width.""" + if not (max_width >= 2 and max_width.bit_count() == 1): + raise AssertionError(f"max_width must be a power of two >= 2, got {max_width}") + if lane_contiguity is None: + lane_contiguity = V.graph.sizevars.analyze_lane_contiguity(expr, lane_var) + start_expr = lane_group_start(expr, lane_var) + width = max_width + while width >= 2: + if ( + lane_contiguity.is_contiguous_for(width) + and V.graph.sizevars.statically_known_multiple_of(start_expr, width) + and V.graph.sizevars.statically_known_geq(start_expr, 0) + ): + return width + width //= 2 + return None + + +def lane_group_start(expr: sympy.Expr, lane_var: sympy.Symbol) -> sympy.Expr: + """Return the lane-group base value by evaluating ``expr`` at lane 0. + + For example, if ``expr = base + lane_var``, this returns ``base``. This is + useful when checking vector-load alignment: a contiguous lane expression is only + safe to vectorize when the first lane's address is sufficiently aligned. + """ + return V.graph.sizevars.simplify(expr.xreplace({lane_var: sympy.Integer(0)})) + + +def decompose_affine_lane_expr( + expr: sympy.Expr, lane_var: sympy.Symbol +) -> tuple[sympy.Expr, sympy.Expr] | None: + """Return ``(stride, base)`` when ``expr`` is affine in ``lane_var``. + + The result satisfies ``expr == stride * lane_var + base``, where neither + ``stride`` nor ``base`` depends on ``lane_var``. + For example: ``stride == 0`` means lane-uniform, ``stride == 1`` means + consecutive lanes access consecutive indices, and other strides are + non-contiguous gathers. + + Examples with ``lane_var = i``: + ``b + i`` -> ``(1, b)`` + ``b + 2 * i`` -> ``(2, b)`` + ``b`` -> ``(0, b)`` + + Returns ``None`` for non-affine expressions or when the extracted stride or + base still depends on ``lane_var``. + """ + expr = V.graph.sizevars.simplify(expr) + lane_coeff = expr.coeff(lane_var) + rest = lane_group_start(expr, lane_var) + if lane_var in lane_coeff.free_symbols or lane_var in rest.free_symbols: + return None + residual = V.graph.sizevars.simplify(expr - (lane_coeff * lane_var + rest)) + if residual != 0: + return None + return lane_coeff, rest diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fec1e0e4617a9663675b339cc9cd71f494da6967 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7d7122b9261334d69db50b0d081b3984507dcdf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/gemm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/gemm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b40acdfe153be1e30838c014a00120ac6108d84 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/gemm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e0bf60ebcf2a8c9ac26d1b0badf8d2536f5d164 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/python_evt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/python_evt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d09124185ddab2813cd355db285b7fb841b0cf6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/python_evt.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9da1e8d2a6943cb57c7afd3b9293aea5877facd0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/serialization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/serialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..479a1ea45c1e73299e1fccc9e5d265b5e1635e3a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/serialization.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5bae7ec3e8cac717aafc58287af981d04c805bb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bc84c936503f94bb2fc0c6f6a866484afd70b5c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..18fc758392e54e3cee0220d8915cc3a8a8a87e63 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/cache.py @@ -0,0 +1,123 @@ +# mypy: allow-untyped-defs +import functools +import hashlib +import inspect +import json +import logging +import os +import time +from typing import Any + +import torch._inductor.config as config +from torch._inductor.codecache import cutlass_key +from torch._inductor.codegen.cutlass import serialization, utils +from torch._inductor.codegen.cutlass.serialization import ( + get_cutlass_operation_serializer, +) +from torch._inductor.runtime.cache_dir_utils import cache_dir +from torch._inductor.utils import clear_on_fresh_cache + + +log = logging.getLogger(__name__) + + +CONFIG_PREFIX: str = "configs" + + +def get_config_request_key( + arch: str, + toolkit_version: str, + instantiation_level: str, +) -> str: + """ + Return a key for the full ops, based on cutlass key, arch, toolkit version, instantiation level, and serialization.py file hash. + """ + + # Get hash of serialization.py and cutlass_utils.py files using their module file paths + def get_file_hash(file_module): + file_path = inspect.getfile(file_module) + with open(file_path, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + serialization_hash = get_file_hash(serialization) + cutlass_utils_hash = get_file_hash(utils) + + hash_target = "-".join( + [ + cutlass_key().hex(), + arch, + toolkit_version, + instantiation_level, + serialization_hash, + cutlass_utils_hash, + ] + ) + return hashlib.sha256(hash_target.encode("utf-8")).hexdigest()[0:8] + + +def _generate_config_filename(request_key: str) -> str: + """ + Generate a filename for the full ops. + """ + return f"{CONFIG_PREFIX}_{request_key}.json" + + +@clear_on_fresh_cache +@functools.cache +def maybe_fetch_ops(device_type: str) -> list[Any] | None: + """ + Fetch ops from databases. + """ + if config.force_disable_caches: + return None + + # setup + arch: str = utils.cutlass_arch(device_type) + version: str = utils.toolkit_version(device_type) + if device_type == "cuda": + # get_cuda_version might return "12.4.0" or "12.4" + # but we want to use "12.4" + version = ".".join(version.split(".")[:2]) + instantiation_level: str = config.cutlass.cutlass_instantiation_level + + # filename and filepath + request_key: str = get_config_request_key(arch, version, instantiation_level) + filename: str = _generate_config_filename(request_key) + filepath: str = os.path.join(cache_dir(), filename) + + # try fetch + serialized_ops: list[str] | None = None + start_time = time.time() + if os.path.isfile(filepath): + # locally + try: + with open(filepath) as f: + serialized_ops = json.load(f) + + if not isinstance(serialized_ops, list): + raise AssertionError( + f"Expected serialized ops is a list, got {type(serialized_ops)}" + ) + except Exception: + log.warning( + "Failed to load CUTLASS config %s from local cache", + filename, + exc_info=True, + ) + serialized_ops = None + elif config.is_fbcode(): + from torch._inductor.fb.cutlass_remote_cache import ( + maybe_fetch_cutlass_configs_from_remote, + ) + + # from remote + serialized_ops = maybe_fetch_cutlass_configs_from_remote(filepath) + + if serialized_ops is None: + return None + + # deserialize + serializer = get_cutlass_operation_serializer() + full_ops = [serializer.deserialize(x) for x in serialized_ops] # type: ignore[union-attr] + log.info("Loaded ops from %s cache in %.3fs", filename, time.time() - start_time) + return full_ops diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/gemm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/gemm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..6ebc194b041a2a419a9770a2e8c2cc85c7edf216 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/gemm_template.py @@ -0,0 +1,2157 @@ +# mypy: allow-untyped-defs +import copy +import enum +import functools +import logging +import re +import time +from abc import ABC, abstractmethod +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._dynamo.utils import counters +from torch._inductor.autotune_process import TensorMeta +from torch._inductor.codegen.cutlass.cache import maybe_fetch_ops +from torch._inductor.codegen.wrapper import PythonWrapperCodegen +from torch._inductor.runtime.runtime_utils import dynamo_timed +from torch._inductor.scheduler import BaseSchedulerNode +from torch._inductor.select_algorithm import create_inputs_key +from torch._inductor.utils import clear_on_fresh_cache + +from ... import ir +from ...config import cutlass as inductor_cutlass_config +from ...ir import ( + Buffer, + ChoiceCaller, + CUTLASSTemplateBuffer, + FixedLayout, + FlexibleLayout, + IRNode, + Layout, + ReinterpretView, +) +from ...utils import is_dynamic, Placeholder, sympy_product +from ...virtualized import V +from ..common import IndentedBuffer +from ..cuda import cuda_env +from . import utils as cutlass_utils +from .kernel import CUTLASSTemplateKernel +from .python_evt import CutlassEVTCodegen, scaled_mm_evt +from .template import CUTLASSTemplate +from .utils import ( + ACCUMULATOR_DTYPES, + dtype_match, + torch_dtype_to_cutlass_type, + XW_DTYPES, +) + + +GemmOperation = Any +EVTArgRenames = Any + +log = logging.getLogger(__name__) + +# Jinja template for GEMM Kernel, used by the CUTLASSGemm3xTemplate class below. +GEMM_TEMPLATE_CUTLASS_3X = r""" +{{template.header().getvalue()}} +{{template.globals().getvalue()}} +{{epilogue_visitor_tree}} +{{instance_definition}} +// When workspace_size is not a nullptr, populates requested workspace_size and returns. +// Otherwise, computes the Gemm kernel using the given workspace ptr. +extern "C" { +PT_EXPORT {{kernel_call_signature}} { + try { + using ElementComputeEpilogue = {{instance_type}}::ElementAccumulator; + using coord_t = cutlass::gemm::GemmCoord::Index; + static cutlass::KernelHardwareInfo hw_info; + if (hw_info.sm_count == 0) { + hw_info.sm_count = cutlass::KernelHardwareInfo::query_device_multiprocessor_count(0); + CUTLASS_TRACE_HOST("Query result for SM count per device: " << hw_info.sm_count); + } + {{dynamic_cluster}} + {{instance_type}}::Arguments arguments; + {{template.render_gemm_arguments(argument_template, epilogue_template, should_swap_xw, + X, W, Bias, Y, alpha, beta, kernel, epilogue_args)}} + {{instance_type}} gemm_op; + if (workspace_size) { + *workspace_size = gemm_op.get_workspace_size(arguments); + return 0; + } + // check for null pointers after workspace size, since querying workspace size doesn't require valid data pointers +#ifndef CUTLASS_BACKEND_DISABLE_CHECKS + { + auto status = gemm_op.can_implement(arguments); + CUTLASS_CHECK(status); + } +#endif +#ifdef CUTLASS_DEBUG_TRACE_LEVEL +#if CUTLASS_DEBUG_TRACE_LEVEL == 1 + { + // Print the maximum number of active blocks per SM for the kernel if CUTLASS_DEBUG_TRACE_LEVEL == 1 + // we don't need a print statement, it's happening inside the function. + gemm_op.maximum_active_blocks(); + } +#endif +#endif + { + auto status = gemm_op.initialize(arguments, workspace, stream); + CUTLASS_CHECK(status); + } + { + auto status = gemm_op(stream); + CUTLASS_CHECK(status); + } + } + catch (std::exception& e) { + std::cerr << "Runtime error: " << e.what() << std::endl; + return -1; + } + catch (...) { + return -1; + } + return 0; +} +} + +// configuration name: {{op_conf_name}} +""" + +# Jinja template for Cutlass 3.x GEMM Kernel arguments, used by the CUTLASSGemmTemplate class below. +GEMM_ARGS_CUTLASS_3X = r""" + // Initialize GemmUniversal3xInstance arguments. + arguments = { + {{template.gemm_mode()}}, // GemmUniversalMode mode + { + static_cast({{M}}), + static_cast({{N}}), + static_cast(K), + static_cast(B) + }, // ProblemShape problem_shape + { + {{template.cutlass_type_cast(X, kernel.ptr(X))}}, // ElementA const* ptr_A + { + {{template.cute_int(kernel.stride(X, -2), "stride_x0")}}, + {{template.cute_int(kernel.stride(X, -1), "stride_x1")}}, + {{template.cute_int(kernel.batch_stride(X), "batch_stride_x")}} + }, // StrideA dA + {{template.cutlass_type_cast(W, kernel.ptr(W))}}, // ElementB const* ptr_B + { + {{template.cute_int(kernel.stride(W, -1), "stride_w1")}}, + {{template.cute_int(kernel.stride(W, -2), "stride_w0")}}, + {{template.cute_int(kernel.batch_stride(W), "batch_stride_w")}} + }, // StrideB dB + }, // MainloopArguments mainloop + {{epilogue_arguments}}, + hw_info + }; + arguments.scheduler.max_swizzle_size = swizzle; +""" + +# Jinja template for Cutlass 3.x GEMM Kernel arguments if epilogue fusion is applied, +# used by the CUTLASSGemmTemplate class below. +GEMM_ARGS_CUTLASS_3X_EPILOGUE = r""" + // see https://tinyurl.com/4rk89z48 + { + {{epilogue_args}}, // thread, typename FusionCallbacks::Arguments ( EVT ) or ThreadEpilogueOp::Params (non-EVT ) + {{template.cutlass_type_cast(Bias, kernel.ptr(Bias))}}, // ElementC const* ptr_C + { + {{template.cute_int(kernel.stride(Bias, -2, 1), "stride_bias0")}}, + {{template.cute_int(kernel.stride(Bias, -1, 1), "stride_bias1")}}, + {{template.cute_int(kernel.batch_stride(Bias), "batch_stride_bias")}} + }, // StrideC dC + {{template.cutlass_type_cast(Y, kernel.ptr(Y))}}, // ElementD const* ptr_D + { + {{template.cute_int(kernel.stride(Y, -2), "stride_y0")}}, + {{template.cute_int(kernel.stride(Y, -1), "stride_y1")}}, + {{template.cute_int(kernel.batch_stride(Y), "batch_stride_y")}} + }, // StrideD dD + }, // EpilogueArguments epilogue +""" + +# Jinja template for GEMM Kernel, used by the CUTLASS2xGemmTemplate class below. +GEMM_TEMPLATE_CUTLASS_2X = r""" +{{template.header().getvalue()}} +{{template.globals().getvalue()}} +{{instance_definition}} +// When workspace_size is not a nullptr, populates requested workspace_size and returns. +// Otherwise, computes the Gemm kernel using the given workspace ptr. +extern "C" { +PT_EXPORT {{kernel_call_signature}} { + try { + int B = {{kernel.size(Y, 0, -3, default_value=1)}}; + using ElementComputeEpilogue = {{instance_type}}::ElementAccumulator; + using coord_t = cutlass::gemm::GemmCoord::Index; + static cutlass::KernelHardwareInfo hw_info; + if (hw_info.sm_count == 0) { + hw_info.sm_count = cutlass::KernelHardwareInfo::query_device_multiprocessor_count(0); + CUTLASS_TRACE_HOST("Query result for SM count per device: " << hw_info.sm_count); + } + {{instance_type}}::Arguments arguments; + {{template.render_gemm_arguments(instance_type, argument_template, epilogue_template, should_swap_xw, + X, W, Bias, Meta, Y, alpha, beta, kernel, epilogue_args)}} + {{instance_type}} gemm_op; + if (workspace_size) { + *workspace_size = gemm_op.get_workspace_size(arguments); + return 0; + } + + // check for null pointers after workspace size, since querying workspace size doesn't require valid data pointers +#ifndef CUTLASS_BACKEND_DISABLE_CHECKS + { + auto status = gemm_op.can_implement(arguments); + CUTLASS_CHECK(status); + } +#endif +#ifdef CUTLASS_DEBUG_TRACE_LEVEL +#if CUTLASS_DEBUG_TRACE_LEVEL == 1 + { + // Print the maximum number of active blocks per SM for the kernel if CUTLASS_DEBUG_TRACE_LEVEL == 1 + // we don't need a print statement, it's happening inside the function. + gemm_op.maximum_active_blocks(); + } +#endif +#endif + + { + auto status = gemm_op.initialize(arguments, workspace, stream); + CUTLASS_CHECK(status); + } + { + auto status = gemm_op(stream); + CUTLASS_CHECK(status); + } + } + catch (std::exception& e) { + std::cerr << "Runtime error: " << e.what() << std::endl; + return -1; + } + catch (...) { + return -1; + } + return 0; +} +} +""" + +# Jinja template for Cutlass 2.x GEMM Kernel arguments, used by the CUTLASS2xGemmTemplate class below. +GEMM_ARGS_CUTLASS_2X = r""" + int64_t batch_stride_x = {{kernel.stride(X, -3)}}; + int64_t row_stride_x = {{kernel.row_or_column_stride(X)}}; + int64_t batch_stride_w = {{kernel.stride(W, -3)}}; + int64_t row_stride_w = {{kernel.row_or_column_stride(W)}}; + int64_t batch_stride_bias = {{kernel.stride(Bias, -3)}}; + int64_t row_stride_bias = {{kernel.row_or_column_stride(Bias)}}; + int64_t batch_stride_y = {{kernel.stride(Y, -3)}}; + int64_t row_stride_y = {{kernel.row_or_column_stride(Y)}}; + // Initialize GemmUniversalInstance arguments. + arguments = { + {{template.gemm_mode()}}, // GemmUniversalMode mode + { + static_cast(M), + static_cast(N), + static_cast(K) + }, // GemmCoord problem_size + {{split_k if split_k > 1 else 'B'}}, // int batch_count + {ElementComputeEpilogue({{alpha}}), ElementComputeEpilogue({{beta}})}, // typename EpilogueOutputOp::Params epilogue + {{template.cutlass_type_cast(X, kernel.ptr(X))}}, // void const * ptr_A + {{template.cutlass_type_cast(W, kernel.ptr(W))}}, // void const * ptr_B + {{template.cutlass_type_cast(Bias, kernel.ptr(Bias))}}, // void const * ptr_C + {{template.cutlass_type_cast(Y, kernel.ptr(Y))}}, // void * ptr_D + batch_stride_x, // int64_t batch_stride_A + batch_stride_w, // int64_t batch_stride_B + batch_stride_bias, // int64_t batch_stride_C + batch_stride_y, // int64_t batch_stride_D + row_stride_x, // typename LayoutA::Stride::LongIndex lda + row_stride_w, // typename LayoutB::Stride::LongIndex ldb + row_stride_bias, // typename LayoutC::Stride::LongIndex ldc + row_stride_y, // typename LayoutC::Stride::LongIndex ldd + }; +""" + +GEMM_ARGS_SPARSE_CUTLASS_2X = r""" + using TensorRefA = cutlass::TensorRef<{{instance_type}}::ElementA, + {{instance_type}}::LayoutA>; + using TensorRefB = cutlass::TensorRef<{{instance_type}}::ElementB, + {{instance_type}}::LayoutB>; + using TensorRefC = cutlass::TensorRef<{{instance_type}}::ElementC, + {{instance_type}}::LayoutC>; + using TensorRefE = cutlass::TensorRef<{{instance_type}}::ElementE, + {{instance_type}}::LayoutE>; + // Note that "X" and "W" names may be misleading here. Namely, for + // sparse GEMM, the first argument is always sparse, while typically + // weight matrix, implied by name "W" will be sparse in + // applications. Thus, just remember that here: "X" refers to first + // argument, that is sparse, and "W" to second, that is dense. + TensorRefA X_ref({{template.cutlass_type_cast(X, kernel.ptr(X))}}, {{kernel.row_or_column_stride(X)}}); + TensorRefB W_ref({{template.cutlass_type_cast(W, kernel.ptr(W))}}, {{kernel.row_or_column_stride(W)}}); + TensorRefC Y_ref({{template.cutlass_type_cast(Y, kernel.ptr(Y))}}, {{kernel.row_or_column_stride(Y)}}); + TensorRefE Meta_ref({{template.cutlass_sparse_meta_type_cast(Meta, kernel.ptr(Meta))}}, + TensorRefE::Layout::packed({ {{kernel.size(Meta, 0)}}, {{kernel.size(Meta, 1)}} })); + // Initialize GemmSparse arguments. + arguments = { + { + static_cast(M), + static_cast(N), + static_cast(2 * K), + }, // GemmCoord problem_size + X_ref, // TensorRef ref_A + W_ref, // TensorRef ref_B + Y_ref, // TensorRef ref_C + Y_ref, // TensorRef ref_D + Meta_ref, // TensorRef ref_E + {ElementComputeEpilogue({{alpha}}), ElementComputeEpilogue({{beta}})}, // typename EpilogueOutputOp::Params epilogue, + }; +""" + +# Additional includes which are necessary if the standalone test / debug runner is generated as well +GEMM_STANDALONE_RUNNER_ADDITIONAL_INCLUDES = r""" +#ifdef GENERATE_STANDALONE_RUNNER +#include "cutlass/util/distribution.h" +#include "cutlass/util/host_tensor.h" +#include "cutlass/util/packed_stride.hpp" +#include "cutlass/util/tensor_view_io.h" +#include "cutlass/util/reference/device/gemm_complex.h" +#include "cutlass/util/reference/device/tensor_compare.h" +#include "cutlass/util/reference/device/tensor_fill.h" +#include +#endif +""" + +# Jinja template for the standalone runner that may be generated as part of the code. +GEMM_STANDALONE_RUNNER_TEMPLATE = r""" +#ifdef GENERATE_STANDALONE_RUNNER +/// Helper to initialize a block of device data +template +bool initialize_block( + cutlass::DeviceAllocation& block, + uint64_t seed, float max=1.0, float min=-1.0) { + if (block.size()<=0) return false; + Element scope_max(static_cast(max)), scope_min(static_cast(min)); + cutlass::reference::device::BlockFillRandomUniform( + (Element*)block.get(), block.size(), seed, scope_max, scope_min); + + return true; +} + +{% if Meta is defined and Meta is not none %} +template +bool initialize_block_meta( + cutlass::DeviceAllocation& block, + uint64_t seed) { + if (block.size()<=0) return false; + cutlass::reference::device::BlockFillRandomSparseMeta( + (Element*)block.get(), block.size(), seed, {{instance_type}}::kMetaSizeInBits); + return true; +} +{% endif %} + +extern "C" int run_standalone(uint64_t seed, int repetitions) { + std::cout << "Starting GEMM Standalone test run with seed " << seed << std::endl; + size_t workspace_size = 0; + size_t* workspace_size_ptr = &workspace_size; + + int M = {{kernel.get_layout_args()[0]}}; + int N = {{kernel.get_layout_args()[1]}}; + int K = {{kernel.get_layout_args()[2]}}; + int B = {{kernel.get_layout_args()[3]}}; + int lda = {{kernel.get_layout_args()[4]}}; + int ldb = {{kernel.get_layout_args()[5]}}; + int ldc = {{kernel.get_layout_args()[6]}}; + int ldd = {{kernel.get_layout_args()[7]}}; + uint8_t swizzle = {{kernel.runtime_arg_values[0]}}; + + using ElementA = {{kernel.cutlass_dtype(X)}}; + using ElementB = {{kernel.cutlass_dtype(W)}}; + using ElementC = {{kernel.cutlass_dtype(Bias, default_dtype='uint8_t')}}; // may not be void + using ElementD = {{kernel.cutlass_dtype(Y)}}; + {% if Meta is defined and Meta is not none %} + using ElementE = {{kernel.cutlass_dtype(Meta)}}; + {% endif %} + + cutlass::DeviceAllocation X_data({{kernel.max_valid_index(X)+1}}); + initialize_block(X_data, seed++); + cutlass::DeviceAllocation W_data({{kernel.max_valid_index(W)+1}}); + initialize_block(W_data, seed++); + cutlass::DeviceAllocation Bias_data({{kernel.max_valid_index(Bias)+1}}); + initialize_block(Bias_data, seed++); + cutlass::DeviceAllocation Y_data({{kernel.max_valid_index(Y)+1}}); + {% if Meta is defined and Meta is not none %} + cutlass::DeviceAllocation Meta_data({{kernel.max_valid_index(Meta)+1}}); + initialize_block_meta(Meta_data, seed++); + {% endif %} + + cutlass::DeviceAllocation workspace_data; + // Call once with workspace_size_ptr set to get workspace size + + std::cout << "Calling once to get workspace size" << std::endl; + {{test_call_statement}}; + // Allocate workspace if necessary + if (workspace_size > 0) { + workspace_data.reset(workspace_size); + std::cout << "Allocated workspace size of " << workspace_size << " bytes" << std::endl; + } + std::cout << "Calling Kernel as {{test_call_statement}};" << std::endl; + workspace_size_ptr = nullptr; + for (int i=0; i None: + """ + Args: + input_nodes (List[Buffer]): List of input nodes of the GEMM kernel. + layout (Layout): Layout type of the resulting output node. + alpha (float): The scaling factor for the product of the inputs in the GEMM operation. + beta (float): The scaling factor applied to the output matrix. + input_reorder (Optional[List[int]]): Specifies the reordering of the input nodes. If not provided, + no reordering is performed. Defaults to None. + use_fast_accum (Optional[bool]): enable/disable tensor-core fast accumulation (only available in `CUTLASS3xGemmTemplate` and Hopper GPUs) + """ + super().__init__( + str(Placeholder.KERNEL_NAME), input_nodes, layout, input_reorder + ) + self.alpha = alpha + self.beta = beta + self.use_fast_accum = use_fast_accum + if not (2 <= len(input_nodes) <= 5): + raise AssertionError(f"expected 2 to 5 input nodes, got {len(input_nodes)}") + if not self._are_inputs_layout_compatible( + [node.get_layout() for node in input_nodes] + ): + raise AssertionError("input nodes have incompatible layouts") + + self.cache_key: str = create_inputs_key(self.input_nodes) + + @staticmethod + @abstractmethod + def add_cutlass_gemm_choices( + choices: list[ChoiceCaller], + layout: ir.Layout, + input_nodes: list[Buffer], + alpha: float | int = 1, + beta: float | int = 0, + input_reorder: list[int] | None = None, + use_fast_accum: bool | None = None, + **extra_kwargs, + ) -> None: + raise NotImplementedError + + @staticmethod + @abstractmethod + def _get_supported_ops() -> "list[cutlass_library.gemm_operation.GemmOperation]": # type: ignore[name-defined] # noqa: F821 + raise NotImplementedError + + @staticmethod + @abstractmethod + def _has_tma_epilogue(self) -> bool: + raise NotImplementedError + + @abstractmethod + def _get_template(self) -> str: + raise NotImplementedError + + @abstractmethod + def _get_template_args( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> tuple[str, str | None]: + raise NotImplementedError + + @abstractmethod + def _are_inputs_layout_compatible(self, layouts: list[Layout]) -> bool: + raise NotImplementedError + + @abstractmethod + def _shape_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + raise NotImplementedError + + @abstractmethod + def _alignment_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + raise NotImplementedError + + @abstractmethod + def _set_bias_layout_and_alignment( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + raise NotImplementedError + + @abstractmethod + def _define_gemm_instance( + self, + op: GemmOperation, + evt_name: str | None = None, + ) -> tuple[str, str]: + raise NotImplementedError + + @abstractmethod + def _get_extra_inputs_and_names( + self, + op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821 + ) -> tuple[Buffer | None, list[Buffer | None], list[str]]: + raise NotImplementedError + + @abstractmethod + def _update_arg_names_for_test_call_statement( + self, + arg_names: list[str], + input_nodes: list[Buffer], + ) -> list[str]: + raise NotImplementedError + + def _add_cutlass_gemm_choices( + self, + choices: list[ChoiceCaller], + layout: ir.Layout, + input_nodes: list[Buffer], + alpha: float | int = 1, + beta: float | int = 0, + input_reorder: list[int] | None = None, + **extra_kwargs, + ) -> None: + """ + Adds Cutlass GEMM configurations choices to the auto-tuning list. + + This function mutates the passed list of choices by appending the choices for Cutlass GEMM configs to it. + + Args: + choices (list): The list to which choices are appended. + layout (ir.Layout): The layout configuration. + input_nodes (list): The list of input nodes. + alpha (float,int): Scaling factor, defaults to 1. + beta (float,int): Offset, defaults to 0. + input_reorder (list, optional): Order of the inputs, defaults to None. + **extra_kwargs: Additional keyword arguments. + + """ + + ops = self.gen_ops() + + # pre-computation + layout_repr: str = str(layout) + input_tensor_meta: TensorMeta | list[TensorMeta] = TensorMeta.from_irnodes( + self.input_nodes + ) + # When input_reorder is set (e.g. [2, 0, 1] for addmm), the kernel + # function signature is reordered (e.g. from [X, W, Bias] to + # [Bias, X, W]). input_tensor_meta must follow the same order + # because subprocess benchmarking creates tensors from this metadata + # and passes them positionally to the compiled kernel. Without this + # reorder the kernel receives mismatched pointers/strides, causing + # out-of-bounds GPU memory access for large shapes. + if self.input_reorder is not None and isinstance(input_tensor_meta, list): + input_tensor_meta = [input_tensor_meta[idx] for idx in self.input_reorder] + output_tensor_meta: TensorMeta | list[TensorMeta] = TensorMeta.from_irnodes( + self.output_node + ) + + with dynamo_timed("CUTLASSGemmTemplate.maybe_append_choice"): + device_config = self._device_cutlass_config + for name, op in ops: + for swizzle in device_config.cutlass_max_profiling_swizzle_options: + description = f"{name} swizzle={swizzle}" + self.maybe_append_choice( + choices, + op=op, + name=name, + description=description, + input_key=self.cache_key, + layout_repr=layout_repr, + input_tensor_meta=input_tensor_meta, + output_tensor_meta=output_tensor_meta, + swizzle=swizzle, + ) + + if len(ops) == 0: + log.info( + "No suitable Cutlass GEMM configs found, fallbacks used " + "( len(ops)=%d, output_layout=%s, input_layouts=%s, input_strides=%s )", + len(ops), + layout, + [node.get_layout() for node in input_nodes], + [node.get_stride() for node in input_nodes], + ) + log.debug( + "Added %d Cutlass gemm configs.", + len(ops), + ) + + def header(self) -> IndentedBuffer: + """ + Returns a buffer containing CUDA C++ code for the header section of the CUTLASS GEMM template. + This section primarily includes the necessary header files. + + Returns: + IndentedBuffer: An instance of IndentedBuffer that contains the generated CUDA C++ header code. + """ + res = super().header() + res.splice( + """ + #include "cutlass/gemm/gemm.h" + #include "cutlass/gemm/device/gemm_universal.h" + #include "cutlass/gemm/device/gemm_universal_adapter.h" + #include "cutlass/gemm/kernel/gemm_universal.hpp" + #include "cutlass/gemm/collective/collective_builder.hpp" + #include "cutlass/epilogue/collective/collective_builder.hpp" + #include "cutlass/epilogue/collective/default_epilogue.hpp" + #include "cutlass/epilogue/thread/linear_combination.h" + #include "cutlass/epilogue/thread/activation.h" + #include "cutlass/gemm/dispatch_policy.hpp" + #include "cutlass/gemm/kernel/tile_scheduler.hpp" + #include "cutlass/tensor_ref.h" + #include "cutlass/util/distribution.h" + #include "cutlass/util/packed_stride.hpp" + #include "cutlass/util/tensor_view_io.h" + """ + ) + if self.device_type != "xpu": + # XPU SYCL-TLA does not support sparse gemm yet + res.splice( + """ + #include "cutlass/gemm/device/gemm_sparse.h" + """ + ) + if inductor_cutlass_config.generate_test_runner and not is_dynamic( + *self.input_nodes, self.output_node + ): + res.splice(GEMM_STANDALONE_RUNNER_ADDITIONAL_INCLUDES) + return res + + @staticmethod + def cutlass_layout(torch_layout: ir.Layout) -> "cutlass_lib.LayoutType | None": # type: ignore[name-defined] # noqa: F821 + """ + Converts an ir.Layout instance into the corresponding cutlass_library.LayoutType enum value + (RowMajor, ColumnMajor, or None if no matching value is found ). + + Args: + torch_layout (ir.Layout): The layout that needs to be looked up. + + Returns: + cutlass_lib.LayoutType: The converted layout corresponding to the `torch_layout` or None if no matching + value is found. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.library as cutlass_lib + + if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1): + return cutlass_lib.LayoutType.RowMajor + elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-2], 1): + return cutlass_lib.LayoutType.ColumnMajor + else: + return None + + @staticmethod + def flip_cutlass_layout( + cutlass_layout: "cutlass_lib.LayoutType", # type: ignore[name-defined] # noqa: F821 + ) -> "cutlass_lib.LayoutType": # type: ignore[name-defined] # noqa: F821 + """Helper method: Flips a given cutlass layout (cutlass_lib.LayoutType) from RowMajor + to ColumnMajor or vice versa""" + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.library as cutlass_lib + + if cutlass_layout == cutlass_lib.LayoutType.RowMajor: + return cutlass_lib.LayoutType.ColumnMajor + else: + return cutlass_lib.LayoutType.RowMajor + + @staticmethod + @functools.lru_cache(32) + def layout_match( + torch_layout: ir.Layout, + cutlass_layout: "cutlass_lib.LayoutType", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + """Helper Method: Determines whether a given torch layout matches a given Cutlass layout""" + return CUTLASSGemmTemplate.cutlass_layout(torch_layout) == cutlass_layout + + @staticmethod + def set_layout(tensor_desc: "TensorDescription", torch_layout: ir.Layout) -> None: # type: ignore[name-defined] # noqa: F821 + """ + Helper method: Sets the layout of a given tensor description to match the given torch layout + """ + if CUTLASSGemmTemplate.layout_match(torch_layout, tensor_desc.layout): + return + tensor_desc.layout = CUTLASSGemmTemplate.cutlass_layout(torch_layout) + + @staticmethod + def set_alignment(torch_layout, op_element) -> bool: + """ + Helper method to update the alignment of a given CUTLASS GEMM op operand's element. + + This method modifies the alignment of the given Cutlass GEMM op operand's element to match the + layout of the corresponding ir.Buffer node. + + Args: + torch_layout: The layout of the corresponding ir.Buffer node. + op_element: The Cutlass GEMM op operand's element whose alignment is to be updated. + + Returns: + bool: True if the alignment was successfully updated, False otherwise. + """ + alignment = cutlass_utils.get_max_alignment(torch_layout) + if torch.cuda.is_available(): + cuda_arch = cuda_env.get_cuda_arch() + cuda_arch = cutlass_utils._normalize_cuda_arch(cuda_arch) + if cuda_arch and int(cuda_arch) >= 90 and alignment < op_element.alignment: + return False + + op_element.alignment = alignment + return True + + @staticmethod + def should_swap_XW( + bias: IRNode, + ) -> bool: + """ + Helper method to determine whether we should do an explicit transpose by switching the order of the + matmul operands. This might be necessary when we can't otherwise arrive at the right memory + layout for the given Bias operand. + + Note: This method is a workaround for CUDA Errors that seemingly non-deterministically + occurred in practice in some CUTLASS GEMM Kernels with Linear epilogues that have a bias term. + it might make sense to check on newer Cutlass releases whether it makes sense to keep + returning True in certain cases or whether it becomes unnecessary. + """ + # If bias is row major, swap all M and N dimensions + if ( + bias is not None + and len(bias.get_stride()) >= 2 + and bias.get_stride()[-1] in (0, 1) + ): + log.debug("GEMM Layout swapped X and W -> explicit transpose") + return True + return False + + @staticmethod + def swap_XW( + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> "cutlass_library.gemm_op.GemmOperation": # type: ignore[name-defined] # noqa: F821 + """ + Swap operands X and W (aka operands A and B) of the GEMM operation. This + requires transposing the operands, which is done by swapping the strides. + Note that we don't change the apparent external layout, just the operand layout. + this is intentional. + """ + new_op = copy.deepcopy(op) + new_op.A.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.A.layout) + new_op.B.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.B.layout) + new_op.A, new_op.B = new_op.B, new_op.A + new_op.C.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.C.layout) + new_op.D.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.D.layout) + return new_op + + def fix_op_layout( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + X: Buffer, + W: Buffer, + Bias: Buffer | None, + Y: Buffer | ReinterpretView, + ) -> "cutlass_library.gemm_op.GemmOperation": # type: ignore[name-defined] # noqa: F821 + # This is a workaround to deal with cases where the input layouts have changed + # between autotuning and rendering. This happens if the inputs layout + # are FlexibleLayout instances. In this case, we need to update the + # op's input layouts. It is a hack, because now the op + # we benchmarked is not the same as the op we render, + # but there is no simple way to fix this in the autotuner, since that would + # potentially disable other optimizations. + a_layout = X.get_layout() + b_layout = W.get_layout() + c_layout = Bias.get_layout() if Bias is not None else None + + d_layout = copy.deepcopy(Y.get_layout()) + match_list = [ + CUTLASSGemmTemplate.layout_match(buf.get_layout(), op_layout) + for buf, op_layout in zip( + (X, W, Bias, Y), + (op.A.layout, op.B.layout, op.C.layout, op.D.layout), + ) + if buf is not None + ] + all_match = all(match_list) + if all_match: + return op + log.warning( + f"Cutlass GEMM Layout change: Input and/or output layouts have changed between autotuning/retuning and call to render on {self}. Applying workaround. This can lead to suboptimal performance. Match List: {match_list}" # noqa: G004 + ) + new_op = copy.deepcopy(op) + + if a_layout is not None: + new_op.A.layout = CUTLASSGemmTemplate.cutlass_layout(a_layout) + if b_layout is not None: + new_op.B.layout = CUTLASSGemmTemplate.cutlass_layout(b_layout) + if c_layout is not None: + new_op.C.layout = CUTLASSGemmTemplate.cutlass_layout(c_layout) + new_op.C.element = cutlass_utils.torch_dtype_to_cutlass_type(c_layout.dtype) + if d_layout is not None: + new_op.D.layout = CUTLASSGemmTemplate.cutlass_layout(d_layout) + return new_op + + def _dtype_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + """ + Checking dtypes of A, B, acc, D here. + + Empirically speaking, CUTLASS2x ops have same dtype for C and D. + """ + X = self.input_nodes[0] + W = self.input_nodes[1] + + accumulator_torch_dtype = cutlass_utils.get_accumulator_dtype( + [X.get_dtype(), W.get_dtype()], + ) + if not ( + cutlass_utils.dtype_match(X.get_dtype(), op.A.element) + and cutlass_utils.dtype_match(W.get_dtype(), op.B.element) + and cutlass_utils.dtype_match( + self.output_node.get_layout().dtype, op.D.element + ) + and cutlass_utils.dtype_match( + accumulator_torch_dtype, op.accumulator_type() + ) + ): + return False + + return True + + @classmethod + def global_filter_ops( + cls, + ops: list["cutlass_library.gemm_op.GemmOperation"], # type: ignore[name-defined] # noqa: F821 + ) -> list["cutlass_library.gemm_op.GemmOperation"]: # type: ignore[name-defined] # noqa: F821 + """ + Filter ops without using information about the torch op, input nodes and output node. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.library as cutlass_lib # type: ignore[import] + + # Skip simt kernels + ops = [ + op + for op in ops + if op.tile_description.math_instruction.opcode_class + != cutlass_lib.OpcodeClass.Simt + ] + + # only keep the set of row x column ops + # for other layout, we modify in place in filter_op, after deepcopy + ops = [ + op + for op in ops + if op.A.layout.name == "RowMajor" and op.B.layout.name == "ColumnMajor" + ] + + # filter by supported accumulator types + ops = [ + op + for op in ops + if any( + dtype_match(torch_dtype, op.accumulator_type()) + for torch_dtype in ACCUMULATOR_DTYPES + ) + ] + + # check if dtypes of A and B are supported + ops = [ + op + for op in ops + if any(dtype_match(torch_dtype, op.A.element) for torch_dtype in XW_DTYPES) + and any(dtype_match(torch_dtype, op.B.element) for torch_dtype in XW_DTYPES) + ] + + return ops + + def filter_op( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> "cutlass_library.gemm_op.GemmOperation": # type: ignore[name-defined] # noqa: F821 + """ + Helper method: + + Determines whether a given Cutlass GEMM op definition is suitable for the current + input / output of the operation that this template is supposed to implement. + + Takes memory layout, dtype and support for EVT operations into account, + and filters potentially problematic ops. + + Returns None if the op is not suitable, otherwise returns the op to be used, which might + have been mutated. + """ + + if op.gemm_kind not in self._get_supported_ops(): + return None + + X = self.input_nodes[0] + W = self.input_nodes[1] + + # Filter ops according to the shape match. + if not self._shape_match(op): + return None + + # Filter ops by dtypes. + if not self._dtype_match(op): + return None + + # Filter ops by alignment. + if not self._alignment_match(op): + log.debug( + "Skipping due to alignment mismatch. op: %s", op.configuration_name() + ) + return None + + # only use stream k for static shape + if op.tile_scheduler.name == "StreamK": + static_shape = PythonWrapperCodegen.statically_known_list_of_ints_or_none( + tuple(X.get_size()) + tuple(W.get_size()) + ) + if not static_shape: + return None + + # Update op. + op = copy.deepcopy(op) + + # set layouts for X and W + self.set_layout(op.A, X.get_layout()) + self.set_layout(op.B, W.get_layout()) + + # Set output layout. + op.D.layout = CUTLASSGemmTemplate.cutlass_layout(self.output_node.get_layout()) + + # Filter ops by alignments and set alignments. + status = ( + self.set_alignment(X.get_layout(), op.A) + and self.set_alignment(W.get_layout(), op.B) + and self.set_alignment(self.output_node.get_layout(), op.D) + ) + if not status: + log.debug( + "Skipping due to alignment setting failure. op: %s", + op.configuration_name(), + ) + return None + + if inductor_cutlass_config.cutlass_tma_only and not self._has_tma_epilogue(op): + return None + + # Set epilogue. + # TODO: update epilogue functor according to epilogues. + op.element_epilogue = op.accumulator_type() + + if ( + self.use_fast_accum is not None + and int(cutlass_utils._normalize_cuda_arch(cuda_env.get_cuda_arch())) == 90 + ): + is_op_fast_accum = "fastaccum" in op.configuration_name() + if self.use_fast_accum ^ is_op_fast_accum: + return None + + # Set bias layout and alignment. + status = self._set_bias_layout_and_alignment(op) + if not status: + log.debug( + "Skipping due to bias layout and alignment setting failure. op: %s", + op.configuration_name(), + ) + return None + + # Apply regex filters at the end when configuration name doesn't change anymore + if inductor_cutlass_config.cutlass_op_allowlist_regex: + if not re.search( + inductor_cutlass_config.cutlass_op_allowlist_regex, + op.configuration_name(), + ): + return None + if inductor_cutlass_config.cutlass_op_denylist_regex is not None: + if re.search( + inductor_cutlass_config.cutlass_op_denylist_regex, + op.configuration_name(), + ): + return None + + # `_procedural_name` is decorated with @functools.cached_property in cutlass, and its value is + # cached based on the key `self`. After we modify some attributes of + # `self` (e.g., layout or alignment), the `self` itself doesn’t change, so the + # cached value remains stale. We therefore need to clear the cached value so that + # `_procedural_name` can be recomputed with the updated attributes. + del op._procedural_name + return op + + def gen_ops(self) -> "list[tuple[str, cutlass_gemm_op.GemmOperation]]": # type: ignore[name-defined] # noqa: F821 + """ + Creates a list of Cutlass GemmOperation instances that match the operation this template is designed to represent. + The matching is carried out with respect to the input and output specifications of the operation. + + No function arguments. + + Returns: + List[tuple[str, cutlass_gemm_op.GemmOperation]]: A list of (cutlass_name, GemmOperation) + tuples that are compatible with the operation requirements of this template. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.gemm_operation as cutlass_gemm_op + + if self.cache_key in self.filtered_ops_cache: + log.debug("Using cached ops for %s", self.cache_key) + return self.filtered_ops_cache[self.cache_key] + + counters["inductor"]["cutlass_filtered_ops_cache_miss"] += 1 + + with dynamo_timed("CUTLASSGemmTemplate.maybe_fetch_ops"): + maybe_ops = maybe_fetch_ops(self.device_type) + if maybe_ops is None: + log.debug("Cannot fetch ops from cache, generating ops from scratch") + full_ops = cutlass_utils.gen_ops(self.device_type) + ops = pytree.tree_flatten(full_ops)[0] + else: + log.debug("Using cached ops from cache") + ops = maybe_ops + + ops = self.global_filter_ops(ops) + + res: dict[str, cutlass_gemm_op.GemmOperation] = {} + start_time = time.time() + for op in ops: + # if changed, need to also change CUTLASS_OPERATION_KIND + if not isinstance(op, cutlass_gemm_op.GemmOperation): + raise AssertionError(f"expected GemmOperation, got {type(op).__name__}") + filter_res = self.filter_op(op) + if ( + filter_res is not None + and res.get(filter_res.configuration_name()) is None + ): + res[filter_res.configuration_name()] = filter_res + log.info( + "Got cutlass configs: total number of ops: %d. Filtering took %.2f seconds", + len(res), + time.time() - start_time, + ) + sorted_res = sorted(res.items()) + device_config = self._device_cutlass_config + ret_res = sorted_res[: device_config.cutlass_max_profiling_configs] + if len(self.filtered_ops_cache) < 50: + self.filtered_ops_cache[self.cache_key] = ret_res + else: + log.debug("Not caching ops since filtered_ops_cache has reached size 50.") + return ret_res + + def gemm_mode(self) -> str: + """ + Returns a Cutlass GEMM mode string for the current operation, dependent on whether this op implements + a batched GEMM or a simple GEMM without batch dimension. + + Returns: + str: A string indicating the Cutlass GEMM mode. If the output node has more than two dimensions, + "cutlass::gemm::GemmUniversalMode::kBatched" is returned, otherwise + "cutlass::gemm::GemmUniversalMode::kGemm" is returned. + """ + sizes = self.output_node.get_size() + if len(sizes) > 2: + return "cutlass::gemm::GemmUniversalMode::kBatched" + else: + return "cutlass::gemm::GemmUniversalMode::kGemm" + + def _dynamic_cluster_block(self, op: "cutlass_gemm_op.GemmOperation") -> str: # type: ignore[name-defined] # noqa: F821 + """ + Temporary workaround for CUTLASS GEMMs that encode cluster shape as runtime values. + + For dynamic-cluster kernels, CUTLASS expects `KernelHardwareInfo.cluster_shape` and + `KernelHardwareInfo.cluster_shape_fallback` to be populated with valid runtime values. + Today we provide a single global preferred/fallback pair (configurable via env), + which is sufficient for correctness but is not performance-optimal. + + Note: This is intentionally minimal because this code path is transitional. Cluster-shape + selection should ultimately be handled in the CuTe/DSL implementation rather than + investing heavily in the legacy CUTLASS template pipeline. + """ + shape = getattr(getattr(op, "tile_description", None), "cluster_shape", None) + if not shape or len(shape) < 2 or (shape[0] > 0 and shape[1] > 0): + return "" + + preferred = inductor_cutlass_config.cutlass_dynamic_cluster_shape + fallback = inductor_cutlass_config.cutlass_dynamic_cluster_fallback + + cluster_k = shape[2] if len(shape) > 2 and shape[2] > 0 else preferred[2] + preferred = (preferred[0], preferred[1], cluster_k) + fallback_k = fallback[2] if len(fallback) > 2 and fallback[2] > 0 else cluster_k + fallback = (fallback[0], fallback[1], fallback_k) + + return ( + f" hw_info.cluster_shape = {{{preferred[0]}, {preferred[1]}, {preferred[2]}}};\n" + f" hw_info.cluster_shape_fallback = {{{fallback[0]}, {fallback[1]}, {fallback[2]}}};" + ) + + def render( # type: ignore[override] + self, + kernel: CUTLASSTemplateKernel, + op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821 + template_buffer_node: CUTLASSTemplateBuffer | None = None, + epilogue_nodes: list[BaseSchedulerNode] | None = None, + **kwargs, + ) -> str: + """ + The primary entry point for the code rendering process used in this template. + Renders the Cutlass based CUDA/XPU C++ code for the GEMM Kernel that this template is designed to implement, + including potentially fused epilogues. + + Args: + kernel (CUTLASSTemplateKernel): The kernel to be rendered. + op (cutlass_gemm_op.GemmOperation, optional): A GEMM operation that is required to be compatible with the + input and output definitions as well as a possible epilogue. Defaults to None. + **kwargs: Additional keyword arguments. Currently unused. + + Returns: + str: Cutlass based CUDA/XPU C++ code fragment as a string, to be used by the current + CUTLASSTemplateKernel or autotuning code. + + Note: + All inputs and their corresponding buffer addresses and names take precedence over previously + passed inputs to the template at construction time. However, they should be layout compatible. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.gemm_operation as cutlass_gemm_op + import cutlass_library.library as cutlass_lib + + if not isinstance(op, cutlass_gemm_op.GemmOperation): + raise AssertionError( + "op argument is required and has to be an instance of GemmOperation" + ) + + if epilogue_nodes: + if self.device_type == "cuda" and not self._has_tma_epilogue(op): + raise NotImplementedError( + "Non-TMA epilogue visitor tree is not supported in NV-Cutlass." + ) + + if not (len(self.input_nodes) >= 2 and self.output_node is not None): + raise AssertionError( + "expected at least 2 input nodes and a non-None output node" + ) + X, W = self.input_nodes[0], self.input_nodes[1] + for input_node in self.input_nodes: + if not isinstance(X.layout, FixedLayout): + input_node.freeze_layout() + + Y = self.output_node + if template_buffer_node is not None: + Y = template_buffer_node + + Bias, extra_inputs, extra_names = self._get_extra_inputs_and_names(op) + + # Define Kernel call signature + # Important: This step also populates Kernel name to node mapping data structures, + # which are required further below ( for example by the template renderer ) + inputs = [X, W, Bias, *extra_inputs] + names = ["X", "W", "Bias", *extra_names] + ["Y"] + names_str = ",".join(names) + if self.input_reorder is not None: + input_reorder = self.input_reorder + else: + input_reorder = None + + # The layouts might have changed between autotuning and this call if they were FlexibleLayout + # we need to adapt, which might lead to suboptimal performance. + op = self.fix_op_layout(op, X, W, Bias, Y) + + # to make op mutable without affecting others + op = copy.deepcopy(op) + is_scaled_mm = len(self.input_nodes) in (4, 5) + if Bias is not None and not is_scaled_mm: + if Bias.get_dtype() != X.get_dtype(): + raise AssertionError( + f"expected Bias dtype {X.get_dtype()}, got {Bias.get_dtype()}" + ) + # This might have been set to void during filtering, when the assumption was still that there's no C + # operand + op.C.element = op.A.element + + if op.C.element != op.D.element: + raise AssertionError( + f"Expect C and D to have the same dtype, found {op.C.element} and {op.D.element}" + ) + + argument_template, epilogue_template = self._get_template_args(op) + should_swap_xw: bool = False + if Bias is not None and self._has_tma_epilogue(op): + if ( + op.epilogue_schedule + != cutlass_lib.EpilogueScheduleType.EpilogueTransposed + and self.should_swap_XW(Bias) + ): + # TMA epilogue requires bias vector in column major to get best perf. + op = self.swap_XW(op) + should_swap_xw = True + + name_to_buffer = {node.get_name(): node for node in self.input_nodes} + # handle the fake output buffer during lowering + name_to_buffer[Y.get_name()] = Y # type: ignore[assignment] + + if epilogue_nodes or is_scaled_mm: + if epilogue_nodes: + ( + input_names, + output_names, + var_name_to_buffer_name, + evt_py_code, + ) = CutlassEVTCodegen.ir_to_evt_python_code( + Y.get_name(), epilogue_nodes, V.kernel.removed_buffers + ) + + # TODO: mlazos remove this by returning buffer metadata from + # ir_to_evt_python code + for name, buf in ( + V.graph.name_to_buffer | V.graph.graph_inputs + ).items(): + if name not in name_to_buffer: + name_to_buffer[name] = buf # type: ignore[assignment] + + D_output_name = var_name_to_buffer_name["D"] + D_output_buffer = name_to_buffer[D_output_name] + Y = D_output_buffer # type: ignore[assignment] + # Interestingly, I don't think the rest of the layout matters here since we + # use the properties of the Y buffer to fill in D's properties in the epilogue + # args. This is needed though because it defines types expected in the epilogue args. + op.D.element = cutlass_utils.torch_dtype_to_cutlass_type( + D_output_buffer.get_dtype() + ) + + # When the D output buffer has a compatible reshape of the template + # output (e.g., [16, 512, 3072] vs [8192, 3072]), use the template's + # layout for EVT since CUTLASS operates on the 2D GEMM output shape. + if ( + template_buffer_node is not None + and D_output_buffer.get_size() != template_buffer_node.get_size() + ): + name_to_buffer[D_output_name] = template_buffer_node + + # Apply the same normalization to external read inputs. EVT + # propagates shapes against the 2D (M, N) accumulator, so a + # higher-rank read with the same number of elements (e.g. a bias + # whose shape is a compatible reshape of the GEMM output) must be + # viewed as the 2D template shape. This is only valid for + # contiguous reads, where the row-major flatten is + # memory-equivalent and thus numerically identical. + if template_buffer_node is not None: + template_size = list(template_buffer_node.get_size()) + for name in input_names: + buf = name_to_buffer[name] + buf_layout = buf.get_layout() + if ( + list(buf.get_size()) != template_size + and buf_layout.is_contiguous() + and V.graph.sizevars.statically_known_equals( + sympy_product(buf.get_size()), + sympy_product(template_size), + ) + ): + new_layout = FixedLayout( + buf_layout.device, + buf_layout.dtype, + template_size, + FlexibleLayout.contiguous_strides(template_size), + ) + name_to_buffer[name] = ReinterpretView( # type: ignore[assignment] # pyrefly: ignore[unsupported-operation] + data=buf, layout=new_layout + ) + + if not output_names: + raise AssertionError("There should be at least one write") + + epilogue_inputs = [name_to_buffer[name] for name in input_names] + # Use D_output_buffer directly for the D output entry in outputs, + # not name_to_buffer[D_output_name] which may have been replaced + # with template_buffer_node for EVT layout purposes. + outputs = [ + D_output_buffer if name == D_output_name else name_to_buffer[name] + for name in output_names + ] + else: # Scaled MM, we read the two scale matrices (and optional bias) and write a single output + bias = None if len(self.input_nodes) < 5 else self.input_nodes[4] + bias_name = bias.get_name() if bias else None + + ( + evt_read_names, + var_name_to_buffer_name, + evt_py_code, + ) = scaled_mm_evt( + self.input_nodes[2].get_name(), # scale_A + self.input_nodes[3].get_name(), # scale_B + bias_name, + Y.get_name(), + ) + + input_names = list(evt_read_names) + output_names = [] # We only need Y + epilogue_inputs = [self.input_nodes[2], self.input_nodes[3]] + if bias: + epilogue_inputs.append(bias) + outputs = [] + + acc_dtype = cutlass_utils.get_accumulator_dtype( + [X.get_dtype(), W.get_dtype()] + ) + if not acc_dtype: + raise AssertionError("Could not determine accumulator dtype") + + evt_name, evt_args, evt_code, evt_arg_renames = self._render_evt( + op, + evt_py_code, + var_name_to_buffer_name, + name_to_buffer, + Y.get_dtype(), + acc_dtype, + ) + + inputs = [ + X, + W, + Bias, + *epilogue_inputs, # type: ignore[list-item] + Y, + *extra_inputs, + ] + # Extend input_reorder to cover epilogue inputs, Y, and extra_inputs + # at their natural positions (identity mapping for new entries) + if input_reorder is not None: + base_len = len(input_reorder) + if not (base_len <= len(inputs)): + raise AssertionError( + "input_reorder must be a prefix mapping for the current input list" + ) + num_new = len(inputs) - base_len + if num_new > 0: + input_reorder = input_reorder + list( + range(base_len, base_len + num_new) + ) + input_names = [evt_arg_renames.get(name) for name in input_names] + output_names = [evt_arg_renames.get(name) for name in output_names] + + names_str = ",".join( + ["X", "W", "Bias", *input_names, "Y", *output_names, *extra_names] + ) + else: + evt_name = None + outputs = [Y] + evt_args = f"{{ElementComputeEpilogue({self.alpha}), ElementComputeEpilogue({self.beta})}}" + evt_code = "" + + kernel_call_signature = kernel.def_kernel( + inputs=inputs, # type: ignore[arg-type] + outputs=outputs, # type: ignore[arg-type] + names_str=names_str, + input_reorder=input_reorder, + ) + + test_call_statement = self.test_call_statement(kernel, inputs, names_str) + + instance_definition, instance_type = self._define_gemm_instance(op, evt_name) + dynamic_cluster = self._dynamic_cluster_block(op) + + options = { + "alpha": self.alpha, + "beta": self.beta, + "X": X, + "W": W, + "Y": Y, + "kernel_call_signature": kernel_call_signature, + "Bias": Bias, + "epilogue_template": epilogue_template, + "argument_template": argument_template, + "should_swap_xw": should_swap_xw, + "template": self, + "kernel": kernel, + "instance_definition": instance_definition, + "instance_type": instance_type, + "input_reorder": self.input_reorder, + "epilogue_args": evt_args, + "test_call_statement": test_call_statement, + "op_conf_name": op.configuration_name(), + "epilogue_visitor_tree": evt_code, + "dynamic_cluster": dynamic_cluster, + } + options.update(dict(zip(extra_names, extra_inputs))) + res = self._template_from_string(self._get_template()).render(**options) + if inductor_cutlass_config.generate_test_runner and not is_dynamic( + X, W, Y, Bias + ): + test_runner_code = self._template_from_string( + GEMM_STANDALONE_RUNNER_TEMPLATE + ).render(**options) + res += "\n\n" + test_runner_code + + # splice to remove trailing spaces in each line + buf = IndentedBuffer() + buf.splice(res) + return buf.getvalue() + + def test_call_statement( + self, + kernel, + input_nodes, + names_str: str = "", + ) -> str: + """ + Helper method to render the Cutlass CUDA/XPU C++ code required for calling the GEMM operation in the standalone + test runner that might also be generated along with the rest of the code, if the corresponding config is + enabled. + + Returns a C++ statement that calls the GEMM operation with the correct arguments. + """ + _, __, arg_types = kernel.args.cpp_argdefs(cutlass_utils.DTYPE_TO_CUTLASS_TYPE) + arg_names = [name.strip() for name in names_str.strip().split(",")] + arg_names = self._update_arg_names_for_test_call_statement( + arg_names, input_nodes + ) + arguments = [ + f"(({arg_type}){arg_name}_data.get())" + for arg_type, arg_name in zip(arg_types, arg_names) + ] + return f"{kernel.kernel_name}({', '.join(arguments)}, M, N, K, B, lda, ldb, ldc, ldd, 0, 0, 0, swizzle, workspace_size_ptr, (uint8_t*)workspace_data.get(), 0);" + + def _render_evt( + self, + op: GemmOperation, + evt_py_code: str, + buffer_renames: dict[str, str], + name_to_buffer: dict[str, Buffer], + output_dtype: torch.dtype, + accumulator_dtype: torch.dtype, + ) -> tuple[str, str, str, EVTArgRenames]: # type: ignore[name-defined] + raise NotImplementedError("_render_evt in CUTLASSGemmTemplate not implemented") + + +class CUTLASS3xGemmTemplate(CUTLASSGemmTemplate): + """ + CUTLASS 3x GEMM Template, which is used to generate CUTLASS GEMM kernels + including those which allow flexible fusions with epilogues. + """ + + @staticmethod + def add_cutlass_gemm_choices( + choices: list[ChoiceCaller], + layout: ir.Layout, + input_nodes: list[Buffer], + alpha: float | int = 1, + beta: float | int = 0, + input_reorder: list[int] | None = None, + use_fast_accum: bool | None = None, + **extra_kwargs, + ) -> None: + template = CUTLASS3xGemmTemplate( + input_nodes, + layout, + alpha, + beta, + input_reorder, + use_fast_accum, + ) + template._add_cutlass_gemm_choices( + choices, layout, input_nodes, alpha, beta, input_reorder, **extra_kwargs + ) + + @staticmethod + @functools.lru_cache(1) + def _get_supported_ops() -> "list[cutlass_library.gemm_operation.GemmOperation]": # type: ignore[name-defined] # noqa: F821 + import cutlass_library.library as cutlass_lib + + return [cutlass_lib.GemmKind.Universal3x] + + def _get_template(self) -> str: + return GEMM_TEMPLATE_CUTLASS_3X + + def _get_template_args( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> tuple[str, str | None]: + return (GEMM_ARGS_CUTLASS_3X, GEMM_ARGS_CUTLASS_3X_EPILOGUE) + + @staticmethod + def _has_tma_epilogue( # type: ignore[arg-type,name-defined] + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined,arg-type] # noqa: F821 + ) -> bool: # type: ignore[name-defined] + """Helper method: Determine whether a given Cutlass GEMM op has a TMA Epilogue""" + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.library as cutlass_lib + + result = False + if op.gemm_kind == cutlass_lib.GemmKind.Universal3x: + epilogue_schedule_str = str(op.epilogue_schedule).split(".")[-1] + result = epilogue_schedule_str.lower().startswith("tma") + return result + + @staticmethod + def supports_epilogue_fusion(op: GemmOperation, device_type: str) -> bool: + if device_type == "xpu": + return True + return CUTLASS3xGemmTemplate._has_tma_epilogue(op) + + def _are_inputs_layout_compatible(self, layouts: list[Layout]) -> bool: + """ + Evaluates whether input layouts are compatible for General Matrix Multiply (GEMM). + + This function checks compatibility of A, B, and possibly C operand layouts for + a General Matrix Multiply (GEMM) operation, expressed as 'alpha * matmul(A, B) + beta * C'. + It verifies requirements such as matching data types, minimum rank, and suitability + for broadcasting, as defined by PyTorch operations like `torch.matmul`, `torch.aten.mm`, + `addmm`, `bmm`, `baddbmm`, etc. + + Args: + layouts (List[Layout]): List containing 2 or 3 Layout objects representing + the input matrices A, B, and possibly C. + + Returns: + bool: True if layouts are GEMM compatible, otherwise False. + """ + if not (2 <= len(layouts) <= 5): + raise AssertionError(f"expected 2 to 5 layouts, got {len(layouts)}") + # Check if A and B are compatible + A_layout, B_layout = layouts[:2] + if len(A_layout.size) < 1: + return False + if len(B_layout.size) < 1: + return False + A_size = list(V.graph.sizevars.guarding_hints_or_throw(A_layout.size)) + B_size = list(V.graph.sizevars.guarding_hints_or_throw(B_layout.size)) + if len(A_size) < 2: + A_size.insert(0, 1) + if len(B_size) < 2: + A_size.insert(1, 1) + # Are batch dims broadcastable? + while len(A_size) < len(B_size): + A_size.insert(0, 1) + while len(B_size) < len(A_size): + B_size.insert(0, 1) + K = max(A_size[-1], B_size[-2]) + M = A_size[-2] + N = B_size[-1] + if K != A_size[-1] and A_size[-1] != 1: + return False + if K != B_size[-2] and B_size[-1] != 1: + return False + # check batch dim broadcastable + for i in range(len(A_size) - 2): + if A_size[i] != B_size[i] and A_size[i] != 1 and B_size[i] != 1: + return False + if len(layouts) == 3: + C_layout = layouts[2] + C_size = list(V.graph.sizevars.guarding_hints_or_throw(C_layout.size)) + while len(C_size) < len(A_size): + C_size.insert(0, 1) + # check batch dims + for i in range(len(A_size) - 2): + bd = max(A_size[i], B_size[i]) + if bd != C_size[i] and C_size[i] != 1: + return False + if len(C_size) > len(A_size): + # This may happen if the last elements of C are contiguous and + # their multiplied size equals the last dim size of B + if M != C_size[len(A_size) - 2] and C_size[len(A_size) - 2] != 1: + return False + remaining_size = 1 + for i in range(len(A_size) - 1, len(C_size)): + remaining_size *= C_size[i] + if N != remaining_size and remaining_size != 1: + return False + return True + if len(C_size) != len(A_size): + raise AssertionError( + f"expected C and A to have same rank, got {len(C_size)} and {len(A_size)}" + ) + if M != C_size[-2] and C_size[-2] != 1: + return False + if N != C_size[-1] and C_size[-1] != 1: + return False + return True + + def _render_evt( + self, + op: GemmOperation, + evt_py_code: str, + var_name_to_buffer_name: dict[str, str], + name_to_buffer: dict[str, Buffer], + output_dtype: torch.dtype, + accumulator_dtype: torch.dtype, + ) -> tuple[str, str, str, EVTArgRenames]: + from .lib_extensions.evt_extensions import create_example_tensors, trace + + acc_dtype = torch_dtype_to_cutlass_type(accumulator_dtype) + output_dtype = torch_dtype_to_cutlass_type(output_dtype) + + # TODO: size_hint_fn is passed to both create_example_tensors (just for + # tracing examples) and trace -> _render_argument_type -> _get_arg_from_node + # where stride values are baked as C++ literals into the generated CUTLASS + # argument struct. For the latter, accessing hint is wrong: even for + # backed symbols we access the hint without installing a guard, so the + # generated strides could be incorrect for different dynamic shape inputs. + # guarding_hint_or_throw would be wrong here — it does not install + # guards either. This should use guard_int to properly guard on the values. + examples = create_example_tensors( + var_name_to_buffer_name, + name_to_buffer, # type: ignore[arg-type] + V.graph.sizevars.optimization_hint, + ) + evt_name, evt_args, evt_code, arg_renames = trace( + evt_py_code, + examples, + acc_dtype, + output_dtype, + op.tile_description, # type: ignore[attr-defined] + op.epilogue_schedule, # type: ignore[attr-defined] + {k: name_to_buffer[v] for k, v in var_name_to_buffer_name.items()}, # type: ignore[arg-type,misc] + V.graph.sizevars.guarding_hint_or_throw, + kernel_schedule=op.kernel_schedule, + device_type=self.device_type, + ) + + return ( + evt_name, + evt_args, + evt_code, + arg_renames, + ) + + def _shape_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + return True + + def _alignment_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + return True + + def _set_bias_layout_and_alignment( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + import cutlass_library.library as cutlass_lib + + has_bias = len(self.input_nodes) == 3 and self.input_nodes[2] is not None + if has_bias: + Bias = self.input_nodes[2] + # bias dtype + op.C.element = cutlass_utils.torch_dtype_to_cutlass_type( + Bias.get_layout().dtype + ) + + # Bias layout + bias_layout = CUTLASSGemmTemplate.cutlass_layout(Bias.get_layout()) + op.C.layout = bias_layout + + # Bias alignment + status = self.set_alignment(Bias.get_layout(), op.C) + if not status: + return False + else: + op.C.element = cutlass_lib.DataType.void + return True + + def _define_gemm_instance( + self, + op: GemmOperation, + evt_name: str | None = None, + ) -> tuple[str, str]: + """Defines and renders the Cutlass / CUDA/XPU C++ code for a given GEMM operation instance. + + This function uses the Cutlass library to generate key parts of the codegen process. General Matrix Multiply + forms a core part of a number of scientific applications, so this efficient and adaptable implementation is + crucial. + + Args: + op (cutlass_library.gemm_op.GemmOperation): This is the core GEMM operation that we are defining and rendering. + + Returns: + tuple[str, str]: A tuple where the first part is a string that constitutes the defined GEMM operation in C++ + code (render) and the second part is the string that specifies the operation type. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.library as cutlass_lib + + from .lib_extensions import gemm_operation_extensions as gemm_extensions + + emitter = gemm_extensions.EmitGemmUniversal3xInstanceWithEVT( + evt_name=evt_name, device_type=self.device_type + ) # type: ignore[call-arg] + + if not hasattr(op, "epilogue_functor") or not isinstance( + op.epilogue_functor, enum.Enum + ): + op = copy.deepcopy(op) + op.epilogue_functor = cutlass_lib.EpilogueFunctor.LinearCombination + + op_def = emitter.emit(op) + pattern = re.compile(r"\s*struct\s(.*?)\s:") + decl = [line for line in op_def.split("\n") if "struct " in line][-1] + + match = pattern.match(decl) + if match is None: + raise RuntimeError("Invalid Gemm config: \n" + op_def) + op_type = match.groups()[0] + if op.gemm_kind == cutlass_lib.GemmKind.Universal3x: + # Append KERNEL_NAME to the struct name to ensure uniqueness across + # compiled .so files. When multiple kernels share the same GEMM core + # but have different epilogues (e.g., LinearCombination vs EVT), they + # produce identical struct names. On SYCL/XPU this causes the runtime + # to dispatch the wrong binary; on CUDA it avoids potential symbol + # collisions. KERNEL_NAME gets replaced with a unique per-.so hash + # in scheduling.py. + unique_op_type = f"{op_type}_{Placeholder.KERNEL_NAME}" + op_def = op_def.replace(f"struct {op_type} :", f"struct {unique_op_type} :") + op_def += f"\n using {unique_op_type}_device_type = cutlass::gemm::device::GemmUniversalAdapter<{unique_op_type}>;\n" + op_type = f"{unique_op_type}_device_type" + + return op_def, op_type + + def _get_extra_inputs_and_names( + self, + op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821 + ) -> tuple[Buffer | None, list[Buffer | None], list[str]]: + Bias = self.input_nodes[2] if len(self.input_nodes) == 3 else None + inputs: list[Buffer | None] = [] + names: list[str] = [] + return (Bias, inputs, names) + + def _update_arg_names_for_test_call_statement( + self, + arg_names: list[str], + input_nodes: list[Buffer], + ) -> list[str]: + if input_nodes[2] is None: + del arg_names[2] + else: + # Reorder them as Bias, A, B + if self.input_reorder is not None: + arg_names[0 : len(self.input_reorder)] = [ + arg_names[i] for i in self.input_reorder + ] + return arg_names + + def render_gemm_arguments( + self, + argument_template: str, + epilogue_template: str, + should_swap_xw: bool, + X: IRNode, + W: IRNode, + Bias: IRNode, + Y: IRNode, + alpha: float, + beta: float, + kernel: CUTLASSTemplateKernel, + epilogue_args, + ) -> str: + """ + Render the Cutlass CUDA/XPU C++ code required for passing arguments to the GEMM operation. + + Args: + argument_template (str): Template for the GEMM operation arguments. + epilogue_template (str): Template for the epilogue arguments. + should_swap_xw (bool): Determines whether X, W operands should be swapped. If True, applies an explicit + transpose operation to X and W. + X (IRNode): The X input tensor. + W (IRNode): The W input tensor. + Bias (IRNode): The bias tensor. + Y (IRNode): The output tensor. + alpha (float): Scaling factor for the product of the inputs. + beta (float): Scaling factor for the output tensor. + kernel (CUTLASSTemplateKernel): CUDA/XPU Template kernel for the operation. + epilogue_args (any): Additional arguments for the epilogue state. + + Returns: + str: A block of CUDA/XPU C++ code as a string, ready to be used as arguments for the GEMM operation. + + Note: If `should_swap_xw` is True, a transpose operation will be applied to the X, W, Bias, and Y + tensors. This operation also implies the M and N dimensions of Bias and GEMM output to be swapped + before the function call. + """ + options = { + "alpha": alpha, + "beta": beta, + "X": X, + "W": W, + "Y": Y, + "Bias": Bias, + "template": self, + "kernel": kernel, + "M": "M", + "N": "N", + "epilogue_args": epilogue_args, + } + if epilogue_template is None: + raise AssertionError("expected epilogue_template to be non-None") + + if should_swap_xw: + # Swap + def clone_with_transposed_stride(node: IRNode) -> IRNode: + old_layout = node.get_layout() + new_stride = list(old_layout.stride) # type: ignore[union-attr] + new_stride[-2], new_stride[-1] = new_stride[-1], new_stride[-2] + if old_layout.device is None: + raise AssertionError("expected old_layout.device to be non-None") + new_layout = FixedLayout( + old_layout.device, + old_layout.dtype, + list(old_layout.size), # type: ignore[union-attr] + new_stride, + old_layout.offset, # type: ignore[union-attr] + ) + return Buffer(name=node.get_name(), layout=new_layout) + + new_X = clone_with_transposed_stride(X) + new_W = clone_with_transposed_stride(W) + new_Bias = clone_with_transposed_stride(Bias) + new_Y = clone_with_transposed_stride(Y) + options["X"], options["W"], options["Bias"], options["Y"] = ( + new_W, + new_X, + new_Bias, + new_Y, + ) + options["M"], options["N"] = "N", "M" + + epilogue_arguments = self._template_from_string(epilogue_template).render( + **options + ) + arguments = self._template_from_string(argument_template).render( + epilogue_arguments=epilogue_arguments, **options + ) + + return arguments + + +class CUTLASS2xGemmTemplate(CUTLASSGemmTemplate): + """CUTLASS 2x GEMM Template, which is used to generate CUTLASS 2x GEMM kernels""" + + def __init__( + self, + input_nodes: list[Buffer], + layout: Layout, + alpha: float, + beta: float, + input_reorder: list[int] | None = None, + ): + super().__init__(input_nodes, layout, alpha, beta, input_reorder) + + @staticmethod + def add_cutlass_gemm_choices( + choices: list[ChoiceCaller], + layout: ir.Layout, + input_nodes: list[Buffer], + alpha: float | int = 1, + beta: float | int = 0, + input_reorder: list[int] | None = None, + use_fast_accum: bool | None = False, + **extra_kwargs, + ) -> None: + template = CUTLASS2xGemmTemplate( + input_nodes, layout, alpha, beta, input_reorder + ) + template._add_cutlass_gemm_choices( + choices, layout, input_nodes, alpha, beta, input_reorder, **extra_kwargs + ) + + @staticmethod + def _get_supported_ops() -> "list[cutlass_library.gemm_operation.GemmOperation]": # type: ignore[name-defined] # noqa: F821 + import cutlass_library.library as cutlass_lib + + return [cutlass_lib.GemmKind.Universal, cutlass_lib.GemmKind.Sparse] + + @staticmethod + def _has_tma_epilogue(self) -> bool: + return False + + def _get_template(self) -> str: + return GEMM_TEMPLATE_CUTLASS_2X + + def _get_template_args( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> tuple[str, str | None]: + import cutlass_library.library as cutlass_lib + + if op.gemm_kind == cutlass_lib.GemmKind.Sparse: + return (GEMM_ARGS_SPARSE_CUTLASS_2X, None) + + return (GEMM_ARGS_CUTLASS_2X, None) + + def _are_inputs_layout_compatible(self, layouts: list[Layout]) -> bool: + """ + Evaluates whether input layouts are compatible for set of operations supported by this class. + + Args: + layouts (List[Layout]): List containing Layout objects representing + the input matrices. + + Returns: + bool: True if layouts are GEMM compatible, otherwise False. + """ + if not (len(layouts) == 2 or len(layouts) == 3): + raise AssertionError(f"expected 2 or 3 layouts, got {len(layouts)}") + # Check if A and B are compatible + A_layout, B_layout = layouts[:2] + if len(A_layout.size) != 2: + return False + if len(B_layout.size) != 2: + return False + A_size = [int(i) for i in A_layout.size] + B_size = [int(i) for i in B_layout.size] + K = max(A_size[1], B_size[0]) + return (K == A_size[1] or K == 2 * A_size[1]) and K == B_size[0] + + def _shape_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + import cutlass_library.library as cutlass_lib + + X, W = self.input_nodes[0], self.input_nodes[1] + + if op.gemm_kind == cutlass_lib.GemmKind.Sparse: + return X.get_size()[1] * 2 == W.get_size()[0] + + return X.get_size()[1] == W.get_size()[0] + + def _alignment_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + import cutlass_library.library as cutlass_lib + + if op.gemm_kind != cutlass_lib.GemmKind.Sparse: + return True + + # SparseGemm in CUTLASS has specific alignment check that for + # small k could make some of the choices throw kMisalignedOperand + # CUTLASS error when run, see: + # https://github.com/NVIDIA/cutlass/blob/e01b9b5029b7caca5a43c29f7d2714d7cf1dcae8/include/cutlass/gemm/kernel/sparse_gemm.h#L198-L200 + # So, let's skip these choices if that would be the case. + X = self.input_nodes[0] + return (X.get_size()[1] * 2) % op.tile_description.tile_shape[2] == 0 + + def _set_bias_layout_and_alignment( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + import cutlass_library.library as cutlass_lib + + if op.gemm_kind == cutlass_lib.GemmKind.Sparse: + op.C.layout = op.D.layout + return True + + if len(self.input_nodes) >= 3 and self.input_nodes[2] is not None: + Bias = self.input_nodes[2] + bias_layout = CUTLASSGemmTemplate.cutlass_layout(Bias.get_layout()) + if bias_layout != op.D.layout: + # For cutlass2, bias and output layout must match + return False + if not self.set_alignment(Bias.get_layout(), op.C): + return False + else: + op.C.layout = op.D.layout + return True + + def _define_gemm_instance( + self, + op: GemmOperation, + evt_name: str | None = None, + ) -> tuple[str, str]: + """Defines and renders the Cutlass / CUDA C++ code for a given GEMM operation instance. + + This function uses the Cutlass library to generate key parts of the codegen process. General Matrix Multiply + forms a core part of a number of scientific applications, so this efficient and adaptable implementation is + crucial. + + Args: + op (cutlass_library.gemm_op.GemmOperation): This is the core GEMM operation that we are defining and rendering. + + Returns: + tuple[str, str]: A tuple where the first part is a string that constitutes the defined GEMM operation in C++ + code (render) and the second part is the string that specifies the operation type. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.gemm_operation as cutlass_gemm_op + import cutlass_library.library as cutlass_lib + + if op.gemm_kind == cutlass_lib.GemmKind.Sparse: + emitter = cutlass_gemm_op.EmitSparseGemmInstance() + else: + emitter = cutlass_gemm_op.EmitGemmInstance() + op_def = emitter.emit(op) + op_def = op_def.replace( + "cutlass::gemm::device::Gemm", "cutlass::gemm::device::GemmUniversal" + ) + if op.gemm_kind != cutlass_lib.GemmKind.Sparse: + op_def = op_def.replace("false,", "") + pattern = re.compile(r"\s*using\s(.*?)\s=") + decl = op_def.split("\n")[2] + + match = pattern.match(decl) + if match is None: + raise RuntimeError("Invalid Gemm config: \n" + op_def) + op_type = match.groups()[0] + return op_def, op_type + + def _get_extra_inputs_and_names( + self, + op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821 + ) -> tuple[Buffer | None, list[Buffer | None], list[str]]: + import cutlass_library.library as cutlass_lib + + if op.gemm_kind == cutlass_lib.GemmKind.Sparse: + Bias = None + Meta = self.input_nodes[2] + else: + Bias = None if len(self.input_nodes) == 2 else self.input_nodes[2] + Meta = None + inputs = [Meta] + names = ["Meta"] + return (Bias, inputs, names) + + def _update_arg_names_for_test_call_statement( + self, + arg_names: list[str], + input_nodes: list[Buffer], + ) -> list[str]: + if input_nodes[3] is None: + del arg_names[3] + if input_nodes[2] is None: + del arg_names[2] + return arg_names + + def render_gemm_arguments( + self, + instance_type: str, + argument_template: str, + epilogue_template: str, + should_swap_xw: bool, + X: IRNode, + W: IRNode, + Bias: IRNode, + Meta: IRNode, + Y: IRNode, + alpha: float, + beta: float, + kernel: CUTLASSTemplateKernel, + epilogue_args, + ) -> str: + """ + Render the Cutlass CUDA C++ code required for passing arguments to the GEMM operation. + + Args: + instance_type (str): GEMM instance type. + argument_template (str): Template for the GEMM operation arguments. + epilogue_template (str): Template for the epilogue arguments. + should_swap_xw (bool): Determines whether X, W operands should be swapped. If True, applies an explicit + transpose operation to X and W. + X (IRNode): The X input tensor. + W (IRNode): The W input tensor. + Bias (IRNode): The bias tensor. + Meta (IRNode): The meta tensor. + Y (IRNode): The output tensor. + alpha (float): Scaling factor for the product of the inputs. + beta (float): Scaling factor for the output tensor. + kernel (CUTLASSTemplateKernel): CUDA Template kernel for the operation. + epilogue_args (any): Additional arguments for the epilogue state. + + Returns: + str: A block of CUDA C++ code as a string, ready to be used as arguments for the GEMM operation. + + Note: If `should_swap_xw` is True, a transpose operation will be applied to the X, W, Bias, and Y + tensors. This operation also implies the M and N dimensions of Bias and GEMM output to be swapped + before the function call. + """ + options = { + "instance_type": instance_type, + "alpha": alpha, + "beta": beta, + "X": X, + "W": W, + "Y": Y, + "Bias": Bias, + "Meta": Meta, + "template": self, + "kernel": kernel, + "M": "M", + "N": "N", + "epilogue_args": epilogue_args, + } + + if epilogue_template is None: + arguments = self._template_from_string(argument_template).render( + split_k=1, **options + ) + return arguments + + epilogue_arguments = self._template_from_string(epilogue_template).render( + **options + ) + arguments = self._template_from_string(argument_template).render( + epilogue_arguments=epilogue_arguments, **options + ) + + return arguments diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..4602a72d5ee15b8dd572ccb73911f8e9d08f3970 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/kernel.py @@ -0,0 +1,723 @@ +# mypy: allow-untyped-defs +import functools +import itertools +import logging +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Literal, TYPE_CHECKING + +from sympy import Expr, symbols + +import torch._inductor.config as config +from torch import dtype as torch_dtype +from torch._inductor.codegen.common import get_device_op_overrides +from torch._inductor.codegen.cpp_wrapper_cpu import CppWrapperCpu +from torch._inductor.scheduler import BaseSchedulerNode +from torch._inductor.utils import do_bench_using_profiling, OrderedSet, Placeholder +from torch.utils._sympy.value_ranges import ValueRanges + +from .utils import DTYPE_TO_CUTLASS_TYPE + + +if TYPE_CHECKING: + from .template import ArgInfo + +from ...autotune_process import CUTLASSBenchmarkRequest +from ...ir import ( + Buffer, + ChoiceCaller, + CUTLASSTemplateBuffer, + IRNode, + Layout, + PrimitiveInfoType, + TensorBox, +) +from ...utils import sympy_product +from ...virtualized import V +from ..common import ( + CSEVariable, + IndentedBuffer, + Kernel, + OpOverrides, + WorkspaceArg, + WorkspaceZeroMode, +) +from ..cpp_utils import CppPrinter, DTYPE_TO_CPP + + +if TYPE_CHECKING: + from torch._inductor.codegen.cutlass.template import CUTLASSTemplate + +log = logging.getLogger(__name__) + +cexpr = CppPrinter().doprint + + +def _normalize_idx(index: int, total_length: int) -> int: + return index if index >= 0 else index + total_length + + +ValidLayoutSymbols = Literal["M", "N", "K", "B", "lda", "ldb", "ldc", "ldd"] +ValidLayoutAttrs = Literal["size", "stride"] + + +@dataclass(frozen=True) +class LayoutArg: + node: IRNode + symbol: ValidLayoutSymbols + attr: ValidLayoutAttrs + dim: int + + def matches(self, node, attr, dim) -> bool: + return self.node == node and self.attr == attr and self.dim == dim + + +class CUTLASSKernel(Kernel): + """ + Baseclass for Cutlass based Kernels + """ + + overrides = OpOverrides # type: ignore[assignment] + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.layout_args: dict[str, list[LayoutArg]] = defaultdict(list) + self.size_args: list[Expr | int] = [] + # Mapping from arg name to IRNode. + self.named_nodes: dict[str, IRNode] = {} + + def find_symbol(self, node: IRNode, attr: ValidLayoutAttrs, dim: int) -> str | None: + arg = self.find_layout_arg(node, attr, dim) + return arg.symbol if arg else None + + def find_layout_arg( + self, node: IRNode, attr: ValidLayoutAttrs, dim: int + ) -> LayoutArg | None: + matches = [ + arg + for arg in itertools.chain.from_iterable(self.layout_args.values()) + if arg.matches(node, attr, dim) + ] + if len(matches) >= 1: + # Verify all matches have the same node, attribute, and dimension + # And if they come from the same node, whichever symbol we use is fine. + # if in runtime the logic changes, this would trigger guard + first_match = matches[0] + if not all( + match.node == first_match.node + and match.attr == first_match.attr + and match.dim == first_match.dim + for match in matches + ): + raise AssertionError("All matching layout args should be identical") + return first_match + attr_values = node.get_size() if attr == "size" else node.get_stride() + if dim >= len(attr_values): + return None + expr = attr_values[dim] + fallback_matches = [] + for arg in itertools.chain.from_iterable(self.layout_args.values()): + if arg.attr != attr: + continue + if arg.node.get_name() != node.get_name(): + continue + arg_values = ( + arg.node.get_size() if arg.attr == "size" else arg.node.get_stride() + ) + if arg.dim >= len(arg_values): + continue + if arg_values[arg.dim] == expr: + fallback_matches.append(arg) + if fallback_matches: + return fallback_matches[0] + return None + + def add_layout_arg( + self, symbol: ValidLayoutSymbols, node: IRNode, attr: ValidLayoutAttrs, dim: int + ): + arg = LayoutArg(node, symbol, attr, dim) + self.layout_args[symbol].append(arg) + + def init_layout_args(self) -> None: + X = self.named_nodes["X"] + W = self.named_nodes["W"] + Y = self.named_nodes["Y"] + Bias = self.named_nodes.get("Bias", None) + x_mdim = _normalize_idx(-2, len(X.get_size())) + x_kdim = _normalize_idx(-1, len(X.get_size())) + w_kdim = _normalize_idx(-2, len(W.get_size())) + w_ndim = _normalize_idx(-1, len(W.get_size())) + y_mdim = _normalize_idx(-2, len(Y.get_size())) + y_ndim = _normalize_idx(-1, len(Y.get_size())) + self.add_layout_arg("M", X, "size", x_mdim) + self.add_layout_arg("K", X, "size", x_kdim) + self.add_layout_arg("K", W, "size", w_kdim) + self.add_layout_arg("N", W, "size", w_ndim) + self.add_layout_arg("M", Y, "size", y_mdim) + self.add_layout_arg("N", Y, "size", y_ndim) + if len(X.get_size()) > 2: + self.add_layout_arg("B", X, "size", 0) + + lda_dim = self.find_ld_idx(X) + ldb_dim = self.find_ld_idx(W) + ldc_dim = self.find_ld_idx(Bias) if Bias else None + ldd_dim = self.find_ld_idx(Y) + self.add_layout_arg("lda", X, "stride", lda_dim) + self.add_layout_arg("ldb", W, "stride", ldb_dim) + if Bias is not None and ldc_dim is not None: + self.add_layout_arg("ldc", Bias, "stride", ldc_dim) + self.add_layout_arg("ldd", Y, "stride", ldd_dim) + + def get_layout_args(self) -> tuple[Expr | int, ...]: + X = self.named_nodes["X"] + W = self.named_nodes["W"] + Y = self.named_nodes["Y"] + Bias = self.named_nodes.get("Bias", None) + mdim = _normalize_idx(-2, len(X.get_size())) + ndim = _normalize_idx(-1, len(W.get_size())) + kdim = _normalize_idx(-1, len(X.get_size())) + + def get_ld(node) -> Expr | int: + dim = self.find_ld_idx(node) + return node.get_stride()[dim] + + M = X.get_size()[mdim] + N = W.get_size()[ndim] + K = X.get_size()[kdim] + B = X.get_size()[0] if len(X.get_size()) > 2 else 1 + LDA = get_ld(X) + LDB = get_ld(W) + LDC = get_ld(Bias) if Bias else 0 + LDD = get_ld(Y) + return (M, N, K, B, LDA, LDB, LDC, LDD) + + def get_dynamic_shape_args(self) -> list[Expr | int]: + return [*self.get_layout_args(), *self.size_args] + + def get_offset_args(self) -> list[Expr]: + return [node.get_layout().offset for node in self.named_nodes.values()] + + @staticmethod + def find_ld_idx(node: IRNode) -> int: + strides = node.get_stride() + # Handle 1D tensor case + if V.graph.sizevars.statically_known_equals(strides[-1], 1): + return _normalize_idx(-2, len(strides)) + + if not V.graph.sizevars.statically_known_equals(strides[-2], 1): + raise AssertionError(strides[-2]) + return _normalize_idx(-1, len(strides)) + + +class CUTLASSTemplateKernel(CUTLASSKernel): + """ + Template kernels defined by Cutlass in C++. + """ + + def __init__( + self, + kernel_name: str, + runtime_arg_info: list["ArgInfo"], + runtime_arg_values: list[Any], + device_type: str = "cuda", # type: ignore[assignment] + ) -> None: + """ + Initializes a new instance of the CUTLASSTemplateKernel class. + + Args: + kernel_name (str): The name of the kernel. + """ + super().__init__() + self.kernel_name = kernel_name + self.runtime_arg_info = runtime_arg_info + self.runtime_arg_values = runtime_arg_values + self.device_type = device_type + self.device_codegen = get_device_op_overrides(self.device_type) + self._EXTRA_CPP_ARGS = f"size_t* workspace_size, uint8_t* workspace, {self.device_codegen.cpp_stream_type()} stream" + + def check_not_null(self, node: IRNode) -> str: + """ + Generates code to check that a node is not null. + """ + if node is None: + return "" + + size_str = self.size(node, 0, -1) + name_str = self.arg_name(node) + if name_str is None: + return "" + + res = IndentedBuffer(initial_indent=2) + res.tabwidth = 1 + res.splice( + f""" + {{ + if (!{name_str}) {{ + int64_t {name_str}_size = {size_str}; + if ({name_str}_size > 0) {{ + throw std::runtime_error("input {name_str} is null but size is not 0!"); + }} + }} + }} + """ + ) + return res.getvalue() + + def get_signature(self) -> str: + return self.signature + + def _collect_unbound_layout_free_symbols(self, node: IRNode) -> OrderedSet[Expr]: + free_symbols: OrderedSet[Expr] = OrderedSet() + for attr_name, values in ( + ("size", node.get_size()), + ("stride", node.get_stride()), + ): + attr = attr_name # help mypy narrow the Literal argument below + for dim, expr in enumerate(values): + if not isinstance(expr, Expr): + continue + if self.find_layout_arg(node, attr, dim) is not None: + continue + for symbol in expr.free_symbols: + free_symbols.add(symbol) # type: ignore[arg-type] + return free_symbols + + def def_kernel( + self, + inputs: list[IRNode], + outputs: list[IRNode], + names_str: str = "", + input_reorder: list[int] | None = None, + ) -> str: + """ + Hook called from template code to generate function definition and + needed args. + + Args: + inputs: List of input IRNodes + outputs: List of output IRNodes + names_str: Comma separated list of input + output argument names. + input_reorder: The actual order of input nodes. + e.g. The template might have input argument defined as [X, W, Bias], + and the actual input passed into this template could be [Bias, X, W]. + In this case, the `input_reorder` would be [2, 0, 1]. + additional_size_args: Additional size arguments for epilogue inputs + """ + # NB: name order matters here, it's used to match up offsets + names = [x.strip() for x in names_str.strip().split(",")] + if len(inputs) + len(outputs) != len(names): + raise RuntimeError( + f"{len(inputs) + len(outputs)=} != {len(names)=}, {inputs=}, {outputs=}, {names=}" + ) + + if input_reorder is not None: + if len(inputs) != len(input_reorder): + raise AssertionError( + f"expected len(inputs) == len(input_reorder), got " + f"{len(inputs)} != {len(input_reorder)}" + ) + else: + input_reorder = list(range(len(inputs))) + + for idx in input_reorder: + name = names[idx] + node = inputs[idx] + if node is not None: + self.named_nodes[name] = node + self.args.input_buffers[node.get_name()] = name + + for name, node in zip(names[len(inputs) : len(inputs) + len(outputs)], outputs): + if node is not None: + # NB: named nodes must be populated in the order of names + self.named_nodes[name] = node + self.args.output_buffers[node.get_name()] = name + + arg_defs, *_ = self.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE) + + self.init_layout_args() + free_symbols: OrderedSet[Expr] = OrderedSet() + for node in self.named_nodes.values(): + free_symbols |= self._collect_unbound_layout_free_symbols(node) + size_vars = ["M", "N", "K", "B", "lda", "ldb", "ldc", "ldd"] + size_vars.extend(str(s) for s in free_symbols) + self.size_args.extend(free_symbols) + size_args = [f"const int {s}" for s in size_vars] + offset_args = [f"const int {name}_offset" for name in self.named_nodes] + runtime_arg_decls = ",".join( + [f"{arg.ty} {arg.name}" for arg in self.runtime_arg_info] + ) + if runtime_arg_decls: + runtime_arg_decls += ", " + + signature = ( + f"int {self.kernel_name}({', '.join(arg_defs + size_args + offset_args)},\ + {runtime_arg_decls}{self._EXTRA_CPP_ARGS})" + ) + self.signature = signature + return signature + + def call_kernel( + self, + name: str, + node: "CUTLASSTemplateBuffer", # type: ignore[name-defined] + ) -> None: + """ + Generates code to call the kernel through V.graph.wrapper_code. + used from within torch._inductor.wrapper.PythonWrapperCodegen + + name: Name of kernel function. + node: The CUTLASSTemplateBuffer node which contains information about the kernel, it's fused epilogue nodes + as well as all required inputs and outputs. + """ + wrapper = V.graph.wrapper_code + + arg_types: list[Any] + if V.graph.cpp_wrapper: + # Make sure we initialize these kernels since they're exported as + # C-style symbol names. + if not isinstance(wrapper, CppWrapperCpu): + raise AssertionError( + f"expected wrapper to be CppWrapperCpu, got {type(wrapper)}" + ) + wrapper.initialized_kernels[name] = self + # We always originally initialize name with "KERNEL_NAME". So, we + # we replace with the real kernel name passed as an arg to this function. + self.signature = self.signature.replace(str(Placeholder.KERNEL_NAME), name) + _, call_args, arg_types = self.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE) + else: + _, call_args, _, arg_types = self.args.python_argdefs() + + dynamic_shape_args = self.get_dynamic_shape_args() + offset_args = self.get_offset_args() + call_args.extend(dynamic_shape_args) # type: ignore[arg-type] + call_args.extend(offset_args) # type: ignore[arg-type] + for arg in self.runtime_arg_values: + call_args.append(str(arg)) + arg_types.extend("const int" for _ in dynamic_shape_args) + arg_types.extend("const int" for _ in offset_args) + for arg in self.runtime_arg_info: + arg_types.append(arg.ty) + # dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar + for i in range(len(call_args)): + if V.graph.is_unspec_arg(call_args[i]): + call_args[i] = call_args[i] + ".item()" + elif isinstance(arg_types[i], torch_dtype): + call_args[i] = ( + call_args[i] + if V.graph.cpp_wrapper + else f"c_void_p({call_args[i]}.data_ptr())" + ) + + # workspace_size ptr is NULL to mark this call is not intended for retrieving workspace_size. + # workspace_size should have already been retrieved prior to this call. + # workspace_size is here. + call_args.append("nullptr" if V.graph.cpp_wrapper else "None") + if V.graph.cpp_wrapper: + arg_types.append("size_t*") + + if node.get_workspace_size() > 0: + ws = WorkspaceArg( + count=node.get_workspace_size(), + device=V.graph.get_current_device_or_throw(), + zero_mode=WorkspaceZeroMode.UNINITIALIZED, + outer_name=WorkspaceArg.unique_name(), + ) + wrapper.generate_workspace_allocation(ws) + workspace = str(ws.outer_name) + call_args.append( + workspace + if V.graph.cpp_wrapper + else f"c_void_p({workspace}.data_ptr())" + ) + else: + ws = None + call_args.append("nullptr" if V.graph.cpp_wrapper else "None") + if V.graph.cpp_wrapper: + arg_types.append("uint8_t*") + + wrapper.generate_kernel_call( + name, + call_args, + triton=False, + arg_types=arg_types, + ) + if ws: + wrapper.generate_workspace_deallocation(ws) + + def dtype(self, node: IRNode) -> str | None: + """ + Generates code which represents dtype of a given node. + """ + + if node is None: + return "void" + return DTYPE_TO_CPP.get(node.get_layout().dtype) + + def cutlass_dtype(self, node: IRNode, default_dtype="void") -> str | None: + # Helper method, called into from CUTLASSGemmTemplate + if node is None: + return default_dtype + from torch._inductor.codegen.cutlass.template import CUTLASSTemplate + + return CUTLASSTemplate._DTYPE_TO_CUTLASS[node.get_layout().dtype] + + def max_valid_index(self, node: IRNode, default=-1): + # Helper method, called into from CUTLASSGemmTemplate + if node is None: + return default + max_valid_offset = 0 + for i in range(len(node.get_size())): + max_valid_offset += (node.get_size()[i] - 1) * node.get_stride()[i] + return max_valid_offset + + def ptr(self, node: IRNode) -> str: + """ + Generates code which represents pointer of a given node. + """ + + if node is None: + return "nullptr" + arg_name = self.arg_name(node) + if arg_name is None: + return "nullptr" + return f"{arg_name} + {arg_name}_offset" + + def size( + self, + node: IRNode, + start_index: int, + end_index: int | None = None, + default_value: int = 0, + ) -> str: + """ + Hook called from template code to get the size of an arg. + Generates code which represents size of a given node in [start_index, end_index). + If node is None, returns default_value. + + TODO: Will add needed args to pass it in if it is dynamic. + """ + + if node is None: + return str(default_value) + + start_index = _normalize_idx(start_index, len(node.get_size())) + if end_index is None: + end_index = start_index + end_index = _normalize_idx(end_index, len(node.get_size())) + sizes = [ + self.find_symbol(node, "size", dim=i) or node.get_size()[i] + for i in range(start_index, end_index + 1) + ] + if len(sizes) == 0: + return str(default_value) + + sizes = [symbols(v) if isinstance(v, str) else v for v in sizes] + val = sympy_product(sizes) + return val + + def stride(self, node: IRNode, index: int, default_value: int = 0) -> str: + """ + Hook called from template code to get the stride of an arg. + Generates code which represents stride of a given node at index. + If node is None, returns default_value. + + TODO: Will add needed args to pass it in if it is dynamic. + """ + + if node is None: + return str(default_value) + + index = _normalize_idx(index, len(node.get_size())) + if index < 0: + return str(default_value) + + stride = node.get_stride()[index] + if V.graph.sizevars.statically_known_leq(stride, 1): + return str(stride) + return self.find_symbol(node, "stride", dim=index) or str(stride) + + def batch_stride(self, node: IRNode, default_value: int = 0) -> str: + """ + Hook called from template code to get the batch stride of an arg. + Returns 0 if batch dim is not present. + + This method assumes that batch stride is the largest stride. + """ + + if node is None: + return str(default_value) + + if len(node.get_size()) < 3: + return str(default_value) + + batch_stride = node.get_stride()[0] + if V.graph.sizevars.statically_known_leq(batch_stride, 1): + return str(batch_stride) + + return "{}*{}".format( + self.find_symbol(node, "size", dim=1) or node.get_size()[1], + self.find_symbol(node, "size", dim=2) or node.get_size()[2], + ) + + def row_or_column_stride(self, node: IRNode, default_value: int = 0) -> str: + """ + Hook called from template code to get the row or column stride of an arg. + This is required by some CUTLASS 2.X APIs. + If the node is in row_major, it returns stride[-2]. + If the node is in column_major, it returns stride[-1]. + + TODO: Will add needed args to pass it in if it is dynamic. + """ + + if node is None or len(node.get_stride()) < 2: + return str(default_value) + + stride0 = node.get_stride()[-1] + stride1 = node.get_stride()[-2] + if stride0 == 1: + return cexpr(self.rename_indexing(stride1)) + elif stride1 == 1: + return cexpr(self.rename_indexing(stride0)) + else: + raise RuntimeError( + f"At least 1 stride should be 1. Strides: {node.get_stride()=}" + ) + + def load(self, name: str, index: Expr, mode: Any = None) -> CSEVariable: + """ + Mock load function for memory planning to optimize allocations properly. + """ + return self.create_cse_var(name, bounds=ValueRanges.unknown()) + + def store(self, name: str, index: Expr, value: Any, mode: Any = None) -> None: + """ + Mock store function for memory planning to optimize allocations properly. + """ + self.store_buffer_names.add(name) + + +class CUTLASSTemplateCaller(ChoiceCaller): + """ + CUTLASSTemplateCaller + + This class represents a caller for CUTLASS template kernels. It is a subclass of ChoiceCaller. + Attributes: + name (str): The name of the caller. + category (str): The category of the caller. + bmreq (CUTLASSBenchmarkRequest): The benchmark request for the caller. + template_buffer (CUTLASSTemplateBuffer): The template buffer for the caller. + """ + + def __init__( + self, + name: str, + category: str, + input_nodes: list[Buffer], + layout: Layout, + make_kernel_render: Callable[ + [CUTLASSTemplateBuffer, list[BaseSchedulerNode] | None], + tuple[CUTLASSTemplateKernel, functools.partial[str]], + ], + bmreq: CUTLASSBenchmarkRequest, + supports_epilogue_fusion: bool, + template: "CUTLASSTemplate", # type: ignore[name-defined] + info_kwargs: dict[str, PrimitiveInfoType | list[PrimitiveInfoType]] | None, # type: ignore[type-arg] + description: str, + ) -> None: + super().__init__(name, input_nodes, layout, description) + self.category = category + self.make_kernel_render = make_kernel_render + self.bmreq = bmreq + self.supports_epilogue_fusion = supports_epilogue_fusion + self.template = template + self.info_kwargs = info_kwargs + + def precompile(self) -> None: + if self.bmreq is None: + raise AssertionError("expected self.bmreq to not be None") + self.bmreq.precompile() + + def benchmark(self, *args, out) -> float: + if self.bmreq is None: + raise AssertionError("expected self.bmreq to not be None") + if config.profile_bandwidth_with_do_bench_using_profiling: + algo = self.bmreq.make_run_fn(*args, out=out) + return do_bench_using_profiling(algo) + return self.bmreq.benchmark(*args, out=out) + + def __str__(self) -> str: + return f"CUTLASSTemplateCaller(source_file={self.bmreq.source_file})" + + def call_name(self) -> str: + return f"cutlass_template_kernels.{self.name}" + + def kernel_hash_key(self) -> str: + """ + Return kernel hash key that does not depend on swizzle. + """ + return "-".join( + [ + self.category, + self.bmreq.hash_key, + ] + ) + + def hash_key(self) -> str: + """ + Return kernel hash key that does not depend on swizzle. + """ + swizzle_str: str = ( + str(self.info_kwargs.get("swizzle")) + if isinstance(self.info_kwargs, dict) + else "None" + ) + return "-".join( + [ + self.category, + self.bmreq.hash_key, + swizzle_str, + ] + ) + + def info_dict(self) -> dict[str, PrimitiveInfoType | list[PrimitiveInfoType]]: + """ + Information returned here is logged to the autotune log file when that is enabled. + + In general, we should avoid calling this function as it is expensive to compute, + and can add up very fast. + """ + if self.info_kwargs is not None and "op" in self.info_kwargs: + op: Any = self.info_kwargs["op"] + return { + "backend": "CUDA", + "op_type": type(op).__name__, + "op_conf_name": str(op.configuration_name()), + "op_arch": str(op.arch), + "tile_shape": str(op.tile_description.tile_shape), + "epilogue_schedule": str(op.epilogue_schedule), + "kernel_schedule": str(op.kernel_schedule), + "element_accumulator": str(op.accumulator_type()), + "op_name": str(op.procedural_name()), + "instruction_shape": str( + op.tile_description.math_instruction.instruction_shape + ), + "swizzle": str(self.info_kwargs["swizzle"]), + } + else: + return {"backend": "CUDA", "op_type": "unknown"} + + def output_node(self) -> TensorBox: + self.bmreq.update_workspace_size() + buffer = CUTLASSTemplateBuffer( + layout=self.layout, + inputs=self.input_nodes, + make_kernel_render=self.make_kernel_render, + workspace_size=self.bmreq.workspace_size, + supports_epilogue_fusion=self.supports_epilogue_fusion, + template=self.template, + ) + # Pass KTC annotation to the buffer for encoding + if "ktc" in self.annotations: + buffer.annotations["ktc"] = self.annotations["ktc"] + return TensorBox.create(buffer) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01661a5584d36bf048aac64192aacdbeb9fa1f24 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/evt_extensions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/evt_extensions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e44d1ffb1c402135c2350844fded95a9e17c656b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/evt_extensions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/gemm_operation_extensions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/gemm_operation_extensions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cdd3dc73756862a65b487b7c8a904b8d6648e92 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/gemm_operation_extensions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7383d6262ad2f308da3b3cbc2b26ca2885cc6600 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e12a86af8ab0ab8d7d7b2d8bf37ec6dec861e0ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__init__.py @@ -0,0 +1,6 @@ +import torch + + +__version__ = torch.version.cuda + +from .cuda import * # noqa: F403 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdcdccc807e441b1f70547d7dd0145edeba9aa97 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cuda.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cuda.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..798b6e3235b2375296b7386b31c0208f8f3271cd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cuda.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cudart.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cudart.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f9ec76c0bfd6152e147611a3b3b3414b27937f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cudart.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cuda.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..ad41f04fc897e33f4530eb42c76a104def58f413 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cuda.py @@ -0,0 +1,24 @@ +# mypy: disable-error-code="no-untyped-def" +# flake8: noqa +import torch + + +class CUdeviceptr: + pass + + +class CUstream: + def __init__(self, v): + pass + + +class CUresult: + CUDA_SUCCESS = True + + +class nvrtc: + pass + + +def cuDeviceGetCount(): + return (CUresult.CUDA_SUCCESS, torch.cuda.device_count()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cudart.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cudart.py new file mode 100644 index 0000000000000000000000000000000000000000..ca2ee5f1f6163d7b20336d6102ce5d8f97880c87 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cudart.py @@ -0,0 +1,17 @@ +# mypy: disable-error-code="no-untyped-def" +import torch.cuda + + +class cudaError_t: + cudaSuccess = True + + +def cudaFree(n): + return (cudaError_t.cudaSuccess,) + + +def cudaGetDeviceProperties(d): + class DummyError: + value = False + + return (DummyError(), torch.cuda.get_device_properties(d)) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8aefb6171b682f062cfe57a1876f51b280f120cc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__init__.py @@ -0,0 +1,2 @@ +# mypy: disable-error-code="var-annotated" +Dot = None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e2ba9c4d9dead34fd58a75525658f4350a7998e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f0378d35a9c442559373f035e45de19b2be927cd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__init__.py @@ -0,0 +1,3 @@ +# typing: ignore +# flake8: noqa +from .special import * diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..164fd26384eca8064b73f1bc37d84f1ff8d290c2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/special.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/special.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73e4cb98294e06a4304d555e64901bcac8a1fd5d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/special.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/special.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/special.py new file mode 100644 index 0000000000000000000000000000000000000000..79af3029aa0b18d0ad55633f8cca8af8b76b520b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/special.py @@ -0,0 +1,2 @@ +# mypy: disable-error-code="var-annotated" +erf = None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/evt_extensions.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/evt_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..666e09d3be718ff81baa6622524cd0f1b36e6371 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/evt_extensions.py @@ -0,0 +1,371 @@ +from collections.abc import Callable +from typing import Any + +from sympy import Expr + +from torch._inductor.ir import ( + ComputedBuffer, + InputBuffer, + is_contiguous_strides_for_shape, +) +from torch.utils._ordered_set import OrderedSet + +from ..utils import cutlass_arch, torch_dtype_to_cutlass_type, try_import_cutlass + + +EpilogueFunctor = Any # EpilogueFunctor local class defined in _trace +Buffer = ComputedBuffer | InputBuffer +CutlassTupleType = Any # cutlass.backend.c_types.tuple_factory_..TupleType +CutlassVisitorType = Any # cutlass.backend.c_types.visitor_factory..VisitorType +CutlassArgType = ( + Any # Can be a CutlassTupleType, CutlassVisitorType, EmptyByte, or ctype.c_void_p +) + + +if try_import_cutlass(): + import ast + import ctypes + import textwrap + + from cutlass_cppgen.backend.c_types import ( # type: ignore[import-not-found] + EmptyByte, + ) + from cutlass_cppgen.backend.epilogue import ( # type: ignore[import-not-found] + dtype2ctype, + ) + from cutlass_cppgen.backend.evt import ( # type: ignore[import-not-found] + backend as evt_backend, + EpilogueFunctorVisitor, + ) + from cutlass_cppgen.backend.evt.backend.emitter_base import ( # type: ignore[import-not-found] + FusionCallbacks, + ) + from cutlass_cppgen.backend.evt.backend.sm100_emitter import ( # type: ignore[import-not-found] + Sm100CollectiveEpilogue, + ) + from cutlass_cppgen.backend.evt.frontend import ( # type: ignore[import-not-found] + PythonASTFrontend, + ) + from cutlass_cppgen.backend.evt.ir.tensor import ( # type: ignore[import-not-found] + Tensor as CutlassTensor, + ) + from cutlass_library import ( + DataType, + EpilogueScheduleType, + LayoutType, + TileDescription, + ) + + from torch._inductor.utils import IndentedBuffer + + _CUTLASS_C_DTYPES = OrderedSet(dtype2ctype.values()) # type: ignore[var-annotated] + + class EVTArgRenames: + """Handles mapping buffer names to variable names in the cpp kernel signature and body""" + + def __init__(self) -> None: + self.buf_renames: dict[str, str] = {} + + def new_name(self, name: str) -> str: + if name in self.buf_renames: + return self.buf_renames[name] + else: + new_name = f"ptr_{len(self.buf_renames)}" + self.buf_renames[name] = new_name + return new_name + + def get(self, name: str) -> str: + return self.buf_renames.get(name, name) + + def create_example_tensors( + var_name_to_buffer_name: dict[str, str], + name_to_buffer: dict[str, Buffer], + size_hint_fn: Callable[[Expr | int], int], + ) -> dict[str, CutlassTensor]: + def cutlass_tensor_from_buffer( + buffer: Buffer, + ) -> CutlassTensor: + shape = buffer.get_layout().size + stride = buffer.get_layout().stride + shape = tuple(size_hint_fn(x) for x in shape) + stride = tuple(size_hint_fn(x) for x in stride) + + is_row_major = is_contiguous_strides_for_shape(stride, shape) + is_column_major = is_contiguous_strides_for_shape(stride[::-1], shape[::-1]) + + if not is_row_major and not is_column_major: + raise RuntimeError( + f"Cannot create example tensor for {buffer.get_name()} with \ +non-contiguous layout, received stride: {stride} and shape: {shape}" + ) + + return CutlassTensor( + shape=shape, + layout_tag=( + LayoutType.RowMajor if is_row_major else LayoutType.ColumnMajor + ), + element=torch_dtype_to_cutlass_type(buffer.get_layout().dtype), + ) + + return { + key: cutlass_tensor_from_buffer(name_to_buffer[name]) + for key, name in var_name_to_buffer_name.items() + } + + def trace( + fn_src: str, + example_tensors: dict[str, CutlassTensor], + accum_type: DataType, + output_type: DataType, + tile_description: TileDescription, + epilogue_schedule: EpilogueScheduleType, + name_to_buffer: dict[str, Buffer], + size_hint_fn: Callable[[Expr | int], int], + kernel_schedule: Any | None = None, + device_type: str = "cuda", + **kwargs: dict[str, Any], + ) -> tuple[str, str, str, EVTArgRenames]: + arch = int(cutlass_arch(device_type)) + if device_type == "cuda" and arch < 90: + raise AssertionError("For CUDA, only SM90+ is supported for EVT") + epilogue_functor = _trace(fn_src, example_tensors, arch, **kwargs) + visitor = EpilogueFunctorVisitor(arch, epilogue_functor) + fusion_callbacks = FusionCallbacks(visitor.graph, arch, emit_CD=False) + arch_prefix = "xe" if device_type == "xpu" else "sm" + + if device_type == "xpu" or arch < 100: + try: + evt_emitter = getattr(evt_backend, f"{arch_prefix}{arch}_emitter") + CollectiveEpilogue = evt_emitter.CollectiveEpilogue + except AttributeError as e: + raise NotImplementedError( + f"EVT backend is not supported on Arch {arch_prefix}{arch}." + ) from e + + collective_epilogue = CollectiveEpilogue( + tile_description, + epilogue_schedule, + accum_type, + output_type, + fusion_callbacks, + ) + else: + collective_epilogue = Sm100CollectiveEpilogue( + tile_description=tile_description, + kernel_schedule=kernel_schedule, + epilogue_schedule=epilogue_schedule, + element_accumulator=accum_type, + element_d=output_type, + fusion_callbacks=fusion_callbacks, + ) + evt_name, evt_code = collective_epilogue.emit() + evt_args, arg_renames = _render_argument_type( + epilogue_functor, name_to_buffer, size_hint_fn + ) + return evt_name, evt_args, evt_code, arg_renames + + # Based off of + # https://github.com/NVIDIA/cutlass/blob/df18f5e4f5de76bed8be1de8e4c245f2f5ec3020/python/cutlass/epilogue/epilogue.py#L117 + # This is modified to enable directly passing the source code of the epilogue vs getting it from a bona-fide python function + # The reason for this is that inspect.getsource does not work with functions defined at runtime via exec/eval + def _trace( + fn_src: str, + example_tensors: dict[str, CutlassTensor], + cc: int, + **kwargs: Any, + ) -> EpilogueFunctor: + class EpilogueFunctor(PythonASTFrontend): + def __init__(self, cc: int, **kwargs: Any): + self.source = textwrap.dedent(fn_src) + super().__init__(cc, **kwargs) + + def parse( + self, + example_inputs: dict[str, CutlassTensor], + ) -> None: + self.example_inputs = example_inputs + self.ast = ast.parse(self.source) + # pyrefly: ignore [missing-attribute] + self.visit(self.ast) + + epilogue_functor = EpilogueFunctor(cc=cc, **kwargs) + epilogue_functor.trace(example_tensors) + return epilogue_functor + + def _render_argument_type( + epilogue_functor: EpilogueFunctor, + name_to_buffer: dict[str, Buffer], + size_hint_fn: Callable[[Expr | int], int], + ) -> tuple[str, EVTArgRenames]: + epilogue_thread_type = epilogue_functor.epilogue_thread_type + arg_renames = EVTArgRenames() + + # Fragile, but this is the only way to guarantee t is expected type because t is a local class + def is_nested_visitor_type(t: type) -> bool: + return ( + ".".join([t.__module__, t.__qualname__]) + == "cutlass_cppgen.backend.c_types.visitor_factory..VisitorType" + ) + + buffer = IndentedBuffer() + with buffer.set_tabwidth(2): + + def get_constant_value(name: str) -> float | int | None: + dag_ir = getattr(epilogue_functor, "dag_ir", None) + if dag_ir is not None: + try: + node_meta = dag_ir.get_node_meta(name) + except Exception: + node_meta = None + if node_meta is not None: + tensor_meta = getattr(node_meta, "tensor", None) + if isinstance(tensor_meta, dict) and tensor_meta.get( + "is_constant" + ): + return tensor_meta.get("tensor") + + # Immediate constants are encoded as "imm__k" where + # the first underscore in stands in for the decimal point + # (e.g. "imm_0_044715_k1" -> 0.044715). dag_ir meta is the primary + # source; this name parsing is a best-effort fallback. + if not name.startswith("imm_"): + return None + + value_part, _, _ = name[len("imm_") :].rpartition("_k") + if not value_part: + return None + try: + return float(value_part.replace("_", ".", 1)) + except ValueError: + return None + + def render_argument_type( + name: str, + t: CutlassArgType, + constant_value: float | int | None = None, + ) -> None: + if constant_value is None and name not in name_to_buffer: + # An imm_* node is an immediate constant whose value we + # failed to recover (dag_ir meta missing AND name parsing + # failed, e.g. an unsupported encoding). Emitting an empty + # struct here would silently drop the constant and produce a + # numerically wrong kernel, so fail loudly instead. + if name.startswith("imm_"): + raise RuntimeError( + f"Could not recover the value of immediate constant " + f"node {name!r} for the CUTLASS EVT epilogue. " + f"Refusing to emit an empty argument that would " + f"silently drop the constant." + ) + # Other non-buffer nodes (e.g. autogen_identity_*/compute_* + # placeholders) legitimately render as an empty struct, + # matching CUTLASS reference EVT kernels. + buffer.writeline(f"{{}}, /* {name} */") + return + if issubclass(t, ctypes.c_byte): + buffer.writeline(f"{{}}, /* {name} */") + else: + fields = [ + ( + fname, + _get_arg_from_node( + ty, + name_to_buffer.get(name), + size_hint_fn, + arg_renames, + constant_value, + ), + ) + for fname, ty in t._fields_ + ] + field_strs = [ + f"/* {fname} */ {str(field)}" for fname, field in fields + ] + buffer.writeline(f"{{{', '.join(field_strs)}}}, /* {name} */") + + def render_thread_type(name: str, t: CutlassArgType) -> None: + if is_nested_visitor_type(t): + buffer.writeline(f"{{ /* {name} */") + with buffer.indent(): + for name, inner_t in t._fields_: + render_thread_type(name, inner_t) + buffer.writeline("},") + else: + render_argument_type(name, t, get_constant_value(name)) + + # unroll the recursion once to address special case formatting + # namely, no ending comma and no indentation for the outermost thread type + buffer.writeline("{ /* thread */") + with buffer.indent(3): + if is_nested_visitor_type(epilogue_thread_type): + with buffer.indent(): + for name, inner_t in epilogue_thread_type._fields_: + render_thread_type(name, inner_t) + else: + render_argument_type("thread", epilogue_thread_type) + buffer.writeline("}") + + return buffer.getvalue(), arg_renames + + def _get_arg_from_node( + arg_ty: type, + node: Buffer | None, + size_hint_fn: Callable[[Expr | int], int], + arg_renames: EVTArgRenames, + constant_value: float | int | None = None, + ) -> str: + from ..template import CUTLASSTemplate + + # Today, arguments are either a pointer to the + # node's memory, a stride tuple, the datatype + # Once again, need to check for local class type for stride tuple + if ( + str(arg_ty) + == ".TupleType'>" + ): + if constant_value is not None: + raise NotImplementedError( + "Immediate constants do not use tuple argument types" + ) + DEFAULT_STRIDE_LEN = 3 + if node is None: + raise AssertionError("node must not be None for tuple argument types") + if len(node.get_layout().stride) > DEFAULT_STRIDE_LEN: + raise AssertionError( + f"expected stride length <= {DEFAULT_STRIDE_LEN}, " + f"got {len(node.get_layout().stride)}" + ) + stride = [size_hint_fn(x) for x in node.get_layout().stride] + for _ in range(DEFAULT_STRIDE_LEN - len(stride)): + stride.append(0) + + def render_stride(x: int) -> str: + # Handle EBO for 0 and 1 + if x == 0: + return "_0{}" + elif x == 1: + return "_1{}" + else: + return str(x) + + return f"{{{', '.join([render_stride(x) for x in stride])}}}" + + elif issubclass(arg_ty, ctypes.c_void_p): + if constant_value is not None: + return "nullptr" + if node is None: + raise AssertionError("node must not be None for pointer argument") + name = arg_renames.new_name(node.get_name()) + return f"({CUTLASSTemplate._DTYPE_TO_CUTLASS[node.get_layout().dtype]}*) ({name} + {name}_offset)" + elif ( + arg_ty in _CUTLASS_C_DTYPES + ): # Assumption: this is the element dtype, this holds for all cutlass ir nodes currently + if constant_value is not None: + return str(constant_value) + if node is None: + raise AssertionError("node must not be None for dtype argument") + return f"{CUTLASSTemplate._DTYPE_TO_CUTLASS[node.get_layout().dtype]}(0)" + elif issubclass(arg_ty, EmptyByte): + return "{}" + + raise NotImplementedError(f"Unsupported arg type: {arg_ty}") diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/gemm_operation_extensions.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/gemm_operation_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0aba5f1413c3fed6ced83f23b3e9895e140358 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/gemm_operation_extensions.py @@ -0,0 +1,418 @@ +# mypy: ignore-errors +from ..utils import try_import_cutlass + + +# copied / modified from original at +# https://github.com/NVIDIA/cutlass/blob/8783c41851cd3582490e04e69e0cd756a8c1db7f/tools/library/scripts/gemm_operation.py#L658 + +if try_import_cutlass(): + import enum + + from cutlass_library.gemm_operation import * # noqa: F403 + from cutlass_library.library import * # noqa: F403 + + _LOGGER = logging.getLogger(__name__) + + class EmitGemmUniversal3xInstanceWithEVT: + """Responsible for emitting a CUTLASS 3.x template definition""" + + def __init__(self, operation_suffix="", evt_name=None, device_type="cuda"): + self.operation_suffix = operation_suffix + self.includes = [ + "cutlass/cutlass.h", + "cutlass/gemm/gemm.h", + "cutlass/numeric_types.h", + "cutlass/gemm/kernel/gemm_universal.hpp", + "cutlass/gemm/collective/collective_builder.hpp", + "cutlass/epilogue/collective/collective_builder.hpp", + ] + self.builtin_epilogue_functor_template = """${epilogue_functor}< + ${element_d}, + ${element_epilogue}, + ${element_c}, + ${element_epilogue} + >""" + self.evt_name = evt_name + self.device_type = device_type + self.gemm_template = """ +using ${operation_name}_epilogue = +typename cutlass::epilogue::collective::CollectiveBuilder< + ${arch}, ${opcode_class_epi}, + cute::Shape, + cute::Shape<${cluster_shape_m}, ${cluster_shape_n}, ${cluster_shape_k}>, + ${epi_tile_mn}, + ${element_accumulator}, ${element_epilogue}, + ${element_c}, ${layout_c}, ${align_c}, + ${element_d}, ${layout_d}, ${align_d}, + ${epilogue_schedule}, + ${epilogue_functor} +>::CollectiveOp; + +${mixed_dtype_prepare_code} + +using ${operation_name}_mainloop = +typename cutlass::gemm::collective::CollectiveBuilder< + ${arch}, ${opcode_class_main}, + ${element_a}, ${layout_a}, ${align_a}, + ${element_b}, ${layout_b}, ${align_b}, + ${element_accumulator}, + cute::Shape, + cute::Shape<${cluster_shape_m}, ${cluster_shape_n}, ${cluster_shape_k}>, + ${stages}, + ${kernel_schedule} +>::CollectiveOp; + +// Gemm operator ${operation_name} +using ${operation_name}_base = cutlass::gemm::kernel::GemmUniversal< + ${problem_shape}, + ${operation_name}_mainloop, + ${operation_name}_epilogue, + ${tile_scheduler}>; + +// Define named type +struct ${operation_name} : +public ${operation_name}_base { }; + + """ + + # + def instance_template(self): + return """ +${compile_guard_start} +{ + using GemmKernel = cutlass::gemm::device::GemmUniversalAdapter<${operation_name}>; + manifest.append( + new ${gemm_kind}("${operation_name}")); +} +${compile_guard_end} + """ + + def emit_block_scale_epilogue_functor(self, operation): + block_scaled_template = """ + ${epilogue_functor}< + ${epi_vs}, + ${element_d}, + ${element_accumulator}, + ${element_sfd}, + ${layout_sfd}, + ${element_c}, + ${element_scalar} + > + """ + block_scaled_values = { + "epi_vs": str(operation.ScaleFactorVectorSize), + "element_d": str(DataTypeTag[operation.D.element]), + "element_sfd": str(DataTypeTag[operation.ScaleFactorD.element]), + "layout_sfd": LayoutTag[operation.ScaleFactorD.layout], + "epilogue_functor": EpilogueFunctor3xTag[ + EpilogueFunctor3x.LinearCombinationBlockScaleFactor + ], + "element_accumulator": str(DataTypeTag[operation.accumulator_type()]), + "element_scalar": str(DataTypeTag[operation.accumulator_type()]), + "element_c": str(DataTypeTag[operation.C.element]), + } + return SubstituteTemplate(block_scaled_template, block_scaled_values) + + @staticmethod + def pointerize_if_grouped(operation, layout): + return layout if not is_grouped(operation.gemm_kind) else layout + "* " + + @staticmethod + def problem_shape(operation): + gemm_shape_type = "cute::Shape" + grouped_gemm_shape_type = "cute::Shape" + grouped_gemm_shape_type = ( + "cutlass::gemm::GroupProblemShape<" + grouped_gemm_shape_type + ">" + ) + + return ( + gemm_shape_type + if not is_grouped(operation.gemm_kind) + else grouped_gemm_shape_type + ) + + def emit(self, operation): + """Given a gem operation, emits a template definition of the operation""" + + opcode_class_main = operation.tile_description.math_instruction.opcode_class + opcode_class_epi = opcode_class_main + + tile_shape = operation.tile_description.tile_shape + instruction_shape = ( + operation.tile_description.math_instruction.instruction_shape + ) + cluster_m = operation.tile_description.cluster_shape[0] + cluster_n = operation.tile_description.cluster_shape[1] + + tile_shape_m, tile_shape_n, tile_shape_k = tile_shape + + # account for static/dynamic cluster shapes + cta_m = tile_shape[0] // cluster_m if cluster_m > 0 else tile_shape[0] + cta_n = tile_shape[1] // cluster_n if cluster_n > 0 else tile_shape[1] + + # Shape passed to epilogue builder + is_sm100_kernel = operation.arch == 100 + if is_sm100_kernel: + cta_m_per_mma_instruction = ( + 2 if "2sm" in operation.procedural_name() else 1 + ) + if cluster_m <= 0: + cta_m = cta_m // cta_m_per_mma_instruction + + if opcode_class_main in [ + OpcodeClass.TensorOp, + OpcodeClass.BlockScaledTensorOp, + ]: + tile_shape_m = instruction_shape[0] + tile_shape_n = instruction_shape[1] + + # stage count set to zero indicates builder automatic stage selection + if operation.tile_description.stages > 0: + stage_count_string = f"cutlass::gemm::collective::StageCount<\ +{str(operation.tile_description.stages)}>" + else: + stage_count_string = ( + f"cutlass::gemm::collective::StageCountAutoCarveout(\ +sizeof(typename {str(operation.procedural_name())}_epilogue::SharedStorage))>" + ) + if self.device_type == "xpu": + stage_count_string = "cutlass::gemm::collective::StageCountAuto" + + epi_tile_mn = "cutlass::epilogue::collective::EpilogueTileAuto" + + ( + instance_layout_A, + instance_layout_B, + instance_layout_C, + instance_layout_D, + ) = ( + operation.A.layout, + operation.B.layout, + operation.C.layout, + operation.D.layout, + ) + + # 3.0 profiler integration only supports trivial epilogues for now + epilogue_vector_length = 1 + + # Support built-in epilogue functors or user-defined functions + if isinstance(operation.epilogue_functor, enum.Enum): + values = { + "element_epilogue": str(DataTypeTag[operation.element_epilogue]), + "epilogue_functor": EpilogueFunctor3xTag[ + operation.epilogue_functor + ], + } + epilogue_functor = SubstituteTemplate( + self.builtin_epilogue_functor_template, values + ) + + if ( + is_block_scaled(operation.gemm_kind) + and operation.ScaleFactorD.element != DataType.void + ): + epilogue_functor = self.emit_block_scale_epilogue_functor(operation) + else: + epilogue_functor = self.epilogue_functor.emit_declaration() + + if ( + is_block_scaled(operation.gemm_kind) + and operation.ScaleFactorD.element != DataType.void + ): + epilogue_functor = self.emit_block_scale_epilogue_functor(operation) + + # + # Cutlass3x complex kernels' ElementA(B) is a tuple in collective mainloop builder, + # e.g. cute::tuple, Transform : cute::identity / cute::conjugate. + element_a = ( + DataTypeTag[operation.A.element] + if not operation.is_complex() + else f"cute::tuple<{str(DataTypeTag[operation.A.element])},\ +{str(ComplexTransformTag3x[operation.A.complex_transform])}>" + ) + element_b = ( + DataTypeTag[operation.B.element] + if not operation.is_complex() + else f"cute::tuple<{str(DataTypeTag[operation.B.element])},\ +{str(ComplexTransformTag3x[operation.B.complex_transform])}>" + ) + epilogue_schedule_type = EpilogueScheduleTag[operation.epilogue_schedule] + + if opcode_class_main == OpcodeClass.BlockScaledTensorOp: + is_no_smem_epilogue = operation.epilogue_schedule in [ + EpilogueScheduleType.NoSmemWarpSpecialized1Sm, + EpilogueScheduleType.NoSmemWarpSpecialized2Sm, + ] + grouped = is_grouped(operation.gemm_kind) + if cta_n == 256 and operation.kernel_schedule == to_grouped_schedule( + KernelScheduleType.Nvf4TmaWarpSpecialized1SmSm100, grouped + ): + epi_tile_mn = "cute::Shape" + if not is_no_smem_epilogue: + epilogue_schedule_type = EpilogueScheduleTag[ + to_grouped_schedule( + EpilogueScheduleType.TmaWarpSpecialized1Sm, grouped + ) + ] + if cta_n == 256 and operation.kernel_schedule == to_grouped_schedule( + KernelScheduleType.Nvf4TmaWarpSpecialized2SmSm100, grouped + ): + epi_tile_mn = "cute::Shape" + if not is_no_smem_epilogue: + epilogue_schedule_type = EpilogueScheduleTag[ + to_grouped_schedule( + EpilogueScheduleType.TmaWarpSpecialized2Sm, grouped + ) + ] + element_a = f"cute::tuple<{str(element_a)},{str(DataTypeTag[operation.ScaleFactorA])}>" + element_b = f"cute::tuple<{str(element_b)},{str(DataTypeTag[operation.ScaleFactorB])}>" + + operation_name_str = operation.procedural_name() + layout_a_str = LayoutTag[instance_layout_A] + layout_b_str = LayoutTag[instance_layout_B] + mixed_dtype_prepare_code = "" + if operation.mixed_input_mode is not None: + A_dtype = operation.A.element + B_dtype = operation.B.element + A_dtype_bits = DataTypeSize[A_dtype] + B_dtype_bits = DataTypeSize[B_dtype] + is_A_dtype_narrow = A_dtype_bits < B_dtype_bits + if is_A_dtype_narrow: + narrow_dtype, wide_dtype = (A_dtype, B_dtype) + narrow_dtype_bits, wide_dtype_bits = (A_dtype_bits, B_dtype_bits) + else: + narrow_dtype, wide_dtype = (B_dtype, A_dtype) + narrow_dtype_bits, wide_dtype_bits = (B_dtype_bits, A_dtype_bits) + + narrow_tag = DataTypeTag[narrow_dtype] + wide_tag = DataTypeTag[wide_dtype] + scale_tag = DataTypeTag[wide_dtype] + zero_tag = DataTypeTag[wide_dtype] + + do_shuffle = False + value_shuffle_str = "" + if narrow_dtype_bits == 4 and wide_dtype_bits == 16: + value_shuffle_str = "cute::Layout, \ +cute::Stride>" + do_shuffle = True + if narrow_dtype_bits == 8 and wide_dtype_bits == 16: + value_shuffle_str = "cute::Layout, \ +cute::Stride>" + do_shuffle = True + do_shuffle = operation.mixed_input_shuffle and do_shuffle + + if do_shuffle: + if is_A_dtype_narrow: + stride_narrow_str = ( + f"cutlass::detail::TagToStrideA_t<{layout_a_str}>" + ) + layout_a_str = f"{operation_name_str}_LayoutNarrowReordered" + else: + stride_narrow_str = ( + f"cutlass::detail::TagToStrideB_t<{layout_b_str}>" + ) + layout_b_str = f"{operation_name_str}_LayoutNarrowReordered" + # The {operation_name_str}_ prefixes in mixed_dtype_prepare_code and + # layout_{a, b}_str are to prevent errors in Windows platform unity build + mixed_dtype_prepare_code = f""" + using {operation_name_str}_StrideNarrow = {stride_narrow_str}; + using {operation_name_str}_ValueShuffle = {value_shuffle_str}; + static constexpr int {operation_name_str}_NumShuffleAtoms = 1; + using {operation_name_str}_MmaAtomShape = \ +cute::Layout>>; + using {operation_name_str}_LayoutAtomQuant = \ +decltype(cutlass::compute_memory_reordering_atom<{wide_tag}, {operation_name_str}_MmaAtomShape, \ +{operation_name_str}_ValueShuffle>()); + using {operation_name_str}_LayoutNarrowReordered = \ +decltype(cute::tile_to_shape({operation_name_str}_LayoutAtomQuant{{}}, \ +cute::Layout, {operation_name_str}_StrideNarrow>{{}})); + """ + + mixed_input_modes_to_element = { + MixedInputMode.ConvertOnly: narrow_tag, + MixedInputMode.ScaleOnly: f"cute::tuple<{narrow_tag}, {scale_tag}>", + MixedInputMode.ScaleWithZeroPoint: f"cute::tuple<{narrow_tag}, {scale_tag}, {zero_tag}>", + } + narrow_element = mixed_input_modes_to_element.get( + operation.mixed_input_mode, narrow_tag + ) + + if narrow_dtype == DataType.s4 and ( + wide_dtype == DataType.e4m3 or wide_dtype == DataType.e5m2 + ): + narrow_element = ( + f"cute::tuple<{narrow_tag}, cutlass::Array<{scale_tag}, 8>>" + ) + + if is_A_dtype_narrow: + element_a = narrow_element + else: + element_b = narrow_element + + if self.evt_name: + epilogue_functor = self.evt_name + + if self.device_type == "xpu": + arch = f"cutlass::arch::Xe{operation.arch}" + else: + arch = f"cutlass::arch::Sm{operation.arch}" + + values = { + "operation_name": operation_name_str, + "operation_suffix": self.operation_suffix, + "problem_shape": self.problem_shape(operation), + "element_a": element_a, + "layout_a": self.pointerize_if_grouped(operation, layout_a_str), + "element_b": element_b, + "layout_b": self.pointerize_if_grouped(operation, layout_b_str), + "element_c": DataTypeTag[operation.C.element], + "layout_c": self.pointerize_if_grouped( + operation, LayoutTag[instance_layout_C] + ), + "element_d": DataTypeTag[operation.D.element], + "layout_d": self.pointerize_if_grouped( + operation, LayoutTag[instance_layout_D] + ), + "element_accumulator": DataTypeTag[operation.accumulator_type()], + "opcode_class_main": OpcodeClassTag[opcode_class_main], + "opcode_class_epi": OpcodeClassTag[opcode_class_epi], + "arch": arch, + "tile_shape_m": str(tile_shape_m), + "tile_shape_n": str(tile_shape_n), + "tile_shape_k": str(tile_shape_k), + "cluster_shape_m": "cute::_" + + str(operation.tile_description.cluster_shape[0]) + if operation.tile_description.cluster_shape[0] > 0 + else "int", + "cluster_shape_n": "cute::_" + + str(operation.tile_description.cluster_shape[1]) + if operation.tile_description.cluster_shape[1] > 0 + else "int", + "cluster_shape_k": "cute::_" + + str(operation.tile_description.cluster_shape[2]) + if operation.tile_description.cluster_shape[2] > 0 + else "int", + "instruction_shape_m": str(instruction_shape[0]), + "instruction_shape_n": str(instruction_shape[1]), + "instruction_shape_k": str(instruction_shape[2]), + "kernel_schedule": str(KernelScheduleTag[operation.kernel_schedule]), + "epilogue_schedule": str(epilogue_schedule_type), + "epi_tile_mn": epi_tile_mn, + "epilogue_functor": epilogue_functor, + "stages": stage_count_string, + "align_a": str(operation.A.alignment), + "align_b": str(operation.B.alignment), + "align_c": str(operation.C.alignment), + "align_d": str(operation.D.alignment), + "transform_a": ComplexTransformTag[operation.A.complex_transform], + "transform_b": ComplexTransformTag[operation.B.complex_transform], + "math_operation": MathOperationTag[ + operation.tile_description.math_instruction.math_operation + ], + "epilogue_vector_length": str(epilogue_vector_length), + "element_epilogue": str(DataTypeTag[operation.element_epilogue]), + "tile_scheduler": str(TileSchedulerTag[operation.tile_scheduler]), + "mixed_dtype_prepare_code": mixed_dtype_prepare_code, + } + + return SubstituteTemplate(self.gemm_template, values) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/python_evt.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/python_evt.py new file mode 100644 index 0000000000000000000000000000000000000000..ef472ff97f08e94369f3d7c5dd5b6e27f003f092 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/python_evt.py @@ -0,0 +1,663 @@ +import ast +import itertools +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +from os import linesep +from typing import Any + +import sympy + +import torch +import torch._inductor.virtualized as virtualized +from torch._inductor.ir import ComputedBuffer, Pointwise +from torch._inductor.ops_handler import DefaultHandler, WrapperHandler +from torch._inductor.scheduler import BaseSchedulerNode +from torch._inductor.utils import DelayReplaceLine, IndentedBuffer, OrderedSet +from torch._inductor.virtualized import OpsValue + +from ...virtualized import V + + +_ACCUMULATOR_ARG_NAME = "accum" + +# 1/sqrt(2) (M_SQRT1_2), the constant Inductor's gelu decomposition multiplies +# the input by before applying erf. +_GELU_ERF_INV_SQRT2 = 0.7071067811865476 + + +def _is_close_constant(node: ast.expr, value: float, tol: float = 1e-6) -> bool: + return ( + isinstance(node, ast.Constant) + and isinstance(node.value, (int, float)) + and not isinstance(node.value, bool) + and abs(float(node.value) - value) < tol + ) + + +def _mult_factors(node: ast.expr) -> list[ast.expr]: + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mult): + return _mult_factors(node.left) + _mult_factors(node.right) + return [node] + + +def _match_call(node: ast.expr, name: str) -> "ast.Call | None": + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == name + and len(node.args) == 1 + ): + return node + return None + + +def _same(a: ast.expr, b: ast.expr) -> bool: + return ast.dump(a) == ast.dump(b) + + +def _match_gelu_erf(node: ast.expr) -> "ast.expr | None": + """Match gelu's erf decomposition ``x * 0.5 * (1 + erf(x / sqrt(2)))`` and + return the inner argument ``x``. Matching is commutativity-aware for the + multiplications and the addition. + """ + factors = _mult_factors(node) + if len(factors) != 3: + return None + half = next((f for f in factors if _is_close_constant(f, 0.5)), None) + if half is None: + return None + rest = [f for f in factors if f is not half] + + def match_one_plus_erf(f: ast.expr) -> "ast.expr | None": + # Match ``1 + erf(x / sqrt(2))`` and return ``x``. + if not (isinstance(f, ast.BinOp) and isinstance(f.op, ast.Add)): + return None + operands = [f.left, f.right] + if not any(_is_close_constant(o, 1.0) for o in operands): + return None + erf_call = next( + (c for c in (_match_call(o, "erf") for o in operands) if c is not None), + None, + ) + if erf_call is None: + return None + erf_factors = _mult_factors(erf_call.args[0]) + if len(erf_factors) != 2 or not any( + _is_close_constant(g, _GELU_ERF_INV_SQRT2) for g in erf_factors + ): + return None + return next( + g for g in erf_factors if not _is_close_constant(g, _GELU_ERF_INV_SQRT2) + ) + + # ``x`` may itself be an addition (e.g. gelu(accum + bias)), so identify the + # ``1 + erf(...)`` factor by structure rather than assuming it is the only Add. + for i, f in enumerate(rest): + erf_x = match_one_plus_erf(f) + if erf_x is not None and _same(erf_x, rest[1 - i]): + return rest[1 - i] + return None + + +def _match_silu(node: ast.expr) -> "ast.expr | None": + """Match SiLU decomposition ``x / (1 + exp(0.0 - x))`` and return ``x``. + + Inductor decomposes silu(x) as x / (1 + exp(-x)). With our neg() op + emitting (0.0 - x), the generated code is: x / (1.0 + exp((0.0 - x))). + """ + # Must be a division: x / denom + if not (isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div)): + return None + x = node.left + denom = node.right + + # denom must be: 1.0 + exp(neg_x) or exp(neg_x) + 1.0 + if not (isinstance(denom, ast.BinOp) and isinstance(denom.op, ast.Add)): + return None + + operands = [denom.left, denom.right] + one = next((o for o in operands if _is_close_constant(o, 1.0)), None) + if one is None: + return None + exp_part = next((o for o in operands if o is not one), None) + if exp_part is None: + return None + + # exp_part must be exp(neg_x) + exp_call = _match_call(exp_part, "exp") + if exp_call is None: + return None + neg_x = exp_call.args[0] + + # neg_x must be (0.0 - x) where x matches the numerator + if ( + isinstance(neg_x, ast.BinOp) + and isinstance(neg_x.op, ast.Sub) + and _is_close_constant(neg_x.left, 0.0) + and _same(neg_x.right, x) + ): + return x + + # Also handle unary minus: -x + if isinstance(neg_x, ast.UnaryOp) and isinstance(neg_x.op, ast.USub): + if _same(neg_x.operand, x): + return x + + return None + + +@dataclass(frozen=True) +class _ActivationPattern: + # ``name`` must be a functor the CUTLASS EVT frontend binds natively (see + # ``ast_op_to_bindings`` in the cutlass python_ast frontend). + name: str + # Cheap substring guard so we only parse epilogues that may contain the + # decomposition (a primitive that the activation expands into). + trigger: str + match: Callable[[ast.expr], "ast.expr | None"] + + +# Activations that Inductor decomposes but CUTLASS can emit as a single functor. +# Add new entries here to re-fuse additional decomposed activations. +_ACTIVATION_PATTERNS: tuple[_ActivationPattern, ...] = ( + _ActivationPattern("gelu", "erf", _match_gelu_erf), + _ActivationPattern("silu", "0.0 -", _match_silu), +) + + +def _fuse_activations(code: str) -> str: + """Re-compose decomposed activations back into single CUTLASS functor calls. + + Inductor lowers activations such as ``aten.gelu`` into + primitive ops (``erf``, ``sigmoid``, ``mul``, ...) before reaching CUTLASS + codegen. The CUTLASS EVT frontend natively supports a number of activation + functors, so we pattern-match each decomposition (``_ACTIVATION_PATTERNS``) + and fold it back into a single activation node. This enables fusion for + activations whose primitives are unsupported (e.g. the ``erf`` in gelu) and + reduces the compute-node count for the rest. + """ + active = [p for p in _ACTIVATION_PATTERNS if p.trigger in code] + if not active: + return code + try: + tree = ast.parse(code) + except SyntaxError: + return code + if not tree.body or not isinstance(tree.body[0], ast.FunctionDef): + return code + func = tree.body[0] + + assigns: dict[str, ast.expr] = {} + for stmt in func.body: + if ( + isinstance(stmt, ast.Assign) + and len(stmt.targets) == 1 + and isinstance(stmt.targets[0], ast.Name) + ): + assigns[stmt.targets[0].id] = stmt.value + + _EMPTY_SET: OrderedSet[str] = OrderedSet() + + def inline(node: ast.expr, seen: OrderedSet[str] | None = None) -> ast.expr: + if seen is None: + seen = _EMPTY_SET + # Fully inline temporary assignments so the expression tree only refers + # to function parameters (accum / read buffers) and literal constants. + if isinstance(node, ast.Name) and node.id in assigns: + if node.id in seen: + return node + return inline(assigns[node.id], seen | OrderedSet([node.id])) + if isinstance(node, ast.BinOp): + return ast.BinOp( + left=inline(node.left, seen), + op=node.op, + right=inline(node.right, seen), + ) + if isinstance(node, ast.UnaryOp): + return ast.UnaryOp(op=node.op, operand=inline(node.operand, seen)) + if isinstance(node, ast.Call): + return ast.Call( + func=node.func, + args=[inline(a, seen) for a in node.args], + keywords=[], + ) + return node + + changed = False + for stmt in func.body: + if ( + isinstance(stmt, ast.Assign) + and len(stmt.targets) == 1 + and isinstance(stmt.targets[0], ast.Name) + ): + inlined = inline(stmt.value) + for pattern in active: + x = pattern.match(inlined) + if x is not None: + stmt.value = ast.Call( + func=ast.Name(id=pattern.name, ctx=ast.Load()), + args=[x], + keywords=[], + ) + changed = True + break + + if not changed: + return code + + # The folded assignment no longer references the decomposition temporaries, + # so drop the now-dead intermediates (the CUTLASS frontend builds a compute + # node for every assignment it sees). The frontend emits ``return`` dedented + # to module level (a sibling of the function def in Python 3.12), so seed + # liveness from every Return in the tree, not only those inside ``func.body``. + live: OrderedSet[str] = OrderedSet() + for node in ast.walk(tree): + if isinstance(node, ast.Return) and node.value is not None: + live.update(n.id for n in ast.walk(node.value) if isinstance(n, ast.Name)) + + kept: list[ast.stmt] = [] + for stmt in reversed(func.body): + if ( + isinstance(stmt, ast.Assign) + and len(stmt.targets) == 1 + and isinstance(stmt.targets[0], ast.Name) + ): + if stmt.targets[0].id not in live: + continue + live.update(n.id for n in ast.walk(stmt.value) if isinstance(n, ast.Name)) + kept.append(stmt) + func.body = list(reversed(kept)) + + folded = ast.unparse(ast.fix_missing_locations(tree)) + + # After dead-code elimination, any activation primitive that served as a + # trigger (e.g. erf) should no longer appear in the live code -- it was + # consumed by the pattern match and eliminated. If one still appears, the + # fold was incomplete (e.g. a standalone erf not part of a known pattern); + # bail out and return the original code so the CUTLASS frontend rejects the + # epilogue cleanly rather than emitting an unsupported functor. + for p in active: + if p.trigger in folded: + return code + + return folded + + +def scaled_mm_evt( + scale_A_name: str, scale_B_name: str, bias_name: str | None, output_name: str +) -> tuple[list[str], dict[str, Any], str]: + evt_read_names = [scale_A_name, scale_B_name] + var_name_to_buffer_name = {n: n for n in [scale_A_name, scale_B_name]} + var_name_to_buffer_name["D"] = output_name + var_name_to_buffer_name[_ACCUMULATOR_ARG_NAME] = output_name + expr = f"accum * {scale_A_name} * {scale_B_name}{linesep}" + if bias_name: + expr = f"({expr}) + {bias_name}" + evt_read_names.append(bias_name) + var_name_to_buffer_name[bias_name] = bias_name + + evt_py_code = f"def fn(accum, {','.join(evt_read_names)}):{linesep}\ + D = {expr}{linesep}\ + return D{linesep}" + + return evt_read_names, var_name_to_buffer_name, evt_py_code + + +class CutlassEVTOpsMixIn: + @staticmethod + def _infix_bin_op(op: str, a: str, b: str) -> str: + return f"{a} {op} {b}" + + @staticmethod + def _prefix_bin_op(op: str, a: str, b: str) -> str: + return f"{op}({a}, {b})" + + @staticmethod + def _prefix_un_op(op: str, a: str) -> str: + return f"{op}({a})" + + @staticmethod + def to_dtype( + x: str, + dtype: Any, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = False, + ) -> str: + return x + + @staticmethod + def constant(value: Any, dtype: Any) -> str: + # Return the constant as a Python float literal so the EVT python code + # string can embed it directly (e.g. for the 0.5 and 1/sqrt(2) factors + # in gelu). The CUTLASS EVT frontend will render it as a C++ scalar. + # Only numeric constants appear here (Inductor does not lower non-numeric + # constants into pointwise epilogues). + return str(float(value)) + + @staticmethod + def neg(x0: str) -> str: + # Use subtraction from zero instead of unary minus because the + # CUTLASS PythonASTFrontend has visit_BinOp but no visit_UnaryOp. + return f"(0.0 - {x0})" + + @staticmethod + def mul(x0: str, x1: str) -> str: + return CutlassEVTOpsMixIn._infix_bin_op("*", x0, x1) + + @staticmethod + def truediv(x0: str, x1: str) -> str: + return CutlassEVTOpsMixIn._infix_bin_op("/", x0, x1) + + @staticmethod + def ge(x0: str, x1: str) -> str: + raise NotImplementedError + + @staticmethod + def add(x0: str, x1: str) -> str: + return CutlassEVTOpsMixIn._infix_bin_op("+", x0, x1) + + @staticmethod + def relu(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("relu", x0) + + @staticmethod + def sigmoid(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("sigmoid", x0) + + @staticmethod + def sub(x0: str, x1: str) -> str: + return CutlassEVTOpsMixIn._infix_bin_op("-", x0, x1) + + @staticmethod + def tanh(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("tanh", x0) + + @staticmethod + def exp(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("exp", x0) + + @staticmethod + def erf(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("erf", x0) + + @staticmethod + def silu(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("silu", x0) + + +class MockCutlassHandler(CutlassEVTOpsMixIn, WrapperHandler): + """Passthrough handler for cutlass ops, used for running epilogue nodes for memory planning""" + + +class _AssignmentFormatter(DefaultHandler): + def __init__(self, parent_handler: "CutlassEVTCodegen"): + self.parent_handler = parent_handler + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + # Handle op dispatch here + if hasattr(self.parent_handler, name): + fn = getattr(self.parent_handler, name) + line = fn(*args, **kwargs) + if name in ("load", "store"): + return OpsValue(line) + else: + var = self.parent_handler._tmp_var() + line = DelayReplaceLine( + var, + lambda: "D" + if var == self.parent_handler.last_stored_var_name + else var, + f"{var} = {line}", + ) + self.parent_handler.body.writeline(line) + return OpsValue(var) + else: + raise NotImplementedError(name) + + +class CutlassEVTCodegen(CutlassEVTOpsMixIn): + """ + Notes: + * Used by CUTLASSGemmTemplate. + * This class should not be instantiated by users, it is intended to be used + by calling CutlassEVTCodegen.ir_to_evt_python_code(...) + which instantiates this class as an ops handler for virtualized.V.ops.[op-name] + * Extend this with more _op_ nodes to add support for new pointwise operations. + """ + + def __init__(self, accumulator_node_name: str, removed_buffers: OrderedSet[str]): + """ + + Initializes a CutlassEVTEpilogueArgumentFormatter object. Do not instantiate directly. + Use the CutlassEVTCodegen.ir_to_evt_python_code static method. + + Args: + accumulator_node_name: The name of the accumulator node which should contain + the Matmul result before fusion according to the IR graph. + epilogue_nodes: The list of scheduler nodes to be fused into the epilogue + """ + self.accumulator_node_name: str = accumulator_node_name # + self.body: IndentedBuffer = IndentedBuffer(1) # The body buffer for codegen + self.var_counter: Iterator[int] = itertools.count() + self.store_name_to_value: dict[ + str, OpsValue + ] = {} # Aliases for subexpression functors + self.reads: OrderedSet[str] = OrderedSet([]) + # Used for creating example tensors + self.var_name_to_buffer_name: dict[str, str] = { + _ACCUMULATOR_ARG_NAME: accumulator_node_name + } + self.removed_buffers: OrderedSet[str] = removed_buffers + self.cur_node: ComputedBuffer | None = None + self.name_to_buffer = V.graph.name_to_buffer | V.graph.graph_inputs + for name in V.graph.constants: + # pyrefly: ignore [unsupported-operation] + self.name_to_buffer[name] = V.graph.add_tensor_constant( + V.graph.constants[name], name + ) + self.is_D_assigned = False + self.D_var_name = None + + if accumulator_node_name not in removed_buffers: + # cannot return accumulator directly, so alias it + var = self._tmp_var() + self.body.writeline(f"{var} = {_ACCUMULATOR_ARG_NAME}") + self.store(accumulator_node_name, value=OpsValue(var)) + + @staticmethod + def ir_to_evt_python_code( + cutlass_template_node_name: str, + epilogue_nodes: list[BaseSchedulerNode], + removed_buffers: OrderedSet[str], + fn_name: str = "fn", + as_standalone_function: bool = False, + ) -> tuple[list[str], list[str], dict[str, Any], str]: + codegen = CutlassEVTCodegen(cutlass_template_node_name, removed_buffers) + handler = _AssignmentFormatter(codegen) + + with virtualized.V.set_ops_handler(handler): + for s_node in epilogue_nodes: + node = s_node.node + if not isinstance(node, ComputedBuffer): + raise AssertionError( + f"expected node to be a ComputedBuffer, got {type(node)}" + ) + with codegen.set_cur_node(node): + index_vars = CutlassEVTCodegen.get_index_vars(node) + node.get_store_function()(index_vars) + + codegen.finalize() + + return ( + codegen.get_reads(), + codegen.get_writes(), + codegen.get_renames(), + codegen.get_value( + fn_name=fn_name, + as_standalone_function=as_standalone_function, + ), + ) + + def get_value( + self, + fn_name: str = "fn", + as_standalone_function: bool = False, + ) -> str: + ret = self._render_return_statement() + if as_standalone_function: + ret = " " + ret + return _fuse_activations( + linesep.join( + [ + self._render_input_signature(fn_name), + self.body.getvalue(), + ret, + ] + ) + ) + + def finalize(self) -> None: + # Rename the last store to D + # no other code references this store + # to workaround https://github.com/NVIDIA/cutlass/issues/2288 + # Note: the delayed line will automatically rewrite the last assignment to + # be to D + buffer_name = self.var_name_to_buffer_name[self.last_stored_var_name] + self.var_name_to_buffer_name.pop(self.last_stored_var_name) + self.var_name_to_buffer_name["D"] = buffer_name + self.store_name_to_value[buffer_name] = OpsValue("D") + + @contextmanager + def set_cur_node(self, node: ComputedBuffer) -> Generator[None, Any, Any]: + prev_node = self.cur_node + try: + self.cur_node = node + yield + finally: + self.cur_node = prev_node + + def get_renames(self) -> dict[str, str]: + return dict(self.var_name_to_buffer_name) + + def get_reads(self) -> list[str]: + return list(self.reads.difference(self.store_name_to_value.keys())) + + def get_writes(self) -> list[str]: + return list(self.store_name_to_value.keys()) + + def load(self, name: str, index: Any) -> str: + self._check_indexing(name, index) + if name in self.store_name_to_value: + return self.store_name_to_value[name].value + elif name == self.accumulator_node_name: + return _ACCUMULATOR_ARG_NAME + else: + self.reads.add(name) + self.var_name_to_buffer_name[name] = name + return name + + def store( + self, name: Any, index: Any = None, value: Any = None, mode: Any = None + ) -> None: + if name not in self.removed_buffers: + if index: + self._check_indexing(name, index) + if value.value == _ACCUMULATOR_ARG_NAME: + raise AssertionError("Cannot store accumulator arg name") + self.var_name_to_buffer_name[value.value] = name + self.store_name_to_value[name] = value + self.last_stored_var_name = value.value + return None + + def _get_cur_node(self) -> ComputedBuffer: + if not self.cur_node: + raise AssertionError("expected cur_node to be set") + return self.cur_node + + @staticmethod + def get_index_vars(node: ComputedBuffer) -> Sequence[sympy.Expr]: + data = node.data + # TODO mlazos: relax this, cutlass supports reductions and other ops + if not isinstance(data, Pointwise): + raise AssertionError(f"expected data to be Pointwise, got {type(data)}") + return data._index(data.ranges) + + def _get_current_index_vars(self) -> Sequence[sympy.Expr]: + return self.get_index_vars(self._get_cur_node()) + + def _check_indexing(self, name: str, index: sympy.Expr) -> None: + # We only support indexing that matches the layout today because + # CUTLASS doesn't support arbitrary indexing + buffer_name = ( + self.accumulator_node_name if name == _ACCUMULATOR_ARG_NAME else name + ) + buffer = self.name_to_buffer[buffer_name] + index_strides = V.graph.sizevars.stride_vars( + index, self._get_current_index_vars() + ) + stride = buffer.get_layout().stride + if not self._stride_compatible(stride, index_strides): + raise NotImplementedError( + f"Unsupported indexing for {name} with index {index}, index strides {index_strides}, and layout stride {stride}" + ) + + def _stride_compatible( + self, left: Iterable[sympy.Expr], right: Iterable[sympy.Expr] + ) -> bool: + def _provably_equal_or_zero(a: sympy.Expr, b: sympy.Expr) -> bool: + # sympy.Eq can return an unevaluated Equality object; only accept + # cases sympy can prove true. + if a == b: + return True + if V.graph.sizevars.statically_known_equals(a, b): + return True + if V.graph.sizevars.statically_known_equals(a, 0): + return True + if V.graph.sizevars.statically_known_equals(b, 0): + return True + return ( + sympy.Eq(a, b) is sympy.true + or sympy.Eq(a, 0) is sympy.true + or sympy.Eq(b, 0) is sympy.true + ) + + left_list = list(left) + right_list = list(right) + # Same length: direct comparison + if len(left_list) == len(right_list): + return all( + _provably_equal_or_zero(lv, rv) for lv, rv in zip(left_list, right_list) + ) + # Different lengths: allow compatible reshapes where trailing strides match. + # This handles view/reshape between template output and consumer, e.g., + # buffer strides [3072, 1] vs index strides [1572864, 3072, 1] + shorter, longer = ( + (left_list, right_list) + if len(left_list) <= len(right_list) + else (right_list, left_list) + ) + n = len(shorter) + # Check that the trailing strides match + return all( + _provably_equal_or_zero(shorter[-(i + 1)], longer[-(i + 1)]) + for i in range(n) + ) + + def _render_input_signature(self, fn_name: str = "fn") -> str: + arguments = ", ".join( + [_ACCUMULATOR_ARG_NAME] + + [name for name in self.reads if name != self.accumulator_node_name] + ) + return f"def {fn_name}({arguments}):" + + def _render_return_statement(self) -> str: + return_vars = OrderedSet( + op_v.value for op_v in self.store_name_to_value.values() + ) + if "D" not in return_vars: + raise AssertionError(f"expected 'D' in return_vars, got {return_vars}") + return f"return {', '.join(return_vars)}" + + def _tmp_var(self) -> str: + return f"tmp_{next(self.var_counter)}" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..08be591d5d70b0b592e83ab5aa6544b18fb51a15 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/scheduling.py @@ -0,0 +1,389 @@ +# mypy: allow-untyped-defs +import hashlib +import logging +from collections.abc import Sequence +from typing import cast, TypeGuard + +import sympy + +from torch._inductor.codegen.cutlass.python_evt import ( + CutlassEVTCodegen, + MockCutlassHandler, +) +from torch._inductor.utils import Placeholder +from torch.utils._ordered_set import OrderedSet + +from ...._dynamo.utils import counters +from ... import config +from ...codecache import code_hash, get_path +from ...ir import Buffer, ComputedBuffer, CUTLASSTemplateBuffer, Pointwise +from ...scheduler import ( + BaseSchedulerNode, + BaseScheduling, + FusedSchedulerNode, + SchedulerNode, + WhyNoFuse, +) +from ...utils import get_fused_kernel_name, get_kernel_metadata, sympy_product +from ...virtualized import V +from ..common import BackendFeature, IndentedBuffer + + +log = logging.getLogger(__name__) + + +class WhyNoFuseNames(WhyNoFuse): + def __init__(self, name1: str, name2: str) -> None: + self.name1 = name1 + self.name2 = name2 + + +class CUTLASSScheduling(BaseScheduling): + """ + Partial Scheduling implementation for cutlass C++ Kernels. + This class is intended to be used in combination with TritonScheduling, + and delegated to by CUDACombinedScheduling/XPUCombinedScheduling. + + It handles fusion decisions and cutlass C++ specific template code generation. + """ + + @classmethod + def get_backend_features(cls, device) -> OrderedSet[BackendFeature]: + return OrderedSet() + + def group_fn(self, sizes): + return tuple(V.graph.sizevars.simplify(sympy_product(s)) for s in sizes) + + @staticmethod + def is_cutlass_template(node: BaseSchedulerNode) -> TypeGuard[SchedulerNode]: + return isinstance(node, SchedulerNode) and isinstance( + node.node, CUTLASSTemplateBuffer + ) + + def is_cutlass_fused_template(self, node: BaseSchedulerNode) -> bool: + return isinstance(node, FusedSchedulerNode) and self.is_cutlass_template(node) + + def can_fuse_vertical( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if self.is_cutlass_template(node1) and isinstance(node2, BaseSchedulerNode): + if not node1.node: + raise AssertionError("node1.node should not be None") + return self._can_fuse_epilogue_impl( + cast(CUTLASSTemplateBuffer, node1.node), + [], + node2, # type: ignore[arg-type] + ) + elif self.is_cutlass_fused_template(node1) and isinstance( + node2, BaseSchedulerNode + ): + if not node1.node: + raise AssertionError("node1.node should not be None") + if not node2.node: + raise AssertionError("node2.node should not be None") + fnode1 = cast(FusedSchedulerNode, node1) + return self._can_fuse_epilogue_impl( + fnode1.get_template_node(), # type: ignore[arg-type] + self._unwrap_epilogue_nodes(fnode1), + node2, # type: ignore[arg-type] + ) + + return False + + def define_kernel(self, src_code: str, node_schedule) -> str: + wrapper = V.graph.wrapper_code + if src_code in wrapper.src_to_kernel: + kernel_name = wrapper.src_to_kernel[src_code] + else: + fused_name = ( + get_fused_kernel_name(node_schedule, config.triton.descriptive_names) + if config.triton.descriptive_names + else "" + ) + + # use the original src_code as the key + kernel_hash = hashlib.sha256(src_code.encode("utf-8")).hexdigest()[:8] + if fused_name == "fused": + # no EVT kernel, use the original kernel name + kernel_name = f"cutlass_{kernel_hash}" + else: + kernel_name = f"cutlass_{fused_name}_{kernel_hash}" + wrapper.src_to_kernel[src_code] = kernel_name + src_code = src_code.replace(str(Placeholder.KERNEL_NAME), kernel_name) + + _, _, kernel_path = get_path(code_hash(src_code), "py") + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline(f"async_compile.{V.graph.device_type}(r'''") + compile_wrapper.splice(src_code, strip=True) + compile_wrapper.writeline( + f"''', 'so', aot_compile={str(V.graph.aot_mode)})" + ) + + metadata_comment = f"# kernel path: {kernel_path}" + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + metadata_comment += "\n" + origins + "\n" + detailed_origins + wrapper.define_kernel( + kernel_name, compile_wrapper.getvalue(), metadata_comment + ) + + # For JIT cpp_wrapper, the kernel call site emits a bare + # `extern "C"` symbol reference; compile the .so now so the + # wrapper compile can link against it via extra_flags. + # Autotune compiled a .so for the unfused kernel name + # (e.g. cutlass_), but at codegen time the kernel name + # gains a descriptive prefix (cutlass_fused_mm_), so the + # exported symbol differs and we need a fresh compile. + if V.graph.cpp_wrapper and not V.graph.aot_mode: + from ...codecache import CUDACodeCache, XPUCodeCache + + codecache_cls = ( + XPUCodeCache if V.graph.device_type == "xpu" else CUDACodeCache + ) + so_path, _, _ = codecache_cls.compile(src_code, "so") + wrapper.external_kernel_libs.add(so_path) + return kernel_name + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + ): + """ + Codegen a cutlass template, possibly with fused epilogues + """ + counters["inductor"]["cutlass_epilogue_fusion_counter"] += len(epilogue_nodes) + if not self.is_cutlass_template(template_node): + raise AssertionError( + "Template node passed to CUTLASSScheduling.codegen_template must be a SchedulerNode that wraps a CUTLASSTemplateBuffer" + ) + _, (_numel, rnumel) = template_node.group + if rnumel != 1: + raise AssertionError(f"expected rnumel == 1, got {rnumel}") + ctb: CUTLASSTemplateBuffer = cast(CUTLASSTemplateBuffer, template_node.node) + epilogue_ir_nodes: list[Buffer] = [n.node for n in epilogue_nodes] # type: ignore[misc] + if not all(isinstance(n, ComputedBuffer) for n in epilogue_ir_nodes): + raise AssertionError( + "Epilogue nodes must all be instances of ir.ComputedBuffer" + ) + kernel, render = ctb.make_kernel_render( # type: ignore[misc] + ctb, epilogue_nodes=epilogue_nodes + ) + with kernel: + for node in [template_node, *epilogue_nodes]: + node.mark_run() + + # typically there is a codegen pass which runs after mark_run + # for this kernel we've already generated the C++ code, but we still + # need to let the kernel know about loads/stores that occur in the fused + # kernel for memory planning to properly optimize allocations + ctb.emulate_store_fn() + for node in epilogue_ir_nodes: + with V.set_ops_handler(MockCutlassHandler(V.get_ops_handler())): + # Not sure why we need to do this again + if not isinstance(node, ComputedBuffer): + raise AssertionError( + f"expected ComputedBuffer, got {type(node)}" + ) + node.get_store_function()(CutlassEVTCodegen.get_index_vars(node)) + + with V.set_kernel_handler(kernel): + src_code = render() + node_schedule = [template_node, *epilogue_nodes] + kernel_name = self.define_kernel(src_code, node_schedule) + + # debug printing values of intermediate tensors + _, call_args, arg_signatures, _ = kernel.args.python_argdefs() + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + call_args, kernel_name, arg_signatures, kernel + ) + with debug_printer_manager: + self.codegen_comment(node_schedule, kernel_name) + kernel.call_kernel(kernel_name, ctb) + + V.graph.removed_buffers |= kernel.removed_buffers + self.free_buffers_in_scheduler() + + @staticmethod + def _unwrap_epilogue_nodes( + fused_node: FusedSchedulerNode, + ) -> list[BaseSchedulerNode]: + nodes = fused_node.get_nodes() + template_node = fused_node.get_template_node() + if not all(n.node is not None for n in nodes): + raise AssertionError("All epilogue nodes should have an IRNode") + # pyrefly: ignore [redundant-cast] + return cast( + list[BaseSchedulerNode], [n for n in nodes if n.node is not template_node] + ) + + @staticmethod + def _is_compatible_reshape( + template_size: Sequence[sympy.Expr], node_size: Sequence[sympy.Expr] + ) -> bool: + """ + Check if node_size is a compatible reshape of template_size. + This allows cases like template [8192, 3072] with node [16, 512, 3072] + where [16*512, 3072] == [8192, 3072] (prefix dims multiply to match). + """ + if len(node_size) <= len(template_size): + return False + # Try to merge consecutive node dims to reconstruct template dims + t_idx = 0 + n_idx = 0 + + def _matches_template_dim(lhs: sympy.Expr, rhs: sympy.Expr) -> bool: + # Fast path for concrete/static equality before invoking simplify. + if lhs == rhs: + return True + if V.graph.sizevars.statically_known_equals(lhs, rhs): + return True + return sympy.simplify(lhs - rhs) == 0 + + while t_idx < len(template_size) and n_idx < len(node_size): + product = node_size[n_idx] + n_idx += 1 + # Try multiplying consecutive node dims until we match template dim + while not _matches_template_dim(product, template_size[t_idx]): + if n_idx >= len(node_size): + return False + product = product * node_size[n_idx] + n_idx += 1 + t_idx += 1 + return t_idx == len(template_size) and n_idx == len(node_size) + + def _can_fuse_epilogue_impl( + self, + cutlass_template_buffer: CUTLASSTemplateBuffer, + existing_epilogue_nodes: list[BaseSchedulerNode], + node_to_fuse: BaseSchedulerNode, + ) -> bool: + """ + Check if the given node can be fused with the epilogue. At the moment, Kernels + support fusion with Pointwise operations, wrapped in (named) ComputedBuffer nodes. + + Args: + cutlass_template_buffer : A CUTLASSTemplateBuffer object representing the CUTLASS template and it's result buffer + existing_epilogue_nodes : List[SchedulerNode]: The list of already fused epilogue nodes. + node_to_fuse: The SchedulerNode node to be checked if it can be fused with the epilogue. + Returns: + - bool: True if the given node can be fused with the epilogue, False otherwise. + + """ + why = WhyNoFuseNames( + cutlass_template_buffer.get_name(), node_to_fuse.get_name() + ) + + scheduler_nodes_to_fuse = node_to_fuse.get_nodes() + + if not isinstance(cutlass_template_buffer, CUTLASSTemplateBuffer): + raise AssertionError( + f"expected CUTLASSTemplateBuffer, got {type(cutlass_template_buffer)}" + ) + + # Checks on constituent nodes + for s_node in scheduler_nodes_to_fuse: + node = s_node.node + + if not isinstance(node, ComputedBuffer): + why(f"{node} is not a ComputedBuffer") + return False + elif not isinstance(node.data, Pointwise): + why(f"{node} is not a Pointwise op") + return False + elif not node.get_computed_buffer_name(): # type: ignore[attr-defined] + why(f"{node} does not have a computed buffer name") + return False + + name = node.get_computed_buffer_name() # type: ignore[attr-defined] + # dtype can differ, and strides can differ as long as they are broadcastable + # Allow compatible reshapes (e.g., [8192, 3072] vs [16, 512, 3072]) + # where the node's shape is a split of the template's shape + if node.get_size() != cutlass_template_buffer.get_size(): + if not self._is_compatible_reshape( + cutlass_template_buffer.get_size(), node.get_size() + ): + why( + f"{name}'s size: {node.get_size()} differs from {cutlass_template_buffer.get_name()}'s \ +size: {cutlass_template_buffer.get_size()}" + ) + return False + + if not ( + len(existing_epilogue_nodes) + or cutlass_template_buffer.get_name() + in OrderedSet([rd.name for rd in node_to_fuse.read_writes.reads]) + ): + raise AssertionError( + "First epilogue node must read from cutlass template buffer" + ) + + if node_to_fuse.has_aliasing_or_mutation(): + why(f"{node_to_fuse.get_name()} has aliasing or mutation") + return False + elif node_to_fuse.is_reduction(): + why( + f"{node_to_fuse.get_name()} is a reduction which is not yet supported by EVT" + ) + return False + elif ( + not config.cutlass.cutlass_epilogue_fusion_enabled + or not config.epilogue_fusion + ): + why("cutlass epilogue fusion is not enabled") + return False + elif not cutlass_template_buffer.supports_epilogue_fusion: + why("epilogue fusion is only supported for TMA-enabled gemm ops") + return False + + try: + from torch._inductor.codegen.cutlass.python_evt import CutlassEVTCodegen + + read_names, _, _, _ = CutlassEVTCodegen.ir_to_evt_python_code( + cutlass_template_buffer.get_name(), + existing_epilogue_nodes + list(node_to_fuse.get_nodes()), + OrderedSet(), + ) + + except NotImplementedError as e: + not_implemented_op = str(e) + if not_implemented_op.startswith("_op_"): + not_implemented_op = not_implemented_op[4:] + why( + f"Cannot fuse epilogue node {node_to_fuse} into {cutlass_template_buffer.name}, \ +likely due to unsupported operation: {not_implemented_op}" + ) + return False + else: # Likely due to unsupported dtype. + why( + f"Cannot fuse epilogue node {node_to_fuse} into {cutlass_template_buffer.name}. \ +Reason: {not_implemented_op}" + ) + return False + + # An external read whose shape is a compatible reshape of the 2D GEMM + # output is normalized to the template shape during rendering, but only + # when it is contiguous (the row-major flatten is memory-equivalent). + # A non-contiguous compatible-reshape read cannot be safely flattened, + # and EVT would fail shape propagation against the (1, M, N) accumulator, + # so reject the fusion in that case. + template_size = cutlass_template_buffer.get_size() + all_bufs = V.graph.name_to_buffer | V.graph.graph_inputs + for read_name in read_names: + buf = all_bufs.get(read_name) + if ( + buf is not None + and self._is_compatible_reshape(template_size, buf.get_size()) + and not buf.get_layout().is_contiguous() + ): + why( + f"external read {read_name} with size {buf.get_size()} is a " + f"non-contiguous compatible reshape of template size " + f"{template_size}, which CUTLASS EVT cannot align to the " + f"accumulator shape" + ) + return False + + return True diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/serialization.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..5f96721281770e11f19e0bba2c0d7a89e015bd7e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/serialization.py @@ -0,0 +1,508 @@ +# mypy: allow-untyped-defs +import functools +import json +from enum import Enum +from typing import Any, Optional + +from torch._inductor.codegen.cutlass.utils import try_import_cutlass + + +class CUTLASSOperationSerializer: + """Serializes and deserializes CUTLASS GEMM operations to/from JSON. + + Handles GemmOperation objects and their nested components (TileDescription, TensorDescription). + """ + + # not used, but keeping in case we want to generalize the serializer + _SUPPORTED_CLASSES: list[str] = [ + "GemmOperation", + "GemmKind", + "TileDescription", + "TensorDescription", + "DataType", + "EpilogueFunctor", + "EpilogueFunctor3x", + "SwizzlingFunctor", + "KernelScheduleType", + "EpilogueScheduleType", + "TileSchedulerType", + ] + + @classmethod + def serialize(cls, operation: "GemmOperation") -> str: # type: ignore[name-defined] # noqa: F821 + """Serialize a GEMM operation to JSON string. + + Args: + operation: GemmOperation object + + Returns: + str: JSON string representation of the operation + """ + if operation.__class__.__qualname__ != "GemmOperation": + raise AssertionError( + "Only GemmOperation objects are supported via the main API" + ) + return json.dumps(cls._gemm_operation_to_json(operation)) + + @classmethod + def deserialize(cls, json_str: str) -> "GemmOperation": # type: ignore[name-defined] # noqa: F821 + """Deserialize JSON string to a GEMM operation. + + Args: + json_str: JSON string of a GEMM operation + + Returns: + GemmOperation: Reconstructed operation + """ + json_dict = json.loads(json_str) + return cls._json_to_gemm_operation(json_dict) + + @classmethod + def _gemm_operation_to_json(cls, operation: "GemmOperation") -> dict[str, Any]: # type: ignore[name-defined] # noqa: F821 + """Convert GemmOperation to JSON-serializable dict. + + Args: + operation: GemmOperation object + + Returns: + dict: Dictionary representation + """ + from cutlass_library.library import TensorDescription + + # Create the main dictionary with required and optional parameters + result = { + # Required parameters + "gemm_kind": cls._enum_to_json(operation.gemm_kind), + "arch": operation.arch, + "tile_description": cls._tile_description_to_json( + operation.tile_description + ), + "A": cls._tensor_description_to_json(operation.A), + "B": cls._tensor_description_to_json(operation.B), + "C": cls._tensor_description_to_json(operation.C), + "element_epilogue": cls._enum_to_json(operation.element_epilogue), + # Optional parameters + "epilogue_functor": cls._enum_to_json(operation.epilogue_functor), + "swizzling_functor": cls._enum_to_json(operation.swizzling_functor), + "D": cls._tensor_description_to_json(operation.D) if operation.D else None, + "kernel_schedule": cls._enum_to_json(operation.kernel_schedule), + "epilogue_schedule": cls._enum_to_json(operation.epilogue_schedule), + "tile_scheduler": cls._enum_to_json(operation.tile_scheduler), + } + + # Process optional attributes + optional_attrs = [ + "mixed_input_mode", + "mixed_input_shuffle", + "ScaleFactorA", + "ScaleFactorB", + "ScaleFactorD", + "ScaleFactorMVecSize", + "ScaleFactorNVecSize", + "ScaleFactorKVecSize", + "ScaleFactorVectorSize", + "is_3x", + ] + + for attr in optional_attrs: + if not hasattr(operation, attr): + continue + + value = getattr(operation, attr) + + if isinstance(value, TensorDescription): + result[attr] = cls._tensor_description_to_json(value) + elif isinstance(value, Enum): + result[attr] = cls._enum_to_json(value) + else: + result[attr] = value + + return result + + @classmethod + def _json_to_gemm_operation(cls, json_dict: dict[str, Any]) -> "GemmOperation": # type: ignore[name-defined] # noqa: F821 + """Convert JSON dict to GemmOperation object. + + Args: + json_dict: Dictionary representation + + Returns: + GemmOperation: Reconstructed object + """ + from cutlass_library import DataType + from cutlass_library.gemm_operation import GemmKind, GemmOperation + from cutlass_library.library import ( + EpilogueFunctor, + EpilogueFunctor3x, + EpilogueScheduleType, + KernelScheduleType, + MixedInputMode, + SwizzlingFunctor, + TileSchedulerType, + ) + + # Extract constructor parameters from the JSON dictionary + gemm_kind = cls._json_to_enum(json_dict["gemm_kind"], GemmKind) + arch = json_dict["arch"] + tile_description = cls._json_to_tile_description(json_dict["tile_description"]) + A = cls._json_to_tensor_description(json_dict.get("A"), "A") + B = cls._json_to_tensor_description(json_dict.get("B"), "B") + C = cls._json_to_tensor_description(json_dict.get("C"), "C") + element_epilogue = cls._json_to_enum(json_dict["element_epilogue"], DataType) + + # Get optional parameters with defaults + epilogue_functor = cls._json_to_enum( + json_dict.get("epilogue_functor"), + EpilogueFunctor3x if json_dict.get("is_3x") else EpilogueFunctor, + ) + swizzling_functor = cls._json_to_enum( + json_dict.get("swizzling_functor"), SwizzlingFunctor + ) + D = cls._json_to_tensor_description(json_dict.get("D"), "D") + kernel_schedule = cls._json_to_enum( + json_dict.get("kernel_schedule"), KernelScheduleType + ) + epilogue_schedule = cls._json_to_enum( + json_dict.get("epilogue_schedule"), EpilogueScheduleType + ) + tile_scheduler = cls._json_to_enum( + json_dict.get("tile_scheduler"), TileSchedulerType + ) + + mixed_input_mode = cls._json_to_enum( + json_dict.get("mixed_input_mode"), MixedInputMode + ) + mixed_input_shuffle = json_dict.get("mixed_input_shuffle", False) + + # Scale factors + ScaleFactorA = cls._json_to_enum(json_dict.get("ScaleFactorA"), DataType) + ScaleFactorB = cls._json_to_enum(json_dict.get("ScaleFactorB"), DataType) + + ScaleFactorD = None + if "ScaleFactorD" in json_dict and "ScaleFactorVectorSize" in json_dict: + ScaleFactorD = { + "tensor": cls._json_to_tensor_description( + json_dict.get("ScaleFactorD"), "ScaleFactorD" + ), + "vector_size": json_dict.get("ScaleFactorVectorSize"), + } + + ScaleFactorMVecSize = json_dict.get("ScaleFactorMVecSize") + ScaleFactorNVecSize = json_dict.get("ScaleFactorNVecSize") + ScaleFactorKVecSize = json_dict.get("ScaleFactorKVecSize") + + # Create the GemmOperation with the extracted parameters + operation = GemmOperation( + gemm_kind=gemm_kind, + arch=arch, + tile_description=tile_description, + A=A, + B=B, + C=C, + element_epilogue=element_epilogue, + epilogue_functor=epilogue_functor, + swizzling_functor=swizzling_functor, + D=D, + kernel_schedule=kernel_schedule, + epilogue_schedule=epilogue_schedule, + tile_scheduler=tile_scheduler, + mixed_input_mode=mixed_input_mode, + mixed_input_shuffle=mixed_input_shuffle, + ScaleFactorA=ScaleFactorA, + ScaleFactorB=ScaleFactorB, + ScaleFactorD=ScaleFactorD, + ScaleFactorMVecSize=ScaleFactorMVecSize, + ScaleFactorNVecSize=ScaleFactorNVecSize, + ScaleFactorKVecSize=ScaleFactorKVecSize, + ) + + return operation + + @classmethod + @functools.lru_cache(None) + def _tile_description_to_json(cls, tile_desc: "TileDescription") -> str: # type: ignore[name-defined] # noqa: F821 + """ + Convert TileDescription to JSON string. + + Args: + tile_desc: TileDescription object + + Returns: + str: JSON string representation + """ + + # Create the main dictionary with field names matching TileDescription constructor parameters + result = { + "threadblock_shape": tile_desc.threadblock_shape, + "stages": tile_desc.stages, + "warp_count": tile_desc.warp_count, + "math_instruction": cls._math_instruction_to_json( + tile_desc.math_instruction + ), + "min_compute": tile_desc.minimum_compute_capability, # Store as min_compute for constructor + "max_compute": tile_desc.maximum_compute_capability, # Store as max_compute for constructor + "cluster_shape": tile_desc.cluster_shape, + "explicit_vector_sizes": tile_desc.explicit_vector_sizes, + } + + # Add tile_shape if it exists and differs from threadblock_shape + if ( + hasattr(tile_desc, "tile_shape") + and tile_desc.tile_shape != tile_desc.threadblock_shape + ): + result["tile_shape"] = tile_desc.tile_shape + + return json.dumps(result) + + @classmethod + @functools.lru_cache(None) + def _json_to_tile_description( + cls, json_dict: str | None + ) -> Optional["TileDescription"]: # type: ignore[name-defined] # noqa: F821 + """ + Convert JSON dict to TileDescription object. + + Args: + json_dict: Dictionary representation + + Returns: + TileDescription: Reconstructed object + """ + if json_dict is None: + return None + + tile_dict = json.loads(json_dict) + + from cutlass_library.library import TileDescription + + math_instruction = cls._json_to_math_instruction(tile_dict["math_instruction"]) + + # Get compute capability values, checking both naming conventions + min_compute = tile_dict.get( + "min_compute", tile_dict.get("minimum_compute_capability") + ) + max_compute = tile_dict.get( + "max_compute", tile_dict.get("maximum_compute_capability") + ) + + # Get cluster shape with default value + cluster_shape = tile_dict.get("cluster_shape", [1, 1, 1]) + + # Create the TileDescription object + tile_desc = TileDescription( + threadblock_shape=tile_dict["threadblock_shape"], + stages=tile_dict["stages"], + warp_count=tile_dict["warp_count"], + math_instruction=math_instruction, + min_compute=min_compute, + max_compute=max_compute, + cluster_shape=cluster_shape, + explicit_vector_sizes=tile_dict.get("explicit_vector_sizes"), + ) + + # Set tile_shape if it exists and differs from threadblock_shape + if ( + "tile_shape" in tile_dict + and tile_dict["tile_shape"] != tile_dict["threadblock_shape"] + ): + tile_desc.tile_shape = tile_dict["tile_shape"] + + return tile_desc + + @classmethod + @functools.lru_cache(None) + def _math_instruction_to_json( + cls, + math_instruction: Optional["MathInstruction"], # type: ignore[name-defined] # noqa: F821 + ) -> str | None: + """Convert MathInstruction to JSON string. + + Args: + math_instruction: MathInstruction object + + Returns: + Optional[str]: JSON string representation or None + """ + if math_instruction is None: + return None + + result = { + "instruction_shape": math_instruction.instruction_shape, + "element_a": cls._enum_to_json(math_instruction.element_a), + "element_b": cls._enum_to_json(math_instruction.element_b), + "element_accumulator": cls._enum_to_json( + math_instruction.element_accumulator + ), + "opcode_class": cls._enum_to_json(math_instruction.opcode_class), + "math_operation": cls._enum_to_json(math_instruction.math_operation), + "element_scale_factor": cls._enum_to_json( + math_instruction.element_scale_factor + ), + } + + return json.dumps(result) + + @classmethod + @functools.lru_cache(None) + def _json_to_math_instruction( + cls, json_dict: str | None + ) -> Optional["MathInstruction"]: # type: ignore[name-defined] # noqa: F821 + """Convert JSON string to MathInstruction object. + + Args: + json_dict: JSON string representation + + Returns: + Optional[MathInstruction]: Reconstructed object or None + """ + if json_dict is None: + return None + + from cutlass_library import DataType + from cutlass_library.library import MathInstruction, MathOperation, OpcodeClass + + mi_dict = json.loads(json_dict) + + # Convert string enum names back to enum values + element_a = cls._json_to_enum(mi_dict["element_a"], DataType) + element_b = cls._json_to_enum(mi_dict["element_b"], DataType) + element_acc = cls._json_to_enum(mi_dict["element_accumulator"], DataType) + + # Get the opcode_class enum + opcode_class = cls._json_to_enum(mi_dict["opcode_class"], OpcodeClass) + + # Get the math_operation enum + math_op = cls._json_to_enum(mi_dict["math_operation"], MathOperation) + + # Create the MathInstruction object + math_instruction_obj = MathInstruction( + instruction_shape=mi_dict["instruction_shape"], + element_a=element_a, + element_b=element_b, + element_accumulator=element_acc, + opcode_class=opcode_class, + math_operation=math_op, + ) + + # Add element_scale_factor if it exists + if ( + "element_scale_factor" in mi_dict + and mi_dict["element_scale_factor"] is not None + ): + math_instruction_obj.element_scale_factor = cls._json_to_enum( + mi_dict["element_scale_factor"], DataType + ) + + return math_instruction_obj + + @classmethod + @functools.lru_cache(None) + def _tensor_description_to_json( + cls, + tensor_desc: Optional["TensorDescription"], # type: ignore[name-defined] # noqa: F821 + ) -> str | None: + """Convert TensorDescription to JSON string. + + Args: + tensor_desc: TensorDescription object + + Returns: + Optional[str]: JSON string representation or None + """ + if tensor_desc is None: + return None + + result = { + "element": cls._enum_to_json(tensor_desc.element), + "layout": cls._enum_to_json(tensor_desc.layout), + "alignment": tensor_desc.alignment, + "complex_transform": cls._enum_to_json(tensor_desc.complex_transform), + } + + return json.dumps(result) + + @classmethod + @functools.lru_cache(None) + def _json_to_tensor_description( + cls, + json_dict: str | None, + tensor_name: str | None = None, + ) -> Optional["TensorDescription"]: # type: ignore[name-defined] # noqa: F821 + """Convert JSON string to TensorDescription object. + + Args: + json_dict: JSON string representation + tensor_name: Name of the tensor to avoid cache in the same op + + Returns: + Optional[TensorDescription]: Reconstructed object or None + """ + if json_dict is None: + return None + + tensor_dict = json.loads(json_dict) + + from cutlass_library import DataType + from cutlass_library.library import ( + ComplexTransform, + LayoutType, + TensorDescription, + ) + + element = cls._json_to_enum(tensor_dict["element"], DataType) + layout = cls._json_to_enum(tensor_dict["layout"], LayoutType) + alignment = tensor_dict["alignment"] + complex_transform = cls._json_to_enum( + tensor_dict["complex_transform"], ComplexTransform + ) + + return TensorDescription(element, layout, alignment, complex_transform) + + @classmethod + @functools.lru_cache(None) + def _enum_to_json(cls, enum_value: Enum | None) -> str | None: + """Convert enum value to JSON string. + + Args: + enum_value: Enum value + + Returns: + Optional[str]: JSON string representation or None + """ + if enum_value is None: + return None + + result = { + "type": enum_value.__class__.__name__, + "name": enum_value.name, + } + + return json.dumps(result) + + @classmethod + @functools.lru_cache(None) + def _json_to_enum(cls, json_dict: str | None, enum_class: Any) -> Enum | None: + """Convert JSON string to enum value. + + Format: {name: "EnumName", value: 1} + + Args: + json_dict: JSON string representation + enum_class: Target enum class + + Returns: + Optional[Enum]: Reconstructed enum value or None + """ + if json_dict is None: + return None + + enum_dict = json.loads(json_dict) + + return enum_class[enum_dict["name"]] + + +@functools.lru_cache(1) +def get_cutlass_operation_serializer() -> CUTLASSOperationSerializer | None: + if not try_import_cutlass(): + return None + return CUTLASSOperationSerializer() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/template.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a2bacfe7b9ffa668bb48ec04f8f4be1e933d9e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/template.py @@ -0,0 +1,387 @@ +# mypy: allow-untyped-defs +import functools +import hashlib +import itertools +from dataclasses import dataclass +from typing import Any, TYPE_CHECKING +from unittest.mock import patch + +import sympy + +import torch +from torch._inductor import config +from torch._inductor.utils import clear_on_fresh_cache, Placeholder +from torch._logging import getArtifactLogger + +from ...autotune_process import CUTLASSBenchmarkRequest, TensorMeta +from ...ir import Buffer, CUTLASSTemplateBuffer, IRNode, Layout +from ...utils import IndentedBuffer, unique +from ...virtualized import V +from ..common import KernelTemplate +from .kernel import CUTLASSTemplateCaller, CUTLASSTemplateKernel +from .utils import DTYPE_TO_CUTLASS_TYPE + + +if TYPE_CHECKING: + from ...scheduler import BaseSchedulerNode +else: + BaseSchedulerNode = Any + +GemmOperation = Any + +autotuning_log = getArtifactLogger(__name__, "autotuning") + + +@dataclass(frozen=True) +class ArgInfo: + name: str + ty: str + + +@clear_on_fresh_cache +class CUTLASSTemplate(KernelTemplate): + """ + CUTLASSTemplate is a class that provides a template for generating CUTLASS Templates. Used as a baseclass for the + CUTLASSGemmTemplate, providing functionality that might also be relevant for non-GEMM CUTLASS Kernels. + """ + + index_counter = itertools.count() + # dict of cache key to (code, size_args) + code_cache: dict[str, tuple[str, tuple[int, ...], tuple[int, ...]]] = {} + cache_clear = staticmethod(code_cache.clear) + + def __init__( + self, + name: str, + input_nodes: list[Buffer], + layout: Layout, + input_reorder: list[int] | None = None, + ) -> None: + """ + Baseclass for CUTLASS C++ Templates, derived from KernelTemplate. + Not to be instantiated directly. + + Args: + name (str): The name of the CUTLASSTemplate object. + input_nodes (List[IRNode]): A list of input IRNodes. + layout (Layout): The layout of the output buffer / tensor. + input_reorder (Optional[List[int]]): An optional list that specifies + the order of the input nodes. + """ + super().__init__(name) + self.input_nodes = input_nodes + self.output_node: Buffer = Buffer(name="buf_out", layout=layout) + self.input_reorder = input_reorder + self.layout = layout + self.device_type = layout.device.type + + @classmethod + @functools.lru_cache(None) + # pyrefly: ignore [bad-override] + def _template_from_string(cls, source: str) -> Any: + return KernelTemplate._template_from_string(source) + + @staticmethod + def supports_epilogue_fusion(op: GemmOperation, device_type: str) -> bool: + return False + + def make_key(self, name: str, input_key: str, layout_repr: str) -> str: + """ + Make a key for the code cache. The idea of the method is to cache + everything that matters but doesn't include runtime param values, i.e., + self.get_runtime_arg_values(). + + Args: + kwargs: Additional keyword arguments. Including op (GemmOperation). + """ + return hashlib.sha256( + str( + ( + input_key, + self.input_reorder, + # output layout, same as self.output_node.get_layout() + layout_repr, + self.get_runtime_arg_info(), + name, + ) + ).encode("utf-8") + ).hexdigest() + + def generate_code_and_args( + self, name: str, input_key: str, layout_repr: str, **kwargs + ) -> tuple[str, tuple[int, ...]]: + """ + Generate code and args with caching. We cache the code even if runtime + args are different. + """ + key: str | None = None + if config.cutlass.enable_caching_codegen: + key = self.make_key(name=name, input_key=input_key, layout_repr=layout_repr) + + if key is not None and key in self.code_cache: + code, size_args, offset_args = self.code_cache[key] + extra_args = tuple( + list(size_args) + + list(offset_args) + + list(self.get_runtime_arg_values(**kwargs)) + ) + return code, extra_args + + kernel_name = str(Placeholder.KERNEL_NAME) + kernel = CUTLASSTemplateKernel( + kernel_name=kernel_name, + runtime_arg_info=self.get_runtime_arg_info(), + runtime_arg_values=self.get_runtime_arg_values(**kwargs), + device_type=self.device_type, + ) + with patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)): + code = self.render(kernel=kernel, **kwargs) + _, call_args, _, _ = kernel.args.python_argdefs() + autotuning_log.debug("Generated Code:\n%s", code) + autotuning_log.debug( + "Args: cpp_argdefs: %s, python_argdefs: %s", + kernel.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE), + kernel.args.python_argdefs(), + ) + + input_reorder = ( + self.input_reorder + if self.input_reorder is not None + else list(range(len(self.input_nodes))) + ) + expected_args = list( + unique(self.input_nodes[idx].get_name() for idx in input_reorder) + ) + expected_args.extend([self.output_node.get_name()]) + if list(call_args)[: len(expected_args)] != expected_args: + raise AssertionError( + ( + call_args, + expected_args, + ) + ) + # Resolve symbolic sizes to concrete ints for benchmarking only. + V.graph.sizevars.optimization_hints( + map(sympy.expand, call_args[len(expected_args) :]) + ) + size_args = V.graph.sizevars.optimization_hints(kernel.get_dynamic_shape_args()) + offset_args = V.graph.sizevars.optimization_hints(kernel.get_offset_args()) + + if key is not None: + self.code_cache[key] = code, size_args, offset_args + + # extra args has runtime params, which shouldn't be cached + extra_args = tuple( + list(size_args) + list(offset_args) + self.get_runtime_arg_values(**kwargs) + ) + + return code, extra_args + + def generate( # type: ignore[override] + self, + name: str, + description: str, + input_key: str, + layout_repr: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + **kwargs, + ) -> CUTLASSTemplateCaller: + """ + Generates the CUDA template caller object for the given GEMM template and operation. + This CUTLASSTemplateCaller may be used to call and benchmark the generated CUDA kernel + in a standalone manner to enable Autotuning. + + Args: + description: op name followed by swizzle. + kwargs: Additional keyword arguments. + + Returns: + A CUTLASSTemplateCaller object representing the generated CUDA template caller. + """ + code, extra_args = self.generate_code_and_args( + name=name, + input_key=input_key, + layout_repr=layout_repr, + **kwargs, + ) + + # not caching since kernel name is needed below + kernel_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()[:8] + kernel_name = f"cutlass_{kernel_hash}" + code = code.replace(self.name, kernel_name) + + # create the BenchmarkRequest + bmreq = CUTLASSBenchmarkRequest( + kernel_name=kernel_name, + input_tensor_meta=input_tensor_meta, + output_tensor_meta=output_tensor_meta, + extra_args=extra_args, + source_code=code, + device_type=self.device_type, + ) + + # kwargs has "op" argument in case of CUTLASSGemmTemplate + op = kwargs["op"] + if not op: + supports_epilogue_fusion = False + else: + # epilogue fusion is only supported for TMA kernels + supports_epilogue_fusion = self.supports_epilogue_fusion( + op, self.device_type + ) + + def make_kernel_render( + template_node: CUTLASSTemplateBuffer, + epilogue_nodes: list[BaseSchedulerNode] | None = None, + ) -> tuple[CUTLASSTemplateKernel, functools.partial[str]]: + if not supports_epilogue_fusion and epilogue_nodes: + raise AssertionError("epilogue fusion is not supported for this kernel") + kernel = CUTLASSTemplateKernel( + kernel_name=str(Placeholder.KERNEL_NAME), + runtime_arg_info=self.get_runtime_arg_info(), + runtime_arg_values=self.get_runtime_arg_values(**kwargs), + device_type=self.device_type, + ) + render = functools.partial( + self.render, + kernel=kernel, + template_buffer_node=template_node, + epilogue_nodes=epilogue_nodes, + **kwargs, # includes "op" argument in case of CUTLASSGemmTemplate + ) + return kernel, render + + return CUTLASSTemplateCaller( + kernel_name, + "cutlass_gemm", + self.input_nodes, + self.output_node.get_layout(), + make_kernel_render, + bmreq, + supports_epilogue_fusion, + self, + kwargs, + description, + ) + + def header(self) -> IndentedBuffer: + res = IndentedBuffer() + res.splice( + """ + #include + #include + #include + #include + #include + """ + ) + res.splice( + """ + #include "cute/tensor.hpp" + #include "cutlass/cutlass.h" + #include "cutlass/numeric_types.h" + #include "cutlass/tensor_ref.h" + #include "cutlass/util/host_tensor.h" + #include "cutlass/util/reference/host/tensor_fill.h" + #include "cutlass/util/reference/device/tensor_fill.h" + #include "cutlass/util/device_memory.h" + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = IndentedBuffer() + res.splice( + """ + // We compile all models with -fvisibility=hidden. Any symbols that need to be + // exposed in the final shared library must be declared with PT_EXPORT to make + // them visible. + #ifdef __GNUC__ // Applies to any compiler with GNU extensions (clang and g++) + #define PT_EXPORT __attribute__((__visibility__("default"))) + #else + #ifdef _WIN32 + #define PT_EXPORT __declspec(dllexport) + #else + #define PT_EXPORT + #endif + #endif + """ + ) + res.splice( + """ + using namespace cute; + #define CUTLASS_CHECK(status) \\ + { \\ + cutlass::Status error = status; \\ + if (error != cutlass::Status::kSuccess) { \\ + auto msg = std::string("[") + __FILE__ + "] Got cutlass error: " + \\ + cutlassGetStatusString(error) + " at: " + std::to_string(__LINE__); \\ + throw std::runtime_error(msg); \\ + } \\ + } + + // Used as pass-through functor in EVT just for type casting / rounding + template + struct identity_op { + CUTLASS_HOST_DEVICE + T operator()(T val) const { return val; } + }; + + """ + ) + return res + + def cute_int(self, int_str: str, var_name: str) -> str: + res = "" + if int_str in ("1", "1L"): + res = "cute::Int<1>{}" + else: + res = int_str + + return f"{res} /* {var_name} */" + + _DTYPE_TO_CUTLASS = { + torch.float32: "float", + torch.float64: "double", + torch.float16: "cutlass::half_t", + torch.int32: "int32_t", + torch.int16: "int16_t", + torch.int8: "int8_t", + torch.uint8: "uint8_t", + torch.bool: "bool", + torch.bfloat16: "cutlass::bfloat16_t", + torch.float8_e4m3fn: "cutlass::float_e4m3_t", + torch.float8_e5m2: "cutlass::float_e5m2_t", + } + + _DTYPE_TO_CUTLASS_SPARSE_META = { + torch.int32: "uint32_t", + torch.int16: "uint16_t", + } + + def cutlass_type_cast(self, node: IRNode, ptr: str) -> str: + if node is None: + return ptr + else: + return f"({self._DTYPE_TO_CUTLASS.get(node.get_dtype())}*)({ptr})" + + def cutlass_sparse_meta_type_cast(self, node: IRNode, ptr: str) -> str: + if node is None: + return ptr + else: + return ( + f"({self._DTYPE_TO_CUTLASS_SPARSE_META.get(node.get_dtype())}*)({ptr})" + ) + + def render(self, **kwargs) -> str: + raise NotImplementedError + + def get_runtime_arg_info(self) -> list[ArgInfo]: + return [ArgInfo("swizzle", "const uint8_t")] + + def get_runtime_arg_values(self, **kwargs) -> list[Any]: + """ + Helper method to retrieve runtime args from generate kwargs + """ + return [kwargs[arg.name] for arg in self.get_runtime_arg_info()] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..efd794f098bb972beddaf06f2b31b24adb2a9192 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/utils.py @@ -0,0 +1,618 @@ +# mypy: allow-untyped-defs +import atexit +import functools +import logging +import os +import shutil +import sys +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any +from typing_extensions import TypeIs + +import sympy + +import torch +from torch._inductor.runtime.runtime_utils import dynamo_timed +from torch._inductor.utils import clear_on_fresh_cache +from torch.utils._ordered_set import OrderedSet + +from ... import config +from ...ir import Layout +from ...runtime.runtime_utils import cache_dir +from ...virtualized import V +from ..cuda.cuda_env import get_cuda_arch, get_cuda_version +from ..xpu.xpu_env import get_xpu_arch, get_xpu_version + + +log = logging.getLogger(__name__) + +CUTLASS_OPERATION_KIND: str = "gemm" +ACCUMULATOR_DTYPES: OrderedSet[torch.dtype] = OrderedSet([torch.float, torch.int32]) +XW_DTYPES: OrderedSet[torch.dtype] = OrderedSet( + [torch.half, torch.bfloat16, torch.float8_e4m3fn, torch.int8, torch.float8_e5m2] +) + + +@atexit.register +def move_cutlass_compiled_cache() -> None: + """Move CUTLASS compiled cache file to the cache directory if it exists.""" + if try_import_cutlass.cache_info().currsize == 0: + return + + try: + import cutlass_cppgen # type: ignore[import-not-found] + except ImportError: + return + + # Check if the CACHE_FILE attribute exists in cutlass_cppgen and if the file exists + if not hasattr(cutlass_cppgen, "CACHE_FILE") or not os.path.exists( + cutlass_cppgen.CACHE_FILE + ): + return + + try: + filename = os.path.basename(cutlass_cppgen.CACHE_FILE) + shutil.move(cutlass_cppgen.CACHE_FILE, os.path.join(cache_dir(), filename)) + log.debug("Moved CUTLASS compiled cache file to %s", cache_dir()) + except OSError: + log.warning("Failed to move CUTLASS compiled cache file", exc_info=True) + + +def _rename_cutlass_import(content: str, cutlass_modules: list[str]) -> str: + for cutlass_module in cutlass_modules: + content = content.replace( + f"from {cutlass_module} import ", + f"from cutlass_library.{cutlass_module} import ", + ) + return content + + +@functools.cache +def try_import_cutlass() -> bool: + """ + We want to support three ways of passing in CUTLASS: + 1. fbcode, handled by the internal build system. + 2. User specifies cutlass_dir. The default is ../third_party/cutlass/, + which is the directory when developers build from source. + """ + if config.is_fbcode(): + try: + import cutlass_cppgen # type: ignore[import-not-found] + import cutlass_library # type: ignore[import-not-found] + except ImportError as e: + log.warning( + "Failed to import CUTLASS packages in fbcode: %s, ignoring the CUTLASS backend.", + e, + ) + return False + + return True + + # Copy CUTLASS python scripts to a temp dir and add the temp dir to Python search path. + # This is a temporary hack to avoid CUTLASS module naming conflicts. + # TODO(ipiszy): remove this hack when CUTLASS solves Python scripts packaging structure issues. + + # TODO(mlazos): epilogue visitor tree currently lives in python/cutlass, + # but will be moved to python/cutlass_library in the future (later 2025) + def path_join(path0, path1): + return os.path.abspath(os.path.join(path0, path1)) + + # contains both cutlass and cutlass_library + # we need cutlass for eVT + cutlass_dir = ( + config.xpu.cutlass_dir + if torch.xpu._is_compiled() + else config.cutlass.cutlass_dir + ) + cutlass_python_path = path_join(cutlass_dir, "python") + torch_root = os.path.abspath(os.path.dirname(torch.__file__)) + mock_src_path = os.path.join( + torch_root, + "_inductor", + "codegen", + "cutlass", + "lib_extensions", + "cutlass_mock_imports", + ) + + cutlass_library_src_path = path_join(cutlass_python_path, "cutlass_library") + cutlass_cppgen_src_path = path_join(cutlass_python_path, "cutlass_cppgen") + pycute_src_path = path_join(cutlass_python_path, "pycute") + + tmp_cutlass_full_path = os.path.abspath(os.path.join(cache_dir(), "torch_cutlass")) + + dst_link_library = path_join(tmp_cutlass_full_path, "cutlass_library") + dst_link_cutlass_cppgen = path_join(tmp_cutlass_full_path, "cutlass_cppgen") + dst_link_pycute = path_join(tmp_cutlass_full_path, "pycute") + + # mock modules to import cutlass + mock_modules = ["cuda", "scipy", "pydot"] + + if os.path.isdir(cutlass_python_path): + if tmp_cutlass_full_path not in sys.path: + + def link_and_append(dst_link, src_path, parent_dir): + if os.path.lexists(dst_link): + if not os.path.islink(dst_link): + raise AssertionError( + f"{dst_link} is not a symlink. Try to remove {dst_link} manually and try again." + ) + if os.path.realpath(os.readlink(dst_link)) != os.path.realpath( + src_path, + ): + raise AssertionError( + f"Symlink at {dst_link} does not point to {src_path}" + ) + else: + os.makedirs(parent_dir, exist_ok=True) + os.symlink(src_path, dst_link) + + if parent_dir not in sys.path: + sys.path.append(parent_dir) + + link_and_append( + dst_link_library, cutlass_library_src_path, tmp_cutlass_full_path + ) + link_and_append( + dst_link_cutlass_cppgen, cutlass_cppgen_src_path, tmp_cutlass_full_path + ) + link_and_append(dst_link_pycute, pycute_src_path, tmp_cutlass_full_path) + + for module in mock_modules: + link_and_append( + path_join(tmp_cutlass_full_path, module), # dst_link + path_join(mock_src_path, module), # src_path + tmp_cutlass_full_path, # parent + ) + + try: + import cutlass_cppgen # type: ignore[import-not-found] # noqa: F401 + import cutlass_library.generator + import cutlass_library.library + import cutlass_library.manifest # noqa: F401 + import pycute # type: ignore[import-not-found] # noqa: F401 + + return True + except ImportError as e: + log.debug( + "Failed to import CUTLASS packages: %s, ignoring the CUTLASS backend.", + e, + ) + else: + log.debug( + "Failed to import CUTLASS packages: CUTLASS repo does not exist: %s", + cutlass_python_path, + ) + return False + + +def _normalize_xpu_arch(arch: str) -> str: + if arch.startswith("Xe"): + return arch[2:] + if 12 <= int(arch) and int(arch) <= 50: + return arch + else: + raise NotImplementedError(f"Unsupported xpu arch: {arch}") + + +def _normalize_cuda_arch(arch: str) -> str: + arch_num = arch + if isinstance(arch, str): + digits = "".join(ch for ch in arch if ch.isdigit()) + if not digits: + raise ValueError(f"Unrecognized cuda arch: {arch}") + arch_num = int(digits) + else: + arch_num = int(arch) + + if arch_num > 107: + log.warning("Detected CUDA architecture > 107: %s. Please file an issue.", arch) + return str(arch_num) + if arch_num >= 107: + return "107" + if arch_num >= 103: + return "103" + if arch_num >= 100: + return "100" + if arch_num >= 90: + return "90" + if arch_num >= 80: + return "80" + if arch_num >= 75: + return "75" + if arch_num >= 70: + return "70" + raise NotImplementedError(f"Unsupported cuda arch: {arch}") + + +@functools.lru_cache(8) +def cutlass_arch(device_type: str) -> str: + if device_type == "xpu": + arch = get_xpu_arch() + return _normalize_xpu_arch(arch) + else: + arch = get_cuda_arch() + return _normalize_cuda_arch(arch) + + +@functools.lru_cache(1) +def toolkit_version(device_type: str) -> str: + if device_type == "xpu": + return get_xpu_version() + else: + return get_cuda_version() + + +def get_device_cutlass_config(device_type: str): + """Get device-specific CUTLASS config (xpu/cuda overrides general cutlass config).""" + if device_type == "xpu": + return config.xpu + from ...config import cutlass as inductor_cutlass_config + + return inductor_cutlass_config + + +@dataclass +class CUTLASSArgs: + """ + CUTLASS args used to initialize a CUTLASS Manifest. + """ + + architectures: str | None = None + toolkit_version: str | None = None + instantiation_level: str | None = None + operations: str | None = None + + build_dir = "" + curr_build_dir = "" + generator_target = "" + kernels = "all" + ignore_kernels = "" + exclude_kernels = "" + # TODO: these three look dead? + kernel_filter_file: None = None + selected_kernel_list: None = None + interface_dir: None = None + filter_by_cc = True + disable_full_archs_compilation = False + device_type: str = "cuda" + + def __post_init__(self): + if self.architectures is None or self.toolkit_version is None: + raise RuntimeError( + f"{self.architectures=} or {self.toolkit_version=} is None!" + ) + + +@clear_on_fresh_cache +@functools.cache +def _gen_ops_cached(arch: str, version: str, device_type: str) -> dict[Any, Any]: + # Note: Cache needs to be specific for cuda architecture and version + + # Import cutlass python scripts. + if not try_import_cutlass(): + raise AssertionError("Failed to import CUTLASS library") + import cutlass_library.generator as cutlass_generator + import cutlass_library.manifest as cutlass_manifest + + if arch is None or version is None: + log.error( + "Cannot detect cuda arch %s or version %s. " + "Will discard all cutlass ops. " + "Please consider setting _inductor.cuda.arch and _inductor.cuda.version configs.", + arch, + version, + ) + return {} + + # SM103 and SM107 reuse the SM100 generator, but the CUTLASS manifest must keep + # their architecture-specific baseline rather than treating them as SM100. + if arch in ("103", "107"): + gen_arch = "100" + manifest_arch = f"{arch}a" + else: + gen_arch = manifest_arch = arch + + instantiation_level: str = config.cutlass.cutlass_instantiation_level + args = CUTLASSArgs( + architectures=manifest_arch, + toolkit_version=version, + instantiation_level=instantiation_level, + operations=CUTLASS_OPERATION_KIND, + device_type=device_type, + ) + manifest = cutlass_manifest.Manifest(args) + if arch == "107": + # CUTLASS uses 103a as the SM100-family feature marker for architectures + # without INT8 UMMA. Keep the SM107 baseline while sharing that feature. + manifest.compute_capabilities_feature_set.append("103a") + + start_time = time.time() + if device_type == "xpu": + if hasattr(cutlass_generator, "GenerateIntelXe"): + cutlass_generator.GenerateIntelXe( + manifest, args.toolkit_version, arch=int(arch) + ) + else: + raise NotImplementedError( + "Arch " + arch + " is not supported by current cutlass lib." + ) + + elif arch == "100": + if hasattr(cutlass_generator, "GenerateSM100"): + cutlass_generator.GenerateSM100(manifest, args.toolkit_version) + cutlass_generator.GenerateSM90(manifest, args.toolkit_version) + else: + try: + func = getattr(cutlass_generator, "GenerateSM" + gen_arch) + func(manifest, args.toolkit_version) + except AttributeError as e: + raise NotImplementedError( + "Arch " + gen_arch + " is not supported by current cutlass lib." + ) from e + + log.info( + "CUTLASS library generated a dict of %d operation kinds in %.2f seconds", + len(manifest.operations), + time.time() - start_time, + ) + return manifest.operations + + +def gen_ops(device_type: str) -> dict[Any, Any]: + """ + Generates all supported CUTLASS operations. + """ + with dynamo_timed("cutlass_utils.gen_ops"): + arch = cutlass_arch(device_type) + version = toolkit_version(device_type) + return _gen_ops_cached(arch, version, device_type) + + +from ..cpp_utils import DTYPE_TO_CPP + + +if torch.xpu._is_compiled(): + DTYPE_TO_CUTLASS_TYPE = { + **DTYPE_TO_CPP, + torch.float16: "uint16_t", + torch.bfloat16: "uint16_t", + torch.float8_e4m3fn: "uint8_t", + torch.float8_e5m2: "uint8_t", + } +else: + DTYPE_TO_CUTLASS_TYPE = { + **DTYPE_TO_CPP, + torch.float16: "__half", + torch.bfloat16: "__nv_bfloat16", + torch.float8_e4m3fn: "__nv_fp8_e4m3", + torch.float8_e5m2: "__nv_fp8_e5m2", + } + + +@functools.lru_cache(32) +def torch_dtype_to_cutlass_type( + torch_dtype: torch.dtype, +) -> "cutlass_library.library.DataType": # type: ignore[name-defined] # noqa: F821 + # Import cutlass python scripts. + if not try_import_cutlass(): + raise AssertionError("Failed to import CUTLASS library") + import cutlass_library # type: ignore[import] + + if torch_dtype == torch.float: + return cutlass_library.library.DataType.f32 + elif torch_dtype == torch.half: + return cutlass_library.library.DataType.f16 + elif torch_dtype == torch.bfloat16: + return cutlass_library.library.DataType.bf16 + elif torch_dtype == torch.float8_e4m3fn: + return cutlass_library.library.DataType.e4m3 + elif torch_dtype == torch.float8_e5m2: + return cutlass_library.library.DataType.e5m2 + else: + raise NotImplementedError(f"Unsupported data type: {torch_dtype=}") + + +@functools.lru_cache(32) +def dtype_match( + torch_dtype: torch.dtype | None, + cutlass_dtype: "cutlass_library.library.DataType", # type: ignore[name-defined] # noqa: F821 +) -> bool: + # Import cutlass python scripts. + if not try_import_cutlass(): + raise AssertionError("Failed to import CUTLASS library") + import cutlass_library + + if torch_dtype == torch.float: + return ( + cutlass_dtype == cutlass_library.library.DataType.f32 + or cutlass_dtype == cutlass_library.library.DataType.tf32 + ) + elif torch_dtype == torch.half: + return cutlass_dtype == cutlass_library.library.DataType.f16 + elif torch_dtype == torch.bfloat16: + return cutlass_dtype == cutlass_library.library.DataType.bf16 + elif torch_dtype == torch.int8: + return cutlass_dtype == cutlass_library.library.DataType.s8 + elif torch_dtype == torch.uint8: + return cutlass_dtype == cutlass_library.library.DataType.u8 + elif torch_dtype == torch.int32: + return cutlass_dtype == cutlass_library.library.DataType.s32 + elif torch_dtype == torch.float8_e4m3fn: + return cutlass_dtype == cutlass_library.library.DataType.e4m3 + elif torch_dtype == torch.float8_e5m2: + return cutlass_dtype == cutlass_library.library.DataType.e5m2 + else: + return False + + +def get_accumulator_dtype( + input_torch_dtypes: list[torch.dtype], +) -> torch.dtype | None: + """ + Given a pair of input torch dtypes, returns the inferred accumulator torch dtype. + """ + + if not (OrderedSet(input_torch_dtypes) <= XW_DTYPES): + raise AssertionError(f"{input_torch_dtypes=} is not supported") + + if len(input_torch_dtypes) != 2: + return None + + if OrderedSet(input_torch_dtypes) == OrderedSet( + [torch.float8_e5m2, torch.float8_e4m3fn] + ): + return torch.float + + torch_dtype = None + if input_torch_dtypes[0] == input_torch_dtypes[1]: + torch_dtype = input_torch_dtypes[0] + else: + size0 = torch.tensor([], dtype=input_torch_dtypes[0]).element_size() + size1 = torch.tensor([], dtype=input_torch_dtypes[1]).element_size() + if size0 > size1: + dtype0, dtype1 = input_torch_dtypes + else: + dtype1, dtype0 = input_torch_dtypes + if dtype0 in [torch.half, torch.bfloat16] and dtype1 in [ + torch.int8, + torch.uint8, + ]: + torch_dtype = dtype0 + + if torch_dtype in ( + torch.float16, + torch.bfloat16, + torch.float, + torch.float8_e4m3fn, + torch.float8_e5m2, + ): + accumulator_dtype = torch.float + elif torch_dtype == torch.int8: + accumulator_dtype = torch.int32 + else: + raise NotImplementedError(f"Unsupported data types: {input_torch_dtypes=}") + + if accumulator_dtype not in ACCUMULATOR_DTYPES: + raise AssertionError(f"{accumulator_dtype=} is not supported") + return accumulator_dtype + + +@functools.lru_cache(32) +def get_alignments(torch_dtype: torch.dtype) -> list[int]: + """ + Returns all possible valid CUTLASS alignments in terms of the number of elements for a given dtype. + CUTLASS gemm / conv SM80 APIs support 16 bytes max alignment, and 2 bytes min alignment. + """ + + if torch_dtype in (torch.half, torch.bfloat16): + return [8, 4, 2, 1] + elif torch_dtype == torch.float: + return [4, 2, 1] + elif torch_dtype in ( + torch.uint8, + torch.int8, + torch.float8_e4m3fn, + torch.float8_e5m2, + ): + return [16, 8, 4, 2] + elif torch_dtype == torch.int32: + return [4, 2, 1] + else: + raise NotImplementedError(f"unsupported {torch_dtype=} for alignments") + + +def get_max_alignment(inductor_layout: Layout) -> int: + """ + Returns the max alignment (in terms of number of elements) for a given Inductor Layout. + """ + + dtype = inductor_layout.dtype + size = inductor_layout.size + offset = inductor_layout.offset + + def is_static_int(number: object) -> TypeIs[int | sympy.Integer]: + return isinstance(number, (int | sympy.Integer)) + + def a_factor_of(x, alignment): + if is_static_int(x) and is_static_int(alignment): + return x % alignment == 0 + rem = sympy.Mod(x, alignment) + return V.graph.sizevars.evaluate_expr(sympy.Eq(rem, 0)) + + try: + contiguous_dim = inductor_layout.stride.index(1) + except ValueError: + # No dim with stride 1 found, return 1 + return 1 + alignments = get_alignments(dtype) + for alignment in alignments: + if not a_factor_of(size[contiguous_dim], alignment) or not a_factor_of( + offset, alignment + ): + continue + if all( + (dim == contiguous_dim) + or a_factor_of(inductor_layout.stride[dim], alignment) + for dim in range(len(size)) + ): + return alignment + return 1 + + +class CUTLASSCompileSourceCapturingContext: + # Helper class for Benchmarking and Testing CUTLASS Kernels in isolation. + # Can be used to capture the sourcecode passed to CUDACodeCache.compile + + def __init__(self, device_type: str): + self.sources = [] + self._compile_patch = None + self.device_type = device_type + + def __enter__(self, *args, **kwargs): + import unittest.mock as mock + + import torch._inductor.codecache + + codecache_cls = ( + torch._inductor.codecache.XPUCodeCache + if self.device_type == "xpu" + else torch._inductor.codecache.CUDACodeCache + ) + _compile_method_orig = codecache_cls.compile + + def my_compile(source_code, dst_file_ext, extra_args: list[str] | None = None): + self.sources.append(source_code) + return _compile_method_orig(source_code, dst_file_ext) + + # pyrefly: ignore [bad-assignment] + self._compile_patch = mock.patch( + f"torch._inductor.codecache.{codecache_cls.__name__}.compile", my_compile + ) + self._compile_patch.__enter__(*args, **kwargs) # type: ignore[union-attr] + return self + + def __exit__(self, *args, **kwargs): + self._compile_patch.__exit__(*args, **kwargs) # type: ignore[union-attr] + + +def cutlass_standalone_runner_compile_command( + device_type: str, srcpath: Path, exepath: Path +): + # returns command string to compile a (captured) CUDA GEMM Kernel source to a standalone executable that's ready to run + # Passes the correct preprocessor define to nvcc to ensure the standalone runner is enabled. + + extra_args = ["-DGENERATE_STANDALONE_RUNNER=1"] + if device_type != "xpu": + extra_args.append("-DCUTLASS_DEBUG_TRACE_LEVEL=1") + cutlass_compile_command = ( + torch._inductor.codegen.xpu.compile_utils.xpu_compile_command + if device_type == "xpu" + else torch._inductor.codegen.cuda.compile_utils.cuda_compile_command + ) + compile_command = cutlass_compile_command( + [str(srcpath)], str(exepath), "exe", extra_args=extra_args + ) + return compile_command diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/debug_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/debug_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..eac55255abacdaaf4da615c6096ff47893964dea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/debug_utils.py @@ -0,0 +1,293 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import functools +import logging +import os +from enum import Enum +from typing import TYPE_CHECKING + +import torch +from torch import dtype as torch_dtype + +from .. import config +from ..virtualized import V +from .multi_kernel import MultiKernel + + +if TYPE_CHECKING: + from collections.abc import Callable + + +log = logging.getLogger(__name__) + + +def _print_debugging_tensor_value_info(msg, arg): + # helper for printing debugging stats for intermediate tensor values + # at jit inductor level codegen + max_numel_to_print = 64 + print(msg) + if not isinstance(arg, torch.Tensor): + print("Value: ", arg) + return + numel = arg.numel() + # print the debug printing stats + if numel <= max_numel_to_print: + print(arg) + print("Number of elements: ", numel) + print("Size: ", arg.size()) + print("Dtype: ", arg.dtype) + arg_f = arg.float() + std, mean = torch.std_mean(arg_f) + amin, amax = torch.aminmax(arg_f) + print("Mean: ", mean.item()) + print("Min: ", amin.item()) + print("Max: ", amax.item()) + print("Std: ", std.item()) + + +# AOTI debug printing related configs +class IntermediateValueDebuggingLevel(Enum): + # OFF: No intermediate tensor value debug info will be printed or saved. + OFF = "0" + # LEVEL 1: Save all intermediate tensor values to individual `.pt` files. No debug printing will be displayed. + SAVE_ONLY = "1" + # LEVEL 2: Print all intermediate tensor values by default to the console. No debug saving will be performed. + PRINT_ONLY = "2" + # LEVEL 3: Print all kernel names to the console only. No debug saving/printing for input tensor value info will be performed. + # This mode can be helpful in cases when you just want to pinpoint what kernel is running into a CUDA IMA issue, etc. + PRINT_KERNEL_NAMES_ONLY = "3" + + +class DebugPrinterManager: + def __init__( + self, + debug_printer_level, + use_array_ref: bool, + writeline: Callable[..., None] | None = None, + args_to_print_or_save: list[str] | None = None, + kernel_name: str = "", + kernel=None, + arg_signatures: list[type] | None = None, + kernel_type=None, + ): + self.debug_printer_level = IntermediateValueDebuggingLevel(debug_printer_level) + self.use_array_ref = use_array_ref + if args_to_print_or_save is None: + args_to_print_or_save = [] + self.args_to_print_or_save = args_to_print_or_save + self.kernel_name = kernel_name + self.arg_signatures: list[type] | None = None + self.kernel = kernel + self.filtered_kernel_names_to_print = self._get_debug_filtered_kernel_names() + self.kernel_type = None + + def __enter__(self): + self._perform_debug_print_or_save_helper( + self.args_to_print_or_save, + self.kernel_name, + before_launch=True, + arg_signatures=self.arg_signatures, + ) + + def __exit__(self, args_to_print_or_save, kernel_name, arg_signatures): + self._perform_debug_print_or_save_helper( + args_to_print_or_save, + kernel_name, + before_launch=False, + arg_signatures=arg_signatures, + ) + + def _perform_debug_print_or_save_helper( + self, + args_to_print_or_save, + kernel_name, + before_launch, + arg_signatures: list[type] | None = None, + ): + if self.debug_printer_level == IntermediateValueDebuggingLevel.OFF: + return + if self.debug_printer_level == IntermediateValueDebuggingLevel.SAVE_ONLY: + # by default save all the tensor values before launch + self.codegen_intermediate_tensor_value_save( + self.args_to_print_or_save, + self.kernel_name, + before_launch, + arg_signatures=self.arg_signatures, + ) + if self.debug_printer_level == IntermediateValueDebuggingLevel.PRINT_ONLY: + # by default print all the tensor values before launch + self.codegen_intermediate_tensor_value_print( + self.args_to_print_or_save, + self.kernel_name, + before_launch, + arg_signatures=self.arg_signatures, + ) + if ( + self.debug_printer_level + == IntermediateValueDebuggingLevel.PRINT_KERNEL_NAMES_ONLY + ): + # Print all kernel names to the console only + self.codegen_intermediate_tensor_value_print( + [], + self.kernel_name, + before_launch, + ) + + @functools.lru_cache # noqa: B019 + def _get_debug_filtered_kernel_names(self) -> list[str]: + if config.aot_inductor.filtered_kernel_names is None: + return [] + return [ + x.strip() + for x in config.aot_inductor.filtered_kernel_names.lower().split(",") + ] + + def set_printer_args( + self, + args_to_print_or_save: list[str], + kernel_name: str, + arg_signatures: list[type] | None, + kernel, + kernel_type=None, + ): + # Note: MultiKernel debug printing is not supported for now + if isinstance(kernel, MultiKernel): + log.info( + "MultiKernel type is not supported in AOTI debug printer tool yet." + ) + self.debug_printer_level = IntermediateValueDebuggingLevel.OFF + + self.kernel_type = kernel_type + # Note: if the kernel type is an extern kernel (or cpp kernel), we do a special handling to + # get the list of args_to_print_or_save + # TODO: Find a more reliable way to detect kernel args types to print for extern kernel calls + if kernel_type == "extern": + args_to_print_or_save_extern = [ + arg + for arg in args_to_print_or_save + if isinstance(arg, str) and arg.startswith(("buf", "arg")) + ] + self.args_to_print_or_save = args_to_print_or_save_extern + elif kernel_type == "cpp": + self.args_to_print_or_save = [ + ( + f"copy_arrayref_tensor_to_tensor({arg})" + if self.use_array_ref + else arg + ) + for arg in args_to_print_or_save + if isinstance(arg, str) and arg.startswith(("buf", "arg")) + ] + else: + self.args_to_print_or_save = args_to_print_or_save + self.kernel_name = kernel_name + self.arg_signatures = arg_signatures + self.kernel = kernel + + def codegen_model_inputs_value_print(self, input_args_to_print: list[str]) -> None: + if self.debug_printer_level != IntermediateValueDebuggingLevel.PRINT_ONLY: + return + for arg in input_args_to_print: + if V.graph.cpp_wrapper: + V.graph.wrapper_code.prefix.writeline( + f'aoti_torch_print_tensor_handle({arg}, "aoti_model_inputs - {arg}");' + ) + + def codegen_intermediate_tensor_value_save( + self, + args_to_save, + kernel_name, + before_launch=True, + arg_signatures: list[type] | None = None, + ) -> None: + for i, arg in enumerate(args_to_save): + if arg_signatures is not None and not isinstance( + arg_signatures[i], torch_dtype + ): + # infer from the arg data type (has torch.dtype) to see if it is a tensor type + continue + launch_prefix = "before_launch" if before_launch else "after_launch" + if V.graph.cpp_wrapper: + V.graph.wrapper_code.writeline( + f'aoti_torch_save_tensor_handle({arg}, "{arg}", "{launch_prefix}", "{kernel_name}");' + ) + else: + cwd = os.getcwd() + saved_dir = cwd + "/tmp/jit_inductor/" + if not os.path.exists(saved_dir): + log.info( + "Creating directory to save inductor intermediate tensor values." + ) + os.makedirs(saved_dir) + # Save the model to the directory + saved_path = saved_dir + f"{launch_prefix}_{kernel_name}_{arg}.pt" + log.info( + "Saved intermediate tensor %s for %s to %s", + arg, + kernel_name, + saved_path, + ) + line = f"torch.save({arg}, '{saved_path}')" + V.graph.wrapper_code.writeline(line) + + def codegen_intermediate_tensor_value_print( + self, + args_to_print, + kernel_name, + before_launch=True, + arg_signatures: list[type] | None = None, + ) -> None: + launch_prefix = "before_launch" if before_launch else "after_launch" + + # if the debug printing level is PRINT_KERNEL_NAMES_ONLY + # we only print the kernel name to the console + if ( + self.debug_printer_level + == IntermediateValueDebuggingLevel.PRINT_KERNEL_NAMES_ONLY + ): + if V.graph.cpp_wrapper: + V.graph.wrapper_code.writeline( + f'printf("[ {launch_prefix}: {kernel_name} ]\\n");' + ) + return + + if self.debug_printer_level != IntermediateValueDebuggingLevel.PRINT_ONLY: + return + for i, arg in enumerate(args_to_print): + # when debug printing is enabled i.e. IntermediateValueDebuggingLevel.PRINT_ONLY, + # check if filtered kernel name list is provided + if ( + len(self.filtered_kernel_names_to_print) > 0 + and kernel_name.lower() not in self.filtered_kernel_names_to_print + ): + continue + if V.graph.cpp_wrapper: + if arg_signatures is not None and isinstance( + arg_signatures[i], torch_dtype + ): + # infer from the arg data type (has torch.dtype) to see if it is a tensor type + V.graph.wrapper_code.writeline( + f'aoti_torch_print_tensor_handle({arg}, "{launch_prefix} - {kernel_name} - {arg}");' + ) + elif arg_signatures is not None and isinstance( + arg_signatures[i], + ( + type(torch._inductor.codegen.wrapper.SymbolicCallArg), + type(int), + type(float), + type(bool), + ), + ): + V.graph.wrapper_code.writeline( + f'printf("[ {launch_prefix} - {kernel_name} - {arg}: %ld ]", {arg}); printf("\\\\n");' + ) + else: + if arg_signatures is None and self.kernel_type in ("cpp", "extern"): + V.graph.wrapper_code.writeline( + f'aoti_torch_print_tensor_handle({arg}, "{launch_prefix} - {kernel_name} - {arg}");' + ) + else: + V.graph.wrapper_code.writeline( + f'_print_debugging_tensor_value_info("inductor: {launch_prefix} - {kernel_name} - {arg}", {arg})' + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/halide.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/halide.py new file mode 100644 index 0000000000000000000000000000000000000000..89c798c10c025364e0634f33684c1c257615036d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/halide.py @@ -0,0 +1,1895 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import dataclasses +import functools +import itertools +import logging +import re +import sys +from collections import defaultdict +from typing import Any, cast, TYPE_CHECKING + +import sympy + +import torch +import torch._logging + +from ..._prims_common import is_integer_dtype +from ...utils._ordered_set import OrderedSet +from ...utils._sympy.functions import FloorDiv, Max, Min, ModularIndexing +from ...utils._sympy.symbol import symbol_is_type, SymT +from ...utils._sympy.value_ranges import ValueRanges +from .. import config, ir +from ..codecache import HalideCodeCache +from ..ir import get_reduction_combine_fn +from ..metrics import is_metric_table_enabled, log_kernel_metadata +from ..ops_handler import AddParenHandler +from ..runtime.hints import HalideInputSpec, HalideMeta +from ..utils import ( + get_bounds_index_expr, + get_kernel_metadata, + parallel_num_threads, + sympy_index_symbol, + sympy_subs, +) +from ..virtualized import _ops as ops, V +from .common import ( + BackendFeature, + CSEVariable, + DeferredLine, + IndentedBuffer, + KernelArgType, + OpOverrides, + PythonPrinter, + SizeArg, + TensorArg, +) +from .cpp import DTYPE_TO_CPP +from .cpp_utils import cexpr +from .simd import constant_repr, SIMDKernel, SIMDScheduling + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from ..ops_handler import ReductionType, StoreMode + from ..shape_propagation import BlockShapeType + +log = logging.getLogger(__name__) + + +def halide_constant(val): + if isinstance(val, int) and not (-2147483648 <= val <= 2147483647): + info = torch.iinfo(torch.int64) + if val == info.min: + return "hl.Int(64).min()" + if val == info.max: + return "hl.Int(64).max()" + return f"hl.i64({val!r})" + if isinstance(val, float): + return f"hl.f64({constant_repr(val)})" + return repr(val) + + +class Unsupported(RuntimeError): + def __init__(self, thing) -> None: + super().__init__(f"halide backend does not support: {thing}") + + +class HalidePrinter(PythonPrinter): # noqa: docstring_linter + @staticmethod + def cast_index(expr): + return f"hl.cast({V.kernel.index_dtype}, {expr})" + + @staticmethod + def cast_float(expr): + return f"hl.cast(hl.Float(32), {expr})" + + def _print_Float(self, expr): + return f"hl.f32({expr})" + + def _print_ToFloat(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.f32({self._print(expr.args[0])})" + + def _print_floor(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return self.cast_index(f"hl.floor({self._print(expr.args[0])})") + + _print_FloorToInt = _print_floor + + def _print_Trunc(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return self.cast_index(f"hl.trunc({self._print(expr.args[0])})") + + _print_TruncToInt = _print_Trunc + + def _print_ceiling(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return self.cast_index(f"hl.ceil({self._print(expr.args[0])})") + + def _helper_sqrt(self, expr): + # pyrefly: ignore [missing-attribute] + return f"hl.sqrt({self.cast_float(self._print(expr))})" + + def _print_Where(self, expr): + c = self.doprint(expr.args[0]) + p = self.doprint(expr.args[1]) + q = self.doprint(expr.args[2]) + return f"hl.select({c}, {p}, {q})" + + def _print_Min(self, expr): + if len(expr.args) == 1: + # pyrefly: ignore [missing-attribute] + return self._print(expr.args[0]) + + mid = len(expr.args) // 2 + # pyrefly: ignore [missing-attribute] + a = self._print(Min(*expr.args[:mid])) + # pyrefly: ignore [missing-attribute] + b = self._print(Min(*expr.args[mid:])) + return f"hl.min({a}, {b})" + + def _print_Max(self, expr): + if len(expr.args) == 1: + # pyrefly: ignore [missing-attribute] + return self._print(expr.args[0]) + + mid = len(expr.args) // 2 + # pyrefly: ignore [missing-attribute] + a = self._print(Max(*expr.args[:mid])) + # pyrefly: ignore [missing-attribute] + b = self._print(Max(*expr.args[mid:])) + + return f"hl.max({a}, {b})" + + def _print_Abs(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return self.cast_index(f"hl.abs({self._print(expr.args[0])})") + + def _print_OpaqueUnaryFn_cos(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.cos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_cosh(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.cosh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_acos(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.acos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sin(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.sin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sinh(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.sinh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_asin(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.asin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tan(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.tan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tanh(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.tanh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_atan(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.atan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_log2(self, expr): + raise NotImplementedError("log2") + + def _print_FloorDiv(self, expr): + if expr.is_integer: + return super()._print_FloorDiv(expr) + + x, div = expr.args + x = self.cast_float(self.doprint(x)) + div = self.cast_float(self.doprint(div)) + return self.cast_index(f"hl.floor({x} / {div})") + + def _print_Round(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return self.cast_index(f"hl.round({self._print(expr.args[0])})") + + _print_RoundToInt = _print_Round + + def _print_IntTrueDiv(self, expr): + a, b = expr.args + # force a cast to float + return f"({a}) / ({b}+hl.f32(0))" + + def _print_RoundDecimal(self, expr): + val, n = expr.args + # pyrefly: ignore [missing-attribute] + val = self._print(val) + n = int(n) + return f"hl.f32({10.0 ** (-n)!r})*hl.round(({val})*hl.f32({10.0**n!r}))" + + +texpr = HalidePrinter().doprint +pexpr = PythonPrinter().doprint + + +_halide_type = { + torch.bool: "hl.Bool()", + torch.bfloat16: "hl.BFloat(16)", + torch.float16: "hl.Float(16)", + torch.float32: "hl.Float(32)", + torch.float64: "hl.Float(64)", + torch.int8: "hl.Int(8)", + torch.int16: "hl.Int(16)", + torch.int32: "hl.Int(32)", + torch.int64: "hl.Int(64)", + torch.uint8: "hl.UInt(8)", + torch.uint16: "hl.UInt(16)", + torch.uint32: "hl.UInt(32)", + torch.uint64: "hl.UInt(64)", +} + + +def halide_type(dtype): + return _halide_type[dtype] + + +def halide_acc_type(dtype): + if is_integer_dtype(dtype) and dtype.is_signed and dtype != torch.int64: + dtype = torch.int32 + if dtype in (torch.float16, torch.bfloat16): + dtype = torch.float32 + return halide_type(dtype) + + +class HalideOverrides(OpOverrides): + @staticmethod + def to_dtype( + x, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types=True, + ): + if dtype == torch.bool: + return f"({x} != 0)" + return f"hl.cast({halide_type(dtype)}, {x})" + + @staticmethod + def to_dtype_bitcast(x, dtype: torch.dtype, src_dtype: torch.dtype): + if src_dtype in (torch.float16, torch.bfloat16): + x = f"hl.cast({halide_type(src_dtype)}, {x})" # body compute is upcast to fp32 + line = f"hl.reinterpret({halide_type(dtype)}, {x})" + if dtype in (torch.float16, torch.bfloat16): + line = f"hl.cast(hl.Float(32), {line})" + return line + + @classmethod + def constant(cls, value, dtype): + return cls.to_dtype(halide_constant(value), dtype) + + @staticmethod + # pyrefly: ignore [bad-override] + def abs(x): + return f"hl.abs({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def exp(x): + if not hasattr(x, "name"): + return f"hl.exp({x})" + return f"hl.fast_exp(hl.cast(hl.Float(32), {x})) if {x.name}.type().bits() <= 32 else hl.exp({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sqrt(x): + return f"hl.sqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a, b): + # return f"hl.min({a}, {b})" <== handles nan wrong + if not hasattr(a, "name"): + return f"hl.min({a}, {b})" + b = f"hl.cast({a.name}.type(), {b})" + return f"hl.select(({a}<{b})|hl.is_nan({a}), {a}, {b}) if {a.name}.type().is_float() else hl.min({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a, b): + # return f"hl.max({a}, {b})" <== handles nan wrong + if not hasattr(a, "name"): + return f"hl.max({a}, {b})" + b = f"hl.cast({a.name}.type(), {b})" + return f"hl.select(({a}>{b})|hl.is_nan({a}), {a}, {b}) if {a.name}.type().is_float() else hl.max({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmaximum(a, b): + return f"hl.max({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def where(a, b, c): + if hasattr(b, "name"): + c = f"hl.cast({b.name}.type(), {c})" + return f"hl.select({a}, {b}, {c})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cos(x): + return f"hl.cos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sin(x): + return f"hl.sin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def lgamma(x): + raise Unsupported("lgamma") + + @staticmethod + # pyrefly: ignore [bad-override] + def erf(x): + return f"hl.erf({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cosh(x): + return f"hl.cosh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sinh(x): + return f"hl.sinh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acos(x): + return f"hl.acos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acosh(x): + return f"hl.acosh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asin(x): + return f"hl.asin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asinh(x): + return f"hl.asinh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan2(x, y): + return f"hl.atan2({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x): + return f"hl.atan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atanh(x): + return f"hl.atanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def copysign(x, y): + raise Unsupported("copysign") + + @staticmethod + # pyrefly: ignore [bad-override] + def erfinv(x): + raise Unsupported("erfinv") + + @staticmethod + # pyrefly: ignore [bad-override] + def hypot(x, y): + return f"hl.hypot({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def nextafter(x, y): + raise Unsupported("nextafter") + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_and(a, b): + return f"{a} & {b}" + + @staticmethod + def logical_not(a): + return f"{a} == 0" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_or(a, b): + return f"{a} | {b}" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_xor(a, b): + return f"({a} ^ {b})" + + @staticmethod + def bitwise_and(a, b): + return f"{a} & {b}" + + @staticmethod + def bitwise_not(a): + return f"~{a}" + + @staticmethod + def bitwise_or(a, b): + return f"{a} | {b}" + + @staticmethod + def bitwise_xor(a, b): + return f"{a} ^ {b}" + + @staticmethod + def bitwise_left_shift(a, b): + return f"{a} << {b}" + + @staticmethod + def bitwise_right_shift(a, b): + return f"{a} >> {b}" + + @staticmethod + def rand(seed, offset): + return f"halide_helpers.rand({seed}, {offset})" + + @staticmethod + def randn(seed, offset): + return f"halide_helpers.randn({seed}, {offset})" + + @staticmethod + def rand_eager(seed, base_offset, threads_per_round, tid, vec): + return f"halide_helpers.rand_eager_kernel({seed}, {base_offset}, {threads_per_round}, {tid}, {vec})" + + @staticmethod + def randint64(seed, offset, low, high): + return f"halide_helpers.randint64({seed}, {offset}, {low}, {high})" + + @staticmethod + def load_seed(name, offset): + return f"{ops.load(name, 0)} + {V.kernel.args.seed_offset('load_seed_offset', offset)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def rsqrt(x): + # return f"hl.fast_inverse_sqrt({x})" <== accuracy issues + return f"1./hl.sqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tan(x): + return f"hl.tan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tanh(x): + return f"hl.tanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def signbit(x): + return f"(hl.reinterpret(hl.UInt(32), hl.cast(hl.Float(32), {x})) >> 31) != 0" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmod(a, b): + # TODO(jansel): find a better way to do this, builtin % has wrong sign + return f"{a} - hl.trunc({a}/{b})*{b}" + + @staticmethod + def pow(a, b): + return f"hl.pow({a}, {b})" # hl.fast_pow fails accuracy + + @staticmethod + # pyrefly: ignore [bad-override] + def ldexp(x, n): + raise Unsupported("ldexp") + + @staticmethod + # pyrefly: ignore [bad-override] + def log(x): + return f"hl.log({x})" # hl.fast_log fails accuracy + + @staticmethod + def log2(x): + raise NotImplementedError("log2") + + @staticmethod + # pyrefly: ignore [bad-override] + def isinf(x): + # workaround https://github.com/halide/Halide/issues/8309 + return f"hl.is_inf(hl.cast(hl.Float(32), {x}))" + + @staticmethod + # pyrefly: ignore [bad-override] + def isnan(x): + # workaround https://github.com/halide/Halide/issues/8309 + return f"hl.is_nan(hl.cast(hl.Float(32), {x}))" + + @staticmethod + # pyrefly: ignore [bad-override] + def round(x): + return f"hl.round({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def floor(x): + return f"hl.floor({x})" + + @staticmethod + def int_truediv(a, b): + return f"({a}) / ({b} + hl.f32(0))" + + @staticmethod + def floordiv(a, b): + # TODO(jansel): find a better ways to do this, the select-based trick from triton.py didn't work + return ( + f"hl.floor(hl.cast(hl.Float(max(32, {a.name}.type().bits())), {a}) / {b})" + ) + + @classmethod + def sign(cls, x): + left = ops.to_dtype(ops.lt("0", x), torch.int8) + right = ops.to_dtype(ops.lt(x, "0"), torch.int8) + sub = ops.sub(left, right) + return f"hl.cast({x.name}.type(), {sub})" + + @staticmethod + # pyrefly: ignore [bad-override] + def trunc(x): + return f"hl.trunc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def truncdiv(a, b): + # this causes crashes with floating point exception, see test_div_zero_dim_cpu + # return f"hl.div_round_to_zero({a}, {b})" + return ( + f"hl.trunc(hl.cast(hl.Float(max(32, {a.name}.type().bits())), {a}) / {b})" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def ceil(x): + return f"hl.ceil({x})" + + @staticmethod + def relu(x): + return f"hl.max({x}, 0)" + + @classmethod + def index_expr(cls, expr, dtype): + index = V.kernel.prepare_indexing(expr) + var = V.kernel.genfunc( + V.kernel.index_to_str(index), + V.kernel.used_dims_from_index(index), + bounds=get_bounds_index_expr(expr), + ) + if dtype not in (torch.int32, torch.int64): + return ops.to_dtype(var, dtype) + return var + + @classmethod + def value_expr(cls, expr, dtype): + index = V.kernel.prepare_indexing(expr) + var = V.kernel.genfunc( + V.kernel.index_to_str(index), + V.kernel.used_dims_from_index(index), + bounds=get_bounds_index_expr(expr), + ) + return ops.to_dtype(var, dtype) + + @classmethod + def indirect_indexing(cls, index_var, size, check=True, wrap_neg=True): + # TODO(jansel): Halide only supports 32-bit indexing, we should error on overflow + index_var = ops.to_dtype(index_var, torch.int32) + index_var = ops.halide_clamp(index_var, size, check) + index_var.indirect_indexing_size = size + return sympy_index_symbol(str(index_var)) + + @classmethod + def halide_clamp(cls, value, size, check): + end = V.kernel.kexpr(V.kernel.rename_indexing(size) - 1) + if not isinstance(size, (int, sympy.Integer)): + end = f"hl.cast({value.name}.type(), {end})" + # Skip unsafe_promise_clamped to workaround: https://github.com/halide/Halide/issues/8261#issuecomment-2148835692 + # return f"hl.unsafe_promise_clamped({value}, 0, {end})" + return f"hl.clamp({value}, 0, {end})" + + @staticmethod + def masked(mask, body, other): + with V.kernel.mask_loads(mask, other) as new_mask: + result = body() + + if result.bounds.is_bool: + other = bool(other) + + # Take dtype from result to prevent accidental promotion + other = V.kernel.genfunc( + f"hl.cast({result.name}.type(), {halide_constant(other)})", + [], + bounds=ValueRanges.wrap(other), + shape=result.shape, + ) + # TODO(jansel): look into removing the where in the same places triton does + return ops.where(new_mask, result, other) + + @staticmethod + # pyrefly: ignore [bad-override] + def frexp(x): + raise NotImplementedError("frexp") + + @staticmethod + def device_assert_async(cond, msg): + raise NotImplementedError("device_assert_async") + + @staticmethod + # pyrefly: ignore [bad-override] + def partial_accumulate( + name: str, + reduction_type: str, + value: CSEVariable, + extra_meta: dict[str, Any], + ) -> None: + raise NotImplementedError + + +HalideOverrides._initialize_pointwise_overrides("halide") + + +class HalideCSEVariable(CSEVariable): + undefined_re = re.compile(r"\b(tmp\d+)\[\?\]") + + def __init__( + self, + name, + bounds: ValueRanges[Any], + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ) -> None: + super().__init__(name, bounds, dtype, shape=shape) + self.used_dims: list[sympy.Symbol] | None = None + + def update_on_args(self, name, args, kwargs): + used = OrderedSet(self.used_dims or ()) + for arg in itertools.chain(args, kwargs.values()): + if isinstance(arg, HalideCSEVariable): + if arg.used_dims is None: + raise AssertionError((name, arg, args)) + used.update(arg.used_dims) + self.used_dims = V.kernel.sort_used_dims(used) + + def index_str(self, dims): + if len(dims) == 0: + return f"{self.name}[()]" + # Reversed since Halide is column major + return f"{self.name}[{', '.join(map(str, dims))}]" + + def __str__(self) -> str: + if self.used_dims is None: + # This will get recomputed and replaced in codegen_kernel() + return f"{self.name}[?]" + return self.index_str(self.used_dims) + + def subs_str(self, replacements): + if not ( + self.used_dims is not None + and all(isinstance(x, sympy.Expr) for x in self.used_dims) + ): + raise AssertionError("used_dims must be set sympy expressions") + return self.index_str([replacements.get(n, n) for n in self.used_dims]) + + +@dataclasses.dataclass +class DimensionInfo: + expr: sympy.Expr | None + size: sympy.Expr + stride: sympy.Expr + + def __init__(self, expr, size, stride) -> None: + super().__init__() + if V.graph.sizevars.statically_known_lt(stride, 0): + stride = -stride + expr = -expr + self.expr = expr + self.size = size + self.stride = stride + + def index_str(self, replacements=None, zero_vars=False): + if self.expr is None: + raise AssertionError("expr must not be None") + expr = self.expr + if zero_vars and expr == 0: + return "hl.Var()" + if replacements: + replacements = {**replacements} + # pyrefly: ignore [missing-attribute] + for sym in expr.free_symbols: + if symbol_is_type(sym, SymT.TMP): + if not isinstance(sym, sympy.Symbol): + raise AssertionError(f"expected sympy.Symbol, got {type(sym)}") + var = V.kernel.lookup_cse_var(sym.name) + if not isinstance(var, HalideCSEVariable): + raise AssertionError( + f"expected HalideCSEVariable, got {type(var)}" + ) + replacements[sym] = sympy_index_symbol(var.subs_str(replacements)) + expr = sympy_subs(expr, replacements) + return V.kernel.index_to_str(expr) + + +def eq(left, right): + return V.graph.sizevars.guard_or_false(sympy.Eq(left, right)) + + +def lt(left, right): + """Compare sizes: only use on inputs known to be >= 0.""" + if V.graph.sizevars.guard_or_false(sympy.Lt(left, right)): + return True + + # GCD fallback: if gcd(left, right) == left then left divides right, + # so left <= right. Combined with left != right this gives left < right. + # + # TODO: This is NOT always sound for unbacked symints. + # e.g. lt(u0, 10*u0): gcd=u0, gcd==left, u0 != 10*u0 → returns True, + # but if u0=0 then 0 < 0 is False. The >= 0 checks mitigate the + # negative case but the zero case remains. + # TODO shall we add a runtime assertion at least. + gcd = sympy.gcd(left, right) + if gcd == left: + return left != right + + return False + + +class HalideKernel(SIMDKernel): + overrides = HalideOverrides # type: ignore[assignment] + kexpr: Callable[[sympy.Expr], str] = texpr + + def __init__( + self, + tiling: dict[str, sympy.Expr], + **kwargs, + ) -> None: + super().__init__(tiling, **kwargs) + # For halide, we just write directly to the body + self.compute = self.body + self.loads = self.body + self.stores = self.body + self.indexing_code_dom = IndentedBuffer() + self.needs_dom_indexing = self.inside_reduction + self.has_reduction = self.inside_reduction + self.buffer_dimensions: dict[str, list[DimensionInfo]] = {} + self.buffer_offsets: dict[str, sympy.Expr] = {} + # {h0: size1, h1: size2, ...} + self.halide_vars: dict[sympy.Symbol, sympy.Expr] = {} + # {x0: h0, x1: h1+10*h2, ...} + self.index_replacements: dict[sympy.Expr, sympy.Expr] = {} + # {h1: hr1, ...} + self.reduction_renames: dict[sympy.Symbol, sympy.Symbol] = {} + # {"i": {h0: hi0}, "o": ...} + self.dom_renames: dict[str, dict[sympy.Symbol, sympy.Symbol]] = {} + # {"in_ptr0": ["in_ptr0_view0"], ...} + self.buffer_aliases: dict[str, list[str]] = defaultdict(list) + self.has_indirect_indexing = False + + def dtype_to_str(self, dtype: torch.dtype) -> str: + return halide_type(dtype) + + # pyrefly: ignore [bad-override] + def create_cse_var(self, name, bounds=None, dtype=None, shape=None): + self.body.writeline(f"{name} = hl.Func({name!r})") + # pyrefly: ignore [bad-argument-type] + return HalideCSEVariable(name, bounds, dtype, shape) + + def finalize_indexing(self, indices: Sequence[sympy.Expr]): + """ + Hook called right before codegen with every index that will be + used in the fused kernel. + + This populates self.halide_vars/index_replacements/reduction_renames which is an alternate indexing + scheme that avoids using divide and modulus. Instead of xindex/yindex/rindex + we base indexing on a larger number of vars whose product combines to those. + + This function populates self.halide_vars, self.index_replacements, and self.reduction_renames + """ + if self.index_replacements or self.halide_vars or self.reduction_renames: + raise AssertionError( + "indexing state must be empty before finalize_indexing" + ) + size_hint = functools.partial( + V.graph.sizevars.optimization_hint, fallback=sys.maxsize + ) + # pyrefly: ignore [bad-assignment] + indices = dict.fromkeys(map(super().prepare_indexing, indices)) + all_used_symbols = OrderedSet[Any]() + sym_to_node = { + n.symbol(): n + for n in itertools.chain.from_iterable( + [tree.nodes.values() for tree in self.range_trees] + ) + } + + def simplify(expr): + return sympy.simplify( + V.graph.sizevars.remove_precomputed_replacements(expr) + ) + + def visit_modular_indexing(base, divisor, modulus): + if base in sym_to_node: + node = sym_to_node[base] + all_used_symbols.add( + node.root.lookup( + node.divisor * divisor, + V.graph.sizevars.evaluate_min( + modulus, + FloorDiv(node.length, divisor), + ), + ).symbol() + ) + + def visit_floor_div(base, divisor): + if base in sym_to_node: + node = sym_to_node[base] + all_used_symbols.add( + node.root.lookup( + node.divisor * divisor, + FloorDiv(node.length, divisor), + ).symbol() + ) + + # first figure out all_used_symbols to do dead symbol elimination + for index in indices: + if index.has(ModularIndexing): + index.replace( + ModularIndexing( + sympy.Wild("base"), + sympy.Wild("divisor"), + sympy.Wild("modulus"), + ), + visit_modular_indexing, + ) + if index.has(FloorDiv): + index.replace( + FloorDiv( + sympy.Wild("base"), + sympy.Wild("divisor"), + ), + visit_floor_div, + ) + all_used_symbols.update(super().prepare_indexing(index).free_symbols) + + self.has_indirect_indexing = any( + symbol_is_type(sym, SymT.INDIRECT) for sym in all_used_symbols + ) + + had_fallback = False + for tree in reversed(self.range_trees): + nodes = [n for n in tree.nodes.values() if n.symbol() in all_used_symbols] + nodes.sort(key=lambda n: size_hint(n.divisor)) + if not nodes: + nodes.append(tree.lookup(1, tree.numel)) + handled_count = 0 + divisor = sympy.S.One + added_sym_size = [] + # decide on a minimal set of symbols and put them in self.halide_vars + while handled_count < len(nodes) and not eq(tree.numel, divisor): + sizes_to_add = [ + simplify(n.length) for n in nodes if eq(n.divisor, divisor) + ] + handled_count += len(sizes_to_add) + if not sizes_to_add: + raise AssertionError(nodes) + end = divisor * functools.reduce( + lambda a, b: V.graph.sizevars.evaluate_max(a, b), + sizes_to_add, + ) + sizes_to_add.extend( + [ + simplify(n.divisor / divisor) + for n in nodes + if lt(divisor, n.divisor) and lt(n.divisor, end) + ] + ) + # pyrefly: ignore [bad-assignment] + while sizes_to_add: + next_size = functools.reduce(sympy.gcd, sizes_to_add) + if eq(next_size, 1): + # sizes share no common factors, e.g [2, 21, 42, 441, 889056] + # TODO(jansel): we should just prevent fusion in cases that hit this + next_size = simplify(tree.numel / divisor) + if eq(next_size, 1): + raise AssertionError("fallback next_size must not be 1") + sizes_to_add = [] + handled_count = len(nodes) + had_fallback = True + sym = sympy_index_symbol(f"h{len(self.halide_vars)}") + # pyrefly: ignore [missing-argument] + if tree.is_reduction: + self.reduction_renames[sym] = sympy_index_symbol( + f"hr{len(self.halide_vars)}" + ) + self.halide_vars[sym] = next_size + added_sym_size.append((sym, next_size)) + divisor *= next_size + new_sizes = [n.length for n in nodes if eq(n.divisor, divisor)] + handled_count += len(new_sizes) + prior_len = len(sizes_to_add) + sizes_to_add = [ + sympy.simplify(s / next_size) + for s in sizes_to_add + if not eq(s, next_size) + ] + if not (len(sizes_to_add) < prior_len or prior_len == 0): + raise AssertionError("sizes_to_add must shrink") + sizes_to_add.extend(new_sizes) + + # create a mapping to the new set of symbols in self.index_replacements + for node in nodes: + try: + idx = 0 + divisor = 1 + while not eq(node.divisor, divisor): + sym, size = added_sym_size[idx] + idx += 1 + divisor *= size + length = 1 + expr = sympy.S.Zero + while not eq(node.length, length): + sym, size = added_sym_size[idx] + idx += 1 + expr += length * sym + length *= size + self.index_replacements[node.symbol()] = expr + except IndexError: + if not had_fallback: + raise AssertionError("IndexError without fallback") from None + full_index = sympy.S.Zero + stride = sympy.S.One + for sym, size in added_sym_size: + full_index += stride * sym + stride *= size + self.index_replacements[node.symbol()] = ( + V.graph.sizevars.simplify_with_ranges( + ModularIndexing(full_index, node.divisor, node.length), + self.halide_vars, # type: ignore[arg-type] + ) + ) + + # codegen the variable definitions + for sym in self.halide_vars: + self.indexing_code.writeline(f"{sym} = hl.Var({sym.name!r})") + if self.reduction_renames: + self.codegen_rdom( + "rdom", + {rv: self.halide_vars[v] for v, rv in self.reduction_renames.items()}, + ) + + def setup_dom_indexing(self): + """RDom based indexing uses explicit iteration ranges for Func updates""" + prefix = "i" if self.inside_reduction else "o" + if prefix in self.dom_renames: + return self.dom_renames[prefix] + + renames = {} + for var in self.halide_vars: + if not self.inside_reduction and var in self.reduction_renames: + continue + m = re.match(r"^h(\d+)$", var.name) + if not m: + raise AssertionError(f"unexpected halide var name {var.name}") + renames[var] = sympy_index_symbol(f"h{prefix}{m.group(1)}") + + self.codegen_rdom( + f"{prefix}dom", {rv: self.halide_vars[v] for v, rv in renames.items()} + ) + + self.dom_renames[prefix] = renames + return renames + + def codegen_rdom(self, name, vars): + rsizes = [ + f"hl.Range(0, {self.kexpr(self.rename_indexing(size))})" + for size in vars.values() + ] + self.indexing_code.writeline(f"{name} = hl.RDom([{', '.join(rsizes)}])") + for i, rsym in enumerate(vars.keys()): + self.indexing_code.writeline(f"{rsym} = {name}[{i}]") + + def prepare_indexing( + self, + index: sympy.Expr, + ): + index = super().prepare_indexing(index) + index = sympy_subs(index, self.index_replacements) + return V.graph.sizevars.simplify_with_ranges(index, self.halide_vars) # type: ignore[arg-type] + + def sym_size(self, sym): + """The size of an index symbol""" + if symbol_is_type(sym, SymT.TMP): + return self.lookup_cse_var(sym.name).indirect_indexing_size + return self.halide_vars[sym] + + def indexing_to_dimensions(self, var: str, index: sympy.Expr, is_store: bool): + """Convert address-based indexing into dimensions using self.halide_vars""" + symbols = [] + for sym in sorted(index.free_symbols, key=lambda x: x.name): # type: ignore[attr-defined] + if symbol_is_type(sym, (SymT.HALIDE, SymT.TMP)): + symbols.append(sym) + else: + if not symbol_is_type( + sym, + ( + SymT.UNBACKED_INT, + SymT.SIZE, + SymT.PRECOMPUTED_SIZE, + ), + ): + raise AssertionError(sym) + + # group the expression by variables used + offset = sympy.S.Zero + split_expr = dict.fromkeys(symbols, sympy.S.Zero) + split_failed: list[tuple[list[sympy.Symbol], sympy.Expr]] = [] + index = sympy.expand(self.rename_indexing(index)) + for part in index.args if isinstance(index, sympy.Add) else [index]: + part_vars = [v for v in part.free_symbols if v in split_expr] + if len(part_vars) == 0: + offset += part + elif len(part_vars) == 1: + split_expr[part_vars[0]] += part + else: + new_split_failed = [] + for i in range(len(split_failed)): + if split_failed[i] is None: + raise AssertionError("split_failed entry must not be None") + other_vars, other_part = split_failed[i] + if OrderedSet(other_vars) & OrderedSet(part_vars): + part_vars.extend([v for v in other_vars if v not in part_vars]) + part += other_part + else: + new_split_failed.append((other_vars, other_part)) + split_failed = [*new_split_failed, (part_vars, part)] + + def expr_to_dimension(expr, syms): + expr = sympy.factor(expr) + if len(syms) == 1: + stride_wild = sympy.Wild("wild", exclude=symbols) + m = expr.match(stride_wild * syms[0]) + if m: + return DimensionInfo( + syms[0], self.sym_size(syms[0]), m[stride_wild] + ) + if is_store: + raise AssertionError(expr) + length = sympy.simplify( + sympy_subs(expr, {sym: self.sym_size(sym) - 1 for sym in syms}) + 1 + ) + stride = sympy.S.One + if isinstance(expr, sympy.Mul): + for term in expr.args: + if isinstance(term, sympy.Integer): + stride *= term + expr = sympy.simplify(expr / term) + length = sympy.simplify(sympy.ceiling(length / term)) + return DimensionInfo(expr, length, stride) + + # try to turn each group into a strided access + dims = [] + for syms, expr in split_failed: + for v in syms: + expr += split_expr.pop(v) + dims.append(expr_to_dimension(expr, syms)) + for sym, expr in split_expr.items(): + dims.append(expr_to_dimension(expr, [sym])) + dims.sort( + key=lambda d: V.graph.sizevars.optimization_hint( + d.stride, fallback=sys.maxsize + ) + ) # type: ignore[arg-type] + + if not dims: # scalar load/store + if self.has_indirect_indexing: + # workaround https://github.com/halide/Halide/issues/8338 + dims.append(DimensionInfo(sympy.S.Zero, 1, 1)) + elif not V.graph.sizevars.statically_known_equals(dims[0].stride, 1): + # Halide assumes dimension 0 is stride == 1, so add a dummy dimension + dims.insert( + 0, DimensionInfo(sympy.S.Zero, 1 if is_store else dims[0].stride, 1) + ) + + if dims and not is_store: + if var in self.buffer_offsets and V.graph.sizevars.statically_known_geq( + offset, self.buffer_offsets[var] + ): + # reuse the existing offset to avoid needing an input alias + self.apply_offset_to_dimension(dims, offset - self.buffer_offsets[var]) + offset = self.buffer_offsets[var] + elif V.graph.sizevars.statically_known_gt( + offset, 0 + ): # TODO(jansel): negative offsets + # roll the offset into the dimensions for cleaner indexing + self.apply_offset_to_dimension(dims, offset) + offset = 0 + + orig_var = var + for i in itertools.count(): + if self.install_dims(var, dims, offset, is_store): + return var, dims + if is_store: + raise AssertionError("install_dims must succeed for stores") + var = f"{orig_var}_view{i}" + if var not in self.buffer_aliases[orig_var]: + self.buffer_aliases[orig_var].append(var) + + def install_dims(self, var, dims, offset, is_store): + """Try to set self.buffer_dimensions[var], return True on success""" + if var not in self.buffer_dimensions: + self.buffer_dimensions[var] = dims + self.buffer_offsets[var] = offset + return True + if self.buffer_offsets[var] != offset or len( + self.buffer_dimensions[var] + ) != len(dims): + return False + if is_store: + return self.buffer_dimensions[var] == dims + for old, new in zip(self.buffer_dimensions[var], dims): + if old.stride != new.stride: + return False + if old.size != new.size or old.expr != new.expr: + old.size = V.graph.sizevars.evaluate_max(old.size, new.size) + old.expr = None + return True + + def apply_offset_to_dimension(self, dims, offset): + if offset == 0: + return + for i in reversed(range(len(dims))): + if dims[i].stride == 1 or V.graph.sizevars.statically_known_geq( + offset, dims[i].stride + ): + part = FloorDiv(offset, dims[i].stride) + offset -= part * dims[i].stride + dims[i].expr += part + if offset != 0: + raise AssertionError(f"offset must be fully applied, got {offset}") + + def used_dims_from_index(self, index: sympy.Expr): + """Detect which range trees are used to populate HalideCSEVariable.used_dims""" + used_dims = OrderedSet[sympy.Symbol]() + for sym in index.free_symbols: + if not isinstance(sym, sympy.Symbol): + raise AssertionError(f"expected sympy.Symbol, got {type(sym)}") + if symbol_is_type(sym, SymT.TMP): + # indirect indexing + cse_var = self.lookup_cse_var(sym.name) + if not ( + isinstance(cse_var, HalideCSEVariable) + and cse_var.used_dims is not None + ): + raise AssertionError( + "cse_var must be HalideCSEVariable with used_dims" + ) + used_dims.update(cse_var.used_dims) + elif symbol_is_type(sym, SymT.HALIDE): + used_dims.add(sym) + elif symbol_is_type( + sym, (SymT.UNBACKED_INT, SymT.SIZE, SymT.PRECOMPUTED_SIZE, SymT.INDEX) + ): + pass + else: + raise NotImplementedError(f"unhandled symbol {sym}") + return self.sort_used_dims(used_dims) + + def sort_used_dims(self, used_dims): + if not all(isinstance(x, sympy.Expr) for x in used_dims): + raise AssertionError("used_dims must all be sympy expressions") + ordered = [ + sym + for sym in itertools.chain( + self.halide_vars, self.reduction_renames.values() + ) + if sym in used_dims + ] + if len(ordered) != len(used_dims): + raise AssertionError( + f"expected {len(used_dims)} ordered dims, got {len(ordered)}" + ) + return ordered + + def make_index_str(self, dims, replacements=None, zero_vars=False): + index_str = ", ".join(d.index_str(replacements, zero_vars) for d in dims) + if len(dims) == 0: + index_str = "()" + elif len(dims) == 1: + # workaround for https://github.com/halide/Halide/issues/8299 + index_str = f"{index_str}," + return index_str + + def load(self, name: str, index: sympy.Expr): + """Codegen a load from an InputBuffer""" + var = self.args.input(name) + index = self.prepare_indexing(index) + var, dims = self.indexing_to_dimensions(var, index, False) + line = f"{var}[{self.make_index_str(dims)}]" + dtype = V.graph.get_dtype(name) + if dtype in (torch.float16, torch.bfloat16): + dtype = torch.float32 + line = f"hl.cast(hl.Float(32), {line})" + + if self._load_mask: + if not ( + isinstance(self._load_mask, HalideCSEVariable) + and self._load_mask.used_dims is not None + ): + raise AssertionError( + "_load_mask must be HalideCSEVariable with used_dims" + ) + used_dims = OrderedSet( + (*self.used_dims_from_index(index), *self._load_mask.used_dims) + ) + result = self.newfunc(self.sort_used_dims(used_dims)) + if result.used_dims: + self.body.writeline(f"{result.name}_mask = hl.RDom([hl.Range(0, 1)])") + self.body.writeline(f"{result.name}_mask.where({self._load_mask})") + other = self.kexpr(self._load_other or 0) # type: ignore[arg-type] + self.body.writeline( + f"{result} = hl.cast({halide_type(dtype)}, {other})" + ) + self.body.writeline( + f"{result} = {line} + hl.cast({halide_type(dtype)}, {result.name}_mask)" + ) + else: + # scalar case + self.body.writeline( + f"{result} = hl.select({self._load_mask}, {line}, hl.cast({halide_type(dtype)}, 0))" + ) + return result + else: + return self.genfunc(line, self.used_dims_from_index(index)) + + def lookup_cse_var(self, name: str): + return self.cse.varname_map[re.sub(r"\[.*", "", name)] + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + """Codegen a store to an OutputBuffer""" + if not isinstance(value, HalideCSEVariable): + raise AssertionError(f"expected HalideCSEVariable, got {type(value)}") + var = self.args.output(name) + index = self.prepare_indexing(index) + var, dims = self.indexing_to_dimensions(var, index, True) + if self.is_indirect_indexing(index) or mode is not None: + replacements = self.setup_dom_indexing() + index_str = self.make_index_str(dims, replacements) + value_str = value.subs_str(replacements) + undef_dims = (", ".join(["hl.Var()"] * len(dims))) or "()" + self.body.writeline( + DeferredLine(name, f"{var}[{undef_dims}] = hl.undef({var}.type())") + ) + else: + index_str = self.make_index_str(dims, zero_vars=True) + value_str = str(value) + + dtype = V.graph.get_dtype(name) + if mode is None: + line = f"{var}[{index_str}] = hl.cast({halide_type(dtype)}, {value_str})" + elif mode == "atomic_add": + line = f"{var}[{index_str}] += hl.cast({halide_type(dtype)}, {value_str})" + else: + raise NotImplementedError(f"store mode={mode}") + self.body.writeline(DeferredLine(name, line)) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + """Codegen a reduction operation""" + if not self.inside_reduction: + raise AssertionError("reduction called outside reduction") + if self._load_mask: + raise AssertionError("reduction with active load mask") + cache_key = (src_dtype, reduction_type, value) + if cache_key in self.cse.reduction_cache: + return self.cse.reduction_cache[cache_key] + + if isinstance(value, tuple): + if reduction_type != "welford_combine": + raise AssertionError(f"expected welford_combine, got {reduction_type}") + self.cse.reduction_cache[cache_key] = result_tuple = ( + self.welford_combine_impl(*value) + ) + return result_tuple + + if not (isinstance(value, HalideCSEVariable) and value.used_dims is not None): + raise AssertionError("value must be HalideCSEVariable with used_dims") + reduction_vars = OrderedSet(self.reduction_renames) + result_var = self.newfunc( + [v for v in value.used_dims if v not in reduction_vars], + ) + if reduction_vars - OrderedSet(value.used_dims): + value = self.genfunc( + f"{value}", + self.sort_used_dims(OrderedSet((*value.used_dims, *reduction_vars))), + shape=value.shape, + ) + value_str = value.subs_str(self.reduction_renames) + default = ir.Reduction.default_accumulator(reduction_type, src_dtype) + acc_type = halide_acc_type(dtype) + + if reduction_type in ("argmax", "argmin"): + index = f"{result_var.name}_{reduction_type}" + self.body.writeline(f"{index} = hl.{reduction_type}(rdom, {value_str})") + # turn the N-D argmax index into a 1-D one + parts = [] + stride = 1 + for i, sym in enumerate(self.reduction_renames): + # pyrefly: ignore [bad-argument-type] + parts.append(f"{index}[{i}]") + if stride != 1: + # pyrefly: ignore [unsupported-operation] + parts[-1] += f"*{stride}" + stride *= self.halide_vars[sym] + self.body.writeline(f"{result_var} = {' + '.join(parts)}") + elif reduction_type == "welford_reduce": + # TODO(jansel): implement welford_reduce without fallback + result_var = self.welford_reduce_fallback(dtype, value) + else: + combine_fn = get_reduction_combine_fn(reduction_type, acc_type) + with V.set_ops_handler(AddParenHandler(HalideOverrides())): + combine_str = combine_fn(result_var, value_str) # type: ignore[arg-type] + default_str = f"hl.cast({acc_type}, {halide_constant(default)})" + self.body.writeline(f"{result_var} = {default_str}") + self.body.writeline(f"{result_var} = {combine_str}") + + self.cse.reduction_cache[cache_key] = result_var + return result_var + + def welford_combine_impl(self, mean, m2, weight): + if not (isinstance(mean, HalideCSEVariable) and mean.used_dims is not None): + raise AssertionError("mean must be HalideCSEVariable with used_dims") + if not (isinstance(m2, HalideCSEVariable) and m2.used_dims is not None): + raise AssertionError("m2 must be HalideCSEVariable with used_dims") + if not (isinstance(weight, HalideCSEVariable) and weight.used_dims is not None): + raise AssertionError("weight must be HalideCSEVariable with used_dims") + used_dims = OrderedSet( + (*mean.used_dims, *m2.used_dims, *weight.used_dims) or self.halide_vars + ) + used_dims -= OrderedSet(self.reduction_renames) + result_var = self.newfunc(self.sort_used_dims(used_dims)) + default = [f"hl.cast({x.name}.type(), 0)" for x in (mean, m2, weight)] + pfx = result_var.name + self.body.writeline(f"{result_var} = hl.Tuple([{', '.join(default)}])") + self.body.writeline(f"{pfx}_mean_1 = {result_var}[0]") + self.body.writeline(f"{pfx}_m2_1 = {result_var}[1]") + self.body.writeline(f"{pfx}_weight_1 = {result_var}[2]") + self.body.writeline(f"{pfx}_mean_2 = {mean.subs_str(self.reduction_renames)}") + self.body.writeline(f"{pfx}_m2_2 = {m2.subs_str(self.reduction_renames)}") + self.body.writeline( + f"{pfx}_weight_2 = {weight.subs_str(self.reduction_renames)}" + ) + self.body.writeline(f"{pfx}_delta = {pfx}_mean_2 - {pfx}_mean_1") + self.body.writeline(f"{pfx}_new_weight = {pfx}_weight_1 + {pfx}_weight_2") + self.body.writeline( + f"{pfx}_w2_over_w = hl.select({pfx}_new_weight == 0.0, 0.0, {pfx}_weight_2 / {pfx}_new_weight)" + ) + update = [ + f"{pfx}_mean_1 + {pfx}_delta * {pfx}_w2_over_w", + f"{pfx}_m2_1 + {pfx}_m2_2 + {pfx}_delta * {pfx}_delta * {pfx}_weight_1 * {pfx}_w2_over_w", + f"{pfx}_new_weight", + ] + self.body.writeline(f"{result_var} = hl.Tuple([{', '.join(update)}])") + + unpacked = [] + for i in range(3): + unpacked.append(self.newfunc(result_var.used_dims)) + self.body.writeline(f"{unpacked[-1]} = {result_var}[{i}]") + return tuple(unpacked) + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], tuple[CSEVariable, ...] + ], + values_orig: tuple[CSEVariable, ...], + ) -> tuple[CSEVariable, ...]: + if not self.inside_reduction: + raise AssertionError("scan called outside reduction") + if len(dtypes) != len(values_orig): + raise AssertionError( + f"expected {len(values_orig)} dtypes, got {len(dtypes)}" + ) + values: list[HalideCSEVariable] = [] + all_used_dims = OrderedSet[sympy.Symbol]() + + for value in values_orig: + if not ( + isinstance(value, HalideCSEVariable) and value.used_dims is not None + ): + raise AssertionError("value must be HalideCSEVariable with used_dims") + if OrderedSet(value.used_dims) & OrderedSet(self.reduction_renames): + values.append(value) + else: + values.append( + self.genfunc( + f"{value}", + [*value.used_dims, [*self.reduction_renames][:1]], + shape=value.shape, + ) + ) + all_used_dims.update(value.used_dims) + result_var = self.newfunc(self.sort_used_dims(all_used_dims)) + if not ( + result_var.used_dims + and OrderedSet(result_var.used_dims) & OrderedSet(self.reduction_renames) + ): + raise AssertionError("result_var must use reduction dims") + initial = [ + f"hl.cast({halide_acc_type(dtype)}, {value})" + for dtype, value in zip(dtypes, values) + ] + + length = self.kexpr(self.rename_indexing(self.range_trees[-1].numel)) + scan_dom = f"{result_var.name}_rdom" + scan = f"{scan_dom}.x" + self.body.writeline(f"{scan_dom} = hl.RDom([hl.Range(1, {length})])") + + if len(self.reduction_renames) != 1: + raise AssertionError("multi-dimensional scan not implemented") + (scan_var,) = [*self.reduction_renames] # type: ignore[misc] + scan_renames_cur = {scan_var: sympy_index_symbol(scan)} + scan_renames_pri = {scan_var: sympy_index_symbol(scan) - 1} + + if len(values) == 1: + + def maybe_tuple(x): + return x[0] + + read_left = [result_var.subs_str(scan_renames_pri)] + read_right = [result_var.subs_str(scan_renames_cur)] + else: + + def maybe_tuple(x): + return f"hl.Tuple([{', '.join(x)}])" + + read_left = [ + result_var.subs_str(scan_renames_pri) + f"[{i}]" + for i in range(len(values)) + ] + read_right = [ + result_var.subs_str(scan_renames_cur) + f"[{i}]" + for i in range(len(values)) + ] + + self.body.writeline(f"{result_var} = {maybe_tuple(initial)}") + + # Disable CSE for update fn + with V.set_ops_handler(AddParenHandler(HalideOverrides())): + combine_str = combine_fn(read_left, read_right) # type: ignore[arg-type] + self.body.writeline( + f"{result_var.subs_str(scan_renames_cur)} = {maybe_tuple(combine_str)}" + ) + + if len(values) == 1: + return (result_var,) + + unpack_vars = [self.newfunc(self.sort_used_dims(all_used_dims)) for _ in values] + for i, v in enumerate(unpack_vars): + self.body.writeline(f"{v} = {result_var}[{i}]") + return tuple(unpack_vars) + + def genfunc( + self, + line, + used_dims, + *, + bounds=ValueRanges.unknown(), + shape: BlockShapeType = None, + ) -> HalideCSEVariable: + var = self.cse.generate(self.body, line, bounds=bounds, shape=shape) + if not isinstance(var, HalideCSEVariable): + raise AssertionError(f"expected HalideCSEVariable, got {type(var)}") + var.used_dims = used_dims + return var + + def newfunc(self, used_dims, *, shape: BlockShapeType = None) -> HalideCSEVariable: + var = self.cse.newvar(shape=shape) + if not isinstance(var, HalideCSEVariable): + raise AssertionError(f"expected HalideCSEVariable, got {type(var)}") + var.used_dims = used_dims + return var + + def halide_buffer_numel(self, name: str): + """ + We map all tensors to 1D buffers in Halide since Halide has trouble representing some strides that PyTorch + supports. If there are gaps in the underlying layout the numel we pass to Halide includes the gaps while + PyTorch's numel excludes them. + """ + return V.graph.get_buffer(name).get_layout().storage_size() + + def halide_argdefs(self): + """ + Halide requires scalar inputs before outputs, so need to reorder args. + """ + + def arg_order(arg_tuple): + _call_str, arg = arg_tuple + if isinstance(arg, SizeArg): + return 1 # this would normally be at the end, move it to middle + elif "out_ptr" in arg.name: + return 2 + else: + if "in_ptr" not in arg.name: + raise AssertionError(f"expected in_ptr in arg name, got {arg.name}") + return 0 + + result: list[tuple[str | None, KernelArgType]] = [] + _, a, b, _ = self.args.python_argdefs() + for call_str, arg in sorted(zip(a, b), key=arg_order): + result.append((call_str, arg)) + if isinstance(arg, TensorArg): + if not (arg.offset == 0 and arg.alias_of is None): + raise AssertionError("TensorArg must have zero offset and no alias") + result.extend( + ( + None, + TensorArg( + alias, + arg.buffer, + arg.dtype, + arg.offset, + alias_of=arg.name, + ), + ) + for alias in self.buffer_aliases.get(arg.name, ()) + ) + return result + + def halide_kernel_meta(self) -> HalideMeta: + """Compute metadata required by codecache.py""" + argtypes = [] + for _, arg in self.halide_argdefs(): + if isinstance(arg, SizeArg): + shape = None + stride = None + offset = None + dtype = "long" + else: + shape = [ + cexpr(self.rename_indexing(x.size)) + for x in self.buffer_dimensions[arg.name] + ] + stride = [ + cexpr(self.rename_indexing(x.stride)) + for x in self.buffer_dimensions[arg.name] + ] + if len(shape) != len(stride): + raise AssertionError( + f"shape/stride length mismatch: {len(shape)} vs {len(stride)}" + ) + offset = cexpr(self.buffer_offsets[arg.name]) + dtype = f"{DTYPE_TO_CPP[arg.dtype]}*" + argtypes.append( + HalideInputSpec( + dtype, + arg.name, + shape=shape, + stride=stride, + offset=offset, + alias_of=arg.alias_of, + ) + ) + + current_device = V.graph.get_current_device_or_throw() + if current_device.type == "cpu": + target = [config.halide.cpu_target] + scheduler = config.halide.scheduler_cpu + scheduler_flags = { + "parallelism": parallel_num_threads(), + } + cuda_device = None + else: + if current_device.type != "cuda": + raise AssertionError("only cpu/cuda supported") + if current_device.index > 0: + raise AssertionError("only default device supported") + target = [config.halide.gpu_target] + scheduler = config.halide.scheduler_cuda + capability = torch.cuda.get_device_properties(current_device) + if "cuda_capability" not in target[0]: + for major, minor in [(8, 6), (8, 0), (7, 5), (7, 0), (6, 1)]: + if capability.major >= major and capability.minor >= minor: + target.append(f"cuda_capability_{major}{minor}") + break + target.append("user_context") + scheduler_flags = { + "parallelism": capability.multi_processor_count, + # TODO(jansel): explore other flags, see: + # grep parser.parse ~/Halide/src/autoschedulers/anderson2021/AutoSchedule.cpp + } + cuda_device = max(0, current_device.index) + + # strict_float is required for correctness + target.append("strict_float") + + # without this we will initialize cuda once per kernel and hit errors + target.append("no_runtime") + + if not config.halide.asserts: + target.append("no_asserts") + + if config.halide.debug: + target.append("debug") + + if "64" in self.index_dtype: + # TODO(jansel): it is unclear if this does anything, since input sizes are still int32 + target.append("large_buffers") + + return HalideMeta( + argtypes, + target="-".join(target), + scheduler=scheduler, + scheduler_flags=scheduler_flags, # type: ignore[arg-type] + cuda_device=cuda_device, + ) + + def codegen_kernel(self, name=None): + """Called at the end to generate a final kernel string""" + if self.args.inplace_buffers: + raise Unsupported("inplace_buffers") + meta = self.halide_kernel_meta() # ensure needed args are added early + code = IndentedBuffer() + code.splice( + """ + import halide as hl + from torch._inductor.runtime import halide_helpers + from math import inf, nan + + @hl.generator(name="kernel") + class Kernel: + """, + strip=True, + ) + code.do_indent() + for _, arg in self.halide_argdefs(): + if isinstance(arg, SizeArg): + code.writeline(f"{arg.name} = hl.InputScalar({self.index_dtype})") + else: + if not arg.buffer: + raise AssertionError(arg) + argcls = "hl.OutputBuffer" if "out" in arg.name else "hl.InputBuffer" + argtype = halide_type(arg.dtype) + ndim = len(self.buffer_dimensions[arg.name]) + code.writeline(f"{arg.name} = {argcls}({argtype}, {ndim})") + code.splice( + """ + def generate(g): + """ + ) + code.do_indent() + for _, arg in self.halide_argdefs(): + code.writeline(f"{arg.name} = g.{arg.name}") + for old, new in self.args.aliases(): + code.writeline(f"{old} = {new}") + code.splice(self.indexing_code) + + def update_index(m): + var = cast(HalideCSEVariable, self.cse.varname_map[m.group(1)]) + if var.used_dims is None: + raise AssertionError(var) + return str(var) + + for line in self.body._lines: + if isinstance(line, str): + # fill in missing indices + line = HalideCSEVariable.undefined_re.sub(update_index, line) + code.writeline(line) + code.writeline("") + code.writeline("assert g.using_autoscheduler()") + + for _, arg in self.halide_argdefs(): + # fallback=1 below because halide requires buffers to be at least as large as the estimates + # This causes crashes if our estimate is greater than the vector length + # https://github.com/halide/Halide/issues/3103 + if isinstance(arg, SizeArg): + hint = V.graph.sizevars.optimization_hint(arg.expr, fallback=1) + code.writeline(f"{arg.name}.set_estimate({hint})") + else: + dims = self.buffer_dimensions[arg.name] + range_hints = [] + for i, dim in enumerate(dims): + hint = self._autoscheduler_workarounds( + V.graph.sizevars.optimization_hint(dim.size, fallback=1), dims + ) + # pyrefly: ignore [bad-argument-type] + range_hints.append(f"hl.Range(0, {hint})") + if "out" not in arg.name: + code.writeline(f"{arg.name}.dim({i}).set_min(0)") + try: + code.writeline( + f"{arg.name}.dim({i}).set_stride({int(dim.stride)})" + ) + except TypeError: + pass # not integer + try: + code.writeline( + f"{arg.name}.dim({i}).set_extent({int(dim.size)})" + ) + except TypeError: + pass # not integer + code.writeline(f"{arg.name}.set_estimates([{', '.join(range_hints)}])") + + code.do_unindent(2) + code.splice( + """ + if __name__ == "__main__": + hl.main() + """.rstrip(), + ) + if meta.scheduler: + code.splice( + f""" + else: + hl.load_plugin({HalideCodeCache.find_libautoschedule(meta.scheduler)!r}) + target = hl.Target({meta.target!r}) + autoscheduler = hl.AutoschedulerParams({meta.scheduler!r}, {meta.scheduler_flags!r}) + with hl.GeneratorContext(target, autoscheduler): + gen = Kernel() + pipeline = gen._build_pipeline() + # gen.compile_to_callable() does not run the autoscheduler + pipeline.apply_autoscheduler(target, autoscheduler) + kernel = pipeline.compile_to_callable([ + gen._get_input_parameter(a.name)._to_argument() + for a in gen._get_arginfos() + if a.dir == hl.ArgInfoDirection.Input + ], target) + """, + strip=True, + ) + else: + code.splice( + f""" + else: + with hl.GeneratorContext(hl.Target({meta.target!r})): + kernel = Kernel().compile_to_callable() + """, + strip=True, + ) + return code.getvalue() + + @staticmethod + def _autoscheduler_workarounds(n, dims): + if ( + len(dims) == 1 + and config.halide.scheduler_cuda == "Anderson2021" + and V.graph.get_current_device_or_throw().type == "cuda" + ): + # workaround https://github.com/halide/Halide/issues/8246 + n = max(2, n) + return n + + def call_kernel(self, name: str, node=None, deallocate_ws: bool = True): + """Codegen a call to this kernel""" + wrapper = V.graph.wrapper_code + call_args = [f"{n}" for n, arg in self.halide_argdefs() if arg.alias_of is None] + current_device = V.graph.get_current_device_or_throw() + if current_device.type == "cuda": + stream_name = wrapper.write_get_raw_stream( + current_device.index, V.graph.name + ) + call_args.append(stream_name) + wrapper.generate_kernel_call( + name, + call_args, + device=current_device, + triton=False, + ) + + def generate_assert(self, check): + return False # TODO(jansel): support asserts + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ): + pass # TODO(jansel): support asserts + + +class HalideScheduling(SIMDScheduling): + kernel_type = HalideKernel # type: ignore[arg-type,assignment] + + @classmethod + def get_backend_features(cls, device: torch.device) -> OrderedSet[BackendFeature]: + result = OrderedSet( + [ + BackendFeature.TUPLE_REDUCTION, + BackendFeature.PREFER_STORE_LOOP_ORDER, + BackendFeature.REDUCE_TO_SINGLE_ELEMENT, + ] + ) + if config.halide.scan_kernels: + result.add(BackendFeature.SCAN) + return result + + def define_kernel(self, src_code, node_schedule, kernel): + """Codegen kernel definition to go in output wrapper code""" + wrapper = V.graph.wrapper_code + if src_code in wrapper.src_to_kernel: + kernel_name = wrapper.src_to_kernel[src_code] + else: + kernel_name = f"halide_kernel_{wrapper.next_kernel_suffix()}" + wrapper.src_to_kernel[src_code] = kernel_name + wrapper.add_import_once( + "from torch._inductor.runtime.hints import HalideMeta, HalideInputSpec" + ) + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline( + f"async_compile.halide({kernel.halide_kernel_meta()!r}, '''" + ) + compile_wrapper.splice(src_code, strip=True) + compile_wrapper.writeline("''')") + + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + metadata_comment = f"{origins}\n{detailed_origins}" + wrapper.define_kernel( + kernel_name, compile_wrapper.getvalue(), metadata_comment + ) + if is_metric_table_enabled("kernel_metadata"): + log_kernel_metadata(kernel_name, "", src_code) + + return kernel_name diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/memory_planning.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/memory_planning.py new file mode 100644 index 0000000000000000000000000000000000000000..a4c41071e7bcc8a03e7c07f74d9c49697a28bc7c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/memory_planning.py @@ -0,0 +1,849 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import collections +import dataclasses +import itertools +import pprint +from typing import Any, Protocol, TYPE_CHECKING + +import torch +from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import Max + +from .. import config +from ..utils import _align, align, cache_on_self, CachedMethod, IndentedBuffer +from ..virtualized import V +from .wrapper import ( + AllocateLine, + BufferLike, + FreeIfNotReusedLine, + MemoryPlanningLine, + NullLine, + ReuseLine, +) + + +if TYPE_CHECKING: + from collections.abc import Iterable + + import sympy + + +@dataclasses.dataclass +class LiveRange: + """ + A range where a given tensor is live. Begin and end are both counters + representing points in the program of grouped memory operations. + Begin is inclusive, end is exclusive. + + Invariant: begin <= end + """ + + begin: float # int | +/-inf + end: float # int | +/-inf + + def contains(self, other: LiveRange): + """Is other entirely within self""" + return self.begin <= other.begin and other.end <= self.end + + def join(self, other: LiveRange): + """Combine two ranges using a union operation""" + return LiveRange(min(self.begin, other.begin), max(self.end, other.end)) + + def __len__(self): + return self.end - self.begin + + +class LiveRanges: + """ + A collection of LiveRange regions, allowing for non-contiguous + live regions. + + Invariant: LiveRanges.ranges is in sorted order and non-overlapping + """ + + def __init__(self, ranges: Iterable[LiveRange]): + ranges = [*sorted(ranges, key=lambda x: x.begin)] + self.ranges = ranges[:1] + for r in ranges[1:]: + if self.ranges[-1].begin > r.begin: + raise AssertionError("ranges must be sorted by begin") + if self.ranges[-1].end >= r.begin: + self.ranges[-1] = LiveRange.join(self.ranges[-1], r) + else: + self.ranges.append(r) + + def overlaps(self, other: LiveRanges): + """Check if any pair of ranges in self and other overlap""" + left = collections.deque(self.ranges) + right = collections.deque(other.ranges) + while left and right: + if left[0].begin > right[0].begin: + left, right = right, left + if left[0].begin > right[0].begin: + raise AssertionError("left should begin no later than right") + if left[0].end > right[0].begin: + return True + left.popleft() + return False + + @property + def begin(self): + return self.ranges[0].begin + + @property + def end(self): + return self.ranges[-1].end + + def __repr__(self): + return f"{self.__class__.__name__}([{', '.join(map(repr, self.ranges))}])" + + +class AllocationTreeNode: + """ + Abstract base class for nodes in allocation pool. + """ + + def allocate(self, block: Allocation, is_last: bool) -> bool: + """ + Try to assign block to a memory location in this pool. Return True if + an assignment was made. + """ + return False + + def get_live_ranges(self) -> LiveRanges: + """Aggregate LiveRanges for all objects below this in tree""" + raise NotImplementedError + + def get_size_hint(self) -> int: + """Number of bytes used for example inputs""" + raise NotImplementedError + + def get_symbolic_size(self) -> sympy.Expr: + """Number of bytes needed at runtime""" + raise NotImplementedError + + def finalize(self, pool, offset) -> AllocationTreeNode: + """Called after all allocations have been made""" + return self + + def is_empty(self): + return False + + +@dataclasses.dataclass +class Allocation(AllocationTreeNode): + """ + Represents memory allocated to a given node in the allocation pool. + """ + + node: BufferLike + live_range: LiveRange + size_hint: int + symbolic_size: sympy.Expr + allocated: bool = False + pool: AllocationPool | None = None + offset: sympy.Expr | None = None + earliest_available: float | None = None + + def __post_init__(self) -> None: + has_unbacked_sym = False + for s in self.node.get_layout().size: + if free_unbacked_symbols(s): + has_unbacked_sym = True + break + + if has_unbacked_sym: + self.earliest_available = self.get_live_ranges().begin + + @property + def device(self): + return self.node.get_device() + + def get_live_ranges(self): + return LiveRanges([self.live_range]) + + def get_size_hint(self): + return self.size_hint + + def get_symbolic_size(self): + return self.symbolic_size + + def mark_allocated(self): + if self.allocated: + raise AssertionError("block already allocated") + self.allocated = True + + def finalize(self, pool, offset): + if not (self.pool is None and self.offset is None): + raise AssertionError("block already finalized") + self.pool = pool + self.offset = offset + return self + + def codegen_alloc_from_pool(self, wrapper): + if not self.pool: + raise AssertionError("block has no pool assigned") + node = self.node + shape = tuple(node.get_size()) + stride = tuple(node.get_stride()) + return wrapper.codegen_alloc_from_pool( + self.pool.name, self.offset, node.get_dtype(), shape, stride + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(" + f"node={self.node.get_name()}, " + f"live_range={self.live_range}, " + f"size_hint={self.size_hint}, " + f"symbolic_size={self.symbolic_size}, " + f"pool={self.pool.name if self.pool else None}, " + f"offset={self.offset})" + ) + + def get_earliest_available(self): + return self.earliest_available + + +@dataclasses.dataclass +class Empty(AllocationTreeNode): + """ + Placeholder to represent empty space in the allocation pool. + Only exists to get the size_hint correct in parent nodes. + """ + + size_hint: int + + def get_live_ranges(self): + return LiveRanges([]) + + def get_size_hint(self): + return self.size_hint + + def get_symbolic_size(self): + return 0 + + def is_empty(self): + return True + + +class MemorySplitProtocol(Protocol): + get_live_ranges: CachedMethod[[], LiveRanges] + get_size_hint: CachedMethod[[], int] + get_symbolic_size: CachedMethod[[], sympy.Expr] + + def _allocate(self, block: Allocation, is_last: bool) -> bool: ... + + +class ClearCacheOnAllocateMixin(MemorySplitProtocol): + """ + Helper to assist in caching get_live_ranges, get_size_hint, and + get_symbolic_size. + """ + + def allocate(self, block: Allocation, is_last: bool): + is_allocated = self._allocate(block, is_last) + if is_allocated: + self.clear_cache() + return is_allocated + + def clear_cache(self): + self.get_live_ranges.clear_cache(self) + self.get_size_hint.clear_cache(self) + self.get_symbolic_size.clear_cache(self) + + +@dataclasses.dataclass +class TemporalSplit(ClearCacheOnAllocateMixin, AllocationTreeNode): + """ + Contains a list of allocations not overlapping in LiveRanges. + + Invariant: no pair (a,b) in self.allocations will have: + a.get_live_ranges().overlaps(b.get_live_ranges()) + """ + + allocations: list[AllocationTreeNode] + + def _allocate(self, block: Allocation, is_last: bool): + slot_size = self.get_size_hint() + block_size = block.get_size_hint() + if not is_last and block_size > slot_size: + return False # doesn't fit + + block_live = block.get_live_ranges() + overlapping = [ + s for s in self.allocations if s.get_live_ranges().overlaps(block_live) + ] + if len(overlapping) > 1: + # TODO(jansel): we could try harder here by merging overlapping in space + return False + elif len(overlapping) == 1: + return overlapping[0].allocate(block, is_last) + else: + block.mark_allocated() + + if len(self.allocations) == 1 and isinstance(self.allocations[-1], Empty): + self.allocations.pop() + + if slot_size == block_size: + # perfect fit + self.allocations.append(block) + elif slot_size > block_size: + self.allocations.append( + SpatialSplit.create(block, slot_size - block_size) + ) + else: # grow this allocation + if not is_last: + raise AssertionError("can only grow allocation when is_last") + self.allocations = [ + *( + SpatialSplit.create(a, block_size - slot_size) + for a in self.allocations + ), + block, + ] + return True + + @cache_on_self + def get_live_ranges(self) -> LiveRanges: + return LiveRanges( + itertools.chain.from_iterable( + x.get_live_ranges().ranges for x in self.allocations + ) + ) + + @cache_on_self + def get_size_hint(self) -> int: + if not self.allocations: + return 0 + return max(x.get_size_hint() for x in self.allocations) + + @cache_on_self + def get_symbolic_size(self) -> sympy.Expr: + if not self.allocations: + return 0 # type: ignore[return-value] + return Max(*[x.get_symbolic_size() for x in self.allocations]) + + def is_empty(self): + return len(self.allocations) == 1 and self.allocations[0].is_empty() + + def finalize(self, pool, offset): + self.allocations = [block.finalize(pool, offset) for block in self.allocations] + self.clear_cache() + if len(self.allocations) == 1: + return self.allocations[0] + return self + + +@dataclasses.dataclass +class SpatialSplit(ClearCacheOnAllocateMixin, AllocationTreeNode): + """ + Contains two allocations, left and right, that do not overlap in space. + Right will be allocated immediately after left in memory. + """ + + left: TemporalSplit + right: TemporalSplit + + @staticmethod + def create(left, extra_space): + if not isinstance(left, AllocationTreeNode): + raise AssertionError(f"expected AllocationTreeNode, got {type(left)}") + if not (isinstance(extra_space, int) and extra_space >= 1): + raise AssertionError( + f"expected positive int extra_space, got {extra_space}" + ) + return SpatialSplit(TemporalSplit([left]), TemporalSplit([Empty(extra_space)])) + + def _allocate(self, block: Allocation, is_last: bool): + return self.left.allocate(block, False) or self.right.allocate(block, is_last) + + @cache_on_self + def get_live_ranges(self): + return LiveRanges( + itertools.chain( + self.left.get_live_ranges().ranges, self.right.get_live_ranges().ranges + ) + ) + + @cache_on_self + def get_size_hint(self) -> int: + return _align(self.left.get_size_hint()) + self.right.get_size_hint() + + @cache_on_self + def get_symbolic_size(self) -> sympy.Expr: + return align(self.left.get_symbolic_size()) + self.right.get_symbolic_size() + + def finalize(self, pool, offset): + self.left = self.left.finalize(pool, offset) + self.right = self.right.finalize( + pool, offset + align(self.left.get_symbolic_size()) + ) + self.clear_cache() + if self.right.is_empty(): + return self.left + return self + + +@dataclasses.dataclass +class AllocationPool: + """ + Represents a pool of allocations that will be generated by a single + call to torch.empty. + """ + + device: torch.device + root: TemporalSplit + can_expand: bool = True + restrict_live_range: LiveRange | None = None + name: str | None = None + names_to_del: list[str] = dataclasses.field(default_factory=list) + creation_cache: dict[str, str] = dataclasses.field(default_factory=dict) + + def __post_init__(self) -> None: + for block in self.root.allocations: + if isinstance(block, Allocation): + self.update_restrict_live_range(block) + + def allocate(self, block: Allocation, is_last: bool): + if ( + self.restrict_live_range is not None + and not self.restrict_live_range.contains(block.live_range) + ): + return False + + block_earliest_available = block.get_earliest_available() + pool_begin = self.root.get_live_ranges().begin + if block_earliest_available and block_earliest_available > pool_begin: + return False + + is_last = self.can_expand and is_last + if self.root.allocate(block, is_last): + self.update_restrict_live_range(block) + return True + + if is_last: + return self.allocate_at_end(block) + + return False + + def update_restrict_live_range(self, block: Allocation): + if block_earliest_available := block.get_earliest_available(): + if self.restrict_live_range is None: + self.restrict_live_range = LiveRange( + block_earliest_available, float("inf") + ) + else: + self.restrict_live_range = LiveRange( + min(self.restrict_live_range.begin, block_earliest_available), + self.restrict_live_range.end, + ) + + def allocate_at_end(self, block): + block.mark_allocated() + self.root = TemporalSplit([SpatialSplit(self.root, TemporalSplit([block]))]) + self.update_restrict_live_range(block) + return True + + def finalize(self, name): + if self.name: + raise AssertionError("pool already finalized") + self.name = name + self.names_to_del.append(name) + self.root.finalize(self, 0) + + def codegen_create(self, wrapper, code: IndentedBuffer): + if not self.name: + raise AssertionError("pool must be finalized before codegen_create") + nbytes = self.root.get_symbolic_size() + for block in self.root.allocations: + if isinstance(block, Allocation) and nbytes == block.get_symbolic_size(): + node = block.node + code.writeline( + wrapper.make_allocation( + self.name, + device=self.device, + dtype=node.get_dtype(), + shape=tuple(node.get_size()), + stride=tuple(node.get_stride()), + ) + ) + return + else: + code.writeline( + wrapper.make_allocation( + self.name, + device=self.device, + dtype=torch.uint8, + shape=(nbytes,), + stride=(1,), + ) + ) + + def codegen_destroy(self, wrapper, code: IndentedBuffer): + code.writeline(wrapper.make_free_by_names(self.names_to_del)) + + def __eq__(self, other): + return self is other + + def __hash__(self): + return id(self) + + +@dataclasses.dataclass +class AllocationPools: + """ + Collection of many AllocationPool objects grouped by device. + """ + + device_to_pools: dict[torch.device, list[AllocationPool]] = dataclasses.field( + default_factory=dict + ) + + def get_pools(self, block): + if block.device not in self.device_to_pools: + self.device_to_pools[block.device] = [] + return self.device_to_pools[block.device] + + def allocate(self, block: Allocation): + pools = self.get_pools(block) + + for pool in pools: + if pool.allocate(block, is_last=pool is pools[-1]): + return + + # everything is full, make a new pool + pools.append( + AllocationPool( + block.device, + TemporalSplit([block]), + can_expand=config.memory_pool != "none", + ) + ) + block.mark_allocated() + + def allocate_output(self, block: Allocation): + """Outputs get different pools so memory gets freed properly""" + pools = self.get_pools(block) + if pools and config.memory_pool in ("outputs", "combined"): + pools[-1].allocate_at_end(block) + else: + # create a new pool + block.mark_allocated() + pools.append( + AllocationPool( + block.device, + TemporalSplit([block]), + can_expand=config.memory_pool == "combined", + ) + ) + + def finalize(self): + """Called at the end of allocation process""" + for i, pool in enumerate( + itertools.chain.from_iterable(self.device_to_pools.values()) + ): + pool.finalize(f"pool{i}") + + def pprint(self): + for pool in itertools.chain.from_iterable(self.device_to_pools.values()): + print() + print(pool.name) + print(pool.root.get_live_ranges()) + pprint.pprint(pool.root) + + +class BufferGroup: + """ + Due to inplace reuse an allocated buffer can have many names. + This tracks these collections of buffers sharing underlying memory. + """ + + def __init__(self, node: BufferLike): + self.node = node + self.names = [node.get_name()] + self.is_output = False + self.allocation: Allocation | None = None + self.live_range = LiveRange(float("inf"), -float("inf")) + + def update_usage(self, timestep: int): + """Expand self.live_range to include timestep""" + self.live_range = LiveRange( + min(timestep, self.live_range.begin), + max(timestep, self.live_range.end), + ) + + def sym_nbytes(self): + return self.node.get_layout().storage_size() * self.node.get_dtype().itemsize + + def make_allocation(self): + if self.allocation: + raise AssertionError("multiple allocations") + if not isinstance(self.live_range.begin, int): + raise AssertionError("live ranges not computed") + nbytes = self.sym_nbytes() + # For now, fallback value will be used if we encounter an unbacked SymInt. The longer-term plan is to have + # size_hint() use better heuristics for unbackeds, at which point the fallback value will be ignored. + size_hint = V.graph.sizevars.optimization_hint(nbytes, fallback=64) + self.allocation = Allocation( + self.node, + self.live_range, + size_hint=size_hint, + symbolic_size=nbytes, + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}({self.names!r}, is_output={self.is_output}, " + f"live_range={self.live_range}" + ) + + +@dataclasses.dataclass +class PoolMemoryPlanningLine(MemoryPlanningLine): + """Abstract base class for {Alloc,Dealloc}FromPoolLine""" + + group: BufferGroup + timestep: int | None = None + + @property + def node(self): + return self.group.node + + +@dataclasses.dataclass +class AllocFromPoolLine(PoolMemoryPlanningLine): + """Similar to AllocationLine, but takes memory from a pool""" + + is_first_pool_usage: bool = False + + def codegen(self, code: IndentedBuffer): + allocation = self.group.allocation + if not (allocation and allocation.pool): + raise AssertionError("group must have an allocation with a pool") + pool = allocation.pool + name = self.node.get_name() + + if self.is_first_pool_usage: + pool.codegen_create(self.wrapper, code) + + pool.names_to_del.extend(self.group.names) + alloc_from_pool, allocation_lines_to_write = allocation.codegen_alloc_from_pool( + self.wrapper + ) + code.writelines(allocation_lines_to_write) + if alloc_from_pool in pool.creation_cache: + code.writeline( + self.wrapper.make_tensor_alias( + name, pool.creation_cache[alloc_from_pool], "alloc" + ) + ) + else: + pool.creation_cache[alloc_from_pool] = name + code.writeline( + f"{self.wrapper.declare}{name} = {alloc_from_pool}{self.wrapper.ending}" + ) + + +@dataclasses.dataclass +class DeallocFromPoolLine(PoolMemoryPlanningLine): + """Similar to FreeIfNotReusedLine, but takes memory from a pool""" + + is_last_pool_usage: bool = False + + def codegen(self, code: IndentedBuffer): + if self.is_last_pool_usage: + if not (self.group.allocation and self.group.allocation.pool): + raise AssertionError("group must have an allocation with a pool") + self.group.allocation.pool.codegen_destroy(self.wrapper, code) + + +@dataclasses.dataclass +class MemoryPlanner: + """ + Coordination object to run memory planning passes during wrapper + codegen. + """ + + wrapper: Any + pools: AllocationPools = dataclasses.field(default_factory=AllocationPools) + buffer_groups: list[BufferGroup] | None = None + + def plan(self, lines: list[Any]) -> list[Any]: + """Call all the memory planning passes in sequence""" + lines = [*lines] + self.drop_removed_buffers(lines) + self.convert_to_pool_lines(lines) + self.compute_live_ranges(lines) + self.allocate_groups() + self.mark_first_last_usage(lines) + return lines + + def drop_removed_buffers(self, lines): + """ + Replace any memory planning lines in V.graph.removed_buffers with NullLine + """ + # drop any removed buffers + for i, line in enumerate(lines): + if isinstance(line, (AllocateLine, FreeIfNotReusedLine, ReuseLine)): + if line.node.get_name() in V.graph.removed_buffers: + lines[i] = NullLine(self.wrapper) + + def compute_buffer_groups(self, lines): + """ + Populates self.buffer_groups with BufferGroup objects that join + allocations with common storage (due to inplace reuse) into a + single object. + """ + name_to_group = {} + for line in lines: + if isinstance(line, AllocateLine): + name = line.node.get_name() + if name in name_to_group: + raise AssertionError(f"duplicate allocation for {name}") + name_to_group[name] = BufferGroup(line.node) + elif isinstance(line, ReuseLine): + old_name = line.node.get_name() + new_name = line.reused_as.get_name() + if new_name in name_to_group: + raise AssertionError(f"duplicate group for reused {new_name}") + # TODO(jansel): we should support reusing buffers created via ExternKernelAlloc + if old_name in name_to_group: + name_to_group[old_name].names.append(new_name) + name_to_group[new_name] = name_to_group[old_name] + + outputs = OrderedSet(V.graph.get_output_names()) + unique_groups = [*{id(g): g for g in name_to_group.values()}.values()] + for group in unique_groups: + group.is_output = any(x in outputs for x in group.names) or any( + any(user.node.get_name() == "OUTPUT" for user in buf.users) + for name in group.names + if (buf := V.graph.scheduler.name_to_buf.get(name)) is not None + ) + + if self.buffer_groups is not None: + raise AssertionError("buffer_groups already computed") + self.buffer_groups = unique_groups + return name_to_group + + def convert_to_pool_lines(self, lines): + """ + Convert AllocateLine/FreeIfNotReusedLine/ReuseLine into their + pool-based counterparts. + """ + name_to_group = self.compute_buffer_groups(lines) + for i, line in enumerate(lines): + if isinstance(line, AllocateLine): + if line.node.get_name() in name_to_group: + lines[i] = AllocFromPoolLine( + self.wrapper, name_to_group[line.node.get_name()] + ) + elif isinstance(line, FreeIfNotReusedLine): + if line.is_reused: + raise AssertionError("expected line not to be reused") + if line.node.get_name() in name_to_group: + lines[i] = DeallocFromPoolLine( + self.wrapper, name_to_group[line.node.get_name()] + ) + elif isinstance(line, ReuseLine): + if line.node.get_name() in name_to_group: + line.delete_old = False + + def compute_live_ranges(self, lines): + """Populate every BufferGroup.live_ranges field based on first/last usage""" + timestep = 0 + worklist = collections.deque(lines) + while worklist: + if isinstance(worklist[0], MemoryPlanningLine): + timestep += 1 + while worklist and isinstance(worklist[0], MemoryPlanningLine): + line = worklist.popleft() + if isinstance(line, PoolMemoryPlanningLine): + line.group.update_usage(timestep) + line.timestep = timestep + else: + worklist.popleft() + + timestep += 1 + if self.buffer_groups is None: + raise AssertionError("buffer_groups not computed") + for group in self.buffer_groups: + if group.is_output: + group.update_usage(timestep) + + def allocate_groups(self): + """ + Assign every allocation to a specific location in a specific AllocationPool. + """ + if config.memory_pool not in ("none", "intermediates", "outputs", "combined"): + raise AssertionError(f"invalid memory_pool {config.memory_pool}") + if self.buffer_groups is None: + raise AssertionError("buffer_groups not computed") + + for group in self.buffer_groups: + group.make_allocation() + + outputs: list[Allocation] = [] + intermediates: list[Allocation] = [] + for group in self.buffer_groups: + if not group.allocation: + raise AssertionError("group has no allocation") + if group.is_output and config.memory_pool != "combined": + outputs.append(group.allocation) + else: + intermediates.append(group.allocation) + + for block in sorted( + outputs, + key=lambda x: ( + x.size_hint, + -len(x.live_range), + ), + ): + self.pools.allocate_output(block) + + for block in sorted( + intermediates, + key=lambda x: ( + -x.size_hint, + -len(x.live_range), + ), + ): + self.pools.allocate(block) + + self.pools.finalize() + + def mark_first_last_usage(self, lines): + """ + Populate the AllocFromPoolLine.is_first_pool_usage and + DeallocFromPoolLine.is_last_pool_usage fields so that pools + are created/destroyed. + """ + seen = OrderedSet[AllocationPool]() + for line in lines: + if isinstance(line, AllocFromPoolLine): + if not line.group.allocation: + raise AssertionError("group has no allocation") + pool = line.group.allocation.pool + if pool is None: + raise AssertionError("allocation has no pool") + if pool not in seen: + line.is_first_pool_usage = True + seen.add(pool) + + seen = OrderedSet[AllocationPool]() + for line in reversed(lines): + if isinstance(line, DeallocFromPoolLine): + if not line.group.allocation: + raise AssertionError("group has no allocation") + pool = line.group.allocation.pool + if pool is None: + raise AssertionError("allocation has no pool") + if pool not in seen: + line.is_last_pool_usage = ( + pool.root.get_live_ranges().end <= line.timestep + ) + seen.add(pool) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/metal_flex_attention_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/metal_flex_attention_template.py new file mode 100644 index 0000000000000000000000000000000000000000..6e1604d730d34088fd68eeee2ac1a6815e721776 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/metal_flex_attention_template.py @@ -0,0 +1,1048 @@ +# mypy: allow-untyped-defs +"""Metal shader template for flex attention on MPS""" + +import itertools +import operator +from collections import namedtuple +from collections.abc import Sequence +from typing import Any + +import torch +from torch.utils._ordered_set import OrderedSet + +from .. import ir + + +METAL_DTYPE_MAP = { + torch.float32: "float", + torch.float16: "half", + torch.bfloat16: "bfloat", +} + +# Captured score_mod/mask_mod buffers may hold more types than q/k/v; elements +# are always loaded and cast to float for use in the (float-typed) op table. +# Integer captures (e.g. document ids) are therefore exact only below 2**24, +# which covers realistic id/index ranges. +CAPTURE_DTYPE_MAP = { + torch.float32: "float", + torch.float16: "half", + torch.bfloat16: "bfloat", + torch.int64: "long", + torch.int32: "int", + torch.int16: "short", + torch.int8: "char", + torch.uint8: "uchar", + torch.bool: "bool", +} + +# log2(e) for converting flex attention stats back +RCP_LN2 = "1.44269504088896340736f" + +# A captured buffer bound as a Metal kernel argument, with its static shape. +_CapturedBuf = namedtuple("_CapturedBuf", ["name", "sizes", "strides", "dtype"]) +# A captured SymInt (dynamic-shape closure) packed into the scalar _params +# buffer; `name` is the unpacked Metal variable holding its runtime value. +_CapturedScalar = namedtuple("_CapturedScalar", ["name"]) + +# Python operator builtins appear in score_mod/mask_mod when a closure does +# arithmetic/comparison on captured SymInts (e.g. q_idx < (s0 // 32) * 32). +# Arithmetic preserves integer typing when both operands are integral, so a +# downstream floordiv/index stays exact; otherwise it falls back to float. +_INT_PRESERVING_OPS = {operator.add: "+", operator.sub: "-", operator.mul: "*"} +_CMP_OPS = { + operator.lt: "<", + operator.le: "<=", + operator.gt: ">", + operator.ge: ">=", + operator.eq: "==", + operator.ne: "!=", +} + +# Fixed score/mask placeholders bound to integer index variables in the kernel; +# the score placeholder (score_val) is the only float-typed fixed input. +_INT_INDEX_VARS = OrderedSet(["b_idx", "h_idx", "m_idx", "n_idx"]) + + +# FX aten target -> (output C type, Metal format string with positional {} placeholders). +aten = torch.ops.aten +prims = torch.ops.prims +_OP_TABLE: dict[Any, tuple[str, str]] = { + # Arithmetic + aten.add.Tensor: ("float", "{} + {}"), + aten.add.Scalar: ("float", "{} + {}"), + aten.sub.Tensor: ("float", "{} - {}"), + aten.sub.Scalar: ("float", "{} - {}"), + aten.mul.Tensor: ("float", "{} * {}"), + aten.mul.Scalar: ("float", "{} * {}"), + # Cast to float so Python truediv semantics hold even when both operands are ints + aten.div.Tensor: ("float", "static_cast({}) / static_cast({})"), + aten.div.Scalar: ("float", "static_cast({}) / static_cast({})"), + aten.neg.default: ("float", "-{}"), + aten.abs.default: ("float", "metal::abs({})"), + # Comparisons + aten.gt.Tensor: ("bool", "{} > {}"), + aten.gt.Scalar: ("bool", "{} > {}"), + aten.ge.Tensor: ("bool", "{} >= {}"), + aten.ge.Scalar: ("bool", "{} >= {}"), + aten.lt.Tensor: ("bool", "{} < {}"), + aten.lt.Scalar: ("bool", "{} < {}"), + aten.le.Tensor: ("bool", "{} <= {}"), + aten.le.Scalar: ("bool", "{} <= {}"), + aten.eq.Tensor: ("bool", "{} == {}"), + aten.eq.Scalar: ("bool", "{} == {}"), + aten.ne.Tensor: ("bool", "{} != {}"), + aten.ne.Scalar: ("bool", "{} != {}"), + aten.logical_and.default: ("bool", "{} && {}"), + aten.logical_or.default: ("bool", "{} || {}"), + aten.logical_not.default: ("bool", "!{}"), + # Math + aten.exp.default: ("float", "metal::precise::exp({})"), + aten.log.default: ("float", "metal::precise::log({})"), + aten.sqrt.default: ("float", "metal::precise::sqrt({})"), + aten.rsqrt.default: ("float", "metal::precise::rsqrt({})"), + aten.tanh.default: ("float", "metal::precise::tanh({})"), + aten.sin.default: ("float", "metal::precise::sin({})"), + aten.cos.default: ("float", "metal::precise::cos({})"), + aten.exp2.default: ("float", "metal::precise::exp2({})"), + # remainder + aten.remainder.Scalar: ("float", "c10::metal::remainder({}, (float){})"), + aten.remainder.Tensor: ("float", "c10::metal::remainder({}, {})"), + aten.maximum.default: ("float", "metal::max({}, {})"), + aten.max.other: ("float", "metal::max({}, {})"), + aten.minimum.default: ("float", "metal::min({}, {})"), + aten.min.other: ("float", "metal::min({}, {})"), + # Bitwise - int output + aten.bitwise_and.Tensor: ("int", "(int){} & (int){}"), + aten.bitwise_and.Scalar: ("int", "(int){} & (int){}"), + aten.bitwise_or.Tensor: ("int", "(int){} | (int){}"), + aten.bitwise_or.Scalar: ("int", "(int){} | (int){}"), + aten.where.self: ("float", "{} ? {} : {}"), + aten._to_copy.default: ("float", "static_cast({})"), + aten.to.dtype: ("float", "static_cast({})"), + prims.convert_element_type.default: ("float", "static_cast({})"), + aten.scalar_tensor.default: ("float", "{}"), +} +del aten, prims + + +def _fx_graph_to_metal( + graph_module: torch.fx.GraphModule, + fixed_inputs: dict[str, str], + captured: dict[str, Any], + output_var: str, + var_prefix: str, + int_ctype: str = "int", +) -> str: + """Compile an FX GraphModule to inline Metal code. + + `fixed_inputs` maps scalar placeholder names (score/b/h/q/kv) to Metal + variables. `captured` maps captured placeholder names to a `_CapturedBuf` + (a tensor, indexed by `aten.index.Tensor` down to a scalar load) or a + `_CapturedScalar` (a SymInt bound directly to a Metal variable). The output + is assigned to `output_var`; `var_prefix` namespaces fresh temps. + """ + var_map: dict[str, str] = {} + views: dict[str, tuple] = {} + # Names of temps/placeholders known to hold an integer value, so operator + # arithmetic on captured SymInts stays in integer math (exact, proper floor). + int_vars: OrderedSet[str] = OrderedSet( + ph for ph, mv in fixed_inputs.items() if mv in _INT_INDEX_VARS + ) + code_lines: list[str] = [] + tmp_counter = itertools.count() + + def _is_int(node) -> bool: + if isinstance(node, bool): + return False + if isinstance(node, int): + return True + return isinstance(node, torch.fx.Node) and node.name in int_vars + + # Only emit nodes the output depends on; this drops dead constant captures + output_node = next(n for n in graph_module.graph.nodes if n.op == "output") + needed: OrderedSet[str] = OrderedSet() + stack = list(output_node.all_input_nodes) + while stack: + nd = stack.pop() + if nd.name not in needed: + needed.add(nd.name) + stack.extend(nd.all_input_nodes) + + def _tmp() -> str: + return f"{var_prefix}{next(tmp_counter)}" + + def _val(node) -> str: + if isinstance(node, torch.fx.Node): + if node.name in views: + raise NotImplementedError( + "flex_attention on MPS: captured buffer used without being " + "fully indexed to a scalar" + ) + return var_map[node.name] + if isinstance(node, bool): + return "true" if node else "false" + if isinstance(node, float): + if node == float("inf"): + return "INFINITY" + if node == float("-inf"): + return "(-INFINITY)" + if node != node: # NaN + return "NAN" + return f"{node}f" + if isinstance(node, int): + return str(node) + return str(node) + + for node in graph_module.graph.nodes: + if node.op == "placeholder": + if node.name in fixed_inputs: + var_map[node.name] = fixed_inputs[node.name] + elif node.name in captured: + cap = captured[node.name] + if isinstance(cap, _CapturedScalar): + var_map[node.name] = cap.name + int_vars.add(node.name) + elif len(cap.sizes) == 0: + var_map[node.name] = f"(float){cap.name}[0]" + else: + views[node.name] = ( + cap.name, + "0", + list(cap.sizes), + list(cap.strides), + ) + else: + var_map[node.name] = f"/* unknown placeholder {node.name} */" + continue + + if node.op == "output": + out_node = node.args[0] + if isinstance(out_node, (tuple, list)): + out_node = out_node[0] + code_lines.append(f"{output_var} = {_val(out_node)};") + continue + + if node.name not in needed: + continue + + if node.op == "get_attr": + raise NotImplementedError( + "flex_attention on MPS does not support constant tensor captures " + "in score_mod/mask_mod yet" + ) + + if node.op != "call_function": + continue + + target = node.target + args = node.args + + # Index a captured buffer: accumulate a flat offset over the leading + # dims, peeling them off; emit a scalar load when fully indexed. + if target == torch.ops.aten.index.Tensor: + base_node, idx_list = args[0], args[1] + if not (isinstance(base_node, torch.fx.Node) and base_node.name in views): + raise NotImplementedError( + "flex_attention on MPS only supports indexing captured buffers" + ) + base, offset, sizes, strides = views[base_node.name] + if any(ix is None for ix in idx_list) or len(idx_list) > len(sizes): + raise NotImplementedError( + "flex_attention on MPS does not support this captured-buffer " + "indexing pattern" + ) + for j, ix in enumerate(idx_list): + term = f"(long)({_val(ix)}) * {strides[j]}" + offset = term if offset == "0" else f"{offset} + {term}" + k = len(idx_list) + rem_sizes, rem_strides = sizes[k:], strides[k:] + if rem_sizes: + views[node.name] = (base, offset, rem_sizes, rem_strides) + else: + t = _tmp() + code_lines.append(f"float {t} = (float){base}[{offset}];") + var_map[node.name] = t + continue + + t = _tmp() + # Python operator builtins on captured SymInts (dynamic-shape closures). + if target in _INT_PRESERVING_OPS: + both_int = _is_int(args[0]) and _is_int(args[1]) + op = _INT_PRESERVING_OPS[target] + ctype = int_ctype if both_int else "float" + code_lines.append(f"{ctype} {t} = {_val(args[0])} {op} {_val(args[1])};") + if both_int: + int_vars.add(node.name) + elif target in _CMP_OPS: + code_lines.append( + f"bool {t} = {_val(args[0])} {_CMP_OPS[target]} {_val(args[1])};" + ) + elif target in (operator.floordiv, operator.mod): + fn = "floor_divide" if target is operator.floordiv else "remainder" + both_int = _is_int(args[0]) and _is_int(args[1]) + if both_int: + a, b, ctype = _val(args[0]), _val(args[1]), int_ctype + else: + a = f"static_cast({_val(args[0])})" + b = f"static_cast({_val(args[1])})" + ctype = "float" + code_lines.append(f"{ctype} {t} = c10::metal::{fn}({a}, {b});") + if both_int: + int_vars.add(node.name) + elif target is operator.neg: + is_int = _is_int(args[0]) + ctype = int_ctype if is_int else "float" + code_lines.append(f"{ctype} {t} = -{_val(args[0])};") + if is_int: + int_vars.add(node.name) + elif target in (operator.and_, operator.or_): + a, b = _val(args[0]), _val(args[1]) + if _is_int(args[0]) and _is_int(args[1]): + op = "&" if target is operator.and_ else "|" + code_lines.append(f"{int_ctype} {t} = {a} {op} {b};") + int_vars.add(node.name) + else: + op = "&&" if target is operator.and_ else "||" + code_lines.append(f"bool {t} = ({a}) {op} ({b});") + elif target in _OP_TABLE: + out_type, fmt = _OP_TABLE[target] + code_lines.append( + f"{out_type} {t} = {fmt.format(*(_val(a) for a in args))};" + ) + elif target == torch.ops.aten.clamp.default: + v = _val(args[0]) + lo = _val(args[1]) if len(args) > 1 and args[1] is not None else None + hi = _val(args[2]) if len(args) > 2 and args[2] is not None else None + if lo is not None and hi is not None: + code_lines.append(f"float {t} = metal::clamp({v}, {lo}, {hi});") + elif lo is not None: + code_lines.append(f"float {t} = metal::max({v}, {lo});") + elif hi is not None: + code_lines.append(f"float {t} = metal::min({v}, {hi});") + else: + code_lines.append(f"float {t} = {v};") + elif target in ( + torch.ops.aten.div.Tensor_mode, + torch.ops.aten.div.Scalar_mode, + ): + # Floor/trunc division (e.g. paged attention's kv_idx // page_size). + mode = args[2] if len(args) > 2 else node.kwargs.get("rounding_mode") + quot = f"static_cast({_val(args[0])}) / static_cast({_val(args[1])})" + if mode == "floor": + code_lines.append(f"float {t} = metal::floor({quot});") + elif mode == "trunc": + code_lines.append(f"float {t} = metal::trunc({quot});") + else: + code_lines.append(f"float {t} = {quot};") + elif target in ( + torch.ops.aten.full_like.default, + torch.ops.aten.full.default, + ): + fill = args[1] if len(args) > 1 else node.kwargs.get("fill_value", 0) + code_lines.append(f"float {t} = {_val(fill)};") + else: + raise NotImplementedError( + f"flex_attention on MPS does not support op {target} in " + f"score_mod/mask_mod yet" + ) + + var_map[node.name] = t + + return "\n".join(code_lines) + + +def _compile_subgraph_to_metal( + graph_module: torch.fx.GraphModule, + placeholder_metal_names: list[str], + captured_meta: list[Any], + output_var: str, + var_prefix: str, + int_ctype: str = "int", +) -> str: + """ + Bind placeholders by position to Metal variable names and emit parts of Metal . + + score_mod placeholders are [score, b, h, q_idx, kv_idx, *captured]; + mask_mod's are [b, h, q_idx, kv_idx, *captured]. The captured placeholders + map positionally to `captured_meta` (each a `_CapturedBuf` or + `_CapturedScalar`). + """ + fixed: dict[str, str] = {} + captured: dict[str, Any] = {} + n_fixed = len(placeholder_metal_names) + for i, node in enumerate( + n for n in graph_module.graph.nodes if n.op == "placeholder" + ): + if i < n_fixed: + fixed[node.name] = placeholder_metal_names[i] + else: + captured[node.name] = captured_meta[i - n_fixed] + return _fx_graph_to_metal( + graph_module, fixed, captured, output_var, var_prefix, int_ctype + ) + + +def _generate_mma_shader( + metal_dtype, + d_qk, + d_v, + kv_dim, + block_m, + block_n, + full_kv_params, + captured_params, + scalar_params_str, + unpack_code, + score_code, + mask_code, + has_full_blocks, + scale, + lse_param="", + lse_write_code="", + max_param="", + max_write_code="", +): + """Generate Metal shader using simdgroup_matrix for Q@K^T.""" + + def _block_loop_body(is_partial): + if is_partial: + mask_section = f""" + bool mask_result = true; +{mask_code} +""" + else: + mask_section = """ + bool mask_result = true; +""" + return f"""\ + for (int tile_start = kv_start; tile_start < kv_end; tile_start += BLOCK_N) {{ + int tile_end = min(tile_start + BLOCK_N, kv_end); + int tile_size = tile_end - tile_start; + + // Load K into KV_tg, zero-padding rows past tile_size for MMA alignment. + for (int i = (int)tid; i < BLOCK_N * D_QK; i += BLOCK_M) {{ + int n_local = i / D_QK; + int d = i % D_QK; + if (n_local < tile_size) {{ + int n_global = tile_start + n_local; + long k_off = b_kv * stride_kz + hkv_idx * stride_kh + (long)n_global * stride_kn + (long)d * stride_kk; + KV_tg[n_local * D_QK + d] = K[k_off]; + }} else {{ + KV_tg[n_local * D_QK + d] = ({metal_dtype})0; + }} + }} + threadgroup_barrier(mem_flags::mem_threadgroup); + + // S = Q_tg @ KV_tg^T via simdgroup MMA. + simdgroup_matrix S_frag[BLOCK_M / 8][BLOCK_N / 8]; + for (int ii = 0; ii < BLOCK_M / 8; ii++) + for (int jj = 0; jj < BLOCK_N / 8; jj++) {{ + S_frag[ii][jj].thread_elements()[0] = 0.0f; + S_frag[ii][jj].thread_elements()[1] = 0.0f; + }} + for (int k = 0; k < D_QK / 8; k++) {{ + simdgroup_matrix<{metal_dtype}, 8, 8> K_frags[BLOCK_N / 8]; + for (int j = 0; j < BLOCK_N / 8; j++) + simdgroup_load(K_frags[j], &KV_tg[j * 8 * D_QK + k * 8], (ulong)D_QK, ulong2(0), true); + for (int i = 0; i < BLOCK_M / 8; i++) {{ + simdgroup_matrix<{metal_dtype}, 8, 8> Q_frag; + simdgroup_load(Q_frag, &Q_tg[i * 8 * D_QK + k * 8], (ulong)D_QK); + for (int j = 0; j < BLOCK_N / 8; j++) + simdgroup_multiply_accumulate(S_frag[i][j], Q_frag, K_frags[j], S_frag[i][j]); + }} + }} + for (int i = 0; i < BLOCK_M / 8; i++) + for (int j = 0; j < BLOCK_N / 8; j++) + simdgroup_store(S_frag[i][j], &S_tg[i * 8 * BLOCK_N + j * 8], (ulong)BLOCK_N); + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Load V into KV_tg (reuses the K slot; safe past the MMA barrier). + for (int i = (int)tid; i < tile_size * D_V; i += BLOCK_M) {{ + int n_local = i / D_V; + int d = i % D_V; + int n_global = tile_start + n_local; + long v_off = b_kv * stride_vz + hkv_idx * stride_vh + (long)n_global * stride_vn + (long)d * stride_vk; + KV_tg[n_local * D_V + d] = V[v_off]; + }} + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Fused per-thread softmax + V accumulation. + if (active) {{ + for (int n_local = 0; n_local < tile_size; n_local++) {{ + int n_idx = tile_start + n_local; + float s = S_tg[(int)tid * BLOCK_N + n_local] * SCALE_VAL; + float score_val = s; +{score_code} + s = score_val; +{mask_section}\ + // s > -inf guards exp(-inf - -inf) = NaN when an entire row is -inf so far. + if (mask_result && s > -INFINITY) {{ + float new_max = metal::max(row_max, s); + float old_scale_v = metal::precise::exp(row_max - new_max); + float p = metal::precise::exp(s - new_max); + row_sum = row_sum * old_scale_v + p; + for (int d = 0; d < D_V; d++) o_acc[d] *= old_scale_v; + for (int d = 0; d < D_V; d++) + o_acc[d] += p * float(KV_tg[n_local * D_V + d]); + row_max = new_max; + }} + }} + }} + threadgroup_barrier(mem_flags::mem_threadgroup); + }}""" + + partial_loop = _block_loop_body(is_partial=True) + full_loop = _block_loop_body(is_partial=False) + + shader = f"""\ +#include +#include +using namespace metal; + +constant int D_QK = {d_qk}; +constant int D_V = {d_v}; +constant int BLOCK_M = {block_m}; +constant int BLOCK_N = {block_n}; +constant int KV_DIM = {kv_dim}; +constant float SCALE_VAL = {scale!r}f; + +kernel void flex_attn_fwd( + device {metal_dtype}* out [[buffer(0)]], + constant {metal_dtype}* Q [[buffer(1)]], + constant {metal_dtype}* K [[buffer(2)]], + constant {metal_dtype}* V [[buffer(3)]], + constant int* kv_num_blocks [[buffer(4)]], + constant int* kv_indices [[buffer(5)]], +{full_kv_params}{captured_params}{lse_param}{max_param}{scalar_params_str}, + uint3 tgpos [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) {{ +{unpack_code} + + int q_block = tgpos.x; + int h_idx = tgpos.y; + int b_idx = tgpos.z; + int b_kv = b_idx % (int)Bkv; + int m_base = q_block * BLOCK_M; + int m_idx = m_base + (int)tid; + bool active = (m_idx < N_Q); + + int hkv_idx = h_idx / (int)gqa_shared_heads; + + threadgroup {metal_dtype} Q_tg[BLOCK_M * D_QK]; + threadgroup {metal_dtype} KV_tg[BLOCK_N * KV_DIM]; + threadgroup float S_tg[BLOCK_M * BLOCK_N]; + + // Q stays resident across all KV tiles. + {{ + long q_base_global = b_idx * stride_qz + h_idx * stride_qh; + for (int i = (int)tid; i < BLOCK_M * D_QK; i += BLOCK_M) {{ + int row = i / D_QK; + int d = i % D_QK; + int global_row = m_base + row; + Q_tg[i] = (global_row < N_Q) + ? Q[q_base_global + (long)global_row * stride_qm + (long)d * stride_qk] + : ({metal_dtype})0; + }} + }} + threadgroup_barrier(mem_flags::mem_threadgroup); + + float row_max = -INFINITY; + float row_sum = 0.0f; + float o_acc[D_V]; + for (int d = 0; d < D_V; d++) o_acc[d] = 0.0f; + + int sparse_q_idx = m_base / (int)SPARSE_Q_BLOCK_SIZE; + long sparse_idx_z = b_idx % SPARSE_Z; + long sparse_idx_hq = h_idx % SPARSE_HQ; + + // Partial blocks: score_mod + mask_mod. + int num_kv_blks = kv_num_blocks[sparse_idx_z * kv_nb_stride_z + sparse_idx_hq * kv_nb_stride_h + sparse_q_idx * kv_nb_stride_q]; + long kv_idx_base = sparse_idx_z * kv_idx_stride_z + sparse_idx_hq * kv_idx_stride_h + (long)sparse_q_idx * kv_idx_stride_q; + + for (int blk = 0; blk < num_kv_blks; blk++) {{ + int kv_block_idx = kv_indices[kv_idx_base + (long)blk * kv_idx_stride_b]; + int kv_start = kv_block_idx * (int)SPARSE_KV_BLOCK_SIZE; + int kv_end = min(kv_start + (int)SPARSE_KV_BLOCK_SIZE, (int)N_KV); + +{partial_loop} + }} +""" + + if has_full_blocks: + shader += f""" + // Full blocks: score_mod only. + int full_num_kv_blks = full_kv_num_blocks[sparse_idx_z * full_kv_nb_stride_z + sparse_idx_hq * full_kv_nb_stride_h + sparse_q_idx * full_kv_nb_stride_q]; + long full_kv_idx_base = sparse_idx_z * full_kv_idx_stride_z + sparse_idx_hq * full_kv_idx_stride_h + (long)sparse_q_idx * full_kv_idx_stride_q; + + for (int blk = 0; blk < full_num_kv_blks; blk++) {{ + int kv_block_idx = full_kv_indices[full_kv_idx_base + (long)blk * full_kv_idx_stride_b]; + int kv_start = kv_block_idx * (int)SPARSE_KV_BLOCK_SIZE; + int kv_end = min(kv_start + (int)SPARSE_KV_BLOCK_SIZE, (int)N_KV); + +{full_loop} + }} +""" + + shader += f""" + if (active) {{ +{lse_write_code}{max_write_code} if (row_sum == 0.0f) row_sum = 1.0f; + long out_base = b_idx * stride_oz + h_idx * stride_oh + (long)m_idx * stride_om; + for (int d = 0; d < D_V; d++) + out[out_base + (long)d * stride_ok] = {metal_dtype}(o_acc[d] / row_sum); + }} +}} +""" + return shader + + +def _generate_metal_shader( + dtype: torch.dtype, + d_qk: int, + d_v: int, + score_mod_graph: torch.fx.GraphModule, + mask_mod_graph: torch.fx.GraphModule, + has_full_blocks: bool, + block_m: int, + scale: float, + score_captured: Sequence[tuple] = (), + mask_captured: Sequence[tuple] = (), + write_lse: bool = False, + write_max: bool = False, + captures_fit_int32: bool = True, +) -> str: + """Generate the complete Metal shader source for flex attention. + + `score_captured` / `mask_captured` describe the captures of score_mod / + mask_mod in placeholder order. Each entry is a tagged tuple: a tensor + capture ("tensor", sizes, strides, dtype) becomes an extra Metal buffer, + while a SymInt capture ("scalar",) is read from the packed scalar buffer. + """ + metal_dtype = METAL_DTYPE_MAP[dtype] + + bytes_per_elem = 4 if dtype == torch.float32 else 2 + kv_dim = max(d_qk, d_v) + + # simdgroup MMA needs each tile dim a multiple of 8. + use_mma = (d_qk % 8 == 0) and (d_v % 8 == 0) and (block_m % 8 == 0) + block_n = 0 + + if use_mma: + # Q_tg + KV_tg + S_tg must fit in the 32KB threadgroup memory budget. + q_tg_bytes = block_m * d_qk * bytes_per_elem + budget = 32768 - q_tg_bytes + per_n = kv_dim * bytes_per_elem + block_m * 4 + max_block_n = budget // per_n + block_n = min(32, max_block_n) + block_n = (block_n // 8) * 8 + if block_n < 8: + use_mma = False + + if not use_mma: + block_n = min(32, 32768 // ((d_qk + d_v) * bytes_per_elem)) + block_n = max(1, block_n) + + buf_idx = 6 # 0=out, 1=Q, 2=K, 3=V, 4=kv_num_blocks, 5=kv_indices + if has_full_blocks: + full_kv_params = ( + f" constant int* full_kv_num_blocks [[buffer({buf_idx})]],\n" + ) + buf_idx += 1 + full_kv_params += f" constant int* full_kv_indices [[buffer({buf_idx})]],\n" + buf_idx += 1 + else: + full_kv_params = "" + + # Captures follow the (full) kv buffers, in the order built in lower_mps: + # score captures first, then mask captures. Tensor captures become extra + # Metal buffers; SymInt captures are read from the packed scalar buffer + captured_decls: list[str] = [] + scalar_capture_names: list[str] = [] + score_meta: list[Any] = [] + mask_meta: list[Any] = [] + for meta_list, caps in ((score_meta, score_captured), (mask_meta, mask_captured)): + for entry in caps: + if entry[0] == "scalar": + sname = f"capsym{len(scalar_capture_names)}" + scalar_capture_names.append(sname) + meta_list.append(_CapturedScalar(sname)) + continue + _, sizes, strides, cap_dtype = entry + mtype = CAPTURE_DTYPE_MAP.get(cap_dtype) + if mtype is None: + raise NotImplementedError( + f"flex_attention on MPS does not support captured buffer " + f"dtype {cap_dtype}" + ) + name = f"capbuf{len(captured_decls)}" + captured_decls.append( + f" constant {mtype}* {name} [[buffer({buf_idx})]]," + ) + meta_list.append(_CapturedBuf(name, list(sizes), list(strides), cap_dtype)) + buf_idx += 1 + captured_params = "".join(d + "\n" for d in captured_decls) + + # Pack scalars into one buffer to stay under Metal's 31-buffer limit. + scalar_names = [ + "B", + "Bkv", + "Hq", + "Hkv", + "N_Q", + "N_KV", + "stride_qz", + "stride_qh", + "stride_qm", + "stride_qk", + "stride_kz", + "stride_kh", + "stride_kn", + "stride_kk", + "stride_vz", + "stride_vh", + "stride_vn", + "stride_vk", + "stride_oz", + "stride_oh", + "stride_om", + "stride_ok", + "SPARSE_KV_BLOCK_SIZE", + "gqa_shared_heads", + "SPARSE_Z", + "SPARSE_HQ", + "kv_nb_stride_z", + "kv_nb_stride_h", + "kv_nb_stride_q", + "kv_idx_stride_z", + "kv_idx_stride_h", + "kv_idx_stride_q", + "kv_idx_stride_b", + "SPARSE_Q_BLOCK_SIZE", + ] + if has_full_blocks: + scalar_names += [ + "full_kv_nb_stride_z", + "full_kv_nb_stride_h", + "full_kv_nb_stride_q", + "full_kv_idx_stride_z", + "full_kv_idx_stride_h", + "full_kv_idx_stride_q", + "full_kv_idx_stride_b", + ] + scalar_names += scalar_capture_names + lse_param = "" + lse_write_code = "" + if write_lse: + lse_param = f" device float* lse [[buffer({buf_idx})]],\n" + buf_idx += 1 + lse_write_code = ( + " lse[(long)b_idx * (Hq * N_Q)" + " + (long)h_idx * N_Q + (long)m_idx]" + " = (row_sum > 0.0f)" + f" ? (row_max + metal::precise::log(row_sum)) * {RCP_LN2}" + " : -INFINITY;\n" + ) + + max_param = "" + max_write_code = "" + if write_max: + max_param = f" device float* max_scores [[buffer({buf_idx})]],\n" + buf_idx += 1 + max_write_code = ( + " max_scores[(long)b_idx * (Hq * N_Q)" + " + (long)h_idx * N_Q + (long)m_idx]" + f" = row_max * {RCP_LN2};\n" + ) + + scalar_params_str = f" constant long* _params [[buffer({buf_idx})]]" + + int_ctype = "int" if captures_fit_int32 else "long" + score_code = _compile_subgraph_to_metal( + graph_module=score_mod_graph, + placeholder_metal_names=["score_val", "b_idx", "h_idx", "m_idx", "n_idx"], + captured_meta=score_meta, + output_var="score_val", + var_prefix="_sm", + int_ctype=int_ctype, + ) + mask_code = _compile_subgraph_to_metal( + graph_module=mask_mod_graph, + placeholder_metal_names=["b_idx", "h_idx", "m_idx", "n_idx"], + captured_meta=mask_meta, + output_var="mask_result", + var_prefix="_mm", + int_ctype=int_ctype, + ) + + capsym_set = OrderedSet(scalar_capture_names) + unpack_code = "\n".join( + f" {int_ctype if name in capsym_set else 'long'} {name} = _params[{i}];" + for i, name in enumerate(scalar_names) + ) + + if use_mma: + return _generate_mma_shader( + metal_dtype, + d_qk, + d_v, + kv_dim, + block_m, + block_n, + full_kv_params, + captured_params, + scalar_params_str, + unpack_code, + score_code, + mask_code, + has_full_blocks, + scale, + lse_param=lse_param, + lse_write_code=lse_write_code, + max_param=max_param, + max_write_code=max_write_code, + ) + + # Fallback: per-thread dot product with cooperative K/V tiling. + def _fallback_block_loop_body(is_partial): + if is_partial: + mask_section = f""" + bool mask_result = true; + {mask_code} + """ + else: + mask_section = """ + bool mask_result = true; + """ + return f"""\ + for (int tile_start = kv_start; tile_start < kv_end; tile_start += BLOCK_N) {{ + int tile_end = min(tile_start + BLOCK_N, kv_end); + int tile_size = tile_end - tile_start; + + for (int i = (int)tid; i < tile_size * D_QK; i += BLOCK_M) {{ + int n_local = i / D_QK; + int d = i % D_QK; + int n_global = tile_start + n_local; + long k_off = b_kv * stride_kz + hkv_idx * stride_kh + (long)n_global * stride_kn + (long)d * stride_kk; + K_tile[n_local * D_QK + d] = K[k_off]; + }} + + for (int i = (int)tid; i < tile_size * D_V; i += BLOCK_M) {{ + int n_local = i / D_V; + int d = i % D_V; + int n_global = tile_start + n_local; + long v_off = b_kv * stride_vz + hkv_idx * stride_vh + (long)n_global * stride_vn + (long)d * stride_vk; + V_tile[n_local * D_V + d] = V[v_off]; + }} + + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (active) {{ + for (int n_local = 0; n_local < tile_size; n_local++) {{ + int n_idx = tile_start + n_local; + + float s = 0.0f; + for (int d = 0; d < D_QK; d++) {{ + s += q_row[d] * float(K_tile[n_local * D_QK + d]); + }} + s *= SCALE_VAL; + + float score_val = s; +{score_code} + s = score_val; +{mask_section}\ + // s > -inf guards exp(-inf - -inf) = NaN when an entire row is -inf so far. + if (mask_result && s > -INFINITY) {{ + float new_max = metal::max(row_max, s); + float old_scale = metal::precise::exp(row_max - new_max); + float p = metal::precise::exp(s - new_max); + row_sum = row_sum * old_scale + p; + for (int d = 0; d < D_V; d++) o_acc[d] *= old_scale; + for (int d = 0; d < D_V; d++) {{ + o_acc[d] += p * float(V_tile[n_local * D_V + d]); + }} + row_max = new_max; + }} + }} + }} + + threadgroup_barrier(mem_flags::mem_threadgroup); + }}""" + + partial_loop = _fallback_block_loop_body(is_partial=True) + full_loop = _fallback_block_loop_body(is_partial=False) + + shader = f"""\ +#include +#include +using namespace metal; + +constant int D_QK = {d_qk}; +constant int D_V = {d_v}; +constant int BLOCK_M = {block_m}; +constant int BLOCK_N = {block_n}; +constant float SCALE_VAL = {scale!r}f; + +kernel void flex_attn_fwd( + device {metal_dtype}* out [[buffer(0)]], + constant {metal_dtype}* Q [[buffer(1)]], + constant {metal_dtype}* K [[buffer(2)]], + constant {metal_dtype}* V [[buffer(3)]], + constant int* kv_num_blocks [[buffer(4)]], + constant int* kv_indices [[buffer(5)]], +{full_kv_params}{captured_params}{lse_param}{max_param}{scalar_params_str}, + uint3 tgpos [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) {{ +{unpack_code} + + int q_block = tgpos.x; + int h_idx = tgpos.y; + int b_idx = tgpos.z; + int b_kv = b_idx % (int)Bkv; + int m_idx = q_block * BLOCK_M + (int)tid; + bool active = (m_idx < N_Q); + + int hkv_idx = h_idx / (int)gqa_shared_heads; + + float q_row[D_QK]; + if (active) {{ + long q_base = b_idx * stride_qz + h_idx * stride_qh + (long)m_idx * stride_qm; + for (int d = 0; d < D_QK; d++) {{ + q_row[d] = float(Q[q_base + (long)d * stride_qk]); + }} + }} + + float row_max = -INFINITY; + float row_sum = 0.0f; + float o_acc[D_V]; + for (int d = 0; d < D_V; d++) o_acc[d] = 0.0f; + + threadgroup {metal_dtype} K_tile[BLOCK_N * D_QK]; + threadgroup {metal_dtype} V_tile[BLOCK_N * D_V]; + + int m_base = q_block * BLOCK_M; + int sparse_q_idx = m_base / (int)SPARSE_Q_BLOCK_SIZE; + long sparse_idx_z = b_idx % SPARSE_Z; + long sparse_idx_hq = h_idx % SPARSE_HQ; + + int num_kv_blks = kv_num_blocks[sparse_idx_z * kv_nb_stride_z + sparse_idx_hq * kv_nb_stride_h + sparse_q_idx * kv_nb_stride_q]; + long kv_idx_base = sparse_idx_z * kv_idx_stride_z + sparse_idx_hq * kv_idx_stride_h + (long)sparse_q_idx * kv_idx_stride_q; + + for (int blk = 0; blk < num_kv_blks; blk++) {{ + int kv_block_idx = kv_indices[kv_idx_base + (long)blk * kv_idx_stride_b]; + int kv_start = kv_block_idx * (int)SPARSE_KV_BLOCK_SIZE; + int kv_end = min(kv_start + (int)SPARSE_KV_BLOCK_SIZE, (int)N_KV); + +{partial_loop} + }} +""" + + if has_full_blocks: + shader += f""" + int full_num_kv_blks = full_kv_num_blocks[sparse_idx_z * full_kv_nb_stride_z + sparse_idx_hq * full_kv_nb_stride_h + sparse_q_idx * full_kv_nb_stride_q]; + long full_kv_idx_base = sparse_idx_z * full_kv_idx_stride_z + sparse_idx_hq * full_kv_idx_stride_h + (long)sparse_q_idx * full_kv_idx_stride_q; + + for (int blk = 0; blk < full_num_kv_blks; blk++) {{ + int kv_block_idx = full_kv_indices[full_kv_idx_base + (long)blk * full_kv_idx_stride_b]; + int kv_start = kv_block_idx * (int)SPARSE_KV_BLOCK_SIZE; + int kv_end = min(kv_start + (int)SPARSE_KV_BLOCK_SIZE, (int)N_KV); + +{full_loop} + }} +""" + + shader += f""" + if (active) {{ +{lse_write_code}{max_write_code} if (row_sum == 0.0f) row_sum = 1.0f; + long out_base = b_idx * stride_oz + h_idx * stride_oh + (long)m_idx * stride_om; + for (int d = 0; d < D_V; d++) {{ + out[out_base + (long)d * stride_ok] = {metal_dtype}(o_acc[d] / row_sum); + }} + }} +}} +""" + return shader + + +class MetalFlexAttentionNode(ir.ExternKernelAlloc): + """IR node for MPS flex attention; emits a compiled Metal shader at codegen.""" + + def __init__( + self, + layout: ir.Layout, + inputs: list[ir.IRNode], + shader_source: str, + scalar_args: list[Any], + grid: tuple[Any, ...], + block_m: int, + num_mutated_outputs: int = 0, + ): + super().__init__( + layout=layout, + inputs=inputs, + python_kernel_name="metal_flex_attention", + ) + self.shader_source = shader_source + self.scalar_args = scalar_args + self.grid = grid + self.block_m = block_m + # The last num_mutated_outputs inputs (logsumexp, max_scores) are written + # in place by the kernel. + self.mutation_outputs = [ + # pyrefly: ignore [bad-argument-type] + ir.MutationOutput(ir.NoneLayout(device=layout.device), buf, self) + for buf in self.inputs[len(self.inputs) - num_mutated_outputs :] + ] + + def codegen(self, wrapper) -> None: + wrapper.add_import_once( + "from torch._inductor.runtime.runtime_utils import compile_mps_shader" + ) + wrapper.add_import_once("import torch") + + src_code = self.shader_source + if src_code in wrapper.src_to_kernel: + lib_name = wrapper.src_to_kernel[src_code] + else: + lib_name = f"_mps_flex_lib_{wrapper.next_kernel_suffix()}" + wrapper.src_to_kernel[src_code] = lib_name + wrapper.header.splice( + f"{lib_name} = compile_mps_shader('''\n{src_code}\n''')" + ) + + name = self.get_name() + layout: ir.Layout = self.layout # type: ignore[assignment] + sizes = ", ".join(wrapper.codegen_sizevar(s) for s in layout.size) + strides = ", ".join(wrapper.codegen_sizevar(s) for s in layout.stride) + device_str = f"{layout.device.type!r}" + wrapper.writeline( + f"{name} = torch.empty_strided(" + f"({sizes},), ({strides},), " + f"dtype={layout.dtype!r}, device={device_str})" + ) + + # One packed int64 buffer keeps us under Metal's 31-buffer limit. + scalar_strs = [wrapper.codegen_sizevar(s) for s in self.scalar_args] + params_name = f"_flex_params_{name}" + wrapper.writeline( + f"{params_name} = torch.tensor(" + f"[{', '.join(scalar_strs)}], dtype=torch.int64, device={device_str})" + ) + + arg_parts = [name] + for inp in self.inputs: + # pyrefly: ignore [missing-attribute] + arg_parts.append(inp.codegen_reference()) + arg_parts.append(params_name) + args_str = ", ".join(arg_parts) + + grid_x = wrapper.codegen_sizevar(self.grid[0]) + grid_y = wrapper.codegen_sizevar(self.grid[1]) + grid_z = wrapper.codegen_sizevar(self.grid[2]) + + wrapper.writeline( + f"{lib_name}.flex_attn_fwd(" + f"{args_str}, " + f"threads=[{grid_x} * {self.block_m}, {grid_y}, {grid_z}], " + f"group_size=[{self.block_m}, 1, 1])" + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps.py new file mode 100644 index 0000000000000000000000000000000000000000..a7c654bdae29a53a6b9d9cd11995b17724c58b5f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps.py @@ -0,0 +1,1267 @@ +# This is not a feature-complete compiler backend +# Just an early prototype that shows that one can compile elementwise ops into a Metal shader +from __future__ import annotations + +import functools +import itertools +import logging +import math +from pathlib import Path +from typing import Any, TYPE_CHECKING + +import sympy +from sympy.printing.precedence import PRECEDENCE + +import torch +from torch.utils._cpp_embed_headers import _embed_headers +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import Min +from torch.utils._sympy.printers import CppPrinter, ExprPrinter as ExprPrinter_ +from torch.utils._sympy.value_ranges import ValueRanges + +from ..utils import ceildiv, get_bounds_index_expr, get_kernel_metadata +from ..virtualized import ops, OpsWrapper, V +from .common import ( + CSEVariable, + DeferredLine, + DTYPE_TO_COMPUTATION_DTYPE, + IndentedBuffer, + OpOverrides, + PythonPrinter, +) +from .simd import IterationRangesEntry, SIMDKernel, SIMDScheduling + + +if TYPE_CHECKING: + from ..ops_handler import ReductionType, StoreMode + from ..scheduler import Scheduler, SchedulerNode + from .common import OpVarT + +log = logging.getLogger(__name__) + +DTYPE_TO_METAL = { + torch.bool: "bool", + torch.int8: "char", + torch.int16: "short", + torch.int32: "int", + torch.int64: "long", + torch.uint8: "uchar", + torch.uint16: "ushort", + torch.uint32: "uint", + torch.uint64: "ulong", + torch.float: "float", + torch.half: "half", + torch.bfloat16: "bfloat", +} + + +def value_to_metal(val: float | int | bool | str | CSEVariable) -> str: + if isinstance(val, float): + if val == torch.inf: + return "HUGE_VALF" + elif val == -torch.inf: + return "-HUGE_VALF" + elif val != val: # Only float that not equal to self is nan + return "NAN" + return str(val) + elif isinstance(val, bool): + return "true" if val else "false" + return str(val) + + +class MetalExprPrinter(ExprPrinter_): + """Converts sympy expression to Metal code snippet""" + + def _print_FloorDiv(self, expr: sympy.Expr) -> str: + x, div = expr.args + x = self.doprint(x) + div = self.doprint(div) + if expr.is_integer: + return f"c10::metal::floor_divide({x}, {div})" + return f"metal::floor({x}) / ({div})" + + def _print_ModularIndexing(self, expr: sympy.Expr) -> str: + x, div, mod = expr.args + # Workaround for Metal compiler bug with fused (x / A) % B, see PR 175481 + use_safe_mod = div == 65536 and (mod & (mod - 1)) != 0 + + x = self.doprint(x) + if div != 1: + div = self.doprint(div) + if expr.is_integer: + x = f"({x}) / ({div})" + else: + x = f"metal::floor({x}) / ({div})" + mod = self.doprint(mod) + if use_safe_mod: + return f"c10::metal::safe_mod({x}, {mod})" + return f"({x}) % ({mod})" + + def _print_min_max(self, expr: sympy.Expr, fn: str) -> str: + # pyrefly: ignore [missing-attribute] + args = list(map(self._print, expr.args)) + result = args[0] + for arg in args[1:]: + result = self._print_binary_min_max(result, arg, fn) + return result + + @staticmethod + def _print_binary_min_max(a: str, b: str, fn: str) -> str: + typecast_a = f"static_cast({a})" + typecast_b = f"static_cast({b})" + return f"metal::{fn}({typecast_a}, {typecast_b})" + + def _print_Min(self, expr: sympy.Expr) -> str: + return self._print_min_max(expr, "min") + + def _print_Max(self, expr: sympy.Expr) -> str: + return self._print_min_max(expr, "max") + + def _print_Abs(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"metal::abs({self._print(expr.args[0])})" + + def _print_RoundToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"static_cast(metal::rint({self._print(expr.args[0])}))" + + def _print_RoundDecimal(self, expr: sympy.Expr) -> str: + if len(expr.args) != 2: + raise AssertionError(f"expected 2 args, got {len(expr.args)}") + number, ndigits = expr.args + if number.is_integer: + # ndigits < 0 should have been filtered by the sympy function + if ndigits >= 0: + raise AssertionError(f"expected ndigits < 0, got {ndigits}") + raise ValueError( + f"For integer inputs, only non-negative ndigits are currently supported, but got {ndigits}." + ) + number_str = self.parenthesize(number, PRECEDENCE["Mul"]) + return f"static_cast(metal::rint(1e{ndigits} * {number_str}) * 1e{-ndigits})" + + def _print_IntTrueDiv(self, expr: sympy.Expr) -> str: + lhs, rhs = expr.args + # TODO: This is only accurate up to 2**23 + # pyrefly: ignore [missing-attribute] + return f"static_cast({self._print(lhs)}) / static_cast({self._print(rhs)})" + + def _print_PowByNatural(self, expr: sympy.Expr) -> str: + if len(expr.args) != 2: + raise AssertionError(f"expected 2 args, got {len(expr.args)}") + x, y = map(self.doprint, expr.args) + return f"metal::precise::pow(static_cast({x}), static_cast({y}))" + + def _print_ToFloat(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + x = self.doprint(expr.args[0]) + return f"static_cast({x})" + + def _print_Float(self, expr: sympy.Expr) -> str: + if expr.is_integer: + # sympy considers 0.0 to be integer, but Metal doesn't. + # this workaround prints the float as an integer + # xref: https://github.com/sympy/sympy/issues/26620 + return str(int(expr)) + else: + return str(expr) + + def _print_FloorToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + x = self.doprint(expr.args[0]) + return f"static_cast(metal::floor(static_cast({x})))" + + _print_floor = _print_FloorToInt + + def _print_TruncToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + x = self.doprint(expr.args[0]) + return f"static_cast(metal::trunc({x}))" + + def _print_OpaqueUnaryFn_log2(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + x = self.doprint(expr.args[0]) + return f"metal::precise::log2({x})" + + def _print_Where(self, expr: sympy.Expr) -> str: + c, p, q = ( + self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args + ) + return f"{c} ? {p} : {q}" + + +class MetalOverrides(OpOverrides): + """Implements Metal-specific overrides for ops. Base class emits Python-friendly overrides.""" + + @staticmethod + def to_dtype( + x: CSEVariable, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = True, + ) -> str: + if dtype == torch.double: + log.warning( + "float64 cast requested, probably from tensorify_python_scalars" + ) + return f"static_cast({x})" + return f"static_cast<{DTYPE_TO_METAL[dtype]}>({x})" + + @staticmethod + def to_dtype_bitcast( + x: CSEVariable, dtype: torch.dtype, src_dtype: torch.dtype + ) -> str: + return f"as_type<{DTYPE_TO_METAL[dtype]}>(static_cast<{DTYPE_TO_METAL[src_dtype]}>({x}))" + + @staticmethod + def constant(val: bool | float | int, dtype: torch.dtype) -> str: + return value_to_metal(val) + + @staticmethod + def index_expr(expr: sympy.Expr, dtype: torch.dtype) -> str: + idx_str = V.kernel.index_to_str(V.kernel.prepare_indexing(expr)) + var = V.kernel.cse.generate( + V.kernel.compute, idx_str, bounds=get_bounds_index_expr(expr) + ) + return ops.to_dtype(var, dtype) + + @staticmethod + def value_expr(expr: sympy.Expr, dtype: torch.dtype) -> str: + # Metal index_expr already emits the requested dtype, so value_expr has + # the same lowering here. + return MetalOverrides.index_expr(expr, dtype) + + @staticmethod + def masked(mask: CSEVariable, body: sympy.Expr, other: CSEVariable) -> str: + # TODO: Type annotation for other is wrong, it's often float or int + # TODO: Should it be converted to lambda on MacOS-15+? + + other_str = value_to_metal(other) + scoped_body = IndentedBuffer() + with V.kernel.swap_buffers(scoped_body), scoped_body.indent(): + # Reset the scoped variable counter so that each invocation of the same body + # generates identical variable names. Without this reset, repeated calls to + # body() would keep incrementing the counter, resulting in different cache key. + V.kernel.cse.iter_buffer_ids = itertools.count() + # Append "_scoped" to the current prefix so each nesting level gets unique vars + V.kernel.cse.name_prefix += "_scoped" + rc = body() + + # Compute cache key manually as variable name is needed to actually generate the code + cache_key = f"{mask}:{scoped_body.getvalue()}:{other_str}" + var = V.kernel.cse.try_get(cache_key) + if not var: + var = V.kernel.cse.newvar(dtype=rc.dtype) + V.kernel.cse.put(cache_key, var) + V.kernel.compute.writelines( + [f"{DTYPE_TO_METAL[rc.dtype]} {var};", f"if ({mask}) {{"] + ) + with V.kernel.compute.indent(): + V.kernel.compute.splice(scoped_body) + V.kernel.compute.writeline( + f"{var} = static_cast({rc});" + ) + V.kernel.compute.writeline( + f"}} else {var} = static_cast({other_str});" + ) + return var + + @staticmethod + # pyrefly: ignore [bad-override] + def where(a: OpVarT, b: OpVarT, c: OpVarT) -> str: + return f"{a} ? {b} : static_cast({value_to_metal(c)})" + + @staticmethod + def remainder(a: OpVarT, b: OpVarT) -> str: + return f"c10::metal::remainder({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a: CSEVariable, b: CSEVariable) -> str: + typecast_a = f"static_cast({a})" + typecast_b = f"static_cast({b})" + return f"c10::metal::max({typecast_a}, {typecast_b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a: CSEVariable, b: CSEVariable) -> str: + typecast_a = f"static_cast({a})" + typecast_b = f"static_cast({b})" + return f"c10::metal::min({typecast_a}, {typecast_b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_or(a: CSEVariable, b: CSEVariable) -> str: + return f"{a} || {b}" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_and(a: CSEVariable, b: CSEVariable) -> str: + return f"{a} && {b}" + + @staticmethod + # pyrefly: ignore [bad-override] + def isnan(x: CSEVariable) -> str: + return f"metal::isnan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def isinf(x: CSEVariable) -> str: + return f"metal::isinf({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def log(x: CSEVariable) -> str: + return f"metal::precise::log({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def exp(x: CSEVariable) -> str: + return f"metal::precise::exp({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def abs(x: CSEVariable) -> str: + return f"metal::abs({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def signbit(x: CSEVariable) -> str: + return f"metal::signbit({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sin(x: CSEVariable) -> str: + return f"metal::precise::sin({x})" + + @staticmethod + def sinc(x: CSEVariable) -> str: + return f"c10::metal::sinc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cos(x: CSEVariable) -> str: + return f"metal::precise::cos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tan(x: CSEVariable) -> str: + return f"metal::precise::tan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asin(x: CSEVariable) -> str: + return f"metal::precise::asin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acos(x: CSEVariable) -> str: + return f"metal::precise::acos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x: CSEVariable) -> str: + return f"metal::precise::atan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan2(x: CSEVariable, y: CSEVariable) -> str: + return f"::metal::precise::atan2({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sqrt(x: CSEVariable) -> str: + return f"metal::precise::sqrt({x})" + + @staticmethod + def neg(x: CSEVariable) -> str: + # TODO: Does it rely on undefined behavior? + # If so, add special logic for unsigned types + return f"static_cast(-{x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def rsqrt(x: CSEVariable) -> str: + return f"metal::precise::rsqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tanh(x: CSEVariable) -> str: + return f"metal::precise::tanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atanh(x: CSEVariable) -> str: + return f"metal::precise::atanh({x})" + + @staticmethod + def floordiv(a: CSEVariable, b: CSEVariable) -> str: + # a and b must be of integer type + return f"c10::metal::floor_divide({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def floor(x: CSEVariable) -> str: + return f"metal::floor({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sign(x: CSEVariable) -> str: + return f"metal::sign({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmod(a: CSEVariable, b: CSEVariable) -> str: + typecast_a = f"static_cast({a})" + typecast_b = f"static_cast({b})" + return f"metal::fmod({typecast_a}, {typecast_b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def trunc(x: CSEVariable) -> str: + return f"metal::trunc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def truncdiv(a: CSEVariable, b: CSEVariable) -> str: + quot = f"{a} / {b}" + if (a.dtype is not None and a.dtype.is_floating_point) or ( + b.dtype is not None and b.dtype.is_floating_point + ): + return f"metal::trunc({quot})" + return quot + + @staticmethod + # pyrefly: ignore [bad-override] + def ceil(x: CSEVariable) -> str: + return f"metal::ceil({x})" + + @staticmethod + def rand(seed: CSEVariable, offset: CSEVariable) -> str: + V.kernel.headers.add("random") + return f"c10::metal::rand({seed}, {offset})" + + @staticmethod + def randn(seed: CSEVariable, offset: CSEVariable) -> str: + V.kernel.headers.add("random") + return f"c10::metal::randn({seed}, {offset})" + + @staticmethod + def randint64( + seed: CSEVariable, offset: CSEVariable, low: CSEVariable, high: CSEVariable + ) -> str: + V.kernel.headers.add("random") + return f"c10::metal::randint64({seed}, {offset}, {low}, {high})" + + @staticmethod + # pyrefly: ignore [bad-override] + def round(x: CSEVariable) -> str: + return f"metal::rint({x})" + + @staticmethod + def pow(a: CSEVariable, b: CSEVariable) -> str: + cast_a = f"static_cast({a})" + cast_b = f"static_cast({b})" + return f"metal::pow({cast_a}, {cast_b})" + + def _special_unary(self, a: CSEVariable, name: str) -> str: + V.kernel.headers.add("special_math") + return f"c10::metal::{name}({a})" + + def _special_binary(self, a: CSEVariable, b: CSEVariable, name: str) -> str: + V.kernel.headers.add("special_math") + return f"c10::metal::{name}({a}, {b})" + + @classmethod + def _initialize_special_ops(cls) -> None: + # Unary special ops + for name in [ + "erf", + "erfc", + "erfinv", + "i0", + "i0e", + "i1", + "i1e", + "digamma", + "spherical_bessel_j0", + ]: + setattr(cls, name, functools.partialmethod(cls._special_unary, name=name)) + + cls.lgamma = functools.partialmethod(cls._special_unary, name="log_gamma") # type: ignore[assignment] + + # Unary special ops with forward in method name + for name in [ + "bessel_j0", + "bessel_j1", + "bessel_y0", + "bessel_y1", + "modified_bessel_i0", + "modified_bessel_i1", + "modified_bessel_k0", + "modified_bessel_k1", + "scaled_modified_bessel_k0", + "scaled_modified_bessel_k1", + ]: + setattr( + cls, + name, + functools.partialmethod(cls._special_unary, name=name + "_forward"), + ) + + # Binary special ops + for name in [ + "polygamma", + "igamma", + "igammac", + "zeta", + ]: + setattr(cls, name, functools.partialmethod(cls._special_binary, name=name)) + + # Binary special ops with forward in method name + for name in [ + "chebyshev_polynomial_t", + "chebyshev_polynomial_u", + "chebyshev_polynomial_v", + "chebyshev_polynomial_w", + "hermite_polynomial_h", + "hermite_polynomial_he", + "shifted_chebyshev_polynomial_t", + "shifted_chebyshev_polynomial_u", + "shifted_chebyshev_polynomial_v", + "shifted_chebyshev_polynomial_w", + ]: + setattr( + cls, + name, + functools.partialmethod(cls._special_binary, name=name + "_forward"), + ) + + +MetalOverrides._initialize_pointwise_overrides("mps") +MetalOverrides._initialize_special_ops() + + +class MetalKernel(SIMDKernel): + """Implement Metal codegen based on the SIMDKernel abstraction""" + + overrides = MetalOverrides # type: ignore[assignment] + suffix = ";" + newvar_prefix = "auto " + max_threadgroup_size = 1024 + simd_group_size = 32 + pexpr = PythonPrinter().doprint + cexpr = CppPrinter().doprint + sexpr = MetalExprPrinter().doprint + kexpr = sexpr + headers: OrderedSet[str] = OrderedSet(["utils"]) + multistage_reduction_entry: list[IterationRangesEntry] = [] + + def __init__( + self, + tiling: dict[str, sympy.Expr], + **kwargs: Any, + ) -> None: + super().__init__(tiling, **kwargs) + self.acc_var_ids = itertools.count() + + def dtype_to_str(self, dtype: torch.dtype) -> str: + return DTYPE_TO_METAL[dtype] + + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + """Codegen a load from an InputBuffer""" + var = self.args.input(name) + index = self.prepare_indexing(index) + dtype = V.graph.get_dtype(name) + line = f"{var}[{self.index_to_str(index)}]" + if dtype in [torch.float16, torch.bfloat16]: + # TODO(NS): Figure out the right balance between optype casts + # op_math_t for half-precision floats should be float32 + # Otherwise it can lead to a correctness issues with eager + line = f"static_cast({line})" + dtype = torch.float32 + return self.cse.generate(self.loads, line, dtype=dtype) + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + var = self.args.output(name) + index = self.prepare_indexing(index) + dtype_str = self.dtype_to_str(V.graph.get_dtype(name)) + cast_val = f"static_cast<{dtype_str}>({value})" + if mode is None: + line = f"{var}[{self.index_to_str(index)}] = {cast_val};" + elif mode == "atomic_add": + self.headers.add("atomic") + atomic_type = f"c10::metal::AtomicType<{dtype_str}>" + cast_var = f"reinterpret_cast({var})" + line = f"{atomic_type}::atomic_add({cast_var}, {self.index_to_str(index)}, {cast_val});" + else: + raise RuntimeError(f"Unimplemented store mode {mode}") + if self.inside_reduction: + self.compute.writeline(DeferredLine(name, line)) + else: + self.stores.writeline(DeferredLine(name, line)) + + def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None: + var = self.args.output(name) + index = self.prepare_indexing(index) + dtype_str = self.dtype_to_str(V.graph.get_dtype(name)) + + reduction_dim = next(t for t in self.range_trees if t.is_reduction) + # Only one thread in the reduction group needs to store the results + line = f"{var}[{self.index_to_str(index)}] = static_cast<{dtype_str}>({value});" + line = f"if ({reduction_dim.name} == 0) {line}" + self.stores.writeline(DeferredLine(name, line)) + + def _new_idxvar( + self, + dtype: str | torch.dtype, + elem_count: int | None = None, + default_value: Any | None = None, + is_threadgroup: bool = True, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + ) -> CSEVariable: + if isinstance(dtype, torch.dtype): + dtype = self.dtype_to_str(dtype) + var_name = f"tmp_acc_{next(self.acc_var_ids)}" + var = V.kernel.create_cse_var(var_name, bounds, dtype) + var_def = "threadgroup " if is_threadgroup else "" + var_def += f"{dtype} {var_name}" + if elem_count: + var_def += f"[{self.sexpr(elem_count)}]" + if default_value is not None: + if is_threadgroup: + raise AssertionError("Thread group var can not have default value") + var_def += f" = {default_value}" + self.indexing_code.writeline(var_def + self.suffix) + return var + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + "Caching wrapper around _reduction_nocache" + cache_key = (src_dtype, reduction_type, value) + # Return cached reduction + if cache_key in self.cse.reduction_cache: + return self.cse.reduction_cache[cache_key] + result = self._reduction_nocache(dtype, src_dtype, reduction_type, value) + self.cse.reduction_cache[cache_key] = result # type: ignore[assignment] + return result + + def _reduction_nocache( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + """Codegen a reduction operation. + Only sum and prod operations are somewhat reasonable optimized""" + if not self.inside_reduction: + raise AssertionError("expected to be inside reduction") + if self._load_mask: + raise AssertionError("expected no load mask during reduction") + + def _unwrap_helper(res3: CSEVariable) -> tuple[CSEVariable, ...]: + # Unwraps vec3 dtype into individual components + return OpsWrapper._unwrap( + [CSEVariable(f"{res3}.{t}", res3.bounds, res3.dtype) for t in "xyz"] + ) + + # Establish reduction buffer size and index expression + reduction_idx = "" + acc_buf_size = 1 + for rd in self.range_trees: + if not rd.is_reduction: + continue + if reduction_idx: + reduction_idx += " + " + reduction_idx += f"{rd.name} * {acc_buf_size}" + + if isinstance(rd.numel, sympy.Integer): + acc_buf_size *= rd.numel + else: + acc_buf_size *= sympy.Symbol( + f"{rd.prefix}numel", integer=True, positive=True + ) + + acc_buf_size = Min(acc_buf_size, self.max_threadgroup_size) + acc_buf_size_str = self.sexpr(acc_buf_size) + # metal threadgroup arrays need a compile time constant size, so + # fall back to the static upper bound when acc buf size is symbolic + # happens when dynamic=True + acc_buf_alloc_size = ( + acc_buf_size + if isinstance(acc_buf_size, sympy.Integer) + else self.max_threadgroup_size + ) + shmem_buf_size = ( + ceildiv(acc_buf_size, self.simd_group_size) + if isinstance(acc_buf_size, sympy.Integer) + else self.simd_group_size + ) + + if reduction_type == "any": + acc = self._new_idxvar(dtype) + self.indexing_code.writeline(f"{acc} = false;") + self.indexing_code.writeline( + "threadgroup_barrier(metal::mem_flags::mem_threadgroup);" + ) + self.compute.splice( + f""" + if ({value}) {{ + {acc} = true; + }} + """ + ) + self.stores.writeline( + "threadgroup_barrier(metal::mem_flags::mem_threadgroup);" + ) + return acc + + self.headers.add("reduction_utils") + + if reduction_type in ["prod", "sum"]: + acc_dtype = DTYPE_TO_COMPUTATION_DTYPE[src_dtype] + acc_buf = self._new_idxvar(acc_dtype, shmem_buf_size) + if not self.multistage_reduction_entry: + val = value + else: + default_val, reduction_op = ( + (0, "+") if reduction_type == "sum" else (1, "*") + ) + val = self._new_idxvar( + acc_dtype, default_value=default_val, is_threadgroup=False + ) + self.compute.splice(f"{val} {reduction_op}= {value};") + + return self.cse.generate( + self.stores, + f"c10::metal::threadgroup_{reduction_type}({acc_buf}, {val}, {reduction_idx}, {acc_buf_size_str})", + dtype=DTYPE_TO_COMPUTATION_DTYPE[dtype], + ) + if reduction_type in ["max", "min"]: + acc_buf = self._new_idxvar(src_dtype, shmem_buf_size) + src_metal_type = DTYPE_TO_METAL[src_dtype] + cast_value = f"static_cast<{src_metal_type}>({value})" + if not self.multistage_reduction_entry: + val = cast_value # type: ignore[assignment] + else: + op_struct = "MaxOp" if reduction_type == "max" else "MinOp" + limit_val = f"::c10::metal::{op_struct}<{src_metal_type}>::identity()" + val = self._new_idxvar( + src_dtype, default_value=limit_val, is_threadgroup=False + ) + self.compute.splice( + f"{val} = ::c10::metal::{reduction_type}({val}, {cast_value});" + ) + return self.cse.generate( + self.stores, + f"c10::metal::threadgroup_{reduction_type}({acc_buf}, {val}, {reduction_idx}, {acc_buf_size_str})", + dtype=DTYPE_TO_COMPUTATION_DTYPE[dtype], + ) + if reduction_type in ["argmin", "argmax"]: + data_acc_buf = self._new_idxvar(src_dtype, shmem_buf_size) + idx_acc_buf = self._new_idxvar(dtype, shmem_buf_size) + src_metal_type = DTYPE_TO_METAL[src_dtype] + cast_value = f"static_cast<{src_metal_type}>({value})" + if not self.multistage_reduction_entry: + val = cast_value # type: ignore[assignment] + idx_val = f"static_cast<{DTYPE_TO_METAL[dtype]}>({reduction_idx})" + else: + op_struct = "MaxOp" if reduction_type == "argmax" else "MinOp" + limit_val = f"::c10::metal::{op_struct}<{src_metal_type}>::identity()" + val = self._new_idxvar( + src_dtype, default_value=limit_val, is_threadgroup=False + ) + idx_val = self._new_idxvar(dtype, default_value=0, is_threadgroup=False) # type: ignore[assignment] + idx_var = next( + t for t in self.range_tree_nodes.values() if t.is_reduction + ) + self.compute.splice(f""" + if (::c10::metal::{op_struct}<{src_metal_type}>::replace({cast_value}, {val})) {{ + {val} = {cast_value}; + {idx_val} = {idx_var.name}; + }} + """) + return self.cse.generate( + self.stores, + f"c10::metal::threadgroup_{reduction_type}({data_acc_buf}, {idx_acc_buf}, " + f"{val}, {idx_val}, {reduction_idx}, {acc_buf_size_str})", + dtype=dtype, + ) + if reduction_type == "welford_reduce": + if not self.multistage_reduction_entry: + acc_buf = self._new_idxvar("float3", acc_buf_alloc_size) + self.compute.splice( + f"{acc_buf}[{reduction_idx}] = float3({value}, 0.0, 1.0);" + ) + wf_res = self.cse.generate( + self.compute, + f"c10::metal::threadgroup_welford_combine({acc_buf}, {reduction_idx}, {acc_buf_size_str})", + dtype=torch.float32, + ) + return _unwrap_helper(wf_res) + acc_buf = self._new_idxvar("float3", acc_buf_alloc_size) + acc_thread_var = f"{acc_buf}[{reduction_idx}]" + self.indexing_code.splice(f"{acc_thread_var} = 0.0;") + self.compute.writeline( + f"{acc_thread_var} = ::c10::metal::welford_combine({acc_thread_var}, float3({value}, 0.0, 1.0));" + ) + wf_res = self.cse.generate( + self.stores, + f"c10::metal::threadgroup_welford_combine({acc_buf}, {reduction_idx}, {acc_buf_size_str})", + dtype=torch.float32, + ) + return _unwrap_helper(wf_res) + if reduction_type == "welford_combine": + if not isinstance(value, tuple): + raise AssertionError("Input to welford combine must be tuple") + acc_buf = self._new_idxvar("float3", acc_buf_alloc_size) + acc_thread_var = f"{acc_buf}[{reduction_idx}]" + inp_value = f"float3({value[0]}, {value[1]}, {value[2]})" + self.indexing_code.splice(f"{acc_thread_var} = 0.0;") + if self.multistage_reduction_entry: + self.indexing_code.splice(f"{acc_thread_var} = 0.0;") + self.compute.writeline( + f"{acc_thread_var} = ::c10::metal::welford_combine({acc_thread_var}, {inp_value});" + ) + else: + self.compute.writeline(f"{acc_thread_var} = {inp_value};") + wf_res = self.cse.generate( + self.stores if self.multistage_reduction_entry else self.compute, + f"c10::metal::threadgroup_welford_combine({acc_buf}, {reduction_idx}, {acc_buf_size_str})", + dtype=torch.float32, + ) + return _unwrap_helper(wf_res) + raise NotImplementedError(reduction_type) + + def codegen_iteration_ranges_entry(self, entry: IterationRangesEntry) -> None: + index_expr = self.rename_indexing(entry.expr) + index_str = self.sexpr(index_expr) # type: ignore[misc] + + if not entry.is_reduction or ( + isinstance(entry.root.numel, sympy.Integer) + and entry.root.numel <= self.max_threadgroup_size + ): + self.indexing_code.writeline( + f"{self.index_dtype} {entry.name} = {index_str};" + ) + return + + acc_size = ( + entry.root.numel + if isinstance(entry.root.numel, sympy.Integer) + else sympy.Symbol(f"{entry.root.prefix}numel", integer=True, positive=True) + ) + + # Check if we've already generated a loop for this reduction root + root_already_processed = any( + e.root is entry.root for e in self.multistage_reduction_entry + ) + + linear_idx_name = f"{entry.root.prefix}_linear_idx" + + if not root_already_processed: + self.multistage_reduction_entry.append(entry) + # When reducing the tensor whose size exceeds max threadgroup size + # loop over extra indices per reduction thread and perform part of the operation + # using values in the shared memory + + # Use floats so that it doesn't do integer division + loop_size = (acc_size + float(self.max_threadgroup_size - 1)) // float( + self.max_threadgroup_size + ) + loop_size_str = self.sexpr(loop_size) + + root_name = entry.root.name + + self.body.writeline( + f"for(auto {entry.root.prefix}_cnt = 0; {entry.root.prefix}_cnt < {loop_size_str}; ++{entry.root.prefix}_cnt) {{" + ) + with self.body.indent(): + if isinstance(acc_size, sympy.Symbol): + self.body.writeline( + f"{self.index_dtype} {linear_idx_name} = " + f"{self.max_threadgroup_size} * {entry.root.prefix}_cnt + {root_name};" + ) + else: + self.body.writeline( + f"{self.index_dtype} {linear_idx_name} = {loop_size_str} * {root_name} + {entry.root.prefix}_cnt;" + ) + + # Check that reduction is performed only within tensor boundary + if ( + isinstance(acc_size, sympy.Symbol) + or loop_size * self.max_threadgroup_size != acc_size + ): + self.body.writeline(f"if ({linear_idx_name} >= {acc_size}) break;") + + # Compute entry value from linear index by substituting root name + sub_index_str = index_str.replace(entry.root.name, linear_idx_name) + self.body.writeline( + f"{self.index_dtype} {entry.name} = {sub_index_str};" + ) + else: + # root is already processed so just need to compute this entry's value inside the existing loop + with self.body.indent(): + sub_index_str = index_str.replace(entry.root.name, linear_idx_name) + self.body.writeline( + f"{self.index_dtype} {entry.name} = {sub_index_str};" + ) + + def codegen_body(self) -> None: + """ + Concat output code from index_code, loads, compute, stores, + suffix into self.body. + + For pointwise kernels, this is called just once at the end. + + For reduction kernels, this generates a loop over the reduction + axis. + """ + if self.multistage_reduction_entry: + with self.body.indent(): + self.body.splice(self.loads) + self.body.splice(self.compute) + self.body.writeline("}" * len(self.multistage_reduction_entry)) + # Invalidate variables instantiated inside loop + # But results of reduction alive. Reduction cache values can be + # either CSEVariable or tuple of CSEVariables, in which case all + # variables in the tuple must be preserved + self.cse.invalidate( + OrderedSet( + v + for item in self.cse.reduction_cache.values() + for v in (item if isinstance(item, tuple) else (item,)) + ) + ) + # And loop codegen + roots = [e.root for e in self.multistage_reduction_entry] + self.multistage_reduction_entry.clear() + for node in self.range_tree_nodes.values(): + if any(node.root is r for r in roots): + node.cache_clear() + else: + self.body.splice(self.loads) + self.body.splice(self.compute) + self.body.splice(self.stores) + self.loads.clear() + self.compute.clear() + self.stores.clear() + + def codegen_kernel(self, name: str = "generated_kernel") -> str: + """Called at the end to generate a final kernel string""" + self.codegen_body() + code = IndentedBuffer() + fn_name = name + + if V.graph.cpp_wrapper: + code.writeline('(R"MTL(') + else: + code.writeline("compile_mps_shader('''") + + idx_vars = self.active_range_trees() + with code.indent(): + if not V.graph.cpp_wrapper: + for header in self.headers: + code.writeline(f"#include ") + else: + headers = [ + f"#include " for header in self.headers + ] + header_contents = _embed_headers( + headers, + [Path(__file__).parent.parent.parent / "include"], + OrderedSet(), # type: ignore[arg-type] + ) + code.writeline(header_contents) + + if self.inside_reduction: + total_reduction_size = math.prod( + t.numel for t in self.range_trees if t.is_reduction + ) + # If using dynamic shapes, set the threadgroup size to be the + # max possible size + threadgroup_size = ( + min(total_reduction_size, self.max_threadgroup_size) + if isinstance(total_reduction_size, sympy.Integer) + else self.max_threadgroup_size + ) + code.writeline( + f"[[max_total_threads_per_threadgroup({threadgroup_size})]]" + ) + code.writeline(f"kernel void {fn_name}(") + with code.indent(): + for outer, inner in self.args.output_buffers.items(): + if outer in self.removed_buffers: + continue + dtype_str = self.dtype_to_str(V.graph.get_dtype(outer)) + code.writeline(f"device {dtype_str}* {inner},") + for outer, inner in self.args.input_buffers.items(): + dtype = V.graph.get_dtype(outer) + # MPS does not support float64, but scalar inputs are fine + if dtype == torch.float64: + outer_buf = V.graph.try_get_buffer(outer) + if outer_buf is None or outer_buf.get_size() != []: + raise RuntimeError("float64 is not supported by MPS") + dtype_str = "float" + else: + dtype_str = self.dtype_to_str(dtype) + code.writeline(f"constant {dtype_str}* {inner},") + for inner in self.args.sizevars.values(): + code.writeline(f"constant long& {inner},") + + # Write dynamic values as inputs + for idx_var in idx_vars: + if isinstance(idx_var.numel, sympy.Integer): + pass + else: + code.writeline(f"constant long& {idx_var.prefix}numel,") + + # Add error buffer parameter if error header is used + if "error" in self.headers: + code.writeline("device c10::metal::ErrorMessages* error_buf,") + + if len(idx_vars) >= 4: + raise AssertionError("Up to 3 index variables are supported") + thread_pos_dtype = ( + f"uint{len(idx_vars)}" if len(idx_vars) > 1 else "uint" + ) + thread_pos_var_name = ( + idx_vars[0].name if len(idx_vars) == 1 else "thread_pos" + ) + thread_pos_suffix = "," if self.inside_reduction else "" + code.writeline( + f"{thread_pos_dtype} {thread_pos_var_name} [[thread_position_in_grid]]{thread_pos_suffix}" + ) + if self.inside_reduction: + code.writeline( + f"{thread_pos_dtype} group_pos [[thread_position_in_threadgroup]]" + ) + code.writeline(") {") + with code.indent(): + if len(idx_vars) > 1: + for idx, var in enumerate(idx_vars): + code.writeline( + f"auto {var.name} = thread_pos.{chr(120 + idx)};" + ) + code.splice(self.indexing_code) + code.splice(self.body) + code.writeline("}") + + if V.graph.cpp_wrapper: + code.writeline(')MTL");') + else: + code.writeline("''')") + + return code.getvalue() + + def call_kernel( + self, name: str, node: Any = None, deallocate_ws: bool = True + ) -> None: + """ + Codegens a call to this kernel + """ + wrapper = V.graph.wrapper_code + # Make sure sizevars has been computed + for v in self.args.sizevars: + wrapper.ensure_size_computed(v) + + _, call_args, _, arg_types = self.args.python_argdefs() + arg_name_to_type = { + str(call_arg): arg_type for call_arg, arg_type in zip(call_args, arg_types) + } + + args = [*self.args.output_buffers.keys(), *self.args.input_buffers.keys()] + args = [arg for arg in args if arg not in self.removed_buffers] + args += [str(v) for v in self.args.sizevars] + arg_types = [arg_name_to_type[arg] for arg in args] + + # Add any dynamic ints as inputs + for tree in self.range_trees: + if isinstance(tree.numel, (sympy.Integer, int)): + # Don't need to pass in integers as inputs + continue + elif isinstance(tree.numel, sympy.Symbol): + expr = tree.numel + else: + expr = V.graph.wrapper_code.generate_numel_expr(name, tree).inner + + if not tree.is_reduction or self.inside_reduction: + args.append(str(expr)) + arg_types.append(int) + + expr_printer = self.cexpr if V.graph.cpp_wrapper else self.pexpr + + def format_threads(threads: list[str], kwarg: str) -> str: + if V.graph.cpp_wrapper: + threads = [f"static_cast({t})" for t in threads] + return f"{{{', '.join(threads)}}}" + else: + return f"{kwarg}=[{', '.join(threads)}]" + + # For reduction kernels, limit the maximum size over reduction dimensions to + # a maximum threadgroup size + if len(self.active_range_trees()) > 0: + threads = [ + expr_printer( + Min(v.numel, self.max_threadgroup_size) # type: ignore[misc] + if v.is_reduction + else v.numel + ) + for v in self.active_range_trees() + ] + + args.append(format_threads(threads, "threads")) + arg_types.append(list) + else: + if V.graph.cpp_wrapper: + raise RuntimeError("We should always have threads?") + + if self.inside_reduction: + threads = [ + expr_printer(Min(v.numel, self.max_threadgroup_size)) # type: ignore[misc] + if v.is_reduction + else "1" + for v in self.active_range_trees() + ] + args.append(format_threads(threads, "group_size")) + arg_types.append(list) + else: + if V.graph.cpp_wrapper: + # Add a None so that we always have a group_size in the + # arguments. We won't use it if the value is None. + args += [None] # type: ignore[list-item] + arg_types.append(None) + + # Add error buffer index if error reporting is used + # TODO(malfet) Figure out how to do it for aoti + if "error" in self.headers and not V.graph.cpp_wrapper: + args.append( + f"error_buf_idx={len([arg for arg in args if arg is not None and '=' not in arg])}" + ) + + wrapper.generate_kernel_call( + name, + args, + device=torch.device("mps"), + triton=False, + arg_types=arg_types, + ) + + def device_assert_async(self, cond: CSEVariable, msg: str) -> None: + if V.graph.cpp_wrapper: + self.cse.generate(self.compute, f"if (!{cond}) return", assignment=False) + else: + self.headers.add("error") + self.compute.writelines( + [ + f"if (!{cond}) {{", + f" TORCH_REPORT_ERROR(error_buf, {repr(msg)});", + " return;", + "}", + ] + ) + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + if not (lower or upper): + return + + expr_str = self.index_to_str(expr) + size_str = self.index_to_str(size) + + # Generate bounds checking with error reporting + # TODO(malfet): Is upper bound inclusive or exclusive? + if lower and upper: + # Check both lower and upper bounds + condition = f"({expr_str} < 0 || {expr_str} >= {size_str})" + elif lower: + condition = f"{expr_str} < 0" + else: + condition = f"{expr_str} >= {size_str}" + + # Generate error reporting code + if V.graph.cpp_wrapper: + self.cse.generate( + self.compute, f"if ({condition}) return", assignment=False + ) + else: + # Add error header for error reporting + self.headers.add("error") + self.compute.writelines( + [ + f"if ({condition}) {{", + f' TORCH_REPORT_ERROR(error_buf, "Index ", {expr_str}, " out of range [0, ", {size_str}, ")");', + " return;", + "}", + ] + ) + + +class MetalScheduling(SIMDScheduling): + kernel_type = MetalKernel # type: ignore[assignment] + + def __init__(self, scheduler: Scheduler | None) -> None: + super().__init__(scheduler) + + def define_kernel( + self, src_code: str, node_schedule: list[SchedulerNode], kernel: MetalKernel + ) -> str: + wrapper = V.graph.wrapper_code + if src_code in wrapper.src_to_kernel: + return wrapper.src_to_kernel[src_code] + + if V.graph.cpp_wrapper: + # C++ path: one library per kernel (each has a single "generated_kernel" function) + mps_lib_name = f"mps_lib_{wrapper.next_kernel_suffix()}" + kernel_name = mps_lib_name + wrapper.src_to_kernel[src_code] = kernel_name + src_code = f"const char* {mps_lib_name}_source = " + src_code + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + wrapper.define_kernel( + mps_lib_name, src_code, f"{origins}\n{detailed_origins}", gpu=False + ) + return kernel_name + + # Python path: register kernel with async_compile; wait() will compile all + # accumulated Metal kernels into a single library and replace each placeholder. + fn_name = f"generated_kernel_{wrapper.next_kernel_suffix()}" + wrapper.src_to_kernel[src_code] = fn_name + + # Extract Metal source from compile_mps_shader('''...''') call + metal_src_start = "compile_mps_shader('''" + start = src_code.index(metal_src_start) + len(metal_src_start) + end = src_code.rindex("''')") + metal_src = src_code[start:end] + + # Strip #include lines and rename the kernel function + body_lines = [] + for line in metal_src.split("\n"): + if line.strip().startswith("#include"): + continue + body_lines.append( + line.replace("kernel void generated_kernel(", f"kernel void {fn_name}(") + ) + + headers_repr = repr(sorted(kernel.headers)) + wrapper.header.writeline(f"{fn_name} = async_compile.metal({fn_name!r}, '''") + for line in body_lines: + wrapper.header.writeline(line) + wrapper.header.writeline(f"''', {headers_repr})") + + return fn_name diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps_device_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps_device_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..f8611b73787fcbc1cf9850d7bac42a7db013ae5d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps_device_op_overrides.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from .common import DeviceIdx, DeviceOpOverrides, register_device_op_overrides + + +class MPSDeviceOpOverrides(DeviceOpOverrides): + # MPS is single-device, so a non-zero index is unexpected. device_idx may be a + # runtime expr (str) under compile-on-one-rank, but MPS never receives that (it has + # no current_device_idx_expr override), so guard only the int case. + def device_guard(self, device_idx: DeviceIdx) -> str: + if isinstance(device_idx, int) and device_idx != 0: + raise AssertionError(f"expected device_idx == 0, got {device_idx}") + return "torch._ops.contextlib.nullcontext()" + + def set_device(self, device_idx: DeviceIdx) -> str: + if isinstance(device_idx, int) and device_idx != 0: + raise AssertionError(f"expected device_idx == 0, got {device_idx}") + return "pass # MPS set device" + + def kernel_driver(self) -> str: + return """ + #include + """ + + def cpp_kernel_type(self) -> str: + return "MTLFunction_t" + + +register_device_op_overrides("mps", MPSDeviceOpOverrides()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e58decc8e5387019b4d56f62c9f942c86b8d3b11 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/device_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/device_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b65b12c1e6df33c614febaf9e715a1ed1675baee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/device_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/device_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/device_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..deb1294a0ea72bd6a2bb735b389416208014b45e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/device_op_overrides.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +from ..common import DeviceIdx, DeviceOpOverrides, register_device_op_overrides + + +class MTIADeviceOpOverrides(DeviceOpOverrides): + def import_get_raw_stream_as(self, name: str) -> str: + return f"from torch._C import _mtia_getCurrentRawStream as {name}" + + def set_device(self, device_idx: DeviceIdx) -> str: + return f"torch.mtia.set_device({device_idx})" + + def synchronize(self) -> str: + return "torch.mtia.synchronize()" + + def device_guard(self, device_idx: DeviceIdx) -> str: + return f"torch.mtia.device({device_idx})" + + def current_stream(self) -> str: + return "torch.mtia.current_stream()" + + +register_device_op_overrides("mtia", MTIADeviceOpOverrides()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/multi_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/multi_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..f3441b622cfb0df19e6a3757495429d5a6f513ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/multi_kernel.py @@ -0,0 +1,650 @@ +# mypy: allow-untyped-defs +import functools +import logging +import math +import os +import pathlib +from typing import Any + +from torch._inductor.ir import MultiTemplateBuffer +from torch._inductor.metrics import get_metric_table, is_metric_table_enabled +from torch.utils._ordered_set import OrderedSet + +from .. import config +from ..codecache import code_hash, CodeCacheFuture, get_path, write_atomic +from ..runtime.benchmarking import benchmarker +from ..utils import cache_on_self, IndentedBuffer +from ..virtualized import V +from .common import TensorArg, WorkspaceArg + + +log = logging.getLogger(__name__) + + +class MultiKernelState: + """ + Maintain state of multi-kernel compilation so we don't define duplicated + multi-kernel for the same set of sub-kernels. + + V.graph.wrapper_code has a reference to MultiKernelState instance. + """ + + def __init__(self): + self.subkernel_to_kernel_name = {} + self.kernel_defs = IndentedBuffer() + + def define_kernel( + self, + kernels: list[Any], + kernel_shape_keys: list[None | tuple[tuple[int, ...], ...]] | None = None, + ) -> str: + """ + Previously we name the multi kernel as "multi_kernel_{kernel_names[0]}". + This has some minor issue. + + E.g. for persistent reduction https://gist.github.com/shunting314/39e7c00ff8bb2055942ed5a3255d61ca , + there are 2 flavors of non-persistent reduction: + https://gist.github.com/shunting314/056d43d35907e87efb883970b35c17d4 + and + https://gist.github.com/shunting314/02ee753b65c513c54e695626afe682bd + + The only different is cache eviction policy. + + We should name the multi-kernel differently in these 2 cases. + + kernels: + A list of kernels + kernel_shape_keys: + Specified for size-hint multi-kernels. + Each list element is a shape key, corresponding to the concrete input & output size hints each kernel was tuned for. + """ + # Prevent circular import + from ..select_algorithm import TritonTemplateKernel + + kernel_names = tuple(k.kernel_name for k in kernels) + if kernel_names in self.subkernel_to_kernel_name: + return self.subkernel_to_kernel_name[kernel_names] + + # name the multi kernel based on the first kernel + multi_kernel_name = f"multi_kernel_{len(self.subkernel_to_kernel_name)}" + self.subkernel_to_kernel_name[kernel_names] = multi_kernel_name + + if V.graph.cpp_wrapper and not config.triton.autotune_at_compile_time: + # we should not generate any python code for multi-kernel during + # the second pass of cpp-wrapper. + return multi_kernel_name + + arg_index: dict[int, list[slice]] = {} + _, call_args, _, arg_types = kernels[0].args.python_argdefs() + if isinstance(kernels[0], TritonTemplateKernel) and isinstance( + kernels[0].output_node, MultiTemplateBuffer + ): + for i, kernel in enumerate(kernels): + additional_call_args, _ = kernel.additional_call_args_and_types() + if i not in arg_index: + arg_index[i] = [] + arg_index[i].append(slice(0, len(call_args))) + arg_index[i].append( + slice( + len(call_args) + i * len(additional_call_args), + len(call_args) + (i + 1) * len(additional_call_args), + ) + ) + else: + kernels[0].add_numel_to_call_args(multi_kernel_name, call_args, arg_types) + for i in range(len(kernels)): + arg_index[i] = [slice(0, len(call_args))] + + keyed_by_sizes = kernel_shape_keys is not None + buf = self.kernel_defs + buf.writeline("") + buf.writeline("arg_index = {") + for key, slice_list in arg_index.items(): + slice_reprs = ", ".join(repr(s) for s in slice_list) + buf.writeline(f" {key}: [{slice_reprs}],") + buf.writeline("}") + + if not keyed_by_sizes: # no size hint keys, just call with list of kernels + buf.writeline( + f"{multi_kernel_name} = async_compile.multi_kernel({multi_kernel_name!r}, [" + ) + with buf.indent(): + for name in kernel_names: + buf.writeline(f"{name},") + buf.writeline("], arg_index=arg_index)") + else: # call with dict[size hint key, kernel] + if not isinstance(kernels[0], TritonTemplateKernel): + raise AssertionError("expected kernels[0] to be a TritonTemplateKernel") + if not isinstance(kernel_shape_keys, list): + raise AssertionError("expected kernel_shape_keys to be a list") + if len(kernels) != len(kernel_shape_keys): + raise AssertionError( + f"expected len(kernels) == len(kernel_shape_keys), " + f"got {len(kernels)} != {len(kernel_shape_keys)}" + ) + buf.writeline( + f"{multi_kernel_name} = async_compile.size_hint_multi_kernel({multi_kernel_name!r}, {{" + ) + with buf.indent(): + for shape_key, name in zip(kernel_shape_keys, kernel_names): + buf.writeline(f"{shape_key}: {name},") + buf.writeline("}, arg_index=arg_index)") + + if config.triton.autotune_at_compile_time: + V.graph.wrapper_code.src_to_kernel["\n".join(kernel_names)] = ( + multi_kernel_name + ) + + return multi_kernel_name + + +class MultiKernel: + """ + This class maintains the compile time state for multi kernels. + + Assume we do codegen for a MultiKernel encapsulating kernel1 and kernel2. + The generated definition for the multi-kernel will looks like: + ``` + multi_kernel_kernel1 = MultiKernelCall( + [kernel1, kernel2], multi_kernel_definition_code + ) + ``` + + Here is a concrete example: https://gist.github.com/shunting314/d9f3fb6bc6cee3dbae005825ca196d39 + """ + + def __init__(self, kernels): + if len(kernels) < 2: + raise AssertionError(f"expected at least 2 kernels, got {len(kernels)}") + + self.kernels = kernels + self.kernel_name = V.graph.wrapper_code.multi_kernel_state.define_kernel( + kernels + ) + + # need this since some code in inductor check if the kernel object has an args + # attribute to decide if it's a non-null kernel. + self.args = object() + + @staticmethod + def _merge_workspace_args(left: list[WorkspaceArg], right: list[WorkspaceArg]): + if left == right: + return left + result = {x.inner_name: x for x in left} + for arg in right: + if arg.inner_name in result: + result[arg.inner_name] = WorkspaceArg.maximum( + result[arg.inner_name], arg + ) + else: + result[arg.inner_name] = arg + return [*result.values()] + + @staticmethod + def merge_workspaces_inplace(kernels): + if len(kernels) < 2: + return + # All kernels must share the same workspace + workspace_args = functools.reduce( + MultiKernel._merge_workspace_args, + [kernel.args.workspace_args for kernel in kernels], + ) + for kernel in kernels: + kernel.args.workspace_args = workspace_args + return workspace_args + + def call_kernel(self, kernel_name): + """ + Collect the union of arguments from all subkernels as the arguments + for the multi-kernel. + """ + # Prevent circular import + from ..select_algorithm import TritonTemplateKernel + + if kernel_name != self.kernel_name: + raise AssertionError( + f"expected kernel_name == self.kernel_name, " + f"got {kernel_name} != {self.kernel_name}" + ) + V.graph.wrapper_code.write_triton_header_once() + _, call_args, _, arg_types = self.kernels[0].args.python_argdefs() + for kernel in self.kernels[1:]: + _, other_call_args, _, other_arg_types = kernel.args.python_argdefs() + if call_args != other_call_args: + raise AssertionError((call_args, other_call_args)) + if arg_types != other_arg_types: + raise AssertionError( + f"expected arg_types == other_arg_types, " + f"got {arg_types} != {other_arg_types}" + ) + + if V.graph.cpp_wrapper and not config.triton.autotune_at_compile_time: + # for the second pass of cpp-wrapper codegen, we should call + # the fast kernel directly + kernel_name = MultiKernelCall.lookup_choice(self.kernel_name) + + if isinstance(self.kernels[0], TritonTemplateKernel) and isinstance( + self.kernels[0].output_node, MultiTemplateBuffer + ): + # For matmuls the grid arguments are passed in as additional arguments + # to the kernel run method. These grids change based on the various + # parameters of the matmul. So we need to pass each kernel's grid into + # the multi call kernel. + multi_call_args = call_args + multi_call_arg_types = arg_types + for kernel in self.kernels: + additional_call_args, additional_arg_types = ( + kernel.additional_call_args_and_types() + ) + multi_call_args.extend(list(additional_call_args)) + multi_call_arg_types.extend(list(additional_arg_types)) + else: + # numels for all subkernels should be the same. Use kernels[0] here + self.kernels[0].add_numel_to_call_args(kernel_name, call_args, arg_types) + multi_call_args = call_args + multi_call_arg_types = arg_types + + for ws in self.kernels[0].args.workspace_args: + V.graph.wrapper_code.generate_workspace_allocation(ws) + + if V.graph.cpp_wrapper: + # We have already selected the best kernel at compile time + # so we only have one set of call args. NB: this currently + # doesn't work with MultiTemplateBuffer kernels. @bobrenjc93 + # will add it in a subsequent PR. + V.graph.wrapper_code.generate_kernel_call( + kernel_name, call_args, arg_types=arg_types + ) + else: + V.graph.wrapper_code.generate_kernel_call( + kernel_name, multi_call_args, arg_types=multi_call_arg_types + ) + + for ws in reversed(self.kernels[0].args.workspace_args): + V.graph.wrapper_code.generate_workspace_deallocation(ws) + + def codegen_nan_check(self): + wrapper = V.graph.wrapper_code + seen: OrderedSet[str] = OrderedSet() + for k in self.kernels: + _, call_args, precompile_args, _ = k.args.python_argdefs() + for arg, precompile_arg in zip(call_args, precompile_args): + if arg in seen: + continue + seen.add(arg) + if isinstance(precompile_arg, TensorArg): + line = f"assert not {arg}.isnan().any().item()" + wrapper.writeline(line) + line = f"assert not {arg}.isinf().any().item()" + wrapper.writeline(line) + + @property + def removed_buffers(self): + return OrderedSet.intersection(*[k.removed_buffers for k in self.kernels]) + + @property + def inplaced_to_remove(self): + return OrderedSet.intersection(*[k.inplaced_to_remove for k in self.kernels]) + + @property + @cache_on_self + def inplace_update_buffers(self): + """ + Make sure all kernels have the same inplace update mappings. + """ + for k in self.kernels[1:]: + if k.inplace_update_buffers != self.kernels[0].inplace_update_buffers: + raise AssertionError( + "expected all kernels to share the same inplace_update_buffers" + ) + return self.kernels[0].inplace_update_buffers + + def warn_mix_layout(self, kernel_name: str): + pass + + +class MultiKernelCall: + """ + This class is called at run time to actually run the kernel + """ + + def __init__(self, multi_kernel_name, kernels, arg_index): + if len(kernels) < 1: + raise AssertionError(f"expected at least 1 kernel, got {len(kernels)}") + self._kernels = kernels + self.multi_kernel_name = multi_kernel_name + + self.disable_cache = os.environ.get( + "TORCHINDUCTOR_DISABLE_MULTI_KERNEL_CACHE" + ) == "1" or is_metric_table_enabled("persistent_red_perf") + + self.picked_kernel = None + self.arg_index = arg_index + if config.triton.multi_kernel > 1: + # manually force a subkernel to ease perf testing + picked_by_config = config.triton.multi_kernel - 2 + if picked_by_config >= len(self._kernels): + raise AssertionError( + f"expected picked_by_config < len(self._kernels), " + f"got {picked_by_config} >= {len(self._kernels)}" + ) + # pyrefly: ignore [bad-assignment] + self.picked_kernel = picked_by_config + elif not self.disable_cache: + self.load_cache() + + self._recorded = False + + def cache_file_path(self): + key = code_hash( + ",".join( + [ + f"{k.fn.cache_key}{k.size_hints!r}{k.triton_meta!r}" + for k in self.kernels + ] + ) + ) + _, _, path = get_path(key, "picked_kernel") + return pathlib.Path(path) + + def load_cache(self): + if self.picked_kernel is not None: + raise AssertionError("expected self.picked_kernel to be None") + path = self.cache_file_path() + if path.exists(): + with path.open() as fd: + # pyrefly: ignore [bad-assignment] + self.picked_kernel = int(fd.read()) + # pyrefly: ignore [unsupported-operation] + if not ( + self.picked_kernel >= 0 and self.picked_kernel < len(self._kernels) + ): + raise AssertionError( + f"expected 0 <= picked_kernel < {len(self._kernels)}, " + f"got {self.picked_kernel}" + ) + log.debug( + "Load picked kernel %d from cache file %s", self.picked_kernel, path + ) + + def store_cache(self): + if self.picked_kernel is None: + raise AssertionError("expected self.picked_kernel to not be None") + path = self.cache_file_path() + path.parent.mkdir(parents=True, exist_ok=True) + + write_atomic(path, str(self.picked_kernel)) + log.debug("Store picked kernel %d to cache file %s", self.picked_kernel, path) + + @property + def kernels(self): + """ + Read results from future. + + This should be called after parallel compilation is done. + In case you call this before compilation is done, + it may slow down the parallel compilation. + """ + for i, kernel in enumerate(self._kernels): + if isinstance(kernel, CodeCacheFuture): + self._kernels[i] = kernel.result() + + return self._kernels + + def benchmark_sub_kernels(self, *args, **kwargs): + """ + Benchmark all the sub kernels and return the execution time + (in milliseconds) for each of time. + + Unit test may mock this method to force a specific kernel to + be picked. + """ + + def wrap_fn(kernel, index): + def inner(): + filtered_args = self._get_filtered_args(args, index) + args_clone, kwargs_clone = kernel.clone_args(*filtered_args, **kwargs) + return kernel.run(*args_clone, **kwargs_clone) + + return inner + + return [ + benchmarker.benchmark( + wrap_fn(kernel, index), + # Currently the kernel type must be a CachingAutotuner + device=kernel.device_props.type, + rep=40, + ) + for index, kernel in enumerate(self.kernels) + ] + + def _get_filtered_args(self, args, index): + """ + We pass in all arguments to all kernels into the MultiKernelCall + so when invoking a particular kernel we need to filter to only the + arguments for that specific kernel. + """ + + # This is sometimes invoked at runtime where V.graph is + # a NullHandler + if hasattr(V.graph, "cpp_wrapper") and V.graph.cpp_wrapper: + # for cpp-wrapper, we should not filter the args since + # we already have chosen a single kernel and arg set. + return args + return [item for s in self.arg_index[index] for item in args[s]] + + # record_choice and lookup_choice are helper functions for cpp-wrapper + # codegen. The first pass use record_choice to keep the choice and + # the second pass do lookup by calling lookup_choice. + # + # An alternative that reused the multi-kernel cache does not work well + # since during codegen of the second pass, it's very hard to know the + # path for the cache file. Also reading the cache file need do some IO + # which can be slower. + @staticmethod + def record_choice(multi_kernel_name: str, picked_kernel_name: str): + """ + Record the multi-kernel choice for cpp-wrapper after autotuning + + We should do nothing if this function is not called during codegen. + """ + from torch._inductor.graph import GraphLowering + + if not isinstance(V.graph, GraphLowering): + return + + if not V.graph.record_multi_kernel_choice: + return + + V.graph.multi_kernel_to_choice[multi_kernel_name] = picked_kernel_name + + @staticmethod + def lookup_choice(multi_kernel_name: str) -> str: + # this should always been done during cpp-wrapper codegen + if not ( + V.graph.record_multi_kernel_choice + and multi_kernel_name in V.graph.multi_kernel_to_choice + ): + raise AssertionError( + f"expected multi_kernel_name {multi_kernel_name} to be recorded " + f"during cpp-wrapper codegen" + ) + # there should be no miss + return V.graph.multi_kernel_to_choice[multi_kernel_name] + + def run(self, *args, **kwargs): + if self.picked_kernel is None: + timings = self.benchmark_sub_kernels(*args, **kwargs) + self.picked_kernel = timings.index(min(timings)) + k0 = self.kernels[0] + log.debug( + "pick %dth sub-kernel in %s. Size hints %s. Reduction hint %s. Timings %s", + self.picked_kernel, + [k.inductor_meta.get("kernel_name") for k in self.kernels], + k0.size_hints, + k0.inductor_meta.get("reduction_hint"), + timings, + ) + get_metric_table("persistent_red_perf").add_row( + functools.partial(self._metrics_table_row, timings) + ) + + if not self.disable_cache: + self.store_cache() + + if not self._recorded: + self._recorded = True + picked_kernel_name = self.kernels[self.picked_kernel].inductor_meta.get( + "kernel_name" + ) + if picked_kernel_name is None: + raise AssertionError("expected picked_kernel_name to not be None") + self.record_choice(self.multi_kernel_name, picked_kernel_name) + + run = self.kernels[self.picked_kernel].run # type: ignore[method-assign] + filtered_args = self._get_filtered_args(args, self.picked_kernel) + run(*filtered_args, **kwargs) + + def _metrics_table_row(self, timings): + def get_kernel_path(k): + return k.fn.fn.__code__.co_filename + + k0 = self.kernels[0] + row = { + "size_hints": k0.size_hints, + "reduction_hint": k0.inductor_meta.get("reduction_hint"), + } + max_kernels = 4 + if len(timings) > max_kernels: + raise AssertionError( + f"expected len(timings) <= {max_kernels}, got {len(timings)}" + ) + for i in range(max_kernels): + if i < len(self.kernels): + row[f"kernel{i}_path"] = get_kernel_path(self.kernels[i]) + row[f"kernel{i}_latency"] = timings[i] + else: + row[f"kernel{i}_path"] = "" + row[f"kernel{i}_latency"] = "" + return row + + +class SizeHintMultiKernel(MultiKernel): + """ + Version of multi-kernel that generates kernels based on specified size hints. + Currently only performs 1-d search over hints; doesn't perform combinatorial n-d search + if n > 1 dynamic dimensions are specified. + + e.g. matmul([s0, s1], [s1, s2]) with size-hints [64, 256] only generates 2 kernels, + based on tuning shapes ([64, 64], [64, 64]) and ([256, 256], [256, 256]) + """ + + def __init__(self, kernels): + if not (isinstance(kernels, dict) and len(kernels) >= 1): + raise AssertionError("expected kernels to be a non-empty dict") + + self.kernels, self.kernel_shape_keys = [], [] + for shape_key, kernel in kernels.items(): + self.kernels.append(kernel) + self.kernel_shape_keys.append(shape_key) + self.kernel_name = V.graph.wrapper_code.multi_kernel_state.define_kernel( + self.kernels, self.kernel_shape_keys + ) + + # need this since some code in inductor check if the kernel object has an args + # attribute to decide if it's a non-null kernel. + self.args = object() + + +class SizeHintMultiKernelCall(MultiKernelCall): + """ + Runtime class for size-hint multi-kernels. + Instead of having a plain list of kernels to benchmark over, keys them by input & output shapes, + and optionally perform shape-based selection. The pre-generated kernel is chosen based on the shape keys, + with the heuristic being log2 l1 distance between the pre-generated / runtime input & output shapes. + """ + + def __init__(self, multi_kernel_name, kernels, arg_index): + super().__init__(multi_kernel_name, list(kernels.values()), arg_index) + self._kernel_hints = list(kernels.keys()) + + # Caches results for unique shapes. + self._shape_cache = {} + + def _get_shape_cache_key(self, *args, **kwargs): + """ + Generate a cache key based on tensor shapes for shape-specialized dispatch. + """ + shapes = [] + for arg in args: + if hasattr(arg, "shape"): + shapes.append(tuple(arg.shape)) + return tuple(shapes) + + def _get_cached_shape_choice(self, cache_key): + """ + Get cached kernel choice for a specific shape. + """ + return self._shape_cache.get(cache_key) + + def _cache_shape_choice(self, cache_key, kernel_idx): + """ + Cache kernel choice for a specific shape. + """ + self._shape_cache[cache_key] = kernel_idx + + def _dist_heuristic(self, k1, k2): + """ + log2 L1 distance heuristic for kernel selection. + """ + + def dist(x, y): + lx = math.log2(x) if x > 0 else -1 + ly = math.log2(y) if y > 0 else -1 + return abs(lx - ly) + + out = 0 + for s1, s2 in zip(k1, k2): + out += sum(dist(x, y) for x, y in zip(s1, s2)) + return out + + def run(self, *args, **kwargs): + cache_key = self._get_shape_cache_key(*args, **kwargs) + cached_choice = self._get_cached_shape_choice(cache_key) + if cached_choice is not None: + self.picked_kernel = cached_choice + log.debug( + "using cached shape-specialized choice %dth sub-kernel in %s. Cache key: %s", + self.picked_kernel, + [k.inductor_meta.get("kernel_name") for k in self.kernels], + cache_key, + ) + else: + self._select_kernel_by_shape(*args, **kwargs) + + if not self._recorded: + self._recorded = True + picked_kernel_name = self.kernels[self.picked_kernel].inductor_meta.get( + "kernel_name" + ) + if picked_kernel_name is None: + raise AssertionError("expected picked_kernel_name to not be None") + self.record_choice(self.multi_kernel_name, picked_kernel_name) + + run = self.kernels[self.picked_kernel].run # type: ignore[method-assign] + filtered_args = self._get_filtered_args(args, self.picked_kernel) + run(*filtered_args, **kwargs) + + def _select_kernel_by_shape(self, *args, **kwargs): + """ + Benchmark kernels for a particular shape and return the + best kernel for this shape. + """ + shape_key = self._get_shape_cache_key(*args, **kwargs) + dists = [ + self._dist_heuristic(shape_key, key) if key is not None else 2**62 + for key in self._kernel_hints + ] + # pyrefly: ignore [bad-assignment] + self.picked_kernel = dists.index(min(dists)) + self._cache_shape_choice(shape_key, self.picked_kernel) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe56018556a87428ade608318df42c05540fb0b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__init__.py @@ -0,0 +1,19 @@ +# mypy: allow-untyped-defs +from .nv_universal_gemm import ( + add_nv_universal_addmm_choices, + add_nv_universal_gemm_choices, + add_nv_universal_grouped_gemm_choices, + add_nv_universal_scaled_gemm_choices, + GemmVariant, + NVUniversalGemmCaller, +) + + +__all__ = [ + "GemmVariant", + "NVUniversalGemmCaller", + "add_nv_universal_addmm_choices", + "add_nv_universal_gemm_choices", + "add_nv_universal_grouped_gemm_choices", + "add_nv_universal_scaled_gemm_choices", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e1be744dba6f4aa648dc5bb4b209154e173f72e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/kernel_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/kernel_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa78f9c008c3431b28e35186c59d62e953a891f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/kernel_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c802f9021a6e5f1040c2e160b3a7ff6823054b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f09bd0abbf44f2de0e65934616f0e97a568e077c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2faf4b8284baca4502ae5adf8e5c199460deae31 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2ba65a17ce017406d0fbcbc84cc4c8e21a80e3b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/kernel_cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/kernel_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..09fb1b38a7e2f80962823430917c8e68a7985b3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/kernel_cache.py @@ -0,0 +1,641 @@ +# mypy: allow-untyped-defs +""" +Global kernel cache for NVIDIA Universal GEMM. + +This module provides a lazy-initialized cache for cutlass.operators kernels, +avoiding expensive manifest scans on every kernel lookup. + +The first call to get_kernel_by_name() loads all kernels from cutlass.operators +(~10 seconds) and builds a name->kernel dict. Subsequent calls use the +dict for O(1) lookup (~0.1 μs). +""" + +import dataclasses +import functools +import logging +import threading +from collections.abc import Callable +from typing import Any, Literal + +import torch + + +log = logging.getLogger(__name__) + + +@functools.cache +def _device_target(cc: int) -> Any: + """The CUDA arch target for this device (e.g. cc=100 -> TargetSm '100a'). + + Used to reject kernels whose `supported_targets` don't cover this device. + `designed_for_min_cc` alone is insufficient: an arch-conditional sm90 kernel + reports min_cc=90 (which is <= a 100 device) yet only lists a cc=90 target + and fails to compile on sm100 ("expects arch sm_90a, but got sm_100a"). + """ + from cutlass.operators.arch import TargetSm + + return TargetSm.ensure(f"{cc}a") + + +def _epilogue_args_signature(epilogue_args: Any) -> tuple: + """Extract a hashable signature of epilogue args for cache keying. + + Two callers with the same `(efc_kernel_name, epilogue_source)` but + different aux-tensor specs (dtype, shape, stride) would otherwise share + a kernel object whose internal JIT state is mutated by each call to + `kernel.compile(args)` — a silent miscompile, since the compiled + artifact's launch closure reads the kernel's CURRENT JIT at launch time + rather than the one from when the artifact was built. + """ + if epilogue_args is None: + return () + tensors = getattr(epilogue_args, "tensors", None) + if not tensors: + return () + sig: list[tuple] = [] + for name, val in tensors.items(): + if torch.is_tensor(val): + sig.append( + (name, "tensor", val.dtype, tuple(val.shape), tuple(val.stride())) + ) + else: + sig.append((name, type(val).__name__)) + return tuple(sig) + + +# Reentrant: get_efc_kernel_with_epilogue holds this lock and may call +# get_kernel_by_name -> _ensure_caches, which re-acquires it on the same thread. +_cache_lock = threading.RLock() + +# Full kernel manifest: kernel_name -> kernel object. Built lazily (~14s, ~290K +# operators) only as a LAST-RESORT fallback -- the common paths (choice +# generation and subprocess precompile) resolve operators via cheap +# args-filtered queries and cache them in _ops_by_name. +_kernel_by_name_cache: dict[str, Any] | None = None + + +def _operand_dtype_str(operand: Any) -> str | None: + """Best-effort cutlass dtype name for a kernel operand or args operand.""" + dtype = getattr(operand, "dtype", None) + if dtype is None: + tensor = getattr(operand, "tensor", None) + dtype = getattr(tensor, "dtype", None) + return None if dtype is None else str(dtype) + + +def _build_kernel_cache() -> dict[str, Any]: + """Build the full kernel name -> kernel manifest (fallback path only).""" + import cutlass.operators + + log.debug("Building NVGEMM kernel cache (this may take a few seconds)...") + + try: + from torch._inductor.kernel.vendored_templates.cutedsl import ( # noqa: F401 + wrappers, + ) + except ImportError: + log.debug("Vendored kernel wrappers not available") + + all_kernels = cutlass.operators.get_operators() + cache = {k.metadata.operator_name: k for k in all_kernels} + log.debug("NVGEMM kernel manifest built: %d kernels", len(cache)) + return cache + + +def _ensure_caches() -> None: + global _kernel_by_name_cache + if _kernel_by_name_cache is None: + with _cache_lock: + if _kernel_by_name_cache is None: + _kernel_by_name_cache = _build_kernel_cache() + + +def _get_kernel_cache() -> dict[str, Any]: + """Return the fallback manifest, building it lazily if needed. + + Snapshot to local frame: a concurrent clear_cache() rebinding the global to + None cannot turn the caller's subsequent read into AttributeError. + """ + _ensure_caches() + cache = _kernel_by_name_cache + if cache is None: + raise AssertionError("expected cache to be not None") + return cache + + +def _operand_sig(operand: Any) -> tuple | None: + """Hashable (dtype, shape, stride, scale-sig, mode, swizzle) signature.""" + if operand is None: + return None + w = getattr(operand, "tensor", operand) + dtype = _operand_dtype_str(operand) + shape = getattr(w, "shape", None) + stride = getattr(w, "stride", None) + if dtype is None or shape is None or stride is None: + return None + scale = getattr(operand, "scale", None) + scale_sig = _operand_sig(scale) if scale is not None else None + # ScaledOperand.mode/.swizzle are distinct from the scale tensor's layout + # and are not folded into it, yet supports(args) depends on them -- two + # scaled GEMMs with identical operand/scale layouts but different scale or + # swizzle modes must not collide. Read from __dict__ (only ScaledOperand + # sets these) so a dense operand's torch.Tensor.mode method isn't captured. + d = getattr(operand, "__dict__", {}) + mode, swizzle = d.get("mode"), d.get("swizzle") + # mode/swizzle are cutlass.operators enums (ScaleMode/ScaleSwizzleMode) that + # are unhashable, so key on their .name to keep the sig usable as a dict key. + mode = getattr(mode, "name", mode) + swizzle = getattr(swizzle, "name", swizzle) + return (dtype, tuple(shape), tuple(stride), scale_sig, mode, swizzle) + + +def _partition_sig(args: Any) -> tuple | None: + """Signature capturing everything `supports(args)` depends on, or None if + it can't be fully determined (falls back to a non-memoized scan).""" + a = _operand_sig(getattr(args, "A", None)) + b = _operand_sig(getattr(args, "B", None)) + o = _operand_sig(getattr(args, "out", None)) + if a is None or b is None or o is None: + return None + return (a, b, o, getattr(args, "accumulator_type", None)) + + +# Per-process cache of instantiated operators, keyed by operator_name. Populated +# incrementally by the args-filtered queries below (choice generation and the +# subprocess precompile fast path). One args query returns the whole set of +# operators compatible with a shape (hundreds); we index all of them, so any +# later lookup -- another config of that shape, another shape sharing those +# templates, or get_kernel_by_name for a chosen +# kernel -- resolves in O(1) without rebuilding the ~14s manifest. Operator +# names embed the arch (e.g. "..._sm100_..."), so the name alone is unambiguous +# within a process. Reusing an operator across different args is safe for the +# same reason the manifest always has been: an operator is a config template +# (its args-specific state lives in the artifact returned by compile(args)), and +# every (name, args) pairing routed here was validated by supports(args). +_ops_by_name: dict[str, Any] = {} + +# Memoizes partition results. `partition_compatible_kernels` is called once per +# GEMM node during choice generation, but FLUX has hundreds of nodes sharing a +# handful of shapes (e.g. 114 nodes are all 4608x3072x3072); memoizing collapses +# that to one args query per unique shape. +_partition_cache: dict[tuple, list[list[Any]]] = {} + + +def _args_query_candidates(args: Any, cc: int, efc_only: bool) -> list[Any]: + """Compatible operators via an args-filtered get_operators query (~0.05s). + + cutlass prunes by supports(args) and the device target internally. Only + valid for the dense GEMM path: for that path this returns the identical set + as the full-manifest scan (verified), avoiding the ~14s manifest build. + """ + import cutlass.operators + + metadata_filter = ( + (lambda md: "EFC" in md.operator_class.__name__) if efc_only else None + ) + return cutlass.operators.get_operators( + args=args, target_sm=f"{cc}a", metadata_filter=metadata_filter + ) + + +def _filter_supported(kernels: Any, args: Any, cc: int) -> list[Any]: + """Keep the kernels that support `args` on this device. + + Prunes by (A, B) operand dtype first (a cheap string compare) so the + expensive supports() runs only on the ~hundreds that could possibly match -- + the ~290K manifest spans all dtypes, and a GEMM only matches its own. + """ + device_target = _device_target(cc) + dtype_a = _operand_dtype_str(getattr(args, "A", None)) + dtype_b = _operand_dtype_str(getattr(args, "B", None)) + out = [] + for kernel in kernels: + if kernel.designed_for_min_cc > cc: + continue + operands = kernel.metadata.operands + if ( + _operand_dtype_str(getattr(operands, "A", None)) != dtype_a + or _operand_dtype_str(getattr(operands, "B", None)) != dtype_b + ): + continue + if not device_target.supports_operators_from(kernel.metadata.supported_targets): + continue + if kernel.supports(args).error is not None: + continue + out.append(kernel) + return out + + +def _manifest_candidates(args: Any, cc: int, efc_only: bool) -> list[Any]: + """Compatible operators via a full-manifest scan (last-resort fallback).""" + kernels = _get_kernel_cache().values() + if efc_only: + kernels = ( + kernel + for kernel in kernels + if "EFC" in kernel.metadata.operator_class.__name__ + ) + return _filter_supported(kernels, args, cc) + + +def _blockscaled_provider_classes() -> list[Any]: + """The operator classes that produce block-scaled (fp4/fp8) kernels. + + Both the cutlass built-in and the vendored provider matter: for NVFP4 the + vendored kernels supply most of the working configs (60 of 96), so missing + either under-generates and breaks scaled autotuning. + """ + classes: list[Any] = [] + try: + from cutlass.operators.providers.cutedsl.gemm.sm100_dense_blockscaled_static_persistent import ( + PersistentDenseBlockScaledGemmOperator, + ) + + classes.append(PersistentDenseBlockScaledGemmOperator) + except ImportError: + pass + try: + from torch._inductor.kernel.vendored_templates.cutedsl.wrappers.dense_blockscaled_gemm_kernel import ( + VendoredDenseBlockScaledGemmKernel, + ) + + classes.append(VendoredDenseBlockScaledGemmKernel) + except ImportError: + pass + return classes + + +@functools.cache +def _blockscaled_operators() -> tuple: + """Generate the architecture-neutral block-scaled operator pool.""" + ops: list[Any] = [] + for cls in _blockscaled_provider_classes(): + ops.extend(cls.generate_operators(lambda md: True, args=None)) + return tuple(ops) + + +def _scaled_operand_type_signature(args: Any) -> tuple: + def operand_signature(operand: Any) -> tuple: + scale = getattr(operand, "scale", None) + return ( + _operand_dtype_str(operand), + _operand_dtype_str(scale), + str(getattr(operand, "mode", None)), + str(getattr(operand, "swizzle", None)), + ) + + return ( + operand_signature(args.A), + operand_signature(args.B), + _operand_dtype_str(args.out), + str(getattr(args, "accumulator_type", None)), + ) + + +def _scaled_metadata_type_signature(metadata: Any) -> tuple: + operands = metadata.operands + + def operand_signature(operand: Any) -> tuple: + scale = getattr(operand, "scale", None) + return ( + _operand_dtype_str(operand), + _operand_dtype_str(scale), + str(getattr(operand, "mode", None)), + str(getattr(operand, "swizzle", None)), + ) + + return ( + operand_signature(operands.A), + operand_signature(operands.B), + _operand_dtype_str(operands.out), + str(getattr(operands, "accumulator_type", None)), + ) + + +@functools.cache +def _blockscaled_manifest(cc: int, type_signature: tuple): + """Build a block-scaled manifest for one operand type recipe. + + The provider set is generated without a concrete target to preserve its + complete design space. The manifest applies shape and target filtering when + candidates are requested. + """ + import cutlass.operators + + manifest = cutlass.operators.Manifest() + manifest.add_operators( + [ + op + for op in _blockscaled_operators() + if _scaled_metadata_type_signature(op.metadata) == type_signature + ] + ) + return manifest + + +def _scaled_candidates(args: Any, cc: int, efc_only: bool) -> list[Any]: + """Compatible operators for a scaled GEMM via direct block-scaled enumeration. + + get_operators(args=...) derives operand configs from the args and + under-generates for scaled (e.g. ~36 of 96 valid fp4 kernels), so we scan the + block-scaled sub-provider's full design space instead -- complete, and ~50x + cheaper than the manifest. Falls back to the manifest if the provider is + unavailable or nothing matches (e.g. a future non-block-scaled scaled dtype). + """ + from torch._inductor.kernel.vendored_templates.cutedsl.wrappers.dense_blockscaled_gemm_kernel import ( + VendoredDenseBlockScaledGemmEFC, + VendoredDenseBlockScaledGemmKernel, + ) + + manifest = _blockscaled_manifest(cc, _scaled_operand_type_signature(args)) + if manifest.operators: + out = manifest.filter_operators( + args=args, + target_sm=f"{cc}a", + ) + if out: + efc = [] + for op in out: + if op.metadata.operator_class is not VendoredDenseBlockScaledGemmKernel: + continue + metadata = dataclasses.replace( + op.metadata, + operator_name=op.metadata.operator_name.replace( + "VendoredDenseBlockScaledGemmKernel", + "VendoredDenseBlockScaledGemmEFC", + 1, + ), + operator_class=VendoredDenseBlockScaledGemmEFC, + ) + efc.append(VendoredDenseBlockScaledGemmEFC(metadata)) + if efc: + return efc if efc_only else [*out, *efc] + if not efc_only: + return out + return _manifest_candidates(args, cc, efc_only) + + +def partition_compatible_kernels( + args: Any, + cc: int, + classifier: Callable[[Any], int], + num_buckets: int, + efc_only: bool = False, + candidate_source: Literal["args", "scaled", "manifest"] = "manifest", + classifier_key: str | None = None, +) -> list[list[Any]]: + """Partition the operators compatible with `args` into N buckets. + + `classifier(metadata)` returns a bucket index in [0, num_buckets-1] or -1 to + drop the kernel. `candidate_source` selects how the compatible set is found, + all of which avoid the ~14s full manifest except "manifest": + - "args" dense GEMM: cheap args-filtered get_operators query + - "scaled" scaled GEMM: direct block-scaled sub-provider enumeration + - "manifest" fallback (e.g. grouped GEMM): full-manifest scan + `efc_only` restricts to epilogue-fusion-capable kernels (the addmm/bias + path). Results are memoized per (shape, cc, num_buckets, efc_only, source). + """ + sig = _partition_sig(args) + cache_key = ( + (sig, cc, num_buckets, efc_only, candidate_source, classifier_key) + if sig is not None and classifier_key is not None + else None + ) + if cache_key is not None: + cached = _partition_cache.get(cache_key) + if cached is not None: + return [list(b) for b in cached] + + if candidate_source == "args": + candidates = _args_query_candidates(args, cc, efc_only) + elif candidate_source == "scaled": + candidates = _scaled_candidates(args, cc, efc_only) + elif candidate_source == "manifest": + candidates = _manifest_candidates(args, cc, efc_only) + else: + raise ValueError(f"Unknown NVGEMM candidate source: {candidate_source}") + + buckets: list[list[Any]] = [[] for _ in range(num_buckets)] + for kernel in candidates: + # Share every compatible operator so a later get_kernel_by_name (e.g. the + # scheduling max_active_clusters lookup for the chosen kernel) hits + # without building the manifest. + _ops_by_name.setdefault(kernel.metadata.operator_name, kernel) + bucket = classifier(kernel.metadata) + if bucket < 0: + continue + buckets[bucket].append(kernel) + log.debug( + "Partitioned %d compatible operators into buckets %s", + len(candidates), + [len(b) for b in buckets], + ) + if cache_key is not None: + _partition_cache[cache_key] = [list(b) for b in buckets] + return buckets + + +def get_kernel_by_name(kernel_name: str) -> Any: + """Get a kernel by name. + + Checks the incrementally-populated operator cache first (filled by the + args-filtered queries during choice generation / precompile), falling back + to the full manifest only if the name was never resolved via args. + """ + kernel = _ops_by_name.get(kernel_name) + if kernel is not None: + return kernel + return _get_kernel_cache().get(kernel_name) + + +def get_kernel_by_name_via_args(kernel_name: str, args: Any, cc: int) -> Any: + """Fast single-kernel lookup via an args-filtered get_operators query. + + Passing concrete `args` (a cutlass RuntimeArguments) plus the device target + prunes the operator space to the ~hundreds compatible with this exact GEMM + in ~0.05s, versus ~14s to enumerate/construct the full ~294K-kernel manifest + (`get_kernel_by_name`). Used by subprocess precompile workers, which need + only the single named kernel and would otherwise each rebuild the whole + manifest. + + A miss runs one args query and indexes every operator it returns into + _ops_by_name, so the ~50ms cost is paid once per distinct operator (not once + per lookup) and is amortized across all configs and shapes a persistent + worker handles. Returns None if no operator matches the name (caller then + falls back to the full manifest). + """ + import cutlass.operators + + cached = _ops_by_name.get(kernel_name) + if cached is not None: + return cached + + ops = cutlass.operators.get_operators(args=args, target_sm=f"{cc}a") + for op in ops: + # setdefault: keep an already-cached (possibly already-compiled) object + # rather than replacing it with a fresh instance from this query. + _ops_by_name.setdefault(op.metadata.operator_name, op) + if ( + kernel_name not in _ops_by_name + and "VendoredDenseBlockScaledGemmEFC" in kernel_name + ): + from cutlass.operators.arguments import GemmArguments + + base_args = GemmArguments( + args.A, + args.B, + args.out, + accumulator_type=args.accumulator_type, + ) + scaled_ops = _scaled_candidates(base_args, cc, efc_only=False) + log.debug( + "Scaled by-name fallback found %d candidates for %s", + len(scaled_ops), + kernel_name, + ) + for op in scaled_ops: + _ops_by_name.setdefault(op.metadata.operator_name, op) + return _ops_by_name.get(kernel_name) + + +def ensure_cache_initialized() -> None: + """Ensure the kernel cache is initialized.""" + _get_kernel_cache() + + +_efc_epilogue_cache: dict[tuple[str, str, tuple], Any] = {} + + +def clear_cache() -> None: + """Clear all kernel caches.""" + global _kernel_by_name_cache, _efc_epilogue_cache + with _cache_lock: + _kernel_by_name_cache = None + _efc_epilogue_cache = {} + _partition_cache.clear() + _ops_by_name.clear() + _blockscaled_operators.cache_clear() + _blockscaled_manifest.cache_clear() + + +class _NVGEMMCacheWrapper: + def cache_clear(self) -> None: + clear_cache() + + +from torch._inductor.utils import clear_on_fresh_cache + + +clear_on_fresh_cache(_NVGEMMCacheWrapper()) + + +def _meta_epilogue_metadata(epilogue_args: Any) -> Any: + """Build the cached kernel's epilogue metadata from meta-device tensors. + + The EFC kernel is cached in ``_efc_epilogue_cache`` and reused across every + call; the real output/aux tensors are supplied per call via the runtime + ``GemmArguments.epilogue``, so the cached kernel needs only the epilogue's + shape/dtype/layout (its IR). Building it from the real ``EpilogueArguments`` + would make it retain those tensors forever -- ``EpilogueMetadata`` shares the + arguments' ``tensors`` (wrapping the output ``D`` and aux inputs) and traced + functor -- keeping the (often intermediate) output alive: a memory leak, and + it breaks CUDA graph capture (a live graph-pool allocation that is not a + tracked graph output). Re-trace the epilogue with meta tensors (carrying + dtype/layout but no device storage; the tracer reads only their metadata) so + the cached kernel holds nothing real. + """ + from cutlass.operators.arguments.epilogue import EpilogueArguments + from cutlass.operators.metadata import EpilogueMetadata + from cutlass.operators.utils.tensor import TensorWrapper + + from .nv_universal_gemm_utils import cutlass_dtype_to_torch + + def _meta_like(t: torch.Tensor) -> torch.Tensor: + return torch.empty_strided(t.shape, t.stride(), dtype=t.dtype, device="meta") + + fake_kwargs = {} + for name, val in epilogue_args.tensors.items(): + # Build a storage-free meta tensor with the same shape/stride/dtype. + # A compile-time-only TensorWrapper (the subprocess-precompile path) has + # no runtime tensor -- its `.runtime_tensor` property raises ValueError -- + # so read `_runtime_tensor` directly and fall back to the wrapper's own + # shape/stride and its CUTLASS dtype. + if isinstance(val, torch.Tensor): + fake_kwargs[name] = _meta_like(val) + elif isinstance(val, TensorWrapper) and isinstance( + val._runtime_tensor, torch.Tensor + ): + fake_kwargs[name] = _meta_like(val._runtime_tensor) + elif ( + isinstance(val, TensorWrapper) + and (dtype := cutlass_dtype_to_torch(val.dtype)) is not None + ): + fake_kwargs[name] = torch.empty_strided( + tuple(val.shape), tuple(val.stride), dtype=dtype, device="meta" + ) + else: + fake_kwargs[name] = val + fake_args = EpilogueArguments(epilogue_args.epilogue_fn, **fake_kwargs) + accum = epilogue_args.traced_epilogue.example_inputs["accum"] + fake_args.trace(accum.shape, accum.element) + return EpilogueMetadata.from_args(fake_args) + + +def get_efc_kernel_with_epilogue( + efc_kernel_name: str, + epilogue_args: Any, + epilogue_source: str = "", + base_kernel: Any | None = None, +) -> Any: + """Get (or create and cache) an EFC kernel bound to a specific epilogue. + + epilogue_source is preferred over inspect.getsource — generated functions + produce unstable source strings that can't be hashed reliably. + + base_kernel: pre-resolved base EFC kernel (e.g. from the args-filtered fast + lookup in a subprocess worker). When None, falls back to the full manifest. + """ + if not epilogue_source: + epilogue_source = str(epilogue_args) if epilogue_args is not None else "" + + cache_key = ( + efc_kernel_name, + epilogue_source, + _epilogue_args_signature(epilogue_args), + ) + + with _cache_lock: + if cache_key in _efc_epilogue_cache: + log.debug("EFC kernel with epilogue found in cache: %s", efc_kernel_name) + return _efc_epilogue_cache[cache_key] + + if base_kernel is None: + # Prefer the args-resolved operator cache (populated by choice + # generation); only build the full manifest if the name was never + # seen via args. + base_kernel = get_kernel_by_name(efc_kernel_name) + if base_kernel is None: + log.debug("Base EFC kernel not found: %s", efc_kernel_name) + return None + + from cutlass.operators.metadata import OperatorMetadata + + epilogue_metadata = _meta_epilogue_metadata(epilogue_args) + + base_metadata = base_kernel.metadata + new_metadata = OperatorMetadata( + operands=base_metadata.operands, + design=base_metadata.design, + operator_name=base_metadata.operator_name, + operator_class=base_metadata.operator_class, + supported_targets=base_metadata.supported_targets, + epilogue=epilogue_metadata, + ) + + kernel_class = base_metadata.operator_class + new_kernel = kernel_class(new_metadata) + + _efc_epilogue_cache[cache_key] = new_kernel + log.debug("Created and cached EFC kernel with epilogue: %s", efc_kernel_name) + + return new_kernel diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..eb9de1cfcf8a3765d7db4e6d9e5704bc965cdcdc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm.py @@ -0,0 +1,1075 @@ +# mypy: allow-untyped-defs +""" +NVIDIA Universal GEMM (NVGEMM) backend for PyTorch Inductor. + +This module provides integration with the cutlass.operators library to enable +high-performance GEMM kernels for NVIDIA GPUs. +""" + +import itertools +import re +from enum import auto, Enum +from typing import Any, Literal + +import torch +from torch._inductor import config +from torch._inductor.autotune_process import ( + BenchmarkRequest, + GPUDeviceBenchmarkMixin, + TensorMeta, +) +from torch._inductor.codegen.cuda.cuda_env import get_cuda_arch +from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import ( + _compile_nvgemm, + _create_gemm_arguments, + _create_gemm_cache_key, + _current_target_sm, + _get_scaled_gemm_modes, + _make_disk_config_key, + _nvgemm_bias_add_epilogue, + _rewrap_efc_compiled_obj, + _unwrap_efc_compiled_obj, +) +from torch._inductor.heuristics.template.nv_universal_gemm import get_nvgemm_heuristics +from torch._inductor.ir import ( + Buffer, + ChoiceCaller, + FixedLayout, + Layout, + PermuteView, + TensorBox, +) +from torch._inductor.kernel_inputs import MMKernelInputs +from torch._inductor.utils import ensure_nv_universal_gemm_available +from torch._inductor.virtualized import V +from torch._logging import getArtifactLogger + + +log = getArtifactLogger(__name__, "output_code") + + +class GemmVariant(Enum): + """ + Enum for different GEMM operation types supported by NVIDIA Universal GEMM. + """ + + GEMM = auto() + + GROUPED_GEMM = auto() + + SCALED_GEMM = auto() + + @property + def op_name(self) -> str: + """Return the operation name for logging and naming.""" + if self == GemmVariant.GROUPED_GEMM: + return "nv_universal_grouped_gemm" + if self == GemmVariant.SCALED_GEMM: + return "nv_universal_scaled_gemm" + return "nv_universal_gemm" + + +class NVUniversalGemmBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest): + """Benchmark request for NVIDIA Universal GEMM kernels.""" + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + kernel, # cutlass.operators.Operator object + accumulator_type: torch.dtype, + variant: GemmVariant, + workspace_size: int = 0, + scale_type_a: Any | None = None, + scale_type_b: Any | None = None, + swizzle_type_a: Any | None = None, + swizzle_type_b: Any | None = None, + swap_ab: bool = False, + has_bias_epilogue: bool = False, + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, ()) + self.kernel = kernel + self.accumulator_type = accumulator_type + self.has_bias_epilogue = has_bias_epilogue + self._workspace: torch.Tensor | None = None + self._disk_fn_cache: dict = {} + self.workspace_size = workspace_size + self.variant = variant + self.scale_type_a = scale_type_a + self.scale_type_b = scale_type_b + self.swizzle_type_a = swizzle_type_a + self.swizzle_type_b = swizzle_type_b + self.swap_ab = swap_ab + + def benchmark( + self, + *input_tensors: torch.Tensor, + out: torch.Tensor | None = None, + ) -> float: + """Benchmark the NVIDIA Universal GEMM kernel. + + Override the base class to always create tensors from input_tensor_meta. + This is necessary because input_nodes may be ReinterpretViews that share + the same underlying buffer name. The autotuning framework deduplicates + inputs by name (in AlgorithmSelectorCache.get_inputs()), resulting in + fewer tensors than expected. By always creating from input_tensor_meta, + we ensure each input gets its own tensor with the correct size/stride/offset + from the view's layout. + + """ + from torch._inductor.runtime.benchmarking import benchmarker + + input_tensors = tuple(x.to_tensor() for x in self.input_tensor_meta) + if out is None: + out = self.output_tensor_meta.to_tensor() + + fn = self.make_run_fn(*input_tensors, out=out) + try: + if self.benchmark_with_cudagraphs: + res = benchmarker.benchmark_gpu_with_cuda_graph(fn) + else: + res = self.do_bench(fn, *input_tensors, out=out) + finally: + self.cleanup_run_fn() + return res + + def make_run_fn(self, *input_tensors: torch.Tensor, out: torch.Tensor): + """Create a function to run the NVIDIA Universal GEMM kernel.""" + from cutlass.operators.artifact import CompiledArtifact + + from torch._inductor.runtime.cutedsl_cache import disk_cache_get, disk_cache_set + from torch._inductor.utils import _ensure_fp4_dtype_registered + + _ensure_fp4_dtype_registered() + + if self.has_bias_epilogue: + # Benchmark the real fused kernel (GEMM + bias-add epilogue). The + # bias is the last input; the rest are the GEMM operands. + return self._make_bias_run_fn(input_tensors, out) + + # swap_ab: transpose operands and write into a transposed view of `out` + # (zero-copy). See _nvgemm_run for the full explanation. + if self.swap_ab and len(input_tensors) >= 2: + a, b = input_tensors[0], input_tensors[1] + if len(input_tensors) >= 4: + sa, sb = input_tensors[2], input_tensors[3] + input_tensors = (b.t(), a.t(), sb, sa) + input_tensors[4:] + else: + input_tensors = (b.t(), a.t()) + input_tensors[2:] + out = out.t() + + helper_kwargs: dict[str, Any] = {} + if self.variant == GemmVariant.SCALED_GEMM: + scale_mode_a, swizzle_mode_a, scale_mode_b, swizzle_mode_b = ( + _get_scaled_gemm_modes( + self.scale_type_a, + self.swizzle_type_a, + self.scale_type_b, + self.swizzle_type_b, + ) + ) + helper_kwargs = { + "scale_mode_a": scale_mode_a, + "swizzle_mode_a": swizzle_mode_a, + "scale_mode_b": scale_mode_b, + "swizzle_mode_b": swizzle_mode_b, + } + + cache_key = _create_gemm_cache_key(input_tensors, out) + dev_idx = input_tensors[0].device.index or 0 + kernel_name = self.kernel.metadata.operator_name + disk_config_key = _make_disk_config_key( + kernel_name, + self.variant.name, + self.accumulator_type, + self.scale_type_a, + self.scale_type_b, + self.swizzle_type_a, + self.swizzle_type_b, + ) + + def disk_fallback(kernel): + compiled_fn = disk_cache_get( + self._disk_fn_cache, + kernel_name, + disk_config_key, + cache_key, + dev_idx, + ) + if compiled_fn is not None: + compiled_fn = _rewrap_efc_compiled_obj(compiled_fn, kernel) + if compiled_fn is not None: + return CompiledArtifact( + compiled_fn, kernel, _current_target_sm(dev_idx) + ) + return None + + artifact, args, kernel, was_compiled = _compile_nvgemm( + self.variant.name, + input_tensors, + out, + self.accumulator_type, + kernel_obj=self.kernel, + args_kwargs=helper_kwargs, + fallback_fn=disk_fallback, + ) + + if was_compiled: + obj = _unwrap_efc_compiled_obj(artifact.compiled_obj) + disk_cache_set( + self._disk_fn_cache, + kernel_name, + disk_config_key, + cache_key, + obj, + dev_idx, + ) + + # Allocate workspace if needed + if self.workspace_size > 0: + self._workspace = torch.empty( + self.workspace_size, device=out.device, dtype=torch.int8 + ) + else: + self._workspace = None + + workspace = self._workspace + + def run_kernel(): + stream = torch.cuda.current_stream() + kernel.run( + args, + artifact, + stream=stream, + workspace=workspace, + assume_supported_args=True, + ) + + return run_kernel + + def _make_bias_run_fn(self, input_tensors, out): + """Build a run fn for the fused GEMM + bias-add epilogue (addmm). + + Mirrors make_run_fn's disk caching but with the bias epilogue: the + unwrap/rewrap machinery serializes the EFC artifact, so subprocess + precompile (which writes the same key) hands off to the benchmark + instead of recompiling serially. + """ + from cutlass.operators.arguments import EpilogueArguments + from cutlass.operators.artifact import CompiledArtifact + + from torch._inductor.runtime.cutedsl_cache import disk_cache_get, disk_cache_set + + *gemm_tensors, bias = input_tensors + gemm_tensors = tuple(gemm_tensors) + epilogue_args = EpilogueArguments(_nvgemm_bias_add_epilogue, bias=bias, D=out) + + kernel_name = self.kernel.metadata.operator_name + cache_key = _create_gemm_cache_key( + gemm_tensors, out, has_epilogue=True, aux_tensors=(bias,) + ) + dev_idx = gemm_tensors[0].device.index or 0 + disk_config_key = _make_disk_config_key( + kernel_name, + self.variant.name, + self.accumulator_type, + self.scale_type_a, + self.scale_type_b, + self.swizzle_type_a, + self.swizzle_type_b, + ) + + def disk_fallback(kernel): + compiled_fn = disk_cache_get( + self._disk_fn_cache, kernel_name, disk_config_key, cache_key, dev_idx + ) + if compiled_fn is not None: + compiled_fn = _rewrap_efc_compiled_obj( + compiled_fn, kernel, epilogue_args=epilogue_args + ) + if compiled_fn is not None: + return CompiledArtifact( + compiled_fn, kernel, _current_target_sm(dev_idx) + ) + return None + + artifact, args, kernel, was_compiled = _compile_nvgemm( + self.variant.name, + gemm_tensors, + out, + self.accumulator_type, + kernel_name=kernel_name, + epilogue_args=epilogue_args, + epilogue_source="nvgemm_addmm_bias_v1", + fallback_fn=disk_fallback, + base_kernel=self.kernel, + ) + + if was_compiled: + disk_cache_set( + self._disk_fn_cache, + kernel_name, + disk_config_key, + cache_key, + _unwrap_efc_compiled_obj(artifact.compiled_obj), + dev_idx, + ) + + if self.workspace_size > 0: + self._workspace = torch.empty( + self.workspace_size, device=out.device, dtype=torch.int8 + ) + else: + self._workspace = None + workspace = self._workspace + + def run_kernel(): + kernel.run( + args, + artifact, + stream=torch.cuda.current_stream(), + workspace=workspace, + assume_supported_args=True, + ) + + return run_kernel + + def precompile(self): + input_tensors = tuple(x.to_tensor() for x in self.input_tensor_meta) + out = self.output_tensor_meta.to_tensor() + self.make_run_fn(*input_tensors, out=out) + self.cleanup_run_fn() + + def cleanup_run_fn(self) -> None: + self._workspace = None + + +class NVUniversalGemmCaller(ChoiceCaller): + """ + ChoiceCaller for NVIDIA Universal GEMM kernels. + + Wraps a cutlass.operators kernel and integrates with Inductor's autotuning. + """ + + index_counter = itertools.count() + + def __init__( + self, + name: str, + input_nodes: list[Buffer], + layout: Layout, + kernel, # cutlass.operators.Operator object + accumulator_type: torch.dtype, + variant: GemmVariant, + workspace_size: int = 0, + scale_type_a: Any | None = None, + scale_type_b: Any | None = None, + swizzle_type_a: Any | None = None, + swizzle_type_b: Any | None = None, + supports_epilogue_fusion: bool = False, + swap_ab: bool = False, + kernel_layout: Layout | None = None, + bias_node: Buffer | None = None, + ) -> None: + super().__init__( + name=name, + input_nodes=input_nodes, + layout=layout, + description=f"{variant.op_name} {kernel.metadata.operator_name}" + + (" swap_ab" if swap_ab else "") + + (" bias" if bias_node is not None else ""), + ) + self.kernel = kernel + self.accumulator_type = accumulator_type + self.workspace_size = workspace_size + self.variant = variant + self.scale_type_a = scale_type_a + self.scale_type_b = scale_type_b + self.swizzle_type_a = swizzle_type_a + self.swizzle_type_b = swizzle_type_b + self.supports_epilogue_fusion = supports_epilogue_fusion + self.swap_ab = swap_ab + self.bias_node = bias_node + self._kernel_layout = kernel_layout or layout + self._cached_output_node: TensorBox | None = None + + output_buffer = Buffer(name=f"{variant.op_name}_out", layout=layout) + + self.bmreq = NVUniversalGemmBenchmarkRequest( + kernel_name=name, + input_tensor_meta=TensorMeta.from_irnodes(input_nodes), + output_tensor_meta=TensorMeta.from_irnodes(output_buffer), + kernel=kernel, + accumulator_type=accumulator_type, + workspace_size=workspace_size, + variant=variant, + scale_type_a=scale_type_a, + scale_type_b=scale_type_b, + swizzle_type_a=swizzle_type_a, + swizzle_type_b=swizzle_type_b, + swap_ab=swap_ab, + has_bias_epilogue=bias_node is not None, + ) + + def __str__(self) -> str: + return f"NVUniversalGemmCaller({self.kernel.metadata.operator_name})" + + def precompile(self): + self.bmreq.precompile() + + def benchmark(self, *args, out) -> float: + self.bmreq.benchmark_with_cudagraphs = self._benchmark_with_cudagraphs + return self.bmreq.benchmark(*args, out=out) + + def output_node(self) -> TensorBox: + from torch._inductor.ir import NVUniversalGemmBuffer + + # Without memoization, each call registers a new buffer (via + # TemplateBuffer.__init__ → V.graph.register_buffer), leaking orphan + # buffers into the graph's name tables during EFC benchmarking. + # + # But a buffer registered during a benchmark sub-context can have its + # name freed when that context rolls back `V.graph.buffers` (names are + # `buf{len(buffers)}`, so a freed slot is reused). A stale cached buffer + # then collides with a fresh buffer that reused its name, corrupting + # finalize_multi_template_buffers. Drop the cache entry in that case and + # rebuild a properly-registered buffer. + if self._cached_output_node is not None: + # pyrefly: ignore [missing-attribute] + cached_name = self._cached_output_node.data.data.get_name() + if cached_name in V.graph.name_to_buffer: + return self._cached_output_node + self._cached_output_node = None + + # For swap_ab, use the original (M, N) layout so the scheduler and + # downstream IR see the expected shape. The runtime handles the + # transpose internally via a temp buffer in _nvgemm_run. + buffer = NVUniversalGemmBuffer( + layout=self.layout, + inputs=self.input_nodes, + kernel=self.kernel, + accumulator_type=self.accumulator_type, + workspace_size=self.workspace_size, + variant=self.variant, + scale_type_a=self.scale_type_a, + scale_type_b=self.scale_type_b, + swizzle_type_a=self.swizzle_type_a, + swizzle_type_b=self.swizzle_type_b, + supports_epilogue_fusion=self.supports_epilogue_fusion, + swap_ab=self.swap_ab, + bias_node=self.bias_node, + ) + if "ktc" in self.annotations: + buffer.annotations["ktc"] = self.annotations["ktc"] + + self._cached_output_node = TensorBox.create(buffer) + return self._cached_output_node + + def call_name(self) -> str: + return self.name + + def to_callable(self): + return self.bmreq.make_run_fn + + def hash_key(self) -> str: + # `select_algorithm` uses this as a precompile dedup key. Two callers + # wrapping the same physical kernel name but with different accumulator/ + # scale/swizzle types produce distinct compiled artifacts; collapsing + # them here would silently drop the second from autotuning. + return "_".join( + str(x) + for x in ( + self.variant.op_name, + self.kernel.metadata.operator_name, + self.accumulator_type, + self.scale_type_a, + self.scale_type_b, + self.swizzle_type_a, + self.swizzle_type_b, + "swap_ab" if self.swap_ab else "", + ) + ) + + def info_dict(self) -> dict[str, Any]: + info = { + "name": self.name, + "backend": self.variant.op_name, + "kernel_name": self.kernel.metadata.operator_name, + } + if self.swap_ab: + info["swap_ab"] = True + return info + + def get_make_kernel_render(self): + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import ( + NVUniversalGemmKernel, + ) + from torch._inductor.utils import Placeholder + + kernel_metadata = { + "kernel_name": self.kernel.metadata.operator_name, + "min_cc": self.kernel.designed_for_min_cc, + } + accumulator_type = self.accumulator_type + workspace_size = self.workspace_size + variant = self.variant + scale_type_a = self.scale_type_a + scale_type_b = self.scale_type_b + swizzle_type_a = self.swizzle_type_a + swizzle_type_b = self.swizzle_type_b + input_nodes = self.input_nodes + swap_ab = self.swap_ab + has_bias = self.bias_node is not None + + def make_kernel_render( + out_node, + hint_override=None, + epilogue_fn_code=None, + epilogue_reads=None, + epilogue_writes=None, + epilogue_var_renames=None, + local_reduce=None, + ): + from torch._inductor.ir import StorageBox, TensorBox + + processed_inputs = [] + for inp in input_nodes: + if isinstance(inp, TensorBox): + inp = inp.data + if isinstance(inp, StorageBox): + inp = inp.data + processed_inputs.append(inp) + + # A baked bias is the last input, consumed by the epilogue rather + # than as a GEMM operand. + bias_node = None + if has_bias: + bias_node = processed_inputs[-1] + processed_inputs = processed_inputs[:-1] + + kernel_name = str(Placeholder.KERNEL_NAME) + + render_kernel = NVUniversalGemmKernel( + kernel_name=kernel_name, + # pyrefly: ignore [bad-argument-type] + input_nodes=processed_inputs, + output_node=out_node, + kernel_metadata=kernel_metadata, + accumulator_type=accumulator_type, + workspace_size=workspace_size, + variant=variant, + scale_type_a=scale_type_a, + scale_type_b=scale_type_b, + swizzle_type_a=swizzle_type_a, + swizzle_type_b=swizzle_type_b, + epilogue_fn_code=epilogue_fn_code, + epilogue_reads=epilogue_reads, + epilogue_writes=epilogue_writes, + epilogue_var_renames=epilogue_var_renames, + local_reduce=local_reduce, + swap_ab=swap_ab, + # pyrefly: ignore [bad-argument-type] + bias_node=bias_node, + ) + + def render(): + return render_kernel.render() + + return render_kernel, render + + return make_kernel_render + + +def _create_dummy_tensor_from_layout( + layout: Layout, dtype_override: torch.dtype | None = None +) -> torch.Tensor | None: + """ + Create a FakeTensor from a Layout for kernel filtering. + + Uses Layout.get_example() which creates FakeTensors within V.fake_mode, + avoiding real CUDA memory allocation. cutlass.operators only needs shape/stride/dtype + metadata for its supports() checks. + """ + try: + result = layout.get_example() + if dtype_override is not None and result.dtype != dtype_override: + result = result.view(dtype_override) + return result + except Exception: + # Broad: layout.get_example()/torch.empty_strided under fake mode can + # raise a variety of unexpected errors (TypeError, AssertionError, etc.) + # depending on stride/symint state. Failing to materialize a dummy + # should never abort autotune — just skip this candidate. + return None + + +_TILE_RE = re.compile(r"tile(\d+)x\d+x\d+") + + +def _include_efc_kernels_only(metadata) -> bool: + """Filter to include only EFC (Epilogue Fusion Compatible) kernels. + + Excludes tile_M=64 EFC kernels: cutlass.operators has a broadcast bug in the + epilogue thread operation for aux-tensor inputs with tile_M=64, and we + don't yet know at autotune time whether fusion will consume aux tensors. + Non-EFC kernels still cover tile_M=64, so plain GEMM autotune is unaffected. + + Strictly requires the kernel name to encode tile dims; if cutlass.operators ever + changes the naming scheme, this raises rather than silently letting the + broken tile_M=64 kernels through. + """ + if "EFC" not in metadata.operator_class.__name__: + return False + match = _TILE_RE.search(metadata.operator_name) + if match is None: + raise RuntimeError( + f"NVGEMM EFC kernel name does not match expected tile pattern " + f"'tileMxNxK': {metadata.operator_name}. The tile_M=64 broadcast " + f"workaround in _include_efc_kernels_only depends on this naming " + f"convention; update the regex or move to metadata-based filtering." + ) + return int(match.group(1)) >= 128 + + +def _exclude_efc_kernels(metadata) -> bool: + """Filter to exclude EFC kernels (for non-epilogue cases).""" + return "EFC" not in metadata.operator_class.__name__ + + +def _add_nv_gemm_choices_impl( + choices: list[ChoiceCaller], + layout: Layout, + input_nodes: list[Buffer], + variant: GemmVariant, + accumulator_type: torch.dtype, + mm_inputs: MMKernelInputs | None = None, + scale_type_a: Any | None = None, + scale_type_b: Any | None = None, + swizzle_type_a: Any | None = None, + swizzle_type_b: Any | None = None, + swap_ab: bool = False, + kernel_layout: Layout | None = None, + bias_node: Buffer | None = None, +) -> None: + """ + Unified implementation for adding NVIDIA Universal GEMM choices. + + Args: + choices: List to append ChoiceCaller objects to + layout: Output layout + input_nodes: GEMM operand nodes (A, B) + variant: The GEMM variant (determines behavior) + accumulator_type: Accumulator dtype + mm_inputs: Optional MMKernelInputs for heuristics + scale_type_a: ScalingType for A (required for SCALED_GEMM) + scale_type_b: ScalingType for B (required for SCALED_GEMM) + swizzle_type_a: SwizzleType for A (required for SCALED_GEMM) + swizzle_type_b: SwizzleType for B (required for SCALED_GEMM) + bias_node: Optional addmm bias, consumed as a fixed bias-add epilogue. + Requires EFC kernels; only these are considered when set. + """ + from torch._inductor.utils import _ensure_fp4_dtype_registered + + _ensure_fp4_dtype_registered() + + from torch._inductor.codegen.nv_universal_gemm.kernel_cache import ( + partition_compatible_kernels, + ) + + # Create dummy tensors for cutlass.operators's supports() checks. + # Pass node dtype to handle FP4 ReinterpretView (uint8 storage viewed as float4_e2m1fn_x2). + dummy_tensors = [ + _create_dummy_tensor_from_layout( + node.get_layout(), dtype_override=node.get_dtype() + ) + for node in input_nodes + ] + + if swap_ab and len(dummy_tensors) >= 2: + # swap_ab: transpose mat_a/mat_b dummies (and swap scales when scaled). + # Original: dummy[0]=mat_a(M,K) row, dummy[1]=mat_b(K,N) col + # Swap: new_A=mat_b.t()=(N,K) row, new_B=mat_a.t()=(K,M) col + d_a, d_b = dummy_tensors[0], dummy_tensors[1] + if d_a is not None and d_b is not None: + if len(dummy_tensors) >= 4: + # scaled: new_scale_a=scale_b, new_scale_b=scale_a + d_sa, d_sb = dummy_tensors[2], dummy_tensors[3] + dummy_tensors = [d_b.t(), d_a.t(), d_sb, d_sa] + dummy_tensors[4:] + else: + dummy_tensors = [d_b.t(), d_a.t()] + dummy_tensors[2:] + + effective_layout = kernel_layout if kernel_layout is not None else layout + out_tensor = _create_dummy_tensor_from_layout(effective_layout) + + if any(t is None for t in dummy_tensors) or out_tensor is None: + log.debug("Failed to create dummy tensors for %s", variant.op_name) + return + + helper_kwargs: dict[str, Any] = {} + if variant == GemmVariant.SCALED_GEMM: + try: + scale_mode_a, swizzle_mode_a, scale_mode_b, swizzle_mode_b = ( + _get_scaled_gemm_modes( + scale_type_a, + swizzle_type_a, + scale_type_b, + swizzle_type_b, + ) + ) + except NotImplementedError: + return + helper_kwargs = { + "scale_mode_a": scale_mode_a, + "swizzle_mode_a": swizzle_mode_a, + "scale_mode_b": scale_mode_b, + "swizzle_mode_b": swizzle_mode_b, + } + + args = _create_gemm_arguments( + variant.name, + tuple(dummy_tensors), + out_tensor, + accumulator_type, + **helper_kwargs, + ) + + cc = get_cuda_arch() + if cc is None: + log.debug("Failed to get CUDA arch") + return + cc_int = int(cc) + + # Single-pass partition over the ~390K-entry kernel cache. The two-pass + # form below called `kernel.supports(args)` once per bucket -- i.e. twice + # per non-EFC-class kernel -- across the full cache. + def _classify(metadata) -> int: + if _include_efc_kernels_only(metadata): + return 1 # efc bucket (with tile_M >= 128) + if _exclude_efc_kernels(metadata): + return 0 # non-efc bucket + # NOTE: tile_M < 128 EFC kernels are dropped due to a cutlass.operators + # broadcast bug. Tracking: https://github.com/pytorch/pytorch/issues/181901 + return -1 + + # A baked bias-add requires an epilogue-fusion-capable (EFC) kernel, so + # scan only EFC kernels -- skips supports() on the far larger non-EFC set. + # The args-filtered fast query is complete only for dense GEMM; scaled uses + # direct block-scaled sub-provider enumeration (get_operators under-generates + # operands from scaled args); anything else falls back to the full manifest. + candidate_source: Literal["args", "scaled", "manifest"] + if variant == GemmVariant.GEMM: + candidate_source = "args" + elif variant == GemmVariant.SCALED_GEMM: + candidate_source = "scaled" + else: + candidate_source = "manifest" + non_efc_kernels, efc_kernels = partition_compatible_kernels( + args, + cc_int, + _classify, + num_buckets=2, + efc_only=bias_node is not None, + candidate_source=candidate_source, + classifier_key="nvgemm_efc_partition_v1", + ) + if not config.epilogue_fusion or swap_ab: + efc_kernels = [] + if bias_node is not None: + non_efc_kernels = [] + if not non_efc_kernels and not efc_kernels: + log.debug("No compatible %s kernels found", variant.op_name) + return + + max_configs = config.nvgemm_max_profiling_configs or max( + len(non_efc_kernels), len(efc_kernels) + ) + if variant in (GemmVariant.GEMM, GemmVariant.SCALED_GEMM) and mm_inputs is not None: + heuristics = get_nvgemm_heuristics() + non_efc_kernels = heuristics.filter_kernels( + non_efc_kernels, mm_inputs, max_configs, accumulator_type + ) + efc_kernels = heuristics.filter_kernels( + efc_kernels, mm_inputs, max_configs, accumulator_type + ) + else: + # TODO(nikhilap): Enable heuristics for grouped GEMM + # when nvMatmulHeuristics adds support + non_efc_kernels = non_efc_kernels[:max_configs] + efc_kernels = efc_kernels[:max_configs] + + all_kernels = [(kernel, False) for kernel in non_efc_kernels] + [ + (kernel, True) for kernel in efc_kernels + ] + + # When a bias is baked in, it is appended as the last caller input so the + # scheduler tracks it as a read; the caller/kernel split it back off. + caller_input_nodes = ( + [*input_nodes, bias_node] if bias_node is not None else input_nodes + ) + + num_added = 0 + for kernel, supports_epilogue_fusion in all_kernels: + name = f"{variant.op_name}_{next(NVUniversalGemmCaller.index_counter)}" + workspace_size = kernel.get_workspace_size(args).size_bytes + try: + caller = NVUniversalGemmCaller( + name=name, + input_nodes=caller_input_nodes, + layout=layout, + kernel=kernel, + accumulator_type=accumulator_type, + workspace_size=workspace_size, + variant=variant, + scale_type_a=scale_type_a, + scale_type_b=scale_type_b, + swizzle_type_a=swizzle_type_a, + swizzle_type_b=swizzle_type_b, + supports_epilogue_fusion=supports_epilogue_fusion, + swap_ab=swap_ab, + kernel_layout=kernel_layout, + bias_node=bias_node, + ) + choices.append(caller) + num_added += 1 + except Exception: + # Broad: caller construction touches cutlass.operators / fake-mode tensors + # which can raise types other than RuntimeError/ValueError. A single + # bad choice should never abort the rest of autotune choice population. + log.debug("Failed to create %s choice", variant.op_name, exc_info=True) + + log.debug("Added %d %s choices", num_added, variant.op_name) + + +def add_nv_universal_gemm_choices( + choices: list[ChoiceCaller], + layout: Layout, + inputs: MMKernelInputs, + accumulator_type: torch.dtype | None = None, +) -> None: + """ + Add NVIDIA Universal GEMM kernels to the autotune choices. + + Thin wrapper around _add_nv_gemm_choices_impl for regular GEMM. + """ + if not ensure_nv_universal_gemm_available(): + log.debug( + "cutlass.operators not available, skipping NVIDIA Universal GEMM choices" + ) + return + + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=inputs.nodes(), + variant=GemmVariant.GEMM, + accumulator_type=accumulator_type or torch.float32, + mm_inputs=inputs, + ) + + # swap_ab: swap A/B so the large N goes on the M-axis, improving tile + # utilization for small-M / tall-skinny shapes (M << N). The kernel computes + # (N, M) and the runtime writes it into a transposed view of the (M, N) + # output. Mirrors the scaled path (see add_nv_universal_scaled_gemm_choices) + # but without scale operands. Only valid for 2D mm: this entry point also + # serves BMM (layout [B, M, N]), where the (M, N) / 2D-PermuteView swap logic + # would be wrong, so skip it there. + if not config.nvgemm_swap_ab or len(layout.size) != 2: + return + m, n = layout.size[0], layout.size[1] + swap_kernel_layout = FixedLayout(layout.device, layout.dtype, [n, m]) + # Rank swap configs with the heuristic on the SWAPPED (N, M, K) problem: + # new mat1 = mat_b.t() (N, K) row, new mat2 = mat_a.t() (K, M) col. Without + # this, the swap variant would fall back to an unranked prefix and miss the + # small-tile configs that make swap_ab win. + mat_a, mat_b = inputs.mat1mat2() + swap_inputs = MMKernelInputs( + [PermuteView.create(mat_b, [1, 0]), PermuteView.create(mat_a, [1, 0])] + ) + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=inputs.nodes(), + variant=GemmVariant.GEMM, + accumulator_type=accumulator_type or torch.float32, + mm_inputs=swap_inputs, + swap_ab=True, + kernel_layout=swap_kernel_layout, + ) + + +def add_nv_universal_addmm_choices( + choices: list[ChoiceCaller], + layout: Layout, + inputs: MMKernelInputs, + bias_node: Buffer, + alpha: float | int = 1, + beta: float | int = 1, + accumulator_type: torch.dtype | None = None, +) -> None: + """Add NVGEMM addmm choices: ``bias + mat1 @ mat2`` via an EFC bias-add + epilogue. + + Only the plain ``alpha == beta == 1`` case is handled; other scalings fall + back to the remaining backends. ``bias_node`` should be the original + (un-expanded) bias so a 1D row vector routes to the row-broadcast epilogue + impl -- passing the (M, N) broadcast *view* is rejected by cutlass.operators. + """ + if not ensure_nv_universal_gemm_available(): + return + # Bias-add requires an epilogue-fusion-capable (EFC) kernel. + if not config.epilogue_fusion: + return + if alpha != 1 or beta != 1: + return + + # Only broadcastable row-vector or full biases are supported. The bias last + # dim must match N; higher-rank or column-only biases are left to fallbacks. + n = layout.size[-1] + bias_size = bias_node.get_size() + # Only rank-1 (row vector) or rank-2 (full) biases are supported. The + # epilogue indexes bias_size[-1], so a rank-0 scalar bias would IndexError; + # reject it (and higher-rank biases) so they fall through to other backends. + if not 1 <= len(bias_size) <= 2: + return + if not V.graph.sizevars.statically_known_equals(bias_size[-1], n): + return + + mat1, mat2 = inputs.mat1mat2() + gemm_inputs = MMKernelInputs([mat1, mat2]) + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=[mat1, mat2], + variant=GemmVariant.GEMM, + accumulator_type=accumulator_type or torch.float32, + mm_inputs=gemm_inputs, + bias_node=bias_node, + ) + + +def add_nv_universal_grouped_gemm_choices( + choices: list[ChoiceCaller], + layout: Layout, + input_nodes: list[Buffer], + accumulator_type: torch.dtype | None = None, +) -> None: + """ + Add NVIDIA Universal Grouped GEMM kernels to the autotune choices. + + Thin wrapper around _add_nv_gemm_choices_impl for grouped GEMM. + + For grouped GEMM (contiguous offset variant): + - A is (TotalM, K) with problems stacked along M + - B is (G, K, N) where B[i] is the weight for problem i + - offsets is (G,) marking where each problem ends in A + - Output is (TotalM, N) + """ + if not ensure_nv_universal_gemm_available(): + log.debug( + "cutlass.operators not available, skipping NVIDIA Universal Grouped GEMM choices" + ) + return + + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=input_nodes, + variant=GemmVariant.GROUPED_GEMM, + accumulator_type=accumulator_type or torch.float32, + ) + + +def add_nv_universal_scaled_gemm_choices( + choices: list[ChoiceCaller], + layout: Layout, + input_nodes: list[Buffer], + accumulator_type: torch.dtype | None = None, + kernel_inputs: MMKernelInputs | None = None, +) -> None: + """ + Add NVIDIA Universal Scaled GEMM (FP8) kernels to the autotune choices. + + The scaling type is inferred from the input shapes/dtypes. + If the scaling mode is unsupported by NVGEMM, this function returns without + adding any choices. + """ + if not ensure_nv_universal_gemm_available(): + return + + from torch._inductor.utils import infer_scale_swizzle_ir + + if len(input_nodes) < 4: + return + + mat_a, mat_b, scale_a, scale_b = input_nodes[:4] + + scale_type_a, swizzle_type_a = infer_scale_swizzle_ir(mat_a, scale_a) + scale_type_b, swizzle_type_b = infer_scale_swizzle_ir( + mat_b, scale_b, transpose=True + ) + + if scale_type_a is None or scale_type_b is None: + return + + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=input_nodes, + variant=GemmVariant.SCALED_GEMM, + accumulator_type=accumulator_type or torch.float32, + mm_inputs=kernel_inputs, + scale_type_a=scale_type_a, + scale_type_b=scale_type_b, + swizzle_type_a=swizzle_type_a, + swizzle_type_b=swizzle_type_b, + ) + + # swap_ab: see add_nv_universal_gemm_choices for the rationale (swap A/B so + # the large N lands on the well-tiled M-axis for small-M shapes). + if not config.nvgemm_swap_ab: + return + + # In the IR, mat_a=(M, K/2) row-major, mat_b=(K/2, N) column-major (already .t()). + # swap_ab computes: un_transpose(mat_b) @ transpose(mat_a) = (N,K/2)@(K/2,M) = (N,M). + # Scales: new A uses scale_b (weight scale), new B uses scale_a (activation scale). + # The un-transposed mat_b is (N, K/2) row-major — same as the original weight. + # The transposed mat_a is (K/2, M) column-major. + # Both have the same layout pattern as the original (row-major A, column-major B). + + # Scale inference: new A is the original weight (N, K/2), no transpose. + # For infer_scale_swizzle_ir, we need to pass the un-transposed shape. + # mat_b.t() gives (N, K/2) — but we use transpose=True on mat_b itself + # since mat_b is (K/2, N), so transpose=True flips it to (N, K/2). + swap_scale_type_a, swap_swizzle_type_a = infer_scale_swizzle_ir( + mat_b, scale_b, transpose=True + ) + # New B is the original activation (M, K/2), used transposed as (K/2, M). + # infer_scale_swizzle_ir with transpose=True on mat_a flips (M, K/2) to (K/2, M). + swap_scale_type_b, swap_swizzle_type_b = infer_scale_swizzle_ir( + mat_a, scale_a, transpose=True + ) + + if swap_scale_type_a is None or swap_scale_type_b is None: + return + + # Kernel output shape is (N, M) — the transpose of the original (M, N) + m, n = layout.size[0], layout.size[1] + swap_kernel_layout = FixedLayout(layout.device, layout.dtype, [n, m]) + + # Skip heuristic filtering for swap_ab: mm_inputs has original (M, N, K) but + # the swapped kernel sees (N, M, K). Let the benchmark pick the best kernel. + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=input_nodes, + variant=GemmVariant.SCALED_GEMM, + accumulator_type=accumulator_type or torch.float32, + mm_inputs=None, + scale_type_a=swap_scale_type_a, + scale_type_b=swap_scale_type_b, + swizzle_type_a=swap_swizzle_type_a, + swizzle_type_b=swap_swizzle_type_b, + swap_ab=True, + kernel_layout=swap_kernel_layout, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..345469e60e20704019774e6e730362eb34ca6fd9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_kernel.py @@ -0,0 +1,1475 @@ +# mypy: allow-untyped-defs +""" +NVIDIA Universal GEMM kernel code generation. + +This module generates Python code that calls cutlass.operators to execute GEMM operations. +The runtime helpers (_nvgemm_run, _nvgemm_precompile, etc.) are imported by the +generated wrapper at runtime, keeping the generated code thin. +""" + +from __future__ import annotations + +import hashlib +import importlib +import logging +import re +import threading +from typing import Any, TYPE_CHECKING + +from torch._inductor.codegen.common import ( + IndentedBuffer, + Kernel, + WorkspaceArg, + WorkspaceZeroMode, +) +from torch._inductor.codegen.cutedsl.cutedsl_op_overrides import CuteDSLOpOverrides +from torch._inductor.codegen.cutlass.python_evt import _ACCUMULATOR_ARG_NAME +from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_utils import ( + to_cutlass_scale_mode, +) +from torch._inductor.ir import ( + BaseView, + Buffer, + ExternKernel, + MutableBox, + ReinterpretView, +) +from torch._inductor.virtualized import V + + +if TYPE_CHECKING: + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm import GemmVariant + from torch._inductor.kernel.gemm_epilogue import GemmReductionPlan + + +log = logging.getLogger(__name__) + + +def _current_target_sm(dev_idx: int): + """TargetSm for the current CUDA device, used to stamp disk-cached artifacts.""" + from cutlass.operators.arch import TargetSm + + import torch + + cc = torch.cuda.get_device_capability(dev_idx) + return TargetSm(cc=cc[0] * 10 + cc[1]) + + +def _make_disk_config_key( + kernel_name: str, + variant_name: str, + accumulator_type: Any, + scale_type_a: Any | None = None, + scale_type_b: Any | None = None, + swizzle_type_a: Any | None = None, + swizzle_type_b: Any | None = None, +) -> tuple: + return ( + kernel_name, + variant_name, + str(accumulator_type), + str(scale_type_a), + str(scale_type_b), + str(swizzle_type_a), + str(swizzle_type_b), + ) + + +def _compile_nvgemm( + variant_name, + input_tensors, + out, + accumulator_type, + *, + kernel_obj=None, + kernel_name: str | None = None, + args_kwargs=None, + epilogue_args=None, + epilogue_source="", + fallback_fn=None, + cc: int | None = None, + base_kernel=None, +): + """Compile an NVGEMM artifact, trying a fallback (disk cache) first. + + Thread safety is handled at the dispatch layer: autotuning precompile + runs in subprocess workers (process-isolated), runtime is + single-threaded per graph execution. + + kernel_obj: pre-resolved kernel (skips _lookup_gemm_kernel). + kernel_name: kernel name for _lookup_gemm_kernel. + base_kernel: pre-reconstructed operator (from metadata passed by the main + process); lets _lookup_gemm_kernel skip operator discovery entirely. + args_kwargs: extra kwargs forwarded to _create_gemm_arguments. + fallback_fn: callable(kernel) -> artifact | None, called before + compiling (for disk cache lookup). + + Returns (artifact, args, kernel, was_compiled). + """ + was_compiled = False + + args = _create_gemm_arguments( + variant_name, + input_tensors, + out, + accumulator_type, + epilogue=epilogue_args, + **(args_kwargs or {}), + ) + if kernel_obj is not None: + kernel = kernel_obj + else: + kernel = _lookup_gemm_kernel( + kernel_name, # pyrefly: ignore[bad-argument-type] + epilogue_args=epilogue_args, + epilogue_source=epilogue_source, + args=args if cc is not None else None, + cc=cc, + base_kernel=base_kernel, + ) + + artifact = None + if fallback_fn is not None: + artifact = fallback_fn(kernel) + if artifact is None: + artifact = kernel.compile(args) + was_compiled = True + + return artifact, args, kernel, was_compiled + + +class CUDAContextMetadata: + """CUDA device metadata that subprocess workers can't query on their own. + + Subprocess compile workers don't have CUDA initialized (and can't due to + fork restrictions). This bundles the values the main process must provide. + """ + + __slots__ = ("max_active_clusters", "device_capability") + + def __init__( + self, + max_active_clusters: int | None, + device_capability: tuple[int, int], + ): + self.max_active_clusters = max_active_clusters + self.device_capability = device_capability + + @staticmethod + def from_kernel(kernel, device) -> CUDAContextMetadata: + """Build from a cutlass.operators Kernel and torch device in the main process.""" + import torch + + mac = None + try: + cluster_shape = getattr( + getattr(kernel, "impl", None), "cluster_shape_mn", None + ) + if cluster_shape is not None: + from cutlass.operators.providers.cutedsl.integration_utils.mma import ( + get_max_active_clusters, + ) + + mac = get_max_active_clusters(cluster_shape) + except Exception: + log.warning("Failed to query max_active_clusters", exc_info=True) + cc = torch.cuda.get_device_capability(device) + return CUDAContextMetadata(mac, cc) + + +def _patch_max_active_clusters(max_active_clusters): + """Patch get_max_active_clusters in all CuTeDSL modules. + + Returns a list of (module, original_fn) pairs for restoration. + Subprocess workers don't have CUDA initialized, so they can't query + the driver; this patches in the pre-computed value from the main process. + """ + patched = [] + + def mac_fn(*a, **kw): + return max_active_clusters + + for mod_name in _MAX_ACTIVE_CLUSTERS_MODULES: + try: + m = importlib.import_module(mod_name) + except ImportError: + continue + if hasattr(m, "get_max_active_clusters"): + patched.append((m, m.get_max_active_clusters)) + m.get_max_active_clusters = mac_fn # pyrefly: ignore [missing-attribute] + return patched + + +def _restore_max_active_clusters(patched): + """Undo _patch_max_active_clusters.""" + for m, orig in patched: + m.get_max_active_clusters = orig # pyrefly: ignore [missing-attribute] + + +def _worker_nvgemm_autotuning_precompile( + kernel_name, + variant_name, + accumulator_type, + input_tensor_meta, + output_tensor_meta, + extra_env, + cuda_ctx, + scale_type_a=None, + scale_type_b=None, + swizzle_type_a=None, + swizzle_type_b=None, + has_bias_epilogue=False, + swap_ab=False, + metadata=None, +): + """Subprocess worker: compile one NVGEMM kernel and save to disk cache. + + Called from AsyncCompile.nvgemm_precompile() in a subprocess worker + so CuTeDSL compilation is process-isolated (no thread-safety issues). + Returns (None, elapsed_us) for compatibility with the precompile callback. + """ + import time + + # Share the persistent-worker env/cache handling used by PyCodeCache workers. + from torch._inductor.runtime.compile_tasks import ( + _apply_subprocess_env_and_clear_caches, + ) + + _apply_subprocess_env_and_clear_caches(extra_env) + + start_ns = time.time_ns() + + import torch + from torch._inductor.runtime.cutedsl_cache import disk_cache_set + from torch._inductor.utils import _ensure_fp4_dtype_registered + from torch._subclasses.fake_tensor import FakeTensorMode + + _ensure_fp4_dtype_registered() + + with FakeTensorMode(): + input_tensors = tuple( + torch.empty_strided(m.sizes, m.strides, device=m.device, dtype=m.dtype) + for m in input_tensor_meta + ) + out = torch.empty_strided( + output_tensor_meta.sizes, + output_tensor_meta.strides, + device=output_tensor_meta.device, + dtype=output_tensor_meta.dtype, + ) + + # swap_ab: the kernel was selected for the transposed (N, M) problem, so the + # worker must swap operands here too -- both to resolve the kernel via the + # args-filtered fast lookup and to key the disk cache the same way the + # benchmark's make_run_fn does (it swaps before compiling). Mirrors the + # runtime swap in _nvgemm_run. swap_ab and a bias epilogue never co-occur. + if swap_ab and len(input_tensors) >= 2: + a, b = input_tensors[0], input_tensors[1] + if len(input_tensors) >= 4: + sa, sb = input_tensors[2], input_tensors[3] + input_tensors = (b.t(), a.t(), sb, sa) + input_tensors[4:] + else: + input_tensors = (b.t(), a.t()) + input_tensors[2:] + out = out.t() + + helper_kwargs: dict[str, Any] = {} + if variant_name == "SCALED_GEMM": + scale_mode_a, swizzle_mode_a, scale_mode_b, swizzle_mode_b = ( + _get_scaled_gemm_modes( + scale_type_a, swizzle_type_a, scale_type_b, swizzle_type_b + ) + ) + helper_kwargs = { + "scale_mode_a": scale_mode_a, + "swizzle_mode_a": swizzle_mode_a, + "scale_mode_b": scale_mode_b, + "swizzle_mode_b": swizzle_mode_b, + } + + # For an addmm bias choice the last input is the bias, consumed by a + # bias-add epilogue; the rest are the GEMM operands. Building the epilogue + # (and keying the cache with it) here lets the parallel precompile hand off + # to the benchmark, which reads the same key. + epilogue_args = None + epilogue_source = "" + aux_tensors: tuple = () + if has_bias_epilogue: + from cutlass.operators.arguments import EpilogueArguments + + *gemm_list, bias = input_tensors + input_tensors = tuple(gemm_list) + epilogue_args = EpilogueArguments(_nvgemm_bias_add_epilogue, bias=bias, D=out) + epilogue_source = "nvgemm_addmm_bias_v1" + aux_tensors = (bias,) + + cache_key = _create_gemm_cache_key( + input_tensors, out, has_epilogue=has_bias_epilogue, aux_tensors=aux_tensors + ) + dev_idx = input_tensors[0].device.index or 0 + disk_config_key = _make_disk_config_key( + kernel_name, + variant_name, + accumulator_type, + scale_type_a, + scale_type_b, + swizzle_type_a, + swizzle_type_b, + ) + disk_fn_cache: dict = {} + + # cc for the args-filtered fast kernel lookup: workers can't query the CUDA + # driver, so use the bundled device capability instead of rebuilding the + # full ~294K-kernel manifest just to resolve one kernel by name. + major, minor = cuda_ctx.device_capability + worker_cc = major * 10 + minor + + patched = _patch_max_active_clusters(cuda_ctx.max_active_clusters) + try: + # Best path: the main process passed the chosen operator's metadata, so + # reconstruct exactly that one operator (~us) instead of enumerating the + # operator space. Done inside the patched region since construction may + # query max_active_clusters, which the worker can't get from the driver. + base_kernel = None + if metadata is not None: + try: + base_kernel = metadata.operator_class(metadata) + except Exception: + log.warning( + "Failed to reconstruct NVGEMM operator %s from metadata; " + "falling back to argument-based lookup", + kernel_name, + exc_info=True, + ) + + artifact, _, _, was_compiled = _compile_nvgemm( + variant_name, + input_tensors, + out, + accumulator_type, + kernel_name=kernel_name, + args_kwargs=helper_kwargs, + epilogue_args=epilogue_args, + epilogue_source=epilogue_source, + cc=worker_cc, + base_kernel=base_kernel, + ) + + if was_compiled: + obj = _unwrap_efc_compiled_obj(artifact.compiled_obj) + disk_cache_set( + disk_fn_cache, + kernel_name, + disk_config_key, + cache_key, + obj, + dev_idx, + device_capability=cuda_ctx.device_capability, + ) + finally: + _restore_max_active_clusters(patched) + + elapsed_us = (time.time_ns() - start_ns) // 1000 + return None, elapsed_us + + +# ── Runtime helpers (imported by generated wrapper code at runtime) ─────────── + + +def _get_scaled_gemm_modes( + scale_type_a: Any | None, + swizzle_type_a: Any | None, + scale_type_b: Any | None, + swizzle_type_b: Any | None, +) -> tuple[Any, Any, Any, Any]: + scale_mode_a, swizzle_mode_a = to_cutlass_scale_mode(scale_type_a, swizzle_type_a) + scale_mode_b, swizzle_mode_b = to_cutlass_scale_mode(scale_type_b, swizzle_type_b) + if any( + mode is None + for mode in (scale_mode_a, swizzle_mode_a, scale_mode_b, swizzle_mode_b) + ): + raise NotImplementedError("Unsupported scale/swizzle mode for scaled GEMM") + return scale_mode_a, swizzle_mode_a, scale_mode_b, swizzle_mode_b + + +def _create_gemm_arguments( + variant_name: str, + input_tensors, + out, + accumulator_type: Any, + *, + scale_mode_a: Any | None = None, + swizzle_mode_a: Any | None = None, + scale_mode_b: Any | None = None, + swizzle_mode_b: Any | None = None, + epilogue: Any | None = None, + local_reduce_out: Any | None = None, + local_reduce_group: int = 0, + local_reduce_axis: int = 1, + local_reduce_type: str = "sum", + local_reduce_source: str = "identity", + local_reduce_feeds_main: bool = False, +): + import cutlass.operators + + has_local_reduce = local_reduce_out is not None or local_reduce_feeds_main + if has_local_reduce and variant_name != "SCALED_GEMM": + raise NotImplementedError( + "NVGEMM local reductions currently require scaled GEMM" + ) + if has_local_reduce and ( + local_reduce_axis not in (0, 1) or local_reduce_group <= 1 + ): + raise NotImplementedError( + "NVGEMM local reductions require an M- or N-axis group greater than 1" + ) + + def with_local_reduce(args): + if not has_local_reduce: + return args + from cutlass.operators.utils.tensor import TensorWrapper + + args.local_reduce_out = ( + TensorWrapper(local_reduce_out) if local_reduce_out is not None else None + ) + args.local_reduce_group = local_reduce_group + args.local_reduce_axis = local_reduce_axis + args.local_reduce_type = local_reduce_type + args.local_reduce_source = local_reduce_source + args.local_reduce_feeds_main = local_reduce_feeds_main + return args + + if epilogue is not None and variant_name == "GROUPED_GEMM": + raise NotImplementedError( + "Epilogue fusion is not yet supported for grouped GEMM" + ) + + match variant_name: + case "GROUPED_GEMM": + a, b, offsets = input_tensors + return cutlass.operators.arguments.GroupedGemmArguments( + a, + b, + out, + accumulator_type=accumulator_type, + offsets=offsets, + ) + + case "SCALED_GEMM": + from cutlass.operators.arguments import ScaledOperand + + a, b, scale_a, scale_b = input_tensors + scaled_a = ScaledOperand(a, scale_a, scale_mode_a, swizzle_mode_a) + scaled_b = ScaledOperand(b, scale_b, scale_mode_b, swizzle_mode_b) + kwargs: dict[str, Any] = {"accumulator_type": accumulator_type} + if epilogue is not None: + kwargs["epilogue"] = epilogue + return with_local_reduce( + cutlass.operators.arguments.GemmArguments( + scaled_a, + scaled_b, + out, + **kwargs, + ) + ) + + case "GEMM": + a, b = input_tensors + kwargs: dict[str, Any] = {"accumulator_type": accumulator_type} + if epilogue is not None: + kwargs["epilogue"] = epilogue + return with_local_reduce( + cutlass.operators.arguments.GemmArguments(a, b, out, **kwargs) + ) + + case _: + raise NotImplementedError(f"Unsupported NVGEMM variant: {variant_name}") + + +def _lookup_gemm_kernel( + kernel_name: str, + *, + epilogue_args: Any | None = None, + epilogue_source: str = "", + args: Any | None = None, + cc: int | None = None, + base_kernel: Any | None = None, +): + from torch._inductor.codegen.nv_universal_gemm.kernel_cache import ( + get_efc_kernel_with_epilogue, + get_kernel_by_name, + get_kernel_by_name_via_args, + ) + + # Best path (subprocess precompile): the caller reconstructed the exact + # operator from metadata passed by the main process (operator_class(metadata), + # ~us), so we skip operator discovery entirely -- no args-filtered query and + # no full manifest. + # Fast path (base_kernel absent): resolve the single named kernel via an + # args-filtered query (~0.05s) instead of building the full manifest (~14s). + fast = args is not None and cc is not None + + if epilogue_args is None: + kernel = base_kernel + # Fast path can miss when the named kernel doesn't support these exact + # args (e.g. a swap_ab kernel selected for the transposed problem while + # the worker holds the original operands); fall back to the manifest. + if kernel is None and fast: + kernel = get_kernel_by_name_via_args(kernel_name, args, cc) + if kernel is None: + kernel = get_kernel_by_name(kernel_name) + if kernel is None: + raise RuntimeError(f"Could not find kernel: {kernel_name}") + return kernel + + if base_kernel is None and fast: + base_kernel = get_kernel_by_name_via_args(kernel_name, args, cc) + kernel = get_efc_kernel_with_epilogue( + kernel_name, + epilogue_args, + epilogue_source=epilogue_source, + base_kernel=base_kernel, + ) + if kernel is None: + raise RuntimeError(f"Could not find EFC kernel: {kernel_name}") + return kernel + + +def _tensor_sig(t): + return (t.shape, t.stride(), t.dtype) + + +def _create_gemm_cache_key( + input_tensors, + out, + *, + has_epilogue: bool = False, + aux_tensors: tuple = (), + epilogue_specialization: tuple = (), +): + cache_key = tuple(s for t in input_tensors for s in _tensor_sig(t)) + cache_key = (*cache_key, *_tensor_sig(out)) + + if has_epilogue: + aux_sig = tuple(_tensor_sig(t) for t in aux_tensors) + return (*cache_key, "epilogue", aux_sig, epilogue_specialization) + return cache_key + + +def _unwrap_efc_compiled_obj(compiled_obj): + """Extract the inner JIT function from an EFC closure for disk serialization.""" + if hasattr(compiled_obj, "__closure__") and compiled_obj.__closure__: + inner = compiled_obj.__closure__[0].cell_contents + if hasattr(inner, "export_to_c"): + return inner + return compiled_obj + + +def _init_efc_jit(kernel, epilogue_args): + """Lightweight EFC JIT init from epilogue args, without a full kernel.compile(). + + EFC.compile() calls analyze_epilogue_with_arguments() then creates the JIT + object. We replicate just those two steps so that disk-cached artifacts can + be rewrapped without recompiling the CuTe DSL kernel. + """ + from cutlass.operators.providers.cutedsl.evt.common_efc import EFC + from cutlass.operators.utils.tensor import TensorWrapper + + efc = kernel.impl.efc + params = [ + e.compile_time_tensor if isinstance(e, TensorWrapper) else e + for e in epilogue_args.parameters + ] + efc.analyze_epilogue_with_arguments(params) + efc.jit = EFC.JIT(efc, efc.epilogue_parameter_names) + + +def _rewrap_efc_compiled_obj(compiled_fn, kernel, epilogue_args=None): + """Reconstruct the EFC wrapped_launch closure from a loaded JIT function. + + When epilogue_args is provided and efc.jit is missing, performs a + lightweight initialization (analyze + JIT creation) so that + disk-cached EFC artifacts can be reused without a full recompile. + Falls back to returning None (triggering recompile) only when + epilogue_args is not available. + """ + if not hasattr(kernel, "impl") or not hasattr(kernel.impl, "efc"): + return compiled_fn + if not hasattr(kernel.impl.efc, "jit"): + if epilogue_args is not None: + _init_efc_jit(kernel, epilogue_args) + else: + return None + + from cutlass.operators.providers.cutedsl.gemm.sm100_static_persistent_efc import ( + Operand as KernelOperand, + TensorWrapper, + ) + + def wrapped_launch(a_tensor, b_tensor, stream, *supplemental_args): + runtime_args = [ + e.runtime_tensor + if isinstance(e, TensorWrapper) + else (e.tensor.runtime_tensor if isinstance(e, KernelOperand) else e) + for e in supplemental_args + ] + # A disk-reloaded artifact is the raw kernel module func: it takes the + # epilogue tensors unpacked (a, b, stream, aux..., out), unlike the + # freshly-JIT-compiled closure which expects pack_arguments(...). All + # callers of _rewrap_efc_compiled_obj load from disk, so pass unpacked. + return compiled_fn(a_tensor, b_tensor, stream, *runtime_args) + + return wrapped_launch + + +def _update_reuse_args_tensors( + variant_name, args, input_tensors, out, epilogue_args, args_kwargs=None +) -> bool: + """Redirect the cached args at this call's runtime tensors. + + A cache hit on ``mem_key`` guarantees identical shapes/strides/dtypes, so + only the data pointers change; mutating ``TensorWrapper._runtime_tensor`` in + place is sufficient and lets us skip the (expensive) _create_gemm_arguments + rebuild. Returns False for GROUPED_GEMM (unsupported), signalling the caller + to use the rebuild path. + """ + if variant_name == "GROUPED_GEMM": + return False + if variant_name == "SCALED_GEMM": + a, b, scale_a, scale_b = input_tensors + args.A.quantized.tensor._runtime_tensor = a + args.A.scale.tensor._runtime_tensor = scale_a + args.B.quantized.tensor._runtime_tensor = b + args.B.scale.tensor._runtime_tensor = scale_b + args.out.tensor._runtime_tensor = out + else: + # GEMM: dense mm and the EFC bias/epilogue addmm path. + a, b = input_tensors + args.A.tensor._runtime_tensor = a + args.B.tensor._runtime_tensor = b + args.out.tensor._runtime_tensor = out + epilogue = getattr(args, "epilogue", None) + if epilogue is not None: + for name, wrapper in epilogue.tensors.items(): + val = epilogue_args.tensors[name] + wrapper._runtime_tensor = getattr(val, "runtime_tensor", val) + local_reduce = getattr(args, "local_reduce_out", None) + if local_reduce is not None: + if args_kwargs is None: + raise AssertionError("expected args_kwargs to be not None") + local_reduce._runtime_tensor = args_kwargs["local_reduce_out"] + return True + + +def _clear_reuse_args_tensors(variant_name, args, epilogue_args): + """Drop the runtime tensors held by cached args after a launch. + + kernel.run enqueues the launch synchronously and reads the pointers during + the call, and the caller keeps the tensors alive, so clearing our cached + references is safe. Required for cudagraph capture, which fails if a cached + object retains a tensor from the graph pool between iterations. + """ + if variant_name == "SCALED_GEMM": + args.A.quantized.tensor._runtime_tensor = None + args.A.scale.tensor._runtime_tensor = None + args.B.quantized.tensor._runtime_tensor = None + args.B.scale.tensor._runtime_tensor = None + args.out.tensor._runtime_tensor = None + else: + args.A.tensor._runtime_tensor = None + args.B.tensor._runtime_tensor = None + args.out.tensor._runtime_tensor = None + epilogue = getattr(args, "epilogue", None) + if epilogue is not None: + for wrapper in epilogue.tensors.values(): + wrapper._runtime_tensor = None + # kernel.run traces the epilogue on first launch, and the trace retains + # the real output/aux tensors in example_inputs (used only for tracing, + # not the launch). Replace them with meta tensors so the cached args + # hold no real storage -- otherwise an intermediate output stays live + # and CUDA graph capture fails. Mirrors _meta_epilogue_metadata. + import torch + + te = getattr(epilogue, "traced_epilogue", None) + example_inputs = getattr(te, "example_inputs", None) if te else None + if example_inputs: + for name, val in example_inputs.items(): + if isinstance(val, torch.Tensor) and val.device.type != "meta": + example_inputs[name] = torch.empty_strided( + val.shape, val.stride(), dtype=val.dtype, device="meta" + ) + local_reduce = getattr(args, "local_reduce_out", None) + if local_reduce is not None: + local_reduce._runtime_tensor = None + + +def _nvgemm_run( + variant_name: str, + kernel_name: str, + input_tensors: tuple, + out, + accumulator_type, + compiled_cache: dict, + disk_fn_cache: dict, + module_path: str, + disk_config_key: tuple, + *, + stream=None, + workspace=None, + variant_kwargs: dict | None = None, + epilogue_args=None, + epilogue_source: str = "", + has_epilogue: bool = False, + aux_tensors: tuple = (), + swap_ab: bool = False, +): + if swap_ab and len(input_tensors) >= 2: + a, b = input_tensors[0], input_tensors[1] + if len(input_tensors) >= 4: + sa, sb = input_tensors[2], input_tensors[3] + input_tensors = (b.t(), a.t(), sb, sa) + input_tensors[4:] + else: + input_tensors = (b.t(), a.t()) + input_tensors[2:] + # Swapped GEMM computes (N, M) = out.t(); write it zero-copy into a + # transposed (column-major) view of the real (M, N) output -- no temp + # buffer / copy (the kernel handles column-major C). + out = out.t() + from cutlass.operators.artifact import CompiledArtifact + + from torch._inductor.runtime.cutedsl_cache import disk_cache_get, disk_cache_set + + epilogue_specialization = tuple( + (key, variant_kwargs[key]) + for key in ("local_reduce_type", "local_reduce_source") + if variant_kwargs is not None and key in variant_kwargs + ) + cache_key = _create_gemm_cache_key( + input_tensors, + out, + has_epilogue=has_epilogue, + aux_tensors=aux_tensors, + epilogue_specialization=epilogue_specialization, + ) + dev_idx = input_tensors[0].device.index or 0 + mem_key = (cache_key, dev_idx) + + if mem_key in compiled_cache: + artifact = compiled_cache[mem_key] + # Fast path: reuse the previously-built args, redirecting only the + # runtime tensor pointers. Skips _create_gemm_arguments, whose cost + # (get_type_hints + deepcopy + full epilogue/layout reprocessing) + # depends solely on shapes/layout -- fixed for a given mem_key. + reuse = getattr(artifact, "_nvgemm_reuse", None) + if reuse is not None: + args, kernel, reuse_lock = reuse + # The cached args are shared mutable state. Serialize the + # redirect->launch->clear so concurrent launches on the same cached + # artifact (e.g. two graph executions sharing this kernel) don't + # stomp each other's runtime tensor pointers. + with reuse_lock: + if _update_reuse_args_tensors( + variant_name, + args, + input_tensors, + out, + epilogue_args, + variant_kwargs, + ): + try: + kernel.run( + args, + artifact, + stream=stream, + workspace=workspace, + assume_supported_args=True, + ) + finally: + _clear_reuse_args_tensors(variant_name, args, epilogue_args) + return + # No reusable args (e.g. artifact loaded from disk by a subprocess + # precompile): build them once, then attach below for future calls. + args = _create_gemm_arguments( + variant_name, + input_tensors, + out, + accumulator_type, + epilogue=epilogue_args, + **(variant_kwargs or {}), + ) + kernel = artifact.operator_obj + else: + + def disk_fallback(kernel): + compiled_fn = disk_cache_get( + disk_fn_cache, + module_path, + disk_config_key, + cache_key, + dev_idx, + ) + if compiled_fn is not None: + compiled_fn = _rewrap_efc_compiled_obj( + compiled_fn, + kernel, + epilogue_args=epilogue_args, + ) + if compiled_fn is not None: + return CompiledArtifact( + compiled_fn, kernel, _current_target_sm(dev_idx) + ) + return None + + artifact, args, kernel, was_compiled = _compile_nvgemm( + variant_name, + input_tensors, + out, + accumulator_type, + kernel_name=kernel_name, + args_kwargs=variant_kwargs, + epilogue_args=epilogue_args, + epilogue_source=epilogue_source, + fallback_fn=disk_fallback, + cc=_current_target_sm(dev_idx).cc, + ) + + if was_compiled: + disk_cache_set( + disk_fn_cache, + module_path, + disk_config_key, + cache_key, + _unwrap_efc_compiled_obj(artifact.compiled_obj), + dev_idx, + ) + + compiled_cache[mem_key] = artifact + + # Attach the built args for reuse on subsequent calls (skipped for + # GROUPED_GEMM, where _update_reuse_args_tensors returns False). This runs + # for both the disk-loaded rebuild branch and the fresh-compile branch. + reuse_supported = _update_reuse_args_tensors( + variant_name, + args, + input_tensors, + out, + epilogue_args, + variant_kwargs, + ) + if reuse_supported: + # Publish and launch under the lock so a concurrent reuse-path caller + # that picks up these args blocks until this launch has cleared them. + reuse_lock = threading.Lock() + with reuse_lock: + artifact._nvgemm_reuse = (args, kernel, reuse_lock) + try: + kernel.run( + args, + artifact, + stream=stream, + workspace=workspace, + assume_supported_args=True, + ) + finally: + _clear_reuse_args_tensors(variant_name, args, epilogue_args) + else: + kernel.run( + args, + artifact, + stream=stream, + workspace=workspace, + assume_supported_args=True, + ) + + +# Patch both the canonical definition (integration_utils.mma) for callers that +# reference it module-qualified, and each gemm module's namespace for callers +# that imported the bare name. _patch_max_active_clusters skips any without it. +_MAX_ACTIVE_CLUSTERS_MODULES = [ + "cutlass.operators.providers.cutedsl.integration_utils.mma", + "cutlass.operators.providers.cutedsl.gemm.sm100_persistent", + "cutlass.operators.providers.cutedsl.gemm.sm100_persistent_preferred_cluster", + "cutlass.operators.providers.cutedsl.gemm.sm100_static_persistent_efc", + "cutlass.operators.providers.cutedsl.gemm.sm100_dense_blockscaled_static_persistent", + "cutlass.operators.providers.cutedsl.gemm.sm100_contiguous_offset_2d3d_dense_gemm", + "cutlass.operators.providers.cutedsl.gemm.sm100_mixed_input", + "cutlass.operators.providers.cutedsl.gemm.sm90_static_persistent", +] + + +def _nvgemm_precompile( + precompile_shapes: dict, + precompile_strides: dict, + precompile_dtypes: dict, + device_index: int = 0, + device_capability: tuple | None = None, + *, + variant_name: str, + kernel_name: str, + accumulator_type, + compiled_cache: dict, + disk_fn_cache: dict, + module_path: str, + disk_config_key: tuple, + input_param_names: list[str], + variant_kwargs: dict | None = None, + max_active_clusters: int | None = None, +): + """Precompile an NVGEMM kernel in a subprocess for parallel compilation. + + Precompiles only the base (non-EFC) kernel. EFC kernels produce + closure-wrapped artifacts that can't be serialized to disk cache. + """ + import torch + from torch._inductor.runtime.cutedsl_cache import disk_cache_set + from torch._subclasses.fake_tensor import FakeTensorMode + + if max_active_clusters is None: + return + + # cutlass.operators queries device occupancy while compiling. In async-compile + # workers forked from a CUDA-initialized parent, skip precompile. + if torch.cuda._is_in_bad_fork(): + return + + device = f"cuda:{device_index}" + with FakeTensorMode(): + tensors = {} + for name in [*input_param_names, "output"]: + tensors[name] = torch.empty_strided( + tuple(precompile_shapes[name]), + tuple(precompile_strides[name]), + device=device, + dtype=getattr(torch, precompile_dtypes[name]), + ) + + input_tensors = tuple(tensors[n] for n in input_param_names) + out = tensors["output"] + + patched = _patch_max_active_clusters(max_active_clusters) + try: + cache_key = _create_gemm_cache_key(input_tensors, out) + mem_key = (cache_key, device_index) + if mem_key not in compiled_cache: + artifact, _, _, _ = _compile_nvgemm( + variant_name, + input_tensors, + out, + accumulator_type, + kernel_name=kernel_name, + args_kwargs=variant_kwargs, + ) + disk_cache_set( + disk_fn_cache, + module_path, + disk_config_key, + cache_key, + artifact.compiled_obj, + device_index, + device_capability=device_capability, + ) + compiled_cache[mem_key] = artifact + finally: + _restore_max_active_clusters(patched) + + +# ── Kernel wrapper (returned by async_compile.nv_universal_gemm) ───────────── + + +class NVUniversalGemmKernelWrapper: + """Wrapper to provide .run() interface for NVIDIA Universal GEMM kernels.""" + + def __init__(self, kernel_fn, kernel_path: str | None = None): + self.kernel_fn = kernel_fn + self.kernel_path = kernel_path + + def run(self, *args, stream=None, **kwargs): + """Execute the NVIDIA Universal GEMM kernel.""" + return self.kernel_fn(*args, stream=stream, **kwargs) + + +# ── Kernel codegen class ───────────────────────────────────────────────────── + + +# Module-level bias-add epilogue for benchmark tracing. Must be a real +# (introspectable) function -- EpilogueArguments parses its source via +# inspect.getsource -- and must contain NO string literals (the AST tracer +# treats any constant as an immediate). The param name is deliberately not +# ``C`` (see _build_bias_epilogue) so a 1D bias routes to the row-broadcast impl. +def _nvgemm_bias_add_epilogue(accum, bias): + D = accum + bias + return D + + +def _build_bias_epilogue( + bias_name: str, out_name: str +) -> tuple[str, list[str], list[str], dict[str, str]]: + """Build the epilogue fields for an addmm bias-add (``accum + bias``). + + Uses the bias buffer name as the epilogue-fn parameter, matching + CutlassEVTCodegen's convention. This deliberately avoids the name ``C``: + cutlass.operators' LoadSrcImpl claims any epilogue param named ``C`` whose + shape equals the output (ignoring stride), which shadows the row/column + broadcast impls and silently mis-reads a broadcast (1D) bias. + """ + epilogue_fn_code = ( + f"def _epilogue_fn(accum, {bias_name}):\n" + f" D = accum + {bias_name}\n" + f" return D" + ) + epilogue_reads = [bias_name] + epilogue_writes: list[str] = [] + epilogue_var_renames = {bias_name: bias_name, "D": out_name} + return epilogue_fn_code, epilogue_reads, epilogue_writes, epilogue_var_renames + + +def _compose_bias_into_epilogue( + epilogue_fn_code: str, + epilogue_reads: list[str], + epilogue_var_renames: dict[str, Any], + bias_name: str, +) -> tuple[str, list[str], dict[str, Any]]: + """Inject an addmm bias-add into a scheduler-fused epilogue. + + The EFC kernel's ``accum`` is the raw ``A @ B``; a fused pointwise epilogue + written by CutlassEVTCodegen assumes its ``accum`` is the addmm output + (``A @ B + bias``). We keep ``accum`` as the raw accumulator (required by + the cutlass epilogue tracer) and rewrite the fused body to read a new + ``biased = accum + bias`` value instead, adding ``bias`` as an aux input. + """ + lines = epilogue_fn_code.splitlines() + def_line = lines[0] + body = lines[1:] + # Add bias as the 2nd parameter (after the required `accum`), unless the + # fused epilogue already reads the same buffer -- then it is already a + # parameter and re-adding it would emit `def fn(accum, b, b)` (SyntaxError). + if bias_name not in epilogue_reads: + def_line = def_line.replace("(accum", f"(accum, {bias_name}", 1) + # Rewrite fused-body references to the accumulator to the biased value. + rewritten = [re.sub(r"\baccum\b", "biased", bl) for bl in body] + composed = "\n".join([def_line, f" biased = accum + {bias_name}", *rewritten]) + reads = list(epilogue_reads) + if bias_name not in reads: + reads.append(bias_name) + renames = dict(epilogue_var_renames) + renames[bias_name] = bias_name + return composed, reads, renames + + +class NVUniversalGemmKernel(Kernel): + """ + Kernel implementation for NVIDIA Universal GEMM. + + Generates a thin Python wrapper that delegates to runtime helpers + (_nvgemm_run, _nvgemm_precompile) for the actual GEMM execution and + compilation logic. + """ + + def __init__( + self, + kernel_name: str, + input_nodes: list[Buffer], + output_node: Buffer, + kernel_metadata: dict[str, Any], + accumulator_type: Any, + variant: GemmVariant, + workspace_size: int = 0, + scale_type_a: Any | None = None, + scale_type_b: Any | None = None, + swizzle_type_a: Any | None = None, + swizzle_type_b: Any | None = None, + epilogue_fn_code: str | None = None, + epilogue_reads: list[str] | None = None, + epilogue_writes: list[str] | None = None, + epilogue_var_renames: dict[str, Any] | None = None, + local_reduce: GemmReductionPlan | None = None, + swap_ab: bool = False, + bias_node: Buffer | None = None, + ) -> None: + super().__init__() + self.kernel_name = kernel_name + self.input_nodes = input_nodes + self.output_node = output_node + self.kernel_metadata = kernel_metadata + self.accumulator_type = accumulator_type + self.workspace_size = workspace_size + self.variant = variant + self.scale_type_a = scale_type_a + self.scale_type_b = scale_type_b + self.swizzle_type_a = swizzle_type_a + self.swizzle_type_b = swizzle_type_b + self.epilogue_fn_code = epilogue_fn_code + self.epilogue_reads = epilogue_reads or [] + self.epilogue_writes = epilogue_writes or [] + self.epilogue_var_renames = epilogue_var_renames or {} + self.local_reduce = local_reduce + self.swap_ab = swap_ab + + # An addmm bias baked into the choice becomes a bias-add epilogue. With + # no scheduler-fused epilogue it's a standalone bias-add; when the + # scheduler also fuses pointwise ops, compose the bias-add into them so + # the fused epilogue sees A@B + bias (matches Triton's epilogue fusion). + if bias_node is not None: + if not self.epilogue_fn_code: + ( + self.epilogue_fn_code, + self.epilogue_reads, + self.epilogue_writes, + self.epilogue_var_renames, + ) = _build_bias_epilogue(bias_node.get_name(), output_node.get_name()) + else: + ( + self.epilogue_fn_code, + self.epilogue_reads, + self.epilogue_var_renames, + ) = _compose_bias_into_epilogue( + self.epilogue_fn_code, + self.epilogue_reads, + self.epilogue_var_renames, + bias_node.get_name(), + ) + + self._template_input_args: list[tuple[str, Buffer]] = [] + + for i, input_node in enumerate(input_nodes): + param_name = f"in_ptr{i}" + self._template_input_args.append((param_name, input_node)) + + def render(self) -> str: + """Render the Python source for the NVGEMM kernel wrapper.""" + kernel_name_str = self.kernel_metadata["kernel_name"] + acc_dtype_str = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get( + self.accumulator_type, "cutlass.Float32" + ) + + input_tensor_names = [f"in_ptr{i}" for i, _ in enumerate(self.input_nodes)] + output_buffers = self._ordered_output_buffers() + input_params = list(input_tensor_names) + input_params.extend(f"out_ptr{i}" for i in range(len(output_buffers))) + input_params.extend(self.epilogue_reads) + if self.workspace_size > 0: + input_params.append("workspace") + input_params.append("stream=None") + params_str = ", ".join(input_params) + + if len(input_tensor_names) == 1: + input_tensors_expr = f"({input_tensor_names[0]},)" + else: + input_tensors_expr = f"({', '.join(input_tensor_names)})" + + workspace_arg = "workspace" if self.workspace_size > 0 else "None" + has_epilogue = bool(self.epilogue_fn_code) or self.local_reduce is not None + + # Build variant_kwargs dict expression for SCALED_GEMM + variant_kwargs_expr = "None" + variant_extra_imports = "" + if self.variant.name == "SCALED_GEMM": + sma, swza, smb, swzb = _get_scaled_gemm_modes( + self.scale_type_a, + self.swizzle_type_a, + self.scale_type_b, + self.swizzle_type_b, + ) + variant_extra_imports = ( + "from cutlass.operators import ScaleMode, ScaleSwizzleMode" + ) + variant_kwargs_expr = ( + "{" + f'"scale_mode_a": ScaleMode.{sma.name}, ' + f'"swizzle_mode_a": ScaleSwizzleMode.{swza.name}, ' + f'"scale_mode_b": ScaleMode.{smb.name}, ' + f'"swizzle_mode_b": ScaleSwizzleMode.{swzb.name}' + "}" + ) + + code = IndentedBuffer() + + # -- Module-level imports and constants -- + code.writeline("import cutlass") + code.writeline( + "from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import (" + ) + with code.indent(): + code.writeline("_make_disk_config_key,") + code.writeline("_nvgemm_run,") + code.writeline("_nvgemm_precompile,") + code.writeline(")") + code.writeline("from torch._inductor.utils import _ensure_fp4_dtype_registered") + code.writeline("_ensure_fp4_dtype_registered()") + if variant_extra_imports: + code.writeline(variant_extra_imports) + if has_epilogue: + code.writeline("from cutlass.operators.arguments import EpilogueArguments") + code.writeline("") + + # -- Epilogue function definition (must be module-level for cutlass.operators) -- + epilogue_fn_code = self.epilogue_fn_code + if has_epilogue and epilogue_fn_code is not None: + epilogue_source_hash = hashlib.sha256(epilogue_fn_code.encode()).hexdigest() + code.writeline(f'_EPILOGUE_FN_SOURCE = "{epilogue_source_hash}"') + # Pass the epilogue to cutlass.operators as a SOURCE STRING, not a + # callable: EpilogueArguments traces a string directly, whereas a + # callable triggers inspect.getsource() at every kernel launch -- + # which fails ("could not get source code") for generated modules + # loaded from the subprocess PyCodeCache. + code.writeline(f"_EPILOGUE_FN_SRC = {epilogue_fn_code!r}") + code.writeline("") + + # -- Module-level state -- + code.writeline(f"_KERNEL_NAME = {kernel_name_str!r}") + disk_key_args = ", ".join( + repr(str(v)) + for v in ( + kernel_name_str, + self.variant.name, + self.accumulator_type, + self.scale_type_a, + self.scale_type_b, + self.swizzle_type_a, + self.swizzle_type_b, + ) + ) + code.writeline( + f"_DISK_CACHE_CONFIG_KEY = _make_disk_config_key({disk_key_args})" + ) + code.writeline("_compiled_cache = {}") + code.writeline("_disk_fn_cache = {}") + code.writeline(f"_VARIANT_KWARGS = {variant_kwargs_expr}") + code.writeline(f"_ACC_TYPE = {acc_dtype_str}") + input_param_names_repr = repr(input_tensor_names) + code.writeline(f"_INPUT_PARAM_NAMES = {input_param_names_repr}") + code.writeline("") + + # -- Main function -- + code.writeline(f"def {self.kernel_name}_main({params_str}):") + with code.indent(): + # Build epilogue args if needed (user-specific variable names) + epi_args_expr = "None" + epi_source_expr = '""' + aux_tensors: list[str] = [] + if self.epilogue_fn_code: + epilogue_kwargs = self._render_epilogue_kwargs() + epi_kwargs_str = "epilogue_fn=_EPILOGUE_FN_SRC" + if epilogue_kwargs: + epi_kwargs_str += f", {epilogue_kwargs}" + code.writeline(f"epi_args = EpilogueArguments({epi_kwargs_str})") + epi_args_expr = "epi_args" + epi_source_expr = "_EPILOGUE_FN_SOURCE" + aux_tensors.extend(self.epilogue_reads) + + run_variant_kwargs = "_VARIANT_KWARGS" + if self.local_reduce is not None: + reduction = self.local_reduce + feed_main = reduction.feeds_main + reduce_ptr = ( + "None" + if reduction.reduction_output is None + else f"out_ptr{output_buffers.index(reduction.reduction_output)}" + ) + run_variant_kwargs = ( + "_VARIANT_KWARGS | {" + f"'local_reduce_out': {reduce_ptr}, " + f"'local_reduce_group': {reduction.group}, " + f"'local_reduce_axis': {reduction.axis}, " + f"'local_reduce_type': {reduction.reduction_type!r}, " + f"'local_reduce_source': {reduction.source_type!r}" + f", 'local_reduce_feeds_main': {feed_main!r}" + "}" + ) + if not feed_main: + aux_tensors.append(reduce_ptr) + + aux_tensors_expr = f"({', '.join(aux_tensors)},)" if aux_tensors else "()" + + code.writeline("_nvgemm_run(") + with code.indent(): + code.writeline(f'"{self.variant.name}", _KERNEL_NAME,') + code.writeline(f"{input_tensors_expr}, out_ptr0, _ACC_TYPE,") + code.writeline( + "_compiled_cache, _disk_fn_cache, __file__, _DISK_CACHE_CONFIG_KEY," + ) + code.writeline(f"stream=stream, workspace={workspace_arg},") + code.writeline(f"variant_kwargs={run_variant_kwargs},") + code.writeline(f"epilogue_args={epi_args_expr},") + code.writeline(f"epilogue_source={epi_source_expr},") + code.writeline(f"has_epilogue={has_epilogue},") + code.writeline(f"aux_tensors={aux_tensors_expr},") + if self.swap_ab: + code.writeline("swap_ab=True,") + code.writeline(")") + + # -- Precompile hook -- + code.writeline("") + code.writeline( + f"def {self.kernel_name}_precompile(" + "precompile_shapes, precompile_strides, precompile_dtypes, " + "device_index=0, device_capability=None, **kwargs):" + ) + with code.indent(): + code.writeline("_nvgemm_precompile(") + with code.indent(): + code.writeline( + "precompile_shapes, precompile_strides, precompile_dtypes," + ) + code.writeline("device_index, device_capability,") + code.writeline(f'variant_name="{self.variant.name}",') + code.writeline("kernel_name=_KERNEL_NAME,") + code.writeline("accumulator_type=_ACC_TYPE,") + code.writeline( + "compiled_cache=_compiled_cache, disk_fn_cache=_disk_fn_cache," + ) + code.writeline( + "module_path=__file__, disk_config_key=_DISK_CACHE_CONFIG_KEY," + ) + code.writeline("input_param_names=_INPUT_PARAM_NAMES,") + code.writeline("variant_kwargs=_VARIANT_KWARGS,") + code.writeline("max_active_clusters=kwargs.get('max_active_clusters'),") + code.writeline(")") + + return code.getvalue() + + def _ordered_output_buffers(self) -> list[str]: + """Graph-output buffer names in out_ptr order. + + out_ptr0 is the primary GEMM output (the epilogue's `D` store, passed as + the kernel's `out`). Additional stores -- a multi-store epilogue where the + GEMM output feeds more than one graph output -- follow in epilogue_writes + order as out_ptr1, out_ptr2, ... + """ + if not self.epilogue_writes: + primary_output = ( + self.local_reduce.primary_output + if self.local_reduce is not None + else self.output_node.get_name() + ) + ordered = [primary_output] + if self.local_reduce is not None: + ordered.extend(self.local_reduce.auxiliary_outputs) + return ordered + d_buf = (self.epilogue_var_renames or {}).get("D") + ordered: list[str] = [] + if d_buf is not None: + ordered.append(d_buf) + for w in self.epilogue_writes: + if w != d_buf and w not in ordered: + ordered.append(w) + if self.local_reduce is not None: + ordered.extend( + output + for output in self.local_reduce.auxiliary_outputs + if output not in ordered + ) + return ordered + + def _render_epilogue_kwargs(self) -> str: + """Render kwargs for the EpilogueArguments constructor. + + Each epilogue variable maps to either an output pointer -- the `D` store + and any additional multi-store outputs become out_ptr0, out_ptr1, ... in + _ordered_output_buffers order -- or, for a read, the aux input buffer. + `accum` is the kernel-supplied accumulator and is not a kwarg. + """ + out_ptr_of = { + buf: f"out_ptr{i}" for i, buf in enumerate(self._ordered_output_buffers()) + } + kwargs_parts = [] + for var_name, buffer_name in self.epilogue_var_renames.items(): + if var_name == _ACCUMULATOR_ARG_NAME: + continue + if buffer_name in out_ptr_of: + kwargs_parts.append(f"{var_name}={out_ptr_of[buffer_name]}") + else: + kwargs_parts.append(f"{var_name}={buffer_name}") + return ", ".join(kwargs_parts) + + def _get_reinterpret_view(self, node) -> ReinterpretView | None: + """Extract or convert to ReinterpretView from a node, handling all views.""" + while isinstance(node, MutableBox): + node = node.data + if isinstance(node, BaseView): + return ExternKernel.convert_to_reinterpret_view(node) + return None + + def call_kernel(self, name: str, node=None): + """ + Generate the kernel call in the wrapper code. + + Similar to CuteDSLTemplateKernel.call_kernel but simplified for NVIDIA Universal GEMM. + Includes epilogue input tensors when epilogue fusion is enabled. + """ + wrapper = V.graph.wrapper_code + + if self.local_reduce is not None: + primary_name = self.local_reduce.primary_output + V.graph.removed_buffers.discard(primary_name) + primary_output = V.graph.get_buffer(primary_name) + wrapper.codegen_allocation( + primary_output + if isinstance(primary_output, Buffer) + else self.output_node + ) + + call_args: list[str] = [] + arg_types: list[Any] = [] + raw_args: list[Buffer | ReinterpretView | None] = [] + raw_keys: list[str | None] = [] + + for param_name, input_node in self._template_input_args: + reinterpret_view = self._get_reinterpret_view(input_node) + if reinterpret_view is not None: + call_args.append(reinterpret_view.codegen_reference()) + # Pass the ReinterpretView as raw_arg so autotune_at_compile_time + # can use it to generate example tensors + raw_args.append(reinterpret_view) + else: + call_args.append(input_node.get_name()) + raw_args.append(input_node) + arg_types.append(V.graph.get_dtype(input_node.get_name())) + raw_keys.append(param_name) + + # The kernel writes the epilogue's output store(s), not the GEMM buffer + # (which is removed via removed_buffers aliasing). out_ptr0 is the primary + # (`D`) output; a multi-store epilogue adds out_ptr1, ... in order. + for i, output_name in enumerate(self._ordered_output_buffers()): + call_args.append(output_name) + arg_types.append(V.graph.get_dtype(output_name)) + raw_args.append(None) # Output buffer is findable by name + raw_keys.append(f"out_ptr{i}") + + for read_name in self.epilogue_reads: + call_args.append(read_name) + arg_types.append(V.graph.get_dtype(read_name)) + buf = V.graph.get_buffer(read_name) + if buf is None: + # Epilogue may read model parameters/inputs (e.g. bias) that are + # graph inputs rather than computed buffers. + buf = V.graph.graph_inputs.get(read_name) + # pyrefly: ignore [bad-argument-type] + raw_args.append(buf) + raw_keys.append(read_name) + + # Allocate workspace if needed + ws: WorkspaceArg | None = None + if self.workspace_size > 0: + ws = WorkspaceArg( + count=self.workspace_size, + device=V.graph.get_current_device_or_throw(), + zero_mode=WorkspaceZeroMode.UNINITIALIZED, + outer_name=WorkspaceArg.unique_name(), + ) + wrapper.generate_workspace_allocation(ws) + call_args.append(ws.outer_name) + arg_types.append(ws.dtype) + raw_args.append(None) + raw_keys.append(None) + + wrapper.generate_kernel_call( + name, + call_args, + triton=True, + arg_types=arg_types, + raw_args=raw_args, + raw_keys=raw_keys, + ) + + # Deallocate workspace after kernel call + if ws is not None: + wrapper.generate_workspace_deallocation(ws) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..16f2094cd8d6d362e95064c12b6b57b61c81c45d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_scheduling.py @@ -0,0 +1,1137 @@ +# mypy: allow-untyped-defs +""" +NVIDIA Universal GEMM scheduling for PyTorch Inductor. +""" + +import dataclasses +import hashlib +import logging +from collections.abc import Sequence +from typing import Any, cast + +from torch._inductor.utils import ( + get_fused_kernel_name, + get_kernel_metadata, + Placeholder, +) +from torch.utils._ordered_set import OrderedSet + +from ... import config +from ...codecache import code_hash, get_path +from ...ir import ( + Buffer, + ComputedBuffer, + Layout, + MultiTemplateBuffer, + NVUniversalGemmBuffer, + Pointwise, + Reduction, +) +from ...kernel.gemm_epilogue import GemmReductionConfig, GemmReductionPlan +from ...kernel.loop_ir_cutedsl_codegen import LoopIRCuteDSLCodegen +from ...kernel.loop_ir_epilogue_lowering import ( + centered_mean_consumer_type_unrolled_ir, + GemmEpilogueIRAnalysis, + grouped_reduction_ir, + single_source_affine_ir, +) +from ...scheduler import ( + BaseSchedulerNode, + BaseScheduling, + FusedSchedulerNode, + SchedulerNode, +) +from ...virtualized import V +from ..common import BackendFeature, IndentedBuffer +from ..cutlass.python_evt import _ACCUMULATOR_ARG_NAME, CutlassEVTCodegen +from .nv_universal_gemm import NVUniversalGemmCaller + + +log = logging.getLogger(__name__) + +MAIN_SUFFIX = "main" +_BENCHMARK_KERNEL_PREFIX = "nv_gemm_" +EPILOGUE_FN_NAME = "_epilogue_fn" + + +@dataclasses.dataclass(frozen=True) +class NVGemmEpiloguePlan: + nodes: tuple[BaseSchedulerNode, ...] + reductions: tuple[GemmReductionConfig, ...] + reduction_nodes: tuple[BaseSchedulerNode, ...] + candidate_reduction: GemmReductionConfig | None = None + feed_main: GemmReductionConfig | None = None + + @property + def evt_nodes(self) -> list[BaseSchedulerNode]: + owned = OrderedSet(self.reduction_nodes) + return [node for node in self.nodes if node not in owned] + + +class NVUniversalGemmScheduling(BaseScheduling): + """ + Scheduling implementation for NVIDIA Universal GEMM kernels. + + This class is intended to be used in combination with other schedulers, + and delegated to by CUDACombinedScheduling. + """ + + @classmethod + def get_backend_features(cls, device) -> OrderedSet[BackendFeature]: + return OrderedSet() + + @staticmethod + def _is_nvgemm_ir_buffer(ir_node: Any) -> bool: + """Return True if `ir_node` is an NVGEMM buffer or an MTB resolving to one. + + Honors finalize_as_*_caller's swap (a MultiTemplateBuffer whose render + kind is "triton" is no longer NVGEMM, even if the autotune winner was). + Falls back to the autotune winner only when no swap has happened. + """ + if isinstance(ir_node, NVUniversalGemmBuffer): + return True + if not isinstance(ir_node, MultiTemplateBuffer): + return False + if ir_node._render_kind == "triton": + return False + if ir_node._render_kind == "nvgemm": + return True + # Fast path: avoid forcing autotune just to answer this query. + if not any(isinstance(c, NVUniversalGemmCaller) for c in ir_node._choices): + return False + try: + min_choice, _ = ir_node.get_min_choice() + return isinstance(min_choice, NVUniversalGemmCaller) + except (RuntimeError, ValueError): + return False + + @staticmethod + def is_nv_universal_gemm_template(node: BaseSchedulerNode) -> bool: + """Check if a node is an NVGEMM template SchedulerNode.""" + if not isinstance(node, SchedulerNode): + return False + return NVUniversalGemmScheduling._is_nvgemm_ir_buffer(node.node) + + @staticmethod + def _best_nvgemm_choice( + ir_node: MultiTemplateBuffer, + require_epilogue_fusion: bool = False, + ) -> NVUniversalGemmCaller: + """Find the best NVUniversalGemmCaller from an MTB's choice timings.""" + choice_timings = ir_node.choice_timings() + best: NVUniversalGemmCaller | None = None + best_time = float("inf") + for choice, timing in choice_timings.items(): + if not isinstance(choice, NVUniversalGemmCaller): + continue + if require_epilogue_fusion and not choice.supports_epilogue_fusion: + continue + if best is None or timing < best_time: + best_time = timing + best = choice + if best is None: + kind = "EFC kernel" if require_epilogue_fusion else "NVUniversalGemmCaller" + raise RuntimeError(f"No {kind} found in choices") + return best + + @staticmethod + def get_nv_gemm_buffer_from_node( + node: BaseSchedulerNode, require_epilogue_fusion: bool = False + ) -> NVUniversalGemmBuffer: + """Extract NVUniversalGemmBuffer from node (direct or via MultiTemplateBuffer).""" + if not isinstance(node, SchedulerNode): + raise AssertionError(f"expected SchedulerNode, got {type(node)}") + ir_node = node.node + + if isinstance(ir_node, NVUniversalGemmBuffer): + return ir_node + elif isinstance(ir_node, MultiTemplateBuffer): + # Honor an explicit swap/finalize -- the fusion benchmark loop swaps + # in each EFC choice one at a time and must not re-select from timings. + if isinstance(ir_node._render_caller, NVUniversalGemmCaller) and ( + not require_epilogue_fusion + or ir_node._render_caller.supports_epilogue_fusion + ): + selected_choice = ir_node._render_caller + elif require_epilogue_fusion: + selected_choice = NVUniversalGemmScheduling._best_nvgemm_choice( + ir_node, require_epilogue_fusion=True + ) + else: + min_choice, _ = ir_node.get_min_choice() + if isinstance(min_choice, NVUniversalGemmCaller): + selected_choice = min_choice + else: + selected_choice = NVUniversalGemmScheduling._best_nvgemm_choice( + ir_node + ) + tensor_box = selected_choice.output_node() + # pyrefly: ignore [missing-attribute] + return cast(NVUniversalGemmBuffer, tensor_box.data.data) + + raise TypeError( + f"Expected NVUniversalGemmBuffer or MultiTemplateBuffer, got {type(ir_node).__name__}" + ) + + @staticmethod + def is_nv_universal_gemm_fused_template(node: BaseSchedulerNode) -> bool: + """Check if a node is a fused NVIDIA Universal GEMM template.""" + if not isinstance(node, FusedSchedulerNode): + return False + return NVUniversalGemmScheduling._is_nvgemm_ir_buffer(node.get_template_node()) + + def can_fuse_vertical( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if self.is_nv_universal_gemm_template(node1): + return self._can_fuse_epilogue_impl( + cast(SchedulerNode, node1), + [], + node2, + ) + elif self.is_nv_universal_gemm_fused_template(node1): + fnode1 = cast(FusedSchedulerNode, node1) + template_snode = next( + (n for n in fnode1.snodes if self.is_nv_universal_gemm_template(n)), + None, + ) + if template_snode is None: + return False + return self._can_fuse_epilogue_impl( + cast(SchedulerNode, template_snode), + self._unwrap_epilogue_nodes(fnode1), + node2, + ) + return False + + def _unwrap_epilogue_nodes( + self, fused_node: FusedSchedulerNode + ) -> list[BaseSchedulerNode]: + """Extract epilogue nodes from a fused node.""" + epilogue_nodes = [] + for node in fused_node.snodes: + if not self.is_nv_universal_gemm_template(node): + epilogue_nodes.append(node) + return epilogue_nodes + + @classmethod + def _grouped_reduce_config( + cls, gemm_node: Buffer, scheduler_node: BaseSchedulerNode + ) -> GemmReductionConfig | None: + nodes = scheduler_node.get_nodes() + if len(nodes) not in (1, 2): + return None + buffers = [snode.node for snode in nodes] + if not all(isinstance(buffer, ComputedBuffer) for buffer in buffers): + return None + buffers = [cast(ComputedBuffer, buffer) for buffer in buffers] + node = buffers[0] + access_node = scheduler_node + output_name = node.get_name() + if len(node.data.ranges) != 2 or len(gemm_node.get_size()) != 2: + return None + try: + m, n = (V.graph.sizevars.optimization_hint(v) for v in gemm_node.get_size()) + out_m, out_n = ( + V.graph.sizevars.optimization_hint(v) for v in node.data.ranges + ) + except Exception: + return None + + if isinstance(node.data, Reduction): + reduction = node.data + if len(reduction.reduction_ranges) != 1: + return None + group = V.graph.sizevars.optimization_hint(reduction.reduction_ranges[0]) + if m == out_m and n % group == 0 and out_n == n // group: + axis = 1 + expected_strides = [n, group, 1] + max_group = n + elif n == out_n and m % group == 0 and out_m == m // group: + axis = 0 + expected_strides = [group * n, 1, n] + max_group = 16 + else: + return None + elif isinstance(node.data, Pointwise): + if n != out_n or out_m <= 0 or m % out_m != 0: + return None + group = m // out_m + axis = 0 + max_group = 16 + expected_strides = [group * n, 1] + else: + return None + if group <= 1 or group > max_group: + return None + + store = GemmEpilogueIRAnalysis.store_from_buffer(node) + classified = ( + grouped_reduction_ir( + store, + gemm_node.get_name(), + group, + gemm_node.get_dtype(), + ) + if store is not None + else None + ) + if classified is None: + return None + reduction_type, source_type = classified + if reduction_type not in ( + "sum", + "mean", + "prod", + "max", + "min", + ) or source_type not in ("identity", "square"): + return None + if ( + isinstance(node.data, Reduction) + and node.data.reduction_type != reduction_type + ): + return None + if len(buffers) == 2: + finalizer = buffers[1] + finalizer_store = GemmEpilogueIRAnalysis.store_from_buffer(finalizer) + finalizer_reads = list(nodes[1].read_writes.reads) + if ( + reduction_type != "sum" + or not isinstance(node.data, Reduction) + or not isinstance(finalizer.data, Pointwise) + or not finalizer_reads + or any(read.name != node.get_name() for read in finalizer_reads) + or not V.graph.sizevars.statically_known_list_equals( + node.get_size(), finalizer.get_size() + ) + or finalizer_store is None + or single_source_affine_ir(finalizer_store, node.get_name()) + != (1.0 / group, 0.0) + ): + return None + reduction_type = "mean" + access_node = nodes[0] + output_name = finalizer.get_name() + + reads = list(access_node.read_writes.reads) + if not reads or any(read.name != gemm_node.get_name() for read in reads): + return None + range_vars = access_node.read_writes.range_vars + if range_vars is None: + return None + if not range_vars: + return GemmReductionConfig( + output_name, group, axis, reduction_type, source_type + ) + if isinstance(node.data, Reduction): + if len(reads) != 1: + return None + strides = V.graph.sizevars.stride_vars(reads[0].index, range_vars) + if list(strides) != expected_strides: + return None + else: + if len(reads) != group: + return None + expected_base = group * n * range_vars[0] + range_vars[1] + offsets = [] + for read in reads: + strides = V.graph.sizevars.stride_vars(read.index, range_vars) + if list(strides) != expected_strides: + return None + offsets.append(V.graph.sizevars.simplify(read.index - expected_base)) + expected_offsets = OrderedSet(offset * n for offset in range(group)) + if OrderedSet(offsets) != expected_offsets: + return None + return GemmReductionConfig( + output_name, group, axis, reduction_type, source_type + ) + + @classmethod + def _grouped_reduce_feeds_main_config( + cls, gemm_node: Buffer, scheduler_node: BaseSchedulerNode + ) -> GemmReductionConfig | None: + nodes = scheduler_node.get_nodes() + if len(nodes) != 1 or not isinstance(nodes[0].node, ComputedBuffer): + return None + node = cast(ComputedBuffer, nodes[0].node) + if not isinstance(node.data, Pointwise): + return None + reads = list(scheduler_node.read_writes.reads) + range_vars = scheduler_node.read_writes.range_vars + if range_vars is None or len(reads) <= 2: + return None + try: + _, n = map(V.graph.sizevars.optimization_hint, gemm_node.get_size()) + except Exception: + return None + group = len(reads) - 1 + if group <= 1 or group > 4: + return None + store = GemmEpilogueIRAnalysis.store_from_buffer(node) + if ( + store is None + or centered_mean_consumer_type_unrolled_ir( + store, gemm_node.get_name(), group + ) + != "mean_linear:1:-1:0" + ): + return None + if any(read.name != gemm_node.get_name() for read in reads): + return None + grouped_base = reads[1].index + if any( + V.graph.sizevars.simplify(read.index - grouped_base) != i * n + for i, read in enumerate(reads[1:]) + ): + return None + return GemmReductionConfig(node.get_name(), group, 0, "mean", "identity") + + @classmethod + def _epilogue_plan( + cls, + gemm_node: Buffer, + epilogue_nodes: Sequence[BaseSchedulerNode], + candidate: BaseSchedulerNode | None = None, + ) -> NVGemmEpiloguePlan: + reductions: list[GemmReductionConfig] = [] + reduction_nodes: list[BaseSchedulerNode] = [] + candidate_reduction = None + for node in epilogue_nodes: + config = cls._grouped_reduce_config(gemm_node, node) + if config is None: + continue + reductions.append(config) + reduction_nodes.extend(node.get_nodes()) + if node is candidate: + candidate_reduction = config + nodes = tuple( + scheduler_node + for node in epilogue_nodes + for scheduler_node in node.get_nodes() + ) + feed_main = ( + cls._grouped_reduce_feeds_main_config(gemm_node, epilogue_nodes[0]) + if len(epilogue_nodes) == 1 + else None + ) + return NVGemmEpiloguePlan( + nodes, + tuple(reductions), + tuple(reduction_nodes), + candidate_reduction, + feed_main, + ) + + def _can_fuse_epilogue_impl( + self, + gemm_template_node: SchedulerNode, + existing_epilogue_nodes: list[BaseSchedulerNode], + node_to_fuse: BaseSchedulerNode, + ) -> bool: + from .nv_universal_gemm import GemmVariant + + if not config.epilogue_fusion: + return False + + ir_node = gemm_template_node.node + if not isinstance(ir_node, (NVUniversalGemmBuffer, MultiTemplateBuffer)): + return False + + if isinstance(ir_node, NVUniversalGemmBuffer): + if ir_node.variant not in (GemmVariant.GEMM, GemmVariant.SCALED_GEMM): + log.debug( + "NVGEMM epilogue fusion: not supported for %s variant", + ir_node.variant.op_name, + ) + return False + if not ir_node.supports_epilogue_fusion: + log.debug( + "NVGEMM epilogue fusion: kernel %s does not support epilogue fusion", + ir_node.kernel_metadata.get("kernel_name", "unknown"), + ) + return False + elif isinstance(ir_node, MultiTemplateBuffer): + # Use _choices, not choice_timings() — the latter forces autotune sync. + has_efc_choice = False + for choice in ir_node._choices: + if not ( + isinstance(choice, NVUniversalGemmCaller) + and choice.supports_epilogue_fusion + ): + continue + has_efc_choice = True + if choice.variant not in ( + GemmVariant.GEMM, + GemmVariant.SCALED_GEMM, + ): + log.debug( + "NVGEMM epilogue fusion: MultiTemplateBuffer has unsupported EFC choices" + ) + return False + if not has_efc_choice: + log.debug("NVGEMM epilogue fusion: no EFC kernel available in choices") + return False + + plan = self._epilogue_plan( + ir_node, (*existing_epilogue_nodes, node_to_fuse), node_to_fuse + ) + reduction_nodes = OrderedSet(plan.reduction_nodes) + local_reduce = plan.candidate_reduction + feed_main = plan.feed_main + variants = ( + (ir_node.variant,) + if isinstance(ir_node, NVUniversalGemmBuffer) + else tuple( + choice.variant + for choice in ir_node._choices + if isinstance(choice, NVUniversalGemmCaller) + and choice.supports_epilogue_fusion + ) + ) + scaled_epilogue = bool(variants) and all( + variant == GemmVariant.SCALED_GEMM for variant in variants + ) + if local_reduce is not None: + if not scaled_epilogue: + return False + + for s_node in plan.nodes: + node = s_node.node + if not isinstance(node, ComputedBuffer): + log.debug("NVGEMM epilogue fusion: %s is not a ComputedBuffer", node) + return False + if ( + feed_main is None + and not isinstance(node.data, Pointwise) + and s_node not in reduction_nodes + ): + log.debug("NVGEMM epilogue fusion: %s is not a Pointwise op", node) + return False + + if ( + feed_main is None + and s_node not in reduction_nodes + and not V.graph.sizevars.statically_known_list_equals( + node.get_size(), ir_node.get_size() + ) + ): + log.debug( + "NVGEMM epilogue fusion: size mismatch %s vs %s", + node.get_size(), + ir_node.get_size(), + ) + return False + # cutlass.operators' EVT supports matrix, row, and column loads here. + # Reject unresolved inputs and shapes outside those broadcast patterns; + # the trial EVT trace below remains the final capability check. + gemm_size = ir_node.get_size() + name_to_buf = V.graph.name_to_buffer | V.graph.graph_inputs + internal_names = OrderedSet([ir_node.get_name()]) | OrderedSet( + [s_node.get_name() for s_node in plan.nodes] + ) + epilogue_inputs: OrderedSet[str] = OrderedSet() + for s_node in plan.nodes: + for rd in s_node.read_writes.reads: + if rd.name in internal_names: + continue + epilogue_inputs.add(rd.name) + read_buf = name_to_buf.get(rd.name) + if read_buf is None: + log.debug( + "NVGEMM epilogue fusion: read %s not in name_to_buffer/graph_inputs, refusing to fuse", + rd.name, + ) + return False + read_size = read_buf.get_size() + if not read_size or len(read_size) > len(gemm_size): + log.debug( + "NVGEMM epilogue fusion: read buffer %s has unsupported rank", + rd.name, + ) + return False + padded_size = [1] * (len(gemm_size) - len(read_size)) + list(read_size) + supported_shapes = ( + gemm_size, + [1, gemm_size[1]], + [gemm_size[0], 1], + ) + if not any( + V.graph.sizevars.statically_known_list_equals(padded_size, shape) + for shape in supported_shapes + ): + log.debug( + "NVGEMM epilogue fusion: read buffer %s size %s is not broadcastable to GEMM size %s", + rd.name, + read_size, + gemm_size, + ) + return False + if scaled_epilogue and len(epilogue_inputs) > 4: + log.debug( + "NVGEMM scaled epilogue has %d captured tensors; at most four are supported", + len(epilogue_inputs), + ) + return False + + if not existing_epilogue_nodes: + reads = OrderedSet(rd.name for rd in node_to_fuse.read_writes.reads) + if ir_node.get_name() not in reads: + log.debug( + "NVGEMM epilogue fusion: first epilogue node doesn't read from GEMM output" + ) + return False + + if node_to_fuse.has_aliasing_or_mutation(): + log.debug("NVGEMM epilogue fusion: node has aliasing or mutation") + return False + elif node_to_fuse.is_reduction() and local_reduce is None: + log.debug("NVGEMM epilogue fusion: reductions not supported") + return False + + all_epilogue_nodes = list(plan.nodes) + fused_buffer_names = OrderedSet( + n.get_name() for n in [gemm_template_node, *all_epilogue_nodes] + ) + preserve_gemm_output = ( + not V.graph.scheduler.can_buffer_be_removed_through_fusion( + ir_node.get_name(), fused_buffer_names + ) + ) + # Multi-store epilogues wire each output to its own destination tensor. + trial_removed_buffers = V.graph.removed_buffers.copy() + if not preserve_gemm_output: + trial_removed_buffers.add(ir_node.get_name()) + try: + evt_nodes = plan.evt_nodes + trial_reads: list[str] = [] + trial_writes: list[str] = [] + if feed_main is not None: + evt_nodes = [] + if evt_nodes: + trial_reads, trial_writes, _, _ = ( + CutlassEVTCodegen.ir_to_evt_python_code( + ir_node.get_name(), + evt_nodes, + trial_removed_buffers, + ) + ) + if scaled_epilogue: + if len(trial_reads) > 4 or len(trial_writes) > 4: + return False + for read_name in trial_reads: + read_buf = name_to_buf.get(read_name) + if read_buf is None: + log.debug( + "NVGEMM scaled EVT input %s cannot be resolved", + read_name, + ) + return False + except (NotImplementedError, AssertionError) as e: + log.debug("NVGEMM epilogue fusion: trial EVT codegen failed: %s", e) + return False + + return True + + def can_fuse_horizontal( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + # NVIDIA Universal GEMM templates don't support horizontal fusion yet + return False + + def can_fuse_reduction_epilogue( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + template = node1.get_template_node() + return isinstance(template, Buffer) and ( + self._grouped_reduce_config(template, node2) is not None + or self._grouped_reduce_feeds_main_config(template, node2) is not None + ) + + def define_kernel( + self, src_code: str, node_schedule, precompile_metadata=None + ) -> str: + """ + Define a NVIDIA Universal GEMM kernel by writing source code and generating wrapper. + + Based on CuteDSLScheduling.define_kernel. + """ + wrapper = V.graph.wrapper_code + + # Use the string as the key for caching + if src_code in wrapper.src_to_kernel: + return wrapper.src_to_kernel[src_code] + + fused_name = ( + get_fused_kernel_name(node_schedule, config.triton.descriptive_names) + if config.triton.descriptive_names + else "" + ) + + kernel_hash = hashlib.sha256(src_code.encode("utf-8")).hexdigest()[:8] + if fused_name == "fused": + kernel_name = f"nv_universal_gemm_{kernel_hash}" + else: + kernel_name = f"nv_universal_gemm_{fused_name}_{kernel_hash}" + + wrapper.src_to_kernel[src_code] = kernel_name + + src_code = src_code.replace(str(Placeholder.KERNEL_NAME), kernel_name) + + _, _, kernel_path = get_path(code_hash(src_code), "py") + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline( + f"async_compile.nv_universal_gemm({kernel_name!r}, r'''" + ) + compile_wrapper.splice(src_code, strip=True) + if precompile_metadata is not None: + compile_wrapper.writeline( + f"''', precompile_metadata={precompile_metadata!r})" + ) + else: + compile_wrapper.writeline("''')") + + metadata_comment = f"# kernel path: {kernel_path}" + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + metadata_comment += "\n" + origins + "\n" + detailed_origins + wrapper.define_kernel(kernel_name, compile_wrapper.getvalue(), metadata_comment) + + return kernel_name + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + *, + only_gen_src_code: bool = False, + ) -> str | None: + """ + Codegen a NVIDIA Universal GEMM template with optional epilogue fusion. + + If `only_gen_src_code=True` the src code will be returned instead of being + codegenned into the wrapper (used for benchmarking). + """ + log.debug( + "NVGEMM codegen_template: template_node=%s, epilogue_nodes=%s, prologue_nodes=%s", + template_node, + [n.get_name() for n in epilogue_nodes] if epilogue_nodes else [], + [n.get_name() for n in prologue_nodes] if prologue_nodes else [], + ) + if not self.is_nv_universal_gemm_template(template_node): + raise AssertionError( + "Template node passed to NVUniversalGemmScheduling.codegen_template must be a " + "SchedulerNode that wraps a NVUniversalGemmBuffer or MultiTemplateBuffer with NVGEMM choice" + ) + if prologue_nodes: + raise AssertionError( + "NVIDIA Universal GEMM doesn't support prologue fusion yet" + ) + + template_node = cast(SchedulerNode, template_node) + + original_ir_node = template_node.node + if not isinstance(original_ir_node, Buffer): + raise AssertionError(f"expected Buffer, got {type(original_ir_node)}") + original_buffer_name = original_ir_node.get_name() + + ctb: NVUniversalGemmBuffer = self.get_nv_gemm_buffer_from_node( + template_node, require_epilogue_fusion=bool(epilogue_nodes) + ) + + epilogue_fn_code: str | None = None + epilogue_reads: list[str] = [] + epilogue_writes: list[str] = [] + epilogue_var_renames: dict[str, Any] = {} + local_reduce: GemmReductionPlan | None = None + + if epilogue_nodes: + scheduler = V.graph.scheduler + try: + plan = self._epilogue_plan(original_ir_node, epilogue_nodes) + if len(plan.reductions) > 1: + raise NotImplementedError( + "NVGEMM supports one grouped local reduction" + ) + if plan.reductions: + reduction = plan.reductions[0] + local_reduce = GemmReductionPlan( + reduction_output=reduction.output_name, + group=reduction.group, + axis=reduction.axis, + reduction_type=reduction.reduction_type, + source_type=reduction.source_type, + primary_output=original_buffer_name, + ) + feed_main = plan.feed_main + if feed_main is not None: + local_reduce = GemmReductionPlan( + reduction_output=None, + group=feed_main.group, + axis=feed_main.axis, + reduction_type=feed_main.reduction_type, + source_type=feed_main.source_type, + primary_output=feed_main.output_name, + feeds_main=True, + ) + epilogue_fn_code = ( + f"def {EPILOGUE_FN_NAME}(accum):\n D = accum\n return D" + ) + epilogue_writes = [feed_main.output_name] + epilogue_var_renames = { + _ACCUMULATOR_ARG_NAME: original_buffer_name, + "D": feed_main.output_name, + } + evt_nodes = [] if feed_main is not None else plan.evt_nodes + fused_buffer_names: OrderedSet[str] = OrderedSet( + n.get_name() for n in epilogue_nodes + ) + fused_buffer_names.add(original_buffer_name) + removed_buffers_with_gemm = V.graph.removed_buffers.copy() + if scheduler.can_buffer_be_removed_through_fusion( + original_buffer_name, fused_buffer_names + ): + removed_buffers_with_gemm.add(original_buffer_name) + + if evt_nodes: + evt_buffers = [ + node.node + for node in evt_nodes + if isinstance(node.node, ComputedBuffer) + ] + try: + reads, writes, var_renames, evt_code = ( + LoopIRCuteDSLCodegen.from_buffers( + original_buffer_name, + evt_buffers, + removed_buffers_with_gemm, + EPILOGUE_FN_NAME, + ) + ) + except NotImplementedError: + reads, writes, var_renames, evt_code = ( + CutlassEVTCodegen.ir_to_evt_python_code( + original_buffer_name, + list(evt_nodes), + removed_buffers_with_gemm, + fn_name=EPILOGUE_FN_NAME, + as_standalone_function=True, + ) + ) + epilogue_fn_code = evt_code + epilogue_reads = reads + epilogue_writes = writes + epilogue_var_renames = var_renames + + if not only_gen_src_code: + write_bufs = OrderedSet(epilogue_writes) + if local_reduce is not None: + write_bufs.update(local_reduce.auxiliary_outputs) + for node in epilogue_nodes: + node_name = node.get_name() + if node_name in write_bufs: + continue + if scheduler.can_buffer_be_removed_through_fusion( + node_name, fused_buffer_names + ): + V.graph.removed_buffers.add(node_name) + if ( + original_buffer_name not in write_bufs + and scheduler.can_buffer_be_removed_through_fusion( + original_buffer_name, fused_buffer_names + ) + ): + V.graph.removed_buffers.add(original_buffer_name) + for node in epilogue_nodes: + node.mark_run() + + log.debug( + "NVGEMM epilogue fusion: %d nodes, reads=%s, writes=%s, local_reduce=%s", + len(epilogue_nodes), + epilogue_reads, + epilogue_writes, + local_reduce, + ) + except (NotImplementedError, AssertionError) as e: + log.warning("NVGEMM epilogue codegen failed unexpectedly: %s", e) + raise + + if ctb.make_kernel_render is None: + raise AssertionError("expected ctb.make_kernel_render to be not None") + kernel, render = ctb.make_kernel_render( + ctb, + epilogue_fn_code=epilogue_fn_code, + epilogue_reads=epilogue_reads, + epilogue_writes=epilogue_writes, + epilogue_var_renames=epilogue_var_renames, + local_reduce=local_reduce, + ) + + if not only_gen_src_code: + template_node.mark_run() + + src_code = render() + + if only_gen_src_code: + return src_code + + # Precompile only base (non-EFC) kernels. EFC kernels produce + # closure-wrapped artifacts that can't be serialized to disk cache. + if epilogue_nodes: + precompile_metadata = None + else: + precompile_metadata = self._build_precompile_metadata(kernel, ctb) + + with V.set_kernel_handler(kernel): + node_schedule: list[BaseSchedulerNode] = [template_node] + if epilogue_nodes: + node_schedule.extend(epilogue_nodes) + kernel_name = self.define_kernel( + src_code, node_schedule, precompile_metadata + ) + + self.codegen_comment(node_schedule, kernel_name) + kernel.call_kernel(kernel_name, ctb) + V.graph.removed_buffers |= kernel.removed_buffers + V.graph.inplaced_to_remove |= kernel.inplaced_to_remove + self.free_buffers_in_scheduler() + return None + + def _build_precompile_metadata(self, kernel, ctb): + """Extract shapes and dtypes from kernel inputs/output for subprocess precompilation. + + Only called for base (non-epilogue) kernels. Returns None if shapes are + symbolic (dynamic shapes), in which case the subprocess will skip + precompilation and the kernel compiles lazily on first call. + """ + if not hasattr(kernel, "_template_input_args"): + return None + + precompile_shapes = {} + precompile_strides = {} + precompile_dtypes = {} + + try: + for param_name, input_node in kernel._template_input_args: + size = input_node.get_size() + precompile_shapes[param_name] = [int(s) for s in size] + stride = input_node.get_stride() + precompile_strides[param_name] = [int(s) for s in stride] + precompile_dtypes[param_name] = str( + input_node.get_dtype() + ).removeprefix("torch.") + + out_layout = cast(Layout, ctb.layout) + precompile_shapes["output"] = [int(s) for s in out_layout.size] + precompile_strides["output"] = [int(s) for s in out_layout.stride] + precompile_dtypes["output"] = str(out_layout.dtype).removeprefix("torch.") + except (TypeError, RuntimeError, ValueError): + log.debug( + "Skipping NV Universal GEMM precompile metadata: symbolic sizes " + "cannot be resolved to concrete values" + ) + return None + + device = ctb.layout.device + device_index = device.index if device.index is not None else 0 + + import torch + + device_capability = None + if torch.cuda.is_available(): + device_capability = torch.cuda.get_device_capability(device_index) + + max_active_clusters = None + kernel_name = ctb.kernel_metadata.get("kernel_name") + try: + if kernel_name and torch.cuda.is_available(): + from torch._inductor.codegen.nv_universal_gemm.kernel_cache import ( + get_kernel_by_name, + ) + + k = get_kernel_by_name(kernel_name) + if k is not None and hasattr(k, "impl"): + from cutlass.operators.providers.cutedsl.integration_utils.mma import ( + get_max_active_clusters, + ) + + max_active_clusters = get_max_active_clusters( + k.impl.cluster_shape_mn + ) + except Exception: + log.debug( + "Failed to resolve max_active_clusters for precompile", exc_info=True + ) + + return { + "precompile_shapes": precompile_shapes, + "precompile_strides": precompile_strides, + "precompile_dtypes": precompile_dtypes, + "device_index": device_index, + "device_capability": device_capability, + "max_active_clusters": max_active_clusters, + } + + def generate_kernel_code_from_nodes( + self, + nodes: Sequence[BaseSchedulerNode], + benchmark_kernel: bool = False, + hint_override: int | None = None, + ) -> str: + prologue, template, epilogue = nodes[0].get_prologue_template_epilogue( + list(nodes) + ) + + epilogue_reads: list[str] = [] + output_bufs: list[str] = [] + if epilogue: + template_sn = cast(SchedulerNode, template) + if not isinstance(template_sn.node, Buffer): + raise AssertionError(f"expected Buffer, got {type(template_sn.node)}") + original_buffer_name = template_sn.node.get_name() + plan = self._epilogue_plan(template_sn.node, epilogue) + evt_nodes = [] if plan.feed_main is not None else plan.evt_nodes + removed_buffers_with_gemm = V.graph.removed_buffers.copy() + if not plan.reductions: + removed_buffers_with_gemm.add(original_buffer_name) + try: + if evt_nodes: + reads, writes, var_renames, _ = ( + CutlassEVTCodegen.ir_to_evt_python_code( + original_buffer_name, + evt_nodes, + removed_buffers_with_gemm, + ) + ) + epilogue_reads = reads + d_buf = var_renames.get("D") + output_bufs = ([d_buf] if d_buf else []) + [ + w for w in writes if w != d_buf + ] + if plan.reductions: + output_bufs = [ + original_buffer_name, + *output_bufs, + plan.reductions[0].output_name, + ] + elif plan.feed_main is not None: + output_bufs = [plan.feed_main.output_name] + except (NotImplementedError, AssertionError) as e: + log.warning("NVGEMM benchmark epilogue codegen failed: %s", e) + + with config.patch("benchmark_kernel", benchmark_kernel): + src_code = self.codegen_template( + template, + epilogue, + prologue, + only_gen_src_code=True, + ) + + if src_code is None: + raise AssertionError("expected src_code to be not None") + src_code = src_code.replace( + str(Placeholder.KERNEL_NAME), _BENCHMARK_KERNEL_PREFIX + ) + + if benchmark_kernel: + src_code = self._add_benchmark_helpers( + src_code, template, epilogue, epilogue_reads, output_bufs + ) + + return src_code + + def _add_benchmark_helpers( + self, + src_code: str, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + epilogue_reads: list[str], + output_bufs: list[str] | None = None, + ) -> str: + template_node = cast(SchedulerNode, template_node) + ctb: NVUniversalGemmBuffer = self.get_nv_gemm_buffer_from_node( + template_node, require_epilogue_fusion=bool(epilogue_nodes) + ) + + input_nodes = cast(list[Buffer], ctb.inputs) + # Output store layouts in out_ptr order. A multi-store epilogue has one + # per graph output; otherwise a single output (the fused final node, or + # the plain GEMM layout). + output_layouts: list[Layout] = [] + if output_bufs: + for b in output_bufs: + buf = V.graph.get_buffer(b) + # pyrefly: ignore [missing-attribute] + output_layouts.append(cast(Layout, buf.get_layout())) + elif epilogue_nodes: + final_node = cast(SchedulerNode, epilogue_nodes[-1]) + # pyrefly: ignore [missing-attribute] + output_layouts.append(cast(Layout, final_node.node.get_layout())) + else: + output_layouts.append(cast(Layout, ctb.layout)) + + args_code = IndentedBuffer() + args_code.writeline("") + args_code.writeline("is_nvgemm = True") + args_code.writeline("") + args_code.writeline("def get_args():") + with args_code.indent(): + args_code.writeline("import torch") + args_code.writeline("from torch._dynamo.testing import rand_strided") + args_code.writeline("args = []") + + for inp in input_nodes: + size = V.graph.sizevars.optimization_hints(inp.get_size()) + stride = V.graph.sizevars.optimization_hints(inp.get_stride()) + dtype = inp.get_dtype() + device = inp.get_device() + args_code.writeline( + f"args.append(rand_strided({size}, {stride}, device='{device}', dtype={dtype}))" + ) + + for ol in output_layouts: + out_size = V.graph.sizevars.optimization_hints(ol.size) + out_stride = V.graph.sizevars.optimization_hints(ol.stride) + args_code.writeline( + f"args.append(rand_strided({out_size}, {out_stride}, device='{ol.device}', dtype={ol.dtype}))" + ) + + for read_name in epilogue_reads: + buf = V.graph.get_buffer(read_name) + size = V.graph.sizevars.optimization_hints(buf.get_size()) + stride = V.graph.sizevars.optimization_hints(buf.get_stride()) + dtype = buf.get_dtype() + device = buf.get_device() + args_code.writeline( + f"args.append(rand_strided({size}, {stride}, device='{device}', dtype={dtype}))" + ) + + if ctb.workspace_size > 0: + args_code.writeline( + f"args.append(torch.empty({ctb.workspace_size}, " + f"device='{output_layouts[0].device}', dtype=torch.int8))" + ) + + args_code.writeline("return args") + + args_code.writeline("") + args_code.writeline("def call(args):") + with args_code.indent(): + args_code.writeline("import torch") + num_inputs = len(input_nodes) + n_fixed = num_inputs + len(output_layouts) + param_list = [f"args[{i}]" for i in range(n_fixed)] + + for j in range(len(epilogue_reads)): + param_list.append(f"args[{n_fixed + j}]") + + if ctb.workspace_size > 0: + param_list.append(f"args[{n_fixed + len(epilogue_reads)}]") + + params_str = ", ".join(param_list) + args_code.writeline("stream = torch.cuda.current_stream().cuda_stream") + bench_fn_name = f"{_BENCHMARK_KERNEL_PREFIX}_{MAIN_SUFFIX}" + args_code.writeline(f"{bench_fn_name}({params_str}, stream=stream)") + + return src_code + args_code.getvalue() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7a0ca95a72414ffbbc75fdef400d94aed6786cb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_utils.py @@ -0,0 +1,126 @@ +# mypy: allow-untyped-defs +""" +Utility functions for NVIDIA Universal GEMM. +""" + +import copyreg +from typing import Any + +from torch.nn.functional import ScalingType, SwizzleType + + +def _rebuild_scaling_type(name: str) -> Any: + return getattr(ScalingType, name) + + +def _rebuild_swizzle_type(name: str) -> Any: + return getattr(SwizzleType, name) + + +def _register_enum_pickling() -> None: + """Make torch.nn.functional ScalingType/SwizzleType picklable. + + They are pybind11 C++ enums whose class __qualname__ is `_ScalingType` / + `_SwizzleType`, but torch.nn.functional only binds the public names + `ScalingType` / `SwizzleType`. Pickle's default reduction reconstructs by + the private qualname and fails, which blocks shipping a scaled-GEMM + benchmark request to the autotuning subprocess pool. Reduce by `.name` + string via the public alias instead (no class object in the pickle). + """ + copyreg.pickle( + type(ScalingType.BlockWise1x16), + lambda v: (_rebuild_scaling_type, (v.name,)), + ) + copyreg.pickle( + type(SwizzleType.NO_SWIZZLE), + lambda v: (_rebuild_swizzle_type, (v.name,)), + ) + + +_register_enum_pickling() + + +def _rebuild_scaled_operand_constraints( + quantized: Any, scale: Any, mode: Any, swizzle: Any +) -> Any: + from cutlass.operators.metadata import ScaledOperandConstraints + + return ScaledOperandConstraints(quantized, scale, mode, swizzle) + + +def _register_scaled_operand_constraints_pickling() -> None: + """Avoid CUTLASS's recursive ``__getattr__`` during unpickling.""" + try: + from cutlass.operators.metadata import ScaledOperandConstraints + except ImportError: + return + + copyreg.pickle( + ScaledOperandConstraints, + lambda value: ( + _rebuild_scaled_operand_constraints, + (value.quantized, value.scale, value.mode, value.swizzle), + ), + ) + + +_register_scaled_operand_constraints_pickling() + + +def to_cutlass_scale_mode( + scale_type: Any, swizzle_type: Any +) -> tuple[Any | None, Any | None]: + """ + Map PyTorch ScalingType/SwizzleType to cutlass.operators ScaleMode/ScaleSwizzleMode. + + Args: + scale_type: ScalingType from torch.nn.functional + swizzle_type: SwizzleType from torch.nn.functional + + Returns: + Tuple of (ScaleMode, ScaleSwizzleMode) from cutlass.operators, + or (None, None) if the types are not supported. + + The returned enum objects can be used directly with cutlass.operators, or their + .name attribute can be used for codegen (e.g., scale_mode.name -> "Blockwise1x32"). + + NOTE: + Currently on Blackwell (SM100), NVGEMM only supports MXFP8 scaling modes. + Update this mapping when additional scaling modes are added. + """ + from cutlass.operators import ScaleMode, ScaleSwizzleMode + + scale_mode_map = { + ScalingType.BlockWise1x32: ScaleMode.Blockwise1x32, + ScalingType.BlockWise1x16: ScaleMode.Blockwise1x16, + } + swizzle_mode_map = { + SwizzleType.SWIZZLE_32_4_4: ScaleSwizzleMode.Swizzle32x4x4, + SwizzleType.NO_SWIZZLE: ScaleSwizzleMode.SwizzleNone, + } + return scale_mode_map.get(scale_type), swizzle_mode_map.get(swizzle_type) + + +# NOTE: cutlass.torch.dtype() doesn't support Float4E2M1FN (raises TypeError), +# so we maintain our own mapping that includes FP4. +_CUTLASS_TO_TORCH_DTYPE: dict | None = None + + +def cutlass_dtype_to_torch(cutlass_dtype: Any) -> "Any | None": + """Map a cutlass dtype to the corresponding torch dtype.""" + import torch + + global _CUTLASS_TO_TORCH_DTYPE + if _CUTLASS_TO_TORCH_DTYPE is None: + import cutlass + + _CUTLASS_TO_TORCH_DTYPE = { + cutlass.Float4E2M1FN: torch.float4_e2m1fn_x2, + cutlass.Float8E4M3FN: torch.float8_e4m3fn, + cutlass.Float8E5M2: torch.float8_e5m2, + cutlass.Float8E8M0FNU: torch.float8_e8m0fnu, + cutlass.BFloat16: torch.bfloat16, + cutlass.Float16: torch.float16, + cutlass.Float32: torch.float32, + } + return _CUTLASS_TO_TORCH_DTYPE.get(cutlass_dtype) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/pallas.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/pallas.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab5b394caf5027f861363406b71e7ea668670c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/pallas.py @@ -0,0 +1,4986 @@ +from __future__ import annotations + +import dataclasses +import hashlib +import math +import re +import typing_extensions +from typing import Any, cast, TYPE_CHECKING + +import sympy + +import torch +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import ( + Max as TorchMax, + Min as TorchMin, + ModularIndexing, +) + +from .. import config +from ..runtime.runtime_utils import torch_dtype_to_jax +from ..utils import get_fused_kernel_name, get_kernel_metadata +from ..virtualized import V +from .block_analysis import BlockPatternMatcher +from .common import ( + BackendFeature, + CSEVariable, + IndentedBuffer, + OpOverrides, + PythonPrinter, +) +from .simd import IterationRangesEntry, SIMDKernel, SIMDScheduling + + +class PallasPrinter(PythonPrinter): + """ + Custom sympy printer for Pallas that handles JAX-specific constructs. + """ + + def _print_Where(self, expr: sympy.Expr) -> str: + """Convert sympy Where to jnp.where.""" + c = self.doprint(expr.args[0]) + p = self.doprint(expr.args[1]) + q = self.doprint(expr.args[2]) + return f"jnp.where({c}, {p}, {q})" + + def _print_Min(self, expr: sympy.Expr) -> str: + """Convert sympy Min to jnp.minimum for JAX compatibility.""" + args = [self.doprint(arg) for arg in expr.args] + result = args[0] + for arg in args[1:]: + result = f"jnp.minimum({result}, {arg})" + return result + + def _print_Max(self, expr: sympy.Expr) -> str: + """Convert sympy Max to jnp.maximum for JAX compatibility.""" + args = [self.doprint(arg) for arg in expr.args] + result = args[0] + for arg in args[1:]: + result = f"jnp.maximum({result}, {arg})" + return result + + +# Use Pallas-specific printer for expression generation +pallas_pexpr = PallasPrinter().doprint + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from ..ir import IRNode + from ..ops_handler import ReductionType + from ..scheduler import BaseSchedulerNode + + +# Main function suffix used in generated Pallas code +MAIN_SUFFIX = "main" + +# Logger for Pallas kernel code +kernel_code_log = torch._logging.getArtifactLogger(__name__, "kernel_code") + + +class PallasKernelWrapper: + """Wrapper to provide .run() interface for Pallas kernels""" + + def __init__(self, kernel_fn: Callable[..., Any], kernel_path: str | None = None): + self.kernel_fn = kernel_fn + self.kernel_path = kernel_path + kernel_code_log.info("Pallas kernel path: %s", kernel_path) + + def run(self, *args, stream=None, **kwargs): + """ + Execute the Pallas kernel. + + Args: + *args: Arguments to pass to the kernel function + stream: CUDA stream to pass to the kernel function + **kwargs: Additional keyword arguments for the kernel + + Returns: + Result of the kernel execution + """ + return self.kernel_fn(*args, stream=stream, **kwargs) + + +class Unsupported(RuntimeError): + """Exception raised when an operation is not supported by the Pallas backend.""" + + +class PallasKernelOverrides(OpOverrides): + """ + Map element-wise ops to JAX/Pallas operations. + + For now, we use the default Python operators which are compatible + with JAX numpy broadcasting semantics. + """ + + @staticmethod + # pyrefly: ignore [bad-override] + def sin(x: str) -> str: + return f"jnp.sin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cos(x: str) -> str: + return f"jnp.cos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tan(x: str) -> str: + return f"jnp.tan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sinh(x: str) -> str: + return f"jnp.sinh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cosh(x: str) -> str: + return f"jnp.cosh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tanh(x: str) -> str: + return f"jnp.tanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asin(x: str) -> str: + return f"jnp.arcsin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acos(x: str) -> str: + return f"jnp.arccos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x: str) -> str: + return f"jnp.arctan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def exp(x: str) -> str: + return f"jnp.exp({x})" + + @staticmethod + def exp2(x: str) -> str: + return f"jnp.exp2({x})" + + @staticmethod + def expm1(x: str) -> str: + return f"jnp.expm1({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def log(x: str) -> str: + return f"jnp.log({x})" + + @staticmethod + def log10(x: str) -> str: + return f"jnp.log10({x})" + + @staticmethod + def log2(x: str) -> str: + return f"jnp.log2({x})" + + @staticmethod + def log1p(x: str) -> str: + return f"jnp.log1p({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sqrt(x: str) -> str: + return f"jnp.sqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def rsqrt(x: str) -> str: + return f"jax.lax.rsqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def abs(x: str) -> str: + return f"jnp.abs({x})" + + @staticmethod + def neg(x: str) -> str: + return f"(-{x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def floor(x: str) -> str: + return f"jnp.floor({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def ceil(x: str) -> str: + return f"jnp.ceil({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def trunc(x: str) -> str: + return f"jnp.trunc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def round(x: str) -> str: + return f"jnp.round({x})" + + @staticmethod + def sigmoid(x: str) -> str: + return f"jax.nn.sigmoid({x})" + + @staticmethod + def relu(x: str) -> str: + return f"jnp.maximum({x}, 0)" + + @staticmethod + def pow(a: str, b: str) -> str: + return f"jnp.power({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a: str, b: str) -> str: + return f"jnp.maximum({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a: str, b: str) -> str: + return f"jnp.minimum({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def where(cond: str, a: str, b: str) -> str: + return f"jnp.where({cond}, {a}, {b})" + + @staticmethod + def masked(mask: str, body: Callable[[], str], other: float) -> str: + """ + Computes body, but only uses the result where mask is true. + Where mask is false, uses the 'other' value instead. + """ + result = body() + # Format the 'other' value properly for JAX + if isinstance(other, float): + if math.isnan(other): + other_str = "jnp.nan" + elif math.isinf(other): + other_str = "jnp.inf" if other > 0 else "-jnp.inf" + else: + other_str = repr(other) + else: + other_str = repr(other) + # Use jnp.where to select between result and other based on mask + return f"jnp.where({mask}, {result}, {other_str})" + + @staticmethod + def to_dtype( + x: str, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = True, + ) -> str: + # TPU doesn't support 64-bit types + if dtype == torch.int64 and V.graph.get_current_device_or_throw().type == "tpu": + dtype = torch.int32 + jax_dtype = torch_dtype_to_jax(dtype) + # Wrap in jnp.asarray to handle scalars from integer indexing + return f"jnp.asarray({x}).astype({jax_dtype})" + + @staticmethod + def to_dtype_bitcast(x: str, dtype: torch.dtype, src_dtype: torch.dtype) -> str: + """Bitcast a value from one dtype to another with the same size.""" + jax_dtype = torch_dtype_to_jax(dtype) + jax_src_dtype = torch_dtype_to_jax(src_dtype) + # First ensure the value is the correct source dtype, then bitcast + return f"jax.lax.bitcast_convert_type(jnp.asarray({x}).astype({jax_src_dtype}), {jax_dtype})" + + @staticmethod + def index_expr(expr: sympy.Expr, dtype: torch.dtype) -> str: + """Convert a sympy expression to a JAX array indexing expression.""" + from ..utils import get_bounds_index_expr + + # Track which iteration variables are used + V.kernel.used_iter_vars.update(V.kernel._get_used_iter_vars(expr)) + + # Prepare and rename indexing to register size symbols as kernel args + prepared = V.kernel.prepare_indexing(expr) + renamed = V.kernel.rename_indexing(prepared) + idx_str = V.kernel.kexpr(renamed) + var = V.kernel.cse.generate( + V.kernel.compute, idx_str, bounds=get_bounds_index_expr(expr) + ) + return PallasKernelOverrides.to_dtype(var, dtype) + + @staticmethod + def value_expr(expr: sympy.Expr, dtype: torch.dtype) -> str: + # Pallas index_expr already emits the requested dtype, so value_expr has + # the same lowering here. + return PallasKernelOverrides.index_expr(expr, dtype) + + @staticmethod + def constant(val, dtype: torch.dtype) -> str: + """Convert a constant value to JAX representation.""" + jax_dtype = torch_dtype_to_jax(dtype) + if dtype == torch.bool: + return "True" if val else "False" + # Handle special float values + if isinstance(val, float): + if math.isnan(val): + return "jnp.nan" + if math.isinf(val): + return "jnp.inf" if val > 0 else "-jnp.inf" + return f"jnp.array({val}, dtype={jax_dtype})" + + @staticmethod + def real(x: str) -> str: + return f"jnp.real({x})" + + @staticmethod + def imag(x: str) -> str: + return f"jnp.imag({x})" + + @staticmethod + def conj(x: str) -> str: + return f"jnp.conj({x})" + + @staticmethod + def angle(x: str) -> str: + return f"jnp.angle({x})" + + @staticmethod + def view_as_real(x: str) -> str: + """View complex tensor as real tensor with extra dimension.""" + return f"jnp.stack([jnp.real({x}), jnp.imag({x})], axis=-1)" + + @staticmethod + def view_as_complex(x: str) -> str: + """View real tensor as complex tensor.""" + return f"({x}[..., 0] + 1j * {x}[..., 1])" + + # Comparison operations + @staticmethod + def eq(a: str, b: str) -> str: + return f"({a} == {b})" + + @staticmethod + def ne(a: str, b: str) -> str: + return f"({a} != {b})" + + @staticmethod + def lt(a: str, b: str) -> str: + return f"({a} < {b})" + + @staticmethod + def le(a: str, b: str) -> str: + return f"({a} <= {b})" + + @staticmethod + def gt(a: str, b: str) -> str: + return f"({a} > {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def isnan(x: str) -> str: + return f"jnp.isnan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def isinf(x: str) -> str: + return f"jnp.isinf({x})" + + @staticmethod + def isfinite(x: str) -> str: + return f"jnp.isfinite({x})" + + @staticmethod + def ge(a: str, b: str) -> str: + return f"({a} >= {b})" + + # Logical operations + @staticmethod + # pyrefly: ignore [bad-override] + def logical_and(a: str, b: str) -> str: + return f"jnp.logical_and({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_or(a: str, b: str) -> str: + return f"jnp.logical_or({a}, {b})" + + @staticmethod + def logical_not(x: str) -> str: + return f"jnp.logical_not({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_xor(a: str, b: str) -> str: + return f"jnp.logical_xor({a}, {b})" + + # Math operations + @staticmethod + # pyrefly: ignore [bad-override] + def atan2(a: str, b: str) -> str: + return f"jnp.arctan2({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def hypot(a: str, b: str) -> str: + return f"jnp.hypot({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmod(a: str, b: str) -> str: + return f"jnp.fmod({a}, {b})" + + @staticmethod + def remainder(a: str, b: str) -> str: + return f"jnp.remainder({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def truncdiv(a: str, b: str) -> str: + # Truncated division (rounds toward zero) + # For integers: sign(a)*sign(b) * (abs(a) // abs(b)) + return f"(jnp.sign({a}) * jnp.sign({b}) * (jnp.abs({a}) // jnp.abs({b}))).astype({a}.dtype)" + + @staticmethod + def floordiv(a: str, b: str) -> str: + return f"({a} // {b})" + + @staticmethod + def clamp(x: str, min_val: str, max_val: str) -> str: + return f"jnp.clip({x}, {min_val}, {max_val})" + + clip = clamp + + # Sign operations + @staticmethod + # pyrefly: ignore [bad-override] + def sign(x: str) -> str: + # PyTorch returns 0 for NaN, JAX returns NaN + return f"jnp.where(jnp.isnan({x}), 0.0, jnp.sign({x}))" + + @staticmethod + # pyrefly: ignore [bad-override] + def signbit(x: str) -> str: + return f"jnp.signbit({x})" + + # Special math functions + @staticmethod + # pyrefly: ignore [bad-override] + def erf(x: str) -> str: + return f"jax.scipy.special.erf({x})" + + @staticmethod + def erfc(x: str) -> str: + return f"jax.scipy.special.erfc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def erfinv(x: str) -> str: + return f"jax.scipy.special.erfinv({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def lgamma(x: str) -> str: + return f"jax.scipy.special.gammaln({x})" + + @staticmethod + def digamma(x: str) -> str: + return f"jax.scipy.special.digamma({x})" + + @staticmethod + def bessel_j0(x: str) -> str: + # bessel_jn requires float64 and has numerical issues at x=0 (returns NaN) + # bessel_jn(x, v=n) returns array of shape (n+1, ...) with J_0 to J_n + # Handle by: convert to float64, compute, handle x=0, convert back + # J0(0) = 1.0 + return ( + f"jnp.where({x}.astype(jnp.float64) == 0.0, 1.0, " + f"jax.scipy.special.bessel_jn({x}.astype(jnp.float64), v=0)[0])" + f".astype({x}.dtype)" + ) + + @staticmethod + def bessel_j1(x: str) -> str: + # bessel_jn requires float64 and has numerical issues at x=0 (returns NaN) + # bessel_jn(x, v=n) returns array of shape (n+1, ...) with J_0 to J_n + # Handle by: convert to float64, compute, handle x=0, convert back + # J1(0) = 0.0 + return ( + f"jnp.where({x}.astype(jnp.float64) == 0.0, 0.0, " + f"jax.scipy.special.bessel_jn({x}.astype(jnp.float64), v=1)[1])" + f".astype({x}.dtype)" + ) + + @staticmethod + def modified_bessel_i0(x: str) -> str: + # Modified Bessel function of the first kind I_0(x) + # I_0(x) = bessel_i0e(x) * exp(|x|) where bessel_i0e is the scaled version + return f"jax.lax.bessel_i0e({x}) * jnp.exp(jnp.abs({x}))" + + @staticmethod + def modified_bessel_i1(x: str) -> str: + # Modified Bessel function of the first kind I_1(x) + # I_1(x) = bessel_i1e(x) * exp(|x|) where bessel_i1e is the scaled version + return f"jax.lax.bessel_i1e({x}) * jnp.exp(jnp.abs({x}))" + + @staticmethod + def spherical_bessel_j0(x: str) -> str: + # Spherical Bessel function of the first kind j_0(x) = sin(x) / x + # Handle x=0: j_0(0) = 1 + return f"jnp.where({x} == 0.0, 1.0, jnp.sin({x}) / {x})" + + i0 = modified_bessel_i0 + + @staticmethod + def i0e(x: str) -> str: + # Exponentially scaled modified Bessel function I_0 + return f"jax.lax.bessel_i0e({x})" + + i1 = modified_bessel_i1 + + @staticmethod + def i1e(x: str) -> str: + # Exponentially scaled modified Bessel function I_1 + return f"jax.lax.bessel_i1e({x})" + + @staticmethod + def gammainc(x: str, y: str) -> str: + # Regularized lower incomplete gamma function P(a, x) + # Note: PyTorch uses gammainc(input, other) where input is a (shape param) + return f"jax.scipy.special.gammainc({x}, {y})" + + @staticmethod + def gammaincc(x: str, y: str) -> str: + # Regularized upper incomplete gamma function Q(a, x) + return f"jax.scipy.special.gammaincc({x}, {y})" + + igamma = gammainc + + igammac = gammaincc + + @staticmethod + def polygamma(x: str, y: str) -> str: + # Polygamma function psi^(n)(x), x is order n, y is the value + # Note: JAX uses polygamma(n, x) where n is integer order + return f"jax.scipy.special.polygamma({x}.astype(jnp.int32), {y})" + + @staticmethod + def ndtri(x: str) -> str: + # Inverse of the standard normal CDF + return f"jax.scipy.special.ndtri({x})" + + @staticmethod + def zeta(x: str, y: str) -> str: + # Hurwitz zeta function zeta(x, q) = sum_{k=0}^inf 1/(k+q)^x + return f"jax.scipy.special.zeta({x}, {y})" + + @staticmethod + def xlogy(x: str, y: str) -> str: + # x * log(y), with proper handling of x=0 + return f"jax.scipy.special.xlogy({x}, {y})" + + @staticmethod + def xlog1py(x: str, y: str) -> str: + # x * log1p(y), with proper handling of x=0 + return f"jax.scipy.special.xlog1py({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def chebyshev_polynomial_t(x: str, n: str) -> str: + # Chebyshev polynomial of the first kind T_n(x) + # For |x| <= 1: T_n(x) = cos(n * arccos(x)) + # For x > 1: T_n(x) = cosh(n * arccosh(x)) + # For x < -1: T_n(x) = (-1)^n * cosh(n * arccosh(-x)) + return ( + f"jnp.where(jnp.abs({x}) <= 1, " + f"jnp.cos({n} * jnp.arccos(jnp.clip({x}, -1, 1))), " + f"jnp.where({x} > 1, " + f"jnp.cosh({n} * jnp.arccosh(jnp.maximum({x}, 1.0))), " + f"((-1.0) ** {n}) * jnp.cosh({n} * jnp.arccosh(jnp.maximum(-{x}, 1.0)))))" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def chebyshev_polynomial_u(x: str, n: str) -> str: + # Chebyshev polynomial of the second kind U_n(x) + # For |x| < 1: U_n(x) = sin((n+1) * arccos(x)) / sqrt(1 - x^2) + # For x = 1: U_n(1) = n+1 + # For x = -1: U_n(-1) = (-1)^n * (n+1) + # For x > 1: U_n(x) = sinh((n+1) * arccosh(x)) / sqrt(x^2 - 1) + # For x < -1: U_n(x) = (-1)^n * U_n(-x) (symmetry) + return ( + f"jnp.where(jnp.abs({x}) < 1, " + f"jnp.sin(({n} + 1) * jnp.arccos(jnp.clip({x}, -1, 1))) / " + f"jnp.sqrt(jnp.maximum(1 - {x}**2, 1e-10)), " + f"jnp.where({x} >= 1, " + f"jnp.where({x} == 1, {n} + 1.0, " + f"jnp.sinh(({n} + 1) * jnp.arccosh(jnp.maximum({x}, 1.0))) / " + f"jnp.sqrt(jnp.maximum({x}**2 - 1, 1e-10))), " + f"jnp.where({x} == -1, ((-1.0) ** {n}) * ({n} + 1.0), " + f"((-1.0) ** {n}) * jnp.sinh(({n} + 1) * jnp.arccosh(jnp.maximum(-{x}, 1.0))) / " + f"jnp.sqrt(jnp.maximum({x}**2 - 1, 1e-10)))))" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def chebyshev_polynomial_v(x: str, n: str) -> str: + # Chebyshev polynomial of the third kind V_n(x) + # V_n(x) = (T_n(x) - T_{n+1}(x)) / (1 - x) for x != 1 + # V_n(1) = 1, recurrence: V_0 = 1, V_1 = 2x - 1, V_n = 2x*V_{n-1} - V_{n-2} + # Explicit: V_0 = 1, V_1 = 2x-1, V_2 = 4x^2-2x-1, V_3 = 8x^3-4x^2-4x+1 + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, 2*{x} - 1, " + f"jnp.where({n} == 2, 4*{x}**2 - 2*{x} - 1, " + f"jnp.where({n} == 3, 8*{x}**3 - 4*{x}**2 - 4*{x} + 1, " + f"jnp.where({n} == 4, 16*{x}**4 - 8*{x}**3 - 12*{x}**2 + 4*{x} + 1, " + f"jnp.where({n} == 5, 32*{x}**5 - 16*{x}**4 - 32*{x}**3 + 12*{x}**2 + 6*{x} - 1, " + f"jnp.zeros_like({x})))))))" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def chebyshev_polynomial_w(x: str, n: str) -> str: + # Chebyshev polynomial of the fourth kind W_n(x) + # W_n(x) = (T_n(x) + T_{n+1}(x)) / (1 + x) for x != -1 + # W_n(-1) = (-1)^n, recurrence: W_0 = 1, W_1 = 2x + 1, W_n = 2x*W_{n-1} - W_{n-2} + # Explicit: W_0 = 1, W_1 = 2x+1, W_2 = 4x^2+2x-1, W_3 = 8x^3+4x^2-4x-1 + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, 2*{x} + 1, " + f"jnp.where({n} == 2, 4*{x}**2 + 2*{x} - 1, " + f"jnp.where({n} == 3, 8*{x}**3 + 4*{x}**2 - 4*{x} - 1, " + f"jnp.where({n} == 4, 16*{x}**4 + 8*{x}**3 - 12*{x}**2 - 4*{x} + 1, " + f"jnp.where({n} == 5, 32*{x}**5 + 16*{x}**4 - 32*{x}**3 - 12*{x}**2 + 6*{x} + 1, " + f"jnp.zeros_like({x})))))))" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def shifted_chebyshev_polynomial_t(x: str, n: str) -> str: + return PallasKernelOverrides.chebyshev_polynomial_t(f"(2 * {x} - 1)", n) + + @staticmethod + # pyrefly: ignore [bad-override] + def shifted_chebyshev_polynomial_u(x: str, n: str) -> str: + return PallasKernelOverrides.chebyshev_polynomial_u(f"(2 * {x} - 1)", n) + + @staticmethod + # pyrefly: ignore [bad-override] + def shifted_chebyshev_polynomial_v(x: str, n: str) -> str: + return PallasKernelOverrides.chebyshev_polynomial_v(f"(2 * {x} - 1)", n) + + @staticmethod + # pyrefly: ignore [bad-override] + def shifted_chebyshev_polynomial_w(x: str, n: str) -> str: + return PallasKernelOverrides.chebyshev_polynomial_w(f"(2 * {x} - 1)", n) + + @staticmethod + # pyrefly: ignore [bad-override] + def hermite_polynomial_h(x: str, n: str) -> str: + # Physicist's Hermite polynomial H_n(x) + # H_n(x) = 2^n * x^n - n*(n-1)/2 * 2^(n-2) * x^(n-2) + ... + # Use explicit formula: H_n(x) = n! * sum_{m=0}^{n//2} (-1)^m / (m! * (n-2m)!) * (2x)^(n-2m) + # For simplicity, use the relation: H_n(x) = 2^(n/2) * He_n(x * sqrt(2)) where He is probabilist's + # Actually simpler: use recurrence or closed form + # H_0 = 1, H_1 = 2x, H_2 = 4x^2 - 2, H_3 = 8x^3 - 12x + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, 2 * {x}, " + f"jnp.where({n} == 2, 4 * {x}**2 - 2, " + f"jnp.where({n} == 3, 8 * {x}**3 - 12 * {x}, " + f"jnp.where({n} == 4, 16 * {x}**4 - 48 * {x}**2 + 12, " + f"jnp.where({n} == 5, 32 * {x}**5 - 160 * {x}**3 + 120 * {x}, " + f"jnp.zeros_like({x})))))))" # Fallback for higher n + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def hermite_polynomial_he(x: str, n: str) -> str: + # Probabilist's Hermite polynomial He_n(x) + # He_0 = 1, He_1 = x, He_2 = x^2 - 1, He_3 = x^3 - 3x + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, {x}, " + f"jnp.where({n} == 2, {x}**2 - 1, " + f"jnp.where({n} == 3, {x}**3 - 3 * {x}, " + f"jnp.where({n} == 4, {x}**4 - 6 * {x}**2 + 3, " + f"jnp.where({n} == 5, {x}**5 - 10 * {x}**3 + 15 * {x}, " + f"jnp.zeros_like({x})))))))" # Fallback for higher n + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def laguerre_polynomial_l(x: str, n: str) -> str: + # Laguerre polynomial L_n(x) + # L_0 = 1, L_1 = 1 - x, L_2 = (x^2 - 4x + 2)/2, L_3 = (-x^3 + 9x^2 - 18x + 6)/6 + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, 1 - {x}, " + f"jnp.where({n} == 2, ({x}**2 - 4*{x} + 2) / 2, " + f"jnp.where({n} == 3, (-{x}**3 + 9*{x}**2 - 18*{x} + 6) / 6, " + f"jnp.where({n} == 4, ({x}**4 - 16*{x}**3 + 72*{x}**2 - 96*{x} + 24) / 24, " + f"jnp.where({n} == 5, (-{x}**5 + 25*{x}**4 - 200*{x}**3 + 600*{x}**2 - 600*{x} + 120) / 120, " + f"jnp.zeros_like({x})))))))" # Fallback for higher n + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def legendre_polynomial_p(x: str, n: str) -> str: + # Legendre polynomial P_n(x) + # P_0 = 1, P_1 = x, P_2 = (3x^2 - 1)/2, P_3 = (5x^3 - 3x)/2 + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, {x}, " + f"jnp.where({n} == 2, (3 * {x}**2 - 1) / 2, " + f"jnp.where({n} == 3, (5 * {x}**3 - 3 * {x}) / 2, " + f"jnp.where({n} == 4, (35 * {x}**4 - 30 * {x}**2 + 3) / 8, " + f"jnp.where({n} == 5, (63 * {x}**5 - 70 * {x}**3 + 15 * {x}) / 8, " + f"jnp.zeros_like({x})))))))" # Fallback for higher n + ) + + # Reciprocal and square + @staticmethod + def reciprocal(x: str) -> str: + return f"jnp.reciprocal({x})" + + @staticmethod + def square(x: str) -> str: + return f"jnp.square({x})" + + # Additional operations + @staticmethod + def fma(a: str, b: str, c: str) -> str: + """Fused multiply-add: a * b + c + + JAX doesn't have jnp.fma, so we use the unfused version. + The compiler may still fuse this on supported hardware. + """ + return f"(({a}) * ({b}) + ({c}))" + + @staticmethod + # pyrefly: ignore [bad-override] + def copysign(a: str, b: str) -> str: + return f"jnp.copysign({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def nextafter(a: str, b: str) -> str: + return f"jnp.nextafter({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def ldexp(a: str, b: str) -> str: + return f"jnp.ldexp({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def frexp(x: str) -> str: + return f"jnp.frexp({x})" + + @staticmethod + def modf(x: str) -> str: + return f"jnp.modf({x})" + + # Bitwise operations + @staticmethod + def bitwise_and(a: str, b: str) -> str: + return f"jnp.bitwise_and({a}, {b})" + + @staticmethod + def bitwise_or(a: str, b: str) -> str: + return f"jnp.bitwise_or({a}, {b})" + + @staticmethod + def bitwise_xor(a: str, b: str) -> str: + return f"jnp.bitwise_xor({a}, {b})" + + @staticmethod + def bitwise_not(x: str) -> str: + return f"jnp.bitwise_not({x})" + + @staticmethod + def left_shift(a: str, b: str) -> str: + return f"jnp.left_shift({a}, {b})" + + @staticmethod + def right_shift(a: str, b: str) -> str: + return f"jnp.right_shift({a}, {b})" + + # Random number generation operations + @staticmethod + def load_seed(name: str, offset: str) -> str: + """Load the random seed value from a buffer.""" + # Load the seed from the buffer and add offset for uniqueness + # pyrefly: ignore[bad-argument-type] + seed_offset = V.kernel.args.seed_offset("load_seed_offset", offset) + return f"({V.kernel.args.input(name)}[0] + {seed_offset})" + + @staticmethod + def rand(seed: str, offset: str) -> str: + """Generate uniform random numbers in [0, 1). + + Uses JAX's threefry2x32 PRNG directly for vectorized random generation. + The seed provides the base key, offset provides per-element uniqueness. + """ + # For vectorized random, we use jax.random.uniform with shape from offset + # Create a base key from seed, then use fold_in with vmap for per-element keys + # Use float32 dtype to match PyTorch's default + return ( + f"jax.vmap(lambda o: jax.random.uniform(" + f"jax.random.fold_in(jax.random.PRNGKey(jnp.uint32({seed})), jnp.uint32(o)), (), dtype=jnp.float32))" + f"(jnp.asarray({offset}).flatten()).reshape(jnp.asarray({offset}).shape)" + ) + + @staticmethod + def randn(seed: str, offset: str) -> str: + """Generate standard normal random numbers. + + Uses JAX's threefry2x32 PRNG directly for vectorized random generation. + The seed provides the base key, offset provides per-element uniqueness. + """ + # For vectorized random, use vmap to fold in each offset value + # Use float32 dtype to match PyTorch's default + return ( + f"jax.vmap(lambda o: jax.random.normal(" + f"jax.random.fold_in(jax.random.PRNGKey(jnp.uint32({seed})), jnp.uint32(o)), (), dtype=jnp.float32))" + f"(jnp.asarray({offset}).flatten()).reshape(jnp.asarray({offset}).shape)" + ) + + @staticmethod + def randint64(seed: str, offset: str, low: str, high: str) -> str: + """Generate random int64 values in [low, high).""" + # For vectorized random, use vmap to fold in each offset value + return ( + f"jax.vmap(lambda o: jax.random.randint(" + f"jax.random.fold_in(jax.random.PRNGKey(jnp.uint32({seed})), jnp.uint32(o)), (), {low}, {high}, dtype=jnp.int64))" + f"(jnp.asarray({offset}).flatten()).reshape(jnp.asarray({offset}).shape)" + ) + + +@dataclasses.dataclass +class _IndirectAccessInfo: + """Describes a detected indirect (data-dependent) buffer access.""" + + table_param: str + table_buf_name: str + table_shape: tuple + indirect_dim: int + indirect_var: str + indices_param: str + + +@dataclasses.dataclass +class _BufferIndexing: + """Encapsulates index string and flattening requirements for buffer access.""" + + index_str: str + needs_flatten: bool + + +@dataclasses.dataclass +class _BroadcastedIterVar: + """Encapsulates information needed to codegen a broadcasted iteration var""" + + # index of this var in `self.range_tree_nodes.items()`` + idx: int + var_sym: sympy.Symbol + entry: IterationRangesEntry + length_val: int | None + + +@dataclasses.dataclass +class _CodegenContext: + """Bundles local state shared across codegen_kernel helper methods.""" + + code: IndentedBuffer + kernel_name: str + is_tpu: bool + interpret_is_cpu: bool + interpret_literal: str + kernel_params: list[str] + pure_out_params: list[str] + output_params: list[str] + size_var_params: list[str] + output_buffer_lookup: dict[str, str] + aliasable_flags: dict[str, bool] + alias_params: list[str] + pointer_tail: list[str] + kernel_input_params: list[str] + full_kernel_params: list[str] + non_alias_out_set: OrderedSet[str] + copy_output_indices: list[int] + alias_pairs: list[tuple[int, int]] + + +class PallasKernel(SIMDKernel): + """Pallas kernel codegen for TPU and GPU (Mosaic backend). + + Generates Python code that defines a Pallas kernel and a host entrypoint, + compiled and loaded via async_compile.pallas. + """ + + overrides = PallasKernelOverrides # type: ignore[assignment] + kexpr: Callable[[sympy.Expr], str] = pallas_pexpr # Use Pallas expression printer + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Determine device type once at initialization + device = V.graph.get_current_device_or_throw() + self.is_gpu = device.type == "cuda" + self.is_tpu = device.type == "tpu" + # Use TMA (Tensor Memory Accelerator) for GPU to handle non-aligned tensor sizes + # TMA automatically masks OOB accesses, eliminating the need for explicit + # padding to multiples of 128. Uses lax.fori_loop with direct TMA primitives. + self.use_emit_pipeline = self.is_gpu # Enable TMA approach for GPU + # Track which output param each store uses: list of (out_ptr_name, store_line) + self.store_with_output: list[tuple[str, str]] = [] + # Track load index expressions for reduction axis detection + self.load_index_exprs: dict[str, sympy.Expr] = {} + # Track outputs that need to be readable (for scatter operations) + self.outputs_need_read: OrderedSet[str] = OrderedSet() + # Map input buffer names to their detected permutation tuples. + self.permuted_input_buffers: dict[str, tuple[int, ...]] = {} + self.collapsed_reshape_inputs: dict[str, tuple[int, ...]] = {} + self.collapsed_output_shape: tuple[int, ...] | None = None + self._cpu_max_grid_product: int | None = None + # Precompute output buffer names from scheduler nodes so that the + # load path can check output shapes before stores are processed. + self._output_buffer_names: list[str] = [] + for snode in self.features.scheduler_nodes(): + for dep in snode.read_writes.writes: + self._output_buffer_names.append(dep.name) + # Track which iteration variables are actually used in the kernel + self.used_iter_vars: OrderedSet[sympy.Symbol] = OrderedSet() + # Iteration vars that have been emitted in tile-relative form + # (safe for tiling even when they appear in the compute body) + self.tile_relative_iter_vars: OrderedSet[sympy.Symbol] = OrderedSet() + # Track if any load/store uses flatten-based indexing (buf[...].flatten()[idx]) + self.has_flatten_indexing = False + # Strided input buffers: map graph buffer name -> per-dim + # (stride, offset, skip) triples. Used to reshape inputs outside + # the kernel and generate static indexing inside + # (e.g. in_ref[:, :, offset] instead of in_ref[...].flatten()[idx]). + self.strided_input_buffers: dict[str, list[tuple[int, int, int]]] = {} + # Buffers that already use flatten+gather indexing; strided + # decomposition must not reshape these (it would break flat offsets). + self.flatten_indexed_buffers: OrderedSet[str] = OrderedSet() + # Indirect (data-dependent) access info for scalar prefetch + self.indirect_access: _IndirectAccessInfo | None = None + self._cse_to_param: dict[str, str] = {} + self._param_to_graph_name: dict[str, str] = {} + self.is_tpu = device.type == "tpu" + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + """Check array bounds for indirect indexing.""" + # For now, skip explicit bounds checking as JAX/Pallas handles this internally + # TODO: Implement explicit bounds checking with assertions if needed + + def _get_index_str(self, index: sympy.Expr) -> str: + """ + Convert an index expression to a string suitable for Pallas indexing. + + Pallas operates on full arrays, so we need to convert index expressions + to JAX array slicing. For example: + - x0 -> "..." (contiguous access, full array) + - 2*x0 -> "::2" (strided access with stride 2) + - 2*x0 + 1 -> "1::2" (strided access with offset 1, stride 2) + + Args: + index: The indexing expression to convert + + Returns: + The indexing string to use in generated code + """ + # Prepare and simplify the index + prepared_index = self.prepare_indexing(index) + + # Note: Block variable detection (im2col patterns) is handled in load()/store() + # where we have access to buffer dimensions. We check the buffer size + # against iteration variables there to detect gather patterns. + + # For simple single-symbol access (contiguous case), we can use [...] + # which is more efficient as it operates on the entire array at once + if isinstance(prepared_index, sympy.Symbol): + return "..." + elif prepared_index.is_Integer: + # Scalar index + return str(prepared_index) + else: + # Complex expression (strided/scatter access) + # Try to extract stride and offset for common patterns + return self._convert_to_jax_slice(prepared_index) + + def _convert_to_jax_slice(self, index: sympy.Expr) -> str: + """ + Convert a sympy index expression to JAX slice notation. + + Handles common patterns like: + - stride*var -> ::stride + - stride*var + offset -> offset::stride + + For more complex patterns, falls back to explicit indexing. + Uses BlockPatternMatcher for robust pattern matching. + """ + # Get the iteration variables for this kernel + if not self.range_trees: + return "..." + + # Rename symbolic sizes to kernel parameter names upfront + index = self.rename_indexing(index) + + # Check for ModularIndexing - this is NOT contiguous access + # ModularIndexing is used for roll/wrap-around operations + if index.has(ModularIndexing): + # Track which iteration variables are used before returning + self.used_iter_vars.update(self._get_used_iter_vars(index)) + # Generate actual index expression - iteration variables are already + # defined as jnp.arange arrays, so we just convert to JAX code + return self.kexpr(index) + + # Simplify the index + index = V.graph.sizevars.simplify(index) + # Find which iteration variable(s) are used + used_vars = self._get_used_iter_vars(index) + + # Track which iteration variables are used + self.used_iter_vars.update(used_vars) + + if len(used_vars) == 0: + # No iteration variables, this is a constant index + return str(index) + elif len(used_vars) == 1: + # Single iteration variable - try to extract stride and offset using BlockPatternMatcher + var = next(iter(used_vars)) + + # Get the subexpression involving this variable + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(index, var) + + # Try to match affine pattern: stride * var + stride = BlockPatternMatcher.match_affine_block_expr(var_expr, var) + + if stride is not None: + offset = index - var_expr + offset = V.graph.sizevars.simplify(offset) + + if stride < 0: + return self.kexpr(index) + + if offset == 0: + return "..." + + # Non-zero offset: check if we can use slice notation + if stride != 1: + return self.kexpr(index) + + try: + offset_val = int(offset) + if offset_val < 0: + return self.kexpr(index) + except (TypeError, ValueError): + return self.kexpr(index) + + return f"{self.kexpr(offset)}::1" + else: + # Couldn't match affine pattern, fall back to original logic + offset = index - var_expr + offset = V.graph.sizevars.simplify(offset) + if offset == 0 and var_expr == var: + # Just the variable itself, unit stride + return "..." + elif len(used_vars) > 1: + # Multi-dimensional indexing + # For contiguous multi-dim access, all terms should have unit stride + all_unit_stride = True + for var in used_vars: + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(index, var) + stride = BlockPatternMatcher.match_affine_block_expr(var_expr, var) + if stride != 1: + all_unit_stride = False + break + if all_unit_stride: + # Contiguous multi-dimensional access + return "..." + else: + # Strided multi-dimensional access + # For most cases, inputs are made contiguous before passing to JAX, + # so strided tensors become contiguous and we can use [...] + # The buffer size check in load() handles im2col-like patterns + return "..." + + # For complex cases, use [...] since inputs are made contiguous + return "..." + + def _generate_strided_index(self, index: sympy.Expr) -> str: + """ + Generate JAX code to compute an index array for strided/complex indexing patterns. + + For expressions like `2 * x3 + 32 * x2 + 256 * x1 + 1024 * x0`, we generate + code that computes the flattened index array using broadcasting. + + The iteration variables (x0, x1, x2, x3) are already defined as jnp.arange arrays + in the kernel. We just need to convert the sympy expression to JAX code. + """ + free_symbols = index.free_symbols + iter_vars = self._get_iter_vars() + + # Check that all free symbols are iteration variables (no indirect vars) + used_vars = free_symbols & iter_vars + if used_vars != free_symbols: + raise Unsupported( + f"Pallas backend does not yet support mixed index pattern: {index}" + ) + + # Track which iteration variables are used + self.used_iter_vars.update(used_vars) + + # Convert sympy expression to Python/JAX code string + # The iteration variables are already defined as jnp.arange arrays + index_str = self.kexpr(index) + + # Mark this as requiring flatten access + return index_str + + def _get_iter_vars(self) -> OrderedSet: + """Get the set of iteration variable symbols.""" + return OrderedSet(self.range_tree_nodes.keys()) + + def _get_used_iter_vars(self, index: sympy.Expr) -> OrderedSet: + """Get iteration variables used in an index expression.""" + return index.free_symbols & self._get_iter_vars() + + def _has_iteration_vars(self, index: sympy.Expr) -> bool: + """Check if index expression contains iteration variables.""" + return bool(self._get_used_iter_vars(index)) + + def _get_indirect_vars(self, index: sympy.Expr) -> list[sympy.Symbol]: + """Get list of indirect variable symbols (tmp*) in an index expression.""" + return [s for s in index.free_symbols if str(s).startswith("tmp")] + + def _has_indirect_vars(self, index: sympy.Expr) -> bool: + """Check if index expression contains indirect variables.""" + return len(self._get_indirect_vars(index)) > 0 + + def _decompose_strided_access( + self, index: sympy.Expr, name: str + ) -> list[tuple[int, int, int]] | None: + """Decompose a flat index into per-dimension (stride, offset, skip) triples. + + Given flat index like ``64*x0 + 2*x1 + 5`` and buffer shape ``(32, 64)`` + with C-contiguous strides ``[64, 1]``: + - x0 coefficient 64 / buffer_stride[0]=64 -> dim 0: stride=1 + - x1 coefficient 2 / buffer_stride[1]=1 -> dim 1: stride=2 + - constant 5: dim 0 gets 5//64=0, dim 1 gets 5//1=5 + - dim 1 offset 5 with stride 2: skip=5//2=2, offset=5%2=1 + + Returns per-dim ``[(stride, offset, skip), ...]`` where: + - stride: access stride on this dim (1 = contiguous) + - offset: static index into the stride dim (0 <= offset < stride) + - skip: number of stride-blocks to skip at the start of this dim + Returns None if decomposition fails. + """ + if self._has_indirect_vars(index) or index.has(ModularIndexing): + return None + + # Don't reshape a buffer that already has flatten+gather loads; + # the reshape would change the flat layout and break those loads. + if name in self.flatten_indexed_buffers: + return None + + info = self._get_buffer_info(name) + if info is None: + return None + _, buf_size, _, _, _ = info + + buf_shape_or_none = [self._safe_int(s) for s in buf_size] + if any(s is None or s <= 0 for s in buf_shape_or_none): + return None + buf_shape: list[int] = cast(list[int], buf_shape_or_none) + ndim = len(buf_shape) + if ndim == 0: + return None + + c_strides = self._c_contiguous_strides(buf_shape) + + # Extract per-variable coefficients + used_vars = self._get_used_iter_vars(index) + if not used_vars: + return None + + # [stride, raw_offset] per dim — raw_offset may be >= stride + result: list[list[int]] = [[1, 0] for _ in range(ndim)] + # Track which variable maps to which dimension + var_to_dim: dict[sympy.Symbol, int] = {} + + remaining = V.graph.sizevars.simplify(index) + for var in used_vars: + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(remaining, var) + coeff = BlockPatternMatcher.match_affine_block_expr(var_expr, var) + if coeff is None: + return None + coeff_int = self._safe_int(coeff) + if coeff_int is None or coeff_int <= 0: + return None + + # Find which buffer dim this variable maps to + dim = None + for d in range(ndim): + if c_strides[d] == 0: + continue + if coeff_int % c_strides[d] == 0: + per_dim_stride = coeff_int // c_strides[d] + if per_dim_stride >= 1: + dim = d + break + if dim is None: + return None + + per_dim_stride = coeff_int // c_strides[dim] + if per_dim_stride < 1 or buf_shape[dim] % per_dim_stride != 0: + return None + + result[dim][0] = per_dim_stride + var_to_dim[var] = dim + remaining = V.graph.sizevars.simplify(remaining - var_expr) + + # Remaining is the constant offset; distribute across dims using + # divmod with C-contiguous strides (largest stride first). + offset_val = self._safe_int(remaining) + if offset_val is None: + return None + if offset_val < 0: + return None + for d in range(ndim): + if c_strides[d] > 0: + result[d][1] = offset_val // c_strides[d] + offset_val = offset_val % c_strides[d] + if offset_val != 0: + return None + + # Only return if there's at least one dim with stride > 1. + # Contiguous accesses with just an offset (stride=1 everywhere) + # are handled by the normal tiling path. + if all(s == 1 for s, _ in result): + return None + + # Decompose each dim's raw offset into (skip, offset) where + # offset < stride: raw = skip * stride + offset. + # Then validate the output numel matches. + decomposed: list[tuple[int, int, int]] = [] + output_numel_expected = 1 + for d in range(ndim): + stride, raw_offset = result[d] + offset = raw_offset % stride + skip = raw_offset // stride + n_blocks = buf_shape[d] // stride + if skip >= n_blocks: + return None + output_numel_expected *= n_blocks - skip + decomposed.append((stride, offset, skip)) + + output_numel, _ = self._compute_output_numel_from_index(index) + if output_numel != output_numel_expected: + return None + + # Verify each variable's range matches its assigned dimension's + # effective size. When the kernel collapses multiple buffer dims + # into one iteration variable (e.g. batch*channels), the variable + # range won't match any single buffer dimension and we must bail + # out to avoid shape mismatches in the generated code. + for var, dim in var_to_dim.items(): + if var not in self.range_tree_nodes: + return None + var_range = self._safe_int(self.range_tree_nodes[var].length) + if var_range is None: + return None + stride_d, _offset_d, skip_d = decomposed[dim] + effective_size = buf_shape[dim] // stride_d - skip_d + if var_range != effective_size: + return None + + return decomposed + + @staticmethod + def _strided_load_expr(buf: str, decomp: list[tuple[int, int, int]]) -> str: + """Build ``buf[:, :, offset]`` for strided dims, ``:`` for others.""" + parts: list[str] = [] + for stride, offset, _skip in decomp: + if stride == 1: + parts.append(":") + else: + parts.append(":") # the halved dim + parts.append(str(offset)) # static index into stride dim + return f"{buf}[{', '.join(parts)}]" + + def _codegen_strided_reshapes( + self, code: IndentedBuffer, params: list[str] + ) -> None: + """Emit reshape + optional slice for strided input parameters. + + For each strided param, reshapes ``(M, N)`` to ``(M, N/stride, stride)`` + and, when ``skip > 0``, slices off leading blocks so the remaining + elements align with the output. + """ + for param in params: + buf_name = self._param_to_buf_name(param) + if buf_name is None or buf_name not in self.strided_input_buffers: + continue + strides = self.strided_input_buffers[buf_name] + info = self._get_buffer_info(buf_name) + if info is None: + continue + _, buf_size, _, _, _ = info + new_shape_parts: list[str] = [] + for d, (stride, _offset, _skip) in enumerate(strides): + dim = self._safe_int(buf_size[d]) + if dim is None: + break + if stride > 1: + new_shape_parts.append(str(dim // stride)) + new_shape_parts.append(str(stride)) + else: + new_shape_parts.append(str(dim)) + else: + code.writeline( + f"{param} = {param}.reshape({', '.join(new_shape_parts)})" + ) + if any(skip > 0 for _, _, skip in strides): + slice_parts: list[str] = [] + for stride, _offset, skip in strides: + if stride == 1: + slice_parts.append(":") + else: + slice_parts.append(f"{skip}:" if skip > 0 else ":") + slice_parts.append(":") + code.writeline(f"{param} = {param}[{', '.join(slice_parts)}]") + + @staticmethod + def _get_actual_out_strides(out_buf, n: int) -> list[int] | None: + """Extract actual output buffer strides from its layout.""" + layout = getattr(out_buf, "get_layout", lambda: None)() + if layout is None: + return None + stride_raw = getattr(layout, "stride", None) + if stride_raw is None or len(stride_raw) != n: + return None + strides: list[int] = [] + for s in stride_raw: + v = int(s) if isinstance(s, (int, sympy.Integer)) else None + if v is None: + return None + strides.append(v) + return strides + + def _compute_store_coeffs(self, ordered: list) -> dict | None: + """Compute store-side linearization coefficients from range tree nesting. + + The tree structure encodes the output iteration order: later + trees (prefix ``x``) are innermost, earlier trees (``y``, ``z``) + are outer. Within a tree, dict order goes inner-to-outer. + The innermost variable gets coefficient 1; each successive + variable (moving outward) multiplies by the previous range. + + Returns ``{sympy.Symbol: int}`` mapping each RT var to its store + coefficient, or ``None`` on failure. + """ + prefix_groups: dict[str, list] = {} + prefix_order: list[str] = [] + for v in ordered: + node = self.range_tree_nodes[v] + p = node.prefix + if p not in prefix_groups: + prefix_groups[p] = [] + prefix_order.append(p) + prefix_groups[p].append(v) + inner_to_outer: list = [] + for p in reversed(prefix_order): + inner_to_outer.extend(prefix_groups[p]) + coeffs: dict = {} + coeff = 1 + for v in inner_to_outer: + sz = self._safe_int(self.range_tree_nodes[v].length) + if sz is None: + return None + coeffs[v] = coeff + coeff *= sz + return coeffs + + def _get_full_load_permutation( + self, name: str, index: sympy.Expr + ) -> tuple[int, ...] | None: + """Return permutation for a full-array load, or None. + + Computes the permutation by mapping each range-tree variable to + both an output dimension (via store coefficients + actual output + strides) and an input dimension (via load coefficients + input + C-contiguous strides). The permutation is then: + + perm[out_dim] = in_dim for each RT variable + + Using actual output strides (not C-contiguous) is critical: the + scheduler may choose a non-standard output layout (e.g. column- + major) to optimise for transposed inputs. + + When all dimensions collapse to a single flat RT variable (e.g. + (2,2,2,2,2) with all dims size 2), infers the permutation + directly from output strides vs input C-contiguous strides. + """ + info = self._get_buffer_info(name) + if not info: + return None + _, buf_size, _, _, is_contiguous = info + in_shape_raw = [self._safe_int(s) for s in buf_size] + if len(in_shape_raw) < 2 or None in in_shape_raw: + return None + in_shape: list[int] = cast(list[int], in_shape_raw) + if not is_contiguous: + return None # .contiguous() at JAX boundary handles this + + # Extract index coefficients for each non-reduction RT variable. + iter_used = self._get_used_iter_vars(index) + ordered = [ + s + for s, e in self.range_tree_nodes.items() + if s in iter_used and not e.is_reduction + ] + if len(ordered) != len(in_shape): + # All dims may have collapsed to a single flat RT variable + # (e.g. (2,2,2,2,2) → single x0 of length 32). In this + # case, infer the permutation directly from output strides + # vs input C-contiguous strides. + n = len(in_shape) + if len(ordered) == 1 and self._safe_int( + self.range_tree_nodes[ordered[0]].length + ) == math.prod(in_shape): + in_strides = self._c_contiguous_strides(in_shape) + for out_name in self._output_buffer_names: + out_buf = V.graph.get_buffer(out_name) + if out_buf is None: + continue + out_shape = [self._safe_int(s) for s in out_buf.get_size()] + if any(s is None for s in out_shape) or len(out_shape) != n: + continue + actual = self._get_actual_out_strides(out_buf, n) + if actual is None: + break + # Map each output dim to the input dim with the + # same stride. + perm = self._map_coeffs_to_dims(actual, in_strides) + if perm is None: + break + if list(perm) == list(range(n)): + return None + return tuple(perm) + return None + coeffs_raw = [ + self._get_index_coefficient(V.graph.sizevars.simplify(index), v) + for v in ordered + ] + if not all(isinstance(c, int) and c > 0 for c in coeffs_raw): + return None + coeffs: list[int] = cast(list[int], coeffs_raw) + + n = len(ordered) + in_strides = self._c_contiguous_strides(in_shape) + store_coeffs = self._compute_store_coeffs(ordered) + + # --- Primary path: dimension-mapping with actual output strides --- + if store_coeffs is not None: + for out_name in self._output_buffer_names: + out_buf = V.graph.get_buffer(out_name) + if out_buf is None: + continue + out_shape = [self._safe_int(s) for s in out_buf.get_size()] + if any(s is None for s in out_shape) or len(out_shape) != n: + continue + + actual = self._get_actual_out_strides(out_buf, n) + if actual is not None: + rt_to_out = self._map_coeffs_to_dims( + [store_coeffs[v] for v in ordered], actual + ) + rt_to_in = self._map_coeffs_to_dims(list(coeffs), in_strides) + if rt_to_out is not None and rt_to_in is not None: + perm = [0] * n + for k in range(n): + perm[rt_to_out[k]] = rt_to_in[k] + if list(perm) == list(range(n)): + return None + return tuple(perm) + break + + return None + + def _get_collapsed_load_permutation( + self, name: str, index: sympy.Expr + ) -> tuple[tuple[int, ...], tuple[int, ...]] | None: + """Handle permutation when range tree has collapsed dimensions. + + When simplify_and_reorder merges contiguous dims, the range tree + has fewer variables than the buffer's rank. This method detects + the permutation in the collapsed space and returns + (collapsed_input_shape, perm) so the caller can generate: + jnp.permute_dims(load.reshape(collapsed_shape), perm) + + Uses index coefficients on both sides: load-index coefficients + map vars to collapsed input dims, and store-side coefficients + (derived from the range tree nesting) map vars to collapsed + output dims. Both sets of strides are always unique, so + matching is unambiguous even with duplicate group sizes. + """ + info = self._get_buffer_info(name) + if not info: + return None + _, buf_size, _, _, is_contiguous = info + in_shape_raw = [self._safe_int(s) for s in buf_size] + if len(in_shape_raw) < 2 or None in in_shape_raw: + return None + in_shape: list[int] = cast(list[int], in_shape_raw) + if not is_contiguous: + return None + + iter_used = self._get_used_iter_vars(index) + ordered = [ + s + for s, e in self.range_tree_nodes.items() + if s in iter_used and not e.is_reduction + ] + n = len(ordered) + if n < 2 or n >= len(in_shape): + return None + ranges_raw = [self._safe_int(self.range_tree_nodes[v].length) for v in ordered] + if None in ranges_raw: + return None + ranges: list[int] = cast(list[int], ranges_raw) + if math.prod(ranges) != math.prod(in_shape): + return None + + # Group consecutive input dims (right-to-left) to match ranges + in_groups = self._group_dims_to_ranges(in_shape, ranges) + if in_groups is None: + return None + + # Compute collapsed input strides (row-major) and use load-index + # coefficients to map each range tree var to a collapsed input dim. + # Strides are always unique, so this is unambiguous even when + # group sizes are duplicated. + collapsed_in_strides = [0] * n + stride = 1 + for i in range(n - 1, -1, -1): + collapsed_in_strides[i] = stride + stride *= in_groups[i] + + simplified = V.graph.sizevars.simplify(index) + in_coeffs_raw = [self._get_index_coefficient(simplified, v) for v in ordered] + if not all(isinstance(c, int) and c > 0 for c in in_coeffs_raw): + return None + in_coeffs: list[int] = cast(list[int], in_coeffs_raw) + + in_stride_to_dim = {s: i for i, s in enumerate(collapsed_in_strides)} + var_to_in_dim = [] + for coeff in in_coeffs: + dim = in_stride_to_dim.get(coeff) + if dim is None: + return None + var_to_in_dim.append(dim) + + store_coeffs = self._compute_store_coeffs(ordered) + if store_coeffs is None: + return None + + # Find the output-side mapping using store coefficients. + for out_name in self._output_buffer_names: + out_buf = V.graph.get_buffer(out_name) + if out_buf is None: + continue + out_shape_raw = [self._safe_int(s) for s in out_buf.get_size()] + if any(s is None for s in out_shape_raw) or len(out_shape_raw) < 2: + continue + out_shape: list[int] = cast(list[int], out_shape_raw) + if math.prod(out_shape) != math.prod(in_shape): + continue + out_groups = self._group_dims_to_ranges(out_shape, list(in_groups)) + if out_groups is None: + continue + + # Compute collapsed output strides and match store coefficients. + collapsed_out_strides = [0] * n + stride = 1 + for i in range(n - 1, -1, -1): + collapsed_out_strides[i] = stride + stride *= out_groups[i] + + out_stride_to_dim = {s: j for j, s in enumerate(collapsed_out_strides)} + var_to_out_dim = [] + for v in ordered: + j = out_stride_to_dim.get(store_coeffs[v]) + if j is None: + return None + var_to_out_dim.append(j) + + # Build perm: perm[out_dim] = in_dim + perm = [0] * n + for k in range(n): + perm[var_to_out_dim[k]] = var_to_in_dim[k] + if perm == list(range(n)): + return None + return (tuple(in_groups), tuple(perm)) + return None + + @staticmethod + def _group_dims_to_ranges(dims: list[int], ranges: list[int]) -> list[int] | None: + """Group consecutive dims (right-to-left) to match range values. + + Returns collapsed shape (left-to-right) or None if no valid grouping. + """ + available = list(ranges) + groups: list[int] = [] + product = 1 + for i in range(len(dims) - 1, -1, -1): + product *= dims[i] + try: + idx = available.index(product) + except ValueError: + continue + groups.append(product) + available.pop(idx) + product = 1 + if product != 1 or available: + return None + groups.reverse() + return groups + + def _get_index_expr(self, index: sympy.Expr) -> _BufferIndexing: + """Get the index expression string and whether it needs flattening.""" + has_indirect = self._has_indirect_vars(index) + has_iter_vars = self._has_iteration_vars(index) + + if has_indirect and has_iter_vars: + return _BufferIndexing( + index_str=self._handle_mixed_indexing(index), needs_flatten=True + ) + elif has_indirect: + return _BufferIndexing(index_str=self.kexpr(index), needs_flatten=False) + else: + index_str = self._get_index_str(index) + # Check if index contains ModularIndexing - this requires flattened access + # ModularIndexing is used for roll/wrap-around operations + needs_flatten = index.has(ModularIndexing) and index_str != "..." + # If index_str is an actual expression (not "..." or a slice pattern), + # we need flattened access because it uses block variables + if not needs_flatten and index_str != "...": + # Check if it's a simple slice pattern (::N or M::N) + if not ("::" in index_str or index_str.lstrip("-").isdigit()): + needs_flatten = True + return _BufferIndexing(index_str=index_str, needs_flatten=needs_flatten) + + @staticmethod + def _safe_int(val: Any) -> int | None: + """Convert value to int, returning None on failure.""" + try: + return int(val) + except (TypeError, ValueError): + return None + + @staticmethod + def _c_contiguous_strides(shape: list[int]) -> list[int]: + """Return C-contiguous strides for the given shape.""" + n = len(shape) + strides = [1] * n + for i in range(n - 2, -1, -1): + strides[i] = strides[i + 1] * shape[i + 1] + return strides + + @staticmethod + def _map_coeffs_to_dims(coeffs: list[int], strides: list[int]) -> list[int] | None: + """Map coefficient values to dimension indices via stride matching. + + Returns a list where entry k is the dimension whose stride equals + coeffs[k], or None if the mapping is ambiguous or incomplete. + """ + stride_to_dim: dict[int, int] = {} + for d, s in enumerate(strides): + if s in stride_to_dim: + return None # duplicate strides + stride_to_dim[s] = d + mapping: list[int] = [] + for c in coeffs: + d = stride_to_dim.get(c) + if d is None: + return None + mapping.append(d) + if len(OrderedSet(mapping)) != len(coeffs): + return None + return mapping + + def _zero_dim_output_flags(self, ctx: _CodegenContext) -> tuple[bool, bool]: + """Return whether an output has a zero or unknown dimension.""" + has_unknown_dim = False + for buf_name in ctx.output_buffer_lookup.values(): + buf = V.graph.try_get_buffer(buf_name) + if buf is None: + has_unknown_dim = True + continue + for dim in buf.get_size(): + dim_int = self._safe_int(dim) + if dim_int == 0: + return True, has_unknown_dim + if dim_int is None: + has_unknown_dim = True + return False, has_unknown_dim + + def _get_reduction_axes(self) -> tuple[int, ...]: + """Determine which axes of the loaded array are reduction axes. + + Finds the innermost reduction stride from the load index + expression, then walks outward through the buffer's dims + using stride ratios until the accumulated product reaches + red_numel. Falls back to stride-direction analysis for + gather/flatten loads. + """ + if not self.load_index_exprs: + return (-1,) + + r_vars = [v for v, e in self.range_tree_nodes.items() if e.is_reduction] + pw_vars = [v for v, e in self.range_tree_nodes.items() if not e.is_reduction] + if not r_vars or not pw_vars: + return (-1,) + + red_numel = self._compute_reduction_numel() + if not red_numel or red_numel <= 1: + return (-1,) + + for buf_name, load_index in self.load_index_exprs.items(): + info = self._get_buffer_info(buf_name) + if info is None: + continue + _, buf_size, _, actual_strides, _ = info + nd = len(buf_size) + if nd < 2: + continue + strides_or_none = [self._safe_int(s) for s in actual_strides] + if any(s is None for s in strides_or_none): + continue + strides: list[int] = cast(list[int], strides_or_none) + + # Get reduction stride coefficients by zeroing pw_vars. + r_only = load_index + for pv in pw_vars: + r_only = r_only.subs(pv, 0) + r_coeffs: OrderedSet[int] = OrderedSet() + for term in sympy.Add.make_args(r_only): + if term.is_number: + continue + coeff, _ = term.as_coeff_Mul() + c = self._safe_int(coeff) + if c is not None and c > 0: + r_coeffs.add(c) + if not r_coeffs: + continue + + # Match all coefficients against buffer strides + matched = sorted( + (i for i in range(nd) if strides[i] in r_coeffs), + ) + if not matched: + continue + + # Multiple r_vars each map to a distinct dim — return directly. + # Single r_var with multiple coefficients (transposed access) + # → skip to fallback. + if len(r_coeffs) > 1: + if len(r_coeffs) == len(matched) and len(r_vars) > 1: + return tuple(i - nd for i in matched) + continue + + # Single coefficient: walk outward from the matched dim + # using span to find flattened contiguous dims. + r_stride = next(iter(r_coeffs)) + span = (red_numel - 1) * r_stride + is_contiguous = all(strides[i] > strides[i + 1] for i in range(nd - 1)) + if is_contiguous: + # Walk by dim index (strides are in descending order) + inner = matched[-1] + start = inner + while start > 0 and span > strides[start - 1]: + start -= 1 + axes = list(range(start, inner + 1)) + else: + # Non-contiguous layout: collect dims whose strides + # fall within the r_var's traversal range + axes = sorted( + i + for i in range(nd) + if r_stride <= strides[i] and strides[i] < span + r_stride + ) + if not axes: + axes = list(matched) + return tuple(i - nd for i in axes) + + # Fallback: stride-direction for gather/flatten loads + load_index = next(iter(self.load_index_exprs.values())) + r_coeff = load_index.coeff(r_vars[0]) + r_stride = self._safe_int(r_coeff) if r_coeff != 0 else 1 + if r_stride is None: + r_stride = 1 + pw_coeff = load_index.coeff(pw_vars[0]) + pw_stride = self._safe_int(pw_coeff) if pw_coeff != 0 else 1 + if pw_stride is None: + pw_stride = 1 + if r_stride > pw_stride: + return (0,) + return (-1,) + + def _compute_prefix_numel(self, prefixes: OrderedSet) -> int | None: + """Compute total numel for given prefixes (e.g., pointwise prefixes).""" + result = 1 + for p in prefixes: + if p in self.numels: + numel = self._safe_int(self.numels[p]) + if numel is None: + return None + result *= numel + return result + + def _compute_reduction_numel(self) -> int | None: + """Compute total reduction numel.""" + result = 1 + for tree in self.range_trees: + if tree.is_reduction: + numel = self._safe_int(tree.numel) + if numel is None: + return None + result *= numel + return result + + def _can_use_tma_approach(self) -> bool: + """ + Check if TMA (Tensor Memory Accelerator) approach can be used. + TMA works for simple element-wise ops but not for: + - Reductions (need different accumulation patterns) + TODO: TMA supports float64 for loading but not for reductions + - Broadcasting (inputs have different shapes or output differs) + - Non-contiguous tensors (strided, transposed) + """ + # TMA flattens to 1D tiles, incompatible with permutation detection + # which emits jnp.permute_dims expecting N-D input. + if self.permuted_input_buffers: + return False + + # Check for reductions + reduction_numel = self._compute_reduction_numel() + if reduction_numel is not None and reduction_numel > 1: + return False + + # Check all input buffers for contiguity, dtype, and shape consistency + input_shapes: list[tuple] = [] + for name in self.args.input_buffers: + info = self._get_buffer_info(name) + if info is None: + return False + buf_obj, buf_size, buf_numel, actual_strides, is_contiguous = info + if not is_contiguous: + return False + + # Check for unsupported dtypes + # TODO: TMA supports float64 for loading but current JAX Mosaic GPU + # implementation doesn't support it yet. Re-enable when JAX adds support. + buf_dtype = getattr(buf_obj, "get_dtype", lambda: None)() + if buf_dtype is not None: + import torch + + if buf_dtype == torch.float64: + return False + + # Collect shape as tuple for comparison + shape_tuple = tuple(self._safe_int(s) for s in buf_size) + if None in shape_tuple: + return False # Dynamic shapes not supported + input_shapes.append(shape_tuple) + + # Check if all input shapes are identical (no broadcasting) + if input_shapes and len(OrderedSet(input_shapes)) > 1: + return False + + # Check that output numel matches input numel (no broadcasting expansion) + if input_shapes: + input_numel = 1 + for s in input_shapes[0]: + input_numel *= s + + # Compute output numel from pointwise range trees (non-reduction) + output_numel = 1 + for tree in self.range_trees: + if not tree.is_reduction: + numel = self._safe_int(tree.numel) + if numel is None: + return False # Dynamic shapes not supported + output_numel *= numel + + if output_numel != input_numel: + return False + + return True + + def _get_buffer_info(self, name: str) -> tuple[Any, Any, Any, list, bool] | None: + """Get buffer metadata (buf_obj, buf_size, buf_numel, actual_strides, is_contiguous). + + Returns None if the buffer doesn't exist. + """ + buf_obj = V.graph.get_buffer(name) + if buf_obj is None: + return None + buf_size = buf_obj.get_size() + buf_numel = 1 + for s in buf_size: + sval = self._safe_int(s) + buf_numel *= sval if sval is not None else s + + # Get buffer strides and check contiguity + actual_strides: list = [] + is_contiguous = True + + layout = getattr(buf_obj, "get_layout", lambda: None)() + buf_stride = getattr(layout, "stride", None) if layout else None + + if buf_stride is not None: + for i in range(len(buf_size)): + actual_stride = self._safe_int(buf_stride[i]) + actual_strides.append(actual_stride) + + # Check contiguity + if len(buf_size) == 1: + if actual_strides[0] is not None and actual_strides[0] != 1: + is_contiguous = False + elif len(buf_size) > 1: + expected_stride = 1 + for i in range(len(buf_size) - 1, -1, -1): + actual_stride = actual_strides[i] + if actual_stride is None or actual_stride != expected_stride: + is_contiguous = False + dim_size = self._safe_int(buf_size[i]) + if dim_size is not None: + expected_stride *= dim_size + + return buf_obj, buf_size, buf_numel, actual_strides, is_contiguous + + def _compute_output_numel_from_index( + self, index: sympy.Expr + ) -> tuple[int, OrderedSet]: + """Compute expected output numel and used vars from iteration variables in index.""" + used_vars = self._get_used_iter_vars(index) + + used_range_lengths = [] + for var in used_vars: + if var in self.range_tree_nodes: + entry = self.range_tree_nodes[var] + length_val = self._safe_int(entry.length) + if length_val is not None: + used_range_lengths.append(length_val) + + output_numel = 1 + for l in used_range_lengths: + output_numel *= l + + return output_numel, used_vars + + def _get_index_coefficients( + self, index: sympy.Expr, used_vars: OrderedSet + ) -> OrderedSet: + """ + Extract coefficients of iteration variables from index expression. + """ + coefficients: OrderedSet = OrderedSet() + for var in used_vars: + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(index, var) + stride = BlockPatternMatcher.match_affine_block_expr(var_expr, var) + if stride is None: + stride = 1 # Variable without explicit coefficient has stride 1 + coef = self._safe_int(stride) + coefficients.add(coef if coef is not None else stride) + return coefficients + + def _check_gather_pattern( + self, + buf_size: list, + actual_strides: list, + is_contiguous: bool, + coefficients: OrderedSet, + ) -> bool: + """ + Check if access pattern requires gather (non-standard striding). + """ + expected_strides = [1] # 1D buffers have stride 1 + + if len(buf_size) > 1: + expected_stride = 1 + expected_strides = [] + for i in range(len(buf_size) - 1, -1, -1): + expected_strides.insert(0, expected_stride) + dim_size = self._safe_int(buf_size[i]) + if dim_size is not None: + expected_stride *= dim_size + + if is_contiguous: + # Buffer is contiguous - check if access coefficients match expected strides + expected_stride_set = OrderedSet(expected_strides) + for coef in coefficients: + if coef not in expected_stride_set: + return True + else: + # Buffer is NOT contiguous (strided input) + # Check if coefficients match actual buffer strides + actual_stride_set = OrderedSet(s for s in actual_strides if s is not None) + for coef in coefficients: + if coef not in actual_stride_set: + return True + + return False + + def _needs_strided_indexing( + self, + name: str, + index: sympy.Expr, + indexing: _BufferIndexing, + ) -> _BufferIndexing: + """Check if buffer access needs strided indexing due to size mismatch or gather patterns.""" + # Only applies when full array access is indicated + if indexing.index_str != "..." or indexing.needs_flatten: + return indexing + + info = self._get_buffer_info(name) + if info is None: + return indexing + + buf_obj, buf_size, buf_numel, actual_strides, is_contiguous = info + output_numel, used_vars = self._compute_output_numel_from_index(index) + all_iter_vars = self._get_iter_vars() + coefficients = self._get_index_coefficients(index, used_vars) + + # Check for gather pattern + has_non_unit_strides = self._check_gather_pattern( + buf_size, actual_strides, is_contiguous, coefficients + ) + + # Check for im2col-like pattern (more iter vars used than buffer dims) + buf_effective_dims = sum(1 for s in buf_size if self._safe_int(s) != 1) + not_all_vars_used = ( + len(used_vars) < len(all_iter_vars) + and len(used_vars) > 0 + and buf_effective_dims > 1 + and len(used_vars) > len(buf_size) + ) + + # Check various conditions for skipping strided indexing + is_tpu = V.graph.get_current_device_or_throw().type == "tpu" + is_known_non_contiguous = not is_contiguous and all( + s is not None for s in actual_strides + ) + has_symbolic_coef = any(not isinstance(c, int | float) for c in coefficients) + skip_for_non_contiguous = ( + is_known_non_contiguous and not is_tpu and buf_numel == output_numel + ) + + # Determine if strided indexing is needed + if ( + output_numel > 0 + and (buf_numel != output_numel or not_all_vars_used or has_non_unit_strides) + and len(used_vars) > 0 + and not skip_for_non_contiguous + and not has_symbolic_coef + ): + return _BufferIndexing( + index_str=self._generate_strided_index(index), needs_flatten=True + ) + + return indexing + + def _adjust_index_for_buffer_shape( + self, + name: str, + index: sympy.Expr, + indexing: _BufferIndexing, + ) -> _BufferIndexing: + """ + Adjust index expression based on buffer shape (0-dim scalar, multi-dim, etc.). + """ + if indexing.needs_flatten or indexing.index_str == "...": + return indexing + + buf_obj = V.graph.get_buffer(name) + if buf_obj is None: + return indexing + + buf_size = buf_obj.get_size() + + if len(buf_size) == 0: + return _BufferIndexing( + index_str="...", needs_flatten=indexing.needs_flatten + ) + + # if buffer size is 1, and index is an integer, use "..." + if ( + len(buf_size) == 1 + and buf_size[0] == 1 + and not self._has_iteration_vars(index) + ): + return _BufferIndexing( + index_str="...", needs_flatten=indexing.needs_flatten + ) + + # Multi-dimensional buffer with constant/scalar index + if len(buf_size) > 1: + has_iter_vars = self._has_iteration_vars(index) + if not has_iter_vars: + return _BufferIndexing( + index_str=indexing.index_str, needs_flatten=True + ) # Use flattened access + elif "::" in indexing.index_str: + # Strided slice patterns need flattened indexing for multi-dim + return _BufferIndexing( + index_str=self._generate_strided_index(index), needs_flatten=True + ) + + # GPU doesn't support gather from slice patterns on 1D buffers + if self.is_gpu and "::" in indexing.index_str: + return _BufferIndexing( + index_str=self._generate_strided_index(index), needs_flatten=True + ) + + return indexing + + def _try_multidim_slice( + self, + name: str, + index: sympy.Expr, + indexing: _BufferIndexing, + ) -> _BufferIndexing: + """ + Try to emit multi-dim slice notation instead of flatten + gather. + + For a buffer with shape (d0, ..., dk) and index `stride * var + offset`, + emit `buf[:, ..., :, offset::stride]` when stride divides dk. + """ + if not indexing.needs_flatten: + return indexing + + buf_obj = V.graph.get_buffer(name) + if buf_obj is None: + return indexing + + buf_size = buf_obj.get_size() + ndim = len(buf_size) + if ndim < 2: + return indexing + + # Need a single iteration variable with an affine index + used_vars = self._get_used_iter_vars(index) + if len(used_vars) != 1: + return indexing + + var = next(iter(used_vars)) + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(index, var) + stride = self._safe_int( + BlockPatternMatcher.match_affine_block_expr(var_expr, var) + ) + if stride is None or stride <= 1: + return indexing + + offset = V.graph.sizevars.simplify(index - var_expr) + try: + offset_val = int(offset) + except (TypeError, ValueError): + return indexing + + if offset_val < 0 or offset_val >= stride: + return indexing + + last_dim = self._safe_int(buf_size[-1]) + if last_dim is None or last_dim % stride != 0: + return indexing + + # Verify the iteration variable covers all buffer elements at the + # given stride: var_length * stride == buf_numel. This ensures + # the flattened stride-access 0, stride, 2*stride, ... maps exactly + # to buf[:, ..., :, offset::stride]. + entry = self.range_tree_nodes.get(var) + if entry is None: + return indexing + var_length = self._safe_int(entry.length) + buf_numel = 1 + for s in buf_size: + d = self._safe_int(s) + if d is None: + return indexing + buf_numel *= d + if var_length is None or var_length * stride != buf_numel: + return indexing + + prefix = ":, " * (ndim - 1) + if offset_val == 0: + slice_str = f"{prefix}::{stride}" + else: + slice_str = f"{prefix}{offset_val}::{stride}" + return _BufferIndexing(index_str=slice_str, needs_flatten=False) + + @staticmethod + def _gather_permute_expr(load_expr: str, perm: tuple[int, ...]) -> str: + """Generate gather-based permutation instead of jnp.permute_dims. + + Avoids a Mosaic compiler bug where jnp.permute_dims produces + corrupted output tensors on TPU for 3D+ arrays. Uses + pallas_permute which flattens to 1D and does a 1D gather. + """ + return f"pallas_permute({load_expr}, {perm})" + + def _trace_to_load_source(self, var_name: str) -> str | None: + """Trace a tmp variable back to its source buffer's kernel param. + + Follows CSE assignments backward through bounds-checking (where/clamp) + until it finds a variable that was directly loaded from a buffer. + """ + if var_name in self._cse_to_param: + return self._cse_to_param[var_name] + for line in self.compute._lines: + line_str = str(line).lstrip() + if not line_str.startswith(f"{var_name} = "): + continue + for ref in re.findall(r"\btmp\d+\b", line_str.split(" = ", 1)[1]): + result = self._trace_to_load_source(ref) + if result is not None: + return result + return None + + def _detect_indirect_access( + self, buf: str, name: str, index: sympy.Expr + ) -> _IndirectAccessInfo | None: + """Detect a load with data-dependent indexing suitable for scalar prefetch. + + Matches exactly one indirect variable whose coefficient corresponds to + a C-contiguous stride dimension. Rejects 1-to-1 gather patterns where + the indices buffer covers the full iteration space. + """ + buf_info = self._get_buffer_info(name) + if buf_info is None: + return None + _, buf_size, _, _, _ = buf_info + buf_size_raw = [self._safe_int(s) for s in buf_size] + if len(buf_size_raw) < 2 or any(s is None for s in buf_size_raw): + return None + buf_size_ints: list[int] = cast(list[int], buf_size_raw) + + indirect_vars = self._get_indirect_vars(index) + if len(indirect_vars) != 1: + return None + indirect_var = indirect_vars[0] + + coeff = self._get_index_coefficient(index, indirect_var) + if coeff == 0 or not isinstance(coeff, int): + return None + + # Use existing stride mapping to find which dimension is indirected + strides = self._c_contiguous_strides(buf_size_ints) + mapping = self._map_coeffs_to_dims([coeff], strides) + if mapping is None: + return None + indirect_dim = mapping[0] + + ndim = len(buf_size_ints) + if indirect_dim >= max(1, ndim - 2): + return None + + indirect_var_name = str(indirect_var) + indices_param = self._trace_to_load_source(indirect_var_name) + if indices_param is None: + return None + + # Reject gather patterns: only 1-D static index tensors supported + indices_graph_name = self._param_to_graph_name.get(indices_param) + if indices_graph_name is not None: + indices_info = self._get_buffer_info(indices_graph_name) + if indices_info is not None: + _, indices_size, _, _, _ = indices_info + if len(indices_size) != 1: + return None + if self._safe_int(indices_size[0]) is None: + return None + indices_numel = math.prod( + v for s in indices_size if (v := self._safe_int(s)) is not None + ) + iter_product = math.prod( + length + for var in self._get_used_iter_vars(index) + if var in self.range_tree_nodes + if (length := self._safe_int(self.range_tree_nodes[var].length)) + is not None + ) + if indices_numel >= iter_product: + return None + + return _IndirectAccessInfo( + table_param=buf, + table_buf_name=name, + table_shape=tuple(buf_size_ints), + indirect_dim=indirect_dim, + indirect_var=indirect_var_name, + indices_param=indices_param, + ) + + def _eliminate_dead_indirect_code(self) -> None: + """Remove dead compute lines after scalar prefetch replaces indirect load. + + When the table load is simplified to buf[0] (scalar prefetch handles + indexing), the indices load and all derived bounds-checking code become + dead. This performs backward liveness analysis from the store variables + to identify and remove dead lines. + """ + # Collect variables used by stores (live roots) + live_vars: OrderedSet[str] = OrderedSet() + for _, store_line in self.store_with_output: + for m in re.finditer(r"\btmp\d+\b", store_line): + live_vars.add(m.group()) + + # Parse assignments from compute lines + assignments: list[tuple[str | None, str, Any]] = [] + for line in self.compute._lines: + line_str = str(line).lstrip() + m = re.match(r"^(tmp\d+)\s*=\s*(.*)", line_str, re.DOTALL) + if m: + assignments.append((m.group(1), m.group(2), line)) + else: + assignments.append((None, line_str, line)) + + # Propagate liveness backward + changed = True + while changed: + changed = False + for var_name, rhs, _ in reversed(assignments): + if var_name and var_name in live_vars: + for m in re.finditer(r"\btmp\d+\b", rhs): + if m.group() not in live_vars: + live_vars.add(m.group()) + changed = True + + # Keep only live assignments (and non-assignment lines) + self.compute._lines = [ + line + for var_name, _, line in assignments + if var_name is None or var_name in live_vars + ] + + def _build_load_expr( + self, + buf: str, + name: str, + index: sympy.Expr, + indexing: _BufferIndexing, + ) -> str: + """ + Build the load expression based on indexing mode. + """ + if indexing.needs_flatten: + # Detect indirect (data-dependent) access for scalar prefetch + indirect = self._detect_indirect_access(buf, name, index) + if indirect is not None: + if self.indirect_access is not None: + # Fused nodes may re-visit the same indirect load (e.g. + # a reduction + pointwise over the same embedding). + # Allow that, but reject truly different indirect accesses. + if indirect != self.indirect_access: + raise AssertionError( + "only one indirect access per kernel supported" + ) + self.indirect_access = indirect + return f"{buf}[0]" + + self.has_flatten_indexing = True + self.flatten_indexed_buffers.add(name) + # Flatten then index for non-contiguous access (gather operation) + has_minmax = index.has(sympy.Min, sympy.Max, TorchMin, TorchMax) + idx_dtype = "jnp.int32" if self.is_tpu else "jnp.int64" + idx = ( + f"({indexing.index_str}).astype({idx_dtype})" + if has_minmax + else indexing.index_str + ) + return f"{buf}[...].flatten()[{idx}]" + else: + # Direct indexing for contiguous access + load_expr = f"{buf}[{indexing.index_str}]" + + if indexing.index_str == "..." and not self.is_gpu: + perm = self._get_full_load_permutation(name, index) + if perm is not None: + load_expr = self._gather_permute_expr(load_expr, perm) + self.permuted_input_buffers[name] = perm + else: + collapsed = self._get_collapsed_load_permutation(name, index) + if collapsed is not None: + collapsed_shape, cperm = collapsed + load_expr = f"jnp.permute_dims({load_expr}, {cperm})" + # Don't store cperm in permuted_input_buffers as it's for the reshaped tensor + # not the original shape, which causes issues later when used for tiling + self.collapsed_reshape_inputs[name] = collapsed_shape + self.collapsed_output_shape = tuple( + collapsed_shape[p] for p in cperm + ) + + return load_expr + + def _maybe_squeeze_intermediate_buffer(self, name: str, load_expr: str) -> str: + """ + Squeeze (N,1) intermediate buffers when kernel has 1D graph inputs. + + This avoids wrong broadcasting: (N,) op (N,1) -> (N,N) instead of (N,) + """ + if not name.startswith("buf"): + return load_expr + + # Check if any input buffer is a 1D graph input + has_1d_input = any( + not buf_name.startswith("buf") + and (buf_obj := V.graph.get_buffer(buf_name)) is not None + and len(buf_obj.get_size()) == 1 + for buf_name in self.args.input_buffers + ) + + if has_1d_input: + buf_obj = V.graph.get_buffer(name) + if buf_obj is not None: + buf_size = buf_obj.get_size() + if len(buf_size) == 2 and buf_size[-1] == 1: + return f"jnp.squeeze({load_expr}, axis=-1)" + + return load_expr + + def _maybe_broadcast_1d_buffer( + self, name: str, index: sympy.Expr, load_expr: str + ) -> str: + """Reshape 1D buffers for higher-dim broadcasting in reduction kernels. + + When a 1D buffer (e.g. a reduction result from a prior kernel, or a + batch-norm parameter) is loaded into a kernel with 2+ iteration dims, + JAX right-aligns it for broadcasting: (N,) becomes (1, N). This is + wrong when the buffer corresponds to a non-trailing axis; we reshape + to (N, 1, ...) so broadcasting matches the correct axis. + """ + buf_obj = V.graph.get_buffer(name) + if buf_obj is None or len(buf_obj.get_size()) != 1: + return load_expr + + # Only graph inputs, not intermediate buffers — intermediates are + # already shaped by the IR and their dim order may not match the + # reference buffer used below for axis inference. + if name.startswith("buf"): + return load_expr + + buf_length = self._safe_int(buf_obj.get_size()[0]) + if buf_length is None: + return load_expr + + dtype = V.graph.get_dtype(name) + if dtype is not None and not dtype.is_floating_point: + return load_expr + + # Find a higher-dimensional reference buffer + ref_buf_size = None + for buf_name in self.args.input_buffers: + other_buf = V.graph.get_buffer(buf_name) + if other_buf is not None and len(other_buf.get_size()) > 1: + ref_buf_size = [self._safe_int(s) for s in other_buf.get_size()] + if all(s is not None for s in ref_buf_size): + break + ref_buf_size = None + if ref_buf_size is None or len(ref_buf_size) <= 1: + return load_expr + + # Must use exactly one iteration variable + used_vars = self._get_used_iter_vars(index) + if len(used_vars) != 1: + return load_expr + used_var = next(iter(used_vars)) + if used_var not in self.range_tree_nodes: + return load_expr + + # Verify buffer length matches variable length + entry = self.range_tree_nodes[used_var] + if self._safe_int(entry.length) != buf_length: + return load_expr + + # Buffer length must uniquely match one non-reduction iteration variable. + # If multiple pointwise vars share the same length (e.g. 2D pointwise + # kernel with both dims equal), the axis is ambiguous and we bail out. + matching_vars = [ + v + for v, e in self.range_tree_nodes.items() + if self._safe_int(e.length) == buf_length and not e.is_reduction + ] + if len(matching_vars) != 1: + return load_expr + + # Determine axis position from the iteration variable's position + # in the range tree (pointwise vars first, then reduction vars). + axis_pos = None + matching_dims = [i for i, s in enumerate(ref_buf_size) if s == buf_length] + if len(matching_dims) == 1: + axis_pos = matching_dims[0] + else: + # Ambiguous by size (e.g. square tensor with reduction). + # Use the variable's position in the range tree. + pw_idx = 0 + for sym, e in self.range_tree_nodes.items(): + if sym == used_var: + axis_pos = pw_idx + break + if not e.is_reduction: + pw_idx += 1 + + if axis_pos is None: + return load_expr + if axis_pos == len(ref_buf_size) - 1: + return load_expr # Last dim uses default broadcasting + + reshape_dims = [1] * len(ref_buf_size) + reshape_dims[axis_pos] = -1 + return f"{load_expr}.reshape({', '.join(map(str, reshape_dims))})" + + def _check_im2col_pattern( + self, index: sympy.Expr, indexing: _BufferIndexing + ) -> _BufferIndexing: + """ + Check for im2col-like patterns where store uses block variables but load doesn't. + + For cat/expand patterns, both load and store prepared indices share block vars. + For im2col patterns, store compresses to block vars but load doesn't. + """ + if indexing.index_str != "..." or indexing.needs_flatten: + return indexing + + prepared_index = self.prepare_indexing(index) + iter_vars = self._get_iter_vars() + store_orig_vars = self._get_used_iter_vars(index) + store_prep_vars = ( + prepared_index.free_symbols + if hasattr(prepared_index, "free_symbols") + else OrderedSet() + ) & iter_vars + new_vars = store_prep_vars - store_orig_vars + + # Only trigger if store introduces new block vars + if not new_vars or len(store_orig_vars) <= 1: + return indexing + + # Check if loads are compatible with broadcast or cat pattern + has_im2col_pattern = False + for buf_name, load_index in self.load_index_exprs.items(): + load_orig_vars = self._get_used_iter_vars(load_index) + if not load_orig_vars: + continue + + # Load has iteration variables + if load_orig_vars != store_orig_vars: + continue + + # Same vars - check if load gets compressed too + prep_load = self.prepare_indexing(load_index) + load_prep_vars = ( + prep_load.free_symbols + if hasattr(prep_load, "free_symbols") + else OrderedSet() + ) & iter_vars + + # If store compresses but load doesn't, check for strided input vs im2col + if load_orig_vars != load_prep_vars or store_prep_vars == store_orig_vars: + continue + + # Check if load coefficients match buffer strides + if not self._check_load_is_strided_input( + buf_name, load_index, load_orig_vars + ): + has_im2col_pattern = True + break + + if has_im2col_pattern: + return _BufferIndexing( + index_str=self._generate_strided_index(prepared_index), + needs_flatten=True, + ) + + return indexing + + def _check_load_is_strided_input( + self, buf_name: str, load_index: sympy.Expr, load_orig_vars: OrderedSet + ) -> bool: + """ + Check if load coefficients match buffer strides (strided input vs im2col). + """ + buf = V.graph.get_buffer(buf_name) + if buf is None: + return False + + layout = getattr(buf, "get_layout", lambda: None)() + if layout is None: + return False + + buf_strides = getattr(layout, "stride", None) + if buf_strides is None: + return False + + buf_sizes = buf.get_size() + + # Get load coefficients + load_coeffs = [] + for var in load_orig_vars: + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(load_index, var) + coef = BlockPatternMatcher.match_affine_block_expr(var_expr, var) + if coef is not None: + int_coef = self._safe_int(coef) + load_coeffs.append(int_coef if int_coef is not None else coef) + + # Check if coefficients match buffer strides + # Only include strides for non-trivial dimensions (size > 1) + buf_stride_set = OrderedSet() + for i, s in enumerate(buf_strides): + dim_size = self._safe_int(buf_sizes[i]) + if dim_size is None or dim_size > 1: + int_s = self._safe_int(s) + buf_stride_set.add(int_s if int_s is not None else s) + + return OrderedSet(load_coeffs) == buf_stride_set + + def _check_store_needs_transpose(self, name: str) -> bool: + """ + Check if output needs transpose for column-major storage. + + Transpose on store is needed when: + - Output has column-major stride (s0 < s1) + - But input(s) have row-major stride + - And we haven't already transposed on load + """ + if self.permuted_input_buffers: + return False + + info = self._get_buffer_info(name) + if info is None: + return False + + _, buf_size, _, actual_strides, _ = info + if len(actual_strides) != 2 or len(buf_size) != 2: + return False + + size0 = self._safe_int(buf_size[0]) + size1 = self._safe_int(buf_size[1]) + s0 = actual_strides[0] + s1 = actual_strides[1] + + # Check if output is column-major with valid dimensions + if not ( + s0 is not None + and s1 is not None + and s0 < s1 + and size0 is not None + and size1 is not None + and size0 > 1 + and size1 > 1 + ): + return False + + # Check if any input is column-major (if so, no transpose needed) + for inp_name in self.args.input_buffers: + inp_info = self._get_buffer_info(inp_name) + if inp_info is None: + continue + _, _, _, inp_strides, _ = inp_info + if len(inp_strides) != 2: + continue + inp_s0 = inp_strides[0] + inp_s1 = inp_strides[1] + if inp_s0 is not None and inp_s1 is not None and inp_s0 < inp_s1: + return False # Input is also column-major + + return True + + def _build_full_array_store_expr( + self, out: str, value: CSEVariable, needs_transpose: bool + ) -> list[str]: + """ + Build store expression for full array assignment. + + Handles scalar broadcast, shape matching, and optional transpose. + Returns a list of lines to emit (variable assignment + store). + """ + lines = [f"_val = jnp.asarray({value})"] + if needs_transpose: + lines.append( + f"{out}[...] = " + f"jnp.full({out}.shape, _val) if _val.ndim == 0 " + f"else jnp.transpose(_val)" + ) + else: + lines.append( + f"{out}[...] = " + f"jnp.full({out}.shape, _val) if _val.ndim == 0 " + f"else (_val.reshape({out}.shape) if _val.size == {out}.size " + f"else jnp.broadcast_to(_val, {out}.shape))" + ) + return lines + + def _build_store_expr( + self, + out: str, + name: str, + index: sympy.Expr, + value: CSEVariable, + indexing: _BufferIndexing, + mode: Any = None, + ) -> list[str]: + """ + Build the store expression based on indexing mode. + mode can be None (set) or "atomic_add" (accumulate). + Returns a list of lines to emit. + """ + if indexing.index_str == "...": + # Full array store with shape matching + needs_transpose = self._check_store_needs_transpose(name) + return self._build_full_array_store_expr(out, value, needs_transpose) + + if indexing.needs_flatten: + self.has_flatten_indexing = True + # Block variable indexing (e.g., im2col) - use flattened scatter + scatter_op = "add" if mode == "atomic_add" else "set" + return [ + f"{out}[...] = {out}[...].flatten().at[jnp.asarray({indexing.index_str}).flatten()].{scatter_op}(" + f"jnp.asarray({value}).flatten()).reshape({out}.shape)" + ] + + # Direct indexed assignment + has_indirect = self._has_indirect_vars(index) + buf = V.graph.get_buffer(name) + + if buf is not None: + buf_size = buf.get_size() + if len(buf_size) > 1 and not self._has_iteration_vars(index): + # Multi-dim output with constant index - use [...] for full assignment + return self._build_full_array_store_expr(out, value, False) + + if has_indirect: + # Indirect indexed store (scatter): use .add() for atomic_add, .set() otherwise + scatter_op = "add" if mode == "atomic_add" else "set" + lines = [f"_val = jnp.asarray({value})"] + value_expr = f"(jnp.full({indexing.index_str}.shape, _val) if _val.ndim == 0 else {value})" + if mode == "atomic_add": + # For atomic_add, mark output as needing to be readable (for aliasing) + self.outputs_need_read.add(out) + alias_param = f"{out}_alias" + lines.append( + f"{out}[...] = {alias_param}[...].flatten().at[jnp.asarray({indexing.index_str}).flatten()].{scatter_op}(" + f"jnp.asarray({value_expr}).flatten()).reshape({out}.shape)" + ) + else: + lines.append(f"{out}[{indexing.index_str}] = {value_expr}") + return lines + + return [f"{out}[{indexing.index_str}] = {value}"] + + def _build_scatter_store_expr( + self, + out: str, + value: CSEVariable, + scatter_info: dict[str, Any], + name: str, + mode: Any, + ) -> str: + """Build store expression for scatter operations (indirect indexing).""" + is_point_scatter = scatter_info.get("is_point_scatter", False) + + # Mark this output parameter as needing to be readable (for aliasing) + self.outputs_need_read.add(out) + alias_param = f"{out}_alias" + + # Use .add() for atomic_add mode, .set() otherwise + scatter_op = "add" if mode == "atomic_add" else "set" + + if is_point_scatter: + # Single-element scatter + indirect_var = scatter_info["indirect_var"] + indirect_dim = scatter_info["indirect_dim"] + output_shape = scatter_info["output_shape"] + + # Build index tuple with 0s for other dimensions + index_parts = [] + for dim in range(len(output_shape)): + if dim == indirect_dim: + index_parts.append(indirect_var) + else: + index_parts.append("0") + + index_tuple = ", ".join(index_parts) + return f"{out}[...] = {alias_param}[...].at[{index_tuple}].{scatter_op}({value})" + + # Scatter with iteration variables + indirect_var = scatter_info["indirect_var"] + dims_before = scatter_info["dims_before"] + dims_after = scatter_info["dims_after"] + + # Determine if element-wise or slice-based scatter + buf = V.graph.get_buffer(name) + output_ndim = len(buf.get_size()) if buf is not None else 0 + + num_iter_vars_in_store = len(dims_before) + len(dims_after) + total_kernel_iter_vars = len(self.range_tree_nodes) + remaining_dims = output_ndim - 1 # dims other than indirect + + is_element_wise = ( + num_iter_vars_in_store == remaining_dims + and num_iter_vars_in_store == total_kernel_iter_vars + ) + + if is_element_wise: + # Element-wise scatter: use iteration variable names + index_parts = [var_name for var_name, size in dims_before] + + # Reshape indirect var for broadcasting if needed + n_leading = len(dims_before) + n_trailing = len(dims_after) + if n_leading > 0 and n_trailing > 0: + leading_ones = "None, " * n_leading + trailing_nones = ", None" * n_trailing + indirect_reshaped = f"{indirect_var}[{leading_ones}...{trailing_nones}]" + else: + indirect_reshaped = indirect_var + index_parts.append(indirect_reshaped) + + index_parts.extend(var_name for var_name, size in dims_after) + else: + # Slice-based scatter: use : for iteration dimensions + index_parts = [":" for _ in dims_before] + index_parts.append(indirect_var) + index_parts.extend(":" for _ in dims_after) + + index_tuple = ", ".join(index_parts) + return ( + f"{out}[...] = {alias_param}[...].at[{index_tuple}].{scatter_op}({value})" + ) + + @typing_extensions.override + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + buf = self.args.input(name) + dtype = V.graph.get_dtype(name) + + # Track the load index expression for argmax/argmin axis detection + self.load_index_exprs[name] = index + + # Get base index expression + indexing = self._get_index_expr(index) + + # Check for buffer size mismatch requiring strided indexing + indexing = self._needs_strided_indexing(name, index, indexing) + + # Try strided decomposition before multidim slice or flatten. + # This generates reshape + static indexing which works on both + # CPU and TPU (unlike slice notation which fails on Mosaic). + decomp = self._decompose_strided_access(index, name) + if decomp is not None: + self.strided_input_buffers[name] = decomp + load_expr = self._strided_load_expr(buf, decomp) + else: + # Adjust index for buffer shape (scalar, multi-dim, etc.) + indexing = self._adjust_index_for_buffer_shape(name, index, indexing) + + # Try to emit multi-dim slice instead of flatten + gather + indexing = self._try_multidim_slice(name, index, indexing) + + # Build the load expression + load_expr = self._build_load_expr(buf, name, index, indexing) + + # Handle intermediate buffer squeezing for correct broadcasting + if not indexing.needs_flatten and indexing.index_str == "...": + load_expr = self._maybe_squeeze_intermediate_buffer(name, load_expr) + # Handle 1D buffer broadcasting for higher-dimensional kernels + load_expr = self._maybe_broadcast_1d_buffer(name, index, load_expr) + + cse_var = self.cse.generate( + self.compute, + load_expr, + dtype=dtype, + ) + # Track CSE var -> param -> graph name for indirect access detection + buf_param = self.args.input(name) + self._cse_to_param[str(cse_var)] = buf_param + self._param_to_graph_name[buf_param] = name + return cse_var + + def _handle_mixed_indexing(self, index: sympy.Expr) -> str: + """ + Handle indexing with both indirect variables and iteration variables. + + For example, x[indices, :] generates index = i0 + stride * tmp0 + where tmp0 is loaded from indices and i0 is the iteration variable. + + We need to convert this to JAX advanced indexing with proper broadcasting. + When there are multiple iteration variables, they need different shapes + to form an outer product (grid) rather than broadcasting together. + + Special case: For gather operations where a single iteration variable + and single indirect variable have the same extent, they should be + element-wise aligned, not broadcast into an outer product. + + PyTorch advanced indexing semantics: When multiple indirect indices have + the same shape, they are paired element-wise (not outer product), and + the combined result dimension appears at the FRONT of the output. + """ + used_iter_vars_set = self._get_used_iter_vars(index) + + # Track which iteration variables are used + self.used_iter_vars.update(used_iter_vars_set) + + if len(used_iter_vars_set) == 0: + return self.kexpr(index) + + # Sort iteration variables by their coefficient (stride) in the index expression. + # Variables with larger strides correspond to earlier output dimensions. + # Use inf default so symbolic coefficients sort as outermost dimensions. + def _coeff(var): + return self._get_index_coefficient(index, var, default=float("inf")) + + used_iter_vars = sorted(used_iter_vars_set, key=_coeff, reverse=True) + iter_coeffs = [_coeff(var) for var in used_iter_vars] + + # Rename symbolic sizes to kernel parameter names + index_str = self.kexpr(self.rename_indexing(index)) + indirect_var_syms = self._get_indirect_vars(index) + indirect_vars = [str(sym) for sym in indirect_var_syms] + + # Get coefficients for indirect vars to determine output ordering + indirect_coeffs = {str(s): _coeff(s) for s in indirect_var_syms} + + # Special case: reduction var + single indirect var = element-wise gather + # Reduction vars (r prefix) iterate over the reduction dimension, and when paired + # with an indirect var, both are aligned to that dimension (element-wise). + # Pointwise vars form output dimensions and need the complex reshape code. + if len(used_iter_vars) == 1 and len(indirect_vars) == 1: + var = used_iter_vars[0] + var_name = str(var) + is_reduction_var = ( + var in self.range_tree_nodes and self.range_tree_nodes[var].is_reduction + ) + + if is_reduction_var: + # Reduction var: simple element-wise gather + if var in self.range_tree_nodes: + range_entry = self.range_tree_nodes[var] + range_size = range_entry.length + # Rename to use kernel parameter names for symbolic sizes + renamed_size = self.rename_indexing(range_size) + arange_expr = f"jnp.arange({self.kexpr(renamed_size)})" + index_str = index_str.replace(var_name, arange_expr) + return index_str + # For pointwise vars, fall through to the complex reshape code + + # Check if multiple indirect vars should be paired element-wise. + # In PyTorch, when multiple advanced indices have the same shape, they pair up. + # The paired dimension goes to the FRONT of the output. + # However, if indirect vars have different shapes (e.g., (1,4) and (4,1)), + # they form an outer product instead. + # We detect element-wise pairing when: + # 1. Multiple indirect vars exist + # 2. There's exactly ONE unused iteration variable (for the shared paired dim) + # For outer product, there are MULTIPLE unused iter vars (one per indirect dim) + paired_indirect = False + if len(indirect_vars) > 1: + # Count unused iteration variables (defined but not in index expression) + unused_iter_vars = self._get_iter_vars() - used_iter_vars_set + # Element-wise pairing: one unused iter var for the shared paired dimension + # Outer product: multiple unused iter vars (one for each indirect var dimension) + paired_indirect = len(unused_iter_vars) == 1 + + if paired_indirect: + # Multiple indirect vars with element-wise pairing + # Output order: (paired_indirect_dim, iter_var_dims...) + # All indirect vars get the same shape: (N, 1, 1, ...) for first dim + # Iter vars come after: second dim onwards + + # Count total output dims: 1 (paired) + len(iter_vars) for non-newaxis + # But some iter vars may be for newaxis dimensions (size 1) + n_output_dims = 1 + len(used_iter_vars) + + # Reshape indirect vars to occupy the first dimension + for indirect_var in indirect_vars: + trailing_ones = ", 1" * len(used_iter_vars) + reshape_expr = f"{indirect_var}.reshape(-1{trailing_ones})" + index_str = index_str.replace(indirect_var, reshape_expr) + + # Reshape iteration variables to occupy subsequent dimensions + # Sort by coefficient (descending) to determine order + for i, var in enumerate(used_iter_vars): + var_name = str(var) + if var in self.range_tree_nodes: + range_entry = self.range_tree_nodes[var] + range_size = range_entry.length + # Rename to use kernel parameter names for symbolic sizes + renamed_size = self.rename_indexing(range_size) + + # Shape: (1, ..., N, ..., 1) where N is at position i+1 + # Position 0 is for paired indirect vars + shape_parts = ["1"] * n_output_dims + shape_parts[i + 1] = self.kexpr(renamed_size) + shape_str = ", ".join(shape_parts) + arange_expr = ( + f"jnp.arange({self.kexpr(renamed_size)}).reshape({shape_str})" + ) + + index_str = index_str.replace(var_name, arange_expr) + + return index_str + + # Single indirect var case (or no indirect vars handled above) + # Build a sorted list of all components by coefficient (descending) + # Each component is (coeff, type, var) where type is 'iter' or 'indirect' + all_components = [] + for var in used_iter_vars: + all_components.append((_coeff(var), "iter", var)) + for sym in indirect_var_syms: + all_components.append((_coeff(sym), "indirect", sym)) + all_components.sort(key=lambda x: x[0], reverse=True) + + # Calculate trailing dims needed for each component + # Each component needs trailing dims for all subsequent iter vars + # plus trailing dims for all dimensions of subsequent indirect vars + # For simplicity, assume each indirect var contributes some dimensions + # that will be handled by the reshape at store time + + # For iter vars, we need to count how many dimensions come after in the output + for i, var in enumerate(used_iter_vars): + var_name = str(var) + if var in self.range_tree_nodes: + range_entry = self.range_tree_nodes[var] + range_size = range_entry.length + # Rename to use kernel parameter names for symbolic sizes + renamed_size = self.rename_indexing(range_size) + var_coeff = _coeff(var) + + arange_expr = f"jnp.arange({self.kexpr(renamed_size)})" + + # Count trailing dims needed: + # - One for each subsequent iter var (with smaller coeff) + # - One for each dimension of indirect vars with smaller coeff + # For indirect vars, assume each contributes 2 dims (common case) + # The actual reshape at store time will fix any shape mismatches + n_trailing_iter = sum(1 for c in iter_coeffs if c < var_coeff) + n_trailing_indirect = sum( + 2 for c in indirect_coeffs.values() if c < var_coeff + ) + n_trailing = n_trailing_iter + n_trailing_indirect + + if n_trailing > 0: + trailing_dims = ", None" * n_trailing + arange_expr = f"{arange_expr}[:{trailing_dims}]" + + index_str = index_str.replace(var_name, arange_expr) + + # Reshape indirect variables for proper broadcasting. + for indirect_var in indirect_vars: + indirect_coeff = indirect_coeffs[indirect_var] + + # Count dims needed before and after this indirect var + n_leading = sum(1 for c in iter_coeffs if c > indirect_coeff) + n_trailing = sum(1 for c in iter_coeffs if c < indirect_coeff) + + # Build the indexing expression with leading Nones, ellipsis, trailing Nones + if n_leading > 0 and n_trailing > 0: + leading_nones = "None, " * n_leading + trailing_nones = ", None" * n_trailing + reshape_expr = f"{indirect_var}[{leading_nones}...{trailing_nones}]" + elif n_leading > 0: + leading_nones = "None, " * n_leading + reshape_expr = f"{indirect_var}[{leading_nones}...]" + elif n_trailing > 0: + trailing_nones = ", None" * n_trailing + reshape_expr = f"{indirect_var}[...{trailing_nones}]" + else: + reshape_expr = indirect_var + + index_str = index_str.replace(indirect_var, reshape_expr) + + return index_str + + @typing_extensions.override + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: Any = None + ) -> None: + # mode can be None (set), "atomic_add" (accumulate), etc. + if mode is not None and mode != "atomic_add": + raise Unsupported(f"pallas store mode '{mode}' not supported") + out = self.args.output(name) + self.store_buffer_names.add(name) + + # Check if this is a scalar output (reduction to scalar) + buf = V.graph.get_buffer(name) + is_scalar = buf is not None and len(buf.get_size()) == 0 + + if is_scalar: + store_lines = [ + f"_val = jnp.asarray({value})", + f"{out}[...] = jnp.full({out}.shape, _val) if _val.ndim == 0 else _val.reshape({out}.shape)", + ] + else: + # When collapsed_output_shape is set, the load-side permutation + # already produces data in the correct layout for the collapsed + # output. Force a full-array store ("...") so the scatter index + # (which was computed for the original output layout) does not + # rearrange the permuted data. + if self.collapsed_output_shape is not None: + store_lines = self._build_full_array_store_expr(out, value, False) + else: + # Check for scatter pattern (indirect indexing for stores) + scatter_info = self._detect_scatter_pattern(index, name) + + if scatter_info is not None: + # Track iteration variables used in scatter index + self.used_iter_vars.update(self._get_used_iter_vars(index)) + store_lines = [ + self._build_scatter_store_expr( + out, value, scatter_info, name, mode + ) + ] + else: + # Get base index expression + indexing = self._get_index_expr(index) + + # Adjust index for buffer shape (scalar, multi-dim, etc.) + indexing = self._adjust_index_for_buffer_shape( + name, index, indexing + ) + + # Check for im2col-like patterns + indexing = self._check_im2col_pattern(index, indexing) + + # Build the store expression + store_lines = self._build_store_expr( + out, name, index, value, indexing, mode + ) + + for line in store_lines: + self.stores.writeline(line) + # Track which output param this store uses for filtering in codegen_kernel + self.store_with_output.append((out, line)) + + @staticmethod + def _get_index_coefficient( + index: sympy.Expr, var: sympy.Symbol, default: int | float = 0 + ) -> int | float: + """Get integer coefficient of a variable in an index expression.""" + coeff = index.coeff(var) + if coeff == 0: + coeff = sympy.diff(index, var) + try: + return int(coeff) + except (TypeError, ValueError): + return default + + def _detect_scatter_pattern( + self, index: sympy.Expr, output_name: str = "" + ) -> dict[str, Any] | None: + """Detect scatter operation pattern. Returns scatter info dict or None.""" + indirect_syms = self._get_indirect_vars(index) + if len(indirect_syms) != 1: + return None + + indirect_sym = indirect_syms[0] + indirect_var = str(indirect_sym) + indirect_coeff: int = int(self._get_index_coefficient(index, indirect_sym)) + if indirect_coeff == 0: + return None + + # Point scatter: no iteration variables, just indirect indexing + if not self._has_iteration_vars(index): + return self._detect_point_scatter(output_name, indirect_var, indirect_coeff) + + # Regular scatter: has both indirect and iteration variables + return self._detect_iter_scatter(index, indirect_var, indirect_coeff) + + def _detect_point_scatter( + self, output_name: str, indirect_var: str, indirect_coeff: int + ) -> dict[str, Any] | None: + """Detect single-element scatter pattern.""" + if not output_name: + return None + try: + buf = V.graph.get_buffer(output_name) + output_shape = [int(s) for s in buf.get_size()] + except Exception: + return None + + if len(output_shape) < 2: + return None + + # Find which dimension indirect var indexes based on coefficient + cumulative = 1 + indirect_dim = len(output_shape) - 1 + for dim in range(len(output_shape) - 1, -1, -1): + if indirect_coeff == cumulative: + indirect_dim = dim + break + cumulative *= output_shape[dim] + + return { + "indirect_var": indirect_var, + "indirect_dim": indirect_dim, + "dims_before": [], + "dims_after": [], + "is_point_scatter": True, + "output_shape": output_shape, + } + + def _detect_iter_scatter( + self, index: sympy.Expr, indirect_var: str, indirect_coeff: int + ) -> dict[str, Any] | None: + """Detect scatter pattern with iteration variables.""" + used_iter_vars = self._get_used_iter_vars(index) + + # Collect (var_name, coefficient, length) for each variable + all_vars: list[tuple[str, int, int]] = [] + for var in used_iter_vars: + coeff = int(self._get_index_coefficient(index, var)) + if coeff > 0 and var in self.range_tree_nodes: + length = self._safe_int(self.range_tree_nodes[var].length) + if length is None: + return None + all_vars.append((str(var), coeff, length)) + + all_vars.append((indirect_var, indirect_coeff, -1)) + all_vars.sort(key=lambda x: x[1], reverse=True) + + # Find indirect variable position + indirect_pos = next( + (i for i, (name, _, _) in enumerate(all_vars) if name == indirect_var), + None, + ) + if indirect_pos is None: + return None + + # Verify coefficients form valid stride pattern + expected = 1 + for _, coeff, length in reversed(all_vars[indirect_pos + 1 :]): + if coeff != expected: + return None + expected *= length + if indirect_coeff != expected: + return None + + return { + "indirect_var": indirect_var, + "indirect_dim": indirect_pos, + "dims_before": [(n, l) for n, _, l in all_vars[:indirect_pos]], + "dims_after": [(n, l) for n, _, l in all_vars[indirect_pos + 1 :]], + "is_point_scatter": False, + "output_shape": None, + } + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: # type: ignore[override] + """ + Generate code for reduction operations in JAX/Pallas. + + Reductions in Pallas work by: + 1. Loading the input data into the kernel + 2. Applying JAX reduction operations (jnp.sum, jnp.max, etc.) + 3. Storing the reduced result + + The reduction happens over the loaded block of data. + """ + if not self.inside_reduction: + raise AssertionError("expected to be inside a reduction") + + # Handle welford_reduce using the fallback (computes via sum reductions) + if reduction_type == "welford_reduce": + return self.welford_reduce_fallback(dtype, value) + + if isinstance(value, tuple): + raise Unsupported( + "Tuple reductions (e.g., welford_combine) not supported in Pallas backend" + ) + + # Check if this reduction is already cached. + cache_key = (src_dtype, reduction_type, value) + if cache_key in self.cse.reduction_cache: + return self.cse.reduction_cache[cache_key] + + # Map reduction types to JAX functions + reduction_ops = { + "sum": "jnp.sum", + "prod": "jnp.prod", # CPU only - not supported in Pallas GPU (Mosaic) backend + "max": "jnp.max", + "min": "jnp.min", + "any": "jnp.any", + "argmax": "jnp.argmax", + "argmin": "jnp.argmin", + } + + # Determine if this is a partial reduction (has pointwise dimensions) + # or a full reduction to scalar + pointwise_prefixes = OrderedSet(["x", "y", "z"]) + has_pointwise = any(p in self.numels for p in pointwise_prefixes) + pointwise_numel: int | None = self._compute_prefix_numel(pointwise_prefixes) + reduction_numel: int | None = self._compute_reduction_numel() + n_reduction_dims = sum( + 1 for entry in self.range_tree_nodes.values() if entry.is_reduction + ) + + is_partial_reduction = ( + has_pointwise + and pointwise_numel is not None + and pointwise_numel > 1 + and reduction_numel + and n_reduction_dims > 0 + ) + is_symbolic_partial = ( + has_pointwise and n_reduction_dims > 0 and pointwise_numel is None + ) + + if reduction_type == "xor_sum": + if is_partial_reduction: + axes = self._get_reduction_axes() + axis_expr = axes[0] if len(axes) == 1 else axes + reduction_expr = f"jnp.bitwise_xor.reduce({value}, axis={axis_expr})" + else: + reduction_expr = f"jnp.bitwise_xor.reduce({value})" + elif reduction_type in ("argmax", "argmin"): + reduction_op = reduction_ops[reduction_type] + if is_partial_reduction: + # argmax/argmin only accept a single axis + axes = self._get_reduction_axes() + reduction_expr = f"{reduction_op}({value}, axis={axes[-1]})" + else: + reduction_expr = f"{reduction_op}({value})" + elif reduction_type in reduction_ops: + reduction_op = reduction_ops[reduction_type] + if is_partial_reduction: + axes = self._get_reduction_axes() + axis_expr = axes[0] if len(axes) == 1 else axes + reduction_expr = ( + f"{reduction_op}({value}, axis={axis_expr}, keepdims=True)" + ) + elif is_symbolic_partial: + # With symbolic shapes, strided loads produce a degenerate + # batch dim at axis=0 that just needs squeezing. + reduction_expr = f"{reduction_op}({value}, axis=0)" + else: + reduction_expr = f"{reduction_op}({value})" + else: + raise Unsupported( + f"Reduction type '{reduction_type}' not yet supported in Pallas backend. " + f"Supported types: {list(reduction_ops.keys())}, xor_sum" + ) + + # Generate CSE variable for the reduction result + result = self.cse.generate( + self.compute, + reduction_expr, + dtype=dtype, + ) + + # Cache the result + self.cse.reduction_cache[cache_key] = result + return result + + @staticmethod + def _buffer_is_contiguous(buffer_name: str) -> bool: + buf = V.graph.get_buffer(buffer_name) + layout = buf.get_layout() + return layout.is_contiguous() + + def _can_tile_cpu_tpu(self) -> bool: + """Check if this kernel can use tiling on CPU/TPU. + + Tiling is compatible with reductions, transpositions, and multi-range-tree + kernels as long as no flatten-based indexing is used (buf[...].flatten()[idx]). + Flatten indexing requires global flat indices which don't decompose into + per-tile local indices. + + Reject: + - GPU (has its own TMA / padding path) + - Flatten-based indexing + - Scatter outputs (indirect indexing complicates tile boundaries) + """ + if self.is_gpu: + return False + if self.has_flatten_indexing: + return False + if self.outputs_need_read: + return False + + # If iteration variables appear in the compute body (not just in + # load/store index resolution that collapses to [...]), tiling is + # unsafe because the arange-based vars have full-tensor shapes. + # Exception: vars emitted in tile-relative form are safe. + if self.used_iter_vars: + compute_text = "\n".join(str(line) for line in self.compute._lines) + for var_sym in self.used_iter_vars: + if var_sym in self.tile_relative_iter_vars: + continue + if str(var_sym) in compute_text: + return False + + # Determine the reference output shape (highest-ndim output). + out_bufs = list(self.args.output_buffers.keys()) + + # Only check the current kernel's actual output buffers for transpose, + # not _has_column_major_output() which scans all graph buffers and can + # be triggered by unrelated intermediates (e.g., (N,1) reductions with + # degenerate column-major strides). + has_col_major_out = False + for buf_name in out_bufs: + info = self._get_buffer_info(buf_name) + if info is None: + continue + _, buf_size, _, actual_strides, _ = info + if len(actual_strides) >= 2 and len(buf_size) >= 2: + s0 = actual_strides[0] + s1 = actual_strides[1] + d0 = self._safe_int(buf_size[0]) + d1 = self._safe_int(buf_size[1]) + if ( + s0 is not None + and s1 is not None + and s0 < s1 + and d0 is not None + and d1 is not None + and d0 > 1 + and d1 > 1 + ): + has_col_major_out = True + break + self.tile_has_transpose = bool(self.permuted_input_buffers) or has_col_major_out + + # Count trailing reduction dimensions in the output shape that must + # not be tiled (the kernel body needs the full reduction range). + # Only count when the kernel actually performs reduction (numel > 1). + reduction_numel = self._compute_reduction_numel() + has_reduction = reduction_numel is not None and reduction_numel > 1 + self.tile_skip_last_n = ( + sum(1 for tree in self.range_trees if tree.is_reduction) + if has_reduction + else 0 + ) + + ref_shape: list[int] = [] + for buf_name in out_bufs: + info = self._get_buffer_info(buf_name) + if info is None: + return False + _, buf_size, _, _, _ = info + int_size = [self._safe_int(s) for s in buf_size] + if any(s is None for s in int_size): + return False + if len(int_size) > len(ref_shape): + ref_shape = int_size # type: ignore[assignment] + + if not ref_shape: + return False + + # For collapsed permutation kernels, override ref_shape with the + # collapsed output shape so all compatibility checks operate in + # collapsed-shape space. + if self.collapsed_output_shape is not None: + ref_shape = list(self.collapsed_output_shape) + + ref_nd = len(ref_shape) + + all_bufs = list(self.args.input_buffers) + out_bufs + has_tileable = False + for buf_name in all_bufs: + info = self._get_buffer_info(buf_name) + if info is None: + return False + _, buf_size, _, _, _ = info + if len(buf_size) == 0: + continue # scalar + + # Use collapsed shapes when available so dimension checks + # operate in the same space as the kernel. + if buf_name in self.collapsed_reshape_inputs: + int_size = list(self.collapsed_reshape_inputs[buf_name]) + elif self.collapsed_output_shape is not None and buf_name in out_bufs: + int_size = list(self.collapsed_output_shape) + else: + int_size = [self._safe_int(s) for s in buf_size] + if any(s is None for s in int_size): + return False + buf_nd = len(int_size) + + if buf_nd == ref_nd: + # Same ndim: check dimensions match or are broadcast (1). + # Allow strided buffers (dims may differ after reshape). + is_strided = buf_name in self.strided_input_buffers + mismatch = False + for i in range(ref_nd): + if ( + int_size[i] == ref_shape[i] + or int_size[i] == 1 + or ref_shape[i] == 1 + or is_strided + ): + continue + mismatch = True + break + + if mismatch and buf_name in self.permuted_input_buffers: + perm = self.permuted_input_buffers[buf_name] + if not ( + len(perm) == ref_nd + and all( + int_size[perm[i]] == ref_shape[i] + or int_size[perm[i]] == 1 + or ref_shape[i] == 1 + for i in range(ref_nd) + ) + ): + return False + elif mismatch: + return False + + # At least one buffer with a tileable dim + if is_strided or any( + int_size[i] == ref_shape[i] and ref_shape[i] > 1 + for i in range(ref_nd) + ): + has_tileable = True + + elif buf_nd > ref_nd: + # Reduction input with extra dims. Find an alignment offset k + # such that buf_shape[k+i] == ref_shape[i] for all i (skipping + # broadcast dims where ref_shape[i] == 1). + found = False + for k in range(buf_nd - ref_nd + 1): + ok = True + for i in range(ref_nd): + if ref_shape[i] == 1: + continue + if int_size[k + i] != ref_shape[i]: + ok = False + break + if ok: + found = True + break + if not found: + return False + has_tileable = True + + else: + # Fewer dims: verify numpy-style broadcastability + for a, b in zip(reversed(int_size), reversed(ref_shape)): + if a != b and a != 1 and b != 1: + return False + + if not has_tileable: + return False + + # On CPU (interpret mode) each tile iteration has significant + # Python/JAX overhead, so cap the grid size. Store the cap + # so _codegen_tiled_specs can pass it to pallas_compute_tiling, + # which will scale up tiles to stay within the limit. + is_tpu = V.graph.get_current_device_or_throw().type == "tpu" + if not is_tpu: + self._cpu_max_grid_product = 64 + else: + self._cpu_max_grid_product = None + + return True + + def codegen_kernel(self, name: str | None = None) -> str: # type: ignore[override] + """ + Generate the complete Pallas kernel code as a Python string. + + This includes: + - Import statements for JAX/Pallas + - The kernel function that operates on refs + - The main wrapper function that handles PyTorch<->JAX conversions via DLPack + + Args: + name: Optional kernel name (will use placeholder if not provided) + + Returns: + str: Complete Python source code for the Pallas kernel + """ + code = IndentedBuffer() + + # Define the Pallas kernel: accepts refs, uses broadcasted expressions + arg_defs, call_args, _, _ = self.args.python_argdefs() + kernel_params = [a.name for a in arg_defs] + pure_out_params = [p for p in kernel_params if p.startswith("out_ptr")] + output_params = [ + p for p in kernel_params if p.startswith(("out_ptr", "in_out_ptr")) + ] + # Identify size variable parameters (scalars like load_seed_offset) + size_var_names = OrderedSet(self.args.sizevars.values()) + size_var_params = [p for p in kernel_params if p in size_var_names] + if not output_params: + raise RuntimeError("Pallas backend requires at least one output buffer") + + output_buffer_lookup = { + inner: outer + for outer, inner in self.args.output_buffers.items() + if isinstance(inner, str) + } + + kernel_name = name or "" + interpret_is_cpu = V.graph.get_current_device_or_throw().type == "cpu" + interpret_literal = "True" if interpret_is_cpu else "False" + + aliasable_flags: dict[str, bool] = {} + for param in pure_out_params: + aliasable_flags[param] = True + alias_params = [ + f"{param}_alias" for param in pure_out_params if aliasable_flags[param] + ] + pointer_tail = [ + p for p in kernel_params if p.startswith(("in_out_ptr", "in_ptr")) + ] + kernel_input_params = alias_params + pointer_tail + full_kernel_params = alias_params + kernel_params + non_alias_out_set = OrderedSet( + [name for name, flag in aliasable_flags.items() if not flag] + ) + # On CPU (interpret=True), pallas_call returns new arrays so we must + # copy back every output. On TPU, call_custom_kernel with + # input_output_aliases handles donation (zero-copy), so no copy is + # needed. On CUDA, aliased outputs are mutated in-place by the + # donated-buffer mechanism so only non-aliased outputs need a copy. + if interpret_is_cpu: + copy_output_indices = list(range(len(output_params))) + elif self.is_tpu: + copy_output_indices = [] + else: + copy_output_indices = [ + idx + for idx, name in enumerate(output_params) + if name in non_alias_out_set + ] + + ctx = _CodegenContext( + code=code, + kernel_name=kernel_name, + is_tpu=self.is_tpu, + interpret_is_cpu=interpret_is_cpu, + interpret_literal=interpret_literal, + kernel_params=kernel_params, + pure_out_params=pure_out_params, + output_params=output_params, + size_var_params=size_var_params, + output_buffer_lookup=output_buffer_lookup, + aliasable_flags=aliasable_flags, + alias_params=alias_params, + pointer_tail=pointer_tail, + kernel_input_params=kernel_input_params, + full_kernel_params=full_kernel_params, + non_alias_out_set=non_alias_out_set, + copy_output_indices=copy_output_indices, + alias_pairs=[], + ) + self.aliasable_out_ptrs = aliasable_flags + + self._codegen_imports(ctx) + + kernel_body = IndentedBuffer() + with kernel_body.indent(): + self._codegen_iteration_vars(kernel_body, ctx) + + for line in self.compute._lines: + kernel_body.writeline(str(line)) + + # Recompute kernel parameters after kernel body generation. + # Size variables may have been registered during kernel body generation + # (e.g., via rename_indexing for symbolic sizes), so we need to re-fetch + # the arg defs to capture all parameters including newly-registered size vars. + arg_defs, call_args, _, _ = self.args.python_argdefs() + kernel_params = [a.name for a in arg_defs] + size_var_names = OrderedSet(self.args.sizevars.values()) + ctx.size_var_params = [p for p in kernel_params if p in size_var_names] + ctx.pointer_tail = [ + p for p in kernel_params if p.startswith(("in_out_ptr", "in_ptr")) + ] + ctx.kernel_input_params = alias_params + ctx.pointer_tail + ctx.full_kernel_params = alias_params + kernel_params + + # Decide whether to use tiling for CPU/TPU after kernel body is fully + # generated (used_iter_vars is populated during load/store codegen). + self.tile_cpu_tpu = self._can_tile_cpu_tpu() + + extra_kernel_params = "" + if self.tile_relative_iter_vars: + extra_kernel_params = ", _pallas_tile=None, _pallas_ax2g=None" + + ctx.alias_pairs = self._compute_alias_pairs(ctx, aliasable_flags) + + use_scalar_prefetch = bool(self.indirect_access) + + if use_scalar_prefetch: + self._eliminate_dead_indirect_code() + kernel_body_sp = IndentedBuffer() + with kernel_body_sp.indent(): + for line in self.compute._lines: + kernel_body_sp.writeline(str(line)) + self._codegen_scalar_prefetch_wrapper( + ctx, + kernel_name, + kernel_body_sp, + ) + return code.getvalue() + + # Emit the kernel function with the correct signature + kernel_signature = f"def {kernel_name}_kernel({', '.join(ctx.full_kernel_params)}{extra_kernel_params}):" + code.writeline(kernel_signature) + + with code.indent(): + self._emit_kernel_body(code, kernel_body, ctx) + + code.writeline("") + jit_wrapper_name = f"{kernel_name}_jit_wrapper" + donate_indices = [] + base_offset = 2 + len(ctx.size_var_params) + for idx, name in enumerate(ctx.kernel_input_params): + if (name in alias_params) or name.startswith("in_out_ptr"): + donate_indices.append(idx + base_offset) + if donate_indices: + donate_literal = "(" + ", ".join(str(x) for x in donate_indices) + ",)" + else: + donate_literal = "()" + static_argnums = list(range(2 + len(ctx.size_var_params))) + static_argnums_literal = "(" + ", ".join(str(x) for x in static_argnums) + ",)" + code.writeline( + "@functools.partial(" + f"jax.jit, static_argnums={static_argnums_literal}, donate_argnums=" + f"{donate_literal})" + ) + wrapper_params = ( + ["out_shapes", "out_dtypes"] + ctx.size_var_params + ctx.kernel_input_params + ) + code.writeline(f"def {jit_wrapper_name}({', '.join(wrapper_params)}):") + + alias_map_literal = ", ".join(f"{i}: {o}" for (i, o) in ctx.alias_pairs) + + has_zero_dim, has_unknown_dim = self._zero_dim_output_flags(ctx) + + zero_dim_return = ( + "results = tuple(jnp.empty(s, dtype=dt) " + "for s, dt in zip(out_shapes, out_dtypes))", + "return results if len(results) > 1 else results[0]", + ) + + with code.indent(): + if has_zero_dim: + code.writelines(zero_dim_return) + else: + if has_unknown_dim: + code.writeline("if any(0 in shape for shape in out_shapes):") + with code.indent(): + code.writelines(zero_dim_return) + # Pallas requires >= 1-d tensors; promote 0-d to (1,) + code.writeline( + "_pallas_out_shapes = tuple(" + "s if len(s) > 0 else (1,) for s in out_shapes)" + ) + if self.collapsed_output_shape is not None: + code.writeline( + f"_pallas_out_shapes = ({self.collapsed_output_shape},)" + ) + # Reshape aliased inputs to match promoted output shapes + for input_idx, out_idx in ctx.alias_pairs: + param = ctx.kernel_input_params[input_idx] + code.writeline( + f"{param} = {param}.reshape(_pallas_out_shapes[{out_idx}])" + ) + code.writeline("out_shapes_pallas = tuple(") + code.writeline(" jax.ShapeDtypeStruct(shape, dtype)") + code.writeline( + " for shape, dtype in zip(_pallas_out_shapes, out_dtypes)" + ) + code.writeline(")") + if self.tile_cpu_tpu: + self._codegen_tiled_specs(ctx) + else: + self._codegen_strided_reshapes(code, ctx.kernel_input_params) + for param in ctx.kernel_input_params: + buf_name = self._param_to_buf_name(param) + cshape = ( + self.collapsed_reshape_inputs.get(buf_name) + if buf_name + else None + ) + if cshape is not None: + code.writeline(f"{param} = {param}.reshape({cshape})") + + code.writeline("out_specs_pallas = tuple(") + code.writeline(" pallas_make_block_spec_non_tiled(shape)") + code.writeline( + " for shape, dtype in zip(_pallas_out_shapes, out_dtypes)" + ) + code.writeline(")") + code.writeline("in_specs_pallas = tuple(") + code.writeline(" pallas_make_block_spec_non_tiled(i.shape)") + code.writeline( + " for i in [" + ", ".join(ctx.kernel_input_params) + "]" + ) + code.writeline(")") + + if self.tile_relative_iter_vars: + if self.tile_cpu_tpu: + code.writeline("_pallas_tile = _tile") + code.writeline("_pallas_ax2g = _ax2g") + else: + code.writeline("_pallas_tile = _pallas_out_shapes[0]") + code.writeline("_pallas_ax2g = {}") + + # Wrap kernel with functools.partial to pass scalar arguments (size variables) + partial_args = [] + for sv_param in ctx.size_var_params: + partial_args.append(f"{sv_param}={sv_param}") + + if self.tile_relative_iter_vars: + partial_args.append("_pallas_tile=_pallas_tile") + partial_args.append("_pallas_ax2g=_pallas_ax2g") + + if partial_args: + kernel_arg = f"functools.partial({kernel_name}_kernel, {', '.join(partial_args)})," + else: + kernel_arg = f"{kernel_name}_kernel," + + use_tma = ( + self.is_gpu + and self.use_emit_pipeline + and self._can_use_tma_approach() + ) + if use_tma: + self._codegen_jit_wrapper_tma(ctx, kernel_arg) + elif self.is_gpu: + self._codegen_jit_wrapper_legacy_gpu(ctx, kernel_arg) + else: + self._codegen_jit_wrapper_cpu_tpu( + ctx, kernel_arg, ctx.alias_pairs, alias_map_literal + ) + + self._codegen_main_entry(ctx, jit_wrapper_name) + return code.getvalue() + + @staticmethod + def _compute_alias_pairs( + ctx: _CodegenContext, aliasable_flags: dict[str, bool] + ) -> list[tuple[int, int]]: + alias_pairs: list[tuple[int, int]] = [] + for out_idx, name in enumerate(ctx.output_params): + if name.startswith("out_ptr"): + if aliasable_flags.get(name, False): + alias_name = f"{name}_alias" + input_idx = ctx.kernel_input_params.index(alias_name) + alias_pairs.append((input_idx, out_idx)) + else: + input_idx = ctx.kernel_input_params.index(name) + alias_pairs.append((input_idx, out_idx)) + return alias_pairs + + def _emit_kernel_body( + self, + code: IndentedBuffer, + kernel_body: IndentedBuffer, + ctx: _CodegenContext, + ) -> None: + """Emit the kernel body lines and store operations into code.""" + for line in kernel_body._lines: + if isinstance(line, str): + code.writeline(line.lstrip()) + else: + code._lines.append(line) + for out_ptr, store_line in self.store_with_output: + if out_ptr in ctx.full_kernel_params: + code.writeline(store_line) + + def _codegen_scalar_prefetch_wrapper( + self, + ctx: _CodegenContext, + kernel_name: str, + kernel_body: IndentedBuffer, + ) -> None: + """Emit kernel, JIT wrapper, and main entry for scalar prefetch.""" + if self.indirect_access is None: + raise AssertionError("expected indirect_access to be set") + indirect = self.indirect_access + code = ctx.code + + alias_set = OrderedSet(ctx.alias_params) + other_input_params = [ + p + for p in ctx.kernel_input_params + if p != indirect.indices_param + and p != indirect.table_param + and p not in alias_set + ] + + # Emit kernel function with params reordered for PrefetchScalarGridSpec: + # [scalar_prefetch] + [in_specs refs] + [out_specs refs] + prefetch_kernel_params = ( + [indirect.indices_param] + + [indirect.table_param] + + other_input_params + + list(ctx.alias_params) + + ctx.output_params + ) + code.writeline( + f"def {kernel_name}_kernel({', '.join(prefetch_kernel_params)}):" + ) + with code.indent(): + self._emit_kernel_body(code, kernel_body, ctx) + + # Emit JIT wrapper + code.writeline("") + jit_wrapper_name = f"{kernel_name}_jit_wrapper" + wrapper_params = ( + ["out_shapes", "out_dtypes"] + ctx.size_var_params + ctx.kernel_input_params + ) + static_argnums = list(range(2 + len(ctx.size_var_params))) + static_argnums_literal = "(" + ", ".join(str(x) for x in static_argnums) + ",)" + code.writeline( + f"@functools.partial(jax.jit, static_argnums={static_argnums_literal})" + ) + code.writeline(f"def {jit_wrapper_name}({', '.join(wrapper_params)}):") + + with code.indent(): + table = indirect.table_param + indices = indirect.indices_param + + ind_dim = indirect.indirect_dim + ndim = len(indirect.table_shape) + code.writeline("_D = 1") + for i in range(ndim): + if i != ind_dim: + code.writeline(f"_D = _D * {table}.shape[{i}]") + code.writeline(f"_seq = {indices}.shape[0]") + + if ind_dim == 0: + code.writeline(f"_table_3d = {table}.reshape({table}.shape[0], 1, _D)") + else: + perm = (ind_dim, *[d for d in range(ndim) if d != ind_dim]) + code.writeline( + f"_table_3d = {table}.transpose{perm}.reshape(" + f"{table}.shape[{ind_dim}], 1, _D)" + ) + + # Reshape other (non-table, non-indices) inputs to 3D to match the + # table's (seq, 1, D) layout. Currently handles: + # - 2D with leading dim == seq: row-aligned, reshape to (seq, 1, D) + # - 1D: broadcast scalar/vector, reshape to (1, 1, numel) + # - else: flatten to (1, 1, -1) — assumes broadcastable with + # (seq, 1, D). This may not work correctly for 3D+ inputs. + pallas_call_other_args = [] + for p in other_input_params: + p3d = f"_{p}_3d" + code.writeline(f"if {p}.ndim == 2 and {p}.shape[0] == _seq:") + code.writeline(f" {p3d} = {p}.reshape(_seq, 1, _D)") + code.writeline(f"elif {p}.ndim == 1:") + code.writeline(f" {p3d} = {p}.reshape(1, 1, {p}.shape[0])") + code.writeline("else:") + code.writeline(f" {p3d} = {p}.reshape(1, 1, -1)") + pallas_call_other_args.append(p3d) + + pallas_call_alias_args = [] + for p in ctx.alias_params: + p3d = f"_{p}_3d" + code.writeline(f"{p3d} = {p}.reshape(_seq, 1, _D)") + pallas_call_alias_args.append(p3d) + + partial_args = [f"{sv}={sv}" for sv in ctx.size_var_params] + if partial_args: + kernel_ref = ( + f"functools.partial({kernel_name}_kernel," + f" {', '.join(partial_args)})" + ) + else: + kernel_ref = f"{kernel_name}_kernel" + + # Reusable row-tiled BlockSpec (all i32 index_map for Mosaic compat) + code.writeline( + "_ROW_SPEC = pl.BlockSpec((1, 1, _D)," + " lambda i, _: (i, jnp.int32(0), jnp.int32(0)))" + ) + + num_non_alias_in_specs = 1 + len(pallas_call_other_args) + code.writeline("_in_specs = [") + with code.indent(): + code.writeline( + "pl.BlockSpec((1, 1, _D)," + " lambda gi, idx: (idx[gi], jnp.int32(0), jnp.int32(0)))," + ) + for p3d in pallas_call_other_args: + code.writeline( + f"_ROW_SPEC" + f" if {p3d}.shape[0] == _seq else" + f" pl.BlockSpec({p3d}.shape," + f" lambda i, _: (jnp.int32(0), jnp.int32(0), jnp.int32(0)))," + ) + for _ in ctx.alias_params: + code.writeline("_ROW_SPEC,") + code.writeline("]") + + num_outputs = len(ctx.output_params) + code.writeline( + "_out_specs = [" + ", ".join(["_ROW_SPEC"] * num_outputs) + "]" + ) + + # input_output_aliases: pallas_call arg index -> output index + # (offset by 1 for scalar prefetch arg) + alias_map_parts = [] + for out_idx, _ in enumerate(ctx.alias_params): + arg_idx = 1 + num_non_alias_in_specs + out_idx + alias_map_parts.append(f"{arg_idx}: {out_idx}") + alias_map_literal = ", ".join(alias_map_parts) + + out_shape_parts = [ + f"jax.ShapeDtypeStruct((_seq, 1, _D), out_dtypes[{i}])" + for i in range(num_outputs) + ] + out_shape_expr = "[" + ", ".join(out_shape_parts) + "]" + + code.writeline("_result = pl.pallas_call(") + with code.indent(): + code.writeline(f"{kernel_ref},") + code.writeline(f"out_shape={out_shape_expr},") + code.writeline("grid_spec=pltpu.PrefetchScalarGridSpec(") + with code.indent(): + code.writeline("num_scalar_prefetch=1,") + code.writeline("grid=(_seq,),") + code.writeline("in_specs=_in_specs,") + code.writeline("out_specs=_out_specs,") + code.writeline("),") + if alias_map_parts: + code.writeline(f"input_output_aliases={{ {alias_map_literal} }},") + if not self.is_tpu: + code.writeline(f"interpret={ctx.interpret_literal},") + + all_pallas_args = ( + [indices] + + ["_table_3d"] + + pallas_call_other_args + + pallas_call_alias_args + ) + code.writeline(f")({', '.join(all_pallas_args)})") + + code.writeline( + "return tuple(r.reshape(s) for r, s in zip(_result, out_shapes))" + ) + + self._codegen_main_entry(ctx, jit_wrapper_name) + + def _codegen_imports(self, ctx: _CodegenContext) -> None: + imports = """ +import functools +import math +import torch +import jax +import jax.numpy as jnp +from jax.experimental import pallas as pl +from torch.utils._ordered_set import OrderedSet +from torch._inductor.runtime.runtime_utils import ( + pallas_compute_tiling, pallas_make_block_spec, pallas_permute, + pallas_gpu_align_output_specs, pallas_gpu_pad_inputs, + pallas_gpu_unpad_results, + pallas_ensure_nonzero_rank, + pallas_make_block_spec_non_tiled, + torch_dtype_to_jax_runtime, +) +""" + if ctx.is_tpu: + imports += "\nimport jax.export" + imports += "\nfrom jax.experimental.pallas import tpu as pltpu" + imports += "\nfrom torch_tpu._internal.pallas import tpu_torch_pallas" + elif not ctx.interpret_is_cpu: + imports += "\nfrom jax.experimental.pallas import mosaic_gpu as plgpu" + if self.indirect_access and not ctx.is_tpu: + imports += ( + "\nimport os as _os; _os.environ.setdefault('JAX_PLATFORMS', 'cpu')" + ) + imports += "\nfrom jax.experimental.pallas import tpu as pltpu" + ctx.code.splice(imports, strip=True) + + def _get_iter_var_axis(self, var_sym: sympy.Symbol) -> int | None: + """Map an iteration variable to its output tensor axis index. + + Non-reduction variables map to axes 0, 1, 2, ... in order. + Reduction variables map to axes after all pointwise axes. + Returns None if the mapping cannot be determined. + """ + pw_idx = 0 + r_idx = 0 + n_pw = sum(1 for e in self.range_tree_nodes.values() if not e.is_reduction) + for sym, entry in self.range_tree_nodes.items(): + if sym == var_sym: + return pw_idx if not entry.is_reduction else n_pw + r_idx + if entry.is_reduction: + r_idx += 1 + else: + pw_idx += 1 + return None + + def _get_reshape_target_shape_and_numel( + self, + ) -> tuple[tuple[int, ...] | None, int | None]: + # Find reshape target: N-D shape whose numel matches an iteration + # var. Try output first (repeat/upsample), then inputs (reductions). + iter_lengths = OrderedSet( + [ + int(e.length) + for e in self.range_tree_nodes.values() + if isinstance(e.length, (int, sympy.Integer)) + ] + ) + + def _get_nd_shape_if_matches(buf_name): + buf = V.graph.try_get_buffer(buf_name) + if buf is None or len(buf.get_size()) <= 1: + return None, None + shape = tuple( + int(s) if isinstance(s, (int, sympy.Integer)) else s + for s in buf.get_size() + ) + numel = math.prod(shape) + return (shape, numel) if numel in iter_lengths else (None, None) + + candidate_buf_names = self._output_buffer_names.copy() + candidate_buf_names.extend(self.args.input_buffers) + + reshape_target_shape, reshape_target_numel = None, None + for buf_name in candidate_buf_names: + result = _get_nd_shape_if_matches(buf_name) + if result[0]: + reshape_target_shape, reshape_target_numel = result + break + + return reshape_target_shape, reshape_target_numel + + def _make_broadcasted_iteration_var_expr( + self, broadcast_vars: list[_BroadcastedIterVar], broadcast_idx: int + ) -> str: + bv = broadcast_vars[broadcast_idx] + length = bv.entry.length + renamed_length = self.rename_indexing(length) + length_str = self.kexpr(renamed_length) + + num_broadcast_dims = len(broadcast_vars) + axis_idx = self._broadcast_axis_idx( + broadcast_vars, broadcast_idx, num_broadcast_dims + ) + shape_parts = ["1"] * num_broadcast_dims + shape_parts[axis_idx] = length_str + shape_str = ", ".join(shape_parts) + arange = f"jnp.arange({length_str})" + reshaped = f"{arange}.reshape({shape_str})" + return reshaped + + def _codegen_iteration_vars( + self, kernel_body: IndentedBuffer, ctx: _CodegenContext + ) -> None: + # Generate iteration variables as jnp.arange arrays + # Skip on GPU - jnp.arange is not supported by Pallas Mosaic backend + if not (self.range_tree_nodes and not self.is_gpu and self.used_iter_vars): + return + + kernel_body.writeline("# Define iteration variables as JAX arrays") + + reshape_target_shape, reshape_target_numel = ( + self._get_reshape_target_shape_and_numel() + ) + + var_items = list(self.range_tree_nodes.items()) + + broadcast_vars = [] + total_var_idx = None + for idx, (var_sym, entry) in enumerate(var_items): + length_val = self._safe_int(entry.length) + if length_val is not None and length_val == reshape_target_numel: + total_var_idx = idx + else: + broadcast_vars.append( + _BroadcastedIterVar(idx, var_sym, entry, length_val) + ) + + num_broadcast_dims = len(broadcast_vars) + + for idx, (var_sym, entry) in enumerate(var_items): + if var_sym not in self.used_iter_vars: + continue + var_name = str(var_sym) + length = entry.length + renamed_length = self.rename_indexing(length) + length_str = self.kexpr(renamed_length) + length_val = self._safe_int(length) + + if length_val is None: + if ( + reshape_target_shape + and num_broadcast_dims > 1 + and idx != total_var_idx + ): + broadcast_idx = next( + (i for i, v in enumerate(broadcast_vars) if v.idx == idx), + None, + ) + if broadcast_idx is not None: + expr = self._make_broadcasted_iteration_var_expr( + broadcast_vars, broadcast_idx + ) + kernel_body.writeline(f"{var_name} = {expr}") + continue + kernel_body.writeline(f"{var_name} = jnp.arange({length_str})") + continue + + if ( + reshape_target_shape + and len(reshape_target_shape) > 1 + and length_val == reshape_target_numel + ): + shape_str = ", ".join(str(s) for s in reshape_target_shape) + arange = f"jnp.arange({length_str})" + kernel_body.writeline(f"{var_name} = {arange}.reshape({shape_str})") + elif num_broadcast_dims > 1 and idx != total_var_idx: + broadcast_idx = next( + i for i, v in enumerate(broadcast_vars) if v.idx == idx + ) + expr = self._make_broadcasted_iteration_var_expr( + broadcast_vars, broadcast_idx + ) + kernel_body.writeline(f"{var_name} = {expr}") + else: + # Simple 1D arange — emit tile-relative form so tiling is safe. + # When grid=(1,), _pallas_tile[ax] == full length and + # pl.program_id(0) == 0, so this degenerates to jnp.arange(N). + # Only do this when the var actually appears in compute body + # (otherwise tiling is not blocked and the full arange is fine). + # Skip for scatter/index kernels where the iter var is used + # as a global index, not a data value. + compute_text = "\n".join(str(line) for line in self.compute._lines) + var_in_compute = var_name in compute_text + can_tile_relative = ( + var_in_compute + and not self.is_gpu + and not self.outputs_need_read + and not self.has_flatten_indexing + and not entry.is_reduction + ) + axis_idx = ( + self._get_iter_var_axis(var_sym) if can_tile_relative else None + ) + if axis_idx is not None: + kernel_body.writeline( + f"{var_name} = jnp.arange(_pallas_tile[{axis_idx}])" + f" + pl.program_id(_pallas_ax2g.get({axis_idx}, 0))" + f" * _pallas_tile[{axis_idx}]" + ) + self.tile_relative_iter_vars.add(var_sym) + else: + kernel_body.writeline(f"{var_name} = jnp.arange({length_str})") + + @staticmethod + def _broadcast_axis_idx( + broadcast_vars: list[_BroadcastedIterVar], + broadcast_idx: int, + num_broadcast_dims: int, + ) -> int: + # Axis placement depends on var types (reduction r* vs x*): + # - Mixed: pointwise first, reduction last for output reshape + # - Same-type: reverse order, first var innermost + has_reduction_vars = any( + str(bv.var_sym).startswith("r") for bv in broadcast_vars + ) + has_pointwise_vars = any( + not str(bv.var_sym).startswith("r") for bv in broadcast_vars + ) + is_mixed = has_reduction_vars and has_pointwise_vars + if is_mixed: + return broadcast_idx + return num_broadcast_dims - 1 - broadcast_idx + + def _codegen_jit_wrapper_tma(self, ctx: _CodegenContext, kernel_arg: str) -> None: + code = ctx.code + kernel_input_params = ctx.kernel_input_params + output_params = ctx.output_params + + # TMA automatically handles out-of-bounds accesses + code.writeline("# Use lax.fori_loop with TMA for automatic OOB masking") + code.writeline("from jax import lax") + code.writeline("_tile_size = 128 # Warpgroup size") + code.writeline("_orig_out_shapes = out_shapes") + + code.writeline("_max_numel = 0") + for param in kernel_input_params: + code.writeline(f"_max_numel = max(_max_numel, {param}.size)") + code.writeline("for shape in out_shapes:") + code.writeline(" _max_numel = max(_max_numel, math.prod(shape))") + + code.writeline("_num_tiles = (_max_numel + _tile_size - 1) // _tile_size") + + gmem_input_params = [f"{p}_gmem" for p in kernel_input_params] + gmem_output_params = [f"{p}_gmem" for p in output_params] + smem_input_params = [f"{p}_smem" for p in kernel_input_params] + smem_output_params = [f"{p}_smem" for p in output_params] + + code.writeline("") + code.writeline("# Wrapper kernel using lax.fori_loop with direct TMA") + + wrapper_kernel_params = gmem_input_params + gmem_output_params + all_smem_params = smem_input_params + smem_output_params + barrier_params = [f"_barrier_{i}" for i in range(len(kernel_input_params))] + scratch_params = ", ".join(all_smem_params + barrier_params) + + code.writeline( + f"def _tma_kernel({', '.join(wrapper_kernel_params)}, *, {scratch_params}):" + ) + with code.indent(): + code.writeline("") + code.writeline("def _tile_body(_tile_idx, _):") + with code.indent(): + code.writeline("_tile_start = _tile_idx * _tile_size") + code.writeline("") + + code.writeline("# TMA load inputs from GMEM to SMEM (OOB auto-masked)") + for i, (gmem_in, smem_in) in enumerate( + zip(gmem_input_params, smem_input_params) + ): + code.writeline( + f"plgpu.copy_gmem_to_smem({gmem_in}.at[pl.ds(_tile_start, _tile_size)], {smem_in}, _barrier_{i})" + ) + + code.writeline("") + code.writeline("# Wait for TMA loads to complete") + for i, _ in enumerate(gmem_input_params): + code.writeline(f"plgpu.barrier_wait(_barrier_{i})") + + code.writeline("") + code.writeline("# Compute on SMEM tiles") + kernel_call_args = smem_input_params + smem_output_params + kernel_fn = kernel_arg.rstrip(",").strip() + code.writeline(f"{kernel_fn}({', '.join(kernel_call_args)})") + + code.writeline("") + code.writeline( + "# TMA store outputs from SMEM to GMEM (OOB auto-masked)" + ) + code.writeline("plgpu.commit_smem()") + for gmem_out, smem_out in zip(gmem_output_params, smem_output_params): + code.writeline( + f"plgpu.copy_smem_to_gmem({smem_out}, {gmem_out}.at[pl.ds(_tile_start, _tile_size)])" + ) + code.writeline("plgpu.wait_smem_to_gmem(0)") + code.writeline("") + code.writeline("return None") + + code.writeline("") + code.writeline("# Iterate over all tiles") + code.writeline("lax.fori_loop(0, _num_tiles, _tile_body, None)") + + # Build scratch_shapes dict + code.writeline("") + code.writeline( + "# Build SMEM scratch shapes for inputs, outputs, and TMA barriers" + ) + code.writeline("_scratch_shapes = {}") + for i, smem_param in enumerate(smem_input_params): + orig_param = kernel_input_params[i] + code.writeline( + f"_scratch_shapes['{smem_param}'] = plgpu.SMEM((_tile_size,), {orig_param}.dtype)" + ) + for i, smem_param in enumerate(smem_output_params): + code.writeline( + f"_scratch_shapes['{smem_param}'] = plgpu.SMEM((_tile_size,), out_dtypes[{i}])" + ) + for barrier_param in barrier_params: + code.writeline( + f"_scratch_shapes['{barrier_param}'] = plgpu.Barrier(num_arrivals=1)" + ) + + code.writeline("") + code.writeline("# Create flattened output specs aligned to tile size") + code.writeline( + "_flat_out_specs, _ = pallas_gpu_align_output_specs(out_shapes, out_dtypes, _tile_size)" + ) + + code.writeline("") + code.writeline("# Call plgpu.kernel with TMA kernel") + code.writeline("_result = plgpu.kernel(") + with code.indent(): + code.writeline("_tma_kernel,") + code.writeline("out_shape=_flat_out_specs,") + code.writeline("scratch_shapes=_scratch_shapes,") + code.writeline(")(") + for param in kernel_input_params: + code.writeline(f" {param}.flatten(),") + code.writeline(")") + + code.writeline("") + code.writeline("# Reshape results to original shapes") + code.writeline("return pallas_gpu_unpad_results(_result, _orig_out_shapes)") + + def _codegen_jit_wrapper_legacy_gpu( + self, ctx: _CodegenContext, kernel_arg: str + ) -> None: + code = ctx.code + kernel_input_params = ctx.kernel_input_params + input_list = f"[{', '.join(kernel_input_params)}]" + + # Legacy GPU path with explicit padding (use_emit_pipeline=False) + # Mosaic GPU requires tensor sizes to be multiples of 128. + # Only apply padding when all tensors have the same size (no broadcasting). + code.writeline("# Check if all tensors have same size (no broadcasting)") + code.writeline("_all_sizes = []") + for param in kernel_input_params: + code.writeline(f"_all_sizes.append({param}.size)") + code.writeline("for shape in out_shapes:") + code.writeline(" _all_sizes.append(math.prod(shape))") + code.writeline("_unique_sizes = OrderedSet(_all_sizes)") + code.writeline( + "_can_pad = len(_unique_sizes) == 1 and all(s > 1 for s in _unique_sizes)" + ) + + code.writeline("") + code.writeline("if _can_pad:") + code.writeline(" # All tensors same size - safe to flatten and pad") + code.writeline(f" _padded_inputs = pallas_gpu_pad_inputs({input_list})") + code.writeline( + " _aligned_out_specs, _is_scalar = pallas_gpu_align_output_specs(out_shapes, out_dtypes)" + ) + code.writeline(" _result = plgpu.kernel(") + code.writeline(" " + kernel_arg) + code.writeline(" out_shape=_aligned_out_specs,") + code.writeline(" )(*_padded_inputs)") + code.writeline( + " return pallas_gpu_unpad_results(_result, out_shapes, _is_scalar)" + ) + + code.writeline("else:") + code.writeline( + " # Different sizes - check if it's a reduction (scalar output)" + ) + code.writeline(" _out_numel = math.prod(out_shapes[0])") + code.writeline(" ") + code.writeline(" if _out_numel <= 1:") + code.writeline( + " # Scalar output (reduction) - pad inputs but keep scalar output" + ) + code.writeline(f" _padded_inputs = pallas_gpu_pad_inputs({input_list})") + code.writeline(" _aligned_out_specs = tuple(") + code.writeline(" jax.ShapeDtypeStruct(shape, dtype)") + code.writeline(" for shape, dtype in zip(out_shapes, out_dtypes)") + code.writeline(" )") + code.writeline(" _result = plgpu.kernel(") + code.writeline(" " + kernel_arg) + code.writeline(" out_shape=_aligned_out_specs,") + code.writeline(" )(*_padded_inputs)") + code.writeline(" return _result") + code.writeline(" else:") + code.writeline( + " # Non-scalar output with broadcasting - broadcast inputs to output shape" + ) + code.writeline(" _target_shape = out_shapes[0]") + code.writeline(" _broadcasted = [") + code.writeline( + f" jnp.broadcast_to(_inp, _target_shape) for _inp in {input_list}" + ) + code.writeline(" ]") + code.writeline(" _padded_inputs = pallas_gpu_pad_inputs(_broadcasted)") + code.writeline( + " _aligned_out_specs, _is_scalar = pallas_gpu_align_output_specs(out_shapes, out_dtypes)" + ) + code.writeline(" _result = plgpu.kernel(") + code.writeline(" " + kernel_arg) + code.writeline(" out_shape=_aligned_out_specs,") + code.writeline(" )(*_padded_inputs)") + code.writeline( + " return pallas_gpu_unpad_results(_result, out_shapes, _is_scalar)" + ) + + def _param_to_buf_name(self, param: str) -> str | None: + """Map a kernel parameter name back to its graph buffer name.""" + for graph_name, inner_name in self.args.input_buffers.items(): + if inner_name == param: + return graph_name + return None + + def _codegen_tiled_specs(self, ctx: _CodegenContext) -> None: + """Generate tiled BlockSpec and grid variables for CPU/TPU. + + Tiles the last 1–2 dimensions of each tensor, respecting TPU + alignment constraints (last dim multiple of 128, second-to-last + multiple of 8). Lower-ndim inputs are right-aligned with the + reference output shape per numpy broadcast rules. + """ + code = ctx.code + skip_n = self.tile_skip_last_n + has_transpose = "True" if self.tile_has_transpose else "False" + is_tpu_literal = "True" if ctx.is_tpu else "False" + + # Collect per-input permutations for tiling alignment. + all_perms: list[tuple[int, ...] | None] = [] + for p in ctx.kernel_input_params: + buf_name = self._param_to_buf_name(p) + all_perms.append( + self.permuted_input_buffers.get(buf_name) if buf_name else None + ) + + mgp = self._cpu_max_grid_product + mgp_arg = f", max_grid_product={mgp}" if mgp else "" + perms_arg = ( + f", permutations={repr(all_perms)}" + if any(p is not None for p in all_perms) + else "" + ) + code.writeline( + f"_tile, _grid, _ax2g = pallas_compute_tiling(" + f"_pallas_out_shapes[0], " + f"transpose={has_transpose}, " + f"skip_last_n={skip_n}, exact_only=len(_pallas_out_shapes[0]) < 2, " + f"is_tpu={is_tpu_literal}" + f"{perms_arg}{mgp_arg})" + ) + code.writeline("_ng = len(_grid)") + code.writeline("_ref = _pallas_out_shapes[0]") + + code.writeline("out_specs_pallas = tuple(") + code.writeline( + " pallas_make_block_spec(s, _ref, _tile, _ax2g, _ng, is_output=True)" + ) + code.writeline(" for s in _pallas_out_shapes") + code.writeline(")") + + self._codegen_strided_reshapes(code, ctx.kernel_input_params) + + # Reshape collapsed inputs before building specs. + for param in ctx.kernel_input_params: + buf_name = self._param_to_buf_name(param) + cshape = self.collapsed_reshape_inputs.get(buf_name) if buf_name else None + if cshape is not None: + code.writeline(f"{param} = {param}.reshape({cshape})") + + # Build input BlockSpecs (with per-input permutation when needed). + input_list = ", ".join(ctx.kernel_input_params) + if any(p is not None for p in all_perms): + perm_list = ", ".join(repr(p) for p in all_perms) + code.writeline(f"_perm_flags = [{perm_list}]") + code.writeline("in_specs_pallas = tuple(") + code.writeline( + f" pallas_make_block_spec(i.shape, _ref, _tile, _ax2g, _ng, permutation=p)" + f" for i, p in zip([{input_list}], _perm_flags)" + ) + code.writeline(")") + else: + code.writeline("in_specs_pallas = tuple(") + code.writeline( + f" pallas_make_block_spec(i.shape, _ref, _tile, _ax2g, _ng) for i in [{input_list}]" + ) + code.writeline(")") + + def _codegen_jit_wrapper_cpu_tpu( + self, + ctx: _CodegenContext, + kernel_arg: str, + alias_pairs: list[tuple[int, int]], + alias_map_literal: str, + ) -> None: + code = ctx.code + grid_expr = "_grid" if self.tile_cpu_tpu else "(1,)" + code.writeline("_result = pl.pallas_call(") + code.writeline(" " + kernel_arg) + code.writeline(" out_shape=out_shapes_pallas,") + code.writeline(" out_specs=out_specs_pallas,") + code.writeline(" in_specs=in_specs_pallas,") + code.writeline(f" interpret={ctx.interpret_literal},") + code.writeline(f" grid={grid_expr},") + code.writeline( + f" input_output_aliases={{ {alias_map_literal} }}," + if alias_pairs + else " input_output_aliases={}," + ) + code.writeline(")(") + if ctx.kernel_input_params: + kernel_input_params_nonzero_rank = [ + f"pallas_ensure_nonzero_rank({p})" for p in ctx.kernel_input_params + ] + code.writeline(f" {', '.join(kernel_input_params_nonzero_rank)},") + code.writeline(")") + # Reshape results back to original shapes (restores 0-d from promoted (1,)) + code.writeline("if isinstance(_result, tuple):") + code.writeline( + " _result = tuple(r.reshape(s) for r, s in zip(_result, out_shapes))" + ) + code.writeline("else:") + code.writeline(" _result = _result.reshape(out_shapes[0])") + code.writeline("return _result") + + def _codegen_main_entry(self, ctx: _CodegenContext, jit_wrapper_name: str) -> None: + if ctx.is_tpu: + self._codegen_main_entry_tpu(ctx, jit_wrapper_name) + else: + self._codegen_main_entry_default(ctx, jit_wrapper_name) + + def _codegen_main_entry_tpu( + self, ctx: _CodegenContext, jit_wrapper_name: str + ) -> None: + code = ctx.code + code.writeline("") + main_name = f"{ctx.kernel_name}_main" + kernel_name_str = ctx.kernel_name + code.writeline( + f"def {main_name}({', '.join(ctx.full_kernel_params)}, stream=None):" + ) + with code.indent(): + # `jax_enable_x64` is per-process. The CPU path sets it to True, + # so running both CPU and TPU tests in one process can cause + # x64-related TPU crashes if we do not explicitly set it to + # False here. + code.writeline("jax.config.update('jax_enable_x64', False)") + code.writeline("jax.clear_caches()") + + # Convert int64 inputs to int32 (TPU doesn't support int64) + all_input_params = list(ctx.alias_params) + list(ctx.pointer_tail) + for param_name in all_input_params: + code.writeline( + f"{param_name} = {param_name}.to(torch.int32) " + f"if {param_name}.dtype == torch.int64 else {param_name}" + ) + + # Build JAX placeholders for all inputs + code.writeline("# Build JAX placeholders for export tracing") + all_jax_input_names = [] + for alias_name in ctx.alias_params: + code.writeline( + f"{alias_name}_placeholder = jax.ShapeDtypeStruct(" + f"{alias_name}.shape, torch_dtype_to_jax_runtime({alias_name}.dtype))" + ) + all_jax_input_names.append(f"{alias_name}_placeholder") + for ptr in ctx.pointer_tail: + code.writeline( + f"{ptr}_placeholder = jax.ShapeDtypeStruct(" + f"{ptr}.shape, torch_dtype_to_jax_runtime({ptr}.dtype))" + ) + all_jax_input_names.append(f"{ptr}_placeholder") + + # Prepare output metadata + code.writeline( + "out_shapes = (" + + ", ".join([f"tuple({name}.shape)" for name in ctx.output_params]) + + ",)" + ) + dtype_exprs: list[str] = [] + for name in ctx.output_params: + buf_name = ctx.output_buffer_lookup.get(name) + if buf_name is not None: + dtype = V.graph.get_dtype(buf_name) + if dtype is not None: + dtype_exprs.append(torch_dtype_to_jax(dtype)) + continue + dtype_exprs.append(f"torch_dtype_to_jax_runtime({name}.dtype)") + code.writeline("out_dtypes = (" + ", ".join(dtype_exprs) + ",)") + + # Export the jit_wrapper + wrapper_placeholder_args = ["out_shapes", "out_dtypes"] + wrapper_placeholder_args.extend(ctx.size_var_params) + wrapper_placeholder_args.extend(all_jax_input_names) + code.writeline( + f"exported = jax.export.export(" + f"{jit_wrapper_name}, platforms=['tpu'])" + f"({', '.join(wrapper_placeholder_args)})" + ) + + # Register and call via tpu_torch_pallas + # Include all output and input shapes in the key to avoid stale + # cache hits when the same kernel name is compiled with different + # input/output ranks (e.g. broadcasting vs non-broadcasting calls). + shape_key_parts = [] + for p in ctx.output_params: + shape_key_parts.append(f"'_'.join(str(s) for s in {p}.shape)") + output_key_expr = ( + " + 'x' + ".join(shape_key_parts) if shape_key_parts else "''" + ) + input_key_parts = [] + for p in ctx.kernel_input_params: + input_key_parts.append(f"'_'.join(str(s) for s in {p}.shape)") + input_key_expr = ( + " + 'x' + ".join(input_key_parts) if input_key_parts else "''" + ) + code.writeline( + f"kernel_key = '{kernel_name_str}_out_' + " + f"{output_key_expr}" + f" + '_in_' + {input_key_expr}" + ) + + code.writeline( + f"if not tpu_torch_pallas.lookup_custom_kernel('{kernel_name_str}', kernel_key):" + ) + with code.indent(): + code.writeline("try:") + with code.indent(): + code.writeline( + f"tpu_torch_pallas.register_custom_kernel(" + f"'{kernel_name_str}', kernel_key, " + f"serialized_mlir_module=exported.mlir_module_serialized)" + ) + code.writeline("except TypeError:") + with code.indent(): + code.writeline( + f"tpu_torch_pallas.register_custom_kernel(" + f"'{kernel_name_str}', kernel_key, " + f"exported.mlir_module_serialized)" + ) + + # Build input tensor list (all non-size-var inputs) + input_tensor_names = list(ctx.alias_params) + list(ctx.pointer_tail) + code.writeline(f"input_tensors = [{', '.join(input_tensor_names)}]") + + # Build output shapes list + code.writeline("output_shape_tensors = [") + with code.indent(): + for name in ctx.output_params: + buf_name = ctx.output_buffer_lookup.get(name) + if buf_name is not None: + dtype = V.graph.get_dtype(buf_name) + if dtype is not None: + code.writeline( + f"torch.empty({name}.shape, dtype={dtype!r}, device='tpu')," + ) + continue + code.writeline( + f"torch.empty({name}.shape, dtype={name}.dtype, device='tpu')," + ) + code.writeline("]") + + # Build donation info for zero-copy aliasing. Current torch_tpu + # exposes donate_argnums (the donated input indices); older + # versions took input_output_aliases ({input: output}). torch_tpu + # itself maps the latter to list(input_output_aliases.keys()), so + # the donated input indices are the alias-pair keys. + if ctx.alias_pairs: + alias_map_str = ", ".join(f"{i}: {o}" for (i, o) in ctx.alias_pairs) + code.writeline(f"_input_output_aliases = {{ {alias_map_str} }}") + donate_argnums_str = ", ".join(str(i) for (i, _o) in ctx.alias_pairs) + code.writeline(f"_donate_argnums = [{donate_argnums_str}]") + else: + code.writeline("_input_output_aliases = {}") + code.writeline("_donate_argnums = []") + + code.writeline("try:") + with code.indent(): + code.writeline( + f"_results = tpu_torch_pallas.call_custom_kernel(" + f"'{kernel_name_str}', kernel_key, " + f"inputs=input_tensors, " + f"output_shapes=output_shape_tensors, " + f"donate_argnums=_donate_argnums)" + ) + code.writeline("except TypeError:") + with code.indent(): + code.writeline( + f"_results = tpu_torch_pallas.call_custom_kernel(" + f"'{kernel_name_str}', kernel_key, " + f"inputs=input_tensors, " + f"output_shapes=output_shape_tensors, " + f"input_output_aliases=_input_output_aliases)" + ) + # call_custom_kernel returns freshly allocated result tensors; + # donate_argnums only lets the kernel reuse the donated buffers + # internally, it does not write back into the passed-in tensors. + # Copy each result into the aliased output buffer the caller reads + # (this mirrors torch_tpu's own JaxCallable alias handling). + code.writeline("if _results is not None:") + with code.indent(): + code.writeline( + "for _in_idx, _out_idx in _input_output_aliases.items():" + ) + with code.indent(): + code.writeline("input_tensors[_in_idx].copy_(_results[_out_idx])") + + def _codegen_main_entry_default( + self, ctx: _CodegenContext, jit_wrapper_name: str + ) -> None: + code = ctx.code + code.writeline("") + main_name = f"{ctx.kernel_name}_main" + code.writeline( + f"def {main_name}({', '.join(ctx.full_kernel_params)}, stream=None):" + ) + with code.indent(): + code.writeline("jax.config.update('jax_enable_x64', True)") + if ctx.interpret_is_cpu: + code.writeline( + "jax.config.update('jax_default_device', jax.devices('cpu')[0])" + ) + code.writeline("jax.clear_caches()") + if ctx.alias_params: + code.writeline("# Convert Torch -> JAX for donated outputs") + for alias_name in ctx.alias_params: + # On CPU/TPU, alias outputs may be non-contiguous (e.g. + # torch.cat slices) and JAX's from_dlpack rejects + # non-trivially strided tensors. Making them contiguous + # is safe because CPU/TPU already copies all results back + # via copy_output_indices. On CUDA, the donated-buffer + # mechanism requires the original buffer for in-place + # mutation, so we cannot make a contiguous copy. + self._emit_torch_to_jax( + code, + alias_name, + ctx.is_tpu, + contiguous=ctx.interpret_is_cpu, + ) + code.writeline("# Convert Torch -> JAX for in-place tensors") + for ptr in ctx.pointer_tail: + if ptr.startswith("in_out_ptr"): + self._emit_torch_to_jax(code, ptr, ctx.is_tpu, contiguous=False) + code.writeline("# Convert Torch -> JAX for inputs") + for ptr in ctx.pointer_tail: + if ptr.startswith("in_ptr"): + self._emit_torch_to_jax(code, ptr, ctx.is_tpu, contiguous=True) + + code.writeline("# Prepare output metadata from PyTorch tensor") + code.writeline( + "out_shapes = (" + + ", ".join([f"tuple({name}.shape)" for name in ctx.output_params]) + + ",)" + ) + dtype_exprs: list[str] = [] + for name in ctx.output_params: + buf_name = ctx.output_buffer_lookup.get(name) + if buf_name is not None: + dtype = V.graph.get_dtype(buf_name) + if dtype is not None: + dtype_exprs.append(torch_dtype_to_jax(dtype)) + continue + dtype_exprs.append(f"torch_dtype_to_jax_runtime({name}.dtype)") + code.writeline("out_dtypes = (" + ", ".join(dtype_exprs) + ",)") + arg_name_map: dict[str, str] = {} + for alias_name in ctx.alias_params: + arg_name_map[alias_name] = f"{alias_name}_jax" + for ptr in ctx.pointer_tail: + arg_name_map[ptr] = f"{ptr}_jax" + + wrapper_call_args = ["out_shapes", "out_dtypes"] + wrapper_call_args.extend(ctx.size_var_params) + wrapper_call_args.extend( + arg_name_map[name] for name in ctx.kernel_input_params + ) + code.writeline(f"res = {jit_wrapper_name}({', '.join(wrapper_call_args)})") + code.writeline("jax.block_until_ready(res)") + if ctx.copy_output_indices: + code.writeline( + "result_values = res if isinstance(res, tuple) else (res,)" + ) + for idx in ctx.copy_output_indices: + out_name = ctx.output_params[idx] + code.writeline( + f"{out_name}.copy_(torch.from_dlpack(result_values[{idx}]))" + ) + + @staticmethod + def _emit_torch_to_jax( + code: IndentedBuffer, var_name: str, is_tpu: bool, *, contiguous: bool + ) -> None: + suffix = ".detach().contiguous()" if contiguous else ".detach()" + code.writeline(f"{var_name}_jax = jax.dlpack.from_dlpack({var_name}{suffix})") + + def call_kernel(self, name: str, node: IRNode | None = None) -> None: # type: ignore[override] + """Generate the Python code that calls this Pallas kernel.""" + wrapper = V.graph.wrapper_code + arg_defs, call_args, _, _ = self.args.python_argdefs() + kernel_param_names = [a.name for a in arg_defs] + pure_out_params = [p for p in kernel_param_names if p.startswith("out_ptr")] + call_arg_strs = list(map(str, call_args)) + aliasable = getattr(self, "aliasable_out_ptrs", {}) + alias_call_args = [ + call_arg_strs[kernel_param_names.index(p)] + for p in pure_out_params + if aliasable.get(p, False) + ] + + # Generate kernel call: kernel_name.run(arg1, arg2, ...) + # Note: async_compile.pallas loads {name}_main function and wraps it in PallasKernelWrapper + # which exposes a run() method + kernel_call = f"{name}.run({', '.join(alias_call_args + call_arg_strs)})" + wrapper.writeline(kernel_call) + + +class PallasScheduling(SIMDScheduling): + kernel_type = PallasKernel # type: ignore[assignment] + + @classmethod + def get_backend_features(cls, device: torch.device) -> OrderedSet[BackendFeature]: + # Pallas/JAX can handle reductions to single elements efficiently + # without requiring split reductions + return OrderedSet([BackendFeature.REDUCE_TO_SINGLE_ELEMENT]) + + def can_fuse(self, node1, node2): # type: ignore[override] + if not super().can_fuse(node1, node2): + return False + # Pallas partial reductions use keepdims, so fusing two reductions + # that read the same buffer with different index patterns produces + # intermediates with incompatible shapes (e.g. (1,8) + (8,1) = (8,8) + # instead of (8,)). Prevent this by rejecting fusion when the read + # indices differ. + if node1.is_reduction() and node2.is_reduction(): + from torch._inductor.dependencies import MemoryDep + + reads1 = {} + for dep in node1.read_writes.reads: + if isinstance(dep, MemoryDep): + reads1[dep.name] = dep.index + for dep in node2.read_writes.reads: + if isinstance(dep, MemoryDep) and dep.name in reads1: + if reads1[dep.name] != dep.index: + return False + return True + + can_fuse_vertical = can_fuse # type: ignore[assignment] + can_fuse_horizontal = can_fuse # type: ignore[assignment] + + def define_kernel( + self, + src_code: str, + node_schedule: Sequence[BaseSchedulerNode], + kernel: PallasKernel, + ) -> str: # type: ignore[override] + wrapper = V.graph.wrapper_code + if src_code in wrapper.src_to_kernel: + return wrapper.src_to_kernel[src_code] + + fused_name = ( + get_fused_kernel_name(node_schedule, config.triton.descriptive_names) + if config.triton.descriptive_names + else "" + ) + kernel_hash = hashlib.sha256(src_code.encode("utf-8")).hexdigest()[:8] + if fused_name == "fused": + kernel_name = f"pallas_{kernel_hash}" + else: + kernel_name = f"pallas_{fused_name}_{kernel_hash}" + wrapper.src_to_kernel[src_code] = kernel_name + + # Replace placeholder if any + src_code = src_code.replace("", kernel_name) + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline(f"async_compile.pallas({kernel_name!r}, r'''") + compile_wrapper.splice(src_code, strip=True) + compile_wrapper.writeline("''')") + + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + metadata_comment = f"{origins}\n{detailed_origins}" + wrapper.define_kernel(kernel_name, compile_wrapper.getvalue(), metadata_comment) + + return kernel_name diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/python_wrapper_mtia.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/python_wrapper_mtia.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0309f2088ae1785a548db4f77103320d11a5b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/python_wrapper_mtia.py @@ -0,0 +1,33 @@ +from typing_extensions import override + +from torch._inductor import ir + +from .wrapper import PythonWrapperCodegen + + +class PythonWrapperMtia(PythonWrapperCodegen): + """ + A thin wrapper of PythonWrapperCodegen with MTIA specific logic + """ + + @override + def write_header(self) -> None: + super().write_header() + + # MITA specific imports + self.imports.splice("import mtia.host_runtime.torch_mtia.dynamic_library") + + @override + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: ir.GraphPartitionSignature | None = None, + ) -> PythonWrapperCodegen: + if is_subgraph: + # Delegate to the parent class to handle the case of subgraph + return PythonWrapperCodegen.create( + is_subgraph, subgraph_name, parent_wrapper, partition_signatures + ) + return PythonWrapperMtia() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af630c55f309014c29dd447c67b47a20548dd18d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_conv_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_conv_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..149659bd9fdd973d2856eb0d180181d54d79b516 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_conv_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3be2ae40f4a258c71313a5dcc87315276ea4dc0e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e30363738af1b96c60a3f689c5248e000295142 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_universal_gemm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_universal_gemm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4742b706be9446ef7a0f510f3ab672d1f8b9461a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_universal_gemm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_universal_gemm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_universal_gemm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0c42b2a61172fb0010f1f513ea5a49f0b63d1e8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_universal_gemm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/compile_command.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/compile_command.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..306e9a10270ad28fbe3f1486c560eac62abbb9b9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/compile_command.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_benchmark_request.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_benchmark_request.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..049d1c9de5bc3d45fcdb5af8712b581eb0269826 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_benchmark_request.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_cpp_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_cpp_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..115be847ad3a71ec3b7b93c3de5c8bcf8118ef02 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_cpp_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4dd57dd30db43fdc970ee0f915086594d7a549b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d25f3af2f6690832b5023f8d9bfbcff7abd18dea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template_buffer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6567d84f7f84ea9037af5b8a41617c8449cbb8c9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template_buffer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05832191030aeb705dc7dc3fde63d5e8f7238ea4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_conv_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_conv_template.py new file mode 100644 index 0000000000000000000000000000000000000000..5210b5fbd577f1d6623819ac50f55535bc7c9c44 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_conv_template.py @@ -0,0 +1,623 @@ +# mypy: allow-untyped-defs +import copy +import logging +import random +from typing import Any +from typing_extensions import override + +from torch._inductor.virtualized import V + +from .rocm_template import ArgInfo + + +try: + import ck4inductor # type: ignore[import] +except ImportError: + ck4inductor = None + +if ck4inductor is not None: + from ck4inductor.grouped_conv_fwd.gen_instances import ( # type: ignore[import] + gen_conv_ops_library, + ) + from ck4inductor.grouped_conv_fwd.op import ( # type: ignore[import] # noqa: TCH002 + CKGroupedConvFwdOp, + ) +else: + + def gen_conv_ops_library(): + return [] + + +from torch._inductor import config +from torch._inductor.codegen.rocm.ck_template import CKTemplate +from torch._inductor.codegen.rocm.rocm_kernel import ROCmTemplateKernel +from torch._inductor.utils import IndentedBuffer + + +log = logging.getLogger(__name__) + + +def torch_layout_to_ck_layouts(torch_layout): + # logically, torch tensors are always NCHW, + # and channels-last memory layout is visible in the strides + if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1): + # when input or output is NCHW + # NB: torch.conv2d result is always NCHW + return ["NGCHW", "GKCYX", "NGKHW"] + elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1): + # when input or output or weight is channels-last + return ["NHWGC", "GKYXC", "NHWGK"] + else: + return None + + +def torch_layout_to_ck_input_layout(torch_layout): + if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1): + return "NGCHW" + elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1): + return "NHWGC" + else: + return None + + +def torch_layout_to_ck_weight_layout(torch_layout): + if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1): + return "GKCYX" + elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1): + return "GKYXC" + else: + return None + + +def torch_layout_to_ck_output_layout(torch_layout): + if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1): + return "NGKHW" + elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1): + return "NHWGK" + else: + return None + + +class CKGroupedConvFwdTemplate(CKTemplate): + conv_template = r""" + {{headers}} + {{globals}} + {{instance_definition}} + extern "C" { + PT_EXPORT {{kernel_definition}} { + auto conv = {{instance_type}} {}; + auto invoker = conv.MakeInvoker(); + + using ck::index_t; + + constexpr index_t NumDTensor = {{n_d_tensors}}; + constexpr index_t NDimSpatial = {{n_dim_spatial}}; + const std::vector FilterSize = { FilterSize_0, FilterSize_1 }; + const std::vector InputSize = { InputSize_0, InputSize_1 }; + const std::vector ConvolutionStrides = { ConvolutionStrides_0, ConvolutionStrides_1 }; + const std::vector Dilations = { Dilations_0, Dilations_1 }; + const std::vector LeftPads = { LeftPads_0, LeftPads_1 }; + const std::vector RightPads = { RightPads_0, RightPads_1 }; + + + auto conv_param = ck::utils::conv::ConvParam { + NDimSpatial, + GroupCount, + NBatch, + NOutChannels, + NInChannels, + FilterSize, + InputSize, + ConvolutionStrides, + Dilations, + LeftPads, + RightPads, + }; + + using InLayout = ck::tensor_layout::convolution::{{input_layout}}; + using WeiLayout = ck::tensor_layout::convolution::{{weight_layout}}; + using OutLayout = ck::tensor_layout::convolution::{{output_layout}}; + + const auto in_g_n_c_wis_desc = + ck::utils::conv::make_input_host_tensor_descriptor_g_n_c_wis_packed(conv_param); + const auto wei_g_k_c_xs_desc = + ck::utils::conv::make_weight_host_tensor_descriptor_g_k_c_xs_packed(conv_param); + const auto out_g_n_k_wos_desc = + ck::utils::conv::make_output_host_tensor_descriptor_g_n_k_wos_packed(conv_param); + + const void* p_a = input; + const void* p_b = weight; + const std::array p_ds; + void* p_e = output; + std::array a_g_n_c_wis_lengths; + std::array a_g_n_c_wis_strides; + std::array b_g_k_c_xs_lengths; + std::array b_g_k_c_xs_strides; + std::array, NumDTensor> ds_g_n_k_wos_lengths; + std::array, NumDTensor> ds_g_n_k_wos_strides; + std::array e_g_n_k_wos_lengths; + std::array e_g_n_k_wos_strides; + std::array conv_filter_strides; + std::array conv_filter_dilations; + std::array input_left_pads; + std::array input_right_pads; + const auto a_element_op = PassThrough {}; + const auto b_element_op = PassThrough {}; + const auto cde_element_op = PassThrough {}; + + auto copy = [](auto& x, auto& y) { ck::ranges::copy(x, y.begin()); }; + + copy(in_g_n_c_wis_desc.GetLengths(), a_g_n_c_wis_lengths); + copy(in_g_n_c_wis_desc.GetStrides(), a_g_n_c_wis_strides); + copy(wei_g_k_c_xs_desc.GetLengths(), b_g_k_c_xs_lengths); + copy(wei_g_k_c_xs_desc.GetStrides(), b_g_k_c_xs_strides); + copy(out_g_n_k_wos_desc.GetLengths(), e_g_n_k_wos_lengths); + copy(out_g_n_k_wos_desc.GetStrides(), e_g_n_k_wos_strides); + copy(conv_param.conv_filter_strides_, conv_filter_strides); + copy(conv_param.conv_filter_dilations_, conv_filter_dilations); + copy(conv_param.input_left_pads_, input_left_pads); + copy(conv_param.input_right_pads_, input_right_pads); + + auto argument = conv.MakeArgument( + p_a, + p_b, + p_ds, + p_e, + a_g_n_c_wis_lengths, + a_g_n_c_wis_strides, + b_g_k_c_xs_lengths, + b_g_k_c_xs_strides, + ds_g_n_k_wos_lengths, + ds_g_n_k_wos_strides, + e_g_n_k_wos_lengths, + e_g_n_k_wos_strides, + conv_filter_strides, + conv_filter_dilations, + input_left_pads, + input_right_pads, + a_element_op, + b_element_op, + cde_element_op + ); + if (!conv.IsSupportedArgument(argument)) { + // we do our best to statically avoid this case in `filter_op` + std::cerr << "invalid argument for conv instance " << conv.GetTypeString() << std::endl; + argument.Print(); + return -23; + } + if (workspace_size) { + *workspace_size = conv.GetWorkSpaceSize(&argument); + return 0; + } + + if (p_a == nullptr) { + std::cerr << "p_a is nullptr" << std::endl; + return -1; + } + if (p_b == nullptr) { + std::cerr << "p_b is nullptr" << std::endl; + return -1; + } + if (p_e == nullptr) { + std::cerr << "p_e is nullptr" << std::endl; + return -1; + } + + // when debugging, do time kernel to serialize launches + auto stream_config = StreamConfig{stream, /* time kernel */ false, /* log level */ 0}; + + if (workspace != nullptr) { + conv.SetWorkSpacePointer(&argument, workspace, stream_config); + } + + // run the kernel + float elapsed_time = invoker.Run(argument, stream_config); + return 0; + } // kernel definition + } // extern C + + #ifdef GENERATE_CK_STANDALONE_RUNNER + int main(int argc, char** argv) { + (void) argc; + (void) argv; + return 0; + } + #endif // GENERATE_CK_STANDALONE_RUNNER +""" + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + // CK conv globals + + using NWC = ck::tensor_layout::convolution::NWC; + using NHWC = ck::tensor_layout::convolution::NHWC; + using NDHWC = ck::tensor_layout::convolution::NDHWC; + + using KXC = ck::tensor_layout::convolution::KXC; + using KYXC = ck::tensor_layout::convolution::KYXC; + using KZYXC = ck::tensor_layout::convolution::KZYXC; + + using NWK = ck::tensor_layout::convolution::NWK; + using NHWK = ck::tensor_layout::convolution::NHWK; + using NDHWK = ck::tensor_layout::convolution::NDHWK; + + using GNWC = ck::tensor_layout::convolution::GNWC; + using GNHWC = ck::tensor_layout::convolution::GNHWC; + using GNDHWC = ck::tensor_layout::convolution::GNDHWC; + + using GKXC = ck::tensor_layout::convolution::GKXC; + using GKYXC = ck::tensor_layout::convolution::GKYXC; + using GKZYXC = ck::tensor_layout::convolution::GKZYXC; + + using GKCX = ck::tensor_layout::convolution::GKCX; + using GKCYX = ck::tensor_layout::convolution::GKCYX; + using GKCZYX = ck::tensor_layout::convolution::GKCZYX; + + using GNWK = ck::tensor_layout::convolution::GNWK; + using GNHWK = ck::tensor_layout::convolution::GNHWK; + using GNDHWK = ck::tensor_layout::convolution::GNDHWK; + + using NGKW = ck::tensor_layout::convolution::NGKW; + using NGKHW = ck::tensor_layout::convolution::NGKHW; + using NGKDHW = ck::tensor_layout::convolution::NGKDHW; + + using NWGC = ck::tensor_layout::convolution::NWGC; + using NHWGC = ck::tensor_layout::convolution::NHWGC; + using NDHWGC = ck::tensor_layout::convolution::NDHWGC; + + using KXGC = ck::tensor_layout::convolution::KXGC; + using KYXGC = ck::tensor_layout::convolution::KYXGC; + using KZYXGC = ck::tensor_layout::convolution::KZYXGC; + + using NWGK = ck::tensor_layout::convolution::NWGK; + using NHWGK = ck::tensor_layout::convolution::NHWGK; + using NDHWGK = ck::tensor_layout::convolution::NDHWGK; + + using NGCW = ck::tensor_layout::convolution::NGCW; + using NGCHW = ck::tensor_layout::convolution::NGCHW; + using NGCDHW = ck::tensor_layout::convolution::NGCDHW; + + using G_K = ck::tensor_layout::convolution::G_K; + + using BlockGemmPipelineScheduler = ck::BlockGemmPipelineScheduler; + using GemmSpecialization = ck::tensor_operation::device::GemmSpecialization; + using BlockGemmPipelineVersion = ck::BlockGemmPipelineVersion; + + using ConvolutionForwardSpecialization = ck::tensor_operation::device::ConvolutionForwardSpecialization; + + using OutElementOp = PassThrough; + + namespace ck { + namespace utils { + namespace conv { + + ConvParam::ConvParam(ck::index_t n_dim, + ck::index_t group_count, + ck::index_t n_batch, + ck::index_t n_out_channels, + ck::index_t n_in_channels, + const std::vector& filters_len, + const std::vector& input_len, + const std::vector& strides, + const std::vector& dilations, + const std::vector& left_pads, + const std::vector& right_pads) + : num_dim_spatial_(static_cast(n_dim)), + G_(static_cast(group_count)), + N_(static_cast(n_batch)), + K_(static_cast(n_out_channels)), + C_(static_cast(n_in_channels)), + filter_spatial_lengths_(num_dim_spatial_), + input_spatial_lengths_(num_dim_spatial_), + output_spatial_lengths_(num_dim_spatial_), + conv_filter_strides_(num_dim_spatial_), + conv_filter_dilations_(num_dim_spatial_), + input_left_pads_(num_dim_spatial_), + input_right_pads_(num_dim_spatial_) + { + if(static_cast(filter_spatial_lengths_.size()) != num_dim_spatial_ || + static_cast(input_spatial_lengths_.size()) != num_dim_spatial_ || + static_cast(conv_filter_strides_.size()) != num_dim_spatial_ || + static_cast(conv_filter_dilations_.size()) != num_dim_spatial_ || + static_cast(input_left_pads_.size()) != num_dim_spatial_ || + static_cast(input_right_pads_.size()) != num_dim_spatial_) + { + throw( + std::runtime_error("ConvParam::ConvParam: " + "parameter size is different from number of declared dimensions!")); + } + + for(ck::index_t i = 0; i < num_dim_spatial_; ++i) + { + filter_spatial_lengths_[i] = static_cast(filters_len[i]); + input_spatial_lengths_[i] = static_cast(input_len[i]); + conv_filter_strides_[i] = static_cast(strides[i]); + conv_filter_dilations_[i] = static_cast(dilations[i]); + input_left_pads_[i] = static_cast(left_pads[i]); + input_right_pads_[i] = static_cast(right_pads[i]); + + // XEff = (X - 1) * conv_dilation_w + 1; + // Wo = (Wi + in_left_pad_w + in_right_pad_w - XEff) / conv_stride_w + 1; + const ck::long_index_t x_eff = + (filter_spatial_lengths_[i] - 1) * conv_filter_dilations_[i] + 1; + + output_spatial_lengths_[i] = + (input_spatial_lengths_[i] + input_left_pads_[i] + input_right_pads_[i] - x_eff) / + conv_filter_strides_[i] + + 1; + } + } + + } // namespace conv + } // namespace utils + } // namespace ck + + // NOTE: HostTensorDescriptor methods are declared in CK headers but defined + // in CK's utility library. For architectural reasons, generated code doesn't + // link with this library, so we provide local definitions here. + // CalculateStrides is omitted as it became a template method in CK 4266f867. + const std::vector& ck::HostTensorDescriptor::GetLengths() const { return mLens; } + const std::vector& ck::HostTensorDescriptor::GetStrides() const { return mStrides; } + std::size_t ck::HostTensorDescriptor::GetNumOfDimension() const { return mLens.size(); } + """ + ) + return res + + def header(self) -> IndentedBuffer: + res = super().header() + res.splice( + """ + // CK conv headers + + #include "ck/tensor_operation/gpu/device/impl/device_grouped_conv_fwd_multiple_abd_xdl_cshuffle_v3.hpp" + #include "ck/tensor_operation/gpu/device/convolution_forward_specialization.hpp" + #include "ck/tensor_operation/gpu/device/gemm_specialization.hpp" + + #include "ck/library/utility/convolution_parameter.hpp" + #include "ck/library/utility/convolution_host_tensor_descriptor_helper.hpp" + """ + ) + return res + + @staticmethod + def add_ck_conv_choices( + choices, + layout, + input_nodes, + *, + stride, + padding, + dilation, + groups, + n_spatial_dimensions, + ): + template = CKGroupedConvFwdTemplate( + input_nodes, + layout, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + n_spatial_dimensions=n_spatial_dimensions, + ) + ops = template.gen_ops() + for op in ops: + template.maybe_append_choice( + choices, + op=op, + ) + + def __init__( + self, + input_nodes, + layout, + *, + stride, + padding, + dilation, + groups, + n_spatial_dimensions, + ): + super().__init__( + "ck_conv_template", + input_nodes, + layout, + ) + self.stride = stride + self.padding = padding + self.dilation = dilation + self.groups = groups + self.n_spatial_dimensions = n_spatial_dimensions + + def filter_op(self, op: "CKGroupedConvFwdOp"): # type: ignore[name-defined] + metas = [ + T.get_layout() + for T in [*self.input_nodes, self.output_node] + if T is not None + ] + X_meta = metas[0] + W_meta = metas[1] + Y_meta = metas[-1] + # disable the instance if dtypes don't match + if op.a_element_dtype != self._TORCH_DTYPE_TO_CK[X_meta.dtype]: + return None + if op.b_element_dtype != self._TORCH_DTYPE_TO_CK[W_meta.dtype]: + return None + if op.e_element_dtype != self._TORCH_DTYPE_TO_CK[Y_meta.dtype]: + return None + # disable the instance if layouts don't match + if op.a_layout != torch_layout_to_ck_input_layout(X_meta): + return None + if op.b_layout != torch_layout_to_ck_weight_layout(W_meta): + return None + if op.e_layout != torch_layout_to_ck_output_layout(Y_meta): + return None + # disable the instance if number of spatial dimensions doesn't match + if op.n_dim_spatial != self.n_spatial_dimensions: + return None + # disable 1x1 and odd-channels conv specializations for now + if "Default" not in op.conv_forward_specialization: + return None + if self.is_blocked_by_tf32_setting(op): + return None + return op + + def gen_ops(self): + unfiltered_instances = gen_conv_ops_library() + + filtered_instances = list( + filter(lambda op: self.filter_op(op), unfiltered_instances) + ) + # NB: when using a fixed list order, most likely we will pick the subset of instances + # which are very similar to each other. Randomizing the choice seems to solve this. + random.seed(-11) + chosen_instances = ( + random.sample( + filtered_instances, + min(len(filtered_instances), config.rocm.ck_max_profiling_configs), + ) + if config.rocm.ck_max_profiling_configs + else filtered_instances + ) + log.debug( + "generated %d ck instances after filter: %s", + len(chosen_instances), + chosen_instances, + ) + return chosen_instances + + def emit_ck_instance(self, op: "CKGroupedConvFwdOp") -> tuple[str, str]: # type: ignore[name-defined] + # The Jinja template for generating a C++ type alias *definition* for a Universal GEMM instance + template_definition = r""" + // Gemm operator {{operation_name}} + using Operation_{{operation_name}} = + ck::tensor_operation::device::DeviceGroupedConvFwdMultipleABD_Xdl_CShuffle_V3< + {{template_params}}>; + +""" + # The Jinja template for generating a C++ type alias *usage* for a Universal GEMM instance + template_type = r""" + Operation_{{operation_name}} +""" + template_params = [] + for field_name, field_value in op.dict_items(): + if isinstance(field_value, tuple): + tuple_elements = ", ".join(map(str, iter(field_value))) + if "ds" in field_name: # element type and layout for bias + arg = f"/* {field_name} */ Tuple<{tuple_elements}>" + else: # tile shape + arg = f"/* {field_name} */ S<{tuple_elements}>" + # pyrefly: ignore [bad-argument-type] + template_params.append(arg) + else: + if field_value is not None: + # pyrefly: ignore [bad-argument-type] + template_params.append(f"/* {field_name} */ {field_value}") + return self._template_from_string(template_definition).render( + operation_name=op.name(), + template_params=(",\n" + 12 * " ").join(template_params), + ), self._template_from_string(template_type).render(operation_name=op.name()) + + def render( # type: ignore[override] + self, + kernel: ROCmTemplateKernel, + op: "CKGroupedConvFwdOp", # type: ignore[name-defined] + **kwargs, + ) -> str: + template_buffer_node = kwargs.get("template_buffer_node") + if template_buffer_node is not None: + self.output_node = template_buffer_node + X, W = self.input_nodes[0], self.input_nodes[1] + Y = self.output_node + Bias = self.input_nodes[2] if 3 == len(self.input_nodes) else None + + op = copy.deepcopy(op) + + instance_definition, instance_type = self.emit_ck_instance(op) + + size_arg_strs = [ + "GroupCount", + "NBatch", + "NOutChannels", + "NInChannels", + "FilterSize_0", + "FilterSize_1", + "InputSize_0", + "InputSize_1", + "ConvolutionStrides_0", + "ConvolutionStrides_1", + "Dilations_0", + "Dilations_1", + "LeftPads_0", + "LeftPads_1", + "RightPads_0", + "RightPads_1", + ] + + return self._template_from_string(self.conv_template).render( + headers=self.header().getvalue(), + globals=self.globals().getvalue(), + instance_definition=instance_definition, + instance_type=instance_type, + kernel_definition=kernel.def_kernel( + inputs=[X, W, Bias] if Bias is not None else [X, W], + outputs=[Y], + names_str="input, weight, bias, output" + if Bias is not None + else "input, weight, output", + size_args=[f"int32_t {arg}" for arg in size_arg_strs], + ), + n_d_tensors=1 if Bias is not None else 0, + n_dim_spatial=self.n_spatial_dimensions, + input_layout=op.a_layout, + weight_layout=op.b_layout, + output_layout=op.e_layout, + ) + + def size_args(self): + x, w = self.input_nodes[0], self.input_nodes[1] + y = self.output_node + + group_count = self.groups + n_batch = x.shape[0] # type: ignore[index] + n_out_channels = y.shape[1] # type: ignore[index] + n_in_channels = x.shape[1] # type: ignore[index] + + filter_size_0, filter_size_1 = w.shape[2:4] # type: ignore[index] + input_size_0, input_size_1 = x.shape[2:4] # type: ignore[index] + convolution_strides_0, convolution_strides_1 = self.stride + dilations_0, dilations_1 = self.dilation + left_pads_0, left_pads_1 = self.padding + right_pads_0, right_pads_1 = self.padding + + return ( + group_count, + n_batch, + n_out_channels, + n_in_channels, + filter_size_0, + filter_size_1, + input_size_0, + input_size_1, + convolution_strides_0, + convolution_strides_1, + dilations_0, + dilations_1, + left_pads_0, + left_pads_1, + right_pads_0, + right_pads_1, + ) + + @override + def get_runtime_arg_info(self) -> list[ArgInfo]: + return [] + + @override + def get_runtime_arg_values(self, **kwargs: Any) -> list[Any]: + """ + Helper method to retrieve runtime args from generate kwargs + """ + return [] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_template.py new file mode 100644 index 0000000000000000000000000000000000000000..863033385ae87716b5029501ed9e15bad96a1941 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_template.py @@ -0,0 +1,125 @@ +from typing import Any +from typing_extensions import override + +import torch +from torch._inductor.codegen.rocm.rocm_template import ROCmTemplate +from torch._inductor.ir import IRNode +from torch._inductor.utils import IndentedBuffer + +from .rocm_template import ArgInfo + + +class CKTemplate(ROCmTemplate): + """ + Base class for generating CK templates, has common, i.e. non-gemm-specific, code generation logic + """ + + _TORCH_DTYPE_TO_CK = { + torch.float32: "F32", + torch.float64: "F64", + torch.float16: "F16", + torch.bfloat16: "BF16", + torch.int32: "I32", + torch.int8: "I8", + torch.float8_e4m3fnuz: "F8", # gfx94 + torch.float8_e4m3fn: "F8", # gfx95 + torch.float8_e5m2fnuz: "BF8", # gfx94 + torch.float8_e5m2: "BF8", # gfx95 + } + + @staticmethod + def is_blocked_by_tf32_setting(op) -> bool: + """True if op internally computes in TF32 but the user has disabled TF32. + + CK exposes this via {a,b}_compute_dtype on op (None == strict compute + matching the element type). Some F32 instances ship with `TF32` here. + """ + if torch.backends.cuda.matmul.allow_tf32: + return False + return ( + getattr(op, "a_compute_dtype", None) == "TF32" + or getattr(op, "b_compute_dtype", None) == "TF32" + ) + + def header(self) -> IndentedBuffer: + res = super().header() + res.splice( + """ + // CK headers + + #ifdef DEBUG_LOG + #define DEBUG_LOG_TMP DEBUG_LOG + #undef DEBUG_LOG + #else + #define DEBUG_LOG_TMP 0 + #endif + #include "ck/ck.hpp" + #undef DEBUG_LOG + #define DEBUG_LOG DEBUG_LOG_TMP + + #include "ck/utility/data_type.hpp" + #include "ck/library/utility/check_err.hpp" + #include "ck/library/utility/device_memory.hpp" + #include "ck/library/utility/fill.hpp" + #include "ck/library/utility/host_tensor.hpp" + #include "ck/library/utility/host_tensor_generator.hpp" + #include "ck/library/utility/literals.hpp" + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + // CK globals + + template + using S = ck::Sequence; + + template + using Tuple = ck::Tuple; + + using PassThrough = ck::tensor_operation::element_wise::PassThrough; + using Bilinear = ck::tensor_operation::element_wise::Bilinear; + using Scale = ck::tensor_operation::element_wise::Scale; + using ScaleAdd = ck::tensor_operation::element_wise::ScaleAdd; + using MultiplyMultiply = ck::tensor_operation::element_wise::MultiplyMultiply; + + // see "composable_kernel/include/ck/utility/data_type.hpp" + using F8 = ck::f8_t; + using BF8 = ck::bf8_t; + using F16 = ck::half_t; + using F32 = float; + // using F64 = double; + using BF16 = ck::bhalf_t; + using TF32 = ck::tf32_t; + // using I32 = int32_t; + // using I8 = int8_t; + // using I4 = ck::int4_t; + + #if DEBUG_LOG + static constexpr auto kDEBUG_LOG = 1; + #else + static constexpr auto kDEBUG_LOG = 0; + #endif + """ + ) + return res + + def torch_type_to_ck(self, node: IRNode, ptr: str) -> str: + if node is None: + return ptr + else: + return f"({self._TORCH_DTYPE_TO_CK.get(node.get_dtype())}*)({ptr})" + + @override + def get_runtime_arg_info(self) -> list[ArgInfo]: + return [ArgInfo("kBatch", "int32_t")] + + @override + def get_runtime_arg_values(self, **kwargs: Any) -> list[Any]: + """ + Helper method to retrieve runtime args from generate kwargs + """ + return [kwargs[arg.name] for arg in self.get_runtime_arg_info()] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_template.py new file mode 100644 index 0000000000000000000000000000000000000000..70d31d635cc36dca295b1d82066376a1185c4da9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_template.py @@ -0,0 +1,58 @@ +import torch +from torch._inductor.codegen.rocm.rocm_template import ROCmTemplate +from torch._inductor.ir import IRNode +from torch._inductor.utils import IndentedBuffer + + +class CKTileTemplate(ROCmTemplate): + """ + Base class for generating CK templates, has common, i.e. non-gemm-specific, code generation logic + """ + + _TORCH_DTYPE_TO_CK = { + torch.float32: "F32", + torch.float64: "F64", + torch.float16: "F16", + torch.bfloat16: "BF16", + torch.int32: "I32", + torch.int8: "I8", + torch.float8_e4m3fnuz: "F8", # gfx94 + torch.float8_e4m3fn: "F8", # gfx95 + torch.float8_e5m2fnuz: "BF8", # gfx94 + torch.float8_e5m2: "BF8", # gfx95 + } + + ck_dtype_to_size = { + "FP16": 2, + "BF16": 2, + } + + def header(self) -> IndentedBuffer: + res = super().header() + res.splice( + """ + // CK headers + #include "ck_tile/core.hpp" + + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + using F8 = ck_tile::fp8_t; + using BF8 = ck_tile::bf8_t; + using F16 = ck_tile::half_t; + using F32 = float; + using BF16 = ck_tile::bfloat16_t; + """ + ) + return res + + def torch_type_to_ck(self, node: IRNode, ptr: str) -> str: + if node is None: + return ptr + else: + return f"({self._TORCH_DTYPE_TO_CK.get(node.get_dtype())}*)({ptr})" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..b08ef49ea7aaebe0462d586aac9d962b7ce6ef30 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py @@ -0,0 +1,878 @@ +# mypy: allow-untyped-defs, disable-error-code="attr-defined, valid-type" +import functools +import logging +import random +from collections import defaultdict +from dataclasses import asdict, dataclass +from typing import Any + +import torch +from torch._inductor import config +from torch._inductor.codegen.rocm.ck_tile_template import CKTileTemplate +from torch._inductor.codegen.rocm.rocm_kernel import ROCmTemplateKernel +from torch._inductor.codegen.rocm.rocm_template import ArgInfo +from torch._inductor.ir import Buffer, Layout +from torch.utils._ordered_set import OrderedSet + +from ...utils import IndentedBuffer + + +log = logging.getLogger(__name__) + + +def is_static_int(number): + import sympy + + return isinstance(number, (int, sympy.Integer)) + + +def torch_layout_to_ck_layout(torch_layout): + if torch_layout.stride[-1] == 1: + return "Row" + elif torch_layout.stride[-2] == 1: + return "Col" + else: + return None + + +@dataclass +class CKTileGemmOperation: + layout_a: str + layout_b: str + layout_c: str + + datatype_a: str + datatype_b: str + datatype_c: str + + tile_m: int + tile_n: int + tile_k: int + + warp_m: int + warp_n: int + warp_k: int + + warp_tile_m: int + warp_tile_n: int + warp_tile_k: int + + m_is_padded: str + n_is_padded: str + k_is_padded: str + + pipeline: str + scheduler: str + epilogue: str + + def layout_repr(self): + return f"{self.layout_a[0]}{self.layout_b[0]}{self.layout_c[0]}" + + def dtype_repr(self): + return f"{self.datatype_a}{self.datatype_b}{self.datatype_c}" + + def tile_sizes(self): + return "_".join( + [ + f"{self.tile_m}{self.tile_n}{self.tile_k}", + f"{self.warp_m}{self.warp_n}{self.warp_k}", + f"{self.warp_tile_m}{self.warp_tile_n}{self.warp_tile_k}", + ] + ) + + def name(self): + return "ck_tile_gemm_universal_" + "_".join( + [ + f"{self.layout_repr()}", + f"{self.dtype_repr()}", + f"{self.tile_sizes()}", + f"{self.pipeline}", + f"{self.scheduler}", + f"{self.epilogue}", + ] + ) + + def dict_items(self): + return asdict(self).items() + + +@functools.cache +def ops(): + """ + Generate the supported instance dataclasses + """ + import itertools + + compute_v3_instances = [ + CKTileGemmOperation( + layout_a=layout_a, + layout_b=layout_b, + layout_c=layout_c, + datatype_a=datatype_a, + datatype_b=datatype_b, + datatype_c=datatype_c, + tile_m=tile_m, + tile_n=tile_n, + tile_k=tile_k, + warp_m=warp_m, + warp_n=warp_n, + warp_k=warp_k, + warp_tile_m=warp_tile_m, + warp_tile_n=warp_tile_n, + warp_tile_k=warp_tile_k, + m_is_padded=m_is_padded, + n_is_padded=n_is_padded, + k_is_padded=k_is_padded, + pipeline="CompV3", + scheduler="Intrawave", + epilogue=epilogue, + ) + for (layout_a, layout_b, layout_c) in [ + ("Row", "Row", "Row"), + ("Row", "Col", "Row"), + ] + for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3] + for (tile_m, tile_n, tile_k) in [(256, 256, 32), (256, 256, 64)] + for (warp_m, warp_n, warp_k) in [(2, 2, 1)] + for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)] + for m_is_padded in ["true", "false"] + for n_is_padded in ["true", "false"] + for k_is_padded in ["true", "false"] + for epilogue in ["Default", "CShuffle"] + ] + + compute_v4_instances = [ + CKTileGemmOperation( + layout_a=layout_a, + layout_b=layout_b, + layout_c=layout_c, + datatype_a=datatype_a, + datatype_b=datatype_b, + datatype_c=datatype_c, + tile_m=tile_m, + tile_n=tile_n, + tile_k=tile_k, + warp_m=warp_m, + warp_n=warp_n, + warp_k=warp_k, + warp_tile_m=warp_tile_m, + warp_tile_n=warp_tile_n, + warp_tile_k=warp_tile_k, + m_is_padded=m_is_padded, + n_is_padded=n_is_padded, + k_is_padded=k_is_padded, + pipeline="CompV4", + scheduler="Intrawave", + epilogue=epilogue, + ) + for (layout_a, layout_b, layout_c) in [ + ("Row", "Row", "Row"), + ("Row", "Col", "Row"), + ] + for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3] + for (tile_m, tile_n, tile_k) in [ + (256, 256, 32) + ] # half the tile size since it has double buffering + for (warp_m, warp_n, warp_k) in [(2, 2, 1)] + for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)] + for m_is_padded in ["true", "false"] + for n_is_padded in ["true", "false"] + for k_is_padded in ["true", "false"] + for epilogue in ["Default", "CShuffle"] + ] + + mem_instances = [ + CKTileGemmOperation( + layout_a=layout_a, + layout_b=layout_b, + layout_c=layout_c, + datatype_a=datatype_a, + datatype_b=datatype_b, + datatype_c=datatype_c, + tile_m=tile_m, + tile_n=tile_n, + tile_k=tile_k, + warp_m=warp_m, + warp_n=warp_n, + warp_k=warp_k, + warp_tile_m=warp_tile_m, + warp_tile_n=warp_tile_n, + warp_tile_k=warp_tile_k, + m_is_padded=m_is_padded, + n_is_padded=n_is_padded, + k_is_padded=k_is_padded, + pipeline="Mem", + scheduler=scheduler, + epilogue=epilogue, + ) + for (layout_a, layout_b, layout_c) in [ + ("Row", "Row", "Row"), + ("Row", "Col", "Row"), + ] + for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3] + for (tile_m, tile_n, tile_k) in [(256, 256, 32), (256, 256, 64)] + for (warp_m, warp_n, warp_k) in [(2, 2, 1)] + for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)] + for m_is_padded in ["true", "false"] + for n_is_padded in ["true", "false"] + for k_is_padded in ["true", "false"] + for scheduler in ["Intrawave", "Interwave"] + for epilogue in ["Default", "CShuffle"] + ] + + return list( + itertools.chain(compute_v3_instances, compute_v4_instances, mem_instances) + ) + + +class CKTileGemmTemplate(CKTileTemplate): + """ + This class is used for rendering CK-Tile Universal GEMM kernels + """ + + gemm_template = r"""{{version_comment}} + {{headers}} + {{globals}} + {{instance_definition}} + extern "C" { + PT_EXPORT {{kernel_definition}} { + + using {{instance_namespace}}::BaseGemmPipeline; + using {{instance_namespace}}::TilePartitioner; + + constexpr auto TileK = {{instance_namespace}}::TileK; + constexpr auto kPrefetchStages = BaseGemmPipeline::PrefetchStages; + + const auto BiasTerms = std::array (); + const auto BiasStrides = std::array (); + + auto kargs = ck_tile::UniversalGemmKernelArgs<> { + {X}, + {W}, + BiasTerms, + Y, + M, + N, + K, + {LDA}, + {LDB}, + BiasStrides, + LDC, + kBatch + }; + + if (workspace_size) { + *workspace_size = 0; + return 0; + } + + const ck_tile::index_t k_grain = kBatch * TileK; + const ck_tile::index_t K_split = (K + k_grain - 1) / k_grain * TileK; + const ck_tile::index_t num_loop = TilePartitioner::GetLoopNum(K_split); + const bool has_hot_loop = BaseGemmPipeline::BlockHasHotloop(num_loop); + const ck_tile::TailNumber tail_num = BaseGemmPipeline::GetBlockLoopTailNum(num_loop); + + // run the kernel + const auto Run = [&](const auto has_hot_loop_, const auto tail_number_) { + constexpr bool has_hot_loop_v = has_hot_loop_.value; + constexpr auto tail_number_v = tail_number_.value; + + using Kernel = {{instance_namespace}}::Kernel; + + if (!Kernel::IsSupportedArgument(kargs)) { + // we do our best to statically avoid this case in `filter_op` + throw std::runtime_error("invalid argument"); + } + auto stream_config = ck_tile::stream_config{stream}; + auto grid_size = Kernel::GridSize(M, N, kBatch); + auto block_size = Kernel::BlockSize(); + constexpr auto lds_bytes = 0; + constexpr auto kBlockPerCU = 1; + auto gemm = ck_tile::make_kernel(Kernel{}, grid_size, block_size, lds_bytes, kargs); + ck_tile::launch_kernel(stream_config, gemm); + }; + + BaseGemmPipeline::TailHandler(Run, has_hot_loop, tail_num); + + return 0; + } // kernel definition + } // extern C + """ + + def __init__( + self, + input_nodes: list[Buffer], + layout: Layout, + ) -> None: + super().__init__( + "ck_tile_gemm_template", + input_nodes=input_nodes, + layout=layout, + ) + + def header(self) -> IndentedBuffer: + res = super().header() + res.splice( + """ + // CK GEMM header(s) + + #include "ck_tile/ops/gemm.hpp" + #include "ck_tile/ops/epilogue.hpp" + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + // CK GEMM globals + + using Row = ck_tile::tensor_layout::gemm::RowMajor; + using Col = ck_tile::tensor_layout::gemm::ColumnMajor; + """ + ) + return res + + def check_dtypes(self, op: "CKTileGemmOperation"): + X_dtype, W_dtype, out_dtype = [ + T.get_layout().dtype for T in [*self.input_nodes, self.output_node] + ] + if op.datatype_a != self._TORCH_DTYPE_TO_CK[X_dtype]: + return False + if op.datatype_b != self._TORCH_DTYPE_TO_CK[W_dtype]: + return False + if op.datatype_c != self._TORCH_DTYPE_TO_CK[out_dtype]: + return False + return True + + def check_layouts(self, op: "CKTileGemmOperation"): + X_layout, W_layout, out_layout = [ + torch_layout_to_ck_layout(T.get_layout()) + for T in [*self.input_nodes, self.output_node] + ] + if op.layout_a != X_layout: + return False + if op.layout_b != W_layout: + return False + if op.layout_c != out_layout: + return False + return True + + def get_gemm_problem_size(self): + X_size, W_size = [T.get_layout().size for T in [*self.input_nodes]] + + M, K = X_size + _, N = W_size + + return M, N, K + + def check_block_tiles(self, op: "CKTileGemmOperation"): + """ + The contiguous dimension of a tensor must be divisible by the block tile size + This helper function enforces it for the inputs and the output. + """ + M, N, K = self.get_gemm_problem_size() + + def check(dim_size, tile_size, is_padded): + if ( + is_static_int(dim_size) + and dim_size % tile_size != 0 + and is_padded == "false" + ): + return False + return True + + if op.layout_a == "Row": + # handle in kBatch check + return True + elif op.layout_a == "Col": + if not check(M, op.tile_m, op.m_is_padded): + return False + else: + raise AssertionError(f"Invalid layout {op.layout_a=}") + + if op.layout_b == "Row": + if not check(N, op.tile_n, op.n_is_padded): + return False + elif op.layout_b == "Col": + # handle in kBatch check + return True + else: + raise AssertionError(f"Invalid {op.layout_b=}") + + if op.layout_c == "Row": + if not check(N, op.tile_n, op.n_is_padded): + return False + elif op.layout_c == "Col": + if not check(M, op.tile_m, op.m_is_padded): + return False + else: + raise AssertionError(f"Invalid layout {op.layout_c=}") + + return True + + def check_alignments(self, op: "CKTileGemmOperation"): + """ + The contiguous dimension of a tensor must be divisible by the vector load size. + """ + M, N, K = self.get_gemm_problem_size() + + def max_alignment(contiguous_elements_per_tile, elements_per_thread, ck_dtype): + for vector_load_bytes in (16, 8, 4, 2, 1): + alignment = vector_load_bytes // self.ck_dtype_to_size[ck_dtype] + if ( + alignment > 0 + and contiguous_elements_per_tile % alignment == 0 + and elements_per_thread % alignment == 0 + ): + return alignment + + threads_per_block = ( + op.warp_m * op.warp_n * op.warp_k * self.gfx9_threads_per_warp + ) + a_elements_per_thread = op.tile_m * op.tile_k / threads_per_block + b_elements_per_thread = op.tile_n * op.tile_k / threads_per_block + + if op.layout_a == "Row": + # K is contiguous tensor dimension + a_max_vector_size = max_alignment( + op.tile_k, a_elements_per_thread, op.datatype_a + ) + if is_static_int(K) and K % a_max_vector_size != 0: + return False + elif op.layout_a == "Col": + # M is contiguous tensor dimension + a_max_vector_size = max_alignment( + op.tile_m, a_elements_per_thread, op.datatype_a + ) + if is_static_int(M) and M % a_max_vector_size != 0: + return False + else: + raise AssertionError(f"Invalid layout {op.layout_a=}") + + if op.layout_b == "Row": + # N is contiguous tensor dimension + b_max_vector_size = max_alignment( + op.tile_n, b_elements_per_thread, op.datatype_b + ) + if is_static_int(N) and N % b_max_vector_size != 0: + return False + elif op.layout_b == "Col": + # K is contiguous tensor dimension + b_max_vector_size = max_alignment( + op.tile_k, b_elements_per_thread, op.datatype_b + ) + if is_static_int(K) and K % b_max_vector_size != 0: + return False + else: + raise AssertionError(f"Invalid layout {op.layout_b=}") + + # the `default` epilogue writes C to memory by 1 tensor element + # (divisibility check not necessary) + # the `cshuffle` epilogue writes C to memory by 16 bytes + # (so the contiguous C dimension size must be divisible by the number of tensor elements in 16 bytes) + if op.epilogue == "CShuffle": + if ( + op.layout_c == "Row" + and is_static_int(N) + and N % (16 / self.ck_dtype_to_size[op.datatype_c]) != 0 + ): + return False + + return True + + def check_warp_tiles(self, op: "CKTileGemmOperation"): + if op.tile_m % (op.warp_m * op.warp_tile_m) != 0: + return False + if op.tile_n % (op.warp_n * op.warp_tile_n) != 0: + return False + if op.tile_k % (op.warp_k * op.warp_tile_k) != 0: + return False + return True + + def check_block_tile_size(self, op: "CKTileGemmOperation"): + # assuming LDS size is 64KB + if op.pipeline == "CompV4": + max_block_tile_size = 2**15 + else: + max_block_tile_size = 2**16 + + block_tile_size = ( + self.ck_dtype_to_size[op.datatype_a] * op.tile_m * op.tile_k + + self.ck_dtype_to_size[op.datatype_b] * op.tile_n * op.tile_k + ) + if block_tile_size > max_block_tile_size: + return False + return True + + def filter_op(self, op: "CKTileGemmOperation"): + """ + Determines whether a given op definition is suitable for the current + input / output of the operation that this template implements. + + Filter is based on inputs' dtype, layout and statically inferred size. + + Returns None if the op is not suitable, otherwise returns the op to be used. + """ + if not self.check_dtypes(op): + return None + if not self.check_layouts(op): + return None + if not self.check_block_tiles(op): + return None + if not self.check_alignments(op): + return None + + return op + + def emit_ck_instance(self, op: "CKTileGemmOperation"): + """ + This method is used to generate code which defines the type alias for the generated kernel class + """ + template_definition = r""" + // Gemm operator {{operation_name}} + + namespace {{operation_name}} { + // block tile + constexpr int32_t TileM = {{tile_m}}; + constexpr int32_t TileN = {{tile_n}}; + constexpr int32_t TileK = {{tile_k}}; + // warps per block + constexpr int32_t WarpM = {{warp_m}}; + constexpr int32_t WarpN = {{warp_n}}; + constexpr int32_t WarpK = {{warp_k}}; + // xdl tile + constexpr int32_t WarpTileM = {{warp_tile_m}}; + constexpr int32_t WarpTileN = {{warp_tile_n}}; + constexpr int32_t WarpTileK = {{warp_tile_k}}; + + constexpr bool kPadM = {{m_is_padded}}; + constexpr bool kPadN = {{n_is_padded}}; + constexpr bool kPadK = {{k_is_padded}}; + + using ALayout = {{layout_a}}; + using BLayout = {{layout_b}}; + using CLayout = {{layout_c}}; + + using ADataType = {{datatype_a}}; + using BDataType = {{datatype_b}}; + using CDataType = {{datatype_c}}; + using AccDataType = F32; + + constexpr bool permuteA = false; + constexpr bool permuteB = false; + constexpr bool DoubleSmemBuffer = {{has_double_smem_buffer}}; + constexpr bool TransposeC = false; + + constexpr int kBlockPerCu = 1; + constexpr ck_tile::index_t TilePartitionerGroupNum = 8; + constexpr ck_tile::index_t TilePartitionerM01 = 4; + + using GemmShape = + ck_tile::TileGemmShape, + ck_tile::sequence, + ck_tile::sequence, + permuteA, + permuteB>; + + using TilePartitioner = + ck_tile::GemmSpatiallyLocalTilePartitioner; + + using Traits = + ck_tile::TileGemmTraits; + + using GemmUniversalTraits = + ck_tile::TileGemmUniversalTraits; + + using GemmPipelineProblem = + ck_tile::GemmPipelineProblem; + + {{rendered_scheduler}} + + template + using UniversalGemmProblem = + ck_tile::UniversalGemmPipelineProblem; + + {{rendered_pipeline}} + + {{rendered_epilogue}} + + template + using Kernel = ck_tile::GemmKernel, GemmEpilogue>; + } + +""" + + def render_epilogue(epilogue_type): + if epilogue_type == "Default": + return r""" + using DsDataType = ck_tile::tuple<>; + using DsLayout = ck_tile::tuple<>; + using CDElementwise = ck_tile::element_wise::PassThrough; + + using EpilogueProblem = ck_tile::DefaultGemm2DEpilogueProblem; + using GemmEpilogue = ck_tile::DefaultGemm2DEpilogue; + """ + elif epilogue_type == "CShuffle": + return r""" + using DsDataType = ck_tile::tuple<>; // no bias terms for vanilla GEMM + using DsLayout = ck_tile::tuple<>; + constexpr auto ELayout = CLayout; + using CDEElementWise = ck_tile::element_wise::PassThrough; // no-op + using EpilogueProblem = ck_tile::CShuffleEpilogueProblem; + + using GemmEpilogue = ck_tile::CShuffleEpilogue; + """ + else: + raise AssertionError("Epilogue must be set") + + def render_pipeline(pipeline_type): + return rf""" + using BaseGemmPipeline = ck_tile::BaseGemmPipelineAgBgCr{pipeline_type}; + + template + using GemmPipeline = ck_tile::GemmPipelineAgBgCr{pipeline_type}>; + """ + + def render_scheduler(scheduler_type): + return rf""" + constexpr auto scheduler = ck_tile::GemmPipelineScheduler::{scheduler_type}; + """ + + rendered_definition = self._template_from_string(template_definition).render( + operation_name=op.name(), + **asdict(op), + rendered_scheduler=render_scheduler(op.scheduler), + rendered_pipeline=render_pipeline(op.pipeline), + rendered_epilogue=render_epilogue(op.epilogue), + has_double_smem_buffer=("true" if op.pipeline == "CompV4" else "false"), + ) + return rendered_definition + + def render( # type: ignore[override] + self, kernel: ROCmTemplateKernel, op: "CKTileGemmOperation", **kwargs + ) -> str: + """ + The primary entry point for the code rendering process used in this template. + """ + epilogue_nodes = kwargs.get("epilogue_nodes") + if not (epilogue_nodes is None or 0 == len(epilogue_nodes)): + raise AssertionError("expected no epilogue_nodes for CK tile gemm template") + template_buffer_node = kwargs.get("template_buffer_node") + if template_buffer_node is not None: + self.output_node = template_buffer_node + if 2 != len(self.input_nodes): + raise AssertionError(f"expected 2 input_nodes, got {len(self.input_nodes)}") + X, W = self.input_nodes + Y = self.output_node + + instance_definition = self.emit_ck_instance(op) + + version_comment = rf"""/** +* Generated code for CK inductor backend +* See {type(self).__module__}.{type(self).__qualname__} +* +* Template instance {op} +* +* {torch.__version__=} +* torch.version.git_version={getattr(torch.version, "git_version", "None")} +*/ +""" + + return self._template_from_string(self.gemm_template).render( + headers=self.header().getvalue(), + globals=self.globals().getvalue(), + instance_definition=instance_definition, + kernel_definition=kernel.def_kernel( + inputs=[X, W], # type: ignore[list-item] + outputs=[Y], + names_str="X, W, Y", + size_args=[ + f"int32_t {arg}" for arg in ["M", "N", "K", "LDA", "LDB", "LDC"] + ], + ), + instance_namespace=op.name(), + version_comment=version_comment, + ) + + def gen_ops(self): + """ + Creates a list of `CKTileGemmOperation` instances that match the GEMM operation this template represents. + The instances are guaranteed to have the correct layout, dtype and dimension padding for the GEMM input arguments. + + An instance may invalidate the GEMM configuration at runtime. + Such instances will be assigned +inf runtime by the autotune process. + """ + instances = ops() + if not instances: + raise AssertionError( + "No Composable Kernel Universal GEMM instances found. " + "Please check if the library is installed." + ) + filtered_instances = list(filter(self.filter_op, instances)) + # NB: when using a fixed list order, most likely we will pick the subset of instances + # which are very similar to each other. Stratified sampling ensures coverage of + # different pipeline/epilogue combinations while still randomizing within each stratum. + # Use a local Random instance so we don't mutate the global RNG state shared with + # other inductor code paths. + rng = random.Random(-11) + max_configs = config.rocm.ck_tile_max_profiling_configs + if max_configs: + strata: dict[tuple[str, str], list] = defaultdict(list) + for inst in filtered_instances: + strata[(inst.pipeline, inst.epilogue)].append(inst) + # Shuffle stratum keys so that when len(strata) > max_configs, the strata that + # get represented are not biased by filter/insertion order. + stratum_keys = list(strata.keys()) + rng.shuffle(stratum_keys) + # Distribute the budget across strata as evenly as possible. The first + # `remainder` strata get one extra slot. + per_stratum, remainder = divmod(max_configs, len(stratum_keys)) + chosen_instances: list = [] + for i, key in enumerate(stratum_keys): + quota = per_stratum + (1 if i < remainder else 0) + if quota == 0: + break + group = strata[key] + chosen_instances.extend(rng.sample(group, min(len(group), quota))) + # If some strata were smaller than their quota, fill the slack from the global + # remainder so we still hit max_configs when possible. + shortfall = max_configs - len(chosen_instances) + if shortfall > 0: + chosen_ids = OrderedSet(id(x) for x in chosen_instances) + remaining = [x for x in filtered_instances if id(x) not in chosen_ids] + if remaining: + chosen_instances.extend( + rng.sample(remaining, min(len(remaining), shortfall)) + ) + else: + chosen_instances = filtered_instances + log.debug( + "generated %d ck instances after sample: %s", + len(chosen_instances), + chosen_instances, + ) + return chosen_instances + + @staticmethod + def add_choices( + choices, + layout, + input_nodes, + ): + """ + Add Composable Kernel Universal GEMM instance choices to the auto-tuning list. + """ + template = CKTileGemmTemplate( + input_nodes, + layout, + ) + ops = template.gen_ops() + for op in ops: + for k_batch in template.k_batch_choices(op): + template.maybe_append_choice( + choices, + op=op, + kBatch=k_batch, + ) + + def k_batch_choices(self, op: "CKTileGemmOperation") -> tuple[int, ...]: + """ + Returns a list of k_batch choices for the template. + """ + default_choices = (1, 2, 4, 8, 16, 32) + + def check(dim_size, tile_size, is_padded): + if ( + is_static_int(dim_size) + and dim_size % tile_size != 0 + and is_padded == "false" + ): + return False + return True + + _, _, K, _, _, _ = self.size_args() + if op.layout_a == "Row" or op.layout_b == "Col": + choices = tuple( + filter( + lambda k_batch: check(K, op.tile_k * k_batch, op.k_is_padded), + default_choices, + ) + ) + else: + choices = default_choices + + if op.epilogue == "Default": + choices = (1,) + + return choices + + def size_args(self): + """ + Sizes and strides to be used for the kernel call + """ + X = self.input_nodes[0] + W = self.input_nodes[1] + Y = self.output_node + + M = X.get_size()[0] + K = X.get_size()[1] + N = W.get_size()[1] + LDA = X.get_stride()[0 if X.get_stride()[1] == 1 else 1] + LDB = W.get_stride()[0 if W.get_stride()[1] == 1 else 1] + LDC = Y.get_stride()[0 if Y.get_stride()[1] == 1 else 1] + + return M, N, K, LDA, LDB, LDC + + def get_runtime_arg_info(self) -> list[ArgInfo]: + return [ArgInfo("kBatch", "int32_t")] + + def get_runtime_arg_values(self, **kwargs: Any) -> list[Any]: + # maybe_append_choice kwarg for k_batch must match the name of the argument + arg_names = OrderedSet([arg.name for arg in self.get_runtime_arg_info()]) + if not arg_names.issubset(kwargs): + raise ValueError( + "Missing runtime arguments: " + ", ".join(arg_names - kwargs.keys()) + ) + return [kwargs[k] for k in arg_names] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_universal_gemm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_universal_gemm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..f383c8252290c93f387d0b16087f32af0af8d666 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_universal_gemm_template.py @@ -0,0 +1,1023 @@ +# mypy: allow-untyped-defs, disable-error-code="attr-defined, valid-type" +import copy +import logging +import math +import random +from collections import namedtuple + +import sympy + +import torch +from torch._inductor import config +from torch._inductor.codegen.cpp_utils import DTYPE_TO_CPP +from torch._inductor.codegen.rocm.ck_template import CKTemplate +from torch._inductor.codegen.rocm.compile_command import rocm_compile_command +from torch._inductor.codegen.rocm.rocm_kernel import ROCmTemplateKernel +from torch._inductor.ir import Buffer, Layout +from torch._inductor.runtime.runtime_utils import next_power_of_2 + +from ...utils import IndentedBuffer, is_dynamic, try_import_ck_lib + + +_, gen_ops_library, gen_ops_preselected, CKGemmOperation = try_import_ck_lib() + + +log = logging.getLogger(__name__) + +# lightweight collection of information about a single op +InductorROCmOp = namedtuple("InductorROCmOp", ["op", "kBatch"]) + +padding_lookup = { + "M": { + "GemmSpecialization::MPadding": True, + "GemmSpecialization::MNPadding": True, + "GemmSpecialization::MKPadding": True, + "GemmSpecialization::MNKPadding": True, + }, + "N": { + "GemmSpecialization::NPadding": True, + "GemmSpecialization::MNPadding": True, + "GemmSpecialization::NKPadding": True, + "GemmSpecialization::MNKPadding": True, + }, + "K": { + "GemmSpecialization::KPadding": True, + "GemmSpecialization::MKPadding": True, + "GemmSpecialization::NKPadding": True, + "GemmSpecialization::MNKPadding": True, + }, +} + + +def is_static_int(number): + return isinstance(number, (int, sympy.Integer)) + + +def torch_layout_to_ck_layout(torch_layout): + if torch_layout.stride[-1] == 1: + return "Row" + elif torch_layout.stride[-2] == 1: + return "Col" + else: + return None + + +class CKGemmTemplate(CKTemplate): + # the JINJA template for rendering CK Universal GEMMs + gemm_template = r"""{{version_comment}} + {{headers}} + {{globals}} + {{instance_definition}} + extern "C" { + PT_EXPORT {{kernel_definition}} { + auto gemm = {{instance_type}} {}; + auto invoker = gemm.MakeInvoker(); + {% if is_batched %} + auto argument = gemm.MakeArgument( + reinterpret_cast(X), + reinterpret_cast(W), + std::array{ {{ds_names}} }, + reinterpret_cast<{{c_element_dtype}}*>(Y), + M, + N, + K, + B, + LDA, + LDB, + std::array{ {{ds_strides}} }, + LDC, + M * K, // batch_stride_A + N * K, // batch_stride_B + std::array{ {{ds_batch_strides}} }, + M * N, // batch_stride_C + {{a_elementwise_op}}, + {{b_elementwise_op}}, + {{epilogue}} // c_elementwise_op + ); + {% else %} + auto argument = gemm.MakeArgument( + reinterpret_cast(X), + reinterpret_cast(W), + std::array{ {{ds_names}} }, + reinterpret_cast<{{c_element_dtype}}*>(Y), + M, + N, + K, + LDA, + LDB, + std::array{ {{ds_strides}} }, + LDC, + kBatch, // kBatch + {{a_elementwise_op}}, + {{b_elementwise_op}}, + {{epilogue}} // c_elementwise_op + ); + {% endif %} + if (!gemm.IsSupportedArgument(argument)) { + // we do our best to statically avoid this case in `filter_op` + std::cerr << "invalid argument for gemm instance " << gemm.GetTypeString() << std::endl; + argument.Print(); + return -23; + } + if (workspace_size) { + *workspace_size = gemm.GetWorkSpaceSize(&argument); + return 0; + } + // run the kernel + #ifdef GENERATE_CK_STANDALONE_RUNNER + const auto stream_config = StreamConfig{ + stream, + /* time kernel */ 1, + /* log level */ 1, + /* n_cold_iter */ 100, + /* n_hot_iter */ 100, + /* flush_l2_cache */ 1, + /* rotate_count */ 5}; + #else + const auto stream_config = StreamConfig{stream, /* time kernel */ false, /* log level */ 0}; + #endif + + const float elapsed_time = invoker.Run(argument, stream_config); + + #ifdef GENERATE_CK_STANDALONE_RUNNER + std::cout << "elapsed time: " << elapsed_time << " ms" << std::endl; + #else + (void)elapsed_time; + #endif + return 0; + } // kernel definition + } // extern C + """ + + standalone_runner_template = r""" + #ifdef GENERATE_CK_STANDALONE_RUNNER + // standalone runner for the generated CK GEMM kernel + + {{inline_utils}} + + extern "C" { + int run_main(int argc, char** argv) { + {% if is_batched %} + const int32_t B = {{B}}; + {% endif %} + const int32_t M = {{M}}; + const int32_t N = {{N}}; + const int32_t K = {{K}}; + const int32_t LDA = {{LDA}}; + const int32_t LDB = {{LDB}}; + const int32_t LDC = {{LDC}}; + const int32_t LDD = {{LDD}}; + const int32_t kBatch = {{kBatch}}; + + using AElementType = {{a_ck_dtype}}; + using BElementType = {{b_ck_dtype}}; + using CElementType = {{c_ck_dtype}}; + {% if has_bias %} + using BiasElementType = {{bias_ck_dtype}}; + {% endif %} + {% if has_scale %} + using ScaleAElementType = {{scale_a_ck_dtype}}; + using ScaleBElementType = {{scale_b_ck_dtype}}; + {% endif %} + + using AArgType = {{a_torch_dtype}}; + using BArgType = {{b_torch_dtype}}; + using CArgType = {{c_torch_dtype}}; + {% if has_bias %} + using BiasArgType = {{bias_torch_dtype}}; + {% endif %} + {% if has_scale %} + using ScaleAArgType = {{scale_a_torch_dtype}}; + using ScaleBArgType = {{scale_b_torch_dtype}}; + {% endif %} + + using ALayout = {{a_layout}}; + using BLayout = {{b_layout}}; + using CLayout = {{c_layout}}; + {% if has_bias %} + using BiasLayout = {{bias_layout}}; + {% endif %} + + {% if is_batched %} + using strides_t = std::array; + auto get_strides = [](int32_t batch_stride, int32_t leading_dimension, auto layout) constexpr -> strides_t { + if constexpr (std::is_same_v) { + return {batch_stride, leading_dimension, 1}; + } + return {batch_stride, 1, leading_dimension}; + }; + auto a_size = strides_t{B, M, K}; + auto a_stride = get_strides(M * K, LDA, ALayout{}); + auto b_size = strides_t{B, N, K}; + auto b_stride = get_strides(N * K, LDB, BLayout{}); + auto c_size = strides_t{B, M, N}; + auto c_stride = get_strides(M * N, LDC, CLayout{}); + {% else %} + using strides_t = std::array; + auto get_strides = [](int32_t leading_dimension, auto layout) constexpr -> strides_t { + if constexpr (std::is_same_v) { + return {leading_dimension, 1}; + } + return {1, leading_dimension}; + }; + auto a_size = strides_t{M, K}; + auto a_stride = get_strides(LDA, ALayout{}); + auto b_size = strides_t{N, K}; + auto b_stride = get_strides(LDB, BLayout{}); + auto c_size = strides_t{M, N}; + auto c_stride = get_strides(LDC, CLayout{}); + {% endif %} + + Tensor a_m_k ( HostTensorDescriptor ( a_size, a_stride ) ); + Tensor b_k_n ( HostTensorDescriptor ( b_size, b_stride ) ); + {% if has_bias %} + Tensor d_m_n ( HostTensorDescriptor ( c_size, get_strides(LDD, BiasLayout{}) ) ); + {% endif %} + {% if has_scale %} + // NB: these are hardcoded + Tensor s_a_m_n ( HostTensorDescriptor ( strides_t{M, N}, get_strides(0, Row{}) )); + Tensor s_b_m_n ( HostTensorDescriptor ( strides_t{M, N}, get_strides(0, Col{}) )); + {% endif %} + + Tensor c_m_n_host ( HostTensorDescriptor ( c_size, c_stride ) ); + Tensor c_m_n_device ( HostTensorDescriptor ( c_size, c_stride ) ); + + a_m_k.GenerateTensorValue(GeneratorTensor_2()); + b_k_n.GenerateTensorValue(GeneratorTensor_2()); + {% if has_bias %} + d_m_n.GenerateTensorValue(GeneratorTensor_2()); + {% endif %} + {% if has_scale %} + s_a_m_n.GenerateTensorValue(GeneratorTensor_2()); + s_b_m_n.GenerateTensorValue(GeneratorTensor_2()); + {% endif %} + DeviceMem a_m_k_device_buf(sizeof(AElementType) * a_m_k.mDesc.GetElementSpaceSize()); + DeviceMem b_k_n_device_buf(sizeof(BElementType) * b_k_n.mDesc.GetElementSpaceSize()); + {% if has_bias %} + DeviceMem d_m_n_device_buf(sizeof(BiasElementType) * d_m_n.mDesc.GetElementSpaceSize()); + {% endif %} + {% if has_scale %} + DeviceMem s_a_m_n_device_buf(sizeof(ScaleAElementType) * s_a_m_n.mDesc.GetElementSpaceSize()); + DeviceMem s_b_m_n_device_buf(sizeof(ScaleBElementType) * s_b_m_n.mDesc.GetElementSpaceSize()); + {% endif %} + DeviceMem c_m_n_device_buf(sizeof(CElementType) * c_m_n_device.mDesc.GetElementSpaceSize()); + + a_m_k_device_buf.ToDevice(a_m_k.mData.data()); + b_k_n_device_buf.ToDevice(b_k_n.mData.data()); + {% if has_bias %} + d_m_n_device_buf.ToDevice(d_m_n.mData.data()); + {% endif %} + {% if has_scale %} + s_a_m_n_device_buf.ToDevice(s_a_m_n.mData.data()); + s_b_m_n_device_buf.ToDevice(s_b_m_n.mData.data()); + {% endif %} + + {{kernel_name}}( + static_cast(a_m_k_device_buf.GetDeviceBuffer()), + static_cast(b_k_n_device_buf.GetDeviceBuffer()), + {% if has_scale %} + static_cast(s_a_m_n_device_buf.GetDeviceBuffer()), + static_cast(s_b_m_n_device_buf.GetDeviceBuffer()), + {% endif %} + {% if has_bias %} + static_cast(d_m_n_device_buf.GetDeviceBuffer()), + {% endif %} + static_cast(c_m_n_device_buf.GetDeviceBuffer()), + {% if is_batched %} + B, + {% endif %} + M, + N, + K, + LDA, + LDB, + LDC, + LDD, + nullptr, // workspace_size + nullptr, // workspace + nullptr); // stream + + hip_check_error(hipDeviceSynchronize()); + + return 0; + } // run_main + } // extern C + + int main(int argc, char** argv) { + return run_main(argc, argv); + } + // compile with: {{compile_cmd}} + #endif // GENERATE_CK_STANDALONE_RUNNER + """ + + def __init__( + self, + input_nodes: list[Buffer], + layout: Layout, + alpha: float, + beta: float, + input_reorder: list[int] | None = None, + ) -> None: + is_batched = len(layout.size) == 3 + name = "ck_batched_gemm_template" if is_batched else "ck_gemm_template" + super().__init__( + name=name, + input_nodes=input_nodes, + layout=layout, + input_reorder=input_reorder, + ) + self.alpha = alpha + self.beta = beta + self.is_batched = is_batched + + def header(self) -> IndentedBuffer: + res = super().header() + if self.is_batched: + res.splice( + """ + // CK GEMM header(s) + + #include "ck/tensor_operation/gpu/device/impl/device_batched_gemm_multiple_d_xdl_cshuffle_v3.hpp" + """ + ) + else: + res.splice( + """ + // CK GEMM header(s) + + #include "ck/tensor_operation/gpu/device/impl/device_gemm_multiple_d_xdl_cshuffle_v3.hpp" + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + // CK GEMM globals + + using Row = ck::tensor_layout::gemm::RowMajor; + using Col = ck::tensor_layout::gemm::ColumnMajor; + + using BlockGemmPipelineScheduler = ck::BlockGemmPipelineScheduler; + using GemmSpecialization = ck::tensor_operation::device::GemmSpecialization; + using BlockGemmPipelineVersion = ck::BlockGemmPipelineVersion; + + struct MultiplyMultiplyAdd { + template + __host__ __device__ constexpr void + operator()(E& e, const C& c, const D0& d0, const D1& d1, const D2& d2) const { + e = ck::type_convert( + ck::type_convert(c) + * ck::type_convert(d0) + * ck::type_convert(d1) + + ck::type_convert(d2) + ); + } + }; + """ + ) + return res + + def inline_utils(self): + res = IndentedBuffer() + res.splice( + """ + #include "host_tensor.cpp" + #include "device_memory.cpp" + """ + ) + return res + + def _has_padding(self, dimension, gemm_specialization): + # Get the relevant padding map for the given dimension + dimension_padding = padding_lookup.get(dimension, {}) + + # Check if the specialization is in the dimension's padding map + return dimension_padding.get(gemm_specialization, False) + + def filter_op(self, op_info: InductorROCmOp): + """ + Determines whether a given op definition is suitable for the current + input / output of the operation that this template implements. + + Filter is based on inputs' dtype, layout and statically inferred size. + + Returns None if the op is not suitable, otherwise returns the op to be used. + """ + op, kBatch = op_info.op, op_info.kBatch + metas = [T.get_layout() for T in [*self.input_nodes, self.output_node]] + X_meta = metas[0] + W_meta = metas[1] + Y_meta = metas[-1] + # disable the instance if dtypes don't match + if op.a_element_dtype != self._TORCH_DTYPE_TO_CK[X_meta.dtype]: + return None + if op.b_element_dtype != self._TORCH_DTYPE_TO_CK[W_meta.dtype]: + return None + if op.c_element_dtype != self._TORCH_DTYPE_TO_CK[Y_meta.dtype]: + return None + if self.is_blocked_by_tf32_setting(op): + return None + # disable the instance if layouts don't match + if op.a_layout != torch_layout_to_ck_layout(X_meta): + return None + if op.b_layout != torch_layout_to_ck_layout(W_meta): + return None + if op.c_layout != torch_layout_to_ck_layout(Y_meta): + return None + # try to avoid launching the instance with invalid problem size + # see GridwiseGemm_xdl_cshuffle_v3::CheckValidity + + M = X_meta.size[-2] + K = X_meta.size[-1] + N = W_meta.size[-1] + + if is_static_int(M): + if not self._has_padding("M", op.gemm_specialization): + if M % op.m_per_block != 0: + return None + if is_static_int(N): + if not self._has_padding("N", op.gemm_specialization): + if N % op.n_per_block != 0: + return None + if is_static_int(K): + if not self._has_padding("K", op.gemm_specialization): + if K % op.k_per_block != 0: + return None + K_t = kBatch * op.k_per_block + if K % K_t != 0: + return None + else: + # need another kBatch check here + lcm = abs(op.a_k1 * op.b_k1) // math.gcd(op.a_k1, op.b_k1) + K_t = kBatch * lcm + k_read_pad_splited = math.ceil(K / K_t) * lcm + if (k_read_pad_splited * (kBatch - 1)) >= K: + return None + + a_contig_size = ( + K if op.a_layout == "Row" else M if op.a_layout == "Col" else None + ) + if ( + is_static_int(a_contig_size) + and a_contig_size % op.a_block_transfer_src_scalar_per_vector != 0 + ): + return None + b_contig_size = ( + N if op.b_layout == "Row" else K if op.b_layout == "Col" else None + ) + if ( + is_static_int(b_contig_size) + and b_contig_size % op.b_block_transfer_src_scalar_per_vector != 0 + ): + return None + c_contig_size = ( + N if op.c_layout == "Row" else M if op.c_layout == "Col" else None + ) + c_shuffle_block_transfer_scalar_per_vector_n_per_block = ( + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block[0] + if isinstance( + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block, tuple + ) + else op.c_shuffle_block_transfer_scalar_per_vector_n_per_block + ) + if ( + is_static_int(c_contig_size) + and c_contig_size % c_shuffle_block_transfer_scalar_per_vector_n_per_block + != 0 + ): + return None + if not self._check_num_k_loops(op, kBatch): + return None + # TBD disable instances with invalid number of pipeline prefetch stages + # It will avoid compiling a small percentage of unrunnable instances which fail the gemm argument check + + return op + + def _check_num_k_loops(self, op, kBatch): + # Additional splitK scenario check + metas = [T.get_layout() for T in [*self.input_nodes]] + X_meta = metas[0] + W_meta = metas[1] + K = X_meta.size[-1] + if kBatch > 1: + if op.block_gemm_pipeline_version != "BlockGemmPipelineVersion::v1": + try: + prefetch_stages = self._prefetch_stages( + op, + torch.empty((), dtype=X_meta.dtype).element_size(), + torch.empty((), dtype=W_meta.dtype).element_size(), + torch.cuda.get_device_properties(X_meta.device).warp_size, + ) + except Exception as e: + log.debug( + "Failed to prefetch_stages for %s with exception %s", op.name, e + ) + # be conservative here and disable the op + return False + + K_t = op.k_per_block * kBatch + ak0 = (K + K_t - 1) // K_t * (op.k_per_block // op.a_k1) + num_k_loop = ak0 // (op.k_per_block // op.a_k1) + if num_k_loop <= prefetch_stages: + log.debug( + "Op %s is not compatible due to invalid number of pipeline prefetch stages. " + "Parameters: kBatch=%s, block_gemm_pipeline_version=%s, prefetch_stages=%s, num_k_loop=%s", + op.name(), + kBatch, + op.block_gemm_pipeline_version, + prefetch_stages, + num_k_loop, + ) + return False + + return True + + # small helper to figure out the prefetch stages on AMD + def _prefetch_stages(self, op, a_dtype_size, b_dtype_size, warp_size: int = 64): + version_str = op.block_gemm_pipeline_version.split("::")[-1] + try: + version = int(version_str[1:]) # Assuming the format is always 'vX' + except ValueError as e: + raise ValueError(f"Invalid version string: {version_str}") from e + if version not in [1, 2, 3, 4, 5]: + raise ValueError( + f"unknown prefetch stages for {op.block_gemm_pipeline_version}" + ) + # Define the mapping of versions to stages + version_to_stages = {1: 1, 3: 2, 4: 4, 5: 3} + # Get the stages for the given version + stages = version_to_stages.get(version) + if stages is None: + # This means we're at stage 2, and this requires computation + # See github.com/ROCm/composable_kernel/blob/d6a4605/include/ck/tensor_operation/gpu/block/blockwise_gemm_pipeline_xdlops_v2.hpp#L143 + wgp_per_cu = max(4 * warp_size // op.block_size, 1) + full_mem_band_prefetch_stages = math.ceil( + 32768 + / wgp_per_cu + / ( + (op.m_per_block * a_dtype_size + op.n_per_block * b_dtype_size) + * op.k_per_block + ) + ) + stages = min(max(full_mem_band_prefetch_stages, 2), 8) + + return stages + + def emit_ck_instance(self, op: "CKGemmOperation"): + # The Jinja template for generating a C++ type alias *definition* for a Universal GEMM instance + struct_name = ( + "DeviceBatchedGemmMultiD_Xdl_CShuffle_V3" + if self.is_batched + else "DeviceGemmMultiD_Xdl_CShuffle_V3" + ) + template_definition = r""" + // Gemm operator {{operation_name}} + using Operation_{{operation_name}} = + ck::tensor_operation::device::{{struct_name}}< + {{template_params}}>; + +""" + # The Jinja template for generating a C++ type alias *usage* for a Universal GEMM instance + template_type = r""" + Operation_{{operation_name}} +""" + template_params = [] + for field_name, field_value in op.dict_items(): + if isinstance(field_value, tuple): + tuple_elements = ", ".join(map(str, iter(field_value))) + if "ds" in field_name: # element type and layout for bias + arg = f"/* {field_name} */ Tuple<{tuple_elements}>" + else: # tile shape + arg = f"/* {field_name} */ S<{tuple_elements}>" + # pyrefly: ignore [bad-argument-type] + template_params.append(arg) + else: + if field_value is not None: + # pyrefly: ignore [bad-argument-type] + template_params.append(f"/* {field_name} */ {field_value}") + operation_name = op.name().replace("(", "").replace(",", "").replace(")", "") + return self._template_from_string(template_definition).render( + operation_name=operation_name, + template_params=(",\n" + 12 * " ").join(template_params), + struct_name=struct_name, + ), self._template_from_string(template_type).render( + operation_name=operation_name + ) + + def render( # type: ignore[override] + self, + kernel: ROCmTemplateKernel, + op: "CKGemmOperation", + **kwargs, + ) -> str: + """ + The primary entry point for the code rendering process used in this template. + """ + epilogue_nodes = kwargs.get("epilogue_nodes") + if not (epilogue_nodes is None or 0 == len(epilogue_nodes)): + raise AssertionError("expected no epilogue nodes for CK GEMM template") + template_buffer_node = kwargs.get("template_buffer_node") + if template_buffer_node is not None: + self.output_node = template_buffer_node + # input nodes: + # * X, W for matmul + # * X, W, Bias for addmm + # * X, W, inv_scale_x, inv_scale_w for scaled_mm + # * X, W, inv_scale_x, inv_scale_w, Bias for scaled_mm with bias + X, W = self.input_nodes[0], self.input_nodes[1] + Y = self.output_node + Bias = ( + self.input_nodes[2] + if 3 == len(self.input_nodes) + else self.input_nodes[4] + if 5 == len(self.input_nodes) + else None + ) + has_bias = Bias is not None + has_scale = len(self.input_nodes) in (4, 5) + op = copy.deepcopy(op) + + # This parameter is converted into tuple because of change + # from DeviceGemm_Xdl_CShuffleV3 to DeviceGemmMultiD_Xdl_CShuffle_V3. + # The first tuple element corresponds to matmul result... + if not isinstance( + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block, tuple + ): + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block = ( + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block, + ) + + if has_scale: + scale_x = self.input_nodes[2] + scale_w = self.input_nodes[3] + if 1 == scale_x.get_numel() and 1 == scale_w.get_numel(): + # tensorwise scale for both X, W + if has_bias: + op.c_elementwise_op = "ScaleAdd" + else: + op.c_elementwise_op = "Scale" + else: + # rowwise scale for both X, W + if has_bias: + op.c_elementwise_op = "MultiplyMultiplyAdd" + else: + op.c_elementwise_op = "MultiplyMultiply" + op.c_shuffle_dtype = "F32" + op.ds_layouts = ( + torch_layout_to_ck_layout(scale_x.get_layout()), + torch_layout_to_ck_layout(scale_w.get_layout()), + ) + op.ds_element_dtypes = ( + self._TORCH_DTYPE_TO_CK[scale_x.get_layout().dtype], + self._TORCH_DTYPE_TO_CK[scale_w.get_layout().dtype], + ) + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block += (1, 1) + else: + scale_x = None + scale_w = None + + bias_dtype = "" + if Bias is not None: + bias_layout = torch_layout_to_ck_layout(Bias.get_layout()) + bias_dtype = self._TORCH_DTYPE_TO_CK[Bias.get_layout().dtype] + op.ds_layouts += (bias_layout,) + op.ds_element_dtypes += (bias_dtype,) + if not has_scale: + op.c_elementwise_op = "Bilinear" + # c_shuffle_dtype is also used for adding bias to matmul result + # before converting down to the result dtype + op.c_shuffle_dtype = op.acc_dtype + # this parameter needs to be set accordingly to bias stride for correct accumulation + if bias_layout == "Row": + # bias has (N, ) shape + bias_shuffle_block_transfer_scalar_per_vector_n_per_block = ( + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block + ) + elif bias_layout == "Col": + # bias has (M, 1) shape + bias_shuffle_block_transfer_scalar_per_vector_n_per_block = (1,) + else: + raise AssertionError( + "Bias layout is neither row-major nor column-major" + ) + # ...and the second tuple element corresponds to the bias + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block += ( + bias_shuffle_block_transfer_scalar_per_vector_n_per_block + ) + + instance_definition, instance_type = self.emit_ck_instance(op) + + version_comment = rf"""/** +* Generated code for CK inductor backend +* See {type(self).__module__}.{type(self).__qualname__} +* +* Template instance {op} +* +* {torch.__version__=} +* torch.version.git_version={getattr(torch.version, "git_version", "None")} +*/ +""" + epilogue = None + + if op.c_elementwise_op == "Bilinear" and scale_w is None: + epilogue = f"Bilinear {{ {self.alpha}, {self.beta} }}" + + elif op.c_elementwise_op == "Scale": + epilogue = "Scale { (inv_scale_w && inv_scale_x) ? (*inv_scale_w * *inv_scale_x) : 1.0f }" + + elif op.c_elementwise_op == "ScaleAdd": + epilogue = "ScaleAdd { (inv_scale_w && inv_scale_x) ? (*inv_scale_w * *inv_scale_x) : 1.0f }" + + elif op.c_elementwise_op == "MultiplyMultiply": + epilogue = "MultiplyMultiply {}" + + elif op.c_elementwise_op == "MultiplyMultiplyAdd": + epilogue = "MultiplyMultiplyAdd {}" + + elif op.c_elementwise_op == "PassThrough": + epilogue = "PassThrough {}" + + if epilogue is None: + raise AssertionError("CK GEMM epilogue is not set") + + size_arg_strs = ["M", "N", "K", "LDA", "LDB", "LDC", "LDD"] + if self.is_batched: + size_arg_strs.insert(0, "B") + + res = self._template_from_string(self.gemm_template).render( + inline_utils=self.inline_utils(), + headers=self.header().getvalue(), + globals=self.globals().getvalue(), + instance_definition=instance_definition, + kernel_definition=kernel.def_kernel( + inputs=[X, W, scale_x, scale_w, Bias], # type: ignore[list-item] + outputs=[Y], + names_str="X, W, inv_scale_x, inv_scale_w, Bias, Y", + input_reorder=self.input_reorder, + size_args=[f"int32_t {arg}" for arg in size_arg_strs], + ), + instance_type=instance_type, + a_element_dtype=op.a_element_dtype, + b_element_dtype=op.b_element_dtype, + c_element_dtype=op.c_element_dtype, + bias_element_dtype=bias_dtype, + alpha=self.alpha, + beta=self.beta, + a_elementwise_op="PassThrough {}", + b_elementwise_op="PassThrough {}", + epilogue=epilogue, + has_bias=has_bias, + ds_size=1 + if op.c_elementwise_op in ("Bilinear", "ScaleAdd") + else 2 + if op.c_elementwise_op == "MultiplyMultiply" + else 3 + if op.c_elementwise_op == "MultiplyMultiplyAdd" + else 0, + ds_names=", ".join( + ["Bias"] + if op.c_elementwise_op in ("Bilinear", "ScaleAdd") + else ["inv_scale_x", "inv_scale_w"] + if op.c_elementwise_op == "MultiplyMultiply" + else ["inv_scale_x", "inv_scale_w", "Bias"] + if op.c_elementwise_op == "MultiplyMultiplyAdd" + else [] + ), + ds_strides=", ".join( + ["LDD"] + if op.c_elementwise_op in ("Bilinear", "ScaleAdd") + else ["0", "0"] + if op.c_elementwise_op == "MultiplyMultiply" + else ["0", "0", "LDD"] + if op.c_elementwise_op == "MultiplyMultiplyAdd" + else [] + ), + version_comment=version_comment, + is_batched=self.is_batched, + ds_batch_strides=", ".join([]), # FIXME when supporting baddbmm + ) + + if config.rocm.generate_test_runner: + is_static_problem = all(is_static_int(arg) for arg in self.size_args()) + # NOTE: size_arg_strs is defined above + size_arg_vals = ( + self.size_args() + if is_static_problem + else ( + f"std::stoi(argv[{k}])" for k, _ in enumerate(self.size_args(), 1) + ) + ) + size_args = dict(zip(size_arg_strs, size_arg_vals, strict=True)) + runtime_args = dict( + zip( + [a.name for a in self.get_runtime_arg_info()], + self.get_runtime_arg_values(), + ) + ) + runner_code = self._template_from_string( + self.standalone_runner_template + ).render( + inline_utils=self.inline_utils().getvalue(), + kernel_name=kernel.kernel_name, + has_bias=has_bias, + has_scale=has_scale, + is_batched=self.is_batched, + a_ck_dtype=op.a_element_dtype, + b_ck_dtype=op.b_element_dtype, + c_ck_dtype=op.c_element_dtype, + bias_ck_dtype=op.ds_element_dtypes[0] if has_bias else "", + scale_a_ck_dtype=op.ds_element_dtypes[0] + if has_scale and 2 == len(op.ds_element_dtypes) + else "BF16", + scale_b_ck_dtype=op.ds_element_dtypes[1] + if has_scale and 2 == len(op.ds_element_dtypes) + else "BF16", + a_torch_dtype=DTYPE_TO_CPP[X.get_layout().dtype], + b_torch_dtype=DTYPE_TO_CPP[W.get_layout().dtype], + c_torch_dtype=DTYPE_TO_CPP[Y.get_layout().dtype], + bias_torch_dtype=DTYPE_TO_CPP[Bias.get_layout().dtype] + if Bias is not None + else "", + scale_a_torch_dtype=DTYPE_TO_CPP[scale_x.get_layout().dtype] + if scale_x is not None + else "", + scale_b_torch_dtype=DTYPE_TO_CPP[scale_w.get_layout().dtype] + if scale_w is not None + else "", + a_layout=torch_layout_to_ck_layout(X.get_layout()), + b_layout=torch_layout_to_ck_layout(W.get_layout()), + c_layout=torch_layout_to_ck_layout(Y.get_layout()), + bias_layout=torch_layout_to_ck_layout(Bias.get_layout()) + if Bias is not None + else "", + compile_cmd=rocm_compile_command( + [""], "", "exe" + ), + **size_args, + **runtime_args, + ) + res += runner_code + + return res + + def _is_rcr_f16(self): + X_meta, W_meta, Y_meta = ( + T.get_layout() for T in [*self.input_nodes, self.output_node] + ) + X_dtype, W_dtype, Y_dtype = ( + self._TORCH_DTYPE_TO_CK[m.dtype] for m in (X_meta, W_meta, Y_meta) + ) + X_layout, W_layout, Y_layout = ( + torch_layout_to_ck_layout(m) for m in (X_meta, W_meta, Y_meta) + ) + + return ( + X_dtype == "F16" + and W_dtype == "F16" + and Y_dtype == "F16" + and X_layout == "Row" + and W_layout == "Col" + and Y_layout == "Row" + ) + + # helper to calculate a potentially optimal kBatch(es) for a problem + def _get_kBatch(self, op): + # we only set a higher kBatch if K > 16 * the larger of M and N + # this is a hand-tuned heuristic to start + metas = [T.get_layout() for T in [*self.input_nodes]] + X_meta = metas[0] + W_meta = metas[1] + M = X_meta.size[-2] + K = X_meta.size[-1] + N = W_meta.size[-1] + if is_dynamic(*self.input_nodes): + return [1] + if K // max(M, N) < config.rocm.split_k_threshold: + return [1] + # if the user is telling us which kBatches to sweep, just use those + if config.rocm.kBatch_sweep is not None: + return config.rocm.kBatch_sweep + # Calculate the number of blocks needed for each dimension + total_k_blocks = math.ceil(K / op.k_per_block) + # we want to calculate how many blocks we need to fit per CU + cus = torch.cuda.get_device_properties(X_meta.device).multi_processor_count + # again, manual heuristics as much larger kBatch are significantly worse in + # initial testing + kBatch = min(max(next_power_of_2(total_k_blocks // cus), 1), 128) + return [kBatch] + + def gen_ops(self) -> list[InductorROCmOp]: + """ + Creates a list of `CKGemmOperation` instances that match the GEMM operation this template represents. + The instances are guaranteed to have the correct layout, dtype and dimension padding for the GEMM input arguments. + + An instance may invalidate the GEMM configuration at runtime. + Such instances will be assigned +inf runtime by the autotune process. + """ + try: + from ck4inductor.batched_universal_gemm.gen_instances import ( # type: ignore[import] + gen_ops_library as gen_batched_gemm_ops_library, + ) + from ck4inductor.universal_gemm.gen_instances import ( # type: ignore[import] + gen_ops_library as gen_gemm_ops_library, + gen_ops_preselected as gen_gemm_ops_preselected, + ) + except ImportError: + return [] + + generator = None + if self.is_batched: + generator = gen_batched_gemm_ops_library + else: + generator = gen_gemm_ops_library + if config.rocm.use_preselected_instances and self._is_rcr_f16(): + generator = gen_gemm_ops_preselected + + if generator is None: + raise AssertionError("expected a non-None CK GEMM ops generator") + + rops = generator() + ops = [] + for o in rops: + kBatches = self._get_kBatch(o) + for kBatch in kBatches: + # pyrefly: ignore [bad-argument-type] + ops.append(InductorROCmOp(op=o, kBatch=kBatch)) + + filtered_instances = list(filter(lambda op: self.filter_op(op), ops)) + + # NB: when using a fixed list order, most likely we will pick the subset of instances + # which are very similar to each other. Randomizing the choice seems to solve this. + random.seed(-11) + chosen_instances = ( + random.sample( + filtered_instances, + min(len(filtered_instances), config.rocm.ck_max_profiling_configs), + ) + if config.rocm.ck_max_profiling_configs + else filtered_instances + ) + log.debug( + "generated %d ck instances after filter: %s", + len(chosen_instances), + chosen_instances, + ) + return chosen_instances + + @staticmethod + def add_ck_gemm_choices( + choices, + layout, + input_nodes, + alpha=1, + beta=0, + input_reorder=None, + ): + """ + Add Composable Kernel Universal GEMM instance choices to the auto-tuning list. + """ + template = CKGemmTemplate( + input_nodes, + layout, + alpha=alpha, + beta=beta, + input_reorder=input_reorder, + ) + ops = template.gen_ops() + for op in ops: + template.maybe_append_choice( + choices, + op=op.op, + kBatch=op.kBatch, + ) + + def size_args(self): + X = self.input_nodes[0] + W = self.input_nodes[1] + Bias = ( + self.input_nodes[2] + if len(self.input_nodes) == 3 + else self.input_nodes[4] + if len(self.input_nodes) == 5 + else None + ) + Y = self.output_node + + M = X.get_size()[-2] + K = X.get_size()[-1] + N = W.get_size()[-1] + LDA = X.get_stride()[-2 if X.get_stride()[-1] == 1 else -1] + LDB = W.get_stride()[-2 if W.get_stride()[-1] == 1 else -1] + LDC = Y.get_stride()[-2 if Y.get_stride()[-1] == 1 else -1] + LDD = ( + 0 + if (Bias is None or len(Bias.get_size()) == 1) + else Bias.get_stride()[-2 if Bias.get_stride()[-1] == 1 else -1] + ) + if self.is_batched: + B = X.get_size()[0] + return B, M, N, K, LDA, LDB, LDC, LDD + else: + return M, N, K, LDA, LDB, LDC, LDD diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/compile_command.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/compile_command.py new file mode 100644 index 0000000000000000000000000000000000000000..2aa4494e0aa32a6cfbb75d4a418a2f22b076fa62 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/compile_command.py @@ -0,0 +1,152 @@ +# mypy: allow-untyped-defs +import logging +import os + +from torch._inductor import config +from torch._inductor.utils import is_linux, try_import_ck_lib + + +log = logging.getLogger(__name__) + + +def _rocm_include_paths(dst_file_ext: str) -> list[str]: + from torch.utils import cpp_extension + + rocm_include = ( + os.path.join(config.rocm.rocm_home, "include") + if config.rocm.rocm_home + else cpp_extension._join_rocm_home("include") + ) + + if config.is_fbcode(): + from libfb.py import parutil + + ck_path = parutil.get_dir_path("composable-kernel-headers") + else: + if not config.rocm.ck_dir: + ck_dir, _, _, _ = try_import_ck_lib() + if not ck_dir: + log.warning("Unspecified Composable Kernel directory") + config.rocm.ck_dir = ck_dir + ck_path = config.rocm.ck_dir or cpp_extension._join_rocm_home( + "composable_kernel" + ) + + log.debug("Using ck path %s", ck_path) + + ck_include = os.path.join(ck_path, "include") + ck_library_include = os.path.join(ck_path, "library", "include") + + # CK has to take priority over ROCm include paths + # Since CK is potentially more up-to-date + paths = [ + os.path.realpath(p) for p in (ck_include, ck_library_include, rocm_include) + ] + if dst_file_ext == "exe": + ck_utility_include = os.path.join(ck_path, "library", "src", "utility") + paths.append(os.path.realpath(ck_utility_include)) + return paths + + +def _rocm_lib_options(dst_file_ext: str) -> list[str]: + from torch.utils import cpp_extension + + rocm_lib_dir = ( + os.path.join(config.rocm.rocm_home, "lib") + if config.rocm.rocm_home + else cpp_extension._join_rocm_home("lib") + ) + hip_lib_dir = ( + os.path.join(config.rocm.rocm_home, "hip", "lib") + if config.rocm.rocm_home + else cpp_extension._join_rocm_home("hip", "lib") + ) + + opts = [ + "-include __clang_hip_runtime_wrapper.h", + f"-L{os.path.realpath(rocm_lib_dir)}", + f"-L{os.path.realpath(hip_lib_dir)}", + "-lamdhip64", + ] + if dst_file_ext == "exe": + opts += ["-lpthread", "-lstdc++"] + return opts + + +def _rocm_compiler_options() -> list[str]: + arch_list = config.rocm.arch or ["native"] + gpu_arch_flags = [f"--offload-arch={arch}" for arch in arch_list] + opts = [ + config.rocm.compile_opt_level, + "-x", + "hip", + "-std=c++20", + *gpu_arch_flags, + "-fno-gpu-rdc", + "-fPIC", + "-fvisibility=hidden", + "-mllvm", + "-amdgpu-early-inline-all=true", + "-mllvm", + "-amdgpu-function-calls=false", + "-mllvm", + "-enable-post-misched=0", + ] + if config.rocm.is_debug: + opts += ["-DDEBUG_LOG=1", "-g"] + if config.rocm.save_temps: + opts += ["--save-temps=obj"] + if config.rocm.print_kernel_resource_usage: + opts += ["-Rpass-analysis=kernel-resource-usage"] + if config.rocm.flush_denormals: + opts += ["-fgpu-flush-denormals-to-zero"] + if config.rocm.use_fast_math: + opts += ["-ffast-math"] + return opts + + +def rocm_compiler() -> str | None: + if is_linux(): + if config.rocm.rocm_home: + return os.path.realpath( + os.path.join(config.rocm.rocm_home, "llvm", "bin", "clang") + ) + try: + from torch.utils import cpp_extension + + return os.path.realpath( + cpp_extension._join_rocm_home("llvm", "bin", "clang") + ) + except OSError: + # neither config.rocm.rocm_home nor env variable ROCM_HOME are set + return "clang" + return None + + +def rocm_compile_command( + src_files: list[str], + dst_file: str, + dst_file_ext: str, + extra_args: list[str] | None = None, +) -> str: + include_paths = _rocm_include_paths(dst_file_ext) + lib_options = _rocm_lib_options(dst_file_ext) + compiler_options = _rocm_compiler_options() + compiler = rocm_compiler() + options = ( + compiler_options + + (extra_args or []) + + [f"-I{path}" for path in include_paths] + + lib_options + ) + src_file = " ".join(src_files) + # supported extensions: .o, .so, .exe + if dst_file_ext == "o": + options.append("-c") + elif dst_file_ext == "so": + options.append("-shared") + elif dst_file_ext == "exe": + options.append("-DGENERATE_CK_STANDALONE_RUNNER") + else: + raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!") + return f"{compiler} {' '.join(options)} -o {dst_file} {src_file}"